|
| 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 | +}); |
0 commit comments