返回源码地图

packages/durable/test/codemode.test.ts

v1.3.0 · 71023aec1546 · 11:193–269,VM重启、完成子调用复用与safe重跑,未本机执行上游suite

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1import { mkdtemp, readdir, readFile, rm } from "node:fs/promises";
2import { tmpdir } from "node:os";
3import { dirname, join } from "node:path";
4import type { Context } from "@earendil-works/chord";
5import { type AssistantMessage, fauxAssistantMessage, fauxText, fauxToolCall, Type } from "@earendil-works/pi-ai";
6import { type CodemodeRun, CodemodeSandbox } from "@earendil-works/pi-codemode";
7import {
8 defineTool,
9 type Harness,
10 type TaskId,
11 type ToolRegistration,
12 ToolResultEntry,
13 ToolTask,
14 type ToolTaskInput,
15} from "@earendil-works/pi-durable";
16import { afterEach, describe, expect, it } from "vitest";
17import {
18 type CodemodeGlobal,
19 CodemodeJournalDoc,
20 CodemodeRunDoc,
21 type CodemodeToolDetails,
22 createCodemodeTool,
23} from "../src/codemode/codemode.ts";
24import type { CodemodeNamespace } from "../src/codemode/describe.ts";
25import { NodeExecutionEnv } from "../src/env/node.ts";
26import { openNodeSqliteStorage } from "../src/storage/sqlite/node.ts";
27import { allEntries, type ChatSetup, chatSetup, openChat } from "./chat-support.ts";
28import { addHooks, addTool } from "./harness-support.ts";
29import { ControlledStorage, context } from "./session-support.ts";
30import { aborted, type Deferred, deferred, eventually } from "./task-support.ts";
31
32const Parameters = Type.Object({ text: Type.Optional(Type.String()), id: Type.Optional(Type.Number()) });
33
34function tool(
35 name: string,
36 execute: ToolRegistration<typeof Parameters>["execute"],
37 replay: "safe" | "unsafe" = "unsafe",
38) {
39 return defineTool({ name, description: name, parameters: Parameters, execute, replay });
40}
41
42const DONE = fauxAssistantMessage([fauxText("done")]);
43
44function script(code: string): AssistantMessage {
45 return fauxAssistantMessage([fauxToolCall("codemode", { code }, { id: "s1" })], { stopReason: "toolUse" });
46}
47
48const directories = new Set<string>();
49afterEach(async () => {
50 for (const directory of directories) await rm(directory, { recursive: true, force: true });
51 directories.clear();
52});
53
54async function sqlitePath(): Promise<string> {
55 const directory = await mkdtemp(join(tmpdir(), "pi-durable-codemode-"));
56 directories.add(directory);
57 return join(directory, "session.sqlite");
58}
59
60/**
61 * A chat with the code mode tool and test tools:
62 * - `echo` returns `echo <text>` and counts its runs by text;
63 * - `hold` (replay-safe) waits for `holds.gate` while `holds.block` is set, then returns `held <id>`;
64 * - `slow` returns `slow <id>` once `slows.release(id)` was called.
65 */
66function codemodeChat(globals: CodemodeGlobal[] = [], namespaces: CodemodeNamespace[] = []) {
67 const setup = chatSetup();
68 const sandbox = new CodemodeSandbox({ memoryLimitBytes: 64 * 1024 * 1024 });
69 const vm: { starts: number; onStart?: (run: CodemodeRun) => void } = { starts: 0 };
70 const start = sandbox.start.bind(sandbox);
71 sandbox.start = (code, options) => {
72 vm.starts++;
73 const run = start(code, options);
74 vm.onStart?.(run);
75 return run;
76 };
77 addTool(setup.registry, createCodemodeTool({ sandbox, globals, namespaces }));
78 const echo = new Map<string, number>();
79 addTool(
80 setup.registry,
81 tool("echo", async (args) => {
82 echo.set(args.text ?? "", (echo.get(args.text ?? "") ?? 0) + 1);
83 return { output: [{ type: "text", text: `echo ${args.text ?? ""}` }] };
84 }),
85 );
86 const holds = { block: true, reached: deferred(), runs: 0 };
87 addTool(
88 setup.registry,
89 tool(
90 "hold",
91 async (args, _api, callContext) => {
92 holds.runs++;
93 if (holds.block) {
94 holds.reached.resolve();
95 await aborted(callContext.abortSignal!);
96 }
97 return { output: [{ type: "text", text: `held ${args.id ?? ""}` }] };
98 },
99 "safe",
100 ),
101 );
102 const pauses = { block: true, reached: deferred() };
103 addTool(
104 setup.registry,
105 tool(
106 "pause",
107 async (_args, _api, callContext) => {
108 if (pauses.block) {
109 pauses.reached.resolve();
110 await aborted(callContext.abortSignal!);
111 }
112 return { output: [{ type: "text", text: "paused" }] };
113 },
114 "safe",
115 ),
116 );
117 const gates = new Map<number, Deferred>();
118 const finished: number[] = [];
119 const slows = {
120 finished,
121 gate: (id: number) => {
122 const gate = gates.get(id) ?? deferred();
123 gates.set(id, gate);
124 return gate;
125 },
126 release: (id: number) => slows.gate(id).resolve(),
127 };
128 addTool(
129 setup.registry,
130 tool("slow", async (args) => {
131 await slows.gate(args.id ?? 0).promise;
132 finished.push(args.id ?? 0);
133 return { output: [{ type: "text", text: `slow ${args.id}` }] };
134 }),
135 );
136 return { setup, sandbox, vm, echo, holds, pauses, slows };
137}
138
139async function scriptTask(harness: Harness): Promise<TaskId> {
140 const tasks = (await harness.commit((tx) => tx.scanTasks({ kind: ToolTask.definition.name }, 100), context)).items;
141 return tasks.find((task) => (task.input as ToolTaskInput).kind === "model")!.id;
142}
143
144async function nestedCount(harness: Harness): Promise<number> {
145 const tasks = (await harness.commit((tx) => tx.scanTasks({ kind: ToolTask.definition.name }, 100), context)).items;
146 return tasks.filter((task) => (task.input as ToolTaskInput).kind === "nested").length;
147}
148
149/** The code mode call's result text. */
150async function resultText(setup: ChatSetup, root: Awaited<ReturnType<typeof openChat>>["root"]) {
151 void setup;
152 const entry = (await allEntries(root)).find((candidate) => ToolResultEntry.is(candidate))!;
153 const message = entry.model![0]!;
154 return {
155 // Without the "Script completed" header and its wall time, which tests of it check themselves.
156 text:
157 message.role === "toolResult"
158 ? message.content
159 .map((item) => (item.type === "text" ? item.text : ""))
160 .join("")
161 .replace(/^Script (completed|failed)\nWall time [\d.]+ seconds\nOutput:\n/, "")
162 : "",
163 isError: message.role === "toolResult" && message.isError,
164 };
165}
166
167/**
168 * Run `code` until `holds.reached`, close the Harness (a restart), let `between` change the stored state, then reopen
169 * with `hold` no longer blocking and wait for the answer.
170 */
171async function restart(
172 chat: ReturnType<typeof codemodeChat>,
173 code: string,
174 between: (harness: Harness, task: TaskId) => Promise<void> = async () => {},
175 beforeClose: (harness: Harness, task: TaskId) => Promise<void> = async () => {},
176) {
177 const path = await sqlitePath();
178 chat.setup.faux.setResponses([script(code), DONE]);
179 let opened = await openChat(await openNodeSqliteStorage(path), chat.setup);
180 const id = (await opened.root.submit({ type: "input", content: "go" }, context)).id;
181 await chat.holds.reached.promise;
182 await beforeClose(opened.harness, await scriptTask(opened.harness));
183 await opened.harness.close(context);
184 chat.holds.block = false;
185 opened = await openChat(await openNodeSqliteStorage(path), chat.setup);
186 await between(opened.harness, await scriptTask(opened.harness));
187 opened.harness.resume();
188 expect((await (await opened.harness.submission(id, context))!.wait(context)).status).toBe("done");
189 return { ...opened, result: await resultText(chat.setup, opened.root) };
190}
191
192describe("durable code mode", () => {
193 it("runs a script that calls tools as nested calls, and journals each result before delivering it", async () => {
194 const chat = codemodeChat();
195 chat.holds.block = false;
196 chat.setup.faux.setResponses([
197 script(`const a = await tools.echo({ text: "a" }); const b = await tools.echo({ text: "b" }); return [a, b];`),
198 DONE,
199 ]);
200 const { harness, root } = await openChat(await openNodeSqliteStorage(await sqlitePath()), chat.setup);
201 await (await root.submit({ type: "input", content: "go" }, context)).wait(context);
202 expect(await resultText(chat.setup, root)).toEqual({ text: '["echo a","echo b"]', isError: false });
203 expect(await nestedCount(harness)).toBe(2);
204 await harness.close(context);
205 });
206
207 it("resumes a script after a restart without running its finished calls again", async () => {
208 const chat = codemodeChat();
209 const { harness, result } = await restart(
210 chat,
211 `const a = await tools.echo({ text: "a" });
212 const held = await tools.hold({ id: 1 });
213 const b = await tools.echo({ text: "b" });
214 return [a, held, b, Date.now() > 0];`,
215 );
216 expect(result).toEqual({ text: '["echo a","held 1","echo b",true]', isError: false });
217 expect(Object.fromEntries(chat.echo)).toEqual({ a: 1, b: 1 });
218 // The VM ran twice; hold, replay-safe, reran once after the restart.
219 expect(chat.vm.starts).toBe(2);
220 expect(chat.holds.runs).toBe(2);
221 await harness.close(context);
222 });
223
224 it("replays results in the order they arrived, not the order the calls were made", async () => {
225 const chat = codemodeChat();
226 const code = `const order = [];
227 await Promise.all([tools.slow({ id: 1 }).then(() => order.push(1)), tools.slow({ id: 2 }).then(() => order.push(2))]);
228 await tools.echo({ text: order.join(",") });
229 await tools.hold({});
230 return order;`;
231 // 2 finishes first, then 1.
232 chat.slows.release(2);
233 void eventually(() => chat.slows.finished.includes(2)).then(() => chat.slows.release(1));
234 const { harness, result } = await restart(chat, code);
235 expect(result).toEqual({ text: "[2,1]", isError: false });
236 expect(Object.fromEntries(chat.echo)).toEqual({ "2,1": 1 });
237 await harness.close(context);
238 });
239
240 it("journals globals with their results and hands a replay the recorded ones", async () => {
241 let counter = 0;
242 const globals: CodemodeGlobal[] = [{ name: "next", execute: async () => ++counter }];
243 const chat = codemodeChat(globals);
244 const { harness, result } = await restart(
245 chat,
246 `const n = await next(); await tools.hold({}); return [n, await next()];`,
247 );
248 // The first next() ran once and was replayed from the journal; the second ran after the restart.
249 expect(result).toEqual({ text: "[1,2]", isError: false });
250 expect(counter).toBe(2);
251 await harness.close(context);
252 });
253
254 it("keeps the script's clock and randomness across a restart", async () => {
255 const chat = codemodeChat();
256 const { harness, result } = await restart(
257 chat,
258 `const before = [Date.now(), Math.random()];
259 await tools.hold({});
260 await tools.echo({ text: String(before[0]) + "/" + String(before[1]) });
261 return "ok";`,
262 );
263 expect(result.text).toBe("ok");
264 // One echo: the same arguments, so the rerun admitted no second call.
265 expect([...chat.echo.values()]).toEqual([1]);
266 await harness.close(context);
267 });
268
269 it("ends the call when a resumed script made a different number of calls than before", async () => {
270 const chat = codemodeChat();
271 const { harness, result } = await restart(
272 chat,
273 `await tools.echo({ text: "a" }); await tools.hold({});`,
274 async (opened, task) => {
275 await opened.commit(async (tx) => {
276 const journal = await tx.doc(CodemodeJournalDoc, task);
277 journal.entries[0]!.issuedAfter = 7;
278 }, context);
279 },
280 );
281 expect(result.isError).toBe(true);
282 expect(result.text).toContain("after result 1 it had made 2 calls, where it had made 7");
283 await harness.close(context);
284 });
285
286 it("ends the call at once when a resumed script waits without making a call it made before", async () => {
287 const chat = codemodeChat();
288 const { harness, result } = await restart(
289 chat,
290 `await tools.echo({ text: "a" }); await tools.hold({});`,
291 async (opened, task) => {
292 await opened.commit(async (tx) => {
293 const journal = await tx.doc(CodemodeJournalDoc, task);
294 journal.entries[0]!.id = 99;
295 }, context);
296 },
297 );
298 expect(result.isError).toBe(true);
299 expect(result.text).toContain("it waits without making call 99");
300 // hold, admitted before the restart, resumed on its own; no call was admitted by the replay.
301 expect(await nestedCount(harness)).toBe(2);
302 await harness.close(context);
303 });
304
305 it("ends the call when a resumed script calls a global with other arguments", async () => {
306 const chat = codemodeChat([{ name: "next", execute: async () => 1 }]);
307 const { harness, result } = await restart(chat, `await next(); await tools.hold({});`, async (opened, task) => {
308 await opened.commit(async (tx) => {
309 const journal = await tx.doc(CodemodeJournalDoc, task);
310 journal.entries[0]!.global!.args = "other";
311 }, context);
312 });
313 expect(result.isError).toBe(true);
314 expect(result.text).toContain("call 1 is next");
315 await harness.close(context);
316 });
317
318 it("admits no call of a diverging replay, even one the script never made before", async () => {
319 const chat = codemodeChat();
320 // With k set, the replay makes three extra calls after result 1, which the live run did not make; the count in
321 // result 1's acknowledgment shows the divergence only after they were issued.
322 const { harness, result } = await restart(
323 chat,
324 `await tools.echo({ text: "a" });
325 const extra = load("k") ?? 0;
326 for (let i = 0; i < extra; i++) tools.echo({ text: "extra" + i });
327 await tools.hold({});`,
328 async (opened, task) => {
329 await opened.commit(async (tx) => {
330 const run = await tx.doc(CodemodeRunDoc, task);
331 run.start!.store = { k: 3 };
332 }, context);
333 },
334 async (opened, task) => {
335 await eventually(
336 async () => (await opened.snapshot(CodemodeJournalDoc, task, context))?.entries[0]?.issuedAfter === 2,
337 );
338 },
339 );
340 expect(result.isError).toBe(true);
341 expect(result.text).toContain("after result 1 it had made 5 calls, where it had made 2");
342 expect(Object.fromEntries(chat.echo)).toEqual({ a: 1 });
343 expect(await nestedCount(harness)).toBe(2);
344 await harness.close(context);
345 });
346
347 it("ends the call when a resumed script ends where it went on before", async () => {
348 const chat = codemodeChat();
349 const { harness, result } = await restart(
350 chat,
351 `await tools.echo({ text: "a" }); if (load("k")) return "early"; await tools.hold({});`,
352 async (opened, task) => {
353 await opened.commit(async (tx) => {
354 const run = await tx.doc(CodemodeRunDoc, task);
355 run.start!.store = { k: true };
356 }, context);
357 },
358 // The live run acknowledged result 1 before the restart: it went on after it.
359 async (opened, task) => {
360 await eventually(
361 async () => (await opened.snapshot(CodemodeJournalDoc, task, context))?.entries[0]?.issuedAfter === 2,
362 );
363 },
364 );
365 expect(result.isError).toBe(true);
366 expect(result.text).toContain("it ended after result 1, where it went on before");
367 await harness.close(context);
368 });
369
370 it("ends the call when a resumed script ends before calls the live run made, even without a recorded count", async () => {
371 const chat = codemodeChat();
372 const { harness, result } = await restart(
373 chat,
374 `await tools.echo({ text: "a" }); if (load("k")) return "early"; await tools.echo({ text: "b" }); await tools.hold({});`,
375 async (opened, task) => {
376 await opened.commit(async (tx) => {
377 const run = await tx.doc(CodemodeRunDoc, task);
378 run.start!.store = { k: true };
379 // As if the live run crashed before recording result 1's count.
380 const journal = await tx.doc(CodemodeJournalDoc, task);
381 delete journal.entries[0]!.issuedAfter;
382 }, context);
383 },
384 );
385 expect(result.isError).toBe(true);
386 expect(result.text).toContain("it ended after result 1, where it went on before");
387 await harness.close(context);
388 });
389
390 it("ends the call when a resumed script makes a call an earlier attempt admitted with other arguments", async () => {
391 const chat = codemodeChat();
392 const { harness, result } = await restart(
393 chat,
394 `await tools.echo({ text: load("k") ?? "a" }); await tools.hold({});`,
395 async (opened, task) => {
396 await opened.commit(async (tx) => {
397 const run = await tx.doc(CodemodeRunDoc, task);
398 run.start!.store = { k: "other" };
399 // As if the restart came before the first journal commit: the rerun runs live from the start.
400 const journal = await tx.doc(CodemodeJournalDoc, task);
401 journal.entries.length = 0;
402 }, context);
403 },
404 );
405 expect(result.isError).toBe(true);
406 expect(result.text).toContain("different path");
407 expect(result.text).toContain("call 1 is tools.echo");
408 expect(Object.fromEntries(chat.echo)).toEqual({ a: 1 });
409 await harness.close(context);
410 });
411
412 it("records a count the live run never recorded as soon as a replay acknowledges it", async () => {
413 const chat = codemodeChat();
414 const path = await sqlitePath();
415 chat.setup.faux.setResponses([script(`await tools.echo({ text: "a" }); await tools.hold({});`), DONE]);
416 let opened = await openChat(await openNodeSqliteStorage(path), chat.setup);
417 const id = (await opened.root.submit({ type: "input", content: "go" }, context)).id;
418 await chat.holds.reached.promise;
419 await opened.harness.close(context);
420 // As if result 1's count was never recorded; hold blocks again after the restart.
421 chat.holds.reached = deferred();
422 opened = await openChat(await openNodeSqliteStorage(path), chat.setup);
423 const task = await scriptTask(opened.harness);
424 await opened.harness.commit(async (tx) => {
425 delete (await tx.doc(CodemodeJournalDoc, task)).entries[0]!.issuedAfter;
426 }, context);
427 opened.harness.resume();
428 // The replay acknowledges result 1 and goes live; the script waits on hold, and the count is already recorded.
429 await chat.holds.reached.promise;
430 await eventually(
431 async () => (await opened.harness.snapshot(CodemodeJournalDoc, task, context))?.entries[0]?.issuedAfter === 2,
432 );
433 await opened.harness.close(context);
434 chat.holds.block = false;
435 opened = await openChat(await openNodeSqliteStorage(path), chat.setup);
436 opened.harness.resume();
437 expect((await (await opened.harness.submission(id, context))!.wait(context)).status).toBe("done");
438 await opened.harness.close(context);
439 });
440
441 it("lists the script's tool calls in its result's details", async () => {
442 const chat = codemodeChat();
443 addTool(
444 chat.setup.registry,
445 tool("fails", async () => ({ output: [{ type: "text", text: "permission denied" }], isError: true })),
446 );
447 chat.setup.faux.setResponses([
448 script(
449 `await tools.echo({ text: "a" }); try { await tools.fails({}); } catch {} tools.hold({ id: 9 }); return 1;`,
450 ),
451 DONE,
452 ]);
453 const { harness, root } = await openChat(await openNodeSqliteStorage(await sqlitePath()), chat.setup);
454 await (await root.submit({ type: "input", content: "go" }, context)).wait(context);
455 const entry = (await allEntries(root)).find((candidate) => ToolResultEntry.is(candidate))!;
456 const details = (entry.model![0] as { details?: CodemodeToolDetails }).details;
457 // A call still running, or not yet launched, when the script ended shows as cancelled.
458 expect(details?.calls).toMatchObject([
459 { id: 1, name: "echo", args: '{"text":"a"}', status: "ok" },
460 { id: 2, name: "fails", args: "{}", status: "error", error: "permission denied" },
461 { id: 3, name: "hold", args: '{"id":9}', status: "cancelled" },
462 ]);
463 expect(details?.calls[0]?.durationMs).toBeGreaterThanOrEqual(0);
464 await harness.close(context);
465 });
466
467 it("stores no outcome when the host closes the sandbox, and replays the script after a restart", async () => {
468 const chat = codemodeChat();
469 const path = await sqlitePath();
470 chat.setup.faux.setResponses([
471 script(`await tools.echo({ text: "a" }); await tools.hold({}); return "done";`),
472 DONE,
473 ]);
474 let opened = await openChat(await openNodeSqliteStorage(path), chat.setup);
475 const id = (await opened.root.submit({ type: "input", content: "go" }, context)).id;
476 await chat.holds.reached.promise;
477 const task = await scriptTask(opened.harness);
478 // A host shutting down closes the sandbox before the Harness.
479 await chat.sandbox.close();
480 await new Promise((resolve) => setTimeout(resolve, 100));
481 expect((await opened.harness.snapshot(CodemodeRunDoc, task, context))?.result).toBeUndefined();
482 await opened.harness.close(context);
483 // The next process has a new sandbox.
484 chat.holds.block = false;
485 addTool(
486 chat.setup.registry,
487 createCodemodeTool({ sandbox: new CodemodeSandbox({ memoryLimitBytes: 64 * 1024 * 1024 }) }),
488 );
489 opened = await openChat(await openNodeSqliteStorage(path), chat.setup);
490 opened.harness.resume();
491 expect((await (await opened.harness.submission(id, context))!.wait(context)).status).toBe("done");
492 expect(await resultText(chat.setup, opened.root)).toEqual({ text: "done", isError: false });
493 expect(Object.fromEntries(chat.echo)).toEqual({ a: 1 });
494 await opened.harness.close(context);
495 });
496
497 it("aborts a call still running when the script ends", async () => {
498 const chat = codemodeChat();
499 chat.setup.faux.setResponses([script(`tools.hold({}); await tools.echo({ text: "a" }); return 1;`), DONE]);
500 const { harness, root } = await openChat(await openNodeSqliteStorage(await sqlitePath()), chat.setup);
501 await (await root.submit({ type: "input", content: "go" }, context)).wait(context);
502 expect(await resultText(chat.setup, root)).toEqual({ text: "1", isError: false });
503 const tasks = (await harness.commit((tx) => tx.scanTasks({ kind: ToolTask.definition.name }, 100), context))
504 .items;
505 const hold = tasks.find(
506 (task) =>
507 (task.input as ToolTaskInput).kind === "nested" &&
508 (task.input as { call: { name: string } }).call.name === "hold",
509 )!;
510 expect(chat.holds.runs).toBe(1);
511 expect(hold.state).toMatchObject({ status: "terminal", outcome: { status: "aborted" } });
512 await harness.close(context);
513 });
514
515 it("admits no call once the script has ended, even one it made before ending", async () => {
516 const chat = codemodeChat();
517 chat.holds.block = false;
518 const storage = new ControlledStorage();
519 // Hold the fingerprint commit, and so the admission of the script's call, until the script has ended.
520 chat.vm.onStart = (run) => {
521 const held = storage.holdCommits();
522 void run.result.then(() => held.release());
523 };
524 chat.setup.faux.setResponses([script(`tools.echo({ text: "late" }); return 1;`), DONE]);
525 const { harness, root } = await openChat(storage, chat.setup);
526 await (await root.submit({ type: "input", content: "go" }, context)).wait(context);
527 expect(await resultText(chat.setup, root)).toEqual({ text: "1", isError: false });
528 expect(chat.echo.size).toBe(0);
529 expect(await nestedCount(harness)).toBe(0);
530 await harness.close(context);
531 });
532
533 it("checks a rerun's calls against an earlier attempt's before admitting any later call", async () => {
534 const chat = codemodeChat();
535 // With k set, call 1 has other arguments and call 2 is another tool than before; call 3 would be new.
536 const { harness, result } = await restart(
537 chat,
538 `const k = load("k");
539 tools.echo({ text: k ?? "a" });
540 if (k) tools.echo({ text: "new" });
541 await tools.hold({});`,
542 async (opened, task) => {
543 await opened.commit(async (tx) => {
544 const run = await tx.doc(CodemodeRunDoc, task);
545 run.start!.store = { k: "x" };
546 // As if the restart came before the first journal commit.
547 (await tx.doc(CodemodeJournalDoc, task)).entries.length = 0;
548 }, context);
549 },
550 );
551 expect(result.isError).toBe(true);
552 // The first run already made more calls than before.
553 expect(result.text).toContain("its first run made 3 calls, where it had made 2");
554 expect(await nestedCount(harness)).toBe(2);
555 expect(Object.fromEntries(chat.echo)).toEqual({ a: 1 });
556 await harness.close(context);
557 });
558
559 it("ends the call when a rerun makes a global call where an earlier attempt made a tool call", async () => {
560 const chat = codemodeChat([{ name: "pick", execute: async () => 1 }]);
561 const { harness, result } = await restart(
562 chat,
563 `if (load("k")) { await pick(); await tools.echo({ text: "new" }); } else { await tools.hold({}); }`,
564 async (opened, task) => {
565 await opened.commit(async (tx) => {
566 const run = await tx.doc(CodemodeRunDoc, task);
567 run.start!.store = { k: true };
568 }, context);
569 },
570 );
571 expect(result.isError).toBe(true);
572 expect(result.text).toContain("call 1 is pick(), but was tools.hold({})");
573 expect(chat.echo.size).toBe(0);
574 await harness.close(context);
575 });
576
577 it("ends the call when a rerun's first run makes fewer calls than an earlier attempt admitted", async () => {
578 // Live, the first run admits hold 1 and hold 2. With k set, it makes only hold 1, and after its result a global and a
579 // new tool call: the global's ID is hold 2's key, which no check after the release would see.
580 const chat = codemodeChat([{ name: "pick", execute: async () => 1 }]);
581 const { harness, result } = await restart(
582 chat,
583 `const k = load("k");
584 const first = tools.hold({ id: 1 });
585 if (!k) tools.hold({ id: 2 });
586 await first;
587 await pick();
588 await tools.echo({ text: "new" });`,
589 async (opened, task) => {
590 await opened.commit(async (tx) => {
591 const run = await tx.doc(CodemodeRunDoc, task);
592 run.start!.store = { k: true };
593 }, context);
594 },
595 async (opened, task) => {
596 await eventually(async () => (await opened.snapshot(CodemodeJournalDoc, task, context))?.firstIssued === 2);
597 },
598 );
599 expect(result.isError).toBe(true);
600 expect(result.text).toContain("its first run made 1 calls, where it had made 2");
601 expect(chat.echo.size).toBe(0);
602 await harness.close(context);
603 });
604
605 it("ends the call when a rerun without journal entries ends in its first run, where it went on before", async () => {
606 const chat = codemodeChat();
607 const { harness, result } = await restart(
608 chat,
609 `if (load("k")) { store("x", 1); return "early"; } await tools.hold({});`,
610 async (opened, task) => {
611 await opened.commit(async (tx) => {
612 const run = await tx.doc(CodemodeRunDoc, task);
613 run.start!.store = { k: true };
614 }, context);
615 },
616 async (opened, task) => {
617 await eventually(async () => (await opened.snapshot(CodemodeJournalDoc, task, context))?.firstIssued === 1);
618 },
619 );
620 expect(result.isError).toBe(true);
621 expect(result.text).toContain("it ended after result 0, where it went on before");
622 await harness.close(context);
623 });
624
625 it("checks every call a rerun holds before launching any of them", async () => {
626 // Live, call 1 is a global that never finishes and call 2 is hold; with k set, call 1 is a new tool call and call 2
627 // holds with other arguments. Checking call 1 alone would launch it before call 2's conflict shows.
628 const chat = codemodeChat([
629 {
630 name: "forever",
631 execute: async (_args, _api, callContext) => {
632 await aborted(callContext.abortSignal!);
633 return null;
634 },
635 },
636 ]);
637 const { harness, result } = await restart(
638 chat,
639 `const k = load("k");
640 if (k) tools.echo({ text: "new" }); else forever();
641 await tools.hold({ id: k ? 2 : 1 });`,
642 async (opened, task) => {
643 await opened.commit(async (tx) => {
644 const run = await tx.doc(CodemodeRunDoc, task);
645 run.start!.store = { k: true };
646 }, context);
647 },
648 );
649 expect(result.isError).toBe(true);
650 expect(result.text).toContain('call 2 is tools.hold({"id":2}), but was tools.hold({"id":1})');
651 expect(chat.echo.size).toBe(0);
652 expect(await nestedCount(harness)).toBe(1);
653 await harness.close(context);
654 });
655
656 it("keeps a global's undefined result undefined, live and replayed", async () => {
657 const chat = codemodeChat([{ name: "nothing", execute: async () => undefined }]);
658 const { harness, result } = await restart(
659 chat,
660 `const before = await nothing(); await tools.hold({}); return [before === undefined, (await nothing()) === undefined];`,
661 );
662 expect(result).toEqual({ text: "[true,true]", isError: false });
663 await harness.close(context);
664 });
665
666 it("rejects a failed tool call with its error text and structured output", async () => {
667 const chat = codemodeChat();
668 addTool(
669 chat.setup.registry,
670 tool("fails", async () => ({ output: [{ type: "text", text: "permission denied" }], isError: true })),
671 );
672 chat.holds.block = false;
673 chat.setup.faux.setResponses([
674 script(`try { await tools.fails({}); } catch (e) { return [e.message, e.structuredOutput]; }`),
675 DONE,
676 ]);
677 const { harness, root } = await openChat(await openNodeSqliteStorage(await sqlitePath()), chat.setup);
678 await (await root.submit({ type: "input", content: "go" }, context)).wait(context);
679 expect(await resultText(chat.setup, root)).toEqual({
680 text: '["permission denied","permission denied"]',
681 isError: false,
682 });
683 await harness.close(context);
684 });
685
686 it("resolves a schema tool's error result that carries its value, and rejects one without with its text", async () => {
687 const chat = codemodeChat();
688 const Exit = Type.Object({ output: Type.String(), exitCode: Type.Number() });
689 addTool(
690 chat.setup.registry,
691 defineTool({
692 name: "run",
693 description: "run",
694 parameters: Type.Object({}),
695 structuredOutputSchema: Exit,
696 // Like bash on a nonzero exit: an error result with its value.
697 execute: async () => ({
698 output: [{ type: "text", text: "no matches" }],
699 structuredOutput: { output: "no matches", exitCode: 1 },
700 isError: true,
701 }),
702 }),
703 );
704 addTool(
705 chat.setup.registry,
706 defineTool({
707 name: "denied",
708 description: "denied",
709 parameters: Type.Object({}),
710 structuredOutputSchema: Exit,
711 execute: async () => ({ output: [{ type: "text", text: "permission denied" }], isError: true }),
712 }),
713 );
714 chat.holds.block = false;
715 chat.setup.faux.setResponses([
716 script(
717 `const r = await tools.run({});
718 let e; try { await tools.denied({}); } catch (error) { e = [error.message, error.structuredOutput ?? null]; }
719 return [r.exitCode, r.output, e];`,
720 ),
721 DONE,
722 ]);
723 const { harness, root } = await openChat(await openNodeSqliteStorage(await sqlitePath()), chat.setup);
724 await (await root.submit({ type: "input", content: "go" }, context)).wait(context);
725 expect(await resultText(chat.setup, root)).toEqual({
726 text: '[1,"no matches",["permission denied",null]]',
727 isError: false,
728 });
729 await harness.close(context);
730 });
731
732 it("resolves a schema-less tool with its text, as its declaration says, also when it returned images", async () => {
733 const chat = codemodeChat();
734 const PNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==";
735 addTool(
736 chat.setup.registry,
737 defineTool({
738 name: "picture",
739 description: "picture",
740 parameters: Type.Object({ caption: Type.Boolean() }),
741 execute: async (args) => ({
742 output: [
743 ...(args.caption ? [{ type: "text" as const, text: "a cat" }] : []),
744 { type: "image" as const, data: PNG, mimeType: "image/png" },
745 ],
746 }),
747 }),
748 );
749 chat.holds.block = false;
750 chat.setup.faux.setResponses([
751 script(`return [await tools.picture({ caption: true }), await tools.picture({ caption: false })];`),
752 DONE,
753 ]);
754 const { harness, root } = await openChat(await openNodeSqliteStorage(await sqlitePath()), chat.setup);
755 await (await root.submit({ type: "input", content: "go" }, context)).wait(context);
756 expect(await resultText(chat.setup, root)).toEqual({ text: '["a cat",""]', isError: false });
757 await harness.close(context);
758 });
759
760 it("delivers a result only after its journal commit", async () => {
761 const storage = new ControlledStorage();
762 const seen: string[] = [];
763 const chat = codemodeChat([
764 {
765 name: "first",
766 execute: async () => {
767 seen.push("first");
768 // The next commit is this result's journal commit: it never lands.
769 storage.failNextCommit(new Error("lost"));
770 return 1;
771 },
772 },
773 {
774 name: "second",
775 execute: async () => {
776 seen.push("second");
777 return 2;
778 },
779 },
780 ]);
781 chat.holds.block = false;
782 chat.setup.faux.setResponses([script(`await first(); await second();`), DONE]);
783 const { harness, root } = await openChat(storage, chat.setup);
784 await root.submit({ type: "input", content: "go" }, context);
785 await eventually(() => seen.includes("first"));
786 await new Promise((resolve) => setTimeout(resolve, 100));
787 expect(seen).toEqual(["first"]);
788 await harness.close(context).catch(() => {});
789 });
790
791 it("refuses to resume when the sandbox's fingerprint or the code mode version changed", async () => {
792 for (const field of ["fingerprint", "version"] as const) {
793 const chat = codemodeChat();
794 const { harness, result } = await restart(
795 chat,
796 `await tools.hold({}); await tools.echo({ text: "late" });`,
797 async (opened, task) => {
798 await opened.commit(async (tx) => {
799 const run = await tx.doc(CodemodeRunDoc, task);
800 if (field === "fingerprint") run.start!.fingerprint = "another sandbox";
801 else run.start!.version = 0;
802 }, context);
803 },
804 );
805 expect(result.isError).toBe(true);
806 expect(result.text).toContain("cannot resume");
807 expect(chat.echo.size).toBe(0);
808 await harness.close(context);
809 }
810 });
811
812 it("times a script out across a restart, without admitting new calls", async () => {
813 const chat = codemodeChat();
814 const { harness, result } = await restart(
815 chat,
816 `// @options: {"timeout_ms": 300}
817 await tools.hold({}); await tools.echo({ text: "late" });`,
818 () => new Promise((resolve) => setTimeout(resolve, 400)),
819 );
820 expect(result.isError).toBe(true);
821 expect(result.text).toContain("deadline passed");
822 expect(chat.echo.size).toBe(0);
823 expect(chat.vm.starts).toBe(1);
824 await harness.close(context);
825 });
826
827 it("returns a decided outcome after a restart without running the script again", async () => {
828 const chat = codemodeChat();
829 const path = await sqlitePath();
830 chat.holds.block = false;
831 chat.setup.faux.setResponses([script(`return "first"`), DONE]);
832 // Stop after execute() returned, so after the outcome is stored, and before the result commits.
833 const stopped = { block: true, reached: deferred() };
834 addHooks(chat.setup.registry, ToolTask, {
835 afterTool: async (call, _result, _api, hookContext) => {
836 if (call.name !== "codemode" || !stopped.block) return undefined;
837 stopped.reached.resolve();
838 await aborted(hookContext.abortSignal!);
839 return undefined;
840 },
841 });
842 let opened = await openChat(await openNodeSqliteStorage(path), chat.setup);
843 const id = (await opened.root.submit({ type: "input", content: "go" }, context)).id;
844 await stopped.reached.promise;
845 const task = await scriptTask(opened.harness);
846 expect((await opened.harness.snapshot(CodemodeRunDoc, task, context))?.result).toBeDefined();
847 await opened.harness.close(context);
848 stopped.block = false;
849 opened = await openChat(await openNodeSqliteStorage(path), chat.setup);
850 opened.harness.resume();
851 expect((await (await opened.harness.submission(id, context))!.wait(context)).status).toBe("done");
852 expect(await resultText(chat.setup, opened.root)).toEqual({ text: "first", isError: false });
853 expect(chat.vm.starts).toBe(1);
854 await opened.harness.close(context);
855 });
856
857 it("keeps store() values per conversation, as of a fork's entry", async () => {
858 const chat = codemodeChat();
859 chat.holds.block = false;
860 chat.setup.faux.setResponses([
861 script(`store("k", 1); return load("k")`),
862 DONE,
863 script(`return [load("k") ?? null]`),
864 DONE,
865 ]);
866 const { harness, root } = await openChat(await openNodeSqliteStorage(await sqlitePath()), chat.setup);
867 await (await root.submit({ type: "input", content: "first" }, context)).wait(context);
868 const firstUser = (await allEntries(root)).find((entry) => entry.kind === "pi.user")!;
869 await (await root.submit({ type: "input", content: "second" }, context)).wait(context);
870 const results = (await allEntries(root)).filter((entry) => ToolResultEntry.is(entry));
871 const texts = results.map((entry) => (entry.model![0] as { content: { text: string }[] }).content[1]!.text);
872 expect(texts).toEqual(["1", "[1]"]);
873 // A fork at the first input is from before the first script stored anything.
874 chat.setup.faux.setResponses([script(`return [load("k") ?? null]`), DONE]);
875 const fork = await root.fork(firstUser.id, { ownership: { kind: "ownerless" } }, context);
876 await (await fork.submit({ type: "input", content: "fork" }, context)).wait(context);
877 const forkResult = (await allEntries(fork)).filter((entry) => ToolResultEntry.is(entry)).at(-1)!;
878 expect((forkResult.model![0] as { content: { text: string }[] }).content[1]!.text).toBe("[null]");
879 await harness.close(context);
880 });
881
882 it("journals results that finish together in one commit", async () => {
883 const release = deferred();
884 let waiting = 0;
885 const chat = codemodeChat([
886 {
887 name: "wait",
888 execute: async () => {
889 if (++waiting === 50) release.resolve();
890 await release.promise;
891 return null;
892 },
893 },
894 ]);
895 chat.holds.block = false;
896 chat.setup.faux.setResponses([
897 script(`return (await Promise.all(Array.from({ length: 50 }, () => wait()))).length`),
898 DONE,
899 ]);
900 const { harness, root } = await openChat(await openNodeSqliteStorage(await sqlitePath()), chat.setup);
901 let journalCommits = 0;
902 harness.subscribeCommits((publication) => {
903 for (const change of publication.changes) {
904 if (change.type === "document" && change.record.kind === "pi.codemode.journal") journalCommits++;
905 }
906 });
907 await (await root.submit({ type: "input", content: "go" }, context)).wait(context);
908 expect(await resultText(chat.setup, root)).toEqual({ text: "50", isError: false });
909 // The journal's creation and a few groups, not one commit per result (51).
910 expect(journalCommits).toBeLessThan(10);
911 await harness.close(context);
912 });
913});
914
915describe("durable code mode output and tool search", () => {
916 /** Run `code` once in a chat with a Node environment; the result's content and details. */
917 async function runScript(code: string, chat = codemodeChat()) {
918 chat.holds.block = false;
919 const cwd = await mkdtemp(join(tmpdir(), "pi-codemode-env-"));
920 directories.add(cwd);
921 chat.setup.faux.setResponses([script(code), DONE]);
922 const { harness, root } = await openChat(await openNodeSqliteStorage(await sqlitePath()), chat.setup, {
923 env: new NodeExecutionEnv({ cwd }),
924 });
925 await (await root.submit({ type: "input", content: "go" }, context)).wait(context);
926 const entry = (await allEntries(root)).find((candidate) => ToolResultEntry.is(candidate))!;
927 const message = entry.model![0] as {
928 content: { type: string; text?: string }[];
929 isError: boolean;
930 details?: CodemodeToolDetails;
931 };
932 await harness.close(context);
933 return { text: message.content.map((item) => item.text ?? `<${item.type}>`).join(""), message };
934 }
935
936 it("lays out text items, console lines, and the returned value under a header", async () => {
937 const { text } = await runScript(`text("one"); console.log("log", 1); text({ two: 2 }); return "three";`);
938 expect(text).toMatch(/^Script completed\nWall time [\d.]+ seconds\nOutput:\n/);
939 expect(text).toContain('==> text 1/3 <==\none\n==> text 2/3 <==\n{"two":2}\n==> text 3/3 <==\nthree');
940 expect(text).toContain("<console_output>\nlog 1\n</console_output>");
941 });
942
943 it("cuts text past the token budget to its start and end, with the full text in a file", async () => {
944 const { text, message } = await runScript(
945 `// @options: {"max_output_tokens": 20}
946 text("BEGIN" + "x".repeat(1000) + "END");`,
947 );
948 expect(text).toContain("Warning: truncated output");
949 expect(text).toContain("BEGIN");
950 expect(text).toContain("END");
951 const path = message.details?.fullOutputPath;
952 expect(text).toContain(`[Full output: ${path}`);
953 expect(await readFile(path!, "utf8")).toBe(`BEGIN${"x".repeat(1000)}END`);
954 });
955
956 it("keeps a result inside the tool's output limits whatever max_output_tokens says, spilling the rest", async () => {
957 // 6 MiB of text: over the Harness's 4 MiB limit, which would cut it without a spill file.
958 const big = await runScript(
959 `// @options: {"max_output_tokens": 2000000}
960 return "x".repeat(6 * 1024 * 1024);`,
961 );
962 expect(big.text).toContain("Warning: truncated output");
963 expect(big.text.length).toBeLessThanOrEqual(1024 * 1024 + 1000);
964 expect((await readFile(big.message.details!.fullOutputPath!, "utf8")).length).toBe(6 * 1024 * 1024);
965 // 200,000 short lines: within the byte limit, over the 100,000 lines one.
966 const long = await runScript(
967 `// @options: {"max_output_tokens": 2000000}
968 return Array.from({ length: 200000 }, () => "a").join("\\n");`,
969 );
970 expect(long.text).toContain("Warning: truncated output");
971 expect(long.text.split("\n").length).toBeLessThan(100_000);
972 expect(long.message.details?.fullOutputPath).toBeDefined();
973 });
974
975 it("writes the result's files to the same paths when it reruns after a crash", async () => {
976 const chat = codemodeChat();
977 chat.holds.block = false;
978 const cwd = await mkdtemp(join(tmpdir(), "pi-codemode-env-"));
979 directories.add(cwd);
980 const written = deferred<string>();
981 // The process dies after the full output was written and before the result was committed.
982 class CrashAfterWrite extends NodeExecutionEnv {
983 override async writeFile(path: string, content: string | Uint8Array, callContext: Context) {
984 const result = await super.writeFile(path, content, callContext);
985 written.resolve(path);
986 await aborted(callContext.abortSignal!);
987 return result;
988 }
989 }
990 const storage = await sqlitePath();
991 chat.setup.faux.setResponses([script(`// @options: {"max_output_tokens": 20}\nreturn "x".repeat(1000);`), DONE]);
992 let opened = await openChat(await openNodeSqliteStorage(storage), chat.setup, {
993 env: new CrashAfterWrite({ cwd }),
994 });
995 const id = (await opened.root.submit({ type: "input", content: "go" }, context)).id;
996 const first = await written.promise;
997 await opened.harness.close(context);
998 opened = await openChat(await openNodeSqliteStorage(storage), chat.setup, { env: new NodeExecutionEnv({ cwd }) });
999 opened.harness.resume();
1000 expect((await (await opened.harness.submission(id, context))!.wait(context)).status).toBe("done");
1001 const entry = (await allEntries(opened.root)).find((candidate) => ToolResultEntry.is(candidate))!;
1002 const details = (entry.model![0] as { details?: CodemodeToolDetails }).details;
1003 expect(details?.fullOutputPath).toBe(first);
1004 directories.add(dirname(first));
1005 expect(await readdir(dirname(first))).toEqual(["output.txt"]);
1006 await opened.harness.close(context);
1007 });
1008
1009 it("saves images to files and names them next to the image", async () => {
1010 const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==";
1011 const { text, message } = await runScript(`image("data:image/png;base64,${png}");`);
1012 const saved = /\[Image saved to (\S+) \(image\/png, \d+ bytes\)\]/.exec(text);
1013 expect(saved).not.toBeNull();
1014 expect((await readFile(saved![1]!)).toString("base64")).toBe(png);
1015 expect(message.content.some((item) => item.type === "image")).toBe(true);
1016 });
1017
1018 it("calls a deferred tool the model is not offered, and finds it in ALL_TOOLS", async () => {
1019 const chat = codemodeChat();
1020 addTool(
1021 chat.setup.registry,
1022 defineTool({
1023 name: "later",
1024 description: "A deferred tool",
1025 parameters: Type.Object({}),
1026 deferred: true,
1027 execute: async () => ({ output: [{ type: "text", text: "later ran" }] }),
1028 }),
1029 );
1030 const { text } = await runScript(
1031 `return [await tools.later({}), ALL_TOOLS.some((tool) => tool.name === "later")];`,
1032 chat,
1033 );
1034 expect(text).toContain('["later ran",true]');
1035 });
1036
1037 it("reports a failed script with its error and the calls already made", async () => {
1038 const { text, message } = await runScript(`await tools.echo({ text: "a" }); throw new Error("boom");`);
1039 expect(message.isError).toBe(true);
1040 expect(text).toMatch(/^Script failed\n/);
1041 expect(text).toContain("Error: boom");
1042 expect(text).toContain("Tool calls made before the failure (they are not undone): echo (ok)");
1043 });
1044
1045 it("finds tools with searchTools(), describeTool(), and describeNamespace(), and lists them in ALL_TOOLS", async () => {
1046 const chat = codemodeChat([], [{ name: "github", description: "GitHub MCP server", prefix: "mcp__github__" }]);
1047 addTool(
1048 chat.setup.registry,
1049 tool("mcp__github__list_issues", async () => ({ output: [] })),
1050 );
1051 const { text } = await runScript(
1052 `const found = await searchTools("issues");
1053 const inNamespace = await searchTools("echo", { namespace: "github" });
1054 return {
1055 found: found.map((tool) => tool.name),
1056 inNamespace,
1057 described: (await describeTool("echo")).includes("echo(args:"),
1058 missing: (await describeTool("nope")) ?? null,
1059 namespace: await describeNamespace("github"),
1060 all: ALL_TOOLS.map((tool) => tool.name).includes("mcp__github__list_issues"),
1061 };`,
1062 chat,
1063 );
1064 expect(JSON.parse(text.replace(/^Script completed\nWall time [\d.]+ seconds\nOutput:\n/, ""))).toEqual({
1065 found: ["mcp__github__list_issues"],
1066 inNamespace: [],
1067 described: true,
1068 missing: null,
1069 namespace: { name: "github", description: "GitHub MCP server", tools: ["mcp__github__list_issues"] },
1070 all: true,
1071 });
1072 });
1073});