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,4731 @@
1
+ // Generated fixed launch domain from packages/pi-better-subagents/index.ts. Do not edit directly.
2
+ import { shouldRestoreWorkObservation } from "./shared-work-client.mjs";
3
+ import { appendTimingWake, removeTimingReceipt, receiptTimingWake, timingWakeReceipt } from "./timing-notifications.domain.mjs";
4
+ import { captureLaunchContext } from "./launch-context.domain.mjs";
5
+ /**
6
+ * pi-better-subagents — Claude Code-style async subagents for pi.
7
+ *
8
+ * Core semantic: launching a subagent IS the deliverable. `subagent_spawn`
9
+ * starts a detached `pi -p` child and returns immediately with a run id; the
10
+ * foreground session stays free for the human while it runs. When the child
11
+ * finishes, its RESULT is posted back into the session (delivered as a followUp
12
+ * so it never cuts into work in progress). The foreground is never BLOCKED on a
13
+ * wait/poll loop — it's only nudged once, at completion, with the answer.
14
+ *
15
+ * launch is the result · completion posts back · the foreground never blocks
16
+ */
17
+ import { createAssignmentProjector } from "./assignment-projection.mjs";
18
+ import { historicalWaits, attentionRevision, attentionDismissed, dismissAttention } from "./historical-attention.domain.mjs";
19
+ import { registerAssignmentAttempt, commitAssignmentTerminal, readOutcome, receiptOutcome, outcomeTranscriptReceipt, inspectOutcome, createOutcomeHost, closeOutcomeHost, claimOutcome } from "./assignment-outcomes.domain.mjs";
20
+ import { currentSandboxPermissions } from "./permission-policy.domain.mjs";
21
+ import { assertWaitToolDependencies, createToolDescriptor } from "./operation-bridge-types.domain.mjs";
22
+ import { requestResumeAdmission } from "./worker-waits.domain.mjs";
23
+ import { execSync } from "node:child_process";
24
+ import { writeFileSync, mkdirSync, renameSync, statSync } from "node:fs";
25
+ import * as PiCodingAgent from "@earendil-works/pi-coding-agent";
26
+ import * as PiTui from "@earendil-works/pi-tui";
27
+ import { CustomEditor } from "@earendil-works/pi-coding-agent";
28
+ import { initializeNavigatorPanels } from "./shared-navigator-panels.domain.mjs";
29
+ import { workObservation, workObservationStarted, workObservationFailure, configureWorkObservation, activateWorkObservation, stopWorkObservation, observedAssignment, observedList, requestWorkDetail, TERMINAL_NAVIGATOR_RETENTION_MS } from "./work-observation.domain.mjs";
30
+ import { withAssignmentObservations } from "./assignment-projection.mjs";
31
+ import { formatNavigatorHealthFacts } from "./health-surface.mjs";
32
+ import { matchesKey, Key, truncateToWidth } from "@earendil-works/pi-tui";
33
+ import { Type } from "typebox";
34
+ import { disposeBackgroundWorkNavigator, ensureBackgroundWorkNavigator, isNavigatorUiAvailable, refreshBackgroundWorkNavigator, registerBackgroundWorkProvider, observeNavigatorLaunch, renderRegisteredWorkDetail, } from "./shared-navigator.domain.mjs";
35
+ import { spawnDetached } from "./spawn.domain.mjs";
36
+ import { parseRun, parseRunForLifecycle, resetParseRunCursor } from "./parse.domain.mjs";
37
+ import { finalizeRun as finalizeRunCore, reconcileInterruptedRun } from "./finalization.domain.mjs";
38
+ import { completeOwnedExit } from "./owned-exit.domain.mjs";
39
+ import { selectSessionByName } from "./session-selection.domain.mjs";
40
+ import { isWithinWorkspace } from "./workspace-scope.domain.mjs";
41
+ import { BUILTIN_TOOLS } from "./extensions.domain.mjs";
42
+ import { ORDINARY_TOOL_PROVIDERS, activeChildProviders, ordinaryChildConfig, addEditablePatch, loadConfig, writeDelegationMode, writeSubagentSettings, isConcurrencyCap, normalizeConcurrencyCap, normalizeTools, resolveExtensionPath, configPath, selfDir, SAFE_DEFAULT_TOOLS, SAFE_CLEAN_TOOLS } from "./config.domain.mjs";
43
+ import { createSubagentSettingsPage } from "./settings-page.domain.mjs";
44
+ import { deliverSubagentPrompt, effectiveSubagentSettings, subagentSettingsTool } from "./effective-settings.domain.mjs";
45
+ import { STEER_FILE_ENV, readSteerReceipt } from "./child-steer.domain.mjs";
46
+ import { continuationTimingParams, decideTiming, describeTiming, DEFAULT_TIMING_MINUTES, emptyProgress, foldProgress, formatTimingLimits, isTimingMinutes, isProgressRelevantLine, resolveRunTiming, steerText, stuckAlertText, TIMING_ENV, timingParameterSchemas, toolWaitAlertText, validatedTimingMinutes, } from "./timing.domain.mjs";
47
+ import { readAppendedLines } from "./log-cursor.domain.mjs";
48
+ import { DELEGATION_MODES, DELEGATION_MODE_REQUEST, isDelegationMode, normalizeDelegationMode } from "./delegation.domain.mjs";
49
+ import { resolveExtensions, extensionArgs } from "./extensions.domain.mjs";
50
+ import { prepareTaskRuntime, applyDirectApplicationLoadout, DEFAULT_TASK_PERMISSIONS, RUN_APPLICATION, SDK_BUILTIN_TOOLS } from "./task-policy.domain.mjs";
51
+ import { canonicalizePath, takeRecoverySnapshot } from "./shared-sandbox-core.domain.mjs";
52
+ import { TASK_BUILTINS } from "./shared-task-sandbox.domain.mjs";
53
+ import { describeTaskTools, planTaskTools, selectEffectiveTaskTools } from "./subagent-tools.domain.mjs";
54
+ import { announceExecutionAdapter, describeSubagentProcessPolicy, effectiveWorkerProcessAccess, observeSandboxPermissions, resolveCommandSettings, resolveSubagentPermissions, } from "./permission-policy.domain.mjs";
55
+ import { dirname, isAbsolute, join } from "node:path";
56
+ import { baseDir, taskWorkspaceDir, sessionsDir, runDir, recordTaskRuntimeProvenance, recordLaunchAttempt, clearLaunchAttempt, logPathFor, promptPathFor, nextRunId, writeMeta, readMeta, listMetas, listActiveMetasForParent, listMetasForOrigin, listMetasForParent, onMetaChanged, effectiveStatus, ownedByThisParent as ownedByFrontend, navigatorVisibleRuns, dismissRun, } from "./registry.domain.mjs";
57
+ import { captureProcessIdentity, extractChildEventFactsFromLog, loadHealthThresholdsFromConfig, isAbandonedByParent, needsMonitoring, observeRunHealth, realProcessProbe, reconcileRun, resetChildEventLogCursor, } from "./health.domain.mjs";
58
+ import { assignBatchJobNames, batchLaunchOutputSchema, batchLaunchResult, mergeJobOptions, nextBatchId, planBatchLaunches, validateBatchPlan, } from "./batch.mjs";
59
+ import { formatCapacityRejectMessage, getSharedCapacityGate, } from "./capacity.mjs";
60
+ import { buildHealthCallbackDelivery } from "./completion.domain.mjs";
61
+ import { cancelCallbackBatch, getCallbackBatcher, packCallbackBatch, setCallbackBatchContext } from "./shared-callback-batcher.domain.mjs";
62
+ let managementPort;
63
+ const ownedByThisParent = (meta) => managementPort ? managementPort.owns(meta) : ownedByFrontend(meta);
64
+ const supervisedMetas = () => managementPort ? managementPort.supervised() : listMetasForParent(process.pid);
65
+ import { completionCallbackFields, failureAttentionFields, healthCallbackFields } from "./callback-fields.domain.mjs";
66
+ import { collectRunFailures, failurePath, markFailureAttentionDelivered, pendingFailureAttention } from "./failures.domain.mjs";
67
+ import { failureAttentionHandled, observeFailures } from "./shared-failure-observations.domain.mjs";
68
+ import { subagentListTool, subagentOutputTool, subagentResultTool, subagentStopTool, } from "./tools.domain.mjs";
69
+ import { stopRun } from "./stop.domain.mjs";
70
+ import { WIDGET_CLEAR, fmtElapsed, fmtSpend, fmtTokens, shortModel, isSpendCacheFresh, resolveHealthLogExtraction, withinRefreshFloor, } from "./widget.domain.mjs";
71
+ import { executeNavigatorClose, pendingNavigatorPark, buildNavigatorDetail, } from "./navigator.domain.mjs";
72
+ import { enforceRegistrySizeCapOnce, runDailyCleanupOnce } from "./cleanup.domain.mjs";
73
+ import { managedRuntimeRoot, selectContinuationRuntime } from "./continuation-runtime.domain.mjs";
74
+ import { ContinuationError, acquireConversationLease, assertContinuationExtensions, buildLaunchRecipe, planContinuation, } from "./continuation.domain.mjs";
75
+ import { createHash } from "node:crypto";
76
+ import { assertThinkingLevel, parseModelThinking } from "./thinking.domain.mjs";
77
+ import { absolutizeSkillPaths, configuredSkillExposure, describeSkillExposure, normalizeSkillExposure, resolveSkillExposure, skillLaunchArgs, } from "./skills.domain.mjs";
78
+ import { createAgentOperations } from "./agent-operations.domain.mjs";
79
+ import { createAgentSessionSettings } from "./agent-session-settings.domain.mjs";
80
+ import { clarifyCatalogRequest, createLaunchEnricher, blankCatalogSelector, hasCatalogSelector, loadSharedLaunchSnapshot, noteCatalogHost, prepareCatalogJob, catalogDefaultNote, tiersForLaunch, } from "./catalog-runtime.domain.mjs";
81
+ import { registerSubagentsGoalProvider } from "./goal-provider.domain.mjs";
82
+ import { DEFAULT_WORKER_BRIDGE_TOOLS, PreSpawnResumeError, assertAssignmentPermissionScope, assertFinalResumeDispatch, releaseChild, cancelParkedWait, branchContains, captureWorkerPolicy, createOwnedAttemptStopper, childBridgeExtensionPath, childWriterLeaseEnv, createResumeOrchestration, createWorkerOperationsHost, finalizeWorkerParkAfterExit, manualResumeRefusal, ownerBindingFromContext, parkedWaitForRun, planWorkerBridgeTools, reconcileParkedWaits, resolveProductionSchemas, resumePrompt, settleResumedAttemptExit, } from "./worker-waits.domain.mjs";
83
+ import { defaultUserRoot } from "./catalog-store.domain.mjs";
84
+ import { restrictContextFilesToWorktree } from "./shared-worktree-context.domain.mjs";
85
+ import { noteCatalogHostContext, closeCatalogHost } from "./catalog-host-admission.domain.mjs";
86
+ const SUBAGENT_MODE_ACTIONS = [
87
+ { value: "history", label: "history", description: "Inspect or cancel waits from other sessions" },
88
+ { value: "history dismiss", label: "history dismiss", description: "Dismiss unchanged historical attention notices" },
89
+ { value: "settings", label: "settings", description: "Open delegation, concurrency, and timing settings" },
90
+ { value: "cap", label: "cap <number>", description: "Set a positive concurrent subagent limit for this session" },
91
+ { value: "tool-wait", label: "tool-wait <minutes>", description: "Set the session tool-wait alert time; 0 turns it off" },
92
+ { value: "stuck", label: "stuck <minutes>", description: "Set the session no-progress alert time; 0 turns it off" },
93
+ { value: "reset", label: "reset", description: "Reset session mode, cap, and timing alerts to saved defaults" },
94
+ { value: "mode manual", label: "mode manual", description: "Delegate only when explicitly requested" },
95
+ { value: "mode adaptive", label: "mode adaptive", description: "Delegate substantial independent work" },
96
+ { value: "mode coordinator", label: "mode coordinator", description: "Delegate role-owned work by default" },
97
+ { value: "save", label: "save", description: "Save the current mode, cap, and timing alerts as defaults" },
98
+ ];
99
+ export function subagentsArgumentCompletions(argumentPrefix) {
100
+ const prefix = argumentPrefix.trimStart().toLowerCase();
101
+ const matches = SUBAGENT_MODE_ACTIONS.filter((action) => action.value.startsWith(prefix));
102
+ return matches.length > 0 ? [...matches] : null;
103
+ }
104
+ /** The tools this extension registers — excluded from children by default so a
105
+ * subagent cannot recursively spawn more subagents unless explicitly allowed. */
106
+ const SUBAGENT_TOOLS = [
107
+ "subagent_spawn",
108
+ "subagent_spawn_batch",
109
+ "subagent_list",
110
+ "subagent_settings",
111
+ "subagent_output",
112
+ "subagent_stop",
113
+ "subagent_result",
114
+ "agents_catalog",
115
+ ];
116
+ const projectConfigDirName = typeof PiCodingAgent.CONFIG_DIR_NAME === "string"
117
+ ? PiCodingAgent.CONFIG_DIR_NAME
118
+ : ".pi";
119
+ const CATALOG_GUIDELINES = [
120
+ "With an agent or role, omit model and thinking to launch on its default model and effort, which agents_catalog shows. Name a model or effort only for a stated reason, such as a task or workflow instruction, and never copy one from another role's runs.",
121
+ "When a task, workflow, or skill instruction names a model or effort, translate that authoritative choice into the structured model and thinking arguments before spawning. The runtime does not parse prose, quoted model names, or comparisons, and copying a model into the child prompt does not change the launch.",
122
+ "Optional agent, role, and alias select a catalog definition. Pass one named agent id (agent: \"agent.payments\") or one role by its short name (role: \"developer\"); the role.developer form also works. Pass an array of role names when one run was given more than one role: that call asks to choose one or split, and without a UI choice it returns clarification-needed and starts no child. Naming both an agent and a role does the same. One job's choice does not change another job. A named agent displays its defined name. A direct role displays the label allocated from the local run registry. Calls without agent or role keep the existing name and model chain.",
123
+ "Catalog model and effort are resolved before the child starts. An unavailable explicit model or unsupported explicit effort does not launch and does not fall back. The catalog grants no tools, sandbox modes, extensions, or permissions.",
124
+ ];
125
+ const SUBAGENT_ORCHESTRATION_GUIDELINES = [
126
+ "Follow the Harness execution policy for concurrency; the active delegation mode determines whether to use subagents, not whether independent background commands can overlap.",
127
+ "When a structured plan is active, follow the current delegation mode. Track delegated and foreground deliverables only when delegation is permitted and actually underway; continue unblocked foreground work and integrate results before marking work complete.",
128
+ "Do not treat launching a subagent as completion of the parent milestone; relevant terminal results must be inspected and integrated before verification or completion.",
129
+ ];
130
+ // ---- retired live status widget ------------------------------------------
131
+ //
132
+ // The shared background-work navigator owns the active subagent list. This
133
+ // legacy `subagents` widget key is now clear-only so users do not see the same
134
+ // run twice (`background work · N` plus `Subagents · N running`). Pure widget
135
+ // helpers remain for compatibility tests and older render contracts.
136
+ /** Freshest UI-bearing context, captured from session_start / tool calls. */
137
+ let uiCtx;
138
+ let activeCallbackOrigin;
139
+ let ticker;
140
+ let widgetNavActive = false;
141
+ let widgetNavSelectedId;
142
+ /** Per-run spend/tool cache for the UI hot path. */
143
+ const spendCache = new Map();
144
+ /**
145
+ * Per-run health-log parse cache — size/mtime gated and floored by
146
+ * HOT_PATH_REFRESH_FLOOR_MS, so a child writing continuously cannot make every
147
+ * frame re-read its log.
148
+ */
149
+ const healthLogCache = new Map();
150
+ function logStatOf(id) {
151
+ try {
152
+ const st = statSync(logPathFor(id));
153
+ return { size: st.size, mtimeMs: Math.trunc(st.mtimeMs) };
154
+ }
155
+ catch {
156
+ return { size: 0 };
157
+ }
158
+ }
159
+ function logSizeOf(id) {
160
+ return logStatOf(id).size;
161
+ }
162
+ function callbackOriginFromContext(ctx) {
163
+ let sessionId;
164
+ try {
165
+ sessionId = ctx.sessionManager?.getSessionId();
166
+ }
167
+ catch {
168
+ sessionId = undefined;
169
+ }
170
+ return { cwd: ctx.cwd, sessionId, branchId: ctx.sessionManager?.getLeafId?.() ?? null };
171
+ }
172
+ /** Origin with a readable session id, or undefined when identity is unavailable. */
173
+ function verifiedOriginFromContext(ctx) {
174
+ if (!ctx?.sessionManager || typeof ctx.cwd !== "string")
175
+ return undefined;
176
+ try {
177
+ const sessionId = ctx.sessionManager.getSessionId();
178
+ return sessionId ? { cwd: ctx.cwd, sessionId } : undefined;
179
+ }
180
+ catch {
181
+ return undefined;
182
+ }
183
+ }
184
+ /**
185
+ * Instance-local suppression: this module has no active session, not the run.
186
+ * A finalizer that runs after `/reload` (the process and its exit observer
187
+ * survive the session) can report this even though the replacing session owns
188
+ * the run, so it must never be written as a durable suppression (#625).
189
+ */
190
+ const NO_ACTIVE_SESSION_REASON = "active session identity is unavailable";
191
+ function callbackSuppressionReason(meta, active = activeCallbackOrigin) {
192
+ const origin = meta.callbackOrigin;
193
+ if (origin) {
194
+ if (!active)
195
+ return NO_ACTIVE_SESSION_REASON;
196
+ if (origin.cwd !== active.cwd)
197
+ return `origin cwd ${origin.cwd} does not match active cwd ${active.cwd}`;
198
+ if (origin.sessionId && origin.sessionId !== active.sessionId) {
199
+ return `origin session ${origin.sessionId} does not match active session ${active.sessionId ?? "unknown"}`;
200
+ }
201
+ const recipient = meta.assignment?.recipient;
202
+ if (recipient && (recipient.sessionId !== active.sessionId || recipient.workspace !== active.cwd)) {
203
+ return `origin session ${recipient.sessionId} does not match the active recipient scope`;
204
+ }
205
+ if (recipient?.branchId && (!uiCtx || !branchContains(uiCtx, recipient.branchId))) {
206
+ return `origin branch ${recipient.branchId} is not active`;
207
+ }
208
+ if (meta.operations?.resumeLaunchToken && meta.operations.branchId
209
+ && (!uiCtx || !branchContains(uiCtx, meta.operations.branchId))) {
210
+ return `origin branch ${meta.operations.branchId} is not active`;
211
+ }
212
+ return undefined;
213
+ }
214
+ if (active && meta.cwd !== active.cwd) {
215
+ return `legacy run cwd ${meta.cwd} does not match active cwd ${active.cwd}`;
216
+ }
217
+ return undefined;
218
+ }
219
+ function belongsToActiveNavigatorSession(meta) {
220
+ const active = activeCallbackOrigin;
221
+ if (!active)
222
+ return false;
223
+ return belongsToOrigin(meta, active);
224
+ }
225
+ function belongsToOrigin(meta, active) {
226
+ const origin = meta.callbackOrigin;
227
+ if (origin) {
228
+ if (origin.cwd !== active.cwd)
229
+ return false;
230
+ if (origin.sessionId || active.sessionId)
231
+ return origin.sessionId === active.sessionId;
232
+ return true;
233
+ }
234
+ if (active.sessionId)
235
+ return false;
236
+ return meta.cwd === active.cwd;
237
+ }
238
+ function hasSelfProcessIdentity(meta) {
239
+ return meta.pid === process.pid || meta.pgid === process.pid;
240
+ }
241
+ /**
242
+ * Runs this extension instance launched, so its in-memory exit observer is the
243
+ * authority that finalizes them. A run adopted after `/reload` is absent here:
244
+ * the instance that held the observer is gone, so supervision falls back to the
245
+ * child's own log (see `finalizeInterruptedRunFromLog`).
246
+ */
247
+ const directlySupervisedRunIds = new Set();
248
+ /**
249
+ * Detach current-session live work instead of killing it (#625).
250
+ *
251
+ * Subagent children are detached process groups: they survive the foreground
252
+ * process dying. The previous shutdown loop therefore made every controlled
253
+ * `/reload` (and every clean quit) a silent, destructive end to in-flight work —
254
+ * no drain, no warning, and the run recorded `killed`. Shutdown now only records
255
+ * that this session's direct supervision ended; the child and all of its saved
256
+ * state stay untouched, and the next session of the same pi process resumes
257
+ * supervision and finalizes it from the child's own log.
258
+ *
259
+ * Returns the interrupted runs so the caller can warn the human.
260
+ */
261
+ function interruptCurrentSessionSubagents(reason, ctx) {
262
+ const origin = callbackOriginFromContext(ctx);
263
+ const now = Date.now();
264
+ const interrupted = [];
265
+ for (const summary of listMetasForParent(process.pid)) {
266
+ if (summary.management)
267
+ continue;
268
+ if (!ownedByThisParent(summary))
269
+ continue;
270
+ if (summary.status !== "running" && summary.status !== "orphaned")
271
+ continue;
272
+ if (!belongsToOrigin(summary, origin))
273
+ continue;
274
+ // Corrupt or synthetic metadata must never point the interruption record
275
+ // (or any later signal) at the foreground Pi process itself.
276
+ if (hasSelfProcessIdentity(summary))
277
+ continue;
278
+ try {
279
+ // Re-read under the id: a run may have finished while shutdown ran.
280
+ const meta = readMeta(summary.id);
281
+ if (!meta || (meta.status !== "running" && meta.status !== "orphaned"))
282
+ continue;
283
+ meta.supervisionInterruptedAt = now;
284
+ meta.supervisionInterruptedReason = reason;
285
+ writeMeta(meta);
286
+ interrupted.push(meta);
287
+ }
288
+ catch { /* a failed marker must never kill or block the child */ }
289
+ spendCache.delete(summary.id);
290
+ healthLogCache.delete(summary.id);
291
+ resetChildEventLogCursor(summary.id);
292
+ }
293
+ return interrupted;
294
+ }
295
+ /** Warn the human that a shutdown/reload left delegated work running (#625). */
296
+ function warnInterruptedSubagents(ctx, interrupted, reason) {
297
+ if (interrupted.length === 0)
298
+ return;
299
+ const count = interrupted.length;
300
+ const label = count === 1 ? "1 subagent run is" : `${count} subagent runs are`;
301
+ const ids = interrupted.slice(0, 3).map((meta) => meta.id).join(", ") + (count > 3 ? ", …" : "");
302
+ const verb = reason === "reload" ? "reload" : "session shutdown";
303
+ const guidance = reason === "reload"
304
+ ? "The reloaded session resumes supervision and reports the result; use subagent_stop to end it instead."
305
+ : "They keep running detached and stay readable with subagent_result/subagent_output; use subagent_stop to end one.";
306
+ try {
307
+ ctx.ui.notify(`Subagent ${label} still running (${ids}) — ${verb} no longer kills delegated work. ${guidance}`, "warning");
308
+ }
309
+ catch { /* no UI available (print/RPC/quit) */ }
310
+ }
311
+ /**
312
+ * True once this extension instance's `session_shutdown` has run. A late child
313
+ * finalizer can still execute after `/reload` (the process and its exit
314
+ * observer survive the session), and such a finalizer must not restart
315
+ * supervision loops or durably suppress a callback just because THIS instance
316
+ * no longer has a session.
317
+ */
318
+ let sessionTornDown = false;
319
+ let outcomeHost = createOutcomeHost();
320
+ const outcomeAdmission = new Map();
321
+ const outcomeEnqueuing = new Set();
322
+ let outcomeTicker;
323
+ const pendingRecipientRecovery = new Map();
324
+ const observedRecipientRows = new Map();
325
+ function trackRecipientRecovery(id, kind) {
326
+ let pending = pendingRecipientRecovery.get(id);
327
+ if (!pending)
328
+ pendingRecipientRecovery.set(id, pending = new Set());
329
+ pending.add(kind);
330
+ }
331
+ function finishRecipientRecovery(id, kind) {
332
+ const pending = pendingRecipientRecovery.get(id);
333
+ pending?.delete(kind);
334
+ if (!pending?.size)
335
+ pendingRecipientRecovery.delete(id);
336
+ }
337
+ /**
338
+ * "The rightful conversation is not the active one", not "this notification is
339
+ * dead" (#625). These reasons only defer delivery to whoever owns the run, so
340
+ * they must never consume an interrupted run's owed completion.
341
+ */
342
+ function isConversationIdentityReason(reason) {
343
+ return reason === NO_ACTIVE_SESSION_REASON
344
+ || reason.startsWith("origin session ")
345
+ || reason.startsWith("origin branch ")
346
+ || reason.startsWith("origin cwd ")
347
+ || reason.startsWith("legacy run cwd ");
348
+ }
349
+ function markCompletionCallbackSuppressed(id, reason, now = Date.now()) {
350
+ // A finalizer that runs after this instance was torn down cannot name the
351
+ // session that owns the run now. Suppressing durably would erase the
352
+ // pending marker the replacing session recovers (#625), so leave it.
353
+ if (sessionTornDown && reason === NO_ACTIVE_SESSION_REASON)
354
+ return;
355
+ const meta = readMeta(id);
356
+ if (!meta || meta.completionCallbackSentAt !== undefined || meta.completionCallbackSuppressedAt !== undefined)
357
+ return;
358
+ // An explicitly interrupted run owes its completion to the conversation that
359
+ // launched it (#625, DEV-226 criterion 5). An unrelated session merely being
360
+ // active — B opening before the original A returns — drops this delivery
361
+ // attempt but must keep the obligation: the pending marker stays, and A
362
+ // recovers it when it comes back. Records that never lost supervision keep
363
+ // today's durable suppression, so legacy/foreign notifications stay dead.
364
+ if ((meta.supervisionInterruptedAt !== undefined || meta.operations?.resumeLaunchToken)
365
+ && isConversationIdentityReason(reason))
366
+ return;
367
+ meta.completionCallbackSuppressedAt = now;
368
+ meta.completionCallbackSuppressedReason = reason;
369
+ writeMeta(meta);
370
+ }
371
+ function markCompletionCallbackSent(id, now) {
372
+ const meta = readMeta(id);
373
+ if (!meta || meta.completionCallbackSentAt !== undefined || meta.completionCallbackSuppressedAt !== undefined)
374
+ return;
375
+ meta.completionCallbackSentAt = now;
376
+ writeMeta(meta);
377
+ }
378
+ /** Queue one durable ordinary terminal event on the host-shared batch. */
379
+ function enqueueCompletionCallback(pi, id) {
380
+ const meta = readMeta(id);
381
+ if (meta?.assignment) {
382
+ try {
383
+ const outcome = commitAssignmentTerminal(meta);
384
+ // Persist mechanically even when the recipient is absent. Only its
385
+ // attached foreground may write or activate the parent transcript.
386
+ if (managementPort)
387
+ return;
388
+ if (outcome) {
389
+ void enqueueAssignmentOutcome(pi, meta);
390
+ return;
391
+ }
392
+ // An unresolved assignment exit belongs to repair, not legacy delivery.
393
+ return;
394
+ }
395
+ catch (error) {
396
+ try {
397
+ uiCtx?.ui?.notify(`Assignment outcome could not commit: ${String(error)}`, "warning");
398
+ }
399
+ catch { /* no UI */ }
400
+ return;
401
+ }
402
+ }
403
+ if (managementPort)
404
+ return;
405
+ if (!meta
406
+ || meta.callback === false
407
+ || meta.completionCallbackPendingAt === undefined
408
+ || meta.completionCallbackSentAt !== undefined
409
+ || meta.completionCallbackSuppressedAt !== undefined)
410
+ return;
411
+ const state = collectRunFailures(id, meta.cwd, true);
412
+ // Lifecycle, current actionability, and retained history are separate facts (#315).
413
+ const due = pendingFailureAttention(state, Date.now(), { terminal: true });
414
+ getCallbackBatcher(pi).enqueue({
415
+ ...completionCallbackFields(meta, state, due?.incidents ?? []),
416
+ callback: true,
417
+ isDelivered: () => {
418
+ const current = readMeta(id);
419
+ return current?.completionCallbackSentAt !== undefined
420
+ || current?.completionCallbackSuppressedAt !== undefined;
421
+ },
422
+ getSuppressionReason: () => {
423
+ const current = readMeta(id);
424
+ if (!current)
425
+ throw new Error("Subagent metadata is unavailable; defer completion");
426
+ return callbackSuppressionReason(current);
427
+ },
428
+ onDelivered: (at) => {
429
+ const state = collectRunFailures(id, meta.cwd, true);
430
+ const due = pendingFailureAttention(state, at, { terminal: true });
431
+ if (due) {
432
+ markFailureAttentionDelivered(failurePath(id), due, at);
433
+ if (due.incidents.some((incident) => pendingFailureAttention(collectRunFailures(id, meta.cwd, true), at, { terminal: true })?.incidents.includes(incident)))
434
+ return;
435
+ }
436
+ markCompletionCallbackSent(id, at);
437
+ },
438
+ onSuppressed: (reason, at) => markCompletionCallbackSuppressed(id, reason, at),
439
+ });
440
+ }
441
+ async function enqueueAssignmentOutcome(pi, meta) {
442
+ if (outcomeEnqueuing.has(meta.id))
443
+ return;
444
+ outcomeEnqueuing.add(meta.id);
445
+ try {
446
+ await tryEnqueueAssignmentOutcome(pi, meta);
447
+ }
448
+ catch (error) {
449
+ try {
450
+ deferOutcome(meta, `Outcome reconciliation failed: ${String(error)}`);
451
+ }
452
+ catch { /* storage remains unavailable; next reconciliation retries */ }
453
+ }
454
+ finally {
455
+ outcomeEnqueuing.delete(meta.id);
456
+ }
457
+ }
458
+ function deferOutcome(meta, reason) {
459
+ const current = readMeta(meta.id);
460
+ if (!current || current.outcomeDeliveryDeferredReason === reason)
461
+ return;
462
+ current.outcomeDeliveryDeferredReason = reason;
463
+ writeMeta(current);
464
+ }
465
+ async function tryEnqueueAssignmentOutcome(pi, meta) {
466
+ const outcome = readOutcome(meta);
467
+ const ctx = uiCtx;
468
+ if (!outcome || outcome.deliveryReceipt || outcome.disposition)
469
+ return;
470
+ if (!ctx || meta.callback === false || typeof ctx.sessionManager?.getBranch !== "function") {
471
+ deferOutcome(meta, meta.callback === false ? "Assignment callbacks are disabled."
472
+ : "Recorded parent transcript is unavailable; automatic reconciliation will retry.");
473
+ return;
474
+ }
475
+ const active = ownerBindingFromContext(ctx);
476
+ if (active.sessionId !== outcome.recipient.sessionId || active.workspace !== outcome.recipient.workspace
477
+ || (outcome.recipient.branchId && !ctx.sessionManager.getBranch().some((entry) => entry.id === outcome.recipient.branchId))) {
478
+ deferOutcome(meta, "Recorded parent session, workspace or branch is inactive; automatic reconciliation will retry.");
479
+ return;
480
+ }
481
+ const prior = outcomeTranscriptReceipt(ctx.sessionManager.getBranch(), outcome.eventId);
482
+ if (prior) {
483
+ receiptOutcome(meta, prior);
484
+ return;
485
+ }
486
+ const deliveryHost = outcomeHost;
487
+ // The Goal scheduler can take up to 20 seconds. Keep the short probe only
488
+ // for a standalone parent, with no bound Goal or acknowledged check.
489
+ const workflowBudgetMs = 25_000;
490
+ const gate = await requestResumeAdmission(pi, active, {
491
+ timeoutMs: active.goalId || outcome.recipient.goalId ? workflowBudgetMs : 50,
492
+ pendingTimeoutMs: workflowBudgetMs,
493
+ });
494
+ outcomeAdmission.set(outcome.eventId, () => gate.allowed ? gate.isCurrent?.() !== false : !active.goalId && !outcome.recipient.goalId && gate.revision === -1);
495
+ if (!gate.allowed && (active.goalId || outcome.recipient.goalId || gate.revision !== -1)) {
496
+ // Admission controls model execution, not delivery of an already
497
+ // committed result. Paused Goals still owe their human a notification.
498
+ if (sessionTornDown || outcomeHost !== deliveryHost || uiCtx !== ctx || callbackSuppressionReason(meta)
499
+ || (outcome.recipient.branchId && !ctx.sessionManager.getBranch().some(entry => entry.id === outcome.recipient.branchId))) {
500
+ deferOutcome(meta, "Recorded parent delivery scope changed; automatic reconciliation will retry.");
501
+ return;
502
+ }
503
+ // Native Pi queues messages during a turn even with triggerTurn:false.
504
+ // Wait for idle so replay cannot enqueue the same unreceipted message.
505
+ if (!ctx.isIdle()) {
506
+ deferOutcome(meta, "Waiting for an idle parent to append the outcome without starting a turn.");
507
+ return;
508
+ }
509
+ if (!claimOutcome(meta, deliveryHost)) {
510
+ deferOutcome(meta, "Outcome dispatch is owned by another host; automatic reconciliation will retry.");
511
+ return;
512
+ }
513
+ const details = { completionEventIds: [outcome.eventId] };
514
+ const packed = packCallbackBatch([{
515
+ source: "subagent", id: outcome.eventId, inspectId: meta.id, receiptId: outcome.eventId,
516
+ label: meta.name ?? meta.id, status: outcome.outcome, outcome: outcome.reason,
517
+ detailTool: "subagent_result", callback: true,
518
+ }]);
519
+ try {
520
+ await pi.sendMessage({ customType: "background-completion-batch", display: true,
521
+ content: `${packed.text}\nAutomatic continuation: ${gate.reason}`, details }, { triggerTurn: false });
522
+ }
523
+ catch (error) {
524
+ // A failed persistence must not look like a durable transcript receipt.
525
+ details.completionEventIds.length = 0;
526
+ throw error;
527
+ }
528
+ const entry = outcomeTranscriptReceipt(ctx.sessionManager.getBranch(), outcome.eventId);
529
+ if (!entry)
530
+ throw new Error("Awaiting durable recipient transcript receipt.");
531
+ receiptOutcome(meta, entry);
532
+ markCompletionCallbackSent(meta.id, Date.now());
533
+ deferOutcome(meta);
534
+ try {
535
+ ctx.ui?.notify(`${meta.name ?? meta.id}: ${outcome.outcome}. Automatic continuation: ${gate.reason}. Inspect subagent_result.`, outcome.outcome === "failed" ? "warning" : "info");
536
+ }
537
+ catch { /* transcript remains visible */ }
538
+ return;
539
+ }
540
+ // Admission may yield across a session switch or Goal/workflow change.
541
+ if (sessionTornDown || outcomeHost !== deliveryHost || !uiCtx || callbackSuppressionReason(meta)
542
+ || !outcomeAdmission.get(outcome.eventId)?.()) {
543
+ deferOutcome(meta, "Parent delivery authority changed; automatic reconciliation will retry.");
544
+ return;
545
+ }
546
+ if (!claimOutcome(meta, outcomeHost)) {
547
+ deferOutcome(meta, "Outcome dispatch is owned by another host; automatic reconciliation will retry.");
548
+ return;
549
+ }
550
+ deferOutcome(meta);
551
+ getCallbackBatcher(pi).enqueue({
552
+ source: "subagent", id: outcome.eventId, inspectId: meta.id, receiptId: outcome.eventId,
553
+ label: meta.name ?? meta.id,
554
+ status: outcome.outcome, outcome: outcome.reason, detailTool: "subagent_result", callback: true,
555
+ isDelivered: () => Boolean(readOutcome(meta)?.deliveryReceipt),
556
+ getSuppressionReason: () => {
557
+ if (outcomeHost !== deliveryHost || !uiCtx || callbackSuppressionReason(meta))
558
+ throw new Error("Recorded parent is inactive; retain outcome.");
559
+ if ((outcome.recipient.branchId && !uiCtx.sessionManager.getBranch().some((entry) => entry.id === outcome.recipient.branchId)) || !outcomeAdmission.get(outcome.eventId)?.())
560
+ throw new Error("Parent delivery authority changed; retain outcome.");
561
+ return undefined;
562
+ },
563
+ onDelivered: (at) => {
564
+ const entry = uiCtx && outcomeTranscriptReceipt(uiCtx.sessionManager.getBranch(), outcome.eventId);
565
+ if (!entry)
566
+ throw new Error("Awaiting durable recipient transcript receipt.");
567
+ receiptOutcome(meta, entry);
568
+ markCompletionCallbackSent(meta.id, at);
569
+ },
570
+ });
571
+ }
572
+ /**
573
+ * Recover only records explicitly marked pending; legacy terminal runs never replay.
574
+ *
575
+ * Current-parent records are recovered unconditionally (the owner decides, and the
576
+ * session gate still suppresses a different foreground session). A run an
577
+ * interrupted DEAD parent left behind is recovered only by the conversation that
578
+ * launched it: that session id is the ownership proof, so an unrelated session
579
+ * never adopts it. A foreign parent that is still alive keeps ownership — the
580
+ * same `isAbandonedByParent` proof the running-record supervision uses — so this
581
+ * path never takes a live pi's terminal callback (#625, DEV-226 criterion 5).
582
+ */
583
+ function recoverAssignmentOutcomes(pi) {
584
+ for (const [id, pending] of pendingRecipientRecovery) {
585
+ const meta = readMeta(id);
586
+ if (!meta) {
587
+ pendingRecipientRecovery.delete(id);
588
+ continue;
589
+ }
590
+ if (pending.has("timing")) {
591
+ replayTimingWakes(pi, meta);
592
+ if (!meta.timing?.pendingWakes?.some(wake => !timingWakeReceipt(id, wake.key)))
593
+ finishRecipientRecovery(id, "timing");
594
+ }
595
+ if (pending.has("health")) {
596
+ if ((meta.status !== "orphaned" && meta.status !== "lost") || isHealthCallbackHandled(meta, meta.status))
597
+ finishRecipientRecovery(id, "health");
598
+ else
599
+ deliverHealthCallback(pi, meta, meta.status, Date.now());
600
+ }
601
+ if (pending.has("failure"))
602
+ deliverFailureAttention(pi, meta, Date.now());
603
+ if (pending.has("completion")) {
604
+ if (meta.completionCallbackSentAt !== undefined || meta.completionCallbackSuppressedAt !== undefined)
605
+ finishRecipientRecovery(id, "completion");
606
+ else
607
+ enqueueCompletionCallback(pi, id);
608
+ }
609
+ if (pending.has("assignment")) {
610
+ try {
611
+ const outcome = readOutcome(meta);
612
+ if (outcome?.deliveryReceipt || outcome?.disposition)
613
+ finishRecipientRecovery(id, "assignment");
614
+ else if (outcome)
615
+ void enqueueAssignmentOutcome(pi, meta);
616
+ }
617
+ catch { /* retry only the recorded pending handoff */ }
618
+ }
619
+ }
620
+ }
621
+ function observeRecipientNotifications(pi) {
622
+ const observation = workObservation();
623
+ if (sessionTornDown || observation?.status !== "ready")
624
+ return;
625
+ const ids = new Set();
626
+ for (const row of observation.rows) {
627
+ const meta = row.meta;
628
+ ids.add(meta.id);
629
+ const revision = JSON.stringify(row);
630
+ if (observedRecipientRows.get(meta.id) === revision)
631
+ continue;
632
+ observedRecipientRows.set(meta.id, revision);
633
+ if (meta.timing?.pendingWakes?.length)
634
+ trackRecipientRecovery(meta.id, "timing");
635
+ if (!meta.assignment && meta.completionCallbackPendingAt !== undefined && meta.completionCallbackSentAt === undefined && meta.completionCallbackSuppressedAt === undefined
636
+ && (meta.management || ownedByThisParent(meta) || (meta.supervisionInterruptedAt !== undefined && isAbandonedByParent(meta, realProcessProbe))))
637
+ trackRecipientRecovery(meta.id, "completion");
638
+ if ((meta.status === "orphaned" || meta.status === "lost") && !isHealthCallbackHandled(meta, meta.status))
639
+ trackRecipientRecovery(meta.id, "health");
640
+ if (meta.assignment && ["completed", "failed", "killed", "lost"].includes(meta.status))
641
+ trackRecipientRecovery(meta.id, "assignment");
642
+ if (row.failurePending || ["running", "orphaned", "lost"].includes(meta.status))
643
+ deliverFailureAttention(pi, meta, Date.now());
644
+ }
645
+ for (const id of observedRecipientRows.keys())
646
+ if (!ids.has(id))
647
+ observedRecipientRows.delete(id);
648
+ recoverAssignmentOutcomes(pi);
649
+ }
650
+ function recoverCompletionCallbacks(pi) {
651
+ observeRecipientNotifications(pi);
652
+ }
653
+ function deliverFailureAttention(pi, meta, now) {
654
+ if (managementPort)
655
+ return;
656
+ if (!pi || meta.callback === false || callbackSuppressionReason(meta))
657
+ return;
658
+ if ((meta.status === "orphaned" || meta.status === "lost") && !isHealthCallbackHandled(meta, meta.status))
659
+ return;
660
+ const state = collectRunFailures(meta.id, meta.cwd, meta.status !== "running" && meta.status !== "orphaned");
661
+ // Evidence gaps (oversized or malformed log records) are not something the parent can act on
662
+ // while the child runs; they ride the completion or health callback instead (#315). Once an
663
+ // orphaned run's health callback is handled there is no later callback that is sure to come
664
+ // (the run may stay orphaned), so gaps found after it are delivered now (#325).
665
+ const pending = pendingFailureAttention(state, now, { deferObservationGaps: meta.status === "running" });
666
+ if (!pending) {
667
+ finishRecipientRecovery(meta.id, "failure");
668
+ return;
669
+ }
670
+ if ((meta.status !== "running" && meta.status !== "orphaned" && meta.completionCallbackPendingAt !== undefined
671
+ && meta.completionCallbackSentAt === undefined && meta.completionCallbackSuppressedAt === undefined))
672
+ return;
673
+ trackRecipientRecovery(meta.id, "failure");
674
+ // Only the pending incidents are rendered; earlier deliveries are counted, not repeated (#315).
675
+ void getCallbackBatcher(pi).deliverUrgent({
676
+ ...failureAttentionFields(meta, state, pending),
677
+ isDelivered: () => failureAttentionHandled(collectRunFailures(meta.id, meta.cwd), pending.incidents),
678
+ getSuppressionReason: () => {
679
+ const current = readMeta(meta.id);
680
+ if (!current)
681
+ throw new Error("Subagent metadata is unavailable; defer failure notification");
682
+ return callbackSuppressionReason(current);
683
+ },
684
+ onDelivered: (at) => { markFailureAttentionDelivered(failurePath(meta.id), pending, at); finishRecipientRecovery(meta.id, "failure"); },
685
+ });
686
+ }
687
+ function markHealthCallbackSuppressed(meta, status, reason, now) {
688
+ if (isConversationIdentityReason(reason))
689
+ return;
690
+ writeMeta(meta, { patch: current => {
691
+ if (isHealthCallbackHandled(current, status))
692
+ return;
693
+ return status === "orphaned"
694
+ ? { orphanedCallbackSuppressedAt: now, orphanedCallbackSuppressedReason: reason }
695
+ : { lostCallbackSuppressedAt: now, lostCallbackSuppressedReason: reason };
696
+ } });
697
+ }
698
+ function isHealthCallbackHandled(meta, status) {
699
+ return status === "orphaned"
700
+ ? meta.orphanedCallbackSentAt !== undefined || meta.orphanedCallbackSuppressedAt !== undefined
701
+ : meta.lostCallbackSentAt !== undefined || meta.lostCallbackSuppressedAt !== undefined;
702
+ }
703
+ /**
704
+ * Refresh spend/tool for a run only when the cache is stale or the log grew —
705
+ * and never more often than the hot-path refresh floor, since a live child grows
706
+ * its log on every frame and each refresh re-parses a bounded log tail.
707
+ */
708
+ function spendFor(id, now) {
709
+ const cached = spendCache.get(id);
710
+ if (withinRefreshFloor(cached, now)) {
711
+ return { usage: cached.usage, tool: cached.tool };
712
+ }
713
+ const logSize = logSizeOf(id);
714
+ if (isSpendCacheFresh(cached, now, logSize)) {
715
+ return { usage: cached.usage, tool: cached.tool };
716
+ }
717
+ const r = parseRun(id);
718
+ const snap = {
719
+ usage: r.usage,
720
+ tool: r.toolCalls.length ? r.toolCalls[r.toolCalls.length - 1] : null,
721
+ refreshedAt: now,
722
+ logSize,
723
+ };
724
+ spendCache.set(id, snap);
725
+ return { usage: snap.usage, tool: snap.tool };
726
+ }
727
+ /**
728
+ * Observe health for a widget/navigator row. Best-effort; never throws into the tick.
729
+ * Full log parse is gated by size/mtime so event/detail refresh does not re-read and
730
+ * reparse every complete log when nothing changed (#67).
731
+ *
732
+ * When `displayStatus` is omitted, uses durable `meta.status`.
733
+ * Navigator detail/list pass `effectiveStatus(meta)` so process liveness cannot
734
+ * say "supervised" while the UI shows transient "exited" (#69).
735
+ */
736
+ function observeWidgetHealth(meta, now, displayStatus) {
737
+ try {
738
+ const cached = healthLogCache.get(meta.id);
739
+ // Inside the floor nothing is read at all — not even the log's stat.
740
+ const { size: logSize, mtimeMs } = withinRefreshFloor(cached, now)
741
+ ? { size: cached.logSize, mtimeMs: cached.mtimeMs }
742
+ : logStatOf(meta.id);
743
+ const resolved = resolveHealthLogExtraction(cached, { logSize, mtimeMs, now }, () => extractChildEventFactsFromLog(meta.id, { now }));
744
+ if (!resolved.hit) {
745
+ healthLogCache.set(meta.id, {
746
+ facts: resolved.facts,
747
+ rawLog: resolved.rawLog,
748
+ logSize,
749
+ mtimeMs,
750
+ refreshedAt: now,
751
+ });
752
+ }
753
+ const status = displayStatus ?? meta.status;
754
+ return observeRunHealth({
755
+ // Prefer caller-supplied effective/display status (navigator detail)
756
+ // so liveness cannot say "supervised" while the UI shows "exited".
757
+ status,
758
+ now,
759
+ facts: resolved.facts,
760
+ rawLog: resolved.rawLog,
761
+ thresholds: loadHealthThresholdsFromConfig(),
762
+ startedAt: meta.startedAt,
763
+ });
764
+ }
765
+ catch {
766
+ return undefined;
767
+ }
768
+ }
769
+ function syncWidgetNavSelection(running) {
770
+ if (!widgetNavActive)
771
+ return;
772
+ if (running.length === 0) {
773
+ widgetNavActive = false;
774
+ widgetNavSelectedId = undefined;
775
+ return;
776
+ }
777
+ if (!widgetNavSelectedId || !running.some((m) => m.id === widgetNavSelectedId)) {
778
+ // Start on the row nearest the input line; Down returns to input.
779
+ widgetNavSelectedId = running[running.length - 1]?.id;
780
+ }
781
+ }
782
+ /**
783
+ * Clear the retired legacy subagent widget and refresh the shared navigator.
784
+ * The shared background-work navigator is now the only list surface; keeping
785
+ * this path as clear-only prevents the old `Subagents · N running` widget from
786
+ * duplicating the same run below `background work · N`.
787
+ */
788
+ function renderWidget() {
789
+ const ctx = uiCtx;
790
+ if (!ctx)
791
+ return;
792
+ // A run can exit after Pi replaced the session that captured this ctx; Pi then throws on any
793
+ // property read. That session's UI is gone, so drop the ctx instead of failing the finalizer.
794
+ try {
795
+ if (!ctx.hasUI)
796
+ return;
797
+ }
798
+ catch {
799
+ if (uiCtx === ctx)
800
+ uiCtx = undefined;
801
+ return;
802
+ }
803
+ updateNavigatorFooter(ctx);
804
+ try {
805
+ ctx.ui.setWidget("subagents", WIDGET_CLEAR);
806
+ }
807
+ catch { /* ignore */ }
808
+ spendCache.clear();
809
+ healthLogCache.clear();
810
+ resetChildEventLogCursor();
811
+ resetParseRunCursor();
812
+ stopTicker();
813
+ }
814
+ /** Clear the retired widget if a UI is present. */
815
+ function ensureTicker() {
816
+ if (!uiCtx?.hasUI)
817
+ return;
818
+ renderWidget();
819
+ }
820
+ function stopTicker() {
821
+ if (ticker) {
822
+ clearInterval(ticker);
823
+ ticker = undefined;
824
+ }
825
+ }
826
+ // ---- periodic health reconciliation (#63) --------------------------------
827
+ //
828
+ // Reconciles durable supervision status for current-parent running/orphaned
829
+ // runs (process-group-only, ADR 0002): a run whose child is gone but whose
830
+ // captured process group still has live members becomes durable non-terminal
831
+ // `orphaned`; a run with no credible process-group evidence becomes durable
832
+ // terminal `lost`. Escaped/reparented descendants are out of contract.
833
+ // Reconciliation never kills anything; it only writes truth. The ticker
834
+ // exists only while current-parent running/orphaned work needs monitoring.
835
+ /** How often supervision is reconciled. Independent of TUI render scheduling. */
836
+ const HEALTH_TICK_MS = 15_000;
837
+ let healthTicker;
838
+ let managedHealthClose;
839
+ /** ExtensionAPI retained so health transitions can deliver coordinator follow-ups (#65). */
840
+ let healthPi;
841
+ /**
842
+ * Deliver a durable, deduped coordinator follow-up for orphaned/lost (#65).
843
+ *
844
+ * Markers live on RunMeta so reloads and repeated health ticks never re-fire.
845
+ * A marker means successful handoff only: written after sendMessage returns, or
846
+ * after a UI warning under callback:false. An unavailable UI, failed or crashed
847
+ * delivery leaves the marker unset so reload/recovery can retry.
848
+ * `callback:false` suppresses the model message only; the scoped frontend UI
849
+ * is notified before recording quiet delivery. Uses the same followUp mechanics as
850
+ * completion, with distinct ATTENTION wording from buildHealthCallbackDelivery.
851
+ */
852
+ function deliverHealthCallback(pi, meta, status, now) {
853
+ if (managementPort)
854
+ return;
855
+ if (!pi)
856
+ return;
857
+ if (isHealthCallbackHandled(meta, status))
858
+ return;
859
+ if (callbackSuppressionReason(meta))
860
+ return;
861
+ const callback = meta.callback !== false;
862
+ const label = meta.name ? `${meta.name} (${meta.id})` : meta.id;
863
+ const failureState = collectRunFailures(meta.id, meta.cwd, status === "lost");
864
+ const attention = pendingFailureAttention(failureState, now, { terminal: status === "lost" });
865
+ const delivery = buildHealthCallbackDelivery({ id: meta.id, label, status, callback });
866
+ if (!delivery) {
867
+ const current = readMeta(meta.id);
868
+ if (!current || current.status !== status || isHealthCallbackHandled(current, status) || callbackSuppressionReason(current))
869
+ return;
870
+ meta = current;
871
+ if (!uiCtx?.hasUI)
872
+ return;
873
+ const notice = status === "orphaned"
874
+ ? `Subagent ${label} lost supervision - related processes may still be alive (orphaned).`
875
+ : `Subagent ${label} is lost - no related process remains and no terminal result was observed.`;
876
+ try {
877
+ uiCtx.ui.notify(notice, "warning");
878
+ }
879
+ catch {
880
+ return;
881
+ }
882
+ // The marker acknowledges quiet delivery, never a model turn.
883
+ writeMeta(meta, { patch: current => {
884
+ if (current.status !== status || isHealthCallbackHandled(current, status) || callbackSuppressionReason(current))
885
+ return;
886
+ return status === "orphaned" ? { orphanedCallbackSentAt: now } : { lostCallbackSentAt: now };
887
+ } });
888
+ return;
889
+ }
890
+ void getCallbackBatcher(pi).deliverUrgent({
891
+ ...healthCallbackFields(meta, status, failureState, delivery.content, attention?.incidents ?? []),
892
+ isDelivered: () => {
893
+ const current = readMeta(meta.id);
894
+ if (!current)
895
+ throw new Error("Subagent metadata is unavailable; defer health notification");
896
+ return isHealthCallbackHandled(current, status);
897
+ },
898
+ getSuppressionReason: () => {
899
+ const current = readMeta(meta.id);
900
+ if (!current)
901
+ throw new Error("Subagent metadata is unavailable; defer health notification");
902
+ return callbackSuppressionReason(current);
903
+ },
904
+ onDelivered: (at) => {
905
+ const current = readMeta(meta.id);
906
+ if (!current || isHealthCallbackHandled(current, status))
907
+ return;
908
+ if (attention) {
909
+ markFailureAttentionDelivered(failurePath(meta.id), attention, at);
910
+ if (attention.incidents.some((incident) => pendingFailureAttention(collectRunFailures(meta.id, meta.cwd), at, { terminal: true })?.incidents.includes(incident)))
911
+ return;
912
+ }
913
+ writeMeta(current, { patch: current => {
914
+ if (isHealthCallbackHandled(current, status))
915
+ return;
916
+ return status === "orphaned" ? { orphanedCallbackSentAt: at } : { lostCallbackSentAt: at };
917
+ } });
918
+ },
919
+ onSuppressed: (reason, at) => {
920
+ const current = readMeta(meta.id);
921
+ if (!current || isHealthCallbackHandled(current, status))
922
+ return;
923
+ markHealthCallbackSuppressed(current, status, reason, at);
924
+ },
925
+ });
926
+ }
927
+ // ---- harness timing: soft deadline, hard ceiling, stuck wake ----------------
928
+ //
929
+ // Timeout control is the harness's job, not the launching prompt's: nothing
930
+ // else enforces an orchestrator's "30-minute attempt", and a parent that only
931
+ // notices late kills a child that was still making progress. Policy lives in
932
+ // timing.ts; this host part reads progress from the child's own event log,
933
+ // writes the steer request the child's control extension (child-steer.ts)
934
+ // delivers, wakes the parent once per event, and stops the run when due.
935
+ /** Incremental progress read per run (rebuilt from the log after /reload). */
936
+ const progressCache = new Map();
937
+ function steerPathFor(id) {
938
+ return join(runDir(id), "steer.json");
939
+ }
940
+ function childSteerExtensionPath() {
941
+ return join(selfDir(), "child-steer.ts");
942
+ }
943
+ function readProgress(meta) {
944
+ let entry = progressCache.get(meta.id);
945
+ const read = readAppendedLines(logPathFor(meta.id), entry?.cursor);
946
+ // A fresh (or restarted) fold may have lost the start of a call that is still
947
+ // running: seed it from the durable record rather than reporting silence.
948
+ if (!entry || read.restarted) {
949
+ entry = { state: emptyProgress(meta.startedAt, meta.timing?.openCalls ?? meta.timing?.inFlight) };
950
+ }
951
+ if (read.error === undefined)
952
+ entry.cursor = read.cursor;
953
+ for (const line of read.lines) {
954
+ if (!isProgressRelevantLine(line))
955
+ continue;
956
+ let event;
957
+ try {
958
+ event = JSON.parse(line);
959
+ }
960
+ catch {
961
+ continue;
962
+ }
963
+ if (event && typeof event === "object")
964
+ foldProgress(entry.state, event);
965
+ }
966
+ progressCache.set(meta.id, entry);
967
+ return entry.state;
968
+ }
969
+ /** Merge into the durable timing record under a fresh read. */
970
+ function patchTiming(id, patch) {
971
+ const current = readMeta(id);
972
+ if (!current?.timing)
973
+ return undefined;
974
+ current.timing = { ...current.timing, ...patch };
975
+ for (const key of Object.keys(patch)) {
976
+ if (patch[key] === undefined)
977
+ delete current.timing[key];
978
+ }
979
+ writeMeta(current);
980
+ return current;
981
+ }
982
+ function requestSteer(meta, now) {
983
+ const path = steerPathFor(meta.id);
984
+ const tmp = `${path}.${process.pid}.tmp`;
985
+ writeFileSync(tmp, JSON.stringify({ id: `deadline:${meta.id}`, text: steerText(meta.timing, meta.startedAt), at: now }));
986
+ renameSync(tmp, path);
987
+ }
988
+ function timingLabel(meta) {
989
+ return meta.name ? `${meta.name} (${meta.id})` : meta.id;
990
+ }
991
+ function fmtWindow(ms) {
992
+ const minutes = Math.round(ms / 60_000);
993
+ return minutes >= 1 ? `${minutes}m` : `${Math.max(1, Math.round(ms / 1000))}s`;
994
+ }
995
+ function sameOpenCalls(a, b) {
996
+ return a !== undefined && a.length === b.length && a.every((call, index) => {
997
+ const next = b[index];
998
+ return next !== undefined && call.id === next.id && call.since === next.since
999
+ && call.name === next.name && call.command === next.command;
1000
+ });
1001
+ }
1002
+ /**
1003
+ * One parent wake for a timing event. The marker records a handoff (or an
1004
+ * intentional suppression), so reloads and later ticks never repeat it.
1005
+ */
1006
+ function deliverTimingWake(pi, meta, kind, key, content, isHandled, markHandled) {
1007
+ if (managementPort) {
1008
+ foldTimingWakeReceipts(readMeta(meta.id) ?? meta);
1009
+ if (isHandled(readMeta(meta.id) ?? meta))
1010
+ return;
1011
+ const receipt = timingWakeReceipt(meta.id, key);
1012
+ if (receipt !== undefined) {
1013
+ markHandled(receipt);
1014
+ return;
1015
+ }
1016
+ const current = readMeta(meta.id);
1017
+ const pending = (current?.timing?.pendingWakes ?? []).filter(wake => timingWakeReceipt(meta.id, wake.key) === undefined);
1018
+ const next = appendTimingWake(pending, { kind, key, content });
1019
+ if (next !== pending)
1020
+ patchTiming(meta.id, { pendingWakes: next });
1021
+ return;
1022
+ }
1023
+ // Foreign/inactive foregrounds must leave the durable notification pending.
1024
+ if (callbackSuppressionReason(meta))
1025
+ return;
1026
+ try {
1027
+ uiCtx?.ui.notify(content, "warning");
1028
+ }
1029
+ catch { /* ignore */ }
1030
+ if (!pi || meta.callback === false) {
1031
+ markHandled(Date.now());
1032
+ return;
1033
+ }
1034
+ void getCallbackBatcher(pi).deliverUrgent({
1035
+ source: "subagent",
1036
+ receiptId: `timing:${meta.id}:${key}`,
1037
+ id: meta.id,
1038
+ label: timingLabel(meta),
1039
+ status: key,
1040
+ customType: `subagent-${kind}`,
1041
+ content,
1042
+ detailTool: "subagent_result",
1043
+ isDelivered: () => {
1044
+ const current = readMeta(meta.id);
1045
+ if (!current)
1046
+ throw new Error("Subagent metadata is unavailable; defer timing notification");
1047
+ return isHandled(current);
1048
+ },
1049
+ getSuppressionReason: () => {
1050
+ const current = readMeta(meta.id);
1051
+ if (!current)
1052
+ throw new Error("Subagent metadata is unavailable; defer timing notification");
1053
+ return callbackSuppressionReason(current);
1054
+ },
1055
+ onDelivered: (at) => markHandled(at),
1056
+ onSuppressed: () => { },
1057
+ });
1058
+ }
1059
+ function replayTimingWakes(pi, meta) {
1060
+ if (managementPort || callbackSuppressionReason(meta))
1061
+ return;
1062
+ meta = readMeta(meta.id) ?? meta;
1063
+ for (const wake of meta.timing?.pendingWakes ?? []) {
1064
+ if (timingWakeHandled(meta, wake.key))
1065
+ continue;
1066
+ const eventId = `timing:${meta.id}:${wake.key}`;
1067
+ const entries = uiCtx?.sessionManager?.getBranch?.() ?? [];
1068
+ const receipt = entries.some((entry) => {
1069
+ const message = entry.type === "custom_message" ? entry : entry.type === "message" && entry.message?.role === "custom" ? entry.message : undefined;
1070
+ return message?.customType === `subagent-${wake.kind}` && message.details?.urgentEventId === eventId;
1071
+ });
1072
+ if (receipt) {
1073
+ receiptTimingWake(meta.id, wake.key, Date.now());
1074
+ continue;
1075
+ }
1076
+ deliverTimingWake(pi, meta, wake.kind, wake.key, wake.content, () => timingWakeHandled(readMeta(meta.id) ?? meta, wake.key), at => receiptTimingWake(meta.id, wake.key, at));
1077
+ }
1078
+ }
1079
+ function timingWakeHandled(meta, key) {
1080
+ if (timingWakeReceipt(meta.id, key) !== undefined)
1081
+ return true;
1082
+ if (key === "deadline")
1083
+ return meta.timing?.deadlineWakeSentAt !== undefined;
1084
+ if (key.startsWith("tool-wait:"))
1085
+ return (meta.timing?.toolWaitAlerted ?? []).includes(key.slice(10));
1086
+ if (key.startsWith("stuck:"))
1087
+ return meta.timing?.stuckWakeSentAt !== undefined && (meta.timing.stuckAnchorAt ?? 0) >= Number(key.slice(6));
1088
+ return false;
1089
+ }
1090
+ function foldTimingWakeReceipts(meta) {
1091
+ const pending = meta.timing?.pendingWakes ?? [];
1092
+ const acknowledged = pending.filter(wake => wake.key !== "timing-overflow" && timingWakeReceipt(meta.id, wake.key) !== undefined);
1093
+ if (!acknowledged.length || !meta.timing)
1094
+ return;
1095
+ const patch = { ...meta.timing, pendingWakes: pending.filter(wake => !acknowledged.includes(wake)) };
1096
+ for (const wake of acknowledged) {
1097
+ const at = timingWakeReceipt(meta.id, wake.key);
1098
+ if (wake.kind === "deadline")
1099
+ patch.deadlineWakeSentAt = at;
1100
+ if (wake.kind === "stuck") {
1101
+ patch.stuckWakeSentAt = at;
1102
+ patch.stuckAnchorAt = Math.max(patch.stuckAnchorAt ?? 0, Number(wake.key.slice(6)));
1103
+ }
1104
+ if (wake.kind === "tool-wait")
1105
+ patch.toolWaitAlerted = [...new Set([...(patch.toolWaitAlerted ?? []), wake.key.slice(10)])];
1106
+ }
1107
+ patchTiming(meta.id, patch);
1108
+ for (const wake of acknowledged)
1109
+ removeTimingReceipt(meta.id, wake.key);
1110
+ }
1111
+ /** Stop a run for a timing reason and report it through the ordinary completion callback. */
1112
+ function stopForTiming(pi, id, reason, now) {
1113
+ if (!patchTiming(id, { stopReason: reason, stoppedAt: now }))
1114
+ return false;
1115
+ const outcome = stopRun(id, { now: () => now });
1116
+ if (outcome.action !== "stopped") {
1117
+ // The child finished on its own first (or an orphaned run's group was already gone and
1118
+ // it was finalized from its log): its own exit is the outcome, not a harness stop.
1119
+ patchTiming(id, { stopReason: undefined, stoppedAt: undefined });
1120
+ progressCache.delete(id);
1121
+ // A log finalization is terminal evidence discovered here, not by the child
1122
+ // exit handler, so this path still owes the one completion callback (#624).
1123
+ if (pi && outcome.action === "finalized")
1124
+ enqueueCompletionCallback(pi, id);
1125
+ return outcome.action === "finalized";
1126
+ }
1127
+ const current = readMeta(id);
1128
+ if (current && current.callback !== false && current.completionCallbackPendingAt === undefined
1129
+ && current.completionCallbackSentAt === undefined && current.completionCallbackSuppressedAt === undefined) {
1130
+ current.completionCallbackPendingAt = now;
1131
+ writeMeta(current);
1132
+ }
1133
+ progressCache.delete(id);
1134
+ if (current && !callbackSuppressionReason(current)) {
1135
+ const note = describeTiming({ ...current, status: current.status });
1136
+ try {
1137
+ uiCtx?.ui.notify(`Subagent ${timingLabel(current)} ${note?.short ?? `stopped: ${reason}`}.`, "warning");
1138
+ }
1139
+ catch { /* ignore */ }
1140
+ }
1141
+ if (pi)
1142
+ enqueueCompletionCallback(pi, id);
1143
+ renderWidget();
1144
+ return true;
1145
+ }
1146
+ /**
1147
+ * Apply the run's timing policy at `now`. Returns true when the run was stopped.
1148
+ * Only supervised `running` runs owned by this parent are timed.
1149
+ */
1150
+ function enforceTiming(pi, meta, now) {
1151
+ const timing = meta.timing;
1152
+ if (!timing || timing.stopReason)
1153
+ return false;
1154
+ // The ceiling also bounds an orphaned run (child gone, its process group still alive).
1155
+ if (meta.status === "orphaned") {
1156
+ return timing.ceilingAt !== undefined && now >= timing.ceilingAt ? stopForTiming(pi, meta.id, "ceiling", now) : false;
1157
+ }
1158
+ if (meta.status !== "running")
1159
+ return false;
1160
+ // Progress is folded whenever a control can use it: the stuck or tool-wait
1161
+ // window, or a deadline whose steer must be held behind a running call (the
1162
+ // record of that call must exist before the deadline, not only after it).
1163
+ const needsProgress = timing.stuckMs !== undefined || timing.toolWaitMs !== undefined || timing.deadlineAt !== undefined;
1164
+ const progress = needsProgress ? readProgress(meta) : undefined;
1165
+ const patch = {};
1166
+ if (progress?.lastProgressAt !== undefined && progress.lastProgressAt > (timing.lastProgressAt ?? 0))
1167
+ patch.lastProgressAt = progress.lastProgressAt;
1168
+ if (progress) {
1169
+ const openCalls = [...progress.open.entries()].map(([id, call]) => ({
1170
+ id, since: call.startedAt,
1171
+ ...(call.name ? { name: call.name } : {}),
1172
+ ...(call.command !== undefined ? { command: call.command.slice(0, 200) } : {}),
1173
+ }));
1174
+ const first = openCalls[0];
1175
+ const openId = first?.id;
1176
+ const since = progress.inFlightSince ?? first?.since ?? progress.lastEventAt ?? meta.startedAt;
1177
+ // Durable still-alive evidence: every call the child is waiting on. Survives a
1178
+ // reload whose bounded log read no longer contains a call's start (#620).
1179
+ if (openCalls.length > 0) {
1180
+ if (!sameOpenCalls(timing.openCalls, openCalls))
1181
+ patch.openCalls = openCalls;
1182
+ }
1183
+ else if (timing.openCalls !== undefined) {
1184
+ patch.openCalls = undefined;
1185
+ }
1186
+ if (openId === undefined) {
1187
+ if (timing.inFlight !== undefined)
1188
+ patch.inFlight = undefined;
1189
+ }
1190
+ else if (timing.inFlight?.id !== openId || timing.inFlight.since !== since) {
1191
+ patch.inFlight = { id: openId, since };
1192
+ }
1193
+ // A finished call needs no marker. Keeping only live call ids bounds the record.
1194
+ const openIds = new Set(openCalls.map((call) => call.id));
1195
+ const alerted = (timing.toolWaitAlerted ?? []).filter((id) => openIds.has(id));
1196
+ if (alerted.length !== (timing.toolWaitAlerted ?? []).length) {
1197
+ patch.toolWaitAlerted = alerted.length > 0 ? alerted : undefined;
1198
+ }
1199
+ }
1200
+ if (timing.steerRequestedAt !== undefined && timing.steerDeliveredAt === undefined) {
1201
+ // The child's receipt for this run's steer; clamped so a skewed clock cannot move grace earlier than the request.
1202
+ const receipt = readSteerReceipt(steerPathFor(meta.id));
1203
+ if (receipt?.id === `deadline:${meta.id}`)
1204
+ patch.steerDeliveredAt = Math.min(now, Math.max(receipt.at, timing.steerRequestedAt));
1205
+ }
1206
+ if (Object.keys(patch).length)
1207
+ meta = patchTiming(meta.id, patch) ?? meta;
1208
+ const actions = decideTiming(meta.timing, progress, now);
1209
+ if (actions.stop)
1210
+ return stopForTiming(pi, meta.id, actions.stop, now);
1211
+ if (actions.steer) {
1212
+ try {
1213
+ requestSteer(meta, now);
1214
+ meta = patchTiming(meta.id, { steerRequestedAt: now }) ?? meta;
1215
+ }
1216
+ catch { /* retried on the next tick */ }
1217
+ }
1218
+ if (actions.deadlineWake && meta.timing?.steerRequestedAt !== undefined) {
1219
+ const t = meta.timing;
1220
+ const limit = t.deadlineAt !== undefined ? fmtWindow(t.deadlineAt - meta.startedAt) : "soft";
1221
+ deliverTimingWake(pi, meta, "deadline", "deadline", `Subagent ${timingLabel(meta)} reached its ${limit} soft deadline. The harness told it to stop starting new work, ` +
1222
+ `commit what is done, and report. The message reaches it after its current tool call; if it has not finished ${fmtWindow(t.graceMs)} after that, ` +
1223
+ `the harness stops it (reason: deadline).`, (current) => current.timing?.deadlineWakeSentAt !== undefined, (at) => { patchTiming(meta.id, { deadlineWakeSentAt: at }); });
1224
+ }
1225
+ for (const wake of actions.toolWaitWakes ?? []) {
1226
+ const lastProgressAt = Math.max(progress?.lastProgressAt ?? 0, meta.timing?.lastProgressAt ?? 0) || undefined;
1227
+ const content = toolWaitAlertText({
1228
+ id: meta.id,
1229
+ label: timingLabel(meta),
1230
+ callId: wake.callId,
1231
+ toolName: wake.name ?? "",
1232
+ ...(wake.command !== undefined ? { command: wake.command } : {}),
1233
+ openMs: wake.ageMs,
1234
+ thresholdMs: meta.timing?.toolWaitMs ?? wake.ageMs,
1235
+ now,
1236
+ ...(lastProgressAt !== undefined ? { lastProgressAt } : {}),
1237
+ logPath: meta.logPath,
1238
+ });
1239
+ deliverTimingWake(pi, meta, "tool-wait", `tool-wait:${wake.callId}`, content, (current) => (current.timing?.toolWaitAlerted ?? []).includes(wake.callId), () => {
1240
+ const current = readMeta(meta.id);
1241
+ const alerted = current?.timing?.toolWaitAlerted ?? [];
1242
+ if (!alerted.includes(wake.callId)) {
1243
+ patchTiming(meta.id, { toolWaitAlerted: [...alerted, wake.callId] });
1244
+ }
1245
+ });
1246
+ }
1247
+ if (actions.stuckWake) {
1248
+ const { anchorAt, ageMs } = actions.stuckWake;
1249
+ const lastProgressAt = Math.max(progress?.lastProgressAt ?? 0, meta.timing?.lastProgressAt ?? 0) || undefined;
1250
+ deliverTimingWake(pi, meta, "stuck", `stuck:${anchorAt}`, stuckAlertText({
1251
+ id: meta.id, label: timingLabel(meta), ageMs,
1252
+ windowMs: meta.timing?.stuckMs ?? ageMs, now,
1253
+ ...(lastProgressAt !== undefined ? { lastProgressAt } : {}),
1254
+ logPath: meta.logPath,
1255
+ }), (current) => current.timing?.stuckWakeSentAt !== undefined && (current.timing.stuckAnchorAt ?? 0) >= anchorAt, (at) => { patchTiming(meta.id, { stuckWakeSentAt: at, stuckAnchorAt: anchorAt }); });
1256
+ }
1257
+ return false;
1258
+ }
1259
+ /** One reconciliation + durable health-callback recovery pass. */
1260
+ function reconcileHealth(ids) {
1261
+ if (!managementPort)
1262
+ return;
1263
+ try {
1264
+ managementPort.assertCurrent();
1265
+ }
1266
+ catch {
1267
+ stopHealthTicker();
1268
+ return;
1269
+ }
1270
+ const ctx = uiCtx;
1271
+ const pi = healthPi;
1272
+ const selected = ids ? ids.map(id => readMeta(id)).filter((meta) => Boolean(meta)) : supervisedMetas();
1273
+ for (const summary of selected) {
1274
+ if (!ownedByThisParent(summary))
1275
+ continue;
1276
+ // running/orphaned: process reconcile. lost: durable callback recovery only.
1277
+ if (summary.status !== "running" && summary.status !== "orphaned" && summary.status !== "lost")
1278
+ continue;
1279
+ // Re-read under the id: finalizeRun / subagent_stop may have written a
1280
+ // terminal status since the owned index was read.
1281
+ const meta = readMeta(summary.id);
1282
+ if (!meta)
1283
+ continue;
1284
+ if (meta.status !== "running" && meta.status !== "orphaned" && meta.status !== "lost")
1285
+ continue;
1286
+ const now = Date.now();
1287
+ if (meta.status === "orphaned" || meta.status === "lost") {
1288
+ observeFailures(failurePath(meta.id), [{ id: `supervision:${meta.status}`, operation: `supervision:${meta.status}`, kind: "incomplete",
1289
+ summary: meta.status === "lost" ? "Child supervision was lost; outcome is unknown" : "Child supervision interrupted; related work may still be alive" }], now);
1290
+ }
1291
+ deliverFailureAttention(pi, meta, now);
1292
+ // Interrupted work whose child already exited is finalized from its own
1293
+ // coherent log before any other verdict (and before timing can mislabel
1294
+ // an already-finished run as stopped) (#625).
1295
+ let interruptedReconciliation;
1296
+ if (meta.status === "running" || meta.status === "orphaned") {
1297
+ try {
1298
+ if (pi && !directlySupervisedRunIds.has(meta.id) && meta.supervisionInterruptedAt !== undefined) {
1299
+ const observed = reconcileInterruptedRun(meta, realProcessProbe, now, {
1300
+ renderWidget,
1301
+ notify: (message, level) => { try {
1302
+ ctx?.ui.notify(message, level);
1303
+ }
1304
+ catch { /* unavailable UI */ } },
1305
+ sendMessage: () => enqueueCompletionCallback(pi, meta.id),
1306
+ });
1307
+ if (observed.finalization?.applied) {
1308
+ syncHealthTicker();
1309
+ continue;
1310
+ }
1311
+ interruptedReconciliation = observed.reconciliation;
1312
+ }
1313
+ }
1314
+ catch { /* best-effort; the ordinary reconciliation below still runs */ }
1315
+ }
1316
+ try {
1317
+ if (enforceTiming(pi, meta, now))
1318
+ continue;
1319
+ }
1320
+ catch { /* timing is best-effort per tick; supervision below still runs */ }
1321
+ if (meta.status === "running" || meta.status === "orphaned") {
1322
+ const result = interruptedReconciliation ?? reconcileRun(meta, realProcessProbe, now);
1323
+ if (result.changed) {
1324
+ Object.assign(meta, result.patch, { status: result.status });
1325
+ writeMeta(meta);
1326
+ if (result.status === "lost") {
1327
+ observeFailures(failurePath(meta.id), [
1328
+ { id: "supervision:orphaned-resolved", operation: "supervision:orphaned", kind: "recovered", incidents: ["supervision:orphaned"] },
1329
+ { id: "supervision:lost", operation: "supervision:lost", kind: "incomplete", summary: "Child supervision was lost; outcome is unknown" },
1330
+ ], now);
1331
+ }
1332
+ else if (result.status === "orphaned") {
1333
+ observeFailures(failurePath(meta.id), [{ id: "supervision:orphaned", operation: "supervision:orphaned", kind: "incomplete", summary: "Child supervision interrupted; related work may still be alive" }], now);
1334
+ }
1335
+ if (result.transition) {
1336
+ // Human-visible health (always) on fresh transitions.
1337
+ if (!callbackSuppressionReason(meta)) {
1338
+ const label = meta.name ? `${meta.name} (${meta.id})` : meta.id;
1339
+ const note = result.status === "orphaned"
1340
+ ? `Subagent ${label} lost supervision — related processes may still be alive (orphaned).`
1341
+ : `Subagent ${label} is lost — no related process remains and no terminal result was observed.`;
1342
+ try {
1343
+ ctx?.ui.notify(note, "warning");
1344
+ }
1345
+ catch { /* ignore */ }
1346
+ }
1347
+ }
1348
+ }
1349
+ }
1350
+ // Canonical loss is an assignment terminal fact even when no recipient
1351
+ // is attached. This manager already proved current epoch, ownership and
1352
+ // process identity above; native foregrounds never enter this pass.
1353
+ if (meta.status === "lost" && meta.assignment && pi)
1354
+ enqueueCompletionCallback(pi, meta.id);
1355
+ // Durable recovery independent of a fresh transition: any current
1356
+ // orphaned/lost without a successful handoff marker must eventually
1357
+ // deliver exactly one coordinator follow-up (or mark callback:false).
1358
+ if (meta.status === "orphaned" || meta.status === "lost") {
1359
+ deliverHealthCallback(pi, meta, meta.status, now);
1360
+ }
1361
+ }
1362
+ // A restart leaves an explicitly interrupted child whose owning pi is gone
1363
+ // (#625). Its record is foreign, so the owner-gated loops above never see it:
1364
+ // finalize it from its own coherent log once the child itself is gone. This
1365
+ // is the human's own interrupted work, not another session's live run, and
1366
+ // `finalizeInterruptedRunFromLog` still requires all process evidence to be
1367
+ // absent, so a live writer is never touched.
1368
+ for (const summary of ids ? selected : listMetas({ includeArchived: false })) {
1369
+ if (summary.status !== "running" && summary.status !== "orphaned")
1370
+ continue;
1371
+ if (ownedByThisParent(summary) || !ownsInterruptedSupervision(summary))
1372
+ continue;
1373
+ const meta = readMeta(summary.id);
1374
+ if (!meta || (meta.status !== "running" && meta.status !== "orphaned"))
1375
+ continue;
1376
+ try {
1377
+ finalizeInterruptedRunFromLog(pi, meta, Date.now());
1378
+ }
1379
+ catch { /* the next tick retries */ }
1380
+ }
1381
+ // Completed runs can still have failed completion handoffs to retry.
1382
+ for (const summary of selected) {
1383
+ if (!pi || !ownedByThisParent(summary) || summary.status === "running" || summary.status === "orphaned" || summary.status === "lost")
1384
+ continue;
1385
+ const meta = readMeta(summary.id);
1386
+ if (meta && meta.completionCallbackPendingAt !== undefined && meta.completionCallbackSentAt === undefined && meta.completionCallbackSuppressedAt === undefined)
1387
+ enqueueCompletionCallback(pi, meta.id);
1388
+ }
1389
+ pruneProgressCache();
1390
+ syncHealthTicker();
1391
+ }
1392
+ /** Release progress state for runs that are no longer live (lost, stopped, or finished by any path). */
1393
+ function pruneProgressCache() {
1394
+ for (const id of [...progressCache.keys()]) {
1395
+ const meta = readMeta(id);
1396
+ if (!meta || (meta.status !== "running" && meta.status !== "orphaned"))
1397
+ progressCache.delete(id);
1398
+ }
1399
+ }
1400
+ /** Test seam: run ids whose progress state is held in memory. */
1401
+ export function progressCacheIdsForTests() {
1402
+ return [...progressCache.keys()];
1403
+ }
1404
+ /** Test seam: drop the in-memory progress fold, as a reloaded extension instance does. */
1405
+ export function forgetProgressCacheForTests() {
1406
+ progressCache.clear();
1407
+ }
1408
+ /**
1409
+ * This pi's own start-identity token, recorded on every run it spawns so a later
1410
+ * process can tell "my parent is gone" from "my parent's pid was recycled".
1411
+ */
1412
+ function parentStartToken() {
1413
+ try {
1414
+ return realProcessProbe.startToken(process.pid);
1415
+ }
1416
+ catch {
1417
+ return undefined;
1418
+ }
1419
+ }
1420
+ /**
1421
+ * Reconcile records whose spawning pi is provably gone.
1422
+ *
1423
+ * Reconciliation above is owner-gated — a pi must not adjudicate another pi's
1424
+ * children — and retention only ever retires TERMINAL records. Those two correct
1425
+ * rules trap a `running`/`orphaned` record whose parent died without a clean
1426
+ * shutdown: no live process is its owner, so nothing moves it to `lost`, so it
1427
+ * never becomes eligible for retention and lives forever. One such record was
1428
+ * observed pinning 1.1 GB indefinitely.
1429
+ *
1430
+ * Adoption is status-only and uses exactly the same evidence rules: reconcileRun
1431
+ * owns the verdict. Deliberately NOT done: no notify (this session did not launch
1432
+ * the run, so reporting it would be noise about someone else's work), no callback
1433
+ * delivery (the coordinator it was meant for no longer exists), and no effect on
1434
+ * ticker lifetime — an adopted record never keeps this session's loop alive. It is
1435
+ * swept when the loop happens to run, and once at session start.
1436
+ *
1437
+ * Best-effort; never throws into a caller.
1438
+ */
1439
+ function reconcileAbandonedRuns(now = Date.now()) {
1440
+ let adopted = 0;
1441
+ try {
1442
+ for (const summary of listMetas()) {
1443
+ if (summary.management && !ownedByThisParent(summary))
1444
+ continue;
1445
+ if (ownedByThisParent(summary))
1446
+ continue;
1447
+ if (summary.status !== "running" && summary.status !== "orphaned")
1448
+ continue;
1449
+ if (!isAbandonedByParent(summary, realProcessProbe))
1450
+ continue;
1451
+ // Re-read under the id: another pi may have adopted it since the snapshot.
1452
+ const meta = readMeta(summary.id);
1453
+ if (!meta)
1454
+ continue;
1455
+ if (meta.status !== "running" && meta.status !== "orphaned")
1456
+ continue;
1457
+ const result = reconcileRun(meta, realProcessProbe, now);
1458
+ if (!result.changed)
1459
+ continue;
1460
+ Object.assign(meta, result.patch, { status: result.status });
1461
+ meta.adoptedFromLostParentAt = meta.adoptedFromLostParentAt ?? now;
1462
+ writeMeta(meta);
1463
+ adopted += 1;
1464
+ }
1465
+ }
1466
+ catch { /* best-effort */ }
1467
+ return adopted;
1468
+ }
1469
+ /** Completion batches own their retry timer; only supervision keeps this one alive. */
1470
+ function syncHealthTicker() {
1471
+ if (!managementPort) {
1472
+ stopHealthTicker();
1473
+ return;
1474
+ }
1475
+ // A replaced instance never restarts supervision loops for a session it no
1476
+ // longer owns; the live instance runs its own. It must still STOP one that is
1477
+ // already armed: a run this instance launched before teardown can finish
1478
+ // afterwards, and returning early here left the interval supervising a
1479
+ // session that no longer exists (#625).
1480
+ if (sessionTornDown) {
1481
+ stopHealthTicker();
1482
+ return;
1483
+ }
1484
+ if (managementPort.observeHealth) {
1485
+ ensureHealthTicker();
1486
+ return;
1487
+ }
1488
+ if (needsMonitoring(supervisedMetas()) || needsInterruptedSupervision())
1489
+ ensureHealthTicker();
1490
+ else
1491
+ stopHealthTicker();
1492
+ }
1493
+ /** Start the reconciliation loop if it isn't already running. */
1494
+ function ensureHealthTicker() {
1495
+ if (!managementPort)
1496
+ return;
1497
+ if (managementPort.observeHealth) {
1498
+ managedHealthClose ??= managementPort.observeHealth(ids => reconcileHealth(ids));
1499
+ return;
1500
+ }
1501
+ // Not gated on `sessionTornDown`: a spawn always means the current session is
1502
+ // doing new work. Only `syncHealthTicker` — the path a late child finalizer
1503
+ // takes — stays closed in a replaced instance.
1504
+ if (healthTicker)
1505
+ return;
1506
+ healthTicker = setInterval(reconcileHealth, HEALTH_TICK_MS);
1507
+ healthTicker.unref?.(); // never keep the process alive on our account
1508
+ }
1509
+ function stopHealthTicker() {
1510
+ managedHealthClose?.();
1511
+ managedHealthClose = undefined;
1512
+ if (healthTicker) {
1513
+ clearInterval(healthTicker);
1514
+ healthTicker = undefined;
1515
+ }
1516
+ }
1517
+ /** Test/diagnostic seam: whether the periodic reconciliation loop is active. */
1518
+ export function isHealthTickerActive() {
1519
+ return healthTicker !== undefined || managedHealthClose !== undefined;
1520
+ }
1521
+ /**
1522
+ * Spawn-time identity probe. Production uses the OS-backed probe; extension-
1523
+ * level tests substitute a deterministic fake at this kernel boundary (never a
1524
+ * mock of a first-party module) via setIdentityProbeForTests.
1525
+ */
1526
+ let spawnIdentityProbe = realProcessProbe;
1527
+ export function setIdentityProbeForTests(probe) {
1528
+ spawnIdentityProbe = probe ?? realProcessProbe;
1529
+ }
1530
+ // ---- minimal subagent navigator (empty-editor ←, #45) --------------------
1531
+ // ---- subagent navigator (empty-editor ← list #45, live detail #46) --------
1532
+ // ---- subagent navigator (list #45, detail #46, two-press close #47) -------
1533
+ //
1534
+ // Human-facing TUI surface. Glue points, all gated on isNavigatorUiAvailable so
1535
+ // print/RPC sessions never see any of it:
1536
+ // 1. an editor wrapper that intercepts bare ← only when the editor is empty
1537
+ // and at least one non-dismissed current-parent run is running,
1538
+ // delegating everything else to the wrapped
1539
+ // editor (composition via navigator.mjs, tested with fakes);
1540
+ // 2. a focused overlay (ctx.ui.custom(..., { overlay: true })) listing the
1541
+ // #44 navigatorVisibleRuns newest first, with Enter → live detail view
1542
+ // that refreshes once per second (#46) and two-press `x` Close (#47).
1543
+ // Detail + close-arm timers dispose on back, Escape, overlay close,
1544
+ // selection change, list↔detail return, and session_shutdown.
1545
+ let unregisterSubagentProvider;
1546
+ let acceptanceProviderRef;
1547
+ let acceptanceSpawnToolRef;
1548
+ let acceptanceStopToolRef;
1549
+ let mainAgentStartedAt;
1550
+ const mainAgentTools = new Map();
1551
+ /**
1552
+ * Observe health for a navigator row/detail (#69). Reuses the size/mtime-gated
1553
+ * log cache so the overlay refresh does not reparse every complete log on each
1554
+ * paint. Passes effective/display status so detail
1555
+ * liveness matches the status line for legacy dead-running metadata.
1556
+ * Best-effort; never throws into the TUI.
1557
+ */
1558
+ function observeNavigatorHealth(meta, now = Date.now()) {
1559
+ return observeWidgetHealth(meta, now, effectiveStatus(meta));
1560
+ }
1561
+ /** Keep expiry and formatting on one observation, only for this refresh. */
1562
+ function createNavigatorProjector() {
1563
+ const project = createAssignmentProjector();
1564
+ const results = new Map();
1565
+ return (meta, status = meta.status) => {
1566
+ if (!results.has(meta.id))
1567
+ results.set(meta.id, project(meta, status));
1568
+ return results.get(meta.id);
1569
+ };
1570
+ }
1571
+ /** Runs that should advertise/open the left-arrow navigator affordance. */
1572
+ function navigatorRunningRuns() {
1573
+ const project = createAssignmentProjector();
1574
+ return sessionVisibleNavigatorRuns(Date.now(), project).filter((m) => ["running", "waiting"].includes(project(m, effectiveStatus(m)).state));
1575
+ }
1576
+ const pendingNavigatorDismissals = new Set();
1577
+ function navigatorRunningCount() {
1578
+ const snapshot = workObservation();
1579
+ return (snapshot?.rows.filter((row) => !pendingNavigatorDismissals.has(row.meta.id) && !row.meta.dismissedAt && ["running", "waiting"].includes(row.assignment.state)).length ?? 0) +
1580
+ (workObservationStarted() && snapshot?.status !== "ready" ? 1 : 0);
1581
+ }
1582
+ /**
1583
+ * The visible run set. The durable origin index limits reads to this session;
1584
+ * each rebuild still reads owned non-terminal metadata so external status
1585
+ * changes are visible immediately without a time-based memo.
1586
+ */
1587
+ function sessionVisibleNavigatorRuns(now = Date.now(), project = createAssignmentProjector()) {
1588
+ const origin = activeCallbackOrigin;
1589
+ if (!origin)
1590
+ return [];
1591
+ return navigatorVisibleRuns(listMetasForOrigin(origin))
1592
+ .filter(belongsToActiveNavigatorSession)
1593
+ .filter((m) => !isExpiredTerminalNavigatorRun(m, now, project));
1594
+ }
1595
+ function isExpiredTerminalNavigatorRun(meta, now, project = createAssignmentProjector()) {
1596
+ const status = project(meta, effectiveStatus(meta)).state;
1597
+ if (!isTerminalNavigatorStatus(status))
1598
+ return false;
1599
+ const endedAt = meta.endedAt ?? meta.lostAt;
1600
+ return typeof endedAt === "number" && now - endedAt >= TERMINAL_NAVIGATOR_RETENTION_MS;
1601
+ }
1602
+ function isTerminalNavigatorStatus(status) {
1603
+ return status !== "running" && status !== "waiting" && status !== "orphaned";
1604
+ }
1605
+ /** Live detail snapshot for one run (registry + log parse + health). */
1606
+ function navigatorDetail(id, now = Date.now()) {
1607
+ return buildNavigatorDetail(id, {
1608
+ readMeta,
1609
+ effectiveStatus,
1610
+ parseRun,
1611
+ shortModel,
1612
+ fmtElapsed,
1613
+ fmtSpend,
1614
+ now,
1615
+ effortFor: (m) => m.effort,
1616
+ healthFor: (m) => observeNavigatorHealth(m, now),
1617
+ });
1618
+ }
1619
+ /**
1620
+ * Set by the active extension instance: cancel a parked assignment's pending
1621
+ * wait. Returns false when the run is not parked, so the ordinary stop path runs.
1622
+ */
1623
+ let cancelParkedForUi;
1624
+ /** Shared #44 stop+dismiss path used by navigator Close (#47). */
1625
+ function navigatorCloseRun(id) {
1626
+ // A parked attempt's child already exited cleanly, so "close" must cancel the
1627
+ // pending automatic resume instead of pretending to stop a live process.
1628
+ if (parkedWaitForRun(id) && cancelParkedForUi) {
1629
+ void cancelParkedForUi(id, "closed from the navigator; the automatic resume is cancelled")
1630
+ .then((cancelled) => {
1631
+ if (!cancelled)
1632
+ throw new Error("The pending wait changed; inspect it again.");
1633
+ dismissRun(id);
1634
+ pendingNavigatorDismissals.add(id);
1635
+ refreshBackgroundWorkNavigator(uiCtx);
1636
+ uiCtx?.ui.notify(`Cancelled the pending wait of ${id}. Writer termination may remain unproven.`, "info");
1637
+ })
1638
+ .catch((error) => uiCtx?.ui.notify(`Cancellation failed for ${id}: ${String(error)}. The wait remains available for inspection and retry.`, "warning"));
1639
+ // The synchronous navigator must retain the row until the durable operation settles.
1640
+ return { action: "missing", id };
1641
+ }
1642
+ const outcome = executeNavigatorClose(id, {
1643
+ readMeta,
1644
+ effectiveStatus,
1645
+ stopRun,
1646
+ dismissRun,
1647
+ });
1648
+ if (outcome.action === "dismissed" || outcome.action === "stopped-and-dismissed")
1649
+ pendingNavigatorDismissals.add(id);
1650
+ // A closed row is off the hot path: release its caches and retained events.
1651
+ spendCache.delete(id);
1652
+ healthLogCache.delete(id);
1653
+ resetChildEventLogCursor(id);
1654
+ resetParseRunCursor(id);
1655
+ syncHealthTicker();
1656
+ // Close stops (or log-finalizes) the run, which is a terminal transition:
1657
+ // queue its one completion callback so no terminal state is silent (#624).
1658
+ // enqueueCompletionCallback is a no-op for runs that owe no callback.
1659
+ if (healthPi)
1660
+ enqueueCompletionCallback(healthPi, id);
1661
+ return outcome;
1662
+ }
1663
+ function statusTone(status) {
1664
+ switch (status) {
1665
+ case "running": return "running";
1666
+ case "completed": return "success";
1667
+ case "failed":
1668
+ case "lost": return "failed";
1669
+ case "held":
1670
+ case "waiting":
1671
+ case "cancelled":
1672
+ case "killed":
1673
+ case "orphaned": return "warning";
1674
+ default: return "muted";
1675
+ }
1676
+ }
1677
+ function subagentWorkRows(now) {
1678
+ const snapshot = workObservation();
1679
+ const sourceRows = snapshot?.rows ?? [];
1680
+ if (snapshot?.status === "ready" && pendingNavigatorDismissals.size) {
1681
+ // A successful local dismissal is already durable; hide its old observation until acknowledged.
1682
+ const undismissed = new Set(sourceRows.filter((row) => !row.meta.dismissedAt).map((row) => row.meta.id));
1683
+ for (const id of pendingNavigatorDismissals)
1684
+ if (!undismissed.has(id))
1685
+ pendingNavigatorDismissals.delete(id);
1686
+ }
1687
+ const rows = sourceRows.filter((row) => !pendingNavigatorDismissals.has(row.meta.id) && !row.meta.dismissedAt).map((row) => {
1688
+ const meta = row.meta;
1689
+ const health = row.health ? observeRunHealth({ ...row.health, status: row.assignment.processStatus === "exited" ? meta.status : row.assignment.processStatus, now, startedAt: meta.startedAt }) : undefined;
1690
+ const terminal = !["running", "waiting"].includes(row.assignment.state);
1691
+ return { providerId: "subagents", id: meta.id, agentId: meta.sessionId ?? meta.id, name: meta.name || meta.id,
1692
+ model: shortModel(meta.model), effort: meta.effort, status: row.assignment.state,
1693
+ tool: row.display?.tool, tokens: row.display?.spend,
1694
+ statusTone: statusTone(row.assignment.state), kind: "subagent", elapsed: fmtElapsed((meta.endedAt ?? now) - meta.startedAt),
1695
+ primary: [shortModel(meta.model), meta.effort, row.display?.tool, row.display?.spend].filter(Boolean).join(" ") || "subagent run", facts: formatNavigatorHealthFacts(health), sortStartedAt: meta.startedAt,
1696
+ expiresAt: terminal && typeof meta.endedAt === "number" ? meta.endedAt + TERMINAL_NAVIGATOR_RETENTION_MS : undefined };
1697
+ });
1698
+ if (workObservationStarted() && snapshot?.status !== "ready")
1699
+ rows.unshift({ providerId: "subagents", id: "runtime-observation", name: "Status sync",
1700
+ status: snapshot?.status ?? "degraded", statusTone: "warning", kind: "observation", readOnly: true, elapsed: "", primary: "Task status unconfirmed · enter for details", sortStartedAt: now });
1701
+ return rows;
1702
+ }
1703
+ const DELEGATION_BLURB = {
1704
+ manual: "only when you or a workflow asks",
1705
+ adaptive: "substantial independent work",
1706
+ coordinator: "every role-owned task",
1707
+ };
1708
+ let readDelegation = () => ({ mode: "adaptive", source: "config" });
1709
+ let cycleDelegation = () => { };
1710
+ let saveDelegationDefault = () => ({ ok: false, message: "Saving the delegation default is unavailable." });
1711
+ function mainAgentWorkRow(now) {
1712
+ let running = mainAgentStartedAt !== undefined;
1713
+ try {
1714
+ running ||= uiCtx?.isIdle() === false;
1715
+ }
1716
+ catch { /* use event state */ }
1717
+ const model = shortModel(uiCtx?.model?.id);
1718
+ const effort = uiCtx?.thinkingLevel;
1719
+ const tool = [...mainAgentTools.values()].at(-1);
1720
+ let contextTokens;
1721
+ try {
1722
+ contextTokens = uiCtx?.getContextUsage()?.tokens;
1723
+ }
1724
+ catch {
1725
+ contextTokens = undefined;
1726
+ }
1727
+ const tokens = typeof contextTokens === "number" ? `${fmtTokens(contextTokens)} tok` : undefined;
1728
+ const delegation = readDelegation();
1729
+ const bits = [
1730
+ effort ? `${model} ${effort}` : model,
1731
+ tool,
1732
+ tokens,
1733
+ delegation.source === "session" ? `${delegation.mode} · session` : delegation.mode,
1734
+ ].filter((bit) => Boolean(bit));
1735
+ return {
1736
+ providerId: "subagents",
1737
+ id: "main",
1738
+ name: "main",
1739
+ model,
1740
+ effort,
1741
+ tool,
1742
+ tokens,
1743
+ status: running ? "running" : "idle",
1744
+ statusTone: running ? "running" : "muted",
1745
+ kind: "main agent",
1746
+ elapsed: running && mainAgentStartedAt !== undefined ? fmtElapsed(now - mainAgentStartedAt) : "idle",
1747
+ primary: bits.join(" · "),
1748
+ sortStartedAt: mainAgentStartedAt ?? now,
1749
+ };
1750
+ }
1751
+ function mainAgentWorkDetail(now) {
1752
+ const row = mainAgentWorkRow(now);
1753
+ const delegation = readDelegation();
1754
+ return {
1755
+ providerId: "subagents",
1756
+ id: "main",
1757
+ title: "main",
1758
+ status: row.status,
1759
+ statusTone: row.statusTone,
1760
+ subtitle: row.primary,
1761
+ metadata: [
1762
+ { label: "kind", value: "main agent" },
1763
+ { label: "model", value: row.effort ? `${row.model} · effort ${row.effort}` : (row.model || "-") },
1764
+ { label: "tool", value: row.tool || "-" },
1765
+ { label: "context", value: row.tokens || "-" },
1766
+ { label: "elapsed", value: row.elapsed },
1767
+ { label: "mode", value: `${delegation.mode} · ${delegation.source}` },
1768
+ ],
1769
+ evidence: {
1770
+ label: "delegation",
1771
+ text: [
1772
+ `${delegation.mode}: ${DELEGATION_BLURB[delegation.mode]}.`,
1773
+ "m cycles this session. ctrl+s saves that mode as the next session's default.",
1774
+ "x does not stop the main agent.",
1775
+ ].filter(Boolean).join(" "),
1776
+ },
1777
+ footerActions: ["m mode", "ctrl+s save"],
1778
+ };
1779
+ }
1780
+ function subagentWorkDetail(id, now, options) {
1781
+ if (id === "main")
1782
+ return mainAgentWorkDetail(now);
1783
+ if (id === "runtime-observation")
1784
+ return {
1785
+ providerId: "subagents", id, title: "Subagent status sync", status: workObservation()?.status ?? "rebuilding", statusTone: "warning",
1786
+ subtitle: "Shared status service · task status unconfirmed",
1787
+ metadata: [{ label: "scope", value: "Subagent status reads; not an individual task" }],
1788
+ evidence: { label: "Full diagnostic", text: workObservationFailure() },
1789
+ footerActions: [],
1790
+ };
1791
+ const row = requestWorkDetail(id);
1792
+ if (!row?.detail)
1793
+ return { providerId: "subagents", id, title: id, status: row?.observationError ? "degraded" : "rebuilding", statusTone: "warning", metadata: [], evidence: { label: "observation", text: row?.observationError ?? workObservationFailure() } };
1794
+ const health = row.health ? observeRunHealth({ ...row.health, status: row.assignment.processStatus === "exited" ? row.meta.status : row.assignment.processStatus, now, startedAt: row.meta.startedAt }) : undefined;
1795
+ const detail = withAssignmentObservations([row], () => buildNavigatorDetail(id, {
1796
+ readMeta: () => row.meta, effectiveStatus: () => row.assignment.processStatus, parseRun: () => row.detail.parsed,
1797
+ shortModel, fmtElapsed, fmtSpend, now, effortFor: (meta) => meta.effort, healthFor: () => health,
1798
+ }));
1799
+ if (!detail)
1800
+ return null;
1801
+ void options;
1802
+ const transcript = row.detail.transcript;
1803
+ const metadata = [
1804
+ { label: "provider", value: "Subagents" },
1805
+ ...(row.observationError ? [{ label: "observation", value: row.observationError }] : []),
1806
+ { label: "id", value: detail.id },
1807
+ ...(detail.role ? [{ label: "role", value: String(detail.role) }] : []),
1808
+ { label: "model", value: detail.effort ? `${detail.model} · effort ${detail.effort}` : detail.model },
1809
+ ...(detail.assignment ? [
1810
+ { label: "revision", value: detail.assignment.revision },
1811
+ { label: "reason", value: detail.assignment.reason },
1812
+ { label: "process", value: `${detail.assignment.processStatus}; termination ${detail.assignment.termination}` },
1813
+ { label: "evidence", value: detail.assignment.evidence.join(", ") },
1814
+ ] : []),
1815
+ { label: "elapsed", value: detail.elapsed },
1816
+ { label: "tools", value: detail.currentTool ? `current ${detail.currentTool}` : (detail.tools || "(none)") },
1817
+ { label: "spend", value: detail.spend || "(none)" },
1818
+ ...(detail.park ? [
1819
+ { label: "wait", value: `${detail.park.waitId} generation ${detail.park.generation}` },
1820
+ ] : []),
1821
+ { label: "pid", value: detail.pid != null ? String(detail.pid) : "-" },
1822
+ { label: "pgid", value: detail.pgid != null ? String(detail.pgid) : "-" },
1823
+ ];
1824
+ return {
1825
+ providerId: "subagents",
1826
+ id: detail.id,
1827
+ title: detail.name || detail.id,
1828
+ status: detail.status,
1829
+ statusTone: statusTone(detail.status),
1830
+ subtitle: detail.currentTool || undefined,
1831
+ metadata,
1832
+ evidence: { label: "transcript", text: detail.output || "(no transcript yet)" },
1833
+ transcript: transcript.entries,
1834
+ transcriptDiagnostic: transcript.diagnostic,
1835
+ footerActions: [detail.park ? "x cancel resume" : detail.attemptStatus === "running" || detail.attemptStatus === "orphaned" ? "x stop" : "x dismiss"],
1836
+ };
1837
+ }
1838
+ function createSubagentTranscriptComponent(detail, theme) {
1839
+ const ContainerComponent = PiTui.Container;
1840
+ const AssistantComponent = PiCodingAgent.AssistantMessageComponent;
1841
+ const ToolComponent = PiCodingAgent.ToolExecutionComponent;
1842
+ const markdownTheme = typeof PiCodingAgent.getMarkdownTheme === "function"
1843
+ ? PiCodingAgent.getMarkdownTheme()
1844
+ : {};
1845
+ if (!ContainerComponent || !AssistantComponent || !ToolComponent) {
1846
+ return {
1847
+ render: () => (detail.transcript ?? []).flatMap((entry) => entry.type === "assistant"
1848
+ ? entry.content.filter((block) => block.type === "text").flatMap((block) => String(block.text ?? "").split("\n"))
1849
+ : [`[${entry.state}] ${entry.name}`]),
1850
+ invalidate() { },
1851
+ };
1852
+ }
1853
+ const container = new ContainerComponent();
1854
+ const ui = { requestRender: () => { try {
1855
+ uiCtx?.ui?.requestRender?.();
1856
+ }
1857
+ catch { /* ignore */ } } };
1858
+ for (const entry of detail.transcript ?? []) {
1859
+ if (entry.type === "assistant") {
1860
+ const message = {
1861
+ role: "assistant",
1862
+ content: entry.content,
1863
+ stopReason: entry.streaming ? undefined : "stop",
1864
+ timestamp: Date.now(),
1865
+ };
1866
+ const component = new AssistantComponent(message, true, markdownTheme, "Thinking...", 1);
1867
+ component.updateContent(message, entry.streaming);
1868
+ container.addChild(component);
1869
+ continue;
1870
+ }
1871
+ const component = new ToolComponent(entry.name, entry.id ?? `transcript-${entry.name}`, entry.args ?? {}, { showImages: false }, undefined, ui, uiCtx?.cwd ?? process.cwd());
1872
+ component.markExecutionStarted();
1873
+ component.setArgsComplete();
1874
+ if (entry.state === "completed") {
1875
+ const result = entry.result && typeof entry.result === "object"
1876
+ ? entry.result
1877
+ : { content: entry.result == null ? [] : [{ type: "text", text: String(entry.result) }] };
1878
+ component.updateResult({ ...result, isError: entry.isError });
1879
+ }
1880
+ container.addChild(component);
1881
+ }
1882
+ return container;
1883
+ }
1884
+ function ensureSubagentProvider() {
1885
+ if (unregisterSubagentProvider)
1886
+ return;
1887
+ const provider = {
1888
+ id: "subagents",
1889
+ label: "Subagents",
1890
+ priority: 10,
1891
+ onOpen: () => { void activateWorkObservation(); },
1892
+ visibleCount: () => navigatorRunningCount(),
1893
+ // The last worker becoming terminal must not hide its retained result.
1894
+ showSection: (rows) => rows.length > 0,
1895
+ parentRow: (now) => mainAgentWorkRow(now),
1896
+ listRows: (now) => subagentWorkRows(now),
1897
+ detail: (id, now, options) => subagentWorkDetail(id, now, options),
1898
+ handleDetailInput: (id, data) => {
1899
+ if (id !== "main")
1900
+ return false;
1901
+ if (data === "m") {
1902
+ cycleDelegation();
1903
+ return true;
1904
+ }
1905
+ if (data !== "ctrl+s")
1906
+ return false;
1907
+ saveDelegationDefault(readDelegation().mode);
1908
+ return true;
1909
+ },
1910
+ armCloseLabel: (row) => pendingNavigatorPark(workObservation()?.rows.find((observed) => observed.meta.id === row.id)?.meta) ? "x again to cancel resume" : row.status === "running" || row.status === "orphaned" ? "x again to stop" : "x again to dismiss",
1911
+ close: (id) => {
1912
+ if (id === "runtime-observation")
1913
+ return { action: "not-closable", providerId: "subagents", id };
1914
+ const outcome = navigatorCloseRun(id);
1915
+ return { ...outcome, providerId: "subagents" };
1916
+ },
1917
+ onVisibleChanged: onMetaChanged,
1918
+ };
1919
+ acceptanceProviderRef = provider;
1920
+ unregisterSubagentProvider = registerBackgroundWorkProvider(provider);
1921
+ }
1922
+ function selectedWidgetNavRun() {
1923
+ const running = navigatorRunningRuns();
1924
+ syncWidgetNavSelection(running);
1925
+ return running.find((m) => m.id === widgetNavSelectedId);
1926
+ }
1927
+ function enterWidgetNav(ctx) {
1928
+ if (!isNavigatorUiAvailable(ctx))
1929
+ return;
1930
+ const running = navigatorRunningRuns();
1931
+ if (running.length === 0)
1932
+ return;
1933
+ widgetNavActive = true;
1934
+ widgetNavSelectedId = running[running.length - 1]?.id;
1935
+ try {
1936
+ renderWidget();
1937
+ }
1938
+ catch { /* ignore */ }
1939
+ }
1940
+ function exitWidgetNav() {
1941
+ if (!widgetNavActive)
1942
+ return;
1943
+ widgetNavActive = false;
1944
+ widgetNavSelectedId = undefined;
1945
+ try {
1946
+ renderWidget();
1947
+ }
1948
+ catch { /* ignore */ }
1949
+ }
1950
+ function moveWidgetNavPrevious() {
1951
+ const running = navigatorRunningRuns();
1952
+ syncWidgetNavSelection(running);
1953
+ const idx = running.findIndex((m) => m.id === widgetNavSelectedId);
1954
+ if (idx > 0)
1955
+ widgetNavSelectedId = running[idx - 1]?.id;
1956
+ try {
1957
+ renderWidget();
1958
+ }
1959
+ catch { /* ignore */ }
1960
+ }
1961
+ function returnWidgetNavToInput() {
1962
+ const running = navigatorRunningRuns();
1963
+ syncWidgetNavSelection(running);
1964
+ const idx = running.findIndex((m) => m.id === widgetNavSelectedId);
1965
+ if (idx >= 0 && idx < running.length - 1) {
1966
+ widgetNavSelectedId = running[idx + 1]?.id;
1967
+ try {
1968
+ renderWidget();
1969
+ }
1970
+ catch { /* ignore */ }
1971
+ return;
1972
+ }
1973
+ exitWidgetNav();
1974
+ }
1975
+ function viewWidgetNavSelection(ctx, owner) {
1976
+ const selected = selectedWidgetNavRun();
1977
+ if (!selected)
1978
+ return;
1979
+ openNavigator(ctx, selected.id, owner);
1980
+ }
1981
+ function stopWidgetNavSelection(ctx) {
1982
+ const selected = selectedWidgetNavRun();
1983
+ if (!selected)
1984
+ return;
1985
+ try {
1986
+ navigatorCloseRun(selected.id);
1987
+ }
1988
+ catch { /* ignore */ }
1989
+ updateNavigatorFooter(ctx);
1990
+ try {
1991
+ renderWidget();
1992
+ }
1993
+ catch { /* ignore */ }
1994
+ }
1995
+ /** Open the focused navigator overlay. No-op without a UI or visible runs. */
1996
+ function openNavigator(ctx, initialDetailId, owner) {
1997
+ void initialDetailId;
1998
+ ensureNavigator(ctx, owner);
1999
+ }
2000
+ /** Refresh the shared navigator after run changes. */
2001
+ function updateNavigatorFooter(ctx) {
2002
+ refreshBackgroundWorkNavigator(ctx);
2003
+ }
2004
+ /** Install the empty-editor ← wrapper once per UI (reload-safe, composable). */
2005
+ function ensureNavigator(ctx, owner) {
2006
+ if (!isNavigatorUiAvailable(ctx))
2007
+ return;
2008
+ try {
2009
+ ensureSubagentProvider();
2010
+ ensureBackgroundWorkNavigator(ctx, {
2011
+ createDefaultEditor: (tui, theme, keybindings) => new CustomEditor(tui, theme, keybindings),
2012
+ isOpenTrigger: (data) => matchesKey(data, Key.left),
2013
+ matchKey: (data, keyId) => matchesKey(data, keyId),
2014
+ truncate: truncateToWidth,
2015
+ createTranscriptComponent: createSubagentTranscriptComponent,
2016
+ }, owner);
2017
+ }
2018
+ catch { /* ignore */ }
2019
+ }
2020
+ /** Resolve the pi binary once per session. */
2021
+ let cachedPi;
2022
+ function resolvePiBinary() {
2023
+ if (cachedPi !== undefined)
2024
+ return cachedPi;
2025
+ try {
2026
+ cachedPi = execSync("which pi", { encoding: "utf-8", timeout: 3000 }).trim();
2027
+ }
2028
+ catch {
2029
+ cachedPi = "pi";
2030
+ }
2031
+ return cachedPi;
2032
+ }
2033
+ /**
2034
+ * Finalize a run once its child exits. Host-facing wrapper around the
2035
+ * first-party finalizer (finalization.ts) so tests can exercise the durable
2036
+ * path without importing the pi package.
2037
+ */
2038
+ function finalizeRun(pi, ctx, id, code) {
2039
+ progressCache.delete(id);
2040
+ directlySupervisedRunIds.delete(id);
2041
+ // Host-facing wrapper around first-party finalizer (finalization.ts).
2042
+ // Coherent child-exit evidence may supersede provisional orphaned/lost
2043
+ // reconciliation; finalization.ts enforces canExitFinalize + lifecycle authority.
2044
+ finalizeRunCore(id, code, {
2045
+ renderWidget,
2046
+ notify: (message, level) => {
2047
+ try {
2048
+ ctx?.ui.notify(message, level);
2049
+ }
2050
+ catch { /* ignore */ }
2051
+ },
2052
+ sendMessage: () => enqueueCompletionCallback(pi, id),
2053
+ });
2054
+ syncHealthTicker();
2055
+ }
2056
+ /**
2057
+ * Finalize a run whose supervision a previous session interrupted (`/reload`,
2058
+ * a session switch, or a quit) once its process evidence is gone (#625).
2059
+ *
2060
+ * The instance that held the in-memory exit observer is gone, so nothing else
2061
+ * reads the child's own log when the process disappears: health reconciliation
2062
+ * alone would record an interrupted-but-finished run `lost`, hiding a result
2063
+ * that is fully on disk. Only coherent terminal stream evidence is accepted
2064
+ * (`agent_end` with every tool call closed); anything else keeps the existing
2065
+ * reconciliation verdict, so no failure or completion is manufactured.
2066
+ *
2067
+ * Runs this instance launched are skipped: their exit observer finalizes them.
2068
+ */
2069
+ function finalizeInterruptedRunFromLog(pi, meta, now) {
2070
+ if (!pi)
2071
+ return false;
2072
+ if (directlySupervisedRunIds.has(meta.id))
2073
+ return false;
2074
+ if (meta.supervisionInterruptedAt === undefined)
2075
+ return false;
2076
+ // Process evidence still exists: the child keeps running, nothing to finalize.
2077
+ if (reconcileRun(meta, realProcessProbe, now).status !== "lost")
2078
+ return false;
2079
+ let run;
2080
+ try {
2081
+ run = parseRunForLifecycle(meta.id);
2082
+ }
2083
+ catch {
2084
+ return false;
2085
+ }
2086
+ if (!run.sawEnd || run.unmatchedToolCalls.length > 0)
2087
+ return false;
2088
+ // Exit code is unknown after the observer is gone; the lifecycle authority
2089
+ // classifies from the coherent stream instead of inventing one.
2090
+ finalizeRun(pi, uiCtx, meta.id, null);
2091
+ return true;
2092
+ }
2093
+ /**
2094
+ * Does this process have to supervise this explicit interruption record (#625)?
2095
+ *
2096
+ * A run this parent launched is this session's own (#625 reload). A run left by
2097
+ * a parent that is provably gone has no live owner at all — the restart case —
2098
+ * so its recorded interruption is the only thing that can recover it. Anything
2099
+ * else belongs to a live pi and is never adjudicated here.
2100
+ */
2101
+ function ownsInterruptedSupervision(summary) {
2102
+ if (summary.management)
2103
+ return Boolean(managementPort?.owns(summary));
2104
+ if (summary.supervisionInterruptedAt === undefined)
2105
+ return false;
2106
+ return ownedByThisParent(summary) || isAbandonedByParent(summary, realProcessProbe);
2107
+ }
2108
+ /** True while an interrupted record still needs this process's supervision loop. */
2109
+ function needsInterruptedSupervision() {
2110
+ try {
2111
+ for (const summary of listMetas({ includeArchived: false })) {
2112
+ if (summary.status !== "running" && summary.status !== "orphaned")
2113
+ continue;
2114
+ if (ownsInterruptedSupervision(summary))
2115
+ return true;
2116
+ }
2117
+ }
2118
+ catch { /* best-effort scheduler gate */ }
2119
+ return false;
2120
+ }
2121
+ /**
2122
+ * Attempt log-evidence finalization for every interrupted run this process has
2123
+ * to supervise: its own current-parent ones and the ones a dead parent left
2124
+ * behind. Live children are never finalized (`finalizeInterruptedRunFromLog`
2125
+ * requires the process evidence to be gone), so this only recovers a child that
2126
+ * already finished on its own.
2127
+ */
2128
+ function recoverInterruptedSubagents(pi) {
2129
+ let recovered = 0;
2130
+ const now = Date.now();
2131
+ for (const summary of listMetas()) {
2132
+ if (summary.status !== "running" && summary.status !== "orphaned")
2133
+ continue;
2134
+ if (!ownsInterruptedSupervision(summary))
2135
+ continue;
2136
+ const meta = readMeta(summary.id);
2137
+ if (!meta || (meta.status !== "running" && meta.status !== "orphaned"))
2138
+ continue;
2139
+ try {
2140
+ if (finalizeInterruptedRunFromLog(pi, meta, now))
2141
+ recovered += 1;
2142
+ }
2143
+ catch { /* best-effort at session start; the health ticker retries */ }
2144
+ }
2145
+ return recovered;
2146
+ }
2147
+ /**
2148
+ * Re-prove a continuation's native history identity after its writer lease is held.
2149
+ *
2150
+ * `planContinuation` validated the saved conversation, but it validated a plan:
2151
+ * between that read and admission another process's sweep can retire the shared
2152
+ * workspace, the saved history, or the prior run record, and Pi's `--session`
2153
+ * opens a missing path by creating a fresh conversation — a silent replacement
2154
+ * instead of a refusal. Cleanup now takes the same per-conversation lock this
2155
+ * admission takes, so re-reading here is reading a conversation nothing else can
2156
+ * retire concurrently. Any change since validation refuses; the cached path is
2157
+ * never reopened on the strength of the earlier check.
2158
+ */
2159
+ function revalidateContinuationUnderLease(plan, origin) {
2160
+ const current = readMeta(plan.prior.id);
2161
+ if (!current) {
2162
+ throw new ContinuationError(`Cannot continue ${plan.prior.id}: its run record was removed while this launch was being prepared. ` +
2163
+ `Its saved history is missing; restore the original history or launch a new run instead.`);
2164
+ }
2165
+ const fresh = planContinuation({
2166
+ id: plan.prior.id,
2167
+ prior: current,
2168
+ origin,
2169
+ // Archived attempts are completed and cannot be competing writers.
2170
+ others: listMetas({ includeArchived: false }),
2171
+ });
2172
+ if (fresh.conversation.sessionId !== plan.conversation.sessionId || fresh.conversation.path !== plan.conversation.path) {
2173
+ throw new ContinuationError(`Cannot continue ${plan.prior.id}: the saved conversation it would reopen changed while this launch was being prepared ` +
2174
+ `(${plan.conversation.path} -> ${fresh.conversation.path}). Launch a new run instead.`);
2175
+ }
2176
+ }
2177
+ /**
2178
+ * The removed launch flag, reported by name so an older caller is told what to
2179
+ * do instead of having its request silently dropped.
2180
+ */
2181
+ const RETAIN_SESSION_REMOVED = "retain_session was removed: every saved conversation persists automatically. " +
2182
+ "Omit it, and pass session_id to continue a saved conversation.";
2183
+ function assertNoRetiredLaunchOptions(value, label = "") {
2184
+ if (value && value.retain_session !== undefined) {
2185
+ throw new Error(`${label}${RETAIN_SESSION_REMOVED}`);
2186
+ }
2187
+ }
2188
+ function sameLaunchPath(left, right) {
2189
+ if (typeof left !== "string" || right === undefined)
2190
+ return false;
2191
+ if (left === right)
2192
+ return true;
2193
+ try {
2194
+ return canonicalizePath(left) === canonicalizePath(right);
2195
+ }
2196
+ catch {
2197
+ return false;
2198
+ }
2199
+ }
2200
+ /** Reporting is injected by the supervisor, not part of the caller's tool intent.
2201
+ * Older recipes included it; remove only this internal name when reading them. */
2202
+ function callerLaunchTools(tools) {
2203
+ return normalizeTools(tools).split(",").filter((name) => name !== "report_assignment_result").join(",");
2204
+ }
2205
+ function sameLaunchTools(left, right) {
2206
+ return typeof left === "string" && callerLaunchTools(left) === callerLaunchTools(right);
2207
+ }
2208
+ /**
2209
+ * A continuation may repeat its launch's skill exposure, and only that. The
2210
+ * saved paths are absolute (frozen at launch), so a caller repeating relative
2211
+ * paths is compared against the recipe's own workspace.
2212
+ *
2213
+ * Discovery and `[]` are different choices and must never compare equal: a
2214
+ * recipe with no `skills` key means "the child discovers the user catalog", and
2215
+ * an explicit `[]` means "load no skills at all". Treating an absent key as an
2216
+ * empty list would accept a continuation that silently disables discovery for a
2217
+ * conversation that was launched with it.
2218
+ */
2219
+ function sameLaunchSkills(value, recipe) {
2220
+ let requested;
2221
+ try {
2222
+ requested = normalizeSkillExposure(value, "skills");
2223
+ }
2224
+ catch {
2225
+ return false;
2226
+ }
2227
+ if (requested === undefined)
2228
+ return false;
2229
+ const saved = recipe.skills;
2230
+ if (saved === undefined)
2231
+ return false;
2232
+ const resolved = requested.length === 0 ? [] : absolutizeSkillPaths(requested, recipe.cwd);
2233
+ return resolved.length === saved.length && resolved.every((path, index) => path === saved[index]);
2234
+ }
2235
+ function sameLaunchRoles(left, right) {
2236
+ if (typeof left === "string")
2237
+ return left === right;
2238
+ if (Array.isArray(left) && Array.isArray(right)) {
2239
+ return left.length === right.length && left.every((value, index) => value === right[index]);
2240
+ }
2241
+ return false;
2242
+ }
2243
+ function continuationLaunchConflicts(job, recipe, options) {
2244
+ const conflicts = [];
2245
+ const check = (key, same) => {
2246
+ const value = job[key];
2247
+ if (value !== undefined && !same(value))
2248
+ conflicts.push(key);
2249
+ };
2250
+ if (options.includeName)
2251
+ check("name", (value) => value === recipe.name);
2252
+ check("agent", (value) => value === recipe.agent);
2253
+ check("role", (value) => sameLaunchRoles(value, recipe.role));
2254
+ check("alias", (value) => value === recipe.alias);
2255
+ check("tools", (value) => sameLaunchTools(value, recipe.tools));
2256
+ check("exclude_tools", (value) => typeof value === "string" && normalizeTools(value) === normalizeTools(recipe.excludeTools ?? ""));
2257
+ check("skills", (value) => sameLaunchSkills(value, recipe));
2258
+ check("clean", (value) => value === recipe.clean);
2259
+ check("sandbox", (value) => value === recipe.sandbox);
2260
+ check("sandbox_dir", (value) => sameLaunchPath(value, recipe.sandboxDir));
2261
+ check("cwd", (value) => sameLaunchPath(value, recipe.cwd));
2262
+ check("git_clone_workspace", (value) => value === recipe.gitCloneWorkspace);
2263
+ check("approve", (value) => value === recipe.approve);
2264
+ check("allow_nested", (value) => value === recipe.allowNested);
2265
+ return conflicts;
2266
+ }
2267
+ /**
2268
+ * Refuse any launch-only option that does not reproduce the saved recipe.
2269
+ * Matching values are allowed (a caller that repeats its original launch call is
2270
+ * provably asking for the same thing); a missing option just keeps the recipe.
2271
+ */
2272
+ function assertContinuationLaunchOptions(job, recipe, label, options = { includeName: true }) {
2273
+ if (job.retain_session !== undefined)
2274
+ throw new ContinuationError(`${label}${RETAIN_SESSION_REMOVED}`);
2275
+ const conflicts = continuationLaunchConflicts(job, recipe, options);
2276
+ if (conflicts.length === 0)
2277
+ return;
2278
+ const named = conflicts.map((key) => `\`${key}\``).join(", ");
2279
+ const prefix = label || "Cannot continue this saved conversation: ";
2280
+ throw new ContinuationError(`${prefix}${named} ${conflicts.length === 1 ? "conflicts" : "conflict"} with the saved launch recipe. ` +
2281
+ `A continued conversation keeps the recipe it was launched with; omit ${conflicts.length === 1 ? "it" : "them"}. ` +
2282
+ `A continuation accepts prompt, session_id, and optional model, thinking, callback, and timing overrides.`);
2283
+ }
2284
+ /**
2285
+ * The attempt that currently owns a saved conversation: the LATEST attempt by
2286
+ * `startedAt` (then id, so ties stay deterministic). Never pick an older
2287
+ * completed sibling: that would branch history from a superseded attempt.
2288
+ */
2289
+ function latestConversationAttempt(sessionId, metas) {
2290
+ let latest;
2291
+ for (const meta of metas) {
2292
+ if (meta.sessionId !== sessionId)
2293
+ continue;
2294
+ if (!latest || meta.startedAt > latest.startedAt
2295
+ || (meta.startedAt === latest.startedAt && meta.id > latest.id))
2296
+ latest = meta;
2297
+ }
2298
+ return latest;
2299
+ }
2300
+ /**
2301
+ * Select a saved conversation by its exact native session id and validate it for
2302
+ * one more attempt. `planContinuation` owns the refusals (a running/orphaned
2303
+ * latest attempt, missing history or workspace, unsupported recipe), so a
2304
+ * missing session is the only error added here. Nothing is ever recreated.
2305
+ */
2306
+ function requestedSessionId(job, cwd) {
2307
+ if (job.session_id !== undefined && job.session_name !== undefined) {
2308
+ throw new Error("Pass either session_id or session_name, not both.");
2309
+ }
2310
+ if (job.session_name !== undefined) {
2311
+ if (typeof job.session_name !== "string")
2312
+ throw new Error("session_name must be a non-empty name.");
2313
+ return selectSessionByName(listMetas(), job.session_name, (workspace) => isWithinWorkspace(workspace, cwd));
2314
+ }
2315
+ return job.session_id;
2316
+ }
2317
+ function continuationPlanFor(sessionId, origin) {
2318
+ const others = listMetas();
2319
+ const latest = latestConversationAttempt(sessionId, others);
2320
+ if (!latest) {
2321
+ throw new ContinuationError(`Cannot continue session ${sessionId}: no saved subagent conversation has that native session id. ` +
2322
+ `Check the session id reported by the launching attempt, or omit session_id to start a new conversation.`);
2323
+ }
2324
+ // The activity index chooses the attempt, not its frozen execution recipe.
2325
+ // Another process may have republished the authoritative record since indexing.
2326
+ const current = readMeta(latest.id);
2327
+ if (!current)
2328
+ throw new ContinuationError(`Cannot continue ${latest.id}: its saved run record is unavailable.`);
2329
+ return planContinuation({ id: latest.id, prior: current, origin, others });
2330
+ }
2331
+ function timingSchemaFields() {
2332
+ return timingParameterSchemas(Type);
2333
+ }
2334
+ /** String for one role, or an array when the caller assigns more than one. Arrays reach clarification instead of being rejected. */
2335
+ function catalogRoleSchema(purpose) {
2336
+ const one = `One role by short name (developer) for this ${purpose}; role.developer also works, case-insensitive. Mutually exclusive with agent.`;
2337
+ const many = `Two or more role names for this ${purpose}. An array is ambiguous and asks to choose one role or split into separate runs. No child launches until that choice is made.`;
2338
+ return Type.Optional(Type.Union([
2339
+ Type.String({ description: one }),
2340
+ Type.Array(Type.String({ minLength: 1 }), { minItems: 1, description: many }),
2341
+ ], { description: `${one} ${many}` }));
2342
+ }
2343
+ /** Loaded Pi skill metadata from the current prompt resources. No model call, no directory scan. */
2344
+ function discoveredSkillsFromContext(ctx) {
2345
+ try {
2346
+ const loaded = ctx.getSystemPromptOptions?.().skills ?? [];
2347
+ const skills = [];
2348
+ for (const raw of loaded) {
2349
+ if (!raw || typeof raw !== "object")
2350
+ continue;
2351
+ const skill = raw;
2352
+ if (typeof skill.name !== "string" || !skill.name || typeof skill.filePath !== "string" || !skill.filePath)
2353
+ continue;
2354
+ skills.push({
2355
+ name: skill.name,
2356
+ description: typeof skill.description === "string" ? skill.description : "",
2357
+ path: skill.filePath,
2358
+ ...(typeof skill.baseDir === "string" ? { baseDir: skill.baseDir } : {}),
2359
+ ...(typeof skill.sourceInfo?.source === "string" ? { source: skill.sourceInfo.source } : {}),
2360
+ });
2361
+ }
2362
+ return skills;
2363
+ }
2364
+ catch {
2365
+ return [];
2366
+ }
2367
+ }
2368
+ export default function (pi, managed) {
2369
+ managementPort = managed;
2370
+ // A standalone Subagents install has no Harness extension, so the parent
2371
+ // session applies the same linked-worktree project boundary as its children.
2372
+ pi.on("before_agent_start", (event) => {
2373
+ restrictContextFilesToWorktree(event.systemPromptOptions, PiCodingAgent.getAgentDir());
2374
+ });
2375
+ initializeNavigatorPanels(pi);
2376
+ // Each cached factory instance owns the navigator it installs (#460).
2377
+ const navigatorOwner = Symbol("subagents navigator factory");
2378
+ const agentSessionSettings = createAgentSessionSettings(pi);
2379
+ let catalogModelRegistry;
2380
+ let delegationOverride;
2381
+ let capOverride;
2382
+ let timingOverride = {};
2383
+ let skillsOverride;
2384
+ const savedSkills = () => {
2385
+ try {
2386
+ return configuredSkillExposure(loadConfig().defaultSkills);
2387
+ }
2388
+ catch (error) {
2389
+ return {
2390
+ mode: "inherit", paths: [], source: "config",
2391
+ error: error instanceof Error ? error.message : String(error),
2392
+ };
2393
+ }
2394
+ };
2395
+ const activeSkills = () => {
2396
+ if (skillsOverride)
2397
+ return { ...skillsOverride, source: "session" };
2398
+ return savedSkills();
2399
+ };
2400
+ /** The same active default a launch sees, shaped for catalog inspection. */
2401
+ const readSkillDefaults = () => {
2402
+ const skills = activeSkills();
2403
+ const value = skills.mode === "inherit" ? undefined : [...skills.paths];
2404
+ const error = skills.error ?? (skills.mode === "explicit" && skills.paths.length === 0
2405
+ ? "Selected skills has no paths. Add at least one skill path or choose No skill catalog."
2406
+ : undefined);
2407
+ return { value, source: skills.source, ...(error ? { error } : {}) };
2408
+ };
2409
+ const changeSkills = (mode, paths) => {
2410
+ if (mode !== "explicit" && paths.length > 0)
2411
+ throw new Error("Only Selected skills carries a path list.");
2412
+ if (mode === "explicit" && paths.some((path) => !isAbsolute(path))) {
2413
+ throw new Error("Enter absolute skill paths so every child resolves the same files.");
2414
+ }
2415
+ const next = { mode, paths: [...paths] };
2416
+ skillsOverride = next;
2417
+ pi.appendEntry("pi-better-subagents-skills", { version: 1, ...next });
2418
+ };
2419
+ /** The current-session choice, with `{}` preserving explicit discovery. */
2420
+ const sessionSkillChoice = () => {
2421
+ if (!skillsOverride)
2422
+ return undefined;
2423
+ if (skillsOverride.mode === "explicit" && skillsOverride.paths.length === 0) {
2424
+ throw new Error("Selected skills has no paths. Add at least one skill path or choose No skill catalog before launching.");
2425
+ }
2426
+ if (skillsOverride.mode === "inherit")
2427
+ return {};
2428
+ return { value: skillsOverride.mode === "none" ? [] : [...skillsOverride.paths] };
2429
+ };
2430
+ const activeConcurrencyCap = () => capOverride ?? normalizeConcurrencyCap(loadConfig().maxConcurrent);
2431
+ const timingSettingsFor = (cfg = loadConfig()) => ({ ...cfg, ...timingOverride });
2432
+ /** A per-run max_minutes wins; otherwise a session timeout choice beats the environment. */
2433
+ const launchTimingParams = (params = {}) => ({
2434
+ ...params,
2435
+ max_minutes: params.max_minutes ?? timingOverride.maxMinutes,
2436
+ });
2437
+ const timingState = () => {
2438
+ const cfg = loadConfig();
2439
+ const envFor = (key) => {
2440
+ const raw = key === "toolWaitMinutes" ? process.env[TIMING_ENV.toolWait] : process.env[TIMING_ENV.stuck];
2441
+ return raw !== undefined && raw.trim() !== "" ? raw : undefined;
2442
+ };
2443
+ const sourceFor = (key) => envFor(key) !== undefined ? "environment"
2444
+ : timingOverride[key] !== undefined ? "session"
2445
+ : cfg[key] !== undefined && cfg[key] !== null ? "config" : "default";
2446
+ const timeoutEnv = process.env[TIMING_ENV.max];
2447
+ const timeoutSource = () => timingOverride.maxMinutes !== undefined ? "session"
2448
+ : timeoutEnv !== undefined && timeoutEnv.trim() !== "" ? "environment"
2449
+ : cfg.maxMinutes !== undefined && cfg.maxMinutes !== null ? "config" : "default";
2450
+ try {
2451
+ const sessionTimeout = timingOverride.maxMinutes !== undefined ? { max_minutes: timingOverride.maxMinutes } : {};
2452
+ const effective = resolveRunTiming({ params: sessionTimeout, settings: timingSettingsFor(cfg), env: process.env, startedAt: 0 });
2453
+ const defaults = resolveRunTiming({ settings: cfg, env: process.env, startedAt: 0 });
2454
+ const minutes = (ms) => ms === undefined ? 0 : ms / 60_000;
2455
+ return {
2456
+ maxMinutes: minutes(effective.ceilingAt),
2457
+ toolWaitMinutes: minutes(effective.toolWaitMs),
2458
+ stuckMinutes: minutes(effective.stuckMs),
2459
+ timeoutSource: timeoutSource(),
2460
+ toolWaitSource: sourceFor("toolWaitMinutes"),
2461
+ stuckSource: sourceFor("stuckMinutes"),
2462
+ defaultMaxMinutes: minutes(defaults.ceilingAt),
2463
+ defaultToolWaitMinutes: minutes(defaults.toolWaitMs),
2464
+ defaultStuckMinutes: minutes(defaults.stuckMs),
2465
+ };
2466
+ }
2467
+ catch (error) {
2468
+ return {
2469
+ maxMinutes: DEFAULT_TIMING_MINUTES.max,
2470
+ toolWaitMinutes: DEFAULT_TIMING_MINUTES.toolWait,
2471
+ stuckMinutes: DEFAULT_TIMING_MINUTES.stuck,
2472
+ timeoutSource: timeoutSource(),
2473
+ toolWaitSource: sourceFor("toolWaitMinutes"),
2474
+ stuckSource: sourceFor("stuckMinutes"),
2475
+ defaultMaxMinutes: DEFAULT_TIMING_MINUTES.max,
2476
+ defaultToolWaitMinutes: DEFAULT_TIMING_MINUTES.toolWait,
2477
+ defaultStuckMinutes: DEFAULT_TIMING_MINUTES.stuck,
2478
+ timingError: error instanceof Error ? error.message : String(error),
2479
+ };
2480
+ }
2481
+ };
2482
+ const changeCap = (cap) => {
2483
+ if (!isConcurrencyCap(cap))
2484
+ throw new Error("Concurrent subagents must be a positive whole number.");
2485
+ capOverride = cap;
2486
+ pi.appendEntry("pi-better-subagents-cap", { version: 1, maxConcurrent: cap });
2487
+ };
2488
+ const changeTiming = (key, minutes) => {
2489
+ const value = validatedTimingMinutes(minutes, key);
2490
+ timingOverride = { ...timingOverride, [key]: value };
2491
+ pi.appendEntry("pi-better-subagents-timing", { version: 1, ...timingOverride });
2492
+ };
2493
+ const changeMode = (mode) => {
2494
+ delegationOverride = mode;
2495
+ pi.appendEntry("pi-better-subagents-delegation", { version: 1, mode });
2496
+ };
2497
+ const resetSettings = () => {
2498
+ capOverride = undefined;
2499
+ delegationOverride = undefined;
2500
+ timingOverride = {};
2501
+ skillsOverride = undefined;
2502
+ pi.appendEntry("pi-better-subagents-cap", { version: 1, maxConcurrent: null });
2503
+ pi.appendEntry("pi-better-subagents-delegation", { version: 1, mode: null });
2504
+ pi.appendEntry("pi-better-subagents-timing", { version: 1, maxMinutes: null, toolWaitMinutes: null, stuckMinutes: null });
2505
+ pi.appendEntry("pi-better-subagents-skills", { version: 1, mode: null });
2506
+ };
2507
+ const activeDelegationMode = () => delegationOverride ?? normalizeDelegationMode(loadConfig().delegationMode);
2508
+ const countRunning = () => listActiveMetasForParent(managed?.owner.pid ?? process.pid).filter((meta) => (!managed || meta.spawnPidStartTime === managed.owner.start) && effectiveStatus(meta) === "running").length;
2509
+ const capacityGate = () => managed ? managed.capacity(countRunning) : getSharedCapacityGate(countRunning);
2510
+ // Supervised worker operations: the Background observed-waits service owns
2511
+ // durable records, this extension owns the trusted transport its children
2512
+ // talk to. Both are absent in a standalone Subagents install, which is why
2513
+ // the bridge is optional and parking refuses instead of pretending.
2514
+ const workerOperations = createWorkerOperationsHost({
2515
+ pi,
2516
+ managedRoot: managed?.identity.root,
2517
+ childExtensionPath: childBridgeExtensionPath(selfDir()),
2518
+ });
2519
+ let resumeOrchestration;
2520
+ const notifyOwnedWait = (message, level = "warning") => {
2521
+ try {
2522
+ uiCtx?.ui?.notify?.(message, level);
2523
+ }
2524
+ catch { /* no UI */ }
2525
+ };
2526
+ /**
2527
+ * Stop a continuation attempt only when this parent owns it and the token
2528
+ * published with it matches. A pid is never signalled on a guess.
2529
+ */
2530
+ const stopPublishedAttempt = createOwnedAttemptStopper();
2531
+ cancelParkedForUi = async (id, reason) => {
2532
+ const parked = parkedWaitForRun(id);
2533
+ if (!parked)
2534
+ return false;
2535
+ try {
2536
+ await cancelParkedWait(workerOperations.service, parked, reason, { stopAttempt: stopPublishedAttempt });
2537
+ if (parked.meta.assignment)
2538
+ enqueueCompletionCallback(pi, id);
2539
+ }
2540
+ finally {
2541
+ syncHealthTicker();
2542
+ }
2543
+ return true;
2544
+ };
2545
+ const effectiveSettings = () => {
2546
+ const timing = timingState();
2547
+ return effectiveSubagentSettings({
2548
+ delegationMode: activeDelegationMode(), maxConcurrent: activeConcurrencyCap(),
2549
+ sources: { delegationMode: delegationOverride ? "session" : "config",
2550
+ maxConcurrent: capOverride !== undefined ? "session" : "config" },
2551
+ timing: {
2552
+ toolWaitMinutes: timing.toolWaitMinutes, stuckMinutes: timing.stuckMinutes,
2553
+ sources: { toolWaitMinutes: timing.toolWaitSource, stuckMinutes: timing.stuckSource },
2554
+ ...(timing.timingError ? { error: timing.timingError } : {}),
2555
+ },
2556
+ }, countRunning(), capacityGate().pending);
2557
+ };
2558
+ const saveSettings = () => {
2559
+ try {
2560
+ const skills = activeSkills();
2561
+ if (!skillsOverride && skills.error) {
2562
+ return {
2563
+ ok: false,
2564
+ message: `Cannot save subagent defaults: the saved defaultSkills value is invalid (${skills.error}). ` +
2565
+ `Choose a skill mode in this session to replace it, or fix the saved config first.`,
2566
+ };
2567
+ }
2568
+ if (skills.mode === "explicit" && skills.paths.length === 0) {
2569
+ return { ok: false, message: "Add at least one skill path, or choose No skill catalog to load none." };
2570
+ }
2571
+ // Saving mode and cap must not write a skill key into a config that
2572
+ // never had one. Discovery only replaces a saved choice when a saved
2573
+ // skill value already exists.
2574
+ const cfg = loadConfig();
2575
+ const savedSkillValue = cfg.defaultSkills;
2576
+ const hasSavedSkillChoice = savedSkillValue !== undefined && savedSkillValue !== null;
2577
+ // An environment timeout shown on the page becomes the saved
2578
+ // default; an untouched built-in default still needs no key.
2579
+ const savedTiming = {};
2580
+ const timeout = timingState();
2581
+ if (timingOverride.maxMinutes !== undefined) {
2582
+ savedTiming.maxMinutes = timingOverride.maxMinutes;
2583
+ }
2584
+ else if (timeout.timeoutSource === "environment") {
2585
+ if (timeout.timingError)
2586
+ return { ok: false, message: `Could not save subagent defaults: ${timeout.timingError}` };
2587
+ savedTiming.maxMinutes = timeout.maxMinutes;
2588
+ }
2589
+ else if (isTimingMinutes(cfg.maxMinutes)) {
2590
+ savedTiming.maxMinutes = cfg.maxMinutes;
2591
+ }
2592
+ if (timingOverride.toolWaitMinutes !== undefined) {
2593
+ savedTiming.toolWaitMinutes = timingOverride.toolWaitMinutes;
2594
+ }
2595
+ else if (isTimingMinutes(cfg.toolWaitMinutes)) {
2596
+ savedTiming.toolWaitMinutes = cfg.toolWaitMinutes;
2597
+ }
2598
+ if (timingOverride.stuckMinutes !== undefined) {
2599
+ savedTiming.stuckMinutes = timingOverride.stuckMinutes;
2600
+ }
2601
+ else if (isTimingMinutes(cfg.stuckMinutes)) {
2602
+ savedTiming.stuckMinutes = cfg.stuckMinutes;
2603
+ }
2604
+ writeSubagentSettings({
2605
+ delegationMode: activeDelegationMode(),
2606
+ maxConcurrent: activeConcurrencyCap(),
2607
+ ...savedTiming,
2608
+ ...(skills.mode === "inherit" && !hasSavedSkillChoice ? {} : {
2609
+ // null is an explicit discovery choice; it must override a saved path list.
2610
+ defaultSkills: skills.mode === "inherit" ? null : [...skills.paths],
2611
+ }),
2612
+ });
2613
+ const sessionTimeout = timingOverride.maxMinutes;
2614
+ resetSettings();
2615
+ // The session timeout beats the environment, even after saving defaults.
2616
+ if (sessionTimeout !== undefined)
2617
+ changeTiming("maxMinutes", sessionTimeout);
2618
+ return { ok: true, message: "Subagent defaults saved." };
2619
+ }
2620
+ catch (error) {
2621
+ return { ok: false, message: `Could not save subagent defaults: ${error instanceof Error ? error.message : String(error)}` };
2622
+ }
2623
+ };
2624
+ readDelegation = () => ({
2625
+ mode: activeDelegationMode(),
2626
+ source: delegationOverride ? "session" : "config",
2627
+ });
2628
+ cycleDelegation = () => {
2629
+ const current = activeDelegationMode();
2630
+ const next = DELEGATION_MODES[(DELEGATION_MODES.indexOf(current) + 1) % DELEGATION_MODES.length];
2631
+ changeMode(next);
2632
+ };
2633
+ saveDelegationDefault = (mode) => {
2634
+ try {
2635
+ writeDelegationMode(mode);
2636
+ }
2637
+ catch (error) {
2638
+ return { ok: false, message: `Could not save the delegation default: ${error instanceof Error ? error.message : String(error)}` };
2639
+ }
2640
+ delegationOverride = undefined;
2641
+ pi.appendEntry("pi-better-subagents-delegation", { version: 1, mode: null });
2642
+ return { ok: true, message: `Delegation default saved: ${mode}.` };
2643
+ };
2644
+ const restoreDelegationMode = (ctx) => {
2645
+ delegationOverride = undefined;
2646
+ capOverride = undefined;
2647
+ timingOverride = {};
2648
+ skillsOverride = undefined;
2649
+ const branch = ctx.sessionManager?.getBranch?.();
2650
+ if (!Array.isArray(branch))
2651
+ return;
2652
+ for (const entry of branch) {
2653
+ if (entry.type === "custom" && entry.customType === "pi-better-subagents-timeout") {
2654
+ const data = entry.data;
2655
+ if (data?.version === 1) {
2656
+ const next = { ...timingOverride };
2657
+ if (data.maxMinutes === null)
2658
+ delete next.maxMinutes;
2659
+ else if (isTimingMinutes(data.maxMinutes))
2660
+ next.maxMinutes = data.maxMinutes;
2661
+ timingOverride = next;
2662
+ }
2663
+ continue;
2664
+ }
2665
+ if (entry.type === "custom" && entry.customType === "pi-better-subagents-cap") {
2666
+ const data = entry.data;
2667
+ if (data?.version === 1) {
2668
+ if (data.maxConcurrent === null)
2669
+ capOverride = undefined;
2670
+ else if (isConcurrencyCap(data.maxConcurrent))
2671
+ capOverride = data.maxConcurrent;
2672
+ }
2673
+ }
2674
+ if (entry.type === "custom" && entry.customType === "pi-better-subagents-skills") {
2675
+ const data = entry.data;
2676
+ if (data?.version !== 1)
2677
+ continue;
2678
+ if (data.mode === null) {
2679
+ skillsOverride = undefined;
2680
+ }
2681
+ else if ((data.mode === "inherit" || data.mode === "none") && Array.isArray(data.paths) && data.paths.length === 0) {
2682
+ skillsOverride = { mode: data.mode, paths: [] };
2683
+ }
2684
+ else if (data.mode === "explicit" && Array.isArray(data.paths)
2685
+ && data.paths.every((path) => typeof path === "string" && isAbsolute(path))) {
2686
+ skillsOverride = { mode: "explicit", paths: [...data.paths] };
2687
+ }
2688
+ continue;
2689
+ }
2690
+ if (entry.type === "custom" && entry.customType === "pi-better-subagents-timing") {
2691
+ const data = entry.data;
2692
+ if (data?.version !== 1)
2693
+ continue;
2694
+ const next = {};
2695
+ if (isTimingMinutes(data.maxMinutes))
2696
+ next.maxMinutes = data.maxMinutes;
2697
+ if (isTimingMinutes(data.toolWaitMinutes))
2698
+ next.toolWaitMinutes = data.toolWaitMinutes;
2699
+ if (isTimingMinutes(data.stuckMinutes))
2700
+ next.stuckMinutes = data.stuckMinutes;
2701
+ timingOverride = next;
2702
+ continue;
2703
+ }
2704
+ if (entry.type !== "custom" || entry.customType !== "pi-better-subagents-delegation")
2705
+ continue;
2706
+ const data = entry.data;
2707
+ if (data?.version !== 1)
2708
+ continue;
2709
+ if (data.mode === null)
2710
+ delegationOverride = undefined;
2711
+ else if (isDelegationMode(data.mode))
2712
+ delegationOverride = data.mode;
2713
+ }
2714
+ };
2715
+ const unsubscribeDelegationRequest = pi.events?.on?.(DELEGATION_MODE_REQUEST, (data) => {
2716
+ if (data && typeof data === "object")
2717
+ data.mode = activeDelegationMode();
2718
+ });
2719
+ // Capture for the health ticker (module-level); needed for orphaned/lost
2720
+ // coordinator follow-ups that fire outside a tool-call stack (#65).
2721
+ healthPi = pi;
2722
+ ensureSubagentProvider();
2723
+ registerSubagentsGoalProvider(pi);
2724
+ observeSandboxPermissions(pi);
2725
+ // Record admission identities during registration: inventory actions are not
2726
+ // available while extensions load. A later replacement must fail the identity check.
2727
+ const registeredSpawnSchemas = new Map();
2728
+ const registerSpawnTool = (definition) => {
2729
+ registeredSpawnSchemas.set(definition.name, definition.parameters);
2730
+ pi.registerTool(managed ? { ...definition, async execute(key, params, signal, onUpdate, ctx) {
2731
+ ctx = captureLaunchContext(ctx);
2732
+ restoreDelegationMode(ctx);
2733
+ await workerOperations.start();
2734
+ return definition.execute(key, params, signal, onUpdate, ctx);
2735
+ } } : { ...definition, async execute(key, params, _signal, _onUpdate, ctx) {
2736
+ ctx = captureLaunchContext(ctx);
2737
+ catalogHostFrom(ctx);
2738
+ const { submitManagedLaunch } = await import("./managed-launch-client.domain.mjs");
2739
+ void activateWorkObservation();
2740
+ return await observeNavigatorLaunch(ctx, "subagents", key, "Subagent launch", () => submitManagedLaunch(pi, ctx, key, definition.name, params));
2741
+ } });
2742
+ };
2743
+ announceExecutionAdapter(pi, {
2744
+ parametersFor: (name) => registeredSpawnSchemas.get(name),
2745
+ runApplication: TASK_BUILTINS.includes(RUN_APPLICATION),
2746
+ });
2747
+ let acceptanceResultToolRef;
2748
+ function publishAcceptanceHooks(tool) {
2749
+ if (process.env.PI_CATALOG_ACCEPTANCE_PROBE !== "1")
2750
+ return;
2751
+ if (tool)
2752
+ acceptanceResultToolRef = tool;
2753
+ globalThis[Symbol.for("pi-better-subagents.acceptance-hooks")] = {
2754
+ subagentResult: acceptanceResultToolRef,
2755
+ subagentSpawn: acceptanceSpawnToolRef,
2756
+ subagentStop: acceptanceStopToolRef,
2757
+ listRows: () => acceptanceProviderRef?.listRows(Date.now()) ?? [],
2758
+ renderDetail: (id, width = 100) => renderRegisteredWorkDetail("subagents", id, width),
2759
+ };
2760
+ }
2761
+ function catalogHostFrom(ctx) {
2762
+ if (!managed)
2763
+ noteCatalogHostContext(ctx, () => agentSessionSettings.snapshot());
2764
+ if (typeof ctx.sessionManager?.getBranch === "function")
2765
+ agentSessionSettings.restore(ctx);
2766
+ catalogModelRegistry = ctx.modelRegistry;
2767
+ const cfg = loadConfig();
2768
+ return {
2769
+ sessionSettings: agentSessionSettings.snapshot(),
2770
+ getSessionSettings: () => agentSessionSettings.snapshot(),
2771
+ cwd: ctx.cwd,
2772
+ projectTrusted: typeof ctx.isProjectTrusted === "function" ? ctx.isProjectTrusted() : false,
2773
+ userRoot: defaultUserRoot(),
2774
+ projectConfigDirName,
2775
+ registry: ctx.modelRegistry,
2776
+ foregroundModel: ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined,
2777
+ configuredDefaultModel: cfg.defaultModel,
2778
+ tiers: tiersForLaunch(cfg),
2779
+ hasUI: ctx.hasUI === true,
2780
+ select: typeof ctx.ui?.select === "function"
2781
+ ? (title, options) => ctx.ui.select(title, options)
2782
+ : undefined,
2783
+ };
2784
+ }
2785
+ function catalogResult(clarification) {
2786
+ return {
2787
+ content: [{ type: "text", text: clarification.message }],
2788
+ details: {
2789
+ status: "clarification-needed",
2790
+ launched: false,
2791
+ wrote: false,
2792
+ choices: [...clarification.choices],
2793
+ },
2794
+ };
2795
+ }
2796
+ async function admitCatalog(ctx, jobs) {
2797
+ const host = catalogHostFrom(ctx);
2798
+ noteCatalogHost(host);
2799
+ if (!jobs.some((job) => hasCatalogSelector(job))) {
2800
+ return { status: "ready", jobs: jobs };
2801
+ }
2802
+ const snapshot = managed ? await managed.snapshot(host) : await loadSharedLaunchSnapshot(host);
2803
+ const clarified = await clarifyCatalogRequest(jobs, { hasUI: host.hasUI === true, select: host.select });
2804
+ if (clarified.status === "clarification-needed")
2805
+ return clarified;
2806
+ const prepared = [];
2807
+ for (const job of clarified.jobs) {
2808
+ if (!hasCatalogSelector(job)) {
2809
+ prepared.push(job);
2810
+ continue;
2811
+ }
2812
+ const result = await prepareCatalogJob(snapshot, job, host);
2813
+ if (result.status === "blocked")
2814
+ throw new Error(result.message);
2815
+ if (result.status !== "ready") {
2816
+ prepared.push(job);
2817
+ continue;
2818
+ }
2819
+ prepared.push({ ...job, ...result.assign });
2820
+ }
2821
+ return { status: "ready", jobs: prepared, snapshot };
2822
+ }
2823
+ /**
2824
+ * Shared internal spawn path used by both subagent_spawn and
2825
+ * subagent_spawn_batch. Every launched job becomes a normal subagent run
2826
+ * with its own run ID, process, log, metadata, callback, result/output/stop
2827
+ * behavior, and sandboxing.
2828
+ */
2829
+ async function spawnSubagentRun(ctx, p, batchInfo, resume,
2830
+ /**
2831
+ * Internal resume identity. Never a tool parameter: an auto-resume
2832
+ * publishes its attempt id and launch token in the coordinator before
2833
+ * this call, and a manual continuation passes neither.
2834
+ */
2835
+ internal) {
2836
+ const { resolveChildClosure, resolveChildLaunch, configSnapshot } = await import("./child-dependencies.mjs");
2837
+ const { resolveSubagentWorkspace } = await import("./git-workspace.domain.mjs");
2838
+ const { PREFLIGHT_ENV } = await import("./child-preflight.mjs");
2839
+ assertThinkingLevel(p.thinking);
2840
+ // Skill exposure is a caller choice, not a launch: validate its shape
2841
+ // before any attempt directory or capacity effect exists. A continuation
2842
+ // validates too, so a malformed repeat is a shape error rather than being
2843
+ // reported as a recipe conflict.
2844
+ normalizeSkillExposure(p.skills, "skills");
2845
+ // A conversation parked on an observed wait resumes through the
2846
+ // coordinator's claim. An ordinary manual continuation would leave that
2847
+ // automatic resume armed for the same assignment, so it is refused until
2848
+ // the human takes the parked attempt over (subagent_stop cancels the wait).
2849
+ if (resume && !internal?.resumeWait) {
2850
+ const parked = parkedWaitForRun(resume.prior.id);
2851
+ if (parked)
2852
+ throw new ContinuationError(manualResumeRefusal(parked));
2853
+ }
2854
+ // A continuation re-applies the CURRENT mandatory human permissions to its
2855
+ // frozen confinement intent. Historical metadata can never widen authority,
2856
+ // and a profile that would change confinement refuses instead of silently
2857
+ // moving a live conversation into a different sandbox.
2858
+ const permissionPlan = resolveSubagentPermissions(pi, p.sandbox, resume && { runId: resume.prior.id, sandbox: resume.recipe.sandbox });
2859
+ const processPolicy = describeSubagentProcessPolicy(permissionPlan, process.platform);
2860
+ const processAccess = effectiveWorkerProcessAccess(permissionPlan);
2861
+ const taskPermissions = permissionPlan.inactiveProfile
2862
+ ? { ...DEFAULT_TASK_PERMISSIONS, processAccess }
2863
+ : permissionPlan.permissions;
2864
+ const cfg = loadConfig();
2865
+ // Harness-owned timing (soft deadline, ceiling, tool-wait and stuck windows); validated before any side effect.
2866
+ resolveRunTiming({ params: launchTimingParams(p), settings: timingSettingsFor(cfg), env: process.env, startedAt: 0 });
2867
+ let model;
2868
+ let thinking;
2869
+ if (resume) {
2870
+ // Preserve the recipe's effective model and effort. Only an explicit
2871
+ // per-attempt model/effort acts as an escalation; a bare foreground or
2872
+ // configured default must not silently replace the owner's choice.
2873
+ assertThinkingLevel(resume.recipe.effort, "saved effort");
2874
+ const baseModel = parseModelThinking(resume.recipe.model, resume.recipe.effort);
2875
+ if (p.model !== undefined) {
2876
+ const explicit = parseModelThinking(p.model, p.thinking ?? baseModel.thinking);
2877
+ model = explicit.model;
2878
+ thinking = explicit.thinking;
2879
+ }
2880
+ else {
2881
+ model = baseModel.model;
2882
+ thinking = p.thinking ?? baseModel.thinking;
2883
+ }
2884
+ }
2885
+ else if (p.catalogResolved === true) {
2886
+ model = p.model;
2887
+ thinking = p.thinking;
2888
+ }
2889
+ else {
2890
+ const requestedModel = p.model ?? cfg.defaultModel ?? (ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined);
2891
+ const parsed = parseModelThinking(requestedModel, p.thinking);
2892
+ model = parsed.model;
2893
+ thinking = parsed.thinking;
2894
+ }
2895
+ // Best-effort daily hygiene for durable tmp state. The marker makes
2896
+ // this effectively free after the first subagent launch each day.
2897
+ // Resume has already validated this history. Retiring it here would let
2898
+ // native --session create an empty replacement before the child runs.
2899
+ if (!resume)
2900
+ runDailyCleanupOnce({ config: cfg });
2901
+ // Age retires history; this bounds the peak one busy day can reach.
2902
+ // Rate-limited inside cleanup.ts, and never on the UI hot path.
2903
+ const capped = resume ? { removed: [] } : enforceRegistrySizeCapOnce({ config: cfg });
2904
+ for (const id of capped.removed) {
2905
+ spendCache.delete(id);
2906
+ healthLogCache.delete(id);
2907
+ resetChildEventLogCursor(id);
2908
+ resetParseRunCursor(id);
2909
+ }
2910
+ const callbackOrigin = internal?.parkOwner
2911
+ ? { cwd: internal.parkOwner.workspace, sessionId: internal.parkOwner.sessionId }
2912
+ : callbackOriginFromContext(ctx);
2913
+ activeCallbackOrigin = callbackOriginFromContext(ctx);
2914
+ // Sandbox is opt-in. sandbox_dir moves the confinement + working
2915
+ // dir elsewhere. git_clone_workspace prepares a disposable clone with
2916
+ // .git/ inside the writable root for Git-mutating sandboxed subagents.
2917
+ const sandboxEnabled = permissionPlan.sandboxEnabled;
2918
+ // An auto-resume carries the attempt id the coordinator already published;
2919
+ // a fresh or manual launch allocates a new one.
2920
+ const id = internal?.assignedRunId ?? managed?.attempt() ?? nextRunId();
2921
+ // Attempt identity (`id`) and conversation identity (`sessionId`) are
2922
+ // separate. A continuation keeps the native session; only the attempt is new.
2923
+ const sessionId = resume ? resume.conversation.sessionId : id;
2924
+ const rootRunId = resume ? resume.rootRunId : id;
2925
+ const childSessionDir = resume
2926
+ ? resume.recipe.sessionDir
2927
+ : sandboxEnabled ? join(sessionsDir(), id) : sessionsDir();
2928
+ // The disposable clone this launch owns (removed if the spawn fails); a caller's sandbox_dir is not ours.
2929
+ // A continuation never prepares another clone: the recipe's workspace already
2930
+ // holds the prior attempt's uncommitted work.
2931
+ const ownedCloneWorkspace = !resume && !p.sandbox_dir && sandboxEnabled && p.git_clone_workspace ? taskWorkspaceDir(id) : undefined;
2932
+ // A launch attempt only becomes a run when `writeMeta` commits. Until
2933
+ // then everything it creates (prompt, control/, provenance, its own
2934
+ // session dir, clone workspace, task scratch) belongs to the attempt and
2935
+ // must go if it fails, so no unreadable record is left in the registry
2936
+ // (#325, #332, #623).
2937
+ let lease;
2938
+ let spawned;
2939
+ let launchScratch;
2940
+ let committed = false;
2941
+ try {
2942
+ if (!resume)
2943
+ mkdirSync(childSessionDir, { recursive: true });
2944
+ mkdirSync(runDir(id), { recursive: true });
2945
+ // Claim the directory before anything else is prepared. Until
2946
+ // `meta.json` exists this claim is the only ownership evidence, so a
2947
+ // concurrent purge can tell this live attempt from dead launch debris
2948
+ // (#623 R1). The outer catch drops the whole directory on failure.
2949
+ recordLaunchAttempt(id);
2950
+ const workspace = resume
2951
+ ? { cwd: resume.recipe.cwd, requestedSandboxDir: resume.recipe.sandboxDir }
2952
+ : resolveSubagentWorkspace({
2953
+ ctxCwd: ctx.cwd,
2954
+ cwd: p.cwd,
2955
+ sandboxDir: p.sandbox_dir ?? ownedCloneWorkspace,
2956
+ gitCloneWorkspace: p.git_clone_workspace,
2957
+ runId: id,
2958
+ runDirPath: runDir(id),
2959
+ sandboxEnabled,
2960
+ });
2961
+ const cwd = workspace.cwd;
2962
+ const requestedSandboxDir = workspace.requestedSandboxDir;
2963
+ // Skill exposure is decided once per attempt. A continuation replays the
2964
+ // frozen recipe (including its absence, which keeps discovery); a fresh
2965
+ // launch resolves launch option → catalog role/agent → this session's
2966
+ // default → saved config default → discovery. Relative paths belong to
2967
+ // the workspace the child runs in.
2968
+ const sessionSkills = resume ? undefined : sessionSkillChoice();
2969
+ if (!resume && !sessionSkills) {
2970
+ const saved = savedSkills();
2971
+ if (saved.error) {
2972
+ throw new Error(`Cannot read config defaultSkills: ${saved.error}`);
2973
+ }
2974
+ }
2975
+ const skills = resolveSkillExposure(resume
2976
+ ? { saved: { paths: resume.recipe.skills }, cwd }
2977
+ : {
2978
+ requested: p.skills,
2979
+ catalog: p.catalog?.effective?.skills?.value,
2980
+ session: sessionSkills,
2981
+ configured: cfg.defaultSkills,
2982
+ cwd,
2983
+ });
2984
+ if (requestedSandboxDir)
2985
+ mkdirSync(requestedSandboxDir, { recursive: true });
2986
+ writeFileSync(promptPathFor(id), p.prompt);
2987
+ // A continuation keeps the recipe's launch intent; only current
2988
+ // permission-driven adjustments are re-derived from it.
2989
+ const requestedTools = resume ? callerLaunchTools(resume.recipe.tools) : p.tools;
2990
+ const requestedExcludeTools = resume ? resume.recipe.excludeTools ?? "" : p.exclude_tools ?? "";
2991
+ const clean = resume ? resume.recipe.clean : p.clean === true;
2992
+ const allowNested = resume ? resume.recipe.allowNested : p.allow_nested === true;
2993
+ const approve = resume ? resume.recipe.approve : p.approve === true;
2994
+ const gitCloneWorkspace = resume ? resume.recipe.gitCloneWorkspace : p.git_clone_workspace === true;
2995
+ const callbackEnabled = resume ? p.callback ?? resume.recipe.callback : p.callback !== false;
2996
+ const launchName = resume ? resume.recipe.name : p.name;
2997
+ // The frozen launch snapshot is the same shape a fresh spawn freezes.
2998
+ const launchCatalog = resume
2999
+ ? resume.recipe.catalog
3000
+ : p.catalog;
3001
+ let allow = normalizeTools(requestedTools ?? cfg.defaultTools ?? (clean ? SAFE_CLEAN_TOOLS : SAFE_DEFAULT_TOOLS));
3002
+ if (allowNested) {
3003
+ const have = new Set(allow.split(","));
3004
+ allow = [...allow.split(","), ...SUBAGENT_TOOLS.filter((t) => !have.has(t))]
3005
+ .filter(Boolean).join(",");
3006
+ }
3007
+ // Exclusions apply to the worker selection before provider admission (ADR 0027).
3008
+ const requestedExcludes = new Set(requestedExcludeTools.split(",").map((t) => t.trim()).filter(Boolean));
3009
+ // Supervised worker operations. This only decides which names the
3010
+ // child's loadout carries: clean children, explicit tool lists,
3011
+ // exclusions and task-sandboxed children keep their restrictions, and
3012
+ // the Background host still intersects the captured task authority
3013
+ // with the current profile before any task launches.
3014
+ // Production schemas come from the parent Background extension's own
3015
+ // tool registrations; a bridge tool without one is withheld instead of
3016
+ // being advertised with a permissive fallback schema.
3017
+ const productionBridgeSchemas = resolveProductionSchemas(pi, DEFAULT_WORKER_BRIDGE_TOOLS);
3018
+ const bridgePlan = planWorkerBridgeTools({
3019
+ allow: allow.split(",").filter(Boolean),
3020
+ excluded: [...requestedExcludes],
3021
+ clean,
3022
+ explicitTools: requestedTools !== undefined,
3023
+ productionSchemas: new Set(productionBridgeSchemas.schemas.keys()),
3024
+ });
3025
+ if (managed) {
3026
+ const captured = new Set(managed.backgroundTools());
3027
+ bridgePlan.tools = bridgePlan.tools.filter(name => captured.has(name));
3028
+ if (requestedTools && requestedTools.split(",").some(name => DEFAULT_WORKER_BRIDGE_TOOLS.includes(name.trim()) && !captured.has(name.trim()))) {
3029
+ throw new Error("The original Pi host did not authorize the requested Background capability");
3030
+ }
3031
+ const has = (name) => bridgePlan.tools.includes(name);
3032
+ bridgePlan.capabilities = { background: { spawn: has("bg_task_spawn"), watch: has("bg_task_watch"), status: has("bg_task_status"), log: has("bg_task_log") }, wait: has("wait_for_operations"), acknowledge: has("acknowledge_operation_result"), parking: has("wait_for_operations") };
3033
+ }
3034
+ const parent = ownerBindingFromContext(ctx);
3035
+ const assignment = internal?.resumeWait && resume?.prior.assignment
3036
+ ? resume.prior.assignment
3037
+ : parent.sessionId && typeof ctx.sessionManager?.getBranch === "function" ? { version: 1, assignmentId: id,
3038
+ owner: { kind: "worker-conversation", sessionId, workspace: cwd, branchId: parent.branchId, goalId: parent.goalId },
3039
+ recipient: { kind: "parent-session", ...parent } } : undefined;
3040
+ if (!workerOperations.available) {
3041
+ bridgePlan.tools = [];
3042
+ bridgePlan.capabilities = { background: { spawn: false, watch: false, status: false, log: false }, wait: false, acknowledge: false, parking: false };
3043
+ }
3044
+ if (assignment && !requestedExcludes.has("report_assignment_result")) {
3045
+ bridgePlan.tools = [...bridgePlan.tools, "report_assignment_result"];
3046
+ bridgePlan.capabilities = { ...bridgePlan.capabilities, reportAssignment: true };
3047
+ productionBridgeSchemas.schemas.set("report_assignment_result", createToolDescriptor("report_assignment_result"));
3048
+ }
3049
+ assertWaitToolDependencies(bridgePlan.capabilities, bridgePlan.tools);
3050
+ const bridgeEnabled = bridgePlan.tools.length > 0;
3051
+ if (bridgeEnabled) {
3052
+ allow = [...new Set([...allow.split(",").filter(Boolean), ...bridgePlan.tools])].join(",");
3053
+ }
3054
+ if (!clean) {
3055
+ const names = allow.split(",").filter(Boolean);
3056
+ // Derive the editable loadout before applying the resource policy.
3057
+ if (!resume)
3058
+ addEditablePatch(names, requestedExcludes);
3059
+ allow = [...new Set(names)].join(",");
3060
+ }
3061
+ if (sandboxEnabled && requestedTools === undefined && processAccess === "read") {
3062
+ allow = [...new Set([...allow.split(","), "process_list"])].join(",");
3063
+ }
3064
+ // Shell Off confines the child to directly launched applications: a requested bash
3065
+ // becomes the guarded run_application builtin. Exclusions stay exclusions (an excluded
3066
+ // run_application leaves bash out rather than restoring it), and a read-only loadout
3067
+ // keeps no command capability at all.
3068
+ const commandSettings = resolveCommandSettings(permissionPlan.permissions);
3069
+ if (sandboxEnabled && !commandSettings.shell) {
3070
+ allow = applyDirectApplicationLoadout(allow.split(",").filter(Boolean), {
3071
+ shell: false, excluded: requestedExcludes,
3072
+ }).tools.join(",");
3073
+ }
3074
+ const bridgeToolNames = new Set(bridgeEnabled ? bridgePlan.tools : []);
3075
+ // A bridge tool the supervisor withholds (no production schema, clean,
3076
+ // excluded) explains itself better than extension admission would.
3077
+ const withheldBridgeReasons = new Map(bridgePlan.withheld.map((tool) => [tool.name, tool.reason]));
3078
+ // Candidates for the task-tool plan: exclusions and bridge-supplied
3079
+ // names never reach extension admission.
3080
+ const plannedTools = allow.split(",").filter((name) => name && !requestedExcludes.has(name) && !bridgeToolNames.has(name));
3081
+ const continuationRuntime = selectContinuationRuntime({ currentDir: selfDir(), recipe: resume?.recipe });
3082
+ const workerPath = (path) => continuationRuntime?.mapPath(path) ?? path;
3083
+ const workerArgs = (args) => continuationRuntime?.mapArgs(args) ?? args;
3084
+ const workerResolvePath = (spec) => {
3085
+ const path = resolveExtensionPath(spec);
3086
+ return path ? workerPath(path) : path;
3087
+ };
3088
+ const normalProviders = ordinaryChildConfig(cfg, managed?.activeProviders?.() ?? activeChildProviders(pi));
3089
+ const taskTools = sandboxEnabled ? planTaskTools({
3090
+ requested: plannedTools,
3091
+ settings: permissionPlan.tools, network: permissionPlan.permissions?.network ?? true,
3092
+ processAccess,
3093
+ builtins: [...TASK_BUILTINS, "codemode"], registered: pi.getAllTools?.() ?? [],
3094
+ toolExtensions: normalProviders.toolExtensions, resolvePath: workerResolvePath,
3095
+ }) : undefined;
3096
+ // One effective selection feeds the task policy, child preflight, worker
3097
+ // bridge and frozen recipe, so a refused tool cannot leak into any of them
3098
+ // (#669). A name this attempt requires - the caller's explicit `tools`, or a
3099
+ // continuation's frozen loadout - refuses the launch instead of narrowing it;
3100
+ // an inherited default is dropped from the child with the reason.
3101
+ const requiredToolNames = new Set(requestedTools === undefined
3102
+ ? []
3103
+ : requestedTools.split(",").map((name) => name.trim()).filter(Boolean));
3104
+ const toolSelection = taskTools
3105
+ ? selectEffectiveTaskTools({
3106
+ tools: allow.split(",").filter(Boolean), plan: taskTools, required: requiredToolNames,
3107
+ })
3108
+ : undefined;
3109
+ if (toolSelection?.required.length) {
3110
+ const detail = toolSelection.required
3111
+ .map((tool) => `${tool.name} (${withheldBridgeReasons.get(tool.name) ?? tool.reason})`).join(", ");
3112
+ throw resume
3113
+ ? new ContinuationError(`Cannot continue ${resume.prior.id}: its frozen launch requires tool(s) this parent can no longer provide: ${detail}. ` +
3114
+ `Launch a new run instead of continuing this conversation. ${processPolicy}`)
3115
+ : new Error(`Requested tool(s) are not available in the task sandbox: ${detail}. ` +
3116
+ `Check the child tool provider and the Subagents resource permissions; nothing was launched.`);
3117
+ }
3118
+ if (toolSelection) {
3119
+ if (plannedTools.length > 0 && toolSelection.tools.length === 0) {
3120
+ throw new Error(`No requested tool has a verified task sandbox adapter: ${toolSelection.refused.map((tool) => `${tool.name} (${withheldBridgeReasons.get(tool.name) ?? tool.reason})`).join(", ")}.`);
3121
+ }
3122
+ allow = toolSelection.tools.join(",");
3123
+ }
3124
+ // Older recipes were frozen before isolated workers gained Harness providers
3125
+ // and inherited workers began loading mappings explicitly.
3126
+ const legacyToolLoading = resume !== undefined && !resume.recipe.toolLoadingVersion;
3127
+ let extensionConfig = cfg;
3128
+ if (!sandboxEnabled && !legacyToolLoading)
3129
+ extensionConfig = normalProviders;
3130
+ if (legacyToolLoading && cfg.inheritExtensions)
3131
+ extensionConfig = { ...cfg, toolExtensions: {} };
3132
+ const dependencyOptions = {
3133
+ model, virtual: (() => {
3134
+ const slash = model?.indexOf("/") ?? -1;
3135
+ return slash > 0 && ctx.modelRegistry?.find?.(model.slice(0, slash), model.slice(slash + 1))?.api === "pi-virtual";
3136
+ })(), config: extensionConfig, resolvePath: workerResolvePath,
3137
+ configPaths: [configPath(), workerPath(join(selfDir(), "config.json"))],
3138
+ };
3139
+ // Bridge tools are supplied by the worker bridge extension, not by a
3140
+ // configured toolExtensions mapping: keep them out of extension
3141
+ // resolution so `unmapped` stays an accurate operator warning and the
3142
+ // frozen launch recipe never depends on bridge availability.
3143
+ const extensionAllowlist = () => allow.split(",")
3144
+ .filter(name => !requestedExcludes.has(name) && !bridgeToolNames.has(name)).join(",");
3145
+ const { resolution, fullResolution } = await resolveChildLaunch({ ...dependencyOptions, resolution: resolveExtensions({
3146
+ // Only SDK builtins reach `--tools` and extension resolution: process_list and run_application
3147
+ // are task builtins that the mandatory guard installs and activates itself.
3148
+ tools: sandboxEnabled ? allow.split(",").filter((name) => SDK_BUILTIN_TOOLS.includes(name)).join(",") : extensionAllowlist(),
3149
+ model, clean, allowNested: sandboxEnabled ? false : allowNested, config: extensionConfig,
3150
+ }) }, taskTools?.trusted.map(tool => tool.loadPath) ?? []);
3151
+ if (!sandboxEnabled && resolution.mode === "isolated" &&
3152
+ fullResolution.specs.every((spec) => Object.values(ORDINARY_TOOL_PROVIDERS).includes(spec))) {
3153
+ const missingTools = resolution.unmapped.filter((name) => requiredToolNames.has(name));
3154
+ if (missingTools.length)
3155
+ throw new Error(`No provider for required child tools: ${missingTools.join(", ")}. Configure toolExtensions or change the requested tools.`);
3156
+ }
3157
+ const { args: resolvedExtArgs, missing } = extensionArgs(resolution, (spec) => resolution.paths[spec] ?? workerResolvePath(spec));
3158
+ const trustedExtArgs = fullResolution.specs.map(spec => fullResolution.paths[spec])
3159
+ .filter(path => !resolvedExtArgs.includes(path)).flatMap(path => ["--extension", path]);
3160
+ // Harness child controls ride along in every mode, including clean and unsandboxed runs.
3161
+ // They deliver deadline steers and keep external monitoring with the coordinator.
3162
+ const codemodeArgs = !sandboxEnabled && allow.split(",").includes("codemode") && !requestedExcludes.has("codemode")
3163
+ ? ["--extension", join(selfDir(), "child-codemode.ts")] : [];
3164
+ const extArgs = workerArgs([...resolvedExtArgs, ...trustedExtArgs, ...codemodeArgs,
3165
+ "--extension", childSteerExtensionPath(), "--extension", join(selfDir(), "child-ownership.ts")]
3166
+ .map((value, index, all) => sandboxEnabled && all[index - 1] === "--extension" ? canonicalizePath(value) : value));
3167
+ const baseExtensionArgs = workerArgs([...resolvedExtArgs, ...codemodeArgs,
3168
+ "--extension", childSteerExtensionPath(), "--extension", join(selfDir(), "child-ownership.ts")]
3169
+ .map((value, index, all) => sandboxEnabled && all[index - 1] === "--extension" ? canonicalizePath(value) : value));
3170
+ if (resume?.recipe.extensionArgs) {
3171
+ // A model escalation may change provider auth, but an unchanged tool
3172
+ // must not silently switch implementations with current configuration.
3173
+ const reference = model === resume.recipe.model ? resolution : await resolveChildClosure({
3174
+ ...dependencyOptions, model: resume.recipe.model, virtual: false, resolution: resolveExtensions({
3175
+ tools: sandboxEnabled ? allow.split(",").filter((name) => SDK_BUILTIN_TOOLS.includes(name)).join(",") : extensionAllowlist(),
3176
+ model: resume.recipe.model, clean, allowNested: sandboxEnabled ? false : allowNested, config: extensionConfig,
3177
+ })
3178
+ });
3179
+ const referenceArgs = [...extensionArgs(reference, (spec) => reference.paths[spec] ?? workerResolvePath(spec)).args, ...codemodeArgs,
3180
+ ...(!resume.recipe.baseExtensionArgs ? trustedExtArgs : []),
3181
+ "--extension", childSteerExtensionPath(), "--extension", join(selfDir(), "child-ownership.ts")]
3182
+ .map((value, index, all) => sandboxEnabled && all[index - 1] === "--extension" ? canonicalizePath(value) : value);
3183
+ assertContinuationExtensions(resume.prior.id, resume.recipe, workerArgs(referenceArgs), (taskTools?.trusted ?? []).map(tool => ({ ...tool, loadPath: workerPath(tool.loadPath) })));
3184
+ }
3185
+ if (sandboxEnabled && resolution.mode === "inherit") {
3186
+ throw new Error("Task confinement requires explicit extensions; inheritExtensions is unsupported while sandboxing is enabled.");
3187
+ }
3188
+ if (missing.length) {
3189
+ throw new Error(`Subagent needs extension(s) that are not installed: ${missing.join(", ")}. ` +
3190
+ `Install them, drop the tools that require them, or remove the mapping from config.json.`);
3191
+ }
3192
+ const excludes = new Set();
3193
+ if (requestedExcludeTools)
3194
+ for (const t of requestedExcludeTools.split(","))
3195
+ if (t.trim())
3196
+ excludes.add(t.trim());
3197
+ if (!allowNested && resolution.mode === "inherit") {
3198
+ for (const t of SUBAGENT_TOOLS)
3199
+ excludes.add(t);
3200
+ }
3201
+ // A continuation reopens the exact saved conversation with `--session`;
3202
+ // never `--session-id`, which would create a replacement session when the
3203
+ // history is missing, and never both (Pi rejects the combination).
3204
+ const sessionArgs = resume
3205
+ ? ["--session", resume.conversation.path, "--session-dir", childSessionDir]
3206
+ : ["--session-dir", childSessionDir, "--session-id", id];
3207
+ // The bridge extension is added to the command, not to the frozen
3208
+ // recipe: whether a supervising Background host is installed is a
3209
+ // supervision capability, not a tool implementation, so it must not
3210
+ // invalidate a conversation's saved recipe when it appears later.
3211
+ const commandExtArgs = bridgeEnabled
3212
+ ? [...extArgs, "--extension", workerPath(childBridgeExtensionPath(selfDir()))]
3213
+ : extArgs;
3214
+ const args = [
3215
+ "-p", "--mode", "json",
3216
+ ...sessionArgs,
3217
+ ...commandExtArgs,
3218
+ ...(model ? ["--model", model] : []),
3219
+ ...(thinking ? ["--thinking", thinking] : []),
3220
+ ...skillLaunchArgs(skills),
3221
+ ...(allow && !sandboxEnabled ? ["--tools", allow] : []),
3222
+ ...(excludes.size ? ["--exclude-tools", [...excludes].join(",")] : []),
3223
+ ...(sandboxEnabled ? ["--no-builtin-tools", "--no-approve"] : approve ? ["--approve"] : []),
3224
+ p.prompt,
3225
+ ];
3226
+ const selectedTools = allow.split(",").filter((name) => name && !excludes.has(name));
3227
+ const inheritedTrusted = resume ? new Set(resume.recipe.optionalTrustedTools ?? []) : undefined;
3228
+ const optionalTrustedTools = taskTools?.trusted.filter(({ name }) => selectedTools.includes(name)
3229
+ && (inheritedTrusted ? inheritedTrusted.has(name) : requestedTools === undefined)).map(({ name }) => name) ?? [];
3230
+ const dropped = toolSelection?.dropped ?? [];
3231
+ const taskRuntime = sandboxEnabled && requestedSandboxDir ? prepareTaskRuntime({
3232
+ root: requestedSandboxDir, controlDir: join(runDir(id), "control"),
3233
+ tools: selectedTools,
3234
+ permissions: taskPermissions && { ...taskPermissions, ...commandSettings },
3235
+ applyPatch: taskTools?.applyPatch === true,
3236
+ extensionTools: taskTools?.trusted.map(({ loadPath: _loadPath, ...tool }) => ({ ...tool, root: workerPath(tool.root) })) ?? [],
3237
+ // The sandboxed child's policy enables the guarded operation bridge
3238
+ // only when the fixed bridge adapter path is among its extension
3239
+ // paths; the task guard then admits those tools by exact source.
3240
+ extensionPaths: [
3241
+ ...extArgs.flatMap((arg, index) => arg === "--extension" && extArgs[index + 1] ? [extArgs[index + 1]] : []),
3242
+ ...(bridgeEnabled ? [workerPath(childBridgeExtensionPath(selfDir()))] : []),
3243
+ ],
3244
+ operationBridgePath: workerPath(childBridgeExtensionPath(selfDir())),
3245
+ runtimeRoots: [baseDir()],
3246
+ capturedDenyWrite: internal?.resumeWait
3247
+ ? resume?.prior.operations?.policy.sandbox?.denyWrite
3248
+ : undefined,
3249
+ }) : undefined;
3250
+ launchScratch = taskRuntime?.policy.scratch;
3251
+ if (sandboxEnabled && !taskRuntime)
3252
+ throw new Error("Task sandbox has no workspace; refusing an unconfined child.");
3253
+ // Parent-authored trust record, written before the child can run (#325).
3254
+ if (taskRuntime)
3255
+ recordTaskRuntimeProvenance(id);
3256
+ // Outside project = Write or Write & delete lets the run change files
3257
+ // outside its workspace: start an APFS local snapshot (macOS, in the
3258
+ // background; a failure is reported, never blocks the run).
3259
+ const snapshot = taskRuntime ? takeRecoverySnapshot(taskRuntime.policy.permissions) : undefined;
3260
+ if (snapshot?.started) {
3261
+ void snapshot.done.then((outcome) => {
3262
+ if (outcome.ok)
3263
+ return;
3264
+ // The snapshot can finish after the session was replaced and ctx went stale.
3265
+ try {
3266
+ ctx.ui?.notify?.(`Subagent ${id}: recovery snapshot failed (run continues): ${outcome.detail}`, "warning");
3267
+ }
3268
+ catch { /* ignore */ }
3269
+ });
3270
+ }
3271
+ const currentCommand = taskRuntime ? { file: taskRuntime.file, fileArgs: [...taskRuntime.fileArgs, ...args] }
3272
+ : managed ? managed.workerCommand(args)
3273
+ : { file: process.execPath, fileArgs: [join(selfDir(), "child-runtime.mjs"), resolvePiBinary(), ...args] };
3274
+ const cmd = continuationRuntime?.command(currentCommand) ?? currentCommand;
3275
+ const sandboxDir = taskRuntime ? requestedSandboxDir : undefined;
3276
+ // Reservations prevent competing admissions, but do not grandfather
3277
+ // unstarted work after a cap reduction. No await separates this live
3278
+ // occupancy check, child creation, and the running metadata below.
3279
+ const maxConcurrent = activeConcurrencyCap();
3280
+ if (countRunning() >= maxConcurrent) {
3281
+ throw new Error(`Max concurrent subagents (${maxConcurrent}) reached. Stop or let some finish first.`);
3282
+ }
3283
+ // One writer per conversation, held across admission, child lifetime,
3284
+ // and finalization. A live duplicate continuation is refused instead of
3285
+ // letting two processes rewrite one session file. A fresh launch has a
3286
+ // brand-new native session id, so it cannot contend with anyone and
3287
+ // needs no lease; every continuation does.
3288
+ if (resume || managed) {
3289
+ lease = acquireConversationLease({ sessionId, attemptId: id });
3290
+ }
3291
+ // The lease is the first moment no other process can retire this
3292
+ // conversation: re-prove the history identity the cached plan was
3293
+ // built from, so `--session` can never reopen a file another sweep
3294
+ // removed as an empty replacement.
3295
+ if (resume)
3296
+ revalidateContinuationUnderLease(resume, callbackOrigin);
3297
+ const preflightPath = join(runDir(id), "child-preflight.json");
3298
+ writeFileSync(preflightPath, JSON.stringify({ ...fullResolution, model, tools: selectedTools,
3299
+ optionalTrustedTools,
3300
+ configSnapshot: configSnapshot([dirname(configPath()), join(cwd, ".pi")]),
3301
+ }));
3302
+ // Register the worker's bridge run before the child can start, so the
3303
+ // child's first handshake finds a bound run and its task authority is
3304
+ // already captured. A resume requires the bridge: without it the
3305
+ // attempt could not read evidence or acknowledge its wait.
3306
+ let workerBridge;
3307
+ if (assignment)
3308
+ registerAssignmentAttempt(assignment, id);
3309
+ if (bridgeEnabled) {
3310
+ const workerPolicy = captureWorkerPolicy({
3311
+ sandbox: sandboxEnabled,
3312
+ mandatoryPermissions: permissionPlan.enforced,
3313
+ tools: selectedTools,
3314
+ clean,
3315
+ workspace: cwd,
3316
+ authorityReference: "",
3317
+ // The assignment deadline the attempt was admitted with; a
3318
+ // continuation must not silently extend it.
3319
+ deadlineAt: resolveRunTiming({ params: launchTimingParams(p), settings: timingSettingsFor(cfg), env: process.env, startedAt: Date.now() }).deadlineAt ?? null,
3320
+ taskPolicy: taskRuntime?.policy ?? null,
3321
+ });
3322
+ const authorityReference = `worker-policy:${createHash("sha256")
3323
+ .update(JSON.stringify(workerPolicy))
3324
+ .digest("hex")
3325
+ .slice(0, 16)}`;
3326
+ // A resumed attempt keeps the owner captured at park time; a fresh
3327
+ // launch uses the active foreground binding.
3328
+ const owner = internal?.parkOwner ?? ownerBindingFromContext(ctx);
3329
+ try {
3330
+ const handle = await workerOperations.register({
3331
+ assignment,
3332
+ runId: id,
3333
+ conversationId: sessionId,
3334
+ workspace: cwd,
3335
+ authorityReference,
3336
+ branchId: owner.branchId,
3337
+ goalId: owner.goalId,
3338
+ policy: { ...workerPolicy, authorityReference },
3339
+ capabilities: bridgePlan.capabilities,
3340
+ tools: bridgePlan.tools,
3341
+ schemas: bridgePlan.tools.map((name) => productionBridgeSchemas.schemas.get(name)).filter(Boolean),
3342
+ attemptId: id,
3343
+ ...(lease?.token ? { writerLeaseId: lease.token } : {}),
3344
+ owner,
3345
+ });
3346
+ workerBridge = {
3347
+ env: { ...handle.env, ...childWriterLeaseEnv(lease?.token) },
3348
+ policy: workerPolicy,
3349
+ authorityReference,
3350
+ };
3351
+ }
3352
+ catch (error) {
3353
+ const reason = error instanceof Error ? error.message : String(error);
3354
+ // The child's loadout already promises the bridge (and a
3355
+ // sandboxed task policy would refuse to start without it), so a
3356
+ // registration failure refuses this launch instead of letting the
3357
+ // child run with tools that cannot work.
3358
+ if (internal?.resumeWait) {
3359
+ throw new PreSpawnResumeError(`Cannot resume this conversation without its operation bridge: ${reason}`);
3360
+ }
3361
+ throw new Error(`Cannot supervise this worker's background operations: ${reason}`);
3362
+ }
3363
+ }
3364
+ // Last gate before execution: the parent identity, Goal admission
3365
+ // revision, durable claim/token and current policy must all still hold.
3366
+ // The fence returns a synchronous release guard that is invoked with no
3367
+ // await between it and the spawn, so a cancellation or parent change
3368
+ // cannot hide inside a final asynchronous window.
3369
+ if (internal?.resumeWait && !resume?.prior.assignment)
3370
+ throw new PreSpawnResumeError("This legacy park has no verified assignment outcome recipient; refusing continuation on an unsupported binding.");
3371
+ if (!assignment && bridgeEnabled)
3372
+ throw new Error("Durable assignment outcomes require a recorded parent session and transcript capability.");
3373
+ if (internal?.resumeWait) {
3374
+ const captured = resume?.prior.operations?.policy;
3375
+ const currentSandbox = taskRuntime ? {
3376
+ root: taskRuntime.policy.root,
3377
+ ...(taskRuntime.policy.permissions ? { permissions: taskRuntime.policy.permissions } : {}),
3378
+ ...(taskRuntime.policy.denyWrite ? { denyWrite: [...taskRuntime.policy.denyWrite] } : {}),
3379
+ } : null;
3380
+ assertAssignmentPermissionScope(captured, { sandbox: currentSandbox, mandatoryPermissions: permissionPlan.enforced }, Boolean(managed));
3381
+ }
3382
+ // Freeze the ordinary recipe before the durable external-launch intent.
3383
+ const recipe = buildLaunchRecipe({
3384
+ ...(!legacyToolLoading ? { toolLoadingVersion: 1 } : {}),
3385
+ attemptId: id, sessionId, sessionDir: childSessionDir, cwd, model, effort: thinking,
3386
+ tools: callerLaunchTools(allow), excludeTools: requestedExcludes.size ? [...requestedExcludes].join(",") : undefined,
3387
+ ...(optionalTrustedTools.length ? { optionalTrustedTools } : {}),
3388
+ skills: skills.mode === "inherit" ? undefined : [...skills.paths], clean, allowNested, approve,
3389
+ sandbox: sandboxEnabled, sandboxDir: requestedSandboxDir, gitCloneWorkspace, callback: callbackEnabled, name: launchName,
3390
+ agent: resume ? resume.recipe.agent : p.agent, role: resume ? resume.recipe.role : p.role,
3391
+ alias: resume ? resume.recipe.alias : p.alias, catalog: launchCatalog, extensionArgs: extArgs, baseExtensionArgs,
3392
+ runtimeRoot: continuationRuntime?.root ?? managedRuntimeRoot(selfDir()),
3393
+ trustedExtensions: resume?.recipe.trustedExtensions ?? taskTools?.trusted.map(({ name, package: owner, loadPath }) => ({ name, package: owner, loadPath })),
3394
+ });
3395
+ const startedAt = Date.now();
3396
+ const meta = {
3397
+ assignment,
3398
+ outcomeSupport: { version: 1, available: Boolean(assignment), ...(!assignment ? { reason: "Legacy host has no verified parent session/transcript; durable assignment delivery is unavailable." } : {}) },
3399
+ id, name: launchName, status: "running",
3400
+ pid: 0, spawnPid: managed?.owner.pid ?? process.pid, spawnPidStartTime: managed?.owner.start ?? parentStartToken(), model,
3401
+ effort: thinking, cwd,
3402
+ ...(skills.mode === "inherit" ? {} : { skills: [...skills.paths] }),
3403
+ skillsSource: skills.source,
3404
+ promptPreview: p.prompt.slice(0, 200),
3405
+ startedAt, logPath: logPathFor(id), sessionId,
3406
+ rootRunId,
3407
+ ...(resume ? { resumedFrom: resume.prior.id } : {}),
3408
+ recipe,
3409
+ ...(managed ? { management: managed.identity } : {}),
3410
+ callbackOrigin,
3411
+ sandbox: sandboxDir, taskRuntime: Boolean(taskRuntime), taskScratch: taskRuntime?.policy.scratch, callback: callbackEnabled,
3412
+ ...batchInfo,
3413
+ // The launch record is JSON. Registry freezes that value; it does not
3414
+ // require the resolver's nominal type to carry an index signature.
3415
+ ...(launchCatalog ? { catalog: launchCatalog } : {}),
3416
+ // Supervised-operation binding (references only; the per-run bridge
3417
+ // token stays in the child environment and is never persisted).
3418
+ ...(workerBridge ? {
3419
+ operations: {
3420
+ version: 1,
3421
+ bridgeRunId: id,
3422
+ conversationId: sessionId,
3423
+ workspace: cwd,
3424
+ authorityReference: workerBridge.authorityReference,
3425
+ // Captured at park time for a resumed attempt; the worker
3426
+ // workspace above stays the actual task/sandbox root.
3427
+ ...(internal?.parkOwner
3428
+ ? { branchId: internal.parkOwner.branchId, goalId: internal.parkOwner.goalId }
3429
+ : {
3430
+ branchId: ownerBindingFromContext(ctx).branchId,
3431
+ goalId: ownerBindingFromContext(ctx).goalId,
3432
+ }),
3433
+ ...(internal?.launchToken ? { resumeLaunchToken: internal.launchToken } : {}),
3434
+ policy: {
3435
+ version: 1,
3436
+ mandatoryPermissions: workerBridge.policy.mandatoryPermissions,
3437
+ sandbox: workerBridge.policy.sandbox,
3438
+ tools: workerBridge.policy.tools,
3439
+ clean: workerBridge.policy.clean,
3440
+ deadlineAt: workerBridge.policy.deadlineAt,
3441
+ },
3442
+ tools: bridgePlan.tools,
3443
+ },
3444
+ } : {}),
3445
+ timing: resolveRunTiming({ params: launchTimingParams(p), settings: timingSettingsFor(cfg), env: process.env, startedAt }),
3446
+ };
3447
+ const dispatchGuard = await internal?.beforeSpawn?.({ runId: id, permissionPlan });
3448
+ const managedEnv = managed?.beforeSpawn({ id, sessionId, lease: lease.token, leasePath: lease.path,
3449
+ preflightPath, policyPath: taskRuntime?.policyPath, permissions: permissionPlan, recipe, recoveryMeta: meta });
3450
+ spawned = releaseChild(dispatchGuard, () => spawnDetached({ file: cmd.file, fileArgs: cmd.fileArgs, cwd, logPath: logPathFor(id),
3451
+ env: {
3452
+ [STEER_FILE_ENV]: steerPathFor(id),
3453
+ [PREFLIGHT_ENV]: preflightPath,
3454
+ ...(workerBridge?.env ?? {}),
3455
+ ...(managedEnv ?? {}),
3456
+ } }));
3457
+ managed?.spawned(id, spawned.pid);
3458
+ internal?.onSpawned?.();
3459
+ // Record process identity (pgid, start-time token) so health
3460
+ // reconciliation can tell a supervised child from a recycled pid
3461
+ // or an orphaned process group (#63). Best-effort: when the OS
3462
+ // probes are unavailable the fields stay absent and the run is
3463
+ // reconciled via the conservative old-metadata path.
3464
+ const identity = captureProcessIdentity(spawned.pid, spawnIdentityProbe);
3465
+ Object.assign(meta, { pid: spawned.pid, ...identity });
3466
+ // This instance holds the exit observer for a run it actually
3467
+ // started; only it can finalize on the exit event (#625).
3468
+ directlySupervisedRunIds.add(id);
3469
+ // A launch is live work of the current session, so an earlier
3470
+ // teardown of this instance no longer applies. Without this the
3471
+ // teardown latch would keep supervision from ever settling again
3472
+ // for a run started after it (#625).
3473
+ sessionTornDown = false;
3474
+ // Register exit supervision before any fallible post-spawn publication.
3475
+ // A failed metadata write must not strand a running child without a close
3476
+ // handler; the lease stays held until that child has actually exited.
3477
+ const exitCompletion = completeOwnedExit(spawned.exit, code => finalizeRun(pi, ctx, id, code), () => { lease?.release(); }, async () => {
3478
+ if (workerBridge)
3479
+ workerOperations.release(id, "attempt-exited");
3480
+ // Reconcile this attempt's earlier published writer before its
3481
+ // next park can admit another continuation of the conversation.
3482
+ if (internal?.resumeWait && resume)
3483
+ await settleResumedAttemptExit({
3484
+ attemptId: id,
3485
+ priorPark: { runId: resume.prior.id, ...internal.resumeWait },
3486
+ service: workerOperations.service,
3487
+ status: readMeta(id)?.status ?? "exited",
3488
+ // The exit handler releases the conversation writer lease just
3489
+ // above, before this call.
3490
+ writerLeaseReleased: true,
3491
+ notify: (message) => {
3492
+ try {
3493
+ uiCtx?.ui?.notify?.(message, "warning");
3494
+ }
3495
+ catch { /* ignore UI failures */ }
3496
+ },
3497
+ });
3498
+ await settleParkedExit(id);
3499
+ });
3500
+ managed?.observeExit?.(id, exitCompletion);
3501
+ writeMeta(meta);
3502
+ committed = true;
3503
+ // `meta.json` is now the record of this run; the claim has served its
3504
+ // purpose. Best effort: a leftover claim is inert while metadata exists.
3505
+ clearLaunchAttempt(id);
3506
+ uiCtx = ctx;
3507
+ ensureTicker();
3508
+ // Start periodic supervision reconciliation (self-stops when idle).
3509
+ ensureHealthTicker();
3510
+ // Footer hint: a visible run now exists, so `← background work · N` shows.
3511
+ updateNavigatorFooter(ctx);
3512
+ const toolSummary = taskTools ? describeTaskTools(taskTools) : undefined;
3513
+ const runtime = resolution.mode === "inherit"
3514
+ ? `Runtime: ALL installed extensions (inheritExtensions) — mid-turn drain risk\n`
3515
+ : toolSummary
3516
+ ? `Runtime: isolated · ${toolSummary}${resolution.specs.length ? ` · extensions ${resolution.specs.join(", ")}` : ""}\n`
3517
+ : resolution.specs.length
3518
+ ? `Runtime: isolated · extensions ${resolution.specs.join(", ")}\n`
3519
+ : `Runtime: isolated · built-in tools only\n`;
3520
+ const warn = (dropped.length ? `Task sandbox: ${dropped.map((tool) => `${tool.name} disabled (${withheldBridgeReasons.get(tool.name) ?? tool.reason})`).join("; ")}.\n` : "") +
3521
+ (!sandboxEnabled && resolution.unmapped.length
3522
+ ? `NOTE: no extension mapped for ${resolution.unmapped.join(", ")} — ` +
3523
+ `${resolution.unmapped.length > 1 ? "these tools" : "this tool"} will NOT exist in the child. ` +
3524
+ `Add a toolExtensions entry in config.json.\n`
3525
+ : "");
3526
+ const modelNote = catalogDefaultNote(resume ? undefined : p.catalog, model, thinking);
3527
+ // The resolved skill exposure rides with the runtime summary, which every
3528
+ // launch and continuation message already prints.
3529
+ const inventoryNote = taskRuntime?.policy.permissions?.processAccess === "read" &&
3530
+ !taskRuntime.policy.tools.includes("process_list") ? " process_list is not in this launch's tool loadout." : "";
3531
+ return { id, meta, spawned, runtime: `${runtime}${processPolicy}${inventoryNote}\n${describeSkillExposure(skills)}\n${meta.timing ? `${formatTimingLimits(meta.timing, startedAt)}\n` : ""}`, warn, sandboxDir, modelNote };
3532
+ }
3533
+ catch (error) {
3534
+ // A launch that never committed metadata is not a run: drop
3535
+ // everything the attempt created so the registry keeps no
3536
+ // unreadable record (#325, #332, #623). A continuation's session
3537
+ // directory belongs to the retained owner and a caller-chosen
3538
+ // `sandbox_dir` is never ours, so `discardFailedLaunch` only
3539
+ // removes this attempt's own paths. A child that already started
3540
+ // must not keep running unsupervised; its log goes with the
3541
+ // attempt, because a record without metadata can never be read.
3542
+ if (!committed) {
3543
+ const { abortUncommittedLaunch } = await import("./launch-abort.domain.mjs");
3544
+ await abortUncommittedLaunch(id, {
3545
+ child: spawned, lease,
3546
+ artifacts: { sessionDir: childSessionDir, workspaceDir: ownedCloneWorkspace, scratch: launchScratch },
3547
+ });
3548
+ }
3549
+ throw error;
3550
+ }
3551
+ }
3552
+ /**
3553
+ * Finalize a parked attempt after its child exited.
3554
+ *
3555
+ * The bridge staged the verified checkpoint while the child was still alive;
3556
+ * this is where Background receives the three-fact exit proof
3557
+ * (checkpoint recorded, writer lease released, original writer gone) and the
3558
+ * durable wait leaves `parking`. A park that cannot be proven holds the
3559
+ * generation instead of leaving a resume armed for supervision that stopped.
3560
+ */
3561
+ async function settleParkedExit(id) {
3562
+ try {
3563
+ const result = await finalizeWorkerParkAfterExit({
3564
+ runId: id,
3565
+ service: workerOperations.service,
3566
+ // The exit handler calls this after `lease?.release()`.
3567
+ writerLeaseReleased: true,
3568
+ });
3569
+ if (result.outcome === "held" && result.reason) {
3570
+ try {
3571
+ uiCtx?.ui?.notify?.(`Subagent ${id} park held: ${result.reason}`, "warning");
3572
+ }
3573
+ catch { /* ignore UI failures */ }
3574
+ }
3575
+ else if (result.outcome === "parked" && result.wait?.phase === "ready" && resumeOrchestration) {
3576
+ // The dependency settled while this attempt was exiting: the ready
3577
+ // delivery may already have been dispatched, but reconcile it here.
3578
+ const park = parkedWaitForRun(id);
3579
+ if (park)
3580
+ void resumeOrchestration.resume(park);
3581
+ }
3582
+ }
3583
+ catch {
3584
+ // The durable park record still shows the staged state; reconciliation
3585
+ // at the next session start retries the proof.
3586
+ }
3587
+ finally {
3588
+ syncHealthTicker();
3589
+ }
3590
+ }
3591
+ /**
3592
+ * Launch one automatic continuation of a parked conversation.
3593
+ *
3594
+ * Everything below is the ordinary continuation admission path
3595
+ * (`planContinuation` → `spawnSubagentRun`), reused unchanged: native session,
3596
+ * frozen recipe, current mandatory permissions, capacity, writer lease. Only
3597
+ * the attempt id/token come from the durable park record written before this
3598
+ * call; every failure is classified as pre-spawn (releasable) or ambiguous
3599
+ * (must be held).
3600
+ */
3601
+ async function launchParkedResume(input) {
3602
+ const ctx = managed?.continuationContext?.() ?? uiCtx;
3603
+ if (!ctx || sessionTornDown) {
3604
+ throw new PreSpawnResumeError("No active foreground session can resume the parked assignment.");
3605
+ }
3606
+ const prior = readMeta(input.park.runId);
3607
+ if (!prior)
3608
+ throw new PreSpawnResumeError(`Cannot resume ${input.park.runId}: its run record is gone.`);
3609
+ const now = Date.now();
3610
+ if (prior.timing?.deadlineAt !== undefined && now >= prior.timing.deadlineAt) {
3611
+ throw new PreSpawnResumeError(`Cannot resume ${input.park.runId}: its assignment deadline passed while it was parked. The wait is held for the owner.`);
3612
+ }
3613
+ let plan;
3614
+ try {
3615
+ plan = planContinuation({
3616
+ id: prior.id,
3617
+ prior,
3618
+ origin: { cwd: input.park.record.ownerWorkspace ?? prior.callbackOrigin?.cwd ?? prior.cwd, sessionId: input.park.record.ownerSessionId ?? prior.callbackOrigin?.sessionId },
3619
+ others: listMetas({ includeArchived: false }),
3620
+ });
3621
+ }
3622
+ catch (error) {
3623
+ throw new PreSpawnResumeError(error instanceof Error ? error.message : String(error));
3624
+ }
3625
+ const owner = {
3626
+ sessionId: input.park.record.ownerSessionId ?? prior.callbackOrigin?.sessionId ?? "",
3627
+ workspace: input.park.record.ownerWorkspace ?? prior.callbackOrigin?.cwd ?? prior.cwd,
3628
+ branchId: input.park.record.ownerBranchId ?? null,
3629
+ goalId: input.park.record.ownerGoalId ?? null,
3630
+ };
3631
+ const target = plan;
3632
+ let spawned = false;
3633
+ try {
3634
+ await spawnSubagentRun(ctx, {
3635
+ prompt: resumePrompt(input.park),
3636
+ session_id: plan.conversation.sessionId,
3637
+ callback: prior.callback ?? true,
3638
+ ...continuationTiming(prior),
3639
+ }, undefined, plan, {
3640
+ assignedRunId: input.assignedRunId,
3641
+ launchToken: input.launchToken,
3642
+ // Marks this launch as an automatic resume: it may continue a
3643
+ // conversation whose wait is still pending, which a manual
3644
+ // continuation is refused until it takes over.
3645
+ resumeWait: { waitId: input.park.waitId, generation: input.park.generation },
3646
+ // The bridge registration and meta.operations must describe the
3647
+ // owner captured when the worker parked, not the foreground
3648
+ // branch as it stands after the parent's later model turn.
3649
+ parkOwner: owner,
3650
+ // Final dispatch fence: extension resolution, permission
3651
+ // re-resolution, the bridge registration and the writer lease
3652
+ // all happened above. Nothing may have changed since admission.
3653
+ beforeSpawn: ({ permissionPlan }) => assertFinalResumeDispatch({
3654
+ pi,
3655
+ rpc: workerOperations.rpc,
3656
+ // Getter, not a captured value: the foreground context can be
3657
+ // replaced during the asynchronous preparation.
3658
+ service: () => workerOperations.service,
3659
+ context: () => managed?.continuationContext?.() ?? uiCtx,
3660
+ park: input.park,
3661
+ claim: input.claim,
3662
+ owner,
3663
+ admissionRevision: input.admissionRevision,
3664
+ permissionsUnchanged: () => samePermissionPlan(permissionPlan, resolveSubagentPermissions(pi, undefined, { runId: target.prior.id, sandbox: target.recipe.sandbox })),
3665
+ capacityAvailable: () => resumeCapacity().recheck(),
3666
+ }),
3667
+ onSpawned: () => { spawned = true; },
3668
+ });
3669
+ }
3670
+ catch (error) {
3671
+ // A child that exists is ambiguous: the coordinator holds the claim
3672
+ // and the next reconciliation must not launch a second execution.
3673
+ if (spawned)
3674
+ throw error;
3675
+ throw error instanceof PreSpawnResumeError
3676
+ ? error
3677
+ : new PreSpawnResumeError(error instanceof Error ? error.message : String(error));
3678
+ }
3679
+ }
3680
+ /**
3681
+ * Compare two permission resolutions by value. A changed worker authority
3682
+ * during preparation (tightened or relaxed) invalidates the admission and
3683
+ * requires a fresh launch decision.
3684
+ */
3685
+ function samePermissionPlan(left, right) {
3686
+ const canonical = (value) => {
3687
+ const sort = (input) => {
3688
+ if (Array.isArray(input))
3689
+ return input.map(sort);
3690
+ if (input && typeof input === "object") {
3691
+ return Object.fromEntries(Object.keys(input).sort()
3692
+ .map((key) => [key, sort(input[key])]));
3693
+ }
3694
+ return input;
3695
+ };
3696
+ return JSON.stringify(sort(value));
3697
+ };
3698
+ // Describe provenance to the caller, but fence on authority, not its display label.
3699
+ const { activationSource: _leftSource, ...leftAuthority } = left;
3700
+ const { activationSource: _rightSource, ...rightAuthority } = right;
3701
+ return canonical(leftAuthority) === canonical(rightAuthority);
3702
+ }
3703
+ /** Preserve the original assignment deadline across parking; never extend it. */
3704
+ function continuationTiming(prior) {
3705
+ const timing = prior.timing;
3706
+ if (!timing)
3707
+ return {};
3708
+ return continuationTimingParams(timing, Date.now());
3709
+ }
3710
+ /**
3711
+ * Capacity admission for an automatic resume. The ordinary shared gate is
3712
+ * reserved before any durable pre-spawn record, so a saturated pool leaves the
3713
+ * generation ready (delivery is retried) instead of publishing an
3714
+ * unresumable claim; the recheck covers a cap reduced in the meantime.
3715
+ */
3716
+ function resumeCapacity() {
3717
+ const gate = capacityGate;
3718
+ return {
3719
+ tryReserve: () => gate().tryReserve(1, activeConcurrencyCap()),
3720
+ recheck: () => countRunning() + gate().pending <= activeConcurrencyCap(),
3721
+ commit: () => gate().commit(1),
3722
+ release: () => gate().release(1),
3723
+ };
3724
+ }
3725
+ /** Create the resume orchestration lazily (needs an active foreground context). */
3726
+ function ensureResumeOrchestration() {
3727
+ resumeOrchestration ??= createResumeOrchestration({
3728
+ pi,
3729
+ leaseOwnerId: managed ? `managed-subagents:${managed.identity.instance}` : undefined,
3730
+ service: () => workerOperations.service,
3731
+ rpc: workerOperations.rpc,
3732
+ context: () => managed?.continuationContext?.() ?? uiCtx,
3733
+ ...(managed?.dispatchContinuation ? { dispatch: managed.dispatchContinuation } : {}),
3734
+ capacity: resumeCapacity(),
3735
+ launch: launchParkedResume,
3736
+ stopAttempt: stopPublishedAttempt,
3737
+ notifyWhen: (meta) => Boolean(activeCallbackOrigin && belongsToOrigin(meta, activeCallbackOrigin)),
3738
+ notify: notifyOwnedWait,
3739
+ });
3740
+ return resumeOrchestration;
3741
+ }
3742
+ /**
3743
+ * Start the supervised-worker path: the local bridge host plus reconciliation
3744
+ * of parked generations left by a previous session. Nothing here runs when the
3745
+ * Background service is absent.
3746
+ */
3747
+ async function startWorkerOperations() {
3748
+ const ready = await workerOperations.start();
3749
+ if (!ready)
3750
+ return;
3751
+ const service = workerOperations.service;
3752
+ if (!service)
3753
+ return;
3754
+ const orchestration = ensureResumeOrchestration();
3755
+ try {
3756
+ // Register the continuation adapter first: Background refuses to
3757
+ // register a park wait without one, and ready deliveries are dispatched
3758
+ // to exactly this adapter.
3759
+ service.registerContinuationAdapter(orchestration.adapter);
3760
+ }
3761
+ catch { /* a host that refuses the adapter leaves parking unavailable */ }
3762
+ try {
3763
+ const reconciliation = reconcileParkedWaits(service, {
3764
+ resume: (park) => orchestration.resume(park),
3765
+ notifyWhen: (meta) => Boolean(activeCallbackOrigin && belongsToOrigin(meta, activeCallbackOrigin)),
3766
+ notify: notifyOwnedWait,
3767
+ });
3768
+ if (managed) {
3769
+ void reconciliation.catch(() => undefined);
3770
+ return;
3771
+ }
3772
+ await reconciliation;
3773
+ const historical = historicalWaits(activeCallbackOrigin);
3774
+ if (historical.length && activeCallbackOrigin && !attentionDismissed(activeCallbackOrigin.cwd, attentionRevision(historical))) {
3775
+ uiCtx?.ui?.notify?.(`${historical.length} historical subagent waits remain. Inspect or cancel with /subagents history; dismiss this notice with /subagents history dismiss.`, "warning");
3776
+ }
3777
+ }
3778
+ catch { /* reconciliation retries on the next session start */ }
3779
+ }
3780
+ // ---- subagent_spawn -------------------------------------------------
3781
+ //
3782
+ // One tool launches both fresh work and a continuation of saved work. A
3783
+ // continuation is an ORDINARY attempt of the SAME saved conversation: a new
3784
+ // run id, the prior native session id, the exact saved session file, and the
3785
+ // frozen launch recipe. Old logs/results/callbacks/timing stay under their
3786
+ // own attempt id. Nothing stays alive between attempts, so a parked
3787
+ // conversation occupies zero capacity slots. `session_id` (not the run id)
3788
+ // selects the conversation, and the latest attempt is always the one that
3789
+ // owns it.
3790
+ const acceptanceSpawnTool = {
3791
+ name: "subagent_spawn",
3792
+ label: "Spawn Subagent",
3793
+ description: "Launch a task in a background pi subagent (a detached `pi -p` process) and return " +
3794
+ "IMMEDIATELY with a run id. The foreground session stays free. Completion is reported " +
3795
+ "later on the user's next turn — never wait or poll for it.",
3796
+ promptSnippet: "Delegate a task to a background subagent that runs without blocking you",
3797
+ promptGuidelines: [
3798
+ "When delegation is permitted by the active mode, use subagent_spawn for assigned work that can run independently. It returns at once with a run id; report the id and continue.",
3799
+ "After subagent_spawn, do NOT call subagent_output or subagent_result in a loop to wait for the result, and do NOT sleep. The run completes on its own and reports back on the next turn.",
3800
+ "Call subagent_result after a completion or attention callback, or when the user explicitly asks for the result. Use subagent_output only when the user explicitly asks how a run is progressing; never use either tool to poll.",
3801
+ ...SUBAGENT_ORCHESTRATION_GUIDELINES,
3802
+ "The tools param is both the tool allowlist AND what determines which extensions load in the child (e.g. tools='read,bash,web_fetch' loads only the web-tools package). Ask for the tools the task needs and nothing more; clean:true gives a built-ins-only child. When the task already names its SKILL.md by path, pass skills with those absolute paths (or [] for none) so the child does not advertise the whole skills catalog. Without an agent or role, pick a model with the model param (e.g. 'xai/grok-4.5@high'); providerless model patterns are resolved by Pi, while provider/model is deterministic and loads mapped provider extensions.",
3803
+ ...CATALOG_GUIDELINES,
3804
+ "Subagent sandboxing defaults to off. Human settings in /sandbox control file, credential-file, command, and network permissions; sandbox:false cannot override an enabled human profile. Set sandbox:true to request kernel confinement, including without published settings. Set callback:false to finish quietly — then read the result on demand via subagent_result.",
3805
+ "Every launch automatically joins one shared harness-owned watcher, including batch launches; it stops when the last active run ends. Do not start a separate heartbeat or background watcher for subagents. A tool call still open for tool_wait_minutes (default 5) or no progress for stuck_minutes (default 10) sends one factual alert; these alerts never stop, cancel, or restart the run. Hard timeouts default to 60 minutes; max_minutes overrides that default (0 disables). Soft deadlines remain opt-in for work with a real wall-clock bound: deadline_minutes steers the child to wrap up and later stops it after grace_minutes, while max_minutes stops it without grace. Do not set elapsed-time limits merely because a task may take a while; use them only when the work needs a real wall-clock bound.",
3806
+ "Use git_clone_workspace:true when the subagent will mutate Git in a sandbox. The parent prepares a disposable, self-contained clone with a real .git/ directory inside the sandbox root, so linked-worktree metadata outside the sandbox cannot stall the child.",
3807
+ "Saved conversations persist automatically. To continue a completed or stopped worker in its own history, call subagent_spawn with session_id (the native session id reported for the saved conversation) and the new feedback as prompt. Omit session_id for a brand-new conversation.",
3808
+ "On a continuation, pass prompt, session_id, and only optional model, thinking, callback, or timing overrides. Launch-only options (name, agent, role, alias, tools, exclude_tools, skills, clean, sandbox, sandbox_dir, cwd, git_clone_workspace, approve, allow_nested) keep the saved recipe; repeat them only with the same value, otherwise the launch is refused.",
3809
+ "Do not restate the original task or role when continuing: they already live in the saved conversation. A running or orphaned latest attempt blocks continuation until it stops, and missing saved history is refused rather than recreated.",
3810
+ ],
3811
+ parameters: Type.Object({
3812
+ prompt: Type.String({ description: "The task for the subagent. This is the only context it gets — be self-contained. On a continuation this is the next user turn; the original task and role stay in saved history." }),
3813
+ session_name: Type.Optional(Type.String({ description: "Exact name of one saved conversation in the current folder and descendants. Alternative to session_id. Duplicate names report matching session ids instead of choosing a conversation." })),
3814
+ session_id: Type.Optional(Type.String({ description: "Native session id of a saved conversation to continue (reported for every launch and attempt). Omit to start a new conversation. A continuation gets a new run id but keeps this session id, history, workspace, and frozen launch recipe." })),
3815
+ name: Type.Optional(Type.String({ description: "Short label for the run (e.g. 'reviewer'). Ignored when agent or role is set, except as the direct-role alias when alias is omitted." })),
3816
+ agent: Type.Optional(Type.String({ description: "Named agent id (agent.<slug>). Mutually exclusive with role. The navigator shows the defined agent name." })),
3817
+ role: catalogRoleSchema("direct role launch"),
3818
+ alias: Type.Optional(Type.String({ description: "Per-run display alias for a direct role launch, such as checkout. Not a reusable agent. Colliding aliases gain a numeric suffix." })),
3819
+ model: Type.Optional(Type.String({ description: "Pi model pattern, preferably provider/id, optionally suffixed with @effort (for example openai/gpt-5.5@high). Providerless patterns are resolved by Pi. Omit to use the agent or role default; without one, inherit the foreground model. Put authoritative model choices here; do not rely on prompt text." })),
3820
+ thinking: Type.Optional(Type.String({ description: "Reasoning effort for the child: off, minimal, low, medium, high, xhigh, or max. Omit to use the agent or role default; without one, the Pi/model default." })),
3821
+ tools: Type.Optional(Type.String({ description: "Tool allowlist: comma-separated names the child may use (e.g. 'read,bash,web_fetch'). This ALSO selects which extensions load — only packages backing a requested tool are loaded. Defaults to the configured safe set." })),
3822
+ exclude_tools: Type.Optional(Type.String({ description: "Comma-separated tool denylist, applied on top of the allowlist." })),
3823
+ skills: Type.Optional(Type.Array(Type.String(), { description: "Skill exposure for the child. Omit to inherit the catalog role/agent choice, then config defaultSkills, then user-catalog discovery. [] loads no skills (--no-skills). Absolute paths load exactly those skills (--no-skills --skill <path>), which is how a task that names one SKILL.md by path avoids advertising the whole catalog. Relative paths resolve against the child workspace." })),
3824
+ clean: Type.Optional(Type.Boolean({ description: "Run a hermetic child with NO extensions at all (only built-ins: read, bash, edit, write). Default false — the extensions backing the requested tools load, so web_fetch and model auth (e.g. xai) work." })),
3825
+ sandbox: Type.Optional(Type.Boolean({ description: "Use the human Subagents profile from /sandbox. Defaults to off without published settings. True requests kernel confinement; false cannot bypass an enabled human profile." })),
3826
+ sandbox_dir: Type.Optional(Type.String({ description: "Confine writes to (and run the child in) this directory instead of the working dir. Created if missing." })),
3827
+ callback: Type.Optional(Type.Boolean({ description: "Default TRUE: on completion, trigger a turn that calls subagent_result and presents the result. Set false to finish quietly — the result is then read on demand via subagent_result." })),
3828
+ cwd: Type.Optional(Type.String({ description: "Working directory (default: current)." })),
3829
+ git_clone_workspace: Type.Optional(Type.Boolean({ description: "Prepare a disposable Git clone workspace for sandboxed Git-mutating subagents. The clone has a real .git/ directory inside the sandbox writable root and is self-contained after setup." })),
3830
+ approve: Type.Optional(Type.Boolean({ description: "Trust project-local files in the child (default: false; headless runs cannot prompt for trust)." })),
3831
+ allow_nested: Type.Optional(Type.Boolean({ description: "Allow the child to spawn its own subagents (default: false). Loads this extension in the child and allowlists its tools." })),
3832
+ ...timingSchemaFields(),
3833
+ }),
3834
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
3835
+ const p = { ...params };
3836
+ p.session_id = requestedSessionId(p, ctx.cwd);
3837
+ if (p.prompt.trim() === "")
3838
+ throw new Error("prompt is empty.");
3839
+ if (p.session_id !== undefined && (typeof p.session_id !== "string" || p.session_id.trim() === "")) {
3840
+ throw new Error("session_id must be a non-empty native session id.");
3841
+ }
3842
+ assertNoRetiredLaunchOptions(p);
3843
+ // A present-but-blank role or agent is a mistake, not a request for a catalog-free child.
3844
+ const blankSelector = blankCatalogSelector(p);
3845
+ if (blankSelector)
3846
+ throw new Error(blankSelector);
3847
+ const maxConcurrent = activeConcurrencyCap();
3848
+ // Shared with batch-spawn: reserve before any async work so an interleaved
3849
+ // batch cannot oversubscribe after this check and before writeMeta.
3850
+ const gate = capacityGate();
3851
+ if (!gate.tryReserve(1, maxConcurrent)) {
3852
+ throw new Error(`Max concurrent subagents (${maxConcurrent}) reached. Stop or let some finish first.`);
3853
+ }
3854
+ let reserved = 1;
3855
+ try {
3856
+ if (p.session_id !== undefined) {
3857
+ // Continue a saved conversation. The same capacity, permission,
3858
+ // lease, callback, and finalization path runs as for a fresh
3859
+ // launch; only the conversation and recipe are inherited. The
3860
+ // catalog is never re-resolved for a saved conversation.
3861
+ const plan = continuationPlanFor(p.session_id, verifiedOriginFromContext(ctx) ?? activeCallbackOrigin);
3862
+ assertContinuationLaunchOptions(p, plan.recipe, "");
3863
+ const continuation = {
3864
+ prompt: p.prompt,
3865
+ model: p.model,
3866
+ thinking: p.thinking,
3867
+ callback: p.callback,
3868
+ deadline_minutes: p.deadline_minutes,
3869
+ grace_minutes: p.grace_minutes,
3870
+ max_minutes: p.max_minutes,
3871
+ tool_wait_minutes: p.tool_wait_minutes,
3872
+ stuck_minutes: p.stuck_minutes,
3873
+ };
3874
+ const { id, spawned, runtime, warn, sandboxDir, modelNote } = await spawnSubagentRun(ctx, continuation, undefined, plan);
3875
+ gate.commit(1);
3876
+ reserved = 0;
3877
+ return {
3878
+ content: [{ type: "text", text: `Subagent continued: ${plan.recipe.name ? `${plan.recipe.name} ` : ""}id=${id} (pid ${spawned.pid}) from ${plan.prior.id}${plan.prior.status === "killed" ? " (interrupted attempt)" : ""}.\n` +
3879
+ `Conversation: session ${plan.conversation.sessionId} — pass session_id=${plan.conversation.sessionId} for the next follow-up.\n` +
3880
+ (modelNote ? `${modelNote[0].toUpperCase()}${modelNote.slice(1)}.\n` : "") +
3881
+ (continuation.callback === false
3882
+ ? `Running in the background; the foreground is free. It will finish quietly — read the result with subagent_result id=${id}.\n`
3883
+ : `Running in the background; the foreground is free. Its result will be posted back here when it finishes.\n`) +
3884
+ (sandboxDir ? `Sandboxed: project root ${sandboxDir}; current launch permissions apply.\n` : "") +
3885
+ runtime + warn +
3886
+ `Log: ${logPathFor(id)}`,
3887
+ }],
3888
+ details: {
3889
+ status: "continued",
3890
+ launched: true,
3891
+ priorId: plan.prior.id,
3892
+ runId: id,
3893
+ sessionId: plan.conversation.sessionId,
3894
+ rootRunId: plan.rootRunId,
3895
+ },
3896
+ };
3897
+ }
3898
+ const catalog = await admitCatalog(ctx, [p]);
3899
+ if (catalog.status === "clarification-needed") {
3900
+ gate.release(1);
3901
+ reserved = 0;
3902
+ return catalogResult(catalog);
3903
+ }
3904
+ if (catalog.jobs.length > 1) {
3905
+ const extra = catalog.jobs.length - 1;
3906
+ if (extra > 0 && !gate.tryReserve(extra, activeConcurrencyCap())) {
3907
+ gate.release(1);
3908
+ reserved = 0;
3909
+ throw new Error(`Choosing split needs ${catalog.jobs.length} subagent slots, but only one was free. Nothing was launched.`);
3910
+ }
3911
+ reserved += extra;
3912
+ const launched = [];
3913
+ for (const job of catalog.jobs) {
3914
+ const { id, modelNote } = await spawnSubagentRun(ctx, job);
3915
+ gate.commit(1);
3916
+ reserved -= 1;
3917
+ launched.push({ name: job.name, id, modelNote });
3918
+ }
3919
+ return {
3920
+ content: [{ type: "text", text: launched.map((item) => `Subagent launched: ${item.name ? `${item.name} ` : ""}id=${item.id} (session ${item.id}).${item.modelNote ? ` ${item.modelNote}.` : ""}`).join("\n") }],
3921
+ details: { status: "launched", launched: true, runIds: launched.map((item) => item.id) },
3922
+ };
3923
+ }
3924
+ Object.assign(p, catalog.jobs[0]);
3925
+ const { id, meta, spawned, runtime, warn, sandboxDir, modelNote } = await spawnSubagentRun(ctx, p);
3926
+ gate.commit(1);
3927
+ reserved = 0;
3928
+ return {
3929
+ content: [{ type: "text", text: `Subagent launched: ${p.name ? `${p.name} ` : ""}id=${id} (pid ${spawned.pid}).\n` +
3930
+ `Session: ${meta.sessionId} — pass it as session_id to continue this conversation.\n` +
3931
+ (modelNote ? `${modelNote[0].toUpperCase()}${modelNote.slice(1)}.\n` : "") +
3932
+ (p.callback === false
3933
+ ? `Running in the background; the foreground is free. It will finish quietly — read the result with subagent_result id=${id}.\n`
3934
+ : `Running in the background; the foreground is free. Its result will be posted back here when it finishes.\n`) +
3935
+ (sandboxDir ? `Sandboxed: project root ${sandboxDir}; launch permissions apply.\n` : "") +
3936
+ runtime + warn +
3937
+ `Log: ${logPathFor(id)}`,
3938
+ }],
3939
+ details: { status: "launched", launched: true, runId: id, sessionId: meta.sessionId },
3940
+ };
3941
+ }
3942
+ catch (err) {
3943
+ if (reserved === 1)
3944
+ gate.release(1);
3945
+ else if (reserved > 0)
3946
+ gate.release(reserved);
3947
+ throw err;
3948
+ }
3949
+ },
3950
+ };
3951
+ acceptanceSpawnToolRef = acceptanceSpawnTool;
3952
+ registerSpawnTool(acceptanceSpawnTool);
3953
+ // ---- subagent_spawn_batch -------------------------------------------
3954
+ registerSpawnTool({
3955
+ name: "subagent_spawn_batch",
3956
+ label: "Spawn Subagent Batch",
3957
+ description: "Launch several independent background pi subagents at once. Each job becomes a " +
3958
+ "normal subagent run with its own run id, process, log, and metadata. " +
3959
+ "'shared' options are applied to every job; per-job options override them. " +
3960
+ "Codemode callers receive a structured launch receipt: status, batchId when assigned, " +
3961
+ "and launched, failed, skipped arrays with 1-based effective job positions (after any confirmed role split). Inspect all arrays; " +
3962
+ "a returned receipt is not proof that every job launched or completed. " +
3963
+ "Await the launch call and preserve its receipt. Script cancellation does not stop launched runs; use subagent_stop.",
3964
+ outputSchema: batchLaunchOutputSchema,
3965
+ promptSnippet: "Launch a batch of background subagents at once",
3966
+ promptGuidelines: [
3967
+ "When delegation is permitted by the active mode, use subagent_spawn_batch for several independent assigned tasks. It returns immediately with a batch id and one run id per launched job.",
3968
+ "Each job is a normal subagent run; use subagent_result / subagent_output / subagent_stop with the individual run ids just like subagent_spawn.",
3969
+ "Do NOT poll for results. Each job reports back on its own when it finishes.",
3970
+ ...SUBAGENT_ORCHESTRATION_GUIDELINES,
3971
+ "By default the whole batch is rejected if there is not enough capacity. Set onCapacity to 'launch-available' to launch as many as fit and report the rest as skipped.",
3972
+ ...CATALOG_GUIDELINES,
3973
+ "Per-job agent, role, alias, model, and thinking override shared. One batch refreshes the catalog once and every job uses that snapshot. Jobs are resolved independently.",
3974
+ ],
3975
+ parameters: Type.Object({
3976
+ batchName: Type.Optional(Type.String({ description: "Optional display label for the batch." })),
3977
+ shared: Type.Optional(Type.Object({
3978
+ name: Type.Optional(Type.String({ description: "Label applied to jobs that do not set their own. Direct-role alias when alias is omitted." })),
3979
+ agent: Type.Optional(Type.String({ description: "Named agent id applied to jobs that do not select their own agent or role." })),
3980
+ role: catalogRoleSchema("shared role selector"),
3981
+ alias: Type.Optional(Type.String({ description: "Direct-role alias applied when a job does not set alias." })),
3982
+ model: Type.Optional(Type.String({ description: "Pi model pattern, preferably provider/id, optionally suffixed with @effort. Omit to use the agent or role default; without one, inherit the foreground model. Put authoritative model choices here; prompt text is not parsed." })),
3983
+ thinking: Type.Optional(Type.String({ description: "Reasoning effort applied to every job: off, minimal, low, medium, high, xhigh, or max." })),
3984
+ tools: Type.Optional(Type.String({ description: "Tool allowlist applied to every job." })),
3985
+ exclude_tools: Type.Optional(Type.String({ description: "Comma-separated tool denylist applied to every job." })),
3986
+ skills: Type.Optional(Type.Array(Type.String(), { description: "Skill exposure applied to every job. Per-job skills override this. [] loads no skills; absolute paths load exactly those skills; omit to inherit discovery." })),
3987
+ sandbox: Type.Optional(Type.Boolean({ description: "Use the human Subagents profile; false cannot override an enabled profile. Defaults to off without published settings; true requests kernel confinement." })),
3988
+ sandbox_dir: Type.Optional(Type.String({ description: "Writable root for every job." })),
3989
+ callback: Type.Optional(Type.Boolean({ description: "Default TRUE: post result back on completion." })),
3990
+ clean: Type.Optional(Type.Boolean({ description: "Hermetic builtins-only child; no extensions load." })),
3991
+ cwd: Type.Optional(Type.String({ description: "Working directory (default: current)." })),
3992
+ git_clone_workspace: Type.Optional(Type.Boolean({ description: "Prepare a disposable Git clone workspace for each job (same semantics as subagent_spawn)." })),
3993
+ approve: Type.Optional(Type.Boolean({ description: "Trust project-local files in children." })),
3994
+ allow_nested: Type.Optional(Type.Boolean({ description: "Allow children to spawn their own subagents." })),
3995
+ ...timingSchemaFields(),
3996
+ }, { description: "Options applied to every job; per-job values override these. session_id is per job and is never inherited from shared, because one shared conversation would make every job compete for the same writer." })),
3997
+ jobs: Type.Array(Type.Object({
3998
+ prompt: Type.String({ description: "The task for this job. On a continuation this is the next user turn." }),
3999
+ session_name: Type.Optional(Type.String({ description: "Exact saved conversation name in the current folder and descendants. Per job only; alternative to session_id. Ambiguous names refuse with matching session ids." })),
4000
+ session_id: Type.Optional(Type.String({ description: "Native session id of a saved conversation this JOB continues. Per job only, never shared. Omit for a new conversation. A continuation keeps its saved history, workspace, and frozen recipe, and accepts only model/thinking/callback/timing overrides." })),
4001
+ name: Type.Optional(Type.String({ description: "Short label for this job. Direct-role alias when alias is omitted." })),
4002
+ agent: Type.Optional(Type.String({ description: "Named agent id for this job. Overrides shared agent and role." })),
4003
+ role: catalogRoleSchema("batch job"),
4004
+ alias: Type.Optional(Type.String({ description: "Direct-role alias for this job." })),
4005
+ model: Type.Optional(Type.String()),
4006
+ thinking: Type.Optional(Type.String()),
4007
+ tools: Type.Optional(Type.String()),
4008
+ exclude_tools: Type.Optional(Type.String()),
4009
+ skills: Type.Optional(Type.Array(Type.String())),
4010
+ sandbox: Type.Optional(Type.Boolean()),
4011
+ sandbox_dir: Type.Optional(Type.String()),
4012
+ callback: Type.Optional(Type.Boolean()),
4013
+ clean: Type.Optional(Type.Boolean()),
4014
+ cwd: Type.Optional(Type.String()),
4015
+ git_clone_workspace: Type.Optional(Type.Boolean()),
4016
+ approve: Type.Optional(Type.Boolean()),
4017
+ allow_nested: Type.Optional(Type.Boolean()),
4018
+ ...timingSchemaFields(),
4019
+ }, { description: "A single batch job." }), {
4020
+ minItems: 1,
4021
+ description: "One or more jobs to launch. Each must have a prompt.",
4022
+ }),
4023
+ onCapacity: Type.Optional(Type.String({ description: 'Capacity behavior: "reject" (default) or "launch-available".' })),
4024
+ }),
4025
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
4026
+ const p = params;
4027
+ const cfg = loadConfig();
4028
+ const launchAvailable = p.onCapacity === "launch-available";
4029
+ // Shared with single-spawn. Reservations count against maxConcurrent so a
4030
+ // concurrent single spawn cannot take a slot the batch already admitted.
4031
+ const gate = capacityGate();
4032
+ // session_id selects one saved conversation, so it is per job: a shared
4033
+ // value would point every job at the same conversation writer.
4034
+ if (p.shared?.session_name !== undefined)
4035
+ throw new Error("session_name is per job, never shared.");
4036
+ if (p.shared?.session_id !== undefined) {
4037
+ throw new Error("session_id is per job: set jobs[i].session_id for the jobs that continue a saved conversation; shared has no session_id.");
4038
+ }
4039
+ assertNoRetiredLaunchOptions(p.shared, "shared: ");
4040
+ p.jobs.forEach((job, index) => assertNoRetiredLaunchOptions(job, `jobs[${index}]: `));
4041
+ validateBatchPlan({ shared: p.shared, jobs: p.jobs, onCapacity: p.onCapacity, config: cfg });
4042
+ // A present-but-blank role or agent rejects the whole batch before any launch.
4043
+ const blankSelector = blankCatalogSelector(p.shared, "shared")
4044
+ ?? p.jobs.map((job, index) => blankCatalogSelector(job, `jobs[${index}]`)).find(Boolean);
4045
+ if (blankSelector)
4046
+ throw new Error(blankSelector);
4047
+ let catalogSnapshot;
4048
+ let catalogHost;
4049
+ const needsCatalog = p.jobs.some((job) => job.session_id === undefined && job.session_name === undefined
4050
+ && hasCatalogSelector(mergeJobOptions(p.shared, job)));
4051
+ if (needsCatalog) {
4052
+ catalogHost = catalogHostFrom(ctx);
4053
+ noteCatalogHost(catalogHost);
4054
+ catalogSnapshot = managed ? await managed.snapshot(catalogHost) : await loadSharedLaunchSnapshot(catalogHost);
4055
+ const clarified = await clarifyCatalogRequest(p.jobs.map((job) => mergeJobOptions(p.shared, job)), { hasUI: catalogHost.hasUI === true, select: catalogHost.select });
4056
+ if (clarified.status === "clarification-needed")
4057
+ return {
4058
+ ...catalogResult(clarified),
4059
+ structuredContent: {
4060
+ status: "clarification-needed",
4061
+ message: clarified.message,
4062
+ choices: [...clarified.choices],
4063
+ launched: [],
4064
+ failed: [],
4065
+ skipped: [],
4066
+ },
4067
+ };
4068
+ p.jobs = clarified.jobs;
4069
+ validateBatchPlan({ shared: undefined, jobs: p.jobs, onCapacity: p.onCapacity, config: cfg });
4070
+ }
4071
+ // reject mode: whole-batch reservation is all-or-nothing. Holding the slots
4072
+ // until each job commits (or the unused remainder is released) closes the
4073
+ // interleaving oversubscribe class — a stale plan alone is not enough.
4074
+ if (!launchAvailable) {
4075
+ const maxConcurrent = activeConcurrencyCap();
4076
+ // planBatchLaunches still produces the public error text (incl. pending).
4077
+ planBatchLaunches({
4078
+ jobs: p.jobs,
4079
+ runningCount: countRunning(),
4080
+ pendingCount: gate.pending,
4081
+ maxConcurrent,
4082
+ onCapacity: p.onCapacity,
4083
+ });
4084
+ if (!gate.tryReserve(p.jobs.length, maxConcurrent)) {
4085
+ // Race: capacity changed between plan and reserve.
4086
+ throw new Error(formatCapacityRejectMessage({
4087
+ jobCount: p.jobs.length,
4088
+ runningCount: countRunning(),
4089
+ pendingCount: gate.pending,
4090
+ maxConcurrent,
4091
+ }));
4092
+ }
4093
+ }
4094
+ const names = assignBatchJobNames(p.jobs);
4095
+ const batchId = nextBatchId();
4096
+ const launched = [];
4097
+ const failed = [];
4098
+ const skipped = [];
4099
+ // How many reject-mode reserved slots are still held (not yet committed/released).
4100
+ let reservedRemaining = launchAvailable ? 0 : p.jobs.length;
4101
+ // Walk every job in order. launch-available reserves one slot at a time and
4102
+ // backfills when a job fails before a normal run is launched (slot released).
4103
+ for (let i = 0; i < p.jobs.length; i++) {
4104
+ const job = p.jobs[i];
4105
+ let name = names[i];
4106
+ const merged = mergeJobOptions(p.shared, job);
4107
+ const isContinuation = job.session_id !== undefined || job.session_name !== undefined;
4108
+ // A continuation keeps its own frozen model and effort. shared.model
4109
+ // is a default for NEW conversations, so only a per-job value is an
4110
+ // explicit escalation of the saved recipe.
4111
+ const launch = !isContinuation
4112
+ ? { ...merged, name }
4113
+ : { ...merged, name, model: job.model, thinking: job.thinking };
4114
+ if (launchAvailable) {
4115
+ if (!gate.tryReserve(1, activeConcurrencyCap())) {
4116
+ for (let j = i; j < p.jobs.length; j++) {
4117
+ skipped.push({ job: j + 1, name: names[j] });
4118
+ }
4119
+ break;
4120
+ }
4121
+ }
4122
+ try {
4123
+ const sessionId = requestedSessionId(job, ctx.cwd);
4124
+ // A saved conversation is never re-resolved against the catalog.
4125
+ if (sessionId === undefined && catalogSnapshot && catalogHost && hasCatalogSelector(merged)) {
4126
+ const explicitName = typeof job.name === "string" && job.name.trim() !== "" ? job.name : undefined;
4127
+ const prepared = await prepareCatalogJob(catalogSnapshot, {
4128
+ ...merged,
4129
+ name: explicitName,
4130
+ alias: typeof merged.alias === "string" && merged.alias.trim() !== "" ? merged.alias : explicitName,
4131
+ }, catalogHost);
4132
+ if (prepared.status === "blocked")
4133
+ throw new Error(prepared.message);
4134
+ if (prepared.status === "ready") {
4135
+ Object.assign(launch, prepared.assign);
4136
+ if (prepared.assign.model === undefined)
4137
+ delete launch.model;
4138
+ if (prepared.assign.thinking === undefined)
4139
+ delete launch.thinking;
4140
+ name = prepared.assign.name;
4141
+ }
4142
+ }
4143
+ let plan;
4144
+ if (sessionId !== undefined) {
4145
+ plan = continuationPlanFor(sessionId, verifiedOriginFromContext(ctx) ?? activeCallbackOrigin);
4146
+ assertContinuationLaunchOptions(launch, plan.recipe, `Job ${i + 1}: `, { includeName: false });
4147
+ }
4148
+ const { id, meta, modelNote } = await spawnSubagentRun(ctx, { ...launch, name }, { batchId, batchName: p.batchName }, plan);
4149
+ gate.commit(1);
4150
+ if (!launchAvailable)
4151
+ reservedRemaining -= 1;
4152
+ launched.push({
4153
+ job: i + 1, name, id, sessionId: meta.sessionId,
4154
+ ...(plan ? { continuedFrom: plan.prior.id } : {}),
4155
+ ...(modelNote ? { modelNote } : {}),
4156
+ });
4157
+ }
4158
+ catch (err) {
4159
+ gate.release(1);
4160
+ if (!launchAvailable)
4161
+ reservedRemaining -= 1;
4162
+ const reason = err instanceof Error ? err.message : String(err);
4163
+ failed.push({ job: i + 1, name, reason });
4164
+ if (!launchAvailable) {
4165
+ // reject mode: leave already-launched runs running, release any
4166
+ // still-held later reservations, and report every later job as failed.
4167
+ if (reservedRemaining > 0) {
4168
+ gate.release(reservedRemaining);
4169
+ reservedRemaining = 0;
4170
+ }
4171
+ for (let j = i + 1; j < p.jobs.length; j++) {
4172
+ failed.push({
4173
+ job: j + 1,
4174
+ name: names[j],
4175
+ reason: "not launched due to earlier job failure in reject mode",
4176
+ });
4177
+ }
4178
+ return batchLaunchResult({
4179
+ batchId, batchName: p.batchName, launched, skipped, failed,
4180
+ });
4181
+ }
4182
+ // launch-available: failure did not consume a slot — continue so
4183
+ // later jobs can use remaining capacity (backfill).
4184
+ }
4185
+ }
4186
+ // Safety: any unused reject-mode reservation must not leak.
4187
+ if (reservedRemaining > 0) {
4188
+ gate.release(reservedRemaining);
4189
+ reservedRemaining = 0;
4190
+ }
4191
+ return batchLaunchResult({ batchId, batchName: p.batchName, launched, skipped, failed });
4192
+ },
4193
+ });
4194
+ // ---- model-facing read/stop tools -----------------------------------
4195
+ // The definitions live in tools.ts; registration uses the exact objects
4196
+ // the factories return, so tests invoke the same execute handlers the
4197
+ // model reaches (no drift-prone second copy). Stop's only UI side effect
4198
+ // (widget redraw after a kill) is injected as onStopped.
4199
+ // The foreground origin from session_start; otherwise the calling context's
4200
+ // own session. An unreadable session id stays unavailable (never cwd-wide).
4201
+ const toolSession = {
4202
+ observeAssignment: observedAssignment,
4203
+ observeList: observedList,
4204
+ inspectOutcome: (meta, params, callCtx) => {
4205
+ if (params.disposition !== undefined && params.disposition !== "consumed" && params.disposition !== "dismissed")
4206
+ throw new Error("Outcome disposition must be consumed or dismissed.");
4207
+ if (!readOutcome(meta)) {
4208
+ if (params.disposition !== undefined || params.operation_id !== undefined)
4209
+ throw new Error("No committed terminal outcome is available for this assignment.");
4210
+ return null;
4211
+ }
4212
+ const context = (callCtx ?? uiCtx);
4213
+ if (!context)
4214
+ throw new Error("Parent identity is unavailable.");
4215
+ return inspectOutcome(meta, { recipient: { kind: "parent-session", ...ownerBindingFromContext(context) }, permissions: currentSandboxPermissions(pi),
4216
+ branchIds: context.sessionManager.getBranch().map((entry) => entry.id),
4217
+ ...(typeof params.operation_id === "string" ? { operationId: params.operation_id } : {}),
4218
+ ...(typeof params.outcome_revision === "number" ? { revision: params.outcome_revision } : {}),
4219
+ ...(params.disposition === "consumed" || params.disposition === "dismissed" ? { disposition: params.disposition, note: String(params.note ?? "") } : {}) });
4220
+ },
4221
+ getActiveOrigin: (ctx) => activeCallbackOrigin ?? verifiedOriginFromContext(ctx),
4222
+ };
4223
+ pi.registerTool(subagentListTool(Type, toolSession));
4224
+ pi.registerTool(subagentSettingsTool(Type, effectiveSettings));
4225
+ pi.registerTool(subagentOutputTool(Type, toolSession));
4226
+ const acceptanceResultTool = subagentResultTool(Type, toolSession);
4227
+ pi.registerTool(acceptanceResultTool);
4228
+ publishAcceptanceHooks(acceptanceResultTool);
4229
+ const acceptanceStopTool = subagentStopTool(Type, { onStopped: (id) => {
4230
+ renderWidget();
4231
+ syncHealthTicker();
4232
+ // Stopping a run is a terminal transition, so it owes the caller its one
4233
+ // completion callback even when the caller is the one who asked (#624).
4234
+ enqueueCompletionCallback(pi, id);
4235
+ } });
4236
+ acceptanceStopToolRef = acceptanceStopTool;
4237
+ // A parked attempt may have exited, but its automatic resume is still armed.
4238
+ // Explicit stop must confirm durable cancellation, not just stop a process.
4239
+ const acceptanceStopToolWithParked = {
4240
+ ...acceptanceStopTool,
4241
+ async execute(toolCallId, params, signal, onUpdate, ctx) {
4242
+ const target = params?.id;
4243
+ try {
4244
+ if (typeof target === "string" && await cancelParkedForUi?.(target, "cancelled by subagent_stop; the automatic resume is cancelled")) {
4245
+ renderWidget();
4246
+ syncHealthTicker();
4247
+ return {
4248
+ content: [{
4249
+ type: "text",
4250
+ text: `Durably cancelled the pending wait of parked subagent ${target}. Writer termination may remain unproven; ordinary continuation admission still applies.`,
4251
+ }],
4252
+ };
4253
+ }
4254
+ }
4255
+ catch (error) {
4256
+ return { isError: true, content: [{ type: "text", text: `Cancellation failed for ${target}: ${String(error)}. The retained wait remains available for inspection and retry.` }] };
4257
+ }
4258
+ return acceptanceStopTool.execute(toolCallId, params, signal, onUpdate, ctx);
4259
+ },
4260
+ };
4261
+ pi.registerTool(acceptanceStopToolWithParked);
4262
+ publishAcceptanceHooks();
4263
+ const agentOperations = createAgentOperations({
4264
+ projectConfigDirName,
4265
+ sessionSettings: agentSessionSettings,
4266
+ readSkillDefaults,
4267
+ discoverSkills: (commandCtx) => discoveredSkillsFromContext(commandCtx),
4268
+ editableModels: () => catalogModelRegistry?.getAvailable().map((model) => `${model.provider}/${model.id}`) ?? [],
4269
+ propagateCommandContext(commandCtx) {
4270
+ noteCatalogHost(catalogHostFrom(commandCtx));
4271
+ },
4272
+ resolveHost(toolCtx) {
4273
+ const full = toolCtx;
4274
+ noteCatalogHost(catalogHostFrom({
4275
+ cwd: full.cwd,
4276
+ hasUI: full.hasUI === true,
4277
+ model: full.model,
4278
+ modelRegistry: full.modelRegistry,
4279
+ sessionManager: full.sessionManager,
4280
+ ui: full.ui ?? { select: async () => undefined },
4281
+ isProjectTrusted: () => full.isProjectTrusted(),
4282
+ }));
4283
+ return {
4284
+ cwd: full.cwd,
4285
+ projectTrusted: full.isProjectTrusted(),
4286
+ userRoot: defaultUserRoot(),
4287
+ projectConfigDirName,
4288
+ sessionSettings: agentSessionSettings.snapshot(),
4289
+ };
4290
+ },
4291
+ enrich: createLaunchEnricher(pi),
4292
+ });
4293
+ const openSettings = async (ctx) => {
4294
+ if (ctx.mode === "tui" && ctx.hasUI && typeof ctx.ui.custom === "function") {
4295
+ const next = await ctx.ui.custom((tui, theme, _kb, done) => createSubagentSettingsPage(theme, {
4296
+ get: () => {
4297
+ const settings = effectiveSettings();
4298
+ const skills = activeSkills();
4299
+ const timing = timingState();
4300
+ return {
4301
+ mode: settings.delegationMode, maxConcurrent: settings.maxConcurrent,
4302
+ maxMinutes: timing.maxMinutes,
4303
+ modeSource: settings.sources.delegationMode,
4304
+ capSource: settings.sources.maxConcurrent,
4305
+ defaultMode: normalizeDelegationMode(loadConfig().delegationMode),
4306
+ defaultCap: normalizeConcurrencyCap(loadConfig().maxConcurrent),
4307
+ toolWaitMinutes: settings.toolWaitMinutes, stuckMinutes: settings.stuckMinutes,
4308
+ toolWaitSource: settings.timingSources.toolWaitMinutes,
4309
+ stuckSource: settings.timingSources.stuckMinutes,
4310
+ defaultToolWaitMinutes: timing.defaultToolWaitMinutes,
4311
+ defaultStuckMinutes: timing.defaultStuckMinutes,
4312
+ ...(settings.timingError ? { timingError: settings.timingError } : {}),
4313
+ skillsMode: skills.mode, skillsPaths: skills.paths, skillsSource: skills.source,
4314
+ skillsError: skills.error,
4315
+ };
4316
+ },
4317
+ changeMode, changeCap, changeTiming, changeSkills, save: saveSettings, reset: resetSettings,
4318
+ discoverSkills: () => discoveredSkillsFromContext(ctx),
4319
+ // Close this page first; the catalog opens after ui.custom resolves.
4320
+ openAgents: () => done("agents"),
4321
+ }, () => { refreshBackgroundWorkNavigator(ctx); tui.requestRender(); }, () => done(undefined)));
4322
+ if (next === "agents")
4323
+ await agentOperations.openCatalog(ctx);
4324
+ }
4325
+ else {
4326
+ const skills = activeSkills();
4327
+ const skillChoice = skills.mode === "inherit" ? "discovery"
4328
+ : skills.mode === "none" ? "no skills" : `${skills.paths.length} selected skills`;
4329
+ const timing = timingState();
4330
+ ctx.ui.notify(`Delegation mode: ${activeDelegationMode()}. Concurrent subagents: ${activeConcurrencyCap()}. ` +
4331
+ `Timeout: ${timing.maxMinutes} minutes (0 disables). Tool-wait alert: ${timing.toolWaitMinutes} min. ` +
4332
+ `No-progress alert: ${timing.stuckMinutes} min. Skills: ${skillChoice}. ` +
4333
+ `Use /subagents mode <mode>, cap <number>, tool-wait <minutes>, stuck <minutes>, or settings; /subagents save persists them.`, "info");
4334
+ }
4335
+ };
4336
+ const contribution = { id: "subagents", label: "Subagents", command: "/subagents settings", open: openSettings };
4337
+ const agentsContribution = { id: "agents", label: "Agents", command: "/agents", open: agentOperations.openCatalog };
4338
+ const registerSettings = () => {
4339
+ pi.events?.emit("harness-settings:register", contribution);
4340
+ pi.events?.emit("harness-settings:register", agentsContribution);
4341
+ };
4342
+ const unsubscribeToolLoading = pi.events?.on?.("pi-better-subagents:default-tool-loading", (request) => {
4343
+ const query = request;
4344
+ if (typeof query?.reply !== "function")
4345
+ return;
4346
+ const config = ordinaryChildConfig(loadConfig(), activeChildProviders(pi));
4347
+ const names = normalizeTools(config.defaultTools ?? SAFE_DEFAULT_TOOLS).split(",").filter(Boolean);
4348
+ addEditablePatch(names, new Set());
4349
+ const rows = [...new Set(names)].map(name => {
4350
+ if (name === "codemode") {
4351
+ const supported = "createCodemodeExtension" in PiCodingAgent && typeof PiCodingAgent.createCodemodeExtension === "function";
4352
+ return { name, provider: supported ? "Harness" : "SDK unavailable" };
4353
+ }
4354
+ if (BUILTIN_TOOLS.includes(name))
4355
+ return { name, provider: "Pi" };
4356
+ const spec = config.toolExtensions?.[name];
4357
+ const sources = typeof spec === "string" ? [spec] : spec ?? [];
4358
+ const providers = sources.map(source => {
4359
+ const label = source === ORDINARY_TOOL_PROVIDERS[name] ? "Harness" : source;
4360
+ return resolveExtensionPath(source) ? label : `${label} (missing)`;
4361
+ });
4362
+ return { name, provider: providers.join(", ") || (config.inheritExtensions ? "Session extensions" : "No provider mapped") };
4363
+ });
4364
+ query.reply(rows);
4365
+ });
4366
+ const unsubscribeSettingsRequest = pi.events?.on?.("harness-settings:request", registerSettings);
4367
+ const unsubscribeOutcomeWorkflow = pi.events?.on?.("pi-better-workflow:changed", () => recoverAssignmentOutcomes(pi));
4368
+ registerSettings();
4369
+ if (typeof pi.registerCommand === "function") {
4370
+ agentOperations.registerCommands(pi);
4371
+ pi.registerCommand("subagents", {
4372
+ description: "[history [dismiss]|settings|mode manual|adaptive|coordinator|cap <number>|tool-wait <minutes>|stuck <minutes>|save|reset] — Subagent management",
4373
+ getArgumentCompletions: subagentsArgumentCompletions,
4374
+ async handler(args, ctx) {
4375
+ const tokens = args.trim().split(/\s+/).filter(Boolean);
4376
+ if (tokens[0] === "history") {
4377
+ try {
4378
+ const origin = { cwd: ctx.cwd, sessionId: ctx.sessionManager.getSessionId() };
4379
+ const waits = historicalWaits(origin);
4380
+ if (tokens[1] === "dismiss") {
4381
+ dismissAttention(ctx.cwd, attentionRevision(waits));
4382
+ ctx.ui.notify("Historical attention notice dismissed. Waits and evidence are unchanged.", "info");
4383
+ return;
4384
+ }
4385
+ const labels = waits.map((p) => `${p.runId} · session ${p.record.ownerSessionId ?? "unknown"} · ${p.phase}`);
4386
+ const selected = await ctx.ui.select("Historical subagent waits", labels);
4387
+ const park = waits[labels.indexOf(selected ?? "")];
4388
+ if (!park)
4389
+ return;
4390
+ const action = await ctx.ui.select(`${park.runId} · session ${park.record.ownerSessionId ?? "unknown"}`, ["Inspect", "Cancel pending wait"]);
4391
+ if (action === "Inspect") {
4392
+ ctx.ui.notify(JSON.stringify({ runId: park.runId, originatingSession: park.record.ownerSessionId,
4393
+ workspace: park.record.ownerWorkspace, waitId: park.waitId, generation: park.generation,
4394
+ phase: park.phase, reason: park.record.heldReason, cancellation: park.record.cancelReason,
4395
+ resumedBy: park.record.resumedBy, log: park.meta.logPath }), "info");
4396
+ }
4397
+ else if (action === "Cancel pending wait" && await ctx.ui.confirm("Cancel pending wait?", `${park.runId} belongs to session ${park.record.ownerSessionId ?? "unknown"}. This does not prove its writer has stopped.`)) {
4398
+ if (!await cancelParkedForUi?.(park.runId, "explicit cancellation from historical management"))
4399
+ throw new Error("The pending wait changed; inspect it again.");
4400
+ ctx.ui.notify(`Durably cancelled the pending wait of ${park.runId}. Writer termination may remain unproven.`, "info");
4401
+ }
4402
+ }
4403
+ catch (error) {
4404
+ ctx.ui.notify(`Historical wait management failed: ${String(error)}. Inspect or retry with /subagents history.`, "warning");
4405
+ }
4406
+ return;
4407
+ }
4408
+ if (tokens.length === 0 || (tokens.length === 1 && tokens[0] === "settings")) {
4409
+ await openSettings(ctx);
4410
+ return;
4411
+ }
4412
+ const requested = tokens[1];
4413
+ if (tokens.length === 1 && tokens[0] === "save") {
4414
+ const skills = activeSkills();
4415
+ if (skills.mode === "explicit" && skills.paths.length === 0) {
4416
+ ctx.ui.notify("Add at least one skill path, or choose No skill catalog to load none.", "warning");
4417
+ return;
4418
+ }
4419
+ const skillChoice = skills.mode === "inherit" ? "skill discovery"
4420
+ : skills.mode === "none" ? "no skills" : `${skills.paths.length} selected skills`;
4421
+ const timing = timingState();
4422
+ if (ctx.hasUI && !(await ctx.ui.confirm("Save subagent defaults?", `Future sessions will start in ${activeDelegationMode()} with a cap of ${activeConcurrencyCap()}, ` +
4423
+ `timeout ${timing.maxMinutes} minutes (0 disables), tool-wait alert ${timing.toolWaitMinutes} min, ` +
4424
+ `no-progress alert ${timing.stuckMinutes} min, and ${skillChoice}.`))) {
4425
+ ctx.ui.notify("Subagent defaults unchanged.", "info");
4426
+ return;
4427
+ }
4428
+ const saved = saveSettings();
4429
+ ctx.ui.notify(saved.message, saved.ok ? "info" : "warning");
4430
+ }
4431
+ else if (tokens.length === 1 && tokens[0] === "reset") {
4432
+ resetSettings();
4433
+ ctx.ui.notify("Session subagent settings reset to saved defaults.", "info");
4434
+ }
4435
+ else if (tokens.length === 2 && tokens[0] === "mode" && isDelegationMode(requested)) {
4436
+ changeMode(requested);
4437
+ ctx.ui.notify(`Delegation mode: ${activeDelegationMode()} (current session).`, "info");
4438
+ }
4439
+ else if (tokens.length === 2 && tokens[0] === "cap") {
4440
+ const cap = /^\d+$/.test(requested) ? Number(requested) : NaN;
4441
+ if (!isConcurrencyCap(cap)) {
4442
+ ctx.ui.notify("Concurrent subagents must be a positive whole number. Nothing changed.", "warning");
4443
+ return;
4444
+ }
4445
+ changeCap(cap);
4446
+ ctx.ui.notify(`Concurrent subagents: ${cap} (current session). Running subagents are unchanged.`, "info");
4447
+ }
4448
+ else if (tokens.length === 2 && (tokens[0] === "tool-wait" || tokens[0] === "stuck")) {
4449
+ const key = tokens[0] === "tool-wait" ? "toolWaitMinutes" : "stuckMinutes";
4450
+ let minutes;
4451
+ try {
4452
+ minutes = validatedTimingMinutes(requested, key);
4453
+ }
4454
+ catch (error) {
4455
+ ctx.ui.notify(`${error instanceof Error ? error.message : String(error)} Nothing changed.`, "warning");
4456
+ return;
4457
+ }
4458
+ changeTiming(key, minutes);
4459
+ ctx.ui.notify(`${tokens[0] === "tool-wait" ? "Tool-wait" : "No-progress"} alert: ${minutes} min (current session). Running subagents are unchanged.`, "info");
4460
+ }
4461
+ else {
4462
+ ctx.ui.notify("Usage: /subagents [history [dismiss]|settings|mode manual|adaptive|coordinator|cap <number>|tool-wait <minutes>|stuck <minutes>|save|reset]", "warning");
4463
+ }
4464
+ refreshBackgroundWorkNavigator(ctx);
4465
+ },
4466
+ });
4467
+ }
4468
+ const discoveryTool = agentOperations.createDiscoveryTool(Type);
4469
+ pi.registerTool(discoveryTool);
4470
+ // Sections on a host that renders them; text only where it renders none.
4471
+ // Returning a prompt on modern pi would set forceSystemPrompt, and the request
4472
+ // would then carry a snapshot, so sections published after it never arrive.
4473
+ pi.on("before_agent_start", (event) => deliverSubagentPrompt(event, effectiveSettings()));
4474
+ // ---- live-status lifecycle -----------------------------------------
4475
+ pi.on("agent_start", async (_event, ctx) => {
4476
+ setCallbackBatchContext(pi, ctx);
4477
+ getCallbackBatcher(pi).setForegroundRunning(true);
4478
+ uiCtx = ctx;
4479
+ mainAgentStartedAt = Date.now();
4480
+ mainAgentTools.clear();
4481
+ refreshBackgroundWorkNavigator(ctx);
4482
+ });
4483
+ pi.on("agent_end", () => { getCallbackBatcher(pi).setForegroundRunning(false); });
4484
+ pi.on("tool_execution_start", async (event, ctx) => {
4485
+ getCallbackBatcher(pi).toolStarted(event.toolCallId);
4486
+ mainAgentTools.set(event.toolCallId, event.toolName);
4487
+ refreshBackgroundWorkNavigator(ctx);
4488
+ });
4489
+ pi.on("tool_execution_end", async (event, ctx) => {
4490
+ await getCallbackBatcher(pi).toolEnded(event.toolCallId);
4491
+ mainAgentTools.delete(event.toolCallId);
4492
+ refreshBackgroundWorkNavigator(ctx);
4493
+ });
4494
+ pi.on("message_end", async (event, ctx) => {
4495
+ if (event.message.role === "assistant")
4496
+ refreshBackgroundWorkNavigator(ctx);
4497
+ });
4498
+ pi.on("model_select", async (_event, ctx) => {
4499
+ // The selected model is already on ctx. Inspection between this event
4500
+ // and the next /agents call must not keep the previous foreground.
4501
+ try {
4502
+ noteCatalogHost(catalogHostFrom(ctx));
4503
+ }
4504
+ catch { /* navigator still redraws */ }
4505
+ refreshBackgroundWorkNavigator(ctx);
4506
+ });
4507
+ pi.on("thinking_level_select", async (_event, ctx) => {
4508
+ refreshBackgroundWorkNavigator(ctx);
4509
+ });
4510
+ pi.on("agent_settled", async (_event, ctx) => {
4511
+ getCallbackBatcher(pi).setForegroundRunning(false);
4512
+ setCallbackBatchContext(pi, ctx);
4513
+ mainAgentStartedAt = undefined;
4514
+ mainAgentTools.clear();
4515
+ refreshBackgroundWorkNavigator(ctx);
4516
+ recoverAssignmentOutcomes(pi);
4517
+ });
4518
+ pi.on("session_tree", async (_event, ctx) => {
4519
+ setCallbackBatchContext(pi, ctx);
4520
+ agentSessionSettings.restore(ctx);
4521
+ try {
4522
+ noteCatalogHost(catalogHostFrom(ctx));
4523
+ }
4524
+ catch { /* catalog inspection stays undecided */ }
4525
+ restoreDelegationMode(ctx);
4526
+ recoverAssignmentOutcomes(pi);
4527
+ });
4528
+ // Capture a UI-bearing context and, if runs from a prior session are still
4529
+ // alive, resume the ticking widget. Deferred out of the factory per pi's
4530
+ // "no background resources at load" rule.
4531
+ let restoreObservation;
4532
+ let offFirstAssignment;
4533
+ const cancelDeferredObservation = () => {
4534
+ if (restoreObservation)
4535
+ clearImmediate(restoreObservation);
4536
+ offFirstAssignment?.();
4537
+ offFirstAssignment = undefined;
4538
+ };
4539
+ pi.on("session_start", async (event, ctx) => {
4540
+ // A session begins in this process again (reload, restart, or a session
4541
+ // switch), so the previous session's teardown no longer applies: the
4542
+ // replacing session owns this instance's supervision loops (#625).
4543
+ sessionTornDown = false;
4544
+ pendingNavigatorDismissals.clear();
4545
+ outcomeHost = createOutcomeHost();
4546
+ setCallbackBatchContext(pi, ctx);
4547
+ agentSessionSettings.restore(ctx);
4548
+ restoreDelegationMode(ctx);
4549
+ uiCtx = ctx;
4550
+ try {
4551
+ noteCatalogHost(catalogHostFrom(ctx));
4552
+ }
4553
+ catch { /* catalog inspection stays undecided */ }
4554
+ try {
4555
+ mainAgentStartedAt = ctx.isIdle() ? undefined : Date.now();
4556
+ }
4557
+ catch {
4558
+ mainAgentStartedAt = undefined;
4559
+ }
4560
+ mainAgentTools.clear();
4561
+ activeCallbackOrigin = callbackOriginFromContext(ctx);
4562
+ pendingRecipientRecovery.clear();
4563
+ observedRecipientRows.clear();
4564
+ cancelDeferredObservation();
4565
+ if (!managed && activeCallbackOrigin) {
4566
+ configureWorkObservation(PiCodingAgent.getAgentDir(), activeCallbackOrigin, () => {
4567
+ refreshBackgroundWorkNavigator(ctx);
4568
+ observeRecipientNotifications(pi);
4569
+ });
4570
+ if (!event?.reason) {
4571
+ // Older hosts use completion of their untyped start callback as the readiness signal.
4572
+ await activateWorkObservation();
4573
+ }
4574
+ else if (shouldRestoreWorkObservation(event, ctx.sessionManager)) {
4575
+ restoreObservation = setImmediate(() => { void activateWorkObservation(); });
4576
+ }
4577
+ else {
4578
+ // Another extension can assign work to this recipient before it calls a tool.
4579
+ const origin = activeCallbackOrigin;
4580
+ offFirstAssignment = onMetaChanged(meta => {
4581
+ if (!meta || !belongsToOrigin(meta, origin))
4582
+ return;
4583
+ offFirstAssignment?.();
4584
+ offFirstAssignment = undefined;
4585
+ void activateWorkObservation();
4586
+ });
4587
+ }
4588
+ }
4589
+ if (!managed) {
4590
+ recoverCompletionCallbacks(pi);
4591
+ observeRecipientNotifications(pi);
4592
+ }
4593
+ // Admission can defer before batcher enqueue, even after the last child
4594
+ // exits. Keep reconciliation independent of the live-run health ticker.
4595
+ if (outcomeTicker)
4596
+ clearInterval(outcomeTicker);
4597
+ if (!managed) {
4598
+ outcomeTicker = setInterval(() => recoverAssignmentOutcomes(pi), 1000);
4599
+ outcomeTicker.unref?.();
4600
+ }
4601
+ // Reload / session switch hardening (#48):
4602
+ // - Drop any leftover overlay timers/confirm state from a prior session
4603
+ // (defensive if the host skipped session_shutdown before re-start).
4604
+ // - Reinstall the editor wrapper without stacking (marked factory).
4605
+ // - Repaint the widget even if its last in-memory lines match; the host
4606
+ // may have dropped extension UI during reload/session replacement.
4607
+ ensureSubagentProvider();
4608
+ // A reload/restart leaves detached children alive without an in-memory
4609
+ // exit observer (#625). Finalize any that finished while the foreground
4610
+ // session was gone; live ones stay `running` and the ticker below
4611
+ // supervises them until they exit. This runs BEFORE abandonment
4612
+ // adoption: a finished child's coherent log is terminal evidence, and
4613
+ // `lost` would otherwise win the race and hide the result.
4614
+ if (managed)
4615
+ recoverInterruptedSubagents(pi);
4616
+ if (managed)
4617
+ for (const meta of managed.supervised()) {
4618
+ if (meta.assignment)
4619
+ commitAssignmentTerminal(meta);
4620
+ }
4621
+ // Adopt records left non-terminal by a pi that died without a clean
4622
+ // shutdown, so the age sweep can eventually retire them.
4623
+ if (managed)
4624
+ reconcileAbandonedRuns();
4625
+ disposeBackgroundWorkNavigator(ctx, navigatorOwner);
4626
+ widgetNavActive = false;
4627
+ widgetNavSelectedId = undefined;
4628
+ ensureNavigator(ctx, navigatorOwner);
4629
+ publishAcceptanceHooks();
4630
+ updateNavigatorFooter(ctx);
4631
+ // Clear the retired legacy widget so the shared navigator is the only
4632
+ // list surface for running/orphaned subagents.
4633
+ renderWidget();
4634
+ // Reattach one watcher after reload; ordinary completion retries belong to the batcher.
4635
+ syncHealthTicker();
4636
+ // Supervised worker operations (ADR 0020): the bridge host is bound to this
4637
+ // process, and parked generations from a previous session are reconciled
4638
+ // against the durable coordinator before anything resumes.
4639
+ if (managed)
4640
+ await startWorkerOperations();
4641
+ });
4642
+ pi.on("session_before_switch", () => {
4643
+ cancelDeferredObservation();
4644
+ closeCatalogHost();
4645
+ agentSessionSettings.clear();
4646
+ catalogModelRegistry = undefined;
4647
+ activeCallbackOrigin = undefined;
4648
+ cancelCallbackBatch(pi);
4649
+ mainAgentStartedAt = undefined;
4650
+ mainAgentTools.clear();
4651
+ // Owned disposal only: a headless child or a stale factory must not clear
4652
+ // the parent's navigator by omitting the context and owner.
4653
+ disposeBackgroundWorkNavigator(undefined, navigatorOwner);
4654
+ });
4655
+ // Tear down the timer and clear the widget when the session ends.
4656
+ pi.on("session_shutdown", async (event, ctx) => {
4657
+ closeCatalogHost();
4658
+ cancelDeferredObservation();
4659
+ stopWorkObservation();
4660
+ pendingNavigatorDismissals.clear();
4661
+ if (outcomeTicker)
4662
+ clearInterval(outcomeTicker);
4663
+ outcomeTicker = undefined;
4664
+ outcomeAdmission.clear();
4665
+ closeOutcomeHost(outcomeHost);
4666
+ if (typeof unsubscribeOutcomeWorkflow === "function")
4667
+ unsubscribeOutcomeWorkflow();
4668
+ if (typeof unsubscribeToolLoading === "function")
4669
+ unsubscribeToolLoading();
4670
+ if (typeof unsubscribeSettingsRequest === "function")
4671
+ unsubscribeSettingsRequest();
4672
+ // #625: subagent children are detached process groups that outlive this
4673
+ // foreground session. A controlled reload or quit must not destroy
4674
+ // delegated work: record the interruption durably, warn the human, and
4675
+ // leave the child, its log, and its saved state untouched. The next
4676
+ // session of this pi process resumes supervision and finalizes the run
4677
+ // from the child's own log.
4678
+ const reason = typeof event?.reason === "string" ? event.reason : "shutdown";
4679
+ try {
4680
+ const interrupted = managed ? [] : interruptCurrentSessionSubagents(reason, ctx);
4681
+ warnInterruptedSubagents(ctx, interrupted, reason);
4682
+ }
4683
+ catch { /* shutdown cleanup must never block the session teardown */ }
4684
+ // Late finalizers of surviving children must not restart supervision
4685
+ // loops in this replaced instance.
4686
+ sessionTornDown = true;
4687
+ // This instance's bridge host dies with the session: a surviving child
4688
+ // loses its transport (and therefore refuses to park) instead of talking
4689
+ // to a replaced session's handlers. Durable wait records are untouched.
4690
+ try {
4691
+ resumeOrchestration?.stop();
4692
+ }
4693
+ catch { /* best effort */ }
4694
+ resumeOrchestration = undefined;
4695
+ await workerOperations.close().catch(() => { });
4696
+ // Children keep running; their finalizers (if this instance still holds
4697
+ // one) must not reach for a ctx that Pi invalidates once the session is
4698
+ // replaced.
4699
+ uiCtx = undefined;
4700
+ agentSessionSettings.clear();
4701
+ catalogModelRegistry = undefined;
4702
+ // `/reload` keeps the same session identity, so a finalizer that lands
4703
+ // after the replacement still targets the live session and may deliver
4704
+ // its completion. Every other reason replaces or ends that identity, so
4705
+ // the origin is dropped and the pending marker is left for whichever
4706
+ // session owns the run next.
4707
+ if (reason !== "reload")
4708
+ activeCallbackOrigin = undefined;
4709
+ if (typeof unsubscribeDelegationRequest === "function")
4710
+ unsubscribeDelegationRequest();
4711
+ cancelCallbackBatch(pi);
4712
+ mainAgentStartedAt = undefined;
4713
+ mainAgentTools.clear();
4714
+ stopTicker();
4715
+ stopHealthTicker();
4716
+ spendCache.clear();
4717
+ healthLogCache.clear();
4718
+ progressCache.clear();
4719
+ // Release the incremental log cursors' retained state with the session.
4720
+ resetChildEventLogCursor();
4721
+ resetParseRunCursor();
4722
+ // Always dispose navigator detail timers (no UI call — just clearInterval).
4723
+ // Safe in every mode; the dispose hook is only set when a TUI overlay opened.
4724
+ disposeBackgroundWorkNavigator(ctx, navigatorOwner);
4725
+ // Widget clear is intentional in every mode that exposes ui, including RPC.
4726
+ try {
4727
+ ctx.ui.setWidget("subagents", WIDGET_CLEAR);
4728
+ }
4729
+ catch { /* ignore */ }
4730
+ });
4731
+ }