Skip to content

Commit 8803855

Browse files
authored
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 #119488 and #119445.
1 parent 70a8191 commit 8803855

4 files changed

Lines changed: 212 additions & 27 deletions

File tree

‎src/agents/cli-output.test.ts‎

Lines changed: 114 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3509,7 +3509,10 @@ describe("createCliJsonlStreamingParser", () => {
35093509
}
35103510
});
35113511

3512-
it("counts raw Claude lines claimed by plugin parsers before dispatching their events", () => {
3512+
it.each([
3513+
{ name: "echoed media bytes", padded: false },
3514+
{ name: "surrounding raw whitespace", padded: true },
3515+
])("counts $name claimed by Claude plugin parsers before dispatch", ({ padded }) => {
35133516
const pluginLines: string[] = [];
35143517
const assistantDeltas: string[] = [];
35153518
const parser = createCliJsonlStreamingParser({
@@ -3521,7 +3524,7 @@ describe("createCliJsonlStreamingParser", () => {
35213524
},
35223525
onAssistantDelta: (delta) => assistantDeltas.push(delta.delta),
35233526
});
3524-
const rawLine = JSON.stringify({
3527+
const semanticLine = JSON.stringify({
35253528
type: "user",
35263529
message: {
35273530
content: [
@@ -3534,22 +3537,128 @@ describe("createCliJsonlStreamingParser", () => {
35343537
source: {
35353538
type: "base64",
35363539
media_type: "image/png",
3537-
data: "a".repeat(4_300_000),
3540+
data: padded ? "YQ==" : "a".repeat(4_300_000),
35383541
},
35393542
},
35403543
],
35413544
},
35423545
],
35433546
},
35443547
});
3548+
const rawLine = padded ? `${" ".repeat(4_300_000)}${semanticLine}` : semanticLine;
35453549

35463550
parser.push(`${rawLine}\n${rawLine}\n`);
35473551

3548-
expect(pluginLines).toEqual([rawLine, rawLine]);
3552+
expect(pluginLines).toEqual([semanticLine, semanticLine]);
35493553
expect(assistantDeltas).toEqual(["claimed"]);
35503554
expect(parser.getErrorText()).toContain("JSONL output exceeded");
35513555
});
35523556

3557+
it("counts actual blank Claude frames without invoking hooks or inventing a finish frame", () => {
3558+
const parseJsonlEvent = vi.fn(() => null);
3559+
const createParser = () =>
3560+
createCliJsonlStreamingParser({
3561+
backend: { command: "claude", output: "jsonl", jsonlDialect: "claude-stream-json" },
3562+
providerId: "claude-cli",
3563+
parseJsonlEvent,
3564+
onAssistantDelta: () => {},
3565+
});
3566+
const completeParser = createParser();
3567+
completeParser.push("\r\n".repeat(20_000));
3568+
completeParser.finish();
3569+
3570+
expect(completeParser.getErrorText()).toBeNull();
3571+
expect(parseJsonlEvent).not.toHaveBeenCalled();
3572+
3573+
const overflowParser = createParser();
3574+
overflowParser.push("\n".repeat(20_001));
3575+
3576+
expect(overflowParser.getErrorText()).toContain("exceeded 20000 lines");
3577+
expect(parseJsonlEvent).not.toHaveBeenCalled();
3578+
});
3579+
3580+
it.each([
3581+
{
3582+
name: "whitespace-only records",
3583+
createLine: () => " ".repeat(4_300_000),
3584+
},
3585+
{
3586+
name: "padding around valid JSON",
3587+
createLine: () => `${" ".repeat(4_300_000)}{}`,
3588+
},
3589+
{
3590+
name: "formatting inside a compacted media record",
3591+
createLine: () =>
3592+
JSON.stringify({
3593+
type: "user",
3594+
message: {
3595+
content: [
3596+
{
3597+
type: "tool_result",
3598+
tool_use_id: "padded-image",
3599+
content: [
3600+
{
3601+
type: "image",
3602+
source: { type: "base64", media_type: "image/png", data: "YQ==" },
3603+
},
3604+
],
3605+
},
3606+
],
3607+
},
3608+
}).replace('"message":', `"message":${" ".repeat(4_300_000)}`),
3609+
},
3610+
])("charges $name against the Claude raw-output budget", ({ createLine }) => {
3611+
const parser = createCliJsonlStreamingParser({
3612+
backend: { command: "claude", output: "jsonl", jsonlDialect: "claude-stream-json" },
3613+
providerId: "claude-cli",
3614+
onAssistantDelta: () => {},
3615+
});
3616+
const line = createLine();
3617+
3618+
parser.push(`${line}\n${line}\n`);
3619+
3620+
expect(parser.getErrorText()).toContain("JSONL output exceeded 8388608 characters");
3621+
});
3622+
3623+
it("normalizes empty Claude image data without treating zero omitted bytes as unchanged", () => {
3624+
const results: CliToolResultDelta[] = [];
3625+
const parser = createCliJsonlStreamingParser({
3626+
backend: { command: "claude", output: "jsonl", jsonlDialect: "claude-stream-json" },
3627+
providerId: "claude-cli",
3628+
onAssistantDelta: () => {},
3629+
onToolResult: (result) => results.push(result),
3630+
});
3631+
3632+
parser.push(
3633+
`${JSON.stringify({
3634+
type: "user",
3635+
message: {
3636+
content: [
3637+
{
3638+
type: "tool_result",
3639+
tool_use_id: "empty-image",
3640+
content: [
3641+
{
3642+
type: "image",
3643+
source: { type: "base64", media_type: "image/png", data: "" },
3644+
},
3645+
],
3646+
},
3647+
],
3648+
},
3649+
})}\n`,
3650+
);
3651+
3652+
expect(results[0]?.result).toEqual([
3653+
{
3654+
type: "image",
3655+
source: { type: "base64", media_type: "image/png" },
3656+
omitted: true,
3657+
bytes: 0,
3658+
},
3659+
]);
3660+
});
3661+
35533662
it("still enforces raw Claude line and retained-text limits", () => {
35543663
const createParser = () =>
35553664
createCliJsonlStreamingParser({
@@ -3649,7 +3758,7 @@ describe("createCliJsonlStreamingParser", () => {
36493758
],
36503759
},
36513760
});
3652-
parser.push(`${rawLine}\n`);
3761+
parser.push(`\n \t\r\n${rawLine}\n`);
36533762

36543763
expect(observedLines).toEqual([rawLine]);
36553764
});

‎src/agents/cli-output.ts‎

Lines changed: 28 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -600,12 +600,13 @@ export function frameBoundedCliJsonlChunk(
600600
/** Drops Claude's echoed binary bytes before they enter retained tool/transcript state. */
601601
export function normalizeClaudeCliStreamJsonRecord(
602602
parsed: Record<string, unknown>,
603-
): string | undefined {
603+
): { line: string; omittedRawChars: number } | undefined {
604604
if (parsed.type !== "user" || !isRecord(parsed.message)) {
605605
return undefined;
606606
}
607607
const content = Array.isArray(parsed.message.content) ? parsed.message.content : [];
608608
let normalized = false;
609+
let omittedRawChars = 0;
609610
for (const result of content) {
610611
if (!isRecord(result) || result.type !== "tool_result" || !Array.isArray(result.content)) {
611612
continue;
@@ -627,10 +628,11 @@ export function normalizeClaudeCliStreamJsonRecord(
627628
block.source = source;
628629
block.omitted = true;
629630
block.bytes = estimateBase64DecodedBytes(data);
631+
omittedRawChars += data.length;
630632
normalized = true;
631633
}
632634
}
633-
return normalized ? JSON.stringify(parsed) : undefined;
635+
return normalized ? { line: JSON.stringify(parsed), omittedRawChars } : undefined;
634636
}
635637

636638
function streamJsonOutputLimitErrorText(kind: "raw" | "line" | "lines", limit: number): string {
@@ -1639,8 +1641,8 @@ export function createCliJsonlStreamingParser(params: {
16391641
};
16401642
};
16411643

1642-
const accountClaudeJsonlLine = (line: string): boolean => {
1643-
rawChars += line.length + 1;
1644+
const accountClaudeJsonlLine = (lineChars: number): boolean => {
1645+
rawChars += lineChars + 1;
16441646
if (rawChars <= outputLimits.maxTurnRawChars) {
16451647
return true;
16461648
}
@@ -1649,7 +1651,7 @@ export function createCliJsonlStreamingParser(params: {
16491651
return false;
16501652
};
16511653

1652-
const handleCustomJsonlLine = (line: string): boolean => {
1654+
const handleCustomJsonlLine = (line: string, rawLine: string): boolean => {
16531655
if (parseErrorText) {
16541656
return true;
16551657
}
@@ -1672,7 +1674,7 @@ export function createCliJsonlStreamingParser(params: {
16721674
if (parsed == null) {
16731675
return false;
16741676
}
1675-
if (claudeStreamJson && !accountClaudeJsonlLine(line)) {
1677+
if (claudeStreamJson && !accountClaudeJsonlLine(rawLine.length)) {
16761678
return true;
16771679
}
16781680
for (const event of Array.isArray(parsed) ? parsed : [parsed]) {
@@ -1937,8 +1939,11 @@ export function createCliJsonlStreamingParser(params: {
19371939
};
19381940

19391941
const handleJsonlLine = (rawLine: string) => {
1942+
if (parseErrorText) {
1943+
return;
1944+
}
19401945
const line = rawLine.trim();
1941-
if (!line || parseErrorText) {
1946+
if (!line && !claudeStreamJson) {
19421947
return;
19431948
}
19441949
rawLines += 1;
@@ -1947,17 +1952,24 @@ export function createCliJsonlStreamingParser(params: {
19471952
lineBuffer.pending = "";
19481953
return;
19491954
}
1950-
if (handleCustomJsonlLine(line)) {
1955+
if (!line) {
1956+
accountClaudeJsonlLine(rawLine.length);
1957+
return;
1958+
}
1959+
if (handleCustomJsonlLine(line, rawLine)) {
19511960
return;
19521961
}
19531962
const parsedRecords = parseJsonRecordCandidates(line);
19541963
if (claudeStreamJson) {
1955-
const normalizedLine =
1964+
const normalized =
19561965
parsedRecords.length === 1
1957-
? (normalizeClaudeCliStreamJsonRecord(parsedRecords[0]!) ?? line)
1958-
: line;
1959-
// Claude repeats tool-returned media in stdout; only retained normalized bytes count.
1960-
if (!accountClaudeJsonlLine(normalizedLine)) {
1966+
? normalizeClaudeCliStreamJsonRecord(parsedRecords[0]!)
1967+
: undefined;
1968+
// Exempt actual media bytes only; JSON serialization must not erase wire whitespace.
1969+
const retainedChars = normalized
1970+
? Math.max(normalized.line.length, rawLine.length - normalized.omittedRawChars)
1971+
: rawLine.length;
1972+
if (!accountClaudeJsonlLine(retainedChars)) {
19611973
return;
19621974
}
19631975
}
@@ -1994,7 +2006,9 @@ export function createCliJsonlStreamingParser(params: {
19942006
}
19952007
const tail = lineBuffer.pending;
19962008
lineBuffer.pending = "";
1997-
handleJsonlLine(tail);
2009+
if (tail) {
2010+
handleJsonlLine(tail);
2011+
}
19982012
finishTaggedReasoningMessage();
19992013
if (classifyClaudeCommentary) {
20002014
flushPendingClaudeAssistantText();

‎src/agents/cli-runner.spawn.test.ts‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2735,6 +2735,54 @@ describe("runCliAgent spawn path", () => {
27352735
);
27362736
});
27372737

2738+
it.each([
2739+
{
2740+
name: "a coalesced blank-frame flood",
2741+
createChunk: () => "\n".repeat(20_001),
2742+
},
2743+
{
2744+
name: "whitespace-only records exceeding the raw budget",
2745+
createChunk: () => `${" ".repeat(4_300_000)}\n${" ".repeat(4_300_000)}\n`,
2746+
},
2747+
{
2748+
name: "valid JSON padded beyond the raw budget",
2749+
createChunk: () => `${" ".repeat(4_300_000)}{}\n${" ".repeat(4_300_000)}{}\n`,
2750+
},
2751+
{
2752+
name: "internal formatting around compacted Claude media",
2753+
createChunk: () => {
2754+
const line = JSON.stringify({
2755+
type: "user",
2756+
message: {
2757+
content: [
2758+
{
2759+
type: "tool_result",
2760+
tool_use_id: "padded-live-image",
2761+
content: [
2762+
{
2763+
type: "image",
2764+
source: { type: "base64", media_type: "image/png", data: "YQ==" },
2765+
},
2766+
],
2767+
},
2768+
],
2769+
},
2770+
}).replace('"message":', `"message":${" ".repeat(4_300_000)}`);
2771+
return `${line}\n${line}\n`;
2772+
},
2773+
},
2774+
])("rejects $name from the managed Claude live session", async ({ createChunk }) => {
2775+
const live: ReturnType<typeof mockClaudeLiveRun> = mockClaudeLiveRun(supervisorSpawnMock, {
2776+
onWrite: () => {
2777+
live.spawnInput.onStdout?.(createChunk());
2778+
},
2779+
});
2780+
2781+
await expect(executePreparedCliRun(buildClaudeLiveRunContext())).rejects.toThrow(
2782+
"Claude CLI turn output exceeded limit.",
2783+
);
2784+
});
2785+
27382786
it("reports Claude live session reply backends as streaming until the turn finishes", async () => {
27392787
let markWriteReady: (() => void) | undefined;
27402788
const writeReady = new Promise<void>((resolve) => {

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

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1317,10 +1317,30 @@ function handleClaudeLiveControlRequest(
13171317
})();
13181318
}
13191319

1320+
function pushClaudeLiveTurnLine(
1321+
session: ClaudeLiveSession,
1322+
turn: ClaudeLiveTurn,
1323+
line: string,
1324+
): boolean {
1325+
turn.streamingParser.push(`${line}\n`);
1326+
if (!turn.streamingParser.getErrorText()) {
1327+
return true;
1328+
}
1329+
closeLiveSession(
1330+
session,
1331+
"abort",
1332+
createOutputLimitError(session, "Claude CLI turn output exceeded limit."),
1333+
);
1334+
return false;
1335+
}
1336+
13201337
function handleClaudeLiveLine(session: ClaudeLiveSession, line: string): void {
13211338
const turn = session.currentTurn;
13221339
const trimmed = line.trim();
13231340
if (!trimmed) {
1341+
if (turn) {
1342+
pushClaudeLiveTurnLine(session, turn, line);
1343+
}
13241344
return;
13251345
}
13261346
const parsed = parseClaudeLiveJsonLine(trimmed);
@@ -1367,17 +1387,11 @@ function handleClaudeLiveLine(session: ClaudeLiveSession, line: string): void {
13671387
) {
13681388
turn.hasReplayUnsafeActivity = true;
13691389
}
1370-
const normalizedLine = normalizeClaudeCliStreamJsonRecord(parsed) ?? trimmed;
1390+
const normalizedLine = normalizeClaudeCliStreamJsonRecord(parsed)?.line ?? trimmed;
13711391
turn.rawLines.push(normalizedLine);
13721392
applyBackgroundTasksChanged(session, parsed);
13731393
const toolEventCountBefore = turn.toolEventCount;
1374-
turn.streamingParser.push(`${normalizedLine}\n`);
1375-
if (turn.streamingParser.getErrorText()) {
1376-
closeLiveSession(
1377-
session,
1378-
"abort",
1379-
createOutputLimitError(session, "Claude CLI turn output exceeded limit."),
1380-
);
1394+
if (!pushClaudeLiveTurnLine(session, turn, line)) {
13811395
return;
13821396
}
13831397
turn.sessionId = parsedSessionId ?? turn.sessionId;

0 commit comments

Comments
 (0)