Repository navigation
fix: preserve Claude CLI replies after long streamed turns - #153545
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. Reviewed October 6, 2026, 7:31 PM ET / 23:31 UTC (Revision 7). ClawSweeper reviewWhat this changesThe PR changes Claude CLI output accounting to discount recognized streaming envelopes while bounding payloads and frame overhead, with parser regressions and documentation. Merge readiness✅ Ready for maintainer review The fix remains necessary: current main still charges repeated streaming envelopes, and the merged neighboring fixes address distinct failures. Exact-head runtime evidence supports the patch, and no blocking correctness finding remains. Priority: P1 Review scores
Verification
How this fits togetherOpenClaw's CLI parser receives streamed output from the Claude backend and converts it into reply text, tool events, and session information. Its output budgets determine whether the completed reply reaches the normal delivery pipeline. flowchart TD
A[Claude CLI output] --> B[Bound individual lines]
B --> C[Recognize delta records]
C --> D[Charge payload and frame overhead]
C --> E[Charge ordinary records fully]
D --> F[Parse replies and tool events]
E --> F
F --> G[Reply delivery or limit error]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +87, Tests +166, Docs +5. Total +258 across 4 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Technical reviewBest possible solution: Keep conservative payload and frame bounds while allowing legitimate Claude streamed turns to deliver their completed replies through the existing parser. Do we have a high-confidence way to reproduce the issue? Yes: current main deterministically rejects sufficiently many partial-message frames, and the supplied exact-head backend run demonstrates baseline refusal followed by candidate reply delivery. This read-only review did not execute target code. Is this the best way to solve the issue? Yes for the reported envelope-overhead defect: the patch repairs the existing accounting owner without adding configuration or changing ordinary-record limits. Broader retained-memory proposals address additional cases separately. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 45228e1aeed6. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (6 earlier review cycles)
|
|
Related but not superseded by #154874. This PR addresses long streamed Claude turns losing their final reply when parser/output budgets are exhausted. #154874 addresses delivery of completed result segments while native background work continues. These are distinct failure mechanisms. Keep this PR open for independent review; do not close it. |
|
Landed in 12302d7. Thanks @zhangguiping-xydt! Verified with real Claude Code 2.1.292 through the OpenClaw backend: main loses the final reply at 20,000 frames, this delivers the full 21,024-character reply, and a tiny-delta flood is still rejected within the 8 MiB budget. |
…penclaw#153545) Charge recognized nonempty text, thinking and tool-input stream deltas for their encoded payload plus a fixed per-frame allowance, so long streamed Claude CLI turns keep their final reply and tool arguments while the 8 MiB budget still bounds tiny-delta floods. Ordinary records keep the 20,000-frame limit and the per-line limit is unchanged. Closes openclaw#150132. Co-authored-by: Ayaan Zaidi <[email protected]>
…153545) Charge recognized nonempty text, thinking and tool-input stream deltas for their encoded payload plus a fixed per-frame allowance, so long streamed Claude CLI turns keep their final reply and tool arguments while the 8 MiB budget still bounds tiny-delta floods. Ordinary records keep the 20,000-frame limit and the per-line limit is unchanged. Closes #150132. Co-authored-by: Ayaan Zaidi <[email protected]> (cherry picked from commit 12302d7)
…text (review feedback) ClawSweeper Revision 5 (head bf578b0) raised three [P2] defects, all in `src/agents/cli-output-stream.ts`. All three were reproduced before fixing and measured after; two of them were failing tests already on the branch, including one that exists on `origin/main`. 1. Charge blank and hook-handled Claude frames to the line budget. Moving `chargeLine()` below the blank-line and custom-parser returns exempted ordinary frames from the line odometer, breaking the documented bounded-frame contract (`docs/gateway/cli-backends.md`). `push("\n".repeat(20001))` spent no line budget at all. Both charges now run through one accountant (`createOrdinaryClaudeLineAccountant`) for blank frames, lifecycle frames and custom-parser frames alike; recognized partial-message deltas keep their line exemption and are still charged for characters. Base-fail: `counts actual blank Claude frames without invoking hooks or inventing a finish frame` (an `origin/main` test) and the branch's own `keeps a finished Claude turn that outgrew the line-count budget` both failed at the reviewed head. Both pass now. 2. Track observed output separately from ordinary-frame charges. `getOutput()` used `turnBudget.lines`, which counts only ordinary built-in records, where `origin/main`'s `rawLines` counted every observed frame. A recognized `text_delta` followed by `finish()` with no result envelope assembled its text and then returned null, never reaching the partial-text fallback. Hook-handled text had the same bug. The budget now keeps an independent `observedLines` fact, charged for every frame. 3. Preserve pre-budget text in a tool-split reply. Once a budget is spent the parser stops assembling, so the closing message is never streamed and `preferStreamedClaudeTextOverResult` cannot see it: the envelope's text replaced the reply text already assembled. Reply selection is now `resolveCliTerminalReplyText`, which on a truncated turn keeps the preserved candidate as a bounded prefix while a tool split still connects it to the answer (a tool outstanding, or a split already applied), and joins it to the envelope with the normal message separator. A draft with no tool split stays superseded exactly as on an unbudgeted turn, and the in-flight message is dropped when the envelope restates it, so a budget spent mid-message cannot duplicate text. The `origin/main` contract at `cli-output-stream.test.ts:364` ("Before.\n\nDONE") is unchanged. Proof harness repaired and extended. `overflowRawCharBudget` counted streamed bytes, but after openclaw#153545 the odometer charges retained characters, so the loop stopped ~96 KB short and `recovered-raw` failed its own truncation assertion at the reviewed head. It now streams until the parser reports exhaustion. Four new scenarios: `tool-split-silent`, `tool-split-commentary`, `superseded-draft` and `discounted-output-seen`. 8/8 pass. Two helpers moved into the existing sibling `cli-output-stream-budget.ts` to keep `cli-output-stream.ts` under the 700-line cap; no coverage was trimmed and no `max-lines` suppression was added. No test that exists on `origin/main` was deleted or weakened. Validation: `pnpm check:changed` exit 0, all 36 lanes (linuxbrew git 2.55 for the ratchet lanes). `pnpm deadcode:unused-files` 0 entries on both the production and full-tree scans. `pnpm tsx scripts/proof-cli-stream-turn-budget.ts` all assertions passed. Beads: openclaw-cy3n Co-Authored-By: Claude <[email protected]>
…e child when it trips (#85) * test(agents): reproduce Claude CLI turns failing on handed-off tool output 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]> * fix(agents): meter the CLI turn budget on retained output and stop the 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]> * test(agents): reproduce retained-budget trips on freed and uncharged 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]> * fix(agents): meter the CLI turn budget as a live gauge of retained output 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]> * test(agents): reproduce subagent stream text leaking into the parent reply Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(agents): keep subagent stream events out of the parent CLI reply 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]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
…penclaw#153545) Charge recognized nonempty text, thinking and tool-input stream deltas for their encoded payload plus a fixed per-frame allowance, so long streamed Claude CLI turns keep their final reply and tool arguments while the 8 MiB budget still bounds tiny-delta floods. Ordinary records keep the 20,000-frame limit and the per-line limit is unchanged. Closes openclaw#150132. Co-authored-by: Ayaan Zaidi <[email protected]> (cherry picked from commit 12302d7) (cherry picked from commit 3cbec4f) Co-authored-by: RomneyDa <[email protected]>
Closes #150132
What Problem This Solves
Fixes missing final replies after long Claude CLI turns, even when the actual streamed content fits the output budget.
User Impact
Long streamed turns can deliver their completed reply and preserve tool arguments. The individual-line limit, 20,000-frame limit for ordinary records, and full accounting for unknown fields and padding remain unchanged.
Why This Change Was Made
Recognized nonempty text, thinking, and tool-input deltas are charged for encoded content plus a fixed per-frame cost instead of their repeated protocol envelopes. Ordinary records keep the existing limits. The fixed charge also bounds tiny-delta floods.
Thanks to @zhangguiping-xydt for the fix and @methylester for the report. The contributor's commit is retained; current main was merged because it changed the affected files.
No overlap with Pash/Sarah changes.
Evidence
Verified in isolated Linux Docker on candidate
a08d9c8e03bc22490383c624e53bc49adb1f98bd, against main2c620bbfe84c17fce0a684e8fee7a261310dab19:CLI JSONL output exceeded 20000 lines; candidate delivers the 21,024-character final reply includingP153545_FINAL_DELIVERED.floor(8388608 / 36) = 233016frames fit. Oversized single lines remain rejected; ordinary records fail at frame 20,001; unknown-field and padding controls exhaust the unchanged 8 MiB budget.pnpm tsgopassed. Candidate runtime build passed.openai/gpt-5-mini, reasoning low, 4,096 output-token budget; returnedP153545_LIVE_OK(16,411 input / 76 output tokens). Temporary credential and credentialed container removed.Hosted CI and ClawSweeper are evaluated separately on the exact published head.