@ashx-j/lunr 0.2.23 → 0.2.24
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 +14 -1
- package/README.md +10 -10
- package/dist/builtin-extensions/ashxj-tui.d.ts.map +1 -1
- package/dist/builtin-extensions/ashxj-tui.js +2 -2
- package/dist/builtin-extensions/ashxj-tui.js.map +1 -1
- package/dist/builtin-extensions/lunr-plan-tools.d.ts +7 -7
- package/dist/builtin-extensions/lunr-plan-tools.d.ts.map +1 -1
- package/dist/builtin-extensions/lunr-plan-tools.js +12 -12
- package/dist/builtin-extensions/lunr-plan-tools.js.map +1 -1
- package/dist/builtin-extensions/pi-intercom/index.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-intercom/index.js +2 -0
- package/dist/builtin-extensions/pi-intercom/index.js.map +1 -1
- package/dist/builtin-extensions/pi-mcp-adapter/direct-tools.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-mcp-adapter/direct-tools.js +1 -0
- package/dist/builtin-extensions/pi-mcp-adapter/direct-tools.js.map +1 -1
- package/dist/builtin-extensions/pi-mcp-adapter/index.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-mcp-adapter/index.js +1 -1
- package/dist/builtin-extensions/pi-mcp-adapter/index.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/schemas.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/schemas.js +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/schemas.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.d.ts +4 -4
- package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.js +6 -4
- package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/intercom/intercom-bridge.d.ts +2 -0
- package/dist/builtin-extensions/pi-subagents/src/intercom/intercom-bridge.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/intercom/intercom-bridge.js +6 -3
- package/dist/builtin-extensions/pi-subagents/src/intercom/intercom-bridge.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.js +7 -2
- package/dist/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.d.ts +2 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.js +4 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.js +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-execution.d.ts +1 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-execution.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-execution.js +5 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-execution.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.js +3 -2
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js +19 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/child-tools.d.ts +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/child-tools.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/child-tools.js +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/child-tools.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/pi-args.d.ts +2 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/pi-args.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/pi-args.js +17 -15
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/pi-args.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/subagent-prompt-runtime.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/subagent-prompt-runtime.js +3 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/subagent-prompt-runtime.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/shared/child-spec.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/shared/child-spec.js +2 -2
- package/dist/builtin-extensions/pi-subagents/src/shared/child-spec.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/shared/types.d.ts +1 -0
- package/dist/builtin-extensions/pi-subagents/src/shared/types.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/shared/types.js.map +1 -1
- package/dist/core/agent-session.d.ts +1 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +5 -4
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/browser/schema.d.ts +1 -1
- package/dist/core/browser/schema.d.ts.map +1 -1
- package/dist/core/browser/schema.js +1 -1
- package/dist/core/browser/schema.js.map +1 -1
- package/dist/core/catalog-cache-scope.d.ts.map +1 -1
- package/dist/core/catalog-cache-scope.js +3 -1
- package/dist/core/catalog-cache-scope.js.map +1 -1
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +3 -2
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/permissions.d.ts +16 -23
- package/dist/core/permissions.d.ts.map +1 -1
- package/dist/core/permissions.js +66 -141
- package/dist/core/permissions.js.map +1 -1
- package/dist/core/plan-mode.d.ts +10 -12
- package/dist/core/plan-mode.d.ts.map +1 -1
- package/dist/core/plan-mode.js +16 -18
- package/dist/core/plan-mode.js.map +1 -1
- package/dist/core/runtime-bridges.d.ts.map +1 -1
- package/dist/core/runtime-bridges.js +2 -0
- package/dist/core/runtime-bridges.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +13 -6
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +9 -2
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-manager.d.ts +9 -1
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +40 -1
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +4 -4
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/subagent-permission-inherit.d.ts +6 -10
- package/dist/core/subagent-permission-inherit.d.ts.map +1 -1
- package/dist/core/subagent-permission-inherit.js +14 -14
- package/dist/core/subagent-permission-inherit.js.map +1 -1
- package/dist/core/system-prompt.d.ts +2 -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/gateway/adapters/discord.d.ts.map +1 -1
- package/dist/gateway/adapters/discord.js +1 -1
- package/dist/gateway/adapters/discord.js.map +1 -1
- package/dist/gateway/approval.d.ts +2 -6
- package/dist/gateway/approval.d.ts.map +1 -1
- package/dist/gateway/approval.js +3 -7
- package/dist/gateway/approval.js.map +1 -1
- package/dist/gateway/mobile-commands.d.ts.map +1 -1
- package/dist/gateway/mobile-commands.js +12 -11
- package/dist/gateway/mobile-commands.js.map +1 -1
- package/dist/gateway/router.d.ts.map +1 -1
- package/dist/gateway/router.js +1 -1
- package/dist/gateway/router.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +1 -2
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +4 -0
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +23 -3
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/thinking-tail.d.ts.map +1 -1
- package/dist/modes/interactive/components/thinking-tail.js +2 -2
- package/dist/modes/interactive/components/thinking-tail.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +1 -0
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +12 -2
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +1 -2
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +76 -90
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/node-runtime/{agent-session-services-GZVSOGYR.js → agent-session-services-IEF7LQWD.js} +8 -9
- package/dist/node-runtime/{builtin-extensions-QVCXNQT4.js → builtin-extensions-EBAWTH4M.js} +3 -3
- package/dist/node-runtime/{chunk-XLTL257W.js → chunk-2KIPT4HJ.js} +5 -1
- package/dist/node-runtime/{chunk-YHQ3NBB3.js → chunk-5Q3EHOHI.js} +17 -17
- package/dist/node-runtime/{chunk-TQGPP4SC.js → chunk-CDVHZOOK.js} +1 -1
- package/dist/node-runtime/{chunk-DQMGU675.js → chunk-DE2JB6J5.js} +20 -17
- package/dist/node-runtime/{chunk-YJMMG7C6.js → chunk-DSIKTUPW.js} +1 -1
- package/dist/node-runtime/{chunk-TVJUOJZJ.js → chunk-F4FLTQKV.js} +1 -1
- package/dist/node-runtime/{chunk-GMHJCCEN.js → chunk-FU6OODRZ.js} +4 -1
- package/dist/node-runtime/{chunk-OFKSVRV7.js → chunk-GYIXXQAO.js} +1 -1
- package/dist/node-runtime/{chunk-BX2RB477.js → chunk-HFVZUPFJ.js} +1 -1
- package/dist/node-runtime/{chunk-AZJHNQKQ.js → chunk-I54LGHWM.js} +1 -1
- package/dist/node-runtime/{chunk-DD5YWFSJ.js → chunk-IGV54Q5V.js} +2 -2
- package/dist/node-runtime/{chunk-RIR5EDDJ.js → chunk-K5AGHH57.js} +17 -12
- package/dist/node-runtime/{chunk-GS66LV4M.js → chunk-KJ6DWS3K.js} +4 -4
- package/dist/node-runtime/{chunk-LLUIPGDR.js → chunk-L3LX4SNR.js} +108 -75
- package/dist/node-runtime/{chunk-VSELYKWU.js → chunk-LWYIVUGV.js} +2 -1
- package/dist/node-runtime/{chunk-JHYKXIMM.js → chunk-MPKSOJBT.js} +1 -1
- package/dist/node-runtime/{chunk-W64JC4E7.js → chunk-OF7PWMG4.js} +2 -2
- package/dist/node-runtime/{chunk-CSUZVNYE.js → chunk-OVX6X377.js} +10 -6
- package/dist/node-runtime/{chunk-X3URCYCU.js → chunk-QM43FEAE.js} +14 -14
- package/dist/node-runtime/{chunk-QAZOULTU.js → chunk-RORY2HMJ.js} +39 -5
- package/dist/node-runtime/{chunk-EKVFP6YF.js → chunk-WHLRAGUQ.js} +13 -12
- package/dist/node-runtime/{chunk-HPUP7E4T.js → chunk-Y73WPE6S.js} +16 -16
- package/dist/node-runtime/{chunk-LFZDVKSP.js → chunk-YVI6L6LU.js} +5 -5
- package/dist/node-runtime/{chunk-5D7LC2ZQ.js → chunk-ZXSGTGJ6.js} +54 -85
- package/dist/node-runtime/cli-runtime.js +1 -1
- package/dist/node-runtime/{command-PDVTBRWA.js → command-7BG7VVTS.js} +3 -3
- package/dist/node-runtime/{commands-KAMO2T6P.js → commands-NZLSOHPE.js} +2 -2
- package/dist/node-runtime/{commands-XDCFGIGW.js → commands-QFDKNQTL.js} +7 -7
- package/dist/node-runtime/{direct-tool-executor-YAVOLDFY.js → direct-tool-executor-77GW4F5P.js} +3 -3
- package/dist/node-runtime/{export-html-KSOIMVPI.js → export-html-VM4J2MNR.js} +1 -1
- package/dist/node-runtime/{gateway-AYWM5DIO.js → gateway-TWR3N65G.js} +12 -12
- package/dist/node-runtime/index.js +16 -17
- package/dist/node-runtime/{init-X2LIUB2H.js → init-HS6NQXSK.js} +2 -2
- package/dist/node-runtime/{install-cli-3BO4MMQ6.js → install-cli-VAP6KBFN.js} +1 -1
- package/dist/node-runtime/{interactive-mode-4MFRKAHG.js → interactive-mode-6J5VZ2TT.js} +10 -11
- package/dist/node-runtime/{interactive-view-TUZHCQM3.js → interactive-view-NGFAMHPW.js} +2 -2
- package/dist/node-runtime/{lunr-browser-RYFIIVJN.js → lunr-browser-J5ZZYVGM.js} +1 -1
- package/dist/node-runtime/{lunr-cron-YWXEPZMQ.js → lunr-cron-CXOL37AL.js} +5 -5
- package/dist/node-runtime/main.js +14 -15
- package/dist/node-runtime/{mobile-commands-LVHDAUDP.js → mobile-commands-VTBM5DSZ.js} +4 -4
- package/dist/node-runtime/{model-runtime-PLQKAG4B.js → model-runtime-OO5HFLWE.js} +1 -1
- package/dist/node-runtime/{package-manager-cli-6GT3Z3CK.js → package-manager-cli-ZLW5DZXF.js} +3 -4
- package/dist/node-runtime/{pi-intercom-HBPK5HSJ.js → pi-intercom-QM53RLTS.js} +2 -0
- package/dist/node-runtime/{pi-mcp-adapter-E6WULBKF.js → pi-mcp-adapter-5UKBZP44.js} +7 -6
- package/dist/node-runtime/{pi-subagents-CDWK2AKY.js → pi-subagents-XPCLLKIM.js} +23 -13
- package/dist/node-runtime/{proxy-modes-OSQCWRBI.js → proxy-modes-LGEUYD7R.js} +3 -3
- package/dist/node-runtime/rpc-entry.js +14 -15
- package/dist/node-runtime/{runtime-bridges-3XUQ46XW.js → runtime-bridges-QYXUX2TG.js} +8 -1
- package/dist/node-runtime/{session-handoff-HC7R5E24.js → session-handoff-GWARVEWT.js} +2 -2
- package/dist/node-runtime/{session-manager-CFN4UFM2.js → session-manager-JB5J6XBN.js} +1 -1
- package/dist/node-runtime/{settings-manager-6VEMXRDL.js → settings-manager-WCQDUVQB.js} +7 -4
- package/dist/node-runtime/{setup-5SR2J35A.js → setup-YRBKH2LD.js} +2 -2
- package/dist/node-runtime/{subagent-executor-M5VWB3D3.js → subagent-executor-OTNISDQU.js} +40 -7
- package/dist/node-runtime/{update-cli-UVKJWRRJ.js → update-cli-VBR2777K.js} +1 -2
- package/dist/startup/interactive-view.d.ts.map +1 -1
- package/dist/startup/interactive-view.js +5 -1
- package/dist/startup/interactive-view.js.map +1 -1
- package/docs/browser.md +1 -1
- package/docs/features.md +15 -14
- package/docs/index.md +1 -1
- package/docs/keybindings.md +1 -1
- package/docs/providers.md +6 -2
- package/docs/quickstart.md +2 -2
- package/docs/settings.md +1 -1
- package/docs/usage.md +4 -4
- 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/plan-mode/README.md +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 +4 -4
- package/dist/node-runtime/chunk-LISUTZS3.js +0 -19
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"direct-tools.d.ts","sourceRoot":"","sources":["../../../src/builtin-extensions/pi-mcp-adapter/direct-tools.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAC5D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAOzD,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,SAAS,EACjB,KAAK,EAAE,aAAa,GAAG,IAAI,EAC3B,MAAM,EAAE,QAAQ,GAAG,MAAM,GAAG,OAAO,EACnC,WAAW,CAAC,EAAE,MAAM,EAAE,GACrB,cAAc,EAAE,CAoGlB;AAED,wBAAgB,qCAAqC,CACnD,MAAM,EAAE,SAAS,EACjB,KAAK,EAAE,aAAa,GAAG,IAAI,GAC1B,MAAM,EAAE,CAkBV;AAED,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,SAAS,EACjB,KAAK,EAAE,aAAa,GAAG,IAAI,EAC3B,WAAW,EAAE,cAAc,EAAE,GAC5B,MAAM,
|
|
1
|
+
{"version":3,"file":"direct-tools.d.ts","sourceRoot":"","sources":["../../../src/builtin-extensions/pi-mcp-adapter/direct-tools.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAC5D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAOzD,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,SAAS,EACjB,KAAK,EAAE,aAAa,GAAG,IAAI,EAC3B,MAAM,EAAE,QAAQ,GAAG,MAAM,GAAG,OAAO,EACnC,WAAW,CAAC,EAAE,MAAM,EAAE,GACrB,cAAc,EAAE,CAoGlB;AAED,wBAAgB,qCAAqC,CACnD,MAAM,EAAE,SAAS,EACjB,KAAK,EAAE,aAAa,GAAG,IAAI,GAC1B,MAAM,EAAE,CAkBV;AAED,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,SAAS,EACjB,KAAK,EAAE,aAAa,GAAG,IAAI,EAC3B,WAAW,EAAE,cAAc,EAAE,GAC5B,MAAM,CAuDR","sourcesContent":["// @ts-nocheck\nimport type { DirectToolSpec, McpConfig } from \"./types.ts\";\nimport type { MetadataCache } from \"./metadata-cache.ts\";\nimport { isServerCacheValid } from \"./metadata-cache.ts\";\nimport { formatToolName, isToolExcluded } from \"./types.ts\";\nimport { resourceNameToToolName } from \"./resource-tools.ts\";\n\nconst BUILTIN_NAMES = new Set([\"read\", \"bash\", \"edit\", \"write\", \"grep\", \"find\", \"ls\", \"mcp\"]);\n\nexport function resolveDirectTools(\n config: McpConfig,\n cache: MetadataCache | null,\n prefix: \"server\" | \"none\" | \"short\",\n envOverride?: string[],\n): DirectToolSpec[] {\n const specs: DirectToolSpec[] = [];\n if (!cache) return specs;\n\n const seenNames = new Set<string>();\n\n const envServers = new Set<string>();\n const envTools = new Map<string, Set<string>>();\n if (envOverride) {\n for (let item of envOverride) {\n item = item.replace(/\\/+$/, \"\");\n if (item.includes(\"/\")) {\n const [server, tool] = item.split(\"/\", 2);\n if (server && tool) {\n if (!envTools.has(server)) envTools.set(server, new Set());\n envTools.get(server)!.add(tool);\n } else if (server) {\n envServers.add(server);\n }\n } else if (item) {\n envServers.add(item);\n }\n }\n }\n\n const globalDirect = config.settings?.directTools;\n\n for (const [serverName, definition] of Object.entries(config.mcpServers)) {\n const serverCache = cache.servers[serverName];\n if (!serverCache || !isServerCacheValid(serverCache, definition)) continue;\n\n let toolFilter: true | string[] | false = false;\n\n if (envOverride) {\n if (envServers.has(serverName)) {\n toolFilter = true;\n } else if (envTools.has(serverName)) {\n toolFilter = [...envTools.get(serverName)!];\n }\n } else {\n if (definition.directTools !== undefined) {\n toolFilter = definition.directTools;\n } else if (globalDirect) {\n toolFilter = globalDirect;\n }\n }\n\n if (!toolFilter) continue;\n\n for (const tool of serverCache.tools ?? []) {\n if (toolFilter !== true && !toolFilter.includes(tool.name)) continue;\n if (isToolExcluded(tool.name, serverName, prefix, definition.excludeTools)) continue;\n const prefixedName = formatToolName(tool.name, serverName, prefix);\n if (BUILTIN_NAMES.has(prefixedName)) {\n console.warn(`MCP: skipping direct tool \"${prefixedName}\" (collides with builtin)`);\n continue;\n }\n if (seenNames.has(prefixedName)) {\n console.warn(`MCP: skipping duplicate direct tool \"${prefixedName}\" from \"${serverName}\"`);\n continue;\n }\n seenNames.add(prefixedName);\n specs.push({\n serverName,\n originalName: tool.name,\n prefixedName,\n description: tool.description ?? \"\",\n inputSchema: tool.inputSchema,\n uiResourceUri: tool.uiResourceUri,\n uiStreamMode: tool.uiStreamMode,\n });\n }\n\n if (definition.exposeResources !== false) {\n for (const resource of serverCache.resources ?? []) {\n const baseName = `get_${resourceNameToToolName(resource.name)}`;\n if (toolFilter !== true && !toolFilter.includes(baseName)) continue;\n if (isToolExcluded(baseName, serverName, prefix, definition.excludeTools)) continue;\n const prefixedName = formatToolName(baseName, serverName, prefix);\n if (BUILTIN_NAMES.has(prefixedName)) {\n console.warn(`MCP: skipping direct resource tool \"${prefixedName}\" (collides with builtin)`);\n continue;\n }\n if (seenNames.has(prefixedName)) {\n console.warn(`MCP: skipping duplicate direct resource tool \"${prefixedName}\" from \"${serverName}\"`);\n continue;\n }\n seenNames.add(prefixedName);\n specs.push({\n serverName,\n originalName: baseName,\n prefixedName,\n description: resource.description ?? `Read resource: ${resource.uri}`,\n resourceUri: resource.uri,\n });\n }\n }\n }\n\n return specs;\n}\n\nexport function getMissingConfiguredDirectToolServers(\n config: McpConfig,\n cache: MetadataCache | null,\n): string[] {\n const missing: string[] = [];\n const globalDirect = config.settings?.directTools;\n\n for (const [serverName, definition] of Object.entries(config.mcpServers)) {\n const hasDirectTools = definition.directTools !== undefined\n ? !!definition.directTools\n : !!globalDirect;\n\n if (!hasDirectTools) continue;\n\n const serverCache = cache?.servers?.[serverName];\n if (!serverCache || !isServerCacheValid(serverCache, definition)) {\n missing.push(serverName);\n }\n }\n\n return missing;\n}\n\nexport function buildProxyDescription(\n config: McpConfig,\n cache: MetadataCache | null,\n directSpecs: DirectToolSpec[],\n): string {\n const prefix = config.settings?.toolPrefix ?? \"server\";\n let desc = `MCP gateway - connect to MCP servers and call their tools. Non-MCP Pi tools should be called directly, not through mcp.\\n`;\n\n const directByServer = new Map<string, number>();\n for (const spec of directSpecs) {\n directByServer.set(spec.serverName, (directByServer.get(spec.serverName) ?? 0) + 1);\n }\n if (directByServer.size > 0) {\n const parts = [...directByServer.entries()].map(\n ([server, count]) => `${server} (${count})`,\n );\n desc += `\\nDirect tools available (call as normal tools): ${parts.join(\", \")}\\n`;\n }\n\n const serverSummaries: string[] = [];\n for (const serverName of Object.keys(config.mcpServers)) {\n const entry = cache?.servers?.[serverName];\n const definition = config.mcpServers[serverName];\n const toolCount = (entry?.tools ?? []).filter(\n (tool) => !isToolExcluded(tool.name, serverName, prefix, definition.excludeTools),\n ).length;\n const resourceCount = definition?.exposeResources !== false\n ? (entry?.resources ?? []).filter((resource) => {\n const baseName = `get_${resourceNameToToolName(resource.name)}`;\n return !isToolExcluded(baseName, serverName, prefix, definition.excludeTools);\n }).length\n : 0;\n const totalItems = toolCount + resourceCount;\n if (totalItems === 0) continue;\n const directCount = directByServer.get(serverName) ?? 0;\n const proxyCount = totalItems - directCount;\n if (proxyCount > 0) {\n serverSummaries.push(`${serverName} (${proxyCount} tools)`);\n }\n }\n\n if (serverSummaries.length > 0) {\n desc += `\\nServers: ${serverSummaries.join(\", \")}\\n`;\n }\n\n desc += `\\nUsage:\\n`;\n desc += ` mcp({ }) → Show server status\\n`;\n desc += ` mcp({ server: \"name\" }) → List tools from server\\n`;\n desc += ` mcp({ search: \"query\" }) → Search MCP tools by name/description\\n`;\n desc += ` mcp({ describe: \"tool_name\" }) → Show tool details and parameters\\n`;\n desc += ` mcp({ connect: \"server-name\" }) → Connect to a server and refresh metadata\\n`;\n desc += ` mcp({ tool: \"name\", args: '{\"key\": \"value\"}' }) → Call a tool (args is JSON string)\\n`;\n desc += ` mcp({ action: \"ui-messages\" }) → Retrieve accumulated messages from completed UI sessions\\n`;\n desc += ` mcp({ action: \"auth-start\", server: \"name\" }) → Start manual OAuth and get a browser URL\\n`;\n desc += ` mcp({ action: \"auth-complete\", server: \"name\", args: '{\"redirectUrl\":\"...\"}' }) → Complete manual OAuth\\n`;\n desc += `\\nMode: action > tool (call) > connect > describe > search > server (list) > nothing (status)`;\n desc += `\\nRead-only mode permits status, search, describe, and ui-messages only. Tool calls, connections, and authentication require yolo or auto; direct MCP tools are blocked in read-only.`;\n\n return desc;\n}\n"]}
|
|
@@ -167,6 +167,7 @@ export function buildProxyDescription(config, cache, directSpecs) {
|
|
|
167
167
|
desc += ` mcp({ action: "auth-start", server: "name" }) → Start manual OAuth and get a browser URL\n`;
|
|
168
168
|
desc += ` mcp({ action: "auth-complete", server: "name", args: '{"redirectUrl":"..."}' }) → Complete manual OAuth\n`;
|
|
169
169
|
desc += `\nMode: action > tool (call) > connect > describe > search > server (list) > nothing (status)`;
|
|
170
|
+
desc += `\nRead-only mode permits status, search, describe, and ui-messages only. Tool calls, connections, and authentication require yolo or auto; direct MCP tools are blocked in read-only.`;
|
|
170
171
|
return desc;
|
|
171
172
|
}
|
|
172
173
|
//# sourceMappingURL=direct-tools.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"direct-tools.js","sourceRoot":"","sources":["../../../src/builtin-extensions/pi-mcp-adapter/direct-tools.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5D,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAE7D,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC;AAE9F,MAAM,UAAU,kBAAkB,CAChC,MAAiB,EACjB,KAA2B,EAC3B,MAAmC,EACnC,WAAsB,EACJ;IAClB,MAAM,KAAK,GAAqB,EAAE,CAAC;IACnC,IAAI,CAAC,KAAK;QAAE,OAAO,KAAK,CAAC;IAEzB,MAAM,SAAS,GAAG,IAAI,GAAG,EAAU,CAAC;IAEpC,MAAM,UAAU,GAAG,IAAI,GAAG,EAAU,CAAC;IACr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AAO,CAAC,cAAc,CAAC,QAAQ,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,CAAC,YAAY,CAAC,CAAC;YAAA,CAC/E,CAAC,CAAC,MAAM;YACX,CAAC,CAAC,CAAC,CAAC;QACN,MAAM,UAAU,GAAG,SAAS,GAAG,aAAa,CAAC;QAC7C,IAAI,UAAU,KAAK,CAAC;YAAE,SAAS;QAC/B,MAAM,WAAW,GAAG,cAAc,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;QACxD,MAAM,UAAU,GAAG,UAAU,GAAG,WAAW,CAAC;QAC5C,IAAI,UAAU,GAAG,CAAC,EAAE,CAAC;YACnB,eAAe,CAAC,IAAI,CAAC,GAAG,UAAU,KAAK,UAAU,SAAS,CAAC,CAAC;QAC9D,CAAC;IACH,CAAC;IAED,IAAI,eAAe,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC/B,IAAI,IAAI,cAAc,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;IACvD,CAAC;IAED,IAAI,IAAI,YAAY,CAAC;IACrB,IAAI,IAAI,kEAAgE,CAAC;IACzE,IAAI,IAAI,sEAAoE,CAAC;IAC7E,IAAI,IAAI,oFAAkF,CAAC;IAC3F,IAAI,IAAI,gFAA8E,CAAC;IACvF,IAAI,IAAI,wFAAsF,CAAC;IAC/F,IAAI,IAAI,8FAA4F,CAAC;IACrG,IAAI,IAAI,wGAAsG,CAAC;IAC/G,IAAI,IAAI,qGAAmG,CAAC;IAC5G,IAAI,IAAI,+GAA6G,CAAC;IACtH,IAAI,IAAI,+FAA+F,CAAC;IAExG,OAAO,IAAI,CAAC;AAAA,CACb","sourcesContent":["// @ts-nocheck\nimport type { DirectToolSpec, McpConfig } from \"./types.ts\";\nimport type { MetadataCache } from \"./metadata-cache.ts\";\nimport { isServerCacheValid } from \"./metadata-cache.ts\";\nimport { formatToolName, isToolExcluded } from \"./types.ts\";\nimport { resourceNameToToolName } from \"./resource-tools.ts\";\n\nconst BUILTIN_NAMES = new Set([\"read\", \"bash\", \"edit\", \"write\", \"grep\", \"find\", \"ls\", \"mcp\"]);\n\nexport function resolveDirectTools(\n config: McpConfig,\n cache: MetadataCache | null,\n prefix: \"server\" | \"none\" | \"short\",\n envOverride?: string[],\n): DirectToolSpec[] {\n const specs: DirectToolSpec[] = [];\n if (!cache) return specs;\n\n const seenNames = new Set<string>();\n\n const envServers = new Set<string>();\n const envTools = new Map<string, Set<string>>();\n if (envOverride) {\n for (let item of envOverride) {\n item = item.replace(/\\/+$/, \"\");\n if (item.includes(\"/\")) {\n const [server, tool] = item.split(\"/\", 2);\n if (server && tool) {\n if (!envTools.has(server)) envTools.set(server, new Set());\n envTools.get(server)!.add(tool);\n } else if (server) {\n envServers.add(server);\n }\n } else if (item) {\n envServers.add(item);\n }\n }\n }\n\n const globalDirect = config.settings?.directTools;\n\n for (const [serverName, definition] of Object.entries(config.mcpServers)) {\n const serverCache = cache.servers[serverName];\n if (!serverCache || !isServerCacheValid(serverCache, definition)) continue;\n\n let toolFilter: true | string[] | false = false;\n\n if (envOverride) {\n if (envServers.has(serverName)) {\n toolFilter = true;\n } else if (envTools.has(serverName)) {\n toolFilter = [...envTools.get(serverName)!];\n }\n } else {\n if (definition.directTools !== undefined) {\n toolFilter = definition.directTools;\n } else if (globalDirect) {\n toolFilter = globalDirect;\n }\n }\n\n if (!toolFilter) continue;\n\n for (const tool of serverCache.tools ?? []) {\n if (toolFilter !== true && !toolFilter.includes(tool.name)) continue;\n if (isToolExcluded(tool.name, serverName, prefix, definition.excludeTools)) continue;\n const prefixedName = formatToolName(tool.name, serverName, prefix);\n if (BUILTIN_NAMES.has(prefixedName)) {\n console.warn(`MCP: skipping direct tool \"${prefixedName}\" (collides with builtin)`);\n continue;\n }\n if (seenNames.has(prefixedName)) {\n console.warn(`MCP: skipping duplicate direct tool \"${prefixedName}\" from \"${serverName}\"`);\n continue;\n }\n seenNames.add(prefixedName);\n specs.push({\n serverName,\n originalName: tool.name,\n prefixedName,\n description: tool.description ?? \"\",\n inputSchema: tool.inputSchema,\n uiResourceUri: tool.uiResourceUri,\n uiStreamMode: tool.uiStreamMode,\n });\n }\n\n if (definition.exposeResources !== false) {\n for (const resource of serverCache.resources ?? []) {\n const baseName = `get_${resourceNameToToolName(resource.name)}`;\n if (toolFilter !== true && !toolFilter.includes(baseName)) continue;\n if (isToolExcluded(baseName, serverName, prefix, definition.excludeTools)) continue;\n const prefixedName = formatToolName(baseName, serverName, prefix);\n if (BUILTIN_NAMES.has(prefixedName)) {\n console.warn(`MCP: skipping direct resource tool \"${prefixedName}\" (collides with builtin)`);\n continue;\n }\n if (seenNames.has(prefixedName)) {\n console.warn(`MCP: skipping duplicate direct resource tool \"${prefixedName}\" from \"${serverName}\"`);\n continue;\n }\n seenNames.add(prefixedName);\n specs.push({\n serverName,\n originalName: baseName,\n prefixedName,\n description: resource.description ?? `Read resource: ${resource.uri}`,\n resourceUri: resource.uri,\n });\n }\n }\n }\n\n return specs;\n}\n\nexport function getMissingConfiguredDirectToolServers(\n config: McpConfig,\n cache: MetadataCache | null,\n): string[] {\n const missing: string[] = [];\n const globalDirect = config.settings?.directTools;\n\n for (const [serverName, definition] of Object.entries(config.mcpServers)) {\n const hasDirectTools = definition.directTools !== undefined\n ? !!definition.directTools\n : !!globalDirect;\n\n if (!hasDirectTools) continue;\n\n const serverCache = cache?.servers?.[serverName];\n if (!serverCache || !isServerCacheValid(serverCache, definition)) {\n missing.push(serverName);\n }\n }\n\n return missing;\n}\n\nexport function buildProxyDescription(\n config: McpConfig,\n cache: MetadataCache | null,\n directSpecs: DirectToolSpec[],\n): string {\n const prefix = config.settings?.toolPrefix ?? \"server\";\n let desc = `MCP gateway - connect to MCP servers and call their tools. Non-MCP Pi tools should be called directly, not through mcp.\\n`;\n\n const directByServer = new Map<string, number>();\n for (const spec of directSpecs) {\n directByServer.set(spec.serverName, (directByServer.get(spec.serverName) ?? 0) + 1);\n }\n if (directByServer.size > 0) {\n const parts = [...directByServer.entries()].map(\n ([server, count]) => `${server} (${count})`,\n );\n desc += `\\nDirect tools available (call as normal tools): ${parts.join(\", \")}\\n`;\n }\n\n const serverSummaries: string[] = [];\n for (const serverName of Object.keys(config.mcpServers)) {\n const entry = cache?.servers?.[serverName];\n const definition = config.mcpServers[serverName];\n const toolCount = (entry?.tools ?? []).filter(\n (tool) => !isToolExcluded(tool.name, serverName, prefix, definition.excludeTools),\n ).length;\n const resourceCount = definition?.exposeResources !== false\n ? (entry?.resources ?? []).filter((resource) => {\n const baseName = `get_${resourceNameToToolName(resource.name)}`;\n return !isToolExcluded(baseName, serverName, prefix, definition.excludeTools);\n }).length\n : 0;\n const totalItems = toolCount + resourceCount;\n if (totalItems === 0) continue;\n const directCount = directByServer.get(serverName) ?? 0;\n const proxyCount = totalItems - directCount;\n if (proxyCount > 0) {\n serverSummaries.push(`${serverName} (${proxyCount} tools)`);\n }\n }\n\n if (serverSummaries.length > 0) {\n desc += `\\nServers: ${serverSummaries.join(\", \")}\\n`;\n }\n\n desc += `\\nUsage:\\n`;\n desc += ` mcp({ }) → Show server status\\n`;\n desc += ` mcp({ server: \"name\" }) → List tools from server\\n`;\n desc += ` mcp({ search: \"query\" }) → Search MCP tools by name/description\\n`;\n desc += ` mcp({ describe: \"tool_name\" }) → Show tool details and parameters\\n`;\n desc += ` mcp({ connect: \"server-name\" }) → Connect to a server and refresh metadata\\n`;\n desc += ` mcp({ tool: \"name\", args: '{\"key\": \"value\"}' }) → Call a tool (args is JSON string)\\n`;\n desc += ` mcp({ action: \"ui-messages\" }) → Retrieve accumulated messages from completed UI sessions\\n`;\n desc += ` mcp({ action: \"auth-start\", server: \"name\" }) → Start manual OAuth and get a browser URL\\n`;\n desc += ` mcp({ action: \"auth-complete\", server: \"name\", args: '{\"redirectUrl\":\"...\"}' }) → Complete manual OAuth\\n`;\n desc += `\\nMode: action > tool (call) > connect > describe > search > server (list) > nothing (status)`;\n\n return desc;\n}\n"]}
|
|
1
|
+
{"version":3,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,EAAE,CAAC;QAC/B,IAAI,IAAI,cAAc,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;IACvD,CAAC;IAED,IAAI,IAAI,YAAY,CAAC;IACrB,IAAI,IAAI,kEAAgE,CAAC;IACzE,IAAI,IAAI,sEAAoE,CAAC;IAC7E,IAAI,IAAI,oFAAkF,CAAC;IAC3F,IAAI,IAAI,gFAA8E,CAAC;IACvF,IAAI,IAAI,wFAAsF,CAAC;IAC/F,IAAI,IAAI,8FAA4F,CAAC;IACrG,IAAI,IAAI,wGAAsG,CAAC;IAC/G,IAAI,IAAI,qGAAmG,CAAC;IAC5G,IAAI,IAAI,+GAA6G,CAAC;IACtH,IAAI,IAAI,+FAA+F,CAAC;IACxG,IAAI,IAAI,uLAAuL,CAAC;IAEhM,OAAO,IAAI,CAAC;AAAA,CACb","sourcesContent":["// @ts-nocheck\nimport type { DirectToolSpec, McpConfig } from \"./types.ts\";\nimport type { MetadataCache } from \"./metadata-cache.ts\";\nimport { isServerCacheValid } from \"./metadata-cache.ts\";\nimport { formatToolName, isToolExcluded } from \"./types.ts\";\nimport { resourceNameToToolName } from \"./resource-tools.ts\";\n\nconst BUILTIN_NAMES = new Set([\"read\", \"bash\", \"edit\", \"write\", \"grep\", \"find\", \"ls\", \"mcp\"]);\n\nexport function resolveDirectTools(\n config: McpConfig,\n cache: MetadataCache | null,\n prefix: \"server\" | \"none\" | \"short\",\n envOverride?: string[],\n): DirectToolSpec[] {\n const specs: DirectToolSpec[] = [];\n if (!cache) return specs;\n\n const seenNames = new Set<string>();\n\n const envServers = new Set<string>();\n const envTools = new Map<string, Set<string>>();\n if (envOverride) {\n for (let item of envOverride) {\n item = item.replace(/\\/+$/, \"\");\n if (item.includes(\"/\")) {\n const [server, tool] = item.split(\"/\", 2);\n if (server && tool) {\n if (!envTools.has(server)) envTools.set(server, new Set());\n envTools.get(server)!.add(tool);\n } else if (server) {\n envServers.add(server);\n }\n } else if (item) {\n envServers.add(item);\n }\n }\n }\n\n const globalDirect = config.settings?.directTools;\n\n for (const [serverName, definition] of Object.entries(config.mcpServers)) {\n const serverCache = cache.servers[serverName];\n if (!serverCache || !isServerCacheValid(serverCache, definition)) continue;\n\n let toolFilter: true | string[] | false = false;\n\n if (envOverride) {\n if (envServers.has(serverName)) {\n toolFilter = true;\n } else if (envTools.has(serverName)) {\n toolFilter = [...envTools.get(serverName)!];\n }\n } else {\n if (definition.directTools !== undefined) {\n toolFilter = definition.directTools;\n } else if (globalDirect) {\n toolFilter = globalDirect;\n }\n }\n\n if (!toolFilter) continue;\n\n for (const tool of serverCache.tools ?? []) {\n if (toolFilter !== true && !toolFilter.includes(tool.name)) continue;\n if (isToolExcluded(tool.name, serverName, prefix, definition.excludeTools)) continue;\n const prefixedName = formatToolName(tool.name, serverName, prefix);\n if (BUILTIN_NAMES.has(prefixedName)) {\n console.warn(`MCP: skipping direct tool \"${prefixedName}\" (collides with builtin)`);\n continue;\n }\n if (seenNames.has(prefixedName)) {\n console.warn(`MCP: skipping duplicate direct tool \"${prefixedName}\" from \"${serverName}\"`);\n continue;\n }\n seenNames.add(prefixedName);\n specs.push({\n serverName,\n originalName: tool.name,\n prefixedName,\n description: tool.description ?? \"\",\n inputSchema: tool.inputSchema,\n uiResourceUri: tool.uiResourceUri,\n uiStreamMode: tool.uiStreamMode,\n });\n }\n\n if (definition.exposeResources !== false) {\n for (const resource of serverCache.resources ?? []) {\n const baseName = `get_${resourceNameToToolName(resource.name)}`;\n if (toolFilter !== true && !toolFilter.includes(baseName)) continue;\n if (isToolExcluded(baseName, serverName, prefix, definition.excludeTools)) continue;\n const prefixedName = formatToolName(baseName, serverName, prefix);\n if (BUILTIN_NAMES.has(prefixedName)) {\n console.warn(`MCP: skipping direct resource tool \"${prefixedName}\" (collides with builtin)`);\n continue;\n }\n if (seenNames.has(prefixedName)) {\n console.warn(`MCP: skipping duplicate direct resource tool \"${prefixedName}\" from \"${serverName}\"`);\n continue;\n }\n seenNames.add(prefixedName);\n specs.push({\n serverName,\n originalName: baseName,\n prefixedName,\n description: resource.description ?? `Read resource: ${resource.uri}`,\n resourceUri: resource.uri,\n });\n }\n }\n }\n\n return specs;\n}\n\nexport function getMissingConfiguredDirectToolServers(\n config: McpConfig,\n cache: MetadataCache | null,\n): string[] {\n const missing: string[] = [];\n const globalDirect = config.settings?.directTools;\n\n for (const [serverName, definition] of Object.entries(config.mcpServers)) {\n const hasDirectTools = definition.directTools !== undefined\n ? !!definition.directTools\n : !!globalDirect;\n\n if (!hasDirectTools) continue;\n\n const serverCache = cache?.servers?.[serverName];\n if (!serverCache || !isServerCacheValid(serverCache, definition)) {\n missing.push(serverName);\n }\n }\n\n return missing;\n}\n\nexport function buildProxyDescription(\n config: McpConfig,\n cache: MetadataCache | null,\n directSpecs: DirectToolSpec[],\n): string {\n const prefix = config.settings?.toolPrefix ?? \"server\";\n let desc = `MCP gateway - connect to MCP servers and call their tools. Non-MCP Pi tools should be called directly, not through mcp.\\n`;\n\n const directByServer = new Map<string, number>();\n for (const spec of directSpecs) {\n directByServer.set(spec.serverName, (directByServer.get(spec.serverName) ?? 0) + 1);\n }\n if (directByServer.size > 0) {\n const parts = [...directByServer.entries()].map(\n ([server, count]) => `${server} (${count})`,\n );\n desc += `\\nDirect tools available (call as normal tools): ${parts.join(\", \")}\\n`;\n }\n\n const serverSummaries: string[] = [];\n for (const serverName of Object.keys(config.mcpServers)) {\n const entry = cache?.servers?.[serverName];\n const definition = config.mcpServers[serverName];\n const toolCount = (entry?.tools ?? []).filter(\n (tool) => !isToolExcluded(tool.name, serverName, prefix, definition.excludeTools),\n ).length;\n const resourceCount = definition?.exposeResources !== false\n ? (entry?.resources ?? []).filter((resource) => {\n const baseName = `get_${resourceNameToToolName(resource.name)}`;\n return !isToolExcluded(baseName, serverName, prefix, definition.excludeTools);\n }).length\n : 0;\n const totalItems = toolCount + resourceCount;\n if (totalItems === 0) continue;\n const directCount = directByServer.get(serverName) ?? 0;\n const proxyCount = totalItems - directCount;\n if (proxyCount > 0) {\n serverSummaries.push(`${serverName} (${proxyCount} tools)`);\n }\n }\n\n if (serverSummaries.length > 0) {\n desc += `\\nServers: ${serverSummaries.join(\", \")}\\n`;\n }\n\n desc += `\\nUsage:\\n`;\n desc += ` mcp({ }) → Show server status\\n`;\n desc += ` mcp({ server: \"name\" }) → List tools from server\\n`;\n desc += ` mcp({ search: \"query\" }) → Search MCP tools by name/description\\n`;\n desc += ` mcp({ describe: \"tool_name\" }) → Show tool details and parameters\\n`;\n desc += ` mcp({ connect: \"server-name\" }) → Connect to a server and refresh metadata\\n`;\n desc += ` mcp({ tool: \"name\", args: '{\"key\": \"value\"}' }) → Call a tool (args is JSON string)\\n`;\n desc += ` mcp({ action: \"ui-messages\" }) → Retrieve accumulated messages from completed UI sessions\\n`;\n desc += ` mcp({ action: \"auth-start\", server: \"name\" }) → Start manual OAuth and get a browser URL\\n`;\n desc += ` mcp({ action: \"auth-complete\", server: \"name\", args: '{\"redirectUrl\":\"...\"}' }) → Complete manual OAuth\\n`;\n desc += `\\nMode: action > tool (call) > connect > describe > search > server (list) > nothing (status)`;\n desc += `\\nRead-only mode permits status, search, describe, and ui-messages only. Tool calls, connections, and authentication require yolo or auto; direct MCP tools are blocked in read-only.`;\n\n return desc;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/builtin-extensions/pi-mcp-adapter/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAA8B,MAAM,iCAAiC,CAAC;AAqChG,MAAM,CAAC,OAAO,UAAU,UAAU,CAAC,EAAE,EAAE,YAAY,QAqgBlD","sourcesContent":["// @ts-nocheck\nimport type { ExtensionAPI, ExtensionContext, ToolInfo } from \"@ashx-j/lunr\";\nimport type { McpExtensionState } from \"./state.ts\";\nimport type { DirectToolSpec, McpConfig } from \"./types.ts\";\nimport type { MetadataCache } from \"./metadata-cache.ts\";\nimport { existsSync } from \"node:fs\";\nimport { Type } from \"typebox\";\nimport { loadMcpConfig } from \"./config.ts\";\nimport { buildProxyDescription, getMissingConfiguredDirectToolServers, resolveDirectTools } from \"./direct-tools.ts\";\nimport { getMetadataCachePath, loadMetadataCache } from \"./metadata-cache.ts\";\nimport { getConfigPathFromArgv, normalizeDirectToolInputSchema, truncateAtWord } from \"./utils.ts\";\nimport { createMcpDirectToolCallRenderer, renderMcpProxyToolCall, renderMcpToolResult } from \"./tool-result-renderer.ts\";\nimport { toolErrorOverride } from \"./error-signal.ts\";\nimport { abortable, throwIfAborted } from \"./abort.ts\";\n\ntype McpHeavyModules = {\n init: typeof import(\"./init.ts\");\n authFlow: typeof import(\"./mcp-auth-flow.ts\");\n commands: typeof import(\"./commands.ts\");\n proxyModes: typeof import(\"./proxy-modes.ts\");\n directToolExecutor: typeof import(\"./direct-tool-executor.ts\");\n};\n\nfunction shouldBackgroundAutostart(config: McpConfig, cache: MetadataCache | null): boolean {\n const serverEntries = Object.entries(config.mcpServers);\n if (serverEntries.length === 0) return false;\n\n if (!existsSync(getMetadataCachePath())) return true;\n\n for (const [, definition] of serverEntries) {\n const mode = definition.lifecycle ?? \"lazy\";\n if (mode === \"keep-alive\" || mode === \"eager\") return true;\n }\n\n if (process.env.MCP_DIRECT_TOOLS === \"__none__\") return false;\n return getMissingConfiguredDirectToolServers(config, cache).length > 0;\n}\n\nexport default function mcpAdapter(pi: ExtensionAPI) {\n let state: McpExtensionState | null = null;\n let initPromise: Promise<McpExtensionState> | null = null;\n let lifecycleGeneration = 0;\n let sessionAbort = new AbortController();\n const initializingStates = new Set<McpExtensionState>();\n const shutdownPromises = new WeakMap<McpExtensionState, Promise<void>>();\n let heavyModules: McpHeavyModules | null = null;\n let heavyModulesPromise: Promise<McpHeavyModules> | null = null;\n const directExecutors = new Map<string, ReturnType<McpHeavyModules[\"directToolExecutor\"][\"createDirectToolExecutor\"]>>();\n\n function loadHeavyModules(): Promise<McpHeavyModules> {\n if (heavyModules) return Promise.resolve(heavyModules);\n if (!heavyModulesPromise) {\n heavyModulesPromise = (async () => {\n const [init, authFlow, commands, proxyModes, directToolExecutor] = await Promise.all([\n import(\"./init.ts\"),\n import(\"./mcp-auth-flow.ts\"),\n import(\"./commands.ts\"),\n import(\"./proxy-modes.ts\"),\n import(\"./direct-tool-executor.ts\"),\n ]);\n const loaded: McpHeavyModules = { init, authFlow, commands, proxyModes, directToolExecutor };\n heavyModules = loaded;\n return loaded;\n })().catch((error) => {\n heavyModulesPromise = null;\n throw error;\n });\n }\n return heavyModulesPromise;\n }\n\n function shutdownState(currentState: McpExtensionState | null, reason: string): Promise<void> {\n if (!currentState) return Promise.resolve();\n const existing = shutdownPromises.get(currentState);\n if (existing) return existing;\n\n const shutdown = (async () => {\n if (currentState.uiServer) {\n currentState.uiServer.close(reason);\n currentState.uiServer = null;\n }\n\n let flushError: unknown;\n try {\n if (heavyModules) {\n heavyModules.init.flushMetadataCache(currentState);\n }\n } catch (error) {\n flushError = error;\n }\n\n try {\n await currentState.lifecycle.gracefulShutdown();\n } catch (error) {\n if (flushError) {\n console.error(\"MCP: graceful shutdown failed after metadata flush error\", error);\n } else {\n throw error;\n }\n }\n\n if (flushError) {\n throw flushError;\n }\n })();\n shutdownPromises.set(currentState, shutdown);\n return shutdown;\n }\n\n async function shutdownInitializingStates(): Promise<void> {\n const pending = [...initializingStates];\n initializingStates.clear();\n await Promise.all(pending.map((entry) => shutdownState(entry, \"initialization_cancelled\")));\n }\n\n async function shutdownLoadedRuntime(): Promise<void> {\n if (!heavyModules) return;\n await heavyModules.authFlow.shutdownOAuth();\n }\n\n async function runInitialize(\n generation: number,\n sessionPi: ExtensionAPI,\n ctx: ExtensionContext,\n ): Promise<McpExtensionState> {\n const signal = sessionAbort.signal;\n const heavy = await loadHeavyModules();\n throwIfAborted(signal);\n if (generation !== lifecycleGeneration) {\n throw new Error(\"MCP initialization aborted (session changed)\");\n }\n\n await heavy.authFlow.initializeOAuth().catch(err => {\n console.error(\"MCP OAuth initialization failed:\", err);\n });\n\n if (generation !== lifecycleGeneration) {\n throw new Error(\"MCP initialization aborted (session changed)\");\n }\n\n let partial: McpExtensionState | undefined;\n try {\n const initialized = await heavy.init.initializeMcp(sessionPi, ctx, {\n signal,\n onState: (entry: McpExtensionState) => {\n partial = entry;\n initializingStates.add(entry);\n },\n });\n if (!partial) {\n partial = initialized;\n initializingStates.add(initialized);\n }\n throwIfAborted(signal);\n return initialized;\n } catch (error) {\n if (partial) {\n initializingStates.delete(partial);\n await shutdownState(partial, \"initialization_failed\");\n }\n throw error;\n } finally {\n if (partial) initializingStates.delete(partial);\n }\n }\n\n function startSessionInit(generation: number, sessionPi: ExtensionAPI, ctx: ExtensionContext): Promise<McpExtensionState> {\n const promise = runInitialize(generation, sessionPi, ctx);\n initPromise = promise;\n\n promise.then(async (nextState) => {\n if (generation !== lifecycleGeneration || initPromise !== promise) {\n try {\n await shutdownState(nextState, \"stale_session_start\");\n } catch (error) {\n console.error(\"MCP: failed to clean stale session state\", error);\n }\n return;\n }\n\n state = nextState;\n if (heavyModules) {\n heavyModules.init.updateStatusBar(nextState);\n }\n initPromise = null;\n }).catch(err => {\n if (generation !== lifecycleGeneration) {\n return;\n }\n if (initPromise !== promise && initPromise !== null) {\n return;\n }\n console.error(\"MCP initialization failed:\", err);\n initPromise = null;\n });\n\n return promise;\n }\n\n async function ensureState(sessionPi: ExtensionAPI, ctx: ExtensionContext, signal?: AbortSignal): Promise<McpExtensionState> {\n throwIfAborted(signal);\n if (state) return state;\n\n const generation = lifecycleGeneration;\n if (!initPromise) {\n startSessionInit(generation, sessionPi, ctx);\n }\n const promise = initPromise;\n if (!promise) {\n throw new Error(\"MCP not initialized\");\n }\n\n try {\n const nextState = await abortable(promise, signal);\n if (generation !== lifecycleGeneration) {\n throw new Error(\"MCP initialization aborted (session changed)\");\n }\n if (state) return state;\n state = nextState;\n if (initPromise === promise) {\n initPromise = null;\n }\n return state;\n } catch (error) {\n if (initPromise === promise && !signal?.aborted) {\n initPromise = null;\n }\n throw error;\n }\n }\n\n function assertCurrentState(currentState: McpExtensionState): void {\n if (currentState !== state) throw new Error(\"MCP session changed before execution\");\n }\n\n function createLazyDirectToolExecute(spec: DirectToolSpec) {\n return async function execute(toolCallId, params, incomingSignal, onUpdate, ctx) {\n const signal = incomingSignal ? AbortSignal.any([incomingSignal, sessionAbort.signal]) : sessionAbort.signal;\n let currentState: McpExtensionState;\n try {\n currentState = await ensureState(pi, ctx, signal);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n content: [{ type: \"text\" as const, text: `MCP initialization failed: ${message}` }],\n details: { error: \"init_failed\", message },\n };\n }\n\n const heavy = await loadHeavyModules();\n throwIfAborted(signal);\n assertCurrentState(currentState);\n let executor = directExecutors.get(spec.prefixedName);\n if (!executor) {\n executor = heavy.directToolExecutor.createDirectToolExecutor(() => currentState, () => null, spec);\n directExecutors.set(spec.prefixedName, executor);\n }\n return executor(toolCallId, params, signal, onUpdate, ctx);\n };\n }\n\n const earlyConfigPath = getConfigPathFromArgv();\n const earlyConfig = loadMcpConfig(earlyConfigPath);\n const earlyCache = loadMetadataCache();\n const prefix = earlyConfig.settings?.toolPrefix ?? \"server\";\n\n const envRaw = process.env.MCP_DIRECT_TOOLS;\n const directSpecs = envRaw === \"__none__\"\n ? []\n : resolveDirectTools(\n earlyConfig,\n earlyCache,\n prefix,\n envRaw?.split(\",\").map(s => s.trim()).filter(Boolean),\n );\n const missingConfiguredDirectToolServers = getMissingConfiguredDirectToolServers(earlyConfig, earlyCache);\n const shouldRegisterProxyTool =\n earlyConfig.settings?.disableProxyTool !== true\n || directSpecs.length === 0\n || missingConfiguredDirectToolServers.length > 0;\n\n for (const spec of directSpecs) {\n (pi.registerTool as (tool: unknown) => unknown)({\n name: spec.prefixedName,\n label: `MCP: ${spec.originalName}`,\n description: spec.description || \"(no description)\",\n promptSnippet: truncateAtWord(spec.description, 100) || `MCP tool from ${spec.serverName}`,\n parameters: Type.Unsafe(normalizeDirectToolInputSchema(spec.inputSchema) as never),\n execute: createLazyDirectToolExecute(spec),\n renderCall: createMcpDirectToolCallRenderer(spec.prefixedName),\n renderResult: renderMcpToolResult,\n });\n }\n\n const getPiTools = (): ToolInfo[] => pi.getAllTools();\n\n pi.registerFlag(\"mcp-config\", {\n description: \"Path to MCP config file\",\n type: \"string\",\n });\n\n pi.on(\"session_start\", async (_event, ctx) => {\n const generation = ++lifecycleGeneration;\n sessionAbort.abort(new Error(\"MCP session changed\"));\n sessionAbort = new AbortController();\n const previousState = state;\n state = null;\n initPromise = null;\n directExecutors.clear();\n\n try {\n await Promise.all([\n shutdownState(previousState, \"session_restart\"),\n shutdownInitializingStates(),\n shutdownLoadedRuntime(),\n ]);\n } catch (error) {\n console.error(\"MCP: failed to shut down previous session state\", error);\n }\n\n if (generation !== lifecycleGeneration) {\n return;\n }\n\n const configPath = (pi.getFlag(\"mcp-config\") as string | undefined) ?? earlyConfigPath;\n const sessionConfig = loadMcpConfig(configPath, ctx.cwd);\n const sessionCache = loadMetadataCache();\n\n if (!shouldBackgroundAutostart(sessionConfig, sessionCache)) {\n return;\n }\n\n startSessionInit(generation, pi, ctx);\n });\n\n pi.on(\"session_shutdown\", async () => {\n ++lifecycleGeneration;\n sessionAbort.abort(new Error(\"MCP session ended\"));\n const currentState = state;\n state = null;\n initPromise = null;\n directExecutors.clear();\n\n try {\n await Promise.all([\n shutdownState(currentState, \"session_shutdown\"),\n shutdownInitializingStates(),\n shutdownLoadedRuntime(),\n ]);\n } catch (error) {\n console.error(\"MCP: session shutdown cleanup failed\", error);\n }\n });\n\n // Re-flag returned MCP tool failures so pi registers them as errors (see toolErrorOverride).\n pi.on(\"tool_result\", (event) => toolErrorOverride(event.details));\n\n pi.registerCommand(\"mcp\", {\n description: \"Show MCP server status\",\n handler: async (args, ctx) => {\n let currentState: McpExtensionState;\n try {\n currentState = await ensureState(pi, ctx);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (ctx.hasUI) ctx.ui.notify(`MCP initialization failed: ${message}`, \"error\");\n return;\n }\n\n const heavy = await loadHeavyModules();\n assertCurrentState(currentState);\n const parts = args?.trim()?.split(/\\s+/) ?? [];\n const subcommand = parts[0] ?? \"\";\n const targetServer = parts[1];\n const rest = parts.slice(1).join(\" \");\n\n switch (subcommand) {\n case \"reconnect\":\n await heavy.commands.reconnectServers(currentState, ctx, targetServer);\n break;\n case \"tools\":\n await heavy.commands.showTools(currentState, ctx);\n break;\n case \"setup\": {\n const result = await heavy.commands.openMcpSetup(currentState, pi, ctx, earlyConfigPath, \"setup\");\n if (result?.configChanged) {\n await ctx.reload();\n return;\n }\n break;\n }\n case \"logout\": {\n const serverName = rest;\n if (!serverName) {\n if (ctx.hasUI) ctx.ui.notify(\"Usage: /mcp logout <server>\", \"error\");\n return;\n }\n await heavy.commands.logoutServer(serverName, currentState, ctx);\n break;\n }\n case \"status\":\n case \"\":\n default:\n if (ctx.hasUI) {\n const result = await heavy.commands.openMcpPanel(currentState, pi, ctx, earlyConfigPath);\n if (result?.configChanged) {\n await ctx.reload();\n return;\n }\n } else {\n await heavy.commands.showStatus(currentState, ctx);\n }\n break;\n }\n },\n });\n\n pi.registerCommand(\"mcp-auth\", {\n description: \"Authenticate with an MCP server (OAuth)\",\n handler: async (args, ctx) => {\n const serverName = args?.trim();\n if (!serverName && !ctx.hasUI) {\n return;\n }\n\n let currentState: McpExtensionState;\n try {\n currentState = await ensureState(pi, ctx);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (ctx.hasUI) ctx.ui.notify(`MCP initialization failed: ${message}`, \"error\");\n return;\n }\n\n const heavy = await loadHeavyModules();\n assertCurrentState(currentState);\n\n if (!serverName) {\n await heavy.commands.openMcpAuthPanel(currentState, pi, ctx, earlyConfigPath);\n return;\n }\n\n await heavy.commands.authenticateServer(serverName, currentState.config, ctx);\n },\n });\n\n if (shouldRegisterProxyTool) {\n (pi.registerTool as (tool: unknown) => unknown)({\n name: \"mcp\",\n label: \"MCP\",\n description: buildProxyDescription(earlyConfig, earlyCache, directSpecs),\n promptSnippet: \"MCP gateway - connect to MCP servers and call their tools\",\n renderCall: renderMcpProxyToolCall,\n parameters: Type.Object({\n tool: Type.Optional(Type.String({ description: \"Tool name to call (e.g., 'xcodebuild_list_sims')\" })),\n args: Type.Optional(Type.String({ description: \"Arguments as JSON string (e.g., '{\\\"key\\\": \\\"value\\\"}')\" })),\n connect: Type.Optional(Type.String({ description: \"Server name to connect (lazy connect + metadata refresh)\" })),\n describe: Type.Optional(Type.String({ description: \"Tool name to describe (shows parameters)\" })),\n search: Type.Optional(Type.String({ description: \"Search tools by name/description\" })),\n regex: Type.Optional(Type.Boolean({ description: \"Treat search as regex (default: substring match)\" })),\n includeSchemas: Type.Optional(Type.Boolean({ description: \"Include parameter schemas in search results (default: true)\" })),\n server: Type.Optional(Type.String({ description: \"Filter to specific server (also disambiguates tool calls)\" })),\n action: Type.Optional(Type.String({ description: \"Action: 'ui-messages', 'auth-start', or 'auth-complete'\" })),\n }),\n renderResult: renderMcpToolResult,\n async execute(_toolCallId, params: {\n tool?: string;\n args?: string;\n connect?: string;\n describe?: string;\n search?: string;\n regex?: boolean;\n includeSchemas?: boolean;\n server?: string;\n action?: string;\n }, incomingSignal, _onUpdate, ctx) {\n const signal = incomingSignal ? AbortSignal.any([incomingSignal, sessionAbort.signal]) : sessionAbort.signal;\n let parsedArgs: Record<string, unknown> | undefined;\n if (params.args) {\n try {\n parsedArgs = JSON.parse(params.args);\n if (typeof parsedArgs !== \"object\" || parsedArgs === null || Array.isArray(parsedArgs)) {\n const gotType = Array.isArray(parsedArgs) ? \"array\" : parsedArgs === null ? \"null\" : typeof parsedArgs;\n throw new Error(`Invalid args: expected a JSON object, got ${gotType}`);\n }\n } catch (error) {\n if (error instanceof SyntaxError) {\n throw new Error(`Invalid args JSON: ${error.message}`, { cause: error });\n }\n throw error;\n }\n }\n\n let currentState: McpExtensionState;\n try {\n currentState = await ensureState(pi, ctx, signal);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n content: [{ type: \"text\" as const, text: `MCP initialization failed: ${message}` }],\n details: { error: \"init_failed\", message },\n };\n }\n\n const heavy = await loadHeavyModules();\n throwIfAborted(signal);\n assertCurrentState(currentState);\n\n if (params.action === \"ui-messages\") {\n return heavy.proxyModes.executeUiMessages(currentState);\n }\n if (params.action === \"auth-start\") {\n if (!params.server) {\n return {\n content: [{ type: \"text\" as const, text: \"auth-start requires `server`. Example: mcp({ action: \\\"auth-start\\\", server: \\\"linear-server\\\" })\" }],\n details: { mode: \"auth-start\", error: \"missing_server\" },\n };\n }\n return heavy.proxyModes.executeAuthStart(currentState, params.server);\n }\n if (params.action === \"auth-complete\") {\n if (!params.server) {\n return {\n content: [{ type: \"text\" as const, text: \"auth-complete requires `server`.\" }],\n details: { mode: \"auth-complete\", error: \"missing_server\" },\n };\n }\n const input = parsedArgs?.redirectUrl ?? parsedArgs?.code ?? parsedArgs?.input;\n if (typeof input !== \"string\" || input.trim().length === 0) {\n return {\n content: [{ type: \"text\" as const, text: \"auth-complete requires args with `redirectUrl`, `code`, or `input`.\" }],\n details: { mode: \"auth-complete\", error: \"missing_input\" },\n };\n }\n return heavy.proxyModes.executeAuthComplete(currentState, params.server, input);\n }\n if (params.tool) {\n return heavy.proxyModes.executeCall(currentState, params.tool, parsedArgs, params.server, getPiTools, signal);\n }\n if (params.connect) {\n return heavy.proxyModes.executeConnect(currentState, params.connect, signal);\n }\n if (params.describe) {\n return heavy.proxyModes.executeDescribe(currentState, params.describe);\n }\n if (params.search) {\n return heavy.proxyModes.executeSearch(currentState, params.search, params.regex, params.server, params.includeSchemas);\n }\n if (params.server) {\n return heavy.proxyModes.executeList(currentState, params.server);\n }\n return heavy.proxyModes.executeStatus(currentState);\n },\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/builtin-extensions/pi-mcp-adapter/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAA8B,MAAM,iCAAiC,CAAC;AAqChG,MAAM,CAAC,OAAO,UAAU,UAAU,CAAC,EAAE,EAAE,YAAY,QAqgBlD","sourcesContent":["// @ts-nocheck\nimport type { ExtensionAPI, ExtensionContext, ToolInfo } from \"@ashx-j/lunr\";\nimport type { McpExtensionState } from \"./state.ts\";\nimport type { DirectToolSpec, McpConfig } from \"./types.ts\";\nimport type { MetadataCache } from \"./metadata-cache.ts\";\nimport { existsSync } from \"node:fs\";\nimport { Type } from \"typebox\";\nimport { loadMcpConfig } from \"./config.ts\";\nimport { buildProxyDescription, getMissingConfiguredDirectToolServers, resolveDirectTools } from \"./direct-tools.ts\";\nimport { getMetadataCachePath, loadMetadataCache } from \"./metadata-cache.ts\";\nimport { getConfigPathFromArgv, normalizeDirectToolInputSchema, truncateAtWord } from \"./utils.ts\";\nimport { createMcpDirectToolCallRenderer, renderMcpProxyToolCall, renderMcpToolResult } from \"./tool-result-renderer.ts\";\nimport { toolErrorOverride } from \"./error-signal.ts\";\nimport { abortable, throwIfAborted } from \"./abort.ts\";\n\ntype McpHeavyModules = {\n init: typeof import(\"./init.ts\");\n authFlow: typeof import(\"./mcp-auth-flow.ts\");\n commands: typeof import(\"./commands.ts\");\n proxyModes: typeof import(\"./proxy-modes.ts\");\n directToolExecutor: typeof import(\"./direct-tool-executor.ts\");\n};\n\nfunction shouldBackgroundAutostart(config: McpConfig, cache: MetadataCache | null): boolean {\n const serverEntries = Object.entries(config.mcpServers);\n if (serverEntries.length === 0) return false;\n\n if (!existsSync(getMetadataCachePath())) return true;\n\n for (const [, definition] of serverEntries) {\n const mode = definition.lifecycle ?? \"lazy\";\n if (mode === \"keep-alive\" || mode === \"eager\") return true;\n }\n\n if (process.env.MCP_DIRECT_TOOLS === \"__none__\") return false;\n return getMissingConfiguredDirectToolServers(config, cache).length > 0;\n}\n\nexport default function mcpAdapter(pi: ExtensionAPI) {\n let state: McpExtensionState | null = null;\n let initPromise: Promise<McpExtensionState> | null = null;\n let lifecycleGeneration = 0;\n let sessionAbort = new AbortController();\n const initializingStates = new Set<McpExtensionState>();\n const shutdownPromises = new WeakMap<McpExtensionState, Promise<void>>();\n let heavyModules: McpHeavyModules | null = null;\n let heavyModulesPromise: Promise<McpHeavyModules> | null = null;\n const directExecutors = new Map<string, ReturnType<McpHeavyModules[\"directToolExecutor\"][\"createDirectToolExecutor\"]>>();\n\n function loadHeavyModules(): Promise<McpHeavyModules> {\n if (heavyModules) return Promise.resolve(heavyModules);\n if (!heavyModulesPromise) {\n heavyModulesPromise = (async () => {\n const [init, authFlow, commands, proxyModes, directToolExecutor] = await Promise.all([\n import(\"./init.ts\"),\n import(\"./mcp-auth-flow.ts\"),\n import(\"./commands.ts\"),\n import(\"./proxy-modes.ts\"),\n import(\"./direct-tool-executor.ts\"),\n ]);\n const loaded: McpHeavyModules = { init, authFlow, commands, proxyModes, directToolExecutor };\n heavyModules = loaded;\n return loaded;\n })().catch((error) => {\n heavyModulesPromise = null;\n throw error;\n });\n }\n return heavyModulesPromise;\n }\n\n function shutdownState(currentState: McpExtensionState | null, reason: string): Promise<void> {\n if (!currentState) return Promise.resolve();\n const existing = shutdownPromises.get(currentState);\n if (existing) return existing;\n\n const shutdown = (async () => {\n if (currentState.uiServer) {\n currentState.uiServer.close(reason);\n currentState.uiServer = null;\n }\n\n let flushError: unknown;\n try {\n if (heavyModules) {\n heavyModules.init.flushMetadataCache(currentState);\n }\n } catch (error) {\n flushError = error;\n }\n\n try {\n await currentState.lifecycle.gracefulShutdown();\n } catch (error) {\n if (flushError) {\n console.error(\"MCP: graceful shutdown failed after metadata flush error\", error);\n } else {\n throw error;\n }\n }\n\n if (flushError) {\n throw flushError;\n }\n })();\n shutdownPromises.set(currentState, shutdown);\n return shutdown;\n }\n\n async function shutdownInitializingStates(): Promise<void> {\n const pending = [...initializingStates];\n initializingStates.clear();\n await Promise.all(pending.map((entry) => shutdownState(entry, \"initialization_cancelled\")));\n }\n\n async function shutdownLoadedRuntime(): Promise<void> {\n if (!heavyModules) return;\n await heavyModules.authFlow.shutdownOAuth();\n }\n\n async function runInitialize(\n generation: number,\n sessionPi: ExtensionAPI,\n ctx: ExtensionContext,\n ): Promise<McpExtensionState> {\n const signal = sessionAbort.signal;\n const heavy = await loadHeavyModules();\n throwIfAborted(signal);\n if (generation !== lifecycleGeneration) {\n throw new Error(\"MCP initialization aborted (session changed)\");\n }\n\n await heavy.authFlow.initializeOAuth().catch(err => {\n console.error(\"MCP OAuth initialization failed:\", err);\n });\n\n if (generation !== lifecycleGeneration) {\n throw new Error(\"MCP initialization aborted (session changed)\");\n }\n\n let partial: McpExtensionState | undefined;\n try {\n const initialized = await heavy.init.initializeMcp(sessionPi, ctx, {\n signal,\n onState: (entry: McpExtensionState) => {\n partial = entry;\n initializingStates.add(entry);\n },\n });\n if (!partial) {\n partial = initialized;\n initializingStates.add(initialized);\n }\n throwIfAborted(signal);\n return initialized;\n } catch (error) {\n if (partial) {\n initializingStates.delete(partial);\n await shutdownState(partial, \"initialization_failed\");\n }\n throw error;\n } finally {\n if (partial) initializingStates.delete(partial);\n }\n }\n\n function startSessionInit(generation: number, sessionPi: ExtensionAPI, ctx: ExtensionContext): Promise<McpExtensionState> {\n const promise = runInitialize(generation, sessionPi, ctx);\n initPromise = promise;\n\n promise.then(async (nextState) => {\n if (generation !== lifecycleGeneration || initPromise !== promise) {\n try {\n await shutdownState(nextState, \"stale_session_start\");\n } catch (error) {\n console.error(\"MCP: failed to clean stale session state\", error);\n }\n return;\n }\n\n state = nextState;\n if (heavyModules) {\n heavyModules.init.updateStatusBar(nextState);\n }\n initPromise = null;\n }).catch(err => {\n if (generation !== lifecycleGeneration) {\n return;\n }\n if (initPromise !== promise && initPromise !== null) {\n return;\n }\n console.error(\"MCP initialization failed:\", err);\n initPromise = null;\n });\n\n return promise;\n }\n\n async function ensureState(sessionPi: ExtensionAPI, ctx: ExtensionContext, signal?: AbortSignal): Promise<McpExtensionState> {\n throwIfAborted(signal);\n if (state) return state;\n\n const generation = lifecycleGeneration;\n if (!initPromise) {\n startSessionInit(generation, sessionPi, ctx);\n }\n const promise = initPromise;\n if (!promise) {\n throw new Error(\"MCP not initialized\");\n }\n\n try {\n const nextState = await abortable(promise, signal);\n if (generation !== lifecycleGeneration) {\n throw new Error(\"MCP initialization aborted (session changed)\");\n }\n if (state) return state;\n state = nextState;\n if (initPromise === promise) {\n initPromise = null;\n }\n return state;\n } catch (error) {\n if (initPromise === promise && !signal?.aborted) {\n initPromise = null;\n }\n throw error;\n }\n }\n\n function assertCurrentState(currentState: McpExtensionState): void {\n if (currentState !== state) throw new Error(\"MCP session changed before execution\");\n }\n\n function createLazyDirectToolExecute(spec: DirectToolSpec) {\n return async function execute(toolCallId, params, incomingSignal, onUpdate, ctx) {\n const signal = incomingSignal ? AbortSignal.any([incomingSignal, sessionAbort.signal]) : sessionAbort.signal;\n let currentState: McpExtensionState;\n try {\n currentState = await ensureState(pi, ctx, signal);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n content: [{ type: \"text\" as const, text: `MCP initialization failed: ${message}` }],\n details: { error: \"init_failed\", message },\n };\n }\n\n const heavy = await loadHeavyModules();\n throwIfAborted(signal);\n assertCurrentState(currentState);\n let executor = directExecutors.get(spec.prefixedName);\n if (!executor) {\n executor = heavy.directToolExecutor.createDirectToolExecutor(() => currentState, () => null, spec);\n directExecutors.set(spec.prefixedName, executor);\n }\n return executor(toolCallId, params, signal, onUpdate, ctx);\n };\n }\n\n const earlyConfigPath = getConfigPathFromArgv();\n const earlyConfig = loadMcpConfig(earlyConfigPath);\n const earlyCache = loadMetadataCache();\n const prefix = earlyConfig.settings?.toolPrefix ?? \"server\";\n\n const envRaw = process.env.MCP_DIRECT_TOOLS;\n const directSpecs = envRaw === \"__none__\"\n ? []\n : resolveDirectTools(\n earlyConfig,\n earlyCache,\n prefix,\n envRaw?.split(\",\").map(s => s.trim()).filter(Boolean),\n );\n const missingConfiguredDirectToolServers = getMissingConfiguredDirectToolServers(earlyConfig, earlyCache);\n const shouldRegisterProxyTool =\n earlyConfig.settings?.disableProxyTool !== true\n || directSpecs.length === 0\n || missingConfiguredDirectToolServers.length > 0;\n\n for (const spec of directSpecs) {\n (pi.registerTool as (tool: unknown) => unknown)({\n name: spec.prefixedName,\n label: `MCP: ${spec.originalName}`,\n description: `${spec.description || \"(no description)\"}\\nUnavailable in read-only mode; switch to yolo or auto to call.`,\n promptSnippet: truncateAtWord(spec.description, 100) || `MCP tool from ${spec.serverName}`,\n parameters: Type.Unsafe(normalizeDirectToolInputSchema(spec.inputSchema) as never),\n execute: createLazyDirectToolExecute(spec),\n renderCall: createMcpDirectToolCallRenderer(spec.prefixedName),\n renderResult: renderMcpToolResult,\n });\n }\n\n const getPiTools = (): ToolInfo[] => pi.getAllTools();\n\n pi.registerFlag(\"mcp-config\", {\n description: \"Path to MCP config file\",\n type: \"string\",\n });\n\n pi.on(\"session_start\", async (_event, ctx) => {\n const generation = ++lifecycleGeneration;\n sessionAbort.abort(new Error(\"MCP session changed\"));\n sessionAbort = new AbortController();\n const previousState = state;\n state = null;\n initPromise = null;\n directExecutors.clear();\n\n try {\n await Promise.all([\n shutdownState(previousState, \"session_restart\"),\n shutdownInitializingStates(),\n shutdownLoadedRuntime(),\n ]);\n } catch (error) {\n console.error(\"MCP: failed to shut down previous session state\", error);\n }\n\n if (generation !== lifecycleGeneration) {\n return;\n }\n\n const configPath = (pi.getFlag(\"mcp-config\") as string | undefined) ?? earlyConfigPath;\n const sessionConfig = loadMcpConfig(configPath, ctx.cwd);\n const sessionCache = loadMetadataCache();\n\n if (!shouldBackgroundAutostart(sessionConfig, sessionCache)) {\n return;\n }\n\n startSessionInit(generation, pi, ctx);\n });\n\n pi.on(\"session_shutdown\", async () => {\n ++lifecycleGeneration;\n sessionAbort.abort(new Error(\"MCP session ended\"));\n const currentState = state;\n state = null;\n initPromise = null;\n directExecutors.clear();\n\n try {\n await Promise.all([\n shutdownState(currentState, \"session_shutdown\"),\n shutdownInitializingStates(),\n shutdownLoadedRuntime(),\n ]);\n } catch (error) {\n console.error(\"MCP: session shutdown cleanup failed\", error);\n }\n });\n\n // Re-flag returned MCP tool failures so pi registers them as errors (see toolErrorOverride).\n pi.on(\"tool_result\", (event) => toolErrorOverride(event.details));\n\n pi.registerCommand(\"mcp\", {\n description: \"Show MCP server status\",\n handler: async (args, ctx) => {\n let currentState: McpExtensionState;\n try {\n currentState = await ensureState(pi, ctx);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (ctx.hasUI) ctx.ui.notify(`MCP initialization failed: ${message}`, \"error\");\n return;\n }\n\n const heavy = await loadHeavyModules();\n assertCurrentState(currentState);\n const parts = args?.trim()?.split(/\\s+/) ?? [];\n const subcommand = parts[0] ?? \"\";\n const targetServer = parts[1];\n const rest = parts.slice(1).join(\" \");\n\n switch (subcommand) {\n case \"reconnect\":\n await heavy.commands.reconnectServers(currentState, ctx, targetServer);\n break;\n case \"tools\":\n await heavy.commands.showTools(currentState, ctx);\n break;\n case \"setup\": {\n const result = await heavy.commands.openMcpSetup(currentState, pi, ctx, earlyConfigPath, \"setup\");\n if (result?.configChanged) {\n await ctx.reload();\n return;\n }\n break;\n }\n case \"logout\": {\n const serverName = rest;\n if (!serverName) {\n if (ctx.hasUI) ctx.ui.notify(\"Usage: /mcp logout <server>\", \"error\");\n return;\n }\n await heavy.commands.logoutServer(serverName, currentState, ctx);\n break;\n }\n case \"status\":\n case \"\":\n default:\n if (ctx.hasUI) {\n const result = await heavy.commands.openMcpPanel(currentState, pi, ctx, earlyConfigPath);\n if (result?.configChanged) {\n await ctx.reload();\n return;\n }\n } else {\n await heavy.commands.showStatus(currentState, ctx);\n }\n break;\n }\n },\n });\n\n pi.registerCommand(\"mcp-auth\", {\n description: \"Authenticate with an MCP server (OAuth)\",\n handler: async (args, ctx) => {\n const serverName = args?.trim();\n if (!serverName && !ctx.hasUI) {\n return;\n }\n\n let currentState: McpExtensionState;\n try {\n currentState = await ensureState(pi, ctx);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (ctx.hasUI) ctx.ui.notify(`MCP initialization failed: ${message}`, \"error\");\n return;\n }\n\n const heavy = await loadHeavyModules();\n assertCurrentState(currentState);\n\n if (!serverName) {\n await heavy.commands.openMcpAuthPanel(currentState, pi, ctx, earlyConfigPath);\n return;\n }\n\n await heavy.commands.authenticateServer(serverName, currentState.config, ctx);\n },\n });\n\n if (shouldRegisterProxyTool) {\n (pi.registerTool as (tool: unknown) => unknown)({\n name: \"mcp\",\n label: \"MCP\",\n description: buildProxyDescription(earlyConfig, earlyCache, directSpecs),\n promptSnippet: \"MCP gateway - connect to MCP servers and call their tools\",\n renderCall: renderMcpProxyToolCall,\n parameters: Type.Object({\n tool: Type.Optional(Type.String({ description: \"Tool name to call (e.g., 'xcodebuild_list_sims')\" })),\n args: Type.Optional(Type.String({ description: \"Arguments as JSON string (e.g., '{\\\"key\\\": \\\"value\\\"}')\" })),\n connect: Type.Optional(Type.String({ description: \"Server name to connect (lazy connect + metadata refresh)\" })),\n describe: Type.Optional(Type.String({ description: \"Tool name to describe (shows parameters)\" })),\n search: Type.Optional(Type.String({ description: \"Search tools by name/description\" })),\n regex: Type.Optional(Type.Boolean({ description: \"Treat search as regex (default: substring match)\" })),\n includeSchemas: Type.Optional(Type.Boolean({ description: \"Include parameter schemas in search results (default: true)\" })),\n server: Type.Optional(Type.String({ description: \"Filter to specific server (also disambiguates tool calls)\" })),\n action: Type.Optional(Type.String({ description: \"Action: 'ui-messages', 'auth-start', or 'auth-complete'\" })),\n }),\n renderResult: renderMcpToolResult,\n async execute(_toolCallId, params: {\n tool?: string;\n args?: string;\n connect?: string;\n describe?: string;\n search?: string;\n regex?: boolean;\n includeSchemas?: boolean;\n server?: string;\n action?: string;\n }, incomingSignal, _onUpdate, ctx) {\n const signal = incomingSignal ? AbortSignal.any([incomingSignal, sessionAbort.signal]) : sessionAbort.signal;\n let parsedArgs: Record<string, unknown> | undefined;\n if (params.args) {\n try {\n parsedArgs = JSON.parse(params.args);\n if (typeof parsedArgs !== \"object\" || parsedArgs === null || Array.isArray(parsedArgs)) {\n const gotType = Array.isArray(parsedArgs) ? \"array\" : parsedArgs === null ? \"null\" : typeof parsedArgs;\n throw new Error(`Invalid args: expected a JSON object, got ${gotType}`);\n }\n } catch (error) {\n if (error instanceof SyntaxError) {\n throw new Error(`Invalid args JSON: ${error.message}`, { cause: error });\n }\n throw error;\n }\n }\n\n let currentState: McpExtensionState;\n try {\n currentState = await ensureState(pi, ctx, signal);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n content: [{ type: \"text\" as const, text: `MCP initialization failed: ${message}` }],\n details: { error: \"init_failed\", message },\n };\n }\n\n const heavy = await loadHeavyModules();\n throwIfAborted(signal);\n assertCurrentState(currentState);\n\n if (params.action === \"ui-messages\") {\n return heavy.proxyModes.executeUiMessages(currentState);\n }\n if (params.action === \"auth-start\") {\n if (!params.server) {\n return {\n content: [{ type: \"text\" as const, text: \"auth-start requires `server`. Example: mcp({ action: \\\"auth-start\\\", server: \\\"linear-server\\\" })\" }],\n details: { mode: \"auth-start\", error: \"missing_server\" },\n };\n }\n return heavy.proxyModes.executeAuthStart(currentState, params.server);\n }\n if (params.action === \"auth-complete\") {\n if (!params.server) {\n return {\n content: [{ type: \"text\" as const, text: \"auth-complete requires `server`.\" }],\n details: { mode: \"auth-complete\", error: \"missing_server\" },\n };\n }\n const input = parsedArgs?.redirectUrl ?? parsedArgs?.code ?? parsedArgs?.input;\n if (typeof input !== \"string\" || input.trim().length === 0) {\n return {\n content: [{ type: \"text\" as const, text: \"auth-complete requires args with `redirectUrl`, `code`, or `input`.\" }],\n details: { mode: \"auth-complete\", error: \"missing_input\" },\n };\n }\n return heavy.proxyModes.executeAuthComplete(currentState, params.server, input);\n }\n if (params.tool) {\n return heavy.proxyModes.executeCall(currentState, params.tool, parsedArgs, params.server, getPiTools, signal);\n }\n if (params.connect) {\n return heavy.proxyModes.executeConnect(currentState, params.connect, signal);\n }\n if (params.describe) {\n return heavy.proxyModes.executeDescribe(currentState, params.describe);\n }\n if (params.search) {\n return heavy.proxyModes.executeSearch(currentState, params.search, params.regex, params.server, params.includeSchemas);\n }\n if (params.server) {\n return heavy.proxyModes.executeList(currentState, params.server);\n }\n return heavy.proxyModes.executeStatus(currentState);\n },\n });\n }\n}\n"]}
|
|
@@ -250,7 +250,7 @@ export default function mcpAdapter(pi) {
|
|
|
250
250
|
pi.registerTool({
|
|
251
251
|
name: spec.prefixedName,
|
|
252
252
|
label: `MCP: ${spec.originalName}`,
|
|
253
|
-
description: spec.description || "(no description)"
|
|
253
|
+
description: `${spec.description || "(no description)"}\nUnavailable in read-only mode; switch to yolo or auto to call.`,
|
|
254
254
|
promptSnippet: truncateAtWord(spec.description, 100) || `MCP tool from ${spec.serverName}`,
|
|
255
255
|
parameters: Type.Unsafe(normalizeDirectToolInputSchema(spec.inputSchema)),
|
|
256
256
|
execute: createLazyDirectToolExecute(spec),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/builtin-extensions/pi-mcp-adapter/index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC/B,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,qBAAqB,EAAE,qCAAqC,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACrH,OAAO,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAC9E,OAAO,EAAE,qBAAqB,EAAE,8BAA8B,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AACnG,OAAO,EAAE,+BAA+B,EAAE,sBAAsB,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AACzH,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE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port type { McpExtensionState } from \"./state.ts\";\nimport type { DirectToolSpec, McpConfig } from \"./types.ts\";\nimport type { MetadataCache } from \"./metadata-cache.ts\";\nimport { existsSync } from \"node:fs\";\nimport { Type } from \"typebox\";\nimport { loadMcpConfig } from \"./config.ts\";\nimport { buildProxyDescription, getMissingConfiguredDirectToolServers, resolveDirectTools } from \"./direct-tools.ts\";\nimport { getMetadataCachePath, loadMetadataCache } from \"./metadata-cache.ts\";\nimport { getConfigPathFromArgv, normalizeDirectToolInputSchema, truncateAtWord } from \"./utils.ts\";\nimport { createMcpDirectToolCallRenderer, renderMcpProxyToolCall, renderMcpToolResult } from \"./tool-result-renderer.ts\";\nimport { toolErrorOverride } from \"./error-signal.ts\";\nimport { abortable, throwIfAborted } from \"./abort.ts\";\n\ntype McpHeavyModules = {\n init: typeof import(\"./init.ts\");\n authFlow: typeof import(\"./mcp-auth-flow.ts\");\n commands: typeof import(\"./commands.ts\");\n proxyModes: typeof import(\"./proxy-modes.ts\");\n directToolExecutor: typeof import(\"./direct-tool-executor.ts\");\n};\n\nfunction shouldBackgroundAutostart(config: McpConfig, cache: MetadataCache | null): boolean {\n const serverEntries = Object.entries(config.mcpServers);\n if (serverEntries.length === 0) return false;\n\n if (!existsSync(getMetadataCachePath())) return true;\n\n for (const [, definition] of serverEntries) {\n const mode = definition.lifecycle ?? \"lazy\";\n if (mode === \"keep-alive\" || mode === \"eager\") return true;\n }\n\n if (process.env.MCP_DIRECT_TOOLS === \"__none__\") return false;\n return getMissingConfiguredDirectToolServers(config, cache).length > 0;\n}\n\nexport default function mcpAdapter(pi: ExtensionAPI) {\n let state: McpExtensionState | null = null;\n let initPromise: Promise<McpExtensionState> | null = null;\n let lifecycleGeneration = 0;\n let sessionAbort = new AbortController();\n const initializingStates = new Set<McpExtensionState>();\n const shutdownPromises = new WeakMap<McpExtensionState, Promise<void>>();\n let heavyModules: McpHeavyModules | null = null;\n let heavyModulesPromise: Promise<McpHeavyModules> | null = null;\n const directExecutors = new Map<string, ReturnType<McpHeavyModules[\"directToolExecutor\"][\"createDirectToolExecutor\"]>>();\n\n function loadHeavyModules(): Promise<McpHeavyModules> {\n if (heavyModules) return Promise.resolve(heavyModules);\n if (!heavyModulesPromise) {\n heavyModulesPromise = (async () => {\n const [init, authFlow, commands, proxyModes, directToolExecutor] = await Promise.all([\n import(\"./init.ts\"),\n import(\"./mcp-auth-flow.ts\"),\n import(\"./commands.ts\"),\n import(\"./proxy-modes.ts\"),\n import(\"./direct-tool-executor.ts\"),\n ]);\n const loaded: McpHeavyModules = { init, authFlow, commands, proxyModes, directToolExecutor };\n heavyModules = loaded;\n return loaded;\n })().catch((error) => {\n heavyModulesPromise = null;\n throw error;\n });\n }\n return heavyModulesPromise;\n }\n\n function shutdownState(currentState: McpExtensionState | null, reason: string): Promise<void> {\n if (!currentState) return Promise.resolve();\n const existing = shutdownPromises.get(currentState);\n if (existing) return existing;\n\n const shutdown = (async () => {\n if (currentState.uiServer) {\n currentState.uiServer.close(reason);\n currentState.uiServer = null;\n }\n\n let flushError: unknown;\n try {\n if (heavyModules) {\n heavyModules.init.flushMetadataCache(currentState);\n }\n } catch (error) {\n flushError = error;\n }\n\n try {\n await currentState.lifecycle.gracefulShutdown();\n } catch (error) {\n if (flushError) {\n console.error(\"MCP: graceful shutdown failed after metadata flush error\", error);\n } else {\n throw error;\n }\n }\n\n if (flushError) {\n throw flushError;\n }\n })();\n shutdownPromises.set(currentState, shutdown);\n return shutdown;\n }\n\n async function shutdownInitializingStates(): Promise<void> {\n const pending = [...initializingStates];\n initializingStates.clear();\n await Promise.all(pending.map((entry) => shutdownState(entry, \"initialization_cancelled\")));\n }\n\n async function shutdownLoadedRuntime(): Promise<void> {\n if (!heavyModules) return;\n await heavyModules.authFlow.shutdownOAuth();\n }\n\n async function runInitialize(\n generation: number,\n sessionPi: ExtensionAPI,\n ctx: ExtensionContext,\n ): Promise<McpExtensionState> {\n const signal = sessionAbort.signal;\n const heavy = await loadHeavyModules();\n throwIfAborted(signal);\n if (generation !== lifecycleGeneration) {\n throw new Error(\"MCP initialization aborted (session changed)\");\n }\n\n await heavy.authFlow.initializeOAuth().catch(err => {\n console.error(\"MCP OAuth initialization failed:\", err);\n });\n\n if (generation !== lifecycleGeneration) {\n throw new Error(\"MCP initialization aborted (session changed)\");\n }\n\n let partial: McpExtensionState | undefined;\n try {\n const initialized = await heavy.init.initializeMcp(sessionPi, ctx, {\n signal,\n onState: (entry: McpExtensionState) => {\n partial = entry;\n initializingStates.add(entry);\n },\n });\n if (!partial) {\n partial = initialized;\n initializingStates.add(initialized);\n }\n throwIfAborted(signal);\n return initialized;\n } catch (error) {\n if (partial) {\n initializingStates.delete(partial);\n await shutdownState(partial, \"initialization_failed\");\n }\n throw error;\n } finally {\n if (partial) initializingStates.delete(partial);\n }\n }\n\n function startSessionInit(generation: number, sessionPi: ExtensionAPI, ctx: ExtensionContext): Promise<McpExtensionState> {\n const promise = runInitialize(generation, sessionPi, ctx);\n initPromise = promise;\n\n promise.then(async (nextState) => {\n if (generation !== lifecycleGeneration || initPromise !== promise) {\n try {\n await shutdownState(nextState, \"stale_session_start\");\n } catch (error) {\n console.error(\"MCP: failed to clean stale session state\", error);\n }\n return;\n }\n\n state = nextState;\n if (heavyModules) {\n heavyModules.init.updateStatusBar(nextState);\n }\n initPromise = null;\n }).catch(err => {\n if (generation !== lifecycleGeneration) {\n return;\n }\n if (initPromise !== promise && initPromise !== null) {\n return;\n }\n console.error(\"MCP initialization failed:\", err);\n initPromise = null;\n });\n\n return promise;\n }\n\n async function ensureState(sessionPi: ExtensionAPI, ctx: ExtensionContext, signal?: AbortSignal): Promise<McpExtensionState> {\n throwIfAborted(signal);\n if (state) return state;\n\n const generation = lifecycleGeneration;\n if (!initPromise) {\n startSessionInit(generation, sessionPi, ctx);\n }\n const promise = initPromise;\n if (!promise) {\n throw new Error(\"MCP not initialized\");\n }\n\n try {\n const nextState = await abortable(promise, signal);\n if (generation !== lifecycleGeneration) {\n throw new Error(\"MCP initialization aborted (session changed)\");\n }\n if (state) return state;\n state = nextState;\n if (initPromise === promise) {\n initPromise = null;\n }\n return state;\n } catch (error) {\n if (initPromise === promise && !signal?.aborted) {\n initPromise = null;\n }\n throw error;\n }\n }\n\n function assertCurrentState(currentState: McpExtensionState): void {\n if (currentState !== state) throw new Error(\"MCP session changed before execution\");\n }\n\n function createLazyDirectToolExecute(spec: DirectToolSpec) {\n return async function execute(toolCallId, params, incomingSignal, onUpdate, ctx) {\n const signal = incomingSignal ? AbortSignal.any([incomingSignal, sessionAbort.signal]) : sessionAbort.signal;\n let currentState: McpExtensionState;\n try {\n currentState = await ensureState(pi, ctx, signal);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n content: [{ type: \"text\" as const, text: `MCP initialization failed: ${message}` }],\n details: { error: \"init_failed\", message },\n };\n }\n\n const heavy = await loadHeavyModules();\n throwIfAborted(signal);\n assertCurrentState(currentState);\n let executor = directExecutors.get(spec.prefixedName);\n if (!executor) {\n executor = heavy.directToolExecutor.createDirectToolExecutor(() => currentState, () => null, spec);\n directExecutors.set(spec.prefixedName, executor);\n }\n return executor(toolCallId, params, signal, onUpdate, ctx);\n };\n }\n\n const earlyConfigPath = getConfigPathFromArgv();\n const earlyConfig = loadMcpConfig(earlyConfigPath);\n const earlyCache = loadMetadataCache();\n const prefix = earlyConfig.settings?.toolPrefix ?? \"server\";\n\n const envRaw = process.env.MCP_DIRECT_TOOLS;\n const directSpecs = envRaw === \"__none__\"\n ? []\n : resolveDirectTools(\n earlyConfig,\n earlyCache,\n prefix,\n envRaw?.split(\",\").map(s => s.trim()).filter(Boolean),\n );\n const missingConfiguredDirectToolServers = getMissingConfiguredDirectToolServers(earlyConfig, earlyCache);\n const shouldRegisterProxyTool =\n earlyConfig.settings?.disableProxyTool !== true\n || directSpecs.length === 0\n || missingConfiguredDirectToolServers.length > 0;\n\n for (const spec of directSpecs) {\n (pi.registerTool as (tool: unknown) => unknown)({\n name: spec.prefixedName,\n label: `MCP: ${spec.originalName}`,\n description: spec.description || \"(no description)\",\n promptSnippet: truncateAtWord(spec.description, 100) || `MCP tool from ${spec.serverName}`,\n parameters: Type.Unsafe(normalizeDirectToolInputSchema(spec.inputSchema) as never),\n execute: createLazyDirectToolExecute(spec),\n renderCall: createMcpDirectToolCallRenderer(spec.prefixedName),\n renderResult: renderMcpToolResult,\n });\n }\n\n const getPiTools = (): ToolInfo[] => pi.getAllTools();\n\n pi.registerFlag(\"mcp-config\", {\n description: \"Path to MCP config file\",\n type: \"string\",\n });\n\n pi.on(\"session_start\", async (_event, ctx) => {\n const generation = ++lifecycleGeneration;\n sessionAbort.abort(new Error(\"MCP session changed\"));\n sessionAbort = new AbortController();\n const previousState = state;\n state = null;\n initPromise = null;\n directExecutors.clear();\n\n try {\n await Promise.all([\n shutdownState(previousState, \"session_restart\"),\n shutdownInitializingStates(),\n shutdownLoadedRuntime(),\n ]);\n } catch (error) {\n console.error(\"MCP: failed to shut down previous session state\", error);\n }\n\n if (generation !== lifecycleGeneration) {\n return;\n }\n\n const configPath = (pi.getFlag(\"mcp-config\") as string | undefined) ?? earlyConfigPath;\n const sessionConfig = loadMcpConfig(configPath, ctx.cwd);\n const sessionCache = loadMetadataCache();\n\n if (!shouldBackgroundAutostart(sessionConfig, sessionCache)) {\n return;\n }\n\n startSessionInit(generation, pi, ctx);\n });\n\n pi.on(\"session_shutdown\", async () => {\n ++lifecycleGeneration;\n sessionAbort.abort(new Error(\"MCP session ended\"));\n const currentState = state;\n state = null;\n initPromise = null;\n directExecutors.clear();\n\n try {\n await Promise.all([\n shutdownState(currentState, \"session_shutdown\"),\n shutdownInitializingStates(),\n shutdownLoadedRuntime(),\n ]);\n } catch (error) {\n console.error(\"MCP: session shutdown cleanup failed\", error);\n }\n });\n\n // Re-flag returned MCP tool failures so pi registers them as errors (see toolErrorOverride).\n pi.on(\"tool_result\", (event) => toolErrorOverride(event.details));\n\n pi.registerCommand(\"mcp\", {\n description: \"Show MCP server status\",\n handler: async (args, ctx) => {\n let currentState: McpExtensionState;\n try {\n currentState = await ensureState(pi, ctx);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (ctx.hasUI) ctx.ui.notify(`MCP initialization failed: ${message}`, \"error\");\n return;\n }\n\n const heavy = await loadHeavyModules();\n assertCurrentState(currentState);\n const parts = args?.trim()?.split(/\\s+/) ?? [];\n const subcommand = parts[0] ?? \"\";\n const targetServer = parts[1];\n const rest = parts.slice(1).join(\" \");\n\n switch (subcommand) {\n case \"reconnect\":\n await heavy.commands.reconnectServers(currentState, ctx, targetServer);\n break;\n case \"tools\":\n await heavy.commands.showTools(currentState, ctx);\n break;\n case \"setup\": {\n const result = await heavy.commands.openMcpSetup(currentState, pi, ctx, earlyConfigPath, \"setup\");\n if (result?.configChanged) {\n await ctx.reload();\n return;\n }\n break;\n }\n case \"logout\": {\n const serverName = rest;\n if (!serverName) {\n if (ctx.hasUI) ctx.ui.notify(\"Usage: /mcp logout <server>\", \"error\");\n return;\n }\n await heavy.commands.logoutServer(serverName, currentState, ctx);\n break;\n }\n case \"status\":\n case \"\":\n default:\n if (ctx.hasUI) {\n const result = await heavy.commands.openMcpPanel(currentState, pi, ctx, earlyConfigPath);\n if (result?.configChanged) {\n await ctx.reload();\n return;\n }\n } else {\n await heavy.commands.showStatus(currentState, ctx);\n }\n break;\n }\n },\n });\n\n pi.registerCommand(\"mcp-auth\", {\n description: \"Authenticate with an MCP server (OAuth)\",\n handler: async (args, ctx) => {\n const serverName = args?.trim();\n if (!serverName && !ctx.hasUI) {\n return;\n }\n\n let currentState: McpExtensionState;\n try {\n currentState = await ensureState(pi, ctx);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (ctx.hasUI) ctx.ui.notify(`MCP initialization failed: ${message}`, \"error\");\n return;\n }\n\n const heavy = await loadHeavyModules();\n assertCurrentState(currentState);\n\n if (!serverName) {\n await heavy.commands.openMcpAuthPanel(currentState, pi, ctx, earlyConfigPath);\n return;\n }\n\n await heavy.commands.authenticateServer(serverName, currentState.config, ctx);\n },\n });\n\n if (shouldRegisterProxyTool) {\n (pi.registerTool as (tool: unknown) => unknown)({\n name: \"mcp\",\n label: \"MCP\",\n description: buildProxyDescription(earlyConfig, earlyCache, directSpecs),\n promptSnippet: \"MCP gateway - connect to MCP servers and call their tools\",\n renderCall: renderMcpProxyToolCall,\n parameters: Type.Object({\n tool: Type.Optional(Type.String({ description: \"Tool name to call (e.g., 'xcodebuild_list_sims')\" })),\n args: Type.Optional(Type.String({ description: \"Arguments as JSON string (e.g., '{\\\"key\\\": \\\"value\\\"}')\" })),\n connect: Type.Optional(Type.String({ description: \"Server name to connect (lazy connect + metadata refresh)\" })),\n describe: Type.Optional(Type.String({ description: \"Tool name to describe (shows parameters)\" })),\n search: Type.Optional(Type.String({ description: \"Search tools by name/description\" })),\n regex: Type.Optional(Type.Boolean({ description: \"Treat search as regex (default: substring match)\" })),\n includeSchemas: Type.Optional(Type.Boolean({ description: \"Include parameter schemas in search results (default: true)\" })),\n server: Type.Optional(Type.String({ description: \"Filter to specific server (also disambiguates tool calls)\" })),\n action: Type.Optional(Type.String({ description: \"Action: 'ui-messages', 'auth-start', or 'auth-complete'\" })),\n }),\n renderResult: renderMcpToolResult,\n async execute(_toolCallId, params: {\n tool?: string;\n args?: string;\n connect?: string;\n describe?: string;\n search?: string;\n regex?: boolean;\n includeSchemas?: boolean;\n server?: string;\n action?: string;\n }, incomingSignal, _onUpdate, ctx) {\n const signal = incomingSignal ? AbortSignal.any([incomingSignal, sessionAbort.signal]) : sessionAbort.signal;\n let parsedArgs: Record<string, unknown> | undefined;\n if (params.args) {\n try {\n parsedArgs = JSON.parse(params.args);\n if (typeof parsedArgs !== \"object\" || parsedArgs === null || Array.isArray(parsedArgs)) {\n const gotType = Array.isArray(parsedArgs) ? \"array\" : parsedArgs === null ? \"null\" : typeof parsedArgs;\n throw new Error(`Invalid args: expected a JSON object, got ${gotType}`);\n }\n } catch (error) {\n if (error instanceof SyntaxError) {\n throw new Error(`Invalid args JSON: ${error.message}`, { cause: error });\n }\n throw error;\n }\n }\n\n let currentState: McpExtensionState;\n try {\n currentState = await ensureState(pi, ctx, signal);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n content: [{ type: \"text\" as const, text: `MCP initialization failed: ${message}` }],\n details: { error: \"init_failed\", message },\n };\n }\n\n const heavy = await loadHeavyModules();\n throwIfAborted(signal);\n assertCurrentState(currentState);\n\n if (params.action === \"ui-messages\") {\n return heavy.proxyModes.executeUiMessages(currentState);\n }\n if (params.action === \"auth-start\") {\n if (!params.server) {\n return {\n content: [{ type: \"text\" as const, text: \"auth-start requires `server`. Example: mcp({ action: \\\"auth-start\\\", server: \\\"linear-server\\\" })\" }],\n details: { mode: \"auth-start\", error: \"missing_server\" },\n };\n }\n return heavy.proxyModes.executeAuthStart(currentState, params.server);\n }\n if (params.action === \"auth-complete\") {\n if (!params.server) {\n return {\n content: [{ type: \"text\" as const, text: \"auth-complete requires `server`.\" }],\n details: { mode: \"auth-complete\", error: \"missing_server\" },\n };\n }\n const input = parsedArgs?.redirectUrl ?? parsedArgs?.code ?? parsedArgs?.input;\n if (typeof input !== \"string\" || input.trim().length === 0) {\n return {\n content: [{ type: \"text\" as const, text: \"auth-complete requires args with `redirectUrl`, `code`, or `input`.\" }],\n details: { mode: \"auth-complete\", error: \"missing_input\" },\n };\n }\n return heavy.proxyModes.executeAuthComplete(currentState, params.server, input);\n }\n if (params.tool) {\n return heavy.proxyModes.executeCall(currentState, params.tool, parsedArgs, params.server, getPiTools, signal);\n }\n if (params.connect) {\n return heavy.proxyModes.executeConnect(currentState, params.connect, signal);\n }\n if (params.describe) {\n return heavy.proxyModes.executeDescribe(currentState, params.describe);\n }\n if (params.search) {\n return heavy.proxyModes.executeSearch(currentState, params.search, params.regex, params.server, params.includeSchemas);\n }\n if (params.server) {\n return heavy.proxyModes.executeList(currentState, params.server);\n }\n return heavy.proxyModes.executeStatus(currentState);\n },\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3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AAU,CAAC,eAAe,CAAC,YAAY,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC;gBACzE,CAAC;gBACD,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;oBAClB,OAAO,KAAK,CAAC,UAAU,CAAC,aAAa,CAAC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,cAAc,CAAC,CAAC;gBACzH,CAAC;gBACD,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;oBAClB,OAAO,KAAK,CAAC,UAAU,CAAC,WAAW,CAAC,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;gBACnE,CAAC;gBACD,OAAO,KAAK,CAAC,UAAU,CAAC,aAAa,CAAC,YAAY,CAAC,CAAC;YAAA,CACrD;SACF,CAAC,CAAC;IACL,CAAC;AAAA,CACF","sourcesContent":["// @ts-nocheck\nimport type { ExtensionAPI, ExtensionContext, ToolInfo } from \"@ashx-j/lunr\";\nimport type { McpExtensionState } from \"./state.ts\";\nimport type { DirectToolSpec, McpConfig } from \"./types.ts\";\nimport type { MetadataCache } from \"./metadata-cache.ts\";\nimport { existsSync } from \"node:fs\";\nimport { Type } from \"typebox\";\nimport { loadMcpConfig } from \"./config.ts\";\nimport { buildProxyDescription, getMissingConfiguredDirectToolServers, resolveDirectTools } from \"./direct-tools.ts\";\nimport { getMetadataCachePath, loadMetadataCache } from \"./metadata-cache.ts\";\nimport { getConfigPathFromArgv, normalizeDirectToolInputSchema, truncateAtWord } from \"./utils.ts\";\nimport { createMcpDirectToolCallRenderer, renderMcpProxyToolCall, renderMcpToolResult } from \"./tool-result-renderer.ts\";\nimport { toolErrorOverride } from \"./error-signal.ts\";\nimport { abortable, throwIfAborted } from \"./abort.ts\";\n\ntype McpHeavyModules = {\n init: typeof import(\"./init.ts\");\n authFlow: typeof import(\"./mcp-auth-flow.ts\");\n commands: typeof import(\"./commands.ts\");\n proxyModes: typeof import(\"./proxy-modes.ts\");\n directToolExecutor: typeof import(\"./direct-tool-executor.ts\");\n};\n\nfunction shouldBackgroundAutostart(config: McpConfig, cache: MetadataCache | null): boolean {\n const serverEntries = Object.entries(config.mcpServers);\n if (serverEntries.length === 0) return false;\n\n if (!existsSync(getMetadataCachePath())) return true;\n\n for (const [, definition] of serverEntries) {\n const mode = definition.lifecycle ?? \"lazy\";\n if (mode === \"keep-alive\" || mode === \"eager\") return true;\n }\n\n if (process.env.MCP_DIRECT_TOOLS === \"__none__\") return false;\n return getMissingConfiguredDirectToolServers(config, cache).length > 0;\n}\n\nexport default function mcpAdapter(pi: ExtensionAPI) {\n let state: McpExtensionState | null = null;\n let initPromise: Promise<McpExtensionState> | null = null;\n let lifecycleGeneration = 0;\n let sessionAbort = new AbortController();\n const initializingStates = new Set<McpExtensionState>();\n const shutdownPromises = new WeakMap<McpExtensionState, Promise<void>>();\n let heavyModules: McpHeavyModules | null = null;\n let heavyModulesPromise: Promise<McpHeavyModules> | null = null;\n const directExecutors = new Map<string, ReturnType<McpHeavyModules[\"directToolExecutor\"][\"createDirectToolExecutor\"]>>();\n\n function loadHeavyModules(): Promise<McpHeavyModules> {\n if (heavyModules) return Promise.resolve(heavyModules);\n if (!heavyModulesPromise) {\n heavyModulesPromise = (async () => {\n const [init, authFlow, commands, proxyModes, directToolExecutor] = await Promise.all([\n import(\"./init.ts\"),\n import(\"./mcp-auth-flow.ts\"),\n import(\"./commands.ts\"),\n import(\"./proxy-modes.ts\"),\n import(\"./direct-tool-executor.ts\"),\n ]);\n const loaded: McpHeavyModules = { init, authFlow, commands, proxyModes, directToolExecutor };\n heavyModules = loaded;\n return loaded;\n })().catch((error) => {\n heavyModulesPromise = null;\n throw error;\n });\n }\n return heavyModulesPromise;\n }\n\n function shutdownState(currentState: McpExtensionState | null, reason: string): Promise<void> {\n if (!currentState) return Promise.resolve();\n const existing = shutdownPromises.get(currentState);\n if (existing) return existing;\n\n const shutdown = (async () => {\n if (currentState.uiServer) {\n currentState.uiServer.close(reason);\n currentState.uiServer = null;\n }\n\n let flushError: unknown;\n try {\n if (heavyModules) {\n heavyModules.init.flushMetadataCache(currentState);\n }\n } catch (error) {\n flushError = error;\n }\n\n try {\n await currentState.lifecycle.gracefulShutdown();\n } catch (error) {\n if (flushError) {\n console.error(\"MCP: graceful shutdown failed after metadata flush error\", error);\n } else {\n throw error;\n }\n }\n\n if (flushError) {\n throw flushError;\n }\n })();\n shutdownPromises.set(currentState, shutdown);\n return shutdown;\n }\n\n async function shutdownInitializingStates(): Promise<void> {\n const pending = [...initializingStates];\n initializingStates.clear();\n await Promise.all(pending.map((entry) => shutdownState(entry, \"initialization_cancelled\")));\n }\n\n async function shutdownLoadedRuntime(): Promise<void> {\n if (!heavyModules) return;\n await heavyModules.authFlow.shutdownOAuth();\n }\n\n async function runInitialize(\n generation: number,\n sessionPi: ExtensionAPI,\n ctx: ExtensionContext,\n ): Promise<McpExtensionState> {\n const signal = sessionAbort.signal;\n const heavy = await loadHeavyModules();\n throwIfAborted(signal);\n if (generation !== lifecycleGeneration) {\n throw new Error(\"MCP initialization aborted (session changed)\");\n }\n\n await heavy.authFlow.initializeOAuth().catch(err => {\n console.error(\"MCP OAuth initialization failed:\", err);\n });\n\n if (generation !== lifecycleGeneration) {\n throw new Error(\"MCP initialization aborted (session changed)\");\n }\n\n let partial: McpExtensionState | undefined;\n try {\n const initialized = await heavy.init.initializeMcp(sessionPi, ctx, {\n signal,\n onState: (entry: McpExtensionState) => {\n partial = entry;\n initializingStates.add(entry);\n },\n });\n if (!partial) {\n partial = initialized;\n initializingStates.add(initialized);\n }\n throwIfAborted(signal);\n return initialized;\n } catch (error) {\n if (partial) {\n initializingStates.delete(partial);\n await shutdownState(partial, \"initialization_failed\");\n }\n throw error;\n } finally {\n if (partial) initializingStates.delete(partial);\n }\n }\n\n function startSessionInit(generation: number, sessionPi: ExtensionAPI, ctx: ExtensionContext): Promise<McpExtensionState> {\n const promise = runInitialize(generation, sessionPi, ctx);\n initPromise = promise;\n\n promise.then(async (nextState) => {\n if (generation !== lifecycleGeneration || initPromise !== promise) {\n try {\n await shutdownState(nextState, \"stale_session_start\");\n } catch (error) {\n console.error(\"MCP: failed to clean stale session state\", error);\n }\n return;\n }\n\n state = nextState;\n if (heavyModules) {\n heavyModules.init.updateStatusBar(nextState);\n }\n initPromise = null;\n }).catch(err => {\n if (generation !== lifecycleGeneration) {\n return;\n }\n if (initPromise !== promise && initPromise !== null) {\n return;\n }\n console.error(\"MCP initialization failed:\", err);\n initPromise = null;\n });\n\n return promise;\n }\n\n async function ensureState(sessionPi: ExtensionAPI, ctx: ExtensionContext, signal?: AbortSignal): Promise<McpExtensionState> {\n throwIfAborted(signal);\n if (state) return state;\n\n const generation = lifecycleGeneration;\n if (!initPromise) {\n startSessionInit(generation, sessionPi, ctx);\n }\n const promise = initPromise;\n if (!promise) {\n throw new Error(\"MCP not initialized\");\n }\n\n try {\n const nextState = await abortable(promise, signal);\n if (generation !== lifecycleGeneration) {\n throw new Error(\"MCP initialization aborted (session changed)\");\n }\n if (state) return state;\n state = nextState;\n if (initPromise === promise) {\n initPromise = null;\n }\n return state;\n } catch (error) {\n if (initPromise === promise && !signal?.aborted) {\n initPromise = null;\n }\n throw error;\n }\n }\n\n function assertCurrentState(currentState: McpExtensionState): void {\n if (currentState !== state) throw new Error(\"MCP session changed before execution\");\n }\n\n function createLazyDirectToolExecute(spec: DirectToolSpec) {\n return async function execute(toolCallId, params, incomingSignal, onUpdate, ctx) {\n const signal = incomingSignal ? AbortSignal.any([incomingSignal, sessionAbort.signal]) : sessionAbort.signal;\n let currentState: McpExtensionState;\n try {\n currentState = await ensureState(pi, ctx, signal);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n content: [{ type: \"text\" as const, text: `MCP initialization failed: ${message}` }],\n details: { error: \"init_failed\", message },\n };\n }\n\n const heavy = await loadHeavyModules();\n throwIfAborted(signal);\n assertCurrentState(currentState);\n let executor = directExecutors.get(spec.prefixedName);\n if (!executor) {\n executor = heavy.directToolExecutor.createDirectToolExecutor(() => currentState, () => null, spec);\n directExecutors.set(spec.prefixedName, executor);\n }\n return executor(toolCallId, params, signal, onUpdate, ctx);\n };\n }\n\n const earlyConfigPath = getConfigPathFromArgv();\n const earlyConfig = loadMcpConfig(earlyConfigPath);\n const earlyCache = loadMetadataCache();\n const prefix = earlyConfig.settings?.toolPrefix ?? \"server\";\n\n const envRaw = process.env.MCP_DIRECT_TOOLS;\n const directSpecs = envRaw === \"__none__\"\n ? []\n : resolveDirectTools(\n earlyConfig,\n earlyCache,\n prefix,\n envRaw?.split(\",\").map(s => s.trim()).filter(Boolean),\n );\n const missingConfiguredDirectToolServers = getMissingConfiguredDirectToolServers(earlyConfig, earlyCache);\n const shouldRegisterProxyTool =\n earlyConfig.settings?.disableProxyTool !== true\n || directSpecs.length === 0\n || missingConfiguredDirectToolServers.length > 0;\n\n for (const spec of directSpecs) {\n (pi.registerTool as (tool: unknown) => unknown)({\n name: spec.prefixedName,\n label: `MCP: ${spec.originalName}`,\n description: `${spec.description || \"(no description)\"}\\nUnavailable in read-only mode; switch to yolo or auto to call.`,\n promptSnippet: truncateAtWord(spec.description, 100) || `MCP tool from ${spec.serverName}`,\n parameters: Type.Unsafe(normalizeDirectToolInputSchema(spec.inputSchema) as never),\n execute: createLazyDirectToolExecute(spec),\n renderCall: createMcpDirectToolCallRenderer(spec.prefixedName),\n renderResult: renderMcpToolResult,\n });\n }\n\n const getPiTools = (): ToolInfo[] => pi.getAllTools();\n\n pi.registerFlag(\"mcp-config\", {\n description: \"Path to MCP config file\",\n type: \"string\",\n });\n\n pi.on(\"session_start\", async (_event, ctx) => {\n const generation = ++lifecycleGeneration;\n sessionAbort.abort(new Error(\"MCP session changed\"));\n sessionAbort = new AbortController();\n const previousState = state;\n state = null;\n initPromise = null;\n directExecutors.clear();\n\n try {\n await Promise.all([\n shutdownState(previousState, \"session_restart\"),\n shutdownInitializingStates(),\n shutdownLoadedRuntime(),\n ]);\n } catch (error) {\n console.error(\"MCP: failed to shut down previous session state\", error);\n }\n\n if (generation !== lifecycleGeneration) {\n return;\n }\n\n const configPath = (pi.getFlag(\"mcp-config\") as string | undefined) ?? earlyConfigPath;\n const sessionConfig = loadMcpConfig(configPath, ctx.cwd);\n const sessionCache = loadMetadataCache();\n\n if (!shouldBackgroundAutostart(sessionConfig, sessionCache)) {\n return;\n }\n\n startSessionInit(generation, pi, ctx);\n });\n\n pi.on(\"session_shutdown\", async () => {\n ++lifecycleGeneration;\n sessionAbort.abort(new Error(\"MCP session ended\"));\n const currentState = state;\n state = null;\n initPromise = null;\n directExecutors.clear();\n\n try {\n await Promise.all([\n shutdownState(currentState, \"session_shutdown\"),\n shutdownInitializingStates(),\n shutdownLoadedRuntime(),\n ]);\n } catch (error) {\n console.error(\"MCP: session shutdown cleanup failed\", error);\n }\n });\n\n // Re-flag returned MCP tool failures so pi registers them as errors (see toolErrorOverride).\n pi.on(\"tool_result\", (event) => toolErrorOverride(event.details));\n\n pi.registerCommand(\"mcp\", {\n description: \"Show MCP server status\",\n handler: async (args, ctx) => {\n let currentState: McpExtensionState;\n try {\n currentState = await ensureState(pi, ctx);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (ctx.hasUI) ctx.ui.notify(`MCP initialization failed: ${message}`, \"error\");\n return;\n }\n\n const heavy = await loadHeavyModules();\n assertCurrentState(currentState);\n const parts = args?.trim()?.split(/\\s+/) ?? [];\n const subcommand = parts[0] ?? \"\";\n const targetServer = parts[1];\n const rest = parts.slice(1).join(\" \");\n\n switch (subcommand) {\n case \"reconnect\":\n await heavy.commands.reconnectServers(currentState, ctx, targetServer);\n break;\n case \"tools\":\n await heavy.commands.showTools(currentState, ctx);\n break;\n case \"setup\": {\n const result = await heavy.commands.openMcpSetup(currentState, pi, ctx, earlyConfigPath, \"setup\");\n if (result?.configChanged) {\n await ctx.reload();\n return;\n }\n break;\n }\n case \"logout\": {\n const serverName = rest;\n if (!serverName) {\n if (ctx.hasUI) ctx.ui.notify(\"Usage: /mcp logout <server>\", \"error\");\n return;\n }\n await heavy.commands.logoutServer(serverName, currentState, ctx);\n break;\n }\n case \"status\":\n case \"\":\n default:\n if (ctx.hasUI) {\n const result = await heavy.commands.openMcpPanel(currentState, pi, ctx, earlyConfigPath);\n if (result?.configChanged) {\n await ctx.reload();\n return;\n }\n } else {\n await heavy.commands.showStatus(currentState, ctx);\n }\n break;\n }\n },\n });\n\n pi.registerCommand(\"mcp-auth\", {\n description: \"Authenticate with an MCP server (OAuth)\",\n handler: async (args, ctx) => {\n const serverName = args?.trim();\n if (!serverName && !ctx.hasUI) {\n return;\n }\n\n let currentState: McpExtensionState;\n try {\n currentState = await ensureState(pi, ctx);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (ctx.hasUI) ctx.ui.notify(`MCP initialization failed: ${message}`, \"error\");\n return;\n }\n\n const heavy = await loadHeavyModules();\n assertCurrentState(currentState);\n\n if (!serverName) {\n await heavy.commands.openMcpAuthPanel(currentState, pi, ctx, earlyConfigPath);\n return;\n }\n\n await heavy.commands.authenticateServer(serverName, currentState.config, ctx);\n },\n });\n\n if (shouldRegisterProxyTool) {\n (pi.registerTool as (tool: unknown) => unknown)({\n name: \"mcp\",\n label: \"MCP\",\n description: buildProxyDescription(earlyConfig, earlyCache, directSpecs),\n promptSnippet: \"MCP gateway - connect to MCP servers and call their tools\",\n renderCall: renderMcpProxyToolCall,\n parameters: Type.Object({\n tool: Type.Optional(Type.String({ description: \"Tool name to call (e.g., 'xcodebuild_list_sims')\" })),\n args: Type.Optional(Type.String({ description: \"Arguments as JSON string (e.g., '{\\\"key\\\": \\\"value\\\"}')\" })),\n connect: Type.Optional(Type.String({ description: \"Server name to connect (lazy connect + metadata refresh)\" })),\n describe: Type.Optional(Type.String({ description: \"Tool name to describe (shows parameters)\" })),\n search: Type.Optional(Type.String({ description: \"Search tools by name/description\" })),\n regex: Type.Optional(Type.Boolean({ description: \"Treat search as regex (default: substring match)\" })),\n includeSchemas: Type.Optional(Type.Boolean({ description: \"Include parameter schemas in search results (default: true)\" })),\n server: Type.Optional(Type.String({ description: \"Filter to specific server (also disambiguates tool calls)\" })),\n action: Type.Optional(Type.String({ description: \"Action: 'ui-messages', 'auth-start', or 'auth-complete'\" })),\n }),\n renderResult: renderMcpToolResult,\n async execute(_toolCallId, params: {\n tool?: string;\n args?: string;\n connect?: string;\n describe?: string;\n search?: string;\n regex?: boolean;\n includeSchemas?: boolean;\n server?: string;\n action?: string;\n }, incomingSignal, _onUpdate, ctx) {\n const signal = incomingSignal ? AbortSignal.any([incomingSignal, sessionAbort.signal]) : sessionAbort.signal;\n let parsedArgs: Record<string, unknown> | undefined;\n if (params.args) {\n try {\n parsedArgs = JSON.parse(params.args);\n if (typeof parsedArgs !== \"object\" || parsedArgs === null || Array.isArray(parsedArgs)) {\n const gotType = Array.isArray(parsedArgs) ? \"array\" : parsedArgs === null ? \"null\" : typeof parsedArgs;\n throw new Error(`Invalid args: expected a JSON object, got ${gotType}`);\n }\n } catch (error) {\n if (error instanceof SyntaxError) {\n throw new Error(`Invalid args JSON: ${error.message}`, { cause: error });\n }\n throw error;\n }\n }\n\n let currentState: McpExtensionState;\n try {\n currentState = await ensureState(pi, ctx, signal);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n content: [{ type: \"text\" as const, text: `MCP initialization failed: ${message}` }],\n details: { error: \"init_failed\", message },\n };\n }\n\n const heavy = await loadHeavyModules();\n throwIfAborted(signal);\n assertCurrentState(currentState);\n\n if (params.action === \"ui-messages\") {\n return heavy.proxyModes.executeUiMessages(currentState);\n }\n if (params.action === \"auth-start\") {\n if (!params.server) {\n return {\n content: [{ type: \"text\" as const, text: \"auth-start requires `server`. Example: mcp({ action: \\\"auth-start\\\", server: \\\"linear-server\\\" })\" }],\n details: { mode: \"auth-start\", error: \"missing_server\" },\n };\n }\n return heavy.proxyModes.executeAuthStart(currentState, params.server);\n }\n if (params.action === \"auth-complete\") {\n if (!params.server) {\n return {\n content: [{ type: \"text\" as const, text: \"auth-complete requires `server`.\" }],\n details: { mode: \"auth-complete\", error: \"missing_server\" },\n };\n }\n const input = parsedArgs?.redirectUrl ?? parsedArgs?.code ?? parsedArgs?.input;\n if (typeof input !== \"string\" || input.trim().length === 0) {\n return {\n content: [{ type: \"text\" as const, text: \"auth-complete requires args with `redirectUrl`, `code`, or `input`.\" }],\n details: { mode: \"auth-complete\", error: \"missing_input\" },\n };\n }\n return heavy.proxyModes.executeAuthComplete(currentState, params.server, input);\n }\n if (params.tool) {\n return heavy.proxyModes.executeCall(currentState, params.tool, parsedArgs, params.server, getPiTools, signal);\n }\n if (params.connect) {\n return heavy.proxyModes.executeConnect(currentState, params.connect, signal);\n }\n if (params.describe) {\n return heavy.proxyModes.executeDescribe(currentState, params.describe);\n }\n if (params.search) {\n return heavy.proxyModes.executeSearch(currentState, params.search, params.regex, params.server, params.includeSchemas);\n }\n if (params.server) {\n return heavy.proxyModes.executeList(currentState, params.server);\n }\n return heavy.proxyModes.executeStatus(currentState);\n },\n });\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schemas.d.ts","sourceRoot":"","sources":["../../../../../src/builtin-extensions/pi-subagents/src/extension/schemas.ts"],"names":[],"mappings":"AACA;;GAEG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AA+I/B,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;EAoB7B,CAAC;AAEH,eAAO,MAAM,mBAAmB;;;;;;;;;EASG,CAAC;AAEpC,eAAO,MAAM,6BAA6B;;;;;;;;;;;;;;;;;;;;;;EAsBP,CAAC;AAEpC,eAAO,MAAM,oBAAoB;;;EAGE,CAAC;AAGpC,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAsCpB,CAAC;AA6FH,eAAO,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAA0D,CAAC;AAkBtF,eAAO,MAAM,kBAAkB;;;;;EAA8D,CAAC","sourcesContent":["// @ts-nocheck\n/**\n * TypeBox schemas for subagent tool parameters\n */\n\nimport { Type } from \"typebox\";\n\nfunction keepTopLevelParameterDescriptions<T>(schema: T): T {\n\treturn pruneNestedDescriptions(schema, []) as T;\n}\n\nfunction pruneNestedDescriptions(value: unknown, path: string[]): unknown {\n\tif (!value || typeof value !== \"object\") return value;\n\n\tconst result = Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value));\n\tfor (const key of Reflect.ownKeys(value)) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\tif (!descriptor) continue;\n\t\t// `description` is both JSON Schema help text and the child UI-label parameter.\n\t\tif (key === \"description\" && !isPropertiesMap(path) && !isTopLevelParameterHelpText(path)) continue;\n\t\tif (\"value\" in descriptor) {\n\t\t\tconst nextPath = typeof key === \"string\" ? [...path, key] : path;\n\t\t\tdescriptor.value = pruneNestedDescriptions(descriptor.value, nextPath);\n\t\t}\n\t\tObject.defineProperty(result, key, descriptor);\n\t}\n\treturn result;\n}\n\nfunction isPropertiesMap(path: string[]): boolean {\n\treturn path[path.length - 1] === \"properties\";\n}\n\nfunction isTopLevelParameterHelpText(path: string[]): boolean {\n\treturn path.length === 2 && path[0] === \"properties\";\n}\n\nconst SkillOverride = Type.Unsafe({\n\tanyOf: [\n\t\t{ type: \"array\", items: { type: \"string\" } },\n\t\t{ type: \"boolean\", enum: [false] },\n\t\t{ type: \"string\" },\n\t],\n\tdescription: \"Skill name(s) to make available (comma-separated), array of strings, or false to disable\",\n});\n\nconst OutputOverride = Type.Unsafe({\n\tanyOf: [\n\t\t{ type: \"string\" },\n\t\t{ type: \"boolean\", enum: [false] },\n\t],\n\tdescription: \"Output filename/path (string), or false to disable file output\",\n});\n\nconst OutputModeOverride = Type.String({\n\tenum: [\"inline\", \"file-only\"],\n\tdescription: \"Return saved output inline (default) or only a concise file reference. file-only requires output to be a path.\",\n});\n\nconst TIER_SELECTION_DESCRIPTION = \"Choose the lowest model tier that can reliably complete the task: 'light' for quick checks, fact gathering, and small code inspections; 'standard' for everyday coding, clearly described bugs, and focused reviews; 'heavy' for complex implementation, difficult debugging, architectural decisions, and large or high-risk reviews.\";\n\n// lunr: choose exactly one of tier or model per executable child.\nconst TierOverride = Type.Optional(Type.String({\n\tenum: [\"light\", \"standard\", \"heavy\"],\n\tdescription: `Required by default. ${TIER_SELECTION_DESCRIPTION} Do not combine with model. The configured tier model must be available and authenticated.`,\n}));\n\nconst ModelOverride = Type.Optional(Type.String({\n\tminLength: 1,\n\tdescription: \"Explicit provider/model id only when the user names a model. Do not combine with tier. Optional thinking belongs in the thinking field or as a known :level suffix.\",\n}));\n\nconst ThinkingOverride = Type.Optional(Type.String({\n\tenum: [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"],\n\tdescription: \"Thinking level for an explicit model launch. Omit for tier launches (they use configured tier thinking).\",\n}));\n\nconst ReadsOverride = Type.Unsafe({\n\tanyOf: [\n\t\t{ type: \"array\", items: { type: \"string\" } },\n\t\t{ type: \"boolean\", enum: [false] },\n\t],\n\tdescription: \"Files to read before running (array of filenames), or false to disable\",\n});\n\nconst JsonSchemaObject = Type.Unsafe({\n\ttype: \"object\",\n\tadditionalProperties: true,\n\tdescription: \"JSON Schema object for strict structured output. Non-object roots are rejected.\",\n});\n\nconst AcceptanceOverride = Type.Unsafe({\n\tanyOf: [\n\t\t{ type: \"string\", enum: [\"auto\", \"attested\", \"checked\", \"verified\", \"reviewed\"] },\n\t\t{ type: \"boolean\", enum: [false] },\n\t\t{ type: \"object\", additionalProperties: true },\n\t],\n\tdescription: \"Optional acceptance policy. Omitted means auto-inferred; verified requires configured runtime commands. Reviewed is inferred-only because explicit runs cannot supply an independent reviewer result. Bare \\\"none\\\" requires { level: \\\"none\\\", reason: \\\"...\\\" }, while false is deprecated.\",\n});\n\nconst TurnBudgetOverride = Type.Object({\n\tmaxTurns: Type.Integer({ minimum: 1 }),\n\tgraceTurns: Type.Optional(Type.Integer({ minimum: 0 })),\n}, { additionalProperties: false, description: \"Optional assistant-turn budget. At maxTurns the child is asked to wrap up; after graceTurns additional assistant turns it is aborted and partial output is returned.\" });\n\nconst ToolBudgetBlock = Type.Unsafe({\n\tanyOf: [\n\t\t{ type: \"array\", minItems: 1, items: { type: \"string\", minLength: 1 } },\n\t\t{ type: \"string\", enum: [\"*\"] },\n\t],\n});\n\nconst ToolBudgetOverride = Type.Object({\n\tsoft: Type.Optional(Type.Integer({ minimum: 1 })),\n\thard: Type.Integer({ minimum: 1 }),\n\tblock: Type.Optional(ToolBudgetBlock),\n}, { additionalProperties: false, description: \"Optional child tool-call budget. soft nudges the child; after hard, block tools (default read/grep/find/ls, or '*' for all tools) are blocked so the child can finalize.\" });\n\nconst DescriptionField = Type.String({\n\tminLength: 1,\n\tmaxLength: 80,\n\tdescription: \"Required concise single-line UI label (max 80 characters). Presentation metadata only; not used as an identifier.\",\n});\n\nconst PermissionsField = Type.Optional(Type.String({\n\tenum: [\"full\", \"read-only\"],\n\tdescription: \"Child permission level. Omit or 'full' for coding tools (read/search/shell/edit/write/web/LSP/MCP). 'read-only' inspects without edit/write. Plan-mode parents must pass 'read-only'.\",\n}));\n\nconst TaskItem = Type.Object({\n\ttask: Type.String({ description: \"Complete model-authored prompt sent to the child.\" }),\n\tdescription: DescriptionField,\n\tpermissions: PermissionsField,\n\tcwd: Type.Optional(Type.String()),\n\tcount: Type.Optional(Type.Integer({ minimum: 1, description: \"Repeat this parallel task N times with the same settings.\" })),\n\toutput: Type.Optional(OutputOverride),\n\toutputMode: Type.Optional(OutputModeOverride),\n\treads: Type.Optional(ReadsOverride),\n\tprogress: Type.Optional(Type.Boolean({ description: \"Enable progress.md tracking for this task\" })),\n\ttier: TierOverride,\n\tmodel: ModelOverride,\n\tthinking: ThinkingOverride,\n\tskill: Type.Optional(SkillOverride),\n\ttoolBudget: Type.Optional(ToolBudgetOverride),\n\tacceptance: Type.Optional(AcceptanceOverride),\n});\n\n// Parallel task item (within a parallel step)\nexport const ParallelTaskSchema = Type.Object({\n\ttask: Type.Optional(Type.String({ description: \"Task template with {task}, {previous}, {chain_dir} variables. Defaults to {previous}.\" })),\n\tdescription: DescriptionField,\n\tpermissions: PermissionsField,\n\tphase: Type.Optional(Type.String({ description: \"Optional phase/group label for status and graph rendering.\" })),\n\tlabel: Type.Optional(Type.String({ description: \"Optional user-facing label for this parallel task.\" })),\n\tas: Type.Optional(Type.String({ description: \"Optional safe identifier used as {outputs.name} in later chain steps.\" })),\n\toutputSchema: Type.Optional(JsonSchemaObject),\n\tcwd: Type.Optional(Type.String()),\n\tcount: Type.Optional(Type.Integer({ minimum: 1, description: \"Repeat this parallel task N times with the same settings.\" })),\n\toutput: Type.Optional(OutputOverride),\n\toutputMode: Type.Optional(OutputModeOverride),\n\treads: Type.Optional(ReadsOverride),\n\tprogress: Type.Optional(Type.Boolean({ description: \"Enable progress.md tracking in {chain_dir}\" })),\n\tskill: Type.Optional(SkillOverride),\n\ttier: TierOverride,\n\tmodel: ModelOverride,\n\tthinking: ThinkingOverride,\n\ttoolBudget: Type.Optional(ToolBudgetOverride),\n\tacceptance: Type.Optional(AcceptanceOverride),\n});\n\nexport const DynamicExpandSchema = Type.Object({\n\tfrom: Type.Object({\n\t\toutput: Type.String({ description: \"Prior named structured output to expand from.\" }),\n\t\tpath: Type.String({ description: \"JSON Pointer into the structured output, e.g. /items.\" }),\n\t}, { additionalProperties: false }),\n\titem: Type.Optional(Type.String({ description: \"Template variable name for each item. Defaults to item.\" })),\n\tkey: Type.Optional(Type.String({ description: \"JSON Pointer relative to each item for stable child ids.\" })),\n\tmaxItems: Type.Optional(Type.Integer({ minimum: 0, description: \"Required fanout bound unless configured globally.\" })),\n\tonEmpty: Type.Optional(Type.String({ enum: [\"skip\", \"fail\"], description: \"Empty input behavior. Defaults to skip.\" })),\n}, { additionalProperties: false });\n\nexport const DynamicParallelTemplateSchema = Type.Object({\n\ttask: Type.Optional(Type.String({ description: \"Task template with {item}, {item.path}, {task}, {previous}, {chain_dir}, and {outputs.name} variables.\" })),\n\tdescription: Type.String({\n\t\tminLength: 1,\n\t\tmaxLength: 80,\n\t\tdescription: \"Required concise single-line UI label. May use the same template variables as task. Maximum 80 characters.\",\n\t}),\n\tpermissions: PermissionsField,\n\tphase: Type.Optional(Type.String({ description: \"Optional phase/group label for status and graph rendering.\" })),\n\tlabel: Type.Optional(Type.String({ description: \"Optional user-facing label; item templates are supported.\" })),\n\toutputSchema: Type.Optional(JsonSchemaObject),\n\tcwd: Type.Optional(Type.String()),\n\toutput: Type.Optional(OutputOverride),\n\toutputMode: Type.Optional(OutputModeOverride),\n\treads: Type.Optional(ReadsOverride),\n\tprogress: Type.Optional(Type.Boolean({ description: \"Enable progress.md tracking in {chain_dir}\" })),\n\tskill: Type.Optional(SkillOverride),\n\ttier: TierOverride,\n\tmodel: ModelOverride,\n\tthinking: ThinkingOverride,\n\ttoolBudget: Type.Optional(ToolBudgetOverride),\n\tacceptance: Type.Optional(AcceptanceOverride),\n}, { additionalProperties: false });\n\nexport const DynamicCollectSchema = Type.Object({\n\tas: Type.String({ description: \"Safe output name for the ordered collected result array.\" }),\n\toutputSchema: Type.Optional(JsonSchemaObject),\n}, { additionalProperties: false });\n\n// Flattened so chain steps do not need an object-shape anyOf/oneOf union.\nexport const ChainItem = Type.Object({\n\ttask: Type.Optional(Type.String({\n\t\tdescription: \"Task template with variables: {task}=original request, {previous}=prior step's text response, {chain_dir}=shared folder, {outputs.name}=prior named output. Required for first sequential step, defaults to '{previous}' for subsequent steps.\"\n\t})),\n\tdescription: Type.Optional(DescriptionField),\n\tpermissions: PermissionsField,\n\tphase: Type.Optional(Type.String({ description: \"Optional phase/group label for status and graph rendering.\" })),\n\tlabel: Type.Optional(Type.String({ description: \"Optional user-facing label for this chain step.\" })),\n\tas: Type.Optional(Type.String({ description: \"Optional safe identifier used as {outputs.name} in later chain steps.\" })),\n\toutputSchema: Type.Optional(JsonSchemaObject),\n\tcwd: Type.Optional(Type.String()),\n\toutput: Type.Optional(OutputOverride),\n\toutputMode: Type.Optional(OutputModeOverride),\n\treads: Type.Optional(ReadsOverride),\n\tprogress: Type.Optional(Type.Boolean({ description: \"Enable progress.md tracking in {chain_dir}\" })),\n\tskill: Type.Optional(SkillOverride),\n\ttier: TierOverride,\n\tmodel: ModelOverride,\n\tthinking: ThinkingOverride,\n\ttoolBudget: Type.Optional(ToolBudgetOverride),\n\tacceptance: Type.Optional(AcceptanceOverride),\n\tparallel: Type.Optional(Type.Unsafe({\n\t\tanyOf: [\n\t\t\tType.Array(ParallelTaskSchema, { minItems: 1, description: \"Tasks to run in parallel\" }),\n\t\t\tDynamicParallelTemplateSchema,\n\t\t],\n\t\tdescription: \"Static parallel tasks array, or a single dynamic fanout child template when expand/collect are present.\",\n\t})),\n\texpand: Type.Optional(DynamicExpandSchema),\n\tcollect: Type.Optional(DynamicCollectSchema),\n\tconcurrency: Type.Optional(Type.Number({ description: \"Max concurrent tasks (default: unlimited)\" })),\n\tfailFast: Type.Optional(Type.Boolean({ description: \"Stop on first failure (default: false)\" })),\n\tworktree: Type.Optional(Type.Boolean({\n\t\tdescription: \"Create isolated git worktrees for each parallel task.\"\n\t})),\n}, {\n\tdescription: \"Chain step: use {task, description, tier|model, permissions?} for sequential, {parallel: [...]} for static concurrent execution, or {expand, parallel: {...}, collect} for dynamic fanout. Every executable child needs exactly one of tier or model.\",\n\tadditionalProperties: false,\n});\n\nconst ControlOverrides = Type.Object({\n\tenabled: Type.Optional(Type.Boolean({ description: \"Enable/disable subagent control attention tracking for this run\" })),\n\tneedsAttentionAfterMs: Type.Optional(Type.Integer({ minimum: 1, description: \"No-observed-activity window before a run needs attention\" })),\n\tactiveNoticeAfterMs: Type.Optional(Type.Integer({ minimum: 1, description: \"Active-long-running notice threshold by elapsed ms (default: 240000)\" })),\n\tactiveNoticeAfterTurns: Type.Optional(Type.Integer({ minimum: 1, description: \"Optional active-long-running notice threshold by assistant turns (disabled by default)\" })),\n\tactiveNoticeAfterTokens: Type.Optional(Type.Integer({ minimum: 1, description: \"Optional active-long-running notice threshold by total tokens (disabled by default)\" })),\n\tfailedToolAttemptsBeforeAttention: Type.Optional(Type.Integer({ minimum: 1, description: \"Consecutive mutating-tool failures before escalating to needs_attention (default: 3)\" })),\n\tnotifyOn: Type.Optional(Type.Array(Type.String({ enum: [\"active_long_running\", \"needs_attention\"] }), {\n\t\tdescription: \"Control event types that should notify the parent/orchestrator. Defaults to active_long_running and needs_attention.\",\n\t})),\n\tnotifyChannels: Type.Optional(Type.Array(Type.String({ enum: [\"event\", \"async\", \"intercom\"] }), {\n\t\tdescription: \"Notification channels to use when available. Defaults to event, async, and intercom.\",\n\t})),\n});\n\nconst SubagentParamsSchema = Type.Object({\n\ttask: Type.Optional(Type.String({ description: \"Complete model-authored prompt sent to the child (SINGLE mode).\" })),\n\tdescription: Type.Optional(DescriptionField),\n\tpermissions: PermissionsField,\n\t// Control action (when present, tool operates in control mode rather than execution)\n\taction: Type.Optional(Type.String({\n\t\tdescription: \"Control action only. Must be omitted for execution mode (single, parallel, or chain). Runtime: status, interrupt, stop, resume, steer, append-step, doctor, watchdog.*, schedule*.\",\n\t})),\n\tid: Type.Optional(Type.String({\n\t\tdescription: \"Run id or prefix for action='status', action='interrupt', action='stop', action='resume', action='steer', or action='append-step'.\"\n\t})),\n\trunId: Type.Optional(Type.String({\n\t\tdescription: \"Target run ID for action='interrupt', action='stop', action='resume', action='steer', or action='append-step'. Prefer id for new calls.\"\n\t})),\n\tdir: Type.Optional(Type.String({\n\t\tdescription: \"Async run directory for action='status', action='stop', action='resume', or action='steer'.\"\n\t})),\n\tindex: Type.Optional(Type.Integer({ minimum: 0, description: \"Zero-based child index for actions that target a specific child or transcript.\" })),\n\tview: Type.Optional(Type.String({\n\t\tenum: [\"fleet\", \"transcript\"],\n\t\tdescription: \"Optional status view. Use view='fleet' for a read-only active foreground/async fleet surface, or view='transcript' with id/dir (and optional index) to tail a run transcript.\",\n\t})),\n\tlines: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: \"Maximum transcript lines for action='status', view='transcript'. Defaults to 80.\" })),\n\tmessage: Type.Optional(Type.String({ description: \"Follow-up message for action='resume' or non-terminal guidance for action='steer'. Use index to choose a child from multi-child runs.\" })),\n\tschedule: Type.Optional(Type.String({ description: \"Explicit one-shot schedule for action='schedule'. Only honored when scheduledRuns.enabled is true. Use '+10m' or a future ISO timestamp with timezone; scheduled runs always launch async with fresh context.\" })),\n\tscheduleName: Type.Optional(Type.String({ description: \"Optional display name for action='schedule'.\" })),\n\ttasks: Type.Optional(Type.Array(TaskItem, { description: \"PARALLEL mode: [{task, description, tier|model, thinking?, permissions?, count?, output?, outputMode?, reads?, progress?}, ...]\" })),\n\tconcurrency: Type.Optional(Type.Integer({ minimum: 1, description: \"Top-level PARALLEL mode only: max concurrent tasks. Defaults to config.parallel.concurrency or unlimited.\" })),\n\tworktree: Type.Optional(Type.Boolean({\n\t\tdescription: \"Create isolated git worktrees for parallel tasks; requires clean git state.\"\n\t})),\n\tchain: Type.Optional(Type.Array(ChainItem, { description: \"CHAIN mode: sequential steps; each result becomes {previous}. append-step takes one tail step and may use {chain_dir}/{outputs.name}.\" })),\n\tcontext: Type.Optional(Type.String({\n\t\tenum: [\"fresh\"],\n\t\tdescription: \"Children always start with a fresh session. Fork context is not available.\",\n\t})),\n\tchainDir: Type.Optional(Type.String({ description: \"Persistent chain artifact directory; defaults to user-scoped temp storage.\" })),\n\tasync: Type.Optional(Type.Boolean({ description: \"Run async in the background. Defaults to true when omitted; set false for immediate foreground results.\" })),\n\ttimeoutMs: Type.Optional(Type.Integer({ minimum: 1, description: \"Optional run-level timeout in ms for foreground and async/background runs. Alias of maxRuntimeMs.\" })),\n\tmaxRuntimeMs: Type.Optional(Type.Integer({ minimum: 1, description: \"Alias of timeoutMs for optional run-level timeout in foreground and async/background runs.\" })),\n\tturnBudget: Type.Optional(TurnBudgetOverride),\n\ttoolBudget: Type.Optional(ToolBudgetOverride),\n\tcwd: Type.Optional(Type.String()),\n\tartifacts: Type.Optional(Type.Boolean({ description: \"Write debug artifacts (default: true)\" })),\n\tincludeProgress: Type.Optional(Type.Boolean({ description: \"Include full progress in result (default: false)\" })),\n\tshare: Type.Optional(Type.Boolean({ description: \"Upload session to GitHub Gist for sharing (default: false)\" })),\n\tsessionDir: Type.Optional(\n\t\tType.String({ description: \"Directory to store session logs (default: temp; enables sessions even if share=false)\" }),\n\t),\n\t// Clarification TUI\n\tclarify: Type.Optional(Type.Boolean({ description: \"Show the interactive TUI preview/editor before execution. clarify:true keeps the run foreground even when async is omitted or true.\" })),\n\tcontrol: Type.Optional(ControlOverrides),\n\toutput: Type.Optional(Type.Unsafe({\n\t\tanyOf: [\n\t\t\t{ type: \"string\" },\n\t\t\t{ type: \"boolean\", enum: [false] },\n\t\t],\n\t\tdescription: \"Output file for a single child (string), or false to disable. Relative paths resolve against cwd.\",\n\t})),\n\toutputMode: Type.Optional(OutputModeOverride),\n\tskill: Type.Optional(SkillOverride),\n\ttier: Type.Optional(Type.String({\n\t\tenum: [\"light\", \"standard\", \"heavy\"],\n\t\tdescription: `Preferred for SINGLE execution. Required by default. Omit for control actions. Do not combine with model; PARALLEL and CHAIN children carry their own tier or model. ${TIER_SELECTION_DESCRIPTION}`,\n\t})),\n\tmodel: Type.Optional(Type.String({\n\t\tminLength: 1,\n\t\tdescription: \"Explicit provider/model for SINGLE execution only when the user names a model. Do not combine with tier.\",\n\t})),\n\tthinking: Type.Optional(Type.String({\n\t\tenum: [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"],\n\t\tdescription: \"Thinking level for an explicit model launch. Tier launches use configured tier thinking instead.\",\n\t})),\n\tacceptance: Type.Optional(AcceptanceOverride),\n});\n\nexport const SubagentParams = keepTopLevelParameterDescriptions(SubagentParamsSchema);\n\nconst SubagentWaitParamsSchema = Type.Object({\n\tid: Type.Optional(Type.String({\n\t\tdescription: \"Async run or remembered detached foreground run id/prefix to wait for one specific run. Omit to wait across every active async run started in this session.\",\n\t})),\n\tquestionId: Type.Optional(Type.String({\n\t\tdescription: \"Wait for one supervisor question id from subagent_supervisor action='ask'. Returns when that question is answered, expired, or cancelled. Separate from final async run results.\",\n\t})),\n\tall: Type.Optional(Type.Boolean({\n\t\tdescription: \"Wait for ALL active runs to finish. Default false: return as soon as the first run finishes, so a fleet manager can spawn a replacement and wait again. Ignored when id or questionId targets one item.\",\n\t})),\n\ttimeoutMs: Type.Optional(Type.Integer({\n\t\tminimum: 1,\n\t\tdescription: \"Give up waiting after this many milliseconds (the runs keep going regardless). Defaults to 1800000 (30 minutes).\",\n\t})),\n});\n\nexport const SubagentWaitParams = keepTopLevelParameterDescriptions(SubagentWaitParamsSchema);\n"]}
|
|
1
|
+
{"version":3,"file":"schemas.d.ts","sourceRoot":"","sources":["../../../../../src/builtin-extensions/pi-subagents/src/extension/schemas.ts"],"names":[],"mappings":"AACA;;GAEG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AA+I/B,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;EAoB7B,CAAC;AAEH,eAAO,MAAM,mBAAmB;;;;;;;;;EASG,CAAC;AAEpC,eAAO,MAAM,6BAA6B;;;;;;;;;;;;;;;;;;;;;;EAsBP,CAAC;AAEpC,eAAO,MAAM,oBAAoB;;;EAGE,CAAC;AAGpC,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAsCpB,CAAC;AA6FH,eAAO,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAA0D,CAAC;AAkBtF,eAAO,MAAM,kBAAkB;;;;;EAA8D,CAAC","sourcesContent":["// @ts-nocheck\n/**\n * TypeBox schemas for subagent tool parameters\n */\n\nimport { Type } from \"typebox\";\n\nfunction keepTopLevelParameterDescriptions<T>(schema: T): T {\n\treturn pruneNestedDescriptions(schema, []) as T;\n}\n\nfunction pruneNestedDescriptions(value: unknown, path: string[]): unknown {\n\tif (!value || typeof value !== \"object\") return value;\n\n\tconst result = Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value));\n\tfor (const key of Reflect.ownKeys(value)) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\tif (!descriptor) continue;\n\t\t// `description` is both JSON Schema help text and the child UI-label parameter.\n\t\tif (key === \"description\" && !isPropertiesMap(path) && !isTopLevelParameterHelpText(path)) continue;\n\t\tif (\"value\" in descriptor) {\n\t\t\tconst nextPath = typeof key === \"string\" ? [...path, key] : path;\n\t\t\tdescriptor.value = pruneNestedDescriptions(descriptor.value, nextPath);\n\t\t}\n\t\tObject.defineProperty(result, key, descriptor);\n\t}\n\treturn result;\n}\n\nfunction isPropertiesMap(path: string[]): boolean {\n\treturn path[path.length - 1] === \"properties\";\n}\n\nfunction isTopLevelParameterHelpText(path: string[]): boolean {\n\treturn path.length === 2 && path[0] === \"properties\";\n}\n\nconst SkillOverride = Type.Unsafe({\n\tanyOf: [\n\t\t{ type: \"array\", items: { type: \"string\" } },\n\t\t{ type: \"boolean\", enum: [false] },\n\t\t{ type: \"string\" },\n\t],\n\tdescription: \"Skill name(s) to make available (comma-separated), array of strings, or false to disable\",\n});\n\nconst OutputOverride = Type.Unsafe({\n\tanyOf: [\n\t\t{ type: \"string\" },\n\t\t{ type: \"boolean\", enum: [false] },\n\t],\n\tdescription: \"Output filename/path (string), or false to disable file output\",\n});\n\nconst OutputModeOverride = Type.String({\n\tenum: [\"inline\", \"file-only\"],\n\tdescription: \"Return saved output inline (default) or only a concise file reference. file-only requires output to be a path.\",\n});\n\nconst TIER_SELECTION_DESCRIPTION = \"Choose the lowest model tier that can reliably complete the task: 'light' for quick checks, fact gathering, and small code inspections; 'standard' for everyday coding, clearly described bugs, and focused reviews; 'heavy' for complex implementation, difficult debugging, architectural decisions, and large or high-risk reviews.\";\n\n// lunr: choose exactly one of tier or model per executable child.\nconst TierOverride = Type.Optional(Type.String({\n\tenum: [\"light\", \"standard\", \"heavy\"],\n\tdescription: `Required by default. ${TIER_SELECTION_DESCRIPTION} Do not combine with model. The configured tier model must be available and authenticated.`,\n}));\n\nconst ModelOverride = Type.Optional(Type.String({\n\tminLength: 1,\n\tdescription: \"Explicit provider/model id only when the user names a model. Do not combine with tier. Optional thinking belongs in the thinking field or as a known :level suffix.\",\n}));\n\nconst ThinkingOverride = Type.Optional(Type.String({\n\tenum: [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"],\n\tdescription: \"Thinking level for an explicit model launch. Omit for tier launches (they use configured tier thinking).\",\n}));\n\nconst ReadsOverride = Type.Unsafe({\n\tanyOf: [\n\t\t{ type: \"array\", items: { type: \"string\" } },\n\t\t{ type: \"boolean\", enum: [false] },\n\t],\n\tdescription: \"Files to read before running (array of filenames), or false to disable\",\n});\n\nconst JsonSchemaObject = Type.Unsafe({\n\ttype: \"object\",\n\tadditionalProperties: true,\n\tdescription: \"JSON Schema object for strict structured output. Non-object roots are rejected.\",\n});\n\nconst AcceptanceOverride = Type.Unsafe({\n\tanyOf: [\n\t\t{ type: \"string\", enum: [\"auto\", \"attested\", \"checked\", \"verified\", \"reviewed\"] },\n\t\t{ type: \"boolean\", enum: [false] },\n\t\t{ type: \"object\", additionalProperties: true },\n\t],\n\tdescription: \"Optional acceptance policy. Omitted means auto-inferred; verified requires configured runtime commands. Reviewed is inferred-only because explicit runs cannot supply an independent reviewer result. Bare \\\"none\\\" requires { level: \\\"none\\\", reason: \\\"...\\\" }, while false is deprecated.\",\n});\n\nconst TurnBudgetOverride = Type.Object({\n\tmaxTurns: Type.Integer({ minimum: 1 }),\n\tgraceTurns: Type.Optional(Type.Integer({ minimum: 0 })),\n}, { additionalProperties: false, description: \"Optional assistant-turn budget. At maxTurns the child is asked to wrap up; after graceTurns additional assistant turns it is aborted and partial output is returned.\" });\n\nconst ToolBudgetBlock = Type.Unsafe({\n\tanyOf: [\n\t\t{ type: \"array\", minItems: 1, items: { type: \"string\", minLength: 1 } },\n\t\t{ type: \"string\", enum: [\"*\"] },\n\t],\n});\n\nconst ToolBudgetOverride = Type.Object({\n\tsoft: Type.Optional(Type.Integer({ minimum: 1 })),\n\thard: Type.Integer({ minimum: 1 }),\n\tblock: Type.Optional(ToolBudgetBlock),\n}, { additionalProperties: false, description: \"Optional child tool-call budget. soft nudges the child; after hard, block tools (default read/grep/find/ls, or '*' for all tools) are blocked so the child can finalize.\" });\n\nconst DescriptionField = Type.String({\n\tminLength: 1,\n\tmaxLength: 80,\n\tdescription: \"Required concise single-line UI label (max 80 characters). Presentation metadata only; not used as an identifier.\",\n});\n\nconst PermissionsField = Type.Optional(Type.String({\n\tenum: [\"full\", \"read-only\"],\n\tdescription: \"Child permission level. Omit or 'full' for coding tools (read/search/shell/edit/write/web/LSP/MCP). 'read-only' inspects without edit/write. Read-only parents must pass 'read-only'.\",\n}));\n\nconst TaskItem = Type.Object({\n\ttask: Type.String({ description: \"Complete model-authored prompt sent to the child.\" }),\n\tdescription: DescriptionField,\n\tpermissions: PermissionsField,\n\tcwd: Type.Optional(Type.String()),\n\tcount: Type.Optional(Type.Integer({ minimum: 1, description: \"Repeat this parallel task N times with the same settings.\" })),\n\toutput: Type.Optional(OutputOverride),\n\toutputMode: Type.Optional(OutputModeOverride),\n\treads: Type.Optional(ReadsOverride),\n\tprogress: Type.Optional(Type.Boolean({ description: \"Enable progress.md tracking for this task\" })),\n\ttier: TierOverride,\n\tmodel: ModelOverride,\n\tthinking: ThinkingOverride,\n\tskill: Type.Optional(SkillOverride),\n\ttoolBudget: Type.Optional(ToolBudgetOverride),\n\tacceptance: Type.Optional(AcceptanceOverride),\n});\n\n// Parallel task item (within a parallel step)\nexport const ParallelTaskSchema = Type.Object({\n\ttask: Type.Optional(Type.String({ description: \"Task template with {task}, {previous}, {chain_dir} variables. Defaults to {previous}.\" })),\n\tdescription: DescriptionField,\n\tpermissions: PermissionsField,\n\tphase: Type.Optional(Type.String({ description: \"Optional phase/group label for status and graph rendering.\" })),\n\tlabel: Type.Optional(Type.String({ description: \"Optional user-facing label for this parallel task.\" })),\n\tas: Type.Optional(Type.String({ description: \"Optional safe identifier used as {outputs.name} in later chain steps.\" })),\n\toutputSchema: Type.Optional(JsonSchemaObject),\n\tcwd: Type.Optional(Type.String()),\n\tcount: Type.Optional(Type.Integer({ minimum: 1, description: \"Repeat this parallel task N times with the same settings.\" })),\n\toutput: Type.Optional(OutputOverride),\n\toutputMode: Type.Optional(OutputModeOverride),\n\treads: Type.Optional(ReadsOverride),\n\tprogress: Type.Optional(Type.Boolean({ description: \"Enable progress.md tracking in {chain_dir}\" })),\n\tskill: Type.Optional(SkillOverride),\n\ttier: TierOverride,\n\tmodel: ModelOverride,\n\tthinking: ThinkingOverride,\n\ttoolBudget: Type.Optional(ToolBudgetOverride),\n\tacceptance: Type.Optional(AcceptanceOverride),\n});\n\nexport const DynamicExpandSchema = Type.Object({\n\tfrom: Type.Object({\n\t\toutput: Type.String({ description: \"Prior named structured output to expand from.\" }),\n\t\tpath: Type.String({ description: \"JSON Pointer into the structured output, e.g. /items.\" }),\n\t}, { additionalProperties: false }),\n\titem: Type.Optional(Type.String({ description: \"Template variable name for each item. Defaults to item.\" })),\n\tkey: Type.Optional(Type.String({ description: \"JSON Pointer relative to each item for stable child ids.\" })),\n\tmaxItems: Type.Optional(Type.Integer({ minimum: 0, description: \"Required fanout bound unless configured globally.\" })),\n\tonEmpty: Type.Optional(Type.String({ enum: [\"skip\", \"fail\"], description: \"Empty input behavior. Defaults to skip.\" })),\n}, { additionalProperties: false });\n\nexport const DynamicParallelTemplateSchema = Type.Object({\n\ttask: Type.Optional(Type.String({ description: \"Task template with {item}, {item.path}, {task}, {previous}, {chain_dir}, and {outputs.name} variables.\" })),\n\tdescription: Type.String({\n\t\tminLength: 1,\n\t\tmaxLength: 80,\n\t\tdescription: \"Required concise single-line UI label. May use the same template variables as task. Maximum 80 characters.\",\n\t}),\n\tpermissions: PermissionsField,\n\tphase: Type.Optional(Type.String({ description: \"Optional phase/group label for status and graph rendering.\" })),\n\tlabel: Type.Optional(Type.String({ description: \"Optional user-facing label; item templates are supported.\" })),\n\toutputSchema: Type.Optional(JsonSchemaObject),\n\tcwd: Type.Optional(Type.String()),\n\toutput: Type.Optional(OutputOverride),\n\toutputMode: Type.Optional(OutputModeOverride),\n\treads: Type.Optional(ReadsOverride),\n\tprogress: Type.Optional(Type.Boolean({ description: \"Enable progress.md tracking in {chain_dir}\" })),\n\tskill: Type.Optional(SkillOverride),\n\ttier: TierOverride,\n\tmodel: ModelOverride,\n\tthinking: ThinkingOverride,\n\ttoolBudget: Type.Optional(ToolBudgetOverride),\n\tacceptance: Type.Optional(AcceptanceOverride),\n}, { additionalProperties: false });\n\nexport const DynamicCollectSchema = Type.Object({\n\tas: Type.String({ description: \"Safe output name for the ordered collected result array.\" }),\n\toutputSchema: Type.Optional(JsonSchemaObject),\n}, { additionalProperties: false });\n\n// Flattened so chain steps do not need an object-shape anyOf/oneOf union.\nexport const ChainItem = Type.Object({\n\ttask: Type.Optional(Type.String({\n\t\tdescription: \"Task template with variables: {task}=original request, {previous}=prior step's text response, {chain_dir}=shared folder, {outputs.name}=prior named output. Required for first sequential step, defaults to '{previous}' for subsequent steps.\"\n\t})),\n\tdescription: Type.Optional(DescriptionField),\n\tpermissions: PermissionsField,\n\tphase: Type.Optional(Type.String({ description: \"Optional phase/group label for status and graph rendering.\" })),\n\tlabel: Type.Optional(Type.String({ description: \"Optional user-facing label for this chain step.\" })),\n\tas: Type.Optional(Type.String({ description: \"Optional safe identifier used as {outputs.name} in later chain steps.\" })),\n\toutputSchema: Type.Optional(JsonSchemaObject),\n\tcwd: Type.Optional(Type.String()),\n\toutput: Type.Optional(OutputOverride),\n\toutputMode: Type.Optional(OutputModeOverride),\n\treads: Type.Optional(ReadsOverride),\n\tprogress: Type.Optional(Type.Boolean({ description: \"Enable progress.md tracking in {chain_dir}\" })),\n\tskill: Type.Optional(SkillOverride),\n\ttier: TierOverride,\n\tmodel: ModelOverride,\n\tthinking: ThinkingOverride,\n\ttoolBudget: Type.Optional(ToolBudgetOverride),\n\tacceptance: Type.Optional(AcceptanceOverride),\n\tparallel: Type.Optional(Type.Unsafe({\n\t\tanyOf: [\n\t\t\tType.Array(ParallelTaskSchema, { minItems: 1, description: \"Tasks to run in parallel\" }),\n\t\t\tDynamicParallelTemplateSchema,\n\t\t],\n\t\tdescription: \"Static parallel tasks array, or a single dynamic fanout child template when expand/collect are present.\",\n\t})),\n\texpand: Type.Optional(DynamicExpandSchema),\n\tcollect: Type.Optional(DynamicCollectSchema),\n\tconcurrency: Type.Optional(Type.Number({ description: \"Max concurrent tasks (default: unlimited)\" })),\n\tfailFast: Type.Optional(Type.Boolean({ description: \"Stop on first failure (default: false)\" })),\n\tworktree: Type.Optional(Type.Boolean({\n\t\tdescription: \"Create isolated git worktrees for each parallel task.\"\n\t})),\n}, {\n\tdescription: \"Chain step: use {task, description, tier|model, permissions?} for sequential, {parallel: [...]} for static concurrent execution, or {expand, parallel: {...}, collect} for dynamic fanout. Every executable child needs exactly one of tier or model.\",\n\tadditionalProperties: false,\n});\n\nconst ControlOverrides = Type.Object({\n\tenabled: Type.Optional(Type.Boolean({ description: \"Enable/disable subagent control attention tracking for this run\" })),\n\tneedsAttentionAfterMs: Type.Optional(Type.Integer({ minimum: 1, description: \"No-observed-activity window before a run needs attention\" })),\n\tactiveNoticeAfterMs: Type.Optional(Type.Integer({ minimum: 1, description: \"Active-long-running notice threshold by elapsed ms (default: 240000)\" })),\n\tactiveNoticeAfterTurns: Type.Optional(Type.Integer({ minimum: 1, description: \"Optional active-long-running notice threshold by assistant turns (disabled by default)\" })),\n\tactiveNoticeAfterTokens: Type.Optional(Type.Integer({ minimum: 1, description: \"Optional active-long-running notice threshold by total tokens (disabled by default)\" })),\n\tfailedToolAttemptsBeforeAttention: Type.Optional(Type.Integer({ minimum: 1, description: \"Consecutive mutating-tool failures before escalating to needs_attention (default: 3)\" })),\n\tnotifyOn: Type.Optional(Type.Array(Type.String({ enum: [\"active_long_running\", \"needs_attention\"] }), {\n\t\tdescription: \"Control event types that should notify the parent/orchestrator. Defaults to active_long_running and needs_attention.\",\n\t})),\n\tnotifyChannels: Type.Optional(Type.Array(Type.String({ enum: [\"event\", \"async\", \"intercom\"] }), {\n\t\tdescription: \"Notification channels to use when available. Defaults to event, async, and intercom.\",\n\t})),\n});\n\nconst SubagentParamsSchema = Type.Object({\n\ttask: Type.Optional(Type.String({ description: \"Complete model-authored prompt sent to the child (SINGLE mode).\" })),\n\tdescription: Type.Optional(DescriptionField),\n\tpermissions: PermissionsField,\n\t// Control action (when present, tool operates in control mode rather than execution)\n\taction: Type.Optional(Type.String({\n\t\tdescription: \"Control action only. Must be omitted for execution mode (single, parallel, or chain). Runtime: status, interrupt, stop, resume, steer, append-step, doctor, watchdog.*, schedule*.\",\n\t})),\n\tid: Type.Optional(Type.String({\n\t\tdescription: \"Run id or prefix for action='status', action='interrupt', action='stop', action='resume', action='steer', or action='append-step'.\"\n\t})),\n\trunId: Type.Optional(Type.String({\n\t\tdescription: \"Target run ID for action='interrupt', action='stop', action='resume', action='steer', or action='append-step'. Prefer id for new calls.\"\n\t})),\n\tdir: Type.Optional(Type.String({\n\t\tdescription: \"Async run directory for action='status', action='stop', action='resume', or action='steer'.\"\n\t})),\n\tindex: Type.Optional(Type.Integer({ minimum: 0, description: \"Zero-based child index for actions that target a specific child or transcript.\" })),\n\tview: Type.Optional(Type.String({\n\t\tenum: [\"fleet\", \"transcript\"],\n\t\tdescription: \"Optional status view. Use view='fleet' for a read-only active foreground/async fleet surface, or view='transcript' with id/dir (and optional index) to tail a run transcript.\",\n\t})),\n\tlines: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: \"Maximum transcript lines for action='status', view='transcript'. Defaults to 80.\" })),\n\tmessage: Type.Optional(Type.String({ description: \"Follow-up message for action='resume' or non-terminal guidance for action='steer'. Use index to choose a child from multi-child runs.\" })),\n\tschedule: Type.Optional(Type.String({ description: \"Explicit one-shot schedule for action='schedule'. Only honored when scheduledRuns.enabled is true. Use '+10m' or a future ISO timestamp with timezone; scheduled runs always launch async with fresh context.\" })),\n\tscheduleName: Type.Optional(Type.String({ description: \"Optional display name for action='schedule'.\" })),\n\ttasks: Type.Optional(Type.Array(TaskItem, { description: \"PARALLEL mode: [{task, description, tier|model, thinking?, permissions?, count?, output?, outputMode?, reads?, progress?}, ...]\" })),\n\tconcurrency: Type.Optional(Type.Integer({ minimum: 1, description: \"Top-level PARALLEL mode only: max concurrent tasks. Defaults to config.parallel.concurrency or unlimited.\" })),\n\tworktree: Type.Optional(Type.Boolean({\n\t\tdescription: \"Create isolated git worktrees for parallel tasks; requires clean git state.\"\n\t})),\n\tchain: Type.Optional(Type.Array(ChainItem, { description: \"CHAIN mode: sequential steps; each result becomes {previous}. append-step takes one tail step and may use {chain_dir}/{outputs.name}.\" })),\n\tcontext: Type.Optional(Type.String({\n\t\tenum: [\"fresh\"],\n\t\tdescription: \"Children always start with a fresh session. Fork context is not available.\",\n\t})),\n\tchainDir: Type.Optional(Type.String({ description: \"Persistent chain artifact directory; defaults to user-scoped temp storage.\" })),\n\tasync: Type.Optional(Type.Boolean({ description: \"Run async in the background. Defaults to true when omitted; set false for immediate foreground results.\" })),\n\ttimeoutMs: Type.Optional(Type.Integer({ minimum: 1, description: \"Optional run-level timeout in ms for foreground and async/background runs. Alias of maxRuntimeMs.\" })),\n\tmaxRuntimeMs: Type.Optional(Type.Integer({ minimum: 1, description: \"Alias of timeoutMs for optional run-level timeout in foreground and async/background runs.\" })),\n\tturnBudget: Type.Optional(TurnBudgetOverride),\n\ttoolBudget: Type.Optional(ToolBudgetOverride),\n\tcwd: Type.Optional(Type.String()),\n\tartifacts: Type.Optional(Type.Boolean({ description: \"Write debug artifacts (default: true)\" })),\n\tincludeProgress: Type.Optional(Type.Boolean({ description: \"Include full progress in result (default: false)\" })),\n\tshare: Type.Optional(Type.Boolean({ description: \"Upload session to GitHub Gist for sharing (default: false)\" })),\n\tsessionDir: Type.Optional(\n\t\tType.String({ description: \"Directory to store session logs (default: temp; enables sessions even if share=false)\" }),\n\t),\n\t// Clarification TUI\n\tclarify: Type.Optional(Type.Boolean({ description: \"Show the interactive TUI preview/editor before execution. clarify:true keeps the run foreground even when async is omitted or true.\" })),\n\tcontrol: Type.Optional(ControlOverrides),\n\toutput: Type.Optional(Type.Unsafe({\n\t\tanyOf: [\n\t\t\t{ type: \"string\" },\n\t\t\t{ type: \"boolean\", enum: [false] },\n\t\t],\n\t\tdescription: \"Output file for a single child (string), or false to disable. Relative paths resolve against cwd.\",\n\t})),\n\toutputMode: Type.Optional(OutputModeOverride),\n\tskill: Type.Optional(SkillOverride),\n\ttier: Type.Optional(Type.String({\n\t\tenum: [\"light\", \"standard\", \"heavy\"],\n\t\tdescription: `Preferred for SINGLE execution. Required by default. Omit for control actions. Do not combine with model; PARALLEL and CHAIN children carry their own tier or model. ${TIER_SELECTION_DESCRIPTION}`,\n\t})),\n\tmodel: Type.Optional(Type.String({\n\t\tminLength: 1,\n\t\tdescription: \"Explicit provider/model for SINGLE execution only when the user names a model. Do not combine with tier.\",\n\t})),\n\tthinking: Type.Optional(Type.String({\n\t\tenum: [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"],\n\t\tdescription: \"Thinking level for an explicit model launch. Tier launches use configured tier thinking instead.\",\n\t})),\n\tacceptance: Type.Optional(AcceptanceOverride),\n});\n\nexport const SubagentParams = keepTopLevelParameterDescriptions(SubagentParamsSchema);\n\nconst SubagentWaitParamsSchema = Type.Object({\n\tid: Type.Optional(Type.String({\n\t\tdescription: \"Async run or remembered detached foreground run id/prefix to wait for one specific run. Omit to wait across every active async run started in this session.\",\n\t})),\n\tquestionId: Type.Optional(Type.String({\n\t\tdescription: \"Wait for one supervisor question id from subagent_supervisor action='ask'. Returns when that question is answered, expired, or cancelled. Separate from final async run results.\",\n\t})),\n\tall: Type.Optional(Type.Boolean({\n\t\tdescription: \"Wait for ALL active runs to finish. Default false: return as soon as the first run finishes, so a fleet manager can spawn a replacement and wait again. Ignored when id or questionId targets one item.\",\n\t})),\n\ttimeoutMs: Type.Optional(Type.Integer({\n\t\tminimum: 1,\n\t\tdescription: \"Give up waiting after this many milliseconds (the runs keep going regardless). Defaults to 1800000 (30 minutes).\",\n\t})),\n});\n\nexport const SubagentWaitParams = keepTopLevelParameterDescriptions(SubagentWaitParamsSchema);\n"]}
|
|
@@ -106,7 +106,7 @@ const DescriptionField = Type.String({
|
|
|
106
106
|
});
|
|
107
107
|
const PermissionsField = Type.Optional(Type.String({
|
|
108
108
|
enum: ["full", "read-only"],
|
|
109
|
-
description: "Child permission level. Omit or 'full' for coding tools (read/search/shell/edit/write/web/LSP/MCP). 'read-only' inspects without edit/write.
|
|
109
|
+
description: "Child permission level. Omit or 'full' for coding tools (read/search/shell/edit/write/web/LSP/MCP). 'read-only' inspects without edit/write. Read-only parents must pass 'read-only'.",
|
|
110
110
|
}));
|
|
111
111
|
const TaskItem = Type.Object({
|
|
112
112
|
task: Type.String({ description: "Complete model-authored prompt sent to the child." }),
|