Repository navigation
Feat: Record Anthropic tool results in session events - #1338
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configuration
📒 Files selected for processing (6)
🚧 Files skipped from review as they are similar to previous changes (1)
Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review. 📝 WalkthroughWalkthroughThe change adds Anthropic tool-result data to inference extensions. Session interning and archives now handle tool-result content. Timeline summaries and replay copies omit it, while request detail filtering retains it. ChangesAnthropic tool-result capture and request details
Session interning and archive handling
Summary and replay-copy filtering
Priority: ➖ Normal Estimated code review effort: 3 (Moderate) | ~20 minutes Change: Feature Sequence Diagram(s)sequenceDiagram
participant AnthropicRequest
participant InferenceParser
participant InferenceExtension
participant SessionInterner
participant SessionArchive
AnthropicRequest->>InferenceParser: request message content
InferenceParser->>InferenceExtension: parsed tool results
InferenceExtension->>SessionInterner: inference event
SessionInterner->>SessionArchive: interned tool-result content
SessionArchive->>SessionArchive: store and restore content references
Suggested reviewers: Merge Risk: ⚪ Minimal · up to The change records Anthropic tool results in session events and keeps them out of summaries and replay copies. No concrete merge-blocking risk was identified in the supplied files. 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
The inference parser flattened each message to its text blocks, so an Anthropic tool_result block — the output of an earlier tool call — left nothing behind but its size in ContentBytes. OpenAI-format clients were unaffected (their tool output arrives as role "tool" text), so the gap was Claude Code's: its error messages, command output and file contents never reached the session store. Record each tool_result block as an InferenceExtension.ToolResults entry — toolUseId, text content, isError — in wire order. It is a new field rather than message Content on purpose: IBAC reads user-role Content as the user's intent, OPA/SPARC/CPEX copy role and content into policy input, and lineage exports Messages as a span, so tool output reaches none of them unless a plugin opts in. Every request re-sends all earlier results, so the field is deduplicated like the conversation: the interner shares each result's text with the previous request (cloning the array first, which both phases of a request alias), the archive writes it as a reference (refs.TR), and view=summary drops it. agentop's detail pane shows it on request rows. Measured on 664 tool-result messages across 15 captured sessions: median 957 bytes, p99 25 KB, largest 58 KB; the heaviest session holds 0.35 MB. Signed-off-by: Hai Huang <[email protected]> Assisted-By: Claude (Anthropic AI) <[email protected]>
Fixes review: ReplayCopy kept Inference.ToolResults, so the startup usage replay held each archived event's accumulated tool results Files: - core/cost/usage/replay.go - core/cost/usage/replay_test.go Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
c0d958d to
a0a6cfc
Compare
cwiklik
left a comment
There was a problem hiding this comment.
Tool output finally lands somewhere a reader can see it, and the mechanics are right: text extraction is case-for-case identical to flattenContent on every input shape (string, null, [], block array, malformed), the archive's TR follows the M/TD/TP/AP pattern exactly including the corruption guard and the all-nil collapse, the interner clones before rewriting so SnapshotInference's shared slices are safe, and the len(next) == 0 table-preservation invariant still holds for a ToolResults-only event. ReplayCopy and summarizeEvent both nil the field, and 26 → 27 on the shape guard is exactly one field.
Nothing blocking. Three of my four comments are about which of your own deferrals shouldn't be deferred — the Fragments() one most of all, because it is the only place the Messages-are-intent rationale doesn't reach, and the gap it leaves is dialect-dependent rather than uniform.
Author: huang195 (MEMBER — maintainer)
Areas reviewed: Go (parser, pipeline extensions, session store + interner, archive format, session API, usage replay), agentop TUI, Docs
Agent/IDE config (.claude/.vscode): none
Commits: 2 commits, all signed-off: yes (Assisted-By, no Co-Authored-By)
CI status: passing (28/28; Spellcheck skipping)
Assisted-By: Claude (Anthropic AI) [email protected]
| // none of them unless a plugin opts in to this field. It is for the session store and its | ||
| // readers. OpenAI-format clients already carry tool output as role "tool" messages, so | ||
| // their requests leave this empty. | ||
| ToolResults []InferenceToolResult `json:"toolResults,omitempty"` |
There was a problem hiding this comment.
suggestion — the KEPT-OUT-OF-MESSAGES rationale holds for Messages, but it doesn't carry over to Fragments(), and that is where this gets asymmetric.
InferenceExtension.Fragments() (core/pipeline/content.go:193) already remaps an OpenAI role: "tool" message to capabilities.RoleToolResult — the constant exists precisely for "content returned from a tool invocation", and MCPExtension.Fragments() emits it explicitly so that "a PII scrubber or credential detector covers the error channel uniformly". After this PR, Anthropic tool output exists in-process and is the one dialect Fragments() withholds. A credential detector built on ContentSource sees a leaked token in tool output from an OpenAI client and not from Claude Code.
The intent argument doesn't apply here: fragments are role-tagged, and core/capabilities/content.go documents the consumer idiom as filtering f.Role == capabilities.RoleUser. Emitting these as RoleToolResult would not contaminate IBAC's view of intent — it would restore that file's own promise that "existing guardrails pick it up automatically".
I see it in "Deferred from review" as a docs task. Worth reconsidering as code, or at least recording the dialect asymmetry rather than describing it as documentation.
| // OPA/SPARC/CPEX as policy input, lineage as an exported span — and tool output reaches | ||
| // none of them unless a plugin opts in to this field. It is for the session store and its | ||
| // readers. OpenAI-format clients already carry tool output as role "tool" messages, so | ||
| // their requests leave this empty. |
There was a problem hiding this comment.
suggestion — "OpenAI-format clients already carry tool output as role tool messages, so their requests leave this empty" is true for Chat Completions and false for Responses. core/plugins/inferenceparser/responses.go:57 says it outright: "Every other item type (reasoning echoes, function_call/function_call_output round-trips) is skipped." Codex tool output isn't carried elsewhere — it isn't captured at all.
As written, a reader of a brand-new exported field is told the gap is dialect-specific coverage when it is a second uncovered dialect. Suggest naming Chat Completions specifically and saying the Responses path records none.
| // the completion, tool descriptions, tool schemas, A2A part content — and nothing else, so the | ||
| // two dedups are of the same thing. MCP params and results stay inline for the interner's | ||
| // reason: they are maps, unmeasured on this workload. | ||
| // The fields are exactly the six core/session.Interner shares in memory — message content, |
There was a problem hiding this comment.
suggestion — core/session/archive/doc.go:13 still reads "exactly the five fields the interner shares". This PR updates the same sentence in three places — here, core/session/intern.go:51, and CLAUDE.md — and leaves the fourth, in this same package. Whoever opens doc.go first gets the wrong count. One word.
| IsError bool `json:"is_error"` | ||
| } | ||
| if err := json.Unmarshal(raw, &blocks); err != nil { | ||
| // A plain string, null, or a shape we do not model: none of them holds a tool result. |
There was a problem hiding this comment.
nit — null doesn't reach this branch. json.Unmarshal succeeds on null into a slice, leaving blocks nil, so it falls out of the loop and returns ("", nil) — the same answer flattenContent gives, so no behaviour change, but the comment names a path it doesn't take.
Three gaps in the tool record, one per layer: - Responses API requests now capture function_call_output input items into InferenceExtension.ToolResults — the Codex dialect's counterpart of Anthropic's tool_result blocks, previously skipped wholesale, so a Codex session recorded that tools ran but not what they returned. - OpenAI Chat Completions streamed tool calls are now assembled from index-keyed delta.tool_calls fragments, on both the frame path and the buffered SSE path, which share one inferenceStreamState. The generic toolCallState (renamed from anthropicToolCallState) is the same assembly Anthropic's input_json_delta already used. This was the last of the four response paths that left ToolCalls empty. - ToolResults[i].ToolUseID is interned below InternMinLen via internID: ids repeat exactly as hard as result content while being ~20 bytes, and the duplication they left was unpriced. Measured on the new BenchmarkRetainedHeapWithToolResults fixture (300 turns): 4.99 MB without the id interning, 4.32 MB with. Also updates the ToolResults and ToolCalls field docs (the 'three of four paths' caveat is gone) and CLAUDE.md gotcha 14, both deferred from the review of #1338. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
Summary
Claude Code's tool results never reached the session store. The inference parser keeps only
type: "text"blocks of each message, and Anthropic sends tool output astool_resultblocks, so a tool result left nothing behind but its size incontentBytes. OpenAI-format clients were unaffected, because their tool output arrives asrole: "tool"text.This records each
tool_resultblock as an entry in a newinference.toolResultslist:toolUseId, its text content, andisError, in wire order.Why a new field, not message content
Plugins read
Messages:Contentas the user's intent.roleandcontentinto their policy input.Messagesas a span.Putting tool output in
Contentwould hand all of them new input. As a separate field, it reaches none of them unless a plugin opts in. MessageContentandContentBytesare unchanged.Storage
Every request re-sends all earlier results, so the field is deduplicated the same way the conversation is:
refs.TRentry.view=summarydrops the field, as it dropsMessages.Measured on 664 tool-result messages across 15 captured sessions: median 957 bytes, p99 25 KB, largest 58 KB. The heaviest session holds 0.35 MB.
Compatibility: an archive written by this version and read by an older binary (a downgrade) reads long tool results back empty. Every other field is intact.
agentop
The detail pane shows
toolResultson request rows and hides them on response rows, the same asmessages.Testing
is_error, results alongside a text block (which stays out ofContent), and an image result recorded without its bytes.core:go vet ./...andgo test ./...pass (65 packages).cmd/agentop:GOWORK=off go vet ./...andgo test ./...pass.cmd/cortexbuilds and vets with thefullplugin profile.gofmtis clean.Not exercised against a running proxy. Installing it would restart the shared laptop service.
Deferred from review
ToolResultsheaders andToolUseIDcopies are held once per event, because the id is too short to intern. A throwaway 300-turn benchmark measured 2.35 → 5.87 MB/session. Follow-ups: add aToolResultscase toBenchmarkRetainedHeap*, internToolUseIDregardless of length, and update CLAUDE.md gotcha 14.core/session/archive/format.godowngrade note and the Compatibility line above: an older binary has noToolResultsfield, so it drops every tool result, short or long.core/pipeline/extensions.gofield comment: "OpenAI-format clients leave this empty" holds for Chat Completions only. The Responses dialect skipsfunction_call_output, so Codex tool output is not recorded.docs/plugin-reference.md: say thatToolResultsis deliberately not a content source.Fragments()covers OpenAIrole: "tool"messages only.core/cost/usage/replay_test.go: the size test fills the heavy fields by name. A reflection-driven fill ofInferenceExtensionwould catch the next field added without a matchingReplayCopychange.core/cost/usage/replay.godoc comment: name tool results among the cleared fields, and citeTestReplayCopy_DoesNotGrowWithTheConversationfor the size claim.core/cost/usage/replay.go: foldinf.ToolResults = nilinto the multi-assignment above it.core/session/archive/doc.go: still says "exactly the five fields the interner shares".intern.goand CLAUDE.md now say six.core/plugins/inferenceparser/anthropic.go: eachtool_resultbody is copied into ajson.RawMessageand decoded again, so it is allocated twice. Server-side*_tool_resultblocks are not captured, and the field comment could say so.Assisted-By: Claude (Anthropic AI) [email protected]
Summary by CodeRabbit