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,7 +1,7 @@
1
1
  import { createHash, timingSafeEqual } from 'node:crypto';
2
2
  import { lstatSync, readFileSync, realpathSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
- import { readProcessStartTokenFresh } from './process-identity.js';
4
+ import { readAdmissionStartToken, readProcessStartTokenFresh } from './process-identity.js';
5
5
  const ordered = (value: any): any => value === null || typeof value !== 'object' ? value : Array.isArray(value) ? value.map(ordered) : Object.fromEntries(Object.keys(value).sort().map(key => [key, ordered(value[key])]));
6
6
  export const backgroundDigest = (value: unknown) => createHash('sha256').update(JSON.stringify(ordered(value))).digest('hex');
7
7
  export function readBackgroundAuthority(root: string, instance: string, authority: any, requireLive = true): any {
@@ -13,14 +13,16 @@ export function readBackgroundAuthority(root: string, instance: string, authorit
13
13
  || !stat.isFile() || stat.isSymbolicLink() || stat.uid !== dir.uid || (stat.mode & 0o077) || stat.size > 1024 * 1024)
14
14
  throw new Error('background-authority-refused');
15
15
  const record = JSON.parse(readFileSync(path, 'utf8')), digest = createHash('sha256').update(authority.secret).digest('hex');
16
- if (record.version !== 1 || record.instanceId !== instance || record.id !== authority.id || typeof record.secretHash !== 'string'
16
+ if ((record.version !== 1 && record.version !== 2) || record.instanceId !== instance || record.id !== authority.id || typeof record.secretHash !== 'string'
17
17
  || record.secretHash.length !== digest.length || !timingSafeEqual(Buffer.from(record.secretHash), Buffer.from(digest))
18
18
  || typeof record.key !== 'string' || !record.key || typeof record.tool !== 'string' || !record.owner?.sessionId
19
19
  || record.owner.workspace !== realpathSync(record.owner.workspace) || !Number.isSafeInteger(record.pid) || !record.start
20
20
  || !Array.isArray(record.branchIds) || record.branchIds.some((id: unknown) => typeof id !== 'string'))
21
21
  throw new Error('background-authority-refused');
22
22
  if (requireLive) {
23
- if (readProcessStartTokenFresh(record.pid) !== record.start)
23
+ const start = record.version === 2 ? readAdmissionStartToken(record.pid) : readProcessStartTokenFresh(record.pid);
24
+ if (!start) throw new Error('background-authority-refused: cannot verify host start time');
25
+ if (start !== record.start)
24
26
  throw new Error('background-authority-refused: host identity changed');
25
27
  process.kill(record.pid, 0);
26
28
  }
@@ -4,25 +4,37 @@ import { lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, w
4
4
  import { join } from 'node:path';
5
5
  import { getAgentDir } from '@earendil-works/pi-coding-agent';
6
6
  import { backgroundDigest } from "./managed-authority.domain.mjs";
7
- import { readProcessStartTokenFresh } from "./process-identity.domain.mjs";
7
+ import { readAdmissionStartToken, readProcessStartTokenFresh } from "./process-identity.domain.mjs";
8
8
  import { currentForegroundSandboxPolicy, FOREGROUND_SANDBOX_POLICY_CHANNEL } from "./sandbox.domain.mjs";
9
- import { backgroundObservation } from "./work-observation.domain.mjs";
9
+ import { backgroundListNeedsHistory, backgroundObservation } from "./work-observation.domain.mjs";
10
10
  /** Native host proof carries scope and captured policy, never a transcript or module path. */
11
11
  export async function requestBackgroundTool(pi, ctx, key, tool, params, parameters, signal) {
12
12
  if (signal?.aborted)
13
13
  throw new Error('Background request cancelled before admission');
14
- await backgroundObservation(pi, ctx);
14
+ const input = params && typeof params === 'object' ? params : {};
15
+ const list = tool === 'bg_task_list' || (tool === 'bg_task' && input.action === 'list');
16
+ if (list && backgroundListNeedsHistory(input)) {
17
+ // The root history index is shared. Wait on its read plane before acquiring
18
+ // a grant or entering the serialized tool queue, even for an all-session list.
19
+ const snapshot = await backgroundObservation(pi, ctx, true, false, { limit: 1 }, { timeoutMs: 60000, signal });
20
+ if (snapshot.status !== 'ready')
21
+ throw new Error(snapshot.reason ?? `Background history is ${snapshot.status}`);
22
+ }
23
+ else {
24
+ await backgroundObservation(pi, ctx);
25
+ }
26
+ signal?.throwIfAborted();
15
27
  const root = realpathSync(getAgentDir()), registration = JSON.parse(readFileSync(join(root, 'server-registration-v1.json'), 'utf8'));
16
28
  if (registration.version !== 1 || registration.agentDir !== root)
17
29
  throw new Error('Invalid runtime registration');
18
30
  const module = new URL('./shared-work-client.mjs', import.meta.url).href;
19
- const { WorkClient } = await import(module);
31
+ const { connectWorkClient } = await import(module);
20
32
  const directory = join(root, 'background-tool-admission');
21
33
  mkdirSync(directory, { recursive: true, mode: 0o700 });
22
34
  const stat = lstatSync(directory);
23
35
  if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o077))
24
36
  throw new Error('Unsafe Background admission directory');
25
- const client = new WorkClient(join(registration.serverDir, 'pi-server.sock'), root, ['runtime-background-execution-v1']);
37
+ const client = await connectWorkClient(join(registration.serverDir, 'pi-server.sock'), root, ['runtime-background-execution-v1'], { signal });
26
38
  const id = randomUUID(), secret = randomBytes(32).toString('hex'), path = join(directory, `${id}.json`);
27
39
  let off;
28
40
  const abort = () => client.close();
@@ -34,9 +46,11 @@ export async function requestBackgroundTool(pi, ctx, key, tool, params, paramete
34
46
  const sessionId = ctx.sessionManager.getSessionId();
35
47
  if (!sessionId)
36
48
  throw new Error('Background tools require a native session identity');
37
- const record = { version: 1, id, secretHash: createHash('sha256').update(secret).digest('hex'), instanceId: hello.instanceId,
49
+ const version = hello.capabilities?.includes("runtime-background-admission-v2") ? 2 : 1;
50
+ const start = version === 2 ? readAdmissionStartToken(process.pid) : readProcessStartTokenFresh(process.pid);
51
+ const record = { version, id, secretHash: createHash('sha256').update(secret).digest('hex'), instanceId: hello.instanceId,
38
52
  owner: { kind: 'parent-session', sessionId, workspace: realpathSync(ctx.cwd) }, branchIds, projectTrusted: ctx.isProjectTrusted(),
39
- pid: process.pid, start: readProcessStartTokenFresh(process.pid), key, tool, params, parametersDigest: parameters === undefined ? undefined : backgroundDigest(parameters), policy };
53
+ pid: process.pid, start, key, tool, params, parametersDigest: parameters === undefined ? undefined : backgroundDigest(parameters), policy };
40
54
  const staged = `${path}.tmp`;
41
55
  writeFileSync(staged, JSON.stringify(record), { flag: 'wx', mode: 0o600 });
42
56
  renameSync(staged, path);
@@ -3,25 +3,36 @@ import { lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, w
3
3
  import { join } from 'node:path';
4
4
  import { getAgentDir, type ExtensionAPI, type ExtensionContext } from '@earendil-works/pi-coding-agent';
5
5
  import { backgroundDigest } from './managed-authority.js';
6
- import { readProcessStartTokenFresh } from './process-identity.js';
6
+ import { readAdmissionStartToken, readProcessStartTokenFresh } from './process-identity.js';
7
7
  import { currentForegroundSandboxPolicy, FOREGROUND_SANDBOX_POLICY_CHANNEL } from './sandbox.js';
8
- import { backgroundObservation } from './work-observation.js';
8
+ import { backgroundListNeedsHistory, backgroundObservation } from './work-observation.js';
9
9
  /** Native host proof carries scope and captured policy, never a transcript or module path. */
10
10
  export async function requestBackgroundTool(pi: ExtensionAPI, ctx: ExtensionContext, key: string, tool: string, params: unknown, parameters?: unknown, signal?: AbortSignal): Promise<any> {
11
11
  if (signal?.aborted)
12
12
  throw new Error('Background request cancelled before admission');
13
- await backgroundObservation(pi, ctx);
13
+ const input = params && typeof params === 'object' ? params as Record<string, unknown> : {};
14
+ const list = tool === 'bg_task_list' || (tool === 'bg_task' && input.action === 'list');
15
+ if (list && backgroundListNeedsHistory(input)) {
16
+ // The root history index is shared. Wait on its read plane before acquiring
17
+ // a grant or entering the serialized tool queue, even for an all-session list.
18
+ const snapshot = await backgroundObservation(pi, ctx, true, false, { limit: 1 }, { timeoutMs: 60000, signal });
19
+ if (snapshot.status !== 'ready')
20
+ throw new Error(snapshot.reason ?? `Background history is ${snapshot.status}`);
21
+ } else {
22
+ await backgroundObservation(pi, ctx);
23
+ }
24
+ signal?.throwIfAborted();
14
25
  const root = realpathSync(getAgentDir()), registration = JSON.parse(readFileSync(join(root, 'server-registration-v1.json'), 'utf8'));
15
26
  if (registration.version !== 1 || registration.agentDir !== root)
16
27
  throw new Error('Invalid runtime registration');
17
28
  const module = new URL('./shared-work-client.mjs', import.meta.url).href;
18
- const { WorkClient } = await import(module);
29
+ const { connectWorkClient } = await import(module);
19
30
  const directory = join(root, 'background-tool-admission');
20
31
  mkdirSync(directory, { recursive: true, mode: 0o700 });
21
32
  const stat = lstatSync(directory);
22
33
  if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o077))
23
34
  throw new Error('Unsafe Background admission directory');
24
- const client = new WorkClient(join(registration.serverDir, 'pi-server.sock'), root, ['runtime-background-execution-v1']);
35
+ const client = await connectWorkClient(join(registration.serverDir, 'pi-server.sock'), root, ['runtime-background-execution-v1'], { signal });
25
36
  const id = randomUUID(), secret = randomBytes(32).toString('hex'), path = join(directory, `${id}.json`);
26
37
  let off: unknown;
27
38
  const abort = () => client.close();
@@ -33,9 +44,11 @@ export async function requestBackgroundTool(pi: ExtensionAPI, ctx: ExtensionCont
33
44
  const sessionId = ctx.sessionManager.getSessionId();
34
45
  if (!sessionId)
35
46
  throw new Error('Background tools require a native session identity');
36
- const record = { version: 1, id, secretHash: createHash('sha256').update(secret).digest('hex'), instanceId: hello.instanceId,
47
+ const version = hello.capabilities?.includes("runtime-background-admission-v2") ? 2 : 1;
48
+ const start = version === 2 ? readAdmissionStartToken(process.pid) : readProcessStartTokenFresh(process.pid);
49
+ const record = { version, id, secretHash: createHash('sha256').update(secret).digest('hex'), instanceId: hello.instanceId,
37
50
  owner: { kind: 'parent-session', sessionId, workspace: realpathSync(ctx.cwd) }, branchIds, projectTrusted: ctx.isProjectTrusted(),
38
- pid: process.pid, start: readProcessStartTokenFresh(process.pid), key, tool, params, parametersDigest: parameters === undefined ? undefined : backgroundDigest(parameters), policy };
51
+ pid: process.pid, start, key, tool, params, parametersDigest: parameters === undefined ? undefined : backgroundDigest(parameters), policy };
39
52
  const staged = `${path}.tmp`;
40
53
  writeFileSync(staged, JSON.stringify(record), { flag: 'wx', mode: 0o600 });
41
54
  renameSync(staged, path);
@@ -3,12 +3,16 @@ import { randomUUID } from 'node:crypto';
3
3
  import { requestBackgroundTool } from "./managed-client.domain.mjs";
4
4
  import { onBackgroundObservation } from "./work-observation.domain.mjs";
5
5
  import { getCallbackBatcher } from "./shared-callback-batcher.domain.mjs";
6
- import { registerObservedWaitClient } from "./observed-waits.domain.mjs";
6
+ import { registerObservedWaitClient } from "./observed-wait-client.domain.mjs";
7
+ import { observeNavigatorLaunch } from "./shared-navigator.domain.mjs";
7
8
  /** Native transcript delivery and cached UI projections; no coordinator or supervisor. */
8
9
  export function createManagedBackgroundFrontend(pi) {
9
10
  let ctx, generation = 0, refresh, dirty = false;
10
11
  let rows = [], legacyRows = [], details = new Map(), logs = new Map();
12
+ const retainedTasks = new Map();
13
+ const cachedTask = (id) => rows.find(row => row.id === id) ?? retainedTasks.get(id);
11
14
  let adoptedScope;
15
+ let observing = false;
12
16
  const scopeOf = (context) => JSON.stringify([context.cwd, context.sessionManager.getSessionId()]);
13
17
  const ownership = new Map();
14
18
  const adoptContext = (context) => {
@@ -18,6 +22,7 @@ export function createManagedBackgroundFrontend(pi) {
18
22
  legacyRows = [];
19
23
  details.clear();
20
24
  logs.clear();
25
+ retainedTasks.clear();
21
26
  generation++;
22
27
  }
23
28
  ctx = context;
@@ -34,6 +39,21 @@ export function createManagedBackgroundFrontend(pi) {
34
39
  ownership.delete(ownership.keys().next().value);
35
40
  };
36
41
  const queued = new Set(), listeners = new Set();
42
+ const traceSeen = new Set();
43
+ const trace = (stage, facts = {}) => {
44
+ if (process.env.PI_BG_OBSERVED_WAITS_DEBUG !== '1')
45
+ return;
46
+ const full = JSON.stringify({ stage, sessionId: ctx?.sessionManager.getSessionId(), ...facts });
47
+ const line = full.length <= 4096 ? full : JSON.stringify({ stage, truncated: true });
48
+ if (traceSeen.has(line) || traceSeen.size >= 128)
49
+ return;
50
+ const output = traceSeen.size === 127 ? JSON.stringify({ stage: 'capture-limit', limit: 128 }) : line;
51
+ traceSeen.add(line);
52
+ try {
53
+ console.error('[background-handoff-frontend]', output);
54
+ }
55
+ catch { /* diagnostics never own delivery */ }
56
+ };
37
57
  const active = (origin, branch) => Boolean(ctx && origin.cwd === ctx.cwd && origin.sessionId === ctx.sessionManager.getSessionId()
38
58
  && (!branch || ctx.sessionManager.getBranch().some(entry => entry.id === branch)));
39
59
  const request = (tool, params) => {
@@ -55,21 +75,38 @@ export function createManagedBackgroundFrontend(pi) {
55
75
  dirty = false;
56
76
  const captured = ctx, version = generation;
57
77
  refresh = (async () => {
58
- const snapshot = await request('__background_poll', {});
78
+ trace('poll-start');
79
+ const snapshot = await request('__background_poll', { knownActiveIds: rows.filter(row => row.active).map(row => row.id).slice(0, 200) });
80
+ trace('poll-received', { stale: version !== generation, total: snapshot.deliveries?.length ?? 0, deliveries: (snapshot.deliveries ?? []).slice(0, 8).map((item) => ({ taskId: item.notification.taskId, receiptId: item.receiptId })) });
59
81
  if (version !== generation)
60
82
  return;
61
83
  if (snapshot.recoveryPending === true)
62
84
  dirty = true;
63
- rows = snapshot.tasks ?? [];
64
- legacyRows = snapshot.legacyRows ?? [];
85
+ // A rebuilding snapshot is not evidence that visible tasks vanished.
86
+ if (snapshot.status !== 'rebuilding' && snapshot.status !== 'degraded') {
87
+ rows = snapshot.tasks ?? [];
88
+ // Detail remains inspectable while Navigator retains a terminal row.
89
+ for (const task of rows) {
90
+ retainedTasks.delete(task.id);
91
+ retainedTasks.set(task.id, task);
92
+ if (retainedTasks.size > 256)
93
+ retainedTasks.delete(retainedTasks.keys().next().value);
94
+ }
95
+ legacyRows = snapshot.legacyRows ?? [];
96
+ }
65
97
  notify();
66
98
  for (const item of snapshot.deliveries ?? []) {
67
99
  if (queued.has(item.token))
68
100
  continue;
69
101
  queued.add(item.token);
70
- const receipt = (delivered, reason) => void requestBackgroundTool(pi, captured, randomUUID(), '__background_receipt', { token: item.token, delivered, reason })
71
- .catch(() => undefined).finally(() => { queued.delete(item.token); if (ctx === captured)
72
- void reconcile().catch(() => undefined); });
102
+ const facts = { taskId: item.notification.taskId, receiptId: item.receiptId };
103
+ const receipt = (delivered, reason) => {
104
+ trace('handoff', { ...facts, delivered, reason: reason?.slice(0, 256) });
105
+ void requestBackgroundTool(pi, captured, randomUUID(), '__background_receipt', { token: item.token, delivered, reason })
106
+ .then(() => trace('receipt-return', facts), error => trace('receipt-error', { ...facts, error: String(error).slice(0, 256) }))
107
+ .finally(() => { queued.delete(item.token); if (ctx === captured)
108
+ void reconcile().catch(() => undefined); });
109
+ };
73
110
  const proof = captured.sessionManager.getBranch().some((entry) => {
74
111
  const message = entry.type === 'custom_message' ? entry : entry.message;
75
112
  return item.notification.urgent ? message?.customType === item.notification.event.customType && message.details?.urgentEventId === item.receiptId : message?.customType === 'background-completion-batch' && message.details?.completionEventIds?.includes(item.receiptId);
@@ -79,6 +116,7 @@ export function createManagedBackgroundFrontend(pi) {
79
116
  continue;
80
117
  }
81
118
  const n = item.notification;
119
+ trace('queue', { ...facts, urgent: n.urgent === true, recipientActive: active(n.origin, n.branchId) });
82
120
  if (n.urgent) {
83
121
  void getCallbackBatcher(pi).deliverUrgent({ ...n.event, receiptId: item.receiptId, getSuppressionReason: () => active(n.origin, n.branchId) ? undefined : 'The originating session or branch is no longer active', onDelivered: () => receipt(true), onSuppressed: (reason) => receipt(false, reason) });
84
122
  continue;
@@ -88,22 +126,37 @@ export function createManagedBackgroundFrontend(pi) {
88
126
  getSuppressionReason: () => active(n.origin, n.branchId) ? undefined : 'The originating session or branch is no longer active',
89
127
  onDelivered: () => receipt(true), onSuppressed: (reason) => receipt(false, reason) });
90
128
  }
91
- })().finally(() => { refresh = undefined; if (dirty && ctx)
129
+ })().catch(error => { trace('poll-error', { error: String(error).slice(0, 256) }); throw error; })
130
+ .finally(() => { refresh = undefined; if (dirty && ctx)
92
131
  void reconcile().catch(() => undefined); });
93
132
  return refresh;
94
133
  };
134
+ const activate = () => {
135
+ if (observing || !ctx)
136
+ return;
137
+ observing = true;
138
+ const version = generation;
139
+ void reconcile().catch(() => { if (generation === version)
140
+ observing = false; });
141
+ };
95
142
  const host = {
96
143
  async reconcileNow() { await reconcile(); while (refresh)
97
144
  await refresh; },
98
- start(context) { adoptContext(context); generation++; void reconcile().catch(() => undefined); },
145
+ start(context, restore = true) {
146
+ adoptContext(context);
147
+ generation++;
148
+ observing = false;
149
+ if (restore)
150
+ activate();
151
+ },
99
152
  noteParentContext(context) { adoptContext(context); generation++; void reconcile().catch(() => undefined); },
100
- close() { ctx = undefined; adoptedScope = undefined; generation++; rows = []; legacyRows = []; details.clear(); logs.clear(); queued.clear(); ownership.clear(); },
153
+ close() { observing = false; ctx = undefined; adoptedScope = undefined; generation++; rows = []; legacyRows = []; details.clear(); logs.clear(); retainedTasks.clear(); queued.clear(); ownership.clear(); },
101
154
  isParentOriginActive: active,
102
155
  onDurableTaskChange(listener) { listeners.add(listener); return () => listeners.delete(listener); },
103
- listDurableTasks(origin, options = {}) { return active(origin) ? rows.filter(row => !options.retentionMs || !row.terminal || Date.now() - (row.endedAt ?? Date.now()) < options.retentionMs) : []; },
104
- readDurableTask(origin, id) { return active(origin) ? rows.find(row => row.id === id) : undefined; },
156
+ listDurableTasks(origin, _options = {}) { return active(origin) ? rows : []; },
157
+ readDurableTask(origin, id) { const task = cachedTask(id); return active(origin, task?.parentRecipient?.branchId) ? task : undefined; },
105
158
  ownsDurableTask(id) { if (!ctx || adoptedScope !== scopeOf(ctx))
106
- return false; return ownership.has(id) || rows.some(row => row.id === id); },
159
+ return false; return ownership.has(id) || rows.some(row => row.id === id && !row.readOnly); },
107
160
  readDurableTaskLog(origin, id, lines = 40) {
108
161
  if (!active(origin))
109
162
  return;
@@ -135,7 +188,10 @@ export function createManagedBackgroundFrontend(pi) {
135
188
  throw new Error('Native Background context unavailable');
136
189
  adoptContext(context);
137
190
  const capturedGeneration = generation, capturedScope = adoptedScope;
138
- const result = await requestBackgroundTool(pi, context, id, definition.name, params, definition.parameters, signal);
191
+ const launch = () => requestBackgroundTool(pi, context, id, definition.name, params, definition.parameters, signal);
192
+ const spawning = ['bg_task_spawn', 'bg_task_spawn_batch', 'bg_task_watch'].includes(definition.name)
193
+ || definition.name === 'bg_task' && ['spawn', 'watch'].includes(params?.action);
194
+ const result = spawning ? await observeNavigatorLaunch(context, 'background-tasks', id, params?.name || 'Background task launch', launch) : await launch();
139
195
  if (ctx === context && generation === capturedGeneration && adoptedScope === capturedScope)
140
196
  rememberOwnership(result.details?.backgroundOwnership, context);
141
197
  await host.reconcileNow().catch(() => undefined);
@@ -146,10 +202,11 @@ export function createManagedBackgroundFrontend(pi) {
146
202
  } });
147
203
  registerObservedWaitClient(proxy, host);
148
204
  const ui = {
149
- rows: () => legacyRows.filter(row => !row.expiresAt || row.expiresAt > Date.now()),
205
+ onOpen: activate,
206
+ rows: () => legacyRows,
150
207
  prepareDetail(id, options) {
151
208
  const lines = options?.logTailLines ?? 40, key = `${id}:${lines}`;
152
- const durable = rows.some(row => row.id === id), cache = durable ? logs : details;
209
+ const durable = Boolean(cachedTask(id)), cache = durable ? logs : details;
153
210
  const version = generation;
154
211
  if (cache.has(key))
155
212
  return;
@@ -161,7 +218,8 @@ export function createManagedBackgroundFrontend(pi) {
161
218
  cache.delete(key); });
162
219
  },
163
220
  detail(id, now, options) { return details.get(`${id}:${options?.logTailLines ?? 40}`) ?? null; },
164
- close(id) { void request('__background_action', { id, action: rows.find(row => row.id === id)?.active || legacyRows.find(row => row.id === id)?.status === 'running' ? 'stop' : 'dismiss' }).then(() => reconcile()).catch(() => undefined); return { action: 'requested', providerId: 'background-tasks', id }; }
221
+ close(id) { if (cachedTask(id)?.readOnly)
222
+ return { action: 'not-closable', providerId: 'background-tasks', id }; void request('__background_action', { id, action: rows.find(row => row.id === id)?.active || legacyRows.find(row => row.id === id)?.status === 'running' ? 'stop' : 'dismiss' }).then(() => reconcile()).catch(() => undefined); return { action: 'requested', providerId: 'background-tasks', id }; }
165
223
  };
166
224
  return { host, proxy, ui };
167
225
  }
@@ -4,17 +4,22 @@ import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-a
4
4
  import { requestBackgroundTool } from './managed-client.js';
5
5
  import { onBackgroundObservation } from './work-observation.js';
6
6
  import { getCallbackBatcher } from './shared-callback-batcher.js';
7
- import { registerObservedWaitClient, type ObservedWaitHost } from './observed-waits.js';
7
+ import { registerObservedWaitClient } from "./observed-wait-client.js";
8
+ import type { ObservedWaitHost } from "./observed-waits.js";
9
+ import { observeNavigatorLaunch } from './shared-navigator.ts';
8
10
  /** Native transcript delivery and cached UI projections; no coordinator or supervisor. */
9
11
  export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
10
12
  let ctx: ExtensionContext | undefined, generation = 0, refresh: Promise<void> | undefined, dirty=false;
11
13
  let rows: any[] = [], legacyRows: any[] = [], details = new Map<string, any>(), logs = new Map<string, any>();
14
+ const retainedTasks = new Map<string, any>();
15
+ const cachedTask = (id: string) => rows.find(row => row.id === id) ?? retainedTasks.get(id);
12
16
  let adoptedScope: string | undefined;
17
+ let observing = false;
13
18
  const scopeOf = (context: ExtensionContext) => JSON.stringify([context.cwd, context.sessionManager.getSessionId()]);
14
19
  const ownership = new Map<string, { operationId: string; owner: { kind: string; sessionId: string; workspace: string } }>();
15
20
  const adoptContext = (context: ExtensionContext) => {
16
21
  if (adoptedScope !== undefined && adoptedScope !== scopeOf(context)) {
17
- ownership.clear(); rows = []; legacyRows = []; details.clear(); logs.clear(); generation++;
22
+ ownership.clear(); rows = []; legacyRows = []; details.clear(); logs.clear(); retainedTasks.clear(); generation++;
18
23
  }
19
24
  ctx = context; adoptedScope = scopeOf(context);
20
25
  };
@@ -26,6 +31,16 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
26
31
  if (ownership.size > 256) ownership.delete(ownership.keys().next().value!);
27
32
  };
28
33
  const queued = new Set<string>(), listeners = new Set<(change: any) => void>();
34
+ const traceSeen = new Set<string>();
35
+ const trace = (stage: string, facts: Record<string, unknown> = {}) => {
36
+ if (process.env.PI_BG_OBSERVED_WAITS_DEBUG !== '1') return;
37
+ const full = JSON.stringify({ stage, sessionId: ctx?.sessionManager.getSessionId(), ...facts });
38
+ const line = full.length <= 4096 ? full : JSON.stringify({ stage, truncated: true });
39
+ if (traceSeen.has(line) || traceSeen.size >= 128) return;
40
+ const output = traceSeen.size === 127 ? JSON.stringify({ stage: 'capture-limit', limit: 128 }) : line;
41
+ traceSeen.add(line);
42
+ try { console.error('[background-handoff-frontend]', output); } catch { /* diagnostics never own delivery */ }
43
+ };
29
44
  const active = (origin: any, branch?: string | null) => Boolean(ctx && origin.cwd === ctx.cwd && origin.sessionId === ctx.sessionManager.getSessionId()
30
45
  && (!branch || ctx.sessionManager.getBranch().some(entry => entry.id === branch)));
31
46
  const request = (tool: string, params: any) => {
@@ -42,19 +57,34 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
42
57
  dirty=false;
43
58
  const captured = ctx, version = generation;
44
59
  refresh = (async () => {
45
- const snapshot = await request('__background_poll', {});
60
+ trace('poll-start');
61
+ const snapshot = await request('__background_poll', { knownActiveIds: rows.filter(row => row.active).map(row => row.id).slice(0, 200) });
62
+ trace('poll-received', { stale: version !== generation, total: snapshot.deliveries?.length ?? 0, deliveries: (snapshot.deliveries ?? []).slice(0, 8).map((item: any) => ({ taskId: item.notification.taskId, receiptId: item.receiptId })) });
46
63
  if (version !== generation)
47
64
  return;
48
65
  if (snapshot.recoveryPending === true) dirty = true;
49
- rows = snapshot.tasks ?? [];
50
- legacyRows = snapshot.legacyRows ?? [];
66
+ // A rebuilding snapshot is not evidence that visible tasks vanished.
67
+ if (snapshot.status !== 'rebuilding' && snapshot.status !== 'degraded') {
68
+ rows = snapshot.tasks ?? [];
69
+ // Detail remains inspectable while Navigator retains a terminal row.
70
+ for (const task of rows) {
71
+ retainedTasks.delete(task.id); retainedTasks.set(task.id, task);
72
+ if (retainedTasks.size > 256) retainedTasks.delete(retainedTasks.keys().next().value!);
73
+ }
74
+ legacyRows = snapshot.legacyRows ?? [];
75
+ }
51
76
  notify();
52
77
  for (const item of snapshot.deliveries ?? []) {
53
78
  if (queued.has(item.token))
54
79
  continue;
55
80
  queued.add(item.token);
56
- const receipt = (delivered: boolean, reason?: string) => void requestBackgroundTool(pi, captured, randomUUID(), '__background_receipt', { token: item.token, delivered, reason })
57
- .catch(() => undefined).finally(() => {queued.delete(item.token);if(ctx===captured)void reconcile().catch(()=>undefined);});
81
+ const facts = { taskId: item.notification.taskId, receiptId: item.receiptId };
82
+ const receipt = (delivered: boolean, reason?: string) => {
83
+ trace('handoff', { ...facts, delivered, reason: reason?.slice(0, 256) });
84
+ void requestBackgroundTool(pi, captured, randomUUID(), '__background_receipt', { token: item.token, delivered, reason })
85
+ .then(() => trace('receipt-return', facts), error => trace('receipt-error', { ...facts, error: String(error).slice(0, 256) }))
86
+ .finally(() => {queued.delete(item.token);if(ctx===captured)void reconcile().catch(()=>undefined);});
87
+ };
58
88
  const proof = captured.sessionManager.getBranch().some((entry: any) => {
59
89
  const message = entry.type === 'custom_message' ? entry : entry.message;
60
90
  return item.notification.urgent ? message?.customType===item.notification.event.customType&&message.details?.urgentEventId===item.receiptId : message?.customType === 'background-completion-batch' && message.details?.completionEventIds?.includes(item.receiptId);
@@ -64,25 +94,36 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
64
94
  continue;
65
95
  }
66
96
  const n = item.notification;
97
+ trace('queue', { ...facts, urgent: n.urgent === true, recipientActive: active(n.origin, n.branchId) });
67
98
  if(n.urgent){void getCallbackBatcher(pi).deliverUrgent({...n.event,receiptId:item.receiptId,getSuppressionReason:()=>active(n.origin,n.branchId)?undefined:'The originating session or branch is no longer active',onDelivered:()=>receipt(true),onSuppressed:(reason)=>receipt(false,reason)});continue;}
68
99
  getCallbackBatcher(pi).enqueue({ ...n.event, source: 'background-task', id: n.taskId, label: n.taskId, status: n.waitId ? `${n.status}; wait ${n.waitId} ready` : n.status,
69
100
  detailTool: 'bg_task_status', outcome: n.outcome, callback: true, receiptId: item.receiptId,
70
101
  getSuppressionReason: () => active(n.origin, n.branchId) ? undefined : 'The originating session or branch is no longer active',
71
102
  onDelivered: () => receipt(true), onSuppressed: (reason) => receipt(false, reason) });
72
103
  }
73
- })().finally(() => { refresh = undefined;if(dirty&&ctx)void reconcile().catch(()=>undefined); });
104
+ })().catch(error => { trace('poll-error', { error: String(error).slice(0, 256) }); throw error; })
105
+ .finally(() => { refresh = undefined;if(dirty&&ctx)void reconcile().catch(()=>undefined); });
74
106
  return refresh;
75
107
  };
108
+ const activate = () => {
109
+ if (observing || !ctx) return;
110
+ observing = true;
111
+ const version = generation;
112
+ void reconcile().catch(() => { if (generation === version) observing = false; });
113
+ };
76
114
  const host = {
77
115
  async reconcileNow() { await reconcile(); while (refresh) await refresh; },
78
- start(context: ExtensionContext) { adoptContext(context); generation++; void reconcile().catch(() => undefined); },
116
+ start(context: ExtensionContext, restore = true) {
117
+ adoptContext(context); generation++; observing = false;
118
+ if (restore) activate();
119
+ },
79
120
  noteParentContext(context: ExtensionContext) { adoptContext(context); generation++; void reconcile().catch(() => undefined); },
80
- close() { ctx = undefined; adoptedScope = undefined; generation++; rows = []; legacyRows = []; details.clear(); logs.clear(); queued.clear(); ownership.clear(); },
121
+ close() { observing = false; ctx = undefined; adoptedScope = undefined; generation++; rows = []; legacyRows = []; details.clear(); logs.clear(); retainedTasks.clear(); queued.clear(); ownership.clear(); },
81
122
  isParentOriginActive: active,
82
123
  onDurableTaskChange(listener: (change: any) => void) { listeners.add(listener); return () => listeners.delete(listener); },
83
- listDurableTasks(origin: any, options: any = {}) { return active(origin) ? rows.filter(row => !options.retentionMs || !row.terminal || Date.now() - (row.endedAt ?? Date.now()) < options.retentionMs) : []; },
84
- readDurableTask(origin: any, id: string) { return active(origin) ? rows.find(row => row.id === id) : undefined; },
85
- ownsDurableTask(id: string) { if (!ctx || adoptedScope !== scopeOf(ctx)) return false; return ownership.has(id) || rows.some(row => row.id === id); },
124
+ listDurableTasks(origin: any, _options: any = {}) { return active(origin) ? rows : []; },
125
+ readDurableTask(origin: any, id: string) { const task = cachedTask(id); return active(origin, task?.parentRecipient?.branchId) ? task : undefined; },
126
+ ownsDurableTask(id: string) { if (!ctx || adoptedScope !== scopeOf(ctx)) return false; return ownership.has(id) || rows.some(row => row.id === id && !row.readOnly); },
86
127
  readDurableTaskLog(origin: any, id: string, lines = 40) {
87
128
  if (!active(origin))
88
129
  return;
@@ -104,7 +145,10 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
104
145
  throw new Error('Native Background context unavailable');
105
146
  adoptContext(context);
106
147
  const capturedGeneration = generation, capturedScope = adoptedScope;
107
- const result = await requestBackgroundTool(pi, context, id, definition.name, params, definition.parameters, signal);
148
+ const launch = () => requestBackgroundTool(pi, context, id, definition.name, params, definition.parameters, signal);
149
+ const spawning = ['bg_task_spawn', 'bg_task_spawn_batch', 'bg_task_watch'].includes(definition.name)
150
+ || definition.name === 'bg_task' && ['spawn', 'watch'].includes(params?.action);
151
+ const result = spawning ? await observeNavigatorLaunch(context, 'background-tasks', id, params?.name || 'Background task launch', launch) : await launch();
108
152
  if (ctx === context && generation === capturedGeneration && adoptedScope === capturedScope) rememberOwnership(result.details?.backgroundOwnership, context);
109
153
  await host.reconcileNow().catch(() => undefined);
110
154
  return result;
@@ -114,10 +158,11 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
114
158
  } });
115
159
  registerObservedWaitClient(proxy, host as unknown as ObservedWaitHost);
116
160
  const ui: ManagedBackgroundNavigator = {
117
- rows: () => legacyRows.filter(row => !row.expiresAt || row.expiresAt > Date.now()),
161
+ onOpen: activate,
162
+ rows: () => legacyRows,
118
163
  prepareDetail(id, options) {
119
164
  const lines = options?.logTailLines ?? 40, key = `${id}:${lines}`;
120
- const durable = rows.some(row => row.id === id), cache = durable ? logs : details;
165
+ const durable = Boolean(cachedTask(id)), cache = durable ? logs : details;
121
166
  const version=generation;
122
167
  if (cache.has(key))
123
168
  return;
@@ -125,7 +170,7 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
125
170
  void request(durable ? '__background_log' : '__background_detail', { id, lines }).then(value => { if(version===generation){cache.set(key, value); notify();} }, () => {if(version===generation)cache.delete(key);});
126
171
  },
127
172
  detail(id, now, options) { return details.get(`${id}:${options?.logTailLines ?? 40}`) ?? null; },
128
- close(id) { void request('__background_action', { id, action: rows.find(row => row.id === id)?.active || legacyRows.find(row => row.id === id)?.status === 'running' ? 'stop' : 'dismiss' }).then(() => reconcile()).catch(() => undefined); return { action: 'requested', providerId: 'background-tasks', id }; }
173
+ close(id) { if (cachedTask(id)?.readOnly) return {action: 'not-closable', providerId: 'background-tasks', id}; void request('__background_action', { id, action: rows.find(row => row.id === id)?.active || legacyRows.find(row => row.id === id)?.status === 'running' ? 'stop' : 'dismiss' }).then(() => reconcile()).catch(() => undefined); return { action: 'requested', providerId: 'background-tasks', id }; }
129
174
  };
130
175
  return { host, proxy, ui };
131
176
  }
@@ -6,13 +6,12 @@ import { actionableFailures, failureLabel, readFailureState } from "./shared-fai
6
6
  import { failurePath, failureView } from "./failures.domain.mjs";
7
7
  import { readLog } from "./logs.domain.mjs";
8
8
  import { listMetasForOrigin, onMetaChanged, readMeta, writeMeta } from "./registry.domain.mjs";
9
- import { getObservedWaitHost } from "./observed-waits.domain.mjs";
10
- import { stopTask } from "./runtime.domain.mjs";
9
+ import { getObservedWaitHost } from "./observed-wait-client.domain.mjs";
11
10
  import { formatBackgroundTaskStall, observeBackgroundTaskStall } from "./stall.domain.mjs";
12
11
  const TERMINAL_NAVIGATOR_RETENTION_MS = 30_000;
13
12
  const DURABLE_ROW_CACHE_MS = 1_000;
14
13
  let durableRowCache;
15
- export function createBackgroundTasksNavigator(runtime = { stopTask }, managed) {
14
+ export function createBackgroundTasksNavigator(runtime, managed) {
16
15
  const owner = Symbol("background-tasks navigator factory");
17
16
  let unregister;
18
17
  let navigatorContext;
@@ -74,6 +73,7 @@ export function createBackgroundTasksNavigator(runtime = { stopTask }, managed)
74
73
  id: "background-tasks",
75
74
  label: "Background Tasks",
76
75
  priority: 20,
76
+ onOpen: managed?.onOpen,
77
77
  visibleCount: () => {
78
78
  const now = Date.now();
79
79
  return (managed ? managed.rows().filter(row => row.status === "running").length : visibleMetas(now).filter((meta) => meta.status === "running").length)
@@ -92,9 +92,13 @@ export function createBackgroundTasksNavigator(runtime = { stopTask }, managed)
92
92
  },
93
93
  armCloseLabel: (row) => row.status === "running" || row.status === "starting" ? "x again to stop" : "x again to dismiss",
94
94
  close: (id) => {
95
+ if (durableTask(id)?.readOnly)
96
+ return { action: "not-closable", providerId: "background-tasks", id };
95
97
  if (managed)
96
98
  return managed.close(id);
97
99
  const durable = durableTask(id);
100
+ if (durable?.readOnly)
101
+ return { action: "not-closable", providerId: "background-tasks", id };
98
102
  if (durable) {
99
103
  const host = navigatorHost();
100
104
  const origin = activeNavigatorOrigin;
@@ -113,7 +117,11 @@ export function createBackgroundTasksNavigator(runtime = { stopTask }, managed)
113
117
  if (!meta)
114
118
  return { action: "missing", providerId: "background-tasks", id };
115
119
  if (meta.status === "running") {
116
- void runtime.stopTask(piRef, id);
120
+ const pi = piRef;
121
+ if (runtime)
122
+ void runtime.stopTask(pi, id);
123
+ else
124
+ void import("./runtime.domain.mjs").then(({ stopTask }) => stopTask(pi, id));
117
125
  return { action: "stopped", providerId: "background-tasks", id, status: "stopping" };
118
126
  }
119
127
  meta.dismissedAt = Date.now();
@@ -180,6 +188,8 @@ export function createBackgroundTasksNavigator(runtime = { stopTask }, managed)
180
188
  return {
181
189
  providerId: "background-tasks",
182
190
  id: task.id,
191
+ parentAgentId: task.parentAgentId,
192
+ readOnly: task.readOnly,
183
193
  name: task.name,
184
194
  status: task.status,
185
195
  statusTone: toneForDurableStatus(task.status),
@@ -204,6 +214,7 @@ export function createBackgroundTasksNavigator(runtime = { stopTask }, managed)
204
214
  const metadata = [
205
215
  { label: "provider", value: "Background Tasks (durable)" },
206
216
  { label: "kind", value: task.kind },
217
+ ...(task.parentAgentId ? [{ label: "agent", value: task.parentAgentId }] : []),
207
218
  { label: "operation", value: task.operationId },
208
219
  { label: "status", value: `${task.status}${task.terminalOutcome ? ` (${task.terminalOutcome})` : ""}` },
209
220
  { label: "started", value: new Date(task.startedAt).toISOString() },
@@ -242,7 +253,7 @@ export function createBackgroundTasksNavigator(runtime = { stopTask }, managed)
242
253
  label: log?.truncated ? "log tail" : "log",
243
254
  text: evidenceText,
244
255
  },
245
- footerActions: [task.active ? "x stop" : "x dismiss"],
256
+ footerActions: task.readOnly ? ["Managed by owning agent"] : [task.active ? "x stop" : "x dismiss"],
246
257
  };
247
258
  }
248
259
  function durableCommandLabel(task) {