@earendil-works/pi-coding-agent 1.0.3 → 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 +23 -0
- package/dist/bundle/chunks/{chunk-PSQJVYXD.js → chunk-2QSWSXFK.js} +4 -4
- package/dist/bundle/chunks/{chunk-AXOERKKW.js → chunk-64GOPQSC.js} +3 -1
- package/dist/bundle/chunks/{chunk-UBHCV62G.js → chunk-F4TCZWQO.js} +1 -1
- package/dist/bundle/chunks/{chunk-7TP2J6F2.js → chunk-FKGBRPJC.js} +1 -1
- package/dist/bundle/chunks/{chunk-BFNE7BHG.js → chunk-H33F2TZD.js} +28 -24
- package/dist/bundle/chunks/{chunk-J52J6TFP.js → chunk-KIPSWGXN.js} +1 -1
- package/dist/bundle/chunks/{chunk-ZSQEXT6X.js → chunk-VLMAON6X.js} +4 -4
- package/dist/bundle/chunks/{chunk-6DBOMCBS.js → chunk-XXKX4I4Z.js} +1 -1
- package/dist/bundle/chunks/{chunk-2VBQLN7Y.js → chunk-YKYP4C4A.js} +8 -5
- package/dist/bundle/chunks/{cli-HTJP6F6Z.js → cli-FRW732V6.js} +1 -1
- package/dist/bundle/chunks/codemode-worker.js +99 -3
- package/dist/bundle/chunks/{easter-egg-3d-6YCNESG3.js → easter-egg-3d-GBYHZI2E.js} +1 -1
- package/dist/bundle/chunks/{execute-JRUOLYDA.js → execute-MNHU53Y5.js} +101 -5
- package/dist/bundle/chunks/{runtime-NW7GPWKS.js → runtime-FW2HXAJ6.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-CFHJO5SY.js → virtual-modules-LQIMBBGM.js} +1 -1
- 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/cli/args.d.ts +1 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +11 -4
- package/dist/cli/args.js.map +1 -1
- package/dist/core/agent-session.d.ts +26 -4
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +47 -14
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/extensions/types.d.ts +2 -0
- 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 +8 -0
- package/dist/core/mcp-servers.d.ts.map +1 -1
- package/dist/core/mcp-servers.js +30 -7
- package/dist/core/mcp-servers.js.map +1 -1
- package/dist/core/resource-loader.d.ts +3 -0
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +4 -3
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/sdk.d.ts +9 -4
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +3 -2
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/skills.d.ts +4 -1
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/skills.js +6 -1
- package/dist/core/skills.js.map +1 -1
- package/dist/core/system-prompt.d.ts +6 -0
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +9 -4
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tools/read.d.ts +13 -0
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +18 -1
- package/dist/core/tools/read.js.map +1 -1
- package/dist/extensions/codemode/execute.d.ts.map +1 -1
- package/dist/extensions/codemode/execute.js +2 -1
- package/dist/extensions/codemode/execute.js.map +1 -1
- package/dist/extensions/codemode/index.d.ts.map +1 -1
- package/dist/extensions/codemode/index.js +1 -0
- package/dist/extensions/codemode/index.js.map +1 -1
- package/dist/extensions/codemode/tool.d.ts +9 -2
- package/dist/extensions/codemode/tool.d.ts.map +1 -1
- package/dist/extensions/codemode/tool.js +12 -4
- package/dist/extensions/codemode/tool.js.map +1 -1
- package/dist/extensions/mcp/resources.d.ts +3 -4
- package/dist/extensions/mcp/resources.d.ts.map +1 -1
- package/dist/extensions/mcp/resources.js +3 -4
- package/dist/extensions/mcp/resources.js.map +1 -1
- package/dist/extensions/mcp/runtime.d.ts +4 -1
- package/dist/extensions/mcp/runtime.d.ts.map +1 -1
- package/dist/extensions/mcp/runtime.js +22 -5
- package/dist/extensions/mcp/runtime.js.map +1 -1
- package/dist/extensions/mcp/tools.d.ts +2 -1
- package/dist/extensions/mcp/tools.d.ts.map +1 -1
- package/dist/extensions/mcp/tools.js +2 -1
- package/dist/extensions/mcp/tools.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +1 -0
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +1 -0
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/dist/utils/syntax-highlight.d.ts.map +1 -1
- package/dist/utils/syntax-highlight.js +6 -1
- package/dist/utils/syntax-highlight.js.map +1 -1
- package/docs/cli.md +15 -3
- package/docs/codemode.md +3 -2
- package/docs/extensions.md +1 -1
- package/docs/mcp.md +3 -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/package.json +10 -10
|
@@ -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,oB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,MAAM,IAAI,GAAG,kBAAkB,CAAC,UAAU,CAAC,CAAC;IAC5C,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE;QACnB,WAAW,EAAE,yBAAyB,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,KAAK,IAAI,EAAE,CAAC;QAClF,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;KAC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["/**\n * The `codemode` tool: the model writes JavaScript that calls other tools. Scripts use `tools`,\n * `ALL_TOOLS`, `text()`, `image()`, `exit()`, `store()`/`load()`, `console.*`, and `return <value>`,\n * may start with a `// @options:` line, and reach the model catalog, classifiers, and image models\n * through `models.*`. Results start with a \"Script completed\" or \"Script failed\" header.\n *\n * Scripts can call the agent loop's nested tools: active `direct` tools and every `codemode` or\n * `deferred` tool. Nested calls run through the agent loop's tool pipeline (`ctx.executeTool`), so\n * validation, `tool_call`/`tool_result` hooks, and permission checks apply exactly as for direct\n * calls. Only the script's output reaches the model; nested results do not.\n *\n * Nested results are handed to the script as follows:\n * - A tool that declares `outputSchema` resolves to its `structuredContent`, also for error\n * results that carry one (MCP tools resolve to their `CallToolResult`, including `isError`).\n * - Any other tool resolves to its text content as one string.\n * - A failed, blocked, or invalid call rejects with an Error carrying the tool's error text.\n *\n * A script that fails returns a normal error result that keeps its partial output, followed by\n * \"Script error:\" and the error. `store(key, value)` and `load(key)` keep JSON values across\n * calls; successful scripts append their writes to the session as `codemode-store` custom entries,\n * so each branch sees the values written on its own path.\n */\n\nimport { join } from \"node:path\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport type { CodemodeJsonSchema, CodemodeTool } from \"@earendil-works/pi-codemode\";\nimport {\n\tMCP_TYPESCRIPT_PREAMBLE,\n\tmcpStructuredContentSchema,\n\trenderToolOutputType,\n\trenderToolSample,\n\ttoCodemodeIdentifier,\n} from \"@earendil-works/pi-codemode/declarations\";\nimport { CODEMODE_SOURCE_GRAMMAR } from \"@earendil-works/pi-codemode/source\";\nimport { type Static, Type } from \"typebox\";\nimport { getDocsPath } from \"../../config.ts\";\nimport type {\n\tToolDefinition,\n\tToolInfo,\n\tToolLoadout,\n\tToolLoadoutChanges,\n\tToolNamespace,\n} from \"../../core/extensions/types.ts\";\nimport type { ModelRegistry } from \"../../core/model-registry.ts\";\nimport type { CodemodeMode } from \"../../core/settings-manager.ts\";\nimport { wrapToolDefinition } from \"../../core/tools/tool-definition-wrapper.ts\";\nimport { loadCodemodeExecutor } from \"./execute.lazy.ts\";\nimport { codemodeRenderers } from \"./renderer.ts\";\n\nexport const CODEMODE_TOOL_NAME = \"codemode\";\n\n/** Custom entry type holding one script's `store()` writes: {@link CodemodeStoreEntryData}. */\nexport const CODEMODE_STORE_ENTRY_TYPE = \"codemode-store\";\n\nexport interface CodemodeStoreEntryData {\n\tset: Record<string, unknown>;\n\tdelete: string[];\n}\n\n/** The part of the model registry that scripts reach through `models`. */\nexport type CodemodeModelRuntime = Pick<\n\tModelRegistry,\n\t\"getModelsOfType\" | \"getAvailableOfType\" | \"getModelOfType\" | \"classify\" | \"generateImages\"\n>;\n\nexport interface CodemodeToolOptions {\n\t/** Namespace of a tool, for `searchTools()` ranking and its `namespace` filter. */\n\tgetToolNamespace?: (toolName: string) => ToolNamespace | undefined;\n\t/**\n\t * Expose the `models` namespace to scripts, backed by the session's model registry\n\t * (`ctx.modelRegistry`). Without it, `models` is not declared.\n\t */\n\tmodels?: boolean;\n\t/**\n\t * Persists `store()` writes as a session custom entry. Without it, writes last only for the\n\t * current script; `load()` still reads entries already on the branch.\n\t */\n\tappendEntry?: (customType: string, data: CodemodeStoreEntryData) => void;\n\t/** How the tool presents the loadout while active (the `codemode.mode` setting). Default: `on`. */\n\tgetMode?: () => CodemodeMode;\n\t/** Token budget for tool declarations in the description. Default: {@link DEFAULT_CODEMODE_INLINE_BUDGET}. */\n\tgetInlineBudget?: () => number | undefined;\n}\n\nconst TEXT_OUTPUT_SCHEMA: CodemodeJsonSchema = { type: \"string\" };\n\nexport const codemodeSchema = Type.Object({\n\tcode: Type.String({\n\t\tdescription: \"Raw JavaScript source.\",\n\t}),\n});\n\nexport type CodemodeToolInput = Static<typeof codemodeSchema>;\n\n/**\n * Whether a registered tool is this package's `codemode` tool rather than another extension's tool\n * with the same name. Compares the parameter schema, which the definition passes through by reference.\n */\nexport function isCodemodeTool(tool: Pick<ToolInfo, \"name\" | \"parameters\">): boolean {\n\treturn tool.name === CODEMODE_TOOL_NAME && tool.parameters === codemodeSchema;\n}\n\nexport type CodemodeNestedCallStatus = \"running\" | \"ok\" | \"error\" | \"cancelled\";\n\nexport interface CodemodeNestedCall {\n\t/** Tool call id of the nested call, `<codemode call id>/<n>`. */\n\tid: string;\n\tname: string;\n\t/** Compact JSON of the arguments, truncated for display. */\n\targs: string;\n\tstatus: CodemodeNestedCallStatus;\n\tdurationMs?: number;\n\t/** Error text, truncated for display. */\n\terror?: string;\n\t/** Cost in USD of a `models.*` call that reported usage. */\n\tcost?: number;\n}\n\nexport interface CodemodeToolDetails {\n\tcalls: CodemodeNestedCall[];\n\t/** Temp file with the full text output, when the output was truncated. */\n\tfullOutputPath?: string;\n}\n\nexport const codemodeToolSystemPromptContribution = {\n\tsnippet: \"Run JavaScript that calls other tools\",\n\tguidelines: [\n\t\t\"Use codemode to batch independent tool calls (Promise.allSettled), chain them, or filter large output, instead of many separate calls.\",\n\t],\n} as const;\n\n/** The reference for scripts: globals, tool results, `store()`, the `models` API, and limits. */\nexport const CODEMODE_DOCS_PATH = join(getDocsPath(), \"codemode.md\");\n\nconst DESCRIPTION_INTRO = `Run JavaScript that calls other tools. The input is raw JavaScript (not JSON, no code fence), run as an async function body in a QuickJS sandbox: top-level \\`await\\` and \\`return\\` work. No Node, file system, network, or timers.\n- \\`await tools.<name>({ ...args })\\` resolves to a string, or an object if the tool's declaration says so, and rejects with an Error on failure. Calls still running when the script ends are cancelled.\n- Optional first line: \\`// @options: {\"max_output_tokens\": 10000, \"timeout_ms\": 60000}\\``;\n\n/** One line per global. The details live in {@link CODEMODE_DOCS_PATH}. */\nfunction describeGlobals(models: boolean): string {\n\tconst lines = [\n\t\t\"Globals:\",\n\t\t\"- `text(value)`, `image(dataUrlOrImageBlock)`, `console.log(...)`, and top-level `return` add output; `exit()` ends the script. `image()` also saves the image to a temp file and the result names its path.\",\n\t\t\"- `store(key, value)` and `load(key)` keep JSON values across codemode calls.\",\n\t\t\"- `ALL_TOOLS`, `searchTools(query, { limit?, namespace? })`, `describeTool(name)`, `describeNamespace(name)`: find unlisted tools, such as MCP tools.\",\n\t];\n\tif (models) {\n\t\tlines.push(`- \\`models\\`: classifiers and image generation. Read ${CODEMODE_DOCS_PATH} first.`);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\n/** Default for {@link CodemodeDescriptionOptions.inlineBudget}, in estimated tokens. */\nexport const DEFAULT_CODEMODE_INLINE_BUDGET = 3000;\n/** Characters per token when estimating the cost of a tool section. */\nconst CHARS_PER_TOKEN = 4;\n\n/** What a script sees of a tool. Tools without an output schema resolve to their text output. */\nexport function toCodemodeDeclaration(tool: AgentTool<any>): Omit<CodemodeTool, \"execute\"> {\n\treturn {\n\t\tname: tool.name,\n\t\tdescription: tool.description,\n\t\tinputSchema: tool.parameters as CodemodeJsonSchema,\n\t\toutputSchema: (tool.outputSchema as CodemodeJsonSchema | undefined) ?? TEXT_OUTPUT_SCHEMA,\n\t};\n}\n\n/** Tools a script may call: every given tool except the codemode tool itself. */\nexport function getCodemodeCallableTools(tools: readonly AgentTool<any>[]): AgentTool<any>[] {\n\treturn tools.filter((tool) => tool.name !== CODEMODE_TOOL_NAME);\n}\n\nexport interface CodemodeDescriptionOptions {\n\t/** Declare the `models` namespace; only for tools created with model access. */\n\tmodels?: boolean;\n\t/** Namespace of each tool, by tool name. Tools of one namespace are listed under one heading. */\n\tnamespaces?: ReadonlyMap<string, ToolNamespace>;\n\t/** Tools that are callable but never listed with their declaration (`deferred` exposure). */\n\tdeferred?: ReadonlySet<string>;\n\t/**\n\t * Estimated tokens (characters / 4) the tool sections may use. Tools that do not fit are left\n\t * out, like deferred tools. Unset lists every tool that is not deferred.\n\t */\n\tinlineBudget?: number;\n}\n\n/** `### \\`id\\` (\\`raw name\\`)` followed by the tool's description and declaration. */\nfunction renderToolSection(declaration: Omit<CodemodeTool, \"execute\">): string {\n\tconst id = toCodemodeIdentifier(declaration.name);\n\tconst heading = id === declaration.name ? `### \\`${id}\\`` : `### \\`${id}\\` (\\`${declaration.name}\\`)`;\n\treturn `${heading}\\n${renderToolSample(declaration).trim()}`;\n}\n\ninterface CatalogEntry {\n\tname: string;\n\tsection: string;\n\tcost: number;\n}\n\ninterface CatalogGroup {\n\tnamespace: ToolNamespace | undefined;\n\tentries: CatalogEntry[];\n}\n\n/**\n * Pick the tool sections that fit the budget, like OpenCode's catalog: in each round every group\n * (tools without a namespace first, then namespaces by name) places its cheapest remaining tool; a\n * group whose next tool does not fit drops out while the others continue. Every namespace is\n * represented before any namespace is complete.\n */\nfunction selectCatalog(groups: readonly CatalogGroup[], budget: number | undefined): Set<string> {\n\tif (budget === undefined) return new Set(groups.flatMap((group) => group.entries.map((entry) => entry.name)));\n\tconst queues = groups.map((group) => [...group.entries].sort((a, b) => a.cost - b.cost));\n\tconst shown = new Set<string>();\n\tlet remaining = budget;\n\tlet active = queues.filter((queue) => queue.length > 0);\n\twhile (active.length > 0) {\n\t\tactive = active.filter((queue) => {\n\t\t\tconst next = queue[0];\n\t\t\tif (next.cost > remaining) return false;\n\t\t\tremaining -= next.cost;\n\t\t\tshown.add(next.name);\n\t\t\tqueue.shift();\n\t\t\treturn queue.length > 0;\n\t\t});\n\t}\n\treturn shown;\n}\n\n/**\n * Model-facing description: the helper list, guidance for finding tools that are not listed, the\n * shared MCP types when listed tools need them, the `models` API, and one section per listed tool,\n * grouped by namespace. Deferred tools are never listed and do not affect the description at all, so\n * it stays the same while MCP servers connect or change their tools. Tool sections are limited to\n * `inlineBudget`.\n */\nexport function createCodemodeDescription(\n\ttools: readonly AgentTool<any>[],\n\toptions: CodemodeDescriptionOptions = {},\n): string {\n\tconst declarations = getCodemodeCallableTools(tools)\n\t\t.filter((tool) => !options.deferred?.has(tool.name))\n\t\t.map(toCodemodeDeclaration);\n\tconst groups = new Map<string, CatalogGroup>([[\"\", { namespace: undefined, entries: [] }]]);\n\tfor (const declaration of declarations) {\n\t\tconst namespace = options.namespaces?.get(declaration.name);\n\t\tconst key = namespace ? `ns:${namespace.name}` : \"\";\n\t\tconst group = groups.get(key) ?? { namespace, entries: [] };\n\t\tgroups.set(key, group);\n\t\tconst section = renderToolSection(declaration);\n\t\tgroup.entries.push({ name: declaration.name, section, cost: Math.ceil(section.length / CHARS_PER_TOKEN) });\n\t}\n\tconst ordered = [...groups.values()].sort((a, b) =>\n\t\ta.namespace === undefined ? -1 : b.namespace === undefined ? 1 : a.namespace.name.localeCompare(b.namespace.name),\n\t);\n\tconst shown = selectCatalog(ordered, options.inlineBudget);\n\n\tconst sections = [DESCRIPTION_INTRO, describeGlobals(options.models === true)];\n\tif (\n\t\tdeclarations.some(\n\t\t\t(declaration) =>\n\t\t\t\tshown.has(declaration.name) && mcpStructuredContentSchema(declaration.outputSchema) !== undefined,\n\t\t)\n\t) {\n\t\tsections.push(`Shared MCP Types:\\n\\`\\`\\`ts\\n${MCP_TYPESCRIPT_PREAMBLE}\\n\\`\\`\\``);\n\t}\n\tif (declarations.length === 0) return sections.join(\"\\n\\n\");\n\n\tconst toolSections = [\"Nested tools:\"];\n\tfor (const { namespace, entries } of ordered) {\n\t\tconst visible = entries.filter((entry) => shown.has(entry.name));\n\t\tif (namespace) {\n\t\t\t// Only tools that did not fit the budget are counted as not listed here.\n\t\t\tconst listing =\n\t\t\t\tvisible.length === entries.length\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: visible.length === 0\n\t\t\t\t\t\t? \" (tools not listed)\"\n\t\t\t\t\t\t: \" (some tools not listed)\";\n\t\t\tconst description = namespace.description?.trim();\n\t\t\ttoolSections.push(`## ${namespace.name}${listing}${description ? `\\n${description}` : \"\"}`);\n\t\t}\n\t\tfor (const entry of visible) toolSections.push(entry.section);\n\t}\n\tsections.push(toolSections.join(\"\\n\\n\"));\n\treturn sections.join(\"\\n\\n\");\n}\n\n/**\n * What a script call resolves to, in one line: `a string`, the field names of an object\n * (`{ output, exit_code, full_output_path? }`), or the rendered type for anything else.\n */\nfunction describeOutput(schema: CodemodeJsonSchema | undefined): string {\n\tconst type = renderToolOutputType(schema);\n\tif (type === \"string\") return \"a string\";\n\tconst object = typeof schema === \"object\" ? schema : undefined;\n\tconst properties = object?.properties;\n\tif (\n\t\tobject?.type === \"object\" &&\n\t\ttypeof properties === \"object\" &&\n\t\tproperties !== null &&\n\t\tmcpStructuredContentSchema(schema) === undefined\n\t) {\n\t\tconst required = new Set(Array.isArray(object.required) ? object.required : []);\n\t\tconst fields = Object.keys(properties).map((name) => (required.has(name) ? name : `${name}?`));\n\t\treturn `\\`{ ${fields.join(\", \")} }\\``;\n\t}\n\treturn `\\`${type.replace(/\\s+/g, \" \")}\\``;\n}\n\n/**\n * A declared tool's description followed by how scripts call it and what the call resolves to. The\n * arguments are the tool's declared parameters, so they are not repeated.\n */\nfunction describeScriptCall(tool: AgentTool<any>): string {\n\treturn `${tool.description.trim()}\\n\\nCodemode: \\`tools.${toCodemodeIdentifier(tool.name)}(args)\\` resolves to ${describeOutput(toCodemodeDeclaration(tool).outputSchema)}.`;\n}\n\n/**\n * How the codemode tool presents tools that are both declared and callable from scripts:\n * - `on`: their descriptions say how scripts call them, and the codemode description\n * lists only the callable tools without `direct` exposure.\n * - `only`: the codemode description lists every callable tool, and requests leave out the\n * declarations of active `direct` tools.\n *\n * Listing by exposure, not by the active set, keeps the codemode description unchanged when\n * `tool_search` loads a tool, so loads do not redeclare codemode.\n */\nfunction prepareCodemodeLoadout(loadout: ToolLoadout, options: CodemodeToolOptions): ToolLoadoutChanges {\n\tconst mode = options.getMode?.() ?? \"on\";\n\tconst isDirect = (tool: AgentTool) => loadout.getExposure(tool.name) === \"direct\";\n\tconst callable = getCodemodeCallableTools(loadout.callable);\n\tconst callableNames = new Set(callable.map((tool) => tool.name));\n\tconst descriptions: Record<string, string> = {};\n\tif (mode === \"on\") {\n\t\tfor (const tool of loadout.declared) {\n\t\t\tif (callableNames.has(tool.name)) descriptions[tool.name] = describeScriptCall(tool);\n\t\t}\n\t}\n\tconst listed = mode === \"only\" ? callable : callable.filter((tool) => !isDirect(tool));\n\tconst namespaces = new Map(\n\t\tlisted.flatMap((tool) => {\n\t\t\tconst namespace = loadout.getNamespace(tool.name);\n\t\t\treturn namespace ? [[tool.name, namespace] as const] : [];\n\t\t}),\n\t);\n\tdescriptions[CODEMODE_TOOL_NAME] = createCodemodeDescription(listed, {\n\t\tmodels: options.models === true,\n\t\tnamespaces,\n\t\tdeferred: new Set(\n\t\t\tlisted.filter((tool) => loadout.getExposure(tool.name) === \"deferred\").map((tool) => tool.name),\n\t\t),\n\t\tinlineBudget: options.getInlineBudget?.() ?? DEFAULT_CODEMODE_INLINE_BUDGET,\n\t});\n\tconst declaredNames = new Set(loadout.declared.map((tool) => tool.name));\n\treturn {\n\t\tdescriptions,\n\t\thiddenDeclarations:\n\t\t\tmode === \"only\"\n\t\t\t\t? callable.filter((tool) => isDirect(tool) && declaredNames.has(tool.name)).map((tool) => tool.name)\n\t\t\t\t: [],\n\t};\n}\n\nexport function createCodemodeToolDefinition(\n\toptions: CodemodeToolOptions = {},\n): ToolDefinition<typeof codemodeSchema, CodemodeToolDetails | undefined> {\n\treturn {\n\t\tname: CODEMODE_TOOL_NAME,\n\t\tlabel: CODEMODE_TOOL_NAME,\n\t\t// Replaced with the declarations of the callable tools when the tool is activated.\n\t\tdescription: createCodemodeDescription([], { models: options.models === true }),\n\t\tpromptSnippet: codemodeToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: [...codemodeToolSystemPromptContribution.guidelines],\n\t\tparameters: codemodeSchema,\n\t\t// Scripts must not start other scripts.\n\t\texposure: \"model-only\",\n\t\tprepareLoadout: (loadout) => prepareCodemodeLoadout(loadout, options),\n\t\t// Capable models write the script as raw text instead of a JSON-escaped string.\n\t\tconstrainedSampling: { type: \"grammar\", variants: { openai_lark: CODEMODE_SOURCE_GRAMMAR } },\n\t\t// The sandbox (worker, QuickJS wasm) loads on the first call, not at startup.\n\t\texecute: async (toolCallId, params, signal, onUpdate, ctx) =>\n\t\t\t(await loadCodemodeExecutor()).executeCodemode(toolCallId, params, signal, onUpdate, ctx, options),\n\t\t...codemodeRenderers,\n\t};\n}\n\n/**\n * Create the codemode tool as an AgentTool. The description lists the given tools; the script can\n * call whatever tools the agent loop provides at execution time.\n */\nexport function createCodemodeTool(\n\ttools: readonly AgentTool<any>[] = [],\n\toptions: CodemodeToolOptions = {},\n): AgentTool<typeof codemodeSchema> {\n\tconst definition = createCodemodeToolDefinition(options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tdescription: createCodemodeDescription(tools, { models: options.models === true }),\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
|
|
1
|
+
{"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,M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,SAAS,EAAE,QAAQ,EAAE,EAAE,WAAW,EAAE,uBAAuB,EAAE,EAAE;QAC5F,8EAA8E;QAC9E,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,EAAE,EAAE,CAC5D,CAAC,MAAM,oBAAoB,EAAE,CAAC,CAAC,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,EAAE,OAAO,CAAC;QACnG,GAAG,iBAAiB;KACpB,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CACjC,KAAK,GAA8B,EAAE,EACrC,OAAO,GAAwB,EAAE;IAEjC,MAAM,UAAU,GAAG,4BAA4B,CAAC,OAAO,CAAC,CAAC;IACzD,MAAM,IAAI,GAAG,kBAAkB,CAAC,UAAU,CAAC,CAAC;IAC5C,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE;QACnB,WAAW,EAAE,yBAAyB,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,KAAK,IAAI,EAAE,CAAC;QAClF,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;KAC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["/**\n * The `codemode` tool: the model writes JavaScript that calls other tools. Scripts use `tools`,\n * `ALL_TOOLS`, `text()`, `image()`, `exit()`, `store()`/`load()`, `console.*`, and `return <value>`,\n * may start with a `// @options:` line, and reach the model catalog, classifiers, and image models\n * through `models.*`. Results start with a \"Script completed\" or \"Script failed\" header.\n *\n * Scripts can call the agent loop's nested tools: active `direct` tools and every `codemode` or\n * `deferred` tool. Nested calls run through the agent loop's tool pipeline (`ctx.executeTool`), so\n * validation, `tool_call`/`tool_result` hooks, and permission checks apply exactly as for direct\n * calls. Only the script's output reaches the model; nested results do not.\n *\n * Nested results are handed to the script as follows:\n * - A tool that declares `outputSchema` resolves to its `structuredContent`, also for error\n * results that carry one (MCP tools resolve to their `CallToolResult`, including `isError`).\n * - Any other tool resolves to its text content as one string.\n * - A failed, blocked, or invalid call rejects with an Error carrying the tool's error text.\n *\n * A script that fails returns a normal error result that keeps its partial output, followed by\n * \"Script error:\" and the error. `store(key, value)` and `load(key)` keep JSON values across\n * calls; successful scripts append their writes to the session as `codemode-store` custom entries,\n * so each branch sees the values written on its own path.\n */\n\nimport { join } from \"node:path\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport type { CodemodeJsonSchema, CodemodeTool } from \"@earendil-works/pi-codemode\";\nimport {\n\tMCP_TYPESCRIPT_PREAMBLE,\n\tmcpStructuredContentSchema,\n\trenderToolOutputType,\n\trenderToolSample,\n\ttoCodemodeIdentifier,\n} from \"@earendil-works/pi-codemode/declarations\";\nimport { CODEMODE_SOURCE_GRAMMAR } from \"@earendil-works/pi-codemode/source\";\nimport { type Static, Type } from \"typebox\";\nimport { getDocsPath } from \"../../config.ts\";\nimport type {\n\tToolDefinition,\n\tToolInfo,\n\tToolLoadout,\n\tToolLoadoutChanges,\n\tToolNamespace,\n} from \"../../core/extensions/types.ts\";\nimport type { ModelRegistry } from \"../../core/model-registry.ts\";\nimport type { CodemodeMode } from \"../../core/settings-manager.ts\";\nimport { wrapToolDefinition } from \"../../core/tools/tool-definition-wrapper.ts\";\nimport { loadCodemodeExecutor } from \"./execute.lazy.ts\";\nimport { codemodeRenderers } from \"./renderer.ts\";\n\nexport const CODEMODE_TOOL_NAME = \"codemode\";\n\n/** Custom entry type holding one script's `store()` writes: {@link CodemodeStoreEntryData}. */\nexport const CODEMODE_STORE_ENTRY_TYPE = \"codemode-store\";\n\nexport interface CodemodeStoreEntryData {\n\tset: Record<string, unknown>;\n\tdelete: string[];\n}\n\n/** The part of the model registry that scripts reach through `models`. */\nexport type CodemodeModelRuntime = Pick<\n\tModelRegistry,\n\t\"getModelsOfType\" | \"getAvailableOfType\" | \"getModelOfType\" | \"classify\" | \"generateImages\"\n>;\n\nexport interface CodemodeToolOptions {\n\t/** Namespace of a tool, for `searchTools()` ranking and its `namespace` filter. */\n\tgetToolNamespace?: (toolName: string) => ToolNamespace | undefined;\n\t/** Prompt guidelines of every tool, by tool name, shown with declarations by `describeTool()` and `ALL_TOOLS`. */\n\tgetToolGuidelines?: () => ReadonlyMap<string, readonly string[]>;\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/**\n * What a script sees of a tool: its description followed by its prompt guidelines, which the system\n * prompt only has for declared tools. Tools without an output schema resolve to their text output.\n */\nexport function toCodemodeDeclaration(\n\ttool: AgentTool<any>,\n\tguidelines: readonly string[] = [],\n): Omit<CodemodeTool, \"execute\"> {\n\tconst bullets = guidelines.flatMap((guideline) => (guideline.trim() ? [`- ${guideline.trim()}`] : []));\n\treturn {\n\t\tname: tool.name,\n\t\tdescription: bullets.length > 0 ? `${tool.description.trim()}\\n\\n${bullets.join(\"\\n\")}` : 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/** Prompt guidelines of each tool, by tool name, listed after its description. */\n\tguidelines?: ReadonlyMap<string, readonly 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((tool) => toCodemodeDeclaration(tool, options.guidelines?.get(tool.name)));\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 * Listed tools carry their prompt guidelines, which the system prompt only has for declared 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\tconst guidelines = new Map(listed.map((tool) => [tool.name, loadout.getPromptGuidelines(tool.name)] as const));\n\tdescriptions[CODEMODE_TOOL_NAME] = createCodemodeDescription(listed, {\n\t\tmodels: options.models === true,\n\t\tnamespaces,\n\t\tguidelines,\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"]}
|
|
@@ -12,11 +12,10 @@
|
|
|
12
12
|
import type { ListResourcesResult, ListResourceTemplatesResult, McpRequestOptions, ReadResourceResult, Resource, ResourceTemplate } from "@earendil-works/pi-mcp";
|
|
13
13
|
import type { TSchema } from "typebox";
|
|
14
14
|
import type { ToolDefinition } from "../../core/extensions/types.ts";
|
|
15
|
+
import { LIST_MCP_RESOURCE_TEMPLATES_TOOL, LIST_MCP_RESOURCES_TOOL, READ_MCP_RESOURCE_TOOL } from "../../core/mcp-servers.ts";
|
|
15
16
|
import type { McpExposure } from "./config.ts";
|
|
16
|
-
import { type McpToolDetails
|
|
17
|
-
export
|
|
18
|
-
export declare const LIST_MCP_RESOURCE_TEMPLATES_TOOL = "list_mcp_resource_templates";
|
|
19
|
-
export { READ_MCP_RESOURCE_TOOL };
|
|
17
|
+
import { type McpToolDetails } from "./tools.ts";
|
|
18
|
+
export { LIST_MCP_RESOURCE_TEMPLATES_TOOL, LIST_MCP_RESOURCES_TOOL, READ_MCP_RESOURCE_TOOL };
|
|
20
19
|
/** A connected server that offers resources. */
|
|
21
20
|
export interface McpResourceServer {
|
|
22
21
|
name: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resources.d.ts","sourceRoot":"","sources":["../../../src/extensions/mcp/resources.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,KAAK,EAEX,mBAAmB,EACnB,2BAA2B,EAC3B,iBAAiB,EACjB,kBAAkB,EAClB,QAAQ,EACR,gBAAgB,EAChB,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,KAAK,EAAmB,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACtF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,
|
|
1
|
+
{"version":3,"file":"resources.d.ts","sourceRoot":"","sources":["../../../src/extensions/mcp/resources.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,KAAK,EAEX,mBAAmB,EACnB,2BAA2B,EAC3B,iBAAiB,EACjB,kBAAkB,EAClB,QAAQ,EACR,gBAAgB,EAChB,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,KAAK,EAAmB,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACtF,OAAO,EACN,gCAAgC,EAChC,uBAAuB,EACvB,sBAAsB,EACtB,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAmB,KAAK,cAAc,EAAkC,MAAM,YAAY,CAAC;AAElG,OAAO,EAAE,gCAAgC,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,CAAC;AAE7F,gDAAgD;AAChD,MAAM,WAAW,iBAAiB;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,EAAE,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAAC;IACpG,qBAAqB,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,EAAE,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAAC;IACpH,YAAY,CAAC,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC;IAC9D,oBAAoB,CAAC,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAAC;IAC9E,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC;CACnF;AAED,0EAA0E;AAC1E,wBAAgB,gBAAgB,CAAC,IAAI,EAAE;IAAE,GAAG,CAAC,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,OAAO,CAGzG;AA6ID;;GAEG;AACH,wBAAgB,gCAAgC,CAAC,OAAO,EAAE;IACzD,QAAQ,EAAE,WAAW,CAAC;IACtB,OAAO,EAAE,MAAM,SAAS,iBAAiB,EAAE,CAAC;CAC5C,GAAG,cAAc,CAAC,OAAO,EAAE,cAAc,CAAC,EAAE,CA8I5C"}
|
|
@@ -9,10 +9,9 @@
|
|
|
9
9
|
* interfaces for hosts that render them, and so are icons. Read resources become text and images for
|
|
10
10
|
* the model; binary resources are saved to temp files. Scripts get the JSON payloads.
|
|
11
11
|
*/
|
|
12
|
-
import {
|
|
13
|
-
|
|
14
|
-
export
|
|
15
|
-
export { READ_MCP_RESOURCE_TOOL };
|
|
12
|
+
import { LIST_MCP_RESOURCE_TEMPLATES_TOOL, LIST_MCP_RESOURCES_TOOL, READ_MCP_RESOURCE_TOOL, } from "../../core/mcp-servers.js";
|
|
13
|
+
import { limitMcpContent, toModelContent, toToolExposure } from "./tools.js";
|
|
14
|
+
export { LIST_MCP_RESOURCE_TEMPLATES_TOOL, LIST_MCP_RESOURCES_TOOL, READ_MCP_RESOURCE_TOOL };
|
|
16
15
|
/** MCP App user interfaces, which only hosts that render them can use. */
|
|
17
16
|
export function isMcpAppResource(item) {
|
|
18
17
|
const uri = item.uri ?? item.uriTemplate ?? "";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resources.js","sourceRoot":"","sources":["../../../src/extensions/mcp/resources.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAeH,OAAO,EACN,eAAe,EAEf,sBAAsB,EACtB,cAAc,EACd,cAAc,GACd,MAAM,YAAY,CAAC;AAEpB,MAAM,CAAC,MAAM,uBAAuB,GAAG,oBAAoB,CAAC;AAC5D,MAAM,CAAC,MAAM,gCAAgC,GAAG,6BAA6B,CAAC;AAC9E,OAAO,EAAE,sBAAsB,EAAE,CAAC;AAalC,0EAA0E;AAC1E,MAAM,UAAU,gBAAgB,CAAC,IAA+D;IAC/F,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,IAAI,IAAI,CAAC,WAAW,IAAI,EAAE,CAAC;IAC/C,OAAO,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,gCAAgC,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,IAAI,EAAE,CAAC,CAAC;AAC9F,CAAC;AAED,uFAAuF;AACvF,SAAS,MAAM,CAAgC,MAAc,EAAE,IAAO;IACrE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,IAA+B,CAAC;IAC1E,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,CAAC;AAC5B,CAAC;AAED,MAAM,cAAc,GAAG,CAAC,WAAmB,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;AAClF,MAAM,aAAa,GAAG,cAAc,CAAC,4DAA4D,CAAC,CAAC;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,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,YAAY,GAAG,YAAY,EAAE,CAAC,CACxF,CAAC;YACF,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,QAAQ,EAAE,GAAG,IAAI,EAAE,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC;YAC7E,OAAO;gBACN,OAAO;gBACP,OAAO,EAAE;oBACR,MAAM,EAAE,MAAM,CAAC,IAAI;oBACnB,IAAI,EAAE,sBAAsB;oBAC5B,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;iBAC7C;gBACD,iBAAiB,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,IAAI,EAAE,GAAG,EAAE,QAAQ,EAA0B;aACjF,CAAC;QACH,CAAC;KACD,CAAC;IAEF,OAAO,CAAC,aAAa,EAAE,aAAa,EAAE,YAAY,CAAC,CAAC;AACrD,CAAC","sourcesContent":["/**\n * MCP resources, through the tools Codex and opencode use: `list_mcp_resources`,\n * `list_mcp_resource_templates`, and `read_mcp_resource`. They take a `server` argument and cover\n * every connected server with resources, so models trained on those tools use them unchanged.\n *\n * Listings are JSON, as in Codex: `{ server?, resources: [{ server, ...resource }], nextCursor? }`.\n * With a `server`, one page is listed and `cursor` continues it; without, every page of every server.\n * MCP App resources (`ui://` URIs and `profile=mcp-app` HTML) are left out, since they are user\n * interfaces for hosts that render them, and so are icons. Read resources become text and images for\n * the model; binary resources are saved to temp files. Scripts get the JSON payloads.\n */\n\nimport type { ImageContent, JsonValue, TextContent } from \"@earendil-works/pi-ai\";\nimport type {\n\tContentBlock,\n\tListResourcesResult,\n\tListResourceTemplatesResult,\n\tMcpRequestOptions,\n\tReadResourceResult,\n\tResource,\n\tResourceTemplate,\n} from \"@earendil-works/pi-mcp\";\nimport type { TSchema } from \"typebox\";\nimport type { ToolAnnotations, ToolDefinition } from \"../../core/extensions/types.ts\";\nimport type { McpExposure } from \"./config.ts\";\nimport {\n\tlimitMcpContent,\n\ttype McpToolDetails,\n\tREAD_MCP_RESOURCE_TOOL,\n\ttoModelContent,\n\ttoToolExposure,\n} from \"./tools.ts\";\n\nexport const LIST_MCP_RESOURCES_TOOL = \"list_mcp_resources\";\nexport const LIST_MCP_RESOURCE_TEMPLATES_TOOL = \"list_mcp_resource_templates\";\nexport { READ_MCP_RESOURCE_TOOL };\n\n/** A connected server that offers resources. */\nexport interface McpResourceServer {\n\tname: string;\n\ttimeoutMs: number;\n\tresourcesPage(cursor: string | undefined, options: McpRequestOptions): Promise<ListResourcesResult>;\n\tresourceTemplatesPage(cursor: string | undefined, options: McpRequestOptions): Promise<ListResourceTemplatesResult>;\n\tallResources(options: McpRequestOptions): Promise<Resource[]>;\n\tallResourceTemplates(options: McpRequestOptions): Promise<ResourceTemplate[]>;\n\treadResource(uri: string, options: McpRequestOptions): Promise<ReadResourceResult>;\n}\n\n/** MCP App user interfaces, which only hosts that render them can use. */\nexport function isMcpAppResource(item: { uri?: string; uriTemplate?: string; mimeType?: string }): boolean {\n\tconst uri = item.uri ?? item.uriTemplate ?? \"\";\n\treturn uri.startsWith(\"ui://\") || /;\\s*profile\\s*=\\s*\"?mcp-app\"?/i.test(item.mimeType ?? \"\");\n}\n\n/** A listed resource or template without `_meta` and icons, tagged with its server. */\nfunction listed<T extends { _meta?: unknown }>(server: string, item: T): Record<string, unknown> {\n\tconst { _meta, icons: _icons, ...rest } = item as T & { icons?: unknown };\n\treturn { server, ...rest };\n}\n\nconst stringProperty = (description: string) => ({ type: \"string\", description });\nconst SERVER_FILTER = stringProperty(\"MCP server name. Omit to list every server with resources.\");\nconst CURSOR = stringProperty(\"Opaque cursor from a previous call with the same server; omit for the first page.\");\nconst LIST_PARAMETERS = {\n\ttype: \"object\",\n\tproperties: { server: SERVER_FILTER, cursor: CURSOR },\n\tadditionalProperties: false,\n};\nconst READ_PARAMETERS = {\n\ttype: \"object\",\n\tproperties: {\n\t\tserver: stringProperty(\n\t\t\t\"MCP server name exactly as configured. Must match the 'server' field returned by list_mcp_resources.\",\n\t\t),\n\t\turi: stringProperty(\"Resource URI to read. Must be one of the URIs returned by list_mcp_resources.\"),\n\t},\n\trequired: [\"server\", \"uri\"],\n\tadditionalProperties: false,\n};\n\nconst optionalString = { type: \"string\" };\nconst LISTING_ERRORS = {\n\ttype: \"array\",\n\tdescription: \"Servers that could not be listed\",\n\titems: {\n\t\ttype: \"object\",\n\t\tproperties: { server: { type: \"string\" }, error: { type: \"string\" } },\n\t\trequired: [\"server\", \"error\"],\n\t},\n};\nconst LIST_OUTPUT_SCHEMA = {\n\ttype: \"object\",\n\tproperties: {\n\t\tserver: optionalString,\n\t\tresources: {\n\t\t\ttype: \"array\",\n\t\t\titems: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tserver: { type: \"string\" },\n\t\t\t\t\turi: { type: \"string\" },\n\t\t\t\t\tname: { type: \"string\" },\n\t\t\t\t\ttitle: optionalString,\n\t\t\t\t\tdescription: optionalString,\n\t\t\t\t\tmimeType: optionalString,\n\t\t\t\t\tsize: { type: \"number\" },\n\t\t\t\t},\n\t\t\t\trequired: [\"server\", \"uri\", \"name\"],\n\t\t\t},\n\t\t},\n\t\tnextCursor: optionalString,\n\t\terrors: LISTING_ERRORS,\n\t},\n\trequired: [\"resources\"],\n};\nconst LIST_TEMPLATES_OUTPUT_SCHEMA = {\n\ttype: \"object\",\n\tproperties: {\n\t\tserver: optionalString,\n\t\tresourceTemplates: {\n\t\t\ttype: \"array\",\n\t\t\titems: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tserver: { type: \"string\" },\n\t\t\t\t\turiTemplate: { type: \"string\", description: \"RFC 6570 URI template\" },\n\t\t\t\t\tname: { type: \"string\" },\n\t\t\t\t\ttitle: optionalString,\n\t\t\t\t\tdescription: optionalString,\n\t\t\t\t\tmimeType: optionalString,\n\t\t\t\t},\n\t\t\t\trequired: [\"server\", \"uriTemplate\", \"name\"],\n\t\t\t},\n\t\t},\n\t\tnextCursor: optionalString,\n\t\terrors: LISTING_ERRORS,\n\t},\n\trequired: [\"resourceTemplates\"],\n};\nconst READ_OUTPUT_SCHEMA = {\n\ttype: \"object\",\n\tproperties: {\n\t\tserver: { type: \"string\" },\n\t\turi: { type: \"string\" },\n\t\tcontents: {\n\t\t\ttype: \"array\",\n\t\t\titems: {\n\t\t\t\tanyOf: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: { uri: { type: \"string\" }, mimeType: optionalString, text: { type: \"string\" } },\n\t\t\t\t\t\trequired: [\"uri\", \"text\"],\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\turi: { type: \"string\" },\n\t\t\t\t\t\t\tmimeType: optionalString,\n\t\t\t\t\t\t\tblob: { type: \"string\", description: \"base64\" },\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"uri\", \"blob\"],\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t},\n\t},\n\trequired: [\"server\", \"uri\", \"contents\"],\n};\n\nfunction stringArgument(params: unknown, key: string): string | undefined {\n\tconst value = (params as Record<string, unknown> | undefined)?.[key];\n\tif (value === undefined || value === null) return undefined;\n\tif (typeof value !== \"string\") throw new Error(`${key} must be a string`);\n\treturn value.trim() || undefined;\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nasync function jsonResult(\n\ttool: string,\n\tserver: string | undefined,\n\tpayload: Record<string, unknown>,\n): Promise<{ content: (TextContent | ImageContent)[]; details: McpToolDetails; structuredContent: JsonValue }> {\n\tconst { content, fullOutputPath } = await limitMcpContent([{ type: \"text\", text: JSON.stringify(payload) }]);\n\treturn {\n\t\tcontent,\n\t\tdetails: { server: server ?? \"\", tool, ...(fullOutputPath ? { fullOutputPath } : {}) },\n\t\tstructuredContent: payload as unknown as JsonValue,\n\t};\n}\n\n/**\n * The three resource tools. `servers` returns the servers whose resources they reach, at call time.\n */\nexport function createMcpResourceToolDefinitions(options: {\n\texposure: McpExposure;\n\tservers: () => readonly McpResourceServer[];\n}): ToolDefinition<TSchema, McpToolDetails>[] {\n\tconst readOnly: ToolAnnotations = { readOnlyHint: true };\n\n\tconst findServer = (name: string): McpResourceServer => {\n\t\tconst servers = options.servers();\n\t\tconst server = servers.find((candidate) => candidate.name === name);\n\t\tif (server) return server;\n\t\tconst available = servers.map((candidate) => candidate.name).join(\", \");\n\t\tthrow new Error(\n\t\t\t`MCP server \"${name}\" has no resources${available ? `. Servers with resources: ${available}` : \"\"}`,\n\t\t);\n\t};\n\n\t/** One page of one server, or every page of every server. */\n\tconst list = async <T extends { _meta?: unknown }>(\n\t\tparams: unknown,\n\t\tsignal: AbortSignal | undefined,\n\t\tkey: \"resources\" | \"resourceTemplates\",\n\t\tpage: (\n\t\t\tserver: McpResourceServer,\n\t\t\tcursor: string | undefined,\n\t\t\toptions: McpRequestOptions,\n\t\t) => Promise<{\n\t\t\titems: T[];\n\t\t\tnextCursor?: string;\n\t\t}>,\n\t\tall: (server: McpResourceServer, options: McpRequestOptions) => Promise<T[]>,\n\t): Promise<Record<string, unknown>> => {\n\t\tconst serverName = stringArgument(params, \"server\");\n\t\tconst cursor = stringArgument(params, \"cursor\");\n\t\tconst visible = (item: T) => !isMcpAppResource(item as { uri?: string; uriTemplate?: string; mimeType?: string });\n\t\tif (serverName) {\n\t\t\tconst server = findServer(serverName);\n\t\t\tconst result = await page(server, cursor, { signal, timeoutMs: server.timeoutMs });\n\t\t\treturn {\n\t\t\t\tserver: server.name,\n\t\t\t\t[key]: result.items.filter(visible).map((item) => listed(server.name, item)),\n\t\t\t\t...(result.nextCursor === undefined ? {} : { nextCursor: result.nextCursor }),\n\t\t\t};\n\t\t}\n\t\tif (cursor) throw new Error(\"cursor can only be used when a server is specified\");\n\t\tconst servers = [...options.servers()].sort((a, b) => a.name.localeCompare(b.name));\n\t\tconst results = await Promise.allSettled(\n\t\t\tservers.map((server) => all(server, { signal, timeoutMs: server.timeoutMs })),\n\t\t);\n\t\tconst items: Record<string, unknown>[] = [];\n\t\tconst errors: { server: string; error: string }[] = [];\n\t\tresults.forEach((result, index) => {\n\t\t\tconst server = servers[index].name;\n\t\t\tif (result.status === \"fulfilled\")\n\t\t\t\titems.push(...result.value.filter(visible).map((item) => listed(server, item)));\n\t\t\telse errors.push({ server, error: errorMessage(result.reason) });\n\t\t});\n\t\treturn { [key]: items, ...(errors.length > 0 ? { errors } : {}) };\n\t};\n\n\tconst listResources: ToolDefinition<TSchema, McpToolDetails> = {\n\t\tname: LIST_MCP_RESOURCES_TOOL,\n\t\tlabel: LIST_MCP_RESOURCES_TOOL,\n\t\tdescription:\n\t\t\t\"Lists resources provided by MCP servers. Resources allow servers to share data that provides context to language models, such as files, database schemas, or application-specific information. Prefer resources over web search when possible.\",\n\t\tparameters: LIST_PARAMETERS as unknown as TSchema,\n\t\toutputSchema: LIST_OUTPUT_SCHEMA as unknown as TSchema,\n\t\texposure: toToolExposure(options.exposure),\n\t\tannotations: readOnly,\n\t\tasync execute(_toolCallId, params, signal) {\n\t\t\tconst payload = await list(\n\t\t\t\tparams,\n\t\t\t\tsignal,\n\t\t\t\t\"resources\",\n\t\t\t\tasync (server, cursor, requestOptions) => {\n\t\t\t\t\tconst result = await server.resourcesPage(cursor, requestOptions);\n\t\t\t\t\treturn { items: result.resources, nextCursor: result.nextCursor };\n\t\t\t\t},\n\t\t\t\t(server, requestOptions) => server.allResources(requestOptions),\n\t\t\t);\n\t\t\treturn jsonResult(LIST_MCP_RESOURCES_TOOL, stringArgument(params, \"server\"), payload);\n\t\t},\n\t};\n\n\tconst listTemplates: ToolDefinition<TSchema, McpToolDetails> = {\n\t\tname: LIST_MCP_RESOURCE_TEMPLATES_TOOL,\n\t\tlabel: LIST_MCP_RESOURCE_TEMPLATES_TOOL,\n\t\tdescription:\n\t\t\t\"Lists resource templates provided by MCP servers. Parameterized resource templates allow servers to share data that takes parameters and provides context to language models, such as files, database schemas, or application-specific information. Prefer resource templates over web search when possible.\",\n\t\tparameters: LIST_PARAMETERS as unknown as TSchema,\n\t\toutputSchema: LIST_TEMPLATES_OUTPUT_SCHEMA as unknown as TSchema,\n\t\texposure: toToolExposure(options.exposure),\n\t\tannotations: readOnly,\n\t\tasync execute(_toolCallId, params, signal) {\n\t\t\tconst payload = await list(\n\t\t\t\tparams,\n\t\t\t\tsignal,\n\t\t\t\t\"resourceTemplates\",\n\t\t\t\tasync (server, cursor, requestOptions) => {\n\t\t\t\t\tconst result = await server.resourceTemplatesPage(cursor, requestOptions);\n\t\t\t\t\treturn { items: result.resourceTemplates, nextCursor: result.nextCursor };\n\t\t\t\t},\n\t\t\t\t(server, requestOptions) => server.allResourceTemplates(requestOptions),\n\t\t\t);\n\t\t\treturn jsonResult(LIST_MCP_RESOURCE_TEMPLATES_TOOL, stringArgument(params, \"server\"), payload);\n\t\t},\n\t};\n\n\tconst readResource: ToolDefinition<TSchema, McpToolDetails> = {\n\t\tname: READ_MCP_RESOURCE_TOOL,\n\t\tlabel: READ_MCP_RESOURCE_TOOL,\n\t\tdescription: \"Read a specific resource from an MCP server given the server name and resource URI.\",\n\t\tparameters: READ_PARAMETERS as unknown as TSchema,\n\t\toutputSchema: READ_OUTPUT_SCHEMA as unknown as TSchema,\n\t\texposure: toToolExposure(options.exposure),\n\t\tannotations: readOnly,\n\t\tasync execute(_toolCallId, params, signal) {\n\t\t\tconst serverName = stringArgument(params, \"server\");\n\t\t\tconst uri = stringArgument(params, \"uri\");\n\t\t\tif (!serverName) throw new Error(\"server must be provided\");\n\t\t\tif (!uri) throw new Error(\"uri must be provided\");\n\t\t\tconst server = findServer(serverName);\n\t\t\tconst result = await server.readResource(uri, { signal, timeoutMs: server.timeoutMs });\n\t\t\t// Several contents (for example a directory) are labeled with their URIs.\n\t\t\tconst blocks: ContentBlock[] = result.contents.flatMap((contents) => [\n\t\t\t\t...(result.contents.length > 1 ? [{ type: \"text\" as const, text: `${contents.uri}:` }] : []),\n\t\t\t\t{ type: \"resource\" as const, resource: contents },\n\t\t\t]);\n\t\t\tconst converted = await toModelContent(server.name, blocks);\n\t\t\tconst { content, fullOutputPath } = await limitMcpContent(\n\t\t\t\tconverted.length > 0 ? converted : [{ type: \"text\", text: `Resource ${uri} is empty.` }],\n\t\t\t);\n\t\t\tconst contents = result.contents.map(({ _meta: _ignored, ...rest }) => rest);\n\t\t\treturn {\n\t\t\t\tcontent,\n\t\t\t\tdetails: {\n\t\t\t\t\tserver: server.name,\n\t\t\t\t\ttool: READ_MCP_RESOURCE_TOOL,\n\t\t\t\t\t...(fullOutputPath ? { fullOutputPath } : {}),\n\t\t\t\t},\n\t\t\t\tstructuredContent: { server: server.name, uri, contents } as unknown as JsonValue,\n\t\t\t};\n\t\t},\n\t};\n\n\treturn [listResources, listTemplates, readResource];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"resources.js","sourceRoot":"","sources":["../../../src/extensions/mcp/resources.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAcH,OAAO,EACN,gCAAgC,EAChC,uBAAuB,EACvB,sBAAsB,GACtB,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EAAE,eAAe,EAAuB,cAAc,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAElG,OAAO,EAAE,gCAAgC,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,CAAC;AAa7F,0EAA0E;AAC1E,MAAM,UAAU,gBAAgB,CAAC,IAA+D;IAC/F,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,IAAI,IAAI,CAAC,WAAW,IAAI,EAAE,CAAC;IAC/C,OAAO,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,g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ources`,\n * `list_mcp_resource_templates`, and `read_mcp_resource`. They take a `server` argument and cover\n * every connected server with resources, so models trained on those tools use them unchanged.\n *\n * Listings are JSON, as in Codex: `{ server?, resources: [{ server, ...resource }], nextCursor? }`.\n * With a `server`, one page is listed and `cursor` continues it; without, every page of every server.\n * MCP App resources (`ui://` URIs and `profile=mcp-app` HTML) are left out, since they are user\n * interfaces for hosts that render them, and so are icons. Read resources become text and images for\n * the model; binary resources are saved to temp files. Scripts get the JSON payloads.\n */\n\nimport type { ImageContent, JsonValue, TextContent } from \"@earendil-works/pi-ai\";\nimport type {\n\tContentBlock,\n\tListResourcesResult,\n\tListResourceTemplatesResult,\n\tMcpRequestOptions,\n\tReadResourceResult,\n\tResource,\n\tResourceTemplate,\n} from \"@earendil-works/pi-mcp\";\nimport type { TSchema } from \"typebox\";\nimport type { ToolAnnotations, ToolDefinition } from \"../../core/extensions/types.ts\";\nimport {\n\tLIST_MCP_RESOURCE_TEMPLATES_TOOL,\n\tLIST_MCP_RESOURCES_TOOL,\n\tREAD_MCP_RESOURCE_TOOL,\n} from \"../../core/mcp-servers.ts\";\nimport type { McpExposure } from \"./config.ts\";\nimport { limitMcpContent, type McpToolDetails, toModelContent, toToolExposure } from \"./tools.ts\";\n\nexport { LIST_MCP_RESOURCE_TEMPLATES_TOOL, LIST_MCP_RESOURCES_TOOL, READ_MCP_RESOURCE_TOOL };\n\n/** A connected server that offers resources. */\nexport interface McpResourceServer {\n\tname: string;\n\ttimeoutMs: number;\n\tresourcesPage(cursor: string | undefined, options: McpRequestOptions): Promise<ListResourcesResult>;\n\tresourceTemplatesPage(cursor: string | undefined, options: McpRequestOptions): Promise<ListResourceTemplatesResult>;\n\tallResources(options: McpRequestOptions): Promise<Resource[]>;\n\tallResourceTemplates(options: McpRequestOptions): Promise<ResourceTemplate[]>;\n\treadResource(uri: string, options: McpRequestOptions): Promise<ReadResourceResult>;\n}\n\n/** MCP App user interfaces, which only hosts that render them can use. */\nexport function isMcpAppResource(item: { uri?: string; uriTemplate?: string; mimeType?: string }): boolean {\n\tconst uri = item.uri ?? item.uriTemplate ?? \"\";\n\treturn uri.startsWith(\"ui://\") || /;\\s*profile\\s*=\\s*\"?mcp-app\"?/i.test(item.mimeType ?? \"\");\n}\n\n/** A listed resource or template without `_meta` and icons, tagged with its server. */\nfunction listed<T extends { _meta?: unknown }>(server: string, item: T): Record<string, unknown> {\n\tconst { _meta, icons: _icons, ...rest } = item as T & { icons?: unknown };\n\treturn { server, ...rest };\n}\n\nconst stringProperty = (description: string) => ({ type: \"string\", description });\nconst SERVER_FILTER = stringProperty(\"MCP server name. Omit to list every server with resources.\");\nconst CURSOR = stringProperty(\"Opaque cursor from a previous call with the same server; omit for the first page.\");\nconst LIST_PARAMETERS = {\n\ttype: \"object\",\n\tproperties: { server: SERVER_FILTER, cursor: CURSOR },\n\tadditionalProperties: false,\n};\nconst READ_PARAMETERS = {\n\ttype: \"object\",\n\tproperties: {\n\t\tserver: stringProperty(\n\t\t\t\"MCP server name exactly as configured. Must match the 'server' field returned by list_mcp_resources.\",\n\t\t),\n\t\turi: stringProperty(\"Resource URI to read. Must be one of the URIs returned by list_mcp_resources.\"),\n\t},\n\trequired: [\"server\", \"uri\"],\n\tadditionalProperties: false,\n};\n\nconst optionalString = { type: \"string\" };\nconst LISTING_ERRORS = {\n\ttype: \"array\",\n\tdescription: \"Servers that could not be listed\",\n\titems: {\n\t\ttype: \"object\",\n\t\tproperties: { server: { type: \"string\" }, error: { type: \"string\" } },\n\t\trequired: [\"server\", \"error\"],\n\t},\n};\nconst LIST_OUTPUT_SCHEMA = {\n\ttype: \"object\",\n\tproperties: {\n\t\tserver: optionalString,\n\t\tresources: {\n\t\t\ttype: \"array\",\n\t\t\titems: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tserver: { type: \"string\" },\n\t\t\t\t\turi: { type: \"string\" },\n\t\t\t\t\tname: { type: \"string\" },\n\t\t\t\t\ttitle: optionalString,\n\t\t\t\t\tdescription: optionalString,\n\t\t\t\t\tmimeType: optionalString,\n\t\t\t\t\tsize: { type: \"number\" },\n\t\t\t\t},\n\t\t\t\trequired: [\"server\", \"uri\", \"name\"],\n\t\t\t},\n\t\t},\n\t\tnextCursor: optionalString,\n\t\terrors: LISTING_ERRORS,\n\t},\n\trequired: [\"resources\"],\n};\nconst LIST_TEMPLATES_OUTPUT_SCHEMA = {\n\ttype: \"object\",\n\tproperties: {\n\t\tserver: optionalString,\n\t\tresourceTemplates: {\n\t\t\ttype: \"array\",\n\t\t\titems: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tserver: { type: \"string\" },\n\t\t\t\t\turiTemplate: { type: \"string\", description: \"RFC 6570 URI template\" },\n\t\t\t\t\tname: { type: \"string\" },\n\t\t\t\t\ttitle: optionalString,\n\t\t\t\t\tdescription: optionalString,\n\t\t\t\t\tmimeType: optionalString,\n\t\t\t\t},\n\t\t\t\trequired: [\"server\", \"uriTemplate\", \"name\"],\n\t\t\t},\n\t\t},\n\t\tnextCursor: optionalString,\n\t\terrors: LISTING_ERRORS,\n\t},\n\trequired: [\"resourceTemplates\"],\n};\nconst READ_OUTPUT_SCHEMA = {\n\ttype: \"object\",\n\tproperties: {\n\t\tserver: { type: \"string\" },\n\t\turi: { type: \"string\" },\n\t\tcontents: {\n\t\t\ttype: \"array\",\n\t\t\titems: {\n\t\t\t\tanyOf: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: { uri: { type: \"string\" }, mimeType: optionalString, text: { type: \"string\" } },\n\t\t\t\t\t\trequired: [\"uri\", \"text\"],\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\turi: { type: \"string\" },\n\t\t\t\t\t\t\tmimeType: optionalString,\n\t\t\t\t\t\t\tblob: { type: \"string\", description: \"base64\" },\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"uri\", \"blob\"],\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t},\n\t},\n\trequired: [\"server\", \"uri\", \"contents\"],\n};\n\nfunction stringArgument(params: unknown, key: string): string | undefined {\n\tconst value = (params as Record<string, unknown> | undefined)?.[key];\n\tif (value === undefined || value === null) return undefined;\n\tif (typeof value !== \"string\") throw new Error(`${key} must be a string`);\n\treturn value.trim() || undefined;\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nasync function jsonResult(\n\ttool: string,\n\tserver: string | undefined,\n\tpayload: Record<string, unknown>,\n): Promise<{ content: (TextContent | ImageContent)[]; details: McpToolDetails; structuredContent: JsonValue }> {\n\tconst { content, fullOutputPath } = await limitMcpContent([{ type: \"text\", text: JSON.stringify(payload) }]);\n\treturn {\n\t\tcontent,\n\t\tdetails: { server: server ?? \"\", tool, ...(fullOutputPath ? { fullOutputPath } : {}) },\n\t\tstructuredContent: payload as unknown as JsonValue,\n\t};\n}\n\n/**\n * The three resource tools. `servers` returns the servers whose resources they reach, at call time.\n */\nexport function createMcpResourceToolDefinitions(options: {\n\texposure: McpExposure;\n\tservers: () => readonly McpResourceServer[];\n}): ToolDefinition<TSchema, McpToolDetails>[] {\n\tconst readOnly: ToolAnnotations = { readOnlyHint: true };\n\n\tconst findServer = (name: string): McpResourceServer => {\n\t\tconst servers = options.servers();\n\t\tconst server = servers.find((candidate) => candidate.name === name);\n\t\tif (server) return server;\n\t\tconst available = servers.map((candidate) => candidate.name).join(\", \");\n\t\tthrow new Error(\n\t\t\t`MCP server \"${name}\" has no resources${available ? `. Servers with resources: ${available}` : \"\"}`,\n\t\t);\n\t};\n\n\t/** One page of one server, or every page of every server. */\n\tconst list = async <T extends { _meta?: unknown }>(\n\t\tparams: unknown,\n\t\tsignal: AbortSignal | undefined,\n\t\tkey: \"resources\" | \"resourceTemplates\",\n\t\tpage: (\n\t\t\tserver: McpResourceServer,\n\t\t\tcursor: string | undefined,\n\t\t\toptions: McpRequestOptions,\n\t\t) => Promise<{\n\t\t\titems: T[];\n\t\t\tnextCursor?: string;\n\t\t}>,\n\t\tall: (server: McpResourceServer, options: McpRequestOptions) => Promise<T[]>,\n\t): Promise<Record<string, unknown>> => {\n\t\tconst serverName = stringArgument(params, \"server\");\n\t\tconst cursor = stringArgument(params, \"cursor\");\n\t\tconst visible = (item: T) => !isMcpAppResource(item as { uri?: string; uriTemplate?: string; mimeType?: string });\n\t\tif (serverName) {\n\t\t\tconst server = findServer(serverName);\n\t\t\tconst result = await page(server, cursor, { signal, timeoutMs: server.timeoutMs });\n\t\t\treturn {\n\t\t\t\tserver: server.name,\n\t\t\t\t[key]: result.items.filter(visible).map((item) => listed(server.name, item)),\n\t\t\t\t...(result.nextCursor === undefined ? {} : { nextCursor: result.nextCursor }),\n\t\t\t};\n\t\t}\n\t\tif (cursor) throw new Error(\"cursor can only be used when a server is specified\");\n\t\tconst servers = [...options.servers()].sort((a, b) => a.name.localeCompare(b.name));\n\t\tconst results = await Promise.allSettled(\n\t\t\tservers.map((server) => all(server, { signal, timeoutMs: server.timeoutMs })),\n\t\t);\n\t\tconst items: Record<string, unknown>[] = [];\n\t\tconst errors: { server: string; error: string }[] = [];\n\t\tresults.forEach((result, index) => {\n\t\t\tconst server = servers[index].name;\n\t\t\tif (result.status === \"fulfilled\")\n\t\t\t\titems.push(...result.value.filter(visible).map((item) => listed(server, item)));\n\t\t\telse errors.push({ server, error: errorMessage(result.reason) });\n\t\t});\n\t\treturn { [key]: items, ...(errors.length > 0 ? { errors } : {}) };\n\t};\n\n\tconst listResources: ToolDefinition<TSchema, McpToolDetails> = {\n\t\tname: LIST_MCP_RESOURCES_TOOL,\n\t\tlabel: LIST_MCP_RESOURCES_TOOL,\n\t\tdescription:\n\t\t\t\"Lists resources provided by MCP servers. Resources allow servers to share data that provides context to language models, such as files, database schemas, or application-specific information. Prefer resources over web search when possible.\",\n\t\tparameters: LIST_PARAMETERS as unknown as TSchema,\n\t\toutputSchema: LIST_OUTPUT_SCHEMA as unknown as TSchema,\n\t\texposure: toToolExposure(options.exposure),\n\t\tannotations: readOnly,\n\t\tasync execute(_toolCallId, params, signal) {\n\t\t\tconst payload = await list(\n\t\t\t\tparams,\n\t\t\t\tsignal,\n\t\t\t\t\"resources\",\n\t\t\t\tasync (server, cursor, requestOptions) => {\n\t\t\t\t\tconst result = await server.resourcesPage(cursor, requestOptions);\n\t\t\t\t\treturn { items: result.resources, nextCursor: result.nextCursor };\n\t\t\t\t},\n\t\t\t\t(server, requestOptions) => server.allResources(requestOptions),\n\t\t\t);\n\t\t\treturn jsonResult(LIST_MCP_RESOURCES_TOOL, stringArgument(params, \"server\"), payload);\n\t\t},\n\t};\n\n\tconst listTemplates: ToolDefinition<TSchema, McpToolDetails> = {\n\t\tname: LIST_MCP_RESOURCE_TEMPLATES_TOOL,\n\t\tlabel: LIST_MCP_RESOURCE_TEMPLATES_TOOL,\n\t\tdescription:\n\t\t\t\"Lists resource templates provided by MCP servers. Parameterized resource templates allow servers to share data that takes parameters and provides context to language models, such as files, database schemas, or application-specific information. Prefer resource templates over web search when possible.\",\n\t\tparameters: LIST_PARAMETERS as unknown as TSchema,\n\t\toutputSchema: LIST_TEMPLATES_OUTPUT_SCHEMA as unknown as TSchema,\n\t\texposure: toToolExposure(options.exposure),\n\t\tannotations: readOnly,\n\t\tasync execute(_toolCallId, params, signal) {\n\t\t\tconst payload = await list(\n\t\t\t\tparams,\n\t\t\t\tsignal,\n\t\t\t\t\"resourceTemplates\",\n\t\t\t\tasync (server, cursor, requestOptions) => {\n\t\t\t\t\tconst result = await server.resourceTemplatesPage(cursor, requestOptions);\n\t\t\t\t\treturn { items: result.resourceTemplates, nextCursor: result.nextCursor };\n\t\t\t\t},\n\t\t\t\t(server, requestOptions) => server.allResourceTemplates(requestOptions),\n\t\t\t);\n\t\t\treturn jsonResult(LIST_MCP_RESOURCE_TEMPLATES_TOOL, stringArgument(params, \"server\"), payload);\n\t\t},\n\t};\n\n\tconst readResource: ToolDefinition<TSchema, McpToolDetails> = {\n\t\tname: READ_MCP_RESOURCE_TOOL,\n\t\tlabel: READ_MCP_RESOURCE_TOOL,\n\t\tdescription: \"Read a specific resource from an MCP server given the server name and resource URI.\",\n\t\tparameters: READ_PARAMETERS as unknown as TSchema,\n\t\toutputSchema: READ_OUTPUT_SCHEMA as unknown as TSchema,\n\t\texposure: toToolExposure(options.exposure),\n\t\tannotations: readOnly,\n\t\tasync execute(_toolCallId, params, signal) {\n\t\t\tconst serverName = stringArgument(params, \"server\");\n\t\t\tconst uri = stringArgument(params, \"uri\");\n\t\t\tif (!serverName) throw new Error(\"server must be provided\");\n\t\t\tif (!uri) throw new Error(\"uri must be provided\");\n\t\t\tconst server = findServer(serverName);\n\t\t\tconst result = await server.readResource(uri, { signal, timeoutMs: server.timeoutMs });\n\t\t\t// Several contents (for example a directory) are labeled with their URIs.\n\t\t\tconst blocks: ContentBlock[] = result.contents.flatMap((contents) => [\n\t\t\t\t...(result.contents.length > 1 ? [{ type: \"text\" as const, text: `${contents.uri}:` }] : []),\n\t\t\t\t{ type: \"resource\" as const, resource: contents },\n\t\t\t]);\n\t\t\tconst converted = await toModelContent(server.name, blocks);\n\t\t\tconst { content, fullOutputPath } = await limitMcpContent(\n\t\t\t\tconverted.length > 0 ? converted : [{ type: \"text\", text: `Resource ${uri} is empty.` }],\n\t\t\t);\n\t\t\tconst contents = result.contents.map(({ _meta: _ignored, ...rest }) => rest);\n\t\t\treturn {\n\t\t\t\tcontent,\n\t\t\t\tdetails: {\n\t\t\t\t\tserver: server.name,\n\t\t\t\t\ttool: READ_MCP_RESOURCE_TOOL,\n\t\t\t\t\t...(fullOutputPath ? { fullOutputPath } : {}),\n\t\t\t\t},\n\t\t\t\tstructuredContent: { server: server.name, uri, contents } as unknown as JsonValue,\n\t\t\t};\n\t\t},\n\t};\n\n\treturn [listResources, listTemplates, readResource];\n}\n"]}
|
|
@@ -38,7 +38,8 @@ export declare class McpServerConnection implements McpToolCaller, McpResourceSe
|
|
|
38
38
|
challenge: OAuthChallenge | undefined;
|
|
39
39
|
private client;
|
|
40
40
|
private opening;
|
|
41
|
-
|
|
41
|
+
/** Aborted by `close()`; cancels a connect in progress, including the wait between retries. */
|
|
42
|
+
private readonly shutdown;
|
|
42
43
|
/** Stderr of the last stdio server that failed to connect. */
|
|
43
44
|
private stderrTail;
|
|
44
45
|
private readonly cwd;
|
|
@@ -61,6 +62,7 @@ export declare class McpServerConnection implements McpToolCaller, McpResourceSe
|
|
|
61
62
|
log?: McpServerLog;
|
|
62
63
|
});
|
|
63
64
|
get name(): string;
|
|
65
|
+
private get closed();
|
|
64
66
|
get timeoutMs(): number;
|
|
65
67
|
/** Server URL when the server authenticates with OAuth. */
|
|
66
68
|
get oauthUrl(): string | undefined;
|
|
@@ -93,6 +95,7 @@ export declare class McpServerConnection implements McpToolCaller, McpResourceSe
|
|
|
93
95
|
private handleClientClose;
|
|
94
96
|
private refreshTools;
|
|
95
97
|
private refreshResources;
|
|
98
|
+
/** Resolves once no transport of this server is open, including one that was still connecting. */
|
|
96
99
|
close(): Promise<void>;
|
|
97
100
|
}
|
|
98
101
|
//# sourceMappingURL=runtime.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../../src/extensions/mcp/runtime.ts"],"names":[],"mappings":"AAAA;;;;GAIG;
|
|
1
|
+
{"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../../src/extensions/mcp/runtime.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAMH,OAAO,EACN,KAAK,YAAY,EACjB,KAAK,cAAc,EAEnB,KAAK,mBAAmB,EACxB,KAAK,2BAA2B,EAEhC,SAAS,EAGT,KAAK,iBAAiB,EAEtB,KAAK,IAAI,IAAI,OAAO,EACpB,KAAK,YAAY,EACjB,KAAK,kBAAkB,EACvB,KAAK,QAAQ,EACb,KAAK,gBAAgB,EAGrB,MAAM,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
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
8
9
|
import { pathToFileURL } from "node:url";
|
|
9
10
|
import { JSON_RPC_ERROR_CODES, McpAuthRequiredError, McpClient, McpError, McpHttpError, McpSessionExpiredError, StdioTransport, StreamableHttpTransport, } from "@earendil-works/pi-mcp";
|
|
10
11
|
import { McpOAuthAuthorizationRequiredError } from "@earendil-works/pi-mcp/oauth";
|
|
@@ -116,7 +117,8 @@ export class McpServerConnection {
|
|
|
116
117
|
challenge;
|
|
117
118
|
client;
|
|
118
119
|
opening;
|
|
119
|
-
|
|
120
|
+
/** Aborted by `close()`; cancels a connect in progress, including the wait between retries. */
|
|
121
|
+
shutdown = new AbortController();
|
|
120
122
|
/** Stderr of the last stdio server that failed to connect. */
|
|
121
123
|
stderrTail;
|
|
122
124
|
cwd;
|
|
@@ -151,6 +153,9 @@ export class McpServerConnection {
|
|
|
151
153
|
get name() {
|
|
152
154
|
return this.entry.name;
|
|
153
155
|
}
|
|
156
|
+
get closed() {
|
|
157
|
+
return this.shutdown.signal.aborted;
|
|
158
|
+
}
|
|
154
159
|
get timeoutMs() {
|
|
155
160
|
return (this.entry.config.timeout ?? DEFAULT_TIMEOUT_SECONDS) * 1000;
|
|
156
161
|
}
|
|
@@ -281,7 +286,7 @@ export class McpServerConnection {
|
|
|
281
286
|
if (this.closed || delay === undefined || !isTransientError(error)) {
|
|
282
287
|
throw this.connectFailed(error);
|
|
283
288
|
}
|
|
284
|
-
await
|
|
289
|
+
await sleep(delay, undefined, { signal: this.shutdown.signal }).catch(() => undefined);
|
|
285
290
|
if (this.closed)
|
|
286
291
|
throw this.connectFailed(error);
|
|
287
292
|
}
|
|
@@ -297,6 +302,14 @@ export class McpServerConnection {
|
|
|
297
302
|
const log = this.log;
|
|
298
303
|
if (log)
|
|
299
304
|
client.onNotification("notifications/message", (params) => log.write(this.entry.name, params));
|
|
305
|
+
// Closing the client fails its pending initialize or discovery requests and closes the transport.
|
|
306
|
+
// Memoized: a second `client.close()` returns before the first finished closing the transport.
|
|
307
|
+
let closing;
|
|
308
|
+
const closeClient = () => {
|
|
309
|
+
closing ??= client.close().catch(() => undefined);
|
|
310
|
+
return closing;
|
|
311
|
+
};
|
|
312
|
+
this.shutdown.signal.addEventListener("abort", closeClient, { once: true });
|
|
300
313
|
let transport;
|
|
301
314
|
try {
|
|
302
315
|
transport = this.createTransport(this.entry, this.cwd, this.authProvider);
|
|
@@ -332,12 +345,15 @@ export class McpServerConnection {
|
|
|
332
345
|
return client;
|
|
333
346
|
}
|
|
334
347
|
catch (error) {
|
|
335
|
-
await
|
|
348
|
+
await closeClient();
|
|
336
349
|
if (transport instanceof StdioTransport) {
|
|
337
350
|
this.stderrTail = transport.stderr.trim().slice(-STDERR_TAIL_CHARS) || undefined;
|
|
338
351
|
}
|
|
339
352
|
throw error;
|
|
340
353
|
}
|
|
354
|
+
finally {
|
|
355
|
+
this.shutdown.signal.removeEventListener("abort", closeClient);
|
|
356
|
+
}
|
|
341
357
|
}
|
|
342
358
|
connectFailed(error) {
|
|
343
359
|
if (this.needsSignIn(error) && !this.closed) {
|
|
@@ -381,13 +397,14 @@ export class McpServerConnection {
|
|
|
381
397
|
this.onTools(this);
|
|
382
398
|
this.changed();
|
|
383
399
|
}
|
|
400
|
+
/** Resolves once no transport of this server is open, including one that was still connecting. */
|
|
384
401
|
async close() {
|
|
385
|
-
this.
|
|
402
|
+
this.shutdown.abort();
|
|
386
403
|
this.state = "closed";
|
|
387
404
|
this.changed();
|
|
388
405
|
const client = this.client;
|
|
389
406
|
this.client = undefined;
|
|
390
|
-
await client?.close().catch(() => undefined);
|
|
407
|
+
await Promise.all([client?.close().catch(() => undefined), this.opening?.catch(() => undefined)]);
|
|
391
408
|
// A refresh the server already answered may have rotated the refresh token; exiting before the
|
|
392
409
|
// new tokens are saved would lose the grant.
|
|
393
410
|
await this.authProvider?.settled();
|