Skip to content

fix(cli): meter base64 image payloads as stubs in Claude live session turns - #119486

Closed
licheer-zte wants to merge 1 commit into
openclaw:mainfrom
licheer-zte:fix/claude-live-image-payload-metering-119445
Closed

licheer-zte wants to merge 1 commit into
openclaw:mainfrom
licheer-zte:fix/claude-live-image-payload-metering-119445

Conversation

@licheer-zte

Copy link
Copy Markdown
Contributor

Fixes #119445

[AI-assisted]

What Problem This Solves

Photo-heavy CLI-backend turns abort with a spurious Claude CLI turn output exceeded limit error. The per-turn stream-json output cap (maxTurnRawChars, default 8 MiB, from #75838) meters the raw JSONL lines the CLI writes to stdout, and those lines embed full base64 photo payloads inside tool_result content blocks. A modest "read a folder of photos" task (14 JPEG/PNG photos of 0.3–2 MB each) produces ~8.48 MB of stream volume — ~7.2 MB of it base64 image data — while the assistant text for the whole turn is ~2.7 KB. The run is aborted and the user sees "Something went wrong".

Why This Change Was Made

openclaw never consumes image source.data from the CLI stream: the CLI backend already sent the images to the model API (vision behavior is unaffected), and the live-session consumer only reads assistant text deltas, tool start/complete status + ids, session id, and usage. Nothing persists the payloads either — verified in the report against the agent/state SQLite stores. The image bytes' only effect is incrementing the raw-chars counter that kills the turn. The ClawSweeper review of this issue calls for normalizing echoed image tool-result blocks before retained aggregate accounting and parser input while preserving block type, tool state, MIME metadata, and decoded byte count — this change does exactly that:

  • New stripClaudeLiveImagePayloads walks the parsed record recursively (image blocks appear in tool_result content arrays inside user message lines) and replaces each source.data with [image: N base64 chars omitted], keeping the block type and MIME metadata intact.
  • The stubbed serialization is used for rawChars accounting, the rawLines buffer, and the streaming parser; non-image lines are passed through byte-identical.
  • The existing raw single-line safety bound (maxPendingLineChars) still applies to the raw line as before.

User Impact

Photo-heavy turns complete instead of aborting mid-turn. The reported 8.48 MB turn drops to ~1.3 MB (6× under the default cap), so the default 8 MiB limit stops being a cliff for bounded photo tasks. Tool result events keep their block structure and MIME metadata with the payload replaced by a byte-count stub — no model-visible or persistence behavior changes.

Evidence

  • src/agents/cli-runner/claude-live-session.ts (+46/−3): stripClaudeLiveImagePayloads helper + meteredLine substituted for trimmed in rawChars accounting, rawLines buffering, and streamingParser.push.
  • New src/agents/cli-runner/claude-live-session.image-payload.test.ts (2 tests):
    • completes a photo-heavy turn instead of tripping the raw-chars output cap: three tool_result lines carrying 3 MiB of base64 each (9 MiB total > 8 MiB cap) complete the turn successfully.
    • feeds the streaming parser stubbed image payloads instead of raw base64: asserts onToolResult receives [image: 1048576 base64 chars omitted] rather than the raw base64.
  • Regression proof: with the production change stashed, both tests fail (2 failed); with it, both pass.
  • Existing suites stay green: claude-live-session.background-tasks, claude-live-session.capability, claude-live-tool-approval — 48/48 pass under vitest.agents-support.config.ts. oxlint and oxfmt clean on changed files; tsgo typecheck clean for both changed files (only pre-existing unrelated rejectSymlinks drift errors remain on this checkout).

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M labels Aug 5, 2026
… turns

Photo-heavy turns (e.g. reading a folder of photos) trip the per-turn
stream-json raw-chars cap (maxTurnRawChars, default 8 MiB) because full
base64 image payloads inside tool_result content blocks are counted
against the cap even though nothing downstream reads image source.data:
the CLI backend already sent the images to the model API, and openclaw
only consumes assistant text, tool status/ids, session id, and usage.

Strip image source.data at ingest and use the stubbed serialization for
rawChars accounting, the rawLines buffer, and the streaming parser, so a
9 MB photo turn meters at ~1.3 MB instead of aborting with a spurious
"Claude CLI turn output exceeded limit" error. Text events are untouched.

Refs openclaw#119445
@licheer-zte
licheer-zte force-pushed the fix/claude-live-image-payload-metering-119445 branch from 723d607 to f1ce51e Compare August 5, 2026 04:54
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. 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. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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, 9:31 AM ET / 13:31 UTC.

ClawSweeper review

What this changes

The PR replaces echoed base64 image data with stubs before Claude live-session buffering, parsing, and per-turn output-limit accounting.

Merge readiness

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

Keep open: the photo-heavy turn failure remains plausible, but this branch still has an unfixed P1 scope error and only mock-based proof.

Priority: P1
Reviewed head: f1ce51efef444caf3fa41e2cbe7581bc3c3f3c67

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The repair targets a credible failure, but it has a P1 control-input regression and lacks real behavior proof.
Proof confidence 🧂 unranked krab (1/6) Needs real behavior proof before merge: The stated evidence is mock-supervisor testing only; add a redacted after-fix Claude CLI terminal output, stream log, or runtime artifact showing a photo-bearing turn completes. 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 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Needs proof Needs real behavior proof before merge: The stated evidence is mock-supervisor testing only; add a redacted after-fix Claude CLI terminal output, stream log, or runtime artifact showing a photo-bearing turn completes. 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 7 items Current-main behavior: Current main counts raw JSONL characters, retains raw lines, and feeds those lines to the shared streaming parser, so large echoed payloads can exhaust the aggregate turn limit.
Patch scope defect: The proposed recursive walk changes every image-shaped object with source.data, before record-type handling, rather than only recognized tool-result envelopes.
Consumed control input: A control request’s input is retained as toolInput and returned to Claude as updatedInput, so broad mutation can alter a tool invocation rather than merely its accounting payload.
Findings 1 actionable finding [P1] Restrict payload stripping to tool-result envelopes
Security None None.

How this fits together

Claude CLI emits stream-json records to OpenClaw’s reusable live-session process. OpenClaw uses those records for turn limits, tool approval, tool events, transcript buffering, and the final agent response.

flowchart LR
  A[Claude CLI stream-json] --> B[Live-session line ingest]
  B --> C[Record classification]
  C --> D[Tool-result image payloads]
  C --> E[Tool approval inputs]
  D --> F[Bounded turn buffer]
  F --> G[Streaming event parser]
  E --> H[Claude control response]
Loading

Before merge

  • Add real behavior proof - Needs real behavior proof before merge: The stated evidence is mock-supervisor testing only; add a redacted after-fix Claude CLI terminal output, stream log, or runtime artifact showing a photo-bearing turn completes. 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.
  • Restrict payload stripping to tool-result envelopes (P1) - The recursive walk stubs every image-shaped value, including control_request.request.input; that object is returned to Claude as updatedInput. Limit it to recognized base64 tool-result envelopes and add preservation coverage for tool/control inputs. This prior P1 finding remains on unchanged code.
  • Resolve merge risk (P1) - The broad normalizer can replace image-shaped control-request or tool inputs before OpenClaw returns them to Claude, changing an existing live-session behavior.
  • Resolve merge risk (P1) - The PR has no redacted after-fix Claude CLI run, log, or artifact; mock supervisor tests do not establish the real stream contract.
  • Complete next step (P2) - A bounded repair can correct the unchanged P1, while the contributor separately supplies real behavior proof before merge.
  • Improve patch quality - Restrict the normalizer to recognized base64 tool-result envelopes and add preservation regressions.
  • Improve patch quality - Add a redacted real Claude CLI after-fix run showing the affected turn completes.

Findings

  • [P1] Restrict payload stripping to tool-result envelopes — src/agents/cli-runner/claude-live-session.ts:1354-1364
Agent review details

Security

None.

PR surface

Source +43, Tests +304. Total +347 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 46 3 +43
Tests 1 304 0 +304
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 350 3 +347

Review metrics

Metric Value Why it matters
Production versus test LOC production +43, tests +304 The new normalization capability is justified by bounded turn accounting, but its production scope must shrink to the owning tool-result envelopes.

Stored data model

Persistent data-model change detected: serialized state: src/agents/cli-runner/claude-live-session.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #119445
Summary: This PR is the candidate fix for the linked photo-heavy Claude live-session failure.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Scope the payload normalizer (recommended)
    Restrict stubbing to recognized base64 tool-result blocks and add preservation regressions for control and tool inputs before merge.

Technical review

Best possible solution:

Stub only base64 payloads inside recognized Claude tool-result envelopes, preserve every other record byte-for-byte, and prove both the control-input preservation and a real photo-bearing turn.

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

No high-confidence end-to-end reproduction is available here. Current main proves the raw accounting path and the PR supplies mock stream fixtures, but no real Claude CLI after-fix artifact is present.

Is this the best way to solve the issue?

No. Ingest-time normalization is the right owner boundary, but the recursive implementation is too broad; it must be constrained to recognized result envelopes and base64 sources.

Full review comments:

  • [P1] Restrict payload stripping to tool-result envelopes — src/agents/cli-runner/claude-live-session.ts:1354-1364
    The recursive walk stubs every image-shaped value, including control_request.request.input; that object is returned to Claude as updatedInput. Limit it to recognized base64 tool-result envelopes and add preservation coverage for tool/control inputs. This prior P1 finding remains on unchanged code.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.99

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 29175dd11e90.

Labels

Label justifications:

  • P1: The default Claude CLI path can abort a real photo-heavy agent turn at the aggregate output cap.
  • merge-risk: 🚨 compatibility: The current recursive mutation can alter already-supported control and tool input records rather than only echoed tool results.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The stated evidence is mock-supervisor testing only; add a redacted after-fix Claude CLI terminal output, stream log, or runtime artifact showing a photo-bearing turn completes. 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

Acceptance criteria:

  • [P1] node scripts/run-vitest.mjs src/agents/cli-runner/claude-live-session.image-payload.test.ts.
  • [P1] node scripts/run-vitest.mjs src/agents/cli-runner/claude-live-session.background-tasks.test.ts.

What I checked:

Likely related people:

  • Jason (Json): Current-main blame identifies this contributor on the live-session and shared parser boundary; older ownership is unavailable in the local history. (role: recent area contributor; confidence: low; commits: 141a16f7b39b; files: src/agents/cli-runner/claude-live-session.ts, src/agents/cli-output.ts)

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 (3 earlier review cycles)
  • reviewed 2026-08-05T05:05:39.945Z sha f1ce51e :: needs real behavior proof before merge. :: [P1] Restrict payload stripping to tool-result envelopes
  • reviewed 2026-08-05T08:12:16.191Z sha f1ce51e :: needs real behavior proof before merge. :: [P1] Restrict payload stripping to tool-result envelopes
  • reviewed 2026-08-05T09:29:10.307Z sha f1ce51e :: needs real behavior proof before merge. :: [P1] Restrict payload stripping to tool-result envelopes

@licheer-zte licheer-zte closed this Aug 5, 2026
@licheer-zte licheer-zte reopened this Aug 5, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 5, 2026
@licheer-zte

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review — the previous review lease expired without a completed review (placeholder comment from the last cycle). Please re-review this PR.

@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:

@licheer-zte licheer-zte closed this Aug 5, 2026
@licheer-zte licheer-zte reopened this Aug 5, 2026
@steipete

steipete commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Thanks for working on #119445! This is now fixed on current main by #119488 (1352332). The merged implementation handles both base64 images and PDFs in the shared Claude JSONL and managed-session paths, preserves bounded output accounting and approval/control-request inputs, and passed 313 focused regression tests. It resolves the same photo-heavy-turn failure, so this PR is superseded. Closing in favor of the landed fix; thank you for the contribution.

@steipete steipete closed this Aug 5, 2026
@vincentkoc vincentkoc added close:superseded PR close reason dedupe:child Duplicate issue/PR child in dedupe cluster labels Aug 5, 2026
@vincentkoc vincentkoc self-assigned this Aug 5, 2026
vincentkoc added a commit that referenced this pull request Aug 24, 2026
* fix(cli): image-heavy Claude CLI turns abort after about fifteen screenshots

The Claude CLI emits every image tool result twice in its stream-json
output: once inside `message.content[].tool_result.content[]` and once in
the `tool_use_result` field it echoes alongside the message. The
normalizer added in #119486 only walks the message copy, so the echoed
copy still counts against the 8 MiB per-turn raw-output budget and is
still retained in the live-turn line buffer.

Walk the whole parsed user record instead, so both copies are stubbed,
and cover the `tool_use_result.file.base64` shape the built-in image
read echoes. openclaw never reads `tool_use_result` (no references in
src), so nothing downstream changes.

[AI-assisted]

* fix(cli): make echoed-payload normalization stack-safe

Addresses the review finding on the recursive walker. The normalizer now
lives in its own module as one canonical entry point, walks the record
iteratively with an explicit stack, and falls back to raw accounting when
a record is too deeply nested for `JSON.stringify` to re-serialize.

Adds a 50,000-deep regression record, built as text because
`JSON.stringify` itself cannot serialize one that deep.

[AI-assisted]

* fix(cli): normalize Agent SDK REPL binary echoes

---------

Co-authored-by: Vincent Koc <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 25, 2026
* fix(cli): image-heavy Claude CLI turns abort after about fifteen screenshots

The Claude CLI emits every image tool result twice in its stream-json
output: once inside `message.content[].tool_result.content[]` and once in
the `tool_use_result` field it echoes alongside the message. The
normalizer added in openclaw#119486 only walks the message copy, so the echoed
copy still counts against the 8 MiB per-turn raw-output budget and is
still retained in the live-turn line buffer.

Walk the whole parsed user record instead, so both copies are stubbed,
and cover the `tool_use_result.file.base64` shape the built-in image
read echoes. openclaw never reads `tool_use_result` (no references in
src), so nothing downstream changes.

[AI-assisted]

* fix(cli): make echoed-payload normalization stack-safe

Addresses the review finding on the recursive walker. The normalizer now
lives in its own module as one canonical entry point, walks the record
iteratively with an explicit stack, and falls back to raw accounting when
a record is too deeply nested for `JSON.stringify` to re-serialize.

Adds a 50,000-deep regression record, built as text because
`JSON.stringify` itself cannot serialize one that deep.

[AI-assisted]

* fix(cli): normalize Agent SDK REPL binary echoes

---------

Co-authored-by: Vincent Koc <[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 close:superseded PR close reason dedupe:child Duplicate issue/PR child in dedupe cluster merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: M 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

3 participants