@maxmo74/pi-coding-agent 1.5.2-max.15 → 1.7.0-max.17

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 (419) hide show
  1. package/CHANGELOG.md +188 -0
  2. package/LICENSE +1 -1
  3. package/README.md +1 -1
  4. package/dist/bundle/chunks/anthropic-messages-VOAE66ME.js +3 -0
  5. package/dist/bundle/chunks/azure-openai-responses-FWQRNMCY.js +2 -0
  6. package/dist/bundle/chunks/bedrock-converse-stream.js +6 -6
  7. package/dist/bundle/chunks/chunk-2BKJ4UF2.js +6 -0
  8. package/dist/bundle/chunks/{chunk-RKNK4Y6L.js → chunk-2HV66XRA.js} +1 -1
  9. package/dist/bundle/chunks/chunk-7TLS4DNZ.js +30 -0
  10. package/dist/bundle/chunks/{chunk-FMPAMX2W.js → chunk-AIIDHDL2.js} +1 -1
  11. package/dist/bundle/chunks/chunk-ARDROFM7.js +20 -0
  12. package/dist/bundle/chunks/{chunk-36QC74V4.js → chunk-D5E4JUBX.js} +1 -1
  13. package/dist/bundle/chunks/chunk-D5U74ZAG.js +2 -0
  14. package/dist/bundle/chunks/{chunk-BAC3QPNW.js → chunk-E3GEPN3H.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-4UNPP53I.js → chunk-G5K7SYL7.js} +2 -2
  16. package/dist/bundle/chunks/chunk-GBB3EUD7.js +16 -0
  17. package/dist/bundle/chunks/chunk-GMDZZCKH.js +2 -0
  18. package/dist/bundle/chunks/{chunk-AUUCDC7R.js → chunk-HFTJRRFR.js} +2 -2
  19. package/dist/bundle/chunks/chunk-INODY4DR.js +2 -0
  20. package/dist/bundle/chunks/{chunk-WL4TUXY7.js → chunk-IOF7AZCL.js} +1 -1
  21. package/dist/bundle/chunks/chunk-J35HXFD7.js +2 -0
  22. package/dist/bundle/chunks/{chunk-COKMCNCW.js → chunk-KPWXWGGJ.js} +1 -1
  23. package/dist/bundle/chunks/chunk-LWG2CUTI.js +31 -0
  24. package/dist/bundle/chunks/chunk-MDJ5LWZA.js +44 -0
  25. package/dist/bundle/chunks/{chunk-VKJQ6CME.js → chunk-O5MXS5TI.js} +1 -1
  26. package/dist/bundle/chunks/chunk-OVXT2WQH.js +2 -0
  27. package/dist/bundle/chunks/{chunk-M6TSYZBS.js → chunk-PADKDPJN.js} +128 -130
  28. package/dist/bundle/chunks/chunk-PST3NXKM.js +2 -0
  29. package/dist/bundle/chunks/chunk-S2GRKWHT.js +14 -0
  30. package/dist/bundle/chunks/{chunk-FF6XOTWB.js → chunk-V7D5E4XS.js} +17 -15
  31. package/dist/bundle/chunks/chunk-Z2XZSUHM.js +2 -0
  32. package/dist/bundle/chunks/{cli-2MK3TR7P.js → cli-OH5BEVHD.js} +1 -1
  33. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-Z73UPEZ7.js +2 -0
  34. package/dist/bundle/chunks/{easter-egg-3d-GEVPKQF6.js → easter-egg-3d-BOWYTYMI.js} +1 -1
  35. package/dist/bundle/chunks/{execute-L2EEDV3L.js → execute-UXTJZEKY.js} +3 -3
  36. package/dist/bundle/chunks/github-copilot.js +1 -1
  37. package/dist/bundle/chunks/google-generative-ai-VI7CGXA2.js +2 -0
  38. package/dist/bundle/chunks/google-vertex-UGCMSJWH.js +2 -0
  39. package/dist/bundle/chunks/{llama-cpp-classify-EJXCQRUQ.js → llama-cpp-classify-SKDW7RUG.js} +2 -2
  40. package/dist/bundle/chunks/mistral-conversations-F2GKIAZI.js +4 -0
  41. package/dist/bundle/chunks/openai-codex-responses-B54DADY4.js +2 -0
  42. package/dist/bundle/chunks/openai-completions-5UNXROMA.js +7 -0
  43. package/dist/bundle/chunks/{openai-decisions-F66BDLOM.js → openai-decisions-IN2F5D4R.js} +1 -1
  44. package/dist/bundle/chunks/openai-responses-2567WJBU.js +4 -0
  45. package/dist/bundle/chunks/openrouter-images-MPCL4RTO.js +2 -0
  46. package/dist/bundle/chunks/pi-decision-GZ2BG2JB.js +2 -0
  47. package/dist/bundle/chunks/pi-image-CXEQM6AW.js +2 -0
  48. package/dist/bundle/chunks/pi-messages-PDCTBGXV.js +2 -0
  49. package/dist/bundle/chunks/{runtime-J5ZSBGTX.js → runtime-JESTW74H.js} +1 -1
  50. package/dist/bundle/chunks/typesafe-system-one-6M47QHZX.js +2 -0
  51. package/dist/bundle/chunks/virtual-modules-QBVXFHBM.js +2 -0
  52. package/dist/bundle/cli-runtime.js +1 -1
  53. package/dist/bundle/index.js +1 -1
  54. package/dist/bundle/rpc-entry.js +1 -1
  55. package/dist/cli/agent-dir-arg.d.ts +20 -0
  56. package/dist/cli/agent-dir-arg.d.ts.map +1 -0
  57. package/dist/cli/agent-dir-arg.js +38 -0
  58. package/dist/cli/agent-dir-arg.js.map +1 -0
  59. package/dist/cli/args.d.ts +6 -0
  60. package/dist/cli/args.d.ts.map +1 -1
  61. package/dist/cli/args.js +49 -5
  62. package/dist/cli/args.js.map +1 -1
  63. package/dist/cli/config-selector.d.ts.map +1 -1
  64. package/dist/cli/config-selector.js +9 -6
  65. package/dist/cli/config-selector.js.map +1 -1
  66. package/dist/cli/list-models.d.ts.map +1 -1
  67. package/dist/cli/list-models.js +0 -5
  68. package/dist/cli/list-models.js.map +1 -1
  69. package/dist/cli/project-trust.d.ts.map +1 -1
  70. package/dist/cli/project-trust.js +6 -6
  71. package/dist/cli/project-trust.js.map +1 -1
  72. package/dist/cli/session-picker.d.ts.map +1 -1
  73. package/dist/cli/session-picker.js +9 -6
  74. package/dist/cli/session-picker.js.map +1 -1
  75. package/dist/cli/startup-ui.d.ts +3 -2
  76. package/dist/cli/startup-ui.d.ts.map +1 -1
  77. package/dist/cli/startup-ui.js +21 -23
  78. package/dist/cli/startup-ui.js.map +1 -1
  79. package/dist/config.d.ts +6 -1
  80. package/dist/config.d.ts.map +1 -1
  81. package/dist/config.js +16 -2
  82. package/dist/config.js.map +1 -1
  83. package/dist/core/agent-session-runtime.d.ts +11 -0
  84. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  85. package/dist/core/agent-session-runtime.js +19 -0
  86. package/dist/core/agent-session-runtime.js.map +1 -1
  87. package/dist/core/agent-session-services.d.ts.map +1 -1
  88. package/dist/core/agent-session-services.js +6 -0
  89. package/dist/core/agent-session-services.js.map +1 -1
  90. package/dist/core/agent-session.d.ts +6 -3
  91. package/dist/core/agent-session.d.ts.map +1 -1
  92. package/dist/core/agent-session.js +22 -13
  93. package/dist/core/agent-session.js.map +1 -1
  94. package/dist/core/auth-storage.d.ts.map +1 -1
  95. package/dist/core/auth-storage.js +7 -1
  96. package/dist/core/auth-storage.js.map +1 -1
  97. package/dist/core/bash-executor.d.ts +3 -1
  98. package/dist/core/bash-executor.d.ts.map +1 -1
  99. package/dist/core/bash-executor.js +24 -13
  100. package/dist/core/bash-executor.js.map +1 -1
  101. package/dist/core/client-identity.d.ts +2 -3
  102. package/dist/core/client-identity.d.ts.map +1 -1
  103. package/dist/core/client-identity.js +3 -4
  104. package/dist/core/client-identity.js.map +1 -1
  105. package/dist/core/compaction/compaction.d.ts.map +1 -1
  106. package/dist/core/compaction/compaction.js +3 -0
  107. package/dist/core/compaction/compaction.js.map +1 -1
  108. package/dist/core/exec.d.ts +1 -0
  109. package/dist/core/exec.d.ts.map +1 -1
  110. package/dist/core/exec.js +4 -1
  111. package/dist/core/exec.js.map +1 -1
  112. package/dist/core/export-html/ansi-to-html.d.ts +6 -1
  113. package/dist/core/export-html/ansi-to-html.d.ts.map +1 -1
  114. package/dist/core/export-html/ansi-to-html.js +57 -20
  115. package/dist/core/export-html/ansi-to-html.js.map +1 -1
  116. package/dist/core/export-html/template.js +1 -1
  117. package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
  118. package/dist/core/export-html/tool-renderer.js +2 -3
  119. package/dist/core/export-html/tool-renderer.js.map +1 -1
  120. package/dist/core/extensions/loader.d.ts.map +1 -1
  121. package/dist/core/extensions/loader.js +18 -1
  122. package/dist/core/extensions/loader.js.map +1 -1
  123. package/dist/core/extensions/runner.d.ts.map +1 -1
  124. package/dist/core/extensions/runner.js +7 -1
  125. package/dist/core/extensions/runner.js.map +1 -1
  126. package/dist/core/extensions/types.d.ts +14 -1
  127. package/dist/core/extensions/types.d.ts.map +1 -1
  128. package/dist/core/extensions/types.js.map +1 -1
  129. package/dist/core/messages.d.ts +4 -0
  130. package/dist/core/messages.d.ts.map +1 -1
  131. package/dist/core/messages.js +10 -2
  132. package/dist/core/messages.js.map +1 -1
  133. package/dist/core/model-config.d.ts +36 -0
  134. package/dist/core/model-config.d.ts.map +1 -1
  135. package/dist/core/model-resolver.d.ts +0 -8
  136. package/dist/core/model-resolver.d.ts.map +1 -1
  137. package/dist/core/model-resolver.js +7 -71
  138. package/dist/core/model-resolver.js.map +1 -1
  139. package/dist/core/model-runtime.d.ts.map +1 -1
  140. package/dist/core/model-runtime.js +6 -2
  141. package/dist/core/model-runtime.js.map +1 -1
  142. package/dist/core/package-manager.d.ts +16 -0
  143. package/dist/core/package-manager.d.ts.map +1 -1
  144. package/dist/core/package-manager.js +45 -2
  145. package/dist/core/package-manager.js.map +1 -1
  146. package/dist/core/pi-ai-schemas.d.ts +4 -0
  147. package/dist/core/pi-ai-schemas.d.ts.map +1 -1
  148. package/dist/core/project-trust.d.ts.map +1 -1
  149. package/dist/core/project-trust.js +1 -1
  150. package/dist/core/project-trust.js.map +1 -1
  151. package/dist/core/provider-composer.d.ts +1 -0
  152. package/dist/core/provider-composer.d.ts.map +1 -1
  153. package/dist/core/provider-composer.js +1 -0
  154. package/dist/core/provider-composer.js.map +1 -1
  155. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  156. package/dist/core/remote-catalog-provider.js +7 -0
  157. package/dist/core/remote-catalog-provider.js.map +1 -1
  158. package/dist/core/resolve-config-value.d.ts +2 -0
  159. package/dist/core/resolve-config-value.d.ts.map +1 -1
  160. package/dist/core/resolve-config-value.js +4 -0
  161. package/dist/core/resolve-config-value.js.map +1 -1
  162. package/dist/core/resource-loader.d.ts +5 -1
  163. package/dist/core/resource-loader.d.ts.map +1 -1
  164. package/dist/core/resource-loader.js +2 -0
  165. package/dist/core/resource-loader.js.map +1 -1
  166. package/dist/core/sdk.js +2 -2
  167. package/dist/core/sdk.js.map +1 -1
  168. package/dist/core/session-manager.d.ts.map +1 -1
  169. package/dist/core/session-manager.js +55 -42
  170. package/dist/core/session-manager.js.map +1 -1
  171. package/dist/core/session-ownership.js +15 -1
  172. package/dist/core/session-ownership.js.map +1 -1
  173. package/dist/core/settings-defaults.d.ts +6 -2
  174. package/dist/core/settings-defaults.d.ts.map +1 -1
  175. package/dist/core/settings-defaults.js +6 -2
  176. package/dist/core/settings-defaults.js.map +1 -1
  177. package/dist/core/settings-manager.d.ts +6 -6
  178. package/dist/core/settings-manager.d.ts.map +1 -1
  179. package/dist/core/settings-manager.js +23 -16
  180. package/dist/core/settings-manager.js.map +1 -1
  181. package/dist/core/settings-schema.d.ts +16 -3
  182. package/dist/core/settings-schema.d.ts.map +1 -1
  183. package/dist/core/settings-schema.js +23 -8
  184. package/dist/core/settings-schema.js.map +1 -1
  185. package/dist/core/tools/bash.d.ts +3 -0
  186. package/dist/core/tools/bash.d.ts.map +1 -1
  187. package/dist/core/tools/bash.js +24 -9
  188. package/dist/core/tools/bash.js.map +1 -1
  189. package/dist/core/tools/find.d.ts.map +1 -1
  190. package/dist/core/tools/find.js +27 -16
  191. package/dist/core/tools/find.js.map +1 -1
  192. package/dist/core/tools/grep.js +1 -1
  193. package/dist/core/tools/grep.js.map +1 -1
  194. package/dist/core/tools/output-accumulator.d.ts +16 -4
  195. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  196. package/dist/core/tools/output-accumulator.js +47 -38
  197. package/dist/core/tools/output-accumulator.js.map +1 -1
  198. package/dist/core/tools/read.d.ts +5 -0
  199. package/dist/core/tools/read.d.ts.map +1 -1
  200. package/dist/core/tools/read.js +10 -15
  201. package/dist/core/tools/read.js.map +1 -1
  202. package/dist/core/tools/renderers/bash.d.ts.map +1 -1
  203. package/dist/core/tools/renderers/bash.js +9 -3
  204. package/dist/core/tools/renderers/bash.js.map +1 -1
  205. package/dist/core/tools/renderers/read.d.ts.map +1 -1
  206. package/dist/core/tools/renderers/read.js +6 -2
  207. package/dist/core/tools/renderers/read.js.map +1 -1
  208. package/dist/core/tools/truncate.d.ts +1 -1
  209. package/dist/core/tools/truncate.d.ts.map +1 -1
  210. package/dist/core/tools/truncate.js +11 -5
  211. package/dist/core/tools/truncate.js.map +1 -1
  212. package/dist/core/usage-totals.d.ts.map +1 -1
  213. package/dist/core/usage-totals.js +3 -0
  214. package/dist/core/usage-totals.js.map +1 -1
  215. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  216. package/dist/extensions/codemode/execute.js +36 -5
  217. package/dist/extensions/codemode/execute.js.map +1 -1
  218. package/dist/extensions/llama/client.d.ts.map +1 -1
  219. package/dist/extensions/llama/client.js +3 -13
  220. package/dist/extensions/llama/client.js.map +1 -1
  221. package/dist/extensions/llama/provider.d.ts +1 -1
  222. package/dist/extensions/llama/provider.d.ts.map +1 -1
  223. package/dist/extensions/llama/provider.js +6 -4
  224. package/dist/extensions/llama/provider.js.map +1 -1
  225. package/dist/extensions/llama/ui.d.ts.map +1 -1
  226. package/dist/extensions/llama/ui.js +2 -1
  227. package/dist/extensions/llama/ui.js.map +1 -1
  228. package/dist/extensions/mcp/index.d.ts.map +1 -1
  229. package/dist/extensions/mcp/index.js +4 -7
  230. package/dist/extensions/mcp/index.js.map +1 -1
  231. package/dist/extensions/mcp/resources.d.ts.map +1 -1
  232. package/dist/extensions/mcp/resources.js +3 -3
  233. package/dist/extensions/mcp/resources.js.map +1 -1
  234. package/dist/extensions/mcp/tools.d.ts +1 -9
  235. package/dist/extensions/mcp/tools.d.ts.map +1 -1
  236. package/dist/extensions/mcp/tools.js +8 -124
  237. package/dist/extensions/mcp/tools.js.map +1 -1
  238. package/dist/main.d.ts +1 -1
  239. package/dist/main.d.ts.map +1 -1
  240. package/dist/main.js +57 -19
  241. package/dist/main.js.map +1 -1
  242. package/dist/modes/diagnostics-stderr.d.ts +4 -0
  243. package/dist/modes/diagnostics-stderr.d.ts.map +1 -0
  244. package/dist/modes/diagnostics-stderr.js +11 -0
  245. package/dist/modes/diagnostics-stderr.js.map +1 -0
  246. package/dist/modes/interactive/components/assistant-message.d.ts +2 -1
  247. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  248. package/dist/modes/interactive/components/assistant-message.js +9 -3
  249. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  250. package/dist/modes/interactive/components/bash-execution.d.ts +2 -1
  251. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  252. package/dist/modes/interactive/components/bash-execution.js +7 -4
  253. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  254. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  255. package/dist/modes/interactive/components/config-selector.js +6 -3
  256. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  257. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  258. package/dist/modes/interactive/components/custom-editor.js +13 -1
  259. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  260. package/dist/modes/interactive/components/extension-editor.d.ts +1 -1
  261. package/dist/modes/interactive/components/extension-editor.js +2 -2
  262. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  263. package/dist/modes/interactive/components/first-time-setup.d.ts +3 -5
  264. package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -1
  265. package/dist/modes/interactive/components/first-time-setup.js +15 -45
  266. package/dist/modes/interactive/components/first-time-setup.js.map +1 -1
  267. package/dist/modes/interactive/components/mermaid.d.ts.map +1 -1
  268. package/dist/modes/interactive/components/mermaid.js +13 -4
  269. package/dist/modes/interactive/components/mermaid.js.map +1 -1
  270. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  271. package/dist/modes/interactive/components/model-selector.js +5 -2
  272. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  273. package/dist/modes/interactive/components/oauth-selector.d.ts +14 -2
  274. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  275. package/dist/modes/interactive/components/oauth-selector.js +17 -12
  276. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  277. package/dist/modes/interactive/components/radius-login-selector.d.ts.map +1 -1
  278. package/dist/modes/interactive/components/radius-login-selector.js +2 -1
  279. package/dist/modes/interactive/components/radius-login-selector.js.map +1 -1
  280. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  281. package/dist/modes/interactive/components/scoped-models-selector.js +9 -1
  282. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  283. package/dist/modes/interactive/components/session-selector.d.ts +8 -1
  284. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  285. package/dist/modes/interactive/components/session-selector.js +44 -12
  286. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  287. package/dist/modes/interactive/components/settings-selector.d.ts +3 -5
  288. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  289. package/dist/modes/interactive/components/settings-selector.js +57 -46
  290. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  291. package/dist/modes/interactive/components/settings-submenu.d.ts +1 -1
  292. package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -1
  293. package/dist/modes/interactive/components/settings-submenu.js +8 -4
  294. package/dist/modes/interactive/components/settings-submenu.js.map +1 -1
  295. package/dist/modes/interactive/components/themed-text.d.ts +1 -1
  296. package/dist/modes/interactive/components/themed-text.d.ts.map +1 -1
  297. package/dist/modes/interactive/components/themed-text.js.map +1 -1
  298. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  299. package/dist/modes/interactive/components/thinking-selector.js +5 -1
  300. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  301. package/dist/modes/interactive/components/tool-execution.d.ts +1 -1
  302. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  303. package/dist/modes/interactive/components/tool-execution.js +3 -1
  304. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  305. package/dist/modes/interactive/components/user-message.d.ts +2 -1
  306. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  307. package/dist/modes/interactive/components/user-message.js +9 -3
  308. package/dist/modes/interactive/components/user-message.js.map +1 -1
  309. package/dist/modes/interactive/components/visual-truncate.d.ts +2 -2
  310. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
  311. package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
  312. package/dist/modes/interactive/external-editor.d.ts.map +1 -1
  313. package/dist/modes/interactive/external-editor.js +13 -3
  314. package/dist/modes/interactive/external-editor.js.map +1 -1
  315. package/dist/modes/interactive/interactive-mode.d.ts +19 -2
  316. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  317. package/dist/modes/interactive/interactive-mode.js +176 -111
  318. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  319. package/dist/modes/interactive/program-resume-reporter.d.ts +32 -0
  320. package/dist/modes/interactive/program-resume-reporter.d.ts.map +1 -0
  321. package/dist/modes/interactive/program-resume-reporter.js +56 -0
  322. package/dist/modes/interactive/program-resume-reporter.js.map +1 -0
  323. package/dist/modes/interactive/program-status-reporter.d.ts +2 -0
  324. package/dist/modes/interactive/program-status-reporter.d.ts.map +1 -1
  325. package/dist/modes/interactive/program-status-reporter.js +4 -0
  326. package/dist/modes/interactive/program-status-reporter.js.map +1 -1
  327. package/dist/modes/interactive/session-share.d.ts.map +1 -1
  328. package/dist/modes/interactive/session-share.js +11 -1
  329. package/dist/modes/interactive/session-share.js.map +1 -1
  330. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  331. package/dist/modes/interactive/theme/theme.js +1 -0
  332. package/dist/modes/interactive/theme/theme.js.map +1 -1
  333. package/dist/modes/print-mode.d.ts.map +1 -1
  334. package/dist/modes/print-mode.js +17 -17
  335. package/dist/modes/print-mode.js.map +1 -1
  336. package/dist/modes/rpc/jsonl.d.ts.map +1 -1
  337. package/dist/modes/rpc/jsonl.js +13 -13
  338. package/dist/modes/rpc/jsonl.js.map +1 -1
  339. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  340. package/dist/modes/rpc/rpc-mode.js +19 -27
  341. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  342. package/dist/package-manager-cli.d.ts.map +1 -1
  343. package/dist/package-manager-cli.js +24 -2
  344. package/dist/package-manager-cli.js.map +1 -1
  345. package/dist/utils/changelog.d.ts.map +1 -1
  346. package/dist/utils/changelog.js +3 -2
  347. package/dist/utils/changelog.js.map +1 -1
  348. package/dist/utils/clipboard.js +1 -1
  349. package/dist/utils/clipboard.js.map +1 -1
  350. package/dist/utils/flush-stdout.d.ts +8 -0
  351. package/dist/utils/flush-stdout.d.ts.map +1 -0
  352. package/dist/utils/flush-stdout.js +23 -0
  353. package/dist/utils/flush-stdout.js.map +1 -0
  354. package/dist/utils/output-files.d.ts +20 -4
  355. package/dist/utils/output-files.d.ts.map +1 -1
  356. package/dist/utils/output-files.js +37 -2
  357. package/dist/utils/output-files.js.map +1 -1
  358. package/dist/utils/shell.d.ts +2 -1
  359. package/dist/utils/shell.d.ts.map +1 -1
  360. package/dist/utils/shell.js +56 -7
  361. package/dist/utils/shell.js.map +1 -1
  362. package/dist/utils/tools-manager.d.ts +1 -0
  363. package/dist/utils/tools-manager.d.ts.map +1 -1
  364. package/dist/utils/tools-manager.js +9 -8
  365. package/dist/utils/tools-manager.js.map +1 -1
  366. package/docs/cli.md +3 -1
  367. package/docs/codemode.md +16 -5
  368. package/docs/environment-variables.md +4 -4
  369. package/docs/extensions.md +18 -8
  370. package/docs/llama-cpp.md +3 -3
  371. package/docs/message-types.md +1 -0
  372. package/docs/models-configuration.md +18 -6
  373. package/docs/models.md +34 -14
  374. package/docs/nvidia-rtx-llama-cpp.md +5 -5
  375. package/docs/providers.md +7 -5
  376. package/docs/rpc-commands.md +2 -2
  377. package/docs/settings.md +5 -3
  378. package/docs/shell-aliases.md +1 -1
  379. package/docs/terminal-setup.md +53 -0
  380. package/docs/tui.md +2 -0
  381. package/docs/windows.md +2 -1
  382. package/examples/extensions/gondolin/index.ts +4 -7
  383. package/examples/extensions/subagent/index.ts +3 -2
  384. package/examples/rpc-extension-ui.ts +8 -7
  385. package/package.json +10 -10
  386. package/schemas/models.schema.json +22 -9
  387. package/schemas/settings.schema.json +30 -10
  388. package/dist/bundle/chunks/anthropic-messages-CA3HHOL3.js +0 -6
  389. package/dist/bundle/chunks/azure-openai-responses-76TWS6DT.js +0 -2
  390. package/dist/bundle/chunks/chunk-4KSTFUIK.js +0 -19
  391. package/dist/bundle/chunks/chunk-CF5GWZHW.js +0 -31
  392. package/dist/bundle/chunks/chunk-GFUN2N5K.js +0 -2
  393. package/dist/bundle/chunks/chunk-IQUU5XIT.js +0 -2
  394. package/dist/bundle/chunks/chunk-PMRZO46Y.js +0 -2
  395. package/dist/bundle/chunks/chunk-QN4TOIZN.js +0 -16
  396. package/dist/bundle/chunks/chunk-V7SLUK6A.js +0 -44
  397. package/dist/bundle/chunks/chunk-Y55SJART.js +0 -13
  398. package/dist/bundle/chunks/chunk-YTPJCXUB.js +0 -30
  399. package/dist/bundle/chunks/chunk-ZBIZYD6W.js +0 -2
  400. package/dist/bundle/chunks/chunk-ZGYS4UTC.js +0 -2
  401. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-U4J7D646.js +0 -2
  402. package/dist/bundle/chunks/google-generative-ai-D5B6W47J.js +0 -2
  403. package/dist/bundle/chunks/google-vertex-U4H5YDEW.js +0 -2
  404. package/dist/bundle/chunks/mistral-conversations-S277EKLB.js +0 -5
  405. package/dist/bundle/chunks/openai-codex-responses-TEQRB65N.js +0 -10
  406. package/dist/bundle/chunks/openai-completions-HRZOSLBO.js +0 -7
  407. package/dist/bundle/chunks/openai-responses-BAKFWTGE.js +0 -4
  408. package/dist/bundle/chunks/openrouter-images-VXF5TVIK.js +0 -2
  409. package/dist/bundle/chunks/pi-messages-UBJKNDRN.js +0 -8
  410. package/dist/bundle/chunks/typesafe-system-one-56TEMIHL.js +0 -2
  411. package/dist/bundle/chunks/virtual-modules-MRQHQVIQ.js +0 -2
  412. package/dist/core/telemetry.d.ts +0 -3
  413. package/dist/core/telemetry.d.ts.map +0 -1
  414. package/dist/core/telemetry.js +0 -9
  415. package/dist/core/telemetry.js.map +0 -1
  416. package/dist/utils/deprecation.d.ts +0 -4
  417. package/dist/utils/deprecation.d.ts.map +0 -1
  418. package/dist/utils/deprecation.js +0 -13
  419. package/dist/utils/deprecation.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"resources.js","sourceRoot":"","sources":["../../../src/extensions/mcp/resources.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,EAIN,eAAe,GAKf,MAAM,wBAAwB,CAAC;AAGhC,OAAO,EACN,gCAAgC,EAChC,uBAAuB,EACvB,sBAAsB,GACtB,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EAAuB,cAAc,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjG,OAAO,EAAE,gCAAgC,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,CAAC;AAa7F,0EAA0E;AAC1E,SAAS,gBAAgB,CAAC,IAA+D;IACxF,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,IAAI,IAAI,CAAC,WAAW,IAAI,EAAE,CAAC;IAC/C,OAAO,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,gCAAgC,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,IAAI,EAAE,CAAC,CAAC;AAC9F,CAAC;AAED,uFAAuF;AACvF,SAAS,MAAM,CAAgC,MAAc,EAAE,IAAO;IACrE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,IAA+B,CAAC;IAC1E,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,CAAC;AAC5B,CAAC;AAED,MAAM,cAAc,GAAG,CAAC,WAAmB,EAAE,EAAE,CAAC,CAAC,EAAE,I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AAM,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;YAC5D,MAAM,EAAE,OAAO,EAAE,cAAc,EAAE,GAAG,MAAM,eAAe,CACxD,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,YAAY,GAAG,YAAY,EAAE,CAAC,EACxF,cAAc,CACd,CAAC;YACF,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,QAAQ,EAAE,GAAG,IAAI,EAAE,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC;YAC7E,OAAO;gBACN,OAAO;gBACP,OAAO,EAAE;oBACR,MAAM,EAAE,MAAM,CAAC,IAAI;oBACnB,IAAI,EAAE,sBAAsB;oBAC5B,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;iBAC7C;gBACD,iBAAiB,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,IAAI,EAAE,GAAG,EAAE,QAAQ,EAA0B;aACjF,CAAC;QACH,CAAC;KACD,CAAC;IAEF,OAAO,CAAC,aAAa,EAAE,aAAa,EAAE,YAAY,CAAC,CAAC;AACrD,CAAC","sourcesContent":["/**\n * MCP resources, through the tools Codex and opencode use: `list_mcp_resources`,\n * `list_mcp_resource_templates`, and `read_mcp_resource`. They take a `server` argument and cover\n * every connected server with resources, so models trained on those tools use them unchanged.\n *\n * Listings are JSON, as in Codex: `{ server?, resources: [{ server, ...resource }], nextCursor? }`.\n * With a `server`, one page is listed and `cursor` continues it; without, every page of every server.\n * MCP App resources (`ui://` URIs and `profile=mcp-app` HTML) are left out, since they are user\n * interfaces for hosts that render them, and so are icons. Read resources become text and images for\n * the model; binary resources are saved to temp files. Scripts get the JSON payloads.\n */\n\nimport type { ImageContent, JsonValue, TextContent } from \"@earendil-works/pi-ai\";\nimport {\n\ttype ContentBlock,\n\ttype ListResourcesResult,\n\ttype ListResourceTemplatesResult,\n\tlimitMcpContent,\n\ttype McpRequestOptions,\n\ttype ReadResourceResult,\n\ttype Resource,\n\ttype ResourceTemplate,\n} from \"@earendil-works/pi-mcp\";\nimport type { TSchema } from \"typebox\";\nimport type { ToolAnnotations, ToolDefinition } from \"../../core/extensions/types.ts\";\nimport {\n\tLIST_MCP_RESOURCE_TEMPLATES_TOOL,\n\tLIST_MCP_RESOURCES_TOOL,\n\tREAD_MCP_RESOURCE_TOOL,\n} from \"../../core/mcp-servers.ts\";\nimport type { McpExposure } from \"./config.ts\";\nimport { type McpToolDetails, saveToTempFile, toModelContent, toToolExposure } from \"./tools.ts\";\n\nexport { LIST_MCP_RESOURCE_TEMPLATES_TOOL, LIST_MCP_RESOURCES_TOOL, READ_MCP_RESOURCE_TOOL };\n\n/** A connected server that offers resources. */\nexport interface McpResourceServer {\n\tname: string;\n\ttimeoutMs: number;\n\tresourcesPage(cursor: string | undefined, options: McpRequestOptions): Promise<ListResourcesResult>;\n\tresourceTemplatesPage(cursor: string | undefined, options: McpRequestOptions): Promise<ListResourceTemplatesResult>;\n\tallResources(options: McpRequestOptions): Promise<Resource[]>;\n\tallResourceTemplates(options: McpRequestOptions): Promise<ResourceTemplate[]>;\n\treadResource(uri: string, options: McpRequestOptions): Promise<ReadResourceResult>;\n}\n\n/** MCP App user interfaces, which only hosts that render them can use. */\nfunction isMcpAppResource(item: { uri?: string; uriTemplate?: string; mimeType?: string }): boolean {\n\tconst uri = item.uri ?? item.uriTemplate ?? \"\";\n\treturn uri.startsWith(\"ui://\") || /;\\s*profile\\s*=\\s*\"?mcp-app\"?/i.test(item.mimeType ?? \"\");\n}\n\n/** A listed resource or template without `_meta` and icons, tagged with its server. */\nfunction listed<T extends { _meta?: unknown }>(server: string, item: T): Record<string, unknown> {\n\tconst { _meta, icons: _icons, ...rest } = item as T & { icons?: unknown };\n\treturn { server, ...rest };\n}\n\nconst stringProperty = (description: string) => ({ type: \"string\", description });\nconst SERVER_FILTER = stringProperty(\"MCP server name. Omit to list every server with resources.\");\nconst CURSOR = stringProperty(\"Opaque cursor from a previous call with the same server; omit for the first page.\");\nconst LIST_PARAMETERS = {\n\ttype: \"object\",\n\tproperties: { server: SERVER_FILTER, cursor: CURSOR },\n\tadditionalProperties: false,\n};\nconst READ_PARAMETERS = {\n\ttype: \"object\",\n\tproperties: {\n\t\tserver: stringProperty(\n\t\t\t\"MCP server name exactly as configured. Must match the 'server' field returned by list_mcp_resources.\",\n\t\t),\n\t\turi: stringProperty(\"Resource URI to read. Must be one of the URIs returned by list_mcp_resources.\"),\n\t},\n\trequired: [\"server\", \"uri\"],\n\tadditionalProperties: false,\n};\n\nconst optionalString = { type: \"string\" };\nconst LISTING_ERRORS = {\n\ttype: \"array\",\n\tdescription: \"Servers that could not be listed\",\n\titems: {\n\t\ttype: \"object\",\n\t\tproperties: { server: { type: \"string\" }, error: { type: \"string\" } },\n\t\trequired: [\"server\", \"error\"],\n\t},\n};\nconst LIST_OUTPUT_SCHEMA = {\n\ttype: \"object\",\n\tproperties: {\n\t\tserver: optionalString,\n\t\tresources: {\n\t\t\ttype: \"array\",\n\t\t\titems: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tserver: { type: \"string\" },\n\t\t\t\t\turi: { type: \"string\" },\n\t\t\t\t\tname: { type: \"string\" },\n\t\t\t\t\ttitle: optionalString,\n\t\t\t\t\tdescription: optionalString,\n\t\t\t\t\tmimeType: optionalString,\n\t\t\t\t\tsize: { type: \"number\" },\n\t\t\t\t},\n\t\t\t\trequired: [\"server\", \"uri\", \"name\"],\n\t\t\t},\n\t\t},\n\t\tnextCursor: optionalString,\n\t\terrors: LISTING_ERRORS,\n\t},\n\trequired: [\"resources\"],\n};\nconst LIST_TEMPLATES_OUTPUT_SCHEMA = {\n\ttype: \"object\",\n\tproperties: {\n\t\tserver: optionalString,\n\t\tresourceTemplates: {\n\t\t\ttype: \"array\",\n\t\t\titems: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tserver: { type: \"string\" },\n\t\t\t\t\turiTemplate: { type: \"string\", description: \"RFC 6570 URI template\" },\n\t\t\t\t\tname: { type: \"string\" },\n\t\t\t\t\ttitle: optionalString,\n\t\t\t\t\tdescription: optionalString,\n\t\t\t\t\tmimeType: optionalString,\n\t\t\t\t},\n\t\t\t\trequired: [\"server\", \"uriTemplate\", \"name\"],\n\t\t\t},\n\t\t},\n\t\tnextCursor: optionalString,\n\t\terrors: LISTING_ERRORS,\n\t},\n\trequired: [\"resourceTemplates\"],\n};\nconst READ_OUTPUT_SCHEMA = {\n\ttype: \"object\",\n\tproperties: {\n\t\tserver: { type: \"string\" },\n\t\turi: { type: \"string\" },\n\t\tcontents: {\n\t\t\ttype: \"array\",\n\t\t\titems: {\n\t\t\t\tanyOf: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: { uri: { type: \"string\" }, mimeType: optionalString, text: { type: \"string\" } },\n\t\t\t\t\t\trequired: [\"uri\", \"text\"],\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\turi: { type: \"string\" },\n\t\t\t\t\t\t\tmimeType: optionalString,\n\t\t\t\t\t\t\tblob: { type: \"string\", description: \"base64\" },\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"uri\", \"blob\"],\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t},\n\t},\n\trequired: [\"server\", \"uri\", \"contents\"],\n};\n\nfunction stringArgument(params: unknown, key: string): string | undefined {\n\tconst value = (params as Record<string, unknown> | undefined)?.[key];\n\tif (value === undefined || value === null) return undefined;\n\tif (typeof value !== \"string\") throw new Error(`${key} must be a string`);\n\treturn value.trim() || undefined;\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nasync function jsonResult(\n\ttool: string,\n\tserver: string | undefined,\n\tpayload: Record<string, unknown>,\n): Promise<{ content: (TextContent | ImageContent)[]; details: McpToolDetails; structuredContent: JsonValue }> {\n\tconst { content, fullOutputPath } = await limitMcpContent(\n\t\t[{ type: \"text\", text: JSON.stringify(payload) }],\n\t\tsaveToTempFile,\n\t);\n\treturn {\n\t\tcontent,\n\t\tdetails: { server: server ?? \"\", tool, ...(fullOutputPath ? { fullOutputPath } : {}) },\n\t\tstructuredContent: payload as unknown as JsonValue,\n\t};\n}\n\n/**\n * The three resource tools. `servers` returns the servers whose resources they reach, at call time.\n */\nexport function createMcpResourceToolDefinitions(options: {\n\texposure: McpExposure;\n\tservers: () => readonly McpResourceServer[];\n}): ToolDefinition<TSchema, McpToolDetails>[] {\n\tconst readOnly: ToolAnnotations = { readOnlyHint: true };\n\n\tconst findServer = (name: string): McpResourceServer => {\n\t\tconst servers = options.servers();\n\t\tconst server = servers.find((candidate) => candidate.name === name);\n\t\tif (server) return server;\n\t\tconst available = servers.map((candidate) => candidate.name).join(\", \");\n\t\tthrow new Error(\n\t\t\t`MCP server \"${name}\" has no resources${available ? `. Servers with resources: ${available}` : \"\"}`,\n\t\t);\n\t};\n\n\t/** One page of one server, or every page of every server. */\n\tconst list = async <T extends { _meta?: unknown }>(\n\t\tparams: unknown,\n\t\tsignal: AbortSignal | undefined,\n\t\tkey: \"resources\" | \"resourceTemplates\",\n\t\tpage: (\n\t\t\tserver: McpResourceServer,\n\t\t\tcursor: string | undefined,\n\t\t\toptions: McpRequestOptions,\n\t\t) => Promise<{\n\t\t\titems: T[];\n\t\t\tnextCursor?: string;\n\t\t}>,\n\t\tall: (server: McpResourceServer, options: McpRequestOptions) => Promise<T[]>,\n\t): Promise<Record<string, unknown>> => {\n\t\tconst serverName = stringArgument(params, \"server\");\n\t\tconst cursor = stringArgument(params, \"cursor\");\n\t\tconst visible = (item: T) => !isMcpAppResource(item as { uri?: string; uriTemplate?: string; mimeType?: string });\n\t\tif (serverName) {\n\t\t\tconst server = findServer(serverName);\n\t\t\tconst result = await page(server, cursor, { signal, timeoutMs: server.timeoutMs });\n\t\t\treturn {\n\t\t\t\tserver: server.name,\n\t\t\t\t[key]: result.items.filter(visible).map((item) => listed(server.name, item)),\n\t\t\t\t...(result.nextCursor === undefined ? {} : { nextCursor: result.nextCursor }),\n\t\t\t};\n\t\t}\n\t\tif (cursor) throw new Error(\"cursor can only be used when a server is specified\");\n\t\tconst servers = [...options.servers()].sort((a, b) => a.name.localeCompare(b.name));\n\t\tconst results = await Promise.allSettled(\n\t\t\tservers.map((server) => all(server, { signal, timeoutMs: server.timeoutMs })),\n\t\t);\n\t\tconst items: Record<string, unknown>[] = [];\n\t\tconst errors: { server: string; error: string }[] = [];\n\t\tresults.forEach((result, index) => {\n\t\t\tconst server = servers[index].name;\n\t\t\tif (result.status === \"fulfilled\")\n\t\t\t\titems.push(...result.value.filter(visible).map((item) => listed(server, item)));\n\t\t\telse errors.push({ server, error: errorMessage(result.reason) });\n\t\t});\n\t\treturn { [key]: items, ...(errors.length > 0 ? { errors } : {}) };\n\t};\n\n\tconst listResources: ToolDefinition<TSchema, McpToolDetails> = {\n\t\tname: LIST_MCP_RESOURCES_TOOL,\n\t\tlabel: LIST_MCP_RESOURCES_TOOL,\n\t\tdescription:\n\t\t\t\"Lists resources provided by MCP servers. Resources allow servers to share data that provides context to language models, such as files, database schemas, or application-specific information. Prefer resources over web search when possible.\",\n\t\tparameters: LIST_PARAMETERS as unknown as TSchema,\n\t\toutputSchema: LIST_OUTPUT_SCHEMA as unknown as TSchema,\n\t\texposure: toToolExposure(options.exposure),\n\t\tannotations: readOnly,\n\t\tasync execute(_toolCallId, params, signal) {\n\t\t\tconst payload = await list(\n\t\t\t\tparams,\n\t\t\t\tsignal,\n\t\t\t\t\"resources\",\n\t\t\t\tasync (server, cursor, requestOptions) => {\n\t\t\t\t\tconst result = await server.resourcesPage(cursor, requestOptions);\n\t\t\t\t\treturn { items: result.resources, nextCursor: result.nextCursor };\n\t\t\t\t},\n\t\t\t\t(server, requestOptions) => server.allResources(requestOptions),\n\t\t\t);\n\t\t\treturn jsonResult(LIST_MCP_RESOURCES_TOOL, stringArgument(params, \"server\"), payload);\n\t\t},\n\t};\n\n\tconst listTemplates: ToolDefinition<TSchema, McpToolDetails> = {\n\t\tname: LIST_MCP_RESOURCE_TEMPLATES_TOOL,\n\t\tlabel: LIST_MCP_RESOURCE_TEMPLATES_TOOL,\n\t\tdescription:\n\t\t\t\"Lists resource templates provided by MCP servers. Parameterized resource templates allow servers to share data that takes parameters and provides context to language models, such as files, database schemas, or application-specific information. Prefer resource templates over web search when possible.\",\n\t\tparameters: LIST_PARAMETERS as unknown as TSchema,\n\t\toutputSchema: LIST_TEMPLATES_OUTPUT_SCHEMA as unknown as TSchema,\n\t\texposure: toToolExposure(options.exposure),\n\t\tannotations: readOnly,\n\t\tasync execute(_toolCallId, params, signal) {\n\t\t\tconst payload = await list(\n\t\t\t\tparams,\n\t\t\t\tsignal,\n\t\t\t\t\"resourceTemplates\",\n\t\t\t\tasync (server, cursor, requestOptions) => {\n\t\t\t\t\tconst result = await server.resourceTemplatesPage(cursor, requestOptions);\n\t\t\t\t\treturn { items: result.resourceTemplates, nextCursor: result.nextCursor };\n\t\t\t\t},\n\t\t\t\t(server, requestOptions) => server.allResourceTemplates(requestOptions),\n\t\t\t);\n\t\t\treturn jsonResult(LIST_MCP_RESOURCE_TEMPLATES_TOOL, stringArgument(params, \"server\"), payload);\n\t\t},\n\t};\n\n\tconst readResource: ToolDefinition<TSchema, McpToolDetails> = {\n\t\tname: READ_MCP_RESOURCE_TOOL,\n\t\tlabel: READ_MCP_RESOURCE_TOOL,\n\t\tdescription: \"Read a specific resource from an MCP server given the server name and resource URI.\",\n\t\tparameters: READ_PARAMETERS as unknown as TSchema,\n\t\toutputSchema: READ_OUTPUT_SCHEMA as unknown as TSchema,\n\t\texposure: toToolExposure(options.exposure),\n\t\tannotations: readOnly,\n\t\tasync execute(_toolCallId, params, signal) {\n\t\t\tconst serverName = stringArgument(params, \"server\");\n\t\t\tconst uri = stringArgument(params, \"uri\");\n\t\t\tif (!serverName) throw new Error(\"server must be provided\");\n\t\t\tif (!uri) throw new Error(\"uri must be provided\");\n\t\t\tconst server = findServer(serverName);\n\t\t\tconst result = await server.readResource(uri, { signal, timeoutMs: server.timeoutMs });\n\t\t\t// Several contents (for example a directory) are labeled with their URIs.\n\t\t\tconst blocks: ContentBlock[] = result.contents.flatMap((contents) => [\n\t\t\t\t...(result.contents.length > 1 ? [{ type: \"text\" as const, text: `${contents.uri}:` }] : []),\n\t\t\t\t{ type: \"resource\" as const, resource: contents },\n\t\t\t]);\n\t\t\tconst converted = await toModelContent(server.name, blocks);\n\t\t\tconst { content, fullOutputPath } = await limitMcpContent(\n\t\t\t\tconverted.length > 0 ? converted : [{ type: \"text\", text: `Resource ${uri} is empty.` }],\n\t\t\t\tsaveToTempFile,\n\t\t\t);\n\t\t\tconst contents = result.contents.map(({ _meta: _ignored, ...rest }) => rest);\n\t\t\treturn {\n\t\t\t\tcontent,\n\t\t\t\tdetails: {\n\t\t\t\t\tserver: server.name,\n\t\t\t\t\ttool: READ_MCP_RESOURCE_TOOL,\n\t\t\t\t\t...(fullOutputPath ? { fullOutputPath } : {}),\n\t\t\t\t},\n\t\t\t\tstructuredContent: { server: server.name, uri, contents } as unknown as JsonValue,\n\t\t\t};\n\t\t},\n\t};\n\n\treturn [listResources, listTemplates, readResource];\n}\n"]}
1
+ {"version":3,"file":"resources.js","sourceRoot":"","sources":["../../../src/extensions/mcp/resources.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,EAIN,eAAe,EAKf,iBAAiB,GACjB,MAAM,wBAAwB,CAAC;AAGhC,OAAO,EACN,gCAAgC,EAChC,uBAAuB,EACvB,sBAAsB,GACtB,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EAAuB,cAAc,EAAE,cAAc,E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IAAI,EAAE,sBAAsB;oBAC5B,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;iBAC7C;gBACD,iBAAiB,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,IAAI,EAAE,GAAG,EAAE,QAAQ,EAA0B;aACjF,CAAC;QACH,CAAC;KACD,CAAC;IAEF,OAAO,CAAC,aAAa,EAAE,aAAa,EAAE,YAAY,CAAC,CAAC;AACrD,CAAC","sourcesContent":["/**\n * MCP resources, through the tools Codex and opencode use: `list_mcp_resources`,\n * `list_mcp_resource_templates`, and `read_mcp_resource`. They take a `server` argument and cover\n * every connected server with resources, so models trained on those tools use them unchanged.\n *\n * Listings are JSON, as in Codex: `{ server?, resources: [{ server, ...resource }], nextCursor? }`.\n * With a `server`, one page is listed and `cursor` continues it; without, every page of every server.\n * MCP App resources (`ui://` URIs and `profile=mcp-app` HTML) are left out, since they are user\n * interfaces for hosts that render them, and so are icons. Read resources become text and images for\n * the model; binary resources are saved to temp files. Scripts get the JSON payloads.\n */\n\nimport type { ImageContent, JsonValue, TextContent } from \"@earendil-works/pi-ai\";\nimport {\n\ttype ContentBlock,\n\ttype ListResourcesResult,\n\ttype ListResourceTemplatesResult,\n\tlimitMcpContent,\n\ttype McpRequestOptions,\n\ttype ReadResourceResult,\n\ttype Resource,\n\ttype ResourceTemplate,\n\ttoMcpModelContent,\n} from \"@earendil-works/pi-mcp\";\nimport type { TSchema } from \"typebox\";\nimport type { ToolAnnotations, ToolDefinition } from \"../../core/extensions/types.ts\";\nimport {\n\tLIST_MCP_RESOURCE_TEMPLATES_TOOL,\n\tLIST_MCP_RESOURCES_TOOL,\n\tREAD_MCP_RESOURCE_TOOL,\n} from \"../../core/mcp-servers.ts\";\nimport type { McpExposure } from \"./config.ts\";\nimport { type McpToolDetails, saveToTempFile, toToolExposure } from \"./tools.ts\";\n\nexport { LIST_MCP_RESOURCE_TEMPLATES_TOOL, LIST_MCP_RESOURCES_TOOL, READ_MCP_RESOURCE_TOOL };\n\n/** A connected server that offers resources. */\nexport interface McpResourceServer {\n\tname: string;\n\ttimeoutMs: number;\n\tresourcesPage(cursor: string | undefined, options: McpRequestOptions): Promise<ListResourcesResult>;\n\tresourceTemplatesPage(cursor: string | undefined, options: McpRequestOptions): Promise<ListResourceTemplatesResult>;\n\tallResources(options: McpRequestOptions): Promise<Resource[]>;\n\tallResourceTemplates(options: McpRequestOptions): Promise<ResourceTemplate[]>;\n\treadResource(uri: string, options: McpRequestOptions): Promise<ReadResourceResult>;\n}\n\n/** MCP App user interfaces, which only hosts that render them can use. */\nfunction isMcpAppResource(item: { uri?: string; uriTemplate?: string; mimeType?: string }): boolean {\n\tconst uri = item.uri ?? item.uriTemplate ?? \"\";\n\treturn uri.startsWith(\"ui://\") || /;\\s*profile\\s*=\\s*\"?mcp-app\"?/i.test(item.mimeType ?? \"\");\n}\n\n/** A listed resource or template without `_meta` and icons, tagged with its server. */\nfunction listed<T extends { _meta?: unknown }>(server: string, item: T): Record<string, unknown> {\n\tconst { _meta, icons: _icons, ...rest } = item as T & { icons?: unknown };\n\treturn { server, ...rest };\n}\n\nconst stringProperty = (description: string) => ({ type: \"string\", description });\nconst SERVER_FILTER = stringProperty(\"MCP server name. Omit to list every server with resources.\");\nconst CURSOR = stringProperty(\"Opaque cursor from a previous call with the same server; omit for the first page.\");\nconst LIST_PARAMETERS = {\n\ttype: \"object\",\n\tproperties: { server: SERVER_FILTER, cursor: CURSOR },\n\tadditionalProperties: false,\n};\nconst READ_PARAMETERS = {\n\ttype: \"object\",\n\tproperties: {\n\t\tserver: stringProperty(\n\t\t\t\"MCP server name exactly as configured. Must match the 'server' field returned by list_mcp_resources.\",\n\t\t),\n\t\turi: stringProperty(\"Resource URI to read. Must be one of the URIs returned by list_mcp_resources.\"),\n\t},\n\trequired: [\"server\", \"uri\"],\n\tadditionalProperties: false,\n};\n\nconst optionalString = { type: \"string\" };\nconst LISTING_ERRORS = {\n\ttype: \"array\",\n\tdescription: \"Servers that could not be listed\",\n\titems: {\n\t\ttype: \"object\",\n\t\tproperties: { server: { type: \"string\" }, error: { type: \"string\" } },\n\t\trequired: [\"server\", \"error\"],\n\t},\n};\nconst LIST_OUTPUT_SCHEMA = {\n\ttype: \"object\",\n\tproperties: {\n\t\tserver: optionalString,\n\t\tresources: {\n\t\t\ttype: \"array\",\n\t\t\titems: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tserver: { type: \"string\" },\n\t\t\t\t\turi: { type: \"string\" },\n\t\t\t\t\tname: { type: \"string\" },\n\t\t\t\t\ttitle: optionalString,\n\t\t\t\t\tdescription: optionalString,\n\t\t\t\t\tmimeType: optionalString,\n\t\t\t\t\tsize: { type: \"number\" },\n\t\t\t\t},\n\t\t\t\trequired: [\"server\", \"uri\", \"name\"],\n\t\t\t},\n\t\t},\n\t\tnextCursor: optionalString,\n\t\terrors: LISTING_ERRORS,\n\t},\n\trequired: [\"resources\"],\n};\nconst LIST_TEMPLATES_OUTPUT_SCHEMA = {\n\ttype: \"object\",\n\tproperties: {\n\t\tserver: optionalString,\n\t\tresourceTemplates: {\n\t\t\ttype: \"array\",\n\t\t\titems: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tserver: { type: \"string\" },\n\t\t\t\t\turiTemplate: { type: \"string\", description: \"RFC 6570 URI template\" },\n\t\t\t\t\tname: { type: \"string\" },\n\t\t\t\t\ttitle: optionalString,\n\t\t\t\t\tdescription: optionalString,\n\t\t\t\t\tmimeType: optionalString,\n\t\t\t\t},\n\t\t\t\trequired: [\"server\", \"uriTemplate\", \"name\"],\n\t\t\t},\n\t\t},\n\t\tnextCursor: optionalString,\n\t\terrors: LISTING_ERRORS,\n\t},\n\trequired: [\"resourceTemplates\"],\n};\nconst READ_OUTPUT_SCHEMA = {\n\ttype: \"object\",\n\tproperties: {\n\t\tserver: { type: \"string\" },\n\t\turi: { type: \"string\" },\n\t\tcontents: {\n\t\t\ttype: \"array\",\n\t\t\titems: {\n\t\t\t\tanyOf: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: { uri: { type: \"string\" }, mimeType: optionalString, text: { type: \"string\" } },\n\t\t\t\t\t\trequired: [\"uri\", \"text\"],\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\turi: { type: \"string\" },\n\t\t\t\t\t\t\tmimeType: optionalString,\n\t\t\t\t\t\t\tblob: { type: \"string\", description: \"base64\" },\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"uri\", \"blob\"],\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t},\n\t},\n\trequired: [\"server\", \"uri\", \"contents\"],\n};\n\nfunction stringArgument(params: unknown, key: string): string | undefined {\n\tconst value = (params as Record<string, unknown> | undefined)?.[key];\n\tif (value === undefined || value === null) return undefined;\n\tif (typeof value !== \"string\") throw new Error(`${key} must be a string`);\n\treturn value.trim() || undefined;\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nasync function jsonResult(\n\ttool: string,\n\tserver: string | undefined,\n\tpayload: Record<string, unknown>,\n): Promise<{ content: (TextContent | ImageContent)[]; details: McpToolDetails; structuredContent: JsonValue }> {\n\tconst { content, fullOutputPath } = await limitMcpContent(\n\t\t[{ type: \"text\", text: JSON.stringify(payload) }],\n\t\tsaveToTempFile,\n\t);\n\treturn {\n\t\tcontent,\n\t\tdetails: { server: server ?? \"\", tool, ...(fullOutputPath ? { fullOutputPath } : {}) },\n\t\tstructuredContent: payload as unknown as JsonValue,\n\t};\n}\n\n/**\n * The three resource tools. `servers` returns the servers whose resources they reach, at call time.\n */\nexport function createMcpResourceToolDefinitions(options: {\n\texposure: McpExposure;\n\tservers: () => readonly McpResourceServer[];\n}): ToolDefinition<TSchema, McpToolDetails>[] {\n\tconst readOnly: ToolAnnotations = { readOnlyHint: true };\n\n\tconst findServer = (name: string): McpResourceServer => {\n\t\tconst servers = options.servers();\n\t\tconst server = servers.find((candidate) => candidate.name === name);\n\t\tif (server) return server;\n\t\tconst available = servers.map((candidate) => candidate.name).join(\", \");\n\t\tthrow new Error(\n\t\t\t`MCP server \"${name}\" has no resources${available ? `. Servers with resources: ${available}` : \"\"}`,\n\t\t);\n\t};\n\n\t/** One page of one server, or every page of every server. */\n\tconst list = async <T extends { _meta?: unknown }>(\n\t\tparams: unknown,\n\t\tsignal: AbortSignal | undefined,\n\t\tkey: \"resources\" | \"resourceTemplates\",\n\t\tpage: (\n\t\t\tserver: McpResourceServer,\n\t\t\tcursor: string | undefined,\n\t\t\toptions: McpRequestOptions,\n\t\t) => Promise<{\n\t\t\titems: T[];\n\t\t\tnextCursor?: string;\n\t\t}>,\n\t\tall: (server: McpResourceServer, options: McpRequestOptions) => Promise<T[]>,\n\t): Promise<Record<string, unknown>> => {\n\t\tconst serverName = stringArgument(params, \"server\");\n\t\tconst cursor = stringArgument(params, \"cursor\");\n\t\tconst visible = (item: T) => !isMcpAppResource(item as { uri?: string; uriTemplate?: string; mimeType?: string });\n\t\tif (serverName) {\n\t\t\tconst server = findServer(serverName);\n\t\t\tconst result = await page(server, cursor, { signal, timeoutMs: server.timeoutMs });\n\t\t\treturn {\n\t\t\t\tserver: server.name,\n\t\t\t\t[key]: result.items.filter(visible).map((item) => listed(server.name, item)),\n\t\t\t\t...(result.nextCursor === undefined ? {} : { nextCursor: result.nextCursor }),\n\t\t\t};\n\t\t}\n\t\tif (cursor) throw new Error(\"cursor can only be used when a server is specified\");\n\t\tconst servers = [...options.servers()].sort((a, b) => a.name.localeCompare(b.name));\n\t\tconst results = await Promise.allSettled(\n\t\t\tservers.map((server) => all(server, { signal, timeoutMs: server.timeoutMs })),\n\t\t);\n\t\tconst items: Record<string, unknown>[] = [];\n\t\tconst errors: { server: string; error: string }[] = [];\n\t\tresults.forEach((result, index) => {\n\t\t\tconst server = servers[index].name;\n\t\t\tif (result.status === \"fulfilled\")\n\t\t\t\titems.push(...result.value.filter(visible).map((item) => listed(server, item)));\n\t\t\telse errors.push({ server, error: errorMessage(result.reason) });\n\t\t});\n\t\treturn { [key]: items, ...(errors.length > 0 ? { errors } : {}) };\n\t};\n\n\tconst listResources: ToolDefinition<TSchema, McpToolDetails> = {\n\t\tname: LIST_MCP_RESOURCES_TOOL,\n\t\tlabel: LIST_MCP_RESOURCES_TOOL,\n\t\tdescription:\n\t\t\t\"Lists resources provided by MCP servers. Resources allow servers to share data that provides context to language models, such as files, database schemas, or application-specific information. Prefer resources over web search when possible.\",\n\t\tparameters: LIST_PARAMETERS as unknown as TSchema,\n\t\toutputSchema: LIST_OUTPUT_SCHEMA as unknown as TSchema,\n\t\texposure: toToolExposure(options.exposure),\n\t\tannotations: readOnly,\n\t\tasync execute(_toolCallId, params, signal) {\n\t\t\tconst payload = await list(\n\t\t\t\tparams,\n\t\t\t\tsignal,\n\t\t\t\t\"resources\",\n\t\t\t\tasync (server, cursor, requestOptions) => {\n\t\t\t\t\tconst result = await server.resourcesPage(cursor, requestOptions);\n\t\t\t\t\treturn { items: result.resources, nextCursor: result.nextCursor };\n\t\t\t\t},\n\t\t\t\t(server, requestOptions) => server.allResources(requestOptions),\n\t\t\t);\n\t\t\treturn jsonResult(LIST_MCP_RESOURCES_TOOL, stringArgument(params, \"server\"), payload);\n\t\t},\n\t};\n\n\tconst listTemplates: ToolDefinition<TSchema, McpToolDetails> = {\n\t\tname: LIST_MCP_RESOURCE_TEMPLATES_TOOL,\n\t\tlabel: LIST_MCP_RESOURCE_TEMPLATES_TOOL,\n\t\tdescription:\n\t\t\t\"Lists resource templates provided by MCP servers. Parameterized resource templates allow servers to share data that takes parameters and provides context to language models, such as files, database schemas, or application-specific information. Prefer resource templates over web search when possible.\",\n\t\tparameters: LIST_PARAMETERS as unknown as TSchema,\n\t\toutputSchema: LIST_TEMPLATES_OUTPUT_SCHEMA as unknown as TSchema,\n\t\texposure: toToolExposure(options.exposure),\n\t\tannotations: readOnly,\n\t\tasync execute(_toolCallId, params, signal) {\n\t\t\tconst payload = await list(\n\t\t\t\tparams,\n\t\t\t\tsignal,\n\t\t\t\t\"resourceTemplates\",\n\t\t\t\tasync (server, cursor, requestOptions) => {\n\t\t\t\t\tconst result = await server.resourceTemplatesPage(cursor, requestOptions);\n\t\t\t\t\treturn { items: result.resourceTemplates, nextCursor: result.nextCursor };\n\t\t\t\t},\n\t\t\t\t(server, requestOptions) => server.allResourceTemplates(requestOptions),\n\t\t\t);\n\t\t\treturn jsonResult(LIST_MCP_RESOURCE_TEMPLATES_TOOL, stringArgument(params, \"server\"), payload);\n\t\t},\n\t};\n\n\tconst readResource: ToolDefinition<TSchema, McpToolDetails> = {\n\t\tname: READ_MCP_RESOURCE_TOOL,\n\t\tlabel: READ_MCP_RESOURCE_TOOL,\n\t\tdescription: \"Read a specific resource from an MCP server given the server name and resource URI.\",\n\t\tparameters: READ_PARAMETERS as unknown as TSchema,\n\t\toutputSchema: READ_OUTPUT_SCHEMA as unknown as TSchema,\n\t\texposure: toToolExposure(options.exposure),\n\t\tannotations: readOnly,\n\t\tasync execute(_toolCallId, params, signal) {\n\t\t\tconst serverName = stringArgument(params, \"server\");\n\t\t\tconst uri = stringArgument(params, \"uri\");\n\t\t\tif (!serverName) throw new Error(\"server must be provided\");\n\t\t\tif (!uri) throw new Error(\"uri must be provided\");\n\t\t\tconst server = findServer(serverName);\n\t\t\tconst result = await server.readResource(uri, { signal, timeoutMs: server.timeoutMs });\n\t\t\t// Several contents (for example a directory) are labeled with their URIs.\n\t\t\tconst blocks: ContentBlock[] = result.contents.flatMap((contents) => [\n\t\t\t\t...(result.contents.length > 1 ? [{ type: \"text\" as const, text: `${contents.uri}:` }] : []),\n\t\t\t\t{ type: \"resource\" as const, resource: contents },\n\t\t\t]);\n\t\t\tconst converted = await toMcpModelContent(server.name, { content: blocks }, { saveOutput: saveToTempFile });\n\t\t\tconst { content, fullOutputPath } = await limitMcpContent(\n\t\t\t\tconverted.length > 0 ? converted : [{ type: \"text\", text: `Resource ${uri} is empty.` }],\n\t\t\t\tsaveToTempFile,\n\t\t\t);\n\t\t\tconst contents = result.contents.map(({ _meta: _ignored, ...rest }) => rest);\n\t\t\treturn {\n\t\t\t\tcontent,\n\t\t\t\tdetails: {\n\t\t\t\t\tserver: server.name,\n\t\t\t\t\ttool: READ_MCP_RESOURCE_TOOL,\n\t\t\t\t\t...(fullOutputPath ? { fullOutputPath } : {}),\n\t\t\t\t},\n\t\t\t\tstructuredContent: { server: server.name, uri, contents } as unknown as JsonValue,\n\t\t\t};\n\t\t},\n\t};\n\n\treturn [listResources, listTemplates, readResource];\n}\n"]}
@@ -10,8 +10,7 @@
10
10
  * errors (`isError`) are error results for the model, but scripts still resolve to the result.
11
11
  */
12
12
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
13
- import type { ImageContent, TextContent } from "@earendil-works/pi-ai";
14
- import { type CallToolResult, type ContentBlock, type McpOutputSaver, type McpRequestOptions, type Tool as McpTool } from "@earendil-works/pi-mcp";
13
+ import { type CallToolResult, type McpOutputSaver, type McpRequestOptions, type Tool as McpTool } from "@earendil-works/pi-mcp";
15
14
  import type { TSchema } from "typebox";
16
15
  import type { ToolDefinition, ToolExposure, ToolNamespace, ToolRenderers } from "../../core/extensions/types.ts";
17
16
  import { READ_MCP_RESOURCE_TOOL } from "../../core/mcp-servers.ts";
@@ -34,19 +33,12 @@ export declare function saveToTempFile(data: string | Uint8Array, extension: str
34
33
  export interface McpToolCaller {
35
34
  callTool(name: string, args: Record<string, unknown>, options: McpRequestOptions): Promise<CallToolResult>;
36
35
  }
37
- /**
38
- * Output schema of every MCP tool: the `CallToolResult` scripts receive (without `_meta`, which
39
- * {@link convertMcpResult} drops), with the tool's own output schema as `structuredContent`.
40
- */
41
- export declare function createMcpResultSchema(structuredContentSchema: Record<string, unknown> | undefined): TSchema;
42
36
  export interface ConvertMcpResultOptions {
43
37
  /** Saves truncated text and binary resources. Default: a temp file. */
44
38
  saveOutput?: McpOutputSaver;
45
39
  /** Whether the server's resources can be read with `read_mcp_resource`, which resource links then name. */
46
40
  readableResources?: boolean;
47
41
  }
48
- /** Model-facing content of `server`'s content blocks, before the output limit. */
49
- export declare function toModelContent(server: string, blocks: readonly ContentBlock[], options?: ConvertMcpResultOptions): Promise<(TextContent | ImageContent)[]>;
50
42
  /** Convert an MCP result. `isError` results become error results that keep the structured result. */
51
43
  export declare function convertMcpResult(server: string, tool: string, result: CallToolResult, options?: ConvertMcpResultOptions): Promise<AgentToolResult<McpToolDetails>>;
52
44
  export declare function createMcpToolDefinition(options: {
@@ -1 +1 @@
1
- {"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../../../src/extensions/mcp/tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AACrE,OAAO,KAAK,EAAE,YAAY,EAAa,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAClF,OAAO,EACN,KAAK,cAAc,EACnB,KAAK,YAAY,EAEjB,KAAK,cAAc,EACnB,KAAK,iBAAiB,EACtB,KAAK,IAAI,IAAI,OAAO,EAGpB,MAAM,wBAAwB,CAAC;AAEhC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,KAAK,EAEX,cAAc,EACd,YAAY,EACZ,aAAa,EACb,aAAa,EACb,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AAMnE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE/C;;;GAGG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,WAAW,GAAG,YAAY,CAElE;AAID,6DAA6D;AAC7D,OAAO,EAAE,sBAAsB,EAAE,CAAC;AAElC,MAAM,WAAW,cAAc;IAC9B,MAAM,EAAE,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E5F;AAED,MAAM,WAAW,aAAa;IAC7B,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC;CAC3G;AASD,MAAM,WAAW,uBAAuB;IACvC,uEAAuE;IACvE,UAAU,CAAC,EAAE,cAAc,CAAC;IAC5B,2GAA2G;IAC3G,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC5B;AAED,qGAAqG;AACrG,wBAAsB,gBAAgB,CACrC,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,cAAc,EACtB,OAAO,GAAE,uBAA4B,GACnC,OAAO,CAAC,eAAe,CAAC,cAAc,CAAC,CAAC,CAiB1C;AAcD,wBAAgB,uBAAuB,CAAC,OAAO,EAAE;IAChD,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,OAAO,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,WAAW,CAAC;IACtB,SAAS,EAAE,aAAa,CAAC;IACzB,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,OAAO,CAAC,aAAa,CAAC,CAAC;IACxC,mEAAmE;IACnE,iBAAiB,CAAC,EAAE,MAAM,OAAO,CAAC;CAClC,GAAG,cAAc,CAAC,OAAO,EAAE,cAAc,CAAC,CA+B1C;AAED,yGAAyG;AACzG,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,CAqCnE"}
@@ -9,11 +9,10 @@
9
9
  * the tool's `structuredContent`, and every MCP tool declares a `CallToolResult` output schema. MCP
10
10
  * errors (`isError`) are error results for the model, but scripts still resolve to the result.
11
11
  */
12
- import { limitMcpContent, normalizeMcpInputSchema, toLlmContent, } from "@earendil-works/pi-mcp";
12
+ import { createMcpResultSchema, limitMcpContent, normalizeMcpInputSchema, toMcpModelContent, } from "@earendil-works/pi-mcp";
13
13
  import { Container, Spacer, Text } from "@earendil-works/pi-tui";
14
14
  import { READ_MCP_RESOURCE_TOOL } from "../../core/mcp-servers.js";
15
15
  import { formatToolCallWithArgs, getTextOutput, replaceTabs } from "../../core/tools/render-utils.js";
16
- import { formatSize } from "../../core/tools/truncate.js";
17
16
  import { keyHint } from "../../modes/interactive/components/keybinding-hints.js";
18
17
  import { VisualLinePreview } from "../../modes/interactive/components/visual-truncate.js";
19
18
  import { writeOutputFile } from "../../utils/output-files.js";
@@ -38,133 +37,17 @@ function textOf(content) {
38
37
  .map((block) => block.text)
39
38
  .join("\n");
40
39
  }
41
- /**
42
- * MCP content blocks as one compact type with the fields of text and image blocks, which scripts
43
- * read most (`image(block)` takes an image block as is). Rendered into every MCP tool's declaration.
44
- */
45
- const CONTENT_BLOCK_SCHEMA = {
46
- type: "object",
47
- properties: {
48
- type: { enum: ["text", "image", "audio", "resource_link", "resource"] },
49
- text: { type: "string" },
50
- data: { type: "string" },
51
- mimeType: { type: "string" },
52
- },
53
- required: ["type"],
54
- additionalProperties: true,
55
- };
56
- /** Keywords whose values are data, so a `$ref` key in them is not a reference. */
57
- const SCHEMA_DATA_KEYWORDS = new Set(["const", "enum", "default", "examples"]);
58
- /** Keywords whose values map names to schemas, so their keys are names, not keywords. */
59
- const SCHEMA_MAP_KEYWORDS = new Set([
60
- "properties",
61
- "patternProperties",
62
- "dependentSchemas",
63
- "dependencies",
64
- "$defs",
65
- "definitions",
66
- ]);
67
- /**
68
- * `schema` as a subschema at the JSON pointer `pointer` (`#/properties/structuredContent`) of
69
- * another schema: its local references (`#`, `#/$defs/Item`) are rewritten to point below
70
- * `pointer`, so they resolve to the same subschemas as before.
71
- */
72
- function relocateSchema(schema, pointer) {
73
- if (Array.isArray(schema))
74
- return schema.map((item) => relocateSchema(item, pointer));
75
- if (typeof schema !== "object" || schema === null)
76
- return schema;
77
- const relocated = {};
78
- for (const [key, value] of Object.entries(schema)) {
79
- if (key === "$ref" && typeof value === "string" && (value === "#" || value.startsWith("#/"))) {
80
- relocated[key] = `${pointer}${value.slice(1)}`;
81
- }
82
- else if (SCHEMA_DATA_KEYWORDS.has(key)) {
83
- relocated[key] = value;
84
- }
85
- else if (SCHEMA_MAP_KEYWORDS.has(key) && typeof value === "object" && value !== null && !Array.isArray(value)) {
86
- relocated[key] = Object.fromEntries(Object.entries(value).map(([name, subschema]) => [name, relocateSchema(subschema, pointer)]));
87
- }
88
- else {
89
- relocated[key] = relocateSchema(value, pointer);
90
- }
91
- }
92
- return relocated;
93
- }
94
- /**
95
- * Output schema of every MCP tool: the `CallToolResult` scripts receive (without `_meta`, which
96
- * {@link convertMcpResult} drops), with the tool's own output schema as `structuredContent`.
97
- */
98
- export function createMcpResultSchema(structuredContentSchema) {
99
- return {
100
- type: "object",
101
- properties: {
102
- content: { type: "array", items: CONTENT_BLOCK_SCHEMA },
103
- // Servers may send structured content without declaring a schema for it, and it may be any JSON value.
104
- structuredContent: structuredContentSchema
105
- ? relocateSchema(structuredContentSchema, "#/properties/structuredContent")
106
- : {},
107
- isError: { type: "boolean" },
108
- },
109
- required: ["content"],
110
- // Fields newer protocol versions add.
111
- additionalProperties: true,
112
- };
113
- }
114
- /** File extension for a saved binary resource: the one its URI ends in, else `.bin`. */
115
- function extensionOf(uri) {
116
- const path = URL.canParse(uri) ? new URL(uri).pathname : uri;
117
- return /\.[A-Za-z0-9]{1,8}$/.exec(path)?.[0] ?? ".bin";
118
- }
119
- /** Blobs of these types are shown as text. */
120
- function isTextMimeType(mimeType) {
121
- if (!mimeType)
122
- return false;
123
- const type = mimeType.split(";", 1)[0].trim().toLowerCase();
124
- return type.startsWith("text/") || type === "application/json" || type.endsWith("+json") || type.endsWith("+xml");
125
- }
126
- /** Model-facing content of one block of `server`'s result. */
127
- async function blockToContent(server, block, options) {
128
- if (block.type === "resource_link") {
129
- const details = [block.mimeType, block.size === undefined ? undefined : formatSize(block.size)].filter(Boolean);
130
- const read = options.readableResources ? `. Read it with ${READ_MCP_RESOURCE_TOOL} (server "${server}")` : "";
131
- const description = block.description ? `: ${block.description}` : "";
132
- return [
133
- {
134
- type: "text",
135
- text: `[Resource ${block.uri} "${block.title ?? block.name}"${details.length > 0 ? ` (${details.join(", ")})` : ""}${description}${read}]`,
136
- },
137
- ];
138
- }
139
- if (block.type === "resource" && "blob" in block.resource && !block.resource.mimeType?.startsWith("image/")) {
140
- const { uri, mimeType, blob } = block.resource;
141
- const data = Buffer.from(blob, "base64");
142
- if (isTextMimeType(mimeType))
143
- return [{ type: "text", text: data.toString("utf8") }];
144
- const kind = `${mimeType ?? "unknown type"}, ${formatSize(data.length)}`;
145
- try {
146
- const path = await (options.saveOutput ?? saveToTempFile)(data, extensionOf(uri));
147
- return [{ type: "text", text: `[Binary resource ${uri} (${kind}) saved to ${path}]` }];
148
- }
149
- catch (error) {
150
- const reason = error instanceof Error ? error.message : String(error);
151
- return [{ type: "text", text: `[Binary resource ${uri} (${kind}) could not be saved: ${reason}]` }];
152
- }
153
- }
154
- return toLlmContent({ content: [block] });
155
- }
156
- /** Model-facing content of `server`'s content blocks, before the output limit. */
157
- export async function toModelContent(server, blocks, options = {}) {
158
- return (await Promise.all(blocks.map((block) => blockToContent(server, block, options)))).flat();
159
- }
160
40
  /** Convert an MCP result. `isError` results become error results that keep the structured result. */
161
41
  export async function convertMcpResult(server, tool, result, options = {}) {
162
- // Without content blocks, toLlmContent falls back to the structured content as JSON.
163
- const converted = result.content.length > 0 ? await toModelContent(server, result.content, options) : toLlmContent(result);
42
+ const saveOutput = options.saveOutput ?? saveToTempFile;
43
+ const converted = await toMcpModelContent(server, result, {
44
+ saveOutput,
45
+ ...(options.readableResources ? { readResourceTool: READ_MCP_RESOURCE_TOOL } : {}),
46
+ });
164
47
  if (result.isError && textOf(converted) === "") {
165
48
  converted.push({ type: "text", text: `MCP tool ${server}/${tool} returned an error` });
166
49
  }
167
- const { content, fullOutputPath } = await limitMcpContent(converted, options.saveOutput ?? saveToTempFile);
50
+ const { content, fullOutputPath } = await limitMcpContent(converted, saveOutput);
168
51
  const { _meta: _ignored, ...scriptResult } = result;
169
52
  return {
170
53
  content,
@@ -195,6 +78,7 @@ export function createMcpToolDefinition(options) {
195
78
  description: tool.description?.trim() || title || `MCP tool ${tool.name} from server ${server}`,
196
79
  // An object schema, which is what TypeBox schemas are at runtime.
197
80
  parameters: normalizeMcpInputSchema(tool.inputSchema),
81
+ // A JSON schema object, which is what TypeBox schemas are at runtime.
198
82
  outputSchema: createMcpResultSchema(tool.outputSchema),
199
83
  exposure: toToolExposure(options.exposure),
200
84
  namespace: options.namespace,
@@ -1 +1 @@
1
- {"version":3,"file":"tools.js","sourceRoot":"","sources":["../../../src/extensions/mcp/tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAIH,OAAO,EAGN,eAAe,EAIf,uBAAuB,EACvB,YAAY,GACZ,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AASjE,OAAO,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACnE,OAAO,EAAE,sBAAsB,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,kCAAkC,CAAC;AACtG,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AAC1D,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AACjF,OAAO,EAAE,iBAAiB,EAAE,MAAM,uDAAuD,CAAC;AAC1F,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAG9D;;;GAGG;AACH,MAAM,UAAU,cAAc,CAAC,QAAqB;IACnD,OAAO,QAAQ,KAAK,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,QAAQ,CAAC;AACxD,CAAC;AAED,yEAAyE;AACzE,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAC/B,6DAA6D;AAC7D,OAAO,EAAE,sBAAsB,EAAE,CAAC;A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c,CAAC,IAAI,OAAO,CAAC,kBAAkB,EAAE,WAAW,CAAC,GAAG,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,CAAC,EAAE;iBAC1H,CAAC,CACF,CAAC;gBACF,MAAM,cAAc,GAAI,MAAM,CAAC,OAAsC,EAAE,cAAc,CAAC;gBACtF,IAAI,cAAc;oBAAE,SAAS,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,gBAAgB,cAAc,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;YAC7G,CAAC;YACD,OAAO,SAAS,CAAC;QAClB,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["/**\n * Adapts MCP tools to pi tool definitions.\n *\n * Results map onto pi's model-facing content (text and images). Text over 20KB keeps its start and\n * end with the middle cut out, like Codex does, and the full text is saved to a temp file the model\n * can read. Binary resources other than images are saved to temp files too, and resource links name\n * the `read_mcp_resource` tool. Codemode scripts receive the whole `CallToolResult` without `_meta`\n * (`content` blocks as sent by the server, `structuredContent`, `isError`), never truncated: it is\n * the tool's `structuredContent`, and every MCP tool declares a `CallToolResult` output schema. MCP\n * errors (`isError`) are error results for the model, but scripts still resolve to the result.\n */\n\nimport type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { ImageContent, JsonValue, TextContent } from \"@earendil-works/pi-ai\";\nimport {\n\ttype CallToolResult,\n\ttype ContentBlock,\n\tlimitMcpContent,\n\ttype McpOutputSaver,\n\ttype McpRequestOptions,\n\ttype Tool as McpTool,\n\tnormalizeMcpInputSchema,\n\ttoLlmContent,\n} from \"@earendil-works/pi-mcp\";\nimport { Container, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport type { TSchema } from \"typebox\";\nimport type {\n\tToolAnnotations,\n\tToolDefinition,\n\tToolExposure,\n\tToolNamespace,\n\tToolRenderers,\n} from \"../../core/extensions/types.ts\";\nimport { READ_MCP_RESOURCE_TOOL } from \"../../core/mcp-servers.ts\";\nimport { formatToolCallWithArgs, getTextOutput, replaceTabs } from \"../../core/tools/render-utils.ts\";\nimport { formatSize } from \"../../core/tools/truncate.ts\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { VisualLinePreview } from \"../../modes/interactive/components/visual-truncate.ts\";\nimport { writeOutputFile } from \"../../utils/output-files.ts\";\nimport type { McpExposure } from \"./config.ts\";\n\n/**\n * Tool exposure of an MCP exposure. `codemode` and `deferred` both leave tools out of the codemode\n * description; they differ only in which tool the MCP extension activates to reach them.\n */\nexport function toToolExposure(exposure: McpExposure): ToolExposure {\n\treturn exposure === \"codemode\" ? \"deferred\" : exposure;\n}\n\n/** Visual (wrapped) result lines shown before the output is expanded. */\nconst OUTPUT_PREVIEW_LINES = 5;\n/** Tool that reads the resources named by resource links. */\nexport { READ_MCP_RESOURCE_TOOL };\n\nexport interface McpToolDetails {\n\tserver: string;\n\ttool: string;\n\t/** Temp file with the full text output, when the model-facing text was truncated. */\n\tfullOutputPath?: string;\n}\n\n/** Saves the full text of a truncated result, or a binary resource, to a temp file and returns its path. */\nexport function saveToTempFile(data: string | Uint8Array, extension: string): Promise<string> {\n\treturn writeOutputFile(\"pi-mcp\", extension, data);\n}\n\nexport interface McpToolCaller {\n\tcallTool(name: string, args: Record<string, unknown>, options: McpRequestOptions): Promise<CallToolResult>;\n}\n\nfunction textOf(content: readonly (TextContent | ImageContent)[]): string {\n\treturn content\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n}\n\n/**\n * MCP content blocks as one compact type with the fields of text and image blocks, which scripts\n * read most (`image(block)` takes an image block as is). Rendered into every MCP tool's declaration.\n */\nconst CONTENT_BLOCK_SCHEMA = {\n\ttype: \"object\",\n\tproperties: {\n\t\ttype: { enum: [\"text\", \"image\", \"audio\", \"resource_link\", \"resource\"] },\n\t\ttext: { type: \"string\" },\n\t\tdata: { type: \"string\" },\n\t\tmimeType: { type: \"string\" },\n\t},\n\trequired: [\"type\"],\n\tadditionalProperties: true,\n};\n\n/** Keywords whose values are data, so a `$ref` key in them is not a reference. */\nconst SCHEMA_DATA_KEYWORDS: ReadonlySet<string> = new Set([\"const\", \"enum\", \"default\", \"examples\"]);\n/** Keywords whose values map names to schemas, so their keys are names, not keywords. */\nconst SCHEMA_MAP_KEYWORDS: ReadonlySet<string> = new Set([\n\t\"properties\",\n\t\"patternProperties\",\n\t\"dependentSchemas\",\n\t\"dependencies\",\n\t\"$defs\",\n\t\"definitions\",\n]);\n\n/**\n * `schema` as a subschema at the JSON pointer `pointer` (`#/properties/structuredContent`) of\n * another schema: its local references (`#`, `#/$defs/Item`) are rewritten to point below\n * `pointer`, so they resolve to the same subschemas as before.\n */\nfunction relocateSchema(schema: unknown, pointer: string): unknown {\n\tif (Array.isArray(schema)) return schema.map((item) => relocateSchema(item, pointer));\n\tif (typeof schema !== \"object\" || schema === null) return schema;\n\tconst relocated: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(schema)) {\n\t\tif (key === \"$ref\" && typeof value === \"string\" && (value === \"#\" || value.startsWith(\"#/\"))) {\n\t\t\trelocated[key] = `${pointer}${value.slice(1)}`;\n\t\t} else if (SCHEMA_DATA_KEYWORDS.has(key)) {\n\t\t\trelocated[key] = value;\n\t\t} else if (SCHEMA_MAP_KEYWORDS.has(key) && typeof value === \"object\" && value !== null && !Array.isArray(value)) {\n\t\t\trelocated[key] = Object.fromEntries(\n\t\t\t\tObject.entries(value).map(([name, subschema]) => [name, relocateSchema(subschema, pointer)]),\n\t\t\t);\n\t\t} else {\n\t\t\trelocated[key] = relocateSchema(value, pointer);\n\t\t}\n\t}\n\treturn relocated;\n}\n\n/**\n * Output schema of every MCP tool: the `CallToolResult` scripts receive (without `_meta`, which\n * {@link convertMcpResult} drops), with the tool's own output schema as `structuredContent`.\n */\nexport function createMcpResultSchema(structuredContentSchema: Record<string, unknown> | undefined): TSchema {\n\treturn {\n\t\ttype: \"object\",\n\t\tproperties: {\n\t\t\tcontent: { type: \"array\", items: CONTENT_BLOCK_SCHEMA },\n\t\t\t// Servers may send structured content without declaring a schema for it, and it may be any JSON value.\n\t\t\tstructuredContent: structuredContentSchema\n\t\t\t\t? relocateSchema(structuredContentSchema, \"#/properties/structuredContent\")\n\t\t\t\t: {},\n\t\t\tisError: { type: \"boolean\" },\n\t\t},\n\t\trequired: [\"content\"],\n\t\t// Fields newer protocol versions add.\n\t\tadditionalProperties: true,\n\t} as unknown as TSchema;\n}\n\nexport interface ConvertMcpResultOptions {\n\t/** Saves truncated text and binary resources. Default: a temp file. */\n\tsaveOutput?: McpOutputSaver;\n\t/** Whether the server's resources can be read with `read_mcp_resource`, which resource links then name. */\n\treadableResources?: boolean;\n}\n\n/** File extension for a saved binary resource: the one its URI ends in, else `.bin`. */\nfunction extensionOf(uri: string): string {\n\tconst path = URL.canParse(uri) ? new URL(uri).pathname : uri;\n\treturn /\\.[A-Za-z0-9]{1,8}$/.exec(path)?.[0] ?? \".bin\";\n}\n\n/** Blobs of these types are shown as text. */\nfunction isTextMimeType(mimeType: string | undefined): boolean {\n\tif (!mimeType) return false;\n\tconst type = mimeType.split(\";\", 1)[0].trim().toLowerCase();\n\treturn type.startsWith(\"text/\") || type === \"application/json\" || type.endsWith(\"+json\") || type.endsWith(\"+xml\");\n}\n\n/** Model-facing content of one block of `server`'s result. */\nasync function blockToContent(\n\tserver: string,\n\tblock: ContentBlock,\n\toptions: ConvertMcpResultOptions,\n): Promise<(TextContent | ImageContent)[]> {\n\tif (block.type === \"resource_link\") {\n\t\tconst details = [block.mimeType, block.size === undefined ? undefined : formatSize(block.size)].filter(Boolean);\n\t\tconst read = options.readableResources ? `. Read it with ${READ_MCP_RESOURCE_TOOL} (server \"${server}\")` : \"\";\n\t\tconst description = block.description ? `: ${block.description}` : \"\";\n\t\treturn [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `[Resource ${block.uri} \"${block.title ?? block.name}\"${details.length > 0 ? ` (${details.join(\", \")})` : \"\"}${description}${read}]`,\n\t\t\t},\n\t\t];\n\t}\n\tif (block.type === \"resource\" && \"blob\" in block.resource && !block.resource.mimeType?.startsWith(\"image/\")) {\n\t\tconst { uri, mimeType, blob } = block.resource;\n\t\tconst data = Buffer.from(blob, \"base64\");\n\t\tif (isTextMimeType(mimeType)) return [{ type: \"text\", text: data.toString(\"utf8\") }];\n\t\tconst kind = `${mimeType ?? \"unknown type\"}, ${formatSize(data.length)}`;\n\t\ttry {\n\t\t\tconst path = await (options.saveOutput ?? saveToTempFile)(data, extensionOf(uri));\n\t\t\treturn [{ type: \"text\", text: `[Binary resource ${uri} (${kind}) saved to ${path}]` }];\n\t\t} catch (error) {\n\t\t\tconst reason = error instanceof Error ? error.message : String(error);\n\t\t\treturn [{ type: \"text\", text: `[Binary resource ${uri} (${kind}) could not be saved: ${reason}]` }];\n\t\t}\n\t}\n\treturn toLlmContent({ content: [block] });\n}\n\n/** Model-facing content of `server`'s content blocks, before the output limit. */\nexport async function toModelContent(\n\tserver: string,\n\tblocks: readonly ContentBlock[],\n\toptions: ConvertMcpResultOptions = {},\n): Promise<(TextContent | ImageContent)[]> {\n\treturn (await Promise.all(blocks.map((block) => blockToContent(server, block, options)))).flat();\n}\n\n/** Convert an MCP result. `isError` results become error results that keep the structured result. */\nexport async function convertMcpResult(\n\tserver: string,\n\ttool: string,\n\tresult: CallToolResult,\n\toptions: ConvertMcpResultOptions = {},\n): Promise<AgentToolResult<McpToolDetails>> {\n\t// Without content blocks, toLlmContent falls back to the structured content as JSON.\n\tconst converted: (TextContent | ImageContent)[] =\n\t\tresult.content.length > 0 ? await toModelContent(server, result.content, options) : toLlmContent(result);\n\tif (result.isError && textOf(converted) === \"\") {\n\t\tconverted.push({ type: \"text\", text: `MCP tool ${server}/${tool} returned an error` });\n\t}\n\tconst { content, fullOutputPath } = await limitMcpContent(converted, options.saveOutput ?? saveToTempFile);\n\tconst { _meta: _ignored, ...scriptResult } = result;\n\treturn {\n\t\tcontent,\n\t\tdetails: { server, tool, ...(fullOutputPath ? { fullOutputPath } : {}) },\n\t\tstructuredContent: scriptResult as unknown as JsonValue,\n\t\t...(result.isError ? { isError: true } : {}),\n\t};\n}\n\nconst ANNOTATION_HINTS = [\"readOnlyHint\", \"destructiveHint\", \"idempotentHint\", \"openWorldHint\"] as const;\n\n/** The boolean hints of an MCP tool's annotations, or undefined when it has none. */\nfunction toToolAnnotations(tool: McpTool): ToolAnnotations | undefined {\n\tconst annotations: ToolAnnotations = {};\n\tfor (const hint of ANNOTATION_HINTS) {\n\t\tconst value = tool.annotations?.[hint];\n\t\tif (typeof value === \"boolean\") annotations[hint] = value;\n\t}\n\treturn Object.keys(annotations).length > 0 ? annotations : undefined;\n}\n\nexport function createMcpToolDefinition(options: {\n\tserver: string;\n\ttool: McpTool;\n\tname: string;\n\texposure: McpExposure;\n\tnamespace: ToolNamespace;\n\ttimeoutMs: number;\n\tgetClient: () => Promise<McpToolCaller>;\n\t/** Whether `read_mcp_resource` can read the server's resources. */\n\treadableResources?: () => boolean;\n}): ToolDefinition<TSchema, McpToolDetails> {\n\tconst { server, tool } = options;\n\tconst title = tool.title ?? tool.annotations?.title;\n\tconst annotations = toToolAnnotations(tool);\n\tconst label = `${server}/${tool.name}`;\n\treturn {\n\t\tname: options.name,\n\t\tlabel,\n\t\tdescription: tool.description?.trim() || title || `MCP tool ${tool.name} from server ${server}`,\n\t\t// An object schema, which is what TypeBox schemas are at runtime.\n\t\tparameters: normalizeMcpInputSchema(tool.inputSchema) as unknown as TSchema,\n\t\toutputSchema: createMcpResultSchema(tool.outputSchema),\n\t\texposure: toToolExposure(options.exposure),\n\t\tnamespace: options.namespace,\n\t\t...(annotations ? { annotations } : {}),\n\t\t...createMcpToolRenderers(label),\n\t\tasync execute(_toolCallId, params, signal, onUpdate) {\n\t\t\tconst client = await options.getClient();\n\t\t\tconst result = await client.callTool(tool.name, (params ?? {}) as Record<string, unknown>, {\n\t\t\t\tsignal,\n\t\t\t\ttimeoutMs: options.timeoutMs,\n\t\t\t\tonProgress: (progress) => {\n\t\t\t\t\tconst total = progress.total === undefined ? \"\" : `/${progress.total}`;\n\t\t\t\t\tconst text = progress.message ?? `Progress ${progress.progress}${total}`;\n\t\t\t\t\tonUpdate?.({ content: [{ type: \"text\", text }], details: { server, tool: tool.name } });\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn convertMcpResult(server, tool.name, result, { readableResources: options.readableResources?.() });\n\t\t},\n\t};\n}\n\n/** Renderers of calls to an MCP tool, labeled `server/tool`, also used before the tool is registered. */\nexport function createMcpToolRenderers(label: string): ToolRenderers {\n\treturn {\n\t\trenderCall(args, theme, context) {\n\t\t\tconst component = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tcomponent.setText(formatToolCallWithArgs(label, args, theme, context.expanded));\n\t\t\treturn component;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\t\tcomponent.clear();\n\t\t\tconst output = getTextOutput(result, context.showImages).trim();\n\t\t\tif (!output) return component;\n\t\t\tconst color = context.isError ? \"error\" : \"toolOutput\";\n\t\t\tconst styled = replaceTabs(output)\n\t\t\t\t.split(\"\\n\")\n\t\t\t\t.map((line) => theme.fg(color, line))\n\t\t\t\t.join(\"\\n\");\n\t\t\tcomponent.addChild(new Spacer(1));\n\t\t\tif (options.expanded) {\n\t\t\t\tcomponent.addChild(new Text(styled, 0, 0));\n\t\t\t} else {\n\t\t\t\t// Limit wrapped lines, not logical ones: MCP results are often one long JSON line.\n\t\t\t\tcomponent.addChild(\n\t\t\t\t\tnew VisualLinePreview({\n\t\t\t\t\t\ttext: styled,\n\t\t\t\t\t\tmaxVisualLines: OUTPUT_PREVIEW_LINES,\n\t\t\t\t\t\tkeep: \"start\",\n\t\t\t\t\t\tformatHint: (hidden) =>\n\t\t\t\t\t\t\t`${theme.fg(\"muted\", `... (${hidden} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tconst fullOutputPath = (result.details as McpToolDetails | undefined)?.fullOutputPath;\n\t\t\t\tif (fullOutputPath) component.addChild(new Text(theme.fg(\"muted\", `Full output: ${fullOutputPath}`), 0, 0));\n\t\t\t}\n\t\t\treturn component;\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"tools.js","sourceRoot":"","sources":["../../../src/extensions/mcp/tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAIH,OAAO,EAEN,qBAAqB,EACrB,eAAe,EAIf,uBAAuB,EACvB,iBAAiB,GACjB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AASjE,OAAO,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACnE,OAAO,EAAE,sBAAsB,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,kCAAkC,CAAC;AACtG,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AACjF,OAAO,EAAE,iBAAiB,EAAE,MAAM,uDAAuD,CAAC;AAC1F,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAG9D;;;GAGG;AACH,MAAM,UAAU,cAAc,CAAC,QAAqB;IACnD,OAAO,QAAQ,KAAK,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,QAAQ,CAAC;AACxD,CAAC;AAED,yEAAyE;AACzE,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAC/B,6DAA6D;AAC7D,OAAO,EAAE,sBAAsB,EAAE,CAAC;AASlC,4GAA4G;AAC5G,MAAM,UAAU,cAAc,CAAC,IAAyB,EAAE,SAAiB;IAC1E,OAAO,eAAe,CAAC,QAAQ,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;AACnD,CAAC;AAMD,SAAS,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AC,CAAC,CAAC,CAAC;YAC5C,CAAC;iBAAM,CAAC;gBACP,mFAAmF;gBACnF,SAAS,CAAC,QAAQ,CACjB,IAAI,iBAAiB,CAAC;oBACrB,IAAI,EAAE,MAAM;oBACZ,cAAc,EAAE,oBAAoB;oBACpC,IAAI,EAAE,OAAO;oBACb,UAAU,EAAE,CAAC,MAAM,EAAE,EAAE,CACtB,GAAG,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,QAAQ,MAAM,cAAc,CAAC,IAAI,OAAO,CAAC,kBAAkB,EAAE,WAAW,CAAC,GAAG,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,CAAC,EAAE;iBAC1H,CAAC,CACF,CAAC;gBACF,MAAM,cAAc,GAAI,MAAM,CAAC,OAAsC,EAAE,cAAc,CAAC;gBACtF,IAAI,cAAc;oBAAE,SAAS,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,gBAAgB,cAAc,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;YAC7G,CAAC;YACD,OAAO,SAAS,CAAC;QAClB,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["/**\n * Adapts MCP tools to pi tool definitions.\n *\n * Results map onto pi's model-facing content (text and images). Text over 20KB keeps its start and\n * end with the middle cut out, like Codex does, and the full text is saved to a temp file the model\n * can read. Binary resources other than images are saved to temp files too, and resource links name\n * the `read_mcp_resource` tool. Codemode scripts receive the whole `CallToolResult` without `_meta`\n * (`content` blocks as sent by the server, `structuredContent`, `isError`), never truncated: it is\n * the tool's `structuredContent`, and every MCP tool declares a `CallToolResult` output schema. MCP\n * errors (`isError`) are error results for the model, but scripts still resolve to the result.\n */\n\nimport type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { ImageContent, JsonValue, TextContent } from \"@earendil-works/pi-ai\";\nimport {\n\ttype CallToolResult,\n\tcreateMcpResultSchema,\n\tlimitMcpContent,\n\ttype McpOutputSaver,\n\ttype McpRequestOptions,\n\ttype Tool as McpTool,\n\tnormalizeMcpInputSchema,\n\ttoMcpModelContent,\n} from \"@earendil-works/pi-mcp\";\nimport { Container, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport type { TSchema } from \"typebox\";\nimport type {\n\tToolAnnotations,\n\tToolDefinition,\n\tToolExposure,\n\tToolNamespace,\n\tToolRenderers,\n} from \"../../core/extensions/types.ts\";\nimport { READ_MCP_RESOURCE_TOOL } from \"../../core/mcp-servers.ts\";\nimport { formatToolCallWithArgs, getTextOutput, replaceTabs } from \"../../core/tools/render-utils.ts\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { VisualLinePreview } from \"../../modes/interactive/components/visual-truncate.ts\";\nimport { writeOutputFile } from \"../../utils/output-files.ts\";\nimport type { McpExposure } from \"./config.ts\";\n\n/**\n * Tool exposure of an MCP exposure. `codemode` and `deferred` both leave tools out of the codemode\n * description; they differ only in which tool the MCP extension activates to reach them.\n */\nexport function toToolExposure(exposure: McpExposure): ToolExposure {\n\treturn exposure === \"codemode\" ? \"deferred\" : exposure;\n}\n\n/** Visual (wrapped) result lines shown before the output is expanded. */\nconst OUTPUT_PREVIEW_LINES = 5;\n/** Tool that reads the resources named by resource links. */\nexport { READ_MCP_RESOURCE_TOOL };\n\nexport interface McpToolDetails {\n\tserver: string;\n\ttool: string;\n\t/** Temp file with the full text output, when the model-facing text was truncated. */\n\tfullOutputPath?: string;\n}\n\n/** Saves the full text of a truncated result, or a binary resource, to a temp file and returns its path. */\nexport function saveToTempFile(data: string | Uint8Array, extension: string): Promise<string> {\n\treturn writeOutputFile(\"pi-mcp\", extension, data);\n}\n\nexport interface McpToolCaller {\n\tcallTool(name: string, args: Record<string, unknown>, options: McpRequestOptions): Promise<CallToolResult>;\n}\n\nfunction textOf(content: readonly (TextContent | ImageContent)[]): string {\n\treturn content\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n}\n\nexport interface ConvertMcpResultOptions {\n\t/** Saves truncated text and binary resources. Default: a temp file. */\n\tsaveOutput?: McpOutputSaver;\n\t/** Whether the server's resources can be read with `read_mcp_resource`, which resource links then name. */\n\treadableResources?: boolean;\n}\n\n/** Convert an MCP result. `isError` results become error results that keep the structured result. */\nexport async function convertMcpResult(\n\tserver: string,\n\ttool: string,\n\tresult: CallToolResult,\n\toptions: ConvertMcpResultOptions = {},\n): Promise<AgentToolResult<McpToolDetails>> {\n\tconst saveOutput = options.saveOutput ?? saveToTempFile;\n\tconst converted = await toMcpModelContent(server, result, {\n\t\tsaveOutput,\n\t\t...(options.readableResources ? { readResourceTool: READ_MCP_RESOURCE_TOOL } : {}),\n\t});\n\tif (result.isError && textOf(converted) === \"\") {\n\t\tconverted.push({ type: \"text\", text: `MCP tool ${server}/${tool} returned an error` });\n\t}\n\tconst { content, fullOutputPath } = await limitMcpContent(converted, saveOutput);\n\tconst { _meta: _ignored, ...scriptResult } = result;\n\treturn {\n\t\tcontent,\n\t\tdetails: { server, tool, ...(fullOutputPath ? { fullOutputPath } : {}) },\n\t\tstructuredContent: scriptResult as unknown as JsonValue,\n\t\t...(result.isError ? { isError: true } : {}),\n\t};\n}\n\nconst ANNOTATION_HINTS = [\"readOnlyHint\", \"destructiveHint\", \"idempotentHint\", \"openWorldHint\"] as const;\n\n/** The boolean hints of an MCP tool's annotations, or undefined when it has none. */\nfunction toToolAnnotations(tool: McpTool): ToolAnnotations | undefined {\n\tconst annotations: ToolAnnotations = {};\n\tfor (const hint of ANNOTATION_HINTS) {\n\t\tconst value = tool.annotations?.[hint];\n\t\tif (typeof value === \"boolean\") annotations[hint] = value;\n\t}\n\treturn Object.keys(annotations).length > 0 ? annotations : undefined;\n}\n\nexport function createMcpToolDefinition(options: {\n\tserver: string;\n\ttool: McpTool;\n\tname: string;\n\texposure: McpExposure;\n\tnamespace: ToolNamespace;\n\ttimeoutMs: number;\n\tgetClient: () => Promise<McpToolCaller>;\n\t/** Whether `read_mcp_resource` can read the server's resources. */\n\treadableResources?: () => boolean;\n}): ToolDefinition<TSchema, McpToolDetails> {\n\tconst { server, tool } = options;\n\tconst title = tool.title ?? tool.annotations?.title;\n\tconst annotations = toToolAnnotations(tool);\n\tconst label = `${server}/${tool.name}`;\n\treturn {\n\t\tname: options.name,\n\t\tlabel,\n\t\tdescription: tool.description?.trim() || title || `MCP tool ${tool.name} from server ${server}`,\n\t\t// An object schema, which is what TypeBox schemas are at runtime.\n\t\tparameters: normalizeMcpInputSchema(tool.inputSchema) as unknown as TSchema,\n\t\t// A JSON schema object, which is what TypeBox schemas are at runtime.\n\t\toutputSchema: createMcpResultSchema(tool.outputSchema) as unknown as TSchema,\n\t\texposure: toToolExposure(options.exposure),\n\t\tnamespace: options.namespace,\n\t\t...(annotations ? { annotations } : {}),\n\t\t...createMcpToolRenderers(label),\n\t\tasync execute(_toolCallId, params, signal, onUpdate) {\n\t\t\tconst client = await options.getClient();\n\t\t\tconst result = await client.callTool(tool.name, (params ?? {}) as Record<string, unknown>, {\n\t\t\t\tsignal,\n\t\t\t\ttimeoutMs: options.timeoutMs,\n\t\t\t\tonProgress: (progress) => {\n\t\t\t\t\tconst total = progress.total === undefined ? \"\" : `/${progress.total}`;\n\t\t\t\t\tconst text = progress.message ?? `Progress ${progress.progress}${total}`;\n\t\t\t\t\tonUpdate?.({ content: [{ type: \"text\", text }], details: { server, tool: tool.name } });\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn convertMcpResult(server, tool.name, result, { readableResources: options.readableResources?.() });\n\t\t},\n\t};\n}\n\n/** Renderers of calls to an MCP tool, labeled `server/tool`, also used before the tool is registered. */\nexport function createMcpToolRenderers(label: string): ToolRenderers {\n\treturn {\n\t\trenderCall(args, theme, context) {\n\t\t\tconst component = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tcomponent.setText(formatToolCallWithArgs(label, args, theme, context.expanded));\n\t\t\treturn component;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\t\tcomponent.clear();\n\t\t\tconst output = getTextOutput(result, context.showImages).trim();\n\t\t\tif (!output) return component;\n\t\t\tconst color = context.isError ? \"error\" : \"toolOutput\";\n\t\t\tconst styled = replaceTabs(output)\n\t\t\t\t.split(\"\\n\")\n\t\t\t\t.map((line) => theme.fg(color, line))\n\t\t\t\t.join(\"\\n\");\n\t\t\tcomponent.addChild(new Spacer(1));\n\t\t\tif (options.expanded) {\n\t\t\t\tcomponent.addChild(new Text(styled, 0, 0));\n\t\t\t} else {\n\t\t\t\t// Limit wrapped lines, not logical ones: MCP results are often one long JSON line.\n\t\t\t\tcomponent.addChild(\n\t\t\t\t\tnew VisualLinePreview({\n\t\t\t\t\t\ttext: styled,\n\t\t\t\t\t\tmaxVisualLines: OUTPUT_PREVIEW_LINES,\n\t\t\t\t\t\tkeep: \"start\",\n\t\t\t\t\t\tformatHint: (hidden) =>\n\t\t\t\t\t\t\t`${theme.fg(\"muted\", `... (${hidden} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tconst fullOutputPath = (result.details as McpToolDetails | undefined)?.fullOutputPath;\n\t\t\t\tif (fullOutputPath) component.addChild(new Text(theme.fg(\"muted\", `Full output: ${fullOutputPath}`), 0, 0));\n\t\t\t}\n\t\t\treturn component;\n\t\t},\n\t};\n}\n"]}
package/dist/main.d.ts CHANGED
@@ -12,5 +12,5 @@ export declare function createSessionManager(parsed: Args, cwd: string, sessionD
12
12
  export interface MainOptions {
13
13
  extensionFactories?: InlineExtension[];
14
14
  }
15
- export declare function main(args: string[], options?: MainOptions): Promise<void>;
15
+ export declare function main(cliArgs: string[], options?: MainOptions): Promise<void>;
16
16
  //# sourceMappingURL=main.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["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4elE"}
package/dist/main.js CHANGED
@@ -6,8 +6,9 @@
6
6
  */
7
7
  import { createInterface } from "node:readline";
8
8
  import { modelsAreEqual } from "@earendil-works/pi-ai";
9
- import { setCapabilityOverrides } from "@earendil-works/pi-tui";
9
+ import { setCapabilityOverrides, takeProgramResumeToken } from "@earendil-works/pi-tui";
10
10
  import chalk from "chalk";
11
+ import { applyAgentDirArg } from "./cli/agent-dir-arg.js";
11
12
  import { normalizeSessionName, parseArgs, printHelp } from "./cli/args.js";
12
13
  import { checkProviderAuth, createAuthCheckModelRuntime, getProviderCredential, } from "./cli/auth-check.js";
13
14
  import { AuthCommandError, getAuthCommandName, getAuthCommandUsage, isAuthCommandHelp, parseAuthCommand, printAuthCommandHelp, validateAuthCommandArgs, } from "./cli/auth-command.js";
@@ -28,7 +29,7 @@ import { formatNoModelsAvailableMessage } from "./core/auth-guidance.js";
28
29
  import { AuthStorage, ReadOnlyAuthStorage } from "./core/auth-storage.js";
29
30
  import { exportFromFile } from "./core/export-html/index.js";
30
31
  import { applyHttpProxySettings, configureHttpDispatcher } from "./core/http-dispatcher.js";
31
- import { resolveCliModel, resolveModelScope } from "./core/model-resolver.js";
32
+ import { resolveCliModel, resolveModelScopeWithDiagnostics } from "./core/model-resolver.js";
32
33
  import { ModelRuntime } from "./core/model-runtime.js";
33
34
  import { restoreStdout, takeOverStdout } from "./core/output-guard.js";
34
35
  import { resolveProjectTrusted } from "./core/project-trust.js";
@@ -42,6 +43,7 @@ import { hasTrustRequiringProjectResources, ProjectTrustStore } from "./core/tru
42
43
  import { builtInExtensions } from "./extensions/index.js";
43
44
  import { loadMcpCommand } from "./extensions/mcp/cli.lazy.js";
44
45
  import { runMigrations, showDeprecationWarnings } from "./migrations.js";
46
+ import { writeDiagnosticsToStderr } from "./modes/diagnostics-stderr.js";
45
47
  import { InteractiveMode, runPrintMode, runRpcMode } from "./modes/index.js";
46
48
  import { initTheme, setThemeJsonValidator, stopThemeWatcher } from "./modes/interactive/theme/theme.js";
47
49
  import { validateThemeJson } from "./modes/interactive/theme/theme-schema.js";
@@ -70,13 +72,6 @@ async function readPipedStdin() {
70
72
  process.stdin.resume();
71
73
  });
72
74
  }
73
- function reportDiagnostics(diagnostics) {
74
- for (const diagnostic of diagnostics) {
75
- const color = diagnostic.type === "error" ? chalk.red : diagnostic.type === "warning" ? chalk.yellow : chalk.dim;
76
- const prefix = diagnostic.type === "error" ? "Error: " : diagnostic.type === "warning" ? "Warning: " : "";
77
- console.error(color(`${prefix}${diagnostic.message}`));
78
- }
79
- }
80
75
  function isTruthyEnvFlag(value) {
81
76
  if (!value)
82
77
  return false;
@@ -503,8 +498,20 @@ function buildSessionOptions(parsed, scopedModels, hasExistingSession, modelRunt
503
498
  function resolveCliPaths(cwd, paths) {
504
499
  return paths?.map((value) => (isLocalPath(value) ? resolvePath(value, cwd) : value));
505
500
  }
506
- export async function main(args, options) {
501
+ export async function main(cliArgs, options) {
507
502
  resetTimings();
503
+ // First, before anything reads the agent dir, and before subcommands are recognized so the flag works with them.
504
+ // Modules have already loaded at this point: a value they cached from getAgentDir() at load ignores the flag.
505
+ const agentDirArg = applyAgentDirArg(cliArgs);
506
+ if (agentDirArg.kind === "error") {
507
+ console.error(chalk.red(`Error: ${agentDirArg.message}`));
508
+ process.exit(1);
509
+ }
510
+ const args = agentDirArg.args;
511
+ // Taken in every mode, before anything starts a child process: pi reports its own resume command, and
512
+ // shells, editors and extension processes it starts must not replace it or register commands that later
513
+ // run with the user's rights (OSC 7577).
514
+ const programResumeToken = takeProgramResumeToken();
508
515
  // Commands and startup selectors can load user-authored themes before runtime creation.
509
516
  setThemeJsonValidator(validateThemeJson);
510
517
  const extensionFactories = [...builtInExtensions, ...(options?.extensionFactories ?? [])];
@@ -599,7 +606,7 @@ export async function main(args, options) {
599
606
  time("runMigrations");
600
607
  const startupSettingsManager = SettingsManager.create(cwd, agentDir);
601
608
  const startupSettingsDiagnostics = collectSettingsDiagnostics(startupSettingsManager);
602
- // Experimental first-time setup: theme choice and analytics opt-in.
609
+ // Experimental first-time setup: analytics opt-in.
603
610
  // Runs before any runtime services are created so the chosen settings apply everywhere.
604
611
  if (appMode === "interactive" && !parsed.help && parsed.listModels === undefined && shouldRunFirstTimeSetup()) {
605
612
  await showFirstTimeSetup(startupSettingsManager);
@@ -660,6 +667,16 @@ export async function main(args, options) {
660
667
  const resolvedSkillPaths = resolveCliPaths(cwd, parsed.skills);
661
668
  const resolvedPromptTemplatePaths = resolveCliPaths(cwd, parsed.promptTemplates);
662
669
  const resolvedThemePaths = resolveCliPaths(cwd, parsed.themes);
670
+ // Interactive mode installs and refreshes packages again on /reload, /new, /resume and /fork while the TUI
671
+ // draws on the terminal, where git and npm output would corrupt its screen (#11264). Their output is
672
+ // captured, and until the TUI starts each install is announced on stderr instead.
673
+ const packageCommandOutput = appMode === "interactive" ? "capture" : "inherit";
674
+ let announcePackageInstalls = packageCommandOutput === "capture";
675
+ const onPackageProgress = (event) => {
676
+ if (announcePackageInstalls && event.type === "start" && event.message) {
677
+ console.error(chalk.dim(event.message));
678
+ }
679
+ };
663
680
  const createRuntime = async ({ cwd, agentDir, sessionManager, sessionStartEvent, projectTrustContext, }) => {
664
681
  const isInitialRuntime = sessionStartEvent === undefined;
665
682
  const projectTrustDiagnostics = [];
@@ -700,6 +717,8 @@ export async function main(args, options) {
700
717
  }
701
718
  : undefined,
702
719
  resourceLoaderOptions: {
720
+ packageCommandOutput,
721
+ onPackageProgress,
703
722
  additionalExtensionPaths: resolvedExtensionPaths,
704
723
  additionalSkillPaths: resolvedSkillPaths,
705
724
  additionalPromptTemplatePaths: resolvedPromptTemplatePaths,
@@ -730,9 +749,14 @@ export async function main(args, options) {
730
749
  })),
731
750
  ];
732
751
  const modelPatterns = parsed.models ?? settingsManager.getEnabledModels();
733
- const scopedModels = modelPatterns && modelPatterns.length > 0
734
- ? await resolveModelScope(modelPatterns, modelRuntime, { signal: AbortSignal.timeout(15_000) })
735
- : [];
752
+ const { scopedModels, diagnostics: modelScopeDiagnostics } = modelPatterns && modelPatterns.length > 0
753
+ ? await resolveModelScopeWithDiagnostics(modelPatterns, modelRuntime, {
754
+ signal: AbortSignal.timeout(15_000),
755
+ })
756
+ : { scopedModels: [], diagnostics: [] };
757
+ // Returned as diagnostics instead of printed: this factory runs again on /new, /resume and /fork,
758
+ // while the interactive TUI draws on the terminal (#11264).
759
+ diagnostics.push(...modelScopeDiagnostics);
736
760
  const { options: sessionOptions, cliThinkingFromModel, diagnostics: sessionOptionDiagnostics, } = buildSessionOptions(parsed, scopedModels, sessionManager.buildSessionContext().messages.length > 0, modelRuntime, settingsManager);
737
761
  diagnostics.push(...sessionOptionDiagnostics);
738
762
  if (parsed.apiKey) {
@@ -762,6 +786,12 @@ export async function main(args, options) {
762
786
  if (created.session.model && cliThinkingOverride) {
763
787
  created.session.setThinkingLevel(created.session.thinkingLevel);
764
788
  }
789
+ // "Could not restore model x/y. Using a/b." is set again on /resume and /fork. As a diagnostic, every
790
+ // mode reports it at startup and after each replacement. Without any model, the message is login
791
+ // guidance instead: interactive mode shows it at startup, the other modes exit with it below.
792
+ if (created.modelFallbackMessage && created.session.model) {
793
+ diagnostics.push({ type: "warning", message: created.modelFallbackMessage });
794
+ }
765
795
  return {
766
796
  ...created,
767
797
  services,
@@ -780,10 +810,14 @@ export async function main(args, options) {
780
810
  setCapabilityOverrides(settingsManager.getTerminalCapabilityOverrides());
781
811
  applyHttpProxySettings(settingsManager.getGlobalSettings().httpProxy);
782
812
  configureHttpDispatcher(settingsManager.getHttpIdleTimeoutMs());
783
- const startupDiagnostics = deduplicateDiagnostics([...startupSettingsDiagnostics, ...runtime.diagnostics]);
813
+ // Taking them marks them reported, so the modes do not report them again after a session replacement.
814
+ const startupDiagnostics = deduplicateDiagnostics([
815
+ ...startupSettingsDiagnostics,
816
+ ...runtime.takeUnreportedDiagnostics(),
817
+ ]);
784
818
  const hasRuntimeErrors = runtime.diagnostics.some((diagnostic) => diagnostic.type === "error");
785
819
  if (parsed.help) {
786
- reportDiagnostics(startupDiagnostics);
820
+ writeDiagnosticsToStderr(startupDiagnostics);
787
821
  const extensionFlags = resourceLoader
788
822
  .getExtensions()
789
823
  .extensions.flatMap((extension) => Array.from(extension.flags.values()));
@@ -791,7 +825,7 @@ export async function main(args, options) {
791
825
  process.exit(0);
792
826
  }
793
827
  if (parsed.listModels !== undefined) {
794
- reportDiagnostics(startupDiagnostics);
828
+ writeDiagnosticsToStderr(startupDiagnostics);
795
829
  const searchPattern = typeof parsed.listModels === "string" ? parsed.listModels : undefined;
796
830
  await listModels(modelRuntime, searchPattern, AbortSignal.timeout(15_000));
797
831
  process.exit(0);
@@ -815,7 +849,7 @@ export async function main(args, options) {
815
849
  }
816
850
  time("resolveModelScope");
817
851
  if (appMode !== "interactive" || hasRuntimeErrors) {
818
- reportDiagnostics(startupDiagnostics);
852
+ writeDiagnosticsToStderr(startupDiagnostics);
819
853
  }
820
854
  if (hasRuntimeErrors) {
821
855
  if (runtime.diagnostics.some((diagnostic) => diagnostic.message.includes("Failed to load extension"))) {
@@ -847,10 +881,12 @@ export async function main(args, options) {
847
881
  await runRpcMode(runtime);
848
882
  }
849
883
  else if (appMode === "interactive") {
884
+ announcePackageInstalls = false;
850
885
  const interactiveMode = new InteractiveMode(runtime, {
851
886
  migratedProviders,
852
887
  startupDiagnostics,
853
- modelFallbackMessage,
888
+ // A fallback to another model is already in startupDiagnostics.
889
+ modelFallbackMessage: session.model ? undefined : modelFallbackMessage,
854
890
  autoTrustOnReloadCwd,
855
891
  initialMessage,
856
892
  initialImages,
@@ -858,6 +894,8 @@ export async function main(args, options) {
858
894
  verbose: parsed.verbose,
859
895
  tuiMode: parsed.tuiMode,
860
896
  initialThemeSetting: parsed.useTheme,
897
+ programResumeToken,
898
+ programResumeFlags: parsed.resumeFlags,
861
899
  });
862
900
  if (startupBenchmark) {
863
901
  await interactiveMode.init();