返回源码地图

packages/durable/src/codemode/codemode.ts

v1.3.0 · 71023aec1546 · 11:1–45与400–466及replay定位;VM replay另追测试

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

1/**
2 * Durable code mode: a tool that runs model-written JavaScript in a QuickJS sandbox, whose script survives a restart.
3 *
4 * Problem: a script is in-memory VM state. A restart while
5 *
6 * const results = await Promise.all(paths.map((path) => tools.read({ path })));
7 *
8 * waits for the last of 200 reads would lose the script and every read it made.
9 *
10 * Solution: deterministic replay (`CodemodeSandboxBase.start()` in pi-codemode). The VM only runs when the host hands
11 * it a result; given the same start data, clock, seed, and results in the same order, it makes the same calls with
12 * the same arguments. The tool is replay-safe: after a restart, `execute()` runs again, starts the script again from
13 * the stored start data, and hands it the results it got before, in the order it got them, from a journal written
14 * before each delivery. Nested tool calls reattach to their tasks by key (`c<VM call id>`), so they never run twice
15 * unless their own replay policy reruns them; their results come from `NestedCallDoc`. Then the script continues live.
16 *
17 * Documents, scoped to the code mode call's task and gone when it settles:
18 * - `pi.codemode.run`: the start data, written once before the VM starts, and the outcome, written once when the call
19 * decides it (with the store writes, in one transaction), so a rerun after that returns it without a VM.
20 * - `pi.codemode.journal`: one entry per delivered result, in delivery order: the VM call ID, the clock value, the
21 * calls the VM had issued after processing it (once acknowledged), and a global's outcome, which nothing else stores.
22 *
23 * Each result's acknowledged call count is recorded with the next journal commit, or at once when the VM has processed
24 * everything delivered: a script waiting on a long call is where a restart usually finds it. A sequential script
25 * therefore costs one journal commit and one count commit per result, on top of its nested calls' own; that is the
26 * price of checking the most common crash point.
27 *
28 * A call is launched only once the count of calls issued in the drain that made it is committed. So every key an earlier
29 * attempt admitted is at most its last recorded count; a replay checks every recorded count, so when it releases its
30 * calls it has made every call an earlier attempt could have admitted, and later calls are new.
31 *
32 * A rerun refuses to replay (no new nested calls; nested calls admitted earlier may still resume on their own and are
33 * aborted by the call's cleanup) when this module's version or the VM's fingerprint changed, when the deadline passed,
34 * or when the script diverges: it makes another call, or calls in another order, than the journal says. Each ends the
35 * call with an error result.
36 */
37import { type Context, copyJson, type JsonValue } from "@earendil-works/chord";
38import type { TextContent } from "@earendil-works/pi-ai";
39import {
40 type CodemodeHostCall,
41 type CodemodeOutcome,
42 type CodemodeResult,
43 type CodemodeRun,
44 type CodemodeSandboxBase,
45 toCodemodeIdentifier,
46} from "@earendil-works/pi-codemode/portable";
47import { CODEMODE_SOURCE_GRAMMAR, parseCodemodeSource } from "@earendil-works/pi-codemode/source";
48import { type Static, Type } from "typebox";
49import { defineDoc } from "../documents.ts";
50import type { ExecutionEnv } from "../env/index.ts";
51import { errorMessage } from "../errors.ts";
52import { defineExtension, defineTool, section } from "../harness/define.ts";
53import { NestedCallDoc, type ToolTaskInput } from "../harness/tool.ts";
54import type {
55 Extension,
56 NestedToolExecutionResult,
57 ToolExecutionApi,
58 ToolExecutionResult,
59 ToolRegistration,
60} from "../harness/types.ts";
61import { rankDocuments } from "../search.ts";
62import type { JsonObject } from "../types.ts";
63import {
64 type CodemodeNamespace,
65 codemodeDescription,
66 codemodeSection,
67 DEFAULT_CODEMODE_INLINE_BUDGET,
68 namespaceOf,
69 sampleOf,
70} from "./describe.ts";
71import {
72 CATALOG_GLOBALS,
73 CODEMODE_INTERNAL_PREFIX,
74 catalogCall,
75 createModelTools,
76 GENERATE_IMAGES_TOOL,
77 MAX_CONCURRENT_MODEL_CALLS,
78 MODEL_CALLS,
79} from "./models.ts";
80import { DEFAULT_MAX_OUTPUT_TOKENS, formatResult, type OutputFile } from "./output.ts";
81
82/**
83 * Version of everything in this module that turns stored results into what a script sees: result mapping, globals,
84 * start data. Bump it when that changes, so a call started before an upgrade is not replayed by different code.
85 */
86export const CODEMODE_MODULE_VERSION = 2;
87
88export const CODEMODE_TOOL_NAME = "codemode";
89
90/** One tool as the script sees it: `tools.<jsName>`. */
91/**
92 * `structured`: the tool declares `structuredOutputSchema`, so an error result with a value resolves with it.
93 * `hidden`: an internal tool of this extension (`pi.codemode.*`), which scripts reach only through a global such as
94 * `models.classify()`; never in `tools`, `ALL_TOOLS`, or tool search.
95 */
96type DeclaredTool = { name: string; jsName: string; description: string; structured?: true; hidden?: true };
97
98/** What a call starts with; a rerun starts the VM from exactly this. */
99type Start = {
100 version: number;
101 startedAt: number;
102 seed: number;
103 /** The VM's fingerprint, recorded by the first run before any call is admitted. */
104 fingerprint?: string;
105 /** `startedAt + timeout_ms` when the script set one. */
106 deadline?: number;
107 tools: DeclaredTool[];
108 /** The namespaces of the tools, as `describeNamespace()` and `searchTools()` see them. */
109 namespaces: { name: string; description?: string; instructions?: string; tools: string[] }[];
110 globals: { name: string; spread: boolean }[];
111 /** `max_output_tokens` of the script's options line, or the default. */
112 maxOutputTokens: number;
113 store: Record<string, JsonValue>;
114};
115
116type RunState = {
117 start?: Start;
118 /** Directory of the result's files (the full output, images), created once: a rerun writes the same files again. */
119 outputDir?: string;
120 /** The outcome, decided once. */
121 result?: JsonObject;
122};
123
124export const CodemodeRunDoc = defineDoc<RunState>({
125 kind: "pi.codemode.run",
126 version: 1,
127 scope: "task",
128 initial: () => ({}),
129});
130
131type JournalEntry = {
132 /** The VM's call ID. Its result is the entry's position + 1 (`seq`). */
133 id: number;
134 /** The VM clock while it processes this result. */
135 at: number;
136 /** Calls the VM had issued after processing this result; absent until acknowledged. */
137 issuedAfter?: number;
138 /** A global's call and outcome; a tool's result is its nested call's. */
139 global?: { name: string; args?: JsonValue; outcome: JsonObject };
140};
141
142type JournalState = {
143 entries: JournalEntry[];
144 /** Calls the VM had issued after the script's first run, before any result; absent until acknowledged. */
145 firstIssued?: number;
146};
147
148export const CodemodeJournalDoc = defineDoc<JournalState>({
149 kind: "pi.codemode.journal",
150 version: 1,
151 scope: "task",
152 initial: () => ({ entries: [] }),
153});
154
155/**
156 * What scripts keep with `store()` and read with `load()`, per conversation. Rewindable and copied as of the fork
157 * point, so a fork sees the values as they were when its entry was committed.
158 */
159export const CodemodeStoreDoc = defineDoc<{ values: Record<string, JsonValue> }>({
160 kind: "pi.codemode.store",
161 version: 1,
162 scope: "conversation",
163 history: "rewindable",
164 fork: "asOf",
165 initial: () => ({ values: {} }),
166});
167
168/** One tool call a script made, as the code mode call's details show it. */
169export type CodemodeNestedCall = {
170 /** The VM's number for the call; its nested call ID is `<callId>/c<id>`. */
171 id: number;
172 name: string;
173 /** Compact JSON of the arguments, cut for display. */
174 args: string;
175 status: "running" | "ok" | "error" | "cancelled";
176 durationMs?: number;
177 /** Error text, cut for display. */
178 error?: string;
179};
180
181/**
182 * The code mode call's details, in its result: its tool calls in the order it made them, with their status. Calls to
183 * globals are not listed. While the script runs, UIs show its nested calls from `pi.live.nestedTools`, so the list is
184 * written once, with the result.
185 */
186export type CodemodeToolDetails = {
187 calls: CodemodeNestedCall[];
188 /** Temp file with the complete text output, when the output was cut to its token budget. */
189 fullOutputPath?: string;
190};
191
192const ARGS_PREVIEW_CHARS = 200;
193const ERROR_PREVIEW_CHARS = 500;
194
195function cut(text: string, max: number): string {
196 return text.length > max ? `${text.slice(0, max - 3)}...` : text;
197}
198
199/** A function scripts call as a top-level global; its result is journaled. */
200export type CodemodeGlobal = {
201 readonly name: string;
202 readonly spread?: boolean;
203 execute(args: unknown, api: ToolExecutionApi, context: Context): Promise<JsonValue | undefined>;
204};
205
206const codemodeSchema = Type.Object({ code: Type.String({ description: "Raw JavaScript source." }) });
207
208export type CodemodeToolInput = Static<typeof codemodeSchema>;
209
210export type CodemodeToolOptions = {
211 /** Runs the scripts: `CodemodeSandbox` on Node, `RemoteCodemodeSandbox` on Cloudflare. */
212 readonly sandbox: CodemodeSandboxBase;
213 /** Groups of tools by name prefix, such as MCP servers, for the `codemode` section and tool search. */
214 readonly namespaces?: readonly CodemodeNamespace[];
215 /** Estimated tokens the tool declarations in the `codemode` section may use. Default 3000. */
216 readonly inlineBudget?: number;
217 /** Give scripts `models.*`: the model catalog, classifiers, and image generation. Default true. */
218 readonly models?: boolean;
219 /** @internal Host functions scripts call as globals. */
220 readonly globals?: readonly CodemodeGlobal[];
221};
222
223/** Outputs bounded by the script's own token budget; the Harness's limits only stop a runaway. */
224const OUTPUT_LIMITS = { maxBytes: 4 * 1024 * 1024, maxLines: 100_000 } as const;
225
226/** Globals for finding tools, answered from the start data, so a replay sees what the first run saw. */
227const DISCOVERY_GLOBALS = ["searchTools", "describeTool", "describeNamespace"] as const;
228const DEFAULT_SEARCH_LIMIT = 8;
229
230/** The code mode tool. Scripts call the conversation's callable tools as `tools.<name>(args)`. */
231export function createCodemodeTool(options: CodemodeToolOptions): ToolRegistration<typeof codemodeSchema> {
232 return defineTool({
233 name: CODEMODE_TOOL_NAME,
234 description: codemodeDescription(options.models !== false),
235 parameters: codemodeSchema,
236 outputLimits: OUTPUT_LIMITS,
237 // Capable models write the script as raw text instead of a JSON-escaped string; pi-ai applies it only for them.
238 constrainedSampling: { type: "grammar", variants: { openai_lark: CODEMODE_SOURCE_GRAMMAR } },
239 callers: ["model"],
240 replay: "safe",
241 execute: (args, api, context) => new CodemodeCall(options, api, context).execute(args.code),
242 });
243}
244
245/**
246 * The `codemode` extension: the code mode tool, and the `codemode` prompt section listing the tools scripts can call.
247 */
248export function createCodemodeExtension(options: CodemodeToolOptions): Extension {
249 return defineExtension({
250 name: "codemode",
251 tools: [createCodemodeTool(options), ...(options.models === false ? [] : createModelTools())],
252 sections: [
253 section("codemode", (input) =>
254 codemodeSection(
255 // Deferred tools are found with `searchTools()`, as the coding agent leaves them out too.
256 input.agent.callable.filter(
257 (tool) => !tool.name.startsWith(CODEMODE_INTERNAL_PREFIX) && tool.deferred !== true,
258 ),
259 options.namespaces ?? [],
260 options.inlineBudget ?? DEFAULT_CODEMODE_INLINE_BUDGET,
261 ),
262 ),
263 ],
264 });
265}
266
267/**
268 * What a script gets for a nested call, as in the coding agent. A tool with a schema resolves with its value, also on
269 * an error result that carries one (`bash`'s `{ output, exitCode }` for a nonzero exit); a schema-less tool
270 * resolves with its text output, images left out, as its declaration says. Any other error rejects, with its text: a
271 * schema-less tool's output, else its error diagnostics.
272 */
273function outcomeOf(name: string, structured: boolean, result: NestedToolExecutionResult): CodemodeOutcome {
274 const value = structured ? result.structuredOutput : textOf(result.structuredOutput);
275 if (!result.isError || (structured && value !== undefined)) return { ok: true, value };
276 const message = structured ? "" : (value as string);
277 const diagnostics = result.diagnostics
278 .filter((diagnostic) => diagnostic.severity === "error")
279 .map((diagnostic) => diagnostic.message)
280 .join("\n");
281 return {
282 ok: false,
283 message: message || diagnostics || `Tool ${name} failed`,
284 ...(value === undefined ? {} : { properties: { structuredOutput: value } }),
285 };
286}
287
288/** The text of a schema-less tool's collapsed output: a string, one image, or an array of text and image blocks. */
289function textOf(value: JsonValue | undefined): string {
290 if (typeof value === "string") return value;
291 if (!Array.isArray(value)) return "";
292 return value.flatMap((item) => (isText(item) ? [item.text] : [])).join("\n");
293}
294
295function isText(item: unknown): item is TextContent {
296 return typeof item === "object" && item !== null && (item as TextContent).type === "text";
297}
298
299function errorResult(message: string): ToolExecutionResult {
300 return { output: [{ type: "text", text: message }], isError: true };
301}
302
303/** One execution of the code mode tool: a first run, or a rerun after a restart that replays the journal. */
304class CodemodeCall {
305 private readonly options: CodemodeToolOptions;
306 private readonly api: ToolExecutionApi;
307 private readonly context: Context;
308 private readonly controller = new AbortController();
309 private run!: CodemodeRun;
310 private start!: Start;
311 /** The journal as this attempt found it; replay delivers exactly these. */
312 private replayed: JournalEntry[] = [];
313 /** Entries in the journal, replayed and live; the next delivery is `length + 1`. */
314 private journalLength = 0;
315 /** Replayed entries delivered so far. */
316 private nextReplayed = 0;
317 private replaying = false;
318 /** Whether an earlier attempt ran this call: its nested call keys may already exist. */
319 private rerun = false;
320 /** Whether live calls may launch; before, they are held (see `release()`). */
321 private released = false;
322 /** The count an earlier attempt recorded after the script's first run. */
323 private firstIssued: number | undefined;
324 /** The highest issued count known to be committed: calls up to it may launch. */
325 private durableIssued = 0;
326 /** Live calls waiting for their issued count to be committed. */
327 private waiting: CodemodeHostCall[] = [];
328 /** Journal index of each replayed call ID. */
329 private replayIndex = new Map<number, number>();
330 /** Calls the VM issued so far; its call IDs are 1, 2, ... */
331 private issued = 0;
332 /** Replay: results of journaled calls, ready to deliver in journal order. */
333 private readonly ready = new Map<number, CodemodeOutcome>();
334 /** Replay: calls the journal does not have, admitted once replay is done. */
335 private held: CodemodeHostCall[] = [];
336 /** Live: finished calls waiting for their journal commit. */
337 private queue: { id: number; at: number; outcome: CodemodeOutcome; global?: JournalEntry["global"] }[] = [];
338 /** Acknowledged counts to record, by result number (0: the script's first run). */
339 private readonly acks = new Map<number, number>();
340 private committing = false;
341 /** Set once the call decided an outcome other than the script's own (divergence, mismatch) or failed. */
342 private ended: ToolExecutionResult | undefined;
343 private failure: unknown;
344 /** `models.classify()`/`generateImages()` calls in flight, and those waiting for a slot. */
345 private modelCalls = 0;
346 private readonly modelWaiters: (() => void)[] = [];
347 /** Images `models.generateImages()` returned, to notice a script that never shows them. */
348 private generatedImages = 0;
349 /** The script's tool calls for `details`, by VM call ID. */
350 private readonly rows = new Map<number, CodemodeNestedCall>();
351 /** Resolves once the VM's fingerprint is checked or recorded; nothing is delivered or admitted before. */
352 private gate!: Promise<void>;
353 private openGate!: () => void;
354
355 constructor(options: CodemodeToolOptions, api: ToolExecutionApi, context: Context) {
356 this.options = options;
357 this.api = api;
358 this.context = context;
359 this.gate = new Promise((resolve) => {
360 this.openGate = resolve;
361 });
362 }
363
364 async execute(source: string): Promise<ToolExecutionResult> {
365 const { code, options: sourceOptions } = parseCodemodeSource(source);
366 const { api, context } = this;
367 const agent = await api.agent(context);
368 const tools: DeclaredTool[] = agent.callable.map((tool) => ({
369 name: tool.name,
370 jsName: toCodemodeIdentifier(tool.name),
371 description: sampleOf(tool),
372 ...(tool.structuredOutputSchema === undefined ? {} : { structured: true as const }),
373 ...(tool.name.startsWith(CODEMODE_INTERNAL_PREFIX) ? { hidden: true as const } : {}),
374 }));
375 const callable = agent.callable.filter((tool) => !tool.name.startsWith(CODEMODE_INTERNAL_PREFIX));
376 const models = this.options.models === false ? [] : [...CATALOG_GLOBALS, ...Object.keys(MODEL_CALLS)];
377 const globals = [
378 ...DISCOVERY_GLOBALS.map((name) => ({ name, spread: true })),
379 ...models.map((name) => ({ name, spread: true })),
380 ...(this.options.globals ?? []).map((global) => ({ name: global.name, spread: global.spread === true })),
381 ];
382 const namespaces: Start["namespaces"] = [];
383 for (const tool of callable) {
384 const namespace = namespaceOf(tool.name, this.options.namespaces ?? []);
385 if (namespace === undefined) continue;
386 let entry = namespaces.find((candidate) => candidate.name === namespace.name);
387 if (entry === undefined) {
388 entry = {
389 name: namespace.name,
390 ...(namespace.description === undefined ? {} : { description: namespace.description }),
391 ...(namespace.instructions === undefined ? {} : { instructions: namespace.instructions }),
392 tools: [],
393 };
394 namespaces.push(entry);
395 }
396 entry.tools.push(tool.name);
397 }
398 const now = Date.now();
399 const seed = crypto.getRandomValues(new Uint32Array(1))[0]!;
400 type Found =
401 | { done: ToolExecutionResult }
402 | { start: Start; journal: JournalEntry[]; firstIssued: number | undefined; rerun: boolean };
403 const found = await api.commit(async (tx): Promise<Found> => {
404 const run = await tx.doc(CodemodeRunDoc, api.taskId);
405 if (run.result !== undefined) return { done: copyJson(run.result as JsonValue) as ToolExecutionResult };
406 const rerun = run.start !== undefined;
407 if (run.start === undefined) {
408 const store = await tx.doc(CodemodeStoreDoc, api.conversationId);
409 const timeout = sourceOptions.timeoutMs;
410 run.start = {
411 version: CODEMODE_MODULE_VERSION,
412 startedAt: now,
413 seed,
414 ...(timeout === undefined ? {} : { deadline: now + timeout }),
415 tools,
416 namespaces,
417 globals,
418 maxOutputTokens: sourceOptions.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS,
419 store: copyJson(store.values as JsonValue) as Record<string, JsonValue>,
420 };
421 }
422 const journal = await tx.doc(CodemodeJournalDoc, api.taskId);
423 return {
424 start: copyJson(run.start as unknown as JsonValue) as unknown as Start,
425 journal: copyJson(journal.entries as unknown as JsonValue) as unknown as JournalEntry[],
426 firstIssued: journal.firstIssued,
427 rerun,
428 };
429 }, context);
430 if ("done" in found) return found.done;
431 this.start = found.start;
432 this.replayed = found.journal;
433 this.replayIndex = new Map(found.journal.map((entry, index) => [entry.id, index]));
434 this.journalLength = found.journal.length;
435 this.replaying = found.journal.length > 0;
436 this.rerun = found.rerun;
437 this.firstIssued = found.firstIssued;
438 // A loop, not spread arguments: a journal can hold more entries than a call takes arguments.
439 this.durableIssued = found.journal.reduce(
440 (max, entry) => Math.max(max, entry.issuedAfter ?? 0),
441 found.firstIssued ?? 0,
442 );
443
444 if (this.start.version !== CODEMODE_MODULE_VERSION) {
445 return this.decide(
446 errorResult(
447 `The script cannot resume: it started under code mode version ${this.start.version}, this is ${CODEMODE_MODULE_VERSION}.`,
448 ),
449 );
450 }
451 const remaining = this.start.deadline === undefined ? undefined : this.start.deadline - Date.now();
452 if (remaining !== undefined && remaining <= 0) {
453 return this.decide(errorResult(`Script timed out: its deadline passed while it was interrupted.`));
454 }
455
456 const onAbort = () => this.controller.abort(context.abortSignal?.reason);
457 context.abortSignal?.addEventListener("abort", onAbort, { once: true });
458 if (context.abortSignal?.aborted) onAbort();
459 try {
460 this.run = this.options.sandbox.start(code, {
461 startedAt: this.start.startedAt,
462 seed: this.start.seed,
463 tools: this.start.tools.filter((tool) => tool.hidden !== true),
464 globals: this.start.globals,
465 store: this.start.store,
466 signal: this.controller.signal,
467 ...(remaining === undefined ? {} : { timeoutMs: remaining }),
468 onStarted: (fingerprint) => void this.checkFingerprint(fingerprint),
469 onCall: (call) => this.onCall(call),
470 onIdle: (seq, issued) => this.onIdle(seq, issued),
471 });
472 const result = await this.run.result;
473 if (this.failure !== undefined) throw this.failure;
474 if (this.ended !== undefined) return this.ended;
475 context.abortSignal?.throwIfAborted();
476 // Aborted, but not by this call: the host closed the sandbox, for example while shutting down before closing the
477 // Harness. That decides nothing about the script: store nothing and end with this invocation, so a later attempt
478 // replays it.
479 if (!result.ok && result.error.kind === "aborted" && !this.controller.signal.aborted) {
480 await new Promise<void>((resolve) => {
481 if (context.abortSignal === undefined || context.abortSignal.aborted) resolve();
482 else context.abortSignal.addEventListener("abort", () => resolve(), { once: true });
483 });
484 context.abortSignal?.throwIfAborted();
485 throw new Error("The code mode sandbox was closed while the script ran");
486 }
487 // A replay that ends where the live run went on is a divergence (design §4.3).
488 const during = result.during;
489 // Within the replayed part, the first run included: a rerun without journal entries replays that much too.
490 if (this.rerun && during !== undefined && during.seq <= this.replayed.length) {
491 // The live run went on: it acknowledged that result, or it made a call that later results answer, which the
492 // replay never made.
493 const continued =
494 (during.seq === 0
495 ? this.replayed.length > 0 || this.firstIssued !== undefined
496 : this.replayed[during.seq - 1]?.issuedAfter !== undefined) ||
497 this.replayed.slice(during.seq).some((entry) => entry.id > during.issued);
498 if (continued) {
499 return this.decide(
500 errorResult(
501 `The script took a different path when resumed after a restart: it ended after result ${during.seq}, where it went on before.`,
502 ),
503 );
504 }
505 }
506 return this.complete(result);
507 } finally {
508 context.abortSignal?.removeEventListener("abort", onAbort);
509 }
510 }
511
512 /** Store an outcome the call decided, and end the VM if it runs; returns the outcome. */
513 private async decide(decided: ToolExecutionResult): Promise<ToolExecutionResult> {
514 const result = { ...decided, details: this.details() as unknown as JsonValue };
515 await this.api.commit(async (tx) => {
516 const run = await tx.doc(CodemodeRunDoc, this.api.taskId);
517 run.result ??= copyJson(result as unknown as JsonValue, { omitUndefinedProperties: true }) as JsonObject;
518 }, this.context);
519 return result;
520 }
521
522 /** End the call with `message`: store it as the outcome, then stop the VM with an error the script cannot catch. */
523 private diverge(message: string): void {
524 if (this.ended !== undefined || this.failure !== undefined) return;
525 const result = errorResult(`The script took a different path when resumed after a restart: ${message}`);
526 this.ended = result;
527 this.decide(result).then(
528 () => this.controller.abort(new Error(message)),
529 (error: unknown) => this.fail(error),
530 );
531 }
532
533 /** Whether nothing more may happen: the run has its outcome, or the call decided or failed. */
534 private get stopped(): boolean {
535 return this.ended !== undefined || this.failure !== undefined || this.run?.finished === true;
536 }
537
538 private fail(error: unknown): void {
539 if (this.failure !== undefined) return;
540 this.failure = error;
541 this.controller.abort(error);
542 }
543
544 /** The script's own outcome, stored with its store writes in one transaction. */
545 private async complete(result: CodemodeResult): Promise<ToolExecutionResult> {
546 const details = this.details();
547 const formatted = await formatResult(result, {
548 generatedImages: this.generatedImages,
549 wallMs: Date.now() - this.start.startedAt,
550 maxOutputTokens: this.start.maxOutputTokens,
551 calls: details.calls,
552 limits: OUTPUT_LIMITS,
553 write: this.outputFiles(),
554 });
555 const tool: ToolExecutionResult = {
556 output: formatted.content,
557 isError: !result.ok,
558 details: {
559 ...details,
560 ...(formatted.fullOutputPath === undefined ? {} : { fullOutputPath: formatted.fullOutputPath }),
561 } as unknown as JsonValue,
562 };
563 const writes = result.ok ? result.storeWrites : undefined;
564 return this.api.commit(async (tx) => {
565 const run = await tx.doc(CodemodeRunDoc, this.api.taskId);
566 if (run.result !== undefined) return run.result as ToolExecutionResult;
567 run.result = copyJson(tool as unknown as JsonValue, { omitUndefinedProperties: true }) as JsonObject;
568 if (writes !== undefined && (Object.keys(writes.set).length > 0 || writes.delete.length > 0)) {
569 const store = await tx.doc(CodemodeStoreDoc, this.api.conversationId);
570 for (const key of writes.delete) delete store.values[key];
571 for (const [key, value] of Object.entries(writes.set)) store.values[key] = value as JsonValue;
572 }
573 return tool;
574 }, this.context);
575 }
576
577 /** Writes the result's files under fixed names into the run's output directory, so a rerun overwrites them. */
578 private outputFiles(): OutputFile {
579 const env = this.api.env;
580 let directory: Promise<string> | undefined;
581 return async (name, data) => {
582 if (env === undefined) return { error: "no execution environment" };
583 try {
584 directory ??= this.outputDir(env);
585 const path = `${await directory}/${name}`;
586 const written = await env.writeFile(path, data, this.context);
587 return written.ok ? { path } : { error: written.error.message };
588 } catch (error) {
589 return { error: errorMessage(error) };
590 }
591 };
592 }
593
594 /** The run's output directory: the recorded one, else a new temp directory, recorded before any file is written. */
595 private async outputDir(env: ExecutionEnv): Promise<string> {
596 const recorded = await this.api.commit(
597 async (tx) => (await tx.doc(CodemodeRunDoc, this.api.taskId)).outputDir,
598 this.context,
599 );
600 if (recorded !== undefined) return recorded;
601 const created = await env.createTempDir("pi-codemode-", this.context);
602 if (!created.ok) throw new Error(created.error.message);
603 return this.api.commit(async (tx) => {
604 const run = await tx.doc(CodemodeRunDoc, this.api.taskId);
605 run.outputDir ??= created.value;
606 return run.outputDir!;
607 }, this.context);
608 }
609
610 private async checkFingerprint(fingerprint: string): Promise<void> {
611 const recorded = this.start.fingerprint;
612 if (recorded !== undefined) {
613 if (recorded !== fingerprint) {
614 this.ended = errorResult(
615 `The script cannot resume: the sandbox changed since it started (${recorded} -> ${fingerprint}).`,
616 );
617 await this.decide(this.ended).catch((error: unknown) => this.fail(error));
618 this.controller.abort(new Error("Sandbox fingerprint changed"));
619 return;
620 }
621 } else {
622 try {
623 await this.api.commit(async (tx) => {
624 const run = await tx.doc(CodemodeRunDoc, this.api.taskId);
625 if (run.start !== undefined) run.start.fingerprint = fingerprint;
626 }, this.context);
627 } catch (error) {
628 this.fail(error);
629 return;
630 }
631 }
632 this.openGate();
633 // Nothing was delivered before the gate: start now. A rerun without a journal releases its calls at the
634 // script's first acknowledgment instead.
635 if (this.replaying) this.deliverReplayed();
636 else if (!this.rerun) void this.release();
637 }
638
639 private onCall(made: CodemodeHostCall): void {
640 if (this.stopped) return;
641 const call = asToolCall(made);
642 if (call.target === "tool") this.started(call);
643 this.issued = Math.max(this.issued, call.id);
644 const index = this.replaying ? (this.replayIndex.get(call.id) ?? -1) : -1;
645 if (index === -1) {
646 if (this.released) {
647 this.waiting.push(call);
648 this.launchCovered();
649 } else this.held.push(call);
650 return;
651 }
652 const entry = this.replayed[index]!;
653 if (entry.global !== undefined) {
654 if (call.target !== "global" || call.name !== entry.global.name || !sameJson(call.args, entry.global.args)) {
655 this.diverge(`call ${call.id} is ${describe(call)}, but was a call to ${entry.global.name}`);
656 return;
657 }
658 this.ready.set(call.id, entry.global.outcome as CodemodeOutcome);
659 void this.gate.then(() => this.deliverReplayed());
660 return;
661 }
662 if (call.target !== "tool") {
663 this.diverge(`call ${call.id} is ${describe(call)}, but was a tool call`);
664 return;
665 }
666 void this.gate
667 .then(() => this.callTool(call))
668 .then(
669 (outcome) => {
670 this.ready.set(call.id, outcome);
671 this.deliverReplayed();
672 },
673 (error: unknown) => {
674 if (this.stopped) return;
675 if (this.context.abortSignal?.aborted) this.fail(error);
676 // The key names another tool or other arguments.
677 else this.diverge(`call ${call.id} is ${describe(call)}: ${errorMessage(error)}`);
678 },
679 );
680 }
681
682 /** Replay: deliver journaled results in journal order, each once the VM has issued its call. */
683 private deliverReplayed(): void {
684 while (this.nextReplayed < this.replayed.length && !this.stopped) {
685 const entry = this.replayed[this.nextReplayed]!;
686 const outcome = this.ready.get(entry.id);
687 if (entry.id > this.issued || outcome === undefined) return;
688 this.ready.delete(entry.id);
689 this.nextReplayed++;
690 this.run.deliver(this.nextReplayed, entry.at, entry.id, outcome);
691 }
692 }
693
694 private onIdle(seq: number, issued: number): void {
695 if (this.stopped) return;
696 // A count an earlier attempt recorded must match; a missing one is recorded now.
697 if (this.rerun && seq <= this.replayed.length) {
698 const recorded = seq === 0 ? this.firstIssued : this.replayed[seq - 1]!.issuedAfter;
699 if (recorded !== undefined && recorded !== issued) {
700 this.diverge(
701 seq === 0
702 ? `its first run made ${issued} calls, where it had made ${recorded}`
703 : `after result ${seq} it had made ${issued} calls, where it had made ${recorded}`,
704 );
705 return;
706 }
707 }
708 this.acks.set(seq, issued);
709 if (!this.replaying) {
710 // A rerun without a journal: every call an earlier attempt could have admitted is made by now.
711 if (seq === 0 && this.rerun) void this.release();
712 // Committed at once when the script has processed everything delivered: calls it made wait for it, and a script
713 // waiting on a long call is where a restart usually finds it. Otherwise with the next commit; the VM catches up
714 // without waiting on anything.
715 if (seq === this.journalLength) void this.pump();
716 return;
717 }
718 // Caught up: the VM processed everything delivered and waits.
719 if (seq !== this.nextReplayed) return;
720 const next = this.replayed[seq];
721 if (next !== undefined) {
722 if (next.id > issued) this.diverge(`it waits without making call ${next.id}, which it made before`);
723 return;
724 }
725 // The last replayed result is acknowledged: continue live, admitting the calls the journal did not have once their
726 // count is committed.
727 this.replaying = false;
728 void this.pump();
729 void this.release();
730 }
731
732 /**
733 * Let the held calls launch, and later live calls, each once its issued count is committed. On a rerun, an earlier
734 * attempt may have admitted some of them under their keys, as other calls: when the replay releases (idle after the
735 * last journaled result, or after its first run without a journal) its counts matched every recorded one, so it has
736 * made every call an earlier attempt could have admitted. All held calls are checked first, whatever their target,
737 * and a divergence launches none. Calls made after this are new.
738 */
739 private async release(): Promise<void> {
740 await this.gate;
741 if (this.stopped || this.released) return;
742 const calls = this.held.splice(0);
743 if (this.rerun) {
744 for (const call of calls) {
745 let other: string | undefined;
746 try {
747 other = await this.earlier(call);
748 } catch (error) {
749 this.fail(error);
750 return;
751 }
752 if (this.stopped) return;
753 if (other !== undefined) {
754 this.diverge(`call ${call.id} is ${describe(call)}, but was ${other}`);
755 return;
756 }
757 }
758 }
759 this.released = true;
760 this.waiting.push(...calls, ...this.held.splice(0));
761 this.launchCovered();
762 }
763
764 /** Launch the waiting calls whose issued count is committed. */
765 private launchCovered(): void {
766 if (!this.released || this.stopped) return;
767 const covered = this.waiting.filter((call) => call.id <= this.durableIssued);
768 if (covered.length === 0) return;
769 this.waiting = this.waiting.filter((call) => call.id > this.durableIssued);
770 for (const call of covered) this.launch(call);
771 }
772
773 /** The call an earlier attempt made under this call's key, when it is another one: another target, tool, or arguments. */
774 private async earlier(call: CodemodeHostCall): Promise<string | undefined> {
775 const { api, context } = this;
776 const taskId = (await api.snapshot(NestedCallDoc, api.taskId, `c${call.id}`, context))?.taskId;
777 if (taskId === undefined) return undefined;
778 const input = (await api.getTask(taskId, context))?.input as ToolTaskInput | undefined;
779 if (input?.kind !== "nested") return undefined;
780 const made = input.call;
781 if (call.target === "tool" && made.name === call.name && sameJson(made.arguments, call.args ?? {}))
782 return undefined;
783 return `tools.${made.name}(${JSON.stringify(made.arguments)})`;
784 }
785
786 /** Run one live call and journal its result. */
787 private launch(call: CodemodeHostCall): void {
788 if (this.stopped) return;
789 const running: Promise<{ outcome: CodemodeOutcome; global?: JournalEntry["global"] }> =
790 call.target === "tool"
791 ? this.callTool(call).then((outcome) => ({ outcome }))
792 : this.callGlobal(call).then((outcome) => ({
793 outcome,
794 global: {
795 name: call.name,
796 ...(call.args === undefined ? {} : { args: call.args as JsonValue }),
797 outcome: outcome as JsonObject,
798 },
799 }));
800 running.then(
801 (done) => {
802 this.queue.push({ id: call.id, at: Date.now(), ...done });
803 void this.pump();
804 },
805 (error: unknown) => {
806 // Stopped meanwhile: the outcome is decided, or a waiting model call gave up.
807 if (this.stopped) return;
808 if (this.context.abortSignal?.aborted) this.fail(error);
809 // A key an earlier attempt admitted with another tool or other arguments: this attempt took another path.
810 else this.diverge(`call ${call.id} is ${describe(call)}: ${errorMessage(error)}`);
811 },
812 );
813 }
814
815 private async callTool(call: CodemodeHostCall): Promise<CodemodeOutcome> {
816 // Passed as the script gave them; validation reports arguments that are not an object.
817 const args = (call.args ?? {}) as JsonObject;
818 const model = call.name.startsWith(CODEMODE_INTERNAL_PREFIX);
819 if (model) {
820 await this.modelSlot();
821 // The call may have stopped while this one waited: a finished script admits no new paid call.
822 if (this.stopped) {
823 this.releaseModelSlot();
824 throw new Error("The script has ended");
825 }
826 }
827 let result: NestedToolExecutionResult;
828 try {
829 result = await this.api.executeTool(call.name, args, this.context, { key: `c${call.id}` });
830 } finally {
831 if (model) this.releaseModelSlot();
832 }
833 if (call.name === GENERATE_IMAGES_TOOL) this.generatedImages += countImages(result.structuredOutput);
834 const structured = this.start.tools.find((tool) => tool.name === call.name)?.structured === true;
835 const outcome = outcomeOf(call.name, structured, result);
836 this.finishRow(call.id, outcome, result);
837 return outcome;
838 }
839
840 /** The script made a tool call: its row appears, running, also while it waits to launch. */
841 private started(call: CodemodeHostCall): void {
842 if (this.rows.has(call.id)) return;
843 const args = call.args === undefined ? "" : (JSON.stringify(call.args) ?? "");
844 const name = call.name.startsWith(CODEMODE_INTERNAL_PREFIX)
845 ? call.name.slice(CODEMODE_INTERNAL_PREFIX.length)
846 : call.name;
847 this.rows.set(call.id, { id: call.id, name, args: cut(args, ARGS_PREVIEW_CHARS), status: "running" });
848 }
849
850 /** A tool call ended: its row gets its status, duration, and error. */
851 /** The call ended: an error result is an error row, also when the script got its value (bash's nonzero exit). */
852 private finishRow(id: number, outcome: CodemodeOutcome, result: NestedToolExecutionResult): void {
853 const row = this.rows.get(id);
854 if (row === undefined) return;
855 row.status = result.isError ? "error" : "ok";
856 if (result.durationMs !== undefined) row.durationMs = result.durationMs;
857 const errors = result.diagnostics.filter((diagnostic) => diagnostic.severity === "error");
858 const error = !outcome.ok ? outcome.message : errors.map((diagnostic) => diagnostic.message).join("\n");
859 if (result.isError && error !== "") row.error = cut(error, ERROR_PREVIEW_CHARS);
860 }
861
862 /** The rows in call order; calls still running when the script ended were cancelled. */
863 private details(): CodemodeToolDetails {
864 const calls = [...this.rows.values()]
865 .sort((a, b) => a.id - b.id)
866 .map((row) => (row.status === "running" ? { ...row, status: "cancelled" as const } : row));
867 return { calls };
868 }
869
870 private async callGlobal(call: CodemodeHostCall): Promise<CodemodeOutcome> {
871 const discovery = (DISCOVERY_GLOBALS as readonly string[]).includes(call.name);
872 const catalog = (CATALOG_GLOBALS as readonly string[]).includes(call.name);
873 const global =
874 discovery || catalog ? undefined : this.options.globals?.find((candidate) => candidate.name === call.name);
875 if (!discovery && !catalog && global === undefined) return { ok: false, message: `Unknown global ${call.name}` };
876 try {
877 // `undefined` stays undefined: the journal omits the value, and a replay resolves with undefined again.
878 const value = discovery
879 ? this.discover(call)
880 : catalog
881 ? await catalogCall(call.name, call.args, this.api.models, this.context)
882 : await global!.execute(call.args, this.api, this.context);
883 return { ok: true, value };
884 } catch (error) {
885 if (this.context.abortSignal?.aborted) throw error;
886 return { ok: false, message: errorMessage(error) };
887 }
888 }
889
890 private async modelSlot(): Promise<void> {
891 if (this.modelCalls >= MAX_CONCURRENT_MODEL_CALLS) {
892 await new Promise<void>((resolve) => this.modelWaiters.push(resolve));
893 }
894 this.modelCalls++;
895 }
896
897 private releaseModelSlot(): void {
898 this.modelCalls--;
899 this.modelWaiters.shift()?.();
900 }
901
902 /** `searchTools()`, `describeTool()`, `describeNamespace()`: answered from the start data. */
903 private discover(call: CodemodeHostCall): JsonValue | undefined {
904 const args = Array.isArray(call.args) ? call.args : [];
905 const { namespaces } = this.start;
906 const tools = this.start.tools.filter((tool) => tool.hidden !== true);
907 const namespaceOfTool = (name: string) => namespaces.find((namespace) => namespace.tools.includes(name));
908 const matchesNamespace = (namespace: Start["namespaces"][number], query: string) =>
909 namespace.name === query || toCodemodeIdentifier(namespace.name) === toCodemodeIdentifier(query);
910 if (call.name === "describeTool") {
911 const [name] = args;
912 if (typeof name !== "string") throw new Error("describeTool() expects a tool name");
913 return tools.find((tool) => tool.name === name || tool.jsName === name)?.description;
914 }
915 if (call.name === "describeNamespace") {
916 const [name] = args;
917 if (typeof name !== "string") throw new Error("describeNamespace() expects a namespace name");
918 const namespace = namespaces.find((candidate) => matchesNamespace(candidate, name));
919 if (namespace === undefined) return undefined;
920 return {
921 name: namespace.name,
922 ...(namespace.description === undefined ? {} : { description: namespace.description }),
923 ...(namespace.instructions === undefined ? {} : { instructions: namespace.instructions }),
924 tools: namespace.tools.map((tool) => toCodemodeIdentifier(tool)),
925 };
926 }
927 const [query, options] = args as [unknown, { limit?: unknown; namespace?: unknown } | undefined];
928 if (typeof query !== "string") throw new Error("searchTools() expects a query string");
929 const limit = options?.limit ?? DEFAULT_SEARCH_LIMIT;
930 if (typeof limit !== "number" || !Number.isInteger(limit) || limit <= 0) {
931 throw new Error("searchTools() limit must be a positive integer");
932 }
933 const namespace = options?.namespace;
934 if (namespace !== undefined && namespace !== null && typeof namespace !== "string") {
935 throw new Error("searchTools() namespace must be a string");
936 }
937 const documents = tools.flatMap((tool) => {
938 const own = namespaceOfTool(tool.name);
939 if (typeof namespace === "string" && (own === undefined || !matchesNamespace(own, namespace))) return [];
940 const text = [
941 tool.name,
942 tool.name.replaceAll("_", " "),
943 tool.description,
944 own?.name ?? "",
945 own?.description ?? "",
946 ];
947 return [{ name: tool.name, text: text.join(" ") }];
948 });
949 return rankDocuments(query, documents, limit).map((name) => {
950 const tool = tools.find((candidate) => candidate.name === name)!;
951 return { name: tool.jsName, description: tool.description };
952 });
953 }
954
955 /**
956 * Journal finished calls and acknowledged counts in one commit, then deliver the calls and launch the calls the
957 * counts cover; one commit in flight at a time, so what arrives meanwhile goes into the next.
958 */
959 private async pump(): Promise<void> {
960 if (this.committing || this.stopped) return;
961 if (this.queue.length === 0 && this.acks.size === 0) return;
962 this.committing = true;
963 const batch = this.queue.splice(0);
964 const acks = [...this.acks];
965 this.acks.clear();
966 try {
967 await this.api.commit(async (tx) => {
968 const journal = await tx.doc(CodemodeJournalDoc, this.api.taskId);
969 for (const [seq, issued] of acks) {
970 if (seq === 0) journal.firstIssued ??= issued;
971 else {
972 const entry = journal.entries[seq - 1];
973 if (entry !== undefined && entry.issuedAfter === undefined) entry.issuedAfter = issued;
974 }
975 }
976 for (const item of batch) {
977 const entry = {
978 id: item.id,
979 at: item.at,
980 ...(item.global === undefined ? {} : { global: item.global }),
981 };
982 journal.entries.push(
983 copyJson(entry as unknown as JsonValue, { omitUndefinedProperties: true }) as unknown as JournalEntry,
984 );
985 }
986 }, this.context);
987 } catch (error) {
988 this.fail(error);
989 return;
990 }
991 for (const [, issued] of acks) this.durableIssued = Math.max(this.durableIssued, issued);
992 for (const item of batch) {
993 this.journalLength++;
994 if (!this.run.finished) this.run.deliver(this.journalLength, item.at, item.id, item.outcome);
995 }
996 this.launchCovered();
997 this.committing = false;
998 void this.pump();
999 }
1000}
1001
1002/** A script's call of `models.classify()` or `models.generateImages()` as the call of its internal tool. */
1003function asToolCall(call: CodemodeHostCall): CodemodeHostCall {
1004 const tool = call.target === "global" ? MODEL_CALLS[call.name] : undefined;
1005 if (tool === undefined) return call;
1006 const [model, context] = Array.isArray(call.args) ? call.args : [];
1007 return { id: call.id, target: "tool", name: tool, args: { model: model ?? null, context: context ?? null } };
1008}
1009
1010/** Image blocks in a `models.generateImages()` result. */
1011function countImages(value: unknown): number {
1012 const output = typeof value === "object" && value !== null ? (value as { output?: unknown }).output : undefined;
1013 return Array.isArray(output) ? output.filter((item) => (item as { type?: unknown })?.type === "image").length : 0;
1014}
1015
1016function describe(call: CodemodeHostCall): string {
1017 return `${call.target === "tool" ? "tools." : ""}${call.name}(${JSON.stringify(call.args) ?? ""})`;
1018}
1019
1020/** Structural JSON equality; key order does not matter. */
1021function sameJson(a: unknown, b: unknown): boolean {
1022 if (a === b) return true;
1023 if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
1024 if (Array.isArray(a) || Array.isArray(b)) {
1025 return (
1026 Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((item, i) => sameJson(item, b[i]))
1027 );
1028 }
1029 const keys = Object.keys(a);
1030 return (
1031 keys.length === Object.keys(b).length &&
1032 keys.every(
1033 (key) =>
1034 Object.hasOwn(b, key) && sameJson((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]),
1035 )
1036 );
1037}