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,913 @@
1
+ /**
2
+ * Background launch sandbox policy. New publishers provide a separate Background
3
+ * tasks profile; older publishers retain the historical Main-policy behavior.
4
+ * Every task keeps its policy snapshot for its whole lifetime.
5
+ *
6
+ * `pi-better-sandbox` owns the foreground policy and publishes an immutable
7
+ * snapshot of it on `pi.events`. This module is the consumer side of that wire
8
+ * contract: it mirrors the latest snapshot, and turns it into a confined
9
+ * command at the moment a local task launches.
10
+ *
11
+ * Two rules make the behaviour predictable:
12
+ *
13
+ * 1. **Snapshot at launch, never a live reference.** The wrapped executable and
14
+ * argv are resolved once, when the task starts, and are what the task keeps
15
+ * running. A later `/sandbox off` or deny-rule change therefore reaches only
16
+ * tasks launched after it.
17
+ * 2. **Opt-in, then fail closed.** `inactive` and explicitly `disabled` states
18
+ * launch unconfined. Once foreground policy says confinement applies, a
19
+ * missing or unusable backend blocks the launch and is never retried
20
+ * unconfined behind the operator's back.
21
+ *
22
+ * The contract is duplicated here rather than imported: `pi-better-sandbox` is
23
+ * an optional peer that this package must keep working without. Two channel
24
+ * names and a payload shape are the entire coupling, and both packages own
25
+ * tests that pin them.
26
+ */
27
+
28
+ import { accessSync, constants, mkdirSync, realpathSync, statSync } from "node:fs";
29
+ import { homedir } from "node:os";
30
+ import { delimiter, dirname, isAbsolute, resolve } from "node:path";
31
+
32
+ import { commandExecution } from "./process.js";
33
+ import { baseDir } from "./registry.js";
34
+ import { canonicalizePath, compileWritePolicy, describeSandboxSupport, directApplicationTarget, maybeBuildSandboxCommand, type SandboxSeams } from "./shared-sandbox-core.js";
35
+
36
+ type SandboxPermissions = {
37
+ /** `write` = read, create and overwrite in place; `read-write` = Write & delete. */
38
+ projectFiles: "off" | "read" | "write" | "read-write";
39
+ outsideProject: "off" | "read" | "write" | "read-write";
40
+ storedCredentials: "off" | "read" | "read-write";
41
+ /** Master switch for command execution. */
42
+ commands: boolean;
43
+ network: boolean;
44
+ /**
45
+ * Optional refinement of `commands`: may a launch command be interpreted by a
46
+ * shell? Absent means yes (the historical behavior). Off confines a launch to
47
+ * a direct executable through `shell: false` argv.
48
+ */
49
+ shell?: boolean;
50
+ /**
51
+ * Optional outer cap for one launch command, in seconds. Absent or null means
52
+ * no cap. A value is validated here and copied into the immutable launch
53
+ * snapshot; it caps each actual command, never a watch's whole lifetime.
54
+ */
55
+ commandTimeoutSeconds?: number | null;
56
+ };
57
+ import type { CommandSpec, TaskSandboxProvenance } from "./types.js";
58
+ import { SandboxDiagnostics, diagnosticPackageVersion, type DiagnosticResource } from "./shared-sandbox-diagnostics.js";
59
+
60
+ function backgroundDiagnostics(policy: unknown): SandboxDiagnostics | undefined {
61
+ try {
62
+ return new SandboxDiagnostics({ context: "background",
63
+ version: diagnosticPackageVersion(new URL("../package.json", import.meta.url)),
64
+ policy: () => policy,
65
+ backend: () => { const support = describeSandboxSupport(); return support.supported ? support.backend : undefined; },
66
+ onError: () => { console.error("Sandbox diagnostics collection gap; enforcement unchanged."); },
67
+ });
68
+ } catch { return undefined; }
69
+ }
70
+
71
+ /**
72
+ * What an operator can do about a missing backend here.
73
+ *
74
+ * A background task inherits the session's foreground policy, so its remedy is
75
+ * the session's: the slash command. `sandbox:false` is the subagent tool's
76
+ * opt-out and means nothing on this surface. The text is duplicated rather than
77
+ * imported for the same reason the rest of this contract is — `pi-better-sandbox`
78
+ * is an optional peer.
79
+ */
80
+ export const FOREGROUND_SANDBOX_REMEDY =
81
+ "Change the controlling Sandbox column in /sandbox, or work in a session that has a backend.";
82
+
83
+ /** Channel `pi-better-sandbox` publishes every effective-policy change on. */
84
+ export const FOREGROUND_SANDBOX_POLICY_CHANNEL = "pi-better-sandbox:policy";
85
+
86
+ /** Channel a consumer emits on to ask for the current policy. */
87
+ export const FOREGROUND_SANDBOX_POLICY_REQUEST_CHANNEL = "pi-better-sandbox:policy-request";
88
+
89
+ /** Largest single-command cap a timer can hold: 2_147_483 seconds is 2_147_483_000 ms. */
90
+ export const MAX_COMMAND_TIMEOUT_SECONDS = 2_147_483;
91
+
92
+ /** A positive finite number of seconds no larger than {@link MAX_COMMAND_TIMEOUT_SECONDS}. */
93
+ export function isCommandTimeoutSeconds(value: unknown): value is number {
94
+ return typeof value === "number" && Number.isFinite(value) && value > 0 && value <= MAX_COMMAND_TIMEOUT_SECONDS;
95
+ }
96
+
97
+ /** Executables whose whole purpose is to interpret a shell command string. */
98
+ const SHELL_EXECUTABLES = Object.freeze([
99
+ "sh", "bash", "zsh", "dash", "ksh", "ksh93", "mksh", "pdksh", "ash", "csh", "tcsh", "fish",
100
+ "yash", "posh", "rbash", "busybox", "pwsh", "powershell", "cmd",
101
+ ] as const);
102
+ const SHELL_NAMES = new Set<string>(SHELL_EXECUTABLES);
103
+
104
+ function shellExecutableName(path: string): boolean {
105
+ const normalized = String(path ?? "").replace(/\\/g, "/");
106
+ const name = normalized.slice(normalized.lastIndexOf("/") + 1).toLowerCase();
107
+ const stem = name.endsWith(".exe") ? name.slice(0, -4) : name;
108
+ return name.length > 0 && (SHELL_NAMES.has(name) || SHELL_NAMES.has(stem));
109
+ }
110
+
111
+ /**
112
+ * Resolve an executable the way spawn will: a relative or bare name against the
113
+ * launch cwd, and a bare name through the launch's PATH. A relative PATH entry
114
+ * is itself resolved against the launch cwd, because the child changes directory
115
+ * before it searches PATH.
116
+ *
117
+ * The candidate must be a regular file this process may execute, so a
118
+ * non-executable shadow earlier on PATH does not stand in for the real target.
119
+ */
120
+ function resolvedExecutablePath(executable: string, env: NodeJS.ProcessEnv, cwd: string): string | undefined {
121
+ const value = String(executable ?? "");
122
+ if (value.includes("/") || (process.platform === "win32" && value.includes("\\"))) {
123
+ return resolve(cwd, value);
124
+ }
125
+ const path = env.PATH ?? env.Path;
126
+ if (!path) return undefined;
127
+ for (const directory of path.split(delimiter)) {
128
+ const candidate = resolve(cwd, directory || ".", value);
129
+ try {
130
+ if (!statSync(candidate).isFile()) continue;
131
+ accessSync(candidate, constants.X_OK);
132
+ return candidate;
133
+ } catch { /* A PATH entry may vanish, or not be executable. */ }
134
+ }
135
+ return undefined;
136
+ }
137
+
138
+ let shellIdentities: { path: string | undefined; cwd: string; ids: Set<string> } | undefined;
139
+
140
+ /**
141
+ * Device/inode identities of the known shell binaries on this launch's PATH.
142
+ *
143
+ * A hardlink to a shell can carry any name, so a name check and a symlink's
144
+ * canonical target cannot see it. This mirrors the confined executor's identity
145
+ * check (`task-sandbox/exec.ts`), resolved against the launch cwd and PATH.
146
+ */
147
+ function knownShellIdentities(env: NodeJS.ProcessEnv, cwd: string): Set<string> {
148
+ const path = env.PATH ?? env.Path;
149
+ const cached = shellIdentities;
150
+ if (cached && cached.path === path && cached.cwd === cwd) return cached.ids;
151
+ const ids = new Set<string>();
152
+ for (const directory of (path ?? "").split(delimiter)) {
153
+ for (const name of SHELL_EXECUTABLES) {
154
+ try {
155
+ const info = statSync(resolve(cwd, directory || ".", name), { bigint: true });
156
+ if (info.isFile()) ids.add(`${info.dev}:${info.ino}`);
157
+ } catch { /* Not present in this directory. */ }
158
+ }
159
+ }
160
+ shellIdentities = { path, cwd, ids };
161
+ return ids;
162
+ }
163
+
164
+ /**
165
+ * True when `argv[0]` names a shell interpreter directly.
166
+ *
167
+ * With Shell scripts Off, a `shell: false` argv is still a way to ask a shell to
168
+ * run a command (`["/bin/bash", "-c", ...]`). The requested name is checked
169
+ * first, then the executable spawn would resolve against `cwd` and the launch's
170
+ * PATH, then its canonical target, so a symlink or an alternate name pointing at
171
+ * a shell is still refused. A hardlink to a shell is refused by inode identity.
172
+ * Only a direct interpreter is refused: an application that happens to launch a
173
+ * shell itself is a different capability from asking Pi to interpret a command.
174
+ */
175
+ export function isShellExecutable(
176
+ executable: string,
177
+ env: NodeJS.ProcessEnv = process.env,
178
+ cwd: string = process.cwd(),
179
+ ): boolean {
180
+ if (shellExecutableName(executable)) return true;
181
+ const resolved = resolvedExecutablePath(String(executable ?? ""), env, cwd);
182
+ if (!resolved) return false;
183
+ let canonical: string;
184
+ try {
185
+ canonical = realpathSync.native(resolved);
186
+ } catch {
187
+ return false;
188
+ }
189
+ if (shellExecutableName(canonical)) return true;
190
+ try {
191
+ const info = statSync(canonical, { bigint: true });
192
+ if (knownShellIdentities(env, cwd).has(`${info.dev}:${info.ino}`)) return true;
193
+ } catch { /* A missing file fails when the launch runs it. */ }
194
+ return false;
195
+ }
196
+
197
+ /**
198
+ * What the foreground sandbox is doing right now.
199
+ *
200
+ * - `inactive` - default-off foreground policy; launch tasks as before.
201
+ * - `enabled` - confine locally launched tasks.
202
+ * - `disabled` - a human switched protection off; launch tasks as before.
203
+ * - `unavailable` - no backend on this platform; block protected launches.
204
+ * - `failed` - protection cannot be applied here; block protected launches.
205
+ */
206
+ export type ForegroundSandboxState = "inactive" | "enabled" | "disabled" | "unavailable" | "failed";
207
+
208
+ /** The published snapshot, narrowed to the fields a task launch needs. */
209
+ export interface ForegroundSandboxPolicy {
210
+ readonly state: ForegroundSandboxState;
211
+ /** The only writable subtree while `state` is `enabled`. */
212
+ readonly writableRoot?: string | undefined;
213
+ /** Canonical paths that stay non-writable inside the writable root. */
214
+ readonly denyWrite: readonly string[];
215
+ /** Human-readable evidence for why `state` is what it is. */
216
+ readonly reason: string;
217
+ readonly permissions?: Readonly<SandboxPermissions & { enabled: boolean; processAccess?: "off" | "read" }>;
218
+ readonly policySource?: "background" | "main-legacy";
219
+ }
220
+
221
+ /** The minimum `pi.events` surface this module uses. */
222
+ export interface PolicyEventBus {
223
+ emit(channel: string, data: unknown): void;
224
+ on(channel: string, handler: (data: unknown) => void): unknown;
225
+ }
226
+
227
+ /** Thrown instead of launching a local task the foreground policy forbids. */
228
+ export class ForegroundSandboxBlockedError extends Error {
229
+ readonly policy: ForegroundSandboxPolicy;
230
+
231
+ constructor(policy: ForegroundSandboxPolicy, detail?: string) {
232
+ super(
233
+ `${policy.policySource === "background" ? "Background tasks" : "Foreground"} sandbox is ${policy.state}; this local background task was blocked rather than launched unconfined. ${detail ?? policy.reason}`,
234
+ );
235
+ this.name = "ForegroundSandboxBlockedError";
236
+ this.policy = policy;
237
+ }
238
+ }
239
+
240
+ /** How one local launch should be confined. Resolved before any task state exists. */
241
+ export type ForegroundSandboxPlan =
242
+ | { readonly confined: false }
243
+ | {
244
+ readonly confined: true;
245
+ readonly writableRoot: string;
246
+ readonly denyWrite: readonly string[];
247
+ readonly permissions?: SandboxPermissions;
248
+ };
249
+
250
+ const UNCONFINED: ForegroundSandboxPlan = { confined: false };
251
+ const launchPolicies = new WeakMap<ForegroundSandboxPlan, ForegroundSandboxPolicy | undefined>();
252
+ function capturePlan(plan: ForegroundSandboxPlan, policy: ForegroundSandboxPolicy | undefined): ForegroundSandboxPlan {
253
+ const snapshot = { ...plan };
254
+ launchPolicies.set(snapshot, policy);
255
+ return snapshot;
256
+ }
257
+
258
+ const VALID_STATES = new Set<string>(["inactive", "enabled", "disabled", "unavailable", "failed"]);
259
+
260
+ /**
261
+ * The latest snapshot per event bus.
262
+ *
263
+ * Keyed by the bus rather than kept in one module variable so that separate Pi
264
+ * sessions inside one process (and separate tests) cannot read each other's
265
+ * policy.
266
+ */
267
+ type PolicyMirror = { policy: ForegroundSandboxPolicy | undefined; error?: Error; processAccess?: "off" | "read"; mainConfined?: boolean };
268
+ const mirrors = new WeakMap<PolicyEventBus, PolicyMirror>();
269
+
270
+ function eventBusOf(pi: unknown): PolicyEventBus | undefined {
271
+ const events = (pi as { events?: unknown } | undefined)?.events;
272
+ if (!events || typeof events !== "object") return undefined;
273
+ const candidate = events as Partial<PolicyEventBus>;
274
+ if (typeof candidate.on !== "function" || typeof candidate.emit !== "function") return undefined;
275
+ return candidate as PolicyEventBus;
276
+ }
277
+
278
+ /**
279
+ * Accept a published payload only when it carries a state this module
280
+ * understands, so an unrelated extension emitting on the channel cannot clear a
281
+ * real policy or invent one.
282
+ */
283
+ function readPolicy(data: unknown, profile = "Main"): ForegroundSandboxPolicy | undefined {
284
+ if (!data || typeof data !== "object") return undefined;
285
+ const value = data as Record<string, unknown>;
286
+ if (typeof value.state !== "string" || !VALID_STATES.has(value.state)) return undefined;
287
+ const writableRoot = typeof value.writableRoot === "string" ? value.writableRoot : undefined;
288
+ const denyWrite = Array.isArray(value.denyWrite)
289
+ ? value.denyWrite.filter((entry): entry is string => typeof entry === "string")
290
+ : [];
291
+ const permissions = value.permissions === undefined ? undefined : readPermissions(value.permissions);
292
+ if (value.permissions !== undefined && !permissions) {
293
+ throw new Error(`Invalid ${profile} sandbox permission profile; update permissions in the sandbox UI.`);
294
+ }
295
+ return {
296
+ state: value.state as ForegroundSandboxState,
297
+ writableRoot,
298
+ denyWrite: Object.freeze([...denyWrite]),
299
+ reason: typeof value.reason === "string" ? value.reason : "No reason was published.",
300
+ ...(permissions ? { permissions } : {}),
301
+ };
302
+ }
303
+
304
+ function readPermissions(value: unknown): ForegroundSandboxPolicy["permissions"] | undefined {
305
+ if (!value || typeof value !== "object") return undefined;
306
+ const p = value as Record<string, unknown>;
307
+ const credential = (v: unknown) => v === "off" || v === "read" || v === "read-write";
308
+ const access = (v: unknown) => credential(v) || v === "write";
309
+ if (typeof p.enabled !== "boolean" || typeof p.commands !== "boolean" ||
310
+ typeof p.network !== "boolean" || !access(p.projectFiles) ||
311
+ !access(p.outsideProject) || !credential(p.storedCredentials) ||
312
+ (p.processAccess !== undefined && p.processAccess !== "off" && p.processAccess !== "read") ||
313
+ (p.shell !== undefined && typeof p.shell !== "boolean") ||
314
+ (p.commandTimeoutSeconds !== undefined && p.commandTimeoutSeconds !== null &&
315
+ !isCommandTimeoutSeconds(p.commandTimeoutSeconds))) return undefined;
316
+ // Copy only what the publisher sent: absent optional settings keep their
317
+ // documented default meaning instead of being invented here.
318
+ return Object.freeze({
319
+ enabled: p.enabled, commands: p.commands, network: p.network,
320
+ projectFiles: p.projectFiles as SandboxPermissions["projectFiles"],
321
+ outsideProject: p.outsideProject as SandboxPermissions["outsideProject"],
322
+ storedCredentials: p.storedCredentials as SandboxPermissions["storedCredentials"],
323
+ ...(p.processAccess === undefined ? {} : { processAccess: p.processAccess as "off" | "read" }),
324
+ ...(p.shell === undefined ? {} : { shell: p.shell as boolean }),
325
+ ...(p.commandTimeoutSeconds === undefined ? {} : { commandTimeoutSeconds: p.commandTimeoutSeconds as number | null }),
326
+ });
327
+ }
328
+
329
+ /**
330
+ * Start mirroring foreground policy on this session's event bus.
331
+ *
332
+ * Idempotent, and safe in either extension load order. If `pi-better-sandbox`
333
+ * loaded first, its last publication is already gone (the bus has no replay), so
334
+ * we ask for a fresh one on the request channel. If it loads later, its own
335
+ * session-start publication reaches the subscription registered here.
336
+ */
337
+ export function observeForegroundSandboxPolicy(pi: unknown): void {
338
+ const events = eventBusOf(pi);
339
+ if (!events || mirrors.has(events)) return;
340
+
341
+ const mirror: PolicyMirror = { policy: undefined };
342
+ mirrors.set(events, mirror);
343
+ events.on(FOREGROUND_SANDBOX_POLICY_CHANNEL, (data) => {
344
+ try {
345
+ const published = data && typeof data === "object" ? data as Record<string, unknown> : undefined;
346
+ const hasBackground = published && Object.hasOwn(published, "background");
347
+ const main = readPolicy(data);
348
+ const policy = hasBackground ? readPolicy(published.background, "Background tasks") : main;
349
+ if (hasBackground && (!main || !policy)) throw new Error("Invalid Background tasks sandbox policy; update permissions in /sandbox.");
350
+ if (!policy || !main) return;
351
+ const isOff = (scope: ForegroundSandboxPolicy) => scope.state === "disabled" || scope.state === "inactive";
352
+ const allowsRead = (scope: ForegroundSandboxPolicy) => scope.permissions !== undefined &&
353
+ (isOff(scope) || scope.permissions.processAccess === "read");
354
+ mirror.mainConfined = !isOff(main);
355
+ mirror.processAccess = allowsRead(main) && allowsRead(policy) ? "read" : "off";
356
+ Object.assign(policy, { policySource: hasBackground ? "background" : "main-legacy" });
357
+ mirror.policy = policy;
358
+ mirror.error = undefined;
359
+ } catch (error) {
360
+ mirror.error = error as Error;
361
+ mirror.processAccess = "off";
362
+ }
363
+ });
364
+ events.emit(FOREGROUND_SANDBOX_POLICY_REQUEST_CHANNEL, undefined);
365
+ }
366
+
367
+ /**
368
+ * The foreground policy as of right now, or `undefined` when no sandbox
369
+ * extension is publishing one.
370
+ *
371
+ * Asks for a re-publication first. Pi's event bus dispatches synchronously, so
372
+ * the answer to that request has already been mirrored by the time this
373
+ * returns; if a future bus were to defer, the last published snapshot is still
374
+ * returned rather than nothing.
375
+ */
376
+ export function currentForegroundSandboxPolicy(pi: unknown): ForegroundSandboxPolicy | undefined {
377
+ observeForegroundSandboxPolicy(pi);
378
+ const events = eventBusOf(pi);
379
+ if (!events) return undefined;
380
+ events.emit(FOREGROUND_SANDBOX_POLICY_REQUEST_CHANNEL, undefined);
381
+ const mirror = mirrors.get(events);
382
+ if (mirror?.error) throw mirror.error;
383
+ return mirror?.policy;
384
+ }
385
+
386
+ /** Current diagnostics permissions are independent of the task's launch snapshot. */
387
+ export function backgroundProcessDiagnosticsAccess(pi: unknown): "read" | "off" | "unknown" | "confined" {
388
+ try { currentForegroundSandboxPolicy(pi); } catch { return "off"; }
389
+ const events = eventBusOf(pi);
390
+ const mirror = events ? mirrors.get(events) : undefined;
391
+ const access = mirror?.processAccess ?? "unknown";
392
+ return access === "read" && mirror?.mainConfined ? "confined" : access;
393
+ }
394
+
395
+ export function sandboxProvenance(plan: ForegroundSandboxPlan, remote = false): TaskSandboxProvenance {
396
+ const policy = launchPolicies.get(plan);
397
+ const policySource = remote ? "remote" : policy?.policySource ?? (policy ? "main-legacy" : "no-publisher");
398
+ if (remote) return { confinement: "unknown", policySource, policySummary: "Remote execution; local sandbox does not establish remote confinement.", changesAffectTask: false };
399
+ if (!plan.confined) return { confinement: "unconfined", policySource,
400
+ policySummary: policy ? "Sandbox disabled at launch." : "No sandbox policy publisher at launch.", changesAffectTask: false };
401
+ const support = describeSandboxSupport();
402
+ const p = plan.permissions;
403
+ return { confinement: "confined", policySource, ...(support.supported ? { backend: support.backend } : {}),
404
+ policySummary: p ? `project=${p.projectFiles}; outside=${p.outsideProject}; credentials=${p.storedCredentials}; commands=${p.commands ? "on" : "off"}; network=${p.network ? "on" : "off"}`
405
+ : "Project write confinement with protected paths.", changesAffectTask: false };
406
+ }
407
+
408
+ /**
409
+ * Decide how a local launch must be confined, before the task has an id, a
410
+ * directory, or a log.
411
+ *
412
+ * Throws for every state that is neither confinable nor intentionally
413
+ * unconfined, which keeps a blocked launch from leaving task state behind.
414
+ */
415
+ export function resolveForegroundSandboxPlan(pi: unknown, remote = false, operation?: unknown, tool = "bg_task_spawn"): ForegroundSandboxPlan {
416
+ const policy = currentForegroundSandboxPolicy(pi);
417
+ if (remote && !policy?.permissions) return capturePlan(UNCONFINED, policy); // Preserve legacy SSH behavior.
418
+ try {
419
+ const plan = planFor(policy);
420
+ if (remote && plan.confined) {
421
+ throw new ForegroundSandboxBlockedError(policy!, !plan.permissions?.network
422
+ ? `${policy?.policySource === "background" ? "Background tasks" : "Main"} profile disables network. SSH launches are blocked.`
423
+ : `Structured SSH cannot apply local file and credential permissions yet. Use SSH through confined bash, or change ${policy?.policySource === "background" ? "Background tasks" : "Main"} permissions in /sandbox.`);
424
+ }
425
+ return capturePlan(plan, policy);
426
+ } catch (error) {
427
+ if (error instanceof ForegroundSandboxBlockedError) {
428
+ const resource: DiagnosticResource = policy?.permissions?.enabled && !policy.permissions.commands ? "command-execution"
429
+ : remote && policy?.permissions?.network === false ? "network-access" : "sandbox-backend";
430
+ backgroundDiagnostics(policy)?.observe({ tool, operation, resource, basis: "policy-refusal", outcome: "denied" });
431
+ }
432
+ throw error;
433
+ }
434
+ }
435
+
436
+ /** The plan for one already-read policy. Exposed for tests and reuse. */
437
+ export function planFor(policy: ForegroundSandboxPolicy | undefined): ForegroundSandboxPlan {
438
+ // No sandbox extension is publishing: this package is installed on its own and
439
+ // keeps its historical unsandboxed behaviour.
440
+ if (!policy) return UNCONFINED;
441
+ if (policy.permissions?.enabled && !policy.permissions.commands) {
442
+ throw new ForegroundSandboxBlockedError(policy, `${policy.policySource === "background" ? "Background tasks" : "Main"} profile disables commands. Change permissions in /sandbox before launching background tasks.`);
443
+ }
444
+ if (policy.state === "inactive" || policy.state === "disabled") return UNCONFINED;
445
+ if (policy.state !== "enabled" || !policy.writableRoot) {
446
+ throw new ForegroundSandboxBlockedError(policy);
447
+ }
448
+ const permissions = policy.permissions?.enabled ? {
449
+ projectFiles: policy.permissions.projectFiles,
450
+ outsideProject: policy.permissions.outsideProject,
451
+ storedCredentials: policy.permissions.storedCredentials,
452
+ commands: policy.permissions.commands,
453
+ network: policy.permissions.network,
454
+ ...(policy.permissions.shell === undefined ? {} : { shell: policy.permissions.shell }),
455
+ ...(policy.permissions.commandTimeoutSeconds === undefined ? {} : { commandTimeoutSeconds: policy.permissions.commandTimeoutSeconds }),
456
+ } : undefined;
457
+ return { confined: true, writableRoot: policy.writableRoot, denyWrite: policy.denyWrite,
458
+ ...(permissions ? { permissions } : {}) };
459
+ }
460
+
461
+ /**
462
+ * The parent-captured task authority a worker conversation launches background
463
+ * tasks under.
464
+ *
465
+ * This is a structural subset of the Subagents task policy and is declared here
466
+ * on purpose: `pi-better-background-tasks` must keep working when the Subagents
467
+ * package is absent, so it never imports that package. The parent supplies the
468
+ * object from the policy it captured at worker launch; it is never built from
469
+ * model tool arguments, so a child cannot widen its own authority by asking for
470
+ * a different profile. The object is treated as immutable; the resolved plan is
471
+ * a copy that later changes to the source cannot alter.
472
+ *
473
+ * A present `root` means the worker was confined. An unconfined worker (the
474
+ * `sandbox:false` opt-out) has no captured task authority and passes `undefined`
475
+ * (or `null`). A `PermissionProfile`-shaped source may also express that with
476
+ * `permissions.enabled === false`.
477
+ *
478
+ * Supported intersection contract:
479
+ *
480
+ * - No worker authority: the current Background tasks profile applies unchanged.
481
+ * - Worker confined, Background tasks off: the worker's confinement and settings
482
+ * are preserved exactly.
483
+ * - Both confined, same canonical root: project/outside/credential levels take
484
+ * the weaker side, commands/network/shell are ANDed, the command cap is the
485
+ * smaller one, and deny paths are unioned.
486
+ * - Both confined with different canonical roots, or either confined side
487
+ * publishing no permission levels to intersect, refuses the launch. Dropping
488
+ * one side's file or command rules would be a weaker profile than either
489
+ * owner approved.
490
+ */
491
+ export interface WorkerSandboxPolicy {
492
+ /** Canonical project directory the parent confined the worker to. */
493
+ readonly root: string;
494
+ readonly permissions?: WorkerSandboxPermissions;
495
+ /** Concrete paths that stay non-writable inside `root`. */
496
+ readonly denyWrite?: readonly string[];
497
+ }
498
+
499
+ /** The capability levels and command switches a worker was launched with. */
500
+ export interface WorkerSandboxPermissions {
501
+ readonly projectFiles: "off" | "read" | "write" | "read-write";
502
+ readonly outsideProject: "off" | "read" | "write" | "read-write";
503
+ readonly storedCredentials: "off" | "read" | "read-write";
504
+ readonly commands: boolean;
505
+ readonly network: boolean;
506
+ readonly shell?: boolean;
507
+ readonly commandTimeoutSeconds?: number | null;
508
+ /** Present only on a `PermissionProfile`-shaped source; false = not confined. */
509
+ readonly enabled?: boolean;
510
+ }
511
+
512
+ /** Thrown when a parent-supplied worker policy is malformed; nothing was launched. */
513
+ export class InvalidWorkerSandboxPolicyError extends Error {
514
+ constructor(detail: string) {
515
+ super(`Invalid worker sandbox policy: ${detail}`);
516
+ this.name = "InvalidWorkerSandboxPolicyError";
517
+ }
518
+ }
519
+
520
+ const FILE_ACCESS_RANK = Object.freeze({ off: 0, read: 1, write: 2, "read-write": 3 } as const);
521
+ const CREDENTIAL_ACCESS_RANK = Object.freeze({ off: 0, read: 1, "read-write": 2 } as const);
522
+
523
+ type WorkerAuthority =
524
+ | { readonly confined: false }
525
+ | { readonly confined: true; readonly root: string; readonly denyWrite: readonly string[]; readonly permissions?: SandboxPermissions };
526
+
527
+ /**
528
+ * Validate and normalize the parent-captured authority before anything else
529
+ * happens. Levels are checked as a whole profile so a typo cannot narrow itself
530
+ * silently, and a relative root or deny entry is refused rather than resolved
531
+ * against Pi's own cwd.
532
+ */
533
+ function readWorkerAuthority(value: WorkerSandboxPolicy | null | undefined): WorkerAuthority {
534
+ if (value === null || value === undefined) return { confined: false };
535
+ if (typeof value !== "object" || Array.isArray(value)) {
536
+ throw new InvalidWorkerSandboxPolicyError("the parent-captured policy must be an object.");
537
+ }
538
+ const raw = value as unknown as Record<string, unknown>;
539
+ if (typeof raw.root !== "string" || raw.root.length === 0 || !isAbsolute(raw.root)) {
540
+ throw new InvalidWorkerSandboxPolicyError("root must be an absolute path.");
541
+ }
542
+ const root = canonicalizePath(raw.root);
543
+ if (root === dirname(root) || root === canonicalizePath(homedir())) {
544
+ throw new InvalidWorkerSandboxPolicyError("root must be a project directory, not the filesystem or home root.");
545
+ }
546
+ const denyWrite = raw.denyWrite;
547
+ if (denyWrite !== undefined && (!Array.isArray(denyWrite) ||
548
+ !denyWrite.every((entry) => typeof entry === "string" && isAbsolute(entry)))) {
549
+ throw new InvalidWorkerSandboxPolicyError("denyWrite must be a list of absolute paths.");
550
+ }
551
+ const deny = Object.freeze([...new Set((denyWrite as string[] | undefined) ?? [])]);
552
+
553
+ if (raw.permissions === undefined) {
554
+ return { confined: true, root, denyWrite: deny };
555
+ }
556
+ const source = raw.permissions;
557
+ if (!source || typeof source !== "object" || Array.isArray(source)) {
558
+ throw new InvalidWorkerSandboxPolicyError("permissions must be an object.");
559
+ }
560
+ const p = source as Record<string, unknown>;
561
+ if (p.enabled !== undefined && typeof p.enabled !== "boolean") {
562
+ throw new InvalidWorkerSandboxPolicyError("permissions.enabled must be a boolean.");
563
+ }
564
+ // A PermissionProfile that is not enabled grants no task authority at all.
565
+ if (p.enabled === false) return { confined: false };
566
+ if (typeof p.projectFiles !== "string" || !Object.hasOwn(FILE_ACCESS_RANK, p.projectFiles)) {
567
+ throw new InvalidWorkerSandboxPolicyError("permissions.projectFiles must be off, read, write or read-write.");
568
+ }
569
+ if (typeof p.outsideProject !== "string" || !Object.hasOwn(FILE_ACCESS_RANK, p.outsideProject)) {
570
+ throw new InvalidWorkerSandboxPolicyError("permissions.outsideProject must be off, read, write or read-write.");
571
+ }
572
+ if (typeof p.storedCredentials !== "string" || !Object.hasOwn(CREDENTIAL_ACCESS_RANK, p.storedCredentials)) {
573
+ throw new InvalidWorkerSandboxPolicyError("permissions.storedCredentials must be off, read or read-write.");
574
+ }
575
+ if (typeof p.commands !== "boolean") {
576
+ throw new InvalidWorkerSandboxPolicyError("permissions.commands must be a boolean.");
577
+ }
578
+ if (typeof p.network !== "boolean") {
579
+ throw new InvalidWorkerSandboxPolicyError("permissions.network must be a boolean.");
580
+ }
581
+ if (p.shell !== undefined && typeof p.shell !== "boolean") {
582
+ throw new InvalidWorkerSandboxPolicyError("permissions.shell must be a boolean.");
583
+ }
584
+ if (p.commandTimeoutSeconds !== undefined && p.commandTimeoutSeconds !== null && !isCommandTimeoutSeconds(p.commandTimeoutSeconds)) {
585
+ throw new InvalidWorkerSandboxPolicyError(`permissions.commandTimeoutSeconds must be null or a positive, finite number of seconds up to ${MAX_COMMAND_TIMEOUT_SECONDS}.`);
586
+ }
587
+ const permissions: SandboxPermissions = {
588
+ projectFiles: p.projectFiles as SandboxPermissions["projectFiles"],
589
+ outsideProject: p.outsideProject as SandboxPermissions["outsideProject"],
590
+ storedCredentials: p.storedCredentials as SandboxPermissions["storedCredentials"],
591
+ commands: p.commands,
592
+ network: p.network,
593
+ ...(p.shell === undefined ? {} : { shell: p.shell }),
594
+ ...(p.commandTimeoutSeconds === undefined ? {} : { commandTimeoutSeconds: p.commandTimeoutSeconds as number | null }),
595
+ };
596
+ return { confined: true, root, denyWrite: deny, permissions: Object.freeze(permissions) };
597
+ }
598
+
599
+ /** The weaker of two file-access levels; deletion is never broader than writes. */
600
+ function weakerFileAccess(
601
+ a: SandboxPermissions["projectFiles"],
602
+ b: SandboxPermissions["projectFiles"],
603
+ ): SandboxPermissions["projectFiles"] {
604
+ return FILE_ACCESS_RANK[a] <= FILE_ACCESS_RANK[b] ? a : b;
605
+ }
606
+
607
+ function weakerCredentialAccess(
608
+ a: SandboxPermissions["storedCredentials"],
609
+ b: SandboxPermissions["storedCredentials"],
610
+ ): SandboxPermissions["storedCredentials"] {
611
+ return CREDENTIAL_ACCESS_RANK[a] <= CREDENTIAL_ACCESS_RANK[b] ? a : b;
612
+ }
613
+
614
+ /** Intersect two already-validated capability profiles. */
615
+ function intersectPermissions(background: SandboxPermissions, worker: SandboxPermissions): SandboxPermissions {
616
+ const backgroundCap = isCommandTimeoutSeconds(background.commandTimeoutSeconds) ? background.commandTimeoutSeconds : undefined;
617
+ const workerCap = isCommandTimeoutSeconds(worker.commandTimeoutSeconds) ? worker.commandTimeoutSeconds : undefined;
618
+ const cap = backgroundCap === undefined ? workerCap
619
+ : workerCap === undefined ? backgroundCap : Math.min(backgroundCap, workerCap);
620
+ const shellGiven = background.shell !== undefined || worker.shell !== undefined;
621
+ const capGiven = background.commandTimeoutSeconds !== undefined || worker.commandTimeoutSeconds !== undefined;
622
+ return Object.freeze({
623
+ projectFiles: weakerFileAccess(background.projectFiles, worker.projectFiles),
624
+ outsideProject: weakerFileAccess(background.outsideProject, worker.outsideProject),
625
+ storedCredentials: weakerCredentialAccess(background.storedCredentials, worker.storedCredentials),
626
+ commands: background.commands && worker.commands,
627
+ network: background.network && worker.network,
628
+ ...(shellGiven ? { shell: background.shell !== false && worker.shell !== false } : {}),
629
+ ...(capGiven ? { commandTimeoutSeconds: cap ?? null } : {}),
630
+ });
631
+ }
632
+
633
+ /**
634
+ * The policy snapshot stored behind a worker-authored plan, so provenance and
635
+ * {@link backgroundExecutionLimits} read the effective authority rather than
636
+ * the parent's published profile.
637
+ */
638
+ function workerPlanPolicy(
639
+ plan: { readonly writableRoot: string; readonly denyWrite: readonly string[]; readonly permissions?: SandboxPermissions },
640
+ reason: string,
641
+ ): ForegroundSandboxPolicy {
642
+ return Object.freeze({
643
+ state: "enabled",
644
+ writableRoot: plan.writableRoot,
645
+ denyWrite: Object.freeze([...plan.denyWrite]),
646
+ reason,
647
+ ...(plan.permissions ? { permissions: Object.freeze({ ...plan.permissions, enabled: true }) } : {}),
648
+ policySource: "background",
649
+ });
650
+ }
651
+
652
+ /**
653
+ * Resolve how a worker-launched local background task must be confined.
654
+ *
655
+ * The effective authority is always the worker's captured task authority and
656
+ * the current Background tasks profile, never the parent session's sibling Main
657
+ * profile. When the publisher sends a Background column this reads that column;
658
+ * a legacy publisher with one profile keeps its historical meaning, which is
659
+ * already what Background tasks enforce.
660
+ *
661
+ * Validation runs before any task state exists. A malformed policy, an invalid
662
+ * command cap or level, a disabled worker command capability, differing
663
+ * canonical roots, or an unsupported intersection refuses the launch instead of
664
+ * dropping a rule. The returned plan is an immutable snapshot: it is captured
665
+ * through {@link capturePlan} so later command checks and
666
+ * {@link backgroundExecutionLimits} keep the authority this launch started with.
667
+ */
668
+ export function resolveWorkerSandboxPlan(
669
+ pi: unknown,
670
+ workerPolicy?: WorkerSandboxPolicy | null,
671
+ operation?: unknown,
672
+ tool = "bg_task_spawn",
673
+ ): ForegroundSandboxPlan {
674
+ const background = currentForegroundSandboxPolicy(pi);
675
+ let worker: WorkerAuthority;
676
+ try {
677
+ worker = readWorkerAuthority(workerPolicy);
678
+ } catch (error) {
679
+ backgroundDiagnostics(background)?.observe({ tool, operation, resource: "sandbox-backend", basis: "policy-refusal", outcome: "denied" });
680
+ throw error;
681
+ }
682
+
683
+ // No captured authority: the current Background tasks profile is the whole
684
+ // answer, exactly as it is for a parent-launched task.
685
+ if (!worker.confined) return capturePlan(planFor(background), background);
686
+
687
+ // Commands Off is the worker's master switch, independent of Background being
688
+ // on or off. It is checked before any plan is built.
689
+ if (worker.permissions && !worker.permissions.commands) {
690
+ const snapshot = { writableRoot: worker.root, denyWrite: worker.denyWrite, permissions: worker.permissions };
691
+ const policy = workerPlanPolicy(snapshot, "The worker task authority disables commands.");
692
+ backgroundDiagnostics(background)?.observe({ tool, operation, resource: "command-execution", basis: "policy-refusal", outcome: "denied" });
693
+ throw new ForegroundSandboxBlockedError(policy,
694
+ "The worker task authority disables commands. Change the Subagents permissions before launching background tasks.");
695
+ }
696
+
697
+ const backgroundOff = !background || background.state === "inactive" || background.state === "disabled";
698
+ if (backgroundOff) {
699
+ // Preserve the worker's own confinement even though no Background profile is
700
+ // enforcing anything. Its settings are copied, never linked to the source.
701
+ const plan = {
702
+ confined: true as const,
703
+ writableRoot: worker.root,
704
+ denyWrite: Object.freeze([...worker.denyWrite]),
705
+ ...(worker.permissions ? { permissions: worker.permissions } : {}),
706
+ };
707
+ return capturePlan(plan, workerPlanPolicy(plan, "Worker task authority applies; the Background tasks profile is off."));
708
+ }
709
+
710
+ try {
711
+ const base = planFor(background);
712
+ if (!base.confined) throw new Error("Worker sandbox resolution expected a confined Background tasks plan.");
713
+ const backgroundRoot = canonicalizePath(base.writableRoot);
714
+ if (backgroundRoot !== worker.root) {
715
+ throw new ForegroundSandboxBlockedError(background,
716
+ `Cannot intersect the Background tasks root ${JSON.stringify(backgroundRoot)} with the worker root ${JSON.stringify(worker.root)}: they confine different directories, so a correct intersection cannot be constructed. Refusing rather than dropping either side's rules.`);
717
+ }
718
+ if (!base.permissions || !worker.permissions) {
719
+ throw new ForegroundSandboxBlockedError(background,
720
+ `Cannot intersect the Background tasks profile with the worker task authority because ${base.permissions ? "the worker" : "the Background tasks profile"} publishes no permission levels (file access, commands, network). Refusing rather than dropping the other side's controls; update the sandbox packages or set permissions in /sandbox.`);
721
+ }
722
+ const permissions = intersectPermissions(base.permissions, worker.permissions);
723
+ const denyWrite = Object.freeze([...new Set([...base.denyWrite, ...worker.denyWrite])]);
724
+ const plan = { confined: true as const, writableRoot: backgroundRoot, denyWrite, permissions };
725
+ return capturePlan(plan, workerPlanPolicy(plan,
726
+ "Worker task authority intersected with the Background tasks profile (weaker levels, ANDed switches, smallest cap, deny paths unioned)."));
727
+ } catch (error) {
728
+ if (error instanceof ForegroundSandboxBlockedError) {
729
+ backgroundDiagnostics(background)?.observe({ tool, operation, resource: "sandbox-backend", basis: "policy-refusal", outcome: "denied" });
730
+ }
731
+ throw error;
732
+ }
733
+ }
734
+
735
+ /**
736
+ * The application, shell, and time switches captured with one launch plan.
737
+ *
738
+ * The Background tasks profile is the gate: when it is off, launches keep their
739
+ * historical unconfined behavior. When it is on, `commands` remains the master
740
+ * switch (enforced by {@link planFor}); this narrows it with the optional
741
+ * `shell` and `commandTimeoutSeconds` fields. An absent `shell` means On, and an
742
+ * absent or null cap means no cap, so a publisher that predates those fields is
743
+ * unchanged.
744
+ */
745
+ export interface BackgroundExecutionLimits {
746
+ /** May a launch command be interpreted by a shell? */
747
+ readonly shell: boolean;
748
+ /** Immutable outer cap for one command, in seconds; undefined means unlimited. */
749
+ readonly commandTimeoutSeconds?: number;
750
+ }
751
+
752
+ const UNLIMITED_EXECUTION: BackgroundExecutionLimits = Object.freeze({ shell: true });
753
+
754
+ /** Read the immutable application switches captured for `plan`. */
755
+ export function backgroundExecutionLimits(plan: ForegroundSandboxPlan): BackgroundExecutionLimits {
756
+ const permissions = launchPolicies.get(plan)?.permissions;
757
+ if (!permissions?.enabled) return UNLIMITED_EXECUTION;
758
+ const cap = isCommandTimeoutSeconds(permissions.commandTimeoutSeconds)
759
+ ? permissions.commandTimeoutSeconds
760
+ : undefined;
761
+ return Object.freeze({
762
+ shell: permissions.shell !== false,
763
+ ...(cap === undefined ? {} : { commandTimeoutSeconds: cap }),
764
+ });
765
+ }
766
+
767
+ /**
768
+ * Refuse a launch the captured Background tasks application switches forbid.
769
+ *
770
+ * Called before any task id, directory, log, or metadata exists, so a refused
771
+ * launch leaves nothing behind. `commands: false` is still the master refusal
772
+ * and is raised by {@link planFor}; this is the narrower shell rule. With Shell
773
+ * scripts Off, only a direct executable through `shell: false` argv is allowed.
774
+ * A shell command string and a direct shell interpreter in argv[0] would both
775
+ * reintroduce shell interpretation, and structured SSH carries a remote shell
776
+ * command, so all three are refused.
777
+ *
778
+ * `cwd` is the launch directory the task will actually run in. A relative
779
+ * executable, a relative PATH entry, and an alias found only in that directory
780
+ * are resolved exactly as the launch resolves them, never against Pi's own
781
+ * process cwd.
782
+ */
783
+ export function assertBackgroundExecutionAllowed(
784
+ spec: CommandSpec,
785
+ plan: ForegroundSandboxPlan,
786
+ options: { remote?: boolean; cwd?: string } = {},
787
+ ): void {
788
+ const limits = backgroundExecutionLimits(plan);
789
+ if (limits.shell) return;
790
+ const launchCwd = options.cwd ?? spec.cwd ?? process.cwd();
791
+ const detail = options.remote
792
+ ? "Structured SSH carries a remote shell command, so it cannot run while Shell scripts is Off. Use a local shell:false argv launch, or turn Shell scripts on in /sandbox."
793
+ : spec.shell !== false
794
+ ? "Background tasks profile disables shell commands. Pass shell:false with an argv for a direct executable, or turn Shell scripts on in /sandbox."
795
+ : isShellExecutable(spec.argv?.[0] ?? "", { ...process.env, ...spec.env }, launchCwd)
796
+ ? "Background tasks profile disables shell commands. A direct shell executable is refused; launch the program itself with shell:false, or turn Shell scripts on in /sandbox."
797
+ : undefined;
798
+ if (detail === undefined) return;
799
+ const policy = launchPolicies.get(plan) ?? {
800
+ state: "failed" as const,
801
+ denyWrite: [],
802
+ reason: "The Background tasks profile disables shell commands.",
803
+ };
804
+ throw new ForegroundSandboxBlockedError(policy, detail);
805
+ }
806
+
807
+ /**
808
+ * Wrap a local command in the platform's write sandbox.
809
+ *
810
+ * The result is an ordinary `CommandSpec` whose argv is the backend wrapper
811
+ * around the exact executable and arguments the unconfined spec would have run,
812
+ * so spawning, streaming, timeouts, process-group termination, and env handling
813
+ * all stay on their existing code paths. The generated macOS profile is written
814
+ * to `profilePath`, which callers put inside the task's own directory so a
815
+ * resumed watch re-reads the policy it launched with.
816
+ *
817
+ * `seams` defaults to the real platform and PATH. It exists so a caller — in
818
+ * practice a test — can prove the argv this produces for a backend other than
819
+ * the one the host happens to have.
820
+ */
821
+ export function confineCommandSpec(
822
+ spec: CommandSpec,
823
+ plan: ForegroundSandboxPlan,
824
+ profilePath: string,
825
+ seams: SandboxSeams = {},
826
+ /** Receives lines to show with the launch (e.g. a placeholder left in the user's files). */
827
+ onNotice: (line: string) => void = () => {},
828
+ tool = "bg_task_spawn",
829
+ ): CommandSpec {
830
+ if (!plan.confined) return spec;
831
+
832
+ const { execPath, execArgs } = commandExecution(spec);
833
+ const directOnly = spec.shell === false && plan.permissions?.shell === false;
834
+ const target = directOnly
835
+ ? directApplicationTarget(execPath, execArgs, { ...process.env, ...spec.env }, false)
836
+ : { execPath, execArgs };
837
+ // The generated profile is written here, so its directory must exist before
838
+ // the backend builds the command.
839
+ mkdirSync(dirname(profilePath), { recursive: true });
840
+ // Task state is this package's control plane: `meta.json` carries the launch
841
+ // vector a resumed watch re-runs verbatim, and `sandbox.sb` is the profile the
842
+ // launch is confined by. It lives under the system temp directory, which both
843
+ // backends leave writable by design, so a confined task could otherwise
844
+ // rewrite what its own next poll executes and choose its own confinement.
845
+ //
846
+ // Denying the whole registry closes that without moving any state, and without
847
+ // costing the task anything it actually needs: pi writes the registry from
848
+ // outside the sandbox, and the task's log reaches it through a descriptor
849
+ // opened before the launch, which no later mount or profile can revoke.
850
+ //
851
+ // Created here rather than assumed, because the Linux backend materializes an
852
+ // absent denied path as an empty *file* and this one has to be a directory.
853
+ const controlPlane = baseDir();
854
+ mkdirSync(controlPlane, { recursive: true });
855
+ const denyWrite = [...plan.denyWrite, controlPlane];
856
+ const policy = {
857
+ writableRoot: plan.writableRoot,
858
+ denyWrite,
859
+ home: homedir(),
860
+ ...(plan.permissions ? { permissions: plan.permissions } : {}),
861
+ };
862
+ let command;
863
+ try {
864
+ if (plan.permissions && !("permissions" in compileWritePolicy(policy))) {
865
+ throw new Error("permission-aware sandbox core is unavailable; update the sandbox packages before launching");
866
+ }
867
+ command = maybeBuildSandboxCommand(
868
+ {
869
+ profilePath,
870
+ policy,
871
+ ...target,
872
+ ...(directOnly ? { internalHelperExecutable: true } : {}),
873
+ },
874
+ // `explicitSandbox` because the foreground state already said a sandbox
875
+ // applies: an absent or unusable backend must throw here rather than hand
876
+ // back an unwrapped command. The remedy is the foreground one: this policy
877
+ // came from the session, and the session is where it is switched off.
878
+ { sandboxEnabled: true, explicitSandbox: true, remedy: FOREGROUND_SANDBOX_REMEDY },
879
+ seams,
880
+ );
881
+ } catch (error) {
882
+ backgroundDiagnostics(plan)?.observe({ tool, operation: spec, resource: "sandbox-backend", basis: "policy-refusal", outcome: "denied" });
883
+ throw blocked(plan, error instanceof Error ? error.message : String(error));
884
+ }
885
+ if (!command) {
886
+ backgroundDiagnostics(plan)?.observe({ tool, operation: spec, resource: "sandbox-backend", basis: "policy-refusal", outcome: "denied" });
887
+ throw blocked(plan, "no sandbox backend was applied");
888
+ }
889
+ for (const line of command.notices ?? []) onNotice(line);
890
+
891
+ return { ...spec, ...(directOnly ? { env: { PATH: "/usr/bin:/bin", HOME: homedir() } } : {}),
892
+ argv: [command.file, ...command.fileArgs], shell: false };
893
+ }
894
+
895
+ function blocked(plan: ForegroundSandboxPlan & { confined: true }, detail: string): Error {
896
+ return new ForegroundSandboxBlockedError(
897
+ {
898
+ state: "failed",
899
+ policySource: launchPolicies.get(plan)?.policySource,
900
+ writableRoot: plan.writableRoot,
901
+ denyWrite: plan.denyWrite,
902
+ reason: detail,
903
+ },
904
+ detail,
905
+ );
906
+ }
907
+
908
+ /** Fixed server adapter clears only its own scope mirror before publishing another captured grant. */
909
+ export function clearForegroundSandboxPolicy(pi: unknown): void {
910
+ observeForegroundSandboxPolicy(pi);
911
+ const events=eventBusOf(pi), mirror=events && mirrors.get(events);
912
+ if(mirror){mirror.policy=undefined;mirror.error=undefined;mirror.processAccess="off";mirror.mainConfined=false;}
913
+ }