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 +1 @@
1
- var ht=Object.defineProperty;var P=(l,t)=>ht(l,"name",{value:t,configurable:!0});import{existsSync as f,readdirSync as lt,readFileSync as B,statSync as T}from"node:fs";import{basename as ct,dirname as q,join as m,resolve as S,sep as b}from"node:path";import{detectCapabilities as pt,getTerminalColorMode as mt}from"@earendil-works/pi-tui";import Q from"chalk";import{APP_NAME as dt,CONFIG_DIR_NAME as v,getExamplesPath as ut}from"../config.js";import{dalBuiltinExtensionPaths as ft}from"../dal/builtins.js";import{fill as $,t as y}from"../dal/i18n.js";import{loadThemeFromPath as Pt}from"../modes/interactive/theme/theme.js";import{canonicalizePath as M,isLocalPath as j,resolvePath as w}from"../utils/paths.js";import{stripBom as W}from"../utils/text.js";import{createEventBus as gt}from"./event-bus.js";import{clearExtensionCache as xt,createExtensionRuntime as St,loadExtensionFromFactory as Z,loadExtensionsCached as tt}from"./extensions/loader.js";import{findGitPaths as yt}from"./footer-data-provider.js";import{DefaultPackageManager as wt}from"./package-manager.js";import{loadPromptTemplates as vt}from"./prompt-templates.js";import{SettingsManager as kt}from"./settings-manager.js";import{loadSkills as Et}from"./skills.js";import{BUILTIN_PATH_PREFIX as k,createSourceInfo as I,getSyntheticPathSource as Ft,isSyntheticPath as N}from"./source-info.js";import{resetTimings as Dt}from"./timings.js";const Tt=new Set(["@earendil-works/pi-agent-core","@earendil-works/pi-ai","@earendil-works/pi-coding-agent","@earendil-works/pi-tui","@mariozechner/pi-agent-core","@mariozechner/pi-ai","@mariozechner/pi-coding-agent","@mariozechner/pi-tui","@sinclair/typebox","typebox"]);function et(l,t){const n=[],s=new Set(l.map(i=>t.get(i)?.packageRoot).filter(i=>i!==void 0));for(const i of s){const e=m(i,"package.json");if(!f(e))continue;const o=JSON.parse(W(B(e,"utf-8")));if(typeof o.dependencies!="object"||o.dependencies===null||Array.isArray(o.dependencies))continue;const a=Object.keys(o.dependencies).filter(c=>Tt.has(c)).sort();a.length!==0&&n.push({path:e,warning:`Host-provided extension packages must be declared in peerDependencies with a "*" range, not dependencies: ${a.join(", ")}. Installed copies can bypass the extension loader and create duplicate runtime modules.`})}return n}P(et,"collectExtensionPackageWarnings");function A(l,t){l.warnings=[...new Map([...l.warnings??[],...t].map(n=>[n.path,n])).values()]}P(A,"mergeExtensionWarnings");function st(l){return typeof l!="function"&&l.builtin===!0}P(st,"isBuiltinExtension");let it;function bt(l){return it??=new Set(ft().map(t=>S(t))),it.has(S(l))}P(bt,"isDalBundledExtensionPath");function nt(l,t){const n=P(i=>[...[...i.tools.keys()].map(e=>`tool:${e}`),...[...i.commands.keys()].map(e=>`command:${e}`),...[...i.flags.keys()].map(e=>`flag:${e}`)],"names"),s=new Map(l.filter(i=>!i.replaceable).flatMap(i=>n(i).map(e=>[e,i])));return l.filter(i=>{if(!i.replaceable)return!0;const e=n(i).map(o=>({name:o,extension:s.get(o)})).find(o=>o.extension!==void 0);if(!e)return!0;if(i.path.startsWith(k)&&!bt(e.extension.path)){const o=i.path.slice(k.length),[a,c]=e.name.split(":",2),h=a==="command"?`/${c}`:a==="flag"?`--${c}`:c;t?.push({path:i.path,warning:$(y("\u6269\u5C55 {path} \u6CE8\u518C\u4E86{kind} `{name}`\uFF0C\u6240\u4EE5\u5185\u7F6E\u6269\u5C55 `{builtin}` \u6CA1\u6709\u52A0\u8F7D\u3002\u8981\u4F7F\u7528 `{builtin}`\uFF0C\u8FD0\u884C `{app} config`\uFF0C\u5728\u5185\u7F6E\u6269\u5C55\u91CC\u786E\u8BA4\u5B83\u5DF2\u542F\u7528\uFF0C\u7136\u540E\u505C\u7528\u6216\u79FB\u9664\u8FD9\u4E2A\u6269\u5C55\u3002\u4E24\u8005\u6700\u597D\u53EA\u4FDD\u7559\u4E00\u4E2A\u3002"),{path:e.extension.path,kind:a==="command"?y("\u4E00\u4E2A\u547D\u4EE4"):a==="flag"?y("\u4E00\u4E2A\u53C2\u6570"):y("\u4E00\u4E2A\u5DE5\u5177"),name:h,builtin:o,app:dt})})}return!1})}P(nt,"omitReplacedExtensions");function ot(l,t){if(l){if(f(l))try{return W(B(l,"utf-8"))}catch(n){return console.error(Q.yellow($(y("\u8B66\u544A\uFF1A\u65E0\u6CD5\u8BFB\u53D6{what}\u6587\u4EF6 {path}\uFF1A{error}"),{what:t,path:l,error:String(n)}))),l}return l}}P(ot,"resolvePromptInput");function z(l){const t=["AGENTS.override.md","AGENTS.md","AGENTS.MD","CLAUDE.md","CLAUDE.MD"];for(const n of t){const s=m(l,n);if(f(s))try{if(!T(s).isFile())continue;return{path:s,content:W(B(s,"utf-8"))}}catch(i){console.error(Q.yellow($(y("\u8B66\u544A\uFF1A\u65E0\u6CD5\u8BFB\u53D6 {path}\uFF1A{error}"),{path:s,error:String(i)})))}}return null}P(z,"loadContextFileFromDir");function Mt(l){const t=yt(l);if(!t)return;const n=M(t.commonGitDir),s=M(t.repoDir),i=q(n);if(!s.startsWith(`${i}${b}`)||M(m(i,".git"))!==n)return;const e=z(s);return e?m(i,ct(e.path)):void 0}P(Mt,"findShadowedContextFile");function It(l){const t=w(l.cwd),n=w(l.agentDir),s=[],i=new Set,e=z(n);e&&(s.push(e),i.add(e.path));const o=[],a=Mt(t);let c=t;for(;;){const h=z(c),g=a!==void 0&&M(h?.path??"")===a;h&&!g&&!i.has(h.path)&&(o.unshift(h),i.add(h.path));const x=q(c);if(x===c)break;c=x}return s.push(...o),s}P(It,"loadProjectContextFiles");class qt{static{P(this,"DefaultResourceLoader")}cwd;agentDir;settingsManager;eventBus;packageManager;additionalExtensionPaths;additionalSkillPaths;additionalPromptTemplatePaths;additionalThemePaths;extensionFactories;builtinExtensions;noExtensions;disabledBuiltinExtensions;noSkills;noPromptTemplates;noThemes;noContextFiles;systemPromptSource;appendSystemPromptSource;extensionsOverride;skillsOverride;promptsOverride;themesOverride;agentsFilesOverride;systemPromptOverride;appendSystemPromptOverride;extensionsResult;skills;skillDiagnostics;prompts;promptDiagnostics;themes;themeDiagnostics;agentsFiles;systemPrompt;systemPromptSourcePath;appendSystemPrompt;appendSystemPromptSourcePaths;lastSkillPaths;extensionSkillSourceInfos;extensionPromptSourceInfos;extensionThemeSourceInfos;resourceMetadataByPath;lastPromptPaths;lastThemePaths;loaded;constructor(t){this.cwd=w(t.cwd),this.agentDir=w(t.agentDir),this.settingsManager=t.settingsManager??kt.create(this.cwd,this.agentDir),this.eventBus=t.eventBus??gt();const n=t.extensionFactories??[];this.extensionFactories=n.filter(s=>!st(s)),this.builtinExtensions=new Map(n.filter(st).map(s=>[s.name,s])),this.packageManager=new wt({cwd:this.cwd,agentDir:this.agentDir,settingsManager:this.settingsManager,builtinExtensions:[...this.builtinExtensions.keys()]}),this.additionalExtensionPaths=t.additionalExtensionPaths??[],this.additionalSkillPaths=t.additionalSkillPaths??[],this.additionalPromptTemplatePaths=t.additionalPromptTemplatePaths??[],this.additionalThemePaths=t.additionalThemePaths??[],this.noExtensions=t.noExtensions??!1,this.disabledBuiltinExtensions=new Set(t.disabledBuiltinExtensions),this.noSkills=t.noSkills??!1,this.noPromptTemplates=t.noPromptTemplates??!1,this.noThemes=t.noThemes??!1,this.noContextFiles=t.noContextFiles??!1,this.systemPromptSource=t.systemPrompt,this.appendSystemPromptSource=t.appendSystemPrompt,this.extensionsOverride=t.extensionsOverride,this.skillsOverride=t.skillsOverride,this.promptsOverride=t.promptsOverride,this.themesOverride=t.themesOverride,this.agentsFilesOverride=t.agentsFilesOverride,this.systemPromptOverride=t.systemPromptOverride,this.appendSystemPromptOverride=t.appendSystemPromptOverride,this.extensionsResult={extensions:[],errors:[],runtime:St()},this.skills=[],this.skillDiagnostics=[],this.prompts=[],this.promptDiagnostics=[],this.themes=[],this.themeDiagnostics=[],this.agentsFiles=[],this.appendSystemPrompt=[],this.appendSystemPromptSourcePaths=[],this.lastSkillPaths=[],this.extensionSkillSourceInfos=new Map,this.extensionPromptSourceInfos=new Map,this.extensionThemeSourceInfos=new Map,this.resourceMetadataByPath=new Map,this.lastPromptPaths=[],this.lastThemePaths=[],this.loaded=!1}getExtensions(){return this.extensionsResult}getSkills(){return{skills:this.skills,diagnostics:this.skillDiagnostics}}getPrompts(){return{prompts:this.prompts,diagnostics:this.promptDiagnostics}}getThemes(){return{themes:this.themes,diagnostics:this.themeDiagnostics}}getAgentsFiles(){return{agentsFiles:this.agentsFiles}}getSystemPrompt(){return this.systemPrompt}getSystemPromptSource(){return this.systemPromptSourcePath?{path:this.systemPromptSourcePath}:void 0}getAppendSystemPrompt(){return this.appendSystemPrompt}getAppendSystemPromptSources(){return this.appendSystemPromptSourcePaths.map(t=>({path:t}))}extendResources(t){const n=this.normalizeExtensionPaths(t.skillPaths??[]),s=this.normalizeExtensionPaths(t.promptPaths??[]),i=this.normalizeExtensionPaths(t.themePaths??[]);for(const e of n)this.extensionSkillSourceInfos.set(e.path,I(e.path,e.metadata));for(const e of s)this.extensionPromptSourceInfos.set(e.path,I(e.path,e.metadata));for(const e of i)this.extensionThemeSourceInfos.set(e.path,I(e.path,e.metadata));n.length>0&&(this.lastSkillPaths=this.mergePaths(this.lastSkillPaths,n.map(e=>e.path)),this.updateSkillsFromPaths(this.lastSkillPaths,this.resourceMetadataByPath)),s.length>0&&(this.lastPromptPaths=this.mergePaths(this.lastPromptPaths,s.map(e=>e.path)),this.updatePromptsFromPaths(this.lastPromptPaths,this.resourceMetadataByPath)),i.length>0&&(this.lastThemePaths=this.mergePaths(this.lastThemePaths,i.map(e=>e.path)),this.updateThemesFromPaths(this.lastThemePaths,this.resourceMetadataByPath))}async loadProjectTrustExtensions(){return this.settingsManager.setProjectTrusted(!1),await this.settingsManager.reload(),this.loadCurrentExtensionSet({includeInlineFactories:!0})}async reload(t){Dt("extensions"),this.loaded&&xt();let n;if(t?.resolveProjectTrust){n=await this.loadProjectTrustExtensions();const r=await t.resolveProjectTrust({extensionsResult:n});this.settingsManager.setProjectTrusted(r)}await this.settingsManager.reload();const s=await this.packageManager.resolve(),i=await this.packageManager.resolveExtensionSources(this.additionalExtensionPaths,{temporary:!0});this.resourceMetadataByPath=new Map;const e=this.resourceMetadataByPath;this.extensionSkillSourceInfos=new Map,this.extensionPromptSourceInfos=new Map,this.extensionThemeSourceInfos=new Map;const o=P(r=>{for(const p of r)e.has(p.path)||e.set(p.path,p.metadata);return r.filter(p=>p.enabled)},"getEnabledResources"),a=P(r=>o(r).map(p=>p.path),"getEnabledPaths"),c=a(s.extensions),h=o(s.skills),g=a(s.prompts),x=a(s.themes),u=h.map(r=>this.mapSkillPath(r,e));for(const r of i.extensions)e.has(r.path)||e.set(r.path,{source:"cli",scope:"temporary",origin:"top-level"});for(const r of i.skills)e.has(r.path)||e.set(r.path,{source:"cli",scope:"temporary",origin:"top-level"});const d=a(i.extensions),E=a(i.skills),L=a(i.prompts),_=a(i.themes),G=(this.noExtensions?d:this.mergePaths(d,c)).filter(r=>!r.startsWith(k)||!this.disabledBuiltinExtensions.has(r.slice(k.length))),at=et(G,e),O=await this.loadFinalExtensionSet(G,n);A(O,at);for(const r of this.additionalExtensionPaths)if(j(r)){const p=this.resolveResourcePath(r);f(p)||O.errors.push({path:p,error:`Extension path does not exist: ${p}`})}this.extensionsResult=this.extensionsOverride?this.extensionsOverride(O):O,this.applyExtensionSourceInfo(this.extensionsResult.extensions,e);const F=m(ut(),"skills"),U=!this.noSkills&&f(F)?[F]:[];U.length>0&&!e.has(F)&&e.set(F,{source:"auto",scope:"user",origin:"top-level",baseDir:F});const Y=this.noSkills?this.mergePaths(E,this.additionalSkillPaths):this.mergePaths([...E,...u,...U],this.additionalSkillPaths);this.lastSkillPaths=Y,this.updateSkillsFromPaths(Y,e);for(const r of this.additionalSkillPaths)if(j(r)){const p=this.resolveResourcePath(r);!f(p)&&!this.skillDiagnostics.some(D=>D.path===p)&&this.skillDiagnostics.push({type:"error",message:"Skill path does not exist",path:p})}const H=this.noPromptTemplates?this.mergePaths(L,this.additionalPromptTemplatePaths):this.mergePaths([...L,...g],this.additionalPromptTemplatePaths);this.lastPromptPaths=H,this.updatePromptsFromPaths(H,e);for(const r of this.additionalPromptTemplatePaths)if(j(r)){const p=this.resolveResourcePath(r);!f(p)&&!this.promptDiagnostics.some(D=>D.path===p)&&this.promptDiagnostics.push({type:"error",message:"Prompt template path does not exist",path:p})}const J=this.noThemes?this.mergePaths(_,this.additionalThemePaths):this.mergePaths([..._,...x],this.additionalThemePaths);this.lastThemePaths=J,this.updateThemesFromPaths(J,e);for(const r of this.additionalThemePaths){const p=this.resolveResourcePath(r);!f(p)&&!this.themeDiagnostics.some(D=>D.path===p)&&this.themeDiagnostics.push({type:"error",message:"Theme path does not exist",path:p})}const K={agentsFiles:this.noContextFiles?[]:It({cwd:this.cwd,agentDir:this.agentDir})},rt=this.agentsFilesOverride?this.agentsFilesOverride(K):K;this.agentsFiles=rt.agentsFiles;const R=this.systemPromptSource??this.discoverSystemPromptFile(),X=ot(R,y("\u7CFB\u7EDF\u63D0\u793A\u8BCD"));this.systemPrompt=this.systemPromptOverride?this.systemPromptOverride(X):X,this.systemPromptSourcePath=R&&f(R)?w(R):void 0;let C=this.appendSystemPromptSource;if(!C){const r=this.discoverAppendSystemPromptFile();C=r?[r]:[]}const V=C.map(r=>ot(r,y("\u8FFD\u52A0\u7684\u7CFB\u7EDF\u63D0\u793A\u8BCD"))).filter(r=>r!==void 0);this.appendSystemPrompt=this.appendSystemPromptOverride?this.appendSystemPromptOverride(V):V,this.appendSystemPromptSourcePaths=C.filter(r=>f(r)).map(r=>w(r)),this.loaded=!0}async loadCurrentExtensionSet(t){const n=await this.packageManager.resolve(),s=await this.packageManager.resolveExtensionSources(this.additionalExtensionPaths,{temporary:!0}),i=n.extensions.filter(u=>u.enabled).map(u=>u.path),e=s.extensions.filter(u=>u.enabled).map(u=>u.path),o=(this.noExtensions?e:this.mergePaths(e,i)).filter(u=>!u.startsWith(k)),a=new Map([...n.extensions,...s.extensions].map(u=>[u.path,u.metadata])),c=et(o,a),h=await tt(o,this.cwd,this.eventBus);if(A(h,c),!t.includeInlineFactories)return h;const g=await this.loadExtensionFactories(h.runtime);h.extensions.push(...g.extensions),h.errors.push(...g.errors);const x=[];return h.extensions=nt(h.extensions,x),A(h,x),h}resolveExtensionLoadPath(t){return N(t)?t:w(t,this.cwd,{normalizeUnicodeSpaces:!0})}async loadExtensionPaths(t,n){const s=P(e=>e.startsWith(k),"isBuiltinPath"),i=await tt(t.filter(e=>!s(e)),this.cwd,this.eventBus,n);for(const e of t.filter(s)){const o=this.builtinExtensions.get(e.slice(k.length));if(!o){i.errors.push({path:e,error:`Unknown built-in extension: ${e}`});continue}try{const a=await Z(o.factory,this.cwd,this.eventBus,i.runtime,e);a.hidden=!0,a.replaceable=o.replaceable===!0,i.extensions.push(a)}catch(a){i.errors.push({path:e,error:a instanceof Error?a.message:"failed to load extension"})}}return i}async loadFinalExtensionSet(t,n){const s=n?.extensions??[],i=new Map(s.filter(d=>!d.path.startsWith("<inline:")).map(d=>[d.resolvedPath,d])),e=new Set((n?.errors??[]).map(d=>this.resolveExtensionLoadPath(d.path))),o=t.filter(d=>{const E=this.resolveExtensionLoadPath(d);return!i.has(E)&&!e.has(E)}),a=await this.loadExtensionPaths(o,n?.runtime),c=new Map(i);for(const d of a.extensions)c.set(d.resolvedPath,d);const h=n?{extensions:s.filter(d=>d.path.startsWith("<inline:")),errors:[]}:await this.loadExtensionFactories(a.runtime),g=t.map(d=>c.get(this.resolveExtensionLoadPath(d))).filter(d=>d!==void 0);g.push(...h.extensions);const x=[],u={extensions:nt(g,x),errors:[...n?.errors??[],...a.errors,...h.errors],warnings:[...n?.warnings??[],...a.warnings??[]],runtime:a.runtime};return A(u,x),this.addExtensionConflictDiagnostics(u),u}addExtensionConflictDiagnostics(t){const n=this.detectExtensionConflicts(t.extensions);for(const s of n)t.errors.push({path:s.path,error:s.message})}mapSkillPath(t,n){if(t.metadata.source!=="auto"&&t.metadata.origin!=="package")return t.path;try{if(!T(t.path).isDirectory())return t.path}catch{return t.path}const s=m(t.path,"SKILL.md");return f(s)?(n.has(s)||n.set(s,t.metadata),s):t.path}normalizeExtensionPaths(t){return t.map(n=>{const s=n.metadata.baseDir?{...n.metadata,baseDir:this.resolveResourcePath(n.metadata.baseDir)}:n.metadata;return{path:this.resolveResourcePath(n.path),metadata:s}})}updateSkillsFromPaths(t,n){let s;this.noSkills&&t.length===0?s={skills:[],diagnostics:[]}:s=Et({cwd:this.cwd,agentDir:this.agentDir,skillPaths:t,includeDefaults:!1});const i=this.skillsOverride?this.skillsOverride(s):s;this.skills=i.skills.map(e=>({...e,sourceInfo:this.findSourceInfoForPath(e.filePath,this.extensionSkillSourceInfos,n)??e.sourceInfo??this.getDefaultSourceInfoForPath(e.filePath)})),this.skillDiagnostics=i.diagnostics}updatePromptsFromPaths(t,n){let s;if(this.noPromptTemplates&&t.length===0)s={prompts:[],diagnostics:[]};else{const e=vt({cwd:this.cwd,agentDir:this.agentDir,promptPaths:t,includeDefaults:!1}),o=this.dedupePrompts(e.templates);s={prompts:o.prompts,diagnostics:[...e.diagnostics,...o.diagnostics]}}const i=this.promptsOverride?this.promptsOverride(s):s;this.prompts=i.prompts.map(e=>({...e,sourceInfo:this.findSourceInfoForPath(e.filePath,this.extensionPromptSourceInfos,n)??e.sourceInfo??this.getDefaultSourceInfoForPath(e.filePath)})),this.promptDiagnostics=i.diagnostics}updateThemesFromPaths(t,n){let s;if(this.noThemes&&t.length===0)s={themes:[],diagnostics:[]};else{const e=mt({...pt(()=>!1),...this.settingsManager.getTerminalCapabilityOverrides()}),o=this.loadThemes(t,!1,e),a=this.dedupeThemes(o.themes);s={themes:a.themes,diagnostics:[...o.diagnostics,...a.diagnostics]}}const i=this.themesOverride?this.themesOverride(s):s;this.themes=i.themes.map(e=>{const o=e.sourcePath;return e.sourceInfo=o?this.findSourceInfoForPath(o,this.extensionThemeSourceInfos,n)??e.sourceInfo??this.getDefaultSourceInfoForPath(o):e.sourceInfo,e}),this.themeDiagnostics=i.diagnostics}applyExtensionSourceInfo(t,n){for(const s of t){s.sourceInfo=this.findSourceInfoForPath(s.path,void 0,n)??this.getDefaultSourceInfoForPath(s.path);for(const i of s.commands.values())i.sourceInfo=s.sourceInfo;for(const i of s.tools.values())i.sourceInfo=s.sourceInfo}}findSourceInfoForPath(t,n,s){if(!t)return;if(N(t))return this.getDefaultSourceInfoForPath(t);const i=S(t);if(n)for(const[e,o]of n.entries()){const a=S(e);if(i===a||i.startsWith(`${a}${b}`))return{...o,path:t}}if(s){const e=s.get(i)??s.get(t);if(e)return I(t,e);for(const[o,a]of s.entries()){const c=S(o);if(i===c||i.startsWith(`${c}${b}`))return I(t,a)}}}getDefaultSourceInfoForPath(t){const n=Ft(t);if(n)return{path:t,source:n,scope:"temporary",origin:"top-level"};const s=S(t),i=[m(this.agentDir,"skills"),m(this.agentDir,"prompts"),m(this.agentDir,"themes"),m(this.agentDir,"extensions")],e=[m(this.cwd,v,"skills"),m(this.cwd,v,"prompts"),m(this.cwd,v,"themes"),m(this.cwd,v,"extensions")];for(const o of i)if(this.isUnderPath(s,o))return{path:t,source:"local",scope:"user",origin:"top-level",baseDir:o};for(const o of e)if(this.isUnderPath(s,o))return{path:t,source:"local",scope:"project",origin:"top-level",baseDir:o};return{path:t,source:"local",scope:"temporary",origin:"top-level",baseDir:T(s).isDirectory()?s:S(s,"..")}}mergePaths(t,n){const s=[],i=new Set;for(const e of[...t,...n]){const o=this.resolveResourcePath(e),a=M(o);i.has(a)||(i.add(a),s.push(o))}return s}resolveResourcePath(t){return N(t)?t:w(t,this.cwd,{trim:!0})}loadThemes(t,n,s){const i=[],e=[];if(n){const o=[m(this.agentDir,"themes"),m(this.cwd,v,"themes")];for(const a of o)this.loadThemesFromDir(a,i,e,s)}for(const o of t){const a=this.resolveResourcePath(o);if(!f(a)){e.push({type:"warning",message:"theme path does not exist",path:a});continue}try{const c=T(a);c.isDirectory()?this.loadThemesFromDir(a,i,e,s):c.isFile()&&a.endsWith(".json")?this.loadThemeFromFile(a,i,e,s):e.push({type:"warning",message:"theme path is not a json file",path:a})}catch(c){const h=c instanceof Error?c.message:"failed to read theme path";e.push({type:"warning",message:h,path:a})}}return{themes:i,diagnostics:e}}loadThemesFromDir(t,n,s,i){if(f(t))try{const e=lt(t,{withFileTypes:!0});for(const o of e){let a=o.isFile();if(o.isSymbolicLink())try{a=T(m(t,o.name)).isFile()}catch{continue}a&&o.name.endsWith(".json")&&this.loadThemeFromFile(m(t,o.name),n,s,i)}}catch(e){const o=e instanceof Error?e.message:"failed to read theme directory";s.push({type:"warning",message:o,path:t})}}loadThemeFromFile(t,n,s,i){try{n.push(Pt(t,i))}catch(e){const o=e instanceof Error?e.message:"failed to load theme";s.push({type:"warning",message:o,path:t})}}async loadExtensionFactories(t){const n=[],s=[];for(const[i,e]of this.extensionFactories.entries()){const o=typeof e!="function",a=o?e.factory:e,c=`<inline:${o?e.name:i+1}>`;try{const h=await Z(a,this.cwd,this.eventBus,t,c);h.hidden=o&&e.hidden,h.replaceable=o&&e.replaceable===!0,n.push(h)}catch(h){const g=h instanceof Error?h.message:"failed to load extension";s.push({path:c,error:g})}}return{extensions:n,errors:s}}dedupePrompts(t){const n=new Map,s=[];for(const i of t){const e=n.get(i.name);e?s.push({type:"collision",message:`name "/${i.name}" collision`,path:i.filePath,collision:{resourceType:"prompt",name:i.name,winnerPath:e.filePath,loserPath:i.filePath}}):n.set(i.name,i)}return{prompts:Array.from(n.values()),diagnostics:s}}dedupeThemes(t){const n=new Map,s=[];for(const i of t){const e=i.name??"unnamed",o=n.get(e);o?s.push({type:"collision",message:`name "${e}" collision`,path:i.sourcePath,collision:{resourceType:"theme",name:e,winnerPath:o.sourcePath??"<builtin>",loserPath:i.sourcePath??"<builtin>"}}):n.set(e,i)}return{themes:Array.from(n.values()),diagnostics:s}}discoverSystemPromptFile(){const t=m(this.cwd,v,"SYSTEM.md");if(this.settingsManager.isProjectTrusted()&&f(t))return t;const n=m(this.agentDir,"SYSTEM.md");if(f(n))return n}discoverAppendSystemPromptFile(){const t=m(this.cwd,v,"APPEND_SYSTEM.md");if(this.settingsManager.isProjectTrusted()&&f(t))return t;const n=m(this.agentDir,"APPEND_SYSTEM.md");if(f(n))return n}isUnderPath(t,n){const s=S(n);if(t===s)return!0;const i=s.endsWith(b)?s:`${s}${b}`;return t.startsWith(i)}detectExtensionConflicts(t){const n=[],s=new Map,i=new Map;for(const e of t){for(const o of e.tools.keys()){const a=s.get(o);a&&a!==e.path?n.push({path:e.path,message:`Tool "${o}" conflicts with ${a}`}):s.set(o,e.path)}for(const o of e.flags.keys()){const a=i.get(o);a&&a!==e.path?n.push({path:e.path,message:`Flag "--${o}" conflicts with ${a}`}):i.set(o,e.path)}}return n}}export{qt as DefaultResourceLoader,st as isBuiltinExtension,It as loadProjectContextFiles};
1
+ var lt=Object.defineProperty;var P=(c,t)=>lt(c,"name",{value:t,configurable:!0});import{existsSync as f,readdirSync as ct,readFileSync as $,statSync as T}from"node:fs";import{basename as mt,dirname as Q,join as p,resolve as y,sep as b}from"node:path";import{detectCapabilities as pt,getTerminalColorMode as dt}from"@earendil-works/pi-tui";import V from"chalk";import{APP_NAME as ut,CONFIG_DIR_NAME as v,getExamplesPath as ft,getPackageDir as Pt}from"../config.js";import{dalBuiltinExtensionPaths as gt}from"../dal/builtins.js";import{applyCommunityEnv as xt,hostDependenciesOf as Z,installedHostCopies as St,isAdaptablePackage as yt,tryEnsurePackageAdapted as wt}from"../dal/extension-compat.js";import{fill as A,t as S}from"../dal/i18n.js";import{loadThemeFromPath as vt}from"../modes/interactive/theme/theme.js";import{canonicalizePath as M,isLocalPath as j,resolvePath as w}from"../utils/paths.js";import{stripBom as W}from"../utils/text.js";import{createEventBus as kt}from"./event-bus.js";import{clearExtensionCache as Et,createExtensionRuntime as Dt,loadExtensionFromFactory as tt,loadExtensionsCached as et}from"./extensions/loader.js";import{findGitPaths as Ft}from"./footer-data-provider.js";import{DefaultPackageManager as Tt}from"./package-manager.js";import{loadPromptTemplates as bt}from"./prompt-templates.js";import{SettingsManager as Mt}from"./settings-manager.js";import{loadSkills as It}from"./skills.js";import{BUILTIN_PATH_PREFIX as k,createSourceInfo as I,getSyntheticPathSource as Ot,isSyntheticPath as N}from"./source-info.js";import{resetTimings as Rt}from"./timings.js";function st(c,t,n){let s;try{s=Pt()}catch{s=void 0}xt({agentDir:n.agentDir,packageDir:s});const i=[],e=new Map;for(const o of c){const a=t.get(o);a?.packageRoot&&!e.has(a.packageRoot)&&e.set(a.packageRoot,a)}for(const[o,a]of e){const l=p(o,"package.json");if(!f(l))continue;JSON.parse(W($(l,"utf-8"))),yt(o,a.source,n)&&wt(o);const h=St(o,Z(o));if(h.length===0)continue;const g=Z(o).filter(x=>h.some(d=>d.endsWith(p(...x.split("/")))));i.push({path:l,warning:A(S('\u6269\u5C55\u5305\u5728 dependencies \u91CC\u81EA\u5E26\u4E86 DAL \u5DF2\u63D0\u4F9B\u7684\u5E93\uFF08{names}\uFF09\uFF0C\u8FD9\u4E9B\u526F\u672C\u4F1A\u548C DAL \u81EA\u5DF1\u7684\u91CD\u590D\u52A0\u8F7D\u3002\u8BF7\u628A\u5B83\u4EEC\u6539\u5230 peerDependencies\uFF0C\u7248\u672C\u5199 "*"\u3002'),{names:g.join(", ")})})}return i}P(st,"prepareExtensionPackages");function B(c,t){c.warnings=[...new Map([...c.warnings??[],...t].map(n=>[n.path,n])).values()]}P(B,"mergeExtensionWarnings");function it(c){return typeof c!="function"&&c.builtin===!0}P(it,"isBuiltinExtension");let nt;function Ct(c){return nt??=new Set(gt().map(t=>y(t))),nt.has(y(c))}P(Ct,"isDalBundledExtensionPath");function ot(c,t){const n=P(i=>[...[...i.tools.keys()].map(e=>`tool:${e}`),...[...i.commands.keys()].map(e=>`command:${e}`),...[...i.flags.keys()].map(e=>`flag:${e}`)],"names"),s=new Map(c.filter(i=>!i.replaceable).flatMap(i=>n(i).map(e=>[e,i])));return c.filter(i=>{if(!i.replaceable)return!0;const e=n(i).map(o=>({name:o,extension:s.get(o)})).find(o=>o.extension!==void 0);if(!e)return!0;if(i.path.startsWith(k)&&!Ct(e.extension.path)){const o=i.path.slice(k.length),[a,l]=e.name.split(":",2),h=a==="command"?`/${l}`:a==="flag"?`--${l}`:l;t?.push({path:i.path,warning:A(S("\u6269\u5C55 {path} \u6CE8\u518C\u4E86{kind} `{name}`\uFF0C\u6240\u4EE5\u5185\u7F6E\u6269\u5C55 `{builtin}` \u6CA1\u6709\u52A0\u8F7D\u3002\u8981\u4F7F\u7528 `{builtin}`\uFF0C\u8FD0\u884C `{app} config`\uFF0C\u5728\u5185\u7F6E\u6269\u5C55\u91CC\u786E\u8BA4\u5B83\u5DF2\u542F\u7528\uFF0C\u7136\u540E\u505C\u7528\u6216\u79FB\u9664\u8FD9\u4E2A\u6269\u5C55\u3002\u4E24\u8005\u6700\u597D\u53EA\u4FDD\u7559\u4E00\u4E2A\u3002"),{path:e.extension.path,kind:a==="command"?S("\u4E00\u4E2A\u547D\u4EE4"):a==="flag"?S("\u4E00\u4E2A\u53C2\u6570"):S("\u4E00\u4E2A\u5DE5\u5177"),name:h,builtin:o,app:ut})})}return!1})}P(ot,"omitReplacedExtensions");function at(c,t){if(c){if(f(c))try{return W($(c,"utf-8"))}catch(n){return console.error(V.yellow(A(S("\u8B66\u544A\uFF1A\u65E0\u6CD5\u8BFB\u53D6{what}\u6587\u4EF6 {path}\uFF1A{error}"),{what:t,path:c,error:String(n)}))),c}return c}}P(at,"resolvePromptInput");function L(c){const t=["AGENTS.override.md","AGENTS.md","AGENTS.MD","CLAUDE.md","CLAUDE.MD"];for(const n of t){const s=p(c,n);if(f(s))try{if(!T(s).isFile())continue;return{path:s,content:W($(s,"utf-8"))}}catch(i){console.error(V.yellow(A(S("\u8B66\u544A\uFF1A\u65E0\u6CD5\u8BFB\u53D6 {path}\uFF1A{error}"),{path:s,error:String(i)})))}}return null}P(L,"loadContextFileFromDir");function At(c){const t=Ft(c);if(!t)return;const n=M(t.commonGitDir),s=M(t.repoDir),i=Q(n);if(!s.startsWith(`${i}${b}`)||M(p(i,".git"))!==n)return;const e=L(s);return e?p(i,mt(e.path)):void 0}P(At,"findShadowedContextFile");function Bt(c){const t=w(c.cwd),n=w(c.agentDir),s=[],i=new Set,e=L(n);e&&(s.push(e),i.add(e.path));const o=[],a=At(t);let l=t;for(;;){const h=L(l),g=a!==void 0&&M(h?.path??"")===a;h&&!g&&!i.has(h.path)&&(o.unshift(h),i.add(h.path));const x=Q(l);if(x===l)break;l=x}return s.push(...o),s}P(Bt,"loadProjectContextFiles");class ie{static{P(this,"DefaultResourceLoader")}cwd;agentDir;settingsManager;eventBus;packageManager;additionalExtensionPaths;additionalSkillPaths;additionalPromptTemplatePaths;additionalThemePaths;extensionFactories;builtinExtensions;noExtensions;disabledBuiltinExtensions;noSkills;noPromptTemplates;noThemes;noContextFiles;systemPromptSource;appendSystemPromptSource;extensionsOverride;skillsOverride;promptsOverride;themesOverride;agentsFilesOverride;systemPromptOverride;appendSystemPromptOverride;extensionsResult;skills;skillDiagnostics;prompts;promptDiagnostics;themes;themeDiagnostics;agentsFiles;systemPrompt;systemPromptSourcePath;appendSystemPrompt;appendSystemPromptSourcePaths;lastSkillPaths;extensionSkillSourceInfos;extensionPromptSourceInfos;extensionThemeSourceInfos;resourceMetadataByPath;lastPromptPaths;lastThemePaths;loaded;constructor(t){this.cwd=w(t.cwd),this.agentDir=w(t.agentDir),this.settingsManager=t.settingsManager??Mt.create(this.cwd,this.agentDir),this.eventBus=t.eventBus??kt();const n=t.extensionFactories??[];this.extensionFactories=n.filter(s=>!it(s)),this.builtinExtensions=new Map(n.filter(it).map(s=>[s.name,s])),this.packageManager=new Tt({cwd:this.cwd,agentDir:this.agentDir,settingsManager:this.settingsManager,builtinExtensions:[...this.builtinExtensions.keys()]}),this.additionalExtensionPaths=t.additionalExtensionPaths??[],this.additionalSkillPaths=t.additionalSkillPaths??[],this.additionalPromptTemplatePaths=t.additionalPromptTemplatePaths??[],this.additionalThemePaths=t.additionalThemePaths??[],this.noExtensions=t.noExtensions??!1,this.disabledBuiltinExtensions=new Set(t.disabledBuiltinExtensions),this.noSkills=t.noSkills??!1,this.noPromptTemplates=t.noPromptTemplates??!1,this.noThemes=t.noThemes??!1,this.noContextFiles=t.noContextFiles??!1,this.systemPromptSource=t.systemPrompt,this.appendSystemPromptSource=t.appendSystemPrompt,this.extensionsOverride=t.extensionsOverride,this.skillsOverride=t.skillsOverride,this.promptsOverride=t.promptsOverride,this.themesOverride=t.themesOverride,this.agentsFilesOverride=t.agentsFilesOverride,this.systemPromptOverride=t.systemPromptOverride,this.appendSystemPromptOverride=t.appendSystemPromptOverride,this.extensionsResult={extensions:[],errors:[],runtime:Dt()},this.skills=[],this.skillDiagnostics=[],this.prompts=[],this.promptDiagnostics=[],this.themes=[],this.themeDiagnostics=[],this.agentsFiles=[],this.appendSystemPrompt=[],this.appendSystemPromptSourcePaths=[],this.lastSkillPaths=[],this.extensionSkillSourceInfos=new Map,this.extensionPromptSourceInfos=new Map,this.extensionThemeSourceInfos=new Map,this.resourceMetadataByPath=new Map,this.lastPromptPaths=[],this.lastThemePaths=[],this.loaded=!1}getExtensions(){return this.extensionsResult}getSkills(){return{skills:this.skills,diagnostics:this.skillDiagnostics}}getPrompts(){return{prompts:this.prompts,diagnostics:this.promptDiagnostics}}getThemes(){return{themes:this.themes,diagnostics:this.themeDiagnostics}}getAgentsFiles(){return{agentsFiles:this.agentsFiles}}getSystemPrompt(){return this.systemPrompt}getSystemPromptSource(){return this.systemPromptSourcePath?{path:this.systemPromptSourcePath}:void 0}getAppendSystemPrompt(){return this.appendSystemPrompt}getAppendSystemPromptSources(){return this.appendSystemPromptSourcePaths.map(t=>({path:t}))}extendResources(t){const n=this.normalizeExtensionPaths(t.skillPaths??[]),s=this.normalizeExtensionPaths(t.promptPaths??[]),i=this.normalizeExtensionPaths(t.themePaths??[]);for(const e of n)this.extensionSkillSourceInfos.set(e.path,I(e.path,e.metadata));for(const e of s)this.extensionPromptSourceInfos.set(e.path,I(e.path,e.metadata));for(const e of i)this.extensionThemeSourceInfos.set(e.path,I(e.path,e.metadata));n.length>0&&(this.lastSkillPaths=this.mergePaths(this.lastSkillPaths,n.map(e=>e.path)),this.updateSkillsFromPaths(this.lastSkillPaths,this.resourceMetadataByPath)),s.length>0&&(this.lastPromptPaths=this.mergePaths(this.lastPromptPaths,s.map(e=>e.path)),this.updatePromptsFromPaths(this.lastPromptPaths,this.resourceMetadataByPath)),i.length>0&&(this.lastThemePaths=this.mergePaths(this.lastThemePaths,i.map(e=>e.path)),this.updateThemesFromPaths(this.lastThemePaths,this.resourceMetadataByPath))}async loadProjectTrustExtensions(){return this.settingsManager.setProjectTrusted(!1),await this.settingsManager.reload(),this.loadCurrentExtensionSet({includeInlineFactories:!0})}async reload(t){Rt("extensions"),this.loaded&&Et();let n;if(t?.resolveProjectTrust){n=await this.loadProjectTrustExtensions();const r=await t.resolveProjectTrust({extensionsResult:n});this.settingsManager.setProjectTrusted(r)}await this.settingsManager.reload();const s=await this.packageManager.resolve(),i=await this.packageManager.resolveExtensionSources(this.additionalExtensionPaths,{temporary:!0});this.resourceMetadataByPath=new Map;const e=this.resourceMetadataByPath;this.extensionSkillSourceInfos=new Map,this.extensionPromptSourceInfos=new Map,this.extensionThemeSourceInfos=new Map;const o=P(r=>{for(const m of r)e.has(m.path)||e.set(m.path,m.metadata);return r.filter(m=>m.enabled)},"getEnabledResources"),a=P(r=>o(r).map(m=>m.path),"getEnabledPaths"),l=a(s.extensions),h=o(s.skills),g=a(s.prompts),x=a(s.themes),d=h.map(r=>this.mapSkillPath(r,e));for(const r of i.extensions)e.has(r.path)||e.set(r.path,{source:"cli",scope:"temporary",origin:"top-level"});for(const r of i.skills)e.has(r.path)||e.set(r.path,{source:"cli",scope:"temporary",origin:"top-level"});const u=a(i.extensions),E=a(i.skills),z=a(i.prompts),U=a(i.themes),G=(this.noExtensions?u:this.mergePaths(u,l)).filter(r=>!r.startsWith(k)||!this.disabledBuiltinExtensions.has(r.slice(k.length))),rt=st(G,e,{agentDir:this.agentDir,cwd:this.cwd}),O=await this.loadFinalExtensionSet(G,n);B(O,rt);for(const r of this.additionalExtensionPaths)if(j(r)){const m=this.resolveResourcePath(r);f(m)||O.errors.push({path:m,error:`Extension path does not exist: ${m}`})}this.extensionsResult=this.extensionsOverride?this.extensionsOverride(O):O,this.applyExtensionSourceInfo(this.extensionsResult.extensions,e);const D=p(ft(),"skills"),_=!this.noSkills&&f(D)?[D]:[];_.length>0&&!e.has(D)&&e.set(D,{source:"auto",scope:"user",origin:"top-level",baseDir:D});const Y=this.noSkills?this.mergePaths(E,this.additionalSkillPaths):this.mergePaths([...E,...d,..._],this.additionalSkillPaths);this.lastSkillPaths=Y,this.updateSkillsFromPaths(Y,e);for(const r of this.additionalSkillPaths)if(j(r)){const m=this.resolveResourcePath(r);!f(m)&&!this.skillDiagnostics.some(F=>F.path===m)&&this.skillDiagnostics.push({type:"error",message:"Skill path does not exist",path:m})}const H=this.noPromptTemplates?this.mergePaths(z,this.additionalPromptTemplatePaths):this.mergePaths([...z,...g],this.additionalPromptTemplatePaths);this.lastPromptPaths=H,this.updatePromptsFromPaths(H,e);for(const r of this.additionalPromptTemplatePaths)if(j(r)){const m=this.resolveResourcePath(r);!f(m)&&!this.promptDiagnostics.some(F=>F.path===m)&&this.promptDiagnostics.push({type:"error",message:"Prompt template path does not exist",path:m})}const J=this.noThemes?this.mergePaths(U,this.additionalThemePaths):this.mergePaths([...U,...x],this.additionalThemePaths);this.lastThemePaths=J,this.updateThemesFromPaths(J,e);for(const r of this.additionalThemePaths){const m=this.resolveResourcePath(r);!f(m)&&!this.themeDiagnostics.some(F=>F.path===m)&&this.themeDiagnostics.push({type:"error",message:"Theme path does not exist",path:m})}const K={agentsFiles:this.noContextFiles?[]:Bt({cwd:this.cwd,agentDir:this.agentDir})},ht=this.agentsFilesOverride?this.agentsFilesOverride(K):K;this.agentsFiles=ht.agentsFiles;const R=this.systemPromptSource??this.discoverSystemPromptFile(),X=at(R,S("\u7CFB\u7EDF\u63D0\u793A\u8BCD"));this.systemPrompt=this.systemPromptOverride?this.systemPromptOverride(X):X,this.systemPromptSourcePath=R&&f(R)?w(R):void 0;let C=this.appendSystemPromptSource;if(!C){const r=this.discoverAppendSystemPromptFile();C=r?[r]:[]}const q=C.map(r=>at(r,S("\u8FFD\u52A0\u7684\u7CFB\u7EDF\u63D0\u793A\u8BCD"))).filter(r=>r!==void 0);this.appendSystemPrompt=this.appendSystemPromptOverride?this.appendSystemPromptOverride(q):q,this.appendSystemPromptSourcePaths=C.filter(r=>f(r)).map(r=>w(r)),this.loaded=!0}async loadCurrentExtensionSet(t){const n=await this.packageManager.resolve(),s=await this.packageManager.resolveExtensionSources(this.additionalExtensionPaths,{temporary:!0}),i=n.extensions.filter(d=>d.enabled).map(d=>d.path),e=s.extensions.filter(d=>d.enabled).map(d=>d.path),o=(this.noExtensions?e:this.mergePaths(e,i)).filter(d=>!d.startsWith(k)),a=new Map([...n.extensions,...s.extensions].map(d=>[d.path,d.metadata])),l=st(o,a,{agentDir:this.agentDir,cwd:this.cwd}),h=await et(o,this.cwd,this.eventBus);if(B(h,l),!t.includeInlineFactories)return h;const g=await this.loadExtensionFactories(h.runtime);h.extensions.push(...g.extensions),h.errors.push(...g.errors);const x=[];return h.extensions=ot(h.extensions,x),B(h,x),h}resolveExtensionLoadPath(t){return N(t)?t:w(t,this.cwd,{normalizeUnicodeSpaces:!0})}async loadExtensionPaths(t,n){const s=P(e=>e.startsWith(k),"isBuiltinPath"),i=await et(t.filter(e=>!s(e)),this.cwd,this.eventBus,n);for(const e of t.filter(s)){const o=this.builtinExtensions.get(e.slice(k.length));if(!o){i.errors.push({path:e,error:`Unknown built-in extension: ${e}`});continue}try{const a=await tt(o.factory,this.cwd,this.eventBus,i.runtime,e);a.hidden=!0,a.replaceable=o.replaceable===!0,i.extensions.push(a)}catch(a){i.errors.push({path:e,error:a instanceof Error?a.message:"failed to load extension"})}}return i}async loadFinalExtensionSet(t,n){const s=n?.extensions??[],i=new Map(s.filter(u=>!u.path.startsWith("<inline:")).map(u=>[u.resolvedPath,u])),e=new Set((n?.errors??[]).map(u=>this.resolveExtensionLoadPath(u.path))),o=t.filter(u=>{const E=this.resolveExtensionLoadPath(u);return!i.has(E)&&!e.has(E)}),a=await this.loadExtensionPaths(o,n?.runtime),l=new Map(i);for(const u of a.extensions)l.set(u.resolvedPath,u);const h=n?{extensions:s.filter(u=>u.path.startsWith("<inline:")),errors:[]}:await this.loadExtensionFactories(a.runtime),g=t.map(u=>l.get(this.resolveExtensionLoadPath(u))).filter(u=>u!==void 0);g.push(...h.extensions);const x=[],d={extensions:ot(g,x),errors:[...n?.errors??[],...a.errors,...h.errors],warnings:[...n?.warnings??[],...a.warnings??[]],runtime:a.runtime};return B(d,x),this.addExtensionConflictDiagnostics(d),d}addExtensionConflictDiagnostics(t){const n=this.detectExtensionConflicts(t.extensions);for(const s of n)t.errors.push({path:s.path,error:s.message})}mapSkillPath(t,n){if(t.metadata.source!=="auto"&&t.metadata.origin!=="package")return t.path;try{if(!T(t.path).isDirectory())return t.path}catch{return t.path}const s=p(t.path,"SKILL.md");return f(s)?(n.has(s)||n.set(s,t.metadata),s):t.path}normalizeExtensionPaths(t){return t.map(n=>{const s=n.metadata.baseDir?{...n.metadata,baseDir:this.resolveResourcePath(n.metadata.baseDir)}:n.metadata;return{path:this.resolveResourcePath(n.path),metadata:s}})}updateSkillsFromPaths(t,n){let s;this.noSkills&&t.length===0?s={skills:[],diagnostics:[]}:s=It({cwd:this.cwd,agentDir:this.agentDir,skillPaths:t,includeDefaults:!1});const i=this.skillsOverride?this.skillsOverride(s):s;this.skills=i.skills.map(e=>({...e,sourceInfo:this.findSourceInfoForPath(e.filePath,this.extensionSkillSourceInfos,n)??e.sourceInfo??this.getDefaultSourceInfoForPath(e.filePath)})),this.skillDiagnostics=i.diagnostics}updatePromptsFromPaths(t,n){let s;if(this.noPromptTemplates&&t.length===0)s={prompts:[],diagnostics:[]};else{const e=bt({cwd:this.cwd,agentDir:this.agentDir,promptPaths:t,includeDefaults:!1}),o=this.dedupePrompts(e.templates);s={prompts:o.prompts,diagnostics:[...e.diagnostics,...o.diagnostics]}}const i=this.promptsOverride?this.promptsOverride(s):s;this.prompts=i.prompts.map(e=>({...e,sourceInfo:this.findSourceInfoForPath(e.filePath,this.extensionPromptSourceInfos,n)??e.sourceInfo??this.getDefaultSourceInfoForPath(e.filePath)})),this.promptDiagnostics=i.diagnostics}updateThemesFromPaths(t,n){let s;if(this.noThemes&&t.length===0)s={themes:[],diagnostics:[]};else{const e=dt({...pt(()=>!1),...this.settingsManager.getTerminalCapabilityOverrides()}),o=this.loadThemes(t,!1,e),a=this.dedupeThemes(o.themes);s={themes:a.themes,diagnostics:[...o.diagnostics,...a.diagnostics]}}const i=this.themesOverride?this.themesOverride(s):s;this.themes=i.themes.map(e=>{const o=e.sourcePath;return e.sourceInfo=o?this.findSourceInfoForPath(o,this.extensionThemeSourceInfos,n)??e.sourceInfo??this.getDefaultSourceInfoForPath(o):e.sourceInfo,e}),this.themeDiagnostics=i.diagnostics}applyExtensionSourceInfo(t,n){for(const s of t){s.sourceInfo=this.findSourceInfoForPath(s.path,void 0,n)??this.getDefaultSourceInfoForPath(s.path);for(const i of s.commands.values())i.sourceInfo=s.sourceInfo;for(const i of s.tools.values())i.sourceInfo=s.sourceInfo}}findSourceInfoForPath(t,n,s){if(!t)return;if(N(t))return this.getDefaultSourceInfoForPath(t);const i=y(t);if(n)for(const[e,o]of n.entries()){const a=y(e);if(i===a||i.startsWith(`${a}${b}`))return{...o,path:t}}if(s){const e=s.get(i)??s.get(t);if(e)return I(t,e);for(const[o,a]of s.entries()){const l=y(o);if(i===l||i.startsWith(`${l}${b}`))return I(t,a)}}}getDefaultSourceInfoForPath(t){const n=Ot(t);if(n)return{path:t,source:n,scope:"temporary",origin:"top-level"};const s=y(t),i=[p(this.agentDir,"skills"),p(this.agentDir,"prompts"),p(this.agentDir,"themes"),p(this.agentDir,"extensions")],e=[p(this.cwd,v,"skills"),p(this.cwd,v,"prompts"),p(this.cwd,v,"themes"),p(this.cwd,v,"extensions")];for(const o of i)if(this.isUnderPath(s,o))return{path:t,source:"local",scope:"user",origin:"top-level",baseDir:o};for(const o of e)if(this.isUnderPath(s,o))return{path:t,source:"local",scope:"project",origin:"top-level",baseDir:o};return{path:t,source:"local",scope:"temporary",origin:"top-level",baseDir:T(s).isDirectory()?s:y(s,"..")}}mergePaths(t,n){const s=[],i=new Set;for(const e of[...t,...n]){const o=this.resolveResourcePath(e),a=M(o);i.has(a)||(i.add(a),s.push(o))}return s}resolveResourcePath(t){return N(t)?t:w(t,this.cwd,{trim:!0})}loadThemes(t,n,s){const i=[],e=[];if(n){const o=[p(this.agentDir,"themes"),p(this.cwd,v,"themes")];for(const a of o)this.loadThemesFromDir(a,i,e,s)}for(const o of t){const a=this.resolveResourcePath(o);if(!f(a)){e.push({type:"warning",message:"theme path does not exist",path:a});continue}try{const l=T(a);l.isDirectory()?this.loadThemesFromDir(a,i,e,s):l.isFile()&&a.endsWith(".json")?this.loadThemeFromFile(a,i,e,s):e.push({type:"warning",message:"theme path is not a json file",path:a})}catch(l){const h=l instanceof Error?l.message:"failed to read theme path";e.push({type:"warning",message:h,path:a})}}return{themes:i,diagnostics:e}}loadThemesFromDir(t,n,s,i){if(f(t))try{const e=ct(t,{withFileTypes:!0});for(const o of e){let a=o.isFile();if(o.isSymbolicLink())try{a=T(p(t,o.name)).isFile()}catch{continue}a&&o.name.endsWith(".json")&&this.loadThemeFromFile(p(t,o.name),n,s,i)}}catch(e){const o=e instanceof Error?e.message:"failed to read theme directory";s.push({type:"warning",message:o,path:t})}}loadThemeFromFile(t,n,s,i){try{n.push(vt(t,i))}catch(e){const o=e instanceof Error?e.message:"failed to load theme";s.push({type:"warning",message:o,path:t})}}async loadExtensionFactories(t){const n=[],s=[];for(const[i,e]of this.extensionFactories.entries()){const o=typeof e!="function",a=o?e.factory:e,l=`<inline:${o?e.name:i+1}>`;try{const h=await tt(a,this.cwd,this.eventBus,t,l);h.hidden=o&&e.hidden,h.replaceable=o&&e.replaceable===!0,n.push(h)}catch(h){const g=h instanceof Error?h.message:"failed to load extension";s.push({path:l,error:g})}}return{extensions:n,errors:s}}dedupePrompts(t){const n=new Map,s=[];for(const i of t){const e=n.get(i.name);e?s.push({type:"collision",message:`name "/${i.name}" collision`,path:i.filePath,collision:{resourceType:"prompt",name:i.name,winnerPath:e.filePath,loserPath:i.filePath}}):n.set(i.name,i)}return{prompts:Array.from(n.values()),diagnostics:s}}dedupeThemes(t){const n=new Map,s=[];for(const i of t){const e=i.name??"unnamed",o=n.get(e);o?s.push({type:"collision",message:`name "${e}" collision`,path:i.sourcePath,collision:{resourceType:"theme",name:e,winnerPath:o.sourcePath??"<builtin>",loserPath:i.sourcePath??"<builtin>"}}):n.set(e,i)}return{themes:Array.from(n.values()),diagnostics:s}}discoverSystemPromptFile(){const t=p(this.cwd,v,"SYSTEM.md");if(this.settingsManager.isProjectTrusted()&&f(t))return t;const n=p(this.agentDir,"SYSTEM.md");if(f(n))return n}discoverAppendSystemPromptFile(){const t=p(this.cwd,v,"APPEND_SYSTEM.md");if(this.settingsManager.isProjectTrusted()&&f(t))return t;const n=p(this.agentDir,"APPEND_SYSTEM.md");if(f(n))return n}isUnderPath(t,n){const s=y(n);if(t===s)return!0;const i=s.endsWith(b)?s:`${s}${b}`;return t.startsWith(i)}detectExtensionConflicts(t){const n=[],s=new Map,i=new Map;for(const e of t){for(const o of e.tools.keys()){const a=s.get(o);a&&a!==e.path?n.push({path:e.path,message:`Tool "${o}" conflicts with ${a}`}):s.set(o,e.path)}for(const o of e.flags.keys()){const a=i.get(o);a&&a!==e.path?n.push({path:e.path,message:`Flag "--${o}" conflicts with ${a}`}):i.set(o,e.path)}}return n}}export{ie as DefaultResourceLoader,it as isBuiltinExtension,Bt as loadProjectContextFiles};
@@ -1 +1 @@
1
- var A=Object.defineProperty;var i=(e,r)=>A(e,"name",{value:r,configurable:!0});import{existsSync as O,readdirSync as C,realpathSync as N}from"node:fs";import{homedir as h}from"node:os";import{isAbsolute as W,join as u,relative as T,resolve as _}from"node:path";import{packageCacheDirs as j}from"./package-managers.js";const B=["read-only","workspace-write","off"],g="DAL_SANDBOX",D={off:0,"workspace-write":1,"read-only":2};function v(e){return typeof e=="string"&&B.includes(e)}i(v,"isSandboxLevel");function I(e,r){return D[r]>D[e]?r:e}i(I,"stricterLevel");function a(e){return Array.isArray(e)?e.filter(r=>typeof r=="string"&&r.length>0):[]}i(a,"strings");function f(e){return[...new Set(e)]}i(f,"unique");const P=process.env[g];function z(e={[g]:P}){const r=e[g];if(r)try{const t=JSON.parse(r);return v(t.level)?{level:t.level,allowedDomains:a(t.allowedDomains)}:void 0}catch{return}}i(z,"readSandboxEnvironment");function $(e){return JSON.stringify({level:e.level,allowedDomains:e.network.allowedDomains})}i($,"sandboxEnvironmentValue");function Q(e){const r=e.settings?.global??{},t=e.settings?.project??{},s=z(e.env),l=e.override??{};let o,c;return l.level?(o=l.level,c="override"):s?.level?(o=s.level,c="environment"):v(r.level)?(o=r.level,c="settings"):(o=e.defaultLevel,c="default"),!l.level&&v(t.level)&&I(o,t.level)!==o&&(o=t.level,c="project"),{level:o,levelSource:c,network:{allowedDomains:f([...a(r.network?.allowedDomains),...a(s?.allowedDomains),...a(l.allowedDomains)]),deniedDomains:f([...a(r.network?.deniedDomains),...a(t.network?.deniedDomains)]),allowLocalBinding:r.network?.allowLocalBinding===!0},filesystem:{allowWrite:a(r.filesystem?.allowWrite),denyRead:f([...a(r.filesystem?.denyRead),...a(t.filesystem?.denyRead)]),denyWrite:f([...a(r.filesystem?.denyWrite),...a(t.filesystem?.denyWrite)]),allowRead:a(r.filesystem?.allowRead)}}}i(Q,"resolveSandboxPolicy");const H=[".git/hooks",".git/config",".gitmodules",".dal",".claude",".agents",".mcp.json",".cursor",".vscode",".idea",".env"],M=[".gitconfig",".bashrc",".bash_profile",".zshrc",".zprofile",".profile",".config/fish",".dal"],V=[".ssh",".gnupg",".aws",".config/gcloud",".azure",".kube",".docker/config.json",".netrc",".npmrc",".pypirc",".git-credentials",".config/gh","Library/Keychains","Library/Application Support/Google/Chrome","Library/Application Support/Firefox","Library/Safari",".mozilla",".config/google-chrome",".config/chromium",".dal/agent/auth.json"];function m(e,r){return e==="~"?h():e.startsWith("~/")?u(h(),e.slice(2)):W(e)?e:_(r,e)}i(m,"expandPath");function w(e){try{return N(e)}catch{return e}}i(w,"realpathOrSelf");function x(e,r){const t=T(r,e);return t===""||!t.startsWith("..")&&!W(t)}i(x,"isWithin");function U(e,r,t={}){const s=h(),l=e.level==="workspace-write"?f([r,w(r),...e.filesystem.allowWrite.map(n=>m(n,r))]):[],o=e.level==="workspace-write"?t.gitDirs??[]:[],c=(t.extraWrite??[]).map(n=>m(n,r)),k=t.scratchDir?[t.scratchDir,w(t.scratchDir)]:[],E=e.level==="workspace-write"?t.packageCaches??j():[],R=f([...l,...o,...c,...k,...E]),d=[];if(e.level==="read-only"){const n=f([r,w(r)]);c.some(y=>n.some(S=>x(y,S)||x(S,y)))||d.push(...n)}for(const n of[...l,...c]){for(const p of H)d.push(u(n,p));d.push(u(n,".env.*"));for(const p of X(n))d.push(u(n,p))}for(const n of o)d.push(u(n,"hooks"),u(n,"config"));for(const n of M)d.push(u(s,n));d.push(...e.filesystem.denyWrite.map(n=>m(n,r)));const b=new Set(e.filesystem.allowRead.map(n=>m(n,r))),L=[...V.map(n=>u(s,n)).filter(n=>!b.has(n)),...e.filesystem.denyRead.map(n=>m(n,r))];return{allowWrite:R,denyWrite:f(d),denyRead:f(L)}}i(U,"filesystemRules");function X(e){if(!O(e))return[];try{return C(e).filter(r=>r.startsWith(".env."))}catch{return[]}}i(X,"listEnvFiles");function Y(e,r){const t=e.toLowerCase(),s=r.toLowerCase();return s.startsWith("*.")?t.endsWith(s.slice(1)):t===s}i(Y,"domainMatches");function Z(e){const r=e.toLowerCase().replace(/^\[|\]$/g,"");if(r==="localhost"||r.endsWith(".localhost")||r==="::1"||r==="0.0.0.0")return!0;if(r.startsWith("fe80:")||r.startsWith("fc")||r.startsWith("fd"))return r.includes(":");const t=r.split(".").map(o=>Number(o));if(t.length!==4||t.some(o=>!Number.isInteger(o)||o<0||o>255))return!1;const[s,l]=t;return s===127||s===10||s===172&&l>=16&&l<=31||s===192&&l===168||s===169&&l===254}i(Z,"isAlwaysBlockedHost");export{V as PROTECTED_HOME_READS,M as PROTECTED_HOME_WRITES,H as PROTECTED_WRITE_NAMES,g as SANDBOX_ENV,B as SANDBOX_LEVELS,Y as domainMatches,m as expandPath,U as filesystemRules,Z as isAlwaysBlockedHost,v as isSandboxLevel,z as readSandboxEnvironment,Q as resolveSandboxPolicy,$ as sandboxEnvironmentValue,I as stricterLevel};
1
+ var A=Object.defineProperty;var i=(e,r)=>A(e,"name",{value:r,configurable:!0});import{existsSync as O,readdirSync as C,realpathSync as N}from"node:fs";import{homedir as h}from"node:os";import{isAbsolute as W,join as u,relative as T,resolve as _,sep as j}from"node:path";import{packageCacheDirs as B}from"./package-managers.js";const I=["read-only","workspace-write","off"],g="DAL_SANDBOX",D={off:0,"workspace-write":1,"read-only":2};function v(e){return typeof e=="string"&&I.includes(e)}i(v,"isSandboxLevel");function P(e,r){return D[r]>D[e]?r:e}i(P,"stricterLevel");function a(e){return Array.isArray(e)?e.filter(r=>typeof r=="string"&&r.length>0):[]}i(a,"strings");function f(e){return[...new Set(e)]}i(f,"unique");const z=process.env[g];function H(e={[g]:z}){const r=e[g];if(r)try{const t=JSON.parse(r);return v(t.level)?{level:t.level,allowedDomains:a(t.allowedDomains)}:void 0}catch{return}}i(H,"readSandboxEnvironment");function Q(e){return JSON.stringify({level:e.level,allowedDomains:e.network.allowedDomains})}i(Q,"sandboxEnvironmentValue");function U(e){const r=e.settings?.global??{},t=e.settings?.project??{},s=H(e.env),l=e.override??{};let o,c;return l.level?(o=l.level,c="override"):s?.level?(o=s.level,c="environment"):v(r.level)?(o=r.level,c="settings"):(o=e.defaultLevel,c="default"),!l.level&&v(t.level)&&P(o,t.level)!==o&&(o=t.level,c="project"),{level:o,levelSource:c,network:{allowedDomains:f([...a(r.network?.allowedDomains),...a(s?.allowedDomains),...a(l.allowedDomains)]),deniedDomains:f([...a(r.network?.deniedDomains),...a(t.network?.deniedDomains)]),allowLocalBinding:r.network?.allowLocalBinding===!0},filesystem:{allowWrite:a(r.filesystem?.allowWrite),denyRead:f([...a(r.filesystem?.denyRead),...a(t.filesystem?.denyRead)]),denyWrite:f([...a(r.filesystem?.denyWrite),...a(t.filesystem?.denyWrite)]),allowRead:a(r.filesystem?.allowRead)}}}i(U,"resolveSandboxPolicy");const M=[".git/hooks",".git/config",".gitmodules",".dal",".claude",".agents",".mcp.json",".cursor",".vscode",".idea",".env"],V=[".gitconfig",".bashrc",".bash_profile",".zshrc",".zprofile",".profile",".config/fish",".dal"],X=[".ssh",".gnupg",".aws",".config/gcloud",".azure",".kube",".docker/config.json",".netrc",".npmrc",".pypirc",".git-credentials",".config/gh","Library/Keychains","Library/Application Support/Google/Chrome","Library/Application Support/Firefox","Library/Safari",".mozilla",".config/google-chrome",".config/chromium",".dal/agent/auth.json"];function m(e,r){return e==="~"?h():e.startsWith("~/")?u(h(),e.slice(2)):W(e)?e:_(r,e)}i(m,"expandPath");function w(e){try{return N(e)}catch{return e}}i(w,"realpathOrSelf");function x(e,r){const t=T(r,e);return t===""||t!==".."&&!t.startsWith(`..${j}`)&&!W(t)}i(x,"isWithin");function Y(e,r,t={}){const s=h(),l=e.level==="workspace-write"?f([r,w(r),...e.filesystem.allowWrite.map(n=>m(n,r))]):[],o=e.level==="workspace-write"?t.gitDirs??[]:[],c=(t.extraWrite??[]).map(n=>m(n,r)),k=t.scratchDir?[t.scratchDir,w(t.scratchDir)]:[],E=e.level==="workspace-write"?t.packageCaches??B():[],R=f([...l,...o,...c,...k,...E]),d=[];if(e.level==="read-only"){const n=f([r,w(r)]);c.some(y=>n.some(S=>x(y,S)||x(S,y)))||d.push(...n)}for(const n of[...l,...c]){for(const p of M)d.push(u(n,p));d.push(u(n,".env.*"));for(const p of F(n))d.push(u(n,p))}for(const n of o)d.push(u(n,"hooks"),u(n,"config"));for(const n of V)d.push(u(s,n));d.push(...e.filesystem.denyWrite.map(n=>m(n,r)));const b=new Set(e.filesystem.allowRead.map(n=>m(n,r))),L=[...X.map(n=>u(s,n)).filter(n=>!b.has(n)),...e.filesystem.denyRead.map(n=>m(n,r))];return{allowWrite:R,denyWrite:f(d),denyRead:f(L)}}i(Y,"filesystemRules");function F(e){if(!O(e))return[];try{return C(e).filter(r=>r.startsWith(".env."))}catch{return[]}}i(F,"listEnvFiles");function Z(e,r){const t=e.toLowerCase(),s=r.toLowerCase();return s.startsWith("*.")?t.endsWith(s.slice(1)):t===s}i(Z,"domainMatches");function ee(e){const r=e.toLowerCase().replace(/^\[|\]$/g,"");if(r==="localhost"||r.endsWith(".localhost")||r==="::1"||r==="0.0.0.0")return!0;if(r.startsWith("fe80:")||r.startsWith("fc")||r.startsWith("fd"))return r.includes(":");const t=r.split(".").map(o=>Number(o));if(t.length!==4||t.some(o=>!Number.isInteger(o)||o<0||o>255))return!1;const[s,l]=t;return s===127||s===10||s===172&&l>=16&&l<=31||s===192&&l===168||s===169&&l===254}i(ee,"isAlwaysBlockedHost");export{X as PROTECTED_HOME_READS,V as PROTECTED_HOME_WRITES,M as PROTECTED_WRITE_NAMES,g as SANDBOX_ENV,I as SANDBOX_LEVELS,Z as domainMatches,m as expandPath,Y as filesystemRules,ee as isAlwaysBlockedHost,v as isSandboxLevel,H as readSandboxEnvironment,U as resolveSandboxPolicy,Q as sandboxEnvironmentValue,P as stricterLevel};
@@ -1,4 +1,4 @@
1
- var S=Object.defineProperty;var c=(e,r)=>S(e,"name",{value:r,configurable:!0});import{spawnSync as D}from"node:child_process";import{existsSync as u,mkdtempSync as I,readFileSync as v,rmSync as w,writeFileSync as p}from"node:fs";import{createRequire as y}from"node:module";import{tmpdir as L}from"node:os";import{join as d,win32 as m}from"node:path";const x="DAL_MXC_SDK_DIR",P="0.6.0-alpha",O=/^0\.6\.\d+$/,H=["Allowlisted domains are reached through dal's filtering proxy, handed to mxc as its network proxy; mxc does not enforce per-host allow or block lists on Windows.","A background process that may listen locally gets mxc's local-network access, which also reaches other machines on the private network, not only localhost.","Protected names inside a writable folder (.env, .git/hooks, .vscode, .dal, \u2026) are protected only if they already exist when the command starts; creating a missing one is not blocked.","Protected credential files (~/.ssh, cloud credentials, \u2026) are denied only if they exist when the command starts."];let h;function V(e){h=e}c(V,"setMxcRuntimeForTesting");function E(e){const r=e[x]?.trim();if(r)return u(d(r,"package.json"))?{dir:r}:{error:`${x} is set to ${r}, but there is no package there.`};try{const o=y(import.meta.url);return{dir:d(o.resolve("@microsoft/mxc-sdk/package.json"),"..")}}catch{return{error:`Microsoft eXecution Containers (mxc) is not installed. Install it with \`npm install -g @microsoft/mxc-sdk@0.6.0\`, or set ${x} to an @microsoft/mxc-sdk 0.6 package directory.`}}}c(E,"sdkDirectory");function B(e={}){if(h)return h;const r=e.env??process.env,o=E(r);if("error"in o)return o;let t;try{t=JSON.parse(v(d(o.dir,"package.json"),"utf8")).version??""}catch(n){return{error:`cannot read the mxc SDK at ${o.dir}: ${n instanceof Error?n.message:n}`}}if(!O.test(t))return{error:`dal supports @microsoft/mxc-sdk 0.6.x, but ${o.dir} is version ${t||"(unknown)"}. Install @microsoft/mxc-sdk@0.6.0.`};const a=(e.arch??process.arch)==="arm64"?"arm64":"x64",s=d(o.dir,"bin",a,"wxc-exec.exe");if(!u(s))return{error:`the mxc SDK at ${o.dir} has no ${a} wxc-exec.exe.`};let i;try{i=y(import.meta.url)(d(o.dir,"dist","index.js"))}catch(n){return{error:`cannot load the mxc SDK at ${o.dir}: ${n instanceof Error?n.message:n}`}}return{sdkDir:o.dir,sdkVersion:t,wxcExec:s,api:i}}c(B,"loadMxcRuntime");function l(e){return e.replace(/\//g,"\\")}c(l,"toWindowsPath");function f(e){return e.length>0&&!/[\s"]/.test(e)?e:`"${e.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\+)$/,"$1$1")}"`}c(f,"quoteWindowsArgument");function g(e){return`'${e.replace(/'/g,"''")}'`}c(g,"powershellQuote");function $(e){return`'${e.replace(/'/g,"'\\''")}'`}c($,"bashQuote");function T(e){const r=m.dirname(e),o=m.dirname(r);return m.basename(r).toLowerCase()==="bin"&&m.basename(o).toLowerCase()==="usr"?m.dirname(o):m.basename(r).toLowerCase()==="bin"?o:r}c(T,"shellInstallRoot");function _(e,r){const o=m.relative(r,e);return o===""||!o.startsWith("..")&&!m.isAbsolute(o)}c(_,"isWithinWindows");function C(e){const r=c(n=>[...new Set(n.map(l))],"unique"),o=r([...e.rules.allowWrite,...e.tools.readwritePaths]),t=e.rules.denyWrite.filter(n=>!/[*?]/.test(n)&&e.exists(n)&&o.some(b=>_(l(n),b))),a=r([...e.tools.readonlyPaths,e.shellRoot,e.runDir,...e.level==="read-only"?[e.cwd]:[],...t]).filter(n=>!o.includes(n)),s=r(e.rules.denyRead.filter(n=>!/[*?]/.test(n)&&e.exists(n))),i=e.proxyPort!==void 0?{proxy:{localhost:e.proxyPort}}:{allowOutbound:!1,allowLocalNetwork:e.allowLocalNetwork};return{version:P,filesystem:{readwritePaths:o,readonlyPaths:a,deniedPaths:s},network:i,ui:{allowWindows:!0,clipboard:"none",allowInputInjection:!1}}}c(C,"windowsSandboxPolicy");function R(e,r){const o={};for(const[s,i]of Object.entries(e))typeof i=="string"&&(o[s]=i);const t=c((s,i)=>{for(const n of Object.keys(o))n.toLowerCase()===s.toLowerCase()&&delete o[n];o[s]=i},"set"),a=l(r.scratchDir);if(t("TMP",a),t("TEMP",a),t("TMPDIR",a),t("DAL_SANDBOX_RUN",r.runId),r.proxyPort!==void 0){const s=`http://127.0.0.1:${r.proxyPort}`;t("HTTP_PROXY",s),t("HTTPS_PROXY",s),o.http_proxy=s,o.https_proxy=s}return Object.entries(o).map(([s,i])=>`${s}=${i}`)}c(R,"windowsSandboxEnvironment");const N="try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}";function W(e,r,o,t){return e==="powershell"?{script:`${N}
1
+ var S=Object.defineProperty;var c=(e,r)=>S(e,"name",{value:r,configurable:!0});import{spawnSync as D}from"node:child_process";import{existsSync as u,mkdtempSync as I,readFileSync as v,rmSync as w,writeFileSync as p}from"node:fs";import{createRequire as y}from"node:module";import{tmpdir as L}from"node:os";import{join as d,win32 as m}from"node:path";const x="DAL_MXC_SDK_DIR",P="0.6.0-alpha",O=/^0\.6\.\d+$/,H=["Allowlisted domains are reached through dal's filtering proxy, handed to mxc as its network proxy; mxc does not enforce per-host allow or block lists on Windows.","A background process that may listen locally gets mxc's local-network access, which also reaches other machines on the private network, not only localhost.","Protected names inside a writable folder (.env, .git/hooks, .vscode, .dal, \u2026) are protected only if they already exist when the command starts; creating a missing one is not blocked.","Protected credential files (~/.ssh, cloud credentials, \u2026) are denied only if they exist when the command starts."];let h;function V(e){h=e}c(V,"setMxcRuntimeForTesting");function E(e){const r=e[x]?.trim();if(r)return u(d(r,"package.json"))?{dir:r}:{error:`${x} is set to ${r}, but there is no package there.`};try{const o=y(import.meta.url);return{dir:d(o.resolve("@microsoft/mxc-sdk/package.json"),"..")}}catch{return{error:`Microsoft eXecution Containers (mxc) is not installed. Install it with \`npm install -g @microsoft/mxc-sdk@0.6.0\`, or set ${x} to an @microsoft/mxc-sdk 0.6 package directory.`}}}c(E,"sdkDirectory");function B(e={}){if(h)return h;const r=e.env??process.env,o=E(r);if("error"in o)return o;let t;try{t=JSON.parse(v(d(o.dir,"package.json"),"utf8")).version??""}catch(n){return{error:`cannot read the mxc SDK at ${o.dir}: ${n instanceof Error?n.message:n}`}}if(!O.test(t))return{error:`dal supports @microsoft/mxc-sdk 0.6.x, but ${o.dir} is version ${t||"(unknown)"}. Install @microsoft/mxc-sdk@0.6.0.`};const a=(e.arch??process.arch)==="arm64"?"arm64":"x64",s=d(o.dir,"bin",a,"wxc-exec.exe");if(!u(s))return{error:`the mxc SDK at ${o.dir} has no ${a} wxc-exec.exe.`};let i;try{i=y(import.meta.url)(d(o.dir,"dist","index.js"))}catch(n){return{error:`cannot load the mxc SDK at ${o.dir}: ${n instanceof Error?n.message:n}`}}return{sdkDir:o.dir,sdkVersion:t,wxcExec:s,api:i}}c(B,"loadMxcRuntime");function l(e){return e.replace(/\//g,"\\")}c(l,"toWindowsPath");function f(e){return e.length>0&&!/[\s"]/.test(e)?e:`"${e.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\+)$/,"$1$1")}"`}c(f,"quoteWindowsArgument");function g(e){return`'${e.replace(/'/g,"''")}'`}c(g,"powershellQuote");function $(e){return`'${e.replace(/'/g,"'\\''")}'`}c($,"bashQuote");function T(e){const r=m.dirname(e),o=m.dirname(r);return m.basename(r).toLowerCase()==="bin"&&m.basename(o).toLowerCase()==="usr"?m.dirname(o):m.basename(r).toLowerCase()==="bin"?o:r}c(T,"shellInstallRoot");function _(e,r){const o=m.relative(r,e);return o===""||o!==".."&&!o.startsWith("..\\")&&!m.isAbsolute(o)}c(_,"isWithinWindows");function C(e){const r=c(n=>[...new Set(n.map(l))],"unique"),o=r([...e.rules.allowWrite,...e.tools.readwritePaths]),t=e.rules.denyWrite.filter(n=>!/[*?]/.test(n)&&e.exists(n)&&o.some(b=>_(l(n),b))),a=r([...e.tools.readonlyPaths,e.shellRoot,e.runDir,...e.level==="read-only"?[e.cwd]:[],...t]).filter(n=>!o.includes(n)),s=r(e.rules.denyRead.filter(n=>!/[*?]/.test(n)&&e.exists(n))),i=e.proxyPort!==void 0?{proxy:{localhost:e.proxyPort}}:{allowOutbound:!1,allowLocalNetwork:e.allowLocalNetwork};return{version:P,filesystem:{readwritePaths:o,readonlyPaths:a,deniedPaths:s},network:i,ui:{allowWindows:!0,clipboard:"none",allowInputInjection:!1}}}c(C,"windowsSandboxPolicy");function R(e,r){const o={};for(const[s,i]of Object.entries(e))typeof i=="string"&&(o[s]=i);const t=c((s,i)=>{for(const n of Object.keys(o))n.toLowerCase()===s.toLowerCase()&&delete o[n];o[s]=i},"set"),a=l(r.scratchDir);if(t("TMP",a),t("TEMP",a),t("TMPDIR",a),t("DAL_SANDBOX_RUN",r.runId),r.proxyPort!==void 0){const s=`http://127.0.0.1:${r.proxyPort}`;t("HTTP_PROXY",s),t("HTTPS_PROXY",s),o.http_proxy=s,o.https_proxy=s}return Object.entries(o).map(([s,i])=>`${s}=${i}`)}c(R,"windowsSandboxEnvironment");const N="try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}";function W(e,r,o,t){return e==="powershell"?{script:`${N}
2
2
  ${o}
3
3
  if (-not $?) { if ($LASTEXITCODE) { exit $LASTEXITCODE } else { exit 1 } }
4
4
  `,commandLine:[f(r),"-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",f(t)].join(" ")}:{script:`${o}
@@ -12,6 +12,7 @@ export interface BuildSystemPromptOptions {
12
12
  sections?: Record<string, string>;
13
13
  cwd: string;
14
14
  gitState?: boolean;
15
+ projectFacts?: boolean;
15
16
  contextFiles?: Array<{
16
17
  path: string;
17
18
  content: string;
@@ -1,28 +1,29 @@
1
- var P=Object.defineProperty;var c=(e,t)=>P(e,"name",{value:t,configurable:!0});import{join as v}from"node:path";import{getSystemMessageText as E}from"@earendil-works/pi-ai";import{APP_NAME as $,APP_TITLE as f,getDalDocsPath as j,getDocsPath as T,getExamplesPath as O,getReadmePath as _,IS_WHITE_LABEL_BUILD as I}from"../config.js";import{describeGitState as N}from"./git-state.js";import{INJECTED_CONTEXT_TAG as A}from"./messages.js";import{formatSkillsForPrompt as D}from"./skills.js";const M=/^[a-z][a-z0-9_-]*$/;function R(e){return{customPrompt:e.customPrompt,forceSystemPrompt:e.forceSystemPrompt,selectedTools:[...e.selectedTools??["read","bash","edit","write"]],hiddenTools:[...e.hiddenTools??[]],toolSnippets:{...e.toolSnippets??{}},toolGuidelines:Object.fromEntries(Object.entries(e.toolGuidelines??{}).map(([t,n])=>[t,[...n]])),promptGuidelines:[...e.promptGuidelines??[]],appendSystemPrompt:e.appendSystemPrompt??"",sections:{...e.sections??{}},cwd:e.cwd,gitState:e.gitState,contextFiles:(e.contextFiles??[]).map(t=>({...t})),skills:(e.skills??[]).map(t=>({...t}))}}c(R,"normalizeBuildSystemPromptOptions");function G(e){return["Project-specific instructions and guidelines:",...e.map(({path:t,content:n})=>`<project_instructions path="${t}">
1
+ var v=Object.defineProperty;var c=(e,t)=>v(e,"name",{value:t,configurable:!0});import{join as P}from"node:path";import{getSystemMessageText as j}from"@earendil-works/pi-ai";import{APP_NAME as E,APP_TITLE as p,getDalDocsPath as $,getDocsPath as T,getExamplesPath as O,getReadmePath as _,IS_WHITE_LABEL_BUILD as I}from"../config.js";import{describeGitState as N}from"./git-state.js";import{INJECTED_CONTEXT_TAG as A}from"./messages.js";import{describeProjectFacts as R}from"./project-facts.js";import{formatSkillsForPrompt as D}from"./skills.js";const F=/^[a-z][a-z0-9_-]*$/;function M(e){return{customPrompt:e.customPrompt,forceSystemPrompt:e.forceSystemPrompt,selectedTools:[...e.selectedTools??["read","bash","edit","write"]],hiddenTools:[...e.hiddenTools??[]],toolSnippets:{...e.toolSnippets??{}},toolGuidelines:Object.fromEntries(Object.entries(e.toolGuidelines??{}).map(([t,n])=>[t,[...n]])),promptGuidelines:[...e.promptGuidelines??[]],appendSystemPrompt:e.appendSystemPrompt??"",sections:{...e.sections??{}},cwd:e.cwd,gitState:e.gitState,projectFacts:e.projectFacts,contextFiles:(e.contextFiles??[]).map(t=>({...t})),skills:(e.skills??[]).map(t=>({...t}))}}c(M,"normalizeBuildSystemPromptOptions");function C(e){return["Project-specific instructions and guidelines:",...e.map(({path:t,content:n})=>`<project_instructions path="${t}">
2
2
  ${n}
3
3
  </project_instructions>`)].join(`
4
4
 
5
- `)}c(G,"renderProjectContext");function L(e,t,n){const i=[],d=new Set,o=c(l=>{const m=l.trim();!m||d.has(m)||(d.add(m),i.push(m))},"addRule"),p=e.includes("bash"),h=e.includes("powershell"),a=e.includes("grep"),g=e.includes("find"),y=e.includes("ls");(p||h)&&!a&&!g&&!y&&o(p&&h?"Use bash or PowerShell for file operations like listing, searching, and finding files":h?"Use PowerShell for file operations like listing, searching, and finding files":"Use bash for file operations like ls, rg, find");for(const l of e)for(const m of t[l]??[])o(m);for(const l of n)o(l);return e.length>0&&(o("When several tool calls do not depend on each other's results (reading multiple files, independent searches or commands), make them all in one response; they run in parallel. Each extra round trip costs the user seconds"),o("Answer as soon as you can: once you know enough, give the answer or your best current conclusion, then offer to dig further. Do not investigate everything before saying anything"),o("During longer work, tell the user every few tool rounds, in a sentence or two, what you found and what you will check next"),o("If you cannot tell which product, project or file the user means, ask instead of searching widely on a guess. When the user writes while you are working, respond to that message first: it may change the direction"),o("In a small project, read every source file the task touches in one response (parallel reads, or one command that prints them) instead of exploring one file per round"),o("Verify the behaviours the request names and the edge cases it implies; do not write exhaustive or randomized test sweeps unless asked"),o("Before reporting done, run every code path you added at least once, including backward-compatibility, fallback and error branches: a branch that never ran is not verified"),o("If the request's premise does not match what the code, data or tests show (the reported bug is absent, the named text is already correct), say so with the evidence and do not change anything just to satisfy the request; ask how to proceed or stop")),o(`Text inside <${A} type="..."> tags comes from ${f} itself, not from the user: follow its instructions, but do not mistake it for the user's request or reply to it as if the user had written it`),o("Be concise in your responses"),o("Show file paths clearly when working with files"),i.map(l=>`- ${l}`).join(`
6
- `)}c(L,"buildRules");function F(e){const t=R(e),{customPrompt:n,selectedTools:i,hiddenTools:d,toolSnippets:o,toolGuidelines:p,promptGuidelines:h,appendSystemPrompt:a,sections:g,cwd:y,contextFiles:l,skills:m}=t;for(const s of Object.keys(g))if(!M.test(s)||s==="preamble")throw new Error(`Invalid system prompt section name: ${s}`);const w=i.filter(s=>!d.includes(s)),r={};if(n)r.preamble=n;else{r.preamble=`You are an expert coding assistant operating inside ${f} (${$}). You help users by reading files, executing commands, editing code, and writing new files.`;const s=w.filter(b=>!!o[b]),u=s.length>0?s.map(b=>`- ${b}: ${o[b]}`).join(`
7
- `):"(none)";r.tools=`${u}
5
+ `)}c(C,"renderProjectContext");function G(e,t,n){const r=[],d=new Set,o=c(l=>{const m=l.trim();!m||d.has(m)||(d.add(m),r.push(m))},"addRule"),h=e.includes("bash"),f=e.includes("powershell"),a=e.includes("grep"),u=e.includes("find"),y=e.includes("ls");(h||f)&&!a&&!u&&!y&&o(h&&f?"Use bash or PowerShell for file operations like listing, searching, and finding files":f?"Use PowerShell for file operations like listing, searching, and finding files":"Use bash for file operations like ls, rg, find");for(const l of e)for(const m of t[l]??[])o(m);for(const l of n)o(l);return e.length>0&&(o("When several tool calls do not depend on each other's results (reading multiple files, independent searches or commands), make them all in one response; they run in parallel. Each extra round trip costs the user seconds"),o("Answer as soon as you can: once you know enough, give the answer or your best current conclusion, then offer to dig further. Do not investigate everything before saying anything"),o("During longer work, tell the user every few tool rounds, in a sentence or two, what you found and what you will check next"),o("If you cannot tell which product, project or file the user means, ask instead of searching widely on a guess. When the user writes while you are working, respond to that message first: it may change the direction"),o("In a small project, read every source file the task touches in one response (parallel reads, or one command that prints them) instead of exploring one file per round"),o("Verify the behaviours the request names and the edge cases it implies, within a few minutes; do not write exhaustive or randomized test sweeps or repeated stress runs unless asked"),o("Before reporting done, run every code path you added at least once, including backward-compatibility, fallback and error branches: a branch that never ran is not verified"),o("Reproduce a reported bug before changing code. If it does not reproduce, or the premise does not match what the code, data or tests show, report the evidence and stop without editing product code, whatever a loaded skill assumes"),o("When a protection refuses a call, stop that step and tell the user why; never reach the same data another way (a copy, another tool or path)"),o(`Adapt instructions written for another agent before following or delegating them; drop what conflicts with your protections. You are ${p}: co-author trailer "Co-Authored-By: ${p} <noreply@deepailab.ai>", never Claude, Codex or Copilot`),o("Before calling a multi-part task done, match each part to its evidence and name what is not done or partly done; a load check is not a review")),o(`Text inside <${A} type="..."> tags comes from ${p} itself, not from the user: follow its instructions, but do not mistake it for the user's request or reply to it as if the user had written it`),o("Reply in the language of the user's latest message, whatever language tool results, skills or injected notices use"),o("Be concise in your responses"),o("Show file paths clearly when working with files"),r.map(l=>`- ${l}`).join(`
6
+ `)}c(G,"buildRules");function B(e){const t=M(e),{customPrompt:n,selectedTools:r,hiddenTools:d,toolSnippets:o,toolGuidelines:h,promptGuidelines:f,appendSystemPrompt:a,sections:u,cwd:y,contextFiles:l,skills:m}=t;for(const s of Object.keys(u))if(!F.test(s)||s==="preamble")throw new Error(`Invalid system prompt section name: ${s}`);const b=r.filter(s=>!d.includes(s)),i={};if(n)i.preamble=n;else{i.preamble=`You are an expert coding assistant operating inside ${p} (${E}). You help users by reading files, executing commands, editing code, and writing new files.`;const s=b.filter(w=>!!o[w]),g=s.length>0?s.map(w=>`- ${w}: ${o[w]}`).join(`
7
+ `):"(none)";i.tools=`${g}
8
8
 
9
- In addition to the tools above, you may have access to other custom tools depending on the project.`,r.rules=L(w,p,h),r.docs=W()}a&&(r.addendum=a),l.length>0&&(r.project_context=G(l));const S=["read","bash"],k=S.find(s=>w.includes(s))??(S.some(s=>i.includes(s))?"indirect":void 0);if(k&&m.length>0){const s=D(m,k).trim();s&&(r.skills=s)}r.cwd=y.replace(/\\/g,"/"),t.gitState&&!g.git_state&&(r.git=N(y));for(const[s,u]of Object.entries(g))u&&(r[s]=u);const x={preamble:r.preamble};for(const[s,u]of Object.entries(r))s!=="preamble"&&(x[s]=`<${s}>
10
- ${u}
11
- </${s}>`);return x}c(F,"buildSystemPromptSections");const U="cwd",B="Environment of this session, part of the system prompt. Later updates to these sections arrive as system prompt updates.";function X(e){const t=e[0];if(!t||t.role!=="system"||!t.sections)return e;const n=Object.keys(t.sections),i=n.indexOf(U);if(i===-1)return e;const d=n.slice(i).map(a=>t.sections?.[a]).filter(a=>typeof a=="string"&&a.length>0),o=Object.fromEntries(n.slice(0,i).map(a=>[a,t.sections?.[a]??null])),p={...t,sections:o};if(d.length===0)return[p,...e.slice(1)];const h={role:"user",content:[{type:"text",text:`<session_environment>
12
- ${B}
9
+ In addition to the tools above, you may have access to other custom tools depending on the project.`,i.rules=G(b,h,f),i.docs=z()}a&&(i.addendum=a),l.length>0&&(i.project_context=C(l));const k=["read","bash"],S=k.find(s=>b.includes(s))??(k.some(s=>r.includes(s))?"indirect":void 0);if(S&&m.length>0){const s=D(m,S).trim();s&&(i.skills=s)}if(i.cwd=y.replace(/\\/g,"/"),t.gitState&&!u.git_state&&(i.git=N(y)),t.projectFacts&&!u.project){const s=R(y);s&&(i.project=s)}for(const[s,g]of Object.entries(u))g&&(i[s]=g);const x={preamble:i.preamble};for(const[s,g]of Object.entries(i))s!=="preamble"&&(x[s]=`<${s}>
10
+ ${g}
11
+ </${s}>`);return x}c(B,"buildSystemPromptSections");const L="cwd",W="Environment of this session, part of the system prompt. Later updates to these sections arrive as system prompt updates.";function Z(e){const t=e[0];if(!t||t.role!=="system"||!t.sections)return e;const n=Object.keys(t.sections),r=n.indexOf(L);if(r===-1)return e;const d=n.slice(r).map(a=>t.sections?.[a]).filter(a=>typeof a=="string"&&a.length>0),o=Object.fromEntries(n.slice(0,r).map(a=>[a,t.sections?.[a]??null])),h={...t,sections:o};if(d.length===0)return[h,...e.slice(1)];const f={role:"user",content:[{type:"text",text:`<session_environment>
12
+ ${W}
13
13
 
14
14
  ${d.join(`
15
15
 
16
16
  `)}
17
- </session_environment>`}],timestamp:t.timestamp};return[p,h,...e.slice(1)]}c(X,"moveSessionEnvironmentOutOfSystemPrompt");function C(e){return e.forceSystemPrompt!==void 0?{content:e.forceSystemPrompt}:{content:"",sections:F(e)}}c(C,"buildSystemPromptState");function Q(e){return E({role:"system",...C(e),timestamp:0})}c(Q,"buildSystemPrompt");function Z(e,t){const n={};for(const[i,d]of Object.entries(t))e[i]!==d&&(n[i]=d);for(const i of Object.keys(e))t[i]===void 0&&(n[i]=null);return Object.keys(n).length>0?n:void 0}c(Z,"diffSystemPromptSections");function W(){if(I){const e=j();return`${f} documentation (read only when the user asks about ${f} itself: its commands, settings, skills, prompt templates, extensions, packages, themes or keybindings):
18
- - Start with: ${v(e,"README.md")}
17
+ </session_environment>`}],timestamp:t.timestamp};return[h,f,...e.slice(1)]}c(Z,"moveSessionEnvironmentOutOfSystemPrompt");function U(e){return e.forceSystemPrompt!==void 0?{content:e.forceSystemPrompt}:{content:"",sections:B(e)}}c(U,"buildSystemPromptState");function ee(e){return j({role:"system",...U(e),timestamp:0})}c(ee,"buildSystemPrompt");function te(e,t){const n={};for(const[r,d]of Object.entries(t))e[r]!==d&&(n[r]=d);for(const r of Object.keys(e))t[r]===void 0&&(n[r]=null);return Object.keys(n).length>0?n:void 0}c(te,"diffSystemPromptSections");function z(){if(I){const e=$();return`${p} documentation (read only when the user asks about ${p} itself: its commands, settings, skills, prompt templates, extensions, packages, themes or keybindings):
18
+ - Start with: ${P(e,"README.md")}
19
19
  - Topics, in the same folder: skills.md, prompt-templates.md, extensions.md, packages.md, themes.md, keybindings.md, settings.md
20
20
  - Resolve those file names under ${e}, not the current working directory
21
- - Read the relevant file completely before answering or implementing, and describe the product as ${f}`}return`${f} documentation (read only when the user asks about ${f} itself, its SDK, extensions, themes, skills, or TUI):
21
+ - Read the relevant file completely before answering or implementing, and describe the product as ${p}
22
+ - To write an extension, follow "Writing one for the user" in extensions.md`}return`${p} documentation (read only when the user asks about ${p} itself, its SDK, extensions, themes, skills, or TUI):
22
23
  - Main documentation: ${_()}
23
24
  - Additional docs: ${T()}
24
25
  - Examples: ${O()} (extensions, custom tools, SDK)
25
26
  - When reading these docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory
26
27
  - When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), packages (docs/packages.md), environment variables (docs/environment-variables.md), MCP servers (docs/mcp.md), codemode scripts and non-LLM models such as classifiers and image models (docs/codemode.md)
27
28
  - When working on these topics, read the docs and examples, and follow .md cross-references before implementing
28
- - Always read these .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`}c(W,"buildDocumentationSection");export{U as SESSION_ENVIRONMENT_FIRST_SECTION,Q as buildSystemPrompt,F as buildSystemPromptSections,C as buildSystemPromptState,Z as diffSystemPromptSections,X as moveSessionEnvironmentOutOfSystemPrompt,R as normalizeBuildSystemPromptOptions};
29
+ - Always read these .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`}c(z,"buildDocumentationSection");export{L as SESSION_ENVIRONMENT_FIRST_SECTION,ee as buildSystemPrompt,B as buildSystemPromptSections,U as buildSystemPromptState,te as diffSystemPromptSections,Z as moveSessionEnvironmentOutOfSystemPrompt,M as normalizeBuildSystemPromptOptions};
@@ -1,19 +1,20 @@
1
- var _e=Object.defineProperty;var r=(t,e)=>_e(t,"name",{value:e,configurable:!0});import{constants as ye}from"node:fs";import{access as ge}from"node:fs/promises";import{constants as $e}from"node:os";import{ToolExecutionError as Le}from"@earendil-works/pi-agent-core";import{Container as Ce,Text as G,truncateToWidth as Te}from"@earendil-works/pi-tui";import{spawn as Pe}from"child_process";import{Type as d}from"typebox";import{fill as R,t as I}from"../../dal/i18n.js";import{keyHint as Ie}from"../../modes/interactive/components/keybinding-hints.js";import{truncateToVisualLines as ve}from"../../modes/interactive/components/visual-truncate.js";import{theme as x}from"../../modes/interactive/theme/theme.js";import{waitForChildProcess as De}from"../../utils/child-process.js";import{writeOutputFile as Ae}from"../../utils/output-files.js";import{getShellConfig as ae,getShellEnv as de,killProcessTree as le,trackDetachedChildPid as ke,untrackDetachedChildPid as Fe}from"../../utils/shell.js";import{describeDenialForModel as Me}from"../sandbox/denial.js";import{getProcessShellSandbox as Ne}from"../sandbox/shell-sandbox.js";import{isReadOnlyBashCommand as Be}from"./bash-read-only.js";import{OutputAccumulator as Re}from"./output-accumulator.js";import{condenseShellOutput as Ue,outputCondenseDisabled as je}from"./output-condense.js";import{countOutputLines as Ge,formatCollapsedSummary as We,getTextOutput as ue,invalidArgText as He,str as ce,truncateDisplay as Ve}from"./render-utils.js";import{wrapToolDefinition as Xe}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as Ye,formatSize as Ke,SHELL_OUTPUT_MAX_CHARS as ee,truncateHeadTail as qe}from"./truncate.js";const me=2147483647,pe=1024*1024,ze=8*1024*1024,Je=me/1e3,te=12e4,ne=30;function Qe(t){if(t===void 0)return te;if(!Number.isFinite(t)||t<=0)throw new Error("Invalid timeout: must be a finite number of seconds");const e=t*1e3;if(e>me)throw new Error(`Invalid timeout: maximum is ${Je} seconds`);return e}r(Qe,"resolveTimeoutMs");const fe=d.Object({command:d.String({description:"Shell command to execute"}),description:d.String({description:`What it does and why, 3-10 words in the user's language, shown instead of the command: "Find hardcoded key names", not "run grep"`}),timeout:d.Optional(d.Number({description:"Seconds to wait for the command (default in the tool description). Raise it for long builds."}))}),Ze=d.Optional(d.Object({mode:d.Union([d.Literal("allow"),d.Literal("unsandboxed")],{description:'"allow": stay sandboxed with the domains/paths below; "unsandboxed": run outside the sandbox'}),justification:d.String({description:"Why, in one sentence for the user, who must approve it"}),allow_domains:d.Optional(d.Array(d.String(),{description:"e.g. registry.npmjs.org"})),allow_write:d.Optional(d.Array(d.String(),{description:"Paths to make writable"}))},{description:"Only after the sandbox blocked this command: the access it needs. Never pre-emptively."})),et=d.Object({...fe.properties,sandbox_escalation:Ze}),he={snippet:"Execute bash commands (ls, grep, find, etc.)",guidelines:["You can inspect DAL_* environment variables for current model and session details."]},tt=d.Object({output:d.String({description:"Combined stdout and stderr, possibly truncated"}),truncated:d.Boolean(),full_output_path:d.Optional(d.String({description:"Full output, when truncated"})),exit_code:d.Number({description:"-1 while the command runs in the background"}),background_id:d.Optional(d.String({description:"Background process id, when it is still running"})),wall_time_seconds:d.Number()});function nt(t,e){return{exec:r(async(n,o,{onData:l,signal:i,timeout:_,env:w,yieldTo:s})=>{const y=Qe(_);if(i?.aborted)throw new Error("aborted");const S=e();try{await ge(o,ye.F_OK)}catch{throw new Error(`Working directory does not exist: ${o}
2
- Cannot execute ${t} commands.`)}const b=S.commandTransport==="stdin",u=Pe(S.shell,b?S.args:[...S.args,n],{cwd:o,detached:process.platform!=="win32",env:w??de(),stdio:[b?"pipe":"ignore","pipe","pipe"],windowsHide:!0});b&&(u.stdin?.on("error",()=>{}),u.stdin?.end(n)),u.pid&&ke(u.pid);let a=!1,m=!1,h;const p=new Promise(A=>{h=r(()=>A("yielded"),"onYielded")});let f;const O=r(()=>{u.pid&&le(u.pid)},"onAbort");try{y!==void 0&&(f=setTimeout(()=>{if(s&&u.exitCode===null&&u.signalCode===null&&s(u)){m=!0,h?.();return}a=!0,u.pid&&le(u.pid)},y)),u.stdout?.on("data",l),u.stderr?.on("data",l),i&&(i.aborted?O():i.addEventListener("abort",O,{once:!0}));const A=De(u),U=await Promise.race([A,p]);if(U==="yielded")return A.catch(()=>{}),{exitCode:null,yielded:!0};const V=U;if(i?.aborted)throw new Error("aborted");if(a)throw new Error(`timeout:${(y??te)/1e3}`);const $=u.signalCode;return{exitCode:V??($?128+($e.signals[$]??0):1)}}finally{u.pid&&!m&&Fe(u.pid),f&&clearTimeout(f),i&&i.removeEventListener("abort",O)}},"exec")}}r(nt,"createLocalShellOperations");function ot(t){return nt("bash",()=>ae(t?.shellPath))}r(ot,"createLocalBashOperations");const oe=new Set;function Ut(t){return oe.add(t),()=>{oe.delete(t)}}r(Ut,"registerShellExecutionGuard");async function it(t){for(const e of oe){let n;try{n=await e(t)}catch(o){return`Command refused: the safety check could not run (${o instanceof Error?o.message:String(o)}).`}if(n!==void 0)return n}}r(it,"shellExecutionRefusal");const st=["SESSION_ID","SESSION_FILE","PROVIDER","MODEL","REASONING_LEVEL"];function rt(t,e,n,o,l){const i={...de()};if(delete i.PI_SESSION_ID,delete i.PI_SESSION_FILE,delete i.PI_PROVIDER,delete i.PI_MODEL,delete i.PI_REASONING_LEVEL,o&&l){const w=l.model;i.PI_SESSION_ID=l.sessionManager.getSessionId();const s=l.sessionManager.getSessionFile();s&&(i.PI_SESSION_FILE=s),w&&(i.PI_PROVIDER=w.provider,i.PI_MODEL=w.id),l.thinkingLevel&&(i.PI_REASONING_LEVEL=l.thinkingLevel)}for(const w of st){delete i[`DAL_${w}`];const s=i[`PI_${w}`];s!==void 0&&(i[`DAL_${w}`]=s)}const _={command:t,cwd:e,env:i};return n?n(_):_}r(rt,"resolveSpawnContext");const at=5,dt=100;class lt extends Ce{static{r(this,"BashResultRenderComponent")}state={cachedWidth:void 0,cachedLines:void 0,cachedSkipped:void 0}}function ut(t){const e=t/1e3;if(e<60)return`${e.toFixed(1)}s`;const n=Math.floor(e),o=Math.floor(n/60),l=n%60;return o<60?`${o}m ${l}s`:`${Math.floor(o/60)}h ${o%60}m ${l}s`}r(ut,"formatDuration");function ct(t,e,n=!1){const o=ce(t?.command),l=ce(t?.description)?.trim(),i=t?.timeout,_=i?x.fg("muted",R(I(" (\u8D85\u65F6 {seconds} \u79D2)"),{seconds:i})):"";if(l){const s=x.fg("toolTitle",x.bold(l))+_;return!n||!o?s:`${s}
3
- ${x.fg("muted",` \u23BF ${e} ${o.trim()}`)}`}const w=o===null?He(x):o?x.fg("dim",Ve(o.replace(/\s+/g," ").trim(),42)):x.fg("dim","\u2026");return`${x.fg("toolTitle",x.bold(e))} ${w}${_}`}r(ct,"formatShellCall");function mt(t,e,n,o,l,i,_,w){const s=t.state;t.clear();const y=pt(n,l,i,w);if(!n.expanded&&!_){const a=ue(e,o),m=Ge(a),h=[];m>0&&h.push(R(I("{count} \u884C"),{count:m})),y&&h.push(y);const p=We(x,h);p&&t.addChild(new G(p,0,0));return}let S=ue(e,o).trim();const b=e.details?.truncation,u=e.details?.fullOutputPath;if(!n.isPartial&&b?.truncated&&u&&S.endsWith("]")){const a=S.lastIndexOf(`
1
+ var _e=Object.defineProperty;var r=(t,e)=>_e(t,"name",{value:e,configurable:!0});import{constants as ye}from"node:fs";import{access as ge}from"node:fs/promises";import{constants as $e}from"node:os";import{ToolExecutionError as Le}from"@earendil-works/pi-agent-core";import{Container as Ce,Text as G,truncateToWidth as Te}from"@earendil-works/pi-tui";import{spawn as Pe}from"child_process";import{Type as l}from"typebox";import{fill as U,t as I}from"../../dal/i18n.js";import{keyHint as Ie}from"../../modes/interactive/components/keybinding-hints.js";import{truncateToVisualLines as ve}from"../../modes/interactive/components/visual-truncate.js";import{theme as x}from"../../modes/interactive/theme/theme.js";import{waitForChildProcess as De}from"../../utils/child-process.js";import{writeOutputFile as Ae}from"../../utils/output-files.js";import{getShellConfig as ae,getShellEnv as de,killProcessTree as le,trackDetachedChildPid as ke,untrackDetachedChildPid as Me}from"../../utils/shell.js";import{missingManagedToolHint as Fe}from"../../utils/tools-manager.js";import{describeDenialForModel as Ne}from"../sandbox/denial.js";import{getProcessShellSandbox as Be}from"../sandbox/shell-sandbox.js";import{isReadOnlyBashCommand as Re}from"./bash-read-only.js";import{OutputAccumulator as Ue}from"./output-accumulator.js";import{condenseShellOutput as He,outputCondenseDisabled as je}from"./output-condense.js";import{countOutputLines as Ge,formatCollapsedSummary as We,getTextOutput as ue,invalidArgText as Ve,str as ce,truncateDisplay as Xe}from"./render-utils.js";import{wrapToolDefinition as Ye}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as Ke,formatSize as qe,SHELL_OUTPUT_MAX_CHARS as ee,truncateHeadTail as ze}from"./truncate.js";const me=2147483647,pe=1024*1024,Je=8*1024*1024,Qe=me/1e3,te=12e4,ne=30;function Ze(t){if(t===void 0)return te;if(!Number.isFinite(t)||t<=0)throw new Error("Invalid timeout: must be a finite number of seconds");const e=t*1e3;if(e>me)throw new Error(`Invalid timeout: maximum is ${Qe} seconds`);return e}r(Ze,"resolveTimeoutMs");const fe=l.Object({command:l.String({description:"Shell command to execute"}),description:l.String({description:`What it does and why, 3-10 words in the user's language, shown instead of the command: "Find hardcoded key names", not "run grep"`}),timeout:l.Optional(l.Number({description:"Seconds to wait for the command (default in the tool description). Raise it for long builds."}))}),et=l.Optional(l.Object({mode:l.Union([l.Literal("allow"),l.Literal("unsandboxed")],{description:'"allow": stay sandboxed with the domains/paths below; "unsandboxed": run outside the sandbox'}),justification:l.String({description:"Why, in one sentence for the user, who must approve it"}),allow_domains:l.Optional(l.Array(l.String(),{description:"e.g. registry.npmjs.org"})),allow_write:l.Optional(l.Array(l.String(),{description:"Paths to make writable"}))},{description:"Only after the sandbox blocked this command: the access it needs. Never pre-emptively."})),tt=l.Object({...fe.properties,sandbox_escalation:et}),he={snippet:"Execute bash commands (ls, grep, find, etc.)",guidelines:["You can inspect DAL_* environment variables for current model and session details."]},nt=l.Object({output:l.String({description:"Combined stdout and stderr, possibly truncated"}),truncated:l.Boolean(),full_output_path:l.Optional(l.String({description:"Full output, when truncated"})),exit_code:l.Number({description:"-1 while the command runs in the background"}),background_id:l.Optional(l.String({description:"Background process id, when it is still running"})),wall_time_seconds:l.Number()});function ot(t,e){return{exec:r(async(n,o,{onData:u,signal:i,timeout:g,env:w,yieldTo:s})=>{const $=Ze(g);if(i?.aborted)throw new Error("aborted");const S=e();try{await ge(o,ye.F_OK)}catch{throw new Error(`Working directory does not exist: ${o}
2
+ Cannot execute ${t} commands.`)}const b=S.commandTransport==="stdin",c=Pe(S.shell,b?S.args:[...S.args,n],{cwd:o,detached:process.platform!=="win32",env:w??de(),stdio:[b?"pipe":"ignore","pipe","pipe"],windowsHide:!0});b&&(c.stdin?.on("error",()=>{}),c.stdin?.end(n)),c.pid&&ke(c.pid);let a=!1,m=!1,h;const p=new Promise(A=>{h=r(()=>A("yielded"),"onYielded")});let f;const O=r(()=>{c.pid&&le(c.pid)},"onAbort");try{$!==void 0&&(f=setTimeout(()=>{if(s&&c.exitCode===null&&c.signalCode===null&&s(c)){m=!0,h?.();return}a=!0,c.pid&&le(c.pid)},$)),c.stdout?.on("data",u),c.stderr?.on("data",u),i&&(i.aborted?O():i.addEventListener("abort",O,{once:!0}));const A=De(c),H=await Promise.race([A,p]);if(H==="yielded")return A.catch(()=>{}),{exitCode:null,yielded:!0};const V=H;if(i?.aborted)throw new Error("aborted");if(a)throw new Error(`timeout:${($??te)/1e3}`);const L=c.signalCode;return{exitCode:V??(L?128+($e.signals[L]??0):1)}}finally{c.pid&&!m&&Me(c.pid),f&&clearTimeout(f),i&&i.removeEventListener("abort",O)}},"exec")}}r(ot,"createLocalShellOperations");function it(t){return ot("bash",()=>ae(t?.shellPath))}r(it,"createLocalBashOperations");const oe=new Set;function jt(t){return oe.add(t),()=>{oe.delete(t)}}r(jt,"registerShellExecutionGuard");async function st(t){for(const e of oe){let n;try{n=await e(t)}catch(o){return`Command refused: the safety check could not run (${o instanceof Error?o.message:String(o)}).`}if(n!==void 0)return n}}r(st,"shellExecutionRefusal");const rt=["SESSION_ID","SESSION_FILE","PROVIDER","MODEL","REASONING_LEVEL"];function at(t,e,n,o,u){const i={...de()};if(delete i.PI_SESSION_ID,delete i.PI_SESSION_FILE,delete i.PI_PROVIDER,delete i.PI_MODEL,delete i.PI_REASONING_LEVEL,o&&u){const w=u.model;i.PI_SESSION_ID=u.sessionManager.getSessionId();const s=u.sessionManager.getSessionFile();s&&(i.PI_SESSION_FILE=s),w&&(i.PI_PROVIDER=w.provider,i.PI_MODEL=w.id),u.thinkingLevel&&(i.PI_REASONING_LEVEL=u.thinkingLevel)}for(const w of rt){delete i[`DAL_${w}`];const s=i[`PI_${w}`];s!==void 0&&(i[`DAL_${w}`]=s)}const g={command:t,cwd:e,env:i};return n?n(g):g}r(at,"resolveSpawnContext");const dt=5,lt=100;class ut extends Ce{static{r(this,"BashResultRenderComponent")}state={cachedWidth:void 0,cachedLines:void 0,cachedSkipped:void 0}}function ct(t){const e=t/1e3;if(e<60)return`${e.toFixed(1)}s`;const n=Math.floor(e),o=Math.floor(n/60),u=n%60;return o<60?`${o}m ${u}s`:`${Math.floor(o/60)}h ${o%60}m ${u}s`}r(ct,"formatDuration");function mt(t,e,n=!1){const o=ce(t?.command),u=ce(t?.description)?.trim(),i=t?.timeout,g=i?x.fg("muted",U(I(" (\u8D85\u65F6 {seconds} \u79D2)"),{seconds:i})):"";if(u){const s=x.fg("toolTitle",x.bold(u))+g;return!n||!o?s:`${s}
3
+ ${x.fg("muted",` \u23BF ${e} ${o.trim()}`)}`}const w=o===null?Ve(x):o?x.fg("dim",Xe(o.replace(/\s+/g," ").trim(),42)):x.fg("dim","\u2026");return`${x.fg("toolTitle",x.bold(e))} ${w}${g}`}r(mt,"formatShellCall");function pt(t,e,n,o,u,i,g,w){const s=t.state;t.clear();const $=ft(n,u,i,w);if(!n.expanded&&!g){const a=ue(e,o),m=Ge(a),h=[];m>0&&h.push(U(I("{count} \u884C"),{count:m})),$&&h.push($);const p=We(x,h);p&&t.addChild(new G(p,0,0));return}let S=ue(e,o).trim();const b=e.details?.truncation,c=e.details?.fullOutputPath;if(!n.isPartial&&b?.truncated&&c&&S.endsWith("]")){const a=S.lastIndexOf(`
4
4
 
5
- [`);a!==-1&&S.slice(a).includes(u)&&(S=S.slice(0,a).trimEnd())}if(S){const a=S.split(`
5
+ [`);a!==-1&&S.slice(a).includes(c)&&(S=S.slice(0,a).trimEnd())}if(S){const a=S.split(`
6
6
  `).map(m=>x.fg("toolOutput",m)).join(`
7
7
  `);n.expanded?t.addChild(new G(`
8
- ${a}`,0,0)):t.addChild({render:r(m=>{if(s.cachedLines===void 0||s.cachedWidth!==m){const h=ve(a,at,m);s.cachedLines=h.visualLines,s.cachedSkipped=h.skippedCount,s.cachedWidth=m}if(s.cachedSkipped&&s.cachedSkipped>0){const h=x.fg("muted",R(I("... (\u524D\u9762\u8FD8\u6709 {count} \u884C\uFF0C"),{count:s.cachedSkipped}))+` ${Ie("app.tools.expand",I("\u5373\u53EF\u5C55\u5F00"))}${x.fg("muted",")")}`;return["",Te(h,m,"..."),...s.cachedLines??[]]}return["",...s.cachedLines??[]]},"render"),invalidate:r(()=>{s.cachedWidth=void 0,s.cachedLines=void 0,s.cachedSkipped=void 0},"invalidate")})}if(b?.truncated||u){const a=[];u&&a.push(R(I("\u5B8C\u6574\u8F93\u51FA\uFF1A{path}"),{path:u})),b?.truncated&&(b.truncatedBy==="lines"?a.push(R(I("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A {shown}/{total} \u884C"),{shown:b.outputLines,total:b.totalLines})):a.push(R(I("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A\u4E86 {shown} \u884C\uFF08\u4E0A\u9650 {limit}\uFF09"),{shown:b.outputLines,limit:Ke(b.maxBytes??Ye)}))),t.addChild(new G(`
9
- ${x.fg("warning",`[${a.join(". ")}]`)}`,0,0))}y&&t.addChild(new G(`
10
- ${x.fg("muted",y)}`,0,0))}r(mt,"rebuildBashResultRenderComponent");function pt(t,e,n,o){let l;if(!t.isPartial&&o!==void 0)l=o;else if(e!==void 0)l=(n??Date.now())-e;else return;if(!(!t.isPartial&&l<100))return`${t.isPartial?I("\u5DF2\u8FD0\u884C"):I("\u8017\u65F6")} ${ut(l)}`}r(pt,"bashTimingLabel");function ft(t,e,n){const o=n?.operations??e.defaultOperations?.()??ot({shellPath:n?.shellPath}),l=n?.commandPrefix,i=n?.exposeSessionEnvironment??!0,_=n?.spawnHook,w=n?.sandbox,s=n?.operations===void 0,y=w?.describeForModel(),S=n?.background;let b=!1;const u=r(a=>`Execute a ${e.shellName} command in the current working directory; returns stdout and stderr. Long output is cut to its start and end (error lines kept) and the full output saved to a file named in the result. ${a?`A command still running after \`timeout\` seconds (default ${ne}) keeps running in the background: you get its id and the output so far, then use the process tool to poll or kill it.`:`A command still running after \`timeout\` seconds (default ${te/1e3}) is killed.`}${y?` ${y}`:""}`,"describe");return{name:e.name,label:e.label,description:u(!1),prepareLoadout:S&&s?a=>(b=a.declared.some(m=>m.name==="process"),b?{descriptions:{[e.name]:u(!0)}}:void 0):void 0,promptSnippet:e.promptSnippet,promptGuidelines:i&&e.promptGuidelines?[...e.promptGuidelines]:void 0,executionMode:"sequential",executionModeFor:e.readOnlyCommand&&!l?a=>e.readOnlyCommand?.(a?.command)?"parallel":void 0:void 0,parameters:w?.active?et:fe,outputSchema:tt,constrainedSampling:{type:"json_schema",strict:"prefer"},async execute(a,m,h,p,f){const{command:O,timeout:A}=m;p&&p({content:[],details:void 0});const U=await it({toolName:e.name,command:O,cwd:f?.cwd||t,sessionFile:f?.sessionManager?.getSessionFile()});if(U!==void 0)throw new Error(U);const V=l?`${l}
11
- ${O}`:O,$=rt(V,f?.cwd||t,_,i,f),X=w??(s?Ne():void 0);let L;if(X?.active){if(!e.sandboxShell)throw new Error(`Command refused: ${e.shellName} commands cannot run inside the OS sandbox yet, and the sandbox level is "${X.level}". Use the bash tool, or the user can opt out with \`dal --sandbox off\`.`);L=await X.prepare({command:$.command,cwd:$.cwd,shell:e.sandboxShell(n?.shellPath),shellKind:e.sandboxShellKind??"bash",env:$.env,toolCallId:a,toolName:e.name,escalation:m.sandbox_escalation,ctx:f,signal:h})}const T=new Re({tempFilePrefix:e.tempFilePrefix,maxBytes:ee});let W=!0,j,Y=!1,ie=0;const K=r(()=>{if(!p||!Y)return;Y=!1,ie=Date.now();const c=T.snapshot({persistIfTruncated:!0});p({content:[{type:"text",text:c.content||""}],details:{truncation:c.truncation.truncated?c.truncation:void 0,fullOutputPath:c.fullOutputPath}})},"emitOutputUpdate"),q=r(()=>{j&&(clearTimeout(j),j=void 0)},"clearUpdateTimer"),we=r(()=>{if(!p)return;Y=!0;const c=dt-(Date.now()-ie);if(c<=0){q(),K();return}j??=setTimeout(()=>{j=void 0,K()},c)},"scheduleOutputUpdate"),Se=r(c=>{W&&(T.append(c),we())},"handleData"),be=r(async()=>{W=!1,T.finish(),q(),K();const c=T.snapshot({persistIfTruncated:!0});return await T.closeTempFile(),c},"finishOutput"),z=r(async(c="(no output)")=>{const g=await be(),k=await T.readFullOutput(ze),C=je()?void 0:Ue(k.content),E=qe(C?.text??k.content,ee);let D=g.fullOutputPath;(E.truncated||C)&&!D&&(D=await Ae(e.tempFilePrefix,".log",k.content));let F=E.content||c,N;const B=g.truncation.totalLines;return E.truncated?(N={truncation:{content:E.content,truncated:!0,truncatedBy:"bytes",totalLines:B,totalBytes:g.truncation.totalBytes,outputLines:E.headLines+E.tailLines,outputBytes:Buffer.byteLength(E.content,"utf-8"),lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:B,maxBytes:ee},fullOutputPath:D},F+=`
8
+ ${a}`,0,0)):t.addChild({render:r(m=>{if(s.cachedLines===void 0||s.cachedWidth!==m){const h=ve(a,dt,m);s.cachedLines=h.visualLines,s.cachedSkipped=h.skippedCount,s.cachedWidth=m}if(s.cachedSkipped&&s.cachedSkipped>0){const h=x.fg("muted",U(I("... (\u524D\u9762\u8FD8\u6709 {count} \u884C\uFF0C"),{count:s.cachedSkipped}))+` ${Ie("app.tools.expand",I("\u5373\u53EF\u5C55\u5F00"))}${x.fg("muted",")")}`;return["",Te(h,m,"..."),...s.cachedLines??[]]}return["",...s.cachedLines??[]]},"render"),invalidate:r(()=>{s.cachedWidth=void 0,s.cachedLines=void 0,s.cachedSkipped=void 0},"invalidate")})}if(b?.truncated||c){const a=[];c&&a.push(U(I("\u5B8C\u6574\u8F93\u51FA\uFF1A{path}"),{path:c})),b?.truncated&&(b.truncatedBy==="lines"?a.push(U(I("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A {shown}/{total} \u884C"),{shown:b.outputLines,total:b.totalLines})):a.push(U(I("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A\u4E86 {shown} \u884C\uFF08\u4E0A\u9650 {limit}\uFF09"),{shown:b.outputLines,limit:qe(b.maxBytes??Ke)}))),t.addChild(new G(`
9
+ ${x.fg("warning",`[${a.join(". ")}]`)}`,0,0))}$&&t.addChild(new G(`
10
+ ${x.fg("muted",$)}`,0,0))}r(pt,"rebuildBashResultRenderComponent");function ft(t,e,n,o){let u;if(!t.isPartial&&o!==void 0)u=o;else if(e!==void 0)u=(n??Date.now())-e;else return;if(!(!t.isPartial&&u<100))return`${t.isPartial?I("\u5DF2\u8FD0\u884C"):I("\u8017\u65F6")} ${ct(u)}`}r(ft,"bashTimingLabel");function ht(t,e,n){const o=n?.operations??e.defaultOperations?.()??it({shellPath:n?.shellPath}),u=n?.commandPrefix,i=n?.exposeSessionEnvironment??!0,g=n?.spawnHook,w=n?.sandbox,s=n?.operations===void 0,$=w?.describeForModel(),S=n?.background;let b=!1;const c=r(a=>`Execute a ${e.shellName} command in the current working directory; returns stdout and stderr. Long output is cut to its start and end (error lines kept) and the full output saved to a file named in the result. ${a?`A command still running after \`timeout\` seconds (default ${ne}) keeps running in the background: you get its id and the output so far, then use the process tool to poll or kill it.`:`A command still running after \`timeout\` seconds (default ${te/1e3}) is killed.`}${$?` ${$}`:""}`,"describe");return{name:e.name,label:e.label,description:c(!1),prepareLoadout:S&&s?a=>(b=a.declared.some(m=>m.name==="process"),b?{descriptions:{[e.name]:c(!0)}}:void 0):void 0,promptSnippet:e.promptSnippet,promptGuidelines:i&&e.promptGuidelines?[...e.promptGuidelines]:void 0,executionMode:"sequential",executionModeFor:e.readOnlyCommand&&!u?a=>e.readOnlyCommand?.(a?.command)?"parallel":void 0:void 0,parameters:w?.active?tt:fe,outputSchema:nt,constrainedSampling:{type:"json_schema",strict:"prefer"},async execute(a,m,h,p,f){const{command:O,timeout:A}=m;p&&p({content:[],details:void 0});const H=await st({toolName:e.name,command:O,cwd:f?.cwd||t,sessionFile:f?.sessionManager?.getSessionFile()});if(H!==void 0)throw new Error(H);const V=u?`${u}
11
+ ${O}`:O,L=at(V,f?.cwd||t,g,i,f),X=w??(s?Be():void 0);let C;if(X?.active){if(!e.sandboxShell)throw new Error(`Command refused: ${e.shellName} commands cannot run inside the OS sandbox yet, and the sandbox level is "${X.level}". Use the bash tool, or the user can opt out with \`dal --sandbox off\`.`);C=await X.prepare({command:L.command,cwd:L.cwd,shell:e.sandboxShell(n?.shellPath),shellKind:e.sandboxShellKind??"bash",env:L.env,toolCallId:a,toolName:e.name,escalation:m.sandbox_escalation,ctx:f,signal:h})}const P=new Ue({tempFilePrefix:e.tempFilePrefix,maxBytes:ee});let W=!0,j,Y=!1,ie=0;const K=r(()=>{if(!p||!Y)return;Y=!1,ie=Date.now();const d=P.snapshot({persistIfTruncated:!0});p({content:[{type:"text",text:d.content||""}],details:{truncation:d.truncation.truncated?d.truncation:void 0,fullOutputPath:d.fullOutputPath}})},"emitOutputUpdate"),q=r(()=>{j&&(clearTimeout(j),j=void 0)},"clearUpdateTimer"),we=r(()=>{if(!p)return;Y=!0;const d=lt-(Date.now()-ie);if(d<=0){q(),K();return}j??=setTimeout(()=>{j=void 0,K()},d)},"scheduleOutputUpdate"),Se=r(d=>{W&&(P.append(d),we())},"handleData"),be=r(async()=>{W=!1,P.finish(),q(),K();const d=P.snapshot({persistIfTruncated:!0});return await P.closeTempFile(),d},"finishOutput"),z=r(async(d="(no output)")=>{const _=await be(),k=await P.readFullOutput(Je),T=je()?void 0:He(k.content),E=ze(T?.text??k.content,ee);let D=_.fullOutputPath;(E.truncated||T)&&!D&&(D=await Ae(e.tempFilePrefix,".log",k.content));let M=E.content||d,B;const R=_.truncation.totalLines;return E.truncated?(B={truncation:{content:E.content,truncated:!0,truncatedBy:"bytes",totalLines:R,totalBytes:_.truncation.totalBytes,outputLines:E.headLines+E.tailLines,outputBytes:Buffer.byteLength(E.content,"utf-8"),lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:R,maxBytes:ee},fullOutputPath:D},M+=`
12
12
 
13
- [Truncated: first ${E.headLines} and last ${E.tailLines} of ${E.totalLines} lines shown${C?`, after condensing ${B} lines (${C.summary})`:""}; read more with read (offset/limit) or grep. Full output: ${D}]`):C&&(N={fullOutputPath:D},F+=`
13
+ [Truncated: first ${E.headLines} and last ${E.tailLines} of ${E.totalLines} lines shown${T?`, after condensing ${R} lines (${T.summary})`:""}; read more with read (offset/limit) or grep. Full output: ${D}]`):T&&(B={fullOutputPath:D},M+=`
14
14
 
15
- [Condensed: ${C.summary}. Full output: ${D}]`),{text:F,details:N,snapshot:g}},"modelOutput"),M=r((c,g)=>`${c?`${c}
15
+ [Condensed: ${T.summary}. Full output: ${D}]`),{text:M,details:B,snapshot:_}},"modelOutput"),N=r((d,_)=>`${d?`${d}
16
16
 
17
- `:""}${g}`,"appendStatus"),se=performance.now();let v;const J=S&&s&&b?c=>{W=!1;try{return v=S.adopt({child:c,command:O,cwd:$.cwd,...L?{prepared:L}:{},...T.handOff()}),!0}catch{return W=!0,!1}}:void 0;try{let c;try{const P=await o.exec(L?.command??$.command,$.cwd,{onData:Se,signal:h,timeout:A??(J?ne:void 0),env:$.env,...J?{yieldTo:J}:{}});if(P.yielded&&v){const{text:H,details:Z}=await z(""),xe=A??ne,Ee=v.urls.length>0?` It printed ${v.urls.join(" ")}.`:"",Oe=`[Still running after ${xe}s, now in the background as ${v.id}.${Ee} For new output and the exit code call process with action "poll" and id "${v.id}"; "kill" stops it.]`,re=await T.readFullOutput(pe);return{content:[{type:"text",text:M(H,Oe)}],details:{...Z,background:v},structuredContent:{output:re.content,truncated:re.truncated,exit_code:-1,background_id:v.id,wall_time_seconds:Math.round((performance.now()-se)/100)/10}}}c=P.exitCode}catch(P){const{text:H}=await z("");if(await L?.finish(null,""),P instanceof Error&&P.message==="aborted")throw new Error(M(H,"Command aborted"));if(P instanceof Error&&P.message.startsWith("timeout:")){const Z=P.message.split(":")[1];throw new Error(M(H,`Command timed out after ${Z} seconds`))}throw P}const{text:g,details:k,snapshot:C}=await z(),E=await L?.finish(c,C.content||"");if(E&&L)throw new Le(`${M(g,`Command exited with code ${c??"(none)"}`)}
17
+ `:""}${_}`,"appendStatus"),se=performance.now();let v;const J=S&&s&&b?d=>{W=!1;try{return v=S.adopt({child:d,command:O,cwd:L.cwd,...C?{prepared:C}:{},...P.handOff()}),!0}catch{return W=!0,!1}}:void 0;try{let d;try{const y=await o.exec(C?.command??L.command,L.cwd,{onData:Se,signal:h,timeout:A??(J?ne:void 0),env:L.env,...J?{yieldTo:J}:{}});if(y.yielded&&v){const{text:F,details:Z}=await z(""),xe=A??ne,Ee=v.urls.length>0?` It printed ${v.urls.join(" ")}.`:"",Oe=`[Still running after ${xe}s, now in the background as ${v.id}.${Ee} For new output and the exit code call process with action "poll" and id "${v.id}"; "kill" stops it.]`,re=await P.readFullOutput(pe);return{content:[{type:"text",text:N(F,Oe)}],details:{...Z,background:v},structuredContent:{output:re.content,truncated:re.truncated,exit_code:-1,background_id:v.id,wall_time_seconds:Math.round((performance.now()-se)/100)/10}}}d=y.exitCode}catch(y){const{text:F}=await z("");if(await C?.finish(null,""),y instanceof Error&&y.message==="aborted")throw new Error(N(F,"Command aborted"));if(y instanceof Error&&y.message.startsWith("timeout:")){const Z=y.message.split(":")[1];throw new Error(N(F,`Command timed out after ${Z} seconds`))}throw y}const{text:_,details:k,snapshot:T}=await z(),E=await C?.finish(d,T.content||"");if(E&&C)throw new Le(`${N(_,`Command exited with code ${d??"(none)"}`)}
18
18
 
19
- ${Me(E)}`,{...k,sandbox:L.details});if(c===null)throw new Error(M(g,"Command terminated without an exit code"));const D=Math.round((performance.now()-se)/100)/10,F=await T.readFullOutput(pe),N={output:F.content,truncated:F.truncated,...F.truncated&&C.fullOutputPath?{full_output_path:C.fullOutputPath}:{},exit_code:c,wall_time_seconds:D},B=L?.details.escalation?L.details:void 0,Q=B?{...k,sandbox:B}:k;return c!==0?{content:[{type:"text",text:M(g,`Command exited with code ${c}`)}],details:Q,structuredContent:N,isError:!0}:{content:[{type:"text",text:g}],details:Q,structuredContent:N}}finally{q()}},renderCall(a,m,h){const p=h.state;h.executionStarted&&p.startedAt===void 0&&(p.startedAt=Date.now(),p.endedAt=void 0);const f=h.lastComponent??new G("",0,0);return f.setText(ct(a,e.prompt,h.expanded===!0)),f},renderResult(a,m,h,p){const f=p.state;f.startedAt!==void 0&&m.isPartial&&!f.interval&&(f.interval=setInterval(()=>p.invalidate(),1e3)),(!m.isPartial||p.isError)&&(f.endedAt??=Date.now(),f.interval&&(clearInterval(f.interval),f.interval=void 0));const O=p.lastComponent??new lt;return mt(O,a,m,p.showImages,f.startedAt,f.endedAt,p.isError,p.durationMs),O.invalidate(),O}}}r(ft,"createShellToolDefinition");const ht={name:"bash",label:"bash",shellName:"bash",prompt:"$",promptSnippet:he.snippet,promptGuidelines:he.guidelines,tempFilePrefix:"dal-bash",readOnlyCommand:Be,sandboxShell:r(t=>ae(t).shell,"sandboxShell")};function wt(t,e){return ft(t,ht,e)}r(wt,"createBashToolDefinition");function jt(t,e){const n=wt(t,e),o=Xe(n);return Object.assign(o,{promptSnippet:n.promptSnippet,promptGuidelines:n.promptGuidelines}),o}r(jt,"createBashTool");export{he as bashToolSystemPromptContribution,jt as createBashTool,wt as createBashToolDefinition,ot as createLocalBashOperations,nt as createLocalShellOperations,ft as createShellToolDefinition,Ut as registerShellExecutionGuard,Ze as sandboxEscalationSchema};
19
+ ${Ne(E)}`,{...k,sandbox:C.details});if(d===null)throw new Error(N(_,"Command terminated without an exit code"));const D=Math.round((performance.now()-se)/100)/10,M=await P.readFullOutput(pe),B={output:M.content,truncated:M.truncated,...M.truncated&&T.fullOutputPath?{full_output_path:T.fullOutputPath}:{},exit_code:d,wall_time_seconds:D},R=C?.details.escalation?C.details:void 0,Q=R?{...k,sandbox:R}:k;if(d!==0){const y=d===127?await Fe(_):void 0,F=N(_,`Command exited with code ${d}`);return{content:[{type:"text",text:y?`${F}
20
+ ${y}`:F}],details:Q,structuredContent:B,isError:!0}}return{content:[{type:"text",text:_}],details:Q,structuredContent:B}}finally{q()}},renderCall(a,m,h){const p=h.state;h.executionStarted&&p.startedAt===void 0&&(p.startedAt=Date.now(),p.endedAt=void 0);const f=h.lastComponent??new G("",0,0);return f.setText(mt(a,e.prompt,h.expanded===!0)),f},renderResult(a,m,h,p){const f=p.state;f.startedAt!==void 0&&m.isPartial&&!f.interval&&(f.interval=setInterval(()=>p.invalidate(),1e3)),(!m.isPartial||p.isError)&&(f.endedAt??=Date.now(),f.interval&&(clearInterval(f.interval),f.interval=void 0));const O=p.lastComponent??new ut;return pt(O,a,m,p.showImages,f.startedAt,f.endedAt,p.isError,p.durationMs),O.invalidate(),O}}}r(ht,"createShellToolDefinition");const wt={name:"bash",label:"bash",shellName:"bash",prompt:"$",promptSnippet:he.snippet,promptGuidelines:he.guidelines,tempFilePrefix:"dal-bash",readOnlyCommand:Re,sandboxShell:r(t=>ae(t).shell,"sandboxShell")};function St(t,e){return ht(t,wt,e)}r(St,"createBashToolDefinition");function Gt(t,e){const n=St(t,e),o=Ye(n);return Object.assign(o,{promptSnippet:n.promptSnippet,promptGuidelines:n.promptGuidelines}),o}r(Gt,"createBashTool");export{he as bashToolSystemPromptContribution,Gt as createBashTool,St as createBashToolDefinition,it as createLocalBashOperations,ot as createLocalShellOperations,ht as createShellToolDefinition,jt as registerShellExecutionGuard,et as sandboxEscalationSchema};
@@ -0,0 +1,5 @@
1
+ export declare function pathExists(filePath: string): Promise<boolean>;
2
+ export declare function expandPath(filePath: string): string;
3
+ export declare function resolveToCwd(filePath: string, cwd: string): string;
4
+ export declare function resolveReadPath(filePath: string, cwd: string): string;
5
+ export declare function resolveReadPathAsync(filePath: string, cwd: string): Promise<string>;
@@ -13,7 +13,9 @@ export interface ProcessToolDetails {
13
13
  process?: BackgroundProcessInfo;
14
14
  processes?: BackgroundProcessInfo[];
15
15
  }
16
+ export declare const POLL_BUDGET_SECONDS = 180;
16
17
  export declare function createProcessToolDefinition(cwd: string, manager: BackgroundProcessManager, options?: {
17
18
  sandboxed?: boolean;
19
+ pollBudgetSeconds?: number;
18
20
  }): ToolDefinition<typeof processSchema, ProcessToolDetails | undefined>;
19
21
  export {};
@@ -1,22 +1,23 @@
1
- var _=Object.defineProperty;var m=(t,e)=>_(t,"name",{value:e,configurable:!0});import{ToolExecutionError as F}from"@earendil-works/pi-agent-core";import{Text as g}from"@earendil-works/pi-tui";import{Type as n}from"typebox";import{theme as w}from"../../modes/interactive/theme/theme.js";import{describeDenialForModel as S}from"../sandbox/denial.js";import{sandboxEscalationSchema as y}from"./bash.js";import{getTextOutput as k}from"./render-utils.js";import{SHELL_OUTPUT_MAX_CHARS as C,truncateHeadTail as U}from"./truncate.js";const T=n.Object({action:n.Union([n.Literal("start"),n.Literal("poll"),n.Literal("stdin"),n.Literal("kill"),n.Literal("list")],{description:'"start" a command in the background; "poll": new output and state; "stdin": send `input`; "kill"; "list"'}),command:n.Optional(n.String({description:'For "start"'})),id:n.Optional(n.String({description:'Process id (from bash or "start")'})),input:n.Optional(n.String({description:'For "stdin"; end with \\n to send a line'})),wait:n.Optional(n.Number({description:'Seconds to wait; "poll" returns early when it exits (default 30, max 300)'}))}),P=n.Object({...T.properties,sandbox_escalation:y}),j=30,D=300,E=2;function x(t){const e=[`${t.id}${t.name?` (${t.name})`:""}: ${t.state}`];t.pid&&e.push(`pid ${t.pid}`),t.state!=="running"&&t.exitCode!==void 0&&e.push(`exit code ${t.exitCode??"none"}`),t.signal&&e.push(`signal ${t.signal}`),t.ports.length>0&&e.push(`ports ${t.ports.join(", ")}`),t.urls.length>0&&e.push(`urls ${t.urls.join(" ")}`),t.sandboxed&&e.push("sandboxed");const o=[e.join(", "),`command: ${t.command}`,`log: ${t.logFile}`];return t.sandboxed&&!t.portsReachableFromHost&&t.ports.length>0&&o.push("note: on Linux the sandbox gives the process its own network namespace; these ports are not reachable from outside the sandbox."),o.join(`
2
- `)}m(x,"describe");function O(t,e){return new Promise(o=>{if(t<=0||e?.aborted)return o();const d=setTimeout(o,t);e?.addEventListener("abort",()=>{clearTimeout(d),o()},{once:!0})})}m(O,"sleep");function $(t,e){const o=typeof t=="number"&&Number.isFinite(t)&&t>=0?t:e;return Math.min(o,D)*1e3}m($,"waitMs");function f(t,e){if(!t)return"(no new output)";const o=U(t,C);return o.truncated?`${o.content}
3
- [Truncated; full output: ${e}]`:o.content}m(f,"limitOutput");function q(t,e,o={}){return{name:"process",label:"process",description:'Background processes: commands bash moved to the background at their timeout, or started here. "poll" waits for new output and returns it with the state (exit code, listening ports and URLs). Processes stop when the session ends.'+(o.sandboxed?' Under the sandbox only commands started here may listen on localhost: start dev servers with "start".':""),promptSnippet:"Poll, feed or stop background processes",parameters:o.sandboxed?P:T,async execute(d,i,u,h,l){const s=i.action;if(s==="list"){const r=e.list();return{content:[{type:"text",text:r.length>0?r.map(x).join(`
1
+ var C=Object.defineProperty;var m=(t,e)=>C(t,"name",{value:e,configurable:!0});import{ToolExecutionError as U}from"@earendil-works/pi-agent-core";import{Text as T}from"@earendil-works/pi-tui";import{Type as o}from"typebox";import{theme as w}from"../../modes/interactive/theme/theme.js";import{describeDenialForModel as E}from"../sandbox/denial.js";import{sandboxEscalationSchema as P}from"./bash.js";import{getTextOutput as M}from"./render-utils.js";import{SHELL_OUTPUT_MAX_CHARS as j,truncateHeadTail as N}from"./truncate.js";const O=o.Object({action:o.Union([o.Literal("start"),o.Literal("poll"),o.Literal("stdin"),o.Literal("kill"),o.Literal("list")],{description:'"start" a command in the background; "poll": new output and state; "stdin": send `input`; "kill"; "list"'}),command:o.Optional(o.String({description:'For "start"'})),id:o.Optional(o.String({description:'Process id (from bash or "start")'})),input:o.Optional(o.String({description:'For "stdin"; end with \\n to send a line'})),wait:o.Optional(o.Number({description:'Seconds to wait; "poll" returns early when it exits (default 30, max 300)'}))}),A=o.Object({...O.properties,sandbox_escalation:P}),B=30,v=300,H=180,L=2;function x(t){const e=[`${t.id}${t.name?` (${t.name})`:""}: ${t.state}`];t.pid&&e.push(`pid ${t.pid}`),t.state!=="running"&&t.exitCode!==void 0&&e.push(`exit code ${t.exitCode??"none"}`),t.signal&&e.push(`signal ${t.signal}`),t.ports.length>0&&e.push(`ports ${t.ports.join(", ")}`),t.urls.length>0&&e.push(`urls ${t.urls.join(" ")}`),t.sandboxed&&e.push("sandboxed");const n=[e.join(", "),`command: ${t.command}`,`log: ${t.logFile}`];return t.sandboxed&&!t.portsReachableFromHost&&t.ports.length>0&&n.push("note: on Linux the sandbox gives the process its own network namespace; these ports are not reachable from outside the sandbox."),n.join(`
2
+ `)}m(x,"describe");function _(t,e){return new Promise(n=>{if(t<=0||e?.aborted)return n();const $=setTimeout(n,t);e?.addEventListener("abort",()=>{clearTimeout($),n()},{once:!0})})}m(_,"sleep");function g(t,e){const n=typeof t=="number"&&Number.isFinite(t)&&t>=0?t:e;return Math.min(n,v)*1e3}m(g,"waitMs");function S(t,e){if(!t)return"(no new output)";const n=N(t,j);return n.truncated?`${n.content}
3
+ [Truncated; full output: ${e}]`:n.content}m(S,"limitOutput");function K(t,e,n={}){const $=n.pollBudgetSeconds??H,b=new Map;return{name:"process",label:"process",description:'Background processes: commands bash moved to the background at their timeout, or started here. "poll" waits for new output and returns it with the state (exit code, listening ports and URLs). Processes stop when the session ends.'+(n.sandboxed?' Under the sandbox only commands started here may listen on localhost: start dev servers with "start".':""),promptSnippet:"Poll, feed or stop background processes",parameters:n.sandboxed?A:O,async execute(p,i,u,h,l){const s=i.action;if(s==="list"){const a=e.list();return{content:[{type:"text",text:a.length>0?a.map(x).join(`
4
4
 
5
- `):"No background processes."}],details:{processes:r}}}if(s==="start"){const r=i.command?.trim();if(!r)throw new Error('action "start" needs a command');const b=await e.start({command:r,cwd:l?.cwd||t,toolCallId:d,escalation:i.sandbox_escalation,ctx:l});await O($(i.wait,E),u);const{text:c,info:a}=e.read(b.id);if(a.denial)throw new F(`${x(a)}
5
+ `):"No background processes."}],details:{processes:a}}}if(s==="start"){const a=i.command?.trim();if(!a)throw new Error('action "start" needs a command');const f=await e.start({command:a,cwd:l?.cwd||t,toolCallId:p,escalation:i.sandbox_escalation,ctx:l});await _(g(i.wait,L),u);const{text:d,info:c}=e.read(f.id);if(c.denial)throw new U(`${x(c)}
6
6
 
7
- ${f(c,a.logFile)}
7
+ ${S(d,c.logFile)}
8
8
 
9
- ${S(a.denial)}`,{process:a});return{content:[{type:"text",text:`Started.
10
- ${x(a)}
9
+ ${E(c.denial)}`,{process:c});return{content:[{type:"text",text:`Started.
10
+ ${x(c)}
11
11
 
12
12
  Output so far:
13
- ${f(c,a.logFile)}`}],details:{process:a}}}const p=i.id?.trim();if(!p)throw new Error(`action "${s}" needs the process id`);if(s==="poll"||s==="stdin"){if(s==="stdin"){if(typeof i.input!="string")throw new Error('action "stdin" needs input');e.write(p,i.input),await O($(i.wait,E),u)}else await e.waitForExit(p,$(i.wait,j),u);const{text:r,truncated:b}=e.read(p),c=e.status(p),a=b?`
14
- [earlier output is in ${c.logFile}]`:"",L=c.denial?`
13
+ ${S(d,c.logFile)}`}],details:{process:c}}}const r=i.id?.trim();if(!r)throw new Error(`action "${s}" needs the process id`);if(s==="poll"||s==="stdin"){if(s==="stdin"){if(typeof i.input!="string")throw new Error('action "stdin" needs input');e.write(r,i.input),await _(g(i.wait,L),u)}else{const D=Date.now();await e.waitForExit(r,g(i.wait,B),u),b.set(r,(b.get(r)??0)+Date.now()-D)}const{text:a,truncated:f}=e.read(r),d=e.status(r),c=Math.round((b.get(r)??0)/1e3),k=d.state==="running"&&c>=$?`
14
+ [You have waited ${c}s on this process. If it is a test or verification run, it is taking too long: kill it and report what you have, or run a smaller check.]`:"",F=`${f?`
15
+ [earlier output is in ${d.logFile}]`:""}${k}`,y=d.denial?`
15
16
 
16
- ${S(c.denial)}`:"";return{content:[{type:"text",text:`${x(c)}
17
+ ${E(d.denial)}`:"";return{content:[{type:"text",text:`${x(d)}
17
18
 
18
- ${f(r,c.logFile)}${a}${L}`}],details:{process:c}}}if(s==="kill"){const r=await e.stop(p);return{content:[{type:"text",text:`Stopped.
19
- ${x(r)}`}],details:{process:r}}}throw new Error(`Unknown action: ${String(s)}`)},renderCall(d,i,u){const h=u.lastComponent??new g("",0,0),l=d?.action??"\u2026",s=l==="start"?d?.command??"":d?.id??"";return h.setText(`${w.fg("toolTitle",w.bold(`process ${l}`))} ${w.fg("dim",String(s))}`),h},renderResult(d,i,u,h){const l=h.lastComponent??new g("",0,0),s=k(d,!1).trim(),p=s.split(`
19
+ ${S(a,d.logFile)}${F}${y}`}],details:{process:d}}}if(s==="kill"){const a=await e.stop(r);return{content:[{type:"text",text:`Stopped.
20
+ ${x(a)}`}],details:{process:a}}}throw new Error(`Unknown action: ${String(s)}`)},renderCall(p,i,u){const h=u.lastComponent??new T("",0,0),l=p?.action??"\u2026",s=l==="start"?p?.command??"":p?.id??"";return h.setText(`${w.fg("toolTitle",w.bold(`process ${l}`))} ${w.fg("dim",String(s))}`),h},renderResult(p,i,u,h){const l=h.lastComponent??new T("",0,0),s=M(p,!1).trim(),r=s.split(`
20
21
  `);return l.setText(i.expanded?`
21
22
  ${w.fg("toolOutput",s)}`:`
22
- ${w.fg("toolOutput",p[0]??"")}`),l}}}m(q,"createProcessToolDefinition");export{q as createProcessToolDefinition};
23
+ ${w.fg("toolOutput",r[0]??"")}`),l}}}m(K,"createProcessToolDefinition");export{H as POLL_BUDGET_SECONDS,K as createProcessToolDefinition};
@@ -0,0 +1,29 @@
1
+ export declare const WORKSPACE_LOCK_FILE = "dal-workspace.lock";
2
+ export declare const STALE_AFTER_MS: number;
3
+ export interface WorkspaceLock {
4
+ pid: number;
5
+ host: string;
6
+ sessionId: string;
7
+ startedAt: string;
8
+ refreshedAt: string;
9
+ worktree?: string;
10
+ }
11
+ export interface WorkspaceClaim {
12
+ gitDir: string;
13
+ worktree?: string;
14
+ heldBy?: WorkspaceLock;
15
+ }
16
+ export declare function gitDirOf(dir: string): {
17
+ gitDir: string;
18
+ worktree?: string;
19
+ } | undefined;
20
+ export declare function workspaceOwnerSessionId(sessionId: string, env?: NodeJS.ProcessEnv): string;
21
+ export declare function readWorkspaceLock(gitDir: string): WorkspaceLock | undefined;
22
+ export declare function workspaceLockIsLive(lock: WorkspaceLock, now?: number): boolean;
23
+ export declare function claimWorkspace(dir: string, sessionId: string, options?: {
24
+ now?: number;
25
+ env?: NodeJS.ProcessEnv;
26
+ force?: boolean;
27
+ }): WorkspaceClaim | undefined;
28
+ export declare function releaseWorkspace(gitDir: string): void;
29
+ export declare function shellCommandDirectory(command: string, cwd: string): string;
@@ -0,0 +1,3 @@
1
+ var l=Object.defineProperty;var c=(t,e)=>l(t,"name",{value:e,configurable:!0});import{execFileSync as m}from"node:child_process";import{readFileSync as k,renameSync as y,rmSync as D,writeFileSync as A}from"node:fs";import{hostname as p}from"node:os";import{isAbsolute as E,join as u,resolve as f}from"node:path";const a="dal-workspace.lock",I=7200*1e3,O=60*1e3,x="DALCODE_PARENT_SESSION_ID",w=new Map;function _(t){const e=f(t),n=w.get(e);if(n!==void 0)return n??void 0;let r=null;try{const i=m("git",["rev-parse","--git-dir","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim().split(`
2
+ `),o=i[0]?.trim();o&&(r={gitDir:E(o)?o:f(e,o),worktree:i[1]?.trim()})}catch{r=null}return w.set(e,r),r??void 0}c(_,"gitDirOf");function v(t,e=process.env){return e[x]||t}c(v,"workspaceOwnerSessionId");function S(t){try{const e=JSON.parse(k(u(t,a),"utf8"));return typeof e.pid!="number"||typeof e.sessionId!="string"||typeof e.host!="string"?void 0:{pid:e.pid,host:e.host,sessionId:e.sessionId,startedAt:typeof e.startedAt=="string"?e.startedAt:new Date(0).toISOString(),refreshedAt:typeof e.refreshedAt=="string"?e.refreshedAt:new Date(0).toISOString(),...typeof e.worktree=="string"?{worktree:e.worktree}:{}}}catch{return}}c(S,"readWorkspaceLock");function L(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}c(L,"processAlive");function g(t,e=Date.now()){const n=Date.parse(t.refreshedAt);return!Number.isFinite(n)||e-n>I?!1:t.host===p()?L(t.pid):!0}c(g,"workspaceLockIsLive");function h(t,e){const n=u(t,a),r=`${n}.${process.pid}.tmp`;A(r,`${JSON.stringify(e,null,2)}
3
+ `),y(r,n)}c(h,"writeLock");function $(t,e,n={}){const r=_(t);if(!r)return;const i=n.now??Date.now(),o=v(e,n.env),s=S(r.gitDir),d={gitDir:r.gitDir,...r.worktree?{worktree:r.worktree}:{}};if(s&&s.sessionId!==o&&g(s,i)&&!n.force)return{...d,heldBy:s};if(s?.sessionId===o&&g(s,i)){if(!(s.pid===process.pid&&s.host===p())||i-Date.parse(s.refreshedAt)<O)return d;try{h(r.gitDir,{...s,refreshedAt:new Date(i).toISOString()})}catch{}return d}try{h(r.gitDir,{pid:process.pid,host:p(),sessionId:o,startedAt:new Date(i).toISOString(),refreshedAt:new Date(i).toISOString(),...r.worktree?{worktree:r.worktree}:{}})}catch{return}return d}c($,"claimWorkspace");function H(t){const e=S(t);if(!(!e||e.pid!==process.pid||e.host!==p()))try{D(u(t,a),{force:!0})}catch{}}c(H,"releaseWorkspace");function P(t,e){let n=e;for(const i of t.split(/&&|;|\n/)){const o=/^\s*cd\s+("([^"]+)"|'([^']+)'|(\S+))\s*$/.exec(i);if(!o)break;const s=(o[2]??o[3]??o[4]??"").replace(/^~(?=\/|$)/,process.env.HOME??"~");n=f(n,s)}const r=/\bgit\s+-C\s+("([^"]+)"|'([^']+)'|(\S+))/.exec(t);return r&&(n=f(n,r[2]??r[3]??r[4]??".")),n}c(P,"shellCommandDirectory");export{I as STALE_AFTER_MS,a as WORKSPACE_LOCK_FILE,$ as claimWorkspace,_ as gitDirOf,S as readWorkspaceLock,H as releaseWorkspace,P as shellCommandDirectory,g as workspaceLockIsLive,v as workspaceOwnerSessionId};
@@ -0,0 +1,62 @@
1
+ export interface CompatEnvInput {
2
+ agentDir: string;
3
+ packageDir?: string;
4
+ env?: NodeJS.ProcessEnv;
5
+ }
6
+ export declare const RENAMED_ENV_VARIABLES: ReadonlyArray<readonly [dal: string, pi: string]>;
7
+ export declare function communityEnv({ agentDir, packageDir, env }: CompatEnvInput): Record<string, string>;
8
+ export declare function applyCommunityEnv(input: CompatEnvInput): Record<string, string>;
9
+ export interface HardcodedPath {
10
+ file: string;
11
+ line: number;
12
+ scope: "home" | "project";
13
+ text: string;
14
+ }
15
+ export declare function findHardcodedPiPaths(source: string): Array<Omit<HardcodedPath, "file">>;
16
+ export declare function scanHardcodedPiPaths(packageRoot: string): HardcodedPath[];
17
+ export interface PathEdit {
18
+ at: number;
19
+ from: string;
20
+ to: string;
21
+ }
22
+ export declare function rewriteHomePiPaths(source: string): {
23
+ text: string;
24
+ edits: PathEdit[];
25
+ };
26
+ export declare function revertEdits(adapted: string, edits: readonly PathEdit[]): string | undefined;
27
+ export declare const HOST_PROVIDED_EXTENSION_PACKAGES: ReadonlySet<string>;
28
+ export declare function hostDependenciesOf(packageRoot: string): string[];
29
+ export declare function installedHostCopies(packageRoot: string, names: readonly string[]): string[];
30
+ export declare const ADAPTER_VERSION = 1;
31
+ export declare const ADAPTATION_FILE = ".dal-adaptation.json";
32
+ export interface AdaptedFile {
33
+ path: string;
34
+ original: string;
35
+ adapted: string;
36
+ edits: PathEdit[];
37
+ }
38
+ export interface Adaptation {
39
+ adapter: number;
40
+ name?: string;
41
+ version?: string;
42
+ adaptedAt: string;
43
+ files: AdaptedFile[];
44
+ removedHostCopies: string[];
45
+ remaining: HardcodedPath[];
46
+ }
47
+ export type AdaptationState = "clean" | "adapted" | "needs-adaptation";
48
+ export declare function adaptationState(adaptation: Adaptation): AdaptationState;
49
+ export declare function readAdaptation(packageRoot: string): Adaptation | undefined;
50
+ export declare function adaptPackage(packageRoot: string): Adaptation;
51
+ export declare function ensurePackageAdapted(packageRoot: string): Adaptation;
52
+ export interface AdaptationCheck {
53
+ ok: boolean;
54
+ mismatched: string[];
55
+ }
56
+ export declare function verifyAdaptation(packageRoot: string, adaptation?: Adaptation | undefined): AdaptationCheck;
57
+ export declare function isManagedSource(source: string): boolean;
58
+ export declare function isAdaptablePackage(packageRoot: string, source: string, roots: {
59
+ agentDir: string;
60
+ cwd?: string;
61
+ }): boolean;
62
+ export declare function tryEnsurePackageAdapted(packageRoot: string): Adaptation | undefined;