diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index e5d1e70e1..7438dc745 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -568,6 +568,32 @@ calls does. Starting such a request anew instead would tell the whole conversation to a new run, a prefix the cache has never seen (#1716, #1717), for every message sent mid-turn. +## Tool calls written as text + +A run told the conversation as text (`renderClaudePrompt`, and +`renderClaudeTurn` with the client's own calls in the turn) is shown each +past call as a `[tool call id=… args=…]` line and each result as +`[tool result id=…]`. The model can copy that form and write its calls as +text: Claude Code has no call to make, the turn ends with end_turn, and the +client shows the lines as the reply's words while nothing runs (Zhenzhen on +Discord: Claude Desktop on Fable 5.1 got +`[tool call mcp__magpie__Bash id=toolu_0Validate bash args={…}]`). + +- Such a prompt ends with a note (`pastCallsNote`) that the lines record + earlier calls and that writing one calls nothing. A prompt with no call in + it is told as before. +- `readOutput` holds back a reply's words from the first line that opens + with `[tool call ` (`textCalls`); words before it, and lines that only + start like it, go on as they come. A reply that ends there with end_turn + and calls none of the client's tools isn't ended: once its turn's + `result` is in, the run is told `textCallsAsk` as a user message, and the + reply goes on in the next message (one `message_start`, as after Claude + Code's own call), so the client gets the real `tool_use` and its results + go on in the run. It is asked once per reply: written as text again, the + words reach the client as written. A run with no input to write to, or a + reply that called the client's tools too (the text is left out), is + not asked. + ## The account's allowance on the reply (#1257) Claude Code tells a run's account allowance in its stream-json @@ -602,7 +628,7 @@ go test -tags nogui ./internal/gateway/ -run '^TestClaudeToolNamesComeBackAsDecl go test -tags nogui ./internal/gateway/ -run 'TestClaudeRunsHeldToTheRoom|TestClaudeRoom|TestClaudeOneOffsTakeRoom|TestClaudeMemRuns|TestClaudeRunsMost|TestClaudeNoRoom' -count=1 go test -tags nogui ./internal/cli/ -run '^TestClaudeCodeRunsSetsTheUsersOwn$' -count=1 go test -tags nogui ./internal/settings/ -run '^TestClaudeRunsMostIsMachineLocal$' -count=1 -go test -tags nogui ./internal/gateway/ -run 'ClaudeSubscriptionRunsTheDownloaded|ClaudeSubscriptionWithoutClaudeCode|ClaudeRewritten|LostMedia|ImagesTakenOut|RunLetGoWhenTheClientRewrote|ClaudeSessionTempFiles|ClaudeLetGo|ClaudeSessionFiles|ClaudeOldSessions|ClaudeSubscriptionReplySaysTheAllowance|ClaudeAllowanceHeaders|ClaudeForksAnsweringTheLeadsCalls|ClaudeTurnGivenUpOn|ClaudeToolResultsGivenUpOn|ClaudePromptMarksEarlierTurns|ClaudeHistoryCachedAcrossNewRuns|ClaudeUnloadableSession|ClaudeEndedRunSaysWhy|ClaudeIdle|ClaudeSideQuestion|ClaudeNoRunSaysWhy|ClaudeToolResultsNoRunSaysWhy|ClaudePromptToldUserText|ClaudePromptKeepsInstructions|ClaudeToolResultsGoOnWithTheUsersWords|ClaudeToolResultsKeepInstructions|ToolResultKeepsUserTextSentMidTurn' -count=1 +go test -tags nogui ./internal/gateway/ -run 'ClaudeSubscriptionRunsTheDownloaded|ClaudeSubscriptionWithoutClaudeCode|ClaudeRewritten|LostMedia|ImagesTakenOut|RunLetGoWhenTheClientRewrote|ClaudeSessionTempFiles|ClaudeLetGo|ClaudeSessionFiles|ClaudeOldSessions|ClaudeSubscriptionReplySaysTheAllowance|ClaudeAllowanceHeaders|ClaudeForksAnsweringTheLeadsCalls|ClaudeTurnGivenUpOn|ClaudeToolResultsGivenUpOn|ClaudePromptMarksEarlierTurns|ClaudeHistoryCachedAcrossNewRuns|ClaudeUnloadableSession|ClaudeEndedRunSaysWhy|ClaudeIdle|ClaudeSideQuestion|ClaudeNoRunSaysWhy|ClaudeToolResultsNoRunSaysWhy|ClaudePromptToldUserText|ClaudePromptKeepsInstructions|ClaudeToolResultsGoOnWithTheUsersWords|ClaudeToolResultsKeepInstructions|ToolResultKeepsUserTextSentMidTurn|ClaudeTextToolCalls|ClaudeTextCallsHoldsOnlyTheLine|ClaudePromptSaysPastCallsAreARecord' -count=1 ``` `claude_rewritten_test.go` has a case for each relaxation and one for each diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 4a6dedde2..fe00ba661 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -2109,13 +2109,44 @@ func (r *subscriptionRun) readOutput(rd io.Reader) { // unstreamedQuiet, as when Claude Code goes on to call the client's // tools and waits on them unstreamed, unstreamedStop, blocks := "", "", 0 + // The reply's tool calls written as text (textCalls), held back from + // the client. A reply that ends with them and calls none of the + // client's tools goes on: once its turn's result is in, the run is + // told to make them (textCallsAsk), and the reply goes on in its next + // message, as after Claude Code's own call. Only once a reply: told + // again, the words go to the client as written. + var calls textCalls + retell := false // the run is told to make its calls once this turn's result is in + retold := false // this reply was told so var pmu sync.Mutex // held for each line, and by quiet's settle var quiet *time.Timer + text := func(s string) { + if s != "" && !r.schema { + shown = true + r.emit(Event{Kind: KText, Text: s}) + } + } + said := func(s string) { text(calls.push(s)) } // what each message's end does, once its stop is known end := func(why string) { if goesOn := why != "" && r.schema && !theirs || why == "tool_use" && len(own) > 0 && !theirs; goesOn { inside = true // the answer is the next message's, or the result's } else if why != "" { + held, seen := calls.end() + switch { + case seen && !theirs && why == "end_turn" && !retold && r.stdin != nil: + retell, retold, inside = true, true, true + log.Printf("claude: a reply wrote its tool calls as text (%d bytes held back); its run is told to make them", len(held)) + return + case seen && theirs: + // it called the client's tools too: those are the reply's + log.Printf("claude: a reply wrote tool calls as text beside real ones; the text (%d bytes) is left out", len(held)) + case seen: + log.Printf("claude: a reply wrote its tool calls as text again; the client is told the words as written") + text(held) + default: + text(held) + } r.emit(Event{Kind: KStop, Stop: stopFromAnthropic(why)}) } } @@ -2158,12 +2189,6 @@ func (r *subscriptionRun) readOutput(rd io.Reader) { r.mu.Unlock() return name, true } - text := func(s string) { - if s != "" && !r.schema { - shown = true - r.emit(Event{Kind: KText, Text: s}) - } - } // begin starts a message: the reply's first, or one it goes on in, // after Claude Code's own call or an attempt cut short begin := func(id, model string, u cliUsage) { @@ -2175,6 +2200,7 @@ func (r *subscriptionRun) readOutput(rd io.Reader) { return } before, this = Usage{}, Usage{} + calls, retold = textCalls{}, false r.mu.Lock() r.asked = nil r.mu.Unlock() @@ -2305,7 +2331,22 @@ func (r *subscriptionRun) readOutput(rd io.Reader) { } return } + if envelope.Type == "result" && retell && !envelope.IsError { + // the turn whose reply wrote its calls as text is over: the run + // is told to make them, and the reply goes on in its answer + retell = false + calls = textCalls{} + ask, _ := json.Marshal(map[string]any{"type": "user", "uuid": newUUID(), "message": map[string]any{"role": "user", + "content": []map[string]any{{"type": "text", "text": textCallsAsk}}}}) + if err := r.tell(ask); err != nil { + inside = false + r.emit(Event{Kind: KError, Text: "Claude Code could not be told to make the tool calls its reply wrote as text: " + err.Error(), Status: http.StatusBadGateway, RequestID: reqID}) + r.endSegment() + } + return + } if envelope.Type == "result" { + retell = false // a turn that failed — out of quota, rate limited — ends with // this and no message_stop, the CLI waiting on its next input: // the reply ends here, or it would wait with it (#177) @@ -2385,7 +2426,7 @@ func (r *subscriptionRun) readOutput(rd io.Reader) { r.emit(Event{Kind: KSig, Text: c.Signature}) } case "text": - text(c.Text) + said(c.Text) case "tool_use": name, theirs := toolStart(index, c.Name) if !theirs { @@ -2440,7 +2481,7 @@ func (r *subscriptionRun) readOutput(rd io.Reader) { r.emit(Event{Kind: KToolStart, ID: e.ContentBlock.ID, Name: name}) } case "text": - text(e.ContentBlock.Text) + said(e.ContentBlock.Text) case "thinking": // a block of its own, signed with no text or not (#1445) r.emit(Event{Kind: KThinkStart}) @@ -2457,7 +2498,7 @@ func (r *subscriptionRun) readOutput(rd io.Reader) { case "content_block_delta": switch e.Delta.Type { case "text_delta": - text(e.Delta.Text) + said(e.Delta.Text) case "thinking_delta": r.emit(Event{Kind: KThink, Text: e.Delta.Thinking}) case "signature_delta": @@ -2675,6 +2716,9 @@ func renderClaudePrompt(req *Request) ([]map[string]any, error) { chunk = len(blocks) - 1 } } + if slices.ContainsFunc(req.Messages, callsTool) { + text.WriteString(pastCallsNote + "\n\n") + } if split > 0 { text.WriteString("") } @@ -2902,6 +2946,9 @@ func renderClaudeTurn(msgs []Message, tools []Tool) []map[string]any { } blocks = renderParts(blocks, &text, m.Parts, offered) } + if slices.ContainsFunc(msgs, callsTool) { + text.WriteString("\n\n" + pastCallsNote) + } return closeBlocks(blocks, &text) } diff --git a/internal/gateway/claude_text_calls.go b/internal/gateway/claude_text_calls.go new file mode 100644 index 000000000..65280c7ca --- /dev/null +++ b/internal/gateway/claude_text_calls.go @@ -0,0 +1,75 @@ +package gateway + +import "strings" + +// A run started anew, or a turn that goes on with the client's own calls in +// it, is told the conversation as text, each past call a "[tool call …]" +// line (renderCachedParts). The model can take that for how it calls a +// tool and write such lines itself: Claude Code then has no call to make, +// the turn ends, and the client shows the lines as the reply's words +// (Zhenzhen on Discord, Claude Desktop on Fable 5.1). +const textCallOpen = "[tool call " + +// textCallsAsk is what a run whose reply wrote its calls as text is told, +// once, so it makes them (readOutput). +const textCallsAsk = `Your last message wrote tool calls out as text ("[tool call …]" lines). ` + + `Text like that runs nothing: no tool ran, and the user doesn't see those lines. Make the calls with your tools now.` + +// pastCallsNote ends a prompt that tells past calls as text: the lines +// record them, and writing one calls nothing. +const pastCallsNote = "(The \"[tool call …]\" and \"[tool result …]\" lines above record calls made earlier. " + + "Writing such a line calls nothing: call a tool only with the tool itself.)" + +// textCalls holds back a reply's words from the first line that opens as a +// call told in text (textCallOpen), so the client isn't shown it. Words up +// to that line go on as they come; a line is held only while it could +// still open so. +type textCalls struct { + mid bool // the words so far end inside a line that can't be one + line string // the start of a line that may open as one + seen bool // a line opened as one: the rest is held + held strings.Builder +} + +// push takes the next of the reply's words and says which go to the client +// now. +func (c *textCalls) push(s string) string { + if c.seen { + c.held.WriteString(s) + return "" + } + var out strings.Builder + for i := 0; i < len(s); i++ { + ch := s[i] + if c.mid { + out.WriteByte(ch) + c.mid = ch != '\n' + continue + } + line := c.line + s[i:i+1] // a byte, as a UTF-8 rune may be cut across chunks + open := strings.TrimLeft(line, " \t") + switch { + case strings.HasPrefix(open, textCallOpen): + c.seen, c.line = true, "" + c.held.WriteString(line) + c.held.WriteString(s[i+1:]) + return out.String() + case strings.HasPrefix(textCallOpen, open): + c.line = line + default: + out.WriteString(line) + c.line, c.mid = "", ch != '\n' + } + } + return out.String() +} + +// end is what was held at the reply's end: the words from the call told in +// text on when seen, else a line's start that never became one. +func (c *textCalls) end() (held string, seen bool) { + if !c.seen { + held, c.line = c.line, "" + return held, false + } + return c.held.String(), true +} diff --git a/internal/gateway/claude_text_calls_test.go b/internal/gateway/claude_text_calls_test.go new file mode 100644 index 000000000..bd2abab5f --- /dev/null +++ b/internal/gateway/claude_text_calls_test.go @@ -0,0 +1,230 @@ +package gateway + +import ( + "bufio" + "encoding/json" + "io" + "strings" + "sync" + "testing" +) + +// The report's lines (Zhenzhen on Discord, Claude Desktop 3.1623.0 on +// "Fable 5.1 High", magpie 0.1.1327): the model wrote its calls in the +// form a conversation told as text gives past calls, ids made up. +const ( + reportedPlanCall = `[tool call mcp__magpie__mcp__ccd_turn__update_plan id=toolu_0Validate args={"advance":true}]` + reportedBashCall = `[tool call mcp__magpie__Bash id=toolu_0Validate bash args={"command":"cd /Users/... && git diff --check ..."}]` +) + +// textCallTurn is a streamed reply whose words are chunks, ended as Claude +// Code ends a turn: end_turn and its result. +func textCallTurn(id string, chunks ...string) []string { + lines := []string{ + `{"type":"stream_event","event":{"type":"message_start","message":{"id":"` + id + `","model":"claude-fable-5-1","usage":{"input_tokens":3,"output_tokens":1}}}}`, + `{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}}`, + } + for _, c := range chunks { + b, _ := json.Marshal(c) + lines = append(lines, `{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":`+string(b)+`}}}`) + } + return append(lines, + `{"type":"stream_event","event":{"type":"content_block_stop","index":0}}`, + `{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":40}}}`, + `{"type":"stream_event","event":{"type":"message_stop"}}`, + `{"type":"result","subtype":"success","is_error":false,"result":"done"}`, + ) +} + +// realCallTurn is a streamed reply that calls the client's update_plan +// through the run's MCP helper, as Claude Code tells it. +var realCallTurn = []string{ + `{"type":"stream_event","event":{"type":"message_start","message":{"id":"msg_real","model":"claude-fable-5-1","usage":{"input_tokens":3,"output_tokens":1}}}}`, + `{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_01RealCall","name":"mcp__magpie__mcp__ccd_turn__update_plan","input":{}}}}`, + `{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\"advance\":true}"}}}`, + `{"type":"stream_event","event":{"type":"content_block_stop","index":0}}`, + `{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":20}}}`, + `{"type":"stream_event","event":{"type":"message_stop"}}`, +} + +// stdinOf gives run an input that records each line it is told. +func stdinOf(t *testing.T, run *subscriptionRun) func() []string { + t.Helper() + pr, pw := io.Pipe() + run.stdin = pw + var mu sync.Mutex + var told []string + done := make(chan struct{}) + go func() { + defer close(done) + s := bufio.NewScanner(pr) + s.Buffer(make([]byte, 64<<10), 1<<20) + for s.Scan() { + mu.Lock() + told = append(told, s.Text()) + mu.Unlock() + } + }() + t.Cleanup(func() { pw.Close(); pr.Close(); <-done }) + return func() []string { + mu.Lock() + defer mu.Unlock() + return append([]string(nil), told...) + } +} + +// A reply that writes its tool calls as "[tool call …]" text shows the +// client none of it: the run is told to make the calls, and the client gets +// the real call, the words before the text calls kept. Before, the client +// showed the lines as the reply's words and nothing ran. +func TestClaudeTextToolCallsAreMadeForReal(t *testing.T) { + run := &subscriptionRun{} + told := stdinOf(t, run) + lines := append(textCallTurn("msg_text", + "Plan advanced; now validating.\n", + "[tool", " call mcp__magpie__mcp__ccd_turn__update_plan id=toolu_0Valid", + strings.TrimPrefix(reportedPlanCall, "[tool call mcp__magpie__mcp__ccd_turn__update_plan id=toolu_0Valid")+"\n", + reportedBashCall+"\n[tool result id=toolu_0Validate]\nok"), + realCallTurn...) + text, stop, _, _, raw, ended, ok := claudeReply(t, run, lines, true) + if strings.Contains(raw, "[tool call") || strings.Contains(raw, "tool result id=") { + t.Fatalf("the client was shown the calls written as text:\n%s", raw) + } + if text != "Plan advanced; now validating.\n[mcp__ccd_turn__update_plan]" || stop != "tool_use" || ended != "tool" || !ok { + t.Fatalf("reply %q stop %q, run ended %q %v:\n%s", text, stop, ended, ok, raw) + } + if strings.Count(raw, `"type":"message_start"`) != 1 { + t.Fatalf("the reply didn't go on as one message:\n%s", raw) + } + asks := told() + if len(asks) != 1 { + t.Fatalf("the run was told %d lines, want the one ask: %q", len(asks), asks) + } + var ask struct { + Type string `json:"type"` + Message struct { + Role string `json:"role"` + Content []struct { + Text string `json:"text"` + } `json:"content"` + } `json:"message"` + } + if json.Unmarshal([]byte(asks[0]), &ask) != nil || ask.Type != "user" || ask.Message.Role != "user" || + len(ask.Message.Content) != 1 || ask.Message.Content[0].Text != textCallsAsk { + t.Fatalf("the run was told %s", asks[0]) + } + // the ask names neither magpie nor the vendor + for _, w := range []string{"magpie", "Claude", "Anthropic"} { + if strings.Contains(textCallsAsk, w) || strings.Contains(pastCallsNote, w) { + t.Fatalf("the text magpie adds names %s", w) + } + } +} + +// Told once, a reply that writes its calls as text again reaches the +// client as written: the run isn't asked over and over. +func TestClaudeTextToolCallsAskedOnce(t *testing.T) { + run := &subscriptionRun{} + told := stdinOf(t, run) + lines := append(textCallTurn("msg_text", reportedPlanCall), textCallTurn("msg_again", "Calling it: \n"+reportedBashCall)...) + text, stop, _, _, raw, ended, ok := claudeReply(t, run, lines, true) + if text != "Calling it: \n"+reportedBashCall || stop != "end_turn" || ended != "stop" || !ok { + t.Fatalf("reply %q stop %q, run ended %q %v:\n%s", text, stop, ended, ok, raw) + } + if n := len(told()); n != 1 { + t.Fatalf("the run was asked %d times", n) + } +} + +// A run with no input to tell (one that ends by itself) gives the client the +// words as written, as before. +func TestClaudeTextToolCallsWithoutInput(t *testing.T) { + text, stop, _, _, raw, _, _ := claudeReply(t, &subscriptionRun{}, textCallTurn("msg_text", "a\n"+reportedPlanCall), true) + if text != "a\n"+reportedPlanCall || stop != "end_turn" { + t.Fatalf("reply %q stop %q:\n%s", text, stop, raw) + } +} + +// Words that only look like the start of such a line, or name it mid-line, +// go to the client whole, however they are cut into chunks. +func TestClaudeTextCallsHoldsOnlyTheLine(t *testing.T) { + for _, words := range []string{ + "[tooling] fixed\n[tool]\n [tool calls] are made with tools", + "see [tool call x id=1 args={}] in the log\nok", + "", + "\n\n[tool ca", + "一只猫\n [工具] 调用 …\n[tool callé]", + } { + for size := 1; size <= len(words)+1; size++ { + var c textCalls + var out strings.Builder + for i := 0; i < len(words); i += size { + out.WriteString(c.push(words[i:min(i+size, len(words))])) + } + held, seen := c.end() + if seen || out.String()+held != words { + t.Fatalf("%q in chunks of %d: shown %q, held %q (%v)", words, size, out.String(), held, seen) + } + } + } + var c textCalls + shown := c.push("ok\n ") + c.push(reportedPlanCall[:3]) + c.push(reportedPlanCall[3:]+"\nmore") + if held, seen := c.end(); shown != "ok\n" || !seen || held != " "+reportedPlanCall+"\nmore" { + t.Fatalf("shown %q, held %q (%v)", shown, held, seen) + } +} + +// A conversation told as text says its "[tool call …]" lines are a +// record, and that writing one calls nothing: for a run started anew and +// for a turn told with the client's own calls. One with no calls is told +// as before. +func TestClaudePromptSaysPastCallsAreARecord(t *testing.T) { + msgs := []Message{ + {Role: "user", Parts: []Part{{Kind: Text, Text: "check the diff"}}}, + {Role: "assistant", Parts: []Part{{Kind: ToolCall, ID: "toolu_01", Name: "Bash", Args: json.RawMessage(`{"command":"git diff --check"}`)}}}, + {Role: "user", Parts: []Part{{Kind: ToolResult, CallID: "toolu_01", Text: "clean"}}}, + {Role: "assistant", Parts: []Part{{Kind: Text, Text: "clean"}}}, + {Role: "user", Parts: []Part{{Kind: Text, Text: "go on"}}}, + } + tools := []Tool{{Name: "Bash"}} + all := func(blocks []map[string]any) string { + var s strings.Builder + for _, b := range blocks { + t, _ := b["text"].(string) + s.WriteString(t) + } + return s.String() + } + blocks, err := renderClaudePrompt(&Request{Messages: msgs, Tools: tools}) + if err != nil { + t.Fatal(err) + } + if got := all(blocks); !strings.HasSuffix(got, pastCallsNote+"\n\n") || !strings.Contains(got, "[tool call mcp__magpie__Bash id=toolu_01") { + t.Fatalf("started anew:\n%s", got) + } + if got := all(renderClaudeTurn(msgs[1:3], tools)); !strings.HasSuffix(got, "\n\n"+pastCallsNote) { + t.Fatalf("the turn since:\n%s", got) + } + for _, m := range [][]Message{{msgs[0]}, {msgs[0], msgs[3], msgs[4]}} { + blocks, _ := renderClaudePrompt(&Request{Messages: m, Tools: tools}) + if got := all(blocks) + all(renderClaudeTurn(m, tools)); strings.Contains(got, pastCallsNote) { + t.Fatalf("no calls, yet told:\n%s", got) + } + } +} + +// The same told in whole messages, as Claude Code tells an answer it asked +// for again without a stream. +func TestClaudeTextToolCallsUnstreamed(t *testing.T) { + run := &subscriptionRun{} + told := stdinOf(t, run) + words, _ := json.Marshal("Validating.\n" + reportedBashCall) + lines := append([]string{ + `{"type":"assistant","message":{"id":"msg_whole","model":"claude-fable-5-1","role":"assistant","content":[{"type":"text","text":` + string(words) + `}],"stop_reason":"end_turn","usage":{"input_tokens":3,"output_tokens":40}}}`, + `{"type":"result","subtype":"success","is_error":false,"result":"done"}`, + }, realCallTurn...) + text, stop, _, _, raw, ended, ok := claudeReply(t, run, lines, true) + if text != "Validating.\n[mcp__ccd_turn__update_plan]" || stop != "tool_use" || ended != "tool" || !ok || len(told()) != 1 { + t.Fatalf("reply %q stop %q, run ended %q %v, told %q:\n%s", text, stop, ended, ok, told(), raw) + } +}