-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathnative.go
More file actions
294 lines (252 loc) · 6.7 KB
/
native.go
File metadata and controls
294 lines (252 loc) · 6.7 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
package slagent
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"sync"
)
const defaultSlackAPIURL = "https://slack.com/api/"
// nativeTurn implements turnWriter using Slack's native streaming API
// (chat.startStream / chat.appendStream / chat.stopStream).
// Requires a bot token (xoxb-*).
type nativeTurn struct {
token string
apiURL string // base URL for API calls (default: https://slack.com/api/)
channel string
threadTS string
convert func(string) string
bufSize int
streamID string // set after startStream
fullText strings.Builder // accumulated raw text (pre-conversion)
flushed int // bytes of fullText already flushed
thinkBuf strings.Builder // accumulated thinking text
started bool
question bool // replace trailing ? with ❓ on finish
qPrefix string // prepended to text on finish
mu sync.Mutex
}
func newNativeTurn(token, apiURL, channel, threadTS string, convert func(string) string, bufSize int) *nativeTurn {
if apiURL == "" {
apiURL = defaultSlackAPIURL
}
return &nativeTurn{
token: token,
apiURL: apiURL,
channel: channel,
threadTS: threadTS,
convert: convert,
bufSize: bufSize,
}
}
// startStream lazily starts the stream on first content.
func (n *nativeTurn) startStream() error {
if n.started {
return nil
}
resp, err := n.callAPI("chat.startStream", map[string]any{
"channel": n.channel,
"thread_ts": n.threadTS,
"task_display_mode": "timeline",
})
if err != nil {
return fmt.Errorf("chat.startStream: %w", err)
}
streamID, ok := resp["stream_id"].(string)
if !ok {
return fmt.Errorf("chat.startStream: missing stream_id in response")
}
n.streamID = streamID
n.started = true
return nil
}
func (n *nativeTurn) writeText(text string) {
n.mu.Lock()
defer n.mu.Unlock()
n.fullText.WriteString(text)
// Flush when unflushed portion exceeds threshold
if n.fullText.Len()-n.flushed >= n.bufSize {
n.flushText()
}
}
// flushText converts and sends the unflushed portion of fullText.
// Converts the entire accumulated text, then sends only the new portion.
// Must be called with lock held.
func (n *nativeTurn) flushText() {
if n.fullText.Len() == n.flushed {
return
}
if err := n.startStream(); err != nil {
return
}
// Convert full text to get correct cross-boundary markdown
converted := n.convert(n.fullText.String())
// Send only the portion after what we already flushed
// On first flush, send everything; on subsequent, approximate the new chunk
// by converting old prefix and taking the diff
var chunk string
if n.flushed == 0 {
chunk = converted
} else {
oldConverted := n.convert(n.fullText.String()[:n.flushed])
if strings.HasPrefix(converted, oldConverted) {
chunk = converted[len(oldConverted):]
} else {
// Conversion changed earlier text (rare); send full reconvert
chunk = converted
}
}
if chunk != "" {
n.callAPI("chat.appendStream", map[string]any{
"stream_id": n.streamID,
"channel": n.channel,
"chunks": []map[string]any{{
"type": "markdown_text",
"value": chunk,
}},
})
}
n.flushed = n.fullText.Len()
}
func (n *nativeTurn) writeThinking(text string) {
n.mu.Lock()
defer n.mu.Unlock()
n.thinkBuf.WriteString(text)
if err := n.startStream(); err != nil {
return
}
// Show last 5 lines of accumulated thinking
display := n.thinkBuf.String()
lines := strings.Split(display, "\n")
if len(lines) > 5 {
lines = append([]string{"…"}, lines[len(lines)-5:]...)
}
n.callAPI("chat.appendStream", map[string]any{
"stream_id": n.streamID,
"channel": n.channel,
"chunks": []map[string]any{{
"type": "task_update",
"value": map[string]any{
"id": "thinking",
"status": "in_progress",
"details": strings.Join(lines, "\n"),
},
}},
})
}
func (n *nativeTurn) writeTool(id, name, status, detail string) {
n.mu.Lock()
defer n.mu.Unlock()
if err := n.startStream(); err != nil {
return
}
taskStatus := "in_progress"
switch status {
case ToolDone:
taskStatus = "completed"
case ToolError:
taskStatus = "failed"
}
details := name
if detail != "" {
details += ": " + detail
}
n.callAPI("chat.appendStream", map[string]any{
"stream_id": n.streamID,
"channel": n.channel,
"chunks": []map[string]any{{
"type": "task_update",
"value": map[string]any{
"id": id,
"status": taskStatus,
"details": details,
},
}},
})
}
func (n *nativeTurn) deleteActivity() {
// Native streaming doesn't have a separate activity message to delete.
}
func (n *nativeTurn) markQuestion(prefix string) {
n.mu.Lock()
defer n.mu.Unlock()
n.question = true
n.qPrefix = prefix
}
func (n *nativeTurn) setPlainText(on bool) {
// Native streaming doesn't need plain text mode.
}
func (n *nativeTurn) writeStatus(text string) {
n.mu.Lock()
defer n.mu.Unlock()
if err := n.startStream(); err != nil {
return
}
n.callAPI("chat.appendStream", map[string]any{
"stream_id": n.streamID,
"channel": n.channel,
"chunks": []map[string]any{{
"type": "task_update",
"value": map[string]any{
"id": "status",
"status": "in_progress",
"details": text,
},
}},
})
}
func (n *nativeTurn) finish() error {
n.mu.Lock()
defer n.mu.Unlock()
// Question turns: prepend @mention, replace trailing ? with ❓
if n.question && n.fullText.Len() > 0 {
s := n.qPrefix + strings.TrimRight(n.fullText.String(), "\n ")
n.fullText.Reset()
if strings.HasSuffix(s, "?") {
n.fullText.WriteString(s[:len(s)-1] + " ❓")
} else {
n.fullText.WriteString(s + " ❓")
}
}
// Flush remaining text (may lazily start the stream)
n.flushText()
if !n.started {
return nil
}
_, err := n.callAPI("chat.stopStream", map[string]any{
"stream_id": n.streamID,
"channel": n.channel,
})
return err
}
// callAPI calls a Slack API method with JSON body.
func (n *nativeTurn) callAPI(method string, params map[string]any) (map[string]any, error) {
body, err := json.Marshal(params)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", n.apiURL+method, strings.NewReader(string(body)))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("Authorization", "Bearer "+n.token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var result map[string]any
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, err
}
if ok, _ := result["ok"].(bool); !ok {
errMsg, _ := result["error"].(string)
return result, fmt.Errorf("%s: %s", method, errMsg)
}
return result, nil
}
// isNativeToken returns true if the token supports native streaming.
func isNativeToken(token string) bool {
return strings.HasPrefix(token, "xoxb-")
}