Skip to content

Commit f1ce51e

Browse files
committed
fix(cli): meter base64 image payloads as stubs in Claude live session 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 #119445
1 parent a1d20ae commit f1ce51e

2 files changed

Lines changed: 350 additions & 3 deletions

File tree

Lines changed: 304 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,304 @@
1+
/** Claude live session: base64 image payloads in tool_result lines are metered as stubs. */
2+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3+
import {
4+
setDiagnosticsEnabledForProcess,
5+
waitForDiagnosticEventsDrained,
6+
} from "../../infra/diagnostic-events.js";
7+
import {
8+
resetDiagnosticRunActivityForTest,
9+
startDiagnosticRunActivityTracking,
10+
} from "../../logging/diagnostic-run-activity.js";
11+
import type { getProcessSupervisor } from "../../process/supervisor/index.js";
12+
import type { CliToolResultDelta } from "../cli-output.js";
13+
import {
14+
restoreCliRunnerPrepareTestDeps,
15+
supervisorSpawnMock,
16+
} from "../cli-runner.test-support.js";
17+
import { runClaudeLiveSessionTurn } from "./claude-live-session.js";
18+
import { resetClaudeLiveSessionsForTest } from "./claude-live-session.test-support.js";
19+
import { setCliRunnerExecuteTestDeps } from "./execute.test-support.js";
20+
import { writeCliSystemPromptFile } from "./helpers.js";
21+
import type { PreparedCliRunContext } from "./types.js";
22+
23+
vi.mock("../../plugin-sdk/anthropic-cli.js", () => ({
24+
CLAUDE_CLI_BACKEND_ID: "claude-cli",
25+
isClaudeCliProvider: (providerId: string) => providerId === "claude-cli",
26+
}));
27+
28+
type ProcessSupervisor = ReturnType<typeof getProcessSupervisor>;
29+
type SupervisorSpawnFn = ProcessSupervisor["spawn"];
30+
31+
beforeEach(() => {
32+
setDiagnosticsEnabledForProcess(true);
33+
resetDiagnosticRunActivityForTest();
34+
startDiagnosticRunActivityTracking();
35+
resetClaudeLiveSessionsForTest();
36+
restoreCliRunnerPrepareTestDeps();
37+
setCliRunnerExecuteTestDeps({ writeCliSystemPromptFile });
38+
supervisorSpawnMock.mockClear();
39+
});
40+
41+
afterEach(async () => {
42+
vi.restoreAllMocks();
43+
vi.useRealTimers();
44+
resetDiagnosticRunActivityForTest();
45+
resetClaudeLiveSessionsForTest();
46+
await waitForDiagnosticEventsDrained();
47+
});
48+
49+
function buildPreparedCliRunContext(params: {
50+
runId: string;
51+
sessionId?: string;
52+
sessionKey?: string;
53+
}): PreparedCliRunContext {
54+
const backend = {
55+
command: "claude",
56+
args: ["-p", "--output-format", "stream-json"],
57+
output: "jsonl" as const,
58+
input: "stdin" as const,
59+
modelArg: "--model",
60+
sessionArgs: ["--session-id", "{sessionId}"],
61+
sessionMode: "always" as const,
62+
systemPromptFileArg: "--append-system-prompt-file",
63+
systemPromptWhen: "first" as const,
64+
serialize: true,
65+
liveSession: "claude-stdio" as const,
66+
};
67+
return {
68+
params: {
69+
sessionId: params.sessionId ?? "s-img",
70+
sessionKey: params.sessionKey ?? "agent:main:img",
71+
sessionFile: "/tmp/session.jsonl",
72+
workspaceDir: "/tmp",
73+
prompt: "hi",
74+
provider: "claude-cli",
75+
model: "sonnet",
76+
timeoutMs: 60_000,
77+
runId: params.runId,
78+
},
79+
started: Date.now(),
80+
workspaceDir: "/tmp",
81+
backendResolved: {
82+
id: "claude-cli",
83+
config: backend,
84+
bundleMcp: true,
85+
pluginId: "anthropic",
86+
},
87+
preparedBackend: {
88+
backend,
89+
env: {},
90+
},
91+
reusableCliSession: { mode: "none" },
92+
hadSessionFile: false,
93+
contextEngineConfig: {},
94+
modelId: "sonnet",
95+
normalizedModel: "sonnet",
96+
systemPrompt: "You are a helpful assistant.",
97+
systemPromptReport: {} as PreparedCliRunContext["systemPromptReport"],
98+
bootstrapPromptWarningLines: [],
99+
authEpochVersion: 2,
100+
};
101+
}
102+
103+
function getProcessSupervisorForTest() {
104+
return {
105+
spawn: (params: Parameters<SupervisorSpawnFn>[0]) =>
106+
supervisorSpawnMock(params) as ReturnType<SupervisorSpawnFn>,
107+
cancel: vi.fn(),
108+
cancelScope: vi.fn(),
109+
getRecord: vi.fn(),
110+
};
111+
}
112+
113+
function installLiveStdoutDriver(): {
114+
cancel: ReturnType<typeof vi.fn>;
115+
userInputUuids: string[];
116+
stdout: {
117+
emit: (chunk: string) => void;
118+
waitReady: () => Promise<void>;
119+
};
120+
} {
121+
let stdoutListener: ((chunk: string) => void) | undefined;
122+
const cancel = vi.fn();
123+
const userInputUuids: string[] = [];
124+
let markReady: (() => void) | undefined;
125+
const ready = new Promise<void>((resolve) => {
126+
markReady = resolve;
127+
});
128+
const stdin = {
129+
write: vi.fn((data: string, cb?: (err?: Error | null) => void) => {
130+
const parsed = JSON.parse(data) as { type?: string; uuid?: string };
131+
if (parsed.type === "user" && typeof parsed.uuid === "string") {
132+
userInputUuids.push(parsed.uuid);
133+
stdoutListener?.(
134+
jsonl([{ type: "command_lifecycle", command_uuid: parsed.uuid, state: "started" }]),
135+
);
136+
}
137+
cb?.();
138+
markReady?.();
139+
}),
140+
end: vi.fn(),
141+
};
142+
supervisorSpawnMock.mockImplementation(async (...args: unknown[]) => {
143+
const input = (args[0] ?? {}) as { onStdout?: (chunk: string) => void };
144+
stdoutListener = input.onStdout;
145+
return {
146+
runId: "live-img-run",
147+
pid: 4242,
148+
startedAtMs: Date.now(),
149+
stdin,
150+
wait: vi.fn(() => new Promise(() => {})),
151+
cancel,
152+
};
153+
});
154+
return {
155+
cancel,
156+
userInputUuids,
157+
stdout: {
158+
emit: (chunk: string) => {
159+
stdoutListener?.(chunk);
160+
},
161+
waitReady: () => ready,
162+
},
163+
};
164+
}
165+
166+
function jsonl(lines: unknown[]): string {
167+
return lines.map((line) => JSON.stringify(line)).join("\n") + "\n";
168+
}
169+
170+
function startLiveTurn(params: {
171+
runId: string;
172+
onToolResult?: (delta: CliToolResultDelta) => void;
173+
}) {
174+
const context = buildPreparedCliRunContext({ runId: params.runId });
175+
return runClaudeLiveSessionTurn({
176+
context,
177+
args: context.preparedBackend.backend.args ?? [],
178+
env: {},
179+
prompt: "hi",
180+
useResume: false,
181+
noOutputTimeoutMs: 5_000,
182+
getProcessSupervisor: getProcessSupervisorForTest,
183+
onAssistantDelta: () => {},
184+
onToolResult: params.onToolResult,
185+
cleanup: async () => {},
186+
});
187+
}
188+
189+
function imageToolResultLine(params: {
190+
toolCallId: string;
191+
base64: string;
192+
}): Record<string, unknown> {
193+
return {
194+
type: "user",
195+
session_id: "live-img",
196+
message: {
197+
role: "user",
198+
content: [
199+
{
200+
type: "tool_result",
201+
tool_use_id: params.toolCallId,
202+
content: [
203+
{
204+
type: "image",
205+
source: {
206+
type: "base64",
207+
media_type: "image/jpeg",
208+
data: params.base64,
209+
},
210+
},
211+
],
212+
},
213+
],
214+
},
215+
};
216+
}
217+
218+
describe("claude live session image payload metering", () => {
219+
it("completes a photo-heavy turn instead of tripping the raw-chars output cap", async () => {
220+
const driver = installLiveStdoutDriver();
221+
const resultPromise = startLiveTurn({ runId: "run-img-over-cap" });
222+
await driver.stdout.waitReady();
223+
224+
// Three tool_result lines carrying ~3 MiB of base64 image data each: the
225+
// turn-level raw-chars cap is 8 MiB, so without stub metering the turn
226+
// would abort with "Claude CLI turn output exceeded limit". Lines are
227+
// emitted one per chunk, as the CLI writes them; a single multi-MiB chunk
228+
// would instead trip the pending-line buffer cap.
229+
const bigImage = "A".repeat(3 * 1024 * 1024);
230+
for (const line of [
231+
{ type: "system", subtype: "init", session_id: "live-img" },
232+
{
233+
type: "assistant",
234+
session_id: "live-img",
235+
message: {
236+
role: "assistant",
237+
content: [{ type: "text", text: "Reading photos." }],
238+
},
239+
},
240+
imageToolResultLine({ toolCallId: "tool-img-1", base64: bigImage }),
241+
imageToolResultLine({ toolCallId: "tool-img-2", base64: bigImage }),
242+
imageToolResultLine({ toolCallId: "tool-img-3", base64: bigImage }),
243+
{
244+
type: "assistant",
245+
session_id: "live-img",
246+
message: {
247+
role: "assistant",
248+
content: [{ type: "text", text: "Summarized the photos." }],
249+
},
250+
},
251+
{
252+
type: "result",
253+
subtype: "success",
254+
session_id: "live-img",
255+
result: "Summarized the photos.",
256+
stop_reason: "end_turn",
257+
},
258+
]) {
259+
driver.stdout.emit(`${JSON.stringify(line)}\n`);
260+
}
261+
262+
const result = await resultPromise;
263+
expect(result.output.text).toContain("Summarized the photos.");
264+
expect(driver.cancel).not.toHaveBeenCalled();
265+
});
266+
267+
it("feeds the streaming parser stubbed image payloads instead of raw base64", async () => {
268+
const driver = installLiveStdoutDriver();
269+
const onToolResult = vi.fn();
270+
const resultPromise = startLiveTurn({ runId: "run-img-stub", onToolResult });
271+
await driver.stdout.waitReady();
272+
273+
const bigImage = "A".repeat(1024 * 1024);
274+
driver.stdout.emit(
275+
jsonl([
276+
{ type: "system", subtype: "init", session_id: "live-img" },
277+
imageToolResultLine({ toolCallId: "tool-img-stub", base64: bigImage }),
278+
{
279+
type: "assistant",
280+
session_id: "live-img",
281+
message: {
282+
role: "assistant",
283+
content: [{ type: "text", text: "Done." }],
284+
},
285+
},
286+
{
287+
type: "result",
288+
subtype: "success",
289+
session_id: "live-img",
290+
result: "Done.",
291+
stop_reason: "end_turn",
292+
},
293+
]),
294+
);
295+
296+
await resultPromise;
297+
const delta = onToolResult.mock.calls[0]?.[0];
298+
expect(delta).toMatchObject({ toolCallId: "tool-img-stub" });
299+
const blocks = delta?.result as Array<Record<string, unknown>>;
300+
expect(Array.isArray(blocks)).toBe(true);
301+
const source = blocks[0]?.source as Record<string, unknown> | undefined;
302+
expect(source?.data).toBe(`[image: ${bigImage.length} base64 chars omitted]`);
303+
});
304+
});

‎src/agents/cli-runner/claude-live-session.ts‎

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1330,6 +1330,44 @@ function handleClaudeLiveControlRequest(
13301330
})();
13311331
}
13321332

1333+
/**
1334+
* Stubs base64 image payloads in a parsed Claude CLI stream-json line in
1335+
* place. Image bytes inside tool_result content blocks are dead weight for
1336+
* openclaw: the CLI backend already sent them to the model API and nothing
1337+
* downstream reads `source.data`. Metering them against maxTurnRawChars makes
1338+
* photo-heavy turns abort with a spurious output-limit error (#119445).
1339+
* Returns true when at least one payload was stubbed so callers only
1340+
* re-serialize lines that actually carried image data.
1341+
*/
1342+
function stripClaudeLiveImagePayloads(parsed: Record<string, unknown>): boolean {
1343+
let stubbed = false;
1344+
const visit = (node: unknown): void => {
1345+
if (Array.isArray(node)) {
1346+
for (const item of node) {
1347+
visit(item);
1348+
}
1349+
return;
1350+
}
1351+
if (!isRecord(node)) {
1352+
return;
1353+
}
1354+
if (
1355+
node.type === "image" &&
1356+
isRecord(node.source) &&
1357+
typeof node.source.data === "string" &&
1358+
node.source.data.length > 0
1359+
) {
1360+
node.source.data = `[image: ${node.source.data.length} base64 chars omitted]`;
1361+
stubbed = true;
1362+
}
1363+
for (const value of Object.values(node)) {
1364+
visit(value);
1365+
}
1366+
};
1367+
visit(parsed);
1368+
return stubbed;
1369+
}
1370+
13331371
function handleClaudeLiveLine(session: ClaudeLiveSession, line: string): void {
13341372
const turn = session.currentTurn;
13351373
const trimmed = line.trim();
@@ -1346,6 +1384,11 @@ function handleClaudeLiveLine(session: ClaudeLiveSession, line: string): void {
13461384
}
13471385
return;
13481386
}
1387+
// Meter base64 image payloads as stubs: image bytes inside tool_result
1388+
// content blocks are never consumed by openclaw (the CLI backend already
1389+
// sent them to the model API), but they dominate maxTurnRawChars accounting
1390+
// and abort photo-heavy turns with a spurious output-limit error (#119445).
1391+
const meteredLine = stripClaudeLiveImagePayloads(parsed) ? JSON.stringify(parsed) : trimmed;
13491392
const parsedSessionId = parseSessionId(parsed);
13501393
if (parsedSessionId) {
13511394
session.sessionId = parsedSessionId;
@@ -1380,7 +1423,7 @@ function handleClaudeLiveLine(session: ClaudeLiveSession, line: string): void {
13801423
) {
13811424
turn.hasReplayUnsafeActivity = true;
13821425
}
1383-
turn.rawChars += trimmed.length + 1;
1426+
turn.rawChars += meteredLine.length + 1;
13841427
if (
13851428
turn.rawChars > turn.outputLimits.maxTurnRawChars ||
13861429
turn.rawLines.length >= turn.outputLimits.maxTurnLines
@@ -1392,10 +1435,10 @@ function handleClaudeLiveLine(session: ClaudeLiveSession, line: string): void {
13921435
);
13931436
return;
13941437
}
1395-
turn.rawLines.push(trimmed);
1438+
turn.rawLines.push(meteredLine);
13961439
applyBackgroundTasksChanged(session, parsed);
13971440
const toolEventCountBefore = turn.toolEventCount;
1398-
turn.streamingParser.push(`${trimmed}\n`);
1441+
turn.streamingParser.push(`${meteredLine}\n`);
13991442
turn.sessionId = parsedSessionId ?? turn.sessionId;
14001443
noteClaudeLiveProgress(turn, parsed, turn.toolEventCount !== toolEventCountBefore);
14011444
handleClaudeLiveControlRequest(session, turn, parsed);

0 commit comments

Comments
 (0)