Skip to content

Commit e6ca526

Browse files
authored
fix: code mode dead-ends on oversized tool results instead of returning bounded output (#122924)
* fix(agents): bound code mode bridge results Return oversized bridge, guest output, and final values as bounded successful projections with actionable narrowing guidance. * refactor(agents): absorb code mode output bounds
1 parent 6076efc commit e6ca526

18 files changed

Lines changed: 409 additions & 305 deletions

‎docs/tools/code-mode.md‎

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -796,10 +796,15 @@ the bridge as JSON-compatible values with explicit size caps.
796796
type CodeModeOutput = { type: "text"; text: string } | { type: "json"; value: unknown };
797797
```
798798

799-
Rules: output order matches guest calls; output is capped by
800-
`maxOutputBytes`; non-serializable values are converted to plain strings or
801-
errors; binary values are not supported. Images and files travel through
802-
ordinary OpenClaw tools, not through the code-mode bridge.
799+
Rules: output order matches guest calls. Nested tool results, cumulative guest
800+
output, and the final value share the `maxOutputBytes` serialized UTF-8 budget.
801+
When a successful result exceeds the budget, OpenClaw returns a bounded value
802+
with `truncated: true`, a UTF-8-safe `prefix`, `omittedBytes`, and guidance to
803+
rerun with narrower arguments. Treat that marker as a successful partial result:
804+
reduce the search scope, paginate, select fewer files, or return a smaller
805+
projection. Non-serializable values are converted to plain strings or errors;
806+
binary values are not supported. Images and files travel through ordinary
807+
OpenClaw tools, not through the code-mode bridge.
803808

804809
## Tool catalog
805810

@@ -905,8 +910,10 @@ session.`.
905910
`completed` or `failed`, or is dropped on Gateway shutdown (nothing
906911
survives a restart: this is transient runtime state).
907912
- For read-only work, `exec` can set `restartSafe: true`. OpenClaw then rejects
908-
side-effecting catalog and namespace tool calls before execution and
909-
marks suspended results as replay-safe. If a restart interrupts `wait`,
913+
catalog and namespace tool surfaces that are not proven replay-safe before
914+
execution and marks suspended results as replay-safe. A generic exec surface
915+
is not replay-safe merely because one command appears read-only; recovery
916+
runs should use the audited read, grep, or find tools. If a restart interrupts `wait`,
910917
[restart recovery](/gateway/restart-recovery) reconstructs the turn from the
911918
transcript instead of restoring the process-local snapshot. The recovery
912919
turn itself remains limited to audited read-only core tools and explicitly
@@ -981,6 +988,9 @@ type CodeModeErrorCode =
981988
rejected module access, TypeScript transform failures, unknown/expired/
982989
wrong-scope `runId` values, and too many suspended runs. `runtime_unavailable`
983990
covers a QuickJS worker that fails to start or exits non-zero.
991+
`output_limit_exceeded` is reserved for a result that cannot be serialized into
992+
the bounded projection; ordinary oversized successful results are truncated and
993+
remain successful.
984994

985995
Errors returned to the guest are plain data; host `Error` instances, stack
986996
objects, prototypes, and host functions do not cross into QuickJS.

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

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { NODE_FS_LIST_DIR_COMMAND } from "../infra/node-commands.js";
66
import { emitSessionLifecycleEvent } from "../sessions/session-lifecycle-events.js";
77
import { parseNodeList } from "../shared/node-list-parse.js";
88
import type { NodeListNode } from "../shared/node-list-types.js";
9-
import { toCodeModeJsonSafe } from "./code-mode-json.js";
9+
import { boundCodeModeValue } from "./code-mode-json.js";
1010
import type { CodeModeNamespaceRuntime } from "./code-mode-namespaces.js";
1111
import type { PendingBridgeRequest, SettledBridgeRequest } from "./code-mode-runtime.js";
1212
import { readCodeModeSkill } from "./code-mode-skills.js";
@@ -393,6 +393,7 @@ export async function runBridgeRequest(params: {
393393
namespaceRuntime: CodeModeNamespaceRuntime;
394394
parentToolCallId: string;
395395
codeModeRunId: string;
396+
maxOutputBytes: number;
396397
ctx: ToolSearchToolContext;
397398
request: PendingBridgeRequest;
398399
signal?: AbortSignal;
@@ -542,7 +543,11 @@ export async function runBridgeRequest(params: {
542543
break;
543544
}
544545
}
545-
return { id: params.request.id, ok: true, value: toCodeModeJsonSafe(value) };
546+
return {
547+
id: params.request.id,
548+
ok: true,
549+
value: boundCodeModeValue(value, params.maxOutputBytes),
550+
};
546551
} catch (error) {
547552
return { id: params.request.id, ok: false, error: formatErrorMessage(error) };
548553
}

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

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { randomUUID } from "node:crypto";
22
import { codeModeReplayIdForToolCall } from "./code-mode-bridge.js";
33
import { awaitCodeModeDeadline } from "./code-mode-deadline.js";
4+
import { boundCodeModeResult } from "./code-mode-json.js";
45
import {
56
createCodeModeNamespaceRuntime,
67
type CodeModeNamespaceRuntime,
@@ -10,8 +11,7 @@ import {
1011
codeModeFailureCode,
1112
codeModeFailureMessage,
1213
createCodeModeApiFilesForRun,
13-
enforceOutputLimit,
14-
enforceResultLimit,
14+
boundOutputToLimit,
1515
enforceSnapshotPayloadLimits,
1616
prepareSource,
1717
resolveCodeModeConfig,
@@ -240,7 +240,7 @@ async function settleCodeModeResult(params: {
240240
let pending = params.pending ?? [];
241241
const activeRunId = params.activeRunId ?? `cm_${randomUUID()}`;
242242
const output = params.output;
243-
const deliveredOutputCount = params.deliveredOutputCount ?? 0;
243+
let deliveredOutputCount = params.deliveredOutputCount ?? 0;
244244
// One exec/wait call shares a single wall-clock deadline across its initial
245245
// worker run and this inline settle phase, so auto-draining bridge calls
246246
// cannot stack a second full `timeoutMs` budget on top of the run that
@@ -300,7 +300,6 @@ async function settleCodeModeResult(params: {
300300
enforceSnapshotPayloadLimits({
301301
snapshotBytes: result.snapshotBytes,
302302
config: params.config,
303-
output,
304303
});
305304
if (!params.reservedActiveRunSlot) {
306305
releaseReservation = reserveActiveRunSlot();
@@ -317,6 +316,7 @@ async function settleCodeModeResult(params: {
317316
pending.push(
318317
...createPendingBridgeStates({
319318
pendingRequests: newPendingRequests,
319+
config: params.config,
320320
runtime: params.runtime,
321321
namespaceRuntime: params.namespaceRuntime,
322322
parentToolCallId: params.parentToolCallId,
@@ -388,7 +388,9 @@ async function settleCodeModeResult(params: {
388388
),
389389
);
390390
output.push(...result.output);
391-
enforceOutputLimit(output, params.config);
391+
if (boundOutputToLimit(output, params.config)) {
392+
deliveredOutputCount = 0;
393+
}
392394
} catch (error) {
393395
cancelPendingBridgeStates(pending);
394396
throw error;
@@ -409,7 +411,8 @@ async function settleCodeModeResult(params: {
409411
cancelPendingBridgeStates(pending);
410412
return {
411413
status: "failed" as const,
412-
error: "restart-safe code mode cannot call side-effecting tools.",
414+
error:
415+
"restart-safe code mode cannot call tool surfaces that are not proven replay-safe; recovery runs must use audited read, grep, or find tools.",
413416
code: "invalid_input" as const,
414417
failurePhase: params.bridgeDispatch.started ? ("bridge" as const) : ("input" as const),
415418
bridgeDispatchStarted: params.bridgeDispatch.started,
@@ -426,7 +429,6 @@ async function settleCodeModeResult(params: {
426429
enforceSnapshotPayloadLimits({
427430
snapshotBytes: result.snapshotBytes,
428431
config: params.config,
429-
output,
430432
});
431433
// Reserve before launching fresh work; transferred snapshots must
432434
// obey the same process-wide active-run cap as initial suspensions.
@@ -443,6 +445,7 @@ async function settleCodeModeResult(params: {
443445
pending.push(
444446
...createPendingBridgeStates({
445447
pendingRequests: newPendingRequests,
448+
config: params.config,
446449
runtime: params.runtime,
447450
namespaceRuntime: params.namespaceRuntime,
448451
parentToolCallId: params.parentToolCallId,
@@ -499,20 +502,21 @@ async function settleCodeModeResult(params: {
499502
// Defensive cleanup covers aborts or terminal failures; successful runs have
500503
// already drained every dispatched call before releasing their snapshot.
501504
cancelPendingBridgeStates(pending);
502-
enforceResultLimit({
505+
const bounded = boundCodeModeResult({
503506
output,
504-
value: result.status === "completed" ? result.value : undefined,
505-
config: params.config,
507+
...(result.status === "completed" ? { value: result.value } : {}),
508+
maxOutputBytes: params.config.maxOutputBytes,
506509
});
507510
return {
508511
...result,
512+
...(result.status === "completed" ? { value: bounded.value } : {}),
509513
...(result.status === "failed"
510514
? {
511515
failurePhase: params.bridgeDispatch.started ? ("bridge" as const) : result.failurePhase,
512516
bridgeDispatchStarted: params.bridgeDispatch.started,
513517
}
514518
: {}),
515-
output: output.slice(deliveredOutputCount),
519+
output: bounded.output.slice(bounded.truncated ? 0 : deliveredOutputCount),
516520
replaySafe: params.replaySafe,
517521
telemetry: telemetry(params.runtime),
518522
};
@@ -616,7 +620,7 @@ export async function runWait(params: {
616620
),
617621
);
618622
const output = [...state.output, ...result.output];
619-
enforceOutputLimit(output, state.config);
623+
const outputTruncated = boundOutputToLimit(output, state.config);
620624
return await settleCodeModeResult({
621625
result,
622626
output,
@@ -629,7 +633,7 @@ export async function runWait(params: {
629633
runtime: state.runtime,
630634
namespaceRuntime: state.namespaceRuntime,
631635
bridgeDispatch: { started: true },
632-
deliveredOutputCount: state.deliveredOutputCount,
636+
deliveredOutputCount: outputTruncated ? 0 : state.deliveredOutputCount,
633637
pending,
634638
activeRunId: state.runId,
635639
reservedActiveRunSlot: true,

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

Lines changed: 9 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -650,7 +650,7 @@ describe("headless Code Mode", () => {
650650
it("bounds output and returned values across separate worker legs", async () => {
651651
const tool = fakeTool("output_boundary", async () => jsonResult({ ok: true }));
652652

653-
const result = expectFailed(
653+
const result = expectCompleted(
654654
await runCodeModeScriptHeadless({
655655
ctx: createHeadlessHarness([tool]),
656656
code: `
@@ -662,7 +662,11 @@ describe("headless Code Mode", () => {
662662
}),
663663
);
664664

665-
expect(result.code).toBe("output_limit_exceeded");
665+
expect(JSON.stringify(result)).toContain("rerun with narrower args");
666+
expect(
667+
Buffer.byteLength(JSON.stringify(result.output), "utf8") +
668+
Buffer.byteLength(JSON.stringify(result.value), "utf8"),
669+
).toBeLessThanOrEqual(1_024);
666670
expect(tool.execute).toHaveBeenCalledOnce();
667671
});
668672

@@ -891,29 +895,15 @@ describe("headless Code Mode", () => {
891895
}
892896
});
893897

894-
it.each([
895-
{
896-
name: "syntax errors",
897-
code: "return (;",
898-
expectedCode: "internal_error",
899-
overrides: undefined,
900-
},
901-
{
902-
name: "output overages",
903-
code: `text("x".repeat(2048)); return true;`,
904-
expectedCode: "output_limit_exceeded",
905-
overrides: { maxOutputBytes: 1024 },
906-
},
907-
])("classifies $name", async ({ code, expectedCode, overrides }) => {
898+
it("classifies syntax errors", async () => {
908899
const result = expectFailed(
909900
await runCodeModeScriptHeadless({
910901
ctx: createHeadlessHarness(),
911-
code,
912-
overrides,
902+
code: "return (;",
913903
}),
914904
);
915905

916-
expect(result.code).toBe(expectedCode);
906+
expect(result.code).toBe("internal_error");
917907
});
918908

919909
it("clamps headless limit overrides to worker-safe bounds", () => {

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

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { randomUUID } from "node:crypto";
22
import { clampNumber } from "../utils.js";
33
import { awaitCodeModeDeadline } from "./code-mode-deadline.js";
4-
import { toCodeModeJsonSafe } from "./code-mode-json.js";
4+
import { boundCodeModeResult, toCodeModeJsonSafe } from "./code-mode-json.js";
55
import {
66
createCodeModeNamespaceRuntime,
77
type CodeModeNamespaceDescriptor,
@@ -16,8 +16,7 @@ import {
1616
codeModeFailureCode,
1717
codeModeFailureMessage,
1818
createCodeModeApiFilesForRun,
19-
enforceOutputLimit,
20-
enforceResultLimit,
19+
boundOutputToLimit,
2120
enforceSnapshotPayloadLimits,
2221
prepareSource,
2322
readPositiveInteger,
@@ -253,10 +252,19 @@ export async function runCodeModeScriptHeadless(params: {
253252

254253
while (true) {
255254
output.push(...result.output);
256-
enforceOutputLimit(output, config);
255+
boundOutputToLimit(output, config);
257256
if (result.status === "completed") {
258-
enforceResultLimit({ output, value: result.value, config });
259-
return { status: "completed", value: result.value, output, toolCallCount };
257+
const bounded = boundCodeModeResult({
258+
output,
259+
value: result.value,
260+
maxOutputBytes: config.maxOutputBytes,
261+
});
262+
return {
263+
status: "completed",
264+
value: bounded.value,
265+
output: bounded.output,
266+
toolCallCount,
267+
};
260268
}
261269
if (result.status === "failed") {
262270
return headlessFailure({
@@ -267,7 +275,7 @@ export async function runCodeModeScriptHeadless(params: {
267275
});
268276
}
269277

270-
enforceSnapshotPayloadLimits({ snapshotBytes: result.snapshotBytes, config, output });
278+
enforceSnapshotPayloadLimits({ snapshotBytes: result.snapshotBytes, config });
271279
const pendingIds = new Set(pending.map((entry) => entry.id));
272280
const newRequests = result.pendingRequests.filter((request) => !pendingIds.has(request.id));
273281
// Node discovery invokes the generic nodes tool for live status too;
@@ -292,6 +300,7 @@ export async function runCodeModeScriptHeadless(params: {
292300
pending.push(
293301
...createPendingBridgeStates({
294302
pendingRequests: newRequests,
303+
config,
295304
runtime,
296305
namespaceRuntime,
297306
parentToolCallId,

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

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import { jsonUtf8Bytes } from "../infra/json-utf8-bytes.js";
2+
import { truncateUtf8Prefix } from "../utils/utf8-truncate.js";
3+
14
export function toCodeModeJsonSafe(value: unknown): unknown {
25
if (value === undefined) {
36
return null;
@@ -26,3 +29,75 @@ export function toCodeModeJsonSafe(value: unknown): unknown {
2629
}
2730
}
2831
}
32+
33+
const TRUNCATION_GUIDANCE = "Output truncated; rerun with narrower args.";
34+
35+
function truncationMarker(serialized: string, maxBytes: number): unknown {
36+
const sourceBytes = Buffer.byteLength(serialized, "utf8");
37+
let prefix = truncateUtf8Prefix(serialized, maxBytes);
38+
while (true) {
39+
const prefixBytes = Buffer.byteLength(prefix, "utf8");
40+
const candidate = {
41+
truncated: true,
42+
omittedBytes: sourceBytes - prefixBytes,
43+
guidance: TRUNCATION_GUIDANCE,
44+
prefix,
45+
};
46+
const overflow = jsonUtf8Bytes(candidate) - maxBytes;
47+
if (overflow <= 0 || prefixBytes === 0) {
48+
return candidate;
49+
}
50+
prefix = truncateUtf8Prefix(prefix, Math.max(0, prefixBytes - overflow));
51+
}
52+
}
53+
54+
/** Bound one JSON-compatible value, preserving a UTF-8-safe serialized prefix. */
55+
export function boundCodeModeValue(value: unknown, maxBytes: number): unknown {
56+
const safe = toCodeModeJsonSafe(value);
57+
const serialized = JSON.stringify(safe) ?? "null";
58+
return Buffer.byteLength(serialized, "utf8") <= maxBytes
59+
? safe
60+
: truncationMarker(serialized, maxBytes);
61+
}
62+
63+
function boundOutputArray(output: unknown[], maxBytes: number): unknown[] {
64+
if (jsonUtf8Bytes(output) <= maxBytes) {
65+
return output;
66+
}
67+
return [truncationMarker(JSON.stringify(output), maxBytes - 2)];
68+
}
69+
70+
/** Bound cumulative guest output and the final value under one serialized byte budget. */
71+
export function boundCodeModeResult(params: {
72+
output: unknown[];
73+
value?: unknown;
74+
maxOutputBytes: number;
75+
}): { output: unknown[]; value?: unknown; truncated: boolean } {
76+
const hasValue = Object.hasOwn(params, "value");
77+
const safeOutput = params.output.map(toCodeModeJsonSafe);
78+
const safeValue = hasValue ? toCodeModeJsonSafe(params.value) : undefined;
79+
const outputBytes = safeOutput.length > 0 ? jsonUtf8Bytes(safeOutput) : 0;
80+
const valueBytes = hasValue ? jsonUtf8Bytes(safeValue) : 0;
81+
if (outputBytes + valueBytes <= params.maxOutputBytes) {
82+
return { output: safeOutput, ...(hasValue ? { value: safeValue } : {}), truncated: false };
83+
}
84+
if (safeOutput.length === 0) {
85+
return {
86+
output: [],
87+
...(hasValue ? { value: boundCodeModeValue(safeValue, params.maxOutputBytes) } : {}),
88+
truncated: true,
89+
};
90+
}
91+
92+
// Preserve both channels when both overflow: reserve half for the final
93+
// value, then let short values donate their unused share to guest output.
94+
const reservedValueBytes = hasValue
95+
? Math.min(valueBytes, Math.floor(params.maxOutputBytes / 2))
96+
: 0;
97+
const output = boundOutputArray(safeOutput, params.maxOutputBytes - reservedValueBytes);
98+
if (!hasValue) {
99+
return { output, truncated: true };
100+
}
101+
const remainingBytes = params.maxOutputBytes - jsonUtf8Bytes(output);
102+
return { output, value: boundCodeModeValue(safeValue, remainingBytes), truncated: true };
103+
}

0 commit comments

Comments
 (0)