pi-namespace-patch 1.2.0-namespace.2 → 1.4.0-namespace.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.
Files changed (233) hide show
  1. package/CHANGELOG.md +102 -0
  2. package/README.md +5 -5
  3. package/dist/bundle/chunks/anthropic-messages-5FHV3XZG.js +6 -0
  4. package/dist/bundle/chunks/azure-openai-responses-KLTRI2FU.js +2 -0
  5. package/dist/bundle/chunks/bedrock-converse-stream.js +12 -9
  6. package/dist/bundle/chunks/{chunk-TRDNDS6A.js → chunk-3V45WARH.js} +6 -3
  7. package/dist/bundle/chunks/chunk-4GGCU36O.js +11 -0
  8. package/dist/bundle/chunks/{chunk-S3GGRYIO.js → chunk-5AGIVGSV.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-F5ZABL6Z.js → chunk-7CBJINYJ.js} +2 -2
  10. package/dist/bundle/chunks/{chunk-DRQDKNXA.js → chunk-7DDKXS2Q.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-CQ3XTLTY.js → chunk-A45IWOC6.js} +4 -4
  12. package/dist/bundle/chunks/{chunk-WJUNYZC5.js → chunk-BSS6T6KQ.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-H3QXYIF7.js → chunk-CF5GWZHW.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-DOST5PQW.js → chunk-EGE5YVUM.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-C2AEIDJZ.js → chunk-FB6L7ZMV.js} +1 -1
  16. package/dist/bundle/chunks/chunk-H76KZMOI.js +2 -0
  17. package/dist/bundle/chunks/{chunk-GDR5JFDJ.js → chunk-INGZIYBC.js} +2 -2
  18. package/dist/bundle/chunks/{chunk-D7PHKNBM.js → chunk-IUWY2KTF.js} +11 -11
  19. package/dist/bundle/chunks/{chunk-4L3WN2XY.js → chunk-JXWJOIH4.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-6CYCI3EJ.js → chunk-LVVZS2NO.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-5GTPJSRI.js → chunk-N43LRJ4N.js} +1 -1
  22. package/dist/bundle/chunks/chunk-NFLURVK3.js +2 -0
  23. package/dist/bundle/chunks/chunk-QSDU2SDK.js +16 -0
  24. package/dist/bundle/chunks/chunk-RISAW7OQ.js +9 -0
  25. package/dist/bundle/chunks/{chunk-AKJ3ZOR3.js → chunk-RWO6Q3KK.js} +1 -1
  26. package/dist/bundle/chunks/{chunk-6MWTY2OB.js → chunk-T726RZZU.js} +10 -9
  27. package/dist/bundle/chunks/{chunk-ZBURYEWF.js → chunk-TMTOQ7H7.js} +1 -1
  28. package/dist/bundle/chunks/chunk-TRERZKRC.js +2 -0
  29. package/dist/bundle/chunks/{chunk-22CYIUS4.js → chunk-UKVNB6C4.js} +1 -1
  30. package/dist/bundle/chunks/chunk-Z6I32PHA.js +2 -0
  31. package/dist/bundle/chunks/{chunk-H7S5Z6OB.js → chunk-ZEIZZEGK.js} +42 -40
  32. package/dist/bundle/chunks/{cli-SWM4FQ6V.js → cli-MIMUTM5L.js} +1 -1
  33. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-7J6REGDV.js +2 -0
  34. package/dist/bundle/chunks/{easter-egg-3d-OX6RUCIS.js → easter-egg-3d-RMLF7AC4.js} +1 -1
  35. package/dist/bundle/chunks/{execute-3CFUPDLS.js → execute-MT7QEDSI.js} +9 -3
  36. package/dist/bundle/chunks/github-copilot.js +1 -1
  37. package/dist/bundle/chunks/google-generative-ai-VPNFZDHO.js +2 -0
  38. package/dist/bundle/chunks/google-vertex-ZFM23MQ4.js +2 -0
  39. package/dist/bundle/chunks/https-proxy-agent-LVOO5TPL.js +13 -0
  40. package/dist/bundle/chunks/{jiti-loader-C3NU2SDH.js → jiti-loader-GL4HJFAD.js} +1 -1
  41. package/dist/bundle/chunks/{jiti-static-loader-E6ANQD5T.js → jiti-static-loader-2RCDI6B4.js} +1 -1
  42. package/dist/bundle/chunks/{lib-TEDK3E5I.js → lib-4AVRLBHM.js} +1 -1
  43. package/dist/bundle/chunks/{llama-cpp-classify-FYN623RH.js → llama-cpp-classify-U4EH6TAM.js} +2 -2
  44. package/dist/bundle/chunks/mistral-conversations-WCAJTBXO.js +5 -0
  45. package/dist/bundle/chunks/{multipart-parser-SQ6GDJL7.js → multipart-parser-FMGQ7342.js} +1 -1
  46. package/dist/bundle/chunks/{node-TWVVAGPO.js → node-AUOGOBCN.js} +1 -1
  47. package/dist/bundle/chunks/{node-N5BSDOA5.js → node-KCMANYC2.js} +1 -1
  48. package/dist/bundle/chunks/openai-codex-responses-JQR3IK2C.js +10 -0
  49. package/dist/bundle/chunks/openai-completions-27RKPL37.js +7 -0
  50. package/dist/bundle/chunks/{openai-decisions-WVPMQ4JD.js → openai-decisions-MJYPUCLX.js} +1 -1
  51. package/dist/bundle/chunks/openai-responses-I2TBW7OL.js +4 -0
  52. package/dist/bundle/chunks/openrouter-images-WBAVKHHY.js +2 -0
  53. package/dist/bundle/chunks/pi-messages-S7RKCD5K.js +8 -0
  54. package/dist/bundle/chunks/{runtime-366HE7CW.js → runtime-GJOZRI5I.js} +1 -1
  55. package/dist/bundle/chunks/{src-UK77SYZE.js → src-QKGKDFSU.js} +1 -1
  56. package/dist/bundle/chunks/typesafe-system-one-4C7ULOVP.js +2 -0
  57. package/dist/bundle/chunks/virtual-modules-6XWNE4NR.js +2 -0
  58. package/dist/bundle/cli-runtime.js +1 -1
  59. package/dist/bundle/index.js +1 -1
  60. package/dist/bundle/rpc-entry.js +1 -1
  61. package/dist/cli/credential-print.d.ts.map +1 -1
  62. package/dist/cli/credential-print.js +4 -4
  63. package/dist/cli/credential-print.js.map +1 -1
  64. package/dist/core/agent-session.d.ts +9 -3
  65. package/dist/core/agent-session.d.ts.map +1 -1
  66. package/dist/core/agent-session.js +45 -15
  67. package/dist/core/agent-session.js.map +1 -1
  68. package/dist/core/client-identity.d.ts +8 -0
  69. package/dist/core/client-identity.d.ts.map +1 -0
  70. package/dist/core/client-identity.js +15 -0
  71. package/dist/core/client-identity.js.map +1 -0
  72. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  73. package/dist/core/compaction/branch-summarization.js +1 -2
  74. package/dist/core/compaction/branch-summarization.js.map +1 -1
  75. package/dist/core/compaction/compaction.d.ts +2 -2
  76. package/dist/core/compaction/compaction.d.ts.map +1 -1
  77. package/dist/core/compaction/compaction.js +20 -15
  78. package/dist/core/compaction/compaction.js.map +1 -1
  79. package/dist/core/export-html/index.d.ts.map +1 -1
  80. package/dist/core/export-html/index.js +2 -0
  81. package/dist/core/export-html/index.js.map +1 -1
  82. package/dist/core/export-html/template.html +1 -0
  83. package/dist/core/export-html/template.js +23 -17
  84. package/dist/core/export-html/vendor/marked-cjk-friendly.min.js +6 -0
  85. package/dist/core/export-html/vendor/marked.min.js +30 -29
  86. package/dist/core/extensions/loader.d.ts.map +1 -1
  87. package/dist/core/extensions/loader.js +3 -0
  88. package/dist/core/extensions/loader.js.map +1 -1
  89. package/dist/core/extensions/virtual-modules.d.ts.map +1 -1
  90. package/dist/core/extensions/virtual-modules.js +3 -0
  91. package/dist/core/extensions/virtual-modules.js.map +1 -1
  92. package/dist/core/model-config.d.ts +939 -8
  93. package/dist/core/model-config.d.ts.map +1 -1
  94. package/dist/core/model-config.js +48 -24
  95. package/dist/core/model-config.js.map +1 -1
  96. package/dist/core/model-resolver.d.ts +56 -43
  97. package/dist/core/model-resolver.d.ts.map +1 -1
  98. package/dist/core/model-resolver.js +253 -358
  99. package/dist/core/model-resolver.js.map +1 -1
  100. package/dist/core/model-runtime.d.ts.map +1 -1
  101. package/dist/core/model-runtime.js +6 -3
  102. package/dist/core/model-runtime.js.map +1 -1
  103. package/dist/core/prompt-templates.d.ts.map +1 -1
  104. package/dist/core/prompt-templates.js +7 -2
  105. package/dist/core/prompt-templates.js.map +1 -1
  106. package/dist/core/provider-composer.d.ts +2 -1
  107. package/dist/core/provider-composer.d.ts.map +1 -1
  108. package/dist/core/provider-composer.js +7 -3
  109. package/dist/core/provider-composer.js.map +1 -1
  110. package/dist/core/sdk.d.ts.map +1 -1
  111. package/dist/core/sdk.js +8 -9
  112. package/dist/core/sdk.js.map +1 -1
  113. package/dist/core/settings-defaults.d.ts +1 -0
  114. package/dist/core/settings-defaults.d.ts.map +1 -1
  115. package/dist/core/settings-defaults.js +1 -0
  116. package/dist/core/settings-defaults.js.map +1 -1
  117. package/dist/core/settings-manager.d.ts +4 -2
  118. package/dist/core/settings-manager.d.ts.map +1 -1
  119. package/dist/core/settings-manager.js +11 -0
  120. package/dist/core/settings-manager.js.map +1 -1
  121. package/dist/core/settings-schema.d.ts +2 -0
  122. package/dist/core/settings-schema.d.ts.map +1 -1
  123. package/dist/core/settings-schema.js +4 -0
  124. package/dist/core/settings-schema.js.map +1 -1
  125. package/dist/core/slash-commands.js +1 -1
  126. package/dist/core/slash-commands.js.map +1 -1
  127. package/dist/core/tools/grep.d.ts.map +1 -1
  128. package/dist/core/tools/grep.js +3 -1
  129. package/dist/core/tools/grep.js.map +1 -1
  130. package/dist/core/tools/render-utils.d.ts +2 -0
  131. package/dist/core/tools/render-utils.d.ts.map +1 -1
  132. package/dist/core/tools/render-utils.js +21 -0
  133. package/dist/core/tools/render-utils.js.map +1 -1
  134. package/dist/core/tools/renderers/read.d.ts.map +1 -1
  135. package/dist/core/tools/renderers/read.js +7 -11
  136. package/dist/core/tools/renderers/read.js.map +1 -1
  137. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  138. package/dist/extensions/codemode/execute.js +101 -14
  139. package/dist/extensions/codemode/execute.js.map +1 -1
  140. package/dist/extensions/mcp/config.d.ts.map +1 -1
  141. package/dist/extensions/mcp/config.js +3 -2
  142. package/dist/extensions/mcp/config.js.map +1 -1
  143. package/dist/index.d.ts +1 -0
  144. package/dist/index.d.ts.map +1 -1
  145. package/dist/index.js +1 -0
  146. package/dist/index.js.map +1 -1
  147. package/dist/main.d.ts.map +1 -1
  148. package/dist/main.js +1 -0
  149. package/dist/main.js.map +1 -1
  150. package/dist/modes/interactive/components/settings-selector.d.ts +3 -1
  151. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  152. package/dist/modes/interactive/components/settings-selector.js +10 -0
  153. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  154. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  155. package/dist/modes/interactive/components/tree-selector.js +2 -9
  156. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  157. package/dist/modes/interactive/interactive-mode.d.ts +11 -15
  158. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  159. package/dist/modes/interactive/interactive-mode.js +76 -111
  160. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  161. package/dist/modes/interactive/session-share.d.ts.map +1 -1
  162. package/dist/modes/interactive/session-share.js +9 -2
  163. package/dist/modes/interactive/session-share.js.map +1 -1
  164. package/dist/package-manager-cli.d.ts.map +1 -1
  165. package/dist/package-manager-cli.js +2 -1
  166. package/dist/package-manager-cli.js.map +1 -1
  167. package/dist/utils/clipboard-command.d.ts.map +1 -1
  168. package/dist/utils/clipboard-command.js +3 -0
  169. package/dist/utils/clipboard-command.js.map +1 -1
  170. package/dist/utils/pi-user-agent.d.ts +1 -0
  171. package/dist/utils/pi-user-agent.d.ts.map +1 -1
  172. package/dist/utils/pi-user-agent.js +3 -2
  173. package/dist/utils/pi-user-agent.js.map +1 -1
  174. package/dist/utils/shell.d.ts.map +1 -1
  175. package/dist/utils/shell.js +45 -13
  176. package/dist/utils/shell.js.map +1 -1
  177. package/dist/utils/tools-manager.d.ts.map +1 -1
  178. package/dist/utils/tools-manager.js +4 -3
  179. package/dist/utils/tools-manager.js.map +1 -1
  180. package/docs/cli.md +3 -3
  181. package/docs/codemode.md +3 -1
  182. package/docs/compaction.md +3 -3
  183. package/docs/custom-provider.md +53 -1
  184. package/docs/docs.json +8 -0
  185. package/docs/environment-variables.md +1 -0
  186. package/docs/extensions.md +133 -10
  187. package/docs/llama-cpp.md +1 -1
  188. package/docs/models-configuration.md +196 -0
  189. package/docs/models.md +21 -5
  190. package/docs/nvidia-rtx-llama-cpp.md +96 -0
  191. package/docs/sessions.md +1 -1
  192. package/docs/settings.md +2 -1
  193. package/docs/tui.md +70 -0
  194. package/docs/usage.md +1 -1
  195. package/docs/windows.md +16 -2
  196. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  197. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  198. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  199. package/examples/extensions/gondolin/package-lock.json +2 -2
  200. package/examples/extensions/gondolin/package.json +1 -1
  201. package/examples/extensions/minimal-mode.ts +4 -5
  202. package/examples/extensions/sandbox/package-lock.json +2 -2
  203. package/examples/extensions/sandbox/package.json +1 -1
  204. package/examples/extensions/subagent/index.ts +4 -6
  205. package/examples/extensions/with-deps/package-lock.json +2 -2
  206. package/examples/extensions/with-deps/package.json +1 -1
  207. package/package.json +7 -6
  208. package/schemas/models.schema.json +88 -34
  209. package/schemas/settings.schema.json +18 -0
  210. package/dist/bundle/chunks/anthropic-messages-Q7SXESRX.js +0 -6
  211. package/dist/bundle/chunks/azure-openai-responses-LM52U7CK.js +0 -2
  212. package/dist/bundle/chunks/chunk-3ZATHNCK.js +0 -9
  213. package/dist/bundle/chunks/chunk-HACVPRBJ.js +0 -11
  214. package/dist/bundle/chunks/chunk-ITZNWD4K.js +0 -2
  215. package/dist/bundle/chunks/chunk-TN4NLWHF.js +0 -11
  216. package/dist/bundle/chunks/chunk-WBQBCFWG.js +0 -2
  217. package/dist/bundle/chunks/chunk-XIX7LUWI.js +0 -2
  218. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-UTBL2KOF.js +0 -2
  219. package/dist/bundle/chunks/google-generative-ai-DXKP72HC.js +0 -2
  220. package/dist/bundle/chunks/google-vertex-W6SIDOVV.js +0 -2
  221. package/dist/bundle/chunks/https-proxy-agent-2VXB7436.js +0 -13
  222. package/dist/bundle/chunks/mistral-conversations-GBMHTSYF.js +0 -5
  223. package/dist/bundle/chunks/openai-codex-responses-RN6B5UPP.js +0 -10
  224. package/dist/bundle/chunks/openai-completions-QW2B4SML.js +0 -7
  225. package/dist/bundle/chunks/openai-responses-KDJUSIU7.js +0 -3
  226. package/dist/bundle/chunks/openrouter-images-DUPG5DZO.js +0 -2
  227. package/dist/bundle/chunks/pi-messages-YHKPQIHC.js +0 -8
  228. package/dist/bundle/chunks/typesafe-system-one-ZSK3RN4B.js +0 -2
  229. package/dist/bundle/chunks/virtual-modules-KHZAOPVZ.js +0 -2
  230. package/dist/core/provider-attribution.d.ts +0 -4
  231. package/dist/core/provider-attribution.d.ts.map +0 -1
  232. package/dist/core/provider-attribution.js +0 -72
  233. package/dist/core/provider-attribution.js.map +0 -1
@@ -19,6 +19,56 @@ const MAX_CONCURRENT_MODEL_CALLS = 4;
19
19
  * `InternalError: out of memory` inside the script.
20
20
  */
21
21
  const CODEMODE_MEMORY_LIMIT_BYTES = 256 * 1024 * 1024;
22
+ // Shared across calls and sessions. Allow one replacement while a cancelled worker is still exiting.
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;
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
+ }
22
72
  const MODEL_TYPES = new Set(["chat", "image", "classifier"]);
23
73
  function truncateText(text, maxChars) {
24
74
  return text.length > maxChars ? `${text.slice(0, maxChars - 3)}...` : text;
@@ -429,26 +479,63 @@ export async function executeCodemode(toolCallId, input, signal, onUpdate, ctx,
429
479
  return toScriptValue(tool, outcome);
430
480
  },
431
481
  }));
432
- const sandbox = new CodemodeSandbox({
433
- tools: sandboxTools,
434
- globals: [
435
- ...createDiscoveryGlobals(callable, samples, options),
436
- ...(options.models && ctx
437
- ? createModelGlobals(ctx.modelRegistry, toolCallId, calls, publish, addModelUsage, addGeneratedImages)
438
- : []),
439
- ],
440
- timeoutMs: sourceOptions.timeoutMs ?? Number.POSITIVE_INFINITY,
441
- memoryLimitBytes: CODEMODE_MEMORY_LIMIT_BYTES,
442
- wasm: loadQuickJSWasm(getQuickJSWasmPath()),
443
- workerUrl: getCodemodeWorkerSpecifier(),
444
- });
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;
445
508
  let result;
446
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
+ });
447
530
  const store = ctx ? readCodemodeStore(ctx.sessionManager.getBranch()) : {};
448
531
  result = await sandbox.execute(code, { signal, store });
449
532
  }
450
533
  finally {
451
- await sandbox.close();
534
+ await sandbox?.close();
535
+ if (reserved) {
536
+ reserved = false;
537
+ releaseCodemodeWorker();
538
+ }
452
539
  }
453
540
  // Calls still marked running were cut off by the script ending, a timeout, or an abort.
454
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,wBAAwB,CAAC;AACzG,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,MAAM,WAAW,GAAwB,IAAI,GAAG,CAAY,CAAC,MAAM,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAA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AE,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 \"../tool-search/tool.ts\";\nimport {\n\tCODEMODE_DOCS_PATH,\n\tCODEMODE_STORE_ENTRY_TYPE,\n\ttype CodemodeModelRuntime,\n\ttype CodemodeNestedCall,\n\ttype CodemodeStoreEntryData,\n\ttype CodemodeToolDetails,\n\ttype CodemodeToolInput,\n\ttype CodemodeToolOptions,\n\tgetCodemodeCallableTools,\n\ttoCodemodeDeclaration,\n} from \"./tool.ts\";\n\nconst ARGS_PREVIEW_CHARS = 200;\nconst ERROR_PREVIEW_CHARS = 500;\n/** `models.classify()` and `models.generateImages()` calls one script may have in flight; `Promise.all` over many items queues the rest. */\nconst MAX_CONCURRENT_MODEL_CALLS = 4;\n/**\n * Heap limit for the QuickJS VM. The worker shares pi's process, so without a limit a runaway\n * script can grow to wasm32's 4 GiB and take the session down. Overruns throw\n * `InternalError: out of memory` inside the script.\n */\nconst CODEMODE_MEMORY_LIMIT_BYTES = 256 * 1024 * 1024;\nconst MODEL_TYPES: ReadonlySet<string> = new Set<ModelType>([\"chat\", \"image\", \"classifier\"]);\n\nfunction truncateText(text: string, maxChars: number): string {\n\treturn text.length > maxChars ? `${text.slice(0, maxChars - 3)}...` : text;\n}\n\nfunction previewArgs(args: unknown): string {\n\tif (args === undefined) return \"\";\n\ttry {\n\t\treturn truncateText(JSON.stringify(args) ?? \"\", ARGS_PREVIEW_CHARS);\n\t} catch {\n\t\treturn \"\";\n\t}\n}\n\nfunction textOf(result: AgentToolResult<unknown>): string {\n\treturn (result.content ?? [])\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n}\n\nfunction toModelType(value: unknown): ModelType {\n\tif (typeof value === \"string\" && MODEL_TYPES.has(value)) return value as ModelType;\n\tthrow new Error(`Unknown model type ${JSON.stringify(value)}. Use \"chat\", \"image\", or \"classifier\".`);\n}\n\nfunction toProvider(value: unknown): string | undefined {\n\tif (value === undefined || value === null) return undefined;\n\tif (typeof value !== \"string\") throw new Error(\"provider must be a string\");\n\treturn value;\n}\n\n/** Catalog entry for scripts. `headers` is dropped because models.json headers can carry credentials. */\nfunction toModelInfo(model: AnyModel): Record<string, unknown> {\n\tconst info: Record<string, unknown> = { ...model };\n\tdelete info.headers;\n\treturn info;\n}\n\n/** `an image`, `a classifier`. */\nfunction withArticle(word: string): string {\n\treturn `${/^[aeiou]/.test(word) ? \"an\" : \"a\"} ${word}`;\n}\n\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});\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,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,wBAAwB,CAAC;AACzG,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,M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AC,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 \"../tool-search/tool.ts\";\nimport {\n\tCODEMODE_DOCS_PATH,\n\tCODEMODE_STORE_ENTRY_TYPE,\n\ttype CodemodeModelRuntime,\n\ttype CodemodeNestedCall,\n\ttype CodemodeStoreEntryData,\n\ttype CodemodeToolDetails,\n\ttype CodemodeToolInput,\n\ttype CodemodeToolOptions,\n\tgetCodemodeCallableTools,\n\ttoCodemodeDeclaration,\n} from \"./tool.ts\";\n\nconst ARGS_PREVIEW_CHARS = 200;\nconst ERROR_PREVIEW_CHARS = 500;\n/** `models.classify()` and `models.generateImages()` calls one script may have in flight; `Promise.all` over many items queues the rest. */\nconst MAX_CONCURRENT_MODEL_CALLS = 4;\n/**\n * Heap limit for the QuickJS VM. The worker shares pi's process, so without a limit a runaway\n * script can grow to wasm32's 4 GiB and take the session down. Overruns throw\n * `InternalError: out of memory` inside the script.\n */\nconst CODEMODE_MEMORY_LIMIT_BYTES = 256 * 1024 * 1024;\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"]}
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../../src/extensions/mcp/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAKH,OAAO,EACN,KAAK,WAAW,EAChB,KAAK,eAAe,EAGpB,MAAM,2BAA2B,CAAC;AAEnC,YAAY,EACX,WAAW,EACX,mBAAmB,EACnB,cAAc,EACd,eAAe,EACf,oBAAoB,GACpB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAE/D,MAAM,WAAW,cAAc;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,eAAe,CAAC;IACxB,2FAA2F;IAC3F,MAAM,EAAE,MAAM,CAAC;IACf;;;OAGG;IACH,KAAK,CAAC,EAAE,QAAQ,GAAG,SAAS,GAAG,WAAW,CAAC;IAC3C,4GAA4G;IAC5G,QAAQ,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,eAAe;IAC/B,OAAO,EAAE,cAAc,EAAE,CAAC;IAC1B,iFAAiF;IACjF,kBAAkB,CAAC,EA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IACb,MAAM,EAAE,eAAe,CAAC;IACxB,2FAA2F;IAC3F,MAAM,EAAE,MAAM,CAAC;IACf;;;OAGG;IACH,KAAK,CAAC,EAAE,QAAQ,GAAG,SAAS,GAAG,WAAW,CAAC;IAC3C,4GAA4G;IAC5G,QAAQ,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,eAAe;IAC/B,OAAO,EAAE,cAAc,EAAE,CAAC;IAC1B,iFAAiF;IACjF,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,gGAAgG;IAChG,aAAa,CAAC,EAAE,MAAM,CAAC;CACvB;AAqED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,cAAc,EAAE,OAAO,CAAA;CAAE,GAAG,eAAe,CAWlH;AAED,+GAA+G;AAC/G,MAAM,WAAW,oBAAoB;IACpC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,QAAQ,CAAC,EAAE,WAAW,CAAC;CACvB;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CACpC,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,oBAAoB,EAC3B,OAAO,GAAE;IAAE,QAAQ,CAAC,EAAE,OAAO,CAAA;CAAO,GAClC,IAAI,CAmBN;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,eAAe,GAAG,OAAO,CAU/F;AAED,0FAA0F;AAC1F,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAUzE"}
@@ -32,6 +32,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
32
32
  import { dirname, join } from "node:path";
33
33
  import { CONFIG_DIR_NAME } from "../../config.js";
34
34
  import { mcpNamespace, validateMcpServerConfig, } from "../../core/mcp-servers.js";
35
+ import { stripBom } from "../../utils/text.js";
35
36
  export { getMcpToolExposure } from "../../core/mcp-servers.js";
36
37
  const OVERRIDE_KEYS = ["enabled", "exposure", "toolExposure"];
37
38
  /** Whether an entry overrides a server defined elsewhere instead of defining one. */
@@ -47,7 +48,7 @@ function readConfigFile(path, scope, state) {
47
48
  return;
48
49
  let parsed;
49
50
  try {
50
- parsed = JSON.parse(readFileSync(path, "utf8"));
51
+ parsed = JSON.parse(stripBom(readFileSync(path, "utf8")));
51
52
  }
52
53
  catch (error) {
53
54
  errors.push(`${path}: ${error instanceof Error ? error.message : String(error)}`);
@@ -179,7 +180,7 @@ export function removeMcpServerConfig(path, name) {
179
180
  * it back with its indentation when `edit` returns true. Other content is kept.
180
181
  */
181
182
  function editMcpServers(path, edit) {
182
- const text = existsSync(path) ? readFileSync(path, "utf8") : undefined;
183
+ const text = existsSync(path) ? stripBom(readFileSync(path, "utf8")) : undefined;
183
184
  const parsed = text === undefined ? {} : JSON.parse(text);
184
185
  if (!isRecord(parsed) || (parsed.mcpServers !== undefined && !isRecord(parsed.mcpServers))) {
185
186
  throw new Error(`${path}: expected an object with an "mcpServers" object`);
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","sourceRoot":"","sources":["../../../src/extensions/mcp/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAGN,YAAY,EACZ,uBAAuB,GACvB,MAAM,2BAA2B,CAAC;AASnC,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAA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,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;AAClE,CAAC","sourcesContent":["/**\n * MCP server configuration.\n *\n * Servers are read from `mcp.json` in the agent directory and, for trusted projects, from\n * `<project>/.pi/mcp.json`. Both use the `mcpServers` shape shared by other MCP clients, so\n * existing configurations can be copied over. Project entries replace global entries with the\n * same name.\n *\n * A project entry without `command`, `url`, or `type` overrides only `enabled`, `exposure`, and\n * `toolExposure` of the global server with the same name, for example to turn it off in one project:\n * `{ \"mcpServers\": { \"internal-tools\": { \"enabled\": false } } }`. The rest of the global entry is kept,\n * including credentials the project could not set itself.\n *\n * ```json\n * {\n * \"mcpServers\": {\n * \"filesystem\": { \"command\": \"npx\", \"args\": [\"-y\", \"@modelcontextprotocol/server-filesystem\", \".\"] },\n * \"docs\": { \"url\": \"https://example.com/mcp\", \"headers\": { \"Authorization\": \"Bearer ${DOCS_TOKEN}\" } },\n * \"sentry\": { \"url\": \"https://mcp.sentry.dev/mcp\" }\n * }\n * }\n * ```\n *\n * HTTP servers without an `Authorization` header use OAuth when they answer 401 (sign in with `/mcp`).\n * `\"auth\": { \"provider\": \"<provider>\" }` sends the token of a `/login` provider instead. Project files\n * cannot use it, so a repository cannot pick where the credential goes.\n *\n * The top-level `autoEnableCodemode` (default true) activates the codemode tool when a server\n * with `codemode` exposure connects. A project value overrides the global one.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { CONFIG_DIR_NAME } from \"../../config.ts\";\nimport {\n\ttype McpExposure,\n\ttype McpServerConfig,\n\tmcpNamespace,\n\tvalidateMcpServerConfig,\n} from \"../../core/mcp-servers.ts\";\n\nexport type {\n\tMcpExposure,\n\tMcpHttpServerConfig,\n\tMcpOAuthConfig,\n\tMcpServerConfig,\n\tMcpStdioServerConfig,\n} from \"../../core/mcp-servers.ts\";\nexport { getMcpToolExposure } from \"../../core/mcp-servers.ts\";\n\nexport interface McpServerEntry {\n\tname: string;\n\tconfig: McpServerConfig;\n\t/** Config file that defined the entry, or the path of the extension that registered it. */\n\tsource: string;\n\t/**\n\t * The global or the project `mcp.json`, or `extension` for servers registered with\n\t * `pi.registerMcpServer()`. Changes to extension servers are not saved.\n\t */\n\tscope?: \"global\" | \"project\" | \"extension\";\n\t/** Project `mcp.json` with an override of this global server's `enabled`, `exposure`, or `toolExposure`. */\n\toverride?: string;\n}\n\nexport interface LoadedMcpConfig {\n\tservers: McpServerEntry[];\n\t/** Activate the codemode tool when `codemode` servers connect. Default: true. */\n\tautoEnableCodemode?: boolean;\n\terrors: string[];\n\t/** The project `mcp.json` when the project is trusted, where `/mcp` saves project overrides. */\n\tprojectConfig?: string;\n}\n\nconst OVERRIDE_KEYS = [\"enabled\", \"exposure\", \"toolExposure\"];\n\n/** Whether an entry overrides a server defined elsewhere instead of defining one. */\nfunction isOverride(value: Record<string, unknown>): boolean {\n\treturn value.command === undefined && value.url === undefined && value.type === undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\ninterface McpConfigState {\n\tservers: Map<string, McpServerEntry>;\n\tautoEnableCodemode?: boolean;\n\terrors: string[];\n}\n\nfunction readConfigFile(path: string, scope: \"global\" | \"project\", state: McpConfigState): void {\n\tconst { servers, errors } = state;\n\tif (!existsSync(path)) return;\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(readFileSync(path, \"utf8\"));\n\t} catch (error) {\n\t\terrors.push(`${path}: ${error instanceof Error ? error.message : String(error)}`);\n\t\treturn;\n\t}\n\tif (!isRecord(parsed) || (parsed.mcpServers !== undefined && !isRecord(parsed.mcpServers))) {\n\t\terrors.push(`${path}: expected an object with an \"mcpServers\" object`);\n\t\treturn;\n\t}\n\tif (typeof parsed.autoEnableCodemode === \"boolean\") state.autoEnableCodemode = parsed.autoEnableCodemode;\n\telse if (parsed.autoEnableCodemode !== undefined) errors.push(`${path}: autoEnableCodemode must be a boolean`);\n\tfor (const [name, value] of Object.entries(parsed.mcpServers ?? {})) {\n\t\tif (scope === \"project\" && isRecord(value) && isOverride(value)) {\n\t\t\tconst base = servers.get(name);\n\t\t\tconst extra = Object.keys(value).filter((key) => !OVERRIDE_KEYS.includes(key));\n\t\t\tif (!base) {\n\t\t\t\terrors.push(`${path}: server \"${name}\" needs \"command\" or \"url\", or a global server to override`);\n\t\t\t} else if (extra.length > 0) {\n\t\t\t\terrors.push(`${path}: server \"${name}\": an override can only set ${OVERRIDE_KEYS.join(\", \")}`);\n\t\t\t} else {\n\t\t\t\tconst config = validateMcpServerConfig(name, { ...base.config, ...value });\n\t\t\t\tif (typeof config === \"string\") errors.push(`${path}: ${config}`);\n\t\t\t\telse servers.set(name, { ...base, config, override: path });\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst config = validateMcpServerConfig(name, value);\n\t\tif (typeof config === \"string\") {\n\t\t\terrors.push(`${path}: ${config}`);\n\t\t\tcontinue;\n\t\t}\n\t\t// Names that differ only in `-` and `_` would share a namespace.\n\t\tconst clash = [...servers.keys()].find((other) => other !== name && mcpNamespace(other) === mcpNamespace(name));\n\t\tif (clash) {\n\t\t\terrors.push(`${path}: server \"${name}\" conflicts with \"${clash}\"`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (scope === \"project\" && \"url\" in config && config.auth) {\n\t\t\terrors.push(`${path}: server \"${name}\": auth is only allowed in the global mcp.json`);\n\t\t\tcontinue;\n\t\t}\n\t\tservers.set(name, { name, config, source: path, scope });\n\t}\n}\n\n/**\n * Load global and (when trusted) project MCP configuration. Disabled servers are included with\n * `enabled: false`, so they can be enabled again.\n */\nexport function loadMcpConfig(options: { agentDir: string; cwd: string; projectTrusted: boolean }): LoadedMcpConfig {\n\tconst state: McpConfigState = { servers: new Map(), errors: [] };\n\treadConfigFile(join(options.agentDir, \"mcp.json\"), \"global\", state);\n\tconst projectConfig = options.projectTrusted ? join(options.cwd, CONFIG_DIR_NAME, \"mcp.json\") : undefined;\n\tif (projectConfig) readConfigFile(projectConfig, \"project\", state);\n\treturn {\n\t\tservers: [...state.servers.values()],\n\t\t...(state.autoEnableCodemode === undefined ? {} : { autoEnableCodemode: state.autoEnableCodemode }),\n\t\terrors: state.errors,\n\t\t...(projectConfig ? { projectConfig } : {}),\n\t};\n}\n\n/** Settings `/mcp` changes. `enabled: true` and `exposure: \"codemode\"` are the defaults and remove the key. */\nexport interface McpServerConfigPatch {\n\tenabled?: boolean;\n\texposure?: McpExposure;\n}\n\n/**\n * Change one server's settings in the `mcp.json` that defines or overrides it. With `override`, a\n * missing entry is added as an override. Overrides keep default values, since they replace the global\n * server's. Other content is kept; the file is rewritten with its indentation.\n */\nexport function updateMcpServerConfig(\n\tpath: string,\n\tname: string,\n\tpatch: McpServerConfigPatch,\n\toptions: { override?: boolean } = {},\n): void {\n\teditMcpServers(path, (servers, parsed) => {\n\t\tlet server = servers?.[name];\n\t\tif (server === undefined && options.override) {\n\t\t\tserver = {};\n\t\t\tparsed.mcpServers = { ...servers, [name]: server };\n\t\t}\n\t\tif (!isRecord(server)) throw new Error(`${path} does not define MCP server \"${name}\"`);\n\t\tconst keepDefaults = isOverride(server);\n\t\tif (patch.enabled !== undefined) {\n\t\t\tif (patch.enabled && !keepDefaults) delete server.enabled;\n\t\t\telse server.enabled = patch.enabled;\n\t\t}\n\t\tif (patch.exposure !== undefined) {\n\t\t\tif (patch.exposure === \"codemode\" && !keepDefaults) delete server.exposure;\n\t\t\telse server.exposure = patch.exposure;\n\t\t}\n\t\treturn true;\n\t});\n}\n\n/**\n * Add a server to an `mcp.json`, creating the file when missing. An existing entry with the same\n * name is replaced. Returns true when an entry was replaced.\n */\nexport function addMcpServerConfig(path: string, name: string, config: McpServerConfig): boolean {\n\tlet replaced = false;\n\teditMcpServers(path, (servers, parsed) => {\n\t\tconst target = servers ?? {};\n\t\treplaced = target[name] !== undefined;\n\t\ttarget[name] = config;\n\t\tparsed.mcpServers = target;\n\t\treturn true;\n\t});\n\treturn replaced;\n}\n\n/** Remove a server from an `mcp.json`. Returns false when the file does not define it. */\nexport function removeMcpServerConfig(path: string, name: string): boolean {\n\tif (!existsSync(path)) return false;\n\tlet removed = false;\n\teditMcpServers(path, (servers) => {\n\t\tif (!servers || servers[name] === undefined) return false;\n\t\tdelete servers[name];\n\t\tremoved = true;\n\t\treturn true;\n\t});\n\treturn removed;\n}\n\n/**\n * Read an `mcp.json` (an empty config when missing), let `edit` change its `mcpServers`, and write\n * it back with its indentation when `edit` returns true. Other content is kept.\n */\nfunction editMcpServers(\n\tpath: string,\n\tedit: (servers: Record<string, unknown> | undefined, parsed: Record<string, unknown>) => boolean,\n): void {\n\tconst text = existsSync(path) ? readFileSync(path, \"utf8\") : undefined;\n\tconst parsed: unknown = text === undefined ? {} : JSON.parse(text);\n\tif (!isRecord(parsed) || (parsed.mcpServers !== undefined && !isRecord(parsed.mcpServers))) {\n\t\tthrow new Error(`${path}: expected an object with an \"mcpServers\" object`);\n\t}\n\tconst servers = isRecord(parsed.mcpServers) ? parsed.mcpServers : undefined;\n\tif (!edit(servers, parsed)) return;\n\tconst indent = (text && /^([ \\t]+)\\S/m.exec(text)?.[1]) || \" \";\n\tmkdirSync(dirname(path), { recursive: true });\n\twriteFileSync(path, `${JSON.stringify(parsed, null, indent)}\\n`);\n}\n"]}
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../../../src/extensions/mcp/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAGN,YAAY,EACZ,uBAAuB,GACvB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,QAAQ,EAAE,MA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,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IAC9C,aAAa,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;AAClE,CAAC","sourcesContent":["/**\n * MCP server configuration.\n *\n * Servers are read from `mcp.json` in the agent directory and, for trusted projects, from\n * `<project>/.pi/mcp.json`. Both use the `mcpServers` shape shared by other MCP clients, so\n * existing configurations can be copied over. Project entries replace global entries with the\n * same name.\n *\n * A project entry without `command`, `url`, or `type` overrides only `enabled`, `exposure`, and\n * `toolExposure` of the global server with the same name, for example to turn it off in one project:\n * `{ \"mcpServers\": { \"internal-tools\": { \"enabled\": false } } }`. The rest of the global entry is kept,\n * including credentials the project could not set itself.\n *\n * ```json\n * {\n * \"mcpServers\": {\n * \"filesystem\": { \"command\": \"npx\", \"args\": [\"-y\", \"@modelcontextprotocol/server-filesystem\", \".\"] },\n * \"docs\": { \"url\": \"https://example.com/mcp\", \"headers\": { \"Authorization\": \"Bearer ${DOCS_TOKEN}\" } },\n * \"sentry\": { \"url\": \"https://mcp.sentry.dev/mcp\" }\n * }\n * }\n * ```\n *\n * HTTP servers without an `Authorization` header use OAuth when they answer 401 (sign in with `/mcp`).\n * `\"auth\": { \"provider\": \"<provider>\" }` sends the token of a `/login` provider instead. Project files\n * cannot use it, so a repository cannot pick where the credential goes.\n *\n * The top-level `autoEnableCodemode` (default true) activates the codemode tool when a server\n * with `codemode` exposure connects. A project value overrides the global one.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { CONFIG_DIR_NAME } from \"../../config.ts\";\nimport {\n\ttype McpExposure,\n\ttype McpServerConfig,\n\tmcpNamespace,\n\tvalidateMcpServerConfig,\n} from \"../../core/mcp-servers.ts\";\nimport { stripBom } from \"../../utils/text.ts\";\n\nexport type {\n\tMcpExposure,\n\tMcpHttpServerConfig,\n\tMcpOAuthConfig,\n\tMcpServerConfig,\n\tMcpStdioServerConfig,\n} from \"../../core/mcp-servers.ts\";\nexport { getMcpToolExposure } from \"../../core/mcp-servers.ts\";\n\nexport interface McpServerEntry {\n\tname: string;\n\tconfig: McpServerConfig;\n\t/** Config file that defined the entry, or the path of the extension that registered it. */\n\tsource: string;\n\t/**\n\t * The global or the project `mcp.json`, or `extension` for servers registered with\n\t * `pi.registerMcpServer()`. Changes to extension servers are not saved.\n\t */\n\tscope?: \"global\" | \"project\" | \"extension\";\n\t/** Project `mcp.json` with an override of this global server's `enabled`, `exposure`, or `toolExposure`. */\n\toverride?: string;\n}\n\nexport interface LoadedMcpConfig {\n\tservers: McpServerEntry[];\n\t/** Activate the codemode tool when `codemode` servers connect. Default: true. */\n\tautoEnableCodemode?: boolean;\n\terrors: string[];\n\t/** The project `mcp.json` when the project is trusted, where `/mcp` saves project overrides. */\n\tprojectConfig?: string;\n}\n\nconst OVERRIDE_KEYS = [\"enabled\", \"exposure\", \"toolExposure\"];\n\n/** Whether an entry overrides a server defined elsewhere instead of defining one. */\nfunction isOverride(value: Record<string, unknown>): boolean {\n\treturn value.command === undefined && value.url === undefined && value.type === undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\ninterface McpConfigState {\n\tservers: Map<string, McpServerEntry>;\n\tautoEnableCodemode?: boolean;\n\terrors: string[];\n}\n\nfunction readConfigFile(path: string, scope: \"global\" | \"project\", state: McpConfigState): void {\n\tconst { servers, errors } = state;\n\tif (!existsSync(path)) return;\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(stripBom(readFileSync(path, \"utf8\")));\n\t} catch (error) {\n\t\terrors.push(`${path}: ${error instanceof Error ? error.message : String(error)}`);\n\t\treturn;\n\t}\n\tif (!isRecord(parsed) || (parsed.mcpServers !== undefined && !isRecord(parsed.mcpServers))) {\n\t\terrors.push(`${path}: expected an object with an \"mcpServers\" object`);\n\t\treturn;\n\t}\n\tif (typeof parsed.autoEnableCodemode === \"boolean\") state.autoEnableCodemode = parsed.autoEnableCodemode;\n\telse if (parsed.autoEnableCodemode !== undefined) errors.push(`${path}: autoEnableCodemode must be a boolean`);\n\tfor (const [name, value] of Object.entries(parsed.mcpServers ?? {})) {\n\t\tif (scope === \"project\" && isRecord(value) && isOverride(value)) {\n\t\t\tconst base = servers.get(name);\n\t\t\tconst extra = Object.keys(value).filter((key) => !OVERRIDE_KEYS.includes(key));\n\t\t\tif (!base) {\n\t\t\t\terrors.push(`${path}: server \"${name}\" needs \"command\" or \"url\", or a global server to override`);\n\t\t\t} else if (extra.length > 0) {\n\t\t\t\terrors.push(`${path}: server \"${name}\": an override can only set ${OVERRIDE_KEYS.join(\", \")}`);\n\t\t\t} else {\n\t\t\t\tconst config = validateMcpServerConfig(name, { ...base.config, ...value });\n\t\t\t\tif (typeof config === \"string\") errors.push(`${path}: ${config}`);\n\t\t\t\telse servers.set(name, { ...base, config, override: path });\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst config = validateMcpServerConfig(name, value);\n\t\tif (typeof config === \"string\") {\n\t\t\terrors.push(`${path}: ${config}`);\n\t\t\tcontinue;\n\t\t}\n\t\t// Names that differ only in `-` and `_` would share a namespace.\n\t\tconst clash = [...servers.keys()].find((other) => other !== name && mcpNamespace(other) === mcpNamespace(name));\n\t\tif (clash) {\n\t\t\terrors.push(`${path}: server \"${name}\" conflicts with \"${clash}\"`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (scope === \"project\" && \"url\" in config && config.auth) {\n\t\t\terrors.push(`${path}: server \"${name}\": auth is only allowed in the global mcp.json`);\n\t\t\tcontinue;\n\t\t}\n\t\tservers.set(name, { name, config, source: path, scope });\n\t}\n}\n\n/**\n * Load global and (when trusted) project MCP configuration. Disabled servers are included with\n * `enabled: false`, so they can be enabled again.\n */\nexport function loadMcpConfig(options: { agentDir: string; cwd: string; projectTrusted: boolean }): LoadedMcpConfig {\n\tconst state: McpConfigState = { servers: new Map(), errors: [] };\n\treadConfigFile(join(options.agentDir, \"mcp.json\"), \"global\", state);\n\tconst projectConfig = options.projectTrusted ? join(options.cwd, CONFIG_DIR_NAME, \"mcp.json\") : undefined;\n\tif (projectConfig) readConfigFile(projectConfig, \"project\", state);\n\treturn {\n\t\tservers: [...state.servers.values()],\n\t\t...(state.autoEnableCodemode === undefined ? {} : { autoEnableCodemode: state.autoEnableCodemode }),\n\t\terrors: state.errors,\n\t\t...(projectConfig ? { projectConfig } : {}),\n\t};\n}\n\n/** Settings `/mcp` changes. `enabled: true` and `exposure: \"codemode\"` are the defaults and remove the key. */\nexport interface McpServerConfigPatch {\n\tenabled?: boolean;\n\texposure?: McpExposure;\n}\n\n/**\n * Change one server's settings in the `mcp.json` that defines or overrides it. With `override`, a\n * missing entry is added as an override. Overrides keep default values, since they replace the global\n * server's. Other content is kept; the file is rewritten with its indentation.\n */\nexport function updateMcpServerConfig(\n\tpath: string,\n\tname: string,\n\tpatch: McpServerConfigPatch,\n\toptions: { override?: boolean } = {},\n): void {\n\teditMcpServers(path, (servers, parsed) => {\n\t\tlet server = servers?.[name];\n\t\tif (server === undefined && options.override) {\n\t\t\tserver = {};\n\t\t\tparsed.mcpServers = { ...servers, [name]: server };\n\t\t}\n\t\tif (!isRecord(server)) throw new Error(`${path} does not define MCP server \"${name}\"`);\n\t\tconst keepDefaults = isOverride(server);\n\t\tif (patch.enabled !== undefined) {\n\t\t\tif (patch.enabled && !keepDefaults) delete server.enabled;\n\t\t\telse server.enabled = patch.enabled;\n\t\t}\n\t\tif (patch.exposure !== undefined) {\n\t\t\tif (patch.exposure === \"codemode\" && !keepDefaults) delete server.exposure;\n\t\t\telse server.exposure = patch.exposure;\n\t\t}\n\t\treturn true;\n\t});\n}\n\n/**\n * Add a server to an `mcp.json`, creating the file when missing. An existing entry with the same\n * name is replaced. Returns true when an entry was replaced.\n */\nexport function addMcpServerConfig(path: string, name: string, config: McpServerConfig): boolean {\n\tlet replaced = false;\n\teditMcpServers(path, (servers, parsed) => {\n\t\tconst target = servers ?? {};\n\t\treplaced = target[name] !== undefined;\n\t\ttarget[name] = config;\n\t\tparsed.mcpServers = target;\n\t\treturn true;\n\t});\n\treturn replaced;\n}\n\n/** Remove a server from an `mcp.json`. Returns false when the file does not define it. */\nexport function removeMcpServerConfig(path: string, name: string): boolean {\n\tif (!existsSync(path)) return false;\n\tlet removed = false;\n\teditMcpServers(path, (servers) => {\n\t\tif (!servers || servers[name] === undefined) return false;\n\t\tdelete servers[name];\n\t\tremoved = true;\n\t\treturn true;\n\t});\n\treturn removed;\n}\n\n/**\n * Read an `mcp.json` (an empty config when missing), let `edit` change its `mcpServers`, and write\n * it back with its indentation when `edit` returns true. Other content is kept.\n */\nfunction editMcpServers(\n\tpath: string,\n\tedit: (servers: Record<string, unknown> | undefined, parsed: Record<string, unknown>) => boolean,\n): void {\n\tconst text = existsSync(path) ? stripBom(readFileSync(path, \"utf8\")) : undefined;\n\tconst parsed: unknown = text === undefined ? {} : JSON.parse(text);\n\tif (!isRecord(parsed) || (parsed.mcpServers !== undefined && !isRecord(parsed.mcpServers))) {\n\t\tthrow new Error(`${path}: expected an object with an \"mcpServers\" object`);\n\t}\n\tconst servers = isRecord(parsed.mcpServers) ? parsed.mcpServers : undefined;\n\tif (!edit(servers, parsed)) return;\n\tconst indent = (text && /^([ \\t]+)\\S/m.exec(text)?.[1]) || \" \";\n\tmkdirSync(dirname(path), { recursive: true });\n\twriteFileSync(path, `${JSON.stringify(parsed, null, indent)}\\n`);\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -24,6 +24,7 @@ export { formatSkillsForPrompt, type LoadSkillsFromDirOptions, type LoadSkillsRe
24
24
  export { createSyntheticSourceInfo } from "./core/source-info.ts";
25
25
  export { type EditDiffResult, generateDiffString, generateUnifiedPatch } from "./core/tools/edit-diff.ts";
26
26
  export { type BashOperations, type BashSpawnContext, type BashSpawnHook, type BashToolDetails, type BashToolInput, type BashToolOptions, createBashToolDefinition, createEditToolDefinition, createFindToolDefinition, createGrepToolDefinition, createLocalBashOperations, createLocalPowerShellOperations, createLsToolDefinition, createPowerShellToolDefinition, createReadToolDefinition, createWriteToolDefinition, DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, type EditOperations, type EditToolDetails, type EditToolInput, type EditToolOptions, type FindOperations, type FindToolDetails, type FindToolInput, type FindToolOptions, formatSize, type GrepOperations, type GrepToolDetails, type GrepToolInput, type GrepToolOptions, type LsOperations, type LsToolDetails, type LsToolInput, type LsToolOptions, type PowerShellOperations, type PowerShellSpawnContext, type PowerShellSpawnHook, type PowerShellToolDetails, type PowerShellToolInput, type PowerShellToolOptions, type ReadOperations, type ReadToolDetails, type ReadToolInput, type ReadToolOptions, type ToolsOptions, type TruncationOptions, type TruncationResult, truncateHead, truncateLine, truncateTail, type WriteOperations, type WriteToolInput, type WriteToolOptions, withFileMutationQueue, } from "./core/tools/index.ts";
27
+ export { formatReadLineRange } from "./core/tools/render-utils.ts";
27
28
  export { hasTrustRequiringProjectResources, type ProjectTrustDecision, ProjectTrustStore, type ProjectTrustStoreEntry, type ProjectTrustUpdate, } from "./core/trust-manager.ts";
28
29
  export { type ModelRoute, type ModelRouteReason, type ModelRouteRequest, VIRTUAL_MODEL_STATE_ENTRY, type VirtualModelDefinition, type VirtualModelStateData, } from "./core/virtual-models.ts";
29
30
  export { type CodemodeExtensionOptions, createCodemodeExtension } from "./extensions/codemode/index.ts";