Skip to content

Commit 977bbe2

Browse files
authored
fix: agents continue after Code Mode tool and JavaScript errors (#128088)
* fix(agents): let code mode recover from ordinary tool failures * fix(agents): preserve read-only reconciliation after side effects * test(qa): track renamed code mode outcome owner * test(agents): prove read-only code mode reconciliation boundary
1 parent 955792c commit 977bbe2

14 files changed

Lines changed: 724 additions & 903 deletions

‎docs/tools/code-mode.md‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,32 @@ value into guessed field-dependent logic in the same program. Observe the raw
171171
value, then use a later `exec` for dependent composition. This costs an extra
172172
model turn, but prevents the model from guessing field names.
173173

174+
### Recover from tool errors
175+
176+
Nested tool failures are ordinary JavaScript errors. Guest code can catch them
177+
and return the information needed to choose the next action:
178+
179+
```javascript
180+
try {
181+
return await terminal({ action: "list" });
182+
} catch (error) {
183+
return { status: "unavailable", error: error.message };
184+
}
185+
```
186+
187+
JavaScript syntax errors, TypeScript transform errors, and tool failures proven
188+
to occur before execution become failed `exec` results that the model can read
189+
and correct across successive turns. A failed tool call does not automatically
190+
end the agent run when OpenClaw can prove that no nested action started.
191+
192+
OpenClaw does not automatically replay a failed program. If earlier calls
193+
already ran or a failed call may have partially applied, OpenClaw first limits
194+
recovery to an authorized read-only inspection of the current state. It does
195+
not expose writes, sends, shell commands, or other mutations during that
196+
reconciliation. Cancellation, explicitly terminal tool outcomes, sandbox
197+
restrictions, approval requirements, and tool-policy denials retain their
198+
existing behavior.
199+
174200
### Verify the active surface
175201

176202
To confirm the model payload shape while debugging, run the Gateway with
@@ -953,6 +979,15 @@ Nested calls project into the transcript as real tool calls so support
953979
bundles show what happened, with the projection identifying the parent
954980
code-mode tool call and the nested tool id.
955981

982+
Nested tool failures cross into the guest as catchable JavaScript errors. If
983+
guest code does not catch an error, `exec` or `wait` returns a failed tool
984+
result. Proven no-start failures and guest-only errors allow ordinary model
985+
recovery; possible nested side effects require authorized read-only
986+
reconciliation before any further action. Network-controlled tool output and
987+
errors retain their existing untrusted-content wrapping and sanitization;
988+
recovering from a failure does not grant new permissions or replay completed
989+
side effects.
990+
956991
Parallel nested calls are allowed up to `maxPendingToolCalls`.
957992

958993
## Run and snapshot lifecycle
@@ -1151,6 +1186,9 @@ Code mode coverage should prove:
11511186
- Tool Search control tools are hidden from both the model surface and the
11521187
hidden catalog
11531188
- nested calls preserve approval and hook behavior
1189+
- caught and uncaught nested failures remain recoverable without replaying
1190+
previously executed side effects
1191+
- network-controlled failures retain untrusted-content wrapping and sanitization
11541192
- shell `exec` is hidden from the model but callable as a guest global when
11551193
allowed
11561194
- recursive code-mode `exec` and `wait` are not callable from guest code

‎qa/scenarios/channels/qa-channel-failed-tool-terminal-finalization.yaml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ scenario:
2020
codeRefs:
2121
- src/agents/embedded-agent-runner/run/incomplete-turn-resolution.ts
2222
- src/agents/embedded-agent-runner/run/incomplete-turn-recovery.ts
23-
- src/agents/embedded-agent-runner/run/code-mode-repair.ts
23+
- src/agents/embedded-agent-runner/run/code-mode-outcome.ts
2424
- extensions/qa-lab/src/providers/mock-openai/server.ts
2525
execution:
2626
kind: flow
Lines changed: 256 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,256 @@
1+
import {
2+
createAssistantMessageEventStream,
3+
type AssistantMessage,
4+
type Context,
5+
type Model,
6+
} from "openclaw/plugin-sdk/llm";
7+
import { afterEach, describe, expect, it } from "vitest";
8+
import { applyCodeModeCatalog } from "./code-mode.js";
9+
import {
10+
createCodeModeHarness,
11+
pluginToolWithExecute,
12+
resetCodeModeTestState,
13+
} from "./code-mode.test-support.js";
14+
import { installCodeModeOutcomeHook } from "./embedded-agent-runner/run/code-mode-outcome.js";
15+
import { Agent } from "./runtime/index.js";
16+
import { isToolResultError } from "./tool-result-error.js";
17+
import { jsonResult, ToolInputError, type AnyAgentTool } from "./tools/common.js";
18+
19+
const model: Model = {
20+
id: "test-model",
21+
name: "Test Model",
22+
api: "openai-responses",
23+
provider: "test-provider",
24+
baseUrl: "https://example.test",
25+
reasoning: false,
26+
input: ["text"],
27+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
28+
contextWindow: 1_000,
29+
maxTokens: 1_000,
30+
};
31+
32+
function createAssistant(content: AssistantMessage["content"]): AssistantMessage {
33+
return {
34+
role: "assistant",
35+
content,
36+
api: model.api,
37+
provider: model.provider,
38+
model: model.id,
39+
usage: {
40+
input: 0,
41+
output: 0,
42+
cacheRead: 0,
43+
cacheWrite: 0,
44+
totalTokens: 0,
45+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
46+
},
47+
stopReason: content.some((entry) => entry.type === "toolCall") ? "toolUse" : "stop",
48+
timestamp: Date.now(),
49+
};
50+
}
51+
52+
async function runCodeModeAgent(params: { programs: string[]; hiddenTools: AnyAgentTool[] }) {
53+
const { config, catalogRef, tools } = createCodeModeHarness();
54+
applyCodeModeCatalog({
55+
tools: [...tools, ...params.hiddenTools],
56+
config,
57+
sessionId: "session-code-mode",
58+
sessionKey: "agent:main:main",
59+
runId: "run-code-mode",
60+
catalogRef,
61+
});
62+
const providerContexts: Context[] = [];
63+
let reconciliationCandidates = 0;
64+
const agent = new Agent({
65+
initialState: { model, tools },
66+
afterToolCall: async ({ result, isError }) => ({
67+
isError: isError || isToolResultError(result),
68+
}),
69+
streamFn: (_activeModel, context) => {
70+
providerContexts.push(context);
71+
const index = providerContexts.length - 1;
72+
const code = params.programs[index];
73+
const message = createAssistant(
74+
code === undefined
75+
? [{ type: "text", text: "recovered" }]
76+
: [{ type: "toolCall", id: `code-call-${index}`, name: "exec", arguments: { code } }],
77+
);
78+
const stream = createAssistantMessageEventStream();
79+
queueMicrotask(() => {
80+
stream.push({
81+
type: "done",
82+
reason: message.stopReason === "toolUse" ? "toolUse" : "stop",
83+
message,
84+
});
85+
stream.end();
86+
});
87+
return stream;
88+
},
89+
});
90+
installCodeModeOutcomeHook({
91+
agent,
92+
onReconciliationCandidate: () => {
93+
reconciliationCandidates += 1;
94+
},
95+
});
96+
await agent.prompt("finish the task despite tool errors");
97+
98+
return { agent, providerContexts, reconciliationCandidates };
99+
}
100+
101+
describe("Code Mode agent-loop error recovery", () => {
102+
afterEach(() => resetCodeModeTestState());
103+
104+
it("returns a trusted no-start tool failure to the model for ordinary recovery", async () => {
105+
const terminal = pluginToolWithExecute("terminal", "Open a terminal", async () =>
106+
jsonResult({ unexpected: true }),
107+
);
108+
terminal.prepareBeforeToolCallParams = () => {
109+
throw new ToolInputError("terminal unavailable before execution");
110+
};
111+
const recover = pluginToolWithExecute("recover_task", "Recover the task", async () =>
112+
jsonResult({ recovered: true }),
113+
);
114+
115+
const { agent, providerContexts, reconciliationCandidates } = await runCodeModeAgent({
116+
hiddenTools: [terminal, recover],
117+
programs: ["return await terminal({});", "return await recover_task({});"],
118+
});
119+
120+
expect(providerContexts).toHaveLength(3);
121+
expect(providerContexts[1]?.messages).toContainEqual(
122+
expect.objectContaining({
123+
role: "toolResult",
124+
toolName: "exec",
125+
isError: true,
126+
details: expect.objectContaining({
127+
status: "failed",
128+
failurePhase: "bridge",
129+
bridgeDispatchStarted: true,
130+
error: expect.stringContaining("terminal unavailable"),
131+
}),
132+
}),
133+
);
134+
expect(terminal.execute).not.toHaveBeenCalled();
135+
expect(recover.execute).toHaveBeenCalledOnce();
136+
expect(reconciliationCandidates).toBe(0);
137+
expect(agent.state.messages.at(-1)).toMatchObject({
138+
role: "assistant",
139+
content: [{ type: "text", text: "recovered" }],
140+
});
141+
});
142+
143+
it("lets the model correct successive JavaScript syntax and runtime errors", async () => {
144+
const complete = pluginToolWithExecute("complete_task", "Complete the task", async () =>
145+
jsonResult({ completed: true }),
146+
);
147+
148+
const { agent, providerContexts } = await runCodeModeAgent({
149+
hiddenTools: [complete],
150+
programs: ["const value = ;", "return missingFn();", "return await complete_task({});"],
151+
});
152+
153+
expect(providerContexts).toHaveLength(4);
154+
for (const [index, errorName] of ["SyntaxError", "ReferenceError"].entries()) {
155+
expect(providerContexts[index + 1]?.messages).toContainEqual(
156+
expect.objectContaining({
157+
role: "toolResult",
158+
toolName: "exec",
159+
isError: true,
160+
details: expect.objectContaining({
161+
status: "failed",
162+
error: expect.stringContaining(errorName),
163+
}),
164+
}),
165+
);
166+
}
167+
expect(complete.execute).toHaveBeenCalledOnce();
168+
expect(agent.state.messages.at(-1)).toMatchObject({
169+
role: "assistant",
170+
content: [{ type: "text", text: "recovered" }],
171+
});
172+
});
173+
174+
it("blocks another action after an earlier side effect and a later tool failure", async () => {
175+
const recordEffect = pluginToolWithExecute("record_effect", "Record an effect", async () =>
176+
jsonResult({ recorded: true }),
177+
);
178+
const terminal = pluginToolWithExecute("terminal", "Open a terminal", async () => {
179+
throw new Error("terminal unavailable");
180+
});
181+
const write = pluginToolWithExecute("write", "Repeat a mutation", async () =>
182+
jsonResult({ repeated: true }),
183+
);
184+
185+
const { providerContexts, reconciliationCandidates } = await runCodeModeAgent({
186+
hiddenTools: [recordEffect, terminal, write],
187+
programs: ["await record_effect({}); return await terminal({});", "return await write({});"],
188+
});
189+
190+
expect(providerContexts).toHaveLength(1);
191+
expect(recordEffect.execute).toHaveBeenCalledOnce();
192+
expect(terminal.execute).toHaveBeenCalledOnce();
193+
expect(write.execute).not.toHaveBeenCalled();
194+
expect(reconciliationCandidates).toBe(1);
195+
});
196+
197+
it("routes a partially applied mutation to restricted reconciliation without replay", async () => {
198+
const appliedChanges: string[] = [];
199+
const applyPatch = pluginToolWithExecute("apply_patch", "Apply a patch", async () => {
200+
appliedChanges.push("first hunk applied");
201+
throw new Error("second hunk is ambiguous");
202+
});
203+
const write = pluginToolWithExecute("write", "Repeat a mutation", async () =>
204+
jsonResult({ repeated: true }),
205+
);
206+
const send = pluginToolWithExecute("message", "Send a message", async () =>
207+
jsonResult({ delivered: true }),
208+
);
209+
const shell = pluginToolWithExecute("shell_command", "Run a shell command", async () =>
210+
jsonResult({ executed: true }),
211+
);
212+
213+
const { providerContexts, reconciliationCandidates } = await runCodeModeAgent({
214+
hiddenTools: [applyPatch, write, send, shell],
215+
programs: ["return await apply_patch({});", "return await write({});"],
216+
});
217+
218+
expect(providerContexts).toHaveLength(1);
219+
expect(applyPatch.execute).toHaveBeenCalledOnce();
220+
expect(write.execute).not.toHaveBeenCalled();
221+
expect(send.execute).not.toHaveBeenCalled();
222+
expect(shell.execute).not.toHaveBeenCalled();
223+
expect(reconciliationCandidates).toBe(1);
224+
expect(appliedChanges).toEqual(["first hunk applied"]);
225+
});
226+
227+
it("preserves an explicitly terminal nested action when later JavaScript fails", async () => {
228+
const terminal = pluginToolWithExecute("terminal_action", "Finish the task", async () => ({
229+
...jsonResult({ delivered: true }),
230+
terminate: true,
231+
}));
232+
const repeat = pluginToolWithExecute("repeat_action", "Repeat the action", async () =>
233+
jsonResult({ repeated: true }),
234+
);
235+
236+
const { agent, providerContexts } = await runCodeModeAgent({
237+
hiddenTools: [terminal, repeat],
238+
programs: [
239+
'await terminal_action({}); throw new Error("after terminal action");',
240+
"return await repeat_action({});",
241+
],
242+
});
243+
244+
expect(providerContexts).toHaveLength(1);
245+
expect(terminal.execute).toHaveBeenCalledOnce();
246+
expect(repeat.execute).not.toHaveBeenCalled();
247+
expect(agent.state.messages.at(-1)).toMatchObject({
248+
role: "toolResult",
249+
isError: true,
250+
details: {
251+
status: "failed",
252+
error: expect.stringContaining("after terminal action"),
253+
},
254+
});
255+
});
256+
});

‎src/agents/code-mode.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,7 @@ function createCodeModeExecDescription(
178178
: undefined;
179179
const catalogIndex = projection ? formatCodeModeCatalogIndex(projection.bindings) : "";
180180
return (
181-
`Run JavaScript or TypeScript in OpenClaw code mode. Enabled tools are async global functions listed in the quick index. Await dependent calls in order; independent calls may run with Promise.all. Declared output fields may feed later calls in the same program; do not spend another \`exec\` merely inspecting them. Return the final value; otherwise the result is \`null\`. \`-> ?\` means unknown output: do not feed it into guessed field-dependent logic in the same program. Return the raw value first, observe it, then use a later \`exec\` for dependent composition. If a tool is omitted from the bounded index, use \`catalog.search(query)\`; results are callable: \`const [tool] = await catalog.search("..."); return await tool({...});\`. Handles expose \`describe()\` when a schema is needed. \`setTimeout\` and \`clearTimeout\` work. Nested calls enforce normal tool policy and approvals. Nested results, output, and final value share ${maxOutputBytes} bytes; truncation reports omitted bytes and asks you to rerun with narrower args. Node.js modules and \`require\`/\`import\` are NOT available; use enabled globals for shell, file, network, or external actions.` +
181+
`Run JavaScript or TypeScript in OpenClaw code mode. Enabled tools are async global functions listed in the quick index. Await dependent calls in order; independent calls may run with Promise.all. Declared output fields may feed later calls in the same program; do not spend another \`exec\` merely inspecting them. Return the final value; otherwise the result is \`null\`. \`-> ?\` means unknown output: do not feed it into guessed field-dependent logic in the same program. Return the raw value first, observe it, then use a later \`exec\` for dependent composition. If a tool is omitted from the bounded index, use \`catalog.search(query)\`; results are callable: \`const [tool] = await catalog.search("..."); return await tool({...});\`. Handles expose \`describe()\` when a schema is needed. \`setTimeout\` and \`clearTimeout\` work. Nested calls enforce normal tool policy and approvals. Tool failures are catchable JavaScript errors; otherwise, use a safe failed result to correct your code or choose another tool. If an action may have started, inspect its outcome without repeating mutations. Never replay actions that already ran. Nested results, output, and final value share ${maxOutputBytes} bytes; truncation reports omitted bytes and asks you to rerun with narrower args. Node.js modules and \`require\`/\`import\` are NOT available; use enabled globals for shell, file, network, or external actions.` +
182182
apiGuidance +
183183
mcpGuidance +
184184
swarmGuidance +

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ describe("Code Mode wait, scope, and suspended runs", () => {
205205
expect(resumed.terminate).toBe(true);
206206
});
207207

208-
it("discards retained terminal bridge evidence when a yielded run fails", async () => {
208+
it("preserves retained terminal bridge evidence when a yielded run fails", async () => {
209209
const { config, catalogRef, tools } = createTerminalBridgeHarness();
210210
const terminal = pluginToolWithExecute("terminal_action", "Terminal action", async () => ({
211211
...jsonResult({ terminal: true }),
@@ -250,7 +250,7 @@ describe("Code Mode wait, scope, and suspended runs", () => {
250250
status: "failed",
251251
error: expect.stringContaining("resumed failure"),
252252
});
253-
expect(resumed.terminate).toBeUndefined();
253+
expect(resumed.terminate).toBe(true);
254254
});
255255

256256
it("keeps a safe suspension clean and wraps network content after wait resumes it", async () => {

‎src/agents/embedded-agent-runner/run/attempt-session-prepare.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ import { buildAfterTurnRuntimeContext } from "./attempt-prompt-helpers.js";
4949
import { resolveExistingAttemptTranscriptState } from "./attempt-transcript-helpers.js";
5050
import type { EmbeddedAttemptTranscriptLifecycle } from "./attempt-transcript-lifecycle.js";
5151
import { createUserTranscriptContextRegistry } from "./attempt-user-transcript-context-registry.js";
52-
import { installCodeModeRepairHook } from "./code-mode-repair.js";
52+
import { installCodeModeOutcomeHook } from "./code-mode-outcome.js";
5353
import { installMessageToolOnlyTerminalHook } from "./message-tool-terminal.js";
5454
import { reconcilePrePersistedCurrentUserTurn } from "./pre-persisted-user-turn.js";
5555
import { resolveSessionBoundaryPromptCacheKey } from "./session-boundary-prompt-cache-key.js";
@@ -243,7 +243,7 @@ export async function prepareEmbeddedAttemptAgentSession(input: {
243243
sessionKey: attempt.sessionKey,
244244
});
245245
if (input.clientToolPreparation.codeModeControlsEnabledForRun) {
246-
installCodeModeRepairHook({
246+
installCodeModeOutcomeHook({
247247
agent: activeSession.agent,
248248
onReconciliationCandidate: () => {
249249
if (codeModeReconciliationReadAuthorized) {

0 commit comments

Comments
 (0)