Repository navigation
fix(agents): Claude CLI turns hit the 20,000-line limit when Claude Code adds stream frame metadata - #186085
Conversation
…aude Code - Current Claude Code (seen on 2.1.296 and 2.1.310) adds api_message_id to every stream_event and thinking_display to thinking frames; measureClaudePartialMessage rejected both as unknown keys, so no partial frame received the openclaw#153545 discount. - Accept api_message_id (string, up to 64 chars) on any recognized delta and thinking_display (string, up to 32 chars) on thinking_delta frames as bounded frame metadata beside uuid, session_id and parent_tool_use_id. - Unknown keys, oversized or non-string metadata, thinking_display on other delta types, empty deltas, the per-line cap, the 20,000 ordinary-line limit and the 8 MiB budget are unchanged. - The per-frame charge comment gives the exact frame bound: 233,016 frames.
|
🦞👀 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 changesAccept bounded Claude Code frame metadata so streamed text, thinking, and tool input retain their existing output-budget discount. Example: A Claude Code 2.1.310 Gateway turn streams 20,100 text deltas and 100 thinking deltas.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep this PR open: it fixes a demonstrated Claude CLI failure still present on current main, with no introduced correctness or security findings; current-head CI remains pending. Priority: P1 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe CLI backend sends Claude Code stdout through the JSONL parser, which accounts for output limits before projecting replies, thinking, and tool events. flowchart LR
A[Gateway agent turn] --> B[Claude CLI backend]
B --> C[Claude Code stdout]
C --> D[JSONL framing and budget accounting]
D --> E[Reply and tool event projection]
E --> F[Completed agent response]
Technical reviewBest possible solution: Restore recognition of the observed bounded metadata in the existing accounting owner while retaining all current output limits. Do we have a high-confidence way to reproduce the issue? Supplied shipped-command output reproduces the base failure and candidate success, and obviyus independently repeats the Gateway A/B with official Claude Code; current-main source retains the same rejection mechanism. Is this the best way to solve the issue? This is a focused repair of the existing recognition boundary, preserving the earlier accounting design without raising budgets or adding operator settings. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against d552a038cf27. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +19, Tests -5. Total +14 across 3 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 HistoryReviewed October 27, 2026, 1:26 PM ET / 17:26 UTC (Revision 3). |
Independent real Claude CLI + built Gateway proofPinned main The shipped agent command dispatches a real Gateway turn with
The native CLI protocol shape was separately captured directly from that same official executable against a short Messages fixture with the same thinking/text event types. Actual stdout contains For example, the real CLI emits: {"type":"stream_event","event":{"index":0,"delta":{"type":"thinking_delta","thinking":"synthetic thought"},"type":"content_block_delta"},"session_id":"<synthetic-session>","parent_tool_use_id":null,"uuid":"<synthetic-event>","thinking_display":"updates","api_message_id":"msg_000000000000000000000001"}No live Anthropic model/generation or 8 MiB production failure is claimed. The fixture deliberately isolates the ordinary-line accounting defect. It does not exercise a multi-tool workload; the contributor's existing tool-heavy proof remains separate. Focused simplification and checksHead Observed in the isolated container: 79 tests passed across three files ( |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Parser-budget ratchet repair —
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
…ode adds stream frame metadata (openclaw#186085) fix(agents): keep Claude CLI stream frame metadata from tripping the 20,000-line limit Claude Code now adds api_message_id and thinking_display metadata to its stream frames. The Claude CLI output budget didn't recognize those frames, so their streamed deltas were counted in full and long replies hit the 20,000-line cap and failed without a final answer. The budget now recognizes the metadata and applies its existing discounts. Evidence: official Claude Code 2.1.310 (not a stub) through built Gateway turns with a local Messages fixture. On main a long reply failed at the 20,000-line cap with no final answer (twice); with this change the exact 20,118-character reply completed (twice). Short replies work on both refs, and a separate stdout capture confirmed both metadata fields. Details: openclaw#186085 (comment). Production about 29 lines. Thanks @etzelm. Co-authored-by: Ayaan Zaidi <[email protected]>
…lowance - Thinking progress ticks (only estimated_tokens is read), content_block_stop and message_stop frames are charged 32 characters plus padding and skip the ordinary-line limit, like recognized partial frames. - signature_delta and message_delta frames, whose content the parser discards, keep the ordinary-line limit and leave at most 8 KiB of each line uncharged. - Unknown keys at any level, oversized or non-string metadata, invalid indexes, non-numeric estimates and thinking text keep full accounting; the 8 MiB budget, per-line cap and 20,000-line limit are unchanged. - Control frames reuse the partial-frame envelope check (metadata keys and caps from openclaw#186085, block index), now shared in readBoundedStreamEvent. - docs/gateway/cli-backends.md describes the control-frame accounting.
…rames (#185404) * fix(agents): charge discarded Claude stream control frames a fixed allowance - Thinking progress ticks (only estimated_tokens is read), content_block_stop and message_stop frames are charged 32 characters plus padding and skip the ordinary-line limit, like recognized partial frames. - signature_delta and message_delta frames, whose content the parser discards, keep the ordinary-line limit and leave at most 8 KiB of each line uncharged. - Unknown keys at any level, oversized or non-string metadata, invalid indexes, non-numeric estimates and thinking text keep full accounting; the 8 MiB budget, per-line cap and 20,000-line limit are unchanged. - Control frames reuse the partial-frame envelope check (metadata keys and caps from #186085, block index), now shared in readBoundedStreamEvent. - docs/gateway/cli-backends.md describes the control-frame accounting. * test(agents): retire superseded control-frame rows and allocate test growth - cli-output-partial-messages.test.ts: drop the empty thinking progress and signature delta rows that expected full accounting; the control-frame suite covers both shapes with their new charges. - cli-output-control-frames.test.ts: drop the small-frame line-limit cases already covered by the allowance-sized mixed-frame test. - config/test-lines-allocations: record the net test growth of this change.
…rames (openclaw#185404) * fix(agents): charge discarded Claude stream control frames a fixed allowance - Thinking progress ticks (only estimated_tokens is read), content_block_stop and message_stop frames are charged 32 characters plus padding and skip the ordinary-line limit, like recognized partial frames. - signature_delta and message_delta frames, whose content the parser discards, keep the ordinary-line limit and leave at most 8 KiB of each line uncharged. - Unknown keys at any level, oversized or non-string metadata, invalid indexes, non-numeric estimates and thinking text keep full accounting; the 8 MiB budget, per-line cap and 20,000-line limit are unchanged. - Control frames reuse the partial-frame envelope check (metadata keys and caps from openclaw#186085, block index), now shared in readBoundedStreamEvent. - docs/gateway/cli-backends.md describes the control-frame accounting. * test(agents): retire superseded control-frame rows and allocate test growth - cli-output-partial-messages.test.ts: drop the empty thinking progress and signature delta rows that expected full accounting; the control-frame suite covers both shapes with their new charges. - cli-output-control-frames.test.ts: drop the small-frame line-limit cases already covered by the allowance-sized mixed-frame test. - config/test-lines-allocations: record the net test growth of this change.
Related: #185404, #153545, #166127, #159930
What Problem This Solves
Long tool-heavy
claude-cliturns on current Claude Code (seen on 2.1.296 and 2.1.310) fail withCLI JSONL output exceeded 20000 lines, because every streamed token frame is charged as a full ordinary record again. The same overcharge pushes long production turns past the 8 MiB budget (exceeded 8388608 characters); that part is estimated from session transcripts below, not reproduced.User Impact
Agents on the
claude-clibackend can again finish long turns with many tool calls and streamed tool input on current Claude Code instead of stopping at the 20,000-line limit. Text, tool-input and nonempty thinking frames again cost their payload plus 32 characters of the 8 MiB budget instead of their full envelope; empty thinking progress frames andsignature_deltaframes stay fully charged, as before. The limits stay as they are, and no setting is added.Why This Change Was Made
#153545 charges a recognized partial-message frame (
stream_event/content_block_deltawith a text, thinking or tool-input delta) for its payload plus a fixed 32 characters, and keeps the 20,000-line limit for ordinary records only. It recognizes a frame only when every top-level key is known. Current Claude Code (seen on 2.1.296 and 2.1.310) attaches two extra fields to these frames:api_message_idon everystream_event, and the display settingthinking_display("updates") on thinking frames. No frame matches any more, so each 12 to 16 character delta is charged its full envelope of about 300 characters and counts as an ordinary line, which is the accounting #153545 replaced.This change accepts the two fields as bounded frame metadata beside
uuid,session_idandparent_tool_use_id:api_message_idas a string of at most 64 characters on any recognized delta (captured ids are 28), andthinking_displayas a string of at most 32 characters onthinking_deltaframes only, the only delta type that carries it in the captures below. Accepting it only there keeps the recognized shape to what Claude Code sends; any other placement keeps full accounting, like any other unrecognized frame. OpenClaw reads neither field: the parser takes message ids frommessage_start(src/agents/cli-output-stream.ts:521,src/agents/cli-output-events.ts:449), and no other tracked file mentions either name (search under Evidence).Unknown keys, non-string or oversized metadata,
thinking_displayon other delta types, and empty deltas keep full accounting as before, and outer padding is still charged on top of a discounted frame. The per-line cap, the 20,000 ordinary-line limit, the 8 MiB budget and the per-frame charge are unchanged. As with the existinguuid,session_idandparent_tool_use_idfields, metadata values are not charged: the caps now allow up to 480 characters of values per recognized frame instead of 384, so a flood of maximal frames can pass more raw bytes through the parser than the budget counts while still stopping at 233,016 frames.This PR repairs the accounting; #185404 proposes operator overrides for the same budgets. #166127 (tool-result payloads) and #159930 (Edit/Write file echoes) discount other record types and compose with this change.
Evidence
The shipped-entry-point run below reproduces the 20,000-line failure on this PR's base and completes with this change. The 8 MiB failures are covered by the production table further down, which is rebuilt from session transcripts and therefore an estimate. Each build ran once, and the model run is nondeterministic.
Current frame shape. A redacted
text_deltaframe from Claude Code 2.1.296 (local capture), and an empty thinking progress frame and a nonemptythinking_deltaframe from 2.1.310 (gateway log). Redaction mapped ids to deterministic fakes and text to filler of the same length.{"type":"stream_event","event":{"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"x"}},"session_id":"7bb6f15c-fe01-9b98-b1be-4ca0f64c0069","parent_tool_use_id":null,"uuid":"4cc2a702-0da8-c07e-351a-530c188e68d3","api_message_id":"msg_cc4edc38fadca693d04ed02a"} {"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"","estimated_tokens":50}},"session_id":"259d133f-756d-7e3a-9eaf-2726d0f00122","parent_tool_use_id":null,"uuid":"2f4932eb-00db-9d31-8539-f72830f05534","thinking_display":"updates","api_message_id":"msg_a063b0b88b4c8398cf55c20e"} {"type":"stream_event","event":{"type":"content_block_delta","index":1,"delta":{"type":"thinking_delta","thinking":"xxx","estimated_tokens":null}},"session_id":"ad848aa6-89e4-5a1d-11da-b532c3d99927","parent_tool_use_id":null,"uuid":"7b2f15e3-b520-b10e-a011-8e4fc7add47e","thinking_display":"updates","api_message_id":"msg_8e31b4ce4d37c57713fa18ad"}api_message_idis on everystream_eventrecord in both captures (2,441 of 2,441 on 2.1.296, 35,432 of 35,432 on 2.1.310). Among delta frames,thinking_displayappears only onthinking_delta, and on every one (24 of 24 on 2.1.296, 1,427 of 1,427 on 2.1.310, of which 21 carry thinking text and are discounted by this change; empty progress frames keep full accounting); elsewhere it is onmessage_start,content_block_startandassistantrecords, which never qualify for the discount.Outside the two changed files, no tracked file mentions either field:
Shipped entry point, before and after. One
openclaw agent execturn through the bundledclaude-clibackend, built from this PR's base (83274dfe321) and from this branch's head (tree84fff5923b7, which identifies the head independent of commit signing). Claude Code 2.1.296,claude-haiku-5-5,--thinking medium, Node 24, macOS. Each run had its own temporaryOPENCLAW_HOMEand this config:{ "agents": { "defaults": { "model": "anthropic/claude-haiku-5-5", "models": { "anthropic/claude-haiku-5-5": { "agentRuntime": { "id": "claude-cli" } } }, "timeoutSeconds": 1800 } } }Prompt: write
part01.txttopart16.txt(300 lines each) with thewritetool, runhead -c 4000 partNN.txtwithexecafter each, then replyDONE. The tool input streams as about 30,000 smallinput_json_deltaframes, the same shape as the failing production turns below.status83274dfe321error:CLI JSONL output exceeded 20000 lines; refusing to parse output.part01.txttopart08.txt)okpart01.txttopart16.txt), 4,800 linesFile and line counts come from the work directories listed below, not from the model's reply. Some files end without a trailing newline, so
wc -lprints 299 for them; theawkcount shows 300 lines in every file.base: redacted output
this change: redacted output
Redaction replaced run and session ids and hashes, and dropped two skill-loading lines from each stderr.
Charge breakdown on real records. Each line (plus its newline) was fed through
chargeClaudeStreamJsonLinefrommainand from this change, with #166127'smeasureClaudeToolResultMessageand #159930's normalizer composed in the order #166127 uses. Redaction kept every line at its original length. The totals and ordinary-line counts for this change (the 2.1.296 turn, the 2.1.310 records and all four production turns) were re-measured with the code at this head and match.OPENCLAW_CLI_BACKEND_LOG_OUTPUT):maindiscounts none of the partial frames. With this changetext_deltagoes from 7,320,100 to 1,218,600 charged characters andinput_json_deltafrom 1,249,728 to 207,720 (both 83% lower). Ordinary lines drop from 41,071 to 12,697.main, 469,353 with this change (57% lower). Ordinary lines drop from 2,494 to 130.Production failures (estimated). Four
claude-cliturns (41 to 73 minutes, 283 to 448 MCP tool calls each, thinking on) failed in one evening withexceeded 8388608 characters. The gateway does not log the stream of a failed turn, so each stream was rebuilt from that run's Claude Code session transcript: payloads from the transcript, envelopes copied from real 2.1.310 records, deltas split at the frame sizes measured above. These rows are estimates, not captured streams.mainWith this change, ordinary lines drop from 20,234 to 22,164 per turn down to 5,136 to 6,281.
Turn 1 by record category (charged characters)
mainstream_eventinput_json_deltastream_eventstart/stop/message envelopesusertool results, MCPexecassistanttool_use snapshotsassistantthinking snapshotsstream_eventsignature_deltastream_eventthinking_deltastream_eventtext_deltasystemthinking_tokensusertool results, other MCP toolsrate_limit_eventassistanttext snapshotssystemstatus/init,readand built-in tool results)The
thinking_deltaandsignature_deltarows stay fully charged: Claude Code's thinking progress frames have empty thinking text, and signature frames are not a recognized delta type. Both keep the existing accounting and are left for a separate change.Tests and checks (macOS, Node 24, at this commit):
src/agents/cli-output-partial-messages.test.ts: 39 passed. New cases cover current text, tool-input and thinking frames withapi_message_idandthinking_display, and with both set tonull(exact charge, and 20,001 frames completing); the captured 2.1.296 text frame and 2.1.310 nonempty thinking frame (charged 35 and 62 characters) and the captured empty thinking progress frame (full charge); each field exactly at its cap; full accounting for anapi_message_idof 65 characters or a non-string one, athinking_displayof 33 characters or a non-string one,thinking_displayon a text or tool-input frame, and an unknown record key; and floods of one-character text frames with typical and maximal metadata and of thinking frames with maximal metadata, which still fail withexceeded 8388608 charactersat frame 233,017 (under 1 second each).thinking_deltascope check, and setting the fixed per-frame charge to 0.src/agents/cli-output-*.test.tsfiles: 233 passed.src/agents/cli-runner/: 73 files, 843 passed.pnpm tsgo:core,pnpm tsgo:core:test, oxlint andoxfmt --checkon the touched files pass.pnpm check:changed: every step passes except the dead-export scan, which reports 14 unused exports inextensions/qa-lab,src/gateway,src/agents/main-session-recovery,test/pluginsandui, none of them touched here.pnpm deadcode:exportson the base commit without this change reports the same 14 entries. With that step skipped (OPENCLAW_CHECK_CHANGED_SKIP_DEADCODE=1),pnpm check:changedexits 0.CONTRIBUTING.mdreservesCHANGELOG.mdfor release generation.docs/gateway/cli-backends.mdalready describes the discount for recognized partial-message envelopes, which this change restores, so it needs no edit.Independent real-Claude Gateway verification
#186085 (comment) — official Claude Code2.1.310 with a local Messages fixture: built Gateway main fails at20,000 lines twice, candidate completes exact20,118-character final replies twice, short controls pass. Native metadata shape is separately captured and its observability limits disclosed. The test-only follow-up consolidates the three redundant flood variants;79 focused tests and scoped formatting/lint pass.
Current test-budget repair
#186085 (comment) — repaired head9f78626eb45f941c3435e492ee59feda80e3120e preserves every distinct parser-budget guard in table rows, consolidates only the same owner's framing scaffolding, and reduces the whole-PR test delta to -5. 81 focused tests and scoped formatting/lint pass. Production and the real Claude CLI proof are unchanged. The earlier test-line CI failure is explicitly superseded, pending repaired-head gates.