pi-better-server 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (597) hide show
  1. package/package.json +8 -1
  2. package/scripts/copy-pi-test-providers.mjs +10 -0
  3. package/scripts/event-publication/README.md +26 -0
  4. package/scripts/event-publication/commit.mjs +21 -0
  5. package/scripts/event-publication/measure.mjs +87 -0
  6. package/scripts/event-publication/writer.mjs +6 -0
  7. package/scripts/measure-full-runtime/frontend.ts +24 -0
  8. package/scripts/measure-full-runtime/hosted-extension.ts +28 -0
  9. package/scripts/measure-full-runtime/probe.mjs +29 -0
  10. package/scripts/measure-full-runtime/recovery-trace-loader.mjs +51 -0
  11. package/scripts/measure-full-runtime/recovery-trace.mjs +16 -0
  12. package/scripts/measure-full-runtime.mjs +146 -0
  13. package/scripts/measure-shared-reads/probe.mjs +26 -2
  14. package/scripts/measure-shared-reads.mjs +44 -9
  15. package/scripts/private-runtime/package-lock.json +66 -4
  16. package/scripts/private-runtime/package.json +10 -2
  17. package/scripts/source-provenance.mjs +31 -0
  18. package/scripts/test-on-pi.sh +3 -9
  19. package/src/handshake.ts +1 -1
  20. package/src/hosted-session.ts +32 -4
  21. package/src/maintenance.ts +35 -7
  22. package/src/registry.ts +28 -4
  23. package/src/runtime/attempt-invalidation.ts +54 -0
  24. package/src/runtime/background-history.ts +151 -45
  25. package/src/runtime/background-policy.ts +27 -0
  26. package/src/runtime/background-tools.ts +389 -0
  27. package/src/runtime/background.ts +410 -48
  28. package/src/runtime/cancellation.ts +28 -7
  29. package/src/runtime/catalog-sources.ts +199 -0
  30. package/src/runtime/catalog.ts +53 -21
  31. package/src/runtime/client.ts +22 -2
  32. package/src/runtime/domain/assignment-inbox.mjs +119 -0
  33. package/src/runtime/domain/assignment-observation.d.mts +1 -1
  34. package/src/runtime/domain/assignment-observation.mjs +71 -33
  35. package/src/runtime/domain/background/process-identity.mjs +20 -2
  36. package/src/runtime/domain/background/process.mjs +3 -3
  37. package/src/runtime/domain/background/registry.mjs +89 -4
  38. package/src/runtime/domain/background/types.mjs +1 -0
  39. package/src/runtime/domain/background-service/adapter-contract.domain.mjs +83 -0
  40. package/src/runtime/domain/background-service/adapter-contract.ts +70 -0
  41. package/src/runtime/domain/background-service/batch.domain.mjs +91 -0
  42. package/src/runtime/domain/background-service/batch.ts +111 -0
  43. package/src/runtime/domain/background-service/conditions.domain.mjs +94 -0
  44. package/src/runtime/domain/background-service/conditions.ts +99 -0
  45. package/src/runtime/domain/background-service/delivery-observer.domain.mjs +37 -0
  46. package/src/runtime/domain/background-service/delivery-observer.ts +42 -0
  47. package/src/runtime/domain/background-service/failures.domain.mjs +209 -0
  48. package/src/runtime/domain/background-service/failures.ts +212 -0
  49. package/src/runtime/domain/background-service/goal-provider.domain.mjs +193 -0
  50. package/src/runtime/domain/background-service/goal-provider.ts +209 -0
  51. package/src/runtime/domain/background-service/index.domain.mjs +54 -0
  52. package/src/runtime/domain/background-service/index.ts +55 -0
  53. package/src/runtime/domain/background-service/logs.domain.mjs +129 -0
  54. package/src/runtime/domain/background-service/logs.ts +134 -0
  55. package/src/runtime/domain/background-service/maintenance.domain.mjs +95 -0
  56. package/src/runtime/domain/background-service/maintenance.ts +98 -0
  57. package/src/runtime/domain/background-service/managed-authority.domain.mjs +32 -0
  58. package/src/runtime/domain/background-service/managed-authority.ts +30 -0
  59. package/src/runtime/domain/background-service/managed-client.domain.mjs +79 -0
  60. package/src/runtime/domain/background-service/managed-client.ts +73 -0
  61. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +225 -0
  62. package/src/runtime/domain/background-service/managed-frontend.ts +176 -0
  63. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +492 -0
  64. package/src/runtime/domain/background-service/navigator-provider.ts +485 -0
  65. package/src/runtime/domain/background-service/observed-wait-client.domain.mjs +6 -0
  66. package/src/runtime/domain/background-service/observed-wait-client.ts +10 -0
  67. package/src/runtime/domain/background-service/observed-waits.domain.mjs +4080 -0
  68. package/src/runtime/domain/background-service/observed-waits.ts +4513 -0
  69. package/src/runtime/domain/background-service/output.domain.mjs +867 -0
  70. package/src/runtime/domain/background-service/output.ts +952 -0
  71. package/src/runtime/domain/background-service/process-identity.domain.mjs +129 -0
  72. package/src/runtime/domain/background-service/process-identity.ts +134 -0
  73. package/src/runtime/domain/background-service/process.domain.mjs +512 -0
  74. package/src/runtime/domain/background-service/process.ts +532 -0
  75. package/src/runtime/domain/background-service/prompt.domain.mjs +58 -0
  76. package/src/runtime/domain/background-service/prompt.ts +72 -0
  77. package/src/runtime/domain/background-service/registry.domain.mjs +460 -0
  78. package/src/runtime/domain/background-service/registry.ts +450 -0
  79. package/src/runtime/domain/background-service/remote-task-preset.domain.mjs +67 -0
  80. package/src/runtime/domain/background-service/remote-task-preset.ts +127 -0
  81. package/src/runtime/domain/background-service/runtime.domain.mjs +1511 -0
  82. package/src/runtime/domain/background-service/runtime.ts +1636 -0
  83. package/src/runtime/domain/background-service/sandbox.domain.mjs +735 -0
  84. package/src/runtime/domain/background-service/sandbox.ts +913 -0
  85. package/src/runtime/domain/background-service/shared-callback-batcher.domain.mjs +777 -0
  86. package/src/runtime/domain/background-service/shared-callback-batcher.ts +956 -0
  87. package/src/runtime/domain/background-service/shared-execution-policy.domain.mjs +50 -0
  88. package/src/runtime/domain/background-service/shared-execution-policy.ts +61 -0
  89. package/src/runtime/domain/background-service/shared-failure-observations.domain.mjs +1078 -0
  90. package/src/runtime/domain/background-service/shared-failure-observations.ts +1166 -0
  91. package/src/runtime/domain/background-service/shared-harness-settings.domain.mjs +126 -0
  92. package/src/runtime/domain/background-service/shared-harness-settings.ts +116 -0
  93. package/src/runtime/domain/background-service/shared-log-utils.domain.mjs +1223 -0
  94. package/src/runtime/domain/background-service/shared-log-utils.ts +1492 -0
  95. package/src/runtime/domain/background-service/shared-navigator-panels.domain.mjs +289 -0
  96. package/src/runtime/domain/background-service/shared-navigator-panels.ts +272 -0
  97. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +1930 -0
  98. package/src/runtime/domain/background-service/shared-navigator.ts +1962 -0
  99. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  100. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +189 -0
  101. package/src/runtime/domain/background-service/shared-operation-coordinator/index.domain.mjs +51 -0
  102. package/src/runtime/domain/background-service/shared-operation-coordinator/index.ts +122 -0
  103. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  104. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  105. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +163 -0
  106. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +174 -0
  107. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-parent-callbacks.domain.mjs +66 -0
  108. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-parent-callbacks.ts +68 -0
  109. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.domain.mjs +87 -0
  110. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.ts +90 -0
  111. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +97 -0
  112. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +139 -0
  113. package/src/runtime/domain/background-service/shared-operation-coordinator/src/errors.domain.mjs +12 -0
  114. package/src/runtime/domain/background-service/shared-operation-coordinator/src/errors.ts +79 -0
  115. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +342 -0
  116. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +513 -0
  117. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +283 -0
  118. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +458 -0
  119. package/src/runtime/domain/background-service/shared-operation-coordinator/src/recovery.domain.mjs +52 -0
  120. package/src/runtime/domain/background-service/shared-operation-coordinator/src/recovery.ts +55 -0
  121. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +114 -0
  122. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +140 -0
  123. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.domain.mjs +280 -0
  124. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.ts +442 -0
  125. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +420 -0
  126. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +441 -0
  127. package/src/runtime/domain/background-service/shared-operation-coordinator/src/sqlite.domain.mjs +194 -0
  128. package/src/runtime/domain/background-service/shared-operation-coordinator/src/sqlite.ts +239 -0
  129. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +275 -0
  130. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +585 -0
  131. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.domain.mjs +120 -0
  132. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.ts +142 -0
  133. package/src/runtime/domain/background-service/shared-operation-coordinator/src/task-cancellation.domain.mjs +188 -0
  134. package/src/runtime/domain/background-service/shared-operation-coordinator/src/task-cancellation.ts +224 -0
  135. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.domain.mjs +25 -0
  136. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.ts +707 -0
  137. package/src/runtime/domain/background-service/shared-operation-coordinator/src/upgrade.domain.mjs +22 -0
  138. package/src/runtime/domain/background-service/shared-operation-coordinator/src/upgrade.ts +22 -0
  139. package/src/runtime/domain/background-service/shared-operation-coordinator/src/validate.domain.mjs +234 -0
  140. package/src/runtime/domain/background-service/shared-operation-coordinator/src/validate.ts +241 -0
  141. package/src/runtime/domain/background-service/shared-operation-coordinator/src/waits.domain.mjs +851 -0
  142. package/src/runtime/domain/background-service/shared-operation-coordinator/src/waits.ts +1424 -0
  143. package/src/runtime/domain/background-service/shared-permission-blocker.domain.mjs +40 -0
  144. package/src/runtime/domain/background-service/shared-permission-blocker.ts +48 -0
  145. package/src/runtime/domain/background-service/shared-render-scheduler.domain.mjs +41 -0
  146. package/src/runtime/domain/background-service/shared-render-scheduler.ts +47 -0
  147. package/src/runtime/domain/background-service/shared-sandbox-core.domain.mjs +1531 -0
  148. package/src/runtime/domain/background-service/shared-sandbox-core.ts +1757 -0
  149. package/src/runtime/domain/background-service/shared-sandbox-diagnostics.domain.mjs +591 -0
  150. package/src/runtime/domain/background-service/shared-sandbox-diagnostics.ts +491 -0
  151. package/src/runtime/domain/background-service/shared-ssh-core/index.domain.mjs +698 -0
  152. package/src/runtime/domain/background-service/shared-ssh-core/index.ts +979 -0
  153. package/src/runtime/domain/background-service/shared-stall-detector.domain.mjs +37 -0
  154. package/src/runtime/domain/background-service/shared-stall-detector.ts +69 -0
  155. package/src/runtime/domain/background-service/shared-work-client.mjs +303 -0
  156. package/src/runtime/domain/background-service/stall-attention.domain.mjs +29 -0
  157. package/src/runtime/domain/background-service/stall-attention.ts +31 -0
  158. package/src/runtime/domain/background-service/stall.domain.mjs +57 -0
  159. package/src/runtime/domain/background-service/stall.ts +57 -0
  160. package/src/runtime/domain/background-service/supervisor/README.md +111 -0
  161. package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +90 -0
  162. package/src/runtime/domain/background-service/supervisor/generated/conditions.mjs +96 -0
  163. package/src/runtime/domain/background-service/supervisor/generated/identity.mjs +95 -0
  164. package/src/runtime/domain/background-service/supervisor/generated/process-identity.mjs +131 -0
  165. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +514 -0
  166. package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +872 -0
  167. package/src/runtime/domain/background-service/supervisor/generated/store.mjs +609 -0
  168. package/src/runtime/domain/background-service/supervisor/generated/types.mjs +50 -0
  169. package/src/runtime/domain/background-service/supervisor/identity.domain.mjs +93 -0
  170. package/src/runtime/domain/background-service/supervisor/identity.ts +99 -0
  171. package/src/runtime/domain/background-service/supervisor/index.domain.mjs +22 -0
  172. package/src/runtime/domain/background-service/supervisor/index.ts +37 -0
  173. package/src/runtime/domain/background-service/supervisor/invocation.domain.mjs +30 -0
  174. package/src/runtime/domain/background-service/supervisor/invocation.ts +44 -0
  175. package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +870 -0
  176. package/src/runtime/domain/background-service/supervisor/runner.ts +982 -0
  177. package/src/runtime/domain/background-service/supervisor/store.domain.mjs +605 -0
  178. package/src/runtime/domain/background-service/supervisor/store.ts +651 -0
  179. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +721 -0
  180. package/src/runtime/domain/background-service/supervisor/supervisor.ts +804 -0
  181. package/src/runtime/domain/background-service/supervisor/types.domain.mjs +48 -0
  182. package/src/runtime/domain/background-service/supervisor/types.ts +394 -0
  183. package/src/runtime/domain/background-service/task-diagnostics.domain.mjs +60 -0
  184. package/src/runtime/domain/background-service/task-diagnostics.ts +71 -0
  185. package/src/runtime/domain/background-service/tools.domain.mjs +1050 -0
  186. package/src/runtime/domain/background-service/tools.ts +1142 -0
  187. package/src/runtime/domain/background-service/types.domain.mjs +5 -0
  188. package/src/runtime/domain/background-service/types.ts +236 -0
  189. package/src/runtime/domain/background-service/work-observation.domain.mjs +176 -0
  190. package/src/runtime/domain/background-service/work-observation.ts +144 -0
  191. package/src/runtime/domain/catalog/catalog-store.d.mts +9 -1
  192. package/src/runtime/domain/catalog/catalog-store.mjs +20 -22
  193. package/src/runtime/domain/coordinator/src/assignment-changes.mjs +75 -0
  194. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +2 -0
  195. package/src/runtime/domain/coordinator/src/background-parent-callbacks.mjs +65 -0
  196. package/src/runtime/domain/coordinator/src/background-requests.mjs +86 -0
  197. package/src/runtime/domain/coordinator/src/discovery.mjs +4 -2
  198. package/src/runtime/domain/coordinator/src/operations.mjs +44 -4
  199. package/src/runtime/domain/coordinator/src/result-supervision.mjs +12 -0
  200. package/src/runtime/domain/coordinator/src/rows.mjs +2 -0
  201. package/src/runtime/domain/coordinator/src/schema.mjs +73 -21
  202. package/src/runtime/domain/coordinator/src/store.mjs +32 -3
  203. package/src/runtime/domain/coordinator/src/subagent-launch.mjs +119 -0
  204. package/src/runtime/domain/coordinator/src/types.mjs +1 -1
  205. package/src/runtime/domain/coordinator/src/upgrade.mjs +22 -0
  206. package/src/runtime/domain/health-observation.d.mts +3 -1
  207. package/src/runtime/domain/health-observation.mjs +189 -190
  208. package/src/runtime/domain/log-cursor.d.mts +2 -0
  209. package/src/runtime/domain/log-cursor.mjs +85 -16
  210. package/src/runtime/domain/parse.d.mts +4 -1
  211. package/src/runtime/domain/parse.mjs +50 -5
  212. package/src/runtime/domain/sandbox-policy/README.md +633 -0
  213. package/src/runtime/domain/sandbox-policy/background-admission.domain.mjs +83 -0
  214. package/src/runtime/domain/sandbox-policy/background-admission.ts +75 -0
  215. package/src/runtime/domain/sandbox-policy/commands.domain.mjs +245 -0
  216. package/src/runtime/domain/sandbox-policy/commands.ts +336 -0
  217. package/src/runtime/domain/sandbox-policy/deny-rules.domain.mjs +440 -0
  218. package/src/runtime/domain/sandbox-policy/deny-rules.ts +620 -0
  219. package/src/runtime/domain/sandbox-policy/diagnostics-command.domain.mjs +30 -0
  220. package/src/runtime/domain/sandbox-policy/diagnostics-command.ts +27 -0
  221. package/src/runtime/domain/sandbox-policy/events.domain.mjs +49 -0
  222. package/src/runtime/domain/sandbox-policy/events.ts +85 -0
  223. package/src/runtime/domain/sandbox-policy/files.domain.mjs +153 -0
  224. package/src/runtime/domain/sandbox-policy/files.ts +224 -0
  225. package/src/runtime/domain/sandbox-policy/index.domain.mjs +289 -0
  226. package/src/runtime/domain/sandbox-policy/index.ts +386 -0
  227. package/src/runtime/domain/sandbox-policy/package.json +66 -0
  228. package/src/runtime/domain/sandbox-policy/permission-settings.domain.mjs +36 -0
  229. package/src/runtime/domain/sandbox-policy/permission-settings.ts +46 -0
  230. package/src/runtime/domain/sandbox-policy/permissions-page.domain.mjs +309 -0
  231. package/src/runtime/domain/sandbox-policy/permissions-page.ts +295 -0
  232. package/src/runtime/domain/sandbox-policy/permissions.domain.mjs +98 -0
  233. package/src/runtime/domain/sandbox-policy/permissions.ts +125 -0
  234. package/src/runtime/domain/sandbox-policy/policy.domain.mjs +80 -0
  235. package/src/runtime/domain/sandbox-policy/policy.ts +102 -0
  236. package/src/runtime/domain/sandbox-policy/preferences.domain.mjs +55 -0
  237. package/src/runtime/domain/sandbox-policy/preferences.ts +82 -0
  238. package/src/runtime/domain/sandbox-policy/rules-page.domain.mjs +138 -0
  239. package/src/runtime/domain/sandbox-policy/rules-page.ts +176 -0
  240. package/src/runtime/domain/sandbox-policy/session-permissions.domain.mjs +22 -0
  241. package/src/runtime/domain/sandbox-policy/session-permissions.ts +24 -0
  242. package/src/runtime/domain/sandbox-policy/shared-harness-settings.domain.mjs +126 -0
  243. package/src/runtime/domain/sandbox-policy/shared-harness-settings.ts +116 -0
  244. package/src/runtime/domain/sandbox-policy/shared-permission-blocker.domain.mjs +40 -0
  245. package/src/runtime/domain/sandbox-policy/shared-permission-blocker.ts +48 -0
  246. package/src/runtime/domain/sandbox-policy/shared-sandbox-core.domain.mjs +1531 -0
  247. package/src/runtime/domain/sandbox-policy/shared-sandbox-core.ts +1757 -0
  248. package/src/runtime/domain/sandbox-policy/shared-sandbox-diagnostics.domain.mjs +591 -0
  249. package/src/runtime/domain/sandbox-policy/shared-sandbox-diagnostics.ts +491 -0
  250. package/src/runtime/domain/sandbox-policy/shared-task-application.domain.mjs +185 -0
  251. package/src/runtime/domain/sandbox-policy/shared-task-application.ts +185 -0
  252. package/src/runtime/domain/sandbox-policy/shared-task-apply-patch.domain.mjs +416 -0
  253. package/src/runtime/domain/sandbox-policy/shared-task-apply-patch.ts +409 -0
  254. package/src/runtime/domain/sandbox-policy/shared-task-exec.domain.mjs +325 -0
  255. package/src/runtime/domain/sandbox-policy/shared-task-exec.ts +335 -0
  256. package/src/runtime/domain/sandbox-policy/shared-task-files.domain.mjs +346 -0
  257. package/src/runtime/domain/sandbox-policy/shared-task-files.ts +342 -0
  258. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.domain.mjs +140 -0
  259. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.ts +126 -0
  260. package/src/runtime/domain/sandbox-policy/shared-task-process-list.domain.mjs +220 -0
  261. package/src/runtime/domain/sandbox-policy/shared-task-process-list.ts +209 -0
  262. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.domain.mjs +227 -0
  263. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.ts +224 -0
  264. package/src/runtime/domain/sandbox-policy/shared-task-tools.domain.mjs +92 -0
  265. package/src/runtime/domain/sandbox-policy/shared-task-tools.ts +123 -0
  266. package/src/runtime/domain/sandbox-policy/shell.domain.mjs +93 -0
  267. package/src/runtime/domain/sandbox-policy/shell.ts +129 -0
  268. package/src/runtime/domain/sandbox-policy/state.domain.mjs +307 -0
  269. package/src/runtime/domain/sandbox-policy/state.ts +408 -0
  270. package/src/runtime/domain/sandbox-policy/status.domain.mjs +64 -0
  271. package/src/runtime/domain/sandbox-policy/status.ts +76 -0
  272. package/src/runtime/domain/sandbox-policy/subagent-admission.domain.mjs +69 -0
  273. package/src/runtime/domain/sandbox-policy/subagent-admission.ts +60 -0
  274. package/src/runtime/domain/subagents/CONTEXT.md +202 -0
  275. package/src/runtime/domain/subagents/PRODUCT.md +49 -0
  276. package/src/runtime/domain/subagents/README.md +201 -0
  277. package/src/runtime/domain/subagents/agent-catalog.mjs +64 -0
  278. package/src/runtime/domain/subagents/agent-commands.domain.mjs +822 -0
  279. package/src/runtime/domain/subagents/agent-commands.ts +905 -0
  280. package/src/runtime/domain/subagents/agent-inspection.domain.mjs +398 -0
  281. package/src/runtime/domain/subagents/agent-inspection.ts +574 -0
  282. package/src/runtime/domain/subagents/agent-operations.domain.mjs +40 -0
  283. package/src/runtime/domain/subagents/agent-operations.ts +61 -0
  284. package/src/runtime/domain/subagents/agent-session-settings.domain.mjs +112 -0
  285. package/src/runtime/domain/subagents/agent-session-settings.ts +118 -0
  286. package/src/runtime/domain/subagents/agents-catalog-tool.domain.mjs +84 -0
  287. package/src/runtime/domain/subagents/agents-catalog-tool.ts +118 -0
  288. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +276 -0
  289. package/src/runtime/domain/subagents/assignment-outcomes.ts +212 -0
  290. package/src/runtime/domain/subagents/assignment-projection.mjs +261 -0
  291. package/src/runtime/domain/subagents/assignment-report.domain.mjs +174 -0
  292. package/src/runtime/domain/subagents/assignment-report.ts +156 -0
  293. package/src/runtime/domain/subagents/batch.mjs +275 -0
  294. package/src/runtime/domain/subagents/callback-fields.domain.mjs +72 -0
  295. package/src/runtime/domain/subagents/callback-fields.ts +95 -0
  296. package/src/runtime/domain/subagents/capacity.mjs +108 -0
  297. package/src/runtime/domain/subagents/catalog-editor.domain.mjs +98 -0
  298. package/src/runtime/domain/subagents/catalog-editor.ts +125 -0
  299. package/src/runtime/domain/subagents/catalog-host-admission.domain.mjs +104 -0
  300. package/src/runtime/domain/subagents/catalog-host-admission.ts +85 -0
  301. package/src/runtime/domain/subagents/catalog-identity.domain.mjs +222 -0
  302. package/src/runtime/domain/subagents/catalog-identity.ts +258 -0
  303. package/src/runtime/domain/subagents/catalog-overlay.domain.mjs +9 -0
  304. package/src/runtime/domain/subagents/catalog-overlay.ts +10 -0
  305. package/src/runtime/domain/subagents/catalog-preferences.domain.mjs +164 -0
  306. package/src/runtime/domain/subagents/catalog-preferences.ts +139 -0
  307. package/src/runtime/domain/subagents/catalog-resolver.domain.mjs +366 -0
  308. package/src/runtime/domain/subagents/catalog-resolver.ts +540 -0
  309. package/src/runtime/domain/subagents/catalog-runtime.domain.mjs +570 -0
  310. package/src/runtime/domain/subagents/catalog-runtime.ts +680 -0
  311. package/src/runtime/domain/subagents/catalog-schema.domain.mjs +1331 -0
  312. package/src/runtime/domain/subagents/catalog-schema.ts +1563 -0
  313. package/src/runtime/domain/subagents/catalog-skill-edits.domain.mjs +95 -0
  314. package/src/runtime/domain/subagents/catalog-skill-edits.ts +116 -0
  315. package/src/runtime/domain/subagents/catalog-store.domain.mjs +808 -0
  316. package/src/runtime/domain/subagents/catalog-store.ts +1006 -0
  317. package/src/runtime/domain/subagents/catalog-ui.domain.mjs +651 -0
  318. package/src/runtime/domain/subagents/catalog-ui.ts +611 -0
  319. package/src/runtime/domain/subagents/child-apply-patch.domain.mjs +13 -0
  320. package/src/runtime/domain/subagents/child-apply-patch.ts +13 -0
  321. package/src/runtime/domain/subagents/child-codemode.domain.mjs +16 -0
  322. package/src/runtime/domain/subagents/child-codemode.ts +17 -0
  323. package/src/runtime/domain/subagents/child-dependencies.mjs +193 -0
  324. package/src/runtime/domain/subagents/child-incidents.domain.mjs +170 -0
  325. package/src/runtime/domain/subagents/child-incidents.ts +169 -0
  326. package/src/runtime/domain/subagents/child-operations.domain.mjs +986 -0
  327. package/src/runtime/domain/subagents/child-operations.ts +1191 -0
  328. package/src/runtime/domain/subagents/child-ownership.domain.mjs +205 -0
  329. package/src/runtime/domain/subagents/child-ownership.ts +160 -0
  330. package/src/runtime/domain/subagents/child-preflight.mjs +38 -0
  331. package/src/runtime/domain/subagents/child-process-list.domain.mjs +7 -0
  332. package/src/runtime/domain/subagents/child-process-list.ts +8 -0
  333. package/src/runtime/domain/subagents/child-runtime.mjs +67 -0
  334. package/src/runtime/domain/subagents/child-steer.domain.mjs +109 -0
  335. package/src/runtime/domain/subagents/child-steer.ts +102 -0
  336. package/src/runtime/domain/subagents/cleanup.domain.mjs +818 -0
  337. package/src/runtime/domain/subagents/cleanup.ts +1017 -0
  338. package/src/runtime/domain/subagents/codex-import.domain.mjs +575 -0
  339. package/src/runtime/domain/subagents/codex-import.ts +717 -0
  340. package/src/runtime/domain/subagents/completion.domain.mjs +6 -0
  341. package/src/runtime/domain/subagents/completion.mjs +152 -0
  342. package/src/runtime/domain/subagents/completion.ts +11 -0
  343. package/src/runtime/domain/subagents/config.domain.mjs +248 -0
  344. package/src/runtime/domain/subagents/config.json +15 -0
  345. package/src/runtime/domain/subagents/config.ts +328 -0
  346. package/src/runtime/domain/subagents/continuation-authority.domain.mjs +38 -0
  347. package/src/runtime/domain/subagents/continuation-authority.ts +31 -0
  348. package/src/runtime/domain/subagents/continuation-runtime.domain.mjs +89 -0
  349. package/src/runtime/domain/subagents/continuation-runtime.ts +88 -0
  350. package/src/runtime/domain/subagents/continuation.domain.mjs +942 -0
  351. package/src/runtime/domain/subagents/continuation.ts +1051 -0
  352. package/src/runtime/domain/subagents/delegation.domain.mjs +19 -0
  353. package/src/runtime/domain/subagents/delegation.ts +24 -0
  354. package/src/runtime/domain/subagents/effective-settings.domain.mjs +130 -0
  355. package/src/runtime/domain/subagents/effective-settings.ts +184 -0
  356. package/src/runtime/domain/subagents/extensions.domain.mjs +6 -0
  357. package/src/runtime/domain/subagents/extensions.mjs +164 -0
  358. package/src/runtime/domain/subagents/extensions.ts +19 -0
  359. package/src/runtime/domain/subagents/failures.domain.mjs +362 -0
  360. package/src/runtime/domain/subagents/failures.ts +319 -0
  361. package/src/runtime/domain/subagents/finalization.domain.mjs +168 -0
  362. package/src/runtime/domain/subagents/finalization.ts +218 -0
  363. package/src/runtime/domain/subagents/git-remotes.domain.mjs +351 -0
  364. package/src/runtime/domain/subagents/git-remotes.ts +413 -0
  365. package/src/runtime/domain/subagents/git-workspace.domain.mjs +337 -0
  366. package/src/runtime/domain/subagents/git-workspace.ts +430 -0
  367. package/src/runtime/domain/subagents/goal-provider.domain.mjs +125 -0
  368. package/src/runtime/domain/subagents/goal-provider.ts +132 -0
  369. package/src/runtime/domain/subagents/health-observation.domain.mjs +617 -0
  370. package/src/runtime/domain/subagents/health-observation.ts +818 -0
  371. package/src/runtime/domain/subagents/health-surface.mjs +284 -0
  372. package/src/runtime/domain/subagents/health.domain.mjs +261 -0
  373. package/src/runtime/domain/subagents/health.ts +343 -0
  374. package/src/runtime/domain/subagents/historical-attention.domain.mjs +37 -0
  375. package/src/runtime/domain/subagents/historical-attention.ts +35 -0
  376. package/src/runtime/domain/subagents/incident-model.domain.mjs +322 -0
  377. package/src/runtime/domain/subagents/incident-model.ts +358 -0
  378. package/src/runtime/domain/subagents/index.domain.mjs +4731 -0
  379. package/src/runtime/domain/subagents/index.ts +4781 -0
  380. package/src/runtime/domain/subagents/launch-abort.domain.mjs +13 -0
  381. package/src/runtime/domain/subagents/launch-abort.ts +21 -0
  382. package/src/runtime/domain/subagents/launch-context.domain.mjs +24 -0
  383. package/src/runtime/domain/subagents/launch-context.ts +23 -0
  384. package/src/runtime/domain/subagents/launch-digest.mjs +6 -0
  385. package/src/runtime/domain/subagents/lifecycle.domain.mjs +265 -0
  386. package/src/runtime/domain/subagents/lifecycle.ts +360 -0
  387. package/src/runtime/domain/subagents/list.domain.mjs +2 -0
  388. package/src/runtime/domain/subagents/list.mjs +152 -0
  389. package/src/runtime/domain/subagents/list.ts +19 -0
  390. package/src/runtime/domain/subagents/log-cursor.domain.mjs +217 -0
  391. package/src/runtime/domain/subagents/log-cursor.ts +268 -0
  392. package/src/runtime/domain/subagents/managed-background-capability.domain.mjs +10 -0
  393. package/src/runtime/domain/subagents/managed-background-capability.ts +9 -0
  394. package/src/runtime/domain/subagents/managed-failure-worker.mjs +36 -0
  395. package/src/runtime/domain/subagents/managed-launch-bootstrap.mjs +48 -0
  396. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +75 -0
  397. package/src/runtime/domain/subagents/managed-launch-client.ts +59 -0
  398. package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +627 -0
  399. package/src/runtime/domain/subagents/managed-launch-host.ts +504 -0
  400. package/src/runtime/domain/subagents/managed-launch-journal.mjs +17 -0
  401. package/src/runtime/domain/subagents/managed-launch-ownership.domain.mjs +29 -0
  402. package/src/runtime/domain/subagents/managed-launch-ownership.ts +22 -0
  403. package/src/runtime/domain/subagents/managed-launch-port.domain.mjs +2 -0
  404. package/src/runtime/domain/subagents/managed-launch-port.ts +25 -0
  405. package/src/runtime/domain/subagents/managed-launch-recovery.domain.mjs +29 -0
  406. package/src/runtime/domain/subagents/managed-launch-recovery.ts +45 -0
  407. package/src/runtime/domain/subagents/managed-worker-bridge.domain.mjs +63 -0
  408. package/src/runtime/domain/subagents/managed-worker-bridge.ts +48 -0
  409. package/src/runtime/domain/subagents/managed-worker.mjs +13 -0
  410. package/src/runtime/domain/subagents/model-resolution-core.domain.mjs +822 -0
  411. package/src/runtime/domain/subagents/model-resolution-core.ts +1074 -0
  412. package/src/runtime/domain/subagents/model-resolution.domain.mjs +22 -0
  413. package/src/runtime/domain/subagents/model-resolution.ts +32 -0
  414. package/src/runtime/domain/subagents/navigator.domain.mjs +6 -0
  415. package/src/runtime/domain/subagents/navigator.mjs +1233 -0
  416. package/src/runtime/domain/subagents/navigator.ts +39 -0
  417. package/src/runtime/domain/subagents/operation-bridge-types.domain.mjs +1012 -0
  418. package/src/runtime/domain/subagents/operation-bridge-types.ts +1156 -0
  419. package/src/runtime/domain/subagents/outage-observations.domain.mjs +84 -0
  420. package/src/runtime/domain/subagents/outage-observations.ts +73 -0
  421. package/src/runtime/domain/subagents/output-payload.domain.mjs +767 -0
  422. package/src/runtime/domain/subagents/output-payload.ts +987 -0
  423. package/src/runtime/domain/subagents/owned-exit.domain.mjs +12 -0
  424. package/src/runtime/domain/subagents/owned-exit.ts +12 -0
  425. package/src/runtime/domain/subagents/package.json +86 -0
  426. package/src/runtime/domain/subagents/park-checkpoint.domain.mjs +55 -0
  427. package/src/runtime/domain/subagents/park-checkpoint.ts +61 -0
  428. package/src/runtime/domain/subagents/parse.domain.mjs +1218 -0
  429. package/src/runtime/domain/subagents/parse.ts +1451 -0
  430. package/src/runtime/domain/subagents/permission-policy.domain.mjs +232 -0
  431. package/src/runtime/domain/subagents/permission-policy.ts +291 -0
  432. package/src/runtime/domain/subagents/process-identity.mjs +33 -0
  433. package/src/runtime/domain/subagents/registry.domain.mjs +1584 -0
  434. package/src/runtime/domain/subagents/registry.ts +1904 -0
  435. package/src/runtime/domain/subagents/role-assignment.domain.mjs +104 -0
  436. package/src/runtime/domain/subagents/role-assignment.ts +141 -0
  437. package/src/runtime/domain/subagents/roles/role.architect.md +13 -0
  438. package/src/runtime/domain/subagents/roles/role.developer.md +16 -0
  439. package/src/runtime/domain/subagents/roles/role.explorer.md +13 -0
  440. package/src/runtime/domain/subagents/roles/role.product-manager.md +13 -0
  441. package/src/runtime/domain/subagents/roles/role.researcher.md +13 -0
  442. package/src/runtime/domain/subagents/roles/role.reviewer.md +13 -0
  443. package/src/runtime/domain/subagents/roles/role.writer.md +12 -0
  444. package/src/runtime/domain/subagents/sandbox.domain.mjs +64 -0
  445. package/src/runtime/domain/subagents/sandbox.ts +92 -0
  446. package/src/runtime/domain/subagents/session-selection.domain.mjs +32 -0
  447. package/src/runtime/domain/subagents/session-selection.ts +35 -0
  448. package/src/runtime/domain/subagents/session-store.domain.mjs +489 -0
  449. package/src/runtime/domain/subagents/session-store.ts +468 -0
  450. package/src/runtime/domain/subagents/settings-page.domain.mjs +313 -0
  451. package/src/runtime/domain/subagents/settings-page.ts +363 -0
  452. package/src/runtime/domain/subagents/shared-callback-batcher.domain.mjs +777 -0
  453. package/src/runtime/domain/subagents/shared-callback-batcher.ts +956 -0
  454. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +70 -0
  455. package/src/runtime/domain/subagents/shared-catalog.ts +61 -0
  456. package/src/runtime/domain/subagents/shared-execution-policy.domain.mjs +50 -0
  457. package/src/runtime/domain/subagents/shared-execution-policy.ts +61 -0
  458. package/src/runtime/domain/subagents/shared-failure-observations.domain.mjs +1078 -0
  459. package/src/runtime/domain/subagents/shared-failure-observations.ts +1166 -0
  460. package/src/runtime/domain/subagents/shared-harness-settings.domain.mjs +126 -0
  461. package/src/runtime/domain/subagents/shared-harness-settings.ts +116 -0
  462. package/src/runtime/domain/subagents/shared-log-utils.domain.mjs +1223 -0
  463. package/src/runtime/domain/subagents/shared-log-utils.ts +1492 -0
  464. package/src/runtime/domain/subagents/shared-navigator-panels.domain.mjs +289 -0
  465. package/src/runtime/domain/subagents/shared-navigator-panels.ts +272 -0
  466. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +1930 -0
  467. package/src/runtime/domain/subagents/shared-navigator.ts +1962 -0
  468. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  469. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +189 -0
  470. package/src/runtime/domain/subagents/shared-operation-coordinator/index.domain.mjs +51 -0
  471. package/src/runtime/domain/subagents/shared-operation-coordinator/index.ts +122 -0
  472. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  473. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  474. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +163 -0
  475. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +174 -0
  476. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-parent-callbacks.domain.mjs +66 -0
  477. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-parent-callbacks.ts +68 -0
  478. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.domain.mjs +87 -0
  479. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.ts +90 -0
  480. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +97 -0
  481. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +139 -0
  482. package/src/runtime/domain/subagents/shared-operation-coordinator/src/errors.domain.mjs +12 -0
  483. package/src/runtime/domain/subagents/shared-operation-coordinator/src/errors.ts +79 -0
  484. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +342 -0
  485. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +513 -0
  486. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +283 -0
  487. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +458 -0
  488. package/src/runtime/domain/subagents/shared-operation-coordinator/src/recovery.domain.mjs +52 -0
  489. package/src/runtime/domain/subagents/shared-operation-coordinator/src/recovery.ts +55 -0
  490. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +114 -0
  491. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +140 -0
  492. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.domain.mjs +280 -0
  493. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.ts +442 -0
  494. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +420 -0
  495. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +441 -0
  496. package/src/runtime/domain/subagents/shared-operation-coordinator/src/sqlite.domain.mjs +194 -0
  497. package/src/runtime/domain/subagents/shared-operation-coordinator/src/sqlite.ts +239 -0
  498. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +275 -0
  499. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +585 -0
  500. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.domain.mjs +120 -0
  501. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.ts +142 -0
  502. package/src/runtime/domain/subagents/shared-operation-coordinator/src/task-cancellation.domain.mjs +188 -0
  503. package/src/runtime/domain/subagents/shared-operation-coordinator/src/task-cancellation.ts +224 -0
  504. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.domain.mjs +25 -0
  505. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.ts +707 -0
  506. package/src/runtime/domain/subagents/shared-operation-coordinator/src/upgrade.domain.mjs +22 -0
  507. package/src/runtime/domain/subagents/shared-operation-coordinator/src/upgrade.ts +22 -0
  508. package/src/runtime/domain/subagents/shared-operation-coordinator/src/validate.domain.mjs +234 -0
  509. package/src/runtime/domain/subagents/shared-operation-coordinator/src/validate.ts +241 -0
  510. package/src/runtime/domain/subagents/shared-operation-coordinator/src/waits.domain.mjs +851 -0
  511. package/src/runtime/domain/subagents/shared-operation-coordinator/src/waits.ts +1424 -0
  512. package/src/runtime/domain/subagents/shared-permission-blocker.domain.mjs +40 -0
  513. package/src/runtime/domain/subagents/shared-permission-blocker.ts +48 -0
  514. package/src/runtime/domain/subagents/shared-render-scheduler.domain.mjs +41 -0
  515. package/src/runtime/domain/subagents/shared-render-scheduler.ts +47 -0
  516. package/src/runtime/domain/subagents/shared-sandbox-core.domain.mjs +1531 -0
  517. package/src/runtime/domain/subagents/shared-sandbox-core.ts +1757 -0
  518. package/src/runtime/domain/subagents/shared-sandbox-diagnostics.domain.mjs +591 -0
  519. package/src/runtime/domain/subagents/shared-sandbox-diagnostics.ts +491 -0
  520. package/src/runtime/domain/subagents/shared-stall-detector.domain.mjs +37 -0
  521. package/src/runtime/domain/subagents/shared-stall-detector.ts +69 -0
  522. package/src/runtime/domain/subagents/shared-task-application.domain.mjs +185 -0
  523. package/src/runtime/domain/subagents/shared-task-application.ts +185 -0
  524. package/src/runtime/domain/subagents/shared-task-apply-patch.domain.mjs +416 -0
  525. package/src/runtime/domain/subagents/shared-task-apply-patch.ts +409 -0
  526. package/src/runtime/domain/subagents/shared-task-exec.domain.mjs +325 -0
  527. package/src/runtime/domain/subagents/shared-task-exec.ts +335 -0
  528. package/src/runtime/domain/subagents/shared-task-files.domain.mjs +346 -0
  529. package/src/runtime/domain/subagents/shared-task-files.ts +342 -0
  530. package/src/runtime/domain/subagents/shared-task-process-identity.domain.mjs +140 -0
  531. package/src/runtime/domain/subagents/shared-task-process-identity.ts +126 -0
  532. package/src/runtime/domain/subagents/shared-task-process-list.domain.mjs +220 -0
  533. package/src/runtime/domain/subagents/shared-task-process-list.ts +209 -0
  534. package/src/runtime/domain/subagents/shared-task-sandbox.domain.mjs +227 -0
  535. package/src/runtime/domain/subagents/shared-task-sandbox.ts +224 -0
  536. package/src/runtime/domain/subagents/shared-task-tools.domain.mjs +92 -0
  537. package/src/runtime/domain/subagents/shared-task-tools.ts +123 -0
  538. package/src/runtime/domain/subagents/shared-work-client.mjs +303 -0
  539. package/src/runtime/domain/subagents/shared-worktree-context.domain.mjs +142 -0
  540. package/src/runtime/domain/subagents/shared-worktree-context.ts +158 -0
  541. package/src/runtime/domain/subagents/skill-picker.domain.mjs +316 -0
  542. package/src/runtime/domain/subagents/skill-picker.ts +353 -0
  543. package/src/runtime/domain/subagents/skills.domain.mjs +138 -0
  544. package/src/runtime/domain/subagents/skills.ts +183 -0
  545. package/src/runtime/domain/subagents/spawn.domain.mjs +72 -0
  546. package/src/runtime/domain/subagents/spawn.ts +80 -0
  547. package/src/runtime/domain/subagents/stop.domain.mjs +184 -0
  548. package/src/runtime/domain/subagents/stop.ts +217 -0
  549. package/src/runtime/domain/subagents/subagent-tools.domain.mjs +101 -0
  550. package/src/runtime/domain/subagents/subagent-tools.ts +137 -0
  551. package/src/runtime/domain/subagents/task-guard.domain.mjs +163 -0
  552. package/src/runtime/domain/subagents/task-guard.ts +144 -0
  553. package/src/runtime/domain/subagents/task-policy.domain.mjs +201 -0
  554. package/src/runtime/domain/subagents/task-policy.ts +236 -0
  555. package/src/runtime/domain/subagents/task-runtime.mjs +53 -0
  556. package/src/runtime/domain/subagents/task-tool-owner.domain.mjs +18 -0
  557. package/src/runtime/domain/subagents/task-tool-owner.ts +21 -0
  558. package/src/runtime/domain/subagents/thinking.domain.mjs +22 -0
  559. package/src/runtime/domain/subagents/thinking.ts +28 -0
  560. package/src/runtime/domain/subagents/tier-policy.domain.mjs +75 -0
  561. package/src/runtime/domain/subagents/tier-policy.ts +126 -0
  562. package/src/runtime/domain/subagents/timing-notifications.domain.mjs +51 -0
  563. package/src/runtime/domain/subagents/timing-notifications.ts +37 -0
  564. package/src/runtime/domain/subagents/timing.domain.mjs +487 -0
  565. package/src/runtime/domain/subagents/timing.ts +634 -0
  566. package/src/runtime/domain/subagents/tools.domain.mjs +558 -0
  567. package/src/runtime/domain/subagents/tools.ts +629 -0
  568. package/src/runtime/domain/subagents/widget.domain.mjs +6 -0
  569. package/src/runtime/domain/subagents/widget.mjs +246 -0
  570. package/src/runtime/domain/subagents/widget.ts +30 -0
  571. package/src/runtime/domain/subagents/work-observation.domain.mjs +316 -0
  572. package/src/runtime/domain/subagents/work-observation.ts +248 -0
  573. package/src/runtime/domain/subagents/worker-catalog.domain.mjs +120 -0
  574. package/src/runtime/domain/subagents/worker-catalog.ts +162 -0
  575. package/src/runtime/domain/subagents/worker-operations-host.domain.mjs +1009 -0
  576. package/src/runtime/domain/subagents/worker-operations-host.ts +1238 -0
  577. package/src/runtime/domain/subagents/worker-waits.domain.mjs +2336 -0
  578. package/src/runtime/domain/subagents/worker-waits.ts +2878 -0
  579. package/src/runtime/domain/subagents/workspace-scope.domain.mjs +52 -0
  580. package/src/runtime/domain/subagents/workspace-scope.ts +50 -0
  581. package/src/runtime/health-config.ts +27 -11
  582. package/src/runtime/log-checkpoints.ts +117 -0
  583. package/src/runtime/mutation-store.ts +5 -4
  584. package/src/runtime/queries.ts +27 -3
  585. package/src/runtime/query-executor.ts +178 -34
  586. package/src/runtime/query-worker.mjs +119 -22
  587. package/src/runtime/read-model.ts +939 -113
  588. package/src/runtime/read-watchdog-probe.ts +4 -0
  589. package/src/runtime/result-supervision.ts +188 -16
  590. package/src/runtime/source-watch.ts +175 -0
  591. package/src/runtime/subagent-launch.ts +73 -0
  592. package/src/runtime/work-budget.ts +130 -0
  593. package/src/runtime/work-client.d.mts +8 -0
  594. package/src/runtime/work-client.mjs +150 -7
  595. package/src/server.ts +185 -22
  596. package/src/session-activity.ts +26 -4
  597. package/src/version.ts +1 -1
@@ -0,0 +1,1757 @@
1
+ // Generated from packages/sandbox-core/index.ts. Do not edit directly.
2
+ /**
3
+ * OS-level write sandbox mechanism shared by Pi extensions.
4
+ *
5
+ * Legacy policies are write-only: a sandboxed process may READ anywhere and use
6
+ * the network, but may only WRITE under a canonical root plus runtime paths.
7
+ * Optional permissions add capability restrictions for reads, writes, launches
8
+ * and network access. They cover known credential files, not OS keychains,
9
+ * credential services, or tokens inherited in the child environment.
10
+ *
11
+ * This module owns the mechanism only: backend discovery, canonical path
12
+ * containment, write-deny compilation, macOS SBPL profile construction, Linux
13
+ * Bubblewrap mount construction, ordered executable/argv wrapping, and support
14
+ * diagnostics. It owns no Pi tool, TUI, background-task, or subagent lifecycle
15
+ * policy — callers decide when a sandbox is requested and what it may write.
16
+ *
17
+ * Every platform/filesystem dependency is reachable through the optional
18
+ * `SandboxSeams` argument so callers can plan deterministically in tests.
19
+ */
20
+
21
+ import { spawn, spawnSync } from "node:child_process";
22
+ import { platform as osPlatform } from "node:os";
23
+ import {
24
+ accessSync,
25
+ closeSync,
26
+ constants,
27
+ existsSync,
28
+ lstatSync,
29
+ mkdirSync,
30
+ openSync,
31
+ readdirSync,
32
+ readlinkSync,
33
+ realpathSync,
34
+ statSync,
35
+ writeFileSync,
36
+ } from "node:fs";
37
+ import { basename, delimiter, dirname, isAbsolute, join, parse, resolve, sep } from "node:path";
38
+
39
+ /** Identifies which kernel mechanism a plan will use. */
40
+ export type SandboxBackendId = "macos-seatbelt" | "linux-bubblewrap";
41
+
42
+ /**
43
+ * File access levels for the Project files and Outside project rows.
44
+ *
45
+ * - `off`: no access.
46
+ * - `read`: read only.
47
+ * - `write`: read, create and overwrite in place. Nothing can be removed or
48
+ * renamed away (unlink, rmdir, rename of an existing entry, or a rename that
49
+ * replaces one), except in the always-disposable places: temp, hidden (dot)
50
+ * entries of the home directory, and git worktree folders (`.worktrees/`,
51
+ * `*-worktrees/`). For Outside project this is the broad-write profile:
52
+ * writes across home and temp, and the fixed deny list.
53
+ * - `read-write`: "Write & delete" — the historical read/write level.
54
+ */
55
+ export type SandboxFileAccess = "off" | "read" | "write" | "read-write";
56
+
57
+ export type SandboxPermissions = {
58
+ projectFiles: SandboxFileAccess;
59
+ outsideProject: SandboxFileAccess;
60
+ storedCredentials: "off" | "read" | "read-write";
61
+ /** Run applications: the master switch for command execution (bash and run_application). */
62
+ commands: boolean;
63
+ /** Shell scripts inside commands; omitted (legacy) profiles keep shell execution On. */
64
+ shell?: boolean;
65
+ /**
66
+ * Cap for every command path, in seconds. The effective timeout is
67
+ * `min(requested, cap)`, and the cap applies when the caller omits a timeout.
68
+ * Omitted or null means no limit. Must be positive, finite and <= 2147483.
69
+ */
70
+ commandTimeoutSeconds?: number | null;
71
+ network: boolean;
72
+ /** Fixed process adapters (inventory and Darwin identity compatibility); omitted legacy profiles keep it Off. */
73
+ processAccess?: "off" | "read";
74
+ };
75
+
76
+ /** Whether a file access level allows creating and overwriting files. */
77
+ export function canWrite(mode: SandboxFileAccess | undefined): boolean {
78
+ return mode === "write" || mode === "read-write";
79
+ }
80
+
81
+ /**
82
+ * What a sandboxed process may write. `writableRoot` and `denyWrite` entries may
83
+ * be relative or contain symlinks; they are canonicalized before use.
84
+ */
85
+ export type SandboxWritePolicy = {
86
+ /** The single directory subtree the sandboxed process may write under. */
87
+ writableRoot: string;
88
+ /**
89
+ * Concrete paths that stay non-writable even inside `writableRoot`. A
90
+ * directory entry denies its whole subtree; a file entry denies that file.
91
+ *
92
+ * An entry need not exist. The Linux backend needs a mount point, so it
93
+ * materializes an absent entry as an empty file (see `materializeDenyPath`);
94
+ * an entry that has to be a *directory* must therefore already exist when the
95
+ * command is built. Callers denying their own state directory create it
96
+ * first, which they do anyway to write into it.
97
+ */
98
+ denyWrite?: readonly string[];
99
+ /** Home directory whose `~/.pi` state stays writable on macOS. */
100
+ home: string;
101
+ /** Optional capability profile; omission preserves the original write-only sandbox. */
102
+ permissions?: SandboxPermissions;
103
+ /** Trusted per-launch runtime state, never supplied by model tool arguments. */
104
+ runtimeWrite?: readonly string[];
105
+ /** Bounded historical default runtime directories; inactive without a capability profile. */
106
+ runtimeCompatibility?: boolean;
107
+ };
108
+
109
+ /** The executable and argv to run inside the sandbox, preserved verbatim. */
110
+ export type SandboxTarget = {
111
+ execPath: string;
112
+ execArgs: readonly string[];
113
+ };
114
+
115
+ export const SHELL_EXECUTABLE_NAMES = Object.freeze([
116
+ "sh", "bash", "zsh", "dash", "ksh", "ksh93", "mksh", "pdksh", "ash", "csh", "tcsh", "fish",
117
+ "yash", "posh", "rbash", "busybox", "pwsh", "powershell", "cmd",
118
+ ] as const);
119
+
120
+ // Fixed runtime code starts after confinement. The launch data is JSON, never
121
+ // env/shell syntax. Native execve never falls back to a command interpreter.
122
+ const APPLICATION_RUNNER = `
123
+ const fs = require("node:fs");
124
+ const path = require("node:path");
125
+ const spec = JSON.parse(process.argv[1]);
126
+ function resolveExecutable(executable) {
127
+ if (executable.includes(path.sep)) return path.resolve(executable);
128
+ const directories = (spec.env.PATH || spec.env.Path || "").split(path.delimiter);
129
+ const resolved = directories.map(directory => path.resolve(directory || ".", executable)).find(candidate => {
130
+ try { fs.accessSync(candidate, fs.constants.X_OK); return fs.statSync(candidate).isFile(); }
131
+ catch { return false; }
132
+ });
133
+ if (!resolved) throw new Error("Executable not found: " + executable);
134
+ return resolved;
135
+ }
136
+ function isShellInterpreter(interpreter) {
137
+ const canonical = fs.realpathSync(interpreter);
138
+ if (spec.shellNames.includes(path.basename(interpreter)) || spec.shellNames.includes(path.basename(canonical))) return true;
139
+ const target = fs.statSync(canonical, { bigint: true });
140
+ const directories = new Set(["/bin", "/usr/bin", ...(spec.env.PATH || spec.env.Path || "").split(path.delimiter)]);
141
+ for (const directory of directories) for (const name of spec.shellNames) {
142
+ try {
143
+ const known = fs.statSync(path.resolve(directory || ".", name), { bigint: true });
144
+ if (target.dev === known.dev && target.ino === known.ino) return true;
145
+ } catch { /* A shell need not exist in every executable directory. */ }
146
+ }
147
+ return false;
148
+ }
149
+ function verifyExecutable(executable, depth = 0) {
150
+ if (depth > 4) throw new Error("Too many shebang interpreters.");
151
+ fs.accessSync(executable, fs.constants.X_OK);
152
+ const fd = fs.openSync(executable, "r");
153
+ const header = Buffer.alloc(4096);
154
+ let size;
155
+ try { size = fs.readSync(fd, header, 0, header.length, 0); }
156
+ finally { fs.closeSync(fd); }
157
+ const magic = size >= 4 ? header.readUInt32BE(0) : 0;
158
+ const binary = [0x7f454c46, 0xfeedface, 0xcefaedfe, 0xfeedfacf, 0xcffaedfe,
159
+ 0xcafebabe, 0xbebafeca, 0xcafebabf, 0xbfbafeca].includes(magic);
160
+ const script = size >= 2 && header[0] === 35 && header[1] === 33;
161
+ if (!binary && !script) throw new Error("Executable has no supported binary format or shebang; shell fallback is disabled.");
162
+ if (!spec.shell && script) {
163
+ const words = header.subarray(2, size).toString("utf8").split(/\\r?\\n/, 1)[0].trim().split(/\\s+/);
164
+ let interpreter = resolveExecutable(words[0]);
165
+ if (path.basename(fs.realpathSync(interpreter)) === "env") {
166
+ if (words.length !== 2 || words[1].startsWith("-") || words[1].includes("=")) {
167
+ throw new Error("Sandbox: Shell scripts are Off; an env shebang must name one direct interpreter without options.");
168
+ }
169
+ interpreter = resolveExecutable(words[1]);
170
+ }
171
+ if (isShellInterpreter(interpreter)) {
172
+ throw new Error("Sandbox: Shell scripts are Off; the executable uses a shell shebang.");
173
+ }
174
+ verifyExecutable(interpreter, depth + 1);
175
+ }
176
+ }
177
+ try {
178
+ if (typeof process.execve !== "function") {
179
+ throw new Error("Direct application execution requires Node.js with process.execve (22.15+ or 24+). Update Node.js; no shell fallback was run.");
180
+ }
181
+ const executable = resolveExecutable(spec.executable);
182
+ verifyExecutable(executable);
183
+ process.execve(executable, [executable, ...spec.args], spec.env);
184
+ } catch (error) {
185
+ console.error(error.code === "ENOEXEC" ? "Executable format is unsupported; shell fallback is disabled." : error.message);
186
+ process.exitCode = 126;
187
+ }
188
+ `;
189
+
190
+ /** Fixed post-boundary launcher for literal argv, without env assignment or shell fallback. */
191
+ export function directApplicationTarget(
192
+ executable: string, args: readonly string[], env: NodeJS.ProcessEnv, shell: boolean,
193
+ ): SandboxTarget {
194
+ return { execPath: canonicalizePath(process.execPath), execArgs: ["--eval", APPLICATION_RUNNER,
195
+ JSON.stringify({ executable, args, env, shell, shellNames: SHELL_EXECUTABLE_NAMES })] };
196
+ }
197
+
198
+ export type SandboxCommandArgs = SandboxTarget & {
199
+ /** Where the macOS backend writes its generated SBPL profile. */
200
+ profilePath: string;
201
+ policy: SandboxWritePolicy;
202
+ /** Fixed internal helper only: expose its executable in a hidden Linux root. */
203
+ internalHelperExecutable?: boolean;
204
+ };
205
+
206
+ /**
207
+ * The wrapper command to spawn: the backend executable and its full argv.
208
+ * `notices` are lines the caller shows with the launch output, such as a
209
+ * placeholder the Linux backend had to leave in the user's files.
210
+ */
211
+ export type SandboxCommand = { file: string; fileArgs: string[]; notices?: string[] };
212
+
213
+ /** The caller's default-on / explicit-request / opt-out decision. */
214
+ export type SandboxRequest = {
215
+ sandboxEnabled: boolean;
216
+ explicitSandbox: boolean;
217
+ /**
218
+ * What this caller's operator can actually do about a missing backend,
219
+ * appended when an explicit request has to be refused. Surfaces differ: a
220
+ * subagent tool takes `sandbox:false`, a foreground session takes
221
+ * `/sandbox off`, so the remedy cannot be stated here.
222
+ */
223
+ remedy?: string;
224
+ };
225
+
226
+ /** Injectable platform and filesystem dependencies. Defaults hit the real OS. */
227
+ export type SandboxSeams = {
228
+ /** Defaults to `os.platform()`. */
229
+ platform?: () => string;
230
+ /** Defaults to a PATH scan that stats and access-checks without executing. */
231
+ lookupExecutable?: (name: string) => string | undefined;
232
+ /**
233
+ * Defaults to `fs.realpathSync.native`, which (unlike the JS `realpathSync`)
234
+ * returns the on-disk case of every existing component on a case-insensitive
235
+ * volume, as the kernel sees it. Must throw when the path does not exist.
236
+ */
237
+ canonicalize?: (path: string) => string;
238
+ /** Defaults to `fs.writeFileSync`. */
239
+ writeProfile?: (path: string, contents: string) => void;
240
+ /**
241
+ * Defaults to creating an empty placeholder file for an absent denied path
242
+ * (see `materializeDenyPath`). Returns whether the path exists afterwards.
243
+ * Injected by tests that plan Linux argv for paths that do not exist on the
244
+ * host running them.
245
+ */
246
+ materializeDenyPath?: (path: string) => boolean;
247
+ /** Defaults to /usr/bin/getconf with a minimal environment (macOS only). */
248
+ getconf?: (name: "DARWIN_USER_TEMP_DIR" | "DARWIN_USER_CACHE_DIR") => string | undefined;
249
+ /** Broad-write Linux planning: directory listing (defaults to `readdirSync`). */
250
+ listDirectory?: (path: string) => { name: string; directory: boolean; symlink: boolean }[];
251
+ /** Broad-write Linux planning: existence (defaults to `existsSync`). */
252
+ pathExists?: (path: string) => boolean;
253
+ /** Broad-write Linux planning: whether an existing path is a directory. */
254
+ isDirectory?: (path: string) => boolean;
255
+ /** Broad-write Linux planning: create an absent directory-type deny entry. */
256
+ makeDirectory?: (path: string) => void;
257
+ /** Broad-write Linux planning: empty mode-000 mask sources. */
258
+ maskSources?: (profilePath: string) => { directory: string; file: string };
259
+ };
260
+
261
+ /** A policy with every path canonicalized, deduplicated, and ordered. */
262
+ export type CompiledSandboxWritePolicy = {
263
+ readonly writableRoot: string;
264
+ readonly denyWrite: readonly string[];
265
+ readonly home: string;
266
+ readonly permissions?: SandboxPermissions;
267
+ readonly credentialPaths?: readonly string[];
268
+ readonly runtimeWrite?: readonly string[];
269
+ readonly compatibilityWrite?: readonly string[];
270
+ /** Present only for the broad-write profile (Outside project = `write`). */
271
+ readonly broad?: CompiledBroadWrite;
272
+ };
273
+
274
+ /** The canonical inputs of a broad-write profile. */
275
+ export type CompiledBroadWrite = {
276
+ /** Canonical home directory. Writes are allowed under it, minus the deny list. */
277
+ readonly home: string;
278
+ /** Canonical temp roots (writable and removal-allowed). */
279
+ readonly tempRoots: readonly string[];
280
+ /** Canonical removal-allowed roots besides temp, dot entries and worktree folders: a Write & delete workspace and runtime scratch. */
281
+ readonly deleteRoots: readonly string[];
282
+ /** Code that runs later: never writable, removable or renamable. Still readable. */
283
+ readonly codePaths: readonly string[];
284
+ };
285
+
286
+ /** Why a write target is or is not permitted by a compiled policy. */
287
+ export type WriteAccessDecision =
288
+ | { allowed: true; path: string }
289
+ | {
290
+ allowed: false;
291
+ path: string;
292
+ reason: "outside-writable-root" | "write-denied" | "permission-denied" | "delete-denied";
293
+ /** The compiled deny entry that matched, for `write-denied` only. */
294
+ deniedBy?: string;
295
+ };
296
+
297
+ export type ReadAccessDecision =
298
+ | { allowed: true; path: string }
299
+ | { allowed: false; path: string; reason: "read-denied" };
300
+
301
+ /** What the current platform can enforce, and why it cannot when it cannot. */
302
+ export type SandboxSupport =
303
+ | { supported: true; platform: string; backend: SandboxBackendId; executable: string }
304
+ | {
305
+ supported: false;
306
+ platform: string;
307
+ backend: undefined;
308
+ executable: undefined;
309
+ reason: string;
310
+ };
311
+
312
+ type SandboxBackend = {
313
+ id: SandboxBackendId;
314
+ executable: string;
315
+ buildCommand(args: SandboxCommandArgs, seams: SandboxSeams): SandboxCommand;
316
+ };
317
+
318
+ const MACOS_SANDBOX_EXEC = "/usr/bin/sandbox-exec";
319
+
320
+ const CREDENTIAL_LOCATIONS = [
321
+ ".ssh", ".aws", ".config/gh", ".config/gcloud", ".azure", ".kube",
322
+ ".docker/config.json", ".npmrc", ".netrc", ".git-credentials", ".pi/agent/auth.json",
323
+ ] as const;
324
+
325
+ /** Credential stores added to the Stored credentials row by the broad-write profile. */
326
+ const BROAD_CREDENTIAL_LOCATIONS = [
327
+ "Library/Keychains", ".claude/.credentials.json", ".claude.json", ".gnupg",
328
+ ".codex/auth.json", ".cargo/credentials.toml", ".cargo/credentials", ".pgpass", ".config/rclone",
329
+ ] as const;
330
+
331
+ /**
332
+ * Code that runs later: shell startup files, agent/harness configuration and
333
+ * login agents. The broad-write profile keeps them readable (skills and
334
+ * extension sources are read by confined tasks) but never writable, removable
335
+ * or renamable. This list is fixed; callers extend it with `denyWrite`.
336
+ */
337
+ const CODE_LATER_LOCATIONS = [
338
+ ".bashrc", ".bash_profile", ".bash_login", ".bash_logout", ".profile",
339
+ ".zshrc", ".zshenv", ".zprofile", ".zlogin", ".zlogout",
340
+ ".config/fish", ".config/git", ".gitconfig", ".config/systemd/user", ".config/autostart",
341
+ ".pi", ".claude", ".agents", "Library/LaunchAgents",
342
+ ".local/bin", "bin", ".git-templates", ".oh-my-zsh/custom", ".gradle/init.d",
343
+ ".cargo/config.toml", ".cargo/config",
344
+ ] as const;
345
+
346
+ /** Deny-list entries that are directories when they exist (Linux materializes them as such). */
347
+ const DIRECTORY_LOCATIONS = new Set([
348
+ ".ssh", ".aws", ".config/gh", ".config/gcloud", ".azure", ".kube", "Library/Keychains",
349
+ ".config/fish", ".config/git", ".config/systemd/user", ".config/autostart",
350
+ ".pi", ".claude", ".agents", "Library/LaunchAgents", ".gnupg", ".config/rclone",
351
+ ".local/bin", "bin", ".git-templates", ".oh-my-zsh/custom", ".gradle/init.d",
352
+ ]);
353
+
354
+ const BROAD_TEMP_ROOTS: Record<string, readonly string[]> = {
355
+ darwin: ["/private/tmp", "/private/var/folders", "/private/var/tmp"],
356
+ linux: ["/tmp", "/var/tmp", "/dev/shm"],
357
+ };
358
+
359
+ // Executables, dynamic libraries and OS frameworks needed to start a child.
360
+ // This deliberately excludes the home directory, /etc, and credential stores.
361
+ // A process relying on /etc or /proc configuration (DNS, certificates, NSS)
362
+ // may not start or function under Linux outsideProject=off; callers must not
363
+ // silently remount these broad host trees to work around that failure.
364
+ const RUNTIME_ROOTS = ["/usr", "/bin", "/sbin", "/lib", "/lib64", "/System/Library", "/System/Cryptexes", "/Library/Apple", "/Library/Developer", "/opt/homebrew"];
365
+ const TEMP_ROOTS = ["/private/var/folders", "/private/tmp", "/tmp", "/dev"];
366
+ const READ_RUNTIME_ROOTS = [...RUNTIME_ROOTS, "/dev"];
367
+
368
+ function systemGetconf(name: "DARWIN_USER_TEMP_DIR" | "DARWIN_USER_CACHE_DIR"): string | undefined {
369
+ const result = spawnSync("/usr/bin/getconf", [name], {
370
+ encoding: "utf8", env: { PATH: "/usr/bin:/bin", LANG: "C" }, timeout: 3000, maxBuffer: 4096,
371
+ });
372
+ return result.status === 0 ? result.stdout.trim() : undefined;
373
+ }
374
+
375
+ function compatibilityPaths(policy: SandboxWritePolicy, seams: SandboxSeams): string[] {
376
+ if (!policy.permissions || !policy.runtimeCompatibility || policy.permissions.outsideProject === "off") return [];
377
+ const platform = currentPlatform(seams);
378
+ if (platform === "linux") return [canonicalizePath("/tmp", seams)];
379
+ if (platform !== "darwin") return [];
380
+ const home = canonicalizePath(policy.home, seams);
381
+ const project = canonicalizePath(policy.writableRoot, seams);
382
+ const paths = [canonicalizePath("/tmp", seams)];
383
+ for (const [key, leaf] of [["DARWIN_USER_TEMP_DIR", ""], ["DARWIN_USER_CACHE_DIR", "mds"]] as const) {
384
+ const raw = (seams.getconf ?? systemGetconf)(key);
385
+ if (!raw || !raw.startsWith("/") || raw.includes("\0") ||
386
+ raw.split("/").some((part) => part === "." || part === "..")) {
387
+ throw new Error(`Invalid ${key} runtime directory`);
388
+ }
389
+ // getconf returns /var/folders on macOS; /var is a system alias for /private/var.
390
+ const normalized = resolve(raw.replace(/^\/var\/folders\//, "/private/var/folders/"));
391
+ const expected = /^\/private\/var\/folders\/[^/]+\/[^/]+\/[TC]$/.test(normalized) &&
392
+ normalized.endsWith(key === "DARWIN_USER_TEMP_DIR" ? "/T" : "/C");
393
+ const canonical = canonicalizePath(normalized, seams);
394
+ if (!expected || canonical !== normalized ||
395
+ (contains(home, canonical) || contains(canonical, home) || contains(project, canonical))) {
396
+ throw new Error(`Unsafe ${key} runtime directory`);
397
+ }
398
+ paths.push(leaf ? join(canonical, leaf) : canonical);
399
+ }
400
+ // An existing MDS symlink must not redirect the narrow write allowance.
401
+ const mds = paths[2];
402
+ if (!mds || canonicalizePath(mds, seams) !== mds || contains(mds, project) || contains(project, mds)) {
403
+ throw new Error("Unsafe MDS runtime directory");
404
+ }
405
+ return [...new Set(paths)];
406
+ }
407
+
408
+ /** Only known on-disk credentials: keychains, services and inherited env tokens are out of scope. */
409
+ export function credentialFilePaths(home: string, seams: SandboxSeams = {}): string[] {
410
+ const paths = CREDENTIAL_LOCATIONS.map((name) => join(home, name));
411
+ const configuredAgentDir = process.env.PI_CODING_AGENT_DIR;
412
+ if (configuredAgentDir) paths.push(join(configuredAgentDir.startsWith("~/")
413
+ ? join(home, configuredAgentDir.slice(2)) : configuredAgentDir, "auth.json"));
414
+ return [...new Set(paths.map((path) => canonicalizePath(path, seams)))].sort();
415
+ }
416
+
417
+ function currentPlatform(seams: SandboxSeams): string {
418
+ return (seams.platform ?? osPlatform)();
419
+ }
420
+
421
+ /**
422
+ * Resolve `path` to an absolute canonical path. Symlinks are resolved on the
423
+ * longest existing ancestor so a target that does not exist yet still
424
+ * canonicalizes through its real parent chain.
425
+ */
426
+ export function canonicalizePath(path: string, seams: SandboxSeams = {}): string {
427
+ const canonicalize = seams.canonicalize ?? realpathSync.native;
428
+ const absolute = resolve(path);
429
+ try {
430
+ const resolved = canonicalize(absolute);
431
+ // APFS firmlinks are not resolved by realpath. Normalize the Data-volume
432
+ // alias only when both names demonstrably refer to the same inode.
433
+ const dataPrefix = "/System/Volumes/Data";
434
+ if (!seams.canonicalize && currentPlatform(seams) === "darwin" && resolved.startsWith(`${dataPrefix}/`)) {
435
+ const candidate = resolved.slice(dataPrefix.length);
436
+ try {
437
+ const source = statSync(resolved);
438
+ const alias = statSync(candidate);
439
+ if (source.dev === alias.dev && source.ino === alias.ino) return realpathSync.native(candidate);
440
+ } catch { /* An unrelated Data-volume path keeps its original identity. */ }
441
+ }
442
+ return resolved;
443
+ } catch {
444
+ // Not created yet (or unreadable): canonicalize the parent instead.
445
+ }
446
+ const parent = dirname(absolute);
447
+ if (parent === absolute) return absolute;
448
+ return join(canonicalizePath(parent, seams), basename(absolute));
449
+ }
450
+
451
+ function compile(
452
+ policy: SandboxWritePolicy,
453
+ seams: SandboxSeams,
454
+ strictRoot: boolean,
455
+ ): CompiledSandboxWritePolicy {
456
+ // The Linux backend has always required the writable root to exist before it
457
+ // bind-mounts it; the macOS backend has always tolerated a not-yet-created
458
+ // one. Keep both behaviors rather than unifying them here.
459
+ const writableRoot = strictRoot
460
+ ? (seams.canonicalize ?? realpathSync.native)(policy.writableRoot)
461
+ : canonicalizePath(policy.writableRoot, seams);
462
+
463
+ // The broad profile also keeps each literal entry: its removal grants would
464
+ // otherwise let a task replace a symlinked control path.
465
+ const lexicalDeny = isBroadWritePermissions(policy.permissions);
466
+ const denyWrite = [
467
+ ...new Set((policy.denyWrite ?? []).flatMap((entry) => lexicalDeny
468
+ ? [resolve(entry), ...symlinkHops(entry), canonicalizePath(entry, seams)] : [canonicalizePath(entry, seams)])),
469
+ ].sort();
470
+
471
+ const broadMode = isBroadWritePermissions(policy.permissions);
472
+ const compatibilityWrite = broadMode ? [] : compatibilityPaths(policy, seams);
473
+ const runtimeWrite = [...new Set([
474
+ ...(policy.runtimeWrite ?? []).map((path) => canonicalizePath(path, seams)),
475
+ ...compatibilityWrite,
476
+ ])];
477
+ return {
478
+ writableRoot, denyWrite, home: policy.home,
479
+ ...(policy.permissions && {
480
+ permissions: { ...policy.permissions },
481
+ credentialPaths: broadMode ? broadCredentialPaths(policy.home, seams) : credentialFilePaths(policy.home, seams),
482
+ compatibilityWrite,
483
+ runtimeWrite,
484
+ }),
485
+ ...(broadMode && {
486
+ broad: compileBroadWrite(policy, writableRoot, runtimeWrite, seams),
487
+ }),
488
+ };
489
+ }
490
+
491
+ /** True when a permission profile selects the broad-write profile. */
492
+ export function isBroadWritePermissions(permissions: SandboxPermissions | undefined): boolean {
493
+ return permissions?.outsideProject === "write";
494
+ }
495
+
496
+ function expandHome(path: string, home: string): string {
497
+ return path === "~" ? home : path.startsWith("~/") ? join(home, path.slice(2)) : path;
498
+ }
499
+
500
+ /**
501
+ * A fixed-list location both as the literal entry under the canonical home and
502
+ * as the path it resolves to. A dotfiles manager (stow, chezmoi) makes
503
+ * `~/.zshrc` a symlink into an ordinary folder: guarding only the target would
504
+ * let a task remove the link and put a real file in its place.
505
+ */
506
+ function lexicalAndCanonical(home: string, name: string, seams: SandboxSeams): string[] {
507
+ const lexical = join(canonicalizePath(home, seams), name);
508
+ return [lexical, ...symlinkHops(lexical), canonicalizePath(lexical, seams)];
509
+ }
510
+
511
+ /**
512
+ * Every symlink directory entry met while resolving `path`, component by
513
+ * component (as `readlink` would follow them), plus where a dangling chain
514
+ * would land. A chain such as
515
+ * `~/.zshrc -> ~/.dotfiles/zshrc -> ~/dotfiles/zshrc` has an intermediate link
516
+ * in a removable directory; replacing it would retarget the protected entry, so
517
+ * each hop the user could replace is protected too. When a followed link
518
+ * points at something missing, creating it would give the entry content, so
519
+ * the first missing component (which covers every missing directory below it)
520
+ * and the full path it would resolve to are protected as well. Bounded: a loop
521
+ * or more than 40 hops stops the walk (such a path resolves to nothing).
522
+ */
523
+ function symlinkHops(path: string): string[] {
524
+ const { hops, unresolved } = walkSymlinks(path);
525
+ return [...hops, ...unresolved];
526
+ }
527
+
528
+ function walkSymlinks(path: string): { hops: string[]; unresolved: string[] } {
529
+ const hops: string[] = [];
530
+ const seen = new Set<string>();
531
+ let followed = 0;
532
+ const absolute = resolve(path);
533
+ let current = parse(absolute).root;
534
+ let pending = absolute.slice(current.length).split(sep);
535
+ while (pending.length) {
536
+ const component = pending.shift()!;
537
+ if (!component || component === ".") continue;
538
+ if (component === "..") { current = dirname(current); continue; }
539
+ const entry = join(current, component);
540
+ let link: boolean;
541
+ try {
542
+ link = lstatSync(entry).isSymbolicLink();
543
+ } catch {
544
+ // Missing. Only a followed link makes this a dangling target; a
545
+ // plain absent path is guarded as it is.
546
+ return { hops, unresolved: followed ? [...new Set([entry, resolve(entry, ...pending)])] : [] };
547
+ }
548
+ if (!link) { current = entry; continue; }
549
+ if (++followed > 40 || seen.has(entry)) break;
550
+ seen.add(entry);
551
+ // Only a link the user can replace matters (not e.g. macOS's root-owned /tmp -> private/tmp).
552
+ try { accessSync(current, constants.W_OK); hops.push(entry); } catch { /* immutable entry */ }
553
+ let target: string;
554
+ try { target = readlinkSync(entry); } catch { break; }
555
+ if (isAbsolute(target)) {
556
+ current = parse(target).root;
557
+ pending = [...target.slice(current.length).split(sep), ...pending];
558
+ } else {
559
+ pending = [...target.split(sep), ...pending];
560
+ }
561
+ }
562
+ return { hops, unresolved: [] };
563
+ }
564
+
565
+ /** Whether a symlink resolves to nothing: dangling (ENOENT), or looping or over 40 hops (ELOOP). */
566
+ function unresolvable(path: string): boolean {
567
+ try { statSync(path); return false; } catch { return true; }
568
+ }
569
+
570
+ function broadCredentialPaths(home: string, seams: SandboxSeams): string[] {
571
+ const configuredAgentDir = process.env.PI_CODING_AGENT_DIR;
572
+ return [...new Set([
573
+ ...credentialFilePaths(home, seams),
574
+ ...[...CREDENTIAL_LOCATIONS, ...BROAD_CREDENTIAL_LOCATIONS].flatMap((name) => lexicalAndCanonical(home, name, seams)),
575
+ ...(configuredAgentDir ? [resolve(expandHome(configuredAgentDir, home), "auth.json"),
576
+ ...symlinkHops(resolve(expandHome(configuredAgentDir, home), "auth.json"))] : []),
577
+ ])].sort();
578
+ }
579
+
580
+ function compileBroadWrite(
581
+ policy: SandboxWritePolicy,
582
+ writableRoot: string,
583
+ runtimeWrite: readonly string[],
584
+ seams: SandboxSeams,
585
+ ): CompiledBroadWrite {
586
+ const permissions = policy.permissions!;
587
+ const home = canonicalizePath(policy.home, seams);
588
+ if (home === sep || RUNTIME_ROOTS.some((root) => contains(canonicalizePath(root, seams), home))) {
589
+ throw new Error("The broad-write sandbox profile needs a real home directory, not / or a system runtime root.");
590
+ }
591
+ if (writableRoot === home || contains(writableRoot, home)) {
592
+ throw new Error("The broad-write sandbox profile needs a project directory inside or beside home, not home itself.");
593
+ }
594
+ const tempRoots = [...new Set((BROAD_TEMP_ROOTS[currentPlatform(seams)] ?? [])
595
+ .map((path) => canonicalizePath(path, seams)))];
596
+ const configuredAgentDir = process.env.PI_CODING_AGENT_DIR;
597
+ const codePaths = [...new Set([
598
+ ...CODE_LATER_LOCATIONS.flatMap((name) => lexicalAndCanonical(home, name, seams)),
599
+ ...(configuredAgentDir ? [resolve(expandHome(configuredAgentDir, home)),
600
+ ...symlinkHops(expandHome(configuredAgentDir, home)),
601
+ canonicalizePath(expandHome(configuredAgentDir, home), seams)] : []),
602
+ ])].sort();
603
+ return {
604
+ home,
605
+ tempRoots,
606
+ deleteRoots: [...new Set([
607
+ ...(permissions.projectFiles === "read-write" ? [writableRoot] : []),
608
+ ...runtimeWrite,
609
+ ])].sort(),
610
+ codePaths,
611
+ };
612
+ }
613
+
614
+ /** Inside a git worktree folder (`.worktrees/`, `*-worktrees/`) below `root`: its contents, not the folder. */
615
+ function insideWorktreeFolder(path: string, root: string): boolean {
616
+ if (!contains(root, path) || path === root) return false;
617
+ return path.slice(root.length + 1).split(sep).slice(0, -1)
618
+ .some((part) => part === ".worktrees" || /^[^/]+-worktrees$/.test(part));
619
+ }
620
+
621
+ /** Hidden entries of home, and git worktree folders anywhere under it. */
622
+ function disposableHomePath(path: string, home: string): boolean {
623
+ if (!contains(home, path) || path === home) return false;
624
+ return path.slice(home.length + 1).startsWith(".") || insideWorktreeFolder(path, home);
625
+ }
626
+
627
+ /**
628
+ * Canonicalize a write policy once so containment checks and backend rules
629
+ * agree on exactly which paths they are talking about.
630
+ */
631
+ export function compileWritePolicy(
632
+ policy: SandboxWritePolicy,
633
+ seams: SandboxSeams = {},
634
+ ): CompiledSandboxWritePolicy {
635
+ return compile(policy, seams, false);
636
+ }
637
+
638
+ function contains(root: string, target: string): boolean {
639
+ if (target === root) return true;
640
+ return target.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
641
+ }
642
+
643
+ /**
644
+ * Spell `path` the way the policy spells it when they differ only in case, on
645
+ * macOS. `canonicalizePath` fixes the case of every existing component on a
646
+ * case-insensitive volume, but a missing tail (`~/.NPMRC` while `~/.npmrc` is
647
+ * absent) keeps the caller's case, and the kernel still treats it as the
648
+ * protected name. Seatbelt matches paths case-insensitively on every volume,
649
+ * case-sensitive APFS included, so this folds on darwin without probing the
650
+ * volume: the pre-check decides as the kernel does (#354, #358). The longest
651
+ * policy path that matches case-insensitively wins. Other platforms never fold.
652
+ */
653
+ function alignCaseToPolicy(path: string, policy: CompiledSandboxWritePolicy, seams: SandboxSeams): string {
654
+ if (currentPlatform(seams) !== "darwin") return path;
655
+ const broad = policy.broad;
656
+ const candidates = [policy.writableRoot, ...policy.denyWrite, ...(policy.credentialPaths ?? []),
657
+ ...(policy.runtimeWrite ?? []), ...(policy.compatibilityWrite ?? []),
658
+ ...(broad ? [broad.home, ...broad.tempRoots, ...broad.deleteRoots, ...broad.codePaths] : [])];
659
+ const lower = path.toLowerCase();
660
+ if (lower.length !== path.length) return path;
661
+ let best: string | undefined;
662
+ for (const candidate of candidates) {
663
+ const folded = candidate.toLowerCase();
664
+ if (folded.length !== candidate.length || !contains(folded, lower)) continue;
665
+ if (!best || candidate.length > best.length) best = candidate;
666
+ }
667
+ if (!best || path.startsWith(best)) return path;
668
+ return `${best}${path.slice(best.length)}`;
669
+ }
670
+
671
+ function isCredential(path: string, policy: CompiledSandboxWritePolicy): boolean {
672
+ return (policy.credentialPaths ?? []).some((credential) => contains(credential, path));
673
+ }
674
+
675
+ function runtimeRoots(seams: SandboxSeams): string[] {
676
+ return [...new Set(READ_RUNTIME_ROOTS.map((path) => canonicalizePath(path, seams)))];
677
+ }
678
+
679
+ /** Decide read access using the same canonical path and capability precedence as writes. */
680
+ export function evaluateReadAccess(
681
+ target: string,
682
+ policy: CompiledSandboxWritePolicy,
683
+ seams: SandboxSeams = {},
684
+ ): ReadAccessDecision {
685
+ const path = alignCaseToPolicy(canonicalizePath(target, seams), policy, seams);
686
+ const permissions = policy.permissions;
687
+ if (!permissions) return { allowed: true, path };
688
+ if (policy.broad) {
689
+ const denied = (isCredential(path, policy) && permissions.storedCredentials === "off") ||
690
+ (permissions.projectFiles === "off" && contains(policy.writableRoot, path));
691
+ return denied ? { allowed: false, path, reason: "read-denied" } : { allowed: true, path };
692
+ }
693
+ const mode = isCredential(path, policy) ? permissions.storedCredentials
694
+ : policy.runtimeWrite?.some((root) => !policy.compatibilityWrite?.includes(root) && contains(root, path)) ? "read-write"
695
+ : contains(policy.writableRoot, path) ? permissions.projectFiles
696
+ : policy.compatibilityWrite?.some((root) => contains(root, path)) ? "read-write"
697
+ : path === sep || runtimeRoots(seams).some((root) => contains(root, path)) ? "read"
698
+ : permissions.outsideProject;
699
+ return mode === "off" ? { allowed: false, path, reason: "read-denied" } : { allowed: true, path };
700
+ }
701
+
702
+ /**
703
+ * Decide whether an in-process write to `target` is permitted by a compiled
704
+ * policy. This is the same containment rule the kernel backends enforce, for
705
+ * callers that mutate files directly instead of spawning a child.
706
+ */
707
+ export function evaluateWriteAccess(
708
+ target: string,
709
+ policy: CompiledSandboxWritePolicy,
710
+ seams: SandboxSeams = {},
711
+ ): WriteAccessDecision {
712
+ const path = alignCaseToPolicy(canonicalizePath(target, seams), policy, seams);
713
+ if (policy.broad) return evaluateBroadWrite(path, policy, policy.broad, seams);
714
+ if (!policy.permissions && !contains(policy.writableRoot, path)) {
715
+ return { allowed: false, path, reason: "outside-writable-root" };
716
+ }
717
+ for (const denied of policy.denyWrite) {
718
+ if (contains(denied, path)) {
719
+ return { allowed: false, path, reason: "write-denied", deniedBy: denied };
720
+ }
721
+ }
722
+ if (policy.permissions) {
723
+ const mode = isCredential(path, policy) ? policy.permissions.storedCredentials
724
+ : policy.runtimeWrite?.some((root) => !policy.compatibilityWrite?.includes(root) && contains(root, path)) ? "read-write"
725
+ : contains(policy.writableRoot, path) ? policy.permissions.projectFiles
726
+ : policy.compatibilityWrite?.some((root) => contains(root, path)) ? "read-write"
727
+ : contains(canonicalizePath("/dev", seams), path) ? "read-write"
728
+ : policy.permissions.outsideProject;
729
+ if (!canWrite(mode)) return { allowed: false, path, reason: "permission-denied" };
730
+ }
731
+ return { allowed: true, path };
732
+ }
733
+
734
+ function evaluateBroadWrite(
735
+ path: string,
736
+ policy: CompiledSandboxWritePolicy,
737
+ broad: CompiledBroadWrite,
738
+ seams: SandboxSeams,
739
+ ): WriteAccessDecision {
740
+ for (const denied of [...policy.denyWrite, ...broad.codePaths]) {
741
+ if (contains(denied, path)) return { allowed: false, path, reason: "write-denied", deniedBy: denied };
742
+ }
743
+ if (isCredential(path, policy)) return canWrite(policy.permissions!.storedCredentials)
744
+ ? { allowed: true, path } : { allowed: false, path, reason: "permission-denied" };
745
+ if (policy.runtimeWrite?.some((root) => contains(root, path))) return { allowed: true, path };
746
+ if (contains(policy.writableRoot, path)) {
747
+ return canWrite(policy.permissions!.projectFiles)
748
+ ? { allowed: true, path } : { allowed: false, path, reason: "permission-denied" };
749
+ }
750
+ if ([...broad.tempRoots, ...broad.deleteRoots, canonicalizePath("/dev", seams)].some((root) => contains(root, path))) {
751
+ return { allowed: true, path };
752
+ }
753
+ if (contains(broad.home, path)) {
754
+ // Linux cannot separate removal from writing, so its fallback keeps
755
+ // ordinary (non-dot) top-level home folders read-only instead.
756
+ if (currentPlatform(seams) === "linux" && !disposableHomePath(path, broad.home)) {
757
+ return { allowed: false, path, reason: "permission-denied" };
758
+ }
759
+ return { allowed: true, path };
760
+ }
761
+ return { allowed: false, path, reason: "permission-denied" };
762
+ }
763
+
764
+ /**
765
+ * Decide whether `target` may be removed or renamed away (unlink, rmdir,
766
+ * rename of the source, or rename over an existing destination). Outside the
767
+ * broad-write profile removal follows write access.
768
+ */
769
+ export function evaluateDeleteAccess(
770
+ target: string,
771
+ policy: CompiledSandboxWritePolicy,
772
+ seams: SandboxSeams = {},
773
+ ): WriteAccessDecision {
774
+ const write = evaluateWriteAccess(target, policy, seams);
775
+ const broad = policy.broad;
776
+ if (!write.allowed) return write;
777
+ const path = write.path;
778
+ if (!broad) {
779
+ // Project files = Write outside the broad profile: nothing in the
780
+ // project is removable except worktree folders' contents.
781
+ return policy.permissions?.projectFiles === "write" && contains(policy.writableRoot, path) &&
782
+ !insideWorktreeFolder(path, policy.writableRoot)
783
+ ? { allowed: false, path, reason: "delete-denied" } : write;
784
+ }
785
+ const anchors = broadProtectedPaths(policy, broad);
786
+ if (anchors.some((protectedPath) => protectedPath !== path && contains(path, protectedPath))) {
787
+ return { allowed: false, path, reason: "delete-denied" };
788
+ }
789
+ if (path === policy.writableRoot || contains(path, policy.writableRoot)) {
790
+ return { allowed: false, path, reason: "delete-denied" };
791
+ }
792
+ if ([...broad.tempRoots, ...broad.deleteRoots].some((root) => contains(root, path)) ||
793
+ disposableHomePath(path, broad.home)) {
794
+ return write;
795
+ }
796
+ return { allowed: false, path, reason: "delete-denied" };
797
+ }
798
+
799
+ /**
800
+ * Whether an already-canonical path lies where a Write level still allows
801
+ * removal: temp, hidden home entries, worktree folders, a Write & delete
802
+ * workspace and runtime scratch (broad profile), or a worktree folder inside a
803
+ * Project files = Write workspace. The leaf is not re-resolved, so a caller can
804
+ * ask about a symlink's own directory entry.
805
+ */
806
+ export function isRemovableUnderWrite(path: string, policy: CompiledSandboxWritePolicy): boolean {
807
+ const broad = policy.broad;
808
+ if (broad) {
809
+ if (broadProtectedPaths(policy, broad).some((guard) => contains(guard, path) || contains(path, guard))) return false;
810
+ return [...broad.tempRoots, ...broad.deleteRoots].some((root) => contains(root, path)) ||
811
+ disposableHomePath(path, broad.home);
812
+ }
813
+ return policy.permissions?.projectFiles === "write" && insideWorktreeFolder(path, policy.writableRoot);
814
+ }
815
+
816
+ /** Outcome of a finished snapshot attempt. */
817
+ export type RecoverySnapshotOutcome = { ok: boolean; detail: string };
818
+
819
+ /** Result of a best-effort recovery snapshot request. */
820
+ export type RecoverySnapshotResult =
821
+ | { started: true; done: Promise<RecoverySnapshotOutcome> }
822
+ | { started: false; reason: "not-needed" | "unsupported" | "rate-limited" };
823
+
824
+ export type RecoverySnapshotSeams = {
825
+ platform?: () => string;
826
+ now?: () => number;
827
+ /** Defaults to an unref'd `/usr/bin/tmutil localsnapshot` child with a 30 s limit. */
828
+ run?: () => Promise<RecoverySnapshotOutcome>;
829
+ };
830
+
831
+ let lastRecoverySnapshot = 0;
832
+ const RECOVERY_SNAPSHOT_INTERVAL_MS = 15 * 60 * 1000;
833
+
834
+ function runLocalSnapshot(): Promise<RecoverySnapshotOutcome> {
835
+ return new Promise((resolveOutcome) => {
836
+ let output = "";
837
+ let settled = false;
838
+ const finish = (outcome: RecoverySnapshotOutcome) => {
839
+ if (settled) return;
840
+ settled = true;
841
+ clearTimeout(timer);
842
+ resolveOutcome(outcome);
843
+ };
844
+ const child = spawn("/usr/bin/tmutil", ["localsnapshot"], {
845
+ env: { PATH: "/usr/bin:/bin", LANG: "C" }, stdio: ["ignore", "pipe", "pipe"],
846
+ });
847
+ const timer = setTimeout(() => { child.kill("SIGKILL"); finish({ ok: false, detail: "tmutil timed out after 30 s" }); }, 30_000);
848
+ timer.unref();
849
+ child.unref();
850
+ for (const stream of [child.stdout, child.stderr]) {
851
+ stream?.on("data", (chunk: Buffer) => { output = (output + chunk.toString()).slice(-2048); });
852
+ (stream as { unref?: () => void } | null)?.unref?.();
853
+ }
854
+ child.on("error", (error) => finish({ ok: false, detail: error.message }));
855
+ child.on("close", (code) => finish(code === 0
856
+ ? { ok: true, detail: output.trim() }
857
+ : { ok: false, detail: output.trim() || `tmutil exited ${code}` }));
858
+ });
859
+ }
860
+
861
+ /**
862
+ * Start an APFS local snapshot (`tmutil localsnapshot`) before a confined run
863
+ * whose Outside project level lets it change files outside the project: Write
864
+ * & delete can remove them, and Write can still truncate, chmod or chflags
865
+ * them in place. macOS only; it needs no elevated privileges. The snapshot
866
+ * runs in the background and never blocks or fails the run; callers log a
867
+ * failed outcome. Snapshots are volume-wide and purgeable, so one per 15
868
+ * minutes per process is enough. `PI_SANDBOX_RECOVERY_SNAPSHOT=off` disables it
869
+ * (test suites set it so they do not create real snapshots).
870
+ */
871
+ export function takeRecoverySnapshot(
872
+ permissions: SandboxPermissions | undefined,
873
+ seams: RecoverySnapshotSeams = {},
874
+ ): RecoverySnapshotResult {
875
+ if (!canWrite(permissions?.outsideProject) || process.env.PI_SANDBOX_RECOVERY_SNAPSHOT === "off") {
876
+ return { started: false, reason: "not-needed" };
877
+ }
878
+ if ((seams.platform ?? osPlatform)() !== "darwin") return { started: false, reason: "unsupported" };
879
+ const now = (seams.now ?? Date.now)();
880
+ if (lastRecoverySnapshot && now - lastRecoverySnapshot < RECOVERY_SNAPSHOT_INTERVAL_MS) {
881
+ return { started: false, reason: "rate-limited" };
882
+ }
883
+ lastRecoverySnapshot = now;
884
+ let done: Promise<RecoverySnapshotOutcome>;
885
+ try {
886
+ done = (seams.run ?? runLocalSnapshot)().catch((error: unknown) =>
887
+ ({ ok: false, detail: error instanceof Error ? error.message : String(error) }));
888
+ } catch (error) {
889
+ done = Promise.resolve({ ok: false, detail: error instanceof Error ? error.message : String(error) });
890
+ }
891
+ return { started: true, done };
892
+ }
893
+
894
+ /** Test hook: forget the last snapshot time. */
895
+ export function resetRecoverySnapshotClock(): void {
896
+ lastRecoverySnapshot = 0;
897
+ }
898
+
899
+ function broadProtectedPaths(policy: CompiledSandboxWritePolicy, broad: CompiledBroadWrite): string[] {
900
+ return [...policy.denyWrite,
901
+ ...(policy.permissions?.storedCredentials === "read-write" ? [] : policy.credentialPaths ?? []), ...broad.codePaths,
902
+ ...(!canWrite(policy.permissions?.projectFiles) ? [policy.writableRoot] : [])];
903
+ }
904
+
905
+ /** Quote a path as an SBPL string literal. */
906
+ function sbpl(path: string): string {
907
+ return `"${path.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
908
+ }
909
+
910
+ function validateRuntimeHome(policy: CompiledSandboxWritePolicy, seams: SandboxSeams): void {
911
+ if (policy.permissions?.outsideProject !== "off") return;
912
+ const home = canonicalizePath(policy.home, seams);
913
+ if (RUNTIME_ROOTS.some((root) => contains(canonicalizePath(root, seams), home))) {
914
+ throw new Error("outsideProject=off cannot expose a home under a required system runtime root; move the home or use another permission mode.");
915
+ }
916
+ }
917
+
918
+ function protectedAncestors(paths: readonly string[]): string[] {
919
+ const parents = new Set<string>();
920
+ for (const path of paths) {
921
+ for (let parent = dirname(path); dirname(parent) !== parent; parent = dirname(parent)) parents.add(parent);
922
+ }
923
+ return [...parents].sort((a, b) => a.length - b.length);
924
+ }
925
+
926
+ function buildPermissionProfile(policy: CompiledSandboxWritePolicy, seams: SandboxSeams): string {
927
+ validateRuntimeHome(policy, seams);
928
+ const permissions = policy.permissions!;
929
+ const protectedPaths = [
930
+ ...policy.denyWrite,
931
+ ...(permissions.projectFiles !== "read-write" ? [policy.writableRoot] : []),
932
+ ...(permissions.storedCredentials !== "read-write" ? policy.credentialPaths ?? [] : []),
933
+ ...(policy.compatibilityWrite ?? []),
934
+ ];
935
+ if (permissions.outsideProject === "write") throw new Error("Outside project = Write uses the broad-write profile.");
936
+ const rules = ["(version 1)", "(allow default)", "(deny file-write*)"];
937
+ if (permissions.outsideProject === "off") {
938
+ rules.push("(deny file-read*)", "(allow file-read-metadata)", '(allow file-read* (literal "/"))');
939
+ for (const root of runtimeRoots(seams)) {
940
+ rules.push(`(allow file-read* (subpath ${sbpl(root)}))`);
941
+ }
942
+ }
943
+ if (permissions.outsideProject === "read-write") rules.push("(allow file-write*)");
944
+ // Temporary host paths are not granted for off/read: doing so would expose
945
+ // other users' files in temp. /dev remains necessary for basic shell I/O.
946
+ for (const root of TEMP_ROOTS.filter((path) => permissions.outsideProject === "read-write" || path === "/dev")
947
+ .map((path) => canonicalizePath(path, seams))) {
948
+ rules.push(`(allow file-write* (subpath ${sbpl(root)}))`);
949
+ }
950
+ const scoped = (root: string, mode: SandboxPermissions["projectFiles"]) => {
951
+ if (mode === "off") rules.push(`(deny file-read* (subpath ${sbpl(root)}))`);
952
+ else rules.push(`(allow file-read* (subpath ${sbpl(root)}))`);
953
+ if (canWrite(mode)) rules.push(`(allow file-write* (subpath ${sbpl(root)}))`);
954
+ else rules.push(`(deny file-write* (subpath ${sbpl(root)}))`);
955
+ };
956
+ // Last matching SBPL rule wins. Credential rules override project and outside;
957
+ // explicit denyWrite entries always override every write allowance.
958
+ for (const path of policy.compatibilityWrite ?? []) scoped(path, "read-write");
959
+ scoped(policy.writableRoot, permissions.projectFiles);
960
+ if (permissions.projectFiles === "write" && !TEMP_ROOTS.filter((root) => root !== "/dev")
961
+ .some((root) => contains(canonicalizePath(root, seams), policy.writableRoot))) {
962
+ // Write without delete: only a worktree folder's contents stay removable.
963
+ const project = sbplRegexPath(policy.writableRoot);
964
+ rules.push(`(deny file-write-unlink (subpath ${sbpl(policy.writableRoot)}))`,
965
+ `(allow file-write-unlink (regex #"^${project}/(.+/)?[.]worktrees/."))`,
966
+ `(allow file-write-unlink (regex #"^${project}/(.+/)?[^/]+-worktrees/."))`);
967
+ }
968
+ for (const path of (policy.runtimeWrite ?? []).filter((path) => !policy.compatibilityWrite?.includes(path))) scoped(path, "read-write");
969
+ for (const path of policy.credentialPaths ?? []) scoped(path, permissions.storedCredentials);
970
+ // Explicit unlink denials too: a `file-write-unlink` allowance above would
971
+ // otherwise outrank a `file-write*` denial.
972
+ for (const path of policy.denyWrite) {
973
+ rules.push(`(deny file-write* (subpath ${sbpl(path)}))`);
974
+ if (permissions.projectFiles === "write") rules.push(`(deny file-write-unlink (subpath ${sbpl(path)}))`);
975
+ }
976
+ // Protect the directory entries, not their contents: unrelated children can
977
+ // still be created, while renaming a parent cannot move a denied subtree.
978
+ for (const path of protectedAncestors(protectedPaths)) rules.push(`(deny file-write-unlink (literal ${sbpl(path)}))`);
979
+ for (const path of policy.compatibilityWrite ?? []) rules.push(`(deny file-write-unlink (literal ${sbpl(path)}))`);
980
+ if (!permissions.network) rules.push("(deny network*)");
981
+ return [...rules, ""].join("\n");
982
+ }
983
+
984
+ /** Escape a canonical path for an SBPL regular expression literal. */
985
+ function sbplRegexPath(path: string): string {
986
+ return path.replace(/[\\.^$|?*+()[\]{}"]/g, (char) => `\\${char}`);
987
+ }
988
+
989
+ /**
990
+ * The broad-write profile on Seatbelt.
991
+ *
992
+ * Seatbelt has no separate rename operation: `file-write-unlink` guards unlink,
993
+ * rmdir, the source of a rename, and an existing destination a rename replaces.
994
+ * Denying it outside the disposable roots therefore refuses `rm`, `rm -rf` and
995
+ * `mv dir elsewhere`, and also a save that renames a temp file over an existing
996
+ * file there. Writing a file in place (truncate + write) stays allowed.
997
+ */
998
+ function buildBroadProfile(policy: CompiledSandboxWritePolicy, seams: SandboxSeams): string {
999
+ const permissions = policy.permissions!;
1000
+ const broad = policy.broad!;
1001
+ const rules = ["(version 1)", "(allow default)", "(deny file-write*)",
1002
+ `(allow file-write* (subpath ${sbpl(broad.home)}))`];
1003
+ const project = policy.writableRoot;
1004
+ for (const root of [...broad.tempRoots, canonicalizePath("/dev", seams), ...broad.deleteRoots,
1005
+ ...(policy.runtimeWrite ?? []), ...(canWrite(permissions.projectFiles) ? [project] : [])]) {
1006
+ rules.push(`(allow file-write* (subpath ${sbpl(root)}))`);
1007
+ }
1008
+ if (permissions.projectFiles === "off") rules.push(`(deny file-read* (subpath ${sbpl(project)}))`);
1009
+ rules.push("(deny file-write-unlink)");
1010
+ for (const root of [...broad.tempRoots, ...broad.deleteRoots]) {
1011
+ rules.push(`(allow file-write-unlink (subpath ${sbpl(root)}))`);
1012
+ }
1013
+ const home = sbplRegexPath(broad.home);
1014
+ rules.push(
1015
+ `(allow file-write-unlink (regex #"^${home}/[.][^/]+$"))`,
1016
+ `(allow file-write-unlink (regex #"^${home}/[.][^/]+/"))`,
1017
+ `(allow file-write-unlink (regex #"^${home}/(.+/)?[.]worktrees/."))`,
1018
+ `(allow file-write-unlink (regex #"^${home}/(.+/)?[^/]+-worktrees/."))`,
1019
+ );
1020
+ // Write-denied controls and credentials override every broad grant above. A rule naming
1021
+ // `file-write-unlink` outranks a `file-write*` wildcard whatever their
1022
+ // order (verified on the real kernel), so each protected path also gets an
1023
+ // explicit unlink denial; otherwise the removal grants above would reopen it.
1024
+ const denyWrite = (path: string) => rules.push(
1025
+ `(deny file-write* (subpath ${sbpl(path)}))`, `(deny file-write-unlink (subpath ${sbpl(path)}))`);
1026
+ if (!canWrite(permissions.projectFiles)) denyWrite(project);
1027
+ for (const path of broad.codePaths) denyWrite(path);
1028
+ for (const path of policy.credentialPaths ?? []) {
1029
+ if (permissions.storedCredentials === "off") rules.push(`(deny file-read* (subpath ${sbpl(path)}))`);
1030
+ if (permissions.storedCredentials !== "read-write") denyWrite(path);
1031
+ }
1032
+ for (const path of policy.denyWrite) denyWrite(path);
1033
+ // Renaming an ancestor would move a protected subtree to an unprotected path,
1034
+ // and renaming the workspace's ancestors could redirect the next launch.
1035
+ const anchors = [...broadProtectedPaths(policy, broad), project];
1036
+ for (const path of [...new Set([...protectedAncestors(anchors), project])]) {
1037
+ rules.push(`(deny file-write-unlink (literal ${sbpl(path)}))`);
1038
+ }
1039
+ if (!permissions.network) rules.push("(deny network*)");
1040
+ return [...rules, ""].join("\n");
1041
+ }
1042
+
1043
+ /** Build the macOS sandbox-exec wrapper and its SBPL profile. */
1044
+ function buildMacOSSandboxCommand(args: SandboxCommandArgs, seams: SandboxSeams): SandboxCommand {
1045
+ // Match on the real (symlink-resolved) path — sandbox-exec evaluates the
1046
+ // canonical path, so /tmp/x must be written as /private/tmp/x.
1047
+ const policy = compile(args.policy, seams, false);
1048
+
1049
+ const profile = policy.broad ? buildBroadProfile(policy, seams)
1050
+ : policy.permissions ? buildPermissionProfile(policy, seams) : [
1051
+ "(version 1)",
1052
+ "(allow default)", // permissive base: reads, exec, network
1053
+ "(deny file-write*)", // ...then deny all writes...
1054
+ `(allow file-write* (subpath ${sbpl(policy.writableRoot)}))`, // ...except here
1055
+ `(allow file-write* (subpath ${sbpl(`${policy.home}/.pi`)}))`, // pi state
1056
+ '(allow file-write* (subpath "/private/var/folders"))', // macOS temp / our runtime
1057
+ '(allow file-write* (subpath "/private/tmp"))',
1058
+ '(allow file-write* (subpath "/dev"))', // /dev/null etc.
1059
+ // Deny rules come last: SBPL applies the last matching rule, so these
1060
+ // carve holes back out of the allowances above.
1061
+ ...policy.denyWrite.map((path) => `(deny file-write* (subpath ${sbpl(path)}))`),
1062
+ "",
1063
+ ].join("\n");
1064
+ (seams.writeProfile ?? writeFileSync)(args.profilePath, profile);
1065
+
1066
+ return {
1067
+ file: MACOS_SANDBOX_EXEC,
1068
+ fileArgs: ["-f", args.profilePath, args.execPath, ...args.execArgs],
1069
+ };
1070
+ }
1071
+
1072
+ const macOSSandboxBackend: SandboxBackend = {
1073
+ id: "macos-seatbelt",
1074
+ executable: MACOS_SANDBOX_EXEC,
1075
+ buildCommand: buildMacOSSandboxCommand,
1076
+ };
1077
+
1078
+ /** Resolve only a root-owned system executable; never inspect task PATH. */
1079
+ function systemSandboxExecutable(name: string): string | undefined {
1080
+ // Never resolve the host-side confinement launcher through task-influenced PATH.
1081
+ for (const directory of ["/usr/bin", "/bin"]) {
1082
+ const candidate = join(directory, name);
1083
+ try {
1084
+ const info = statSync(candidate);
1085
+ if (!info.isFile() || info.uid !== 0 || (info.mode & 0o022) !== 0) continue;
1086
+ accessSync(candidate, constants.X_OK);
1087
+ return candidate;
1088
+ } catch { /* Try the next system location. */ }
1089
+ }
1090
+ return undefined;
1091
+ }
1092
+
1093
+ export function executableFromPath(name: string): string | undefined {
1094
+ const path = process.env.PATH;
1095
+ if (!path) return undefined;
1096
+
1097
+ for (const entry of path.split(delimiter)) {
1098
+ const candidate = resolve(entry || ".", name);
1099
+ try {
1100
+ if (!statSync(candidate).isFile()) continue;
1101
+ accessSync(candidate, constants.X_OK);
1102
+ return candidate;
1103
+ } catch {
1104
+ // A PATH entry may disappear or be inaccessible between lookup and use.
1105
+ }
1106
+ }
1107
+ return undefined;
1108
+ }
1109
+
1110
+ /**
1111
+ * Give an absent denied path something the kernel can hold out.
1112
+ *
1113
+ * A mount needs a mount point. `--ro-bind-try` skips a source that does not
1114
+ * exist, so before this a denied path that had not been created yet was not
1115
+ * denied at all: inside the sandbox `echo secret > .env.local` simply created
1116
+ * it. `.env` and `.env.local` are absent in most projects, which made the
1117
+ * packaged defaults hold on macOS — SBPL denies by resolved path, existing or
1118
+ * not — and not on Linux.
1119
+ *
1120
+ * Nothing bubblewrap offers closes that without a mount point, and every
1121
+ * bubblewrap operation that would create one (`--dir`, `--file`, `--tmpfs`)
1122
+ * creates it through the read-write bind of the project, which is to say on the
1123
+ * real filesystem anyway. So the placeholder is created here, deliberately and
1124
+ * visibly, rather than as a side effect of a mount operation.
1125
+ *
1126
+ * An empty regular file is the least destructive placeholder: a later
1127
+ * `cp .env.example .env` overwrites it, where an empty *directory* at that path
1128
+ * would fail. Callers whose denied entry has to be a directory create it before
1129
+ * building the command, and an entry that already exists — file or directory —
1130
+ * is bound as it is. The file is created with O_EXCL, so anything that appears
1131
+ * in the meantime is bound rather than clobbered, and it is left in place
1132
+ * afterwards because a resumed task re-runs the launch vector it captured and
1133
+ * its `--ro-bind` sources have to still be there.
1134
+ *
1135
+ * Returns false when the placeholder could not be created. Callers must fail
1136
+ * closed for writable regions: a task may replace or chmod the blocking parent.
1137
+ */
1138
+ function materializeDenyPath(path: string): boolean {
1139
+ if (existsSync(path)) return true;
1140
+ try {
1141
+ mkdirSync(dirname(path), { recursive: true });
1142
+ closeSync(openSync(path, "wx"));
1143
+ return true;
1144
+ } catch {
1145
+ // Re-check rather than trust the errno. EEXIST from the O_EXCL create
1146
+ // means the path appeared in between, which is the outcome we wanted and
1147
+ // not ours to overwrite; EEXIST from the mkdir means a parent is a
1148
+ // regular file, and nothing can exist under it. Only the first leaves a
1149
+ // source a bind can use.
1150
+ return existsSync(path);
1151
+ }
1152
+ }
1153
+
1154
+ /**
1155
+ * Whether a denied path lies in a region this backend binds read-write.
1156
+ *
1157
+ * Everywhere else is already covered by the read-only bind of `/`, so a
1158
+ * placeholder there would deny nothing that is not denied already — and would
1159
+ * scatter empty files across the host for the sake of it. Materializing is
1160
+ * confined to the two regions that are genuinely writable inside the sandbox:
1161
+ * the writable root, and the `/tmp` rebind that pi's own tooling needs.
1162
+ */
1163
+ function writableInsideLinuxSandbox(path: string, writableRoot: string): boolean {
1164
+ return contains(writableRoot, path) || contains("/tmp", path);
1165
+ }
1166
+
1167
+ function buildLinuxSandboxCommand(
1168
+ bwrap: string,
1169
+ args: SandboxCommandArgs,
1170
+ seams: SandboxSeams,
1171
+ ): SandboxCommand {
1172
+ // The caller creates the selected work directory before it reaches this
1173
+ // boundary. Canonicalizing it before bind-mounting keeps symlink aliases from
1174
+ // widening the writable root.
1175
+ const policy = compile(args.policy, seams, true);
1176
+ if (policy.broad) return buildLinuxBroadCommand(bwrap, args, policy, seams);
1177
+ if (policy.permissions) return buildLinuxPermissionCommand(bwrap, args, policy, seams);
1178
+ const materialize = seams.materializeDenyPath ?? materializeDenyPath;
1179
+ const denyBinds = policy.denyWrite.flatMap((path) => {
1180
+ const writable = writableInsideLinuxSandbox(path, policy.writableRoot);
1181
+ if (writable && !materialize(path)) throw new Error(`Cannot protect denied path: ${path}`);
1182
+ return [writable ? "--ro-bind" : "--ro-bind-try", path, path];
1183
+ });
1184
+ return {
1185
+ file: bwrap,
1186
+ fileArgs: [
1187
+ "--ro-bind", "/", "/",
1188
+ "--bind", policy.writableRoot, policy.writableRoot,
1189
+ "--bind", "/tmp", "/tmp",
1190
+ "--dev", "/dev",
1191
+ // Layered last so a denied path wins over every writable bind above.
1192
+ // A denied path need not exist yet, so one inside a writable region
1193
+ // is materialized first; `-try` remains for the paths that are
1194
+ // read-only regardless. A writable region whose guard cannot be
1195
+ // materialized must fail before launching the task.
1196
+ ...denyBinds,
1197
+ "--",
1198
+ args.execPath, ...args.execArgs,
1199
+ ],
1200
+ };
1201
+ }
1202
+
1203
+ function buildLinuxPermissionCommand(
1204
+ bwrap: string,
1205
+ args: SandboxCommandArgs,
1206
+ policy: CompiledSandboxWritePolicy,
1207
+ seams: SandboxSeams,
1208
+ ): SandboxCommand {
1209
+ const permissions = policy.permissions!;
1210
+ validateRuntimeHome(policy, seams);
1211
+ if (permissions.projectFiles === "write" || permissions.outsideProject === "write") {
1212
+ throw new Error("Linux bubblewrap cannot separate removal from writing for Project files; use Write & delete or Read.");
1213
+ }
1214
+ const project = policy.writableRoot;
1215
+ const credentials = policy.credentialPaths ?? [];
1216
+ const writableProject = permissions.projectFiles === "read-write";
1217
+ const overlappingCredentials = credentials.filter((path) => contains(project, path));
1218
+ if (credentials.some((path) => contains(path, project)) &&
1219
+ permissions.projectFiles !== permissions.storedCredentials) {
1220
+ throw new Error("Linux bubblewrap cannot apply differing project and credential permissions when a credential directory contains the project.");
1221
+ }
1222
+ if (writableProject && policy.denyWrite.some((path) => contains(path, project))) {
1223
+ throw new Error("Linux bubblewrap cannot make a project writable inside a write-denied directory.");
1224
+ }
1225
+ // Protected leaves and their writable ancestors become mount points below.
1226
+ // Linux refuses renaming mount points, preventing ancestor replacement.
1227
+ if (permissions.outsideProject === "read-write" && (
1228
+ permissions.projectFiles !== "read-write" || permissions.storedCredentials !== "read-write" ||
1229
+ policy.denyWrite.length > 0
1230
+ )) {
1231
+ throw new Error("Linux bubblewrap cannot enforce restricted project/credential/denyWrite paths under a writable outsideProject mount.");
1232
+ }
1233
+ if (permissions.outsideProject === "read" && permissions.storedCredentials === "read-write" &&
1234
+ credentials.some((path) => !contains(project, path))) {
1235
+ throw new Error("Linux bubblewrap cannot write credential stores under a read-only outsideProject root.");
1236
+ }
1237
+ if (permissions.projectFiles === "read" && permissions.storedCredentials === "read-write" &&
1238
+ overlappingCredentials.length > 0) {
1239
+ throw new Error("Linux bubblewrap cannot write credential stores under a read-only project mount.");
1240
+ }
1241
+ if (permissions.outsideProject === "read" && permissions.storedCredentials === "off") {
1242
+ throw new Error("Linux bubblewrap cannot hide stored credentials in a read-only whole-root bind.");
1243
+ }
1244
+ if (permissions.outsideProject === "off" && permissions.storedCredentials === "off" &&
1245
+ credentials.some((path) => contains(project, path) && permissions.projectFiles !== "off")) {
1246
+ throw new Error("Linux bubblewrap cannot hide credentials inside a visible read-only project.");
1247
+ }
1248
+ if (permissions.outsideProject === "off" && permissions.projectFiles === "off" &&
1249
+ RUNTIME_ROOTS.some((root) => contains(canonicalizePath(root, seams), project))) {
1250
+ throw new Error("Linux bubblewrap cannot hide a project nested under a required system runtime bind.");
1251
+ }
1252
+ if (permissions.outsideProject === "off" && credentials.some((path) =>
1253
+ !contains(project, path) &&
1254
+ RUNTIME_ROOTS.some((root) => contains(canonicalizePath(root, seams), path)) &&
1255
+ permissions.storedCredentials === "off")) {
1256
+ throw new Error("Linux bubblewrap cannot hide credentials under a required system runtime bind.");
1257
+ }
1258
+ if (permissions.outsideProject === "off" && permissions.storedCredentials === "read-write" &&
1259
+ credentials.some((path) => !contains(project, path))) {
1260
+ throw new Error("Linux bubblewrap cannot create or safely bind writable credential stores outside a hidden root.");
1261
+ }
1262
+ if (permissions.outsideProject === "off" && permissions.projectFiles === "off" &&
1263
+ permissions.storedCredentials !== "off" && credentials.some((path) => contains(project, path))) {
1264
+ throw new Error("Linux bubblewrap cannot expose credentials inside a hidden project without exposing the project.");
1265
+ }
1266
+ if (permissions.outsideProject !== "off" && permissions.projectFiles === "off") {
1267
+ throw new Error("Linux bubblewrap cannot hide a project inside a visible outsideProject root.");
1268
+ }
1269
+ const mounts: string[] = permissions.outsideProject === "off" ? ["--tmpfs", "/"]
1270
+ : [permissions.outsideProject === "read" ? "--ro-bind" : "--bind", "/", "/"];
1271
+ if (permissions.outsideProject === "off") {
1272
+ // Bounded system executable/library roots only. /tmp is private, not a
1273
+ // host bind: otherwise outsideProject=off would expose user temp data.
1274
+ for (const root of RUNTIME_ROOTS) {
1275
+ if (existsSync(root)) mounts.push("--ro-bind", root, root);
1276
+ }
1277
+ mounts.push("--tmpfs", "/tmp");
1278
+ if (args.internalHelperExecutable) {
1279
+ const executable = canonicalizePath(args.execPath, seams);
1280
+ if (!RUNTIME_ROOTS.some((root) => contains(canonicalizePath(root, seams), executable))) {
1281
+ mounts.push("--ro-bind", executable, executable);
1282
+ }
1283
+ }
1284
+ } else {
1285
+ mounts.push(permissions.outsideProject === "read" && !policy.compatibilityWrite?.includes(canonicalizePath("/tmp", seams)) ? "--ro-bind" : "--bind", "/tmp", "/tmp");
1286
+ }
1287
+ mounts.push("--dev", "/dev");
1288
+ const scopedMounts: { option: "--bind" | "--ro-bind"; path: string }[] = [];
1289
+ const writableAncestors = new Set<string>();
1290
+ const readOnlyGuards = new Set<string>();
1291
+ if (permissions.outsideProject === "off" && permissions.storedCredentials === "read") {
1292
+ for (const path of credentials) {
1293
+ if (existsSync(path) && !contains(project, path)) readOnlyGuards.add(path);
1294
+ }
1295
+ }
1296
+ // A broad /tmp bind is already present for visible outside roots. Cover
1297
+ // existing leaves and absent leaves via a read-only existing ancestor; do
1298
+ // not create credential or control files in host runtime directories.
1299
+ const compatibility = policy.compatibilityWrite ?? [];
1300
+ if (compatibility.length) {
1301
+ const tmp = canonicalizePath("/tmp", seams);
1302
+ const protectedInTmp = [...policy.denyWrite, ...(permissions.storedCredentials !== "read-write" ? credentials : [])]
1303
+ .filter((path) => contains(tmp, path) && !contains(project, path));
1304
+ if (permissions.storedCredentials === "off" && protectedInTmp.some((path) =>
1305
+ credentials.some((credential) => credential === path))) {
1306
+ throw new Error("Linux bubblewrap cannot hide credentials under a writable runtime directory.");
1307
+ }
1308
+ if (policy.denyWrite.some((path) => contains(path, tmp))) {
1309
+ throw new Error("Runtime directory overlaps a write-denied control path.");
1310
+ }
1311
+ const guards = new Set<string>();
1312
+ for (const path of protectedInTmp) {
1313
+ let guard = path;
1314
+ while (!existsSync(guard) && contains(tmp, guard) && guard !== tmp) guard = dirname(guard);
1315
+ if (guard === tmp || !contains(tmp, guard)) {
1316
+ throw new Error("Cannot protect an absent path directly under writable runtime directory.");
1317
+ }
1318
+ guards.add(guard);
1319
+ }
1320
+ for (const guard of [...guards].sort((a, b) => a.length - b.length)) {
1321
+ if ([...guards].some((parent) => parent !== guard && contains(parent, guard))) continue;
1322
+ for (const parent of protectedAncestors([guard]).filter((parent) => contains(tmp, parent) && parent !== tmp)) {
1323
+ writableAncestors.add(parent);
1324
+ }
1325
+ readOnlyGuards.add(guard);
1326
+ }
1327
+ // A writable /tmp can rename any directory above the captured project
1328
+ // root, then substitute a symlink before the next launch. Anchor each
1329
+ // ancestor even when there are no explicit control or credential guards.
1330
+ if (permissions.projectFiles !== "off" && contains(tmp, project)) {
1331
+ for (const parent of protectedAncestors([project]).filter((path) => contains(tmp, path) && path !== tmp)) {
1332
+ writableAncestors.add(parent);
1333
+ }
1334
+ }
1335
+ }
1336
+ if (permissions.projectFiles !== "off") {
1337
+ scopedMounts.push({ option: writableProject ? "--bind" : "--ro-bind", path: project });
1338
+ }
1339
+ for (const path of policy.runtimeWrite ?? []) {
1340
+ if (compatibility.includes(path)) continue;
1341
+ if (credentials.some((protectedPath) => contains(path, protectedPath) || contains(protectedPath, path)) ||
1342
+ policy.denyWrite.some((protectedPath) => contains(protectedPath, path))) {
1343
+ throw new Error("Runtime directory overlaps protected credentials or control paths.");
1344
+ }
1345
+ scopedMounts.push({ option: "--bind", path });
1346
+ }
1347
+ const protectedPaths = [...policy.denyWrite,
1348
+ ...(permissions.storedCredentials !== "read-write" ? overlappingCredentials : [])];
1349
+ for (const writableRoot of [...(writableProject ? [project] : []),
1350
+ ...(policy.runtimeWrite ?? []).filter((path) => !compatibility.includes(path))]) {
1351
+ const materialize = seams.materializeDenyPath ?? materializeDenyPath;
1352
+ const leaves = protectedPaths.filter((path) => contains(writableRoot, path));
1353
+ for (const path of leaves) {
1354
+ if (!materialize(path)) throw new Error(`Cannot protect denied path: ${path}`);
1355
+ }
1356
+ for (const parent of protectedAncestors(leaves).filter((path) => contains(writableRoot, path) && path !== writableRoot)) {
1357
+ writableAncestors.add(parent);
1358
+ }
1359
+ for (const path of leaves) readOnlyGuards.add(path);
1360
+ }
1361
+ // A nearest-existing guard can be an ancestor of an unrelated writable
1362
+ // project (e.g. absent ~/.npmrc with a project under ~/work). Mount that
1363
+ // broad guard in path order, keeping its intervening anchors read-only;
1364
+ // only the disjoint project subtree may be rebound writable afterwards.
1365
+ const ancestorGuards = [...readOnlyGuards].filter((guard) =>
1366
+ scopedMounts.some(({ option, path }) => option === "--bind" && guard !== path && contains(guard, path)));
1367
+ for (const guard of ancestorGuards) {
1368
+ scopedMounts.push({ option: "--ro-bind", path: guard });
1369
+ readOnlyGuards.delete(guard);
1370
+ }
1371
+ for (const path of writableAncestors) scopedMounts.push({
1372
+ option: ancestorGuards.some((guard) => contains(guard, path)) ? "--ro-bind" : "--bind", path,
1373
+ });
1374
+ scopedMounts.sort((a, b) => a.path.length - b.path.length);
1375
+ for (const { option, path } of scopedMounts) mounts.push(option, path, path);
1376
+ for (const path of [...readOnlyGuards].sort((a, b) => a.length - b.length)) {
1377
+ mounts.push("--ro-bind", path, path);
1378
+ }
1379
+ return {
1380
+ file: bwrap,
1381
+ fileArgs: [...mounts, ...(!permissions.network ? ["--unshare-net"] : []),
1382
+ "--", args.execPath, ...args.execArgs],
1383
+ };
1384
+ }
1385
+
1386
+ type DirectoryEntry = { name: string; directory: boolean; symlink: boolean };
1387
+
1388
+ function systemListDirectory(path: string): DirectoryEntry[] {
1389
+ try {
1390
+ return readdirSync(path, { withFileTypes: true }).map((entry) => ({
1391
+ name: entry.name, directory: entry.isDirectory(), symlink: entry.isSymbolicLink(),
1392
+ }));
1393
+ } catch {
1394
+ return [];
1395
+ }
1396
+ }
1397
+
1398
+ /**
1399
+ * Worktree folders (`.worktrees`, `*-worktrees`) within three levels of home.
1400
+ * Bounded so a large home cannot stall a launch; a folder created after launch
1401
+ * or deeper than that stays read-only on Linux.
1402
+ */
1403
+ function discoverWorktreeFolders(home: string, list: (path: string) => DirectoryEntry[]): string[] {
1404
+ const found: string[] = [];
1405
+ let budget = 4000;
1406
+ const walk = (directory: string, depth: number) => {
1407
+ for (const entry of list(directory)) {
1408
+ if (--budget < 0 || !entry.directory || entry.symlink) continue;
1409
+ const path = join(directory, entry.name);
1410
+ if (entry.name === ".worktrees" || entry.name.endsWith("-worktrees")) found.push(path);
1411
+ else if (!entry.name.startsWith(".") && depth < 3) walk(path, depth + 1);
1412
+ }
1413
+ };
1414
+ walk(home, 1);
1415
+ return found;
1416
+ }
1417
+
1418
+ /** Empty, mode-000 mask sources a hidden credential is bound over. */
1419
+ function maskSources(profilePath: string): { directory: string; file: string } {
1420
+ const base = join(dirname(profilePath), ".pi-sandbox-mask");
1421
+ mkdirSync(base, { recursive: true, mode: 0o700 });
1422
+ const directory = join(base, "directory");
1423
+ const file = join(base, "file");
1424
+ if (!existsSync(directory)) mkdirSync(directory, { mode: 0o000 });
1425
+ if (!existsSync(file)) closeSync(openSync(file, "wx", 0o000));
1426
+ for (const [path, isDirectory] of [[directory, true], [file, false]] as const) {
1427
+ const info = lstatSync(path);
1428
+ if (info.isDirectory() !== isDirectory || (info.mode & 0o777) !== 0 || (!isDirectory && info.size !== 0)) {
1429
+ throw new Error(`Unsafe sandbox mask source: ${path}`);
1430
+ }
1431
+ }
1432
+ return { directory, file };
1433
+ }
1434
+
1435
+ /**
1436
+ * The broad-write profile on Bubblewrap.
1437
+ *
1438
+ * Mount namespaces cannot separate removal from writing, and Landlock is not
1439
+ * reachable from Node or bwrap here, so Linux uses the documented fallback:
1440
+ * the root is read-only; temp, the workspace, hidden home entries and worktree
1441
+ * folders are writable (removal included); ordinary top-level home folders and
1442
+ * home itself stay read-only, so sibling repositories cannot even be edited in
1443
+ * place there. Off credentials are masked by empty mode-000 mounts, Read
1444
+ * credentials are read-only binds, and Read / write credentials follow the
1445
+ * surrounding broad-write rules. Code that runs later and caller-denied paths
1446
+ * are read-only binds. Every writable bind and protected leaf is a mount point,
1447
+ * which Linux refuses to rename. A protected
1448
+ * symlink inside a writable directory (a stow link in `~/.config`) makes that
1449
+ * directory read-only with each existing entry bound writable again, so only
1450
+ * new top-level entries there are refused.
1451
+ */
1452
+ function buildLinuxBroadCommand(
1453
+ bwrap: string,
1454
+ args: SandboxCommandArgs,
1455
+ policy: CompiledSandboxWritePolicy,
1456
+ seams: SandboxSeams,
1457
+ ): SandboxCommand {
1458
+ const permissions = policy.permissions!;
1459
+ const broad = policy.broad!;
1460
+ const project = policy.writableRoot;
1461
+ if (permissions.projectFiles === "off") {
1462
+ throw new Error("Linux bubblewrap cannot hide a project inside the broad-write profile's visible root.");
1463
+ }
1464
+ if (permissions.projectFiles === "write") {
1465
+ throw new Error("Linux bubblewrap cannot separate removal from writing for Project files; use Write & delete or Read.");
1466
+ }
1467
+ const credentials = policy.credentialPaths ?? [];
1468
+ const protectedCredentials = permissions.storedCredentials === "read-write" ? [] : credentials;
1469
+ const writeDenied = [...broad.codePaths, ...policy.denyWrite];
1470
+ if (permissions.projectFiles === "read-write" &&
1471
+ [...protectedCredentials, ...writeDenied].some((path) => path !== project && contains(path, project))) {
1472
+ throw new Error("Linux bubblewrap cannot make a project writable inside a protected directory.");
1473
+ }
1474
+ const list = seams.listDirectory ?? systemListDirectory;
1475
+ const exists = (path: string) => (seams.pathExists ?? existsSync)(path);
1476
+ const protectedPaths = [...protectedCredentials, ...writeDenied];
1477
+ const insideProtected = (path: string) => protectedPaths.some((guard) => contains(guard, path));
1478
+
1479
+ const writable = new Set<string>();
1480
+ for (const root of broad.tempRoots) if (exists(root)) writable.add(root);
1481
+ for (const entry of list(broad.home)) {
1482
+ if (entry.symlink) continue;
1483
+ const path = join(broad.home, entry.name);
1484
+ if (entry.name.startsWith(".") && !insideProtected(path)) writable.add(path);
1485
+ }
1486
+ for (const path of discoverWorktreeFolders(broad.home, list)) if (!insideProtected(path)) writable.add(path);
1487
+ for (const path of [...broad.deleteRoots, ...(policy.runtimeWrite ?? [])]) {
1488
+ if (path === project || !exists(path)) continue;
1489
+ if (insideProtected(path)) throw new Error(`Writable sandbox root overlaps a protected path: ${path}`);
1490
+ writable.add(path);
1491
+ }
1492
+ if (permissions.projectFiles === "read-write") writable.add(project);
1493
+ const writableRoots = [...writable];
1494
+ const writableAt = (path: string) => writableRoots.some((root) => contains(root, path));
1495
+
1496
+ const mask = (seams.maskSources ?? maskSources)(args.profilePath);
1497
+ const materialize = seams.materializeDenyPath ?? materializeDenyPath;
1498
+ const hidden: { path: string; source: string }[] = [];
1499
+ const readOnly = new Set<string>();
1500
+ const directoryLocation = (path: string) => [...DIRECTORY_LOCATIONS]
1501
+ .some((name) => canonicalizePath(join(broad.home, name), seams) === path);
1502
+ // The literal fixed-list entry (a dangling `~/.ssh` link) or its canonical path.
1503
+ const directoryEntry = (path: string) => directoryLocation(path) ||
1504
+ [...DIRECTORY_LOCATIONS].some((name) => join(broad.home, name) === path);
1505
+ // Directories holding a protected symlink: read-only, so the link cannot be
1506
+ // replaced, with their existing entries bound writable again below.
1507
+ const linkParents = new Set<string>();
1508
+ // Where dangling links would land. Only the first missing component of each
1509
+ // needs a guard: nothing can be created below a read-only mount or a locked
1510
+ // parent. It is a directory when more of the path lies below it, or when the
1511
+ // link is a directory-type entry (`~/.ssh -> ~/work/ssh`).
1512
+ const firstMissing = new Map<string, boolean>();
1513
+ const belowFirstMissing = new Set<string>();
1514
+ for (const path of protectedPaths) {
1515
+ const unresolved = walkSymlinks(path).unresolved;
1516
+ if (!unresolved.length) continue;
1517
+ const first = unresolved[0]!;
1518
+ const full = unresolved.at(-1)!;
1519
+ firstMissing.set(first, firstMissing.get(first) === true || first !== full || directoryEntry(path));
1520
+ if (full !== first) belowFirstMissing.add(full);
1521
+ }
1522
+ const created: string[] = [];
1523
+ const makeDirectory = seams.makeDirectory ?? ((target: string) => mkdirSync(target, { recursive: true, mode: 0o700 }));
1524
+ const guard = (path: string, hide: boolean) => {
1525
+ let directory: boolean | undefined;
1526
+ let link = false;
1527
+ try { link = lstatSync(path).isSymbolicLink(); } catch { /* absent or intermediate link */ }
1528
+ if (canonicalizePath(path, seams) !== path || (link && unresolvable(path))) {
1529
+ // A literal twin of a canonical deny entry: its target is guarded on
1530
+ // its own. A looping link resolves to nothing (ELOOP), and a dangling
1531
+ // one's missing target is guarded below, so only the link itself
1532
+ // needs guarding here. A symlink leaf inside a writable root could be
1533
+ // replaced, so its directory is protected; home already is.
1534
+ if (link && dirname(path) !== broad.home && writableAt(dirname(path))) linkParents.add(dirname(path));
1535
+ return;
1536
+ }
1537
+ if (belowFirstMissing.has(path) && !firstMissing.has(path)) return; // Its first missing component is guarded.
1538
+ if (firstMissing.has(path)) {
1539
+ // Where a dangling link would land: nothing may be created there.
1540
+ // A missing directory gets an empty read-only placeholder directory,
1541
+ // so only that one name is taken, not every new entry beside it
1542
+ // (`~/.cache/<tool>/…` would otherwise lock all of `~/.cache`). A
1543
+ // missing file is not planted in the user's files: its parent is
1544
+ // locked instead (entries stay writable, see below), except in the
1545
+ // workspace root and temp, which must keep accepting new entries,
1546
+ // so the file placeholder is bound there. Each placeholder made is
1547
+ // reported, and the workspace and temp fail closed without one.
1548
+ if (!writableAt(path)) return;
1549
+ const ancestor = dirname(path);
1550
+ if (ancestor === broad.home) return; // Home is read-only already.
1551
+ const failClosed = ancestor === project || broad.tempRoots.includes(ancestor);
1552
+ const directory = firstMissing.get(path)!;
1553
+ if (directory || failClosed) {
1554
+ const existed = exists(path);
1555
+ let made: boolean;
1556
+ if (directory) {
1557
+ try { makeDirectory(path); } catch { /* Re-checked below. */ }
1558
+ made = exists(path);
1559
+ } else {
1560
+ made = materialize(path);
1561
+ }
1562
+ if (made) {
1563
+ if (!existed) created.push(`${path}${directory ? "/" : ""}`);
1564
+ readOnly.add(path);
1565
+ return;
1566
+ }
1567
+ if (failClosed) throw new Error(`Cannot protect denied path: ${path}`);
1568
+ }
1569
+ linkParents.add(ancestor);
1570
+ return;
1571
+ }
1572
+ if (!exists(path)) {
1573
+ if (!writableAt(path)) return; // Nothing inside the sandbox can create it.
1574
+ let ancestor = dirname(path);
1575
+ while (!exists(ancestor) && dirname(ancestor) !== ancestor) ancestor = dirname(ancestor);
1576
+ if (directoryLocation(path)) {
1577
+ (seams.makeDirectory ?? ((target: string) => mkdirSync(target, { recursive: true, mode: 0o700 })))(path);
1578
+ directory = true;
1579
+ } else if (writableRoots.includes(ancestor) || contains(project, ancestor) ||
1580
+ broad.tempRoots.some((root) => contains(root, ancestor))) {
1581
+ if (!materialize(path)) throw new Error(`Cannot protect denied path: ${path}`);
1582
+ } else {
1583
+ readOnly.add(ancestor);
1584
+ return;
1585
+ }
1586
+ }
1587
+ if (hide) {
1588
+ directory ??= seams.isDirectory ? seams.isDirectory(path) : statSync(path).isDirectory();
1589
+ hidden.push({ path, source: directory ? mask.directory : mask.file });
1590
+ } else {
1591
+ readOnly.add(path);
1592
+ }
1593
+ };
1594
+ for (const path of credentials) {
1595
+ if (permissions.storedCredentials === "off") guard(path, true);
1596
+ else if (permissions.storedCredentials === "read") guard(path, false);
1597
+ }
1598
+ for (const path of writeDenied) guard(path, false);
1599
+ if (permissions.projectFiles === "read") readOnly.add(project);
1600
+
1601
+ // A read-only link parent keeps its existing entries writable: each one is
1602
+ // bound back read-write (a mount point, so it cannot be renamed away either).
1603
+ // Only new top-level entries in that directory are lost. Protected entries
1604
+ // keep their own mounts, and a symlink entry is never bound: a bind follows
1605
+ // it, and writes through it already meet its target's own mounts.
1606
+ const rebound = new Set<string>();
1607
+ for (const parent of linkParents) readOnly.add(parent);
1608
+ for (const parent of linkParents) {
1609
+ for (const entry of list(parent)) {
1610
+ if (entry.symlink) continue;
1611
+ const path = join(parent, entry.name);
1612
+ if (insideProtected(path) || readOnly.has(path) || writable.has(path)) continue;
1613
+ rebound.add(path);
1614
+ }
1615
+ }
1616
+
1617
+ // Intermediate directories between a writable root and anything bound
1618
+ // inside it become mount points too, so none of them can be renamed away.
1619
+ const anchors = new Set<string>();
1620
+ for (const target of [...writableRoots, ...readOnly, ...hidden.map((entry) => entry.path)]) {
1621
+ for (const parent of protectedAncestors([target])) {
1622
+ if (writableRoots.some((root) => root !== parent && contains(root, parent)) &&
1623
+ !readOnly.has(parent) && !writable.has(parent) && !rebound.has(parent)) anchors.add(parent);
1624
+ }
1625
+ }
1626
+ type Mount = { option: "--bind" | "--bind-try" | "--ro-bind"; source: string; path: string; rank: number };
1627
+ const mounts: Mount[] = [
1628
+ ...[...anchors].map((path) => ({ option: "--bind" as const, source: path, path, rank: 0 })),
1629
+ ...writableRoots.map((path) => ({ option: "--bind" as const, source: path, path, rank: 1 })),
1630
+ // `-try`: an entry removed before a resumed launch stays read-only instead of failing it.
1631
+ ...[...rebound].map((path) => ({ option: "--bind-try" as const, source: path, path, rank: 1 })),
1632
+ ...[...readOnly].map((path) => ({ option: "--ro-bind" as const, source: path, path, rank: 2 })),
1633
+ ...hidden.map(({ path, source }) => ({ option: "--ro-bind" as const, source, path, rank: 3 })),
1634
+ ].sort((a, b) => a.path.length - b.path.length || a.rank - b.rank);
1635
+ const seen = new Set<string>();
1636
+ const fileArgs = ["--ro-bind", "/", "/", "--dev", "/dev"];
1637
+ for (const mount of mounts) {
1638
+ const key = `${mount.option}\0${mount.source}\0${mount.path}`;
1639
+ if (seen.has(key)) continue;
1640
+ seen.add(key);
1641
+ fileArgs.push(mount.option, mount.source, mount.path);
1642
+ }
1643
+ return {
1644
+ file: bwrap,
1645
+ fileArgs: [...fileArgs, ...(!permissions.network ? ["--unshare-net"] : []),
1646
+ "--", args.execPath, ...args.execArgs],
1647
+ ...(created.length && { notices: [
1648
+ `Sandbox: created an empty read-only placeholder where a protected symlink points at nothing, and left it in place (remove it before creating the real target): ${created.join(", ")}`,
1649
+ ] }),
1650
+ };
1651
+ }
1652
+
1653
+ function linuxSandboxBackend(seams: SandboxSeams): SandboxBackend | undefined {
1654
+ const bwrap = (seams.lookupExecutable ?? systemSandboxExecutable)("bwrap");
1655
+ if (!bwrap) return undefined;
1656
+ return {
1657
+ id: "linux-bubblewrap",
1658
+ executable: bwrap,
1659
+ buildCommand: (args, buildSeams) => buildLinuxSandboxCommand(bwrap, args, buildSeams),
1660
+ };
1661
+ }
1662
+
1663
+ function selectedSandboxBackend(seams: SandboxSeams): SandboxBackend | undefined {
1664
+ const platform = currentPlatform(seams);
1665
+ if (platform === "darwin") return macOSSandboxBackend;
1666
+ if (platform === "linux") return linuxSandboxBackend(seams);
1667
+ return undefined;
1668
+ }
1669
+
1670
+ /**
1671
+ * Why no backend applies here. The requirement only: what a caller can do
1672
+ * instead is a property of that caller's surface, not of the platform, and is
1673
+ * supplied through `SandboxRequest.remedy`.
1674
+ */
1675
+ function unavailableMessage(platform: string): string {
1676
+ if (platform === "linux") {
1677
+ return "Linux sandbox requires executable bubblewrap (bwrap) in /usr/bin or /bin. Install bubblewrap to enable it.";
1678
+ }
1679
+ if (platform === "darwin") {
1680
+ return "macOS sandbox requires /usr/bin/sandbox-exec, which is missing here.";
1681
+ }
1682
+ return `sandbox is unsupported on ${platform}.`;
1683
+ }
1684
+
1685
+ /** Report which backend this platform would select, and why it would not. */
1686
+ export function describeSandboxSupport(seams: SandboxSeams = {}): SandboxSupport {
1687
+ const platform = currentPlatform(seams);
1688
+ const backend = selectedSandboxBackend(seams);
1689
+ if (!backend) {
1690
+ return {
1691
+ supported: false,
1692
+ platform,
1693
+ backend: undefined,
1694
+ executable: undefined,
1695
+ reason: unavailableMessage(platform),
1696
+ };
1697
+ }
1698
+ return { supported: true, platform, backend: backend.id, executable: backend.executable };
1699
+ }
1700
+
1701
+ /** The message explaining why no backend is available on this platform. */
1702
+ export function sandboxUnavailableMessage(seams: SandboxSeams = {}): string {
1703
+ return unavailableMessage(currentPlatform(seams));
1704
+ }
1705
+
1706
+ /** True when an OS write-sandbox backend can be applied on this platform. */
1707
+ export function sandboxSupported(seams: SandboxSeams = {}): boolean {
1708
+ return selectedSandboxBackend(seams) !== undefined;
1709
+ }
1710
+
1711
+ /**
1712
+ * Resolve the caller's default-on, explicit-request, and opt-out policy before
1713
+ * spawning. A selected backend always returns its wrapper; callers never retry
1714
+ * the child directly when that wrapper exits or cannot initialize.
1715
+ */
1716
+ export function maybeBuildSandboxCommand(
1717
+ args: SandboxCommandArgs,
1718
+ request: SandboxRequest,
1719
+ seams: SandboxSeams = {},
1720
+ ): SandboxCommand | undefined {
1721
+ if (args.policy.permissions?.commands === false) {
1722
+ throw new Error("Sandbox commands permission is off; enable commands before launching a sandboxed process (including bootstrap).");
1723
+ }
1724
+ if (!request.sandboxEnabled) return undefined;
1725
+
1726
+ const backend = selectedSandboxBackend(seams);
1727
+ if (!backend) {
1728
+ if (args.policy.permissions) {
1729
+ throw new Error(`Cannot enforce sandbox permissions: ${sandboxUnavailableMessage(seams)}`);
1730
+ }
1731
+ if (request.explicitSandbox) {
1732
+ const reason = sandboxUnavailableMessage(seams);
1733
+ throw new Error(request.remedy ? `${reason} ${request.remedy}` : reason);
1734
+ }
1735
+ return undefined;
1736
+ }
1737
+ return backend.buildCommand(args, seams);
1738
+ }
1739
+
1740
+ /**
1741
+ * Return the selected backend's executable and ordered argv wrapper around the
1742
+ * target. The fallback preserves the pre-existing direct-call result for callers
1743
+ * that bypass the request-policy helper above.
1744
+ */
1745
+ export function buildSandboxCommand(
1746
+ args: SandboxCommandArgs,
1747
+ seams: SandboxSeams = {},
1748
+ ): SandboxCommand {
1749
+ if (args.policy.permissions?.commands === false) {
1750
+ throw new Error("Sandbox commands permission is off; enable commands before launching a sandboxed process (including bootstrap).");
1751
+ }
1752
+ const backend = selectedSandboxBackend(seams);
1753
+ if (!backend && args.policy.permissions) {
1754
+ throw new Error(`Cannot enforce sandbox permissions: ${sandboxUnavailableMessage(seams)}`);
1755
+ }
1756
+ return (backend ?? macOSSandboxBackend).buildCommand(args, seams);
1757
+ }