Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(pi): strip leaked tool markup safely (#2956)

Dmitry5bc77f2953d1
diff --git a/server/pkg/agent/pi.go b/server/pkg/agent/pi.go
index 26e441c3ac..03b5390814 100644
--- a/server/pkg/agent/pi.go
+++ b/server/pkg/agent/pi.go
@@ -9,6 +9,7 @@ import (
"os"
"os/exec"
"path/filepath"
+ "regexp"
"strings"
"time"
)
@@ -20,6 +21,158 @@ type piBackend struct {
cfg Config
}
+var (
+ piControlTokenRE = regexp.MustCompile(`<\|[A-Za-z0-9_-]+>[A-Za-z0-9_-]*|<[A-Za-z0-9_-]+\|>`)
+)
+
+func stripPiToolCallMarkup(s string) string {
+ s = stripPiStructuredToolMarkup(s)
+ return piControlTokenRE.ReplaceAllString(s, "")
+}
+
+func drainPiTextBuffer(buf *strings.Builder, delta string) string {
+ buf.WriteString(delta)
+ emit, pending := drainPiSanitizedText(buf.String())
+ buf.Reset()
+ buf.WriteString(pending)
+ return emit
+}
+
+func flushPiTextBuffer(buf *strings.Builder) string {
+ s := buf.String()
+ buf.Reset()
+ emit, pending := drainPiSanitizedText(s)
+ emit += piControlTokenRE.ReplaceAllString(pending, "")
+ return emit
+}
+
+func drainPiSanitizedText(s string) (string, string) {
+ var out strings.Builder
+ for i := 0; i < len(s); {
+ start, prefixLen := nextPiToolMarkupPrefix(s, i)
+ if start == -1 {
+ safeLen := safePiTextEmitLen(s[i:])
+ out.WriteString(s[i : i+safeLen])
+ return piControlTokenRE.ReplaceAllString(out.String(), ""), s[i+safeLen:]
+ }
+ out.WriteString(s[i:start])
+ end, ok := scanPiToolMarkupEnd(s, start+prefixLen)
+ if !ok {
+ return piControlTokenRE.ReplaceAllString(out.String(), ""), s[start:]
+ }
+ i = end
+ }
+ return piControlTokenRE.ReplaceAllString(out.String(), ""), ""
+}
+
+func stripPiStructuredToolMarkup(s string) string {
+ var out strings.Builder
+ for i := 0; i < len(s); {
+ start, prefixLen := nextPiToolMarkupPrefix(s, i)
+ if start == -1 {
+ out.WriteString(s[i:])
+ break
+ }
+ out.WriteString(s[i:start])
+ end, ok := scanPiToolMarkupEnd(s, start+prefixLen)
+ if !ok {
+ out.WriteString(s[start:])
+ break
+ }
+ i = end
+ }
+ return out.String()
+}
+
+func safePiTextEmitLen(s string) int {
+ hold := 0
+ for _, prefix := range []string{"call:", "response:"} {
+ for n := 1; n < len(prefix) && n <= len(s); n++ {
+ if strings.HasSuffix(s, prefix[:n]) && n > hold {
+ hold = n
+ }
+ }
+ }
+ if i := strings.LastIndexByte(s, '<'); i >= 0 && looksLikePiControlTokenPrefix(s[i:]) {
+ if len(s)-i > hold {
+ hold = len(s) - i
+ }
+ }
+ return len(s) - hold
+}
+
+func looksLikePiControlTokenPrefix(s string) bool {
+ if len(s) == 0 || s[0] != '<' || len(s) > 64 {
+ return false
+ }
+ for i := 1; i < len(s); i++ {
+ b := s[i]
+ if (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || (b >= '0' && b <= '9') || b == '_' || b == '-' || b == '|' || b == '>' {
+ continue
+ }
+ return false
+ }
+ return true
+}
+
+func nextPiToolMarkupPrefix(s string, from int) (int, int) {
+ best := -1
+ bestLen := 0
+ for _, prefix := range []string{"call:", "response:"} {
+ if i := strings.Index(s[from:], prefix); i >= 0 {
+ abs := from + i
+ if best == -1 || abs < best {
+ best = abs
+ bestLen = len(prefix)
+ }
+ }
+ }
+ return best, bestLen
+}
+
+func scanPiToolMarkupEnd(s string, i int) (int, bool) {
+ nameStart := i
+ for i < len(s) && isPiToolNameByte(s[i]) {
+ i++
+ }
+ if i == nameStart || i >= len(s) || s[i] != '{' {
+ return 0, false
+ }
+
+ const quoteMarker = `<|"|>`
+ depth := 0
+ inQuote := false
+ for i < len(s) {
+ if strings.HasPrefix(s[i:], quoteMarker) {
+ inQuote = !inQuote
+ i += len(quoteMarker)
+ continue
+ }
+
+ if !inQuote {
+ switch s[i] {
+ case '{':
+ depth++
+ case '}':
+ depth--
+ if depth == 0 {
+ i++
+ if strings.HasPrefix(s[i:], "<tool_call|>") {
+ i += len("<tool_call|>")
+ }
+ return i, true
+ }
+ }
+ }
+ i++
+ }
+ return 0, false
+}
+
+func isPiToolNameByte(b byte) bool {
+ return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || (b >= '0' && b <= '9') || b == '_' || b == '-'
+}
+
func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions) (*Session, error) {
execPath := b.cfg.ExecutablePath
if execPath == "" {
@@ -100,6 +253,7 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
// Pi message_update events can be large (they embed the full message
// partial on each delta), so give the scanner generous headroom.
scanner.Buffer(make([]byte, 0, 1024*1024), 32*1024*1024)
+ var textBuffer strings.Builder
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
@@ -121,7 +275,7 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
}
switch evt.AssistantMessageEvent.Type {
case "text_delta":
- if d := evt.AssistantMessageEvent.Delta; d != "" {
+ if d := drainPiTextBuffer(&textBuffer, evt.AssistantMessageEvent.Delta); d != "" {
output.WriteString(d)
trySend(msgCh, Message{Type: MessageText, Content: d})
}
@@ -186,6 +340,10 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
}
}
}
+ if d := flushPiTextBuffer(&textBuffer); d != "" {
+ output.WriteString(d)
+ trySend(msgCh, Message{Type: MessageText, Content: d})
+ }
waitErr := cmd.Wait()
duration := time.Since(startTime)
@@ -249,9 +407,9 @@ type piAssistantMessageEvent struct {
}
type piMessage struct {
- Role string `json:"role,omitempty"`
- Model string `json:"model,omitempty"`
- Usage *piUsage `json:"usage,omitempty"`
+ Role string `json:"role,omitempty"`
+ Model string `json:"model,omitempty"`
+ Usage *piUsage `json:"usage,omitempty"`
}
type piUsage struct {
diff --git a/server/pkg/agent/pi_test.go b/server/pkg/agent/pi_test.go
index c524fb7d75..694fec9a17 100644
--- a/server/pkg/agent/pi_test.go
+++ b/server/pkg/agent/pi_test.go
@@ -53,3 +53,66 @@ func TestBuildPiArgsCustomArgsAppended(t *testing.T) {
t.Errorf("custom --tools should pass through via custom_args, got: %v", args)
}
}
+
+func TestStripPiToolCallMarkup(t *testing.T) {
+ tests := map[string]string{
+ `before call:bash{command:<|"|>cd repo/path && ls -F<|"|>}<tool_call|> after`: "before after",
+ `before call:read{path:<|"|>repo/path/roles/example/verify.yml<|"|>} after`: "before after",
+ `before response:bash{command:<|"|>multica issue comment list issue-id --all --output json<|"|>} after`: "before after",
+ `before call:bash{command:<|"|>printf '{"key":"value"}'<|"|>} after`: "before after",
+ `before <|turn>model after`: "before after",
+ }
+ for in, want := range tests {
+ got := stripPiToolCallMarkup(in)
+ if got != want {
+ t.Fatalf("unexpected stripped text: %q, want %q", got, want)
+ }
+ }
+}
+
+func TestDrainPiTextBufferSplitToolCall(t *testing.T) {
+ chunks := []string{
+ "before ca",
+ `ll:bash{command:<|"|>ls -R repo/path`,
+ `/roles/example<|"|>}`,
+ " after",
+ }
+ var buf strings.Builder
+ var got strings.Builder
+ for _, chunk := range chunks {
+ got.WriteString(drainPiTextBuffer(&buf, chunk))
+ }
+ got.WriteString(flushPiTextBuffer(&buf))
+ if got.String() != "before after" {
+ t.Fatalf("unexpected streamed text: %q", got.String())
+ }
+}
+
+func TestDrainPiTextBufferSplitControlToken(t *testing.T) {
+ chunks := []string{"before <|tu", "rn>model after"}
+ var buf strings.Builder
+ var got strings.Builder
+ for _, chunk := range chunks {
+ got.WriteString(drainPiTextBuffer(&buf, chunk))
+ }
+ got.WriteString(flushPiTextBuffer(&buf))
+ if got.String() != "before after" {
+ t.Fatalf("unexpected streamed text: %q", got.String())
+ }
+}
+
+func TestFlushPiTextBufferKeepsUnmatchedToolPrefixes(t *testing.T) {
+ tests := []string{
+ "plain response: see below",
+ "plain call: see below",
+ `plain call:bash{command:<|"|>unterminated`,
+ }
+ for _, want := range tests {
+ var buf strings.Builder
+ got := drainPiTextBuffer(&buf, want)
+ got += flushPiTextBuffer(&buf)
+ if got != want {
+ t.Fatalf("unexpected flushed text: %q, want %q", got, want)
+ }
+ }
+}