Files
slacker-bot/slackerbot/internal/bot/stream.go
T
2026-11-01 13:01:54 -05:00

151 lines
2.9 KiB
Go

package bot
import (
"context"
"log"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/slack-go/slack"
"slackerbot/internal/acp"
)
const (
slackMsgLimit = 3500
flushEvery = 1500 * time.Millisecond // under Slack's edit rate limit
)
type Streamer struct {
api *slack.Client
channel string
thread string
mu sync.Mutex
full strings.Builder
dirty bool
// Only the flush loop touches these.
ts string
offset int
quit chan struct{}
done chan struct{}
}
func NewStreamer(api *slack.Client, channel, thread, placeholderTS string) *Streamer {
s := &Streamer{api: api, channel: channel, thread: thread, ts: placeholderTS,
quit: make(chan struct{}), done: make(chan struct{})}
go s.loop()
return s
}
func (s *Streamer) Update(u acp.Update) {
s.mu.Lock()
defer s.mu.Unlock()
switch u.Kind {
case "agent_message_chunk":
s.full.WriteString(u.Text)
case "tool_call":
if u.Title == "" {
return
}
if t := s.full.String(); t != "" && !strings.HasSuffix(t, "\n") {
s.full.WriteString("\n")
}
s.full.WriteString("> :wrench: " + u.Title + "\n")
default:
return
}
s.dirty = true
}
func (s *Streamer) Finish(stopReason string, err error) {
close(s.quit)
<-s.done
s.mu.Lock()
note := ""
switch {
case err != nil:
note = ":warning: " + err.Error()
case stopReason == "max_tokens", stopReason == "max_turn_requests":
note = "_(stopped: hit the agent's length limit. Reply to keep going.)_"
case stopReason == "refusal":
note = "_(the agent declined this one)_"
case stopReason == "cancelled":
note = "_(cancelled)_"
}
if note != "" {
if s.full.Len() > 0 {
s.full.WriteString("\n\n")
}
s.full.WriteString(note)
}
if s.full.Len() == 0 {
s.full.WriteString("_(no reply)_")
}
s.dirty = true
s.mu.Unlock()
s.flush()
}
func (s *Streamer) loop() {
defer close(s.done)
t := time.NewTicker(flushEvery)
defer t.Stop()
for {
select {
case <-s.quit:
return
case <-t.C:
s.flush()
}
}
}
func (s *Streamer) flush() {
s.mu.Lock()
if !s.dirty {
s.mu.Unlock()
return
}
s.dirty = false
text := s.full.String()[s.offset:]
s.mu.Unlock()
ctx := context.Background()
for len(text) > slackMsgLimit {
cut := strings.LastIndex(text[:slackMsgLimit], "\n")
if cut < slackMsgLimit/2 {
cut = slackMsgLimit
for cut > 0 && !utf8.RuneStart(text[cut]) {
cut--
}
}
s.edit(ctx, text[:cut])
_, ts, err := s.api.PostMessageContext(ctx, s.channel,
slack.MsgOptionText("…", false), slack.MsgOptionTS(s.thread))
if err != nil {
log.Printf("slack post: %v", err)
return
}
s.ts = ts
s.offset += cut
text = text[cut:]
}
s.edit(ctx, text)
}
func (s *Streamer) edit(ctx context.Context, text string) {
if strings.TrimSpace(text) == "" {
text = "…"
}
if _, _, _, err := s.api.UpdateMessageContext(ctx, s.channel, s.ts, slack.MsgOptionText(text, false)); err != nil {
log.Printf("slack update: %v", err)
}
}