dal-code 1.0.38 → 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 (320) hide show
  1. package/CHANGELOG.md +87 -0
  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/dal-docs/settings.md +1 -1
  23. package/dist/cli/args.d.ts +3 -0
  24. package/dist/cli/args.js +17 -17
  25. package/dist/config.d.ts +1 -0
  26. package/dist/config.js +1 -1
  27. package/dist/core/agent-session.js +6 -6
  28. package/dist/core/compaction/compaction.js +31 -13
  29. package/dist/core/extensions/loader.js +1 -1
  30. package/dist/core/extensions/permission-surface.js +1 -1
  31. package/dist/core/extensions/runner.js +1 -1
  32. package/dist/core/extensions/types.d.ts +15 -1
  33. package/dist/core/model-registry.d.ts +1 -0
  34. package/dist/core/model-registry.js +1 -1
  35. package/dist/core/nested-tool-calls.js +2 -2
  36. package/dist/core/permissions/tool-policy.js +1 -1
  37. package/dist/core/project-facts.d.ts +16 -0
  38. package/dist/core/project-facts.js +2 -0
  39. package/dist/core/resource-loader.js +1 -1
  40. package/dist/core/sandbox/policy.js +1 -1
  41. package/dist/core/sandbox/windows.js +1 -1
  42. package/dist/core/system-prompt.d.ts +1 -0
  43. package/dist/core/system-prompt.js +13 -12
  44. package/dist/core/tools/bash.js +13 -12
  45. package/dist/core/tools/path-utils.d.ts +5 -0
  46. package/dist/core/tools/process.d.ts +2 -0
  47. package/dist/core/tools/process.js +14 -13
  48. package/dist/core/workspace-lock.d.ts +29 -0
  49. package/dist/core/workspace-lock.js +3 -0
  50. package/dist/dal/extension-compat.d.ts +62 -0
  51. package/dist/dal/extension-compat.js +4 -0
  52. package/dist/dal/hooks/extension.js +2 -2
  53. package/dist/dal/i18n.js +1 -1
  54. package/dist/dal/manifest.js +1 -1
  55. package/dist/dal/reviewed/endorsed-cli.js +1 -1
  56. package/dist/dal/reviewed/endorsed.js +1 -1
  57. package/dist/dal/reviewed/market-keys.js +1 -0
  58. package/dist/dal/reviewed/market.d.ts +64 -0
  59. package/dist/dal/reviewed/market.js +2 -0
  60. package/dist/extensions/mcp/runtime.d.ts +2 -1
  61. package/dist/extensions/mcp/runtime.js +3 -3
  62. package/dist/extensions/mcp/runtime.lazy.d.ts +1 -0
  63. package/dist/index.d.ts +9 -1
  64. package/dist/index.js +1 -1
  65. package/dist/main.js +4 -4
  66. package/dist/modes/acp/acp-mode.js +1 -1
  67. package/dist/modes/interactive/interactive-mode.d.ts +1 -0
  68. package/dist/modes/interactive/interactive-mode.js +14 -14
  69. package/dist/modes/print-mode.js +3 -3
  70. package/dist/modes/rpc/rpc-mode.js +1 -1
  71. package/dist/node_modules/@dalcode/dal-advisor/LICENSE +45 -0
  72. package/dist/node_modules/@dalcode/dal-advisor/package.json +35 -0
  73. package/dist/node_modules/@dalcode/dal-advisor/src/index.js +22 -0
  74. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  75. package/dist/node_modules/@dalcode/dal-bridge/src/ask-user.js +1 -1
  76. package/dist/node_modules/@dalcode/dal-capabilities/LICENSE +21 -0
  77. package/dist/node_modules/@dalcode/dal-capabilities/package.json +38 -0
  78. package/dist/node_modules/@dalcode/dal-capabilities/src/catalogue.js +1 -0
  79. package/dist/node_modules/@dalcode/dal-capabilities/src/index.js +11 -0
  80. package/dist/node_modules/@dalcode/dal-capabilities/src/install.js +4 -0
  81. package/dist/node_modules/@dalcode/dal-capabilities/src/match.js +1 -0
  82. package/dist/node_modules/@dalcode/dal-capabilities/src/state.js +3 -0
  83. package/dist/node_modules/@dalcode/dal-compat/LICENSE +21 -0
  84. package/dist/node_modules/@dalcode/dal-compat/package.json +32 -0
  85. package/dist/node_modules/@dalcode/dal-compat/src/claude-rules.js +3 -0
  86. package/dist/node_modules/@dalcode/dal-compat/src/index.js +7 -0
  87. package/dist/node_modules/@dalcode/dal-dap/LICENSE +47 -0
  88. package/dist/node_modules/@dalcode/dal-dap/package.json +38 -0
  89. package/dist/node_modules/@dalcode/dal-dap/src/adapters.js +1 -0
  90. package/dist/node_modules/@dalcode/dal-dap/src/client.js +5 -0
  91. package/dist/node_modules/@dalcode/dal-dap/src/index.js +9 -0
  92. package/dist/node_modules/@dalcode/dal-dap/src/install.js +2 -0
  93. package/dist/node_modules/@dalcode/dal-dap/src/session.js +2 -0
  94. package/dist/node_modules/@dalcode/dal-dap/src/types.js +0 -0
  95. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  96. package/dist/node_modules/@dalcode/dal-goal/package.json +4 -3
  97. package/dist/node_modules/@dalcode/dal-goal/src/core.js +6 -6
  98. package/dist/node_modules/@dalcode/dal-goal/src/index.js +17 -7
  99. package/dist/node_modules/@dalcode/dal-goal/src/verify.js +26 -0
  100. package/dist/node_modules/@dalcode/dal-guard/package.json +6 -4
  101. package/dist/node_modules/@dalcode/dal-guard/src/attribution.js +1 -0
  102. package/dist/node_modules/@dalcode/dal-guard/src/credentials.js +1 -1
  103. package/dist/node_modules/@dalcode/dal-guard/src/edit-anchor-core.js +23 -0
  104. package/dist/node_modules/@dalcode/dal-guard/src/edit-anchor.js +4 -0
  105. package/dist/node_modules/@dalcode/dal-guard/src/index.js +1 -1
  106. package/dist/node_modules/@dalcode/dal-guard/src/package-manager.js +1 -0
  107. package/dist/node_modules/@dalcode/dal-guard/src/workspace.js +2 -0
  108. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  109. package/dist/node_modules/@dalcode/dal-interactive/LICENSE +209 -0
  110. package/dist/node_modules/@dalcode/dal-interactive/package.json +4 -3
  111. package/dist/node_modules/@dalcode/dal-interactive/src/btw.js +25 -0
  112. package/dist/node_modules/@dalcode/dal-interactive/src/index.js +1 -1
  113. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  114. package/dist/node_modules/@dalcode/dal-learn/LICENSE +21 -0
  115. package/dist/node_modules/@dalcode/dal-learn/package.json +35 -0
  116. package/dist/node_modules/@dalcode/dal-learn/src/engine.js +8 -0
  117. package/dist/node_modules/@dalcode/dal-learn/src/extract.js +14 -0
  118. package/dist/node_modules/@dalcode/dal-learn/src/index.js +17 -0
  119. package/dist/node_modules/@dalcode/dal-learn/src/lessons.js +3 -0
  120. package/dist/node_modules/@dalcode/dal-learn/src/migrate.js +1 -0
  121. package/dist/node_modules/@dalcode/dal-learn/src/procedures.js +11 -0
  122. package/dist/node_modules/@dalcode/dal-learn/src/project-map.js +2 -0
  123. package/dist/node_modules/@dalcode/dal-learn/src/project.js +1 -0
  124. package/dist/node_modules/@dalcode/dal-learn/src/safety.js +2 -0
  125. package/dist/node_modules/@dalcode/dal-learn/src/signals.js +5 -0
  126. package/dist/node_modules/@dalcode/dal-learn/src/skill-actions.js +1 -0
  127. package/dist/node_modules/@dalcode/dal-learn/src/skill-evolution.js +16 -0
  128. package/dist/node_modules/@dalcode/dal-learn/src/store.js +2 -0
  129. package/dist/node_modules/@dalcode/dal-lsp/package.json +6 -4
  130. package/dist/node_modules/@dalcode/dal-lsp/src/client.js +3 -3
  131. package/dist/node_modules/@dalcode/dal-lsp/src/config.js +1 -1
  132. package/dist/node_modules/@dalcode/dal-lsp/src/format.js +8 -7
  133. package/dist/node_modules/@dalcode/dal-lsp/src/index.js +11 -8
  134. package/dist/node_modules/@dalcode/dal-mcp/package.json +6 -5
  135. package/dist/node_modules/@dalcode/dal-mcp/src/config.d.ts +1 -0
  136. package/dist/node_modules/@dalcode/dal-mcp/src/config.js +1 -1
  137. package/dist/node_modules/@dalcode/dal-mcp/src/http-client.d.ts +32 -1
  138. package/dist/node_modules/@dalcode/dal-mcp/src/http-client.js +2 -1
  139. package/dist/node_modules/@dalcode/dal-mcp/src/index.js +16 -16
  140. package/dist/node_modules/@dalcode/dal-mcp/src/oauth.js +2 -0
  141. package/dist/node_modules/@dalcode/dal-mcp/src/stdio-client.d.ts +4 -2
  142. package/dist/node_modules/@dalcode/dal-mcp/src/stdio-client.js +4 -4
  143. package/dist/node_modules/@dalcode/dal-mcp/src/types.d.ts +9 -0
  144. package/dist/node_modules/@dalcode/dal-mcp/src/types.js +1 -1
  145. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  146. package/dist/node_modules/@dalcode/dal-office/src/index.d.ts +6 -3
  147. package/dist/node_modules/@dalcode/dal-office/src/index.js +1 -1
  148. package/dist/node_modules/@dalcode/dal-office/src/render/chart-theme.d.ts +13 -0
  149. package/dist/node_modules/@dalcode/dal-office/src/render/chart-theme.js +1 -0
  150. package/dist/node_modules/@dalcode/dal-office/src/render/chart.d.ts +16 -0
  151. package/dist/node_modules/@dalcode/dal-office/src/render/chart.js +4 -2
  152. package/dist/node_modules/@dalcode/dal-office/src/render/docx.d.ts +4 -1
  153. package/dist/node_modules/@dalcode/dal-office/src/render/docx.js +1 -1
  154. package/dist/node_modules/@dalcode/dal-office/src/render/drawio-style.d.ts +4 -0
  155. package/dist/node_modules/@dalcode/dal-office/src/render/drawio-style.js +1 -0
  156. package/dist/node_modules/@dalcode/dal-office/src/render/pptx.d.ts +52 -4
  157. package/dist/node_modules/@dalcode/dal-office/src/render/pptx.js +3 -2
  158. package/dist/node_modules/@dalcode/dal-office/src/render/thumbnails.d.ts +1 -1
  159. package/dist/node_modules/@dalcode/dal-office/src/render/thumbnails.js +1 -1
  160. package/dist/node_modules/@dalcode/dal-office/src/render/xlsx.d.ts +1 -0
  161. package/dist/node_modules/@dalcode/dal-office/src/render/xlsx.js +1 -1
  162. package/dist/node_modules/@dalcode/dal-office/src/scratchpad.d.ts +30 -1
  163. package/dist/node_modules/@dalcode/dal-office/src/scratchpad.js +1 -1
  164. package/dist/node_modules/@dalcode/dal-office/src/themes.d.ts +35 -1
  165. package/dist/node_modules/@dalcode/dal-office/src/themes.js +1 -1
  166. package/dist/node_modules/@dalcode/dal-office/src/tools/chart-generate.js +3 -3
  167. package/dist/node_modules/@dalcode/dal-office/src/tools/doc-generate.js +2 -2
  168. package/dist/node_modules/@dalcode/dal-office/src/tools/drawio-generate.js +3 -3
  169. package/dist/node_modules/@dalcode/dal-office/src/tools/ppt-generate.js +2 -2
  170. package/dist/node_modules/@dalcode/dal-office/src/tools/ppt-plan.js +2 -2
  171. package/dist/node_modules/@dalcode/dal-office/src/tools/sheet-generate.js +2 -2
  172. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +5 -3
  173. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  174. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +5 -3
  175. package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -5
  176. package/dist/node_modules/@dalcode/dal-plugins/src/index.js +11 -11
  177. package/dist/node_modules/@dalcode/dal-plugins/src/manage.js +8 -10
  178. package/dist/node_modules/@dalcode/dal-plugins/src/npm-hook.js +1 -1
  179. package/dist/node_modules/@dalcode/dal-plugins/src/registry.js +2 -2
  180. package/dist/node_modules/@dalcode/dal-recall/LICENSE +45 -0
  181. package/dist/node_modules/@dalcode/dal-recall/package.json +34 -0
  182. package/dist/node_modules/@dalcode/dal-recall/src/index-db.js +57 -0
  183. package/dist/node_modules/@dalcode/dal-recall/src/index.js +1 -0
  184. package/dist/node_modules/@dalcode/dal-recall/src/query.js +1 -0
  185. package/dist/node_modules/@dalcode/dal-recall/src/redact.js +1 -0
  186. package/dist/node_modules/@dalcode/dal-recall/src/sqlite.js +1 -0
  187. package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
  188. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  189. package/dist/node_modules/@dalcode/dal-rewind/src/commands.js +2 -2
  190. package/dist/node_modules/@dalcode/dal-rewind/src/core.d.ts +21 -8
  191. package/dist/node_modules/@dalcode/dal-rewind/src/core.js +8 -3
  192. package/dist/node_modules/@dalcode/dal-rewind/src/index.js +1 -1
  193. package/dist/node_modules/@dalcode/dal-rewind/src/state.js +1 -1
  194. package/dist/node_modules/@dalcode/dal-router/package.json +7 -5
  195. package/dist/node_modules/@dalcode/dal-router/src/advisor.js +1 -0
  196. package/dist/node_modules/@dalcode/dal-router/src/assist.js +4 -2
  197. package/dist/node_modules/@dalcode/dal-router/src/commands.js +8 -8
  198. package/dist/node_modules/@dalcode/dal-router/src/config.d.ts +5 -0
  199. package/dist/node_modules/@dalcode/dal-router/src/config.js +2 -2
  200. package/dist/node_modules/@dalcode/dal-router/src/index.js +4 -4
  201. package/dist/node_modules/@dalcode/dal-router/src/jev.d.ts +2 -1
  202. package/dist/node_modules/@dalcode/dal-router/src/jev.js +4 -4
  203. package/dist/node_modules/@dalcode/dal-router/src/services.js +1 -1
  204. package/dist/node_modules/@dalcode/dal-router/src/subagent.js +1 -1
  205. package/dist/node_modules/@dalcode/dal-router/src/suggest.js +2 -0
  206. package/dist/node_modules/@dalcode/dal-skills/package.json +4 -3
  207. package/dist/node_modules/@dalcode/dal-skills/src/bundled/browser-qa/SKILL.md +48 -0
  208. package/dist/node_modules/@dalcode/dal-skills/src/bundled/diagram-design/SKILL.md +81 -0
  209. package/dist/node_modules/@dalcode/dal-skills/src/bundled/poster-design/SKILL.md +50 -0
  210. package/dist/node_modules/@dalcode/dal-skills/src/bundled/print-design/SKILL.md +55 -0
  211. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/dashboard.html +177 -0
  212. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/diagram.html +39 -0
  213. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/echarts-dal.json +360 -0
  214. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/email/notice.html +46 -0
  215. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/landing.html +173 -0
  216. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/mermaid-dal.json +140 -0
  217. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/mindmap.html +65 -0
  218. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/event-poster.html +40 -0
  219. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/poster.css +41 -0
  220. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/square-card.html +25 -0
  221. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/wechat-cover.html +29 -0
  222. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/xhs-card.html +35 -0
  223. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/xhs-cover.html +26 -0
  224. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/print/letter.html +35 -0
  225. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/print/print.css +65 -0
  226. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/print/report.html +76 -0
  227. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/print/resume.html +72 -0
  228. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/render.mjs +18 -0
  229. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/tokens.css +264 -0
  230. package/dist/node_modules/@dalcode/dal-skills/src/bundled/web-design/SKILL.md +73 -0
  231. package/dist/node_modules/@dalcode/dal-skills/src/bundled.js +1 -0
  232. package/dist/node_modules/@dalcode/dal-skills/src/catalog.js +2 -2
  233. package/dist/node_modules/@dalcode/dal-skills/src/index.js +16 -11
  234. package/dist/node_modules/@dalcode/dal-statusline/LICENSE +21 -0
  235. package/dist/node_modules/@dalcode/dal-statusline/package.json +31 -0
  236. package/dist/node_modules/@dalcode/dal-statusline/src/index.js +3 -0
  237. package/dist/node_modules/@dalcode/dal-structured/LICENSE +21 -0
  238. package/dist/node_modules/@dalcode/dal-structured/package.json +32 -0
  239. package/dist/node_modules/@dalcode/dal-structured/src/index.js +9 -0
  240. package/dist/node_modules/@dalcode/dal-subagent/LICENSE +24 -0
  241. package/dist/node_modules/@dalcode/dal-subagent/package.json +7 -6
  242. package/dist/node_modules/@dalcode/dal-subagent/src/background.js +13 -0
  243. package/dist/node_modules/@dalcode/dal-subagent/src/index.js +22 -14
  244. package/dist/node_modules/@dalcode/dal-subagent/src/inproc-runner.js +3 -0
  245. package/dist/node_modules/@dalcode/dal-subagent/src/pool.js +1 -0
  246. package/dist/node_modules/@dalcode/dal-subagent/src/process-runner.js +3 -3
  247. package/dist/node_modules/@dalcode/dal-subagent/src/tmux-runner.js +3 -0
  248. package/dist/node_modules/@dalcode/dal-subagent/src/worktree.js +2 -0
  249. package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
  250. package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
  251. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  252. package/dist/node_modules/@dalcode/dal-tool-catalog/src/groups.js +1 -1
  253. package/dist/node_modules/@dalcode/dal-tool-catalog/src/index.js +4 -4
  254. package/dist/node_modules/@dalcode/dal-tool-catalog/src/repair-hook.js +1 -0
  255. package/dist/node_modules/@dalcode/dal-tool-catalog/src/repair.js +4 -0
  256. package/dist/node_modules/@dalcode/dal-usage/LICENSE +45 -0
  257. package/dist/node_modules/@dalcode/dal-usage/package.json +33 -0
  258. package/dist/node_modules/@dalcode/dal-usage/src/budget.d.ts +14 -0
  259. package/dist/node_modules/@dalcode/dal-usage/src/budget.js +3 -0
  260. package/dist/node_modules/@dalcode/dal-usage/src/data.d.ts +30 -0
  261. package/dist/node_modules/@dalcode/dal-usage/src/data.js +1 -0
  262. package/dist/node_modules/@dalcode/dal-usage/src/index.d.ts +12 -0
  263. package/dist/node_modules/@dalcode/dal-usage/src/index.js +2 -0
  264. package/dist/node_modules/@dalcode/dal-usage/src/report.d.ts +29 -0
  265. package/dist/node_modules/@dalcode/dal-usage/src/report.js +3 -0
  266. package/dist/node_modules/@dalcode/dal-web/package.json +6 -4
  267. package/dist/node_modules/@dalcode/dal-web/src/fetch.js +11 -5
  268. package/dist/node_modules/@dalcode/dal-web/src/index.js +2 -2
  269. package/dist/node_modules/@dalcode/dal-web/src/pdf.js +5 -0
  270. package/dist/node_modules/@dalcode/dal-workflow/LICENSE +24 -0
  271. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  272. package/dist/node_modules/@dalcode/dal-workflow/src/announce-check.js +1 -0
  273. package/dist/node_modules/@dalcode/dal-workflow/src/check-in.js +1 -1
  274. package/dist/node_modules/@dalcode/dal-workflow/src/completion-check.js +4 -0
  275. package/dist/node_modules/@dalcode/dal-workflow/src/index.js +4 -4
  276. package/dist/node_modules/@dalcode/dal-workflow/src/lean-code.js +1 -0
  277. package/dist/node_modules/@dalcode/dal-workflow/src/ledger.js +3 -0
  278. package/dist/node_modules/@dalcode/dal-workflow/src/loop-guard.js +3 -0
  279. package/dist/node_modules/@dalcode/dal-workflow/src/shared.js +2 -2
  280. package/dist/node_modules/@dalcode/dal-workflow/src/todo.js +4 -2
  281. package/dist/node_modules/@dalcode/dal-workflow/src/verify-check.js +2 -0
  282. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  283. package/dist/node_modules/@earendil-works/chord/package.json +1 -1
  284. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
  285. package/dist/node_modules/@earendil-works/pi-ai/dist/cli.js +0 -0
  286. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  287. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  288. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  289. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/radius.json +1 -1
  290. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  291. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
  292. package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
  293. package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
  294. package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
  295. package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
  296. package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
  297. package/dist/node_modules/@earendil-works/pi-server/package.json +3 -3
  298. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  299. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  300. package/dist/package-manager-cli.js +61 -61
  301. package/dist/sdk/office.d.ts +1 -1
  302. package/dist/sdk/office.js +1 -1
  303. package/dist/sdk/rewind.d.ts +1 -1
  304. package/dist/sdk/rewind.js +1 -1
  305. package/dist/sdk/usage.d.ts +8 -0
  306. package/dist/sdk/usage.js +1 -0
  307. package/dist/utils/open-browser.d.ts +1 -0
  308. package/dist/utils/tools-manager.js +1 -1
  309. package/dist/utils/version-check.d.ts +1 -0
  310. package/dist/utils/version-check.js +2 -2
  311. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  312. package/examples/extensions/gondolin/package-lock.json +2 -2
  313. package/examples/extensions/gondolin/package.json +1 -1
  314. package/examples/extensions/sandbox/package-lock.json +2 -2
  315. package/examples/extensions/sandbox/package.json +1 -1
  316. package/examples/extensions/with-deps/package-lock.json +2 -2
  317. package/examples/extensions/with-deps/package.json +1 -1
  318. package/npm-shrinkwrap.json +57 -14
  319. package/package.json +9 -2
  320. package/dist/node_modules/@dalcode/dal-plugins/src/compat.js +0 -2
@@ -1,4 +1,4 @@
1
- var q=Object.defineProperty;var f=(e,t)=>q(e,"name",{value:t,configurable:!0});import{contentText as b,getCurrentSystemMessage as G,normalizeContext as Y,retryAssistantCall as H,uuidv7 as J}from"@earendil-works/pi-ai";import{completeSimple as Q}from"@earendil-works/pi-ai/compat";import{convertToLlm as N}from"../messages.js";import{buildSessionProjection as ee,sessionEntryToContextMessages as C}from"../session-manager.js";import{DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS as te}from"../settings-manager.js";import{combineUsage as ne}from"../usage-totals.js";import{shrinkToolResultsForSummary as se}from"./tool-output-pruning.js";import{computeFileLists as oe,createFileOps as re,estimateTokens as P,extractFileOpsFromMessage as _,formatFileOperations as ie,SUMMARIZATION_SYSTEM_PROMPT as ae,serializeConversation as D}from"./utils.js";function ce(e,t,o){const n=re();if(o>=0){const s=t[o];if(!s.fromHook&&s.details){const i=s.details;if(Array.isArray(i.readFiles))for(const a of i.readFiles)n.read.add(a);if(Array.isArray(i.modifiedFiles))for(const a of i.modifiedFiles)n.edited.add(a)}}for(const s of e)_(s,n);return n}f(ce,"extractFileOperations");function F(e){return e.sourceEntry.type==="compaction"?[]:e.messages.filter(t=>t.role!=="system")}f(F,"getMessagesFromProjectedEntryForCompaction");const Ue={enabled:!0,reserveTokens:16384,keepRecentTokens:2e4};function z(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}f(z,"calculateContextTokens");function K(e){if(e.role==="assistant"&&"usage"in e){const t=e;if(t.stopReason!=="aborted"&&t.stopReason!=="error"&&t.usage&&z(t.usage)>0)return t.usage}}f(K,"getAssistantUsage");function be(e){for(let t=e.length-1;t>=0;t--){const o=e[t];if(o.type==="message"){const n=K(o.message);if(n)return n}}}f(be,"getLastAssistantUsage");function ue(e){for(let t=e.length-1;t>=0;t--){const o=K(e[t]);if(o)return{usage:o,index:t}}}f(ue,"getLastAssistantUsageInfo");function fe(e){const t=ue(e);if(!t){let s=0;for(const i of e)s+=P(i);return{tokens:s,usageTokens:0,trailingTokens:s,lastUsageIndex:null}}const o=z(t.usage);let n=0;for(let s=t.index+1;s<e.length;s++)n+=P(e[s]);return{tokens:o+n,usageTokens:o,trailingTokens:n,lastUsageIndex:t.index}}f(fe,"estimateContextTokens");function me(e,t){const o=fe(e.messages);if(o.lastUsageIndex!==null){let i=0,a;for(const m of e.entries){const c=i+m.messages.length;if(o.lastUsageIndex<c){a=m.sourceEntry.id;break}i=c}const u=a?t.findIndex(m=>m.id===a):-1;let l=-1;for(let m=t.length-1;m>=0;m--){const c=t[m];if(c.type==="context_edit"||c.type==="compaction"){l=m;break}}if(u>l)return o}const n=G(e.messages);let s=n?P(n):0;for(const i of e.messages)i.role!=="system"&&(s+=P(i));return{tokens:s,usageTokens:0,trailingTokens:s,lastUsageIndex:null}}f(me,"estimateProjectedContextTokens");const le=32e3;function pe(e,t,o=0){const n=e-t.reserveTokens;if(!t.maxContextTokens)return n;if(t.maxContextTokens!==te)return Math.min(n,t.maxContextTokens);const s=o+t.keepRecentTokens+le;return Math.min(n,Math.max(t.maxContextTokens,s))}f(pe,"compactionThreshold");function Ne(e,t,o,n=0){return o.enabled?e>pe(t,o,n):!1}f(Ne,"shouldCompact");function $(e){switch(e.role){case"user":case"assistant":case"bashExecution":case"custom":case"branchSummary":case"compactionSummary":return!0;case"toolResult":return!1}return!1}f($,"isCutPointMessage");function B(e){switch(e.role){case"user":case"bashExecution":case"custom":case"branchSummary":case"compactionSummary":return!0;case"assistant":case"toolResult":return!1}return!1}f(B,"isTurnStartMessage");function L(e){return e.type==="compaction"?!1:C(e).some(B)}f(L,"isTurnStartEntry");function de(e,t,o){const n=[];for(let s=t;s<o;s++){const i=e[s];i.type!=="compaction"&&C(i).some($)&&n.push(s)}return n}f(de,"findValidCutPoints");function ge(e,t,o){for(let n=t;n>=o;n--)if(L(e[n]))return n;return-1}f(ge,"findTurnStartIndex");function _e(e,t,o,n){const s=de(e,t,o);if(s.length===0)return{firstKeptEntryIndex:t,turnStartIndex:-1,isSplitTurn:!1};let i=0,a=s[0];for(let c=o-1;c>=t;c--){const d=e[c],x=C(d).reduce((y,T)=>y+P(T),0);if(x!==0&&(i+=x,i>=n)){a=s.find(y=>y>=c)??s[s.length-1];break}}for(;a>t;){const c=e[a-1];if(c.type==="compaction"||C(c).length>0)break;a--}const u=e[a],l=L(u),m=l?-1:ge(e,a,t);return{firstKeptEntryIndex:a,turnStartIndex:m,isSplitTurn:!l&&m!==-1}}f(_e,"findCutPoint");const xe=`The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.
1
+ var q=Object.defineProperty;var m=(e,t)=>q(e,"name",{value:t,configurable:!0});import{contentText as U,getCurrentSystemMessage as G,normalizeContext as Y,retryAssistantCall as H,uuidv7 as J}from"@earendil-works/pi-ai";import{completeSimple as Q}from"@earendil-works/pi-ai/compat";import{convertToLlm as N}from"../messages.js";import{buildSessionProjection as ee,sessionEntryToContextMessages as P}from"../session-manager.js";import{DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS as te}from"../settings-manager.js";import{combineUsage as ne}from"../usage-totals.js";import{shrinkToolResultsForSummary as se}from"./tool-output-pruning.js";import{computeFileLists as oe,createFileOps as re,estimateTokens as I,extractFileOpsFromMessage as _,formatFileOperations as ae,SUMMARIZATION_SYSTEM_PROMPT as ie,serializeConversation as D}from"./utils.js";function ce(e,t,o){const n=re();if(o>=0){const s=t[o];if(!s.fromHook&&s.details){const a=s.details;if(Array.isArray(a.readFiles))for(const i of a.readFiles)n.read.add(i);if(Array.isArray(a.modifiedFiles))for(const i of a.modifiedFiles)n.edited.add(i)}}for(const s of e)_(s,n);return n}m(ce,"extractFileOperations");function F(e){return e.sourceEntry.type==="compaction"?[]:e.messages.filter(t=>t.role!=="system")}m(F,"getMessagesFromProjectedEntryForCompaction");const Ae={enabled:!0,reserveTokens:16384,keepRecentTokens:2e4};function z(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}m(z,"calculateContextTokens");function K(e){if(e.role==="assistant"&&"usage"in e){const t=e;if(t.stopReason!=="aborted"&&t.stopReason!=="error"&&t.usage&&z(t.usage)>0)return t.usage}}m(K,"getAssistantUsage");function Ue(e){for(let t=e.length-1;t>=0;t--){const o=e[t];if(o.type==="message"){const n=K(o.message);if(n)return n}}}m(Ue,"getLastAssistantUsage");function ue(e){for(let t=e.length-1;t>=0;t--){const o=K(e[t]);if(o)return{usage:o,index:t}}}m(ue,"getLastAssistantUsageInfo");function me(e){const t=ue(e);if(!t){let s=0;for(const a of e)s+=I(a);return{tokens:s,usageTokens:0,trailingTokens:s,lastUsageIndex:null}}const o=z(t.usage);let n=0;for(let s=t.index+1;s<e.length;s++)n+=I(e[s]);return{tokens:o+n,usageTokens:o,trailingTokens:n,lastUsageIndex:t.index}}m(me,"estimateContextTokens");function le(e,t){const o=me(e.messages);if(o.lastUsageIndex!==null){let a=0,i;for(const l of e.entries){const c=a+l.messages.length;if(o.lastUsageIndex<c){i=l.sourceEntry.id;break}a=c}const u=i?t.findIndex(l=>l.id===i):-1;let f=-1;for(let l=t.length-1;l>=0;l--){const c=t[l];if(c.type==="context_edit"||c.type==="compaction"){f=l;break}}if(u>f)return o}const n=G(e.messages);let s=n?I(n):0;for(const a of e.messages)a.role!=="system"&&(s+=I(a));return{tokens:s,usageTokens:0,trailingTokens:s,lastUsageIndex:null}}m(le,"estimateProjectedContextTokens");const fe=32e3;function de(e,t,o=0){const n=e-t.reserveTokens;if(!t.maxContextTokens)return n;if(t.maxContextTokens!==te)return Math.min(n,t.maxContextTokens);const s=o+t.keepRecentTokens+fe;return Math.min(n,Math.max(t.maxContextTokens,s))}m(de,"compactionThreshold");function Ne(e,t,o,n=0){return o.enabled?e>de(t,o,n):!1}m(Ne,"shouldCompact");function $(e){switch(e.role){case"user":case"assistant":case"bashExecution":case"custom":case"branchSummary":case"compactionSummary":return!0;case"toolResult":return!1}return!1}m($,"isCutPointMessage");function W(e){switch(e.role){case"user":case"bashExecution":case"custom":case"branchSummary":case"compactionSummary":return!0;case"assistant":case"toolResult":return!1}return!1}m(W,"isTurnStartMessage");function L(e){return e.type==="compaction"?!1:P(e).some(W)}m(L,"isTurnStartEntry");function pe(e,t,o){const n=[];for(let s=t;s<o;s++){const a=e[s];a.type!=="compaction"&&P(a).some($)&&n.push(s)}return n}m(pe,"findValidCutPoints");function he(e,t,o){for(let n=t;n>=o;n--)if(L(e[n]))return n;return-1}m(he,"findTurnStartIndex");function _e(e,t,o,n){const s=pe(e,t,o);if(s.length===0)return{firstKeptEntryIndex:t,turnStartIndex:-1,isSplitTurn:!1};let a=0,i=s[0];for(let c=o-1;c>=t;c--){const p=e[c],g=P(p).reduce((x,y)=>x+I(y),0);if(g!==0&&(a+=g,a>=n)){i=s.find(x=>x>=c)??s[s.length-1];break}}for(;i>t;){const c=e[i-1];if(c.type==="compaction"||P(c).length>0)break;i--}const u=e[i],f=L(u),l=f?-1:he(e,i,t);return{firstKeptEntryIndex:i,turnStartIndex:l,isSplitTurn:!f&&l!==-1}}m(_e,"findCutPoint");const ge=`The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.
2
2
 
3
3
  Use this EXACT format:
4
4
 
@@ -19,6 +19,14 @@ Use this EXACT format:
19
19
  ### Blocked
20
20
  - [Issues preventing progress, if any]
21
21
 
22
+ ## Tracks
23
+ - **[Track name]**: [where it stands, in one line] \u2014 workspace: [directory or worktree], branch [name], last commit [short hash and subject], uncommitted: [yes/no, which files]; next: [the next step]
24
+ - [One line per separate line of work; "(single track)" when there is only one]
25
+
26
+ ## Workspace State
27
+ - [Every repository, worktree or directory the work happened in, with the branch, last commit and whether changes are uncommitted, as last seen in the conversation; who else is working there, if known]
28
+ - [Or "(none)"]
29
+
22
30
  ## Key Decisions
23
31
  - **[Decision]**: [Brief rationale]
24
32
 
@@ -26,15 +34,16 @@ Use this EXACT format:
26
34
  1. [Ordered list of what should happen next]
27
35
 
28
36
  ## Critical Context
29
- - [Any data, examples, or references needed to continue]
37
+ - [Any data, examples, or references needed to continue: commands that work in this environment (package manager, how tests are run), ids, URLs, exact error messages]
30
38
  - [Or "(none)" if not applicable]
31
39
 
32
- Keep each section concise. Preserve exact file paths, function names, and error messages.`,ye=`Update the existing structured summary with new information. RULES:
40
+ Keep each section concise. Preserve exact file paths, function names, and error messages. Record facts that would otherwise have to be looked up again (git state, which commands work), so the work can continue without re-checking them.`,xe=`Update the existing structured summary with new information. RULES:
33
41
  - PRESERVE all existing information from the previous summary
34
42
  - ADD new progress, decisions, and context from the new messages
35
43
  - UPDATE the Progress section: move items from "In Progress" to "Done" when completed
36
44
  - UPDATE "Next Steps" based on what was accomplished
37
45
  - PRESERVE exact file paths, function names, and error messages
46
+ - UPDATE "Tracks" and "Workspace State" so they describe the state at the end of the new messages
38
47
  - If something is no longer relevant, you may remove it
39
48
 
40
49
  Use this EXACT format:
@@ -55,6 +64,12 @@ Use this EXACT format:
55
64
  ### Blocked
56
65
  - [Current blockers - remove if resolved]
57
66
 
67
+ ## Tracks
68
+ - **[Track name]**: [where it stands] \u2014 workspace, branch, last commit, uncommitted changes; next step (update each track, keep finished ones as one "done" line)
69
+
70
+ ## Workspace State
71
+ - [Update the branch, last commit and uncommitted state of every repository or worktree in use, as last seen]
72
+
58
73
  ## Key Decisions
59
74
  - **[Decision]**: [Brief rationale] (preserve all previous, add new)
60
75
 
@@ -64,19 +79,19 @@ Use this EXACT format:
64
79
  ## Critical Context
65
80
  - [Preserve important context, add new if needed]
66
81
 
67
- Keep each section concise. Preserve exact file paths, function names, and error messages.`,Te=`The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.
82
+ Keep each section concise. Preserve exact file paths, function names, and error messages.`,ye=`The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.
68
83
 
69
- ${ye}`;function j(e,t){if(e.stopReason==="error")return`${t} failed: ${e.errorMessage||"Unknown error"}`;if(e.stopReason==="length")return`${t} failed: generation hit the token cap and the summary is incomplete`}f(j,"getSummarizationFailure");function V(e,t,o,n,s,i,a,u){const l={maxTokens:t,signal:i,apiKey:o,headers:n,env:s,sessionId:u};return e.reasoning&&a&&a!=="off"&&(l.reasoning=a),l}f(V,"createSummarizationOptions");async function W(e,t,o,n,s,i){const a={...o,cacheRetention:"none",sessionId:o.sessionId??J()};return H(f(async()=>n?(await n(e,t,a)).result():Q(e,t,a),"produce"),s,a.signal,i)}f(W,"completeSummarization");async function De(e,t,o,n,s,i,a,u,l,m,c,d,x,y){return(await A(e,t,o,n,s,i,a,u,l,m,c,d,x,y)).text}f(De,"generateSummary");function X(e){return Y({systemPrompt:ae,messages:[{role:"user",content:[{type:"text",text:e}],timestamp:Date.now()}]})}f(X,"buildSummarizationContext");async function A(e,t,o,n,s,i,a,u,l,m,c,d,x,y){const T=Math.min(Math.floor(.8*o),t.maxTokens>0?t.maxTokens:Number.POSITIVE_INFINITY);let g=u?Te:xe;a&&(g=`${g}
84
+ ${xe}`;function j(e,t){if(e.stopReason==="error")return`${t} failed: ${e.errorMessage||"Unknown error"}`;if(e.stopReason==="length")return`${t} failed: generation hit the token cap and the summary is incomplete`}m(j,"getSummarizationFailure");function B(e,t,o,n,s,a,i,u){const f={maxTokens:t,signal:a,apiKey:o,headers:n,env:s,sessionId:u};return e.reasoning&&i&&i!=="off"&&(f.reasoning=i),f}m(B,"createSummarizationOptions");async function V(e,t,o,n,s,a){const i={...o,cacheRetention:"none",sessionId:o.sessionId??J()};return H(m(async()=>n?(await n(e,t,i)).result():Q(e,t,i),"produce"),s,i.signal,a)}m(V,"completeSummarization");async function De(e,t,o,n,s,a,i,u,f,l,c,p,g,x){return(await b(e,t,o,n,s,a,i,u,f,l,c,p,g,x)).text}m(De,"generateSummary");function X(e){return Y({systemPrompt:ie,messages:[{role:"user",content:[{type:"text",text:e}],timestamp:Date.now()}]})}m(X,"buildSummarizationContext");async function b(e,t,o,n,s,a,i,u,f,l,c,p,g,x){const y=Math.min(Math.floor(.8*o),t.maxTokens>0?t.maxTokens:Number.POSITIVE_INFINITY);let h=u?ye:ge;i&&(h=`${h}
70
85
 
71
- Additional focus: ${a}`);const r=N(e);let h=`<conversation>
86
+ Additional focus: ${i}`);const r=N(e);let T=`<conversation>
72
87
  ${D(r)}
73
88
  </conversation>
74
89
 
75
- `;u&&(h+=`<previous-summary>
90
+ `;u&&(T+=`<previous-summary>
76
91
  ${u}
77
92
  </previous-summary>
78
93
 
79
- `),h+=g;const S=V(t,T,n,s,c,i,l,y),E=await W(t,X(h),S,m,d,x),k=j(E,"Summarization");if(k)throw new Error(k);if(E.content.some(v=>v.type==="toolCall"))throw new Error("Summarization attempted to call a tool");return{text:b(E.content),usage:E.usage}}f(A,"generateSummaryWithUsage");function Z(e){return e.sourceEntry.type==="compaction"?!1:e.messages.some(B)}f(Z,"isProjectedTurnStart");function he(e,t,o){for(let n=t;n>=o;n--)if(Z(e[n]))return n;return-1}f(he,"findProjectedTurnStartIndex");function Se(e,t,o,n){const s=[];for(let r=t;r<o;r++){const p=e[r];p.sourceEntry.type!=="compaction"&&p.messages.some($)&&s.push(r)}if(s.length===0)return{firstKeptEntryIndex:t,turnStartIndex:-1,isSplitTurn:!1};let i=0,a=!1,u=s[0];for(let r=o-1;r>=t;r--){const p=e[r].messages.reduce((h,S)=>h+P(S),0);if(p!==0&&(i+=p,i>=n)){a=!0,u=s.find(h=>h>=r)??s[s.length-1];break}}const l=e.slice(u+1,o),m=f(r=>r.sourceEntry.type!=="context_edit"&&C(r.sourceEntry).length>0,"isIntrinsicallyVisible"),c=f(r=>m(r)&&r.messages.length===0,"isOmitted"),d=new Set(l.filter(c).map(r=>r.sourceEntry.id)),x=l.some(r=>r.sourceEntry.type==="context_edit"&&r.sourceEntry.replacement!==null&&!d.has(r.sourceEntry.targetId));for(a&&!x&&l.some(r=>r.sourceEntry.type==="message"&&r.sourceEntry.message.role==="assistant"&&c(r))&&l.every(r=>r.sourceEntry.type!=="compaction"&&(!m(r)||c(r)))&&u++;u>t;){const r=e[u-1];if(r.sourceEntry.type==="compaction"||r.messages.length>0)break;u--}const T=Z(e[u]),g=T?-1:he(e,u,t);return{firstKeptEntryIndex:u,turnStartIndex:g,isSplitTurn:!T&&g!==-1}}f(Se,"findProjectedCutPoint");function Fe(e,t){if(e.length>0&&e[e.length-1].type==="compaction")return;const o=ee(e),n=o.entries,s=n.map(p=>p.sourceEntry),i=n.findIndex(p=>p.sourceEntry.type==="compaction"&&p.messages.length>0);let a,u=0;i>=0&&(a=n[i].sourceEntry.summary,u=i+1);const l=n.length,m=me(o,e).tokens,c=Se(n,u,l,t.keepRecentTokens),d=n[c.firstKeptEntryIndex]?.sourceEntry;if(!d?.id)return;const x=d.id,y=c.isSplitTurn?c.turnStartIndex:c.firstKeptEntryIndex,T=n.slice(u,y).flatMap(F),g=c.isSplitTurn?n.slice(c.turnStartIndex,c.firstKeptEntryIndex).flatMap(F):[];if(T.length===0&&g.length===0)return;const r=ce(T,s,i);if(c.isSplitTurn)for(const p of g)_(p,r);return{firstKeptEntryId:x,messagesToSummarize:T,turnPrefixMessages:g,isSplitTurn:c.isSplitTurn,tokensBefore:m,previousSummary:a,fileOps:r,settings:t}}f(Fe,"prepareCompaction");const Ee=`The messages above are earlier context from an ongoing conversation. Later messages are stored separately and do not need to be reconstructed.
94
+ `),T+=h;const k=B(t,y,n,s,c,a,f,x),w=await V(t,X(T),k,l,p,g),S=j(w,"Summarization");if(S)throw new Error(S);if(w.content.some(v=>v.type==="toolCall"))throw new Error("Summarization attempted to call a tool");return{text:U(w.content),usage:w.usage}}m(b,"generateSummaryWithUsage");function Z(e){return e.sourceEntry.type==="compaction"?!1:e.messages.some(W)}m(Z,"isProjectedTurnStart");function Te(e,t,o){for(let n=t;n>=o;n--)if(Z(e[n]))return n;return-1}m(Te,"findProjectedTurnStartIndex");function ke(e,t,o,n){const s=[];for(let r=t;r<o;r++){const d=e[r];d.sourceEntry.type!=="compaction"&&d.messages.some($)&&s.push(r)}if(s.length===0)return{firstKeptEntryIndex:t,turnStartIndex:-1,isSplitTurn:!1};let a=0,i=!1,u=s[0];for(let r=o-1;r>=t;r--){const d=e[r].messages.reduce((T,k)=>T+I(k),0);if(d!==0&&(a+=d,a>=n)){i=!0,u=s.find(T=>T>=r)??s[s.length-1];break}}const f=e.slice(u+1,o),l=m(r=>r.sourceEntry.type!=="context_edit"&&P(r.sourceEntry).length>0,"isIntrinsicallyVisible"),c=m(r=>l(r)&&r.messages.length===0,"isOmitted"),p=new Set(f.filter(c).map(r=>r.sourceEntry.id)),g=f.some(r=>r.sourceEntry.type==="context_edit"&&r.sourceEntry.replacement!==null&&!p.has(r.sourceEntry.targetId));for(i&&!g&&f.some(r=>r.sourceEntry.type==="message"&&r.sourceEntry.message.role==="assistant"&&c(r))&&f.every(r=>r.sourceEntry.type!=="compaction"&&(!l(r)||c(r)))&&u++;u>t;){const r=e[u-1];if(r.sourceEntry.type==="compaction"||r.messages.length>0)break;u--}const y=Z(e[u]),h=y?-1:Te(e,u,t);return{firstKeptEntryIndex:u,turnStartIndex:h,isSplitTurn:!y&&h!==-1}}m(ke,"findProjectedCutPoint");function Fe(e,t){if(e.length>0&&e[e.length-1].type==="compaction")return;const o=ee(e),n=o.entries,s=n.map(d=>d.sourceEntry),a=n.findIndex(d=>d.sourceEntry.type==="compaction"&&d.messages.length>0);let i,u=0;a>=0&&(i=n[a].sourceEntry.summary,u=a+1);const f=n.length,l=le(o,e).tokens,c=ke(n,u,f,t.keepRecentTokens),p=n[c.firstKeptEntryIndex]?.sourceEntry;if(!p?.id)return;const g=p.id,x=c.isSplitTurn?c.turnStartIndex:c.firstKeptEntryIndex,y=n.slice(u,x).flatMap(F),h=c.isSplitTurn?n.slice(c.turnStartIndex,c.firstKeptEntryIndex).flatMap(F):[];if(y.length===0&&h.length===0)return;const r=ce(y,s,a);if(c.isSplitTurn)for(const d of h)_(d,r);return{firstKeptEntryId:g,messagesToSummarize:y,turnPrefixMessages:h,isSplitTurn:c.isSplitTurn,tokensBefore:l,previousSummary:i,fileOps:r,settings:t}}m(Fe,"prepareCompaction");const we=`The messages above are earlier context from an ongoing conversation. Later messages are stored separately and do not need to be reconstructed.
80
95
 
81
96
  Create a concise checkpoint of the user's request and the progress shown above. This checkpoint will be placed before the later messages so the conversation can continue with the necessary context.
82
97
 
@@ -86,17 +101,20 @@ Create a concise checkpoint of the user's request and the progress shown above.
86
101
  ## Progress So Far
87
102
  - [Key decisions and work completed in these messages]
88
103
 
104
+ ## Tracks & Workspace State
105
+ - [Each separate line of work: where it stands, the directory or worktree it happens in, branch, last commit, uncommitted changes, next step; or "(single track)"]
106
+
89
107
  ## Context Needed to Continue
90
- - [Information from these messages needed to understand the later work]
108
+ - [Information from these messages needed to understand the later work: commands that work here (package manager, how tests run), ids, exact error messages]
91
109
 
92
- Only summarize information explicitly present above. Do not infer or recreate later messages.`;async function ze(e,t,o,n,s,i,a,u,l,m,c,d){const{firstKeptEntryId:x,isSplitTurn:y,tokensBefore:T,previousSummary:g,fileOps:r,settings:p}=e,h=p.pruneToolOutputs===!1?I=>I:se,S=h(e.messagesToSummarize),E=h(e.turnPrefixMessages);let k,w;if(y&&E.length>0){let I=g??"No prior history.",M;if(S.length>0){const U=await A(S,t,p.reserveTokens,o,n,i,s,g,a,u,l,m,c,d);I=U.text,M=U.usage}const O=await ke(E,t,p.reserveTokens,o,n,l,i,a,u,m,c,d);k=`${I}
110
+ Only summarize information explicitly present above. Do not infer or recreate later messages.`;async function ze(e,t,o,n,s,a,i,u,f,l,c,p){const{firstKeptEntryId:g,isSplitTurn:x,tokensBefore:y,previousSummary:h,fileOps:r,settings:d}=e,T=d.pruneToolOutputs===!1?E=>E:se,k=T(e.messagesToSummarize),w=T(e.turnPrefixMessages);let S,C;if(x&&w.length>0){let E=h??"No prior history.",M;if(k.length>0){const A=await b(k,t,d.reserveTokens,o,n,a,s,h,i,u,f,l,c,p);E=A.text,M=A.usage}const O=await Se(w,t,d.reserveTokens,o,n,f,a,i,u,l,c,p);S=`${E}
93
111
 
94
112
  ---
95
113
 
96
114
  **Turn Context (split turn):**
97
115
 
98
- ${O.text}`,w=M?ne(M,O.usage):O.usage}else{const I=await A(S,t,p.reserveTokens,o,n,i,s,g,a,u,l,m,c,d);k=I.text,w=I.usage}const{readFiles:v,modifiedFiles:R}=oe(r);if(k+=ie(v,R),!x)throw new Error("First kept entry has no UUID - session may need migration");return{summary:k,firstKeptEntryId:x,tokensBefore:T,usage:w,details:{readFiles:v,modifiedFiles:R}}}f(ze,"compact");async function ke(e,t,o,n,s,i,a,u,l,m,c,d){const x=Math.min(Math.floor(.5*o),t.maxTokens>0?t.maxTokens:Number.POSITIVE_INFINITY),y=N(e),g=`# Conversation
99
- ${D(y)}
116
+ ${O.text}`,C=M?ne(M,O.usage):O.usage}else{const E=await b(k,t,d.reserveTokens,o,n,a,s,h,i,u,f,l,c,p);S=E.text,C=E.usage}const{readFiles:v,modifiedFiles:R}=oe(r);if(S+=ae(v,R),!g)throw new Error("First kept entry has no UUID - session may need migration");return{summary:S,firstKeptEntryId:g,tokensBefore:y,usage:C,details:{readFiles:v,modifiedFiles:R}}}m(ze,"compact");async function Se(e,t,o,n,s,a,i,u,f,l,c,p){const g=Math.min(Math.floor(.5*o),t.maxTokens>0?t.maxTokens:Number.POSITIVE_INFINITY),x=N(e),h=`# Conversation
117
+ ${D(x)}
100
118
 
101
119
  # Instructions
102
- ${Ee}`,r=await W(t,X(g),V(t,x,n,s,i,a,u,d),l,m,c),p=j(r,"Turn prefix summarization");if(p)throw new Error(p);if(r.content.some(h=>h.type==="toolCall"))throw new Error("Turn prefix summarization attempted to call a tool");return{text:b(r.content),usage:r.usage}}f(ke,"generateTurnPrefixSummary");export{Ue as DEFAULT_COMPACTION_SETTINGS,le as MIN_COMPACTION_HEADROOM_TOKENS,z as calculateContextTokens,ze as compact,pe as compactionThreshold,W as completeSummarization,fe as estimateContextTokens,me as estimateProjectedContextTokens,_e as findCutPoint,ge as findTurnStartIndex,De as generateSummary,A as generateSummaryWithUsage,be as getLastAssistantUsage,j as getSummarizationFailure,Fe as prepareCompaction,Ne as shouldCompact};
120
+ ${we}`,r=await V(t,X(h),B(t,g,n,s,a,i,u,p),f,l,c),d=j(r,"Turn prefix summarization");if(d)throw new Error(d);if(r.content.some(T=>T.type==="toolCall"))throw new Error("Turn prefix summarization attempted to call a tool");return{text:U(r.content),usage:r.usage}}m(Se,"generateTurnPrefixSummary");export{Ae as DEFAULT_COMPACTION_SETTINGS,fe as MIN_COMPACTION_HEADROOM_TOKENS,z as calculateContextTokens,ze as compact,de as compactionThreshold,V as completeSummarization,me as estimateContextTokens,le as estimateProjectedContextTokens,_e as findCutPoint,he as findTurnStartIndex,De as generateSummary,b as generateSummaryWithUsage,Ue as getLastAssistantUsage,j as getSummarizationFailure,Fe as prepareCompaction,Ne as shouldCompact};
@@ -1 +1 @@
1
- var B=Object.defineProperty;var i=(t,r)=>B(t,"name",{value:r,configurable:!0});import*as w from"node:fs";import{createRequire as _}from"node:module";import*as g from"node:path";import{fileURLToPath as b}from"node:url";import{CONFIG_DIR_NAME as O,getAgentDir as J,isBunBinary as R,isBundledNode as H}from"../../config.js";import{resolvePath as E}from"../../utils/paths.js";import{createEventBus as q}from"../event-bus.js";import{execCommand as W}from"../exec.js";import{McpServerRegistry as G,mcpNamespace as I,validateMcpServerConfig as X}from"../mcp-servers.js";import{findNearestPiManifest as K,getExtensionApiMismatchError as Q,readPiManifest as Y}from"../pi-manifest.js";import{createSyntheticSourceInfo as Z,getSyntheticPathSource as ee,isSyntheticPath as te}from"../source-info.js";import{time as j}from"../timings.js";import{applyPermissionSurface as re}from"./permission-surface.js";const P=_(import.meta.url),se=Symbol.for("dalcode.extensions.apiDecorator"),ne="sea"in process.features&&process.features.sea===!0||process.getBuiltinModule("node:sea")?.isSea()===!0,oe=!R&&g.extname(b(import.meta.url))===".ts",V=R||ne||H;let N;function ie(){return N??=(V?import("./jiti-static-loader.js"):import("./jiti-loader.js")).then(t=>t.createJiti),N}i(ie,"getCreateJiti");let $;function L(){return $??=import("./virtual-modules.js").then(t=>t.VIRTUAL_MODULES),$}i(L,"getVirtualModules");let M=null;function ae(){if(M)return M;const t=g.dirname(b(import.meta.url)),r=g.resolve(t,"../..","index.js"),u=P.resolve("typebox"),d=P.resolve("typebox/compile"),c=P.resolve("typebox/value"),a=g.resolve(t,"../../../../"),o=i((s,p)=>{const v=g.join(a,s);return w.existsSync(v)?v:b(import.meta.resolve(p))},"resolveWorkspaceOrImport"),l=r,n=o("agent/dist/index.js","@earendil-works/pi-agent-core"),f=o("tui/dist/index.js","@earendil-works/pi-tui"),h=o("ai/dist/compat.js","@earendil-works/pi-ai/compat"),m=o("ai/dist/oauth.js","@earendil-works/pi-ai/oauth"),e=o("ai/dist/providers/all.js","@earendil-works/pi-ai/providers/all");return M={"@earendil-works/pi-coding-agent":l,"@earendil-works/pi-agent-core":n,"@earendil-works/pi-tui":f,"@earendil-works/pi-ai/providers/all":e,"@earendil-works/pi-ai/compat":h,"@earendil-works/pi-ai/oauth":m,"@earendil-works/pi-ai":h,"@mariozechner/pi-coding-agent":l,"@mariozechner/pi-agent-core":n,"@mariozechner/pi-tui":f,"@mariozechner/pi-ai/providers/all":e,"@mariozechner/pi-ai/compat":h,"@mariozechner/pi-ai/oauth":m,"@mariozechner/pi-ai":h,typebox:u,"typebox/compile":d,"typebox/value":c,"@sinclair/typebox":u,"@sinclair/typebox/compile":d,"@sinclair/typebox/value":c},M}i(ae,"getAliases");let x,T=0;const k=new Map;function ce(){k.clear(),x=void 0,T++}i(ce,"clearExtensionCache");function le(t){const r=E(t);return x!==void 0&&x!==r&&ce(),x=r,{cwd:r,generation:T}}i(le,"useExtensionCacheCwd");function de(){const t=i(()=>{throw new Error("Extension runtime not initialized. Action methods cannot be called during extension loading.")},"notInitialized"),r={},u=new Set,d=i(()=>{if(r.staleMessage)throw new Error(r.staleMessage)},"assertActive"),c={sendMessage:t,sendUserMessage:t,appendEntry:t,emitHostEvent:i(()=>{},"emitHostEvent"),setSessionName:t,getSessionName:t,setLabel:t,getActiveTools:t,getAllTools:t,getSettings:t,setActiveTools:t,isToolAllowed:t,getToolAllowlist:t,refreshTools:i(()=>{},"refreshTools"),getCommands:t,setModel:i(()=>Promise.reject(new Error("Extension runtime not initialized")),"setModel"),getThinkingLevel:t,setThinkingLevel:t,flagValues:new Map,pendingProviderRegistrations:[],pendingNativeProviderRegistrations:[],mcpServers:new G,pendingVirtualModelRegistrations:[],createContext:t,assertActive:d,invalidate:i(a=>{if(!r.staleMessage){r.staleMessage=a??"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().";for(const o of u)o();u.clear()}},"invalidate"),trackEventBusSubscription:i(a=>{let o=!0;const l=i(()=>{o&&(o=!1,u.delete(l),a())},"trackedUnsubscribe");return u.add(l),l},"trackEventBusSubscription"),registerProvider:i((a,o,l="<unknown>")=>{c.pendingProviderRegistrations.push({name:a,config:o,extensionPath:l})},"registerProvider"),registerNativeProvider:i((a,o="<unknown>")=>{c.pendingNativeProviderRegistrations.push({provider:a,extensionPath:o})},"registerNativeProvider"),unregisterProvider:i(a=>{c.pendingProviderRegistrations=c.pendingProviderRegistrations.filter(o=>o.name!==a),c.pendingNativeProviderRegistrations=c.pendingNativeProviderRegistrations.filter(o=>o.provider.id!==a)},"unregisterProvider"),registerVirtualModel:i((a,o="<unknown>")=>{c.pendingVirtualModelRegistrations.push({definition:a,extensionPath:o})},"registerVirtualModel"),unregisterVirtualModel:i((a,o)=>{c.pendingVirtualModelRegistrations=c.pendingVirtualModelRegistrations.filter(({definition:l})=>l.provider!==a||l.id!==o)},"unregisterVirtualModel")};return c}i(de,"createExtensionRuntime");function ue(t,r,u,d){const c=new Map,a=[],o=[];let l="loading";const n=i(()=>{if(l==="failed")throw new Error(`Extension "${t.path}" failed to load and its API is no longer active.`);r.assertActive()},"assertActive"),f=i(e=>{l==="loading"?a.push(e):e()},"applyRuntimeChange"),h=i(()=>{c.clear(),a.length=0,o.length=0},"clearPending");return{api:{on(e,s){n();const p=i((...y)=>s(...y),"registeredHandler"),v=t.handlers.get(e)??[];return v.push(p),t.handlers.set(e,v),()=>{const y=t.handlers.get(e);if(!y)return;const S=y.indexOf(p);S!==-1&&(y.splice(S,1),y.length===0&&t.handlers.delete(e))}},registerTool(e){if(n(),typeof e.parameters!="object"||e.parameters===null||Array.isArray(e.parameters))throw new Error(`Tool "${e.name}" registered by extension "${t.path}" must define an object parameter schema.`);t.tools.set(e.name,{definition:e,sourceInfo:t.sourceInfo}),r.refreshTools()},registerCommand(e,s){if(n(),typeof e!="string"||e.length===0)throw new Error(`Command registered by extension "${t.path}" must have a non-empty string name. Use pi.registerCommand("name", { description, handler }).`);if(typeof s?.handler!="function")throw new Error(`Command "/${e}" registered by extension "${t.path}" must define handler().`);t.commands.set(e,{name:e,sourceInfo:t.sourceInfo,...s})},registerShortcut(e,s){n(),t.shortcuts.set(e,{shortcut:e,extensionPath:t.path,...s})},registerFlag(e,s){if(n(),s.default!==void 0&&typeof s.default!==s.type)throw new Error(`Invalid default for flag "${e}": expected ${s.type}, got ${typeof s.default}`);t.flags.set(e,{name:e,extensionPath:t.path,...s}),s.default!==void 0&&!r.flagValues.has(e)&&(l==="loading"?c.has(e)||c.set(e,s.default):r.flagValues.set(e,s.default))},registerMessageRenderer(e,s){n(),t.messageRenderers.set(e,s)},registerMarkdownTransformer(e){n(),t.markdownTransformer=e},registerEntryRenderer(e,s){n(),t.entryRenderers??=new Map,t.entryRenderers.set(e,s)},registerToolRenderer(e){n(),t.toolRenderers??=[],t.toolRenderers.push(e)},getFlag(e){if(n(),!!t.flags.has(e))return r.flagValues.has(e)?r.flagValues.get(e):c.get(e)},sendMessage(e,s){n(),r.sendMessage(e,s)},sendUserMessage(e,s){n(),r.sendUserMessage(e,s)},appendEntry(e,s){n(),r.appendEntry(e,s)},emitHostEvent(e,s){n(),r.emitHostEvent?.(e,s)},setSessionName(e){n(),r.setSessionName(e)},getSessionName(){return n(),r.getSessionName()},setLabel(e,s){n(),r.setLabel(e,s)},exec(e,s,p){return n(),W(e,s,p?.cwd??u,p)},getActiveTools(){return n(),r.getActiveTools()},getAllTools(){return n(),r.getAllTools()},getSettings(){return n(),r.getSettings()},setActiveTools(e){n(),r.setActiveTools(e)},isToolAllowed(e){return n(),r.isToolAllowed(e)},getToolAllowlist(){return n(),r.getToolAllowlist()},getToolDenylist(){return n(),r.getToolDenylist?.()},getCommands(){return n(),r.getCommands()},setModel(e){return n(),r.setModel(e)},getThinkingLevel(){return n(),r.getThinkingLevel()},setThinkingLevel(e){n(),r.setThinkingLevel(e)},registerModelPickerEntry(e,s){n(),t.modelPickerEntries??=new Map,t.modelPickerEntries.set(e,{...s,id:e,extensionPath:t.path})},registerProvider(e,s){if(n(),typeof e=="string"){if(!s)throw new Error("Provider config is required when registering by name");f(()=>r.registerProvider(e,s,t.path));return}f(()=>r.registerNativeProvider(e,t.path))},unregisterProvider(e){n(),f(()=>r.unregisterProvider(e,t.path))},registerMcpServer(e,s){n();const p=X(e,s);if(typeof p=="string")throw new Error(`Invalid MCP server registered by extension "${t.path}": ${p}`);const v=r.mcpServers.get(e)?.extensionPath;if(v!==void 0&&v!==t.path)throw new Error(`MCP server "${e}" is already registered by extension "${v}"`);const y=r.mcpServers.list().find(A=>A.name!==e&&I(A.name)===I(e));if(y)throw new Error(`MCP server "${e}" conflicts with registered server "${y.name}"`);const S={name:e,config:structuredClone(p),extensionPath:t.path};f(()=>r.mcpServers.register(S))},unregisterMcpServer(e){n(),f(()=>r.mcpServers.unregister(e,t.path))},getMcpServers(){return n(),r.mcpServers.list()},registerVirtualModel(e){n();const s={...e,route:i(p=>e.route(p,r.createContext()),"route")};f(()=>r.registerVirtualModel(s,t.path))},unregisterVirtualModel(e,s){n(),f(()=>r.unregisterVirtualModel(e,s))},events:{emit(e,s){n(),d.emit(e,s)},on(e,s){n();const p=r.trackEventBusSubscription(d.on(e,s));return l==="loading"&&o.push(p),p}}},commit:i(()=>{if(l==="loading"){r.assertActive();for(const[e,s]of c)r.flagValues.has(e)||r.flagValues.set(e,s);for(const e of a)e();l="active",h()}},"commit"),discard:i(()=>{if(l==="loading"){l="failed";for(const e of o)e();h()}},"discard")}}i(ue,"createExtensionAPI");function D(t){return t!==void 0&&x===t.cwd&&T===t.generation}i(D,"isCurrentCacheToken");async function pe(t,r){if(D(r)){const l=k.get(t);if(l)return l}const u=await ie(),d=V?{virtualModules:await L(),tryNative:!1}:oe?{virtualModules:await L(),tsconfigPaths:!0}:{alias:ae()},o=await u(import.meta.url,{moduleCache:!1,...d}).import(t,{default:!0});if(typeof o=="function")return D(r)&&k.set(t,o),o}i(pe,"loadExtensionModule");function fe(t,r){const u=ee(t)??"local",d=te(t)?void 0:g.dirname(r);return{path:t,resolvedPath:r,sourceInfo:Z(t,{source:u,baseDir:d}),handlers:new Map,tools:new Map,messageRenderers:new Map,entryRenderers:new Map,commands:new Map,flags:new Map,shortcuts:new Map}}i(fe,"createExtension");async function z(t,r,u,d,c,a,o){const l=fe(r,u),n=ue(l,a,d,c),f=globalThis[se],h=typeof f=="function"?f(n.api,{extensionPath:r,resolvedPath:u}):n.api;try{await t(re(h,o)),n.commit()}catch(m){throw n.discard(),m}return j(`${r} factory`,"extensions"),l}i(z,"initializeExtension");async function ge(t,r,u,d,c){const a=E(t,r,{normalizeUnicodeSpaces:!0});try{const o=K(a),l=Q(o?.manifest);if(l)return{extension:null,error:l};const n=await pe(a,c);return j(`${t} module import`,"extensions"),n?{extension:await z(n,t,a,r,u,d,o?.manifest.permissions),error:null}:{extension:null,error:`Extension does not export a valid factory function: ${t}`}}catch(o){return{extension:null,error:`Failed to load extension: ${o instanceof Error?o.message:String(o)}`}}}i(ge,"loadExtension");async function Ae(t,r,u,d,c="<inline>"){const a=E(r);return z(t,c,c,a,u,d)}i(Ae,"loadExtensionFromFactory");async function F(t,r,u,d,c=!1){const a=[],o=[],l=[],n=c?le(r):void 0,f=n?.cwd??E(r),h=u??q(),m=d??de();for(const e of t){const{extension:s,error:p}=await ge(e,f,h,m,n);if(p){o.push({path:e,error:p});continue}s&&a.push(s)}return{extensions:a,errors:o,warnings:l,runtime:m}}i(F,"loadExtensionsInternal");async function he(t,r,u,d){return F(t,r,u,d)}i(he,"loadExtensions");async function Re(t,r,u,d){return F(t,r,u,d,!0)}i(Re,"loadExtensionsCached");function me(t){return t.endsWith(".ts")||t.endsWith(".js")}i(me,"isExtensionFile");function U(t){const r=g.join(t,"package.json");if(w.existsSync(r)){const c=Y(r);if(c?.extensions?.length){const a=[];for(const o of c.extensions){const l=g.resolve(t,o);w.existsSync(l)&&a.push(l)}if(a.length>0)return a}}const u=g.join(t,"index.ts"),d=g.join(t,"index.js");return w.existsSync(u)?[u]:w.existsSync(d)?[d]:null}i(U,"resolveExtensionEntries");function C(t){if(!w.existsSync(t))return[];const r=[];try{const u=w.readdirSync(t,{withFileTypes:!0});for(const d of u){const c=g.join(t,d.name);if((d.isFile()||d.isSymbolicLink())&&me(d.name)){r.push(c);continue}if(d.isDirectory()||d.isSymbolicLink()){const a=U(c);a&&r.push(...a)}}}catch{return[]}return r}i(C,"discoverExtensionsInDir");async function Ie(t,r,u=J(),d){const c=E(r),a=E(u),o=[],l=new Set,n=i(m=>{for(const e of m){const s=g.resolve(e);l.has(s)||(l.add(s),o.push(e))}},"addPaths"),f=g.join(c,O,"extensions");n(C(f));const h=g.join(a,"extensions");n(C(h));for(const m of t){const e=E(m,c,{normalizeUnicodeSpaces:!0});if(w.existsSync(e)&&w.statSync(e).isDirectory()){const s=U(e);if(s){n(s);continue}n(C(e));continue}n([e])}return he(o,c,d)}i(Ie,"discoverAndLoadExtensions");export{se as EXTENSION_API_DECORATOR_SLOT,ce as clearExtensionCache,de as createExtensionRuntime,Ie as discoverAndLoadExtensions,Ae as loadExtensionFromFactory,he as loadExtensions,Re as loadExtensionsCached};
1
+ var B=Object.defineProperty;var i=(t,r)=>B(t,"name",{value:r,configurable:!0});import*as w from"node:fs";import{createRequire as _}from"node:module";import*as g from"node:path";import{fileURLToPath as b}from"node:url";import{CONFIG_DIR_NAME as O,getAgentDir as J,isBunBinary as R,isBundledNode as H}from"../../config.js";import{resolvePath as E}from"../../utils/paths.js";import{createEventBus as q}from"../event-bus.js";import{execCommand as W}from"../exec.js";import{McpServerRegistry as G,mcpNamespace as I,validateMcpServerConfig as X}from"../mcp-servers.js";import{findNearestPiManifest as K,getExtensionApiMismatchError as Q,readPiManifest as Y}from"../pi-manifest.js";import{createSyntheticSourceInfo as Z,getSyntheticPathSource as ee,isSyntheticPath as te}from"../source-info.js";import{time as j}from"../timings.js";import{applyPermissionSurface as re}from"./permission-surface.js";const P=_(import.meta.url),se=Symbol.for("dalcode.extensions.apiDecorator"),ne="sea"in process.features&&process.features.sea===!0||process.getBuiltinModule("node:sea")?.isSea()===!0,oe=!R&&g.extname(b(import.meta.url))===".ts",V=R||ne||H;let N;function ie(){return N??=(V?import("./jiti-static-loader.js"):import("./jiti-loader.js")).then(t=>t.createJiti),N}i(ie,"getCreateJiti");let $;function L(){return $??=import("./virtual-modules.js").then(t=>t.VIRTUAL_MODULES),$}i(L,"getVirtualModules");let M=null;function ae(){if(M)return M;const t=g.dirname(b(import.meta.url)),r=g.resolve(t,"../..","index.js"),p=P.resolve("typebox"),d=P.resolve("typebox/compile"),c=P.resolve("typebox/value"),a=g.resolve(t,"../../../../"),o=i((s,u)=>{const v=g.join(a,s);return w.existsSync(v)?v:b(import.meta.resolve(u))},"resolveWorkspaceOrImport"),l=r,n=o("agent/dist/index.js","@earendil-works/pi-agent-core"),f=o("tui/dist/index.js","@earendil-works/pi-tui"),h=o("ai/dist/compat.js","@earendil-works/pi-ai/compat"),m=o("ai/dist/oauth.js","@earendil-works/pi-ai/oauth"),e=o("ai/dist/providers/all.js","@earendil-works/pi-ai/providers/all");return M={"@earendil-works/pi-coding-agent":l,"@earendil-works/pi-agent-core":n,"@earendil-works/pi-tui":f,"@earendil-works/pi-ai/providers/all":e,"@earendil-works/pi-ai/compat":h,"@earendil-works/pi-ai/oauth":m,"@earendil-works/pi-ai":h,"@mariozechner/pi-coding-agent":l,"@mariozechner/pi-agent-core":n,"@mariozechner/pi-tui":f,"@mariozechner/pi-ai/providers/all":e,"@mariozechner/pi-ai/compat":h,"@mariozechner/pi-ai/oauth":m,"@mariozechner/pi-ai":h,typebox:p,"typebox/compile":d,"typebox/value":c,"@sinclair/typebox":p,"@sinclair/typebox/compile":d,"@sinclair/typebox/value":c},M}i(ae,"getAliases");let x,T=0;const k=new Map;function ce(){k.clear(),x=void 0,T++}i(ce,"clearExtensionCache");function le(t){const r=E(t);return x!==void 0&&x!==r&&ce(),x=r,{cwd:r,generation:T}}i(le,"useExtensionCacheCwd");function de(){const t=i(()=>{throw new Error("Extension runtime not initialized. Action methods cannot be called during extension loading.")},"notInitialized"),r={},p=new Set,d=i(()=>{if(r.staleMessage)throw new Error(r.staleMessage)},"assertActive"),c={sendMessage:t,sendUserMessage:t,appendEntry:t,appendUsage:t,emitHostEvent:i(()=>{},"emitHostEvent"),setSessionName:t,getSessionName:t,setLabel:t,getActiveTools:t,getAllTools:t,getSettings:t,setActiveTools:t,isToolAllowed:t,getToolAllowlist:t,refreshTools:i(()=>{},"refreshTools"),getCommands:t,setModel:i(()=>Promise.reject(new Error("Extension runtime not initialized")),"setModel"),getThinkingLevel:t,setThinkingLevel:t,flagValues:new Map,pendingProviderRegistrations:[],pendingNativeProviderRegistrations:[],mcpServers:new G,pendingVirtualModelRegistrations:[],createContext:t,assertActive:d,invalidate:i(a=>{if(!r.staleMessage){r.staleMessage=a??"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().";for(const o of p)o();p.clear()}},"invalidate"),trackEventBusSubscription:i(a=>{let o=!0;const l=i(()=>{o&&(o=!1,p.delete(l),a())},"trackedUnsubscribe");return p.add(l),l},"trackEventBusSubscription"),registerProvider:i((a,o,l="<unknown>")=>{c.pendingProviderRegistrations.push({name:a,config:o,extensionPath:l})},"registerProvider"),registerNativeProvider:i((a,o="<unknown>")=>{c.pendingNativeProviderRegistrations.push({provider:a,extensionPath:o})},"registerNativeProvider"),unregisterProvider:i(a=>{c.pendingProviderRegistrations=c.pendingProviderRegistrations.filter(o=>o.name!==a),c.pendingNativeProviderRegistrations=c.pendingNativeProviderRegistrations.filter(o=>o.provider.id!==a)},"unregisterProvider"),registerVirtualModel:i((a,o="<unknown>")=>{c.pendingVirtualModelRegistrations.push({definition:a,extensionPath:o})},"registerVirtualModel"),unregisterVirtualModel:i((a,o)=>{c.pendingVirtualModelRegistrations=c.pendingVirtualModelRegistrations.filter(({definition:l})=>l.provider!==a||l.id!==o)},"unregisterVirtualModel")};return c}i(de,"createExtensionRuntime");function pe(t,r,p,d){const c=new Map,a=[],o=[];let l="loading";const n=i(()=>{if(l==="failed")throw new Error(`Extension "${t.path}" failed to load and its API is no longer active.`);r.assertActive()},"assertActive"),f=i(e=>{l==="loading"?a.push(e):e()},"applyRuntimeChange"),h=i(()=>{c.clear(),a.length=0,o.length=0},"clearPending");return{api:{on(e,s){n();const u=i((...y)=>s(...y),"registeredHandler"),v=t.handlers.get(e)??[];return v.push(u),t.handlers.set(e,v),()=>{const y=t.handlers.get(e);if(!y)return;const S=y.indexOf(u);S!==-1&&(y.splice(S,1),y.length===0&&t.handlers.delete(e))}},registerTool(e){if(n(),typeof e.parameters!="object"||e.parameters===null||Array.isArray(e.parameters))throw new Error(`Tool "${e.name}" registered by extension "${t.path}" must define an object parameter schema.`);t.tools.set(e.name,{definition:e,sourceInfo:t.sourceInfo}),r.refreshTools()},registerCommand(e,s){if(n(),typeof e!="string"||e.length===0)throw new Error(`Command registered by extension "${t.path}" must have a non-empty string name. Use pi.registerCommand("name", { description, handler }).`);if(typeof s?.handler!="function")throw new Error(`Command "/${e}" registered by extension "${t.path}" must define handler().`);t.commands.set(e,{name:e,sourceInfo:t.sourceInfo,...s})},registerShortcut(e,s){n(),t.shortcuts.set(e,{shortcut:e,extensionPath:t.path,...s})},registerFlag(e,s){if(n(),s.default!==void 0&&typeof s.default!==s.type)throw new Error(`Invalid default for flag "${e}": expected ${s.type}, got ${typeof s.default}`);t.flags.set(e,{name:e,extensionPath:t.path,...s}),s.default!==void 0&&!r.flagValues.has(e)&&(l==="loading"?c.has(e)||c.set(e,s.default):r.flagValues.set(e,s.default))},registerMessageRenderer(e,s){n(),t.messageRenderers.set(e,s)},registerMarkdownTransformer(e){n(),t.markdownTransformer=e},registerEntryRenderer(e,s){n(),t.entryRenderers??=new Map,t.entryRenderers.set(e,s)},registerToolRenderer(e){n(),t.toolRenderers??=[],t.toolRenderers.push(e)},getFlag(e){if(n(),!!t.flags.has(e))return r.flagValues.has(e)?r.flagValues.get(e):c.get(e)},sendMessage(e,s){n(),r.sendMessage(e,s)},sendUserMessage(e,s){n(),r.sendUserMessage(e,s)},appendEntry(e,s){n(),r.appendEntry(e,s)},appendUsage(e,s){n(),r.appendUsage?.(e,s)},emitHostEvent(e,s){n(),r.emitHostEvent?.(e,s)},setSessionName(e){n(),r.setSessionName(e)},getSessionName(){return n(),r.getSessionName()},setLabel(e,s){n(),r.setLabel(e,s)},exec(e,s,u){return n(),W(e,s,u?.cwd??p,u)},getActiveTools(){return n(),r.getActiveTools()},getAllTools(){return n(),r.getAllTools()},getSettings(){return n(),r.getSettings()},setActiveTools(e){n(),r.setActiveTools(e)},isToolAllowed(e){return n(),r.isToolAllowed(e)},getToolAllowlist(){return n(),r.getToolAllowlist()},getToolDenylist(){return n(),r.getToolDenylist?.()},getCommands(){return n(),r.getCommands()},setModel(e){return n(),r.setModel(e)},getThinkingLevel(){return n(),r.getThinkingLevel()},setThinkingLevel(e){n(),r.setThinkingLevel(e)},registerModelPickerEntry(e,s){n(),t.modelPickerEntries??=new Map,t.modelPickerEntries.set(e,{...s,id:e,extensionPath:t.path})},registerProvider(e,s){if(n(),typeof e=="string"){if(!s)throw new Error("Provider config is required when registering by name");f(()=>r.registerProvider(e,s,t.path));return}f(()=>r.registerNativeProvider(e,t.path))},unregisterProvider(e){n(),f(()=>r.unregisterProvider(e,t.path))},registerMcpServer(e,s){n();const u=X(e,s);if(typeof u=="string")throw new Error(`Invalid MCP server registered by extension "${t.path}": ${u}`);const v=r.mcpServers.get(e)?.extensionPath;if(v!==void 0&&v!==t.path)throw new Error(`MCP server "${e}" is already registered by extension "${v}"`);const y=r.mcpServers.list().find(A=>A.name!==e&&I(A.name)===I(e));if(y)throw new Error(`MCP server "${e}" conflicts with registered server "${y.name}"`);const S={name:e,config:structuredClone(u),extensionPath:t.path};f(()=>r.mcpServers.register(S))},unregisterMcpServer(e){n(),f(()=>r.mcpServers.unregister(e,t.path))},getMcpServers(){return n(),r.mcpServers.list()},registerVirtualModel(e){n();const s={...e,route:i(u=>e.route(u,r.createContext()),"route")};f(()=>r.registerVirtualModel(s,t.path))},unregisterVirtualModel(e,s){n(),f(()=>r.unregisterVirtualModel(e,s))},events:{emit(e,s){n(),d.emit(e,s)},on(e,s){n();const u=r.trackEventBusSubscription(d.on(e,s));return l==="loading"&&o.push(u),u}}},commit:i(()=>{if(l==="loading"){r.assertActive();for(const[e,s]of c)r.flagValues.has(e)||r.flagValues.set(e,s);for(const e of a)e();l="active",h()}},"commit"),discard:i(()=>{if(l==="loading"){l="failed";for(const e of o)e();h()}},"discard")}}i(pe,"createExtensionAPI");function D(t){return t!==void 0&&x===t.cwd&&T===t.generation}i(D,"isCurrentCacheToken");async function ue(t,r){if(D(r)){const l=k.get(t);if(l)return l}const p=await ie(),d=V?{virtualModules:await L(),tryNative:!1}:oe?{virtualModules:await L(),tsconfigPaths:!0}:{alias:ae()},o=await p(import.meta.url,{moduleCache:!1,...d}).import(t,{default:!0});if(typeof o=="function")return D(r)&&k.set(t,o),o}i(ue,"loadExtensionModule");function fe(t,r){const p=ee(t)??"local",d=te(t)?void 0:g.dirname(r);return{path:t,resolvedPath:r,sourceInfo:Z(t,{source:p,baseDir:d}),handlers:new Map,tools:new Map,messageRenderers:new Map,entryRenderers:new Map,commands:new Map,flags:new Map,shortcuts:new Map}}i(fe,"createExtension");async function U(t,r,p,d,c,a,o){const l=fe(r,p),n=pe(l,a,d,c),f=globalThis[se],h=typeof f=="function"?f(n.api,{extensionPath:r,resolvedPath:p}):n.api;try{await t(re(h,o)),n.commit()}catch(m){throw n.discard(),m}return j(`${r} factory`,"extensions"),l}i(U,"initializeExtension");async function ge(t,r,p,d,c){const a=E(t,r,{normalizeUnicodeSpaces:!0});try{const o=K(a),l=Q(o?.manifest);if(l)return{extension:null,error:l};const n=await ue(a,c);return j(`${t} module import`,"extensions"),n?{extension:await U(n,t,a,r,p,d,o?.manifest.permissions),error:null}:{extension:null,error:`Extension does not export a valid factory function: ${t}`}}catch(o){return{extension:null,error:`Failed to load extension: ${o instanceof Error?o.message:String(o)}`}}}i(ge,"loadExtension");async function Ae(t,r,p,d,c="<inline>"){const a=E(r);return U(t,c,c,a,p,d)}i(Ae,"loadExtensionFromFactory");async function z(t,r,p,d,c=!1){const a=[],o=[],l=[],n=c?le(r):void 0,f=n?.cwd??E(r),h=p??q(),m=d??de();for(const e of t){const{extension:s,error:u}=await ge(e,f,h,m,n);if(u){o.push({path:e,error:u});continue}s&&a.push(s)}return{extensions:a,errors:o,warnings:l,runtime:m}}i(z,"loadExtensionsInternal");async function he(t,r,p,d){return z(t,r,p,d)}i(he,"loadExtensions");async function Re(t,r,p,d){return z(t,r,p,d,!0)}i(Re,"loadExtensionsCached");function me(t){return t.endsWith(".ts")||t.endsWith(".js")}i(me,"isExtensionFile");function F(t){const r=g.join(t,"package.json");if(w.existsSync(r)){const c=Y(r);if(c?.extensions?.length){const a=[];for(const o of c.extensions){const l=g.resolve(t,o);w.existsSync(l)&&a.push(l)}if(a.length>0)return a}}const p=g.join(t,"index.ts"),d=g.join(t,"index.js");return w.existsSync(p)?[p]:w.existsSync(d)?[d]:null}i(F,"resolveExtensionEntries");function C(t){if(!w.existsSync(t))return[];const r=[];try{const p=w.readdirSync(t,{withFileTypes:!0});for(const d of p){const c=g.join(t,d.name);if((d.isFile()||d.isSymbolicLink())&&me(d.name)){r.push(c);continue}if(d.isDirectory()||d.isSymbolicLink()){const a=F(c);a&&r.push(...a)}}}catch{return[]}return r}i(C,"discoverExtensionsInDir");async function Ie(t,r,p=J(),d){const c=E(r),a=E(p),o=[],l=new Set,n=i(m=>{for(const e of m){const s=g.resolve(e);l.has(s)||(l.add(s),o.push(e))}},"addPaths"),f=g.join(c,O,"extensions");n(C(f));const h=g.join(a,"extensions");n(C(h));for(const m of t){const e=E(m,c,{normalizeUnicodeSpaces:!0});if(w.existsSync(e)&&w.statSync(e).isDirectory()){const s=F(e);if(s){n(s);continue}n(C(e));continue}n([e])}return he(o,c,d)}i(Ie,"discoverAndLoadExtensions");export{se as EXTENSION_API_DECORATOR_SLOT,ce as clearExtensionCache,de as createExtensionRuntime,Ie as discoverAndLoadExtensions,Ae as loadExtensionFromFactory,he as loadExtensions,Re as loadExtensionsCached};
@@ -1 +1 @@
1
- var g=Object.defineProperty;var o=(e,s)=>g(e,"name",{value:s,configurable:!0});const a={tools:["registerTool","getActiveTools","getAllTools","setActiveTools","isToolAllowed","getToolAllowlist","getToolDenylist"],commands:["registerCommand","registerShortcut","registerFlag","getFlag","getCommands"],session:["sendMessage","sendUserMessage","appendEntry","emitHostEvent","setSessionName","getSessionName","setLabel"],providers:["registerProvider","unregisterProvider","setModel","getThinkingLevel","setThinkingLevel","registerModelPickerEntry"],subprocess:["exec"]};function c(e,s){return`Extension did not declare pi.permissions "${e}"; ${s} is unavailable.`}o(c,"deniedPermissionMessage");function u(e,s){if(s===void 0)return e;const i=new Set(s),t={...e};for(const[n,l]of Object.entries(a))if(!i.has(n))for(const r of l){const d=o(()=>{throw new Error(c(n,String(r)))},"denied");t[r]=d}return t}o(u,"applyPermissionSurface");export{u as applyPermissionSurface,c as deniedPermissionMessage};
1
+ var g=Object.defineProperty;var o=(e,s)=>g(e,"name",{value:s,configurable:!0});const a={tools:["registerTool","getActiveTools","getAllTools","setActiveTools","isToolAllowed","getToolAllowlist","getToolDenylist"],commands:["registerCommand","registerShortcut","registerFlag","getFlag","getCommands"],session:["sendMessage","sendUserMessage","appendEntry","appendUsage","emitHostEvent","setSessionName","getSessionName","setLabel"],providers:["registerProvider","unregisterProvider","setModel","getThinkingLevel","setThinkingLevel","registerModelPickerEntry"],subprocess:["exec"]};function c(e,s){return`Extension did not declare pi.permissions "${e}"; ${s} is unavailable.`}o(c,"deniedPermissionMessage");function u(e,s){if(s===void 0)return e;const i=new Set(s),t={...e};for(const[n,l]of Object.entries(a))if(!i.has(n))for(const r of l){const d=o(()=>{throw new Error(c(n,String(r)))},"denied");t[r]=d}return t}o(u,"applyPermissionSurface");export{u as applyPermissionSurface,c as deniedPermissionMessage};
@@ -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 m=Object.defineProperty;var t=(e,n)=>m(e,"name",{value:n,configurable:!0});import{existsSync as h,realpathSync as p}from"node:fs";import{isAbsolute as y,relative as b,resolve as v}from"node:path";import{isReadOnlyBashCommand as R}from"../tools/bash-read-only.js";import{resolveToCwd as k}from"../tools/path-utils.js";import{matchPermissionRules as S,pathPatternMatches as g,readDenyPatterns as w,targetPathOf as x}from"./rules.js";const d=Symbol.for("dal.permissions.askHandlers"),a=globalThis;a[d]instanceof Set||(a[d]=new Set);const c=a[d];function O(e){return c.add(e),()=>{c.delete(e)}}t(O,"registerPermissionAskHandler");function j(){return[...c]}t(j,"permissionAskHandlers");let u;function B(e){u=e}t(B,"setProcessReadGuard");function l(e,n){const r=b(n,e);return r===""||!r.startsWith("..")&&!y(r)}t(l,"isWithin");function f(e){try{return h(e)?p(e):e}catch{return e}}t(f,"realpathOrSelf");function P(e,n=u){if(!n)return;const r=[...new Set([v(e),f(e)])];for(const s of n.deniedPaths){const o=f(s);if(r.some(i=>l(i,s)||l(i,o)))return`Reading ${e} is blocked: it is a protected credential location (${s}). The sandbox keeps it unreadable for every tool.`}for(const{pattern:s,rule:o}of n.deniedPatterns)if(r.some(i=>g(s,i,n.cwd)))return`Reading ${e} is blocked by the permission rule ${o}.`}t(P,"readAccessDenial");const A=new Set(["read","grep","find","ls","lsp"]);function C(e,n){if(A.has(e.toolName)&&n.readGuard){const s=x(e);if(s!==void 0){const o=P(k(s,e.cwd),n.readGuard);if(o)return{behavior:"deny",reason:o}}}const r=S(n.rules,e,R);if(r?.behavior==="deny")return{behavior:"deny",reason:`Blocked by the permission rule ${r.rule} (${r.source==="user"?"~/.dal/agent/settings.json":".dal/settings.json"}).`};if(r?.behavior==="ask")return{behavior:"ask",rule:r.rule,source:r.source}}t(C,"evaluateToolPolicy");function L(e){const n=w(e.rules),r=e.protectedReads??[];if(!(r.length===0&&n.length===0))return{cwd:e.cwd,deniedPaths:r,deniedPatterns:n}}t(L,"buildReadGuard");export{L as buildReadGuard,C as evaluateToolPolicy,j as permissionAskHandlers,P as readAccessDenial,O as registerPermissionAskHandler,B as setProcessReadGuard};
1
+ var m=Object.defineProperty;var t=(e,n)=>m(e,"name",{value:n,configurable:!0});import{existsSync as p,realpathSync as h}from"node:fs";import{isAbsolute as y,relative as b,resolve as v,sep as R}from"node:path";import{isReadOnlyBashCommand as k}from"../tools/bash-read-only.js";import{resolveToCwd as S}from"../tools/path-utils.js";import{matchPermissionRules as g,pathPatternMatches as w,readDenyPatterns as x,targetPathOf as P}from"./rules.js";const d=Symbol.for("dal.permissions.askHandlers"),a=globalThis;a[d]instanceof Set||(a[d]=new Set);const c=a[d];function j(e){return c.add(e),()=>{c.delete(e)}}t(j,"registerPermissionAskHandler");function B(){return[...c]}t(B,"permissionAskHandlers");let u;function C(e){u=e}t(C,"setProcessReadGuard");function l(e,n){const r=b(n,e);return r===""||r!==".."&&!r.startsWith(`..${R}`)&&!y(r)}t(l,"isWithin");function f(e){try{return p(e)?h(e):e}catch{return e}}t(f,"realpathOrSelf");function A(e,n=u){if(!n)return;const r=[...new Set([v(e),f(e)])];for(const s of n.deniedPaths){const o=f(s);if(r.some(i=>l(i,s)||l(i,o)))return`Reading ${e} is blocked: it is a protected credential location (${s}). The sandbox keeps it unreadable for every tool.`}for(const{pattern:s,rule:o}of n.deniedPatterns)if(r.some(i=>w(s,i,n.cwd)))return`Reading ${e} is blocked by the permission rule ${o}.`}t(A,"readAccessDenial");const $=new Set(["read","grep","find","ls","lsp"]);function L(e,n){if($.has(e.toolName)&&n.readGuard){const s=P(e);if(s!==void 0){const o=A(S(s,e.cwd),n.readGuard);if(o)return{behavior:"deny",reason:o}}}const r=g(n.rules,e,k);if(r?.behavior==="deny")return{behavior:"deny",reason:`Blocked by the permission rule ${r.rule} (${r.source==="user"?"~/.dal/agent/settings.json":".dal/settings.json"}).`};if(r?.behavior==="ask")return{behavior:"ask",rule:r.rule,source:r.source}}t(L,"evaluateToolPolicy");function M(e){const n=x(e.rules),r=e.protectedReads??[];if(!(r.length===0&&n.length===0))return{cwd:e.cwd,deniedPaths:r,deniedPatterns:n}}t(M,"buildReadGuard");export{M as buildReadGuard,L as evaluateToolPolicy,B as permissionAskHandlers,A as readAccessDenial,j as registerPermissionAskHandler,C as setProcessReadGuard};
@@ -0,0 +1,16 @@
1
+ export type PackageManagerName = "npm" | "pnpm" | "yarn" | "bun";
2
+ export interface ProjectFacts {
3
+ root: string;
4
+ manager?: PackageManagerName;
5
+ managerSource?: string;
6
+ otherLockfiles: string[];
7
+ testConfigPackages: string[];
8
+ rootTestConfig: boolean;
9
+ }
10
+ export declare function findProjectRoot(cwd: string): string | undefined;
11
+ export declare function detectProjectFacts(cwd: string): ProjectFacts | undefined;
12
+ export declare function projectPackageManager(dir: string): {
13
+ manager: PackageManagerName;
14
+ source: string;
15
+ } | undefined;
16
+ export declare function describeProjectFacts(cwd: string): string | undefined;
@@ -0,0 +1,2 @@
1
+ var b=Object.defineProperty;var o=(n,e)=>b(n,"name",{value:e,configurable:!0});import{existsSync as g,readdirSync as d,readFileSync as k,statSync as F}from"node:fs";import{dirname as M,join as s,relative as T,resolve as y}from"node:path";const u=[{file:"package-lock.json",manager:"npm"},{file:"npm-shrinkwrap.json",manager:"npm"},{file:"pnpm-lock.yaml",manager:"pnpm"},{file:"yarn.lock",manager:"yarn"},{file:"bun.lock",manager:"bun"},{file:"bun.lockb",manager:"bun"}],L=/^(?:vitest|vite|jest)\.config\.(?:[cm]?[jt]s|json)$/,m=12;function h(n){try{const e=JSON.parse(k(n,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}catch{return}}o(h,"readJson");function j(n){if(typeof n!="string")return;const e=n.split("@")[0];return e==="npm"||e==="pnpm"||e==="yarn"||e==="bun"?e:void 0}o(j,"managerFromField");function $(n){try{return d(n).some(e=>L.test(e))}catch{return!1}}o($,"hasTestConfig");function x(n,e){const r=[],a=e?.workspaces;if(Array.isArray(a))r.push(...a.filter(t=>typeof t=="string"));else if(a&&typeof a=="object"){const t=a.packages;Array.isArray(t)&&r.push(...t.filter(c=>typeof c=="string"))}try{const t=k(s(n,"pnpm-workspace.yaml"),"utf8");for(const c of t.matchAll(/^\s*-\s*['"]?([^'"\n#]+?)['"]?\s*$/gm))r.push(c[1])}catch{}const i=new Set;for(const t of r)if(!t.startsWith("!"))if(t.endsWith("/*")){const c=s(n,t.slice(0,-2));try{for(const p of d(c,{withFileTypes:!0}))p.isDirectory()&&i.add(s(c,p.name))}catch{}}else/[*?]/.test(t)||i.add(s(n,t));return[...i].sort()}o(x,"workspaceDirs");function v(n){return["package.json","pnpm-workspace.yaml",...u.map(e=>e.file)].map(e=>{try{return`${e}:${F(s(n,e)).mtimeMs}`}catch{return`${e}:-`}}).join("|")}o(v,"versionKey");function E(n){let e=y(n);for(;;){if(u.some(a=>g(s(e,a.file)))||j(h(s(e,"package.json"))?.packageManager))return e;if(g(s(e,".git")))return;const r=M(e);if(r===e)return;e=r}}o(E,"findProjectRoot");const w=new Map;function S(n){const e=E(n);if(!e)return;const r=v(e),a=w.get(e);if(a?.key===r)return a.facts;const i=h(s(e,"package.json")),t=u.filter(f=>g(s(e,f.file))),c=j(i?.packageManager),p=c??t[0]?.manager,P=c?"packageManager in package.json":t[0]?.file,A=t.filter(f=>f.manager!==p).map(f=>f.file),C=x(e,i).filter($).map(f=>T(e,f)),l={root:e,...p?{manager:p,managerSource:P}:{},otherLockfiles:A,testConfigPackages:C,rootTestConfig:$(e)};return w.set(e,{key:r,facts:l}),l}o(S,"detectProjectFacts");function O(n){const e=S(n);return e?.manager&&e.managerSource?{manager:e.manager,source:e.managerSource}:void 0}o(O,"projectPackageManager");function _(n){const e=S(n);if(!e)return;const r=[],a=e.root===y(n)?"":` (project root ${e.root.replace(/\\/g,"/")})`;if(e.manager&&r.push(`Package manager: ${e.manager}, from ${e.managerSource}${a}. Install and run scripts with ${e.manager} only.`),e.otherLockfiles.length>0&&r.push(`Also present, not in use: ${e.otherLockfiles.join(", ")}.`),e.testConfigPackages.length>0){const i=e.testConfigPackages.slice(0,m).join(", "),t=e.testConfigPackages.length>m?` and ${e.testConfigPackages.length-m} more`:"";r.push(`Packages with their own test config: ${i}${t}. Run a package's tests from its directory, where its config and setup files apply${e.rootTestConfig?"":"; the root has no test config of its own"}.`)}return r.length>0?r.join(`
2
+ `):void 0}o(_,"describeProjectFacts");export{_ as describeProjectFacts,S as detectProjectFacts,E as findProjectRoot,O as projectPackageManager};