返回源码地图

packages/coding-agent/src/extensions/codemode/execute.ts

v1.3.0 · 71023aec1546 · 09/15:nested结果映射、live worker上限2、256MiB、成功store提交

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

1/**
2 * Runs one codemode script in the sandbox. Split from tool.ts and loaded through
3 * execute.lazy.ts so the sandbox runtime only loads when a script runs.
4 */
5
6import type { AgentTool, AgentToolCallOutcome, AgentToolResult } from "@earendil-works/pi-agent-core";
7import type {
8 AnyModel,
9 ClassifierContext,
10 ImageContent,
11 ImagesContext,
12 ModelType,
13 ModelTypeMap,
14 TextContent,
15 Usage,
16} from "@earendil-works/pi-ai";
17import {
18 type CodemodeOutputItem,
19 type CodemodeResult,
20 CodemodeSandbox,
21 type CodemodeTool,
22 loadQuickJSWasm,
23 parseCodemodeSource,
24 renderToolSample,
25 toCodemodeIdentifier,
26} from "@earendil-works/pi-codemode";
27import { getCodemodeWorkerSpecifier, getQuickJSWasmPath } from "../../config.ts";
28import type { ExtensionToolContext, ToolNamespace } from "../../core/extensions/types.ts";
29import type { SessionEntry } from "../../core/session-manager.ts";
30import { formatSize } from "../../core/tools/truncate.ts";
31import { combineUsage } from "../../core/usage-totals.ts";
32import { writeOutputFile } from "../../utils/output-files.ts";
33import { Bm25Ranker, createToolSearchDocument, DEFAULT_TOOL_SEARCH_LIMIT } from "../tool-search/tool.ts";
34import {
35 CODEMODE_DOCS_PATH,
36 CODEMODE_STORE_ENTRY_TYPE,
37 type CodemodeModelRuntime,
38 type CodemodeNestedCall,
39 type CodemodeStoreEntryData,
40 type CodemodeToolDetails,
41 type CodemodeToolInput,
42 type CodemodeToolOptions,
43 getCodemodeCallableTools,
44 toCodemodeDeclaration,
45} from "./tool.ts";
46
47const ARGS_PREVIEW_CHARS = 200;
48const ERROR_PREVIEW_CHARS = 500;
49/** `models.classify()` and `models.generateImages()` calls one script may have in flight; `Promise.all` over many items queues the rest. */
50const MAX_CONCURRENT_MODEL_CALLS = 4;
51/**
52 * Heap limit for the QuickJS VM. The worker shares pi's process, so without a limit a runaway
53 * script can grow to wasm32's 4 GiB and take the session down. Overruns throw
54 * `InternalError: out of memory` inside the script.
55 */
56const CODEMODE_MEMORY_LIMIT_BYTES = 256 * 1024 * 1024;
57// Shared across calls and sessions. Allow one replacement while a cancelled worker is still exiting.
58const MAX_CONCURRENT_CODEMODE_WORKERS = 2;
59let activeCodemodeWorkers = 0;
60const MODEL_TYPES: ReadonlySet<string> = new Set<ModelType>(["chat", "image", "classifier"]);
61
62function truncateText(text: string, maxChars: number): string {
63 return text.length > maxChars ? `${text.slice(0, maxChars - 3)}...` : text;
64}
65
66function previewArgs(args: unknown): string {
67 if (args === undefined) return "";
68 try {
69 return truncateText(JSON.stringify(args) ?? "", ARGS_PREVIEW_CHARS);
70 } catch {
71 return "";
72 }
73}
74
75function textOf(result: AgentToolResult<unknown>): string {
76 return (result.content ?? [])
77 .filter((block): block is TextContent => block.type === "text")
78 .map((block) => block.text)
79 .join("\n");
80}
81
82function toModelType(value: unknown): ModelType {
83 if (typeof value === "string" && MODEL_TYPES.has(value)) return value as ModelType;
84 throw new Error(`Unknown model type ${JSON.stringify(value)}. Use "chat", "image", or "classifier".`);
85}
86
87function toProvider(value: unknown): string | undefined {
88 if (value === undefined || value === null) return undefined;
89 if (typeof value !== "string") throw new Error("provider must be a string");
90 return value;
91}
92
93/** Catalog entry for scripts. `headers` is dropped because models.json headers can carry credentials. */
94function toModelInfo(model: AnyModel): Record<string, unknown> {
95 const info: Record<string, unknown> = { ...model };
96 delete info.headers;
97 return info;
98}
99
100/** `an image`, `a classifier`. */
101function withArticle(word: string): string {
102 return `${/^[aeiou]/.test(word) ? "an" : "a"} ${word}`;
103}
104
105/** A JSON value from a script, read field by field: values that are not objects have no fields. */
106type ScriptValue = { readonly [key: string]: unknown } | null | undefined;
107
108/** A script value in an error message: `undefined`, `a string`, `an array`, or its keys (`{ prompt }`). */
109function describeValue(value: unknown): string {
110 if (value === undefined || value === null) return String(value);
111 if (Array.isArray(value)) return value.length === 0 ? "an empty array" : "an array";
112 if (typeof value === "object") {
113 const keys = Object.keys(value);
114 if (keys.length === 0) return "{}";
115 return `{ ${keys.slice(0, 6).join(", ")}${keys.length > 6 ? ", ..." : ""} }`;
116 }
117 return typeof value === "string" ? "a string" : `a ${typeof value}`;
118}
119
120const CLASSIFIER_CONTEXT_SHAPE =
121 '{ state: { ... }, images?: [{ type: "image", data: <base64>, mimeType }], questions: { <id>: { type: "choice", instructions, criteria: { <label>: <meaning> } } | { type: "score", instructions, criteria: [<lowest level>, ..., <highest level>] } | { type: "bool", instructions, criteria: { true: <meaning>, false: <meaning> } } } }';
122
123/** Check a script's classifier context, so mistakes fail with the expected shape instead of a provider error. */
124function checkClassifierContext(context: unknown): ClassifierContext {
125 const fail = (problem: string) =>
126 new Error(
127 `models.classify() ${problem}. Expected context: ${CLASSIFIER_CONTEXT_SHAPE}. See "Classify" in ${CODEMODE_DOCS_PATH}.`,
128 );
129 if (typeof context !== "object" || context === null || Array.isArray(context)) {
130 throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);
131 }
132 const { state, images, questions } = context as Record<string, unknown>;
133 if (typeof state !== "object" || state === null || Array.isArray(state)) {
134 throw fail(`context.state must be an object, got ${describeValue(state)}`);
135 }
136 if (images !== undefined) {
137 if (!Array.isArray(images)) throw fail(`context.images must be an array, got ${describeValue(images)}`);
138 images.forEach((image: ScriptValue, index) => {
139 if (image?.type !== "image" || typeof image.data !== "string" || typeof image.mimeType !== "string") {
140 throw fail(`context.images[${index}] must be an image block, got ${describeValue(image)}`);
141 }
142 });
143 }
144 if (
145 typeof questions !== "object" ||
146 questions === null ||
147 Array.isArray(questions) ||
148 Object.keys(questions).length === 0
149 ) {
150 throw fail(`context.questions must map question IDs to questions, got ${describeValue(questions)}`);
151 }
152 const isStrings = (values: unknown[]) => values.length > 0 && values.every((value) => typeof value === "string");
153 for (const [id, question] of Object.entries(questions)) {
154 const at = `context.questions.${id}`;
155 if (typeof question !== "object" || question === null || Array.isArray(question)) {
156 throw fail(`${at} must be a question object, got ${describeValue(question)}`);
157 }
158 const { type, instructions, criteria } = question as Record<string, unknown>;
159 if (typeof instructions !== "string") throw fail(`${at}.instructions must be a string`);
160 if (type === "choice") {
161 if (
162 typeof criteria !== "object" ||
163 criteria === null ||
164 Array.isArray(criteria) ||
165 !isStrings(Object.values(criteria))
166 ) {
167 throw fail(`${at} is a "choice" question, so criteria must map each label to its meaning`);
168 }
169 } else if (type === "score") {
170 if (!Array.isArray(criteria) || !isStrings(criteria)) {
171 throw fail(`${at} is a "score" question, so criteria must list the levels as strings, lowest first`);
172 }
173 } else if (type === "bool") {
174 const labels = criteria as ScriptValue;
175 if (typeof labels?.true !== "string" || typeof labels.false !== "string") {
176 throw fail(`${at} is a "bool" question, so criteria must be { true: string, false: string }`);
177 }
178 } else {
179 throw fail(`${at}.type must be "choice", "score", or "bool", got ${JSON.stringify(type)}`);
180 }
181 }
182 return context as unknown as ClassifierContext;
183}
184
185/** Check a script's image context, so mistakes such as `{ prompt }` fail with the expected shape. */
186function checkImagesContext(context: unknown): ImagesContext {
187 const fail = (problem: string) =>
188 new Error(
189 `models.generateImages() ${problem}. Expected context: { input: [{ type: "text", text: <prompt> }, ...optional { type: "image", data: <base64>, mimeType } references] }. See "Generate images" in ${CODEMODE_DOCS_PATH}.`,
190 );
191 if (typeof context !== "object" || context === null || Array.isArray(context)) {
192 throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);
193 }
194 const { input } = context as Record<string, unknown>;
195 if (!Array.isArray(input) || input.length === 0) {
196 throw fail(`context.input must be a non-empty array of blocks, got ${describeValue(input)}`);
197 }
198 input.forEach((block: ScriptValue, index) => {
199 if (block?.type === "text" && typeof block.text === "string") return;
200 if (block?.type === "image" && typeof block.data === "string" && typeof block.mimeType === "string") return;
201 throw fail(`context.input[${index}] must be a text or image block, got ${describeValue(block)}`);
202 });
203 return context as unknown as ImagesContext;
204}
205
206/** The fields of `ClassifierResult` and `AssistantImages` that a nested call row reports. */
207interface ModelCallResult {
208 stopReason: "stop" | "error" | "aborted";
209 errorMessage?: string;
210 usage?: Usage;
211}
212
213/** Runs at most `limit` calls at once, in call order. */
214function createLimiter(limit: number): <T>(run: () => Promise<T>) => Promise<T> {
215 let active = 0;
216 const waiting: (() => void)[] = [];
217 return async (run) => {
218 if (active >= limit) await new Promise<void>((resolve) => waiting.push(resolve));
219 active++;
220 try {
221 return await run();
222 } finally {
223 active--;
224 waiting.shift()?.();
225 }
226 };
227}
228
229function isStoreEntryData(data: unknown): data is CodemodeStoreEntryData {
230 if (typeof data !== "object" || data === null) return false;
231 const { set, delete: deleted } = data as Partial<CodemodeStoreEntryData>;
232 return (
233 typeof set === "object" &&
234 set !== null &&
235 Array.isArray(deleted) &&
236 deleted.every((key: unknown) => typeof key === "string")
237 );
238}
239
240/** Values of `load()`: the `codemode-store` entries on the branch, applied from the root. */
241export function readCodemodeStore(branch: readonly SessionEntry[]): Record<string, unknown> {
242 const store = new Map<string, unknown>();
243 for (const entry of branch) {
244 if (entry.type !== "custom" || entry.customType !== CODEMODE_STORE_ENTRY_TYPE || !isStoreEntryData(entry.data)) {
245 continue;
246 }
247 for (const key of entry.data.delete) store.delete(key);
248 for (const [key, value] of Object.entries(entry.data.set)) store.set(key, value);
249 }
250 return Object.fromEntries(store);
251}
252
253/** Default token budget for script output. */
254const DEFAULT_MAX_OUTPUT_TOKENS = 10_000;
255/** Characters per token when estimating. */
256const CHARS_PER_TOKEN = 4;
257
258/** Like the script's `text()`: strings as is, other values as compact JSON. */
259function valueText(value: unknown): string {
260 if (typeof value === "string") return value;
261 return JSON.stringify(value) ?? String(value);
262}
263
264/**
265 * Lay out the script's output so the model can tell items apart: providers join adjacent text
266 * blocks with a newline or with nothing. With more than one text item (`text()` or the returned
267 * value), each starts with a `==> text N/M <==` line. `console.*` lines follow all other output in
268 * one `<console_output>` block.
269 */
270function formatOutput(output: readonly CodemodeOutputItem[]): (TextContent | ImageContent)[] {
271 const total = output.filter((item) => item.type === "text" && !item.console).length;
272 const items: (TextContent | ImageContent)[] = [];
273 const consoleLines: string[] = [];
274 let index = 0;
275 for (const item of output) {
276 if (item.type === "image") {
277 items.push(item);
278 } else if (item.console) {
279 consoleLines.push(item.text);
280 } else {
281 index++;
282 items.push({ type: "text", text: total > 1 ? `==> text ${index}/${total} <==\n${item.text}` : item.text });
283 }
284 }
285 if (consoleLines.length > 0) {
286 items.push({ type: "text", text: `<console_output>\n${consoleLines.join("\n")}\n</console_output>` });
287 }
288 return items;
289}
290
291/**
292 * Join adjacent text items into one, each part starting on its own line. The separator check looks
293 * at the last non-empty part, not the joined text: reading the end of a growing concatenation makes
294 * V8 copy it on every item, which is quadratic (#10678).
295 */
296function joinAdjacentText(items: (TextContent | ImageContent)[]): (TextContent | ImageContent)[] {
297 const joined: (TextContent | ImageContent)[] = [];
298 let parts: string[] = [];
299 let lastPart = "";
300 const flush = () => {
301 if (parts.length > 0) joined.push({ type: "text", text: parts.join("") });
302 parts = [];
303 lastPart = "";
304 };
305 for (const item of items) {
306 if (item.type !== "text") {
307 flush();
308 joined.push(item);
309 continue;
310 }
311 if (lastPart !== "" && !lastPart.endsWith("\n")) {
312 parts.push("\n");
313 lastPart = "\n";
314 }
315 parts.push(item.text);
316 if (item.text !== "") lastPart = item.text;
317 }
318 flush();
319 return joined;
320}
321
322function formatCallSummary(calls: readonly CodemodeNestedCall[]): string {
323 if (calls.length === 0) return "No tool calls were made.";
324 return `Tool calls made before the failure (they are not undone): ${calls.map((call) => `${call.name} (${call.status})`).join(", ")}`;
325}
326
327function formatError(result: Extract<CodemodeResult, { ok: false }>, calls: readonly CodemodeNestedCall[]): string {
328 const { error } = result;
329 const head =
330 error.kind === "script"
331 ? (error.stack ?? `${error.name ?? "Error"}: ${error.message}`)
332 : error.kind === "timeout"
333 ? `Script timed out: ${error.message}`
334 : error.kind === "aborted"
335 ? `Script aborted: ${error.message}`
336 : `Script sandbox failed: ${error.message}`;
337 return `${head}\n\n${formatCallSummary(calls)}`;
338}
339
340/** Write the full text output to a temp file, like bash does for truncated output. */
341async function spillOutput(text: string): Promise<{ path: string } | { error: string }> {
342 try {
343 return { path: await writeOutputFile("pi-codemode", ".txt", text) };
344 } catch (error) {
345 return { error: error instanceof Error ? error.message : String(error) };
346 }
347}
348
349/** File extensions of the image types `image()` accepts. Must list every type the sandbox's `image()` detects. */
350const IMAGE_EXTENSIONS: Record<string, string> = {
351 "image/png": ".png",
352 "image/jpeg": ".jpg",
353 "image/gif": ".gif",
354 "image/webp": ".webp",
355};
356
357/**
358 * Save each image to a temp file and put a text item with its path before it. The model sees the
359 * image but has no other way to reach its bytes: scripts cannot write files, and `write` only takes
360 * text. Images shown more than once are saved once.
361 */
362async function saveImages(items: (TextContent | ImageContent)[]): Promise<(TextContent | ImageContent)[]> {
363 const labels = new Map<string, Promise<string>>();
364 const label = async ({ data, mimeType }: ImageContent): Promise<string> => {
365 const bytes = Buffer.from(data, "base64");
366 const kind = `${mimeType}, ${formatSize(bytes.length)}`;
367 const extension = IMAGE_EXTENSIONS[mimeType];
368 if (!extension) throw new Error(`No file extension for image type ${mimeType}`);
369 // A failed write (disk full, unwritable temp dir) must not discard the result of a script whose
370 // tool calls already ran, so it becomes part of the label.
371 try {
372 const path = await writeOutputFile("pi-codemode", extension, bytes);
373 return `[Image saved to ${path} (${kind})]`;
374 } catch (error) {
375 return `[Image (${kind}) could not be saved: ${error instanceof Error ? error.message : String(error)}]`;
376 }
377 };
378 const result = await Promise.all(
379 items.map(async (item): Promise<(TextContent | ImageContent)[]> => {
380 if (item.type !== "image") return [item];
381 let pending = labels.get(item.data);
382 if (!pending) {
383 pending = label(item);
384 labels.set(item.data, pending);
385 }
386 return [{ type: "text", text: await pending }, item];
387 }),
388 );
389 return result.flat();
390}
391
392/**
393 * Apply the token budget: when the combined text exceeds it, the text items become one
394 * item that keeps the start and end of the text, and images follow it. The full text is written to
395 * a temp file.
396 */
397async function truncateOutput(
398 items: (TextContent | ImageContent)[],
399 maxTokens: number,
400): Promise<{ items: (TextContent | ImageContent)[]; fullOutputPath?: string }> {
401 const texts = items.filter((item): item is TextContent => item.type === "text").map((item) => item.text);
402 const combined = texts.join("\n");
403 const budget = maxTokens * CHARS_PER_TOKEN;
404 if (texts.length === 0 || combined.length <= budget) return { items };
405 const headChars = Math.floor(budget / 2);
406 const tailChars = budget - headChars;
407 const removed = combined.length - headChars - tailChars;
408 const head = combined.slice(0, headChars);
409 const tail = tailChars > 0 ? combined.slice(-tailChars) : "";
410 let text = `Warning: truncated output (original token count: ${Math.ceil(combined.length / CHARS_PER_TOKEN)})\nTotal output lines: ${combined.split("\n").length}\n\n${head}…${Math.ceil(removed / CHARS_PER_TOKEN)} tokens truncated…${tail}`;
411 const spilled = await spillOutput(combined);
412 text +=
413 "path" in spilled
414 ? `\n\n[Full output: ${spilled.path} (read with offset/limit)]`
415 : `\n\n[Could not save the full output: ${spilled.error}]`;
416 return {
417 items: [{ type: "text", text }, ...items.filter((item) => item.type === "image")],
418 ...("path" in spilled ? { fullOutputPath: spilled.path } : {}),
419 };
420}
421
422/**
423 * The value a script receives for a nested call: a tool that declares
424 * `outputSchema` resolves to its `structuredContent`, also for error results that carry one (such
425 * as MCP results with `isError`); any other tool resolves to its text content. Other failures
426 * reject with the tool's error text.
427 */
428function toScriptValue(tool: AgentTool<any>, outcome: AgentToolCallOutcome): unknown {
429 const { result } = outcome;
430 if (tool.outputSchema && result.structuredContent !== undefined) return result.structuredContent;
431 const text = textOf(result);
432 if (outcome.isError) throw new Error(text || `Tool "${tool.name}" failed`);
433 return text;
434}
435
436/**
437 * Run one script. Without a session context (a plain Agent or a direct call) scripts cannot call
438 * tools, `store()` starts empty, and writes are dropped.
439 */
440export async function executeCodemode(
441 toolCallId: string,
442 input: CodemodeToolInput,
443 signal: AbortSignal | undefined,
444 onUpdate: ((result: AgentToolResult<CodemodeToolDetails>) => void) | undefined,
445 ctx: ExtensionToolContext | undefined,
446 options: CodemodeToolOptions = {},
447): Promise<AgentToolResult<CodemodeToolDetails>> {
448 const startedAt = performance.now();
449 const { code, options: sourceOptions } = parseCodemodeSource(input.code);
450 const calls: CodemodeNestedCall[] = [];
451 // Usage of the script's `models.*` calls. Nested tool calls report theirs through the session.
452 let modelUsage: Usage | undefined;
453 // Images returned by `models.generateImages()`, to notice a script that never shows them.
454 let generatedImages = 0;
455 const addGeneratedImages = (count: number) => {
456 generatedImages += count;
457 };
458 const addModelUsage = (usage: Usage) => {
459 modelUsage = modelUsage ? combineUsage(modelUsage, usage) : usage;
460 };
461
462 const snapshot = (): CodemodeToolDetails => ({ calls: calls.map((call) => ({ ...call })) });
463 const publish = () => onUpdate?.({ content: [], details: snapshot() });
464 // Show the script as running before its first nested call, so the row's timer starts.
465 publish();
466
467 const callable = ctx ? getCodemodeCallableTools(ctx.tools) : [];
468 // ALL_TOOLS entries carry the declaration.
469 const guidelines = options.getToolGuidelines?.();
470 const samples = new Map(
471 callable.map((tool) => [tool.name, renderToolSample(toCodemodeDeclaration(tool, guidelines?.get(tool.name)))]),
472 );
473 const sandboxTools: CodemodeTool[] = callable.map((tool) => ({
474 name: tool.name,
475 description: samples.get(tool.name),
476 execute: async (args, { signal: callSignal }) => {
477 const record: CodemodeNestedCall = {
478 id: `${toolCallId}/?`,
479 name: tool.name,
480 args: previewArgs(args),
481 status: "running",
482 };
483 calls.push(record);
484 publish();
485 const callStartedAt = performance.now();
486 // Only tools from ctx.tools are callable, so ctx is set here.
487 if (!ctx) throw new Error("Tool calls need a session");
488 const outcome = await ctx.executeTool(tool.name, args, { signal: callSignal });
489 record.id = outcome.toolCall.id;
490 record.durationMs = performance.now() - callStartedAt;
491 if (outcome.isError) {
492 record.status = callSignal.aborted ? "cancelled" : "error";
493 record.error = truncateText(textOf(outcome.result) || `Tool "${tool.name}" failed`, ERROR_PREVIEW_CHARS);
494 } else {
495 record.status = "ok";
496 }
497 publish();
498 return toScriptValue(tool, outcome);
499 },
500 }));
501
502 const sandbox = new CodemodeSandbox({
503 tools: sandboxTools,
504 globals: [
505 ...createDiscoveryGlobals(callable, samples, options),
506 ...(options.models && ctx
507 ? createModelGlobals(ctx.modelRegistry, toolCallId, calls, publish, addModelUsage, addGeneratedImages)
508 : []),
509 ],
510 timeoutMs: sourceOptions.timeoutMs ?? Number.POSITIVE_INFINITY,
511 memoryLimitBytes: CODEMODE_MEMORY_LIMIT_BYTES,
512 wasm: loadQuickJSWasm(getQuickJSWasmPath()),
513 workerUrl: getCodemodeWorkerSpecifier(),
514 acquireWorker: () => {
515 if (activeCodemodeWorkers >= MAX_CONCURRENT_CODEMODE_WORKERS) {
516 throw new Error(
517 `Codemode worker limit reached (${MAX_CONCURRENT_CODEMODE_WORKERS} workers are still running or shutting down). Retry after they exit.`,
518 );
519 }
520 activeCodemodeWorkers++;
521 return () => {
522 activeCodemodeWorkers--;
523 };
524 },
525 });
526
527 let result: CodemodeResult;
528 try {
529 const store = ctx ? readCodemodeStore(ctx.sessionManager.getBranch()) : {};
530 result = await sandbox.execute(code, { signal, store });
531 } finally {
532 await sandbox.close();
533 }
534 // Calls still marked running were cut off by the script ending, a timeout, or an abort.
535 for (const call of calls) {
536 if (call.status === "running") call.status = "cancelled";
537 }
538
539 const scriptOutput = [...result.output];
540 if (result.ok) {
541 const { set, delete: deleted } = result.storeWrites;
542 if (Object.keys(set).length > 0 || deleted.length > 0) {
543 options.appendEntry?.(CODEMODE_STORE_ENTRY_TYPE, { set, delete: deleted });
544 }
545 // pi extension: a returned value is appended like text().
546 if (result.value !== undefined) scriptOutput.push({ type: "text", text: valueText(result.value) });
547 }
548 const items = formatOutput(scriptOutput);
549 if (!result.ok) items.push({ type: "text", text: `Script error:\n${formatError(result, calls)}` });
550 if (generatedImages > 0 && !items.some((item) => item.type === "image")) {
551 items.push({
552 type: "text",
553 text: `Note: models.generateImages() returned ${generatedImages} image${generatedImages === 1 ? "" : "s"} that the script did not show. Show each image block of result.output with image(block).`,
554 });
555 }
556
557 const truncated = await truncateOutput(
558 joinAdjacentText(items),
559 sourceOptions.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS,
560 );
561 // After truncation, which joins the text items and moves images after them, so each path stays
562 // next to its image and is never cut.
563 const output = joinAdjacentText(await saveImages(truncated.items));
564 const wallTime = ((performance.now() - startedAt) / 1000).toFixed(1);
565 const header = `${result.ok ? "Script completed" : "Script failed"}\nWall time ${wallTime} seconds\nOutput:\n`;
566 const details = snapshot();
567 if (truncated.fullOutputPath) details.fullOutputPath = truncated.fullOutputPath;
568 return {
569 content: [{ type: "text", text: header }, ...output],
570 details,
571 ...(modelUsage ? { usage: modelUsage } : {}),
572 ...(result.ok ? {} : { isError: true }),
573 };
574}
575
576/**
577 * Whether `query` names the namespace: its name or one of its aliases, as written or as the same
578 * script identifier (`dev-radius` and `dev_radius` are both `dev_radius`).
579 */
580function isNamespaceName(namespace: ToolNamespace, query: string): boolean {
581 const queryId = toCodemodeIdentifier(query);
582 return [namespace.name, ...(namespace.aliases ?? [])].some(
583 (name) => name === query || toCodemodeIdentifier(name) === queryId,
584 );
585}
586
587/**
588 * `searchTools()`, `describeTool()`, and `describeNamespace()`: ranked search and lookup over the
589 * script's nested tools and their namespaces.
590 */
591function createDiscoveryGlobals(
592 tools: readonly AgentTool<any>[],
593 samples: ReadonlyMap<string, string>,
594 options: CodemodeToolOptions,
595): CodemodeTool[] {
596 const ranker = new Bm25Ranker();
597 const entry = (name: string) => ({ name: toCodemodeIdentifier(name), description: samples.get(name) ?? "" });
598 return [
599 {
600 name: "searchTools",
601 spread: true,
602 execute: (args) => {
603 const [query, searchOptions] = args as [unknown, { limit?: unknown; namespace?: unknown } | undefined];
604 if (typeof query !== "string") throw new Error("searchTools() expects a query string");
605 const limit = searchOptions?.limit ?? DEFAULT_TOOL_SEARCH_LIMIT;
606 if (typeof limit !== "number" || !Number.isInteger(limit) || limit <= 0) {
607 throw new Error("searchTools() limit must be a positive integer");
608 }
609 const namespace = searchOptions?.namespace;
610 if (namespace !== undefined && namespace !== null && typeof namespace !== "string") {
611 throw new Error("searchTools() namespace must be a string");
612 }
613 const documents = tools.flatMap((tool) => {
614 const toolNamespace = options.getToolNamespace?.(tool.name);
615 if (namespace && (!toolNamespace || !isNamespaceName(toolNamespace, namespace))) return [];
616 return [createToolSearchDocument(tool, toolNamespace)];
617 });
618 return ranker.rank(query, documents, limit).map((match) => entry(match.name));
619 },
620 },
621 {
622 name: "describeTool",
623 spread: true,
624 execute: (args) => {
625 const [name] = args as unknown[];
626 if (typeof name !== "string") throw new Error("describeTool() expects a tool name");
627 const tool = tools.find(
628 (candidate) => candidate.name === name || toCodemodeIdentifier(candidate.name) === name,
629 );
630 return tool ? samples.get(tool.name) : undefined;
631 },
632 },
633 {
634 name: "describeNamespace",
635 spread: true,
636 execute: (args) => {
637 const [name] = args as unknown[];
638 if (typeof name !== "string") throw new Error("describeNamespace() expects a namespace name");
639 let namespace: ToolNamespace | undefined;
640 const names: string[] = [];
641 for (const tool of tools) {
642 const toolNamespace = options.getToolNamespace?.(tool.name);
643 if (!toolNamespace || !isNamespaceName(toolNamespace, name)) continue;
644 namespace ??= toolNamespace;
645 names.push(toCodemodeIdentifier(tool.name));
646 }
647 if (!namespace) return undefined;
648 return {
649 name: namespace.name,
650 ...(namespace.description ? { description: namespace.description } : {}),
651 ...(namespace.instructions ? { instructions: namespace.instructions } : {}),
652 tools: names,
653 };
654 },
655 },
656 ];
657}
658
659/**
660 * `models.*` for scripts: the model registry methods documented in docs/codemode.md.
661 * Classifier and image calls appear as nested call rows so the renderer shows them, and their usage
662 * goes to `addUsage`. Rows show only the model, never prompts or image data.
663 */
664function createModelGlobals(
665 models: CodemodeModelRuntime,
666 toolCallId: string,
667 calls: CodemodeNestedCall[],
668 publish: () => void,
669 addUsage: (usage: Usage) => void,
670 addGeneratedImages: (count: number) => void,
671): CodemodeTool[] {
672 const limit = createLimiter(MAX_CONCURRENT_MODEL_CALLS);
673 let callCount = 0;
674
675 /**
676 * Resolve the script's model by provider and id only, check the context, then run the call as a
677 * nested call row. A script-supplied baseUrl or headers must never receive the credentials.
678 */
679 const runModelCall = async <TType extends "classifier" | "image", TContext, TResult extends ModelCallResult>(
680 name: string,
681 type: TType,
682 [model, context]: unknown[],
683 checkContext: (context: unknown) => TContext,
684 run: (resolved: ModelTypeMap[TType], context: TContext) => Promise<TResult>,
685 ): Promise<TResult> => {
686 const listHint = `List the ${type} models you can use with models.getAvailableOfType("${type}").`;
687 const given = model as ScriptValue;
688 if (typeof given?.provider !== "string" || typeof given.id !== "string") {
689 // undefined arrives as null: spread arguments cross the sandbox as a JSON array.
690 const undefinedHint =
691 model === undefined || model === null
692 ? " models.getModelOfType() returns undefined for an unknown provider or id."
693 : "";
694 throw new Error(
695 `${name}() expects ${withArticle(type)} model as its first argument, got ${describeValue(model)}.${undefinedHint} ${listHint}`,
696 );
697 }
698 const provider = given.provider;
699 const id = given.id;
700 const ref = `${provider}/${id}`;
701 const resolved = models.getModelOfType(type, provider, id);
702 if (!resolved) {
703 const actualType = [...MODEL_TYPES].find(
704 (other) => other !== type && models.getModelOfType(other as ModelType, provider, id) !== undefined,
705 );
706 throw new Error(
707 actualType
708 ? `"${ref}" is ${withArticle(actualType)} model, not ${withArticle(type)} model. ${listHint}`
709 : `Unknown ${type} model "${ref}". ${listHint}`,
710 );
711 }
712 const checked = checkContext(context);
713
714 const record: CodemodeNestedCall = {
715 id: `${toolCallId}/${name}/${++callCount}`,
716 name,
717 args: `${resolved.provider}/${resolved.id}`,
718 status: "running",
719 };
720 calls.push(record);
721 publish();
722 const startedAt = performance.now();
723 const result = await limit(() => run(resolved, checked));
724 record.durationMs = performance.now() - startedAt;
725 record.status = result.stopReason === "stop" ? "ok" : result.stopReason === "aborted" ? "cancelled" : "error";
726 if (result.errorMessage) record.error = truncateText(result.errorMessage, ERROR_PREVIEW_CHARS);
727 if (result.usage) {
728 record.cost = result.usage.cost.total;
729 addUsage(result.usage);
730 }
731 publish();
732 return result;
733 };
734 const implementations: Record<string, CodemodeTool["execute"]> = {
735 "models.getModelsOfType": (args) => {
736 const [type, provider] = args as unknown[];
737 return models.getModelsOfType(toModelType(type), toProvider(provider)).map(toModelInfo);
738 },
739 "models.getAvailableOfType": async (args, { signal }) => {
740 const [type, provider] = args as unknown[];
741 const available = await models.getAvailableOfType(toModelType(type), toProvider(provider), { signal });
742 return available.map(toModelInfo);
743 },
744 "models.getModelOfType": (args) => {
745 const [type, provider, id] = args as unknown[];
746 if (typeof provider !== "string" || typeof id !== "string") {
747 throw new Error(
748 `models.getModelOfType(type, provider, id) expects three strings, got (${(args as unknown[]).map(describeValue).join(", ")}). The provider and the id are separate arguments, for example models.getModelOfType("classifier", "typesafe", "jev-latest").`,
749 );
750 }
751 const model = models.getModelOfType(toModelType(type), provider, id);
752 return model === undefined ? undefined : toModelInfo(model);
753 },
754 "models.classify": (args, { signal }) =>
755 runModelCall("models.classify", "classifier", args as unknown[], checkClassifierContext, (resolved, context) =>
756 models.classify(resolved, context, { signal }),
757 ),
758 "models.generateImages": (args, { signal }) =>
759 runModelCall(
760 "models.generateImages",
761 "image",
762 args as unknown[],
763 checkImagesContext,
764 async (resolved, context) => {
765 const result = await models.generateImages(resolved, context, { signal });
766 addGeneratedImages(result.output.filter((block) => block.type === "image").length);
767 return result;
768 },
769 ),
770 };
771 return Object.entries(implementations).map(([name, execute]) => ({ name, spread: true, execute }));
772}