Skip to content

Commit f273b0a

Browse files
committed
fix(code-mode): keep truncation counts tied to original output
Retain bounded original normalized JSON through worker legs and headless execution instead of truncating earlier markers. Preserve accepted output on later failures and share the output budget with terminal diagnostics. Fixes #132575.
1 parent 6b27585 commit f273b0a

20 files changed

Lines changed: 826 additions & 445 deletions

‎docs/tools/code-mode.md‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -680,7 +680,7 @@ initial execution that completes without suspending does not consume a slot.
680680
- the caller is not in the same run/session scope as the suspended run.
681681
- a `wait` is already in flight for that `runId`.
682682
- QuickJS-WASI restore fails.
683-
- resuming would exceed `maxOutputBytes` or `maxSnapshotBytes`.
683+
- resuming would exceed `maxSnapshotBytes`. Ordinary oversized successful output is truncated and remains successful.
684684

685685
## Guest runtime API
686686

@@ -1009,9 +1009,9 @@ the bridge as JSON-compatible values with explicit size caps.
10091009
type CodeModeOutput = { type: "text"; text: string } | { type: "json"; value: unknown };
10101010
```
10111011

1012-
Rules: output order matches guest calls. Nested tool results, cumulative guest
1013-
output, and the final value or failure diagnostic share the `maxOutputBytes`
1014-
serialized UTF-8 budget. Oversized errors retain their leading cause and end
1012+
Output order matches guest calls. Each nested tool result is bounded separately
1013+
by `maxOutputBytes`. Cumulative guest output and the final value or failure
1014+
diagnostic share one `maxOutputBytes` serialized UTF-8 budget across all waits. Oversized errors retain their leading cause and end
10151015
with `[error truncated]`; truncation does not turn a failure into success.
10161016
Catalog search rejects when its callable-name array cannot fit this budget;
10171017
narrow the query or lower `limit` and retry. For other successful results that
@@ -1023,6 +1023,12 @@ projection. Non-serializable values are converted to plain strings or errors;
10231023
binary values are not supported. Images and files travel through ordinary
10241024
OpenClaw tools, not through the code-mode bridge.
10251025

1026+
Marker prefixes and omitted-byte counts describe the original compact JSON after
1027+
normalization, including array brackets, separators, and JSON escaping. Ordinary
1028+
output is delivered incrementally. An unchanged cumulative summary is not repeated;
1029+
new output or a changed final-value/error reservation can produce a replacement
1030+
summary of that same original output.
1031+
10261032
## Tool catalog
10271033

10281034
The hidden catalog includes tools after effective policy filtering, in this

‎src/agents/code-mode-bridge.ts‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import type { NodeListNode } from "../shared/node-list-types.js";
1010
import { resolveEligibleNodeFromList } from "../shared/node-resolve.js";
1111
import { resolveSafeTimeoutDelayMs } from "../utils/timer-delay.js";
1212
import { redactCodeModeCatalogIds, type CodeModeCatalogProjection } from "./code-mode-catalog.js";
13-
import { boundCodeModeResult, boundCodeModeValue } from "./code-mode-json.js";
13+
import { boundCodeModeError, boundCodeModeValue } from "./code-mode-json.js";
1414
import type { CodeModeNamespaceRuntime } from "./code-mode-namespaces.js";
1515
import type { PendingBridgeRequest, SettledBridgeRequest } from "./code-mode-runtime.js";
1616
import { readCodeModeSkill } from "./code-mode-skills.js";
@@ -603,15 +603,14 @@ export async function runBridgeRequest(params: {
603603
const settled: SettledBridgeRequest = { id: params.request.id, ok: true, value };
604604
return effectReceipt ? registerToolEffectReceipt(settled, effectReceipt) : settled;
605605
} catch (error) {
606-
const bounded = boundCodeModeResult({
607-
error: redactCodeModeCatalogIds(formatErrorMessage(error), catalogProjection.bindings),
608-
output: [],
609-
maxOutputBytes: params.maxOutputBytes,
610-
});
606+
const boundedError = boundCodeModeError(
607+
redactCodeModeCatalogIds(formatErrorMessage(error), catalogProjection.bindings),
608+
params.maxOutputBytes,
609+
);
611610
const settled: SettledBridgeRequest = {
612611
id: params.request.id,
613612
ok: false,
614-
error: bounded.error,
613+
error: boundedError,
615614
};
616615
const trustedNoStart = consumeTrustedToolNoStartError(error);
617616
if (trustedNoStart) {

‎src/agents/code-mode-execution.ts‎

Lines changed: 24 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import {
88
type CodeModeCatalogProjection,
99
} from "./code-mode-catalog.js";
1010
import { awaitCodeModeDeadline } from "./code-mode-deadline.js";
11-
import { boundCodeModeResult } from "./code-mode-json.js";
11+
import { CodeModeOutputState } from "./code-mode-json.js";
1212
import {
1313
createCodeModeNamespaceRuntime,
1414
type CodeModeNamespaceRuntime,
@@ -19,7 +19,6 @@ import {
1919
codeModeFailureCode,
2020
codeModeFailureMessage,
2121
createCodeModeApiFilesForRun,
22-
boundOutputToLimit,
2322
enforceSnapshotPayloadLimits,
2423
prepareSource,
2524
toToolSearchConfig,
@@ -48,7 +47,6 @@ import {
4847
resumingRunIds,
4948
settledBridgeRequestsInCompletionOrder,
5049
storeSnapshotState,
51-
takeUndeliveredCodeModeRunOutput,
5250
telemetry,
5351
waitForPendingBridgeSettlement,
5452
type PendingBridgeState,
@@ -101,6 +99,7 @@ export async function runCodeModeExec(params: {
10199
const approvalWait = observeAgentRunApprovalWait(params.ctx);
102100
const owner = createCodeModeRunOwner(params.ctx);
103101
const signal = owner.bindCall(params.signal);
102+
const output = new CodeModeOutputState(config.maxOutputBytes);
104103
try {
105104
const source = await awaitCodeModeDeadline({
106105
operation: () => prepareSource({ code: params.code, language: params.language, config }),
@@ -129,10 +128,11 @@ export async function runCodeModeExec(params: {
129128
signal,
130129
),
131130
);
131+
output.append(result.output);
132132
return await settleCodeModeResult({
133133
owner,
134134
result,
135-
output: result.output,
135+
output,
136136
replaySafe: params.restartSafe,
137137
deadlineMs,
138138
parentToolCallId: params.toolCallId,
@@ -149,22 +149,18 @@ export async function runCodeModeExec(params: {
149149
});
150150
} catch (error) {
151151
const code = signal.aborted ? ("aborted" as const) : codeModeFailureCode(error);
152-
const bounded = boundCodeModeResult({
153-
error: signal.aborted ? "code mode execution aborted" : codeModeFailureMessage(error),
154-
output: [],
155-
maxOutputBytes: config.maxOutputBytes,
156-
});
157152
return {
158153
status: "failed" as const,
159-
error: bounded.error,
154+
...output.take({
155+
error: signal.aborted ? "code mode execution aborted" : codeModeFailureMessage(error),
156+
}),
160157
code,
161158
failurePhase: bridgeDispatch.started
162159
? ("bridge" as const)
163160
: code === "invalid_input"
164161
? ("input" as const)
165162
: ("host" as const),
166163
bridgeDispatchStarted: bridgeDispatch.started,
167-
output: [],
168164
replaySafe: params.restartSafe,
169165
telemetry: telemetry(runtime),
170166
};
@@ -254,7 +250,7 @@ async function waitForPending(
254250
async function settleCodeModeResult(params: {
255251
owner: CodeModeRunOwner;
256252
result: CodeModeWorkerResult;
257-
output: unknown[];
253+
output: CodeModeOutputState;
258254
replaySafe: boolean;
259255
parentToolCallId: string;
260256
codeModeReplayId: string;
@@ -264,7 +260,6 @@ async function settleCodeModeResult(params: {
264260
catalogProjection: CodeModeCatalogProjection;
265261
namespaceRuntime: CodeModeNamespaceRuntime;
266262
deadlineMs: number;
267-
deliveredOutputCount?: number;
268263
pending?: PendingBridgeState[];
269264
reservedActiveRunSlot?: boolean;
270265
bridgeDispatch: CodeModeBridgeDispatchState;
@@ -279,15 +274,14 @@ async function settleCodeModeResult(params: {
279274
}
280275
const activeRunId = params.owner.runId;
281276
const output = params.output;
282-
let deliveredOutputCount = params.deliveredOutputCount ?? 0;
283277
// One exec/wait call shares a single wall-clock deadline across its initial
284278
// worker run and this inline settle phase, so auto-draining bridge calls
285279
// cannot stack a second full `timeoutMs` budget on top of the run that
286280
// produced them. The deadline is also the only bound on sequential drain
287281
// rounds; maxPendingToolCalls stays a per-batch concurrency cap enforced in
288282
// the worker.
289283
const settleDeadline = () => params.deadlineMs + params.approvalWait.pausedMs;
290-
const abortedResult = () => codeModeAbortedResult({ ...params, output, deliveredOutputCount });
284+
const abortedResult = () => codeModeAbortedResult(params);
291285
// Bridge tool calls (search/describe/call/namespace) run through the same
292286
// policy-checked executor whether the model awaits them one at a time or in a
293287
// batch, so resolve them inline within the exec deadline and resume the VM
@@ -381,7 +375,6 @@ async function settleCodeModeResult(params: {
381375
catalogProjection: params.catalogProjection,
382376
namespaceRuntime: params.namespaceRuntime,
383377
output,
384-
deliveredOutputCount,
385378
bridgeDispatch: params.bridgeDispatch,
386379
});
387380
}
@@ -410,13 +403,10 @@ async function settleCodeModeResult(params: {
410403
params.signal,
411404
),
412405
);
406+
output.append(result.output);
413407
if (result.status === "waiting") {
414408
cancelPendingBridgeStatesById(pending, result.canceledRequestIds);
415409
}
416-
output.push(...result.output);
417-
if (boundOutputToLimit(output, params.config)) {
418-
deliveredOutputCount = 0;
419-
}
420410
} catch (error) {
421411
cancelPendingBridgeStates(pending);
422412
throw error;
@@ -438,13 +428,14 @@ async function settleCodeModeResult(params: {
438428
cancelPendingBridgeStates(pending);
439429
return {
440430
status: "failed" as const,
441-
error: result.pendingRequests.every((request) => request.method === "namespace")
442-
? "restart-safe code mode cannot call namespace tools."
443-
: "restart-safe code mode cannot call tool surfaces that are not proven replay-safe; recovery runs must use audited read, grep, or find tools.",
431+
...output.take({
432+
error: result.pendingRequests.every((request) => request.method === "namespace")
433+
? "restart-safe code mode cannot call namespace tools."
434+
: "restart-safe code mode cannot call tool surfaces that are not proven replay-safe; recovery runs must use audited read, grep, or find tools.",
435+
}),
444436
code: "invalid_input" as const,
445437
failurePhase: params.bridgeDispatch.started ? ("bridge" as const) : ("input" as const),
446438
bridgeDispatchStarted: params.bridgeDispatch.started,
447-
output: output.slice(deliveredOutputCount),
448439
replaySafe: true,
449440
telemetry: telemetry(params.runtime),
450441
};
@@ -497,7 +488,6 @@ async function settleCodeModeResult(params: {
497488
catalogProjection: params.catalogProjection,
498489
namespaceRuntime: params.namespaceRuntime,
499490
output,
500-
deliveredOutputCount,
501491
bridgeDispatch: params.bridgeDispatch,
502492
});
503493
} catch (error) {
@@ -510,11 +500,9 @@ async function settleCodeModeResult(params: {
510500
// Defensive cleanup covers aborts or terminal failures; successful runs have
511501
// already drained every dispatched call before releasing their snapshot.
512502
cancelPendingBridgeStates(pending);
513-
const bounded = boundCodeModeResult({
514-
output,
503+
const bounded = output.take({
515504
...(result.status === "completed" ? { value: result.value } : {}),
516505
...(result.status === "failed" ? { error: result.error } : {}),
517-
maxOutputBytes: params.config.maxOutputBytes,
518506
});
519507
const finalized = {
520508
...result,
@@ -526,7 +514,7 @@ async function settleCodeModeResult(params: {
526514
bridgeDispatchStarted: params.bridgeDispatch.started,
527515
}
528516
: {}),
529-
output: bounded.output.slice(bounded.outputTruncated ? 0 : deliveredOutputCount),
517+
output: bounded.output,
530518
replaySafe: params.replaySafe,
531519
telemetry: telemetry(params.runtime),
532520
};
@@ -590,16 +578,7 @@ export async function runWait(params: {
590578
// parking it would pin a process-global active-run slot until TTL expiry.
591579
if (signal.aborted) {
592580
disposeCodeModeRun(state.runId);
593-
return {
594-
status: "failed" as const,
595-
error: "code mode execution aborted",
596-
code: "aborted" as const,
597-
failurePhase: "bridge" as const,
598-
bridgeDispatchStarted: state.bridgeDispatch.started,
599-
output: takeUndeliveredCodeModeRunOutput(state),
600-
replaySafe: state.replaySafe,
601-
telemetry: telemetry(state.runtime),
602-
};
581+
return { ...codeModeAbortedResult(state), failurePhase: "bridge" as const };
603582
}
604583
// Not ready, or ready without a usable resume budget: keep the snapshot
605584
// so the next wait can resume with a fresh deadline instead of losing
@@ -611,7 +590,7 @@ export async function runWait(params: {
611590
reason: codeModeWaitingReason(pending.length > 0 ? pending : state.pending),
612591
pendingToolCalls: pendingToolCalls(pending.length > 0 ? pending : state.pending),
613592
replaySafe: state.replaySafe,
614-
output: takeUndeliveredCodeModeRunOutput(state),
593+
output: state.output.take().output,
615594
telemetry: telemetry(state.runtime),
616595
};
617596
}
@@ -642,12 +621,11 @@ export async function runWait(params: {
642621
signal,
643622
),
644623
);
645-
const output = [...state.output, ...result.output];
646-
const outputTruncated = boundOutputToLimit(output, state.config);
624+
state.output.append(result.output);
647625
return await settleCodeModeResult({
648626
owner: state.owner,
649627
result,
650-
output,
628+
output: state.output,
651629
replaySafe: state.replaySafe,
652630
deadlineMs,
653631
parentToolCallId: state.parentToolCallId,
@@ -659,7 +637,6 @@ export async function runWait(params: {
659637
namespaceRuntime: state.namespaceRuntime,
660638
bridgeDispatch: state.bridgeDispatch,
661639
approvalWait,
662-
deliveredOutputCount: outputTruncated ? 0 : state.deliveredOutputCount,
663640
pending,
664641
reservedActiveRunSlot: true,
665642
signal,
@@ -669,18 +646,14 @@ export async function runWait(params: {
669646
const aborted = signal.aborted;
670647
state.owner.close();
671648
cancelPendingBridgeStates(state.pending);
672-
const bounded = boundCodeModeResult({
673-
error: aborted ? "code mode execution aborted" : codeModeFailureMessage(error),
674-
output: takeUndeliveredCodeModeRunOutput(state),
675-
maxOutputBytes: state.config.maxOutputBytes,
676-
});
677649
return {
678650
status: "failed" as const,
679-
error: bounded.error,
651+
...state.output.take({
652+
error: aborted ? "code mode execution aborted" : codeModeFailureMessage(error),
653+
}),
680654
code: aborted ? ("aborted" as const) : codeModeFailureCode(error),
681655
failurePhase: "bridge" as const,
682656
bridgeDispatchStarted: state.bridgeDispatch.started,
683-
output: bounded.output,
684657
replaySafe: state.replaySafe,
685658
telemetry: telemetry(state.runtime),
686659
};

‎src/agents/code-mode-headless.test.ts‎

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -795,29 +795,6 @@ describe("headless Code Mode", () => {
795795
expect(result.toolCallCount).toBe(0);
796796
});
797797

798-
it("bounds output and returned values across separate worker legs", async () => {
799-
const tool = fakeTool("output_boundary", async () => jsonResult({ ok: true }));
800-
801-
const result = expectCompleted(
802-
await runCodeModeScriptHeadless({
803-
ctx: createHeadlessCodeModeHarness([tool]),
804-
code: `
805-
text("x".repeat(700));
806-
await output_boundary({});
807-
return "y".repeat(700);
808-
`,
809-
overrides: { maxOutputBytes: 1_024 },
810-
}),
811-
);
812-
813-
expect(JSON.stringify(result)).toContain("rerun with narrower args");
814-
expect(
815-
Buffer.byteLength(JSON.stringify(result.output), "utf8") +
816-
Buffer.byteLength(JSON.stringify(result.value), "utf8"),
817-
).toBeLessThanOrEqual(1_024);
818-
expect(tool.execute).toHaveBeenCalledOnce();
819-
});
820-
821798
it("honors cron payload tool budgets above the old headless cap", async () => {
822799
const tool = fakeTool("budgeted", async () => jsonResult({ ok: true }));
823800
const result = expectCompleted(

0 commit comments

Comments
 (0)