@earendil-works/pi-coding-agent 0.99.1 → 0.99.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +40 -0
- package/dist/bundle/chunks/anthropic-messages-UID2PALB.js +6 -0
- package/dist/bundle/chunks/{azure-openai-responses-EN5WOBET.js → azure-openai-responses-TLHNIYZK.js} +1 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
- package/dist/bundle/chunks/{chunk-IMTXZUO7.js → chunk-3KYEVQKX.js} +3 -3
- package/dist/bundle/chunks/{chunk-W2DOMZSC.js → chunk-3LH3ZQKY.js} +1 -1
- package/dist/bundle/chunks/chunk-3NVH2HQH.js +4 -0
- package/dist/bundle/chunks/{chunk-GUORCHFS.js → chunk-3YAHQSW6.js} +23 -20
- package/dist/bundle/chunks/{chunk-LLMKQWZS.js → chunk-45SXDISG.js} +5 -7
- package/dist/bundle/chunks/chunk-6D7LHLKG.js +2 -0
- package/dist/bundle/chunks/{chunk-AXPY26X7.js → chunk-7QSPBJKW.js} +3 -3
- package/dist/bundle/chunks/{chunk-SLDA2X2H.js → chunk-ECRK44UV.js} +1 -1
- package/dist/bundle/chunks/{chunk-PEHWOV5U.js → chunk-G3UZ5FWD.js} +12 -23
- package/dist/bundle/chunks/chunk-LD2P6SFZ.js +2 -0
- package/dist/bundle/chunks/{chunk-J4CWPC4N.js → chunk-OSKPX3Z5.js} +1 -1
- package/dist/bundle/chunks/{chunk-LRS5S6EK.js → chunk-R5J3MOBF.js} +1 -1
- package/dist/bundle/chunks/chunk-VIV3CWXG.js +2 -0
- package/dist/bundle/chunks/{cli-AZXNGIZH.js → cli-ALNBTL3U.js} +6 -4
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-XJQQYGGU.js → cloudflare-workers-ai-system-one-NPQN263E.js} +1 -1
- package/dist/bundle/chunks/codemode-worker.js +23 -3
- package/dist/bundle/chunks/{execute-7XXPZAWW.js → execute-RC7W4ML3.js} +26 -6
- package/dist/bundle/chunks/github-copilot.js +1 -1
- package/dist/bundle/chunks/{google-generative-ai-CQAKKJTA.js → google-generative-ai-APTPZOQL.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-AE36YXJU.js → google-vertex-MXCOSOY3.js} +1 -1
- package/dist/bundle/chunks/{llama-cpp-classify-PJJYKPLD.js → llama-cpp-classify-XT44PI3C.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-KEYTXJM7.js → mistral-conversations-DKVFNQL6.js} +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-JQTCOVEG.js → openai-codex-responses-3GKGNXC4.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-XW2Q5HVC.js → openai-completions-JXDDPZ23.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-6AXWFL75.js → openai-responses-S7GKCCDG.js} +1 -1
- package/dist/bundle/chunks/{openrouter-images-TPQ4V6OR.js → openrouter-images-ZVXWCSIM.js} +1 -1
- package/dist/bundle/chunks/{runtime-G5WJPRBM.js → runtime-NJPX4ID2.js} +1 -1
- package/dist/bundle/chunks/{typesafe-system-one-E7A4HNJI.js → typesafe-system-one-A4CZTQWZ.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-5UGH4HRZ.js +2 -0
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/config.d.ts +5 -8
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +16 -13
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session.d.ts +7 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +14 -2
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +13 -1
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/types.d.ts +6 -1
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/mcp-servers.d.ts +28 -7
- package/dist/core/mcp-servers.d.ts.map +1 -1
- package/dist/core/mcp-servers.js +45 -11
- package/dist/core/mcp-servers.js.map +1 -1
- package/dist/core/model-runtime.d.ts +6 -0
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +22 -18
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/remote-catalog-provider.d.ts.map +1 -1
- package/dist/core/remote-catalog-provider.js +4 -9
- package/dist/core/remote-catalog-provider.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +1 -0
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/tools/renderers/bash.d.ts.map +1 -1
- package/dist/core/tools/renderers/bash.js +11 -31
- package/dist/core/tools/renderers/bash.js.map +1 -1
- package/dist/core/virtual-models.d.ts +2 -0
- package/dist/core/virtual-models.d.ts.map +1 -1
- package/dist/core/virtual-models.js +19 -12
- package/dist/core/virtual-models.js.map +1 -1
- package/dist/extensions/codemode/execute.d.ts.map +1 -1
- package/dist/extensions/codemode/execute.js +43 -4
- package/dist/extensions/codemode/execute.js.map +1 -1
- package/dist/extensions/codemode/renderer.d.ts.map +1 -1
- package/dist/extensions/codemode/renderer.js +43 -25
- package/dist/extensions/codemode/renderer.js.map +1 -1
- package/dist/extensions/codemode/tool.d.ts +5 -4
- package/dist/extensions/codemode/tool.d.ts.map +1 -1
- package/dist/extensions/codemode/tool.js +22 -31
- package/dist/extensions/codemode/tool.js.map +1 -1
- package/dist/extensions/codemode/worker.d.ts +1 -1
- package/dist/extensions/codemode/worker.js +1 -1
- package/dist/extensions/codemode/worker.js.map +1 -1
- package/dist/extensions/mcp/cli.d.ts.map +1 -1
- package/dist/extensions/mcp/cli.js +18 -3
- package/dist/extensions/mcp/cli.js.map +1 -1
- package/dist/extensions/mcp/config.d.ts +4 -2
- package/dist/extensions/mcp/config.d.ts.map +1 -1
- package/dist/extensions/mcp/config.js +14 -2
- package/dist/extensions/mcp/config.js.map +1 -1
- package/dist/extensions/mcp/index.d.ts +32 -8
- package/dist/extensions/mcp/index.d.ts.map +1 -1
- package/dist/extensions/mcp/index.js +205 -52
- package/dist/extensions/mcp/index.js.map +1 -1
- package/dist/extensions/mcp/oauth.d.ts +2 -0
- package/dist/extensions/mcp/oauth.d.ts.map +1 -1
- package/dist/extensions/mcp/oauth.js +1 -1
- package/dist/extensions/mcp/oauth.js.map +1 -1
- package/dist/extensions/mcp/runtime.d.ts +2 -0
- package/dist/extensions/mcp/runtime.d.ts.map +1 -1
- package/dist/extensions/mcp/runtime.js +14 -8
- package/dist/extensions/mcp/runtime.js.map +1 -1
- package/dist/extensions/mcp/tools.d.ts +5 -4
- package/dist/extensions/mcp/tools.d.ts.map +1 -1
- package/dist/extensions/mcp/tools.js +33 -15
- package/dist/extensions/mcp/tools.js.map +1 -1
- package/dist/extensions/mcp/ui.d.ts.map +1 -1
- package/dist/extensions/mcp/ui.js +4 -2
- package/dist/extensions/mcp/ui.js.map +1 -1
- package/dist/extensions/tool-search/tool.d.ts +5 -4
- package/dist/extensions/tool-search/tool.d.ts.map +1 -1
- package/dist/extensions/tool-search/tool.js +7 -28
- package/dist/extensions/tool-search/tool.js.map +1 -1
- package/dist/modes/interactive/components/visual-truncate.d.ts +27 -3
- package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
- package/dist/modes/interactive/components/visual-truncate.js +39 -6
- package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
- package/docs/cli.md +3 -3
- package/docs/extensions.md +3 -3
- package/docs/mcp.md +125 -82
- package/docs/providers.md +2 -0
- package/docs/sdk.md +1 -1
- package/docs/settings.md +3 -1
- package/examples/extensions/built-in-tool-renderer.ts +16 -40
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/minimal-mode.ts +24 -96
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/examples/sdk/14-codemode-mcp.ts +2 -2
- package/npm-shrinkwrap.json +26 -26
- package/package.json +10 -10
- package/dist/bundle/chunks/anthropic-messages-A6EXUBG6.js +0 -6
- package/dist/bundle/chunks/chunk-GOPCREV2.js +0 -4
- package/dist/bundle/chunks/chunk-HSPCVFST.js +0 -2
- package/dist/bundle/chunks/chunk-XNGRGP62.js +0 -2
- package/dist/bundle/chunks/virtual-modules-CSWRO37N.js +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execute.js","sourceRoot":"","sources":["../../../src/extensions/codemode/execute.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,OAAO,EAEN,eAAe,EAEf,eAAe,EACf,mBAAmB,EACnB,gBAAgB,EAChB,oBAAoB,GACpB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAG3E,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC1D,OAAO,EAAE,UAAU,EAAE,wBAAwB,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AACzG,OAAO,EACN,yBAAyB,EAOzB,wBAAwB,EACxB,yBAAyB,EACzB,qBAAqB,GACrB,MAAM,WAAW,CAAC;AAEnB,MAAM,kBAAkB,GAAG,GAAG,CAAC;AAC/B,MAAM,mBAAmB,GAAG,G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AC,GAAG,EAAE,GAAG,SAAS,CAAC;YAClD,MAAM,CAAC,MAAM,GAAG,MAAM,CAAC,UAAU,KAAK,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,OAAO,CAAC;YAC9G,IAAI,MAAM,CAAC,YAAY;gBAAE,MAAM,CAAC,KAAK,GAAG,YAAY,CAAC,MAAM,CAAC,YAAY,EAAE,mBAAmB,CAAC,CAAC;YAC/F,IAAI,MAAM,CAAC,KAAK,EAAE,CAAC;gBAClB,MAAM,CAAC,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC;gBACtC,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACxB,CAAC;YACD,OAAO,EAAE,CAAC;YACV,OAAO,MAAM,CAAC;QACf,CAAC;KACD,CAAC;IACF,OAAO,yBAAyB,CAAC,GAAG,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;QACtD,IAAI,EAAE,WAAW,CAAC,IAAI;QACtB,MAAM,EAAE,IAAI;QACZ,OAAO,EAAE,eAAe,CAAC,WAAW,CAAC,IAAI,CAAC;KAC1C,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * Runs one codemode script in the sandbox. Split from tool.ts and loaded through\n * execute.lazy.ts so the sandbox runtime only loads when a script runs.\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { AgentTool, AgentToolCallOutcome, AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { AnyModel, ClassifierContext, ImageContent, ModelType, TextContent, Usage } from \"@earendil-works/pi-ai\";\nimport {\n\ttype CodemodeResult,\n\tCodemodeSandbox,\n\ttype CodemodeTool,\n\tloadQuickJSWasm,\n\tparseCodemodeSource,\n\trenderToolSample,\n\ttoCodemodeIdentifier,\n} from \"@earendil-works/pi-codemode\";\nimport { getCodemodeWorkerUrl, getQuickJSWasmPath } from \"../../config.ts\";\nimport type { ExtensionToolContext } from \"../../core/extensions/types.ts\";\nimport type { SessionEntry } from \"../../core/session-manager.ts\";\nimport { combineUsage } from \"../../core/usage-totals.ts\";\nimport { Bm25Ranker, createToolSearchDocument, DEFAULT_TOOL_SEARCH_LIMIT } from \"../tool-search/tool.ts\";\nimport {\n\tCODEMODE_STORE_ENTRY_TYPE,\n\ttype CodemodeModelRuntime,\n\ttype CodemodeNestedCall,\n\ttype CodemodeStoreEntryData,\n\ttype CodemodeToolDetails,\n\ttype CodemodeToolInput,\n\ttype CodemodeToolOptions,\n\tgetCodemodeCallableTools,\n\tMODEL_GLOBAL_DECLARATIONS,\n\ttoCodemodeDeclaration,\n} from \"./tool.ts\";\n\nconst ARGS_PREVIEW_CHARS = 200;\nconst ERROR_PREVIEW_CHARS = 500;\n/** Classifier calls one script may have in flight; `Promise.all` over many items queues the rest. */\nconst MAX_CONCURRENT_MODEL_CALLS = 4;\n/**\n * Heap limit for the QuickJS VM. The worker shares pi's process, so without a limit a runaway\n * script can grow to wasm32's 4 GiB and take the session down. Overruns throw\n * `InternalError: out of memory` inside the script.\n */\nconst CODEMODE_MEMORY_LIMIT_BYTES = 256 * 1024 * 1024;\nconst MODEL_TYPES: ReadonlySet<string> = new Set<ModelType>([\"chat\", \"image\", \"classifier\"]);\n\nfunction truncateText(text: string, maxChars: number): string {\n\treturn text.length > maxChars ? `${text.slice(0, maxChars - 3)}...` : text;\n}\n\nfunction previewArgs(args: unknown): string {\n\tif (args === undefined) return \"\";\n\ttry {\n\t\treturn truncateText(JSON.stringify(args) ?? \"\", ARGS_PREVIEW_CHARS);\n\t} catch {\n\t\treturn \"\";\n\t}\n}\n\nfunction textOf(result: AgentToolResult<unknown>): string {\n\treturn (result.content ?? [])\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n}\n\nfunction toModelType(value: unknown): ModelType {\n\tif (typeof value === \"string\" && MODEL_TYPES.has(value)) return value as ModelType;\n\tthrow new Error(`Unknown model type ${JSON.stringify(value)}. Use \"chat\", \"image\", or \"classifier\".`);\n}\n\nfunction toProvider(value: unknown): string | undefined {\n\tif (value === undefined || value === null) return undefined;\n\tif (typeof value !== \"string\") throw new Error(\"provider must be a string\");\n\treturn value;\n}\n\n/** Catalog entry for scripts. `headers` is dropped because models.json headers can carry credentials. */\nfunction toModelInfo(model: AnyModel): Record<string, unknown> {\n\tconst info: Record<string, unknown> = { ...model };\n\tdelete info.headers;\n\treturn info;\n}\n\n/** Runs at most `limit` calls at once, in call order. */\nfunction createLimiter(limit: number): <T>(run: () => Promise<T>) => Promise<T> {\n\tlet active = 0;\n\tconst waiting: (() => void)[] = [];\n\treturn async (run) => {\n\t\tif (active >= limit) await new Promise<void>((resolve) => waiting.push(resolve));\n\t\tactive++;\n\t\ttry {\n\t\t\treturn await run();\n\t\t} finally {\n\t\t\tactive--;\n\t\t\twaiting.shift()?.();\n\t\t}\n\t};\n}\n\nfunction isStoreEntryData(data: unknown): data is CodemodeStoreEntryData {\n\tif (typeof data !== \"object\" || data === null) return false;\n\tconst { set, delete: deleted } = data as Partial<CodemodeStoreEntryData>;\n\treturn (\n\t\ttypeof set === \"object\" &&\n\t\tset !== null &&\n\t\tArray.isArray(deleted) &&\n\t\tdeleted.every((key: unknown) => typeof key === \"string\")\n\t);\n}\n\n/** Values of `load()`: the `codemode-store` entries on the branch, applied from the root. */\nexport function readCodemodeStore(branch: readonly SessionEntry[]): Record<string, unknown> {\n\tconst store = new Map<string, unknown>();\n\tfor (const entry of branch) {\n\t\tif (entry.type !== \"custom\" || entry.customType !== CODEMODE_STORE_ENTRY_TYPE || !isStoreEntryData(entry.data)) {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const key of entry.data.delete) store.delete(key);\n\t\tfor (const [key, value] of Object.entries(entry.data.set)) store.set(key, value);\n\t}\n\treturn Object.fromEntries(store);\n}\n\n/** Default token budget for script output. */\nconst DEFAULT_MAX_OUTPUT_TOKENS = 10_000;\n/** Characters per token when estimating. */\nconst CHARS_PER_TOKEN = 4;\n\n/** Like the script's `text()`: strings as is, other values as compact JSON. */\nfunction valueText(value: unknown): string {\n\tif (typeof value === \"string\") return value;\n\treturn JSON.stringify(value) ?? String(value);\n}\n\nfunction formatCallSummary(calls: readonly CodemodeNestedCall[]): string {\n\tif (calls.length === 0) return \"No tool calls were made.\";\n\treturn `Tool calls made before the failure (they are not undone): ${calls.map((call) => `${call.name} (${call.status})`).join(\", \")}`;\n}\n\nfunction formatError(result: Extract<CodemodeResult, { ok: false }>, calls: readonly CodemodeNestedCall[]): string {\n\tconst { error } = result;\n\tconst head =\n\t\terror.kind === \"script\"\n\t\t\t? (error.stack ?? `${error.name ?? \"Error\"}: ${error.message}`)\n\t\t\t: error.kind === \"timeout\"\n\t\t\t\t? `Script timed out: ${error.message}`\n\t\t\t\t: error.kind === \"aborted\"\n\t\t\t\t\t? `Script aborted: ${error.message}`\n\t\t\t\t\t: `Script sandbox failed: ${error.message}`;\n\treturn `${head}\\n\\n${formatCallSummary(calls)}`;\n}\n\n/** Write the full text output to a temp file, like bash does for truncated output. */\nasync function spillOutput(text: string): Promise<{ path: string } | { error: string }> {\n\tconst path = join(tmpdir(), `pi-codemode-${randomBytes(8).toString(\"hex\")}.txt`);\n\ttry {\n\t\tawait writeFile(path, text);\n\t\treturn { path };\n\t} catch (error) {\n\t\treturn { error: error instanceof Error ? error.message : String(error) };\n\t}\n}\n\n/**\n * Apply the token budget: when the combined text exceeds it, the text items become one\n * item that keeps the start and end of the text, and images follow it. The full text is written to\n * a temp file.\n */\nasync function truncateOutput(\n\titems: (TextContent | ImageContent)[],\n\tmaxTokens: number,\n): Promise<{ items: (TextContent | ImageContent)[]; fullOutputPath?: string }> {\n\tconst texts = items.filter((item): item is TextContent => item.type === \"text\").map((item) => item.text);\n\tconst combined = texts.join(\"\\n\");\n\tconst budget = maxTokens * CHARS_PER_TOKEN;\n\tif (texts.length === 0 || combined.length <= budget) return { items };\n\tconst headChars = Math.floor(budget / 2);\n\tconst tailChars = budget - headChars;\n\tconst removed = combined.length - headChars - tailChars;\n\tconst head = combined.slice(0, headChars);\n\tconst tail = tailChars > 0 ? combined.slice(-tailChars) : \"\";\n\tlet text = `Warning: truncated output (original token count: ${Math.ceil(combined.length / CHARS_PER_TOKEN)})\\nTotal output lines: ${combined.split(\"\\n\").length}\\n\\n${head}…${Math.ceil(removed / CHARS_PER_TOKEN)} tokens truncated…${tail}`;\n\tconst spilled = await spillOutput(combined);\n\ttext +=\n\t\t\"path\" in spilled\n\t\t\t? `\\n\\n[Full output: ${spilled.path} (read with offset/limit)]`\n\t\t\t: `\\n\\n[Could not save the full output: ${spilled.error}]`;\n\treturn {\n\t\titems: [{ type: \"text\", text }, ...items.filter((item) => item.type === \"image\")],\n\t\t...(\"path\" in spilled ? { fullOutputPath: spilled.path } : {}),\n\t};\n}\n\n/**\n * The value a script receives for a nested call: a tool that declares\n * `outputSchema` resolves to its `structuredContent`, also for error results that carry one (such\n * as MCP results with `isError`); any other tool resolves to its text content. Other failures\n * reject with the tool's error text.\n */\nfunction toScriptValue(tool: AgentTool<any>, outcome: AgentToolCallOutcome): unknown {\n\tconst { result } = outcome;\n\tif (tool.outputSchema && result.structuredContent !== undefined) return result.structuredContent;\n\tconst text = textOf(result);\n\tif (outcome.isError) throw new Error(text || `Tool \"${tool.name}\" failed`);\n\treturn text;\n}\n\n/**\n * Run one script. Without a session context (a plain Agent or a direct call) scripts cannot call\n * tools, `store()` starts empty, and writes are dropped.\n */\nexport async function executeCodemode(\n\ttoolCallId: string,\n\tinput: CodemodeToolInput,\n\tsignal: AbortSignal | undefined,\n\tonUpdate: ((result: AgentToolResult<CodemodeToolDetails>) => void) | undefined,\n\tctx: ExtensionToolContext | undefined,\n\toptions: CodemodeToolOptions = {},\n): Promise<AgentToolResult<CodemodeToolDetails>> {\n\tconst startedAt = performance.now();\n\tconst { code, options: sourceOptions } = parseCodemodeSource(input.code);\n\tconst calls: CodemodeNestedCall[] = [];\n\t// Usage of the script's `models.*` calls. Nested tool calls report theirs through the session.\n\tlet modelUsage: Usage | undefined;\n\tconst addModelUsage = (usage: Usage) => {\n\t\tmodelUsage = modelUsage ? combineUsage(modelUsage, usage) : usage;\n\t};\n\n\tconst snapshot = (): CodemodeToolDetails => ({ calls: calls.map((call) => ({ ...call })) });\n\tconst publish = () => onUpdate?.({ content: [], details: snapshot() });\n\n\tconst callable = ctx ? getCodemodeCallableTools(ctx.tools) : [];\n\t// ALL_TOOLS entries carry the declaration.\n\tconst samples = new Map(callable.map((tool) => [tool.name, renderToolSample(toCodemodeDeclaration(tool))]));\n\tconst sandboxTools: CodemodeTool[] = callable.map((tool) => ({\n\t\tname: tool.name,\n\t\tdescription: samples.get(tool.name),\n\t\texecute: async (args, { signal: callSignal }) => {\n\t\t\tconst record: CodemodeNestedCall = {\n\t\t\t\tid: `${toolCallId}/?`,\n\t\t\t\tname: tool.name,\n\t\t\t\targs: previewArgs(args),\n\t\t\t\tstatus: \"running\",\n\t\t\t};\n\t\t\tcalls.push(record);\n\t\t\tpublish();\n\t\t\tconst callStartedAt = performance.now();\n\t\t\t// Only tools from ctx.tools are callable, so ctx is set here.\n\t\t\tif (!ctx) throw new Error(\"Tool calls need a session\");\n\t\t\tconst outcome = await ctx.executeTool(tool.name, args, { signal: callSignal });\n\t\t\trecord.id = outcome.toolCall.id;\n\t\t\trecord.durationMs = performance.now() - callStartedAt;\n\t\t\tif (outcome.isError) {\n\t\t\t\trecord.status = callSignal.aborted ? \"cancelled\" : \"error\";\n\t\t\t\trecord.error = truncateText(textOf(outcome.result) || `Tool \"${tool.name}\" failed`, ERROR_PREVIEW_CHARS);\n\t\t\t} else {\n\t\t\t\trecord.status = \"ok\";\n\t\t\t}\n\t\t\tpublish();\n\t\t\treturn toScriptValue(tool, outcome);\n\t\t},\n\t}));\n\n\tconst sandbox = new CodemodeSandbox({\n\t\ttools: sandboxTools,\n\t\tglobals: [\n\t\t\t...createDiscoveryGlobals(callable, samples, options),\n\t\t\t...(options.models && ctx\n\t\t\t\t? createModelGlobals(ctx.modelRegistry, toolCallId, calls, publish, addModelUsage)\n\t\t\t\t: []),\n\t\t],\n\t\ttimeoutMs: sourceOptions.timeoutMs ?? Number.POSITIVE_INFINITY,\n\t\tmemoryLimitBytes: CODEMODE_MEMORY_LIMIT_BYTES,\n\t\twasm: loadQuickJSWasm(getQuickJSWasmPath()),\n\t\tworkerUrl: getCodemodeWorkerUrl(),\n\t});\n\n\tlet result: CodemodeResult;\n\ttry {\n\t\tconst store = ctx ? readCodemodeStore(ctx.sessionManager.getBranch()) : {};\n\t\tresult = await sandbox.execute(code, { signal, store });\n\t} finally {\n\t\tawait sandbox.close();\n\t}\n\t// Calls still marked running were cut off by the script ending, a timeout, or an abort.\n\tfor (const call of calls) {\n\t\tif (call.status === \"running\") call.status = \"cancelled\";\n\t}\n\n\tconst items: (TextContent | ImageContent)[] = result.output.map((item) =>\n\t\titem.type === \"text\" ? { type: \"text\", text: item.text } : item,\n\t);\n\tif (result.ok) {\n\t\tconst { set, delete: deleted } = result.storeWrites;\n\t\tif (Object.keys(set).length > 0 || deleted.length > 0) {\n\t\t\toptions.appendEntry?.(CODEMODE_STORE_ENTRY_TYPE, { set, delete: deleted });\n\t\t}\n\t\t// pi extension: a returned value is appended like text().\n\t\tif (result.value !== undefined) items.push({ type: \"text\", text: valueText(result.value) });\n\t} else {\n\t\titems.push({ type: \"text\", text: `Script error:\\n${formatError(result, calls)}` });\n\t}\n\n\tconst truncated = await truncateOutput(items, sourceOptions.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS);\n\tconst wallTime = ((performance.now() - startedAt) / 1000).toFixed(1);\n\tconst header = `${result.ok ? \"Script completed\" : \"Script failed\"}\\nWall time ${wallTime} seconds\\nOutput:\\n`;\n\tconst details = snapshot();\n\tif (truncated.fullOutputPath) details.fullOutputPath = truncated.fullOutputPath;\n\treturn {\n\t\tcontent: [{ type: \"text\", text: header }, ...truncated.items],\n\t\tdetails,\n\t\t...(modelUsage ? { usage: modelUsage } : {}),\n\t\t...(result.ok ? {} : { isError: true }),\n\t};\n}\n\n/** `searchTools()` and `describeTool()`: ranked search and lookup over the script's nested tools. */\nfunction createDiscoveryGlobals(\n\ttools: readonly AgentTool<any>[],\n\tsamples: ReadonlyMap<string, string>,\n\toptions: CodemodeToolOptions,\n): CodemodeTool[] {\n\tconst ranker = new Bm25Ranker();\n\tconst entry = (name: string) => ({ name: toCodemodeIdentifier(name), description: samples.get(name) ?? \"\" });\n\treturn [\n\t\t{\n\t\t\tname: \"searchTools\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [query, searchOptions] = args as [unknown, { limit?: unknown; namespace?: unknown } | undefined];\n\t\t\t\tif (typeof query !== \"string\") throw new Error(\"searchTools() expects a query string\");\n\t\t\t\tconst limit = searchOptions?.limit ?? DEFAULT_TOOL_SEARCH_LIMIT;\n\t\t\t\tif (typeof limit !== \"number\" || !Number.isInteger(limit) || limit <= 0) {\n\t\t\t\t\tthrow new Error(\"searchTools() limit must be a positive integer\");\n\t\t\t\t}\n\t\t\t\tconst namespace = searchOptions?.namespace;\n\t\t\t\tif (namespace !== undefined && namespace !== null && typeof namespace !== \"string\") {\n\t\t\t\t\tthrow new Error(\"searchTools() namespace must be a string\");\n\t\t\t\t}\n\t\t\t\tconst documents = tools.flatMap((tool) => {\n\t\t\t\t\tconst toolNamespace = options.getToolNamespace?.(tool.name);\n\t\t\t\t\tif (namespace && toolNamespace?.name !== namespace) return [];\n\t\t\t\t\treturn [createToolSearchDocument(tool, toolNamespace)];\n\t\t\t\t});\n\t\t\t\treturn ranker.rank(query, documents, limit).map((match) => entry(match.name));\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"describeTool\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [name] = args as unknown[];\n\t\t\t\tif (typeof name !== \"string\") throw new Error(\"describeTool() expects a tool name\");\n\t\t\t\tconst tool = tools.find(\n\t\t\t\t\t(candidate) => candidate.name === name || toCodemodeIdentifier(candidate.name) === name,\n\t\t\t\t);\n\t\t\t\treturn tool ? samples.get(tool.name) : undefined;\n\t\t\t},\n\t\t},\n\t];\n}\n\n/**\n * `models.*` for scripts: the model registry methods declared in {@link MODEL_GLOBAL_DECLARATIONS}.\n * Classifier calls appear as nested call rows so the renderer shows them, and their usage goes to\n * `addUsage`.\n */\nfunction createModelGlobals(\n\tmodels: CodemodeModelRuntime,\n\ttoolCallId: string,\n\tcalls: CodemodeNestedCall[],\n\tpublish: () => void,\n\taddUsage: (usage: Usage) => void,\n): CodemodeTool[] {\n\tconst limit = createLimiter(MAX_CONCURRENT_MODEL_CALLS);\n\tlet classifyCount = 0;\n\tconst implementations: Record<string, CodemodeTool[\"execute\"]> = {\n\t\t\"models.getModelsOfType\": (args) => {\n\t\t\tconst [type, provider] = args as unknown[];\n\t\t\treturn models.getModelsOfType(toModelType(type), toProvider(provider)).map(toModelInfo);\n\t\t},\n\t\t\"models.getAvailableOfType\": async (args, { signal }) => {\n\t\t\tconst [type, provider] = args as unknown[];\n\t\t\tconst available = await models.getAvailableOfType(toModelType(type), toProvider(provider), { signal });\n\t\t\treturn available.map(toModelInfo);\n\t\t},\n\t\t\"models.getModelOfType\": (args) => {\n\t\t\tconst [type, provider, id] = args as unknown[];\n\t\t\tif (typeof provider !== \"string\" || typeof id !== \"string\") {\n\t\t\t\tthrow new Error(\"models.getModelOfType() expects a type, a provider, and an id\");\n\t\t\t}\n\t\t\tconst model = models.getModelOfType(toModelType(type), provider, id);\n\t\t\treturn model === undefined ? undefined : toModelInfo(model);\n\t\t},\n\t\t\"models.classify\": async (args, { signal }) => {\n\t\t\tconst [model, context] = args as unknown[];\n\t\t\tconst ref = model as { provider?: unknown; id?: unknown } | null;\n\t\t\tif (\n\t\t\t\ttypeof ref !== \"object\" ||\n\t\t\t\tref === null ||\n\t\t\t\ttypeof ref.provider !== \"string\" ||\n\t\t\t\ttypeof ref.id !== \"string\"\n\t\t\t) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"models.classify() expects a model from models.getModelOfType() or models.getAvailableOfType()\",\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Only provider and id count. A script-supplied baseUrl or headers must never receive the credentials.\n\t\t\tconst resolved = models.getModelOfType(\"classifier\", ref.provider, ref.id);\n\t\t\tif (!resolved) throw new Error(`Unknown classifier model \"${ref.provider}/${ref.id}\"`);\n\n\t\t\tconst record: CodemodeNestedCall = {\n\t\t\t\tid: `${toolCallId}/models.classify/${++classifyCount}`,\n\t\t\t\tname: \"models.classify\",\n\t\t\t\targs: `${resolved.provider}/${resolved.id}`,\n\t\t\t\tstatus: \"running\",\n\t\t\t};\n\t\t\tcalls.push(record);\n\t\t\tpublish();\n\t\t\tconst startedAt = performance.now();\n\t\t\tconst result = await limit(() => models.classify(resolved, context as ClassifierContext, { signal }));\n\t\t\trecord.durationMs = performance.now() - startedAt;\n\t\t\trecord.status = result.stopReason === \"stop\" ? \"ok\" : result.stopReason === \"aborted\" ? \"cancelled\" : \"error\";\n\t\t\tif (result.errorMessage) record.error = truncateText(result.errorMessage, ERROR_PREVIEW_CHARS);\n\t\t\tif (result.usage) {\n\t\t\t\trecord.cost = result.usage.cost.total;\n\t\t\t\taddUsage(result.usage);\n\t\t\t}\n\t\t\tpublish();\n\t\t\treturn result;\n\t\t},\n\t};\n\treturn MODEL_GLOBAL_DECLARATIONS.map((declaration) => ({\n\t\tname: declaration.name,\n\t\tspread: true,\n\t\texecute: implementations[declaration.name],\n\t}));\n}\n"]}
|
|
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,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W,CAAC,CAAC,CAAC,OAAO,CAAC;YAC9G,IAAI,MAAM,CAAC,YAAY;gBAAE,MAAM,CAAC,KAAK,GAAG,YAAY,CAAC,MAAM,CAAC,YAAY,EAAE,mBAAmB,CAAC,CAAC;YAC/F,IAAI,MAAM,CAAC,KAAK,EAAE,CAAC;gBAClB,MAAM,CAAC,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC;gBACtC,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACxB,CAAC;YACD,OAAO,EAAE,CAAC;YACV,OAAO,MAAM,CAAC;QACf,CAAC;KACD,CAAC;IACF,OAAO,yBAAyB,CAAC,GAAG,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;QACtD,IAAI,EAAE,WAAW,CAAC,IAAI;QACtB,MAAM,EAAE,IAAI;QACZ,OAAO,EAAE,eAAe,CAAC,WAAW,CAAC,IAAI,CAAC;KAC1C,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * Runs one codemode script in the sandbox. Split from tool.ts and loaded through\n * execute.lazy.ts so the sandbox runtime only loads when a script runs.\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { AgentTool, AgentToolCallOutcome, AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { AnyModel, ClassifierContext, ImageContent, ModelType, TextContent, Usage } from \"@earendil-works/pi-ai\";\nimport {\n\ttype CodemodeResult,\n\tCodemodeSandbox,\n\ttype CodemodeTool,\n\tloadQuickJSWasm,\n\tparseCodemodeSource,\n\trenderToolSample,\n\ttoCodemodeIdentifier,\n} from \"@earendil-works/pi-codemode\";\nimport { getCodemodeWorkerSpecifier, getQuickJSWasmPath } from \"../../config.ts\";\nimport type { ExtensionToolContext, ToolNamespace } from \"../../core/extensions/types.ts\";\nimport type { SessionEntry } from \"../../core/session-manager.ts\";\nimport { combineUsage } from \"../../core/usage-totals.ts\";\nimport { Bm25Ranker, createToolSearchDocument, DEFAULT_TOOL_SEARCH_LIMIT } from \"../tool-search/tool.ts\";\nimport {\n\tCODEMODE_STORE_ENTRY_TYPE,\n\ttype CodemodeModelRuntime,\n\ttype CodemodeNestedCall,\n\ttype CodemodeStoreEntryData,\n\ttype CodemodeToolDetails,\n\ttype CodemodeToolInput,\n\ttype CodemodeToolOptions,\n\tgetCodemodeCallableTools,\n\tMODEL_GLOBAL_DECLARATIONS,\n\ttoCodemodeDeclaration,\n} from \"./tool.ts\";\n\nconst ARGS_PREVIEW_CHARS = 200;\nconst ERROR_PREVIEW_CHARS = 500;\n/** Classifier calls one script may have in flight; `Promise.all` over many items queues the rest. */\nconst MAX_CONCURRENT_MODEL_CALLS = 4;\n/**\n * Heap limit for the QuickJS VM. The worker shares pi's process, so without a limit a runaway\n * script can grow to wasm32's 4 GiB and take the session down. Overruns throw\n * `InternalError: out of memory` inside the script.\n */\nconst CODEMODE_MEMORY_LIMIT_BYTES = 256 * 1024 * 1024;\nconst MODEL_TYPES: ReadonlySet<string> = new Set<ModelType>([\"chat\", \"image\", \"classifier\"]);\n\nfunction truncateText(text: string, maxChars: number): string {\n\treturn text.length > maxChars ? `${text.slice(0, maxChars - 3)}...` : text;\n}\n\nfunction previewArgs(args: unknown): string {\n\tif (args === undefined) return \"\";\n\ttry {\n\t\treturn truncateText(JSON.stringify(args) ?? \"\", ARGS_PREVIEW_CHARS);\n\t} catch {\n\t\treturn \"\";\n\t}\n}\n\nfunction textOf(result: AgentToolResult<unknown>): string {\n\treturn (result.content ?? [])\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n}\n\nfunction toModelType(value: unknown): ModelType {\n\tif (typeof value === \"string\" && MODEL_TYPES.has(value)) return value as ModelType;\n\tthrow new Error(`Unknown model type ${JSON.stringify(value)}. Use \"chat\", \"image\", or \"classifier\".`);\n}\n\nfunction toProvider(value: unknown): string | undefined {\n\tif (value === undefined || value === null) return undefined;\n\tif (typeof value !== \"string\") throw new Error(\"provider must be a string\");\n\treturn value;\n}\n\n/** Catalog entry for scripts. `headers` is dropped because models.json headers can carry credentials. */\nfunction toModelInfo(model: AnyModel): Record<string, unknown> {\n\tconst info: Record<string, unknown> = { ...model };\n\tdelete info.headers;\n\treturn info;\n}\n\n/** Runs at most `limit` calls at once, in call order. */\nfunction createLimiter(limit: number): <T>(run: () => Promise<T>) => Promise<T> {\n\tlet active = 0;\n\tconst waiting: (() => void)[] = [];\n\treturn async (run) => {\n\t\tif (active >= limit) await new Promise<void>((resolve) => waiting.push(resolve));\n\t\tactive++;\n\t\ttry {\n\t\t\treturn await run();\n\t\t} finally {\n\t\t\tactive--;\n\t\t\twaiting.shift()?.();\n\t\t}\n\t};\n}\n\nfunction isStoreEntryData(data: unknown): data is CodemodeStoreEntryData {\n\tif (typeof data !== \"object\" || data === null) return false;\n\tconst { set, delete: deleted } = data as Partial<CodemodeStoreEntryData>;\n\treturn (\n\t\ttypeof set === \"object\" &&\n\t\tset !== null &&\n\t\tArray.isArray(deleted) &&\n\t\tdeleted.every((key: unknown) => typeof key === \"string\")\n\t);\n}\n\n/** Values of `load()`: the `codemode-store` entries on the branch, applied from the root. */\nexport function readCodemodeStore(branch: readonly SessionEntry[]): Record<string, unknown> {\n\tconst store = new Map<string, unknown>();\n\tfor (const entry of branch) {\n\t\tif (entry.type !== \"custom\" || entry.customType !== CODEMODE_STORE_ENTRY_TYPE || !isStoreEntryData(entry.data)) {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const key of entry.data.delete) store.delete(key);\n\t\tfor (const [key, value] of Object.entries(entry.data.set)) store.set(key, value);\n\t}\n\treturn Object.fromEntries(store);\n}\n\n/** Default token budget for script output. */\nconst DEFAULT_MAX_OUTPUT_TOKENS = 10_000;\n/** Characters per token when estimating. */\nconst CHARS_PER_TOKEN = 4;\n\n/** Like the script's `text()`: strings as is, other values as compact JSON. */\nfunction valueText(value: unknown): string {\n\tif (typeof value === \"string\") return value;\n\treturn JSON.stringify(value) ?? String(value);\n}\n\nfunction formatCallSummary(calls: readonly CodemodeNestedCall[]): string {\n\tif (calls.length === 0) return \"No tool calls were made.\";\n\treturn `Tool calls made before the failure (they are not undone): ${calls.map((call) => `${call.name} (${call.status})`).join(\", \")}`;\n}\n\nfunction formatError(result: Extract<CodemodeResult, { ok: false }>, calls: readonly CodemodeNestedCall[]): string {\n\tconst { error } = result;\n\tconst head =\n\t\terror.kind === \"script\"\n\t\t\t? (error.stack ?? `${error.name ?? \"Error\"}: ${error.message}`)\n\t\t\t: error.kind === \"timeout\"\n\t\t\t\t? `Script timed out: ${error.message}`\n\t\t\t\t: error.kind === \"aborted\"\n\t\t\t\t\t? `Script aborted: ${error.message}`\n\t\t\t\t\t: `Script sandbox failed: ${error.message}`;\n\treturn `${head}\\n\\n${formatCallSummary(calls)}`;\n}\n\n/** Write the full text output to a temp file, like bash does for truncated output. */\nasync function spillOutput(text: string): Promise<{ path: string } | { error: string }> {\n\tconst path = join(tmpdir(), `pi-codemode-${randomBytes(8).toString(\"hex\")}.txt`);\n\ttry {\n\t\tawait writeFile(path, text);\n\t\treturn { path };\n\t} catch (error) {\n\t\treturn { error: error instanceof Error ? error.message : String(error) };\n\t}\n}\n\n/**\n * Apply the token budget: when the combined text exceeds it, the text items become one\n * item that keeps the start and end of the text, and images follow it. The full text is written to\n * a temp file.\n */\nasync function truncateOutput(\n\titems: (TextContent | ImageContent)[],\n\tmaxTokens: number,\n): Promise<{ items: (TextContent | ImageContent)[]; fullOutputPath?: string }> {\n\tconst texts = items.filter((item): item is TextContent => item.type === \"text\").map((item) => item.text);\n\tconst combined = texts.join(\"\\n\");\n\tconst budget = maxTokens * CHARS_PER_TOKEN;\n\tif (texts.length === 0 || combined.length <= budget) return { items };\n\tconst headChars = Math.floor(budget / 2);\n\tconst tailChars = budget - headChars;\n\tconst removed = combined.length - headChars - tailChars;\n\tconst head = combined.slice(0, headChars);\n\tconst tail = tailChars > 0 ? combined.slice(-tailChars) : \"\";\n\tlet text = `Warning: truncated output (original token count: ${Math.ceil(combined.length / CHARS_PER_TOKEN)})\\nTotal output lines: ${combined.split(\"\\n\").length}\\n\\n${head}…${Math.ceil(removed / CHARS_PER_TOKEN)} tokens truncated…${tail}`;\n\tconst spilled = await spillOutput(combined);\n\ttext +=\n\t\t\"path\" in spilled\n\t\t\t? `\\n\\n[Full output: ${spilled.path} (read with offset/limit)]`\n\t\t\t: `\\n\\n[Could not save the full output: ${spilled.error}]`;\n\treturn {\n\t\titems: [{ type: \"text\", text }, ...items.filter((item) => item.type === \"image\")],\n\t\t...(\"path\" in spilled ? { fullOutputPath: spilled.path } : {}),\n\t};\n}\n\n/**\n * The value a script receives for a nested call: a tool that declares\n * `outputSchema` resolves to its `structuredContent`, also for error results that carry one (such\n * as MCP results with `isError`); any other tool resolves to its text content. Other failures\n * reject with the tool's error text.\n */\nfunction toScriptValue(tool: AgentTool<any>, outcome: AgentToolCallOutcome): unknown {\n\tconst { result } = outcome;\n\tif (tool.outputSchema && result.structuredContent !== undefined) return result.structuredContent;\n\tconst text = textOf(result);\n\tif (outcome.isError) throw new Error(text || `Tool \"${tool.name}\" failed`);\n\treturn text;\n}\n\n/**\n * Run one script. Without a session context (a plain Agent or a direct call) scripts cannot call\n * tools, `store()` starts empty, and writes are dropped.\n */\nexport async function executeCodemode(\n\ttoolCallId: string,\n\tinput: CodemodeToolInput,\n\tsignal: AbortSignal | undefined,\n\tonUpdate: ((result: AgentToolResult<CodemodeToolDetails>) => void) | undefined,\n\tctx: ExtensionToolContext | undefined,\n\toptions: CodemodeToolOptions = {},\n): Promise<AgentToolResult<CodemodeToolDetails>> {\n\tconst startedAt = performance.now();\n\tconst { code, options: sourceOptions } = parseCodemodeSource(input.code);\n\tconst calls: CodemodeNestedCall[] = [];\n\t// Usage of the script's `models.*` calls. Nested tool calls report theirs through the session.\n\tlet modelUsage: Usage | undefined;\n\tconst addModelUsage = (usage: Usage) => {\n\t\tmodelUsage = modelUsage ? combineUsage(modelUsage, usage) : usage;\n\t};\n\n\tconst snapshot = (): CodemodeToolDetails => ({ calls: calls.map((call) => ({ ...call })) });\n\tconst publish = () => onUpdate?.({ content: [], details: snapshot() });\n\n\tconst callable = ctx ? getCodemodeCallableTools(ctx.tools) : [];\n\t// ALL_TOOLS entries carry the declaration.\n\tconst samples = new Map(callable.map((tool) => [tool.name, renderToolSample(toCodemodeDeclaration(tool))]));\n\tconst sandboxTools: CodemodeTool[] = callable.map((tool) => ({\n\t\tname: tool.name,\n\t\tdescription: samples.get(tool.name),\n\t\texecute: async (args, { signal: callSignal }) => {\n\t\t\tconst record: CodemodeNestedCall = {\n\t\t\t\tid: `${toolCallId}/?`,\n\t\t\t\tname: tool.name,\n\t\t\t\targs: previewArgs(args),\n\t\t\t\tstatus: \"running\",\n\t\t\t};\n\t\t\tcalls.push(record);\n\t\t\tpublish();\n\t\t\tconst callStartedAt = performance.now();\n\t\t\t// Only tools from ctx.tools are callable, so ctx is set here.\n\t\t\tif (!ctx) throw new Error(\"Tool calls need a session\");\n\t\t\tconst outcome = await ctx.executeTool(tool.name, args, { signal: callSignal });\n\t\t\trecord.id = outcome.toolCall.id;\n\t\t\trecord.durationMs = performance.now() - callStartedAt;\n\t\t\tif (outcome.isError) {\n\t\t\t\trecord.status = callSignal.aborted ? \"cancelled\" : \"error\";\n\t\t\t\trecord.error = truncateText(textOf(outcome.result) || `Tool \"${tool.name}\" failed`, ERROR_PREVIEW_CHARS);\n\t\t\t} else {\n\t\t\t\trecord.status = \"ok\";\n\t\t\t}\n\t\t\tpublish();\n\t\t\treturn toScriptValue(tool, outcome);\n\t\t},\n\t}));\n\n\tconst sandbox = new CodemodeSandbox({\n\t\ttools: sandboxTools,\n\t\tglobals: [\n\t\t\t...createDiscoveryGlobals(callable, samples, options),\n\t\t\t...(options.models && ctx\n\t\t\t\t? createModelGlobals(ctx.modelRegistry, toolCallId, calls, publish, addModelUsage)\n\t\t\t\t: []),\n\t\t],\n\t\ttimeoutMs: sourceOptions.timeoutMs ?? Number.POSITIVE_INFINITY,\n\t\tmemoryLimitBytes: CODEMODE_MEMORY_LIMIT_BYTES,\n\t\twasm: loadQuickJSWasm(getQuickJSWasmPath()),\n\t\tworkerUrl: getCodemodeWorkerSpecifier(),\n\t});\n\n\tlet result: CodemodeResult;\n\ttry {\n\t\tconst store = ctx ? readCodemodeStore(ctx.sessionManager.getBranch()) : {};\n\t\tresult = await sandbox.execute(code, { signal, store });\n\t} finally {\n\t\tawait sandbox.close();\n\t}\n\t// Calls still marked running were cut off by the script ending, a timeout, or an abort.\n\tfor (const call of calls) {\n\t\tif (call.status === \"running\") call.status = \"cancelled\";\n\t}\n\n\tconst items: (TextContent | ImageContent)[] = result.output.map((item) =>\n\t\titem.type === \"text\" ? { type: \"text\", text: item.text } : item,\n\t);\n\tif (result.ok) {\n\t\tconst { set, delete: deleted } = result.storeWrites;\n\t\tif (Object.keys(set).length > 0 || deleted.length > 0) {\n\t\t\toptions.appendEntry?.(CODEMODE_STORE_ENTRY_TYPE, { set, delete: deleted });\n\t\t}\n\t\t// pi extension: a returned value is appended like text().\n\t\tif (result.value !== undefined) items.push({ type: \"text\", text: valueText(result.value) });\n\t} else {\n\t\titems.push({ type: \"text\", text: `Script error:\\n${formatError(result, calls)}` });\n\t}\n\n\tconst truncated = await truncateOutput(items, sourceOptions.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS);\n\tconst wallTime = ((performance.now() - startedAt) / 1000).toFixed(1);\n\tconst header = `${result.ok ? \"Script completed\" : \"Script failed\"}\\nWall time ${wallTime} seconds\\nOutput:\\n`;\n\tconst details = snapshot();\n\tif (truncated.fullOutputPath) details.fullOutputPath = truncated.fullOutputPath;\n\treturn {\n\t\tcontent: [{ type: \"text\", text: header }, ...truncated.items],\n\t\tdetails,\n\t\t...(modelUsage ? { usage: modelUsage } : {}),\n\t\t...(result.ok ? {} : { isError: true }),\n\t};\n}\n\n/**\n * Whether `query` names the namespace: its name, its script identifier (`mcp__dev-radius` is\n * `mcp__dev_radius`), or the part after its last `__` in either form (`dev-radius`, `dev_radius`).\n */\nfunction isNamespaceName(namespace: string, query: string): boolean {\n\tconst id = toCodemodeIdentifier(namespace);\n\tconst queryId = toCodemodeIdentifier(query);\n\tconst suffix = (name: string) => (name.includes(\"__\") ? name.slice(name.lastIndexOf(\"__\") + 2) : undefined);\n\treturn namespace === query || id === queryId || suffix(namespace) === query || suffix(id) === queryId;\n}\n\n/**\n * `searchTools()`, `describeTool()`, and `describeNamespace()`: ranked search and lookup over the\n * script's nested tools and their namespaces.\n */\nfunction createDiscoveryGlobals(\n\ttools: readonly AgentTool<any>[],\n\tsamples: ReadonlyMap<string, string>,\n\toptions: CodemodeToolOptions,\n): CodemodeTool[] {\n\tconst ranker = new Bm25Ranker();\n\tconst entry = (name: string) => ({ name: toCodemodeIdentifier(name), description: samples.get(name) ?? \"\" });\n\treturn [\n\t\t{\n\t\t\tname: \"searchTools\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [query, searchOptions] = args as [unknown, { limit?: unknown; namespace?: unknown } | undefined];\n\t\t\t\tif (typeof query !== \"string\") throw new Error(\"searchTools() expects a query string\");\n\t\t\t\tconst limit = searchOptions?.limit ?? DEFAULT_TOOL_SEARCH_LIMIT;\n\t\t\t\tif (typeof limit !== \"number\" || !Number.isInteger(limit) || limit <= 0) {\n\t\t\t\t\tthrow new Error(\"searchTools() limit must be a positive integer\");\n\t\t\t\t}\n\t\t\t\tconst namespace = searchOptions?.namespace;\n\t\t\t\tif (namespace !== undefined && namespace !== null && typeof namespace !== \"string\") {\n\t\t\t\t\tthrow new Error(\"searchTools() namespace must be a string\");\n\t\t\t\t}\n\t\t\t\tconst documents = tools.flatMap((tool) => {\n\t\t\t\t\tconst toolNamespace = options.getToolNamespace?.(tool.name);\n\t\t\t\t\tif (namespace && (!toolNamespace || !isNamespaceName(toolNamespace.name, namespace))) return [];\n\t\t\t\t\treturn [createToolSearchDocument(tool, toolNamespace)];\n\t\t\t\t});\n\t\t\t\treturn ranker.rank(query, documents, limit).map((match) => entry(match.name));\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"describeTool\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [name] = args as unknown[];\n\t\t\t\tif (typeof name !== \"string\") throw new Error(\"describeTool() expects a tool name\");\n\t\t\t\tconst tool = tools.find(\n\t\t\t\t\t(candidate) => candidate.name === name || toCodemodeIdentifier(candidate.name) === name,\n\t\t\t\t);\n\t\t\t\treturn tool ? samples.get(tool.name) : undefined;\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"describeNamespace\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [name] = args as unknown[];\n\t\t\t\tif (typeof name !== \"string\") throw new Error(\"describeNamespace() expects a namespace name\");\n\t\t\t\tlet namespace: ToolNamespace | undefined;\n\t\t\t\tconst names: string[] = [];\n\t\t\t\tfor (const tool of tools) {\n\t\t\t\t\tconst toolNamespace = options.getToolNamespace?.(tool.name);\n\t\t\t\t\tif (!toolNamespace || !isNamespaceName(toolNamespace.name, name)) continue;\n\t\t\t\t\tnamespace ??= toolNamespace;\n\t\t\t\t\tnames.push(toCodemodeIdentifier(tool.name));\n\t\t\t\t}\n\t\t\t\tif (!namespace) return undefined;\n\t\t\t\treturn {\n\t\t\t\t\tname: namespace.name,\n\t\t\t\t\t...(namespace.description ? { description: namespace.description } : {}),\n\t\t\t\t\t...(namespace.instructions ? { instructions: namespace.instructions } : {}),\n\t\t\t\t\ttools: names,\n\t\t\t\t};\n\t\t\t},\n\t\t},\n\t];\n}\n\n/**\n * `models.*` for scripts: the model registry methods declared in {@link MODEL_GLOBAL_DECLARATIONS}.\n * Classifier calls appear as nested call rows so the renderer shows them, and their usage goes to\n * `addUsage`.\n */\nfunction createModelGlobals(\n\tmodels: CodemodeModelRuntime,\n\ttoolCallId: string,\n\tcalls: CodemodeNestedCall[],\n\tpublish: () => void,\n\taddUsage: (usage: Usage) => void,\n): CodemodeTool[] {\n\tconst limit = createLimiter(MAX_CONCURRENT_MODEL_CALLS);\n\tlet classifyCount = 0;\n\tconst implementations: Record<string, CodemodeTool[\"execute\"]> = {\n\t\t\"models.getModelsOfType\": (args) => {\n\t\t\tconst [type, provider] = args as unknown[];\n\t\t\treturn models.getModelsOfType(toModelType(type), toProvider(provider)).map(toModelInfo);\n\t\t},\n\t\t\"models.getAvailableOfType\": async (args, { signal }) => {\n\t\t\tconst [type, provider] = args as unknown[];\n\t\t\tconst available = await models.getAvailableOfType(toModelType(type), toProvider(provider), { signal });\n\t\t\treturn available.map(toModelInfo);\n\t\t},\n\t\t\"models.getModelOfType\": (args) => {\n\t\t\tconst [type, provider, id] = args as unknown[];\n\t\t\tif (typeof provider !== \"string\" || typeof id !== \"string\") {\n\t\t\t\tthrow new Error(\"models.getModelOfType() expects a type, a provider, and an id\");\n\t\t\t}\n\t\t\tconst model = models.getModelOfType(toModelType(type), provider, id);\n\t\t\treturn model === undefined ? undefined : toModelInfo(model);\n\t\t},\n\t\t\"models.classify\": async (args, { signal }) => {\n\t\t\tconst [model, context] = args as unknown[];\n\t\t\tconst ref = model as { provider?: unknown; id?: unknown } | null;\n\t\t\tif (\n\t\t\t\ttypeof ref !== \"object\" ||\n\t\t\t\tref === null ||\n\t\t\t\ttypeof ref.provider !== \"string\" ||\n\t\t\t\ttypeof ref.id !== \"string\"\n\t\t\t) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"models.classify() expects a model from models.getModelOfType() or models.getAvailableOfType()\",\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Only provider and id count. A script-supplied baseUrl or headers must never receive the credentials.\n\t\t\tconst resolved = models.getModelOfType(\"classifier\", ref.provider, ref.id);\n\t\t\tif (!resolved) throw new Error(`Unknown classifier model \"${ref.provider}/${ref.id}\"`);\n\n\t\t\tconst record: CodemodeNestedCall = {\n\t\t\t\tid: `${toolCallId}/models.classify/${++classifyCount}`,\n\t\t\t\tname: \"models.classify\",\n\t\t\t\targs: `${resolved.provider}/${resolved.id}`,\n\t\t\t\tstatus: \"running\",\n\t\t\t};\n\t\t\tcalls.push(record);\n\t\t\tpublish();\n\t\t\tconst startedAt = performance.now();\n\t\t\tconst result = await limit(() => models.classify(resolved, context as ClassifierContext, { signal }));\n\t\t\trecord.durationMs = performance.now() - startedAt;\n\t\t\trecord.status = result.stopReason === \"stop\" ? \"ok\" : result.stopReason === \"aborted\" ? \"cancelled\" : \"error\";\n\t\t\tif (result.errorMessage) record.error = truncateText(result.errorMessage, ERROR_PREVIEW_CHARS);\n\t\t\tif (result.usage) {\n\t\t\t\trecord.cost = result.usage.cost.total;\n\t\t\t\taddUsage(result.usage);\n\t\t\t}\n\t\t\tpublish();\n\t\t\treturn result;\n\t\t},\n\t};\n\treturn MODEL_GLOBAL_DECLARATIONS.map((declaration) => ({\n\t\tname: declaration.name,\n\t\tspread: true,\n\t\texecute: implementations[declaration.name],\n\t}));\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"renderer.d.ts","sourceRoot":"","sources":["../../../src/extensions/codemode/renderer.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;
|
|
1
|
+
{"version":3,"file":"renderer.d.ts","sourceRoot":"","sources":["../../../src/extensions/codemode/renderer.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAKrE,OAAO,KAAK,EAAsB,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAiDzE,eAAO,MAAM,iBAAiB,EAAE,IAAI,CACnC,cAAc,CAAC,GAAG,EAAE,mBAAmB,GAAG,SAAS,CAAC,EACpD,YAAY,GAAG,cAAc,CAmF7B,CAAC"}
|
|
@@ -6,9 +6,10 @@
|
|
|
6
6
|
* header. Nested calls are not
|
|
7
7
|
* separate tool rows because they never reach the model as tool calls.
|
|
8
8
|
*/
|
|
9
|
-
import { Text } from "@earendil-works/pi-tui";
|
|
9
|
+
import { Container, Spacer, Text } from "@earendil-works/pi-tui";
|
|
10
10
|
import { getTextOutput, replaceTabs, str } from "../../core/tools/render-utils.js";
|
|
11
11
|
import { keyHint } from "../../modes/interactive/components/keybinding-hints.js";
|
|
12
|
+
import { VisualLinePreview } from "../../modes/interactive/components/visual-truncate.js";
|
|
12
13
|
import { highlightCode } from "../../modes/interactive/theme/theme.js";
|
|
13
14
|
const CODE_PREVIEW_LINES = 10;
|
|
14
15
|
const CALL_PREVIEW_COUNT = 8;
|
|
@@ -59,23 +60,30 @@ export const codemodeRenderers = {
|
|
|
59
60
|
renderCall(args, theme, context) {
|
|
60
61
|
// The code includes the `// @options:` line, so options show as part of the script.
|
|
61
62
|
const code = str(args?.code);
|
|
62
|
-
|
|
63
|
+
const title = theme.fg("toolTitle", theme.bold("codemode"));
|
|
64
|
+
const component = context.lastComponent ?? new Container();
|
|
65
|
+
component.clear();
|
|
63
66
|
if (code === null) {
|
|
64
|
-
|
|
67
|
+
component.addChild(new Text(`${title} ${theme.fg("error", "[invalid arg]")}`, 0, 0));
|
|
68
|
+
return component;
|
|
65
69
|
}
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
70
|
+
component.addChild(new Text(title, 0, 0));
|
|
71
|
+
if (code) {
|
|
72
|
+
const highlighted = highlightCode(replaceTabs(code.replace(/\r/g, "").trimEnd()), "javascript").join("\n");
|
|
73
|
+
component.addChild(context.expanded
|
|
74
|
+
? new Text(highlighted, 0, 0)
|
|
75
|
+
: new VisualLinePreview({
|
|
76
|
+
text: highlighted,
|
|
77
|
+
maxVisualLines: CODE_PREVIEW_LINES,
|
|
78
|
+
keep: "start",
|
|
79
|
+
formatHint: (hidden) => expandHint(theme, hidden, "lines"),
|
|
80
|
+
}));
|
|
72
81
|
}
|
|
73
|
-
const component = context.lastComponent ?? new Text("", 0, 0);
|
|
74
|
-
component.setText(text);
|
|
75
82
|
return component;
|
|
76
83
|
},
|
|
77
84
|
renderResult(result, options, theme, context) {
|
|
78
|
-
const
|
|
85
|
+
const component = context.lastComponent ?? new Container();
|
|
86
|
+
component.clear();
|
|
79
87
|
const calls = result.details?.calls ?? [];
|
|
80
88
|
if (calls.length > 0) {
|
|
81
89
|
const shown = options.expanded ? calls : calls.slice(-CALL_PREVIEW_COUNT);
|
|
@@ -89,7 +97,8 @@ export const codemodeRenderers = {
|
|
|
89
97
|
const total = priced.reduce((sum, call) => sum + (call.cost ?? 0), 0);
|
|
90
98
|
lines.push(theme.fg("muted", `Model calls: ${formatCost(total)}`));
|
|
91
99
|
}
|
|
92
|
-
|
|
100
|
+
component.addChild(new Spacer(1));
|
|
101
|
+
component.addChild(new Text(lines.join("\n"), 0, 0));
|
|
93
102
|
}
|
|
94
103
|
// Drop the "Script completed\nWall time ...\nOutput:\n" header. Rejected input (invalid options)
|
|
95
104
|
// has no header.
|
|
@@ -100,19 +109,28 @@ export const codemodeRenderers = {
|
|
|
100
109
|
: getTextOutput({ ...result, content: hasHeader ? rest : result.content }, context.showImages).trim();
|
|
101
110
|
if (output) {
|
|
102
111
|
const color = context.isError ? "error" : "toolOutput";
|
|
103
|
-
const
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
112
|
+
const styled = replaceTabs(output)
|
|
113
|
+
.split("\n")
|
|
114
|
+
.map((line) => theme.fg(color, line))
|
|
115
|
+
.join("\n");
|
|
116
|
+
component.addChild(new Spacer(1));
|
|
117
|
+
if (options.expanded) {
|
|
118
|
+
component.addChild(new Text(styled, 0, 0));
|
|
119
|
+
}
|
|
120
|
+
else {
|
|
121
|
+
// Limit wrapped lines, not logical ones: script output is often one long JSON line.
|
|
122
|
+
component.addChild(new VisualLinePreview({
|
|
123
|
+
text: styled,
|
|
124
|
+
maxVisualLines: OUTPUT_PREVIEW_LINES,
|
|
125
|
+
keep: "start",
|
|
126
|
+
formatHint: (hidden) => expandHint(theme, hidden, "lines"),
|
|
127
|
+
}));
|
|
128
|
+
// The collapsed preview hides the truncation notice at the end, so name the file here.
|
|
129
|
+
const fullOutputPath = result.details?.fullOutputPath;
|
|
130
|
+
if (fullOutputPath)
|
|
131
|
+
component.addChild(new Text(theme.fg("muted", `Full output: ${fullOutputPath}`), 0, 0));
|
|
132
|
+
}
|
|
113
133
|
}
|
|
114
|
-
const component = context.lastComponent ?? new Text("", 0, 0);
|
|
115
|
-
component.setText(sections.length > 0 ? `\n${sections.join("\n\n")}` : "");
|
|
116
134
|
return component;
|
|
117
135
|
},
|
|
118
136
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"renderer.js","sourceRoot":"","sources":["../../../src/extensions/codemode/renderer.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAE9C,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,GAAG,EAAE,MAAM,kCAAkC,CAAC;AACnF,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AACjF,OAAO,EAAE,aAAa,EAAc,MAAM,wCAAwC,CAAC;AAGnF,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAC9B,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAC7B,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAC/B,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAChC,MAAM,aAAa,GAAG,kEAAkE,CAAC;AAEzF,SAAS,UAAU,CAAC,KAAY,EAAE,MAAc,EAAE,IAAY;IAC7D,OAAO,GAAG,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,QAAQ,MAAM,SAAS,IAAI,GAAG,CAAC,IAAI,OAAO,CAAC,k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,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACrB,CAAC;QAED,MAAM,SAAS,GAAI,OAAO,CAAC,aAAkC,IAAI,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QACpF,SAAS,CAAC,OAAO,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;QAC3E,OAAO,SAAS,CAAC;IAClB,CAAC;CACD,CAAC","sourcesContent":["/**\n * Presentation for the codemode tool.\n *\n * The call shows the script; the result lists the nested tool calls with their status as they\n * run and the cost of its model calls, followed by the script output without the \"Script completed\"\n * header. Nested calls are not\n * separate tool rows because they never reach the model as tool calls.\n */\n\nimport { Text } from \"@earendil-works/pi-tui\";\nimport type { ToolDefinition } from \"../../core/extensions/types.ts\";\nimport { getTextOutput, replaceTabs, str } from \"../../core/tools/render-utils.ts\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { highlightCode, type Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { CodemodeNestedCall, CodemodeToolDetails } from \"./tool.ts\";\n\nconst CODE_PREVIEW_LINES = 10;\nconst CALL_PREVIEW_COUNT = 8;\nconst OUTPUT_PREVIEW_LINES = 5;\nconst COLLAPSED_ARGS_CHARS = 80;\nconst SCRIPT_HEADER = /^Script (completed|failed)\\nWall time [\\d.]+ seconds\\nOutput:\\n$/;\n\nfunction expandHint(theme: Theme, hidden: number, noun: string): string {\n\treturn `${theme.fg(\"muted\", `... (${hidden} more ${noun},`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n}\n\nfunction formatDuration(ms: number | undefined): string {\n\tif (ms === undefined) return \"\";\n\treturn ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(1)}s`;\n}\n\n/** Cents for larger amounts, two significant digits for the fractions of a cent classifier calls cost. */\nfunction formatCost(cost: number): string {\n\treturn `$${cost >= 0.01 ? cost.toFixed(2) : cost.toPrecision(2)}`;\n}\n\nfunction statusIcon(call: CodemodeNestedCall, theme: Theme): string {\n\tswitch (call.status) {\n\t\tcase \"running\":\n\t\t\treturn theme.fg(\"warning\", \"…\");\n\t\tcase \"ok\":\n\t\t\treturn theme.fg(\"success\", \"✓\");\n\t\tcase \"error\":\n\t\t\treturn theme.fg(\"error\", \"✗\");\n\t\tcase \"cancelled\":\n\t\t\treturn theme.fg(\"muted\", \"⊘\");\n\t}\n}\n\nfunction formatCall(call: CodemodeNestedCall, theme: Theme, expanded: boolean): string {\n\tconst args =\n\t\t!expanded && call.args.length > COLLAPSED_ARGS_CHARS\n\t\t\t? `${call.args.slice(0, COLLAPSED_ARGS_CHARS - 3)}...`\n\t\t\t: call.args;\n\tconst duration = formatDuration(call.durationMs);\n\tlet line = `${statusIcon(call, theme)} ${theme.fg(\"toolTitle\", call.name)}`;\n\tif (args) line += ` ${theme.fg(\"muted\", args)}`;\n\tif (duration) line += ` ${theme.fg(\"dim\", duration)}`;\n\tif (call.cost) line += ` ${theme.fg(\"dim\", formatCost(call.cost))}`;\n\tif (expanded && call.error) line += `\\n ${theme.fg(\"error\", call.error.split(\"\\n\").join(\"\\n \"))}`;\n\treturn line;\n}\n\nexport const codemodeRenderers: Pick<\n\tToolDefinition<any, CodemodeToolDetails | undefined>,\n\t\"renderCall\" | \"renderResult\"\n> = {\n\trenderCall(args, theme, context) {\n\t\t// The code includes the `// @options:` line, so options show as part of the script.\n\t\tconst code = str((args as { code?: unknown } | undefined)?.code);\n\t\tlet text = theme.fg(\"toolTitle\", theme.bold(\"codemode\"));\n\t\tif (code === null) {\n\t\t\ttext += ` ${theme.fg(\"error\", \"[invalid arg]\")}`;\n\t\t} else if (code) {\n\t\t\tconst lines = highlightCode(replaceTabs(code.replace(/\\r/g, \"\").trimEnd()), \"javascript\");\n\t\t\tconst shown = context.expanded ? lines : lines.slice(0, CODE_PREVIEW_LINES);\n\t\t\ttext += `\\n${shown.join(\"\\n\")}`;\n\t\t\tif (shown.length < lines.length) text += `\\n${expandHint(theme, lines.length - shown.length, \"lines\")}`;\n\t\t}\n\t\tconst component = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\tcomponent.setText(text);\n\t\treturn component;\n\t},\n\trenderResult(result, options, theme, context) {\n\t\tconst sections: string[] = [];\n\t\tconst calls = result.details?.calls ?? [];\n\t\tif (calls.length > 0) {\n\t\t\tconst shown = options.expanded ? calls : calls.slice(-CALL_PREVIEW_COUNT);\n\t\t\tconst lines = shown.map((call) => formatCall(call, theme, options.expanded));\n\t\t\tif (shown.length < calls.length) {\n\t\t\t\tlines.unshift(\n\t\t\t\t\t`${theme.fg(\"muted\", `... (${calls.length - shown.length} earlier calls,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Collapsed rows hide earlier calls, so the total covers every call.\n\t\t\tconst priced = calls.filter((call) => call.cost);\n\t\t\tif (priced.length > 1) {\n\t\t\t\tconst total = priced.reduce((sum, call) => sum + (call.cost ?? 0), 0);\n\t\t\t\tlines.push(theme.fg(\"muted\", `Model calls: ${formatCost(total)}`));\n\t\t\t}\n\t\t\tsections.push(lines.join(\"\\n\"));\n\t\t}\n\n\t\t// Drop the \"Script completed\\nWall time ...\\nOutput:\\n\" header. Rejected input (invalid options)\n\t\t// has no header.\n\t\tconst [first, ...rest] = result.content;\n\t\tconst hasHeader = first?.type === \"text\" && SCRIPT_HEADER.test(first.text);\n\t\tconst output = options.isPartial\n\t\t\t? \"\"\n\t\t\t: getTextOutput({ ...result, content: hasHeader ? rest : result.content }, context.showImages).trim();\n\t\tif (output) {\n\t\t\tconst color = context.isError ? \"error\" : \"toolOutput\";\n\t\t\tconst lines = replaceTabs(output).split(\"\\n\");\n\t\t\tconst shown = options.expanded ? lines : lines.slice(0, OUTPUT_PREVIEW_LINES);\n\t\t\tlet text = shown.map((line) => theme.fg(color, line)).join(\"\\n\");\n\t\t\tif (shown.length < lines.length) text += `\\n${expandHint(theme, lines.length - shown.length, \"lines\")}`;\n\t\t\t// The collapsed preview hides the truncation notice at the end, so name the file here.\n\t\t\tconst fullOutputPath = result.details?.fullOutputPath;\n\t\t\tif (fullOutputPath && !options.expanded) text += `\\n${theme.fg(\"muted\", `Full output: ${fullOutputPath}`)}`;\n\t\t\tsections.push(text);\n\t\t}\n\n\t\tconst component = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\tcomponent.setText(sections.length > 0 ? `\\n${sections.join(\"\\n\\n\")}` : \"\");\n\t\treturn component;\n\t},\n};\n"]}
|
|
1
|
+
{"version":3,"file":"renderer.js","sourceRoot":"","sources":["../../../src/extensions/codemode/renderer.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAEjE,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,GAAG,EAAE,MAAM,kCAAkC,CAAC;AACnF,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AACjF,OAAO,EAAE,iBAAiB,EAAE,MAAM,uDAAuD,CAAC;AAC1F,OAAO,EAAE,aAAa,EAAc,MAAM,wCAAwC,CAAC;AAGnF,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAC9B,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAC7B,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAC/B,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAChC,MAAM,aAAa,GAAG,kEAAkE,CAAC;AAEzF,SAAS,UAAU,CAAC,KAAY,EAAE,MAAc,EAAE,IAAY;IAC7D,OAAO,GAAG,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,QAAQ,MAAM,SAAS,IAAI,GAAG,CAAC,IAAI,OAAO,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CAAC;gBACP,oFAAoF;gBACpF,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,CAAC,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC;iBAC1D,CAAC,CACF,CAAC;gBACF,uFAAuF;gBACvF,MAAM,cAAc,GAAG,MAAM,CAAC,OAAO,EAAE,cAAc,CAAC;gBACtD,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;QACF,CAAC;QACD,OAAO,SAAS,CAAC;IAClB,CAAC;CACD,CAAC","sourcesContent":["/**\n * Presentation for the codemode tool.\n *\n * The call shows the script; the result lists the nested tool calls with their status as they\n * run and the cost of its model calls, followed by the script output without the \"Script completed\"\n * header. Nested calls are not\n * separate tool rows because they never reach the model as tool calls.\n */\n\nimport { Container, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport type { ToolDefinition } from \"../../core/extensions/types.ts\";\nimport { getTextOutput, replaceTabs, str } from \"../../core/tools/render-utils.ts\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { VisualLinePreview } from \"../../modes/interactive/components/visual-truncate.ts\";\nimport { highlightCode, type Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { CodemodeNestedCall, CodemodeToolDetails } from \"./tool.ts\";\n\nconst CODE_PREVIEW_LINES = 10;\nconst CALL_PREVIEW_COUNT = 8;\nconst OUTPUT_PREVIEW_LINES = 5;\nconst COLLAPSED_ARGS_CHARS = 80;\nconst SCRIPT_HEADER = /^Script (completed|failed)\\nWall time [\\d.]+ seconds\\nOutput:\\n$/;\n\nfunction expandHint(theme: Theme, hidden: number, noun: string): string {\n\treturn `${theme.fg(\"muted\", `... (${hidden} more ${noun},`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n}\n\nfunction formatDuration(ms: number | undefined): string {\n\tif (ms === undefined) return \"\";\n\treturn ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(1)}s`;\n}\n\n/** Cents for larger amounts, two significant digits for the fractions of a cent classifier calls cost. */\nfunction formatCost(cost: number): string {\n\treturn `$${cost >= 0.01 ? cost.toFixed(2) : cost.toPrecision(2)}`;\n}\n\nfunction statusIcon(call: CodemodeNestedCall, theme: Theme): string {\n\tswitch (call.status) {\n\t\tcase \"running\":\n\t\t\treturn theme.fg(\"warning\", \"…\");\n\t\tcase \"ok\":\n\t\t\treturn theme.fg(\"success\", \"✓\");\n\t\tcase \"error\":\n\t\t\treturn theme.fg(\"error\", \"✗\");\n\t\tcase \"cancelled\":\n\t\t\treturn theme.fg(\"muted\", \"⊘\");\n\t}\n}\n\nfunction formatCall(call: CodemodeNestedCall, theme: Theme, expanded: boolean): string {\n\tconst args =\n\t\t!expanded && call.args.length > COLLAPSED_ARGS_CHARS\n\t\t\t? `${call.args.slice(0, COLLAPSED_ARGS_CHARS - 3)}...`\n\t\t\t: call.args;\n\tconst duration = formatDuration(call.durationMs);\n\tlet line = `${statusIcon(call, theme)} ${theme.fg(\"toolTitle\", call.name)}`;\n\tif (args) line += ` ${theme.fg(\"muted\", args)}`;\n\tif (duration) line += ` ${theme.fg(\"dim\", duration)}`;\n\tif (call.cost) line += ` ${theme.fg(\"dim\", formatCost(call.cost))}`;\n\tif (expanded && call.error) line += `\\n ${theme.fg(\"error\", call.error.split(\"\\n\").join(\"\\n \"))}`;\n\treturn line;\n}\n\nexport const codemodeRenderers: Pick<\n\tToolDefinition<any, CodemodeToolDetails | undefined>,\n\t\"renderCall\" | \"renderResult\"\n> = {\n\trenderCall(args, theme, context) {\n\t\t// The code includes the `// @options:` line, so options show as part of the script.\n\t\tconst code = str((args as { code?: unknown } | undefined)?.code);\n\t\tconst title = theme.fg(\"toolTitle\", theme.bold(\"codemode\"));\n\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\tcomponent.clear();\n\t\tif (code === null) {\n\t\t\tcomponent.addChild(new Text(`${title} ${theme.fg(\"error\", \"[invalid arg]\")}`, 0, 0));\n\t\t\treturn component;\n\t\t}\n\t\tcomponent.addChild(new Text(title, 0, 0));\n\t\tif (code) {\n\t\t\tconst highlighted = highlightCode(replaceTabs(code.replace(/\\r/g, \"\").trimEnd()), \"javascript\").join(\"\\n\");\n\t\t\tcomponent.addChild(\n\t\t\t\tcontext.expanded\n\t\t\t\t\t? new Text(highlighted, 0, 0)\n\t\t\t\t\t: new VisualLinePreview({\n\t\t\t\t\t\t\ttext: highlighted,\n\t\t\t\t\t\t\tmaxVisualLines: CODE_PREVIEW_LINES,\n\t\t\t\t\t\t\tkeep: \"start\",\n\t\t\t\t\t\t\tformatHint: (hidden) => expandHint(theme, hidden, \"lines\"),\n\t\t\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\treturn component;\n\t},\n\trenderResult(result, options, theme, context) {\n\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\tcomponent.clear();\n\t\tconst calls = result.details?.calls ?? [];\n\t\tif (calls.length > 0) {\n\t\t\tconst shown = options.expanded ? calls : calls.slice(-CALL_PREVIEW_COUNT);\n\t\t\tconst lines = shown.map((call) => formatCall(call, theme, options.expanded));\n\t\t\tif (shown.length < calls.length) {\n\t\t\t\tlines.unshift(\n\t\t\t\t\t`${theme.fg(\"muted\", `... (${calls.length - shown.length} earlier calls,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Collapsed rows hide earlier calls, so the total covers every call.\n\t\t\tconst priced = calls.filter((call) => call.cost);\n\t\t\tif (priced.length > 1) {\n\t\t\t\tconst total = priced.reduce((sum, call) => sum + (call.cost ?? 0), 0);\n\t\t\t\tlines.push(theme.fg(\"muted\", `Model calls: ${formatCost(total)}`));\n\t\t\t}\n\t\t\tcomponent.addChild(new Spacer(1));\n\t\t\tcomponent.addChild(new Text(lines.join(\"\\n\"), 0, 0));\n\t\t}\n\n\t\t// Drop the \"Script completed\\nWall time ...\\nOutput:\\n\" header. Rejected input (invalid options)\n\t\t// has no header.\n\t\tconst [first, ...rest] = result.content;\n\t\tconst hasHeader = first?.type === \"text\" && SCRIPT_HEADER.test(first.text);\n\t\tconst output = options.isPartial\n\t\t\t? \"\"\n\t\t\t: getTextOutput({ ...result, content: hasHeader ? rest : result.content }, context.showImages).trim();\n\t\tif (output) {\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: script output is 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) => expandHint(theme, hidden, \"lines\"),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\t// The collapsed preview hides the truncation notice at the end, so name the file here.\n\t\t\t\tconst fullOutputPath = result.details?.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}\n\t\treturn component;\n\t},\n};\n"]}
|
|
@@ -107,10 +107,11 @@ export interface CodemodeDescriptionOptions {
|
|
|
107
107
|
inlineBudget?: number;
|
|
108
108
|
}
|
|
109
109
|
/**
|
|
110
|
-
* Model-facing description: the helper list, guidance for
|
|
111
|
-
* MCP tools
|
|
112
|
-
*
|
|
113
|
-
*
|
|
110
|
+
* Model-facing description: the helper list, guidance for finding tools that are not listed, the
|
|
111
|
+
* shared MCP types when listed tools need them, the `models` API, and one section per listed tool,
|
|
112
|
+
* grouped by namespace. Deferred tools are never listed and do not affect the description at all, so
|
|
113
|
+
* it stays the same while MCP servers connect or change their tools. Tool sections are limited to
|
|
114
|
+
* `inlineBudget`.
|
|
114
115
|
*/
|
|
115
116
|
export declare function createCodemodeDescription(tools: readonly AgentTool<any>[], options?: CodemodeDescriptionOptions): string;
|
|
116
117
|
export declare function createCodemodeToolDefinition(options?: CodemodeToolOptions): ToolDefinition<typeof codemodeSchema, CodemodeToolDetails | undefined>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool.d.ts","sourceRoot":"","sources":["../../../src/extensions/codemode/tool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAC/D,OAAO,KAAK,EAAsB,YAAY,EAAE,MAAM,6BAA6B,CAAC;AASpF,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,KAAK,EACX,cAAc,EACd,QAAQ,EAGR,aAAa,EACb,MAAM,gCAAgC,CAAC;AACxC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAKnE,eAAO,MAAM,kBAAkB,aAAa,CAAC;AAE7C,+FAA+F;AAC/F,eAAO,MAAM,yBAAyB,mBAAmB,CAAC;AAE1D,MAAM,WAAW,sBAAsB;IACtC,GAAG,EAAE,MAAM,CAAC,MAAM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8BAA8B,OAAO,CAAC;AAInD,iGAAiG;AACjG,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,SAAS,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,YAAY,EAAE,SAAS,CAAC,CAOzF;AAED,iFAAiF;AACjF,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,SAAS,SAAS,CAAC,GAAG,CAAC,EAAE,GAAG,SAAS,CAAC,GAAG,CAAC,EAAE,CAE3F;AAED,MAAM,WAAW,0BAA0B;IAC1C,gFAAgF;IAChF,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,iGAAiG;IACjG,UAAU,CAAC,EAAE,WAAW,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IAChD,6FAA6F;IAC7F,QAAQ,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IAC/B;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB;AA6CD;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CACxC,KAAK,EAAE,SAAS,SAAS,CAAC,GAAG,CAAC,EAAE,EAChC,OAAO,GAAE,0BAA+B,GACtC,MAAM,CAsDR;AAgDD,wBAAgB,4BAA4B,CAC3C,OAAO,GAAE,mBAAwB,GAC/B,cAAc,CAAC,OAAO,cAAc,EAAE,mBAAmB,GAAG,SAAS,CAAC,CAmBxE;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CACjC,KAAK,GAAE,SAAS,SAAS,CAAC,GAAG,CAAC,EAAO,EACrC,OAAO,GAAE,mBAAwB,GAC/B,SAAS,CAAC,OAAO,cAAc,CAAC,CASlC"}
|
|
@@ -72,6 +72,7 @@ const DESCRIPTION_INTRO = `Run JavaScript code to orchestrate/compose tool calls
|
|
|
72
72
|
- \`ALL_TOOLS\`: metadata for the enabled nested tools as \`{ name, description }\` entries.
|
|
73
73
|
- \`searchTools(query: string, options?: { limit?: number; namespace?: string })\`: resolves to the nested tools that best match the query (BM25, default limit 8), as \`{ name, description }\` entries like \`ALL_TOOLS\`.
|
|
74
74
|
- \`describeTool(name: string)\`: resolves to the description and declaration of a nested tool, or \`undefined\`.
|
|
75
|
+
- \`describeNamespace(name: string)\`: resolves to \`{ name, description?, instructions?, tools }\` for a namespace of nested tools, such as an MCP server: its usage instructions and the names of its tools, or \`undefined\`.
|
|
75
76
|
- \`console.log(...)\` and the other \`console\` methods append a text item like \`text()\`.
|
|
76
77
|
- \`return value\` at the top level appends the value like \`text()\`.`;
|
|
77
78
|
const MODEL_TYPES = `type ModelType = "chat" | "image" | "classifier";
|
|
@@ -132,8 +133,8 @@ export const MODEL_GLOBAL_DECLARATIONS = [
|
|
|
132
133
|
signature: "(model: ModelInfo, context: ClassifierContext): Promise<ClassifierResult>",
|
|
133
134
|
},
|
|
134
135
|
];
|
|
135
|
-
const DEFERRED_TOOLS_GUIDANCE = `Some
|
|
136
|
-
To find one, call \`await searchTools(query)
|
|
136
|
+
const DEFERRED_TOOLS_GUIDANCE = `Some nested tools may be omitted from this description, such as deferred tools and MCP tools. They are still available on the global \`tools\` object and listed in \`ALL_TOOLS\`.
|
|
137
|
+
To find one, call \`await searchTools(query)\` (pass \`{ namespace }\` to search one namespace), or filter \`ALL_TOOLS\` by \`name\` and \`description\`. \`await describeNamespace(name)\` returns a namespace's usage instructions and the names of its tools.`;
|
|
137
138
|
/** Default for {@link CodemodeDescriptionOptions.inlineBudget}, in estimated tokens. */
|
|
138
139
|
export const DEFAULT_CODEMODE_INLINE_BUDGET = 3000;
|
|
139
140
|
/** Characters per token when estimating the cost of a tool section. */
|
|
@@ -164,10 +165,9 @@ function renderToolSection(declaration) {
|
|
|
164
165
|
* represented before any namespace is complete.
|
|
165
166
|
*/
|
|
166
167
|
function selectCatalog(groups, budget) {
|
|
167
|
-
const listable = groups.map((group) => group.entries.filter((entry) => !entry.deferred));
|
|
168
168
|
if (budget === undefined)
|
|
169
|
-
return new Set(
|
|
170
|
-
const queues =
|
|
169
|
+
return new Set(groups.flatMap((group) => group.entries.map((entry) => entry.name)));
|
|
170
|
+
const queues = groups.map((group) => [...group.entries].sort((a, b) => a.cost - b.cost));
|
|
171
171
|
const shown = new Set();
|
|
172
172
|
let remaining = budget;
|
|
173
173
|
let active = queues.filter((queue) => queue.length > 0);
|
|
@@ -185,13 +185,16 @@ function selectCatalog(groups, budget) {
|
|
|
185
185
|
return shown;
|
|
186
186
|
}
|
|
187
187
|
/**
|
|
188
|
-
* Model-facing description: the helper list, guidance for
|
|
189
|
-
* MCP tools
|
|
190
|
-
*
|
|
191
|
-
*
|
|
188
|
+
* Model-facing description: the helper list, guidance for finding tools that are not listed, the
|
|
189
|
+
* shared MCP types when listed tools need them, the `models` API, and one section per listed tool,
|
|
190
|
+
* grouped by namespace. Deferred tools are never listed and do not affect the description at all, so
|
|
191
|
+
* it stays the same while MCP servers connect or change their tools. Tool sections are limited to
|
|
192
|
+
* `inlineBudget`.
|
|
192
193
|
*/
|
|
193
194
|
export function createCodemodeDescription(tools, options = {}) {
|
|
194
|
-
const declarations = getCodemodeCallableTools(tools)
|
|
195
|
+
const declarations = getCodemodeCallableTools(tools)
|
|
196
|
+
.filter((tool) => !options.deferred?.has(tool.name))
|
|
197
|
+
.map(toCodemodeDeclaration);
|
|
195
198
|
const groups = new Map([["", { namespace: undefined, entries: [] }]]);
|
|
196
199
|
for (const declaration of declarations) {
|
|
197
200
|
const namespace = options.namespaces?.get(declaration.name);
|
|
@@ -199,20 +202,12 @@ export function createCodemodeDescription(tools, options = {}) {
|
|
|
199
202
|
const group = groups.get(key) ?? { namespace, entries: [] };
|
|
200
203
|
groups.set(key, group);
|
|
201
204
|
const section = renderToolSection(declaration);
|
|
202
|
-
group.entries.push({
|
|
203
|
-
name: declaration.name,
|
|
204
|
-
section,
|
|
205
|
-
cost: Math.ceil(section.length / CHARS_PER_TOKEN),
|
|
206
|
-
deferred: options.deferred?.has(declaration.name) === true,
|
|
207
|
-
});
|
|
205
|
+
group.entries.push({ name: declaration.name, section, cost: Math.ceil(section.length / CHARS_PER_TOKEN) });
|
|
208
206
|
}
|
|
209
207
|
const ordered = [...groups.values()].sort((a, b) => a.namespace === undefined ? -1 : b.namespace === undefined ? 1 : a.namespace.name.localeCompare(b.namespace.name));
|
|
210
208
|
const shown = selectCatalog(ordered, options.inlineBudget);
|
|
211
|
-
const
|
|
212
|
-
|
|
213
|
-
if (!complete)
|
|
214
|
-
sections.push(DEFERRED_TOOLS_GUIDANCE);
|
|
215
|
-
if (declarations.some((declaration) => mcpStructuredContentSchema(declaration.outputSchema) !== undefined)) {
|
|
209
|
+
const sections = [DESCRIPTION_INTRO, DEFERRED_TOOLS_GUIDANCE];
|
|
210
|
+
if (declarations.some((declaration) => shown.has(declaration.name) && mcpStructuredContentSchema(declaration.outputSchema) !== undefined)) {
|
|
216
211
|
sections.push(`Shared MCP Types:\n\`\`\`ts\n${MCP_TYPESCRIPT_PREAMBLE}\n\`\`\``);
|
|
217
212
|
}
|
|
218
213
|
if (options.models) {
|
|
@@ -224,22 +219,18 @@ export function createCodemodeDescription(tools, options = {}) {
|
|
|
224
219
|
}
|
|
225
220
|
if (declarations.length === 0)
|
|
226
221
|
return sections.join("\n\n");
|
|
227
|
-
const toolSections = [
|
|
228
|
-
complete
|
|
229
|
-
? `Nested tools: COMPLETE list (${declarations.length} tool${declarations.length === 1 ? "" : "s"}).`
|
|
230
|
-
: `Nested tools: PARTIAL - ${shown.size} of ${declarations.length} shown.`,
|
|
231
|
-
];
|
|
222
|
+
const toolSections = ["Nested tools:"];
|
|
232
223
|
for (const { namespace, entries } of ordered) {
|
|
233
224
|
const visible = entries.filter((entry) => shown.has(entry.name));
|
|
234
225
|
if (namespace) {
|
|
235
|
-
|
|
236
|
-
const
|
|
226
|
+
// Only tools that did not fit the budget are counted as not listed here.
|
|
227
|
+
const listing = visible.length === entries.length
|
|
237
228
|
? ""
|
|
238
229
|
: visible.length === 0
|
|
239
|
-
? "
|
|
240
|
-
:
|
|
230
|
+
? " (tools not listed)"
|
|
231
|
+
: " (some tools not listed)";
|
|
241
232
|
const description = namespace.description?.trim();
|
|
242
|
-
toolSections.push(`## ${namespace.name}
|
|
233
|
+
toolSections.push(`## ${namespace.name}${listing}${description ? `\n${description}` : ""}`);
|
|
243
234
|
}
|
|
244
235
|
for (const entry of visible)
|
|
245
236
|
toolSections.push(entry.section);
|