diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index 21233c1ea..ffde2f909 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -62,7 +62,11 @@ That message holds the history in blocks of `historyChunk` messages, and magpie's one mark (Claude Code keeps three of Anthropic's four) is on the last whole block, else on the caller's instructions: a later run started anew for the same conversation within the hour reads the history up to an -earlier run's mark, found within Anthropic's 20-block lookback. +earlier run's mark, found within Anthropic's 20-block lookback. A +conversation with no history (no reply that calls no tool, as a sub-agent's +loop of tool calls that Claude Code's AgentSummary asks a summary of) has +its every message but the last chunked instead. The turn to answer after a +history is not chunked, and image blocks count toward the lookback. A turn that goes on in the run that had the last one is told only the messages since (`renderClaudeTurn`), and Anthropic reads the rest from the cache. diff --git a/internal/gateway/claude_prompt_cache_test.go b/internal/gateway/claude_prompt_cache_test.go index 376b51f27..76e2763c6 100644 --- a/internal/gateway/claude_prompt_cache_test.go +++ b/internal/gateway/claude_prompt_cache_test.go @@ -129,3 +129,80 @@ func TestClaudeHistoryCachedAcrossNewRuns(t *testing.T) { t.Fatalf("short conversation marks %v", at) } } + +// A conversation with no reply that calls no tool, as a sub-agent's loop +// of tool calls that Claude Code's AgentSummary asks a summary of with its +// last results, has no history to chunk: its messages before the last are +// chunked, so a later request of the same loop, started anew, reads what +// the earlier one wrote (#1716, JinJieBeWater). +func TestClaudeToolLoopCachedAcrossNewRuns(t *testing.T) { + loop := func(rounds int, ask string) *Request { + req := &Request{System: "rules", Tools: []Tool{{Name: "read"}}} + req.Messages = append(req.Messages, Message{Role: "user", Parts: []Part{{Kind: Text, Text: "the task"}}}) + for i := 0; i < rounds; i++ { + last := []Part{{Kind: ToolResult, CallID: fmt.Sprintf("c%d", i), Text: "contents"}} + if i == rounds-1 { + last = append(last, Part{Kind: Text, Text: ask}) + } + req.Messages = append(req.Messages, + Message{Role: "assistant", Parts: []Part{{Kind: ToolCall, ID: fmt.Sprintf("c%d", i), Name: "read", Args: json.RawMessage(`{"path":"a"}`)}}}, + Message{Role: "user", Parts: last}) + } + return req + } + marked := func(blocks []map[string]any) []int { + var at []int + for i, b := range blocks { + if _, ok := b["cache_control"].(map[string]string); ok { + at = append(at, i) + } + } + return at + } + earlier, err := renderClaudePrompt(loop(20, "summarize so far")) + if err != nil { + t.Fatal(err) + } + later, err := renderClaudePrompt(loop(24, "summarize again")) + if err != nil { + t.Fatal(err) + } + if historyEnd(loop(20, "x").Messages) != 0 { + t.Fatal("the loop has a history") + } + first, second := marked(earlier), marked(later) + if len(first) != 1 || len(second) != 1 || first[0] == 0 || second[0] < first[0] || second[0]-first[0] > 20 { + t.Fatalf("marks: earlier %v, later %v", first, second) + } + for i := 0; i <= first[0]; i++ { + if earlier[i]["text"] != later[i]["text"] { + t.Fatalf("block %d differs:\n%q\n%q", i, earlier[i]["text"], later[i]["text"]) + } + } + if strings.Contains(earlier[first[0]]["text"].(string), "summarize") { + t.Fatalf("the marked block holds the last message") + } + // the last message is never in a chunk, when it would end one either + even := loop(15, "summarize at the end of a chunk") + even.Messages = append([]Message{{Role: "user", Parts: []Part{{Kind: Text, Text: "context"}}}}, even.Messages...) + if len(even.Messages)%historyChunk != 0 { + t.Fatalf("%d messages", len(even.Messages)) + } + blocks := mustRender(t, even) + if at := marked(blocks); len(at) != 1 || strings.Contains(blocks[at[0]]["text"].(string), "summarize") { + t.Fatalf("marks %v in %v", at, blocks) + } + // a loop shorter than a chunk keeps the mark on the instructions + if at := marked(mustRender(t, loop(3, "x"))); len(at) != 1 || at[0] != 0 { + t.Fatalf("short loop marks %v", at) + } +} + +func mustRender(t *testing.T, req *Request) []map[string]any { + t.Helper() + blocks, err := renderClaudePrompt(req) + if err != nil { + t.Fatal(err) + } + return blocks +} diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 6cb80b59e..f7481c3f4 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -2511,6 +2511,17 @@ func renderClaudePrompt(req *Request) ([]map[string]any, error) { // as one stretch of Human:/Assistant: text, the images of earlier turns // read as just sent, and the model answered them again (#1365). split := historyEnd(req.Messages) + // The history is told in chunks, each a block of its own (historyChunk). + // A conversation with no reply that calls no tool, as a sub-agent's + // loop of tool calls (Claude Code's AgentSummary asks a summary of one + // with its last results), has no history: its every message but the + // last is chunked instead, which a later request of the same loop + // repeats. One with a history later is told it wrapped, from its first + // message on, so nothing is lost there either. + chunked := split + if split == 0 { + chunked = len(req.Messages) - 1 + } for i, m := range req.Messages { if split > 0 && i == 0 { text.WriteString(historyOpen) @@ -2525,7 +2536,7 @@ func renderClaudePrompt(req *Request) ([]map[string]any, error) { text.WriteString(label + ": ") blocks = renderParts(blocks, &text, m.Parts, offered) text.WriteString("\n\n") - if i+1 <= split && (i+1)%historyChunk == 0 { + if i+1 <= chunked && (i+1)%historyChunk == 0 { blocks = append(blocks, map[string]any{"type": "text", "text": text.String()}) text.Reset() chunk = len(blocks) - 1 @@ -2540,6 +2551,8 @@ func renderClaudePrompt(req *Request) ([]map[string]any, error) { // the same conversation, as after a change of tools or a turn that // missed its run, reads the history this one wrote, found within // Anthropic's 20-block lookback, instead of writing all of it again. + // The turn to answer is never chunked when there is a history: a later + // run whose history ends further on tells those messages in it. if chunk >= 0 { if instructions >= 0 { delete(blocks[instructions], "cache_control")