pi-better-server 0.5.0 → 0.7.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 (340) hide show
  1. package/package.json +7 -3
  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 +37 -5
  6. package/scripts/event-publication/writer.mjs +3 -8
  7. package/scripts/measure-full-runtime/frontend.ts +10 -2
  8. package/scripts/measure-full-runtime/probe.mjs +4 -2
  9. package/scripts/measure-full-runtime/recovery-trace-loader.mjs +51 -0
  10. package/scripts/measure-full-runtime/recovery-trace.mjs +16 -0
  11. package/scripts/measure-full-runtime.mjs +2 -0
  12. package/scripts/measure-shared-reads.mjs +2 -1
  13. package/scripts/private-runtime/package-lock.json +18 -0
  14. package/scripts/private-runtime/package.json +4 -1
  15. package/scripts/source-provenance.mjs +2 -2
  16. package/scripts/test-on-pi.sh +2 -9
  17. package/src/handshake.ts +1 -1
  18. package/src/hosted-session.ts +32 -4
  19. package/src/maintenance.ts +35 -7
  20. package/src/registry.ts +28 -4
  21. package/src/runtime/attempt-invalidation.ts +54 -0
  22. package/src/runtime/background-history.ts +151 -45
  23. package/src/runtime/background-policy.ts +9 -4
  24. package/src/runtime/background-tools.ts +181 -27
  25. package/src/runtime/background.ts +365 -70
  26. package/src/runtime/cancellation.ts +28 -7
  27. package/src/runtime/catalog-sources.ts +199 -0
  28. package/src/runtime/catalog.ts +53 -21
  29. package/src/runtime/client.ts +22 -2
  30. package/src/runtime/domain/assignment-inbox.mjs +119 -0
  31. package/src/runtime/domain/assignment-observation.d.mts +1 -1
  32. package/src/runtime/domain/assignment-observation.mjs +43 -35
  33. package/src/runtime/domain/background/process-identity.mjs +20 -2
  34. package/src/runtime/domain/background/process.mjs +52 -14
  35. package/src/runtime/domain/background/registry.mjs +61 -3
  36. package/src/runtime/domain/background/supervisor/store.mjs +3 -3
  37. package/src/runtime/domain/background/supervisor/supervisor.mjs +9 -3
  38. package/src/runtime/domain/background/types.mjs +1 -0
  39. package/src/runtime/domain/background-service/adapter-contract.domain.mjs +1 -1
  40. package/src/runtime/domain/background-service/adapter-contract.ts +1 -1
  41. package/src/runtime/domain/background-service/goal-provider.domain.mjs +35 -16
  42. package/src/runtime/domain/background-service/goal-provider.ts +31 -16
  43. package/src/runtime/domain/background-service/index.domain.mjs +25 -9
  44. package/src/runtime/domain/background-service/index.ts +25 -9
  45. package/src/runtime/domain/background-service/managed-authority.domain.mjs +6 -3
  46. package/src/runtime/domain/background-service/managed-authority.ts +5 -3
  47. package/src/runtime/domain/background-service/managed-client.domain.mjs +21 -7
  48. package/src/runtime/domain/background-service/managed-client.ts +20 -7
  49. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +159 -19
  50. package/src/runtime/domain/background-service/managed-frontend.ts +135 -19
  51. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +21 -5
  52. package/src/runtime/domain/background-service/navigator-provider.ts +19 -5
  53. package/src/runtime/domain/background-service/observed-wait-client.domain.mjs +6 -0
  54. package/src/runtime/domain/background-service/observed-wait-client.ts +10 -0
  55. package/src/runtime/domain/background-service/observed-waits.domain.mjs +372 -57
  56. package/src/runtime/domain/background-service/observed-waits.ts +321 -53
  57. package/src/runtime/domain/background-service/process-identity.domain.mjs +20 -2
  58. package/src/runtime/domain/background-service/process-identity.ts +18 -2
  59. package/src/runtime/domain/background-service/process.domain.mjs +52 -14
  60. package/src/runtime/domain/background-service/process.ts +48 -14
  61. package/src/runtime/domain/background-service/registry.domain.mjs +61 -3
  62. package/src/runtime/domain/background-service/registry.ts +53 -5
  63. package/src/runtime/domain/background-service/review-settings.domain.mjs +16 -0
  64. package/src/runtime/domain/background-service/review-settings.ts +18 -0
  65. package/src/runtime/domain/background-service/runtime.domain.mjs +40 -86
  66. package/src/runtime/domain/background-service/runtime.ts +27 -82
  67. package/src/runtime/domain/background-service/sandbox.domain.mjs +14 -15
  68. package/src/runtime/domain/background-service/sandbox.ts +14 -11
  69. package/src/runtime/domain/background-service/shared-callback-batcher.domain.mjs +8 -1
  70. package/src/runtime/domain/background-service/shared-callback-batcher.ts +11 -2
  71. package/src/runtime/domain/background-service/shared-navigator-panels.domain.mjs +24 -2
  72. package/src/runtime/domain/background-service/shared-navigator-panels.ts +26 -4
  73. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +273 -41
  74. package/src/runtime/domain/background-service/shared-navigator.ts +244 -40
  75. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  76. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +53 -41
  77. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  78. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  79. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
  80. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  81. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
  82. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.ts +14 -3
  83. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
  84. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +5 -3
  85. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +44 -4
  86. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +50 -2
  87. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  88. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +9 -0
  89. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
  90. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +12 -0
  91. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.domain.mjs +2 -0
  92. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.ts +2 -0
  93. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +42 -21
  94. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +40 -24
  95. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +26 -4
  96. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +40 -8
  97. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
  98. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  99. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.domain.mjs +1 -1
  100. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.ts +5 -1
  101. package/src/runtime/domain/background-service/shared-sandbox-core.ts +1 -1
  102. package/src/runtime/domain/background-service/shared-work-client.mjs +174 -7
  103. package/src/runtime/domain/background-service/stall.domain.mjs +5 -3
  104. package/src/runtime/domain/background-service/stall.ts +7 -4
  105. package/src/runtime/domain/background-service/supervised-progress.domain.mjs +42 -0
  106. package/src/runtime/domain/background-service/supervised-progress.ts +43 -0
  107. package/src/runtime/domain/background-service/supervisor/README.md +1 -4
  108. package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
  109. package/src/runtime/domain/background-service/supervisor/generated/process-identity.mjs +20 -2
  110. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +52 -14
  111. package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +47 -4
  112. package/src/runtime/domain/background-service/supervisor/generated/store.mjs +3 -3
  113. package/src/runtime/domain/background-service/supervisor/generated/watch-fingerprint.mjs +69 -0
  114. package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +47 -4
  115. package/src/runtime/domain/background-service/supervisor/runner.ts +38 -3
  116. package/src/runtime/domain/background-service/supervisor/store.domain.mjs +3 -3
  117. package/src/runtime/domain/background-service/supervisor/store.ts +3 -3
  118. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +9 -3
  119. package/src/runtime/domain/background-service/supervisor/supervisor.ts +6 -3
  120. package/src/runtime/domain/background-service/task-diagnostics.domain.mjs +1 -1
  121. package/src/runtime/domain/background-service/task-diagnostics.ts +1 -1
  122. package/src/runtime/domain/background-service/tools.domain.mjs +53 -40
  123. package/src/runtime/domain/background-service/tools.ts +67 -54
  124. package/src/runtime/domain/background-service/types.domain.mjs +1 -0
  125. package/src/runtime/domain/background-service/types.ts +7 -3
  126. package/src/runtime/domain/background-service/watch-fingerprint.domain.mjs +67 -0
  127. package/src/runtime/domain/background-service/watch-fingerprint.ts +70 -0
  128. package/src/runtime/domain/background-service/work-observation.domain.mjs +46 -20
  129. package/src/runtime/domain/background-service/work-observation.ts +46 -19
  130. package/src/runtime/domain/catalog/catalog-store.d.mts +9 -1
  131. package/src/runtime/domain/catalog/catalog-store.mjs +20 -22
  132. package/src/runtime/domain/coordinator/src/assignment-changes.mjs +75 -0
  133. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +2 -0
  134. package/src/runtime/domain/coordinator/src/background-requests.mjs +11 -2
  135. package/src/runtime/domain/coordinator/src/discovery.mjs +4 -2
  136. package/src/runtime/domain/coordinator/src/operations.mjs +44 -4
  137. package/src/runtime/domain/coordinator/src/outbox.mjs +7 -0
  138. package/src/runtime/domain/coordinator/src/result-supervision.mjs +12 -0
  139. package/src/runtime/domain/coordinator/src/rows.mjs +2 -0
  140. package/src/runtime/domain/coordinator/src/schema.mjs +42 -21
  141. package/src/runtime/domain/coordinator/src/store.mjs +26 -4
  142. package/src/runtime/domain/coordinator/src/subagent-launch.mjs +23 -1
  143. package/src/runtime/domain/coordinator/src/types.mjs +1 -1
  144. package/src/runtime/domain/health-observation.d.mts +3 -1
  145. package/src/runtime/domain/health-observation.mjs +189 -190
  146. package/src/runtime/domain/log-cursor.d.mts +2 -0
  147. package/src/runtime/domain/log-cursor.mjs +85 -16
  148. package/src/runtime/domain/log-paths.mjs +8 -1
  149. package/src/runtime/domain/parse.d.mts +4 -1
  150. package/src/runtime/domain/parse.mjs +58 -9
  151. package/src/runtime/domain/sandbox-policy/README.md +63 -65
  152. package/src/runtime/domain/sandbox-policy/commands.domain.mjs +11 -8
  153. package/src/runtime/domain/sandbox-policy/commands.ts +12 -7
  154. package/src/runtime/domain/sandbox-policy/index.domain.mjs +53 -9
  155. package/src/runtime/domain/sandbox-policy/index.ts +52 -9
  156. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  157. package/src/runtime/domain/sandbox-policy/permission-settings.domain.mjs +5 -2
  158. package/src/runtime/domain/sandbox-policy/permission-settings.ts +9 -2
  159. package/src/runtime/domain/sandbox-policy/permissions-page.domain.mjs +56 -137
  160. package/src/runtime/domain/sandbox-policy/permissions-page.ts +52 -130
  161. package/src/runtime/domain/sandbox-policy/permissions.domain.mjs +1 -6
  162. package/src/runtime/domain/sandbox-policy/permissions.ts +1 -6
  163. package/src/runtime/domain/sandbox-policy/shared-sandbox-core.ts +1 -1
  164. package/src/runtime/domain/sandbox-policy/shared-task-exec.domain.mjs +14 -1
  165. package/src/runtime/domain/sandbox-policy/shared-task-exec.ts +12 -1
  166. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.domain.mjs +140 -0
  167. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.ts +126 -0
  168. package/src/runtime/domain/sandbox-policy/shared-task-process-list.domain.mjs +3 -2
  169. package/src/runtime/domain/sandbox-policy/shared-task-process-list.ts +8 -2
  170. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.domain.mjs +4 -3
  171. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.ts +5 -3
  172. package/src/runtime/domain/sandbox-policy/shared-task-tools.domain.mjs +8 -5
  173. package/src/runtime/domain/sandbox-policy/shared-task-tools.ts +8 -5
  174. package/src/runtime/domain/session-store.mjs +7 -0
  175. package/src/runtime/domain/subagents/README.md +13 -11
  176. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +10 -7
  177. package/src/runtime/domain/subagents/assignment-outcomes.ts +9 -6
  178. package/src/runtime/domain/subagents/assignment-report.domain.mjs +109 -24
  179. package/src/runtime/domain/subagents/assignment-report.ts +103 -19
  180. package/src/runtime/domain/subagents/batch.mjs +13 -5
  181. package/src/runtime/domain/subagents/catalog-host-admission.domain.mjs +21 -3
  182. package/src/runtime/domain/subagents/catalog-host-admission.ts +19 -3
  183. package/src/runtime/domain/subagents/catalog-preferences.ts +1 -1
  184. package/src/runtime/domain/subagents/catalog-resolver.domain.mjs +35 -1
  185. package/src/runtime/domain/subagents/catalog-resolver.ts +35 -1
  186. package/src/runtime/domain/subagents/catalog-store.domain.mjs +20 -22
  187. package/src/runtime/domain/subagents/catalog-store.ts +27 -20
  188. package/src/runtime/domain/subagents/child-apply-patch.domain.mjs +13 -0
  189. package/src/runtime/domain/subagents/child-apply-patch.ts +13 -0
  190. package/src/runtime/domain/subagents/child-dependencies.mjs +27 -15
  191. package/src/runtime/domain/subagents/child-operations.domain.mjs +80 -2
  192. package/src/runtime/domain/subagents/child-operations.ts +80 -1
  193. package/src/runtime/domain/subagents/child-preflight.mjs +9 -2
  194. package/src/runtime/domain/subagents/child-process-list.domain.mjs +7 -0
  195. package/src/runtime/domain/subagents/child-process-list.ts +8 -0
  196. package/src/runtime/domain/subagents/cleanup.domain.mjs +11 -2
  197. package/src/runtime/domain/subagents/cleanup.ts +10 -2
  198. package/src/runtime/domain/subagents/config.domain.mjs +54 -2
  199. package/src/runtime/domain/subagents/config.ts +53 -3
  200. package/src/runtime/domain/subagents/continuation-authority.domain.mjs +5 -1
  201. package/src/runtime/domain/subagents/continuation-authority.ts +3 -1
  202. package/src/runtime/domain/subagents/continuation-runtime.domain.mjs +89 -0
  203. package/src/runtime/domain/subagents/continuation-runtime.ts +88 -0
  204. package/src/runtime/domain/subagents/continuation.domain.mjs +4 -2
  205. package/src/runtime/domain/subagents/continuation.ts +4 -2
  206. package/src/runtime/domain/subagents/extensions.mjs +11 -13
  207. package/src/runtime/domain/subagents/failures.domain.mjs +11 -2
  208. package/src/runtime/domain/subagents/failures.ts +10 -2
  209. package/src/runtime/domain/subagents/finalization.domain.mjs +16 -1
  210. package/src/runtime/domain/subagents/finalization.ts +21 -1
  211. package/src/runtime/domain/subagents/goal-provider.domain.mjs +44 -2
  212. package/src/runtime/domain/subagents/goal-provider.ts +44 -2
  213. package/src/runtime/domain/subagents/health-observation.domain.mjs +189 -190
  214. package/src/runtime/domain/subagents/health-observation.ts +43 -48
  215. package/src/runtime/domain/subagents/index.domain.mjs +457 -182
  216. package/src/runtime/domain/subagents/index.ts +417 -155
  217. package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +515 -0
  218. package/src/runtime/domain/subagents/isolated-workspace.ts +557 -0
  219. package/src/runtime/domain/subagents/launch-context.domain.mjs +24 -0
  220. package/src/runtime/domain/subagents/launch-context.ts +23 -0
  221. package/src/runtime/domain/subagents/launch-digest.mjs +6 -0
  222. package/src/runtime/domain/subagents/list.mjs +2 -2
  223. package/src/runtime/domain/subagents/log-cursor.domain.mjs +85 -16
  224. package/src/runtime/domain/subagents/log-cursor.ts +91 -15
  225. package/src/runtime/domain/subagents/managed-launch-bootstrap.mjs +2 -2
  226. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +27 -7
  227. package/src/runtime/domain/subagents/managed-launch-client.ts +28 -8
  228. package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +222 -14
  229. package/src/runtime/domain/subagents/managed-launch-host.ts +168 -15
  230. package/src/runtime/domain/subagents/managed-launch-journal.mjs +1 -5
  231. package/src/runtime/domain/subagents/managed-launch-port.ts +4 -0
  232. package/src/runtime/domain/subagents/operation-bridge-types.domain.mjs +27 -2
  233. package/src/runtime/domain/subagents/operation-bridge-types.ts +27 -2
  234. package/src/runtime/domain/subagents/output-payload.domain.mjs +24 -9
  235. package/src/runtime/domain/subagents/output-payload.ts +26 -12
  236. package/src/runtime/domain/subagents/owned-exit.domain.mjs +12 -0
  237. package/src/runtime/domain/subagents/owned-exit.ts +12 -0
  238. package/src/runtime/domain/subagents/package.json +4 -2
  239. package/src/runtime/domain/subagents/parse.domain.mjs +58 -9
  240. package/src/runtime/domain/subagents/parse.ts +57 -10
  241. package/src/runtime/domain/subagents/permission-policy.domain.mjs +32 -8
  242. package/src/runtime/domain/subagents/permission-policy.ts +41 -8
  243. package/src/runtime/domain/subagents/process-identity.mjs +33 -0
  244. package/src/runtime/domain/subagents/registry.domain.mjs +71 -51
  245. package/src/runtime/domain/subagents/registry.ts +77 -38
  246. package/src/runtime/domain/subagents/retained-result.domain.mjs +56 -0
  247. package/src/runtime/domain/subagents/retained-result.ts +65 -0
  248. package/src/runtime/domain/subagents/session-selection.domain.mjs +3 -1
  249. package/src/runtime/domain/subagents/session-selection.ts +2 -1
  250. package/src/runtime/domain/subagents/session-store.domain.mjs +7 -0
  251. package/src/runtime/domain/subagents/session-store.ts +9 -0
  252. package/src/runtime/domain/subagents/settings-page.domain.mjs +151 -107
  253. package/src/runtime/domain/subagents/settings-page.ts +147 -108
  254. package/src/runtime/domain/subagents/shared-callback-batcher.domain.mjs +8 -1
  255. package/src/runtime/domain/subagents/shared-callback-batcher.ts +11 -2
  256. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +28 -29
  257. package/src/runtime/domain/subagents/shared-catalog.ts +29 -21
  258. package/src/runtime/domain/subagents/shared-navigator-panels.domain.mjs +24 -2
  259. package/src/runtime/domain/subagents/shared-navigator-panels.ts +26 -4
  260. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +273 -41
  261. package/src/runtime/domain/subagents/shared-navigator.ts +244 -40
  262. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  263. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +53 -41
  264. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  265. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  266. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
  267. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  268. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
  269. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.ts +14 -3
  270. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
  271. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +5 -3
  272. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +44 -4
  273. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +50 -2
  274. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  275. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +9 -0
  276. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
  277. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +12 -0
  278. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.domain.mjs +2 -0
  279. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.ts +2 -0
  280. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +42 -21
  281. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +40 -24
  282. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +26 -4
  283. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +40 -8
  284. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
  285. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  286. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.domain.mjs +1 -1
  287. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.ts +5 -1
  288. package/src/runtime/domain/subagents/shared-sandbox-core.ts +1 -1
  289. package/src/runtime/domain/subagents/shared-task-exec.domain.mjs +14 -1
  290. package/src/runtime/domain/subagents/shared-task-exec.ts +12 -1
  291. package/src/runtime/domain/subagents/shared-task-process-identity.domain.mjs +140 -0
  292. package/src/runtime/domain/subagents/shared-task-process-identity.ts +126 -0
  293. package/src/runtime/domain/subagents/shared-task-process-list.domain.mjs +3 -2
  294. package/src/runtime/domain/subagents/shared-task-process-list.ts +8 -2
  295. package/src/runtime/domain/subagents/shared-task-sandbox.domain.mjs +4 -3
  296. package/src/runtime/domain/subagents/shared-task-sandbox.ts +5 -3
  297. package/src/runtime/domain/subagents/shared-task-tools.domain.mjs +8 -5
  298. package/src/runtime/domain/subagents/shared-task-tools.ts +8 -5
  299. package/src/runtime/domain/subagents/shared-work-client.mjs +174 -7
  300. package/src/runtime/domain/subagents/subagent-tools.domain.mjs +22 -38
  301. package/src/runtime/domain/subagents/subagent-tools.ts +28 -34
  302. package/src/runtime/domain/subagents/task-guard.domain.mjs +14 -1
  303. package/src/runtime/domain/subagents/task-guard.ts +13 -1
  304. package/src/runtime/domain/subagents/task-policy.domain.mjs +3 -2
  305. package/src/runtime/domain/subagents/task-policy.ts +8 -2
  306. package/src/runtime/domain/subagents/timing.domain.mjs +10 -1
  307. package/src/runtime/domain/subagents/timing.ts +10 -1
  308. package/src/runtime/domain/subagents/tools.domain.mjs +4 -8
  309. package/src/runtime/domain/subagents/tools.ts +4 -7
  310. package/src/runtime/domain/subagents/work-observation.domain.mjs +102 -17
  311. package/src/runtime/domain/subagents/work-observation.ts +91 -17
  312. package/src/runtime/domain/subagents/worker-operations-host.domain.mjs +9 -4
  313. package/src/runtime/domain/subagents/worker-operations-host.ts +12 -4
  314. package/src/runtime/domain/subagents/worker-waits.domain.mjs +89 -35
  315. package/src/runtime/domain/subagents/worker-waits.ts +93 -34
  316. package/src/runtime/domain/subagents/workspace-files.domain.mjs +103 -0
  317. package/src/runtime/domain/subagents/workspace-files.ts +114 -0
  318. package/src/runtime/domain/subagents/workspace-scope.domain.d.mts +38 -0
  319. package/src/runtime/domain/subagents/workspace-scope.domain.mjs +5 -0
  320. package/src/runtime/domain/subagents/workspace-scope.ts +6 -0
  321. package/src/runtime/domain/subagents/worktree-feedback.domain.mjs +55 -0
  322. package/src/runtime/domain/subagents/worktree-feedback.ts +77 -0
  323. package/src/runtime/health-config.ts +27 -11
  324. package/src/runtime/log-checkpoints.ts +117 -0
  325. package/src/runtime/mutation-store.ts +5 -4
  326. package/src/runtime/queries.ts +25 -2
  327. package/src/runtime/query-executor.ts +149 -28
  328. package/src/runtime/query-worker.mjs +106 -21
  329. package/src/runtime/read-model.ts +849 -121
  330. package/src/runtime/read-watchdog-probe.ts +4 -0
  331. package/src/runtime/result-supervision.ts +188 -16
  332. package/src/runtime/root.ts +5 -2
  333. package/src/runtime/source-watch.ts +175 -0
  334. package/src/runtime/subagent-launch.ts +11 -4
  335. package/src/runtime/work-budget.ts +130 -0
  336. package/src/runtime/work-client.d.mts +8 -0
  337. package/src/runtime/work-client.mjs +150 -7
  338. package/src/server.ts +104 -23
  339. package/src/session-activity.ts +26 -4
  340. package/src/version.ts +1 -1
@@ -12,7 +12,7 @@ import { setParentCallbackPending, listPendingParentCallbacks, listRecentBackgro
12
12
  import { BackgroundRequests } from "./background-requests.ts";
13
13
  import { StoreError } from "./errors.ts";
14
14
  import { SubagentLaunchJournal } from "./subagent-launch.ts";
15
- import { resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.ts";
15
+ import { resultSupervisionChanges, resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.ts";
16
16
  import { acceptTaskCancellation, getTaskCancellation, recordTaskStopRequested, admitTaskCancellation, authorizedTaskCancellation, finishTaskCancellation, cancellationRuntimeEpoch, acceptAuthorizedTaskCancellation, taskCancellationManaged, pendingTaskCancellations, finishTaskCancellationIntent, unknownTaskCancellation } from "./task-cancellation.ts";
17
17
  import type { TaskCancellationIntent, TaskCancellationRequest } from "./task-cancellation.ts";
18
18
  import { repairFailedResume, type RepairResumeInput } from "./recovery.ts";
@@ -26,9 +26,11 @@ import {
26
26
  requirePath,
27
27
  } from "./validate.ts";
28
28
  import { ensureSchema } from "./schema.ts";
29
- import { createContext, openDatabase, type StoreContext } from "./sqlite.ts";
29
+ import { ensureAssignmentChanges } from "./assignment-changes.ts";
30
+ import { createContext, openDatabase, run, type StoreContext } from "./sqlite.ts";
30
31
  import {
31
32
  getOperation as readOperationRecord,
33
+ listAssignmentCleanupOperations as readAssignmentCleanupOperations,
32
34
  listOperations as readOperationRecords,
33
35
  listRunningSupervisedBy as readRunningSupervisedBy,
34
36
  releaseSupervision as writeSupervisionRelease,
@@ -66,6 +68,7 @@ import {
66
68
  } from "./waits.ts";
67
69
  import {
68
70
  claimOutbox as writeOutboxClaim,
71
+ hasDeliveredWaitDependency as readDeliveredWaitDependency,
69
72
  listDispatchableOutboxRecipients as readDispatchableOutboxRecipients,
70
73
  listOutbox as readOutbox,
71
74
  markOutboxDelivered as writeOutboxDelivery,
@@ -124,6 +127,8 @@ import {
124
127
  } from "./types.ts";
125
128
 
126
129
  export interface Store {
130
+ hasSubagentManagement(): boolean;
131
+ resultSupervisionChanges(after?: Parameters<typeof resultSupervisionChanges>[1]): ReturnType<typeof resultSupervisionChanges>;
127
132
  subagentLaunchJournal(): SubagentLaunchJournal;
128
133
  resultScopeManaged(scope: string): boolean;
129
134
  handoffResultScope(input: Parameters<typeof handoffResultScope>[1]): ReturnType<typeof handoffResultScope>;
@@ -160,18 +165,17 @@ export interface Store {
160
165
 
161
166
  // ---- operations ----
162
167
 
163
- /**
164
- * Register a durable operation for one task launch. The owner, task id,
165
- * launch token and observer are immutable: a replay of the same launch
166
- * returns `created: false`, and any difference is refused with
167
- * `operation-conflict` or `task-ownership`.
168
- */
169
168
  backgroundRequests(): BackgroundRequests;
170
169
  setParentCallbackPending(taskId: string, pending: boolean): boolean;
171
170
  listPendingParentCallbacks(scope: ParentCallbackScope, options?: ParentCallbackPage): OperationRecord[];
172
171
  listRecentBackgroundTerminals(options: RecentBackgroundTerminalPage): OperationRecord[];
173
172
  seedPendingParentCallbacks(options?: { limit?: number }): { done: boolean; seeded: number };
174
173
  setUpgradeFence(epoch: string | null): void;
174
+ /**
175
+ * Register a durable launch. Owner, task id, launch token, observer, and
176
+ * assignment attempt provenance are immutable. An exact replay returns
177
+ * `created: false`, even after assignment end, and admits no new work.
178
+ */
175
179
  registerOperation(input: RegisterOperationInput): RegisterOperationResult;
176
180
  /**
177
181
  * Replace supervision identity and/or report observer health
@@ -196,6 +200,12 @@ export interface Store {
196
200
  recordTerminalOutcome(input: RecordTerminalOutcomeInput): RecordTerminalOutcomeResult;
197
201
  getOperation(operationId: string): OperationRecord | null;
198
202
  listOperations(filter?: OperationFilter): OperationRecord[];
203
+ /**
204
+ * Read up to 256 unfinished cleanup obligations in operation id order.
205
+ * The cursor is exclusive. Start each new sweep without a cursor.
206
+ */
207
+ listAssignmentCleanupOperations(limit: number, afterOperationId?: string): OperationRecord[];
208
+ verifyAssignmentCleanup(operationId: string, launchToken: string, terminalRevision: number): boolean;
199
209
  /** Running operations currently assigned to this supervising host. */
200
210
  listRunningSupervisedBy(hostId: string): OperationRecord[];
201
211
  listOperationEvidence(operationId: string, terminalRevision?: number): OperationEvidenceRecord[];
@@ -309,6 +319,7 @@ export interface Store {
309
319
  // ---- outbox ----
310
320
 
311
321
  listOutbox(filter?: OutboxFilter): OutboxEventRecord[];
322
+ hasDeliveredWaitDependency(operationId: string, terminalRevision: number, recipient: OwnerIdentity): boolean;
312
323
  /** Lightweight dispatch candidates; evidence is read only after a claim succeeds. */
313
324
  listDispatchableOutboxRecipients(): Array<{ recipient: OwnerIdentity; count: number }>;
314
325
  /** Claim pending deliveries for a `ready`/`resuming` generation. */
@@ -327,6 +338,7 @@ export function openStore(options: StoreOptions): Store {
327
338
  const ctx: StoreContext = createContext(db, options.now ? { now: options.now } : {});
328
339
  try {
329
340
  ensureSchema(ctx);
341
+ ensureAssignmentChanges(ctx);
330
342
  } catch (error) {
331
343
  try {
332
344
  db.close();
@@ -351,6 +363,8 @@ export function openStore(options: StoreOptions): Store {
351
363
  resultScopeManaged(scope) { alive(); return resultScopeManaged(ctx, scope); },
352
364
  handoffResultScope(input) { alive(); return handoffResultScope(ctx, input); },
353
365
  resultSupervision(id) { alive(); return resultSupervision(ctx, id); },
366
+ hasSubagentManagement() { alive(); return Boolean(ctx.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='subagent_management'").get()); },
367
+ resultSupervisionChanges(after) { alive(); return resultSupervisionChanges(ctx, after); },
354
368
  resultSupervisions(activeOnly) { alive(); return resultSupervisions(ctx, activeOnly); },
355
369
  handoffResultSupervision(input) { alive(); return handoffResultSupervision(ctx, input); },
356
370
  handoffResultSupervisions(input) { alive(); return handoffResultSupervisions(ctx, input); },
@@ -408,6 +422,20 @@ export function openStore(options: StoreOptions): Store {
408
422
  alive();
409
423
  return readOperationRecords(ctx, filter);
410
424
  },
425
+ listAssignmentCleanupOperations(limit, afterOperationId) {
426
+ alive();
427
+ return readAssignmentCleanupOperations(ctx, limit, afterOperationId);
428
+ },
429
+ verifyAssignmentCleanup(operationId, launchToken, terminalRevision) {
430
+ alive();
431
+ if (!Number.isSafeInteger(terminalRevision) || terminalRevision < 1) return false;
432
+ return run(ctx, `INSERT OR IGNORE INTO coordinator_state (key, value)
433
+ SELECT 'assignment-cleanup-verified:' || op.operation_id, op.launch_token
434
+ FROM operations op JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
435
+ JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
436
+ WHERE op.operation_id = ? AND op.launch_token = ? AND op.terminal_revision = ?`,
437
+ operationId, launchToken, terminalRevision) > 0;
438
+ },
411
439
  listRunningSupervisedBy(hostId) {
412
440
  alive();
413
441
  return readRunningSupervisedBy(ctx, hostId);
@@ -533,6 +561,10 @@ export function openStore(options: StoreOptions): Store {
533
561
  alive();
534
562
  return readOutbox(ctx, filter);
535
563
  },
564
+ hasDeliveredWaitDependency(operationId, terminalRevision, recipient) {
565
+ alive();
566
+ return readDeliveredWaitDependency(ctx, operationId, terminalRevision, recipient);
567
+ },
536
568
  listDispatchableOutboxRecipients() {
537
569
  alive();
538
570
  return readDispatchableOutboxRecipients(ctx);
@@ -1,6 +1,6 @@
1
1
  // Generated fixed launch domain from packages/pi-better-background-tasks/src/shared-operation-coordinator/src/subagent-launch.ts. Do not edit directly.
2
2
  // Generated from packages/operation-coordinator/src/subagent-launch.ts. Do not edit directly.
3
- import { randomBytes } from "node:crypto";
3
+ import { createHash, randomBytes } from "node:crypto";
4
4
  /** Fixed launch journal on the coordinator's existing connection and transaction. */
5
5
  export class SubagentLaunchJournal {
6
6
  context;
@@ -41,6 +41,25 @@ export class SubagentLaunchJournal {
41
41
  pendingIntents() {
42
42
  return this.db.prepare("SELECT * FROM subagent_launch_intents WHERE state='accepted'").all();
43
43
  }
44
+ progressKey(owner, key) { return `launch-progress:${createHash('sha256').update(JSON.stringify([owner, key])).digest('hex')}`; }
45
+ progress(owner, key) {
46
+ const row = this.db.prepare('SELECT value FROM coordinator_state WHERE key=?').get(this.progressKey(owner, key));
47
+ return row ? JSON.parse(String(row.value)) : undefined;
48
+ }
49
+ noteProgress(owner, key) {
50
+ const previous = this.progress(owner, key), now = Date.now();
51
+ this.db.prepare('INSERT OR REPLACE INTO coordinator_state (key,value) VALUES (?,?)').run(this.progressKey(owner, key), JSON.stringify({ acceptedAt: previous?.acceptedAt ?? now, lastProgressAt: now }));
52
+ }
53
+ lifecycleReasons(owner, key) {
54
+ const exact = owner !== undefined && key !== undefined ? this.read(owner, key) : undefined;
55
+ const intents = owner !== undefined ? exact?.state === 'accepted' ? [exact] : [] : this.pendingIntents();
56
+ return intents.map(intent => ({ kind: 'task', id: this.progressKey(intent.owner, intent.request_key),
57
+ owner: intent.owner, management: { epoch: intent.epoch }, acceptedAt: this.progress(intent.owner, intent.request_key)?.acceptedAt ?? null,
58
+ lastProgressAt: this.progress(intent.owner, intent.request_key)?.lastProgressAt ?? null, executionDeadline: null, nextDeadline: null,
59
+ attempts: JSON.parse(intent.attempts).map(attempt => ({ id: attempt.id, sessionId: attempt.sessionId,
60
+ state: attempt.state, writer: { pid: attempt.writerPid ?? attempt.pid, start: attempt.writerStartTime ?? attempt.pidStartTime } })),
61
+ recovery: 'drain-accepted-launch-until-journal-return-or-authoritative-handoff' }));
62
+ }
44
63
  finishRecovery(owner, key, epoch, result) {
45
64
  this.transaction(() => {
46
65
  this.current(epoch);
@@ -58,6 +77,7 @@ export class SubagentLaunchJournal {
58
77
  return { prior: true, ...prior };
59
78
  }
60
79
  this.db.prepare("INSERT INTO subagent_launch_intents VALUES (?, ?, ?, ?, 'accepted', '[]', NULL)").run(owner, key, digest, epoch);
80
+ this.noteProgress(owner, key);
61
81
  return this.read(owner, key);
62
82
  });
63
83
  }
@@ -73,6 +93,7 @@ export class SubagentLaunchJournal {
73
93
  const attempt = { ...input, token: randomBytes(32).toString("hex"), state: "prepared" };
74
94
  attempts.push(attempt);
75
95
  this.db.prepare("UPDATE subagent_launch_intents SET attempts=? WHERE owner=? AND request_key=?").run(JSON.stringify(attempts), owner, key);
96
+ this.noteProgress(owner, key);
76
97
  return attempt;
77
98
  });
78
99
  }
@@ -87,6 +108,7 @@ export class SubagentLaunchJournal {
87
108
  throw new Error("Launch writer does not match spawned process");
88
109
  Object.assign(attempt, { state: "spawned", pid, pidStartTime });
89
110
  this.db.prepare("UPDATE subagent_launch_intents SET attempts=? WHERE owner=? AND request_key=?").run(JSON.stringify(attempts), owner, key);
111
+ this.noteProgress(owner, key);
90
112
  });
91
113
  }
92
114
  finish(owner, key, epoch, result) {
@@ -1,5 +1,5 @@
1
1
  // Generated from packages/operation-coordinator/src/subagent-launch.ts. Do not edit directly.
2
- import { randomBytes } from "node:crypto";
2
+ import { createHash, randomBytes } from "node:crypto";
3
3
  import type { StoreContext } from "./sqlite.ts";
4
4
 
5
5
  export interface LaunchAttempt {
@@ -67,6 +67,26 @@ export class SubagentLaunchJournal {
67
67
  pendingIntents(): LaunchIntent[] {
68
68
  return this.db.prepare("SELECT * FROM subagent_launch_intents WHERE state='accepted'").all() as unknown as LaunchIntent[];
69
69
  }
70
+ private progressKey(owner: string, key: string) { return `launch-progress:${createHash('sha256').update(JSON.stringify([owner, key])).digest('hex')}`; }
71
+ private progress(owner: string, key: string) {
72
+ const row = this.db.prepare('SELECT value FROM coordinator_state WHERE key=?').get(this.progressKey(owner, key));
73
+ return row ? JSON.parse(String(row.value)) as { acceptedAt: number; lastProgressAt: number } : undefined;
74
+ }
75
+ private noteProgress(owner: string, key: string) {
76
+ const previous = this.progress(owner, key), now = Date.now();
77
+ this.db.prepare('INSERT OR REPLACE INTO coordinator_state (key,value) VALUES (?,?)').run(this.progressKey(owner, key),
78
+ JSON.stringify({ acceptedAt: previous?.acceptedAt ?? now, lastProgressAt: now }));
79
+ }
80
+ lifecycleReasons(owner?: string, key?: string) {
81
+ const exact = owner !== undefined && key !== undefined ? this.read(owner, key) : undefined;
82
+ const intents = owner !== undefined ? exact?.state === 'accepted' ? [exact] : [] : this.pendingIntents();
83
+ return intents.map(intent => ({ kind: 'task', id: this.progressKey(intent.owner, intent.request_key),
84
+ owner: intent.owner, management: { epoch: intent.epoch }, acceptedAt: this.progress(intent.owner, intent.request_key)?.acceptedAt ?? null,
85
+ lastProgressAt: this.progress(intent.owner, intent.request_key)?.lastProgressAt ?? null, executionDeadline: null, nextDeadline: null,
86
+ attempts: (JSON.parse(intent.attempts) as LaunchAttempt[]).map(attempt => ({ id: attempt.id, sessionId: attempt.sessionId,
87
+ state: attempt.state, writer: { pid: attempt.writerPid ?? attempt.pid, start: attempt.writerStartTime ?? attempt.pidStartTime } })),
88
+ recovery: 'drain-accepted-launch-until-journal-return-or-authoritative-handoff' }));
89
+ }
70
90
  finishRecovery(owner: string, key: string, epoch: number, result: unknown) {
71
91
  this.transaction(() => {
72
92
  this.current(epoch);
@@ -83,6 +103,7 @@ export class SubagentLaunchJournal {
83
103
  return { prior: true, ...prior };
84
104
  }
85
105
  this.db.prepare("INSERT INTO subagent_launch_intents VALUES (?, ?, ?, ?, 'accepted', '[]', NULL)").run(owner, key, digest, epoch);
106
+ this.noteProgress(owner, key);
86
107
  return this.read(owner, key);
87
108
  });
88
109
  }
@@ -96,6 +117,7 @@ export class SubagentLaunchJournal {
96
117
  const attempt: LaunchAttempt = { ...input, token: randomBytes(32).toString("hex"), state: "prepared" };
97
118
  attempts.push(attempt);
98
119
  this.db.prepare("UPDATE subagent_launch_intents SET attempts=? WHERE owner=? AND request_key=?").run(JSON.stringify(attempts), owner, key);
120
+ this.noteProgress(owner, key);
99
121
  return attempt;
100
122
  });
101
123
  }
@@ -108,6 +130,7 @@ export class SubagentLaunchJournal {
108
130
  if (attempt.writerPid && attempt.writerPid !== pid) throw new Error("Launch writer does not match spawned process");
109
131
  Object.assign(attempt, { state: "spawned", pid, pidStartTime });
110
132
  this.db.prepare("UPDATE subagent_launch_intents SET attempts=? WHERE owner=? AND request_key=?").run(JSON.stringify(attempts), owner, key);
133
+ this.noteProgress(owner, key);
111
134
  });
112
135
  }
113
136
  finish(owner: string, key: string, epoch: number, result: unknown) {
@@ -19,7 +19,7 @@
19
19
  * - a resume attempt id and launch token are persisted before the attempt is
20
20
  * spawned, so a crash is reconciled instead of relaunched.
21
21
  */
22
- /** Schema version this build writes and accepts. Any other version is refused. */
22
+ /** Schema version this build writes after creating or migrating a store. */
23
23
  export const SCHEMA_VERSION = 4;
24
24
  /** Phases that no longer accept automatic continuation. */
25
25
  export const TERMINAL_WAIT_PHASES = ["consumed", "cancelled"];
@@ -19,7 +19,7 @@
19
19
  * spawned, so a crash is reconciled instead of relaunched.
20
20
  */
21
21
 
22
- /** Schema version this build writes and accepts. Any other version is refused. */
22
+ /** Schema version this build writes after creating or migrating a store. */
23
23
  export const SCHEMA_VERSION = 4;
24
24
 
25
25
  /** Who receives an operation's result and decides what happens next. */
@@ -107,6 +107,8 @@ export interface RegisterOperationInput {
107
107
  */
108
108
  launchToken: string;
109
109
  owner: OwnerIdentity;
110
+ /** Exact registered worker attempt for this launch. Omit when no binding is known. */
111
+ assignmentAttemptId?: string;
110
112
  observer: ObserverIdentity;
111
113
  supervision?: SupervisionIdentity | null;
112
114
  /** Reference to the permission/authority snapshot. Never credential material. */
@@ -122,6 +124,8 @@ export interface OperationRecord {
122
124
  taskId: string;
123
125
  launchToken: string;
124
126
  owner: OwnerIdentity;
127
+ /** Immutable launch provenance. Absent on unbound and legacy operations. */
128
+ assignmentAttemptId?: string;
125
129
  observer: ObserverIdentity;
126
130
  supervision: SupervisionIdentity | null;
127
131
  authorityRef: string | null;
@@ -69,7 +69,7 @@ export type SandboxPermissions = {
69
69
  */
70
70
  commandTimeoutSeconds?: number | null;
71
71
  network: boolean;
72
- /** Fixed process_list adapter only; omitted legacy profiles keep it Off. */
72
+ /** Fixed process adapters (inventory and Darwin identity compatibility); omitted legacy profiles keep it Off. */
73
73
  processAccess?: "off" | "read";
74
74
  };
75
75
 
@@ -1,6 +1,20 @@
1
1
  // Generated fixed launch domain from packages/pi-better-background-tasks/src/shared-work-client.mjs. Do not edit directly.
2
+ import { existsSync } from "node:fs";
2
3
  import { connect } from "node:net";
3
4
  import { performance } from "node:perf_hooks";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+ /** A persisted session can own work even when its selected branch is empty. */
7
+ export function shouldRestoreWorkObservation(event, session) {
8
+ if (event?.piBetterObserveWork)
9
+ return true;
10
+ const reason = event?.reason;
11
+ if (reason === "new")
12
+ return false;
13
+ if (reason !== "startup" || typeof session?.getSessionFile !== "function")
14
+ return true;
15
+ const file = session.getSessionFile();
16
+ return file ? existsSync(file) : Boolean(session.getLeafId?.());
17
+ }
4
18
  /** SDK-free observation stream. Cached snapshots are the only synchronous read API. */
5
19
  export class WorkClient {
6
20
  socket;
@@ -12,6 +26,11 @@ export class WorkClient {
12
26
  scope;
13
27
  buffer = "";
14
28
  closed = false;
29
+ recoveryTimer;
30
+ recoveryActive = false;
31
+ recoveryAgain = false;
32
+ recoveryDelay = 100;
33
+ scopeGeneration = 0;
15
34
  constructor(socketPath, agentDir, requiredCapabilities = []) {
16
35
  this.socket = typeof socketPath === "string" ? connect(socketPath) : socketPath;
17
36
  this.socket.setEncoding("utf8");
@@ -32,10 +51,10 @@ export class WorkClient {
32
51
  }
33
52
  if (message.event.type === "resync_required") {
34
53
  this.degrade(message.event.reason);
35
- void this.resync().catch(error => this.degrade(String(error)));
54
+ this.scheduleRecovery();
36
55
  }
37
56
  else if (message.event.type === "runtime_snapshot")
38
- this.accept(message.event.snapshot);
57
+ this.accept(message.event.snapshot, message.event.previousSeq);
39
58
  }
40
59
  else {
41
60
  const request = this.pending.get(message.id);
@@ -54,7 +73,9 @@ export class WorkClient {
54
73
  }
55
74
  }
56
75
  });
57
- this.socket.on("error", error => this.fail(error));
76
+ this.socket.on("error", error => this.fail(["ECONNRESET", "EPIPE"].includes(error.code)
77
+ ? Object.assign(new Error(`runtime-unavailable: disconnected (${error.code}); resync required`, { cause: error }), { code: error.code })
78
+ : error));
58
79
  this.socket.on("close", () => this.fail(new Error("runtime-unavailable: disconnected; resync required")));
59
80
  this.ready = this.request("hello", { protocolVersion: 1, runtimeRoot: agentDir, requiredCapabilities: ["runtime-state-v1", "runtime-subscriptions-v1", ...requiredCapabilities] })
60
81
  .then(async (hello) => { if (typeof socketPath === "string" && hello.capabilities?.includes("runtime-client-retention-v1"))
@@ -80,31 +101,78 @@ export class WorkClient {
80
101
  this.snapshot = { ...this.snapshot, status: "degraded", reason, rows: this.snapshot?.rows ?? [] };
81
102
  this.notify();
82
103
  }
83
- accept(snapshot) {
104
+ accept(snapshot, previousSeq) {
84
105
  if (this.snapshot?.instanceId === snapshot.instanceId && snapshot.seq < this.snapshot.seq)
85
106
  return;
86
107
  if (this.snapshot?.instanceId && this.snapshot.instanceId !== snapshot.instanceId) {
87
108
  this.degrade("instance-changed: resync required");
88
109
  snapshot = { ...snapshot, resyncRequired: true, resyncReason: "instance-changed" };
89
110
  }
90
- else if (this.snapshot?.seq !== undefined && snapshot.seq > this.snapshot.seq + 1) {
111
+ else if (this.snapshot?.seq !== undefined && Number.isSafeInteger(previousSeq) && previousSeq > this.snapshot.seq) {
91
112
  this.degrade("sequence-gap: replacing with a full authoritative snapshot");
92
113
  snapshot = { ...snapshot, resyncRequired: true, resyncReason: "sequence-gap" };
93
114
  }
94
- // Every event contains a complete bounded snapshot; gaps do not require inferred deltas.
115
+ // Global seq may skip unrelated changes; only a missing subscription
116
+ // predecessor indicates loss. The received snapshot is still complete.
95
117
  this.snapshot = Object.freeze(snapshot);
96
118
  this.notify();
97
119
  }
120
+ scheduleRecovery(delay = 0) {
121
+ if (this.closed)
122
+ return;
123
+ if (this.recoveryActive) {
124
+ this.recoveryAgain = true;
125
+ return;
126
+ }
127
+ if (this.recoveryTimer)
128
+ return;
129
+ this.recoveryTimer = setTimeout(() => {
130
+ this.recoveryTimer = undefined;
131
+ void this.recover();
132
+ }, delay);
133
+ this.recoveryTimer.unref?.();
134
+ }
135
+ async recover() {
136
+ const generation = this.scopeGeneration;
137
+ this.recoveryActive = true;
138
+ let retry = false;
139
+ try {
140
+ await this.resync();
141
+ this.recoveryDelay = 100;
142
+ }
143
+ catch (error) {
144
+ if (!this.closed && generation === this.scopeGeneration) {
145
+ this.degrade(String(error));
146
+ retry = /runtime-(?:timeout|overloaded|unhealthy)/.test(String(error));
147
+ }
148
+ }
149
+ finally {
150
+ this.recoveryActive = false;
151
+ const again = this.recoveryAgain;
152
+ this.recoveryAgain = false;
153
+ if (!this.closed && (again || retry && generation === this.scopeGeneration)) {
154
+ this.scheduleRecovery(again ? 0 : this.recoveryDelay);
155
+ this.recoveryDelay = Math.min(1000, this.recoveryDelay * 2);
156
+ }
157
+ }
158
+ }
98
159
  async subscribe(scope) {
99
160
  await this.ready;
161
+ this.scopeGeneration++;
162
+ clearTimeout(this.recoveryTimer);
163
+ this.recoveryTimer = undefined;
164
+ this.recoveryAgain = false;
165
+ this.recoveryDelay = 100;
100
166
  this.scope = scope;
101
167
  const snapshot = await this.request("runtime_subscribe", { scope });
102
168
  this.accept(snapshot);
103
169
  return snapshot;
104
170
  }
105
171
  async resync() {
172
+ const generation = this.scopeGeneration;
106
173
  const snapshot = await this.request("runtime_subscribe", { scope: this.scope, sinceSeq: this.snapshot?.seq, instanceId: this.snapshot?.instanceId });
107
- this.accept(snapshot);
174
+ if (!this.closed && generation === this.scopeGeneration)
175
+ this.accept(snapshot);
108
176
  return snapshot;
109
177
  }
110
178
  async get(scope) {
@@ -122,6 +190,9 @@ export class WorkClient {
122
190
  if (this.closed)
123
191
  return;
124
192
  this.closed = true;
193
+ this.scopeGeneration++;
194
+ clearTimeout(this.recoveryTimer);
195
+ this.recoveryTimer = undefined;
125
196
  for (const request of this.pending.values()) {
126
197
  clearTimeout(request.timer);
127
198
  request.reject(error);
@@ -134,3 +205,99 @@ export class WorkClient {
134
205
  }
135
206
  close() { this.fail(new Error("runtime-unavailable: client closed")); this.listeners.clear(); this.catalogListeners.clear(); }
136
207
  }
208
+ // Shared across the standalone extension copies, but never across agent roots.
209
+ const recoveryKey = Symbol.for("pi-better-runtime.connection-recovery.v2");
210
+ const recoveries = globalThis[recoveryKey] ??= new Map();
211
+ const connectionDemands = globalThis[Symbol.for("pi-better-runtime.connection-demand.v2")] ??= new Map();
212
+ /** Establish a transport only. Never replay an application request after dispatch. */
213
+ export async function connectWorkClient(socketPath, agentDir, capabilities = [], options = {}) {
214
+ const timeoutMs = options.timeoutMs ?? 60000;
215
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
216
+ throw new Error("Invalid connection timeout");
217
+ const deadline = performance.now() + timeoutMs;
218
+ const started = performance.now();
219
+ let backoff = 100, recovered = false, lastError, recoveryError, ownedRecovery;
220
+ const remaining = () => Math.max(1, deadline - performance.now());
221
+ const key = JSON.stringify([agentDir, socketPath]);
222
+ connectionDemands.set(key, (connectionDemands.get(key) ?? 0) + 1);
223
+ try {
224
+ while (performance.now() < deadline) {
225
+ options.signal?.throwIfAborted();
226
+ const client = new WorkClient(socketPath, agentDir, capabilities);
227
+ const abort = () => client.close();
228
+ options.signal?.addEventListener("abort", abort, { once: true });
229
+ const timer = setTimeout(() => client.close(), remaining());
230
+ try {
231
+ await client.ready;
232
+ options.signal?.throwIfAborted();
233
+ return client;
234
+ }
235
+ catch (error) {
236
+ client.close();
237
+ options.signal?.throwIfAborted();
238
+ lastError = error;
239
+ if (recoveryError)
240
+ throw recoveryError;
241
+ if (!["ENOENT", "ECONNREFUSED", "ECONNRESET", "EPIPE"].includes(error?.code)
242
+ && !/runtime-unavailable: (?:disconnected|server closed)/.test(String(error)))
243
+ throw error;
244
+ }
245
+ finally {
246
+ clearTimeout(timer);
247
+ options.signal?.removeEventListener("abort", abort);
248
+ }
249
+ // Most replacement gaps need only a reconnect. Startup remains owner-safe.
250
+ if (!recovered && options.recover && performance.now() - started >= 250 && performance.now() < deadline) {
251
+ recovered = true;
252
+ let recovery = recoveries.get(key);
253
+ if (!recovery) {
254
+ const controller = new AbortController();
255
+ const budget = Math.ceil(remaining());
256
+ const timer = setTimeout(() => {
257
+ controller.abort(new Error("runtime-unavailable: reconnect deadline exceeded during recovery"));
258
+ }, budget);
259
+ const promise = waitForRecovery(Promise.resolve().then(() => options.recover({ timeoutMs: budget, signal: controller.signal })), controller.signal)
260
+ .finally(() => clearTimeout(timer));
261
+ recovery = { promise, controller, key };
262
+ recoveries.set(key, recovery);
263
+ void recovery.promise.finally(() => { if (recoveries.get(key) === recovery)
264
+ recoveries.delete(key); }).catch(() => { });
265
+ }
266
+ // A caller can cancel its wait without cancelling another caller's recovery.
267
+ // Keep trying the transport while the owner-safe installer waits.
268
+ // A replacement can accept compatible clients before the pinned
269
+ // installer finishes; waiting for it would stall all subscribers.
270
+ ownedRecovery = recovery;
271
+ void recovery.promise.catch(error => { recoveryError = error; });
272
+ }
273
+ if (performance.now() >= deadline)
274
+ break;
275
+ await delay(Math.min(backoff, remaining()), undefined, { signal: options.signal });
276
+ backoff = Math.min(1000, backoff * 2);
277
+ }
278
+ throw new Error("runtime-unavailable: reconnect deadline exceeded; task state is unknown, retry after recovery", { cause: lastError });
279
+ }
280
+ finally {
281
+ const remainingDemand = connectionDemands.get(key) - 1;
282
+ if (remainingDemand)
283
+ connectionDemands.set(key, remainingDemand);
284
+ else {
285
+ connectionDemands.delete(key);
286
+ const recovery = recoveries.get(key) ?? ownedRecovery;
287
+ if (recovery) {
288
+ recoveries.delete(key);
289
+ recovery.controller.abort();
290
+ }
291
+ }
292
+ }
293
+ }
294
+ function waitForRecovery(recovery, signal) {
295
+ return new Promise((resolve, reject) => {
296
+ const finish = (callback, value) => { signal.removeEventListener("abort", abort); callback(value); };
297
+ const abort = () => finish(reject, signal.reason);
298
+ signal.addEventListener("abort", abort, { once: true });
299
+ recovery.then(value => finish(resolve, value), error => finish(reject, error));
300
+ if (signal.aborted)
301
+ abort();
302
+ });
303
+ }
@@ -46,12 +46,14 @@ export function observeBackgroundTaskStall(meta, now = Date.now()) {
46
46
  thresholds: backgroundTaskStallThresholds(),
47
47
  });
48
48
  }
49
+ export function formatProgressDuration(ms) {
50
+ const seconds = Math.max(0, Math.round(ms / 1000));
51
+ return seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m${(seconds % 60).toString().padStart(2, "0")}s`;
52
+ }
49
53
  /** Silence is an observation, not proof that the process is hung. */
50
54
  export function formatBackgroundTaskStall(observation) {
51
55
  if (observation.state !== "quiet" && observation.state !== "stalled")
52
56
  return undefined;
53
- const seconds = Math.max(0, Math.round((observation.ageMs ?? 0) / 1000));
54
- const duration = seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m${(seconds % 60).toString().padStart(2, "0")}s`;
55
57
  const label = observation.state === "stalled" ? "suspected stall" : "quiet";
56
- return `${label}; no observed progress for ${duration}`;
58
+ return `${label}; no observed progress for ${formatProgressDuration(observation.ageMs ?? 0)}`;
57
59
  }
@@ -47,11 +47,14 @@ export function observeBackgroundTaskStall(meta: BackgroundTaskMeta, now = Date.
47
47
  });
48
48
  }
49
49
 
50
+ export function formatProgressDuration(ms: number): string {
51
+ const seconds = Math.max(0, Math.round(ms / 1000));
52
+ return seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m${(seconds % 60).toString().padStart(2, "0")}s`;
53
+ }
54
+
50
55
  /** Silence is an observation, not proof that the process is hung. */
51
- export function formatBackgroundTaskStall(observation: StallObservation): string | undefined {
56
+ export function formatBackgroundTaskStall(observation: Pick<StallObservation, "state" | "ageMs">): string | undefined {
52
57
  if (observation.state !== "quiet" && observation.state !== "stalled") return undefined;
53
- const seconds = Math.max(0, Math.round((observation.ageMs ?? 0) / 1000));
54
- const duration = seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m${(seconds % 60).toString().padStart(2, "0")}s`;
55
58
  const label = observation.state === "stalled" ? "suspected stall" : "quiet";
56
- return `${label}; no observed progress for ${duration}`;
59
+ return `${label}; no observed progress for ${formatProgressDuration(observation.ageMs ?? 0)}`;
57
60
  }
@@ -0,0 +1,42 @@
1
+ // Generated fixed launch domain from packages/pi-better-background-tasks/src/supervised-progress.ts. Do not edit directly.
2
+ import { readFileSync, statSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { backgroundTaskStallThresholds, formatBackgroundTaskStall } from "./stall.domain.mjs";
5
+ import { observeStall } from "./shared-stall-detector.domain.mjs";
6
+ export function supervisedProgress(source, now = Date.now()) {
7
+ if (source?.status !== "running" || !source.claim)
8
+ return;
9
+ let observedAt;
10
+ try {
11
+ observedAt = JSON.parse(readFileSync(join(dirname(source.logs.stdout), "progress.json"), "utf8")).observedAt;
12
+ if (!Number.isFinite(observedAt) || observedAt < source.claim.claimedAt)
13
+ return;
14
+ }
15
+ catch (error) {
16
+ // Older process runners still have separate append-only streams. Older watches
17
+ // appended every poll, so their logs cannot establish a meaningful progress time.
18
+ if (error.code !== "ENOENT" || source.kind !== "process")
19
+ return;
20
+ observedAt = source.claim.claimedAt;
21
+ for (const path of [source.logs.stdout, source.logs.stderr]) {
22
+ if (!path)
23
+ continue;
24
+ try {
25
+ const stat = statSync(path, { throwIfNoEntry: false });
26
+ if (stat?.size)
27
+ observedAt = Math.max(observedAt, Math.trunc(stat.mtimeMs));
28
+ }
29
+ catch {
30
+ return;
31
+ }
32
+ }
33
+ }
34
+ const { state, thresholds } = observeStall({ now, lastProgressAt: observedAt, thresholds: backgroundTaskStallThresholds() });
35
+ const quietAt = observedAt + thresholds.quietMs;
36
+ const stalledAt = observedAt + thresholds.stallMs;
37
+ const alertAt = stalledAt + 60_000;
38
+ return { observedAt, state, alertDue: now >= alertAt, nextDeadline: [quietAt, stalledAt, alertAt].find(time => time > now) };
39
+ }
40
+ export function describeSupervisedProgress(progress, now = Date.now()) {
41
+ return formatBackgroundTaskStall({ ...progress, ageMs: now - progress.observedAt });
42
+ }