@astralyn/pi 1.0.2 → 1.0.4
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 +24 -0
- package/dist/bundle/chunks/{anthropic-messages-YET4T7BO.js → anthropic-messages-YIOJIMVL.js} +1 -1
- package/dist/bundle/chunks/azure-openai-responses-LDW4FGAQ.js +2 -0
- package/dist/bundle/chunks/{chunk-5RBGZ6YW.js → chunk-23OTKHCH.js} +53 -53
- package/dist/bundle/chunks/{chunk-MPDALHNJ.js → chunk-57XI7YJH.js} +1 -1
- package/dist/bundle/chunks/{chunk-MWM24AOB.js → chunk-73WG7F7N.js} +1 -1
- package/dist/bundle/chunks/{chunk-SVJ7OGEB.js → chunk-A6ALEEY5.js} +1 -1
- package/dist/bundle/chunks/chunk-D3ZCGC4T.js +2 -0
- package/dist/bundle/chunks/{chunk-IZ3S3GDX.js → chunk-IFELM7MW.js} +1 -1
- package/dist/bundle/chunks/chunk-RZ2V53SP.js +2 -0
- package/dist/bundle/chunks/{chunk-V66VGGOM.js → chunk-TCQ4HHQD.js} +1 -1
- package/dist/bundle/chunks/chunk-TXJO4AJ7.js +11 -0
- package/dist/bundle/chunks/{chunk-NY3CWK44.js → chunk-UCXU7KLO.js} +1 -1
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-QI46LUZ6.js → cloudflare-workers-ai-system-one-OWU5SM6J.js} +1 -1
- package/dist/bundle/chunks/codemode-worker.js +0 -1
- package/dist/bundle/chunks/{google-generative-ai-YTZCSHQN.js → google-generative-ai-S5A5IBU4.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-OTFZJJXQ.js → google-vertex-UBRQFDB4.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-ELH4V4TY.js → mistral-conversations-A2N5FSOV.js} +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-OLVTU4UA.js → openai-codex-responses-Q6JHCWLE.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-53M2KJ67.js → openai-completions-H4VMO7AU.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-4ABDEL4Z.js → openai-responses-G4PGNM2H.js} +1 -1
- package/dist/bundle/chunks/{typesafe-system-one-RREJAKWB.js → typesafe-system-one-KYKKNU3E.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-IJTAY26N.js +2 -0
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/config.d.ts +18 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +44 -6
- package/dist/config.js.map +1 -1
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +2 -7
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/keybindings.d.ts +4 -4
- package/dist/core/model-resolver.js +1 -1
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/tasks/runtime.d.ts +1 -0
- package/dist/core/tasks/runtime.d.ts.map +1 -1
- package/dist/core/tasks/runtime.js +4 -0
- package/dist/core/tasks/runtime.js.map +1 -1
- package/dist/core/tasks/types.d.ts +2 -0
- package/dist/core/tasks/types.d.ts.map +1 -1
- package/dist/core/tasks/types.js.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +6 -11
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/extensions/codemode/execute.d.ts.map +1 -1
- package/dist/extensions/codemode/execute.js +49 -8
- package/dist/extensions/codemode/execute.js.map +1 -1
- package/dist/extensions/codemode/tool.js +1 -1
- package/dist/extensions/codemode/tool.js.map +1 -1
- package/dist/extensions/mcp/tools.d.ts.map +1 -1
- package/dist/extensions/mcp/tools.js +4 -9
- package/dist/extensions/mcp/tools.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +7 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +42 -6
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/tasks/index.d.ts.map +1 -1
- package/dist/modes/interactive/tasks/index.js +10 -18
- package/dist/modes/interactive/tasks/index.js.map +1 -1
- package/dist/utils/output-files.d.ts +17 -0
- package/dist/utils/output-files.d.ts.map +1 -0
- package/dist/utils/output-files.js +30 -0
- package/dist/utils/output-files.js.map +1 -0
- package/docs/bundled/tasks.md +2 -2
- package/docs/bundled/tool-presentation.md +1 -1
- package/docs/codemode.md +3 -3
- package/docs/extensions.md +1 -0
- package/docs/keybindings.md +7 -7
- package/docs/providers.md +5 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +54 -54
- package/package.json +11 -11
- package/dist/bundle/chunks/azure-openai-responses-SBLL5YN3.js +0 -2
- package/dist/bundle/chunks/chunk-G4RY3GN7.js +0 -11
- package/dist/bundle/chunks/chunk-TRHTWM3C.js +0 -2
- package/dist/bundle/chunks/virtual-modules-EDIGEIG6.js +0 -2
|
@@ -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;A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,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,CA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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;
|
|
1
|
+
{"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../../../src/extensions/mcp/tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AACrE,OAAO,KAAK,EAAE,YAAY,EAAa,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAClF,OAAO,EACN,KAAK,cAAc,EACnB,KAAK,YAAY,EACjB,KAAK,iBAAiB,EACtB,KAAK,IAAI,IAAI,OAAO,EAEpB,MAAM,wBAAwB,CAAC;AAEhC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,KAAK,EAEX,cAAc,EACd,YAAY,EACZ,aAAa,EACb,aAAa,EACb,MAAM,gCAAgC,CAAC;AAMxC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE/C;;;GAGG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,WAAW,GAAG,YAAY,CAElE;AAID,2EAA2E;AAC3E,eAAO,MAAM,oBAAoB,QAAY,CAAC;AAG9C,6DAA6D;AAC7D,eAAO,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;IAC3G,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC5B;AAgDD,kFAAkF;AAClF,wBAAsB,cAAc,CACnC,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,SAAS,YAAY,EAAE,EAC/B,OAAO,GAAE,uBAA4B,GACnC,OAAO,CAAC,CAAC,WAAW,GAAG,YAAY,CAAC,EAAE,CAAC,CAEzC;AAED,qGAAqG;AACrG,wBAAsB,gBAAgB,CACrC,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
|
|
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
|
|
38
|
-
|
|
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,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AE,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,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;AAC1F,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAG9D;;;GAGG;AACH,MAAM,UAAU,cAAc,CAAC,QAAqB;IACnD,OAAO,QAAQ,KAAK,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,QAAQ,CAAC;AACxD,CAAC;AAED,2EAA2E;AAC3E,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAChC,2EAA2E;AAC3E,MAAM,CAAC,MAAM,oBAAoB,GAAG,EAAE,GAAG,IAAI,CAAC;AAC9C,yEAAyE;AACzE,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAC/B,6DAA6D;AAC7D,MAAM,CAAC,MAAM,sBAAsB,GAAG,mBAAmB,CAAC;AAe1D,MAAM,UAAU,cAAc,CAAC,IAAyB,EAAE,SAAiB;IAC1E,OAAO,eAAe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AI,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"]}
|
|
@@ -104,6 +104,7 @@ export declare class InteractiveMode {
|
|
|
104
104
|
private shutdownRequested;
|
|
105
105
|
/** The `/bug` hint is shown at most once per session so error output stays readable. */
|
|
106
106
|
private bugReportHintShown;
|
|
107
|
+
private installChangeWarningShown;
|
|
107
108
|
private extensionSelector;
|
|
108
109
|
private extensionInput;
|
|
109
110
|
private extensionEditor;
|
|
@@ -196,6 +197,12 @@ export declare class InteractiveMode {
|
|
|
196
197
|
private crashReportInstructions;
|
|
197
198
|
private suggestBugReport;
|
|
198
199
|
private maybeSuggestBugReport;
|
|
200
|
+
/**
|
|
201
|
+
* After an error, check whether an update replaced or removed this install while the session ran.
|
|
202
|
+
* Code loaded on demand then fails with missing modules until restart (#10439). Returns true when
|
|
203
|
+
* the install changed.
|
|
204
|
+
*/
|
|
205
|
+
private maybeShowInstallChangeWarning;
|
|
199
206
|
private renderCurrentSessionState;
|
|
200
207
|
/**
|
|
201
208
|
* Get a registered tool definition by name (for custom rendering).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interactive-mode.d.ts","sourceRoot":"","sources":["../../../src/modes/interactive/interactive-mode.ts"],"names":[],"mappings":"AAaA,OAAO,EAEN,KAAK,YAAY,EAKjB,MAAM,8BAA8B,CAAC;AActC,OAAO,EAYN,KAAK,QAAQ,EASb,MAAM,wBAAwB,CAAC;
|
|
1
|
+
{"version":3,"file":"interactive-mode.d.ts","sourceRoot":"","sources":["../../../src/modes/interactive/interactive-mode.ts"],"names":[],"mappings":"AAaA,OAAO,EAEN,KAAK,YAAY,EAKjB,MAAM,8BAA8B,CAAC;AActC,OAAO,EAYN,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BAAmB;YA4FnB,mBAAmB;IAkBjC,OAAO,CAAC,sBAAsB;YA6BhB,mBAAmB;YA4CnB,kBAAkB;YAWlB,gBAAgB;YAehB,iBAAiB;IA+B/B,OAAO,CAAC,iBAAiB;IAyBzB,OAAO,CAAC,oBAAoB;IAiF5B,OAAO,CAAC,sBAAsB;IAqB9B;;OAEG;IACH,OAAO,CAAC,gBAAgB;IAIxB;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAI3B,OAAO,CAAC,oBAAoB;YAwHd,kBAAkB;IAehC,OAAO,CAAC,kBAAkB;IAiC1B,OAAO,CAAC,iBAAiB;IAOzB,OAAO,CAAC,oBAAoB;YAMd,iBAAiB;YA6FjB,oBAAoB;IAUlC,IAAI,CAAC,oBAAoB,uBAAiD,GAAG,IAAI;CAsBjF"}
|
|
@@ -13,7 +13,7 @@ import * as TuiLayouts from "@earendil-works/pi-tui";
|
|
|
13
13
|
import { CombinedAutocompleteProvider, Container, fuzzyFilter, getCapabilities, hyperlink, Markdown, matchesKey, Spacer, setCapabilityOverrides, setKeybindings, Text, TruncatedText, TuiAltScreen, TuiMainScreen, visibleWidth, } from "@earendil-works/pi-tui";
|
|
14
14
|
import chalk from "chalk";
|
|
15
15
|
import { spawn } from "child_process";
|
|
16
|
-
import { APP_NAME, APP_TITLE, CONFIG_DIR_NAME, getAgentDir, getAuthPath, getDebugLogPath, getDocsPath, INSTALL_TELEMETRY_URL, UPDATE_CHANGELOG_HINT, VERSION, } from "../../config.js";
|
|
16
|
+
import { APP_NAME, APP_TITLE, CONFIG_DIR_NAME, detectInstallChange, getAgentDir, getAuthPath, getDebugLogPath, getDocsPath, INSTALL_TELEMETRY_URL, UPDATE_CHANGELOG_HINT, VERSION, } from "../../config.js";
|
|
17
17
|
import { parseSkillBlock } from "../../core/agent-session.js";
|
|
18
18
|
import { SessionImportFileNotFoundError } from "../../core/agent-session-runtime.js";
|
|
19
19
|
import { CACHE_TTL_MS, collectCacheMisses, computeCacheWaste, detectCacheMiss, } from "../../core/cache-stats.js";
|
|
@@ -147,7 +147,9 @@ function hotkeysTaskSection(display) {
|
|
|
147
147
|
| \`${display("app.tasks.detachSelected")}\` | ${detachSelected.description} (while /tasks is open) |
|
|
148
148
|
`;
|
|
149
149
|
}
|
|
150
|
-
|
|
150
|
+
// EIO: tty reads/ioctls from an orphaned background process group, or writes after hangup.
|
|
151
|
+
// ENOTTY: the tty was revoked (macOS) and stdin is no longer a terminal.
|
|
152
|
+
const DEAD_TERMINAL_ERROR_CODES = new Set(["EIO", "EPIPE", "ENOTCONN", "ENOTTY"]);
|
|
151
153
|
function isDeadTerminalError(error) {
|
|
152
154
|
if (!error || typeof error !== "object" || !("code" in error)) {
|
|
153
155
|
return false;
|
|
@@ -326,6 +328,7 @@ export class InteractiveMode {
|
|
|
326
328
|
this.shutdownRequested = false;
|
|
327
329
|
/** The `/bug` hint is shown at most once per session so error output stays readable. */
|
|
328
330
|
this.bugReportHintShown = false;
|
|
331
|
+
this.installChangeWarningShown = false;
|
|
329
332
|
// Extension UI state
|
|
330
333
|
this.extensionSelector = undefined;
|
|
331
334
|
this.extensionInput = undefined;
|
|
@@ -1654,8 +1657,32 @@ export class InteractiveMode {
|
|
|
1654
1657
|
return;
|
|
1655
1658
|
if (/\b(?:abort(?:ed)?|cancel(?:l?ed)?)\b/i.test(message.errorMessage ?? ""))
|
|
1656
1659
|
return;
|
|
1660
|
+
if (this.maybeShowInstallChangeWarning())
|
|
1661
|
+
return;
|
|
1657
1662
|
this.suggestBugReport();
|
|
1658
1663
|
}
|
|
1664
|
+
/**
|
|
1665
|
+
* After an error, check whether an update replaced or removed this install while the session ran.
|
|
1666
|
+
* Code loaded on demand then fails with missing modules until restart (#10439). Returns true when
|
|
1667
|
+
* the install changed.
|
|
1668
|
+
*/
|
|
1669
|
+
maybeShowInstallChangeWarning() {
|
|
1670
|
+
if (this.installChangeWarningShown)
|
|
1671
|
+
return true;
|
|
1672
|
+
const change = detectInstallChange();
|
|
1673
|
+
if (!change)
|
|
1674
|
+
return false;
|
|
1675
|
+
this.installChangeWarningShown = true;
|
|
1676
|
+
const cause = change.kind === "updated"
|
|
1677
|
+
? `${APP_NAME} was updated to ${change.version} while this session was running (${VERSION})`
|
|
1678
|
+
: `The ${APP_NAME} installation this session runs from was removed or replaced`;
|
|
1679
|
+
const resumeCommand = formatResumeCommand(this.sessionManager);
|
|
1680
|
+
const restart = resumeCommand
|
|
1681
|
+
? `Restart with \`${resumeCommand}\` to continue this session.`
|
|
1682
|
+
: `Restart ${APP_NAME}.`;
|
|
1683
|
+
this.showWarning(`${cause}. Features that load code on demand can fail until restart. ${restart}`);
|
|
1684
|
+
return true;
|
|
1685
|
+
}
|
|
1659
1686
|
renderCurrentSessionState() {
|
|
1660
1687
|
this.loadedResourcesContainer.clear();
|
|
1661
1688
|
this.chatContainer.clear();
|
|
@@ -2878,6 +2905,8 @@ export class InteractiveMode {
|
|
|
2878
2905
|
break;
|
|
2879
2906
|
}
|
|
2880
2907
|
case "tool_execution_end": {
|
|
2908
|
+
if (event.isError)
|
|
2909
|
+
this.maybeShowInstallChangeWarning();
|
|
2881
2910
|
const component = this.pendingTools.get(event.toolCallId);
|
|
2882
2911
|
if (component) {
|
|
2883
2912
|
component.updateResult({ ...event.result, isError: event.isError });
|
|
@@ -3458,6 +3487,10 @@ export class InteractiveMode {
|
|
|
3458
3487
|
* paste / Kitty / modifyOtherKeys sequences.
|
|
3459
3488
|
*/
|
|
3460
3489
|
uncaughtCrash(error) {
|
|
3490
|
+
// A dead terminal is not a pi crash. Do not try to restore it or record it.
|
|
3491
|
+
if (isDeadTerminalError(error)) {
|
|
3492
|
+
this.emergencyTerminalExit();
|
|
3493
|
+
}
|
|
3461
3494
|
if (this.isShuttingDown) {
|
|
3462
3495
|
process.exit(1);
|
|
3463
3496
|
}
|
|
@@ -3516,10 +3549,13 @@ export class InteractiveMode {
|
|
|
3516
3549
|
}
|
|
3517
3550
|
throw error;
|
|
3518
3551
|
};
|
|
3519
|
-
|
|
3520
|
-
process
|
|
3521
|
-
|
|
3522
|
-
|
|
3552
|
+
// stdin needs the handler too: once the terminal is gone, reads and setRawMode
|
|
3553
|
+
// fail with EIO (orphaned background process group) or ENOTTY (revoked tty).
|
|
3554
|
+
// Node emits these as stream errors, which are uncaught without a listener.
|
|
3555
|
+
for (const stream of [process.stdin, process.stdout, process.stderr]) {
|
|
3556
|
+
stream.on("error", terminalErrorHandler);
|
|
3557
|
+
this.signalCleanupHandlers.push(() => stream.off("error", terminalErrorHandler));
|
|
3558
|
+
}
|
|
3523
3559
|
// Restore the terminal before the process dies on any uncaught throw.
|
|
3524
3560
|
// Without this, an unhandled exception from extension code (or anywhere
|
|
3525
3561
|
// in pi) leaves the terminal in raw mode with no cursor.
|