@earendil-works/pi-coding-agent 0.99.1 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +86 -0
- package/dist/bundle/chunks/anthropic-messages-UID2PALB.js +6 -0
- package/dist/bundle/chunks/anthropic.js +2 -2
- package/dist/bundle/chunks/{azure-openai-responses-EN5WOBET.js → azure-openai-responses-AFMVM6NP.js} +1 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
- package/dist/bundle/chunks/{chunk-AXPY26X7.js → chunk-2KTBZM5G.js} +14 -28
- package/dist/bundle/chunks/{chunk-LRS5S6EK.js → chunk-2VNGUWBO.js} +2 -2
- package/dist/bundle/chunks/chunk-33XOIQ5N.js +1204 -0
- package/dist/bundle/chunks/{chunk-W2DOMZSC.js → chunk-3LH3ZQKY.js} +1 -1
- package/dist/bundle/chunks/chunk-4KU537KD.js +2 -0
- package/dist/bundle/chunks/chunk-6D7LHLKG.js +2 -0
- package/dist/bundle/chunks/chunk-7FH3BDRG.js +82 -0
- package/dist/bundle/chunks/{chunk-LLMKQWZS.js → chunk-IBCPYVFK.js} +7 -9
- package/dist/bundle/chunks/chunk-KDN6RCEQ.js +4 -0
- package/dist/bundle/chunks/chunk-LD2P6SFZ.js +2 -0
- package/dist/bundle/chunks/{chunk-PEHWOV5U.js → chunk-LTXEMVMA.js} +18 -78
- package/dist/bundle/chunks/{chunk-J4CWPC4N.js → chunk-OSKPX3Z5.js} +1 -1
- package/dist/bundle/chunks/chunk-PRD6WYBT.js +16 -0
- package/dist/bundle/chunks/chunk-VIV3CWXG.js +2 -0
- package/dist/bundle/chunks/{cli-AZXNGIZH.js → cli-QOMC26IJ.js} +8 -6
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-XJQQYGGU.js → cloudflare-workers-ai-system-one-NPQN263E.js} +1 -1
- package/dist/bundle/chunks/codemode-worker.js +67 -8
- package/dist/bundle/chunks/execute-GVRSEGHL.js +367 -0
- package/dist/bundle/chunks/github-copilot.js +1 -1
- package/dist/bundle/chunks/{google-generative-ai-CQAKKJTA.js → google-generative-ai-APTPZOQL.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-AE36YXJU.js → google-vertex-MXCOSOY3.js} +1 -1
- package/dist/bundle/chunks/{llama-cpp-classify-PJJYKPLD.js → llama-cpp-classify-XT44PI3C.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-KEYTXJM7.js → mistral-conversations-DKVFNQL6.js} +1 -1
- package/dist/bundle/chunks/openai-chatgpt.js +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-JQTCOVEG.js → openai-codex-responses-GK67DQQJ.js} +1 -1
- package/dist/bundle/chunks/openai-codex.js +1 -1
- package/dist/bundle/chunks/{openai-completions-XW2Q5HVC.js → openai-completions-JXDDPZ23.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-6AXWFL75.js → openai-responses-CQDDLDQF.js} +1 -1
- package/dist/bundle/chunks/{openrouter-images-TPQ4V6OR.js → openrouter-images-ZVXWCSIM.js} +1 -1
- package/dist/bundle/chunks/openrouter.js +1 -1
- package/dist/bundle/chunks/pi-logo-animation-MPKZE4EK.js +2 -0
- package/dist/bundle/chunks/radius.js +1 -1
- package/dist/bundle/chunks/runtime-2SO2JDWM.js +2 -0
- package/dist/bundle/chunks/{typesafe-system-one-E7A4HNJI.js → typesafe-system-one-A4CZTQWZ.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-6ZMK7GDO.js +2 -0
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli/args.js +2 -2
- package/dist/cli/args.js.map +1 -1
- package/dist/config.d.ts +5 -8
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +16 -13
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session.d.ts +15 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +51 -10
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +13 -1
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/types.d.ts +6 -1
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/mcp-servers.d.ts +34 -7
- package/dist/core/mcp-servers.d.ts.map +1 -1
- package/dist/core/mcp-servers.js +52 -11
- package/dist/core/mcp-servers.js.map +1 -1
- package/dist/core/model-registry.d.ts +3 -1
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +4 -0
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-runtime.d.ts +6 -0
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +22 -18
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/radius.d.ts +2 -0
- package/dist/core/radius.d.ts.map +1 -1
- package/dist/core/radius.js +2 -0
- package/dist/core/radius.js.map +1 -1
- package/dist/core/remote-catalog-provider.d.ts.map +1 -1
- package/dist/core/remote-catalog-provider.js +4 -9
- package/dist/core/remote-catalog-provider.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +1 -0
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/settings-manager.d.ts +7 -5
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +3 -2
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/system-prompt.js +1 -1
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +3 -5
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/renderers/bash.d.ts.map +1 -1
- package/dist/core/tools/renderers/bash.js +11 -31
- package/dist/core/tools/renderers/bash.js.map +1 -1
- package/dist/core/virtual-models.d.ts +2 -0
- package/dist/core/virtual-models.d.ts.map +1 -1
- package/dist/core/virtual-models.js +19 -12
- package/dist/core/virtual-models.js.map +1 -1
- package/dist/extensions/codemode/execute.d.ts.map +1 -1
- package/dist/extensions/codemode/execute.js +197 -51
- package/dist/extensions/codemode/execute.js.map +1 -1
- package/dist/extensions/codemode/renderer.d.ts.map +1 -1
- package/dist/extensions/codemode/renderer.js +43 -25
- package/dist/extensions/codemode/renderer.js.map +1 -1
- package/dist/extensions/codemode/tool.d.ts +12 -11
- package/dist/extensions/codemode/tool.d.ts.map +1 -1
- package/dist/extensions/codemode/tool.js +73 -129
- package/dist/extensions/codemode/tool.js.map +1 -1
- package/dist/extensions/codemode/worker.d.ts +1 -1
- package/dist/extensions/codemode/worker.js +1 -1
- package/dist/extensions/codemode/worker.js.map +1 -1
- package/dist/extensions/mcp/cli.d.ts.map +1 -1
- package/dist/extensions/mcp/cli.js +20 -5
- package/dist/extensions/mcp/cli.js.map +1 -1
- package/dist/extensions/mcp/config.d.ts +4 -2
- package/dist/extensions/mcp/config.d.ts.map +1 -1
- package/dist/extensions/mcp/config.js +14 -2
- package/dist/extensions/mcp/config.js.map +1 -1
- package/dist/extensions/mcp/index.d.ts +32 -8
- package/dist/extensions/mcp/index.d.ts.map +1 -1
- package/dist/extensions/mcp/index.js +220 -56
- package/dist/extensions/mcp/index.js.map +1 -1
- package/dist/extensions/mcp/oauth.d.ts +10 -7
- package/dist/extensions/mcp/oauth.d.ts.map +1 -1
- package/dist/extensions/mcp/oauth.js +56 -31
- package/dist/extensions/mcp/oauth.js.map +1 -1
- package/dist/extensions/mcp/runtime.d.ts +2 -0
- package/dist/extensions/mcp/runtime.d.ts.map +1 -1
- package/dist/extensions/mcp/runtime.js +16 -9
- package/dist/extensions/mcp/runtime.js.map +1 -1
- package/dist/extensions/mcp/tools.d.ts +5 -4
- package/dist/extensions/mcp/tools.d.ts.map +1 -1
- package/dist/extensions/mcp/tools.js +33 -15
- package/dist/extensions/mcp/tools.js.map +1 -1
- package/dist/extensions/mcp/ui.d.ts.map +1 -1
- package/dist/extensions/mcp/ui.js +4 -2
- package/dist/extensions/mcp/ui.js.map +1 -1
- package/dist/extensions/tool-search/tool.d.ts +5 -4
- package/dist/extensions/tool-search/tool.d.ts.map +1 -1
- package/dist/extensions/tool-search/tool.js +7 -28
- package/dist/extensions/tool-search/tool.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +6 -0
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.d.ts +8 -2
- package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.js +24 -21
- package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
- package/dist/modes/interactive/components/pi-logo-animation.d.ts +68 -0
- package/dist/modes/interactive/components/pi-logo-animation.d.ts.map +1 -0
- package/dist/modes/interactive/components/pi-logo-animation.js +1086 -0
- package/dist/modes/interactive/components/pi-logo-animation.js.map +1 -0
- package/dist/modes/interactive/components/pi-logo-animation.lazy.d.ts +7 -0
- package/dist/modes/interactive/components/pi-logo-animation.lazy.d.ts.map +1 -0
- package/dist/modes/interactive/components/pi-logo-animation.lazy.js +12 -0
- package/dist/modes/interactive/components/pi-logo-animation.lazy.js.map +1 -0
- package/dist/modes/interactive/components/pi-logo.d.ts +7 -0
- package/dist/modes/interactive/components/pi-logo.d.ts.map +1 -1
- package/dist/modes/interactive/components/pi-logo.js +13 -1
- package/dist/modes/interactive/components/pi-logo.js.map +1 -1
- package/dist/modes/interactive/components/radius-login-selector.d.ts +15 -0
- package/dist/modes/interactive/components/radius-login-selector.d.ts.map +1 -0
- package/dist/modes/interactive/components/radius-login-selector.js +85 -0
- package/dist/modes/interactive/components/radius-login-selector.js.map +1 -0
- package/dist/modes/interactive/components/settings-selector.d.ts +3 -3
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +5 -5
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/user-message.js +5 -4
- package/dist/modes/interactive/components/user-message.js.map +1 -1
- package/dist/modes/interactive/components/visual-truncate.d.ts +27 -3
- package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
- package/dist/modes/interactive/components/visual-truncate.js +39 -6
- package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +10 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +153 -40
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/theme/system-theme.d.ts +2 -1
- package/dist/modes/interactive/theme/system-theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/system-theme.js +16 -5
- package/dist/modes/interactive/theme/system-theme.js.map +1 -1
- package/docs/cli.md +8 -18
- package/docs/codemode.md +207 -0
- package/docs/docs.json +5 -1
- package/docs/environment-variables.md +2 -2
- package/docs/extensions.md +3 -3
- package/docs/index.md +1 -1
- package/docs/mcp.md +142 -82
- package/docs/models.md +22 -1
- package/docs/providers.md +18 -6
- package/docs/sdk.md +2 -2
- package/docs/settings.md +5 -3
- package/docs/usage.md +1 -1
- package/examples/extensions/built-in-tool-renderer.ts +16 -40
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/minimal-mode.ts +24 -96
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/examples/sdk/14-codemode-mcp.ts +2 -2
- package/npm-shrinkwrap.json +25 -30
- package/package.json +10 -10
- package/dist/bundle/chunks/anthropic-messages-A6EXUBG6.js +0 -6
- package/dist/bundle/chunks/chunk-GOPCREV2.js +0 -4
- package/dist/bundle/chunks/chunk-GUORCHFS.js +0 -1435
- package/dist/bundle/chunks/chunk-HSPCVFST.js +0 -2
- package/dist/bundle/chunks/chunk-IMTXZUO7.js +0 -82
- package/dist/bundle/chunks/chunk-SLDA2X2H.js +0 -2
- package/dist/bundle/chunks/chunk-XNGRGP62.js +0 -2
- package/dist/bundle/chunks/execute-7XXPZAWW.js +0 -308
- package/dist/bundle/chunks/runtime-G5WJPRBM.js +0 -2
- package/dist/bundle/chunks/virtual-modules-CSWRO37N.js +0 -2
|
@@ -7,13 +7,13 @@ import { writeFile } from "node:fs/promises";
|
|
|
7
7
|
import { tmpdir } from "node:os";
|
|
8
8
|
import { join } from "node:path";
|
|
9
9
|
import { CodemodeSandbox, loadQuickJSWasm, parseCodemodeSource, renderToolSample, toCodemodeIdentifier, } from "@earendil-works/pi-codemode";
|
|
10
|
-
import {
|
|
10
|
+
import { getCodemodeWorkerSpecifier, getQuickJSWasmPath } from "../../config.js";
|
|
11
11
|
import { combineUsage } from "../../core/usage-totals.js";
|
|
12
12
|
import { Bm25Ranker, createToolSearchDocument, DEFAULT_TOOL_SEARCH_LIMIT } from "../tool-search/tool.js";
|
|
13
|
-
import { CODEMODE_STORE_ENTRY_TYPE, getCodemodeCallableTools,
|
|
13
|
+
import { CODEMODE_DOCS_PATH, CODEMODE_STORE_ENTRY_TYPE, getCodemodeCallableTools, toCodemodeDeclaration, } from "./tool.js";
|
|
14
14
|
const ARGS_PREVIEW_CHARS = 200;
|
|
15
15
|
const ERROR_PREVIEW_CHARS = 500;
|
|
16
|
-
/**
|
|
16
|
+
/** `models.classify()` and `models.generateImages()` calls one script may have in flight; `Promise.all` over many items queues the rest. */
|
|
17
17
|
const MAX_CONCURRENT_MODEL_CALLS = 4;
|
|
18
18
|
/**
|
|
19
19
|
* Heap limit for the QuickJS VM. The worker shares pi's process, so without a limit a runaway
|
|
@@ -59,6 +59,90 @@ function toModelInfo(model) {
|
|
|
59
59
|
delete info.headers;
|
|
60
60
|
return info;
|
|
61
61
|
}
|
|
62
|
+
/** `an image`, `a classifier`. */
|
|
63
|
+
function withArticle(word) {
|
|
64
|
+
return `${/^[aeiou]/.test(word) ? "an" : "a"} ${word}`;
|
|
65
|
+
}
|
|
66
|
+
function isRecord(value) {
|
|
67
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
68
|
+
}
|
|
69
|
+
/** A script value in an error message: `undefined`, `a string`, `an array`, or its keys (`{ prompt }`). */
|
|
70
|
+
function describeValue(value) {
|
|
71
|
+
if (value === undefined || value === null)
|
|
72
|
+
return String(value);
|
|
73
|
+
if (Array.isArray(value))
|
|
74
|
+
return value.length === 0 ? "an empty array" : "an array";
|
|
75
|
+
if (typeof value === "object") {
|
|
76
|
+
const keys = Object.keys(value);
|
|
77
|
+
if (keys.length === 0)
|
|
78
|
+
return "{}";
|
|
79
|
+
return `{ ${keys.slice(0, 6).join(", ")}${keys.length > 6 ? ", ..." : ""} }`;
|
|
80
|
+
}
|
|
81
|
+
return typeof value === "string" ? "a string" : `a ${typeof value}`;
|
|
82
|
+
}
|
|
83
|
+
const CLASSIFIER_CONTEXT_SHAPE = '{ state: { ... }, questions: { <id>: { type: "choice", instructions, criteria: { <label>: <meaning> } } | { type: "score", instructions, criteria: [<lowest level>, ..., <highest level>] } | { type: "bool", instructions, criteria: { true: <meaning>, false: <meaning> } } } }';
|
|
84
|
+
/** Check a script's classifier context, so mistakes fail with the expected shape instead of a provider error. */
|
|
85
|
+
function checkClassifierContext(context) {
|
|
86
|
+
const fail = (problem) => new Error(`models.classify() ${problem}. Expected context: ${CLASSIFIER_CONTEXT_SHAPE}. See "Classify" in ${CODEMODE_DOCS_PATH}.`);
|
|
87
|
+
if (!isRecord(context))
|
|
88
|
+
throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);
|
|
89
|
+
if (!isRecord(context.state))
|
|
90
|
+
throw fail(`context.state must be an object, got ${describeValue(context.state)}`);
|
|
91
|
+
const { questions } = context;
|
|
92
|
+
if (!isRecord(questions) || Object.keys(questions).length === 0) {
|
|
93
|
+
throw fail(`context.questions must map question IDs to questions, got ${describeValue(questions)}`);
|
|
94
|
+
}
|
|
95
|
+
const isStrings = (values) => values.length > 0 && values.every((value) => typeof value === "string");
|
|
96
|
+
for (const [id, question] of Object.entries(questions)) {
|
|
97
|
+
const at = `context.questions.${id}`;
|
|
98
|
+
if (!isRecord(question))
|
|
99
|
+
throw fail(`${at} must be a question object, got ${describeValue(question)}`);
|
|
100
|
+
if (typeof question.instructions !== "string")
|
|
101
|
+
throw fail(`${at}.instructions must be a string`);
|
|
102
|
+
const { criteria } = question;
|
|
103
|
+
if (question.type === "choice") {
|
|
104
|
+
if (!isRecord(criteria) || !isStrings(Object.values(criteria))) {
|
|
105
|
+
throw fail(`${at} is a "choice" question, so criteria must map each label to its meaning`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
else if (question.type === "score") {
|
|
109
|
+
if (!Array.isArray(criteria) || !isStrings(criteria)) {
|
|
110
|
+
throw fail(`${at} is a "score" question, so criteria must list the levels as strings, lowest first`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
else if (question.type === "bool") {
|
|
114
|
+
if (!isRecord(criteria) || typeof criteria.true !== "string" || typeof criteria.false !== "string") {
|
|
115
|
+
throw fail(`${at} is a "bool" question, so criteria must be { true: string, false: string }`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
throw fail(`${at}.type must be "choice", "score", or "bool", got ${JSON.stringify(question.type)}`);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return context;
|
|
123
|
+
}
|
|
124
|
+
/** Check a script's image context, so mistakes such as `{ prompt }` fail with the expected shape. */
|
|
125
|
+
function checkImagesContext(context) {
|
|
126
|
+
const fail = (problem) => new Error(`models.generateImages() ${problem}. Expected context: { input: [{ type: "text", text: <prompt> }, ...optional { type: "image", data: <base64>, mimeType } references] }. See "Generate images" in ${CODEMODE_DOCS_PATH}.`);
|
|
127
|
+
if (!isRecord(context))
|
|
128
|
+
throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);
|
|
129
|
+
const { input } = context;
|
|
130
|
+
if (!Array.isArray(input) || input.length === 0) {
|
|
131
|
+
throw fail(`context.input must be a non-empty array of blocks, got ${describeValue(input)}`);
|
|
132
|
+
}
|
|
133
|
+
input.forEach((block, index) => {
|
|
134
|
+
if (isRecord(block) && block.type === "text" && typeof block.text === "string")
|
|
135
|
+
return;
|
|
136
|
+
if (isRecord(block) &&
|
|
137
|
+
block.type === "image" &&
|
|
138
|
+
typeof block.data === "string" &&
|
|
139
|
+
typeof block.mimeType === "string") {
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
throw fail(`context.input[${index}] must be a text or image block, got ${describeValue(block)}`);
|
|
143
|
+
});
|
|
144
|
+
return context;
|
|
145
|
+
}
|
|
62
146
|
/** Runs at most `limit` calls at once, in call order. */
|
|
63
147
|
function createLimiter(limit) {
|
|
64
148
|
let active = 0;
|
|
@@ -188,6 +272,11 @@ export async function executeCodemode(toolCallId, input, signal, onUpdate, ctx,
|
|
|
188
272
|
const calls = [];
|
|
189
273
|
// Usage of the script's `models.*` calls. Nested tool calls report theirs through the session.
|
|
190
274
|
let modelUsage;
|
|
275
|
+
// Images returned by `models.generateImages()`, to notice a script that never shows them.
|
|
276
|
+
let generatedImages = 0;
|
|
277
|
+
const addGeneratedImages = (count) => {
|
|
278
|
+
generatedImages += count;
|
|
279
|
+
};
|
|
191
280
|
const addModelUsage = (usage) => {
|
|
192
281
|
modelUsage = modelUsage ? combineUsage(modelUsage, usage) : usage;
|
|
193
282
|
};
|
|
@@ -231,13 +320,13 @@ export async function executeCodemode(toolCallId, input, signal, onUpdate, ctx,
|
|
|
231
320
|
globals: [
|
|
232
321
|
...createDiscoveryGlobals(callable, samples, options),
|
|
233
322
|
...(options.models && ctx
|
|
234
|
-
? createModelGlobals(ctx.modelRegistry, toolCallId, calls, publish, addModelUsage)
|
|
323
|
+
? createModelGlobals(ctx.modelRegistry, toolCallId, calls, publish, addModelUsage, addGeneratedImages)
|
|
235
324
|
: []),
|
|
236
325
|
],
|
|
237
326
|
timeoutMs: sourceOptions.timeoutMs ?? Number.POSITIVE_INFINITY,
|
|
238
327
|
memoryLimitBytes: CODEMODE_MEMORY_LIMIT_BYTES,
|
|
239
328
|
wasm: loadQuickJSWasm(getQuickJSWasmPath()),
|
|
240
|
-
workerUrl:
|
|
329
|
+
workerUrl: getCodemodeWorkerSpecifier(),
|
|
241
330
|
});
|
|
242
331
|
let result;
|
|
243
332
|
try {
|
|
@@ -265,6 +354,12 @@ export async function executeCodemode(toolCallId, input, signal, onUpdate, ctx,
|
|
|
265
354
|
else {
|
|
266
355
|
items.push({ type: "text", text: `Script error:\n${formatError(result, calls)}` });
|
|
267
356
|
}
|
|
357
|
+
if (generatedImages > 0 && !items.some((item) => item.type === "image")) {
|
|
358
|
+
items.push({
|
|
359
|
+
type: "text",
|
|
360
|
+
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).`,
|
|
361
|
+
});
|
|
362
|
+
}
|
|
268
363
|
const truncated = await truncateOutput(items, sourceOptions.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS);
|
|
269
364
|
const wallTime = ((performance.now() - startedAt) / 1000).toFixed(1);
|
|
270
365
|
const header = `${result.ok ? "Script completed" : "Script failed"}\nWall time ${wallTime} seconds\nOutput:\n`;
|
|
@@ -278,7 +373,20 @@ export async function executeCodemode(toolCallId, input, signal, onUpdate, ctx,
|
|
|
278
373
|
...(result.ok ? {} : { isError: true }),
|
|
279
374
|
};
|
|
280
375
|
}
|
|
281
|
-
/**
|
|
376
|
+
/**
|
|
377
|
+
* Whether `query` names the namespace: its name, its script identifier (`mcp__dev-radius` is
|
|
378
|
+
* `mcp__dev_radius`), or the part after its last `__` in either form (`dev-radius`, `dev_radius`).
|
|
379
|
+
*/
|
|
380
|
+
function isNamespaceName(namespace, query) {
|
|
381
|
+
const id = toCodemodeIdentifier(namespace);
|
|
382
|
+
const queryId = toCodemodeIdentifier(query);
|
|
383
|
+
const suffix = (name) => (name.includes("__") ? name.slice(name.lastIndexOf("__") + 2) : undefined);
|
|
384
|
+
return namespace === query || id === queryId || suffix(namespace) === query || suffix(id) === queryId;
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* `searchTools()`, `describeTool()`, and `describeNamespace()`: ranked search and lookup over the
|
|
388
|
+
* script's nested tools and their namespaces.
|
|
389
|
+
*/
|
|
282
390
|
function createDiscoveryGlobals(tools, samples, options) {
|
|
283
391
|
const ranker = new Bm25Ranker();
|
|
284
392
|
const entry = (name) => ({ name: toCodemodeIdentifier(name), description: samples.get(name) ?? "" });
|
|
@@ -300,7 +408,7 @@ function createDiscoveryGlobals(tools, samples, options) {
|
|
|
300
408
|
}
|
|
301
409
|
const documents = tools.flatMap((tool) => {
|
|
302
410
|
const toolNamespace = options.getToolNamespace?.(tool.name);
|
|
303
|
-
if (namespace && toolNamespace
|
|
411
|
+
if (namespace && (!toolNamespace || !isNamespaceName(toolNamespace.name, namespace)))
|
|
304
412
|
return [];
|
|
305
413
|
return [createToolSearchDocument(tool, toolNamespace)];
|
|
306
414
|
});
|
|
@@ -318,16 +426,86 @@ function createDiscoveryGlobals(tools, samples, options) {
|
|
|
318
426
|
return tool ? samples.get(tool.name) : undefined;
|
|
319
427
|
},
|
|
320
428
|
},
|
|
429
|
+
{
|
|
430
|
+
name: "describeNamespace",
|
|
431
|
+
spread: true,
|
|
432
|
+
execute: (args) => {
|
|
433
|
+
const [name] = args;
|
|
434
|
+
if (typeof name !== "string")
|
|
435
|
+
throw new Error("describeNamespace() expects a namespace name");
|
|
436
|
+
let namespace;
|
|
437
|
+
const names = [];
|
|
438
|
+
for (const tool of tools) {
|
|
439
|
+
const toolNamespace = options.getToolNamespace?.(tool.name);
|
|
440
|
+
if (!toolNamespace || !isNamespaceName(toolNamespace.name, name))
|
|
441
|
+
continue;
|
|
442
|
+
namespace ??= toolNamespace;
|
|
443
|
+
names.push(toCodemodeIdentifier(tool.name));
|
|
444
|
+
}
|
|
445
|
+
if (!namespace)
|
|
446
|
+
return undefined;
|
|
447
|
+
return {
|
|
448
|
+
name: namespace.name,
|
|
449
|
+
...(namespace.description ? { description: namespace.description } : {}),
|
|
450
|
+
...(namespace.instructions ? { instructions: namespace.instructions } : {}),
|
|
451
|
+
tools: names,
|
|
452
|
+
};
|
|
453
|
+
},
|
|
454
|
+
},
|
|
321
455
|
];
|
|
322
456
|
}
|
|
323
457
|
/**
|
|
324
|
-
* `models.*` for scripts: the model registry methods
|
|
325
|
-
* Classifier calls appear as nested call rows so the renderer shows them, and their usage
|
|
326
|
-
* `addUsage`.
|
|
458
|
+
* `models.*` for scripts: the model registry methods documented in docs/codemode.md.
|
|
459
|
+
* Classifier and image calls appear as nested call rows so the renderer shows them, and their usage
|
|
460
|
+
* goes to `addUsage`. Rows show only the model, never prompts or image data.
|
|
327
461
|
*/
|
|
328
|
-
function createModelGlobals(models, toolCallId, calls, publish, addUsage) {
|
|
462
|
+
function createModelGlobals(models, toolCallId, calls, publish, addUsage, addGeneratedImages) {
|
|
329
463
|
const limit = createLimiter(MAX_CONCURRENT_MODEL_CALLS);
|
|
330
|
-
let
|
|
464
|
+
let callCount = 0;
|
|
465
|
+
/**
|
|
466
|
+
* Resolve the script's model by provider and id only, check the context, then run the call as a
|
|
467
|
+
* nested call row. A script-supplied baseUrl or headers must never receive the credentials.
|
|
468
|
+
*/
|
|
469
|
+
const runModelCall = async (name, type, [model, context], checkContext, run) => {
|
|
470
|
+
const listHint = `List the ${type} models you can use with models.getAvailableOfType("${type}").`;
|
|
471
|
+
if (!isRecord(model) || typeof model.provider !== "string" || typeof model.id !== "string") {
|
|
472
|
+
// undefined arrives as null: spread arguments cross the sandbox as a JSON array.
|
|
473
|
+
const undefinedHint = model === undefined || model === null
|
|
474
|
+
? " models.getModelOfType() returns undefined for an unknown provider or id."
|
|
475
|
+
: "";
|
|
476
|
+
throw new Error(`${name}() expects ${withArticle(type)} model as its first argument, got ${describeValue(model)}.${undefinedHint} ${listHint}`);
|
|
477
|
+
}
|
|
478
|
+
const { provider, id } = model;
|
|
479
|
+
const ref = `${provider}/${id}`;
|
|
480
|
+
const resolved = models.getModelOfType(type, provider, id);
|
|
481
|
+
if (!resolved) {
|
|
482
|
+
const actualType = [...MODEL_TYPES].find((other) => other !== type && models.getModelOfType(other, provider, id) !== undefined);
|
|
483
|
+
throw new Error(actualType
|
|
484
|
+
? `"${ref}" is ${withArticle(actualType)} model, not ${withArticle(type)} model. ${listHint}`
|
|
485
|
+
: `Unknown ${type} model "${ref}". ${listHint}`);
|
|
486
|
+
}
|
|
487
|
+
const checked = checkContext(context);
|
|
488
|
+
const record = {
|
|
489
|
+
id: `${toolCallId}/${name}/${++callCount}`,
|
|
490
|
+
name,
|
|
491
|
+
args: `${resolved.provider}/${resolved.id}`,
|
|
492
|
+
status: "running",
|
|
493
|
+
};
|
|
494
|
+
calls.push(record);
|
|
495
|
+
publish();
|
|
496
|
+
const startedAt = performance.now();
|
|
497
|
+
const result = await limit(() => run(resolved, checked));
|
|
498
|
+
record.durationMs = performance.now() - startedAt;
|
|
499
|
+
record.status = result.stopReason === "stop" ? "ok" : result.stopReason === "aborted" ? "cancelled" : "error";
|
|
500
|
+
if (result.errorMessage)
|
|
501
|
+
record.error = truncateText(result.errorMessage, ERROR_PREVIEW_CHARS);
|
|
502
|
+
if (result.usage) {
|
|
503
|
+
record.cost = result.usage.cost.total;
|
|
504
|
+
addUsage(result.usage);
|
|
505
|
+
}
|
|
506
|
+
publish();
|
|
507
|
+
return result;
|
|
508
|
+
};
|
|
331
509
|
const implementations = {
|
|
332
510
|
"models.getModelsOfType": (args) => {
|
|
333
511
|
const [type, provider] = args;
|
|
@@ -341,50 +519,18 @@ function createModelGlobals(models, toolCallId, calls, publish, addUsage) {
|
|
|
341
519
|
"models.getModelOfType": (args) => {
|
|
342
520
|
const [type, provider, id] = args;
|
|
343
521
|
if (typeof provider !== "string" || typeof id !== "string") {
|
|
344
|
-
throw new Error(
|
|
522
|
+
throw new Error(`models.getModelOfType(type, provider, id) expects three strings, got (${args.map(describeValue).join(", ")}). The provider and the id are separate arguments, for example models.getModelOfType("classifier", "typesafe", "jev-latest").`);
|
|
345
523
|
}
|
|
346
524
|
const model = models.getModelOfType(toModelType(type), provider, id);
|
|
347
525
|
return model === undefined ? undefined : toModelInfo(model);
|
|
348
526
|
},
|
|
349
|
-
"models.classify":
|
|
350
|
-
|
|
351
|
-
const
|
|
352
|
-
|
|
353
|
-
ref === null ||
|
|
354
|
-
typeof ref.provider !== "string" ||
|
|
355
|
-
typeof ref.id !== "string") {
|
|
356
|
-
throw new Error("models.classify() expects a model from models.getModelOfType() or models.getAvailableOfType()");
|
|
357
|
-
}
|
|
358
|
-
// Only provider and id count. A script-supplied baseUrl or headers must never receive the credentials.
|
|
359
|
-
const resolved = models.getModelOfType("classifier", ref.provider, ref.id);
|
|
360
|
-
if (!resolved)
|
|
361
|
-
throw new Error(`Unknown classifier model "${ref.provider}/${ref.id}"`);
|
|
362
|
-
const record = {
|
|
363
|
-
id: `${toolCallId}/models.classify/${++classifyCount}`,
|
|
364
|
-
name: "models.classify",
|
|
365
|
-
args: `${resolved.provider}/${resolved.id}`,
|
|
366
|
-
status: "running",
|
|
367
|
-
};
|
|
368
|
-
calls.push(record);
|
|
369
|
-
publish();
|
|
370
|
-
const startedAt = performance.now();
|
|
371
|
-
const result = await limit(() => models.classify(resolved, context, { signal }));
|
|
372
|
-
record.durationMs = performance.now() - startedAt;
|
|
373
|
-
record.status = result.stopReason === "stop" ? "ok" : result.stopReason === "aborted" ? "cancelled" : "error";
|
|
374
|
-
if (result.errorMessage)
|
|
375
|
-
record.error = truncateText(result.errorMessage, ERROR_PREVIEW_CHARS);
|
|
376
|
-
if (result.usage) {
|
|
377
|
-
record.cost = result.usage.cost.total;
|
|
378
|
-
addUsage(result.usage);
|
|
379
|
-
}
|
|
380
|
-
publish();
|
|
527
|
+
"models.classify": (args, { signal }) => runModelCall("models.classify", "classifier", args, checkClassifierContext, (resolved, context) => models.classify(resolved, context, { signal })),
|
|
528
|
+
"models.generateImages": (args, { signal }) => runModelCall("models.generateImages", "image", args, checkImagesContext, async (resolved, context) => {
|
|
529
|
+
const result = await models.generateImages(resolved, context, { signal });
|
|
530
|
+
addGeneratedImages(result.output.filter((block) => block.type === "image").length);
|
|
381
531
|
return result;
|
|
382
|
-
},
|
|
532
|
+
}),
|
|
383
533
|
};
|
|
384
|
-
return
|
|
385
|
-
name: declaration.name,
|
|
386
|
-
spread: true,
|
|
387
|
-
execute: implementations[declaration.name],
|
|
388
|
-
}));
|
|
534
|
+
return Object.entries(implementations).map(([name, execute]) => ({ name, spread: true, execute }));
|
|
389
535
|
}
|
|
390
536
|
//# sourceMappingURL=execute.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execute.js","sourceRoot":"","sources":["../../../src/extensions/codemode/execute.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,OAAO,EAEN,eAAe,EAEf,eAAe,EACf,mBAAmB,EACnB,gBAAgB,EAChB,oBAAoB,GACpB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAG3E,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC1D,OAAO,EAAE,UAAU,EAAE,wBAAwB,EAAE,yBAA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CAAC;YACpC,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,EAAE,OAA4B,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC;YACtG,MAAM,CAAC,UAAU,GAAG,WAAW,CAAC,GAAG,EAAE,GAAG,SAAS,CAAC;YAClD,MAAM,CAAC,MAAM,GAAG,MAAM,CAAC,UAAU,KAAK,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,OAAO,CAAC;YAC9G,IAAI,MAAM,CAAC,YAAY;gBAAE,MAAM,CAAC,KAAK,GAAG,YAAY,CAAC,MAAM,CAAC,YAAY,EAAE,mBAAmB,CAAC,CAAC;YAC/F,IAAI,MAAM,CAAC,KAAK,EAAE,CAAC;gBAClB,MAAM,CAAC,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC;gBACtC,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACxB,CAAC;YACD,OAAO,EAAE,CAAC;YACV,OAAO,MAAM,CAAC;QACf,CAAC;KACD,CAAC;IACF,OAAO,yBAAyB,CAAC,GAAG,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;QACtD,IAAI,EAAE,WAAW,CAAC,IAAI;QACtB,MAAM,EAAE,IAAI;QACZ,OAAO,EAAE,eAAe,CAAC,WAAW,CAAC,IAAI,CAAC;KAC1C,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * Runs one codemode script in the sandbox. Split from tool.ts and loaded through\n * execute.lazy.ts so the sandbox runtime only loads when a script runs.\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { AgentTool, AgentToolCallOutcome, AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { AnyModel, ClassifierContext, ImageContent, ModelType, TextContent, Usage } from \"@earendil-works/pi-ai\";\nimport {\n\ttype CodemodeResult,\n\tCodemodeSandbox,\n\ttype CodemodeTool,\n\tloadQuickJSWasm,\n\tparseCodemodeSource,\n\trenderToolSample,\n\ttoCodemodeIdentifier,\n} from \"@earendil-works/pi-codemode\";\nimport { getCodemodeWorkerUrl, getQuickJSWasmPath } from \"../../config.ts\";\nimport type { ExtensionToolContext } from \"../../core/extensions/types.ts\";\nimport type { SessionEntry } from \"../../core/session-manager.ts\";\nimport { combineUsage } from \"../../core/usage-totals.ts\";\nimport { Bm25Ranker, createToolSearchDocument, DEFAULT_TOOL_SEARCH_LIMIT } from \"../tool-search/tool.ts\";\nimport {\n\tCODEMODE_STORE_ENTRY_TYPE,\n\ttype CodemodeModelRuntime,\n\ttype CodemodeNestedCall,\n\ttype CodemodeStoreEntryData,\n\ttype CodemodeToolDetails,\n\ttype CodemodeToolInput,\n\ttype CodemodeToolOptions,\n\tgetCodemodeCallableTools,\n\tMODEL_GLOBAL_DECLARATIONS,\n\ttoCodemodeDeclaration,\n} from \"./tool.ts\";\n\nconst ARGS_PREVIEW_CHARS = 200;\nconst ERROR_PREVIEW_CHARS = 500;\n/** Classifier calls one script may have in flight; `Promise.all` over many items queues the rest. */\nconst MAX_CONCURRENT_MODEL_CALLS = 4;\n/**\n * Heap limit for the QuickJS VM. The worker shares pi's process, so without a limit a runaway\n * script can grow to wasm32's 4 GiB and take the session down. Overruns throw\n * `InternalError: out of memory` inside the script.\n */\nconst CODEMODE_MEMORY_LIMIT_BYTES = 256 * 1024 * 1024;\nconst MODEL_TYPES: ReadonlySet<string> = new Set<ModelType>([\"chat\", \"image\", \"classifier\"]);\n\nfunction truncateText(text: string, maxChars: number): string {\n\treturn text.length > maxChars ? `${text.slice(0, maxChars - 3)}...` : text;\n}\n\nfunction previewArgs(args: unknown): string {\n\tif (args === undefined) return \"\";\n\ttry {\n\t\treturn truncateText(JSON.stringify(args) ?? \"\", ARGS_PREVIEW_CHARS);\n\t} catch {\n\t\treturn \"\";\n\t}\n}\n\nfunction textOf(result: AgentToolResult<unknown>): string {\n\treturn (result.content ?? [])\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n}\n\nfunction toModelType(value: unknown): ModelType {\n\tif (typeof value === \"string\" && MODEL_TYPES.has(value)) return value as ModelType;\n\tthrow new Error(`Unknown model type ${JSON.stringify(value)}. Use \"chat\", \"image\", or \"classifier\".`);\n}\n\nfunction toProvider(value: unknown): string | undefined {\n\tif (value === undefined || value === null) return undefined;\n\tif (typeof value !== \"string\") throw new Error(\"provider must be a string\");\n\treturn value;\n}\n\n/** Catalog entry for scripts. `headers` is dropped because models.json headers can carry credentials. */\nfunction toModelInfo(model: AnyModel): Record<string, unknown> {\n\tconst info: Record<string, unknown> = { ...model };\n\tdelete info.headers;\n\treturn info;\n}\n\n/** Runs at most `limit` calls at once, in call order. */\nfunction createLimiter(limit: number): <T>(run: () => Promise<T>) => Promise<T> {\n\tlet active = 0;\n\tconst waiting: (() => void)[] = [];\n\treturn async (run) => {\n\t\tif (active >= limit) await new Promise<void>((resolve) => waiting.push(resolve));\n\t\tactive++;\n\t\ttry {\n\t\t\treturn await run();\n\t\t} finally {\n\t\t\tactive--;\n\t\t\twaiting.shift()?.();\n\t\t}\n\t};\n}\n\nfunction isStoreEntryData(data: unknown): data is CodemodeStoreEntryData {\n\tif (typeof data !== \"object\" || data === null) return false;\n\tconst { set, delete: deleted } = data as Partial<CodemodeStoreEntryData>;\n\treturn (\n\t\ttypeof set === \"object\" &&\n\t\tset !== null &&\n\t\tArray.isArray(deleted) &&\n\t\tdeleted.every((key: unknown) => typeof key === \"string\")\n\t);\n}\n\n/** Values of `load()`: the `codemode-store` entries on the branch, applied from the root. */\nexport function readCodemodeStore(branch: readonly SessionEntry[]): Record<string, unknown> {\n\tconst store = new Map<string, unknown>();\n\tfor (const entry of branch) {\n\t\tif (entry.type !== \"custom\" || entry.customType !== CODEMODE_STORE_ENTRY_TYPE || !isStoreEntryData(entry.data)) {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const key of entry.data.delete) store.delete(key);\n\t\tfor (const [key, value] of Object.entries(entry.data.set)) store.set(key, value);\n\t}\n\treturn Object.fromEntries(store);\n}\n\n/** Default token budget for script output. */\nconst DEFAULT_MAX_OUTPUT_TOKENS = 10_000;\n/** Characters per token when estimating. */\nconst CHARS_PER_TOKEN = 4;\n\n/** Like the script's `text()`: strings as is, other values as compact JSON. */\nfunction valueText(value: unknown): string {\n\tif (typeof value === \"string\") return value;\n\treturn JSON.stringify(value) ?? String(value);\n}\n\nfunction formatCallSummary(calls: readonly CodemodeNestedCall[]): string {\n\tif (calls.length === 0) return \"No tool calls were made.\";\n\treturn `Tool calls made before the failure (they are not undone): ${calls.map((call) => `${call.name} (${call.status})`).join(\", \")}`;\n}\n\nfunction formatError(result: Extract<CodemodeResult, { ok: false }>, calls: readonly CodemodeNestedCall[]): string {\n\tconst { error } = result;\n\tconst head =\n\t\terror.kind === \"script\"\n\t\t\t? (error.stack ?? `${error.name ?? \"Error\"}: ${error.message}`)\n\t\t\t: error.kind === \"timeout\"\n\t\t\t\t? `Script timed out: ${error.message}`\n\t\t\t\t: error.kind === \"aborted\"\n\t\t\t\t\t? `Script aborted: ${error.message}`\n\t\t\t\t\t: `Script sandbox failed: ${error.message}`;\n\treturn `${head}\\n\\n${formatCallSummary(calls)}`;\n}\n\n/** Write the full text output to a temp file, like bash does for truncated output. */\nasync function spillOutput(text: string): Promise<{ path: string } | { error: string }> {\n\tconst path = join(tmpdir(), `pi-codemode-${randomBytes(8).toString(\"hex\")}.txt`);\n\ttry {\n\t\tawait writeFile(path, text);\n\t\treturn { path };\n\t} catch (error) {\n\t\treturn { error: error instanceof Error ? error.message : String(error) };\n\t}\n}\n\n/**\n * Apply the token budget: when the combined text exceeds it, the text items become one\n * item that keeps the start and end of the text, and images follow it. The full text is written to\n * a temp file.\n */\nasync function truncateOutput(\n\titems: (TextContent | ImageContent)[],\n\tmaxTokens: number,\n): Promise<{ items: (TextContent | ImageContent)[]; fullOutputPath?: string }> {\n\tconst texts = items.filter((item): item is TextContent => item.type === \"text\").map((item) => item.text);\n\tconst combined = texts.join(\"\\n\");\n\tconst budget = maxTokens * CHARS_PER_TOKEN;\n\tif (texts.length === 0 || combined.length <= budget) return { items };\n\tconst headChars = Math.floor(budget / 2);\n\tconst tailChars = budget - headChars;\n\tconst removed = combined.length - headChars - tailChars;\n\tconst head = combined.slice(0, headChars);\n\tconst tail = tailChars > 0 ? combined.slice(-tailChars) : \"\";\n\tlet 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}`;\n\tconst spilled = await spillOutput(combined);\n\ttext +=\n\t\t\"path\" in spilled\n\t\t\t? `\\n\\n[Full output: ${spilled.path} (read with offset/limit)]`\n\t\t\t: `\\n\\n[Could not save the full output: ${spilled.error}]`;\n\treturn {\n\t\titems: [{ type: \"text\", text }, ...items.filter((item) => item.type === \"image\")],\n\t\t...(\"path\" in spilled ? { fullOutputPath: spilled.path } : {}),\n\t};\n}\n\n/**\n * The value a script receives for a nested call: a tool that declares\n * `outputSchema` resolves to its `structuredContent`, also for error results that carry one (such\n * as MCP results with `isError`); any other tool resolves to its text content. Other failures\n * reject with the tool's error text.\n */\nfunction toScriptValue(tool: AgentTool<any>, outcome: AgentToolCallOutcome): unknown {\n\tconst { result } = outcome;\n\tif (tool.outputSchema && result.structuredContent !== undefined) return result.structuredContent;\n\tconst text = textOf(result);\n\tif (outcome.isError) throw new Error(text || `Tool \"${tool.name}\" failed`);\n\treturn text;\n}\n\n/**\n * Run one script. Without a session context (a plain Agent or a direct call) scripts cannot call\n * tools, `store()` starts empty, and writes are dropped.\n */\nexport async function executeCodemode(\n\ttoolCallId: string,\n\tinput: CodemodeToolInput,\n\tsignal: AbortSignal | undefined,\n\tonUpdate: ((result: AgentToolResult<CodemodeToolDetails>) => void) | undefined,\n\tctx: ExtensionToolContext | undefined,\n\toptions: CodemodeToolOptions = {},\n): Promise<AgentToolResult<CodemodeToolDetails>> {\n\tconst startedAt = performance.now();\n\tconst { code, options: sourceOptions } = parseCodemodeSource(input.code);\n\tconst calls: CodemodeNestedCall[] = [];\n\t// Usage of the script's `models.*` calls. Nested tool calls report theirs through the session.\n\tlet modelUsage: Usage | undefined;\n\tconst addModelUsage = (usage: Usage) => {\n\t\tmodelUsage = modelUsage ? combineUsage(modelUsage, usage) : usage;\n\t};\n\n\tconst snapshot = (): CodemodeToolDetails => ({ calls: calls.map((call) => ({ ...call })) });\n\tconst publish = () => onUpdate?.({ content: [], details: snapshot() });\n\n\tconst callable = ctx ? getCodemodeCallableTools(ctx.tools) : [];\n\t// ALL_TOOLS entries carry the declaration.\n\tconst samples = new Map(callable.map((tool) => [tool.name, renderToolSample(toCodemodeDeclaration(tool))]));\n\tconst sandboxTools: CodemodeTool[] = callable.map((tool) => ({\n\t\tname: tool.name,\n\t\tdescription: samples.get(tool.name),\n\t\texecute: async (args, { signal: callSignal }) => {\n\t\t\tconst record: CodemodeNestedCall = {\n\t\t\t\tid: `${toolCallId}/?`,\n\t\t\t\tname: tool.name,\n\t\t\t\targs: previewArgs(args),\n\t\t\t\tstatus: \"running\",\n\t\t\t};\n\t\t\tcalls.push(record);\n\t\t\tpublish();\n\t\t\tconst callStartedAt = performance.now();\n\t\t\t// Only tools from ctx.tools are callable, so ctx is set here.\n\t\t\tif (!ctx) throw new Error(\"Tool calls need a session\");\n\t\t\tconst outcome = await ctx.executeTool(tool.name, args, { signal: callSignal });\n\t\t\trecord.id = outcome.toolCall.id;\n\t\t\trecord.durationMs = performance.now() - callStartedAt;\n\t\t\tif (outcome.isError) {\n\t\t\t\trecord.status = callSignal.aborted ? \"cancelled\" : \"error\";\n\t\t\t\trecord.error = truncateText(textOf(outcome.result) || `Tool \"${tool.name}\" failed`, ERROR_PREVIEW_CHARS);\n\t\t\t} else {\n\t\t\t\trecord.status = \"ok\";\n\t\t\t}\n\t\t\tpublish();\n\t\t\treturn toScriptValue(tool, outcome);\n\t\t},\n\t}));\n\n\tconst sandbox = new CodemodeSandbox({\n\t\ttools: sandboxTools,\n\t\tglobals: [\n\t\t\t...createDiscoveryGlobals(callable, samples, options),\n\t\t\t...(options.models && ctx\n\t\t\t\t? createModelGlobals(ctx.modelRegistry, toolCallId, calls, publish, addModelUsage)\n\t\t\t\t: []),\n\t\t],\n\t\ttimeoutMs: sourceOptions.timeoutMs ?? Number.POSITIVE_INFINITY,\n\t\tmemoryLimitBytes: CODEMODE_MEMORY_LIMIT_BYTES,\n\t\twasm: loadQuickJSWasm(getQuickJSWasmPath()),\n\t\tworkerUrl: getCodemodeWorkerUrl(),\n\t});\n\n\tlet result: CodemodeResult;\n\ttry {\n\t\tconst store = ctx ? readCodemodeStore(ctx.sessionManager.getBranch()) : {};\n\t\tresult = await sandbox.execute(code, { signal, store });\n\t} finally {\n\t\tawait sandbox.close();\n\t}\n\t// Calls still marked running were cut off by the script ending, a timeout, or an abort.\n\tfor (const call of calls) {\n\t\tif (call.status === \"running\") call.status = \"cancelled\";\n\t}\n\n\tconst items: (TextContent | ImageContent)[] = result.output.map((item) =>\n\t\titem.type === \"text\" ? { type: \"text\", text: item.text } : item,\n\t);\n\tif (result.ok) {\n\t\tconst { set, delete: deleted } = result.storeWrites;\n\t\tif (Object.keys(set).length > 0 || deleted.length > 0) {\n\t\t\toptions.appendEntry?.(CODEMODE_STORE_ENTRY_TYPE, { set, delete: deleted });\n\t\t}\n\t\t// pi extension: a returned value is appended like text().\n\t\tif (result.value !== undefined) items.push({ type: \"text\", text: valueText(result.value) });\n\t} else {\n\t\titems.push({ type: \"text\", text: `Script error:\\n${formatError(result, calls)}` });\n\t}\n\n\tconst truncated = await truncateOutput(items, sourceOptions.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS);\n\tconst wallTime = ((performance.now() - startedAt) / 1000).toFixed(1);\n\tconst header = `${result.ok ? \"Script completed\" : \"Script failed\"}\\nWall time ${wallTime} seconds\\nOutput:\\n`;\n\tconst details = snapshot();\n\tif (truncated.fullOutputPath) details.fullOutputPath = truncated.fullOutputPath;\n\treturn {\n\t\tcontent: [{ type: \"text\", text: header }, ...truncated.items],\n\t\tdetails,\n\t\t...(modelUsage ? { usage: modelUsage } : {}),\n\t\t...(result.ok ? {} : { isError: true }),\n\t};\n}\n\n/** `searchTools()` and `describeTool()`: ranked search and lookup over the script's nested tools. */\nfunction createDiscoveryGlobals(\n\ttools: readonly AgentTool<any>[],\n\tsamples: ReadonlyMap<string, string>,\n\toptions: CodemodeToolOptions,\n): CodemodeTool[] {\n\tconst ranker = new Bm25Ranker();\n\tconst entry = (name: string) => ({ name: toCodemodeIdentifier(name), description: samples.get(name) ?? \"\" });\n\treturn [\n\t\t{\n\t\t\tname: \"searchTools\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [query, searchOptions] = args as [unknown, { limit?: unknown; namespace?: unknown } | undefined];\n\t\t\t\tif (typeof query !== \"string\") throw new Error(\"searchTools() expects a query string\");\n\t\t\t\tconst limit = searchOptions?.limit ?? DEFAULT_TOOL_SEARCH_LIMIT;\n\t\t\t\tif (typeof limit !== \"number\" || !Number.isInteger(limit) || limit <= 0) {\n\t\t\t\t\tthrow new Error(\"searchTools() limit must be a positive integer\");\n\t\t\t\t}\n\t\t\t\tconst namespace = searchOptions?.namespace;\n\t\t\t\tif (namespace !== undefined && namespace !== null && typeof namespace !== \"string\") {\n\t\t\t\t\tthrow new Error(\"searchTools() namespace must be a string\");\n\t\t\t\t}\n\t\t\t\tconst documents = tools.flatMap((tool) => {\n\t\t\t\t\tconst toolNamespace = options.getToolNamespace?.(tool.name);\n\t\t\t\t\tif (namespace && toolNamespace?.name !== namespace) return [];\n\t\t\t\t\treturn [createToolSearchDocument(tool, toolNamespace)];\n\t\t\t\t});\n\t\t\t\treturn ranker.rank(query, documents, limit).map((match) => entry(match.name));\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"describeTool\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [name] = args as unknown[];\n\t\t\t\tif (typeof name !== \"string\") throw new Error(\"describeTool() expects a tool name\");\n\t\t\t\tconst tool = tools.find(\n\t\t\t\t\t(candidate) => candidate.name === name || toCodemodeIdentifier(candidate.name) === name,\n\t\t\t\t);\n\t\t\t\treturn tool ? samples.get(tool.name) : undefined;\n\t\t\t},\n\t\t},\n\t];\n}\n\n/**\n * `models.*` for scripts: the model registry methods declared in {@link MODEL_GLOBAL_DECLARATIONS}.\n * Classifier calls appear as nested call rows so the renderer shows them, and their usage goes to\n * `addUsage`.\n */\nfunction createModelGlobals(\n\tmodels: CodemodeModelRuntime,\n\ttoolCallId: string,\n\tcalls: CodemodeNestedCall[],\n\tpublish: () => void,\n\taddUsage: (usage: Usage) => void,\n): CodemodeTool[] {\n\tconst limit = createLimiter(MAX_CONCURRENT_MODEL_CALLS);\n\tlet classifyCount = 0;\n\tconst implementations: Record<string, CodemodeTool[\"execute\"]> = {\n\t\t\"models.getModelsOfType\": (args) => {\n\t\t\tconst [type, provider] = args as unknown[];\n\t\t\treturn models.getModelsOfType(toModelType(type), toProvider(provider)).map(toModelInfo);\n\t\t},\n\t\t\"models.getAvailableOfType\": async (args, { signal }) => {\n\t\t\tconst [type, provider] = args as unknown[];\n\t\t\tconst available = await models.getAvailableOfType(toModelType(type), toProvider(provider), { signal });\n\t\t\treturn available.map(toModelInfo);\n\t\t},\n\t\t\"models.getModelOfType\": (args) => {\n\t\t\tconst [type, provider, id] = args as unknown[];\n\t\t\tif (typeof provider !== \"string\" || typeof id !== \"string\") {\n\t\t\t\tthrow new Error(\"models.getModelOfType() expects a type, a provider, and an id\");\n\t\t\t}\n\t\t\tconst model = models.getModelOfType(toModelType(type), provider, id);\n\t\t\treturn model === undefined ? undefined : toModelInfo(model);\n\t\t},\n\t\t\"models.classify\": async (args, { signal }) => {\n\t\t\tconst [model, context] = args as unknown[];\n\t\t\tconst ref = model as { provider?: unknown; id?: unknown } | null;\n\t\t\tif (\n\t\t\t\ttypeof ref !== \"object\" ||\n\t\t\t\tref === null ||\n\t\t\t\ttypeof ref.provider !== \"string\" ||\n\t\t\t\ttypeof ref.id !== \"string\"\n\t\t\t) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"models.classify() expects a model from models.getModelOfType() or models.getAvailableOfType()\",\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Only provider and id count. A script-supplied baseUrl or headers must never receive the credentials.\n\t\t\tconst resolved = models.getModelOfType(\"classifier\", ref.provider, ref.id);\n\t\t\tif (!resolved) throw new Error(`Unknown classifier model \"${ref.provider}/${ref.id}\"`);\n\n\t\t\tconst record: CodemodeNestedCall = {\n\t\t\t\tid: `${toolCallId}/models.classify/${++classifyCount}`,\n\t\t\t\tname: \"models.classify\",\n\t\t\t\targs: `${resolved.provider}/${resolved.id}`,\n\t\t\t\tstatus: \"running\",\n\t\t\t};\n\t\t\tcalls.push(record);\n\t\t\tpublish();\n\t\t\tconst startedAt = performance.now();\n\t\t\tconst result = await limit(() => models.classify(resolved, context as ClassifierContext, { signal }));\n\t\t\trecord.durationMs = performance.now() - startedAt;\n\t\t\trecord.status = result.stopReason === \"stop\" ? \"ok\" : result.stopReason === \"aborted\" ? \"cancelled\" : \"error\";\n\t\t\tif (result.errorMessage) record.error = truncateText(result.errorMessage, ERROR_PREVIEW_CHARS);\n\t\t\tif (result.usage) {\n\t\t\t\trecord.cost = result.usage.cost.total;\n\t\t\t\taddUsage(result.usage);\n\t\t\t}\n\t\t\tpublish();\n\t\t\treturn result;\n\t\t},\n\t};\n\treturn MODEL_GLOBAL_DECLARATIONS.map((declaration) => ({\n\t\tname: declaration.name,\n\t\tspread: true,\n\t\texecute: implementations[declaration.name],\n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runs one codemode script in the sandbox. Split from tool.ts and loaded through\n * execute.lazy.ts so the sandbox runtime only loads when a script runs.\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { AgentTool, AgentToolCallOutcome, AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type {\n\tAnyModel,\n\tClassifierContext,\n\tImageContent,\n\tImagesContext,\n\tModelType,\n\tModelTypeMap,\n\tTextContent,\n\tUsage,\n} from \"@earendil-works/pi-ai\";\nimport {\n\ttype CodemodeResult,\n\tCodemodeSandbox,\n\ttype CodemodeTool,\n\tloadQuickJSWasm,\n\tparseCodemodeSource,\n\trenderToolSample,\n\ttoCodemodeIdentifier,\n} from \"@earendil-works/pi-codemode\";\nimport { getCodemodeWorkerSpecifier, getQuickJSWasmPath } from \"../../config.ts\";\nimport type { ExtensionToolContext, ToolNamespace } from \"../../core/extensions/types.ts\";\nimport type { SessionEntry } from \"../../core/session-manager.ts\";\nimport { combineUsage } from \"../../core/usage-totals.ts\";\nimport { Bm25Ranker, createToolSearchDocument, DEFAULT_TOOL_SEARCH_LIMIT } from \"../tool-search/tool.ts\";\nimport {\n\tCODEMODE_DOCS_PATH,\n\tCODEMODE_STORE_ENTRY_TYPE,\n\ttype CodemodeModelRuntime,\n\ttype CodemodeNestedCall,\n\ttype CodemodeStoreEntryData,\n\ttype CodemodeToolDetails,\n\ttype CodemodeToolInput,\n\ttype CodemodeToolOptions,\n\tgetCodemodeCallableTools,\n\ttoCodemodeDeclaration,\n} from \"./tool.ts\";\n\nconst ARGS_PREVIEW_CHARS = 200;\nconst ERROR_PREVIEW_CHARS = 500;\n/** `models.classify()` and `models.generateImages()` calls one script may have in flight; `Promise.all` over many items queues the rest. */\nconst MAX_CONCURRENT_MODEL_CALLS = 4;\n/**\n * Heap limit for the QuickJS VM. The worker shares pi's process, so without a limit a runaway\n * script can grow to wasm32's 4 GiB and take the session down. Overruns throw\n * `InternalError: out of memory` inside the script.\n */\nconst CODEMODE_MEMORY_LIMIT_BYTES = 256 * 1024 * 1024;\nconst MODEL_TYPES: ReadonlySet<string> = new Set<ModelType>([\"chat\", \"image\", \"classifier\"]);\n\nfunction truncateText(text: string, maxChars: number): string {\n\treturn text.length > maxChars ? `${text.slice(0, maxChars - 3)}...` : text;\n}\n\nfunction previewArgs(args: unknown): string {\n\tif (args === undefined) return \"\";\n\ttry {\n\t\treturn truncateText(JSON.stringify(args) ?? \"\", ARGS_PREVIEW_CHARS);\n\t} catch {\n\t\treturn \"\";\n\t}\n}\n\nfunction textOf(result: AgentToolResult<unknown>): string {\n\treturn (result.content ?? [])\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n}\n\nfunction toModelType(value: unknown): ModelType {\n\tif (typeof value === \"string\" && MODEL_TYPES.has(value)) return value as ModelType;\n\tthrow new Error(`Unknown model type ${JSON.stringify(value)}. Use \"chat\", \"image\", or \"classifier\".`);\n}\n\nfunction toProvider(value: unknown): string | undefined {\n\tif (value === undefined || value === null) return undefined;\n\tif (typeof value !== \"string\") throw new Error(\"provider must be a string\");\n\treturn value;\n}\n\n/** Catalog entry for scripts. `headers` is dropped because models.json headers can carry credentials. */\nfunction toModelInfo(model: AnyModel): Record<string, unknown> {\n\tconst info: Record<string, unknown> = { ...model };\n\tdelete info.headers;\n\treturn info;\n}\n\n/** `an image`, `a classifier`. */\nfunction withArticle(word: string): string {\n\treturn `${/^[aeiou]/.test(word) ? \"an\" : \"a\"} ${word}`;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** A script value in an error message: `undefined`, `a string`, `an array`, or its keys (`{ prompt }`). */\nfunction describeValue(value: unknown): string {\n\tif (value === undefined || value === null) return String(value);\n\tif (Array.isArray(value)) return value.length === 0 ? \"an empty array\" : \"an array\";\n\tif (typeof value === \"object\") {\n\t\tconst keys = Object.keys(value);\n\t\tif (keys.length === 0) return \"{}\";\n\t\treturn `{ ${keys.slice(0, 6).join(\", \")}${keys.length > 6 ? \", ...\" : \"\"} }`;\n\t}\n\treturn typeof value === \"string\" ? \"a string\" : `a ${typeof value}`;\n}\n\nconst CLASSIFIER_CONTEXT_SHAPE =\n\t'{ state: { ... }, questions: { <id>: { type: \"choice\", instructions, criteria: { <label>: <meaning> } } | { type: \"score\", instructions, criteria: [<lowest level>, ..., <highest level>] } | { type: \"bool\", instructions, criteria: { true: <meaning>, false: <meaning> } } } }';\n\n/** Check a script's classifier context, so mistakes fail with the expected shape instead of a provider error. */\nfunction checkClassifierContext(context: unknown): ClassifierContext {\n\tconst fail = (problem: string) =>\n\t\tnew Error(\n\t\t\t`models.classify() ${problem}. Expected context: ${CLASSIFIER_CONTEXT_SHAPE}. See \"Classify\" in ${CODEMODE_DOCS_PATH}.`,\n\t\t);\n\tif (!isRecord(context)) throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);\n\tif (!isRecord(context.state)) throw fail(`context.state must be an object, got ${describeValue(context.state)}`);\n\tconst { questions } = context;\n\tif (!isRecord(questions) || Object.keys(questions).length === 0) {\n\t\tthrow fail(`context.questions must map question IDs to questions, got ${describeValue(questions)}`);\n\t}\n\tconst isStrings = (values: unknown[]) => values.length > 0 && values.every((value) => typeof value === \"string\");\n\tfor (const [id, question] of Object.entries(questions)) {\n\t\tconst at = `context.questions.${id}`;\n\t\tif (!isRecord(question)) throw fail(`${at} must be a question object, got ${describeValue(question)}`);\n\t\tif (typeof question.instructions !== \"string\") throw fail(`${at}.instructions must be a string`);\n\t\tconst { criteria } = question;\n\t\tif (question.type === \"choice\") {\n\t\t\tif (!isRecord(criteria) || !isStrings(Object.values(criteria))) {\n\t\t\t\tthrow fail(`${at} is a \"choice\" question, so criteria must map each label to its meaning`);\n\t\t\t}\n\t\t} else if (question.type === \"score\") {\n\t\t\tif (!Array.isArray(criteria) || !isStrings(criteria)) {\n\t\t\t\tthrow fail(`${at} is a \"score\" question, so criteria must list the levels as strings, lowest first`);\n\t\t\t}\n\t\t} else if (question.type === \"bool\") {\n\t\t\tif (!isRecord(criteria) || typeof criteria.true !== \"string\" || typeof criteria.false !== \"string\") {\n\t\t\t\tthrow fail(`${at} is a \"bool\" question, so criteria must be { true: string, false: string }`);\n\t\t\t}\n\t\t} else {\n\t\t\tthrow fail(`${at}.type must be \"choice\", \"score\", or \"bool\", got ${JSON.stringify(question.type)}`);\n\t\t}\n\t}\n\treturn context as unknown as ClassifierContext;\n}\n\n/** Check a script's image context, so mistakes such as `{ prompt }` fail with the expected shape. */\nfunction checkImagesContext(context: unknown): ImagesContext {\n\tconst fail = (problem: string) =>\n\t\tnew Error(\n\t\t\t`models.generateImages() ${problem}. Expected context: { input: [{ type: \"text\", text: <prompt> }, ...optional { type: \"image\", data: <base64>, mimeType } references] }. See \"Generate images\" in ${CODEMODE_DOCS_PATH}.`,\n\t\t);\n\tif (!isRecord(context)) throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);\n\tconst { input } = context;\n\tif (!Array.isArray(input) || input.length === 0) {\n\t\tthrow fail(`context.input must be a non-empty array of blocks, got ${describeValue(input)}`);\n\t}\n\tinput.forEach((block: unknown, index) => {\n\t\tif (isRecord(block) && block.type === \"text\" && typeof block.text === \"string\") return;\n\t\tif (\n\t\t\tisRecord(block) &&\n\t\t\tblock.type === \"image\" &&\n\t\t\ttypeof block.data === \"string\" &&\n\t\t\ttypeof block.mimeType === \"string\"\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tthrow fail(`context.input[${index}] must be a text or image block, got ${describeValue(block)}`);\n\t});\n\treturn context as unknown as ImagesContext;\n}\n\n/** The fields of `ClassifierResult` and `AssistantImages` that a nested call row reports. */\ninterface ModelCallResult {\n\tstopReason: \"stop\" | \"error\" | \"aborted\";\n\terrorMessage?: string;\n\tusage?: Usage;\n}\n\n/** Runs at most `limit` calls at once, in call order. */\nfunction createLimiter(limit: number): <T>(run: () => Promise<T>) => Promise<T> {\n\tlet active = 0;\n\tconst waiting: (() => void)[] = [];\n\treturn async (run) => {\n\t\tif (active >= limit) await new Promise<void>((resolve) => waiting.push(resolve));\n\t\tactive++;\n\t\ttry {\n\t\t\treturn await run();\n\t\t} finally {\n\t\t\tactive--;\n\t\t\twaiting.shift()?.();\n\t\t}\n\t};\n}\n\nfunction isStoreEntryData(data: unknown): data is CodemodeStoreEntryData {\n\tif (typeof data !== \"object\" || data === null) return false;\n\tconst { set, delete: deleted } = data as Partial<CodemodeStoreEntryData>;\n\treturn (\n\t\ttypeof set === \"object\" &&\n\t\tset !== null &&\n\t\tArray.isArray(deleted) &&\n\t\tdeleted.every((key: unknown) => typeof key === \"string\")\n\t);\n}\n\n/** Values of `load()`: the `codemode-store` entries on the branch, applied from the root. */\nexport function readCodemodeStore(branch: readonly SessionEntry[]): Record<string, unknown> {\n\tconst store = new Map<string, unknown>();\n\tfor (const entry of branch) {\n\t\tif (entry.type !== \"custom\" || entry.customType !== CODEMODE_STORE_ENTRY_TYPE || !isStoreEntryData(entry.data)) {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const key of entry.data.delete) store.delete(key);\n\t\tfor (const [key, value] of Object.entries(entry.data.set)) store.set(key, value);\n\t}\n\treturn Object.fromEntries(store);\n}\n\n/** Default token budget for script output. */\nconst DEFAULT_MAX_OUTPUT_TOKENS = 10_000;\n/** Characters per token when estimating. */\nconst CHARS_PER_TOKEN = 4;\n\n/** Like the script's `text()`: strings as is, other values as compact JSON. */\nfunction valueText(value: unknown): string {\n\tif (typeof value === \"string\") return value;\n\treturn JSON.stringify(value) ?? String(value);\n}\n\nfunction formatCallSummary(calls: readonly CodemodeNestedCall[]): string {\n\tif (calls.length === 0) return \"No tool calls were made.\";\n\treturn `Tool calls made before the failure (they are not undone): ${calls.map((call) => `${call.name} (${call.status})`).join(\", \")}`;\n}\n\nfunction formatError(result: Extract<CodemodeResult, { ok: false }>, calls: readonly CodemodeNestedCall[]): string {\n\tconst { error } = result;\n\tconst head =\n\t\terror.kind === \"script\"\n\t\t\t? (error.stack ?? `${error.name ?? \"Error\"}: ${error.message}`)\n\t\t\t: error.kind === \"timeout\"\n\t\t\t\t? `Script timed out: ${error.message}`\n\t\t\t\t: error.kind === \"aborted\"\n\t\t\t\t\t? `Script aborted: ${error.message}`\n\t\t\t\t\t: `Script sandbox failed: ${error.message}`;\n\treturn `${head}\\n\\n${formatCallSummary(calls)}`;\n}\n\n/** Write the full text output to a temp file, like bash does for truncated output. */\nasync function spillOutput(text: string): Promise<{ path: string } | { error: string }> {\n\tconst path = join(tmpdir(), `pi-codemode-${randomBytes(8).toString(\"hex\")}.txt`);\n\ttry {\n\t\tawait writeFile(path, text);\n\t\treturn { path };\n\t} catch (error) {\n\t\treturn { error: error instanceof Error ? error.message : String(error) };\n\t}\n}\n\n/**\n * Apply the token budget: when the combined text exceeds it, the text items become one\n * item that keeps the start and end of the text, and images follow it. The full text is written to\n * a temp file.\n */\nasync function truncateOutput(\n\titems: (TextContent | ImageContent)[],\n\tmaxTokens: number,\n): Promise<{ items: (TextContent | ImageContent)[]; fullOutputPath?: string }> {\n\tconst texts = items.filter((item): item is TextContent => item.type === \"text\").map((item) => item.text);\n\tconst combined = texts.join(\"\\n\");\n\tconst budget = maxTokens * CHARS_PER_TOKEN;\n\tif (texts.length === 0 || combined.length <= budget) return { items };\n\tconst headChars = Math.floor(budget / 2);\n\tconst tailChars = budget - headChars;\n\tconst removed = combined.length - headChars - tailChars;\n\tconst head = combined.slice(0, headChars);\n\tconst tail = tailChars > 0 ? combined.slice(-tailChars) : \"\";\n\tlet 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}`;\n\tconst spilled = await spillOutput(combined);\n\ttext +=\n\t\t\"path\" in spilled\n\t\t\t? `\\n\\n[Full output: ${spilled.path} (read with offset/limit)]`\n\t\t\t: `\\n\\n[Could not save the full output: ${spilled.error}]`;\n\treturn {\n\t\titems: [{ type: \"text\", text }, ...items.filter((item) => item.type === \"image\")],\n\t\t...(\"path\" in spilled ? { fullOutputPath: spilled.path } : {}),\n\t};\n}\n\n/**\n * The value a script receives for a nested call: a tool that declares\n * `outputSchema` resolves to its `structuredContent`, also for error results that carry one (such\n * as MCP results with `isError`); any other tool resolves to its text content. Other failures\n * reject with the tool's error text.\n */\nfunction toScriptValue(tool: AgentTool<any>, outcome: AgentToolCallOutcome): unknown {\n\tconst { result } = outcome;\n\tif (tool.outputSchema && result.structuredContent !== undefined) return result.structuredContent;\n\tconst text = textOf(result);\n\tif (outcome.isError) throw new Error(text || `Tool \"${tool.name}\" failed`);\n\treturn text;\n}\n\n/**\n * Run one script. Without a session context (a plain Agent or a direct call) scripts cannot call\n * tools, `store()` starts empty, and writes are dropped.\n */\nexport async function executeCodemode(\n\ttoolCallId: string,\n\tinput: CodemodeToolInput,\n\tsignal: AbortSignal | undefined,\n\tonUpdate: ((result: AgentToolResult<CodemodeToolDetails>) => void) | undefined,\n\tctx: ExtensionToolContext | undefined,\n\toptions: CodemodeToolOptions = {},\n): Promise<AgentToolResult<CodemodeToolDetails>> {\n\tconst startedAt = performance.now();\n\tconst { code, options: sourceOptions } = parseCodemodeSource(input.code);\n\tconst calls: CodemodeNestedCall[] = [];\n\t// Usage of the script's `models.*` calls. Nested tool calls report theirs through the session.\n\tlet modelUsage: Usage | undefined;\n\t// Images returned by `models.generateImages()`, to notice a script that never shows them.\n\tlet generatedImages = 0;\n\tconst addGeneratedImages = (count: number) => {\n\t\tgeneratedImages += count;\n\t};\n\tconst addModelUsage = (usage: Usage) => {\n\t\tmodelUsage = modelUsage ? combineUsage(modelUsage, usage) : usage;\n\t};\n\n\tconst snapshot = (): CodemodeToolDetails => ({ calls: calls.map((call) => ({ ...call })) });\n\tconst publish = () => onUpdate?.({ content: [], details: snapshot() });\n\n\tconst callable = ctx ? getCodemodeCallableTools(ctx.tools) : [];\n\t// ALL_TOOLS entries carry the declaration.\n\tconst samples = new Map(callable.map((tool) => [tool.name, renderToolSample(toCodemodeDeclaration(tool))]));\n\tconst sandboxTools: CodemodeTool[] = callable.map((tool) => ({\n\t\tname: tool.name,\n\t\tdescription: samples.get(tool.name),\n\t\texecute: async (args, { signal: callSignal }) => {\n\t\t\tconst record: CodemodeNestedCall = {\n\t\t\t\tid: `${toolCallId}/?`,\n\t\t\t\tname: tool.name,\n\t\t\t\targs: previewArgs(args),\n\t\t\t\tstatus: \"running\",\n\t\t\t};\n\t\t\tcalls.push(record);\n\t\t\tpublish();\n\t\t\tconst callStartedAt = performance.now();\n\t\t\t// Only tools from ctx.tools are callable, so ctx is set here.\n\t\t\tif (!ctx) throw new Error(\"Tool calls need a session\");\n\t\t\tconst outcome = await ctx.executeTool(tool.name, args, { signal: callSignal });\n\t\t\trecord.id = outcome.toolCall.id;\n\t\t\trecord.durationMs = performance.now() - callStartedAt;\n\t\t\tif (outcome.isError) {\n\t\t\t\trecord.status = callSignal.aborted ? \"cancelled\" : \"error\";\n\t\t\t\trecord.error = truncateText(textOf(outcome.result) || `Tool \"${tool.name}\" failed`, ERROR_PREVIEW_CHARS);\n\t\t\t} else {\n\t\t\t\trecord.status = \"ok\";\n\t\t\t}\n\t\t\tpublish();\n\t\t\treturn toScriptValue(tool, outcome);\n\t\t},\n\t}));\n\n\tconst sandbox = new CodemodeSandbox({\n\t\ttools: sandboxTools,\n\t\tglobals: [\n\t\t\t...createDiscoveryGlobals(callable, samples, options),\n\t\t\t...(options.models && ctx\n\t\t\t\t? createModelGlobals(ctx.modelRegistry, toolCallId, calls, publish, addModelUsage, addGeneratedImages)\n\t\t\t\t: []),\n\t\t],\n\t\ttimeoutMs: sourceOptions.timeoutMs ?? Number.POSITIVE_INFINITY,\n\t\tmemoryLimitBytes: CODEMODE_MEMORY_LIMIT_BYTES,\n\t\twasm: loadQuickJSWasm(getQuickJSWasmPath()),\n\t\tworkerUrl: getCodemodeWorkerSpecifier(),\n\t});\n\n\tlet result: CodemodeResult;\n\ttry {\n\t\tconst store = ctx ? readCodemodeStore(ctx.sessionManager.getBranch()) : {};\n\t\tresult = await sandbox.execute(code, { signal, store });\n\t} finally {\n\t\tawait sandbox.close();\n\t}\n\t// Calls still marked running were cut off by the script ending, a timeout, or an abort.\n\tfor (const call of calls) {\n\t\tif (call.status === \"running\") call.status = \"cancelled\";\n\t}\n\n\tconst items: (TextContent | ImageContent)[] = result.output.map((item) =>\n\t\titem.type === \"text\" ? { type: \"text\", text: item.text } : item,\n\t);\n\tif (result.ok) {\n\t\tconst { set, delete: deleted } = result.storeWrites;\n\t\tif (Object.keys(set).length > 0 || deleted.length > 0) {\n\t\t\toptions.appendEntry?.(CODEMODE_STORE_ENTRY_TYPE, { set, delete: deleted });\n\t\t}\n\t\t// pi extension: a returned value is appended like text().\n\t\tif (result.value !== undefined) items.push({ type: \"text\", text: valueText(result.value) });\n\t} else {\n\t\titems.push({ type: \"text\", text: `Script error:\\n${formatError(result, calls)}` });\n\t}\n\tif (generatedImages > 0 && !items.some((item) => item.type === \"image\")) {\n\t\titems.push({\n\t\t\ttype: \"text\",\n\t\t\ttext: `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).`,\n\t\t});\n\t}\n\n\tconst truncated = await truncateOutput(items, sourceOptions.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS);\n\tconst wallTime = ((performance.now() - startedAt) / 1000).toFixed(1);\n\tconst header = `${result.ok ? \"Script completed\" : \"Script failed\"}\\nWall time ${wallTime} seconds\\nOutput:\\n`;\n\tconst details = snapshot();\n\tif (truncated.fullOutputPath) details.fullOutputPath = truncated.fullOutputPath;\n\treturn {\n\t\tcontent: [{ type: \"text\", text: header }, ...truncated.items],\n\t\tdetails,\n\t\t...(modelUsage ? { usage: modelUsage } : {}),\n\t\t...(result.ok ? {} : { isError: true }),\n\t};\n}\n\n/**\n * Whether `query` names the namespace: its name, its script identifier (`mcp__dev-radius` is\n * `mcp__dev_radius`), or the part after its last `__` in either form (`dev-radius`, `dev_radius`).\n */\nfunction isNamespaceName(namespace: string, query: string): boolean {\n\tconst id = toCodemodeIdentifier(namespace);\n\tconst queryId = toCodemodeIdentifier(query);\n\tconst suffix = (name: string) => (name.includes(\"__\") ? name.slice(name.lastIndexOf(\"__\") + 2) : undefined);\n\treturn namespace === query || id === queryId || suffix(namespace) === query || suffix(id) === queryId;\n}\n\n/**\n * `searchTools()`, `describeTool()`, and `describeNamespace()`: ranked search and lookup over the\n * script's nested tools and their namespaces.\n */\nfunction createDiscoveryGlobals(\n\ttools: readonly AgentTool<any>[],\n\tsamples: ReadonlyMap<string, string>,\n\toptions: CodemodeToolOptions,\n): CodemodeTool[] {\n\tconst ranker = new Bm25Ranker();\n\tconst entry = (name: string) => ({ name: toCodemodeIdentifier(name), description: samples.get(name) ?? \"\" });\n\treturn [\n\t\t{\n\t\t\tname: \"searchTools\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [query, searchOptions] = args as [unknown, { limit?: unknown; namespace?: unknown } | undefined];\n\t\t\t\tif (typeof query !== \"string\") throw new Error(\"searchTools() expects a query string\");\n\t\t\t\tconst limit = searchOptions?.limit ?? DEFAULT_TOOL_SEARCH_LIMIT;\n\t\t\t\tif (typeof limit !== \"number\" || !Number.isInteger(limit) || limit <= 0) {\n\t\t\t\t\tthrow new Error(\"searchTools() limit must be a positive integer\");\n\t\t\t\t}\n\t\t\t\tconst namespace = searchOptions?.namespace;\n\t\t\t\tif (namespace !== undefined && namespace !== null && typeof namespace !== \"string\") {\n\t\t\t\t\tthrow new Error(\"searchTools() namespace must be a string\");\n\t\t\t\t}\n\t\t\t\tconst documents = tools.flatMap((tool) => {\n\t\t\t\t\tconst toolNamespace = options.getToolNamespace?.(tool.name);\n\t\t\t\t\tif (namespace && (!toolNamespace || !isNamespaceName(toolNamespace.name, namespace))) return [];\n\t\t\t\t\treturn [createToolSearchDocument(tool, toolNamespace)];\n\t\t\t\t});\n\t\t\t\treturn ranker.rank(query, documents, limit).map((match) => entry(match.name));\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"describeTool\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [name] = args as unknown[];\n\t\t\t\tif (typeof name !== \"string\") throw new Error(\"describeTool() expects a tool name\");\n\t\t\t\tconst tool = tools.find(\n\t\t\t\t\t(candidate) => candidate.name === name || toCodemodeIdentifier(candidate.name) === name,\n\t\t\t\t);\n\t\t\t\treturn tool ? samples.get(tool.name) : undefined;\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"describeNamespace\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [name] = args as unknown[];\n\t\t\t\tif (typeof name !== \"string\") throw new Error(\"describeNamespace() expects a namespace name\");\n\t\t\t\tlet namespace: ToolNamespace | undefined;\n\t\t\t\tconst names: string[] = [];\n\t\t\t\tfor (const tool of tools) {\n\t\t\t\t\tconst toolNamespace = options.getToolNamespace?.(tool.name);\n\t\t\t\t\tif (!toolNamespace || !isNamespaceName(toolNamespace.name, name)) continue;\n\t\t\t\t\tnamespace ??= toolNamespace;\n\t\t\t\t\tnames.push(toCodemodeIdentifier(tool.name));\n\t\t\t\t}\n\t\t\t\tif (!namespace) return undefined;\n\t\t\t\treturn {\n\t\t\t\t\tname: namespace.name,\n\t\t\t\t\t...(namespace.description ? { description: namespace.description } : {}),\n\t\t\t\t\t...(namespace.instructions ? { instructions: namespace.instructions } : {}),\n\t\t\t\t\ttools: names,\n\t\t\t\t};\n\t\t\t},\n\t\t},\n\t];\n}\n\n/**\n * `models.*` for scripts: the model registry methods documented in docs/codemode.md.\n * Classifier and image calls appear as nested call rows so the renderer shows them, and their usage\n * goes to `addUsage`. Rows show only the model, never prompts or image data.\n */\nfunction createModelGlobals(\n\tmodels: CodemodeModelRuntime,\n\ttoolCallId: string,\n\tcalls: CodemodeNestedCall[],\n\tpublish: () => void,\n\taddUsage: (usage: Usage) => void,\n\taddGeneratedImages: (count: number) => void,\n): CodemodeTool[] {\n\tconst limit = createLimiter(MAX_CONCURRENT_MODEL_CALLS);\n\tlet callCount = 0;\n\n\t/**\n\t * Resolve the script's model by provider and id only, check the context, then run the call as a\n\t * nested call row. A script-supplied baseUrl or headers must never receive the credentials.\n\t */\n\tconst runModelCall = async <TType extends \"classifier\" | \"image\", TContext, TResult extends ModelCallResult>(\n\t\tname: string,\n\t\ttype: TType,\n\t\t[model, context]: unknown[],\n\t\tcheckContext: (context: unknown) => TContext,\n\t\trun: (resolved: ModelTypeMap[TType], context: TContext) => Promise<TResult>,\n\t): Promise<TResult> => {\n\t\tconst listHint = `List the ${type} models you can use with models.getAvailableOfType(\"${type}\").`;\n\t\tif (!isRecord(model) || typeof model.provider !== \"string\" || typeof model.id !== \"string\") {\n\t\t\t// undefined arrives as null: spread arguments cross the sandbox as a JSON array.\n\t\t\tconst undefinedHint =\n\t\t\t\tmodel === undefined || model === null\n\t\t\t\t\t? \" models.getModelOfType() returns undefined for an unknown provider or id.\"\n\t\t\t\t\t: \"\";\n\t\t\tthrow new Error(\n\t\t\t\t`${name}() expects ${withArticle(type)} model as its first argument, got ${describeValue(model)}.${undefinedHint} ${listHint}`,\n\t\t\t);\n\t\t}\n\t\tconst { provider, id } = model;\n\t\tconst ref = `${provider}/${id}`;\n\t\tconst resolved = models.getModelOfType(type, provider, id);\n\t\tif (!resolved) {\n\t\t\tconst actualType = [...MODEL_TYPES].find(\n\t\t\t\t(other) => other !== type && models.getModelOfType(other as ModelType, provider, id) !== undefined,\n\t\t\t);\n\t\t\tthrow new Error(\n\t\t\t\tactualType\n\t\t\t\t\t? `\"${ref}\" is ${withArticle(actualType)} model, not ${withArticle(type)} model. ${listHint}`\n\t\t\t\t\t: `Unknown ${type} model \"${ref}\". ${listHint}`,\n\t\t\t);\n\t\t}\n\t\tconst checked = checkContext(context);\n\n\t\tconst record: CodemodeNestedCall = {\n\t\t\tid: `${toolCallId}/${name}/${++callCount}`,\n\t\t\tname,\n\t\t\targs: `${resolved.provider}/${resolved.id}`,\n\t\t\tstatus: \"running\",\n\t\t};\n\t\tcalls.push(record);\n\t\tpublish();\n\t\tconst startedAt = performance.now();\n\t\tconst result = await limit(() => run(resolved, checked));\n\t\trecord.durationMs = performance.now() - startedAt;\n\t\trecord.status = result.stopReason === \"stop\" ? \"ok\" : result.stopReason === \"aborted\" ? \"cancelled\" : \"error\";\n\t\tif (result.errorMessage) record.error = truncateText(result.errorMessage, ERROR_PREVIEW_CHARS);\n\t\tif (result.usage) {\n\t\t\trecord.cost = result.usage.cost.total;\n\t\t\taddUsage(result.usage);\n\t\t}\n\t\tpublish();\n\t\treturn result;\n\t};\n\tconst implementations: Record<string, CodemodeTool[\"execute\"]> = {\n\t\t\"models.getModelsOfType\": (args) => {\n\t\t\tconst [type, provider] = args as unknown[];\n\t\t\treturn models.getModelsOfType(toModelType(type), toProvider(provider)).map(toModelInfo);\n\t\t},\n\t\t\"models.getAvailableOfType\": async (args, { signal }) => {\n\t\t\tconst [type, provider] = args as unknown[];\n\t\t\tconst available = await models.getAvailableOfType(toModelType(type), toProvider(provider), { signal });\n\t\t\treturn available.map(toModelInfo);\n\t\t},\n\t\t\"models.getModelOfType\": (args) => {\n\t\t\tconst [type, provider, id] = args as unknown[];\n\t\t\tif (typeof provider !== \"string\" || typeof id !== \"string\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`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\").`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst model = models.getModelOfType(toModelType(type), provider, id);\n\t\t\treturn model === undefined ? undefined : toModelInfo(model);\n\t\t},\n\t\t\"models.classify\": (args, { signal }) =>\n\t\t\trunModelCall(\"models.classify\", \"classifier\", args as unknown[], checkClassifierContext, (resolved, context) =>\n\t\t\t\tmodels.classify(resolved, context, { signal }),\n\t\t\t),\n\t\t\"models.generateImages\": (args, { signal }) =>\n\t\t\trunModelCall(\n\t\t\t\t\"models.generateImages\",\n\t\t\t\t\"image\",\n\t\t\t\targs as unknown[],\n\t\t\t\tcheckImagesContext,\n\t\t\t\tasync (resolved, context) => {\n\t\t\t\t\tconst result = await models.generateImages(resolved, context, { signal });\n\t\t\t\t\taddGeneratedImages(result.output.filter((block) => block.type === \"image\").length);\n\t\t\t\t\treturn result;\n\t\t\t\t},\n\t\t\t),\n\t};\n\treturn Object.entries(implementations).map(([name, execute]) => ({ name, spread: true, execute }));\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"renderer.d.ts","sourceRoot":"","sources":["../../../src/extensions/codemode/renderer.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;
|
|
1
|
+
{"version":3,"file":"renderer.d.ts","sourceRoot":"","sources":["../../../src/extensions/codemode/renderer.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAKrE,OAAO,KAAK,EAAsB,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAiDzE,eAAO,MAAM,iBAAiB,EAAE,IAAI,CACnC,cAAc,CAAC,GAAG,EAAE,mBAAmB,GAAG,SAAS,CAAC,EACpD,YAAY,GAAG,cAAc,CAmF7B,CAAC"}
|