// Package chatstream extracts display text, never arbitrary tool arguments. package chatstream import ( "encoding/json" "strconv" "strings" "unicode/utf8" ) const Limit = 32 << 10 type Stream struct { text, args, reply string toolIndex int post bool } func (s *Stream) Add(raw []byte) { var v struct { Event struct { Type string Index int Content struct{ Type, Name string } `json:"content_block"` Delta struct { Type, Text string JSON string `json:"partial_json"` } } } if json.Unmarshal(raw, &v) != nil { return } e := v.Event switch e.Type { case "content_block_start": s.post = e.Content.Type == "tool_use" && (e.Content.Name == "mcp__equipo__post_message" || e.Content.Name == "post_message") if s.post { s.args = "" s.toolIndex = e.Index } case "content_block_delta": if e.Delta.Type == "text_delta" && len(s.text)+len(e.Delta.Text) <= Limit { s.text += e.Delta.Text } if e.Delta.Type == "input_json_delta" && s.post && e.Index == s.toolIndex && len(s.args)+len(e.Delta.JSON) <= Limit*6 { s.args += e.Delta.JSON if body, ok := partialBody(s.args); ok && len(body) <= Limit { s.reply = body } } } } func (s *Stream) Text() string { if s.reply != "" { return s.reply } return s.text } func partialBody(raw string) (string, bool) { // Tokenize complete preceding fields; only the top-level body string is visible. d := json.NewDecoder(strings.NewReader(raw)) token, err := d.Token() if err != nil || token != json.Delim('{') { return "", false } for d.More() { k, err := d.Token() if err != nil { return "", false } if k != "body" { var discard json.RawMessage if d.Decode(&discard) != nil { return "", false } continue } rest := strings.TrimSpace(raw[d.InputOffset():]) rest = strings.TrimSpace(strings.TrimPrefix(rest, ":")) if !strings.HasPrefix(rest, `"`) { return "", false } // Decode only complete characters, leaving a split escape for the next chunk. var out strings.Builder for i := 1; i < len(rest); { if rest[i] == '"' { return out.String(), true } if rest[i] == '\\' { n := 2 if i+1 >= len(rest) { break } if rest[i+1] == 'u' { n = 6 } if i+n > len(rest) { break } part := rest[i : i+n] if n == 6 { code, _ := strconv.ParseUint(part[2:], 16, 16) if code >= 0xd800 && code <= 0xdbff { if i+12 > len(rest) { break } part = rest[i : i+12] n = 12 } } var decoded string if json.Unmarshal([]byte(`"`+part+`"`), &decoded) != nil { return "", false } out.WriteString(decoded) i += n } else { r, n := utf8.DecodeRuneInString(rest[i:]) if r == utf8.RuneError && n == 1 { break } out.WriteRune(r) i += n } } return out.String(), true } return "", false }