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,2336 @@
1
+ // Generated fixed launch domain from packages/pi-better-subagents/worker-waits.ts. Do not edit directly.
2
+ /**
3
+ * Autonomous worker park/resume for Subagents.
4
+ *
5
+ * A supervised worker conversation may launch background operations, register an
6
+ * all-settled wait on them, and park: its attempt completes cleanly with a
7
+ * durable park disposition while the assignment keeps its native conversation,
8
+ * launch recipe and saved history. When the dependency settles, the Background
9
+ * host delivers the ready wait to this module's continuation adapter, which
10
+ * admits exactly one continuation through the ordinary continuation launch path.
11
+ *
12
+ * Ownership split (ADR 0020, observed-waits design):
13
+ *
14
+ * - **Subagents (this module)** owns the trusted bridge host each worker child
15
+ * talks to, the per-run transport token, the child extension arguments,
16
+ * native-checkpoint validation against the trusted launch recipe, the park
17
+ * disposition on the run record, and resume admission/launch.
18
+ * - **Background Tasks** owns the durable operation/wait/outbox records, the
19
+ * supervisor transport, permission intersection and dispatch. This module never
20
+ * opens that database and never imports Background code: it consumes the
21
+ * service object Background publishes on its versioned event channel.
22
+ * - **Goal** controls parent execution only; assignment admission does not ask it.
23
+ *
24
+ * The service contract mirror below is intentionally structural: it names only
25
+ * the members this module calls, so either package can load first and a missing
26
+ * host reads as an unavailable capability instead of a broken import.
27
+ */
28
+ import { randomUUID } from "node:crypto";
29
+ import { managedWorkerBridge } from "./managed-worker-bridge.domain.mjs";
30
+ import { realpathSync } from "node:fs";
31
+ import { join } from "node:path";
32
+ import { OPERATIONS_ATTEMPT_ID_ENV, OPERATIONS_CHILD_ID_ENV, OPERATIONS_DEADLINE_AT_ENV, OPERATIONS_CONVERSATION_ID_ENV, OPERATIONS_ENABLED_ENV, OPERATIONS_ENDPOINT_ENV, OPERATIONS_RUN_ID_ENV, OPERATIONS_TOKEN_ENV, OPERATIONS_WRITER_LEASE_ID_ENV, WAIT_OPERATIONS_TOOL, assertWaitToolDependencies, createToolDescriptor, extractResultTaskIds, normalizeWaitForOperationsResult, normalizeToolDescriptors, OperationBridgeError, } from "./operation-bridge-types.domain.mjs";
33
+ import { createOperationBridgeHost, } from "./worker-operations-host.domain.mjs";
34
+ import { captureParkCheckpoint, verifyParkCheckpoint } from "./park-checkpoint.domain.mjs";
35
+ import { findSavedConversation, readConversationLease } from "./continuation.domain.mjs";
36
+ import { commitAssignmentTerminal, readOutcome, coordinatorPath } from "./assignment-outcomes.domain.mjs";
37
+ import { openStore } from "./shared-operation-coordinator/index.domain.mjs";
38
+ import { recordAssignmentReport, recordAssignmentReportRejection } from "./assignment-report.domain.mjs";
39
+ import { currentSandboxPermissions } from "./permission-policy.domain.mjs";
40
+ import { effectiveStatus, isPendingPark, listParkRecordCandidates, scanParkRecords, listPendingParkedRuns, readMeta, readParkRecord, processStartToken, updateParkRecord, writeParkRecord, writeMeta, } from "./registry.domain.mjs";
41
+ import { processExists } from "./spawn.domain.mjs";
42
+ import { realProcessProbe } from "./health.domain.mjs";
43
+ import { stopRun } from "./stop.domain.mjs";
44
+ import { assertObservationStorage, pendingObservations, retainObservation, resolveObservation } from "./outage-observations.domain.mjs";
45
+ // ---- Background service contract (versioned event bus) --------------------
46
+ /**
47
+ * Background publishes its operation service object here and answers a request
48
+ * for it on the request channel. The shape mirrors `BackgroundOperationService`
49
+ * in `pi-better-background-tasks/src/observed-waits.ts`; only the members this
50
+ * module calls are declared.
51
+ */
52
+ export const OBSERVED_WAITS_SERVICE_CHANNEL = "pi-better-background-tasks:observed-waits-service";
53
+ export const OBSERVED_WAITS_SERVICE_REQUEST_CHANNEL = "pi-better-background-tasks:observed-waits-service-request";
54
+ export const OBSERVED_WAITS_SERVICE_VERSION = 2;
55
+ /**
56
+ * Request/reply surface Background publishes for the Subagents coordinator. It
57
+ * carries the pieces the object service does not: run bindings for the worker's
58
+ * captured policy, checkpoint staging, and the resume claim/publish/release fence.
59
+ */
60
+ export const WORKER_OPERATIONS_RPC_CHANNEL = "pi-better-background-tasks:observed-waits";
61
+ export const WORKER_OPERATIONS_RPC_VERSION = 1;
62
+ export class WorkerOperationsRefusal extends Error {
63
+ code;
64
+ constructor(code, message) {
65
+ super(message);
66
+ this.name = "WorkerOperationsRefusal";
67
+ this.code = code;
68
+ }
69
+ }
70
+ export class WorkerOperationsUnavailable extends Error {
71
+ constructor(message) {
72
+ super(message);
73
+ this.name = "WorkerOperationsUnavailable";
74
+ }
75
+ }
76
+ /**
77
+ * Bounded request/reply client. A missing or slow host is an explicit
78
+ * unavailability, never an assumed success; a late reply is ignored.
79
+ */
80
+ export function createWorkerOperationsRpc(pi, options = {}) {
81
+ const budgetFor = (override) => Math.max(50, Math.min(120_000, override ?? options.timeoutMs ?? 30_000));
82
+ const call = (method, params, overrideMs) => {
83
+ const bus = serviceBusOf(pi);
84
+ if (!bus) {
85
+ return Promise.reject(new WorkerOperationsUnavailable("This Pi runtime exposes no extension event bus, so worker operations are unavailable."));
86
+ }
87
+ const budget = budgetFor(overrideMs);
88
+ return new Promise((resolve, reject) => {
89
+ let settled = false;
90
+ const finish = (action) => {
91
+ if (settled)
92
+ return;
93
+ settled = true;
94
+ clearTimeout(timer);
95
+ action();
96
+ };
97
+ const timer = setTimeout(() => {
98
+ finish(() => reject(new WorkerOperationsUnavailable(`The Background observed-waits host did not answer ${method} within ${budget} ms. No wait, checkpoint or resume was recorded.`)));
99
+ }, budget);
100
+ timer.unref?.();
101
+ const request = {
102
+ version: WORKER_OPERATIONS_RPC_VERSION,
103
+ id: `ow_${randomUUID()}`,
104
+ method,
105
+ params,
106
+ reply: (reply) => {
107
+ if (!reply || typeof reply !== "object") {
108
+ finish(() => reject(new WorkerOperationsUnavailable("The observed-waits host returned a malformed reply.")));
109
+ return;
110
+ }
111
+ const value = reply;
112
+ if (value.ok === true) {
113
+ finish(() => resolve(value.value && typeof value.value === "object" ? value.value : {}));
114
+ return;
115
+ }
116
+ finish(() => reject(new WorkerOperationsRefusal(typeof value.code === "string" ? value.code : "refused", typeof value.reason === "string" && value.reason ? value.reason : "The observed-waits host refused the request.")));
117
+ },
118
+ };
119
+ try {
120
+ bus.emit(WORKER_OPERATIONS_RPC_CHANNEL, request);
121
+ }
122
+ catch (error) {
123
+ finish(() => reject(new WorkerOperationsUnavailable(`The observed-waits request failed: ${error instanceof Error ? error.message : String(error)}`)));
124
+ }
125
+ });
126
+ };
127
+ return { call };
128
+ }
129
+ /** Goal's admission gate; this module only asks, never decides. */
130
+ export const OPERATION_RESUME_ADMISSION_EVENT = "pi-better-goal:operation-resume-admission";
131
+ const serviceMirrors = new WeakMap();
132
+ function serviceBusOf(pi) {
133
+ const events = pi?.events;
134
+ if (!events || typeof events !== "object")
135
+ return undefined;
136
+ const candidate = events;
137
+ if (typeof candidate.on !== "function" || typeof candidate.emit !== "function")
138
+ return undefined;
139
+ return candidate;
140
+ }
141
+ function isPublishedService(value) {
142
+ if (!value || typeof value !== "object")
143
+ return false;
144
+ const candidate = value;
145
+ return candidate.version === OBSERVED_WAITS_SERVICE_VERSION
146
+ && candidate.available === true
147
+ && typeof candidate.launchForWorker === "function"
148
+ && typeof candidate.statusForWorker === "function"
149
+ && typeof candidate.logForWorker === "function"
150
+ && typeof candidate.registerWorkerWait === "function"
151
+ && typeof candidate.checkpointWorkerWait === "function"
152
+ && typeof candidate.failWorkerPark === "function"
153
+ && typeof candidate.acknowledgeForWorker === "function"
154
+ && typeof candidate.listWorkerWaits === "function"
155
+ && typeof candidate.cancelWorkerWait === "function"
156
+ && typeof candidate.ownsTask === "function"
157
+ && typeof candidate.registerContinuationAdapter === "function"
158
+ && (candidate.holdFailedResumeForWorker === undefined || typeof candidate.holdFailedResumeForWorker === "function");
159
+ }
160
+ function mirrorOf(pi) {
161
+ const bus = serviceBusOf(pi);
162
+ if (!bus)
163
+ return undefined;
164
+ let mirror = serviceMirrors.get(bus);
165
+ if (!mirror) {
166
+ mirror = {};
167
+ serviceMirrors.set(bus, mirror);
168
+ bus.on(OBSERVED_WAITS_SERVICE_CHANNEL, (data) => {
169
+ const current = serviceMirrors.get(bus);
170
+ if (!current)
171
+ return;
172
+ if (data && typeof data === "object" && data.version !== OBSERVED_WAITS_SERVICE_VERSION) {
173
+ current.service = undefined;
174
+ current.reason = "The Background host does not support observed-waits service v2 assignment continuation";
175
+ return;
176
+ }
177
+ if (isPublishedService(data)) {
178
+ current.service = data;
179
+ current.reason = undefined;
180
+ return;
181
+ }
182
+ if (data && typeof data === "object"
183
+ && data.version === OBSERVED_WAITS_SERVICE_VERSION
184
+ && data.available === false) {
185
+ current.service = undefined;
186
+ const reason = data.reason;
187
+ current.reason = typeof reason === "string" ? reason : "the Background operation host is unavailable";
188
+ }
189
+ });
190
+ }
191
+ return { mirror, bus };
192
+ }
193
+ /**
194
+ * Resolve the Background operation service through its versioned channel. Pi's
195
+ * bus dispatches synchronously, so a host that is already running answers before
196
+ * this returns; `undefined` means this package runs alone (or the host closed).
197
+ */
198
+ export function getWorkerOperationService(pi) {
199
+ const resolved = mirrorOf(pi);
200
+ if (!resolved)
201
+ return undefined;
202
+ try {
203
+ resolved.bus.emit(OBSERVED_WAITS_SERVICE_REQUEST_CHANNEL, { version: OBSERVED_WAITS_SERVICE_VERSION });
204
+ }
205
+ catch {
206
+ return undefined;
207
+ }
208
+ return resolved.mirror.service;
209
+ }
210
+ /** Why the service request returned nothing, when a host refused to open. */
211
+ export function workerOperationsUnavailableReason(pi) {
212
+ const resolved = mirrorOf(pi);
213
+ if (!resolved)
214
+ return "this Pi runtime exposes no extension event bus";
215
+ if (!resolved.mirror.service) {
216
+ try {
217
+ resolved.bus.emit(OBSERVED_WAITS_SERVICE_REQUEST_CHANNEL, { version: OBSERVED_WAITS_SERVICE_VERSION });
218
+ }
219
+ catch { /* keep the previous reason */ }
220
+ }
221
+ return resolved.mirror.reason;
222
+ }
223
+ /** Build the policy Background needs; `taskPolicy` is the immutable task launch contract. */
224
+ export function captureWorkerPolicy(input) {
225
+ const sandbox = input.sandbox && input.taskPolicy
226
+ ? {
227
+ root: input.taskPolicy.root,
228
+ ...(input.taskPolicy.permissions ? { permissions: input.taskPolicy.permissions } : {}),
229
+ ...(input.taskPolicy.denyWrite ? { denyWrite: [...input.taskPolicy.denyWrite] } : {}),
230
+ }
231
+ : null;
232
+ return {
233
+ version: 1,
234
+ mandatoryPermissions: input.mandatoryPermissions === true,
235
+ sandbox,
236
+ tools: [...input.tools],
237
+ clean: input.clean,
238
+ deadlineAt: input.deadlineAt ?? null,
239
+ authorityReference: input.authorityReference,
240
+ workspace: input.workspace,
241
+ };
242
+ }
243
+ /** Refuse permission loss or widening when reconstructing a captured assignment. */
244
+ export function assertAssignmentPermissionScope(captured, current, allowNarrowing = false) {
245
+ if (!captured)
246
+ throw new PreSpawnResumeError("Captured assignment permissions are missing");
247
+ const requiresAuthority = captured.mandatoryPermissions === true
248
+ || (captured.mandatoryPermissions === undefined && captured.sandbox !== null);
249
+ if (requiresAuthority && !current.mandatoryPermissions) {
250
+ throw new PreSpawnResumeError("Expected mandatory permission authority is unavailable");
251
+ }
252
+ const normalize = (value) => {
253
+ if (Array.isArray(value))
254
+ return value.map(normalize);
255
+ if (value && typeof value === "object")
256
+ return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, entry]) => [key, normalize(entry)]));
257
+ return value;
258
+ };
259
+ const oldSandbox = captured.sandbox;
260
+ const newSandbox = current.sandbox;
261
+ if (oldSandbox?.denyWrite?.some((path) => !newSandbox?.denyWrite?.includes(path))) {
262
+ throw new PreSpawnResumeError("Current permissions would remove captured assignment protected paths");
263
+ }
264
+ if (allowNarrowing && oldSandbox && newSandbox && oldSandbox.root === newSandbox.root && oldSandbox.permissions && newSandbox.permissions) {
265
+ const old = oldSandbox.permissions, next = newSandbox.permissions;
266
+ const access = ["off", "read", "write", "read-write"];
267
+ const files = ["projectFiles", "outsideProject", "storedCredentials"].every(key => access.includes(next[key]) && access.indexOf(next[key]) <= access.indexOf(old[key]));
268
+ const commands = (!next.commands || old.commands) && (!next.network || old.network)
269
+ && (next.shell === false || old.shell !== false);
270
+ const oldCap = old.commandTimeoutSeconds ?? Infinity, nextCap = next.commandTimeoutSeconds ?? Infinity;
271
+ if (files && commands && nextCap <= oldCap)
272
+ return;
273
+ }
274
+ const authority = (sandbox) => sandbox ? { root: sandbox.root, permissions: sandbox.permissions } : null;
275
+ if (JSON.stringify(normalize(authority(oldSandbox))) !== JSON.stringify(normalize(authority(newSandbox)))) {
276
+ throw new PreSpawnResumeError("Current permissions would change the captured assignment scope");
277
+ }
278
+ }
279
+ // ---- child capability planning -------------------------------------------
280
+ /** Fallback tool set for a supervised worker; user restrictions still subtract. */
281
+ export const DEFAULT_WORKER_BRIDGE_TOOLS = [
282
+ "bg_task_spawn",
283
+ "bg_task_watch",
284
+ "bg_task_status",
285
+ "bg_task_log",
286
+ WAIT_OPERATIONS_TOOL,
287
+ "acknowledge_operation_result",
288
+ ];
289
+ /**
290
+ * Decide the worker's operation tools.
291
+ *
292
+ * - `clean` children keep their explicit no-ambient-capability loadout.
293
+ * - An explicit `tools` allowlist only passes bridge tools the caller named.
294
+ * - `exclude_tools` always wins.
295
+ * - A sandboxed child is not treated differently here: its task policy enables
296
+ * the guarded bridge only when the fixed bridge adapter is present, and the
297
+ * task guard admits the tools by exact source. Withholding them here would
298
+ * silently disable a capability the sandbox already supports.
299
+ * - Without any restriction, defaults get the full set; the Background host
300
+ * still intersects the run's captured task authority with the current profile
301
+ * before anything launches.
302
+ */
303
+ export function planWorkerBridgeTools(input) {
304
+ const excluded = new Set(input.excluded.map((name) => name.trim()).filter(Boolean));
305
+ const allow = new Set(input.allow.map((name) => name.trim()).filter(Boolean));
306
+ const withheld = [];
307
+ const tools = [];
308
+ for (const name of DEFAULT_WORKER_BRIDGE_TOOLS) {
309
+ if (excluded.has(name)) {
310
+ withheld.push({ name, reason: "excluded by the launch's exclude_tools" });
311
+ continue;
312
+ }
313
+ if (input.clean) {
314
+ withheld.push({ name, reason: "clean mode disables ambient operation capabilities" });
315
+ continue;
316
+ }
317
+ if (input.explicitTools && !allow.has(name)) {
318
+ withheld.push({ name, reason: "not in the launch's explicit tools list" });
319
+ continue;
320
+ }
321
+ // Background tools must be described by the production schemas the parent
322
+ // publishes; the bridge's own two tools carry their own contract.
323
+ const backgroundTool = name !== WAIT_OPERATIONS_TOOL && name !== "acknowledge_operation_result";
324
+ if (backgroundTool && input.productionSchemas && !input.productionSchemas.has(name)) {
325
+ withheld.push({ name, reason: "the parent Background extension publishes no production schema for this tool" });
326
+ continue;
327
+ }
328
+ tools.push(name);
329
+ }
330
+ if (tools.includes(WAIT_OPERATIONS_TOOL)
331
+ && (!tools.includes("acknowledge_operation_result") || !tools.some(name => name === "bg_task_status" || name === "bg_task_log"))
332
+ && !(input.explicitTools && allow.has(WAIT_OPERATIONS_TOOL))) {
333
+ tools.splice(tools.indexOf(WAIT_OPERATIONS_TOOL), 1);
334
+ withheld.push({ name: WAIT_OPERATIONS_TOOL, reason: "the authorized tools cannot read and acknowledge terminal evidence" });
335
+ }
336
+ const has = (name) => tools.includes(name);
337
+ const capabilities = {
338
+ background: { spawn: has("bg_task_spawn"), watch: has("bg_task_watch"), status: has("bg_task_status"), log: has("bg_task_log") },
339
+ wait: has(WAIT_OPERATIONS_TOOL), acknowledge: has("acknowledge_operation_result"), parking: has(WAIT_OPERATIONS_TOOL),
340
+ };
341
+ assertWaitToolDependencies(capabilities, tools);
342
+ return {
343
+ tools,
344
+ withheld,
345
+ capabilities,
346
+ };
347
+ }
348
+ /** Production tool descriptors for bridge tools, from the parent's registrations. */
349
+ export function resolveProductionSchemas(pi, names = DEFAULT_WORKER_BRIDGE_TOOLS) {
350
+ const inventory = pi.getAllTools?.() ?? [];
351
+ const schemas = new Map();
352
+ const missing = [];
353
+ for (const name of names) {
354
+ if (name === WAIT_OPERATIONS_TOOL || name === "acknowledge_operation_result") {
355
+ schemas.set(name, createToolDescriptor(name));
356
+ continue;
357
+ }
358
+ const tool = inventory.find((entry) => entry?.name === name);
359
+ if (!tool || !tool.parameters || typeof tool.parameters !== "object") {
360
+ missing.push(name);
361
+ continue;
362
+ }
363
+ schemas.set(name, {
364
+ name,
365
+ label: tool.label && typeof tool.label === "string" ? tool.label : createToolDescriptor(name).label,
366
+ description: typeof tool.description === "string" && tool.description ? tool.description : createToolDescriptor(name).description,
367
+ parameters: tool.parameters,
368
+ });
369
+ }
370
+ return { schemas, missing };
371
+ }
372
+ function canonical(path) {
373
+ try {
374
+ return realpathSync.native(path);
375
+ }
376
+ catch {
377
+ return path;
378
+ }
379
+ }
380
+ /**
381
+ * Default validator: the persisted point must be the trusted launch recipe's own
382
+ * saved conversation (same directory, session id and workspace), and the captured
383
+ * checkpoint must match the evidence the child reported. A file path plus a hash
384
+ * the child chose is not proof.
385
+ */
386
+ export const recipeCheckpointEvidenceValidator = (input) => {
387
+ const meta = readMeta(input.runId);
388
+ const recipe = meta?.recipe;
389
+ if (!recipe) {
390
+ throw new Error(`Cannot verify a park checkpoint for ${input.runId}: its trusted launch recipe is missing.`);
391
+ }
392
+ if (recipe.sessionId !== input.conversationId) {
393
+ throw new Error(`Cannot verify a park checkpoint for ${input.runId}: the launch recipe belongs to conversation ${recipe.sessionId}, not ${input.conversationId}.`);
394
+ }
395
+ if (canonical(recipe.cwd) !== canonical(input.workspace)) {
396
+ throw new Error(`Cannot verify a park checkpoint for ${input.runId}: the launch recipe belongs to workspace ${recipe.cwd}, not ${input.workspace}.`);
397
+ }
398
+ const lookup = findSavedConversation({
399
+ sessionDir: recipe.sessionDir,
400
+ sessionId: recipe.sessionId,
401
+ expectedCwd: recipe.cwd,
402
+ });
403
+ switch (lookup.kind) {
404
+ case "ok":
405
+ break;
406
+ case "missing":
407
+ throw new Error(`Cannot verify a park checkpoint for ${input.runId}: its saved conversation is gone.`);
408
+ case "ambiguous":
409
+ throw new Error(`Cannot verify a park checkpoint for ${input.runId}: its saved conversation is ambiguous (${lookup.paths.length} files).`);
410
+ case "invalid":
411
+ case "mismatch":
412
+ throw new Error(`Cannot verify a park checkpoint for ${input.runId}: ${lookup.detail}`);
413
+ }
414
+ if (canonical(lookup.conversation.path) !== canonical(input.evidence.sessionFile)) {
415
+ throw new Error(`Cannot verify a park checkpoint for ${input.runId}: the evidence names ${input.evidence.sessionFile}, not this conversation's saved session ${lookup.conversation.path}.`);
416
+ }
417
+ if (input.evidence.sessionId !== recipe.sessionId) {
418
+ throw new Error(`Cannot verify a park checkpoint for ${input.runId}: the evidence names another session id.`);
419
+ }
420
+ const captured = captureParkCheckpoint({
421
+ sessionId: recipe.sessionId,
422
+ sessionFile: lookup.conversation.path,
423
+ toolCallId: input.evidence.toolCallId,
424
+ waitId: input.waitId,
425
+ generation: input.generation,
426
+ });
427
+ verifyParkCheckpoint(captured);
428
+ if (captured.prefixSha256 !== input.evidence.prefixSha256
429
+ || captured.prefixBytes !== input.evidence.prefixBytes
430
+ || captured.entryId !== input.evidence.entryId) {
431
+ throw new Error(`Cannot verify a park checkpoint for ${input.runId}: the reported evidence does not describe the persisted session.`);
432
+ }
433
+ return captured;
434
+ };
435
+ export class WorkerOperationsHostUnavailable extends Error {
436
+ constructor(reason) {
437
+ super(reason);
438
+ this.name = "WorkerOperationsHostUnavailable";
439
+ }
440
+ }
441
+ function scopeOf(registration) {
442
+ return {
443
+ runId: registration.runId,
444
+ conversationId: registration.conversationId,
445
+ ...(registration.assignment && registration.attemptId ? { assignmentAttemptId: registration.attemptId } : {}),
446
+ workspace: registration.workspace,
447
+ authorityReference: registration.authorityReference,
448
+ branchId: registration.branchId ?? null,
449
+ goalId: registration.goalId ?? null,
450
+ };
451
+ }
452
+ /**
453
+ * Trusted parent-side bridge host.
454
+ *
455
+ * One host per Pi process. It owns no task runner and no database: every launch,
456
+ * observation, wait, checkpoint and interpretation call goes to the Background
457
+ * service with the run's captured policy, and ownership is re-derived from the
458
+ * durable store on each request (so an attempt resumed into a conversation still
459
+ * sees the tasks that conversation launched earlier).
460
+ */
461
+ export function createWorkerOperationsHost(options) {
462
+ const durable = options.managedRoot ? managedWorkerBridge(options.managedRoot) : undefined;
463
+ const created = {};
464
+ const hosting = {};
465
+ const starting = {};
466
+ const capability = { available: false };
467
+ const runs = new Map();
468
+ const waitNotes = new Map();
469
+ const rpc = options.rpc ?? createWorkerOperationsRpc(options.pi);
470
+ const validate = options.checkpointEvidenceValidator ?? recipeCheckpointEvidenceValidator;
471
+ const ensureHost = async () => {
472
+ if (created.host)
473
+ return created.host;
474
+ if (!hosting.promise) {
475
+ const factory = options.hostFactory ?? createOperationBridgeHost;
476
+ hosting.promise = factory({
477
+ ...(durable ? { socketPath: durable.socketPath } : {}),
478
+ ...(options.logger ? { logger: options.logger } : {}),
479
+ ...(options.now ? { now: options.now } : {}),
480
+ }).then((host) => { created.host = host; return host; })
481
+ .finally(() => { hosting.promise = undefined; });
482
+ }
483
+ return hosting.promise;
484
+ };
485
+ const start = async () => {
486
+ if (starting.promise)
487
+ return starting.promise;
488
+ starting.promise = (async () => {
489
+ const service = getWorkerOperationService(options.pi);
490
+ if (!service) {
491
+ capability.available = false;
492
+ return false;
493
+ }
494
+ await ensureHost();
495
+ capability.service = service;
496
+ capability.available = true;
497
+ for (const registration of durable?.restore() ?? [])
498
+ await register(registration);
499
+ return true;
500
+ })();
501
+ return starting.promise;
502
+ };
503
+ const requireService = () => {
504
+ if (!capability.service) {
505
+ throw new WorkerOperationsHostUnavailable("The Background observed-waits service is not available, so this worker cannot be given supervised operation tools or parking. Install pi-better-background-tasks, or launch without them.");
506
+ }
507
+ return capability.service;
508
+ };
509
+ const register = async (registration) => {
510
+ assertWaitToolDependencies(registration.capabilities, registration.tools);
511
+ const supervised = registration.tools.some((name) => name !== "report_assignment_result");
512
+ if (supervised && !capability.available) {
513
+ const ready = await start();
514
+ if (!ready)
515
+ throw new WorkerOperationsHostUnavailable(workerOperationsUnavailableReason(options.pi) ?? "The Background observed-waits service is not available.");
516
+ }
517
+ const service = supervised ? requireService() : undefined;
518
+ const host = await ensureHost();
519
+ const scope = scopeOf(registration);
520
+ runs.set(registration.runId, scope);
521
+ const owner = {
522
+ kind: "worker-conversation",
523
+ sessionId: registration.conversationId,
524
+ workspace: registration.workspace,
525
+ branchId: registration.branchId ?? null,
526
+ goalId: registration.goalId ?? null,
527
+ };
528
+ // The durable run binding captures the worker's task authority and the
529
+ // conversation identity. Every later tool call, checkpoint and resume fence
530
+ // is checked against it by the Background host.
531
+ const registered = supervised ? await rpc.call("register-run", {
532
+ runId: registration.runId,
533
+ conversationId: registration.conversationId,
534
+ attemptId: registration.attemptId,
535
+ workspace: registration.workspace,
536
+ authorityReference: registration.authorityReference,
537
+ policy: registration.policy,
538
+ tools: [...registration.tools],
539
+ capabilities: registration.capabilities,
540
+ assignmentOutcomesVersion: 1,
541
+ assignmentTaskOwnership: registration.assignment !== undefined,
542
+ owner,
543
+ ...(registration.writerLeaseId ? { writerLeaseId: registration.writerLeaseId } : {}),
544
+ }) : { assignmentOutcomesVersion: 1 };
545
+ if (registered.assignmentOutcomesVersion !== 1) {
546
+ runs.delete(registration.runId);
547
+ try {
548
+ await rpc.call("release-run", { runId: registration.runId, reason: "assignment outcome capability mismatch" });
549
+ }
550
+ catch { /* preserve the capability refusal */ }
551
+ throw new WorkerOperationsRefusal("service-unavailable", "Background host does not support durable assignment outcomes v1; upgrade the standalone packages together.");
552
+ }
553
+ /**
554
+ * Ownership is re-derived from the durable store (by conversation), so an
555
+ * attempt resumed into this conversation still owns the tasks an earlier
556
+ * attempt launched. This is a transport guard; Background rechecks too.
557
+ */
558
+ const ownsTask = (taskId) => {
559
+ try {
560
+ return service?.ownsTask(scope, taskId) ?? false;
561
+ }
562
+ catch {
563
+ return false;
564
+ }
565
+ };
566
+ const handlers = {};
567
+ let onToolRejected;
568
+ if (registration.capabilities.reportAssignment && registration.assignment) {
569
+ const assertReportAuthority = (context) => {
570
+ const live = host.getRun(registration.runId);
571
+ const meta = readMeta(registration.runId);
572
+ if (!live || live.revoked || live.tokenGeneration !== context.tokenGeneration || context.signal.aborted
573
+ || !runs.has(registration.runId) || !meta || meta.status !== "running" || meta.park
574
+ || meta.sessionId !== registration.conversationId
575
+ || JSON.stringify(meta.assignment) !== JSON.stringify(registration.assignment) || readOutcome(meta))
576
+ throw new Error("Assignment report writer is no longer authoritative.");
577
+ if (!processExists(meta.pid) || (meta.pidStartTime && processStartToken(meta.pid) !== meta.pidStartTime))
578
+ throw new Error("Assignment report writer has exited or changed identity.");
579
+ if (registration.writerLeaseId) {
580
+ const lease = readConversationLease(registration.conversationId);
581
+ if (!lease || lease.attemptId !== meta.id || lease.token !== registration.writerLeaseId)
582
+ throw new Error("Assignment report writer lease changed.");
583
+ }
584
+ if (meta.operations?.resumeLaunchToken) {
585
+ const store = openStore({ path: coordinatorPath() });
586
+ try {
587
+ const claims = store.listResumeClaims({ state: "published" });
588
+ if (!claims.some((c) => {
589
+ const wait = store.getWait({ waitId: c.waitId, generation: c.generation });
590
+ return c.attemptId === meta.id && c.launchToken === meta.operations.resumeLaunchToken
591
+ && wait && wait.cancelEpoch === c.cancelEpoch && !["cancelled", "held"].includes(wait.phase);
592
+ }))
593
+ throw new Error("Assignment resume writer fence changed.");
594
+ }
595
+ finally {
596
+ store.close();
597
+ }
598
+ }
599
+ return meta;
600
+ };
601
+ handlers.report_assignment_result = async (params, context) => {
602
+ let permissions;
603
+ try {
604
+ permissions = currentSandboxPermissions(options.pi);
605
+ }
606
+ catch (error) {
607
+ recordAssignmentReportRejection(reasonOf(error), () => assertReportAuthority(context));
608
+ throw error;
609
+ }
610
+ return recordAssignmentReport(registration.runId, params, () => assertReportAuthority(context), permissions);
611
+ };
612
+ onToolRejected = (error, context) => {
613
+ if (context.tool === "report_assignment_result")
614
+ recordAssignmentReportRejection(error.message, () => assertReportAuthority(context));
615
+ };
616
+ }
617
+ const execute = (tool, params) => rpc.call("execute-tool", {
618
+ runId: registration.runId,
619
+ conversationId: registration.conversationId,
620
+ tool,
621
+ params,
622
+ });
623
+ if (registration.capabilities.background.spawn) {
624
+ handlers.bg_task_spawn = async (params) => execute("bg_task_spawn", params);
625
+ }
626
+ if (registration.capabilities.background.watch) {
627
+ handlers.bg_task_watch = async (params) => execute("bg_task_watch", params);
628
+ }
629
+ if (registration.capabilities.background.status) {
630
+ handlers.bg_task_status = async (params) => execute("bg_task_status", params);
631
+ }
632
+ if (registration.capabilities.background.log) {
633
+ handlers.bg_task_log = async (params) => execute("bg_task_log", params);
634
+ }
635
+ if (registration.capabilities.wait && registration.capabilities.parking) {
636
+ handlers.wait_for_operations = async (params) => {
637
+ const taskIds = Array.isArray(params.task_ids)
638
+ ? params.task_ids.filter((value) => typeof value === "string")
639
+ : [];
640
+ if (taskIds.length === 0) {
641
+ throw new WorkerOperationsRefusal("task-invalid", "wait_for_operations needs at least one task id");
642
+ }
643
+ const note = typeof params.continuation_note === "string" ? params.continuation_note : "";
644
+ if (!note) {
645
+ throw new WorkerOperationsRefusal("task-invalid", "wait_for_operations needs a continuation note");
646
+ }
647
+ const view = await rpc.call("wait-admission", {
648
+ runId: registration.runId,
649
+ conversationId: registration.conversationId,
650
+ taskIds,
651
+ continuationNote: note,
652
+ attemptId: registration.attemptId,
653
+ owner,
654
+ });
655
+ if (!view.park) {
656
+ throw new WorkerOperationsRefusal("wait-invalid", "the Background host did not register a park wait for this worker");
657
+ }
658
+ waitNotes.set(`${view.waitId}:${view.generation}`, note);
659
+ const normalized = normalizeWaitForOperationsResult({ ...view, park: true, taskIds: view.taskIds.length ? view.taskIds : taskIds });
660
+ if (!normalized.ok) {
661
+ throw new WorkerOperationsRefusal("wait-invalid", `wait admission returned an invalid result: ${normalized.message}`);
662
+ }
663
+ return { ...view, ...normalized.result, park: true };
664
+ };
665
+ }
666
+ if (registration.capabilities.acknowledge) {
667
+ handlers.acknowledge_operation_result = async (params) => {
668
+ const waitId = typeof params.wait_id === "string" ? params.wait_id : "";
669
+ const generation = typeof params.generation === "number" ? params.generation : 0;
670
+ const disposition = params.disposition;
671
+ if (!waitId || !generation || typeof disposition !== "string" || !["continue", "blocked", "assignment-complete"].includes(disposition)) {
672
+ throw new WorkerOperationsRefusal("schema-invalid", "acknowledge_operation_result needs wait_id, generation and a disposition");
673
+ }
674
+ const view = await rpc.call("acknowledge", {
675
+ runId: registration.runId,
676
+ conversationId: registration.conversationId,
677
+ waitId,
678
+ generation,
679
+ terminalRevisions: params.terminal_revisions,
680
+ disposition: disposition,
681
+ note: typeof params.note === "string" ? params.note : "",
682
+ owner,
683
+ });
684
+ const parked = await parkedWaitByGeneration(waitId, generation);
685
+ if (parked)
686
+ updateParkRecord(parked.runId, { phase: "consumed" });
687
+ return view;
688
+ };
689
+ }
690
+ if (registration.capabilities.parking) {
691
+ handlers.checkpoint = async (params) => {
692
+ const waitId = typeof params.wait_id === "string" ? params.wait_id : "";
693
+ const generation = typeof params.generation === "number" ? params.generation : 0;
694
+ const evidence = params.evidence;
695
+ if (!waitId || !generation || !evidence || typeof evidence !== "object") {
696
+ throw new WorkerOperationsRefusal("checkpoint-invalid", "checkpoint needs wait_id, generation and evidence");
697
+ }
698
+ // Validate against the trusted recipe (session location, id and
699
+ // workspace) and re-capture the checkpoint from the file itself.
700
+ let captured;
701
+ try {
702
+ captured = await validate({
703
+ runId: registration.runId,
704
+ conversationId: registration.conversationId,
705
+ waitId,
706
+ generation,
707
+ evidence,
708
+ workspace: registration.workspace,
709
+ });
710
+ }
711
+ catch (error) {
712
+ throw new OperationBridgeError("checkpoint-invalid", reasonOf(error));
713
+ }
714
+ const note = waitNotes.get(`${waitId}:${generation}`);
715
+ assertObservationStorage();
716
+ const at = options.now?.() ?? Date.now();
717
+ // STAGED: the original writer is still alive, so the generation stays
718
+ // `parking`; Background records the evidence and the exit path proves
719
+ // writer exit before the wait can leave parking.
720
+ const staged = await rpc.call("checkpoint", {
721
+ runId: registration.runId,
722
+ conversationId: registration.conversationId,
723
+ waitId,
724
+ generation,
725
+ toolCallId: captured.toolCallId,
726
+ attemptId: registration.attemptId,
727
+ evidence: captured,
728
+ });
729
+ if (staged.phase !== "parking" && staged.staged !== true) {
730
+ throw new WorkerOperationsRefusal("checkpoint-invalid", `the Background host reported ${String(staged.phase)} for a staged park checkpoint`);
731
+ }
732
+ writeParkRecord(registration.runId, {
733
+ version: 1,
734
+ waitId,
735
+ generation,
736
+ observedCoordinator: (() => {
737
+ try {
738
+ const wait = capability.service?.listWorkerWaits({ runId: registration.runId,
739
+ conversationId: registration.conversationId, workspace: registration.workspace,
740
+ authorityReference: registration.authorityReference }).find((entry) => entry.waitId === waitId && entry.generation === generation);
741
+ return wait ? { cancelEpoch: wait.cancelEpoch, dependencies: wait.dependencies.map((entry) => ({
742
+ operationId: entry.operationId, terminalRevision: entry.terminalRevision
743
+ })) } : undefined;
744
+ }
745
+ catch {
746
+ return undefined;
747
+ }
748
+ })(),
749
+ phase: "parking",
750
+ attemptId: registration.attemptId,
751
+ ...(note ? { continuationNote: note } : {}),
752
+ ...(registration.owner ? {
753
+ ownerSessionId: registration.owner.sessionId,
754
+ ownerWorkspace: registration.owner.workspace,
755
+ ownerBranchId: registration.owner.branchId,
756
+ ownerGoalId: registration.owner.goalId,
757
+ } : {}),
758
+ checkpoint: {
759
+ sessionId: captured.sessionId,
760
+ sessionFile: captured.sessionFile,
761
+ toolCallId: captured.toolCallId,
762
+ entryId: captured.entryId,
763
+ prefixBytes: captured.prefixBytes,
764
+ prefixSha256: captured.prefixSha256,
765
+ },
766
+ parkedAt: at,
767
+ updatedAt: at,
768
+ });
769
+ return { checkpointed: true, staged: true, phase: "parking", waitId, generation };
770
+ };
771
+ handlers.park_failed = async (params) => {
772
+ const waitId = typeof params.wait_id === "string" ? params.wait_id : "";
773
+ const generation = typeof params.generation === "number" ? params.generation : 0;
774
+ const reason = typeof params.reason === "string" && params.reason ? params.reason : "the worker could not certify its park checkpoint";
775
+ if (!waitId || !generation) {
776
+ throw new WorkerOperationsRefusal("schema-invalid", "park_failed needs wait_id and generation");
777
+ }
778
+ const view = await rpc.call("park-failed", {
779
+ runId: registration.runId,
780
+ conversationId: registration.conversationId,
781
+ waitId,
782
+ generation,
783
+ reason,
784
+ });
785
+ updateParkRecord(registration.runId, { phase: phaseOf(String(view.phase)), heldReason: reason });
786
+ return { held: true, phase: view.phase };
787
+ };
788
+ }
789
+ const handle = host.registerRun({
790
+ ...(registration.token ? { token: registration.token } : {}),
791
+ runId: registration.runId,
792
+ conversationId: registration.conversationId,
793
+ workspace: registration.workspace,
794
+ authorityReference: registration.authorityReference,
795
+ capabilities: registration.capabilities,
796
+ tools: normalizeToolDescriptors(registration.schemas, registration.capabilities),
797
+ ownership: (taskId) => ownsTask(taskId),
798
+ handlers,
799
+ onToolRejected,
800
+ });
801
+ durable?.save(registration, handle.token);
802
+ return {
803
+ runId: registration.runId,
804
+ conversationId: registration.conversationId,
805
+ token: handle.token,
806
+ endpoint: host.endpoint,
807
+ capabilities: registration.capabilities,
808
+ tools: registration.tools,
809
+ childExtensionArgs: ["--extension", options.childExtensionPath],
810
+ env: childEnvironment(handle.token, host.endpoint, registration),
811
+ descriptorFingerprint: handle.descriptor.fingerprint,
812
+ };
813
+ };
814
+ const release = (runId, reason) => {
815
+ durable?.remove(runId);
816
+ runs.delete(runId);
817
+ try {
818
+ created.host?.unregisterRun(runId);
819
+ }
820
+ catch { /* already gone */ }
821
+ if (capability.service)
822
+ void rpc.call("release-run", { runId, reason }).catch(() => { });
823
+ };
824
+ const close = async () => {
825
+ try {
826
+ await hosting.promise;
827
+ }
828
+ catch { /* failed creation has no host to close */ }
829
+ const host = created.host;
830
+ created.host = undefined;
831
+ starting.promise = undefined;
832
+ capability.available = false;
833
+ capability.service = undefined;
834
+ runs.clear();
835
+ waitNotes.clear();
836
+ if (!host)
837
+ return;
838
+ await host.close();
839
+ };
840
+ return {
841
+ get available() {
842
+ return capability.available;
843
+ },
844
+ get service() {
845
+ return capability.service;
846
+ },
847
+ rpc,
848
+ start,
849
+ register,
850
+ release,
851
+ getRun: (runId) => created.host?.getRun(runId),
852
+ close,
853
+ };
854
+ }
855
+ /** Environment handed to the child; the token is the only secret and is never persisted. */
856
+ export function childEnvironment(token, endpoint, registration) {
857
+ return {
858
+ [OPERATIONS_ENABLED_ENV]: "1",
859
+ [OPERATIONS_ENDPOINT_ENV]: endpoint,
860
+ [OPERATIONS_TOKEN_ENV]: token,
861
+ [OPERATIONS_RUN_ID_ENV]: registration.runId,
862
+ [OPERATIONS_CONVERSATION_ID_ENV]: registration.conversationId,
863
+ [OPERATIONS_ATTEMPT_ID_ENV]: registration.attemptId,
864
+ [OPERATIONS_CHILD_ID_ENV]: `${registration.runId}:${randomUUID()}`,
865
+ ...(registration.policy ? { [OPERATIONS_DEADLINE_AT_ENV]: String(registration.policy.deadlineAt ?? 0) } : {}),
866
+ };
867
+ }
868
+ /** Writer-lease id for a parked attempt, when the continuation path holds one. */
869
+ export function childWriterLeaseEnv(leaseId) {
870
+ return leaseId ? { [OPERATIONS_WRITER_LEASE_ID_ENV]: leaseId } : {};
871
+ }
872
+ // ---- park record, disposition and post-exit finalization ------------------
873
+ /** Phases a wait can report, mirrored into the park record. */
874
+ export function phaseOf(phase) {
875
+ switch (phase) {
876
+ case "parking":
877
+ case "waiting":
878
+ case "ready":
879
+ case "resuming":
880
+ case "held":
881
+ case "consumed":
882
+ case "cancelled":
883
+ return phase;
884
+ default:
885
+ return "held";
886
+ }
887
+ }
888
+ /** True when the recorded exit is a clean completed attempt. */
889
+ export function isCleanParkExit(meta) {
890
+ if (!meta)
891
+ return false;
892
+ if (meta.exitCode !== 0)
893
+ return false;
894
+ if (meta.failureReason !== undefined)
895
+ return false;
896
+ if (meta.lifecycleClassification === "incomplete_no_terminal_event")
897
+ return false;
898
+ if (meta.lifecycleClassification === "incomplete_open_tools")
899
+ return false;
900
+ if (meta.lifecycleClassification === "failed_model_error")
901
+ return false;
902
+ return meta.status === "completed";
903
+ }
904
+ /**
905
+ * Decide the exit disposition for a run.
906
+ *
907
+ * A park is recognized only when the exit was clean, a durable park record
908
+ * exists, its wait generation is still live, and the recorded checkpoint still
909
+ * verifies against the saved conversation. A staged record (`parking`) counts:
910
+ * the durable wait is finalized separately, after the writer exit is proven.
911
+ */
912
+ export function evaluateParkDisposition(input) {
913
+ const record = readParkRecord(input.runId);
914
+ if (!record)
915
+ return { parked: false };
916
+ if (!isPendingPark(record)) {
917
+ return { parked: false, reason: `wait ${record.waitId} generation ${record.generation} is ${record.phase}` };
918
+ }
919
+ if (record.phase === "held" || record.phase === "resuming") {
920
+ return { parked: false, record, reason: record.heldReason ?? `the wait is ${record.phase}` };
921
+ }
922
+ if (!input.cleanExit) {
923
+ return { parked: false, record, reason: "the child did not exit cleanly" };
924
+ }
925
+ if (!record.checkpoint)
926
+ return { parked: false, record, reason: "no verified park checkpoint was recorded" };
927
+ const verify = input.verifyCheckpoint ?? verifyParkCheckpoint;
928
+ try {
929
+ verify({
930
+ version: 1,
931
+ sessionId: record.checkpoint.sessionId,
932
+ sessionFile: record.checkpoint.sessionFile,
933
+ toolCallId: record.checkpoint.toolCallId,
934
+ waitId: record.waitId,
935
+ generation: record.generation,
936
+ entryId: record.checkpoint.entryId,
937
+ prefixBytes: record.checkpoint.prefixBytes,
938
+ prefixSha256: record.checkpoint.prefixSha256,
939
+ });
940
+ }
941
+ catch (error) {
942
+ return { parked: false, record, reason: `checkpoint no longer verifies: ${reasonOf(error)}` };
943
+ }
944
+ return { parked: true, record };
945
+ }
946
+ /**
947
+ * The Background owner scope for a parked worker attempt.
948
+ *
949
+ * `record.ownerWorkspace` belongs to the FOREGROUND parent that owns the
950
+ * assignment and is only used for resume admission. Background registered this
951
+ * worker conversation under the WORKER's workspace (the `sandbox_dir` or clone the
952
+ * child actually ran in), so ownership must use that; mixing the two makes every
953
+ * post-exit operation foreign to the durable record.
954
+ */
955
+ export function backgroundScopeForMeta(meta, record) {
956
+ const operations = meta.operations;
957
+ const conversationId = operations?.conversationId ?? meta.sessionId;
958
+ const workspace = operations?.workspace ?? meta.cwd;
959
+ if (!conversationId || !workspace)
960
+ return null;
961
+ return {
962
+ runId: meta.id,
963
+ conversationId,
964
+ workspace,
965
+ authorityReference: operations?.authorityReference ?? `worker:${meta.id}`,
966
+ branchId: record.ownerBranchId ?? null,
967
+ goalId: record.ownerGoalId ?? null,
968
+ };
969
+ }
970
+ /**
971
+ * Finalize a staged park AFTER the child exited.
972
+ *
973
+ * Background requires three facts before a generation may leave `parking`:
974
+ * the checkpoint was recorded (staged by the bridge while the child was alive),
975
+ * the writer lease was released, and the original writer process is gone. This is
976
+ * the only place that sends that proof; a missing or unproven fact holds the
977
+ * generation instead of claiming a park.
978
+ */
979
+ export async function finalizeWorkerParkAfterExit(input) {
980
+ const meta = readMeta(input.runId);
981
+ const record = readParkRecord(input.runId);
982
+ if (!meta || !record)
983
+ return { outcome: "skipped" };
984
+ const service = input.service;
985
+ const hold = (reason) => {
986
+ updateParkRecord(input.runId, { phase: "held", heldReason: reason });
987
+ return { outcome: "held", reason };
988
+ };
989
+ const unverified = (reason) => {
990
+ let detail = `Coordinator state is unverified; ${reason}`;
991
+ try {
992
+ retainObservation(meta, record);
993
+ }
994
+ catch (error) {
995
+ detail = `Degraded supervision: observation not retained (${reasonOf(error)}); new parking requires durable storage.`;
996
+ }
997
+ updateParkRecord(input.runId, { heldReason: detail });
998
+ return { outcome: "held", reason: detail };
999
+ };
1000
+ if (!service)
1001
+ return unverified("the Background operation service is unavailable; park finalization awaits compatible supervision");
1002
+ const scope = backgroundScopeForMeta(meta, record);
1003
+ if (!scope)
1004
+ return hold("this run records no conversation workspace for its park wait");
1005
+ // A restart has no exit observation. The staged checkpoint plus a proven-dead
1006
+ // writer is the strongest available evidence; an unknown exit code alone is
1007
+ // never treated as success, but it does not strand a finished attempt either.
1008
+ const writerGone = input.writerPidGone ?? !processExists(meta.pid);
1009
+ const cleanExit = isCleanParkExit(meta) || (input.interrupted === true && writerGone);
1010
+ const disposition = evaluateParkDisposition({ runId: input.runId, cleanExit });
1011
+ if (!disposition.parked) {
1012
+ const reason = disposition.reason ?? "the attempt did not park cleanly";
1013
+ try {
1014
+ const view = service.failWorkerPark(scope, { waitId: record.waitId, generation: record.generation, reason });
1015
+ const phase = phaseOf(view.phase);
1016
+ updateParkRecord(input.runId, { phase, heldReason: phase === "cancelled" ? reason : undefined });
1017
+ return { outcome: phase === "cancelled" ? "cancelled" : "held", reason, wait: view };
1018
+ }
1019
+ catch (error) {
1020
+ return hold(`${reason}; releasing the wait failed: ${reasonOf(error)}`);
1021
+ }
1022
+ }
1023
+ const proof = {
1024
+ checkpointRecorded: record.checkpoint !== undefined,
1025
+ writerLeaseReleased: input.writerLeaseReleased,
1026
+ writerPidGone: input.writerPidGone ?? !processExists(meta.pid),
1027
+ };
1028
+ if (!proof.checkpointRecorded || !proof.writerLeaseReleased || !proof.writerPidGone) {
1029
+ const missing = [
1030
+ proof.checkpointRecorded ? undefined : "the checkpoint was not recorded",
1031
+ proof.writerLeaseReleased ? undefined : "the writer lease was not released",
1032
+ proof.writerPidGone ? undefined : "the original writer process is still alive",
1033
+ ].filter(Boolean).join("; ");
1034
+ return hold(`the parked wait needs proven exit: ${missing}`);
1035
+ }
1036
+ try {
1037
+ const view = await service.checkpointWorkerWait(scope, {
1038
+ waitId: record.waitId,
1039
+ generation: record.generation,
1040
+ proof,
1041
+ });
1042
+ updateParkRecord(input.runId, {
1043
+ phase: phaseOf(view.phase),
1044
+ heldReason: view.phase === "held" ? "the Background host held the wait after checkout" : undefined,
1045
+ });
1046
+ return { outcome: "parked", wait: view, proof };
1047
+ }
1048
+ catch (error) {
1049
+ try {
1050
+ service.listWorkerWaits(scope);
1051
+ }
1052
+ catch {
1053
+ return unverified(`park finalization could not be verified (${reasonOf(error)})`);
1054
+ }
1055
+ return hold(`the Background host refused the park checkpoint: ${reasonOf(error)}`);
1056
+ }
1057
+ }
1058
+ /** Read-only mirror of Goal's public session-entry shape (no Goal import). */
1059
+ const GOAL_SESSION_ENTRY = "pi-better-goal";
1060
+ const LEGACY_GOAL_SESSION_ENTRY = "pi-codex-goal";
1061
+ /**
1062
+ * Current Goal binding for a foreground context, or null when no goal is
1063
+ * recorded. Only the id is read: status, holds and workflow gates stay Goal's
1064
+ * decision, answered through the admission event. An unreadable branch yields
1065
+ * `null`, so admission refuses instead of resuming against a guessed goal.
1066
+ */
1067
+ export function readGoalBinding(ctx) {
1068
+ if (!ctx)
1069
+ return { goalId: null, branchId: null };
1070
+ try {
1071
+ const branch = ctx.sessionManager.getBranch();
1072
+ let goalId = null;
1073
+ for (const entry of branch) {
1074
+ if (entry?.type !== "custom")
1075
+ continue;
1076
+ if (entry.customType !== GOAL_SESSION_ENTRY && entry.customType !== LEGACY_GOAL_SESSION_ENTRY)
1077
+ continue;
1078
+ const data = entry.data;
1079
+ if (!data || typeof data !== "object")
1080
+ continue;
1081
+ if (data.kind === "clear")
1082
+ goalId = null;
1083
+ if (data.kind === "set") {
1084
+ const goal = data.goal;
1085
+ goalId = typeof goal?.goalId === "string" ? goal.goalId : goalId;
1086
+ }
1087
+ }
1088
+ const last = branch.at(-1);
1089
+ return { goalId, branchId: typeof last?.id === "string" ? last.id : null };
1090
+ }
1091
+ catch {
1092
+ return { goalId: null, branchId: null };
1093
+ }
1094
+ }
1095
+ /** True when the recorded branch anchor is still on the current branch. */
1096
+ export function branchContains(ctx, anchor) {
1097
+ try {
1098
+ return ctx.sessionManager.getBranch().some((entry) => entry.id === anchor);
1099
+ }
1100
+ catch {
1101
+ return false;
1102
+ }
1103
+ }
1104
+ /** Owner binding recorded at launch for a foreground context. */
1105
+ export function ownerBindingFromContext(ctx) {
1106
+ const { goalId, branchId } = readGoalBinding(ctx);
1107
+ let sessionId;
1108
+ try {
1109
+ sessionId = ctx.sessionManager.getSessionId();
1110
+ }
1111
+ catch {
1112
+ sessionId = "";
1113
+ }
1114
+ return { sessionId, workspace: ctx.cwd, branchId, goalId };
1115
+ }
1116
+ /**
1117
+ * Legacy parent Goal admission helper. Delegated assignments do not call this.
1118
+ * The owner binding is the one captured when the worker parked.
1119
+ */
1120
+ export async function requestResumeAdmission(pi, owner, options = {}) {
1121
+ const bus = serviceBusOf(pi);
1122
+ if (!bus) {
1123
+ return { allowed: false, reason: "No Goal admission channel is available; a resume needs an active owning parent.", revision: -1 };
1124
+ }
1125
+ const timeoutMs = Math.max(50, Math.min(60_000, options.timeoutMs ?? 10_000));
1126
+ const answer = await new Promise((resolve) => {
1127
+ let settled = false;
1128
+ const finish = (value) => {
1129
+ if (settled)
1130
+ return;
1131
+ settled = true;
1132
+ clearTimeout(timer);
1133
+ resolve(value);
1134
+ };
1135
+ let timer = setTimeout(() => finish(null), timeoutMs);
1136
+ timer.unref?.();
1137
+ let pending = false;
1138
+ const request = {
1139
+ version: 1,
1140
+ owner: {
1141
+ sessionId: owner.sessionId,
1142
+ workspace: owner.workspace,
1143
+ branchId: owner.branchId,
1144
+ goalId: owner.goalId,
1145
+ },
1146
+ pending: () => {
1147
+ if (pending || settled || options.pendingTimeoutMs === undefined)
1148
+ return;
1149
+ pending = true;
1150
+ clearTimeout(timer);
1151
+ const budget = Math.max(timeoutMs, Math.min(60_000, options.pendingTimeoutMs));
1152
+ timer = setTimeout(() => finish({ allowed: false, reason: `Workflow admission did not answer within ${budget} ms`, revision: 0 }), budget);
1153
+ timer.unref?.();
1154
+ },
1155
+ reply: (gate) => {
1156
+ if (!gate || typeof gate.allowed !== "boolean") {
1157
+ finish({ allowed: false, reason: "Goal returned a malformed resume admission", revision: -1 });
1158
+ return;
1159
+ }
1160
+ finish(gate.allowed
1161
+ ? { allowed: true, revision: typeof gate.revision === "number" ? gate.revision : 0,
1162
+ ...(typeof gate.isCurrent === "function" ? { isCurrent: gate.isCurrent } : {}) }
1163
+ : {
1164
+ allowed: false,
1165
+ reason: typeof gate.reason === "string" && gate.reason ? gate.reason : "Goal refused the resume",
1166
+ revision: typeof gate.revision === "number" ? gate.revision : 0,
1167
+ });
1168
+ },
1169
+ };
1170
+ try {
1171
+ bus.emit(OPERATION_RESUME_ADMISSION_EVENT, request);
1172
+ }
1173
+ catch {
1174
+ finish({ allowed: false, reason: "The Goal admission channel failed", revision: -1 });
1175
+ }
1176
+ });
1177
+ if (answer)
1178
+ return answer;
1179
+ return {
1180
+ allowed: false,
1181
+ reason: "No Goal admission answer arrived; a resume needs an active owning parent and Goal gate.",
1182
+ revision: -1,
1183
+ };
1184
+ }
1185
+ function parkedEntry(meta, record) {
1186
+ return {
1187
+ runId: meta.id,
1188
+ conversationId: meta.sessionId,
1189
+ attemptId: meta.id,
1190
+ waitId: record.waitId,
1191
+ generation: record.generation,
1192
+ phase: record.phase,
1193
+ meta,
1194
+ record,
1195
+ };
1196
+ }
1197
+ /** Parked runs whose wait can still resume (including held ones). */
1198
+ export function parkedWaits() {
1199
+ const parked = [];
1200
+ for (const meta of listPendingParkedRuns()) {
1201
+ const record = readParkRecord(meta.id);
1202
+ if (!record || !isPendingPark(record))
1203
+ continue;
1204
+ parked.push(parkedEntry(meta, record));
1205
+ }
1206
+ return parked;
1207
+ }
1208
+ export function parkedWaitForRun(runId) {
1209
+ const meta = readMeta(runId);
1210
+ const record = meta && readParkRecord(runId);
1211
+ return meta && record && isPendingPark(record) ? parkedEntry(meta, record) : null;
1212
+ }
1213
+ /** A parked attempt's record for one wait generation, in any phase. */
1214
+ export async function parkedWaitByGeneration(waitId, generation) {
1215
+ for await (const { meta, record } of scanParkRecords()) {
1216
+ if (record.waitId !== waitId || record.generation !== generation)
1217
+ continue;
1218
+ return parkedEntry(meta, record);
1219
+ }
1220
+ return null;
1221
+ }
1222
+ /** Refusal text for a manual continuation of a conversation parked on a wait. */
1223
+ export function manualResumeRefusal(parked) {
1224
+ return `Cannot continue ${parked.runId} manually: it is parked on wait ${parked.waitId} generation ${parked.generation} (${parked.phase}) and will resume automatically when its dependency settles. ` +
1225
+ `To take over, run subagent_stop ${parked.runId} first; that cancels the pending automatic resume.`;
1226
+ }
1227
+ /**
1228
+ * Default owner-checked stopper: only a child this parent spawned, whose recorded
1229
+ * publication token matches, may be stopped. Anything else is reported as
1230
+ * `foreign` so no pid is signalled on a guess.
1231
+ */
1232
+ export function createOwnedAttemptStopper(options = {}) {
1233
+ const parentPid = options.parentPid ?? process.pid;
1234
+ const stop = options.stop ?? ((attemptId) => stopRun(attemptId));
1235
+ return (input) => {
1236
+ const meta = readMeta(input.attemptId);
1237
+ if (!meta)
1238
+ return "aborted";
1239
+ if (meta.spawnPid !== parentPid)
1240
+ return "foreign";
1241
+ if (input.launchToken && meta.operations?.resumeLaunchToken !== input.launchToken)
1242
+ return "foreign";
1243
+ const outcome = stop(input.attemptId);
1244
+ return outcome.action === "stopped" || outcome.action === "finalized" ? "stopped" : "aborted";
1245
+ };
1246
+ }
1247
+ /**
1248
+ * A continuation refused before any child could exist (planning, capacity,
1249
+ * current permission admission, writer lease). The launcher throws this only for
1250
+ * a proven pre-spawn failure; anything else is ambiguous and is held.
1251
+ */
1252
+ export class PreSpawnResumeError extends Error {
1253
+ constructor(message) {
1254
+ super(message);
1255
+ this.name = "PreSpawnResumeError";
1256
+ }
1257
+ }
1258
+ /**
1259
+ * Release one child: the synchronous dispatch guard runs with no await (and no
1260
+ * other code) between it and the spawn, so nothing can slip in after the guard.
1261
+ */
1262
+ export function releaseChild(guard, spawn) {
1263
+ if (typeof guard === "function")
1264
+ guard();
1265
+ return spawn();
1266
+ }
1267
+ /** A proven pre-spawn refusal from the final dispatch fence. */
1268
+ export class FinalDispatchRefusal extends PreSpawnResumeError {
1269
+ constructor(message) {
1270
+ super(message);
1271
+ this.name = "FinalDispatchRefusal";
1272
+ }
1273
+ }
1274
+ /**
1275
+ * Final dispatch fence.
1276
+ *
1277
+ * Final dispatch checks the compatible host, captured permission scope, durable
1278
+ * claim, cancellation epoch, launch identity and capacity. Parent Goal, session
1279
+ * and branch changes do not revoke an existing assignment.
1280
+ */
1281
+ export async function assertFinalResumeDispatch(input) {
1282
+ const refusal = (message) => {
1283
+ throw new FinalDispatchRefusal(message);
1284
+ };
1285
+ const assertIdentity = (_phase) => {
1286
+ const ctx = input.context();
1287
+ if (!ctx)
1288
+ refusal("No compatible supervisor host is available");
1289
+ if (canonical(ctx.cwd) !== canonical(input.owner.workspace)) {
1290
+ refusal("The supervisor workspace is incompatible with the assignment");
1291
+ }
1292
+ if (input.service()?.assignmentContinuation !== 1) {
1293
+ refusal("The Background host does not support assignment-local continuation");
1294
+ }
1295
+ };
1296
+ /**
1297
+ * The only durable confirmation that matters at release time.
1298
+ *
1299
+ * `listWorkerWaits` is synchronous, so it runs after every await and directly
1300
+ * before the spawn with no window for cancellation, a claim change or a parent
1301
+ * switch to hide inside. The store enforces one active claim per generation, and
1302
+ * the async part above already replayed `publish-resume` with the exact token,
1303
+ * so phase + cancellation epoch identify this publication.
1304
+ */
1305
+ const durableGuard = () => {
1306
+ const service = input.service();
1307
+ if (!service)
1308
+ refusal("The Background operation service is unavailable at dispatch; the continuation was not started");
1309
+ const scope = backgroundScopeForMeta(input.park.meta, input.park.record);
1310
+ if (!scope)
1311
+ refusal("The parked attempt records no worker conversation scope; the continuation was not started");
1312
+ let view;
1313
+ try {
1314
+ view = service.listWorkerWaits(scope, { pendingOnly: true })
1315
+ .find((entry) => entry.waitId === input.park.waitId && entry.generation === input.park.generation);
1316
+ }
1317
+ catch (error) {
1318
+ refusal(`The durable wait could not be read at dispatch: ${reasonOf(error)}`);
1319
+ }
1320
+ if (!view) {
1321
+ refusal("The durable wait is gone at dispatch (consumed or cancelled); the continuation was not started");
1322
+ }
1323
+ if (view.phase !== "resuming") {
1324
+ refusal(`The durable wait is ${view.phase} at dispatch, not resuming; the continuation was not started`);
1325
+ }
1326
+ if (view.cancelEpoch !== input.claim.cancelEpoch) {
1327
+ refusal("The wait was cancelled or replaced at dispatch; the continuation was not started");
1328
+ }
1329
+ };
1330
+ const guard = () => {
1331
+ assertIdentity("dispatch");
1332
+ if (!input.permissionsUnchanged()) {
1333
+ refusal("The worker's permissions changed before dispatch; the continuation was not started");
1334
+ }
1335
+ if (!input.capacityAvailable()) {
1336
+ refusal("Capacity changed before dispatch; the continuation was not started");
1337
+ }
1338
+ durableGuard();
1339
+ input.extraCheck?.();
1340
+ // Identity can only change synchronously through this process, so one final
1341
+ // read after the durable check closes the guard.
1342
+ assertIdentity("release");
1343
+ };
1344
+ // Synchronous identity and captured policy first: cheap and fail-closed.
1345
+ assertIdentity("preparation");
1346
+ if (!input.permissionsUnchanged()) {
1347
+ refusal("The worker's permissions changed while the resume was being prepared; the continuation was not started");
1348
+ }
1349
+ if (!input.capacityAvailable()) {
1350
+ refusal("Capacity changed while the resume was being prepared; the continuation was not started");
1351
+ }
1352
+ // Durable claim, phase and cancellation epoch (async pre-check).
1353
+ const snapshot = await input.rpc.call("wait-snapshot", {
1354
+ waitId: input.park.waitId,
1355
+ generation: input.park.generation,
1356
+ });
1357
+ if (snapshot.phase !== "resuming") {
1358
+ refusal(`The durable wait is ${String(snapshot.phase)}, not resuming; the continuation was not started`);
1359
+ }
1360
+ if (Number(snapshot.cancelEpoch ?? -1) !== input.claim.cancelEpoch) {
1361
+ refusal("The wait was cancelled or replaced while the resume was being prepared; the continuation was not started");
1362
+ }
1363
+ const active = snapshot.claim;
1364
+ if (!active || active.state !== "published" || active.attemptId !== input.claim.attemptId) {
1365
+ refusal("The published resume claim no longer names this attempt; the continuation was not started");
1366
+ }
1367
+ // Exact launch token: replaying the publication is idempotent only for the
1368
+ // same (claim, token, attempt, launch token) tuple.
1369
+ await input.rpc.call("publish-resume", {
1370
+ runId: input.park.runId,
1371
+ waitId: input.park.waitId,
1372
+ generation: input.park.generation,
1373
+ claimId: input.claim.claimId,
1374
+ claimToken: input.claim.claimToken,
1375
+ attemptId: input.claim.attemptId,
1376
+ launchToken: input.claim.launchToken,
1377
+ });
1378
+ // Parent workflow state is provenance, not assignment authority.
1379
+ // Validate the synchronous guard once here (so the returned guard is known to
1380
+ // hold after the last await) and hand it back for the release point.
1381
+ guard();
1382
+ return guard;
1383
+ }
1384
+ /**
1385
+ * One resume at a time, through the existing continuation launch path.
1386
+ *
1387
+ * Order is fixed: capacity is reserved with the ordinary gate, captured assignment
1388
+ * scope is restored, the durable wait is
1389
+ * re-read, the attempt id/token are written to the park record, and only then is
1390
+ * a child spawned. A full capacity defers delivery without touching the wait, so
1391
+ * a queued resume never becomes "held". A proven pre-spawn failure holds the wait
1392
+ * with its reason; an ambiguous failure holds without relaunching.
1393
+ */
1394
+ export function createResumeOrchestration(options) {
1395
+ const inFlight = new Set();
1396
+ const now = options.now ?? (() => Date.now());
1397
+ const hold = (park, reason) => {
1398
+ updateParkRecord(park.runId, { phase: "held", heldReason: reason });
1399
+ try {
1400
+ options.service()?.failWorkerPark(backgroundScopeForMeta(park.meta, park.record) ?? {
1401
+ runId: park.runId,
1402
+ conversationId: park.conversationId,
1403
+ workspace: park.meta.operations?.workspace ?? park.meta.cwd,
1404
+ authorityReference: park.meta.operations?.authorityReference ?? `worker:${park.runId}`,
1405
+ }, { waitId: park.waitId, generation: park.generation, reason });
1406
+ }
1407
+ catch { /* the park record still shows the hold */ }
1408
+ if (park.meta.assignment)
1409
+ commitAssignmentTerminal({ ...park.meta, status: "failed", failureReason: reason }, true);
1410
+ try {
1411
+ if (!options.notifyWhen || options.notifyWhen(park.meta))
1412
+ options.notify?.(`Subagent ${park.runId} wait ${park.waitId} is held: ${reason}`, "warning");
1413
+ }
1414
+ catch { /* ignore UI failures */ }
1415
+ return "held";
1416
+ };
1417
+ const resumeInScope = async (park) => {
1418
+ const key = `${park.waitId}:${park.generation}`;
1419
+ if (inFlight.has(key))
1420
+ return "skipped";
1421
+ inFlight.add(key);
1422
+ let capacity;
1423
+ let reserved = false;
1424
+ try {
1425
+ capacity = typeof options.capacity === "function" ? options.capacity(park) : options.capacity;
1426
+ // The durable wait is the authority for readiness (checked below). A
1427
+ // record that is in flight or already held must never start another
1428
+ // automatic attempt: `resuming` has a published attempt, and `held`
1429
+ // waits for its owner's interpretation.
1430
+ if (park.record.phase === "resuming" || park.record.phase === "held")
1431
+ return "skipped";
1432
+ const ctx = options.context(park);
1433
+ if (!ctx)
1434
+ return "skipped";
1435
+ const current = ownerBindingFromContext(ctx);
1436
+ if (park.record.ownerWorkspace && canonical(park.record.ownerWorkspace) !== canonical(current.workspace))
1437
+ return "skipped";
1438
+ const prior = readMeta(park.runId);
1439
+ if (prior && prior.status === "running" && processExists(prior.pid))
1440
+ return "skipped";
1441
+ const service = options.service();
1442
+ if (!service)
1443
+ return "skipped";
1444
+ if (service.assignmentContinuation !== 1)
1445
+ return hold(park, "The Background host does not support assignment-local continuation");
1446
+ if (!park.meta.operations?.policy)
1447
+ return hold(park, "The captured assignment permission policy is missing; migration refused");
1448
+ if (park.meta.operations.policy.deadlineAt !== null && park.meta.operations.policy.deadlineAt <= now())
1449
+ return hold(park, "The assignment-local deadline expired");
1450
+ const scope = backgroundScopeForMeta(park.meta, park.record);
1451
+ if (!scope)
1452
+ return "skipped";
1453
+ if (!park.record.ownerSessionId && !park.meta.callbackOrigin?.sessionId) {
1454
+ return hold(park, "The captured assignment recipient is missing; migration refused");
1455
+ }
1456
+ // Capacity FIRST: a saturated pool leaves the generation ready and the
1457
+ // delivery pending, so a queued resume never becomes "held" and no
1458
+ // unresumable claim is published.
1459
+ if (!capacity.tryReserve())
1460
+ return "skipped";
1461
+ reserved = true;
1462
+ if (!capacity.recheck()) {
1463
+ capacity.release();
1464
+ reserved = false;
1465
+ return "skipped";
1466
+ }
1467
+ // Captured recipient metadata is never replaced by the host's session.
1468
+ const owner = {
1469
+ sessionId: park.record.ownerSessionId ?? park.meta.callbackOrigin.sessionId,
1470
+ workspace: park.record.ownerWorkspace ?? park.meta.callbackOrigin?.cwd ?? current.workspace,
1471
+ branchId: park.record.ownerBranchId ?? null,
1472
+ goalId: park.record.ownerGoalId ?? null,
1473
+ };
1474
+ const admission = { revision: 0 };
1475
+ // Rehydrate the parked attempt's run binding: the claim fence is
1476
+ // addressed by run id and requires a binding for this conversation.
1477
+ await options.rpc.call("register-run", {
1478
+ runId: park.runId,
1479
+ conversationId: scope.conversationId,
1480
+ attemptId: park.runId,
1481
+ workspace: scope.workspace,
1482
+ authorityReference: scope.authorityReference,
1483
+ policy: {
1484
+ version: 1,
1485
+ sandbox: park.meta.operations?.policy?.sandbox ?? null,
1486
+ tools: park.meta.operations?.policy?.tools ?? [],
1487
+ clean: park.meta.operations?.policy?.clean === true,
1488
+ deadlineAt: park.meta.operations?.policy?.deadlineAt ?? null,
1489
+ authorityReference: scope.authorityReference,
1490
+ workspace: scope.workspace,
1491
+ },
1492
+ tools: park.meta.operations?.tools ?? [],
1493
+ capabilities: {},
1494
+ owner: {
1495
+ kind: "worker-conversation",
1496
+ sessionId: scope.conversationId,
1497
+ workspace: scope.workspace,
1498
+ branchId: owner.branchId,
1499
+ goalId: owner.goalId,
1500
+ },
1501
+ });
1502
+ const snapshot = await options.rpc.call("wait-snapshot", {
1503
+ waitId: park.waitId,
1504
+ generation: park.generation,
1505
+ });
1506
+ if (snapshot.phase !== "ready") {
1507
+ capacity.release();
1508
+ reserved = false;
1509
+ if (snapshot.phase === "waiting" || snapshot.phase === "parking" || snapshot.phase === "resuming") {
1510
+ if (snapshot.phase !== park.phase)
1511
+ updateParkRecord(park.runId, { phase: phaseOf(String(snapshot.phase)) });
1512
+ return "skipped";
1513
+ }
1514
+ updateParkRecord(park.runId, { phase: phaseOf(String(snapshot.phase)) });
1515
+ return "skipped";
1516
+ }
1517
+ if (snapshot.claim) {
1518
+ // Another supervisor holds or published this generation.
1519
+ capacity.release();
1520
+ reserved = false;
1521
+ return "skipped";
1522
+ }
1523
+ const expectedCancelEpoch = typeof snapshot.cancelEpoch === "number" ? snapshot.cancelEpoch : 0;
1524
+ const claim = await options.rpc.call("claim-resume", {
1525
+ runId: park.runId,
1526
+ waitId: park.waitId,
1527
+ generation: park.generation,
1528
+ expectedCancelEpoch,
1529
+ lease: { ownerId: options.leaseOwnerId ?? `subagents:${process.pid}`, pid: process.pid, processStartToken: processStartToken(process.pid) ? Buffer.from(processStartToken(process.pid)).toString("base64url") : undefined },
1530
+ reservedCheckpointId: park.record.checkpoint?.entryId ?? park.waitId,
1531
+ });
1532
+ const claimId = String(claim.claimId ?? "");
1533
+ const claimToken = String(claim.claimToken ?? "");
1534
+ const assignedRunId = `sa_${now().toString(36)}_${randomUUID().replace(/-/g, "").slice(0, 8)}`;
1535
+ const launchToken = `slt_${randomUUID()}`;
1536
+ if (!claimId || !claimToken) {
1537
+ capacity.release();
1538
+ reserved = false;
1539
+ return hold(park, "the Background host returned no usable resume claim");
1540
+ }
1541
+ try {
1542
+ await options.rpc.call("publish-resume", {
1543
+ runId: park.runId,
1544
+ waitId: park.waitId,
1545
+ generation: park.generation,
1546
+ claimId,
1547
+ claimToken,
1548
+ attemptId: assignedRunId,
1549
+ launchToken,
1550
+ });
1551
+ }
1552
+ catch (error) {
1553
+ capacity.release();
1554
+ reserved = false;
1555
+ try {
1556
+ await options.rpc.call("release-resume", {
1557
+ runId: park.runId,
1558
+ waitId: park.waitId,
1559
+ generation: park.generation,
1560
+ claimId,
1561
+ claimToken,
1562
+ outcome: "ready",
1563
+ reason: reasonOf(error),
1564
+ });
1565
+ }
1566
+ catch { /* the claim stays for reconciliation */ }
1567
+ return hold(park, reasonOf(error));
1568
+ }
1569
+ // Mirror the published attempt identity into the park record. The store
1570
+ // claim is the cross-process fence; this keeps the local record readable.
1571
+ updateParkRecord(park.runId, {
1572
+ phase: "resuming",
1573
+ resumedAt: now(),
1574
+ resumedBy: assignedRunId,
1575
+ resumeLaunchToken: launchToken,
1576
+ resumeClaimId: claimId,
1577
+ resumeClaimToken: claimToken,
1578
+ heldReason: undefined,
1579
+ });
1580
+ try {
1581
+ await options.launch({
1582
+ park,
1583
+ assignedRunId,
1584
+ launchToken,
1585
+ claim: {
1586
+ claimId,
1587
+ claimToken,
1588
+ cancelEpoch: expectedCancelEpoch,
1589
+ attemptId: assignedRunId,
1590
+ launchToken,
1591
+ },
1592
+ admissionRevision: admission.revision,
1593
+ });
1594
+ }
1595
+ catch (error) {
1596
+ const reason = reasonOf(error);
1597
+ // A published claim cannot be released; the durable record holds it
1598
+ // for recovery. Capacity and admission already succeeded, so this is a
1599
+ // spawn-time failure, not a queue condition.
1600
+ updateParkRecord(park.runId, { phase: "held", heldReason: reason });
1601
+ if (park.meta.assignment)
1602
+ commitAssignmentTerminal({ ...park.meta, status: "lost", failureReason: `Published launch could not be proved: ${reason}` }, true);
1603
+ return "held";
1604
+ }
1605
+ capacity.commit();
1606
+ reserved = false;
1607
+ void options.rpc.call("release-run", { runId: park.runId, reason: "resumed into a new attempt" }).catch(() => { });
1608
+ return "resumed";
1609
+ }
1610
+ catch (error) {
1611
+ return hold(park, reasonOf(error));
1612
+ }
1613
+ finally {
1614
+ if (reserved)
1615
+ capacity?.release();
1616
+ inFlight.delete(key);
1617
+ }
1618
+ };
1619
+ const resume = (park) => options.dispatch
1620
+ ? options.dispatch(park, () => resumeInScope(park)).catch(error => hold(park, reasonOf(error)))
1621
+ : resumeInScope(park);
1622
+ const adapter = {
1623
+ version: 1,
1624
+ id: `subagents-continuation:${randomUUID()}`,
1625
+ async onWaitReady(event) {
1626
+ let park;
1627
+ if (event.parkedAttemptId !== undefined) {
1628
+ const meta = readMeta(event.parkedAttemptId);
1629
+ const record = meta && readParkRecord(meta.id);
1630
+ if (!meta || meta.sessionId !== event.owner.sessionId || !record
1631
+ || record.waitId !== event.waitId || record.generation !== event.generation)
1632
+ return "deferred";
1633
+ park = parkedEntry(meta, record);
1634
+ }
1635
+ else {
1636
+ park = await parkedWaitByGeneration(event.waitId, event.generation);
1637
+ }
1638
+ if (!park)
1639
+ return "delivered";
1640
+ const outcome = await resume(park);
1641
+ return outcome === "skipped" ? "deferred" : "delivered";
1642
+ },
1643
+ async onWaitCancelled(event) {
1644
+ const park = await parkedWaitByGeneration(event.waitId, event.generation);
1645
+ if (!park || park.record.phase === "cancelled")
1646
+ return;
1647
+ const cancellation = await stopPublishedAttempt(park, event.reason, options.stopAttempt, options.now);
1648
+ updateParkRecord(park.runId, {
1649
+ phase: "cancelled",
1650
+ cancelReason: cancellation === "stopped"
1651
+ ? `${event.reason} (the published continuation ${park.record.resumedBy} was stopped)`
1652
+ : cancellation === "foreign"
1653
+ ? `${event.reason} (the published continuation could not be attributed to this parent and was left running)`
1654
+ : event.reason,
1655
+ cancelledAt: now(),
1656
+ });
1657
+ },
1658
+ };
1659
+ return {
1660
+ resume,
1661
+ adapter,
1662
+ stop() {
1663
+ try {
1664
+ options.service()?.unregisterContinuationAdapter(adapter.id);
1665
+ }
1666
+ catch { /* host already gone */ }
1667
+ },
1668
+ };
1669
+ }
1670
+ function reasonOf(error) {
1671
+ return error instanceof Error ? error.message : String(error);
1672
+ }
1673
+ /**
1674
+ * Cancel a parked assignment's automatic resume. Called by `subagent_stop`.
1675
+ * The durable wait is cancelled first; the run record is marked so nothing
1676
+ * resumes it.
1677
+ */
1678
+ export async function cancelParkedWait(service, park, reason, options = {}) {
1679
+ // Cancel the durable wait first: no new claim can be published after this.
1680
+ // The registered continuation adapter is notified by the host and performs the
1681
+ // same follow-up, so an already-recorded cancellation is left alone.
1682
+ const scope = backgroundScopeForMeta(park.meta, park.record);
1683
+ const at = (options.now ?? Date.now)();
1684
+ if (park.meta.assignment) {
1685
+ const outcome = commitAssignmentTerminal({ ...park.meta, status: "killed" });
1686
+ if (outcome?.outcome !== "cancelled")
1687
+ throw new Error("The assignment already has a non-cancelled terminal outcome; cancellation was not committed.");
1688
+ const cancellation = await stopPublishedAttempt(park, reason, options.stopAttempt, options.now);
1689
+ updateParkRecord(park.runId, { phase: "cancelled", cancelReason: cancellation === "foreign" ? `${reason} (published writer termination remains unproven)` : reason, cancelledAt: at });
1690
+ return;
1691
+ }
1692
+ if (service && scope) {
1693
+ let view;
1694
+ try {
1695
+ view = service.cancelWorkerWait(scope, { waitId: park.waitId, generation: park.generation, reason });
1696
+ }
1697
+ catch (error) {
1698
+ updateParkRecord(park.runId, {
1699
+ phase: "held",
1700
+ cancelReason: `${reason} (the durable cancellation failed: ${reasonOf(error)})`,
1701
+ });
1702
+ throw new Error(`Durable cancellation failed: ${reasonOf(error)}`);
1703
+ }
1704
+ if (view.phase !== "cancelled")
1705
+ throw new Error(`Durable cancellation was not confirmed (wait is ${view.phase}).`);
1706
+ const settled = readParkRecord(park.runId);
1707
+ if (settled?.phase === "cancelled" && settled.cancelReason)
1708
+ return;
1709
+ const cancellation = await stopPublishedAttempt(park, reason, options.stopAttempt, options.now);
1710
+ updateParkRecord(park.runId, {
1711
+ phase: phaseOf(view.phase),
1712
+ cancelReason: cancellation === "stopped"
1713
+ ? `${reason} (the published continuation ${park.record.resumedBy} was stopped)`
1714
+ : cancellation === "foreign"
1715
+ ? `${reason} (the published continuation could not be attributed to this parent and was left running)`
1716
+ : reason,
1717
+ cancelledAt: at,
1718
+ });
1719
+ return;
1720
+ }
1721
+ throw new Error("Durable cancellation unavailable: the original worker scope and observed-waits service are required.");
1722
+ }
1723
+ /**
1724
+ * Follow a cancelled generation to the attempt it already published.
1725
+ *
1726
+ * A `resuming` record with no registered attempt is a pre-dispatch abort: nothing
1727
+ * was spawned. A record whose attempt exists is stopped only through the injected
1728
+ * owner-checked seam; an unattributable identity is reported as `foreign` and left
1729
+ * alone, never signalled by pid guesswork.
1730
+ */
1731
+ async function stopPublishedAttempt(park, reason, stopAttempt, now) {
1732
+ const attemptId = park.record.resumedBy;
1733
+ if (!attemptId)
1734
+ return "none";
1735
+ const meta = readMeta(attemptId);
1736
+ if (!meta) {
1737
+ updateParkRecord(park.runId, { phase: "cancelled", cancelReason: reason, cancelledAt: (now ?? Date.now)() });
1738
+ return "aborted";
1739
+ }
1740
+ if (!stopAttempt)
1741
+ return "foreign";
1742
+ try {
1743
+ return await stopAttempt({
1744
+ attemptId,
1745
+ launchToken: park.record.resumeLaunchToken,
1746
+ waitId: park.waitId,
1747
+ generation: park.generation,
1748
+ reason,
1749
+ });
1750
+ }
1751
+ catch {
1752
+ return "foreign";
1753
+ }
1754
+ }
1755
+ /**
1756
+ * Reconcile parked generations at session start.
1757
+ *
1758
+ * A `resuming` record with no attempt metadata is the crash window between the
1759
+ * durable pre-spawn write and the spawn: it is held, never relaunched. A ready
1760
+ * generation whose delivery was missed (inactive owner, host restart) is resumed
1761
+ * here. Everything else mirrors the durable phase.
1762
+ */
1763
+ /**
1764
+ * Retry a staged park after a restart.
1765
+ *
1766
+ * Evidence required: the staged checkpoint still verifies, the recorded writer
1767
+ * process is gone, and no live conversation writer lease remains. A live writer,
1768
+ * a lease held by a live process, or a missing/foreign identity is reported as an
1769
+ * explicit hold, never left indistinguishable from a healthy `parking` wait.
1770
+ */
1771
+ /**
1772
+ * Whether the recorded writer process is still alive, proven independently of the
1773
+ * recorded status. `unverified` means a live pid exists but its process-start
1774
+ * identity cannot be compared, so neither "gone" nor "the same writer" is proven.
1775
+ */
1776
+ export function writerPresence(meta, probe = realProcessProbe) {
1777
+ if (!Number.isInteger(meta.pid) || meta.pid <= 0)
1778
+ return "absent";
1779
+ if (!probe.pidExists(meta.pid))
1780
+ return "absent";
1781
+ if (meta.pidStartTime === undefined)
1782
+ return "unverified";
1783
+ const token = probe.startToken?.(meta.pid);
1784
+ if (token === undefined)
1785
+ return "unverified";
1786
+ // A different start token is a recycled pid: the recorded writer is gone.
1787
+ return token === meta.pidStartTime ? "alive" : "absent";
1788
+ }
1789
+ export async function recoverStagedPark(park, service, options = {}) {
1790
+ const writer = writerPresence(park.meta, options.probe ?? realProcessProbe);
1791
+ if (writer === "alive") {
1792
+ // A supervised running attempt still has its exit handler; anything else
1793
+ // may still be appending to the saved conversation, and a fresh writer has
1794
+ // no lease, so a live process is the only reliable evidence.
1795
+ if (park.meta.status === "running")
1796
+ return "skipped";
1797
+ updateParkRecord(park.runId, {
1798
+ phase: "held",
1799
+ heldReason: `the staged park cannot be finalized while writer pid ${park.meta.pid} is still alive (${park.meta.status})`,
1800
+ });
1801
+ return "held";
1802
+ }
1803
+ if (writer === "unverified") {
1804
+ updateParkRecord(park.runId, {
1805
+ phase: "held",
1806
+ heldReason: `the recorded writer pid ${park.meta.pid} is alive but its process identity cannot be verified, so its exit is unproven`,
1807
+ });
1808
+ return "held";
1809
+ }
1810
+ const lease = readConversationLease(park.meta.sessionId);
1811
+ const leaseStart = lease ? processStartToken(lease.pid) : undefined;
1812
+ const leaseLive = lease !== undefined
1813
+ && (options.writerLeaseLocked?.(park.meta.sessionId)
1814
+ ?? (processExists(lease.pid) && (lease.start === undefined || leaseStart === undefined || lease.start === leaseStart)));
1815
+ if (leaseLive) {
1816
+ updateParkRecord(park.runId, {
1817
+ phase: "held",
1818
+ heldReason: "the staged park cannot be finalized while a live conversation writer lease is held",
1819
+ });
1820
+ return "held";
1821
+ }
1822
+ const scope = backgroundScopeForMeta(park.meta, park.record);
1823
+ if (!scope) {
1824
+ updateParkRecord(park.runId, { phase: "held", heldReason: "the staged park records no worker conversation workspace" });
1825
+ return "held";
1826
+ }
1827
+ const result = await finalizeWorkerParkAfterExit({
1828
+ runId: park.runId,
1829
+ service,
1830
+ writerLeaseReleased: true,
1831
+ writerPidGone: true,
1832
+ interrupted: true,
1833
+ });
1834
+ if (result.outcome !== "parked")
1835
+ return "held";
1836
+ if (result.wait?.phase === "ready")
1837
+ return "ready";
1838
+ return "parked";
1839
+ }
1840
+ /** Every park record (any phase) that published `attemptId` as its resume. */
1841
+ export function parkedWaitsForResumedAttempt(attemptId) {
1842
+ const found = [];
1843
+ for (const meta of listParkRecordCandidates()) {
1844
+ const record = readParkRecord(meta.id);
1845
+ if (!record || record.resumedBy !== attemptId)
1846
+ continue;
1847
+ found.push(parkedEntry(meta, record));
1848
+ }
1849
+ return found;
1850
+ }
1851
+ /** Terminal for the purposes of "this attempt will never interpret the wait again". */
1852
+ export function isTerminalAttempt(meta) {
1853
+ const status = effectiveStatus(meta);
1854
+ return status !== "running" && status !== "orphaned";
1855
+ }
1856
+ /** True when a lease payload still names a live writer for the conversation. */
1857
+ export function conversationWriterLeaseLive(sessionId, probe = { pidExists: processExists, startToken: processStartToken }) {
1858
+ const lease = readConversationLease(sessionId);
1859
+ if (!lease)
1860
+ return false;
1861
+ if (!probe.pidExists(lease.pid))
1862
+ return false;
1863
+ if (lease.start === undefined)
1864
+ return true;
1865
+ const current = probe.startToken?.(lease.pid);
1866
+ return current === undefined || current === lease.start;
1867
+ }
1868
+ /**
1869
+ * Hold the unconsumed generation that a published resume attempt was admitted for,
1870
+ * after that attempt exited without interpreting it.
1871
+ *
1872
+ * This is a HOLD, not a cancellation: the store keeps the cancellation epoch and
1873
+ * the evidence pins, records the failure reason, and invalidates the publish-only
1874
+ * claim. Assignment-capable hosts instead atomically admit one bounded repair or
1875
+ * retain terminal failure through the coordinator. This requires the exact
1876
+ * published identity (generation, claim id/token persisted with the attempt,
1877
+ * attempt id, launch token) and proven writer exit plus a free writer lease. An
1878
+ * ambiguous identity (live or unverifiable writer, live lease, missing claim
1879
+ * identity, missing host capability) is reported as a local hold and the durable
1880
+ * generation is left untouched with its live writer — never a fallback cancel.
1881
+ * An interpreted generation needs only claim cleanup; its receipt and assignment
1882
+ * remain unchanged, even if writer exit cannot yet be proved.
1883
+ */
1884
+ export async function settleResumedAttemptExit(input) {
1885
+ if (input.priorPark) {
1886
+ const { runId, waitId, generation } = input.priorPark;
1887
+ const meta = readMeta(runId);
1888
+ const record = meta && readParkRecord(runId);
1889
+ if (!meta || !record || record.waitId !== waitId || record.generation !== generation || record.resumedBy !== input.attemptId) {
1890
+ return { outcome: "ignored" };
1891
+ }
1892
+ return settleResumedAttemptExitForParks(input, [parkedEntry(meta, record)]);
1893
+ }
1894
+ const candidates = [];
1895
+ for await (const { meta, record } of scanParkRecords()) {
1896
+ if (record.resumedBy === input.attemptId)
1897
+ candidates.push(parkedEntry(meta, record));
1898
+ }
1899
+ return settleResumedAttemptExitForParks(input, candidates);
1900
+ }
1901
+ async function settleResumedAttemptExitForParks(input, candidates) {
1902
+ if (candidates.length === 0)
1903
+ return { outcome: "ignored" };
1904
+ const attempt = readMeta(input.attemptId);
1905
+ const at = (input.now ?? Date.now)();
1906
+ let result = { outcome: "ignored" };
1907
+ for (const park of candidates) {
1908
+ if ((park.record.phase === "consumed" && park.record.resumeClaimId && park.record.resumeExitReconciledClaimId === park.record.resumeClaimId)
1909
+ || (park.record.phase === "cancelled" && !park.meta.assignment)) {
1910
+ result = { outcome: "ignored", waitPhase: park.record.phase };
1911
+ continue;
1912
+ }
1913
+ let interpreted = park.record.phase === "consumed";
1914
+ const exitReason = `the published resume attempt ${input.attemptId} exited (${input.status ?? attempt?.status ?? "unknown"})`;
1915
+ let reason = input.reason ?? `${exitReason}${interpreted ? "" : " without interpreting the wait"}`;
1916
+ const holdLocally = (cause, outcome = "deferred") => {
1917
+ updateParkRecord(park.runId, { phase: interpreted ? "consumed" : park.record.phase === "cancelled" ? "cancelled" : "held", heldReason: `${reason}; ${cause}` });
1918
+ const report = attempt ?? park.meta;
1919
+ if (!interpreted && input.service && report.assignment) {
1920
+ commitAssignmentTerminal({ ...report, status: "lost", failureReason: `${reason}; ${cause}` }, true);
1921
+ }
1922
+ result = { outcome, reason };
1923
+ };
1924
+ const retainUnverified = (cause) => {
1925
+ let detail = `Coordinator state is unverified; ${cause}. Awaiting compatible supervision.`;
1926
+ try {
1927
+ retainObservation(park.meta, park.record, attempt);
1928
+ }
1929
+ catch (error) {
1930
+ detail = `Degraded supervision: observation could not be retained (${reasonOf(error)}); new parking requires durable storage.`;
1931
+ }
1932
+ updateParkRecord(park.runId, { heldReason: detail });
1933
+ input.notify?.(`Subagent ${park.runId}: ${detail}`, "warning");
1934
+ result = { outcome: "deferred", reason: detail };
1935
+ };
1936
+ // The publication token is what identifies THIS resume of the record.
1937
+ const recordedToken = park.record.resumeLaunchToken;
1938
+ const attemptToken = attempt?.operations?.resumeLaunchToken;
1939
+ if (recordedToken && attemptToken && recordedToken !== attemptToken) {
1940
+ updateParkRecord(park.runId, {
1941
+ phase: park.record.phase === "cancelled" ? "cancelled" : "held",
1942
+ heldReason: `attempt ${input.attemptId} does not match the launch token published for this wait; the wait was left for its owner`,
1943
+ });
1944
+ input.notify?.(`Subagent ${park.runId}: resume attempt ${input.attemptId} does not match the published launch token; the wait is held for inspection.`, "warning");
1945
+ result = { outcome: "foreign" };
1946
+ continue;
1947
+ }
1948
+ if (!input.service) {
1949
+ retainUnverified("the Background operation service is unavailable");
1950
+ continue;
1951
+ }
1952
+ const scope = backgroundScopeForMeta(park.meta, park.record);
1953
+ if (!scope) {
1954
+ holdLocally("the parked attempt records no worker conversation scope");
1955
+ continue;
1956
+ }
1957
+ let wait;
1958
+ try {
1959
+ wait = input.service.listWorkerWaits(scope).find((w) => w.waitId === park.waitId && w.generation === park.generation);
1960
+ interpreted = wait?.phase === "consumed" || interpreted;
1961
+ if (interpreted && !input.reason)
1962
+ reason = exitReason;
1963
+ }
1964
+ catch (error) {
1965
+ retainUnverified(`the coordinator could not verify the wait (${reasonOf(error)})`);
1966
+ continue;
1967
+ }
1968
+ if (typeof input.service.holdFailedResumeForWorker !== "function") {
1969
+ holdLocally("this Background host has no proven-exit hold capability yet");
1970
+ continue;
1971
+ }
1972
+ const claimId = park.record.resumeClaimId;
1973
+ const claimToken = park.record.resumeClaimToken;
1974
+ if (!claimId || !claimToken) {
1975
+ holdLocally("the resume claim identity was not recorded with the attempt, so the durable claim cannot be matched");
1976
+ continue;
1977
+ }
1978
+ if (!attempt) {
1979
+ holdLocally("the published continuation's metadata is missing; its writer identity and exit cannot be proved");
1980
+ continue;
1981
+ }
1982
+ const writer = writerPresence(attempt);
1983
+ const writerPidGone = writer === "absent";
1984
+ if (!writerPidGone) {
1985
+ holdLocally(`writer pid ${attempt?.pid} is still alive, so its exit is unproven`);
1986
+ continue;
1987
+ }
1988
+ if (writer === "unverified" && attempt) {
1989
+ holdLocally(`the recorded writer pid ${attempt.pid} is alive but its process identity cannot be verified`);
1990
+ continue;
1991
+ }
1992
+ const writerLeaseReleased = input.writerLeaseReleased
1993
+ ?? !conversationWriterLeaseLive(attempt?.sessionId ?? park.conversationId);
1994
+ if (!writerLeaseReleased) {
1995
+ holdLocally("a live conversation writer lease still holds the history, so writer exit is unproven");
1996
+ continue;
1997
+ }
1998
+ try {
1999
+ // A held terminal writer needs proof-only reconciliation, not admission.
2000
+ const reconcileOnly = interpreted || park.record.phase === "cancelled" || wait?.phase === "held";
2001
+ if (!reconcileOnly && attempt.assignment && !input.service.repairFailedResumeForWorker) {
2002
+ holdLocally("this Background host does not support bounded autonomous repair");
2003
+ continue;
2004
+ }
2005
+ if (!reconcileOnly && park.meta.operations?.policy?.deadlineAt != null && park.meta.operations.policy.deadlineAt <= at) {
2006
+ holdLocally("the assignment-local deadline expired");
2007
+ continue;
2008
+ }
2009
+ const exitInput = {
2010
+ waitId: park.waitId,
2011
+ generation: park.generation,
2012
+ claimId,
2013
+ claimToken,
2014
+ attemptId: input.attemptId,
2015
+ launchToken: park.record.resumeLaunchToken ?? attemptToken ?? "",
2016
+ proof: { writerPidGone: writerPidGone && writer !== "unverified", writerLeaseReleased },
2017
+ reason,
2018
+ };
2019
+ let held;
2020
+ if (!reconcileOnly && input.service.repairFailedResumeForWorker && attempt.assignment) {
2021
+ if (!park.record.checkpoint)
2022
+ throw new Error("Required saved checkpoint is missing");
2023
+ verifyParkCheckpoint({ ...park.record.checkpoint, version: 1, waitId: park.waitId, generation: park.generation });
2024
+ if (!wait)
2025
+ throw new Error("Required authoritative wait history is missing");
2026
+ held = input.service.repairFailedResumeForWorker(scope, { ...exitInput,
2027
+ checkpointId: `park:${park.record.attemptId}`,
2028
+ expectedCancelEpoch: wait.cancelEpoch });
2029
+ }
2030
+ else {
2031
+ held = input.service.holdFailedResumeForWorker(scope, exitInput);
2032
+ }
2033
+ const phase = phaseOf(held.phase);
2034
+ updateParkRecord(park.runId, {
2035
+ phase: park.record.phase === "cancelled" ? "cancelled" : phase,
2036
+ resumeExitReconciledClaimId: claimId,
2037
+ ...(phase === "consumed" ? { heldReason: undefined } : {}),
2038
+ ...(phase === "held" && park.record.phase !== "cancelled" ? { heldReason: reason } : {}),
2039
+ });
2040
+ if (phase !== "consumed")
2041
+ input.notify?.(`Subagent ${park.runId}: ${reason}. The reconciled wait is ${phase}.`, "warning");
2042
+ result = { outcome: "settled", waitPhase: phase, reason };
2043
+ }
2044
+ catch (error) {
2045
+ // The store refused (stale identity, terminal generation, unproven exit).
2046
+ // Never fall back to cancellation: report the local hold and leave the
2047
+ // durable generation exactly as it is.
2048
+ let durablePhase;
2049
+ try {
2050
+ durablePhase = input.service.listWorkerWaits(scope)
2051
+ .find((entry) => entry.waitId === park.waitId && entry.generation === park.generation)?.phase;
2052
+ }
2053
+ catch { /* durable state unreadable */ }
2054
+ if (!durablePhase) {
2055
+ retainUnverified(`the coordinator could not verify the exit (${reasonOf(error)})`);
2056
+ continue;
2057
+ }
2058
+ if (durablePhase === "consumed" || durablePhase === "cancelled") {
2059
+ updateParkRecord(park.runId, { phase: phaseOf(durablePhase) });
2060
+ result = { outcome: "ignored", waitPhase: durablePhase };
2061
+ continue;
2062
+ }
2063
+ holdLocally(`the durable hold was refused (${reasonOf(error)})`);
2064
+ if (durablePhase)
2065
+ result = { ...result, waitPhase: durablePhase };
2066
+ }
2067
+ }
2068
+ void at;
2069
+ return result;
2070
+ }
2071
+ export async function reconcileParkedWaits(service, outerOptions) {
2072
+ let resumed = 0;
2073
+ let held = 0;
2074
+ let skipped = 0;
2075
+ const options = outerOptions;
2076
+ const scopedOptions = (meta) => ({ ...outerOptions,
2077
+ notify: outerOptions.notifyWhen && !outerOptions.notifyWhen(meta) ? undefined : outerOptions.notify });
2078
+ if (service?.outageReconciliation === 1) {
2079
+ try {
2080
+ for (const report of pendingObservations()) {
2081
+ const options = scopedOptions(report.meta);
2082
+ try {
2083
+ const scope = backgroundScopeForMeta(report.meta, report.record);
2084
+ if (!scope)
2085
+ continue;
2086
+ const current = service.listWorkerWaits(scope).find((wait) => wait.waitId === report.record.waitId && wait.generation === report.observedRevision.generation);
2087
+ if (!current) {
2088
+ // Missing required history is assignment failure, not process-exit proof.
2089
+ if (report.meta.assignment && commitAssignmentTerminal({ ...report.meta, status: "lost",
2090
+ failureReason: "Required authoritative wait history is missing after coordinator recovery; writer termination remains unproven." }, true)) {
2091
+ if (!readMeta(report.meta.id))
2092
+ writeMeta(report.meta, { ifAbsent: true });
2093
+ resolveObservation(report);
2094
+ }
2095
+ continue;
2096
+ }
2097
+ const cached = readParkRecord(report.meta.id);
2098
+ const cancelled = (cached ?? report.record).phase === "cancelled";
2099
+ if ((cancelled || current.phase === "consumed") && report.attempt && current.publishedClaimId === report.record.resumeClaimId) {
2100
+ // Terminal waits still retain independent writer-exit proof.
2101
+ if (!readMeta(report.meta.id))
2102
+ writeMeta(report.meta, { ifAbsent: true });
2103
+ if (!cached)
2104
+ writeParkRecord(report.meta.id, report.record, { ifAbsent: true });
2105
+ if (!readMeta(report.attempt.id))
2106
+ writeMeta(report.attempt, { ifAbsent: true });
2107
+ const replay = await settleResumedAttemptExit({ attemptId: report.attempt.id, service,
2108
+ ...(options.notify ? { notify: options.notify } : {}) });
2109
+ if (replay.outcome !== "deferred")
2110
+ resolveObservation(report);
2111
+ continue;
2112
+ }
2113
+ if ((current.phase === "resuming" && current.publishedClaimId !== report.record.resumeClaimId)
2114
+ || (report.coordinatorEvidence && current.cancelEpoch !== report.coordinatorEvidence.cancelEpoch)) {
2115
+ resolveObservation(report);
2116
+ continue;
2117
+ }
2118
+ if (current.phase === "consumed" || current.phase === "cancelled") {
2119
+ const local = readParkRecord(report.meta.id);
2120
+ if (local?.waitId === current.waitId && local.generation === current.generation) {
2121
+ updateParkRecord(report.meta.id, { phase: local.phase === "cancelled" ? "cancelled" : phaseOf(current.phase), heldReason: undefined });
2122
+ }
2123
+ resolveObservation(report);
2124
+ continue;
2125
+ }
2126
+ // Restore missing conversation evidence, never replace a newer local publication.
2127
+ if (!readMeta(report.meta.id))
2128
+ writeMeta(report.meta, { ifAbsent: true });
2129
+ if (!readParkRecord(report.meta.id))
2130
+ writeParkRecord(report.meta.id, report.record, { ifAbsent: true });
2131
+ if (report.attempt && !readMeta(report.attempt.id))
2132
+ writeMeta(report.attempt, { ifAbsent: true });
2133
+ const local = readParkRecord(report.meta.id);
2134
+ if (local?.resumeClaimId !== report.record.resumeClaimId
2135
+ || local?.resumeLaunchToken !== report.record.resumeLaunchToken) {
2136
+ resolveObservation(report);
2137
+ continue;
2138
+ }
2139
+ if (current.phase === "resuming" && report.attempt) {
2140
+ const replay = await settleResumedAttemptExit({ attemptId: report.attempt.id, service,
2141
+ ...(options.notify ? { notify: options.notify } : {}) });
2142
+ if (replay.outcome === "deferred")
2143
+ continue;
2144
+ }
2145
+ updateParkRecord(report.meta.id, { heldReason: undefined });
2146
+ resolveObservation(report);
2147
+ }
2148
+ catch (error) {
2149
+ options.notify?.(`Subagent ${report.meta.id}: retained outage observation could not be reconciled (${reasonOf(error)}).`, "warning");
2150
+ }
2151
+ }
2152
+ }
2153
+ catch (error) {
2154
+ options.notify?.(`Degraded supervision: outage replay unavailable (${reasonOf(error)}).`, "warning");
2155
+ }
2156
+ }
2157
+ // Consumed waits cannot resume, but a missed exit observer may have left
2158
+ // their published writer claim behind. Reconcile that exact claim once.
2159
+ const candidates = [];
2160
+ for await (const { meta, record } of scanParkRecords()) {
2161
+ if (!isPendingPark(record) && !(record.phase === "consumed" && record.resumedBy
2162
+ && record.resumeClaimId && record.resumeExitReconciledClaimId !== record.resumeClaimId))
2163
+ continue;
2164
+ candidates.push(parkedEntry(meta, record));
2165
+ }
2166
+ // Release earlier writers before admitting later waits in the conversation.
2167
+ candidates.sort((a, b) => a.record.parkedAt - b.record.parkedAt);
2168
+ for (const park of candidates) {
2169
+ const options = scopedOptions(park.meta);
2170
+ try {
2171
+ if (park.record.phase === "resuming" || park.record.phase === "consumed") {
2172
+ const attemptId = park.record.resumedBy ?? "";
2173
+ const attempt = attemptId ? readMeta(attemptId) : undefined;
2174
+ if (!attemptId || !attempt) {
2175
+ if (park.record.phase === "consumed") {
2176
+ skipped += 1;
2177
+ continue;
2178
+ }
2179
+ updateParkRecord(park.runId, {
2180
+ phase: "held",
2181
+ heldReason: `Resume attempt ${attemptId || "(unknown)"} was published but launch and writer identity remain unproven.`,
2182
+ });
2183
+ if (park.meta.assignment)
2184
+ commitAssignmentTerminal({ ...park.meta, status: "lost", failureReason: "Published continuation metadata is missing; launch and writer termination remain unproven." }, true);
2185
+ options.notify?.(`Subagent ${park.runId}: resume attempt ${attemptId || "(unknown)"} has no verifiable launch metadata. The writer fence is retained.`, "warning");
2186
+ held += 1;
2187
+ continue;
2188
+ }
2189
+ // A missed exit needs either unconsumed-wait recovery or proof-only
2190
+ // cleanup of a consumed wait's writer claim.
2191
+ const consumedWriterGone = park.record.phase === "consumed" && attempt.pid > 0 && writerPresence(attempt) === "absent";
2192
+ if (isTerminalAttempt(attempt) || consumedWriterGone) {
2193
+ const settled = await settleResumedAttemptExitForParks({
2194
+ attemptId,
2195
+ service,
2196
+ status: effectiveStatus(attempt),
2197
+ ...(options.notify ? { notify: options.notify } : {}),
2198
+ }, [park]);
2199
+ if (settled.outcome === "settled" && settled.waitPhase !== "consumed")
2200
+ held += 1;
2201
+ else
2202
+ skipped += 1;
2203
+ continue;
2204
+ }
2205
+ if (park.record.phase === "consumed") {
2206
+ skipped += 1;
2207
+ continue;
2208
+ }
2209
+ }
2210
+ if (!service) {
2211
+ let reason = "Coordinator state is unverified; awaiting compatible supervision.";
2212
+ try {
2213
+ retainObservation(park.meta, park.record);
2214
+ }
2215
+ catch (error) {
2216
+ reason = `Degraded supervision: ${reasonOf(error)}. New parking requires durable storage.`;
2217
+ options.notify?.(reason, "warning");
2218
+ }
2219
+ updateParkRecord(park.runId, { heldReason: reason });
2220
+ skipped += 1;
2221
+ continue;
2222
+ }
2223
+ const scope = backgroundScopeForMeta(park.meta, park.record);
2224
+ if (!scope) {
2225
+ skipped += 1;
2226
+ continue;
2227
+ }
2228
+ const wait = service.listWorkerWaits(scope)
2229
+ .find((entry) => entry.waitId === park.waitId && entry.generation === park.generation);
2230
+ if (!wait) {
2231
+ // A missing generation is not an interpretation receipt.
2232
+ retainObservation(park.meta, park.record);
2233
+ updateParkRecord(park.runId, { heldReason: "Coordinator generation is unverified; retained observation awaits reconciliation." });
2234
+ skipped += 1;
2235
+ continue;
2236
+ }
2237
+ if (wait.phase === "consumed" || wait.phase === "cancelled") {
2238
+ updateParkRecord(park.runId, { phase: phaseOf(wait.phase), heldReason: undefined });
2239
+ if (wait.phase === "consumed" && park.record.resumedBy) {
2240
+ await settleResumedAttemptExitForParks({ attemptId: park.record.resumedBy, service,
2241
+ ...(options.notify ? { notify: options.notify } : {}) }, [park]);
2242
+ }
2243
+ skipped += 1;
2244
+ continue;
2245
+ }
2246
+ if (wait.phase === "resuming" || (wait.phase === "held" && park.record.resumedBy)) {
2247
+ // A published attempt owns this generation. If it already ended (or
2248
+ // its record vanished), the unconsumed generation is settled
2249
+ // explicitly; nothing else may resume or mirror it.
2250
+ const attemptId = park.record.resumedBy ?? "";
2251
+ const attempt = attemptId ? readMeta(attemptId) : undefined;
2252
+ if (!attempt || isTerminalAttempt(attempt)) {
2253
+ const settled = await settleResumedAttemptExitForParks({
2254
+ attemptId: attemptId || park.runId,
2255
+ service,
2256
+ status: attempt ? effectiveStatus(attempt) : "missing",
2257
+ ...(options.notify ? { notify: options.notify } : {}),
2258
+ }, [park]);
2259
+ // `deferred` means the local record was held while the durable
2260
+ // generation could not be proven (ambiguous identity/capability);
2261
+ // it is never a silent success.
2262
+ if (settled.outcome === "settled" || settled.outcome === "deferred")
2263
+ held += 1;
2264
+ else
2265
+ skipped += 1;
2266
+ continue;
2267
+ }
2268
+ // The attempt is still live; it will acknowledge or exit.
2269
+ skipped += 1;
2270
+ continue;
2271
+ }
2272
+ if (wait.phase === "ready") {
2273
+ const outcome = await options.resume(park);
2274
+ if (outcome === "resumed")
2275
+ resumed += 1;
2276
+ else if (outcome === "held")
2277
+ held += 1;
2278
+ else
2279
+ skipped += 1;
2280
+ continue;
2281
+ }
2282
+ if (wait.phase === "parking") {
2283
+ // The exit proof is normally sent by the run's exit handler. After a
2284
+ // restart that handler is gone, so the staged checkpoint is retried
2285
+ // here against real writer and lease evidence. Anything ambiguous is
2286
+ // held explicitly instead of parking forever.
2287
+ const recovered = await recoverStagedPark(park, service);
2288
+ if (recovered === "parked" || recovered === "ready")
2289
+ resumed += 1;
2290
+ else if (recovered === "held")
2291
+ held += 1;
2292
+ else
2293
+ skipped += 1;
2294
+ continue;
2295
+ }
2296
+ if (phaseOf(wait.phase) !== park.phase)
2297
+ updateParkRecord(park.runId, { phase: phaseOf(wait.phase) });
2298
+ skipped += 1;
2299
+ }
2300
+ catch (error) {
2301
+ try {
2302
+ retainObservation(park.meta, park.record, park.record.resumedBy ? readMeta(park.record.resumedBy) : undefined);
2303
+ }
2304
+ catch (storageError) {
2305
+ options.notify?.(`Degraded supervision: observation not retained (${reasonOf(storageError)}).`, "warning");
2306
+ }
2307
+ updateParkRecord(park.runId, { heldReason: `Coordinator state is unverified (${reasonOf(error)}).` });
2308
+ options.notify?.(`Subagent ${park.runId}: wait reconciliation failed (${reasonOf(error)}).`, "warning");
2309
+ held += 1;
2310
+ }
2311
+ }
2312
+ return { resumed, held, skipped };
2313
+ }
2314
+ /**
2315
+ * Prompt for the continuation attempt. It restates the durable wait identity and
2316
+ * the next reasoning step only: it changes no tool, model, role, permission,
2317
+ * workspace or authorization, and it does not tell the worker the outcome.
2318
+ */
2319
+ export function resumePrompt(park) {
2320
+ const note = park.record.continuationNote ?? "Continue the assignment you were working on.";
2321
+ return [
2322
+ "Your previous execution attempt parked while it waited on background operations, and they have now all reached a terminal outcome.",
2323
+ `Durable wait: ${park.waitId} generation ${park.generation}.`,
2324
+ "Read the terminal evidence for every task listed in that wait (bg_task_status / bg_task_log), interpret it yourself, and then acknowledge the result with acknowledge_operation_result naming the exact terminal revisions you read.",
2325
+ "Then continue the original assignment. The evidence decides what to do; it does not by itself mean the assignment succeeded.",
2326
+ `Next reasoning step recorded when you parked: ${note}`,
2327
+ ].join("\n");
2328
+ }
2329
+ /** Child bridge extension path inside this package. */
2330
+ export function childBridgeExtensionPath(packageDir) {
2331
+ return join(packageDir, "child-operations.ts");
2332
+ }
2333
+ /** True when `taskId` appeared in a launch result (used by the host's ownership seam). */
2334
+ export function launchedTaskIds(result) {
2335
+ return extractResultTaskIds(result);
2336
+ }