Skip to content

fix(agents): strip echoed base64 image payloads so photo-heavy turns no longer hit the per-turn output cap - #119488

Merged
steipete merged 4 commits into
openclaw:mainfrom
ml12580:fix/issue-119445
Aug 5, 2026
Merged

steipete merged 4 commits into
openclaw:mainfrom
ml12580:fix/issue-119445

Conversation

@ml12580

@ml12580 ml12580 commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

[AI-assisted] This PR was generated using Claude Code.
Maintainer repair and verification were performed with Codex.

Closes #119445

Original pull request and proposal: @ml12580. Reported by @orbitingflea.

What Problem This Solves

Fixes an issue where users asking a Claude-backed agent to read several photos or PDFs would see their turn abort with Claude CLI turn output exceeded limit, even though every individual JSONL record was safely bounded. The reported turn had 14 individually valid 0.2–2.4 MB records and 8.48 M aggregate characters against the 8 MiB limit; approximately 7.2 MB was already-consumed echoed base64 media. Multiple valid records can share a stdout callback, while blank lines and JSON whitespace must still count against the security budget.

Why This Change Was Made

Use one bounded newline-cursor framer and canonical retained-output accounting owner across the generic JSONL parser and managed Claude live-session stdout path. Keep the hard 8 MiB pre-parse limit on each complete raw record and unresolved trailing partial; normalize only Anthropic user.message.content[].tool_result.content[] base64 image/PDF blocks; and charge every physical Claude frame, including blank, CRLF, whitespace-only, and outer/inner-padded JSON records.

For compacted media, charge max(normalizedRetainedLength, rawFrameLength - actualRemovedImageAndPdfBase64Characters) + newline, so only genuinely omitted media bytes are exempt and serialization cannot erase attack-controlled whitespace. Preserve synchronous-reentry-safe framing, the shipped trimmed-but-unredacted parseJsonlEvent hook contract, raw accounting for claimed plugin events, approval/control payloads, all line-count and text limits, and Codex/Pi/Gemini provider payloads.

User Impact

Claude-backed agents can finish ordinary multi-photo/PDF turns even when individually valid image and PDF records arrive together in one stdout callback. Vision inputs, plugin raw-line hooks, approved tool inputs, and source MIME metadata remain intact. Oversized single records, oversized growing partial records, blank-frame floods, whitespace floods, padded JSON, oversized retained text, and excessive line counts are rejected.

Evidence

  • Fresh independently verified Blacksmith Testbox proof on this exact frozen tree: 313/313 tests passed: src/agents/cli-output.test.ts 126; src/agents/cli-runner.spawn.test.ts 127; src/agents/embedded-agent-runner/cli-backend-dispatch-transcript.test.ts 9; src/agents/cli-runner/execute.supervisor-capture.test.ts 51.
  • Command: node scripts/crabbox-wrapper.mjs run --provider blacksmith-testbox --timing-json -- OPENCLAW_TESTBOX=1 OPENCLAW_TESTBOX_REMOTE_RUN=1 pnpm test src/agents/cli-output.test.ts src/agents/cli-runner.spawn.test.ts src/agents/embedded-agent-runner/cli-backend-dispatch-transcript.test.ts src/agents/cli-runner/execute.supervisor-capture.test.ts
  • Exact one-shot lease tbx_01kz8ashyg2r3c2pkhs3gnq6w1; backing workflow. The lease was intentionally stopped after proof; its orchestration workflow may briefly remain running or display cancelled, while authoritative command timing reports exitCode=0, runStatus=succeeded, commandMs=171681, and totalMs=173883.
  • Previous P2 fixed in both owners. Generic Claude parsing and managed live-session stdout now count actual blank/CRLF frames toward both the 20,000-line limit and the 8 MiB aggregate budget. finish() never invents a phantom blank frame; blank lines never invoke plugin hooks.
  • Whitespace and padding bypasses closed. Both runtime paths reject two coalesced 4.3 M-character whitespace-only frames, two outer-padded valid JSON frames, and two media-bearing JSON records padded inside their valid JSON structure. Metering subtracts only the actual removed image/PDF source.data characters and still includes outer whitespace, inner JSON formatting, CRLF, and the physical newline.
  • Previous P1 framing fixes retained. The managed-session runtime (executePreparedCliRun → handleClaudeStdout) receives 4.3 M-char image + 4.3 M-char PDF records in one mocked-supervisor stdout callback, completes with both files read, and emits canonical {omitted:true,bytes:3225000} metadata. One generic parser push accepts the same coalesced records. This exercises the real OpenClaw session/dispatch seam with mocked CLI transport; no live external Claude-provider call is claimed.
  • Shipped plugin SDK contract retained. parseJsonlEvent sees the original shipped trimmed, unredacted line; surrounding physical padding is charged against the untrimmed raw frame. Claimed plugin events are raw-metered before dispatch, preserving both the shipped raw-line hook contract and public plugin SDK export.
  • Hostile-input regressions in both paths reject a single >8 MiB complete raw record, an unresolved partial growing beyond 8 MiB, aggregate retained text >8 MiB, and >20,000 frames. Empty image base64 remains canonical {omitted:true,bytes:0}. The real report concerns individually valid 0.2–2.4 MB records; accepting an oversized single raw line would weaken the security boundary and is intentionally not implemented.
  • Approval regression proves image/PDF-containing control_request.request.input remains byte-for-byte identical in control_response.response.response.updatedInput; custom-provider frames and Codex, Pi, and Gemini payloads remain byte-for-byte unchanged.
  • Direct pinned dependency contracts: Anthropic base64 image/PDF source types; Anthropic mixed tool-result media blocks; Codex MCP result wire payload; Codex JSONL MCP content passthrough; Codex MCP protocol result; Codex multimodal tool-output contract.
  • Production +178/-101 = +77; the added canonical framing/accounting owner is required to preserve hostile-input security limits, the shipped plugin SDK hook, and Anthropic/Codex dependency contracts while deleting duplicate accounting. Tests +573/-1 = +572, counted separately. git diff --check passed; two independent final source reviews PASS, no findings.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M labels Aug 5, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. labels Aug 5, 2026
@clawsweeper

clawsweeper Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed August 5, 2026, 6:33 AM ET / 10:33 UTC.

ClawSweeper review

What this changes

The PR frames Claude CLI JSONL by physical record and omits echoed base64 image/PDF data from retained-output accounting while retaining output limits.

Merge readiness

⛔ Blocked until real behavior proof from a real setup is added - 4 items remain

Keep open: current main still has the reported raw-output accounting path, but this external PR has only mocked behavior proof and the required direct Codex-source contract check is unavailable.

Priority: P1
Reviewed head: 8803855714c5a653024f1da261283ba483dfac90

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The source patch is coherent and well-covered by focused tests, but real behavior proof remains a merge gate.
Proof confidence 🦪 silver shellfish (2/6) Needs real behavior proof before merge: Focused mocked-supervisor/Testbox coverage is strong supplemental evidence, but the PR body provides no redacted after-fix real managed Claude CLI run. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs real behavior proof before merge: Focused mocked-supervisor/Testbox coverage is strong supplemental evidence, but the PR body provides no redacted after-fix real managed Claude CLI run. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 6 items Current main still lacks the repair: Current main retains the previous raw-output accounting and live-session buffering path; the PR's framing and normalization helpers are absent.
Shared owner-boundary implementation: The PR introduces one bounded framer and Claude-only media normalization, then uses them in both generic parsing and managed live stdout handling.
Focused regression coverage: Tests cover coalesced image/PDF records, blank and padded frames, raw plugin-hook input, control payload preservation, and limits.
Findings None None.
Security None None.

How this fits together

Claude-backed agent runs consume stream-json records from a CLI process, parse tool and result events, and retain bounded output for the active turn. This change sits between CLI stdout and the agent event/transcript path.

flowchart LR
A[Claude CLI stdout] --> B[JSONL record framing]
B --> C[Claude media normalization]
C --> D[Retained-output limits]
D --> E[Agent tool and result events]
E --> F[Turn completion]
Loading

Before merge

  • Add real behavior proof - Needs real behavior proof before merge: Focused mocked-supervisor/Testbox coverage is strong supplemental evidence, but the PR body provides no redacted after-fix real managed Claude CLI run. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Resolve merge risk (P1) - Merging changes the availability boundary for Claude live turns without an after-fix real managed-CLI run.
  • Resolve merge risk (P1) - The Codex payload-preservation claim cannot be independently verified until the required sibling Codex source is available.
  • Complete next step (P2) - Do not dispatch a repair: the remaining blockers are contributor real-behavior proof and reviewer dependency-contract evidence, not a mechanical code defect.
Agent review details

Security

None.

PR surface

Source +77, Tests +572. Total +649 across 4 files.

View PR surface stats
Area Files Added Removed Net
Source 2 178 101 +77
Tests 2 573 1 +572
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 751 102 +649

Review metrics

Metric Value Why it matters
Production vs test delta production +77, tests +572 The production growth creates the shared framing/accounting owner and is paired with broad hostile-input regression coverage.

Stored data model

Persistent data-model change detected: serialized state: src/agents/cli-output.test.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Prove the managed Claude path before merge (recommended)
    Add a redacted terminal transcript, recording, or runtime log of a real managed Claude CLI photo/PDF turn completing after the fix, then repeat the review with direct Codex-source evidence.
  2. Pause until dependency evidence is available
    Do not merge while the required Codex payload-contract source remains unavailable to reviewers.

Technical review

Best possible solution:

Keep the shared framing/accounting design, then add redacted proof from an actual managed Claude CLI multi-image/PDF turn and complete the direct Codex contract inspection before merge.

Do we have a high-confidence way to reproduce the issue?

Yes for source reproduction: current main accounts the raw Claude records that the linked report identifies, and the report supplies a concrete multi-image/PDF managed-CLI scenario; this review did not execute it.

Is this the best way to solve the issue?

Unclear: source inspection favors the shared framing/accounting owner over raising the cap or preserving two accounting paths, but real behavior and direct Codex contract proof remain required.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 637de7d37945.

Labels

Label justifications:

  • P1: Photo-heavy Claude turns can abort on the default output limit, breaking an active agent workflow.
  • merge-risk: 🚨 availability: This changes output-limit accounting and managed live-session framing, so an error could abort or stall Claude agent turns.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: Focused mocked-supervisor/Testbox coverage is strong supplemental evidence, but the PR body provides no redacted after-fix real managed Claude CLI run. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

  • Current main still lacks the repair: Current main retains the previous raw-output accounting and live-session buffering path; the PR's framing and normalization helpers are absent. (src/agents/cli-output.ts:1908, 637de7d37945)
  • Shared owner-boundary implementation: The PR introduces one bounded framer and Claude-only media normalization, then uses them in both generic parsing and managed live stdout handling. (src/agents/cli-output.ts:571, 8803855714c5)
  • Focused regression coverage: Tests cover coalesced image/PDF records, blank and padded frames, raw plugin-hook input, control payload preservation, and limits. (src/agents/cli-output.test.ts:3426, 8803855714c5)
  • History and current ownership: The final three repair commits were authored by steipete; the PR head is the blank-frame/padded-output accounting follow-up. (src/agents/cli-runner/claude-live-session.ts:1320, 8803855714c5)
  • Real proof remains mock-only: The PR body explicitly describes mocked CLI transport and does not claim a live managed Claude CLI run; the linked issue remains the open canonical bug report. (8803855714c5)
  • Required Codex dependency check is unavailable: The repository policy requires direct sibling Codex source inspection for this payload-contract claim, but ../codex is absent and DNS prevented the required clone. (AGENTS.md:14, 637de7d37945)

Likely related people:

  • steipete: Authored the three corrective commits after the initial proposal and has recent history in both accounting owners. (role: recent agent-runtime repair contributor; confidence: high; commits: be70313a5a69, 70a8191bb96f, 8803855714c5; files: src/agents/cli-output.ts, src/agents/cli-runner/claude-live-session.ts)
  • Ayaan Zaidi: History includes shared CLI stream classification and Claude live-session behavior in the two affected owners. (role: historical CLI-output and live-session contributor; confidence: medium; commits: d18817019f, 7cc40d9e46, 969efdac4f; files: src/agents/cli-output.ts, src/agents/cli-runner/claude-live-session.ts)
  • joshavant: Recent parser repairs in the generic CLI output owner make this a relevant review route. (role: recent adjacent parser contributor; confidence: medium; commits: 97f8f25f, 0ccae508; files: src/agents/cli-output.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Add redacted output from an actual managed Claude CLI multi-photo/PDF run that completes after the fix.
  • Make the exact Codex payload contract available for direct reviewer inspection.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (4 earlier review cycles)
  • reviewed 2026-08-05T05:06:28.564Z sha 92efc07 :: needs real behavior proof before merge. :: [P1] Normalize before the live line-size guards
  • reviewed 2026-08-05T05:45:24.703Z sha be70313 :: needs real behavior proof before merge. :: [P1] Frame stdout records before enforcing the pending-line cap | [P1] Meter Claude output after framing complete JSONL records
  • reviewed 2026-08-05T06:28:59.890Z sha 70a8191 :: needs real behavior proof before merge. :: [P2] Account for blank Claude JSONL frames
  • reviewed 2026-08-05T07:04:29.619Z sha 8803855 :: needs real behavior proof before merge. :: none

Complete the owner-boundary repair for openclaw#119488 and openclaw#119445.

Preserve contributor @ml12580 and reporter @orbitingflea attribution.
@steipete

steipete commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added 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. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Aug 5, 2026
Resolve both exact-head P1 coalesced-line framing findings and preserve the shipped raw-line CLI backend hook.

Preserve contributor @ml12580 and reporter @orbitingflea attribution for openclaw#119488 and openclaw#119445.
@steipete

steipete commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. and removed merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Aug 5, 2026
Resolve exact-head blank-frame and padded-output accounting across both Claude parser owners while preserving coalesced media and the shipped raw-line plugin hook.

Preserve contributor @ml12580 and reporter @orbitingflea attribution for openclaw#119488 and openclaw#119445.
@steipete

steipete commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@steipete

steipete commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Maintainer proof-scope waiver — exact head 8803855714c5a653024f1da261283ba483dfac90. The requesting maintainer explicitly waives the optional live authenticated managed-Claude multi-photo/PDF run. The actual production parser and managed-supervisor owner path passed 313/313 exact-head Blacksmith tests (Testbox workflow); the supervisor/Claude transport was mocked, and no live Claude-provider proof is claimed. Exact-head required CI and ci-gate, Workflow Sanity, security, and fresh independent Codex Sol/high autoreview all pass (no findings; confidence 0.98).

I directly inspected Codex MCP wire results, exec_events.rs:261-293, JSONL passthrough, event_processor_with_jsonl_output.rs:205-229, MCP/image preservation, protocol/src/models.rs:2022-2190, and pinned Anthropic SDK 0.115.0 image/PDF / tool-result contracts. ClawSweeper rank-up 1 is explicitly waived; rank-up 2 is fulfilled. Production +178/-101 (net +77); tests +573/-1 (net +572); production growth owns canonical bounded framing/accounting and preserves hostile-input and sibling-provider payload contracts.

@steipete
steipete merged commit 1352332 into openclaw:main Aug 5, 2026
125 checks passed
@steipete

steipete commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Merged via squash.

vincentkoc added a commit to VACInc/openclaw that referenced this pull request Aug 5, 2026
* origin/main: (130 commits)
  refactor(qa): consolidate scenario runtime helpers (openclaw#119623)
  fix(telegram): bind Mini App auth to dashboard launches
  refactor(agent-core): unify session projection and compaction summaries (openclaw#119639)
  fix(codex): allow natural reactions in the current conversation (openclaw#119649)
  refactor(providers): deduplicate bundled model catalogs (openclaw#119627)
  fix(ui): observe the active service worker after asset refresh (openclaw#119622)
  fix(agents): strip echoed base64 image payloads so photo-heavy turns no longer hit the per-turn output cap (openclaw#119488)
  improve: make state-heavy test suites faster (openclaw#119617)
  perf(agents): add concurrency benchmark (openclaw#119569)
  fix(browser): visibly report failed pairing and tab-sharing actions (openclaw#119526)
  refactor(lobster): consolidate embedded workflow execution (openclaw#119630)
  fix(plugin-sdk): stabilize tuple-derived API baseline ordering (openclaw#119635)
  docs(skills): make full-authority maintainer runs unattended (openclaw#119629)
  fix(managed-child): honor process groups that vanish before cleanup (openclaw#119614)
  fix(ci): stop label-driven automation churn (openclaw#119610)
  fix(media): keep the ttl sweep out of the managed outgoing tree (openclaw#119127)
  fix(claws): remove owner-qualified skills (openclaw#119606)
  fix(clawrouter): show stable error for malformed usage responses (openclaw#119580)
  fix(gateway): claim malformed plugin icon routes (openclaw#119559)
  fix(telegram): preserve truthful empty-content delivery (openclaw#88810)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 6, 2026
…no longer hit the per-turn output cap (openclaw#119488)

* fix(agents): strip echoed base64 image payloads before per-turn CLI output-limit accounting

* fix(agents): normalize Claude tool media before output metering

Complete the owner-boundary repair for openclaw#119488 and openclaw#119445.

Preserve contributor @ml12580 and reporter @orbitingflea attribution.

* fix(agents): frame coalesced CLI records before output limits

Resolve both exact-head P1 coalesced-line framing findings and preserve the shipped raw-line CLI backend hook.

Preserve contributor @ml12580 and reporter @orbitingflea attribution for openclaw#119488 and openclaw#119445.

* fix(agents): meter every bounded Claude output frame

Resolve exact-head blank-frame and padded-output accounting across both Claude parser owners while preserving coalesced media and the shipped raw-line plugin hook.

Preserve contributor @ml12580 and reporter @orbitingflea attribution for openclaw#119488 and openclaw#119445.

---------

Co-authored-by: Peter Steinberger <[email protected]>
tomorrowflow added a commit to tomorrowflow/openclaw that referenced this pull request Oct 15, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: L status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Image tool_result payloads (base64) count toward the per-turn CLI output limit but are never read by openclaw, aborting photo-heavy turns

2 participants