dal-code 1.0.43 → 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 (441) hide show
  1. package/CHANGELOG.md +36 -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 +7 -7
  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 +7 -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/permissions/tool-policy.d.ts +2 -1
  32. package/dist/core/permissions/tool-policy.js +1 -1
  33. package/dist/core/project-trust.js +2 -2
  34. package/dist/core/prompt-templates.js +2 -2
  35. package/dist/core/remote-catalog-provider.js +1 -1
  36. package/dist/core/resource-loader.js +1 -1
  37. package/dist/core/sandbox/libreoffice.js +1 -0
  38. package/dist/core/sandbox/runtime.d.ts +1 -0
  39. package/dist/core/sandbox/runtime.js +1 -1
  40. package/dist/core/sandbox/shell-sandbox.js +6 -6
  41. package/dist/core/sandbox/windows.js +4 -4
  42. package/dist/core/session-manager.d.ts +1 -0
  43. package/dist/core/session-manager.js +12 -12
  44. package/dist/core/settings-defaults.js +1 -0
  45. package/dist/core/settings-manager.d.ts +5 -0
  46. package/dist/core/settings-manager.js +1 -1
  47. package/dist/core/settings-schema.d.ts +229 -0
  48. package/dist/core/settings-schema.js +1 -0
  49. package/dist/core/tool-denial.d.ts +13 -0
  50. package/dist/core/tool-denial.js +1 -0
  51. package/dist/core/tools/bash-read-only.d.ts +1 -0
  52. package/dist/core/tools/bash.js +13 -13
  53. package/dist/core/tools/read.js +12 -12
  54. package/dist/core/tools/render-utils.d.ts +40 -0
  55. package/dist/core/tools/render-utils.js +7 -7
  56. package/dist/core/tools/renderers/read.js +8 -8
  57. package/dist/core/trust-manager.js +1 -1
  58. package/dist/core/workspace-lock.d.ts +6 -2
  59. package/dist/core/workspace-lock.js +3 -3
  60. package/dist/dal/extension-compat.js +4 -4
  61. package/dist/dal/hooks/config.d.ts +5 -1
  62. package/dist/dal/hooks/config.js +1 -1
  63. package/dist/dal/hooks/extension.js +3 -3
  64. package/dist/dal/hooks/index.d.ts +1 -1
  65. package/dist/dal/hooks/index.js +1 -1
  66. package/dist/dal/i18n.js +1 -1
  67. package/dist/dal/manifest.js +1 -1
  68. package/dist/extensions/codemode/execute.js +14 -13
  69. package/dist/extensions/codemode/index.js +1 -1
  70. package/dist/extensions/codemode/renderer.js +6 -6
  71. package/dist/extensions/codemode/tool.d.ts +2 -3
  72. package/dist/extensions/codemode/tool.js +9 -12
  73. package/dist/extensions/mcp/cli.js +4 -4
  74. package/dist/extensions/mcp/index.js +12 -12
  75. package/dist/extensions/mcp/resources.d.ts +0 -5
  76. package/dist/extensions/mcp/resources.js +1 -1
  77. package/dist/extensions/mcp/runtime.d.ts +1 -4
  78. package/dist/extensions/mcp/runtime.js +3 -3
  79. package/dist/extensions/mcp/tools.js +7 -7
  80. package/dist/extensions/tool-search/tool.js +3 -3
  81. package/dist/index.d.ts +6 -2
  82. package/dist/index.js +1 -1
  83. package/dist/main.js +3 -3
  84. package/dist/migrations.js +5 -5
  85. package/dist/modes/interactive/components/settings-selector.d.ts +3 -1
  86. package/dist/modes/interactive/components/settings-selector.js +1 -1
  87. package/dist/modes/interactive/components/status-indicator.d.ts +1 -1
  88. package/dist/modes/interactive/components/status-indicator.js +1 -1
  89. package/dist/modes/interactive/components/tree-selector.js +1 -1
  90. package/dist/modes/interactive/interactive-mode.js +17 -17
  91. package/dist/modes/interactive/session-share.js +2 -2
  92. package/dist/modes/interactive/theme/dark.json +1 -1
  93. package/dist/modes/interactive/theme/light.json +1 -1
  94. package/dist/modes/interactive/theme/theme-schema.d.ts +18 -0
  95. package/dist/modes/interactive/theme/theme-schema.js +12 -0
  96. package/dist/modes/interactive/theme/theme-tokens.d.ts +255 -0
  97. package/dist/modes/interactive/theme/theme-tokens.js +1 -0
  98. package/dist/modes/interactive/theme/theme.d.ts +7 -10
  99. package/dist/modes/interactive/theme/theme.js +5 -5
  100. package/dist/modes/rpc/rpc-client.d.ts +5 -1
  101. package/dist/modes/rpc/rpc-client.js +2 -2
  102. package/dist/modes/rpc/rpc-mode.js +1 -1
  103. package/dist/modes/rpc/rpc-types.d.ts +20 -0
  104. package/dist/node_modules/@dalcode/dal-advisor/package.json +3 -3
  105. package/dist/node_modules/@dalcode/dal-advisor/src/index.js +8 -8
  106. package/dist/node_modules/@dalcode/dal-awake/package.json +2 -2
  107. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  108. package/dist/node_modules/@dalcode/dal-bridge/src/index.js +1 -1
  109. package/dist/node_modules/@dalcode/dal-capabilities/package.json +4 -4
  110. package/dist/node_modules/@dalcode/dal-capabilities/src/index.js +10 -10
  111. package/dist/node_modules/@dalcode/dal-codeindex/package.json +34 -0
  112. package/dist/node_modules/@dalcode/dal-codeindex/src/extract.js +3 -0
  113. package/dist/node_modules/@dalcode/dal-codeindex/src/format.js +11 -0
  114. package/dist/node_modules/@dalcode/dal-codeindex/src/index.js +4 -0
  115. package/dist/node_modules/@dalcode/dal-codeindex/src/indexer.js +1 -0
  116. package/dist/node_modules/@dalcode/dal-codeindex/src/languages.js +176 -0
  117. package/dist/node_modules/@dalcode/dal-codeindex/src/project.js +1 -0
  118. package/dist/node_modules/@dalcode/dal-codeindex/src/query.js +2 -0
  119. package/dist/node_modules/@dalcode/dal-codeindex/src/runtime.js +1 -0
  120. package/dist/node_modules/@dalcode/dal-codeindex/src/scan.js +1 -0
  121. package/dist/node_modules/@dalcode/dal-codeindex/src/semantic.js +2 -0
  122. package/dist/node_modules/@dalcode/dal-codeindex/src/sqlite.js +1 -0
  123. package/dist/node_modules/@dalcode/dal-codeindex/src/store.js +33 -0
  124. package/dist/node_modules/@dalcode/dal-codeindex/src/worker.js +1 -0
  125. package/dist/node_modules/@dalcode/dal-compat/package.json +2 -2
  126. package/dist/node_modules/@dalcode/dal-dap/package.json +2 -2
  127. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  128. package/dist/node_modules/@dalcode/dal-goal/package.json +3 -3
  129. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  130. package/dist/node_modules/@dalcode/dal-guard/src/index.js +4 -2
  131. package/dist/node_modules/@dalcode/dal-guard/src/mode.js +2 -2
  132. package/dist/node_modules/@dalcode/dal-guard/src/policy.js +1 -0
  133. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  134. package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
  135. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  136. package/dist/node_modules/@dalcode/dal-learn/package.json +2 -2
  137. package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
  138. package/dist/node_modules/@dalcode/dal-lsp/src/index.js +12 -10
  139. package/dist/node_modules/@dalcode/dal-mcp/package.json +7 -5
  140. package/dist/node_modules/@dalcode/dal-mcp/src/http-client.d.ts +9 -27
  141. package/dist/node_modules/@dalcode/dal-mcp/src/http-client.js +1 -2
  142. package/dist/node_modules/@dalcode/dal-mcp/src/index.js +17 -17
  143. package/dist/node_modules/@dalcode/dal-mcp/src/protocol-client.d.ts +38 -0
  144. package/dist/node_modules/@dalcode/dal-mcp/src/protocol-client.js +1 -0
  145. package/dist/node_modules/@dalcode/dal-mcp/src/proxy.js +6 -6
  146. package/dist/node_modules/@dalcode/dal-mcp/src/resources.js +1 -0
  147. package/dist/node_modules/@dalcode/dal-mcp/src/stdio-client.d.ts +9 -18
  148. package/dist/node_modules/@dalcode/dal-mcp/src/stdio-client.js +4 -5
  149. package/dist/node_modules/@dalcode/dal-mcp/src/types.d.ts +50 -5
  150. package/dist/node_modules/@dalcode/dal-mcp/src/types.js +1 -1
  151. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  152. package/dist/node_modules/@dalcode/dal-office/src/index.d.ts +2 -2
  153. package/dist/node_modules/@dalcode/dal-office/src/index.js +1 -1
  154. package/dist/node_modules/@dalcode/dal-office/src/render/docx.js +1 -1
  155. package/dist/node_modules/@dalcode/dal-office/src/render/pptx.d.ts +8 -0
  156. package/dist/node_modules/@dalcode/dal-office/src/render/pptx.js +3 -3
  157. package/dist/node_modules/@dalcode/dal-office/src/render/xlsx.js +1 -1
  158. package/dist/node_modules/@dalcode/dal-office/src/themes.d.ts +2 -0
  159. package/dist/node_modules/@dalcode/dal-office/src/themes.js +1 -1
  160. package/dist/node_modules/@dalcode/dal-office/src/tools/ppt-generate.js +3 -2
  161. package/dist/node_modules/@dalcode/dal-office/src/tools/ppt-plan.js +2 -2
  162. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +9 -3
  163. package/dist/node_modules/@dalcode/dal-pi-kit/dist/index.js +1 -1
  164. package/dist/node_modules/@dalcode/dal-pi-kit/dist/session-scope.js +1 -0
  165. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  166. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +9 -3
  167. package/dist/node_modules/@dalcode/dal-pi-kit/src/index.js +1 -1
  168. package/dist/node_modules/@dalcode/dal-pi-kit/src/session-scope.js +1 -0
  169. package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -4
  170. package/dist/node_modules/@dalcode/dal-plugins/src/brand.js +1 -1
  171. package/dist/node_modules/@dalcode/dal-plugins/src/index.js +11 -11
  172. package/dist/node_modules/@dalcode/dal-recall/package.json +2 -2
  173. package/dist/node_modules/@dalcode/dal-remote/package.json +2 -2
  174. package/dist/node_modules/@dalcode/dal-remote/src/cli.js +14 -9
  175. package/dist/node_modules/@dalcode/dal-remote/src/processes.js +2 -0
  176. package/dist/node_modules/@dalcode/dal-remote/src/service.js +7 -7
  177. package/dist/node_modules/@dalcode/dal-remote/src/spec.js +1 -1
  178. package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
  179. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  180. package/dist/node_modules/@dalcode/dal-rewind/src/core.d.ts +0 -1
  181. package/dist/node_modules/@dalcode/dal-rewind/src/core.js +8 -8
  182. package/dist/node_modules/@dalcode/dal-rewind/src/index.js +1 -1
  183. package/dist/node_modules/@dalcode/dal-router/package.json +9 -5
  184. package/dist/node_modules/@dalcode/dal-router/src/advisor.js +1 -1
  185. package/dist/node_modules/@dalcode/dal-router/src/commands.js +8 -7
  186. package/dist/node_modules/@dalcode/dal-router/src/config.d.ts +11 -0
  187. package/dist/node_modules/@dalcode/dal-router/src/config.js +2 -2
  188. package/dist/node_modules/@dalcode/dal-router/src/index.js +4 -4
  189. package/dist/node_modules/@dalcode/dal-router/src/roles/changes.js +5 -0
  190. package/dist/node_modules/@dalcode/dal-router/src/roles/index.js +13 -0
  191. package/dist/node_modules/@dalcode/dal-router/src/roles/models.d.ts +50 -0
  192. package/dist/node_modules/@dalcode/dal-router/src/roles/models.js +1 -0
  193. package/dist/node_modules/@dalcode/dal-router/src/roles/prompts.js +40 -0
  194. package/dist/node_modules/@dalcode/dal-router/src/roles/signals.js +2 -0
  195. package/dist/node_modules/@dalcode/dal-router/src/runtime.d.ts +3 -0
  196. package/dist/node_modules/@dalcode/dal-router/src/runtime.js +1 -1
  197. package/dist/node_modules/@dalcode/dal-router/src/subagent.js +1 -1
  198. package/dist/node_modules/@dalcode/dal-rtk/package.json +2 -2
  199. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  200. package/dist/node_modules/@dalcode/dal-skills/src/bundled/dal-slides/SKILL.md +74 -0
  201. package/dist/node_modules/@dalcode/dal-skills/src/bundled.js +1 -1
  202. package/dist/node_modules/@dalcode/dal-skills/src/client.js +1 -1
  203. package/dist/node_modules/@dalcode/dal-skills/src/index.js +14 -14
  204. package/dist/node_modules/@dalcode/dal-skills/src/packages.js +3 -3
  205. package/dist/node_modules/@dalcode/dal-skills/src/search.js +1 -1
  206. package/dist/node_modules/@dalcode/dal-statusline/package.json +2 -2
  207. package/dist/node_modules/@dalcode/dal-structured/package.json +2 -2
  208. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  209. package/dist/node_modules/@dalcode/dal-subagent/src/background.js +8 -8
  210. package/dist/node_modules/@dalcode/dal-subagent/src/index.js +21 -21
  211. package/dist/node_modules/@dalcode/dal-subagent/src/progress.js +1 -1
  212. package/dist/node_modules/@dalcode/dal-telemetry/package.json +3 -3
  213. package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
  214. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  215. package/dist/node_modules/@dalcode/dal-tool-catalog/src/index.js +4 -4
  216. package/dist/node_modules/@dalcode/dal-usage/package.json +2 -2
  217. package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
  218. package/dist/node_modules/@dalcode/dal-workflow/LICENSE +27 -0
  219. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  220. package/dist/node_modules/@dalcode/dal-workflow/src/index.js +4 -4
  221. package/dist/node_modules/@dalcode/dal-workflow/src/plan-mode.js +13 -13
  222. package/dist/node_modules/@dalcode/dal-workflow/src/todo-snapshot.js +2 -0
  223. package/dist/node_modules/@dalcode/dal-workflow/src/todo.js +4 -4
  224. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  225. package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js +1 -1
  226. package/dist/node_modules/@earendil-works/pi-agent-core/dist/types.d.ts +1 -0
  227. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
  228. package/dist/node_modules/@earendil-works/pi-ai/README.md +5 -34
  229. package/dist/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js +5 -5
  230. package/dist/node_modules/@earendil-works/pi-ai/dist/api/google-shared.js +1 -1
  231. package/dist/node_modules/@earendil-works/pi-ai/dist/api/mistral-conversations.js +4 -4
  232. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.js +1 -1
  233. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js +6 -6
  234. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js +2 -2
  235. package/dist/node_modules/@earendil-works/pi-ai/dist/index.d.ts +0 -1
  236. package/dist/node_modules/@earendil-works/pi-ai/dist/index.js +1 -1
  237. package/dist/node_modules/@earendil-works/pi-ai/dist/models.d.ts +1 -0
  238. package/dist/node_modules/@earendil-works/pi-ai/dist/models.js +1 -1
  239. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/compat-schema.d.ts +359 -0
  240. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/compat-schema.js +1 -0
  241. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  242. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
  243. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/anthropic.json +1 -1
  244. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/azure.json +1 -1
  245. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/baseten.json +1 -1
  246. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cerebras.json +1 -1
  247. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
  248. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
  249. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
  250. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/github-copilot.json +1 -1
  251. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/google.json +1 -1
  252. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/groq.json +1 -1
  253. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/huggingface.json +1 -1
  254. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/kimi-coding.json +1 -1
  255. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/minimax-cn.json +1 -1
  256. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/minimax.json +1 -1
  257. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/mistral.json +1 -1
  258. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/moonshotai-cn.json +1 -1
  259. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/nvidia.json +1 -1
  260. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openai-codex.json +1 -1
  261. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openai.json +1 -1
  262. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
  263. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  264. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  265. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/qwen-token-plan-cn.json +1 -1
  266. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/qwen-token-plan.json +1 -1
  267. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/radius.json +1 -1
  268. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/together.json +1 -1
  269. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  270. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xai.json +1 -1
  271. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi-token-plan-ams.json +1 -1
  272. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi-token-plan-cn.json +1 -1
  273. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi-token-plan-sgp.json +1 -1
  274. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi.json +1 -1
  275. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/kimi-coding.js +1 -1
  276. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/model-schema.d.ts +90 -0
  277. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/model-schema.js +1 -0
  278. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/openrouter-api.js +1 -0
  279. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/openrouter.js +1 -1
  280. package/dist/node_modules/@earendil-works/pi-ai/dist/types.d.ts +5 -146
  281. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/retry.js +1 -1
  282. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
  283. package/dist/node_modules/@earendil-works/pi-codemode/README.md +195 -11
  284. package/dist/node_modules/@earendil-works/pi-codemode/dist/cloudflare.js +1 -0
  285. package/dist/node_modules/@earendil-works/pi-codemode/dist/declarations.d.ts +0 -2
  286. package/dist/node_modules/@earendil-works/pi-codemode/dist/declarations.js +9 -84
  287. package/dist/node_modules/@earendil-works/pi-codemode/dist/index.d.ts +5 -2
  288. package/dist/node_modules/@earendil-works/pi-codemode/dist/index.js +1 -1
  289. package/dist/node_modules/@earendil-works/pi-codemode/dist/portable.js +1 -0
  290. package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/execution.d.ts +29 -0
  291. package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/execution.js +1 -0
  292. package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/host.d.ts +3 -16
  293. package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/host.js +1 -1
  294. package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/inline.d.ts +13 -0
  295. package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/inline.js +1 -0
  296. package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/prelude-source.js +14 -6
  297. package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/protocol.d.ts +72 -0
  298. package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/protocol.js +1 -1
  299. package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/remote.d.ts +32 -0
  300. package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/remote.js +1 -0
  301. package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/vm.js +3 -0
  302. package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/worker.js +1 -3
  303. package/dist/node_modules/@earendil-works/pi-codemode/dist/source.js +4 -3
  304. package/dist/node_modules/@earendil-works/pi-codemode/dist/types.d.ts +51 -1
  305. package/dist/node_modules/@earendil-works/pi-codemode/package.json +14 -2
  306. package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
  307. package/dist/node_modules/@earendil-works/pi-mcp/CHANGELOG.md +13 -0
  308. package/dist/node_modules/@earendil-works/pi-mcp/dist/client.js +1 -1
  309. package/dist/node_modules/@earendil-works/pi-mcp/dist/index.d.ts +1 -1
  310. package/dist/node_modules/@earendil-works/pi-mcp/dist/oauth/errors.d.ts +2 -2
  311. package/dist/node_modules/@earendil-works/pi-mcp/dist/oauth/errors.js +1 -1
  312. package/dist/node_modules/@earendil-works/pi-mcp/dist/oauth/flow.js +1 -1
  313. package/dist/node_modules/@earendil-works/pi-mcp/dist/protocol/content.d.ts +1 -1
  314. package/dist/node_modules/@earendil-works/pi-mcp/dist/transports/streamable-http.d.ts +2 -2
  315. package/dist/node_modules/@earendil-works/pi-mcp/dist/transports/streamable-http.js +4 -4
  316. package/dist/node_modules/@earendil-works/pi-mcp/dist/transports/transport.d.ts +4 -1
  317. package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
  318. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  319. package/dist/node_modules/@earendil-works/pi-tui/README.md +5 -3
  320. package/dist/node_modules/@earendil-works/pi-tui/dist/components/editor.js +6 -6
  321. package/dist/node_modules/@earendil-works/pi-tui/dist/components/input.js +2 -2
  322. package/dist/node_modules/@earendil-works/pi-tui/dist/index.d.ts +1 -1
  323. package/dist/node_modules/@earendil-works/pi-tui/dist/index.js +1 -1
  324. package/dist/node_modules/@earendil-works/pi-tui/dist/keys.js +5 -5
  325. package/dist/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.js +1 -1
  326. package/dist/node_modules/@earendil-works/pi-tui/dist/terminal-image.js +1 -1
  327. package/dist/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.js +3 -3
  328. package/dist/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.js +1 -1
  329. package/dist/node_modules/@earendil-works/pi-tui/dist/tui.d.ts +4 -0
  330. package/dist/node_modules/@earendil-works/pi-tui/dist/tui.js +2 -2
  331. package/dist/node_modules/@earendil-works/pi-tui/dist/utils.js +1 -1
  332. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  333. package/dist/sdk/index.d.ts +3 -3
  334. package/dist/sdk/index.js +1 -1
  335. package/dist/sdk/rewind.d.ts +1 -1
  336. package/dist/sdk/rewind.js +1 -1
  337. package/dist/utils/clipboard.js +1 -1
  338. package/dist/utils/output-files.js +1 -1
  339. package/dist/utils/temp-files.js +1 -0
  340. package/docs/security.md +24 -7
  341. package/examples/README.md +0 -3
  342. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  343. package/examples/extensions/dynamic-resources/dynamic.json +1 -1
  344. package/examples/extensions/gondolin/package-lock.json +2 -2
  345. package/examples/extensions/gondolin/package.json +1 -1
  346. package/examples/extensions/minimal-mode.ts +4 -5
  347. package/examples/extensions/overlay-test.ts +2 -2
  348. package/examples/extensions/sandbox/package-lock.json +2 -2
  349. package/examples/extensions/sandbox/package.json +1 -1
  350. package/examples/extensions/subagent/index.ts +4 -6
  351. package/examples/extensions/with-deps/package-lock.json +2 -2
  352. package/examples/extensions/with-deps/package.json +1 -1
  353. package/npm-shrinkwrap.json +9 -460
  354. package/package.json +3 -12
  355. package/dist/modes/interactive/theme/theme-json.d.ts +0 -75
  356. package/dist/modes/interactive/theme/theme-json.js +0 -12
  357. package/dist/modes/interactive/theme/theme-schema.json +0 -361
  358. package/dist/node_modules/@earendil-works/chord/README.md +0 -264
  359. package/dist/node_modules/@earendil-works/chord/dist/api.js +0 -1
  360. package/dist/node_modules/@earendil-works/chord/dist/bundler.js +0 -1
  361. package/dist/node_modules/@earendil-works/chord/dist/context/index.js +0 -1
  362. package/dist/node_modules/@earendil-works/chord/dist/delta/apply-immutable-trusted.js +0 -1
  363. package/dist/node_modules/@earendil-works/chord/dist/delta/diff.js +0 -1
  364. package/dist/node_modules/@earendil-works/chord/dist/delta/draft.js +0 -0
  365. package/dist/node_modules/@earendil-works/chord/dist/delta/index.js +0 -1
  366. package/dist/node_modules/@earendil-works/chord/dist/delta/revision-validator.js +0 -1
  367. package/dist/node_modules/@earendil-works/chord/dist/delta/tracker.js +0 -1
  368. package/dist/node_modules/@earendil-works/chord/dist/facets/host.js +0 -1
  369. package/dist/node_modules/@earendil-works/chord/dist/facets/loader.js +0 -1
  370. package/dist/node_modules/@earendil-works/chord/dist/index.js +0 -1
  371. package/dist/node_modules/@earendil-works/chord/dist/json.js +0 -1
  372. package/dist/node_modules/@earendil-works/chord/dist/node/bundle-loader.js +0 -2
  373. package/dist/node_modules/@earendil-works/chord/dist/node/bundle.js +0 -4
  374. package/dist/node_modules/@earendil-works/chord/dist/node/manifest.js +0 -1
  375. package/dist/node_modules/@earendil-works/chord/dist/node/package.js +0 -1
  376. package/dist/node_modules/@earendil-works/chord/dist/node.js +0 -1
  377. package/dist/node_modules/@earendil-works/chord/dist/services/consumer.js +0 -1
  378. package/dist/node_modules/@earendil-works/chord/dist/services/errors.js +0 -1
  379. package/dist/node_modules/@earendil-works/chord/dist/services/handle.js +0 -1
  380. package/dist/node_modules/@earendil-works/chord/dist/services/instances.js +0 -1
  381. package/dist/node_modules/@earendil-works/chord/dist/services/loopback.js +0 -1
  382. package/dist/node_modules/@earendil-works/chord/dist/services/provider.js +0 -1
  383. package/dist/node_modules/@earendil-works/chord/dist/services/state-codec.js +0 -1
  384. package/dist/node_modules/@earendil-works/chord/dist/services/state-internals.js +0 -1
  385. package/dist/node_modules/@earendil-works/chord/dist/services/state.js +0 -1
  386. package/dist/node_modules/@earendil-works/chord/dist/services/wire.js +0 -1
  387. package/dist/node_modules/@earendil-works/chord/dist/types.js +0 -0
  388. package/dist/node_modules/@earendil-works/chord/package.json +0 -62
  389. package/dist/node_modules/@earendil-works/chord/src/delta/README.md +0 -191
  390. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/assistant-message-frame.d.ts +0 -63
  391. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/assistant-message-frame.js +0 -1
  392. package/dist/node_modules/@earendil-works/pi-client/CHANGELOG.md +0 -45
  393. package/dist/node_modules/@earendil-works/pi-client/LICENSE +0 -21
  394. package/dist/node_modules/@earendil-works/pi-client/README.md +0 -72
  395. package/dist/node_modules/@earendil-works/pi-client/dist/client.js +0 -1
  396. package/dist/node_modules/@earendil-works/pi-client/dist/connection.js +0 -1
  397. package/dist/node_modules/@earendil-works/pi-client/dist/errors.js +0 -1
  398. package/dist/node_modules/@earendil-works/pi-client/dist/index.js +0 -1
  399. package/dist/node_modules/@earendil-works/pi-client/dist/promise.js +0 -1
  400. package/dist/node_modules/@earendil-works/pi-client/dist/transport.js +0 -0
  401. package/dist/node_modules/@earendil-works/pi-client/dist/types.js +0 -0
  402. package/dist/node_modules/@earendil-works/pi-client/dist/unix.js +0 -1
  403. package/dist/node_modules/@earendil-works/pi-client/package.json +0 -46
  404. package/dist/node_modules/@earendil-works/pi-protocol/LICENSE +0 -21
  405. package/dist/node_modules/@earendil-works/pi-protocol/README.md +0 -41
  406. package/dist/node_modules/@earendil-works/pi-protocol/dist/cbor/decoder.js +0 -1
  407. package/dist/node_modules/@earendil-works/pi-protocol/dist/cbor/encoder.js +0 -1
  408. package/dist/node_modules/@earendil-works/pi-protocol/dist/cbor/index.js +0 -1
  409. package/dist/node_modules/@earendil-works/pi-protocol/dist/cbor/options.js +0 -1
  410. package/dist/node_modules/@earendil-works/pi-protocol/dist/codec.js +0 -1
  411. package/dist/node_modules/@earendil-works/pi-protocol/dist/framing.js +0 -1
  412. package/dist/node_modules/@earendil-works/pi-protocol/dist/index.js +0 -1
  413. package/dist/node_modules/@earendil-works/pi-protocol/dist/protocol.js +0 -1
  414. package/dist/node_modules/@earendil-works/pi-protocol/dist/schemas.js +0 -1
  415. package/dist/node_modules/@earendil-works/pi-protocol/package.json +0 -39
  416. package/dist/node_modules/@earendil-works/pi-server/CHANGELOG.md +0 -81
  417. package/dist/node_modules/@earendil-works/pi-server/LICENSE +0 -21
  418. package/dist/node_modules/@earendil-works/pi-server/README.md +0 -63
  419. package/dist/node_modules/@earendil-works/pi-server/dist/connection.js +0 -1
  420. package/dist/node_modules/@earendil-works/pi-server/dist/errors.js +0 -1
  421. package/dist/node_modules/@earendil-works/pi-server/dist/index.js +0 -1
  422. package/dist/node_modules/@earendil-works/pi-server/dist/listener.js +0 -0
  423. package/dist/node_modules/@earendil-works/pi-server/dist/server.js +0 -1
  424. package/dist/node_modules/@earendil-works/pi-server/dist/session-router.js +0 -1
  425. package/dist/node_modules/@earendil-works/pi-server/dist/testing/client.js +0 -1
  426. package/dist/node_modules/@earendil-works/pi-server/dist/testing/host.js +0 -1
  427. package/dist/node_modules/@earendil-works/pi-server/dist/testing/index.js +0 -1
  428. package/dist/node_modules/@earendil-works/pi-server/dist/testing/server.js +0 -1
  429. package/dist/node_modules/@earendil-works/pi-server/dist/transports/unix/address.js +0 -1
  430. package/dist/node_modules/@earendil-works/pi-server/dist/transports/unix/index.js +0 -1
  431. package/dist/node_modules/@earendil-works/pi-server/dist/transports/unix/listener.js +0 -1
  432. package/dist/node_modules/@earendil-works/pi-server/dist/transports/unix/preset.js +0 -1
  433. package/dist/node_modules/@earendil-works/pi-server/dist/transports/unix/types.js +0 -0
  434. package/dist/node_modules/@earendil-works/pi-server/dist/types.js +0 -0
  435. package/dist/node_modules/@earendil-works/pi-server/package.json +0 -45
  436. package/examples/plugins/pi-example-plugin/README.md +0 -38
  437. package/examples/plugins/pi-example-plugin/package.json +0 -10
  438. package/examples/plugins/pi-example-plugin/src/contract.ts +0 -13
  439. package/examples/plugins/pi-example-plugin/src/session.ts +0 -24
  440. package/examples/plugins/pi-example-plugin/src/tui.ts +0 -31
  441. /package/dist/node_modules/{@earendil-works/chord → @dalcode/dal-codeindex}/LICENSE +0 -0
@@ -1,23 +1,24 @@
1
- var Z=Object.defineProperty;var s=(e,t)=>Z(e,"name",{value:t,configurable:!0});import{CodemodeSandbox as ee,loadQuickJSWasm as te,parseCodemodeSource as ne,renderToolSample as re,toCodemodeIdentifier as I}from"@earendil-works/pi-codemode";import{getCodemodeWorkerSpecifier as oe,getQuickJSWasmPath as se}from"../../config.js";import{formatSize as ie}from"../../core/tools/truncate.js";import{combineUsage as ae}from"../../core/usage-totals.js";import{writeOutputFile as H}from"../../utils/output-files.js";import{Bm25Ranker as ce,createToolSearchDocument as ue,DEFAULT_TOOL_SEARCH_LIMIT as le}from"../tool-search/tool.js";import{CODEMODE_DOCS_PATH as F,CODEMODE_STORE_ENTRY_TYPE as G,getCodemodeCallableTools as fe,toCodemodeDeclaration as pe}from"./tool.js";const de=200,J=500,me=4,ge=256*1024*1024,Y=new Set(["chat","image","classifier"]);function v(e,t){return e.length>t?`${e.slice(0,t-3)}...`:e}s(v,"truncateText");function ye(e){if(e===void 0)return"";try{return v(JSON.stringify(e)??"",de)}catch{return""}}s(ye,"previewArgs");function B(e){return(e.content??[]).filter(t=>t.type==="text").map(t=>t.text).join(`
2
- `)}s(B,"textOf");function P(e){if(typeof e=="string"&&Y.has(e))return e;throw new Error(`Unknown model type ${JSON.stringify(e)}. Use "chat", "image", or "classifier".`)}s(P,"toModelType");function V(e){if(e!=null){if(typeof e!="string")throw new Error("provider must be a string");return e}}s(V,"toProvider");function D(e){const t={...e};return delete t.headers,t}s(D,"toModelInfo");function L(e){return`${/^[aeiou]/.test(e)?"an":"a"} ${e}`}s(L,"withArticle");function w(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(w,"isRecord");function b(e){if(e==null)return String(e);if(Array.isArray(e))return e.length===0?"an empty array":"an array";if(typeof e=="object"){const t=Object.keys(e);return t.length===0?"{}":`{ ${t.slice(0,6).join(", ")}${t.length>6?", ...":""} }`}return typeof e=="string"?"a string":`a ${typeof e}`}s(b,"describeValue");const he='{ state: { ... }, images?: [{ type: "image", data: <base64>, mimeType }], questions: { <id>: { type: "choice", instructions, criteria: { <label>: <meaning> } } | { type: "score", instructions, criteria: [<lowest level>, ..., <highest level>] } | { type: "bool", instructions, criteria: { true: <meaning>, false: <meaning> } } } }';function $e(e){const t=s(o=>new Error(`models.classify() ${o}. Expected context: ${he}. See "Classify" in ${F}.`),"fail");if(!w(e))throw t(`expects a context object as its second argument, got ${b(e)}`);if(!w(e.state))throw t(`context.state must be an object, got ${b(e.state)}`);const{images:n}=e;if(n!==void 0){if(!Array.isArray(n))throw t(`context.images must be an array, got ${b(n)}`);n.forEach((o,c)=>{if(!w(o)||o.type!=="image"||typeof o.data!="string"||typeof o.mimeType!="string")throw t(`context.images[${c}] must be an image block, got ${b(o)}`)})}const{questions:r}=e;if(!w(r)||Object.keys(r).length===0)throw t(`context.questions must map question IDs to questions, got ${b(r)}`);const i=s(o=>o.length>0&&o.every(c=>typeof c=="string"),"isStrings");for(const[o,c]of Object.entries(r)){const f=`context.questions.${o}`;if(!w(c))throw t(`${f} must be a question object, got ${b(c)}`);if(typeof c.instructions!="string")throw t(`${f}.instructions must be a string`);const{criteria:p}=c;if(c.type==="choice"){if(!w(p)||!i(Object.values(p)))throw t(`${f} is a "choice" question, so criteria must map each label to its meaning`)}else if(c.type==="score"){if(!Array.isArray(p)||!i(p))throw t(`${f} is a "score" question, so criteria must list the levels as strings, lowest first`)}else if(c.type==="bool"){if(!w(p)||typeof p.true!="string"||typeof p.false!="string")throw t(`${f} is a "bool" question, so criteria must be { true: string, false: string }`)}else throw t(`${f}.type must be "choice", "score", or "bool", got ${JSON.stringify(c.type)}`)}return e}s($e,"checkClassifierContext");function we(e){const t=s(r=>new Error(`models.generateImages() ${r}. Expected context: { input: [{ type: "text", text: <prompt> }, ...optional { type: "image", data: <base64>, mimeType } references] }. See "Generate images" in ${F}.`),"fail");if(!w(e))throw t(`expects a context object as its second argument, got ${b(e)}`);const{input:n}=e;if(!Array.isArray(n)||n.length===0)throw t(`context.input must be a non-empty array of blocks, got ${b(n)}`);return n.forEach((r,i)=>{if(!(w(r)&&r.type==="text"&&typeof r.text=="string")&&!(w(r)&&r.type==="image"&&typeof r.data=="string"&&typeof r.mimeType=="string"))throw t(`context.input[${i}] must be a text or image block, got ${b(r)}`)}),e}s(we,"checkImagesContext");function be(e){let t=0;const n=[];return async r=>{t>=e&&await new Promise(i=>n.push(i)),t++;try{return await r()}finally{t--,n.shift()?.()}}}s(be,"createLimiter");function xe(e){if(typeof e!="object"||e===null)return!1;const{set:t,delete:n}=e;return typeof t=="object"&&t!==null&&Array.isArray(n)&&n.every(r=>typeof r=="string")}s(xe,"isStoreEntryData");function Te(e){const t=new Map;for(const n of e)if(!(n.type!=="custom"||n.customType!==G||!xe(n.data))){for(const r of n.data.delete)t.delete(r);for(const[r,i]of Object.entries(n.data.set))t.set(r,i)}return Object.fromEntries(t)}s(Te,"readCodemodeStore");const Ee=1e4,q=4;function Oe(e){return typeof e=="string"?e:JSON.stringify(e)??String(e)}s(Oe,"valueText");function Se(e){const t=e.filter(o=>o.type==="text"&&!o.console).length,n=[],r=[];let i=0;for(const o of e)o.type==="image"?n.push(o):o.console?r.push(o.text):(i++,n.push({type:"text",text:t>1?`==> text ${i}/${t} <==
3
- ${o.text}`:o.text}));return r.length>0&&n.push({type:"text",text:`<console_output>
1
+ var ee=Object.defineProperty;var o=(e,t)=>ee(e,"name",{value:t,configurable:!0});import{CodemodeSandbox as te,loadQuickJSWasm as ne,parseCodemodeSource as re,renderToolSample as oe,toCodemodeIdentifier as _}from"@earendil-works/pi-codemode";import{getCodemodeWorkerSpecifier as se,getQuickJSWasmPath as ie}from"../../config.js";import{formatSize as ae}from"../../core/tools/truncate.js";import{combineUsage as ce}from"../../core/usage-totals.js";import{writeOutputFile as F}from"../../utils/output-files.js";import{Bm25Ranker as ue,createToolSearchDocument as le,DEFAULT_TOOL_SEARCH_LIMIT as fe}from"../tool-search/tool.js";import{CODEMODE_DOCS_PATH as G,CODEMODE_STORE_ENTRY_TYPE as J,getCodemodeCallableTools as pe,toCodemodeDeclaration as de}from"./tool.js";const me=200,Y=500,ge=4,ye=256*1024*1024,B=2;let v=0;const V=new Set(["chat","image","classifier"]);function D(e,t){return e.length>t?`${e.slice(0,t-3)}...`:e}o(D,"truncateText");function he(e){if(e===void 0)return"";try{return D(JSON.stringify(e)??"",me)}catch{return""}}o(he,"previewArgs");function X(e){return(e.content??[]).filter(t=>t.type==="text").map(t=>t.text).join(`
2
+ `)}o(X,"textOf");function P(e){if(typeof e=="string"&&V.has(e))return e;throw new Error(`Unknown model type ${JSON.stringify(e)}. Use "chat", "image", or "classifier".`)}o(P,"toModelType");function K(e){if(e!=null){if(typeof e!="string")throw new Error("provider must be a string");return e}}o(K,"toProvider");function q(e){const t={...e};return delete t.headers,t}o(q,"toModelInfo");function L(e){return`${/^[aeiou]/.test(e)?"an":"a"} ${e}`}o(L,"withArticle");function w(e){if(e==null)return String(e);if(Array.isArray(e))return e.length===0?"an empty array":"an array";if(typeof e=="object"){const t=Object.keys(e);return t.length===0?"{}":`{ ${t.slice(0,6).join(", ")}${t.length>6?", ...":""} }`}return typeof e=="string"?"a string":`a ${typeof e}`}o(w,"describeValue");const we='{ state: { ... }, images?: [{ type: "image", data: <base64>, mimeType }], questions: { <id>: { type: "choice", instructions, criteria: { <label>: <meaning> } } | { type: "score", instructions, criteria: [<lowest level>, ..., <highest level>] } | { type: "bool", instructions, criteria: { true: <meaning>, false: <meaning> } } } }';function $e(e){const t=o(u=>new Error(`models.classify() ${u}. Expected context: ${we}. See "Classify" in ${G}.`),"fail");if(typeof e!="object"||e===null||Array.isArray(e))throw t(`expects a context object as its second argument, got ${w(e)}`);const{state:n,images:r,questions:i}=e;if(typeof n!="object"||n===null||Array.isArray(n))throw t(`context.state must be an object, got ${w(n)}`);if(r!==void 0){if(!Array.isArray(r))throw t(`context.images must be an array, got ${w(r)}`);r.forEach((u,l)=>{if(u?.type!=="image"||typeof u.data!="string"||typeof u.mimeType!="string")throw t(`context.images[${l}] must be an image block, got ${w(u)}`)})}if(typeof i!="object"||i===null||Array.isArray(i)||Object.keys(i).length===0)throw t(`context.questions must map question IDs to questions, got ${w(i)}`);const s=o(u=>u.length>0&&u.every(l=>typeof l=="string"),"isStrings");for(const[u,l]of Object.entries(i)){const p=`context.questions.${u}`;if(typeof l!="object"||l===null||Array.isArray(l))throw t(`${p} must be a question object, got ${w(l)}`);const{type:d,instructions:c,criteria:a}=l;if(typeof c!="string")throw t(`${p}.instructions must be a string`);if(d==="choice"){if(typeof a!="object"||a===null||Array.isArray(a)||!s(Object.values(a)))throw t(`${p} is a "choice" question, so criteria must map each label to its meaning`)}else if(d==="score"){if(!Array.isArray(a)||!s(a))throw t(`${p} is a "score" question, so criteria must list the levels as strings, lowest first`)}else if(d==="bool"){const f=a;if(typeof f?.true!="string"||typeof f.false!="string")throw t(`${p} is a "bool" question, so criteria must be { true: string, false: string }`)}else throw t(`${p}.type must be "choice", "score", or "bool", got ${JSON.stringify(d)}`)}return e}o($e,"checkClassifierContext");function be(e){const t=o(r=>new Error(`models.generateImages() ${r}. Expected context: { input: [{ type: "text", text: <prompt> }, ...optional { type: "image", data: <base64>, mimeType } references] }. See "Generate images" in ${G}.`),"fail");if(typeof e!="object"||e===null||Array.isArray(e))throw t(`expects a context object as its second argument, got ${w(e)}`);const{input:n}=e;if(!Array.isArray(n)||n.length===0)throw t(`context.input must be a non-empty array of blocks, got ${w(n)}`);return n.forEach((r,i)=>{if(!(r?.type==="text"&&typeof r.text=="string")&&!(r?.type==="image"&&typeof r.data=="string"&&typeof r.mimeType=="string"))throw t(`context.input[${i}] must be a text or image block, got ${w(r)}`)}),e}o(be,"checkImagesContext");function Ee(e){let t=0;const n=[];return async r=>{t>=e&&await new Promise(i=>n.push(i)),t++;try{return await r()}finally{t--,n.shift()?.()}}}o(Ee,"createLimiter");function xe(e){if(typeof e!="object"||e===null)return!1;const{set:t,delete:n}=e;return typeof t=="object"&&t!==null&&Array.isArray(n)&&n.every(r=>typeof r=="string")}o(xe,"isStoreEntryData");function Te(e){const t=new Map;for(const n of e)if(!(n.type!=="custom"||n.customType!==J||!xe(n.data))){for(const r of n.data.delete)t.delete(r);for(const[r,i]of Object.entries(n.data.set))t.set(r,i)}return Object.fromEntries(t)}o(Te,"readCodemodeStore");const Oe=1e4,U=4;function Se(e){return typeof e=="string"?e:JSON.stringify(e)??String(e)}o(Se,"valueText");function Ae(e){const t=e.filter(s=>s.type==="text"&&!s.console).length,n=[],r=[];let i=0;for(const s of e)s.type==="image"?n.push(s):s.console?r.push(s.text):(i++,n.push({type:"text",text:t>1?`==> text ${i}/${t} <==
3
+ ${s.text}`:s.text}));return r.length>0&&n.push({type:"text",text:`<console_output>
4
4
  ${r.join(`
5
5
  `)}
6
- </console_output>`}),n}s(Se,"formatOutput");function X(e){const t=[];for(const n of e){const r=t.at(-1);if(n.type==="text"&&r?.type==="text"){const i=r.text===""||r.text.endsWith(`
7
- `)?"":`
8
- `;t[t.length-1]={type:"text",text:`${r.text}${i}${n.text}`}}else t.push(n)}return t}s(X,"joinAdjacentText");function Me(e){return e.length===0?"No tool calls were made.":`Tool calls made before the failure (they are not undone): ${e.map(t=>`${t.name} (${t.status})`).join(", ")}`}s(Me,"formatCallSummary");function Ae(e,t){const{error:n}=e;return`${n.kind==="script"?n.stack??`${n.name??"Error"}: ${n.message}`:n.kind==="timeout"?`Script timed out: ${n.message}`:n.kind==="aborted"?`Script aborted: ${n.message}`:`Script sandbox failed: ${n.message}`}
6
+ </console_output>`}),n}o(Ae,"formatOutput");function Q(e){const t=[];let n=[],r="";const i=o(()=>{n.length>0&&t.push({type:"text",text:n.join("")}),n=[],r=""},"flush");for(const s of e){if(s.type!=="text"){i(),t.push(s);continue}r!==""&&!r.endsWith(`
7
+ `)&&(n.push(`
8
+ `),r=`
9
+ `),n.push(s.text),s.text!==""&&(r=s.text)}return i(),t}o(Q,"joinAdjacentText");function Me(e){return e.length===0?"No tool calls were made.":`Tool calls made before the failure (they are not undone): ${e.map(t=>`${t.name} (${t.status})`).join(", ")}`}o(Me,"formatCallSummary");function Ce(e,t){const{error:n}=e;return`${n.kind==="script"?n.stack??`${n.name??"Error"}: ${n.message}`:n.kind==="timeout"?`Script timed out: ${n.message}`:n.kind==="aborted"?`Script aborted: ${n.message}`:`Script sandbox failed: ${n.message}`}
9
10
 
10
- ${Me(t)}`}s(Ae,"formatError");async function _e(e){try{return{path:await H("pi-codemode",".txt",e)}}catch(t){return{error:t instanceof Error?t.message:String(t)}}}s(_e,"spillOutput");const Ce={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp"};async function ke(e){const t=new Map,n=s(async({data:i,mimeType:o})=>{const c=Buffer.from(i,"base64"),f=`${o}, ${ie(c.length)}`,p=Ce[o];if(!p)throw new Error(`No file extension for image type ${o}`);try{return`[Image saved to ${await H("pi-codemode",p,c)} (${f})]`}catch(m){return`[Image (${f}) could not be saved: ${m instanceof Error?m.message:String(m)}]`}},"label");return(await Promise.all(e.map(async i=>{if(i.type!=="image")return[i];let o=t.get(i.data);return o||(o=n(i),t.set(i.data,o)),[{type:"text",text:await o},i]}))).flat()}s(ke,"saveImages");async function Ie(e,t){const n=e.filter(l=>l.type==="text").map(l=>l.text),r=n.join(`
11
- `),i=t*q;if(n.length===0||r.length<=i)return{items:e};const o=Math.floor(i/2),c=i-o,f=r.length-o-c,p=r.slice(0,o),m=c>0?r.slice(-c):"";let u=`Warning: truncated output (original token count: ${Math.ceil(r.length/q)})
11
+ ${Me(t)}`}o(Ce,"formatError");async function ke(e){try{return{path:await F("pi-codemode",".txt",e)}}catch(t){return{error:t instanceof Error?t.message:String(t)}}}o(ke,"spillOutput");const je={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp"};async function _e(e){const t=new Map,n=o(async({data:i,mimeType:s})=>{const u=Buffer.from(i,"base64"),l=`${s}, ${ae(u.length)}`,p=je[s];if(!p)throw new Error(`No file extension for image type ${s}`);try{return`[Image saved to ${await F("pi-codemode",p,u)} (${l})]`}catch(d){return`[Image (${l}) could not be saved: ${d instanceof Error?d.message:String(d)}]`}},"label");return(await Promise.all(e.map(async i=>{if(i.type!=="image")return[i];let s=t.get(i.data);return s||(s=n(i),t.set(i.data,s)),[{type:"text",text:await s},i]}))).flat()}o(_e,"saveImages");async function Ie(e,t){const n=e.filter(f=>f.type==="text").map(f=>f.text),r=n.join(`
12
+ `),i=t*U;if(n.length===0||r.length<=i)return{items:e};const s=Math.floor(i/2),u=i-s,l=r.length-s-u,p=r.slice(0,s),d=u>0?r.slice(-u):"";let c=`Warning: truncated output (original token count: ${Math.ceil(r.length/U)})
12
13
  Total output lines: ${r.split(`
13
14
  `).length}
14
15
 
15
- ${p}\u2026${Math.ceil(f/q)} tokens truncated\u2026${m}`;const a=await _e(r);return u+="path"in a?`
16
+ ${p}\u2026${Math.ceil(l/U)} tokens truncated\u2026${d}`;const a=await ke(r);return c+="path"in a?`
16
17
 
17
18
  [Full output: ${a.path} (read with offset/limit)]`:`
18
19
 
19
- [Could not save the full output: ${a.error}]`,{items:[{type:"text",text:u},...e.filter(l=>l.type==="image")],..."path"in a?{fullOutputPath:a.path}:{}}}s(Ie,"truncateOutput");function je(e,t){const{result:n}=t;if(e.outputSchema&&n.structuredContent!==void 0)return n.structuredContent;const r=B(n);if(t.isError)throw new Error(r||`Tool "${e.name}" failed`);return r}s(je,"toScriptValue");async function Fe(e,t,n,r,i,o={}){const c=performance.now(),{code:f,options:p}=ne(t.code),m=[];let u,a=0;const l=s(d=>{a+=d},"addGeneratedImages"),g=s(d=>{u=u?ae(u,d):d},"addModelUsage"),$=s(()=>({calls:m.map(d=>({...d}))}),"snapshot"),T=s(()=>r?.({content:[],details:$()}),"publish"),E=i?fe(i.tools):[],C=o.getToolGuidelines?.(),S=new Map(E.map(d=>[d.name,re(pe(d,C?.get(d.name)))])),j=E.map(d=>({name:d.name,description:S.get(d.name),execute:s(async(k,{signal:W})=>{const _={id:`${e}/?`,name:d.name,args:ye(k),status:"running"};m.push(_),T();const z=performance.now();if(!i)throw new Error("Tool calls need a session");const R=await i.executeTool(d.name,k,{signal:W});return _.id=R.toolCall.id,_.durationMs=performance.now()-z,R.isError?(_.status=W.aborted?"cancelled":"error",_.error=v(B(R.result)||`Tool "${d.name}" failed`,J)):_.status="ok",T(),je(d,R)},"execute")})),O=new ee({tools:j,globals:[...Ne(E,S,o),...o.models&&i?Re(i.modelRegistry,e,m,T,g,l):[]],timeoutMs:p.timeoutMs??Number.POSITIVE_INFINITY,memoryLimitBytes:ge,wasm:te(se()),workerUrl:oe()});let y;try{const d=i?Te(i.sessionManager.getBranch()):{};y=await O.execute(f,{signal:n,store:d})}finally{await O.close()}for(const d of m)d.status==="running"&&(d.status="cancelled");const x=[...y.output];if(y.ok){const{set:d,delete:k}=y.storeWrites;(Object.keys(d).length>0||k.length>0)&&o.appendEntry?.(G,{set:d,delete:k}),y.value!==void 0&&x.push({type:"text",text:Oe(y.value)})}const M=Se(x);y.ok||M.push({type:"text",text:`Script error:
20
- ${Ae(y,m)}`}),a>0&&!M.some(d=>d.type==="image")&&M.push({type:"text",text:`Note: models.generateImages() returned ${a} image${a===1?"":"s"} that the script did not show. Show each image block of result.output with image(block).`});const h=await Ie(X(M),p.maxOutputTokens??Ee),A=X(await ke(h.items)),N=((performance.now()-c)/1e3).toFixed(1),Q=`${y.ok?"Script completed":"Script failed"}
21
- Wall time ${N} seconds
20
+ [Could not save the full output: ${a.error}]`,{items:[{type:"text",text:c},...e.filter(f=>f.type==="image")],..."path"in a?{fullOutputPath:a.path}:{}}}o(Ie,"truncateOutput");function Ne(e,t){const{result:n}=t;if(e.outputSchema&&n.structuredContent!==void 0)return n.structuredContent;const r=X(n);if(t.isError)throw new Error(r||`Tool "${e.name}" failed`);return r}o(Ne,"toScriptValue");async function Ge(e,t,n,r,i,s={}){const u=performance.now(),{code:l,options:p}=re(t.code),d=[];let c,a=0;const f=o(m=>{a+=m},"addGeneratedImages"),y=o(m=>{c=c?ce(c,m):m},"addModelUsage"),h=o(()=>({calls:d.map(m=>({...m}))}),"snapshot"),E=o(()=>r?.({content:[],details:h()}),"publish");E();const x=i?pe(i.tools):[],T=s.getToolGuidelines?.(),O=new Map(x.map(m=>[m.name,oe(de(m,T?.get(m.name)))])),M=x.map(m=>({name:m.name,description:O.get(m.name),execute:o(async(j,{signal:H})=>{const A={id:`${e}/?`,name:m.name,args:he(j),status:"running"};d.push(A),E();const Z=performance.now();if(!i)throw new Error("Tool calls need a session");const R=await i.executeTool(m.name,j,{signal:H});return A.id=R.toolCall.id,A.durationMs=performance.now()-Z,R.isError?(A.status=H.aborted?"cancelled":"error",A.error=D(X(R.result)||`Tool "${m.name}" failed`,Y)):A.status="ok",E(),Ne(m,R)},"execute")})),C=new te({tools:M,globals:[...Re(x,O,s),...s.models&&i?ve(i.modelRegistry,e,d,E,y,f):[]],timeoutMs:p.timeoutMs??Number.POSITIVE_INFINITY,memoryLimitBytes:ye,wasm:ne(ie()),workerUrl:se(),acquireWorker:o(()=>{if(v>=B)throw new Error(`Codemode worker limit reached (${B} workers are still running or shutting down). Retry after they exit.`);return v++,()=>{v--}},"acquireWorker")});let g;try{const m=i?Te(i.sessionManager.getBranch()):{};g=await C.execute(l,{signal:n,store:m})}finally{await C.close()}for(const m of d)m.status==="running"&&(m.status="cancelled");const I=[...g.output];if(g.ok){const{set:m,delete:j}=g.storeWrites;(Object.keys(m).length>0||j.length>0)&&s.appendEntry?.(J,{set:m,delete:j}),g.value!==void 0&&I.push({type:"text",text:Se(g.value)})}const $=Ae(I);g.ok||$.push({type:"text",text:`Script error:
21
+ ${Ce(g,d)}`}),a>0&&!$.some(m=>m.type==="image")&&$.push({type:"text",text:`Note: models.generateImages() returned ${a} image${a===1?"":"s"} that the script did not show. Show each image block of result.output with image(block).`});const k=await Ie(Q($),p.maxOutputTokens??Oe),b=Q(await _e(k.items)),S=((performance.now()-u)/1e3).toFixed(1),N=`${g.ok?"Script completed":"Script failed"}
22
+ Wall time ${S} seconds
22
23
  Output:
23
- `,U=$();return h.fullOutputPath&&(U.fullOutputPath=h.fullOutputPath),{content:[{type:"text",text:Q},...A],details:U,...u?{usage:u}:{},...y.ok?{}:{isError:!0}}}s(Fe,"executeCodemode");function K(e,t){const n=I(e),r=I(t),i=s(o=>o.includes("__")?o.slice(o.lastIndexOf("__")+2):void 0,"suffix");return e===t||n===r||i(e)===t||i(n)===r}s(K,"isNamespaceName");function Ne(e,t,n){const r=new ce,i=s(o=>({name:I(o),description:t.get(o)??""}),"entry");return[{name:"searchTools",spread:!0,execute:s(o=>{const[c,f]=o;if(typeof c!="string")throw new Error("searchTools() expects a query string");const p=f?.limit??le;if(typeof p!="number"||!Number.isInteger(p)||p<=0)throw new Error("searchTools() limit must be a positive integer");const m=f?.namespace;if(m!=null&&typeof m!="string")throw new Error("searchTools() namespace must be a string");const u=e.flatMap(a=>{const l=n.getToolNamespace?.(a.name);return m&&(!l||!K(l.name,m))?[]:[ue(a,l)]});return r.rank(c,u,p).map(a=>i(a.name))},"execute")},{name:"describeTool",spread:!0,execute:s(o=>{const[c]=o;if(typeof c!="string")throw new Error("describeTool() expects a tool name");const f=e.find(p=>p.name===c||I(p.name)===c);return f?t.get(f.name):void 0},"execute")},{name:"describeNamespace",spread:!0,execute:s(o=>{const[c]=o;if(typeof c!="string")throw new Error("describeNamespace() expects a namespace name");let f;const p=[];for(const m of e){const u=n.getToolNamespace?.(m.name);!u||!K(u.name,c)||(f??=u,p.push(I(m.name)))}if(f)return{name:f.name,...f.description?{description:f.description}:{},...f.instructions?{instructions:f.instructions}:{},tools:p}},"execute")}]}s(Ne,"createDiscoveryGlobals");function Re(e,t,n,r,i,o){const c=be(me);let f=0;const p=s(async(u,a,[l,g],$,T)=>{const E=`List the ${a} models you can use with models.getAvailableOfType("${a}").`;if(!w(l)||typeof l.provider!="string"||typeof l.id!="string"){const A=l==null?" models.getModelOfType() returns undefined for an unknown provider or id.":"";throw new Error(`${u}() expects ${L(a)} model as its first argument, got ${b(l)}.${A} ${E}`)}const{provider:C,id:S}=l,j=`${C}/${S}`,O=e.getModelOfType(a,C,S);if(!O){const A=[...Y].find(N=>N!==a&&e.getModelOfType(N,C,S)!==void 0);throw new Error(A?`"${j}" is ${L(A)} model, not ${L(a)} model. ${E}`:`Unknown ${a} model "${j}". ${E}`)}const y=$(g),x={id:`${t}/${u}/${++f}`,name:u,args:`${O.provider}/${O.id}`,status:"running"};n.push(x),r();const M=performance.now(),h=await c(()=>T(O,y));return x.durationMs=performance.now()-M,x.status=h.stopReason==="stop"?"ok":h.stopReason==="aborted"?"cancelled":"error",h.errorMessage&&(x.error=v(h.errorMessage,J)),h.usage&&(x.cost=h.usage.cost.total,i(h.usage)),r(),h},"runModelCall");return Object.entries({"models.getModelsOfType":s(u=>{const[a,l]=u;return e.getModelsOfType(P(a),V(l)).map(D)},"models.getModelsOfType"),"models.getAvailableOfType":s(async(u,{signal:a})=>{const[l,g]=u;return(await e.getAvailableOfType(P(l),V(g),{signal:a})).map(D)},"models.getAvailableOfType"),"models.getModelOfType":s(u=>{const[a,l,g]=u;if(typeof l!="string"||typeof g!="string")throw new Error(`models.getModelOfType(type, provider, id) expects three strings, got (${u.map(b).join(", ")}). The provider and the id are separate arguments, for example models.getModelOfType("classifier", "typesafe", "jev-latest").`);const $=e.getModelOfType(P(a),l,g);return $===void 0?void 0:D($)},"models.getModelOfType"),"models.classify":s((u,{signal:a})=>p("models.classify","classifier",u,$e,(l,g)=>e.classify(l,g,{signal:a})),"models.classify"),"models.generateImages":s((u,{signal:a})=>p("models.generateImages","image",u,we,async(l,g)=>{const $=await e.generateImages(l,g,{signal:a});return o($.output.filter(T=>T.type==="image").length),$}),"models.generateImages")}).map(([u,a])=>({name:u,spread:!0,execute:a}))}s(Re,"createModelGlobals");export{Fe as executeCodemode,Te as readCodemodeStore};
24
+ `,W=h();return k.fullOutputPath&&(W.fullOutputPath=k.fullOutputPath),{content:[{type:"text",text:N},...b],details:W,...c?{usage:c}:{},...g.ok?{}:{isError:!0}}}o(Ge,"executeCodemode");function z(e,t){const n=_(t);return[e.name,...e.aliases??[]].some(r=>r===t||_(r)===n)}o(z,"isNamespaceName");function Re(e,t,n){const r=new ue,i=o(s=>({name:_(s),description:t.get(s)??""}),"entry");return[{name:"searchTools",spread:!0,execute:o(s=>{const[u,l]=s;if(typeof u!="string")throw new Error("searchTools() expects a query string");const p=l?.limit??fe;if(typeof p!="number"||!Number.isInteger(p)||p<=0)throw new Error("searchTools() limit must be a positive integer");const d=l?.namespace;if(d!=null&&typeof d!="string")throw new Error("searchTools() namespace must be a string");const c=e.flatMap(a=>{const f=n.getToolNamespace?.(a.name);return d&&(!f||!z(f,d))?[]:[le(a,f)]});return r.rank(u,c,p).map(a=>i(a.name))},"execute")},{name:"describeTool",spread:!0,execute:o(s=>{const[u]=s;if(typeof u!="string")throw new Error("describeTool() expects a tool name");const l=e.find(p=>p.name===u||_(p.name)===u);return l?t.get(l.name):void 0},"execute")},{name:"describeNamespace",spread:!0,execute:o(s=>{const[u]=s;if(typeof u!="string")throw new Error("describeNamespace() expects a namespace name");let l;const p=[];for(const d of e){const c=n.getToolNamespace?.(d.name);!c||!z(c,u)||(l??=c,p.push(_(d.name)))}if(l)return{name:l.name,...l.description?{description:l.description}:{},...l.instructions?{instructions:l.instructions}:{},tools:p}},"execute")}]}o(Re,"createDiscoveryGlobals");function ve(e,t,n,r,i,s){const u=Ee(ge);let l=0;const p=o(async(c,a,[f,y],h,E)=>{const x=`List the ${a} models you can use with models.getAvailableOfType("${a}").`,T=f;if(typeof T?.provider!="string"||typeof T.id!="string"){const S=f==null?" models.getModelOfType() returns undefined for an unknown provider or id.":"";throw new Error(`${c}() expects ${L(a)} model as its first argument, got ${w(f)}.${S} ${x}`)}const O=T.provider,M=T.id,C=`${O}/${M}`,g=e.getModelOfType(a,O,M);if(!g){const S=[...V].find(N=>N!==a&&e.getModelOfType(N,O,M)!==void 0);throw new Error(S?`"${C}" is ${L(S)} model, not ${L(a)} model. ${x}`:`Unknown ${a} model "${C}". ${x}`)}const I=h(y),$={id:`${t}/${c}/${++l}`,name:c,args:`${g.provider}/${g.id}`,status:"running"};n.push($),r();const k=performance.now(),b=await u(()=>E(g,I));return $.durationMs=performance.now()-k,$.status=b.stopReason==="stop"?"ok":b.stopReason==="aborted"?"cancelled":"error",b.errorMessage&&($.error=D(b.errorMessage,Y)),b.usage&&($.cost=b.usage.cost.total,i(b.usage)),r(),b},"runModelCall");return Object.entries({"models.getModelsOfType":o(c=>{const[a,f]=c;return e.getModelsOfType(P(a),K(f)).map(q)},"models.getModelsOfType"),"models.getAvailableOfType":o(async(c,{signal:a})=>{const[f,y]=c;return(await e.getAvailableOfType(P(f),K(y),{signal:a})).map(q)},"models.getAvailableOfType"),"models.getModelOfType":o(c=>{const[a,f,y]=c;if(typeof f!="string"||typeof y!="string")throw new Error(`models.getModelOfType(type, provider, id) expects three strings, got (${c.map(w).join(", ")}). The provider and the id are separate arguments, for example models.getModelOfType("classifier", "typesafe", "jev-latest").`);const h=e.getModelOfType(P(a),f,y);return h===void 0?void 0:q(h)},"models.getModelOfType"),"models.classify":o((c,{signal:a})=>p("models.classify","classifier",c,$e,(f,y)=>e.classify(f,y,{signal:a})),"models.classify"),"models.generateImages":o((c,{signal:a})=>p("models.generateImages","image",c,be,async(f,y)=>{const h=await e.generateImages(f,y,{signal:a});return s(h.output.filter(E=>E.type==="image").length),h}),"models.generateImages")}).map(([c,a])=>({name:c,spread:!0,execute:a}))}o(ve,"createModelGlobals");export{Ge as executeCodemode,Te as readCodemodeStore};
@@ -1 +1 @@
1
- var l=Object.defineProperty;var t=(n,e)=>l(n,"name",{value:e,configurable:!0});import{createCodemodeToolDefinition as r}from"./tool.js";function i(n){return n.getSettings().codemode?.mode==="only"?"only":"on"}t(i,"readMode");function u(n){const e=n.getSettings().codemode?.inlineBudget;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}t(u,"readInlineBudget");function m(n={}){return e=>{e.registerTool({...r({appendEntry:t((o,d)=>e.appendEntry(o,d),"appendEntry"),models:n.models??!0,getToolNamespace:t(o=>e.getAllTools().find(d=>d.name===o)?.namespace,"getToolNamespace"),getToolGuidelines:t(()=>new Map(e.getAllTools().map(o=>[o.name,o.promptGuidelines??[]])),"getToolGuidelines"),getMode:t(()=>n.mode??i(e),"getMode"),getInlineBudget:t(()=>n.inlineBudget??u(e),"getInlineBudget")}),defaultActive:!1})}}t(m,"createCodemodeExtension");var s=m();export{m as createCodemodeExtension,s as default};
1
+ var r=Object.defineProperty;var o=(n,e)=>r(n,"name",{value:e,configurable:!0});import{SETTINGS_DEFAULTS as l}from"../../core/settings-defaults.js";import{createCodemodeToolDefinition as m}from"./tool.js";function i(n){return n.getSettings().codemode?.mode==="only"?"only":l.codemode.mode}o(i,"readMode");function u(n){const e=n.getSettings().codemode?.inlineBudget;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}o(u,"readInlineBudget");function a(n={}){return e=>{e.registerTool({...m({appendEntry:o((t,d)=>e.appendEntry(t,d),"appendEntry"),models:n.models??!0,getToolNamespace:o(t=>e.getAllTools().find(d=>d.name===t)?.namespace,"getToolNamespace"),getToolGuidelines:o(()=>new Map(e.getAllTools().map(t=>[t.name,t.promptGuidelines??[]])),"getToolGuidelines"),getMode:o(()=>n.mode??i(e),"getMode"),getInlineBudget:o(()=>n.inlineBudget??u(e),"getInlineBudget")}),defaultActive:!1})}}o(a,"createCodemodeExtension");var f=a();export{a as createCodemodeExtension,f as default};
@@ -1,8 +1,8 @@
1
- var I=Object.defineProperty;var d=(t,n)=>I(t,"name",{value:n,configurable:!0});import{Container as $,Spacer as w,Text as f}from"@earendil-works/pi-tui";import{getTextOutput as S,replaceTabs as h,str as H}from"../../core/tools/render-utils.js";import{fill as g,t as s}from"../../dal/i18n.js";import{keyHint as x}from"../../modes/interactive/components/keybinding-hints.js";import{VisualLinePreview as E}from"../../modes/interactive/components/visual-truncate.js";import{highlightCode as V}from"../../modes/interactive/theme/theme.js";const j=10,A=8,k=5,P=80,D=/^Script (completed|failed)\nWall time [\d.]+ seconds\nOutput:\n$/;function L(t,n){return`${t.fg("muted",g(s("\u2026\uFF08\u8FD8\u6709 {count} \u884C\uFF0C"),{count:n}))}${x("app.tools.expand",s("\u5C55\u5F00"))}${t.fg("muted",s("\uFF09"))}`}d(L,"expandHint");function W(t){return t===void 0?"":t<1e3?`${Math.round(t)}ms`:`${(t/1e3).toFixed(1)}s`}d(W,"formatDuration");function O(t){return`$${t>=.01?t.toFixed(2):t.toPrecision(2)}`}d(O,"formatCost");function y(t,n){switch(t.status){case"running":return n.fg("warning","\u2026");case"ok":return n.fg("success","\u2713");case"error":return n.fg("error","\u2717");case"cancelled":return n.fg("muted","\u2298")}}d(y,"statusIcon");function N(t,n,r){const i=!r&&t.args.length>P?`${t.args.slice(0,P-3)}...`:t.args,e=W(t.durationMs);let o=`${y(t,n)} ${n.fg("toolTitle",t.name)}`;return i&&(o+=` ${n.fg("muted",i)}`),e&&(o+=` ${n.fg("dim",e)}`),t.cost&&(o+=` ${n.fg("dim",O(t.cost))}`),r&&t.error&&(o+=`
1
+ var S=Object.defineProperty;var a=(t,n)=>S(t,"name",{value:n,configurable:!0});import{Container as w,Spacer as C,Text as l}from"@earendil-works/pi-tui";import{getTextOutput as H,replaceTabs as h,startToolTimer as V,str as j,toolTimerText as A}from"../../core/tools/render-utils.js";import{fill as m,t as d}from"../../dal/i18n.js";import{keyHint as x}from"../../modes/interactive/components/keybinding-hints.js";import{VisualLinePreview as E}from"../../modes/interactive/components/visual-truncate.js";import{highlightCode as k}from"../../modes/interactive/theme/theme.js";const D=10,W=8,y=5,T=80,N=/^Script (completed|failed)\nWall time [\d.]+ seconds\nOutput:\n$/;function P(t,n){return`${t.fg("muted",m(d("\u2026\uFF08\u8FD8\u6709 {count} \u884C\uFF0C"),{count:n}))}${x("app.tools.expand",d("\u5C55\u5F00"))}${t.fg("muted",d("\uFF09"))}`}a(P,"expandHint");function U(t){return t===void 0?"":t<1e3?`${Math.round(t)}ms`:`${(t/1e3).toFixed(1)}s`}a(U,"formatDuration");function L(t){return`$${t>=.01?t.toFixed(2):t.toPrecision(2)}`}a(L,"formatCost");function b(t,n){switch(t.status){case"running":return n.fg("warning","\u2026");case"ok":return n.fg("success","\u2713");case"error":return n.fg("error","\u2717");case"cancelled":return n.fg("muted","\u2298")}}a(b,"statusIcon");function v(t,n,r){const e=!r&&t.args.length>T?`${t.args.slice(0,T-3)}...`:t.args,s=U(t.durationMs);let o=`${b(t,n)} ${n.fg("toolTitle",t.name)}`;return e&&(o+=` ${n.fg("muted",e)}`),s&&(o+=` ${n.fg("dim",s)}`),t.cost&&(o+=` ${n.fg("dim",L(t.cost))}`),r&&t.error&&(o+=`
2
2
  ${n.fg("error",t.error.split(`
3
3
  `).join(`
4
- `))}`),o}d(N,"formatCall");const z={renderCall(t,n,r){const i=H(t?.code),e=n.fg("toolTitle",n.bold("codemode")),o=r.lastComponent??new $;if(o.clear(),i===null)return o.addChild(new f(`${e} ${n.fg("error",s("[\u53C2\u6570\u65E0\u6548]"))}`,0,0)),o;if(o.addChild(new f(e,0,0)),i){const l=V(h(i.replace(/\r/g,"").trimEnd()),"javascript").join(`
5
- `);o.addChild(r.expanded?new f(l,0,0):new E({text:l,maxVisualLines:j,keep:"start",formatHint:d(m=>L(n,m),"formatHint")}))}return o},renderResult(t,n,r,i){const e=i.lastComponent??new $;e.clear();const o=t.details?.calls??[];if(o.length>0){const p=n.expanded?o:o.slice(-A),u=p.map(c=>N(c,r,n.expanded));p.length<o.length&&u.unshift(`${r.fg("muted",g(s("\u2026\uFF08\u4E4B\u524D\u8FD8\u6709 {count} \u6B21\u8C03\u7528\uFF0C"),{count:o.length-p.length}))}${x("app.tools.expand",s("\u5C55\u5F00"))}${r.fg("muted",s("\uFF09"))}`);const a=o.filter(c=>c.cost);if(a.length>1){const c=a.reduce((T,_)=>T+(_.cost??0),0);u.push(r.fg("muted",g(s("\u6A21\u578B\u8C03\u7528\u8D39\u7528\uFF1A{cost}"),{cost:O(c)})))}e.addChild(new w(1)),e.addChild(new f(u.join(`
6
- `),0,0))}const[l,...m]=t.content,R=l?.type==="text"&&D.test(l.text),C=n.isPartial?"":S({...t,content:R?m:t.content},i.showImages).trim();if(C){const p=i.isError?"error":"toolOutput",u=h(C).split(`
7
- `).map(a=>r.fg(p,a)).join(`
8
- `);if(e.addChild(new w(1)),n.expanded)e.addChild(new f(u,0,0));else{e.addChild(new E({text:u,maxVisualLines:k,keep:"start",formatHint:d(c=>L(r,c),"formatHint")}));const a=t.details?.fullOutputPath;a&&e.addChild(new f(r.fg("muted",g(s("\u5B8C\u6574\u8F93\u51FA\uFF1A{path}"),{path:a})),0,0))}}return e}};export{z as codemodeRenderers};
4
+ `))}`),o}a(v,"formatCall");const K={renderCall(t,n,r){V(r);const e=j(t?.code),s=n.fg("toolTitle",n.bold("codemode")),o=r.lastComponent??new w;if(o.clear(),e===null)return o.addChild(new l(`${s} ${n.fg("error",d("[\u53C2\u6570\u65E0\u6548]"))}`,0,0)),o;if(o.addChild(new l(s,0,0)),e){const i=k(h(e.replace(/\r/g,"").trimEnd()),"javascript").join(`
5
+ `);o.addChild(r.expanded?new l(i,0,0):new E({text:i,maxVisualLines:D,keep:"start",formatHint:a(g=>P(n,g),"formatHint")}))}return o},renderResult(t,n,r,e){const s=A(e,n.isPartial),o=e.lastComponent??new w;o.clear();const i=t.details?.calls??[];if(i.length>0){const p=n.expanded?i:i.slice(-W),u=p.map(f=>v(f,r,n.expanded));p.length<i.length&&u.unshift(`${r.fg("muted",m(d("\u2026\uFF08\u4E4B\u524D\u8FD8\u6709 {count} \u6B21\u8C03\u7528\uFF0C"),{count:i.length-p.length}))}${x("app.tools.expand",d("\u5C55\u5F00"))}${r.fg("muted",d("\uFF09"))}`);const c=i.filter(f=>f.cost);if(c.length>1){const f=c.reduce((_,I)=>_+(I.cost??0),0);u.push(r.fg("muted",m(d("\u6A21\u578B\u8C03\u7528\u8D39\u7528\uFF1A{cost}"),{cost:L(f)})))}o.addChild(new C(1)),o.addChild(new l(u.join(`
6
+ `),0,0))}const[g,...O]=t.content,R=g?.type==="text"&&N.test(g.text),$=n.isPartial?"":H({...t,content:R?O:t.content},e.showImages).trim();if($){const p=e.isError?"error":"toolOutput",u=h($).split(`
7
+ `).map(c=>r.fg(p,c)).join(`
8
+ `);if(o.addChild(new C(1)),n.expanded)o.addChild(new l(u,0,0));else{o.addChild(new E({text:u,maxVisualLines:y,keep:"start",formatHint:a(f=>P(r,f),"formatHint")}));const c=t.details?.fullOutputPath;c&&o.addChild(new l(r.fg("muted",m(d("\u5B8C\u6574\u8F93\u51FA\uFF1A{path}"),{path:c})),0,0))}}return s&&(o.addChild(new C(1)),o.addChild(new l(r.fg("muted",s),0,0))),o}};export{K as codemodeRenderers};
@@ -1,7 +1,7 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import type { CodemodeTool } from "@earendil-works/pi-codemode";
3
3
  import { type Static, Type } from "typebox";
4
- import type { ToolDefinition, ToolInfo, ToolNamespace } from "../../core/extensions/types.ts";
4
+ import type { ToolDefinition, ToolNamespace } from "../../core/extensions/types.ts";
5
5
  import type { ModelRegistry } from "../../core/model-registry.ts";
6
6
  import type { CodemodeMode } from "../../core/settings-manager.ts";
7
7
  export declare const CODEMODE_TOOL_NAME = "codemode";
@@ -23,7 +23,6 @@ export declare const codemodeSchema: Type.TObject<{
23
23
  code: Type.TString;
24
24
  }>;
25
25
  export type CodemodeToolInput = Static<typeof codemodeSchema>;
26
- export declare function isCodemodeTool(tool: Pick<ToolInfo, "name" | "parameters">): boolean;
27
26
  export type CodemodeNestedCallStatus = "running" | "ok" | "error" | "cancelled";
28
27
  export interface CodemodeNestedCall {
29
28
  id: string;
@@ -43,7 +42,7 @@ export declare const codemodeToolSystemPromptContribution: {
43
42
  readonly guidelines: readonly ["Use codemode to batch independent tool calls (Promise.allSettled), chain them, or filter large output, instead of many separate calls."];
44
43
  };
45
44
  export declare const CODEMODE_DOCS_PATH: string;
46
- export declare const DEFAULT_CODEMODE_INLINE_BUDGET = 3000;
45
+ export declare const DEFAULT_CODEMODE_INLINE_BUDGET: 3000;
47
46
  export declare function toCodemodeDeclaration(tool: AgentTool<any>, guidelines?: readonly string[]): Omit<CodemodeTool, "execute">;
48
47
  export declare function getCodemodeCallableTools(tools: readonly AgentTool<any>[]): AgentTool<any>[];
49
48
  export interface CodemodeDescriptionOptions {
@@ -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
  }