forked from sttts/slagent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompat.go
More file actions
487 lines (426 loc) · 13.2 KB
/
compat.go
File metadata and controls
487 lines (426 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
package slagent
import (
"fmt"
"io"
"strings"
"sync"
"time"
slackapi "github.com/slack-go/slack"
)
const (
maxBlockTextLen = 3000
maxDisplayLines = 6
compatThrottleMs = 1000
)
// compatTurn implements turnWriter using postMessage/update for session/user tokens.
// Thinking + tools + status share a single "activity" message (≤6 lines, updated in-place).
// Text streams in a separate message (last 6 lines while streaming, full text on finish).
// No messages are ever deleted.
type compatTurn struct {
api *slackapi.Client
channel string
threadTS string
blockID string // slagent block_id for message tagging
emoji string // identity emoji prefix for text messages
thinkingEmoji string // Slack shortcode for thinking/running indicator
slackLog io.Writer // optional Slack API logger
// Unified activity message (thinking + tools + status)
thinkBuf strings.Builder // accumulated thinking text
activities []string // discrete lines: tools, status
toolIndex map[string]int // tool ID → index in activities
activityTS string // single message timestamp
actUpdate time.Time // throttle
activityTimer *time.Timer // debounce timer for activity flush
activityDeleted bool // activity was deleted by text; don't recreate
// Text streaming
textBuf strings.Builder
textTS string
textUpdate time.Time
textTimer *time.Timer // debounce timer for text flush
question bool // replace trailing ? with ❓ on finish
qPrefix string // prepended to text on finish (e.g. "@user: ")
plainText bool // wrap text in code block instead of mrkdwn conversion
mu sync.Mutex
}
func newCompatTurn(api *slackapi.Client, channel, threadTS, blockID, emoji, thinkingEmoji string, slackLog io.Writer) *compatTurn {
return &compatTurn{
api: api,
channel: channel,
threadTS: threadTS,
blockID: blockID,
emoji: emoji,
thinkingEmoji: thinkingEmoji,
slackLog: slackLog,
toolIndex: make(map[string]int),
}
}
// logSlack writes a Slack API action to the log writer. Must be called with lock held.
func (c *compatTurn) logSlack(action, content string) {
if c.slackLog == nil {
return
}
fmt.Fprintf(c.slackLog, "[slack] %s: %s\n", action, content)
}
// textMsgOpts returns message options for a text message with emoji prefix.
// Converts markdown to Slack mrkdwn format. Uses a section block with the given block_id.
// The block_id should include the appropriate suffix (~, ~act, or none).
func textMsgOpts(display, blockID, emoji string, plainText bool) []slackapi.MsgOption {
var converted string
if plainText {
// Plan mode: wrap in code block, no mrkdwn conversion
converted = emoji + " 📋\n```\n" + display + "\n```"
} else {
body := MarkdownToMrkdwn(display)
// Blockquote every line so bot messages stand out among human messages
lines := strings.Split(body, "\n")
lines[0] = "> " + emoji + " " + lines[0]
for i := 1; i < len(lines); i++ {
lines[i] = "> " + lines[i]
}
converted = strings.Join(lines, "\n")
}
section := slackapi.NewSectionBlock(
slackapi.NewTextBlockObject("mrkdwn", converted, false, false),
nil, nil,
)
section.BlockID = blockID
return []slackapi.MsgOption{
slackapi.MsgOptionBlocks(section),
slackapi.MsgOptionText(converted, false),
}
}
// renderActivity builds the activity message content from thinking + activity lines,
// keeping at most maxDisplayLines. Must be called with lock held.
func (c *compatTurn) renderActivity() string {
var lines []string
// Thinking indicator: only shown before tools appear.
// Once tools are active they carry their own :claude: spinner.
if c.thinkBuf.Len() > 0 && len(c.activities) == 0 {
lines = append(lines, c.emoji+c.thinkingEmoji)
thinkText := c.thinkBuf.String()
if len(thinkText) > 500 {
thinkText = "…" + thinkText[len(thinkText)-499:]
}
for _, l := range strings.Split(thinkText, "\n") {
lines = append(lines, " "+l)
}
}
// Activity lines (tools, status).
// Only one :claude: spinner visible at a time (the last running tool),
// unless in question mode where all spinners are shown.
if c.question {
lines = append(lines, c.activities...)
} else {
// Find the last line with a running spinner
lastSpinner := -1
for i := len(c.activities) - 1; i >= 0; i-- {
if strings.HasPrefix(c.activities[i], c.thinkingEmoji+" ") {
lastSpinner = i
break
}
}
for i, line := range c.activities {
// Demote earlier running spinners to "⋯"
if i != lastSpinner && strings.HasPrefix(line, c.thinkingEmoji+" ") {
lines = append(lines, "⋯"+line[len(c.thinkingEmoji):])
} else {
lines = append(lines, line)
}
}
}
// Keep last maxDisplayLines
if len(lines) > maxDisplayLines {
lines = lines[len(lines)-maxDisplayLines:]
}
return strings.Join(lines, "\n")
}
// flushActivity posts or updates the unified activity message. Must be called with lock held.
func (c *compatTurn) flushActivity() {
// Throttle to 1/sec
if c.activityTS != "" && time.Since(c.actUpdate) < time.Duration(compatThrottleMs)*time.Millisecond {
c.scheduleActivityFlush()
return
}
c.stopActivityTimer()
c.postActivity()
}
// postActivity posts or updates the activity message. Must be called with lock held.
func (c *compatTurn) postActivity() {
if c.activityDeleted {
return
}
display := c.renderActivity()
if display == "" {
return
}
// Activity messages use ~act suffix — always skipped by all pollers
actBlockID := c.blockID + "~act"
ctx := slackapi.NewContextBlock(actBlockID,
slackapi.NewTextBlockObject("mrkdwn", display, false, false),
)
if c.activityTS == "" {
c.logSlack("postMessage(activity)", display)
_, ts, err := c.api.PostMessage(
c.channel,
slackapi.MsgOptionBlocks(ctx),
slackapi.MsgOptionText("activity", false),
slackapi.MsgOptionTS(c.threadTS),
)
if err == nil {
c.activityTS = ts
}
} else {
c.logSlack("updateMessage(activity)", display)
c.api.UpdateMessage(
c.channel,
c.activityTS,
slackapi.MsgOptionBlocks(ctx),
slackapi.MsgOptionText("activity", false),
)
}
c.actUpdate = time.Now()
}
// scheduleActivityFlush starts a debounce timer for activity. Must be called with lock held.
func (c *compatTurn) scheduleActivityFlush() {
if c.activityTimer != nil {
return
}
c.activityTimer = time.AfterFunc(time.Duration(compatThrottleMs)*time.Millisecond, func() {
c.mu.Lock()
defer c.mu.Unlock()
c.activityTimer = nil
c.postActivity()
})
}
// stopActivityTimer cancels any pending activity debounce timer. Must be called with lock held.
func (c *compatTurn) stopActivityTimer() {
if c.activityTimer != nil {
c.activityTimer.Stop()
c.activityTimer = nil
}
}
// forceFlushText updates the text message with current buffer content,
// bypassing throttle. Must be called with lock held.
func (c *compatTurn) forceFlushText() {
c.stopTimer()
if c.textBuf.Len() == 0 {
return
}
c.postText()
}
// deleteActivity deletes the activity message and resets activity state.
// Acquires the lock.
func (c *compatTurn) deleteActivity() {
c.mu.Lock()
defer c.mu.Unlock()
c.deleteActivityLocked()
}
// deleteActivityLocked deletes the activity message. Must be called with lock held.
func (c *compatTurn) deleteActivityLocked() {
c.stopActivityTimer()
if c.activityTS == "" {
return
}
c.logSlack("deleteMessage(activity)", c.activityTS)
c.api.DeleteMessage(c.channel, c.activityTS)
c.activityTS = ""
c.activityDeleted = true
c.thinkBuf.Reset()
c.activities = nil
c.toolIndex = make(map[string]int)
}
func (c *compatTurn) writeThinking(text string) {
c.mu.Lock()
defer c.mu.Unlock()
// Flush any pending text before activity
c.forceFlushText()
c.activityDeleted = false // new thinking starts fresh activity
c.thinkBuf.WriteString(text)
c.flushActivity()
}
func (c *compatTurn) writeTool(id, name, status, detail string) {
c.mu.Lock()
defer c.mu.Unlock()
// Flush any pending text before activity
c.forceFlushText()
// New running tool (not a done/error update) starts fresh activity
if status == ToolRunning {
if _, exists := c.toolIndex[id]; !exists {
c.activityDeleted = false
}
}
summary := name
if detail != "" {
summary += ": " + detail
}
// :claude: while running, ✅ when done, ❌ on error
var icon string
switch status {
case ToolDone:
icon = "✓"
case ToolError:
icon = "❌"
default:
icon = c.thinkingEmoji
}
line := fmt.Sprintf("%s %s", icon, summary)
// Update existing line or append new one
if idx, ok := c.toolIndex[id]; ok {
c.activities[idx] = line
} else {
c.toolIndex[id] = len(c.activities)
c.activities = append(c.activities, line)
}
c.flushActivity()
}
func (c *compatTurn) markQuestion(prefix string) {
c.mu.Lock()
defer c.mu.Unlock()
c.question = true
c.qPrefix = prefix
}
func (c *compatTurn) setPlainText(on bool) {
c.mu.Lock()
defer c.mu.Unlock()
c.plainText = on
}
func (c *compatTurn) writeStatus(text string) {
c.mu.Lock()
defer c.mu.Unlock()
if text == "" {
return
}
c.activities = append(c.activities, fmt.Sprintf("⏳ %s", text))
c.flushActivity()
}
func (c *compatTurn) writeText(text string) {
c.mu.Lock()
defer c.mu.Unlock()
// Strip leading newlines from the first text content
if c.textBuf.Len() == 0 {
text = strings.TrimLeft(text, "\n")
if text == "" {
return
}
// Delete activity and post text immediately (same lock scope, minimal gap)
c.deleteActivityLocked()
}
c.textBuf.WriteString(text)
// Throttle updates to 1/sec
if c.textTS != "" && time.Since(c.textUpdate) < time.Duration(compatThrottleMs)*time.Millisecond {
// Schedule a debounce flush: if no further event within 1s, flush
c.scheduleFlush()
return
}
c.stopTimer()
c.postText()
}
// postText posts or updates the text message with current buffer content.
// Uses streaming block_id suffix (~) to indicate the message is not yet final.
// Must be called with lock held.
func (c *compatTurn) postText() {
full := c.textBuf.String()
// While streaming, use ~ suffix so pollers know this message isn't final
streamBlockID := c.blockID + "~"
opts := textMsgOpts(full, streamBlockID, c.emoji, c.plainText)
converted := c.emoji + " " + MarkdownToMrkdwn(full)
if c.textTS == "" {
c.logSlack("postMessage(text)", converted)
allOpts := append(opts, slackapi.MsgOptionTS(c.threadTS))
_, ts, err := c.api.PostMessage(c.channel, allOpts...)
if err == nil {
c.textTS = ts
}
} else {
c.logSlack("updateMessage(text)", converted)
c.api.UpdateMessage(c.channel, c.textTS, opts...)
}
c.textUpdate = time.Now()
}
// scheduleFlush starts a debounce timer that flushes text after 1s.
// Must be called with lock held.
func (c *compatTurn) scheduleFlush() {
if c.textTimer != nil {
return // already scheduled
}
c.textTimer = time.AfterFunc(time.Duration(compatThrottleMs)*time.Millisecond, func() {
c.mu.Lock()
defer c.mu.Unlock()
c.textTimer = nil
c.postText()
})
}
// stopTimer cancels any pending debounce timer. Must be called with lock held.
func (c *compatTurn) stopTimer() {
if c.textTimer != nil {
c.textTimer.Stop()
c.textTimer = nil
}
}
// finish freezes the activity message and updates the text message to the full final response.
func (c *compatTurn) finish() error {
c.mu.Lock()
defer c.mu.Unlock()
// Cancel debounce timers
c.stopTimer()
c.stopActivityTimer()
// If no text and no real activity, delete the activity message (e.g. early thinking indicator)
finalText := strings.TrimLeft(c.textBuf.String(), "\n")
if finalText == "" && len(c.activities) == 0 && strings.TrimSpace(c.thinkBuf.String()) == "" {
c.deleteActivityLocked()
return nil
}
// Final flush of activity (frozen as-is, no deletion)
c.postActivity()
if c.activityTS != "" {
display := c.renderActivity()
actBlockID := c.blockID + "~act"
ctx := slackapi.NewContextBlock(actBlockID,
slackapi.NewTextBlockObject("mrkdwn", display, false, false),
)
c.api.UpdateMessage(
c.channel,
c.activityTS,
slackapi.MsgOptionBlocks(ctx),
slackapi.MsgOptionText("activity", false),
)
}
// Update text message to full final response
if finalText == "" {
return nil
}
// Question turns: prepend @mention, replace trailing ? with ❓
if c.question {
if c.qPrefix != "" {
finalText = c.qPrefix + finalText
}
finalText = strings.TrimRight(finalText, "\n ")
if strings.HasSuffix(finalText, "?") {
finalText = finalText[:len(finalText)-1] + " ❓"
} else {
finalText += " ❓"
}
}
// Update existing text message with full content — use final block_id (no suffix)
opts := textMsgOpts(finalText, c.blockID, c.emoji, c.plainText)
finalConverted := c.emoji + " " + MarkdownToMrkdwn(finalText)
// If activity is below the text message, delete old text and repost below activity
// so the final order is: activity (tools), then text.
if c.textTS != "" && c.activityTS != "" && c.textTS < c.activityTS {
c.logSlack("deleteMessage(text/repost)", c.textTS)
c.api.DeleteMessage(c.channel, c.textTS)
c.textTS = ""
}
if c.textTS != "" {
c.logSlack("updateMessage(text/final)", finalConverted)
c.api.UpdateMessage(c.channel, c.textTS, opts...)
} else {
c.logSlack("postMessage(text/final)", finalConverted)
allOpts := append(opts, slackapi.MsgOptionTS(c.threadTS))
_, _, err := c.api.PostMessage(c.channel, allOpts...)
if err != nil {
return err
}
}
return nil
}