Repository navigation
fix(agents): keep Claude CLI replies after many large tool results - #166127
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesThis PR excludes discarded Claude CLI tool-result payloads from cumulative output accounting while preserving charges for retained metadata and existing line and frame limits. Example: A Claude CLI turn executes 72 tools, each producing 120,000 characters.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep this PR open for landing: it fixes a distinct, demonstrated reply-loss bug that remains on current main, with no actionable findings and successful exact-head CI gates. Priority: P1 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe CLI streaming parser receives Claude stream-json records, accounts for bounded output, dispatches tool results to consumers, and assembles the final agent reply. flowchart LR
A[Agent exec] --> B[Anthropic CLI backend]
B --> C[Native Claude Code]
C --> D[JSONL framing and accounting]
D --> E[Tool result consumers]
D --> F[Final agent reply]
Technical reviewBest possible solution: Land the focused accounting repair in the existing streaming-limit owner while preserving the demonstrated retained-data, line, and frame guards. Do we have a high-confidence way to reproduce the issue? Current-main source exposes the overcharging path, and supplied shipped-entry output demonstrates the failure on pinned main and recovery on the exact PR head; this review executed no target code. Is this the best way to solve the issue? The patch repairs the accounting boundary directly, conservatively discounts only discarded payloads, and preserves existing consumer behavior without a new setting or parallel parser. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 323df2111e89. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +42, Tests -19, Docs +3. Total +26 across 4 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes: No label changes. Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (7 earlier review cycles)
Reviewed November 2, 2026, 6:12 PM ET / 23:12 UTC (Revision 8). |
|
Heads-up: #153545 landed in 12302d7 and closed #150132. Partial-message deltas (text, thinking, tool input) are now charged by encoded payload, and a real Claude Code 2.1.292 run that lost its reply at 20,000 frames now delivers it. This PR also changes retained-budget accounting and covers tool-result floods, which #153545 does not. If a long turn still fails on current main (for example many large tool results), please rebase onto main and update the PR to that remaining case with a repro; otherwise it can be closed. Thanks @RTapiador! |
9cb6b49 to
269665d
Compare
|
Reviewed the introduced accounting change at The fit is the distinction between consumed tool-result payloads and retained metadata. The implementation measures before in-place media normalization, discounts only tool-result-only user records, conservatively treats number encodings, and retains raw-line/frame limits. The shipped-runner 72-command before/after proof in the PR body is especially useful. I have not run this head locally and am not claiming additional runtime proof. This is complementary to #160209 / #186967: genuinely exhausting 20,000 ordinary frames still needs terminal recovery; increasing budgets in #185404 does not fix the accounting owner. Keeping those cases separate will help avoid closing the frame-loss report prematurely. Remaining landing gate is normal current-head CI/maintainer review. |
Claude Code echoes each tool result twice (message.content and tool_use_result), and the parser charged the whole line against the 8 MiB turn budget even though it only hands those payloads to onToolResult and keeps the tool ID. A turn with a few dozen large tool results lost its final reply with "CLI JSONL output exceeded 8388608 characters". Charge tool-result-only user records for everything except the result payloads: IDs, metadata, padding and a 32-character floor still count, and the records still count as ordinary frames under the 20,000-frame limit. Mixed user records keep full raw accounting. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rges The tool-result discount subtracted each payload's JSON.stringify length from the raw line. Re-encoding can be longer than the wire (`1e20` becomes 21 digits), so a record with a huge tool ID and many compact numbers in tool_use_result was charged only the 32-character floor while the parser still retained the ID. Discount a lower bound of each payload's wire size instead: strings and structure re-encode minimally, and every number counts as one character. IDs, metadata and padding are now always charged in full. Also rework the mixed-record regression so each record stays below the line limit and the assertion targets the cumulative budget error, and drop the uncommented type assertion flagged by the assertion-safety ratchet. Co-Authored-By: Claude Opus 5.5 <[email protected]>
main's subagent budget control pushed the same tool-result volume in the parent conversation and expected the 8 MiB budget to trip. Tool-result-only records are now discounted in the parent conversation too, so the control adds a text block to each record: parent records stay on raw accounting and only child attribution separates the two turns. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_019TfRR2HYxENXfvm4JB6bXx
42753be to
cbe785d
Compare
|
Rebased onto
One test from Checks (Node 24, macOS):
The branch is up to date with |
Linux shipped-entry proof on the exact headCandidate 47d7ecf, pinned main 573fd8c. Both were source-built and exercised through ordinary Each case used an independent task-owned retained state directory and the pinned task config. The exact binary printed its resolved config and SQLite database paths before execution. A synthetic managed Anthropic profile was installed and selected through the public auth CLI. HTTPS used the trusted-CA CONNECT route from #188069: Claude still requested The fixture issued 72 sequential tool calls. Each real shell command printed 120,000 characters (1,500 lines of 79 The main payload total includes the five small cancellation/denial results after the 67 large results; the fixture still offered all 72 calls. Each successful native full-result payload measured 121,525 encoded characters in Claude's own transcript. Candidate completed all 72 with zero tool failures, then delivered Selected actual result fields: // main, both runs
{"ok":false,"status":"error","final":"","payloads":[],"error":{"message":"CLI JSONL output exceeded 8388608 characters; refusing to parse output.","kind":"exception"}}
// exact candidate, both runs
{"ok":true,"status":"ok","final":"FINAL_REPLY_166127","toolSummary":{"calls":72,"tools":["mcp__openclaw__exec"],"failures":0}}Controls
Focused checks and simplification69/69 tests passed across framing, partial-message and subagent-budget suites; changed TypeScript lint reported 0 warnings/errors. The identical new repeated-text regression on main fails specifically with the 8 MiB budget error. @RTapiador's three original commits are preserved. The accounting owner no longer builds temporary block/map/spread arrays or re-measures already-discarded subagent payloads. New regressions are consolidated into existing framing fixtures, including all four tool-argument assembly boundaries. Whole PR: production +43/-1 (44 gross), tests +105/-124 (net -19), docs +8/-5. Public APIs, auth handling, model-facing text, per-line/frame limits and turn deadlines are unchanged. |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Landed in 8828c59. Thanks @RTapiador. Long tool-heavy Claude CLI runs no longer lose their final reply. |
…penclaw#166127) fix(agents): don't count discarded CLI tool results against the stream budget In Claude CLI runs, tool results that had already been discarded still counted toward the 8 MiB stream budget. Long tool-heavy runs therefore hit the budget, failed and lost the final reply. Only tool results that are still kept now count. Short runs are unchanged, and kept tool results still enforce the budget. Evidence: built `agent exec` with native Claude Code 2.1.288 and a real MCP `exec` tool, in Node 24.22.1 Linux Docker with a synthetic managed profile and a trusted-CA CONNECT fixture, running 72 tool calls with 120,000-character results. Main failed with the 8 MiB error and lost the final reply twice; with this change all 72 tools completed and the final reply was delivered twice. Short-run and kept-result controls were unchanged on both builds. Details: openclaw#166127 (comment). Thanks @RTapiador. Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Ismael <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
Root cause: src/agents/cli-output-stream-limits.ts:232 (`chargeClaudeStreamJsonLine`) charged every Claude frame the parser discards: each ordinary frame counted toward the 20,000-frame limit, and assistant snapshots, tool-result records, block starts, message starts and status records were charged their whole envelope against the 8 MiB budget, so a healthy turn of a few thousand small tool calls ran out of budget it never retained. Fixes #186967 Related: #159929, #192735, #192734 ## What Problem This Solves A long Claude CLI turn that makes many tool calls (a subagent building a repo, a scheduled job editing files) finishes its work, but OpenClaw drops the final reply and reports `CLI JSONL output exceeded 20000 lines` or `CLI JSONL output exceeded 8388608 characters`. The work is on disk; the requester sees a failure. ## User Impact User impact: Claude CLI turns with thousands of tool calls keep their final reply. The limits still stop turns that retain more than 8 MiB of text, thinking or tool input, and turns that stream a large volume of discarded output. ## Why This Change Was Made The two budgets were meant to bound what the parser keeps, but they counted stream volume. Every tool call costs about five frames of envelope metadata (message ids, uuids, timestamps, usage, tool-result metadata) that the parser throws away, so the limits tripped after roughly 3,300 sequential or 4,900 parallel small tool calls. The budget now charges what the parser keeps (text, thinking and tool-input payloads, assistant content blocks, block headers, tool ids), plus a fixed 32-character allowance for each discounted frame, so 8 MiB still bounds the number of frames. The 20,000-frame limit now counts only frames that leave more than 1 KiB of their raw line uncharged (for example large tool results), which is the parse work the character budget cannot see. The old payload re-serialization for tool results is gone; tool results are charged by their ids. No limit value, config or error text changes. #187125 rewords the limit error; this PR removes the cause instead, so that wording is not needed. ## Evidence Real Claude Code 2.1.322 run by `openclaw agent --local` (built `dist/`, isolated state, `claude-cli/claude-sonnet-4-6`) against a local Anthropic Messages fixture that returns `mcp__openclaw__read` calls of a tiny file, then a final reply. Base `d979dba02457`, candidate `48f1eb236794`. Fixture, harness and captured stdout breakdown are kept with the proof. | Turn | Base | Candidate | | --- | --- | --- | | 3,600 sequential tool calls | fails after 3,338 calls: `CLI JSONL output exceeded 20000 lines` (twice), no reply | `FINAL_REPLY_OK after 3600 tool calls` (twice) | | 7,000 tool calls, 10 per message | fails after about 4,900 calls: `CLI JSONL output exceeded 8388608 characters` (twice), no reply | `FINAL_REPLY_OK after 7000 tool calls` (twice) | | Control: 10 MB of reply text | | still fails with `exceeded 8388608 characters` | Measured from the captured stdout of the same CLI, the budget charge per small tool call drops from about 1,640 characters to about 500, and none of those frames counts toward the frame limit. Tests: `cli-output-framing.test.ts` › "keeps the reply of a turn with thousands of small tool calls" fails on base (`CLI JSONL output exceeded 20000 lines`) and passes here. The control-frame, partial-message, subagent, framing, output-limit, stream and JSONL suites pass (173 tests). On #159929: it no longer happens on main. #166127 already discounts the `tool_use_result` file copies, and the claude-cli path now edits through OpenClaw's MCP `edit` tool, whose result records are about 650 characters with no file echo. With this PR a tool result costs its id plus 32 characters. Changes: production +74/-57 (net +17) in `cli-output-stream-limits.ts` and `cli-output-stream.ts`; tests +81/-89 (net -8); docs updated. Merge danger: two-way door, a revert restores the old accounting; no state or config is written. Blast radius: Claude CLI turns only. If the accounting were too loose, a misbehaving CLI could stream more discarded frames before the limits stop it (bounded by about 254,000 small frames per turn). Thanks @Terwox for the measured report in #159929, @Trinity-AI-Coder for #186967, and @slatem for the follow-up reports. Co-authored-by: Ayaan Zaidi <[email protected]>
Root cause: src/agents/cli-output-stream-limits.ts:232 (`chargeClaudeStreamJsonLine`) charged every Claude frame the parser discards: each ordinary frame counted toward the 20,000-frame limit, and assistant snapshots, tool-result records, block starts, message starts and status records were charged their whole envelope against the 8 MiB budget, so a healthy turn of a few thousand small tool calls ran out of budget it never retained. Fixes #186967 Related: #159929, #192735, #192734 ## What Problem This Solves A long Claude CLI turn that makes many tool calls (a subagent building a repo, a scheduled job editing files) finishes its work, but OpenClaw drops the final reply and reports `CLI JSONL output exceeded 20000 lines` or `CLI JSONL output exceeded 8388608 characters`. The work is on disk; the requester sees a failure. ## User Impact User impact: Claude CLI turns with thousands of tool calls keep their final reply. The limits still stop turns that retain more than 8 MiB of text, thinking or tool input, and turns that stream a large volume of discarded output. ## Why This Change Was Made The two budgets were meant to bound what the parser keeps, but they counted stream volume. Every tool call costs about five frames of envelope metadata (message ids, uuids, timestamps, usage, tool-result metadata) that the parser throws away, so the limits tripped after roughly 3,300 sequential or 4,900 parallel small tool calls. The budget now charges what the parser keeps (text, thinking and tool-input payloads, assistant content blocks, block headers, tool ids), plus a fixed 32-character allowance for each discounted frame, so 8 MiB still bounds the number of frames. The 20,000-frame limit now counts only frames that leave more than 1 KiB of their raw line uncharged (for example large tool results), which is the parse work the character budget cannot see. The old payload re-serialization for tool results is gone; tool results are charged by their ids. No limit value, config or error text changes. #187125 rewords the limit error; this PR removes the cause instead, so that wording is not needed. ## Evidence Real Claude Code 2.1.322 run by `openclaw agent --local` (built `dist/`, isolated state, `claude-cli/claude-sonnet-4-6`) against a local Anthropic Messages fixture that returns `mcp__openclaw__read` calls of a tiny file, then a final reply. Base `d979dba02457`, candidate `48f1eb236794`. Fixture, harness and captured stdout breakdown are kept with the proof. | Turn | Base | Candidate | | --- | --- | --- | | 3,600 sequential tool calls | fails after 3,338 calls: `CLI JSONL output exceeded 20000 lines` (twice), no reply | `FINAL_REPLY_OK after 3600 tool calls` (twice) | | 7,000 tool calls, 10 per message | fails after about 4,900 calls: `CLI JSONL output exceeded 8388608 characters` (twice), no reply | `FINAL_REPLY_OK after 7000 tool calls` (twice) | | Control: 10 MB of reply text | | still fails with `exceeded 8388608 characters` | Measured from the captured stdout of the same CLI, the budget charge per small tool call drops from about 1,640 characters to about 500, and none of those frames counts toward the frame limit. Tests: `cli-output-framing.test.ts` › "keeps the reply of a turn with thousands of small tool calls" fails on base (`CLI JSONL output exceeded 20000 lines`) and passes here. The control-frame, partial-message, subagent, framing, output-limit, stream and JSONL suites pass (173 tests). On #159929: it no longer happens on main. #166127 already discounts the `tool_use_result` file copies, and the claude-cli path now edits through OpenClaw's MCP `edit` tool, whose result records are about 650 characters with no file echo. With this PR a tool result costs its id plus 32 characters. Changes: production +74/-57 (net +17) in `cli-output-stream-limits.ts` and `cli-output-stream.ts`; tests +81/-89 (net -8); docs updated. Merge danger: two-way door, a revert restores the old accounting; no state or config is written. Blast radius: Claude CLI turns only. If the accounting were too loose, a misbehaving CLI could stream more discarded frames before the limits stop it (bounded by about 254,000 small frames per turn). Thanks @Terwox for the measured report in #159929, @Trinity-AI-Coder for #186967, and @slatem for the follow-up reports. Co-authored-by: Ayaan Zaidi <[email protected]> Stable adaptation: retain stable argument fixtures; include the missing bounded control-frame owner and its contracts. Allocate 294 net regression lines for long-turn completion and rejection controls. Numeric limits and provider routing unchanged. (cherry picked from commit 96ce195) Co-authored-by: RomneyDa <[email protected]>
) Root cause: src/agents/cli-output-stream-limits.ts:232 (`chargeClaudeStreamJsonLine`) charged every Claude frame the parser discards: each ordinary frame counted toward the 20,000-frame limit, and assistant snapshots, tool-result records, block starts, message starts and status records were charged their whole envelope against the 8 MiB budget, so a healthy turn of a few thousand small tool calls ran out of budget it never retained. Fixes openclaw#186967 Related: openclaw#159929, openclaw#192735, openclaw#192734 ## What Problem This Solves A long Claude CLI turn that makes many tool calls (a subagent building a repo, a scheduled job editing files) finishes its work, but OpenClaw drops the final reply and reports `CLI JSONL output exceeded 20000 lines` or `CLI JSONL output exceeded 8388608 characters`. The work is on disk; the requester sees a failure. ## User Impact User impact: Claude CLI turns with thousands of tool calls keep their final reply. The limits still stop turns that retain more than 8 MiB of text, thinking or tool input, and turns that stream a large volume of discarded output. ## Why This Change Was Made The two budgets were meant to bound what the parser keeps, but they counted stream volume. Every tool call costs about five frames of envelope metadata (message ids, uuids, timestamps, usage, tool-result metadata) that the parser throws away, so the limits tripped after roughly 3,300 sequential or 4,900 parallel small tool calls. The budget now charges what the parser keeps (text, thinking and tool-input payloads, assistant content blocks, block headers, tool ids), plus a fixed 32-character allowance for each discounted frame, so 8 MiB still bounds the number of frames. The 20,000-frame limit now counts only frames that leave more than 1 KiB of their raw line uncharged (for example large tool results), which is the parse work the character budget cannot see. The old payload re-serialization for tool results is gone; tool results are charged by their ids. No limit value, config or error text changes. openclaw#187125 rewords the limit error; this PR removes the cause instead, so that wording is not needed. ## Evidence Real Claude Code 2.1.322 run by `openclaw agent --local` (built `dist/`, isolated state, `claude-cli/claude-sonnet-4-6`) against a local Anthropic Messages fixture that returns `mcp__openclaw__read` calls of a tiny file, then a final reply. Base `f7230e5c0acb`, candidate `48f1eb236794`. Fixture, harness and captured stdout breakdown are kept with the proof. | Turn | Base | Candidate | | --- | --- | --- | | 3,600 sequential tool calls | fails after 3,338 calls: `CLI JSONL output exceeded 20000 lines` (twice), no reply | `FINAL_REPLY_OK after 3600 tool calls` (twice) | | 7,000 tool calls, 10 per message | fails after about 4,900 calls: `CLI JSONL output exceeded 8388608 characters` (twice), no reply | `FINAL_REPLY_OK after 7000 tool calls` (twice) | | Control: 10 MB of reply text | | still fails with `exceeded 8388608 characters` | Measured from the captured stdout of the same CLI, the budget charge per small tool call drops from about 1,640 characters to about 500, and none of those frames counts toward the frame limit. Tests: `cli-output-framing.test.ts` › "keeps the reply of a turn with thousands of small tool calls" fails on base (`CLI JSONL output exceeded 20000 lines`) and passes here. The control-frame, partial-message, subagent, framing, output-limit, stream and JSONL suites pass (173 tests). On openclaw#159929: it no longer happens on main. openclaw#166127 already discounts the `tool_use_result` file copies, and the claude-cli path now edits through OpenClaw's MCP `edit` tool, whose result records are about 650 characters with no file echo. With this PR a tool result costs its id plus 32 characters. Changes: production +74/-57 (net +17) in `cli-output-stream-limits.ts` and `cli-output-stream.ts`; tests +81/-89 (net -8); docs updated. Merge danger: two-way door, a revert restores the old accounting; no state or config is written. Blast radius: Claude CLI turns only. If the accounting were too loose, a misbehaving CLI could stream more discarded frames before the limits stop it (bounded by about 254,000 small frames per turn). Thanks @Terwox for the measured report in openclaw#159929, @Trinity-AI-Coder for openclaw#186967, and @slatem for the follow-up reports. Co-authored-by: Ayaan Zaidi <[email protected]>
Related: #150132, #153545
What Problem This Solves
A tool-heavy Claude CLI turn can lose its final reply with
CLI JSONL output exceeded 8388608 characterseven though most of those characters are discarded tool-result payloads. Claude supplies a preview inmessage.contentand echoes full output intool_use_result; the parser hands payloads to consumers and keeps only the tool ID.Charge pure tool-result records for retained IDs, metadata, unknown fields, whitespace and frames, but discount a conservative lower bound of the discarded payloads' wire size. Numbers count as one character during re-encoding so compact wire literals cannot erase retained charges. Mixed records and payloads too deep to re-serialize keep raw accounting. Per-line limits, ordinary frame limits, deadlines, auth, public APIs and model-facing text are unchanged.
Preserves @RTapiador's three original commits. Simplification removes temporary block/map/spread arrays and skips redundant child-payload measurement. Regression coverage is consolidated into the existing framing owner rather than adding a duplicate suite.
Evidence
Inspectable Linux shipped-entry output and controls, exact candidate
47d7ecf0b49fd600b346021176b4a04947978903versus main573fd8c1f005293d662890b7aad888ad7643edf5:openclaw agent exec, bundled Anthropic plugin, native Claude Code 2.1.288, Node 24.22.1 secretless Linux Docker. Synthetic managed profile and fix(agents): show CLI tool activity in session tail and trajectory exports #188069 trusted-CA CONNECT route to a local Claude protocol fixture; no paid provider key or TLS verification bypass.execcalls, each emitting 120,000 characters of line-oriented filler under default limits. This is a character count, not a claimed tokenizer measurement.Merge danger
Two-way door: revert restores the old accounting; no storage/configuration/schema or public API migration. Blast radius is Claude stream-json tool-result accounting. An excessive discount could weaken retained-output bounds, so only pure tool-result payloads qualify and the line/frame, mixed-record, metadata, padding and conservative-number guards remain active. Custom plugin-claimed records bypass the discount and retain full raw charging.