Repository navigation
fix(agents): meter the CLI turn budget on retained output and stop the child when it trips - #85
Merged
Merged
Conversation
…utput A long tool-heavy Claude CLI turn trips the per-turn stream-json budget on wire bytes the parser never retains: tool_result text arrives twice (message copy and tool_use_result echo), is handed to onToolResult, and is dropped, yet every byte is charged against the 8 MiB turn budget. Four 1.5 MB reads discard the final reply with "CLI JSONL output exceeded 8388608 characters". Fails on current code at the getErrorText() assertion. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e child on parse failure A Workboard node ticket runs as one long Claude Code CLI turn. After ~18 min of tool-heavy work the Gateway discarded its report with "CLI JSONL output exceeded 8388608 characters", tool tracking froze at tool:Edit:started, and the child kept running blind until exit. Root cause: the per-turn budget in cli-output-stream.ts metered wire bytes (every stdout line, with discounts for partial deltas and echoed media), while the parser retains only text, reasoning, result text, and tool bookkeeping. Tool results are handed to onToolResult and dropped, yet each was charged twice (message copy and tool_use_result echo), as were full assistant snapshots and subagent traffic. The budget dates from 02c4ea5, when the retired claude-live-session kept every raw line; every later fix (openclaw#119488, openclaw#128699, openclaw#153545) carved out one more record type instead of charging what is kept. Fix: - One ledger in the parser charges what it appends to turn state: streamed deltas, custom text/thinking events, item texts, result text, Gemini content, tool ids and names, pending tool-input JSON, and native thinking. The tool and thinking trackers report their own retention through a `retain` callback. Each append also pays a fixed 32-char overhead so floods of one-character appends stay bounded (string pieces and map entries cost memory the payload alone does not show). - Records the parser hands off or drops only meet the per-line limit. `measureClaudePartialMessage`, the omitted-raw arithmetic, and the per-chunk charge for non-Claude dialects are removed; those dialects retain text through the same ledger. The media normalizer stays because it keeps base64 out of tool-result events and the transcript mirror, but it no longer re-serializes the record for accounting. - maxTurnLines is removed. It guarded per-line retention that no longer exists: blank, system, and empty frames retain nothing, and per-tool bookkeeping is now charged by content. A long turn with subagent traffic was the next way to hit it. - execute-process.ts owns an output-rejection AbortController. Any parser failure stops the child promptly through the existing cancellation of each path (supervisor cancel, node abort which sends node.invoke.cancel, plugin turn abort) and reports the parser failure as the "format" failover. A caller abort that coincides with it still wins. - Limit messages now say the retained output exceeded the Gateway parse budget, the CLI was stopped, and work on the node or worktree may exist. Tests: - cli-output-framing: 12 MB of handed-off tool results keep the reply (committed first, failed on the old budget); the oversized-text case now uses streamed deltas because a finished assistant snapshot is never a retained delta; the wire-byte cases (plugin-claimed media bytes, whitespace padding, 20,000-line cap) are rewritten or removed because the budget no longer meters wire bytes. - cli-output-partial-messages: retained delta payloads still trip; dropped input_json_delta without an open block does not; the tiny-delta flood is bounded by the per-append overhead; frame-limit and padding cases removed. - execute.supervisor-capture: a budget trip cancels the child ("manual-cancel") and rejects with the new message; without the stop the test times out at 120 s. - execute.pending-cancellation: the fixture aborts in the same tick as the unrelated parser failure, since the failure now stops the child itself. Cost (--maxWorkers=1): framing + partial-messages 4.6 s wall, supervisor-capture 37.5 s wall (18 s compiled-worker preparation, test bodies 4%), pending-cancellation 12.5 s wall. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…CLI state The retained ledger is cumulative, but the parser frees pending tool input at content_block_stop and native thinking at each message start without a refund, so a turn of 30 Write calls (9 MB streamed, 300 KB live) and a turn of 20 reasoning messages (1 MB live) both trip the 8 MiB budget. Tool input carried on content_block_start and names from custom toolResult events are retained without any charge, so 40 unterminated 300 KB starts and ten 1 MB names pass silently. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tput The retained ledger was cumulative, but the parser frees state during the turn without a refund: pending tool input at content_block_stop and native thinking at each message start. With --include-partial-messages every Write or Edit input streams as input_json_delta, so a long tool-heavy turn tripped the 8 MiB budget while holding a few hundred KB. Two retentions were also uncharged: tool input carried on content_block_start and tool names from custom toolResult events. - cli-output-stream-limits.ts owns a RetainedOutputLedger: retain/release for turn-lived state and scope() for lifetimes refunded as one unit. The per-append overhead is paid into the scope and refunded with it. - Each pending tool block owns a scope (id, name, serialized start input, streamed input JSON), refunded at content_block_stop, when a start replaces the index, or at the next message_start, since block indexes restart per message and an unstopped block can only be abandoned. - The thinking tracker owns a message scope covering both copies it keeps (per-index block text and the message aggregate), refunded on reset. - The tagged-reasoning router charges what it holds back and refunds on settle. The stream's message scope covers the snapshot diff base and tagged reasoning, refunded at the next message start and at a result, so a reply streamed in one message and repeated by the result holds two copies (reply text, result text), not three. Commentary pending text has its own scope, refunded on flush. Reply text is charged where appended. - Tool names are charged once per id via retainToolName, replacing a prior name refunds it; custom toolResult names go through the same path. - The limit message names the lost final reply and work the CLI already did (files, commits) for local and node runs alike. Tests: the four reproductions pass; the bounded-payload cases use 2 MB payloads with a bounded push count since text and thinking are now held twice within a message; a new case pins the 2x headroom at the result (fails if the message copy is kept through the result). Cost (--maxWorkers=1): partial-messages 3.4 s wall, framing 3.2 s wall, pending-cancellation 30.6 s wall (compiled-worker transform; comment only). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…reply Co-Authored-By: Claude Opus 5.5 <[email protected]>
Streamed text deltas and message boundaries from subagent records (parent_tool_use_id set) were treated as the parent's: their text joined the reply and was charged to the turn budget as kept reply text, and a subagent message_start reset the parent's snapshot base. Ignore them like the snapshot path already does. Also keep the append overhead constant module-private. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This was referenced Nov 21, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
A Workboard node ticket runs as one long Claude CLI turn. On 2026-10-15 at 19:03:55 the UFH-06 ticket failed after 18 minutes of normal, tool-heavy work with this error:
Its final reply was lost and the card was blocked. The work itself was already committed on the node.
The stream-json parser (
src/agents/cli-output-stream.ts) charged its 8 MiB per-turn budget on wire bytes, but it keeps only the reply and thinking text and tool bookkeeping. Every record it reads and immediately drops still counted against the budget:tool_use_resultecho;Why 8 MiB: it dates from
02c4ea5cf4e, when the live session stored every raw line. The streaming parser no longer does. Since then each upstream fix carved out one more record type: media in openclaw#128699, partial deltas in openclaw#153545.On a trip, nothing stopped the run.
pushreturned early from then on, nothing stopped the child, and the CLI ran blind until it exited. Only then did the error surface, as aformatfailure.Why node turns hit it now: fork #69 forwards all node stdout to the Gateway, which exposed node turns to this budget.
Solution
Count what the parser keeps.
createRetainedOutputLedgerincli-output-stream-limits.tskeeps a running total of what the parser currently holds.retainadds to it and scopes release their bytes when that state is freed. Over 8 MiB is a runaway.measureClaudePartialMessage, the omitted-raw arithmetic,maxTurnLines, and the per-chunk charge for other dialects. Their text is counted through the same ledger.Stop the run on a parser failure.
execute-process.tsaborts as soon as the parser reports an error, and the abort is wired to each execution path:supervisor.cancel;stopSignal, which sendsnode.invoke.cancel;cancelRunthe reply backend uses.A caller abort that lands at the same time still wins.
Message: "CLI turn retained output exceeded the 8388608-character Gateway parse budget; the CLI was stopped and its final reply was lost. Work the CLI already did (files, commits) may exist; check it before re-running."
Subagent stream events stay out of the parent reply.
stream_eventtext deltas and message boundaries withparent_tool_use_idwere treated as the parent's. Their text joined the reply ('Hello\n\nSUBAGENT') and was counted as kept reply text. A subagentmessage_startalso reset the parent's snapshot base. They are now ignored, as the snapshot path already did.Evidence
e00e88eece3, a turn whose dropped tool results exceed 8 MiB:expected 'CLI JSONL output exceeded 8388608 cha…' to be null.55c4717ecb8: 4 failures. Tool input was not released at block stop, thinking was not released at the next message, and both the input on a tool block's start and custom tool names were kept uncounted.0da9993ae27:expected 'Hello\n\nSUBAGENT' to be 'Hello'.pnpm test src/agents/cli-output-stream.test.ts src/agents/cli-output-framing.test.ts src/agents/cli-output-partial-messages.test.ts src/agents/cli-output-jsonl.test.ts src/agents/cli-output-events.test.ts --maxWorkers=1: 110 passed, about 3 s wall.execute.supervisor-capture.test.tschecks that a budget trip stops the child and reports the budget message. A mutation check with the abort removed makes it hang, which was the old run-blind behavior.pnpm test src/agents/cli-runner src/agents/cli-output-{framing,partial-messages,stream,jsonl,events}.test.ts src/gateway/node-claude-skill-runtime.test.ts --maxWorkers=2passes 780 tests at the final head.pnpm tsgois clean.oxfmtandgit diff --checkare clean.First review: it found the tool-input and thinking releases missing, plus the two uncounted kept paths. Those are fixed in
ecfe40344ae.Second review: it found no correctness defect in the ledger. Its probes:
Its subagent finding is fixed in
4e2a612d90d.Known limits and follow-ups (not in this PR)
formatfailures still go through model fallback. With fallback candidates configured, a stopped turn would be replayed on the next model, side effects included. Workboard node tickets pin an explicit model, so they are strict: the live failure loggednext=none.toolArgsByCallIdinexecute-events.tskeeps args for tool starts that never get a result. The old wire budget capped that indirectly.openclaw/openclaw. The fix should be offered there as well.Impact
Long tool-heavy CLI turns, such as Workboard node tickets, no longer lose their reply. A real runaway now stops the CLI immediately instead of letting it run blind, and subagent text no longer appears in the parent's reply.
🤖 Generated with Claude Code