Skip to content

fix(agents): keep Claude CLI replies after many large tool results - #166127

Merged
obviyus merged 4 commits into
openclaw:mainfrom
RTapiador:fix/cli-stream-retained-budget
Nov 2, 2026
Merged

obviyus merged 4 commits into
openclaw:mainfrom
RTapiador:fix/cli-stream-retained-budget

Conversation

@RTapiador

@RTapiador RTapiador commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Related: #150132, #153545

What Problem This Solves

A tool-heavy Claude CLI turn can lose its final reply with CLI JSONL output exceeded 8388608 characters even though most of those characters are discarded tool-result payloads. Claude supplies a preview in message.content and echoes full output in tool_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 47d7ecf0b49fd600b346021176b4a04947978903 versus main 573fd8c1f005293d662890b7aad888ad7643edf5:

  • Source-built 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.
  • Fixture requests 72 real MCP exec calls, each emitting 120,000 characters of line-oriented filler under default limits. This is a character count, not a claimed tokenizer measurement.
  • Main 2/2: budget error, empty final reply; 67 large results completed before cancellation. Candidate 2/2: all 72 tools completed with zero failures and final reply delivered; native full-result payloads totaled 8,749,800 encoded characters per run.
  • Short runs pass 2/2 per build unchanged. Retained-ID negative controls still hit the unchanged budget 2/2 per build. Plugin-claimed tool records still charge full raw payload/padding in focused controls.
  • Focused parser suites 69/69, changed TypeScript lint clean; identical discarded-text regression fails on main. Numeric re-encoding, mixed records, metadata, padding, raw lines, frames, deep fallback, child attribution and retained snapshots remain covered.
  • Whole PR delta: production +43/-1 (44 gross), tests net −19, docs +3.

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.

@clawsweeper

clawsweeper Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: M labels Oct 6, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 6, 2026
@clawsweeper

clawsweeper Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

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

  • Before: The supplied main runs stop after 67 large results with the 8,388,608-character budget error and no final reply.
  • After: Both exact-head runs complete all 72 tools without failures and deliver FINAL_REPLY_166127.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused, worthwhile repair with exact-head shipped-entry before/after evidence, meaningful negative controls, successful CI gates, and no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Exact-head output exercises the changed accounting through openclaw agent exec, the bundled Anthropic plugin, native Claude Code 2.1.288, and real MCP exec calls in isolated Linux Docker: both 72-call candidate runs deliver the final reply, both main runs fail, and short-turn plus oversized retained-ID controls preserve expected behavior.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Long Claude CLI turns can finish useful tool work but lose their final reply because discarded result payloads exhaust the output budget.
Reason: The demonstrated failure remains on main, and collaborator discussion supports this narrowly scoped repair while keeping broader budget recovery separate.

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
Reviewed head: 47d7ecf0b49fd600b346021176b4a04947978903

Before merge

None.

Findings

None.

Agent review details

How this fits together

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

Technical review

Best 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

  • Partial-message and child-message accounting keeps the original intent (d1470c8: Discarded child messages should not consume the parent's retained-output budget; retained child-attributed deltas must remain bounded.)
  • Ordinary tool-result charging changes intended behavior with a stated reason (unknown: Earlier symbol-history lookup encountered an unavailable promisor blob, preventing verification of the original budget introduction; current source and merged repair descriptions establish the existing bounded-output contract.)
  • Media normalization and tool-argument regressions keeps the original intent (fix(cli): normalize echoed binary tool outputs #128699: Normalize duplicated binary echoes before accounting while preserving tool metadata; the consolidated tests retain media expectations and all four argument-assembly cases.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • xingzhou: Raw commit 12302d7 adds src/agents/cli-output-stream-limits.ts:83 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 12302d7fa133; files: src/agents/cli-output-stream-limits.ts)
  • Peter Steinberger: Raw commit 436a01a adds src/agents/cli-output-stream-limits.ts:12 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 436a01a2e3e4; files: src/agents/cli-output-stream-limits.ts)

PR surface

Source +42, Tests -19, Docs +3. Total +26 across 4 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 43 1 +42
Tests 2 105 124 -19
Docs 1 8 5 +3
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 156 130 +26

Review metrics

Metric Value Why it matters
Production versus test LOC Production +43/-1; tests +105/-124 Necessary production growth stays in the existing accounting owner, while consolidation preserves distinct regressions with net test reduction.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: Real tool-heavy Claude CLI turns lose their final reply after useful work has already executed.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (7 earlier review cycles)
  • reviewed 2026-10-06T13:43:21.249Z sha daa92558d0901eea35f1e2fa2d8d42b99d60eb71 :: needs real behavior proof before merge. :: [P2] [P2] Charge complete start-block tool inputs | [P2] [P2] Bound retained tool IDs and names
  • reviewed 2026-10-06T14:42:58.745Z sha 5b2f99b6e34fe23d748c3792fc253e1893d33e53 :: blocked before merge. :: [P2] [P2] Charge tool metadata while blocks are still pending | [P2] [P2] Bound collection growth from empty retained fragments
  • reviewed 2026-10-06T15:33:01.230Z sha 9cb6b49cc558131b4bd06d895e27b835ef2d8560 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-07T11:18:47.647Z sha 269665d89fd6597cab40b653187574fc8f46a4ed :: needs real behavior proof before merge. :: [P2] [P2] Charge metadata independently of payload reserialization | [P2] [P2] Keep the mixed-record control below the raw-line limit
  • reviewed 2026-10-07T12:14:57.138Z sha 9ab7531564b79d431c9c892595fea5d9cb83342e :: needs changes before merge. :: none
  • reviewed 2026-10-20T20:03:09.299Z sha 9ab7531564b79d431c9c892595fea5d9cb83342e :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-22T01:39:10.327Z sha 42753beb4e09724d496c2ec507d2ec51e107e8ee :: needs maintainer review before merge. :: none

Reviewed November 2, 2026, 6:12 PM ET / 23:12 UTC (Revision 8).

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 6, 2026
@obviyus

obviyus commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

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!

@RTapiador RTapiador changed the title fix: long Claude CLI turns lose their final reply once the stream passes 20,000 lines or 8 MiB fix(agents): keep Claude CLI replies after many large tool results Oct 7, 2026
@RTapiador
RTapiador force-pushed the fix/cli-stream-retained-budget branch from 9cb6b49 to 269665d Compare October 7, 2026 11:11
@GoatInAHat

Copy link
Copy Markdown
Contributor

Reviewed the introduced accounting change at 42753beb4e09724d496c2ec507d2ec51e107e8ee against our independently observed 8 MiB reply-loss case on 2026.10.8. We are adopting this repair rather than opening a competing PR.

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.

RTapiador and others added 3 commits November 2, 2026 22:20
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
@RTapiador
RTapiador force-pushed the fix/cli-stream-retained-budget branch from 42753be to cbe785d Compare November 2, 2026 21:34
@RTapiador

Copy link
Copy Markdown
Contributor Author

Rebased onto main @ 232147c49. The head is now cbe785dee.

main had reworked the same code, so the rebase hit conflicts in four files:

  • cli-output-stream-limits.ts / cli-output-stream.ts. main moved the per-line charge into chargeClaudeStreamJsonLine (fix(agents): preserve Claude parent replies after discarded subagent output #184352), which already picks the single decoded record once. The tool-result measurement now lives there as a private helper, between the subagent and partial-message charges and media normalization: subagent ?? partial ?? toolResult ?? normalized. It is still measured before normalization rewrites the record. cli-output-stream.ts is unchanged from main, so my line-cap refactor (42753beb4) was redundant and is dropped.
  • cli-output-framing.test.ts. main introduced a toolResultFrame helper. The oversized-budget case still uses retained assistant snapshots, as before; the helper stays for the image cases.
  • docs/gateway/cli-backends.md. Merged both paragraphs: the tool-result payload discount, plus main's fixed allowance for discarded subagent records.

One test from main needed an update. In cli-output-subagent-budget.test.ts, the "still bounds the same volume in the parent conversation" control sends tool-result-only records without child attribution and expects the 8 MiB error. With this PR those payloads are discounted, so I added a text block to each record in that turn (cbe785dee). Parent records stay on raw accounting, and only child attribution separates the two turns. All four cases pass with this branch and with main's parser.

Checks (Node 24, macOS):

Check Result
vitest: src/agents/cli-output*, src/agents/cli-runner* and src/agents/cli-runner/ (no e2e), src/agents/cli-backends.test.ts, src/plugins/cli-backends.runtime.test.ts 100 files, 1,313 tests passed
cli-output-tool-results.test.ts against main's parser the two main cases fail with the budget error, 5 pass
Replay of the raw Claude Code 2.1.288 capture (72 results of about 120 KB) main @ 232147c49: budget error after 66 of 72, reply lost. This branch: 72 of 72, DONE
tsgo:core exit 0
check:assertion-safety, check:line-cap-ratchet, check:test-timeout-race-ratchet, check:test-mock-exports OK
oxfmt --check, git diff --check; lint:core reports nothing in the changed files clean

lint:core still fails on max-lines in files this PR does not touch, and it does the same on main. I did not repeat the shipped claude-cli backend run from the description. The parser replay covers the same scenario, and the accounting logic is unchanged apart from where it is called.

The branch is up to date with main. CI needs to run again on the new head.

@obviyus

obviyus commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator

Linux shipped-entry proof on the exact head

Candidate 47d7ecf, pinned main 573fd8c. Both were source-built and exercised through ordinary openclaw agent exec → bundled Anthropic plugin → native Claude Code 2.1.288 → OpenClaw MCP exec in secretless Node 24.22.1 Linux Docker.

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 api.anthropic.com:443, a task CA authenticated the local protocol fixture, and the fixture verified synthetic authorization. No TLS verification bypass, real provider key, operator state or paid provider access was used.

The fixture issued 72 sequential tool calls. Each real shell command printed 120,000 characters (1,500 lines of 79 = characters plus newline), matching the contributor's shipped-backend workload. This is a character count, not a claimed tokenizer measurement. Native Claude supplied the actual tool-result records and 2 KB provider previews; no JSONL parser replay or fake CLI executable was used. Limits were left at their defaults.

Long run                        main #1      main #2      candidate #1   candidate #2
CLI exit                           1            1               0              0
status                           error        error             ok             ok
successful large tools            67           67              72             72
final reply delivered             no           no              yes            yes
native full-result payload chars  8,142,815    8,142,815       8,749,800      8,749,800

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 FINAL_REPLY_166127 in the ordinary CLI result envelope.

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

  • Short run: two identical large tool calls; main and candidate each passed 2/2, delivered the final reply, and had zero failures. Native payload accounting was identical: two results totaling 243,050 encoded characters.
  • Retained metadata: a synthetic tool ID of 3,000,015 characters retained by the native stream exhausted the unchanged 8 MiB turn budget on both builds, 2/2 each. Each emitted a native tool-result record and returned the expected budget refusal with no final reply. This is an expected negative control, not a failed repair case.
  • Claimed/kept tool records: focused framing controls still charge full raw bytes when a custom plugin parser claims the tool-result record, before dispatch. The two cases cover large payloads and raw padding. Raw-line, 20k-frame, mixed-record, unknown-metadata, ID, padding, numeric re-encoding, deep-payload fallback, subagent and retained-assistant controls also passed.

Focused checks and simplification

69/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.

@obviyus

obviyus commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 2, 2026
@obviyus
obviyus merged commit 8828c59 into openclaw:main Nov 2, 2026
124 of 125 checks passed
@obviyus

obviyus commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator

Landed in 8828c59. Thanks @RTapiador. Long tool-heavy Claude CLI runs no longer lose their final reply.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 3, 2026
…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]>
obviyus added a commit that referenced this pull request Nov 17, 2026
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]>
RomneyDa added a commit that referenced this pull request Nov 17, 2026
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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 18, 2026
)

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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. triage: blank-template Candidate: PR template appears mostly untouched.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants