Skip to content

fix(agents): Claude CLI turns hit the 20,000-line limit when Claude Code adds stream frame metadata - #186085

Merged
obviyus merged 3 commits into
openclaw:mainfrom
etzelm:fix/claude-cli-partial-message-metadata
Oct 27, 2026
Merged

obviyus merged 3 commits into
openclaw:mainfrom
etzelm:fix/claude-cli-partial-message-metadata

Conversation

@etzelm

@etzelm etzelm commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Related: #185404, #153545, #166127, #159930

What Problem This Solves

Long tool-heavy claude-cli turns on current Claude Code (seen on 2.1.296 and 2.1.310) fail with CLI 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-cli backend 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 and signature_delta frames 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_delta with 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_id on every stream_event, and the display setting thinking_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_id and parent_tool_use_id: api_message_id as a string of at most 64 characters on any recognized delta (captured ids are 28), and thinking_display as a string of at most 32 characters on thinking_delta frames 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 from message_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_display on 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 existing uuid, session_id and parent_tool_use_id fields, 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_delta frame from Claude Code 2.1.296 (local capture), and an empty thinking progress frame and a nonempty thinking_delta frame 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_id is on every stream_event record 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_display appears only on thinking_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 on message_start, content_block_start and assistant records, which never qualify for the discount.

Outside the two changed files, no tracked file mentions either field:

$ git grep -n -e api_message_id -e thinking_display -- . ':!src/agents/cli-output-stream-limits.ts' ':!src/agents/cli-output-partial-messages.test.ts'
$ echo $?
1

Shipped entry point, before and after. One openclaw agent exec turn through the bundled claude-cli backend, built from this PR's base (83274dfe321) and from this branch's head (tree 84fff5923b7, 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 temporary OPENCLAW_HOME and 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.txt to part16.txt (300 lines each) with the write tool, run head -c 4000 partNN.txt with exec after each, then reply DONE. The tool input streams as about 30,000 small input_json_delta frames, the same shape as the failing production turns below.

Build Exit status Tool calls Files in the work dir after the run
base 83274dfe321 1 error: CLI JSONL output exceeded 20000 lines; refusing to parse output. not reported 8 (part01.txt to part08.txt)
this change 0 ok 32, 0 failures 16 (part01.txt to part16.txt), 4,800 lines

File 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 -l prints 299 for them; the awk count shows 300 lines in every file.

base: redacted output
$ git rev-parse --short=11 HEAD
83274dfe321
$ claude --version
2.1.296 (Claude Code)
$ openclaw agent exec --config openclaw.json --cwd work --message-file work/prompt.txt --thinking medium --timeout 1800 --json
{
  "ok": false,
  "status": "error",
  "final": "",
  "payloads": [],
  "model": null,
  "provider": null,
  "sessionId": "<run-id>",
  "error": {
    "message": "CLI JSONL output exceeded 20000 lines; refusing to parse output.",
    "kind": "exception"
  }
}
--- stderr (filtered) ---
[agent/cli-backend] cli session history refused across auth boundary: reason=auth-unknown
[agent/cli-backend] cli live session start: provider=claude-cli model=claude-haiku-5-5 activeSessions=1
[state/agent-db] agent database clean-close receipt: written; agent=main
[diagnostic] lane task error: lane=cli:claude-cli:owner:<hash> durationMs=428669 error="CLI JSONL output exceeded 20000 lines; refusing to parse output." errorName=FailoverError
[agent/cli-backend] cli terminal failure: provider=claude-cli model=claude-haiku-5-5 durationMs=429292 runId=<run-id> error=CLI JSONL output exceeded 20000 lines; refusing to parse output.
[model-fallback/decision] model fallback decision: decision=candidate_failed requested=anthropic/claude-haiku-5-5 candidate=anthropic/claude-haiku-5-5 reason=format next=none
[trajectory] retention deferred until the next sweep: Error: Agent database execution admission is closed
[state/agent-db] agent database clean-close receipt: written; agent=main
CLI JSONL output exceeded 20000 lines; refusing to parse output.
exit 1

$ ls work
part01.txt
part02.txt
part03.txt
part04.txt
part05.txt
part06.txt
part07.txt
part08.txt
prompt.txt
$ wc -l work/part*.txt
     299 work/part01.txt
     299 work/part02.txt
     299 work/part03.txt
     299 work/part04.txt
     299 work/part05.txt
     299 work/part06.txt
     299 work/part07.txt
     299 work/part08.txt
    2392 total
$ for f in work/part*.txt; do awk 'END { print NR }' "$f"; done | sort | uniq -c
   8 300
this change: redacted output
$ git rev-parse --short=11 'HEAD^{tree}'
84fff5923b7
$ claude --version
2.1.296 (Claude Code)
$ openclaw agent exec --config openclaw.json --cwd work --message-file work/prompt.txt --thinking medium --timeout 1800 --json
{
  "ok": true,
  "status": "ok",
  "final": "DONE",
  "payloads": [
    {
      "text": "DONE",
      "mediaUrl": null
    }
  ],
  "usage": {
    "input": 2,
    "output": 4,
    "cacheRead": 92735,
    "cacheWrite": 1288,
    "cacheWrite1h": 1288
  },
  "toolSummary": {
    "calls": 32,
    "tools": [
      "mcp__openclaw__write",
      "mcp__openclaw__exec"
    ],
    "failures": 0
  },
  "model": "claude-haiku-5-5",
  "provider": "anthropic",
  "sessionId": "<run-id>"
}
--- stderr (filtered) ---
[agent/cli-backend] cli session history refused across auth boundary: reason=auth-unknown
[agent/cli-backend] cli live session start: provider=claude-cli model=claude-haiku-5-5 activeSessions=1
[state/agent-db] agent database clean-close receipt: written; agent=main
[agent/cli-backend] cli turn: provider=claude-cli model=claude-haiku-5-5 durationMs=932380 outBytes=4 outHash=<hash>
[state/agent-db] agent database clean-close receipt: written; agent=main
exit 0

$ ls work
part01.txt
part02.txt
part03.txt
part04.txt
part05.txt
part06.txt
part07.txt
part08.txt
part09.txt
part10.txt
part11.txt
part12.txt
part13.txt
part14.txt
part15.txt
part16.txt
prompt.txt
$ wc -l work/part*.txt
     299 work/part01.txt
     299 work/part02.txt
     299 work/part03.txt
     299 work/part04.txt
     299 work/part05.txt
     299 work/part06.txt
     299 work/part07.txt
     300 work/part08.txt
     300 work/part09.txt
     300 work/part10.txt
     300 work/part11.txt
     300 work/part12.txt
     300 work/part13.txt
     300 work/part14.txt
     300 work/part15.txt
     300 work/part16.txt
    4793 total
$ for f in work/part*.txt; do awk 'END { print NR }' "$f"; done | sort | uniq -c
  16 300

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 chargeClaudeStreamJsonLine from main and from this change, with #166127's measureClaudeToolResultMessage and #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.

  • 41,071 real stream-json records from Claude Code 2.1.310 (694 completed gateway turns, logged with OPENCLAW_CLI_BACKEND_LOG_OUTPUT): main discounts none of the partial frames. With this change text_delta goes from 7,320,100 to 1,218,600 charged characters and input_json_delta from 1,249,728 to 207,720 (both 83% lower). Ordinary lines drop from 41,071 to 12,697.
  • One complete real turn from Claude Code 2.1.296 (Haiku, thinking, 8 tool calls, 2,494 records): 1,093,169 charged characters on main, 469,353 with this change (57% lower). Ordinary lines drop from 2,494 to 130.

Production failures (estimated). Four claude-cli turns (41 to 73 minutes, 283 to 448 MCP tool calls each, thinking on) failed in one evening with exceeded 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.

Turn main with #166127 with #166127 + #159930 this change this change + #166127
1 9,574,858 (114%), fails 8,684,976 (104%), fails at 20,001 lines same as #166127 5,089,994 (61%), completes 4,200,112 (50%)
2 9,228,939 (110%), fails 8,637,531 (103%), fails at 20,001 lines same as #166127 5,094,927 (61%), completes 4,503,519 (54%)
3 9,443,232 (113%), fails 8,675,253 (103%), fails at 20,001 lines same as #166127 5,427,108 (65%), completes 4,659,129 (56%)
4 9,104,150 (109%), fails 8,358,876 (100%), fails at 20,001 lines same as #166127 5,256,654 (63%), completes 4,511,380 (54%)

With 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)
Category Raw main with #166127 this change this change + #166127
stream_event input_json_delta 5,064,144 5,064,144 5,064,144 767,280 767,280
stream_event start/stop/message envelopes 838,692 838,692 838,692 838,692 838,692
user tool results, MCP exec 838,006 838,006 112,103 838,006 112,103
assistant tool_use snapshots 794,883 794,883 794,883 794,883 794,883
assistant thinking snapshots 554,569 554,569 554,569 554,569 554,569
stream_event signature_delta 366,870 366,870 366,870 366,870 366,870
stream_event thinking_delta 266,944 266,944 266,944 266,944 266,944
stream_event text_delta 224,259 224,259 224,259 36,259 36,259
system thinking_tokens 150,544 150,544 150,544 150,544 150,544
user tool results, other MCP tools 143,599 143,599 17,057 143,599 17,057
rate_limit_event 134,037 134,037 134,037 134,037 134,037
assistant text snapshots 113,849 113,849 113,849 113,849 113,849
other (system status/init, read and built-in tool results) 84,462 84,462 47,025 84,462 47,025
Total 9,574,858 9,574,858 8,684,976 5,089,994 4,200,112

The thinking_delta and signature_delta rows 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 with api_message_id and thinking_display, and with both set to null (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 an api_message_id of 65 characters or a non-string one, a thinking_display of 33 characters or a non-string one, thinking_display on 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 with exceeded 8388608 characters at frame 233,017 (under 1 second each).
  • With only the production change reverted, 19 tests fail and 20 pass. Ten mutations each fail at least one test: raising either cap, lowering either cap by one, dropping the string check, accepting any record key, removing either field, dropping the thinking_delta scope check, and setting the fixed per-frame charge to 0.
  • All 10 src/agents/cli-output-*.test.ts files: 233 passed. src/agents/cli-runner/: 73 files, 843 passed.
  • pnpm tsgo:core, pnpm tsgo:core:test, oxlint and oxfmt --check on the touched files pass.
  • pnpm check:changed: every step passes except the dead-export scan, which reports 14 unused exports in extensions/qa-lab, src/gateway, src/agents/main-session-recovery, test/plugins and ui, none of them touched here. pnpm deadcode:exports on the base commit without this change reports the same 14 entries. With that step skipped (OPENCLAW_CHECK_CHANGED_SKIP_DEADCODE=1), pnpm check:changed exits 0.
  • No changelog entry: CONTRIBUTING.md reserves CHANGELOG.md for release generation. docs/gateway/cli-backends.md already 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.

…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.
@clawsweeper

clawsweeper Bot commented Oct 27, 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 agents Agent runtime and tooling size: S labels Oct 27, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. labels Oct 27, 2026
@clawsweeper

clawsweeper Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

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

  • Before: The turn fails with “CLI JSONL output exceeded 20000 lines” and produces no final payload.
  • After: The turn completes with the exact 20,118-character reply ending in DONE186085 long-1.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused, source-supported repair with shipped-entry-point A/B proof and no actionable findings; pending CI is not a passing claim.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The contributor supplies real openclaw agent exec before-and-after terminal output for a tool-heavy turn on macOS, and obviyus supplies repeated built-Gateway A/B results using official Claude Code 2.1.310 in isolated Linux containers against a deterministic Messages fixture; candidate turns complete where main hits the ordinary-line limit, and subsequent changes affect tests only.
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 abort before delivering their final response because current stream metadata defeats the intended delta discount.
Reason: The repair restores documented behavior with captured protocol shapes, bounded acceptance, and demonstrated user-visible recovery.

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
Reviewed head: 9f78626eb45f941c3435e492ee59feda80e3120e

Before merge

None.

Findings

None.

Agent review details

How this fits together

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

Technical review

Best 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

  • Partial-message recognition and accounting keeps the original intent (12302d7: Discount repeated protocol envelopes while charging payloads and bounding tiny-delta floods; unknown shapes retain ordinary accounting.)
  • CLI parser framing fixtures keeps the original intent (5fad24c: Split parser concepts while preserving existing streaming, tool, usage, media, and error behavior.)
  • Echoed binary framing regressions keeps the original intent (636b00c: Normalize duplicated binary echoes before accounting while preserving projected tool metadata; the shared constructors retain the same wire records and assertions.)

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:26 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)
  • Ayaan Zaidi: Raw commit d1470c8 adds src/agents/cli-output-stream-limits.ts:94 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: d1470c8514ce; files: src/agents/cli-output-stream-limits.ts)

PR surface

Source +19, Tests -5. Total +14 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 24 5 +19
Tests 2 172 177 -5
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 196 182 +14

Review metrics

Metric Value Why it matters
Production versus test LOC Production +24/-5; tests +172/-177 The small production increase implements bounded metadata recognition; fixture and table consolidation keeps the whole-PR test delta negative without removing assertions.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: Current Claude Code metadata causes long CLI-backed agent turns to abort and lose their final response, demonstrated through shipped commands.
  • 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 (2 earlier review cycles)
  • reviewed 2026-10-27T15:47:01.996Z sha ffefe52 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-27T16:57:36.068Z sha 82e5949 :: needs maintainer review before merge. :: none

Reviewed October 27, 2026, 1:26 PM ET / 17:26 UTC (Revision 3).

@obviyus

obviyus commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator

Independent real Claude CLI + built Gateway proof

Pinned main 339c89cf7be90725640e7db6e3ad244b38e946a8; candidate production ffefe52b66b916ece41904912823c0c87b7cd908. Both refs built successfully in fresh secretless Linux node:24.22.1 containers. Each container installed the official @anthropic-ai/[email protected]; the actual executable reports 2.1.310 (Claude Code). No stub executable, personal login or paid-provider key is used.

The shipped agent command dispatches a real Gateway turn with anthropic/claude-sonnet-4-6, agentRuntime.id: claude-cli. The real Claude CLI is pointed at a task-owned deterministic Anthropic Messages SSE fixture using synthetic credentials and the existing OPENCLAW_LIVE_CLI_BACKEND_PRESERVE_ENV route. The fixture records actual native Messages requests. It emits 20,100 single-character text deltas plus 100 thinking deltas, then the final marker. These are real API events consumed by the official CLI, not injected parser records.

Gateway turn Main Candidate
Short control Completes: SHORT186085 short Same completion
Long run 1 Fails: CLI JSONL output exceeded 20000 lines; refusing to parse output. No final payload Completes: exact 20,118-character reply ending DONE186085 long-1
Long run 2 Same 20,000-line failure, no final payload Exact 20,118-character reply ending DONE186085 long-2

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 api_message_id: msg_000000000000000000000001 on text/thinking/signature stream events, and thinking_display: updates on the thinking event. This shape diagnostic is separate from the Gateway A/B: the initial passive child-stdout observer only saw auxiliary subprocesses and yielded no Gateway raw-byte measurements, so it is not counted as native-frame-count or aggregate-byte evidence. The Gateway failure, successful final payloads and external Messages requests are directly captured.

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 checks

Head 82e59494618aae0f71d283022fd2de926e3e6608 preserves the contributor commit and changes only the test flood matrix: three identical 233,017-frame exhaustion loops become one maximal-current-metadata thinking flood. The exact-charge/metadata-boundary tables, 20,001-frame acceptance table, unknown/oversized/misplaced metadata, empty-thinking, padding and ordinary-frame guards remain. The surviving flood still asserts the 8,388,608-character limit and exact 233,017th frame failure. No production behavior changes after the built A/B.

Observed in the isolated container: 79 tests passed across three files (cli-output-partial-messages, cli-output-framing, cli-output-jsonl); scoped Oxfmt/Oxlint passed. Whole-PR delta against the merge base: production +24/-5 (net +19), tests +163/-0, a six-line reduction and two fewer expensive flood executions relative to the contributor head. No budgets or configuration defaults changed.

@obviyus

obviyus commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Oct 27, 2026
@obviyus

obviyus commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator

Parser-budget ratchet repair — 9f78626eb45f941c3435e492ee59feda80e3120e

The first worker push (82e5949) exposed a required test-lines failure: total6,286,109 vs ceiling6,285,587, PR delta+163. That failure was triggered by test growth, not an unrelated baseline failure. No jobs were rerun and no global ceiling was changed.

With maintainer authorization, the same parser owner's budget tests now use one guard matrix: exact charges and20,001-line behavior remain paired for current/captured/legacy delta shapes, all five metadata caps, over-cap and wrong-type values, unknown fields, misplaced display metadata, empty thinking and signature deltas, and custom-parser accounting. Encoded payload, whitespace, raw-line, ordinary-line, terminal/tool-turn and exact233,017-frame flood boundaries remain. The same owner's framing file shares its repeated tool-result/image wire constructors; all framing test cases and assertions remain.

Whole-PR test delta is now -5 lines: partial-message budget suite +66, same-owner framing scaffolding -71. Production is unchanged (+24/-5, net+19), so the real-Claude Gateway proof carries unchanged. No tests belonging to another owner or budget/configuration file were edited.

Observed final local checks in the secretless container: 81 tests passed across3 files (39 budget-matrix cases,42 framing/JSONL cases); scoped Oxfmt/Oxlint passed. Both changed test files are unchanged on current main relative to the PR base, so no main integration was necessary. Hosted CI and hosted review must now evaluate this repaired head; the earlier +163 failure is historical, not a passing claim.

@obviyus

obviyus commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus
obviyus merged commit 72c9a55 into openclaw:main Oct 27, 2026
113 of 115 checks passed
@obviyus

obviyus commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator

Landed in 72c9a55. Thanks @etzelm. Claude CLI long replies no longer hit the line limit.

@etzelm
etzelm deleted the fix/claude-cli-partial-message-metadata branch October 27, 2026 17:47
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 28, 2026
…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]>
etzelm added a commit to etzelm/openclaw that referenced this pull request Oct 31, 2026
…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.
vyctorbrzezowski pushed a commit that referenced this pull request Nov 9, 2026
…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.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 10, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling 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.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants