package chatstream import ( "amadan.net/oficina/equipo/internal/runnerproto" "context" "encoding/json" "time" "unicode/utf8" ) type Forwarder struct { Send func(context.Context, string, int64) error stream Stream at time.Time sequence int64 sent string } func (f *Forwarder) Add(ctx context.Context, raw []byte) error { f.stream.Add(raw) text := f.stream.Text() if text == "" || text == f.sent || time.Since(f.at) < 200*time.Millisecond || f.sequence >= runnerproto.MaxCoordinatorTextEvents { return nil } f.sequence++ if err := f.Send(ctx, text, f.sequence); err != nil { return err } f.sent, f.at = text, time.Now() return nil } func TextEvent(e runnerproto.Event, text string, sequence int64) runnerproto.Event { e.Kind = "coordinator.text" e.Epoch = "coordinator.text.v1" e.Sequence = &sequence // Escaping can make a JSON string larger than its UTF-8 source. for { e.Payload, _ = json.Marshal(runnerproto.CoordinatorText{Text: text}) if len(e.Payload) <= runnerproto.MaxEventBytes { break } text = text[:len(text)/2] for !utf8.ValidString(text) { text = text[:len(text)-1] } } e.ID = runnerproto.EventHash([]any{e.AssignmentID, e.Kind, e.SessionID, sequence}) e.RequestID = e.ID return e }