@astralyn/pi 1.1.0 → 1.3.0

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 (290) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/dist/bundle/chunks/anthropic-messages-MSB6JBS2.js +6 -0
  3. package/dist/bundle/chunks/{azure-openai-responses-CH74HGP4.js → azure-openai-responses-ATZ757I2.js} +1 -1
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +14 -11
  5. package/dist/bundle/chunks/{chunk-H35KWBT5.js → chunk-4XZYHGVN.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-MAC4N3BW.js → chunk-7UBIBLPN.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-KAC2YPTW.js → chunk-J75WV3FL.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-EJEOEBSJ.js → chunk-KSCGI7JW.js} +2 -2
  9. package/dist/bundle/chunks/chunk-LUYFHZ6W.js +11 -0
  10. package/dist/bundle/chunks/{chunk-TEAAYBTS.js → chunk-NM2KGRFS.js} +1 -1
  11. package/dist/bundle/chunks/chunk-Q74S7ILH.js +2 -0
  12. package/dist/bundle/chunks/{chunk-QLU3LESZ.js → chunk-QDDSFJ35.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-D3XW5X3Z.js → chunk-R2KES7LS.js} +175 -244
  14. package/dist/bundle/chunks/{chunk-5B3S5DVL.js → chunk-SA2AQYEI.js} +5 -2
  15. package/dist/bundle/chunks/{chunk-C2ARIVS3.js → chunk-YHRHHXFG.js} +1 -1
  16. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-XO45ZT3V.js → cloudflare-workers-ai-system-one-HGOVFZDC.js} +1 -1
  17. package/dist/bundle/chunks/codemode-worker.js +17 -9
  18. package/dist/bundle/chunks/github-copilot.js +1 -1
  19. package/dist/bundle/chunks/{google-generative-ai-VVO64ZRQ.js → google-generative-ai-QRLQ4MCJ.js} +1 -1
  20. package/dist/bundle/chunks/{google-vertex-LKS5NUHA.js → google-vertex-L3T6EGTL.js} +1 -1
  21. package/dist/bundle/chunks/mistral-conversations-6E6SS3WF.js +5 -0
  22. package/dist/bundle/chunks/openai-codex-responses-4GUO76XJ.js +10 -0
  23. package/dist/bundle/chunks/{openai-completions-7HTTU6FH.js → openai-completions-O4TKZCIM.js} +1 -1
  24. package/dist/bundle/chunks/{openai-decisions-776H4VDZ.js → openai-decisions-TVCDIPZX.js} +1 -1
  25. package/dist/bundle/chunks/openai-responses-VBQKJFNO.js +3 -0
  26. package/dist/bundle/chunks/{pi-messages-ZXNERWJG.js → pi-messages-3POWZ43C.js} +1 -1
  27. package/dist/bundle/chunks/{typesafe-system-one-2DQLG4R2.js → typesafe-system-one-LWPJYTJP.js} +1 -1
  28. package/dist/bundle/chunks/{virtual-modules-2NHGQRS6.js → virtual-modules-TG53AOL4.js} +1 -1
  29. package/dist/bundle/cli.js +1 -1
  30. package/dist/bundle/index.js +1 -1
  31. package/dist/bundle/rpc-entry.js +1 -1
  32. package/dist/cli/credential-print.d.ts.map +1 -1
  33. package/dist/cli/credential-print.js +4 -4
  34. package/dist/cli/credential-print.js.map +1 -1
  35. package/dist/core/agent-session.d.ts +18 -3
  36. package/dist/core/agent-session.d.ts.map +1 -1
  37. package/dist/core/agent-session.js +98 -62
  38. package/dist/core/agent-session.js.map +1 -1
  39. package/dist/core/auth-storage.d.ts.map +1 -1
  40. package/dist/core/auth-storage.js +20 -13
  41. package/dist/core/auth-storage.js.map +1 -1
  42. package/dist/core/bug-report.d.ts +9 -1
  43. package/dist/core/bug-report.d.ts.map +1 -1
  44. package/dist/core/compaction/utils.d.ts +6 -0
  45. package/dist/core/compaction/utils.d.ts.map +1 -1
  46. package/dist/core/compaction/utils.js +7 -8
  47. package/dist/core/compaction/utils.js.map +1 -1
  48. package/dist/core/export-html/template.js +21 -16
  49. package/dist/core/extensions/index.d.ts +1 -1
  50. package/dist/core/extensions/index.d.ts.map +1 -1
  51. package/dist/core/extensions/index.js.map +1 -1
  52. package/dist/core/extensions/runner.d.ts +4 -2
  53. package/dist/core/extensions/runner.d.ts.map +1 -1
  54. package/dist/core/extensions/runner.js +2 -3
  55. package/dist/core/extensions/runner.js.map +1 -1
  56. package/dist/core/extensions/types.d.ts +31 -7
  57. package/dist/core/extensions/types.d.ts.map +1 -1
  58. package/dist/core/extensions/types.js.map +1 -1
  59. package/dist/core/key-id-schema.d.ts +6 -0
  60. package/dist/core/key-id-schema.d.ts.map +1 -0
  61. package/dist/core/key-id-schema.js +16 -0
  62. package/dist/core/key-id-schema.js.map +1 -0
  63. package/dist/core/keybinding-registry.d.ts +4 -3
  64. package/dist/core/keybinding-registry.d.ts.map +1 -1
  65. package/dist/core/keybinding-registry.js +4 -3
  66. package/dist/core/keybinding-registry.js.map +1 -1
  67. package/dist/core/keybindings-schema.d.ts +4 -0
  68. package/dist/core/keybindings-schema.d.ts.map +1 -0
  69. package/dist/core/keybindings-schema.js +16 -0
  70. package/dist/core/keybindings-schema.js.map +1 -0
  71. package/dist/core/keybindings.d.ts +258 -81
  72. package/dist/core/keybindings.d.ts.map +1 -1
  73. package/dist/core/keybindings.js +27 -24
  74. package/dist/core/keybindings.js.map +1 -1
  75. package/dist/core/model-config.d.ts +729 -180
  76. package/dist/core/model-config.d.ts.map +1 -1
  77. package/dist/core/model-config.js +18 -179
  78. package/dist/core/model-config.js.map +1 -1
  79. package/dist/core/model-resolver.d.ts +56 -43
  80. package/dist/core/model-resolver.d.ts.map +1 -1
  81. package/dist/core/model-resolver.js +247 -352
  82. package/dist/core/model-resolver.js.map +1 -1
  83. package/dist/core/model-runtime.d.ts.map +1 -1
  84. package/dist/core/model-runtime.js +11 -6
  85. package/dist/core/model-runtime.js.map +1 -1
  86. package/dist/core/package-manager.d.ts.map +1 -1
  87. package/dist/core/package-manager.js +3 -3
  88. package/dist/core/package-manager.js.map +1 -1
  89. package/dist/core/project-trust.d.ts.map +1 -1
  90. package/dist/core/project-trust.js +2 -1
  91. package/dist/core/project-trust.js.map +1 -1
  92. package/dist/core/prompt-templates.d.ts.map +1 -1
  93. package/dist/core/prompt-templates.js +7 -2
  94. package/dist/core/prompt-templates.js.map +1 -1
  95. package/dist/core/remote-catalog-provider.d.ts +12 -1
  96. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  97. package/dist/core/remote-catalog-provider.js +82 -24
  98. package/dist/core/remote-catalog-provider.js.map +1 -1
  99. package/dist/core/resource-loader.d.ts.map +1 -1
  100. package/dist/core/resource-loader.js +7 -2
  101. package/dist/core/resource-loader.js.map +1 -1
  102. package/dist/core/settings-defaults.d.ts +66 -0
  103. package/dist/core/settings-defaults.d.ts.map +1 -0
  104. package/dist/core/settings-defaults.js +67 -0
  105. package/dist/core/settings-defaults.js.map +1 -0
  106. package/dist/core/settings-manager.d.ts +6 -149
  107. package/dist/core/settings-manager.d.ts.map +1 -1
  108. package/dist/core/settings-manager.js +59 -44
  109. package/dist/core/settings-manager.js.map +1 -1
  110. package/dist/core/settings-schema.d.ts +233 -0
  111. package/dist/core/settings-schema.d.ts.map +1 -0
  112. package/dist/core/settings-schema.js +298 -0
  113. package/dist/core/settings-schema.js.map +1 -0
  114. package/dist/core/slash-commands.js +1 -1
  115. package/dist/core/slash-commands.js.map +1 -1
  116. package/dist/core/tools/render-utils.d.ts +20 -0
  117. package/dist/core/tools/render-utils.d.ts.map +1 -1
  118. package/dist/core/tools/render-utils.js +67 -0
  119. package/dist/core/tools/render-utils.js.map +1 -1
  120. package/dist/core/tools/renderers/bash.d.ts.map +1 -1
  121. package/dist/core/tools/renderers/bash.js +21 -50
  122. package/dist/core/tools/renderers/bash.js.map +1 -1
  123. package/dist/core/tools/renderers/read.d.ts.map +1 -1
  124. package/dist/core/tools/renderers/read.js +7 -11
  125. package/dist/core/tools/renderers/read.js.map +1 -1
  126. package/dist/extensions/btw/keybindings.d.ts +2 -2
  127. package/dist/extensions/btw/keybindings.d.ts.map +1 -1
  128. package/dist/extensions/btw/keybindings.js.map +1 -1
  129. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  130. package/dist/extensions/codemode/execute.js +76 -45
  131. package/dist/extensions/codemode/execute.js.map +1 -1
  132. package/dist/extensions/codemode/index.d.ts.map +1 -1
  133. package/dist/extensions/codemode/index.js +3 -7
  134. package/dist/extensions/codemode/index.js.map +1 -1
  135. package/dist/extensions/codemode/renderer.d.ts +2 -2
  136. package/dist/extensions/codemode/renderer.d.ts.map +1 -1
  137. package/dist/extensions/codemode/renderer.js +9 -3
  138. package/dist/extensions/codemode/renderer.js.map +1 -1
  139. package/dist/extensions/codemode/tool.d.ts +6 -12
  140. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  141. package/dist/extensions/codemode/tool.js +44 -32
  142. package/dist/extensions/codemode/tool.js.map +1 -1
  143. package/dist/extensions/list-keybindings.d.ts +2 -2
  144. package/dist/extensions/list-keybindings.d.ts.map +1 -1
  145. package/dist/extensions/list-keybindings.js.map +1 -1
  146. package/dist/extensions/mcp/cli.js +5 -8
  147. package/dist/extensions/mcp/cli.js.map +1 -1
  148. package/dist/extensions/mcp/index.d.ts.map +1 -1
  149. package/dist/extensions/mcp/index.js +25 -34
  150. package/dist/extensions/mcp/index.js.map +1 -1
  151. package/dist/extensions/mcp/resources.d.ts +0 -6
  152. package/dist/extensions/mcp/resources.d.ts.map +1 -1
  153. package/dist/extensions/mcp/resources.js +1 -1
  154. package/dist/extensions/mcp/resources.js.map +1 -1
  155. package/dist/extensions/mcp/runtime.d.ts +3 -6
  156. package/dist/extensions/mcp/runtime.d.ts.map +1 -1
  157. package/dist/extensions/mcp/runtime.js +4 -39
  158. package/dist/extensions/mcp/runtime.js.map +1 -1
  159. package/dist/extensions/mcp/tools.d.ts +2 -3
  160. package/dist/extensions/mcp/tools.d.ts.map +1 -1
  161. package/dist/extensions/mcp/tools.js +62 -6
  162. package/dist/extensions/mcp/tools.js.map +1 -1
  163. package/dist/extensions/provider/keybindings.d.ts +2 -2
  164. package/dist/extensions/provider/keybindings.d.ts.map +1 -1
  165. package/dist/extensions/provider/keybindings.js.map +1 -1
  166. package/dist/extensions/search/code-search.d.ts +0 -2
  167. package/dist/extensions/search/code-search.d.ts.map +1 -1
  168. package/dist/extensions/search/code-search.js +2 -2
  169. package/dist/extensions/search/code-search.js.map +1 -1
  170. package/dist/extensions/search/command.js +2 -2
  171. package/dist/extensions/search/command.js.map +1 -1
  172. package/dist/extensions/search/index.d.ts.map +1 -1
  173. package/dist/extensions/search/index.js +14 -11
  174. package/dist/extensions/search/index.js.map +1 -1
  175. package/dist/extensions/search/workspace.d.ts +11 -10
  176. package/dist/extensions/search/workspace.d.ts.map +1 -1
  177. package/dist/extensions/search/workspace.js +259 -141
  178. package/dist/extensions/search/workspace.js.map +1 -1
  179. package/dist/extensions/tool-search/index.d.ts.map +1 -1
  180. package/dist/extensions/tool-search/index.js +1 -6
  181. package/dist/extensions/tool-search/index.js.map +1 -1
  182. package/dist/extensions/tool-search/tool.d.ts +0 -2
  183. package/dist/extensions/tool-search/tool.d.ts.map +1 -1
  184. package/dist/extensions/tool-search/tool.js +2 -4
  185. package/dist/extensions/tool-search/tool.js.map +1 -1
  186. package/dist/index.d.ts +2 -1
  187. package/dist/index.d.ts.map +1 -1
  188. package/dist/index.js +1 -0
  189. package/dist/index.js.map +1 -1
  190. package/dist/main.d.ts.map +1 -1
  191. package/dist/main.js +4 -3
  192. package/dist/main.js.map +1 -1
  193. package/dist/modes/interactive/components/settings-selector.d.ts +3 -1
  194. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  195. package/dist/modes/interactive/components/settings-selector.js +13 -2
  196. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  197. package/dist/modes/interactive/components/status-indicator.d.ts +1 -1
  198. package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
  199. package/dist/modes/interactive/components/status-indicator.js +2 -2
  200. package/dist/modes/interactive/components/status-indicator.js.map +1 -1
  201. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  202. package/dist/modes/interactive/components/tree-selector.js +2 -9
  203. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  204. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  205. package/dist/modes/interactive/interactive-mode.js +20 -8
  206. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  207. package/dist/modes/interactive/session-share.d.ts.map +1 -1
  208. package/dist/modes/interactive/session-share.js +9 -2
  209. package/dist/modes/interactive/session-share.js.map +1 -1
  210. package/dist/modes/interactive/tasks/layout.d.ts +2 -0
  211. package/dist/modes/interactive/tasks/layout.d.ts.map +1 -1
  212. package/dist/modes/interactive/tasks/layout.js +32 -6
  213. package/dist/modes/interactive/tasks/layout.js.map +1 -1
  214. package/dist/modes/interactive/tasks/manager.d.ts.map +1 -1
  215. package/dist/modes/interactive/tasks/manager.js +20 -2
  216. package/dist/modes/interactive/tasks/manager.js.map +1 -1
  217. package/dist/modes/interactive/theme/dark.json +1 -1
  218. package/dist/modes/interactive/theme/light.json +1 -1
  219. package/dist/modes/interactive/theme/theme-schema.d.ts +28 -0
  220. package/dist/modes/interactive/theme/theme-schema.d.ts.map +1 -0
  221. package/dist/modes/interactive/theme/theme-schema.js +105 -0
  222. package/dist/modes/interactive/theme/theme-schema.js.map +1 -0
  223. package/dist/modes/interactive/theme/theme-tokens.d.ts +257 -0
  224. package/dist/modes/interactive/theme/theme-tokens.d.ts.map +1 -0
  225. package/dist/modes/interactive/theme/theme-tokens.js +94 -0
  226. package/dist/modes/interactive/theme/theme-tokens.js.map +1 -0
  227. package/dist/modes/interactive/theme/theme.d.ts +13 -16
  228. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  229. package/dist/modes/interactive/theme/theme.js +23 -31
  230. package/dist/modes/interactive/theme/theme.js.map +1 -1
  231. package/dist/modes/print-mode.d.ts.map +1 -1
  232. package/dist/modes/print-mode.js +4 -0
  233. package/dist/modes/print-mode.js.map +1 -1
  234. package/dist/utils/clipboard.d.ts.map +1 -1
  235. package/dist/utils/clipboard.js +6 -1
  236. package/dist/utils/clipboard.js.map +1 -1
  237. package/docs/bundled/extensions/search.md +2 -1
  238. package/docs/bundled/tasks.md +1 -1
  239. package/docs/codemode.md +2 -1
  240. package/docs/compaction.md +2 -2
  241. package/docs/development.md +0 -13
  242. package/docs/docs.json +12 -0
  243. package/docs/environment-variables.md +2 -3
  244. package/docs/extensions.md +11 -5
  245. package/docs/keybindings.md +1 -0
  246. package/docs/llama-cpp.md +1 -1
  247. package/docs/mcp.md +1 -1
  248. package/docs/models.md +1 -0
  249. package/docs/nvidia-rtx-llama-cpp.md +96 -0
  250. package/docs/providers.md +17 -1
  251. package/docs/sdk.md +0 -27
  252. package/docs/sessions.md +1 -1
  253. package/docs/settings.md +4 -3
  254. package/docs/themes.md +4 -2
  255. package/docs/tui.md +1 -1
  256. package/docs/usage.md +7 -5
  257. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  258. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  259. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  260. package/examples/extensions/dynamic-resources/dynamic.json +1 -1
  261. package/examples/extensions/gondolin/package-lock.json +2 -2
  262. package/examples/extensions/gondolin/package.json +1 -1
  263. package/examples/extensions/minimal-mode.ts +4 -5
  264. package/examples/extensions/overlay-test.ts +2 -2
  265. package/examples/extensions/plan-mode/index.ts +6 -2
  266. package/examples/extensions/sandbox/package-lock.json +2 -2
  267. package/examples/extensions/sandbox/package.json +1 -1
  268. package/examples/extensions/with-deps/package-lock.json +2 -2
  269. package/examples/extensions/with-deps/package.json +1 -1
  270. package/npm-shrinkwrap.json +151 -199
  271. package/package.json +8 -20
  272. package/schemas/keybindings.schema.json +453 -0
  273. package/schemas/models.schema.json +1157 -0
  274. package/schemas/settings.schema.json +800 -0
  275. package/schemas/theme.schema.json +365 -0
  276. package/dist/bundle/chunks/anthropic-messages-3K3DWVY6.js +0 -6
  277. package/dist/bundle/chunks/chunk-3MMB5I7J.js +0 -11
  278. package/dist/bundle/chunks/mistral-conversations-NJUOG4ET.js +0 -5
  279. package/dist/bundle/chunks/openai-codex-responses-TZWBTTYM.js +0 -10
  280. package/dist/bundle/chunks/openai-responses-7A6BAQ5X.js +0 -3
  281. package/dist/modes/interactive/theme/theme-json.d.ts +0 -85
  282. package/dist/modes/interactive/theme/theme-json.d.ts.map +0 -1
  283. package/dist/modes/interactive/theme/theme-json.js +0 -132
  284. package/dist/modes/interactive/theme/theme-json.js.map +0 -1
  285. package/dist/modes/interactive/theme/theme-schema.json +0 -361
  286. package/examples/plugins/pi-example-plugin/README.md +0 -38
  287. package/examples/plugins/pi-example-plugin/package.json +0 -10
  288. package/examples/plugins/pi-example-plugin/src/contract.ts +0 -13
  289. package/examples/plugins/pi-example-plugin/src/session.ts +0 -24
  290. package/examples/plugins/pi-example-plugin/src/tui.ts +0 -31
@@ -3,11 +3,11 @@
3
3
  *
4
4
  * The call shows the script; the result lists the nested tool calls with their status as they
5
5
  * run and the cost of its model calls, followed by the script output without the "Script completed"
6
- * header. Nested calls are not
7
- * separate tool rows because they never reach the model as tool calls.
6
+ * header, and the time the script has been running (`Elapsed`) or took (`Took`), like bash rows.
7
+ * Nested calls are not separate tool rows because they never reach the model as tool calls.
8
8
  */
9
9
  import { Container, Spacer, Text } from "@earendil-works/pi-tui";
10
- import { getTextOutput, replaceTabs, str } from "../../core/tools/render-utils.js";
10
+ import { getTextOutput, replaceTabs, startToolTimer, str, toolTimerText } from "../../core/tools/render-utils.js";
11
11
  import { keyHint } from "../../modes/interactive/components/keybinding-hints.js";
12
12
  import { VisualLinePreview } from "../../modes/interactive/components/visual-truncate.js";
13
13
  import { highlightCode } from "../../modes/interactive/theme/theme.js";
@@ -58,6 +58,7 @@ function formatCall(call, theme, expanded) {
58
58
  }
59
59
  export const codemodeRenderers = {
60
60
  renderCall(args, theme, context) {
61
+ startToolTimer(context);
61
62
  // The code includes the `// @options:` line, so options show as part of the script.
62
63
  const code = str(args?.code);
63
64
  const title = theme.fg("toolTitle", theme.bold("codemode"));
@@ -82,6 +83,7 @@ export const codemodeRenderers = {
82
83
  return component;
83
84
  },
84
85
  renderResult(result, options, theme, context) {
86
+ const timerText = toolTimerText(context, options.isPartial);
85
87
  const component = context.lastComponent ?? new Container();
86
88
  component.clear();
87
89
  const calls = result.details?.calls ?? [];
@@ -131,6 +133,10 @@ export const codemodeRenderers = {
131
133
  component.addChild(new Text(theme.fg("muted", `Full output: ${fullOutputPath}`), 0, 0));
132
134
  }
133
135
  }
136
+ if (timerText) {
137
+ component.addChild(new Spacer(1));
138
+ component.addChild(new Text(theme.fg("muted", timerText), 0, 0));
139
+ }
134
140
  return component;
135
141
  },
136
142
  };
@@ -1 +1 @@
1
- {"version":3,"file":"renderer.js","sourceRoot":"","sources":["../../../src/extensions/codemode/renderer.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAEjE,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,GAAG,EAAE,MAAM,kCAAkC,CAAC;AACnF,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AACjF,OAAO,EAAE,iBAAiB,EAAE,MAAM,uDAAuD,CAAC;AAC1F,OAAO,EAAE,aAAa,EAAc,MAAM,wCAAwC,CAAC;AAGnF,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAC9B,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAC7B,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAC/B,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAChC,MAAM,aAAa,GAAG,kEAAkE,CAAC;AAEzF,SAAS,UAAU,CAAC,KAAY,EAAE,MAAc,EAAE,IAAY;IAC7D,OAAO,GAAG,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,QAAQ,MAAM,SAAS,IAAI,GAAG,CAAC,IAAI,OAAO,CAAC,kBAAkB,EAAE,WAAW,CAAC,GAAG,KAAK,CAAC,EAAE,CAAC,O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iB,CAAC;oBACrB,IAAI,EAAE,MAAM;oBACZ,cAAc,EAAE,oBAAoB;oBACpC,IAAI,EAAE,OAAO;oBACb,UAAU,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC;iBAC1D,CAAC,CACF,CAAC;gBACF,uFAAuF;gBACvF,MAAM,cAAc,GAAG,MAAM,CAAC,OAAO,EAAE,cAAc,CAAC;gBACtD,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;QACF,CAAC;QACD,OAAO,SAAS,CAAC;IAClB,CAAC;CACD,CAAC","sourcesContent":["/**\n * Presentation for the codemode tool.\n *\n * The call shows the script; the result lists the nested tool calls with their status as they\n * run and the cost of its model calls, followed by the script output without the \"Script completed\"\n * header. Nested calls are not\n * separate tool rows because they never reach the model as tool calls.\n */\n\nimport { Container, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport type { ToolDefinition } from \"../../core/extensions/types.ts\";\nimport { getTextOutput, replaceTabs, str } 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 { highlightCode, type Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { CodemodeNestedCall, CodemodeToolDetails } from \"./tool.ts\";\n\nconst CODE_PREVIEW_LINES = 10;\nconst CALL_PREVIEW_COUNT = 8;\nconst OUTPUT_PREVIEW_LINES = 5;\nconst COLLAPSED_ARGS_CHARS = 80;\nconst SCRIPT_HEADER = /^Script (completed|failed)\\nWall time [\\d.]+ seconds\\nOutput:\\n$/;\n\nfunction expandHint(theme: Theme, hidden: number, noun: string): string {\n\treturn `${theme.fg(\"muted\", `... (${hidden} more ${noun},`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n}\n\nfunction formatDuration(ms: number | undefined): string {\n\tif (ms === undefined) return \"\";\n\treturn ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(1)}s`;\n}\n\n/** Cents for larger amounts, two significant digits for the fractions of a cent classifier calls cost. */\nfunction formatCost(cost: number): string {\n\treturn `$${cost >= 0.01 ? cost.toFixed(2) : cost.toPrecision(2)}`;\n}\n\nfunction statusIcon(call: CodemodeNestedCall, theme: Theme): string {\n\tswitch (call.status) {\n\t\tcase \"running\":\n\t\t\treturn theme.fg(\"warning\", \"…\");\n\t\tcase \"ok\":\n\t\t\treturn theme.fg(\"success\", \"✓\");\n\t\tcase \"error\":\n\t\t\treturn theme.fg(\"error\", \"✗\");\n\t\tcase \"cancelled\":\n\t\t\treturn theme.fg(\"muted\", \"⊘\");\n\t}\n}\n\nfunction formatCall(call: CodemodeNestedCall, theme: Theme, expanded: boolean): string {\n\tconst args =\n\t\t!expanded && call.args.length > COLLAPSED_ARGS_CHARS\n\t\t\t? `${call.args.slice(0, COLLAPSED_ARGS_CHARS - 3)}...`\n\t\t\t: call.args;\n\tconst duration = formatDuration(call.durationMs);\n\tlet line = `${statusIcon(call, theme)} ${theme.fg(\"toolTitle\", call.name)}`;\n\tif (args) line += ` ${theme.fg(\"muted\", args)}`;\n\tif (duration) line += ` ${theme.fg(\"dim\", duration)}`;\n\tif (call.cost) line += ` ${theme.fg(\"dim\", formatCost(call.cost))}`;\n\tif (expanded && call.error) line += `\\n ${theme.fg(\"error\", call.error.split(\"\\n\").join(\"\\n \"))}`;\n\treturn line;\n}\n\nexport const codemodeRenderers: Pick<\n\tToolDefinition<any, CodemodeToolDetails | undefined>,\n\t\"renderCall\" | \"renderResult\"\n> = {\n\trenderCall(args, theme, context) {\n\t\t// The code includes the `// @options:` line, so options show as part of the script.\n\t\tconst code = str((args as { code?: unknown } | undefined)?.code);\n\t\tconst title = theme.fg(\"toolTitle\", theme.bold(\"codemode\"));\n\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\tcomponent.clear();\n\t\tif (code === null) {\n\t\t\tcomponent.addChild(new Text(`${title} ${theme.fg(\"error\", \"[invalid arg]\")}`, 0, 0));\n\t\t\treturn component;\n\t\t}\n\t\tcomponent.addChild(new Text(title, 0, 0));\n\t\tif (code) {\n\t\t\tconst highlighted = highlightCode(replaceTabs(code.replace(/\\r/g, \"\").trimEnd()), \"javascript\").join(\"\\n\");\n\t\t\tcomponent.addChild(\n\t\t\t\tcontext.expanded\n\t\t\t\t\t? new Text(highlighted, 0, 0)\n\t\t\t\t\t: new VisualLinePreview({\n\t\t\t\t\t\t\ttext: highlighted,\n\t\t\t\t\t\t\tmaxVisualLines: CODE_PREVIEW_LINES,\n\t\t\t\t\t\t\tkeep: \"start\",\n\t\t\t\t\t\t\tformatHint: (hidden) => expandHint(theme, hidden, \"lines\"),\n\t\t\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\treturn component;\n\t},\n\trenderResult(result, options, theme, context) {\n\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\tcomponent.clear();\n\t\tconst calls = result.details?.calls ?? [];\n\t\tif (calls.length > 0) {\n\t\t\tconst shown = options.expanded ? calls : calls.slice(-CALL_PREVIEW_COUNT);\n\t\t\tconst lines = shown.map((call) => formatCall(call, theme, options.expanded));\n\t\t\tif (shown.length < calls.length) {\n\t\t\t\tlines.unshift(\n\t\t\t\t\t`${theme.fg(\"muted\", `... (${calls.length - shown.length} earlier calls,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Collapsed rows hide earlier calls, so the total covers every call.\n\t\t\tconst priced = calls.filter((call) => call.cost);\n\t\t\tif (priced.length > 1) {\n\t\t\t\tconst total = priced.reduce((sum, call) => sum + (call.cost ?? 0), 0);\n\t\t\t\tlines.push(theme.fg(\"muted\", `Model calls: ${formatCost(total)}`));\n\t\t\t}\n\t\t\tcomponent.addChild(new Spacer(1));\n\t\t\tcomponent.addChild(new Text(lines.join(\"\\n\"), 0, 0));\n\t\t}\n\n\t\t// Drop the \"Script completed\\nWall time ...\\nOutput:\\n\" header. Rejected input (invalid options)\n\t\t// has no header.\n\t\tconst [first, ...rest] = result.content;\n\t\tconst hasHeader = first?.type === \"text\" && SCRIPT_HEADER.test(first.text);\n\t\tconst output = options.isPartial\n\t\t\t? \"\"\n\t\t\t: getTextOutput({ ...result, content: hasHeader ? rest : result.content }, context.showImages).trim();\n\t\tif (output) {\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: script output is 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) => expandHint(theme, hidden, \"lines\"),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\t// The collapsed preview hides the truncation notice at the end, so name the file here.\n\t\t\t\tconst fullOutputPath = result.details?.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}\n\t\treturn component;\n\t},\n};\n"]}
1
+ {"version":3,"file":"renderer.js","sourceRoot":"","sources":["../../../src/extensions/codemode/renderer.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;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,EAAE,CAAC,OAAO,EAAE,gBAAgB,cAAc,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;YAC7G,CAAC;QACF,CAAC;QACD,IAAI,SAAS,EAAE,CAAC;YACf,SAAS,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;YAClC,SAAS,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,SAAS,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;QAClE,CAAC;QACD,OAAO,SAAS,CAAC;IAClB,CAAC;CACD,CAAC","sourcesContent":["/**\n * Presentation for the codemode tool.\n *\n * The call shows the script; the result lists the nested tool calls with their status as they\n * run and the cost of its model calls, followed by the script output without the \"Script completed\"\n * header, and the time the script has been running (`Elapsed`) or took (`Took`), like bash rows.\n * Nested calls are not separate tool rows because they never reach the model as tool calls.\n */\n\nimport { Container, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport type { ToolDefinition } from \"../../core/extensions/types.ts\";\nimport { getTextOutput, replaceTabs, startToolTimer, str, toolTimerText } 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 { highlightCode, type Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { CodemodeNestedCall, CodemodeToolDetails } from \"./tool.ts\";\n\nconst CODE_PREVIEW_LINES = 10;\nconst CALL_PREVIEW_COUNT = 8;\nconst OUTPUT_PREVIEW_LINES = 5;\nconst COLLAPSED_ARGS_CHARS = 80;\nconst SCRIPT_HEADER = /^Script (completed|failed)\\nWall time [\\d.]+ seconds\\nOutput:\\n$/;\n\nfunction expandHint(theme: Theme, hidden: number, noun: string): string {\n\treturn `${theme.fg(\"muted\", `... (${hidden} more ${noun},`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n}\n\nfunction formatDuration(ms: number | undefined): string {\n\tif (ms === undefined) return \"\";\n\treturn ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(1)}s`;\n}\n\n/** Cents for larger amounts, two significant digits for the fractions of a cent classifier calls cost. */\nfunction formatCost(cost: number): string {\n\treturn `$${cost >= 0.01 ? cost.toFixed(2) : cost.toPrecision(2)}`;\n}\n\nfunction statusIcon(call: CodemodeNestedCall, theme: Theme): string {\n\tswitch (call.status) {\n\t\tcase \"running\":\n\t\t\treturn theme.fg(\"warning\", \"…\");\n\t\tcase \"ok\":\n\t\t\treturn theme.fg(\"success\", \"✓\");\n\t\tcase \"error\":\n\t\t\treturn theme.fg(\"error\", \"✗\");\n\t\tcase \"cancelled\":\n\t\t\treturn theme.fg(\"muted\", \"⊘\");\n\t}\n}\n\nfunction formatCall(call: CodemodeNestedCall, theme: Theme, expanded: boolean): string {\n\tconst args =\n\t\t!expanded && call.args.length > COLLAPSED_ARGS_CHARS\n\t\t\t? `${call.args.slice(0, COLLAPSED_ARGS_CHARS - 3)}...`\n\t\t\t: call.args;\n\tconst duration = formatDuration(call.durationMs);\n\tlet line = `${statusIcon(call, theme)} ${theme.fg(\"toolTitle\", call.name)}`;\n\tif (args) line += ` ${theme.fg(\"muted\", args)}`;\n\tif (duration) line += ` ${theme.fg(\"dim\", duration)}`;\n\tif (call.cost) line += ` ${theme.fg(\"dim\", formatCost(call.cost))}`;\n\tif (expanded && call.error) line += `\\n ${theme.fg(\"error\", call.error.split(\"\\n\").join(\"\\n \"))}`;\n\treturn line;\n}\n\nexport const codemodeRenderers: Pick<\n\tToolDefinition<any, CodemodeToolDetails | undefined>,\n\t\"renderCall\" | \"renderResult\"\n> = {\n\trenderCall(args, theme, context) {\n\t\tstartToolTimer(context);\n\t\t// The code includes the `// @options:` line, so options show as part of the script.\n\t\tconst code = str((args as { code?: unknown } | undefined)?.code);\n\t\tconst title = theme.fg(\"toolTitle\", theme.bold(\"codemode\"));\n\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\tcomponent.clear();\n\t\tif (code === null) {\n\t\t\tcomponent.addChild(new Text(`${title} ${theme.fg(\"error\", \"[invalid arg]\")}`, 0, 0));\n\t\t\treturn component;\n\t\t}\n\t\tcomponent.addChild(new Text(title, 0, 0));\n\t\tif (code) {\n\t\t\tconst highlighted = highlightCode(replaceTabs(code.replace(/\\r/g, \"\").trimEnd()), \"javascript\").join(\"\\n\");\n\t\t\tcomponent.addChild(\n\t\t\t\tcontext.expanded\n\t\t\t\t\t? new Text(highlighted, 0, 0)\n\t\t\t\t\t: new VisualLinePreview({\n\t\t\t\t\t\t\ttext: highlighted,\n\t\t\t\t\t\t\tmaxVisualLines: CODE_PREVIEW_LINES,\n\t\t\t\t\t\t\tkeep: \"start\",\n\t\t\t\t\t\t\tformatHint: (hidden) => expandHint(theme, hidden, \"lines\"),\n\t\t\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\treturn component;\n\t},\n\trenderResult(result, options, theme, context) {\n\t\tconst timerText = toolTimerText(context, options.isPartial);\n\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\tcomponent.clear();\n\t\tconst calls = result.details?.calls ?? [];\n\t\tif (calls.length > 0) {\n\t\t\tconst shown = options.expanded ? calls : calls.slice(-CALL_PREVIEW_COUNT);\n\t\t\tconst lines = shown.map((call) => formatCall(call, theme, options.expanded));\n\t\t\tif (shown.length < calls.length) {\n\t\t\t\tlines.unshift(\n\t\t\t\t\t`${theme.fg(\"muted\", `... (${calls.length - shown.length} earlier calls,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Collapsed rows hide earlier calls, so the total covers every call.\n\t\t\tconst priced = calls.filter((call) => call.cost);\n\t\t\tif (priced.length > 1) {\n\t\t\t\tconst total = priced.reduce((sum, call) => sum + (call.cost ?? 0), 0);\n\t\t\t\tlines.push(theme.fg(\"muted\", `Model calls: ${formatCost(total)}`));\n\t\t\t}\n\t\t\tcomponent.addChild(new Spacer(1));\n\t\t\tcomponent.addChild(new Text(lines.join(\"\\n\"), 0, 0));\n\t\t}\n\n\t\t// Drop the \"Script completed\\nWall time ...\\nOutput:\\n\" header. Rejected input (invalid options)\n\t\t// has no header.\n\t\tconst [first, ...rest] = result.content;\n\t\tconst hasHeader = first?.type === \"text\" && SCRIPT_HEADER.test(first.text);\n\t\tconst output = options.isPartial\n\t\t\t? \"\"\n\t\t\t: getTextOutput({ ...result, content: hasHeader ? rest : result.content }, context.showImages).trim();\n\t\tif (output) {\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: script output is 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) => expandHint(theme, hidden, \"lines\"),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\t// The collapsed preview hides the truncation notice at the end, so name the file here.\n\t\t\t\tconst fullOutputPath = result.details?.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}\n\t\tif (timerText) {\n\t\t\tcomponent.addChild(new Spacer(1));\n\t\t\tcomponent.addChild(new Text(theme.fg(\"muted\", timerText), 0, 0));\n\t\t}\n\t\treturn component;\n\t},\n};\n"]}
@@ -11,7 +11,7 @@
11
11
  *
12
12
  * Nested results are handed to the script as follows:
13
13
  * - A tool that declares `outputSchema` resolves to its `structuredContent`, also for error
14
- * results that carry one (MCP tools resolve to their `CallToolResult`, including `isError`).
14
+ * results that carry one.
15
15
  * - Any other tool resolves to its text content as one string.
16
16
  * - A failed, blocked, or invalid call rejects with an Error carrying the tool's error text.
17
17
  *
@@ -23,7 +23,7 @@
23
23
  import type { AgentTool } from "@earendil-works/pi-agent-core";
24
24
  import type { CodemodeTool } from "@earendil-works/pi-codemode";
25
25
  import { type Static, Type } from "typebox";
26
- import type { ToolDefinition, ToolInfo, ToolNamespace } from "../../core/extensions/types.ts";
26
+ import type { ToolDefinition, ToolNamespace } from "../../core/extensions/types.ts";
27
27
  import type { ModelRegistry } from "../../core/model-registry.ts";
28
28
  import type { CodemodeMode } from "../../core/settings-manager.ts";
29
29
  export declare const CODEMODE_TOOL_NAME = "codemode";
@@ -59,11 +59,6 @@ export declare const codemodeSchema: Type.TObject<{
59
59
  code: Type.TString;
60
60
  }>;
61
61
  export type CodemodeToolInput = Static<typeof codemodeSchema>;
62
- /**
63
- * Whether a registered tool is this package's `codemode` tool rather than another extension's tool
64
- * with the same name. Compares the parameter schema, which the definition passes through by reference.
65
- */
66
- export declare function isCodemodeTool(tool: Pick<ToolInfo, "name" | "parameters">): boolean;
67
62
  export type CodemodeNestedCallStatus = "running" | "ok" | "error" | "cancelled";
68
63
  export interface CodemodeNestedCall {
69
64
  /** Tool call id of the nested call, `<codemode call id>/<n>`. */
@@ -90,7 +85,7 @@ export declare const codemodeToolSystemPromptContribution: {
90
85
  /** The reference for scripts: globals, tool results, `store()`, the `models` API, and limits. */
91
86
  export declare const CODEMODE_DOCS_PATH: string;
92
87
  /** Default for {@link CodemodeDescriptionOptions.inlineBudget}, in estimated tokens. */
93
- export declare const DEFAULT_CODEMODE_INLINE_BUDGET = 3000;
88
+ export declare const DEFAULT_CODEMODE_INLINE_BUDGET: 3000;
94
89
  /**
95
90
  * What a script sees of a tool: its description followed by its prompt guidelines, which the system
96
91
  * prompt only has for declared tools. Tools without an output schema resolve to their text output.
@@ -115,10 +110,9 @@ export interface CodemodeDescriptionOptions {
115
110
  }
116
111
  /**
117
112
  * Model-facing description: the helper list, guidance for finding tools that are not listed, the
118
- * shared MCP types when listed tools need them, the `models` API, and one section per listed tool,
119
- * grouped by namespace. Deferred tools are never listed and do not affect the description at all, so
120
- * it stays the same while MCP servers connect or change their tools. Tool sections are limited to
121
- * `inlineBudget`.
113
+ * `models` API, and one section per listed tool, grouped by namespace. Deferred tools are never
114
+ * listed and do not affect the description at all, so it stays the same while tools are registered
115
+ * late (for example by MCP servers that connect). Tool sections are limited to `inlineBudget`.
122
116
  */
123
117
  export declare function createCodemodeDescription(tools: readonly AgentTool<any>[], options?: CodemodeDescriptionOptions): string;
124
118
  export declare function createCodemodeToolDefinition(options?: CodemodeToolOptions): ToolDefinition<typeof codemodeSchema, CodemodeToolDetails | undefined>;
@@ -1 +1 @@
1
- {"version":3,"file":"tool.d.ts","sourceRoot":"","sources":["../../../src/extensions/codemode/tool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAGH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAC/D,OAAO,KAAK,EAAsB,YAAY,EAAE,MAAM,6BAA6B,CAAC;AASpF,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,KAAK,EACX,cAAc,EACd,QAAQ,EAGR,aAAa,EACb,MAAM,gCAAgC,CAAC;AACxC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAKnE,eAAO,MAAM,kBAAkB,aAAa,CAAC;AAE7C,+FAA+F;AAC/F,eAAO,MAAM,yBAAyB,mBAAmB,CAAC;AAE1D,MAAM,WAAW,sBAAsB;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AGG;AACH,wBAAgB,qBAAqB,CACpC,IAAI,EAAE,SAAS,CAAC,GAAG,CAAC,EACpB,UAAU,GAAE,SAAS,MAAM,EAAO,GAChC,IAAI,CAAC,YAAY,EAAE,SAAS,CAAC,CAQ/B;AAED,iFAAiF;AACjF,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,SAAS,SAAS,CAAC,GAAG,CAAC,EAAE,GAAG,SAAS,CAAC,GAAG,CAAC,EAAE,CAE3F;AAED,MAAM,WAAW,0BAA0B;IAC1C,gFAAgF;IAChF,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,iGAAiG;IACjG,UAAU,CAAC,EAAE,WAAW,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IAChD,6FAA6F;IAC7F,QAAQ,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IAC/B,kFAAkF;IAClF,UAAU,CAAC,EAAE,WAAW,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC,CAAC;IACpD;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB;AA6CD;;;;;GAKG;AACH,wBAAgB,yBAAyB,CACxC,KAAK,EAAE,SAAS,SAAS,CAAC,GAAG,CAAC,EAAE,EAChC,OAAO,GAAE,0BAA+B,GACtC,MAAM,CAuCR;AAqGD,wBAAgB,4BAA4B,CAC3C,OAAO,GAAE,mBAAwB,GAC/B,cAAc,CAAC,OAAO,cAAc,EAAE,mBAAmB,GAAG,SAAS,CAAC,CAoBxE;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CACjC,KAAK,GAAE,SAAS,SAAS,CAAC,GAAG,CAAC,EAAO,EACrC,OAAO,GAAE,mBAAwB,GAC/B,SAAS,CAAC,OAAO,cAAc,CAAC,CASlC"}
@@ -11,7 +11,7 @@
11
11
  *
12
12
  * Nested results are handed to the script as follows:
13
13
  * - A tool that declares `outputSchema` resolves to its `structuredContent`, also for error
14
- * results that carry one (MCP tools resolve to their `CallToolResult`, including `isError`).
14
+ * results that carry one.
15
15
  * - Any other tool resolves to its text content as one string.
16
16
  * - A failed, blocked, or invalid call rejects with an Error carrying the tool's error text.
17
17
  *
@@ -21,10 +21,11 @@
21
21
  * so each branch sees the values written on its own path.
22
22
  */
23
23
  import { join } from "node:path";
24
- import { MCP_TYPESCRIPT_PREAMBLE, mcpStructuredContentSchema, renderToolOutputType, renderToolSample, toCodemodeIdentifier, } from "@earendil-works/pi-codemode/declarations";
24
+ import { renderToolOutputType, renderToolSample, toCodemodeIdentifier } from "@earendil-works/pi-codemode/declarations";
25
25
  import { CODEMODE_SOURCE_GRAMMAR } from "@earendil-works/pi-codemode/source";
26
26
  import { Type } from "typebox";
27
27
  import { getDocsPath } from "../../config.js";
28
+ import { SETTINGS_DEFAULTS } from "../../core/settings-defaults.js";
28
29
  import { wrapToolDefinition } from "../../core/tools/tool-definition-wrapper.js";
29
30
  import { loadCodemodeExecutor } from "./execute.lazy.js";
30
31
  import { codemodeRenderers } from "./renderer.js";
@@ -37,13 +38,6 @@ export const codemodeSchema = Type.Object({
37
38
  description: "Raw JavaScript source.",
38
39
  }),
39
40
  });
40
- /**
41
- * Whether a registered tool is this package's `codemode` tool rather than another extension's tool
42
- * with the same name. Compares the parameter schema, which the definition passes through by reference.
43
- */
44
- export function isCodemodeTool(tool) {
45
- return tool.name === CODEMODE_TOOL_NAME && tool.parameters === codemodeSchema;
46
- }
47
41
  export const codemodeToolSystemPromptContribution = {
48
42
  snippet: "Run JavaScript that calls other tools",
49
43
  guidelines: [
@@ -53,7 +47,7 @@ export const codemodeToolSystemPromptContribution = {
53
47
  /** The reference for scripts: globals, tool results, `store()`, the `models` API, and limits. */
54
48
  export const CODEMODE_DOCS_PATH = join(getDocsPath(), "codemode.md");
55
49
  const DESCRIPTION_INTRO = `Run JavaScript that calls other tools. The input is raw JavaScript (not JSON, no code fence), run as an async function body in a QuickJS sandbox: top-level \`await\` and \`return\` work. No Node, file system, network, or timers.
56
- - \`await tools.<name>({ ...args })\` resolves to a string, or an object if the tool's declaration says so, and rejects with an Error on failure. Calls still running when the script ends are cancelled.
50
+ - \`await tools.<name>({ ...args })\` resolves to a string, or an object if the tool's declaration says so, and rejects with an Error on failure. A tool whose declaration returns an object resolves on failure too when it returned that object; check its fields. Calls still running when the script ends are cancelled.
57
51
  - Optional first line: \`// @options: {"max_output_tokens": 10000, "timeout_ms": 60000}\``;
58
52
  /** One line per global. The details live in {@link CODEMODE_DOCS_PATH}. */
59
53
  function describeGlobals(models) {
@@ -69,7 +63,7 @@ function describeGlobals(models) {
69
63
  return lines.join("\n");
70
64
  }
71
65
  /** Default for {@link CodemodeDescriptionOptions.inlineBudget}, in estimated tokens. */
72
- export const DEFAULT_CODEMODE_INLINE_BUDGET = 3000;
66
+ export const DEFAULT_CODEMODE_INLINE_BUDGET = SETTINGS_DEFAULTS.codemode.inlineBudget;
73
67
  /** Characters per token when estimating the cost of a tool section. */
74
68
  const CHARS_PER_TOKEN = 4;
75
69
  /**
@@ -123,10 +117,9 @@ function selectCatalog(groups, budget) {
123
117
  }
124
118
  /**
125
119
  * Model-facing description: the helper list, guidance for finding tools that are not listed, the
126
- * shared MCP types when listed tools need them, the `models` API, and one section per listed tool,
127
- * grouped by namespace. Deferred tools are never listed and do not affect the description at all, so
128
- * it stays the same while MCP servers connect or change their tools. Tool sections are limited to
129
- * `inlineBudget`.
120
+ * `models` API, and one section per listed tool, grouped by namespace. Deferred tools are never
121
+ * listed and do not affect the description at all, so it stays the same while tools are registered
122
+ * late (for example by MCP servers that connect). Tool sections are limited to `inlineBudget`.
130
123
  */
131
124
  export function createCodemodeDescription(tools, options = {}) {
132
125
  const declarations = getCodemodeCallableTools(tools)
@@ -144,9 +137,6 @@ export function createCodemodeDescription(tools, options = {}) {
144
137
  const ordered = [...groups.values()].sort((a, b) => a.namespace === undefined ? -1 : b.namespace === undefined ? 1 : a.namespace.name.localeCompare(b.namespace.name));
145
138
  const shown = selectCatalog(ordered, options.inlineBudget);
146
139
  const sections = [DESCRIPTION_INTRO, describeGlobals(options.models === true)];
147
- if (declarations.some((declaration) => shown.has(declaration.name) && mcpStructuredContentSchema(declaration.outputSchema) !== undefined)) {
148
- sections.push(`Shared MCP Types:\n\`\`\`ts\n${MCP_TYPESCRIPT_PREAMBLE}\n\`\`\``);
149
- }
150
140
  if (declarations.length === 0)
151
141
  return sections.join("\n\n");
152
142
  const toolSections = ["Nested tools:"];
@@ -169,24 +159,33 @@ export function createCodemodeDescription(tools, options = {}) {
169
159
  return sections.join("\n\n");
170
160
  }
171
161
  /**
172
- * What a script call resolves to, in one line: `a string`, the field names of an object
173
- * (`{ output, exit_code, full_output_path? }`), or the rendered type for anything else.
162
+ * The field names of an object schema, `{ output, exit_code, full_output_path? }`, with the fields of
163
+ * object-typed fields `depth` levels deep: `{ content, structuredContent?: { results } }`. Undefined
164
+ * for other schemas.
165
+ */
166
+ function describeFields(schema, depth) {
167
+ if (typeof schema !== "object" || schema === null)
168
+ return undefined;
169
+ const { type, properties, required } = schema;
170
+ if (type !== "object" || typeof properties !== "object" || properties === null)
171
+ return undefined;
172
+ const requiredNames = new Set(Array.isArray(required) ? required : []);
173
+ const fields = Object.entries(properties).map(([name, field]) => {
174
+ const nested = depth > 0 ? describeFields(field, depth - 1) : undefined;
175
+ return `${name}${requiredNames.has(name) ? "" : "?"}${nested ? `: ${nested}` : ""}`;
176
+ });
177
+ return `{ ${fields.join(", ")} }`;
178
+ }
179
+ /**
180
+ * What a script call resolves to, in one line: `a string`, the field names of an object (see
181
+ * {@link describeFields}), or the rendered type for anything else.
174
182
  */
175
183
  function describeOutput(schema) {
176
184
  const type = renderToolOutputType(schema);
177
185
  if (type === "string")
178
186
  return "a string";
179
- const object = typeof schema === "object" ? schema : undefined;
180
- const properties = object?.properties;
181
- if (object?.type === "object" &&
182
- typeof properties === "object" &&
183
- properties !== null &&
184
- mcpStructuredContentSchema(schema) === undefined) {
185
- const required = new Set(Array.isArray(object.required) ? object.required : []);
186
- const fields = Object.keys(properties).map((name) => (required.has(name) ? name : `${name}?`));
187
- return `\`{ ${fields.join(", ")} }\``;
188
- }
189
- return `\`${type.replace(/\s+/g, " ")}\``;
187
+ const fields = describeFields(schema, 1);
188
+ return `\`${fields ?? type.replace(/\s+/g, " ")}\``;
190
189
  }
191
190
  /**
192
191
  * A declared tool's description followed by how scripts call it and what the call resolves to. The
@@ -208,7 +207,7 @@ function describeScriptCall(tool) {
208
207
  * `tool_search` loads a tool, so loads do not redeclare codemode.
209
208
  */
210
209
  function prepareCodemodeLoadout(loadout, options) {
211
- const mode = options.getMode?.() ?? "on";
210
+ const mode = options.getMode?.() ?? SETTINGS_DEFAULTS.codemode.mode;
212
211
  const isDirect = (tool) => loadout.getExposure(tool.name) === "direct";
213
212
  const callable = getCodemodeCallableTools(loadout.callable);
214
213
  const callableNames = new Set(callable.map((tool) => tool.name));
@@ -240,6 +239,18 @@ function prepareCodemodeLoadout(loadout, options) {
240
239
  : [],
241
240
  };
242
241
  }
242
+ /** Script globals that list or look up tools and namespaces, which the script may then call by any name. */
243
+ const DISCOVERY_GLOBALS = /\b(searchTools|describeNamespace|describeTool|ALL_TOOLS)\b/;
244
+ /**
245
+ * The tools a script may call (`ToolDefinition.reachesTools`): every tool when it uses a discovery
246
+ * global, else the words of its source, so `tools.mcp__docs__search` and
247
+ * `tools["mcp__docs__" + name]` both name the `mcp__docs` namespace.
248
+ */
249
+ function getScriptReach(code) {
250
+ if (typeof code !== "string")
251
+ return [];
252
+ return DISCOVERY_GLOBALS.test(code) ? "all" : (code.match(/\w+/g) ?? []);
253
+ }
243
254
  export function createCodemodeToolDefinition(options = {}) {
244
255
  return {
245
256
  name: CODEMODE_TOOL_NAME,
@@ -252,6 +263,7 @@ export function createCodemodeToolDefinition(options = {}) {
252
263
  // Scripts must not start other scripts.
253
264
  exposure: "model-only",
254
265
  prepareLoadout: (loadout) => prepareCodemodeLoadout(loadout, options),
266
+ reachesTools: (input) => getScriptReach(input.code),
255
267
  // Capable models write the script as raw text instead of a JSON-escaped string.
256
268
  constrainedSampling: { type: "grammar", variants: { openai_lark: CODEMODE_SOURCE_GRAMMAR } },
257
269
  // The sandbox (worker, QuickJS wasm) loads on the first call, not at startup.
@@ -1 +1 @@
1
- {"version":3,"file":"tool.js","sourceRoot":"","sources":["../../../src/extensions/codemode/tool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,OAAO,EACN,uBAAuB,EACvB,0BAA0B,EAC1B,oBAAoB,EACpB,gBAAgB,EAChB,oBAAoB,GACpB,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,uBAAuB,EAAE,MAAM,oCAAoC,CAAC;AAC7E,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAU9C,OAAO,EAAE,kBAAkB,EAAE,MAAM,6CAA6C,CAAC;AACjF,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAElD,MAAM,CAAC,MAAM,kBAAkB,GAAG,UAAU,CAAC;AAE7C,+FAA+F;AAC/F,MAAM,CAAC,MAAM,yBAAyB,GAAG,gBAAgB,CAAC;AAkC1D,MAAM,kBAAkB,GAAuB,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;AAElE,MAAM,CAAC,MAAM,cAAc,GAAG,IAAI,CAAC,MAAM,CAAC;IACzC,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC;QACjB,WAAW,EAAE,wBAAwB;KACrC,CAAC;CACF,CAAC,CAAC;AAIH;;;GAGG;AACH,MAAM,UAAU,cAAc,CAAC,IAA2C;IACzE,OAAO,IAAI,CAAC,IAAI,KAAK,kBAAkB,IAAI,IAAI,CAAC,UAAU,KAAK,cAAc,CAAC;AAC/E,CAAC;AAwBD,MAAM,CAAC,MAAM,oCAAo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AK,IAAI,EAAE,CAAC;QAClF,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;KAC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["/**\n * The `codemode` tool: the model writes JavaScript that calls other tools. Scripts use `tools`,\n * `ALL_TOOLS`, `text()`, `image()`, `exit()`, `store()`/`load()`, `console.*`, and `return <value>`,\n * may start with a `// @options:` line, and reach the model catalog, classifiers, and image models\n * through `models.*`. Results start with a \"Script completed\" or \"Script failed\" header.\n *\n * Scripts can call the agent loop's nested tools: active `direct` tools and every `codemode` or\n * `deferred` tool. Nested calls run through the agent loop's tool pipeline (`ctx.executeTool`), so\n * validation, `tool_call`/`tool_result` hooks, and permission checks apply exactly as for direct\n * calls. Only the script's output reaches the model; nested results do not.\n *\n * Nested results are handed to the script as follows:\n * - A tool that declares `outputSchema` resolves to its `structuredContent`, also for error\n * results that carry one (MCP tools resolve to their `CallToolResult`, including `isError`).\n * - Any other tool resolves to its text content as one string.\n * - A failed, blocked, or invalid call rejects with an Error carrying the tool's error text.\n *\n * A script that fails returns a normal error result that keeps its partial output, followed by\n * \"Script error:\" and the error. `store(key, value)` and `load(key)` keep JSON values across\n * calls; successful scripts append their writes to the session as `codemode-store` custom entries,\n * so each branch sees the values written on its own path.\n */\n\nimport { join } from \"node:path\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport type { CodemodeJsonSchema, CodemodeTool } from \"@earendil-works/pi-codemode\";\nimport {\n\tMCP_TYPESCRIPT_PREAMBLE,\n\tmcpStructuredContentSchema,\n\trenderToolOutputType,\n\trenderToolSample,\n\ttoCodemodeIdentifier,\n} from \"@earendil-works/pi-codemode/declarations\";\nimport { CODEMODE_SOURCE_GRAMMAR } from \"@earendil-works/pi-codemode/source\";\nimport { type Static, Type } from \"typebox\";\nimport { getDocsPath } from \"../../config.ts\";\nimport type {\n\tToolDefinition,\n\tToolInfo,\n\tToolLoadout,\n\tToolLoadoutChanges,\n\tToolNamespace,\n} from \"../../core/extensions/types.ts\";\nimport type { ModelRegistry } from \"../../core/model-registry.ts\";\nimport type { CodemodeMode } from \"../../core/settings-manager.ts\";\nimport { wrapToolDefinition } from \"../../core/tools/tool-definition-wrapper.ts\";\nimport { loadCodemodeExecutor } from \"./execute.lazy.ts\";\nimport { codemodeRenderers } from \"./renderer.ts\";\n\nexport const CODEMODE_TOOL_NAME = \"codemode\";\n\n/** Custom entry type holding one script's `store()` writes: {@link CodemodeStoreEntryData}. */\nexport const CODEMODE_STORE_ENTRY_TYPE = \"codemode-store\";\n\nexport interface CodemodeStoreEntryData {\n\tset: Record<string, unknown>;\n\tdelete: string[];\n}\n\n/** The part of the model registry that scripts reach through `models`. */\nexport type CodemodeModelRuntime = Pick<\n\tModelRegistry,\n\t\"getModelsOfType\" | \"getAvailableOfType\" | \"getModelOfType\" | \"classify\" | \"generateImages\"\n>;\n\nexport interface CodemodeToolOptions {\n\t/** Namespace of a tool, for `searchTools()` ranking and its `namespace` filter. */\n\tgetToolNamespace?: (toolName: string) => ToolNamespace | undefined;\n\t/** Prompt guidelines of every tool, by tool name, shown with declarations by `describeTool()` and `ALL_TOOLS`. */\n\tgetToolGuidelines?: () => ReadonlyMap<string, readonly string[]>;\n\t/**\n\t * Expose the `models` namespace to scripts, backed by the session's model registry\n\t * (`ctx.modelRegistry`). Without it, `models` is not declared.\n\t */\n\tmodels?: boolean;\n\t/**\n\t * Persists `store()` writes as a session custom entry. Without it, writes last only for the\n\t * current script; `load()` still reads entries already on the branch.\n\t */\n\tappendEntry?: (customType: string, data: CodemodeStoreEntryData) => void;\n\t/** How the tool presents the loadout while active (the `codemode.mode` setting). Default: `on`. */\n\tgetMode?: () => CodemodeMode;\n\t/** Token budget for tool declarations in the description. Default: {@link DEFAULT_CODEMODE_INLINE_BUDGET}. */\n\tgetInlineBudget?: () => number | undefined;\n}\n\nconst TEXT_OUTPUT_SCHEMA: CodemodeJsonSchema = { type: \"string\" };\n\nexport const codemodeSchema = Type.Object({\n\tcode: Type.String({\n\t\tdescription: \"Raw JavaScript source.\",\n\t}),\n});\n\nexport type CodemodeToolInput = Static<typeof codemodeSchema>;\n\n/**\n * Whether a registered tool is this package's `codemode` tool rather than another extension's tool\n * with the same name. Compares the parameter schema, which the definition passes through by reference.\n */\nexport function isCodemodeTool(tool: Pick<ToolInfo, \"name\" | \"parameters\">): boolean {\n\treturn tool.name === CODEMODE_TOOL_NAME && tool.parameters === codemodeSchema;\n}\n\nexport type CodemodeNestedCallStatus = \"running\" | \"ok\" | \"error\" | \"cancelled\";\n\nexport interface CodemodeNestedCall {\n\t/** Tool call id of the nested call, `<codemode call id>/<n>`. */\n\tid: string;\n\tname: string;\n\t/** Compact JSON of the arguments, truncated for display. */\n\targs: string;\n\tstatus: CodemodeNestedCallStatus;\n\tdurationMs?: number;\n\t/** Error text, truncated for display. */\n\terror?: string;\n\t/** Cost in USD of a `models.*` call that reported usage. */\n\tcost?: number;\n}\n\nexport interface CodemodeToolDetails {\n\tcalls: CodemodeNestedCall[];\n\t/** Temp file with the full text output, when the output was truncated. */\n\tfullOutputPath?: string;\n}\n\nexport const codemodeToolSystemPromptContribution = {\n\tsnippet: \"Run JavaScript that calls other tools\",\n\tguidelines: [\n\t\t\"Use codemode to batch independent tool calls (Promise.allSettled), chain them, or filter large output, instead of many separate calls.\",\n\t],\n} as const;\n\n/** The reference for scripts: globals, tool results, `store()`, the `models` API, and limits. */\nexport const CODEMODE_DOCS_PATH = join(getDocsPath(), \"codemode.md\");\n\nconst DESCRIPTION_INTRO = `Run JavaScript that calls other tools. The input is raw JavaScript (not JSON, no code fence), run as an async function body in a QuickJS sandbox: top-level \\`await\\` and \\`return\\` work. No Node, file system, network, or timers.\n- \\`await tools.<name>({ ...args })\\` resolves to a string, or an object if the tool's declaration says so, and rejects with an Error on failure. Calls still running when the script ends are cancelled.\n- Optional first line: \\`// @options: {\"max_output_tokens\": 10000, \"timeout_ms\": 60000}\\``;\n\n/** One line per global. The details live in {@link CODEMODE_DOCS_PATH}. */\nfunction describeGlobals(models: boolean): string {\n\tconst lines = [\n\t\t\"Globals:\",\n\t\t\"- `text(value)`, `image(dataUrlOrImageBlock)`, `console.log(...)`, and top-level `return` add output; `exit()` ends the script. With several text items, each starts with a `==> text N/M <==` line, and `console` lines follow the other output in one `<console_output>` block. `image()` also saves the image to a temp file and the result names its path.\",\n\t\t\"- `store(key, value)` and `load(key)` keep JSON values across codemode calls.\",\n\t\t\"- `ALL_TOOLS`, `await searchTools(query, { limit?, namespace? })`, `await describeTool(name)`, `await describeNamespace(name)`: find unlisted tools, such as MCP tools.\",\n\t];\n\tif (models) {\n\t\tlines.push(`- \\`models\\`: classifiers and image generation. Read ${CODEMODE_DOCS_PATH} first.`);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\n/** Default for {@link CodemodeDescriptionOptions.inlineBudget}, in estimated tokens. */\nexport const DEFAULT_CODEMODE_INLINE_BUDGET = 3000;\n/** Characters per token when estimating the cost of a tool section. */\nconst CHARS_PER_TOKEN = 4;\n\n/**\n * What a script sees of a tool: its description followed by its prompt guidelines, which the system\n * prompt only has for declared tools. Tools without an output schema resolve to their text output.\n */\nexport function toCodemodeDeclaration(\n\ttool: AgentTool<any>,\n\tguidelines: readonly string[] = [],\n): Omit<CodemodeTool, \"execute\"> {\n\tconst bullets = guidelines.flatMap((guideline) => (guideline.trim() ? [`- ${guideline.trim()}`] : []));\n\treturn {\n\t\tname: tool.name,\n\t\tdescription: bullets.length > 0 ? `${tool.description.trim()}\\n\\n${bullets.join(\"\\n\")}` : tool.description,\n\t\tinputSchema: tool.parameters as CodemodeJsonSchema,\n\t\toutputSchema: (tool.outputSchema as CodemodeJsonSchema | undefined) ?? TEXT_OUTPUT_SCHEMA,\n\t};\n}\n\n/** Tools a script may call: every given tool except the codemode tool itself. */\nexport function getCodemodeCallableTools(tools: readonly AgentTool<any>[]): AgentTool<any>[] {\n\treturn tools.filter((tool) => tool.name !== CODEMODE_TOOL_NAME);\n}\n\nexport interface CodemodeDescriptionOptions {\n\t/** Declare the `models` namespace; only for tools created with model access. */\n\tmodels?: boolean;\n\t/** Namespace of each tool, by tool name. Tools of one namespace are listed under one heading. */\n\tnamespaces?: ReadonlyMap<string, ToolNamespace>;\n\t/** Tools that are callable but never listed with their declaration (`deferred` exposure). */\n\tdeferred?: ReadonlySet<string>;\n\t/** Prompt guidelines of each tool, by tool name, listed after its description. */\n\tguidelines?: ReadonlyMap<string, readonly string[]>;\n\t/**\n\t * Estimated tokens (characters / 4) the tool sections may use. Tools that do not fit are left\n\t * out, like deferred tools. Unset lists every tool that is not deferred.\n\t */\n\tinlineBudget?: number;\n}\n\n/** `### \\`id\\` (\\`raw name\\`)` followed by the tool's description and declaration. */\nfunction renderToolSection(declaration: Omit<CodemodeTool, \"execute\">): string {\n\tconst id = toCodemodeIdentifier(declaration.name);\n\tconst heading = id === declaration.name ? `### \\`${id}\\`` : `### \\`${id}\\` (\\`${declaration.name}\\`)`;\n\treturn `${heading}\\n${renderToolSample(declaration).trim()}`;\n}\n\ninterface CatalogEntry {\n\tname: string;\n\tsection: string;\n\tcost: number;\n}\n\ninterface CatalogGroup {\n\tnamespace: ToolNamespace | undefined;\n\tentries: CatalogEntry[];\n}\n\n/**\n * Pick the tool sections that fit the budget, like OpenCode's catalog: in each round every group\n * (tools without a namespace first, then namespaces by name) places its cheapest remaining tool; a\n * group whose next tool does not fit drops out while the others continue. Every namespace is\n * represented before any namespace is complete.\n */\nfunction selectCatalog(groups: readonly CatalogGroup[], budget: number | undefined): Set<string> {\n\tif (budget === undefined) return new Set(groups.flatMap((group) => group.entries.map((entry) => entry.name)));\n\tconst queues = groups.map((group) => [...group.entries].sort((a, b) => a.cost - b.cost));\n\tconst shown = new Set<string>();\n\tlet remaining = budget;\n\tlet active = queues.filter((queue) => queue.length > 0);\n\twhile (active.length > 0) {\n\t\tactive = active.filter((queue) => {\n\t\t\tconst next = queue[0];\n\t\t\tif (next.cost > remaining) return false;\n\t\t\tremaining -= next.cost;\n\t\t\tshown.add(next.name);\n\t\t\tqueue.shift();\n\t\t\treturn queue.length > 0;\n\t\t});\n\t}\n\treturn shown;\n}\n\n/**\n * Model-facing description: the helper list, guidance for finding tools that are not listed, the\n * shared MCP types when listed tools need them, the `models` API, and one section per listed tool,\n * grouped by namespace. Deferred tools are never listed and do not affect the description at all, so\n * it stays the same while MCP servers connect or change their tools. Tool sections are limited to\n * `inlineBudget`.\n */\nexport function createCodemodeDescription(\n\ttools: readonly AgentTool<any>[],\n\toptions: CodemodeDescriptionOptions = {},\n): string {\n\tconst declarations = getCodemodeCallableTools(tools)\n\t\t.filter((tool) => !options.deferred?.has(tool.name))\n\t\t.map((tool) => toCodemodeDeclaration(tool, options.guidelines?.get(tool.name)));\n\tconst groups = new Map<string, CatalogGroup>([[\"\", { namespace: undefined, entries: [] }]]);\n\tfor (const declaration of declarations) {\n\t\tconst namespace = options.namespaces?.get(declaration.name);\n\t\tconst key = namespace ? `ns:${namespace.name}` : \"\";\n\t\tconst group = groups.get(key) ?? { namespace, entries: [] };\n\t\tgroups.set(key, group);\n\t\tconst section = renderToolSection(declaration);\n\t\tgroup.entries.push({ name: declaration.name, section, cost: Math.ceil(section.length / CHARS_PER_TOKEN) });\n\t}\n\tconst ordered = [...groups.values()].sort((a, b) =>\n\t\ta.namespace === undefined ? -1 : b.namespace === undefined ? 1 : a.namespace.name.localeCompare(b.namespace.name),\n\t);\n\tconst shown = selectCatalog(ordered, options.inlineBudget);\n\n\tconst sections = [DESCRIPTION_INTRO, describeGlobals(options.models === true)];\n\tif (\n\t\tdeclarations.some(\n\t\t\t(declaration) =>\n\t\t\t\tshown.has(declaration.name) && mcpStructuredContentSchema(declaration.outputSchema) !== undefined,\n\t\t)\n\t) {\n\t\tsections.push(`Shared MCP Types:\\n\\`\\`\\`ts\\n${MCP_TYPESCRIPT_PREAMBLE}\\n\\`\\`\\``);\n\t}\n\tif (declarations.length === 0) return sections.join(\"\\n\\n\");\n\n\tconst toolSections = [\"Nested tools:\"];\n\tfor (const { namespace, entries } of ordered) {\n\t\tconst visible = entries.filter((entry) => shown.has(entry.name));\n\t\tif (namespace) {\n\t\t\t// Only tools that did not fit the budget are counted as not listed here.\n\t\t\tconst listing =\n\t\t\t\tvisible.length === entries.length\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: visible.length === 0\n\t\t\t\t\t\t? \" (tools not listed)\"\n\t\t\t\t\t\t: \" (some tools not listed)\";\n\t\t\tconst description = namespace.description?.trim();\n\t\t\ttoolSections.push(`## ${namespace.name}${listing}${description ? `\\n${description}` : \"\"}`);\n\t\t}\n\t\tfor (const entry of visible) toolSections.push(entry.section);\n\t}\n\tsections.push(toolSections.join(\"\\n\\n\"));\n\treturn sections.join(\"\\n\\n\");\n}\n\n/**\n * What a script call resolves to, in one line: `a string`, the field names of an object\n * (`{ output, exit_code, full_output_path? }`), or the rendered type for anything else.\n */\nfunction describeOutput(schema: CodemodeJsonSchema | undefined): string {\n\tconst type = renderToolOutputType(schema);\n\tif (type === \"string\") return \"a string\";\n\tconst object = typeof schema === \"object\" ? schema : undefined;\n\tconst properties = object?.properties;\n\tif (\n\t\tobject?.type === \"object\" &&\n\t\ttypeof properties === \"object\" &&\n\t\tproperties !== null &&\n\t\tmcpStructuredContentSchema(schema) === undefined\n\t) {\n\t\tconst required = new Set(Array.isArray(object.required) ? object.required : []);\n\t\tconst fields = Object.keys(properties).map((name) => (required.has(name) ? name : `${name}?`));\n\t\treturn `\\`{ ${fields.join(\", \")} }\\``;\n\t}\n\treturn `\\`${type.replace(/\\s+/g, \" \")}\\``;\n}\n\n/**\n * A declared tool's description followed by how scripts call it and what the call resolves to. The\n * arguments are the tool's declared parameters, so they are not repeated.\n */\nfunction describeScriptCall(tool: AgentTool<any>): string {\n\treturn `${tool.description.trim()}\\n\\nCodemode: \\`tools.${toCodemodeIdentifier(tool.name)}(args)\\` resolves to ${describeOutput(toCodemodeDeclaration(tool).outputSchema)}.`;\n}\n\n/**\n * How the codemode tool presents tools that are both declared and callable from scripts:\n * - `on`: their descriptions say how scripts call them, and the codemode description\n * lists only the callable tools without `direct` exposure.\n * - `only`: the codemode description lists every callable tool, and requests leave out the\n * declarations of active `direct` tools.\n *\n * Listed tools carry their prompt guidelines, which the system prompt only has for declared tools.\n *\n * Listing by exposure, not by the active set, keeps the codemode description unchanged when\n * `tool_search` loads a tool, so loads do not redeclare codemode.\n */\nfunction prepareCodemodeLoadout(loadout: ToolLoadout, options: CodemodeToolOptions): ToolLoadoutChanges {\n\tconst mode = options.getMode?.() ?? \"on\";\n\tconst isDirect = (tool: AgentTool) => loadout.getExposure(tool.name) === \"direct\";\n\tconst callable = getCodemodeCallableTools(loadout.callable);\n\tconst callableNames = new Set(callable.map((tool) => tool.name));\n\tconst descriptions: Record<string, string> = {};\n\tif (mode === \"on\") {\n\t\tfor (const tool of loadout.declared) {\n\t\t\tif (callableNames.has(tool.name)) descriptions[tool.name] = describeScriptCall(tool);\n\t\t}\n\t}\n\tconst listed = mode === \"only\" ? callable : callable.filter((tool) => !isDirect(tool));\n\tconst namespaces = new Map(\n\t\tlisted.flatMap((tool) => {\n\t\t\tconst namespace = loadout.getNamespace(tool.name);\n\t\t\treturn namespace ? [[tool.name, namespace] as const] : [];\n\t\t}),\n\t);\n\tconst guidelines = new Map(listed.map((tool) => [tool.name, loadout.getPromptGuidelines(tool.name)] as const));\n\tdescriptions[CODEMODE_TOOL_NAME] = createCodemodeDescription(listed, {\n\t\tmodels: options.models === true,\n\t\tnamespaces,\n\t\tguidelines,\n\t\tdeferred: new Set(\n\t\t\tlisted.filter((tool) => loadout.getExposure(tool.name) === \"deferred\").map((tool) => tool.name),\n\t\t),\n\t\tinlineBudget: options.getInlineBudget?.() ?? DEFAULT_CODEMODE_INLINE_BUDGET,\n\t});\n\tconst declaredNames = new Set(loadout.declared.map((tool) => tool.name));\n\treturn {\n\t\tdescriptions,\n\t\thiddenDeclarations:\n\t\t\tmode === \"only\"\n\t\t\t\t? callable.filter((tool) => isDirect(tool) && declaredNames.has(tool.name)).map((tool) => tool.name)\n\t\t\t\t: [],\n\t};\n}\n\nexport function createCodemodeToolDefinition(\n\toptions: CodemodeToolOptions = {},\n): ToolDefinition<typeof codemodeSchema, CodemodeToolDetails | undefined> {\n\treturn {\n\t\tname: CODEMODE_TOOL_NAME,\n\t\tlabel: CODEMODE_TOOL_NAME,\n\t\t// Replaced with the declarations of the callable tools when the tool is activated.\n\t\tdescription: createCodemodeDescription([], { models: options.models === true }),\n\t\tpromptSnippet: codemodeToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: [...codemodeToolSystemPromptContribution.guidelines],\n\t\tparameters: codemodeSchema,\n\t\t// Scripts must not start other scripts.\n\t\texposure: \"model-only\",\n\t\tprepareLoadout: (loadout) => prepareCodemodeLoadout(loadout, options),\n\t\t// Capable models write the script as raw text instead of a JSON-escaped string.\n\t\tconstrainedSampling: { type: \"grammar\", variants: { openai_lark: CODEMODE_SOURCE_GRAMMAR } },\n\t\t// The sandbox (worker, QuickJS wasm) loads on the first call, not at startup.\n\t\texecute: async (toolCallId, params, signal, onUpdate, ctx) =>\n\t\t\t(await loadCodemodeExecutor()).executeCodemode(toolCallId, params, signal, onUpdate, ctx, options),\n\t\t...codemodeRenderers,\n\t};\n}\n\n/**\n * Create the codemode tool as an AgentTool. The description lists the given tools; the script can\n * call whatever tools the agent loop provides at execution time.\n */\nexport function createCodemodeTool(\n\ttools: readonly AgentTool<any>[] = [],\n\toptions: CodemodeToolOptions = {},\n): AgentTool<typeof codemodeSchema> {\n\tconst definition = createCodemodeToolDefinition(options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tdescription: createCodemodeDescription(tools, { models: options.models === true }),\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
1
+ {"version":3,"file":"tool.js","sourceRoot":"","sources":["../../../src/extensions/codemode/tool.ts"],"names":[],"mappings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AAG,4BAA4B,CAAC,OAAO,CAAC,CAAC;IACzD,MAAM,IAAI,GAAG,kBAAkB,CAAC,UAAU,CAAC,CAAC;IAC5C,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE;QACnB,WAAW,EAAE,yBAAyB,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,KAAK,IAAI,EAAE,CAAC;QAClF,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;KAC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["/**\n * The `codemode` tool: the model writes JavaScript that calls other tools. Scripts use `tools`,\n * `ALL_TOOLS`, `text()`, `image()`, `exit()`, `store()`/`load()`, `console.*`, and `return <value>`,\n * may start with a `// @options:` line, and reach the model catalog, classifiers, and image models\n * through `models.*`. Results start with a \"Script completed\" or \"Script failed\" header.\n *\n * Scripts can call the agent loop's nested tools: active `direct` tools and every `codemode` or\n * `deferred` tool. Nested calls run through the agent loop's tool pipeline (`ctx.executeTool`), so\n * validation, `tool_call`/`tool_result` hooks, and permission checks apply exactly as for direct\n * calls. Only the script's output reaches the model; nested results do not.\n *\n * Nested results are handed to the script as follows:\n * - A tool that declares `outputSchema` resolves to its `structuredContent`, also for error\n * results that carry one.\n * - Any other tool resolves to its text content as one string.\n * - A failed, blocked, or invalid call rejects with an Error carrying the tool's error text.\n *\n * A script that fails returns a normal error result that keeps its partial output, followed by\n * \"Script error:\" and the error. `store(key, value)` and `load(key)` keep JSON values across\n * calls; successful scripts append their writes to the session as `codemode-store` custom entries,\n * so each branch sees the values written on its own path.\n */\n\nimport { join } from \"node:path\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport type { CodemodeJsonSchema, CodemodeTool } from \"@earendil-works/pi-codemode\";\nimport { renderToolOutputType, renderToolSample, toCodemodeIdentifier } from \"@earendil-works/pi-codemode/declarations\";\nimport { CODEMODE_SOURCE_GRAMMAR } from \"@earendil-works/pi-codemode/source\";\nimport { type Static, Type } from \"typebox\";\nimport { getDocsPath } from \"../../config.ts\";\nimport type { ToolDefinition, ToolLoadout, ToolLoadoutChanges, ToolNamespace } from \"../../core/extensions/types.ts\";\nimport type { ModelRegistry } from \"../../core/model-registry.ts\";\nimport { SETTINGS_DEFAULTS } from \"../../core/settings-defaults.ts\";\nimport type { CodemodeMode } from \"../../core/settings-manager.ts\";\nimport { wrapToolDefinition } from \"../../core/tools/tool-definition-wrapper.ts\";\nimport { loadCodemodeExecutor } from \"./execute.lazy.ts\";\nimport { codemodeRenderers } from \"./renderer.ts\";\n\nexport const CODEMODE_TOOL_NAME = \"codemode\";\n\n/** Custom entry type holding one script's `store()` writes: {@link CodemodeStoreEntryData}. */\nexport const CODEMODE_STORE_ENTRY_TYPE = \"codemode-store\";\n\nexport interface CodemodeStoreEntryData {\n\tset: Record<string, unknown>;\n\tdelete: string[];\n}\n\n/** The part of the model registry that scripts reach through `models`. */\nexport type CodemodeModelRuntime = Pick<\n\tModelRegistry,\n\t\"getModelsOfType\" | \"getAvailableOfType\" | \"getModelOfType\" | \"classify\" | \"generateImages\"\n>;\n\nexport interface CodemodeToolOptions {\n\t/** Namespace of a tool, for `searchTools()` ranking and its `namespace` filter. */\n\tgetToolNamespace?: (toolName: string) => ToolNamespace | undefined;\n\t/** Prompt guidelines of every tool, by tool name, shown with declarations by `describeTool()` and `ALL_TOOLS`. */\n\tgetToolGuidelines?: () => ReadonlyMap<string, readonly string[]>;\n\t/**\n\t * Expose the `models` namespace to scripts, backed by the session's model registry\n\t * (`ctx.modelRegistry`). Without it, `models` is not declared.\n\t */\n\tmodels?: boolean;\n\t/**\n\t * Persists `store()` writes as a session custom entry. Without it, writes last only for the\n\t * current script; `load()` still reads entries already on the branch.\n\t */\n\tappendEntry?: (customType: string, data: CodemodeStoreEntryData) => void;\n\t/** How the tool presents the loadout while active (the `codemode.mode` setting). Default: `on`. */\n\tgetMode?: () => CodemodeMode;\n\t/** Token budget for tool declarations in the description. Default: {@link DEFAULT_CODEMODE_INLINE_BUDGET}. */\n\tgetInlineBudget?: () => number | undefined;\n}\n\nconst TEXT_OUTPUT_SCHEMA: CodemodeJsonSchema = { type: \"string\" };\n\nexport const codemodeSchema = Type.Object({\n\tcode: Type.String({\n\t\tdescription: \"Raw JavaScript source.\",\n\t}),\n});\n\nexport type CodemodeToolInput = Static<typeof codemodeSchema>;\n\nexport type CodemodeNestedCallStatus = \"running\" | \"ok\" | \"error\" | \"cancelled\";\n\nexport interface CodemodeNestedCall {\n\t/** Tool call id of the nested call, `<codemode call id>/<n>`. */\n\tid: string;\n\tname: string;\n\t/** Compact JSON of the arguments, truncated for display. */\n\targs: string;\n\tstatus: CodemodeNestedCallStatus;\n\tdurationMs?: number;\n\t/** Error text, truncated for display. */\n\terror?: string;\n\t/** Cost in USD of a `models.*` call that reported usage. */\n\tcost?: number;\n}\n\nexport interface CodemodeToolDetails {\n\tcalls: CodemodeNestedCall[];\n\t/** Temp file with the full text output, when the output was truncated. */\n\tfullOutputPath?: string;\n}\n\nexport const codemodeToolSystemPromptContribution = {\n\tsnippet: \"Run JavaScript that calls other tools\",\n\tguidelines: [\n\t\t\"Use codemode to batch independent tool calls (Promise.allSettled), chain them, or filter large output, instead of many separate calls.\",\n\t],\n} as const;\n\n/** The reference for scripts: globals, tool results, `store()`, the `models` API, and limits. */\nexport const CODEMODE_DOCS_PATH = join(getDocsPath(), \"codemode.md\");\n\nconst DESCRIPTION_INTRO = `Run JavaScript that calls other tools. The input is raw JavaScript (not JSON, no code fence), run as an async function body in a QuickJS sandbox: top-level \\`await\\` and \\`return\\` work. No Node, file system, network, or timers.\n- \\`await tools.<name>({ ...args })\\` resolves to a string, or an object if the tool's declaration says so, and rejects with an Error on failure. A tool whose declaration returns an object resolves on failure too when it returned that object; check its fields. Calls still running when the script ends are cancelled.\n- Optional first line: \\`// @options: {\"max_output_tokens\": 10000, \"timeout_ms\": 60000}\\``;\n\n/** One line per global. The details live in {@link CODEMODE_DOCS_PATH}. */\nfunction describeGlobals(models: boolean): string {\n\tconst lines = [\n\t\t\"Globals:\",\n\t\t\"- `text(value)`, `image(dataUrlOrImageBlock)`, `console.log(...)`, and top-level `return` add output; `exit()` ends the script. With several text items, each starts with a `==> text N/M <==` line, and `console` lines follow the other output in one `<console_output>` block. `image()` also saves the image to a temp file and the result names its path.\",\n\t\t\"- `store(key, value)` and `load(key)` keep JSON values across codemode calls.\",\n\t\t\"- `ALL_TOOLS`, `await searchTools(query, { limit?, namespace? })`, `await describeTool(name)`, `await describeNamespace(name)`: find unlisted tools, such as MCP tools.\",\n\t];\n\tif (models) {\n\t\tlines.push(`- \\`models\\`: classifiers and image generation. Read ${CODEMODE_DOCS_PATH} first.`);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\n/** Default for {@link CodemodeDescriptionOptions.inlineBudget}, in estimated tokens. */\nexport const DEFAULT_CODEMODE_INLINE_BUDGET = SETTINGS_DEFAULTS.codemode.inlineBudget;\n/** Characters per token when estimating the cost of a tool section. */\nconst CHARS_PER_TOKEN = 4;\n\n/**\n * What a script sees of a tool: its description followed by its prompt guidelines, which the system\n * prompt only has for declared tools. Tools without an output schema resolve to their text output.\n */\nexport function toCodemodeDeclaration(\n\ttool: AgentTool<any>,\n\tguidelines: readonly string[] = [],\n): Omit<CodemodeTool, \"execute\"> {\n\tconst bullets = guidelines.flatMap((guideline) => (guideline.trim() ? [`- ${guideline.trim()}`] : []));\n\treturn {\n\t\tname: tool.name,\n\t\tdescription: bullets.length > 0 ? `${tool.description.trim()}\\n\\n${bullets.join(\"\\n\")}` : tool.description,\n\t\tinputSchema: tool.parameters as CodemodeJsonSchema,\n\t\toutputSchema: (tool.outputSchema as CodemodeJsonSchema | undefined) ?? TEXT_OUTPUT_SCHEMA,\n\t};\n}\n\n/** Tools a script may call: every given tool except the codemode tool itself. */\nexport function getCodemodeCallableTools(tools: readonly AgentTool<any>[]): AgentTool<any>[] {\n\treturn tools.filter((tool) => tool.name !== CODEMODE_TOOL_NAME);\n}\n\nexport interface CodemodeDescriptionOptions {\n\t/** Declare the `models` namespace; only for tools created with model access. */\n\tmodels?: boolean;\n\t/** Namespace of each tool, by tool name. Tools of one namespace are listed under one heading. */\n\tnamespaces?: ReadonlyMap<string, ToolNamespace>;\n\t/** Tools that are callable but never listed with their declaration (`deferred` exposure). */\n\tdeferred?: ReadonlySet<string>;\n\t/** Prompt guidelines of each tool, by tool name, listed after its description. */\n\tguidelines?: ReadonlyMap<string, readonly string[]>;\n\t/**\n\t * Estimated tokens (characters / 4) the tool sections may use. Tools that do not fit are left\n\t * out, like deferred tools. Unset lists every tool that is not deferred.\n\t */\n\tinlineBudget?: number;\n}\n\n/** `### \\`id\\` (\\`raw name\\`)` followed by the tool's description and declaration. */\nfunction renderToolSection(declaration: Omit<CodemodeTool, \"execute\">): string {\n\tconst id = toCodemodeIdentifier(declaration.name);\n\tconst heading = id === declaration.name ? `### \\`${id}\\`` : `### \\`${id}\\` (\\`${declaration.name}\\`)`;\n\treturn `${heading}\\n${renderToolSample(declaration).trim()}`;\n}\n\ninterface CatalogEntry {\n\tname: string;\n\tsection: string;\n\tcost: number;\n}\n\ninterface CatalogGroup {\n\tnamespace: ToolNamespace | undefined;\n\tentries: CatalogEntry[];\n}\n\n/**\n * Pick the tool sections that fit the budget, like OpenCode's catalog: in each round every group\n * (tools without a namespace first, then namespaces by name) places its cheapest remaining tool; a\n * group whose next tool does not fit drops out while the others continue. Every namespace is\n * represented before any namespace is complete.\n */\nfunction selectCatalog(groups: readonly CatalogGroup[], budget: number | undefined): Set<string> {\n\tif (budget === undefined) return new Set(groups.flatMap((group) => group.entries.map((entry) => entry.name)));\n\tconst queues = groups.map((group) => [...group.entries].sort((a, b) => a.cost - b.cost));\n\tconst shown = new Set<string>();\n\tlet remaining = budget;\n\tlet active = queues.filter((queue) => queue.length > 0);\n\twhile (active.length > 0) {\n\t\tactive = active.filter((queue) => {\n\t\t\tconst next = queue[0];\n\t\t\tif (next.cost > remaining) return false;\n\t\t\tremaining -= next.cost;\n\t\t\tshown.add(next.name);\n\t\t\tqueue.shift();\n\t\t\treturn queue.length > 0;\n\t\t});\n\t}\n\treturn shown;\n}\n\n/**\n * Model-facing description: the helper list, guidance for finding tools that are not listed, the\n * `models` API, and one section per listed tool, grouped by namespace. Deferred tools are never\n * listed and do not affect the description at all, so it stays the same while tools are registered\n * late (for example by MCP servers that connect). Tool sections are limited to `inlineBudget`.\n */\nexport function createCodemodeDescription(\n\ttools: readonly AgentTool<any>[],\n\toptions: CodemodeDescriptionOptions = {},\n): string {\n\tconst declarations = getCodemodeCallableTools(tools)\n\t\t.filter((tool) => !options.deferred?.has(tool.name))\n\t\t.map((tool) => toCodemodeDeclaration(tool, options.guidelines?.get(tool.name)));\n\tconst groups = new Map<string, CatalogGroup>([[\"\", { namespace: undefined, entries: [] }]]);\n\tfor (const declaration of declarations) {\n\t\tconst namespace = options.namespaces?.get(declaration.name);\n\t\tconst key = namespace ? `ns:${namespace.name}` : \"\";\n\t\tconst group = groups.get(key) ?? { namespace, entries: [] };\n\t\tgroups.set(key, group);\n\t\tconst section = renderToolSection(declaration);\n\t\tgroup.entries.push({ name: declaration.name, section, cost: Math.ceil(section.length / CHARS_PER_TOKEN) });\n\t}\n\tconst ordered = [...groups.values()].sort((a, b) =>\n\t\ta.namespace === undefined ? -1 : b.namespace === undefined ? 1 : a.namespace.name.localeCompare(b.namespace.name),\n\t);\n\tconst shown = selectCatalog(ordered, options.inlineBudget);\n\n\tconst sections = [DESCRIPTION_INTRO, describeGlobals(options.models === true)];\n\tif (declarations.length === 0) return sections.join(\"\\n\\n\");\n\n\tconst toolSections = [\"Nested tools:\"];\n\tfor (const { namespace, entries } of ordered) {\n\t\tconst visible = entries.filter((entry) => shown.has(entry.name));\n\t\tif (namespace) {\n\t\t\t// Only tools that did not fit the budget are counted as not listed here.\n\t\t\tconst listing =\n\t\t\t\tvisible.length === entries.length\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: visible.length === 0\n\t\t\t\t\t\t? \" (tools not listed)\"\n\t\t\t\t\t\t: \" (some tools not listed)\";\n\t\t\tconst description = namespace.description?.trim();\n\t\t\ttoolSections.push(`## ${namespace.name}${listing}${description ? `\\n${description}` : \"\"}`);\n\t\t}\n\t\tfor (const entry of visible) toolSections.push(entry.section);\n\t}\n\tsections.push(toolSections.join(\"\\n\\n\"));\n\treturn sections.join(\"\\n\\n\");\n}\n\n/**\n * The field names of an object schema, `{ output, exit_code, full_output_path? }`, with the fields of\n * object-typed fields `depth` levels deep: `{ content, structuredContent?: { results } }`. Undefined\n * for other schemas.\n */\nfunction describeFields(schema: unknown, depth: number): string | undefined {\n\tif (typeof schema !== \"object\" || schema === null) return undefined;\n\tconst { type, properties, required } = schema as Record<string, unknown>;\n\tif (type !== \"object\" || typeof properties !== \"object\" || properties === null) return undefined;\n\tconst requiredNames = new Set(Array.isArray(required) ? required : []);\n\tconst fields = Object.entries(properties).map(([name, field]) => {\n\t\tconst nested = depth > 0 ? describeFields(field, depth - 1) : undefined;\n\t\treturn `${name}${requiredNames.has(name) ? \"\" : \"?\"}${nested ? `: ${nested}` : \"\"}`;\n\t});\n\treturn `{ ${fields.join(\", \")} }`;\n}\n\n/**\n * What a script call resolves to, in one line: `a string`, the field names of an object (see\n * {@link describeFields}), or the rendered type for anything else.\n */\nfunction describeOutput(schema: CodemodeJsonSchema | undefined): string {\n\tconst type = renderToolOutputType(schema);\n\tif (type === \"string\") return \"a string\";\n\tconst fields = describeFields(schema, 1);\n\treturn `\\`${fields ?? type.replace(/\\s+/g, \" \")}\\``;\n}\n\n/**\n * A declared tool's description followed by how scripts call it and what the call resolves to. The\n * arguments are the tool's declared parameters, so they are not repeated.\n */\nfunction describeScriptCall(tool: AgentTool<any>): string {\n\treturn `${tool.description.trim()}\\n\\nCodemode: \\`tools.${toCodemodeIdentifier(tool.name)}(args)\\` resolves to ${describeOutput(toCodemodeDeclaration(tool).outputSchema)}.`;\n}\n\n/**\n * How the codemode tool presents tools that are both declared and callable from scripts:\n * - `on`: their descriptions say how scripts call them, and the codemode description\n * lists only the callable tools without `direct` exposure.\n * - `only`: the codemode description lists every callable tool, and requests leave out the\n * declarations of active `direct` tools.\n *\n * Listed tools carry their prompt guidelines, which the system prompt only has for declared tools.\n *\n * Listing by exposure, not by the active set, keeps the codemode description unchanged when\n * `tool_search` loads a tool, so loads do not redeclare codemode.\n */\nfunction prepareCodemodeLoadout(loadout: ToolLoadout, options: CodemodeToolOptions): ToolLoadoutChanges {\n\tconst mode = options.getMode?.() ?? SETTINGS_DEFAULTS.codemode.mode;\n\tconst isDirect = (tool: AgentTool) => loadout.getExposure(tool.name) === \"direct\";\n\tconst callable = getCodemodeCallableTools(loadout.callable);\n\tconst callableNames = new Set(callable.map((tool) => tool.name));\n\tconst descriptions: Record<string, string> = {};\n\tif (mode === \"on\") {\n\t\tfor (const tool of loadout.declared) {\n\t\t\tif (callableNames.has(tool.name)) descriptions[tool.name] = describeScriptCall(tool);\n\t\t}\n\t}\n\tconst listed = mode === \"only\" ? callable : callable.filter((tool) => !isDirect(tool));\n\tconst namespaces = new Map(\n\t\tlisted.flatMap((tool) => {\n\t\t\tconst namespace = loadout.getNamespace(tool.name);\n\t\t\treturn namespace ? [[tool.name, namespace] as const] : [];\n\t\t}),\n\t);\n\tconst guidelines = new Map(listed.map((tool) => [tool.name, loadout.getPromptGuidelines(tool.name)] as const));\n\tdescriptions[CODEMODE_TOOL_NAME] = createCodemodeDescription(listed, {\n\t\tmodels: options.models === true,\n\t\tnamespaces,\n\t\tguidelines,\n\t\tdeferred: new Set(\n\t\t\tlisted.filter((tool) => loadout.getExposure(tool.name) === \"deferred\").map((tool) => tool.name),\n\t\t),\n\t\tinlineBudget: options.getInlineBudget?.() ?? DEFAULT_CODEMODE_INLINE_BUDGET,\n\t});\n\tconst declaredNames = new Set(loadout.declared.map((tool) => tool.name));\n\treturn {\n\t\tdescriptions,\n\t\thiddenDeclarations:\n\t\t\tmode === \"only\"\n\t\t\t\t? callable.filter((tool) => isDirect(tool) && declaredNames.has(tool.name)).map((tool) => tool.name)\n\t\t\t\t: [],\n\t};\n}\n\n/** Script globals that list or look up tools and namespaces, which the script may then call by any name. */\nconst DISCOVERY_GLOBALS = /\\b(searchTools|describeNamespace|describeTool|ALL_TOOLS)\\b/;\n\n/**\n * The tools a script may call (`ToolDefinition.reachesTools`): every tool when it uses a discovery\n * global, else the words of its source, so `tools.mcp__docs__search` and\n * `tools[\"mcp__docs__\" + name]` both name the `mcp__docs` namespace.\n */\nfunction getScriptReach(code: unknown): \"all\" | readonly string[] {\n\tif (typeof code !== \"string\") return [];\n\treturn DISCOVERY_GLOBALS.test(code) ? \"all\" : (code.match(/\\w+/g) ?? []);\n}\n\nexport function createCodemodeToolDefinition(\n\toptions: CodemodeToolOptions = {},\n): ToolDefinition<typeof codemodeSchema, CodemodeToolDetails | undefined> {\n\treturn {\n\t\tname: CODEMODE_TOOL_NAME,\n\t\tlabel: CODEMODE_TOOL_NAME,\n\t\t// Replaced with the declarations of the callable tools when the tool is activated.\n\t\tdescription: createCodemodeDescription([], { models: options.models === true }),\n\t\tpromptSnippet: codemodeToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: [...codemodeToolSystemPromptContribution.guidelines],\n\t\tparameters: codemodeSchema,\n\t\t// Scripts must not start other scripts.\n\t\texposure: \"model-only\",\n\t\tprepareLoadout: (loadout) => prepareCodemodeLoadout(loadout, options),\n\t\treachesTools: (input) => getScriptReach(input.code),\n\t\t// Capable models write the script as raw text instead of a JSON-escaped string.\n\t\tconstrainedSampling: { type: \"grammar\", variants: { openai_lark: CODEMODE_SOURCE_GRAMMAR } },\n\t\t// The sandbox (worker, QuickJS wasm) loads on the first call, not at startup.\n\t\texecute: async (toolCallId, params, signal, onUpdate, ctx) =>\n\t\t\t(await loadCodemodeExecutor()).executeCodemode(toolCallId, params, signal, onUpdate, ctx, options),\n\t\t...codemodeRenderers,\n\t};\n}\n\n/**\n * Create the codemode tool as an AgentTool. The description lists the given tools; the script can\n * call whatever tools the agent loop provides at execution time.\n */\nexport function createCodemodeTool(\n\ttools: readonly AgentTool<any>[] = [],\n\toptions: CodemodeToolOptions = {},\n): AgentTool<typeof codemodeSchema> {\n\tconst definition = createCodemodeToolDefinition(options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tdescription: createCodemodeDescription(tools, { models: options.models === true }),\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
@@ -1,5 +1,5 @@
1
- declare module "../core/keybindings.ts" {
2
- interface AppKeybindings {
1
+ declare module "@earendil-works/pi-tui" {
2
+ interface Keybindings {
3
3
  "app.list.toggle": true;
4
4
  }
5
5
  }
@@ -1 +1 @@
1
- {"version":3,"file":"list-keybindings.d.ts","sourceRoot":"","sources":["../../src/extensions/list-keybindings.ts"],"names":[],"mappings":"AAEA,OAAO,QAAQ,wBAAwB,CAAC;IACvC,UAAU,cAAc;QACvB,iBAAiB,EAAE,IAAI,CAAC;KACxB;CACD;AAED,gFAAgF;AAChF,wBAAgB,uBAAuB,IAAI,IAAI,CAI9C"}
1
+ {"version":3,"file":"list-keybindings.d.ts","sourceRoot":"","sources":["../../src/extensions/list-keybindings.ts"],"names":[],"mappings":"AAEA,OAAO,QAAQ,wBAAwB,CAAC;IACvC,UAAU,WAAW;QACpB,iBAAiB,EAAE,IAAI,CAAC;KACxB;CACD;AAED,gFAAgF;AAChF,wBAAgB,uBAAuB,IAAI,IAAI,CAI9C"}
@@ -1 +1 @@
1
- {"version":3,"file":"list-keybindings.js","sourceRoot":"","sources":["../../src/extensions/list-keybindings.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AAQrE,gFAAgF;AAChF,MAAM,UAAU,uBAAuB;IACtC,mBAAmB,CAAC;QACnB,iBAAiB,EAAE,EAAE,WAAW,EAAE,OAAO,EAAE,WAAW,EAAE,2BAA2B,EAAE;KACrF,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { registerKeybindings } from \"../core/keybinding-registry.ts\";\n\ndeclare module \"../core/keybindings.ts\" {\n\tinterface AppKeybindings {\n\t\t\"app.list.toggle\": true;\n\t}\n}\n\n/** Multi-select lists shared by bundled extensions (Question and /provider). */\nexport function registerListKeybindings(): void {\n\tregisterKeybindings({\n\t\t\"app.list.toggle\": { defaultKeys: \"space\", description: \"Toggle selected list item\" },\n\t});\n}\n"]}
1
+ {"version":3,"file":"list-keybindings.js","sourceRoot":"","sources":["../../src/extensions/list-keybindings.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AAQrE,gFAAgF;AAChF,MAAM,UAAU,uBAAuB;IACtC,mBAAmB,CAAC;QACnB,iBAAiB,EAAE,EAAE,WAAW,EAAE,OAAO,EAAE,WAAW,EAAE,2BAA2B,EAAE;KACrF,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { registerKeybindings } from \"../core/keybinding-registry.ts\";\n\ndeclare module \"@earendil-works/pi-tui\" {\n\tinterface Keybindings {\n\t\t\"app.list.toggle\": true;\n\t}\n}\n\n/** Multi-select lists shared by bundled extensions (Question and /provider). */\nexport function registerListKeybindings(): void {\n\tregisterKeybindings({\n\t\t\"app.list.toggle\": { defaultKeys: \"space\", description: \"Toggle selected list item\" },\n\t});\n}\n"]}
@@ -54,7 +54,7 @@ Options for add:
54
54
 
55
55
  Other options:
56
56
  --json Print the list as JSON
57
- --timeout <seconds> How long login waits for the browser (default: 300)`;
57
+ --timeout <seconds> Time limit for the whole sign-in (default: 300)`;
58
58
  const HELP_HINT = chalk.dim(`Use "${APP_NAME} mcp --help" for usage.`);
59
59
  const DEFAULT_LOGIN_TIMEOUT_SECONDS = 300;
60
60
  function errorMessage(error) {
@@ -374,10 +374,8 @@ async function list(loaded, json, untrustedNote, options, credentials, log) {
374
374
  });
375
375
  if (overrides.length > 0)
376
376
  report.toolExposure = Object.fromEntries(overrides);
377
- if (connection.hasResources) {
378
- report.resources = connection.resources.length;
379
- report.resourceTemplates = connection.resourceTemplates.length;
380
- }
377
+ if (connection.hasResources)
378
+ report.resources = true;
381
379
  if (connection.state !== "connected" && connection.error)
382
380
  report.error = connection.error;
383
381
  await connection.close();
@@ -410,9 +408,8 @@ async function list(loaded, json, untrustedNote, options, credentials, log) {
410
408
  });
411
409
  log(` tools: ${tools.join(", ")}`);
412
410
  }
413
- if (report.resources !== undefined) {
414
- log(` resources: ${report.resources}, URI templates: ${report.resourceTemplates ?? 0}`);
415
- }
411
+ if (report.resources)
412
+ log(" offers resources");
416
413
  if (report.error)
417
414
  log(` ${report.error.split("\n").join("\n ")}`);
418
415
  }