dal-code 1.0.39 → 1.0.40

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 (305) hide show
  1. package/CHANGELOG.md +82 -4
  2. package/NOTICE +224 -0
  3. package/dal-docs/examples/extensions/LICENSE +21 -0
  4. package/dal-docs/examples/extensions/README.md +64 -0
  5. package/dal-docs/examples/extensions/bookmark.ts +52 -0
  6. package/dal-docs/examples/extensions/claude-rules.ts +88 -0
  7. package/dal-docs/examples/extensions/commands.ts +74 -0
  8. package/dal-docs/examples/extensions/custom-footer.ts +66 -0
  9. package/dal-docs/examples/extensions/dirty-repo-guard.ts +58 -0
  10. package/dal-docs/examples/extensions/dynamic-tools.ts +76 -0
  11. package/dal-docs/examples/extensions/hello.ts +49 -0
  12. package/dal-docs/examples/extensions/inline-bash.ts +96 -0
  13. package/dal-docs/examples/extensions/permission-gate.ts +36 -0
  14. package/dal-docs/examples/extensions/protected-paths.ts +32 -0
  15. package/dal-docs/examples/extensions/session-name.ts +29 -0
  16. package/dal-docs/examples/extensions/status-line.ts +34 -0
  17. package/dal-docs/examples/extensions/structured-output.ts +67 -0
  18. package/dal-docs/examples/extensions/tool-override.ts +146 -0
  19. package/dal-docs/examples/extensions/trigger-compact.ts +59 -0
  20. package/dal-docs/examples/extensions/truncated-tool.ts +197 -0
  21. package/dal-docs/extensions.md +27 -0
  22. package/dist/cli/args.d.ts +3 -0
  23. package/dist/cli/args.js +17 -17
  24. package/dist/config.d.ts +1 -0
  25. package/dist/config.js +1 -1
  26. package/dist/core/agent-session.js +6 -6
  27. package/dist/core/extensions/loader.js +1 -1
  28. package/dist/core/extensions/permission-surface.js +1 -1
  29. package/dist/core/extensions/runner.js +1 -1
  30. package/dist/core/extensions/types.d.ts +15 -1
  31. package/dist/core/model-registry.d.ts +1 -0
  32. package/dist/core/model-registry.js +1 -1
  33. package/dist/core/nested-tool-calls.js +2 -2
  34. package/dist/core/resource-loader.js +1 -1
  35. package/dist/core/system-prompt.js +10 -9
  36. package/dist/core/tools/bash.js +13 -12
  37. package/dist/core/tools/path-utils.d.ts +5 -0
  38. package/dist/core/tools/process.d.ts +2 -0
  39. package/dist/core/tools/process.js +14 -13
  40. package/dist/dal/extension-compat.d.ts +62 -0
  41. package/dist/dal/extension-compat.js +4 -0
  42. package/dist/dal/hooks/extension.js +2 -2
  43. package/dist/dal/i18n.js +1 -1
  44. package/dist/dal/manifest.js +1 -1
  45. package/dist/dal/reviewed/endorsed-cli.js +1 -1
  46. package/dist/dal/reviewed/endorsed.js +1 -1
  47. package/dist/dal/reviewed/market-keys.js +1 -0
  48. package/dist/dal/reviewed/market.d.ts +64 -0
  49. package/dist/dal/reviewed/market.js +2 -0
  50. package/dist/extensions/mcp/runtime.d.ts +2 -1
  51. package/dist/extensions/mcp/runtime.js +3 -3
  52. package/dist/extensions/mcp/runtime.lazy.d.ts +1 -0
  53. package/dist/index.d.ts +7 -1
  54. package/dist/index.js +1 -1
  55. package/dist/main.js +4 -4
  56. package/dist/modes/acp/acp-mode.js +1 -1
  57. package/dist/modes/interactive/interactive-mode.d.ts +1 -0
  58. package/dist/modes/interactive/interactive-mode.js +14 -14
  59. package/dist/modes/print-mode.js +3 -3
  60. package/dist/modes/rpc/rpc-mode.js +1 -1
  61. package/dist/node_modules/@dalcode/dal-advisor/LICENSE +45 -0
  62. package/dist/node_modules/@dalcode/dal-advisor/package.json +35 -0
  63. package/dist/node_modules/@dalcode/dal-advisor/src/index.js +22 -0
  64. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  65. package/dist/node_modules/@dalcode/dal-bridge/src/ask-user.js +1 -1
  66. package/dist/node_modules/@dalcode/dal-capabilities/LICENSE +21 -0
  67. package/dist/node_modules/@dalcode/dal-capabilities/package.json +38 -0
  68. package/dist/node_modules/@dalcode/dal-capabilities/src/catalogue.js +1 -0
  69. package/dist/node_modules/@dalcode/dal-capabilities/src/index.js +11 -0
  70. package/dist/node_modules/@dalcode/dal-capabilities/src/install.js +4 -0
  71. package/dist/node_modules/@dalcode/dal-capabilities/src/match.js +1 -0
  72. package/dist/node_modules/@dalcode/dal-capabilities/src/state.js +3 -0
  73. package/dist/node_modules/@dalcode/dal-compat/LICENSE +21 -0
  74. package/dist/node_modules/@dalcode/dal-compat/package.json +32 -0
  75. package/dist/node_modules/@dalcode/dal-compat/src/claude-rules.js +3 -0
  76. package/dist/node_modules/@dalcode/dal-compat/src/index.js +7 -0
  77. package/dist/node_modules/@dalcode/dal-dap/LICENSE +47 -0
  78. package/dist/node_modules/@dalcode/dal-dap/package.json +38 -0
  79. package/dist/node_modules/@dalcode/dal-dap/src/adapters.js +1 -0
  80. package/dist/node_modules/@dalcode/dal-dap/src/client.js +5 -0
  81. package/dist/node_modules/@dalcode/dal-dap/src/index.js +9 -0
  82. package/dist/node_modules/@dalcode/dal-dap/src/install.js +2 -0
  83. package/dist/node_modules/@dalcode/dal-dap/src/session.js +2 -0
  84. package/dist/node_modules/@dalcode/dal-dap/src/types.js +0 -0
  85. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  86. package/dist/node_modules/@dalcode/dal-goal/package.json +4 -3
  87. package/dist/node_modules/@dalcode/dal-goal/src/core.js +6 -6
  88. package/dist/node_modules/@dalcode/dal-goal/src/index.js +17 -7
  89. package/dist/node_modules/@dalcode/dal-goal/src/verify.js +26 -0
  90. package/dist/node_modules/@dalcode/dal-guard/package.json +6 -4
  91. package/dist/node_modules/@dalcode/dal-guard/src/credentials.js +1 -1
  92. package/dist/node_modules/@dalcode/dal-guard/src/edit-anchor-core.js +23 -0
  93. package/dist/node_modules/@dalcode/dal-guard/src/edit-anchor.js +4 -0
  94. package/dist/node_modules/@dalcode/dal-guard/src/index.js +1 -1
  95. package/dist/node_modules/@dalcode/dal-guard/src/workspace.js +2 -2
  96. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  97. package/dist/node_modules/@dalcode/dal-interactive/LICENSE +209 -0
  98. package/dist/node_modules/@dalcode/dal-interactive/package.json +4 -3
  99. package/dist/node_modules/@dalcode/dal-interactive/src/btw.js +25 -0
  100. package/dist/node_modules/@dalcode/dal-interactive/src/index.js +1 -1
  101. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  102. package/dist/node_modules/@dalcode/dal-learn/LICENSE +21 -0
  103. package/dist/node_modules/@dalcode/dal-learn/package.json +35 -0
  104. package/dist/node_modules/@dalcode/dal-learn/src/engine.js +8 -0
  105. package/dist/node_modules/@dalcode/dal-learn/src/extract.js +14 -0
  106. package/dist/node_modules/@dalcode/dal-learn/src/index.js +17 -0
  107. package/dist/node_modules/@dalcode/dal-learn/src/lessons.js +3 -0
  108. package/dist/node_modules/@dalcode/dal-learn/src/migrate.js +1 -0
  109. package/dist/node_modules/@dalcode/dal-learn/src/procedures.js +11 -0
  110. package/dist/node_modules/@dalcode/dal-learn/src/project-map.js +2 -0
  111. package/dist/node_modules/@dalcode/dal-learn/src/project.js +1 -0
  112. package/dist/node_modules/@dalcode/dal-learn/src/safety.js +2 -0
  113. package/dist/node_modules/@dalcode/dal-learn/src/signals.js +5 -0
  114. package/dist/node_modules/@dalcode/dal-learn/src/skill-actions.js +1 -0
  115. package/dist/node_modules/@dalcode/dal-learn/src/skill-evolution.js +16 -0
  116. package/dist/node_modules/@dalcode/dal-learn/src/store.js +2 -0
  117. package/dist/node_modules/@dalcode/dal-lsp/package.json +6 -4
  118. package/dist/node_modules/@dalcode/dal-lsp/src/client.js +3 -3
  119. package/dist/node_modules/@dalcode/dal-lsp/src/config.js +1 -1
  120. package/dist/node_modules/@dalcode/dal-lsp/src/format.js +8 -7
  121. package/dist/node_modules/@dalcode/dal-lsp/src/index.js +11 -8
  122. package/dist/node_modules/@dalcode/dal-mcp/package.json +6 -5
  123. package/dist/node_modules/@dalcode/dal-mcp/src/config.d.ts +1 -0
  124. package/dist/node_modules/@dalcode/dal-mcp/src/config.js +1 -1
  125. package/dist/node_modules/@dalcode/dal-mcp/src/http-client.d.ts +32 -1
  126. package/dist/node_modules/@dalcode/dal-mcp/src/http-client.js +2 -1
  127. package/dist/node_modules/@dalcode/dal-mcp/src/index.js +16 -16
  128. package/dist/node_modules/@dalcode/dal-mcp/src/oauth.js +2 -0
  129. package/dist/node_modules/@dalcode/dal-mcp/src/stdio-client.d.ts +4 -2
  130. package/dist/node_modules/@dalcode/dal-mcp/src/stdio-client.js +4 -4
  131. package/dist/node_modules/@dalcode/dal-mcp/src/types.d.ts +9 -0
  132. package/dist/node_modules/@dalcode/dal-mcp/src/types.js +1 -1
  133. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  134. package/dist/node_modules/@dalcode/dal-office/src/index.d.ts +6 -3
  135. package/dist/node_modules/@dalcode/dal-office/src/index.js +1 -1
  136. package/dist/node_modules/@dalcode/dal-office/src/render/chart-theme.d.ts +13 -0
  137. package/dist/node_modules/@dalcode/dal-office/src/render/chart-theme.js +1 -0
  138. package/dist/node_modules/@dalcode/dal-office/src/render/chart.d.ts +16 -0
  139. package/dist/node_modules/@dalcode/dal-office/src/render/chart.js +4 -2
  140. package/dist/node_modules/@dalcode/dal-office/src/render/docx.d.ts +4 -1
  141. package/dist/node_modules/@dalcode/dal-office/src/render/docx.js +1 -1
  142. package/dist/node_modules/@dalcode/dal-office/src/render/drawio-style.d.ts +4 -0
  143. package/dist/node_modules/@dalcode/dal-office/src/render/drawio-style.js +1 -0
  144. package/dist/node_modules/@dalcode/dal-office/src/render/pptx.d.ts +52 -4
  145. package/dist/node_modules/@dalcode/dal-office/src/render/pptx.js +3 -2
  146. package/dist/node_modules/@dalcode/dal-office/src/render/thumbnails.d.ts +1 -1
  147. package/dist/node_modules/@dalcode/dal-office/src/render/thumbnails.js +1 -1
  148. package/dist/node_modules/@dalcode/dal-office/src/render/xlsx.d.ts +1 -0
  149. package/dist/node_modules/@dalcode/dal-office/src/render/xlsx.js +1 -1
  150. package/dist/node_modules/@dalcode/dal-office/src/scratchpad.d.ts +30 -1
  151. package/dist/node_modules/@dalcode/dal-office/src/scratchpad.js +1 -1
  152. package/dist/node_modules/@dalcode/dal-office/src/themes.d.ts +35 -1
  153. package/dist/node_modules/@dalcode/dal-office/src/themes.js +1 -1
  154. package/dist/node_modules/@dalcode/dal-office/src/tools/chart-generate.js +3 -3
  155. package/dist/node_modules/@dalcode/dal-office/src/tools/doc-generate.js +2 -2
  156. package/dist/node_modules/@dalcode/dal-office/src/tools/drawio-generate.js +3 -3
  157. package/dist/node_modules/@dalcode/dal-office/src/tools/ppt-generate.js +2 -2
  158. package/dist/node_modules/@dalcode/dal-office/src/tools/ppt-plan.js +2 -2
  159. package/dist/node_modules/@dalcode/dal-office/src/tools/sheet-generate.js +2 -2
  160. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +4 -4
  161. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  162. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +4 -4
  163. package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -5
  164. package/dist/node_modules/@dalcode/dal-plugins/src/index.js +11 -11
  165. package/dist/node_modules/@dalcode/dal-plugins/src/manage.js +8 -10
  166. package/dist/node_modules/@dalcode/dal-plugins/src/npm-hook.js +1 -1
  167. package/dist/node_modules/@dalcode/dal-plugins/src/registry.js +2 -2
  168. package/dist/node_modules/@dalcode/dal-recall/LICENSE +45 -0
  169. package/dist/node_modules/@dalcode/dal-recall/package.json +34 -0
  170. package/dist/node_modules/@dalcode/dal-recall/src/index-db.js +57 -0
  171. package/dist/node_modules/@dalcode/dal-recall/src/index.js +1 -0
  172. package/dist/node_modules/@dalcode/dal-recall/src/query.js +1 -0
  173. package/dist/node_modules/@dalcode/dal-recall/src/redact.js +1 -0
  174. package/dist/node_modules/@dalcode/dal-recall/src/sqlite.js +1 -0
  175. package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
  176. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  177. package/dist/node_modules/@dalcode/dal-rewind/src/commands.js +2 -2
  178. package/dist/node_modules/@dalcode/dal-rewind/src/core.d.ts +21 -8
  179. package/dist/node_modules/@dalcode/dal-rewind/src/core.js +8 -3
  180. package/dist/node_modules/@dalcode/dal-rewind/src/index.js +1 -1
  181. package/dist/node_modules/@dalcode/dal-rewind/src/state.js +1 -1
  182. package/dist/node_modules/@dalcode/dal-router/package.json +6 -5
  183. package/dist/node_modules/@dalcode/dal-router/src/advisor.js +1 -0
  184. package/dist/node_modules/@dalcode/dal-router/src/assist.js +4 -2
  185. package/dist/node_modules/@dalcode/dal-router/src/commands.js +8 -8
  186. package/dist/node_modules/@dalcode/dal-router/src/config.d.ts +3 -0
  187. package/dist/node_modules/@dalcode/dal-router/src/config.js +2 -2
  188. package/dist/node_modules/@dalcode/dal-router/src/index.js +4 -4
  189. package/dist/node_modules/@dalcode/dal-router/src/jev.d.ts +2 -1
  190. package/dist/node_modules/@dalcode/dal-router/src/jev.js +4 -4
  191. package/dist/node_modules/@dalcode/dal-router/src/services.js +1 -1
  192. package/dist/node_modules/@dalcode/dal-router/src/subagent.js +1 -1
  193. package/dist/node_modules/@dalcode/dal-skills/package.json +4 -3
  194. package/dist/node_modules/@dalcode/dal-skills/src/bundled/browser-qa/SKILL.md +48 -0
  195. package/dist/node_modules/@dalcode/dal-skills/src/bundled/diagram-design/SKILL.md +81 -0
  196. package/dist/node_modules/@dalcode/dal-skills/src/bundled/poster-design/SKILL.md +50 -0
  197. package/dist/node_modules/@dalcode/dal-skills/src/bundled/print-design/SKILL.md +55 -0
  198. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/dashboard.html +177 -0
  199. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/diagram.html +39 -0
  200. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/echarts-dal.json +360 -0
  201. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/email/notice.html +46 -0
  202. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/landing.html +173 -0
  203. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/mermaid-dal.json +140 -0
  204. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/mindmap.html +65 -0
  205. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/event-poster.html +40 -0
  206. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/poster.css +41 -0
  207. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/square-card.html +25 -0
  208. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/wechat-cover.html +29 -0
  209. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/xhs-card.html +35 -0
  210. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/xhs-cover.html +26 -0
  211. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/print/letter.html +35 -0
  212. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/print/print.css +65 -0
  213. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/print/report.html +76 -0
  214. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/print/resume.html +72 -0
  215. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/render.mjs +18 -0
  216. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/tokens.css +264 -0
  217. package/dist/node_modules/@dalcode/dal-skills/src/bundled/web-design/SKILL.md +73 -0
  218. package/dist/node_modules/@dalcode/dal-skills/src/bundled.js +1 -0
  219. package/dist/node_modules/@dalcode/dal-skills/src/catalog.js +2 -2
  220. package/dist/node_modules/@dalcode/dal-skills/src/index.js +16 -11
  221. package/dist/node_modules/@dalcode/dal-statusline/LICENSE +21 -0
  222. package/dist/node_modules/@dalcode/dal-statusline/package.json +31 -0
  223. package/dist/node_modules/@dalcode/dal-statusline/src/index.js +3 -0
  224. package/dist/node_modules/@dalcode/dal-structured/LICENSE +21 -0
  225. package/dist/node_modules/@dalcode/dal-structured/package.json +32 -0
  226. package/dist/node_modules/@dalcode/dal-structured/src/index.js +9 -0
  227. package/dist/node_modules/@dalcode/dal-subagent/LICENSE +24 -0
  228. package/dist/node_modules/@dalcode/dal-subagent/package.json +7 -6
  229. package/dist/node_modules/@dalcode/dal-subagent/src/background.js +13 -0
  230. package/dist/node_modules/@dalcode/dal-subagent/src/index.js +22 -14
  231. package/dist/node_modules/@dalcode/dal-subagent/src/inproc-runner.js +3 -0
  232. package/dist/node_modules/@dalcode/dal-subagent/src/pool.js +1 -0
  233. package/dist/node_modules/@dalcode/dal-subagent/src/process-runner.js +3 -3
  234. package/dist/node_modules/@dalcode/dal-subagent/src/tmux-runner.js +3 -0
  235. package/dist/node_modules/@dalcode/dal-subagent/src/worktree.js +2 -0
  236. package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
  237. package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
  238. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  239. package/dist/node_modules/@dalcode/dal-tool-catalog/src/groups.js +1 -1
  240. package/dist/node_modules/@dalcode/dal-tool-catalog/src/index.js +4 -4
  241. package/dist/node_modules/@dalcode/dal-tool-catalog/src/repair-hook.js +1 -0
  242. package/dist/node_modules/@dalcode/dal-tool-catalog/src/repair.js +4 -0
  243. package/dist/node_modules/@dalcode/dal-usage/LICENSE +45 -0
  244. package/dist/node_modules/@dalcode/dal-usage/package.json +33 -0
  245. package/dist/node_modules/@dalcode/dal-usage/src/budget.d.ts +14 -0
  246. package/dist/node_modules/@dalcode/dal-usage/src/budget.js +3 -0
  247. package/dist/node_modules/@dalcode/dal-usage/src/data.d.ts +30 -0
  248. package/dist/node_modules/@dalcode/dal-usage/src/data.js +1 -0
  249. package/dist/node_modules/@dalcode/dal-usage/src/index.d.ts +12 -0
  250. package/dist/node_modules/@dalcode/dal-usage/src/index.js +2 -0
  251. package/dist/node_modules/@dalcode/dal-usage/src/report.d.ts +29 -0
  252. package/dist/node_modules/@dalcode/dal-usage/src/report.js +3 -0
  253. package/dist/node_modules/@dalcode/dal-web/package.json +6 -4
  254. package/dist/node_modules/@dalcode/dal-web/src/fetch.js +11 -5
  255. package/dist/node_modules/@dalcode/dal-web/src/index.js +2 -2
  256. package/dist/node_modules/@dalcode/dal-web/src/pdf.js +5 -0
  257. package/dist/node_modules/@dalcode/dal-workflow/LICENSE +24 -0
  258. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  259. package/dist/node_modules/@dalcode/dal-workflow/src/announce-check.js +1 -0
  260. package/dist/node_modules/@dalcode/dal-workflow/src/check-in.js +1 -1
  261. package/dist/node_modules/@dalcode/dal-workflow/src/completion-check.js +2 -2
  262. package/dist/node_modules/@dalcode/dal-workflow/src/index.js +4 -4
  263. package/dist/node_modules/@dalcode/dal-workflow/src/lean-code.js +1 -0
  264. package/dist/node_modules/@dalcode/dal-workflow/src/ledger.js +3 -3
  265. package/dist/node_modules/@dalcode/dal-workflow/src/loop-guard.js +3 -0
  266. package/dist/node_modules/@dalcode/dal-workflow/src/shared.js +2 -2
  267. package/dist/node_modules/@dalcode/dal-workflow/src/todo.js +4 -2
  268. package/dist/node_modules/@dalcode/dal-workflow/src/verify-check.js +2 -0
  269. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  270. package/dist/node_modules/@earendil-works/chord/package.json +1 -1
  271. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
  272. package/dist/node_modules/@earendil-works/pi-ai/dist/cli.js +0 -0
  273. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  274. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  275. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  276. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/radius.json +1 -1
  277. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  278. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
  279. package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
  280. package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
  281. package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
  282. package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
  283. package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
  284. package/dist/node_modules/@earendil-works/pi-server/package.json +3 -3
  285. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  286. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  287. package/dist/package-manager-cli.js +61 -61
  288. package/dist/sdk/office.d.ts +1 -1
  289. package/dist/sdk/office.js +1 -1
  290. package/dist/sdk/rewind.d.ts +1 -1
  291. package/dist/sdk/rewind.js +1 -1
  292. package/dist/sdk/usage.d.ts +8 -0
  293. package/dist/sdk/usage.js +1 -0
  294. package/dist/utils/open-browser.d.ts +1 -0
  295. package/dist/utils/tools-manager.js +1 -1
  296. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  297. package/examples/extensions/gondolin/package-lock.json +2 -2
  298. package/examples/extensions/gondolin/package.json +1 -1
  299. package/examples/extensions/sandbox/package-lock.json +2 -2
  300. package/examples/extensions/sandbox/package.json +1 -1
  301. package/examples/extensions/with-deps/package-lock.json +2 -2
  302. package/examples/extensions/with-deps/package.json +1 -1
  303. package/npm-shrinkwrap.json +57 -14
  304. package/package.json +9 -2
  305. package/dist/node_modules/@dalcode/dal-plugins/src/compat.js +0 -2
@@ -1 +1 @@
1
- var v=Object.defineProperty;var a=(u,e)=>v(u,"name",{value:e,configurable:!0});import{getCurrentSystemMessage as P}from"@earendil-works/pi-ai";import{theme as w}from"../../modes/interactive/theme/theme.js";import{buildSystemPrompt as E,normalizeBuildSystemPromptOptions as p}from"../system-prompt.js";const S=["app.interrupt","app.clear","app.exit","app.suspend","app.thinking.cycle","app.model.cycleForward","app.model.cycleBackward","app.model.select","app.tools.expand","app.thinking.toggle","app.editor.external","app.message.copy","app.message.followUp","tui.input.submit","tui.select.confirm","tui.select.cancel","tui.input.copy","tui.editor.deleteToLineEnd"],C=a(u=>{const e={};for(const[s,t]of Object.entries(u)){if(t===void 0)continue;const i=Array.isArray(t)?t:[t],n=S.includes(s);for(const o of i){const r=o.toLowerCase();e[r]?.restrictOverride&&!n||(e[r]={keybinding:s,restrictOverride:n})}}return e},"buildBuiltinKeybindings");function k(u){if(typeof u!="object"||u===null)return!1;const e=u,s=e.operations!==void 0,t=e.result!==void 0;if(s===t)return!1;if(s){const o=e.operations;return typeof o!="object"||o===null?!1:typeof o.exec=="function"}const i=e.result;if(typeof i!="object"||i===null)return!1;const n=i;return typeof n.output=="string"&&"exitCode"in n&&(n.exitCode===void 0||typeof n.exitCode=="number")&&typeof n.cancelled=="boolean"&&typeof n.truncated=="boolean"&&(n.fullOutputPath===void 0||typeof n.fullOutputPath=="string")}a(k,"isUserBashEventResult");async function R(u,e){return u.hasHandlers("session_shutdown")?(await u.emit(e),!0):!1}a(R,"emitSessionShutdownEvent");function g(u,e){return u.map(s=>({ext:s,handlers:s.handlers.get(e)?.slice()??[]}))}a(g,"snapshotEventHandlers");function y(u,e){return u.length===e.length&&u.every((s,t)=>s===e[t])}a(y,"sameMessages");function M(u,e,s){if(y(s,e))return u;const t=P(u);return t?[t,...s]:s}a(M,"restoreSystemMessages");async function I(u,e,s){const t=[];for(const{ext:i,handlers:n}of g(u.extensions,"project_trust"))for(const o of n)try{const r=await o(e,s);if(r.trusted==="undecided")continue;return{result:r,errors:t}}catch(r){t.push({extensionPath:i.path,event:e.type,error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0})}return{errors:t}}a(I,"emitProjectTrustEvent");const x={select:a(async()=>{},"select"),confirm:a(async()=>!1,"confirm"),input:a(async()=>{},"input"),notify:a(()=>{},"notify"),setPanel:a(()=>{},"setPanel"),requestInput:a(async()=>{},"requestInput"),requestChoice:a(async()=>{},"requestChoice"),onTerminalInput:a(()=>()=>{},"onTerminalInput"),setStatus:a(()=>{},"setStatus"),setWorkingMessage:a(()=>{},"setWorkingMessage"),setWorkingVisible:a(()=>{},"setWorkingVisible"),setWorkingIndicator:a(()=>{},"setWorkingIndicator"),setHiddenThinkingLabel:a(()=>{},"setHiddenThinkingLabel"),setWidget:a(()=>{},"setWidget"),setFooter:a(()=>{},"setFooter"),setHeader:a(()=>{},"setHeader"),setTitle:a(()=>{},"setTitle"),custom:a(async()=>{},"custom"),pasteToEditor:a(()=>{},"pasteToEditor"),setEditorText:a(()=>{},"setEditorText"),getEditorText:a(()=>"","getEditorText"),editor:a(async()=>{},"editor"),addAutocompleteProvider:a(()=>{},"addAutocompleteProvider"),setEditorComponent:a(()=>{},"setEditorComponent"),getEditorComponent:a(()=>{},"getEditorComponent"),get theme(){return w},getAllThemes:a(()=>[],"getAllThemes"),getTheme:a(()=>{},"getTheme"),setTheme:a(u=>({success:!1,error:"UI not available"}),"setTheme"),getToolsExpanded:a(()=>!1,"getToolsExpanded"),setToolsExpanded:a(()=>{},"setToolsExpanded")};class U{static{a(this,"ExtensionRunner")}extensions;runtime;uiContext;mode="print";cwd;sessionManager;modelRegistry;errorListeners=new Set;getModel=a(()=>{},"getModel");getScopedModels=a(()=>[],"getScopedModels");isIdleFn=a(()=>!0,"isIdleFn");isProjectTrustedFn=a(()=>!0,"isProjectTrustedFn");getSignalFn=a(()=>{},"getSignalFn");waitForIdleFn=a(async()=>{},"waitForIdleFn");abortFn=a(()=>{},"abortFn");hasPendingMessagesFn=a(()=>!1,"hasPendingMessagesFn");getContextUsageFn=a(()=>{},"getContextUsageFn");compactFn=a(()=>{},"compactFn");getSystemPromptFn=a(()=>"","getSystemPromptFn");getSystemPromptOptionsFn=a(()=>p({cwd:this.cwd}),"getSystemPromptOptionsFn");executeToolFn;getCallableToolsFn=a(()=>[],"getCallableToolsFn");reportedMcpServers=new Set;newSessionHandler=a(async()=>({cancelled:!1}),"newSessionHandler");forkHandler=a(async()=>({cancelled:!1}),"forkHandler");navigateTreeHandler=a(async()=>({cancelled:!1}),"navigateTreeHandler");switchSessionHandler=a(async()=>({cancelled:!1}),"switchSessionHandler");reloadHandler=a(async()=>{},"reloadHandler");shutdownHandler=a(()=>{},"shutdownHandler");shortcutDiagnostics=[];commandDiagnostics=[];staleMessage;uiPromptDepth=0;activeUIPrompt;constructor(e,s,t,i,n){this.extensions=e,this.runtime=s,this.uiContext=x,this.cwd=t,this.sessionManager=i,this.modelRegistry=n}bindCore(e,s,t){this.runtime.sendMessage=e.sendMessage,this.runtime.sendUserMessage=e.sendUserMessage,this.runtime.appendEntry=e.appendEntry,this.runtime.emitHostEvent=e.emitHostEvent??(()=>{}),this.runtime.setSessionName=e.setSessionName,this.runtime.getSessionName=e.getSessionName,this.runtime.setLabel=e.setLabel,this.runtime.getActiveTools=e.getActiveTools,this.runtime.getAllTools=e.getAllTools,this.runtime.getSettings=e.getSettings,this.runtime.setActiveTools=e.setActiveTools,this.runtime.isToolAllowed=e.isToolAllowed,this.runtime.getToolAllowlist=e.getToolAllowlist,this.runtime.getToolDenylist=e.getToolDenylist,this.runtime.refreshTools=e.refreshTools,this.runtime.getCommands=e.getCommands,this.runtime.setModel=e.setModel,this.runtime.getThinkingLevel=e.getThinkingLevel,this.runtime.setThinkingLevel=e.setThinkingLevel,this.runtime.createContext=()=>this.createContext(),this.getModel=s.getModel,this.getScopedModels=s.getScopedModels,this.isIdleFn=s.isIdle,this.isProjectTrustedFn=s.isProjectTrusted,this.getSignalFn=s.getSignal,this.abortFn=s.abort,this.hasPendingMessagesFn=s.hasPendingMessages,this.shutdownHandler=s.shutdown,this.getContextUsageFn=s.getContextUsage,this.compactFn=s.compact,this.getSystemPromptFn=s.getSystemPrompt,this.getSystemPromptOptionsFn=s.getSystemPromptOptions??(()=>p({cwd:this.cwd})),this.executeToolFn=s.executeTool,this.getCallableToolsFn=s.getCallableTools??(()=>[]),this.runtime.mcpServers.setChangeListener(()=>{this.emit({type:"mcp_servers_change",servers:this.runtime.mcpServers.list()}),this.reportUnhandledMcpServers()});for(const{name:n,config:o,extensionPath:r}of this.runtime.pendingProviderRegistrations)try{t?.registerProvider?t.registerProvider(n,o):this.modelRegistry.registerProvider(n,o)}catch(c){this.emitError({extensionPath:r,event:"register_provider",error:c instanceof Error?c.message:String(c),stack:c instanceof Error?c.stack:void 0})}this.runtime.pendingProviderRegistrations=[];for(const{provider:n,extensionPath:o}of this.runtime.pendingNativeProviderRegistrations)try{t?.registerNativeProvider?t.registerNativeProvider(n):this.modelRegistry.registerProvider(n)}catch(r){this.emitError({extensionPath:o,event:"register_provider",error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0})}this.runtime.pendingNativeProviderRegistrations=[];const i=a(n=>{t?.registerVirtualModel?t.registerVirtualModel(n):this.modelRegistry.registerVirtualModel(n)},"registerVirtualModel");for(const{definition:n,extensionPath:o}of this.runtime.pendingVirtualModelRegistrations)try{i(n)}catch(r){this.emitError({extensionPath:o,event:"register_virtual_model",error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0})}this.runtime.pendingVirtualModelRegistrations=[],this.runtime.registerProvider=(n,o)=>{if(t?.registerProvider){t.registerProvider(n,o);return}this.modelRegistry.registerProvider(n,o)},this.runtime.registerNativeProvider=n=>{if(t?.registerNativeProvider){t.registerNativeProvider(n);return}this.modelRegistry.registerProvider(n)},this.runtime.unregisterProvider=n=>{if(t?.unregisterProvider){t.unregisterProvider(n);return}this.modelRegistry.unregisterProvider(n)},this.runtime.registerVirtualModel=i,this.runtime.unregisterVirtualModel=(n,o)=>{t?.unregisterVirtualModel?t.unregisterVirtualModel(n,o):this.modelRegistry.unregisterVirtualModel(n,o)}}bindCommandContext(e){if(e){this.waitForIdleFn=e.waitForIdle,this.newSessionHandler=e.newSession,this.forkHandler=e.fork,this.navigateTreeHandler=e.navigateTree,this.switchSessionHandler=e.switchSession,this.reloadHandler=e.reload;return}this.waitForIdleFn=async()=>{},this.newSessionHandler=async()=>({cancelled:!1}),this.forkHandler=async()=>({cancelled:!1}),this.navigateTreeHandler=async()=>({cancelled:!1}),this.switchSessionHandler=async()=>({cancelled:!1}),this.reloadHandler=async()=>{}}setUIContext(e,s="print"){this.uiContext=e?this.wrapUIPromptContext(e):x,this.mode=s}wrapUIPromptContext(e){return{...e,select:a((s,t,i)=>this.withUIPrompt("select",s,()=>e.select(s,t,i)),"select"),confirm:a((s,t,i)=>this.withUIPrompt("confirm",s,()=>e.confirm(s,t,i)),"confirm"),input:a((s,t,i)=>this.withUIPrompt("input",s,()=>e.input(s,t,i)),"input"),editor:a((s,t)=>this.withUIPrompt("editor",s,()=>e.editor(s,t)),"editor"),custom:a((s,t)=>this.withUIPrompt("custom",void 0,()=>e.custom(s,t)),"custom")}}withUIPrompt(e,s,t){this.uiPromptDepth++===0&&(this.activeUIPrompt={kind:e,title:s},this.emitUIPromptEvent({type:"ui_prompt_start",reason:"ui_prompt",kind:e,...s?{title:s}:{}}));const n=a(()=>{if(--this.uiPromptDepth>0)return;this.uiPromptDepth=0;const o=this.activeUIPrompt??{kind:e,title:s};this.activeUIPrompt=void 0,this.emitUIPromptEvent({type:"ui_prompt_end",reason:"ui_prompt",kind:o.kind,...o.title?{title:o.title}:{}})},"finish");try{return t().finally(n)}catch(o){throw n(),o}}emitUIPromptEvent(e){queueMicrotask(()=>{this.emit(e)})}getUIContext(){return this.uiContext}hasUI(){return this.uiContext!==x}getExtensionPaths(){return this.extensions.map(e=>e.path)}getAllRegisteredTools(){const e=new Map;for(const s of this.extensions)for(const t of s.tools.values())e.has(t.definition.name)||e.set(t.definition.name,t);return Array.from(e.values())}getToolDefinition(e){for(const s of this.extensions){const t=s.tools.get(e);if(t)return t.definition}}getFlags(){const e=new Map;for(const s of this.extensions)for(const[t,i]of s.flags)e.has(t)||e.set(t,i);return e}setFlagValue(e,s){this.runtime.flagValues.set(e,s)}getFlagValues(){return new Map(this.runtime.flagValues)}getShortcuts(e){this.shortcutDiagnostics=[];const s=C(e),t=new Map,i=a((n,o)=>{this.shortcutDiagnostics.push({type:"warning",message:n,path:o}),this.hasUI()||console.warn(n)},"addDiagnostic");for(const n of this.extensions)for(const[o,r]of n.shortcuts){const c=o.toLowerCase(),l=s[c];if(l?.restrictOverride===!0){i(`Extension shortcut '${o}' from ${r.extensionPath} conflicts with built-in shortcut. Skipping.`,r.extensionPath);continue}l?.restrictOverride===!1&&i(`Extension shortcut conflict: '${o}' is built-in shortcut for ${l.keybinding} and ${r.extensionPath}. Using ${r.extensionPath}.`,r.extensionPath);const h=t.get(c);h&&i(`Extension shortcut conflict: '${o}' registered by both ${h.extensionPath} and ${r.extensionPath}. Using ${r.extensionPath}.`,r.extensionPath),t.set(c,r)}return t}getShortcutDiagnostics(){return this.shortcutDiagnostics}invalidate(e="This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload()."){this.staleMessage||(this.staleMessage=e,this.runtime.invalidate(e))}assertActive(){if(this.staleMessage)throw new Error(this.staleMessage)}onError(e){return this.errorListeners.add(e),()=>this.errorListeners.delete(e)}emitError(e){for(const s of this.errorListeners)s(e)}reportUnhandledMcpServers(){if(!this.hasHandlers("mcp_servers_change"))for(const e of this.runtime.mcpServers.list())this.reportedMcpServers.has(e.name)||(this.reportedMcpServers.add(e.name),this.emitError({extensionPath:e.extensionPath,event:"register_mcp_server",error:`MCP server "${e.name}" is registered, but no loaded extension connects MCP servers; another extension may have replaced the built-in MCP support`}))}hasHandlers(e){for(const s of this.extensions){const t=s.handlers.get(e);if(t&&t.length>0)return!0}return!1}getMessageRenderer(e){for(const s of this.extensions){const t=s.messageRenderers.get(e);if(t)return t}}getMarkdownTransformers(){return this.extensions.flatMap(e=>e.markdownTransformer?[e.markdownTransformer]:[])}getModelPickerEntries(){return this.extensions.flatMap(e=>[...e.modelPickerEntries?.values()??[]])}resolveToolRenderers(e,s){const t=this.extensions.flatMap(n=>n.toolRenderers??[]),i=a(n=>n<t.length?t[n](e,()=>i(n+1)):s(),"resolve");return i(0)}getEntryRenderer(e){for(const s of this.extensions){const t=s.entryRenderers?.get(e);if(t)return t}}resolveRegisteredCommands(){const e=[],s=new Map;for(const n of this.extensions)for(const o of n.commands.values())e.push(o),s.set(o.name,(s.get(o.name)??0)+1);const t=new Map,i=new Set;return e.map(n=>{const o=(t.get(n.name)??0)+1;t.set(n.name,o);let r=(s.get(n.name)??0)>1?`${n.name}:${o}`:n.name;if(i.has(r)){let c=o;do c++,r=`${n.name}:${c}`;while(i.has(r))}return i.add(r),{...n,invocationName:r}})}getModelRegistry(){return this.modelRegistry}getRegisteredCommands(){return this.commandDiagnostics=[],this.resolveRegisteredCommands()}getCommandDiagnostics(){return this.commandDiagnostics}getCommand(e){return this.resolveRegisteredCommands().find(s=>s.invocationName===e)}shutdown(){this.shutdownHandler()}getActiveTools(){return this.assertActive(),this.runtime.getActiveTools()}createContext(){const e=this,s=this.getModel,t=this.getScopedModels;return{get ui(){return e.assertActive(),e.uiContext},get mode(){return e.assertActive(),e.mode},get hasUI(){return e.assertActive(),e.hasUI()},get cwd(){return e.assertActive(),e.cwd},get sessionManager(){return e.assertActive(),e.sessionManager},get modelRegistry(){return e.assertActive(),e.modelRegistry},get model(){return e.assertActive(),s()},get scopedModels(){return e.assertActive(),t()},get thinkingLevel(){return e.assertActive(),e.runtime.getThinkingLevel()},isIdle:a(()=>(e.assertActive(),e.isIdleFn()),"isIdle"),isProjectTrusted:a(()=>(e.assertActive(),e.isProjectTrustedFn()),"isProjectTrusted"),get signal(){return e.assertActive(),e.getSignalFn()},abort:a(()=>{e.assertActive(),e.abortFn()},"abort"),hasPendingMessages:a(()=>(e.assertActive(),e.hasPendingMessagesFn()),"hasPendingMessages"),shutdown:a(()=>{e.assertActive(),e.shutdownHandler()},"shutdown"),getContextUsage:a(()=>(e.assertActive(),e.getContextUsageFn()),"getContextUsage"),compact:a(i=>{e.assertActive(),e.compactFn(i)},"compact"),getSystemPrompt:a(()=>(e.assertActive(),e.getSystemPromptFn()),"getSystemPrompt")}}createToolContext(e,s){const t=this;return Object.defineProperties(this.createContext(),{tools:{get(){return t.assertActive(),t.getCallableToolsFn()}},executeTool:{value:a(async(i,n,o={})=>(t.assertActive(),t.executeToolFn?t.executeToolFn(e,i,n,{...o,signal:o.signal??s}):{toolCall:{type:"toolCall",id:`${e}/0`,name:i,arguments:{}},result:{content:[{type:"text",text:"Nested tool calls are not available in this context"}],details:{}},isError:!0}),"value")}})}createCommandContext(){const e=Object.defineProperties({},Object.getOwnPropertyDescriptors(this.createContext()));return e.getSystemPromptOptions=()=>(this.assertActive(),this.getSystemPromptOptionsFn()),e.waitForIdle=()=>(this.assertActive(),this.waitForIdleFn()),e.newSession=s=>(this.assertActive(),this.newSessionHandler(s)),e.fork=(s,t)=>(this.assertActive(),this.forkHandler(s,t)),e.navigateTree=(s,t)=>(this.assertActive(),this.navigateTreeHandler(s,t)),e.switchSession=(s,t)=>(this.assertActive(),this.switchSessionHandler(s,t)),e.reload=()=>(this.assertActive(),this.reloadHandler()),e}async emitBoundary(e,s){const t=this.createContext();let i=[],n=!1,o=await s(i),r=!0;for(const{ext:c,handlers:l}of g(this.extensions,e.type))for(const h of l){const f={...e,entries:i,continue:n,context:o};try{const d=await h(f,t);d?.entries!==void 0&&(i=d.entries),d?.continue!==void 0&&(n=d.continue)}catch(d){this.emitError({extensionPath:c.path,event:e.type,error:d instanceof Error?d.message:String(d),stack:d instanceof Error?d.stack:void 0})}try{o=await s(i),r=!0}catch(d){r=!1,this.emitError({extensionPath:c.path,event:e.type,error:`Invalid boundary entries: ${d instanceof Error?d.message:String(d)}`,stack:d instanceof Error?d.stack:void 0})}}return r?{entries:i,continue:n,context:o,valid:!0}:{entries:[],continue:!1,context:o,valid:!1}}isSessionBeforeEvent(e){return e.type==="session_before_switch"||e.type==="session_before_fork"||e.type==="session_before_compact"||e.type==="session_before_tree"}async emit(e){const s=this.createContext();let t;for(const{ext:i,handlers:n}of g(this.extensions,e.type))for(const o of n)try{const r=await o(e,s);if(this.isSessionBeforeEvent(e)&&r&&(t=r,t.cancel))return t}catch(r){const c=r instanceof Error?r.message:String(r),l=r instanceof Error?r.stack:void 0;this.emitError({extensionPath:i.path,event:e.type,error:c,stack:l})}return t}async emitCacheWarmingDecision(e){const s=this.createContext();let t=e.action;for(const{ext:i,handlers:n}of g(this.extensions,e.type))for(const o of n)try{const r=await o(e,s);r?.action!==void 0&&(t=r.action)}catch(r){this.emitError({extensionPath:i.path,event:e.type,error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0})}return t}async emitMessageEnd(e){const s=this.createContext();let t=e.message,i=!1;for(const{ext:n,handlers:o}of g(this.extensions,"message_end"))for(const r of o)try{const c={...e,message:t},l=await r(c,s);if(!l?.message)continue;if(l.message.role!==t.role){this.emitError({extensionPath:n.path,event:"message_end",error:"message_end handlers must return a message with the same role"});continue}t=l.message,i=!0}catch(c){const l=c instanceof Error?c.message:String(c),h=c instanceof Error?c.stack:void 0;this.emitError({extensionPath:n.path,event:"message_end",error:l,stack:h})}return i?t:void 0}async emitToolResult(e){const s=this.createContext(),t={...e};let i=!1;for(const{ext:n,handlers:o}of g(this.extensions,"tool_result"))for(const r of o)try{const c=await r(t,s);if(!c)continue;c.content!==void 0&&(t.content=c.content,c.structuredContent===void 0&&delete t.structuredContent,i=!0),c.details!==void 0&&(t.details=c.details,i=!0),c.structuredContent!==void 0&&(t.structuredContent=c.structuredContent,i=!0),c.isError!==void 0&&(t.isError=c.isError,i=!0),c.usage!==void 0&&(t.usage=c.usage,i=!0)}catch(c){const l=c instanceof Error?c.message:String(c),h=c instanceof Error?c.stack:void 0;this.emitError({extensionPath:n.path,event:"tool_result",error:l,stack:h})}if(i)return{content:t.content,details:t.details,structuredContent:t.structuredContent,isError:t.isError,usage:t.usage}}async emitToolCall(e){const s=this.createContext();let t;for(const{handlers:i}of g(this.extensions,"tool_call"))for(const n of i){const o=await n(e,s);if(o&&(t=o,t.block))return t}return t}async emitUserBash(e){const s=this.createContext();for(const{ext:t,handlers:i}of g(this.extensions,"user_bash"))for(const n of i)try{const o=await n(e,s);if(o===void 0)continue;if(!k(o))throw new Error("Invalid user_bash handler result: return undefined for local execution or exactly one valid { operations } or { result } object");return o}catch(o){const r=o instanceof Error?o.message:String(o),c=o instanceof Error?o.stack:void 0;throw this.emitError({extensionPath:t.path,event:"user_bash",error:r,stack:c}),o}}async emitContext(e){const s=this.createContext();let t=structuredClone(e);for(const{ext:i,handlers:n}of g(this.extensions,"context"))for(const o of n)try{const r=t.filter(d=>d.role!=="system"),c=r.slice(),f=(await o({type:"context",messages:r},s))?.messages??(y(r,c)?void 0:r);if(!f)continue;t=M(t,c,f)}catch(r){const c=r instanceof Error?r.message:String(r),l=r instanceof Error?r.stack:void 0;this.emitError({extensionPath:i.path,event:"context",error:c,stack:l})}for(const{ext:i,handlers:n}of g(this.extensions,"context_with_system"))for(const o of n)try{const r=t[0]?.role==="system";t=(await o({type:"context_with_system",messages:t},s))?.messages??t,r&&t[0]?.role!=="system"&&this.emitError({extensionPath:i.path,event:"context_with_system",error:"Handler removed the leading system message; the request has no prompt or initial tool declarations. Keep it at index 0 or replace a dropped prefix with getCurrentSystemMessage()."})}catch(r){const c=r instanceof Error?r.message:String(r),l=r instanceof Error?r.stack:void 0;this.emitError({extensionPath:i.path,event:"context_with_system",error:c,stack:l})}return t}async emitBeforeProviderRequest(e){const s=this.createContext();let t=e;for(const{ext:i,handlers:n}of g(this.extensions,"before_provider_request"))for(const o of n)try{const c=await o({type:"before_provider_request",payload:t},s);c!==void 0&&(t=c)}catch(r){const c=r instanceof Error?r.message:String(r),l=r instanceof Error?r.stack:void 0;this.emitError({extensionPath:i.path,event:"before_provider_request",error:c,stack:l})}return t}async emitBeforeProviderHeaders(e){const s=this.createContext();for(const{ext:t,handlers:i}of g(this.extensions,"before_provider_headers"))for(const n of i)try{await n({type:"before_provider_headers",headers:e},s)}catch(o){const r=o instanceof Error?o.message:String(o),c=o instanceof Error?o.stack:void 0;this.emitError({extensionPath:t.path,event:"before_provider_headers",error:r,stack:c})}return e}async emitBeforeAgentStart(e,s){const t=p(s),i=a(()=>E(t),"renderCurrentSystemPrompt"),n=Object.defineProperties({},Object.getOwnPropertyDescriptors(this.createContext()));n.getSystemPrompt=()=>(this.assertActive(),i());const o=[];for(const{ext:r,handlers:c}of g(this.extensions,"before_agent_start"))for(const l of c)try{const h={...e,type:"before_agent_start",get systemPrompt(){return i()},systemPromptOptions:t},f=await l(h,n);if(f){const d=f;d.message&&o.push(d.message),d.systemPrompt!==void 0&&(t.forceSystemPrompt=d.systemPrompt)}}catch(h){const f=h instanceof Error?h.message:String(h),d=h instanceof Error?h.stack:void 0;this.emitError({extensionPath:r.path,event:"before_agent_start",error:f,stack:d})}return{messages:o,systemPromptOptions:t}}async emitResourcesDiscover(e,s){const t=this.createContext(),i=[],n=[],o=[];for(const{ext:r,handlers:c}of g(this.extensions,"resources_discover"))for(const l of c)try{const d=await l({type:"resources_discover",cwd:e,reason:s},t);d?.skillPaths?.length&&i.push(...d.skillPaths.map(m=>({path:m,extensionPath:r.path}))),d?.promptPaths?.length&&n.push(...d.promptPaths.map(m=>({path:m,extensionPath:r.path}))),d?.themePaths?.length&&o.push(...d.themePaths.map(m=>({path:m,extensionPath:r.path})))}catch(h){const f=h instanceof Error?h.message:String(h),d=h instanceof Error?h.stack:void 0;this.emitError({extensionPath:r.path,event:"resources_discover",error:f,stack:d})}return{skillPaths:i,promptPaths:n,themePaths:o}}async emitInput(e,s,t,i){const n=this.createContext();let o=e,r=s;for(const{ext:c,handlers:l}of g(this.extensions,"input"))for(const h of l)try{const d=await h({type:"input",text:o,images:r,source:t,streamingBehavior:i},n);if(d?.action==="handled")return d;d?.action==="transform"&&(o=d.text,r=d.images??r)}catch(f){this.emitError({extensionPath:c.path,event:"input",error:f instanceof Error?f.message:String(f),stack:f instanceof Error?f.stack:void 0})}return o!==e||r!==s?{action:"transform",text:o,images:r}:{action:"continue"}}}export{U as ExtensionRunner,I as emitProjectTrustEvent,R as emitSessionShutdownEvent};
1
+ var v=Object.defineProperty;var a=(u,e)=>v(u,"name",{value:e,configurable:!0});import{getCurrentSystemMessage as P}from"@earendil-works/pi-ai";import{theme as w}from"../../modes/interactive/theme/theme.js";import{buildSystemPrompt as E,normalizeBuildSystemPromptOptions as p}from"../system-prompt.js";const S=["app.interrupt","app.clear","app.exit","app.suspend","app.thinking.cycle","app.model.cycleForward","app.model.cycleBackward","app.model.select","app.tools.expand","app.thinking.toggle","app.editor.external","app.message.copy","app.message.followUp","tui.input.submit","tui.select.confirm","tui.select.cancel","tui.input.copy","tui.editor.deleteToLineEnd"],C=a(u=>{const e={};for(const[s,t]of Object.entries(u)){if(t===void 0)continue;const i=Array.isArray(t)?t:[t],n=S.includes(s);for(const o of i){const r=o.toLowerCase();e[r]?.restrictOverride&&!n||(e[r]={keybinding:s,restrictOverride:n})}}return e},"buildBuiltinKeybindings");function k(u){if(typeof u!="object"||u===null)return!1;const e=u,s=e.operations!==void 0,t=e.result!==void 0;if(s===t)return!1;if(s){const o=e.operations;return typeof o!="object"||o===null?!1:typeof o.exec=="function"}const i=e.result;if(typeof i!="object"||i===null)return!1;const n=i;return typeof n.output=="string"&&"exitCode"in n&&(n.exitCode===void 0||typeof n.exitCode=="number")&&typeof n.cancelled=="boolean"&&typeof n.truncated=="boolean"&&(n.fullOutputPath===void 0||typeof n.fullOutputPath=="string")}a(k,"isUserBashEventResult");async function R(u,e){return u.hasHandlers("session_shutdown")?(await u.emit(e),!0):!1}a(R,"emitSessionShutdownEvent");function g(u,e){return u.map(s=>({ext:s,handlers:s.handlers.get(e)?.slice()??[]}))}a(g,"snapshotEventHandlers");function y(u,e){return u.length===e.length&&u.every((s,t)=>s===e[t])}a(y,"sameMessages");function M(u,e,s){if(y(s,e))return u;const t=P(u);return t?[t,...s]:s}a(M,"restoreSystemMessages");async function I(u,e,s){const t=[];for(const{ext:i,handlers:n}of g(u.extensions,"project_trust"))for(const o of n)try{const r=await o(e,s);if(r.trusted==="undecided")continue;return{result:r,errors:t}}catch(r){t.push({extensionPath:i.path,event:e.type,error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0})}return{errors:t}}a(I,"emitProjectTrustEvent");const x={select:a(async()=>{},"select"),confirm:a(async()=>!1,"confirm"),input:a(async()=>{},"input"),notify:a(()=>{},"notify"),setPanel:a(()=>{},"setPanel"),requestInput:a(async()=>{},"requestInput"),requestChoice:a(async()=>{},"requestChoice"),onTerminalInput:a(()=>()=>{},"onTerminalInput"),setStatus:a(()=>{},"setStatus"),setWorkingMessage:a(()=>{},"setWorkingMessage"),setWorkingVisible:a(()=>{},"setWorkingVisible"),setWorkingIndicator:a(()=>{},"setWorkingIndicator"),setHiddenThinkingLabel:a(()=>{},"setHiddenThinkingLabel"),setWidget:a(()=>{},"setWidget"),setFooter:a(()=>{},"setFooter"),setHeader:a(()=>{},"setHeader"),setTitle:a(()=>{},"setTitle"),custom:a(async()=>{},"custom"),pasteToEditor:a(()=>{},"pasteToEditor"),setEditorText:a(()=>{},"setEditorText"),getEditorText:a(()=>"","getEditorText"),editor:a(async()=>{},"editor"),addAutocompleteProvider:a(()=>{},"addAutocompleteProvider"),setEditorComponent:a(()=>{},"setEditorComponent"),getEditorComponent:a(()=>{},"getEditorComponent"),get theme(){return w},getAllThemes:a(()=>[],"getAllThemes"),getTheme:a(()=>{},"getTheme"),setTheme:a(u=>({success:!1,error:"UI not available"}),"setTheme"),getToolsExpanded:a(()=>!1,"getToolsExpanded"),setToolsExpanded:a(()=>{},"setToolsExpanded")};class U{static{a(this,"ExtensionRunner")}extensions;runtime;uiContext;mode="print";cwd;sessionManager;modelRegistry;errorListeners=new Set;getModel=a(()=>{},"getModel");getScopedModels=a(()=>[],"getScopedModels");isIdleFn=a(()=>!0,"isIdleFn");isProjectTrustedFn=a(()=>!0,"isProjectTrustedFn");getSignalFn=a(()=>{},"getSignalFn");waitForIdleFn=a(async()=>{},"waitForIdleFn");abortFn=a(()=>{},"abortFn");hasPendingMessagesFn=a(()=>!1,"hasPendingMessagesFn");getContextUsageFn=a(()=>{},"getContextUsageFn");compactFn=a(()=>{},"compactFn");getSystemPromptFn=a(()=>"","getSystemPromptFn");getSystemPromptOptionsFn=a(()=>p({cwd:this.cwd}),"getSystemPromptOptionsFn");executeToolFn;getCallableToolsFn=a(()=>[],"getCallableToolsFn");reportedMcpServers=new Set;newSessionHandler=a(async()=>({cancelled:!1}),"newSessionHandler");forkHandler=a(async()=>({cancelled:!1}),"forkHandler");navigateTreeHandler=a(async()=>({cancelled:!1}),"navigateTreeHandler");switchSessionHandler=a(async()=>({cancelled:!1}),"switchSessionHandler");reloadHandler=a(async()=>{},"reloadHandler");shutdownHandler=a(()=>{},"shutdownHandler");shortcutDiagnostics=[];commandDiagnostics=[];staleMessage;uiPromptDepth=0;activeUIPrompt;constructor(e,s,t,i,n){this.extensions=e,this.runtime=s,this.uiContext=x,this.cwd=t,this.sessionManager=i,this.modelRegistry=n}bindCore(e,s,t){this.runtime.sendMessage=e.sendMessage,this.runtime.sendUserMessage=e.sendUserMessage,this.runtime.appendEntry=e.appendEntry,this.runtime.emitHostEvent=e.emitHostEvent??(()=>{}),this.runtime.appendUsage=e.appendUsage??(()=>{}),this.runtime.setSessionName=e.setSessionName,this.runtime.getSessionName=e.getSessionName,this.runtime.setLabel=e.setLabel,this.runtime.getActiveTools=e.getActiveTools,this.runtime.getAllTools=e.getAllTools,this.runtime.getSettings=e.getSettings,this.runtime.setActiveTools=e.setActiveTools,this.runtime.isToolAllowed=e.isToolAllowed,this.runtime.getToolAllowlist=e.getToolAllowlist,this.runtime.getToolDenylist=e.getToolDenylist,this.runtime.refreshTools=e.refreshTools,this.runtime.getCommands=e.getCommands,this.runtime.setModel=e.setModel,this.runtime.getThinkingLevel=e.getThinkingLevel,this.runtime.setThinkingLevel=e.setThinkingLevel,this.runtime.createContext=()=>this.createContext(),this.getModel=s.getModel,this.getScopedModels=s.getScopedModels,this.isIdleFn=s.isIdle,this.isProjectTrustedFn=s.isProjectTrusted,this.getSignalFn=s.getSignal,this.abortFn=s.abort,this.hasPendingMessagesFn=s.hasPendingMessages,this.shutdownHandler=s.shutdown,this.getContextUsageFn=s.getContextUsage,this.compactFn=s.compact,this.getSystemPromptFn=s.getSystemPrompt,this.getSystemPromptOptionsFn=s.getSystemPromptOptions??(()=>p({cwd:this.cwd})),this.executeToolFn=s.executeTool,this.getCallableToolsFn=s.getCallableTools??(()=>[]),this.runtime.mcpServers.setChangeListener(()=>{this.emit({type:"mcp_servers_change",servers:this.runtime.mcpServers.list()}),this.reportUnhandledMcpServers()});for(const{name:n,config:o,extensionPath:r}of this.runtime.pendingProviderRegistrations)try{t?.registerProvider?t.registerProvider(n,o):this.modelRegistry.registerProvider(n,o)}catch(c){this.emitError({extensionPath:r,event:"register_provider",error:c instanceof Error?c.message:String(c),stack:c instanceof Error?c.stack:void 0})}this.runtime.pendingProviderRegistrations=[];for(const{provider:n,extensionPath:o}of this.runtime.pendingNativeProviderRegistrations)try{t?.registerNativeProvider?t.registerNativeProvider(n):this.modelRegistry.registerProvider(n)}catch(r){this.emitError({extensionPath:o,event:"register_provider",error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0})}this.runtime.pendingNativeProviderRegistrations=[];const i=a(n=>{t?.registerVirtualModel?t.registerVirtualModel(n):this.modelRegistry.registerVirtualModel(n)},"registerVirtualModel");for(const{definition:n,extensionPath:o}of this.runtime.pendingVirtualModelRegistrations)try{i(n)}catch(r){this.emitError({extensionPath:o,event:"register_virtual_model",error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0})}this.runtime.pendingVirtualModelRegistrations=[],this.runtime.registerProvider=(n,o)=>{if(t?.registerProvider){t.registerProvider(n,o);return}this.modelRegistry.registerProvider(n,o)},this.runtime.registerNativeProvider=n=>{if(t?.registerNativeProvider){t.registerNativeProvider(n);return}this.modelRegistry.registerProvider(n)},this.runtime.unregisterProvider=n=>{if(t?.unregisterProvider){t.unregisterProvider(n);return}this.modelRegistry.unregisterProvider(n)},this.runtime.registerVirtualModel=i,this.runtime.unregisterVirtualModel=(n,o)=>{t?.unregisterVirtualModel?t.unregisterVirtualModel(n,o):this.modelRegistry.unregisterVirtualModel(n,o)}}bindCommandContext(e){if(e){this.waitForIdleFn=e.waitForIdle,this.newSessionHandler=e.newSession,this.forkHandler=e.fork,this.navigateTreeHandler=e.navigateTree,this.switchSessionHandler=e.switchSession,this.reloadHandler=e.reload;return}this.waitForIdleFn=async()=>{},this.newSessionHandler=async()=>({cancelled:!1}),this.forkHandler=async()=>({cancelled:!1}),this.navigateTreeHandler=async()=>({cancelled:!1}),this.switchSessionHandler=async()=>({cancelled:!1}),this.reloadHandler=async()=>{}}setUIContext(e,s="print"){this.uiContext=e?this.wrapUIPromptContext(e):x,this.mode=s}wrapUIPromptContext(e){return{...e,select:a((s,t,i)=>this.withUIPrompt("select",s,()=>e.select(s,t,i)),"select"),confirm:a((s,t,i)=>this.withUIPrompt("confirm",s,()=>e.confirm(s,t,i)),"confirm"),input:a((s,t,i)=>this.withUIPrompt("input",s,()=>e.input(s,t,i)),"input"),editor:a((s,t)=>this.withUIPrompt("editor",s,()=>e.editor(s,t)),"editor"),custom:a((s,t)=>this.withUIPrompt("custom",void 0,()=>e.custom(s,t)),"custom")}}withUIPrompt(e,s,t){this.uiPromptDepth++===0&&(this.activeUIPrompt={kind:e,title:s},this.emitUIPromptEvent({type:"ui_prompt_start",reason:"ui_prompt",kind:e,...s?{title:s}:{}}));const n=a(()=>{if(--this.uiPromptDepth>0)return;this.uiPromptDepth=0;const o=this.activeUIPrompt??{kind:e,title:s};this.activeUIPrompt=void 0,this.emitUIPromptEvent({type:"ui_prompt_end",reason:"ui_prompt",kind:o.kind,...o.title?{title:o.title}:{}})},"finish");try{return t().finally(n)}catch(o){throw n(),o}}emitUIPromptEvent(e){queueMicrotask(()=>{this.emit(e)})}getUIContext(){return this.uiContext}hasUI(){return this.uiContext!==x}getExtensionPaths(){return this.extensions.map(e=>e.path)}getAllRegisteredTools(){const e=new Map;for(const s of this.extensions)for(const t of s.tools.values())e.has(t.definition.name)||e.set(t.definition.name,t);return Array.from(e.values())}getToolDefinition(e){for(const s of this.extensions){const t=s.tools.get(e);if(t)return t.definition}}getFlags(){const e=new Map;for(const s of this.extensions)for(const[t,i]of s.flags)e.has(t)||e.set(t,i);return e}setFlagValue(e,s){this.runtime.flagValues.set(e,s)}getFlagValues(){return new Map(this.runtime.flagValues)}getShortcuts(e){this.shortcutDiagnostics=[];const s=C(e),t=new Map,i=a((n,o)=>{this.shortcutDiagnostics.push({type:"warning",message:n,path:o}),this.hasUI()||console.warn(n)},"addDiagnostic");for(const n of this.extensions)for(const[o,r]of n.shortcuts){const c=o.toLowerCase(),l=s[c];if(l?.restrictOverride===!0){i(`Extension shortcut '${o}' from ${r.extensionPath} conflicts with built-in shortcut. Skipping.`,r.extensionPath);continue}l?.restrictOverride===!1&&i(`Extension shortcut conflict: '${o}' is built-in shortcut for ${l.keybinding} and ${r.extensionPath}. Using ${r.extensionPath}.`,r.extensionPath);const h=t.get(c);h&&i(`Extension shortcut conflict: '${o}' registered by both ${h.extensionPath} and ${r.extensionPath}. Using ${r.extensionPath}.`,r.extensionPath),t.set(c,r)}return t}getShortcutDiagnostics(){return this.shortcutDiagnostics}invalidate(e="This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload()."){this.staleMessage||(this.staleMessage=e,this.runtime.invalidate(e))}assertActive(){if(this.staleMessage)throw new Error(this.staleMessage)}onError(e){return this.errorListeners.add(e),()=>this.errorListeners.delete(e)}emitError(e){for(const s of this.errorListeners)s(e)}reportUnhandledMcpServers(){if(!this.hasHandlers("mcp_servers_change"))for(const e of this.runtime.mcpServers.list())this.reportedMcpServers.has(e.name)||(this.reportedMcpServers.add(e.name),this.emitError({extensionPath:e.extensionPath,event:"register_mcp_server",error:`MCP server "${e.name}" is registered, but no loaded extension connects MCP servers; another extension may have replaced the built-in MCP support`}))}hasHandlers(e){for(const s of this.extensions){const t=s.handlers.get(e);if(t&&t.length>0)return!0}return!1}getMessageRenderer(e){for(const s of this.extensions){const t=s.messageRenderers.get(e);if(t)return t}}getMarkdownTransformers(){return this.extensions.flatMap(e=>e.markdownTransformer?[e.markdownTransformer]:[])}getModelPickerEntries(){return this.extensions.flatMap(e=>[...e.modelPickerEntries?.values()??[]])}resolveToolRenderers(e,s){const t=this.extensions.flatMap(n=>n.toolRenderers??[]),i=a(n=>n<t.length?t[n](e,()=>i(n+1)):s(),"resolve");return i(0)}getEntryRenderer(e){for(const s of this.extensions){const t=s.entryRenderers?.get(e);if(t)return t}}resolveRegisteredCommands(){const e=[],s=new Map;for(const n of this.extensions)for(const o of n.commands.values())e.push(o),s.set(o.name,(s.get(o.name)??0)+1);const t=new Map,i=new Set;return e.map(n=>{const o=(t.get(n.name)??0)+1;t.set(n.name,o);let r=(s.get(n.name)??0)>1?`${n.name}:${o}`:n.name;if(i.has(r)){let c=o;do c++,r=`${n.name}:${c}`;while(i.has(r))}return i.add(r),{...n,invocationName:r}})}getModelRegistry(){return this.modelRegistry}getRegisteredCommands(){return this.commandDiagnostics=[],this.resolveRegisteredCommands()}getCommandDiagnostics(){return this.commandDiagnostics}getCommand(e){return this.resolveRegisteredCommands().find(s=>s.invocationName===e)}shutdown(){this.shutdownHandler()}getActiveTools(){return this.assertActive(),this.runtime.getActiveTools()}createContext(){const e=this,s=this.getModel,t=this.getScopedModels;return{get ui(){return e.assertActive(),e.uiContext},get mode(){return e.assertActive(),e.mode},get hasUI(){return e.assertActive(),e.hasUI()},get cwd(){return e.assertActive(),e.cwd},get sessionManager(){return e.assertActive(),e.sessionManager},get modelRegistry(){return e.assertActive(),e.modelRegistry},get model(){return e.assertActive(),s()},get scopedModels(){return e.assertActive(),t()},get thinkingLevel(){return e.assertActive(),e.runtime.getThinkingLevel()},isIdle:a(()=>(e.assertActive(),e.isIdleFn()),"isIdle"),isProjectTrusted:a(()=>(e.assertActive(),e.isProjectTrustedFn()),"isProjectTrusted"),get signal(){return e.assertActive(),e.getSignalFn()},abort:a(()=>{e.assertActive(),e.abortFn()},"abort"),hasPendingMessages:a(()=>(e.assertActive(),e.hasPendingMessagesFn()),"hasPendingMessages"),shutdown:a(()=>{e.assertActive(),e.shutdownHandler()},"shutdown"),getContextUsage:a(()=>(e.assertActive(),e.getContextUsageFn()),"getContextUsage"),compact:a(i=>{e.assertActive(),e.compactFn(i)},"compact"),getSystemPrompt:a(()=>(e.assertActive(),e.getSystemPromptFn()),"getSystemPrompt")}}createToolContext(e,s){const t=this;return Object.defineProperties(this.createContext(),{tools:{get(){return t.assertActive(),t.getCallableToolsFn()}},executeTool:{value:a(async(i,n,o={})=>(t.assertActive(),t.executeToolFn?t.executeToolFn(e,i,n,{...o,signal:o.signal??s}):{toolCall:{type:"toolCall",id:`${e}/0`,name:i,arguments:{}},result:{content:[{type:"text",text:"Nested tool calls are not available in this context"}],details:{}},isError:!0}),"value")}})}createCommandContext(){const e=Object.defineProperties({},Object.getOwnPropertyDescriptors(this.createContext()));return e.getSystemPromptOptions=()=>(this.assertActive(),this.getSystemPromptOptionsFn()),e.waitForIdle=()=>(this.assertActive(),this.waitForIdleFn()),e.newSession=s=>(this.assertActive(),this.newSessionHandler(s)),e.fork=(s,t)=>(this.assertActive(),this.forkHandler(s,t)),e.navigateTree=(s,t)=>(this.assertActive(),this.navigateTreeHandler(s,t)),e.switchSession=(s,t)=>(this.assertActive(),this.switchSessionHandler(s,t)),e.reload=()=>(this.assertActive(),this.reloadHandler()),e}async emitBoundary(e,s){const t=this.createContext();let i=[],n=!1,o=await s(i),r=!0;for(const{ext:c,handlers:l}of g(this.extensions,e.type))for(const h of l){const f={...e,entries:i,continue:n,context:o};try{const d=await h(f,t);d?.entries!==void 0&&(i=d.entries),d?.continue!==void 0&&(n=d.continue)}catch(d){this.emitError({extensionPath:c.path,event:e.type,error:d instanceof Error?d.message:String(d),stack:d instanceof Error?d.stack:void 0})}try{o=await s(i),r=!0}catch(d){r=!1,this.emitError({extensionPath:c.path,event:e.type,error:`Invalid boundary entries: ${d instanceof Error?d.message:String(d)}`,stack:d instanceof Error?d.stack:void 0})}}return r?{entries:i,continue:n,context:o,valid:!0}:{entries:[],continue:!1,context:o,valid:!1}}isSessionBeforeEvent(e){return e.type==="session_before_switch"||e.type==="session_before_fork"||e.type==="session_before_compact"||e.type==="session_before_tree"}async emit(e){const s=this.createContext();let t;for(const{ext:i,handlers:n}of g(this.extensions,e.type))for(const o of n)try{const r=await o(e,s);if(this.isSessionBeforeEvent(e)&&r&&(t=r,t.cancel))return t}catch(r){const c=r instanceof Error?r.message:String(r),l=r instanceof Error?r.stack:void 0;this.emitError({extensionPath:i.path,event:e.type,error:c,stack:l})}return t}async emitCacheWarmingDecision(e){const s=this.createContext();let t=e.action;for(const{ext:i,handlers:n}of g(this.extensions,e.type))for(const o of n)try{const r=await o(e,s);r?.action!==void 0&&(t=r.action)}catch(r){this.emitError({extensionPath:i.path,event:e.type,error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0})}return t}async emitMessageEnd(e){const s=this.createContext();let t=e.message,i=!1;for(const{ext:n,handlers:o}of g(this.extensions,"message_end"))for(const r of o)try{const c={...e,message:t},l=await r(c,s);if(!l?.message)continue;if(l.message.role!==t.role){this.emitError({extensionPath:n.path,event:"message_end",error:"message_end handlers must return a message with the same role"});continue}t=l.message,i=!0}catch(c){const l=c instanceof Error?c.message:String(c),h=c instanceof Error?c.stack:void 0;this.emitError({extensionPath:n.path,event:"message_end",error:l,stack:h})}return i?t:void 0}async emitToolResult(e){const s=this.createContext(),t={...e};let i=!1;for(const{ext:n,handlers:o}of g(this.extensions,"tool_result"))for(const r of o)try{const c=await r(t,s);if(!c)continue;c.content!==void 0&&(t.content=c.content,c.structuredContent===void 0&&delete t.structuredContent,i=!0),c.details!==void 0&&(t.details=c.details,i=!0),c.structuredContent!==void 0&&(t.structuredContent=c.structuredContent,i=!0),c.isError!==void 0&&(t.isError=c.isError,i=!0),c.usage!==void 0&&(t.usage=c.usage,i=!0)}catch(c){const l=c instanceof Error?c.message:String(c),h=c instanceof Error?c.stack:void 0;this.emitError({extensionPath:n.path,event:"tool_result",error:l,stack:h})}if(i)return{content:t.content,details:t.details,structuredContent:t.structuredContent,isError:t.isError,usage:t.usage}}async emitToolCall(e){const s=this.createContext();let t;for(const{handlers:i}of g(this.extensions,"tool_call"))for(const n of i){const o=await n(e,s);if(o&&(t=o,t.block))return t}return t}async emitUserBash(e){const s=this.createContext();for(const{ext:t,handlers:i}of g(this.extensions,"user_bash"))for(const n of i)try{const o=await n(e,s);if(o===void 0)continue;if(!k(o))throw new Error("Invalid user_bash handler result: return undefined for local execution or exactly one valid { operations } or { result } object");return o}catch(o){const r=o instanceof Error?o.message:String(o),c=o instanceof Error?o.stack:void 0;throw this.emitError({extensionPath:t.path,event:"user_bash",error:r,stack:c}),o}}async emitContext(e){const s=this.createContext();let t=structuredClone(e);for(const{ext:i,handlers:n}of g(this.extensions,"context"))for(const o of n)try{const r=t.filter(d=>d.role!=="system"),c=r.slice(),f=(await o({type:"context",messages:r},s))?.messages??(y(r,c)?void 0:r);if(!f)continue;t=M(t,c,f)}catch(r){const c=r instanceof Error?r.message:String(r),l=r instanceof Error?r.stack:void 0;this.emitError({extensionPath:i.path,event:"context",error:c,stack:l})}for(const{ext:i,handlers:n}of g(this.extensions,"context_with_system"))for(const o of n)try{const r=t[0]?.role==="system";t=(await o({type:"context_with_system",messages:t},s))?.messages??t,r&&t[0]?.role!=="system"&&this.emitError({extensionPath:i.path,event:"context_with_system",error:"Handler removed the leading system message; the request has no prompt or initial tool declarations. Keep it at index 0 or replace a dropped prefix with getCurrentSystemMessage()."})}catch(r){const c=r instanceof Error?r.message:String(r),l=r instanceof Error?r.stack:void 0;this.emitError({extensionPath:i.path,event:"context_with_system",error:c,stack:l})}return t}async emitBeforeProviderRequest(e){const s=this.createContext();let t=e;for(const{ext:i,handlers:n}of g(this.extensions,"before_provider_request"))for(const o of n)try{const c=await o({type:"before_provider_request",payload:t},s);c!==void 0&&(t=c)}catch(r){const c=r instanceof Error?r.message:String(r),l=r instanceof Error?r.stack:void 0;this.emitError({extensionPath:i.path,event:"before_provider_request",error:c,stack:l})}return t}async emitBeforeProviderHeaders(e){const s=this.createContext();for(const{ext:t,handlers:i}of g(this.extensions,"before_provider_headers"))for(const n of i)try{await n({type:"before_provider_headers",headers:e},s)}catch(o){const r=o instanceof Error?o.message:String(o),c=o instanceof Error?o.stack:void 0;this.emitError({extensionPath:t.path,event:"before_provider_headers",error:r,stack:c})}return e}async emitBeforeAgentStart(e,s){const t=p(s),i=a(()=>E(t),"renderCurrentSystemPrompt"),n=Object.defineProperties({},Object.getOwnPropertyDescriptors(this.createContext()));n.getSystemPrompt=()=>(this.assertActive(),i());const o=[];for(const{ext:r,handlers:c}of g(this.extensions,"before_agent_start"))for(const l of c)try{const h={...e,type:"before_agent_start",get systemPrompt(){return i()},systemPromptOptions:t},f=await l(h,n);if(f){const d=f;d.message&&o.push(d.message),d.systemPrompt!==void 0&&(t.forceSystemPrompt=d.systemPrompt)}}catch(h){const f=h instanceof Error?h.message:String(h),d=h instanceof Error?h.stack:void 0;this.emitError({extensionPath:r.path,event:"before_agent_start",error:f,stack:d})}return{messages:o,systemPromptOptions:t}}async emitResourcesDiscover(e,s){const t=this.createContext(),i=[],n=[],o=[];for(const{ext:r,handlers:c}of g(this.extensions,"resources_discover"))for(const l of c)try{const d=await l({type:"resources_discover",cwd:e,reason:s},t);d?.skillPaths?.length&&i.push(...d.skillPaths.map(m=>({path:m,extensionPath:r.path}))),d?.promptPaths?.length&&n.push(...d.promptPaths.map(m=>({path:m,extensionPath:r.path}))),d?.themePaths?.length&&o.push(...d.themePaths.map(m=>({path:m,extensionPath:r.path})))}catch(h){const f=h instanceof Error?h.message:String(h),d=h instanceof Error?h.stack:void 0;this.emitError({extensionPath:r.path,event:"resources_discover",error:f,stack:d})}return{skillPaths:i,promptPaths:n,themePaths:o}}async emitInput(e,s,t,i){const n=this.createContext();let o=e,r=s;for(const{ext:c,handlers:l}of g(this.extensions,"input"))for(const h of l)try{const d=await h({type:"input",text:o,images:r,source:t,streamingBehavior:i},n);if(d?.action==="handled")return d;d?.action==="transform"&&(o=d.text,r=d.images??r)}catch(f){this.emitError({extensionPath:c.path,event:"input",error:f instanceof Error?f.message:String(f),stack:f instanceof Error?f.stack:void 0})}return o!==e||r!==s?{action:"transform",text:o,images:r}:{action:"continue"}}}export{U as ExtensionRunner,I as emitProjectTrustEvent,R as emitSessionShutdownEvent};
@@ -162,6 +162,7 @@ export interface ExtensionContext {
162
162
  export interface ExecuteToolOptions {
163
163
  signal?: AbortSignal;
164
164
  onUpdate?: AgentToolUpdateCallback;
165
+ detached?: boolean;
165
166
  }
166
167
  export interface ExtensionToolContext extends ExtensionContext {
167
168
  readonly tools: readonly AgentTool[];
@@ -853,12 +854,18 @@ export interface ExtensionAPI {
853
854
  sendMessage<T = unknown>(message: Pick<CustomMessage<T>, "customType" | "content" | "display" | "details">, options?: {
854
855
  triggerTurn?: boolean;
855
856
  deliverAs?: "steer" | "followUp" | "nextTurn";
856
- }): Promise<void>;
857
+ }): void;
857
858
  sendUserMessage(content: string | (TextContent | ImageContent)[], options?: {
858
859
  deliverAs?: "steer" | "followUp";
859
860
  expandPromptTemplates?: boolean;
860
861
  }): Promise<void>;
861
862
  appendEntry<T = unknown>(customType: string, data?: T): void;
863
+ appendUsage(usage: Usage, options: {
864
+ kind: string;
865
+ provider?: string;
866
+ model?: string;
867
+ note?: string;
868
+ }): void;
862
869
  emitHostEvent(name: string, data?: unknown): void;
863
870
  setSessionName(name: string): void;
864
871
  getSessionName(): string | undefined;
@@ -979,6 +986,12 @@ export type SendUserMessageHandler = (content: string | (TextContent | ImageCont
979
986
  }) => void;
980
987
  export type AppendEntryHandler = <T = unknown>(customType: string, data?: T) => void;
981
988
  export type EmitHostEventHandler = (name: string, data?: unknown) => void;
989
+ export type AppendUsageHandler = (usage: Usage, options: {
990
+ kind: string;
991
+ provider?: string;
992
+ model?: string;
993
+ note?: string;
994
+ }) => void;
982
995
  export type SetSessionNameHandler = (name: string) => void;
983
996
  export type GetSessionNameHandler = () => string | undefined;
984
997
  export type GetActiveToolsHandler = () => string[];
@@ -1031,6 +1044,7 @@ export interface ExtensionActions {
1031
1044
  sendUserMessage: SendUserMessageHandler;
1032
1045
  appendEntry: AppendEntryHandler;
1033
1046
  emitHostEvent?: EmitHostEventHandler;
1047
+ appendUsage?: AppendUsageHandler;
1034
1048
  setSessionName: SetSessionNameHandler;
1035
1049
  getSessionName: GetSessionNameHandler;
1036
1050
  setLabel: SetLabelHandler;
@@ -17,6 +17,7 @@ export { clearApiKeyCache } from "./provider-composer.ts";
17
17
  export declare class ModelRegistry {
18
18
  private readonly runtime;
19
19
  constructor(runtime: ModelRuntime);
20
+ getRuntime(): ModelRuntime;
20
21
  refresh(options?: ModelsRefreshOptions): Promise<ModelsRefreshResult>;
21
22
  getError(): string | undefined;
22
23
  getAll(): Model<Api>[];
@@ -1 +1 @@
1
- var u=Object.defineProperty;var n=(i,e)=>u(i,"name",{value:e,configurable:!0});import{clearApiKeyCache as d}from"./provider-composer.js";class a{static{n(this,"ModelRegistry")}runtime;constructor(e){this.runtime=e}refresh(e){return this.runtime.refresh(e)}getError(){return this.runtime.getError()}getAll(){return[...this.runtime.getModels()]}getAvailable(){return[...this.runtime.getAvailableSnapshot()]}find(e,r){return this.runtime.getModel(e,r)}findOfType(e,r,t){return this.runtime.getModelOfType(e,r,t)}hasConfiguredAuth(e){return this.runtime.hasConfiguredAuth(e.provider)}async getApiKeyAndHeaders(e){try{const r=await this.runtime.getAuth(e);if(!r){const t=this.runtime.getCompatibilityRequestConfig(e);return t.authHeader?{ok:!1,error:`No API key found for "${e.provider}"`}:{ok:!0,headers:t.headers}}return{ok:!0,apiKey:r.auth.apiKey,headers:r.auth.headers,...r.auth.baseUrl?{baseUrl:r.auth.baseUrl}:{},env:r.env}}catch(r){const t=r instanceof Error?r.cause:void 0,s=t instanceof Error?t.message:r instanceof Error?r.message:String(r);return{ok:!1,error:s==="authHeader requires a resolved API key"?`No API key found for "${e.provider}"`:s}}}getProviderAuthStatus(e){return this.runtime.getProviderAuthStatus(e)}getProvider(e){return this.runtime.getProvider(e)}stream(e,r,t){return this.runtime.stream(e,r,t)}streamSimple(e,r,t){return this.runtime.streamSimple(e,r,t)}complete(e,r,t){return this.runtime.complete(e,r,t)}getModelsOfType(e,r){return this.runtime.getModelsOfType(e,r)}getAvailableOfType(e,r,t){return this.runtime.getAvailableOfType(e,r,t)}getModelOfType(e,r,t){return this.runtime.getModelOfType(e,r,t)}classify(e,r,t){return this.runtime.classify(e,r,t)}generateImages(e,r,t){return this.runtime.generateImages(e,r,t)}getProviderDisplayName(e){return this.runtime.getProvider(e)?.name??e}getProviderAuth(e){return this.runtime.getAuth(e)}async getApiKeyForProvider(e){try{return(await this.runtime.getAuth(e))?.auth.apiKey}catch{return}}isUsingOAuth(e){return this.runtime.isUsingOAuth(e.provider)}registerProvider(e,r){if(typeof e=="string"){if(!r)throw new Error("Provider config is required when registering by name");this.runtime.registerProvider(e,r);return}this.runtime.registerNativeProvider(e)}unregisterProvider(e){this.runtime.unregisterProvider(e)}registerVirtualModel(e){this.runtime.registerVirtualModel(e)}unregisterVirtualModel(e,r){this.runtime.unregisterVirtualModel(e,r)}getRegisteredProviderConfig(e){return this.runtime.getRegisteredProviderConfig(e)}getRegisteredNativeProvider(e){return this.runtime.getRegisteredNativeProvider(e)}getRegisteredProviderIds(){return this.runtime.getRegisteredProviderIds()}}export{a as ModelRegistry,d as clearApiKeyCache};
1
+ var u=Object.defineProperty;var n=(i,e)=>u(i,"name",{value:e,configurable:!0});import{clearApiKeyCache as d}from"./provider-composer.js";class a{static{n(this,"ModelRegistry")}runtime;constructor(e){this.runtime=e}getRuntime(){return this.runtime}refresh(e){return this.runtime.refresh(e)}getError(){return this.runtime.getError()}getAll(){return[...this.runtime.getModels()]}getAvailable(){return[...this.runtime.getAvailableSnapshot()]}find(e,r){return this.runtime.getModel(e,r)}findOfType(e,r,t){return this.runtime.getModelOfType(e,r,t)}hasConfiguredAuth(e){return this.runtime.hasConfiguredAuth(e.provider)}async getApiKeyAndHeaders(e){try{const r=await this.runtime.getAuth(e);if(!r){const t=this.runtime.getCompatibilityRequestConfig(e);return t.authHeader?{ok:!1,error:`No API key found for "${e.provider}"`}:{ok:!0,headers:t.headers}}return{ok:!0,apiKey:r.auth.apiKey,headers:r.auth.headers,...r.auth.baseUrl?{baseUrl:r.auth.baseUrl}:{},env:r.env}}catch(r){const t=r instanceof Error?r.cause:void 0,s=t instanceof Error?t.message:r instanceof Error?r.message:String(r);return{ok:!1,error:s==="authHeader requires a resolved API key"?`No API key found for "${e.provider}"`:s}}}getProviderAuthStatus(e){return this.runtime.getProviderAuthStatus(e)}getProvider(e){return this.runtime.getProvider(e)}stream(e,r,t){return this.runtime.stream(e,r,t)}streamSimple(e,r,t){return this.runtime.streamSimple(e,r,t)}complete(e,r,t){return this.runtime.complete(e,r,t)}getModelsOfType(e,r){return this.runtime.getModelsOfType(e,r)}getAvailableOfType(e,r,t){return this.runtime.getAvailableOfType(e,r,t)}getModelOfType(e,r,t){return this.runtime.getModelOfType(e,r,t)}classify(e,r,t){return this.runtime.classify(e,r,t)}generateImages(e,r,t){return this.runtime.generateImages(e,r,t)}getProviderDisplayName(e){return this.runtime.getProvider(e)?.name??e}getProviderAuth(e){return this.runtime.getAuth(e)}async getApiKeyForProvider(e){try{return(await this.runtime.getAuth(e))?.auth.apiKey}catch{return}}isUsingOAuth(e){return this.runtime.isUsingOAuth(e.provider)}registerProvider(e,r){if(typeof e=="string"){if(!r)throw new Error("Provider config is required when registering by name");this.runtime.registerProvider(e,r);return}this.runtime.registerNativeProvider(e)}unregisterProvider(e){this.runtime.unregisterProvider(e)}registerVirtualModel(e){this.runtime.registerVirtualModel(e)}unregisterVirtualModel(e,r){this.runtime.unregisterVirtualModel(e,r)}getRegisteredProviderConfig(e){return this.runtime.getRegisteredProviderConfig(e)}getRegisteredNativeProvider(e){return this.runtime.getRegisteredNativeProvider(e)}getRegisteredProviderIds(){return this.runtime.getRegisteredProviderIds()}}export{a as ModelRegistry,d as clearApiKeyCache};
@@ -1,2 +1,2 @@
1
- var g=Object.defineProperty;var u=(l,e)=>g(l,"name",{value:e,configurable:!0});import{combineUsage as f}from"./usage-totals.js";const c={maxCalls:256,maxArgumentBytesPerCall:8*1024,maxArgumentBytesTotal:32*1024,maxErrorChars:500},x=new TextEncoder;class y{static{u(this,"NestedCallRecorder")}calls=[];startedAt=new Map;complete=!0;argumentBytes=0;usage;start(e){if(this.calls.length>=c.maxCalls){this.complete=!1;return}const t={id:e.id,name:e.name,status:"unfinished"},a=JSON.stringify(e.arguments??{}),n=x.encode(a).length;return n>c.maxArgumentBytesPerCall||this.argumentBytes+n>c.maxArgumentBytesTotal?(t.argumentsBytes=n,this.complete=!1):(t.arguments=JSON.parse(a),this.argumentBytes+=n),this.calls.push(t),this.startedAt.set(t,performance.now()),t}finish(e,t,a){e&&(e.status=t?"error":"ok",e.durationMs=Math.round(performance.now()-(this.startedAt.get(e)??performance.now())),this.startedAt.delete(e),t&&a&&(e.error=a.slice(0,c.maxErrorChars)))}addUsage(e){this.usage=this.usage?f(this.usage,e):e}get totalUsage(){return this.usage}snapshot(){if(this.calls.length===0&&this.complete)return;const e=this.calls.map(t=>({...t}));return{calls:e,complete:this.complete&&e.every(t=>t.status!=="unfinished")}}}function C(l){return(l.content??[]).filter(e=>e.type==="text").map(e=>e.text).join(`
2
- `)}u(C,"textOf");class A{static{u(this,"NestedToolCallRunner")}host;scopes=new Map;queueTail=Promise.resolve();constructor(e){this.host=e}async execute(e,t,a,n={}){let s=this.scopes.get(e);s||(s={recorder:new y,nextId:1,holdsQueue:!1},this.scopes.set(e,s));const r={type:"toolCall",id:`${e}/${s.nextId++}`,name:t,arguments:a??{}},m=s.recorder.start(r);await this.host.emit({type:"tool_execution_start",toolCallId:r.id,toolName:t,args:r.arguments,parentToolCallId:e});const h=!s.holdsQueue&&(this.host.isSequential()||this.host.getTools().find(i=>i.name===t)?.executionMode==="sequential");let d;if(h){const i=this.queueTail;this.queueTail=new Promise(p=>{d=p}),await i}this.scopes.set(r.id,{recorder:s.recorder,nextId:1,holdsQueue:s.holdsQueue||h});let o;try{o=await this.host.runToolCall(r,e,n.signal,async i=>{n.onUpdate?.(i),await this.host.emit({type:"tool_execution_update",toolCallId:r.id,toolName:t,args:r.arguments,partialResult:i,parentToolCallId:e})})}finally{this.scopes.delete(r.id),d?.()}return s.recorder.finish(m,o.isError,C(o.result)),o.result.usage&&s.recorder.addUsage(o.result.usage),await this.host.emit({type:"tool_execution_end",toolCallId:r.id,toolName:t,result:o.result,isError:o.isError,...o.durationMs===void 0?{}:{durationMs:o.durationMs},parentToolCallId:e}),o}takeRecord(e){const t=this.scopes.get(e);if(this.scopes.delete(e),!!t)return{calls:t.recorder.snapshot(),usage:t.recorder.totalUsage}}clear(){this.scopes.clear()}}export{c as NESTED_CALL_LIMITS,y as NestedCallRecorder,A as NestedToolCallRunner};
1
+ var C=Object.defineProperty;var d=(l,e)=>C(l,"name",{value:e,configurable:!0});import{combineUsage as w}from"./usage-totals.js";const c={maxCalls:256,maxArgumentBytesPerCall:8*1024,maxArgumentBytesTotal:32*1024,maxErrorChars:500},T=new TextEncoder;class f{static{d(this,"NestedCallRecorder")}calls=[];startedAt=new Map;complete=!0;argumentBytes=0;usage;start(e){if(this.calls.length>=c.maxCalls){this.complete=!1;return}const t={id:e.id,name:e.name,status:"unfinished"},i=JSON.stringify(e.arguments??{}),r=T.encode(i).length;return r>c.maxArgumentBytesPerCall||this.argumentBytes+r>c.maxArgumentBytesTotal?(t.argumentsBytes=r,this.complete=!1):(t.arguments=JSON.parse(i),this.argumentBytes+=r),this.calls.push(t),this.startedAt.set(t,performance.now()),t}finish(e,t,i){e&&(e.status=t?"error":"ok",e.durationMs=Math.round(performance.now()-(this.startedAt.get(e)??performance.now())),this.startedAt.delete(e),t&&i&&(e.error=i.slice(0,c.maxErrorChars)))}addUsage(e){this.usage=this.usage?w(this.usage,e):e}get totalUsage(){return this.usage}snapshot(){if(this.calls.length===0&&this.complete)return;const e=this.calls.map(t=>({...t}));return{calls:e,complete:this.complete&&e.every(t=>t.status!=="unfinished")}}}function A(l){return(l.content??[]).filter(e=>e.type==="text").map(e=>e.text).join(`
2
+ `)}d(A,"textOf");class N{static{d(this,"NestedToolCallRunner")}host;scopes=new Map;queueTail=Promise.resolve();detachedSeq=1;constructor(e){this.host=e}async execute(e,t,i,r={}){let s=this.scopes.get(e),h;r.detached&&!s?.detached?(s={recorder:new f,nextId:1,holdsQueue:!1,detached:!0},h=`${e}/detached-${this.detachedSeq++}`):(s||(s={recorder:new f,nextId:1,holdsQueue:!1,detached:!1},this.scopes.set(e,s)),h=`${e}/${s.nextId++}`);const u=s.detached,a={type:"toolCall",id:h,name:t,arguments:i??{}},m=u?async()=>{}:n=>this.host.emit(n),x=u?void 0:s.recorder.start(a);await m({type:"tool_execution_start",toolCallId:a.id,toolName:t,args:a.arguments,parentToolCallId:e});const p=!s.holdsQueue&&(this.host.isSequential()||this.host.getTools().find(n=>n.name===t)?.executionMode==="sequential");let g;if(p){const n=this.queueTail;this.queueTail=new Promise(y=>{g=y}),await n}this.scopes.set(a.id,{recorder:s.recorder,nextId:1,holdsQueue:s.holdsQueue||p,detached:u});let o;try{o=await this.host.runToolCall(a,e,r.signal,async n=>{r.onUpdate?.(n),await m({type:"tool_execution_update",toolCallId:a.id,toolName:t,args:a.arguments,partialResult:n,parentToolCallId:e})})}finally{this.scopes.delete(a.id),g?.()}return s.recorder.finish(x,o.isError,A(o.result)),o.result.usage&&!u&&s.recorder.addUsage(o.result.usage),await m({type:"tool_execution_end",toolCallId:a.id,toolName:t,result:o.result,isError:o.isError,...o.durationMs===void 0?{}:{durationMs:o.durationMs},parentToolCallId:e}),o}takeRecord(e){const t=this.scopes.get(e);if(this.scopes.delete(e),!!t)return{calls:t.recorder.snapshot(),usage:t.recorder.totalUsage}}clear(){this.scopes.clear()}}export{c as NESTED_CALL_LIMITS,f as NestedCallRecorder,N as NestedToolCallRunner};
@@ -1 +1 @@
1
- var ht=Object.defineProperty;var P=(l,t)=>ht(l,"name",{value:t,configurable:!0});import{existsSync as f,readdirSync as lt,readFileSync as B,statSync as T}from"node:fs";import{basename as ct,dirname as q,join as m,resolve as S,sep as b}from"node:path";import{detectCapabilities as pt,getTerminalColorMode as mt}from"@earendil-works/pi-tui";import Q from"chalk";import{APP_NAME as dt,CONFIG_DIR_NAME as v,getExamplesPath as ut}from"../config.js";import{dalBuiltinExtensionPaths as ft}from"../dal/builtins.js";import{fill as $,t as y}from"../dal/i18n.js";import{loadThemeFromPath as Pt}from"../modes/interactive/theme/theme.js";import{canonicalizePath as M,isLocalPath as j,resolvePath as w}from"../utils/paths.js";import{stripBom as W}from"../utils/text.js";import{createEventBus as gt}from"./event-bus.js";import{clearExtensionCache as xt,createExtensionRuntime as St,loadExtensionFromFactory as Z,loadExtensionsCached as tt}from"./extensions/loader.js";import{findGitPaths as yt}from"./footer-data-provider.js";import{DefaultPackageManager as wt}from"./package-manager.js";import{loadPromptTemplates as vt}from"./prompt-templates.js";import{SettingsManager as kt}from"./settings-manager.js";import{loadSkills as Et}from"./skills.js";import{BUILTIN_PATH_PREFIX as k,createSourceInfo as I,getSyntheticPathSource as Ft,isSyntheticPath as N}from"./source-info.js";import{resetTimings as Dt}from"./timings.js";const Tt=new Set(["@earendil-works/pi-agent-core","@earendil-works/pi-ai","@earendil-works/pi-coding-agent","@earendil-works/pi-tui","@mariozechner/pi-agent-core","@mariozechner/pi-ai","@mariozechner/pi-coding-agent","@mariozechner/pi-tui","@sinclair/typebox","typebox"]);function et(l,t){const n=[],s=new Set(l.map(i=>t.get(i)?.packageRoot).filter(i=>i!==void 0));for(const i of s){const e=m(i,"package.json");if(!f(e))continue;const o=JSON.parse(W(B(e,"utf-8")));if(typeof o.dependencies!="object"||o.dependencies===null||Array.isArray(o.dependencies))continue;const a=Object.keys(o.dependencies).filter(c=>Tt.has(c)).sort();a.length!==0&&n.push({path:e,warning:`Host-provided extension packages must be declared in peerDependencies with a "*" range, not dependencies: ${a.join(", ")}. Installed copies can bypass the extension loader and create duplicate runtime modules.`})}return n}P(et,"collectExtensionPackageWarnings");function A(l,t){l.warnings=[...new Map([...l.warnings??[],...t].map(n=>[n.path,n])).values()]}P(A,"mergeExtensionWarnings");function st(l){return typeof l!="function"&&l.builtin===!0}P(st,"isBuiltinExtension");let it;function bt(l){return it??=new Set(ft().map(t=>S(t))),it.has(S(l))}P(bt,"isDalBundledExtensionPath");function nt(l,t){const n=P(i=>[...[...i.tools.keys()].map(e=>`tool:${e}`),...[...i.commands.keys()].map(e=>`command:${e}`),...[...i.flags.keys()].map(e=>`flag:${e}`)],"names"),s=new Map(l.filter(i=>!i.replaceable).flatMap(i=>n(i).map(e=>[e,i])));return l.filter(i=>{if(!i.replaceable)return!0;const e=n(i).map(o=>({name:o,extension:s.get(o)})).find(o=>o.extension!==void 0);if(!e)return!0;if(i.path.startsWith(k)&&!bt(e.extension.path)){const o=i.path.slice(k.length),[a,c]=e.name.split(":",2),h=a==="command"?`/${c}`:a==="flag"?`--${c}`:c;t?.push({path:i.path,warning:$(y("\u6269\u5C55 {path} \u6CE8\u518C\u4E86{kind} `{name}`\uFF0C\u6240\u4EE5\u5185\u7F6E\u6269\u5C55 `{builtin}` \u6CA1\u6709\u52A0\u8F7D\u3002\u8981\u4F7F\u7528 `{builtin}`\uFF0C\u8FD0\u884C `{app} config`\uFF0C\u5728\u5185\u7F6E\u6269\u5C55\u91CC\u786E\u8BA4\u5B83\u5DF2\u542F\u7528\uFF0C\u7136\u540E\u505C\u7528\u6216\u79FB\u9664\u8FD9\u4E2A\u6269\u5C55\u3002\u4E24\u8005\u6700\u597D\u53EA\u4FDD\u7559\u4E00\u4E2A\u3002"),{path:e.extension.path,kind:a==="command"?y("\u4E00\u4E2A\u547D\u4EE4"):a==="flag"?y("\u4E00\u4E2A\u53C2\u6570"):y("\u4E00\u4E2A\u5DE5\u5177"),name:h,builtin:o,app:dt})})}return!1})}P(nt,"omitReplacedExtensions");function ot(l,t){if(l){if(f(l))try{return W(B(l,"utf-8"))}catch(n){return console.error(Q.yellow($(y("\u8B66\u544A\uFF1A\u65E0\u6CD5\u8BFB\u53D6{what}\u6587\u4EF6 {path}\uFF1A{error}"),{what:t,path:l,error:String(n)}))),l}return l}}P(ot,"resolvePromptInput");function z(l){const t=["AGENTS.override.md","AGENTS.md","AGENTS.MD","CLAUDE.md","CLAUDE.MD"];for(const n of t){const s=m(l,n);if(f(s))try{if(!T(s).isFile())continue;return{path:s,content:W(B(s,"utf-8"))}}catch(i){console.error(Q.yellow($(y("\u8B66\u544A\uFF1A\u65E0\u6CD5\u8BFB\u53D6 {path}\uFF1A{error}"),{path:s,error:String(i)})))}}return null}P(z,"loadContextFileFromDir");function Mt(l){const t=yt(l);if(!t)return;const n=M(t.commonGitDir),s=M(t.repoDir),i=q(n);if(!s.startsWith(`${i}${b}`)||M(m(i,".git"))!==n)return;const e=z(s);return e?m(i,ct(e.path)):void 0}P(Mt,"findShadowedContextFile");function It(l){const t=w(l.cwd),n=w(l.agentDir),s=[],i=new Set,e=z(n);e&&(s.push(e),i.add(e.path));const o=[],a=Mt(t);let c=t;for(;;){const h=z(c),g=a!==void 0&&M(h?.path??"")===a;h&&!g&&!i.has(h.path)&&(o.unshift(h),i.add(h.path));const x=q(c);if(x===c)break;c=x}return s.push(...o),s}P(It,"loadProjectContextFiles");class qt{static{P(this,"DefaultResourceLoader")}cwd;agentDir;settingsManager;eventBus;packageManager;additionalExtensionPaths;additionalSkillPaths;additionalPromptTemplatePaths;additionalThemePaths;extensionFactories;builtinExtensions;noExtensions;disabledBuiltinExtensions;noSkills;noPromptTemplates;noThemes;noContextFiles;systemPromptSource;appendSystemPromptSource;extensionsOverride;skillsOverride;promptsOverride;themesOverride;agentsFilesOverride;systemPromptOverride;appendSystemPromptOverride;extensionsResult;skills;skillDiagnostics;prompts;promptDiagnostics;themes;themeDiagnostics;agentsFiles;systemPrompt;systemPromptSourcePath;appendSystemPrompt;appendSystemPromptSourcePaths;lastSkillPaths;extensionSkillSourceInfos;extensionPromptSourceInfos;extensionThemeSourceInfos;resourceMetadataByPath;lastPromptPaths;lastThemePaths;loaded;constructor(t){this.cwd=w(t.cwd),this.agentDir=w(t.agentDir),this.settingsManager=t.settingsManager??kt.create(this.cwd,this.agentDir),this.eventBus=t.eventBus??gt();const n=t.extensionFactories??[];this.extensionFactories=n.filter(s=>!st(s)),this.builtinExtensions=new Map(n.filter(st).map(s=>[s.name,s])),this.packageManager=new wt({cwd:this.cwd,agentDir:this.agentDir,settingsManager:this.settingsManager,builtinExtensions:[...this.builtinExtensions.keys()]}),this.additionalExtensionPaths=t.additionalExtensionPaths??[],this.additionalSkillPaths=t.additionalSkillPaths??[],this.additionalPromptTemplatePaths=t.additionalPromptTemplatePaths??[],this.additionalThemePaths=t.additionalThemePaths??[],this.noExtensions=t.noExtensions??!1,this.disabledBuiltinExtensions=new Set(t.disabledBuiltinExtensions),this.noSkills=t.noSkills??!1,this.noPromptTemplates=t.noPromptTemplates??!1,this.noThemes=t.noThemes??!1,this.noContextFiles=t.noContextFiles??!1,this.systemPromptSource=t.systemPrompt,this.appendSystemPromptSource=t.appendSystemPrompt,this.extensionsOverride=t.extensionsOverride,this.skillsOverride=t.skillsOverride,this.promptsOverride=t.promptsOverride,this.themesOverride=t.themesOverride,this.agentsFilesOverride=t.agentsFilesOverride,this.systemPromptOverride=t.systemPromptOverride,this.appendSystemPromptOverride=t.appendSystemPromptOverride,this.extensionsResult={extensions:[],errors:[],runtime:St()},this.skills=[],this.skillDiagnostics=[],this.prompts=[],this.promptDiagnostics=[],this.themes=[],this.themeDiagnostics=[],this.agentsFiles=[],this.appendSystemPrompt=[],this.appendSystemPromptSourcePaths=[],this.lastSkillPaths=[],this.extensionSkillSourceInfos=new Map,this.extensionPromptSourceInfos=new Map,this.extensionThemeSourceInfos=new Map,this.resourceMetadataByPath=new Map,this.lastPromptPaths=[],this.lastThemePaths=[],this.loaded=!1}getExtensions(){return this.extensionsResult}getSkills(){return{skills:this.skills,diagnostics:this.skillDiagnostics}}getPrompts(){return{prompts:this.prompts,diagnostics:this.promptDiagnostics}}getThemes(){return{themes:this.themes,diagnostics:this.themeDiagnostics}}getAgentsFiles(){return{agentsFiles:this.agentsFiles}}getSystemPrompt(){return this.systemPrompt}getSystemPromptSource(){return this.systemPromptSourcePath?{path:this.systemPromptSourcePath}:void 0}getAppendSystemPrompt(){return this.appendSystemPrompt}getAppendSystemPromptSources(){return this.appendSystemPromptSourcePaths.map(t=>({path:t}))}extendResources(t){const n=this.normalizeExtensionPaths(t.skillPaths??[]),s=this.normalizeExtensionPaths(t.promptPaths??[]),i=this.normalizeExtensionPaths(t.themePaths??[]);for(const e of n)this.extensionSkillSourceInfos.set(e.path,I(e.path,e.metadata));for(const e of s)this.extensionPromptSourceInfos.set(e.path,I(e.path,e.metadata));for(const e of i)this.extensionThemeSourceInfos.set(e.path,I(e.path,e.metadata));n.length>0&&(this.lastSkillPaths=this.mergePaths(this.lastSkillPaths,n.map(e=>e.path)),this.updateSkillsFromPaths(this.lastSkillPaths,this.resourceMetadataByPath)),s.length>0&&(this.lastPromptPaths=this.mergePaths(this.lastPromptPaths,s.map(e=>e.path)),this.updatePromptsFromPaths(this.lastPromptPaths,this.resourceMetadataByPath)),i.length>0&&(this.lastThemePaths=this.mergePaths(this.lastThemePaths,i.map(e=>e.path)),this.updateThemesFromPaths(this.lastThemePaths,this.resourceMetadataByPath))}async loadProjectTrustExtensions(){return this.settingsManager.setProjectTrusted(!1),await this.settingsManager.reload(),this.loadCurrentExtensionSet({includeInlineFactories:!0})}async reload(t){Dt("extensions"),this.loaded&&xt();let n;if(t?.resolveProjectTrust){n=await this.loadProjectTrustExtensions();const r=await t.resolveProjectTrust({extensionsResult:n});this.settingsManager.setProjectTrusted(r)}await this.settingsManager.reload();const s=await this.packageManager.resolve(),i=await this.packageManager.resolveExtensionSources(this.additionalExtensionPaths,{temporary:!0});this.resourceMetadataByPath=new Map;const e=this.resourceMetadataByPath;this.extensionSkillSourceInfos=new Map,this.extensionPromptSourceInfos=new Map,this.extensionThemeSourceInfos=new Map;const o=P(r=>{for(const p of r)e.has(p.path)||e.set(p.path,p.metadata);return r.filter(p=>p.enabled)},"getEnabledResources"),a=P(r=>o(r).map(p=>p.path),"getEnabledPaths"),c=a(s.extensions),h=o(s.skills),g=a(s.prompts),x=a(s.themes),u=h.map(r=>this.mapSkillPath(r,e));for(const r of i.extensions)e.has(r.path)||e.set(r.path,{source:"cli",scope:"temporary",origin:"top-level"});for(const r of i.skills)e.has(r.path)||e.set(r.path,{source:"cli",scope:"temporary",origin:"top-level"});const d=a(i.extensions),E=a(i.skills),L=a(i.prompts),_=a(i.themes),G=(this.noExtensions?d:this.mergePaths(d,c)).filter(r=>!r.startsWith(k)||!this.disabledBuiltinExtensions.has(r.slice(k.length))),at=et(G,e),O=await this.loadFinalExtensionSet(G,n);A(O,at);for(const r of this.additionalExtensionPaths)if(j(r)){const p=this.resolveResourcePath(r);f(p)||O.errors.push({path:p,error:`Extension path does not exist: ${p}`})}this.extensionsResult=this.extensionsOverride?this.extensionsOverride(O):O,this.applyExtensionSourceInfo(this.extensionsResult.extensions,e);const F=m(ut(),"skills"),U=!this.noSkills&&f(F)?[F]:[];U.length>0&&!e.has(F)&&e.set(F,{source:"auto",scope:"user",origin:"top-level",baseDir:F});const Y=this.noSkills?this.mergePaths(E,this.additionalSkillPaths):this.mergePaths([...E,...u,...U],this.additionalSkillPaths);this.lastSkillPaths=Y,this.updateSkillsFromPaths(Y,e);for(const r of this.additionalSkillPaths)if(j(r)){const p=this.resolveResourcePath(r);!f(p)&&!this.skillDiagnostics.some(D=>D.path===p)&&this.skillDiagnostics.push({type:"error",message:"Skill path does not exist",path:p})}const H=this.noPromptTemplates?this.mergePaths(L,this.additionalPromptTemplatePaths):this.mergePaths([...L,...g],this.additionalPromptTemplatePaths);this.lastPromptPaths=H,this.updatePromptsFromPaths(H,e);for(const r of this.additionalPromptTemplatePaths)if(j(r)){const p=this.resolveResourcePath(r);!f(p)&&!this.promptDiagnostics.some(D=>D.path===p)&&this.promptDiagnostics.push({type:"error",message:"Prompt template path does not exist",path:p})}const J=this.noThemes?this.mergePaths(_,this.additionalThemePaths):this.mergePaths([..._,...x],this.additionalThemePaths);this.lastThemePaths=J,this.updateThemesFromPaths(J,e);for(const r of this.additionalThemePaths){const p=this.resolveResourcePath(r);!f(p)&&!this.themeDiagnostics.some(D=>D.path===p)&&this.themeDiagnostics.push({type:"error",message:"Theme path does not exist",path:p})}const K={agentsFiles:this.noContextFiles?[]:It({cwd:this.cwd,agentDir:this.agentDir})},rt=this.agentsFilesOverride?this.agentsFilesOverride(K):K;this.agentsFiles=rt.agentsFiles;const R=this.systemPromptSource??this.discoverSystemPromptFile(),X=ot(R,y("\u7CFB\u7EDF\u63D0\u793A\u8BCD"));this.systemPrompt=this.systemPromptOverride?this.systemPromptOverride(X):X,this.systemPromptSourcePath=R&&f(R)?w(R):void 0;let C=this.appendSystemPromptSource;if(!C){const r=this.discoverAppendSystemPromptFile();C=r?[r]:[]}const V=C.map(r=>ot(r,y("\u8FFD\u52A0\u7684\u7CFB\u7EDF\u63D0\u793A\u8BCD"))).filter(r=>r!==void 0);this.appendSystemPrompt=this.appendSystemPromptOverride?this.appendSystemPromptOverride(V):V,this.appendSystemPromptSourcePaths=C.filter(r=>f(r)).map(r=>w(r)),this.loaded=!0}async loadCurrentExtensionSet(t){const n=await this.packageManager.resolve(),s=await this.packageManager.resolveExtensionSources(this.additionalExtensionPaths,{temporary:!0}),i=n.extensions.filter(u=>u.enabled).map(u=>u.path),e=s.extensions.filter(u=>u.enabled).map(u=>u.path),o=(this.noExtensions?e:this.mergePaths(e,i)).filter(u=>!u.startsWith(k)),a=new Map([...n.extensions,...s.extensions].map(u=>[u.path,u.metadata])),c=et(o,a),h=await tt(o,this.cwd,this.eventBus);if(A(h,c),!t.includeInlineFactories)return h;const g=await this.loadExtensionFactories(h.runtime);h.extensions.push(...g.extensions),h.errors.push(...g.errors);const x=[];return h.extensions=nt(h.extensions,x),A(h,x),h}resolveExtensionLoadPath(t){return N(t)?t:w(t,this.cwd,{normalizeUnicodeSpaces:!0})}async loadExtensionPaths(t,n){const s=P(e=>e.startsWith(k),"isBuiltinPath"),i=await tt(t.filter(e=>!s(e)),this.cwd,this.eventBus,n);for(const e of t.filter(s)){const o=this.builtinExtensions.get(e.slice(k.length));if(!o){i.errors.push({path:e,error:`Unknown built-in extension: ${e}`});continue}try{const a=await Z(o.factory,this.cwd,this.eventBus,i.runtime,e);a.hidden=!0,a.replaceable=o.replaceable===!0,i.extensions.push(a)}catch(a){i.errors.push({path:e,error:a instanceof Error?a.message:"failed to load extension"})}}return i}async loadFinalExtensionSet(t,n){const s=n?.extensions??[],i=new Map(s.filter(d=>!d.path.startsWith("<inline:")).map(d=>[d.resolvedPath,d])),e=new Set((n?.errors??[]).map(d=>this.resolveExtensionLoadPath(d.path))),o=t.filter(d=>{const E=this.resolveExtensionLoadPath(d);return!i.has(E)&&!e.has(E)}),a=await this.loadExtensionPaths(o,n?.runtime),c=new Map(i);for(const d of a.extensions)c.set(d.resolvedPath,d);const h=n?{extensions:s.filter(d=>d.path.startsWith("<inline:")),errors:[]}:await this.loadExtensionFactories(a.runtime),g=t.map(d=>c.get(this.resolveExtensionLoadPath(d))).filter(d=>d!==void 0);g.push(...h.extensions);const x=[],u={extensions:nt(g,x),errors:[...n?.errors??[],...a.errors,...h.errors],warnings:[...n?.warnings??[],...a.warnings??[]],runtime:a.runtime};return A(u,x),this.addExtensionConflictDiagnostics(u),u}addExtensionConflictDiagnostics(t){const n=this.detectExtensionConflicts(t.extensions);for(const s of n)t.errors.push({path:s.path,error:s.message})}mapSkillPath(t,n){if(t.metadata.source!=="auto"&&t.metadata.origin!=="package")return t.path;try{if(!T(t.path).isDirectory())return t.path}catch{return t.path}const s=m(t.path,"SKILL.md");return f(s)?(n.has(s)||n.set(s,t.metadata),s):t.path}normalizeExtensionPaths(t){return t.map(n=>{const s=n.metadata.baseDir?{...n.metadata,baseDir:this.resolveResourcePath(n.metadata.baseDir)}:n.metadata;return{path:this.resolveResourcePath(n.path),metadata:s}})}updateSkillsFromPaths(t,n){let s;this.noSkills&&t.length===0?s={skills:[],diagnostics:[]}:s=Et({cwd:this.cwd,agentDir:this.agentDir,skillPaths:t,includeDefaults:!1});const i=this.skillsOverride?this.skillsOverride(s):s;this.skills=i.skills.map(e=>({...e,sourceInfo:this.findSourceInfoForPath(e.filePath,this.extensionSkillSourceInfos,n)??e.sourceInfo??this.getDefaultSourceInfoForPath(e.filePath)})),this.skillDiagnostics=i.diagnostics}updatePromptsFromPaths(t,n){let s;if(this.noPromptTemplates&&t.length===0)s={prompts:[],diagnostics:[]};else{const e=vt({cwd:this.cwd,agentDir:this.agentDir,promptPaths:t,includeDefaults:!1}),o=this.dedupePrompts(e.templates);s={prompts:o.prompts,diagnostics:[...e.diagnostics,...o.diagnostics]}}const i=this.promptsOverride?this.promptsOverride(s):s;this.prompts=i.prompts.map(e=>({...e,sourceInfo:this.findSourceInfoForPath(e.filePath,this.extensionPromptSourceInfos,n)??e.sourceInfo??this.getDefaultSourceInfoForPath(e.filePath)})),this.promptDiagnostics=i.diagnostics}updateThemesFromPaths(t,n){let s;if(this.noThemes&&t.length===0)s={themes:[],diagnostics:[]};else{const e=mt({...pt(()=>!1),...this.settingsManager.getTerminalCapabilityOverrides()}),o=this.loadThemes(t,!1,e),a=this.dedupeThemes(o.themes);s={themes:a.themes,diagnostics:[...o.diagnostics,...a.diagnostics]}}const i=this.themesOverride?this.themesOverride(s):s;this.themes=i.themes.map(e=>{const o=e.sourcePath;return e.sourceInfo=o?this.findSourceInfoForPath(o,this.extensionThemeSourceInfos,n)??e.sourceInfo??this.getDefaultSourceInfoForPath(o):e.sourceInfo,e}),this.themeDiagnostics=i.diagnostics}applyExtensionSourceInfo(t,n){for(const s of t){s.sourceInfo=this.findSourceInfoForPath(s.path,void 0,n)??this.getDefaultSourceInfoForPath(s.path);for(const i of s.commands.values())i.sourceInfo=s.sourceInfo;for(const i of s.tools.values())i.sourceInfo=s.sourceInfo}}findSourceInfoForPath(t,n,s){if(!t)return;if(N(t))return this.getDefaultSourceInfoForPath(t);const i=S(t);if(n)for(const[e,o]of n.entries()){const a=S(e);if(i===a||i.startsWith(`${a}${b}`))return{...o,path:t}}if(s){const e=s.get(i)??s.get(t);if(e)return I(t,e);for(const[o,a]of s.entries()){const c=S(o);if(i===c||i.startsWith(`${c}${b}`))return I(t,a)}}}getDefaultSourceInfoForPath(t){const n=Ft(t);if(n)return{path:t,source:n,scope:"temporary",origin:"top-level"};const s=S(t),i=[m(this.agentDir,"skills"),m(this.agentDir,"prompts"),m(this.agentDir,"themes"),m(this.agentDir,"extensions")],e=[m(this.cwd,v,"skills"),m(this.cwd,v,"prompts"),m(this.cwd,v,"themes"),m(this.cwd,v,"extensions")];for(const o of i)if(this.isUnderPath(s,o))return{path:t,source:"local",scope:"user",origin:"top-level",baseDir:o};for(const o of e)if(this.isUnderPath(s,o))return{path:t,source:"local",scope:"project",origin:"top-level",baseDir:o};return{path:t,source:"local",scope:"temporary",origin:"top-level",baseDir:T(s).isDirectory()?s:S(s,"..")}}mergePaths(t,n){const s=[],i=new Set;for(const e of[...t,...n]){const o=this.resolveResourcePath(e),a=M(o);i.has(a)||(i.add(a),s.push(o))}return s}resolveResourcePath(t){return N(t)?t:w(t,this.cwd,{trim:!0})}loadThemes(t,n,s){const i=[],e=[];if(n){const o=[m(this.agentDir,"themes"),m(this.cwd,v,"themes")];for(const a of o)this.loadThemesFromDir(a,i,e,s)}for(const o of t){const a=this.resolveResourcePath(o);if(!f(a)){e.push({type:"warning",message:"theme path does not exist",path:a});continue}try{const c=T(a);c.isDirectory()?this.loadThemesFromDir(a,i,e,s):c.isFile()&&a.endsWith(".json")?this.loadThemeFromFile(a,i,e,s):e.push({type:"warning",message:"theme path is not a json file",path:a})}catch(c){const h=c instanceof Error?c.message:"failed to read theme path";e.push({type:"warning",message:h,path:a})}}return{themes:i,diagnostics:e}}loadThemesFromDir(t,n,s,i){if(f(t))try{const e=lt(t,{withFileTypes:!0});for(const o of e){let a=o.isFile();if(o.isSymbolicLink())try{a=T(m(t,o.name)).isFile()}catch{continue}a&&o.name.endsWith(".json")&&this.loadThemeFromFile(m(t,o.name),n,s,i)}}catch(e){const o=e instanceof Error?e.message:"failed to read theme directory";s.push({type:"warning",message:o,path:t})}}loadThemeFromFile(t,n,s,i){try{n.push(Pt(t,i))}catch(e){const o=e instanceof Error?e.message:"failed to load theme";s.push({type:"warning",message:o,path:t})}}async loadExtensionFactories(t){const n=[],s=[];for(const[i,e]of this.extensionFactories.entries()){const o=typeof e!="function",a=o?e.factory:e,c=`<inline:${o?e.name:i+1}>`;try{const h=await Z(a,this.cwd,this.eventBus,t,c);h.hidden=o&&e.hidden,h.replaceable=o&&e.replaceable===!0,n.push(h)}catch(h){const g=h instanceof Error?h.message:"failed to load extension";s.push({path:c,error:g})}}return{extensions:n,errors:s}}dedupePrompts(t){const n=new Map,s=[];for(const i of t){const e=n.get(i.name);e?s.push({type:"collision",message:`name "/${i.name}" collision`,path:i.filePath,collision:{resourceType:"prompt",name:i.name,winnerPath:e.filePath,loserPath:i.filePath}}):n.set(i.name,i)}return{prompts:Array.from(n.values()),diagnostics:s}}dedupeThemes(t){const n=new Map,s=[];for(const i of t){const e=i.name??"unnamed",o=n.get(e);o?s.push({type:"collision",message:`name "${e}" collision`,path:i.sourcePath,collision:{resourceType:"theme",name:e,winnerPath:o.sourcePath??"<builtin>",loserPath:i.sourcePath??"<builtin>"}}):n.set(e,i)}return{themes:Array.from(n.values()),diagnostics:s}}discoverSystemPromptFile(){const t=m(this.cwd,v,"SYSTEM.md");if(this.settingsManager.isProjectTrusted()&&f(t))return t;const n=m(this.agentDir,"SYSTEM.md");if(f(n))return n}discoverAppendSystemPromptFile(){const t=m(this.cwd,v,"APPEND_SYSTEM.md");if(this.settingsManager.isProjectTrusted()&&f(t))return t;const n=m(this.agentDir,"APPEND_SYSTEM.md");if(f(n))return n}isUnderPath(t,n){const s=S(n);if(t===s)return!0;const i=s.endsWith(b)?s:`${s}${b}`;return t.startsWith(i)}detectExtensionConflicts(t){const n=[],s=new Map,i=new Map;for(const e of t){for(const o of e.tools.keys()){const a=s.get(o);a&&a!==e.path?n.push({path:e.path,message:`Tool "${o}" conflicts with ${a}`}):s.set(o,e.path)}for(const o of e.flags.keys()){const a=i.get(o);a&&a!==e.path?n.push({path:e.path,message:`Flag "--${o}" conflicts with ${a}`}):i.set(o,e.path)}}return n}}export{qt as DefaultResourceLoader,st as isBuiltinExtension,It as loadProjectContextFiles};
1
+ var lt=Object.defineProperty;var P=(c,t)=>lt(c,"name",{value:t,configurable:!0});import{existsSync as f,readdirSync as ct,readFileSync as $,statSync as T}from"node:fs";import{basename as mt,dirname as Q,join as p,resolve as y,sep as b}from"node:path";import{detectCapabilities as pt,getTerminalColorMode as dt}from"@earendil-works/pi-tui";import V from"chalk";import{APP_NAME as ut,CONFIG_DIR_NAME as v,getExamplesPath as ft,getPackageDir as Pt}from"../config.js";import{dalBuiltinExtensionPaths as gt}from"../dal/builtins.js";import{applyCommunityEnv as xt,hostDependenciesOf as Z,installedHostCopies as St,isAdaptablePackage as yt,tryEnsurePackageAdapted as wt}from"../dal/extension-compat.js";import{fill as A,t as S}from"../dal/i18n.js";import{loadThemeFromPath as vt}from"../modes/interactive/theme/theme.js";import{canonicalizePath as M,isLocalPath as j,resolvePath as w}from"../utils/paths.js";import{stripBom as W}from"../utils/text.js";import{createEventBus as kt}from"./event-bus.js";import{clearExtensionCache as Et,createExtensionRuntime as Dt,loadExtensionFromFactory as tt,loadExtensionsCached as et}from"./extensions/loader.js";import{findGitPaths as Ft}from"./footer-data-provider.js";import{DefaultPackageManager as Tt}from"./package-manager.js";import{loadPromptTemplates as bt}from"./prompt-templates.js";import{SettingsManager as Mt}from"./settings-manager.js";import{loadSkills as It}from"./skills.js";import{BUILTIN_PATH_PREFIX as k,createSourceInfo as I,getSyntheticPathSource as Ot,isSyntheticPath as N}from"./source-info.js";import{resetTimings as Rt}from"./timings.js";function st(c,t,n){let s;try{s=Pt()}catch{s=void 0}xt({agentDir:n.agentDir,packageDir:s});const i=[],e=new Map;for(const o of c){const a=t.get(o);a?.packageRoot&&!e.has(a.packageRoot)&&e.set(a.packageRoot,a)}for(const[o,a]of e){const l=p(o,"package.json");if(!f(l))continue;JSON.parse(W($(l,"utf-8"))),yt(o,a.source,n)&&wt(o);const h=St(o,Z(o));if(h.length===0)continue;const g=Z(o).filter(x=>h.some(d=>d.endsWith(p(...x.split("/")))));i.push({path:l,warning:A(S('\u6269\u5C55\u5305\u5728 dependencies \u91CC\u81EA\u5E26\u4E86 DAL \u5DF2\u63D0\u4F9B\u7684\u5E93\uFF08{names}\uFF09\uFF0C\u8FD9\u4E9B\u526F\u672C\u4F1A\u548C DAL \u81EA\u5DF1\u7684\u91CD\u590D\u52A0\u8F7D\u3002\u8BF7\u628A\u5B83\u4EEC\u6539\u5230 peerDependencies\uFF0C\u7248\u672C\u5199 "*"\u3002'),{names:g.join(", ")})})}return i}P(st,"prepareExtensionPackages");function B(c,t){c.warnings=[...new Map([...c.warnings??[],...t].map(n=>[n.path,n])).values()]}P(B,"mergeExtensionWarnings");function it(c){return typeof c!="function"&&c.builtin===!0}P(it,"isBuiltinExtension");let nt;function Ct(c){return nt??=new Set(gt().map(t=>y(t))),nt.has(y(c))}P(Ct,"isDalBundledExtensionPath");function ot(c,t){const n=P(i=>[...[...i.tools.keys()].map(e=>`tool:${e}`),...[...i.commands.keys()].map(e=>`command:${e}`),...[...i.flags.keys()].map(e=>`flag:${e}`)],"names"),s=new Map(c.filter(i=>!i.replaceable).flatMap(i=>n(i).map(e=>[e,i])));return c.filter(i=>{if(!i.replaceable)return!0;const e=n(i).map(o=>({name:o,extension:s.get(o)})).find(o=>o.extension!==void 0);if(!e)return!0;if(i.path.startsWith(k)&&!Ct(e.extension.path)){const o=i.path.slice(k.length),[a,l]=e.name.split(":",2),h=a==="command"?`/${l}`:a==="flag"?`--${l}`:l;t?.push({path:i.path,warning:A(S("\u6269\u5C55 {path} \u6CE8\u518C\u4E86{kind} `{name}`\uFF0C\u6240\u4EE5\u5185\u7F6E\u6269\u5C55 `{builtin}` \u6CA1\u6709\u52A0\u8F7D\u3002\u8981\u4F7F\u7528 `{builtin}`\uFF0C\u8FD0\u884C `{app} config`\uFF0C\u5728\u5185\u7F6E\u6269\u5C55\u91CC\u786E\u8BA4\u5B83\u5DF2\u542F\u7528\uFF0C\u7136\u540E\u505C\u7528\u6216\u79FB\u9664\u8FD9\u4E2A\u6269\u5C55\u3002\u4E24\u8005\u6700\u597D\u53EA\u4FDD\u7559\u4E00\u4E2A\u3002"),{path:e.extension.path,kind:a==="command"?S("\u4E00\u4E2A\u547D\u4EE4"):a==="flag"?S("\u4E00\u4E2A\u53C2\u6570"):S("\u4E00\u4E2A\u5DE5\u5177"),name:h,builtin:o,app:ut})})}return!1})}P(ot,"omitReplacedExtensions");function at(c,t){if(c){if(f(c))try{return W($(c,"utf-8"))}catch(n){return console.error(V.yellow(A(S("\u8B66\u544A\uFF1A\u65E0\u6CD5\u8BFB\u53D6{what}\u6587\u4EF6 {path}\uFF1A{error}"),{what:t,path:c,error:String(n)}))),c}return c}}P(at,"resolvePromptInput");function L(c){const t=["AGENTS.override.md","AGENTS.md","AGENTS.MD","CLAUDE.md","CLAUDE.MD"];for(const n of t){const s=p(c,n);if(f(s))try{if(!T(s).isFile())continue;return{path:s,content:W($(s,"utf-8"))}}catch(i){console.error(V.yellow(A(S("\u8B66\u544A\uFF1A\u65E0\u6CD5\u8BFB\u53D6 {path}\uFF1A{error}"),{path:s,error:String(i)})))}}return null}P(L,"loadContextFileFromDir");function At(c){const t=Ft(c);if(!t)return;const n=M(t.commonGitDir),s=M(t.repoDir),i=Q(n);if(!s.startsWith(`${i}${b}`)||M(p(i,".git"))!==n)return;const e=L(s);return e?p(i,mt(e.path)):void 0}P(At,"findShadowedContextFile");function Bt(c){const t=w(c.cwd),n=w(c.agentDir),s=[],i=new Set,e=L(n);e&&(s.push(e),i.add(e.path));const o=[],a=At(t);let l=t;for(;;){const h=L(l),g=a!==void 0&&M(h?.path??"")===a;h&&!g&&!i.has(h.path)&&(o.unshift(h),i.add(h.path));const x=Q(l);if(x===l)break;l=x}return s.push(...o),s}P(Bt,"loadProjectContextFiles");class ie{static{P(this,"DefaultResourceLoader")}cwd;agentDir;settingsManager;eventBus;packageManager;additionalExtensionPaths;additionalSkillPaths;additionalPromptTemplatePaths;additionalThemePaths;extensionFactories;builtinExtensions;noExtensions;disabledBuiltinExtensions;noSkills;noPromptTemplates;noThemes;noContextFiles;systemPromptSource;appendSystemPromptSource;extensionsOverride;skillsOverride;promptsOverride;themesOverride;agentsFilesOverride;systemPromptOverride;appendSystemPromptOverride;extensionsResult;skills;skillDiagnostics;prompts;promptDiagnostics;themes;themeDiagnostics;agentsFiles;systemPrompt;systemPromptSourcePath;appendSystemPrompt;appendSystemPromptSourcePaths;lastSkillPaths;extensionSkillSourceInfos;extensionPromptSourceInfos;extensionThemeSourceInfos;resourceMetadataByPath;lastPromptPaths;lastThemePaths;loaded;constructor(t){this.cwd=w(t.cwd),this.agentDir=w(t.agentDir),this.settingsManager=t.settingsManager??Mt.create(this.cwd,this.agentDir),this.eventBus=t.eventBus??kt();const n=t.extensionFactories??[];this.extensionFactories=n.filter(s=>!it(s)),this.builtinExtensions=new Map(n.filter(it).map(s=>[s.name,s])),this.packageManager=new Tt({cwd:this.cwd,agentDir:this.agentDir,settingsManager:this.settingsManager,builtinExtensions:[...this.builtinExtensions.keys()]}),this.additionalExtensionPaths=t.additionalExtensionPaths??[],this.additionalSkillPaths=t.additionalSkillPaths??[],this.additionalPromptTemplatePaths=t.additionalPromptTemplatePaths??[],this.additionalThemePaths=t.additionalThemePaths??[],this.noExtensions=t.noExtensions??!1,this.disabledBuiltinExtensions=new Set(t.disabledBuiltinExtensions),this.noSkills=t.noSkills??!1,this.noPromptTemplates=t.noPromptTemplates??!1,this.noThemes=t.noThemes??!1,this.noContextFiles=t.noContextFiles??!1,this.systemPromptSource=t.systemPrompt,this.appendSystemPromptSource=t.appendSystemPrompt,this.extensionsOverride=t.extensionsOverride,this.skillsOverride=t.skillsOverride,this.promptsOverride=t.promptsOverride,this.themesOverride=t.themesOverride,this.agentsFilesOverride=t.agentsFilesOverride,this.systemPromptOverride=t.systemPromptOverride,this.appendSystemPromptOverride=t.appendSystemPromptOverride,this.extensionsResult={extensions:[],errors:[],runtime:Dt()},this.skills=[],this.skillDiagnostics=[],this.prompts=[],this.promptDiagnostics=[],this.themes=[],this.themeDiagnostics=[],this.agentsFiles=[],this.appendSystemPrompt=[],this.appendSystemPromptSourcePaths=[],this.lastSkillPaths=[],this.extensionSkillSourceInfos=new Map,this.extensionPromptSourceInfos=new Map,this.extensionThemeSourceInfos=new Map,this.resourceMetadataByPath=new Map,this.lastPromptPaths=[],this.lastThemePaths=[],this.loaded=!1}getExtensions(){return this.extensionsResult}getSkills(){return{skills:this.skills,diagnostics:this.skillDiagnostics}}getPrompts(){return{prompts:this.prompts,diagnostics:this.promptDiagnostics}}getThemes(){return{themes:this.themes,diagnostics:this.themeDiagnostics}}getAgentsFiles(){return{agentsFiles:this.agentsFiles}}getSystemPrompt(){return this.systemPrompt}getSystemPromptSource(){return this.systemPromptSourcePath?{path:this.systemPromptSourcePath}:void 0}getAppendSystemPrompt(){return this.appendSystemPrompt}getAppendSystemPromptSources(){return this.appendSystemPromptSourcePaths.map(t=>({path:t}))}extendResources(t){const n=this.normalizeExtensionPaths(t.skillPaths??[]),s=this.normalizeExtensionPaths(t.promptPaths??[]),i=this.normalizeExtensionPaths(t.themePaths??[]);for(const e of n)this.extensionSkillSourceInfos.set(e.path,I(e.path,e.metadata));for(const e of s)this.extensionPromptSourceInfos.set(e.path,I(e.path,e.metadata));for(const e of i)this.extensionThemeSourceInfos.set(e.path,I(e.path,e.metadata));n.length>0&&(this.lastSkillPaths=this.mergePaths(this.lastSkillPaths,n.map(e=>e.path)),this.updateSkillsFromPaths(this.lastSkillPaths,this.resourceMetadataByPath)),s.length>0&&(this.lastPromptPaths=this.mergePaths(this.lastPromptPaths,s.map(e=>e.path)),this.updatePromptsFromPaths(this.lastPromptPaths,this.resourceMetadataByPath)),i.length>0&&(this.lastThemePaths=this.mergePaths(this.lastThemePaths,i.map(e=>e.path)),this.updateThemesFromPaths(this.lastThemePaths,this.resourceMetadataByPath))}async loadProjectTrustExtensions(){return this.settingsManager.setProjectTrusted(!1),await this.settingsManager.reload(),this.loadCurrentExtensionSet({includeInlineFactories:!0})}async reload(t){Rt("extensions"),this.loaded&&Et();let n;if(t?.resolveProjectTrust){n=await this.loadProjectTrustExtensions();const r=await t.resolveProjectTrust({extensionsResult:n});this.settingsManager.setProjectTrusted(r)}await this.settingsManager.reload();const s=await this.packageManager.resolve(),i=await this.packageManager.resolveExtensionSources(this.additionalExtensionPaths,{temporary:!0});this.resourceMetadataByPath=new Map;const e=this.resourceMetadataByPath;this.extensionSkillSourceInfos=new Map,this.extensionPromptSourceInfos=new Map,this.extensionThemeSourceInfos=new Map;const o=P(r=>{for(const m of r)e.has(m.path)||e.set(m.path,m.metadata);return r.filter(m=>m.enabled)},"getEnabledResources"),a=P(r=>o(r).map(m=>m.path),"getEnabledPaths"),l=a(s.extensions),h=o(s.skills),g=a(s.prompts),x=a(s.themes),d=h.map(r=>this.mapSkillPath(r,e));for(const r of i.extensions)e.has(r.path)||e.set(r.path,{source:"cli",scope:"temporary",origin:"top-level"});for(const r of i.skills)e.has(r.path)||e.set(r.path,{source:"cli",scope:"temporary",origin:"top-level"});const u=a(i.extensions),E=a(i.skills),z=a(i.prompts),U=a(i.themes),G=(this.noExtensions?u:this.mergePaths(u,l)).filter(r=>!r.startsWith(k)||!this.disabledBuiltinExtensions.has(r.slice(k.length))),rt=st(G,e,{agentDir:this.agentDir,cwd:this.cwd}),O=await this.loadFinalExtensionSet(G,n);B(O,rt);for(const r of this.additionalExtensionPaths)if(j(r)){const m=this.resolveResourcePath(r);f(m)||O.errors.push({path:m,error:`Extension path does not exist: ${m}`})}this.extensionsResult=this.extensionsOverride?this.extensionsOverride(O):O,this.applyExtensionSourceInfo(this.extensionsResult.extensions,e);const D=p(ft(),"skills"),_=!this.noSkills&&f(D)?[D]:[];_.length>0&&!e.has(D)&&e.set(D,{source:"auto",scope:"user",origin:"top-level",baseDir:D});const Y=this.noSkills?this.mergePaths(E,this.additionalSkillPaths):this.mergePaths([...E,...d,..._],this.additionalSkillPaths);this.lastSkillPaths=Y,this.updateSkillsFromPaths(Y,e);for(const r of this.additionalSkillPaths)if(j(r)){const m=this.resolveResourcePath(r);!f(m)&&!this.skillDiagnostics.some(F=>F.path===m)&&this.skillDiagnostics.push({type:"error",message:"Skill path does not exist",path:m})}const H=this.noPromptTemplates?this.mergePaths(z,this.additionalPromptTemplatePaths):this.mergePaths([...z,...g],this.additionalPromptTemplatePaths);this.lastPromptPaths=H,this.updatePromptsFromPaths(H,e);for(const r of this.additionalPromptTemplatePaths)if(j(r)){const m=this.resolveResourcePath(r);!f(m)&&!this.promptDiagnostics.some(F=>F.path===m)&&this.promptDiagnostics.push({type:"error",message:"Prompt template path does not exist",path:m})}const J=this.noThemes?this.mergePaths(U,this.additionalThemePaths):this.mergePaths([...U,...x],this.additionalThemePaths);this.lastThemePaths=J,this.updateThemesFromPaths(J,e);for(const r of this.additionalThemePaths){const m=this.resolveResourcePath(r);!f(m)&&!this.themeDiagnostics.some(F=>F.path===m)&&this.themeDiagnostics.push({type:"error",message:"Theme path does not exist",path:m})}const K={agentsFiles:this.noContextFiles?[]:Bt({cwd:this.cwd,agentDir:this.agentDir})},ht=this.agentsFilesOverride?this.agentsFilesOverride(K):K;this.agentsFiles=ht.agentsFiles;const R=this.systemPromptSource??this.discoverSystemPromptFile(),X=at(R,S("\u7CFB\u7EDF\u63D0\u793A\u8BCD"));this.systemPrompt=this.systemPromptOverride?this.systemPromptOverride(X):X,this.systemPromptSourcePath=R&&f(R)?w(R):void 0;let C=this.appendSystemPromptSource;if(!C){const r=this.discoverAppendSystemPromptFile();C=r?[r]:[]}const q=C.map(r=>at(r,S("\u8FFD\u52A0\u7684\u7CFB\u7EDF\u63D0\u793A\u8BCD"))).filter(r=>r!==void 0);this.appendSystemPrompt=this.appendSystemPromptOverride?this.appendSystemPromptOverride(q):q,this.appendSystemPromptSourcePaths=C.filter(r=>f(r)).map(r=>w(r)),this.loaded=!0}async loadCurrentExtensionSet(t){const n=await this.packageManager.resolve(),s=await this.packageManager.resolveExtensionSources(this.additionalExtensionPaths,{temporary:!0}),i=n.extensions.filter(d=>d.enabled).map(d=>d.path),e=s.extensions.filter(d=>d.enabled).map(d=>d.path),o=(this.noExtensions?e:this.mergePaths(e,i)).filter(d=>!d.startsWith(k)),a=new Map([...n.extensions,...s.extensions].map(d=>[d.path,d.metadata])),l=st(o,a,{agentDir:this.agentDir,cwd:this.cwd}),h=await et(o,this.cwd,this.eventBus);if(B(h,l),!t.includeInlineFactories)return h;const g=await this.loadExtensionFactories(h.runtime);h.extensions.push(...g.extensions),h.errors.push(...g.errors);const x=[];return h.extensions=ot(h.extensions,x),B(h,x),h}resolveExtensionLoadPath(t){return N(t)?t:w(t,this.cwd,{normalizeUnicodeSpaces:!0})}async loadExtensionPaths(t,n){const s=P(e=>e.startsWith(k),"isBuiltinPath"),i=await et(t.filter(e=>!s(e)),this.cwd,this.eventBus,n);for(const e of t.filter(s)){const o=this.builtinExtensions.get(e.slice(k.length));if(!o){i.errors.push({path:e,error:`Unknown built-in extension: ${e}`});continue}try{const a=await tt(o.factory,this.cwd,this.eventBus,i.runtime,e);a.hidden=!0,a.replaceable=o.replaceable===!0,i.extensions.push(a)}catch(a){i.errors.push({path:e,error:a instanceof Error?a.message:"failed to load extension"})}}return i}async loadFinalExtensionSet(t,n){const s=n?.extensions??[],i=new Map(s.filter(u=>!u.path.startsWith("<inline:")).map(u=>[u.resolvedPath,u])),e=new Set((n?.errors??[]).map(u=>this.resolveExtensionLoadPath(u.path))),o=t.filter(u=>{const E=this.resolveExtensionLoadPath(u);return!i.has(E)&&!e.has(E)}),a=await this.loadExtensionPaths(o,n?.runtime),l=new Map(i);for(const u of a.extensions)l.set(u.resolvedPath,u);const h=n?{extensions:s.filter(u=>u.path.startsWith("<inline:")),errors:[]}:await this.loadExtensionFactories(a.runtime),g=t.map(u=>l.get(this.resolveExtensionLoadPath(u))).filter(u=>u!==void 0);g.push(...h.extensions);const x=[],d={extensions:ot(g,x),errors:[...n?.errors??[],...a.errors,...h.errors],warnings:[...n?.warnings??[],...a.warnings??[]],runtime:a.runtime};return B(d,x),this.addExtensionConflictDiagnostics(d),d}addExtensionConflictDiagnostics(t){const n=this.detectExtensionConflicts(t.extensions);for(const s of n)t.errors.push({path:s.path,error:s.message})}mapSkillPath(t,n){if(t.metadata.source!=="auto"&&t.metadata.origin!=="package")return t.path;try{if(!T(t.path).isDirectory())return t.path}catch{return t.path}const s=p(t.path,"SKILL.md");return f(s)?(n.has(s)||n.set(s,t.metadata),s):t.path}normalizeExtensionPaths(t){return t.map(n=>{const s=n.metadata.baseDir?{...n.metadata,baseDir:this.resolveResourcePath(n.metadata.baseDir)}:n.metadata;return{path:this.resolveResourcePath(n.path),metadata:s}})}updateSkillsFromPaths(t,n){let s;this.noSkills&&t.length===0?s={skills:[],diagnostics:[]}:s=It({cwd:this.cwd,agentDir:this.agentDir,skillPaths:t,includeDefaults:!1});const i=this.skillsOverride?this.skillsOverride(s):s;this.skills=i.skills.map(e=>({...e,sourceInfo:this.findSourceInfoForPath(e.filePath,this.extensionSkillSourceInfos,n)??e.sourceInfo??this.getDefaultSourceInfoForPath(e.filePath)})),this.skillDiagnostics=i.diagnostics}updatePromptsFromPaths(t,n){let s;if(this.noPromptTemplates&&t.length===0)s={prompts:[],diagnostics:[]};else{const e=bt({cwd:this.cwd,agentDir:this.agentDir,promptPaths:t,includeDefaults:!1}),o=this.dedupePrompts(e.templates);s={prompts:o.prompts,diagnostics:[...e.diagnostics,...o.diagnostics]}}const i=this.promptsOverride?this.promptsOverride(s):s;this.prompts=i.prompts.map(e=>({...e,sourceInfo:this.findSourceInfoForPath(e.filePath,this.extensionPromptSourceInfos,n)??e.sourceInfo??this.getDefaultSourceInfoForPath(e.filePath)})),this.promptDiagnostics=i.diagnostics}updateThemesFromPaths(t,n){let s;if(this.noThemes&&t.length===0)s={themes:[],diagnostics:[]};else{const e=dt({...pt(()=>!1),...this.settingsManager.getTerminalCapabilityOverrides()}),o=this.loadThemes(t,!1,e),a=this.dedupeThemes(o.themes);s={themes:a.themes,diagnostics:[...o.diagnostics,...a.diagnostics]}}const i=this.themesOverride?this.themesOverride(s):s;this.themes=i.themes.map(e=>{const o=e.sourcePath;return e.sourceInfo=o?this.findSourceInfoForPath(o,this.extensionThemeSourceInfos,n)??e.sourceInfo??this.getDefaultSourceInfoForPath(o):e.sourceInfo,e}),this.themeDiagnostics=i.diagnostics}applyExtensionSourceInfo(t,n){for(const s of t){s.sourceInfo=this.findSourceInfoForPath(s.path,void 0,n)??this.getDefaultSourceInfoForPath(s.path);for(const i of s.commands.values())i.sourceInfo=s.sourceInfo;for(const i of s.tools.values())i.sourceInfo=s.sourceInfo}}findSourceInfoForPath(t,n,s){if(!t)return;if(N(t))return this.getDefaultSourceInfoForPath(t);const i=y(t);if(n)for(const[e,o]of n.entries()){const a=y(e);if(i===a||i.startsWith(`${a}${b}`))return{...o,path:t}}if(s){const e=s.get(i)??s.get(t);if(e)return I(t,e);for(const[o,a]of s.entries()){const l=y(o);if(i===l||i.startsWith(`${l}${b}`))return I(t,a)}}}getDefaultSourceInfoForPath(t){const n=Ot(t);if(n)return{path:t,source:n,scope:"temporary",origin:"top-level"};const s=y(t),i=[p(this.agentDir,"skills"),p(this.agentDir,"prompts"),p(this.agentDir,"themes"),p(this.agentDir,"extensions")],e=[p(this.cwd,v,"skills"),p(this.cwd,v,"prompts"),p(this.cwd,v,"themes"),p(this.cwd,v,"extensions")];for(const o of i)if(this.isUnderPath(s,o))return{path:t,source:"local",scope:"user",origin:"top-level",baseDir:o};for(const o of e)if(this.isUnderPath(s,o))return{path:t,source:"local",scope:"project",origin:"top-level",baseDir:o};return{path:t,source:"local",scope:"temporary",origin:"top-level",baseDir:T(s).isDirectory()?s:y(s,"..")}}mergePaths(t,n){const s=[],i=new Set;for(const e of[...t,...n]){const o=this.resolveResourcePath(e),a=M(o);i.has(a)||(i.add(a),s.push(o))}return s}resolveResourcePath(t){return N(t)?t:w(t,this.cwd,{trim:!0})}loadThemes(t,n,s){const i=[],e=[];if(n){const o=[p(this.agentDir,"themes"),p(this.cwd,v,"themes")];for(const a of o)this.loadThemesFromDir(a,i,e,s)}for(const o of t){const a=this.resolveResourcePath(o);if(!f(a)){e.push({type:"warning",message:"theme path does not exist",path:a});continue}try{const l=T(a);l.isDirectory()?this.loadThemesFromDir(a,i,e,s):l.isFile()&&a.endsWith(".json")?this.loadThemeFromFile(a,i,e,s):e.push({type:"warning",message:"theme path is not a json file",path:a})}catch(l){const h=l instanceof Error?l.message:"failed to read theme path";e.push({type:"warning",message:h,path:a})}}return{themes:i,diagnostics:e}}loadThemesFromDir(t,n,s,i){if(f(t))try{const e=ct(t,{withFileTypes:!0});for(const o of e){let a=o.isFile();if(o.isSymbolicLink())try{a=T(p(t,o.name)).isFile()}catch{continue}a&&o.name.endsWith(".json")&&this.loadThemeFromFile(p(t,o.name),n,s,i)}}catch(e){const o=e instanceof Error?e.message:"failed to read theme directory";s.push({type:"warning",message:o,path:t})}}loadThemeFromFile(t,n,s,i){try{n.push(vt(t,i))}catch(e){const o=e instanceof Error?e.message:"failed to load theme";s.push({type:"warning",message:o,path:t})}}async loadExtensionFactories(t){const n=[],s=[];for(const[i,e]of this.extensionFactories.entries()){const o=typeof e!="function",a=o?e.factory:e,l=`<inline:${o?e.name:i+1}>`;try{const h=await tt(a,this.cwd,this.eventBus,t,l);h.hidden=o&&e.hidden,h.replaceable=o&&e.replaceable===!0,n.push(h)}catch(h){const g=h instanceof Error?h.message:"failed to load extension";s.push({path:l,error:g})}}return{extensions:n,errors:s}}dedupePrompts(t){const n=new Map,s=[];for(const i of t){const e=n.get(i.name);e?s.push({type:"collision",message:`name "/${i.name}" collision`,path:i.filePath,collision:{resourceType:"prompt",name:i.name,winnerPath:e.filePath,loserPath:i.filePath}}):n.set(i.name,i)}return{prompts:Array.from(n.values()),diagnostics:s}}dedupeThemes(t){const n=new Map,s=[];for(const i of t){const e=i.name??"unnamed",o=n.get(e);o?s.push({type:"collision",message:`name "${e}" collision`,path:i.sourcePath,collision:{resourceType:"theme",name:e,winnerPath:o.sourcePath??"<builtin>",loserPath:i.sourcePath??"<builtin>"}}):n.set(e,i)}return{themes:Array.from(n.values()),diagnostics:s}}discoverSystemPromptFile(){const t=p(this.cwd,v,"SYSTEM.md");if(this.settingsManager.isProjectTrusted()&&f(t))return t;const n=p(this.agentDir,"SYSTEM.md");if(f(n))return n}discoverAppendSystemPromptFile(){const t=p(this.cwd,v,"APPEND_SYSTEM.md");if(this.settingsManager.isProjectTrusted()&&f(t))return t;const n=p(this.agentDir,"APPEND_SYSTEM.md");if(f(n))return n}isUnderPath(t,n){const s=y(n);if(t===s)return!0;const i=s.endsWith(b)?s:`${s}${b}`;return t.startsWith(i)}detectExtensionConflicts(t){const n=[],s=new Map,i=new Map;for(const e of t){for(const o of e.tools.keys()){const a=s.get(o);a&&a!==e.path?n.push({path:e.path,message:`Tool "${o}" conflicts with ${a}`}):s.set(o,e.path)}for(const o of e.flags.keys()){const a=i.get(o);a&&a!==e.path?n.push({path:e.path,message:`Flag "--${o}" conflicts with ${a}`}):i.set(o,e.path)}}return n}}export{ie as DefaultResourceLoader,it as isBuiltinExtension,Bt as loadProjectContextFiles};
@@ -1,28 +1,29 @@
1
- var v=Object.defineProperty;var c=(e,t)=>v(e,"name",{value:t,configurable:!0});import{join as P}from"node:path";import{getSystemMessageText as j}from"@earendil-works/pi-ai";import{APP_NAME as E,APP_TITLE as p,getDalDocsPath as $,getDocsPath as T,getExamplesPath as O,getReadmePath as _,IS_WHITE_LABEL_BUILD as I}from"../config.js";import{describeGitState as N}from"./git-state.js";import{INJECTED_CONTEXT_TAG as A}from"./messages.js";import{describeProjectFacts as D}from"./project-facts.js";import{formatSkillsForPrompt as F}from"./skills.js";const M=/^[a-z][a-z0-9_-]*$/;function R(e){return{customPrompt:e.customPrompt,forceSystemPrompt:e.forceSystemPrompt,selectedTools:[...e.selectedTools??["read","bash","edit","write"]],hiddenTools:[...e.hiddenTools??[]],toolSnippets:{...e.toolSnippets??{}},toolGuidelines:Object.fromEntries(Object.entries(e.toolGuidelines??{}).map(([t,n])=>[t,[...n]])),promptGuidelines:[...e.promptGuidelines??[]],appendSystemPrompt:e.appendSystemPrompt??"",sections:{...e.sections??{}},cwd:e.cwd,gitState:e.gitState,projectFacts:e.projectFacts,contextFiles:(e.contextFiles??[]).map(t=>({...t})),skills:(e.skills??[]).map(t=>({...t}))}}c(R,"normalizeBuildSystemPromptOptions");function C(e){return["Project-specific instructions and guidelines:",...e.map(({path:t,content:n})=>`<project_instructions path="${t}">
1
+ var v=Object.defineProperty;var c=(e,t)=>v(e,"name",{value:t,configurable:!0});import{join as P}from"node:path";import{getSystemMessageText as j}from"@earendil-works/pi-ai";import{APP_NAME as E,APP_TITLE as p,getDalDocsPath as $,getDocsPath as T,getExamplesPath as O,getReadmePath as _,IS_WHITE_LABEL_BUILD as I}from"../config.js";import{describeGitState as N}from"./git-state.js";import{INJECTED_CONTEXT_TAG as A}from"./messages.js";import{describeProjectFacts as R}from"./project-facts.js";import{formatSkillsForPrompt as D}from"./skills.js";const F=/^[a-z][a-z0-9_-]*$/;function M(e){return{customPrompt:e.customPrompt,forceSystemPrompt:e.forceSystemPrompt,selectedTools:[...e.selectedTools??["read","bash","edit","write"]],hiddenTools:[...e.hiddenTools??[]],toolSnippets:{...e.toolSnippets??{}},toolGuidelines:Object.fromEntries(Object.entries(e.toolGuidelines??{}).map(([t,n])=>[t,[...n]])),promptGuidelines:[...e.promptGuidelines??[]],appendSystemPrompt:e.appendSystemPrompt??"",sections:{...e.sections??{}},cwd:e.cwd,gitState:e.gitState,projectFacts:e.projectFacts,contextFiles:(e.contextFiles??[]).map(t=>({...t})),skills:(e.skills??[]).map(t=>({...t}))}}c(M,"normalizeBuildSystemPromptOptions");function C(e){return["Project-specific instructions and guidelines:",...e.map(({path:t,content:n})=>`<project_instructions path="${t}">
2
2
  ${n}
3
3
  </project_instructions>`)].join(`
4
4
 
5
- `)}c(C,"renderProjectContext");function G(e,t,n){const r=[],d=new Set,s=c(l=>{const m=l.trim();!m||d.has(m)||(d.add(m),r.push(m))},"addRule"),h=e.includes("bash"),f=e.includes("powershell"),a=e.includes("grep"),u=e.includes("find"),y=e.includes("ls");(h||f)&&!a&&!u&&!y&&s(h&&f?"Use bash or PowerShell for file operations like listing, searching, and finding files":f?"Use PowerShell for file operations like listing, searching, and finding files":"Use bash for file operations like ls, rg, find");for(const l of e)for(const m of t[l]??[])s(m);for(const l of n)s(l);return e.length>0&&(s("When several tool calls do not depend on each other's results (reading multiple files, independent searches or commands), make them all in one response; they run in parallel. Each extra round trip costs the user seconds"),s("Answer as soon as you can: once you know enough, give the answer or your best current conclusion, then offer to dig further. Do not investigate everything before saying anything"),s("During longer work, tell the user every few tool rounds, in a sentence or two, what you found and what you will check next"),s("If you cannot tell which product, project or file the user means, ask instead of searching widely on a guess. When the user writes while you are working, respond to that message first: it may change the direction"),s("In a small project, read every source file the task touches in one response (parallel reads, or one command that prints them) instead of exploring one file per round"),s("Verify the behaviours the request names and the edge cases it implies; do not write exhaustive or randomized test sweeps unless asked"),s("Before reporting done, run every code path you added at least once, including backward-compatibility, fallback and error branches: a branch that never ran is not verified"),s("If the request's premise does not match what the code, data or tests show (the reported bug is absent, the named text is already correct), say so with the evidence and do not change anything just to satisfy the request; ask how to proceed or stop"),s("When a protection refuses a call, stop that step and tell the user why; never reach the same data another way (a copy, another tool or path)"),s(`Adapt instructions written for another agent before following or delegating them; drop what conflicts with your protections. You are ${p}: co-author trailer "Co-Authored-By: ${p} <noreply@deepailab.ai>", never Claude, Codex or Copilot`),s("Before calling a multi-part task done, match each part to its evidence and name what is not done or partly done; a load check is not a review")),s(`Text inside <${A} type="..."> tags comes from ${p} itself, not from the user: follow its instructions, but do not mistake it for the user's request or reply to it as if the user had written it`),s("Be concise in your responses"),s("Show file paths clearly when working with files"),r.map(l=>`- ${l}`).join(`
6
- `)}c(G,"buildRules");function B(e){const t=R(e),{customPrompt:n,selectedTools:r,hiddenTools:d,toolSnippets:s,toolGuidelines:h,promptGuidelines:f,appendSystemPrompt:a,sections:u,cwd:y,contextFiles:l,skills:m}=t;for(const o of Object.keys(u))if(!M.test(o)||o==="preamble")throw new Error(`Invalid system prompt section name: ${o}`);const b=r.filter(o=>!d.includes(o)),i={};if(n)i.preamble=n;else{i.preamble=`You are an expert coding assistant operating inside ${p} (${E}). You help users by reading files, executing commands, editing code, and writing new files.`;const o=b.filter(w=>!!s[w]),g=o.length>0?o.map(w=>`- ${w}: ${s[w]}`).join(`
5
+ `)}c(C,"renderProjectContext");function G(e,t,n){const r=[],d=new Set,o=c(l=>{const m=l.trim();!m||d.has(m)||(d.add(m),r.push(m))},"addRule"),h=e.includes("bash"),f=e.includes("powershell"),a=e.includes("grep"),u=e.includes("find"),y=e.includes("ls");(h||f)&&!a&&!u&&!y&&o(h&&f?"Use bash or PowerShell for file operations like listing, searching, and finding files":f?"Use PowerShell for file operations like listing, searching, and finding files":"Use bash for file operations like ls, rg, find");for(const l of e)for(const m of t[l]??[])o(m);for(const l of n)o(l);return e.length>0&&(o("When several tool calls do not depend on each other's results (reading multiple files, independent searches or commands), make them all in one response; they run in parallel. Each extra round trip costs the user seconds"),o("Answer as soon as you can: once you know enough, give the answer or your best current conclusion, then offer to dig further. Do not investigate everything before saying anything"),o("During longer work, tell the user every few tool rounds, in a sentence or two, what you found and what you will check next"),o("If you cannot tell which product, project or file the user means, ask instead of searching widely on a guess. When the user writes while you are working, respond to that message first: it may change the direction"),o("In a small project, read every source file the task touches in one response (parallel reads, or one command that prints them) instead of exploring one file per round"),o("Verify the behaviours the request names and the edge cases it implies, within a few minutes; do not write exhaustive or randomized test sweeps or repeated stress runs unless asked"),o("Before reporting done, run every code path you added at least once, including backward-compatibility, fallback and error branches: a branch that never ran is not verified"),o("Reproduce a reported bug before changing code. If it does not reproduce, or the premise does not match what the code, data or tests show, report the evidence and stop without editing product code, whatever a loaded skill assumes"),o("When a protection refuses a call, stop that step and tell the user why; never reach the same data another way (a copy, another tool or path)"),o(`Adapt instructions written for another agent before following or delegating them; drop what conflicts with your protections. You are ${p}: co-author trailer "Co-Authored-By: ${p} <noreply@deepailab.ai>", never Claude, Codex or Copilot`),o("Before calling a multi-part task done, match each part to its evidence and name what is not done or partly done; a load check is not a review")),o(`Text inside <${A} type="..."> tags comes from ${p} itself, not from the user: follow its instructions, but do not mistake it for the user's request or reply to it as if the user had written it`),o("Reply in the language of the user's latest message, whatever language tool results, skills or injected notices use"),o("Be concise in your responses"),o("Show file paths clearly when working with files"),r.map(l=>`- ${l}`).join(`
6
+ `)}c(G,"buildRules");function B(e){const t=M(e),{customPrompt:n,selectedTools:r,hiddenTools:d,toolSnippets:o,toolGuidelines:h,promptGuidelines:f,appendSystemPrompt:a,sections:u,cwd:y,contextFiles:l,skills:m}=t;for(const s of Object.keys(u))if(!F.test(s)||s==="preamble")throw new Error(`Invalid system prompt section name: ${s}`);const b=r.filter(s=>!d.includes(s)),i={};if(n)i.preamble=n;else{i.preamble=`You are an expert coding assistant operating inside ${p} (${E}). You help users by reading files, executing commands, editing code, and writing new files.`;const s=b.filter(w=>!!o[w]),g=s.length>0?s.map(w=>`- ${w}: ${o[w]}`).join(`
7
7
  `):"(none)";i.tools=`${g}
8
8
 
9
- In addition to the tools above, you may have access to other custom tools depending on the project.`,i.rules=G(b,h,f),i.docs=z()}a&&(i.addendum=a),l.length>0&&(i.project_context=C(l));const k=["read","bash"],S=k.find(o=>b.includes(o))??(k.some(o=>r.includes(o))?"indirect":void 0);if(S&&m.length>0){const o=F(m,S).trim();o&&(i.skills=o)}if(i.cwd=y.replace(/\\/g,"/"),t.gitState&&!u.git_state&&(i.git=N(y)),t.projectFacts&&!u.project){const o=D(y);o&&(i.project=o)}for(const[o,g]of Object.entries(u))g&&(i[o]=g);const x={preamble:i.preamble};for(const[o,g]of Object.entries(i))o!=="preamble"&&(x[o]=`<${o}>
9
+ In addition to the tools above, you may have access to other custom tools depending on the project.`,i.rules=G(b,h,f),i.docs=z()}a&&(i.addendum=a),l.length>0&&(i.project_context=C(l));const k=["read","bash"],S=k.find(s=>b.includes(s))??(k.some(s=>r.includes(s))?"indirect":void 0);if(S&&m.length>0){const s=D(m,S).trim();s&&(i.skills=s)}if(i.cwd=y.replace(/\\/g,"/"),t.gitState&&!u.git_state&&(i.git=N(y)),t.projectFacts&&!u.project){const s=R(y);s&&(i.project=s)}for(const[s,g]of Object.entries(u))g&&(i[s]=g);const x={preamble:i.preamble};for(const[s,g]of Object.entries(i))s!=="preamble"&&(x[s]=`<${s}>
10
10
  ${g}
11
- </${o}>`);return x}c(B,"buildSystemPromptSections");const L="cwd",U="Environment of this session, part of the system prompt. Later updates to these sections arrive as system prompt updates.";function Z(e){const t=e[0];if(!t||t.role!=="system"||!t.sections)return e;const n=Object.keys(t.sections),r=n.indexOf(L);if(r===-1)return e;const d=n.slice(r).map(a=>t.sections?.[a]).filter(a=>typeof a=="string"&&a.length>0),s=Object.fromEntries(n.slice(0,r).map(a=>[a,t.sections?.[a]??null])),h={...t,sections:s};if(d.length===0)return[h,...e.slice(1)];const f={role:"user",content:[{type:"text",text:`<session_environment>
12
- ${U}
11
+ </${s}>`);return x}c(B,"buildSystemPromptSections");const L="cwd",W="Environment of this session, part of the system prompt. Later updates to these sections arrive as system prompt updates.";function Z(e){const t=e[0];if(!t||t.role!=="system"||!t.sections)return e;const n=Object.keys(t.sections),r=n.indexOf(L);if(r===-1)return e;const d=n.slice(r).map(a=>t.sections?.[a]).filter(a=>typeof a=="string"&&a.length>0),o=Object.fromEntries(n.slice(0,r).map(a=>[a,t.sections?.[a]??null])),h={...t,sections:o};if(d.length===0)return[h,...e.slice(1)];const f={role:"user",content:[{type:"text",text:`<session_environment>
12
+ ${W}
13
13
 
14
14
  ${d.join(`
15
15
 
16
16
  `)}
17
- </session_environment>`}],timestamp:t.timestamp};return[h,f,...e.slice(1)]}c(Z,"moveSessionEnvironmentOutOfSystemPrompt");function W(e){return e.forceSystemPrompt!==void 0?{content:e.forceSystemPrompt}:{content:"",sections:B(e)}}c(W,"buildSystemPromptState");function ee(e){return j({role:"system",...W(e),timestamp:0})}c(ee,"buildSystemPrompt");function te(e,t){const n={};for(const[r,d]of Object.entries(t))e[r]!==d&&(n[r]=d);for(const r of Object.keys(e))t[r]===void 0&&(n[r]=null);return Object.keys(n).length>0?n:void 0}c(te,"diffSystemPromptSections");function z(){if(I){const e=$();return`${p} documentation (read only when the user asks about ${p} itself: its commands, settings, skills, prompt templates, extensions, packages, themes or keybindings):
17
+ </session_environment>`}],timestamp:t.timestamp};return[h,f,...e.slice(1)]}c(Z,"moveSessionEnvironmentOutOfSystemPrompt");function U(e){return e.forceSystemPrompt!==void 0?{content:e.forceSystemPrompt}:{content:"",sections:B(e)}}c(U,"buildSystemPromptState");function ee(e){return j({role:"system",...U(e),timestamp:0})}c(ee,"buildSystemPrompt");function te(e,t){const n={};for(const[r,d]of Object.entries(t))e[r]!==d&&(n[r]=d);for(const r of Object.keys(e))t[r]===void 0&&(n[r]=null);return Object.keys(n).length>0?n:void 0}c(te,"diffSystemPromptSections");function z(){if(I){const e=$();return`${p} documentation (read only when the user asks about ${p} itself: its commands, settings, skills, prompt templates, extensions, packages, themes or keybindings):
18
18
  - Start with: ${P(e,"README.md")}
19
19
  - Topics, in the same folder: skills.md, prompt-templates.md, extensions.md, packages.md, themes.md, keybindings.md, settings.md
20
20
  - Resolve those file names under ${e}, not the current working directory
21
- - Read the relevant file completely before answering or implementing, and describe the product as ${p}`}return`${p} documentation (read only when the user asks about ${p} itself, its SDK, extensions, themes, skills, or TUI):
21
+ - Read the relevant file completely before answering or implementing, and describe the product as ${p}
22
+ - To write an extension, follow "Writing one for the user" in extensions.md`}return`${p} documentation (read only when the user asks about ${p} itself, its SDK, extensions, themes, skills, or TUI):
22
23
  - Main documentation: ${_()}
23
24
  - Additional docs: ${T()}
24
25
  - Examples: ${O()} (extensions, custom tools, SDK)
25
26
  - When reading these docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory
26
27
  - When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), packages (docs/packages.md), environment variables (docs/environment-variables.md), MCP servers (docs/mcp.md), codemode scripts and non-LLM models such as classifiers and image models (docs/codemode.md)
27
28
  - When working on these topics, read the docs and examples, and follow .md cross-references before implementing
28
- - Always read these .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`}c(z,"buildDocumentationSection");export{L as SESSION_ENVIRONMENT_FIRST_SECTION,ee as buildSystemPrompt,B as buildSystemPromptSections,W as buildSystemPromptState,te as diffSystemPromptSections,Z as moveSessionEnvironmentOutOfSystemPrompt,R as normalizeBuildSystemPromptOptions};
29
+ - Always read these .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`}c(z,"buildDocumentationSection");export{L as SESSION_ENVIRONMENT_FIRST_SECTION,ee as buildSystemPrompt,B as buildSystemPromptSections,U as buildSystemPromptState,te as diffSystemPromptSections,Z as moveSessionEnvironmentOutOfSystemPrompt,M as normalizeBuildSystemPromptOptions};
@@ -1,19 +1,20 @@
1
- var _e=Object.defineProperty;var r=(t,e)=>_e(t,"name",{value:e,configurable:!0});import{constants as ye}from"node:fs";import{access as ge}from"node:fs/promises";import{constants as $e}from"node:os";import{ToolExecutionError as Le}from"@earendil-works/pi-agent-core";import{Container as Ce,Text as G,truncateToWidth as Te}from"@earendil-works/pi-tui";import{spawn as Pe}from"child_process";import{Type as d}from"typebox";import{fill as R,t as I}from"../../dal/i18n.js";import{keyHint as Ie}from"../../modes/interactive/components/keybinding-hints.js";import{truncateToVisualLines as ve}from"../../modes/interactive/components/visual-truncate.js";import{theme as x}from"../../modes/interactive/theme/theme.js";import{waitForChildProcess as De}from"../../utils/child-process.js";import{writeOutputFile as Ae}from"../../utils/output-files.js";import{getShellConfig as ae,getShellEnv as de,killProcessTree as le,trackDetachedChildPid as ke,untrackDetachedChildPid as Fe}from"../../utils/shell.js";import{describeDenialForModel as Me}from"../sandbox/denial.js";import{getProcessShellSandbox as Ne}from"../sandbox/shell-sandbox.js";import{isReadOnlyBashCommand as Be}from"./bash-read-only.js";import{OutputAccumulator as Re}from"./output-accumulator.js";import{condenseShellOutput as Ue,outputCondenseDisabled as je}from"./output-condense.js";import{countOutputLines as Ge,formatCollapsedSummary as We,getTextOutput as ue,invalidArgText as He,str as ce,truncateDisplay as Ve}from"./render-utils.js";import{wrapToolDefinition as Xe}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as Ye,formatSize as Ke,SHELL_OUTPUT_MAX_CHARS as ee,truncateHeadTail as qe}from"./truncate.js";const me=2147483647,pe=1024*1024,ze=8*1024*1024,Je=me/1e3,te=12e4,ne=30;function Qe(t){if(t===void 0)return te;if(!Number.isFinite(t)||t<=0)throw new Error("Invalid timeout: must be a finite number of seconds");const e=t*1e3;if(e>me)throw new Error(`Invalid timeout: maximum is ${Je} seconds`);return e}r(Qe,"resolveTimeoutMs");const fe=d.Object({command:d.String({description:"Shell command to execute"}),description:d.String({description:`What it does and why, 3-10 words in the user's language, shown instead of the command: "Find hardcoded key names", not "run grep"`}),timeout:d.Optional(d.Number({description:"Seconds to wait for the command (default in the tool description). Raise it for long builds."}))}),Ze=d.Optional(d.Object({mode:d.Union([d.Literal("allow"),d.Literal("unsandboxed")],{description:'"allow": stay sandboxed with the domains/paths below; "unsandboxed": run outside the sandbox'}),justification:d.String({description:"Why, in one sentence for the user, who must approve it"}),allow_domains:d.Optional(d.Array(d.String(),{description:"e.g. registry.npmjs.org"})),allow_write:d.Optional(d.Array(d.String(),{description:"Paths to make writable"}))},{description:"Only after the sandbox blocked this command: the access it needs. Never pre-emptively."})),et=d.Object({...fe.properties,sandbox_escalation:Ze}),he={snippet:"Execute bash commands (ls, grep, find, etc.)",guidelines:["You can inspect DAL_* environment variables for current model and session details."]},tt=d.Object({output:d.String({description:"Combined stdout and stderr, possibly truncated"}),truncated:d.Boolean(),full_output_path:d.Optional(d.String({description:"Full output, when truncated"})),exit_code:d.Number({description:"-1 while the command runs in the background"}),background_id:d.Optional(d.String({description:"Background process id, when it is still running"})),wall_time_seconds:d.Number()});function nt(t,e){return{exec:r(async(n,o,{onData:l,signal:i,timeout:_,env:w,yieldTo:s})=>{const y=Qe(_);if(i?.aborted)throw new Error("aborted");const S=e();try{await ge(o,ye.F_OK)}catch{throw new Error(`Working directory does not exist: ${o}
2
- Cannot execute ${t} commands.`)}const b=S.commandTransport==="stdin",u=Pe(S.shell,b?S.args:[...S.args,n],{cwd:o,detached:process.platform!=="win32",env:w??de(),stdio:[b?"pipe":"ignore","pipe","pipe"],windowsHide:!0});b&&(u.stdin?.on("error",()=>{}),u.stdin?.end(n)),u.pid&&ke(u.pid);let a=!1,m=!1,h;const p=new Promise(A=>{h=r(()=>A("yielded"),"onYielded")});let f;const O=r(()=>{u.pid&&le(u.pid)},"onAbort");try{y!==void 0&&(f=setTimeout(()=>{if(s&&u.exitCode===null&&u.signalCode===null&&s(u)){m=!0,h?.();return}a=!0,u.pid&&le(u.pid)},y)),u.stdout?.on("data",l),u.stderr?.on("data",l),i&&(i.aborted?O():i.addEventListener("abort",O,{once:!0}));const A=De(u),U=await Promise.race([A,p]);if(U==="yielded")return A.catch(()=>{}),{exitCode:null,yielded:!0};const V=U;if(i?.aborted)throw new Error("aborted");if(a)throw new Error(`timeout:${(y??te)/1e3}`);const $=u.signalCode;return{exitCode:V??($?128+($e.signals[$]??0):1)}}finally{u.pid&&!m&&Fe(u.pid),f&&clearTimeout(f),i&&i.removeEventListener("abort",O)}},"exec")}}r(nt,"createLocalShellOperations");function ot(t){return nt("bash",()=>ae(t?.shellPath))}r(ot,"createLocalBashOperations");const oe=new Set;function Ut(t){return oe.add(t),()=>{oe.delete(t)}}r(Ut,"registerShellExecutionGuard");async function it(t){for(const e of oe){let n;try{n=await e(t)}catch(o){return`Command refused: the safety check could not run (${o instanceof Error?o.message:String(o)}).`}if(n!==void 0)return n}}r(it,"shellExecutionRefusal");const st=["SESSION_ID","SESSION_FILE","PROVIDER","MODEL","REASONING_LEVEL"];function rt(t,e,n,o,l){const i={...de()};if(delete i.PI_SESSION_ID,delete i.PI_SESSION_FILE,delete i.PI_PROVIDER,delete i.PI_MODEL,delete i.PI_REASONING_LEVEL,o&&l){const w=l.model;i.PI_SESSION_ID=l.sessionManager.getSessionId();const s=l.sessionManager.getSessionFile();s&&(i.PI_SESSION_FILE=s),w&&(i.PI_PROVIDER=w.provider,i.PI_MODEL=w.id),l.thinkingLevel&&(i.PI_REASONING_LEVEL=l.thinkingLevel)}for(const w of st){delete i[`DAL_${w}`];const s=i[`PI_${w}`];s!==void 0&&(i[`DAL_${w}`]=s)}const _={command:t,cwd:e,env:i};return n?n(_):_}r(rt,"resolveSpawnContext");const at=5,dt=100;class lt extends Ce{static{r(this,"BashResultRenderComponent")}state={cachedWidth:void 0,cachedLines:void 0,cachedSkipped:void 0}}function ut(t){const e=t/1e3;if(e<60)return`${e.toFixed(1)}s`;const n=Math.floor(e),o=Math.floor(n/60),l=n%60;return o<60?`${o}m ${l}s`:`${Math.floor(o/60)}h ${o%60}m ${l}s`}r(ut,"formatDuration");function ct(t,e,n=!1){const o=ce(t?.command),l=ce(t?.description)?.trim(),i=t?.timeout,_=i?x.fg("muted",R(I(" (\u8D85\u65F6 {seconds} \u79D2)"),{seconds:i})):"";if(l){const s=x.fg("toolTitle",x.bold(l))+_;return!n||!o?s:`${s}
3
- ${x.fg("muted",` \u23BF ${e} ${o.trim()}`)}`}const w=o===null?He(x):o?x.fg("dim",Ve(o.replace(/\s+/g," ").trim(),42)):x.fg("dim","\u2026");return`${x.fg("toolTitle",x.bold(e))} ${w}${_}`}r(ct,"formatShellCall");function mt(t,e,n,o,l,i,_,w){const s=t.state;t.clear();const y=pt(n,l,i,w);if(!n.expanded&&!_){const a=ue(e,o),m=Ge(a),h=[];m>0&&h.push(R(I("{count} \u884C"),{count:m})),y&&h.push(y);const p=We(x,h);p&&t.addChild(new G(p,0,0));return}let S=ue(e,o).trim();const b=e.details?.truncation,u=e.details?.fullOutputPath;if(!n.isPartial&&b?.truncated&&u&&S.endsWith("]")){const a=S.lastIndexOf(`
1
+ var _e=Object.defineProperty;var r=(t,e)=>_e(t,"name",{value:e,configurable:!0});import{constants as ye}from"node:fs";import{access as ge}from"node:fs/promises";import{constants as $e}from"node:os";import{ToolExecutionError as Le}from"@earendil-works/pi-agent-core";import{Container as Ce,Text as G,truncateToWidth as Te}from"@earendil-works/pi-tui";import{spawn as Pe}from"child_process";import{Type as l}from"typebox";import{fill as U,t as I}from"../../dal/i18n.js";import{keyHint as Ie}from"../../modes/interactive/components/keybinding-hints.js";import{truncateToVisualLines as ve}from"../../modes/interactive/components/visual-truncate.js";import{theme as x}from"../../modes/interactive/theme/theme.js";import{waitForChildProcess as De}from"../../utils/child-process.js";import{writeOutputFile as Ae}from"../../utils/output-files.js";import{getShellConfig as ae,getShellEnv as de,killProcessTree as le,trackDetachedChildPid as ke,untrackDetachedChildPid as Me}from"../../utils/shell.js";import{missingManagedToolHint as Fe}from"../../utils/tools-manager.js";import{describeDenialForModel as Ne}from"../sandbox/denial.js";import{getProcessShellSandbox as Be}from"../sandbox/shell-sandbox.js";import{isReadOnlyBashCommand as Re}from"./bash-read-only.js";import{OutputAccumulator as Ue}from"./output-accumulator.js";import{condenseShellOutput as He,outputCondenseDisabled as je}from"./output-condense.js";import{countOutputLines as Ge,formatCollapsedSummary as We,getTextOutput as ue,invalidArgText as Ve,str as ce,truncateDisplay as Xe}from"./render-utils.js";import{wrapToolDefinition as Ye}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as Ke,formatSize as qe,SHELL_OUTPUT_MAX_CHARS as ee,truncateHeadTail as ze}from"./truncate.js";const me=2147483647,pe=1024*1024,Je=8*1024*1024,Qe=me/1e3,te=12e4,ne=30;function Ze(t){if(t===void 0)return te;if(!Number.isFinite(t)||t<=0)throw new Error("Invalid timeout: must be a finite number of seconds");const e=t*1e3;if(e>me)throw new Error(`Invalid timeout: maximum is ${Qe} seconds`);return e}r(Ze,"resolveTimeoutMs");const fe=l.Object({command:l.String({description:"Shell command to execute"}),description:l.String({description:`What it does and why, 3-10 words in the user's language, shown instead of the command: "Find hardcoded key names", not "run grep"`}),timeout:l.Optional(l.Number({description:"Seconds to wait for the command (default in the tool description). Raise it for long builds."}))}),et=l.Optional(l.Object({mode:l.Union([l.Literal("allow"),l.Literal("unsandboxed")],{description:'"allow": stay sandboxed with the domains/paths below; "unsandboxed": run outside the sandbox'}),justification:l.String({description:"Why, in one sentence for the user, who must approve it"}),allow_domains:l.Optional(l.Array(l.String(),{description:"e.g. registry.npmjs.org"})),allow_write:l.Optional(l.Array(l.String(),{description:"Paths to make writable"}))},{description:"Only after the sandbox blocked this command: the access it needs. Never pre-emptively."})),tt=l.Object({...fe.properties,sandbox_escalation:et}),he={snippet:"Execute bash commands (ls, grep, find, etc.)",guidelines:["You can inspect DAL_* environment variables for current model and session details."]},nt=l.Object({output:l.String({description:"Combined stdout and stderr, possibly truncated"}),truncated:l.Boolean(),full_output_path:l.Optional(l.String({description:"Full output, when truncated"})),exit_code:l.Number({description:"-1 while the command runs in the background"}),background_id:l.Optional(l.String({description:"Background process id, when it is still running"})),wall_time_seconds:l.Number()});function ot(t,e){return{exec:r(async(n,o,{onData:u,signal:i,timeout:g,env:w,yieldTo:s})=>{const $=Ze(g);if(i?.aborted)throw new Error("aborted");const S=e();try{await ge(o,ye.F_OK)}catch{throw new Error(`Working directory does not exist: ${o}
2
+ Cannot execute ${t} commands.`)}const b=S.commandTransport==="stdin",c=Pe(S.shell,b?S.args:[...S.args,n],{cwd:o,detached:process.platform!=="win32",env:w??de(),stdio:[b?"pipe":"ignore","pipe","pipe"],windowsHide:!0});b&&(c.stdin?.on("error",()=>{}),c.stdin?.end(n)),c.pid&&ke(c.pid);let a=!1,m=!1,h;const p=new Promise(A=>{h=r(()=>A("yielded"),"onYielded")});let f;const O=r(()=>{c.pid&&le(c.pid)},"onAbort");try{$!==void 0&&(f=setTimeout(()=>{if(s&&c.exitCode===null&&c.signalCode===null&&s(c)){m=!0,h?.();return}a=!0,c.pid&&le(c.pid)},$)),c.stdout?.on("data",u),c.stderr?.on("data",u),i&&(i.aborted?O():i.addEventListener("abort",O,{once:!0}));const A=De(c),H=await Promise.race([A,p]);if(H==="yielded")return A.catch(()=>{}),{exitCode:null,yielded:!0};const V=H;if(i?.aborted)throw new Error("aborted");if(a)throw new Error(`timeout:${($??te)/1e3}`);const L=c.signalCode;return{exitCode:V??(L?128+($e.signals[L]??0):1)}}finally{c.pid&&!m&&Me(c.pid),f&&clearTimeout(f),i&&i.removeEventListener("abort",O)}},"exec")}}r(ot,"createLocalShellOperations");function it(t){return ot("bash",()=>ae(t?.shellPath))}r(it,"createLocalBashOperations");const oe=new Set;function jt(t){return oe.add(t),()=>{oe.delete(t)}}r(jt,"registerShellExecutionGuard");async function st(t){for(const e of oe){let n;try{n=await e(t)}catch(o){return`Command refused: the safety check could not run (${o instanceof Error?o.message:String(o)}).`}if(n!==void 0)return n}}r(st,"shellExecutionRefusal");const rt=["SESSION_ID","SESSION_FILE","PROVIDER","MODEL","REASONING_LEVEL"];function at(t,e,n,o,u){const i={...de()};if(delete i.PI_SESSION_ID,delete i.PI_SESSION_FILE,delete i.PI_PROVIDER,delete i.PI_MODEL,delete i.PI_REASONING_LEVEL,o&&u){const w=u.model;i.PI_SESSION_ID=u.sessionManager.getSessionId();const s=u.sessionManager.getSessionFile();s&&(i.PI_SESSION_FILE=s),w&&(i.PI_PROVIDER=w.provider,i.PI_MODEL=w.id),u.thinkingLevel&&(i.PI_REASONING_LEVEL=u.thinkingLevel)}for(const w of rt){delete i[`DAL_${w}`];const s=i[`PI_${w}`];s!==void 0&&(i[`DAL_${w}`]=s)}const g={command:t,cwd:e,env:i};return n?n(g):g}r(at,"resolveSpawnContext");const dt=5,lt=100;class ut extends Ce{static{r(this,"BashResultRenderComponent")}state={cachedWidth:void 0,cachedLines:void 0,cachedSkipped:void 0}}function ct(t){const e=t/1e3;if(e<60)return`${e.toFixed(1)}s`;const n=Math.floor(e),o=Math.floor(n/60),u=n%60;return o<60?`${o}m ${u}s`:`${Math.floor(o/60)}h ${o%60}m ${u}s`}r(ct,"formatDuration");function mt(t,e,n=!1){const o=ce(t?.command),u=ce(t?.description)?.trim(),i=t?.timeout,g=i?x.fg("muted",U(I(" (\u8D85\u65F6 {seconds} \u79D2)"),{seconds:i})):"";if(u){const s=x.fg("toolTitle",x.bold(u))+g;return!n||!o?s:`${s}
3
+ ${x.fg("muted",` \u23BF ${e} ${o.trim()}`)}`}const w=o===null?Ve(x):o?x.fg("dim",Xe(o.replace(/\s+/g," ").trim(),42)):x.fg("dim","\u2026");return`${x.fg("toolTitle",x.bold(e))} ${w}${g}`}r(mt,"formatShellCall");function pt(t,e,n,o,u,i,g,w){const s=t.state;t.clear();const $=ft(n,u,i,w);if(!n.expanded&&!g){const a=ue(e,o),m=Ge(a),h=[];m>0&&h.push(U(I("{count} \u884C"),{count:m})),$&&h.push($);const p=We(x,h);p&&t.addChild(new G(p,0,0));return}let S=ue(e,o).trim();const b=e.details?.truncation,c=e.details?.fullOutputPath;if(!n.isPartial&&b?.truncated&&c&&S.endsWith("]")){const a=S.lastIndexOf(`
4
4
 
5
- [`);a!==-1&&S.slice(a).includes(u)&&(S=S.slice(0,a).trimEnd())}if(S){const a=S.split(`
5
+ [`);a!==-1&&S.slice(a).includes(c)&&(S=S.slice(0,a).trimEnd())}if(S){const a=S.split(`
6
6
  `).map(m=>x.fg("toolOutput",m)).join(`
7
7
  `);n.expanded?t.addChild(new G(`
8
- ${a}`,0,0)):t.addChild({render:r(m=>{if(s.cachedLines===void 0||s.cachedWidth!==m){const h=ve(a,at,m);s.cachedLines=h.visualLines,s.cachedSkipped=h.skippedCount,s.cachedWidth=m}if(s.cachedSkipped&&s.cachedSkipped>0){const h=x.fg("muted",R(I("... (\u524D\u9762\u8FD8\u6709 {count} \u884C\uFF0C"),{count:s.cachedSkipped}))+` ${Ie("app.tools.expand",I("\u5373\u53EF\u5C55\u5F00"))}${x.fg("muted",")")}`;return["",Te(h,m,"..."),...s.cachedLines??[]]}return["",...s.cachedLines??[]]},"render"),invalidate:r(()=>{s.cachedWidth=void 0,s.cachedLines=void 0,s.cachedSkipped=void 0},"invalidate")})}if(b?.truncated||u){const a=[];u&&a.push(R(I("\u5B8C\u6574\u8F93\u51FA\uFF1A{path}"),{path:u})),b?.truncated&&(b.truncatedBy==="lines"?a.push(R(I("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A {shown}/{total} \u884C"),{shown:b.outputLines,total:b.totalLines})):a.push(R(I("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A\u4E86 {shown} \u884C\uFF08\u4E0A\u9650 {limit}\uFF09"),{shown:b.outputLines,limit:Ke(b.maxBytes??Ye)}))),t.addChild(new G(`
9
- ${x.fg("warning",`[${a.join(". ")}]`)}`,0,0))}y&&t.addChild(new G(`
10
- ${x.fg("muted",y)}`,0,0))}r(mt,"rebuildBashResultRenderComponent");function pt(t,e,n,o){let l;if(!t.isPartial&&o!==void 0)l=o;else if(e!==void 0)l=(n??Date.now())-e;else return;if(!(!t.isPartial&&l<100))return`${t.isPartial?I("\u5DF2\u8FD0\u884C"):I("\u8017\u65F6")} ${ut(l)}`}r(pt,"bashTimingLabel");function ft(t,e,n){const o=n?.operations??e.defaultOperations?.()??ot({shellPath:n?.shellPath}),l=n?.commandPrefix,i=n?.exposeSessionEnvironment??!0,_=n?.spawnHook,w=n?.sandbox,s=n?.operations===void 0,y=w?.describeForModel(),S=n?.background;let b=!1;const u=r(a=>`Execute a ${e.shellName} command in the current working directory; returns stdout and stderr. Long output is cut to its start and end (error lines kept) and the full output saved to a file named in the result. ${a?`A command still running after \`timeout\` seconds (default ${ne}) keeps running in the background: you get its id and the output so far, then use the process tool to poll or kill it.`:`A command still running after \`timeout\` seconds (default ${te/1e3}) is killed.`}${y?` ${y}`:""}`,"describe");return{name:e.name,label:e.label,description:u(!1),prepareLoadout:S&&s?a=>(b=a.declared.some(m=>m.name==="process"),b?{descriptions:{[e.name]:u(!0)}}:void 0):void 0,promptSnippet:e.promptSnippet,promptGuidelines:i&&e.promptGuidelines?[...e.promptGuidelines]:void 0,executionMode:"sequential",executionModeFor:e.readOnlyCommand&&!l?a=>e.readOnlyCommand?.(a?.command)?"parallel":void 0:void 0,parameters:w?.active?et:fe,outputSchema:tt,constrainedSampling:{type:"json_schema",strict:"prefer"},async execute(a,m,h,p,f){const{command:O,timeout:A}=m;p&&p({content:[],details:void 0});const U=await it({toolName:e.name,command:O,cwd:f?.cwd||t,sessionFile:f?.sessionManager?.getSessionFile()});if(U!==void 0)throw new Error(U);const V=l?`${l}
11
- ${O}`:O,$=rt(V,f?.cwd||t,_,i,f),X=w??(s?Ne():void 0);let L;if(X?.active){if(!e.sandboxShell)throw new Error(`Command refused: ${e.shellName} commands cannot run inside the OS sandbox yet, and the sandbox level is "${X.level}". Use the bash tool, or the user can opt out with \`dal --sandbox off\`.`);L=await X.prepare({command:$.command,cwd:$.cwd,shell:e.sandboxShell(n?.shellPath),shellKind:e.sandboxShellKind??"bash",env:$.env,toolCallId:a,toolName:e.name,escalation:m.sandbox_escalation,ctx:f,signal:h})}const T=new Re({tempFilePrefix:e.tempFilePrefix,maxBytes:ee});let W=!0,j,Y=!1,ie=0;const K=r(()=>{if(!p||!Y)return;Y=!1,ie=Date.now();const c=T.snapshot({persistIfTruncated:!0});p({content:[{type:"text",text:c.content||""}],details:{truncation:c.truncation.truncated?c.truncation:void 0,fullOutputPath:c.fullOutputPath}})},"emitOutputUpdate"),q=r(()=>{j&&(clearTimeout(j),j=void 0)},"clearUpdateTimer"),we=r(()=>{if(!p)return;Y=!0;const c=dt-(Date.now()-ie);if(c<=0){q(),K();return}j??=setTimeout(()=>{j=void 0,K()},c)},"scheduleOutputUpdate"),Se=r(c=>{W&&(T.append(c),we())},"handleData"),be=r(async()=>{W=!1,T.finish(),q(),K();const c=T.snapshot({persistIfTruncated:!0});return await T.closeTempFile(),c},"finishOutput"),z=r(async(c="(no output)")=>{const g=await be(),k=await T.readFullOutput(ze),C=je()?void 0:Ue(k.content),E=qe(C?.text??k.content,ee);let D=g.fullOutputPath;(E.truncated||C)&&!D&&(D=await Ae(e.tempFilePrefix,".log",k.content));let F=E.content||c,N;const B=g.truncation.totalLines;return E.truncated?(N={truncation:{content:E.content,truncated:!0,truncatedBy:"bytes",totalLines:B,totalBytes:g.truncation.totalBytes,outputLines:E.headLines+E.tailLines,outputBytes:Buffer.byteLength(E.content,"utf-8"),lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:B,maxBytes:ee},fullOutputPath:D},F+=`
8
+ ${a}`,0,0)):t.addChild({render:r(m=>{if(s.cachedLines===void 0||s.cachedWidth!==m){const h=ve(a,dt,m);s.cachedLines=h.visualLines,s.cachedSkipped=h.skippedCount,s.cachedWidth=m}if(s.cachedSkipped&&s.cachedSkipped>0){const h=x.fg("muted",U(I("... (\u524D\u9762\u8FD8\u6709 {count} \u884C\uFF0C"),{count:s.cachedSkipped}))+` ${Ie("app.tools.expand",I("\u5373\u53EF\u5C55\u5F00"))}${x.fg("muted",")")}`;return["",Te(h,m,"..."),...s.cachedLines??[]]}return["",...s.cachedLines??[]]},"render"),invalidate:r(()=>{s.cachedWidth=void 0,s.cachedLines=void 0,s.cachedSkipped=void 0},"invalidate")})}if(b?.truncated||c){const a=[];c&&a.push(U(I("\u5B8C\u6574\u8F93\u51FA\uFF1A{path}"),{path:c})),b?.truncated&&(b.truncatedBy==="lines"?a.push(U(I("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A {shown}/{total} \u884C"),{shown:b.outputLines,total:b.totalLines})):a.push(U(I("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A\u4E86 {shown} \u884C\uFF08\u4E0A\u9650 {limit}\uFF09"),{shown:b.outputLines,limit:qe(b.maxBytes??Ke)}))),t.addChild(new G(`
9
+ ${x.fg("warning",`[${a.join(". ")}]`)}`,0,0))}$&&t.addChild(new G(`
10
+ ${x.fg("muted",$)}`,0,0))}r(pt,"rebuildBashResultRenderComponent");function ft(t,e,n,o){let u;if(!t.isPartial&&o!==void 0)u=o;else if(e!==void 0)u=(n??Date.now())-e;else return;if(!(!t.isPartial&&u<100))return`${t.isPartial?I("\u5DF2\u8FD0\u884C"):I("\u8017\u65F6")} ${ct(u)}`}r(ft,"bashTimingLabel");function ht(t,e,n){const o=n?.operations??e.defaultOperations?.()??it({shellPath:n?.shellPath}),u=n?.commandPrefix,i=n?.exposeSessionEnvironment??!0,g=n?.spawnHook,w=n?.sandbox,s=n?.operations===void 0,$=w?.describeForModel(),S=n?.background;let b=!1;const c=r(a=>`Execute a ${e.shellName} command in the current working directory; returns stdout and stderr. Long output is cut to its start and end (error lines kept) and the full output saved to a file named in the result. ${a?`A command still running after \`timeout\` seconds (default ${ne}) keeps running in the background: you get its id and the output so far, then use the process tool to poll or kill it.`:`A command still running after \`timeout\` seconds (default ${te/1e3}) is killed.`}${$?` ${$}`:""}`,"describe");return{name:e.name,label:e.label,description:c(!1),prepareLoadout:S&&s?a=>(b=a.declared.some(m=>m.name==="process"),b?{descriptions:{[e.name]:c(!0)}}:void 0):void 0,promptSnippet:e.promptSnippet,promptGuidelines:i&&e.promptGuidelines?[...e.promptGuidelines]:void 0,executionMode:"sequential",executionModeFor:e.readOnlyCommand&&!u?a=>e.readOnlyCommand?.(a?.command)?"parallel":void 0:void 0,parameters:w?.active?tt:fe,outputSchema:nt,constrainedSampling:{type:"json_schema",strict:"prefer"},async execute(a,m,h,p,f){const{command:O,timeout:A}=m;p&&p({content:[],details:void 0});const H=await st({toolName:e.name,command:O,cwd:f?.cwd||t,sessionFile:f?.sessionManager?.getSessionFile()});if(H!==void 0)throw new Error(H);const V=u?`${u}
11
+ ${O}`:O,L=at(V,f?.cwd||t,g,i,f),X=w??(s?Be():void 0);let C;if(X?.active){if(!e.sandboxShell)throw new Error(`Command refused: ${e.shellName} commands cannot run inside the OS sandbox yet, and the sandbox level is "${X.level}". Use the bash tool, or the user can opt out with \`dal --sandbox off\`.`);C=await X.prepare({command:L.command,cwd:L.cwd,shell:e.sandboxShell(n?.shellPath),shellKind:e.sandboxShellKind??"bash",env:L.env,toolCallId:a,toolName:e.name,escalation:m.sandbox_escalation,ctx:f,signal:h})}const P=new Ue({tempFilePrefix:e.tempFilePrefix,maxBytes:ee});let W=!0,j,Y=!1,ie=0;const K=r(()=>{if(!p||!Y)return;Y=!1,ie=Date.now();const d=P.snapshot({persistIfTruncated:!0});p({content:[{type:"text",text:d.content||""}],details:{truncation:d.truncation.truncated?d.truncation:void 0,fullOutputPath:d.fullOutputPath}})},"emitOutputUpdate"),q=r(()=>{j&&(clearTimeout(j),j=void 0)},"clearUpdateTimer"),we=r(()=>{if(!p)return;Y=!0;const d=lt-(Date.now()-ie);if(d<=0){q(),K();return}j??=setTimeout(()=>{j=void 0,K()},d)},"scheduleOutputUpdate"),Se=r(d=>{W&&(P.append(d),we())},"handleData"),be=r(async()=>{W=!1,P.finish(),q(),K();const d=P.snapshot({persistIfTruncated:!0});return await P.closeTempFile(),d},"finishOutput"),z=r(async(d="(no output)")=>{const _=await be(),k=await P.readFullOutput(Je),T=je()?void 0:He(k.content),E=ze(T?.text??k.content,ee);let D=_.fullOutputPath;(E.truncated||T)&&!D&&(D=await Ae(e.tempFilePrefix,".log",k.content));let M=E.content||d,B;const R=_.truncation.totalLines;return E.truncated?(B={truncation:{content:E.content,truncated:!0,truncatedBy:"bytes",totalLines:R,totalBytes:_.truncation.totalBytes,outputLines:E.headLines+E.tailLines,outputBytes:Buffer.byteLength(E.content,"utf-8"),lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:R,maxBytes:ee},fullOutputPath:D},M+=`
12
12
 
13
- [Truncated: first ${E.headLines} and last ${E.tailLines} of ${E.totalLines} lines shown${C?`, after condensing ${B} lines (${C.summary})`:""}; read more with read (offset/limit) or grep. Full output: ${D}]`):C&&(N={fullOutputPath:D},F+=`
13
+ [Truncated: first ${E.headLines} and last ${E.tailLines} of ${E.totalLines} lines shown${T?`, after condensing ${R} lines (${T.summary})`:""}; read more with read (offset/limit) or grep. Full output: ${D}]`):T&&(B={fullOutputPath:D},M+=`
14
14
 
15
- [Condensed: ${C.summary}. Full output: ${D}]`),{text:F,details:N,snapshot:g}},"modelOutput"),M=r((c,g)=>`${c?`${c}
15
+ [Condensed: ${T.summary}. Full output: ${D}]`),{text:M,details:B,snapshot:_}},"modelOutput"),N=r((d,_)=>`${d?`${d}
16
16
 
17
- `:""}${g}`,"appendStatus"),se=performance.now();let v;const J=S&&s&&b?c=>{W=!1;try{return v=S.adopt({child:c,command:O,cwd:$.cwd,...L?{prepared:L}:{},...T.handOff()}),!0}catch{return W=!0,!1}}:void 0;try{let c;try{const P=await o.exec(L?.command??$.command,$.cwd,{onData:Se,signal:h,timeout:A??(J?ne:void 0),env:$.env,...J?{yieldTo:J}:{}});if(P.yielded&&v){const{text:H,details:Z}=await z(""),xe=A??ne,Ee=v.urls.length>0?` It printed ${v.urls.join(" ")}.`:"",Oe=`[Still running after ${xe}s, now in the background as ${v.id}.${Ee} For new output and the exit code call process with action "poll" and id "${v.id}"; "kill" stops it.]`,re=await T.readFullOutput(pe);return{content:[{type:"text",text:M(H,Oe)}],details:{...Z,background:v},structuredContent:{output:re.content,truncated:re.truncated,exit_code:-1,background_id:v.id,wall_time_seconds:Math.round((performance.now()-se)/100)/10}}}c=P.exitCode}catch(P){const{text:H}=await z("");if(await L?.finish(null,""),P instanceof Error&&P.message==="aborted")throw new Error(M(H,"Command aborted"));if(P instanceof Error&&P.message.startsWith("timeout:")){const Z=P.message.split(":")[1];throw new Error(M(H,`Command timed out after ${Z} seconds`))}throw P}const{text:g,details:k,snapshot:C}=await z(),E=await L?.finish(c,C.content||"");if(E&&L)throw new Le(`${M(g,`Command exited with code ${c??"(none)"}`)}
17
+ `:""}${_}`,"appendStatus"),se=performance.now();let v;const J=S&&s&&b?d=>{W=!1;try{return v=S.adopt({child:d,command:O,cwd:L.cwd,...C?{prepared:C}:{},...P.handOff()}),!0}catch{return W=!0,!1}}:void 0;try{let d;try{const y=await o.exec(C?.command??L.command,L.cwd,{onData:Se,signal:h,timeout:A??(J?ne:void 0),env:L.env,...J?{yieldTo:J}:{}});if(y.yielded&&v){const{text:F,details:Z}=await z(""),xe=A??ne,Ee=v.urls.length>0?` It printed ${v.urls.join(" ")}.`:"",Oe=`[Still running after ${xe}s, now in the background as ${v.id}.${Ee} For new output and the exit code call process with action "poll" and id "${v.id}"; "kill" stops it.]`,re=await P.readFullOutput(pe);return{content:[{type:"text",text:N(F,Oe)}],details:{...Z,background:v},structuredContent:{output:re.content,truncated:re.truncated,exit_code:-1,background_id:v.id,wall_time_seconds:Math.round((performance.now()-se)/100)/10}}}d=y.exitCode}catch(y){const{text:F}=await z("");if(await C?.finish(null,""),y instanceof Error&&y.message==="aborted")throw new Error(N(F,"Command aborted"));if(y instanceof Error&&y.message.startsWith("timeout:")){const Z=y.message.split(":")[1];throw new Error(N(F,`Command timed out after ${Z} seconds`))}throw y}const{text:_,details:k,snapshot:T}=await z(),E=await C?.finish(d,T.content||"");if(E&&C)throw new Le(`${N(_,`Command exited with code ${d??"(none)"}`)}
18
18
 
19
- ${Me(E)}`,{...k,sandbox:L.details});if(c===null)throw new Error(M(g,"Command terminated without an exit code"));const D=Math.round((performance.now()-se)/100)/10,F=await T.readFullOutput(pe),N={output:F.content,truncated:F.truncated,...F.truncated&&C.fullOutputPath?{full_output_path:C.fullOutputPath}:{},exit_code:c,wall_time_seconds:D},B=L?.details.escalation?L.details:void 0,Q=B?{...k,sandbox:B}:k;return c!==0?{content:[{type:"text",text:M(g,`Command exited with code ${c}`)}],details:Q,structuredContent:N,isError:!0}:{content:[{type:"text",text:g}],details:Q,structuredContent:N}}finally{q()}},renderCall(a,m,h){const p=h.state;h.executionStarted&&p.startedAt===void 0&&(p.startedAt=Date.now(),p.endedAt=void 0);const f=h.lastComponent??new G("",0,0);return f.setText(ct(a,e.prompt,h.expanded===!0)),f},renderResult(a,m,h,p){const f=p.state;f.startedAt!==void 0&&m.isPartial&&!f.interval&&(f.interval=setInterval(()=>p.invalidate(),1e3)),(!m.isPartial||p.isError)&&(f.endedAt??=Date.now(),f.interval&&(clearInterval(f.interval),f.interval=void 0));const O=p.lastComponent??new lt;return mt(O,a,m,p.showImages,f.startedAt,f.endedAt,p.isError,p.durationMs),O.invalidate(),O}}}r(ft,"createShellToolDefinition");const ht={name:"bash",label:"bash",shellName:"bash",prompt:"$",promptSnippet:he.snippet,promptGuidelines:he.guidelines,tempFilePrefix:"dal-bash",readOnlyCommand:Be,sandboxShell:r(t=>ae(t).shell,"sandboxShell")};function wt(t,e){return ft(t,ht,e)}r(wt,"createBashToolDefinition");function jt(t,e){const n=wt(t,e),o=Xe(n);return Object.assign(o,{promptSnippet:n.promptSnippet,promptGuidelines:n.promptGuidelines}),o}r(jt,"createBashTool");export{he as bashToolSystemPromptContribution,jt as createBashTool,wt as createBashToolDefinition,ot as createLocalBashOperations,nt as createLocalShellOperations,ft as createShellToolDefinition,Ut as registerShellExecutionGuard,Ze as sandboxEscalationSchema};
19
+ ${Ne(E)}`,{...k,sandbox:C.details});if(d===null)throw new Error(N(_,"Command terminated without an exit code"));const D=Math.round((performance.now()-se)/100)/10,M=await P.readFullOutput(pe),B={output:M.content,truncated:M.truncated,...M.truncated&&T.fullOutputPath?{full_output_path:T.fullOutputPath}:{},exit_code:d,wall_time_seconds:D},R=C?.details.escalation?C.details:void 0,Q=R?{...k,sandbox:R}:k;if(d!==0){const y=d===127?await Fe(_):void 0,F=N(_,`Command exited with code ${d}`);return{content:[{type:"text",text:y?`${F}
20
+ ${y}`:F}],details:Q,structuredContent:B,isError:!0}}return{content:[{type:"text",text:_}],details:Q,structuredContent:B}}finally{q()}},renderCall(a,m,h){const p=h.state;h.executionStarted&&p.startedAt===void 0&&(p.startedAt=Date.now(),p.endedAt=void 0);const f=h.lastComponent??new G("",0,0);return f.setText(mt(a,e.prompt,h.expanded===!0)),f},renderResult(a,m,h,p){const f=p.state;f.startedAt!==void 0&&m.isPartial&&!f.interval&&(f.interval=setInterval(()=>p.invalidate(),1e3)),(!m.isPartial||p.isError)&&(f.endedAt??=Date.now(),f.interval&&(clearInterval(f.interval),f.interval=void 0));const O=p.lastComponent??new ut;return pt(O,a,m,p.showImages,f.startedAt,f.endedAt,p.isError,p.durationMs),O.invalidate(),O}}}r(ht,"createShellToolDefinition");const wt={name:"bash",label:"bash",shellName:"bash",prompt:"$",promptSnippet:he.snippet,promptGuidelines:he.guidelines,tempFilePrefix:"dal-bash",readOnlyCommand:Re,sandboxShell:r(t=>ae(t).shell,"sandboxShell")};function St(t,e){return ht(t,wt,e)}r(St,"createBashToolDefinition");function Gt(t,e){const n=St(t,e),o=Ye(n);return Object.assign(o,{promptSnippet:n.promptSnippet,promptGuidelines:n.promptGuidelines}),o}r(Gt,"createBashTool");export{he as bashToolSystemPromptContribution,Gt as createBashTool,St as createBashToolDefinition,it as createLocalBashOperations,ot as createLocalShellOperations,ht as createShellToolDefinition,jt as registerShellExecutionGuard,et as sandboxEscalationSchema};
@@ -0,0 +1,5 @@
1
+ export declare function pathExists(filePath: string): Promise<boolean>;
2
+ export declare function expandPath(filePath: string): string;
3
+ export declare function resolveToCwd(filePath: string, cwd: string): string;
4
+ export declare function resolveReadPath(filePath: string, cwd: string): string;
5
+ export declare function resolveReadPathAsync(filePath: string, cwd: string): Promise<string>;
@@ -13,7 +13,9 @@ export interface ProcessToolDetails {
13
13
  process?: BackgroundProcessInfo;
14
14
  processes?: BackgroundProcessInfo[];
15
15
  }
16
+ export declare const POLL_BUDGET_SECONDS = 180;
16
17
  export declare function createProcessToolDefinition(cwd: string, manager: BackgroundProcessManager, options?: {
17
18
  sandboxed?: boolean;
19
+ pollBudgetSeconds?: number;
18
20
  }): ToolDefinition<typeof processSchema, ProcessToolDetails | undefined>;
19
21
  export {};