@earendil-works/pi-coding-agent 0.99.2 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/dist/bundle/chunks/anthropic.js +2 -2
  3. package/dist/bundle/chunks/{azure-openai-responses-TLHNIYZK.js → azure-openai-responses-AFMVM6NP.js} +1 -1
  4. package/dist/bundle/chunks/{chunk-7QSPBJKW.js → chunk-2KTBZM5G.js} +14 -28
  5. package/dist/bundle/chunks/{chunk-R5J3MOBF.js → chunk-2VNGUWBO.js} +1 -1
  6. package/dist/bundle/chunks/chunk-33XOIQ5N.js +1204 -0
  7. package/dist/bundle/chunks/chunk-4KU537KD.js +2 -0
  8. package/dist/bundle/chunks/chunk-7FH3BDRG.js +82 -0
  9. package/dist/bundle/chunks/{chunk-45SXDISG.js → chunk-IBCPYVFK.js} +4 -4
  10. package/dist/bundle/chunks/chunk-KDN6RCEQ.js +4 -0
  11. package/dist/bundle/chunks/{chunk-G3UZ5FWD.js → chunk-LTXEMVMA.js} +11 -60
  12. package/dist/bundle/chunks/chunk-PRD6WYBT.js +16 -0
  13. package/dist/bundle/chunks/{cli-ALNBTL3U.js → cli-QOMC26IJ.js} +3 -3
  14. package/dist/bundle/chunks/codemode-worker.js +44 -5
  15. package/dist/bundle/chunks/execute-GVRSEGHL.js +367 -0
  16. package/dist/bundle/chunks/openai-chatgpt.js +1 -1
  17. package/dist/bundle/chunks/{openai-codex-responses-3GKGNXC4.js → openai-codex-responses-GK67DQQJ.js} +1 -1
  18. package/dist/bundle/chunks/openai-codex.js +1 -1
  19. package/dist/bundle/chunks/{openai-responses-S7GKCCDG.js → openai-responses-CQDDLDQF.js} +1 -1
  20. package/dist/bundle/chunks/openrouter.js +1 -1
  21. package/dist/bundle/chunks/pi-logo-animation-MPKZE4EK.js +2 -0
  22. package/dist/bundle/chunks/radius.js +1 -1
  23. package/dist/bundle/chunks/runtime-2SO2JDWM.js +2 -0
  24. package/dist/bundle/chunks/virtual-modules-6ZMK7GDO.js +2 -0
  25. package/dist/bundle/cli-runtime.js +1 -1
  26. package/dist/bundle/index.js +1 -1
  27. package/dist/bundle/rpc-entry.js +1 -1
  28. package/dist/cli/args.js +2 -2
  29. package/dist/cli/args.js.map +1 -1
  30. package/dist/core/agent-session.d.ts +8 -0
  31. package/dist/core/agent-session.d.ts.map +1 -1
  32. package/dist/core/agent-session.js +37 -8
  33. package/dist/core/agent-session.js.map +1 -1
  34. package/dist/core/mcp-servers.d.ts +6 -0
  35. package/dist/core/mcp-servers.d.ts.map +1 -1
  36. package/dist/core/mcp-servers.js +7 -0
  37. package/dist/core/mcp-servers.js.map +1 -1
  38. package/dist/core/model-registry.d.ts +3 -1
  39. package/dist/core/model-registry.d.ts.map +1 -1
  40. package/dist/core/model-registry.js +4 -0
  41. package/dist/core/model-registry.js.map +1 -1
  42. package/dist/core/radius.d.ts +2 -0
  43. package/dist/core/radius.d.ts.map +1 -1
  44. package/dist/core/radius.js +2 -0
  45. package/dist/core/radius.js.map +1 -1
  46. package/dist/core/settings-manager.d.ts +7 -5
  47. package/dist/core/settings-manager.d.ts.map +1 -1
  48. package/dist/core/settings-manager.js +3 -2
  49. package/dist/core/settings-manager.js.map +1 -1
  50. package/dist/core/system-prompt.js +1 -1
  51. package/dist/core/system-prompt.js.map +1 -1
  52. package/dist/core/tools/bash.d.ts.map +1 -1
  53. package/dist/core/tools/bash.js +3 -5
  54. package/dist/core/tools/bash.js.map +1 -1
  55. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  56. package/dist/extensions/codemode/execute.js +154 -47
  57. package/dist/extensions/codemode/execute.js.map +1 -1
  58. package/dist/extensions/codemode/tool.d.ts +7 -7
  59. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  60. package/dist/extensions/codemode/tool.js +55 -102
  61. package/dist/extensions/codemode/tool.js.map +1 -1
  62. package/dist/extensions/mcp/cli.js +2 -2
  63. package/dist/extensions/mcp/cli.js.map +1 -1
  64. package/dist/extensions/mcp/index.d.ts.map +1 -1
  65. package/dist/extensions/mcp/index.js +23 -12
  66. package/dist/extensions/mcp/index.js.map +1 -1
  67. package/dist/extensions/mcp/oauth.d.ts +8 -7
  68. package/dist/extensions/mcp/oauth.d.ts.map +1 -1
  69. package/dist/extensions/mcp/oauth.js +55 -30
  70. package/dist/extensions/mcp/oauth.js.map +1 -1
  71. package/dist/extensions/mcp/runtime.d.ts.map +1 -1
  72. package/dist/extensions/mcp/runtime.js +2 -1
  73. package/dist/extensions/mcp/runtime.js.map +1 -1
  74. package/dist/index.d.ts +1 -1
  75. package/dist/index.d.ts.map +1 -1
  76. package/dist/index.js.map +1 -1
  77. package/dist/main.d.ts.map +1 -1
  78. package/dist/main.js +6 -0
  79. package/dist/main.js.map +1 -1
  80. package/dist/modes/interactive/components/oauth-selector.d.ts +8 -2
  81. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  82. package/dist/modes/interactive/components/oauth-selector.js +24 -21
  83. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  84. package/dist/modes/interactive/components/pi-logo-animation.d.ts +68 -0
  85. package/dist/modes/interactive/components/pi-logo-animation.d.ts.map +1 -0
  86. package/dist/modes/interactive/components/pi-logo-animation.js +1086 -0
  87. package/dist/modes/interactive/components/pi-logo-animation.js.map +1 -0
  88. package/dist/modes/interactive/components/pi-logo-animation.lazy.d.ts +7 -0
  89. package/dist/modes/interactive/components/pi-logo-animation.lazy.d.ts.map +1 -0
  90. package/dist/modes/interactive/components/pi-logo-animation.lazy.js +12 -0
  91. package/dist/modes/interactive/components/pi-logo-animation.lazy.js.map +1 -0
  92. package/dist/modes/interactive/components/pi-logo.d.ts +7 -0
  93. package/dist/modes/interactive/components/pi-logo.d.ts.map +1 -1
  94. package/dist/modes/interactive/components/pi-logo.js +13 -1
  95. package/dist/modes/interactive/components/pi-logo.js.map +1 -1
  96. package/dist/modes/interactive/components/radius-login-selector.d.ts +15 -0
  97. package/dist/modes/interactive/components/radius-login-selector.d.ts.map +1 -0
  98. package/dist/modes/interactive/components/radius-login-selector.js +85 -0
  99. package/dist/modes/interactive/components/radius-login-selector.js.map +1 -0
  100. package/dist/modes/interactive/components/settings-selector.d.ts +3 -3
  101. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  102. package/dist/modes/interactive/components/settings-selector.js +5 -5
  103. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  104. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  105. package/dist/modes/interactive/components/user-message.js +5 -4
  106. package/dist/modes/interactive/components/user-message.js.map +1 -1
  107. package/dist/modes/interactive/interactive-mode.d.ts +10 -0
  108. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  109. package/dist/modes/interactive/interactive-mode.js +153 -40
  110. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  111. package/dist/modes/interactive/theme/system-theme.d.ts +2 -1
  112. package/dist/modes/interactive/theme/system-theme.d.ts.map +1 -1
  113. package/dist/modes/interactive/theme/system-theme.js +16 -5
  114. package/dist/modes/interactive/theme/system-theme.js.map +1 -1
  115. package/docs/cli.md +6 -16
  116. package/docs/codemode.md +207 -0
  117. package/docs/docs.json +5 -1
  118. package/docs/environment-variables.md +2 -2
  119. package/docs/index.md +1 -1
  120. package/docs/mcp.md +17 -0
  121. package/docs/models.md +22 -1
  122. package/docs/providers.md +16 -6
  123. package/docs/sdk.md +1 -1
  124. package/docs/settings.md +3 -3
  125. package/docs/usage.md +1 -1
  126. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  127. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  128. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  129. package/examples/extensions/gondolin/package-lock.json +2 -2
  130. package/examples/extensions/gondolin/package.json +1 -1
  131. package/examples/extensions/sandbox/package-lock.json +2 -2
  132. package/examples/extensions/sandbox/package.json +1 -1
  133. package/examples/extensions/with-deps/package-lock.json +2 -2
  134. package/examples/extensions/with-deps/package.json +1 -1
  135. package/npm-shrinkwrap.json +25 -30
  136. package/package.json +10 -10
  137. package/dist/bundle/chunks/chunk-3KYEVQKX.js +0 -82
  138. package/dist/bundle/chunks/chunk-3NVH2HQH.js +0 -4
  139. package/dist/bundle/chunks/chunk-3YAHQSW6.js +0 -1438
  140. package/dist/bundle/chunks/chunk-ECRK44UV.js +0 -2
  141. package/dist/bundle/chunks/execute-RC7W4ML3.js +0 -328
  142. package/dist/bundle/chunks/runtime-NJPX4ID2.js +0 -2
  143. package/dist/bundle/chunks/virtual-modules-5UGH4HRZ.js +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"execute.js","sourceRoot":"","sources":["../../../src/extensions/codemode/execute.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,OAAO,EAEN,eAAe,EAEf,eAAe,EACf,mBAAmB,EACnB,gBAAgB,EAChB,oBAAoB,GACpB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,0BAA0B,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAGjF,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC1D,OAAO,EAAE,UAAU,EAAE,wBAAwB,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AACzG,OAAO,EACN,yBAAyB,EAOzB,wBAAwB,EACxB,yBAAyB,EACzB,qBAAqB,GACrB,MAAM,WAAW,CAAC;AAEnB,MAAM,kBAAkB,GAAG,GAAG,CAAC;AAC/B,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAChC,qGAAqG;AACrG,MAAM,0BAA0B,GAAG,CAAC,CAAC;AACrC;;;;GAIG;A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ool.ts and loaded through\n * execute.lazy.ts so the sandbox runtime only loads when a script runs.\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { AgentTool, AgentToolCallOutcome, AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { AnyModel, ClassifierContext, ImageContent, ModelType, TextContent, Usage } from \"@earendil-works/pi-ai\";\nimport {\n\ttype CodemodeResult,\n\tCodemodeSandbox,\n\ttype CodemodeTool,\n\tloadQuickJSWasm,\n\tparseCodemodeSource,\n\trenderToolSample,\n\ttoCodemodeIdentifier,\n} from \"@earendil-works/pi-codemode\";\nimport { getCodemodeWorkerSpecifier, getQuickJSWasmPath } from \"../../config.ts\";\nimport type { ExtensionToolContext, ToolNamespace } from \"../../core/extensions/types.ts\";\nimport type { SessionEntry } from \"../../core/session-manager.ts\";\nimport { combineUsage } from \"../../core/usage-totals.ts\";\nimport { Bm25Ranker, createToolSearchDocument, DEFAULT_TOOL_SEARCH_LIMIT } from \"../tool-search/tool.ts\";\nimport {\n\tCODEMODE_STORE_ENTRY_TYPE,\n\ttype CodemodeModelRuntime,\n\ttype CodemodeNestedCall,\n\ttype CodemodeStoreEntryData,\n\ttype CodemodeToolDetails,\n\ttype CodemodeToolInput,\n\ttype CodemodeToolOptions,\n\tgetCodemodeCallableTools,\n\tMODEL_GLOBAL_DECLARATIONS,\n\ttoCodemodeDeclaration,\n} from \"./tool.ts\";\n\nconst ARGS_PREVIEW_CHARS = 200;\nconst ERROR_PREVIEW_CHARS = 500;\n/** Classifier calls one script may have in flight; `Promise.all` over many items queues the rest. */\nconst MAX_CONCURRENT_MODEL_CALLS = 4;\n/**\n * Heap limit for the QuickJS VM. The worker shares pi's process, so without a limit a runaway\n * script can grow to wasm32's 4 GiB and take the session down. Overruns throw\n * `InternalError: out of memory` inside the script.\n */\nconst CODEMODE_MEMORY_LIMIT_BYTES = 256 * 1024 * 1024;\nconst MODEL_TYPES: ReadonlySet<string> = new Set<ModelType>([\"chat\", \"image\", \"classifier\"]);\n\nfunction truncateText(text: string, maxChars: number): string {\n\treturn text.length > maxChars ? `${text.slice(0, maxChars - 3)}...` : text;\n}\n\nfunction previewArgs(args: unknown): string {\n\tif (args === undefined) return \"\";\n\ttry {\n\t\treturn truncateText(JSON.stringify(args) ?? \"\", ARGS_PREVIEW_CHARS);\n\t} catch {\n\t\treturn \"\";\n\t}\n}\n\nfunction textOf(result: AgentToolResult<unknown>): string {\n\treturn (result.content ?? [])\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n}\n\nfunction toModelType(value: unknown): ModelType {\n\tif (typeof value === \"string\" && MODEL_TYPES.has(value)) return value as ModelType;\n\tthrow new Error(`Unknown model type ${JSON.stringify(value)}. Use \"chat\", \"image\", or \"classifier\".`);\n}\n\nfunction toProvider(value: unknown): string | undefined {\n\tif (value === undefined || value === null) return undefined;\n\tif (typeof value !== \"string\") throw new Error(\"provider must be a string\");\n\treturn value;\n}\n\n/** Catalog entry for scripts. `headers` is dropped because models.json headers can carry credentials. */\nfunction toModelInfo(model: AnyModel): Record<string, unknown> {\n\tconst info: Record<string, unknown> = { ...model };\n\tdelete info.headers;\n\treturn info;\n}\n\n/** Runs at most `limit` calls at once, in call order. */\nfunction createLimiter(limit: number): <T>(run: () => Promise<T>) => Promise<T> {\n\tlet active = 0;\n\tconst waiting: (() => void)[] = [];\n\treturn async (run) => {\n\t\tif (active >= limit) await new Promise<void>((resolve) => waiting.push(resolve));\n\t\tactive++;\n\t\ttry {\n\t\t\treturn await run();\n\t\t} finally {\n\t\t\tactive--;\n\t\t\twaiting.shift()?.();\n\t\t}\n\t};\n}\n\nfunction isStoreEntryData(data: unknown): data is CodemodeStoreEntryData {\n\tif (typeof data !== \"object\" || data === null) return false;\n\tconst { set, delete: deleted } = data as Partial<CodemodeStoreEntryData>;\n\treturn (\n\t\ttypeof set === \"object\" &&\n\t\tset !== null &&\n\t\tArray.isArray(deleted) &&\n\t\tdeleted.every((key: unknown) => typeof key === \"string\")\n\t);\n}\n\n/** Values of `load()`: the `codemode-store` entries on the branch, applied from the root. */\nexport function readCodemodeStore(branch: readonly SessionEntry[]): Record<string, unknown> {\n\tconst store = new Map<string, unknown>();\n\tfor (const entry of branch) {\n\t\tif (entry.type !== \"custom\" || entry.customType !== CODEMODE_STORE_ENTRY_TYPE || !isStoreEntryData(entry.data)) {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const key of entry.data.delete) store.delete(key);\n\t\tfor (const [key, value] of Object.entries(entry.data.set)) store.set(key, value);\n\t}\n\treturn Object.fromEntries(store);\n}\n\n/** Default token budget for script output. */\nconst DEFAULT_MAX_OUTPUT_TOKENS = 10_000;\n/** Characters per token when estimating. */\nconst CHARS_PER_TOKEN = 4;\n\n/** Like the script's `text()`: strings as is, other values as compact JSON. */\nfunction valueText(value: unknown): string {\n\tif (typeof value === \"string\") return value;\n\treturn JSON.stringify(value) ?? String(value);\n}\n\nfunction formatCallSummary(calls: readonly CodemodeNestedCall[]): string {\n\tif (calls.length === 0) return \"No tool calls were made.\";\n\treturn `Tool calls made before the failure (they are not undone): ${calls.map((call) => `${call.name} (${call.status})`).join(\", \")}`;\n}\n\nfunction formatError(result: Extract<CodemodeResult, { ok: false }>, calls: readonly CodemodeNestedCall[]): string {\n\tconst { error } = result;\n\tconst head =\n\t\terror.kind === \"script\"\n\t\t\t? (error.stack ?? `${error.name ?? \"Error\"}: ${error.message}`)\n\t\t\t: error.kind === \"timeout\"\n\t\t\t\t? `Script timed out: ${error.message}`\n\t\t\t\t: error.kind === \"aborted\"\n\t\t\t\t\t? `Script aborted: ${error.message}`\n\t\t\t\t\t: `Script sandbox failed: ${error.message}`;\n\treturn `${head}\\n\\n${formatCallSummary(calls)}`;\n}\n\n/** Write the full text output to a temp file, like bash does for truncated output. */\nasync function spillOutput(text: string): Promise<{ path: string } | { error: string }> {\n\tconst path = join(tmpdir(), `pi-codemode-${randomBytes(8).toString(\"hex\")}.txt`);\n\ttry {\n\t\tawait writeFile(path, text);\n\t\treturn { path };\n\t} catch (error) {\n\t\treturn { error: error instanceof Error ? error.message : String(error) };\n\t}\n}\n\n/**\n * Apply the token budget: when the combined text exceeds it, the text items become one\n * item that keeps the start and end of the text, and images follow it. The full text is written to\n * a temp file.\n */\nasync function truncateOutput(\n\titems: (TextContent | ImageContent)[],\n\tmaxTokens: number,\n): Promise<{ items: (TextContent | ImageContent)[]; fullOutputPath?: string }> {\n\tconst texts = items.filter((item): item is TextContent => item.type === \"text\").map((item) => item.text);\n\tconst combined = texts.join(\"\\n\");\n\tconst budget = maxTokens * CHARS_PER_TOKEN;\n\tif (texts.length === 0 || combined.length <= budget) return { items };\n\tconst headChars = Math.floor(budget / 2);\n\tconst tailChars = budget - headChars;\n\tconst removed = combined.length - headChars - tailChars;\n\tconst head = combined.slice(0, headChars);\n\tconst tail = tailChars > 0 ? combined.slice(-tailChars) : \"\";\n\tlet text = `Warning: truncated output (original token count: ${Math.ceil(combined.length / CHARS_PER_TOKEN)})\\nTotal output lines: ${combined.split(\"\\n\").length}\\n\\n${head}…${Math.ceil(removed / CHARS_PER_TOKEN)} tokens truncated…${tail}`;\n\tconst spilled = await spillOutput(combined);\n\ttext +=\n\t\t\"path\" in spilled\n\t\t\t? `\\n\\n[Full output: ${spilled.path} (read with offset/limit)]`\n\t\t\t: `\\n\\n[Could not save the full output: ${spilled.error}]`;\n\treturn {\n\t\titems: [{ type: \"text\", text }, ...items.filter((item) => item.type === \"image\")],\n\t\t...(\"path\" in spilled ? { fullOutputPath: spilled.path } : {}),\n\t};\n}\n\n/**\n * The value a script receives for a nested call: a tool that declares\n * `outputSchema` resolves to its `structuredContent`, also for error results that carry one (such\n * as MCP results with `isError`); any other tool resolves to its text content. Other failures\n * reject with the tool's error text.\n */\nfunction toScriptValue(tool: AgentTool<any>, outcome: AgentToolCallOutcome): unknown {\n\tconst { result } = outcome;\n\tif (tool.outputSchema && result.structuredContent !== undefined) return result.structuredContent;\n\tconst text = textOf(result);\n\tif (outcome.isError) throw new Error(text || `Tool \"${tool.name}\" failed`);\n\treturn text;\n}\n\n/**\n * Run one script. Without a session context (a plain Agent or a direct call) scripts cannot call\n * tools, `store()` starts empty, and writes are dropped.\n */\nexport async function executeCodemode(\n\ttoolCallId: string,\n\tinput: CodemodeToolInput,\n\tsignal: AbortSignal | undefined,\n\tonUpdate: ((result: AgentToolResult<CodemodeToolDetails>) => void) | undefined,\n\tctx: ExtensionToolContext | undefined,\n\toptions: CodemodeToolOptions = {},\n): Promise<AgentToolResult<CodemodeToolDetails>> {\n\tconst startedAt = performance.now();\n\tconst { code, options: sourceOptions } = parseCodemodeSource(input.code);\n\tconst calls: CodemodeNestedCall[] = [];\n\t// Usage of the script's `models.*` calls. Nested tool calls report theirs through the session.\n\tlet modelUsage: Usage | undefined;\n\tconst addModelUsage = (usage: Usage) => {\n\t\tmodelUsage = modelUsage ? combineUsage(modelUsage, usage) : usage;\n\t};\n\n\tconst snapshot = (): CodemodeToolDetails => ({ calls: calls.map((call) => ({ ...call })) });\n\tconst publish = () => onUpdate?.({ content: [], details: snapshot() });\n\n\tconst callable = ctx ? getCodemodeCallableTools(ctx.tools) : [];\n\t// ALL_TOOLS entries carry the declaration.\n\tconst samples = new Map(callable.map((tool) => [tool.name, renderToolSample(toCodemodeDeclaration(tool))]));\n\tconst sandboxTools: CodemodeTool[] = callable.map((tool) => ({\n\t\tname: tool.name,\n\t\tdescription: samples.get(tool.name),\n\t\texecute: async (args, { signal: callSignal }) => {\n\t\t\tconst record: CodemodeNestedCall = {\n\t\t\t\tid: `${toolCallId}/?`,\n\t\t\t\tname: tool.name,\n\t\t\t\targs: previewArgs(args),\n\t\t\t\tstatus: \"running\",\n\t\t\t};\n\t\t\tcalls.push(record);\n\t\t\tpublish();\n\t\t\tconst callStartedAt = performance.now();\n\t\t\t// Only tools from ctx.tools are callable, so ctx is set here.\n\t\t\tif (!ctx) throw new Error(\"Tool calls need a session\");\n\t\t\tconst outcome = await ctx.executeTool(tool.name, args, { signal: callSignal });\n\t\t\trecord.id = outcome.toolCall.id;\n\t\t\trecord.durationMs = performance.now() - callStartedAt;\n\t\t\tif (outcome.isError) {\n\t\t\t\trecord.status = callSignal.aborted ? \"cancelled\" : \"error\";\n\t\t\t\trecord.error = truncateText(textOf(outcome.result) || `Tool \"${tool.name}\" failed`, ERROR_PREVIEW_CHARS);\n\t\t\t} else {\n\t\t\t\trecord.status = \"ok\";\n\t\t\t}\n\t\t\tpublish();\n\t\t\treturn toScriptValue(tool, outcome);\n\t\t},\n\t}));\n\n\tconst sandbox = new CodemodeSandbox({\n\t\ttools: sandboxTools,\n\t\tglobals: [\n\t\t\t...createDiscoveryGlobals(callable, samples, options),\n\t\t\t...(options.models && ctx\n\t\t\t\t? createModelGlobals(ctx.modelRegistry, toolCallId, calls, publish, addModelUsage)\n\t\t\t\t: []),\n\t\t],\n\t\ttimeoutMs: sourceOptions.timeoutMs ?? Number.POSITIVE_INFINITY,\n\t\tmemoryLimitBytes: CODEMODE_MEMORY_LIMIT_BYTES,\n\t\twasm: loadQuickJSWasm(getQuickJSWasmPath()),\n\t\tworkerUrl: getCodemodeWorkerSpecifier(),\n\t});\n\n\tlet result: CodemodeResult;\n\ttry {\n\t\tconst store = ctx ? readCodemodeStore(ctx.sessionManager.getBranch()) : {};\n\t\tresult = await sandbox.execute(code, { signal, store });\n\t} finally {\n\t\tawait sandbox.close();\n\t}\n\t// Calls still marked running were cut off by the script ending, a timeout, or an abort.\n\tfor (const call of calls) {\n\t\tif (call.status === \"running\") call.status = \"cancelled\";\n\t}\n\n\tconst items: (TextContent | ImageContent)[] = result.output.map((item) =>\n\t\titem.type === \"text\" ? { type: \"text\", text: item.text } : item,\n\t);\n\tif (result.ok) {\n\t\tconst { set, delete: deleted } = result.storeWrites;\n\t\tif (Object.keys(set).length > 0 || deleted.length > 0) {\n\t\t\toptions.appendEntry?.(CODEMODE_STORE_ENTRY_TYPE, { set, delete: deleted });\n\t\t}\n\t\t// pi extension: a returned value is appended like text().\n\t\tif (result.value !== undefined) items.push({ type: \"text\", text: valueText(result.value) });\n\t} else {\n\t\titems.push({ type: \"text\", text: `Script error:\\n${formatError(result, calls)}` });\n\t}\n\n\tconst truncated = await truncateOutput(items, sourceOptions.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS);\n\tconst wallTime = ((performance.now() - startedAt) / 1000).toFixed(1);\n\tconst header = `${result.ok ? \"Script completed\" : \"Script failed\"}\\nWall time ${wallTime} seconds\\nOutput:\\n`;\n\tconst details = snapshot();\n\tif (truncated.fullOutputPath) details.fullOutputPath = truncated.fullOutputPath;\n\treturn {\n\t\tcontent: [{ type: \"text\", text: header }, ...truncated.items],\n\t\tdetails,\n\t\t...(modelUsage ? { usage: modelUsage } : {}),\n\t\t...(result.ok ? {} : { isError: true }),\n\t};\n}\n\n/**\n * Whether `query` names the namespace: its name, its script identifier (`mcp__dev-radius` is\n * `mcp__dev_radius`), or the part after its last `__` in either form (`dev-radius`, `dev_radius`).\n */\nfunction isNamespaceName(namespace: string, query: string): boolean {\n\tconst id = toCodemodeIdentifier(namespace);\n\tconst queryId = toCodemodeIdentifier(query);\n\tconst suffix = (name: string) => (name.includes(\"__\") ? name.slice(name.lastIndexOf(\"__\") + 2) : undefined);\n\treturn namespace === query || id === queryId || suffix(namespace) === query || suffix(id) === queryId;\n}\n\n/**\n * `searchTools()`, `describeTool()`, and `describeNamespace()`: ranked search and lookup over the\n * script's nested tools and their namespaces.\n */\nfunction createDiscoveryGlobals(\n\ttools: readonly AgentTool<any>[],\n\tsamples: ReadonlyMap<string, string>,\n\toptions: CodemodeToolOptions,\n): CodemodeTool[] {\n\tconst ranker = new Bm25Ranker();\n\tconst entry = (name: string) => ({ name: toCodemodeIdentifier(name), description: samples.get(name) ?? \"\" });\n\treturn [\n\t\t{\n\t\t\tname: \"searchTools\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [query, searchOptions] = args as [unknown, { limit?: unknown; namespace?: unknown } | undefined];\n\t\t\t\tif (typeof query !== \"string\") throw new Error(\"searchTools() expects a query string\");\n\t\t\t\tconst limit = searchOptions?.limit ?? DEFAULT_TOOL_SEARCH_LIMIT;\n\t\t\t\tif (typeof limit !== \"number\" || !Number.isInteger(limit) || limit <= 0) {\n\t\t\t\t\tthrow new Error(\"searchTools() limit must be a positive integer\");\n\t\t\t\t}\n\t\t\t\tconst namespace = searchOptions?.namespace;\n\t\t\t\tif (namespace !== undefined && namespace !== null && typeof namespace !== \"string\") {\n\t\t\t\t\tthrow new Error(\"searchTools() namespace must be a string\");\n\t\t\t\t}\n\t\t\t\tconst documents = tools.flatMap((tool) => {\n\t\t\t\t\tconst toolNamespace = options.getToolNamespace?.(tool.name);\n\t\t\t\t\tif (namespace && (!toolNamespace || !isNamespaceName(toolNamespace.name, namespace))) return [];\n\t\t\t\t\treturn [createToolSearchDocument(tool, toolNamespace)];\n\t\t\t\t});\n\t\t\t\treturn ranker.rank(query, documents, limit).map((match) => entry(match.name));\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"describeTool\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [name] = args as unknown[];\n\t\t\t\tif (typeof name !== \"string\") throw new Error(\"describeTool() expects a tool name\");\n\t\t\t\tconst tool = tools.find(\n\t\t\t\t\t(candidate) => candidate.name === name || toCodemodeIdentifier(candidate.name) === name,\n\t\t\t\t);\n\t\t\t\treturn tool ? samples.get(tool.name) : undefined;\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"describeNamespace\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [name] = args as unknown[];\n\t\t\t\tif (typeof name !== \"string\") throw new Error(\"describeNamespace() expects a namespace name\");\n\t\t\t\tlet namespace: ToolNamespace | undefined;\n\t\t\t\tconst names: string[] = [];\n\t\t\t\tfor (const tool of tools) {\n\t\t\t\t\tconst toolNamespace = options.getToolNamespace?.(tool.name);\n\t\t\t\t\tif (!toolNamespace || !isNamespaceName(toolNamespace.name, name)) continue;\n\t\t\t\t\tnamespace ??= toolNamespace;\n\t\t\t\t\tnames.push(toCodemodeIdentifier(tool.name));\n\t\t\t\t}\n\t\t\t\tif (!namespace) return undefined;\n\t\t\t\treturn {\n\t\t\t\t\tname: namespace.name,\n\t\t\t\t\t...(namespace.description ? { description: namespace.description } : {}),\n\t\t\t\t\t...(namespace.instructions ? { instructions: namespace.instructions } : {}),\n\t\t\t\t\ttools: names,\n\t\t\t\t};\n\t\t\t},\n\t\t},\n\t];\n}\n\n/**\n * `models.*` for scripts: the model registry methods declared in {@link MODEL_GLOBAL_DECLARATIONS}.\n * Classifier calls appear as nested call rows so the renderer shows them, and their usage goes to\n * `addUsage`.\n */\nfunction createModelGlobals(\n\tmodels: CodemodeModelRuntime,\n\ttoolCallId: string,\n\tcalls: CodemodeNestedCall[],\n\tpublish: () => void,\n\taddUsage: (usage: Usage) => void,\n): CodemodeTool[] {\n\tconst limit = createLimiter(MAX_CONCURRENT_MODEL_CALLS);\n\tlet classifyCount = 0;\n\tconst implementations: Record<string, CodemodeTool[\"execute\"]> = {\n\t\t\"models.getModelsOfType\": (args) => {\n\t\t\tconst [type, provider] = args as unknown[];\n\t\t\treturn models.getModelsOfType(toModelType(type), toProvider(provider)).map(toModelInfo);\n\t\t},\n\t\t\"models.getAvailableOfType\": async (args, { signal }) => {\n\t\t\tconst [type, provider] = args as unknown[];\n\t\t\tconst available = await models.getAvailableOfType(toModelType(type), toProvider(provider), { signal });\n\t\t\treturn available.map(toModelInfo);\n\t\t},\n\t\t\"models.getModelOfType\": (args) => {\n\t\t\tconst [type, provider, id] = args as unknown[];\n\t\t\tif (typeof provider !== \"string\" || typeof id !== \"string\") {\n\t\t\t\tthrow new Error(\"models.getModelOfType() expects a type, a provider, and an id\");\n\t\t\t}\n\t\t\tconst model = models.getModelOfType(toModelType(type), provider, id);\n\t\t\treturn model === undefined ? undefined : toModelInfo(model);\n\t\t},\n\t\t\"models.classify\": async (args, { signal }) => {\n\t\t\tconst [model, context] = args as unknown[];\n\t\t\tconst ref = model as { provider?: unknown; id?: unknown } | null;\n\t\t\tif (\n\t\t\t\ttypeof ref !== \"object\" ||\n\t\t\t\tref === null ||\n\t\t\t\ttypeof ref.provider !== \"string\" ||\n\t\t\t\ttypeof ref.id !== \"string\"\n\t\t\t) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"models.classify() expects a model from models.getModelOfType() or models.getAvailableOfType()\",\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Only provider and id count. A script-supplied baseUrl or headers must never receive the credentials.\n\t\t\tconst resolved = models.getModelOfType(\"classifier\", ref.provider, ref.id);\n\t\t\tif (!resolved) throw new Error(`Unknown classifier model \"${ref.provider}/${ref.id}\"`);\n\n\t\t\tconst record: CodemodeNestedCall = {\n\t\t\t\tid: `${toolCallId}/models.classify/${++classifyCount}`,\n\t\t\t\tname: \"models.classify\",\n\t\t\t\targs: `${resolved.provider}/${resolved.id}`,\n\t\t\t\tstatus: \"running\",\n\t\t\t};\n\t\t\tcalls.push(record);\n\t\t\tpublish();\n\t\t\tconst startedAt = performance.now();\n\t\t\tconst result = await limit(() => models.classify(resolved, context as ClassifierContext, { signal }));\n\t\t\trecord.durationMs = performance.now() - startedAt;\n\t\t\trecord.status = result.stopReason === \"stop\" ? \"ok\" : result.stopReason === \"aborted\" ? \"cancelled\" : \"error\";\n\t\t\tif (result.errorMessage) record.error = truncateText(result.errorMessage, ERROR_PREVIEW_CHARS);\n\t\t\tif (result.usage) {\n\t\t\t\trecord.cost = result.usage.cost.total;\n\t\t\t\taddUsage(result.usage);\n\t\t\t}\n\t\t\tpublish();\n\t\t\treturn result;\n\t\t},\n\t};\n\treturn MODEL_GLOBAL_DECLARATIONS.map((declaration) => ({\n\t\tname: declaration.name,\n\t\tspread: true,\n\t\texecute: implementations[declaration.name],\n\t}));\n}\n"]}
1
+ {"version":3,"file":"exec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azy.ts so the sandbox runtime only loads when a script runs.\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { AgentTool, AgentToolCallOutcome, AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type {\n\tAnyModel,\n\tClassifierContext,\n\tImageContent,\n\tImagesContext,\n\tModelType,\n\tModelTypeMap,\n\tTextContent,\n\tUsage,\n} from \"@earendil-works/pi-ai\";\nimport {\n\ttype CodemodeResult,\n\tCodemodeSandbox,\n\ttype CodemodeTool,\n\tloadQuickJSWasm,\n\tparseCodemodeSource,\n\trenderToolSample,\n\ttoCodemodeIdentifier,\n} from \"@earendil-works/pi-codemode\";\nimport { getCodemodeWorkerSpecifier, getQuickJSWasmPath } from \"../../config.ts\";\nimport type { ExtensionToolContext, ToolNamespace } from \"../../core/extensions/types.ts\";\nimport type { SessionEntry } from \"../../core/session-manager.ts\";\nimport { combineUsage } from \"../../core/usage-totals.ts\";\nimport { Bm25Ranker, createToolSearchDocument, DEFAULT_TOOL_SEARCH_LIMIT } from \"../tool-search/tool.ts\";\nimport {\n\tCODEMODE_DOCS_PATH,\n\tCODEMODE_STORE_ENTRY_TYPE,\n\ttype CodemodeModelRuntime,\n\ttype CodemodeNestedCall,\n\ttype CodemodeStoreEntryData,\n\ttype CodemodeToolDetails,\n\ttype CodemodeToolInput,\n\ttype CodemodeToolOptions,\n\tgetCodemodeCallableTools,\n\ttoCodemodeDeclaration,\n} from \"./tool.ts\";\n\nconst ARGS_PREVIEW_CHARS = 200;\nconst ERROR_PREVIEW_CHARS = 500;\n/** `models.classify()` and `models.generateImages()` calls one script may have in flight; `Promise.all` over many items queues the rest. */\nconst MAX_CONCURRENT_MODEL_CALLS = 4;\n/**\n * Heap limit for the QuickJS VM. The worker shares pi's process, so without a limit a runaway\n * script can grow to wasm32's 4 GiB and take the session down. Overruns throw\n * `InternalError: out of memory` inside the script.\n */\nconst CODEMODE_MEMORY_LIMIT_BYTES = 256 * 1024 * 1024;\nconst MODEL_TYPES: ReadonlySet<string> = new Set<ModelType>([\"chat\", \"image\", \"classifier\"]);\n\nfunction truncateText(text: string, maxChars: number): string {\n\treturn text.length > maxChars ? `${text.slice(0, maxChars - 3)}...` : text;\n}\n\nfunction previewArgs(args: unknown): string {\n\tif (args === undefined) return \"\";\n\ttry {\n\t\treturn truncateText(JSON.stringify(args) ?? \"\", ARGS_PREVIEW_CHARS);\n\t} catch {\n\t\treturn \"\";\n\t}\n}\n\nfunction textOf(result: AgentToolResult<unknown>): string {\n\treturn (result.content ?? [])\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n}\n\nfunction toModelType(value: unknown): ModelType {\n\tif (typeof value === \"string\" && MODEL_TYPES.has(value)) return value as ModelType;\n\tthrow new Error(`Unknown model type ${JSON.stringify(value)}. Use \"chat\", \"image\", or \"classifier\".`);\n}\n\nfunction toProvider(value: unknown): string | undefined {\n\tif (value === undefined || value === null) return undefined;\n\tif (typeof value !== \"string\") throw new Error(\"provider must be a string\");\n\treturn value;\n}\n\n/** Catalog entry for scripts. `headers` is dropped because models.json headers can carry credentials. */\nfunction toModelInfo(model: AnyModel): Record<string, unknown> {\n\tconst info: Record<string, unknown> = { ...model };\n\tdelete info.headers;\n\treturn info;\n}\n\n/** `an image`, `a classifier`. */\nfunction withArticle(word: string): string {\n\treturn `${/^[aeiou]/.test(word) ? \"an\" : \"a\"} ${word}`;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** A script value in an error message: `undefined`, `a string`, `an array`, or its keys (`{ prompt }`). */\nfunction describeValue(value: unknown): string {\n\tif (value === undefined || value === null) return String(value);\n\tif (Array.isArray(value)) return value.length === 0 ? \"an empty array\" : \"an array\";\n\tif (typeof value === \"object\") {\n\t\tconst keys = Object.keys(value);\n\t\tif (keys.length === 0) return \"{}\";\n\t\treturn `{ ${keys.slice(0, 6).join(\", \")}${keys.length > 6 ? \", ...\" : \"\"} }`;\n\t}\n\treturn typeof value === \"string\" ? \"a string\" : `a ${typeof value}`;\n}\n\nconst CLASSIFIER_CONTEXT_SHAPE =\n\t'{ state: { ... }, questions: { <id>: { type: \"choice\", instructions, criteria: { <label>: <meaning> } } | { type: \"score\", instructions, criteria: [<lowest level>, ..., <highest level>] } | { type: \"bool\", instructions, criteria: { true: <meaning>, false: <meaning> } } } }';\n\n/** Check a script's classifier context, so mistakes fail with the expected shape instead of a provider error. */\nfunction checkClassifierContext(context: unknown): ClassifierContext {\n\tconst fail = (problem: string) =>\n\t\tnew Error(\n\t\t\t`models.classify() ${problem}. Expected context: ${CLASSIFIER_CONTEXT_SHAPE}. See \"Classify\" in ${CODEMODE_DOCS_PATH}.`,\n\t\t);\n\tif (!isRecord(context)) throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);\n\tif (!isRecord(context.state)) throw fail(`context.state must be an object, got ${describeValue(context.state)}`);\n\tconst { questions } = context;\n\tif (!isRecord(questions) || Object.keys(questions).length === 0) {\n\t\tthrow fail(`context.questions must map question IDs to questions, got ${describeValue(questions)}`);\n\t}\n\tconst isStrings = (values: unknown[]) => values.length > 0 && values.every((value) => typeof value === \"string\");\n\tfor (const [id, question] of Object.entries(questions)) {\n\t\tconst at = `context.questions.${id}`;\n\t\tif (!isRecord(question)) throw fail(`${at} must be a question object, got ${describeValue(question)}`);\n\t\tif (typeof question.instructions !== \"string\") throw fail(`${at}.instructions must be a string`);\n\t\tconst { criteria } = question;\n\t\tif (question.type === \"choice\") {\n\t\t\tif (!isRecord(criteria) || !isStrings(Object.values(criteria))) {\n\t\t\t\tthrow fail(`${at} is a \"choice\" question, so criteria must map each label to its meaning`);\n\t\t\t}\n\t\t} else if (question.type === \"score\") {\n\t\t\tif (!Array.isArray(criteria) || !isStrings(criteria)) {\n\t\t\t\tthrow fail(`${at} is a \"score\" question, so criteria must list the levels as strings, lowest first`);\n\t\t\t}\n\t\t} else if (question.type === \"bool\") {\n\t\t\tif (!isRecord(criteria) || typeof criteria.true !== \"string\" || typeof criteria.false !== \"string\") {\n\t\t\t\tthrow fail(`${at} is a \"bool\" question, so criteria must be { true: string, false: string }`);\n\t\t\t}\n\t\t} else {\n\t\t\tthrow fail(`${at}.type must be \"choice\", \"score\", or \"bool\", got ${JSON.stringify(question.type)}`);\n\t\t}\n\t}\n\treturn context as unknown as ClassifierContext;\n}\n\n/** Check a script's image context, so mistakes such as `{ prompt }` fail with the expected shape. */\nfunction checkImagesContext(context: unknown): ImagesContext {\n\tconst fail = (problem: string) =>\n\t\tnew Error(\n\t\t\t`models.generateImages() ${problem}. Expected context: { input: [{ type: \"text\", text: <prompt> }, ...optional { type: \"image\", data: <base64>, mimeType } references] }. See \"Generate images\" in ${CODEMODE_DOCS_PATH}.`,\n\t\t);\n\tif (!isRecord(context)) throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);\n\tconst { input } = context;\n\tif (!Array.isArray(input) || input.length === 0) {\n\t\tthrow fail(`context.input must be a non-empty array of blocks, got ${describeValue(input)}`);\n\t}\n\tinput.forEach((block: unknown, index) => {\n\t\tif (isRecord(block) && block.type === \"text\" && typeof block.text === \"string\") return;\n\t\tif (\n\t\t\tisRecord(block) &&\n\t\t\tblock.type === \"image\" &&\n\t\t\ttypeof block.data === \"string\" &&\n\t\t\ttypeof block.mimeType === \"string\"\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tthrow fail(`context.input[${index}] must be a text or image block, got ${describeValue(block)}`);\n\t});\n\treturn context as unknown as ImagesContext;\n}\n\n/** The fields of `ClassifierResult` and `AssistantImages` that a nested call row reports. */\ninterface ModelCallResult {\n\tstopReason: \"stop\" | \"error\" | \"aborted\";\n\terrorMessage?: string;\n\tusage?: Usage;\n}\n\n/** Runs at most `limit` calls at once, in call order. */\nfunction createLimiter(limit: number): <T>(run: () => Promise<T>) => Promise<T> {\n\tlet active = 0;\n\tconst waiting: (() => void)[] = [];\n\treturn async (run) => {\n\t\tif (active >= limit) await new Promise<void>((resolve) => waiting.push(resolve));\n\t\tactive++;\n\t\ttry {\n\t\t\treturn await run();\n\t\t} finally {\n\t\t\tactive--;\n\t\t\twaiting.shift()?.();\n\t\t}\n\t};\n}\n\nfunction isStoreEntryData(data: unknown): data is CodemodeStoreEntryData {\n\tif (typeof data !== \"object\" || data === null) return false;\n\tconst { set, delete: deleted } = data as Partial<CodemodeStoreEntryData>;\n\treturn (\n\t\ttypeof set === \"object\" &&\n\t\tset !== null &&\n\t\tArray.isArray(deleted) &&\n\t\tdeleted.every((key: unknown) => typeof key === \"string\")\n\t);\n}\n\n/** Values of `load()`: the `codemode-store` entries on the branch, applied from the root. */\nexport function readCodemodeStore(branch: readonly SessionEntry[]): Record<string, unknown> {\n\tconst store = new Map<string, unknown>();\n\tfor (const entry of branch) {\n\t\tif (entry.type !== \"custom\" || entry.customType !== CODEMODE_STORE_ENTRY_TYPE || !isStoreEntryData(entry.data)) {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const key of entry.data.delete) store.delete(key);\n\t\tfor (const [key, value] of Object.entries(entry.data.set)) store.set(key, value);\n\t}\n\treturn Object.fromEntries(store);\n}\n\n/** Default token budget for script output. */\nconst DEFAULT_MAX_OUTPUT_TOKENS = 10_000;\n/** Characters per token when estimating. */\nconst CHARS_PER_TOKEN = 4;\n\n/** Like the script's `text()`: strings as is, other values as compact JSON. */\nfunction valueText(value: unknown): string {\n\tif (typeof value === \"string\") return value;\n\treturn JSON.stringify(value) ?? String(value);\n}\n\nfunction formatCallSummary(calls: readonly CodemodeNestedCall[]): string {\n\tif (calls.length === 0) return \"No tool calls were made.\";\n\treturn `Tool calls made before the failure (they are not undone): ${calls.map((call) => `${call.name} (${call.status})`).join(\", \")}`;\n}\n\nfunction formatError(result: Extract<CodemodeResult, { ok: false }>, calls: readonly CodemodeNestedCall[]): string {\n\tconst { error } = result;\n\tconst head =\n\t\terror.kind === \"script\"\n\t\t\t? (error.stack ?? `${error.name ?? \"Error\"}: ${error.message}`)\n\t\t\t: error.kind === \"timeout\"\n\t\t\t\t? `Script timed out: ${error.message}`\n\t\t\t\t: error.kind === \"aborted\"\n\t\t\t\t\t? `Script aborted: ${error.message}`\n\t\t\t\t\t: `Script sandbox failed: ${error.message}`;\n\treturn `${head}\\n\\n${formatCallSummary(calls)}`;\n}\n\n/** Write the full text output to a temp file, like bash does for truncated output. */\nasync function spillOutput(text: string): Promise<{ path: string } | { error: string }> {\n\tconst path = join(tmpdir(), `pi-codemode-${randomBytes(8).toString(\"hex\")}.txt`);\n\ttry {\n\t\tawait writeFile(path, text);\n\t\treturn { path };\n\t} catch (error) {\n\t\treturn { error: error instanceof Error ? error.message : String(error) };\n\t}\n}\n\n/**\n * Apply the token budget: when the combined text exceeds it, the text items become one\n * item that keeps the start and end of the text, and images follow it. The full text is written to\n * a temp file.\n */\nasync function truncateOutput(\n\titems: (TextContent | ImageContent)[],\n\tmaxTokens: number,\n): Promise<{ items: (TextContent | ImageContent)[]; fullOutputPath?: string }> {\n\tconst texts = items.filter((item): item is TextContent => item.type === \"text\").map((item) => item.text);\n\tconst combined = texts.join(\"\\n\");\n\tconst budget = maxTokens * CHARS_PER_TOKEN;\n\tif (texts.length === 0 || combined.length <= budget) return { items };\n\tconst headChars = Math.floor(budget / 2);\n\tconst tailChars = budget - headChars;\n\tconst removed = combined.length - headChars - tailChars;\n\tconst head = combined.slice(0, headChars);\n\tconst tail = tailChars > 0 ? combined.slice(-tailChars) : \"\";\n\tlet text = `Warning: truncated output (original token count: ${Math.ceil(combined.length / CHARS_PER_TOKEN)})\\nTotal output lines: ${combined.split(\"\\n\").length}\\n\\n${head}…${Math.ceil(removed / CHARS_PER_TOKEN)} tokens truncated…${tail}`;\n\tconst spilled = await spillOutput(combined);\n\ttext +=\n\t\t\"path\" in spilled\n\t\t\t? `\\n\\n[Full output: ${spilled.path} (read with offset/limit)]`\n\t\t\t: `\\n\\n[Could not save the full output: ${spilled.error}]`;\n\treturn {\n\t\titems: [{ type: \"text\", text }, ...items.filter((item) => item.type === \"image\")],\n\t\t...(\"path\" in spilled ? { fullOutputPath: spilled.path } : {}),\n\t};\n}\n\n/**\n * The value a script receives for a nested call: a tool that declares\n * `outputSchema` resolves to its `structuredContent`, also for error results that carry one (such\n * as MCP results with `isError`); any other tool resolves to its text content. Other failures\n * reject with the tool's error text.\n */\nfunction toScriptValue(tool: AgentTool<any>, outcome: AgentToolCallOutcome): unknown {\n\tconst { result } = outcome;\n\tif (tool.outputSchema && result.structuredContent !== undefined) return result.structuredContent;\n\tconst text = textOf(result);\n\tif (outcome.isError) throw new Error(text || `Tool \"${tool.name}\" failed`);\n\treturn text;\n}\n\n/**\n * Run one script. Without a session context (a plain Agent or a direct call) scripts cannot call\n * tools, `store()` starts empty, and writes are dropped.\n */\nexport async function executeCodemode(\n\ttoolCallId: string,\n\tinput: CodemodeToolInput,\n\tsignal: AbortSignal | undefined,\n\tonUpdate: ((result: AgentToolResult<CodemodeToolDetails>) => void) | undefined,\n\tctx: ExtensionToolContext | undefined,\n\toptions: CodemodeToolOptions = {},\n): Promise<AgentToolResult<CodemodeToolDetails>> {\n\tconst startedAt = performance.now();\n\tconst { code, options: sourceOptions } = parseCodemodeSource(input.code);\n\tconst calls: CodemodeNestedCall[] = [];\n\t// Usage of the script's `models.*` calls. Nested tool calls report theirs through the session.\n\tlet modelUsage: Usage | undefined;\n\t// Images returned by `models.generateImages()`, to notice a script that never shows them.\n\tlet generatedImages = 0;\n\tconst addGeneratedImages = (count: number) => {\n\t\tgeneratedImages += count;\n\t};\n\tconst addModelUsage = (usage: Usage) => {\n\t\tmodelUsage = modelUsage ? combineUsage(modelUsage, usage) : usage;\n\t};\n\n\tconst snapshot = (): CodemodeToolDetails => ({ calls: calls.map((call) => ({ ...call })) });\n\tconst publish = () => onUpdate?.({ content: [], details: snapshot() });\n\n\tconst callable = ctx ? getCodemodeCallableTools(ctx.tools) : [];\n\t// ALL_TOOLS entries carry the declaration.\n\tconst samples = new Map(callable.map((tool) => [tool.name, renderToolSample(toCodemodeDeclaration(tool))]));\n\tconst sandboxTools: CodemodeTool[] = callable.map((tool) => ({\n\t\tname: tool.name,\n\t\tdescription: samples.get(tool.name),\n\t\texecute: async (args, { signal: callSignal }) => {\n\t\t\tconst record: CodemodeNestedCall = {\n\t\t\t\tid: `${toolCallId}/?`,\n\t\t\t\tname: tool.name,\n\t\t\t\targs: previewArgs(args),\n\t\t\t\tstatus: \"running\",\n\t\t\t};\n\t\t\tcalls.push(record);\n\t\t\tpublish();\n\t\t\tconst callStartedAt = performance.now();\n\t\t\t// Only tools from ctx.tools are callable, so ctx is set here.\n\t\t\tif (!ctx) throw new Error(\"Tool calls need a session\");\n\t\t\tconst outcome = await ctx.executeTool(tool.name, args, { signal: callSignal });\n\t\t\trecord.id = outcome.toolCall.id;\n\t\t\trecord.durationMs = performance.now() - callStartedAt;\n\t\t\tif (outcome.isError) {\n\t\t\t\trecord.status = callSignal.aborted ? \"cancelled\" : \"error\";\n\t\t\t\trecord.error = truncateText(textOf(outcome.result) || `Tool \"${tool.name}\" failed`, ERROR_PREVIEW_CHARS);\n\t\t\t} else {\n\t\t\t\trecord.status = \"ok\";\n\t\t\t}\n\t\t\tpublish();\n\t\t\treturn toScriptValue(tool, outcome);\n\t\t},\n\t}));\n\n\tconst sandbox = new CodemodeSandbox({\n\t\ttools: sandboxTools,\n\t\tglobals: [\n\t\t\t...createDiscoveryGlobals(callable, samples, options),\n\t\t\t...(options.models && ctx\n\t\t\t\t? createModelGlobals(ctx.modelRegistry, toolCallId, calls, publish, addModelUsage, addGeneratedImages)\n\t\t\t\t: []),\n\t\t],\n\t\ttimeoutMs: sourceOptions.timeoutMs ?? Number.POSITIVE_INFINITY,\n\t\tmemoryLimitBytes: CODEMODE_MEMORY_LIMIT_BYTES,\n\t\twasm: loadQuickJSWasm(getQuickJSWasmPath()),\n\t\tworkerUrl: getCodemodeWorkerSpecifier(),\n\t});\n\n\tlet result: CodemodeResult;\n\ttry {\n\t\tconst store = ctx ? readCodemodeStore(ctx.sessionManager.getBranch()) : {};\n\t\tresult = await sandbox.execute(code, { signal, store });\n\t} finally {\n\t\tawait sandbox.close();\n\t}\n\t// Calls still marked running were cut off by the script ending, a timeout, or an abort.\n\tfor (const call of calls) {\n\t\tif (call.status === \"running\") call.status = \"cancelled\";\n\t}\n\n\tconst items: (TextContent | ImageContent)[] = result.output.map((item) =>\n\t\titem.type === \"text\" ? { type: \"text\", text: item.text } : item,\n\t);\n\tif (result.ok) {\n\t\tconst { set, delete: deleted } = result.storeWrites;\n\t\tif (Object.keys(set).length > 0 || deleted.length > 0) {\n\t\t\toptions.appendEntry?.(CODEMODE_STORE_ENTRY_TYPE, { set, delete: deleted });\n\t\t}\n\t\t// pi extension: a returned value is appended like text().\n\t\tif (result.value !== undefined) items.push({ type: \"text\", text: valueText(result.value) });\n\t} else {\n\t\titems.push({ type: \"text\", text: `Script error:\\n${formatError(result, calls)}` });\n\t}\n\tif (generatedImages > 0 && !items.some((item) => item.type === \"image\")) {\n\t\titems.push({\n\t\t\ttype: \"text\",\n\t\t\ttext: `Note: models.generateImages() returned ${generatedImages} image${generatedImages === 1 ? \"\" : \"s\"} that the script did not show. Show each image block of result.output with image(block).`,\n\t\t});\n\t}\n\n\tconst truncated = await truncateOutput(items, sourceOptions.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS);\n\tconst wallTime = ((performance.now() - startedAt) / 1000).toFixed(1);\n\tconst header = `${result.ok ? \"Script completed\" : \"Script failed\"}\\nWall time ${wallTime} seconds\\nOutput:\\n`;\n\tconst details = snapshot();\n\tif (truncated.fullOutputPath) details.fullOutputPath = truncated.fullOutputPath;\n\treturn {\n\t\tcontent: [{ type: \"text\", text: header }, ...truncated.items],\n\t\tdetails,\n\t\t...(modelUsage ? { usage: modelUsage } : {}),\n\t\t...(result.ok ? {} : { isError: true }),\n\t};\n}\n\n/**\n * Whether `query` names the namespace: its name, its script identifier (`mcp__dev-radius` is\n * `mcp__dev_radius`), or the part after its last `__` in either form (`dev-radius`, `dev_radius`).\n */\nfunction isNamespaceName(namespace: string, query: string): boolean {\n\tconst id = toCodemodeIdentifier(namespace);\n\tconst queryId = toCodemodeIdentifier(query);\n\tconst suffix = (name: string) => (name.includes(\"__\") ? name.slice(name.lastIndexOf(\"__\") + 2) : undefined);\n\treturn namespace === query || id === queryId || suffix(namespace) === query || suffix(id) === queryId;\n}\n\n/**\n * `searchTools()`, `describeTool()`, and `describeNamespace()`: ranked search and lookup over the\n * script's nested tools and their namespaces.\n */\nfunction createDiscoveryGlobals(\n\ttools: readonly AgentTool<any>[],\n\tsamples: ReadonlyMap<string, string>,\n\toptions: CodemodeToolOptions,\n): CodemodeTool[] {\n\tconst ranker = new Bm25Ranker();\n\tconst entry = (name: string) => ({ name: toCodemodeIdentifier(name), description: samples.get(name) ?? \"\" });\n\treturn [\n\t\t{\n\t\t\tname: \"searchTools\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [query, searchOptions] = args as [unknown, { limit?: unknown; namespace?: unknown } | undefined];\n\t\t\t\tif (typeof query !== \"string\") throw new Error(\"searchTools() expects a query string\");\n\t\t\t\tconst limit = searchOptions?.limit ?? DEFAULT_TOOL_SEARCH_LIMIT;\n\t\t\t\tif (typeof limit !== \"number\" || !Number.isInteger(limit) || limit <= 0) {\n\t\t\t\t\tthrow new Error(\"searchTools() limit must be a positive integer\");\n\t\t\t\t}\n\t\t\t\tconst namespace = searchOptions?.namespace;\n\t\t\t\tif (namespace !== undefined && namespace !== null && typeof namespace !== \"string\") {\n\t\t\t\t\tthrow new Error(\"searchTools() namespace must be a string\");\n\t\t\t\t}\n\t\t\t\tconst documents = tools.flatMap((tool) => {\n\t\t\t\t\tconst toolNamespace = options.getToolNamespace?.(tool.name);\n\t\t\t\t\tif (namespace && (!toolNamespace || !isNamespaceName(toolNamespace.name, namespace))) return [];\n\t\t\t\t\treturn [createToolSearchDocument(tool, toolNamespace)];\n\t\t\t\t});\n\t\t\t\treturn ranker.rank(query, documents, limit).map((match) => entry(match.name));\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"describeTool\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [name] = args as unknown[];\n\t\t\t\tif (typeof name !== \"string\") throw new Error(\"describeTool() expects a tool name\");\n\t\t\t\tconst tool = tools.find(\n\t\t\t\t\t(candidate) => candidate.name === name || toCodemodeIdentifier(candidate.name) === name,\n\t\t\t\t);\n\t\t\t\treturn tool ? samples.get(tool.name) : undefined;\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"describeNamespace\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [name] = args as unknown[];\n\t\t\t\tif (typeof name !== \"string\") throw new Error(\"describeNamespace() expects a namespace name\");\n\t\t\t\tlet namespace: ToolNamespace | undefined;\n\t\t\t\tconst names: string[] = [];\n\t\t\t\tfor (const tool of tools) {\n\t\t\t\t\tconst toolNamespace = options.getToolNamespace?.(tool.name);\n\t\t\t\t\tif (!toolNamespace || !isNamespaceName(toolNamespace.name, name)) continue;\n\t\t\t\t\tnamespace ??= toolNamespace;\n\t\t\t\t\tnames.push(toCodemodeIdentifier(tool.name));\n\t\t\t\t}\n\t\t\t\tif (!namespace) return undefined;\n\t\t\t\treturn {\n\t\t\t\t\tname: namespace.name,\n\t\t\t\t\t...(namespace.description ? { description: namespace.description } : {}),\n\t\t\t\t\t...(namespace.instructions ? { instructions: namespace.instructions } : {}),\n\t\t\t\t\ttools: names,\n\t\t\t\t};\n\t\t\t},\n\t\t},\n\t];\n}\n\n/**\n * `models.*` for scripts: the model registry methods documented in docs/codemode.md.\n * Classifier and image calls appear as nested call rows so the renderer shows them, and their usage\n * goes to `addUsage`. Rows show only the model, never prompts or image data.\n */\nfunction createModelGlobals(\n\tmodels: CodemodeModelRuntime,\n\ttoolCallId: string,\n\tcalls: CodemodeNestedCall[],\n\tpublish: () => void,\n\taddUsage: (usage: Usage) => void,\n\taddGeneratedImages: (count: number) => void,\n): CodemodeTool[] {\n\tconst limit = createLimiter(MAX_CONCURRENT_MODEL_CALLS);\n\tlet callCount = 0;\n\n\t/**\n\t * Resolve the script's model by provider and id only, check the context, then run the call as a\n\t * nested call row. A script-supplied baseUrl or headers must never receive the credentials.\n\t */\n\tconst runModelCall = async <TType extends \"classifier\" | \"image\", TContext, TResult extends ModelCallResult>(\n\t\tname: string,\n\t\ttype: TType,\n\t\t[model, context]: unknown[],\n\t\tcheckContext: (context: unknown) => TContext,\n\t\trun: (resolved: ModelTypeMap[TType], context: TContext) => Promise<TResult>,\n\t): Promise<TResult> => {\n\t\tconst listHint = `List the ${type} models you can use with models.getAvailableOfType(\"${type}\").`;\n\t\tif (!isRecord(model) || typeof model.provider !== \"string\" || typeof model.id !== \"string\") {\n\t\t\t// undefined arrives as null: spread arguments cross the sandbox as a JSON array.\n\t\t\tconst undefinedHint =\n\t\t\t\tmodel === undefined || model === null\n\t\t\t\t\t? \" models.getModelOfType() returns undefined for an unknown provider or id.\"\n\t\t\t\t\t: \"\";\n\t\t\tthrow new Error(\n\t\t\t\t`${name}() expects ${withArticle(type)} model as its first argument, got ${describeValue(model)}.${undefinedHint} ${listHint}`,\n\t\t\t);\n\t\t}\n\t\tconst { provider, id } = model;\n\t\tconst ref = `${provider}/${id}`;\n\t\tconst resolved = models.getModelOfType(type, provider, id);\n\t\tif (!resolved) {\n\t\t\tconst actualType = [...MODEL_TYPES].find(\n\t\t\t\t(other) => other !== type && models.getModelOfType(other as ModelType, provider, id) !== undefined,\n\t\t\t);\n\t\t\tthrow new Error(\n\t\t\t\tactualType\n\t\t\t\t\t? `\"${ref}\" is ${withArticle(actualType)} model, not ${withArticle(type)} model. ${listHint}`\n\t\t\t\t\t: `Unknown ${type} model \"${ref}\". ${listHint}`,\n\t\t\t);\n\t\t}\n\t\tconst checked = checkContext(context);\n\n\t\tconst record: CodemodeNestedCall = {\n\t\t\tid: `${toolCallId}/${name}/${++callCount}`,\n\t\t\tname,\n\t\t\targs: `${resolved.provider}/${resolved.id}`,\n\t\t\tstatus: \"running\",\n\t\t};\n\t\tcalls.push(record);\n\t\tpublish();\n\t\tconst startedAt = performance.now();\n\t\tconst result = await limit(() => run(resolved, checked));\n\t\trecord.durationMs = performance.now() - startedAt;\n\t\trecord.status = result.stopReason === \"stop\" ? \"ok\" : result.stopReason === \"aborted\" ? \"cancelled\" : \"error\";\n\t\tif (result.errorMessage) record.error = truncateText(result.errorMessage, ERROR_PREVIEW_CHARS);\n\t\tif (result.usage) {\n\t\t\trecord.cost = result.usage.cost.total;\n\t\t\taddUsage(result.usage);\n\t\t}\n\t\tpublish();\n\t\treturn result;\n\t};\n\tconst implementations: Record<string, CodemodeTool[\"execute\"]> = {\n\t\t\"models.getModelsOfType\": (args) => {\n\t\t\tconst [type, provider] = args as unknown[];\n\t\t\treturn models.getModelsOfType(toModelType(type), toProvider(provider)).map(toModelInfo);\n\t\t},\n\t\t\"models.getAvailableOfType\": async (args, { signal }) => {\n\t\t\tconst [type, provider] = args as unknown[];\n\t\t\tconst available = await models.getAvailableOfType(toModelType(type), toProvider(provider), { signal });\n\t\t\treturn available.map(toModelInfo);\n\t\t},\n\t\t\"models.getModelOfType\": (args) => {\n\t\t\tconst [type, provider, id] = args as unknown[];\n\t\t\tif (typeof provider !== \"string\" || typeof id !== \"string\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`models.getModelOfType(type, provider, id) expects three strings, got (${(args as unknown[]).map(describeValue).join(\", \")}). The provider and the id are separate arguments, for example models.getModelOfType(\"classifier\", \"typesafe\", \"jev-latest\").`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst model = models.getModelOfType(toModelType(type), provider, id);\n\t\t\treturn model === undefined ? undefined : toModelInfo(model);\n\t\t},\n\t\t\"models.classify\": (args, { signal }) =>\n\t\t\trunModelCall(\"models.classify\", \"classifier\", args as unknown[], checkClassifierContext, (resolved, context) =>\n\t\t\t\tmodels.classify(resolved, context, { signal }),\n\t\t\t),\n\t\t\"models.generateImages\": (args, { signal }) =>\n\t\t\trunModelCall(\n\t\t\t\t\"models.generateImages\",\n\t\t\t\t\"image\",\n\t\t\t\targs as unknown[],\n\t\t\t\tcheckImagesContext,\n\t\t\t\tasync (resolved, context) => {\n\t\t\t\t\tconst result = await models.generateImages(resolved, context, { signal });\n\t\t\t\t\taddGeneratedImages(result.output.filter((block) => block.type === \"image\").length);\n\t\t\t\t\treturn result;\n\t\t\t\t},\n\t\t\t),\n\t};\n\treturn Object.entries(implementations).map(([name, execute]) => ({ name, spread: true, execute }));\n}\n"]}
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * The `codemode` tool: the model writes JavaScript that calls other tools. Scripts use `tools`,
3
3
  * `ALL_TOOLS`, `text()`, `image()`, `exit()`, `store()`/`load()`, `console.*`, and `return <value>`,
4
- * may start with a `// @options:` line, and reach the model catalog and classifiers through
5
- * `models.*`. Results start with a "Script completed" or "Script failed" header.
4
+ * may start with a `// @options:` line, and reach the model catalog, classifiers, and image models
5
+ * through `models.*`. Results start with a "Script completed" or "Script failed" header.
6
6
  *
7
7
  * Scripts can call the agent loop's nested tools: active `direct` tools and every `codemode` or
8
8
  * `deferred` tool. Nested calls run through the agent loop's tool pipeline (`ctx.executeTool`), so
@@ -34,7 +34,7 @@ export interface CodemodeStoreEntryData {
34
34
  delete: string[];
35
35
  }
36
36
  /** The part of the model registry that scripts reach through `models`. */
37
- export type CodemodeModelRuntime = Pick<ModelRegistry, "getModelsOfType" | "getAvailableOfType" | "getModelOfType" | "classify">;
37
+ export type CodemodeModelRuntime = Pick<ModelRegistry, "getModelsOfType" | "getAvailableOfType" | "getModelOfType" | "classify" | "generateImages">;
38
38
  export interface CodemodeToolOptions {
39
39
  /** Namespace of a tool, for `searchTools()` ranking and its `namespace` filter. */
40
40
  getToolNamespace?: (toolName: string) => ToolNamespace | undefined;
@@ -82,11 +82,11 @@ export interface CodemodeToolDetails {
82
82
  fullOutputPath?: string;
83
83
  }
84
84
  export declare const codemodeToolSystemPromptContribution: {
85
- readonly snippet: "Run JavaScript that calls other tools (chains, loops, Promise.all, filtering large results)";
86
- readonly guidelines: readonly ["Use codemode to batch or chain several tool calls, or to filter large tool output down to what you need, instead of issuing many individual tool calls. Batch independent calls in one codemode call using await Promise.allSettled([...])."];
85
+ readonly snippet: "Run JavaScript that calls other tools";
86
+ readonly guidelines: readonly ["Use codemode to batch independent tool calls (Promise.allSettled), chain them, or filter large output, instead of many separate calls."];
87
87
  };
88
- /** Declarations of the `models` globals; codemode-execute.ts implements them. */
89
- export declare const MODEL_GLOBAL_DECLARATIONS: readonly Omit<CodemodeTool, "execute">[];
88
+ /** The reference for scripts: globals, tool results, `store()`, the `models` API, and limits. */
89
+ export declare const CODEMODE_DOCS_PATH: string;
90
90
  /** Default for {@link CodemodeDescriptionOptions.inlineBudget}, in estimated tokens. */
91
91
  export declare const DEFAULT_CODEMODE_INLINE_BUDGET = 3000;
92
92
  /** What a script sees of a tool. Tools without an output schema resolve to their text output. */
@@ -1 +1 @@
1
- {"version":3,"file":"tool.d.ts","sourceRoot":"","sources":["../../../src/extensions/codemode/tool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAC/D,OAAO,KAAK,EAAsB,YAAY,EAAE,MAAM,6BAA6B,CAAC;AASpF,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,KAAK,EACX,cAAc,EACd,QAAQ,EAGR,aAAa,EACb,MAAM,gCAAgC,CAAC;AACxC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAKnE,eAAO,MAAM,kBAAkB,aAAa,CAAC;AAE7C,+FAA+F;AAC/F,eAAO,MAAM,yB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CAAC,IAAI,EAAE,SAAS,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,YAAY,EAAE,SAAS,CAAC,CAOzF;AAED,iFAAiF;AACjF,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,SAAS,SAAS,CAAC,GAAG,CAAC,EAAE,GAAG,SAAS,CAAC,GAAG,CAAC,EAAE,CAE3F;AAED,MAAM,WAAW,0BAA0B;IAC1C,gFAAgF;IAChF,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,iGAAiG;IACjG,UAAU,CAAC,EAAE,WAAW,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IAChD,6FAA6F;IAC7F,QAAQ,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IAC/B;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB;AA6CD;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CACxC,KAAK,EAAE,SAAS,SAAS,CAAC,GAAG,CAAC,EAAE,EAChC,OAAO,GAAE,0BAA+B,GACtC,MAAM,CA+CR;AA8ED,wBAAgB,4BAA4B,CAC3C,OAAO,GAAE,mBAAwB,GAC/B,cAAc,CAAC,OAAO,cAAc,EAAE,mBAAmB,GAAG,SAAS,CAAC,CAmBxE;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CACjC,KAAK,GAAE,SAAS,SAAS,CAAC,GAAG,CAAC,EAAO,EACrC,OAAO,GAAE,mBAAwB,GAC/B,SAAS,CAAC,OAAO,cAAc,CAAC,CASlC"}
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * The `codemode` tool: the model writes JavaScript that calls other tools. Scripts use `tools`,
3
3
  * `ALL_TOOLS`, `text()`, `image()`, `exit()`, `store()`/`load()`, `console.*`, and `return <value>`,
4
- * may start with a `// @options:` line, and reach the model catalog and classifiers through
5
- * `models.*`. Results start with a "Script completed" or "Script failed" header.
4
+ * may start with a `// @options:` line, and reach the model catalog, classifiers, and image models
5
+ * through `models.*`. Results start with a "Script completed" or "Script failed" header.
6
6
  *
7
7
  * Scripts can call the agent loop's nested tools: active `direct` tools and every `codemode` or
8
8
  * `deferred` tool. Nested calls run through the agent loop's tool pipeline (`ctx.executeTool`), so
@@ -20,9 +20,11 @@
20
20
  * calls; successful scripts append their writes to the session as `codemode-store` custom entries,
21
21
  * so each branch sees the values written on its own path.
22
22
  */
23
- import { MCP_TYPESCRIPT_PREAMBLE, mcpStructuredContentSchema, renderDeclarations, renderToolSample, toCodemodeIdentifier, } from "@earendil-works/pi-codemode/declarations";
23
+ import { join } from "node:path";
24
+ import { MCP_TYPESCRIPT_PREAMBLE, mcpStructuredContentSchema, renderToolOutputType, renderToolSample, toCodemodeIdentifier, } from "@earendil-works/pi-codemode/declarations";
24
25
  import { CODEMODE_SOURCE_GRAMMAR } from "@earendil-works/pi-codemode/source";
25
26
  import { Type } from "typebox";
27
+ import { getDocsPath } from "../../config.js";
26
28
  import { wrapToolDefinition } from "../../core/tools/tool-definition-wrapper.js";
27
29
  import { loadCodemodeExecutor } from "./execute.lazy.js";
28
30
  import { codemodeRenderers } from "./renderer.js";
@@ -32,7 +34,7 @@ export const CODEMODE_STORE_ENTRY_TYPE = "codemode-store";
32
34
  const TEXT_OUTPUT_SCHEMA = { type: "string" };
33
35
  export const codemodeSchema = Type.Object({
34
36
  code: Type.String({
35
- description: 'Raw JavaScript source. Top-level await and return work. May start with a `// @options: {"max_output_tokens": 1000}` line.',
37
+ description: "Raw JavaScript source.",
36
38
  }),
37
39
  });
38
40
  /**
@@ -43,98 +45,29 @@ export function isCodemodeTool(tool) {
43
45
  return tool.name === CODEMODE_TOOL_NAME && tool.parameters === codemodeSchema;
44
46
  }
45
47
  export const codemodeToolSystemPromptContribution = {
46
- snippet: "Run JavaScript that calls other tools (chains, loops, Promise.all, filtering large results)",
48
+ snippet: "Run JavaScript that calls other tools",
47
49
  guidelines: [
48
- "Use codemode to batch or chain several tool calls, or to filter large tool output down to what you need, instead of issuing many individual tool calls. Batch independent calls in one codemode call using await Promise.allSettled([...]).",
50
+ "Use codemode to batch independent tool calls (Promise.allSettled), chain them, or filter large output, instead of many separate calls.",
49
51
  ],
50
52
  };
51
- const DESCRIPTION_INTRO = `Run JavaScript code to orchestrate/compose tool calls
52
- - Evaluates the provided JavaScript code in a fresh QuickJS sandbox as the body of an async function: top-level \`await\` and \`return\` work.
53
- - All nested tools are available on the global \`tools\` object, for example \`await tools.read(...)\`. Tool names are exposed as normalized JavaScript identifiers, for example \`await tools.mcp__ologs__get_profile(...)\`.
54
- - Nested tool methods take an object as their input argument.
55
- - Nested tools return either an object or a string, based on the description.
56
- - A nested tool call that fails, is blocked, or gets invalid arguments rejects with an Error carrying the tool's error text.
57
- - Runs raw JavaScript -- no Node, no file system, no network access, no timers.
58
- - Accepts raw JavaScript source text, not JSON, quoted strings, or markdown code fences.
59
- - You may optionally start the tool input with a first line like \`// @options: {"max_output_tokens": 1000, "timeout_ms": 60000}\`.
60
- - \`max_output_tokens\` sets the token budget for the script's output. Defaults to 10000 tokens.
61
- - \`timeout_ms\` sets a hard deadline for the whole script. By default there is none.
62
- - When the JS code is fully evaluated, calls that are still running are cancelled and unawaited promises are silently discarded.
63
- - Tool calls are real and have side effects. If the script fails partway, earlier calls are not undone.
64
- - Scripts have a 256 MB memory limit; exceeding it throws \`InternalError: out of memory\`. Filter or aggregate large data instead of accumulating it.
65
-
66
- - Global helpers:
67
- - \`exit()\`: Immediately ends the current script successfully (like an early return from the top level).
68
- - \`text(value: string | number | boolean | undefined | null)\`: Appends a text item. Non-string values are stringified with \`JSON.stringify(...)\` when possible.
69
- - \`image(imageUrlOrItem: string | { image_url: string } | ImageContent)\`: Appends an image item. \`image_url\` should be a base64-encoded \`data:\` URL. To forward an MCP tool image, pass an individual \`ImageContent\` block from \`result.content\`, for example \`image(result.content[0])\`.
70
- - \`store(key: string, value: any)\`: stores a serializable value under a string key for later \`codemode\` calls in the same session. Storing \`undefined\` deletes the key. Writes are kept only if the script succeeds.
71
- - \`load(key: string)\`: returns the stored value for a string key, or \`undefined\` if it is missing.
72
- - \`ALL_TOOLS\`: metadata for the enabled nested tools as \`{ name, description }\` entries.
73
- - \`searchTools(query: string, options?: { limit?: number; namespace?: string })\`: resolves to the nested tools that best match the query (BM25, default limit 8), as \`{ name, description }\` entries like \`ALL_TOOLS\`.
74
- - \`describeTool(name: string)\`: resolves to the description and declaration of a nested tool, or \`undefined\`.
75
- - \`describeNamespace(name: string)\`: resolves to \`{ name, description?, instructions?, tools }\` for a namespace of nested tools, such as an MCP server: its usage instructions and the names of its tools, or \`undefined\`.
76
- - \`console.log(...)\` and the other \`console\` methods append a text item like \`text()\`.
77
- - \`return value\` at the top level appends the value like \`text()\`.`;
78
- const MODEL_TYPES = `type ModelType = "chat" | "image" | "classifier";
79
- /** A model catalog entry. \`provider\` and \`id\` identify it; the other fields depend on the type. */
80
- interface ModelInfo {
81
- type?: ModelType;
82
- provider: string;
83
- id: string;
84
- name: string;
85
- api: string;
86
- input: ("text" | "image")[];
87
- contextWindow?: number;
88
- [key: string]: unknown;
89
- }
90
- type ClassifierQuestion =
91
- | { type: "choice"; instructions: string; criteria: Record<string, string> }
92
- | { type: "score"; instructions: string; criteria: string[] }
93
- | { type: "bool"; instructions: string; criteria: { true: string; false: string } };
94
- type ClassifierAnswer =
95
- | { type: "choice"; choice: string; probabilities: Record<string, number>; confidence: number }
96
- | { type: "score"; score: number; confidence: number }
97
- | { type: "bool"; probability: number };
98
- interface ClassifierContext {
99
- state: Record<string, unknown>;
100
- questions: Record<string, ClassifierQuestion>;
53
+ /** The reference for scripts: globals, tool results, `store()`, the `models` API, and limits. */
54
+ export const CODEMODE_DOCS_PATH = join(getDocsPath(), "codemode.md");
55
+ const DESCRIPTION_INTRO = `Run JavaScript that calls other tools. The input is raw JavaScript (not JSON, no code fence), run as an async function body in a QuickJS sandbox: top-level \`await\` and \`return\` work. No Node, file system, network, or timers.
56
+ - \`await tools.<name>({ ...args })\` resolves to a string, or an object if the tool's declaration says so, and rejects with an Error on failure. Calls still running when the script ends are cancelled.
57
+ - Optional first line: \`// @options: {"max_output_tokens": 10000, "timeout_ms": 60000}\``;
58
+ /** One line per global. The details live in {@link CODEMODE_DOCS_PATH}. */
59
+ function describeGlobals(models) {
60
+ const lines = [
61
+ "Globals:",
62
+ "- `text(value)`, `image(dataUrlOrImageBlock)`, `console.log(...)`, and top-level `return` add output; `exit()` ends the script.",
63
+ "- `store(key, value)` and `load(key)` keep JSON values across codemode calls.",
64
+ "- `ALL_TOOLS`, `searchTools(query, { limit?, namespace? })`, `describeTool(name)`, `describeNamespace(name)`: find unlisted tools, such as MCP tools.",
65
+ ];
66
+ if (models) {
67
+ lines.push(`- \`models\`: classifiers and image generation. Read ${CODEMODE_DOCS_PATH} first.`);
68
+ }
69
+ return lines.join("\n");
101
70
  }
102
- interface ClassifierResult {
103
- api: string;
104
- provider: string;
105
- model: string;
106
- answers: Record<string, ClassifierAnswer>;
107
- /** Set when the service reports token counts. Cost is in USD. */
108
- usage?: { input: number; output: number; totalTokens: number; cost: { total: number } };
109
- stopReason: "stop" | "error" | "aborted";
110
- errorMessage?: string;
111
- timestamp: number;
112
- }`;
113
- /** Declarations of the `models` globals; codemode-execute.ts implements them. */
114
- export const MODEL_GLOBAL_DECLARATIONS = [
115
- {
116
- name: "models.getModelsOfType",
117
- description: "Every known model of a type, optionally for one provider.",
118
- signature: "(type: ModelType, provider?: string): Promise<ModelInfo[]>",
119
- },
120
- {
121
- name: "models.getAvailableOfType",
122
- description: "Models of a type whose provider has working credentials.",
123
- signature: "(type: ModelType, provider?: string): Promise<ModelInfo[]>",
124
- },
125
- {
126
- name: "models.getModelOfType",
127
- description: "One catalog entry, or undefined.",
128
- signature: "(type: ModelType, provider: string, id: string): Promise<ModelInfo | undefined>",
129
- },
130
- {
131
- name: "models.classify",
132
- description: "Run a classifier model on one state. Only `provider` and `id` of `model` are used. Provider errors do not throw: check `stopReason` and `errorMessage`.",
133
- signature: "(model: ModelInfo, context: ClassifierContext): Promise<ClassifierResult>",
134
- },
135
- ];
136
- const DEFERRED_TOOLS_GUIDANCE = `Some nested tools may be omitted from this description, such as deferred tools and MCP tools. They are still available on the global \`tools\` object and listed in \`ALL_TOOLS\`.
137
- To find one, call \`await searchTools(query)\` (pass \`{ namespace }\` to search one namespace), or filter \`ALL_TOOLS\` by \`name\` and \`description\`. \`await describeNamespace(name)\` returns a namespace's usage instructions and the names of its tools.`;
138
71
  /** Default for {@link CodemodeDescriptionOptions.inlineBudget}, in estimated tokens. */
139
72
  export const DEFAULT_CODEMODE_INLINE_BUDGET = 3000;
140
73
  /** Characters per token when estimating the cost of a tool section. */
@@ -206,17 +139,10 @@ export function createCodemodeDescription(tools, options = {}) {
206
139
  }
207
140
  const ordered = [...groups.values()].sort((a, b) => a.namespace === undefined ? -1 : b.namespace === undefined ? 1 : a.namespace.name.localeCompare(b.namespace.name));
208
141
  const shown = selectCatalog(ordered, options.inlineBudget);
209
- const sections = [DESCRIPTION_INTRO, DEFERRED_TOOLS_GUIDANCE];
142
+ const sections = [DESCRIPTION_INTRO, describeGlobals(options.models === true)];
210
143
  if (declarations.some((declaration) => shown.has(declaration.name) && mcpStructuredContentSchema(declaration.outputSchema) !== undefined)) {
211
144
  sections.push(`Shared MCP Types:\n\`\`\`ts\n${MCP_TYPESCRIPT_PREAMBLE}\n\`\`\``);
212
145
  }
213
- if (options.models) {
214
- const noop = () => undefined;
215
- const models = renderDeclarations({
216
- globals: MODEL_GLOBAL_DECLARATIONS.map((global) => ({ ...global, execute: noop })),
217
- });
218
- sections.push(`Model API:\n\`\`\`ts\n${MODEL_TYPES}\n\n${models}\n\`\`\``);
219
- }
220
146
  if (declarations.length === 0)
221
147
  return sections.join("\n\n");
222
148
  const toolSections = ["Nested tools:"];
@@ -238,9 +164,36 @@ export function createCodemodeDescription(tools, options = {}) {
238
164
  sections.push(toolSections.join("\n\n"));
239
165
  return sections.join("\n\n");
240
166
  }
167
+ /**
168
+ * What a script call resolves to, in one line: `a string`, the field names of an object
169
+ * (`{ output, exit_code, full_output_path? }`), or the rendered type for anything else.
170
+ */
171
+ function describeOutput(schema) {
172
+ const type = renderToolOutputType(schema);
173
+ if (type === "string")
174
+ return "a string";
175
+ const object = typeof schema === "object" ? schema : undefined;
176
+ const properties = object?.properties;
177
+ if (object?.type === "object" &&
178
+ typeof properties === "object" &&
179
+ properties !== null &&
180
+ mcpStructuredContentSchema(schema) === undefined) {
181
+ const required = new Set(Array.isArray(object.required) ? object.required : []);
182
+ const fields = Object.keys(properties).map((name) => (required.has(name) ? name : `${name}?`));
183
+ return `\`{ ${fields.join(", ")} }\``;
184
+ }
185
+ return `\`${type.replace(/\s+/g, " ")}\``;
186
+ }
187
+ /**
188
+ * A declared tool's description followed by how scripts call it and what the call resolves to. The
189
+ * arguments are the tool's declared parameters, so they are not repeated.
190
+ */
191
+ function describeScriptCall(tool) {
192
+ return `${tool.description.trim()}\n\nCodemode: \`tools.${toCodemodeIdentifier(tool.name)}(args)\` resolves to ${describeOutput(toCodemodeDeclaration(tool).outputSchema)}.`;
193
+ }
241
194
  /**
242
195
  * How the codemode tool presents tools that are both declared and callable from scripts:
243
- * - `on`: their descriptions get the codemode declaration appended, and the codemode description
196
+ * - `on`: their descriptions say how scripts call them, and the codemode description
244
197
  * lists only the callable tools without `direct` exposure.
245
198
  * - `only`: the codemode description lists every callable tool, and requests leave out the
246
199
  * declarations of active `direct` tools.
@@ -257,7 +210,7 @@ function prepareCodemodeLoadout(loadout, options) {
257
210
  if (mode === "on") {
258
211
  for (const tool of loadout.declared) {
259
212
  if (callableNames.has(tool.name))
260
- descriptions[tool.name] = renderToolSample(toCodemodeDeclaration(tool));
213
+ descriptions[tool.name] = describeScriptCall(tool);
261
214
  }
262
215
  }
263
216
  const listed = mode === "only" ? callable : callable.filter((tool) => !isDirect(tool));