dal-code 1.0.44 → 1.0.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (426) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/NOTICE +17 -0
  3. package/PRIVACY.md +159 -102
  4. package/dal-docs/README.md +1 -1
  5. package/dal-docs/keybindings.md +1 -0
  6. package/dal-docs/settings.md +5 -0
  7. package/dist/cli/credential-print.js +1 -1
  8. package/dist/config.d.ts +1 -0
  9. package/dist/config.js +1 -1
  10. package/dist/core/agent-session-runtime.js +1 -1
  11. package/dist/core/agent-session.d.ts +1 -1
  12. package/dist/core/agent-session.js +5 -5
  13. package/dist/core/auth-storage.js +1 -1
  14. package/dist/core/background-processes.js +7 -7
  15. package/dist/core/export-html/template.js +34 -34
  16. package/dist/core/extensions/runner.js +1 -1
  17. package/dist/core/extensions/types.d.ts +5 -1
  18. package/dist/core/key-id-schema.js +1 -0
  19. package/dist/core/keybindings-schema.js +1 -0
  20. package/dist/core/keybindings.d.ts +5 -0
  21. package/dist/core/keybindings.js +1 -1
  22. package/dist/core/model-config.d.ts +818 -99
  23. package/dist/core/model-config.js +5 -5
  24. package/dist/core/model-resolver.d.ts +30 -10
  25. package/dist/core/model-resolver.js +1 -1
  26. package/dist/core/model-runtime.d.ts +1 -0
  27. package/dist/core/model-runtime.js +2 -2
  28. package/dist/core/package-manager.d.ts +5 -0
  29. package/dist/core/package-manager.js +2 -2
  30. package/dist/core/permissions/shell-words.d.ts +26 -0
  31. package/dist/core/project-trust.js +2 -2
  32. package/dist/core/prompt-templates.js +2 -2
  33. package/dist/core/remote-catalog-provider.js +1 -1
  34. package/dist/core/resource-loader.js +1 -1
  35. package/dist/core/sandbox/libreoffice.js +1 -0
  36. package/dist/core/sandbox/runtime.d.ts +1 -0
  37. package/dist/core/sandbox/runtime.js +1 -1
  38. package/dist/core/sandbox/shell-sandbox.js +6 -6
  39. package/dist/core/sandbox/windows.js +4 -4
  40. package/dist/core/session-manager.d.ts +1 -0
  41. package/dist/core/session-manager.js +12 -12
  42. package/dist/core/settings-defaults.js +1 -0
  43. package/dist/core/settings-manager.d.ts +5 -0
  44. package/dist/core/settings-manager.js +1 -1
  45. package/dist/core/settings-schema.d.ts +229 -0
  46. package/dist/core/settings-schema.js +1 -0
  47. package/dist/core/tools/bash-read-only.d.ts +1 -0
  48. package/dist/core/tools/read.js +12 -12
  49. package/dist/core/tools/render-utils.d.ts +40 -0
  50. package/dist/core/tools/render-utils.js +7 -7
  51. package/dist/core/tools/renderers/read.js +8 -8
  52. package/dist/core/trust-manager.js +1 -1
  53. package/dist/core/workspace-lock.d.ts +6 -2
  54. package/dist/core/workspace-lock.js +3 -3
  55. package/dist/dal/extension-compat.js +4 -4
  56. package/dist/dal/hooks/config.d.ts +5 -1
  57. package/dist/dal/hooks/config.js +1 -1
  58. package/dist/dal/hooks/extension.js +3 -3
  59. package/dist/dal/hooks/index.d.ts +1 -1
  60. package/dist/dal/hooks/index.js +1 -1
  61. package/dist/dal/i18n.js +1 -1
  62. package/dist/dal/manifest.js +1 -1
  63. package/dist/extensions/codemode/execute.js +14 -13
  64. package/dist/extensions/codemode/index.js +1 -1
  65. package/dist/extensions/codemode/renderer.js +6 -6
  66. package/dist/extensions/codemode/tool.d.ts +2 -3
  67. package/dist/extensions/codemode/tool.js +9 -12
  68. package/dist/extensions/mcp/cli.js +4 -4
  69. package/dist/extensions/mcp/index.js +12 -12
  70. package/dist/extensions/mcp/resources.d.ts +0 -5
  71. package/dist/extensions/mcp/resources.js +1 -1
  72. package/dist/extensions/mcp/runtime.d.ts +1 -4
  73. package/dist/extensions/mcp/runtime.js +3 -3
  74. package/dist/extensions/mcp/tools.js +7 -7
  75. package/dist/extensions/tool-search/tool.js +3 -3
  76. package/dist/index.d.ts +5 -2
  77. package/dist/index.js +1 -1
  78. package/dist/main.js +3 -3
  79. package/dist/migrations.js +5 -5
  80. package/dist/modes/interactive/components/settings-selector.d.ts +3 -1
  81. package/dist/modes/interactive/components/settings-selector.js +1 -1
  82. package/dist/modes/interactive/components/status-indicator.d.ts +1 -1
  83. package/dist/modes/interactive/components/status-indicator.js +1 -1
  84. package/dist/modes/interactive/components/tree-selector.js +1 -1
  85. package/dist/modes/interactive/interactive-mode.js +17 -17
  86. package/dist/modes/interactive/session-share.js +2 -2
  87. package/dist/modes/interactive/theme/dark.json +1 -1
  88. package/dist/modes/interactive/theme/light.json +1 -1
  89. package/dist/modes/interactive/theme/theme-schema.d.ts +18 -0
  90. package/dist/modes/interactive/theme/theme-schema.js +12 -0
  91. package/dist/modes/interactive/theme/theme-tokens.d.ts +255 -0
  92. package/dist/modes/interactive/theme/theme-tokens.js +1 -0
  93. package/dist/modes/interactive/theme/theme.d.ts +7 -10
  94. package/dist/modes/interactive/theme/theme.js +5 -5
  95. package/dist/modes/rpc/rpc-client.d.ts +5 -1
  96. package/dist/modes/rpc/rpc-client.js +2 -2
  97. package/dist/modes/rpc/rpc-mode.js +1 -1
  98. package/dist/modes/rpc/rpc-types.d.ts +20 -0
  99. package/dist/node_modules/@dalcode/dal-advisor/package.json +3 -3
  100. package/dist/node_modules/@dalcode/dal-advisor/src/index.js +8 -8
  101. package/dist/node_modules/@dalcode/dal-awake/package.json +2 -2
  102. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  103. package/dist/node_modules/@dalcode/dal-capabilities/package.json +4 -4
  104. package/dist/node_modules/@dalcode/dal-capabilities/src/index.js +10 -10
  105. package/dist/node_modules/@dalcode/dal-codeindex/package.json +34 -0
  106. package/dist/node_modules/@dalcode/dal-codeindex/src/extract.js +3 -0
  107. package/dist/node_modules/@dalcode/dal-codeindex/src/format.js +11 -0
  108. package/dist/node_modules/@dalcode/dal-codeindex/src/index.js +4 -0
  109. package/dist/node_modules/@dalcode/dal-codeindex/src/indexer.js +1 -0
  110. package/dist/node_modules/@dalcode/dal-codeindex/src/languages.js +176 -0
  111. package/dist/node_modules/@dalcode/dal-codeindex/src/project.js +1 -0
  112. package/dist/node_modules/@dalcode/dal-codeindex/src/query.js +2 -0
  113. package/dist/node_modules/@dalcode/dal-codeindex/src/runtime.js +1 -0
  114. package/dist/node_modules/@dalcode/dal-codeindex/src/scan.js +1 -0
  115. package/dist/node_modules/@dalcode/dal-codeindex/src/semantic.js +2 -0
  116. package/dist/node_modules/@dalcode/dal-codeindex/src/sqlite.js +1 -0
  117. package/dist/node_modules/@dalcode/dal-codeindex/src/store.js +33 -0
  118. package/dist/node_modules/@dalcode/dal-codeindex/src/worker.js +1 -0
  119. package/dist/node_modules/@dalcode/dal-compat/package.json +2 -2
  120. package/dist/node_modules/@dalcode/dal-dap/package.json +2 -2
  121. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  122. package/dist/node_modules/@dalcode/dal-goal/package.json +3 -3
  123. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  124. package/dist/node_modules/@dalcode/dal-guard/src/index.js +4 -2
  125. package/dist/node_modules/@dalcode/dal-guard/src/mode.js +2 -2
  126. package/dist/node_modules/@dalcode/dal-guard/src/policy.js +1 -0
  127. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  128. package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
  129. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  130. package/dist/node_modules/@dalcode/dal-learn/package.json +2 -2
  131. package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
  132. package/dist/node_modules/@dalcode/dal-lsp/src/index.js +12 -10
  133. package/dist/node_modules/@dalcode/dal-mcp/package.json +7 -5
  134. package/dist/node_modules/@dalcode/dal-mcp/src/http-client.d.ts +9 -27
  135. package/dist/node_modules/@dalcode/dal-mcp/src/http-client.js +1 -2
  136. package/dist/node_modules/@dalcode/dal-mcp/src/index.js +17 -17
  137. package/dist/node_modules/@dalcode/dal-mcp/src/protocol-client.d.ts +38 -0
  138. package/dist/node_modules/@dalcode/dal-mcp/src/protocol-client.js +1 -0
  139. package/dist/node_modules/@dalcode/dal-mcp/src/proxy.js +6 -6
  140. package/dist/node_modules/@dalcode/dal-mcp/src/resources.js +1 -0
  141. package/dist/node_modules/@dalcode/dal-mcp/src/stdio-client.d.ts +9 -18
  142. package/dist/node_modules/@dalcode/dal-mcp/src/stdio-client.js +4 -5
  143. package/dist/node_modules/@dalcode/dal-mcp/src/types.d.ts +50 -5
  144. package/dist/node_modules/@dalcode/dal-mcp/src/types.js +1 -1
  145. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  146. package/dist/node_modules/@dalcode/dal-office/src/index.d.ts +2 -2
  147. package/dist/node_modules/@dalcode/dal-office/src/index.js +1 -1
  148. package/dist/node_modules/@dalcode/dal-office/src/render/docx.js +1 -1
  149. package/dist/node_modules/@dalcode/dal-office/src/render/pptx.d.ts +8 -0
  150. package/dist/node_modules/@dalcode/dal-office/src/render/pptx.js +3 -3
  151. package/dist/node_modules/@dalcode/dal-office/src/render/xlsx.js +1 -1
  152. package/dist/node_modules/@dalcode/dal-office/src/themes.d.ts +2 -0
  153. package/dist/node_modules/@dalcode/dal-office/src/themes.js +1 -1
  154. package/dist/node_modules/@dalcode/dal-office/src/tools/ppt-generate.js +3 -2
  155. package/dist/node_modules/@dalcode/dal-office/src/tools/ppt-plan.js +2 -2
  156. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +9 -3
  157. package/dist/node_modules/@dalcode/dal-pi-kit/dist/index.js +1 -1
  158. package/dist/node_modules/@dalcode/dal-pi-kit/dist/session-scope.js +1 -0
  159. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  160. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +9 -3
  161. package/dist/node_modules/@dalcode/dal-pi-kit/src/index.js +1 -1
  162. package/dist/node_modules/@dalcode/dal-pi-kit/src/session-scope.js +1 -0
  163. package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -4
  164. package/dist/node_modules/@dalcode/dal-plugins/src/brand.js +1 -1
  165. package/dist/node_modules/@dalcode/dal-plugins/src/index.js +11 -11
  166. package/dist/node_modules/@dalcode/dal-recall/package.json +2 -2
  167. package/dist/node_modules/@dalcode/dal-remote/package.json +2 -2
  168. package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
  169. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  170. package/dist/node_modules/@dalcode/dal-rewind/src/core.d.ts +0 -1
  171. package/dist/node_modules/@dalcode/dal-rewind/src/core.js +8 -8
  172. package/dist/node_modules/@dalcode/dal-rewind/src/index.js +1 -1
  173. package/dist/node_modules/@dalcode/dal-router/package.json +9 -5
  174. package/dist/node_modules/@dalcode/dal-router/src/advisor.js +1 -1
  175. package/dist/node_modules/@dalcode/dal-router/src/commands.js +8 -7
  176. package/dist/node_modules/@dalcode/dal-router/src/config.d.ts +11 -0
  177. package/dist/node_modules/@dalcode/dal-router/src/config.js +2 -2
  178. package/dist/node_modules/@dalcode/dal-router/src/index.js +4 -4
  179. package/dist/node_modules/@dalcode/dal-router/src/roles/changes.js +5 -0
  180. package/dist/node_modules/@dalcode/dal-router/src/roles/index.js +13 -0
  181. package/dist/node_modules/@dalcode/dal-router/src/roles/models.d.ts +50 -0
  182. package/dist/node_modules/@dalcode/dal-router/src/roles/models.js +1 -0
  183. package/dist/node_modules/@dalcode/dal-router/src/roles/prompts.js +40 -0
  184. package/dist/node_modules/@dalcode/dal-router/src/roles/signals.js +2 -0
  185. package/dist/node_modules/@dalcode/dal-router/src/runtime.d.ts +3 -0
  186. package/dist/node_modules/@dalcode/dal-router/src/runtime.js +1 -1
  187. package/dist/node_modules/@dalcode/dal-router/src/subagent.js +1 -1
  188. package/dist/node_modules/@dalcode/dal-rtk/package.json +2 -2
  189. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  190. package/dist/node_modules/@dalcode/dal-skills/src/bundled/dal-slides/SKILL.md +74 -0
  191. package/dist/node_modules/@dalcode/dal-skills/src/bundled.js +1 -1
  192. package/dist/node_modules/@dalcode/dal-skills/src/client.js +1 -1
  193. package/dist/node_modules/@dalcode/dal-skills/src/index.js +14 -14
  194. package/dist/node_modules/@dalcode/dal-skills/src/packages.js +3 -3
  195. package/dist/node_modules/@dalcode/dal-skills/src/search.js +1 -1
  196. package/dist/node_modules/@dalcode/dal-statusline/package.json +2 -2
  197. package/dist/node_modules/@dalcode/dal-structured/package.json +2 -2
  198. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  199. package/dist/node_modules/@dalcode/dal-telemetry/package.json +3 -3
  200. package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
  201. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  202. package/dist/node_modules/@dalcode/dal-tool-catalog/src/index.js +4 -4
  203. package/dist/node_modules/@dalcode/dal-usage/package.json +2 -2
  204. package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
  205. package/dist/node_modules/@dalcode/dal-workflow/LICENSE +27 -0
  206. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  207. package/dist/node_modules/@dalcode/dal-workflow/src/index.js +4 -4
  208. package/dist/node_modules/@dalcode/dal-workflow/src/plan-mode.js +13 -13
  209. package/dist/node_modules/@dalcode/dal-workflow/src/todo-snapshot.js +2 -0
  210. package/dist/node_modules/@dalcode/dal-workflow/src/todo.js +4 -4
  211. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  212. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
  213. package/dist/node_modules/@earendil-works/pi-ai/README.md +5 -34
  214. package/dist/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js +5 -5
  215. package/dist/node_modules/@earendil-works/pi-ai/dist/api/google-shared.js +1 -1
  216. package/dist/node_modules/@earendil-works/pi-ai/dist/api/mistral-conversations.js +4 -4
  217. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.js +1 -1
  218. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js +6 -6
  219. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js +2 -2
  220. package/dist/node_modules/@earendil-works/pi-ai/dist/index.d.ts +0 -1
  221. package/dist/node_modules/@earendil-works/pi-ai/dist/index.js +1 -1
  222. package/dist/node_modules/@earendil-works/pi-ai/dist/models.d.ts +1 -0
  223. package/dist/node_modules/@earendil-works/pi-ai/dist/models.js +1 -1
  224. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/compat-schema.d.ts +359 -0
  225. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/compat-schema.js +1 -0
  226. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  227. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
  228. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/anthropic.json +1 -1
  229. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/azure.json +1 -1
  230. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/baseten.json +1 -1
  231. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cerebras.json +1 -1
  232. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
  233. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
  234. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
  235. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/github-copilot.json +1 -1
  236. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/google.json +1 -1
  237. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/groq.json +1 -1
  238. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/huggingface.json +1 -1
  239. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/kimi-coding.json +1 -1
  240. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/minimax-cn.json +1 -1
  241. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/minimax.json +1 -1
  242. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/mistral.json +1 -1
  243. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/moonshotai-cn.json +1 -1
  244. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/nvidia.json +1 -1
  245. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openai-codex.json +1 -1
  246. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openai.json +1 -1
  247. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
  248. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  249. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  250. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/qwen-token-plan-cn.json +1 -1
  251. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/qwen-token-plan.json +1 -1
  252. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/radius.json +1 -1
  253. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/together.json +1 -1
  254. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  255. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xai.json +1 -1
  256. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi-token-plan-ams.json +1 -1
  257. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi-token-plan-cn.json +1 -1
  258. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi-token-plan-sgp.json +1 -1
  259. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi.json +1 -1
  260. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/kimi-coding.js +1 -1
  261. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/model-schema.d.ts +90 -0
  262. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/model-schema.js +1 -0
  263. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/openrouter-api.js +1 -0
  264. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/openrouter.js +1 -1
  265. package/dist/node_modules/@earendil-works/pi-ai/dist/types.d.ts +5 -146
  266. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/retry.js +1 -1
  267. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
  268. package/dist/node_modules/@earendil-works/pi-codemode/README.md +195 -11
  269. package/dist/node_modules/@earendil-works/pi-codemode/dist/cloudflare.js +1 -0
  270. package/dist/node_modules/@earendil-works/pi-codemode/dist/declarations.d.ts +0 -2
  271. package/dist/node_modules/@earendil-works/pi-codemode/dist/declarations.js +9 -84
  272. package/dist/node_modules/@earendil-works/pi-codemode/dist/index.d.ts +5 -2
  273. package/dist/node_modules/@earendil-works/pi-codemode/dist/index.js +1 -1
  274. package/dist/node_modules/@earendil-works/pi-codemode/dist/portable.js +1 -0
  275. package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/execution.d.ts +29 -0
  276. package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/execution.js +1 -0
  277. package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/host.d.ts +3 -16
  278. package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/host.js +1 -1
  279. package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/inline.d.ts +13 -0
  280. package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/inline.js +1 -0
  281. package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/prelude-source.js +14 -6
  282. package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/protocol.d.ts +72 -0
  283. package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/protocol.js +1 -1
  284. package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/remote.d.ts +32 -0
  285. package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/remote.js +1 -0
  286. package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/vm.js +3 -0
  287. package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/worker.js +1 -3
  288. package/dist/node_modules/@earendil-works/pi-codemode/dist/source.js +4 -3
  289. package/dist/node_modules/@earendil-works/pi-codemode/dist/types.d.ts +51 -1
  290. package/dist/node_modules/@earendil-works/pi-codemode/package.json +14 -2
  291. package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
  292. package/dist/node_modules/@earendil-works/pi-mcp/CHANGELOG.md +13 -0
  293. package/dist/node_modules/@earendil-works/pi-mcp/dist/client.js +1 -1
  294. package/dist/node_modules/@earendil-works/pi-mcp/dist/index.d.ts +1 -1
  295. package/dist/node_modules/@earendil-works/pi-mcp/dist/oauth/errors.d.ts +2 -2
  296. package/dist/node_modules/@earendil-works/pi-mcp/dist/oauth/errors.js +1 -1
  297. package/dist/node_modules/@earendil-works/pi-mcp/dist/oauth/flow.js +1 -1
  298. package/dist/node_modules/@earendil-works/pi-mcp/dist/protocol/content.d.ts +1 -1
  299. package/dist/node_modules/@earendil-works/pi-mcp/dist/transports/streamable-http.d.ts +2 -2
  300. package/dist/node_modules/@earendil-works/pi-mcp/dist/transports/streamable-http.js +4 -4
  301. package/dist/node_modules/@earendil-works/pi-mcp/dist/transports/transport.d.ts +4 -1
  302. package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
  303. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  304. package/dist/node_modules/@earendil-works/pi-tui/README.md +5 -3
  305. package/dist/node_modules/@earendil-works/pi-tui/dist/components/editor.js +6 -6
  306. package/dist/node_modules/@earendil-works/pi-tui/dist/components/input.js +2 -2
  307. package/dist/node_modules/@earendil-works/pi-tui/dist/index.d.ts +1 -1
  308. package/dist/node_modules/@earendil-works/pi-tui/dist/index.js +1 -1
  309. package/dist/node_modules/@earendil-works/pi-tui/dist/keys.js +5 -5
  310. package/dist/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.js +1 -1
  311. package/dist/node_modules/@earendil-works/pi-tui/dist/terminal-image.js +1 -1
  312. package/dist/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.js +3 -3
  313. package/dist/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.js +1 -1
  314. package/dist/node_modules/@earendil-works/pi-tui/dist/tui.d.ts +4 -0
  315. package/dist/node_modules/@earendil-works/pi-tui/dist/tui.js +2 -2
  316. package/dist/node_modules/@earendil-works/pi-tui/dist/utils.js +1 -1
  317. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  318. package/dist/sdk/index.d.ts +3 -3
  319. package/dist/sdk/index.js +1 -1
  320. package/dist/sdk/rewind.d.ts +1 -1
  321. package/dist/sdk/rewind.js +1 -1
  322. package/dist/utils/clipboard.js +1 -1
  323. package/dist/utils/output-files.js +1 -1
  324. package/dist/utils/temp-files.js +1 -0
  325. package/docs/security.md +24 -7
  326. package/examples/README.md +0 -3
  327. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  328. package/examples/extensions/dynamic-resources/dynamic.json +1 -1
  329. package/examples/extensions/gondolin/package-lock.json +2 -2
  330. package/examples/extensions/gondolin/package.json +1 -1
  331. package/examples/extensions/minimal-mode.ts +4 -5
  332. package/examples/extensions/overlay-test.ts +2 -2
  333. package/examples/extensions/sandbox/package-lock.json +2 -2
  334. package/examples/extensions/sandbox/package.json +1 -1
  335. package/examples/extensions/subagent/index.ts +4 -6
  336. package/examples/extensions/with-deps/package-lock.json +2 -2
  337. package/examples/extensions/with-deps/package.json +1 -1
  338. package/npm-shrinkwrap.json +9 -460
  339. package/package.json +3 -12
  340. package/dist/modes/interactive/theme/theme-json.d.ts +0 -75
  341. package/dist/modes/interactive/theme/theme-json.js +0 -12
  342. package/dist/modes/interactive/theme/theme-schema.json +0 -361
  343. package/dist/node_modules/@earendil-works/chord/README.md +0 -264
  344. package/dist/node_modules/@earendil-works/chord/dist/api.js +0 -1
  345. package/dist/node_modules/@earendil-works/chord/dist/bundler.js +0 -1
  346. package/dist/node_modules/@earendil-works/chord/dist/context/index.js +0 -1
  347. package/dist/node_modules/@earendil-works/chord/dist/delta/apply-immutable-trusted.js +0 -1
  348. package/dist/node_modules/@earendil-works/chord/dist/delta/diff.js +0 -1
  349. package/dist/node_modules/@earendil-works/chord/dist/delta/draft.js +0 -0
  350. package/dist/node_modules/@earendil-works/chord/dist/delta/index.js +0 -1
  351. package/dist/node_modules/@earendil-works/chord/dist/delta/revision-validator.js +0 -1
  352. package/dist/node_modules/@earendil-works/chord/dist/delta/tracker.js +0 -1
  353. package/dist/node_modules/@earendil-works/chord/dist/facets/host.js +0 -1
  354. package/dist/node_modules/@earendil-works/chord/dist/facets/loader.js +0 -1
  355. package/dist/node_modules/@earendil-works/chord/dist/index.js +0 -1
  356. package/dist/node_modules/@earendil-works/chord/dist/json.js +0 -1
  357. package/dist/node_modules/@earendil-works/chord/dist/node/bundle-loader.js +0 -2
  358. package/dist/node_modules/@earendil-works/chord/dist/node/bundle.js +0 -4
  359. package/dist/node_modules/@earendil-works/chord/dist/node/manifest.js +0 -1
  360. package/dist/node_modules/@earendil-works/chord/dist/node/package.js +0 -1
  361. package/dist/node_modules/@earendil-works/chord/dist/node.js +0 -1
  362. package/dist/node_modules/@earendil-works/chord/dist/services/consumer.js +0 -1
  363. package/dist/node_modules/@earendil-works/chord/dist/services/errors.js +0 -1
  364. package/dist/node_modules/@earendil-works/chord/dist/services/handle.js +0 -1
  365. package/dist/node_modules/@earendil-works/chord/dist/services/instances.js +0 -1
  366. package/dist/node_modules/@earendil-works/chord/dist/services/loopback.js +0 -1
  367. package/dist/node_modules/@earendil-works/chord/dist/services/provider.js +0 -1
  368. package/dist/node_modules/@earendil-works/chord/dist/services/state-codec.js +0 -1
  369. package/dist/node_modules/@earendil-works/chord/dist/services/state-internals.js +0 -1
  370. package/dist/node_modules/@earendil-works/chord/dist/services/state.js +0 -1
  371. package/dist/node_modules/@earendil-works/chord/dist/services/wire.js +0 -1
  372. package/dist/node_modules/@earendil-works/chord/dist/types.js +0 -0
  373. package/dist/node_modules/@earendil-works/chord/package.json +0 -62
  374. package/dist/node_modules/@earendil-works/chord/src/delta/README.md +0 -191
  375. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/assistant-message-frame.d.ts +0 -63
  376. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/assistant-message-frame.js +0 -1
  377. package/dist/node_modules/@earendil-works/pi-client/CHANGELOG.md +0 -45
  378. package/dist/node_modules/@earendil-works/pi-client/LICENSE +0 -21
  379. package/dist/node_modules/@earendil-works/pi-client/README.md +0 -72
  380. package/dist/node_modules/@earendil-works/pi-client/dist/client.js +0 -1
  381. package/dist/node_modules/@earendil-works/pi-client/dist/connection.js +0 -1
  382. package/dist/node_modules/@earendil-works/pi-client/dist/errors.js +0 -1
  383. package/dist/node_modules/@earendil-works/pi-client/dist/index.js +0 -1
  384. package/dist/node_modules/@earendil-works/pi-client/dist/promise.js +0 -1
  385. package/dist/node_modules/@earendil-works/pi-client/dist/transport.js +0 -0
  386. package/dist/node_modules/@earendil-works/pi-client/dist/types.js +0 -0
  387. package/dist/node_modules/@earendil-works/pi-client/dist/unix.js +0 -1
  388. package/dist/node_modules/@earendil-works/pi-client/package.json +0 -46
  389. package/dist/node_modules/@earendil-works/pi-protocol/LICENSE +0 -21
  390. package/dist/node_modules/@earendil-works/pi-protocol/README.md +0 -41
  391. package/dist/node_modules/@earendil-works/pi-protocol/dist/cbor/decoder.js +0 -1
  392. package/dist/node_modules/@earendil-works/pi-protocol/dist/cbor/encoder.js +0 -1
  393. package/dist/node_modules/@earendil-works/pi-protocol/dist/cbor/index.js +0 -1
  394. package/dist/node_modules/@earendil-works/pi-protocol/dist/cbor/options.js +0 -1
  395. package/dist/node_modules/@earendil-works/pi-protocol/dist/codec.js +0 -1
  396. package/dist/node_modules/@earendil-works/pi-protocol/dist/framing.js +0 -1
  397. package/dist/node_modules/@earendil-works/pi-protocol/dist/index.js +0 -1
  398. package/dist/node_modules/@earendil-works/pi-protocol/dist/protocol.js +0 -1
  399. package/dist/node_modules/@earendil-works/pi-protocol/dist/schemas.js +0 -1
  400. package/dist/node_modules/@earendil-works/pi-protocol/package.json +0 -39
  401. package/dist/node_modules/@earendil-works/pi-server/CHANGELOG.md +0 -81
  402. package/dist/node_modules/@earendil-works/pi-server/LICENSE +0 -21
  403. package/dist/node_modules/@earendil-works/pi-server/README.md +0 -63
  404. package/dist/node_modules/@earendil-works/pi-server/dist/connection.js +0 -1
  405. package/dist/node_modules/@earendil-works/pi-server/dist/errors.js +0 -1
  406. package/dist/node_modules/@earendil-works/pi-server/dist/index.js +0 -1
  407. package/dist/node_modules/@earendil-works/pi-server/dist/listener.js +0 -0
  408. package/dist/node_modules/@earendil-works/pi-server/dist/server.js +0 -1
  409. package/dist/node_modules/@earendil-works/pi-server/dist/session-router.js +0 -1
  410. package/dist/node_modules/@earendil-works/pi-server/dist/testing/client.js +0 -1
  411. package/dist/node_modules/@earendil-works/pi-server/dist/testing/host.js +0 -1
  412. package/dist/node_modules/@earendil-works/pi-server/dist/testing/index.js +0 -1
  413. package/dist/node_modules/@earendil-works/pi-server/dist/testing/server.js +0 -1
  414. package/dist/node_modules/@earendil-works/pi-server/dist/transports/unix/address.js +0 -1
  415. package/dist/node_modules/@earendil-works/pi-server/dist/transports/unix/index.js +0 -1
  416. package/dist/node_modules/@earendil-works/pi-server/dist/transports/unix/listener.js +0 -1
  417. package/dist/node_modules/@earendil-works/pi-server/dist/transports/unix/preset.js +0 -1
  418. package/dist/node_modules/@earendil-works/pi-server/dist/transports/unix/types.js +0 -0
  419. package/dist/node_modules/@earendil-works/pi-server/dist/types.js +0 -0
  420. package/dist/node_modules/@earendil-works/pi-server/package.json +0 -45
  421. package/examples/plugins/pi-example-plugin/README.md +0 -38
  422. package/examples/plugins/pi-example-plugin/package.json +0 -10
  423. package/examples/plugins/pi-example-plugin/src/contract.ts +0 -13
  424. package/examples/plugins/pi-example-plugin/src/session.ts +0 -24
  425. package/examples/plugins/pi-example-plugin/src/tui.ts +0 -31
  426. /package/dist/node_modules/{@earendil-works/chord → @dalcode/dal-codeindex}/LICENSE +0 -0
@@ -1,18 +1,15 @@
1
- var y=Object.defineProperty;var c=(e,t)=>y(e,"name",{value:t,configurable:!0});import{join as b}from"node:path";import{MCP_TYPESCRIPT_PREAMBLE as x,mcpStructuredContentSchema as g,renderToolOutputType as _,renderToolSample as M,toCodemodeIdentifier as S}from"@earendil-works/pi-codemode/declarations";import{CODEMODE_SOURCE_GRAMMAR as D}from"@earendil-works/pi-codemode/source";import{Type as C}from"typebox";import{getDocsPath as $}from"../../config.js";import{wrapToolDefinition as v}from"../../core/tools/tool-definition-wrapper.js";import{loadCodemodeExecutor as N}from"./execute.lazy.js";import{codemodeRenderers as j}from"./renderer.js";const f="codemode",ee="codemode-store",R={type:"string"},T=C.Object({code:C.String({description:"Raw JavaScript source."})});function te(e){return e.name===f&&e.parameters===T}c(te,"isCodemodeTool");const E={snippet:"Run JavaScript that calls other tools",guidelines:["Use codemode to batch independent tool calls (Promise.allSettled), chain them, or filter large output, instead of many separate calls."]},P=b($(),"codemode.md"),k='Run JavaScript that calls other tools. The input is raw JavaScript (not JSON, no code fence), run as an async function body in a QuickJS sandbox: top-level `await` and `return` work. No Node, file system, network, or timers.\n- `await tools.<name>({ ...args })` resolves to a string, or an object if the tool\'s declaration says so, and rejects with an Error on failure. Calls still running when the script ends are cancelled.\n- Optional first line: `// @options: {"max_output_tokens": 10000, "timeout_ms": 60000}`';function A(e){const t=["Globals:","- `text(value)`, `image(dataUrlOrImageBlock)`, `console.log(...)`, and top-level `return` add output; `exit()` ends the script. With several text items, each starts with a `==> text N/M <==` line, and `console` lines follow the other output in one `<console_output>` block. `image()` also saves the image to a temp file and the result names its path.","- `store(key, value)` and `load(key)` keep JSON values across codemode calls.","- `ALL_TOOLS`, `await searchTools(query, { limit?, namespace? })`, `await describeTool(name)`, `await describeNamespace(name)`: find unlisted tools, such as MCP tools."];return e&&t.push(`- \`models\`: classifiers and image generation. Read ${P} first.`),t.join(`
2
- `)}c(A,"describeGlobals");const I=3e3,L=4;function O(e,t=[]){const o=t.flatMap(a=>a.trim()?[`- ${a.trim()}`]:[]);return{name:e.name,description:o.length>0?`${e.description.trim()}
1
+ var C=Object.defineProperty;var c=(e,t)=>C(e,"name",{value:t,configurable:!0});import{join as y}from"node:path";import{renderToolOutputType as _,renderToolSample as x,toCodemodeIdentifier as g}from"@earendil-works/pi-codemode/declarations";import{CODEMODE_SOURCE_GRAMMAR as D}from"@earendil-works/pi-codemode/source";import{Type as S}from"typebox";import{getDocsPath as $}from"../../config.js";import{SETTINGS_DEFAULTS as T}from"../../core/settings-defaults.js";import{wrapToolDefinition as N}from"../../core/tools/tool-definition-wrapper.js";import{loadCodemodeExecutor as M}from"./execute.lazy.js";import{codemodeRenderers as v}from"./renderer.js";const f="codemode",oe="codemode-store",j={type:"string"},R=S.Object({code:S.String({description:"Raw JavaScript source."})}),O={snippet:"Run JavaScript that calls other tools",guidelines:["Use codemode to batch independent tool calls (Promise.allSettled), chain them, or filter large output, instead of many separate calls."]},A=y($(),"codemode.md"),L='Run JavaScript that calls other tools. The input is raw JavaScript (not JSON, no code fence), run as an async function body in a QuickJS sandbox: top-level `await` and `return` work. No Node, file system, network, or timers.\n- `await tools.<name>({ ...args })` resolves to a string, or an object if the tool\'s declaration says so, and rejects with an Error on failure. A tool whose declaration returns an object resolves on failure too when it returned that object; check its fields. Calls still running when the script ends are cancelled.\n- Optional first line: `// @options: {"max_output_tokens": 10000, "timeout_ms": 60000}`';function k(e){const t=["Globals:","- `text(value)`, `image(dataUrlOrImageBlock)`, `console.log(...)`, and top-level `return` add output; `exit()` ends the script. With several text items, each starts with a `==> text N/M <==` line, and `console` lines follow the other output in one `<console_output>` block. `image()` also saves the image to a temp file and the result names its path.","- `store(key, value)` and `load(key)` keep JSON values across codemode calls.","- `ALL_TOOLS`, `await searchTools(query, { limit?, namespace? })`, `await describeTool(name)`, `await describeNamespace(name)`: find unlisted tools, such as MCP tools."];return e&&t.push(`- \`models\`: classifiers and image generation. Read ${A} first.`),t.join(`
2
+ `)}c(k,"describeGlobals");const G=T.codemode.inlineBudget,I=4;function b(e,t=[]){const o=t.flatMap(s=>s.trim()?[`- ${s.trim()}`]:[]);return{name:e.name,description:o.length>0?`${e.description.trim()}
3
3
 
4
4
  ${o.join(`
5
- `)}`:e.description,inputSchema:e.parameters,outputSchema:e.outputSchema??R}}c(O,"toCodemodeDeclaration");function w(e){return e.filter(t=>t.name!==f)}c(w,"getCodemodeCallableTools");function G(e){const t=S(e.name);return`${t===e.name?`### \`${t}\``:`### \`${t}\` (\`${e.name}\`)`}
6
- ${M(e).trim()}`}c(G,"renderToolSection");function J(e,t){if(t===void 0)return new Set(e.flatMap(s=>s.entries.map(i=>i.name)));const o=e.map(s=>[...s.entries].sort((i,r)=>i.cost-r.cost)),a=new Set;let l=t,m=o.filter(s=>s.length>0);for(;m.length>0;)m=m.filter(s=>{const i=s[0];return i.cost>l?!1:(l-=i.cost,a.add(i.name),s.shift(),s.length>0)});return a}c(J,"selectCatalog");function h(e,t={}){const o=w(e).filter(r=>!t.deferred?.has(r.name)).map(r=>O(r,t.guidelines?.get(r.name))),a=new Map([["",{namespace:void 0,entries:[]}]]);for(const r of o){const d=t.namespaces?.get(r.name),p=d?`ns:${d.name}`:"",n=a.get(p)??{namespace:d,entries:[]};a.set(p,n);const u=G(r);n.entries.push({name:r.name,section:u,cost:Math.ceil(u.length/L)})}const l=[...a.values()].sort((r,d)=>r.namespace===void 0?-1:d.namespace===void 0?1:r.namespace.name.localeCompare(d.namespace.name)),m=J(l,t.inlineBudget),s=[k,A(t.models===!0)];if(o.some(r=>m.has(r.name)&&g(r.outputSchema)!==void 0)&&s.push(`Shared MCP Types:
7
- \`\`\`ts
8
- ${x}
9
- \`\`\``),o.length===0)return s.join(`
5
+ `)}`:e.description,inputSchema:e.parameters,outputSchema:e.outputSchema??j}}c(b,"toCodemodeDeclaration");function w(e){return e.filter(t=>t.name!==f)}c(w,"getCodemodeCallableTools");function P(e){const t=g(e.name);return`${t===e.name?`### \`${t}\``:`### \`${t}\` (\`${e.name}\`)`}
6
+ ${x(e).trim()}`}c(P,"renderToolSection");function U(e,t){if(t===void 0)return new Set(e.flatMap(i=>i.entries.map(a=>a.name)));const o=e.map(i=>[...i.entries].sort((a,r)=>a.cost-r.cost)),s=new Set;let l=t,m=o.filter(i=>i.length>0);for(;m.length>0;)m=m.filter(i=>{const a=i[0];return a.cost>l?!1:(l-=a.cost,s.add(a.name),i.shift(),i.length>0)});return s}c(U,"selectCatalog");function h(e,t={}){const o=w(e).filter(r=>!t.deferred?.has(r.name)).map(r=>b(r,t.guidelines?.get(r.name))),s=new Map([["",{namespace:void 0,entries:[]}]]);for(const r of o){const d=t.namespaces?.get(r.name),p=d?`ns:${d.name}`:"",n=s.get(p)??{namespace:d,entries:[]};s.set(p,n);const u=P(r);n.entries.push({name:r.name,section:u,cost:Math.ceil(u.length/I)})}const l=[...s.values()].sort((r,d)=>r.namespace===void 0?-1:d.namespace===void 0?1:r.namespace.name.localeCompare(d.namespace.name)),m=U(l,t.inlineBudget),i=[L,k(t.models===!0)];if(o.length===0)return i.join(`
10
7
 
11
- `);const i=["Nested tools:"];for(const{namespace:r,entries:d}of l){const p=d.filter(n=>m.has(n.name));if(r){const n=p.length===d.length?"":p.length===0?" (tools not listed)":" (some tools not listed)",u=r.description?.trim();i.push(`## ${r.name}${n}${u?`
12
- ${u}`:""}`)}for(const n of p)i.push(n.section)}return s.push(i.join(`
8
+ `);const a=["Nested tools:"];for(const{namespace:r,entries:d}of l){const p=d.filter(n=>m.has(n.name));if(r){const n=p.length===d.length?"":p.length===0?" (tools not listed)":" (some tools not listed)",u=r.description?.trim();a.push(`## ${r.name}${n}${u?`
9
+ ${u}`:""}`)}for(const n of p)a.push(n.section)}return i.push(a.join(`
13
10
 
14
- `)),s.join(`
11
+ `)),i.join(`
15
12
 
16
- `)}c(h,"createCodemodeDescription");function U(e){const t=_(e);if(t==="string")return"a string";const o=typeof e=="object"?e:void 0,a=o?.properties;if(o?.type==="object"&&typeof a=="object"&&a!==null&&g(e)===void 0){const l=new Set(Array.isArray(o.required)?o.required:[]);return`\`{ ${Object.keys(a).map(s=>l.has(s)?s:`${s}?`).join(", ")} }\``}return`\`${t.replace(/\s+/g," ")}\``}c(U,"describeOutput");function B(e){return`${e.description.trim()}
13
+ `)}c(h,"createCodemodeDescription");function E(e,t){if(typeof e!="object"||e===null)return;const{type:o,properties:s,required:l}=e;if(o!=="object"||typeof s!="object"||s===null)return;const m=new Set(Array.isArray(l)?l:[]);return`{ ${Object.entries(s).map(([a,r])=>{const d=t>0?E(r,t-1):void 0;return`${a}${m.has(a)?"":"?"}${d?`: ${d}`:""}`}).join(", ")} }`}c(E,"describeFields");function B(e){const t=_(e);return t==="string"?"a string":`\`${E(e,1)??t.replace(/\s+/g," ")}\``}c(B,"describeOutput");function J(e){return`${e.description.trim()}
17
14
 
18
- Codemode: \`tools.${S(e.name)}(args)\` resolves to ${U(O(e).outputSchema)}.`}c(B,"describeScriptCall");function q(e,t){const o=t.getMode?.()??"on",a=c(n=>e.getExposure(n.name)==="direct","isDirect"),l=w(e.callable),m=new Set(l.map(n=>n.name)),s={};if(o==="on")for(const n of e.declared)m.has(n.name)&&(s[n.name]=B(n));const i=o==="only"?l:l.filter(n=>!a(n)),r=new Map(i.flatMap(n=>{const u=e.getNamespace(n.name);return u?[[n.name,u]]:[]})),d=new Map(i.map(n=>[n.name,e.getPromptGuidelines(n.name)]));s[f]=h(i,{models:t.models===!0,namespaces:r,guidelines:d,deferred:new Set(i.filter(n=>e.getExposure(n.name)==="deferred").map(n=>n.name)),inlineBudget:t.getInlineBudget?.()??I});const p=new Set(e.declared.map(n=>n.name));return{descriptions:s,hiddenDeclarations:o==="only"?l.filter(n=>a(n)&&p.has(n.name)).map(n=>n.name):[]}}c(q,"prepareCodemodeLoadout");function H(e={}){return{name:f,label:f,description:h([],{models:e.models===!0}),promptSnippet:E.snippet,promptGuidelines:[...E.guidelines],parameters:T,exposure:"model-only",prepareLoadout:c(t=>q(t,e),"prepareLoadout"),constrainedSampling:{type:"grammar",variants:{openai_lark:D}},execute:c(async(t,o,a,l,m)=>(await N()).executeCodemode(t,o,a,l,m,e),"execute"),...j}}c(H,"createCodemodeToolDefinition");function ne(e=[],t={}){const o=H(t),a=v(o);return Object.assign(a,{description:h(e,{models:t.models===!0}),promptSnippet:o.promptSnippet,promptGuidelines:o.promptGuidelines}),a}c(ne,"createCodemodeTool");export{P as CODEMODE_DOCS_PATH,ee as CODEMODE_STORE_ENTRY_TYPE,f as CODEMODE_TOOL_NAME,I as DEFAULT_CODEMODE_INLINE_BUDGET,T as codemodeSchema,E as codemodeToolSystemPromptContribution,h as createCodemodeDescription,ne as createCodemodeTool,H as createCodemodeToolDefinition,w as getCodemodeCallableTools,te as isCodemodeTool,O as toCodemodeDeclaration};
15
+ Codemode: \`tools.${g(e.name)}(args)\` resolves to ${B(b(e).outputSchema)}.`}c(J,"describeScriptCall");function F(e,t){const o=t.getMode?.()??T.codemode.mode,s=c(n=>e.getExposure(n.name)==="direct","isDirect"),l=w(e.callable),m=new Set(l.map(n=>n.name)),i={};if(o==="on")for(const n of e.declared)m.has(n.name)&&(i[n.name]=J(n));const a=o==="only"?l:l.filter(n=>!s(n)),r=new Map(a.flatMap(n=>{const u=e.getNamespace(n.name);return u?[[n.name,u]]:[]})),d=new Map(a.map(n=>[n.name,e.getPromptGuidelines(n.name)]));i[f]=h(a,{models:t.models===!0,namespaces:r,guidelines:d,deferred:new Set(a.filter(n=>e.getExposure(n.name)==="deferred").map(n=>n.name)),inlineBudget:t.getInlineBudget?.()??G});const p=new Set(e.declared.map(n=>n.name));return{descriptions:i,hiddenDeclarations:o==="only"?l.filter(n=>s(n)&&p.has(n.name)).map(n=>n.name):[]}}c(F,"prepareCodemodeLoadout");const H=/\b(searchTools|describeNamespace|describeTool|ALL_TOOLS)\b/;function Y(e){return typeof e!="string"?[]:H.test(e)?"all":e.match(/\w+/g)??[]}c(Y,"getScriptReach");function q(e={}){return{name:f,label:f,description:h([],{models:e.models===!0}),promptSnippet:O.snippet,promptGuidelines:[...O.guidelines],parameters:R,exposure:"model-only",prepareLoadout:c(t=>F(t,e),"prepareLoadout"),reachesTools:c(t=>Y(t.code),"reachesTools"),constrainedSampling:{type:"grammar",variants:{openai_lark:D}},execute:c(async(t,o,s,l,m)=>(await M()).executeCodemode(t,o,s,l,m,e),"execute"),...v}}c(q,"createCodemodeToolDefinition");function se(e=[],t={}){const o=q(t),s=N(o);return Object.assign(s,{description:h(e,{models:t.models===!0}),promptSnippet:o.promptSnippet,promptGuidelines:o.promptGuidelines}),s}c(se,"createCodemodeTool");export{A as CODEMODE_DOCS_PATH,oe as CODEMODE_STORE_ENTRY_TYPE,f as CODEMODE_TOOL_NAME,G as DEFAULT_CODEMODE_INLINE_BUDGET,R as codemodeSchema,O as codemodeToolSystemPromptContribution,h as createCodemodeDescription,se as createCodemodeTool,q as createCodemodeToolDefinition,w as getCodemodeCallableTools,b as toCodemodeDeclaration};
@@ -38,13 +38,13 @@ Options for add:
38
38
 
39
39
  Other options:
40
40
  --json Print the list as JSON
41
- --timeout <seconds> How long login waits for the browser (default: 300)`,j=U.dim(W(L('\u7528\u6CD5\u89C1 "{app} mcp --help"\u3002'),{app:g})),se=300;function y(o){return o instanceof Error?o.message:String(o)}h(y,"errorMessage");function ie(o){const{config:t}=o;return"url"in t?t.url:[t.command,...t.args??[]].join(" ")}h(ie,"describeTransport");function _(o,t,i){return new ee({entry:o,cwd:t.cwd,createTransport:X,credentials:i,log:new te(S(t.agentDir,"mcp.log")),onTools:h(()=>{},"onTools")})}h(_,"createConnection");const ae=new Map([["-l","--local"]]);function T(o,t,i,c=Number.POSITIVE_INFINITY){const n=[],a=new Map,d=new Map;for(let f=0;f<o.length;f++){const e=ae.get(o[f])??o[f];if(e==="--"||n.length>=c){n.push(...o.slice(e==="--"?f+1:f));break}if(!e.startsWith("--")){n.push(e);continue}const l=e.slice(2),s=t[l];if(!s){i(`Unknown option ${e}.
41
+ --timeout <seconds> Time limit for the whole sign-in (default: 300)`,j=U.dim(W(L('\u7528\u6CD5\u89C1 "{app} mcp --help"\u3002'),{app:g})),se=300;function y(o){return o instanceof Error?o.message:String(o)}h(y,"errorMessage");function ie(o){const{config:t}=o;return"url"in t?t.url:[t.command,...t.args??[]].join(" ")}h(ie,"describeTransport");function _(o,t,i){return new ee({entry:o,cwd:t.cwd,createTransport:X,credentials:i,log:new te(S(t.agentDir,"mcp.log")),onTools:h(()=>{},"onTools")})}h(_,"createConnection");const ae=new Map([["-l","--local"]]);function T(o,t,i,c=Number.POSITIVE_INFINITY){const n=[],a=new Map,d=new Map;for(let f=0;f<o.length;f++){const e=ae.get(o[f])??o[f];if(e==="--"||n.length>=c){n.push(...o.slice(e==="--"?f+1:f));break}if(!e.startsWith("--")){n.push(e);continue}const l=e.slice(2),s=t[l];if(!s){i(`Unknown option ${e}.
42
42
  ${j}`);return}if(s==="flag"){a.set(l,!0);continue}const r=o[++f];if(r===void 0){i(`${e} needs a value.`);return}s==="list"?d.set(l,[...d.get(l)??[],r]):a.set(l,r)}return{positional:n,values:a,lists:d}}h(T,"parseOptions");async function Oe(o,t){const i=t.log??(r=>console.log(r)),c=t.error??(r=>console.error(r)),[n,...a]=o;if(n===void 0||n==="help"||o.includes("--help")||o.includes("-h"))return i(oe),0;const d=S(t.cwd,A,"mcp.json");if(n==="add"||n==="remove")return n==="add"?ce(a,d,t,i,c):le(a,d,t,i,c);const f=new D(t.agentDir).get(t.cwd)===!0,e=R({agentDir:t.agentDir,cwd:t.cwd,projectTrusted:f}),l=!f&&V(d)?`${d} is ignored because the project is not trusted. Start ${g} in the project to trust it.`:void 0,s=t.credentials??new Z;switch(n){case"list":{const r=T(a,{json:"flag"},c);return r?r.positional.length>0?(c(`Usage: ${g} mcp list [--json]
43
43
  ${j}`),1):de(e,r.values.has("json"),l,t,s,i):1}case"login":case"logout":{const r=T(a,n==="login"?{timeout:"value"}:{},c);if(!r)return 1;const[u,...p]=r.positional;if(!u||p.length>0)return c(`Usage: ${g} mcp ${n} <server>
44
44
  ${j}`),1;const v=e.servers.find($=>$.name===u);if(!v)return c(`No MCP server named "${u}".${l?` ${l}`:""} Configured: ${e.servers.map($=>$.name).join(", ")||"none"}.`),1;const O=_(v,t,s),P=O.oauthUrl;if(!P)return c(`MCP server "${u}" does not use OAuth. Only HTTP servers without an Authorization header do.`),1;if(n==="logout"){const $=s.remove(u,P);return i($?`Signed out of MCP server "${u}".`:`No stored credentials for MCP server "${u}".`),0}const b=Number(r.values.get("timeout")??se);if(!Number.isFinite(b)||b<=0)return c("--timeout must be a positive number of seconds."),1;try{return await ue(v,O,P,b*1e3,t,s,i,c)}finally{await O.close()}}default:return c(`Unknown mcp command "${n}".
45
- ${j}`),1}}h(Oe,"runMcpCommand");function H(o,t,i){if(!t)return{};const c={};for(const n of t){const a=n.indexOf("=");if(a<=0){i(`--${o} expects KEY=VALUE, got "${n}".`);return}c[n.slice(0,a)]=n.slice(a+1)}return c}h(H,"parsePairs");function ce(o,t,i,c,n){const a=`Usage: ${g} mcp add <server> [options] (--url <url> | -- <command> [args...])
46
- ${j}`,d=T(o,{local:"flag",url:"value",env:"list",cwd:"value",header:"list","bearer-token-env-var":"value","oauth-client-id":"value","oauth-client-secret":"value","oauth-callback-port":"value","oauth-client-name":"value",exposure:"value",description:"value"},n,2);if(!d)return 1;const{positional:f,values:e,lists:l}=d,[s,...r]=f,u=e.get("url");if(!s||u===void 0==(r.length===0))return n(a),1;const p=h(m=>{const w=e.get(m);return typeof w=="string"?w:void 0},"value"),v=p("exposure"),b=(u===void 0?["header","bearer-token-env-var","oauth-client-id","oauth-client-secret","oauth-callback-port","oauth-client-name"]:["env","cwd"]).find(m=>e.has(m)||l.has(m));if(b)return n(`--${b} only applies to ${u===void 0?"HTTP servers (--url)":"stdio servers"}.`),1;let $;if(typeof u=="string"){const m=H("header",l.get("header"),n);if(!m)return 1;const w=p("bearer-token-env-var");w!==void 0&&(m.Authorization=`Bearer \${${w}}`);const M=p("oauth-callback-port"),N={...p("oauth-client-id")===void 0?{}:{clientId:p("oauth-client-id")},...p("oauth-client-secret")===void 0?{}:{clientSecret:p("oauth-client-secret")},...M===void 0?{}:{callbackPort:Number(M)},...p("oauth-client-name")===void 0?{}:{clientName:p("oauth-client-name")}};$={url:u,...Object.keys(m).length>0?{headers:m}:{},...Object.keys(N).length>0?{oauth:N}:{}}}else{const m=H("env",l.get("env"),n);if(!m)return 1;const[w,...M]=r;$={command:w,...M.length>0?{args:M}:{},...Object.keys(m).length>0?{env:m}:{},...p("cwd")===void 0?{}:{cwd:p("cwd")}}}v!==void 0&&($.exposure=v);const k=p("description");k!==void 0&&($.description=k);const C=K(s,$);if(typeof C=="string")return n(C),1;const x=e.has("local"),E=x?t:S(i.agentDir,"mcp.json"),F=x?"project":"global";let I;try{I=G(E,s,C)}catch(m){return n(`Could not update ${E}: ${y(m)}`),1}c(`${I?"Replaced":"Added"} ${F} MCP server "${s}" in ${E}.`),x&&new D(i.agentDir).get(i.cwd)!==!0&&c(`The project is not trusted, so ${E} is ignored until you start ${g} in the project and trust it.`);const Y="url"in C&&!Object.keys(C.headers??{}).some(m=>m.toLowerCase()==="authorization");return c(`Check it with: ${g} mcp list${Y?`. If it requires sign-in: ${g} mcp login ${s}`:""}`),0}h(ce,"add");function le(o,t,i,c,n){const a=T(o,{local:"flag"},n);if(!a)return 1;const[d,...f]=a.positional;if(!d||f.length>0)return n(`Usage: ${g} mcp remove <server> [-l]
47
- ${j}`),1;const e=a.values.has("local"),l=S(i.agentDir,"mcp.json"),s=e?t:l,r=e?"project":"global";let u;try{u=Q(s,d)}catch(v){return n(`Could not update ${s}: ${y(v)}`),1}if(u)return c(`Removed ${r} MCP server "${d}" from ${s}.`),0;const p=R({agentDir:i.agentDir,cwd:i.cwd,projectTrusted:!0}).servers.find(v=>v.name===d&&v.scope!==r);return n(`No ${r} MCP server named "${d}" in ${s}.${p?` It is defined in ${p.source}${p.scope==="project"?"; use --local":"; omit --local"}.`:""}`),1}h(le,"remove");async function de(o,t,i,c,n,a){const d=await Promise.all(o.servers.map(async e=>{const l={name:e.name,scope:e.scope??"global",source:e.source,...e.override?{override:e.override}:{},enabled:e.config.enabled!==!1,exposure:e.config.exposure??"codemode",transport:ie(e),state:"disabled",tools:[]};if(!l.enabled)return l;const s=_(e,c,n);try{await s.getClient()}catch{}l.state=s.state,l.tools=s.tools.map(u=>u.name);const r=s.tools.flatMap(u=>{const p=J(e.config,u.name);return p===l.exposure?[]:[[u.name,p]]});return r.length>0&&(l.toolExposure=Object.fromEntries(r)),s.hasResources&&(l.resources=s.resources.length,l.resourceTemplates=s.resourceTemplates.length),s.state!=="connected"&&s.error&&(l.error=s.error),await s.close(),l})),f=o.errors.length>0||d.some(e=>e.enabled&&e.state!=="connected");if(t)return a(JSON.stringify({servers:d,errors:o.errors,...i?{note:i}:{}},null,2)),f?1:0;d.length===0&&o.errors.length===0&&a(`No MCP servers configured. Add them to ${S(c.agentDir,"mcp.json")} or .pi/mcp.json.`);for(const e of d){const l=e.state==="connected"?`connected, ${e.tools.length} tool${e.tools.length===1?"":"s"}`:e.state==="needs-auth"?"needs sign-in":e.state;if(a(`${e.name}: ${l} (${e.exposure}, ${e.scope})`),a(` ${e.transport}`),e.override&&a(` project override: ${e.override}`),e.state==="needs-auth"&&a(` sign in with: ${g} mcp login ${e.name}`),e.tools.length>0){const s=e.tools.map(r=>{const u=e.toolExposure?.[r];return u?`${r} [${u}]`:r});a(` tools: ${s.join(", ")}`)}e.resources!==void 0&&a(` resources: ${e.resources}, URI templates: ${e.resourceTemplates??0}`),e.error&&a(` ${e.error.split(`
45
+ ${j}`),1}}h(Oe,"runMcpCommand");function F(o,t,i){if(!t)return{};const c={};for(const n of t){const a=n.indexOf("=");if(a<=0){i(`--${o} expects KEY=VALUE, got "${n}".`);return}c[n.slice(0,a)]=n.slice(a+1)}return c}h(F,"parsePairs");function ce(o,t,i,c,n){const a=`Usage: ${g} mcp add <server> [options] (--url <url> | -- <command> [args...])
46
+ ${j}`,d=T(o,{local:"flag",url:"value",env:"list",cwd:"value",header:"list","bearer-token-env-var":"value","oauth-client-id":"value","oauth-client-secret":"value","oauth-callback-port":"value","oauth-client-name":"value",exposure:"value",description:"value"},n,2);if(!d)return 1;const{positional:f,values:e,lists:l}=d,[s,...r]=f,u=e.get("url");if(!s||u===void 0==(r.length===0))return n(a),1;const p=h(m=>{const w=e.get(m);return typeof w=="string"?w:void 0},"value"),v=p("exposure"),b=(u===void 0?["header","bearer-token-env-var","oauth-client-id","oauth-client-secret","oauth-callback-port","oauth-client-name"]:["env","cwd"]).find(m=>e.has(m)||l.has(m));if(b)return n(`--${b} only applies to ${u===void 0?"HTTP servers (--url)":"stdio servers"}.`),1;let $;if(typeof u=="string"){const m=F("header",l.get("header"),n);if(!m)return 1;const w=p("bearer-token-env-var");w!==void 0&&(m.Authorization=`Bearer \${${w}}`);const M=p("oauth-callback-port"),I={...p("oauth-client-id")===void 0?{}:{clientId:p("oauth-client-id")},...p("oauth-client-secret")===void 0?{}:{clientSecret:p("oauth-client-secret")},...M===void 0?{}:{callbackPort:Number(M)},...p("oauth-client-name")===void 0?{}:{clientName:p("oauth-client-name")}};$={url:u,...Object.keys(m).length>0?{headers:m}:{},...Object.keys(I).length>0?{oauth:I}:{}}}else{const m=F("env",l.get("env"),n);if(!m)return 1;const[w,...M]=r;$={command:w,...M.length>0?{args:M}:{},...Object.keys(m).length>0?{env:m}:{},...p("cwd")===void 0?{}:{cwd:p("cwd")}}}v!==void 0&&($.exposure=v);const k=p("description");k!==void 0&&($.description=k);const C=K(s,$);if(typeof C=="string")return n(C),1;const x=e.has("local"),E=x?t:S(i.agentDir,"mcp.json"),H=x?"project":"global";let N;try{N=G(E,s,C)}catch(m){return n(`Could not update ${E}: ${y(m)}`),1}c(`${N?"Replaced":"Added"} ${H} MCP server "${s}" in ${E}.`),x&&new D(i.agentDir).get(i.cwd)!==!0&&c(`The project is not trusted, so ${E} is ignored until you start ${g} in the project and trust it.`);const Y="url"in C&&!Object.keys(C.headers??{}).some(m=>m.toLowerCase()==="authorization");return c(`Check it with: ${g} mcp list${Y?`. If it requires sign-in: ${g} mcp login ${s}`:""}`),0}h(ce,"add");function le(o,t,i,c,n){const a=T(o,{local:"flag"},n);if(!a)return 1;const[d,...f]=a.positional;if(!d||f.length>0)return n(`Usage: ${g} mcp remove <server> [-l]
47
+ ${j}`),1;const e=a.values.has("local"),l=S(i.agentDir,"mcp.json"),s=e?t:l,r=e?"project":"global";let u;try{u=Q(s,d)}catch(v){return n(`Could not update ${s}: ${y(v)}`),1}if(u)return c(`Removed ${r} MCP server "${d}" from ${s}.`),0;const p=R({agentDir:i.agentDir,cwd:i.cwd,projectTrusted:!0}).servers.find(v=>v.name===d&&v.scope!==r);return n(`No ${r} MCP server named "${d}" in ${s}.${p?` It is defined in ${p.source}${p.scope==="project"?"; use --local":"; omit --local"}.`:""}`),1}h(le,"remove");async function de(o,t,i,c,n,a){const d=await Promise.all(o.servers.map(async e=>{const l={name:e.name,scope:e.scope??"global",source:e.source,...e.override?{override:e.override}:{},enabled:e.config.enabled!==!1,exposure:e.config.exposure??"codemode",transport:ie(e),state:"disabled",tools:[]};if(!l.enabled)return l;const s=_(e,c,n);try{await s.getClient()}catch{}l.state=s.state,l.tools=s.tools.map(u=>u.name);const r=s.tools.flatMap(u=>{const p=J(e.config,u.name);return p===l.exposure?[]:[[u.name,p]]});return r.length>0&&(l.toolExposure=Object.fromEntries(r)),s.hasResources&&(l.resources=!0),s.state!=="connected"&&s.error&&(l.error=s.error),await s.close(),l})),f=o.errors.length>0||d.some(e=>e.enabled&&e.state!=="connected");if(t)return a(JSON.stringify({servers:d,errors:o.errors,...i?{note:i}:{}},null,2)),f?1:0;d.length===0&&o.errors.length===0&&a(`No MCP servers configured. Add them to ${S(c.agentDir,"mcp.json")} or .pi/mcp.json.`);for(const e of d){const l=e.state==="connected"?`connected, ${e.tools.length} tool${e.tools.length===1?"":"s"}`:e.state==="needs-auth"?"needs sign-in":e.state;if(a(`${e.name}: ${l} (${e.exposure}, ${e.scope})`),a(` ${e.transport}`),e.override&&a(` project override: ${e.override}`),e.state==="needs-auth"&&a(` sign in with: ${g} mcp login ${e.name}`),e.tools.length>0){const s=e.tools.map(r=>{const u=e.toolExposure?.[r];return u?`${r} [${u}]`:r});a(` tools: ${s.join(", ")}`)}e.resources&&a(" offers resources"),e.error&&a(` ${e.error.split(`
48
48
  `).join(`
49
49
  `)}`)}for(const e of o.errors)a(`config error: ${e}`);return i&&a(i),f?1:0}h(de,"list");async function ue(o,t,i,c,n,a,d,f){const{name:e}=o;try{return await t.getClient(),d(`Already signed in to MCP server "${e}" (${t.tools.length} tools).`),0}catch{if(t.state!=="needs-auth")return f(`MCP server "${e}" failed to connect: ${t.error??"unknown error"}`),1}const l=n.openUrl??q,s=process.stdin.isTTY===!0&&n.openUrl===void 0;try{await ne({serverUrl:i,store:a.forServer(e,i),settings:t.oauthSettings(),challenge:t.challenge,prompt:{showAuthorizationUrl:h(r=>{d(`Sign in to MCP server "${e}" in your browser:
50
50
  ${r.href}`),l(r.href)},"showAuthorizationUrl"),promptForRedirectUrl:h(r=>fe(r,s),"promptForRedirectUrl")},signal:AbortSignal.timeout(c)})}catch(r){return f(r instanceof re?`Sign-in to MCP server "${e}" was cancelled or not completed within ${Math.round(c/1e3)} seconds.`:`Sign-in to MCP server "${e}" failed: ${y(r)}`),1}t.challenge=void 0;try{await t.reconnect()}catch(r){return f(`Signed in, but ${y(r)}`),1}return d(`Signed in to MCP server "${e}" (${t.tools.length} tools).`),0}h(ue,"login");async function fe(o,t){if(!t){o.aborted||await new Promise(c=>o.addEventListener("abort",c,{once:!0}));return}const i=B({input:process.stdin,output:process.stderr});try{return await i.question("If the browser cannot reach this machine, paste the URL it was redirected to: ",{signal:o})}catch{return}finally{i.close()}}h(fe,"waitForRedirectUrl");export{Oe as runMcpCommand};
@@ -1,17 +1,17 @@
1
- var Qe=Object.defineProperty;var i=(l,a)=>Qe(l,"name",{value:a,configurable:!0});import{join as Ye,resolve as Ce}from"node:path";import{getAgentDir as z}from"../../config.js";import{mcpNamespace as I}from"../../core/mcp-servers.js";import{openBrowser as Ze}from"../../utils/open-browser.js";import{CODEMODE_TOOL_NAME as Z,isCodemodeTool as ve}from"../codemode/tool.js";import{isToolSearchTool as Me,TOOL_SEARCH_TOOL_NAME as ee}from"../tool-search/tool.js";import{getMcpToolExposure as ne,loadMcpConfig as en,updateMcpServerConfig as nn}from"./config.js";import{createMcpResourceToolDefinitions as tn,LIST_MCP_RESOURCE_TEMPLATES_TOOL as on,LIST_MCP_RESOURCES_TOOL as rn,READ_MCP_RESOURCE_TOOL as sn}from"./resources.js";import{loadMcpRuntime as F}from"./runtime.lazy.js";import{createMcpToolDefinition as cn,createMcpToolName as Te,createMcpToolRenderers as an}from"./tools.js";import{showMcpManager as Ee}from"./ui.js";const ln=1e4,dn=new Set([rn,on,sn]),te={codemode:"called from codemode scripts, which find them with searchTools()",deferred:"not declared until tool_search loads them, then called directly; no codemode needed",direct:"declared to the model like built-in tools"};function O(l){return l instanceof Error?l.message:String(l)}i(O,"errorMessage");function Pe(l){return l.split(`
2
- `,1)[0]??""}i(Pe,"firstLine");function p(l){return l.entry.config.enabled!==!1}i(p,"isEnabled");function P(l){return l.config.exposure??"codemode"}i(P,"exposureOf");function H(l){return new Set([P(l),...Object.values(l.config.toolExposure??{})])}i(H,"configuredExposures");function un(l){return H(l).has("direct")}i(un,"hasDirectTools");function fn(l){const a=H(l);return a.has("codemode")||a.has("deferred")}i(fn,"hasIndirectTools");const _e="mcp_servers",mn=250,Ae=4096;function gn(l){let a="MCP servers whose tools are not declared to you.";return l.has("codemode")&&(a+=" Call the tools of `codemode` servers from codemode scripts."),l.has("tool_search")&&(a+=" Load the tools of `tool_search` servers with `tool_search`."),a}i(gn,"serversSectionIntro");function hn(l,a){return l.length<=a?l:a<=1?"":`${l.slice(0,a-1).trimEnd()}\u2026`}i(hn,"truncate");function pn(l){return((l.entry.config.description?.trim()||l.connection?.instructions||"").split(`
3
- `,1)[0]??"").trim()}i(pn,"serverSummary");function yn(l){const a=l.filter(m=>p(m)&&fn(m.entry)).sort((m,E)=>m.entry.name.localeCompare(E.entry.name));if(a.length===0)return;const u=a.map(m=>H(m.entry).has("codemode")?"codemode":"tool_search"),T=gn(new Set(u)),w=a.map((m,E)=>`- ${I(m.entry.name)} (${u[E]})`),C=i(m=>m>0?[`- \u2026 ${m} more server${m===1?"":"s"}; find their tools with searchTools()`]:[],"omitted"),v=i(m=>[T,...w.slice(0,m),...C(a.length-m)].join(`
4
- `).length,"size");let b=a.length;for(;b>0&&v(b)>Ae;)b--;const R=b===0?0:Math.min(mn,Math.floor((Ae-v(b))/b)-2),L=a.slice(0,b).map((m,E)=>{const k=R>0?hn(pn(m),R):"";return k?`${w[E]}: ${k}`:w[E]});return[T,...L,...C(a.length-b)].join(`
5
- `)}i(yn,"renderServersSection");function bn(l,a){return/\b(searchTools|describeNamespace|describeTool|ALL_TOOLS)\b/.test(l)?!0:l.includes(I(a))}i(bn,"scriptNeedsServer");function N(l,a=!0){if(!p(l))return"disabled";const u=l.connection;if(!u)return"starting";switch(u.state){case"needs-auth":return"needs sign-in";case"failed":return a?`failed: ${Pe(u.error??"unknown error")}`:"failed";case"connected":{const{tools:T,resources:w}=u,C=w.length,v=C>0?` \xB7 ${C} resource${C===1?"":"s"}`:"";return`connected \xB7 ${T.length} tool${T.length===1?"":"s"}${v}`}case"connecting":return"connecting\u2026";default:return u.state}}i(N,"describeState");function Oe(l){if(!p(l))return 5;switch(l.connection?.state){case"needs-auth":return 0;case"failed":return 1;case"disconnected":return 2;case"connected":return 4;default:return 3}}i(Oe,"attentionRank");function wn(l){const{config:a}=l;return"url"in a?a.url:[a.command,...a.args??[]].join(" ")}i(wn,"describeTransport");const Re="Usage: /mcp, /mcp login [server], /mcp logout [server], /mcp reconnect [server]";function Sn(l={}){return a=>{let u=[],T=[],w=[],C,v=[],b=!0,R=!1,L,m=!1;const E=l.startupWaitMs??ln;let k=process.cwd(),D=l.credentials,oe,re;const se=l.openUrl??Ze,je=l.updateConfig??((e,n)=>nn(e.override??e.source,e.name,n,{override:e.override!==void 0}));let S=new AbortController;S.abort();const B=new Set,ie=i(e=>{const n=e.then(()=>{},()=>{});return B.add(n),n.finally(()=>B.delete(n)),e},"track"),V=new Set,M=i(()=>{for(const e of V)e()},"emitChange"),ce=i(e=>(V.add(e),()=>{V.delete(e)}),"subscribe"),Le=i(()=>u.flatMap(e=>e.connection?[e.connection]:[]),"connections"),j=i(e=>u.find(n=>n.entry.name===e),"findServer"),ae=i(()=>{const e=[],n=[];for(const{name:t,config:r,extensionPath:o}of a.getMcpServers()){const s=T.find(c=>I(c.name)===I(t));if(s){n.push(`"${t}" registered by ${o} is overridden by "${s.name}" in ${s.source}`);continue}e.push({entry:{name:t,config:r,source:o,scope:"extension"},registeredConfig:JSON.stringify(r)})}return{servers:e,overridden:n}},"registeredServers"),X=i(e=>(D??=new e.McpOAuthCredentialStore,D),"getCredentials"),ke=i(e=>(re??=new e.McpServerLog(l.logPath??Ye(z(),"mcp.log")),re),"getServerLog"),J=new Map,U=new Map,q=new Map;a.registerToolRenderer((e,n)=>{const t=/^mcp__(.+?)__(.+)$/.exec(e);return n()??(t?an(`${t[1]}/${t[2]}`):void 0)});const le=i(e=>{const n=e.entry.name,t=j(n)?.entry??e.entry,r=t.config.description?.trim(),o={name:I(n),...r?{description:r}:{},...e.instructions?{instructions:e.instructions}:{}},s=U.get(n)??new Set,c=new Set,d=[...new Set(e.tools.map(g=>g.name))].map(g=>Te(n,g)),f=i((g,h)=>{const y=Te(n,g,$=>{const W=J.get($);return W!==void 0&&W!==h||c.has($)||d.indexOf($)!==d.lastIndexOf($)});return J.set(y,h),c.add(y),y},"assignName");for(const g of e.tools){const h=cn({server:n,tool:g,name:f(g.name,`${n}\0${g.name}`),exposure:ne(t.config,g.name),namespace:o,timeoutMs:e.timeoutMs,getClient:i(async()=>{const y=j(n);if(!y||!p(y))throw new Error(`MCP server "${n}" is disabled.`);const $=y.connection;if(!$)throw new Error(`MCP server "${n}" is still starting.`);if(ne(y.entry.config,g.name)==="hidden"||$.state==="connected"&&!$.tools.some(W=>W.name===g.name))throw new Error(`MCP tool "${n}/${g.name}" is no longer available.`);return $},"getClient"),readableResources:i(()=>fe().some(y=>y.name===n),"readableResources")});q.set(h.name,h),a.registerTool(h)}U.set(n,c);for(const g of s){const h=q.get(g);!c.has(g)&&h&&a.registerTool({...h,exposure:"hidden"})}G()},"registerTools"),de=i(e=>{for(const n of U.get(e)??[]){const t=q.get(n);t&&a.registerTool({...t,exposure:"hidden"})}U.set(e,new Set),G()},"hideTools"),ue=i(()=>u.filter(e=>e.connection?.hasResources&&p(e)&&P(e.entry)!=="hidden"),"serversWithResources"),fe=i(()=>ue().flatMap(e=>e.connection?[e.connection]:[]),"resourceServers");let x;const G=i(()=>{const e=new Set(ue().map(s=>P(s.entry))),t=["direct","codemode","deferred"].find(s=>e.has(s))??"hidden";if(t===x||x===void 0&&t==="hidden")return;const r=x==="direct";x=t;const o=tn({exposure:t,servers:fe});for(const s of o)a.registerTool(s);if(r){const s=new Set(o.map(c=>c.name));a.setActiveTools(a.getActiveTools().filter(c=>!s.has(c)))}},"syncResourceTools"),_=i(e=>{const n=new Set;for(const y of u)if(p(y))for(const $ of H(y.entry))n.add($);const t=n.has("codemode"),r=n.has("deferred");if(!t&&!r)return;const o=a.getAllTools(),s=o.some(ve),c=o.some(Me),d=a.getActiveTools(),f=[];t&&s&&b&&!d.includes(Z)&&f.push(Z),r&&c&&!d.includes(ee)&&f.push(ee),f.length>0&&a.setActiveTools([...d,...f]);const g=[...d,...f];if(s&&g.includes(Z)||c&&g.includes(ee)||R)return;R=!0;const h=t&&s&&!b?" (autoEnableCodemode is false)":"";e.ui.notify(`MCP tools are only reachable from the codemode or tool_search tool, but neither is active${h}; they cannot be called.`,"warning")},"ensureDiscoveryActive"),A=new Map,me=i(e=>{const n=e.oauthUrl;return n&&D?JSON.stringify(D.tokens(e.name,n)??null):"null"},"storedTokens"),Ue=i(e=>{e.state!=="needs-auth"?A.delete(e):A.has(e)||A.set(e,me(e)),M()},"onConnectionChange"),Ie=i(async e=>{const n=[...A].filter(([t,r])=>me(t)!==r);if(n.length!==0){for(const[t]of n)A.delete(t);await Promise.allSettled(n.map(([t])=>t.reconnect())),_(e)}},"reconnectSignedIn"),Ne=i(async(e,n)=>{const t=await F();if(!n())return;const r=new t.McpServerConnection({entry:e.entry,cwd:k,createTransport:l.createTransport??t.createDefaultTransport,credentials:X(t),providerToken:i(async o=>oe?.getApiKeyForProvider(o),"providerToken"),log:ke(t),onTools:i(o=>{n()&&le(o)},"onTools"),onChange:i(o=>{n()?Ue(o):A.delete(o)},"onChange")});return e.connection=r,M(),r},"createConnection"),K=i((e,n)=>{const{signal:t}=S,r=Symbol();e.attempt=r;const o=i(()=>!t.aborted&&e.attempt===r&&p(e)&&u.includes(e),"isCurrent"),s=(async()=>{if(await n,!o())return;const c=await Ne(e,o);!c||!o()||await c.getClient().catch(()=>{})})();return e.ready=s.catch(()=>{}),s},"startConnection"),De=i(async(e,n)=>{for(;;){const t=e.flatMap(o=>p(o)&&u.includes(o)&&o.ready?[{server:o,ready:o.ready}]:[]);if(t.length===0||n?.aborted)return;let r;if(await Promise.race([Promise.all(t.map(o=>o.ready)),new Promise(o=>{r=i(()=>o(),"onAbort"),n?.addEventListener("abort",r,{once:!0})})]),r&&n?.removeEventListener("abort",r),n?.aborted||t.every(o=>!p(o.server)||!u.includes(o.server)||o.ready===o.server.ready))return}},"waitForServers"),Q=i((e,n)=>{const t=n?[]:w.map(r=>`config: ${r}`);for(const r of n??u){const o=r.connection?.state;(o==="needs-auth"||o==="failed")&&t.push(`${r.entry.name}: ${N(r)}`)}t.length!==0&&e.ui.notify(`MCP servers need attention:
1
+ var Ge=Object.defineProperty;var i=(l,a)=>Ge(l,"name",{value:a,configurable:!0});import{join as Ke,resolve as Ce}from"node:path";import{getAgentDir as z}from"../../config.js";import{mcpNamespace as N}from"../../core/mcp-servers.js";import{openBrowser as Qe}from"../../utils/open-browser.js";import{CODEMODE_TOOL_NAME as F}from"../codemode/tool.js";import{TOOL_SEARCH_TOOL_NAME as H}from"../tool-search/tool.js";import{getMcpToolExposure as ne,loadMcpConfig as Ye,updateMcpServerConfig as Ze}from"./config.js";import{createMcpResourceToolDefinitions as en,LIST_MCP_RESOURCE_TEMPLATES_TOOL as nn,LIST_MCP_RESOURCES_TOOL as tn,READ_MCP_RESOURCE_TOOL as on}from"./resources.js";import{loadMcpRuntime as B}from"./runtime.lazy.js";import{createMcpToolDefinition as rn,createMcpToolName as ve,createMcpToolRenderers as sn}from"./tools.js";import{showMcpManager as Me}from"./ui.js";const cn=1e4,an=new Set([tn,nn,on]),te={codemode:"called from codemode scripts, which find them with searchTools()",deferred:"not declared until tool_search loads them, then called directly; no codemode needed",direct:"declared to the model like built-in tools"};function O(l){return l instanceof Error?l.message:String(l)}i(O,"errorMessage");function Te(l){return l.split(`
2
+ `,1)[0]??""}i(Te,"firstLine");function p(l){return l.entry.config.enabled!==!1}i(p,"isEnabled");function P(l){return l.config.exposure??"codemode"}i(P,"exposureOf");function V(l){return new Set([P(l),...Object.values(l.config.toolExposure??{})])}i(V,"configuredExposures");function ln(l){return V(l).has("direct")}i(ln,"hasDirectTools");function dn(l){const a=V(l);return a.has("codemode")||a.has("deferred")}i(dn,"hasIndirectTools");const Ee="mcp_servers",un=250,Pe=4096;function fn(l){let a="MCP servers whose tools are not declared to you.";return l.has("codemode")&&(a+=" Call the tools of `codemode` servers from codemode scripts."),l.has("tool_search")&&(a+=" Load the tools of `tool_search` servers with `tool_search`."),a}i(fn,"serversSectionIntro");function mn(l,a){return l.length<=a?l:a<=1?"":`${l.slice(0,a-1).trimEnd()}\u2026`}i(mn,"truncate");function gn(l){return((l.entry.config.description?.trim()||l.connection?.instructions||"").split(`
3
+ `,1)[0]??"").trim()}i(gn,"serverSummary");function hn(l){const a=l.filter(h=>p(h)&&dn(h.entry)).sort((h,E)=>h.entry.name.localeCompare(E.entry.name));if(a.length===0)return;const u=a.map(h=>V(h.entry).has("codemode")?"codemode":"tool_search"),C=fn(new Set(u)),S=a.map((h,E)=>`- ${N(h.entry.name)} (${u[E]})`),R=i(h=>h>0?[`- \u2026 ${h} more server${h===1?"":"s"}; find their tools with searchTools()`]:[],"omitted"),T=i(h=>[C,...S.slice(0,h),...R(a.length-h)].join(`
4
+ `).length,"size");let b=a.length;for(;b>0&&T(b)>Pe;)b--;const j=b===0?0:Math.min(un,Math.floor((Pe-T(b))/b)-2),k=a.slice(0,b).map((h,E)=>{const U=j>0?mn(gn(h),j):"";return U?`${S[E]}: ${U}`:S[E]});return[C,...k,...R(a.length-b)].join(`
5
+ `)}i(hn,"renderServersSection");function pn(l,a){if(l==="all")return!0;const u=N(a);return l.some(C=>C.includes(u))}i(pn,"reachesServer");function D(l,a=!0){if(!p(l))return"disabled";const u=l.connection;if(!u)return"starting";switch(u.state){case"needs-auth":return"needs sign-in";case"failed":return a?`failed: ${Te(u.error??"unknown error")}`:"failed";case"connected":{const{tools:C,hasResources:S}=u;return`connected \xB7 ${C.length} tool${C.length===1?"":"s"}${S?" \xB7 resources":""}`}case"connecting":return"connecting\u2026";default:return u.state}}i(D,"describeState");function _e(l){if(!p(l))return 5;switch(l.connection?.state){case"needs-auth":return 0;case"failed":return 1;case"disconnected":return 2;case"connected":return 4;default:return 3}}i(_e,"attentionRank");function yn(l){const{config:a}=l;return"url"in a?a.url:[a.command,...a.args??[]].join(" ")}i(yn,"describeTransport");const Ae="Usage: /mcp, /mcp login [server], /mcp logout [server], /mcp reconnect [server]";function bn(l={}){return a=>{let u=[],C=[],S=[],R,T=[],b=!0,j=!1,k,h=!1;const E=l.startupWaitMs??cn;let U=process.cwd(),x=l.credentials,oe,re;const se=l.openUrl??Qe,Oe=l.updateConfig??((e,n)=>Ze(e.override??e.source,e.name,n,{override:e.override!==void 0}));let $=new AbortController;$.abort();const X=new Set,ie=i(e=>{const n=e.then(()=>{},()=>{});return X.add(n),n.finally(()=>X.delete(n)),e},"track"),J=new Set,v=i(()=>{for(const e of J)e()},"emitChange"),ce=i(e=>(J.add(e),()=>{J.delete(e)}),"subscribe"),Re=i(()=>u.flatMap(e=>e.connection?[e.connection]:[]),"connections"),L=i(e=>u.find(n=>n.entry.name===e),"findServer"),ae=i(()=>{const e=[],n=[];for(const{name:t,config:r,extensionPath:o}of a.getMcpServers()){const s=C.find(c=>N(c.name)===N(t));if(s){n.push(`"${t}" registered by ${o} is overridden by "${s.name}" in ${s.source}`);continue}e.push({entry:{name:t,config:r,source:o,scope:"extension"},registeredConfig:JSON.stringify(r)})}return{servers:e,overridden:n}},"registeredServers"),q=i(e=>(x??=new e.McpOAuthCredentialStore,x),"getCredentials"),je=i(e=>(re??=new e.McpServerLog(l.logPath??Ke(z(),"mcp.log")),re),"getServerLog"),G=new Map,I=new Map,K=new Map;a.registerToolRenderer((e,n)=>{const t=/^mcp__(.+?)__(.+)$/.exec(e);return n()??(t?sn(`${t[1]}/${t[2]}`):void 0)});const le=i(e=>{const n=e.entry.name,t=L(n)?.entry??e.entry,r=t.config.description?.trim(),o={name:N(n),aliases:[n],...r?{description:r}:{},...e.instructions?{instructions:e.instructions}:{}},s=I.get(n)??new Set,c=new Set,d=[...new Set(e.tools.map(m=>m.name))].map(m=>ve(n,m)),f=i((m,g)=>{const w=ve(n,m,y=>{const M=G.get(y);return M!==void 0&&M!==g||c.has(y)||d.indexOf(y)!==d.lastIndexOf(y)});return G.set(w,g),c.add(w),w},"assignName");for(const m of e.tools){const g=rn({server:n,tool:m,name:f(m.name,`${n}\0${m.name}`),exposure:ne(t.config,m.name),namespace:o,timeoutMs:e.timeoutMs,getClient:i(async()=>{const w=L(n);if(!w||!p(w))throw new Error(`MCP server "${n}" is disabled.`);const y=w.connection;if(!y)throw new Error(`MCP server "${n}" is still starting.`);if(ne(w.entry.config,m.name)==="hidden"||y.state==="connected"&&!y.tools.some(M=>M.name===m.name))throw new Error(`MCP tool "${n}/${m.name}" is no longer available.`);return y},"getClient"),readableResources:i(()=>fe().some(w=>w.name===n),"readableResources")});K.set(g.name,g),a.registerTool(g)}I.set(n,c);for(const m of s){const g=K.get(m);!c.has(m)&&g&&a.registerTool({...g,exposure:"hidden"})}Q()},"registerTools"),de=i(e=>{for(const n of I.get(e)??[]){const t=K.get(n);t&&a.registerTool({...t,exposure:"hidden"})}I.set(e,new Set),Q()},"hideTools"),ue=i(()=>u.filter(e=>e.connection?.hasResources&&p(e)&&P(e.entry)!=="hidden"),"serversWithResources"),fe=i(()=>ue().flatMap(e=>e.connection?[e.connection]:[]),"resourceServers");let W;const Q=i(()=>{const e=new Set(ue().map(s=>P(s.entry))),t=["direct","codemode","deferred"].find(s=>e.has(s))??"hidden";if(t===W||W===void 0&&t==="hidden")return;const r=W==="direct";W=t;const o=en({exposure:t,servers:fe});for(const s of o)a.registerTool(s);if(r){const s=new Set(o.map(c=>c.name));a.setActiveTools(a.getActiveTools().filter(c=>!s.has(c)))}},"syncResourceTools"),_=i(e=>{const n=new Set;for(const y of u)if(p(y))for(const M of V(y.entry))n.add(M);const t=n.has("codemode"),r=n.has("deferred");if(!t&&!r)return;const o=a.getAllTools(),s=i(y=>o.some(M=>M.name===y&&M.reachesTools),"hasReachingTool"),c=s(F),d=s(H),f=a.getActiveTools(),m=[];t&&c&&b&&!f.includes(F)&&m.push(F),r&&d&&!f.includes(H)&&m.push(H),m.length>0&&a.setActiveTools([...f,...m]);const g=[...f,...m];if(c&&g.includes(F)||d&&g.includes(H)||j)return;j=!0;const w=t&&c&&!b?" (autoEnableCodemode is false)":"";e.ui.notify(`MCP tools are only reachable from the codemode or tool_search tool, but neither is active${w}; they cannot be called.`,"warning")},"ensureDiscoveryActive"),A=new Map,me=i(e=>{const n=e.oauthUrl;return n&&x?JSON.stringify(x.tokens(e.name,n)??null):"null"},"storedTokens"),Le=i(e=>{e.state!=="needs-auth"?A.delete(e):A.has(e)||A.set(e,me(e)),v()},"onConnectionChange"),ke=i(async e=>{const n=[...A].filter(([t,r])=>me(t)!==r);if(n.length!==0){for(const[t]of n)A.delete(t);await Promise.allSettled(n.map(([t])=>t.reconnect())),_(e)}},"reconnectSignedIn"),Ue=i(async(e,n)=>{const t=await B();if(!n())return;const r=new t.McpServerConnection({entry:e.entry,cwd:U,createTransport:l.createTransport??t.createDefaultTransport,credentials:q(t),providerToken:i(async o=>oe?.getApiKeyForProvider(o),"providerToken"),log:je(t),onTools:i(o=>{n()&&le(o)},"onTools"),onChange:i(o=>{n()?Le(o):A.delete(o)},"onChange")});return e.connection=r,v(),r},"createConnection"),Y=i((e,n)=>{const{signal:t}=$,r=Symbol();e.attempt=r;const o=i(()=>!t.aborted&&e.attempt===r&&p(e)&&u.includes(e),"isCurrent"),s=(async()=>{if(await n,!o())return;const c=await Ue(e,o);!c||!o()||await c.getClient().catch(()=>{})})();return e.ready=s.catch(()=>{}),s},"startConnection"),Ie=i(async(e,n)=>{for(;;){const t=e.flatMap(o=>p(o)&&u.includes(o)&&o.ready?[{server:o,ready:o.ready}]:[]);if(t.length===0||n?.aborted)return;let r;if(await Promise.race([Promise.all(t.map(o=>o.ready)),new Promise(o=>{r=i(()=>o(),"onAbort"),n?.addEventListener("abort",r,{once:!0})})]),r&&n?.removeEventListener("abort",r),n?.aborted||t.every(o=>!p(o.server)||!u.includes(o.server)||o.ready===o.server.ready))return}},"waitForServers"),Z=i((e,n)=>{const t=n?[]:S.map(r=>`config: ${r}`);for(const r of n??u){const o=r.connection?.state;(o==="needs-auth"||o==="failed")&&t.push(`${r.entry.name}: ${D(r)}`)}t.length!==0&&e.ui.notify(`MCP servers need attention:
6
6
  ${t.map(r=>` ${r}`).join(`
7
7
  `)}
8
- Run /mcp to fix.`,"warning")},"reportProblems"),ge=i((e,n,t=!1)=>{const r=t?C:e.entry.override,o=r?{...e.entry,override:r}:e.entry;if(o.scope!=="extension")try{je(o,n)}catch(s){return`Could not update ${o.override??o.source}: ${O(s)}`}e.entry={...o,config:{...o.config,...n}}},"saveConfig"),he=i(async(e,n,t)=>{const r=e.connection,o=r?.oauthUrl;if(!r||!o)return`MCP server "${e.entry.name}" does not use OAuth.`;const s=await F(),c=t?AbortSignal.any([S.signal,t]):S.signal;try{await ie(s.signInMcpServer({serverUrl:o,store:X(s).forServer(e.entry.name,o),settings:r.oauthSettings(),challenge:r.challenge,prompt:n,signal:c}))}catch(d){return d instanceof s.McpSignInCancelledError?"Sign-in cancelled.":`Sign-in failed: ${O(d)}`}r.challenge=void 0;try{await r.reconnect()}catch(d){return`Signed in, but ${O(d)}`}},"signIn"),pe=i(async e=>{const n=e.connection,t=n?.oauthUrl;if(!n||!t)return!1;const r=X(await F()).remove(e.entry.name,t);return await n.signOut(),r},"signOut"),ye=i(async e=>{const n=e.connection;if(!n)return`MCP server "${e.entry.name}" is disabled.`;const t=e.ready,r=(async()=>{await t,await n.reconnect()})();e.ready=r.catch(()=>{});try{await r;return}catch(o){return O(o)}},"reconnect"),xe=i(async(e,n,t=!1)=>{const r=ge(e,{enabled:n},t);if(r)return r;if(!n){const o=e.connection;e.attempt=void 0,e.connection=void 0,o&&(e.closing=Promise.all([o.close(),e.ready]).then(()=>{}));const s=e.closing;de(e.entry.name),M();try{await s}finally{e.closing===s&&(e.closing=void 0)}return}await K(e,e.closing)},"setEnabled"),We=i((e,n)=>{const t=ge(e,{exposure:n});if(t)return t;e.connection?.state==="connected"&&le(e.connection),G();const r=new Set(a.getAllTools().filter(s=>s.exposure!=="direct").map(s=>s.name)),o=U.get(e.entry.name)??new Set;a.setActiveTools(a.getActiveTools().filter(s=>!o.has(s)||!r.has(s))),M()},"setExposure"),ze=i(()=>[...w.map(e=>`config: ${e}`),...v.map(e=>`overridden: ${e}`)],"notices"),Fe=i(()=>({title:"MCP servers",error:ze().join(`
9
- `)||void 0,items:[...u].sort((e,n)=>Oe(e)-Oe(n)||e.entry.name.localeCompare(n.entry.name)).map(e=>({value:e.entry.name,label:e.entry.name,description:`${N(e)} \xB7 ${P(e.entry)} \xB7 ${e.entry.override?"global, project override":e.entry.scope??e.entry.source}`})),empty:`No MCP servers configured. Add them to ${Ce(z(),"mcp.json")} or .pi/mcp.json.`,confirmLabel:"manage",cancelLabel:"close"}),"serversMenu"),He=i(e=>{const n=j(e);if(!n)return{title:e,items:[],empty:"This server is no longer configured.",confirmLabel:"",cancelLabel:"back"};const{entry:t,connection:r}=n,o=t.scope==="extension"?"for this session":t.override?"saved to the project mcp.json":t.scope?`saved to the ${t.scope} mcp.json`:"saved to mcp.json",s=t.scope==="global"&&!t.override&&C!==void 0,c="saved to the project mcp.json",d=[];if(!p(n))d.push({value:"enable",label:"Enable",description:o}),s&&d.push({value:"enable-project",label:"Enable in this project",description:c});else{const h=r?.state;h==="needs-auth"&&d.push({value:"signin",label:"Sign in",description:"opens the browser"}),h==="connected"&&r&&d.push({value:"tools",label:"Tools",description:`${r.tools.length} offered`}),(h==="failed"||h==="disconnected"||h==="connected"||h==="needs-auth")&&d.push({value:"reconnect",label:"Reconnect"}),h==="connected"&&r?.oauthUrl&&d.push({value:"signout",label:"Sign out",description:"deletes the stored credentials"}),d.push({value:"exposure",label:"Exposure",description:P(t)}),d.push({value:"disable",label:"Disable",description:o}),s&&d.push({value:"disable-project",label:"Disable in this project",description:c})}const f=[wn(t),`${t.scope??"config"}: ${t.source}`,...t.override?[`project override: ${t.override}`]:[],`State: ${N(n,!1)}`],g=[n.message,r?.state==="connected"?void 0:r?.error].filter(h=>h!==void 0).join(`
8
+ Run /mcp to fix.`,"warning")},"reportProblems"),ge=i((e,n,t=!1)=>{const r=t?R:e.entry.override,o=r?{...e.entry,override:r}:e.entry;if(o.scope!=="extension")try{Oe(o,n)}catch(s){return`Could not update ${o.override??o.source}: ${O(s)}`}e.entry={...o,config:{...o.config,...n}}},"saveConfig"),he=i(async(e,n,t)=>{const r=e.connection,o=r?.oauthUrl;if(!r||!o)return`MCP server "${e.entry.name}" does not use OAuth.`;const s=await B(),c=t?AbortSignal.any([$.signal,t]):$.signal;try{await ie(s.signInMcpServer({serverUrl:o,store:q(s).forServer(e.entry.name,o),settings:r.oauthSettings(),challenge:r.challenge,prompt:n,signal:c}))}catch(d){return d instanceof s.McpSignInCancelledError?"Sign-in cancelled.":`Sign-in failed: ${O(d)}`}r.challenge=void 0;try{await r.reconnect()}catch(d){return`Signed in, but ${O(d)}`}},"signIn"),pe=i(async e=>{const n=e.connection,t=n?.oauthUrl;if(!n||!t)return!1;const r=q(await B()).remove(e.entry.name,t);return await n.signOut(),r},"signOut"),ye=i(async e=>{const n=e.connection;if(!n)return`MCP server "${e.entry.name}" is disabled.`;const t=e.ready,r=(async()=>{await t,await n.reconnect()})();e.ready=r.catch(()=>{});try{await r;return}catch(o){return O(o)}},"reconnect"),Ne=i(async(e,n,t=!1)=>{const r=ge(e,{enabled:n},t);if(r)return r;if(!n){const o=e.connection;e.attempt=void 0,e.connection=void 0,o&&(e.closing=Promise.all([o.close(),e.ready]).then(()=>{}));const s=e.closing;de(e.entry.name),v();try{await s}finally{e.closing===s&&(e.closing=void 0)}return}await Y(e,e.closing)},"setEnabled"),De=i((e,n)=>{const t=ge(e,{exposure:n});if(t)return t;e.connection?.state==="connected"&&le(e.connection),Q();const r=new Set(a.getAllTools().filter(s=>s.exposure!=="direct").map(s=>s.name)),o=I.get(e.entry.name)??new Set;a.setActiveTools(a.getActiveTools().filter(s=>!o.has(s)||!r.has(s))),v()},"setExposure"),xe=i(()=>[...S.map(e=>`config: ${e}`),...T.map(e=>`overridden: ${e}`)],"notices"),We=i(()=>({title:"MCP servers",error:xe().join(`
9
+ `)||void 0,items:[...u].sort((e,n)=>_e(e)-_e(n)||e.entry.name.localeCompare(n.entry.name)).map(e=>({value:e.entry.name,label:e.entry.name,description:`${D(e)} \xB7 ${P(e.entry)} \xB7 ${e.entry.override?"global, project override":e.entry.scope??e.entry.source}`})),empty:`No MCP servers configured. Add them to ${Ce(z(),"mcp.json")} or .pi/mcp.json.`,confirmLabel:"manage",cancelLabel:"close"}),"serversMenu"),ze=i(e=>{const n=L(e);if(!n)return{title:e,items:[],empty:"This server is no longer configured.",confirmLabel:"",cancelLabel:"back"};const{entry:t,connection:r}=n,o=t.scope==="extension"?"for this session":t.override?"saved to the project mcp.json":t.scope?`saved to the ${t.scope} mcp.json`:"saved to mcp.json",s=t.scope==="global"&&!t.override&&R!==void 0,c="saved to the project mcp.json",d=[];if(!p(n))d.push({value:"enable",label:"Enable",description:o}),s&&d.push({value:"enable-project",label:"Enable in this project",description:c});else{const g=r?.state;g==="needs-auth"&&d.push({value:"signin",label:"Sign in",description:"opens the browser"}),g==="connected"&&r&&d.push({value:"tools",label:"Tools",description:`${r.tools.length} offered`}),(g==="failed"||g==="disconnected"||g==="connected"||g==="needs-auth")&&d.push({value:"reconnect",label:"Reconnect"}),g==="connected"&&r?.oauthUrl&&d.push({value:"signout",label:"Sign out",description:"deletes the stored credentials"}),d.push({value:"exposure",label:"Exposure",description:P(t)}),d.push({value:"disable",label:"Disable",description:o}),s&&d.push({value:"disable-project",label:"Disable in this project",description:c})}const f=[yn(t),`${t.scope??"config"}: ${t.source}`,...t.override?[`project override: ${t.override}`]:[],`State: ${D(n,!1)}`],m=[n.message,r?.state==="connected"?void 0:r?.error].filter(g=>g!==void 0).join(`
10
10
  `);return{title:`MCP server ${e}`,details:f.join(`
11
- `),error:g||void 0,items:d,selected:d[0]?.value,confirmLabel:"select",cancelLabel:"back"}},"serverMenu"),Be=i(async(e,n)=>{const t=P(n.entry),r=Object.keys(n.entry.config.toolExposure??{}).length>0;await e.menu(()=>({title:`Tools of ${n.entry.name}`,details:`Exposure ${t}: ${t==="hidden"?"unreachable":te[t]}${r?`
12
- Some tools override it with toolExposure.`:""}`,items:(n.connection?.tools??[]).map(o=>{const s=ne(n.entry.config,o.name),c=Pe(o.description??"");return{value:o.name,label:o.name,description:s===t?c:`[${s}] ${c}`}}),empty:"The server offers no tools.",confirmLabel:"back",cancelLabel:"back"}))},"showTools"),Ve=i(async(e,n)=>{const t=P(n.entry),r=await e.menu(()=>({title:`Exposure of ${n.entry.name}`,details:n.entry.scope==="extension"?`Applies to this session; the server is registered by ${n.entry.source}.`:`Saved to ${n.entry.override??n.entry.source}.`,items:Object.keys(te).map(o=>({value:o,label:`${o===t?"\u2713 ":" "}${o}`,description:te[o]})),selected:t,confirmLabel:"save",cancelLabel:"back"}));if(!(!r||r===t))return We(n,r)},"chooseExposure"),be=i((e,n)=>{const t=`Sign in to ${n.entry.name}`,r=new AbortController,o=i(c=>e.status(t,c,()=>r.abort()),"status");let s="";return o("Contacting the authorization server\u2026"),he(n,{showAuthorizationUrl:i(c=>{s=c.href,se(c.href)},"showAuthorizationUrl"),promptForRedirectUrl:i(async c=>{const d=await e.redirectUrl(t,s,c);return o("Connecting\u2026"),d},"promptForRedirectUrl")},r.signal)},"signInWithUi"),we=i((e,n,t)=>{const r=t(),o=n.attempt,{signal:s}=S,c=i(d=>{s.aborted||n.attempt!==o||!u.includes(n)||(n.message=d,_(e),M())},"finish");ie(r.then(c,d=>c(O(d))))},"runInBackground"),Xe=i(async(e,n,t,r)=>{const{signal:o}=S;let s;switch(r){case"signin":s=await be(e,t);break;case"reconnect":we(n,t,async()=>{await ye(t)});break;case"signout":await pe(t);break;case"tools":await Be(e,t);break;case"exposure":s=await Ve(e,t);break;case"enable":case"disable":case"enable-project":case"disable-project":{const c=r.startsWith("enable");we(n,t,()=>xe(t,c,r.endsWith("-project")));break}}o.aborted||(t.message=s,_(n),M())},"runAction"),Je=i(async(e,n)=>{for(;;){const t=await e.menu(Fe,ce);if(!t)return;for(;;){const r=await e.menu(()=>He(t),ce),o=j(t);if(!r||!o)break;await Xe(e,n,o,r)}}},"manage"),qe=i(()=>{if(u.length===0&&w.length===0&&v.length===0)return`No MCP servers configured. Add them to ${Ce(z(),"mcp.json")} or .pi/mcp.json.`;const e=u.map(n=>{const{name:t}=n.entry,r=P(n.entry),o=n.connection;if(o?.state==="needs-auth")return`${t}: needs sign-in, run /mcp login ${t} (${r})`;const s=o?.state==="connected"?`, ${o.tools.length} tools`:"",c=p(n)?o?.state==="disconnected"?"disconnected, reconnects on next call":o?.state??"starting":"disabled",d=o?.error&&o.state!=="connected"?`
11
+ `),error:m||void 0,items:d,selected:d[0]?.value,confirmLabel:"select",cancelLabel:"back"}},"serverMenu"),Fe=i(async(e,n)=>{const t=P(n.entry),r=Object.keys(n.entry.config.toolExposure??{}).length>0;await e.menu(()=>({title:`Tools of ${n.entry.name}`,details:`Exposure ${t}: ${t==="hidden"?"unreachable":te[t]}${r?`
12
+ Some tools override it with toolExposure.`:""}`,items:(n.connection?.tools??[]).map(o=>{const s=ne(n.entry.config,o.name),c=Te(o.description??"");return{value:o.name,label:o.name,description:s===t?c:`[${s}] ${c}`}}),empty:"The server offers no tools.",confirmLabel:"back",cancelLabel:"back"}))},"showTools"),He=i(async(e,n)=>{const t=P(n.entry),r=await e.menu(()=>({title:`Exposure of ${n.entry.name}`,details:n.entry.scope==="extension"?`Applies to this session; the server is registered by ${n.entry.source}.`:`Saved to ${n.entry.override??n.entry.source}.`,items:Object.keys(te).map(o=>({value:o,label:`${o===t?"\u2713 ":" "}${o}`,description:te[o]})),selected:t,confirmLabel:"save",cancelLabel:"back"}));if(!(!r||r===t))return De(n,r)},"chooseExposure"),be=i((e,n)=>{const t=`Sign in to ${n.entry.name}`,r=new AbortController,o=i(c=>e.status(t,c,()=>r.abort()),"status");let s="";return o("Contacting the authorization server\u2026"),he(n,{showAuthorizationUrl:i(c=>{s=c.href,se(c.href)},"showAuthorizationUrl"),promptForRedirectUrl:i(async c=>{const d=await e.redirectUrl(t,s,c);return o("Connecting\u2026"),d},"promptForRedirectUrl")},r.signal)},"signInWithUi"),we=i((e,n,t)=>{const r=t(),o=n.attempt,{signal:s}=$,c=i(d=>{s.aborted||n.attempt!==o||!u.includes(n)||(n.message=d,_(e),v())},"finish");ie(r.then(c,d=>c(O(d))))},"runInBackground"),Be=i(async(e,n,t,r)=>{const{signal:o}=$;let s;switch(r){case"signin":s=await be(e,t);break;case"reconnect":we(n,t,async()=>{await ye(t)});break;case"signout":await pe(t);break;case"tools":await Fe(e,t);break;case"exposure":s=await He(e,t);break;case"enable":case"disable":case"enable-project":case"disable-project":{const c=r.startsWith("enable");we(n,t,()=>Ne(t,c,r.endsWith("-project")));break}}o.aborted||(t.message=s,_(n),v())},"runAction"),Ve=i(async(e,n)=>{for(;;){const t=await e.menu(We,ce);if(!t)return;for(;;){const r=await e.menu(()=>ze(t),ce),o=L(t);if(!r||!o)break;await Be(e,n,o,r)}}},"manage"),Xe=i(()=>{if(u.length===0&&S.length===0&&T.length===0)return`No MCP servers configured. Add them to ${Ce(z(),"mcp.json")} or .pi/mcp.json.`;const e=u.map(n=>{const{name:t}=n.entry,r=P(n.entry),o=n.connection;if(o?.state==="needs-auth")return`${t}: needs sign-in, run /mcp login ${t} (${r})`;const s=o?.state==="connected"?`, ${o.tools.length} tools`:"",c=p(n)?o?.state==="disconnected"?"disconnected, reconnects on next call":o?.state??"starting":"disabled",d=o?.error&&o.state!=="connected"?`
13
13
  ${o.error.split(`
14
14
  `).join(`
15
- `)}`:"";return`${t}: ${c}${s} (${r})${d}`});for(const n of w)e.push(`config error: ${n}`);for(const n of v)e.push(`overridden: ${n}`);return e.join(`
16
- `)},"formatStatus"),Y=i(async(e,n,t)=>{if(e){const c=j(e);return c?t.eligible(c)||n.ui.notify(t.none,"error"):n.ui.notify(`No MCP server named "${e}".`,"error"),c&&t.eligible(c)?c:void 0}const r=u.filter(t.eligible);if(r.length===0){n.ui.notify(t.none,"info");return}const o=r.filter(t.preferred);if(r.length===1)return r[0];if(o.length===1)return o[0];const s=await n.ui.select("MCP server",r.map(c=>c.entry.name));return r.find(c=>c.entry.name===s)},"pickServer"),Se=i(e=>e.connection?.oauthUrl!==void 0,"usesOAuth"),$e={eligible:Se,preferred:i(e=>e.connection?.state==="needs-auth","preferred"),none:"No enabled MCP server uses OAuth. Only HTTP servers without an Authorization header do."},Ge=i(async(e,n)=>{const{name:t}=e.entry;if(!n.hasUI){n.ui.notify(`Signing in to MCP server "${t}" requires interactive mode.`,"error");return}const{signal:r}=S;let o;if(n.mode==="tui"?await Ee(n,async s=>{o=await be(s,e)}):o=await he(e,{showAuthorizationUrl:i(s=>{n.ui.notify(`Sign in to MCP server "${t}" in your browser:
17
- ${s.href}`,"info"),se(s.href)},"showAuthorizationUrl"),promptForRedirectUrl:i(s=>n.ui.input(`Waiting for sign-in to "${t}". If the browser cannot reach this machine, paste the URL it was redirected to.`,"http://127.0.0.1:.../callback?code=...",{signal:s}),"promptForRedirectUrl")}),!r.aborted){if(o){n.ui.notify(o,o==="Sign-in cancelled."?"info":"error");return}_(n),n.ui.notify(`Signed in to MCP server "${t}" (${e.connection?.tools.length??0} tools).`,"info")}},"loginCommand");a.on("session_start",(e,n)=>{const t=(l.loadConfig??$n)(n);w=t.errors,C=t.projectConfig,b=t.autoEnableCodemode??!0,R=!1,m=!1,k=n.cwd,oe=n.modelRegistry,S=new AbortController;const{signal:r}=S;T=t.servers;const o=ae();v=o.overridden,u=[...t.servers.map(d=>({entry:d})),...o.servers],M(),_(n);const s=u.filter(p);if(s.length===0){Q(n);return}const c=new Promise(d=>setImmediate(d)).then(()=>F());L=Promise.all(s.map(d=>K(d,c))).then(()=>{r.aborted||Q(n)}).catch(d=>{try{n.ui.notify(`MCP failed to load: ${O(d)}`,"error")}catch{}})});const Ke=i(async e=>{if(m)return;m=!0;const n=u.flatMap(o=>p(o)&&un(o.entry)&&o.ready?[o.ready]:[]);if(n.length===0)return;let t;const r=await Promise.race([Promise.all(n).then(()=>!0),new Promise(o=>{t=setTimeout(()=>o(!1),E)})]);clearTimeout(t),r||e.ui.notify("MCP servers are still connecting; their tools become available once connected.","info")},"waitForDirectServers");a.on("before_agent_start",async(e,n)=>{await Ke(n);const{sections:t}=e.systemPromptOptions,r=yn(u);r?t[_e]=r:delete t[_e]}),a.on("tool_call",async(e,n)=>{const t=a.getAllTools().find(s=>s.name===e.toolName);if(!t)return;const r=u.filter(s=>p(s)&&s.ready);if(r.length===0)return;let o=[];if(ve(t)){const{code:s}=e.input,c=typeof s=="string"?s:"";o=r.filter(d=>bn(c,d.entry.name))}else if(Me(t)||dn.has(t.name))o=r;else{const s=J.get(e.toolName)?.split("\0",1)[0];o=r.filter(c=>c.entry.name===s)}await De(o,n.signal)}),a.on("turn_start",async(e,n)=>{A.size>0&&await Ie(n)}),a.on("mcp_servers_change",async(e,n)=>{const{signal:t}=S;if(t.aborted)return;const r=ae();v=r.overridden;const o=new Map(r.servers.map(f=>[f.entry.name,f])),s=u.filter(f=>f.entry.scope==="extension"&&o.get(f.entry.name)?.registeredConfig!==f.registeredConfig);u=u.filter(f=>!s.includes(f));for(const f of s)de(f.entry.name);const c=r.servers.filter(f=>!j(f.entry.name));u.push(...c),M(),_(n),await Promise.all(s.map(f=>f.connection?.close()));const d=c.filter(p);if(!(t.aborted||d.length===0)){try{if(await Promise.all(d.map(f=>K(f))),t.aborted){await Promise.all(d.map(f=>f.connection?.close()));return}}catch(f){n.ui.notify(`MCP failed to load: ${O(f)}`,"error");return}t.aborted||Q(n,d)}}),a.on("session_shutdown",async()=>{S.abort();const e=Le();u=[],M(),await Promise.all([...B,...e.map(n=>n.close())])}),a.registerCommand("mcp",{description:"Manage MCP servers: sign in, reconnect, enable or disable, and change exposure",getArgumentCompletions:i(e=>{const[n,t,...r]=e.trimStart().split(/\s+/);if(r.length>0)return null;if(t===void 0)return["login","logout","reconnect"].filter(s=>s.startsWith(n??"")).map(s=>({value:`${s} `,label:s}));if(n!=="login"&&n!=="logout"&&n!=="reconnect")return null;const o=u.filter(s=>n==="reconnect"?s.connection!==void 0:Se(s)).filter(s=>s.entry.name.startsWith(t)).map(s=>({value:`${n} ${s.entry.name}`,label:s.entry.name,description:N(s)}));return o.length>0?o:null},"getArgumentCompletions"),handler:i(async(e,n)=>{const[t,r,...o]=e.trim().split(/\s+/).filter(Boolean);if(t===void 0){n.mode==="tui"?await Ee(n,s=>Je(s,n)):(await L,n.ui.notify(qe(),"info"));return}if(o.length>0){n.ui.notify(Re,"warning");return}switch(await L,t){case"login":{const s=await Y(r,n,$e);s&&await Ge(s,n);return}case"logout":{const s=await Y(r,n,$e);if(!s)return;const c=await pe(s);n.ui.notify(c?`Signed out of MCP server "${s.entry.name}".`:`No stored credentials for MCP server "${s.entry.name}".`,"info");return}case"reconnect":{const s=await Y(r,n,{eligible:i(d=>d.connection!==void 0,"eligible"),preferred:i(d=>d.connection?.state==="failed"||d.connection?.state==="disconnected","preferred"),none:"No enabled MCP server to reconnect."});if(!s)return;const c=await ye(s);c?n.ui.notify(c,"error"):(_(n),n.ui.notify(`Reconnected to MCP server "${s.entry.name}" (${N(s)}).`,"info"));return}default:n.ui.notify(Re,"warning")}},"handler")})}}i(Sn,"createMcpExtension");function $n(l){return en({agentDir:z(),cwd:l.cwd,projectTrusted:l.isProjectTrusted()})}i($n,"defaultLoadConfig");var kn=Sn();export{Ae as MAX_SERVERS_SECTION_CHARS,_e as MCP_SERVERS_SECTION,Sn as createMcpExtension,kn as default,yn as renderServersSection};
15
+ `)}`:"";return`${t}: ${c}${s} (${r})${d}`});for(const n of S)e.push(`config error: ${n}`);for(const n of T)e.push(`overridden: ${n}`);return e.join(`
16
+ `)},"formatStatus"),ee=i(async(e,n,t)=>{if(e){const c=L(e);return c?t.eligible(c)||n.ui.notify(t.none,"error"):n.ui.notify(`No MCP server named "${e}".`,"error"),c&&t.eligible(c)?c:void 0}const r=u.filter(t.eligible);if(r.length===0){n.ui.notify(t.none,"info");return}const o=r.filter(t.preferred);if(r.length===1)return r[0];if(o.length===1)return o[0];const s=await n.ui.select("MCP server",r.map(c=>c.entry.name));return r.find(c=>c.entry.name===s)},"pickServer"),Se=i(e=>e.connection?.oauthUrl!==void 0,"usesOAuth"),$e={eligible:Se,preferred:i(e=>e.connection?.state==="needs-auth","preferred"),none:"No enabled MCP server uses OAuth. Only HTTP servers without an Authorization header do."},Je=i(async(e,n)=>{const{name:t}=e.entry;if(!n.hasUI){n.ui.notify(`Signing in to MCP server "${t}" requires interactive mode.`,"error");return}const{signal:r}=$;let o;if(n.mode==="tui"?await Me(n,async s=>{o=await be(s,e)}):o=await he(e,{showAuthorizationUrl:i(s=>{n.ui.notify(`Sign in to MCP server "${t}" in your browser:
17
+ ${s.href}`,"info"),se(s.href)},"showAuthorizationUrl"),promptForRedirectUrl:i(s=>n.ui.input(`Waiting for sign-in to "${t}". If the browser cannot reach this machine, paste the URL it was redirected to.`,"http://127.0.0.1:.../callback?code=...",{signal:s}),"promptForRedirectUrl")}),!r.aborted){if(o){n.ui.notify(o,o==="Sign-in cancelled."?"info":"error");return}_(n),n.ui.notify(`Signed in to MCP server "${t}" (${e.connection?.tools.length??0} tools).`,"info")}},"loginCommand");a.on("session_start",(e,n)=>{const t=(l.loadConfig??wn)(n);S=t.errors,R=t.projectConfig,b=t.autoEnableCodemode??!0,j=!1,h=!1,U=n.cwd,oe=n.modelRegistry,$=new AbortController;const{signal:r}=$;C=t.servers;const o=ae();T=o.overridden,u=[...t.servers.map(d=>({entry:d})),...o.servers],v(),_(n);const s=u.filter(p);if(s.length===0){Z(n);return}const c=new Promise(d=>setImmediate(d)).then(()=>B());k=Promise.all(s.map(d=>Y(d,c))).then(()=>{r.aborted||Z(n)}).catch(d=>{try{n.ui.notify(`MCP failed to load: ${O(d)}`,"error")}catch{}})});const qe=i(async e=>{if(h)return;h=!0;const n=u.flatMap(o=>p(o)&&ln(o.entry)&&o.ready?[o.ready]:[]);if(n.length===0)return;let t;const r=await Promise.race([Promise.all(n).then(()=>!0),new Promise(o=>{t=setTimeout(()=>o(!1),E)})]);clearTimeout(t),r||e.ui.notify("MCP servers are still connecting; their tools become available once connected.","info")},"waitForDirectServers");a.on("before_agent_start",async(e,n)=>{await qe(n);const{sections:t}=e.systemPromptOptions,r=hn(u);r?t[Ee]=r:delete t[Ee]}),a.on("tool_call",async(e,n)=>{const t=a.getAllTools().find(c=>c.name===e.toolName);if(!t)return;const r=u.filter(c=>p(c)&&c.ready);if(r.length===0)return;let o=[];const s=t.reachesTools?.(e.input);if(s!==void 0)o=r.filter(c=>pn(s,c.entry.name));else if(an.has(t.name))o=r;else{const c=G.get(e.toolName)?.split("\0",1)[0];o=r.filter(d=>d.entry.name===c)}await Ie(o,n.signal)}),a.on("turn_start",async(e,n)=>{A.size>0&&await ke(n)}),a.on("mcp_servers_change",async(e,n)=>{const{signal:t}=$;if(t.aborted)return;const r=ae();T=r.overridden;const o=new Map(r.servers.map(f=>[f.entry.name,f])),s=u.filter(f=>f.entry.scope==="extension"&&o.get(f.entry.name)?.registeredConfig!==f.registeredConfig);u=u.filter(f=>!s.includes(f));for(const f of s)de(f.entry.name);const c=r.servers.filter(f=>!L(f.entry.name));u.push(...c),v(),_(n),await Promise.all(s.map(f=>f.connection?.close()));const d=c.filter(p);if(!(t.aborted||d.length===0)){try{if(await Promise.all(d.map(f=>Y(f))),t.aborted){await Promise.all(d.map(f=>f.connection?.close()));return}}catch(f){n.ui.notify(`MCP failed to load: ${O(f)}`,"error");return}t.aborted||Z(n,d)}}),a.on("session_shutdown",async()=>{$.abort();const e=Re();u=[],v(),await Promise.all([...X,...e.map(n=>n.close())])}),a.registerCommand("mcp",{description:"Manage MCP servers: sign in, reconnect, enable or disable, and change exposure",getArgumentCompletions:i(e=>{const[n,t,...r]=e.trimStart().split(/\s+/);if(r.length>0)return null;if(t===void 0)return["login","logout","reconnect"].filter(s=>s.startsWith(n??"")).map(s=>({value:`${s} `,label:s}));if(n!=="login"&&n!=="logout"&&n!=="reconnect")return null;const o=u.filter(s=>n==="reconnect"?s.connection!==void 0:Se(s)).filter(s=>s.entry.name.startsWith(t)).map(s=>({value:`${n} ${s.entry.name}`,label:s.entry.name,description:D(s)}));return o.length>0?o:null},"getArgumentCompletions"),handler:i(async(e,n)=>{const[t,r,...o]=e.trim().split(/\s+/).filter(Boolean);if(t===void 0){n.mode==="tui"?await Me(n,s=>Ve(s,n)):(await k,n.ui.notify(Xe(),"info"));return}if(o.length>0){n.ui.notify(Ae,"warning");return}switch(await k,t){case"login":{const s=await ee(r,n,$e);s&&await Je(s,n);return}case"logout":{const s=await ee(r,n,$e);if(!s)return;const c=await pe(s);n.ui.notify(c?`Signed out of MCP server "${s.entry.name}".`:`No stored credentials for MCP server "${s.entry.name}".`,"info");return}case"reconnect":{const s=await ee(r,n,{eligible:i(d=>d.connection!==void 0,"eligible"),preferred:i(d=>d.connection?.state==="failed"||d.connection?.state==="disconnected","preferred"),none:"No enabled MCP server to reconnect."});if(!s)return;const c=await ye(s);c?n.ui.notify(c,"error"):(_(n),n.ui.notify(`Reconnected to MCP server "${s.entry.name}" (${D(s)}).`,"info"));return}default:n.ui.notify(Ae,"warning")}},"handler")})}}i(bn,"createMcpExtension");function wn(l){return Ye({agentDir:z(),cwd:l.cwd,projectTrusted:l.isProjectTrusted()})}i(wn,"defaultLoadConfig");var jn=bn();export{Pe as MAX_SERVERS_SECTION_CHARS,Ee as MCP_SERVERS_SECTION,bn as createMcpExtension,jn as default,hn as renderServersSection};
@@ -14,11 +14,6 @@ export interface McpResourceServer {
14
14
  allResourceTemplates(options: McpRequestOptions): Promise<ResourceTemplate[]>;
15
15
  readResource(uri: string, options: McpRequestOptions): Promise<ReadResourceResult>;
16
16
  }
17
- export declare function isMcpAppResource(item: {
18
- uri?: string;
19
- uriTemplate?: string;
20
- mimeType?: string;
21
- }): boolean;
22
17
  export declare function createMcpResourceToolDefinitions(options: {
23
18
  exposure: McpExposure;
24
19
  servers: () => readonly McpResourceServer[];
@@ -1 +1 @@
1
- var q=Object.defineProperty;var p=(e,n)=>q(e,"name",{value:n,configurable:!0});import{LIST_MCP_RESOURCE_TEMPLATES_TOOL as C,LIST_MCP_RESOURCES_TOOL as x,READ_MCP_RESOURCE_TOOL as E}from"../../core/mcp-servers.js";import{limitMcpContent as S,toModelContent as $,toToolExposure as M}from"./tools.js";function D(e){return(e.uri??e.uriTemplate??"").startsWith("ui://")||/;\s*profile\s*=\s*"?mcp-app"?/i.test(e.mimeType??"")}p(D,"isMcpAppResource");function P(e,n){const{_meta:a,icons:h,...v}=n;return{server:e,...v}}p(P,"listed");const _=p(e=>({type:"string",description:e}),"stringProperty"),H=_("MCP server name. Omit to list every server with resources."),N=_("Opaque cursor from a previous call with the same server; omit for the first page."),O={type:"object",properties:{server:H,cursor:N},additionalProperties:!1},z={type:"object",properties:{server:_("MCP server name exactly as configured. Must match the 'server' field returned by list_mcp_resources."),uri:_("Resource URI to read. Must be one of the URIs returned by list_mcp_resources.")},required:["server","uri"],additionalProperties:!1},i={type:"string"},I={type:"array",description:"Servers that could not be listed",items:{type:"object",properties:{server:{type:"string"},error:{type:"string"}},required:["server","error"]}},F={type:"object",properties:{server:i,resources:{type:"array",items:{type:"object",properties:{server:{type:"string"},uri:{type:"string"},name:{type:"string"},title:i,description:i,mimeType:i,size:{type:"number"}},required:["server","uri","name"]}},nextCursor:i,errors:I},required:["resources"]},G={type:"object",properties:{server:i,resourceTemplates:{type:"array",items:{type:"object",properties:{server:{type:"string"},uriTemplate:{type:"string",description:"RFC 6570 URI template"},name:{type:"string"},title:i,description:i,mimeType:i},required:["server","uriTemplate","name"]}},nextCursor:i,errors:I},required:["resourceTemplates"]},J={type:"object",properties:{server:{type:"string"},uri:{type:"string"},contents:{type:"array",items:{anyOf:[{type:"object",properties:{uri:{type:"string"},mimeType:i,text:{type:"string"}},required:["uri","text"]},{type:"object",properties:{uri:{type:"string"},mimeType:i,blob:{type:"string",description:"base64"}},required:["uri","blob"]}]}}},required:["server","uri","contents"]};function f(e,n){const a=e?.[n];if(a!=null){if(typeof a!="string")throw new Error(`${n} must be a string`);return a.trim()||void 0}}p(f,"stringArgument");function V(e){return e instanceof Error?e.message:String(e)}p(V,"errorMessage");async function A(e,n,a){const{content:h,fullOutputPath:v}=await S([{type:"text",text:JSON.stringify(a)}]);return{content:h,details:{server:n??"",tool:e,...v?{fullOutputPath:v}:{}},structuredContent:a}}p(A,"jsonResult");function K(e){const n={readOnlyHint:!0},a=p(y=>{const o=e.servers(),c=o.find(t=>t.name===y);if(c)return c;const u=o.map(t=>t.name).join(", ");throw new Error(`MCP server "${y}" has no resources${u?`. Servers with resources: ${u}`:""}`)},"findServer"),h=p(async(y,o,c,u,t)=>{const s=f(y,"server"),l=f(y,"cursor"),m=p(r=>!D(r),"visible");if(s){const r=a(s),d=await u(r,l,{signal:o,timeoutMs:r.timeoutMs});return{server:r.name,[c]:d.items.filter(m).map(R=>P(r.name,R)),...d.nextCursor===void 0?{}:{nextCursor:d.nextCursor}}}if(l)throw new Error("cursor can only be used when a server is specified");const T=[...e.servers()].sort((r,d)=>r.name.localeCompare(d.name)),w=await Promise.allSettled(T.map(r=>t(r,{signal:o,timeoutMs:r.timeoutMs}))),b=[],g=[];return w.forEach((r,d)=>{const R=T[d].name;r.status==="fulfilled"?b.push(...r.value.filter(m).map(j=>P(R,j))):g.push({server:R,error:V(r.reason)})}),{[c]:b,...g.length>0?{errors:g}:{}}},"list"),v={name:x,label:x,description:"Lists resources provided by MCP servers. Resources allow servers to share data that provides context to language models, such as files, database schemas, or application-specific information. Prefer resources over web search when possible.",parameters:O,outputSchema:F,exposure:M(e.exposure),annotations:n,async execute(y,o,c){const u=await h(o,c,"resources",async(t,s,l)=>{const m=await t.resourcesPage(s,l);return{items:m.resources,nextCursor:m.nextCursor}},(t,s)=>t.allResources(s));return A(x,f(o,"server"),u)}},L={name:C,label:C,description:"Lists resource templates provided by MCP servers. Parameterized resource templates allow servers to share data that takes parameters and provides context to language models, such as files, database schemas, or application-specific information. Prefer resource templates over web search when possible.",parameters:O,outputSchema:G,exposure:M(e.exposure),annotations:n,async execute(y,o,c){const u=await h(o,c,"resourceTemplates",async(t,s,l)=>{const m=await t.resourceTemplatesPage(s,l);return{items:m.resourceTemplates,nextCursor:m.nextCursor}},(t,s)=>t.allResourceTemplates(s));return A(C,f(o,"server"),u)}},U={name:E,label:E,description:"Read a specific resource from an MCP server given the server name and resource URI.",parameters:z,outputSchema:J,exposure:M(e.exposure),annotations:n,async execute(y,o,c){const u=f(o,"server"),t=f(o,"uri");if(!u)throw new Error("server must be provided");if(!t)throw new Error("uri must be provided");const s=a(u),l=await s.readResource(t,{signal:c,timeoutMs:s.timeoutMs}),m=l.contents.flatMap(r=>[...l.contents.length>1?[{type:"text",text:`${r.uri}:`}]:[],{type:"resource",resource:r}]),T=await $(s.name,m),{content:w,fullOutputPath:b}=await S(T.length>0?T:[{type:"text",text:`Resource ${t} is empty.`}]),g=l.contents.map(({_meta:r,...d})=>d);return{content:w,details:{server:s.name,tool:E,...b?{fullOutputPath:b}:{}},structuredContent:{server:s.name,uri:t,contents:g}}}};return[v,L,U]}p(K,"createMcpResourceToolDefinitions");export{x as LIST_MCP_RESOURCES_TOOL,C as LIST_MCP_RESOURCE_TEMPLATES_TOOL,E as READ_MCP_RESOURCE_TOOL,K as createMcpResourceToolDefinitions,D as isMcpAppResource};
1
+ var q=Object.defineProperty;var p=(e,n)=>q(e,"name",{value:n,configurable:!0});import{LIST_MCP_RESOURCE_TEMPLATES_TOOL as C,LIST_MCP_RESOURCES_TOOL as x,READ_MCP_RESOURCE_TOOL as E}from"../../core/mcp-servers.js";import{limitMcpContent as S,toModelContent as $,toToolExposure as M}from"./tools.js";function D(e){return(e.uri??e.uriTemplate??"").startsWith("ui://")||/;\s*profile\s*=\s*"?mcp-app"?/i.test(e.mimeType??"")}p(D,"isMcpAppResource");function P(e,n){const{_meta:a,icons:h,...v}=n;return{server:e,...v}}p(P,"listed");const _=p(e=>({type:"string",description:e}),"stringProperty"),H=_("MCP server name. Omit to list every server with resources."),N=_("Opaque cursor from a previous call with the same server; omit for the first page."),O={type:"object",properties:{server:H,cursor:N},additionalProperties:!1},z={type:"object",properties:{server:_("MCP server name exactly as configured. Must match the 'server' field returned by list_mcp_resources."),uri:_("Resource URI to read. Must be one of the URIs returned by list_mcp_resources.")},required:["server","uri"],additionalProperties:!1},i={type:"string"},I={type:"array",description:"Servers that could not be listed",items:{type:"object",properties:{server:{type:"string"},error:{type:"string"}},required:["server","error"]}},F={type:"object",properties:{server:i,resources:{type:"array",items:{type:"object",properties:{server:{type:"string"},uri:{type:"string"},name:{type:"string"},title:i,description:i,mimeType:i,size:{type:"number"}},required:["server","uri","name"]}},nextCursor:i,errors:I},required:["resources"]},G={type:"object",properties:{server:i,resourceTemplates:{type:"array",items:{type:"object",properties:{server:{type:"string"},uriTemplate:{type:"string",description:"RFC 6570 URI template"},name:{type:"string"},title:i,description:i,mimeType:i},required:["server","uriTemplate","name"]}},nextCursor:i,errors:I},required:["resourceTemplates"]},J={type:"object",properties:{server:{type:"string"},uri:{type:"string"},contents:{type:"array",items:{anyOf:[{type:"object",properties:{uri:{type:"string"},mimeType:i,text:{type:"string"}},required:["uri","text"]},{type:"object",properties:{uri:{type:"string"},mimeType:i,blob:{type:"string",description:"base64"}},required:["uri","blob"]}]}}},required:["server","uri","contents"]};function f(e,n){const a=e?.[n];if(a!=null){if(typeof a!="string")throw new Error(`${n} must be a string`);return a.trim()||void 0}}p(f,"stringArgument");function V(e){return e instanceof Error?e.message:String(e)}p(V,"errorMessage");async function A(e,n,a){const{content:h,fullOutputPath:v}=await S([{type:"text",text:JSON.stringify(a)}]);return{content:h,details:{server:n??"",tool:e,...v?{fullOutputPath:v}:{}},structuredContent:a}}p(A,"jsonResult");function K(e){const n={readOnlyHint:!0},a=p(y=>{const o=e.servers(),c=o.find(t=>t.name===y);if(c)return c;const u=o.map(t=>t.name).join(", ");throw new Error(`MCP server "${y}" has no resources${u?`. Servers with resources: ${u}`:""}`)},"findServer"),h=p(async(y,o,c,u,t)=>{const s=f(y,"server"),l=f(y,"cursor"),m=p(r=>!D(r),"visible");if(s){const r=a(s),d=await u(r,l,{signal:o,timeoutMs:r.timeoutMs});return{server:r.name,[c]:d.items.filter(m).map(R=>P(r.name,R)),...d.nextCursor===void 0?{}:{nextCursor:d.nextCursor}}}if(l)throw new Error("cursor can only be used when a server is specified");const T=[...e.servers()].sort((r,d)=>r.name.localeCompare(d.name)),w=await Promise.allSettled(T.map(r=>t(r,{signal:o,timeoutMs:r.timeoutMs}))),b=[],g=[];return w.forEach((r,d)=>{const R=T[d].name;r.status==="fulfilled"?b.push(...r.value.filter(m).map(j=>P(R,j))):g.push({server:R,error:V(r.reason)})}),{[c]:b,...g.length>0?{errors:g}:{}}},"list"),v={name:x,label:x,description:"Lists resources provided by MCP servers. Resources allow servers to share data that provides context to language models, such as files, database schemas, or application-specific information. Prefer resources over web search when possible.",parameters:O,outputSchema:F,exposure:M(e.exposure),annotations:n,async execute(y,o,c){const u=await h(o,c,"resources",async(t,s,l)=>{const m=await t.resourcesPage(s,l);return{items:m.resources,nextCursor:m.nextCursor}},(t,s)=>t.allResources(s));return A(x,f(o,"server"),u)}},L={name:C,label:C,description:"Lists resource templates provided by MCP servers. Parameterized resource templates allow servers to share data that takes parameters and provides context to language models, such as files, database schemas, or application-specific information. Prefer resource templates over web search when possible.",parameters:O,outputSchema:G,exposure:M(e.exposure),annotations:n,async execute(y,o,c){const u=await h(o,c,"resourceTemplates",async(t,s,l)=>{const m=await t.resourceTemplatesPage(s,l);return{items:m.resourceTemplates,nextCursor:m.nextCursor}},(t,s)=>t.allResourceTemplates(s));return A(C,f(o,"server"),u)}},U={name:E,label:E,description:"Read a specific resource from an MCP server given the server name and resource URI.",parameters:z,outputSchema:J,exposure:M(e.exposure),annotations:n,async execute(y,o,c){const u=f(o,"server"),t=f(o,"uri");if(!u)throw new Error("server must be provided");if(!t)throw new Error("uri must be provided");const s=a(u),l=await s.readResource(t,{signal:c,timeoutMs:s.timeoutMs}),m=l.contents.flatMap(r=>[...l.contents.length>1?[{type:"text",text:`${r.uri}:`}]:[],{type:"resource",resource:r}]),T=await $(s.name,m),{content:w,fullOutputPath:b}=await S(T.length>0?T:[{type:"text",text:`Resource ${t} is empty.`}]),g=l.contents.map(({_meta:r,...d})=>d);return{content:w,details:{server:s.name,tool:E,...b?{fullOutputPath:b}:{}},structuredContent:{server:s.name,uri:t,contents:g}}}};return[v,L,U]}p(K,"createMcpResourceToolDefinitions");export{x as LIST_MCP_RESOURCES_TOOL,C as LIST_MCP_RESOURCE_TEMPLATES_TOOL,E as READ_MCP_RESOURCE_TOOL,K as createMcpResourceToolDefinitions};
@@ -3,7 +3,7 @@ import { type OAuthChallenge } from "@earendil-works/pi-mcp/oauth";
3
3
  import type { McpServerEntry } from "./config.ts";
4
4
  import type { McpServerLog } from "./log.ts";
5
5
  import { type McpOAuthCredentialStore, type McpOAuthSettings } from "./oauth.ts";
6
- import { type McpResourceServer } from "./resources.ts";
6
+ import type { McpResourceServer } from "./resources.ts";
7
7
  import type { McpToolCaller } from "./tools.ts";
8
8
  export { McpOAuthAuthorizationRequiredError } from "@earendil-works/pi-mcp/oauth";
9
9
  export { McpServerLog } from "./log.ts";
@@ -17,8 +17,6 @@ export declare class McpServerConnection implements McpToolCaller, McpResourceSe
17
17
  error: string | undefined;
18
18
  tools: McpTool[];
19
19
  hasResources: boolean;
20
- resources: Resource[];
21
- resourceTemplates: ResourceTemplate[];
22
20
  instructions: string | undefined;
23
21
  challenge: OAuthChallenge | undefined;
24
22
  private client;
@@ -65,6 +63,5 @@ export declare class McpServerConnection implements McpToolCaller, McpResourceSe
65
63
  private connectFailed;
66
64
  private handleClientClose;
67
65
  private refreshTools;
68
- private refreshResources;
69
66
  close(): Promise<void>;
70
67
  }
@@ -1,3 +1,3 @@
1
- var E=Object.defineProperty;var s=(n,e)=>E(n,"name",{value:e,configurable:!0});import{homedir as f}from"node:os";import{basename as P,join as A,resolve as O}from"node:path";import{setTimeout as b}from"node:timers/promises";import{pathToFileURL as N}from"node:url";import{JSON_RPC_ERROR_CODES as _,McpAuthRequiredError as $,McpClient as k,McpError as U,McpHttpError as m,McpSessionExpiredError as I,StdioTransport as h,StreamableHttpTransport as L}from"@earendil-works/pi-mcp";import{McpOAuthAuthorizationRequiredError as x}from"@earendil-works/pi-mcp/oauth";import{VERSION as F}from"../../config.js";import{resolveConfigValueOrThrow as g,resolveHeadersOrThrow as q}from"../../core/resolve-config-value.js";import{createMcpAuthProvider as D}from"./oauth.js";import{isMcpAppResource as p}from"./resources.js";import{McpOAuthAuthorizationRequiredError as ie}from"@earendil-works/pi-mcp/oauth";import{McpServerLog as oe}from"./log.js";import{createMcpAuthProvider as ae,McpOAuthCredentialStore as he,McpSignInCancelledError as le,signInMcpServer as ue}from"./oauth.js";const H=60,w=2e3,T=[250,1e3];function l(n){return n instanceof Error?n.message:String(n)}s(l,"errorMessage");function C(n){return n instanceof m?n.status===408||n.status===429||n.status>=500&&n.status!==501:n instanceof TypeError}s(C,"isTransientError");function y(n){const e="url"in n.config?n.config.auth?.provider:void 0;return`MCP server "${n.name}" requires sign-in. Run ${e?`/login ${e}`:"/mcp"} to sign in.`}s(y,"signInRequiredMessage");function j(n){const{config:e}=n;return!("url"in e)||e.auth?!1:!Object.keys(e.headers??{}).some(t=>t.toLowerCase()==="authorization")}s(j,"usesOAuth");function u(n){return n==="~"?f():n.startsWith("~/")||process.platform==="win32"&&n.startsWith("~\\")?A(f(),n.slice(2)):n}s(u,"expandHome");function ee(n,e,t){const{config:r,name:i}=n;if("url"in r)return new L({url:r.url,headers:q(r.headers,`MCP server "${i}"`),authProvider:t});const o={};for(const[c,a]of Object.entries(r.env??{}))o[c]=g(a,`MCP server "${i}" env "${c}"`);return new h({command:u(r.command),args:r.args?.map(u),cwd:O(e,u(r.cwd??".")),env:o,stderr:"pipe"})}s(ee,"createDefaultTransport");async function v(n,e){try{return await n()}catch(t){if(t instanceof U&&t.code===_.methodNotFound)return e;throw t}}s(v,"withoutTemplates");function R(n,e={}){return v(()=>n.listResourceTemplates(e),[])}s(R,"listTemplates");async function S(n){const[e,t]=await Promise.all([n.listResources().catch(()=>[]),R(n).catch(()=>[])]);return{resources:e.filter(r=>!p(r)),resourceTemplates:t.filter(r=>!p(r))}}s(S,"fetchResources");class te{static{s(this,"McpServerConnection")}entry;state="connecting";error;tools=[];hasResources=!1;resources=[];resourceTemplates=[];instructions;challenge;client;opening;shutdown=new AbortController;stderrTail;cwd;createTransport;authProvider;onTools;onChange;log;constructor(e){this.entry=e.entry,this.cwd=e.cwd,this.createTransport=e.createTransport,this.onTools=e.onTools,this.onChange=e.onChange,this.log=e.log;const t=this.oauthUrl,r="url"in this.entry.config?this.entry.config.auth?.provider:void 0;this.authProvider=t?D({serverUrl:t,store:e.credentials.forServer(this.entry.name,t),settings:s(()=>this.oauthSettings(),"settings"),onChallenge:s(i=>{this.challenge=i},"onChallenge")}):r?{token:s(async()=>e.providerToken?.(r),"token"),settled:s(async()=>{},"settled")}:void 0}get name(){return this.entry.name}get closed(){return this.shutdown.signal.aborted}get timeoutMs(){return(this.entry.config.timeout??H)*1e3}get oauthUrl(){return j(this.entry)&&"url"in this.entry.config?this.entry.config.url:void 0}oauthSettings(){const e="url"in this.entry.config?this.entry.config.oauth:void 0;return e?{clientId:e.clientId,clientSecret:e.clientSecret===void 0?void 0:g(e.clientSecret,`MCP server "${this.entry.name}" oauth.clientSecret`),callbackPort:e.callbackPort,callbackUrl:e.callbackUrl,scope:e.scope,clientName:e.clientName,clientRegistration:e.clientRegistration,authServerMetadataUrl:e.authServerMetadataUrl?new URL(e.authServerMetadataUrl):void 0}:{}}getClient(){return this.closed?Promise.reject(new Error(`MCP server "${this.entry.name}" is shut down`)):this.client?.connectionState==="connected"?Promise.resolve(this.client):(this.opening??=this.open().finally(()=>{this.opening=void 0}),this.opening)}callTool(e,t,r){return this.withClient(i=>i.callTool(e,t,r))}readResource(e,t){return this.withClient(r=>r.readResource(e,t),!0)}resourcesPage(e,t){return this.withClient(r=>r.listResourcesPage(e,t),!0)}resourceTemplatesPage(e,t){return this.withClient(r=>v(()=>r.listResourceTemplatesPage(e,t),{resourceTemplates:[]}),!0)}allResources(e){return this.withClient(t=>t.listResources(e),!0)}allResourceTemplates(e){return this.withClient(t=>R(t,e),!0)}async withClient(e,t=!1){for(let r=1;;r++){const i=await this.getClient();try{return await e(i)}catch(o){if(t&&r===1&&o instanceof m&&C(o)){await new Promise(c=>setTimeout(c,T[0]));continue}if(o instanceof I&&r===1){this.client===i&&(this.client=void 0);continue}throw this.needsSignIn(o)?(await this.dropClient(i),this.markNeedsAuth(),new Error(y(this.entry))):o}}}async reconnect(){await this.opening?.catch(()=>{}),this.client&&await this.dropClient(this.client),await this.getClient()}async signOut(){await this.opening?.catch(()=>{}),this.client&&await this.dropClient(this.client),this.closed||this.markNeedsAuth()}needsSignIn(e){return e instanceof x||this.authProvider!==void 0&&e instanceof $}markNeedsAuth(){this.state="needs-auth",this.error=void 0,this.changed()}changed(){this.onChange?.(this)}async dropClient(e){this.client===e&&(this.client=void 0),await e.close().catch(()=>{})}async open(){this.state="connecting",this.changed();const e="url"in this.entry.config?T:[];for(let t=0;;t++){this.stderrTail=void 0;try{return await this.connectOnce()}catch(r){const i=e[t];if(this.closed||i===void 0||!C(r))throw this.connectFailed(r);if(await b(i,void 0,{signal:this.shutdown.signal}).catch(()=>{}),this.closed)throw this.connectFailed(r)}}}async connectOnce(){const e=new k({name:"pi",version:F,requestTimeoutMs:this.timeoutMs,roots:[{uri:N(this.cwd).href,name:P(this.cwd)}]}),t=this.log;t&&e.onNotification("notifications/message",c=>t.write(this.entry.name,c));let r;const i=s(()=>(r??=e.close().catch(()=>{}),r),"closeClient");this.shutdown.signal.addEventListener("abort",i,{once:!0});let o;try{o=this.createTransport(this.entry,this.cwd,this.authProvider),await e.connect(o),e.onNotification("notifications/tools/list_changed",()=>{this.refreshTools(e)}),e.onNotification("notifications/resources/list_changed",()=>{this.refreshResources(e)});const c=o instanceof h?o:void 0;e.onClose(()=>this.handleClientClose(e,c));const a=e.serverCapabilities?.resources!==void 0,[M,d]=await Promise.all([e.serverCapabilities?.tools?e.listTools():[],a?S(e):{resources:[],resourceTemplates:[]}]);if(this.closed)throw new Error("shut down while connecting");if(e.connectionState!=="connected")throw new Error("connection closed during setup");return this.client=e,this.tools=M,this.hasResources=a,this.resources=d.resources,this.resourceTemplates=d.resourceTemplates,this.instructions=e.instructions?.trim()||void 0,this.state="connected",this.error=void 0,this.onTools(this),this.changed(),e}catch(c){throw await i(),o instanceof h&&(this.stderrTail=o.stderr.trim().slice(-w)||void 0),c}finally{this.shutdown.signal.removeEventListener("abort",i)}}connectFailed(e){return this.needsSignIn(e)&&!this.closed?(this.markNeedsAuth(),new Error(y(this.entry))):(this.state=this.closed?"closed":"failed",this.error=this.stderrTail?`${l(e)}
2
- ${this.stderrTail}`:l(e),this.changed(),new Error(`MCP server "${this.entry.name}" failed to connect: ${this.error}`))}handleClientClose(e,t){if(this.client!==e||this.closed)return;this.client=void 0,this.state="disconnected";const r=t?.stderr.trim().slice(-w);this.error=r?`Connection closed
3
- ${r}`:"Connection closed",this.changed()}async refreshTools(e){try{const t=await e.listTools();if(this.client!==e||this.closed)return;this.tools=t,this.onTools(this)}catch(t){this.error=`Failed to refresh tools: ${l(t)}`}this.changed()}async refreshResources(e){const{resources:t,resourceTemplates:r}=await S(e);this.client!==e||this.closed||(this.resources=t,this.resourceTemplates=r,this.onTools(this),this.changed())}async close(){this.shutdown.abort(),this.state="closed",this.changed();const e=this.client;this.client=void 0,await Promise.all([e?.close().catch(()=>{}),this.opening?.catch(()=>{})]),await this.authProvider?.settled()}}export{ie as McpOAuthAuthorizationRequiredError,he as McpOAuthCredentialStore,te as McpServerConnection,oe as McpServerLog,le as McpSignInCancelledError,ee as createDefaultTransport,ae as createMcpAuthProvider,ue as signInMcpServer};
1
+ var y=Object.defineProperty;var o=(i,t)=>y(i,"name",{value:t,configurable:!0});import{homedir as u}from"node:os";import{basename as v,join as S,resolve as M}from"node:path";import{setTimeout as E}from"node:timers/promises";import{pathToFileURL as R}from"node:url";import{JSON_RPC_ERROR_CODES as P,McpAuthRequiredError as A,McpClient as O,McpError as b,McpHttpError as f,McpSessionExpiredError as N,StdioTransport as h,StreamableHttpTransport as $}from"@earendil-works/pi-mcp";import{McpOAuthAuthorizationRequiredError as _}from"@earendil-works/pi-mcp/oauth";import{VERSION as k}from"../../config.js";import{resolveConfigValueOrThrow as g,resolveHeadersOrThrow as U}from"../../core/resolve-config-value.js";import{createMcpAuthProvider as I}from"./oauth.js";import{McpOAuthAuthorizationRequiredError as Z}from"@earendil-works/pi-mcp/oauth";import{McpServerLog as et}from"./log.js";import{createMcpAuthProvider as it,McpOAuthCredentialStore as rt,McpSignInCancelledError as st,signInMcpServer as ot}from"./oauth.js";const L=60,m=2e3,p=[250,1e3];function l(i){return i instanceof Error?i.message:String(i)}o(l,"errorMessage");function w(i){return i instanceof f?i.status===408||i.status===429||i.status>=500&&i.status!==501:i instanceof TypeError}o(w,"isTransientError");function C(i){const t="url"in i.config?i.config.auth?.provider:void 0;return`MCP server "${i.name}" requires sign-in. Run ${t?`/login ${t}`:"/mcp"} to sign in.`}o(C,"signInRequiredMessage");function x(i){const{config:t}=i;return!("url"in t)||t.auth?!1:!Object.keys(t.headers??{}).some(e=>e.toLowerCase()==="authorization")}o(x,"usesOAuth");function d(i){return i==="~"?u():i.startsWith("~/")||process.platform==="win32"&&i.startsWith("~\\")?S(u(),i.slice(2)):i}o(d,"expandHome");function G(i,t,e){const{config:n,name:r}=i;if("url"in n)return new $({url:n.url,headers:U(n.headers,`MCP server "${r}"`),authProvider:e});const s={};for(const[c,a]of Object.entries(n.env??{}))s[c]=g(a,`MCP server "${r}" env "${c}"`);return new h({command:d(n.command),args:n.args?.map(d),cwd:M(t,d(n.cwd??".")),env:s,stderr:"pipe"})}o(G,"createDefaultTransport");async function T(i,t){try{return await i()}catch(e){if(e instanceof b&&e.code===P.methodNotFound)return t;throw e}}o(T,"withoutTemplates");function F(i,t={}){return T(()=>i.listResourceTemplates(t),[])}o(F,"listTemplates");class K{static{o(this,"McpServerConnection")}entry;state="connecting";error;tools=[];hasResources=!1;instructions;challenge;client;opening;shutdown=new AbortController;stderrTail;cwd;createTransport;authProvider;onTools;onChange;log;constructor(t){this.entry=t.entry,this.cwd=t.cwd,this.createTransport=t.createTransport,this.onTools=t.onTools,this.onChange=t.onChange,this.log=t.log;const e=this.oauthUrl,n="url"in this.entry.config?this.entry.config.auth?.provider:void 0;this.authProvider=e?I({serverUrl:e,store:t.credentials.forServer(this.entry.name,e),settings:o(()=>this.oauthSettings(),"settings"),onChallenge:o(r=>{this.challenge=r},"onChallenge")}):n?{token:o(async()=>t.providerToken?.(n),"token"),settled:o(async()=>{},"settled")}:void 0}get name(){return this.entry.name}get closed(){return this.shutdown.signal.aborted}get timeoutMs(){return(this.entry.config.timeout??L)*1e3}get oauthUrl(){return x(this.entry)&&"url"in this.entry.config?this.entry.config.url:void 0}oauthSettings(){const t="url"in this.entry.config?this.entry.config.oauth:void 0;return t?{clientId:t.clientId,clientSecret:t.clientSecret===void 0?void 0:g(t.clientSecret,`MCP server "${this.entry.name}" oauth.clientSecret`),callbackPort:t.callbackPort,callbackUrl:t.callbackUrl,scope:t.scope,clientName:t.clientName,clientRegistration:t.clientRegistration,authServerMetadataUrl:t.authServerMetadataUrl?new URL(t.authServerMetadataUrl):void 0}:{}}getClient(){return this.closed?Promise.reject(new Error(`MCP server "${this.entry.name}" is shut down`)):this.client?.connectionState==="connected"?Promise.resolve(this.client):(this.opening??=this.open().finally(()=>{this.opening=void 0}),this.opening)}callTool(t,e,n){return this.withClient(r=>r.callTool(t,e,n))}readResource(t,e){return this.withClient(n=>n.readResource(t,e),!0)}resourcesPage(t,e){return this.withClient(n=>n.listResourcesPage(t,e),!0)}resourceTemplatesPage(t,e){return this.withClient(n=>T(()=>n.listResourceTemplatesPage(t,e),{resourceTemplates:[]}),!0)}allResources(t){return this.withClient(e=>e.listResources(t),!0)}allResourceTemplates(t){return this.withClient(e=>F(e,t),!0)}async withClient(t,e=!1){for(let n=1;;n++){const r=await this.getClient();try{return await t(r)}catch(s){if(e&&n===1&&s instanceof f&&w(s)){await new Promise(c=>setTimeout(c,p[0]));continue}if(s instanceof N&&n===1){this.client===r&&(this.client=void 0);continue}throw this.needsSignIn(s)?(await this.dropClient(r),this.markNeedsAuth(),new Error(C(this.entry))):s}}}async reconnect(){await this.opening?.catch(()=>{}),this.client&&await this.dropClient(this.client),await this.getClient()}async signOut(){await this.opening?.catch(()=>{}),this.client&&await this.dropClient(this.client),this.closed||this.markNeedsAuth()}needsSignIn(t){return t instanceof _||this.authProvider!==void 0&&t instanceof A}markNeedsAuth(){this.state="needs-auth",this.error=void 0,this.changed()}changed(){this.onChange?.(this)}async dropClient(t){this.client===t&&(this.client=void 0),await t.close().catch(()=>{})}async open(){this.state="connecting",this.changed();const t="url"in this.entry.config?p:[];for(let e=0;;e++){this.stderrTail=void 0;try{return await this.connectOnce()}catch(n){const r=t[e];if(this.closed||r===void 0||!w(n))throw this.connectFailed(n);if(await E(r,void 0,{signal:this.shutdown.signal}).catch(()=>{}),this.closed)throw this.connectFailed(n)}}}async connectOnce(){const t=new O({name:"pi",version:k,requestTimeoutMs:this.timeoutMs,roots:[{uri:R(this.cwd).href,name:v(this.cwd)}]}),e=this.log;e&&t.onNotification("notifications/message",c=>e.write(this.entry.name,c));let n;const r=o(()=>(n??=t.close().catch(()=>{}),n),"closeClient");this.shutdown.signal.addEventListener("abort",r,{once:!0});let s;try{s=this.createTransport(this.entry,this.cwd,this.authProvider),await t.connect(s),t.onNotification("notifications/tools/list_changed",()=>{this.refreshTools(t)});const c=s instanceof h?s:void 0;t.onClose(()=>this.handleClientClose(t,c));const a=t.serverCapabilities?.tools?await t.listTools():[];if(this.closed)throw new Error("shut down while connecting");if(t.connectionState!=="connected")throw new Error("connection closed during setup");return this.client=t,this.tools=a,this.hasResources=t.serverCapabilities?.resources!==void 0,this.instructions=t.instructions?.trim()||void 0,this.state="connected",this.error=void 0,this.onTools(this),this.changed(),t}catch(c){throw await r(),s instanceof h&&(this.stderrTail=s.stderr.trim().slice(-m)||void 0),c}finally{this.shutdown.signal.removeEventListener("abort",r)}}connectFailed(t){return this.needsSignIn(t)&&!this.closed?(this.markNeedsAuth(),new Error(C(this.entry))):(this.state=this.closed?"closed":"failed",this.error=this.stderrTail?`${l(t)}
2
+ ${this.stderrTail}`:l(t),this.changed(),new Error(`MCP server "${this.entry.name}" failed to connect: ${this.error}`))}handleClientClose(t,e){if(this.client!==t||this.closed)return;this.client=void 0,this.state="disconnected";const n=e?.stderr.trim().slice(-m);this.error=n?`Connection closed
3
+ ${n}`:"Connection closed",this.changed()}async refreshTools(t){try{const e=await t.listTools();if(this.client!==t||this.closed)return;this.tools=e,this.onTools(this)}catch(e){this.error=`Failed to refresh tools: ${l(e)}`}this.changed()}async close(){this.shutdown.abort(),this.state="closed",this.changed();const t=this.client;this.client=void 0,await Promise.all([t?.close().catch(()=>{}),this.opening?.catch(()=>{})]),await this.authProvider?.settled()}}export{Z as McpOAuthAuthorizationRequiredError,rt as McpOAuthCredentialStore,K as McpServerConnection,et as McpServerLog,st as McpSignInCancelledError,G as createDefaultTransport,it as createMcpAuthProvider,ot as signInMcpServer};
@@ -1,9 +1,9 @@
1
- var w=Object.defineProperty;var s=(e,t)=>w(e,"name",{value:t,configurable:!0});import{createHash as O}from"node:crypto";import{toLlmContent as f}from"@earendil-works/pi-mcp";import{Container as M,Spacer as E,Text as d}from"@earendil-works/pi-tui";import{READ_MCP_RESOURCE_TOOL as x}from"../../core/mcp-servers.js";import{formatToolCallWithArgs as P,getTextOutput as R,replaceTabs as S}from"../../core/tools/render-utils.js";import{formatSize as $,truncateMiddle as v}from"../../core/tools/truncate.js";import{keyHint as L}from"../../modes/interactive/components/keybinding-hints.js";import{VisualLinePreview as j}from"../../modes/interactive/components/visual-truncate.js";import{writeOutputFile as A}from"../../utils/output-files.js";function H(e){return e==="codemode"?"deferred":e}s(H,"toToolExposure");const y=64,b=20*1024,N=5;function h(e,t){return A("pi-mcp",t,e)}s(h,"saveToTempFile");function rt(e,t,n=()=>!1){const o=`mcp__${e}__${t}`.replace(/[^A-Za-z0-9_]/g,"_");if(o.length<=y&&!n(o))return o;const r=O("sha256").update(`${e}\0${t}`).digest("hex").slice(0,8);return`${o.slice(0,y-r.length-1)}_${r}`}s(rt,"createMcpToolName");function T(e){return e.filter(t=>t.type==="text").map(t=>t.text).join(`
2
- `)}s(T,"textOf");function W(e){return{type:"object",properties:{content:{type:"array",items:{type:"object"}},...e?{structuredContent:e}:{},isError:{type:"boolean"},_meta:{type:"object"}},required:["content"]}}s(W,"createMcpResultSchema");async function U(e,t=h){const n=T(e),o=v(n,b);if(!o.truncated)return{content:e};let r,a;try{r=await t(n,".txt"),a=`[Full output: ${r} (read it with offset/limit)]`}catch(i){a=`[Could not save the full output: ${i instanceof Error?i.message:String(i)}]`}return{content:[{type:"text",text:`Warning: truncated output (original token count: ${Math.ceil(o.totalBytes/4)})
3
- Total output lines: ${o.totalLines}
1
+ var w=Object.defineProperty;var a=(e,t)=>w(e,"name",{value:t,configurable:!0});import{createHash as E}from"node:crypto";import{toLlmContent as y}from"@earendil-works/pi-mcp";import{Container as M,Spacer as P,Text as f}from"@earendil-works/pi-tui";import{READ_MCP_RESOURCE_TOOL as x}from"../../core/mcp-servers.js";import{formatToolCallWithArgs as S,getTextOutput as A,replaceTabs as R}from"../../core/tools/render-utils.js";import{formatSize as $,truncateMiddle as j}from"../../core/tools/truncate.js";import{keyHint as b}from"../../modes/interactive/components/keybinding-hints.js";import{VisualLinePreview as v}from"../../modes/interactive/components/visual-truncate.js";import{writeOutputFile as H}from"../../utils/output-files.js";function L(e){return e==="codemode"?"deferred":e}a(L,"toToolExposure");const h=64,W=20*1024,N=5;function T(e,t){return H("pi-mcp",t,e)}a(T,"saveToTempFile");function ut(e,t,r=()=>!1){const n=`mcp__${e}__${t}`.replace(/[^A-Za-z0-9_]/g,"_");if(n.length<=h&&!r(n))return n;const o=E("sha256").update(`${e}\0${t}`).digest("hex").slice(0,8);return`${n.slice(0,h-o.length-1)}_${o}`}a(ut,"createMcpToolName");function g(e){return e.filter(t=>t.type==="text").map(t=>t.text).join(`
2
+ `)}a(g,"textOf");const B={type:"object",properties:{type:{enum:["text","image","audio","resource_link","resource"]},text:{type:"string"},data:{type:"string"},mimeType:{type:"string"}},required:["type"],additionalProperties:!0},U=new Set(["const","enum","default","examples"]),I=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function d(e,t){if(Array.isArray(e))return e.map(n=>d(n,t));if(typeof e!="object"||e===null)return e;const r={};for(const[n,o]of Object.entries(e))n==="$ref"&&typeof o=="string"&&(o==="#"||o.startsWith("#/"))?r[n]=`${t}${o.slice(1)}`:U.has(n)?r[n]=o:I.has(n)&&typeof o=="object"&&o!==null&&!Array.isArray(o)?r[n]=Object.fromEntries(Object.entries(o).map(([i,u])=>[i,d(u,t)])):r[n]=d(o,t);return r}a(d,"relocateSchema");function z(e){return{type:"object",properties:{content:{type:"array",items:B},structuredContent:e?d(e,"#/properties/structuredContent"):{},isError:{type:"boolean"}},required:["content"],additionalProperties:!0}}a(z,"createMcpResultSchema");async function D(e,t=T){const r=g(e),n=j(r,W);if(!n.truncated)return{content:e};let o,i;try{o=await t(r,".txt"),i=`[Full output: ${o} (read it with offset/limit)]`}catch(s){i=`[Could not save the full output: ${s instanceof Error?s.message:String(s)}]`}return{content:[{type:"text",text:`Warning: truncated output (original token count: ${Math.ceil(n.totalBytes/4)})
3
+ Total output lines: ${n.totalLines}
4
4
 
5
- ${o.content}
5
+ ${n.content}
6
6
 
7
- ${a}`},...e.filter(i=>i.type==="image")],...r?{fullOutputPath:r}:{}}}s(U,"limitMcpContent");function B(e){const t=URL.canParse(e)?new URL(e).pathname:e;return/\.[A-Za-z0-9]{1,8}$/.exec(t)?.[0]??".bin"}s(B,"extensionOf");function I(e){if(!e)return!1;const t=e.split(";",1)[0].trim().toLowerCase();return t.startsWith("text/")||t==="application/json"||t.endsWith("+json")||t.endsWith("+xml")}s(I,"isTextMimeType");async function z(e,t,n){if(t.type==="resource_link"){const o=[t.mimeType,t.size===void 0?void 0:$(t.size)].filter(Boolean),r=n.readableResources?`. Read it with ${x} (server "${e}")`:"",a=t.description?`: ${t.description}`:"";return[{type:"text",text:`[Resource ${t.uri} "${t.title??t.name}"${o.length>0?` (${o.join(", ")})`:""}${a}${r}]`}]}if(t.type==="resource"&&"blob"in t.resource&&!t.resource.mimeType?.startsWith("image/")){const{uri:o,mimeType:r,blob:a}=t.resource,u=Buffer.from(a,"base64");if(I(r))return[{type:"text",text:u.toString("utf8")}];const c=`${r??"unknown type"}, ${$(u.length)}`;try{const i=await(n.saveOutput??h)(u,B(o));return[{type:"text",text:`[Binary resource ${o} (${c}) saved to ${i}]`}]}catch(i){const p=i instanceof Error?i.message:String(i);return[{type:"text",text:`[Binary resource ${o} (${c}) could not be saved: ${p}]`}]}}return f({content:[t]})}s(z,"blockToContent");async function F(e,t,n={}){return(await Promise.all(t.map(o=>z(e,o,n)))).flat()}s(F,"toModelContent");async function V(e,t,n,o={}){const r=n.content.length>0?await F(e,n.content,o):f(n);n.isError&&T(r)===""&&r.push({type:"text",text:`MCP tool ${e}/${t} returned an error`});const{content:a,fullOutputPath:u}=await U(r,o.saveOutput),{_meta:c,...i}=n;return{content:a,details:{server:e,tool:t,...u?{fullOutputPath:u}:{}},structuredContent:i,...n.isError?{isError:!0}:{}}}s(V,"convertMcpResult");function D(e){return{...e,type:e.type??"object",...e.properties===void 0?{properties:{}}:{}}}s(D,"toParameters");const X=["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"];function Z(e){const t={};for(const n of X){const o=e.annotations?.[n];typeof o=="boolean"&&(t[n]=o)}return Object.keys(t).length>0?t:void 0}s(Z,"toToolAnnotations");function at(e){const{server:t,tool:n}=e,o=n.title??n.annotations?.title,r=Z(n),a=`${t}/${n.name}`;return{name:e.name,label:a,description:n.description?.trim()||o||`MCP tool ${n.name} from server ${t}`,parameters:D(n.inputSchema),outputSchema:W(n.outputSchema),exposure:H(e.exposure),namespace:e.namespace,...r?{annotations:r}:{},...q(a),async execute(u,c,i,p){const g=await(await e.getClient()).callTool(n.name,c??{},{signal:i,timeoutMs:e.timeoutMs,onProgress:s(l=>{const _=l.total===void 0?"":`/${l.total}`,C=l.message??`Progress ${l.progress}${_}`;p?.({content:[{type:"text",text:C}],details:{server:t,tool:n.name}})},"onProgress")});return V(t,n.name,g,{readableResources:e.readableResources?.()})}}}s(at,"createMcpToolDefinition");function q(e){return{renderCall(t,n,o){const r=o.lastComponent??new d("",0,0);return r.setText(P(e,t,n,o.expanded)),r},renderResult(t,n,o,r){const a=r.lastComponent??new M;a.clear();const u=R(t,r.showImages).trim();if(!u)return a;const c=r.isError?"error":"toolOutput",i=S(u).split(`
8
- `).map(p=>o.fg(c,p)).join(`
9
- `);if(a.addChild(new E(1)),n.expanded)a.addChild(new d(i,0,0));else{a.addChild(new j({text:i,maxVisualLines:N,keep:"start",formatHint:s(m=>`${o.fg("muted",`... (${m} more lines,`)} ${L("app.tools.expand","to expand")}${o.fg("muted",")")}`,"formatHint")}));const p=t.details?.fullOutputPath;p&&a.addChild(new d(o.fg("muted",`Full output: ${p}`),0,0))}return a}}}s(q,"createMcpToolRenderers");export{b as MCP_OUTPUT_MAX_BYTES,x as READ_MCP_RESOURCE_TOOL,V as convertMcpResult,W as createMcpResultSchema,at as createMcpToolDefinition,rt as createMcpToolName,q as createMcpToolRenderers,U as limitMcpContent,h as saveToTempFile,F as toModelContent,H as toToolExposure};
7
+ ${i}`},...e.filter(s=>s.type==="image")],...o?{fullOutputPath:o}:{}}}a(D,"limitMcpContent");function F(e){const t=URL.canParse(e)?new URL(e).pathname:e;return/\.[A-Za-z0-9]{1,8}$/.exec(t)?.[0]??".bin"}a(F,"extensionOf");function K(e){if(!e)return!1;const t=e.split(";",1)[0].trim().toLowerCase();return t.startsWith("text/")||t==="application/json"||t.endsWith("+json")||t.endsWith("+xml")}a(K,"isTextMimeType");async function V(e,t,r){if(t.type==="resource_link"){const n=[t.mimeType,t.size===void 0?void 0:$(t.size)].filter(Boolean),o=r.readableResources?`. Read it with ${x} (server "${e}")`:"",i=t.description?`: ${t.description}`:"";return[{type:"text",text:`[Resource ${t.uri} "${t.title??t.name}"${n.length>0?` (${n.join(", ")})`:""}${i}${o}]`}]}if(t.type==="resource"&&"blob"in t.resource&&!t.resource.mimeType?.startsWith("image/")){const{uri:n,mimeType:o,blob:i}=t.resource,u=Buffer.from(i,"base64");if(K(o))return[{type:"text",text:u.toString("utf8")}];const c=`${o??"unknown type"}, ${$(u.length)}`;try{const s=await(r.saveOutput??T)(u,F(n));return[{type:"text",text:`[Binary resource ${n} (${c}) saved to ${s}]`}]}catch(s){const p=s instanceof Error?s.message:String(s);return[{type:"text",text:`[Binary resource ${n} (${c}) could not be saved: ${p}]`}]}}return y({content:[t]})}a(V,"blockToContent");async function Y(e,t,r={}){return(await Promise.all(t.map(n=>V(e,n,r)))).flat()}a(Y,"toModelContent");async function q(e,t,r,n={}){const o=r.content.length>0?await Y(e,r.content,n):y(r);r.isError&&g(o)===""&&o.push({type:"text",text:`MCP tool ${e}/${t} returned an error`});const{content:i,fullOutputPath:u}=await D(o,n.saveOutput),{_meta:c,...s}=r;return{content:i,details:{server:e,tool:t,...u?{fullOutputPath:u}:{}},structuredContent:s,...r.isError?{isError:!0}:{}}}a(q,"convertMcpResult");function X(e){return{...e,type:e.type??"object",...e.properties===void 0?{properties:{}}:{}}}a(X,"toParameters");const Z=["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"];function G(e){const t={};for(const r of Z){const n=e.annotations?.[r];typeof n=="boolean"&&(t[r]=n)}return Object.keys(t).length>0?t:void 0}a(G,"toToolAnnotations");function ct(e){const{server:t,tool:r}=e,n=r.title??r.annotations?.title,o=G(r),i=`${t}/${r.name}`;return{name:e.name,label:i,description:r.description?.trim()||n||`MCP tool ${r.name} from server ${t}`,parameters:X(r.inputSchema),outputSchema:z(r.outputSchema),exposure:L(e.exposure),namespace:e.namespace,...o?{annotations:o}:{},...J(i),async execute(u,c,s,p){const _=await(await e.getClient()).callTool(r.name,c??{},{signal:s,timeoutMs:e.timeoutMs,onProgress:a(l=>{const C=l.total===void 0?"":`/${l.total}`,O=l.message??`Progress ${l.progress}${C}`;p?.({content:[{type:"text",text:O}],details:{server:t,tool:r.name}})},"onProgress")});return q(t,r.name,_,{readableResources:e.readableResources?.()})}}}a(ct,"createMcpToolDefinition");function J(e){return{renderCall(t,r,n){const o=n.lastComponent??new f("",0,0);return o.setText(S(e,t,r,n.expanded)),o},renderResult(t,r,n,o){const i=o.lastComponent??new M;i.clear();const u=A(t,o.showImages).trim();if(!u)return i;const c=o.isError?"error":"toolOutput",s=R(u).split(`
8
+ `).map(p=>n.fg(c,p)).join(`
9
+ `);if(i.addChild(new P(1)),r.expanded)i.addChild(new f(s,0,0));else{i.addChild(new v({text:s,maxVisualLines:N,keep:"start",formatHint:a(m=>`${n.fg("muted",`... (${m} more lines,`)} ${b("app.tools.expand","to expand")}${n.fg("muted",")")}`,"formatHint")}));const p=t.details?.fullOutputPath;p&&i.addChild(new f(n.fg("muted",`Full output: ${p}`),0,0))}return i}}}a(J,"createMcpToolRenderers");export{W as MCP_OUTPUT_MAX_BYTES,x as READ_MCP_RESOURCE_TOOL,q as convertMcpResult,z as createMcpResultSchema,ct as createMcpToolDefinition,ut as createMcpToolName,J as createMcpToolRenderers,D as limitMcpContent,T as saveToTempFile,Y as toModelContent,L as toToolExposure};
@@ -1,7 +1,7 @@
1
- var $=Object.defineProperty;var l=(e,t)=>$(e,"name",{value:t,configurable:!0});import{Type as p}from"typebox";const u="tool_search",T=8,v=new Set(["a","an","and","are","as","at","be","by","for","from","in","is","it","of","on","or","that","the","this","to","with"]);function w(e){return e.length>4&&e.endsWith("ies")?`${e.slice(0,-3)}y`:e.length>4&&/(ches|shes|sses|xes|zes)$/.test(e)?e.slice(0,-2):e.length>3&&e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e}l(w,"stem");function b(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>0&&!v.has(t)).map(w)}l(b,"tokenize");function S(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}l(S,"isObject");function d(e,t){if(S(e)){if(typeof e.description=="string"&&t.push(e.description),S(e.properties))for(const[o,s]of Object.entries(e.properties))t.push(o),d(s,t);d(e.items,t);for(const o of["anyOf","oneOf","allOf"]){const s=e[o];if(Array.isArray(s))for(const i of s)d(i,t)}}}l(d,"schemaText");function _(e,t){const o=[e.name,e.name.replaceAll("_"," "),e.description];return d(e.parameters,o),t&&o.push(t.name,t.description??"",t.instructions??""),{name:e.name,text:o.filter(s=>s.trim()).join(" ")}}l(_,"createToolSearchDocument");class k{static{l(this,"Bm25Ranker")}k1;b;constructor(t={}){this.k1=t.k1??1.2,this.b=t.b??.75}rank(t,o,s){const i=[...new Set(b(t))];if(i.length===0||o.length===0||s<=0)return[];const c=o.map(a=>{const r=new Map;for(const f of b(a.text))r.set(f,(r.get(f)??0)+1);return r}),h=c.map(a=>[...a.values()].reduce((r,f)=>r+f,0)),n=h.reduce((a,r)=>a+r,0)/o.length||1,m=new Map(i.map(a=>{const r=c.filter(f=>f.has(a)).length;return[a,Math.log(1+(o.length-r+.5)/(r+.5))]})),y=[];return o.forEach((a,r)=>{let f=0;for(const x of i){const g=c[r].get(x);if(!g)continue;const A=this.k1*(1-this.b+this.b*h[r]/n);f+=(m.get(x)??0)*(g*(this.k1+1)/(g+A))}f>0&&y.push({name:a.name,score:f})}),y.sort((a,r)=>r.score-a.score).slice(0,s)}}const O=p.Object({query:p.String({description:"Search query for deferred tools."}),limit:p.Optional(p.Number({description:`Maximum number of tools to return. Defaults to ${T}.`}))});function D(e){return e.name===u&&e.parameters===O}l(D,"isToolSearchTool");function L(e){return e==="codemode"||e==="deferred"}l(L,"isSearchable");function C(e,t,o){const s=e.getActiveTools(),i=e.getAllTools().filter(n=>L(n.exposure)&&!s.includes(n.name)),c=i.map(n=>_(n,n.namespace)),h=new k().rank(t,c,o);return h.length>0&&e.setActiveTools([...s,...h.map(n=>n.name)]),h.map(n=>({name:n.name,description:i.find(m=>m.name===n.name)?.description??""}))}l(C,"searchAndLoad");const E=`# Tool discovery
1
+ var A=Object.defineProperty;var l=(e,t)=>A(e,"name",{value:t,configurable:!0});import{Type as u}from"typebox";const p="tool_search",b=8,$=new Set(["a","an","and","are","as","at","be","by","for","from","in","is","it","of","on","or","that","the","this","to","with"]);function v(e){return e.length>4&&e.endsWith("ies")?`${e.slice(0,-3)}y`:e.length>4&&/(ches|shes|sses|xes|zes)$/.test(e)?e.slice(0,-2):e.length>3&&e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e}l(v,"stem");function T(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>0&&!$.has(t)).map(v)}l(T,"tokenize");function S(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}l(S,"isObject");function d(e,t){if(S(e)){if(typeof e.description=="string"&&t.push(e.description),S(e.properties))for(const[o,s]of Object.entries(e.properties))t.push(o),d(s,t);d(e.items,t);for(const o of["anyOf","oneOf","allOf"]){const s=e[o];if(Array.isArray(s))for(const i of s)d(i,t)}}}l(d,"schemaText");function w(e,t){const o=[e.name,e.name.replaceAll("_"," "),e.description];return d(e.parameters,o),t&&o.push(t.name,t.description??"",t.instructions??""),{name:e.name,text:o.filter(s=>s.trim()).join(" ")}}l(w,"createToolSearchDocument");class _{static{l(this,"Bm25Ranker")}k1;b;constructor(t={}){this.k1=t.k1??1.2,this.b=t.b??.75}rank(t,o,s){const i=[...new Set(T(t))];if(i.length===0||o.length===0||s<=0)return[];const c=o.map(a=>{const r=new Map;for(const f of T(a.text))r.set(f,(r.get(f)??0)+1);return r}),h=c.map(a=>[...a.values()].reduce((r,f)=>r+f,0)),n=h.reduce((a,r)=>a+r,0)/o.length||1,m=new Map(i.map(a=>{const r=c.filter(f=>f.has(a)).length;return[a,Math.log(1+(o.length-r+.5)/(r+.5))]})),y=[];return o.forEach((a,r)=>{let f=0;for(const x of i){const g=c[r].get(x);if(!g)continue;const O=this.k1*(1-this.b+this.b*h[r]/n);f+=(m.get(x)??0)*(g*(this.k1+1)/(g+O))}f>0&&y.push({name:a.name,score:f})}),y.sort((a,r)=>r.score-a.score).slice(0,s)}}const k=u.Object({query:u.String({description:"Search query for deferred tools."}),limit:u.Optional(u.Number({description:`Maximum number of tools to return. Defaults to ${b}.`}))});function L(e){return e==="codemode"||e==="deferred"}l(L,"isSearchable");function C(e,t,o){const s=e.getActiveTools(),i=e.getAllTools().filter(n=>L(n.exposure)&&!s.includes(n.name)),c=i.map(n=>w(n,n.namespace)),h=new _().rank(t,c,o);return h.length>0&&e.setActiveTools([...s,...h.map(n=>n.name)]),h.map(n=>({name:n.name,description:i.find(m=>m.name===n.name)?.description??""}))}l(C,"searchAndLoad");const E=`# Tool discovery
2
2
 
3
3
  Searches over deferred tool metadata with BM25 and exposes matching tools for the next model call.
4
4
 
5
- Some of the tools, such as tools of MCP servers, may not have been provided to you upfront, and you should use this tool (\`${u}\`) to search for the required tools. For MCP tool discovery, always use \`${u}\`.`;function I(e={}){return{name:u,label:u,description:E,promptSnippet:"Search for tools that are not loaded yet and load the matches",parameters:O,exposure:"model-only",async execute(t,{query:o,limit:s}){if(o.trim()==="")throw new Error("query must not be empty");const i=s??T;if(!Number.isInteger(i)||i<=0)throw new Error("limit must be a positive integer");const c=e.tools?C(e.tools,o,i):[];return{content:[{type:"text",text:c.length===0?"No matching tools found.":`Loaded ${c.length} tool${c.length===1?"":"s"}. They are available from your next call:
5
+ Some of the tools, such as tools of MCP servers, may not have been provided to you upfront, and you should use this tool (\`${p}\`) to search for the required tools. For MCP tool discovery, always use \`${p}\`.`;function D(e={}){return{name:p,label:p,description:E,promptSnippet:"Search for tools that are not loaded yet and load the matches",parameters:k,exposure:"model-only",reachesTools:l(()=>"all","reachesTools"),async execute(t,{query:o,limit:s}){if(o.trim()==="")throw new Error("query must not be empty");const i=s??b;if(!Number.isInteger(i)||i<=0)throw new Error("limit must be a positive integer");const c=e.tools?C(e.tools,o,i):[];return{content:[{type:"text",text:c.length===0?"No matching tools found.":`Loaded ${c.length} tool${c.length===1?"":"s"}. They are available from your next call:
6
6
  ${c.map(n=>`- ${n.name}: ${n.description.trim().split(/\r?\n/)[0]}`).join(`
7
- `)}`}],details:{loaded:c.map(n=>n.name)}}}}}l(I,"createToolSearchToolDefinition");export{k as Bm25Ranker,T as DEFAULT_TOOL_SEARCH_LIMIT,E as TOOL_SEARCH_DESCRIPTION,u as TOOL_SEARCH_TOOL_NAME,_ as createToolSearchDocument,I as createToolSearchToolDefinition,D as isToolSearchTool,b as tokenize,O as toolSearchSchema};
7
+ `)}`}],details:{loaded:c.map(n=>n.name)}}}}}l(D,"createToolSearchToolDefinition");export{_ as Bm25Ranker,b as DEFAULT_TOOL_SEARCH_LIMIT,E as TOOL_SEARCH_DESCRIPTION,p as TOOL_SEARCH_TOOL_NAME,w as createToolSearchDocument,D as createToolSearchToolDefinition,T as tokenize,k as toolSearchSchema};
package/dist/index.d.ts CHANGED
@@ -18,24 +18,27 @@ export { type CreateModelRuntimeOptions, CredentialSynchronizationError, type Cr
18
18
  export type { PackageManager, PathMetadata, ProgressCallback, ProgressEvent, ResolvedPaths, ResolvedResource, } from "./core/package-manager.ts";
19
19
  export { DefaultPackageManager } from "./core/package-manager.ts";
20
20
  export { buildRuleSet, matchPermissionRules, type PermissionBehavior, type PermissionRule, type PermissionRuleSet, type PermissionRuleSource, parsePermissionRule, type RuleCall, type RuleVerdict, } from "./core/permissions/rules.ts";
21
+ export { type SimpleCommand, simpleCommands, type UnwrappedCommand, unwrapCommand, } from "./core/permissions/shell-words.ts";
21
22
  export { evaluateToolPolicy, type PermissionAskHandler, type PermissionAskRequest, readAccessDenial, registerPermissionAskHandler, type ToolPolicyDecision, } from "./core/permissions/tool-policy.ts";
22
23
  export { describeProjectFacts, detectProjectFacts, type PackageManagerName, type ProjectFacts, projectPackageManager, } from "./core/project-facts.ts";
23
24
  export { buildProjectMap, formatProjectMapPrompt, type ProjectMap, type ProjectMapOptions, } from "./core/project-map.ts";
24
25
  export type { ResourceCollision, ResourceDiagnostic, ResourceLoader } from "./core/resource-loader.ts";
25
26
  export { DefaultResourceLoader, loadProjectContextFiles } from "./core/resource-loader.ts";
26
- export { detectSandboxAvailability, getProcessShellSandbox, type PlannedNetworkEscalation, type ResolvedSandboxPolicy, registerSandboxEscalationHandler, resolveSandboxPolicy, SANDBOX_ENV, type SandboxAvailability, type SandboxBlockedAccess, type SandboxDenial, type SandboxEscalationDecision, type SandboxEscalationHandler, type SandboxEscalationInput, type SandboxEscalationRequest, type SandboxEvent, type SandboxLevel, type SandboxOptions, type SandboxRunDetails, type SandboxSettings, type SandboxStatus, ShellSandbox, } from "./core/sandbox/index.ts";
27
+ export { detectSandboxAvailability, getProcessShellSandbox, type PlannedNetworkEscalation, PROTECTED_WRITE_NAMES, type ResolvedSandboxPolicy, registerSandboxEscalationHandler, resolveSandboxPolicy, SANDBOX_ENV, type SandboxAvailability, type SandboxBlockedAccess, type SandboxDenial, type SandboxEscalationDecision, type SandboxEscalationHandler, type SandboxEscalationInput, type SandboxEscalationRequest, type SandboxEvent, type SandboxLevel, type SandboxOptions, type SandboxRunDetails, type SandboxSettings, type SandboxStatus, ShellSandbox, } from "./core/sandbox/index.ts";
27
28
  export { AgentSessionRuntime, type AgentSessionRuntimeDiagnostic, type AgentSessionServices, type CreateAgentSessionFromServicesOptions, type CreateAgentSessionOptions, type CreateAgentSessionResult, type CreateAgentSessionRuntimeFactory, type CreateAgentSessionRuntimeResult, type CreateAgentSessionServicesOptions, createAgentSession, createAgentSessionFromServices, createAgentSessionRuntime, createAgentSessionServices, createBashTool, createCodingTools, createEditTool, createFindTool, createGrepTool, createLsTool, createPowerShellTool, createReadOnlyTools, createReadTool, createWriteTool, type PromptTemplate, } from "./core/sdk.ts";
28
29
  export { type BranchSummaryEntry, buildContextEntries, buildSessionContext, buildSessionProjection, type CompactionEntry, type ContextEditableContent, type ContextEditEntry, CURRENT_SESSION_VERSION, type CustomEntry, type CustomMessageEntry, type FileEntry, getLatestCompactionEntry, type ModelChangeEntry, migrateSessionEntries, type NewSessionOptions, type ProjectedSessionEntry, parseSessionEntries, type SessionContext, type SessionEntry, type SessionEntryBase, type SessionHeader, type SessionInfo, type SessionInfoEntry, SessionManager, type SessionMessageEntry, type SessionProjection, type SessionTreeNode, sessionEntryToContextMessages, type ThinkingLevelChangeEntry, } from "./core/session-manager.ts";
29
30
  export { type CacheWarmingMode, type CompactionModelOverride, type CompactionSettings, type DefaultProjectTrust, type FullscreenExitOutput, type ImageSettings, type PackageSource, type QuietStartup, type RetrySettings, SettingsManager, type SettingsManagerCreateOptions, type TuiMode, } from "./core/settings-manager.ts";
30
31
  export { formatSkillsForPrompt, type LoadSkillsFromDirOptions, type LoadSkillsResult, loadSkills, loadSkillsFromDir, type Skill, type SkillFrontmatter, } from "./core/skills.ts";
31
32
  export { createSyntheticSourceInfo } from "./core/source-info.ts";
32
33
  export { getToolDenial, type ToolDenial, type ToolDenialHint, type ToolDenialSource, } from "./core/tool-denial.ts";
34
+ export { isReadOnlyBashCommand } from "./core/tools/bash-read-only.ts";
33
35
  export { type EditDiffResult, generateDiffString, generateUnifiedPatch, normalizeForFuzzyMatch, } from "./core/tools/edit-diff.ts";
34
36
  export { type BashOperations, type BashSpawnContext, type BashSpawnHook, type BashToolDetails, type BashToolInput, type BashToolOptions, createBashToolDefinition, createEditToolDefinition, createFindToolDefinition, createGrepToolDefinition, createLocalBashOperations, createLocalPowerShellOperations, createLsToolDefinition, createPowerShellToolDefinition, createProcessToolDefinition, createReadToolDefinition, createWriteToolDefinition, DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, type EditOperations, type EditToolDetails, type EditToolInput, type EditToolOptions, type FindOperations, type FindToolDetails, type FindToolInput, type FindToolOptions, formatSize, type GrepOperations, type GrepToolDetails, type GrepToolInput, type GrepToolOptions, type LsOperations, type LsToolDetails, type LsToolInput, type LsToolOptions, type PowerShellOperations, type PowerShellSpawnContext, type PowerShellSpawnHook, type PowerShellToolDetails, type PowerShellToolInput, type PowerShellToolOptions, type ProcessToolDetails, type ProcessToolInput, type ReadOperations, type ReadToolDetails, type ReadToolInput, type ReadToolOptions, registerShellExecutionGuard, type ShellExecutionGuard, type ShellExecutionRequest, shellExecutionRefusal, type ToolsOptions, type TruncationOptions, type TruncationResult, truncateHead, truncateLine, truncateTail, type WriteOperations, type WriteToolInput, type WriteToolOptions, withFileMutationQueue, } from "./core/tools/index.ts";
35
37
  export { resolveToCwd } from "./core/tools/path-utils.ts";
38
+ export { formatReadLineRange } from "./core/tools/render-utils.ts";
36
39
  export { hasTrustRequiringProjectResources, type ProjectTrustDecision, ProjectTrustStore, type ProjectTrustStoreEntry, type ProjectTrustUpdate, } from "./core/trust-manager.ts";
37
40
  export { type ModelRoute, type ModelRouteReason, type ModelRouteRequest, VIRTUAL_MODEL_STATE_ENTRY, type VirtualModelDefinition, type VirtualModelStateData, } from "./core/virtual-models.ts";
38
- export { claimWorkspace, gitDirOf, readWorkspaceLock, releaseWorkspace, STALE_AFTER_MS, shellCommandDirectory, WORKSPACE_LOCK_FILE, type WorkspaceClaim, type WorkspaceLock, workspaceLockIsLive, workspaceOwnerSessionId, } from "./core/workspace-lock.ts";
41
+ export { claimWorkspace, defaultWorkspaceLockDir, gitDirOf, readWorkspaceLock, releaseWorkspace, STALE_AFTER_MS, shellCommandDirectory, WORKSPACE_LOCK_DIR_NAME, WORKSPACE_LOCK_FILE, type WorkspaceClaim, type WorkspaceLock, workspaceLockIsLive, workspaceLockPath, workspaceOwnerSessionId, } from "./core/workspace-lock.ts";
39
42
  export { applyShellEnvironmentPolicy, DEFAULT_SHELL_ENV_EXCLUDES, isDalCodeCredentialName, type ShellEnvironmentPolicy, withoutDalCodeCredentials, } from "./dal/child-env.ts";
40
43
  export { ADAPTATION_FILE, type Adaptation, type AdaptationState, adaptationState, adaptPackage, applyCommunityEnv, communityEnv, ensurePackageAdapted, type HardcodedPath, isAdaptablePackage, readAdaptation, scanHardcodedPiPaths, tryEnsurePackageAdapted, verifyAdaptation, } from "./dal/extension-compat.ts";
41
44
  export * from "./dal/hooks/index.ts";