dal-code 1.0.45 → 1.0.46

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 (520) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/NOTICE +49 -1
  3. package/dist/bun/register-bedrock.js +1 -0
  4. package/dist/cli/args.js +2 -2
  5. package/dist/cli/auth-check.js +1 -1
  6. package/dist/cli/auth-command.js +6 -5
  7. package/dist/cli/experimental/auth.js +1 -0
  8. package/dist/cli/experimental/cli.js +1 -0
  9. package/dist/cli/experimental/command-options.js +1 -0
  10. package/dist/cli/experimental/command.js +1 -0
  11. package/dist/cli/experimental/commands/client.js +1 -0
  12. package/dist/cli/experimental/commands/pi.js +1 -0
  13. package/dist/cli/experimental/commands/server.js +1 -0
  14. package/dist/cli/experimental/transport-address.js +1 -0
  15. package/dist/cli/list-models.js +2 -2
  16. package/dist/cli/piped-stdin.js +2 -0
  17. package/dist/cli/startup-diagnostics.js +1 -0
  18. package/dist/client/index.js +1 -0
  19. package/dist/client/remote-session.js +1 -0
  20. package/dist/client/transcript.js +1 -0
  21. package/dist/core/agent-log.d.ts +6 -0
  22. package/dist/core/agent-log.js +3 -0
  23. package/dist/core/agent-session-services.d.ts +0 -1
  24. package/dist/core/agent-session-services.js +1 -1
  25. package/dist/core/agent-session.d.ts +19 -2
  26. package/dist/core/agent-session.js +8 -8
  27. package/dist/core/client-identity.js +1 -0
  28. package/dist/core/compaction/branch-summarization.js +3 -3
  29. package/dist/core/compaction/compaction.d.ts +2 -2
  30. package/dist/core/compaction/compaction.js +11 -9
  31. package/dist/core/compaction-backoff.js +1 -0
  32. package/dist/core/dal-session-headers.js +1 -0
  33. package/dist/core/export-html/index.js +2 -2
  34. package/dist/core/export-html/template.html +1 -0
  35. package/dist/core/export-html/template.js +6 -6
  36. package/dist/core/export-html/vendor/marked-cjk-friendly.min.js +6 -0
  37. package/dist/core/export-html/vendor/marked.min.js +30 -29
  38. package/dist/core/extensions/loader.js +1 -1
  39. package/dist/core/extensions/runner.d.ts +6 -0
  40. package/dist/core/extensions/runner.js +1 -1
  41. package/dist/core/extensions/types.d.ts +1 -0
  42. package/dist/core/extensions/virtual-modules.js +1 -1
  43. package/dist/core/http-dispatcher.js +1 -1
  44. package/dist/core/model-config.d.ts +984 -0
  45. package/dist/core/model-config.js +5 -5
  46. package/dist/core/model-identity.js +2 -0
  47. package/dist/core/model-resolver.js +1 -1
  48. package/dist/core/model-runtime.d.ts +2 -0
  49. package/dist/core/model-runtime.js +2 -2
  50. package/dist/core/package-manager.d.ts +2 -0
  51. package/dist/core/package-manager.js +2 -2
  52. package/dist/core/provider-attribution.js +1 -1
  53. package/dist/core/provider-composer.d.ts +2 -1
  54. package/dist/core/provider-composer.js +1 -1
  55. package/dist/core/sandbox/bwrap-placeholders.js +1 -1
  56. package/dist/core/sandbox/index.d.ts +1 -1
  57. package/dist/core/sandbox/index.js +1 -1
  58. package/dist/core/sandbox/policy.d.ts +4 -0
  59. package/dist/core/sandbox/policy.js +1 -1
  60. package/dist/core/sandbox/runtime.d.ts +2 -0
  61. package/dist/core/sandbox/runtime.js +1 -1
  62. package/dist/core/sandbox/shell-sandbox.d.ts +2 -0
  63. package/dist/core/sandbox/shell-sandbox.js +6 -6
  64. package/dist/core/sdk.js +1 -1
  65. package/dist/core/session-stall-monitor.d.ts +41 -0
  66. package/dist/core/session-stall-monitor.js +2 -0
  67. package/dist/core/settings-manager.d.ts +4 -0
  68. package/dist/core/settings-manager.js +1 -1
  69. package/dist/core/settings-schema.d.ts +2 -0
  70. package/dist/core/settings-schema.js +1 -1
  71. package/dist/core/stall-watchdog.d.ts +55 -0
  72. package/dist/core/stall-watchdog.js +1 -0
  73. package/dist/core/system-prompt.js +10 -10
  74. package/dist/core/tools/bash.d.ts +1 -0
  75. package/dist/core/tools/bash.js +14 -14
  76. package/dist/core/tools/edit.d.ts +1 -1
  77. package/dist/core/tools/edit.js +3 -3
  78. package/dist/core/tools/grep.js +1 -1
  79. package/dist/core/tools/path-utils.d.ts +1 -0
  80. package/dist/core/tools/path-utils.js +1 -1
  81. package/dist/dal/builtins.js +2 -2
  82. package/dist/dal/manifest.d.ts +1 -0
  83. package/dist/dal/manifest.js +1 -1
  84. package/dist/dal/safety-net.js +3 -1
  85. package/dist/extensions/codemode/execute.js +22 -16
  86. package/dist/extensions/mcp/config.js +2 -2
  87. package/dist/extensions/mcp/oauth.js +2 -2
  88. package/dist/index.d.ts +3 -2
  89. package/dist/index.js +1 -1
  90. package/dist/main.js +4 -4
  91. package/dist/migrations.js +3 -5
  92. package/dist/modes/interactive/components/daxnuts.js +1 -0
  93. package/dist/modes/interactive/external-editor.js +1 -1
  94. package/dist/modes/interactive/interactive-mode.d.ts +7 -7
  95. package/dist/modes/interactive/interactive-mode.js +25 -25
  96. package/dist/modes/interactive/session-share.js +1 -1
  97. package/dist/modes/interactive/theme/theme-json.js +12 -0
  98. package/dist/modes/interactive/theme/theme-schema.json +356 -0
  99. package/dist/modes/print-mode.d.ts +1 -0
  100. package/dist/modes/print-mode.js +8 -7
  101. package/dist/modes/rpc/rpc-client.js +3 -3
  102. package/dist/modes/rpc/rpc-mode.js +1 -1
  103. package/dist/node_modules/@dalcode/dal-advisor/package.json +3 -3
  104. package/dist/node_modules/@dalcode/dal-awake/package.json +2 -2
  105. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  106. package/dist/node_modules/@dalcode/dal-capabilities/package.json +4 -4
  107. package/dist/node_modules/@dalcode/dal-capabilities/src/catalogue.js +1 -1
  108. package/dist/node_modules/@dalcode/dal-capabilities/src/index.js +10 -10
  109. package/dist/node_modules/@dalcode/dal-capabilities/src/match.js +1 -1
  110. package/dist/node_modules/@dalcode/dal-capabilities/src/state.js +3 -3
  111. package/dist/node_modules/@dalcode/dal-codeindex/package.json +2 -2
  112. package/dist/node_modules/@dalcode/dal-codeindex/src/index.js +4 -4
  113. package/dist/node_modules/@dalcode/dal-compat/package.json +2 -2
  114. package/dist/node_modules/@dalcode/dal-dap/package.json +2 -2
  115. package/dist/node_modules/@dalcode/dal-dap/src/install.js +2 -2
  116. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  117. package/dist/node_modules/@dalcode/dal-goal/package.json +3 -3
  118. package/dist/node_modules/@dalcode/dal-guard/package.json +5 -4
  119. package/dist/node_modules/@dalcode/dal-guard/src/credentials.js +7 -1
  120. package/dist/node_modules/@dalcode/dal-guard/src/edit-anchor-core.js +25 -23
  121. package/dist/node_modules/@dalcode/dal-guard/src/edit-anchor.js +4 -4
  122. package/dist/node_modules/@dalcode/dal-guard/src/index.js +4 -4
  123. package/dist/node_modules/@dalcode/dal-guard/src/policy.js +1 -1
  124. package/dist/node_modules/@dalcode/dal-guard/src/session-files.js +1 -0
  125. package/dist/node_modules/@dalcode/dal-guard/src/suspicion.js +1 -0
  126. package/dist/node_modules/@dalcode/dal-guard/src/workspace.js +2 -2
  127. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  128. package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
  129. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  130. package/dist/node_modules/@dalcode/dal-learn/package.json +4 -2
  131. package/dist/node_modules/@dalcode/dal-learn/src/engine.js +4 -4
  132. package/dist/node_modules/@dalcode/dal-learn/src/index.js +15 -14
  133. package/dist/node_modules/@dalcode/dal-learn/src/revisions.js +3 -0
  134. package/dist/node_modules/@dalcode/dal-learn/src/safety.js +1 -1
  135. package/dist/node_modules/@dalcode/dal-learn/src/skill-evolution.js +14 -14
  136. package/dist/node_modules/@dalcode/dal-lsp/package.json +5 -3
  137. package/dist/node_modules/@dalcode/dal-lsp/src/config.js +1 -1
  138. package/dist/node_modules/@dalcode/dal-lsp/src/index.js +14 -13
  139. package/dist/node_modules/@dalcode/dal-lsp/src/managed.js +1 -0
  140. package/dist/node_modules/@dalcode/dal-mcp/package.json +7 -6
  141. package/dist/node_modules/@dalcode/dal-mcp/src/child-env.js +3 -0
  142. package/dist/node_modules/@dalcode/dal-mcp/src/stdio-client.d.ts +1 -0
  143. package/dist/node_modules/@dalcode/dal-mcp/src/stdio-client.js +3 -3
  144. package/dist/node_modules/@dalcode/dal-office/package.json +3 -2
  145. package/dist/node_modules/@dalcode/dal-office/src/extract/cell.js +1 -0
  146. package/dist/node_modules/@dalcode/dal-office/src/extract/index.js +2 -2
  147. package/dist/node_modules/@dalcode/dal-office/src/extract/ooxml.js +4 -4
  148. package/dist/node_modules/@dalcode/dal-office/src/extract/pdf.js +4 -4
  149. package/dist/node_modules/@dalcode/dal-office/src/facts.d.ts +15 -0
  150. package/dist/node_modules/@dalcode/dal-office/src/facts.js +4 -0
  151. package/dist/node_modules/@dalcode/dal-office/src/index.js +1 -1
  152. package/dist/node_modules/@dalcode/dal-office/src/lazy.js +1 -0
  153. package/dist/node_modules/@dalcode/dal-office/src/{index.d.ts → office.d.ts} +2 -3
  154. package/dist/node_modules/@dalcode/dal-office/src/office.js +1 -0
  155. package/dist/node_modules/@dalcode/dal-office/src/render/capture.d.ts +21 -0
  156. package/dist/node_modules/@dalcode/dal-office/src/render/capture.js +13 -0
  157. package/dist/node_modules/@dalcode/dal-office/src/render/chart.d.ts +15 -0
  158. package/dist/node_modules/@dalcode/dal-office/src/render/chart.js +3 -3
  159. package/dist/node_modules/@dalcode/dal-office/src/render/docx.d.ts +4 -0
  160. package/dist/node_modules/@dalcode/dal-office/src/render/docx.js +1 -1
  161. package/dist/node_modules/@dalcode/dal-office/src/render/pptx.d.ts +2 -0
  162. package/dist/node_modules/@dalcode/dal-office/src/render/pptx.js +4 -3
  163. package/dist/node_modules/@dalcode/dal-office/src/render/table-layout.js +1 -0
  164. package/dist/node_modules/@dalcode/dal-office/src/render/xlsx-chart.d.ts +24 -0
  165. package/dist/node_modules/@dalcode/dal-office/src/render/xlsx-chart.js +1 -0
  166. package/dist/node_modules/@dalcode/dal-office/src/render/xlsx.d.ts +9 -0
  167. package/dist/node_modules/@dalcode/dal-office/src/render/xlsx.js +1 -1
  168. package/dist/node_modules/@dalcode/dal-office/src/scratchpad.d.ts +2 -0
  169. package/dist/node_modules/@dalcode/dal-office/src/scratchpad.js +1 -1
  170. package/dist/node_modules/@dalcode/dal-office/src/table-stats.js +2 -0
  171. package/dist/node_modules/@dalcode/dal-office/src/tools/chart-generate.js +4 -3
  172. package/dist/node_modules/@dalcode/dal-office/src/tools/doc-generate.js +2 -3
  173. package/dist/node_modules/@dalcode/dal-office/src/tools/docx-edit.js +5 -5
  174. package/dist/node_modules/@dalcode/dal-office/src/tools/drawio-generate.js +2 -3
  175. package/dist/node_modules/@dalcode/dal-office/src/tools/md-generate.js +2 -3
  176. package/dist/node_modules/@dalcode/dal-office/src/tools/ppt-generate.js +5 -3
  177. package/dist/node_modules/@dalcode/dal-office/src/tools/ppt-plan.js +4 -2
  178. package/dist/node_modules/@dalcode/dal-office/src/tools/pptx-edit.js +5 -5
  179. package/dist/node_modules/@dalcode/dal-office/src/tools/read-file.js +4 -3
  180. package/dist/node_modules/@dalcode/dal-office/src/tools/render-page.js +4 -0
  181. package/dist/node_modules/@dalcode/dal-office/src/tools/sheet-generate.js +3 -3
  182. package/dist/node_modules/@dalcode/dal-office/src/tools/xlsx-edit.js +3 -3
  183. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +15 -15
  184. package/dist/node_modules/@dalcode/dal-pi-kit/dist/index.js +1 -1
  185. package/dist/node_modules/@dalcode/dal-pi-kit/dist/project-size.js +1 -0
  186. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  187. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +15 -15
  188. package/dist/node_modules/@dalcode/dal-pi-kit/src/index.js +1 -1
  189. package/dist/node_modules/@dalcode/dal-pi-kit/src/project-size.js +1 -0
  190. package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -5
  191. package/dist/node_modules/@dalcode/dal-plugins/src/index.js +11 -11
  192. package/dist/node_modules/@dalcode/dal-plugins/src/manage.js +7 -7
  193. package/dist/node_modules/@dalcode/dal-recall/package.json +2 -2
  194. package/dist/node_modules/@dalcode/dal-recall/src/index.js +1 -1
  195. package/dist/node_modules/@dalcode/dal-remote/package.json +2 -2
  196. package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
  197. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  198. package/dist/node_modules/@dalcode/dal-rewind/src/commands.js +1 -1
  199. package/dist/node_modules/@dalcode/dal-rewind/src/core.d.ts +2 -0
  200. package/dist/node_modules/@dalcode/dal-rewind/src/core.js +6 -6
  201. package/dist/node_modules/@dalcode/dal-rewind/src/index.js +1 -1
  202. package/dist/node_modules/@dalcode/dal-rewind/src/state.js +1 -1
  203. package/dist/node_modules/@dalcode/dal-router/package.json +8 -9
  204. package/dist/node_modules/@dalcode/dal-router/src/commands.js +8 -9
  205. package/dist/node_modules/@dalcode/dal-router/src/config.d.ts +3 -36
  206. package/dist/node_modules/@dalcode/dal-router/src/config.js +2 -2
  207. package/dist/node_modules/@dalcode/dal-router/src/index.js +2 -4
  208. package/dist/node_modules/@dalcode/dal-router/src/notice.js +1 -0
  209. package/dist/node_modules/@dalcode/dal-router/src/roles/deliverables.js +4 -0
  210. package/dist/node_modules/@dalcode/dal-router/src/roles/index.js +10 -8
  211. package/dist/node_modules/@dalcode/dal-router/src/roles/planner.js +4 -0
  212. package/dist/node_modules/@dalcode/dal-router/src/roles/prompts.js +18 -16
  213. package/dist/node_modules/@dalcode/dal-router/src/roles/signals.js +2 -2
  214. package/dist/node_modules/@dalcode/dal-router/src/runtime.d.ts +0 -13
  215. package/dist/node_modules/@dalcode/dal-router/src/runtime.js +1 -1
  216. package/dist/node_modules/@dalcode/dal-router/src/subagent.js +1 -1
  217. package/dist/node_modules/@dalcode/dal-router/src/task-shape.d.ts +8 -0
  218. package/dist/node_modules/@dalcode/dal-router/src/task-shape.js +1 -0
  219. package/dist/node_modules/@dalcode/dal-rtk/package.json +2 -2
  220. package/dist/node_modules/@dalcode/dal-skills/package.json +4 -3
  221. package/dist/node_modules/@dalcode/dal-skills/src/bundled/chart-design/SKILL.md +35 -0
  222. package/dist/node_modules/@dalcode/dal-skills/src/bundled/dal-slides/SKILL.md +17 -9
  223. package/dist/node_modules/@dalcode/dal-skills/src/bundled/diagram-design/SKILL.md +7 -5
  224. package/dist/node_modules/@dalcode/dal-skills/src/bundled/poster-design/SKILL.md +8 -6
  225. package/dist/node_modules/@dalcode/dal-skills/src/bundled/print-design/SKILL.md +21 -8
  226. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/diagram.html +1 -1
  227. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/mindmap.html +1 -1
  228. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/event-poster.html +1 -1
  229. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/poster.css +1 -1
  230. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/square-card.html +1 -1
  231. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/wechat-cover.html +1 -1
  232. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/xhs-card.html +1 -1
  233. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/xhs-cover.html +8 -5
  234. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/print/letter.html +1 -1
  235. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/print/report.html +1 -1
  236. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/print/resume.html +7 -3
  237. package/dist/node_modules/@dalcode/dal-skills/src/bundled/web-design/SKILL.md +4 -4
  238. package/dist/node_modules/@dalcode/dal-skills/src/bundled.js +1 -1
  239. package/dist/node_modules/@dalcode/dal-skills/src/catalog.js +3 -2
  240. package/dist/node_modules/@dalcode/dal-skills/src/hint.js +1 -0
  241. package/dist/node_modules/@dalcode/dal-skills/src/index.js +13 -14
  242. package/dist/node_modules/@dalcode/dal-skills/src/search.js +1 -1
  243. package/dist/node_modules/@dalcode/dal-statusline/package.json +2 -2
  244. package/dist/node_modules/@dalcode/dal-structured/package.json +2 -2
  245. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  246. package/dist/node_modules/@dalcode/dal-subagent/src/background.js +10 -10
  247. package/dist/node_modules/@dalcode/dal-subagent/src/index.js +18 -20
  248. package/dist/node_modules/@dalcode/dal-telemetry/package.json +3 -3
  249. package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
  250. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  251. package/dist/node_modules/@dalcode/dal-tool-catalog/src/groups.js +1 -1
  252. package/dist/node_modules/@dalcode/dal-tool-catalog/src/index.js +4 -4
  253. package/dist/node_modules/@dalcode/dal-usage/package.json +2 -2
  254. package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
  255. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  256. package/dist/node_modules/@dalcode/dal-workflow/src/announce-check.js +3 -1
  257. package/dist/node_modules/@dalcode/dal-workflow/src/deliverable-scope.js +1 -0
  258. package/dist/node_modules/@dalcode/dal-workflow/src/index.js +4 -4
  259. package/dist/node_modules/@dalcode/dal-workflow/src/test-proof-note.js +3 -0
  260. package/dist/node_modules/@dalcode/dal-workflow/src/todo-snapshot.js +2 -2
  261. package/dist/node_modules/@dalcode/dal-workflow/src/todo.js +4 -4
  262. package/dist/node_modules/@dalcode/dal-workflow/src/truncation-check.js +1 -0
  263. package/dist/node_modules/@dalcode/dal-workflow/src/working-contract.js +1 -1
  264. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  265. package/dist/node_modules/@dalcode/deepailab/src/index.js +3 -3
  266. package/dist/node_modules/@earendil-works/pi-agent-core/README.md +5 -0
  267. package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.d.ts +2 -1
  268. package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js +1 -1
  269. package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent.d.ts +3 -1
  270. package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent.js +1 -1
  271. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/agent-harness.js +1 -0
  272. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/branch-summarization.js +37 -0
  273. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/compaction.js +104 -0
  274. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/utils.js +16 -0
  275. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/config.js +1 -0
  276. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/context.js +1 -0
  277. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/env/nodejs.js +10 -0
  278. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/events.js +1 -0
  279. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/execution/assistant.js +1 -0
  280. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/execution/effect-gate.js +1 -0
  281. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/execution/tools.js +1 -0
  282. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/hooks.js +1 -0
  283. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/messages.js +17 -0
  284. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/bash.js +1 -0
  285. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/bounded.js +1 -0
  286. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/chord.js +1 -0
  287. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/context.js +1 -0
  288. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/harness.js +1 -0
  289. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/hooks.js +1 -0
  290. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/index.js +1 -0
  291. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/jsonl.js +4 -0
  292. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/collapse.js +3 -0
  293. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/entries.js +1 -0
  294. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/frames.js +1 -0
  295. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/generation.js +1 -0
  296. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/job.js +1 -0
  297. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/plugin.js +1 -0
  298. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/post-tools.js +1 -0
  299. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/task-api.js +1 -0
  300. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/tool.js +3 -0
  301. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/membrane.js +1 -0
  302. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/memory.js +1 -0
  303. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/scheduler.js +1 -0
  304. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/session.js +1 -0
  305. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/system.js +8 -0
  306. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/types.js +1 -0
  307. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/view.js +1 -0
  308. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/prompt-templates.js +5 -0
  309. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/reducer.js +1 -0
  310. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/result.js +1 -0
  311. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/boundary.js +1 -0
  312. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/checkpoint.js +1 -0
  313. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/deferred.js +1 -0
  314. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/generation.js +1 -0
  315. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/reconcile.js +1 -0
  316. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/recovery.js +1 -0
  317. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/response.js +1 -0
  318. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/retry.js +1 -0
  319. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/structural.js +1 -0
  320. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/terminal.js +1 -0
  321. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/tool-placement.js +1 -0
  322. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/tools.js +1 -0
  323. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive.js +1 -0
  324. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/harness.js +1 -0
  325. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/index.js +1 -0
  326. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/lane.js +1 -0
  327. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/progress.js +1 -0
  328. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/reducer.js +1 -0
  329. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/restore.js +1 -0
  330. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/transcript.js +1 -0
  331. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/types.js +1 -0
  332. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/commit.js +1 -0
  333. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/context.js +1 -0
  334. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/fork-policy.js +1 -0
  335. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/fork.js +1 -0
  336. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/in-memory-storage-state.js +1 -0
  337. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/index.js +1 -0
  338. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/codec.js +1 -0
  339. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/errors.js +1 -0
  340. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/fork.js +1 -0
  341. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/index.js +1 -0
  342. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/io.js +3 -0
  343. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/legacy-v3.js +1 -0
  344. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/repo.js +1 -0
  345. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/storage.js +8 -0
  346. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/types.js +1 -0
  347. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl-repo.js +1 -0
  348. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl-storage.js +5 -0
  349. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl.js +1 -0
  350. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/memory-repo.js +1 -0
  351. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/memory-storage.js +1 -0
  352. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/memory.js +1 -0
  353. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/mutation-line.js +1 -0
  354. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/repo-utils.js +1 -0
  355. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/session.js +1 -0
  356. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/state.js +1 -0
  357. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/benchmark/datasets.js +1 -0
  358. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/benchmark/session-repo.js +1 -0
  359. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/benchmark/storage.js +1 -0
  360. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/conformance/session-repo.js +1 -0
  361. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/conformance/storage.js +1 -0
  362. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/conformance.js +1 -0
  363. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/gating-storage.js +1 -0
  364. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/index.js +1 -0
  365. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/instrumented-storage.js +1 -0
  366. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/storage-decorator.js +1 -0
  367. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/types.js +0 -0
  368. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/types.js +1 -0
  369. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/values.js +1 -0
  370. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/skills.js +10 -0
  371. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/system-prompt.js +2 -0
  372. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/telemetry.js +1 -0
  373. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/bash.js +12 -0
  374. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit-diff.js +16 -0
  375. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit.js +1 -0
  376. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/file-mutation-queue.js +1 -0
  377. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/image.js +1 -0
  378. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/index.js +1 -0
  379. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/path-utils.js +1 -0
  380. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/read.js +14 -0
  381. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/tool-context.js +0 -0
  382. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/write.js +1 -0
  383. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/types.js +1 -0
  384. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/adaptive-publisher.js +1 -0
  385. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/output-capture.js +5 -0
  386. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/shell-output.js +1 -0
  387. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/truncate.js +5 -0
  388. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/usage.js +1 -0
  389. package/dist/node_modules/@earendil-works/pi-agent-core/dist/node.js +1 -0
  390. package/dist/node_modules/@earendil-works/pi-agent-core/dist/search/index.js +0 -0
  391. package/dist/node_modules/@earendil-works/pi-agent-core/dist/search/scanning.js +1 -0
  392. package/dist/node_modules/@earendil-works/pi-agent-core/dist/types.d.ts +2 -0
  393. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
  394. package/dist/node_modules/@earendil-works/pi-ai/README.md +78 -3
  395. package/dist/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js +5 -5
  396. package/dist/node_modules/@earendil-works/pi-ai/dist/api/azure-openai-responses.js +1 -1
  397. package/dist/node_modules/@earendil-works/pi-ai/dist/api/bedrock-converse-stream.js +1 -1
  398. package/dist/node_modules/@earendil-works/pi-ai/dist/api/classifier-shared.js +1 -1
  399. package/dist/node_modules/@earendil-works/pi-ai/dist/api/cloudflare-gateway-binding.js +1 -0
  400. package/dist/node_modules/@earendil-works/pi-ai/dist/api/cloudflare-workers-ai-system-one.js +1 -1
  401. package/dist/node_modules/@earendil-works/pi-ai/dist/api/google-generative-ai.js +1 -1
  402. package/dist/node_modules/@earendil-works/pi-ai/dist/api/google-shared.js +1 -1
  403. package/dist/node_modules/@earendil-works/pi-ai/dist/api/google-vertex.js +1 -1
  404. package/dist/node_modules/@earendil-works/pi-ai/dist/api/lazy.d.ts +6 -2
  405. package/dist/node_modules/@earendil-works/pi-ai/dist/api/lazy.js +1 -1
  406. package/dist/node_modules/@earendil-works/pi-ai/dist/api/llama-cpp-classify.js +5 -5
  407. package/dist/node_modules/@earendil-works/pi-ai/dist/api/mistral-conversations.js +2 -2
  408. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.js +6 -6
  409. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js +5 -5
  410. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js +10 -5
  411. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js +3 -2
  412. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openrouter-images.js +1 -1
  413. package/dist/node_modules/@earendil-works/pi-ai/dist/api/pi-messages.js +4 -4
  414. package/dist/node_modules/@earendil-works/pi-ai/dist/api/simple-options.js +1 -1
  415. package/dist/node_modules/@earendil-works/pi-ai/dist/api/system-one-shared.js +1 -1
  416. package/dist/node_modules/@earendil-works/pi-ai/dist/api/typesafe-system-one.js +1 -1
  417. package/dist/node_modules/@earendil-works/pi-ai/dist/auth/oauth/oauth-page.js +74 -0
  418. package/dist/node_modules/@earendil-works/pi-ai/dist/cli.js +0 -0
  419. package/dist/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js +1 -0
  420. package/dist/node_modules/@earendil-works/pi-ai/dist/images-models.js +1 -0
  421. package/dist/node_modules/@earendil-works/pi-ai/dist/index.d.ts +2 -0
  422. package/dist/node_modules/@earendil-works/pi-ai/dist/index.js +1 -1
  423. package/dist/node_modules/@earendil-works/pi-ai/dist/models.d.ts +4 -0
  424. package/dist/node_modules/@earendil-works/pi-ai/dist/models.js +1 -1
  425. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/azure-openai-responses.js +1 -0
  426. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/azure-openai-responses.models.js +1 -0
  427. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/compat-schema.d.ts +180 -0
  428. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/compat-schema.js +1 -1
  429. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  430. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
  431. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
  432. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/huggingface.json +1 -1
  433. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/minimax-cn.json +1 -1
  434. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/minimax.json +1 -1
  435. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/mistral.json +1 -1
  436. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/nvidia.json +1 -1
  437. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openai-codex.json +1 -1
  438. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
  439. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  440. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  441. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/typesafe.json +1 -1
  442. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  443. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/model-schema.js +1 -1
  444. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/openrouter-images.js +1 -0
  445. package/dist/node_modules/@earendil-works/pi-ai/dist/telemetry.d.ts +286 -0
  446. package/dist/node_modules/@earendil-works/pi-ai/dist/telemetry.js +1 -0
  447. package/dist/node_modules/@earendil-works/pi-ai/dist/types.d.ts +20 -4
  448. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/assistant-message-frame.js +1 -0
  449. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/deferred-tools.js +1 -0
  450. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/event-stream.d.ts +4 -0
  451. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/event-stream.js +1 -1
  452. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/identity.d.ts +27 -0
  453. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/identity.js +1 -0
  454. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js +1 -1
  455. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/provider-retry.js +1 -1
  456. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/retry.js +1 -1
  457. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/transcript.d.ts +3 -2
  458. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/transcript.js +2 -2
  459. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/version.d.ts +1 -0
  460. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/version.js +1 -0
  461. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
  462. package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
  463. package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
  464. package/dist/node_modules/@earendil-works/pi-mcp/CHANGELOG.md +2 -0
  465. package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
  466. package/dist/node_modules/@earendil-works/pi-telemetry/README.md +167 -21
  467. package/dist/node_modules/@earendil-works/pi-telemetry/dist/index.d.ts +77 -2
  468. package/dist/node_modules/@earendil-works/pi-telemetry/dist/index.js +1 -1
  469. package/dist/node_modules/@earendil-works/pi-telemetry/dist/memory.d.ts +35 -2
  470. package/dist/node_modules/@earendil-works/pi-telemetry/dist/memory.js +1 -1
  471. package/dist/node_modules/@earendil-works/pi-telemetry/dist/metrics.d.ts +70 -0
  472. package/dist/node_modules/@earendil-works/pi-telemetry/dist/metrics.js +1 -0
  473. package/dist/node_modules/@earendil-works/pi-telemetry/dist/noop.d.ts +5 -2
  474. package/dist/node_modules/@earendil-works/pi-telemetry/dist/noop.js +1 -1
  475. package/dist/node_modules/@earendil-works/pi-telemetry/dist/render.js +2 -0
  476. package/dist/node_modules/@earendil-works/pi-telemetry/dist/testing/conformance.js +1 -1
  477. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +6 -1
  478. package/dist/node_modules/@earendil-works/pi-tui/dist/autocomplete.js +2 -2
  479. package/dist/node_modules/@earendil-works/pi-tui/dist/components/markdown.js +8 -7
  480. package/dist/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.d.ts +3 -0
  481. package/dist/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.js +1 -1
  482. package/dist/node_modules/@earendil-works/pi-tui/dist/terminal-image.js +1 -1
  483. package/dist/node_modules/@earendil-works/pi-tui/dist/terminal.d.ts +3 -0
  484. package/dist/node_modules/@earendil-works/pi-tui/dist/terminal.js +1 -1
  485. package/dist/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.d.ts +2 -0
  486. package/dist/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.js +4 -4
  487. package/dist/node_modules/@earendil-works/pi-tui/dist/tui.d.ts +3 -0
  488. package/dist/node_modules/@earendil-works/pi-tui/dist/tui.js +2 -2
  489. package/dist/node_modules/@earendil-works/pi-tui/package.json +3 -2
  490. package/dist/package-manager-cli.js +9 -9
  491. package/dist/sdk/office.d.ts +1 -1
  492. package/dist/sdk/office.js +1 -1
  493. package/dist/sdk/router.d.ts +4 -4
  494. package/dist/sdk/router.js +1 -1
  495. package/dist/server/create-harness.js +1 -0
  496. package/dist/utils/clipboard-command.js +1 -1
  497. package/dist/utils/clipboard-native.js +1 -0
  498. package/dist/utils/pi-user-agent.js +1 -1
  499. package/dist/utils/shell.js +2 -2
  500. package/dist/utils/tools-manager.js +1 -1
  501. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  502. package/examples/extensions/gondolin/package-lock.json +2 -2
  503. package/examples/extensions/gondolin/package.json +1 -1
  504. package/examples/extensions/sandbox/package-lock.json +2 -2
  505. package/examples/extensions/sandbox/package.json +1 -1
  506. package/examples/extensions/with-deps/package-lock.json +2 -2
  507. package/examples/extensions/with-deps/package.json +1 -1
  508. package/npm-shrinkwrap.json +15 -2
  509. package/package.json +6 -2
  510. package/dist/node_modules/@dalcode/dal-guard/src/review.js +0 -3
  511. package/dist/node_modules/@dalcode/dal-office/src/scenes.js +0 -1
  512. package/dist/node_modules/@dalcode/dal-plugins/src/rank.js +0 -4
  513. package/dist/node_modules/@dalcode/dal-router/src/assist.js +0 -4
  514. package/dist/node_modules/@dalcode/dal-router/src/compact-defer.js +0 -3
  515. package/dist/node_modules/@dalcode/dal-router/src/jev.d.ts +0 -52
  516. package/dist/node_modules/@dalcode/dal-router/src/jev.js +0 -5
  517. package/dist/node_modules/@dalcode/dal-router/src/router.d.ts +0 -32
  518. package/dist/node_modules/@dalcode/dal-router/src/router.js +0 -1
  519. package/dist/node_modules/@dalcode/dal-router/src/services.js +0 -1
  520. package/dist/node_modules/@dalcode/dal-subagent/src/role-pick.js +0 -2
@@ -1 +1 @@
1
- var M=Object.defineProperty;var a=(e,s)=>M(e,"name",{value:s,configurable:!0});import{lstatSync as O,statSync as P,unlinkSync as T}from"node:fs";import{createRequire as U}from"node:module";import{dirname as p}from"node:path";const m=U(import.meta.url)("shell-quote"),$={"--new-session":0,"--die-with-parent":0,"--unshare-net":0,"--unshare-pid":0,"--dev":1,"--proc":1,"--tmpfs":1,"--bind":2,"--ro-bind":2,"--setenv":2},w={"--bind":"rw","--ro-bind":"ro","--tmpfs":"rw","--dev":"rw","--proc":"rw"};function b(e){try{return P(e).isDirectory()?"dir":"file"}catch{return"missing"}}a(b,"pathKind");const A=a((e,s)=>e.startsWith(s==="/"?"/":`${s}/`),"within");function B(e,s=b){if(e[0]!=="bwrap")return;const c=[];let n=1;for(;n<e.length&&e[n]!=="--";){const t=e[n],r=$[t];if(r===void 0||n+r>=e.length)return;c.push({name:t,values:e.slice(n+1,n+1+r)}),n+=1+r}if(e[n]!=="--")return;const o=e.slice(n),i=a(t=>t.name==="--ro-bind"&&t.values[0]==="/dev/null","isPlaceholder"),y=c.filter(t=>w[t.name]&&!i(t)),x=a(t=>{let r;for(const f of y){const u=f.values[f.values.length-1];if(!A(t,u)&&t!==u)continue;const v=r?.values[r.values.length-1];(v===void 0||u.length>=v.length)&&(r=f)}return r},"decidingMount"),d=[],h=new Set,g=new Set;for(const t of c){if(!i(t)){d.push(t);continue}let r=t.values[1];for(let u=p(r);u!==p(u);u=p(u))s(u)==="file"&&(r=u);const f=x(p(r));f?.name==="--ro-bind"&&s(f.values[1])==="dir"||g.has(r)||(g.add(r),s(r)==="missing"&&h.add(r),d.push({name:t.name,values:["/dev/null",r]}))}const S=["bwrap",...d.flatMap(t=>[t.name,...t.values]),...o],q=d.filter(t=>w[t.name]).map(t=>t.values[t.values.length-1]);return{args:S,placeholders:[...h],targets:[...new Set(q)]}}a(B,"planBwrapArgs");function j(e,s=b){if(!e.startsWith("bwrap "))return;let c;try{c=m.parse(e,i=>`$${i}`)}catch{return}const n=c.map(i=>typeof i=="object"&&i!==null&&i.op==="glob"?i.pattern:i);if(!n.every(i=>typeof i=="string")||m.quote(n)!==e)return;const o=B(n,s);if(o)return{...o,command:m.quote(o.args)}}a(j,"planBwrapCommand");const l=new Map;function z(e){for(const s of e.targets)l.set(s,(l.get(s)??0)+1)}a(z,"acquirePlan");function C(e,s){for(const n of e.targets){const o=(l.get(n)??1)-1;o>0?l.set(n,o):l.delete(n)}const c=[];for(const n of e.placeholders)if(!l.has(n))try{const o=O(n);if(!o.isFile()||o.size!==0||(o.mode&146)!==0||process.getuid&&o.uid!==process.getuid()||o.mtimeMs<s-2e3)continue;T(n),c.push(n)}catch{}return c}a(C,"releasePlan");function D(e){return l.get(e)??0}a(D,"mountUsersOf");export{z as acquirePlan,D as mountUsersOf,b as pathKind,B as planBwrapArgs,j as planBwrapCommand,C as releasePlan};
1
+ var M=Object.defineProperty;var a=(e,s)=>M(e,"name",{value:s,configurable:!0});import{lstatSync as O,statSync as P,unlinkSync as T}from"node:fs";import{createRequire as U}from"node:module";import{dirname as p}from"node:path";const m=U(import.meta.url)("shell-quote"),$={"--new-session":0,"--die-with-parent":0,"--unshare-net":0,"--unshare-pid":0,"--dev":1,"--proc":1,"--tmpfs":1,"--bind":2,"--ro-bind":2,"--setenv":2},w={"--bind":"rw","--ro-bind":"ro","--tmpfs":"rw","--dev":"rw","--proc":"rw"};function b(e){try{return P(e).isDirectory()?"dir":"file"}catch{return"missing"}}a(b,"pathKind");const A=a((e,s)=>e.startsWith(s==="/"?"/":`${s}/`),"within");function B(e,s=b){if(e[0]!=="bwrap")return;const c=[];let n=1;for(;n<e.length&&e[n]!=="--";){const t=e[n],r=$[t];if(r===void 0||n+r>=e.length)return;c.push({name:t,values:e.slice(n+1,n+1+r)}),n+=1+r}if(e[n]!=="--")return;const o=e.slice(n),i=a(t=>t.name==="--ro-bind"&&t.values[0]==="/dev/null","isPlaceholder"),y=c.filter(t=>w[t.name]&&!i(t)),x=a(t=>{let r;for(const f of y){const u=f.values[f.values.length-1];if(!A(t,u)&&t!==u)continue;const v=r?.values[r.values.length-1];(v===void 0||u.length>=v.length)&&(r=f)}return r},"decidingMount"),d=[],h=new Set,g=new Set;for(const t of c){if(!i(t)){d.push(t);continue}let r=t.values[1];for(let u=p(r);u!==p(u);u=p(u))s(u)==="file"&&(r=u);const f=s(r)==="missing"?x(p(r)):void 0;f?.name==="--ro-bind"&&s(f.values[1])==="dir"||g.has(r)||(g.add(r),s(r)==="missing"&&h.add(r),d.push({name:t.name,values:["/dev/null",r]}))}const S=["bwrap",...d.flatMap(t=>[t.name,...t.values]),...o],q=d.filter(t=>w[t.name]).map(t=>t.values[t.values.length-1]);return{args:S,placeholders:[...h],targets:[...new Set(q)]}}a(B,"planBwrapArgs");function j(e,s=b){if(!e.startsWith("bwrap "))return;let c;try{c=m.parse(e,i=>`$${i}`)}catch{return}const n=c.map(i=>typeof i=="object"&&i!==null&&i.op==="glob"?i.pattern:i);if(!n.every(i=>typeof i=="string")||m.quote(n)!==e)return;const o=B(n,s);if(o)return{...o,command:m.quote(o.args)}}a(j,"planBwrapCommand");const l=new Map;function z(e){for(const s of e.targets)l.set(s,(l.get(s)??0)+1)}a(z,"acquirePlan");function C(e,s){for(const n of e.targets){const o=(l.get(n)??1)-1;o>0?l.set(n,o):l.delete(n)}const c=[];for(const n of e.placeholders)if(!l.has(n))try{const o=O(n);if(!o.isFile()||o.size!==0||(o.mode&146)!==0||process.getuid&&o.uid!==process.getuid()||o.mtimeMs<s-2e3)continue;T(n),c.push(n)}catch{}return c}a(C,"releasePlan");function D(e){return l.get(e)??0}a(D,"mountUsersOf");export{z as acquirePlan,D as mountUsersOf,b as pathKind,B as planBwrapArgs,j as planBwrapCommand,C as releasePlan};
@@ -1,6 +1,6 @@
1
1
  export { detectSandboxAvailability, type SandboxAvailability, setSandboxAvailabilityForTesting, } from "./availability.ts";
2
2
  export { collectBlockedAccesses, describeDenialForModel, parseOutput, parseViolationLine, type SandboxBlockedAccess, type SandboxDenial, } from "./denial.ts";
3
3
  export { detectNetworkCommand, FAIL_FAST_NETWORK_ENV, type NetworkCommand, networkDomainsFor, PACKAGE_MANAGERS, type PackageEcosystem, type PackageManager, packageCacheDirs, } from "./package-managers.ts";
4
- export { domainMatches, filesystemRules, isAlwaysBlockedHost, isSandboxLevel, PROTECTED_HOME_READS, PROTECTED_HOME_WRITES, PROTECTED_WRITE_NAMES, type ResolvedSandboxPolicy, readSandboxEnvironment, resolveSandboxPolicy, SANDBOX_ENV, SANDBOX_LEVELS, type SandboxLevel, type SandboxOverride, type SandboxSettings, type SandboxSettingsSources, sandboxEnvironmentValue, stricterLevel, } from "./policy.ts";
4
+ export { domainMatches, filesystemRules, isAlwaysBlockedHost, isSandboxLevel, PROTECTED_HOME_READS, PROTECTED_HOME_WRITES, PROTECTED_WRITE_NAMES, type ResolvedSandboxPolicy, readSandboxEnvironment, resolveSandboxPolicy, SANDBOX_ENV, SANDBOX_LEVELS, type SandboxLevel, type SandboxOverride, type SandboxSettings, type SandboxSettingsSources, sandboxEnvironmentValue, stricterLevel, systemTempDirs, } from "./policy.ts";
5
5
  export { decideNetworkRequest, type NetworkGrant, registerNetworkGrant, resetSandboxRuntime } from "./runtime.ts";
6
6
  export { getProcessShellSandbox, type PlannedNetworkEscalation, type PreparedCommand, registerSandboxEscalationHandler, type SandboxEscalationDecision, type SandboxEscalationHandler, type SandboxEscalationInput, type SandboxEscalationRequest, type SandboxEvent, type SandboxOptions, type SandboxRunDetails, type SandboxStatus, ShellSandbox, type ShellSandboxOptions, setProcessShellSandbox, } from "./shell-sandbox.ts";
@@ -1 +1 @@
1
- import{detectSandboxAvailability as r,setSandboxAvailabilityForTesting as t}from"./availability.js";import{collectBlockedAccesses as s,describeDenialForModel as n,parseOutput as i,parseViolationLine as l}from"./denial.js";import{detectNetworkCommand as E,FAIL_FAST_NETWORK_ENV as S,networkDomainsFor as c,PACKAGE_MANAGERS as x,packageCacheDirs as b}from"./package-managers.js";import{domainMatches as A,filesystemRules as _,isAlwaysBlockedHost as R,isSandboxLevel as T,PROTECTED_HOME_READS as p,PROTECTED_HOME_WRITES as N,PROTECTED_WRITE_NAMES as D,readSandboxEnvironment as O,resolveSandboxPolicy as f,SANDBOX_ENV as k,SANDBOX_LEVELS as v,sandboxEnvironmentValue as P,stricterLevel as u}from"./policy.js";import{decideNetworkRequest as L,registerNetworkGrant as M,resetSandboxRuntime as g}from"./runtime.js";import{getProcessShellSandbox as w,registerSandboxEscalationHandler as y,ShellSandbox as F,setProcessShellSandbox as V}from"./shell-sandbox.js";export{S as FAIL_FAST_NETWORK_ENV,x as PACKAGE_MANAGERS,p as PROTECTED_HOME_READS,N as PROTECTED_HOME_WRITES,D as PROTECTED_WRITE_NAMES,k as SANDBOX_ENV,v as SANDBOX_LEVELS,F as ShellSandbox,s as collectBlockedAccesses,L as decideNetworkRequest,n as describeDenialForModel,E as detectNetworkCommand,r as detectSandboxAvailability,A as domainMatches,_ as filesystemRules,w as getProcessShellSandbox,R as isAlwaysBlockedHost,T as isSandboxLevel,c as networkDomainsFor,b as packageCacheDirs,i as parseOutput,l as parseViolationLine,O as readSandboxEnvironment,M as registerNetworkGrant,y as registerSandboxEscalationHandler,g as resetSandboxRuntime,f as resolveSandboxPolicy,P as sandboxEnvironmentValue,V as setProcessShellSandbox,t as setSandboxAvailabilityForTesting,u as stricterLevel};
1
+ import{detectSandboxAvailability as r,setSandboxAvailabilityForTesting as t}from"./availability.js";import{collectBlockedAccesses as a,describeDenialForModel as n,parseOutput as i,parseViolationLine as l}from"./denial.js";import{detectNetworkCommand as E,FAIL_FAST_NETWORK_ENV as S,networkDomainsFor as c,PACKAGE_MANAGERS as x,packageCacheDirs as m}from"./package-managers.js";import{domainMatches as A,filesystemRules as T,isAlwaysBlockedHost as _,isSandboxLevel as p,PROTECTED_HOME_READS as R,PROTECTED_HOME_WRITES as D,PROTECTED_WRITE_NAMES as N,readSandboxEnvironment as O,resolveSandboxPolicy as f,SANDBOX_ENV as k,SANDBOX_LEVELS as v,sandboxEnvironmentValue as P,stricterLevel as u,systemTempDirs as y}from"./policy.js";import{decideNetworkRequest as L,registerNetworkGrant as M,resetSandboxRuntime as g}from"./runtime.js";import{getProcessShellSandbox as w,registerSandboxEscalationHandler as F,ShellSandbox as V,setProcessShellSandbox as B}from"./shell-sandbox.js";export{S as FAIL_FAST_NETWORK_ENV,x as PACKAGE_MANAGERS,R as PROTECTED_HOME_READS,D as PROTECTED_HOME_WRITES,N as PROTECTED_WRITE_NAMES,k as SANDBOX_ENV,v as SANDBOX_LEVELS,V as ShellSandbox,a as collectBlockedAccesses,L as decideNetworkRequest,n as describeDenialForModel,E as detectNetworkCommand,r as detectSandboxAvailability,A as domainMatches,T as filesystemRules,w as getProcessShellSandbox,_ as isAlwaysBlockedHost,p as isSandboxLevel,c as networkDomainsFor,m as packageCacheDirs,i as parseOutput,l as parseViolationLine,O as readSandboxEnvironment,M as registerNetworkGrant,F as registerSandboxEscalationHandler,g as resetSandboxRuntime,f as resolveSandboxPolicy,P as sandboxEnvironmentValue,B as setProcessShellSandbox,t as setSandboxAvailabilityForTesting,u as stricterLevel,y as systemTempDirs};
@@ -3,6 +3,7 @@ export declare const SANDBOX_LEVELS: readonly SandboxLevel[];
3
3
  export interface SandboxSettings {
4
4
  level?: SandboxLevel;
5
5
  network?: {
6
+ access?: "open" | "allowlist";
6
7
  allowedDomains?: string[];
7
8
  deniedDomains?: string[];
8
9
  allowLocalBinding?: boolean;
@@ -26,6 +27,7 @@ export interface ResolvedSandboxPolicy {
26
27
  level: SandboxLevel;
27
28
  levelSource: "override" | "environment" | "settings" | "project" | "default";
28
29
  network: {
30
+ open: boolean;
29
31
  allowedDomains: string[];
30
32
  deniedDomains: string[];
31
33
  allowLocalBinding: boolean;
@@ -51,6 +53,8 @@ export declare function resolveSandboxPolicy(options: {
51
53
  export declare const PROTECTED_WRITE_NAMES: readonly string[];
52
54
  export declare const PROTECTED_HOME_WRITES: readonly string[];
53
55
  export declare const PROTECTED_HOME_READS: readonly string[];
56
+ export declare const HOME_CACHE_DIRS: readonly string[];
57
+ export declare function systemTempDirs(): string[];
54
58
  export declare function expandPath(path: string, cwd: string): string;
55
59
  export interface CommandFilesystemRules {
56
60
  allowWrite: string[];
@@ -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 _,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
+ var T=Object.defineProperty;var i=(e,t)=>T(e,"name",{value:t,configurable:!0});import{existsSync as A,readdirSync as k,realpathSync as C}from"node:fs";import{homedir as g,tmpdir as O}from"node:os";import{isAbsolute as E,join as c,relative as N,resolve as P,sep as I}from"node:path";import{packageCacheDirs as j}from"./package-managers.js";const H=["read-only","workspace-write","off"],v="DAL_SANDBOX",x={off:0,"workspace-write":1,"read-only":2};function y(e){return typeof e=="string"&&H.includes(e)}i(y,"isSandboxLevel");function B(e,t){return x[t]>x[e]?t:e}i(B,"stricterLevel");function f(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}i(f,"strings");function u(e){return[...new Set(e)]}i(u,"unique");const M=process.env[v];function z(e={[v]:M}){const t=e[v];if(t)try{const r=JSON.parse(t);return y(r.level)?{level:r.level,allowedDomains:f(r.allowedDomains)}:void 0}catch{return}}i(z,"readSandboxEnvironment");function re(e){return JSON.stringify({level:e.level,allowedDomains:e.network.allowedDomains})}i(re,"sandboxEnvironmentValue");function ne(e){const t=e.settings?.global??{},r=e.settings?.project??{},o=z(e.env),a=e.override??{};let s,l;a.level?(s=a.level,l="override"):o?.level?(s=o.level,l="environment"):y(t.level)?(s=t.level,l="settings"):(s=e.defaultLevel,l="default"),!a.level&&y(r.level)&&B(s,r.level)!==s&&(s=r.level,l="project");const w=s==="workspace-write"&&t.network?.access!=="allowlist"&&r.network?.access!=="allowlist";return{level:s,levelSource:l,network:{open:w,allowedDomains:u([...f(t.network?.allowedDomains),...f(o?.allowedDomains),...f(a.allowedDomains)]),deniedDomains:u([...f(t.network?.deniedDomains),...f(r.network?.deniedDomains)]),allowLocalBinding:t.network?.allowLocalBinding===!0},filesystem:{allowWrite:f(t.filesystem?.allowWrite),denyRead:u([...f(t.filesystem?.denyRead),...f(r.filesystem?.denyRead)]),denyWrite:u([...f(t.filesystem?.denyWrite),...f(r.filesystem?.denyWrite)]),allowRead:f(t.filesystem?.allowRead)}}}i(ne,"resolveSandboxPolicy");const F=[".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","Library/Keychains","Library/Application Support/Google/Chrome","Library/Application Support/Firefox","Library/Safari",".mozilla",".config/google-chrome",".config/chromium",".dal/agent/auth.json",".dal/agent/factory.json",".dal/agent/web.json"],J=[".cache","Library/Caches","go/pkg",".gradle/caches",".m2/repository"];function K(){const e=[O(),"/tmp","/var/tmp"];return process.platform==="darwin"&&e.push("/private/tmp","/private/var/tmp"),u([...e,...e.map(h)])}i(K,"systemTempDirs");function p(e,t){return e==="~"?g():e.startsWith("~/")?c(g(),e.slice(2)):E(e)?e:P(t,e)}i(p,"expandPath");function h(e){try{return C(e)}catch{return e}}i(h,"realpathOrSelf");function W(e,t){const r=N(t,e);return r===""||r!==".."&&!r.startsWith(`..${I}`)&&!E(r)}i(W,"isWithin");function oe(e,t,r={}){const o=g(),a=e.level==="workspace-write"?u([t,h(t),...e.filesystem.allowWrite.map(n=>p(n,t))]):[],s=e.level==="workspace-write"?r.gitDirs??[]:[],l=(r.extraWrite??[]).map(n=>p(n,t)),w=r.scratchDir?[r.scratchDir,h(r.scratchDir)]:[],R=e.level==="workspace-write"?[...r.packageCaches??j(),...J.map(n=>c(o,n)),...K()]:[],b=u([...a,...s,...l,...w,...R]),d=[];if(e.level==="read-only"){const n=u([t,h(t)]);l.some(D=>n.some(S=>W(D,S)||W(S,D)))||d.push(...n)}for(const n of[...a,...l]){for(const m of F)d.push(c(n,m));d.push(c(n,".env.*"));for(const m of Q(n))d.push(c(n,m))}for(const n of s)d.push(c(n,"hooks"),c(n,"config"));if(e.level==="workspace-write")for(const n of a)for(const m of G(n))d.push(c(m,".git","config"),c(m,".git","hooks"));for(const n of V)d.push(c(o,n));d.push(...e.filesystem.denyWrite.map(n=>p(n,t)));const L=new Set(e.filesystem.allowRead.map(n=>p(n,t))),_=[...X.map(n=>c(o,n)).filter(n=>!L.has(n)),...e.filesystem.denyRead.map(n=>p(n,t))];return{allowWrite:b,denyWrite:u(d),denyRead:u(_)}}i(oe,"filesystemRules");const $=3,q=new Set(["node_modules",".git","dist","build","target",".venv","venv"]);function G(e){const t=[],r=i((o,a)=>{let s;try{s=k(o,{withFileTypes:!0})}catch{return}for(const l of s)if(l.isDirectory()){if(l.name===".git"){t.push(o);continue}a<$&&!q.has(l.name)&&r(c(o,l.name),a+1)}},"walk");return r(e,0),t}i(G,"nestedRepositories");function Q(e){if(!A(e))return[];try{return k(e).filter(t=>t.startsWith(".env."))}catch{return[]}}i(Q,"listEnvFiles");function se(e,t){const r=e.toLowerCase(),o=t.toLowerCase();return o.startsWith("*.")?r.endsWith(o.slice(1)):r===o}i(se,"domainMatches");function ie(e){const t=e.toLowerCase().replace(/^\[|\]$/g,"");if(t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="0.0.0.0")return!0;if(t.startsWith("fe80:")||t.startsWith("fc")||t.startsWith("fd"))return t.includes(":");const r=t.split(".").map(s=>Number(s));if(r.length!==4||r.some(s=>!Number.isInteger(s)||s<0||s>255))return!1;const[o,a]=r;return o===127||o===10||o===172&&a>=16&&a<=31||o===192&&a===168||o===169&&a===254}i(ie,"isAlwaysBlockedHost");export{J as HOME_CACHE_DIRS,X as PROTECTED_HOME_READS,V as PROTECTED_HOME_WRITES,F as PROTECTED_WRITE_NAMES,v as SANDBOX_ENV,H as SANDBOX_LEVELS,se as domainMatches,p as expandPath,oe as filesystemRules,ie as isAlwaysBlockedHost,y as isSandboxLevel,z as readSandboxEnvironment,ne as resolveSandboxPolicy,re as sandboxEnvironmentValue,B as stricterLevel,K as systemTempDirs};
@@ -15,6 +15,8 @@ export interface WrapRequest {
15
15
  denyWrite: string[];
16
16
  denyRead: string[];
17
17
  allowLocalBinding: boolean;
18
+ openNetwork?: boolean;
19
+ allowGitConfig?: boolean;
18
20
  allowUnixSockets?: string[];
19
21
  ripgrep?: string;
20
22
  }
@@ -1 +1 @@
1
- var M=Object.defineProperty;var t=(e,r)=>M(e,"name",{value:r,configurable:!0});import{acquirePlan as W,planBwrapCommand as F,releasePlan as L}from"./bwrap-placeholders.js";import{domainMatches as R,isAlwaysBlockedHost as N}from"./policy.js";const b="dal-sandbox.invalid",u=new Set;let l,c,x,w=Promise.resolve(),y=0;async function A(){return l??=import("@anthropic-ai/sandbox-runtime").then(e=>e.SandboxManager),l}t(A,"loadManager");function D(e){return{network:{allowedDomains:[b],deniedDomains:[],allowLocalBinding:e.allowLocalBinding,...e.allowUnixSockets?.length?{allowUnixSockets:e.allowUnixSockets}:{}},filesystem:{denyRead:[],allowWrite:[],denyWrite:[]},...e.ripgrep?{ripgrep:{command:e.ripgrep}}:{}}}t(D,"baseConfig");function B(e){return u.add(e),()=>{u.delete(e)}}t(B,"registerNetworkGrant");function k(e,r){let i=!1;if(!N(e))for(const a of u)a.deniedDomains.some(n=>R(e,n))||a.allowedDomains.some(n=>R(e,n))&&(i=!0);if(!i)for(const a of u)a.refusals.some(n=>n.host===e&&n.port===r)||a.refusals.push({host:e,...r!==void 0?{port:r}:{}});return i}t(k,"decideNetworkRequest");function T(){const e=process._getActiveHandles;return new Set(typeof e=="function"?e.call(process):[])}t(T,"activeHandles");async function H(e,r){c||(x??=(async()=>{const i={SIGINT:new Set(process.listeners("SIGINT")),SIGTERM:new Set(process.listeners("SIGTERM"))},a=T();try{await e.initialize(D(r),async({host:n,port:s})=>k(n,s),!1),c={ready:!0}}catch(n){c={ready:!1,error:n instanceof Error?n.message:String(n)}}finally{for(const n of["SIGINT","SIGTERM"])for(const s of process.listeners(n))i[n].has(s)||process.removeListener(n,s);for(const n of T())!a.has(n)&&typeof n.unref=="function"&&n.unref()}})(),await x)}t(H,"ensureProxy");function X(){return c&&!c.ready?c.error:o&&"error"in o?o.error:void 0}t(X,"proxyUnavailableReason");let o,g,G;function Y(e){G=e?async()=>{const r=await e();return"error"in r?r:{port:r.port,server:{close:t(()=>{},"close")}}}:void 0,o=void 0,g=void 0}t(Y,"setFilteringProxyStarterForTesting");async function U(){try{const{createHttpProxyServer:e}=await import("@anthropic-ai/sandbox-runtime/dist/sandbox/http-proxy.js"),r=e({filter:t((a,n)=>k(n,a),"filter")}),i=await new Promise((a,n)=>{r.once("error",n),r.listen(0,"127.0.0.1",()=>{const s=r.address();a(typeof s=="object"&&s?s.port:0)})});return r.unref(),{port:i,server:r}}catch(e){return{error:e instanceof Error?e.message:String(e)}}}t(U,"startFilteringProxy");async function J(){return o?"error"in o?o:{port:o.port}:(g??=(G??U)(),o=await g,"error"in o?o:{port:o.port})}t(J,"ensureFilteringProxy");function K(){y++}t(K,"acquireSandboxRuntime");async function Q(){y=Math.max(0,y-1),y===0&&await O()}t(Q,"releaseSandboxRuntime");async function Z(e,r){const i=await A(),a=r.allowedDomains.length>0;a&&await H(i,e);const n=t(async()=>{const f={denyRead:e.denyRead,allowWrite:e.allowWrite,denyWrite:e.denyWrite};i.updateConfig({...D(e),filesystem:f});const h=a&&c?.ready===!0,E=Date.now(),v=await i.wrapWithSandbox(e.command,e.shell,{network:{allowedDomains:h?[b]:[],deniedDomains:[]},filesystem:f}),m=process.platform==="linux"?F(v):void 0;return m&&W(m),{wrapped:m?.command??v,proxied:h,plan:m,wrappedAt:E}},"run"),s=w.then(n,n);w=s.catch(()=>{});const{wrapped:p,proxied:d,plan:S,wrappedAt:I}=await s,C=B(r);let P=!1;return{command:p,proxied:d,release:t(()=>{if(P||(P=!0,C(),!S))return;const f=t(()=>{L(S,I)},"cleanup");w=w.then(f,f)},"release")}}t(Z,"wrapCommand");async function $(e,r,i){if(!l)return[];const n=(await l).getSandboxViolationStore();if(n.getTotalCount()===0)return[];const s=Date.now()+i;for(;;){const p=n.getViolationsForCommand(e).filter(d=>d.timestamp.getTime()>=r-1e3);if(p.length>0||Date.now()>=s)return p;await new Promise(d=>setTimeout(d,50))}}t($,"violationsForCommand");async function O(){u.clear(),o&&"server"in o&&o.server.close(),o=void 0,g=void 0;const e=c!==void 0;if(c=void 0,x=void 0,!e||!l)return;await(await l).reset()}t(O,"resetSandboxRuntime");export{K as acquireSandboxRuntime,k as decideNetworkRequest,J as ensureFilteringProxy,X as proxyUnavailableReason,B as registerNetworkGrant,Q as releaseSandboxRuntime,O as resetSandboxRuntime,Y as setFilteringProxyStarterForTesting,$ as violationsForCommand,Z as wrapCommand};
1
+ var W=Object.defineProperty;var t=(e,r)=>W(e,"name",{value:r,configurable:!0});import{acquirePlan as E,planBwrapCommand as L,releasePlan as M}from"./bwrap-placeholders.js";import{domainMatches as R,isAlwaysBlockedHost as A}from"./policy.js";const v="dal-sandbox.invalid",p=new Set;let d,l,x,m=Promise.resolve(),g=0;async function B(){return d??=import("@anthropic-ai/sandbox-runtime").then(e=>e.SandboxManager),d}t(B,"loadManager");function D(e){return e.openNetwork?{network:{deniedDomains:[],allowLocalBinding:!0,allowAllUnixSockets:!0},filesystem:{denyRead:[],allowWrite:[],denyWrite:[]},...e.ripgrep?{ripgrep:{command:e.ripgrep}}:{}}:{network:{allowedDomains:[v],deniedDomains:[],allowLocalBinding:e.allowLocalBinding,...e.allowUnixSockets?.length?{allowUnixSockets:e.allowUnixSockets}:{}},filesystem:{denyRead:[],allowWrite:[],denyWrite:[]},...e.ripgrep?{ripgrep:{command:e.ripgrep}}:{}}}t(D,"baseConfig");function F(e){return p.add(e),()=>{p.delete(e)}}t(F,"registerNetworkGrant");function b(e,r){let i=!1;if(!A(e))for(const a of p)a.deniedDomains.some(n=>R(e,n))||a.allowedDomains.some(n=>R(e,n))&&(i=!0);if(!i)for(const a of p)a.refusals.some(n=>n.host===e&&n.port===r)||a.refusals.push({host:e,...r!==void 0?{port:r}:{}});return i}t(b,"decideNetworkRequest");function G(){const e=process._getActiveHandles;return new Set(typeof e=="function"?e.call(process):[])}t(G,"activeHandles");async function H(e,r){l||(x??=(async()=>{const i={SIGINT:new Set(process.listeners("SIGINT")),SIGTERM:new Set(process.listeners("SIGTERM"))},a=G();try{await e.initialize(D(r),async({host:n,port:s})=>b(n,s),!1),l={ready:!0}}catch(n){l={ready:!1,error:n instanceof Error?n.message:String(n)}}finally{for(const n of["SIGINT","SIGTERM"])for(const s of process.listeners(n))i[n].has(s)||process.removeListener(n,s);for(const n of G())!a.has(n)&&typeof n.unref=="function"&&n.unref()}})(),await x)}t(H,"ensureProxy");function X(){return l&&!l.ready?l.error:o&&"error"in o?o.error:void 0}t(X,"proxyUnavailableReason");let o,y,C;function Y(e){C=e?async()=>{const r=await e();return"error"in r?r:{port:r.port,server:{close:t(()=>{},"close")}}}:void 0,o=void 0,y=void 0}t(Y,"setFilteringProxyStarterForTesting");async function U(){try{const{createHttpProxyServer:e}=await import("@anthropic-ai/sandbox-runtime/dist/sandbox/http-proxy.js"),r=e({filter:t((a,n)=>b(n,a),"filter")}),i=await new Promise((a,n)=>{r.once("error",n),r.listen(0,"127.0.0.1",()=>{const s=r.address();a(typeof s=="object"&&s?s.port:0)})});return r.unref(),{port:i,server:r}}catch(e){return{error:e instanceof Error?e.message:String(e)}}}t(U,"startFilteringProxy");async function J(){return o?"error"in o?o:{port:o.port}:(y??=(C??U)(),o=await y,"error"in o?o:{port:o.port})}t(J,"ensureFilteringProxy");function K(){g++}t(K,"acquireSandboxRuntime");async function Q(){g=Math.max(0,g-1),g===0&&await O()}t(Q,"releaseSandboxRuntime");async function Z(e,r){const i=await B(),a=!e.openNetwork&&r.allowedDomains.length>0;a&&await H(i,e);const n=t(async()=>{const c={denyRead:e.denyRead,allowWrite:e.allowWrite,denyWrite:e.denyWrite,...e.allowGitConfig?{allowGitConfig:!0}:{}};i.updateConfig({...D(e),filesystem:c});const h=a&&l?.ready===!0,N=Date.now(),k=await i.wrapWithSandbox(e.command,e.shell,e.openNetwork?{filesystem:c}:{network:{allowedDomains:h?[v]:[],deniedDomains:[]},filesystem:c}),w=process.platform==="linux"?L(k):void 0;return w&&E(w),{wrapped:w?.command??k,proxied:h,plan:w,wrappedAt:N}},"run"),s=m.then(n,n);m=s.catch(()=>{});const{wrapped:u,proxied:f,plan:S,wrappedAt:T}=await s,I=F(r);let P=!1;return{command:u,proxied:f,release:t(()=>{if(P||(P=!0,I(),!S))return;const c=t(()=>{M(S,T)},"cleanup");m=m.then(c,c)},"release")}}t(Z,"wrapCommand");async function $(e,r,i){if(!d)return[];const n=(await d).getSandboxViolationStore();if(n.getTotalCount()===0)return[];const s=Date.now()+i;for(;;){const u=n.getViolationsForCommand(e).filter(f=>f.timestamp.getTime()>=r-1e3);if(u.length>0||Date.now()>=s)return u;await new Promise(f=>setTimeout(f,50))}}t($,"violationsForCommand");async function O(){p.clear(),o&&"server"in o&&o.server.close(),o=void 0,y=void 0;const e=l!==void 0;if(l=void 0,x=void 0,!e||!d)return;await(await d).reset()}t(O,"resetSandboxRuntime");export{K as acquireSandboxRuntime,b as decideNetworkRequest,J as ensureFilteringProxy,X as proxyUnavailableReason,F as registerNetworkGrant,Q as releaseSandboxRuntime,O as resetSandboxRuntime,Y as setFilteringProxyStarterForTesting,$ as violationsForCommand,Z as wrapCommand};
@@ -98,6 +98,7 @@ export interface SandboxRunDetails {
98
98
  export declare function registerSandboxEscalationHandler(handler: SandboxEscalationHandler): () => void;
99
99
  export declare function setProcessShellSandbox(sandbox: ShellSandbox | undefined): void;
100
100
  export declare function getProcessShellSandbox(): ShellSandbox | undefined;
101
+ export declare const MACOS_HEREDOC_TEMP = "/private/tmp/sh-thd-*";
101
102
  export declare class ShellSandbox {
102
103
  readonly policy: ResolvedSandboxPolicy;
103
104
  private readonly onEscalation?;
@@ -115,6 +116,7 @@ export declare class ShellSandbox {
115
116
  get active(): boolean;
116
117
  private availability;
117
118
  status(): SandboxStatus;
119
+ private networkOpen;
118
120
  describeForModel(): string | undefined;
119
121
  unavailableRefusal(): string | undefined;
120
122
  planNetworkEscalation(call: {
@@ -1,7 +1,7 @@
1
- var z=Object.defineProperty;var c=(e,o)=>z(e,"name",{value:o,configurable:!0});import{spawnSync as J}from"node:child_process";import{mkdirSync as Z}from"node:fs";import{isAbsolute as O,relative as q,resolve as oo}from"node:path";import{ToolExecutionError as eo}from"@earendil-works/pi-agent-core";import{fill as v,t as h}from"../../dal/i18n.js";import{createTempDir as no,removeTempPath as ao}from"../../utils/temp-files.js";import{toolDenial as io,withToolDenial as to}from"../tool-denial.js";import{detectSandboxAvailability as so}from"./availability.js";import{collectBlockedAccesses as U}from"./denial.js";import{libreOfficeAccess as ro}from"./libreoffice.js";import{detectNetworkCommand as B,FAIL_FAST_NETWORK_ENV as L,networkDomainsFor as lo,packageCacheDirs as co}from"./package-managers.js";import{domainMatches as M,expandPath as F,filesystemRules as mo}from"./policy.js";import{acquireSandboxRuntime as ho,ensureFilteringProxy as fo,proxyUnavailableReason as K,registerNetworkGrant as po,releaseSandboxRuntime as wo,violationsForCommand as uo,wrapCommand as bo}from"./runtime.js";import{prepareWindowsCommand as vo}from"./windows.js";function E(e,o){return new eo(e,to({sandbox:o},io("sandbox",e)))}c(E,"sandboxRefusal");const N=Symbol.for("dal.sandbox.escalationHandlers"),k=globalThis;k[N]instanceof Set||(k[N]=new Set);const R=k[N];function Lo(e){return R.add(e),()=>{R.delete(e)}}c(Lo,"registerSandboxEscalationHandler");const H=Symbol.for("dal.sandbox.processSandbox");function Mo(e){k[H]=e}c(Mo,"setProcessShellSandbox");function Fo(){return k[H]}c(Fo,"getProcessShellSandbox");const X=new Map;function yo(e){const o=X.get(e);if(o)return o;const n=J("git",["rev-parse","--absolute-git-dir","--git-common-dir"],{cwd:e,encoding:"utf8",timeout:3e3}),r=[];if(n.status===0)for(const s of n.stdout.split(`
2
- `)){const i=s.trim();if(!i)continue;const a=O(i)?i:oo(e,i),t=q(e,a);(t.startsWith("..")||O(t))&&r.push(a)}const l=[...new Set(r)];return X.set(e,l),l}c(yo,"gitDirsOutside");function $(e){return Array.isArray(e)?e.filter(o=>typeof o=="string"&&o.trim().length>0).map(o=>o.trim()):[]}c($,"cleanList");let xo=0;class Ko{static{c(this,"ShellSandbox")}policy;onEscalation;onEvent;availabilityOverride;sessionDomains=new Set;sessionWritable=new Set;holdsRuntime=!1;sharedScratch;ownScratch;constructor(o){this.policy=o.policy,this.onEscalation=o.onEscalation,this.onEvent=o.onEvent,this.availabilityOverride=o.availability,this.sharedScratch=o.scratchDir,this.active&&(ho(),this.holdsRuntime=!0)}scratchDir(){return this.sharedScratch?this.sharedScratch():(this.ownScratch??=Do(),this.ownScratch)}async dispose(){this.ownScratch&&(ao(this.ownScratch),this.ownScratch=void 0),this.holdsRuntime&&(this.holdsRuntime=!1,await wo())}get level(){return this.policy.level}get active(){return this.policy.level!=="off"}availability(){return this.availabilityOverride??so()}status(){const o=this.availability(),n=K();return{level:this.policy.level,levelSource:this.policy.levelSource,enforced:this.active&&o.available,platform:o.platform,...o.mechanism?{mechanism:o.mechanism}:{},...this.active&&!o.available&&o.reason?{unavailableReason:o.reason}:{},...o.isolationTier?{isolationTier:o.isolationTier}:{},...o.limitations?.length?{limitations:[...o.limitations]}:{},network:{allowedDomains:[...this.policy.network.allowedDomains],deniedDomains:[...this.policy.network.deniedDomains],...n?{proxyError:n}:{}},sessionAllowances:{domains:[...this.sessionDomains],writablePaths:[...this.sessionWritable]}}}describeForModel(){if(!this.active)return;const o=this.policy.level==="read-only"?"writes only to $TMPDIR (session scratch)":"writes only to the working directory, $TMPDIR (session scratch) and package caches (agent/editor config, git hooks and .env stay read-only)",n=this.policy.network.allowedDomains,r=(n.length>0?`network off except ${n.join(", ")}`:"network off")+(this.policy.level==="workspace-write"?" (package installs via npm/pnpm/yarn/pip/uv/cargo/go and curl/wget/git clone ask the user for their hosts by themselves: run them plainly, without sandbox_escalation)":"");return`OS sandbox (${this.policy.level}): ${o}; ${r}; ~/.ssh and other credentials unreadable. Use sandbox_escalation only after the result says the sandbox blocked something the task needs.`}unavailableRefusal(){if(!this.active)return;const o=this.availability();if(!o.available)return[`Command refused: the sandbox level is "${this.policy.level}", but ${o.reason??"the OS sandbox is unavailable."}`,"Commands are not run without the sandbox unless the user says so explicitly.",'The user can fix the sandbox, or opt out explicitly with `dal --sandbox off` or "sandbox": { "level": "off" } in ~/.dal/agent/settings.json.','A single command can still run if the user approves it: retry with sandbox_escalation {"mode":"unsandboxed","justification":"..."}.'].join(`
3
- `)}planNetworkEscalation(o){if(this.policy.level!=="workspace-write"||!this.availability().available)return;const n=B(o.command);if(!n)return;const r=[...this.policy.network.allowedDomains,...this.sessionDomains],l=this.policy.network.deniedDomains,s=lo(n,o.cwd).filter(a=>!r.some(t=>M(a,t))&&!l.some(t=>M(a,t)));if(s.length===0)return;const i=n.ecosystems.length>0?"package-install":"download";return{mode:"allow",allow_domains:s,trigger:i,justification:i==="package-install"?h("\u8FD9\u6761\u547D\u4EE4\u8981\u5B89\u88C5\u4F9D\u8D56\uFF0C\u9700\u8981\u4ECE\u8F6F\u4EF6\u6E90\u4E0B\u8F7D\u3002"):h("\u8FD9\u6761\u547D\u4EE4\u8981\u4ECE\u7F51\u4E0A\u4E0B\u8F7D\u6587\u4EF6\u3002")}}async prepare(o){const n=this.policy.level;if(n==="off")return Y(o.command,{level:n,sandboxed:!1});const r=this.unavailableRefusal();if(r&&o.escalation?.mode!=="unsandboxed")throw E(r,{level:n,sandboxed:!1});let l=[],s=[],i;const a=o.escalation||r?void 0:this.planNetworkEscalation(o),t=a?await this.approveEscalation(o,a,a.trigger):void 0;if(a&&t&&t.decidedBy!=="none"){const f={request:t.request,decision:t.decision};if(i=f,!f.decision.approved)throw E(`The user did not allow network access for this command${f.decision.message?` (${f.decision.message})`:""}: it needs ${a.allow_domains.join(", ")}. Do not retry it with sandbox_escalation; continue without it or ask the user.`,{level:n,sandboxed:!1,escalation:f});l=t.allowDomains,s=t.allowWrite}else if(o.escalation){const{decidedBy:f,allowDomains:D,allowWrite:C,...b}=await this.approveEscalation(o,o.escalation);if(i=b,!b.decision.approved)throw E(`Sandbox escalation refused${b.decision.message?`: ${b.decision.message}`:"."} Do not retry the same escalation; continue without it or ask the user.`,{level:n,sandboxed:!1,escalation:i});if(b.request.mode==="unsandboxed")return Y(o.command,{level:n,sandboxed:!1,escalation:i});l=D,s=C}const d=this.availability(),w=o.shellKind??"bash";if(w!=="bash"&&d.mechanism!=="mxc")throw E(`Command refused: ${w} commands cannot run inside the ${d.mechanism??"OS"} sandbox, and the sandbox level is "${n}". Use the bash tool, or the user can opt out with \`dal --sandbox off\`.`,{level:n,sandboxed:!1});const p=this.scratchDir();n==="workspace-write"&&go(B(o.command)?.managers);const u=mo(this.policy,o.cwd,{gitDirs:this.policy.level==="workspace-write"?yo(o.cwd):[],extraWrite:[...this.sessionWritable,...s],scratchDir:p}),m={allowedDomains:[...this.policy.network.allowedDomains,...this.sessionDomains,...l],deniedDomains:this.policy.network.deniedDomains,refusals:[]},S=`${process.pid}-${++xo}`,x=m.allowedDomains.length===0;if(d.mechanism==="mxc"&&d.mxc){const f=x?{...o.env??process.env,...L}:o.env;return this.prepareWindows({...o,...f?{env:f}:{}},{level:n,shellKind:w,scratch:p,rules:u,grant:m,runId:S,escalation:i,availability:d})}const y=ko(p),W=x?Object.entries(L).map(([f,D])=>` ${f}=${D}`).join(""):"",g=ro(p,d.platform),G=g?` UserInstallation="\${UserInstallation:-${g.env.UserInstallation.replace(/[\\"$`]/g,"\\$&")}}"`:"",A=`export DAL_SANDBOX_RUN=${S} TMPDIR=${y} TMP=${y} TEMP=${y}${W}${G}
4
- ${o.command}`,Q=Date.now(),_=await bo({command:A,shell:o.shell,allowWrite:g?[...u.allowWrite,...g.allowWrite]:u.allowWrite,denyWrite:u.denyWrite,denyRead:u.denyRead,allowLocalBinding:o.background===!0||this.policy.network.allowLocalBinding,...g?{allowUnixSockets:g.allowUnixSockets}:{},...d.ripgrep?{ripgrep:d.ripgrep}:{}},m),j={level:n,sandboxed:!0,...i?{escalation:i}:{}};let P=!1;return{command:_.command,sandboxed:!0,details:j,finish:c(async(f,D)=>{if(P)return j.denial;if(P=!0,_.release(),f===0)return;const C=d.platform==="darwin"?await uo(A,Q,400):[],b=U({refusals:m.refusals,violations:C,output:D});if(!b)return;const T=_.proxied?void 0:K(),I={level:n,platform:d.platform,command:o.command,cwd:o.cwd,blocked:b,scratchDir:p,...T&&b.some(V=>V.kind==="network")?{networkProxyError:T}:{}};return j.denial=I,this.onEvent?.({type:"sandbox_denied",toolCallId:o.toolCallId,toolName:o.toolName,denial:I}),I},"finish")}}async prepareWindows(o,n){const{level:r,grant:l,availability:s}=n,i=s.mxc;if(!i)throw new Error("Command refused: the Windows sandbox (mxc) is not loaded.");let a,t;if(l.allowedDomains.length>0){const m=await fo();"port"in m?a=m.port:t=m.error}const d=vo({runtime:i,kind:n.shellKind,shellPath:o.shell,command:o.command,cwd:o.cwd,level:r,rules:n.rules,env:o.env??process.env,scratchDir:n.scratch,runId:n.runId,...a!==void 0?{proxyPort:a}:{},allowLocalNetwork:o.background===!0||this.policy.network.allowLocalBinding}),w=po(l),p={level:r,sandboxed:!0,...n.escalation?{escalation:n.escalation}:{}};let u=!1;return{command:d.command,sandboxed:!0,details:p,finish:c(async(m,S)=>{if(u)return p.denial;if(u=!0,w(),d.cleanup(),m===0)return;const x=U({refusals:l.refusals,violations:[],output:S});if(!x)return;const y={level:r,platform:s.platform,command:o.command,cwd:o.cwd,blocked:x,scratchDir:n.scratch,...t&&x.some(W=>W.kind==="network")?{networkProxyError:t}:{}};return p.denial=y,this.onEvent?.({type:"sandbox_denied",toolCallId:o.toolCallId,toolName:o.toolName,denial:y}),y},"finish")}}uiApprovals=Promise.resolve();queueUiApproval(o){const n=this.uiApprovals.then(o,o);return this.uiApprovals=n.catch(()=>{}),n}async approveEscalation(o,n,r){const l=n.mode==="unsandboxed"?"unsandboxed":"allow",s={toolCallId:o.toolCallId,toolName:o.toolName,command:o.command,cwd:o.cwd,level:this.policy.level,mode:l,justification:typeof n.justification=="string"?n.justification.trim():"",allowDomains:l==="allow"?$(n.allow_domains):[],allowWrite:l==="allow"?$(n.allow_write).map(a=>F(a,o.cwd)):[],background:o.background===!0,...r?{trigger:r}:{}},i=c((a,t)=>{const d=a.approved&&a.scope==="session"&&l==="unsandboxed"?{...a,scope:"once"}:a,w=d.approved&&l==="allow"?d.grant:void 0,p=[...new Set([...s.allowDomains,...$(w?.allowDomains)])],u=[...new Set([...s.allowWrite,...$(w?.allowWrite).map(m=>F(m,o.cwd))])];if(d.approved&&d.scope==="session"){for(const m of p)this.sessionDomains.add(m);for(const m of u)this.sessionWritable.add(m)}return r&&t==="none"||this.onEvent?.({type:"sandbox_escalation",toolCallId:o.toolCallId,toolName:o.toolName,request:s,decision:d,decidedBy:t}),{request:s,decision:d,decidedBy:t,allowDomains:p,allowWrite:u}},"finish");if(!s.justification)return i({approved:!1,message:"an escalation needs a justification"},"none");if(l==="allow"&&s.allowDomains.length===0&&s.allowWrite.length===0)return i({approved:!1,message:'mode "allow" needs allow_domains or allow_write'},"none");if(this.onEscalation){const a=await this.onEscalation(s,o.ctx);if(a)return i(a,"sdk")}for(const a of R){const t=await a(s,o.ctx);if(t)return i(t,"handler")}if(o.ctx?.hasUI){const a=o.ctx;return i(await this.queueUiApproval(()=>So(s,a,o.signal)),"ui")}return i({approved:!1,message:"nobody is available to approve it (no interactive UI and no approver configured)"},"none")}}function Y(e,o){return{command:e,sandboxed:!1,details:o,finish:c(async()=>{},"finish")}}c(Y,"passthrough");function go(e){if(!(!e||e.length===0))for(const o of co(e))try{Z(o,{recursive:!0,mode:448})}catch{}}c(go,"ensurePackageCaches");function Do(){return no("sandbox")}c(Do,"createScratchDir");function ko(e){return`'${e.replace(/'/g,"'\\''")}'`}c(ko,"shellQuote");async function So(e,o,n){if(n?.aborted)return{approved:!1,message:"the turn was interrupted before the user answered"};const r=h("\u4EC5\u672C\u6B21\u5141\u8BB8"),l=h("\u672C\u4F1A\u8BDD\u5185\u90FD\u5141\u8BB8"),s=h("\u62D2\u7EDD"),i=e.mode==="unsandboxed"?h("\u5728\u6C99\u7BB1\u4E4B\u5916\u8FD0\u884C\u547D\u4EE4\uFF08\u53EF\u8BBF\u95EE\u4F60\u7684\u5168\u90E8\u6587\u4EF6\u548C\u7F51\u7EDC\uFF09"):[e.allowDomains.length>0?v(h("\u8BBF\u95EE {domains}"),{domains:e.allowDomains.join(", ")}):"",e.allowWrite.length>0?v(h("\u5199\u5165 {paths}"),{paths:e.allowWrite.join(", ")}):""].filter(Boolean).join(h("\uFF0C\u5E76")),a=[v(h("\u52A9\u624B\u60F3\u8981{what}\u3002"),{what:i}),v(h("\u547D\u4EE4\uFF1A{command}"),{command:e.command}),v(h("\u76EE\u5F55\uFF1A{cwd}"),{cwd:e.cwd}),e.trigger?v(h("\u539F\u56E0\uFF1A{reason}"),{reason:e.justification}):v(h("\u52A9\u624B\u7ED9\u7684\u7406\u7531\uFF08\u672A\u7ECF\u6838\u5B9E\uFF09\uFF1A{reason}"),{reason:e.justification})].join(`
5
- `),t=e.mode==="unsandboxed"?[r,s]:[r,l,s],d=v(h("\u52A9\u624B\u60F3\u8981{what}\u3002"),{what:i}),w=await o.ui.select(a,t,{...n?{signal:n}:{},approval:{source:"sandbox",toolCallId:e.toolCallId,toolName:e.toolName,args:{command:e.command,cwd:e.cwd,mode:e.mode,...e.allowDomains.length>0?{allowDomains:e.allowDomains}:{},...e.allowWrite.length>0?{allowWrite:e.allowWrite}:{},justification:e.justification},risk:{level:e.mode==="unsandboxed"?"high":"medium",reason:e.trigger?e.justification:v(h("\u52A9\u624B\u7ED9\u7684\u7406\u7531\uFF08\u672A\u7ECF\u6838\u5B9E\uFF09\uFF1A{reason}"),{reason:e.justification}),ruleId:`sandbox:${e.mode}`},title:d,description:a.split(`
1
+ var no=Object.defineProperty;var d=(e,o)=>no(e,"name",{value:o,configurable:!0});import{spawnSync as to}from"node:child_process";import{mkdirSync as j}from"node:fs";import{homedir as io}from"node:os";import{isAbsolute as L,join as ao,relative as so,resolve as B}from"node:path";import{ToolExecutionError as ro}from"@earendil-works/pi-agent-core";import{fill as b,t as h}from"../../dal/i18n.js";import{createTempDir as lo,removeTempPath as co}from"../../utils/temp-files.js";import{toolDenial as mo,withToolDenial as ho}from"../tool-denial.js";import{detectSandboxAvailability as po}from"./availability.js";import{collectBlockedAccesses as F}from"./denial.js";import{libreOfficeAccess as fo}from"./libreoffice.js";import{detectNetworkCommand as H,FAIL_FAST_NETWORK_ENV as G,networkDomainsFor as uo,packageCacheDirs as wo}from"./package-managers.js";import{domainMatches as K,expandPath as X,filesystemRules as vo}from"./policy.js";import{acquireSandboxRuntime as bo,ensureFilteringProxy as yo,proxyUnavailableReason as Y,registerNetworkGrant as go,releaseSandboxRuntime as xo,violationsForCommand as ko,wrapCommand as Do}from"./runtime.js";import{prepareWindowsCommand as So}from"./windows.js";function _(e,o){return new ro(e,ho({sandbox:o},mo("sandbox",e)))}d(_,"sandboxRefusal");const A=Symbol.for("dal.sandbox.escalationHandlers"),D=globalThis;D[A]instanceof Set||(D[A]=new Set);const N=D[A];function zo(e){return N.add(e),()=>{N.delete(e)}}d(zo,"registerSandboxEscalationHandler");const Q=Symbol.for("dal.sandbox.processSandbox");function Jo(e){D[Q]=e}d(Jo,"setProcessShellSandbox");function Zo(){return D[Q]}d(Zo,"getProcessShellSandbox");const V=new Map,Eo="/private/tmp/sh-thd-*";function $o(e){const o=B(e,"git-template");try{return j(o,{recursive:!0}),o}catch{return}}d($o,"ensureEmptyGitTemplate");function _o(e){const o=V.get(e);if(o)return o;const n=to("git",["rev-parse","--absolute-git-dir","--git-common-dir"],{cwd:e,encoding:"utf8",timeout:3e3}),c=[];if(n.status===0)for(const s of n.stdout.split(`
2
+ `)){const i=s.trim();if(!i)continue;const t=L(i)?i:B(e,i),a=so(e,t);(a.startsWith("..")||L(a))&&c.push(t)}const r=[...new Set(c)];return V.set(e,r),r}d(_o,"gitDirsOutside");function W(e){return Array.isArray(e)?e.filter(o=>typeof o=="string"&&o.trim().length>0).map(o=>o.trim()):[]}d(W,"cleanList");let Wo=0;class qo{static{d(this,"ShellSandbox")}policy;onEscalation;onEvent;availabilityOverride;sessionDomains=new Set;sessionWritable=new Set;holdsRuntime=!1;sharedScratch;ownScratch;constructor(o){this.policy=o.policy,this.onEscalation=o.onEscalation,this.onEvent=o.onEvent,this.availabilityOverride=o.availability,this.sharedScratch=o.scratchDir,this.active&&(bo(),this.holdsRuntime=!0)}scratchDir(){return this.sharedScratch?this.sharedScratch():(this.ownScratch??=To(),this.ownScratch)}async dispose(){this.ownScratch&&(co(this.ownScratch),this.ownScratch=void 0),this.holdsRuntime&&(this.holdsRuntime=!1,await xo())}get level(){return this.policy.level}get active(){return this.policy.level!=="off"}availability(){return this.availabilityOverride??po()}status(){const o=this.availability(),n=Y();return{level:this.policy.level,levelSource:this.policy.levelSource,enforced:this.active&&o.available,platform:o.platform,...o.mechanism?{mechanism:o.mechanism}:{},...this.active&&!o.available&&o.reason?{unavailableReason:o.reason}:{},...o.isolationTier?{isolationTier:o.isolationTier}:{},...o.limitations?.length?{limitations:[...o.limitations]}:{},network:{allowedDomains:[...this.policy.network.allowedDomains],deniedDomains:[...this.policy.network.deniedDomains],...n?{proxyError:n}:{}},sessionAllowances:{domains:[...this.sessionDomains],writablePaths:[...this.sessionWritable]}}}networkOpen(){return this.policy.network.open&&this.availability().mechanism!=="mxc"}describeForModel(){if(!this.active)return;const o=this.policy.level==="read-only"?"writes only to $TMPDIR (session scratch)":"writes to the working directory, temp directories and caches (agent/editor config, git hooks, shell start-up files and .env stay read-only)",n=this.policy.network.allowedDomains,c=this.networkOpen()?"network on":(n.length>0?`network off except ${n.join(", ")}`:"network off")+(this.policy.level==="workspace-write"?" (package installs via npm/pnpm/yarn/pip/uv/cargo/go and curl/wget/git clone ask the user for their hosts by themselves: run them plainly, without sandbox_escalation)":"");return`OS sandbox (${this.policy.level}): ${o}; ${c}; ~/.ssh and other credentials unreadable; scratch files (helper scripts, test programs, build caches, unpacked archives) go in $TMPDIR, the session's own temp directory, removed when the session ends: not /tmp, not the working directory; read, write and edit take $TMPDIR paths too. Use sandbox_escalation only after the result says the sandbox blocked something the task needs.`}unavailableRefusal(){if(!this.active)return;const o=this.availability();if(!o.available)return[`Command refused: the sandbox level is "${this.policy.level}", but ${o.reason??"the OS sandbox is unavailable."}`,"Commands are not run without the sandbox unless the user says so explicitly.",'The user can fix the sandbox, or opt out explicitly with `dal --sandbox off` or "sandbox": { "level": "off" } in ~/.dal/agent/settings.json.','A single command can still run if the user approves it: retry with sandbox_escalation {"mode":"unsandboxed","justification":"..."}.'].join(`
3
+ `)}planNetworkEscalation(o){if(this.policy.level!=="workspace-write"||this.networkOpen()||!this.availability().available)return;const n=H(o.command);if(!n)return;const c=[...this.policy.network.allowedDomains,...this.sessionDomains],r=this.policy.network.deniedDomains,s=uo(n,o.cwd).filter(t=>!c.some(a=>K(t,a))&&!r.some(a=>K(t,a)));if(s.length===0)return;const i=n.ecosystems.length>0?"package-install":"download";return{mode:"allow",allow_domains:s,trigger:i,justification:i==="package-install"?h("\u8FD9\u6761\u547D\u4EE4\u8981\u5B89\u88C5\u4F9D\u8D56\uFF0C\u9700\u8981\u4ECE\u8F6F\u4EF6\u6E90\u4E0B\u8F7D\u3002"):h("\u8FD9\u6761\u547D\u4EE4\u8981\u4ECE\u7F51\u4E0A\u4E0B\u8F7D\u6587\u4EF6\u3002")}}async prepare(o){const n=this.policy.level;if(n==="off")return z(o.command,{level:n,sandboxed:!1});const c=this.unavailableRefusal();if(c&&o.escalation?.mode!=="unsandboxed")throw _(c,{level:n,sandboxed:!1});let r=[],s=[],i;const t=o.escalation||c?void 0:this.planNetworkEscalation(o),a=t?await this.approveEscalation(o,t,t.trigger):void 0;if(t&&a&&a.decidedBy!=="none"){const f={request:a.request,decision:a.decision};if(i=f,!f.decision.approved)throw _(`The user did not allow network access for this command${f.decision.message?` (${f.decision.message})`:""}: it needs ${t.allow_domains.join(", ")}. Do not retry it with sandbox_escalation; continue without it or ask the user.`,{level:n,sandboxed:!1,escalation:f});r=a.allowDomains,s=a.allowWrite}else if(o.escalation){const{decidedBy:f,allowDomains:k,allowWrite:T,...v}=await this.approveEscalation(o,o.escalation);if(i=v,!v.decision.approved)throw _(`Sandbox escalation refused${v.decision.message?`: ${v.decision.message}`:"."} Do not retry the same escalation; continue without it or ask the user.`,{level:n,sandboxed:!1,escalation:i});if(v.request.mode==="unsandboxed")return z(o.command,{level:n,sandboxed:!1,escalation:i});r=k,s=T}const l=this.availability(),u=o.shellKind??"bash";if(u!=="bash"&&l.mechanism!=="mxc")throw _(`Command refused: ${u} commands cannot run inside the ${l.mechanism??"OS"} sandbox, and the sandbox level is "${n}". Use the bash tool, or the user can opt out with \`dal --sandbox off\`.`,{level:n,sandboxed:!1});const p=this.scratchDir();n==="workspace-write"&&(Co(),Io(H(o.command)?.managers));const w=vo(this.policy,o.cwd,{gitDirs:this.policy.level==="workspace-write"?_o(o.cwd):[],extraWrite:[...this.sessionWritable,...s],scratchDir:p}),m={allowedDomains:[...this.policy.network.allowedDomains,...this.sessionDomains,...r],deniedDomains:this.policy.network.deniedDomains,refusals:[]},S=`${process.pid}-${++Wo}`,y=this.networkOpen(),g=!y&&m.allowedDomains.length===0;if(l.mechanism==="mxc"&&l.mxc){const f=g?{...o.env??process.env,...G}:o.env;return this.prepareWindows({...o,...f?{env:f}:{}},{level:n,shellKind:u,scratch:p,rules:w,grant:m,runId:S,escalation:i,availability:l})}const x=Ro(p),J=g?Object.entries(G).map(([f,k])=>` ${f}=${k}`).join(""):"",E=fo(p,l.platform),$=E&&!y?E:void 0,Z=E?` UserInstallation="\${UserInstallation:-${E.env.UserInstallation.replace(/[\\"$`]/g,"\\$&")}}"`:"",O=n==="workspace-write"?$o(p):void 0,q=O?` GIT_TEMPLATE_DIR="\${GIT_TEMPLATE_DIR:-${O.replace(/[\\"$`]/g,"\\$&")}}"`:"",P=`export DAL_SANDBOX_RUN=${S} TMPDIR=${x} TMP=${x} TEMP=${x}${J}${Z}${q}
4
+ ${o.command}`,oo=Date.now(),C=await Do({command:P,shell:o.shell,allowWrite:[...w.allowWrite,...$?$.allowWrite:[],...l.platform==="darwin"&&n==="read-only"?[Eo]:[]],denyWrite:w.denyWrite,denyRead:w.denyRead,allowLocalBinding:o.background===!0||this.policy.network.allowLocalBinding,openNetwork:y,allowGitConfig:n==="workspace-write",...$?{allowUnixSockets:$.allowUnixSockets}:{},...l.ripgrep?{ripgrep:l.ripgrep}:{}},m),I={level:n,sandboxed:!0,...i?{escalation:i}:{}};let U=!1;return{command:C.command,sandboxed:!0,details:I,finish:d(async(f,k)=>{if(U)return I.denial;if(U=!0,C.release(),f===0)return;const T=l.platform==="darwin"?await ko(P,oo,400):[],v=F({refusals:m.refusals,violations:T,output:k});if(!v)return;const M=C.proxied?void 0:Y(),R={level:n,platform:l.platform,command:o.command,cwd:o.cwd,blocked:v,scratchDir:p,...M&&v.some(eo=>eo.kind==="network")?{networkProxyError:M}:{}};return I.denial=R,this.onEvent?.({type:"sandbox_denied",toolCallId:o.toolCallId,toolName:o.toolName,denial:R}),R},"finish")}}async prepareWindows(o,n){const{level:c,grant:r,availability:s}=n,i=s.mxc;if(!i)throw new Error("Command refused: the Windows sandbox (mxc) is not loaded.");let t,a;if(r.allowedDomains.length>0){const m=await yo();"port"in m?t=m.port:a=m.error}const l=So({runtime:i,kind:n.shellKind,shellPath:o.shell,command:o.command,cwd:o.cwd,level:c,rules:n.rules,env:o.env??process.env,scratchDir:n.scratch,runId:n.runId,...t!==void 0?{proxyPort:t}:{},allowLocalNetwork:o.background===!0||this.policy.network.allowLocalBinding}),u=go(r),p={level:c,sandboxed:!0,...n.escalation?{escalation:n.escalation}:{}};let w=!1;return{command:l.command,sandboxed:!0,details:p,finish:d(async(m,S)=>{if(w)return p.denial;if(w=!0,u(),l.cleanup(),m===0)return;const y=F({refusals:r.refusals,violations:[],output:S});if(!y)return;const g={level:c,platform:s.platform,command:o.command,cwd:o.cwd,blocked:y,scratchDir:n.scratch,...a&&y.some(x=>x.kind==="network")?{networkProxyError:a}:{}};return p.denial=g,this.onEvent?.({type:"sandbox_denied",toolCallId:o.toolCallId,toolName:o.toolName,denial:g}),g},"finish")}}uiApprovals=Promise.resolve();queueUiApproval(o){const n=this.uiApprovals.then(o,o);return this.uiApprovals=n.catch(()=>{}),n}async approveEscalation(o,n,c){const r=n.mode==="unsandboxed"?"unsandboxed":"allow",s={toolCallId:o.toolCallId,toolName:o.toolName,command:o.command,cwd:o.cwd,level:this.policy.level,mode:r,justification:typeof n.justification=="string"?n.justification.trim():"",allowDomains:r==="allow"?W(n.allow_domains):[],allowWrite:r==="allow"?W(n.allow_write).map(t=>X(t,o.cwd)):[],background:o.background===!0,...c?{trigger:c}:{}},i=d((t,a)=>{const l=t.approved&&t.scope==="session"&&r==="unsandboxed"?{...t,scope:"once"}:t,u=l.approved&&r==="allow"?l.grant:void 0,p=[...new Set([...s.allowDomains,...W(u?.allowDomains)])],w=[...new Set([...s.allowWrite,...W(u?.allowWrite).map(m=>X(m,o.cwd))])];if(l.approved&&l.scope==="session"){for(const m of p)this.sessionDomains.add(m);for(const m of w)this.sessionWritable.add(m)}return c&&a==="none"||this.onEvent?.({type:"sandbox_escalation",toolCallId:o.toolCallId,toolName:o.toolName,request:s,decision:l,decidedBy:a}),{request:s,decision:l,decidedBy:a,allowDomains:p,allowWrite:w}},"finish");if(!s.justification)return i({approved:!1,message:"an escalation needs a justification"},"none");if(r==="allow"&&s.allowDomains.length===0&&s.allowWrite.length===0)return i({approved:!1,message:'mode "allow" needs allow_domains or allow_write'},"none");if(this.onEscalation){const t=await this.onEscalation(s,o.ctx);if(t)return i(t,"sdk")}for(const t of N){const a=await t(s,o.ctx);if(a)return i(a,"handler")}if(o.ctx?.hasUI){const t=o.ctx;return i(await this.queueUiApproval(()=>jo(s,t,o.signal)),"ui")}return i({approved:!1,message:"nobody is available to approve it (no interactive UI and no approver configured)"},"none")}}function z(e,o){return{command:e,sandboxed:!1,details:o,finish:d(async()=>{},"finish")}}d(z,"passthrough");function Co(){if(process.platform!=="linux")return;const e=process.env.XDG_CACHE_HOME?.trim()||ao(io(),".cache");try{j(e,{recursive:!0,mode:448})}catch{}}d(Co,"ensureUserCacheRoot");function Io(e){if(!(!e||e.length===0))for(const o of wo(e))try{j(o,{recursive:!0,mode:448})}catch{}}d(Io,"ensurePackageCaches");function To(){return lo("sandbox")}d(To,"createScratchDir");function Ro(e){return`'${e.replace(/'/g,"'\\''")}'`}d(Ro,"shellQuote");async function jo(e,o,n){if(n?.aborted)return{approved:!1,message:"the turn was interrupted before the user answered"};const c=h("\u4EC5\u672C\u6B21\u5141\u8BB8"),r=h("\u672C\u4F1A\u8BDD\u5185\u90FD\u5141\u8BB8"),s=h("\u62D2\u7EDD"),i=e.mode==="unsandboxed"?h("\u5728\u6C99\u7BB1\u4E4B\u5916\u8FD0\u884C\u547D\u4EE4\uFF08\u53EF\u8BBF\u95EE\u4F60\u7684\u5168\u90E8\u6587\u4EF6\u548C\u7F51\u7EDC\uFF09"):[e.allowDomains.length>0?b(h("\u8BBF\u95EE {domains}"),{domains:e.allowDomains.join(", ")}):"",e.allowWrite.length>0?b(h("\u5199\u5165 {paths}"),{paths:e.allowWrite.join(", ")}):""].filter(Boolean).join(h("\uFF0C\u5E76")),t=[b(h("\u52A9\u624B\u60F3\u8981{what}\u3002"),{what:i}),b(h("\u547D\u4EE4\uFF1A{command}"),{command:e.command}),b(h("\u76EE\u5F55\uFF1A{cwd}"),{cwd:e.cwd}),e.trigger?b(h("\u539F\u56E0\uFF1A{reason}"),{reason:e.justification}):b(h("\u52A9\u624B\u7ED9\u7684\u7406\u7531\uFF08\u672A\u7ECF\u6838\u5B9E\uFF09\uFF1A{reason}"),{reason:e.justification})].join(`
5
+ `),a=e.mode==="unsandboxed"?[c,s]:[c,r,s],l=b(h("\u52A9\u624B\u60F3\u8981{what}\u3002"),{what:i}),u=await o.ui.select(t,a,{...n?{signal:n}:{},approval:{source:"sandbox",toolCallId:e.toolCallId,toolName:e.toolName,args:{command:e.command,cwd:e.cwd,mode:e.mode,...e.allowDomains.length>0?{allowDomains:e.allowDomains}:{},...e.allowWrite.length>0?{allowWrite:e.allowWrite}:{},justification:e.justification},risk:{level:e.mode==="unsandboxed"?"high":"medium",reason:e.trigger?e.justification:b(h("\u52A9\u624B\u7ED9\u7684\u7406\u7531\uFF08\u672A\u7ECF\u6838\u5B9E\uFF09\uFF1A{reason}"),{reason:e.justification}),ruleId:`sandbox:${e.mode}`},title:l,description:t.split(`
6
6
  `).slice(1).join(`
7
- `),options:e.mode==="unsandboxed"?["allow_once","deny"]:["allow_once","allow_session","deny"]}});return n?.aborted?{approved:!1,message:"the turn was interrupted before the user answered"}:w===r?{approved:!0,scope:"once"}:w===l?{approved:!0,scope:"session"}:{approved:!1,message:"the user declined"}}c(So,"askThroughUi");export{Ko as ShellSandbox,Do as createScratchDir,Fo as getProcessShellSandbox,Lo as registerSandboxEscalationHandler,Mo as setProcessShellSandbox};
7
+ `),options:e.mode==="unsandboxed"?["allow_once","deny"]:["allow_once","allow_session","deny"]}});return n?.aborted?{approved:!1,message:"the turn was interrupted before the user answered"}:u===c?{approved:!0,scope:"once"}:u===r?{approved:!0,scope:"session"}:{approved:!1,message:"the user declined"}}d(jo,"askThroughUi");export{Eo as MACOS_HEREDOC_TEMP,qo as ShellSandbox,To as createScratchDir,Zo as getProcessShellSandbox,zo as registerSandboxEscalationHandler,Jo as setProcessShellSandbox};
package/dist/core/sdk.js CHANGED
@@ -1 +1 @@
1
- var z=Object.defineProperty;var d=(o,u)=>z(o,"name",{value:u,configurable:!0});import{join as A}from"node:path";import{Agent as J,setDefaultStreamFn as X}from"@earendil-works/pi-agent-core";import{clampThinkingLevel as Y,streamSimple as Z}from"@earendil-works/pi-ai/compat";import{getAgentDir as ee}from"../config.js";import{resolvePath as b}from"../utils/paths.js";import{AgentSession as te}from"./agent-session.js";import{formatNoModelsAvailableMessage as oe}from"./auth-guidance.js";import{CacheWarmer as re}from"./cache-warmer.js";import{DEFAULT_THINKING_LEVEL as B}from"./defaults.js";import{createToolNameMatcher as ne}from"./mcp-servers.js";import{convertToLlm as se}from"./messages.js";import{findInitialModel as ie}from"./model-resolver.js";import{ModelRuntime as ae}from"./model-runtime.js";import{mergeProviderAttributionHeaders as de}from"./provider-attribution.js";import{DefaultResourceLoader as le}from"./resource-loader.js";import{getDefaultSessionDir as me,SessionManager as ce}from"./session-manager.js";import{applyToolModifiers as ue,DEFAULT_TOOL_NAMES as ge,getToolListError as fe,isToolModifier as ve,SettingsManager as Te}from"./settings-manager.js";import{moveSessionEnvironmentOutOfSystemPrompt as he}from"./system-prompt.js";import{time as pe}from"./timings.js";import{createBashTool as Me,createCodingTools as ye,createEditTool as xe,createFindTool as Le,createGrepTool as ke,createLsTool as Se,createPowerShellTool as De,createReadOnlyTools as Re,createReadTool as Ie,createWriteTool as we,withFileMutationQueue as Ce}from"./tools/index.js";import{getBranchSelection as Pe}from"./virtual-models.js";X(Z);export*from"./agent-session-runtime.js";function Ee(){return ee()}d(Ee,"getDefaultAgentDir");async function et(o={}){const u=b(o.cwd??o.sessionManager?.getCwd()??process.cwd()),h=o.agentDir?b(o.agentDir):Ee();let p=o.resourceLoader;const N=o.agentDir?A(h,"auth.json"):void 0,H=o.agentDir?A(h,"models.json"):void 0,g=o.modelRuntime??await ae.create({authPath:N,modelsPath:H}),r=o.settingsManager??Te.create(u,h),l=o.sessionManager??ce.create(u,me(u,h));p||(p=new le({cwd:u,agentDir:h,settingsManager:r}),await p.reload(),pe("resourceLoader.reload"));const D=l.buildSessionContext(),k=D.messages.length>0,w=l.getBranch().some(e=>e.type==="thinking_level_change");let n=o.model,M,R;const f=Pe(l.getBranch(),(e,t)=>g.getModel(e,t));if(!n&&k&&f){const e=g.getModel(f.provider,f.modelId);e&&g.hasConfiguredAuth(e.provider)&&(n=e),n||(M=`Could not restore model ${f.provider}/${f.modelId}`,R={provider:f.provider,modelId:f.modelId})}if(!n){const e=r.getDefaultProvider(),t=r.getDefaultModel();n=(await ie({scopedModels:[],isContinuing:k,defaultProvider:e,defaultModelId:t,defaultThinkingLevel:r.getDefaultThinkingLevel(),modelThinkingLevels:r.getAllModelThinkingLevels(),modelRuntime:g})).model,n?M&&(M+=`. Using ${n.provider}/${n.id}`):M=oe(),e&&t&&(!n||n.provider!==e||n.id!==t)&&(R={provider:e,modelId:t})}let i=o.thinkingLevel;if(i===void 0&&k&&(i=w?D.thinkingLevel:r.getDefaultThinkingLevel()??B),i===void 0&&n){const e=r.getModelThinkingLevel(n.provider,n.id);e&&(i=e)}i===void 0&&(i=r.getDefaultThinkingLevel()??B),n?i=Y(n,i):i="off";const C=o.tools?fe(o.tools):void 0;if(C)throw new Error(`Invalid tools option: ${C}`);const P=o.noTools?[]:r.getDefaultTools()??o.defaultActiveTools??ge,y=o.tools?.some(ve)?o.tools:void 0,E=y?ue(P,y):o.tools,F=y?o.noTools==="all"?E:void 0:o.tools??(o.noTools==="all"?[]:void 0),I=o.excludeTools,O=I?ne(I):void 0,W=(E??P).filter(e=>!O?.(e)),U=d(e=>{const t=se(e);return r.getBlockImages()?t.map(s=>{if(s.role==="user"||s.role==="toolResult"){const a=s.content;if(Array.isArray(a)&&a.some(m=>m.type==="image")){const m=a.map(c=>c.type==="image"?{type:"text",text:"Image reading is disabled."}:c).filter((c,x,L)=>!(c.type==="text"&&c.text==="Image reading is disabled."&&x>0&&L[x-1].type==="text"&&L[x-1].text==="Image reading is disabled."));return{...s,content:m}}}return s}):t},"convertToLlmWithBlockImages"),v={},_=new re(g,l,()=>r.getCacheWarmingMode(),async e=>v.current?.emitCacheWarmingDecision(e)??e.action),$=d((e,t={})=>{const s=r.getProviderRetrySettings(),a=r.getHttpIdleTimeoutMs(),T=a===0?2147483647:a,m=v.current,c=r.getOutputTokenLimit(e.maxTokens);return{...t,maxTokens:t.maxTokens??(c!==e.maxTokens?c:void 0),timeoutMs:t.timeoutMs??s.timeoutMs??T,websocketConnectTimeoutMs:t.websocketConnectTimeoutMs??r.getWebSocketConnectTimeoutMs(),maxRetries:t.maxRetries??s.maxRetries,maxRetryDelayMs:t.maxRetryDelayMs??s.maxRetryDelayMs,transformHeaders:d(async x=>{const L=de(e,r,t.sessionId,x);return m?.hasHandlers("before_provider_headers")?m.emitBeforeProviderHeaders(L??{}):L??{}},"transformHeaders")}},"buildRequestOptions"),j=d(e=>{const t=S.state.messages;return()=>{const s=S.state.model,a=S.state.messages;return s.provider===e.provider&&s.id===e.id&&t.length<=a.length&&t.every((T,m)=>a[m]===T)}},"cacheContextIsCurrent"),q=d(async e=>{const t=v.current;return t?.hasHandlers("before_provider_request")?t.emitBeforeProviderRequest(e):e},"transformProviderPayload"),G=d(async e=>{const t=v.current;t?.hasHandlers("after_provider_response")&&await t.emit({type:"after_provider_response",status:e.status,headers:e.headers})},"handleProviderResponse"),K=d(async(e,t)=>{const s=v.current;s?.hasHandlers("provider_stream_event")&&await s.emit({data:e,type:"provider_stream_event",provider:t.provider,api:t.api,model:t.id})},"handleProviderStreamEvent"),S=new J({initialState:{systemPrompt:"",model:n,thinkingLevel:i,tools:[],messages:D.messages},convertToLlm:U,streamFn:d(async(e,t,s)=>{const a=$(e,s),T={...t,messages:he(t.messages)};return s?.sessionId===l.getSessionId()&&_.start({model:e,context:T,options:a},j(e)),g.streamSimple(e,T,a)},"streamFn"),onPayload:q,onResponse:G,onProviderStreamEvent:K,sessionId:l.getSessionId(),transformContext:d(async e=>{const t=v.current;return t?t.emitContext(e):e},"transformContext"),steeringMode:r.getSteeringMode(),followUpMode:r.getFollowUpMode(),transport:r.getTransport(),thinkingBudgets:r.getThinkingBudgets(),maxRetryDelayMs:r.getProviderRetrySettings().maxRetryDelayMs});k?w||l.appendThinkingLevelChange(i):(n&&l.appendModelChange(n.provider,n.id),l.appendThinkingLevelChange(i));const Q=new te({agent:S,sessionManager:l,settingsManager:r,cwd:u,scopedModels:o.scopedModels,resourceLoader:p,customTools:o.customTools,modelRuntime:g,cacheWarmer:_,initialActiveToolNames:W,usesDefaultTools:(o.tools===void 0||y!==void 0)&&!o.noTools,defaultToolModifiers:y,allowedToolNames:F,excludedToolNames:I,extensionRunnerRef:v,sessionStartEvent:o.sessionStartEvent,desiredModel:R,sandbox:o.sandbox}),V=p.getExtensions();return{session:Q,extensionsResult:V,modelFallbackMessage:M}}d(et,"createAgentSession");export{et as createAgentSession,Me as createBashTool,ye as createCodingTools,xe as createEditTool,Le as createFindTool,ke as createGrepTool,Se as createLsTool,De as createPowerShellTool,Re as createReadOnlyTools,Ie as createReadTool,we as createWriteTool,Ce as withFileMutationQueue};
1
+ var z=Object.defineProperty;var d=(o,u)=>z(o,"name",{value:u,configurable:!0});import{join as A}from"node:path";import{Agent as J,setDefaultStreamFn as X}from"@earendil-works/pi-agent-core";import{clampThinkingLevel as Y,streamSimple as Z}from"@earendil-works/pi-ai/compat";import{getAgentDir as ee}from"../config.js";import{resolvePath as b}from"../utils/paths.js";import{AgentSession as te}from"./agent-session.js";import{formatNoModelsAvailableMessage as oe}from"./auth-guidance.js";import{CacheWarmer as re}from"./cache-warmer.js";import{getClientIdentity as ne}from"./client-identity.js";import{withDalSessionHeaders as se}from"./dal-session-headers.js";import{DEFAULT_THINKING_LEVEL as B}from"./defaults.js";import{createToolNameMatcher as ie}from"./mcp-servers.js";import{convertToLlm as ae}from"./messages.js";import{findInitialModel as de}from"./model-resolver.js";import{ModelRuntime as le}from"./model-runtime.js";import{DefaultResourceLoader as me}from"./resource-loader.js";import{getDefaultSessionDir as ce,SessionManager as ue}from"./session-manager.js";import{applyToolModifiers as ge,DEFAULT_TOOL_NAMES as fe,getToolListError as Te,isToolModifier as ve,SettingsManager as he}from"./settings-manager.js";import{moveSessionEnvironmentOutOfSystemPrompt as pe}from"./system-prompt.js";import{time as Me}from"./timings.js";import{createBashTool as ye,createCodingTools as xe,createEditTool as ke,createFindTool as Le,createGrepTool as Se,createLsTool as De,createPowerShellTool as Ie,createReadOnlyTools as Re,createReadTool as we,createWriteTool as Ce,withFileMutationQueue as Ee}from"./tools/index.js";import{getBranchSelection as Pe}from"./virtual-models.js";X(Z);export*from"./agent-session-runtime.js";function _e(){return ee()}d(_e,"getDefaultAgentDir");async function ot(o={}){const u=b(o.cwd??o.sessionManager?.getCwd()??process.cwd()),h=o.agentDir?b(o.agentDir):_e();let p=o.resourceLoader;const N=o.agentDir?A(h,"auth.json"):void 0,F=o.agentDir?A(h,"models.json"):void 0,g=o.modelRuntime??await le.create({authPath:N,modelsPath:F}),r=o.settingsManager??he.create(u,h),l=o.sessionManager??ue.create(u,ce(u,h));p||(p=new me({cwd:u,agentDir:h,settingsManager:r}),await p.reload(),Me("resourceLoader.reload"));const D=l.buildSessionContext(),L=D.messages.length>0,w=l.getBranch().some(e=>e.type==="thinking_level_change");let n=o.model,M,I;const f=Pe(l.getBranch(),(e,t)=>g.getModel(e,t));if(!n&&L&&f){const e=g.getModel(f.provider,f.modelId);e&&g.hasConfiguredAuth(e.provider)&&(n=e),n||(M=`Could not restore model ${f.provider}/${f.modelId}`,I={provider:f.provider,modelId:f.modelId})}if(!n){const e=r.getDefaultProvider(),t=r.getDefaultModel();n=(await de({scopedModels:[],isContinuing:L,defaultProvider:e,defaultModelId:t,defaultThinkingLevel:r.getDefaultThinkingLevel(),modelThinkingLevels:r.getAllModelThinkingLevels(),modelRuntime:g})).model,n?M&&(M+=`. Using ${n.provider}/${n.id}`):M=oe(),e&&t&&(!n||n.provider!==e||n.id!==t)&&(I={provider:e,modelId:t})}let i=o.thinkingLevel;if(i===void 0&&L&&(i=w?D.thinkingLevel:r.getDefaultThinkingLevel()??B),i===void 0&&n){const e=r.getModelThinkingLevel(n.provider,n.id);e&&(i=e)}i===void 0&&(i=r.getDefaultThinkingLevel()??B),n?i=Y(n,i):i="off";const C=o.tools?Te(o.tools):void 0;if(C)throw new Error(`Invalid tools option: ${C}`);const E=o.noTools?[]:r.getDefaultTools()??o.defaultActiveTools??fe,y=o.tools?.some(ve)?o.tools:void 0,P=y?ge(E,y):o.tools,H=y?o.noTools==="all"?P:void 0:o.tools??(o.noTools==="all"?[]:void 0),R=o.excludeTools,O=R?ie(R):void 0,W=(P??E).filter(e=>!O?.(e)),U=d(e=>{const t=ae(e);return r.getBlockImages()?t.map(s=>{if(s.role==="user"||s.role==="toolResult"){const a=s.content;if(Array.isArray(a)&&a.some(m=>m.type==="image")){const m=a.map(c=>c.type==="image"?{type:"text",text:"Image reading is disabled."}:c).filter((c,x,k)=>!(c.type==="text"&&c.text==="Image reading is disabled."&&x>0&&k[x-1].type==="text"&&k[x-1].text==="Image reading is disabled."));return{...s,content:m}}}return s}):t},"convertToLlmWithBlockImages"),T={},_=new re(g,l,()=>r.getCacheWarmingMode(),async e=>T.current?.emitCacheWarmingDecision(e)??e.action),$=d((e,t={})=>{const s=r.getProviderRetrySettings(),a=r.getHttpIdleTimeoutMs(),v=a===0?2147483647:a,m=T.current,c=r.getOutputTokenLimit(e.maxTokens);return{...t,maxTokens:t.maxTokens??(c!==e.maxTokens?c:void 0),timeoutMs:t.timeoutMs??s.timeoutMs??v,firstTokenTimeoutMs:t.firstTokenTimeoutMs??r.getFirstTokenTimeoutMs(),websocketConnectTimeoutMs:t.websocketConnectTimeoutMs??r.getWebSocketConnectTimeoutMs(),maxRetries:t.maxRetries??s.maxRetries,maxRetryDelayMs:t.maxRetryDelayMs??s.maxRetryDelayMs,identity:ne(r),transformHeaders:d(async x=>{const k=se(e,t.sessionId,x);return m?.hasHandlers("before_provider_headers")?m.emitBeforeProviderHeaders(k):k},"transformHeaders")}},"buildRequestOptions"),j=d(e=>{const t=S.state.messages;return()=>{const s=S.state.model,a=S.state.messages;return s.provider===e.provider&&s.id===e.id&&t.length<=a.length&&t.every((v,m)=>a[m]===v)}},"cacheContextIsCurrent"),q=d(async e=>{const t=T.current;return t?.hasHandlers("before_provider_request")?t.emitBeforeProviderRequest(e):e},"transformProviderPayload"),G=d(async e=>{const t=T.current;t?.hasHandlers("after_provider_response")&&await t.emit({type:"after_provider_response",status:e.status,headers:e.headers})},"handleProviderResponse"),K=d(async(e,t)=>{const s=T.current;s?.hasHandlers("provider_stream_event")&&await s.emit({data:e,type:"provider_stream_event",provider:t.provider,api:t.api,model:t.id})},"handleProviderStreamEvent"),S=new J({initialState:{systemPrompt:"",model:n,thinkingLevel:i,tools:[],messages:D.messages},convertToLlm:U,streamFn:d(async(e,t,s)=>{const a=$(e,s),v={...t,messages:pe(t.messages)};return s?.sessionId===l.getSessionId()&&_.start({model:e,context:v,options:a},j(e)),g.streamSimple(e,v,a)},"streamFn"),onPayload:q,onResponse:G,onProviderStreamEvent:K,sessionId:l.getSessionId(),transformContext:d(async e=>{const t=T.current;return t?t.emitContext(e):e},"transformContext"),steeringMode:r.getSteeringMode(),followUpMode:r.getFollowUpMode(),transport:r.getTransport(),thinkingBudgets:r.getThinkingBudgets(),maxRetryDelayMs:r.getProviderRetrySettings().maxRetryDelayMs});L?w||l.appendThinkingLevelChange(i):(n&&l.appendModelChange(n.provider,n.id),l.appendThinkingLevelChange(i));const Q=new te({agent:S,sessionManager:l,settingsManager:r,cwd:u,scopedModels:o.scopedModels,resourceLoader:p,customTools:o.customTools,modelRuntime:g,cacheWarmer:_,initialActiveToolNames:W,usesDefaultTools:(o.tools===void 0||y!==void 0)&&!o.noTools,defaultToolModifiers:y,allowedToolNames:H,excludedToolNames:R,extensionRunnerRef:T,sessionStartEvent:o.sessionStartEvent,desiredModel:I,sandbox:o.sandbox}),V=p.getExtensions();return{session:Q,extensionsResult:V,modelFallbackMessage:M}}d(ot,"createAgentSession");export{ot as createAgentSession,ye as createBashTool,xe as createCodingTools,ke as createEditTool,Le as createFindTool,Se as createGrepTool,De as createLsTool,Ie as createPowerShellTool,Re as createReadOnlyTools,we as createReadTool,Ce as createWriteTool,Ee as withFileMutationQueue};
@@ -0,0 +1,41 @@
1
+ import { type StallReport, type StallWaitKind, StallWatchdog } from "./stall-watchdog.ts";
2
+ export type StallWatchdogEvent = {
3
+ type: "stall_watchdog";
4
+ } & StallReport;
5
+ export declare function stallLogPath(agentDir: string): string;
6
+ export declare function appendStallLog(path: string, record: Record<string, unknown>): void;
7
+ type ObservedEvent = {
8
+ type: string;
9
+ message?: {
10
+ role?: string;
11
+ model?: string;
12
+ };
13
+ toolCallId?: string;
14
+ toolName?: string;
15
+ args?: unknown;
16
+ reason?: string;
17
+ attempt?: number;
18
+ maxAttempts?: number;
19
+ };
20
+ export interface SessionStallMonitorOptions {
21
+ thresholdMs: number;
22
+ onReport: (event: StallWatchdogEvent) => void;
23
+ now?: () => number;
24
+ setInterval?: (fn: () => void, ms: number) => unknown;
25
+ clearInterval?: (handle: unknown) => void;
26
+ checkEveryMs?: number;
27
+ }
28
+ export declare class SessionStallMonitor {
29
+ readonly watchdog: StallWatchdog;
30
+ private readonly toolStages;
31
+ private requestStage;
32
+ private modelStage;
33
+ private compactionStage;
34
+ private retryStage;
35
+ constructor(options: SessionStallMonitorOptions);
36
+ enter: (name: string, kind: StallWaitKind, detail?: string) => (() => void);
37
+ observe(event: ObservedEvent): void;
38
+ stop(): void;
39
+ private leaveRetry;
40
+ }
41
+ export {};
@@ -0,0 +1,2 @@
1
+ var c=Object.defineProperty;var a=(e,t)=>c(e,"name",{value:t,configurable:!0});import{appendFileSync as l,mkdirSync as g,renameSync as h,statSync as d}from"node:fs";import{dirname as u,join as m}from"node:path";import{StallWatchdog as S}from"./stall-watchdog.js";const p=1e6;function q(e){return m(e,"logs","stall.jsonl")}a(q,"stallLogPath");function k(e,t){try{g(u(e),{recursive:!0});try{d(e).size>p&&h(e,`${e}.1`)}catch{}l(e,`${JSON.stringify(t)}
2
+ `)}catch{}}a(k,"appendStallLog");function f(e,t){const o=t??{},s=a(n=>typeof o[n]=="string"?o[n]:void 0,"pick"),i=s("command")??s("path")??s("file_path")??s("url")??s("query")??s("description");if(!i)return e;const r=i.replace(/\s+/g," ").trim();return`${e}: ${r.length>80?`${r.slice(0,79)}\u2026`:r}`}a(f,"describeToolArgs");class ${static{a(this,"SessionStallMonitor")}watchdog;toolStages=new Map;requestStage;modelStage;compactionStage;retryStage;constructor(t){this.watchdog=new S({thresholdMs:t.thresholdMs,onReport:a(o=>t.onReport({type:"stall_watchdog",...o}),"onReport"),now:t.now,setInterval:t.setInterval,clearInterval:t.clearInterval,checkEveryMs:t.checkEveryMs})}enter=a((t,o,s)=>this.watchdog.enter(t,o,s),"enter");observe(t){if(!(!this.watchdog.enabled||t.type==="stall_watchdog")){switch(t.type){case"agent_start":this.leaveRetry(),this.watchdog.running?this.watchdog.progress():this.watchdog.start();return;case"turn_start":this.requestStage?.(),this.requestStage=this.watchdog.enter("request:preparing","engine");return;case"message_start":if(t.message?.role==="assistant"){this.requestStage?.(),this.requestStage=void 0,this.modelStage?.(),this.modelStage=this.watchdog.enter("model:response","model",t.message.model);return}break;case"message_end":if(t.message?.role==="assistant"){this.modelStage?.(),this.modelStage=void 0;return}break;case"tool_execution_start":if(t.toolCallId){this.toolStages.get(t.toolCallId)?.(),this.toolStages.set(t.toolCallId,this.watchdog.enter(`tool:${t.toolName??"unknown"}`,"tool",f(t.toolName??"tool",t.args)));return}break;case"tool_execution_end":if(t.toolCallId){this.toolStages.get(t.toolCallId)?.(),this.toolStages.delete(t.toolCallId);return}break;case"compaction_start":this.compactionStage?.(),this.compactionStage=this.watchdog.enter("compaction","compaction",t.reason);return;case"compaction_end":this.compactionStage?.(),this.compactionStage=void 0;return;case"auto_retry_start":this.leaveRetry(),this.retryStage=this.watchdog.enter("retry:wait","retry",t.attempt!==void 0?`${t.attempt}/${t.maxAttempts??"?"}`:void 0);return;case"auto_retry_end":this.leaveRetry();return;case"agent_settled":this.stop();return}this.watchdog.progress()}}stop(){for(const t of this.toolStages.values())t();this.toolStages.clear(),this.requestStage?.(),this.modelStage?.(),this.compactionStage?.(),this.leaveRetry(),this.requestStage=this.modelStage=this.compactionStage=void 0,this.watchdog.stop()}leaveRetry(){this.retryStage?.(),this.retryStage=void 0}}export{$ as SessionStallMonitor,k as appendStallLog,q as stallLogPath};
@@ -142,6 +142,8 @@ export interface Settings {
142
142
  sessionShareDestination?: SessionShareDestination;
143
143
  httpProxy?: string;
144
144
  httpIdleTimeoutMs?: number;
145
+ stallWatchdogMs?: number;
146
+ firstTokenTimeoutMs?: number;
145
147
  maxOutputTokens?: number;
146
148
  cacheWarming?: CacheWarmingMode;
147
149
  websocketConnectTimeoutMs?: number;
@@ -283,7 +285,9 @@ export declare class SettingsManager {
283
285
  };
284
286
  getMaxOutputTokens(): number;
285
287
  getOutputTokenLimit(modelMaxTokens: number): number;
288
+ getStallWatchdogMs(): number;
286
289
  getHttpIdleTimeoutMs(): number;
290
+ getFirstTokenTimeoutMs(): number;
287
291
  setHttpIdleTimeoutMs(timeoutMs: number): void;
288
292
  getCacheWarmingMode(): CacheWarmingMode;
289
293
  setCacheWarmingMode(mode: CacheWarmingMode): void;
@@ -1 +1 @@
1
- var N=Object.defineProperty;var d=(r,e)=>N(r,"name",{value:e,configurable:!0});import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS as D}from"@earendil-works/pi-ai";import{randomUUID as A}from"crypto";import{existsSync as w,mkdirSync as R,readFileSync as W}from"fs";import{dirname as _,join as f}from"path";import $ from"proper-lockfile";import{CONFIG_DIR_NAME as E,getAgentDir as U}from"../config.js";import{normalizePath as C,resolvePath as p}from"../utils/paths.js";import{stripBom as M}from"../utils/text.js";import{DEFAULT_HTTP_IDLE_TIMEOUT_MS as B,parseHttpIdleTimeoutMs as V}from"./http-dispatcher.js";import{SETTINGS_DEFAULTS as l}from"./settings-defaults.js";import{declaredDataFormat as S,reportNewerDataFormat as H,writeFileAtomicSync as q}from"./shared-data.js";const X=8e4,G={reserveTokens:16384,keepRecentTokens:2e4,maxContextTokens:X},K=32e3,z=5,Q=["off","streaming","idle"];function y(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}d(y,"isMergeableObject");function x(r,e){const t={...r};for(const s of Object.keys(e)){const i=e[s];if(i===void 0)continue;const o=r[s];t[s]=y(o)&&y(i)?x(o,i):i}return t}d(x,"deepMergeObjects");const J=["read","bash","edit","write"];function b(r){return typeof r=="string"&&(r.startsWith("+")||r.startsWith("-"))}d(b,"isToolModifier");function pe(r){const e=r.filter(b);if(e.length===0)return;if(e.length<r.length)return"tool names cannot be mixed with +name or -name entries";const t=e.find(s=>s.includes("*"));if(t)return`+name and -name entries take exact tool names, not patterns: ${t}`}d(pe,"getToolListError");function Y(r,e){const t=[...r];for(const s of e){if(!b(s))continue;const i=s.slice(1),o=t.indexOf(i);s.startsWith("+")&&o===-1&&i?t.push(i):s.startsWith("-")&&o!==-1&&t.splice(o,1)}return t}d(Y,"applyToolModifiers");function Z(r,e){return e===void 0?r:!Array.isArray(r)||!Array.isArray(e)||!e.every(b)?e:[...r,...e]}d(Z,"mergeDefaultTools");function ee(r){const e=r.filter(t=>!b(t));return Y(e.length>0||r.length===0?e:J,r)}d(ee,"resolveDefaultTools");function c(r,e){const t=x(r,e),s=Z(r.defaultTools,e.defaultTools);return s===void 0?t:{...t,defaultTools:s}}d(c,"deepMergeSettings");function F(r,e){const t=V(r);if(t!==void 0)return t;if(r!==void 0)throw new Error(`Invalid ${e} setting: ${String(r)}`)}d(F,"parseTimeoutSetting");const k=1,T=["enableAnalytics","trackingId"];function te(r){let e;try{e=JSON.parse(M(r))}catch{return}if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e;if(!(S(t)>k)&&T.some(s=>s in t)){for(const s of T)delete t[s];return JSON.stringify(t,null,2)}}d(te,"withoutRetiredKeys");function v(r,e,t){return{scope:r,...t?{path:t}:{},error:e instanceof Error?e:new Error(String(e))}}d(v,"toSettingsError");class se{static{d(this,"FileSettingsStorage")}globalSettingsPath;projectSettingsPath;constructor(e,t){const s=p(e),i=p(t);this.globalSettingsPath=f(i,"settings.json"),this.projectSettingsPath=f(s,E,"settings.json")}acquireLockSyncWithRetry(e){let i;for(let o=1;o<=100;o++)try{return $.lockSync(e,{realpath:!1})}catch(n){if((typeof n=="object"&&n!==null&&"code"in n?String(n.code):void 0)!=="ELOCKED"||o===100)throw n;i=n;const h=Date.now();for(;Date.now()-h<20;);}throw i??new Error("Failed to acquire settings lock")}withLock(e,t){const s=e==="global"?this.globalSettingsPath:this.projectSettingsPath,i=_(s);let o;try{const n=w(s);n&&(o=this.acquireLockSyncWithRetry(s));const a=n?W(s,"utf-8"):void 0,h=t(a);h!==void 0&&(w(i)||R(i,{recursive:!0}),o||(o=this.acquireLockSyncWithRetry(s)),q(s,h))}finally{o&&o()}}}class ie{static{d(this,"InMemorySettingsStorage")}global;project;withLock(e,t){const s=e==="global"?this.global:this.project,i=t(s);i!==void 0&&(e==="global"?this.global=i:this.project=i)}}class g{static{d(this,"SettingsManager")}storage;globalSettings;projectSettings;settings;projectTrusted;modifiedFields=new Set;modifiedNestedFields=new Map;modifiedProjectFields=new Set;modifiedProjectNestedFields=new Map;globalSettingsLoadError=null;projectSettingsLoadError=null;writeQueue=Promise.resolve();errors;settingsPaths;constructor(e,t,s,i=null,o=null,n=[],a=!0,h={}){this.storage=e,this.globalSettings=t,this.projectSettings=s,this.projectTrusted=a,this.globalSettingsLoadError=i,this.projectSettingsLoadError=o,this.errors=[...n],this.settingsPaths=h,this.settings=c(this.globalSettings,this.projectSettings),this.reportNewerFormatScopes()}static create(e,t=U(),s={}){const i=p(e),o=p(t),n=new se(i,o);return g.fromStorageWithPaths(n,s,{global:f(o,"settings.json"),project:f(i,E,"settings.json")})}static fromStorage(e,t={}){return g.fromStorageWithPaths(e,t)}static fromStorageWithPaths(e,t,s={}){const i=t.projectTrusted??!0,o=g.tryLoadFromStorage(e,"global"),n=g.tryLoadFromStorage(e,"project",i),a=[];return o.error&&a.push(v("global",o.error,s.global)),n.error&&a.push(v("project",n.error,s.project)),new g(e,o.settings,n.settings,o.error,n.error,a,i,s)}static inMemory(e={},t={}){const s=new ie,i=g.migrateSettings(structuredClone(e));return s.withLock("global",()=>JSON.stringify(i,null,2)),g.fromStorage(s,t)}static loadFromStorage(e,t,s=!0){if(t==="project"&&!s)return{};let i;if(e.withLock(t,n=>(i=n,t==="global"&&n?te(n):void 0)),!i)return{};const o=JSON.parse(M(i));return g.migrateSettings(o)}static tryLoadFromStorage(e,t,s=!0){try{return{settings:g.loadFromStorage(e,t,s),error:null}}catch(i){return{settings:{},error:i}}}static migrateSettings(e){for(const t of T)delete e[t];if("queueMode"in e&&!("steeringMode"in e)&&(e.steeringMode=e.queueMode,delete e.queueMode),!("transport"in e)&&typeof e.websockets=="boolean"&&(e.transport=e.websockets?"websocket":"sse",delete e.websockets),"skills"in e&&typeof e.skills=="object"&&e.skills!==null&&!Array.isArray(e.skills)){const t=e.skills;t.enableSkillCommands!==void 0&&e.enableSkillCommands===void 0&&(e.enableSkillCommands=t.enableSkillCommands),Array.isArray(t.customDirectories)&&t.customDirectories.length>0?e.skills=t.customDirectories:delete e.skills}if("retry"in e&&typeof e.retry=="object"&&e.retry!==null&&!Array.isArray(e.retry)){const t=e.retry,s=typeof t.provider=="object"&&t.provider!==null?t.provider:void 0;typeof t.maxDelayMs=="number"&&(s?.maxRetryDelayMs===void 0||s?.maxRetryDelayMs===null)&&(t.provider={...s??{},maxRetryDelayMs:t.maxDelayMs}),delete t.maxDelayMs}return e}getSettings(){return structuredClone(this.settings)}getGlobalSettings(){return structuredClone(this.globalSettings)}getProjectSettings(){return structuredClone(this.projectSettings)}isProjectTrusted(){return this.projectTrusted}setProjectTrusted(e){if(this.projectTrusted===e)return;if(this.projectTrusted=e,this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear(),!e){this.projectSettings={},this.projectSettingsLoadError=null,this.settings=c(this.globalSettings,this.projectSettings);return}const t=g.tryLoadFromStorage(this.storage,"project",e);this.projectSettings=t.settings,this.projectSettingsLoadError=t.error,t.error&&this.recordError("project",t.error),this.settings=c(this.globalSettings,this.projectSettings)}async reload(){await this.writeQueue;const e=g.tryLoadFromStorage(this.storage,"global");e.error?(this.globalSettingsLoadError=e.error,this.recordError("global",e.error)):(this.globalSettings=e.settings,this.globalSettingsLoadError=null),this.modifiedFields.clear(),this.modifiedNestedFields.clear(),this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear();const t=g.tryLoadFromStorage(this.storage,"project",this.projectTrusted);t.error?(this.projectSettingsLoadError=t.error,this.recordError("project",t.error)):(this.projectSettings=t.settings,this.projectSettingsLoadError=null),this.settings=c(this.globalSettings,this.projectSettings),this.reportNewerFormatScopes()}applyOverrides(e){this.settings=c(this.settings,e)}markModified(e,t){this.modifiedFields.add(e),t&&(this.modifiedNestedFields.has(e)||this.modifiedNestedFields.set(e,new Set),this.modifiedNestedFields.get(e).add(t))}markProjectModified(e,t){this.modifiedProjectFields.add(e),t&&(this.modifiedProjectNestedFields.has(e)||this.modifiedProjectNestedFields.set(e,new Set),this.modifiedProjectNestedFields.get(e).add(t))}assertProjectTrustedForWrite(){if(!this.projectTrusted)throw new Error("Project is not trusted; refusing to write project settings")}reportNewerFormat(e){H(this.settingsPaths[e]??`${e} settings.json`)}reportNewerFormatScopes(){S(this.globalSettings)>k&&this.reportNewerFormat("global"),S(this.projectSettings)>k&&this.reportNewerFormat("project")}recordError(e,t){this.errors.push(v(e,t,this.settingsPaths[e]))}clearModifiedScope(e){if(e==="global"){this.modifiedFields.clear(),this.modifiedNestedFields.clear();return}this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear()}enqueueWrite(e,t){this.writeQueue=this.writeQueue.then(()=>{e==="project"&&this.assertProjectTrustedForWrite(),t(),this.clearModifiedScope(e)}).catch(s=>{this.recordError(e,s)})}cloneModifiedNestedFields(e){const t=new Map;for(const[s,i]of e.entries())t.set(s,new Set(i));return t}persistScopedSettings(e,t,s,i){this.storage.withLock(e,o=>{const n=o?JSON.parse(M(o)):{};if(S(n)>k){this.reportNewerFormat(e);return}const a=o?g.migrateSettings(n):{},h={...a};for(const u of s){const m=t[u];if(i.has(u)&&typeof m=="object"&&m!==null){const L=i.get(u),I=a[u]??{},O=m,P={...I};for(const j of L)P[j]=O[j];h[u]=P}else h[u]=m}return JSON.stringify(h,null,2)})}save(){if(this.settings=c(this.globalSettings,this.projectSettings),this.globalSettingsLoadError)return;const e=structuredClone(this.globalSettings),t=new Set(this.modifiedFields),s=this.cloneModifiedNestedFields(this.modifiedNestedFields);this.enqueueWrite("global",()=>{this.persistScopedSettings("global",e,t,s)})}saveProjectSettings(e){if(this.assertProjectTrustedForWrite(),this.projectSettings=structuredClone(e),this.settings=c(this.globalSettings,this.projectSettings),this.projectSettingsLoadError)return;const t=structuredClone(this.projectSettings),s=new Set(this.modifiedProjectFields),i=this.cloneModifiedNestedFields(this.modifiedProjectNestedFields);this.enqueueWrite("project",()=>{this.persistScopedSettings("project",t,s,i)})}updateProjectSettings(e,t){this.assertProjectTrustedForWrite();const s=structuredClone(this.projectSettings);t(s),this.markProjectModified(e),this.saveProjectSettings(s)}async flush(){await this.writeQueue}drainErrors(){const e=[...this.errors];return this.errors=[],e}getLastChangelogVersion(){return this.settings.lastChangelogVersion}setLastChangelogVersion(e){this.globalSettings.lastChangelogVersion=e,this.markModified("lastChangelogVersion"),this.save()}getSessionDir(){const e=this.settings.sessionDir;return e&&C(e)}getDefaultProvider(){return this.settings.defaultProvider}getDefaultModel(){return this.settings.defaultModel}setDefaultProvider(e){this.globalSettings.defaultProvider=e,this.markModified("defaultProvider"),this.save()}setDefaultModel(e){this.globalSettings.defaultModel=e,this.markModified("defaultModel"),this.save()}setDefaultModelAndProvider(e,t){this.globalSettings.defaultProvider=e,this.globalSettings.defaultModel=t,this.markModified("defaultProvider"),this.markModified("defaultModel"),this.save()}getSteeringMode(){return this.settings.steeringMode||l.steeringMode}setSteeringMode(e){this.globalSettings.steeringMode=e,this.markModified("steeringMode"),this.save()}getFollowUpMode(){return this.settings.followUpMode||l.followUpMode}setFollowUpMode(e){this.globalSettings.followUpMode=e,this.markModified("followUpMode"),this.save()}getThemeSetting(){const e=this.settings.theme;if(typeof e=="string")return e}getTheme(){const e=this.getThemeSetting();return e?.includes("/")?void 0:e}setTheme(e){this.globalSettings.theme=e,this.markModified("theme"),this.save()}getDefaultThinkingLevel(){return this.settings.defaultThinkingLevel}setDefaultThinkingLevel(e){this.globalSettings.defaultThinkingLevel=e,this.markModified("defaultThinkingLevel"),this.save()}getModelThinkingLevel(e,t){return this.settings.modelThinkingLevels?.[`${e}/${t}`]}getAllModelThinkingLevels(){return{...this.settings.modelThinkingLevels??{}}}setModelThinkingLevel(e,t,s){this.globalSettings.modelThinkingLevels||(this.globalSettings.modelThinkingLevels={}),this.globalSettings.modelThinkingLevels[`${e}/${t}`]=s,this.markModified("modelThinkingLevels"),this.save()}removeModelThinkingLevel(e,t){this.globalSettings.modelThinkingLevels&&(delete this.globalSettings.modelThinkingLevels[`${e}/${t}`],Object.keys(this.globalSettings.modelThinkingLevels).length===0&&delete this.globalSettings.modelThinkingLevels,this.markModified("modelThinkingLevels"),this.save())}getTransport(){return this.settings.transport??l.transport}setTransport(e){this.globalSettings.transport=e,this.markModified("transport"),this.save()}getSessionShareDestination(){const e=this.settings.sessionShareDestination;return e==="gist"||e==="radius"?e:l.sessionShareDestination}setSessionShareDestination(e){this.globalSettings.sessionShareDestination=e,this.markModified("sessionShareDestination"),this.save()}getCompactionEnabled(){return this.settings.compaction?.enabled??l.compaction.enabled}setCompactionEnabled(e){this.globalSettings.compaction||(this.globalSettings.compaction={}),this.globalSettings.compaction.enabled=e,this.markModified("compaction","enabled"),this.save()}getCompactionTokenSetting(e,t){const s=this.settings.compaction,i=s?.[e];if(i!==void 0&&(typeof i!="number"||!Number.isSafeInteger(i)||i<0))throw new Error(`Invalid compaction.${e} setting: ${String(i)}. Expected a non-negative safe integer.`);const o=t?`${t.provider}/${t.id}`:void 0,n=o!==void 0?s?.modelOverrides?.[o]:void 0;if(n!==void 0&&!y(n))throw new Error(`Invalid compaction.modelOverrides["${o}"] setting: ${String(n)}. Expected an object.`);const a=n?.[e];if(a!==void 0&&(typeof a!="number"||!Number.isSafeInteger(a)||a<0))throw new Error(`Invalid compaction.modelOverrides["${o}"].${e} setting: ${String(a)}. Expected a non-negative safe integer.`);return a??i??G[e]}getCompactionReserveTokens(e){return this.getCompactionTokenSetting("reserveTokens",e)}getCompactionKeepRecentTokens(e){return this.getCompactionTokenSetting("keepRecentTokens",e)}getCompactionSettings(e){return{enabled:this.getCompactionEnabled(),reserveTokens:this.getCompactionReserveTokens(e),keepRecentTokens:this.getCompactionKeepRecentTokens(e),maxContextTokens:this.getCompactionMaxContextTokens(e),pruneToolOutputs:this.getCompactionPruneToolOutputs()}}getCompactionMaxContextTokens(e){return this.getCompactionTokenSetting("maxContextTokens",e)}getCompactionPruneToolOutputs(){const e=this.settings.compaction?.pruneToolOutputs;if(e!==void 0&&typeof e!="boolean")throw new Error(`Invalid compaction.pruneToolOutputs setting: ${String(e)}. Expected a boolean.`);return e??!0}getCompactionSummaryModel(){const e=this.settings.compaction?.summaryModel;if(e===void 0||e==="")return;const t=typeof e=="string"?e.indexOf("/"):-1;if(typeof e!="string"||t<=0||t===e.length-1)throw new Error(`Invalid compaction.summaryModel setting: ${String(e)}. Expected "provider/modelId".`);return{provider:e.slice(0,t),modelId:e.slice(t+1)}}getBranchSummarySettings(){return{reserveTokens:this.settings.branchSummary?.reserveTokens??l.branchSummary.reserveTokens,skipPrompt:this.settings.branchSummary?.skipPrompt??l.branchSummary.skipPrompt}}getBranchSummarySkipPrompt(){return this.settings.branchSummary?.skipPrompt??l.branchSummary.skipPrompt}getRetryEnabled(){return this.settings.retry?.enabled??l.retry.enabled}setRetryEnabled(e){this.globalSettings.retry||(this.globalSettings.retry={}),this.globalSettings.retry.enabled=e,this.markModified("retry","enabled"),this.save()}getRetrySettings(){return{enabled:this.getRetryEnabled(),maxRetries:this.settings.retry?.maxRetries??z,baseDelayMs:this.settings.retry?.baseDelayMs??2e3,maxAgentDelayMs:this.settings.retry?.maxAgentDelayMs??D}}getMaxOutputTokens(){const e=this.settings.maxOutputTokens;if(e===void 0)return K;if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new Error(`Invalid maxOutputTokens setting: ${String(e)}. Expected a non-negative safe integer.`);return e}getOutputTokenLimit(e){const t=this.getMaxOutputTokens();return t>0&&(e<=0||e>t)?t:e}getHttpIdleTimeoutMs(){return F(this.settings.httpIdleTimeoutMs,"httpIdleTimeoutMs")??B}setHttpIdleTimeoutMs(e){if(!Number.isFinite(e)||e<0)throw new Error(`Invalid httpIdleTimeoutMs setting: ${String(e)}`);this.globalSettings.httpIdleTimeoutMs=Math.floor(e),this.markModified("httpIdleTimeoutMs"),this.save()}getCacheWarmingMode(){const e=this.globalSettings.cacheWarming;return e!==void 0&&Q.includes(e)?e:l.cacheWarming}setCacheWarmingMode(e){this.globalSettings.cacheWarming=e,this.markModified("cacheWarming"),this.save()}getProviderRetrySettings(){return{timeoutMs:this.settings.retry?.provider?.timeoutMs,maxRetries:this.settings.retry?.provider?.maxRetries,maxRetryDelayMs:this.settings.retry?.provider?.maxRetryDelayMs??l.retry.provider.maxRetryDelayMs}}getWebSocketConnectTimeoutMs(){return F(this.settings.websocketConnectTimeoutMs,"websocketConnectTimeoutMs")}getHideThinkingBlock(){return this.settings.hideThinkingBlock??!0}getShowCacheMissNotices(){return this.settings.showCacheMissNotices??l.showCacheMissNotices}getExternalEditorCommand(){const e=this.settings.externalEditor;if(typeof e=="string"&&e.trim()!=="")return e;const t=process.env.VISUAL||process.env.EDITOR;return t||(process.platform==="win32"?"notepad":"nano")}setHideThinkingBlock(e){this.globalSettings.hideThinkingBlock=e,this.markModified("hideThinkingBlock"),this.save()}setShowCacheMissNotices(e){this.globalSettings.showCacheMissNotices=e,this.markModified("showCacheMissNotices"),this.save()}getShellPath(){const e=this.settings.shellPath;return e&&C(e)}setShellPath(e){this.globalSettings.shellPath=e,this.markModified("shellPath"),this.save()}getQuietStartup(){const e=this.settings.quietStartup;return e===!1?!1:e==="header"?e:!0}setQuietStartup(e){this.globalSettings.quietStartup=e,this.markModified("quietStartup"),this.save()}getDefaultProjectTrust(){const e=this.globalSettings.defaultProjectTrust;return e==="always"||e==="never"?e:l.defaultProjectTrust}setDefaultProjectTrust(e){this.globalSettings.defaultProjectTrust=e,this.markModified("defaultProjectTrust"),this.save()}getShellCommandPrefix(){return this.settings.shellCommandPrefix}getShellEnvironmentPolicy(){const e=this.globalSettings.shellEnvironment??{},t=[...e.exclude??[],...this.projectSettings.shellEnvironment?.exclude??[]];return{...e.inherit!==void 0?{inherit:e.inherit}:{},...t.length>0?{exclude:t}:{},...e.include!==void 0?{include:[...e.include]}:{},...e.set!==void 0?{set:{...e.set}}:{}}}getPermissionRuleSources(){return{...this.globalSettings.permissions?{user:structuredClone(this.globalSettings.permissions)}:{},...this.projectSettings.permissions?{project:structuredClone(this.projectSettings.permissions)}:{}}}getSandboxSettingsSources(){return{...this.globalSettings.sandbox?{global:structuredClone(this.globalSettings.sandbox)}:{},...this.projectSettings.sandbox?{project:structuredClone(this.projectSettings.sandbox)}:{}}}setShellCommandPrefix(e){this.globalSettings.shellCommandPrefix=e,this.markModified("shellCommandPrefix"),this.save()}getNpmCommand(){return this.settings.npmCommand?[...this.settings.npmCommand]:void 0}setNpmCommand(e){this.globalSettings.npmCommand=e?[...e]:void 0,this.markModified("npmCommand"),this.save()}getCollapseChangelog(){return this.settings.collapseChangelog??!0}setCollapseChangelog(e){this.globalSettings.collapseChangelog=e,this.markModified("collapseChangelog"),this.save()}getEnableInstallTelemetry(){return this.settings.enableInstallTelemetry??l.enableInstallTelemetry}setEnableInstallTelemetry(e){this.globalSettings.enableInstallTelemetry=e,this.markModified("enableInstallTelemetry"),this.save()}getOrCreateDeviceId(){return this.globalSettings.deviceId||(this.globalSettings.deviceId=A(),this.markModified("deviceId"),this.save()),this.globalSettings.deviceId}getPackages(){return[...this.settings.packages??[]]}setPackages(e){this.globalSettings.packages=e,this.markModified("packages"),this.save()}setProjectPackages(e){this.updateProjectSettings("packages",t=>{t.packages=e})}getExtensionPaths(){return[...this.settings.extensions??[]]}setExtensionPaths(e){this.globalSettings.extensions=e,this.markModified("extensions"),this.save()}setProjectExtensionPaths(e){this.updateProjectSettings("extensions",t=>{t.extensions=e})}getSkillPaths(){return[...this.settings.skills??[]]}setSkillPaths(e){this.globalSettings.skills=e,this.markModified("skills"),this.save()}setProjectSkillPaths(e){this.updateProjectSettings("skills",t=>{t.skills=e})}getPromptTemplatePaths(){return[...this.settings.prompts??[]]}setPromptTemplatePaths(e){this.globalSettings.prompts=e,this.markModified("prompts"),this.save()}setProjectPromptTemplatePaths(e){this.updateProjectSettings("prompts",t=>{t.prompts=e})}getThemePaths(){return[...this.settings.themes??[]]}setThemePaths(e){this.globalSettings.themes=e,this.markModified("themes"),this.save()}setProjectThemePaths(e){this.updateProjectSettings("themes",t=>{t.themes=e})}getEnableSkillCommands(){return this.settings.enableSkillCommands??l.enableSkillCommands}setEnableSkillCommands(e){this.globalSettings.enableSkillCommands=e,this.markModified("enableSkillCommands"),this.save()}getFactoryEnabled(){return this.settings.factoryEnabled??!0}setFactoryEnabled(e){this.globalSettings.factoryEnabled=e,this.markModified("factoryEnabled"),this.save()}getThinkingBudgets(){return this.settings.thinkingBudgets}getTerminalCapabilityOverrides(){const e=this.settings.terminal,t=e?.images;return{...t==="kitty"||t==="iterm2"?{images:t}:t===!1?{images:null}:{},...typeof e?.trueColor=="boolean"?{trueColor:e.trueColor}:{},...typeof e?.hyperlinks=="boolean"?{hyperlinks:e.hyperlinks}:{}}}getShowImages(){return this.settings.terminal?.showImages??l.terminal.showImages}setShowImages(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showImages=e,this.markModified("terminal","showImages"),this.save()}getImageWidthCells(){const e=this.settings.terminal?.imageWidthCells;return typeof e!="number"||!Number.isFinite(e)?l.terminal.imageWidthCells:Math.max(1,Math.floor(e))}setImageWidthCells(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.imageWidthCells=Math.max(1,Math.floor(e)),this.markModified("terminal","imageWidthCells"),this.save()}getClearOnShrink(){return this.settings.terminal?.clearOnShrink!==void 0?this.settings.terminal.clearOnShrink:process.env.PI_CLEAR_ON_SHRINK==="1"?!0:l.terminal.clearOnShrink}setClearOnShrink(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.clearOnShrink=e,this.markModified("terminal","clearOnShrink"),this.save()}getShowTerminalProgress(){return this.settings.terminal?.showTerminalProgress??l.terminal.showTerminalProgress}setShowTerminalProgress(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showTerminalProgress=e,this.markModified("terminal","showTerminalProgress"),this.save()}getTuiMode(){return this.settings.tuiMode==="fullscreen"?"fullscreen":(this.settings.tuiMode==="regular"||this.settings.tuiMode,"regular")}setTuiMode(e){this.globalSettings.tuiMode=e,this.markModified("tuiMode"),this.save()}getFullscreenExitOutput(){return this.settings.fullscreenExitOutput==="resume-hint"?"resume-hint":l.fullscreenExitOutput}setFullscreenExitOutput(e){this.globalSettings.fullscreenExitOutput=e,this.markModified("fullscreenExitOutput"),this.save()}getFullscreenScrollbar(){const e=this.settings.fullscreenScrollbar;return e==="always"||e==="hidden"?e:l.fullscreenScrollbar}setFullscreenScrollbar(e){this.globalSettings.fullscreenScrollbar=e,this.markModified("fullscreenScrollbar"),this.save()}getFullscreenCopyOnSelect(){return this.settings.fullscreenCopyOnSelect??l.fullscreenCopyOnSelect}setFullscreenCopyOnSelect(e){this.globalSettings.fullscreenCopyOnSelect=e,this.markModified("fullscreenCopyOnSelect"),this.save()}getFullscreenWheelScrollLines(){const e=this.settings.fullscreenWheelScrollLines;return typeof e=="number"&&Number.isFinite(e)?Math.max(1,Math.min(100,Math.floor(e))):l.fullscreenWheelScrollLines}setFullscreenWheelScrollLines(e){this.globalSettings.fullscreenWheelScrollLines=e==="auto"?e:Math.max(1,Math.min(100,Math.floor(e))),this.markModified("fullscreenWheelScrollLines"),this.save()}getImageAutoResize(){return this.settings.images?.autoResize??l.images.autoResize}setImageAutoResize(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.autoResize=e,this.markModified("images","autoResize"),this.save()}getBlockImages(){return this.settings.images?.blockImages??l.images.blockImages}setBlockImages(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.blockImages=e,this.markModified("images","blockImages"),this.save()}getEnabledModels(){return this.settings.enabledModels}getDefaultTools(){const e=this.settings.defaultTools;if(e!==void 0)return ee(Array.isArray(e)?e.filter(t=>typeof t=="string"):[])}setEnabledModels(e){this.globalSettings.enabledModels=e,this.markModified("enabledModels"),this.save()}getDoubleEscapeAction(){return this.settings.doubleEscapeAction??l.doubleEscapeAction}setDoubleEscapeAction(e){this.globalSettings.doubleEscapeAction=e,this.markModified("doubleEscapeAction"),this.save()}getTreeFilterMode(){const e=this.settings.treeFilterMode;return e&&["default","no-tools","user-only","labeled-only","all"].includes(e)?e:l.treeFilterMode}setTreeFilterMode(e){this.globalSettings.treeFilterMode=e,this.markModified("treeFilterMode"),this.save()}getShowHardwareCursor(){return this.settings.showHardwareCursor??process.env.PI_HARDWARE_CURSOR==="1"}setShowHardwareCursor(e){this.globalSettings.showHardwareCursor=e,this.markModified("showHardwareCursor"),this.save()}getEditorPaddingX(){return this.settings.editorPaddingX??1}setEditorPaddingX(e){this.globalSettings.editorPaddingX=Math.max(0,Math.min(3,Math.floor(e))),this.markModified("editorPaddingX"),this.save()}getOutputPad(){return this.settings.outputPad===1?1:0}setOutputPad(e){this.globalSettings.outputPad=e,this.markModified("outputPad"),this.save()}getAutocompleteMaxVisible(){return this.settings.autocompleteMaxVisible??l.autocompleteMaxVisible}setAutocompleteMaxVisible(e){this.globalSettings.autocompleteMaxVisible=Math.max(3,Math.min(20,Math.floor(e))),this.markModified("autocompleteMaxVisible"),this.save()}getCodeBlockIndent(){return this.settings.markdown?.codeBlockIndent??l.markdown.codeBlockIndent}getMermaidRenderingMode(){const e=this.settings.markdown?.mermaid;return e==="off"||e==="final"?e:l.markdown.mermaid}setMermaidRenderingMode(e){this.globalSettings.markdown??={},this.globalSettings.markdown.mermaid=e,this.markModified("markdown","mermaid"),this.save()}getWarnings(){return{...this.settings.warnings??{}}}setWarnings(e){this.globalSettings.warnings={...e},this.markModified("warnings"),this.save()}}export{Q as CACHE_WARMING_MODES,X as DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS,K as DEFAULT_MAX_OUTPUT_TOKENS,z as DEFAULT_MAX_RETRIES,J as DEFAULT_TOOL_NAMES,se as FileSettingsStorage,ie as InMemorySettingsStorage,k as SETTINGS_FORMAT_VERSION,g as SettingsManager,Y as applyToolModifiers,pe as getToolListError,b as isToolModifier};
1
+ var D=Object.defineProperty;var d=(r,e)=>D(r,"name",{value:e,configurable:!0});import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS as N}from"@earendil-works/pi-ai";import{randomUUID as R}from"crypto";import{existsSync as w,mkdirSync as W,readFileSync as _}from"fs";import{dirname as U,join as f}from"path";import $ from"proper-lockfile";import{CONFIG_DIR_NAME as C,getAgentDir as H}from"../config.js";import{normalizePath as x,resolvePath as p}from"../utils/paths.js";import{stripBom as T}from"../utils/text.js";import{DEFAULT_FIRST_TOKEN_TIMEOUT_MS as B,DEFAULT_HTTP_IDLE_TIMEOUT_MS as V,parseHttpIdleTimeoutMs as F}from"./http-dispatcher.js";import{SETTINGS_DEFAULTS as l}from"./settings-defaults.js";import{declaredDataFormat as S,reportNewerDataFormat as q,writeFileAtomicSync as G}from"./shared-data.js";import{DEFAULT_STALL_WATCHDOG_MS as K}from"./stall-watchdog.js";const X=8e4,z={reserveTokens:16384,keepRecentTokens:2e4,maxContextTokens:X},Q=32e3,J=5,Y=["off","streaming","idle"];function y(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}d(y,"isMergeableObject");function L(r,e){const t={...r};for(const s of Object.keys(e)){const i=e[s];if(i===void 0)continue;const o=r[s];t[s]=y(o)&&y(i)?L(o,i):i}return t}d(L,"deepMergeObjects");const Z=["read","bash","edit","write"];function b(r){return typeof r=="string"&&(r.startsWith("+")||r.startsWith("-"))}d(b,"isToolModifier");function ke(r){const e=r.filter(b);if(e.length===0)return;if(e.length<r.length)return"tool names cannot be mixed with +name or -name entries";const t=e.find(s=>s.includes("*"));if(t)return`+name and -name entries take exact tool names, not patterns: ${t}`}d(ke,"getToolListError");function ee(r,e){const t=[...r];for(const s of e){if(!b(s))continue;const i=s.slice(1),o=t.indexOf(i);s.startsWith("+")&&o===-1&&i?t.push(i):s.startsWith("-")&&o!==-1&&t.splice(o,1)}return t}d(ee,"applyToolModifiers");function te(r,e){return e===void 0?r:!Array.isArray(r)||!Array.isArray(e)||!e.every(b)?e:[...r,...e]}d(te,"mergeDefaultTools");function se(r){const e=r.filter(t=>!b(t));return ee(e.length>0||r.length===0?e:Z,r)}d(se,"resolveDefaultTools");function c(r,e){const t=L(r,e),s=te(r.defaultTools,e.defaultTools);return s===void 0?t:{...t,defaultTools:s}}d(c,"deepMergeSettings");function k(r,e){const t=F(r);if(t!==void 0)return t;if(r!==void 0)throw new Error(`Invalid ${e} setting: ${String(r)}`)}d(k,"parseTimeoutSetting");const M=1,v=["enableAnalytics","trackingId"];function ie(r){let e;try{e=JSON.parse(T(r))}catch{return}if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e;if(!(S(t)>M)&&v.some(s=>s in t)){for(const s of v)delete t[s];return JSON.stringify(t,null,2)}}d(ie,"withoutRetiredKeys");function P(r,e,t){return{scope:r,...t?{path:t}:{},error:e instanceof Error?e:new Error(String(e))}}d(P,"toSettingsError");class re{static{d(this,"FileSettingsStorage")}globalSettingsPath;projectSettingsPath;constructor(e,t){const s=p(e),i=p(t);this.globalSettingsPath=f(i,"settings.json"),this.projectSettingsPath=f(s,C,"settings.json")}acquireLockSyncWithRetry(e){let i;for(let o=1;o<=100;o++)try{return $.lockSync(e,{realpath:!1})}catch(n){if((typeof n=="object"&&n!==null&&"code"in n?String(n.code):void 0)!=="ELOCKED"||o===100)throw n;i=n;const h=Date.now();for(;Date.now()-h<20;);}throw i??new Error("Failed to acquire settings lock")}withLock(e,t){const s=e==="global"?this.globalSettingsPath:this.projectSettingsPath,i=U(s);let o;try{const n=w(s);n&&(o=this.acquireLockSyncWithRetry(s));const a=n?_(s,"utf-8"):void 0,h=t(a);h!==void 0&&(w(i)||W(i,{recursive:!0}),o||(o=this.acquireLockSyncWithRetry(s)),G(s,h))}finally{o&&o()}}}class oe{static{d(this,"InMemorySettingsStorage")}global;project;withLock(e,t){const s=e==="global"?this.global:this.project,i=t(s);i!==void 0&&(e==="global"?this.global=i:this.project=i)}}class g{static{d(this,"SettingsManager")}storage;globalSettings;projectSettings;settings;projectTrusted;modifiedFields=new Set;modifiedNestedFields=new Map;modifiedProjectFields=new Set;modifiedProjectNestedFields=new Map;globalSettingsLoadError=null;projectSettingsLoadError=null;writeQueue=Promise.resolve();errors;settingsPaths;constructor(e,t,s,i=null,o=null,n=[],a=!0,h={}){this.storage=e,this.globalSettings=t,this.projectSettings=s,this.projectTrusted=a,this.globalSettingsLoadError=i,this.projectSettingsLoadError=o,this.errors=[...n],this.settingsPaths=h,this.settings=c(this.globalSettings,this.projectSettings),this.reportNewerFormatScopes()}static create(e,t=H(),s={}){const i=p(e),o=p(t),n=new re(i,o);return g.fromStorageWithPaths(n,s,{global:f(o,"settings.json"),project:f(i,C,"settings.json")})}static fromStorage(e,t={}){return g.fromStorageWithPaths(e,t)}static fromStorageWithPaths(e,t,s={}){const i=t.projectTrusted??!0,o=g.tryLoadFromStorage(e,"global"),n=g.tryLoadFromStorage(e,"project",i),a=[];return o.error&&a.push(P("global",o.error,s.global)),n.error&&a.push(P("project",n.error,s.project)),new g(e,o.settings,n.settings,o.error,n.error,a,i,s)}static inMemory(e={},t={}){const s=new oe,i=g.migrateSettings(structuredClone(e));return s.withLock("global",()=>JSON.stringify(i,null,2)),g.fromStorage(s,t)}static loadFromStorage(e,t,s=!0){if(t==="project"&&!s)return{};let i;if(e.withLock(t,n=>(i=n,t==="global"&&n?ie(n):void 0)),!i)return{};const o=JSON.parse(T(i));return g.migrateSettings(o)}static tryLoadFromStorage(e,t,s=!0){try{return{settings:g.loadFromStorage(e,t,s),error:null}}catch(i){return{settings:{},error:i}}}static migrateSettings(e){for(const t of v)delete e[t];if("queueMode"in e&&!("steeringMode"in e)&&(e.steeringMode=e.queueMode,delete e.queueMode),!("transport"in e)&&typeof e.websockets=="boolean"&&(e.transport=e.websockets?"websocket":"sse",delete e.websockets),"skills"in e&&typeof e.skills=="object"&&e.skills!==null&&!Array.isArray(e.skills)){const t=e.skills;t.enableSkillCommands!==void 0&&e.enableSkillCommands===void 0&&(e.enableSkillCommands=t.enableSkillCommands),Array.isArray(t.customDirectories)&&t.customDirectories.length>0?e.skills=t.customDirectories:delete e.skills}if("retry"in e&&typeof e.retry=="object"&&e.retry!==null&&!Array.isArray(e.retry)){const t=e.retry,s=typeof t.provider=="object"&&t.provider!==null?t.provider:void 0;typeof t.maxDelayMs=="number"&&(s?.maxRetryDelayMs===void 0||s?.maxRetryDelayMs===null)&&(t.provider={...s??{},maxRetryDelayMs:t.maxDelayMs}),delete t.maxDelayMs}return e}getSettings(){return structuredClone(this.settings)}getGlobalSettings(){return structuredClone(this.globalSettings)}getProjectSettings(){return structuredClone(this.projectSettings)}isProjectTrusted(){return this.projectTrusted}setProjectTrusted(e){if(this.projectTrusted===e)return;if(this.projectTrusted=e,this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear(),!e){this.projectSettings={},this.projectSettingsLoadError=null,this.settings=c(this.globalSettings,this.projectSettings);return}const t=g.tryLoadFromStorage(this.storage,"project",e);this.projectSettings=t.settings,this.projectSettingsLoadError=t.error,t.error&&this.recordError("project",t.error),this.settings=c(this.globalSettings,this.projectSettings)}async reload(){await this.writeQueue;const e=g.tryLoadFromStorage(this.storage,"global");e.error?(this.globalSettingsLoadError=e.error,this.recordError("global",e.error)):(this.globalSettings=e.settings,this.globalSettingsLoadError=null),this.modifiedFields.clear(),this.modifiedNestedFields.clear(),this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear();const t=g.tryLoadFromStorage(this.storage,"project",this.projectTrusted);t.error?(this.projectSettingsLoadError=t.error,this.recordError("project",t.error)):(this.projectSettings=t.settings,this.projectSettingsLoadError=null),this.settings=c(this.globalSettings,this.projectSettings),this.reportNewerFormatScopes()}applyOverrides(e){this.settings=c(this.settings,e)}markModified(e,t){this.modifiedFields.add(e),t&&(this.modifiedNestedFields.has(e)||this.modifiedNestedFields.set(e,new Set),this.modifiedNestedFields.get(e).add(t))}markProjectModified(e,t){this.modifiedProjectFields.add(e),t&&(this.modifiedProjectNestedFields.has(e)||this.modifiedProjectNestedFields.set(e,new Set),this.modifiedProjectNestedFields.get(e).add(t))}assertProjectTrustedForWrite(){if(!this.projectTrusted)throw new Error("Project is not trusted; refusing to write project settings")}reportNewerFormat(e){q(this.settingsPaths[e]??`${e} settings.json`)}reportNewerFormatScopes(){S(this.globalSettings)>M&&this.reportNewerFormat("global"),S(this.projectSettings)>M&&this.reportNewerFormat("project")}recordError(e,t){this.errors.push(P(e,t,this.settingsPaths[e]))}clearModifiedScope(e){if(e==="global"){this.modifiedFields.clear(),this.modifiedNestedFields.clear();return}this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear()}enqueueWrite(e,t){this.writeQueue=this.writeQueue.then(()=>{e==="project"&&this.assertProjectTrustedForWrite(),t(),this.clearModifiedScope(e)}).catch(s=>{this.recordError(e,s)})}cloneModifiedNestedFields(e){const t=new Map;for(const[s,i]of e.entries())t.set(s,new Set(i));return t}persistScopedSettings(e,t,s,i){this.storage.withLock(e,o=>{const n=o?JSON.parse(T(o)):{};if(S(n)>M){this.reportNewerFormat(e);return}const a=o?g.migrateSettings(n):{},h={...a};for(const u of s){const m=t[u];if(i.has(u)&&typeof m=="object"&&m!==null){const I=i.get(u),O=a[u]??{},A=m,j={...O};for(const E of I)j[E]=A[E];h[u]=j}else h[u]=m}return JSON.stringify(h,null,2)})}save(){if(this.settings=c(this.globalSettings,this.projectSettings),this.globalSettingsLoadError)return;const e=structuredClone(this.globalSettings),t=new Set(this.modifiedFields),s=this.cloneModifiedNestedFields(this.modifiedNestedFields);this.enqueueWrite("global",()=>{this.persistScopedSettings("global",e,t,s)})}saveProjectSettings(e){if(this.assertProjectTrustedForWrite(),this.projectSettings=structuredClone(e),this.settings=c(this.globalSettings,this.projectSettings),this.projectSettingsLoadError)return;const t=structuredClone(this.projectSettings),s=new Set(this.modifiedProjectFields),i=this.cloneModifiedNestedFields(this.modifiedProjectNestedFields);this.enqueueWrite("project",()=>{this.persistScopedSettings("project",t,s,i)})}updateProjectSettings(e,t){this.assertProjectTrustedForWrite();const s=structuredClone(this.projectSettings);t(s),this.markProjectModified(e),this.saveProjectSettings(s)}async flush(){await this.writeQueue}drainErrors(){const e=[...this.errors];return this.errors=[],e}getLastChangelogVersion(){return this.settings.lastChangelogVersion}setLastChangelogVersion(e){this.globalSettings.lastChangelogVersion=e,this.markModified("lastChangelogVersion"),this.save()}getSessionDir(){const e=this.settings.sessionDir;return e&&x(e)}getDefaultProvider(){return this.settings.defaultProvider}getDefaultModel(){return this.settings.defaultModel}setDefaultProvider(e){this.globalSettings.defaultProvider=e,this.markModified("defaultProvider"),this.save()}setDefaultModel(e){this.globalSettings.defaultModel=e,this.markModified("defaultModel"),this.save()}setDefaultModelAndProvider(e,t){this.globalSettings.defaultProvider=e,this.globalSettings.defaultModel=t,this.markModified("defaultProvider"),this.markModified("defaultModel"),this.save()}getSteeringMode(){return this.settings.steeringMode||l.steeringMode}setSteeringMode(e){this.globalSettings.steeringMode=e,this.markModified("steeringMode"),this.save()}getFollowUpMode(){return this.settings.followUpMode||l.followUpMode}setFollowUpMode(e){this.globalSettings.followUpMode=e,this.markModified("followUpMode"),this.save()}getThemeSetting(){const e=this.settings.theme;if(typeof e=="string")return e}getTheme(){const e=this.getThemeSetting();return e?.includes("/")?void 0:e}setTheme(e){this.globalSettings.theme=e,this.markModified("theme"),this.save()}getDefaultThinkingLevel(){return this.settings.defaultThinkingLevel}setDefaultThinkingLevel(e){this.globalSettings.defaultThinkingLevel=e,this.markModified("defaultThinkingLevel"),this.save()}getModelThinkingLevel(e,t){return this.settings.modelThinkingLevels?.[`${e}/${t}`]}getAllModelThinkingLevels(){return{...this.settings.modelThinkingLevels??{}}}setModelThinkingLevel(e,t,s){this.globalSettings.modelThinkingLevels||(this.globalSettings.modelThinkingLevels={}),this.globalSettings.modelThinkingLevels[`${e}/${t}`]=s,this.markModified("modelThinkingLevels"),this.save()}removeModelThinkingLevel(e,t){this.globalSettings.modelThinkingLevels&&(delete this.globalSettings.modelThinkingLevels[`${e}/${t}`],Object.keys(this.globalSettings.modelThinkingLevels).length===0&&delete this.globalSettings.modelThinkingLevels,this.markModified("modelThinkingLevels"),this.save())}getTransport(){return this.settings.transport??l.transport}setTransport(e){this.globalSettings.transport=e,this.markModified("transport"),this.save()}getSessionShareDestination(){const e=this.settings.sessionShareDestination;return e==="gist"||e==="radius"?e:l.sessionShareDestination}setSessionShareDestination(e){this.globalSettings.sessionShareDestination=e,this.markModified("sessionShareDestination"),this.save()}getCompactionEnabled(){return this.settings.compaction?.enabled??l.compaction.enabled}setCompactionEnabled(e){this.globalSettings.compaction||(this.globalSettings.compaction={}),this.globalSettings.compaction.enabled=e,this.markModified("compaction","enabled"),this.save()}getCompactionTokenSetting(e,t){const s=this.settings.compaction,i=s?.[e];if(i!==void 0&&(typeof i!="number"||!Number.isSafeInteger(i)||i<0))throw new Error(`Invalid compaction.${e} setting: ${String(i)}. Expected a non-negative safe integer.`);const o=t?`${t.provider}/${t.id}`:void 0,n=o!==void 0?s?.modelOverrides?.[o]:void 0;if(n!==void 0&&!y(n))throw new Error(`Invalid compaction.modelOverrides["${o}"] setting: ${String(n)}. Expected an object.`);const a=n?.[e];if(a!==void 0&&(typeof a!="number"||!Number.isSafeInteger(a)||a<0))throw new Error(`Invalid compaction.modelOverrides["${o}"].${e} setting: ${String(a)}. Expected a non-negative safe integer.`);return a??i??z[e]}getCompactionReserveTokens(e){return this.getCompactionTokenSetting("reserveTokens",e)}getCompactionKeepRecentTokens(e){return this.getCompactionTokenSetting("keepRecentTokens",e)}getCompactionSettings(e){return{enabled:this.getCompactionEnabled(),reserveTokens:this.getCompactionReserveTokens(e),keepRecentTokens:this.getCompactionKeepRecentTokens(e),maxContextTokens:this.getCompactionMaxContextTokens(e),pruneToolOutputs:this.getCompactionPruneToolOutputs()}}getCompactionMaxContextTokens(e){return this.getCompactionTokenSetting("maxContextTokens",e)}getCompactionPruneToolOutputs(){const e=this.settings.compaction?.pruneToolOutputs;if(e!==void 0&&typeof e!="boolean")throw new Error(`Invalid compaction.pruneToolOutputs setting: ${String(e)}. Expected a boolean.`);return e??!0}getCompactionSummaryModel(){const e=this.settings.compaction?.summaryModel;if(e===void 0||e==="")return;const t=typeof e=="string"?e.indexOf("/"):-1;if(typeof e!="string"||t<=0||t===e.length-1)throw new Error(`Invalid compaction.summaryModel setting: ${String(e)}. Expected "provider/modelId".`);return{provider:e.slice(0,t),modelId:e.slice(t+1)}}getBranchSummarySettings(){return{reserveTokens:this.settings.branchSummary?.reserveTokens??l.branchSummary.reserveTokens,skipPrompt:this.settings.branchSummary?.skipPrompt??l.branchSummary.skipPrompt}}getBranchSummarySkipPrompt(){return this.settings.branchSummary?.skipPrompt??l.branchSummary.skipPrompt}getRetryEnabled(){return this.settings.retry?.enabled??l.retry.enabled}setRetryEnabled(e){this.globalSettings.retry||(this.globalSettings.retry={}),this.globalSettings.retry.enabled=e,this.markModified("retry","enabled"),this.save()}getRetrySettings(){return{enabled:this.getRetryEnabled(),maxRetries:this.settings.retry?.maxRetries??J,baseDelayMs:this.settings.retry?.baseDelayMs??2e3,maxAgentDelayMs:this.settings.retry?.maxAgentDelayMs??N}}getMaxOutputTokens(){const e=this.settings.maxOutputTokens;if(e===void 0)return Q;if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new Error(`Invalid maxOutputTokens setting: ${String(e)}. Expected a non-negative safe integer.`);return e}getOutputTokenLimit(e){const t=this.getMaxOutputTokens();return t>0&&(e<=0||e>t)?t:e}getStallWatchdogMs(){const e=F(process.env.DAL_STALL_WATCHDOG_MS);return e!==void 0?e:k(this.settings.stallWatchdogMs,"stallWatchdogMs")??K}getHttpIdleTimeoutMs(){return k(this.settings.httpIdleTimeoutMs,"httpIdleTimeoutMs")??V}getFirstTokenTimeoutMs(){return k(this.settings.firstTokenTimeoutMs,"firstTokenTimeoutMs")??B}setHttpIdleTimeoutMs(e){if(!Number.isFinite(e)||e<0)throw new Error(`Invalid httpIdleTimeoutMs setting: ${String(e)}`);this.globalSettings.httpIdleTimeoutMs=Math.floor(e),this.markModified("httpIdleTimeoutMs"),this.save()}getCacheWarmingMode(){const e=this.globalSettings.cacheWarming;return e!==void 0&&Y.includes(e)?e:l.cacheWarming}setCacheWarmingMode(e){this.globalSettings.cacheWarming=e,this.markModified("cacheWarming"),this.save()}getProviderRetrySettings(){return{timeoutMs:this.settings.retry?.provider?.timeoutMs,maxRetries:this.settings.retry?.provider?.maxRetries,maxRetryDelayMs:this.settings.retry?.provider?.maxRetryDelayMs??l.retry.provider.maxRetryDelayMs}}getWebSocketConnectTimeoutMs(){return k(this.settings.websocketConnectTimeoutMs,"websocketConnectTimeoutMs")}getHideThinkingBlock(){return this.settings.hideThinkingBlock??!0}getShowCacheMissNotices(){return this.settings.showCacheMissNotices??l.showCacheMissNotices}getExternalEditorCommand(){const e=this.settings.externalEditor;if(typeof e=="string"&&e.trim()!=="")return e;const t=process.env.VISUAL||process.env.EDITOR;return t||(process.platform==="win32"?"notepad":"nano")}setHideThinkingBlock(e){this.globalSettings.hideThinkingBlock=e,this.markModified("hideThinkingBlock"),this.save()}setShowCacheMissNotices(e){this.globalSettings.showCacheMissNotices=e,this.markModified("showCacheMissNotices"),this.save()}getShellPath(){const e=this.settings.shellPath;return e&&x(e)}setShellPath(e){this.globalSettings.shellPath=e,this.markModified("shellPath"),this.save()}getQuietStartup(){const e=this.settings.quietStartup;return e===!1?!1:e==="header"?e:!0}setQuietStartup(e){this.globalSettings.quietStartup=e,this.markModified("quietStartup"),this.save()}getDefaultProjectTrust(){const e=this.globalSettings.defaultProjectTrust;return e==="always"||e==="never"?e:l.defaultProjectTrust}setDefaultProjectTrust(e){this.globalSettings.defaultProjectTrust=e,this.markModified("defaultProjectTrust"),this.save()}getShellCommandPrefix(){return this.settings.shellCommandPrefix}getShellEnvironmentPolicy(){const e=this.globalSettings.shellEnvironment??{},t=[...e.exclude??[],...this.projectSettings.shellEnvironment?.exclude??[]];return{...e.inherit!==void 0?{inherit:e.inherit}:{},...t.length>0?{exclude:t}:{},...e.include!==void 0?{include:[...e.include]}:{},...e.set!==void 0?{set:{...e.set}}:{}}}getPermissionRuleSources(){return{...this.globalSettings.permissions?{user:structuredClone(this.globalSettings.permissions)}:{},...this.projectSettings.permissions?{project:structuredClone(this.projectSettings.permissions)}:{}}}getSandboxSettingsSources(){return{...this.globalSettings.sandbox?{global:structuredClone(this.globalSettings.sandbox)}:{},...this.projectSettings.sandbox?{project:structuredClone(this.projectSettings.sandbox)}:{}}}setShellCommandPrefix(e){this.globalSettings.shellCommandPrefix=e,this.markModified("shellCommandPrefix"),this.save()}getNpmCommand(){return this.settings.npmCommand?[...this.settings.npmCommand]:void 0}setNpmCommand(e){this.globalSettings.npmCommand=e?[...e]:void 0,this.markModified("npmCommand"),this.save()}getCollapseChangelog(){return this.settings.collapseChangelog??!0}setCollapseChangelog(e){this.globalSettings.collapseChangelog=e,this.markModified("collapseChangelog"),this.save()}getEnableInstallTelemetry(){return this.settings.enableInstallTelemetry??l.enableInstallTelemetry}setEnableInstallTelemetry(e){this.globalSettings.enableInstallTelemetry=e,this.markModified("enableInstallTelemetry"),this.save()}getOrCreateDeviceId(){return this.globalSettings.deviceId||(this.globalSettings.deviceId=R(),this.markModified("deviceId"),this.save()),this.globalSettings.deviceId}getPackages(){return[...this.settings.packages??[]]}setPackages(e){this.globalSettings.packages=e,this.markModified("packages"),this.save()}setProjectPackages(e){this.updateProjectSettings("packages",t=>{t.packages=e})}getExtensionPaths(){return[...this.settings.extensions??[]]}setExtensionPaths(e){this.globalSettings.extensions=e,this.markModified("extensions"),this.save()}setProjectExtensionPaths(e){this.updateProjectSettings("extensions",t=>{t.extensions=e})}getSkillPaths(){return[...this.settings.skills??[]]}setSkillPaths(e){this.globalSettings.skills=e,this.markModified("skills"),this.save()}setProjectSkillPaths(e){this.updateProjectSettings("skills",t=>{t.skills=e})}getPromptTemplatePaths(){return[...this.settings.prompts??[]]}setPromptTemplatePaths(e){this.globalSettings.prompts=e,this.markModified("prompts"),this.save()}setProjectPromptTemplatePaths(e){this.updateProjectSettings("prompts",t=>{t.prompts=e})}getThemePaths(){return[...this.settings.themes??[]]}setThemePaths(e){this.globalSettings.themes=e,this.markModified("themes"),this.save()}setProjectThemePaths(e){this.updateProjectSettings("themes",t=>{t.themes=e})}getEnableSkillCommands(){return this.settings.enableSkillCommands??l.enableSkillCommands}setEnableSkillCommands(e){this.globalSettings.enableSkillCommands=e,this.markModified("enableSkillCommands"),this.save()}getFactoryEnabled(){return this.settings.factoryEnabled??!0}setFactoryEnabled(e){this.globalSettings.factoryEnabled=e,this.markModified("factoryEnabled"),this.save()}getThinkingBudgets(){return this.settings.thinkingBudgets}getTerminalCapabilityOverrides(){const e=this.settings.terminal,t=e?.images;return{...t==="kitty"||t==="iterm2"?{images:t}:t===!1?{images:null}:{},...typeof e?.trueColor=="boolean"?{trueColor:e.trueColor}:{},...typeof e?.hyperlinks=="boolean"?{hyperlinks:e.hyperlinks}:{}}}getShowImages(){return this.settings.terminal?.showImages??l.terminal.showImages}setShowImages(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showImages=e,this.markModified("terminal","showImages"),this.save()}getImageWidthCells(){const e=this.settings.terminal?.imageWidthCells;return typeof e!="number"||!Number.isFinite(e)?l.terminal.imageWidthCells:Math.max(1,Math.floor(e))}setImageWidthCells(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.imageWidthCells=Math.max(1,Math.floor(e)),this.markModified("terminal","imageWidthCells"),this.save()}getClearOnShrink(){return this.settings.terminal?.clearOnShrink!==void 0?this.settings.terminal.clearOnShrink:process.env.PI_CLEAR_ON_SHRINK==="1"?!0:l.terminal.clearOnShrink}setClearOnShrink(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.clearOnShrink=e,this.markModified("terminal","clearOnShrink"),this.save()}getShowTerminalProgress(){return this.settings.terminal?.showTerminalProgress??l.terminal.showTerminalProgress}setShowTerminalProgress(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showTerminalProgress=e,this.markModified("terminal","showTerminalProgress"),this.save()}getTuiMode(){return this.settings.tuiMode==="fullscreen"?"fullscreen":(this.settings.tuiMode==="regular"||this.settings.tuiMode,"regular")}setTuiMode(e){this.globalSettings.tuiMode=e,this.markModified("tuiMode"),this.save()}getFullscreenExitOutput(){return this.settings.fullscreenExitOutput==="resume-hint"?"resume-hint":l.fullscreenExitOutput}setFullscreenExitOutput(e){this.globalSettings.fullscreenExitOutput=e,this.markModified("fullscreenExitOutput"),this.save()}getFullscreenScrollbar(){const e=this.settings.fullscreenScrollbar;return e==="always"||e==="hidden"?e:l.fullscreenScrollbar}setFullscreenScrollbar(e){this.globalSettings.fullscreenScrollbar=e,this.markModified("fullscreenScrollbar"),this.save()}getFullscreenCopyOnSelect(){return this.settings.fullscreenCopyOnSelect??l.fullscreenCopyOnSelect}setFullscreenCopyOnSelect(e){this.globalSettings.fullscreenCopyOnSelect=e,this.markModified("fullscreenCopyOnSelect"),this.save()}getFullscreenWheelScrollLines(){const e=this.settings.fullscreenWheelScrollLines;return typeof e=="number"&&Number.isFinite(e)?Math.max(1,Math.min(100,Math.floor(e))):l.fullscreenWheelScrollLines}setFullscreenWheelScrollLines(e){this.globalSettings.fullscreenWheelScrollLines=e==="auto"?e:Math.max(1,Math.min(100,Math.floor(e))),this.markModified("fullscreenWheelScrollLines"),this.save()}getImageAutoResize(){return this.settings.images?.autoResize??l.images.autoResize}setImageAutoResize(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.autoResize=e,this.markModified("images","autoResize"),this.save()}getBlockImages(){return this.settings.images?.blockImages??l.images.blockImages}setBlockImages(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.blockImages=e,this.markModified("images","blockImages"),this.save()}getEnabledModels(){return this.settings.enabledModels}getDefaultTools(){const e=this.settings.defaultTools;if(e!==void 0)return se(Array.isArray(e)?e.filter(t=>typeof t=="string"):[])}setEnabledModels(e){this.globalSettings.enabledModels=e,this.markModified("enabledModels"),this.save()}getDoubleEscapeAction(){return this.settings.doubleEscapeAction??l.doubleEscapeAction}setDoubleEscapeAction(e){this.globalSettings.doubleEscapeAction=e,this.markModified("doubleEscapeAction"),this.save()}getTreeFilterMode(){const e=this.settings.treeFilterMode;return e&&["default","no-tools","user-only","labeled-only","all"].includes(e)?e:l.treeFilterMode}setTreeFilterMode(e){this.globalSettings.treeFilterMode=e,this.markModified("treeFilterMode"),this.save()}getShowHardwareCursor(){return this.settings.showHardwareCursor??process.env.PI_HARDWARE_CURSOR==="1"}setShowHardwareCursor(e){this.globalSettings.showHardwareCursor=e,this.markModified("showHardwareCursor"),this.save()}getEditorPaddingX(){return this.settings.editorPaddingX??1}setEditorPaddingX(e){this.globalSettings.editorPaddingX=Math.max(0,Math.min(3,Math.floor(e))),this.markModified("editorPaddingX"),this.save()}getOutputPad(){return this.settings.outputPad===1?1:0}setOutputPad(e){this.globalSettings.outputPad=e,this.markModified("outputPad"),this.save()}getAutocompleteMaxVisible(){return this.settings.autocompleteMaxVisible??l.autocompleteMaxVisible}setAutocompleteMaxVisible(e){this.globalSettings.autocompleteMaxVisible=Math.max(3,Math.min(20,Math.floor(e))),this.markModified("autocompleteMaxVisible"),this.save()}getCodeBlockIndent(){return this.settings.markdown?.codeBlockIndent??l.markdown.codeBlockIndent}getMermaidRenderingMode(){const e=this.settings.markdown?.mermaid;return e==="off"||e==="final"?e:l.markdown.mermaid}setMermaidRenderingMode(e){this.globalSettings.markdown??={},this.globalSettings.markdown.mermaid=e,this.markModified("markdown","mermaid"),this.save()}getWarnings(){return{...this.settings.warnings??{}}}setWarnings(e){this.globalSettings.warnings={...e},this.markModified("warnings"),this.save()}}export{Y as CACHE_WARMING_MODES,X as DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS,Q as DEFAULT_MAX_OUTPUT_TOKENS,J as DEFAULT_MAX_RETRIES,Z as DEFAULT_TOOL_NAMES,re as FileSettingsStorage,oe as InMemorySettingsStorage,M as SETTINGS_FORMAT_VERSION,g as SettingsManager,ee as applyToolModifiers,ke as getToolListError,b as isToolModifier};
@@ -179,6 +179,8 @@ export declare const SettingsSchema: Type.TObject<{
179
179
  sessionDir: Type.TOptional<Type.TString>;
180
180
  httpProxy: Type.TOptional<Type.TString>;
181
181
  httpIdleTimeoutMs: Type.TOptional<Type.TUnion<[Type.TNumber, Type.TLiteral<"disabled">]>>;
182
+ stallWatchdogMs: Type.TOptional<Type.TUnion<[Type.TNumber, Type.TLiteral<"disabled">]>>;
183
+ firstTokenTimeoutMs: Type.TOptional<Type.TUnion<[Type.TNumber, Type.TLiteral<"disabled">]>>;
182
184
  cacheWarming: Type.TOptional<Type.TUnion<[Type.TLiteral<"off">, Type.TLiteral<"streaming">, Type.TLiteral<"idle">]>>;
183
185
  websocketConnectTimeoutMs: Type.TOptional<Type.TUnion<[Type.TNumber, Type.TLiteral<"disabled">]>>;
184
186
  tuiMode: Type.TOptional<Type.TUnion<[Type.TLiteral<"regular">, Type.TLiteral<"fullscreen">]>>;