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,1511 @@
1
+ // Generated fixed launch domain from packages/pi-better-background-tasks/src/runtime.ts. Do not edit directly.
2
+ import { createHash } from "node:crypto";
3
+ import { readFileSync, statSync } from "node:fs";
4
+ import { appendLine, appendTaskOutput, appendWatchResult, retainLogTail, resolveMaxLogBytes } from "./logs.domain.mjs";
5
+ import { evaluateCondition, validateCondition } from "./conditions.domain.mjs";
6
+ import { parseStepGateFailure, processExists, runCommandOnce, spawnCommand, STEP_GATE_COMMAND_ENV, stepGateScript, stopProcessGroup } from "./process.domain.mjs";
7
+ import { currentProcessStartToken, readProcessStartToken } from "./process-identity.domain.mjs";
8
+ import { DEFAULT_TMUX_BOOTSTRAP_TIMEOUT_MS, expandSshRemoteTaskPreset } from "./remote-task-preset.domain.mjs";
9
+ import { ensureTaskDir, logPathFor, nextTaskId, readMeta, sandboxProfilePathFor, writeMeta } from "./registry.domain.mjs";
10
+ import { assertBackgroundExecutionAllowed, backgroundExecutionLimits, confineCommandSpec, isCommandTimeoutSeconds, resolveForegroundSandboxPlan, sandboxProvenance } from "./sandbox.domain.mjs";
11
+ import { takeRecoverySnapshot } from "./shared-sandbox-core.domain.mjs";
12
+ import { failurePath, readTaskIntent, recordExitFailure, recordFailure, recoverDeclaredOperation, recoverFailure, createFailureAttention, defaultAttention, terminalFailureAttention } from "./failures.domain.mjs";
13
+ import { markFailureAttentionDelivered } from "./shared-failure-observations.domain.mjs";
14
+ import { getCallbackBatcher } from "./shared-callback-batcher.domain.mjs";
15
+ import { formatCallbackFacts } from "./output.domain.mjs";
16
+ import { observeTaskStallAttention } from "./stall-attention.domain.mjs";
17
+ import { FIRST_WATCH_CHECK_WAIT_MS, isTerminalStatus } from "./types.domain.mjs";
18
+ export const DEFAULT_WATCH_TIMEOUT_SECONDS = 15 * 60;
19
+ /** Consecutive blind checks (exit 0, stderr, no condition matched) before a watch is flagged (#359). */
20
+ export const DEFAULT_BLIND_CHECKS = 3;
21
+ /** How long bg_task_watch waits for the first check before returning (#359). */
22
+ export { FIRST_WATCH_CHECK_WAIT_MS } from "./types.domain.mjs";
23
+ /** How to fix a false alarm: some tools write progress or warnings to stderr on success. */
24
+ export const BLIND_CHECK_HINT = "If the stderr is expected (progress or warnings), redirect it (2>/dev/null) or set blind_checks:0.";
25
+ /** Each cached extension factory owns its scheduling and suspension state. */
26
+ export function createBackgroundTaskRuntime(attention = createFailureAttention(), deliverCompletion, admission, sourceWork = (_kind, _id, work) => work()) {
27
+ const { resumeFailureAttention, scheduleFailureAttention, stopFailureAttention, suspendFailureAttention } = attention;
28
+ const watcherTimers = new Map();
29
+ const remoteSessionTimers = new Map();
30
+ const processTimeoutTimers = new Map();
31
+ const activeProcessTimeouts = new Set();
32
+ const activeRemoteTasks = new Map();
33
+ const remoteSessionStarts = new Map();
34
+ /** Tasks whose stop in this instance is waiting on an in-flight tmux start, and kills the session itself. */
35
+ const remoteStopsAwaitingStart = new Set();
36
+ const activePolls = new Set();
37
+ const logRetentionTimers = new Map();
38
+ const LOG_RETENTION_CHECK_MS = 1000;
39
+ const handoffTimers = new Map();
40
+ // The handoff check backs off from 250 ms to 4 s while the task keeps running,
41
+ // and returns to 250 ms once its process is gone so the grace period is timed closely.
42
+ const HANDOFF_CHECK_MS = 250;
43
+ const HANDOFF_MAX_CHECK_MS = 4_000;
44
+ const HANDOFF_LOST_GRACE_MS = 5_000;
45
+ let scheduledWorkSuspended = false;
46
+ const REMOTE_SESSION_POLL_MS = 100;
47
+ const BLIND_OPERATION = "watch-blind";
48
+ /** In-flight first checks of watches launched by this instance, keyed by task id. */
49
+ const firstCheckWaiters = new Map();
50
+ /**
51
+ * Wait for a watch's first check, bounded by `timeoutMs` and `signal` (#359). Resolves a pending
52
+ * outcome when the wait ends first, and undefined when this instance did not launch the watch
53
+ * or the watch ended without a check.
54
+ */
55
+ async function awaitFirstWatchCheck(id, timeoutMs = FIRST_WATCH_CHECK_WAIT_MS, signal) {
56
+ const waiter = firstCheckWaiters.get(id);
57
+ if (!waiter)
58
+ return undefined;
59
+ const started = Date.now();
60
+ const pending = (reason) => ({ pending: reason, waitedMs: Date.now() - started });
61
+ if (signal?.aborted)
62
+ return pending("aborted");
63
+ let timer;
64
+ let onAbort;
65
+ const timeout = new Promise((resolve) => {
66
+ // Kept referenced: the launching tool call is waiting on it, and the watch timers are
67
+ // unref'd, so an unref'd wait could let the event loop drain before the first check.
68
+ timer = setTimeout(() => resolve("timeout"), Math.max(0, timeoutMs));
69
+ });
70
+ const aborted = new Promise((resolve) => {
71
+ onAbort = () => resolve("aborted");
72
+ signal?.addEventListener("abort", onAbort, { once: true });
73
+ });
74
+ try {
75
+ const outcome = await Promise.race([waiter.promise, timeout, aborted]);
76
+ if (outcome === "timeout" || outcome === "aborted" || outcome === "suspended")
77
+ return pending(outcome);
78
+ return outcome;
79
+ }
80
+ finally {
81
+ if (timer)
82
+ clearTimeout(timer);
83
+ if (onAbort)
84
+ signal?.removeEventListener("abort", onAbort);
85
+ }
86
+ }
87
+ function settleFirstCheck(id, check) {
88
+ const waiter = firstCheckWaiters.get(id);
89
+ if (!waiter)
90
+ return;
91
+ firstCheckWaiters.delete(id);
92
+ waiter.resolve(check);
93
+ }
94
+ /**
95
+ * Stop this extension instance's scheduled work when its session shuts down (#324).
96
+ *
97
+ * Pi emits session_shutdown for /reload, /new, /resume, fork, session switch,
98
+ * and quit, and the next session loads a fresh extension instance. Work left in
99
+ * the old instance runs with no active session, so a task finishing there used to
100
+ * have its completion callback durably suppressed ("active session identity is
101
+ * unavailable") and the next session never heard about it.
102
+ *
103
+ * After suspension this instance schedules nothing and notifies nothing. Work
104
+ * already in flight (a child's close listener, a remote tmux bootstrap/start, a
105
+ * timeout kill) still records its result in metadata, but leaves the callback to
106
+ * the instance that resumes the task. Processes are not stopped.
107
+ *
108
+ * Resume is per callback origin: session_start resumes only tasks whose origin
109
+ * (cwd and session id) matches the new session. After /reload that is every task
110
+ * of the session. After switching to another session, the previous session's
111
+ * tasks keep running, but their watches do not poll, remote tmux output is not
112
+ * collected, and their `timeout_seconds` deadlines are not enforced until that
113
+ * session is active again; an overdue deadline is enforced immediately on resume.
114
+ * A local process that exits meanwhile, while this Pi process is still running,
115
+ * is recorded as terminal and its callback is delivered when its session resumes;
116
+ * after Pi quits, a resumed task whose process is gone is marked lost instead.
117
+ */
118
+ function suspendScheduledWork() {
119
+ scheduledWorkSuspended = true;
120
+ for (const timer of watcherTimers.values())
121
+ clearTimeout(timer);
122
+ for (const timer of remoteSessionTimers.values())
123
+ clearTimeout(timer);
124
+ for (const timer of processTimeoutTimers.values())
125
+ clearTimeout(timer);
126
+ for (const timer of logRetentionTimers.values())
127
+ clearInterval(timer);
128
+ for (const timer of handoffTimers.values())
129
+ clearTimeout(timer);
130
+ handoffTimers.clear();
131
+ watcherTimers.clear();
132
+ remoteSessionTimers.clear();
133
+ processTimeoutTimers.clear();
134
+ logRetentionTimers.clear();
135
+ // A launch still waiting on a first check that will not run here reports it as still running.
136
+ for (const id of [...firstCheckWaiters.keys()])
137
+ settleFirstCheck(id, "suspended");
138
+ suspendFailureAttention();
139
+ }
140
+ /** Allow scheduling again; called at session_start before running tasks are resumed. */
141
+ function resumeScheduledWork() {
142
+ scheduledWorkSuspended = false;
143
+ resumeFailureAttention();
144
+ }
145
+ /**
146
+ * Persist the launch-time per-command cap with the task metadata. Reload and
147
+ * resume go through `readMeta`, so the value travels as ordinary JSON and the
148
+ * task keeps the cap it launched under.
149
+ */
150
+ function withCommandPolicy(meta, seconds) {
151
+ return seconds === undefined ? meta : { ...meta, commandTimeoutSeconds: seconds };
152
+ }
153
+ /**
154
+ * The step gate applies to a shell command only (#619). A direct argv launch already
155
+ * reports the real exit code, and a structured SSH command runs under remote
156
+ * semantics the local gate cannot observe, so both are refused rather than silently
157
+ * ignored: a gate that quietly does nothing is the masking bug it exists to fix.
158
+ */
159
+ function stepGateRefusal(params) {
160
+ if (params.require_successful_steps !== true)
161
+ return undefined;
162
+ if (params.shell === false) {
163
+ return "Invalid step gate: require_successful_steps needs a shell command; argv with shell:false already reports the real exit code. The task was not started.";
164
+ }
165
+ if (!params.command || params.command.trim().length === 0) {
166
+ return "Invalid step gate: require_successful_steps needs a non-empty shell command. The task was not started.";
167
+ }
168
+ if (params.ssh) {
169
+ return "Invalid step gate: require_successful_steps is local-only and cannot observe a structured ssh command. The task was not started.";
170
+ }
171
+ return undefined;
172
+ }
173
+ /** Read the gate verdict bash wrote at the end of the task log (#619). */
174
+ function readStepGateFailure(meta) {
175
+ try {
176
+ return parseStepGateFailure(readFileSync(meta.logPath, "utf8"), meta.id);
177
+ }
178
+ catch {
179
+ // A swept temp dir or an unreadable log costs the reason, never the verdict.
180
+ return undefined;
181
+ }
182
+ }
183
+ /**
184
+ * The command actually spawned for a gated task: bash runs the gate script and
185
+ * `eval`s the operator's own command from `STEP_GATE_COMMAND_ENV`. Meta keeps the
186
+ * operator's command verbatim, so status, log, and recovery never show the wrapper.
187
+ */
188
+ function withStepGate(spec, id, gated) {
189
+ if (!gated)
190
+ return spec;
191
+ return { ...spec, command: stepGateScript(id), env: { ...spec.env, [STEP_GATE_COMMAND_ENV]: spec.command } };
192
+ }
193
+ function persistedCommandCapSeconds(meta) {
194
+ const value = meta.commandTimeoutSeconds;
195
+ return isCommandTimeoutSeconds(value) ? value : undefined;
196
+ }
197
+ /**
198
+ * A cap that was persisted but is not a valid number of seconds.
199
+ *
200
+ * Metadata can be edited or written by an older build, so a present-but-invalid
201
+ * value must not quietly mean "unlimited": the task fails closed on resume
202
+ * instead of running without the cap the operator asked for.
203
+ */
204
+ function invalidPersistedCommandCap(meta) {
205
+ if (meta.commandTimeoutSeconds === undefined || isCommandTimeoutSeconds(meta.commandTimeoutSeconds))
206
+ return undefined;
207
+ return `Persisted command time limit ${JSON.stringify(meta.commandTimeoutSeconds)} is invalid; the task was not resumed with an unlimited command.`;
208
+ }
209
+ function spawnTask(pi, params, defaultCwd, callbackOrigin, getActiveSession, dependencies = {}) {
210
+ admission?.assert();
211
+ // Resolved before any task directory, log, or metadata exists so a blocked
212
+ // launch leaves nothing behind. Structured SSH must also honor launch restrictions.
213
+ const intent = readTaskIntent(params);
214
+ // A gate that could only be silently ignored is refused before any task state exists (#619).
215
+ const stepGateRefused = stepGateRefusal(params);
216
+ if (stepGateRefused)
217
+ throw new Error(stepGateRefused);
218
+ const stepGated = params.require_successful_steps === true;
219
+ const cwd = params.cwd ?? defaultCwd;
220
+ const sandboxPlan = resolveForegroundSandboxPlan(pi, !!params.ssh, params);
221
+ // The application/shell switches apply before any task state exists, so a
222
+ // refused launch leaves no id, directory, or metadata behind. Structured SSH
223
+ // is checked here too, because its command is a remote shell command. The
224
+ // launch cwd is passed so a relative alias resolves where the task will run.
225
+ assertBackgroundExecutionAllowed(params, sandboxPlan, { remote: Boolean(params.ssh), cwd });
226
+ const commandLimits = backgroundExecutionLimits(sandboxPlan);
227
+ const id = nextTaskId();
228
+ admission?.prepared?.(id);
229
+ const logPath = logPathFor(id);
230
+ ensureTaskDir(id);
231
+ const remoteTask = params.ssh
232
+ ? expandSshRemoteTaskPreset({
233
+ operation: "spawn",
234
+ taskId: id,
235
+ command: params.command,
236
+ cwd,
237
+ env: params.env,
238
+ ssh: params.ssh,
239
+ remote: params.remote,
240
+ }, dependencies.remoteRunner)
241
+ : undefined;
242
+ const operatorSpec = remoteTask?.commandSpec ?? { ...params, cwd, shell: params.shell ?? true };
243
+ const commandSpec = withStepGate(operatorSpec, id, stepGated);
244
+ const sandboxNotices = [];
245
+ const launchSpec = remoteTask
246
+ ? commandSpec
247
+ : confineCommandSpec(commandSpec, sandboxPlan, sandboxProfilePathFor(id), {}, (line) => sandboxNotices.push(line));
248
+ const tmuxBacked = remoteTask?.metadata.remote.session === "tmux";
249
+ // Outside project = Write or Write & delete can change files outside the
250
+ // project: start an APFS local snapshot (macOS, background, never blocks).
251
+ const snapshot = !remoteTask && sandboxPlan.confined ? takeRecoverySnapshot(sandboxPlan.permissions) : undefined;
252
+ const spawned = tmuxBacked
253
+ ? undefined
254
+ : remoteTask
255
+ ? remoteTask.spawn(logPath, true)
256
+ : spawnCommand(launchSpec, logPath, true);
257
+ for (const line of sandboxNotices) {
258
+ try {
259
+ appendLine(logPath, `--- ${line} ---`);
260
+ }
261
+ catch { /* log gone */ }
262
+ }
263
+ if (snapshot?.started) {
264
+ void snapshot.done.then((outcome) => {
265
+ if (!outcome.ok) {
266
+ try {
267
+ appendLine(logPath, `--- recovery snapshot failed (task continues): ${outcome.detail} ---`);
268
+ }
269
+ catch { /* log gone */ }
270
+ }
271
+ });
272
+ }
273
+ const now = Date.now();
274
+ const meta = withCommandPolicy({
275
+ id,
276
+ name: params.name,
277
+ batchId: params.batchId,
278
+ batchName: params.batchName,
279
+ kind: "process",
280
+ status: "running",
281
+ startedAt: now,
282
+ lastProgressAt: now,
283
+ deadlineAt: params.timeout_seconds ? now + params.timeout_seconds * 1000 : undefined,
284
+ logPath,
285
+ callback: params.callback,
286
+ callbackOrigin,
287
+ command: params.command,
288
+ argv: commandSpec.argv,
289
+ shell: commandSpec.shell,
290
+ ...(stepGated ? { requireSuccessfulSteps: true } : {}),
291
+ cwd,
292
+ env: params.env,
293
+ launchArgv: launchArgvOf(commandSpec, launchSpec),
294
+ sandbox: sandboxProvenance(sandboxPlan, !!remoteTask),
295
+ maxLogBytes: resolveMaxLogBytes(params.max_log_bytes),
296
+ pid: spawned?.child.pid,
297
+ pidStartTime: spawned?.child.pid ? readProcessStartToken(spawned.child.pid) : undefined,
298
+ pgid: spawned?.pgid,
299
+ spawnPid: process.pid,
300
+ spawnPidStartTime: currentProcessStartToken(),
301
+ ssh: remoteTask?.metadata.ssh,
302
+ remote: remoteTask?.metadata.remote,
303
+ ...intent,
304
+ }, commandLimits.commandTimeoutSeconds);
305
+ writeMeta(meta);
306
+ scheduleLogRetention(pi, id, getActiveSession);
307
+ if (tmuxBacked && remoteTask) {
308
+ activeRemoteTasks.set(id, remoteTask);
309
+ appendLine(logPath, `--- remote tmux bootstrap ${new Date(now).toISOString()} target=${remoteTask.metadata.ssh.target} session=${remoteTask.metadata.remote.sessionName} ---`);
310
+ void launchRemoteTmux(pi, id, remoteTask, getActiveSession);
311
+ }
312
+ else if (spawned) {
313
+ spawned.child.unref();
314
+ spawned.child.on("close", (exitCode, signal) => {
315
+ clearProcessTimeout(id);
316
+ stopLogRetention(id);
317
+ const latest = readMeta(id);
318
+ if (!latest)
319
+ return;
320
+ enforceLogRetention(latest);
321
+ if (isTerminalStatus(latest.status))
322
+ return;
323
+ // The gate's own marker names the failing step (#619). It never decides the
324
+ // verdict: bash errexit already exits with that step's code (and the gate's EXIT
325
+ // trap forces it when a command disabled errexit), so a missing marker loses the
326
+ // reason, not the failure.
327
+ const stepGateFailure = latest.requireSuccessfulSteps ? readStepGateFailure(latest) : undefined;
328
+ const detail = `Process exited with code ${exitCode ?? "unknown"}${signal ? ` (${signal})` : ""}`;
329
+ if (exitCode !== 0) {
330
+ recordExitFailure(latest, "execution", stepGateFailure
331
+ ? `${detail}; step gate: ${stepGateFailure.command || "a chained step"} exited ${stepGateFailure.stepExitCode}`
332
+ : detail, exitCode, "close", { at: Date.now() });
333
+ }
334
+ else {
335
+ recoverFailure(latest, "execution", "close");
336
+ recoverDeclaredOperation(latest);
337
+ }
338
+ latest.status = exitCode === 0 ? "succeeded" : "failed";
339
+ latest.endedAt = Date.now();
340
+ latest.lastExitCode = exitCode;
341
+ latest.lastSignal = signal;
342
+ if (stepGateFailure)
343
+ latest.stepGateFailure = stepGateFailure;
344
+ latest.result = { exitCode, signal };
345
+ writeMeta(latest);
346
+ void notifyTerminal(pi, latest, getActiveSession);
347
+ });
348
+ }
349
+ scheduleProcessKill(pi, meta, getActiveSession);
350
+ return meta;
351
+ }
352
+ async function launchRemoteTmux(pi, id, remoteTask, getActiveSession) {
353
+ try {
354
+ const beforeBootstrap = readMeta(id);
355
+ const remainingMs = remainingDeadlineMs(beforeBootstrap?.deadlineAt);
356
+ const bootstrap = await remoteTask.bootstrapTmux(remainingMs === undefined
357
+ ? undefined
358
+ : { timeoutMs: Math.min(DEFAULT_TMUX_BOOTSTRAP_TIMEOUT_MS, remainingMs) });
359
+ const latest = readMeta(id);
360
+ if (!latest || latest.status !== "running" || latest.stopRequestedAt)
361
+ return;
362
+ latest.remote = {
363
+ ...latest.remote,
364
+ bootstrapStatus: bootstrap.status,
365
+ bootstrapMessage: bootstrap.message,
366
+ tmuxInstalled: bootstrap.status === "installed",
367
+ };
368
+ appendLine(latest.logPath, `--- remote setup: ${bootstrap.message} ---`);
369
+ writeMeta(latest);
370
+ if (bootstrap.status !== "present" && bootstrap.status !== "installed") {
371
+ recordFailure(latest, "remote-bootstrap", bootstrap.message, "bootstrap", { category: "ssh" });
372
+ latest.error = bootstrap.message;
373
+ finalize(latest, { status: "failed", reason: bootstrap.message }, pi, getActiveSession);
374
+ return;
375
+ }
376
+ recoverFailure(latest, "remote-bootstrap", "bootstrap");
377
+ const startAttempt = remoteTask.startTmuxSession(bootstrap.tmuxPath);
378
+ remoteSessionStarts.set(id, startAttempt);
379
+ let started;
380
+ try {
381
+ started = await startAttempt;
382
+ }
383
+ finally {
384
+ if (remoteSessionStarts.get(id) === startAttempt)
385
+ remoteSessionStarts.delete(id);
386
+ }
387
+ const afterStart = readMeta(id);
388
+ if (!afterStart)
389
+ return;
390
+ if (afterStart.status !== "running" || afterStart.stopRequestedAt) {
391
+ // Stopped (or timed out) while the start was in flight. A stop in this instance awaited the
392
+ // attempt and kills the session itself. Anything else could not see the attempt: a stop from
393
+ // an instance loaded by /reload, or a deadline that found the session not yet started. Only
394
+ // this launch can still reach the session it may just have created, so it kills it (#332).
395
+ if (!remoteStopsAwaitingStart.has(id))
396
+ await killSessionStartedAfterStop(afterStart, remoteTask);
397
+ return;
398
+ }
399
+ if (started.exitCode !== 0) {
400
+ const detail = started.stderr.trim() || started.stdout.trim() || "remote tmux returned no diagnostic";
401
+ const reason = `Could not create remote tmux session ${afterStart.remote?.sessionName} on ${afterStart.ssh?.target} (exit ${started.exitCode ?? "unknown"}): ${detail}`;
402
+ afterStart.error = reason;
403
+ recordFailure(afterStart, "remote-start", reason, "start", { category: "ssh", at: started.endedAt });
404
+ finalize(afterStart, { status: "failed", reason, commandResult: started }, pi, getActiveSession);
405
+ return;
406
+ }
407
+ recoverFailure(afterStart, "remote-start", "start");
408
+ appendLine(afterStart.logPath, `--- remote tmux session ${afterStart.remote?.sessionName} started on ${afterStart.ssh?.target} ---`);
409
+ afterStart.remote = { ...afterStart.remote, sessionStarted: true };
410
+ afterStart.lastProgressAt = Date.now();
411
+ writeMeta(afterStart);
412
+ scheduleRemoteSessionPoll(pi, id, 0, getActiveSession);
413
+ }
414
+ catch (error) {
415
+ failRemoteTask(pi, id, error, getActiveSession);
416
+ }
417
+ }
418
+ /** Kill a tmux session whose start completed after its task stopped; a failed start may still have left it running. */
419
+ async function killSessionStartedAfterStop(meta, remoteTask) {
420
+ const session = `remote tmux session ${meta.remote?.sessionName} on ${meta.ssh?.target}`;
421
+ try {
422
+ const stopped = await remoteTask.killTmuxSession();
423
+ appendLine(meta.logPath, stopped.exitCode === 0
424
+ ? `--- Killed ${session}: it started after the task was ${meta.status === "running" ? "stopped" : meta.status} ---`
425
+ : `--- Could not kill ${session} that started after the task stopped (exit ${stopped.exitCode ?? "unknown"}) ---`);
426
+ }
427
+ catch (error) {
428
+ appendLine(meta.logPath, `--- Could not kill ${session} that started after the task stopped: ${error instanceof Error ? error.message : String(error)} ---`);
429
+ }
430
+ }
431
+ function scheduleRemoteSessionPoll(pi, id, delayMs, getActiveSession) {
432
+ clearRemoteSessionTimer(id);
433
+ if (scheduledWorkSuspended)
434
+ return;
435
+ const dueAt = Date.now() + delayMs;
436
+ const timer = setTimeout(() => void sourceWork("remote-poll", id, () => scheduledWorkSuspended ? undefined : pollRemoteSession(pi, id, getActiveSession), dueAt), delayMs);
437
+ timer.unref();
438
+ remoteSessionTimers.set(id, timer);
439
+ }
440
+ function clearRemoteSessionTimer(id) {
441
+ const timer = remoteSessionTimers.get(id);
442
+ if (timer)
443
+ clearTimeout(timer);
444
+ remoteSessionTimers.delete(id);
445
+ }
446
+ async function pollRemoteSession(pi, id, getActiveSession) {
447
+ if (activePolls.has(id))
448
+ return;
449
+ activePolls.add(id);
450
+ try {
451
+ const meta = readMeta(id);
452
+ const remoteTask = activeRemoteTasks.get(id);
453
+ if (!meta || meta.status !== "running" || meta.remote?.session !== "tmux" || !remoteTask)
454
+ return;
455
+ const poll = await remoteTask.pollTmuxSession(meta.remote.logOffset ?? 0, remainingDeadlineMs(processKillDeadlineMs(meta)));
456
+ if (scheduledWorkSuspended)
457
+ return;
458
+ appendTaskOutput(meta.logPath, poll.output);
459
+ if (poll.status === "timed_out") {
460
+ clearProcessTimeout(id);
461
+ await timeoutProcess(pi, id, getActiveSession);
462
+ return;
463
+ }
464
+ const latest = readMeta(id);
465
+ if (!latest || latest.status !== "running")
466
+ return;
467
+ latest.remote = { ...latest.remote, logOffset: poll.logSize };
468
+ latest.lastCheckedAt = poll.commandResult.endedAt;
469
+ if (poll.output)
470
+ latest.lastProgressAt = poll.commandResult.endedAt;
471
+ enforceLogRetention(latest);
472
+ if (latest.stopRequestedAt) {
473
+ writeMeta(latest);
474
+ return;
475
+ }
476
+ if (poll.status === "running") {
477
+ writeMeta(latest);
478
+ scheduleRemoteSessionPoll(pi, id, REMOTE_SESSION_POLL_MS, getActiveSession);
479
+ return;
480
+ }
481
+ if (poll.status === "missing") {
482
+ const reason = `Remote tmux session ${latest.remote?.sessionName} disappeared on ${latest.ssh?.target} before an exit status was captured.`;
483
+ recordFailure(latest, "remote-session", reason, "missing", { incomplete: true });
484
+ latest.error = reason;
485
+ finalize(latest, { status: "failed", reason }, pi, getActiveSession);
486
+ return;
487
+ }
488
+ const commandResult = { ...poll.commandResult, exitCode: poll.status, stdout: poll.output };
489
+ latest.lastExitCode = poll.status;
490
+ if (poll.status !== 0)
491
+ recordExitFailure(latest, "execution", `Remote command exited with code ${poll.status}`, poll.status, "exit");
492
+ else
493
+ recoverFailure(latest, "execution", "exit");
494
+ finalize(latest, {
495
+ status: poll.status === 0 ? "succeeded" : "failed",
496
+ reason: `remote command exited with code ${poll.status}`,
497
+ commandResult,
498
+ }, pi, getActiveSession);
499
+ }
500
+ catch (error) {
501
+ const latest = readMeta(id);
502
+ if (latest?.status === "running" && latest.deadlineAt !== undefined && Date.now() >= latest.deadlineAt) {
503
+ clearProcessTimeout(id);
504
+ await timeoutProcess(pi, id, getActiveSession);
505
+ }
506
+ else {
507
+ failRemoteTask(pi, id, error, getActiveSession);
508
+ }
509
+ }
510
+ finally {
511
+ activePolls.delete(id);
512
+ }
513
+ }
514
+ function failRemoteTask(pi, id, error, getActiveSession) {
515
+ const meta = readMeta(id);
516
+ if (!meta || meta.status !== "running" || meta.stopRequestedAt)
517
+ return;
518
+ const reason = error instanceof Error ? error.message : String(error);
519
+ meta.error = reason;
520
+ recordFailure(meta, "remote-control", reason, "error", { category: "ssh" });
521
+ finalize(meta, { status: "failed", reason }, pi, getActiveSession);
522
+ }
523
+ function startWatchTask(pi, params, defaultCwd, callbackOrigin, getActiveSession, dependencies = {}) {
524
+ admission?.assert();
525
+ for (const [name, condition] of [["success_when", params.success_when], ["failure_when", params.failure_when]]) {
526
+ const error = condition && validateCondition(condition);
527
+ if (error)
528
+ throw new Error(`${name}: ${error}`);
529
+ }
530
+ if (params.require_successful_steps === true) {
531
+ throw new Error("Invalid step gate: require_successful_steps is for a spawned shell command; a watch poll reports its own exit code as the outcome. The task was not started.");
532
+ }
533
+ const blindChecks = readBlindChecks(params.blind_checks);
534
+ const intent = readTaskIntent(params);
535
+ const cwd = params.cwd ?? defaultCwd;
536
+ const sandboxPlan = resolveForegroundSandboxPlan(pi, !!params.ssh, params, "bg_task_watch");
537
+ assertBackgroundExecutionAllowed(params, sandboxPlan, { remote: Boolean(params.ssh), cwd });
538
+ const commandLimits = backgroundExecutionLimits(sandboxPlan);
539
+ const id = nextTaskId();
540
+ admission?.prepared?.(id);
541
+ const now = Date.now();
542
+ const timeoutSeconds = resolveWatchTimeoutSeconds(params.timeout_seconds);
543
+ const remoteTask = params.ssh
544
+ ? expandSshRemoteTaskPreset({
545
+ operation: "watch",
546
+ command: params.command,
547
+ cwd,
548
+ env: params.env,
549
+ ssh: params.ssh,
550
+ remote: params.remote,
551
+ }, dependencies.remoteRunner)
552
+ : undefined;
553
+ const commandSpec = remoteTask?.commandSpec ?? { ...params, cwd, shell: params.shell ?? true };
554
+ const sandboxNotices = [];
555
+ const launchSpec = remoteTask
556
+ ? commandSpec
557
+ : confineCommandSpec(commandSpec, sandboxPlan, sandboxProfilePathFor(id), {}, (line) => sandboxNotices.push(line), "bg_task_watch");
558
+ const meta = withCommandPolicy({
559
+ id,
560
+ name: params.name,
561
+ kind: "command_watch",
562
+ status: "running",
563
+ startedAt: now,
564
+ lastProgressAt: now,
565
+ deadlineAt: timeoutSeconds ? now + timeoutSeconds * 1000 : undefined,
566
+ intervalMs: Math.max(1, params.interval_seconds ?? 30) * 1000,
567
+ logPath: logPathFor(id),
568
+ callback: params.callback,
569
+ callbackOrigin,
570
+ command: params.command,
571
+ argv: commandSpec.argv,
572
+ shell: commandSpec.shell,
573
+ cwd,
574
+ env: params.env,
575
+ launchArgv: launchArgvOf(commandSpec, launchSpec),
576
+ sandbox: sandboxProvenance(sandboxPlan, !!remoteTask),
577
+ maxLogBytes: resolveMaxLogBytes(params.max_log_bytes),
578
+ spawnPid: process.pid,
579
+ spawnPidStartTime: currentProcessStartToken(),
580
+ successWhen: params.success_when,
581
+ failureWhen: params.failure_when,
582
+ ...(blindChecks !== undefined ? { blindChecks } : {}),
583
+ notifyOn: "terminal",
584
+ ssh: remoteTask?.metadata.ssh,
585
+ remote: remoteTask?.metadata.remote,
586
+ ...intent,
587
+ }, commandLimits.commandTimeoutSeconds);
588
+ ensureTaskDir(id);
589
+ appendLine(meta.logPath, `--- watch ${new Date(now).toISOString()} interval_ms=${meta.intervalMs} ---`);
590
+ for (const line of sandboxNotices)
591
+ appendLine(meta.logPath, `--- ${line} ---`);
592
+ writeMeta(meta);
593
+ scheduleLogRetention(pi, meta.id, getActiveSession);
594
+ let resolveFirst;
595
+ const firstCheck = new Promise((resolve) => { resolveFirst = resolve; });
596
+ firstCheckWaiters.set(id, { promise: firstCheck, resolve: resolveFirst });
597
+ scheduleWatch(pi, id, 0, getActiveSession, remoteTask
598
+ ? (timeoutMs) => remoteTask.runOnce(undefined, timeoutMs)
599
+ : dependencies.watchPollRunner);
600
+ return meta;
601
+ }
602
+ function readBlindChecks(value) {
603
+ if (value === undefined || value === null)
604
+ return undefined;
605
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
606
+ throw new Error("blind_checks must be a non-negative integer (0 turns the blind-check rule off).");
607
+ }
608
+ return value;
609
+ }
610
+ function resolveWatchTimeoutSeconds(timeoutSeconds) {
611
+ if (timeoutSeconds === undefined)
612
+ return DEFAULT_WATCH_TIMEOUT_SECONDS;
613
+ if (timeoutSeconds <= 0)
614
+ return undefined;
615
+ return timeoutSeconds;
616
+ }
617
+ function resumeRunningTask(pi, meta, getActiveSession, dependencies = {}) {
618
+ if (meta.status !== "running") {
619
+ void notifyTerminal(pi, meta, getActiveSession);
620
+ return meta;
621
+ }
622
+ // A corrupt persisted cap must never resume as an unlimited command. Fail
623
+ // the task before any timer, poll, or launch is scheduled.
624
+ const invalidCap = invalidPersistedCommandCap(meta);
625
+ if (invalidCap) {
626
+ finalize(meta, { status: "failed", reason: invalidCap }, pi, getActiveSession);
627
+ return meta;
628
+ }
629
+ scheduleFailureAttention(pi, meta.id, getActiveSession);
630
+ // Same Pi process: an earlier (reloaded or switched-away) extension instance may
631
+ // still hold this task's child or in-flight remote work and record its result.
632
+ const ownedByThisProcess = meta.spawnPid === process.pid && meta.spawnPidStartTime === currentProcessStartToken();
633
+ if (meta.spawnPid !== process.pid || meta.spawnPidStartTime !== currentProcessStartToken()) {
634
+ meta.spawnPid = process.pid;
635
+ meta.spawnPidStartTime = currentProcessStartToken();
636
+ writeMeta(meta);
637
+ }
638
+ scheduleLogRetention(pi, meta.id, getActiveSession);
639
+ const remoteTask = resolvePersistedRemoteTask(meta, dependencies.remoteRunner);
640
+ if (meta.kind === "command_watch") {
641
+ // Shared display refreshes can revisit an already supervised watch. They
642
+ // must not replace its captured interval with a new immediate poll.
643
+ if (watcherTimers.has(meta.id) || activePolls.has(meta.id))
644
+ return meta;
645
+ scheduleWatch(pi, meta.id, 0, getActiveSession, remoteTask
646
+ ? (timeoutMs) => remoteTask.runOnce(undefined, timeoutMs)
647
+ : dependencies.watchPollRunner);
648
+ return meta;
649
+ }
650
+ if (meta.remote?.session === "tmux" && meta.remote.sessionStarted !== false && remoteTask) {
651
+ activeRemoteTasks.set(meta.id, remoteTask);
652
+ scheduleRemoteSessionPoll(pi, meta.id, 0, getActiveSession);
653
+ scheduleProcessKill(pi, meta, getActiveSession);
654
+ // An earlier instance's in-flight timeout kill may still finalize it.
655
+ if (ownedByThisProcess)
656
+ scheduleHandoff(pi, meta.id, getActiveSession);
657
+ return meta;
658
+ }
659
+ if (ownedByThisProcess) {
660
+ // A dead pid is not yet "lost" here: the earlier instance's close listener may
661
+ // still record the real exit. The handoff marks it lost after a grace period.
662
+ scheduleHandoff(pi, meta.id, getActiveSession, remoteTask);
663
+ }
664
+ else if (meta.pid && !processExists(meta.pid)) {
665
+ markProcessLost(pi, meta, getActiveSession);
666
+ return meta;
667
+ }
668
+ scheduleProcessKill(pi, meta, getActiveSession);
669
+ return meta;
670
+ }
671
+ /**
672
+ * Watch a task whose driver may still be an earlier instance in this process: a
673
+ * local child's close listener, or a remote tmux launch that was mid-bootstrap.
674
+ * Deliver the completion once it is recorded terminal, and take over remote
675
+ * polling once the tmux session is recorded as started (#324).
676
+ */
677
+ function scheduleHandoff(pi, id, getActiveSession, remoteTask) {
678
+ stopHandoff(id);
679
+ if (scheduledWorkSuspended)
680
+ return;
681
+ let deadSince;
682
+ let delayMs = HANDOFF_CHECK_MS;
683
+ const check = () => {
684
+ handoffTimers.delete(id);
685
+ const meta = readMeta(id);
686
+ if (!meta) {
687
+ stopHandoff(id);
688
+ return;
689
+ }
690
+ if (meta.status !== "running") {
691
+ stopHandoff(id);
692
+ clearProcessTimeout(id);
693
+ stopLogRetention(id);
694
+ void notifyTerminal(pi, meta, getActiveSession);
695
+ return;
696
+ }
697
+ if (meta.remote?.session === "tmux" && meta.remote.sessionStarted === true && remoteTask && !activeRemoteTasks.has(id)) {
698
+ stopHandoff(id);
699
+ activeRemoteTasks.set(id, remoteTask);
700
+ scheduleRemoteSessionPoll(pi, id, 0, getActiveSession);
701
+ return;
702
+ }
703
+ if (meta.remote?.session !== "tmux" && meta.pid && !processExists(meta.pid)) {
704
+ deadSince ??= Date.now();
705
+ if (Date.now() - deadSince >= HANDOFF_LOST_GRACE_MS) {
706
+ stopHandoff(id);
707
+ clearProcessTimeout(id);
708
+ stopLogRetention(id);
709
+ markProcessLost(pi, meta, getActiveSession);
710
+ return;
711
+ }
712
+ delayMs = HANDOFF_CHECK_MS;
713
+ }
714
+ else {
715
+ delayMs = Math.min(HANDOFF_MAX_CHECK_MS, delayMs * 2);
716
+ }
717
+ arm();
718
+ };
719
+ const arm = () => {
720
+ if (scheduledWorkSuspended)
721
+ return;
722
+ const dueAt = Date.now() + delayMs;
723
+ const timer = setTimeout(() => sourceWork("handoff", id, () => { if (!scheduledWorkSuspended)
724
+ check(); }, dueAt), delayMs);
725
+ timer.unref();
726
+ handoffTimers.set(id, timer);
727
+ };
728
+ arm();
729
+ }
730
+ function stopHandoff(id) {
731
+ const timer = handoffTimers.get(id);
732
+ if (timer)
733
+ clearTimeout(timer);
734
+ handoffTimers.delete(id);
735
+ }
736
+ function markProcessLost(pi, meta, getActiveSession) {
737
+ meta.status = "failed";
738
+ meta.endedAt = Date.now();
739
+ meta.error = "process is no longer alive; exit result was not captured by this pi session";
740
+ meta.result = { reason: meta.error };
741
+ recordFailure(meta, "execution", meta.error, "lost", { incomplete: true });
742
+ writeMeta(meta);
743
+ void notifyTerminal(pi, meta, getActiveSession);
744
+ }
745
+ function resolvePersistedRemoteTask(meta, remoteRunner) {
746
+ if (!meta.ssh || !meta.remote?.session)
747
+ return undefined;
748
+ return expandSshRemoteTaskPreset({
749
+ operation: meta.kind === "command_watch" ? "watch" : "spawn",
750
+ taskId: meta.id,
751
+ sessionName: meta.remote.sessionName,
752
+ command: meta.remote.command || meta.command,
753
+ cwd: meta.cwd,
754
+ env: meta.env,
755
+ ssh: {
756
+ host: meta.ssh.host,
757
+ user: meta.ssh.user,
758
+ port: meta.ssh.port,
759
+ identity_file: meta.ssh.identityFile,
760
+ jump: meta.ssh.jump,
761
+ options: meta.ssh.options,
762
+ },
763
+ remote: {
764
+ session: meta.remote.session,
765
+ install_tmux: meta.remote.installTmux,
766
+ workdir: meta.remote.workdir,
767
+ },
768
+ }, remoteRunner);
769
+ }
770
+ async function stopTask(pi, id, getActiveSession) {
771
+ const meta = readMeta(id);
772
+ if (!meta)
773
+ return undefined;
774
+ if (isTerminalStatus(meta.status))
775
+ return meta;
776
+ meta.stopRequestedAt = Date.now();
777
+ writeMeta(meta);
778
+ clearWatchTimer(id);
779
+ clearRemoteSessionTimer(id);
780
+ clearProcessTimeout(id);
781
+ const remoteStartAttempt = remoteSessionStarts.get(id);
782
+ const remote = meta.remote;
783
+ const remoteSessionMayExist = remote?.session === "tmux"
784
+ && (remote.sessionStarted !== false || remoteStartAttempt !== undefined);
785
+ if (remoteStartAttempt) {
786
+ remoteStopsAwaitingStart.add(id);
787
+ try {
788
+ await remoteStartAttempt;
789
+ }
790
+ catch { /* A failed SSH result can still leave the detached session running. */ }
791
+ finally {
792
+ remoteStopsAwaitingStart.delete(id);
793
+ }
794
+ }
795
+ if (remoteSessionMayExist) {
796
+ const remoteTask = activeRemoteTasks.get(id);
797
+ if (!remoteTask) {
798
+ recordStopError(meta, `Cannot stop remote tmux session ${remote.sessionName}: its active SSH controller is unavailable.`);
799
+ scheduleRemoteSessionPoll(pi, id, REMOTE_SESSION_POLL_MS, getActiveSession);
800
+ return meta;
801
+ }
802
+ try {
803
+ const stopped = await remoteTask.killTmuxSession();
804
+ if (stopped.exitCode !== 0) {
805
+ const detail = stopped.stderr.trim() || stopped.stdout.trim() || "remote tmux returned no diagnostic";
806
+ recordStopError(meta, `Could not kill remote tmux session ${remote.sessionName} on ${meta.ssh?.target} (exit ${stopped.exitCode ?? "unknown"}): ${detail}`);
807
+ scheduleRemoteSessionPoll(pi, id, REMOTE_SESSION_POLL_MS, getActiveSession);
808
+ return meta;
809
+ }
810
+ remote.stopMessage = `Killed remote tmux session ${remote.sessionName} on ${meta.ssh?.target}.`;
811
+ appendLine(meta.logPath, `--- ${remote.stopMessage} ---`);
812
+ }
813
+ catch (error) {
814
+ recordStopError(meta, error instanceof Error ? error.message : String(error));
815
+ scheduleRemoteSessionPoll(pi, id, REMOTE_SESSION_POLL_MS, getActiveSession);
816
+ return meta;
817
+ }
818
+ }
819
+ else if (meta.kind === "process" && meta.pid) {
820
+ try {
821
+ stopProcessGroup(meta.pid, meta.pgid);
822
+ }
823
+ catch (error) {
824
+ recordStopError(meta, error instanceof Error ? error.message : String(error));
825
+ const killAt = processKillDeadlineMs(meta);
826
+ if (killAt !== undefined && killAt > Date.now()) {
827
+ scheduleProcessTimeout(pi, id, killAt, getActiveSession);
828
+ }
829
+ return meta;
830
+ }
831
+ }
832
+ stopFailureAttention(id);
833
+ meta.status = "cancelled";
834
+ meta.stopError = undefined;
835
+ meta.endedAt = Date.now();
836
+ meta.result = {
837
+ reason: meta.remote?.session === "direct"
838
+ ? "cancelled local SSH client; the remote process may still be running"
839
+ : "cancelled",
840
+ };
841
+ writeMeta(meta);
842
+ stopLogRetention(id);
843
+ activeRemoteTasks.delete(id);
844
+ void notifyTerminal(pi, meta, getActiveSession);
845
+ return meta;
846
+ }
847
+ function recordStopError(meta, message) {
848
+ meta.stopRequestedAt = undefined;
849
+ meta.stopError = message;
850
+ meta.error = message;
851
+ writeMeta(meta);
852
+ }
853
+ function scheduleWatch(pi, id, delayMs, getActiveSession, runOnce) {
854
+ clearWatchTimer(id);
855
+ if (scheduledWorkSuspended)
856
+ return;
857
+ const dueAt = Date.now() + delayMs;
858
+ const timer = setTimeout(() => void sourceWork("watch", id, () => scheduledWorkSuspended ? undefined : pollWatch(pi, id, getActiveSession, runOnce), dueAt), delayMs);
859
+ timer.unref();
860
+ watcherTimers.set(id, timer);
861
+ }
862
+ function clearWatchTimer(id) {
863
+ const timer = watcherTimers.get(id);
864
+ if (timer)
865
+ clearTimeout(timer);
866
+ watcherTimers.delete(id);
867
+ }
868
+ async function pollWatch(pi, id, getActiveSession, runOnce) {
869
+ if (activePolls.has(id))
870
+ return;
871
+ activePolls.add(id);
872
+ let checked;
873
+ try {
874
+ const meta = readMeta(id);
875
+ if (!meta || meta.status !== "running" || meta.kind !== "command_watch")
876
+ return;
877
+ const now = Date.now();
878
+ if (meta.deadlineAt && now >= meta.deadlineAt) {
879
+ finalize(meta, { status: "timed_out", reason: watchTimeoutReason(meta) }, pi, getActiveSession);
880
+ return;
881
+ }
882
+ const timeoutMs = remainingDeadlineMs(meta.deadlineAt);
883
+ // The policy cap bounds one check, never the watch's whole lifetime. The
884
+ // smaller of it and the caller's remaining timeout_seconds wins, and a
885
+ // caller's timeout_seconds:0 cannot disable the policy cap.
886
+ const capMs = commandCapMs(meta);
887
+ const pollTimeoutMs = capMs === undefined ? timeoutMs : timeoutMs === undefined ? capMs : Math.min(timeoutMs, capMs);
888
+ const capBound = capMs !== undefined && (timeoutMs === undefined || capMs < timeoutMs);
889
+ const result = runOnce
890
+ ? await runOnce(pollTimeoutMs)
891
+ : await runCommandOnce(commandSpecFromMeta(meta), undefined, pollTimeoutMs);
892
+ checked = {
893
+ exitCode: result.exitCode, signal: result.signal, durationMs: Math.max(0, result.endedAt - result.startedAt),
894
+ ...(result.timedOut ? { timedOut: true } : {}), stdout: result.stdout, stderr: result.stderr,
895
+ };
896
+ // A poll that was in flight when the session shut down belongs to a stale instance.
897
+ if (scheduledWorkSuspended)
898
+ return;
899
+ appendWatchResult(meta.logPath, result);
900
+ const latest = readMeta(id);
901
+ if (!latest || latest.status !== "running")
902
+ return;
903
+ applyCaptureOverflow(latest, result);
904
+ enforceLogRetention(latest);
905
+ latest.lastCheckedAt = Date.now();
906
+ latest.lastExitCode = result.exitCode;
907
+ latest.lastSignal = result.signal;
908
+ latest.lastState = extractLastState(result);
909
+ observeWatchOutcome(latest, result);
910
+ const pollKey = result.startedAt;
911
+ if (result.timedOut) {
912
+ finalize(latest, { status: "timed_out", reason: capBound ? commandCapReason(latest) : watchTimeoutReason(latest), commandResult: result }, pi, getActiveSession);
913
+ return;
914
+ }
915
+ const conditionErrors = [];
916
+ delete latest.error;
917
+ for (const [name, condition] of [["success_when", latest.successWhen], ["failure_when", latest.failureWhen]]) {
918
+ const error = condition && validateCondition(condition);
919
+ if (error) {
920
+ latest.error = `${name}: ${error}`;
921
+ if (result.exitCode !== 0)
922
+ recordExitFailure(latest, "watch-poll", `Watch poll exited with code ${result.exitCode ?? "unknown"}`, result.exitCode, pollKey, { at: result.endedAt });
923
+ recordFailure(latest, name, latest.error, pollKey, { incomplete: true, at: result.endedAt });
924
+ finalize(latest, { status: "failed", reason: latest.error, commandResult: result }, pi, getActiveSession);
925
+ return;
926
+ }
927
+ }
928
+ // Evaluate both conditions before deciding whether either can terminate the watch.
929
+ const failure = latest.failureWhen ? evaluateCondition(latest.failureWhen, result) : undefined;
930
+ const success = latest.successWhen ? evaluateCondition(latest.successWhen, result) : undefined;
931
+ for (const [name, match] of [["failure_when", failure], ["success_when", success]]) {
932
+ if (match?.error) {
933
+ conditionErrors.push(`${name}: ${match.error}`);
934
+ recordFailure(latest, name, `${name}: ${match.error}`, pollKey, { incomplete: true, at: result.endedAt });
935
+ }
936
+ else if (match) {
937
+ recoverFailure(latest, name, pollKey, result.endedAt);
938
+ }
939
+ }
940
+ const transportFailure = sshTransportFailure(latest, result);
941
+ const expectedPollExit = !transportFailure && !conditionErrors.length && failure?.matched !== true &&
942
+ success?.matched === true && latest.successWhen?.type === "exit_code";
943
+ if (expectedPollExit)
944
+ recoverFailure(latest, "watch-poll", pollKey, result.endedAt);
945
+ if (transportFailure)
946
+ recordFailure(latest, "watch-poll", transportFailure, pollKey, { category: "ssh", at: result.endedAt });
947
+ else if (result.exitCode !== 0)
948
+ recordExitFailure(latest, "watch-poll", `Watch poll exited with code ${result.exitCode ?? "unknown"}`, result.exitCode, pollKey, { expected: expectedPollExit, at: result.endedAt });
949
+ else
950
+ recoverFailure(latest, "watch-poll", pollKey, result.endedAt);
951
+ observeBlindCheck(latest, result, pollKey, {
952
+ clean: !transportFailure && !conditionErrors.length,
953
+ matched: failure?.matched === true || success?.matched === true,
954
+ });
955
+ if (conditionErrors.length)
956
+ latest.error = conditionErrors.join("; ");
957
+ if (failure?.matched) {
958
+ recordFailure(latest, "failure_when", "failure condition matched", pollKey, { category: "condition", at: result.endedAt });
959
+ finalize(latest, {
960
+ status: "failed",
961
+ reason: "failure condition matched",
962
+ matchedCondition: latest.failureWhen,
963
+ matchedValue: failure.value,
964
+ commandResult: result,
965
+ }, pi, getActiveSession);
966
+ return;
967
+ }
968
+ if (transportFailure) {
969
+ latest.error = transportFailure;
970
+ finalize(latest, { status: "failed", reason: transportFailure, commandResult: result }, pi, getActiveSession);
971
+ return;
972
+ }
973
+ if (conditionErrors.length) {
974
+ writeMeta(latest);
975
+ scheduleFailureAttention(pi, id, getActiveSession);
976
+ scheduleWatch(pi, id, nextWatchDelayMs(latest), getActiveSession, runOnce);
977
+ return;
978
+ }
979
+ if (success?.matched) {
980
+ finalize(latest, {
981
+ status: "succeeded",
982
+ reason: "success condition matched",
983
+ matchedCondition: latest.successWhen,
984
+ matchedValue: success.value,
985
+ commandResult: result,
986
+ }, pi, getActiveSession);
987
+ return;
988
+ }
989
+ writeMeta(latest);
990
+ scheduleFailureAttention(pi, id, getActiveSession);
991
+ scheduleWatch(pi, id, nextWatchDelayMs(latest), getActiveSession, runOnce);
992
+ }
993
+ catch (error) {
994
+ const meta = readMeta(id);
995
+ if (meta && meta.status === "running") {
996
+ const detail = readableError(error);
997
+ const reason = meta.ssh ? `SSH poll to ${meta.ssh.target} failed: ${detail}` : detail;
998
+ if (meta.ssh) {
999
+ meta.error = reason;
1000
+ appendLine(meta.logPath, `--- poll error ${new Date().toISOString()} ---\n${reason}`);
1001
+ }
1002
+ recordFailure(meta, "watch-poll", reason, `throw:${meta.lastCheckedAt ?? meta.startedAt}`, { category: meta.ssh ? "ssh" : "execution" });
1003
+ finalize(meta, { status: "failed", reason }, pi, getActiveSession);
1004
+ checked ??= { exitCode: null, signal: null, durationMs: 0, stdout: "", stderr: "", error: reason };
1005
+ }
1006
+ }
1007
+ finally {
1008
+ activePolls.delete(id);
1009
+ if (firstCheckWaiters.has(id)) {
1010
+ if (checked)
1011
+ settleFirstCheck(id, checked);
1012
+ else if (readMeta(id)?.status !== "running")
1013
+ settleFirstCheck(id, undefined);
1014
+ }
1015
+ }
1016
+ }
1017
+ /**
1018
+ * Blind-check rule (#359). A check that exits 0, writes stderr, and matches neither condition
1019
+ * is probably broken: it prints an error and then reports "still pending" forever (the real
1020
+ * incident was a gcloud --format error followed by `exit 0`). After `blindChecks` such checks
1021
+ * in a row, record one actionable incident; the existing attention path wakes the parent once.
1022
+ * The watch keeps running. A later check with empty stderr, whatever its exit code (including a
1023
+ * non-zero, SSH-transport-failed or condition-error check), or one matching a condition,
1024
+ * recovers it; those failures are recorded as their own incidents. Any other check (non-zero
1025
+ * with stderr) resets the count and leaves the incident open. A clean pending check (exit 0,
1026
+ * no stderr) never counts.
1027
+ */
1028
+ function observeBlindCheck(meta, result, pollKey, check) {
1029
+ const threshold = meta.blindChecks ?? DEFAULT_BLIND_CHECKS;
1030
+ const stderr = result.stderr.trim();
1031
+ const blind = threshold > 0 && check.clean && !check.matched && result.exitCode === 0 && stderr.length > 0;
1032
+ if (!blind) {
1033
+ meta.blindCheckStreak = 0;
1034
+ if (!stderr || check.matched)
1035
+ recoverFailure(meta, BLIND_OPERATION, pollKey, result.endedAt);
1036
+ return;
1037
+ }
1038
+ const streak = (meta.blindCheckStreak ?? 0) + 1;
1039
+ meta.blindCheckStreak = streak;
1040
+ if (streak !== threshold)
1041
+ return;
1042
+ const lastLine = stderr.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).at(-1) ?? "";
1043
+ const clipped = lastLine.length > 240 ? `${lastLine.slice(0, 239)}…` : lastLine;
1044
+ // The summary is capped in compact rows; the stderr line rides as evidence, which rows show whole.
1045
+ recordFailure(meta, BLIND_OPERATION, `Blind watch check: ${streak} checks in a row exited 0 with stderr and matched no condition; the check may be broken. The watch keeps running.`, pollKey, { category: "blind-check", at: result.endedAt, evidence: `latest stderr: ${clipped} · ${BLIND_CHECK_HINT}` });
1046
+ }
1047
+ function finalize(meta, terminal, pi, getActiveSession) {
1048
+ stopFailureAttention(meta.id);
1049
+ if (terminal.status === "timed_out")
1050
+ recordFailure(meta, "timeout", terminal.reason, "deadline", { category: "timeout" });
1051
+ if (terminal.status === "succeeded")
1052
+ recoverDeclaredOperation(meta);
1053
+ meta.status = terminal.status;
1054
+ meta.endedAt = Date.now();
1055
+ meta.result = {
1056
+ reason: terminal.reason,
1057
+ matchedCondition: terminal.matchedCondition,
1058
+ matchedValue: terminal.matchedValue,
1059
+ exitCode: terminal.commandResult?.exitCode,
1060
+ signal: terminal.commandResult?.signal,
1061
+ };
1062
+ if (terminal.commandResult) {
1063
+ applyCaptureOverflow(meta, terminal.commandResult);
1064
+ meta.lastExitCode = terminal.commandResult.exitCode;
1065
+ meta.lastSignal = terminal.commandResult.signal;
1066
+ meta.lastCheckedAt = terminal.commandResult.endedAt;
1067
+ meta.lastState = extractLastState(terminal.commandResult);
1068
+ }
1069
+ writeMeta(meta);
1070
+ clearWatchTimer(meta.id);
1071
+ clearRemoteSessionTimer(meta.id);
1072
+ clearProcessTimeout(meta.id);
1073
+ activeRemoteTasks.delete(meta.id);
1074
+ stopLogRetention(meta.id);
1075
+ void notifyTerminal(pi, meta, getActiveSession);
1076
+ }
1077
+ function sshTransportFailure(meta, result) {
1078
+ if (!meta.ssh || result.exitCode !== 255)
1079
+ return undefined;
1080
+ const detail = readableError(result.stderr || result.stdout);
1081
+ return `SSH poll to ${meta.ssh.target} failed with exit 255${detail ? `: ${detail}` : ""}`;
1082
+ }
1083
+ function readableError(error) {
1084
+ const value = error instanceof Error ? error.message : String(error);
1085
+ return value.replace(/\s+/g, " ").trim().slice(0, 500);
1086
+ }
1087
+ function watchTimeoutReason(meta) {
1088
+ return meta.ssh ? `timeout waiting for SSH watch condition on ${meta.ssh.target}` : "timeout";
1089
+ }
1090
+ function nextWatchDelayMs(meta) {
1091
+ const intervalMs = meta.intervalMs ?? 30_000;
1092
+ if (!meta.deadlineAt)
1093
+ return intervalMs;
1094
+ return Math.max(0, Math.min(intervalMs, meta.deadlineAt - Date.now()));
1095
+ }
1096
+ function remainingDeadlineMs(deadlineAt) {
1097
+ if (deadlineAt === undefined)
1098
+ return undefined;
1099
+ return Math.max(1, deadlineAt - Date.now());
1100
+ }
1101
+ /** A validated persisted per-command cap, in milliseconds. */
1102
+ function commandCapMs(meta) {
1103
+ const seconds = persistedCommandCapSeconds(meta);
1104
+ if (seconds === undefined)
1105
+ return undefined;
1106
+ return Math.max(1, Math.round(seconds * 1000));
1107
+ }
1108
+ /**
1109
+ * When a spawned task's command hits the policy cap.
1110
+ *
1111
+ * A spawn task is one command, so the cap runs from the launch (`startedAt`). A
1112
+ * resumed task keeps that same snapshot, which is why the cap is measured from
1113
+ * the persisted start rather than from the moment of resume.
1114
+ */
1115
+ function commandCapDeadlineMs(meta) {
1116
+ const capMs = commandCapMs(meta);
1117
+ return capMs === undefined ? undefined : meta.startedAt + capMs;
1118
+ }
1119
+ /** The smaller of the caller's whole-task deadline and the policy cap. */
1120
+ function processKillDeadlineMs(meta) {
1121
+ const capDeadlineAt = commandCapDeadlineMs(meta);
1122
+ if (capDeadlineAt === undefined)
1123
+ return meta.deadlineAt;
1124
+ if (meta.deadlineAt === undefined)
1125
+ return capDeadlineAt;
1126
+ return Math.min(capDeadlineAt, meta.deadlineAt);
1127
+ }
1128
+ /** True when the cap, not the caller's timeout_seconds, ends this command first. */
1129
+ function capEndsFirst(meta) {
1130
+ const capDeadlineAt = commandCapDeadlineMs(meta);
1131
+ return capDeadlineAt !== undefined && (meta.deadlineAt === undefined || capDeadlineAt < meta.deadlineAt);
1132
+ }
1133
+ function commandCapReason(meta) {
1134
+ return `timeout: Background tasks command time limit of ${persistedCommandCapSeconds(meta)}s was reached`;
1135
+ }
1136
+ function scheduleProcessKill(pi, meta, getActiveSession) {
1137
+ const killAt = processKillDeadlineMs(meta);
1138
+ if (killAt !== undefined)
1139
+ scheduleProcessTimeout(pi, meta.id, killAt, getActiveSession);
1140
+ }
1141
+ function scheduleProcessTimeout(pi, id, deadlineAt, getActiveSession) {
1142
+ clearProcessTimeout(id);
1143
+ if (scheduledWorkSuspended)
1144
+ return;
1145
+ const delay = Math.max(0, deadlineAt - Date.now());
1146
+ const dueAt = deadlineAt;
1147
+ const timer = setTimeout(() => void sourceWork("process-deadline", id, () => scheduledWorkSuspended ? undefined : timeoutProcess(pi, id, getActiveSession), dueAt), delay);
1148
+ timer.unref();
1149
+ processTimeoutTimers.set(id, timer);
1150
+ }
1151
+ function clearProcessTimeout(id) {
1152
+ const timer = processTimeoutTimers.get(id);
1153
+ if (timer)
1154
+ clearTimeout(timer);
1155
+ processTimeoutTimers.delete(id);
1156
+ }
1157
+ async function timeoutProcess(pi, id, getActiveSession) {
1158
+ if (activeProcessTimeouts.has(id))
1159
+ return;
1160
+ activeProcessTimeouts.add(id);
1161
+ try {
1162
+ await finalizeProcessTimeout(pi, id, getActiveSession);
1163
+ }
1164
+ finally {
1165
+ activeProcessTimeouts.delete(id);
1166
+ }
1167
+ }
1168
+ async function finalizeProcessTimeout(pi, id, getActiveSession) {
1169
+ const meta = readMeta(id);
1170
+ if (!meta || meta.status !== "running" || meta.kind !== "process")
1171
+ return;
1172
+ let reason = capEndsFirst(meta) ? commandCapReason(meta) : "timeout";
1173
+ if (meta.remote?.session === "tmux" && meta.remote.sessionStarted !== true) {
1174
+ reason = `timeout before remote tmux session ${meta.remote.sessionName} started on ${meta.ssh?.target}`;
1175
+ }
1176
+ else if (meta.remote?.session === "tmux") {
1177
+ const remoteTask = activeRemoteTasks.get(id);
1178
+ if (!remoteTask) {
1179
+ reason = `timeout; remote tmux session ${meta.remote.sessionName} on ${meta.ssh?.target} could not be killed because its SSH controller is unavailable`;
1180
+ meta.error = reason;
1181
+ }
1182
+ else {
1183
+ try {
1184
+ const stopped = await remoteTask.killTmuxSession();
1185
+ if (stopped.exitCode === 0) {
1186
+ meta.remote.stopMessage = `Killed remote tmux session ${meta.remote.sessionName} on ${meta.ssh?.target} after timeout.`;
1187
+ appendLine(meta.logPath, `--- ${meta.remote.stopMessage} ---`);
1188
+ reason = `timeout; killed remote tmux session ${meta.remote.sessionName} on ${meta.ssh?.target}`;
1189
+ }
1190
+ else {
1191
+ const detail = stopped.stderr.trim() || stopped.stdout.trim() || "remote tmux returned no diagnostic";
1192
+ reason = `timeout; could not kill remote tmux session ${meta.remote.sessionName} on ${meta.ssh?.target} (exit ${stopped.exitCode ?? "unknown"}): ${detail}`;
1193
+ meta.error = reason;
1194
+ }
1195
+ }
1196
+ catch (error) {
1197
+ reason = `timeout; could not kill remote tmux session ${meta.remote.sessionName} on ${meta.ssh?.target}: ${readableError(error)}`;
1198
+ meta.error = reason;
1199
+ }
1200
+ }
1201
+ }
1202
+ else {
1203
+ if (meta.pid) {
1204
+ try {
1205
+ stopProcessGroup(meta.pid, meta.pgid);
1206
+ }
1207
+ catch (error) {
1208
+ reason = `timeout; could not terminate local process tree: ${readableError(error)}`;
1209
+ // The task is still running: this is a stop failure, reported as such.
1210
+ recordStopError(meta, reason);
1211
+ return;
1212
+ }
1213
+ }
1214
+ if (meta.remote?.session === "direct") {
1215
+ reason = "timeout; terminated local SSH client, but the remote process may still be running";
1216
+ }
1217
+ }
1218
+ const latest = readMeta(id);
1219
+ if (!latest || latest.status !== "running")
1220
+ return;
1221
+ latest.remote = latest.remote && meta.remote
1222
+ ? { ...latest.remote, stopMessage: meta.remote.stopMessage }
1223
+ : meta.remote;
1224
+ latest.error = meta.error;
1225
+ finalize(latest, { status: "timed_out", reason }, pi, getActiveSession);
1226
+ }
1227
+ async function notifyTerminal(pi, meta, getActiveSession) {
1228
+ observeTaskStallAttention(readMeta(meta.id) ?? meta);
1229
+ // A suspended instance has no active session: delivering or suppressing here would
1230
+ // be wrong either way. The instance that resumes the task delivers it (#324).
1231
+ if (scheduledWorkSuspended)
1232
+ return;
1233
+ if (meta.callback === false || meta.callbackSentAt || meta.callbackSuppressedAt)
1234
+ return;
1235
+ const latest = readMeta(meta.id) ?? meta;
1236
+ if (latest.callback === false || latest.callbackSentAt || latest.callbackSuppressedAt)
1237
+ return;
1238
+ // Cancellation is an explicit action by the agent or user, so a completion
1239
+ // wakeup would be noise. Record the suppression durably so the session_start
1240
+ // replay path never fires a callback for a cancelled task either.
1241
+ if (latest.status === "cancelled") {
1242
+ latest.callbackSuppressedAt = Date.now();
1243
+ latest.callbackSuppressedReason = "task was cancelled; no completion callback is needed";
1244
+ writeMeta(latest);
1245
+ return;
1246
+ }
1247
+ const pending = terminalFailureAttention(latest.id);
1248
+ const label = latest.name ? `${latest.name} (${latest.id})` : latest.id;
1249
+ const facts = formatCallbackFacts(latest);
1250
+ const enqueue = (event) => deliverCompletion ? deliverCompletion(latest.callbackOrigin, event) : getCallbackBatcher(pi).enqueue(event);
1251
+ enqueue({
1252
+ receiptId: `background-legacy:${latest.id}:${latest.endedAt ?? latest.startedAt}`,
1253
+ source: "background-task",
1254
+ id: latest.id,
1255
+ label,
1256
+ // Lifecycle plus an attention count; the incident text rides failureRows
1257
+ // with exact counts, so the status field is never a clipped summary (#323).
1258
+ status: pending
1259
+ ? `${latest.status}; ${pending.incidents.length} incident${pending.incidents.length === 1 ? "" : "s"} need${pending.incidents.length === 1 ? "s" : ""} attention`
1260
+ : latest.status,
1261
+ detailTool: "bg_task_status",
1262
+ outcome: facts.outcome,
1263
+ failureRows: facts.failureRows,
1264
+ decision: facts.decision,
1265
+ incidentCount: facts.incidentCount,
1266
+ callback: true,
1267
+ isDelivered: () => {
1268
+ const current = readMeta(latest.id);
1269
+ return current?.callbackSentAt !== undefined || current?.callbackSuppressedAt !== undefined;
1270
+ },
1271
+ getSuppressionReason: () => {
1272
+ const current = readMeta(latest.id);
1273
+ if (!current)
1274
+ throw new Error("Background task metadata is unavailable; defer completion");
1275
+ return getCallbackSuppressionReason(current, getActiveSession?.());
1276
+ },
1277
+ onDelivered: (at) => {
1278
+ const current = readMeta(latest.id);
1279
+ if (!current || current.callbackSentAt !== undefined || current.callbackSuppressedAt !== undefined)
1280
+ return;
1281
+ current.callbackSentAt = at;
1282
+ writeMeta(current);
1283
+ if (pending)
1284
+ markFailureAttentionDelivered(failurePath(latest.id), pending, at);
1285
+ },
1286
+ onSuppressed: (reason, at) => {
1287
+ const current = readMeta(latest.id);
1288
+ if (!current || current.callbackSentAt !== undefined || current.callbackSuppressedAt !== undefined)
1289
+ return;
1290
+ current.callbackSuppressedAt = at;
1291
+ current.callbackSuppressedReason = reason;
1292
+ writeMeta(current);
1293
+ },
1294
+ });
1295
+ }
1296
+ function getCallbackSuppressionReason(meta, activeSession) {
1297
+ const origin = meta.callbackOrigin;
1298
+ if (origin) {
1299
+ if (!activeSession)
1300
+ return "active session identity is unavailable";
1301
+ if (origin.cwd !== activeSession.cwd)
1302
+ return `origin cwd ${origin.cwd} does not match active cwd ${activeSession.cwd}`;
1303
+ if (origin.sessionId && origin.sessionId !== activeSession.sessionId) {
1304
+ return `origin session ${origin.sessionId} does not match active session ${activeSession.sessionId ?? "unknown"}`;
1305
+ }
1306
+ return undefined;
1307
+ }
1308
+ if (activeSession && meta.cwd !== activeSession.cwd) {
1309
+ return `legacy task cwd ${meta.cwd} does not match active cwd ${activeSession.cwd}`;
1310
+ }
1311
+ return undefined;
1312
+ }
1313
+ function commandSpecFromMeta(meta) {
1314
+ // A task that launched under a sandbox re-runs the wrapper it captured then,
1315
+ // not whatever the foreground policy says now — including after a resume in a
1316
+ // later Pi session.
1317
+ if (meta.launchArgv?.length) {
1318
+ return {
1319
+ argv: meta.launchArgv,
1320
+ shell: false,
1321
+ cwd: meta.cwd,
1322
+ env: meta.env,
1323
+ };
1324
+ }
1325
+ return {
1326
+ command: meta.command,
1327
+ argv: meta.argv,
1328
+ shell: meta.shell,
1329
+ cwd: meta.cwd,
1330
+ env: meta.env,
1331
+ };
1332
+ }
1333
+ /** Record a launch vector only when confinement actually rewrote the spec. */
1334
+ function launchArgvOf(commandSpec, launchSpec) {
1335
+ return launchSpec === commandSpec ? undefined : launchSpec.argv;
1336
+ }
1337
+ function scheduleLogRetention(pi, id, getActiveSession) {
1338
+ stopLogRetention(id);
1339
+ if (scheduledWorkSuspended)
1340
+ return;
1341
+ let dueAt = Date.now() + LOG_RETENTION_CHECK_MS;
1342
+ const timer = setInterval(() => {
1343
+ const due = dueAt;
1344
+ dueAt = Date.now() + LOG_RETENTION_CHECK_MS;
1345
+ return sourceWork("log-retention", id, () => {
1346
+ if (scheduledWorkSuspended)
1347
+ return;
1348
+ const meta = readMeta(id);
1349
+ if (!meta || meta.status !== "running") {
1350
+ stopLogRetention(id);
1351
+ return;
1352
+ }
1353
+ if (meta.kind === "process")
1354
+ enforceLogRetention(meta);
1355
+ if (observeTaskStallAttention(meta))
1356
+ scheduleFailureAttention(pi, id, getActiveSession);
1357
+ }, due);
1358
+ }, LOG_RETENTION_CHECK_MS);
1359
+ timer.unref();
1360
+ logRetentionTimers.set(id, timer);
1361
+ }
1362
+ function stopLogRetention(id) {
1363
+ const timer = logRetentionTimers.get(id);
1364
+ if (timer)
1365
+ clearInterval(timer);
1366
+ logRetentionTimers.delete(id);
1367
+ }
1368
+ function enforceLogRetention(meta) {
1369
+ try {
1370
+ const log = statSync(meta.logPath);
1371
+ const mtimeMs = Math.trunc(log.mtimeMs);
1372
+ const maintenance = meta.logMaintenance?.mtimeMs === mtimeMs && meta.logMaintenance.size === log.size;
1373
+ // A watch's log only records its own polls, so its mtime is poll activity and
1374
+ // never evidence that the watch's observed outcome moved. Spawned processes
1375
+ // keep taking real log writes as progress.
1376
+ if (meta.kind !== "command_watch" && !maintenance && mtimeMs > (meta.lastProgressAt ?? meta.startedAt)) {
1377
+ meta.lastProgressAt = mtimeMs;
1378
+ writeMeta(meta);
1379
+ }
1380
+ }
1381
+ catch {
1382
+ // Logs are optional progress evidence; retention still proceeds if absent.
1383
+ }
1384
+ const compacted = retainLogTail(meta.logPath, resolveMaxLogBytes(meta.maxLogBytes));
1385
+ if (!compacted)
1386
+ return;
1387
+ meta.logDiscardedBytes = (meta.logDiscardedBytes ?? 0) + compacted.discardedBytes;
1388
+ meta.logRetentionEvents = (meta.logRetentionEvents ?? 0) + 1;
1389
+ meta.logGeneration = (meta.logGeneration ?? 0) + 1;
1390
+ try {
1391
+ const log = statSync(meta.logPath);
1392
+ meta.logMaintenance = { mtimeMs: Math.trunc(log.mtimeMs), size: log.size };
1393
+ }
1394
+ catch { /* Missing log remains an evidence gap. */ }
1395
+ writeMeta(meta);
1396
+ }
1397
+ /** Results whose capture loss is already counted; one poll result is counted once. */
1398
+ const countedCaptureResults = new WeakSet();
1399
+ function applyCaptureOverflow(meta, result) {
1400
+ const stdout = result.stdoutDiscardedBytes ?? 0;
1401
+ const stderr = result.stderrDiscardedBytes ?? 0;
1402
+ if (!result.captureTruncated && stdout === 0 && stderr === 0)
1403
+ return;
1404
+ // pollWatch counts a result before evaluating conditions, and finalize sees
1405
+ // the same result again when that poll ends the watch.
1406
+ if (countedCaptureResults.has(result))
1407
+ return;
1408
+ countedCaptureResults.add(result);
1409
+ meta.stdoutDiscardedBytes = (meta.stdoutDiscardedBytes ?? 0) + stdout;
1410
+ meta.stderrDiscardedBytes = (meta.stderrDiscardedBytes ?? 0) + stderr;
1411
+ meta.captureDiscardedBytes = (meta.captureDiscardedBytes ?? 0) + stdout + stderr;
1412
+ meta.captureOverflowEvents = (meta.captureOverflowEvents ?? 0) + 1;
1413
+ }
1414
+ function extractLastState(result) {
1415
+ try {
1416
+ return JSON.parse(result.stdout);
1417
+ }
1418
+ catch {
1419
+ return result.stdout.slice(0, 4000);
1420
+ }
1421
+ }
1422
+ /** Version tag of the watch outcome fingerprint. A value from another version is adopted, never compared. */
1423
+ const WATCH_FINGERPRINT_VERSION = "v1";
1424
+ /** OSC and CSI control sequences are display markup, not content. */
1425
+ const TERMINAL_ESCAPE = /\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)|\u001b\[[0-?]*[ -/]*[@-~]/g;
1426
+ /**
1427
+ * Text as the terminal would settle it. Redraw frames and control sequences are
1428
+ * display churn: repainting the same visible line is not a new observation.
1429
+ */
1430
+ function settledTerminalText(text) {
1431
+ return text
1432
+ .replace(TERMINAL_ESCAPE, "")
1433
+ .split("\n")
1434
+ .map((line) => {
1435
+ // A CR immediately before LF ends the line; any other CR overwrites it in place.
1436
+ const body = line.endsWith("\r") ? line.slice(0, -1) : line;
1437
+ return (body.split("\r").at(-1) ?? "").replace(/[ \t]+$/, "");
1438
+ })
1439
+ .join("\n")
1440
+ .replace(/\n+$/, "");
1441
+ }
1442
+ /** Objects compare by content regardless of key order, so reordered keys are not progress. */
1443
+ function canonicalJsonText(value) {
1444
+ if (Array.isArray(value))
1445
+ return `[${value.map(canonicalJsonText).join(",")}]`;
1446
+ if (value && typeof value === "object") {
1447
+ const record = value;
1448
+ const entries = Object.keys(record).sort()
1449
+ .map((key) => `${JSON.stringify(key)}:${canonicalJsonText(record[key])}`);
1450
+ return `{${entries.join(",")}}`;
1451
+ }
1452
+ return JSON.stringify(value) ?? "null";
1453
+ }
1454
+ /** stdout compares as JSON content when it parses, and as settled text otherwise. */
1455
+ function canonicalWatchStdout(stdout) {
1456
+ const settled = settledTerminalText(stdout);
1457
+ try {
1458
+ return `json:${canonicalJsonText(JSON.parse(settled))}`;
1459
+ }
1460
+ catch {
1461
+ return `text:${settled}`;
1462
+ }
1463
+ }
1464
+ /**
1465
+ * What a poll observed, independent of when it ran. Exit status, signal, error,
1466
+ * stdout content, and stderr content are included; poll metadata (start time,
1467
+ * end time, duration, check count) is deliberately not, so it can never hide a
1468
+ * watch that reports the same outcome forever. Watch stdout may carry its own
1469
+ * timestamps: projecting meaningful fields is the caller's job, not this
1470
+ * fingerprint's guess.
1471
+ */
1472
+ function watchOutcomeFingerprint(result) {
1473
+ // A runner may report why the check itself could not run; that is part of the
1474
+ // observed outcome, not poll metadata.
1475
+ const reported = result.error;
1476
+ const error = typeof reported === "string" ? settledTerminalText(reported) : null;
1477
+ const payload = JSON.stringify([
1478
+ result.exitCode,
1479
+ result.signal ?? null,
1480
+ result.timedOut === true,
1481
+ error,
1482
+ canonicalWatchStdout(result.stdout),
1483
+ settledTerminalText(result.stderr),
1484
+ ]);
1485
+ return `${WATCH_FINGERPRINT_VERSION}:${createHash("sha256").update(payload).digest("hex")}`;
1486
+ }
1487
+ /**
1488
+ * A watch's state clock advances only when its observed outcome changes. The
1489
+ * poll itself is activity (`lastCheckedAt`), not progress, so a stationary
1490
+ * watch still becomes quiet and then a suspected stall while it keeps polling.
1491
+ * A record with no current fingerprint is adopted without moving the clock, so
1492
+ * an upgrade or reload cannot keep resetting that silence.
1493
+ */
1494
+ function observeWatchOutcome(meta, result) {
1495
+ const fingerprint = watchOutcomeFingerprint(result);
1496
+ const prior = meta.watchFingerprint;
1497
+ meta.watchFingerprint = fingerprint;
1498
+ const comparable = typeof prior === "string" && prior.startsWith(`${WATCH_FINGERPRINT_VERSION}:`);
1499
+ if (!comparable) {
1500
+ if (meta.lastProgressAt === undefined)
1501
+ meta.lastProgressAt = meta.startedAt;
1502
+ return;
1503
+ }
1504
+ if (prior !== fingerprint)
1505
+ meta.lastProgressAt = meta.lastCheckedAt ?? Date.now();
1506
+ }
1507
+ return { awaitFirstWatchCheck, suspendScheduledWork, resumeScheduledWork, spawnTask, startWatchTask, resumeRunningTask, stopTask };
1508
+ }
1509
+ const defaultRuntime = createBackgroundTaskRuntime(defaultAttention);
1510
+ /** Compatibility for callers using the original singleton API. */
1511
+ export const { awaitFirstWatchCheck, suspendScheduledWork, resumeScheduledWork, spawnTask, startWatchTask, resumeRunningTask, stopTask } = defaultRuntime;