pi-namespace-patch 1.0.2-namespace.2 → 1.0.3-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 (84) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +8 -8
  3. package/dist/bundle/chunks/{anthropic-messages-MVG2FL56.js → anthropic-messages-Y22YDKSW.js} +1 -1
  4. package/dist/bundle/chunks/azure-openai-responses-YJDJIIDQ.js +2 -0
  5. package/dist/bundle/chunks/chunk-22CYIUS4.js +2 -0
  6. package/dist/bundle/chunks/{chunk-SYF2TF6W.js → chunk-2VBQLN7Y.js} +3 -3
  7. package/dist/bundle/chunks/{chunk-ZSI3BL5Q.js → chunk-6DBOMCBS.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-2KAZSACP.js → chunk-7TP2J6F2.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-6FX7UEPL.js → chunk-AXOERKKW.js} +3 -3
  10. package/dist/bundle/chunks/{chunk-OSKPX3Z5.js → chunk-C47CLQZK.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-DN3QEIXS.js → chunk-DEVCTHZR.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-IKZJX7ZT.js → chunk-HQHD6PZI.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-OLBCNJCL.js → chunk-ITAWMMSC.js} +30 -30
  14. package/dist/bundle/chunks/chunk-KJUDFE6Y.js +11 -0
  15. package/dist/bundle/chunks/{chunk-WCQZGZ6I.js → chunk-PSQJVYXD.js} +1 -1
  16. package/dist/bundle/chunks/{chunk-G7EDXK4D.js → chunk-TAOL3JFA.js} +1 -1
  17. package/dist/bundle/chunks/chunk-UBHCV62G.js +20 -0
  18. package/dist/bundle/chunks/{chunk-BYB6ZAAQ.js → chunk-WE4MXUQS.js} +1 -1
  19. package/dist/bundle/chunks/chunk-ZBURYEWF.js +2 -0
  20. package/dist/bundle/chunks/chunk-ZSQEXT6X.js +15 -0
  21. package/dist/bundle/chunks/{cli-KILDDGW3.js → cli-HTJP6F6Z.js} +1 -1
  22. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-X5PVWWYJ.js → cloudflare-workers-ai-system-one-NM3JRRWQ.js} +1 -1
  23. package/dist/bundle/chunks/codemode-worker.js +0 -1
  24. package/dist/bundle/chunks/{easter-egg-3d-T5FFWIBR.js → easter-egg-3d-6YCNESG3.js} +1 -1
  25. package/dist/bundle/chunks/{execute-RYVK27GT.js → execute-JRUOLYDA.js} +4 -4
  26. package/dist/bundle/chunks/{google-generative-ai-ZOK6CV7D.js → google-generative-ai-XMFHGQC5.js} +1 -1
  27. package/dist/bundle/chunks/{google-vertex-VKWZQ3AY.js → google-vertex-4XRRNP74.js} +1 -1
  28. package/dist/bundle/chunks/{mistral-conversations-7DAUEE4N.js → mistral-conversations-Q22M3IBG.js} +1 -1
  29. package/dist/bundle/chunks/{openai-codex-responses-TC3OK7B4.js → openai-codex-responses-4MYQSO5E.js} +1 -1
  30. package/dist/bundle/chunks/{openai-completions-GWHGMQ3T.js → openai-completions-OSRCWAAA.js} +1 -1
  31. package/dist/bundle/chunks/{openai-responses-EZ7FJ2KL.js → openai-responses-UHF3DHNG.js} +1 -1
  32. package/dist/bundle/chunks/{runtime-D5I2NTIF.js → runtime-NW7GPWKS.js} +1 -1
  33. package/dist/bundle/chunks/{typesafe-system-one-A4CZTQWZ.js → typesafe-system-one-PRR5K6CI.js} +1 -1
  34. package/dist/bundle/chunks/virtual-modules-U4SEX4TD.js +2 -0
  35. package/dist/bundle/cli-runtime.js +1 -1
  36. package/dist/bundle/index.js +1 -1
  37. package/dist/bundle/rpc-entry.js +1 -1
  38. package/dist/config.d.ts +18 -1
  39. package/dist/config.d.ts.map +1 -1
  40. package/dist/config.js +44 -6
  41. package/dist/config.js.map +1 -1
  42. package/dist/core/bash-executor.d.ts.map +1 -1
  43. package/dist/core/bash-executor.js +2 -7
  44. package/dist/core/bash-executor.js.map +1 -1
  45. package/dist/core/keybindings.d.ts +4 -4
  46. package/dist/core/model-resolver.js +1 -1
  47. package/dist/core/model-resolver.js.map +1 -1
  48. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  49. package/dist/core/tools/output-accumulator.js +4 -10
  50. package/dist/core/tools/output-accumulator.js.map +1 -1
  51. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  52. package/dist/extensions/codemode/execute.js +49 -8
  53. package/dist/extensions/codemode/execute.js.map +1 -1
  54. package/dist/extensions/codemode/tool.js +1 -1
  55. package/dist/extensions/codemode/tool.js.map +1 -1
  56. package/dist/extensions/mcp/tools.d.ts.map +1 -1
  57. package/dist/extensions/mcp/tools.js +4 -9
  58. package/dist/extensions/mcp/tools.js.map +1 -1
  59. package/dist/modes/interactive/interactive-mode.d.ts +7 -0
  60. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  61. package/dist/modes/interactive/interactive-mode.js +42 -6
  62. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  63. package/dist/utils/output-files.d.ts +15 -0
  64. package/dist/utils/output-files.d.ts.map +1 -0
  65. package/dist/utils/output-files.js +30 -0
  66. package/dist/utils/output-files.js.map +1 -0
  67. package/docs/codemode.md +3 -3
  68. package/docs/keybindings.md +4 -4
  69. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  70. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  71. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  72. package/examples/extensions/gondolin/package-lock.json +2 -2
  73. package/examples/extensions/gondolin/package.json +1 -1
  74. package/examples/extensions/sandbox/package-lock.json +2 -2
  75. package/examples/extensions/sandbox/package.json +1 -1
  76. package/examples/extensions/with-deps/package-lock.json +2 -2
  77. package/examples/extensions/with-deps/package.json +1 -1
  78. package/package.json +10 -10
  79. package/dist/bundle/chunks/azure-openai-responses-7AMFUIWJ.js +0 -2
  80. package/dist/bundle/chunks/chunk-7JGR3GZN.js +0 -11
  81. package/dist/bundle/chunks/chunk-OYBSLV7Y.js +0 -16
  82. package/dist/bundle/chunks/chunk-PDFMCAOZ.js +0 -19
  83. package/dist/bundle/chunks/chunk-VIV3CWXG.js +0 -2
  84. package/dist/bundle/chunks/virtual-modules-J2M3WAR2.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;AAYjC,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,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,CAAC;AAE7F,SAAS,YAAY,CAAC,IAAY,EAAE,QAAgB;IACnD,OAAO,IAAI,CAAC,MAAM,GAAG,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O,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 { 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
+ {"version":3,"file":"execute.js","sourceRoot":"","sources":["../../../src/extensions/codemode/execute.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAaH,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,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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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 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\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\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\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\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 = 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, 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"]}
@@ -59,7 +59,7 @@ const DESCRIPTION_INTRO = `Run JavaScript that calls other tools. The input is r
59
59
  function describeGlobals(models) {
60
60
  const lines = [
61
61
  "Globals:",
62
- "- `text(value)`, `image(dataUrlOrImageBlock)`, `console.log(...)`, and top-level `return` add output; `exit()` ends the script.",
62
+ "- `text(value)`, `image(dataUrlOrImageBlock)`, `console.log(...)`, and top-level `return` add output; `exit()` ends the script. `image()` also saves the image to a temp file and the result names its path.",
63
63
  "- `store(key, value)` and `load(key)` keep JSON values across codemode calls.",
64
64
  "- `ALL_TOOLS`, `searchTools(query, { limit?, namespace? })`, `describeTool(name)`, `describeNamespace(name)`: find unlisted tools, such as MCP tools.",
65
65
  ];
@@ -1 +1 @@
1
- {"version":3,"file":"tool.js","sourceRoot":"","sources":["../../../src/extensions/codemode/tool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,OAAO,EACN,uBAAuB,EACvB,0BAA0B,EAC1B,oBAAoB,EACpB,gBAAgB,EAChB,oBAAoB,GACpB,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,uBAAuB,EAAE,MAAM,oCAAoC,CAAC;AAC7E,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAU9C,OAAO,EAAE,kBAAkB,EAAE,MAAM,6CAA6C,CAAC;AACjF,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAElD,MAAM,CAAC,MAAM,kBAAkB,GAAG,UAAU,CAAC;AAE7C,+FAA+F;AAC/F,MAAM,CAAC,MAAM,yBAAyB,GAAG,gBAAgB,CAAC;AAgC1D,MAAM,kBAAkB,GAAuB,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;AAElE,MAAM,CAAC,MAAM,cAAc,GAAG,IAAI,CAAC,MAAM,CAAC;IACzC,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC;QACjB,WAAW,EAAE,wBAAwB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E,OAAO,CAAC;QACrE,gFAAgF;QAChF,mBAAmB,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,EAAE,WAAW,EAAE,uBAAuB,EAAE,EAAE;QAC5F,8EAA8E;QAC9E,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,EAAE,EAAE,CAC5D,CAAC,MAAM,oBAAoB,EAAE,CAAC,CAAC,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,EAAE,OAAO,CAAC;QACnG,GAAG,iBAAiB;KACpB,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CACjC,KAAK,GAA8B,EAAE,EACrC,OAAO,GAAwB,EAAE;IAEjC,MAAM,UAAU,GAAG,4BAA4B,CAAC,OAAO,CAAC,CAAC;IACzD,MAAM,IAAI,GAAG,kBAAkB,CAAC,UAAU,CAAC,CAAC;IAC5C,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE;QACnB,WAAW,EAAE,yBAAyB,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,KAAK,IAAI,EAAE,CAAC;QAClF,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;KAC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["/**\n * The `codemode` tool: the model writes JavaScript that calls other tools. Scripts use `tools`,\n * `ALL_TOOLS`, `text()`, `image()`, `exit()`, `store()`/`load()`, `console.*`, and `return <value>`,\n * may start with a `// @options:` line, and reach the model catalog, classifiers, and image models\n * through `models.*`. Results start with a \"Script completed\" or \"Script failed\" header.\n *\n * Scripts can call the agent loop's nested tools: active `direct` tools and every `codemode` or\n * `deferred` tool. Nested calls run through the agent loop's tool pipeline (`ctx.executeTool`), so\n * validation, `tool_call`/`tool_result` hooks, and permission checks apply exactly as for direct\n * calls. Only the script's output reaches the model; nested results do not.\n *\n * Nested results are handed to the script as follows:\n * - A tool that declares `outputSchema` resolves to its `structuredContent`, also for error\n * results that carry one (MCP tools resolve to their `CallToolResult`, including `isError`).\n * - Any other tool resolves to its text content as one string.\n * - A failed, blocked, or invalid call rejects with an Error carrying the tool's error text.\n *\n * A script that fails returns a normal error result that keeps its partial output, followed by\n * \"Script error:\" and the error. `store(key, value)` and `load(key)` keep JSON values across\n * calls; successful scripts append their writes to the session as `codemode-store` custom entries,\n * so each branch sees the values written on its own path.\n */\n\nimport { join } from \"node:path\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport type { CodemodeJsonSchema, CodemodeTool } from \"@earendil-works/pi-codemode\";\nimport {\n\tMCP_TYPESCRIPT_PREAMBLE,\n\tmcpStructuredContentSchema,\n\trenderToolOutputType,\n\trenderToolSample,\n\ttoCodemodeIdentifier,\n} from \"@earendil-works/pi-codemode/declarations\";\nimport { CODEMODE_SOURCE_GRAMMAR } from \"@earendil-works/pi-codemode/source\";\nimport { type Static, Type } from \"typebox\";\nimport { getDocsPath } from \"../../config.ts\";\nimport type {\n\tToolDefinition,\n\tToolInfo,\n\tToolLoadout,\n\tToolLoadoutChanges,\n\tToolNamespace,\n} from \"../../core/extensions/types.ts\";\nimport type { ModelRegistry } from \"../../core/model-registry.ts\";\nimport type { CodemodeMode } from \"../../core/settings-manager.ts\";\nimport { wrapToolDefinition } from \"../../core/tools/tool-definition-wrapper.ts\";\nimport { loadCodemodeExecutor } from \"./execute.lazy.ts\";\nimport { codemodeRenderers } from \"./renderer.ts\";\n\nexport const CODEMODE_TOOL_NAME = \"codemode\";\n\n/** Custom entry type holding one script's `store()` writes: {@link CodemodeStoreEntryData}. */\nexport const CODEMODE_STORE_ENTRY_TYPE = \"codemode-store\";\n\nexport interface CodemodeStoreEntryData {\n\tset: Record<string, unknown>;\n\tdelete: string[];\n}\n\n/** The part of the model registry that scripts reach through `models`. */\nexport type CodemodeModelRuntime = Pick<\n\tModelRegistry,\n\t\"getModelsOfType\" | \"getAvailableOfType\" | \"getModelOfType\" | \"classify\" | \"generateImages\"\n>;\n\nexport interface CodemodeToolOptions {\n\t/** Namespace of a tool, for `searchTools()` ranking and its `namespace` filter. */\n\tgetToolNamespace?: (toolName: string) => ToolNamespace | undefined;\n\t/**\n\t * Expose the `models` namespace to scripts, backed by the session's model registry\n\t * (`ctx.modelRegistry`). Without it, `models` is not declared.\n\t */\n\tmodels?: boolean;\n\t/**\n\t * Persists `store()` writes as a session custom entry. Without it, writes last only for the\n\t * current script; `load()` still reads entries already on the branch.\n\t */\n\tappendEntry?: (customType: string, data: CodemodeStoreEntryData) => void;\n\t/** How the tool presents the loadout while active (the `codemode.mode` setting). Default: `on`. */\n\tgetMode?: () => CodemodeMode;\n\t/** Token budget for tool declarations in the description. Default: {@link DEFAULT_CODEMODE_INLINE_BUDGET}. */\n\tgetInlineBudget?: () => number | undefined;\n}\n\nconst TEXT_OUTPUT_SCHEMA: CodemodeJsonSchema = { type: \"string\" };\n\nexport const codemodeSchema = Type.Object({\n\tcode: Type.String({\n\t\tdescription: \"Raw JavaScript source.\",\n\t}),\n});\n\nexport type CodemodeToolInput = Static<typeof codemodeSchema>;\n\n/**\n * Whether a registered tool is this package's `codemode` tool rather than another extension's tool\n * with the same name. Compares the parameter schema, which the definition passes through by reference.\n */\nexport function isCodemodeTool(tool: Pick<ToolInfo, \"name\" | \"parameters\">): boolean {\n\treturn tool.name === CODEMODE_TOOL_NAME && tool.parameters === codemodeSchema;\n}\n\nexport type CodemodeNestedCallStatus = \"running\" | \"ok\" | \"error\" | \"cancelled\";\n\nexport interface CodemodeNestedCall {\n\t/** Tool call id of the nested call, `<codemode call id>/<n>`. */\n\tid: string;\n\tname: string;\n\t/** Compact JSON of the arguments, truncated for display. */\n\targs: string;\n\tstatus: CodemodeNestedCallStatus;\n\tdurationMs?: number;\n\t/** Error text, truncated for display. */\n\terror?: string;\n\t/** Cost in USD of a `models.*` call that reported usage. */\n\tcost?: number;\n}\n\nexport interface CodemodeToolDetails {\n\tcalls: CodemodeNestedCall[];\n\t/** Temp file with the full text output, when the output was truncated. */\n\tfullOutputPath?: string;\n}\n\nexport const codemodeToolSystemPromptContribution = {\n\tsnippet: \"Run JavaScript that calls other tools\",\n\tguidelines: [\n\t\t\"Use codemode to batch independent tool calls (Promise.allSettled), chain them, or filter large output, instead of many separate calls.\",\n\t],\n} as const;\n\n/** The reference for scripts: globals, tool results, `store()`, the `models` API, and limits. */\nexport const CODEMODE_DOCS_PATH = join(getDocsPath(), \"codemode.md\");\n\nconst 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.\n- \\`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.\n- Optional first line: \\`// @options: {\"max_output_tokens\": 10000, \"timeout_ms\": 60000}\\``;\n\n/** One line per global. The details live in {@link CODEMODE_DOCS_PATH}. */\nfunction describeGlobals(models: boolean): string {\n\tconst lines = [\n\t\t\"Globals:\",\n\t\t\"- `text(value)`, `image(dataUrlOrImageBlock)`, `console.log(...)`, and top-level `return` add output; `exit()` ends the script.\",\n\t\t\"- `store(key, value)` and `load(key)` keep JSON values across codemode calls.\",\n\t\t\"- `ALL_TOOLS`, `searchTools(query, { limit?, namespace? })`, `describeTool(name)`, `describeNamespace(name)`: find unlisted tools, such as MCP tools.\",\n\t];\n\tif (models) {\n\t\tlines.push(`- \\`models\\`: classifiers and image generation. Read ${CODEMODE_DOCS_PATH} first.`);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\n/** Default for {@link CodemodeDescriptionOptions.inlineBudget}, in estimated tokens. */\nexport const DEFAULT_CODEMODE_INLINE_BUDGET = 3000;\n/** Characters per token when estimating the cost of a tool section. */\nconst CHARS_PER_TOKEN = 4;\n\n/** What a script sees of a tool. Tools without an output schema resolve to their text output. */\nexport function toCodemodeDeclaration(tool: AgentTool<any>): Omit<CodemodeTool, \"execute\"> {\n\treturn {\n\t\tname: tool.name,\n\t\tdescription: tool.description,\n\t\tinputSchema: tool.parameters as CodemodeJsonSchema,\n\t\toutputSchema: (tool.outputSchema as CodemodeJsonSchema | undefined) ?? TEXT_OUTPUT_SCHEMA,\n\t};\n}\n\n/** Tools a script may call: every given tool except the codemode tool itself. */\nexport function getCodemodeCallableTools(tools: readonly AgentTool<any>[]): AgentTool<any>[] {\n\treturn tools.filter((tool) => tool.name !== CODEMODE_TOOL_NAME);\n}\n\nexport interface CodemodeDescriptionOptions {\n\t/** Declare the `models` namespace; only for tools created with model access. */\n\tmodels?: boolean;\n\t/** Namespace of each tool, by tool name. Tools of one namespace are listed under one heading. */\n\tnamespaces?: ReadonlyMap<string, ToolNamespace>;\n\t/** Tools that are callable but never listed with their declaration (`deferred` exposure). */\n\tdeferred?: ReadonlySet<string>;\n\t/**\n\t * Estimated tokens (characters / 4) the tool sections may use. Tools that do not fit are left\n\t * out, like deferred tools. Unset lists every tool that is not deferred.\n\t */\n\tinlineBudget?: number;\n}\n\n/** `### \\`id\\` (\\`raw name\\`)` followed by the tool's description and declaration. */\nfunction renderToolSection(declaration: Omit<CodemodeTool, \"execute\">): string {\n\tconst id = toCodemodeIdentifier(declaration.name);\n\tconst heading = id === declaration.name ? `### \\`${id}\\`` : `### \\`${id}\\` (\\`${declaration.name}\\`)`;\n\treturn `${heading}\\n${renderToolSample(declaration).trim()}`;\n}\n\ninterface CatalogEntry {\n\tname: string;\n\tsection: string;\n\tcost: number;\n}\n\ninterface CatalogGroup {\n\tnamespace: ToolNamespace | undefined;\n\tentries: CatalogEntry[];\n}\n\n/**\n * Pick the tool sections that fit the budget, like OpenCode's catalog: in each round every group\n * (tools without a namespace first, then namespaces by name) places its cheapest remaining tool; a\n * group whose next tool does not fit drops out while the others continue. Every namespace is\n * represented before any namespace is complete.\n */\nfunction selectCatalog(groups: readonly CatalogGroup[], budget: number | undefined): Set<string> {\n\tif (budget === undefined) return new Set(groups.flatMap((group) => group.entries.map((entry) => entry.name)));\n\tconst queues = groups.map((group) => [...group.entries].sort((a, b) => a.cost - b.cost));\n\tconst shown = new Set<string>();\n\tlet remaining = budget;\n\tlet active = queues.filter((queue) => queue.length > 0);\n\twhile (active.length > 0) {\n\t\tactive = active.filter((queue) => {\n\t\t\tconst next = queue[0];\n\t\t\tif (next.cost > remaining) return false;\n\t\t\tremaining -= next.cost;\n\t\t\tshown.add(next.name);\n\t\t\tqueue.shift();\n\t\t\treturn queue.length > 0;\n\t\t});\n\t}\n\treturn shown;\n}\n\n/**\n * Model-facing description: the helper list, guidance for finding tools that are not listed, the\n * shared MCP types when listed tools need them, the `models` API, and one section per listed tool,\n * grouped by namespace. Deferred tools are never listed and do not affect the description at all, so\n * it stays the same while MCP servers connect or change their tools. Tool sections are limited to\n * `inlineBudget`.\n */\nexport function createCodemodeDescription(\n\ttools: readonly AgentTool<any>[],\n\toptions: CodemodeDescriptionOptions = {},\n): string {\n\tconst declarations = getCodemodeCallableTools(tools)\n\t\t.filter((tool) => !options.deferred?.has(tool.name))\n\t\t.map(toCodemodeDeclaration);\n\tconst groups = new Map<string, CatalogGroup>([[\"\", { namespace: undefined, entries: [] }]]);\n\tfor (const declaration of declarations) {\n\t\tconst namespace = options.namespaces?.get(declaration.name);\n\t\tconst key = namespace ? `ns:${namespace.name}` : \"\";\n\t\tconst group = groups.get(key) ?? { namespace, entries: [] };\n\t\tgroups.set(key, group);\n\t\tconst section = renderToolSection(declaration);\n\t\tgroup.entries.push({ name: declaration.name, section, cost: Math.ceil(section.length / CHARS_PER_TOKEN) });\n\t}\n\tconst ordered = [...groups.values()].sort((a, b) =>\n\t\ta.namespace === undefined ? -1 : b.namespace === undefined ? 1 : a.namespace.name.localeCompare(b.namespace.name),\n\t);\n\tconst shown = selectCatalog(ordered, options.inlineBudget);\n\n\tconst sections = [DESCRIPTION_INTRO, describeGlobals(options.models === true)];\n\tif (\n\t\tdeclarations.some(\n\t\t\t(declaration) =>\n\t\t\t\tshown.has(declaration.name) && mcpStructuredContentSchema(declaration.outputSchema) !== undefined,\n\t\t)\n\t) {\n\t\tsections.push(`Shared MCP Types:\\n\\`\\`\\`ts\\n${MCP_TYPESCRIPT_PREAMBLE}\\n\\`\\`\\``);\n\t}\n\tif (declarations.length === 0) return sections.join(\"\\n\\n\");\n\n\tconst toolSections = [\"Nested tools:\"];\n\tfor (const { namespace, entries } of ordered) {\n\t\tconst visible = entries.filter((entry) => shown.has(entry.name));\n\t\tif (namespace) {\n\t\t\t// Only tools that did not fit the budget are counted as not listed here.\n\t\t\tconst listing =\n\t\t\t\tvisible.length === entries.length\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: visible.length === 0\n\t\t\t\t\t\t? \" (tools not listed)\"\n\t\t\t\t\t\t: \" (some tools not listed)\";\n\t\t\tconst description = namespace.description?.trim();\n\t\t\ttoolSections.push(`## ${namespace.name}${listing}${description ? `\\n${description}` : \"\"}`);\n\t\t}\n\t\tfor (const entry of visible) toolSections.push(entry.section);\n\t}\n\tsections.push(toolSections.join(\"\\n\\n\"));\n\treturn sections.join(\"\\n\\n\");\n}\n\n/**\n * What a script call resolves to, in one line: `a string`, the field names of an object\n * (`{ output, exit_code, full_output_path? }`), or the rendered type for anything else.\n */\nfunction describeOutput(schema: CodemodeJsonSchema | undefined): string {\n\tconst type = renderToolOutputType(schema);\n\tif (type === \"string\") return \"a string\";\n\tconst object = typeof schema === \"object\" ? schema : undefined;\n\tconst properties = object?.properties;\n\tif (\n\t\tobject?.type === \"object\" &&\n\t\ttypeof properties === \"object\" &&\n\t\tproperties !== null &&\n\t\tmcpStructuredContentSchema(schema) === undefined\n\t) {\n\t\tconst required = new Set(Array.isArray(object.required) ? object.required : []);\n\t\tconst fields = Object.keys(properties).map((name) => (required.has(name) ? name : `${name}?`));\n\t\treturn `\\`{ ${fields.join(\", \")} }\\``;\n\t}\n\treturn `\\`${type.replace(/\\s+/g, \" \")}\\``;\n}\n\n/**\n * A declared tool's description followed by how scripts call it and what the call resolves to. The\n * arguments are the tool's declared parameters, so they are not repeated.\n */\nfunction describeScriptCall(tool: AgentTool<any>): string {\n\treturn `${tool.description.trim()}\\n\\nCodemode: \\`tools.${toCodemodeIdentifier(tool.name)}(args)\\` resolves to ${describeOutput(toCodemodeDeclaration(tool).outputSchema)}.`;\n}\n\n/**\n * How the codemode tool presents tools that are both declared and callable from scripts:\n * - `on`: their descriptions say how scripts call them, and the codemode description\n * lists only the callable tools without `direct` exposure.\n * - `only`: the codemode description lists every callable tool, and requests leave out the\n * declarations of active `direct` tools.\n *\n * Listing by exposure, not by the active set, keeps the codemode description unchanged when\n * `tool_search` loads a tool, so loads do not redeclare codemode.\n */\nfunction prepareCodemodeLoadout(loadout: ToolLoadout, options: CodemodeToolOptions): ToolLoadoutChanges {\n\tconst mode = options.getMode?.() ?? \"on\";\n\tconst isDirect = (tool: AgentTool) => loadout.getExposure(tool.name) === \"direct\";\n\tconst callable = getCodemodeCallableTools(loadout.callable);\n\tconst callableNames = new Set(callable.map((tool) => tool.name));\n\tconst descriptions: Record<string, string> = {};\n\tif (mode === \"on\") {\n\t\tfor (const tool of loadout.declared) {\n\t\t\tif (callableNames.has(tool.name)) descriptions[tool.name] = describeScriptCall(tool);\n\t\t}\n\t}\n\tconst listed = mode === \"only\" ? callable : callable.filter((tool) => !isDirect(tool));\n\tconst namespaces = new Map(\n\t\tlisted.flatMap((tool) => {\n\t\t\tconst namespace = loadout.getNamespace(tool.name);\n\t\t\treturn namespace ? [[tool.name, namespace] as const] : [];\n\t\t}),\n\t);\n\tdescriptions[CODEMODE_TOOL_NAME] = createCodemodeDescription(listed, {\n\t\tmodels: options.models === true,\n\t\tnamespaces,\n\t\tdeferred: new Set(\n\t\t\tlisted.filter((tool) => loadout.getExposure(tool.name) === \"deferred\").map((tool) => tool.name),\n\t\t),\n\t\tinlineBudget: options.getInlineBudget?.() ?? DEFAULT_CODEMODE_INLINE_BUDGET,\n\t});\n\tconst declaredNames = new Set(loadout.declared.map((tool) => tool.name));\n\treturn {\n\t\tdescriptions,\n\t\thiddenDeclarations:\n\t\t\tmode === \"only\"\n\t\t\t\t? callable.filter((tool) => isDirect(tool) && declaredNames.has(tool.name)).map((tool) => tool.name)\n\t\t\t\t: [],\n\t};\n}\n\nexport function createCodemodeToolDefinition(\n\toptions: CodemodeToolOptions = {},\n): ToolDefinition<typeof codemodeSchema, CodemodeToolDetails | undefined> {\n\treturn {\n\t\tname: CODEMODE_TOOL_NAME,\n\t\tlabel: CODEMODE_TOOL_NAME,\n\t\t// Replaced with the declarations of the callable tools when the tool is activated.\n\t\tdescription: createCodemodeDescription([], { models: options.models === true }),\n\t\tpromptSnippet: codemodeToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: [...codemodeToolSystemPromptContribution.guidelines],\n\t\tparameters: codemodeSchema,\n\t\t// Scripts must not start other scripts.\n\t\texposure: \"model-only\",\n\t\tprepareLoadout: (loadout) => prepareCodemodeLoadout(loadout, options),\n\t\t// Capable models write the script as raw text instead of a JSON-escaped string.\n\t\tconstrainedSampling: { type: \"grammar\", variants: { openai_lark: CODEMODE_SOURCE_GRAMMAR } },\n\t\t// The sandbox (worker, QuickJS wasm) loads on the first call, not at startup.\n\t\texecute: async (toolCallId, params, signal, onUpdate, ctx) =>\n\t\t\t(await loadCodemodeExecutor()).executeCodemode(toolCallId, params, signal, onUpdate, ctx, options),\n\t\t...codemodeRenderers,\n\t};\n}\n\n/**\n * Create the codemode tool as an AgentTool. The description lists the given tools; the script can\n * call whatever tools the agent loop provides at execution time.\n */\nexport function createCodemodeTool(\n\ttools: readonly AgentTool<any>[] = [],\n\toptions: CodemodeToolOptions = {},\n): AgentTool<typeof codemodeSchema> {\n\tconst definition = createCodemodeToolDefinition(options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tdescription: createCodemodeDescription(tools, { models: options.models === true }),\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
1
+ {"version":3,"file":"tool.js","sourceRoot":"","sources":["../../../src/extensions/codemode/tool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,OAAO,EACN,uBAAuB,EACvB,0BAA0B,EAC1B,oBAAoB,EACpB,gBAAgB,EAChB,oBAAoB,GACpB,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,uBAAuB,EAAE,MAAM,oCAAoC,CAAC;AAC7E,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAU9C,OAAO,EAAE,kBAAkB,EAAE,MAAM,6CAA6C,CAAC;AACjF,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAElD,MAAM,CAAC,MAAM,kBAAkB,GAAG,UAAU,CAAC;AAE7C,+FAA+F;AAC/F,MAAM,CAAC,MAAM,yBAAyB,GAAG,gBAAgB,CAAC;AAgC1D,MAAM,kBAAkB,GAAuB,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;AAElE,MAAM,CAAC,MAAM,cAAc,GAAG,IAAI,CAAC,MAAM,CAAC;IACzC,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC;QACjB,WAAW,EAAE,wBAAwB;KACrC,CAAC;CACF,CAAC,CAAC;AAIH;;;GAGG;AACH,MAAM,UAAU,cAAc,CAAC,IAA2C;IACzE,OAAO,IAAI,CAAC,IAAI,KAAK,kBAAkB,IAAI,IAAI,CAAC,UAAU,KAAK,cAAc,CAAC;AAC/E,CAAC;AAwBD,MAAM,CAAC,MAAM,oCAAoC,GAAG;IACnD,OAAO,EAAE,uCAAuC;IAChD,UA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AAC,MAAM,oBAAoB,EAAE,CAAC,CAAC,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,EAAE,OAAO,CAAC;QACnG,GAAG,iBAAiB;KACpB,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CACjC,KAAK,GAA8B,EAAE,EACrC,OAAO,GAAwB,EAAE;IAEjC,MAAM,UAAU,GAAG,4BAA4B,CAAC,OAAO,CAAC,CAAC;IACzD,MAAM,IAAI,GAAG,kBAAkB,CAAC,UAAU,CAAC,CAAC;IAC5C,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE;QACnB,WAAW,EAAE,yBAAyB,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,KAAK,IAAI,EAAE,CAAC;QAClF,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;KAC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["/**\n * The `codemode` tool: the model writes JavaScript that calls other tools. Scripts use `tools`,\n * `ALL_TOOLS`, `text()`, `image()`, `exit()`, `store()`/`load()`, `console.*`, and `return <value>`,\n * may start with a `// @options:` line, and reach the model catalog, classifiers, and image models\n * through `models.*`. Results start with a \"Script completed\" or \"Script failed\" header.\n *\n * Scripts can call the agent loop's nested tools: active `direct` tools and every `codemode` or\n * `deferred` tool. Nested calls run through the agent loop's tool pipeline (`ctx.executeTool`), so\n * validation, `tool_call`/`tool_result` hooks, and permission checks apply exactly as for direct\n * calls. Only the script's output reaches the model; nested results do not.\n *\n * Nested results are handed to the script as follows:\n * - A tool that declares `outputSchema` resolves to its `structuredContent`, also for error\n * results that carry one (MCP tools resolve to their `CallToolResult`, including `isError`).\n * - Any other tool resolves to its text content as one string.\n * - A failed, blocked, or invalid call rejects with an Error carrying the tool's error text.\n *\n * A script that fails returns a normal error result that keeps its partial output, followed by\n * \"Script error:\" and the error. `store(key, value)` and `load(key)` keep JSON values across\n * calls; successful scripts append their writes to the session as `codemode-store` custom entries,\n * so each branch sees the values written on its own path.\n */\n\nimport { join } from \"node:path\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport type { CodemodeJsonSchema, CodemodeTool } from \"@earendil-works/pi-codemode\";\nimport {\n\tMCP_TYPESCRIPT_PREAMBLE,\n\tmcpStructuredContentSchema,\n\trenderToolOutputType,\n\trenderToolSample,\n\ttoCodemodeIdentifier,\n} from \"@earendil-works/pi-codemode/declarations\";\nimport { CODEMODE_SOURCE_GRAMMAR } from \"@earendil-works/pi-codemode/source\";\nimport { type Static, Type } from \"typebox\";\nimport { getDocsPath } from \"../../config.ts\";\nimport type {\n\tToolDefinition,\n\tToolInfo,\n\tToolLoadout,\n\tToolLoadoutChanges,\n\tToolNamespace,\n} from \"../../core/extensions/types.ts\";\nimport type { ModelRegistry } from \"../../core/model-registry.ts\";\nimport type { CodemodeMode } from \"../../core/settings-manager.ts\";\nimport { wrapToolDefinition } from \"../../core/tools/tool-definition-wrapper.ts\";\nimport { loadCodemodeExecutor } from \"./execute.lazy.ts\";\nimport { codemodeRenderers } from \"./renderer.ts\";\n\nexport const CODEMODE_TOOL_NAME = \"codemode\";\n\n/** Custom entry type holding one script's `store()` writes: {@link CodemodeStoreEntryData}. */\nexport const CODEMODE_STORE_ENTRY_TYPE = \"codemode-store\";\n\nexport interface CodemodeStoreEntryData {\n\tset: Record<string, unknown>;\n\tdelete: string[];\n}\n\n/** The part of the model registry that scripts reach through `models`. */\nexport type CodemodeModelRuntime = Pick<\n\tModelRegistry,\n\t\"getModelsOfType\" | \"getAvailableOfType\" | \"getModelOfType\" | \"classify\" | \"generateImages\"\n>;\n\nexport interface CodemodeToolOptions {\n\t/** Namespace of a tool, for `searchTools()` ranking and its `namespace` filter. */\n\tgetToolNamespace?: (toolName: string) => ToolNamespace | undefined;\n\t/**\n\t * Expose the `models` namespace to scripts, backed by the session's model registry\n\t * (`ctx.modelRegistry`). Without it, `models` is not declared.\n\t */\n\tmodels?: boolean;\n\t/**\n\t * Persists `store()` writes as a session custom entry. Without it, writes last only for the\n\t * current script; `load()` still reads entries already on the branch.\n\t */\n\tappendEntry?: (customType: string, data: CodemodeStoreEntryData) => void;\n\t/** How the tool presents the loadout while active (the `codemode.mode` setting). Default: `on`. */\n\tgetMode?: () => CodemodeMode;\n\t/** Token budget for tool declarations in the description. Default: {@link DEFAULT_CODEMODE_INLINE_BUDGET}. */\n\tgetInlineBudget?: () => number | undefined;\n}\n\nconst TEXT_OUTPUT_SCHEMA: CodemodeJsonSchema = { type: \"string\" };\n\nexport const codemodeSchema = Type.Object({\n\tcode: Type.String({\n\t\tdescription: \"Raw JavaScript source.\",\n\t}),\n});\n\nexport type CodemodeToolInput = Static<typeof codemodeSchema>;\n\n/**\n * Whether a registered tool is this package's `codemode` tool rather than another extension's tool\n * with the same name. Compares the parameter schema, which the definition passes through by reference.\n */\nexport function isCodemodeTool(tool: Pick<ToolInfo, \"name\" | \"parameters\">): boolean {\n\treturn tool.name === CODEMODE_TOOL_NAME && tool.parameters === codemodeSchema;\n}\n\nexport type CodemodeNestedCallStatus = \"running\" | \"ok\" | \"error\" | \"cancelled\";\n\nexport interface CodemodeNestedCall {\n\t/** Tool call id of the nested call, `<codemode call id>/<n>`. */\n\tid: string;\n\tname: string;\n\t/** Compact JSON of the arguments, truncated for display. */\n\targs: string;\n\tstatus: CodemodeNestedCallStatus;\n\tdurationMs?: number;\n\t/** Error text, truncated for display. */\n\terror?: string;\n\t/** Cost in USD of a `models.*` call that reported usage. */\n\tcost?: number;\n}\n\nexport interface CodemodeToolDetails {\n\tcalls: CodemodeNestedCall[];\n\t/** Temp file with the full text output, when the output was truncated. */\n\tfullOutputPath?: string;\n}\n\nexport const codemodeToolSystemPromptContribution = {\n\tsnippet: \"Run JavaScript that calls other tools\",\n\tguidelines: [\n\t\t\"Use codemode to batch independent tool calls (Promise.allSettled), chain them, or filter large output, instead of many separate calls.\",\n\t],\n} as const;\n\n/** The reference for scripts: globals, tool results, `store()`, the `models` API, and limits. */\nexport const CODEMODE_DOCS_PATH = join(getDocsPath(), \"codemode.md\");\n\nconst 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.\n- \\`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.\n- Optional first line: \\`// @options: {\"max_output_tokens\": 10000, \"timeout_ms\": 60000}\\``;\n\n/** One line per global. The details live in {@link CODEMODE_DOCS_PATH}. */\nfunction describeGlobals(models: boolean): string {\n\tconst lines = [\n\t\t\"Globals:\",\n\t\t\"- `text(value)`, `image(dataUrlOrImageBlock)`, `console.log(...)`, and top-level `return` add output; `exit()` ends the script. `image()` also saves the image to a temp file and the result names its path.\",\n\t\t\"- `store(key, value)` and `load(key)` keep JSON values across codemode calls.\",\n\t\t\"- `ALL_TOOLS`, `searchTools(query, { limit?, namespace? })`, `describeTool(name)`, `describeNamespace(name)`: find unlisted tools, such as MCP tools.\",\n\t];\n\tif (models) {\n\t\tlines.push(`- \\`models\\`: classifiers and image generation. Read ${CODEMODE_DOCS_PATH} first.`);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\n/** Default for {@link CodemodeDescriptionOptions.inlineBudget}, in estimated tokens. */\nexport const DEFAULT_CODEMODE_INLINE_BUDGET = 3000;\n/** Characters per token when estimating the cost of a tool section. */\nconst CHARS_PER_TOKEN = 4;\n\n/** What a script sees of a tool. Tools without an output schema resolve to their text output. */\nexport function toCodemodeDeclaration(tool: AgentTool<any>): Omit<CodemodeTool, \"execute\"> {\n\treturn {\n\t\tname: tool.name,\n\t\tdescription: tool.description,\n\t\tinputSchema: tool.parameters as CodemodeJsonSchema,\n\t\toutputSchema: (tool.outputSchema as CodemodeJsonSchema | undefined) ?? TEXT_OUTPUT_SCHEMA,\n\t};\n}\n\n/** Tools a script may call: every given tool except the codemode tool itself. */\nexport function getCodemodeCallableTools(tools: readonly AgentTool<any>[]): AgentTool<any>[] {\n\treturn tools.filter((tool) => tool.name !== CODEMODE_TOOL_NAME);\n}\n\nexport interface CodemodeDescriptionOptions {\n\t/** Declare the `models` namespace; only for tools created with model access. */\n\tmodels?: boolean;\n\t/** Namespace of each tool, by tool name. Tools of one namespace are listed under one heading. */\n\tnamespaces?: ReadonlyMap<string, ToolNamespace>;\n\t/** Tools that are callable but never listed with their declaration (`deferred` exposure). */\n\tdeferred?: ReadonlySet<string>;\n\t/**\n\t * Estimated tokens (characters / 4) the tool sections may use. Tools that do not fit are left\n\t * out, like deferred tools. Unset lists every tool that is not deferred.\n\t */\n\tinlineBudget?: number;\n}\n\n/** `### \\`id\\` (\\`raw name\\`)` followed by the tool's description and declaration. */\nfunction renderToolSection(declaration: Omit<CodemodeTool, \"execute\">): string {\n\tconst id = toCodemodeIdentifier(declaration.name);\n\tconst heading = id === declaration.name ? `### \\`${id}\\`` : `### \\`${id}\\` (\\`${declaration.name}\\`)`;\n\treturn `${heading}\\n${renderToolSample(declaration).trim()}`;\n}\n\ninterface CatalogEntry {\n\tname: string;\n\tsection: string;\n\tcost: number;\n}\n\ninterface CatalogGroup {\n\tnamespace: ToolNamespace | undefined;\n\tentries: CatalogEntry[];\n}\n\n/**\n * Pick the tool sections that fit the budget, like OpenCode's catalog: in each round every group\n * (tools without a namespace first, then namespaces by name) places its cheapest remaining tool; a\n * group whose next tool does not fit drops out while the others continue. Every namespace is\n * represented before any namespace is complete.\n */\nfunction selectCatalog(groups: readonly CatalogGroup[], budget: number | undefined): Set<string> {\n\tif (budget === undefined) return new Set(groups.flatMap((group) => group.entries.map((entry) => entry.name)));\n\tconst queues = groups.map((group) => [...group.entries].sort((a, b) => a.cost - b.cost));\n\tconst shown = new Set<string>();\n\tlet remaining = budget;\n\tlet active = queues.filter((queue) => queue.length > 0);\n\twhile (active.length > 0) {\n\t\tactive = active.filter((queue) => {\n\t\t\tconst next = queue[0];\n\t\t\tif (next.cost > remaining) return false;\n\t\t\tremaining -= next.cost;\n\t\t\tshown.add(next.name);\n\t\t\tqueue.shift();\n\t\t\treturn queue.length > 0;\n\t\t});\n\t}\n\treturn shown;\n}\n\n/**\n * Model-facing description: the helper list, guidance for finding tools that are not listed, the\n * shared MCP types when listed tools need them, the `models` API, and one section per listed tool,\n * grouped by namespace. Deferred tools are never listed and do not affect the description at all, so\n * it stays the same while MCP servers connect or change their tools. Tool sections are limited to\n * `inlineBudget`.\n */\nexport function createCodemodeDescription(\n\ttools: readonly AgentTool<any>[],\n\toptions: CodemodeDescriptionOptions = {},\n): string {\n\tconst declarations = getCodemodeCallableTools(tools)\n\t\t.filter((tool) => !options.deferred?.has(tool.name))\n\t\t.map(toCodemodeDeclaration);\n\tconst groups = new Map<string, CatalogGroup>([[\"\", { namespace: undefined, entries: [] }]]);\n\tfor (const declaration of declarations) {\n\t\tconst namespace = options.namespaces?.get(declaration.name);\n\t\tconst key = namespace ? `ns:${namespace.name}` : \"\";\n\t\tconst group = groups.get(key) ?? { namespace, entries: [] };\n\t\tgroups.set(key, group);\n\t\tconst section = renderToolSection(declaration);\n\t\tgroup.entries.push({ name: declaration.name, section, cost: Math.ceil(section.length / CHARS_PER_TOKEN) });\n\t}\n\tconst ordered = [...groups.values()].sort((a, b) =>\n\t\ta.namespace === undefined ? -1 : b.namespace === undefined ? 1 : a.namespace.name.localeCompare(b.namespace.name),\n\t);\n\tconst shown = selectCatalog(ordered, options.inlineBudget);\n\n\tconst sections = [DESCRIPTION_INTRO, describeGlobals(options.models === true)];\n\tif (\n\t\tdeclarations.some(\n\t\t\t(declaration) =>\n\t\t\t\tshown.has(declaration.name) && mcpStructuredContentSchema(declaration.outputSchema) !== undefined,\n\t\t)\n\t) {\n\t\tsections.push(`Shared MCP Types:\\n\\`\\`\\`ts\\n${MCP_TYPESCRIPT_PREAMBLE}\\n\\`\\`\\``);\n\t}\n\tif (declarations.length === 0) return sections.join(\"\\n\\n\");\n\n\tconst toolSections = [\"Nested tools:\"];\n\tfor (const { namespace, entries } of ordered) {\n\t\tconst visible = entries.filter((entry) => shown.has(entry.name));\n\t\tif (namespace) {\n\t\t\t// Only tools that did not fit the budget are counted as not listed here.\n\t\t\tconst listing =\n\t\t\t\tvisible.length === entries.length\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: visible.length === 0\n\t\t\t\t\t\t? \" (tools not listed)\"\n\t\t\t\t\t\t: \" (some tools not listed)\";\n\t\t\tconst description = namespace.description?.trim();\n\t\t\ttoolSections.push(`## ${namespace.name}${listing}${description ? `\\n${description}` : \"\"}`);\n\t\t}\n\t\tfor (const entry of visible) toolSections.push(entry.section);\n\t}\n\tsections.push(toolSections.join(\"\\n\\n\"));\n\treturn sections.join(\"\\n\\n\");\n}\n\n/**\n * What a script call resolves to, in one line: `a string`, the field names of an object\n * (`{ output, exit_code, full_output_path? }`), or the rendered type for anything else.\n */\nfunction describeOutput(schema: CodemodeJsonSchema | undefined): string {\n\tconst type = renderToolOutputType(schema);\n\tif (type === \"string\") return \"a string\";\n\tconst object = typeof schema === \"object\" ? schema : undefined;\n\tconst properties = object?.properties;\n\tif (\n\t\tobject?.type === \"object\" &&\n\t\ttypeof properties === \"object\" &&\n\t\tproperties !== null &&\n\t\tmcpStructuredContentSchema(schema) === undefined\n\t) {\n\t\tconst required = new Set(Array.isArray(object.required) ? object.required : []);\n\t\tconst fields = Object.keys(properties).map((name) => (required.has(name) ? name : `${name}?`));\n\t\treturn `\\`{ ${fields.join(\", \")} }\\``;\n\t}\n\treturn `\\`${type.replace(/\\s+/g, \" \")}\\``;\n}\n\n/**\n * A declared tool's description followed by how scripts call it and what the call resolves to. The\n * arguments are the tool's declared parameters, so they are not repeated.\n */\nfunction describeScriptCall(tool: AgentTool<any>): string {\n\treturn `${tool.description.trim()}\\n\\nCodemode: \\`tools.${toCodemodeIdentifier(tool.name)}(args)\\` resolves to ${describeOutput(toCodemodeDeclaration(tool).outputSchema)}.`;\n}\n\n/**\n * How the codemode tool presents tools that are both declared and callable from scripts:\n * - `on`: their descriptions say how scripts call them, and the codemode description\n * lists only the callable tools without `direct` exposure.\n * - `only`: the codemode description lists every callable tool, and requests leave out the\n * declarations of active `direct` tools.\n *\n * Listing by exposure, not by the active set, keeps the codemode description unchanged when\n * `tool_search` loads a tool, so loads do not redeclare codemode.\n */\nfunction prepareCodemodeLoadout(loadout: ToolLoadout, options: CodemodeToolOptions): ToolLoadoutChanges {\n\tconst mode = options.getMode?.() ?? \"on\";\n\tconst isDirect = (tool: AgentTool) => loadout.getExposure(tool.name) === \"direct\";\n\tconst callable = getCodemodeCallableTools(loadout.callable);\n\tconst callableNames = new Set(callable.map((tool) => tool.name));\n\tconst descriptions: Record<string, string> = {};\n\tif (mode === \"on\") {\n\t\tfor (const tool of loadout.declared) {\n\t\t\tif (callableNames.has(tool.name)) descriptions[tool.name] = describeScriptCall(tool);\n\t\t}\n\t}\n\tconst listed = mode === \"only\" ? callable : callable.filter((tool) => !isDirect(tool));\n\tconst namespaces = new Map(\n\t\tlisted.flatMap((tool) => {\n\t\t\tconst namespace = loadout.getNamespace(tool.name);\n\t\t\treturn namespace ? [[tool.name, namespace] as const] : [];\n\t\t}),\n\t);\n\tdescriptions[CODEMODE_TOOL_NAME] = createCodemodeDescription(listed, {\n\t\tmodels: options.models === true,\n\t\tnamespaces,\n\t\tdeferred: new Set(\n\t\t\tlisted.filter((tool) => loadout.getExposure(tool.name) === \"deferred\").map((tool) => tool.name),\n\t\t),\n\t\tinlineBudget: options.getInlineBudget?.() ?? DEFAULT_CODEMODE_INLINE_BUDGET,\n\t});\n\tconst declaredNames = new Set(loadout.declared.map((tool) => tool.name));\n\treturn {\n\t\tdescriptions,\n\t\thiddenDeclarations:\n\t\t\tmode === \"only\"\n\t\t\t\t? callable.filter((tool) => isDirect(tool) && declaredNames.has(tool.name)).map((tool) => tool.name)\n\t\t\t\t: [],\n\t};\n}\n\nexport function createCodemodeToolDefinition(\n\toptions: CodemodeToolOptions = {},\n): ToolDefinition<typeof codemodeSchema, CodemodeToolDetails | undefined> {\n\treturn {\n\t\tname: CODEMODE_TOOL_NAME,\n\t\tlabel: CODEMODE_TOOL_NAME,\n\t\t// Replaced with the declarations of the callable tools when the tool is activated.\n\t\tdescription: createCodemodeDescription([], { models: options.models === true }),\n\t\tpromptSnippet: codemodeToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: [...codemodeToolSystemPromptContribution.guidelines],\n\t\tparameters: codemodeSchema,\n\t\t// Scripts must not start other scripts.\n\t\texposure: \"model-only\",\n\t\tprepareLoadout: (loadout) => prepareCodemodeLoadout(loadout, options),\n\t\t// Capable models write the script as raw text instead of a JSON-escaped string.\n\t\tconstrainedSampling: { type: \"grammar\", variants: { openai_lark: CODEMODE_SOURCE_GRAMMAR } },\n\t\t// The sandbox (worker, QuickJS wasm) loads on the first call, not at startup.\n\t\texecute: async (toolCallId, params, signal, onUpdate, ctx) =>\n\t\t\t(await loadCodemodeExecutor()).executeCodemode(toolCallId, params, signal, onUpdate, ctx, options),\n\t\t...codemodeRenderers,\n\t};\n}\n\n/**\n * Create the codemode tool as an AgentTool. The description lists the given tools; the script can\n * call whatever tools the agent loop provides at execution time.\n */\nexport function createCodemodeTool(\n\ttools: readonly AgentTool<any>[] = [],\n\toptions: CodemodeToolOptions = {},\n): AgentTool<typeof codemodeSchema> {\n\tconst definition = createCodemodeToolDefinition(options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tdescription: createCodemodeDescription(tools, { models: options.models === true }),\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../../../src/extensions/mcp/tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAMH,OAAO,KAAK,EAAE,eAAe,EAAE,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C,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,cAAc,EACtB,OAAO,GAAE,uBAA4B,GACnC,OAAO,CAAC,eAAe,CAAC,cAAc,CAAC,CAAC,CAe1C;AA0BD,wBAAgB,uBAAuB,CAAC,OAAO,EAAE;IAChD,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,OAAO,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,WAAW,CAAC;IACtB,SAAS,EAAE,aAAa,CAAC;IACzB,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,OAAO,CAAC,aAAa,CAAC,CAAC;IACxC,mEAAmE;IACnE,iBAAiB,CAAC,EAAE,MAAM,OAAO,CAAC;CAClC,GAAG,cAAc,CAAC,OAAO,EAAE,cAAc,CAAC,CA6B1C;AAED,yGAAyG;AACzG,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,CAqCnE"}
@@ -9,16 +9,14 @@
9
9
  * the tool's `structuredContent`, and every MCP tool declares a `CallToolResult` output schema. MCP
10
10
  * errors (`isError`) are error results for the model, but scripts still resolve to the result.
11
11
  */
12
- import { createHash, randomBytes } from "node:crypto";
13
- import { writeFile } from "node:fs/promises";
14
- import { tmpdir } from "node:os";
15
- import { join } from "node:path";
12
+ import { createHash } from "node:crypto";
16
13
  import { toLlmContent, } from "@earendil-works/pi-mcp";
17
14
  import { Container, Spacer, Text } from "@earendil-works/pi-tui";
18
15
  import { formatToolCallWithArgs, getTextOutput, replaceTabs } from "../../core/tools/render-utils.js";
19
16
  import { formatSize, truncateMiddle } from "../../core/tools/truncate.js";
20
17
  import { keyHint } from "../../modes/interactive/components/keybinding-hints.js";
21
18
  import { VisualLinePreview } from "../../modes/interactive/components/visual-truncate.js";
19
+ import { writeOutputFile } from "../../utils/output-files.js";
22
20
  /**
23
21
  * Tool exposure of an MCP exposure. `codemode` and `deferred` both leave tools out of the codemode
24
22
  * description; they differ only in which tool the MCP extension activates to reach them.
@@ -34,11 +32,8 @@ export const MCP_OUTPUT_MAX_BYTES = 20 * 1024;
34
32
  const OUTPUT_PREVIEW_LINES = 5;
35
33
  /** Tool that reads the resources named by resource links. */
36
34
  export const READ_MCP_RESOURCE_TOOL = "read_mcp_resource";
37
- export async function saveToTempFile(data, extension) {
38
- const path = join(tmpdir(), `pi-mcp-${randomBytes(8).toString("hex")}${extension}`);
39
- // Results can carry private data, so only the user may read the file.
40
- await writeFile(path, data, { mode: 0o600 });
41
- return path;
35
+ export function saveToTempFile(data, extension) {
36
+ return writeOutputFile("pi-mcp", extension, data);
42
37
  }
43
38
  /**
44
39
  * `mcp__<server>__<tool>`, sanitized and shortened with a hash suffix when too long. Like Codex,
@@ -1 +1 @@
1
- {"version":3,"file":"tools.js","sourceRoot":"","sources":["../../../src/extensions/mcp/tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACtD,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,EAKN,YAAY,GACZ,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AASjE,OAAO,EAAE,sBAAsB,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,kCAAkC,CAAC;AACtG,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AACjF,OAAO,EAAE,iBAAiB,EAAE,MAAM,uDAAuD,CAAC;AAG1F;;;GAGG;AACH,MAAM,UAAU,cAAc,CAAC,QAAqB;IACnD,OAAO,QAAQ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SAAS,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;YAClC,IAAI,OAAO,CAAC,QAAQ,EAAE,CAAC;gBACtB,SAAS,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;YAC5C,CAAC;iBAAM,CAAC;gBACP,mFAAmF;gBACnF,SAAS,CAAC,QAAQ,CACjB,IAAI,iBAAiB,CAAC;oBACrB,IAAI,EAAE,MAAM;oBACZ,cAAc,EAAE,oBAAoB;oBACpC,IAAI,EAAE,OAAO;oBACb,UAAU,EAAE,CAAC,MAAM,EAAE,EAAE,CACtB,GAAG,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,QAAQ,MAAM,cAAc,CAAC,IAAI,OAAO,CAAC,kBAAkB,EAAE,WAAW,CAAC,GAAG,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,CAAC,EAAE;iBAC1H,CAAC,CACF,CAAC;gBACF,MAAM,cAAc,GAAI,MAAM,CAAC,OAAsC,EAAE,cAAc,CAAC;gBACtF,IAAI,cAAc;oBAAE,SAAS,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,gBAAgB,cAAc,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;YAC7G,CAAC;YACD,OAAO,SAAS,CAAC;QAClB,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["/**\n * Adapts MCP tools to pi tool definitions.\n *\n * Results map onto pi's model-facing content (text and images). Text over 20KB keeps its start and\n * end with the middle cut out, like Codex does, and the full text is saved to a temp file the model\n * can read. Binary resources other than images are saved to temp files too, and resource links name\n * the `read_mcp_resource` tool. Codemode scripts receive the whole `CallToolResult` without `_meta`\n * (`content` blocks as sent by the server, `structuredContent`, `isError`), never truncated: it is\n * the tool's `structuredContent`, and every MCP tool declares a `CallToolResult` output schema. MCP\n * errors (`isError`) are error results for the model, but scripts still resolve to the result.\n */\n\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { ImageContent, JsonValue, TextContent } from \"@earendil-works/pi-ai\";\nimport {\n\ttype CallToolResult,\n\ttype ContentBlock,\n\ttype McpRequestOptions,\n\ttype Tool as McpTool,\n\ttoLlmContent,\n} from \"@earendil-works/pi-mcp\";\nimport { Container, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport type { TSchema } from \"typebox\";\nimport type {\n\tToolAnnotations,\n\tToolDefinition,\n\tToolExposure,\n\tToolNamespace,\n\tToolRenderers,\n} from \"../../core/extensions/types.ts\";\nimport { formatToolCallWithArgs, getTextOutput, replaceTabs } from \"../../core/tools/render-utils.ts\";\nimport { formatSize, truncateMiddle } from \"../../core/tools/truncate.ts\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { VisualLinePreview } from \"../../modes/interactive/components/visual-truncate.ts\";\nimport type { McpExposure } from \"./config.ts\";\n\n/**\n * Tool exposure of an MCP exposure. `codemode` and `deferred` both leave tools out of the codemode\n * description; they differ only in which tool the MCP extension activates to reach them.\n */\nexport function toToolExposure(exposure: McpExposure): ToolExposure {\n\treturn exposure === \"codemode\" ? \"deferred\" : exposure;\n}\n\n/** Provider tool names are limited to 64 characters of `[A-Za-z0-9_-]`. */\nconst MAX_TOOL_NAME_LENGTH = 64;\n/** Model-facing text of an MCP result beyond this is cut in the middle. */\nexport const MCP_OUTPUT_MAX_BYTES = 20 * 1024;\n/** Visual (wrapped) result lines shown before the output is expanded. */\nconst OUTPUT_PREVIEW_LINES = 5;\n/** Tool that reads the resources named by resource links. */\nexport const READ_MCP_RESOURCE_TOOL = \"read_mcp_resource\";\n\nexport interface McpToolDetails {\n\tserver: string;\n\ttool: string;\n\t/** Temp file with the full text output, when the model-facing text was truncated. */\n\tfullOutputPath?: string;\n}\n\n/**\n * Saves the full text of a truncated result, or a binary resource, and returns the file path.\n * `extension` includes the dot, for example `.txt`.\n */\nexport type McpOutputSaver = (data: string | Uint8Array, extension: string) => Promise<string>;\n\nexport async function saveToTempFile(data: string | Uint8Array, extension: string): Promise<string> {\n\tconst path = join(tmpdir(), `pi-mcp-${randomBytes(8).toString(\"hex\")}${extension}`);\n\t// Results can carry private data, so only the user may read the file.\n\tawait writeFile(path, data, { mode: 0o600 });\n\treturn path;\n}\n\nexport interface McpToolCaller {\n\tcallTool(name: string, args: Record<string, unknown>, options: McpRequestOptions): Promise<CallToolResult>;\n}\n\n/**\n * `mcp__<server>__<tool>`, sanitized and shortened with a hash suffix when too long. Like Codex,\n * everything but `[A-Za-z0-9_]` becomes `_`, so the name is also the identifier codemode scripts\n * call it by. `isTaken` reports names used by a different MCP tool: sanitizing can map two tools to\n * one name (`a-b` and `a_b`), which then get the hash suffix.\n */\nexport function createMcpToolName(\n\tserver: string,\n\ttool: string,\n\tisTaken: (name: string) => boolean = () => false,\n): string {\n\tconst name = `mcp__${server}__${tool}`.replace(/[^A-Za-z0-9_]/g, \"_\");\n\tif (name.length <= MAX_TOOL_NAME_LENGTH && !isTaken(name)) return name;\n\tconst hash = createHash(\"sha256\").update(`${server}\\0${tool}`).digest(\"hex\").slice(0, 8);\n\treturn `${name.slice(0, MAX_TOOL_NAME_LENGTH - hash.length - 1)}_${hash}`;\n}\n\nfunction textOf(content: readonly (TextContent | ImageContent)[]): string {\n\treturn 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\n/**\n * Output schema of every MCP tool: the `CallToolResult` scripts receive, with the tool's own output\n * schema as `structuredContent`. Codemode detects this shape to render `CallToolResult<T>`\n * declarations.\n */\nexport function createMcpResultSchema(structuredContentSchema: Record<string, unknown> | undefined): TSchema {\n\treturn {\n\t\ttype: \"object\",\n\t\tproperties: {\n\t\t\tcontent: { type: \"array\", items: { type: \"object\" } },\n\t\t\t...(structuredContentSchema ? { structuredContent: structuredContentSchema } : {}),\n\t\t\tisError: { type: \"boolean\" },\n\t\t\t_meta: { type: \"object\" },\n\t\t},\n\t\trequired: [\"content\"],\n\t} as unknown as TSchema;\n}\n\n/**\n * Keep model-facing text within {@link MCP_OUTPUT_MAX_BYTES}. Longer text becomes one text block in\n * Codex's truncation format, followed by the path of the file with the full text; images follow it.\n */\nexport async function limitMcpContent(\n\tcontent: (TextContent | ImageContent)[],\n\tsaveOutput: McpOutputSaver = saveToTempFile,\n): Promise<{ content: (TextContent | ImageContent)[]; fullOutputPath?: string }> {\n\tconst combined = textOf(content);\n\tconst truncation = truncateMiddle(combined, MCP_OUTPUT_MAX_BYTES);\n\tif (!truncation.truncated) return { content };\n\tlet fullOutputPath: string | undefined;\n\tlet where: string;\n\ttry {\n\t\tfullOutputPath = await saveOutput(combined, \".txt\");\n\t\twhere = `[Full output: ${fullOutputPath} (read it with offset/limit)]`;\n\t} catch (error) {\n\t\twhere = `[Could not save the full output: ${error instanceof Error ? error.message : String(error)}]`;\n\t}\n\tconst tokens = Math.ceil(truncation.totalBytes / 4);\n\tconst text = `Warning: truncated output (original token count: ${tokens})\\nTotal output lines: ${truncation.totalLines}\\n\\n${truncation.content}\\n\\n${where}`;\n\treturn {\n\t\tcontent: [{ type: \"text\", text }, ...content.filter((block) => block.type === \"image\")],\n\t\t...(fullOutputPath ? { fullOutputPath } : {}),\n\t};\n}\n\nexport interface ConvertMcpResultOptions {\n\t/** Saves truncated text and binary resources. Default: a temp file. */\n\tsaveOutput?: McpOutputSaver;\n\t/** Whether the server's resources can be read with `read_mcp_resource`, which resource links then name. */\n\treadableResources?: boolean;\n}\n\n/** File extension for a saved binary resource: the one its URI ends in, else `.bin`. */\nfunction extensionOf(uri: string): string {\n\tconst path = URL.canParse(uri) ? new URL(uri).pathname : uri;\n\treturn /\\.[A-Za-z0-9]{1,8}$/.exec(path)?.[0] ?? \".bin\";\n}\n\n/** Blobs of these types are shown as text. */\nfunction isTextMimeType(mimeType: string | undefined): boolean {\n\tif (!mimeType) return false;\n\tconst type = mimeType.split(\";\", 1)[0].trim().toLowerCase();\n\treturn type.startsWith(\"text/\") || type === \"application/json\" || type.endsWith(\"+json\") || type.endsWith(\"+xml\");\n}\n\n/** Model-facing content of one block of `server`'s result. */\nasync function blockToContent(\n\tserver: string,\n\tblock: ContentBlock,\n\toptions: ConvertMcpResultOptions,\n): Promise<(TextContent | ImageContent)[]> {\n\tif (block.type === \"resource_link\") {\n\t\tconst details = [block.mimeType, block.size === undefined ? undefined : formatSize(block.size)].filter(Boolean);\n\t\tconst read = options.readableResources ? `. Read it with ${READ_MCP_RESOURCE_TOOL} (server \"${server}\")` : \"\";\n\t\tconst description = block.description ? `: ${block.description}` : \"\";\n\t\treturn [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `[Resource ${block.uri} \"${block.title ?? block.name}\"${details.length > 0 ? ` (${details.join(\", \")})` : \"\"}${description}${read}]`,\n\t\t\t},\n\t\t];\n\t}\n\tif (block.type === \"resource\" && \"blob\" in block.resource && !block.resource.mimeType?.startsWith(\"image/\")) {\n\t\tconst { uri, mimeType, blob } = block.resource;\n\t\tconst data = Buffer.from(blob, \"base64\");\n\t\tif (isTextMimeType(mimeType)) return [{ type: \"text\", text: data.toString(\"utf8\") }];\n\t\tconst kind = `${mimeType ?? \"unknown type\"}, ${formatSize(data.length)}`;\n\t\ttry {\n\t\t\tconst path = await (options.saveOutput ?? saveToTempFile)(data, extensionOf(uri));\n\t\t\treturn [{ type: \"text\", text: `[Binary resource ${uri} (${kind}) saved to ${path}]` }];\n\t\t} catch (error) {\n\t\t\tconst reason = error instanceof Error ? error.message : String(error);\n\t\t\treturn [{ type: \"text\", text: `[Binary resource ${uri} (${kind}) could not be saved: ${reason}]` }];\n\t\t}\n\t}\n\treturn toLlmContent({ content: [block] });\n}\n\n/** Model-facing content of `server`'s content blocks, before the output limit. */\nexport async function toModelContent(\n\tserver: string,\n\tblocks: readonly ContentBlock[],\n\toptions: ConvertMcpResultOptions = {},\n): Promise<(TextContent | ImageContent)[]> {\n\treturn (await Promise.all(blocks.map((block) => blockToContent(server, block, options)))).flat();\n}\n\n/** Convert an MCP result. `isError` results become error results that keep the structured result. */\nexport async function convertMcpResult(\n\tserver: string,\n\ttool: string,\n\tresult: CallToolResult,\n\toptions: ConvertMcpResultOptions = {},\n): Promise<AgentToolResult<McpToolDetails>> {\n\t// Without content blocks, toLlmContent falls back to the structured content as JSON.\n\tconst converted: (TextContent | ImageContent)[] =\n\t\tresult.content.length > 0 ? await toModelContent(server, result.content, options) : toLlmContent(result);\n\tif (result.isError && textOf(converted) === \"\") {\n\t\tconverted.push({ type: \"text\", text: `MCP tool ${server}/${tool} returned an error` });\n\t}\n\tconst { content, fullOutputPath } = await limitMcpContent(converted, options.saveOutput);\n\tconst { _meta: _ignored, ...scriptResult } = result;\n\treturn {\n\t\tcontent,\n\t\tdetails: { server, tool, ...(fullOutputPath ? { fullOutputPath } : {}) },\n\t\tstructuredContent: scriptResult as unknown as JsonValue,\n\t\t...(result.isError ? { isError: true } : {}),\n\t};\n}\n\n/**\n * Tool input schemas must be objects. MCP servers may omit `type`, and some providers reject object\n * schemas without `properties`.\n */\nfunction toParameters(schema: Record<string, unknown>): TSchema {\n\treturn {\n\t\t...schema,\n\t\ttype: schema.type ?? \"object\",\n\t\t...(schema.properties === undefined ? { properties: {} } : {}),\n\t} as unknown as TSchema;\n}\n\nconst ANNOTATION_HINTS = [\"readOnlyHint\", \"destructiveHint\", \"idempotentHint\", \"openWorldHint\"] as const;\n\n/** The boolean hints of an MCP tool's annotations, or undefined when it has none. */\nfunction toToolAnnotations(tool: McpTool): ToolAnnotations | undefined {\n\tconst annotations: ToolAnnotations = {};\n\tfor (const hint of ANNOTATION_HINTS) {\n\t\tconst value = tool.annotations?.[hint];\n\t\tif (typeof value === \"boolean\") annotations[hint] = value;\n\t}\n\treturn Object.keys(annotations).length > 0 ? annotations : undefined;\n}\n\nexport function createMcpToolDefinition(options: {\n\tserver: string;\n\ttool: McpTool;\n\tname: string;\n\texposure: McpExposure;\n\tnamespace: ToolNamespace;\n\ttimeoutMs: number;\n\tgetClient: () => Promise<McpToolCaller>;\n\t/** Whether `read_mcp_resource` can read the server's resources. */\n\treadableResources?: () => boolean;\n}): ToolDefinition<TSchema, McpToolDetails> {\n\tconst { server, tool } = options;\n\tconst title = tool.title ?? tool.annotations?.title;\n\tconst annotations = toToolAnnotations(tool);\n\tconst label = `${server}/${tool.name}`;\n\treturn {\n\t\tname: options.name,\n\t\tlabel,\n\t\tdescription: tool.description?.trim() || title || `MCP tool ${tool.name} from server ${server}`,\n\t\tparameters: toParameters(tool.inputSchema),\n\t\toutputSchema: createMcpResultSchema(tool.outputSchema),\n\t\texposure: toToolExposure(options.exposure),\n\t\tnamespace: options.namespace,\n\t\t...(annotations ? { annotations } : {}),\n\t\t...createMcpToolRenderers(label),\n\t\tasync execute(_toolCallId, params, signal, onUpdate) {\n\t\t\tconst client = await options.getClient();\n\t\t\tconst result = await client.callTool(tool.name, (params ?? {}) as Record<string, unknown>, {\n\t\t\t\tsignal,\n\t\t\t\ttimeoutMs: options.timeoutMs,\n\t\t\t\tonProgress: (progress) => {\n\t\t\t\t\tconst total = progress.total === undefined ? \"\" : `/${progress.total}`;\n\t\t\t\t\tconst text = progress.message ?? `Progress ${progress.progress}${total}`;\n\t\t\t\t\tonUpdate?.({ content: [{ type: \"text\", text }], details: { server, tool: tool.name } });\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn convertMcpResult(server, tool.name, result, { readableResources: options.readableResources?.() });\n\t\t},\n\t};\n}\n\n/** Renderers of calls to an MCP tool, labeled `server/tool`, also used before the tool is registered. */\nexport function createMcpToolRenderers(label: string): ToolRenderers {\n\treturn {\n\t\trenderCall(args, theme, context) {\n\t\t\tconst component = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tcomponent.setText(formatToolCallWithArgs(label, args, theme, context.expanded));\n\t\t\treturn component;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\t\tcomponent.clear();\n\t\t\tconst output = getTextOutput(result, context.showImages).trim();\n\t\t\tif (!output) return component;\n\t\t\tconst color = context.isError ? \"error\" : \"toolOutput\";\n\t\t\tconst styled = replaceTabs(output)\n\t\t\t\t.split(\"\\n\")\n\t\t\t\t.map((line) => theme.fg(color, line))\n\t\t\t\t.join(\"\\n\");\n\t\t\tcomponent.addChild(new Spacer(1));\n\t\t\tif (options.expanded) {\n\t\t\t\tcomponent.addChild(new Text(styled, 0, 0));\n\t\t\t} else {\n\t\t\t\t// Limit wrapped lines, not logical ones: MCP results are often one long JSON line.\n\t\t\t\tcomponent.addChild(\n\t\t\t\t\tnew VisualLinePreview({\n\t\t\t\t\t\ttext: styled,\n\t\t\t\t\t\tmaxVisualLines: OUTPUT_PREVIEW_LINES,\n\t\t\t\t\t\tkeep: \"start\",\n\t\t\t\t\t\tformatHint: (hidden) =>\n\t\t\t\t\t\t\t`${theme.fg(\"muted\", `... (${hidden} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tconst fullOutputPath = (result.details as McpToolDetails | undefined)?.fullOutputPath;\n\t\t\t\tif (fullOutputPath) component.addChild(new Text(theme.fg(\"muted\", `Full output: ${fullOutputPath}`), 0, 0));\n\t\t\t}\n\t\t\treturn component;\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"tools.js","sourceRoot":"","sources":["../../../src/extensions/mcp/tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGzC,OAAO,EAKN,YAAY,GACZ,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,SAAS,EAAE,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AAC,MAAM,CAAC;iBAChC,KAAK,CAAC,IAAI,CAAC;iBACX,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;iBACpC,IAAI,CAAC,IAAI,CAAC,CAAC;YACb,SAAS,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;YAClC,IAAI,OAAO,CAAC,QAAQ,EAAE,CAAC;gBACtB,SAAS,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;YAC5C,CAAC;iBAAM,CAAC;gBACP,mFAAmF;gBACnF,SAAS,CAAC,QAAQ,CACjB,IAAI,iBAAiB,CAAC;oBACrB,IAAI,EAAE,MAAM;oBACZ,cAAc,EAAE,oBAAoB;oBACpC,IAAI,EAAE,OAAO;oBACb,UAAU,EAAE,CAAC,MAAM,EAAE,EAAE,CACtB,GAAG,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,QAAQ,MAAM,cAAc,CAAC,IAAI,OAAO,CAAC,kBAAkB,EAAE,WAAW,CAAC,GAAG,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,CAAC,EAAE;iBAC1H,CAAC,CACF,CAAC;gBACF,MAAM,cAAc,GAAI,MAAM,CAAC,OAAsC,EAAE,cAAc,CAAC;gBACtF,IAAI,cAAc;oBAAE,SAAS,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,gBAAgB,cAAc,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;YAC7G,CAAC;YACD,OAAO,SAAS,CAAC;QAClB,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["/**\n * Adapts MCP tools to pi tool definitions.\n *\n * Results map onto pi's model-facing content (text and images). Text over 20KB keeps its start and\n * end with the middle cut out, like Codex does, and the full text is saved to a temp file the model\n * can read. Binary resources other than images are saved to temp files too, and resource links name\n * the `read_mcp_resource` tool. Codemode scripts receive the whole `CallToolResult` without `_meta`\n * (`content` blocks as sent by the server, `structuredContent`, `isError`), never truncated: it is\n * the tool's `structuredContent`, and every MCP tool declares a `CallToolResult` output schema. MCP\n * errors (`isError`) are error results for the model, but scripts still resolve to the result.\n */\n\nimport { createHash } from \"node:crypto\";\nimport type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { ImageContent, JsonValue, TextContent } from \"@earendil-works/pi-ai\";\nimport {\n\ttype CallToolResult,\n\ttype ContentBlock,\n\ttype McpRequestOptions,\n\ttype Tool as McpTool,\n\ttoLlmContent,\n} from \"@earendil-works/pi-mcp\";\nimport { Container, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport type { TSchema } from \"typebox\";\nimport type {\n\tToolAnnotations,\n\tToolDefinition,\n\tToolExposure,\n\tToolNamespace,\n\tToolRenderers,\n} from \"../../core/extensions/types.ts\";\nimport { formatToolCallWithArgs, getTextOutput, replaceTabs } from \"../../core/tools/render-utils.ts\";\nimport { formatSize, truncateMiddle } from \"../../core/tools/truncate.ts\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { VisualLinePreview } from \"../../modes/interactive/components/visual-truncate.ts\";\nimport { writeOutputFile } from \"../../utils/output-files.ts\";\nimport type { McpExposure } from \"./config.ts\";\n\n/**\n * Tool exposure of an MCP exposure. `codemode` and `deferred` both leave tools out of the codemode\n * description; they differ only in which tool the MCP extension activates to reach them.\n */\nexport function toToolExposure(exposure: McpExposure): ToolExposure {\n\treturn exposure === \"codemode\" ? \"deferred\" : exposure;\n}\n\n/** Provider tool names are limited to 64 characters of `[A-Za-z0-9_-]`. */\nconst MAX_TOOL_NAME_LENGTH = 64;\n/** Model-facing text of an MCP result beyond this is cut in the middle. */\nexport const MCP_OUTPUT_MAX_BYTES = 20 * 1024;\n/** Visual (wrapped) result lines shown before the output is expanded. */\nconst OUTPUT_PREVIEW_LINES = 5;\n/** Tool that reads the resources named by resource links. */\nexport const READ_MCP_RESOURCE_TOOL = \"read_mcp_resource\";\n\nexport interface McpToolDetails {\n\tserver: string;\n\ttool: string;\n\t/** Temp file with the full text output, when the model-facing text was truncated. */\n\tfullOutputPath?: string;\n}\n\n/**\n * Saves the full text of a truncated result, or a binary resource, and returns the file path.\n * `extension` includes the dot, for example `.txt`.\n */\nexport type McpOutputSaver = (data: string | Uint8Array, extension: string) => Promise<string>;\n\nexport function saveToTempFile(data: string | Uint8Array, extension: string): Promise<string> {\n\treturn writeOutputFile(\"pi-mcp\", extension, data);\n}\n\nexport interface McpToolCaller {\n\tcallTool(name: string, args: Record<string, unknown>, options: McpRequestOptions): Promise<CallToolResult>;\n}\n\n/**\n * `mcp__<server>__<tool>`, sanitized and shortened with a hash suffix when too long. Like Codex,\n * everything but `[A-Za-z0-9_]` becomes `_`, so the name is also the identifier codemode scripts\n * call it by. `isTaken` reports names used by a different MCP tool: sanitizing can map two tools to\n * one name (`a-b` and `a_b`), which then get the hash suffix.\n */\nexport function createMcpToolName(\n\tserver: string,\n\ttool: string,\n\tisTaken: (name: string) => boolean = () => false,\n): string {\n\tconst name = `mcp__${server}__${tool}`.replace(/[^A-Za-z0-9_]/g, \"_\");\n\tif (name.length <= MAX_TOOL_NAME_LENGTH && !isTaken(name)) return name;\n\tconst hash = createHash(\"sha256\").update(`${server}\\0${tool}`).digest(\"hex\").slice(0, 8);\n\treturn `${name.slice(0, MAX_TOOL_NAME_LENGTH - hash.length - 1)}_${hash}`;\n}\n\nfunction textOf(content: readonly (TextContent | ImageContent)[]): string {\n\treturn 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\n/**\n * Output schema of every MCP tool: the `CallToolResult` scripts receive, with the tool's own output\n * schema as `structuredContent`. Codemode detects this shape to render `CallToolResult<T>`\n * declarations.\n */\nexport function createMcpResultSchema(structuredContentSchema: Record<string, unknown> | undefined): TSchema {\n\treturn {\n\t\ttype: \"object\",\n\t\tproperties: {\n\t\t\tcontent: { type: \"array\", items: { type: \"object\" } },\n\t\t\t...(structuredContentSchema ? { structuredContent: structuredContentSchema } : {}),\n\t\t\tisError: { type: \"boolean\" },\n\t\t\t_meta: { type: \"object\" },\n\t\t},\n\t\trequired: [\"content\"],\n\t} as unknown as TSchema;\n}\n\n/**\n * Keep model-facing text within {@link MCP_OUTPUT_MAX_BYTES}. Longer text becomes one text block in\n * Codex's truncation format, followed by the path of the file with the full text; images follow it.\n */\nexport async function limitMcpContent(\n\tcontent: (TextContent | ImageContent)[],\n\tsaveOutput: McpOutputSaver = saveToTempFile,\n): Promise<{ content: (TextContent | ImageContent)[]; fullOutputPath?: string }> {\n\tconst combined = textOf(content);\n\tconst truncation = truncateMiddle(combined, MCP_OUTPUT_MAX_BYTES);\n\tif (!truncation.truncated) return { content };\n\tlet fullOutputPath: string | undefined;\n\tlet where: string;\n\ttry {\n\t\tfullOutputPath = await saveOutput(combined, \".txt\");\n\t\twhere = `[Full output: ${fullOutputPath} (read it with offset/limit)]`;\n\t} catch (error) {\n\t\twhere = `[Could not save the full output: ${error instanceof Error ? error.message : String(error)}]`;\n\t}\n\tconst tokens = Math.ceil(truncation.totalBytes / 4);\n\tconst text = `Warning: truncated output (original token count: ${tokens})\\nTotal output lines: ${truncation.totalLines}\\n\\n${truncation.content}\\n\\n${where}`;\n\treturn {\n\t\tcontent: [{ type: \"text\", text }, ...content.filter((block) => block.type === \"image\")],\n\t\t...(fullOutputPath ? { fullOutputPath } : {}),\n\t};\n}\n\nexport interface ConvertMcpResultOptions {\n\t/** Saves truncated text and binary resources. Default: a temp file. */\n\tsaveOutput?: McpOutputSaver;\n\t/** Whether the server's resources can be read with `read_mcp_resource`, which resource links then name. */\n\treadableResources?: boolean;\n}\n\n/** File extension for a saved binary resource: the one its URI ends in, else `.bin`. */\nfunction extensionOf(uri: string): string {\n\tconst path = URL.canParse(uri) ? new URL(uri).pathname : uri;\n\treturn /\\.[A-Za-z0-9]{1,8}$/.exec(path)?.[0] ?? \".bin\";\n}\n\n/** Blobs of these types are shown as text. */\nfunction isTextMimeType(mimeType: string | undefined): boolean {\n\tif (!mimeType) return false;\n\tconst type = mimeType.split(\";\", 1)[0].trim().toLowerCase();\n\treturn type.startsWith(\"text/\") || type === \"application/json\" || type.endsWith(\"+json\") || type.endsWith(\"+xml\");\n}\n\n/** Model-facing content of one block of `server`'s result. */\nasync function blockToContent(\n\tserver: string,\n\tblock: ContentBlock,\n\toptions: ConvertMcpResultOptions,\n): Promise<(TextContent | ImageContent)[]> {\n\tif (block.type === \"resource_link\") {\n\t\tconst details = [block.mimeType, block.size === undefined ? undefined : formatSize(block.size)].filter(Boolean);\n\t\tconst read = options.readableResources ? `. Read it with ${READ_MCP_RESOURCE_TOOL} (server \"${server}\")` : \"\";\n\t\tconst description = block.description ? `: ${block.description}` : \"\";\n\t\treturn [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `[Resource ${block.uri} \"${block.title ?? block.name}\"${details.length > 0 ? ` (${details.join(\", \")})` : \"\"}${description}${read}]`,\n\t\t\t},\n\t\t];\n\t}\n\tif (block.type === \"resource\" && \"blob\" in block.resource && !block.resource.mimeType?.startsWith(\"image/\")) {\n\t\tconst { uri, mimeType, blob } = block.resource;\n\t\tconst data = Buffer.from(blob, \"base64\");\n\t\tif (isTextMimeType(mimeType)) return [{ type: \"text\", text: data.toString(\"utf8\") }];\n\t\tconst kind = `${mimeType ?? \"unknown type\"}, ${formatSize(data.length)}`;\n\t\ttry {\n\t\t\tconst path = await (options.saveOutput ?? saveToTempFile)(data, extensionOf(uri));\n\t\t\treturn [{ type: \"text\", text: `[Binary resource ${uri} (${kind}) saved to ${path}]` }];\n\t\t} catch (error) {\n\t\t\tconst reason = error instanceof Error ? error.message : String(error);\n\t\t\treturn [{ type: \"text\", text: `[Binary resource ${uri} (${kind}) could not be saved: ${reason}]` }];\n\t\t}\n\t}\n\treturn toLlmContent({ content: [block] });\n}\n\n/** Model-facing content of `server`'s content blocks, before the output limit. */\nexport async function toModelContent(\n\tserver: string,\n\tblocks: readonly ContentBlock[],\n\toptions: ConvertMcpResultOptions = {},\n): Promise<(TextContent | ImageContent)[]> {\n\treturn (await Promise.all(blocks.map((block) => blockToContent(server, block, options)))).flat();\n}\n\n/** Convert an MCP result. `isError` results become error results that keep the structured result. */\nexport async function convertMcpResult(\n\tserver: string,\n\ttool: string,\n\tresult: CallToolResult,\n\toptions: ConvertMcpResultOptions = {},\n): Promise<AgentToolResult<McpToolDetails>> {\n\t// Without content blocks, toLlmContent falls back to the structured content as JSON.\n\tconst converted: (TextContent | ImageContent)[] =\n\t\tresult.content.length > 0 ? await toModelContent(server, result.content, options) : toLlmContent(result);\n\tif (result.isError && textOf(converted) === \"\") {\n\t\tconverted.push({ type: \"text\", text: `MCP tool ${server}/${tool} returned an error` });\n\t}\n\tconst { content, fullOutputPath } = await limitMcpContent(converted, options.saveOutput);\n\tconst { _meta: _ignored, ...scriptResult } = result;\n\treturn {\n\t\tcontent,\n\t\tdetails: { server, tool, ...(fullOutputPath ? { fullOutputPath } : {}) },\n\t\tstructuredContent: scriptResult as unknown as JsonValue,\n\t\t...(result.isError ? { isError: true } : {}),\n\t};\n}\n\n/**\n * Tool input schemas must be objects. MCP servers may omit `type`, and some providers reject object\n * schemas without `properties`.\n */\nfunction toParameters(schema: Record<string, unknown>): TSchema {\n\treturn {\n\t\t...schema,\n\t\ttype: schema.type ?? \"object\",\n\t\t...(schema.properties === undefined ? { properties: {} } : {}),\n\t} as unknown as TSchema;\n}\n\nconst ANNOTATION_HINTS = [\"readOnlyHint\", \"destructiveHint\", \"idempotentHint\", \"openWorldHint\"] as const;\n\n/** The boolean hints of an MCP tool's annotations, or undefined when it has none. */\nfunction toToolAnnotations(tool: McpTool): ToolAnnotations | undefined {\n\tconst annotations: ToolAnnotations = {};\n\tfor (const hint of ANNOTATION_HINTS) {\n\t\tconst value = tool.annotations?.[hint];\n\t\tif (typeof value === \"boolean\") annotations[hint] = value;\n\t}\n\treturn Object.keys(annotations).length > 0 ? annotations : undefined;\n}\n\nexport function createMcpToolDefinition(options: {\n\tserver: string;\n\ttool: McpTool;\n\tname: string;\n\texposure: McpExposure;\n\tnamespace: ToolNamespace;\n\ttimeoutMs: number;\n\tgetClient: () => Promise<McpToolCaller>;\n\t/** Whether `read_mcp_resource` can read the server's resources. */\n\treadableResources?: () => boolean;\n}): ToolDefinition<TSchema, McpToolDetails> {\n\tconst { server, tool } = options;\n\tconst title = tool.title ?? tool.annotations?.title;\n\tconst annotations = toToolAnnotations(tool);\n\tconst label = `${server}/${tool.name}`;\n\treturn {\n\t\tname: options.name,\n\t\tlabel,\n\t\tdescription: tool.description?.trim() || title || `MCP tool ${tool.name} from server ${server}`,\n\t\tparameters: toParameters(tool.inputSchema),\n\t\toutputSchema: createMcpResultSchema(tool.outputSchema),\n\t\texposure: toToolExposure(options.exposure),\n\t\tnamespace: options.namespace,\n\t\t...(annotations ? { annotations } : {}),\n\t\t...createMcpToolRenderers(label),\n\t\tasync execute(_toolCallId, params, signal, onUpdate) {\n\t\t\tconst client = await options.getClient();\n\t\t\tconst result = await client.callTool(tool.name, (params ?? {}) as Record<string, unknown>, {\n\t\t\t\tsignal,\n\t\t\t\ttimeoutMs: options.timeoutMs,\n\t\t\t\tonProgress: (progress) => {\n\t\t\t\t\tconst total = progress.total === undefined ? \"\" : `/${progress.total}`;\n\t\t\t\t\tconst text = progress.message ?? `Progress ${progress.progress}${total}`;\n\t\t\t\t\tonUpdate?.({ content: [{ type: \"text\", text }], details: { server, tool: tool.name } });\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn convertMcpResult(server, tool.name, result, { readableResources: options.readableResources?.() });\n\t\t},\n\t};\n}\n\n/** Renderers of calls to an MCP tool, labeled `server/tool`, also used before the tool is registered. */\nexport function createMcpToolRenderers(label: string): ToolRenderers {\n\treturn {\n\t\trenderCall(args, theme, context) {\n\t\t\tconst component = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tcomponent.setText(formatToolCallWithArgs(label, args, theme, context.expanded));\n\t\t\treturn component;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\t\tcomponent.clear();\n\t\t\tconst output = getTextOutput(result, context.showImages).trim();\n\t\t\tif (!output) return component;\n\t\t\tconst color = context.isError ? \"error\" : \"toolOutput\";\n\t\t\tconst styled = replaceTabs(output)\n\t\t\t\t.split(\"\\n\")\n\t\t\t\t.map((line) => theme.fg(color, line))\n\t\t\t\t.join(\"\\n\");\n\t\t\tcomponent.addChild(new Spacer(1));\n\t\t\tif (options.expanded) {\n\t\t\t\tcomponent.addChild(new Text(styled, 0, 0));\n\t\t\t} else {\n\t\t\t\t// Limit wrapped lines, not logical ones: MCP results are often one long JSON line.\n\t\t\t\tcomponent.addChild(\n\t\t\t\t\tnew VisualLinePreview({\n\t\t\t\t\t\ttext: styled,\n\t\t\t\t\t\tmaxVisualLines: OUTPUT_PREVIEW_LINES,\n\t\t\t\t\t\tkeep: \"start\",\n\t\t\t\t\t\tformatHint: (hidden) =>\n\t\t\t\t\t\t\t`${theme.fg(\"muted\", `... (${hidden} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tconst fullOutputPath = (result.details as McpToolDetails | undefined)?.fullOutputPath;\n\t\t\t\tif (fullOutputPath) component.addChild(new Text(theme.fg(\"muted\", `Full output: ${fullOutputPath}`), 0, 0));\n\t\t\t}\n\t\t\treturn component;\n\t\t},\n\t};\n}\n"]}