Skip to content

Feat: Record Anthropic tool results in session events - #1338

Merged
huang195 merged 2 commits into
rossoctl:mainfrom
huang195:feat/tool-results
Oct 9, 2026
Merged

huang195 merged 2 commits into
rossoctl:mainfrom
huang195:feat/tool-results

Conversation

@huang195

@huang195 huang195 commented Oct 8, 2026 •

Copy link
Copy Markdown
Member

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 as tool_result blocks, so a tool result left nothing behind but its size in contentBytes. OpenAI-format clients were unaffected, because their tool output arrives as role: "tool" text.

This records each tool_result block as an entry in a new inference.toolResults list: toolUseId, its text content, and isError, in wire order.

Why a new field, not message content

Plugins read Messages:

  • IBAC treats user-role Content as the user's intent.
  • OPA, SPARC and CPEX copy role and content into their policy input.
  • Lineage exports Messages as a span.

Putting tool output in Content would hand all of them new input. As a separate field, it reaches none of them unless a plugin opts in. Message Content and ContentBytes are unchanged.

Storage

Every request re-sends all earlier results, so the field is deduplicated the same way the conversation is:

  • In memory: the interner shares each result's text with the previous request. It copies the array first, because both phases of a request share it.
  • On disk: the archive writes long results as references, via a new refs.TR entry.
  • Summary view: view=summary drops the field, as it drops Messages.

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 toolResults on request rows and hides them on response rows, the same as messages.

Testing

  • Parser: string and text-block content, is_error, results alongside a text block (which stays out of Content), and an image result recorded without its bytes.
  • Interner: sharing across requests, and the caller's array is not rewritten. I confirmed the second test fails without the copy.
  • Archive: reference and round trip. The fixture now carries accumulating results, so the existing no-mutation test covers the new copy; also confirmed it fails without it.
  • Summary: the field is dropped, and the shape guard is updated from 26 to 27 fields.
  • agentop: shown on request rows, hidden on response rows.
  • core: go vet ./... and go test ./... pass (65 packages). cmd/agentop: GOWORK=off go vet ./... and go test ./... pass. cmd/cortex builds and vets with the full plugin profile. gofmt is clean.

Not exercised against a running proxy. Installing it would restart the shared laptop service.

Deferred from review

  • Retention of the per-event headers: ToolResults headers and ToolUseID copies 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 a ToolResults case to BenchmarkRetainedHeap*, intern ToolUseID regardless of length, and update CLAUDE.md gotcha 14.
  • core/session/archive/format.go downgrade note and the Compatibility line above: an older binary has no ToolResults field, so it drops every tool result, short or long.
  • core/pipeline/extensions.go field comment: "OpenAI-format clients leave this empty" holds for Chat Completions only. The Responses dialect skips function_call_output, so Codex tool output is not recorded.
  • docs/plugin-reference.md: say that ToolResults is deliberately not a content source. Fragments() covers OpenAI role: "tool" messages only.
  • core/cost/usage/replay_test.go: the size test fills the heavy fields by name. A reflection-driven fill of InferenceExtension would catch the next field added without a matching ReplayCopy change.
  • core/cost/usage/replay.go doc comment: name tool results among the cleared fields, and cite TestReplayCopy_DoesNotGrowWithTheConversation for the size claim.
  • core/cost/usage/replay.go: fold inf.ToolResults = nil into the multi-assignment above it.
  • core/session/archive/doc.go: still says "exactly the five fields the interner shares". intern.go and CLAUDE.md now say six.
  • core/plugins/inferenceparser/anthropic.go: each tool_result body is copied into a json.RawMessage and decoded again, so it is allocated twice. Server-side *_tool_result blocks are not captured, and the field comment could say so.

Assisted-By: Claude (Anthropic AI) [email protected]

Summary by CodeRabbit

  • New Features
    • Anthropic tool results are retained in session archives with their text, associated tool-use ID, and error status.
    • Request details show tool results; timeline summaries continue to omit them.
  • Improvements
    • Repeated tool-result content is deduplicated in archives, while shorter content remains inline.
    • Tool-result data is excluded from usage replay copies.
  • Documentation
    • Updated architecture and service documentation to describe tool-result storage and archive behavior.

@coderabbitai

coderabbitai Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 49a5061e-1665-4431-8e3e-2704ce6db4a5
📥 Commits

Reviewing files that changed from the base of the PR and between 21331d8 and a0a6cfc.

📒 Files selected for processing (6)
  • CLAUDE.md
  • cmd/agentop/tui/detail_pane.go
  • core/cost/usage/replay.go
  • core/cost/usage/replay_test.go
  • core/pipeline/extensions.go
  • core/sessionapi/summary_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • CLAUDE.md

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

The 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.

Changes

Anthropic tool-result capture and request details

Layer / File(s) Summary
Parse tool results and expose request details
core/pipeline/extensions.go, core/plugins/inferenceparser/anthropic.go, core/plugins/inferenceparser/anthropic_test.go, cmd/agentop/tui/*, docs/framework-architecture.md
The Anthropic parser extracts tool-result IDs, text content, and error flags into InferenceExtension.ToolResults. Request detail filtering retains the field. Tests cover parsed results and request-versus-response filtering.

Session interning and archive handling

Layer / File(s) Summary
Intern and archive tool-result content
core/session/intern.go, core/session/intern_test.go, core/session/archive/*, CLAUDE.md, docs/laptop-service.md
Session interning processes tool-result content. Archive splitting references qualifying content, and joining restores it with validation. Tests cover interning and archive round trips.

Summary and replay-copy filtering

Layer / File(s) Summary
Exclude tool results from summary and replay copies
core/sessionapi/summary.go, core/sessionapi/summary_test.go, core/cost/usage/replay.go, core/cost/usage/replay_test.go
Timeline summary projection and replay copies clear Inference.ToolResults. Tests cover summary projection and replay-copy size.

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
Loading

Suggested reviewers: esnible

Merge Risk: ⚪ Minimal · up to a0a6c

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)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 25 functions across 14 files. (1 skipped: …
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the primary change: recording Anthropic tool results in session events.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

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]>

@cwiklik cwiklik left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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"`

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@huang195
huang195 merged commit 51b6b92 into rossoctl:main Oct 9, 2026
30 checks passed
@huang195
huang195 deleted the feat/tool-results branch October 9, 2026 00:11
huang195 added a commit that referenced this pull request Oct 15, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants