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
@@ -3,24 +3,49 @@ import { Check } from 'typebox/value';
3
3
  import { setImmediate as yieldTurn } from 'node:timers/promises';
4
4
  import { randomUUID } from 'node:crypto';
5
5
  import { join } from 'node:path';
6
- import { existsSync } from 'node:fs';
6
+ import { existsSync, openSync, closeSync, readSync, fstatSync } from 'node:fs';
7
7
  import { createAgentSession, DefaultResourceLoader, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent';
8
8
  import { acquireMutationStore } from './mutation-store.ts';
9
9
  /** Fixed canonical adapter. It never owns a native parent transcript. */
10
- export async function createBackgroundTools(root: string, instance: string, draining: () => boolean = () => false, observe?: (scope: Record<string, unknown>) => Promise<any>) {
10
+ export async function createBackgroundTools(root: string, instance: string, draining: () => boolean = () => false, observe?: (scope: Record<string, unknown>) => Promise<any>, verificationMs = 30000,
11
+ trace?: (slot: number, phase: 'queued' | 'executing' | 'recovery' | 'read-pending' | 'read-returned' | 'tool-pending' | 'tool-returned' | 'settled') => void) {
11
12
  const load = (file: string) => import(`./domain/background-service/${file}.domain.mjs`);
12
- const [{ createObservedWaitHost }, { registerTools }, { createBackgroundTaskRuntime }, sandbox, authority, permissions, registry, navigator, failures] = await Promise.all([
13
+ const [{ createObservedWaitHost }, { registerTools }, { createBackgroundTaskRuntime }, sandbox, authority, permissions, registry, navigator, failures, reviewSettings] = await Promise.all([
13
14
  load('observed-waits'), load('tools'), load('runtime'), load('sandbox'), load('managed-authority'),
14
- import(String('./domain/sandbox-policy/permission-settings.domain.mjs')), load('registry'), load('navigator-provider'), load('failures'),
15
+ import(String('./domain/sandbox-policy/permission-settings.domain.mjs')), load('registry'), load('navigator-provider'), load('failures'), load('review-settings'),
15
16
  ]);
17
+ const identity = await load('process-identity');
16
18
  const lease = acquireMutationStore(root);
19
+ const unknownWriters = new Map<string, number>();
17
20
  let journal: ReturnType<typeof lease.store.backgroundRequests>;
18
21
  let pi: any, service: any, session: any, runtime: any, current: any;
19
22
  let tail: Promise<unknown> = Promise.resolve(), pending = 0;
23
+ let traceSlot = 0;
20
24
  const projections = new Map<string, any>(), metrics = { scopeRefreshes: 0, exactDetailReads: 0, reconciles: 0 };
21
25
  const recoveryVersions = new Map<string, string>();
22
26
  const scopes = new Map<string, any>(), deliveries = new Map<string, any>();
27
+ const traceSeen = new Set<string>();
28
+ const traceHandoff = (stage: string, facts: Record<string, unknown>) => {
29
+ if (process.env.PI_BG_OBSERVED_WAITS_DEBUG !== '1') return;
30
+ const full = JSON.stringify({ stage, ...facts });
31
+ const line = full.length <= 4096 ? full : JSON.stringify({ stage, truncated: true });
32
+ if (traceSeen.has(line) || traceSeen.size >= 128) return;
33
+ const output = traceSeen.size === 127 ? JSON.stringify({ stage: 'capture-limit', limit: 128 }) : line;
34
+ traceSeen.add(line);
35
+ try { console.error('[background-handoff-server]', output); } catch { /* diagnostics never own delivery */ }
36
+ };
37
+ const isAttentionDelivery = (item: any) => {
38
+ const type = item.notification.event?.customType;
39
+ return type === 'background-task-stall' || type === 'background-wait-review';
40
+ };
41
+ const sameNativeHost = (item: any, record: any) => item.scope.pid === record.pid && item.scope.start === record.start;
42
+ const deliveryLeaseMs = 30000;
23
43
  const ownerKey = (owner: any) => JSON.stringify([owner.workspace, owner.sessionId]);
44
+ const forgetView = (view: string) => { projections.delete(view); recoveryVersions.delete(view); };
45
+ const forgetOwner = (key: string) => {
46
+ for (const view of new Set([...projections.keys(), ...recoveryVersions.keys()]))
47
+ if (JSON.parse(view)[0] === key) forgetView(view);
48
+ };
24
49
  const effectivePolicy = (record: any) => effectiveBackgroundPolicy(record.policy, permissions.readPermissionSettings({ agentDir: () => root }).background, record.owner.workspace);
25
50
  const assertAdmission = () => {
26
51
  if (!current)
@@ -31,16 +56,21 @@ export async function createBackgroundTools(root: string, instance: string, drai
31
56
  };
32
57
  const notifyParent = (notification: any, delivery: any) => {
33
58
  const owner = { workspace: notification.origin?.cwd, sessionId: notification.origin?.sessionId }, scope = scopes.get(ownerKey(owner));
59
+ const facts = { taskId: notification.taskId, receiptId: delivery.receiptId, sessionId: owner.sessionId, urgent: notification.urgent === true };
60
+ traceHandoff('notify', facts);
34
61
  if (!scope || deliveries.size >= 256) {
62
+ traceHandoff('defer', { ...facts, scopeKnown: Boolean(scope), backlog: deliveries.size });
35
63
  delivery.defer('Native recipient unavailable or delivery backlog full');
36
64
  return;
37
65
  }
38
66
  if ([...deliveries.values()].some(item => item.receiptId === delivery.receiptId && ownerKey(item.scope.owner) === ownerKey(owner))) {
67
+ traceHandoff('duplicate', facts);
39
68
  delivery.defer('Delivery already pending');
40
69
  return;
41
70
  }
42
71
  const token = randomUUID();
43
72
  deliveries.set(token, { token, notification, receiptId: delivery.receiptId ?? `background-terminal:${notification.operationId}`, delivery, scope, createdAt: Date.now() });
73
+ traceHandoff('enqueued', facts);
44
74
  };
45
75
  try {
46
76
  journal = lease.store.backgroundRequests();
@@ -64,8 +94,14 @@ export async function createBackgroundTools(root: string, instance: string, drai
64
94
  pi = new Proxy(api, { get(target, key) { if (key === 'sendMessage')
65
95
  return () => { throw new Error('Native parent transcript delivery requires authenticated frontend'); }; const value = Reflect.get(target, key); return typeof value === 'function' ? value.bind(target) : value; } });
66
96
  runtime = createBackgroundTaskRuntime(failures.createFailureAttention((origin:any,event:any)=>new Promise<boolean>(resolve=>notifyParent({origin,taskId:event.inspectId??event.id,status:event.status,urgent:true,event:{...event,isDelivered:undefined,getSuppressionReason:undefined,onDelivered:undefined}},
67
- {receiptId:event.receiptId,delivered:()=>{event.onDelivered?.(Date.now());resolve(true);},defer:()=>resolve(false)}))), (origin: any, event: any) => notifyParent({ origin, taskId: event.id, status: event.status, outcome: event.outcome, event: { ...event, isDelivered: undefined, getSuppressionReason: undefined, onDelivered: undefined, onSuppressed: undefined } }, { receiptId: event.receiptId, delivered: () => event.onDelivered?.(Date.now()), defer: () => undefined }), { assert: assertAdmission, prepared: (id: string) => journal.operation(current.ownerKey, current.record.key, { operationId: `legacy:${id}`, taskId: id, token: current.record.key }) });
97
+ {receiptId:event.receiptId,delivered:()=>{event.onDelivered?.(Date.now());resolve(true);},defer:()=>resolve(false)}))), (origin: any, event: any) => notifyParent({ origin, taskId: event.id, status: event.status, outcome: event.outcome, event: { ...event, isDelivered: undefined, getSuppressionReason: undefined, onDelivered: undefined, onSuppressed: undefined } }, { receiptId: event.receiptId, delivered: () => event.onDelivered?.(Date.now()), defer: () => undefined }), { assert: assertAdmission,
98
+ prepared: (id: string) => journal.operation(current.ownerKey, current.record.key, { operationId: `legacy:${id}`, taskId: id, token: current.record.key }) },
99
+ (kind: string, id: string, work: () => unknown, dueAt?: number) => {
100
+ const origin = registry.readMeta(id)?.callbackOrigin;
101
+ return lease.budget.scheduleSource(`legacy-${kind}`, id, work, JSON.stringify([origin?.cwd ?? root, origin?.sessionId ?? null]), dueAt);
102
+ });
68
103
  service = createObservedWaitHost(pi, { sharedStore: lease.store, storePath: join(root, 'operation-coordinator.sqlite'), serverOwnedResults: true, pollMs: 0,
104
+ enterControl: () => lease.budget.enter('control'),
69
105
  notifyParent, assertAdmission,
70
106
  authorizeParentCancellation: ({requester, operation, requestId}: any) => {
71
107
  assertAdmission();
@@ -107,21 +143,49 @@ export async function createBackgroundTools(root: string, instance: string, drai
107
143
  }
108
144
  return {
109
145
  get busy() { return pending > 0; },
146
+ lifecycleReasons() {
147
+ const now = Date.now(), reasons: any[] = journal.lifecycleReasons().map((reason: any) => ({ ...reason,
148
+ management: { instance } }));
149
+ for (const scope of scopes.values()) for (const meta of registry.listActiveMetasForOrigin({ cwd: scope.owner.workspace, sessionId: scope.owner.sessionId })) {
150
+ if (meta.status !== 'running') continue;
151
+ const watch = meta.kind === 'command_watch' || Boolean(meta.remote);
152
+ const verified = meta.pid && meta.pidStartTime && identity.readProcessStartToken(meta.pid) === meta.pidStartTime;
153
+ if (!watch && !verified) {
154
+ if (!unknownWriters.has(meta.id)) unknownWriters.set(meta.id, now);
155
+ const since = unknownWriters.get(meta.id)!;
156
+ if (now >= since + verificationMs) continue;
157
+ reasons.push({ kind: 'verification', id: meta.id, owner: scope.owner, lastProgressAt: since,
158
+ nextDeadline: since + verificationMs, recovery: 'legacy-writer-unverified-no-takeover' });
159
+ continue;
160
+ }
161
+ unknownWriters.delete(meta.id);
162
+ reasons.push({ kind: watch ? 'task' : 'runner', id: meta.id, owner: scope.owner,
163
+ writer: { pid: meta.pid, start: meta.pidStartTime }, lastProgressAt: meta.lastProgressAt ?? meta.startedAt,
164
+ nextDeadline: meta.deadlineAt ?? (watch ? (meta.lastCheckedAt ?? meta.startedAt) + (meta.intervalMs ?? 1000) : now + 1000),
165
+ recovery: watch ? 'captured-legacy-watch' : 'captured-legacy-command' });
166
+ }
167
+ return reasons;
168
+ },
110
169
  metrics() { return { ...metrics, registry: registry.getRegistryIoMetrics(), cachedScopes: projections.size }; },
111
- handle(command: any) {
170
+ handle(command: any, onAccepted?: (id: string) => void) {
112
171
  if (Object.keys(command).some(key => !['id', 'type', 'authority'].includes(key)))
113
172
  return Promise.reject(new Error('unsupported Background request field'));
114
173
  if (pending >= 64)
115
174
  return Promise.reject(new Error('runtime-overloaded: Background request capacity'));
116
175
  pending++;
176
+ const slot = ++traceSlot;
177
+ trace?.(slot, 'queued');
117
178
  const request = tail.catch(() => undefined).then(async () => {
179
+ trace?.(slot, 'executing');
118
180
  const record = authority.readBackgroundAuthority(root, instance, command.authority), key = ownerKey(record.owner);
181
+ // A warmed branch view must not overwrite another foreground's progress.
182
+ const viewKey = JSON.stringify([key, authority.backgroundDigest(record.branchIds)]);
119
183
  const policy = effectivePolicy(record);
120
184
  current = { record, authority: command.authority, ownerKey: key, digest: authority.backgroundDigest(record), policy, policyDigest: authority.backgroundDigest(policy ?? null) };
121
185
  if (scopes.size >= 128 && !scopes.has(key)) {
122
186
  const oldest = [...scopes.keys()].find(candidate => ![...deliveries.values()].some(item => ownerKey(item.scope.owner) === candidate));
123
187
  if (oldest) {
124
- scopes.delete(oldest); recoveryVersions.delete(oldest);
188
+ scopes.delete(oldest); forgetOwner(oldest);
125
189
  }
126
190
  else
127
191
  throw new Error('runtime-overloaded: Background scope capacity');
@@ -135,15 +199,16 @@ export async function createBackgroundTools(root: string, instance: string, drai
135
199
  sessionManager: { getSessionId: () => record.owner.sessionId, getBranch: () => branch, getEntries: () => branch, getLeafId: () => record.branchIds.at(-1), getSessionFile: () => undefined } };
136
200
  service.noteParentContext(ctx, { recover: false });
137
201
  for (const [token, item] of deliveries)
138
- if (Date.now() - item.createdAt > 30000) {
202
+ if (Date.now() - item.createdAt >= deliveryLeaseMs) {
139
203
  item.delivery.defer('Native delivery lease expired');
140
- projections.delete(ownerKey(item.scope.owner));
141
- recoveryVersions.delete(ownerKey(item.scope.owner));
204
+ forgetOwner(ownerKey(item.scope.owner));
142
205
  deliveries.delete(token);
143
206
  }
144
207
  if (record.tool === '__background_receipt') {
145
208
  const item = deliveries.get(record.params.token);
146
- if (!item || ownerKey(item.scope.owner) !== key)
209
+ traceHandoff('receipt', { sessionId: record.owner.sessionId, taskId: item?.notification.taskId,
210
+ receiptId: item?.receiptId, found: Boolean(item), delivered: record.params.delivered === true });
211
+ if (!item || ownerKey(item.scope.owner) !== key || isAttentionDelivery(item) && !sameNativeHost(item, record))
147
212
  throw new Error('delivery-receipt-refused');
148
213
  if (record.params.delivered === true && !service.isParentOriginActive(item.notification.origin, item.notification.branchId))
149
214
  throw new Error('delivery-recipient-inactive');
@@ -151,42 +216,104 @@ export async function createBackgroundTools(root: string, instance: string, drai
151
216
  item.delivery.delivered();
152
217
  else {
153
218
  item.delivery.defer(String(record.params.reason ?? 'Native handoff deferred'));
154
- projections.delete(key);
155
219
  }
156
220
  deliveries.delete(record.params.token);
157
- projections.delete(key);
158
- recoveryVersions.delete(key);
221
+ forgetOwner(key);
159
222
  return { receipted: record.params.delivered === true };
160
223
  }
161
224
  if (record.tool === '__background_poll') {
225
+ traceHandoff('poll-enter', { sessionId: record.owner.sessionId });
162
226
  if (!observe)
163
227
  throw new Error('Shared Background observation unavailable');
164
228
  // Recovery is indexed and bounded independently of display readiness.
165
229
  const recoveryVersion = authority.backgroundDigest([lease.store.getChangeRevision(), record.branchIds]);
166
- if (recoveryVersions.get(key) !== recoveryVersion || service.hasPendingParentCallbackRecovery()) {
230
+ if (recoveryVersions.get(viewKey) !== recoveryVersion || service.hasPendingParentCallbackRecovery()) {
167
231
  metrics.reconciles++;
168
232
  service.noteParentContext(ctx);
233
+ trace?.(slot, 'recovery');
169
234
  await service.reconcileNow();
170
- recoveryVersions.set(key, recoveryVersion);
235
+ if (!recoveryVersions.has(viewKey) && recoveryVersions.size >= 128) forgetView(recoveryVersions.keys().next().value!);
236
+ recoveryVersions.set(viewKey, recoveryVersion);
171
237
  }
238
+ trace?.(slot, 'read-pending');
172
239
  const snapshot = await observe({ background: true, cwd: record.owner.workspace, sessionId: record.owner.sessionId });
240
+ trace?.(slot, 'read-returned');
173
241
  if (snapshot.status !== 'ready')
174
242
  throw new Error(snapshot.reason ?? 'Shared Background observation unverified');
243
+ // Callback pointers carry a delivery obligation but no navigator detail.
244
+ const visibleRows = snapshot.rows.filter(({ meta }: any) => !meta.callbackPending
245
+ && (!meta.parentRecipient?.branchId || record.branchIds.includes(meta.parentRecipient.branchId)));
175
246
  const revision = authority.backgroundDigest([snapshot.scopeRevision, record.branchIds]);
176
- let projection = projections.get(key);
247
+ let projection = projections.get(viewKey);
177
248
  if (projection?.revision !== revision) {
178
249
  metrics.scopeRefreshes++;
179
- const legacy = snapshot.rows.filter((row: any) => !row.meta.durable).map((row: any) => row.meta);
250
+ const legacy = visibleRows.filter((row: any) => !row.meta.durable).map((row: any) => row.meta);
180
251
  const recovery=new Map([...legacy,...registry.listPendingCallbackMetasForOrigin({cwd:record.owner.workspace,sessionId:record.owner.sessionId})].map((meta:any)=>[meta.id,meta]));
181
252
  for (const meta of recovery.values())
182
253
  if (meta.status === 'running' || meta.callback !== false && !meta.callbackSentAt && !meta.callbackSuppressedAt)
183
254
  runtime.resumeRunningTask(pi, meta, () => ({ cwd: record.owner.workspace, sessionId: record.owner.sessionId }));
184
- projection = { revision, tasks: snapshot.rows.filter((row: any) => row.meta.durable).map((row: any) => row.meta), legacyRows: legacy.filter((meta: any) => !meta.dismissedAt).map((meta: any) => navigator.rowFromMeta(meta, Date.now())) };
185
- if (projections.size >= 128 && !projections.has(key))
186
- projections.delete(projections.keys().next().value!);
187
- projections.set(key, projection);
255
+ projection = { revision, tasks: visibleRows.filter((row: any) => row.meta.durable).map((row: any) => row.meta), legacyRows: legacy.filter((meta: any) => !meta.dismissedAt).map((meta: any) => navigator.rowFromMeta(meta, Date.now())) };
256
+ if (projections.size >= 128 && !projections.has(viewKey))
257
+ forgetView(projections.keys().next().value!);
258
+ projections.set(viewKey, projection);
259
+ }
260
+ // A task may finish while the client is disconnected, then
261
+ // age out of the recent index before reconnect. Resolve only
262
+ // the client's bounded, previously active IDs in this owner.
263
+ const tasks = [...projection.tasks];
264
+ const present = new Set(tasks.map((task: any) => task.id));
265
+ if (Array.isArray(record.params.knownActiveIds)) {
266
+ for (const id of new Set(record.params.knownActiveIds.slice(0, 200))) {
267
+ if (typeof id !== 'string' || present.has(id)) continue;
268
+ let task = service.readDurableTask({cwd: record.owner.workspace, sessionId: record.owner.sessionId}, id);
269
+ if (!task) {
270
+ const exact = await observe({background: true, cwd: record.owner.workspace, sessionId: record.owner.sessionId, id});
271
+ task = exact.rows.find((row: any) => row.meta.id === id && !row.meta.callbackPending)?.meta;
272
+ }
273
+ if (task && task.dismissedAt === undefined && (!task.parentRecipient?.branchId || record.branchIds.includes(task.parentRecipient.branchId))) { tasks.push(task); present.add(id); }
274
+ }
188
275
  }
189
- return { ...projection, recoveryPending: service.hasPendingParentCallbackRecovery(), deliveries: [...deliveries.values()].filter(item => ownerKey(item.scope.owner) === key).map(({ token, notification, receiptId }) => ({ token, notification, receiptId })) };
276
+ const origin = { cwd: record.owner.workspace, sessionId: record.owner.sessionId };
277
+ const liveAlerts = new Map<string, any>();
278
+ const reviewTasks = tasks.filter(task => task.active && task.progress && task.callback && task.owner.kind === 'parent-session');
279
+ let intervalMinutes = reviewSettings.DEFAULT_BACKGROUND_REVIEW_INTERVAL_MINUTES;
280
+ if (reviewTasks.some(task => task.waits.length)) {
281
+ try { intervalMinutes = reviewSettings.readBackgroundReviewInterval({ agentDir: () => root }); }
282
+ catch { /* An unreadable settings file must not interrupt Background delivery. */ }
283
+ }
284
+ let nextReviewAt = Infinity;
285
+ for (const task of reviewTasks) {
286
+ const stall = task.progress.alertDue ? service.pendingStallAlert(origin, task.id, task.waits) : undefined;
287
+ const review = task.waits.length ? service.backgroundWaitReview(origin, task.id, task.waits, intervalMinutes * 60_000) : undefined;
288
+ for (const alert of [stall, review?.alert]) {
289
+ if (!alert) continue;
290
+ liveAlerts.set(alert.delivery.receiptId, alert.notification);
291
+ notifyParent(alert.notification, alert.delivery);
292
+ }
293
+ if (review && !review.alert) nextReviewAt = Math.min(nextReviewAt, review.dueAt);
294
+ }
295
+ const outgoing = [];
296
+ let retryAfterMs = Number.isFinite(nextReviewAt) ? Math.max(1, nextReviewAt - Date.now()) : undefined;
297
+ if (liveAlerts.size && deliveries.size >= 256) retryAfterMs = Math.min(retryAfterMs ?? 1000, 1000);
298
+ for (const [token, item] of deliveries) {
299
+ if (ownerKey(item.scope.owner) !== key) continue;
300
+ let notification = item.notification;
301
+ if (isAttentionDelivery(item)) {
302
+ if (item.notification.branchId && !record.branchIds.includes(item.notification.branchId)) continue;
303
+ notification = liveAlerts.get(item.receiptId);
304
+ if (!notification) { deliveries.delete(token); continue; }
305
+ // Two frontends can share a session and branch. Only the holder may hand off
306
+ // each alert. A survivor polls again at lease expiry if no receipt arrives.
307
+ if (!sameNativeHost(item, record)) {
308
+ const remaining = Math.max(1, item.createdAt + deliveryLeaseMs - Date.now());
309
+ retryAfterMs = Math.min(retryAfterMs ?? remaining, remaining);
310
+ continue;
311
+ }
312
+ }
313
+ outgoing.push({ token, notification, receiptId: item.receiptId });
314
+ }
315
+ traceHandoff('poll-return', { sessionId: record.owner.sessionId, total: outgoing.length, deliveries: outgoing.slice(0, 8).map(item => ({ taskId: item.notification.taskId, receiptId: item.receiptId })) });
316
+ return { ...projection, tasks, retryAfterMs, recoveryPending: service.hasPendingParentCallbackRecovery(), deliveries: outgoing };
190
317
  }
191
318
  const origin = { cwd: record.owner.workspace, sessionId: record.owner.sessionId };
192
319
  if (record.tool === '__background_detail' || record.tool === '__background_action') {
@@ -209,8 +336,28 @@ export async function createBackgroundTools(root: string, instance: string, drai
209
336
  registry.writeMeta(meta);
210
337
  return true;
211
338
  }
212
- if (record.tool === '__background_log')
213
- return service.readDurableTaskLog(origin, record.params.id, record.params.lines);
339
+ if (record.tool === '__background_log') {
340
+ const owned = service.readDurableTaskLog(origin, record.params.id, record.params.lines);
341
+ if (owned) return owned;
342
+ const snapshot = await observe?.({background: true, ...origin, id: record.params.id});
343
+ if (snapshot?.status !== 'ready') throw new Error('Background task observation unavailable; retry after recovery');
344
+ const task = snapshot.rows.find((row: any) => row.meta.id === record.params.id)?.meta;
345
+ if (!task?.readOnly || task.parentRecipient?.branchId && !record.branchIds.includes(task.parentRecipient.branchId))
346
+ throw new Error('Background task is outside the captured scope');
347
+ const count = Math.max(1, Math.min(200, Number(record.params.lines) || 40));
348
+ let truncated = false;
349
+ const tail = (path: string) => {
350
+ const fd = openSync(path, 'r');
351
+ try {
352
+ const size = fstatSync(fd).size, bytes = Math.min(size, 65536);
353
+ truncated ||= size > bytes;
354
+ const buffer = Buffer.alloc(bytes); const read = readSync(fd, buffer, 0, bytes, size - bytes);
355
+ return buffer.subarray(0, read).toString('utf8').split('\n').slice(-count).join('\n');
356
+ } finally { closeSync(fd); }
357
+ };
358
+ return {taskId: task.id, status: task.status, stdout: tail(task.logPaths.stdout),
359
+ stderr: tail(task.logPaths.stderr), events: tail(task.logPaths.events), truncated};
360
+ }
214
361
  if (record.tool === '__background_stop')
215
362
  return service.stopDurableTask(origin, record.params.id);
216
363
  if (record.tool === '__background_dismiss')
@@ -226,15 +373,19 @@ export async function createBackgroundTools(root: string, instance: string, drai
226
373
  if (admission && draining() && !prior)
227
374
  throw new Error('runtime-draining: new Background execution deferred for upgrade');
228
375
  if (mutation) {
229
- const accepted = journal.accept(key, record.key, authority.backgroundDigest({ tool: record.tool, params: record.params }));
376
+ const accepted = journal.accept(key, record.key, authority.backgroundDigest({ tool: record.tool, params: record.params }),
377
+ { instance, pid: record.pid, start: record.start });
230
378
  if (accepted.prior)
231
379
  return accepted.record.result ?? { content: [{ type: 'text', text: 'Accepted Background request has an uncertain outcome; inspect its exact operations before issuing new work.' }], details: { status: 'outcome_unknown', operations: accepted.record.operations } };
232
380
  journal.dispatch(key, record.key);
381
+ onAccepted?.(`background-request-v1:${authority.backgroundDigest([key, record.key])}`);
233
382
  }
234
383
  assertAdmission();
235
384
  let result;
236
385
  try {
386
+ trace?.(slot, 'tool-pending');
237
387
  result = await tool.execute(record.key, record.params, undefined, undefined, ctx);
388
+ trace?.(slot, 'tool-returned');
238
389
  }
239
390
  catch (error) {
240
391
  if (mutation)
@@ -253,7 +404,10 @@ export async function createBackgroundTools(root: string, instance: string, drai
253
404
  if (mutation)
254
405
  journal.finish(key, record.key, result);
255
406
  return result;
256
- }).finally(() => { pending--; });
407
+ }).catch(error => {
408
+ traceHandoff('request-error', { tool: current?.record.tool, sessionId: current?.record.owner.sessionId, error: String(error).slice(0, 256) });
409
+ throw error;
410
+ }).finally(() => { pending--; trace?.(slot, 'settled'); });
257
411
  tail = request;
258
412
  return request;
259
413
  },