@astralyn/pi 1.3.1 → 1.4.1
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 +52 -0
- package/dist/bundle/chunks/anthropic-messages-HWL6AS7T.js +6 -0
- package/dist/bundle/chunks/azure-openai-responses-4YYPDYV5.js +2 -0
- package/dist/bundle/chunks/bedrock-converse-stream.js +8 -8
- package/dist/bundle/chunks/chunk-24FY4C5S.js +2 -0
- package/dist/bundle/chunks/chunk-6JS2SOFO.js +11 -0
- package/dist/bundle/chunks/chunk-ANCZPKX7.js +2 -0
- package/dist/bundle/chunks/{chunk-VOAXAPU6.js → chunk-KSKBY3VV.js} +161 -91
- package/dist/bundle/chunks/chunk-MMNIHCU7.js +2 -0
- package/dist/bundle/chunks/{chunk-KSCGI7JW.js → chunk-MZJC45TM.js} +2 -2
- package/dist/bundle/chunks/{chunk-LXR54CGB.js → chunk-N77PYEXG.js} +1 -1
- package/dist/bundle/chunks/{chunk-J75WV3FL.js → chunk-OV2VMHBX.js} +1 -1
- package/dist/bundle/chunks/chunk-TPVFPFJP.js +2 -0
- package/dist/bundle/chunks/chunk-ZAIGBRV5.js +16 -0
- package/dist/bundle/chunks/cloudflare-workers-ai-system-one-7BKATOEJ.js +2 -0
- package/dist/bundle/chunks/github-copilot.js +1 -1
- package/dist/bundle/chunks/google-generative-ai-HTUSU45F.js +2 -0
- package/dist/bundle/chunks/google-vertex-AVQV4P76.js +2 -0
- package/dist/bundle/chunks/{llama-cpp-classify-H3IZDR5O.js → llama-cpp-classify-27QYLJZY.js} +2 -2
- package/dist/bundle/chunks/{mistral-conversations-6E6SS3WF.js → mistral-conversations-V2JJTMJ5.js} +1 -1
- package/dist/bundle/chunks/openai-codex-responses-Q25MHDFX.js +10 -0
- package/dist/bundle/chunks/openai-completions-TXZXILJR.js +7 -0
- package/dist/bundle/chunks/{openai-decisions-TVCDIPZX.js → openai-decisions-3WYFPGSK.js} +1 -1
- package/dist/bundle/chunks/openai-responses-E4BNZIQK.js +4 -0
- package/dist/bundle/chunks/openrouter-images-CBP3OPOD.js +2 -0
- package/dist/bundle/chunks/pi-messages-LBJQ4NGP.js +8 -0
- package/dist/bundle/chunks/typesafe-system-one-BNICP2LS.js +2 -0
- package/dist/bundle/chunks/virtual-modules-XNEYDLXF.js +2 -0
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/core/agent-session.d.ts +7 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +61 -13
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/client-identity.d.ts +8 -0
- package/dist/core/client-identity.d.ts.map +1 -0
- package/dist/core/client-identity.js +15 -0
- package/dist/core/client-identity.js.map +1 -0
- package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
- package/dist/core/compaction/branch-summarization.js +1 -2
- package/dist/core/compaction/branch-summarization.js.map +1 -1
- package/dist/core/compaction/compaction.d.ts +2 -2
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +25 -20
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/export-html/index.d.ts.map +1 -1
- package/dist/core/export-html/index.js +2 -0
- package/dist/core/export-html/index.js.map +1 -1
- package/dist/core/export-html/template.html +1 -0
- package/dist/core/export-html/template.js +2 -1
- package/dist/core/export-html/vendor/marked-cjk-friendly.min.js +6 -0
- package/dist/core/export-html/vendor/marked.min.js +30 -29
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +3 -0
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/virtual-modules.d.ts.map +1 -1
- package/dist/core/extensions/virtual-modules.js +3 -0
- package/dist/core/extensions/virtual-modules.js.map +1 -1
- package/dist/core/model-config.d.ts +915 -0
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-config.js +48 -24
- package/dist/core/model-config.js.map +1 -1
- package/dist/core/model-resolver.js +7 -7
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +6 -3
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/provider-composer.d.ts +2 -1
- package/dist/core/provider-composer.d.ts.map +1 -1
- package/dist/core/provider-composer.js +7 -3
- package/dist/core/provider-composer.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +9 -10
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/tasks/presentation.d.ts.map +1 -1
- package/dist/core/tasks/presentation.js +3 -1
- package/dist/core/tasks/presentation.js.map +1 -1
- package/dist/core/tasks/reminder.d.ts +15 -0
- package/dist/core/tasks/reminder.d.ts.map +1 -0
- package/dist/core/tasks/reminder.js +54 -0
- package/dist/core/tasks/reminder.js.map +1 -0
- package/dist/core/tasks/runtime.d.ts +4 -1
- package/dist/core/tasks/runtime.d.ts.map +1 -1
- package/dist/core/tasks/runtime.js +37 -11
- package/dist/core/tasks/runtime.js.map +1 -1
- package/dist/core/tasks/session.d.ts +9 -0
- package/dist/core/tasks/session.d.ts.map +1 -1
- package/dist/core/tasks/session.js +24 -0
- package/dist/core/tasks/session.js.map +1 -1
- package/dist/core/tasks/types.d.ts +6 -1
- package/dist/core/tasks/types.d.ts.map +1 -1
- package/dist/core/tasks/types.js.map +1 -1
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +3 -1
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/shell-tool.js +2 -2
- package/dist/core/tools/shell-tool.js.map +1 -1
- package/dist/core/tools/tasks/actions.d.ts +1 -1
- package/dist/core/tools/tasks/actions.d.ts.map +1 -1
- package/dist/core/tools/tasks/actions.js +98 -5
- package/dist/core/tools/tasks/actions.js.map +1 -1
- package/dist/core/tools/tasks/schema.d.ts +1 -1
- package/dist/core/tools/tasks/schema.d.ts.map +1 -1
- package/dist/core/tools/tasks/schema.js +9 -6
- package/dist/core/tools/tasks/schema.js.map +1 -1
- package/dist/core/tools/tasks/types.d.ts +9 -3
- package/dist/core/tools/tasks/types.d.ts.map +1 -1
- package/dist/core/tools/tasks/types.js.map +1 -1
- package/dist/core/tools/tasks.d.ts +1 -1
- package/dist/core/tools/tasks.d.ts.map +1 -1
- package/dist/core/tools/tasks.js +2 -2
- package/dist/core/tools/tasks.js.map +1 -1
- package/dist/extensions/cached-compaction/index.d.ts +3 -0
- package/dist/extensions/cached-compaction/index.d.ts.map +1 -0
- package/dist/extensions/cached-compaction/index.js +91 -0
- package/dist/extensions/cached-compaction/index.js.map +1 -0
- package/dist/extensions/cached-compaction/render.d.ts +11 -0
- package/dist/extensions/cached-compaction/render.d.ts.map +1 -0
- package/dist/extensions/cached-compaction/render.js +19 -0
- package/dist/extensions/cached-compaction/render.js.map +1 -0
- package/dist/extensions/cached-compaction/summary.d.ts +15 -0
- package/dist/extensions/cached-compaction/summary.d.ts.map +1 -0
- package/dist/extensions/cached-compaction/summary.js +131 -0
- package/dist/extensions/cached-compaction/summary.js.map +1 -0
- package/dist/extensions/codemode/execute.d.ts.map +1 -1
- package/dist/extensions/codemode/execute.js +99 -24
- package/dist/extensions/codemode/execute.js.map +1 -1
- package/dist/extensions/index.d.ts.map +1 -1
- package/dist/extensions/index.js +2 -0
- package/dist/extensions/index.js.map +1 -1
- package/dist/extensions/mcp/config.d.ts.map +1 -1
- package/dist/extensions/mcp/config.js +3 -2
- package/dist/extensions/mcp/config.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +11 -15
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +68 -109
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/tasks/render.d.ts.map +1 -1
- package/dist/modes/interactive/tasks/render.js +17 -9
- package/dist/modes/interactive/tasks/render.js.map +1 -1
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +2 -1
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/utils/clipboard-command.d.ts.map +1 -1
- package/dist/utils/clipboard-command.js +3 -0
- package/dist/utils/clipboard-command.js.map +1 -1
- package/dist/utils/pi-user-agent.d.ts +1 -0
- package/dist/utils/pi-user-agent.d.ts.map +1 -1
- package/dist/utils/pi-user-agent.js +3 -2
- package/dist/utils/pi-user-agent.js.map +1 -1
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +45 -13
- package/dist/utils/shell.js.map +1 -1
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +4 -3
- package/dist/utils/tools-manager.js.map +1 -1
- package/docs/bundled/extensions/cached-compaction.md +35 -0
- package/docs/bundled/tasks.md +17 -7
- package/docs/codemode.md +2 -2
- package/docs/compaction.md +5 -3
- package/docs/custom-provider.md +53 -1
- package/docs/docs.json +8 -0
- package/docs/environment-variables.md +1 -0
- package/docs/extensions.md +98 -3
- package/docs/models-configuration.md +196 -0
- package/docs/models.md +9 -5
- package/docs/sdk.md +2 -2
- package/docs/session-format.md +2 -2
- package/docs/settings.md +2 -2
- package/docs/tui.md +71 -0
- package/docs/windows.md +28 -0
- 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/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/npm-shrinkwrap.json +150 -137
- package/package.json +7 -6
- package/schemas/models.schema.json +83 -29
- package/dist/bundle/chunks/anthropic-messages-MSB6JBS2.js +0 -6
- package/dist/bundle/chunks/azure-openai-responses-ATZ757I2.js +0 -2
- package/dist/bundle/chunks/chunk-4XZYHGVN.js +0 -11
- package/dist/bundle/chunks/chunk-7UBIBLPN.js +0 -2
- package/dist/bundle/chunks/chunk-LUYFHZ6W.js +0 -11
- package/dist/bundle/chunks/chunk-NM2KGRFS.js +0 -2
- package/dist/bundle/chunks/chunk-QDDSFJ35.js +0 -2
- package/dist/bundle/chunks/cloudflare-workers-ai-system-one-HGOVFZDC.js +0 -2
- package/dist/bundle/chunks/google-generative-ai-QRLQ4MCJ.js +0 -2
- package/dist/bundle/chunks/google-vertex-L3T6EGTL.js +0 -2
- package/dist/bundle/chunks/openai-codex-responses-4GUO76XJ.js +0 -10
- package/dist/bundle/chunks/openai-completions-O4TKZCIM.js +0 -7
- package/dist/bundle/chunks/openai-responses-VBQKJFNO.js +0 -3
- package/dist/bundle/chunks/openrouter-images-TDLJV5N4.js +0 -2
- package/dist/bundle/chunks/pi-messages-3POWZ43C.js +0 -8
- package/dist/bundle/chunks/typesafe-system-one-LWPJYTJP.js +0 -2
- package/dist/bundle/chunks/virtual-modules-CKPHR6LX.js +0 -2
- package/dist/core/provider-attribution.d.ts +0 -4
- package/dist/core/provider-attribution.d.ts.map +0 -1
- package/dist/core/provider-attribution.js +0 -72
- package/dist/core/provider-attribution.js.map +0 -1
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { contentText } from "@earendil-works/pi-ai";
|
|
2
|
+
import { convertToLlm } from "../../core/messages.js";
|
|
3
|
+
import { buildSessionProjection, getLatestCompactionEntry } from "../../core/session-manager.js";
|
|
4
|
+
function sameMessage(candidate, projected) {
|
|
5
|
+
const serialized = JSON.stringify(candidate);
|
|
6
|
+
return convertToLlm([projected]).some((message) => JSON.stringify(message) === serialized);
|
|
7
|
+
}
|
|
8
|
+
function messagePreview(message) {
|
|
9
|
+
let text;
|
|
10
|
+
if (message.role === "user") {
|
|
11
|
+
text = contentText(message.content);
|
|
12
|
+
}
|
|
13
|
+
else if (message.role === "assistant") {
|
|
14
|
+
text = message.content
|
|
15
|
+
.flatMap((block) => block.type === "text"
|
|
16
|
+
? [block.text]
|
|
17
|
+
: block.type === "toolCall"
|
|
18
|
+
? [`[tool call: ${block.name} ${JSON.stringify(block.arguments)}]`]
|
|
19
|
+
: [])
|
|
20
|
+
.join("\n");
|
|
21
|
+
}
|
|
22
|
+
text = text?.trim();
|
|
23
|
+
if (!text)
|
|
24
|
+
return undefined;
|
|
25
|
+
return text.length > 400 ? `${text.slice(0, 400)}…` : text;
|
|
26
|
+
}
|
|
27
|
+
export function keptStart(entries, firstKeptEntryId, conversation) {
|
|
28
|
+
const projected = buildSessionProjection(entries).entries;
|
|
29
|
+
const start = projected.findIndex((entry) => entry.sourceEntry.id === firstKeptEntryId);
|
|
30
|
+
if (start === -1)
|
|
31
|
+
return undefined;
|
|
32
|
+
let at = -1;
|
|
33
|
+
for (const message of projected.slice(start).flatMap((entry) => entry.messages)) {
|
|
34
|
+
at = conversation.findLastIndex((candidate) => sameMessage(candidate, message));
|
|
35
|
+
if (at !== -1)
|
|
36
|
+
break;
|
|
37
|
+
}
|
|
38
|
+
if (at === -1)
|
|
39
|
+
return undefined;
|
|
40
|
+
const previews = conversation.slice(at).map(messagePreview);
|
|
41
|
+
const text = previews[0];
|
|
42
|
+
return text
|
|
43
|
+
? { text, fromEnd: previews.filter((preview) => preview === text).length, count: previews.length }
|
|
44
|
+
: undefined;
|
|
45
|
+
}
|
|
46
|
+
export function summaryInstruction(kept, customInstructions) {
|
|
47
|
+
const repeated = kept.fromEnd > 1
|
|
48
|
+
? ` Several retained messages begin with this text. The boundary is occurrence ${kept.fromEnd}, counting backward from the end of the conversation.`
|
|
49
|
+
: "";
|
|
50
|
+
const toolCalls = kept.text.includes("[tool call: ")
|
|
51
|
+
? " Tool calls are written as [tool call: name arguments]."
|
|
52
|
+
: "";
|
|
53
|
+
const focus = customInstructions?.trim() ? `\n\nAdditional focus from the user:\n${customInstructions.trim()}` : "";
|
|
54
|
+
return `Stop working on the current task. Do not call any tools.
|
|
55
|
+
|
|
56
|
+
Write a structured context checkpoint summary of the earlier part of this conversation. Another LLM will continue the task from your summary, followed by the last ${kept.count} messages, which will remain in context verbatim.
|
|
57
|
+
|
|
58
|
+
The retained messages begin with the message that starts with this text.${repeated}${toolCalls}
|
|
59
|
+
|
|
60
|
+
<kept-start>
|
|
61
|
+
${kept.text}
|
|
62
|
+
</kept-start>
|
|
63
|
+
|
|
64
|
+
Summarize only the messages before that boundary, as if the conversation had ended immediately before it. Work occurring at or after the boundary has not happened as far as this summary is concerned: do not list it as completed. If it was already planned, include it under Next Steps instead.
|
|
65
|
+
|
|
66
|
+
If the conversation contains an earlier checkpoint summary, fold its still-relevant facts into this summary and update its progress and next steps.
|
|
67
|
+
|
|
68
|
+
Use exactly this structure:
|
|
69
|
+
|
|
70
|
+
## Goal
|
|
71
|
+
[What the user is trying to accomplish. Include multiple goals if applicable.]
|
|
72
|
+
|
|
73
|
+
## Constraints & Preferences
|
|
74
|
+
- [Requirements, preferences, and explicit constraints from the user]
|
|
75
|
+
- [Use "(none)" when appropriate]
|
|
76
|
+
|
|
77
|
+
## Progress
|
|
78
|
+
### Done
|
|
79
|
+
- [x] [Work completed before the boundary]
|
|
80
|
+
|
|
81
|
+
### In Progress
|
|
82
|
+
- [ ] [Work underway at the boundary]
|
|
83
|
+
|
|
84
|
+
### Blocked
|
|
85
|
+
- [Issues preventing progress, or "(none)"]
|
|
86
|
+
|
|
87
|
+
## Key Decisions
|
|
88
|
+
- **[Decision]**: [Rationale]
|
|
89
|
+
|
|
90
|
+
## Next Steps
|
|
91
|
+
1. [Ordered steps needed to continue]
|
|
92
|
+
|
|
93
|
+
## Critical Context
|
|
94
|
+
- [Exact information needed to continue: file paths, symbols, commands, important tool results, error messages, and relevant technical details]
|
|
95
|
+
|
|
96
|
+
Be concise but preserve information required to continue without rereading the original conversation. Keep exact file paths, function names, commands, and error messages. Do not include file-operation lists; they will be added automatically. Return only the summary.${focus}`;
|
|
97
|
+
}
|
|
98
|
+
function isPlainObject(value) {
|
|
99
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
100
|
+
}
|
|
101
|
+
export function checkpointSummary(text, fileOps, entries) {
|
|
102
|
+
const read = new Set(fileOps.read);
|
|
103
|
+
const modified = new Set([...fileOps.written, ...fileOps.edited]);
|
|
104
|
+
const previousDetails = getLatestCompactionEntry(entries)?.details;
|
|
105
|
+
if (isPlainObject(previousDetails)) {
|
|
106
|
+
const { readFiles, modifiedFiles } = previousDetails;
|
|
107
|
+
if (Array.isArray(readFiles)) {
|
|
108
|
+
for (const file of readFiles)
|
|
109
|
+
if (typeof file === "string")
|
|
110
|
+
read.add(file);
|
|
111
|
+
}
|
|
112
|
+
if (Array.isArray(modifiedFiles)) {
|
|
113
|
+
for (const file of modifiedFiles)
|
|
114
|
+
if (typeof file === "string")
|
|
115
|
+
modified.add(file);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
const details = {
|
|
119
|
+
readFiles: [...read].filter((file) => !modified.has(file)).sort(),
|
|
120
|
+
modifiedFiles: [...modified].sort(),
|
|
121
|
+
};
|
|
122
|
+
const sections = [
|
|
123
|
+
text.replace(/<(read-files|modified-files)>[\s\S]*?<\/\1>/g, "").trim(),
|
|
124
|
+
details.readFiles.length > 0 ? `<read-files>\n${details.readFiles.join("\n")}\n</read-files>` : "",
|
|
125
|
+
details.modifiedFiles.length > 0
|
|
126
|
+
? `<modified-files>\n${details.modifiedFiles.join("\n")}\n</modified-files>`
|
|
127
|
+
: "",
|
|
128
|
+
];
|
|
129
|
+
return { summary: sections.filter(Boolean).join("\n\n"), details };
|
|
130
|
+
}
|
|
131
|
+
//# sourceMappingURL=summary.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"summary.js","sourceRoot":"","sources":["../../../src/extensions/cached-compaction/summary.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAgB,MAAM,uBAAuB,CAAC;AAElE,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACtD,OAAO,EAAE,sBA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,IAAI,IAAI,SAAS;gBAAE,IAAI,OAAO,IAAI,KAAK,QAAQ;oBAAE,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC5E,CAAC;QACD,IAAI,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,EAAE,CAAC;YAClC,KAAK,MAAM,IAAI,IAAI,aAAa;gBAAE,IAAI,OAAO,IAAI,KAAK,QAAQ;oBAAE,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACpF,CAAC;IACF,CAAC;IACD,MAAM,OAAO,GAAG;QACf,SAAS,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE;QACjE,aAAa,EAAE,CAAC,GAAG,QAAQ,CAAC,CAAC,IAAI,EAAE;KACnC,CAAC;IACF,MAAM,QAAQ,GAAG;QAChB,IAAI,CAAC,OAAO,CAAC,8CAA8C,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE;QACvE,OAAO,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,iBAAiB,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC,CAAC,EAAE;QAClG,OAAO,CAAC,aAAa,CAAC,MAAM,GAAG,CAAC;YAC/B,CAAC,CAAC,qBAAqB,OAAO,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,qBAAqB;YAC5E,CAAC,CAAC,EAAE;KACL,CAAC;IACF,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,CAAC;AACpE,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport { contentText, type Message } from \"@earendil-works/pi-ai\";\nimport type { CompactionDetails, FileOperations } from \"../../core/compaction/index.ts\";\nimport { convertToLlm } from \"../../core/messages.ts\";\nimport { buildSessionProjection, getLatestCompactionEntry, type SessionEntry } from \"../../core/session-manager.ts\";\n\nexport interface KeptStart {\n\ttext: string;\n\tfromEnd: number;\n\tcount: number;\n}\n\nfunction sameMessage(candidate: Message, projected: AgentMessage): boolean {\n\tconst serialized = JSON.stringify(candidate);\n\treturn convertToLlm([projected]).some((message) => JSON.stringify(message) === serialized);\n}\n\nfunction messagePreview(message: Message): string | undefined {\n\tlet text: string | undefined;\n\tif (message.role === \"user\") {\n\t\ttext = contentText(message.content);\n\t} else if (message.role === \"assistant\") {\n\t\ttext = message.content\n\t\t\t.flatMap((block) =>\n\t\t\t\tblock.type === \"text\"\n\t\t\t\t\t? [block.text]\n\t\t\t\t\t: block.type === \"toolCall\"\n\t\t\t\t\t\t? [`[tool call: ${block.name} ${JSON.stringify(block.arguments)}]`]\n\t\t\t\t\t\t: [],\n\t\t\t)\n\t\t\t.join(\"\\n\");\n\t}\n\ttext = text?.trim();\n\tif (!text) return undefined;\n\treturn text.length > 400 ? `${text.slice(0, 400)}…` : text;\n}\n\nexport function keptStart(\n\tentries: SessionEntry[],\n\tfirstKeptEntryId: string,\n\tconversation: Message[],\n): KeptStart | undefined {\n\tconst projected = buildSessionProjection(entries).entries;\n\tconst start = projected.findIndex((entry) => entry.sourceEntry.id === firstKeptEntryId);\n\tif (start === -1) return undefined;\n\tlet at = -1;\n\tfor (const message of projected.slice(start).flatMap((entry) => entry.messages)) {\n\t\tat = conversation.findLastIndex((candidate) => sameMessage(candidate, message));\n\t\tif (at !== -1) break;\n\t}\n\tif (at === -1) return undefined;\n\tconst previews = conversation.slice(at).map(messagePreview);\n\tconst text = previews[0];\n\treturn text\n\t\t? { text, fromEnd: previews.filter((preview) => preview === text).length, count: previews.length }\n\t\t: undefined;\n}\n\nexport function summaryInstruction(kept: KeptStart, customInstructions?: string): string {\n\tconst repeated =\n\t\tkept.fromEnd > 1\n\t\t\t? ` Several retained messages begin with this text. The boundary is occurrence ${kept.fromEnd}, counting backward from the end of the conversation.`\n\t\t\t: \"\";\n\tconst toolCalls = kept.text.includes(\"[tool call: \")\n\t\t? \" Tool calls are written as [tool call: name arguments].\"\n\t\t: \"\";\n\tconst focus = customInstructions?.trim() ? `\\n\\nAdditional focus from the user:\\n${customInstructions.trim()}` : \"\";\n\treturn `Stop working on the current task. Do not call any tools.\n\nWrite a structured context checkpoint summary of the earlier part of this conversation. Another LLM will continue the task from your summary, followed by the last ${kept.count} messages, which will remain in context verbatim.\n\nThe retained messages begin with the message that starts with this text.${repeated}${toolCalls}\n\n<kept-start>\n${kept.text}\n</kept-start>\n\nSummarize only the messages before that boundary, as if the conversation had ended immediately before it. Work occurring at or after the boundary has not happened as far as this summary is concerned: do not list it as completed. If it was already planned, include it under Next Steps instead.\n\nIf the conversation contains an earlier checkpoint summary, fold its still-relevant facts into this summary and update its progress and next steps.\n\nUse exactly this structure:\n\n## Goal\n[What the user is trying to accomplish. Include multiple goals if applicable.]\n\n## Constraints & Preferences\n- [Requirements, preferences, and explicit constraints from the user]\n- [Use \"(none)\" when appropriate]\n\n## Progress\n### Done\n- [x] [Work completed before the boundary]\n\n### In Progress\n- [ ] [Work underway at the boundary]\n\n### Blocked\n- [Issues preventing progress, or \"(none)\"]\n\n## Key Decisions\n- **[Decision]**: [Rationale]\n\n## Next Steps\n1. [Ordered steps needed to continue]\n\n## Critical Context\n- [Exact information needed to continue: file paths, symbols, commands, important tool results, error messages, and relevant technical details]\n\nBe concise but preserve information required to continue without rereading the original conversation. Keep exact file paths, function names, commands, and error messages. Do not include file-operation lists; they will be added automatically. Return only the summary.${focus}`;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport function checkpointSummary(\n\ttext: string,\n\tfileOps: FileOperations,\n\tentries: SessionEntry[],\n): { summary: string; details: CompactionDetails } {\n\tconst read = new Set(fileOps.read);\n\tconst modified = new Set([...fileOps.written, ...fileOps.edited]);\n\tconst previousDetails: unknown = getLatestCompactionEntry(entries)?.details;\n\tif (isPlainObject(previousDetails)) {\n\t\tconst { readFiles, modifiedFiles } = previousDetails;\n\t\tif (Array.isArray(readFiles)) {\n\t\t\tfor (const file of readFiles) if (typeof file === \"string\") read.add(file);\n\t\t}\n\t\tif (Array.isArray(modifiedFiles)) {\n\t\t\tfor (const file of modifiedFiles) if (typeof file === \"string\") modified.add(file);\n\t\t}\n\t}\n\tconst details = {\n\t\treadFiles: [...read].filter((file) => !modified.has(file)).sort(),\n\t\tmodifiedFiles: [...modified].sort(),\n\t};\n\tconst sections = [\n\t\ttext.replace(/<(read-files|modified-files)>[\\s\\S]*?<\\/\\1>/g, \"\").trim(),\n\t\tdetails.readFiles.length > 0 ? `<read-files>\\n${details.readFiles.join(\"\\n\")}\\n</read-files>` : \"\",\n\t\tdetails.modifiedFiles.length > 0\n\t\t\t? `<modified-files>\\n${details.modifiedFiles.join(\"\\n\")}\\n</modified-files>`\n\t\t\t: \"\",\n\t];\n\treturn { summary: sections.filter(Boolean).join(\"\\n\\n\"), details };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execute.d.ts","sourceRoot":"","sources":["../../../src/extensions/codemode/execute.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAmC,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAsBtG,OAAO,KAAK,EAAE,oBAAoB,EAAiB,MAAM,gCAAgC,CAAC;AAC1F,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAKlE,OAAO,EAMN,KAAK,mBAAmB,EACxB,KAAK,iBAAiB,EACtB,KAAK,mBAAmB,EAGxB,MAAM,WAAW,CAAC;
|
|
1
|
+
{"version":3,"file":"execute.d.ts","sourceRoot":"","sources":["../../../src/extensions/codemode/execute.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAmC,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAsBtG,OAAO,KAAK,EAAE,oBAAoB,EAAiB,MAAM,gCAAgC,CAAC;AAC1F,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAKlE,OAAO,EAMN,KAAK,mBAAmB,EACxB,KAAK,iBAAiB,EACtB,KAAK,mBAAmB,EAGxB,MAAM,WAAW,CAAC;AAuPnB,6FAA6F;AAC7F,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,SAAS,YAAY,EAAE,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAU1F;AAyLD;;;GAGG;AACH,wBAAsB,eAAe,CACpC,UAAU,EAAE,MAAM,EAClB,KAAK,EAAE,iBAAiB,EACxB,MAAM,EAAE,WAAW,GAAG,SAAS,EAC/B,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,eAAe,CAAC,mBAAmB,CAAC,KAAK,IAAI,CAAC,GAAG,SAAS,EAC9E,GAAG,EAAE,oBAAoB,GAAG,SAAS,EACrC,OAAO,GAAE,mBAAwB,GAC/B,OAAO,CAAC,eAAe,CAAC,mBAAmB,CAAC,CAAC,CAyJ/C"}
|
|
@@ -20,8 +20,55 @@ const MAX_CONCURRENT_MODEL_CALLS = 4;
|
|
|
20
20
|
*/
|
|
21
21
|
const CODEMODE_MEMORY_LIMIT_BYTES = 256 * 1024 * 1024;
|
|
22
22
|
// Shared across calls and sessions. Allow one replacement while a cancelled worker is still exiting.
|
|
23
|
-
const
|
|
23
|
+
const DEFAULT_MAX_CODEMODE_WORKERS = 2;
|
|
24
|
+
/** `PI_CODEMODE_MAX_WORKERS` if it is a positive integer. Read per call so SDK hosts can set it at runtime. */
|
|
25
|
+
function maxCodemodeWorkers() {
|
|
26
|
+
const value = Number(process.env.PI_CODEMODE_MAX_WORKERS);
|
|
27
|
+
return Number.isInteger(value) && value > 0 ? value : DEFAULT_MAX_CODEMODE_WORKERS;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* How long a script waits for a free worker before failing. Bounds the wait when every worker is
|
|
31
|
+
* held by a script that waits on another script, for example an in-process subagent that uses codemode.
|
|
32
|
+
*/
|
|
33
|
+
const CODEMODE_WORKER_WAIT_MS = 60_000;
|
|
24
34
|
let activeCodemodeWorkers = 0;
|
|
35
|
+
/** Scripts waiting for a worker, in arrival order. */
|
|
36
|
+
const codemodeWorkerWaiters = [];
|
|
37
|
+
/**
|
|
38
|
+
* Reserve one worker slot, waiting in arrival order while all are taken. Resolves with why it could
|
|
39
|
+
* not reserve one: the signal aborted, or `timeoutMs` passed.
|
|
40
|
+
*/
|
|
41
|
+
function reserveCodemodeWorker(signal, timeoutMs) {
|
|
42
|
+
if (signal?.aborted)
|
|
43
|
+
return Promise.resolve("aborted");
|
|
44
|
+
return new Promise((resolve) => {
|
|
45
|
+
const settle = (outcome) => {
|
|
46
|
+
clearTimeout(timer);
|
|
47
|
+
signal?.removeEventListener("abort", onAbort);
|
|
48
|
+
const index = codemodeWorkerWaiters.indexOf(grant);
|
|
49
|
+
if (index >= 0)
|
|
50
|
+
codemodeWorkerWaiters.splice(index, 1);
|
|
51
|
+
resolve(outcome);
|
|
52
|
+
};
|
|
53
|
+
const grant = () => settle("reserved");
|
|
54
|
+
const onAbort = () => settle("aborted");
|
|
55
|
+
const timer = setTimeout(() => settle("timeout"), timeoutMs);
|
|
56
|
+
codemodeWorkerWaiters.push(grant);
|
|
57
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
58
|
+
admitCodemodeWorkers();
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
/** Give free slots to waiting scripts in arrival order. */
|
|
62
|
+
function admitCodemodeWorkers() {
|
|
63
|
+
while (codemodeWorkerWaiters.length > 0 && activeCodemodeWorkers < maxCodemodeWorkers()) {
|
|
64
|
+
activeCodemodeWorkers++;
|
|
65
|
+
codemodeWorkerWaiters.shift()?.();
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
function releaseCodemodeWorker() {
|
|
69
|
+
activeCodemodeWorkers--;
|
|
70
|
+
admitCodemodeWorkers();
|
|
71
|
+
}
|
|
25
72
|
const MODEL_TYPES = new Set(["chat", "image", "classifier"]);
|
|
26
73
|
function truncateText(text, maxChars) {
|
|
27
74
|
return text.length > maxChars ? `${text.slice(0, maxChars - 3)}...` : text;
|
|
@@ -432,35 +479,63 @@ export async function executeCodemode(toolCallId, input, signal, onUpdate, ctx,
|
|
|
432
479
|
return toScriptValue(tool, outcome);
|
|
433
480
|
},
|
|
434
481
|
}));
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
}
|
|
456
|
-
}
|
|
482
|
+
// The wait for a worker counts toward the script's deadline.
|
|
483
|
+
const deadline = sourceOptions.timeoutMs ?? Number.POSITIVE_INFINITY;
|
|
484
|
+
const waitStartedAt = performance.now();
|
|
485
|
+
const admission = await reserveCodemodeWorker(signal, Math.min(deadline, CODEMODE_WORKER_WAIT_MS));
|
|
486
|
+
const waitedMs = performance.now() - waitStartedAt;
|
|
487
|
+
if (admission !== "reserved") {
|
|
488
|
+
const waited = ((performance.now() - startedAt) / 1000).toFixed(1);
|
|
489
|
+
const reason = signal?.reason;
|
|
490
|
+
const error = admission === "aborted"
|
|
491
|
+
? `Script aborted: ${reason instanceof Error ? reason.message : "Execution aborted"}`
|
|
492
|
+
: deadline <= CODEMODE_WORKER_WAIT_MS
|
|
493
|
+
? `Script timed out: Execution timed out after ${deadline} ms while waiting for a free codemode worker`
|
|
494
|
+
: `No codemode worker became free within ${CODEMODE_WORKER_WAIT_MS / 1000} seconds. All ${maxCodemodeWorkers()} workers, shared by every session in this process, are held by other scripts. Retry after they finish.`;
|
|
495
|
+
return {
|
|
496
|
+
content: [
|
|
497
|
+
{ type: "text", text: `Script failed\nWall time ${waited} seconds\nOutput:\n` },
|
|
498
|
+
{ type: "text", text: `Script error:\n${error}\n\nThe script did not start.` },
|
|
499
|
+
],
|
|
500
|
+
details: snapshot(),
|
|
501
|
+
isError: true,
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
// The reservation covers the one worker this script starts. A launch that resumes after the result
|
|
505
|
+
// settled finds it released and starts no worker.
|
|
506
|
+
let reserved = true;
|
|
507
|
+
let sandbox;
|
|
457
508
|
let result;
|
|
458
509
|
try {
|
|
510
|
+
sandbox = new CodemodeSandbox({
|
|
511
|
+
tools: sandboxTools,
|
|
512
|
+
globals: [
|
|
513
|
+
...createDiscoveryGlobals(callable, samples, options),
|
|
514
|
+
...(options.models && ctx
|
|
515
|
+
? createModelGlobals(ctx.modelRegistry, toolCallId, calls, publish, addModelUsage, addGeneratedImages)
|
|
516
|
+
: []),
|
|
517
|
+
],
|
|
518
|
+
timeoutMs: Math.max(1, Math.round(deadline - waitedMs)),
|
|
519
|
+
memoryLimitBytes: CODEMODE_MEMORY_LIMIT_BYTES,
|
|
520
|
+
wasm: loadQuickJSWasm(getQuickJSWasmPath()),
|
|
521
|
+
workerUrl: getCodemodeWorkerSpecifier(),
|
|
522
|
+
acquireWorker: () => {
|
|
523
|
+
if (!reserved)
|
|
524
|
+
throw new Error("The script already settled");
|
|
525
|
+
// From here the sandbox releases the slot when the worker actually exits.
|
|
526
|
+
reserved = false;
|
|
527
|
+
return releaseCodemodeWorker;
|
|
528
|
+
},
|
|
529
|
+
});
|
|
459
530
|
const store = ctx ? readCodemodeStore(ctx.sessionManager.getBranch()) : {};
|
|
460
531
|
result = await sandbox.execute(code, { signal, store });
|
|
461
532
|
}
|
|
462
533
|
finally {
|
|
463
|
-
await sandbox
|
|
534
|
+
await sandbox?.close();
|
|
535
|
+
if (reserved) {
|
|
536
|
+
reserved = false;
|
|
537
|
+
releaseCodemodeWorker();
|
|
538
|
+
}
|
|
464
539
|
}
|
|
465
540
|
// Calls still marked running were cut off by the script ending, a timeout, or an abort.
|
|
466
541
|
for (const call of calls) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execute.js","sourceRoot":"","sources":["../../../src/extensions/codemode/execute.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAaH,OAAO,EAGN,eAAe,EAEf,eAAe,EACf,mBAAmB,EACnB,gBAAgB,EAChB,oBAAoB,GACpB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,0BAA0B,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAGjF,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC1D,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EAAE,UAAU,EAAE,wBAAwB,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AAC9F,OAAO,EACN,kBAAkB,EAClB,yBAAyB,EAOzB,wBAAwB,EACxB,qBAAqB,GACrB,MAAM,WAAW,CAAC;AAEnB,MAAM,kBAAkB,GAAG,GAAG,CAAC;AAC/B,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAChC,4IAA4I;AAC5I,MAAM,0BAA0B,GAAG,CAAC,CAAC;AACrC;;;;GAIG;AACH,MAAM,2BAA2B,GAAG,GAAG,GAAG,IAAI,GAAG,IAAI,CAAC;AACtD,qGAAqG;AACrG,MAAM,+BAA+B,GAAG,CAAC,CAAC;AAC1C,IAAI,qBAAqB,GAAG,CAAC,CAAC;AAC9B,MAAM,WAAW,GAAwB,IAAI,GAAG,CAAY,CAAC,MAAM,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC;AAE7F,SAAS,YAAY,CAAC,IAAY,EAAE,QAAgB;IACnD,OAAO,IAAI,CAAC,MAAM,GAAG,Q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CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;QAC7D,CAAC;QACD,iBAAiB,EAAE,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,CACvC,YAAY,CAAC,iBAAiB,EAAE,YAAY,EAAE,IAAiB,EAAE,sBAAsB,EAAE,CAAC,QAAQ,EAAE,OAAO,EAAE,EAAE,CAC9G,MAAM,CAAC,QAAQ,CAAC,QAAQ,EAAE,OAAO,EAAE,EAAE,MAAM,EAAE,CAAC,CAC9C;QACF,uBAAuB,EAAE,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,CAC7C,YAAY,CACX,uBAAuB,EACvB,OAAO,EACP,IAAiB,EACjB,kBAAkB,EAClB,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE;YAC3B,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,cAAc,CAAC,QAAQ,EAAE,OAAO,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;YAC1E,kBAAkB,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC;YACnF,OAAO,MAAM,CAAC;QACf,CAAC,CACD;KACF,CAAC;IACF,OAAO,MAAM,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,OAAO,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;AACpG,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 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 CodemodeOutputItem,\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 { formatSize } from \"../../core/tools/truncate.ts\";\nimport { combineUsage } from \"../../core/usage-totals.ts\";\nimport { writeOutputFile } from \"../../utils/output-files.ts\";\nimport { Bm25Ranker, createToolSearchDocument, DEFAULT_TOOL_SEARCH_LIMIT } from \"./search.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;\n// Shared across calls and sessions. Allow one replacement while a cancelled worker is still exiting.\nconst MAX_CONCURRENT_CODEMODE_WORKERS = 2;\nlet activeCodemodeWorkers = 0;\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\n/** A JSON value from a script, read field by field: values that are not objects have no fields. */\ntype ScriptValue = { readonly [key: string]: unknown } | null | undefined;\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: { ... }, 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> } } } }';\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 (typeof context !== \"object\" || context === null || Array.isArray(context)) {\n\t\tthrow fail(`expects a context object as its second argument, got ${describeValue(context)}`);\n\t}\n\tconst { state, images, questions } = context as Record<string, unknown>;\n\tif (typeof state !== \"object\" || state === null || Array.isArray(state)) {\n\t\tthrow fail(`context.state must be an object, got ${describeValue(state)}`);\n\t}\n\tif (images !== undefined) {\n\t\tif (!Array.isArray(images)) throw fail(`context.images must be an array, got ${describeValue(images)}`);\n\t\timages.forEach((image: ScriptValue, index) => {\n\t\t\tif (image?.type !== \"image\" || typeof image.data !== \"string\" || typeof image.mimeType !== \"string\") {\n\t\t\t\tthrow fail(`context.images[${index}] must be an image block, got ${describeValue(image)}`);\n\t\t\t}\n\t\t});\n\t}\n\tif (\n\t\ttypeof questions !== \"object\" ||\n\t\tquestions === null ||\n\t\tArray.isArray(questions) ||\n\t\tObject.keys(questions).length === 0\n\t) {\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 (typeof question !== \"object\" || question === null || Array.isArray(question)) {\n\t\t\tthrow fail(`${at} must be a question object, got ${describeValue(question)}`);\n\t\t}\n\t\tconst { type, instructions, criteria } = question as Record<string, unknown>;\n\t\tif (typeof instructions !== \"string\") throw fail(`${at}.instructions must be a string`);\n\t\tif (type === \"choice\") {\n\t\t\tif (\n\t\t\t\ttypeof criteria !== \"object\" ||\n\t\t\t\tcriteria === null ||\n\t\t\t\tArray.isArray(criteria) ||\n\t\t\t\t!isStrings(Object.values(criteria))\n\t\t\t) {\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 (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 (type === \"bool\") {\n\t\t\tconst labels = criteria as ScriptValue;\n\t\t\tif (typeof labels?.true !== \"string\" || typeof labels.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(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 (typeof context !== \"object\" || context === null || Array.isArray(context)) {\n\t\tthrow fail(`expects a context object as its second argument, got ${describeValue(context)}`);\n\t}\n\tconst { input } = context as Record<string, unknown>;\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: ScriptValue, index) => {\n\t\tif (block?.type === \"text\" && typeof block.text === \"string\") return;\n\t\tif (block?.type === \"image\" && typeof block.data === \"string\" && typeof block.mimeType === \"string\") return;\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\n/**\n * Lay out the script's output so the model can tell items apart: providers join adjacent text\n * blocks with a newline or with nothing. With more than one text item (`text()` or the returned\n * value), each starts with a `==> text N/M <==` line. `console.*` lines follow all other output in\n * one `<console_output>` block.\n */\nfunction formatOutput(output: readonly CodemodeOutputItem[]): (TextContent | ImageContent)[] {\n\tconst total = output.filter((item) => item.type === \"text\" && !item.console).length;\n\tconst items: (TextContent | ImageContent)[] = [];\n\tconst consoleLines: string[] = [];\n\tlet index = 0;\n\tfor (const item of output) {\n\t\tif (item.type === \"image\") {\n\t\t\titems.push(item);\n\t\t} else if (item.console) {\n\t\t\tconsoleLines.push(item.text);\n\t\t} else {\n\t\t\tindex++;\n\t\t\titems.push({ type: \"text\", text: total > 1 ? `==> text ${index}/${total} <==\\n${item.text}` : item.text });\n\t\t}\n\t}\n\tif (consoleLines.length > 0) {\n\t\titems.push({ type: \"text\", text: `<console_output>\\n${consoleLines.join(\"\\n\")}\\n</console_output>` });\n\t}\n\treturn items;\n}\n\n/**\n * Join adjacent text items into one, each part starting on its own line. The separator check looks\n * at the last non-empty part, not the joined text: reading the end of a growing concatenation makes\n * V8 copy it on every item, which is quadratic (#10678).\n */\nfunction joinAdjacentText(items: (TextContent | ImageContent)[]): (TextContent | ImageContent)[] {\n\tconst joined: (TextContent | ImageContent)[] = [];\n\tlet parts: string[] = [];\n\tlet lastPart = \"\";\n\tconst flush = () => {\n\t\tif (parts.length > 0) joined.push({ type: \"text\", text: parts.join(\"\") });\n\t\tparts = [];\n\t\tlastPart = \"\";\n\t};\n\tfor (const item of items) {\n\t\tif (item.type !== \"text\") {\n\t\t\tflush();\n\t\t\tjoined.push(item);\n\t\t\tcontinue;\n\t\t}\n\t\tif (lastPart !== \"\" && !lastPart.endsWith(\"\\n\")) {\n\t\t\tparts.push(\"\\n\");\n\t\t\tlastPart = \"\\n\";\n\t\t}\n\t\tparts.push(item.text);\n\t\tif (item.text !== \"\") lastPart = item.text;\n\t}\n\tflush();\n\treturn joined;\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\ttry {\n\t\treturn { path: await writeOutputFile(\"pi-codemode\", \".txt\", text) };\n\t} catch (error) {\n\t\treturn { error: error instanceof Error ? error.message : String(error) };\n\t}\n}\n\n/** File extensions of the image types `image()` accepts. Must list every type the sandbox's `image()` detects. */\nconst IMAGE_EXTENSIONS: Record<string, string> = {\n\t\"image/png\": \".png\",\n\t\"image/jpeg\": \".jpg\",\n\t\"image/gif\": \".gif\",\n\t\"image/webp\": \".webp\",\n};\n\n/**\n * Save each image to a temp file and put a text item with its path before it. The model sees the\n * image but has no other way to reach its bytes: scripts cannot write files, and `write` only takes\n * text. Images shown more than once are saved once.\n */\nasync function saveImages(items: (TextContent | ImageContent)[]): Promise<(TextContent | ImageContent)[]> {\n\tconst labels = new Map<string, Promise<string>>();\n\tconst label = async ({ data, mimeType }: ImageContent): Promise<string> => {\n\t\tconst bytes = Buffer.from(data, \"base64\");\n\t\tconst kind = `${mimeType}, ${formatSize(bytes.length)}`;\n\t\tconst extension = IMAGE_EXTENSIONS[mimeType];\n\t\tif (!extension) throw new Error(`No file extension for image type ${mimeType}`);\n\t\t// A failed write (disk full, unwritable temp dir) must not discard the result of a script whose\n\t\t// tool calls already ran, so it becomes part of the label.\n\t\ttry {\n\t\t\tconst path = await writeOutputFile(\"pi-codemode\", extension, bytes);\n\t\t\treturn `[Image saved to ${path} (${kind})]`;\n\t\t} catch (error) {\n\t\t\treturn `[Image (${kind}) could not be saved: ${error instanceof Error ? error.message : String(error)}]`;\n\t\t}\n\t};\n\tconst result = await Promise.all(\n\t\titems.map(async (item): Promise<(TextContent | ImageContent)[]> => {\n\t\t\tif (item.type !== \"image\") return [item];\n\t\t\tlet pending = labels.get(item.data);\n\t\t\tif (!pending) {\n\t\t\t\tpending = label(item);\n\t\t\t\tlabels.set(item.data, pending);\n\t\t\t}\n\t\t\treturn [{ type: \"text\", text: await pending }, item];\n\t\t}),\n\t);\n\treturn result.flat();\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\t// Show the script as running before its first nested call, so the row's timer starts.\n\tpublish();\n\n\tconst callable = ctx ? getCodemodeCallableTools(ctx.tools) : [];\n\t// ALL_TOOLS entries carry the declaration.\n\tconst guidelines = options.getToolGuidelines?.();\n\tconst samples = new Map(\n\t\tcallable.map((tool) => [tool.name, renderToolSample(toCodemodeDeclaration(tool, guidelines?.get(tool.name)))]),\n\t);\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\tacquireWorker: () => {\n\t\t\tif (activeCodemodeWorkers >= MAX_CONCURRENT_CODEMODE_WORKERS) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Codemode worker limit reached (${MAX_CONCURRENT_CODEMODE_WORKERS} workers are still running or shutting down). Retry after they exit.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tactiveCodemodeWorkers++;\n\t\t\treturn () => {\n\t\t\t\tactiveCodemodeWorkers--;\n\t\t\t};\n\t\t},\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 scriptOutput = [...result.output];\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) scriptOutput.push({ type: \"text\", text: valueText(result.value) });\n\t}\n\tconst items = formatOutput(scriptOutput);\n\tif (!result.ok) items.push({ type: \"text\", text: `Script error:\\n${formatError(result, calls)}` });\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(\n\t\tjoinAdjacentText(items),\n\t\tsourceOptions.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS,\n\t);\n\t// After truncation, which joins the text items and moves images after them, so each path stays\n\t// next to its image and is never cut.\n\tconst output = joinAdjacentText(await saveImages(truncated.items));\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 }, ...output],\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 or one of its aliases, as written or as the same\n * script identifier (`dev-radius` and `dev_radius` are both `dev_radius`).\n */\nfunction isNamespaceName(namespace: ToolNamespace, query: string): boolean {\n\tconst queryId = toCodemodeIdentifier(query);\n\treturn [namespace.name, ...(namespace.aliases ?? [])].some(\n\t\t(name) => name === query || toCodemodeIdentifier(name) === queryId,\n\t);\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, 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)) 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\tconst given = model as ScriptValue;\n\t\tif (typeof given?.provider !== \"string\" || typeof given.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 = given.provider;\n\t\tconst id = given.id;\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
|
+
{"version":3,"file":"execute.js","sourceRoot":"","sources":["../../../src/extensions/codemode/execute.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAaH,OAAO,EAGN,eAAe,EAEf,eA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C,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;AACpG,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 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 CodemodeOutputItem,\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 { formatSize } from \"../../core/tools/truncate.ts\";\nimport { combineUsage } from \"../../core/usage-totals.ts\";\nimport { writeOutputFile } from \"../../utils/output-files.ts\";\nimport { Bm25Ranker, createToolSearchDocument, DEFAULT_TOOL_SEARCH_LIMIT } from \"./search.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;\n// Shared across calls and sessions. Allow one replacement while a cancelled worker is still exiting.\nconst DEFAULT_MAX_CODEMODE_WORKERS = 2;\n\n/** `PI_CODEMODE_MAX_WORKERS` if it is a positive integer. Read per call so SDK hosts can set it at runtime. */\nfunction maxCodemodeWorkers(): number {\n\tconst value = Number(process.env.PI_CODEMODE_MAX_WORKERS);\n\treturn Number.isInteger(value) && value > 0 ? value : DEFAULT_MAX_CODEMODE_WORKERS;\n}\n/**\n * How long a script waits for a free worker before failing. Bounds the wait when every worker is\n * held by a script that waits on another script, for example an in-process subagent that uses codemode.\n */\nconst CODEMODE_WORKER_WAIT_MS = 60_000;\nlet activeCodemodeWorkers = 0;\n/** Scripts waiting for a worker, in arrival order. */\nconst codemodeWorkerWaiters: (() => void)[] = [];\n\n/**\n * Reserve one worker slot, waiting in arrival order while all are taken. Resolves with why it could\n * not reserve one: the signal aborted, or `timeoutMs` passed.\n */\nfunction reserveCodemodeWorker(\n\tsignal: AbortSignal | undefined,\n\ttimeoutMs: number,\n): Promise<\"reserved\" | \"aborted\" | \"timeout\"> {\n\tif (signal?.aborted) return Promise.resolve(\"aborted\");\n\treturn new Promise((resolve) => {\n\t\tconst settle = (outcome: \"reserved\" | \"aborted\" | \"timeout\") => {\n\t\t\tclearTimeout(timer);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\tconst index = codemodeWorkerWaiters.indexOf(grant);\n\t\t\tif (index >= 0) codemodeWorkerWaiters.splice(index, 1);\n\t\t\tresolve(outcome);\n\t\t};\n\t\tconst grant = () => settle(\"reserved\");\n\t\tconst onAbort = () => settle(\"aborted\");\n\t\tconst timer = setTimeout(() => settle(\"timeout\"), timeoutMs);\n\t\tcodemodeWorkerWaiters.push(grant);\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\tadmitCodemodeWorkers();\n\t});\n}\n\n/** Give free slots to waiting scripts in arrival order. */\nfunction admitCodemodeWorkers(): void {\n\twhile (codemodeWorkerWaiters.length > 0 && activeCodemodeWorkers < maxCodemodeWorkers()) {\n\t\tactiveCodemodeWorkers++;\n\t\tcodemodeWorkerWaiters.shift()?.();\n\t}\n}\n\nfunction releaseCodemodeWorker(): void {\n\tactiveCodemodeWorkers--;\n\tadmitCodemodeWorkers();\n}\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\n/** A JSON value from a script, read field by field: values that are not objects have no fields. */\ntype ScriptValue = { readonly [key: string]: unknown } | null | undefined;\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: { ... }, 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> } } } }';\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 (typeof context !== \"object\" || context === null || Array.isArray(context)) {\n\t\tthrow fail(`expects a context object as its second argument, got ${describeValue(context)}`);\n\t}\n\tconst { state, images, questions } = context as Record<string, unknown>;\n\tif (typeof state !== \"object\" || state === null || Array.isArray(state)) {\n\t\tthrow fail(`context.state must be an object, got ${describeValue(state)}`);\n\t}\n\tif (images !== undefined) {\n\t\tif (!Array.isArray(images)) throw fail(`context.images must be an array, got ${describeValue(images)}`);\n\t\timages.forEach((image: ScriptValue, index) => {\n\t\t\tif (image?.type !== \"image\" || typeof image.data !== \"string\" || typeof image.mimeType !== \"string\") {\n\t\t\t\tthrow fail(`context.images[${index}] must be an image block, got ${describeValue(image)}`);\n\t\t\t}\n\t\t});\n\t}\n\tif (\n\t\ttypeof questions !== \"object\" ||\n\t\tquestions === null ||\n\t\tArray.isArray(questions) ||\n\t\tObject.keys(questions).length === 0\n\t) {\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 (typeof question !== \"object\" || question === null || Array.isArray(question)) {\n\t\t\tthrow fail(`${at} must be a question object, got ${describeValue(question)}`);\n\t\t}\n\t\tconst { type, instructions, criteria } = question as Record<string, unknown>;\n\t\tif (typeof instructions !== \"string\") throw fail(`${at}.instructions must be a string`);\n\t\tif (type === \"choice\") {\n\t\t\tif (\n\t\t\t\ttypeof criteria !== \"object\" ||\n\t\t\t\tcriteria === null ||\n\t\t\t\tArray.isArray(criteria) ||\n\t\t\t\t!isStrings(Object.values(criteria))\n\t\t\t) {\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 (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 (type === \"bool\") {\n\t\t\tconst labels = criteria as ScriptValue;\n\t\t\tif (typeof labels?.true !== \"string\" || typeof labels.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(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 (typeof context !== \"object\" || context === null || Array.isArray(context)) {\n\t\tthrow fail(`expects a context object as its second argument, got ${describeValue(context)}`);\n\t}\n\tconst { input } = context as Record<string, unknown>;\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: ScriptValue, index) => {\n\t\tif (block?.type === \"text\" && typeof block.text === \"string\") return;\n\t\tif (block?.type === \"image\" && typeof block.data === \"string\" && typeof block.mimeType === \"string\") return;\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\n/**\n * Lay out the script's output so the model can tell items apart: providers join adjacent text\n * blocks with a newline or with nothing. With more than one text item (`text()` or the returned\n * value), each starts with a `==> text N/M <==` line. `console.*` lines follow all other output in\n * one `<console_output>` block.\n */\nfunction formatOutput(output: readonly CodemodeOutputItem[]): (TextContent | ImageContent)[] {\n\tconst total = output.filter((item) => item.type === \"text\" && !item.console).length;\n\tconst items: (TextContent | ImageContent)[] = [];\n\tconst consoleLines: string[] = [];\n\tlet index = 0;\n\tfor (const item of output) {\n\t\tif (item.type === \"image\") {\n\t\t\titems.push(item);\n\t\t} else if (item.console) {\n\t\t\tconsoleLines.push(item.text);\n\t\t} else {\n\t\t\tindex++;\n\t\t\titems.push({ type: \"text\", text: total > 1 ? `==> text ${index}/${total} <==\\n${item.text}` : item.text });\n\t\t}\n\t}\n\tif (consoleLines.length > 0) {\n\t\titems.push({ type: \"text\", text: `<console_output>\\n${consoleLines.join(\"\\n\")}\\n</console_output>` });\n\t}\n\treturn items;\n}\n\n/**\n * Join adjacent text items into one, each part starting on its own line. The separator check looks\n * at the last non-empty part, not the joined text: reading the end of a growing concatenation makes\n * V8 copy it on every item, which is quadratic (#10678).\n */\nfunction joinAdjacentText(items: (TextContent | ImageContent)[]): (TextContent | ImageContent)[] {\n\tconst joined: (TextContent | ImageContent)[] = [];\n\tlet parts: string[] = [];\n\tlet lastPart = \"\";\n\tconst flush = () => {\n\t\tif (parts.length > 0) joined.push({ type: \"text\", text: parts.join(\"\") });\n\t\tparts = [];\n\t\tlastPart = \"\";\n\t};\n\tfor (const item of items) {\n\t\tif (item.type !== \"text\") {\n\t\t\tflush();\n\t\t\tjoined.push(item);\n\t\t\tcontinue;\n\t\t}\n\t\tif (lastPart !== \"\" && !lastPart.endsWith(\"\\n\")) {\n\t\t\tparts.push(\"\\n\");\n\t\t\tlastPart = \"\\n\";\n\t\t}\n\t\tparts.push(item.text);\n\t\tif (item.text !== \"\") lastPart = item.text;\n\t}\n\tflush();\n\treturn joined;\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\ttry {\n\t\treturn { path: await writeOutputFile(\"pi-codemode\", \".txt\", text) };\n\t} catch (error) {\n\t\treturn { error: error instanceof Error ? error.message : String(error) };\n\t}\n}\n\n/** File extensions of the image types `image()` accepts. Must list every type the sandbox's `image()` detects. */\nconst IMAGE_EXTENSIONS: Record<string, string> = {\n\t\"image/png\": \".png\",\n\t\"image/jpeg\": \".jpg\",\n\t\"image/gif\": \".gif\",\n\t\"image/webp\": \".webp\",\n};\n\n/**\n * Save each image to a temp file and put a text item with its path before it. The model sees the\n * image but has no other way to reach its bytes: scripts cannot write files, and `write` only takes\n * text. Images shown more than once are saved once.\n */\nasync function saveImages(items: (TextContent | ImageContent)[]): Promise<(TextContent | ImageContent)[]> {\n\tconst labels = new Map<string, Promise<string>>();\n\tconst label = async ({ data, mimeType }: ImageContent): Promise<string> => {\n\t\tconst bytes = Buffer.from(data, \"base64\");\n\t\tconst kind = `${mimeType}, ${formatSize(bytes.length)}`;\n\t\tconst extension = IMAGE_EXTENSIONS[mimeType];\n\t\tif (!extension) throw new Error(`No file extension for image type ${mimeType}`);\n\t\t// A failed write (disk full, unwritable temp dir) must not discard the result of a script whose\n\t\t// tool calls already ran, so it becomes part of the label.\n\t\ttry {\n\t\t\tconst path = await writeOutputFile(\"pi-codemode\", extension, bytes);\n\t\t\treturn `[Image saved to ${path} (${kind})]`;\n\t\t} catch (error) {\n\t\t\treturn `[Image (${kind}) could not be saved: ${error instanceof Error ? error.message : String(error)}]`;\n\t\t}\n\t};\n\tconst result = await Promise.all(\n\t\titems.map(async (item): Promise<(TextContent | ImageContent)[]> => {\n\t\t\tif (item.type !== \"image\") return [item];\n\t\t\tlet pending = labels.get(item.data);\n\t\t\tif (!pending) {\n\t\t\t\tpending = label(item);\n\t\t\t\tlabels.set(item.data, pending);\n\t\t\t}\n\t\t\treturn [{ type: \"text\", text: await pending }, item];\n\t\t}),\n\t);\n\treturn result.flat();\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\t// Show the script as running before its first nested call, so the row's timer starts.\n\tpublish();\n\n\tconst callable = ctx ? getCodemodeCallableTools(ctx.tools) : [];\n\t// ALL_TOOLS entries carry the declaration.\n\tconst guidelines = options.getToolGuidelines?.();\n\tconst samples = new Map(\n\t\tcallable.map((tool) => [tool.name, renderToolSample(toCodemodeDeclaration(tool, guidelines?.get(tool.name)))]),\n\t);\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\t// The wait for a worker counts toward the script's deadline.\n\tconst deadline = sourceOptions.timeoutMs ?? Number.POSITIVE_INFINITY;\n\tconst waitStartedAt = performance.now();\n\tconst admission = await reserveCodemodeWorker(signal, Math.min(deadline, CODEMODE_WORKER_WAIT_MS));\n\tconst waitedMs = performance.now() - waitStartedAt;\n\tif (admission !== \"reserved\") {\n\t\tconst waited = ((performance.now() - startedAt) / 1000).toFixed(1);\n\t\tconst reason = signal?.reason;\n\t\tconst error =\n\t\t\tadmission === \"aborted\"\n\t\t\t\t? `Script aborted: ${reason instanceof Error ? reason.message : \"Execution aborted\"}`\n\t\t\t\t: deadline <= CODEMODE_WORKER_WAIT_MS\n\t\t\t\t\t? `Script timed out: Execution timed out after ${deadline} ms while waiting for a free codemode worker`\n\t\t\t\t\t: `No codemode worker became free within ${CODEMODE_WORKER_WAIT_MS / 1000} seconds. All ${maxCodemodeWorkers()} workers, shared by every session in this process, are held by other scripts. Retry after they finish.`;\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{ type: \"text\", text: `Script failed\\nWall time ${waited} seconds\\nOutput:\\n` },\n\t\t\t\t{ type: \"text\", text: `Script error:\\n${error}\\n\\nThe script did not start.` },\n\t\t\t],\n\t\t\tdetails: snapshot(),\n\t\t\tisError: true,\n\t\t};\n\t}\n\t// The reservation covers the one worker this script starts. A launch that resumes after the result\n\t// settled finds it released and starts no worker.\n\tlet reserved = true;\n\n\tlet sandbox: CodemodeSandbox | undefined;\n\tlet result: CodemodeResult;\n\ttry {\n\t\tsandbox = new CodemodeSandbox({\n\t\t\ttools: sandboxTools,\n\t\t\tglobals: [\n\t\t\t\t...createDiscoveryGlobals(callable, samples, options),\n\t\t\t\t...(options.models && ctx\n\t\t\t\t\t? createModelGlobals(ctx.modelRegistry, toolCallId, calls, publish, addModelUsage, addGeneratedImages)\n\t\t\t\t\t: []),\n\t\t\t],\n\t\t\ttimeoutMs: Math.max(1, Math.round(deadline - waitedMs)),\n\t\t\tmemoryLimitBytes: CODEMODE_MEMORY_LIMIT_BYTES,\n\t\t\twasm: loadQuickJSWasm(getQuickJSWasmPath()),\n\t\t\tworkerUrl: getCodemodeWorkerSpecifier(),\n\t\t\tacquireWorker: () => {\n\t\t\t\tif (!reserved) throw new Error(\"The script already settled\");\n\t\t\t\t// From here the sandbox releases the slot when the worker actually exits.\n\t\t\t\treserved = false;\n\t\t\t\treturn releaseCodemodeWorker;\n\t\t\t},\n\t\t});\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\tif (reserved) {\n\t\t\treserved = false;\n\t\t\treleaseCodemodeWorker();\n\t\t}\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 scriptOutput = [...result.output];\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) scriptOutput.push({ type: \"text\", text: valueText(result.value) });\n\t}\n\tconst items = formatOutput(scriptOutput);\n\tif (!result.ok) items.push({ type: \"text\", text: `Script error:\\n${formatError(result, calls)}` });\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(\n\t\tjoinAdjacentText(items),\n\t\tsourceOptions.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS,\n\t);\n\t// After truncation, which joins the text items and moves images after them, so each path stays\n\t// next to its image and is never cut.\n\tconst output = joinAdjacentText(await saveImages(truncated.items));\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 }, ...output],\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 or one of its aliases, as written or as the same\n * script identifier (`dev-radius` and `dev_radius` are both `dev_radius`).\n */\nfunction isNamespaceName(namespace: ToolNamespace, query: string): boolean {\n\tconst queryId = toCodemodeIdentifier(query);\n\treturn [namespace.name, ...(namespace.aliases ?? [])].some(\n\t\t(name) => name === query || toCodemodeIdentifier(name) === queryId,\n\t);\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, 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)) 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\tconst given = model as ScriptValue;\n\t\tif (typeof given?.provider !== \"string\" || typeof given.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 = given.provider;\n\t\tconst id = given.id;\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"]}
|