pi-better-server 0.5.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 (278) hide show
  1. package/package.json +4 -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 +37 -5
  6. package/scripts/event-publication/writer.mjs +3 -8
  7. package/scripts/measure-full-runtime/probe.mjs +4 -2
  8. package/scripts/measure-full-runtime/recovery-trace-loader.mjs +51 -0
  9. package/scripts/measure-full-runtime/recovery-trace.mjs +16 -0
  10. package/scripts/measure-shared-reads.mjs +2 -1
  11. package/scripts/private-runtime/package-lock.json +18 -0
  12. package/scripts/private-runtime/package.json +4 -1
  13. package/scripts/source-provenance.mjs +2 -2
  14. package/scripts/test-on-pi.sh +2 -9
  15. package/src/handshake.ts +1 -1
  16. package/src/hosted-session.ts +32 -4
  17. package/src/maintenance.ts +35 -7
  18. package/src/registry.ts +28 -4
  19. package/src/runtime/attempt-invalidation.ts +54 -0
  20. package/src/runtime/background-history.ts +151 -45
  21. package/src/runtime/background-policy.ts +9 -4
  22. package/src/runtime/background-tools.ts +131 -23
  23. package/src/runtime/background.ts +351 -68
  24. package/src/runtime/cancellation.ts +28 -7
  25. package/src/runtime/catalog-sources.ts +199 -0
  26. package/src/runtime/catalog.ts +53 -21
  27. package/src/runtime/client.ts +22 -2
  28. package/src/runtime/domain/assignment-inbox.mjs +119 -0
  29. package/src/runtime/domain/assignment-observation.d.mts +1 -1
  30. package/src/runtime/domain/assignment-observation.mjs +43 -35
  31. package/src/runtime/domain/background/process-identity.mjs +20 -2
  32. package/src/runtime/domain/background/process.mjs +3 -3
  33. package/src/runtime/domain/background/registry.mjs +61 -3
  34. package/src/runtime/domain/background/types.mjs +1 -0
  35. package/src/runtime/domain/background-service/adapter-contract.domain.mjs +1 -1
  36. package/src/runtime/domain/background-service/adapter-contract.ts +1 -1
  37. package/src/runtime/domain/background-service/goal-provider.domain.mjs +35 -16
  38. package/src/runtime/domain/background-service/goal-provider.ts +31 -16
  39. package/src/runtime/domain/background-service/index.domain.mjs +6 -9
  40. package/src/runtime/domain/background-service/index.ts +6 -9
  41. package/src/runtime/domain/background-service/managed-authority.domain.mjs +6 -3
  42. package/src/runtime/domain/background-service/managed-authority.ts +5 -3
  43. package/src/runtime/domain/background-service/managed-client.domain.mjs +21 -7
  44. package/src/runtime/domain/background-service/managed-client.ts +20 -7
  45. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +75 -17
  46. package/src/runtime/domain/background-service/managed-frontend.ts +62 -17
  47. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +16 -5
  48. package/src/runtime/domain/background-service/navigator-provider.ts +15 -5
  49. package/src/runtime/domain/background-service/observed-wait-client.domain.mjs +6 -0
  50. package/src/runtime/domain/background-service/observed-wait-client.ts +10 -0
  51. package/src/runtime/domain/background-service/observed-waits.domain.mjs +170 -27
  52. package/src/runtime/domain/background-service/observed-waits.ts +154 -30
  53. package/src/runtime/domain/background-service/process-identity.domain.mjs +20 -2
  54. package/src/runtime/domain/background-service/process-identity.ts +18 -2
  55. package/src/runtime/domain/background-service/process.domain.mjs +3 -3
  56. package/src/runtime/domain/background-service/process.ts +3 -3
  57. package/src/runtime/domain/background-service/registry.domain.mjs +61 -3
  58. package/src/runtime/domain/background-service/registry.ts +53 -5
  59. package/src/runtime/domain/background-service/runtime.domain.mjs +32 -16
  60. package/src/runtime/domain/background-service/runtime.ts +19 -9
  61. package/src/runtime/domain/background-service/sandbox.domain.mjs +14 -15
  62. package/src/runtime/domain/background-service/sandbox.ts +14 -11
  63. package/src/runtime/domain/background-service/shared-callback-batcher.domain.mjs +8 -1
  64. package/src/runtime/domain/background-service/shared-callback-batcher.ts +11 -2
  65. package/src/runtime/domain/background-service/shared-navigator-panels.domain.mjs +24 -2
  66. package/src/runtime/domain/background-service/shared-navigator-panels.ts +26 -4
  67. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +218 -13
  68. package/src/runtime/domain/background-service/shared-navigator.ts +197 -14
  69. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  70. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +53 -41
  71. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  72. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  73. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
  74. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  75. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
  76. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.ts +14 -3
  77. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
  78. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +5 -3
  79. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +44 -4
  80. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +50 -2
  81. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
  82. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +12 -0
  83. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.domain.mjs +2 -0
  84. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.ts +2 -0
  85. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +42 -21
  86. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +40 -24
  87. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +21 -3
  88. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +34 -8
  89. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
  90. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  91. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.domain.mjs +1 -1
  92. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.ts +5 -1
  93. package/src/runtime/domain/background-service/shared-sandbox-core.ts +1 -1
  94. package/src/runtime/domain/background-service/shared-work-client.mjs +174 -7
  95. package/src/runtime/domain/background-service/supervisor/generated/process-identity.mjs +20 -2
  96. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +3 -3
  97. package/src/runtime/domain/background-service/task-diagnostics.domain.mjs +1 -1
  98. package/src/runtime/domain/background-service/task-diagnostics.ts +1 -1
  99. package/src/runtime/domain/background-service/tools.domain.mjs +31 -24
  100. package/src/runtime/domain/background-service/tools.ts +41 -38
  101. package/src/runtime/domain/background-service/types.domain.mjs +1 -0
  102. package/src/runtime/domain/background-service/types.ts +3 -1
  103. package/src/runtime/domain/background-service/work-observation.domain.mjs +46 -20
  104. package/src/runtime/domain/background-service/work-observation.ts +46 -19
  105. package/src/runtime/domain/catalog/catalog-store.d.mts +9 -1
  106. package/src/runtime/domain/catalog/catalog-store.mjs +20 -22
  107. package/src/runtime/domain/coordinator/src/assignment-changes.mjs +75 -0
  108. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +2 -0
  109. package/src/runtime/domain/coordinator/src/background-requests.mjs +11 -2
  110. package/src/runtime/domain/coordinator/src/discovery.mjs +4 -2
  111. package/src/runtime/domain/coordinator/src/operations.mjs +44 -4
  112. package/src/runtime/domain/coordinator/src/result-supervision.mjs +12 -0
  113. package/src/runtime/domain/coordinator/src/rows.mjs +2 -0
  114. package/src/runtime/domain/coordinator/src/schema.mjs +42 -21
  115. package/src/runtime/domain/coordinator/src/store.mjs +21 -3
  116. package/src/runtime/domain/coordinator/src/subagent-launch.mjs +23 -1
  117. package/src/runtime/domain/coordinator/src/types.mjs +1 -1
  118. package/src/runtime/domain/health-observation.d.mts +3 -1
  119. package/src/runtime/domain/health-observation.mjs +189 -190
  120. package/src/runtime/domain/log-cursor.d.mts +2 -0
  121. package/src/runtime/domain/log-cursor.mjs +85 -16
  122. package/src/runtime/domain/parse.d.mts +4 -1
  123. package/src/runtime/domain/parse.mjs +50 -5
  124. package/src/runtime/domain/sandbox-policy/README.md +61 -63
  125. package/src/runtime/domain/sandbox-policy/commands.domain.mjs +11 -8
  126. package/src/runtime/domain/sandbox-policy/commands.ts +12 -7
  127. package/src/runtime/domain/sandbox-policy/index.domain.mjs +53 -9
  128. package/src/runtime/domain/sandbox-policy/index.ts +52 -9
  129. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  130. package/src/runtime/domain/sandbox-policy/permission-settings.domain.mjs +5 -2
  131. package/src/runtime/domain/sandbox-policy/permission-settings.ts +9 -2
  132. package/src/runtime/domain/sandbox-policy/permissions-page.domain.mjs +56 -137
  133. package/src/runtime/domain/sandbox-policy/permissions-page.ts +52 -130
  134. package/src/runtime/domain/sandbox-policy/permissions.domain.mjs +1 -6
  135. package/src/runtime/domain/sandbox-policy/permissions.ts +1 -6
  136. package/src/runtime/domain/sandbox-policy/shared-sandbox-core.ts +1 -1
  137. package/src/runtime/domain/sandbox-policy/shared-task-exec.domain.mjs +14 -1
  138. package/src/runtime/domain/sandbox-policy/shared-task-exec.ts +12 -1
  139. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.domain.mjs +140 -0
  140. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.ts +126 -0
  141. package/src/runtime/domain/sandbox-policy/shared-task-process-list.domain.mjs +3 -2
  142. package/src/runtime/domain/sandbox-policy/shared-task-process-list.ts +8 -2
  143. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.domain.mjs +4 -3
  144. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.ts +5 -3
  145. package/src/runtime/domain/sandbox-policy/shared-task-tools.domain.mjs +8 -5
  146. package/src/runtime/domain/sandbox-policy/shared-task-tools.ts +8 -5
  147. package/src/runtime/domain/subagents/README.md +1 -1
  148. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +12 -6
  149. package/src/runtime/domain/subagents/assignment-outcomes.ts +11 -5
  150. package/src/runtime/domain/subagents/assignment-report.domain.mjs +87 -24
  151. package/src/runtime/domain/subagents/assignment-report.ts +83 -19
  152. package/src/runtime/domain/subagents/catalog-host-admission.domain.mjs +21 -3
  153. package/src/runtime/domain/subagents/catalog-host-admission.ts +19 -3
  154. package/src/runtime/domain/subagents/catalog-preferences.ts +1 -1
  155. package/src/runtime/domain/subagents/catalog-resolver.domain.mjs +35 -1
  156. package/src/runtime/domain/subagents/catalog-resolver.ts +35 -1
  157. package/src/runtime/domain/subagents/catalog-store.domain.mjs +20 -22
  158. package/src/runtime/domain/subagents/catalog-store.ts +27 -20
  159. package/src/runtime/domain/subagents/child-apply-patch.domain.mjs +13 -0
  160. package/src/runtime/domain/subagents/child-apply-patch.ts +13 -0
  161. package/src/runtime/domain/subagents/child-dependencies.mjs +27 -15
  162. package/src/runtime/domain/subagents/child-operations.domain.mjs +80 -2
  163. package/src/runtime/domain/subagents/child-operations.ts +80 -1
  164. package/src/runtime/domain/subagents/child-preflight.mjs +9 -2
  165. package/src/runtime/domain/subagents/child-process-list.domain.mjs +7 -0
  166. package/src/runtime/domain/subagents/child-process-list.ts +8 -0
  167. package/src/runtime/domain/subagents/config.domain.mjs +49 -2
  168. package/src/runtime/domain/subagents/config.ts +46 -2
  169. package/src/runtime/domain/subagents/continuation-authority.domain.mjs +5 -1
  170. package/src/runtime/domain/subagents/continuation-authority.ts +3 -1
  171. package/src/runtime/domain/subagents/continuation-runtime.domain.mjs +89 -0
  172. package/src/runtime/domain/subagents/continuation-runtime.ts +88 -0
  173. package/src/runtime/domain/subagents/extensions.mjs +11 -13
  174. package/src/runtime/domain/subagents/finalization.domain.mjs +12 -0
  175. package/src/runtime/domain/subagents/finalization.ts +15 -0
  176. package/src/runtime/domain/subagents/goal-provider.domain.mjs +44 -2
  177. package/src/runtime/domain/subagents/goal-provider.ts +44 -2
  178. package/src/runtime/domain/subagents/health-observation.domain.mjs +189 -190
  179. package/src/runtime/domain/subagents/health-observation.ts +43 -48
  180. package/src/runtime/domain/subagents/index.domain.mjs +296 -123
  181. package/src/runtime/domain/subagents/index.ts +257 -98
  182. package/src/runtime/domain/subagents/launch-context.domain.mjs +24 -0
  183. package/src/runtime/domain/subagents/launch-context.ts +23 -0
  184. package/src/runtime/domain/subagents/launch-digest.mjs +6 -0
  185. package/src/runtime/domain/subagents/log-cursor.domain.mjs +85 -16
  186. package/src/runtime/domain/subagents/log-cursor.ts +91 -15
  187. package/src/runtime/domain/subagents/managed-launch-bootstrap.mjs +2 -2
  188. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +6 -3
  189. package/src/runtime/domain/subagents/managed-launch-client.ts +6 -3
  190. package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +222 -14
  191. package/src/runtime/domain/subagents/managed-launch-host.ts +168 -15
  192. package/src/runtime/domain/subagents/managed-launch-journal.mjs +1 -5
  193. package/src/runtime/domain/subagents/managed-launch-port.ts +4 -0
  194. package/src/runtime/domain/subagents/operation-bridge-types.domain.mjs +27 -2
  195. package/src/runtime/domain/subagents/operation-bridge-types.ts +27 -2
  196. package/src/runtime/domain/subagents/owned-exit.domain.mjs +12 -0
  197. package/src/runtime/domain/subagents/owned-exit.ts +12 -0
  198. package/src/runtime/domain/subagents/package.json +1 -1
  199. package/src/runtime/domain/subagents/parse.domain.mjs +50 -5
  200. package/src/runtime/domain/subagents/parse.ts +48 -6
  201. package/src/runtime/domain/subagents/permission-policy.domain.mjs +32 -8
  202. package/src/runtime/domain/subagents/permission-policy.ts +41 -8
  203. package/src/runtime/domain/subagents/process-identity.mjs +33 -0
  204. package/src/runtime/domain/subagents/registry.domain.mjs +47 -33
  205. package/src/runtime/domain/subagents/registry.ts +54 -33
  206. package/src/runtime/domain/subagents/shared-callback-batcher.domain.mjs +8 -1
  207. package/src/runtime/domain/subagents/shared-callback-batcher.ts +11 -2
  208. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +6 -23
  209. package/src/runtime/domain/subagents/shared-catalog.ts +6 -14
  210. package/src/runtime/domain/subagents/shared-navigator-panels.domain.mjs +24 -2
  211. package/src/runtime/domain/subagents/shared-navigator-panels.ts +26 -4
  212. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +218 -13
  213. package/src/runtime/domain/subagents/shared-navigator.ts +197 -14
  214. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  215. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +53 -41
  216. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  217. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  218. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
  219. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  220. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
  221. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.ts +14 -3
  222. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
  223. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +5 -3
  224. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +44 -4
  225. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +50 -2
  226. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
  227. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +12 -0
  228. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.domain.mjs +2 -0
  229. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.ts +2 -0
  230. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +42 -21
  231. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +40 -24
  232. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +21 -3
  233. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +34 -8
  234. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
  235. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  236. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.domain.mjs +1 -1
  237. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.ts +5 -1
  238. package/src/runtime/domain/subagents/shared-sandbox-core.ts +1 -1
  239. package/src/runtime/domain/subagents/shared-task-exec.domain.mjs +14 -1
  240. package/src/runtime/domain/subagents/shared-task-exec.ts +12 -1
  241. package/src/runtime/domain/subagents/shared-task-process-identity.domain.mjs +140 -0
  242. package/src/runtime/domain/subagents/shared-task-process-identity.ts +126 -0
  243. package/src/runtime/domain/subagents/shared-task-process-list.domain.mjs +3 -2
  244. package/src/runtime/domain/subagents/shared-task-process-list.ts +8 -2
  245. package/src/runtime/domain/subagents/shared-task-sandbox.domain.mjs +4 -3
  246. package/src/runtime/domain/subagents/shared-task-sandbox.ts +5 -3
  247. package/src/runtime/domain/subagents/shared-task-tools.domain.mjs +8 -5
  248. package/src/runtime/domain/subagents/shared-task-tools.ts +8 -5
  249. package/src/runtime/domain/subagents/shared-work-client.mjs +174 -7
  250. package/src/runtime/domain/subagents/subagent-tools.domain.mjs +22 -38
  251. package/src/runtime/domain/subagents/subagent-tools.ts +28 -34
  252. package/src/runtime/domain/subagents/task-policy.domain.mjs +1 -1
  253. package/src/runtime/domain/subagents/task-policy.ts +3 -1
  254. package/src/runtime/domain/subagents/timing.domain.mjs +10 -1
  255. package/src/runtime/domain/subagents/timing.ts +10 -1
  256. package/src/runtime/domain/subagents/work-observation.domain.mjs +77 -16
  257. package/src/runtime/domain/subagents/work-observation.ts +71 -16
  258. package/src/runtime/domain/subagents/worker-operations-host.domain.mjs +9 -4
  259. package/src/runtime/domain/subagents/worker-operations-host.ts +12 -4
  260. package/src/runtime/domain/subagents/worker-waits.domain.mjs +89 -35
  261. package/src/runtime/domain/subagents/worker-waits.ts +93 -34
  262. package/src/runtime/health-config.ts +27 -11
  263. package/src/runtime/log-checkpoints.ts +117 -0
  264. package/src/runtime/mutation-store.ts +5 -4
  265. package/src/runtime/queries.ts +25 -2
  266. package/src/runtime/query-executor.ts +149 -28
  267. package/src/runtime/query-worker.mjs +106 -21
  268. package/src/runtime/read-model.ts +846 -120
  269. package/src/runtime/read-watchdog-probe.ts +4 -0
  270. package/src/runtime/result-supervision.ts +188 -16
  271. package/src/runtime/source-watch.ts +175 -0
  272. package/src/runtime/subagent-launch.ts +11 -4
  273. package/src/runtime/work-budget.ts +130 -0
  274. package/src/runtime/work-client.d.mts +8 -0
  275. package/src/runtime/work-client.mjs +150 -7
  276. package/src/server.ts +104 -23
  277. package/src/session-activity.ts +26 -4
  278. package/src/version.ts +1 -1
@@ -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
+ }
@@ -1,6 +1,7 @@
1
1
  // Generated fixed launch domain from packages/pi-better-background-tasks/src/supervisor/generated/process-identity.mjs. Do not edit directly.
2
2
  // Generated by src/supervisor/emit-runner.mjs from the TypeScript source.
3
3
  // Do not edit: change the source and re-run the emitter (a drift test enforces this).
4
+ import { readFileSync } from "node:fs";
4
5
  import { execFileSync } from "node:child_process";
5
6
  /**
6
7
  * Process start-token reads.
@@ -23,11 +24,12 @@ const TOKEN_MEMO_TTL_MS = 1_000;
23
24
  /** Bound on memo entries; the panel is small, but a long session is not. */
24
25
  const TOKEN_MEMO_MAX_ENTRIES = 512;
25
26
  const tokenMemo = new Map();
26
- function readTokenUncached(pid) {
27
+ function readTokenUncached(pid, admission = false) {
27
28
  if (!Number.isInteger(pid) || pid <= 0 || process.platform === "win32")
28
29
  return undefined;
29
30
  try {
30
- const output = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
31
+ const output = execFileSync(admission ? "/bin/ps" : "ps", ["-o", "lstart=", "-p", String(pid)], {
32
+ env: admission ? { LC_ALL: "C", TZ: "UTC0", PATH: "/usr/bin:/bin" } : process.env,
31
33
  encoding: "utf8",
32
34
  stdio: ["ignore", "pipe", "ignore"],
33
35
  timeout: 2_000,
@@ -38,6 +40,22 @@ function readTokenUncached(pid) {
38
40
  return undefined;
39
41
  }
40
42
  }
43
+ // Admission crosses process environments; stored task tokens retain their original format.
44
+ export function readAdmissionStartToken(pid) {
45
+ if (process.platform !== "linux")
46
+ return readTokenUncached(pid, true);
47
+ if (!Number.isInteger(pid) || pid <= 0)
48
+ return undefined;
49
+ try {
50
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
51
+ // Fields after the parenthesized command start at field 3. Start time is field 22.
52
+ const start = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
53
+ return start && /^\d+$/.test(start) ? start : undefined;
54
+ }
55
+ catch {
56
+ return undefined;
57
+ }
58
+ }
41
59
  function remember(pid, token, now) {
42
60
  if (tokenMemo.size >= TOKEN_MEMO_MAX_ENTRIES) {
43
61
  // Drop expired entries first; only evict live ones if that was not enough.
@@ -62,8 +62,8 @@ export function validateCommandSpec(spec) {
62
62
  /** Convert a Windows path to the `/c/...` form MSYS bash resolves in redirections. Exposed for tests and reuse. */
63
63
  export function toMsysPath(path) {
64
64
  const forward = path.replace(/\\/g, "/");
65
- const drive = /^([A-Za-z]):(\/.+)$/.exec(forward);
66
- return drive ? `/${drive[1].toLowerCase()}${drive[2]}` : forward;
65
+ const [, drive, rest] = /^([A-Za-z]):(\/.+)$/.exec(forward) ?? [];
66
+ return drive && rest ? `/${drive.toLowerCase()}${rest}` : forward;
67
67
  }
68
68
  /** Single-quote a value for safe literal use in a bash script line. Exposed for tests and reuse. */
69
69
  export function bashSingleQuote(value) {
@@ -147,7 +147,7 @@ export function parseStepGateFailure(logText, id) {
147
147
  if (!line.startsWith(marker) || !line.endsWith(" ---"))
148
148
  continue;
149
149
  const match = /^--- step gate \[[^\]]+\]: first failing step exit=(-?\d+); shell exit=(-?\d+): (.*) ---$/.exec(line);
150
- if (!match)
150
+ if (!match || match[3] === undefined)
151
151
  continue;
152
152
  const stepExitCode = Number(match[1]);
153
153
  const shellExitCode = Number(match[2]);
@@ -33,7 +33,7 @@ export function inspectTaskProcess(meta, access, probe = sampleProcess) {
33
33
  return unavailable("Process activity adapter is unavailable under Main confinement; no unconfined process probe was run. Process access Read does not bypass kernel rules.");
34
34
  if (access !== "read")
35
35
  return { availability: "blocked", reason: access === "off"
36
- ? "Process access is Off in Main or Background tasks. Enable Read in /sandbox; this does not describe task confinement."
36
+ ? "An active Main or Background tasks profile denies process reads. Check Process access in /sandbox; this does not describe task confinement."
37
37
  : "Current process-access policy is unavailable; no process probe was run.", limit: LIMIT };
38
38
  if (meta.ssh)
39
39
  return unavailable("Remote activity is unavailable; no remote diagnostic command was run.");
@@ -52,7 +52,7 @@ export function inspectTaskProcess(
52
52
  ({ availability: "unavailable", reason, ...(identity ? { identity } : {}), limit: LIMIT });
53
53
  if (access === "confined") return unavailable("Process activity adapter is unavailable under Main confinement; no unconfined process probe was run. Process access Read does not bypass kernel rules.");
54
54
  if (access !== "read") return { availability: "blocked", reason: access === "off"
55
- ? "Process access is Off in Main or Background tasks. Enable Read in /sandbox; this does not describe task confinement."
55
+ ? "An active Main or Background tasks profile denies process reads. Check Process access in /sandbox; this does not describe task confinement."
56
56
  : "Current process-access policy is unavailable; no process probe was run.", limit: LIMIT };
57
57
  if (meta.ssh) return unavailable("Remote activity is unavailable; no remote diagnostic command was run.");
58
58
  if (meta.kind !== "process") return unavailable("Watch poll PID is not retained; last completed check is progress evidence only.");
@@ -1,22 +1,18 @@
1
1
  // Generated fixed launch domain from packages/pi-better-background-tasks/src/tools.ts. Do not edit directly.
2
2
  import { Type } from "typebox";
3
3
  import { advertiseBackgroundAdapter } from "./adapter-contract.domain.mjs";
4
- import { formatBatchLaunch, spawnTaskBatch } from "./batch.domain.mjs";
5
4
  import { refreshBackgroundTasksNavigator } from "./navigator-provider.domain.mjs";
6
5
  import { classifyOwnership, formatLaunch, formatList, formatLog, formatMissingTask, formatMutationRefusal, formatStatus, formatDurableStatusMetadata, formatStopResult, } from "./output.domain.mjs";
7
6
  import { cursorKind, readOutputControls } from "./shared-log-utils.domain.mjs";
8
7
  import { cancelCallbackBatch, getCallbackBatcher, setCallbackBatchContext } from "./shared-callback-batcher.domain.mjs";
9
8
  import { registerDeliveryObserver } from "./delivery-observer.domain.mjs";
10
- import { formatWaitView, getObservedWaitHost, observedWaitServiceUnavailableReason, } from "./observed-waits.domain.mjs";
11
- import { backgroundObservation } from "./work-observation.domain.mjs";
9
+ import { getObservedWaitHost } from "./observed-wait-client.domain.mjs";
10
+ import { backgroundListNeedsHistory, backgroundObservation } from "./work-observation.domain.mjs";
12
11
  import { inspectMeta, listMetasForOrigin, readMeta, writeMeta } from "./registry.domain.mjs";
13
- import { awaitFirstWatchCheck, FIRST_WATCH_CHECK_WAIT_MS, resumeRunningTask, spawnTask, startWatchTask, stopTask } from "./runtime.domain.mjs";
14
- import { runTaskMaintenance } from "./maintenance.domain.mjs";
15
12
  import { backgroundProcessDiagnosticsAccess, ForegroundSandboxBlockedError } from "./sandbox.domain.mjs";
16
13
  import { inspectTaskProcess } from "./task-diagnostics.domain.mjs";
17
- import { isTerminalStatus } from "./types.domain.mjs";
14
+ import { FIRST_WATCH_CHECK_WAIT_MS, isTerminalStatus } from "./types.domain.mjs";
18
15
  export { formatLaunch } from "./output.domain.mjs";
19
- const defaultRuntime = { awaitFirstWatchCheck, resumeRunningTask, spawnTask, startWatchTask, stopTask };
20
16
  const JsonPathSchema = Type.String({
21
17
  pattern: "^\\$",
22
18
  description: "Root-prefixed JSON path, e.g. $.status, $.terminalFailure, or $.steps[0].status. Bare keys and wildcards are unsupported.",
@@ -136,7 +132,7 @@ const IdParams = Type.Object({
136
132
  ...CursorFields,
137
133
  });
138
134
  const HistoryField = {
139
- diagnostics: Type.Optional(Type.Boolean({ description: "For status: sample registered task process identity, CPU time, state and wait evidence. Requires current Process access Read in both Main and Background tasks. No arguments, environment or remote probes; a snapshot cannot prove useful work or a hang." })),
135
+ diagnostics: Type.Optional(Type.Boolean({ description: "For status: sample registered task process identity, CPU time, state and wait evidence. Requires Process access Read in each enabled sandbox profile (Main and Background tasks); unavailable under Main confinement. No arguments, environment or remote probes; a snapshot cannot prove useful work or a hang." })),
140
136
  history: Type.Optional(Type.Boolean({ description: "If true, return an incident page that also lists failure history: expected failures and recovered or superseded incidents. Default output lists only failures that need action and counts the rest." })),
141
137
  };
142
138
  const StatusParams = Type.Object({
@@ -247,8 +243,7 @@ const BACKGROUND_ORCHESTRATION_GUIDELINES = [
247
243
  "When a structured plan is active, keep it as the coordinator ledger: launch relevant background work early, continue unblocked foreground work without polling, and update the plan after inspecting each terminal result or failure.",
248
244
  "Do not treat launch as completion of the parent milestone; relevant background work must be terminal, inspected, and integrated before verification or completion.",
249
245
  ];
250
- export function registerTools(pi, runtime = defaultRuntime, refreshNavigator = refreshBackgroundTasksNavigator, options = {}) {
251
- const { resumeRunningTask, spawnTask } = runtime;
246
+ export function registerTools(pi, runtime, refreshNavigator = refreshBackgroundTasksNavigator, options = {}) {
252
247
  let activeSession;
253
248
  const getActiveSession = () => activeSession;
254
249
  const schemas = new Map();
@@ -263,6 +258,8 @@ export function registerTools(pi, runtime = defaultRuntime, refreshNavigator = r
263
258
  setCallbackBatchContext(pi, ctx);
264
259
  activeSession = getCallbackOrigin(ctx);
265
260
  if (options.resumeLocal !== false) {
261
+ const { resumeRunningTask } = runtime ?? await import("./runtime.domain.mjs");
262
+ const { runTaskMaintenance } = await import("./maintenance.domain.mjs");
266
263
  for (const meta of listMetasForOrigin(activeSession)) {
267
264
  if (meta.status === "running" || (meta.callback !== false && !meta.callbackSentAt && !meta.callbackSuppressedAt)) {
268
265
  resumeRunningTask(pi, meta, getActiveSession);
@@ -306,6 +303,7 @@ export function registerTools(pi, runtime = defaultRuntime, refreshNavigator = r
306
303
  refreshNavigator(ctx);
307
304
  return text(durable, launchReceipt(receipt));
308
305
  }
306
+ const { spawnTask } = runtime ?? await import("./runtime.domain.mjs");
309
307
  const launched = reportLaunch(() => spawnTask(pi, params, ctx.cwd, origin, getActiveSession));
310
308
  refreshNavigator(ctx);
311
309
  return text(launched);
@@ -319,6 +317,7 @@ export function registerTools(pi, runtime = defaultRuntime, refreshNavigator = r
319
317
  parameters: BatchParams,
320
318
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
321
319
  activeSession = getCallbackOrigin(ctx);
320
+ const { formatBatchLaunch, spawnTaskBatch } = await import("./batch.domain.mjs");
322
321
  const launched = spawnTaskBatch(pi, params, ctx.cwd, activeSession, getActiveSession, {}, runtime);
323
322
  refreshNavigator(ctx);
324
323
  return text(formatBatchLaunch(launched), launched);
@@ -398,7 +397,7 @@ export function registerTools(pi, runtime = defaultRuntime, refreshNavigator = r
398
397
  refreshNavigator(ctx);
399
398
  return text(durable);
400
399
  }
401
- const result = await formatStop(pi, params.id, ctx, getActiveSession, statusOptions(params, origin), runtime);
400
+ const result = await formatStop(pi, params.id, ctx, getActiveSession, statusOptions(params, origin), runtime ?? await import("./runtime.domain.mjs"));
402
401
  refreshNavigator(ctx);
403
402
  return text(result);
404
403
  },
@@ -414,7 +413,7 @@ export function registerTools(pi, runtime = defaultRuntime, refreshNavigator = r
414
413
  },
415
414
  async execute(toolCallId, params, signal, _onUpdate, ctx) {
416
415
  activeSession = getCallbackOrigin(ctx);
417
- return actionText(pi, { ...params, request_id: params.request_id ?? toolCallId }, ctx, activeSession, getActiveSession, signal, runtime, refreshNavigator);
416
+ return actionText(pi, { ...params, request_id: params.request_id ?? toolCallId }, ctx, activeSession, getActiveSession, signal, runtime ?? await import("./runtime.domain.mjs"), refreshNavigator);
418
417
  },
419
418
  });
420
419
  register({
@@ -427,7 +426,7 @@ export function registerTools(pi, runtime = defaultRuntime, refreshNavigator = r
427
426
  },
428
427
  async execute(toolCallId, params, _signal, _onUpdate, ctx) {
429
428
  activeSession = getCallbackOrigin(ctx);
430
- return actionText(pi, { ...params, request_id: params.request_id ?? toolCallId }, ctx, activeSession, getActiveSession, undefined, runtime, refreshNavigator);
429
+ return actionText(pi, { ...params, request_id: params.request_id ?? toolCallId }, ctx, activeSession, getActiveSession, undefined, runtime ?? await import("./runtime.domain.mjs"), refreshNavigator);
431
430
  },
432
431
  });
433
432
  register({
@@ -442,14 +441,14 @@ export function registerTools(pi, runtime = defaultRuntime, refreshNavigator = r
442
441
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
443
442
  const host = getObservedWaitHost(pi);
444
443
  if (!host?.available) {
445
- return text(observedWaitServiceUnavailableReason(pi)
444
+ return text((await import("./observed-waits.domain.mjs")).observedWaitServiceUnavailableReason(pi)
446
445
  ?? "Observed waits are unavailable in this session; inspect tasks directly and continue without a durable wait.");
447
446
  }
448
447
  try {
449
448
  const wait = host.usesServerResults
450
449
  ? await host.superviseParentWait(ctx, params.task_ids, params.continuation_note)
451
450
  : host.waitForParent(ctx, params.task_ids, params.continuation_note);
452
- return text(formatWaitView(wait), wait);
451
+ return text((await import("./observed-waits.domain.mjs")).formatWaitView(wait), wait);
453
452
  }
454
453
  catch (error) {
455
454
  return text(`Wait was not registered: ${readableError(error)}`);
@@ -464,7 +463,7 @@ export function registerTools(pi, runtime = defaultRuntime, refreshNavigator = r
464
463
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
465
464
  const host = getObservedWaitHost(pi);
466
465
  if (!host?.available) {
467
- return text(observedWaitServiceUnavailableReason(pi)
466
+ return text((await import("./observed-waits.domain.mjs")).observedWaitServiceUnavailableReason(pi)
468
467
  ?? "Observed waits are unavailable in this session; no wait was consumed.");
469
468
  }
470
469
  try {
@@ -513,6 +512,7 @@ export function registerTools(pi, runtime = defaultRuntime, refreshNavigator = r
513
512
  const waits = host.listWaitsForParent(ctx, { pendingOnly: params.pending_only === true });
514
513
  if (waits.length === 0)
515
514
  return text("No durable waits for this session.");
515
+ const { formatWaitView } = await import("./observed-waits.domain.mjs");
516
516
  return text(waits.map((wait) => formatWaitView(wait)).join("\n\n"), waits);
517
517
  }
518
518
  catch (error) {
@@ -669,13 +669,19 @@ async function runAction(pi, params, ctx, callbackOrigin, getActiveSession, sign
669
669
  return `Unknown action: ${String(params.action)}`;
670
670
  }
671
671
  }
672
- /** Shared history applies ownership, filters and paging before metadata crosses the socket. */
672
+ /** Ordinary lists reuse retained activity; explicit filtered/paged lists open history. */
673
673
  async function durableAwareList(pi, params, origin, ctx) {
674
674
  const options = listOptions(params, origin);
675
- const snapshot = origin && !unavailableSessionOrigins.has(origin) ? await backgroundObservation(pi, ctx, true, params.all === true, { limit: options.limit, statuses: options.statuses, cursor: options.cursor }) : undefined;
675
+ const history = backgroundListNeedsHistory(params);
676
+ const snapshot = origin && !unavailableSessionOrigins.has(origin) ? await backgroundObservation(pi, ctx, history, params.all === true, { limit: options.limit, statuses: options.statuses, cursor: options.cursor }) : undefined;
676
677
  if (snapshot && snapshot.status !== "ready")
677
678
  throw new Error(snapshot.reason ?? "Background activity is unverified");
678
- const legacy = formatList(options, snapshot?.backgroundIndex);
679
+ const index = snapshot?.backgroundIndex ?? (snapshot ? { records: snapshot.rows
680
+ .map((row) => ({ found: true, meta: row.meta.durable ? { ...row.meta,
681
+ callbackOrigin: { cwd: row.meta.owner.workspace, sessionId: row.meta.owner.sessionId },
682
+ logPath: row.meta.logPaths?.stdout ?? "" } : row.meta }))
683
+ .sort((a, b) => b.meta.startedAt - a.meta.startedAt || b.meta.id.localeCompare(a.meta.id)) } : undefined);
684
+ const legacy = formatList(options, index);
679
685
  if (snapshot)
680
686
  return legacy;
681
687
  const host = getObservedWaitHost(pi);
@@ -833,8 +839,8 @@ function reportLaunch(launch) {
833
839
  * Start a watch and wait, bounded by `waitMs`, for its first check, so the launch result
834
840
  * shows what the check really prints (#359). Local and SSH watches share this path.
835
841
  */
836
- export async function launchWatch(pi, params, cwd, callbackOrigin, getActiveSession, waitMs = FIRST_WATCH_CHECK_WAIT_MS, signal, runtime = defaultRuntime) {
837
- const { startWatchTask, awaitFirstWatchCheck } = runtime;
842
+ export async function launchWatch(pi, params, cwd, callbackOrigin, getActiveSession, waitMs = FIRST_WATCH_CHECK_WAIT_MS, signal, runtime) {
843
+ const { startWatchTask, awaitFirstWatchCheck } = runtime ?? await import("./runtime.domain.mjs");
838
844
  let meta;
839
845
  try {
840
846
  meta = startWatchTask(pi, params, cwd, callbackOrigin, getActiveSession);
@@ -863,7 +869,8 @@ function getCallbackOrigin(ctx) {
863
869
  sessionId = undefined;
864
870
  unavailable = true;
865
871
  }
866
- const origin = { cwd: ctx?.cwd ?? "", sessionId };
872
+ const origin = { cwd: ctx?.cwd ?? "", sessionId,
873
+ branchId: ctx?.sessionManager?.getLeafId?.() ?? null };
867
874
  if (unavailable)
868
875
  unavailableSessionOrigins.add(origin);
869
876
  return origin;
@@ -968,8 +975,8 @@ function truncateToVisibleWidth(value, width) {
968
975
  const max = Math.max(0, Math.floor(width || 0));
969
976
  return String(value ?? "").slice(0, max);
970
977
  }
971
- async function formatStop(pi, id, _ctx, getActiveSession, options = {}, runtime = defaultRuntime) {
972
- const { stopTask } = runtime;
978
+ async function formatStop(pi, id, _ctx, getActiveSession, options = {}, runtime) {
979
+ const { stopTask } = runtime ?? await import("./runtime.domain.mjs");
973
980
  const existing = inspectMeta(id);
974
981
  if (!existing.meta && !existing.found)
975
982
  return formatStopResult(existing, options);