pi-better-server 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (278) hide show
  1. package/package.json +4 -1
  2. package/scripts/copy-pi-test-providers.mjs +10 -0
  3. package/scripts/event-publication/README.md +26 -0
  4. package/scripts/event-publication/commit.mjs +21 -0
  5. package/scripts/event-publication/measure.mjs +37 -5
  6. package/scripts/event-publication/writer.mjs +3 -8
  7. package/scripts/measure-full-runtime/probe.mjs +4 -2
  8. package/scripts/measure-full-runtime/recovery-trace-loader.mjs +51 -0
  9. package/scripts/measure-full-runtime/recovery-trace.mjs +16 -0
  10. package/scripts/measure-shared-reads.mjs +2 -1
  11. package/scripts/private-runtime/package-lock.json +18 -0
  12. package/scripts/private-runtime/package.json +4 -1
  13. package/scripts/source-provenance.mjs +2 -2
  14. package/scripts/test-on-pi.sh +2 -9
  15. package/src/handshake.ts +1 -1
  16. package/src/hosted-session.ts +32 -4
  17. package/src/maintenance.ts +35 -7
  18. package/src/registry.ts +28 -4
  19. package/src/runtime/attempt-invalidation.ts +54 -0
  20. package/src/runtime/background-history.ts +151 -45
  21. package/src/runtime/background-policy.ts +9 -4
  22. package/src/runtime/background-tools.ts +131 -23
  23. package/src/runtime/background.ts +351 -68
  24. package/src/runtime/cancellation.ts +28 -7
  25. package/src/runtime/catalog-sources.ts +199 -0
  26. package/src/runtime/catalog.ts +53 -21
  27. package/src/runtime/client.ts +22 -2
  28. package/src/runtime/domain/assignment-inbox.mjs +119 -0
  29. package/src/runtime/domain/assignment-observation.d.mts +1 -1
  30. package/src/runtime/domain/assignment-observation.mjs +43 -35
  31. package/src/runtime/domain/background/process-identity.mjs +20 -2
  32. package/src/runtime/domain/background/process.mjs +3 -3
  33. package/src/runtime/domain/background/registry.mjs +61 -3
  34. package/src/runtime/domain/background/types.mjs +1 -0
  35. package/src/runtime/domain/background-service/adapter-contract.domain.mjs +1 -1
  36. package/src/runtime/domain/background-service/adapter-contract.ts +1 -1
  37. package/src/runtime/domain/background-service/goal-provider.domain.mjs +35 -16
  38. package/src/runtime/domain/background-service/goal-provider.ts +31 -16
  39. package/src/runtime/domain/background-service/index.domain.mjs +6 -9
  40. package/src/runtime/domain/background-service/index.ts +6 -9
  41. package/src/runtime/domain/background-service/managed-authority.domain.mjs +6 -3
  42. package/src/runtime/domain/background-service/managed-authority.ts +5 -3
  43. package/src/runtime/domain/background-service/managed-client.domain.mjs +21 -7
  44. package/src/runtime/domain/background-service/managed-client.ts +20 -7
  45. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +75 -17
  46. package/src/runtime/domain/background-service/managed-frontend.ts +62 -17
  47. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +16 -5
  48. package/src/runtime/domain/background-service/navigator-provider.ts +15 -5
  49. package/src/runtime/domain/background-service/observed-wait-client.domain.mjs +6 -0
  50. package/src/runtime/domain/background-service/observed-wait-client.ts +10 -0
  51. package/src/runtime/domain/background-service/observed-waits.domain.mjs +170 -27
  52. package/src/runtime/domain/background-service/observed-waits.ts +154 -30
  53. package/src/runtime/domain/background-service/process-identity.domain.mjs +20 -2
  54. package/src/runtime/domain/background-service/process-identity.ts +18 -2
  55. package/src/runtime/domain/background-service/process.domain.mjs +3 -3
  56. package/src/runtime/domain/background-service/process.ts +3 -3
  57. package/src/runtime/domain/background-service/registry.domain.mjs +61 -3
  58. package/src/runtime/domain/background-service/registry.ts +53 -5
  59. package/src/runtime/domain/background-service/runtime.domain.mjs +32 -16
  60. package/src/runtime/domain/background-service/runtime.ts +19 -9
  61. package/src/runtime/domain/background-service/sandbox.domain.mjs +14 -15
  62. package/src/runtime/domain/background-service/sandbox.ts +14 -11
  63. package/src/runtime/domain/background-service/shared-callback-batcher.domain.mjs +8 -1
  64. package/src/runtime/domain/background-service/shared-callback-batcher.ts +11 -2
  65. package/src/runtime/domain/background-service/shared-navigator-panels.domain.mjs +24 -2
  66. package/src/runtime/domain/background-service/shared-navigator-panels.ts +26 -4
  67. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +218 -13
  68. package/src/runtime/domain/background-service/shared-navigator.ts +197 -14
  69. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  70. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +53 -41
  71. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  72. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  73. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
  74. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  75. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
  76. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.ts +14 -3
  77. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
  78. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +5 -3
  79. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +44 -4
  80. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +50 -2
  81. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
  82. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +12 -0
  83. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.domain.mjs +2 -0
  84. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.ts +2 -0
  85. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +42 -21
  86. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +40 -24
  87. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +21 -3
  88. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +34 -8
  89. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
  90. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  91. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.domain.mjs +1 -1
  92. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.ts +5 -1
  93. package/src/runtime/domain/background-service/shared-sandbox-core.ts +1 -1
  94. package/src/runtime/domain/background-service/shared-work-client.mjs +174 -7
  95. package/src/runtime/domain/background-service/supervisor/generated/process-identity.mjs +20 -2
  96. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +3 -3
  97. package/src/runtime/domain/background-service/task-diagnostics.domain.mjs +1 -1
  98. package/src/runtime/domain/background-service/task-diagnostics.ts +1 -1
  99. package/src/runtime/domain/background-service/tools.domain.mjs +31 -24
  100. package/src/runtime/domain/background-service/tools.ts +41 -38
  101. package/src/runtime/domain/background-service/types.domain.mjs +1 -0
  102. package/src/runtime/domain/background-service/types.ts +3 -1
  103. package/src/runtime/domain/background-service/work-observation.domain.mjs +46 -20
  104. package/src/runtime/domain/background-service/work-observation.ts +46 -19
  105. package/src/runtime/domain/catalog/catalog-store.d.mts +9 -1
  106. package/src/runtime/domain/catalog/catalog-store.mjs +20 -22
  107. package/src/runtime/domain/coordinator/src/assignment-changes.mjs +75 -0
  108. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +2 -0
  109. package/src/runtime/domain/coordinator/src/background-requests.mjs +11 -2
  110. package/src/runtime/domain/coordinator/src/discovery.mjs +4 -2
  111. package/src/runtime/domain/coordinator/src/operations.mjs +44 -4
  112. package/src/runtime/domain/coordinator/src/result-supervision.mjs +12 -0
  113. package/src/runtime/domain/coordinator/src/rows.mjs +2 -0
  114. package/src/runtime/domain/coordinator/src/schema.mjs +42 -21
  115. package/src/runtime/domain/coordinator/src/store.mjs +21 -3
  116. package/src/runtime/domain/coordinator/src/subagent-launch.mjs +23 -1
  117. package/src/runtime/domain/coordinator/src/types.mjs +1 -1
  118. package/src/runtime/domain/health-observation.d.mts +3 -1
  119. package/src/runtime/domain/health-observation.mjs +189 -190
  120. package/src/runtime/domain/log-cursor.d.mts +2 -0
  121. package/src/runtime/domain/log-cursor.mjs +85 -16
  122. package/src/runtime/domain/parse.d.mts +4 -1
  123. package/src/runtime/domain/parse.mjs +50 -5
  124. package/src/runtime/domain/sandbox-policy/README.md +61 -63
  125. package/src/runtime/domain/sandbox-policy/commands.domain.mjs +11 -8
  126. package/src/runtime/domain/sandbox-policy/commands.ts +12 -7
  127. package/src/runtime/domain/sandbox-policy/index.domain.mjs +53 -9
  128. package/src/runtime/domain/sandbox-policy/index.ts +52 -9
  129. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  130. package/src/runtime/domain/sandbox-policy/permission-settings.domain.mjs +5 -2
  131. package/src/runtime/domain/sandbox-policy/permission-settings.ts +9 -2
  132. package/src/runtime/domain/sandbox-policy/permissions-page.domain.mjs +56 -137
  133. package/src/runtime/domain/sandbox-policy/permissions-page.ts +52 -130
  134. package/src/runtime/domain/sandbox-policy/permissions.domain.mjs +1 -6
  135. package/src/runtime/domain/sandbox-policy/permissions.ts +1 -6
  136. package/src/runtime/domain/sandbox-policy/shared-sandbox-core.ts +1 -1
  137. package/src/runtime/domain/sandbox-policy/shared-task-exec.domain.mjs +14 -1
  138. package/src/runtime/domain/sandbox-policy/shared-task-exec.ts +12 -1
  139. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.domain.mjs +140 -0
  140. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.ts +126 -0
  141. package/src/runtime/domain/sandbox-policy/shared-task-process-list.domain.mjs +3 -2
  142. package/src/runtime/domain/sandbox-policy/shared-task-process-list.ts +8 -2
  143. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.domain.mjs +4 -3
  144. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.ts +5 -3
  145. package/src/runtime/domain/sandbox-policy/shared-task-tools.domain.mjs +8 -5
  146. package/src/runtime/domain/sandbox-policy/shared-task-tools.ts +8 -5
  147. package/src/runtime/domain/subagents/README.md +1 -1
  148. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +12 -6
  149. package/src/runtime/domain/subagents/assignment-outcomes.ts +11 -5
  150. package/src/runtime/domain/subagents/assignment-report.domain.mjs +87 -24
  151. package/src/runtime/domain/subagents/assignment-report.ts +83 -19
  152. package/src/runtime/domain/subagents/catalog-host-admission.domain.mjs +21 -3
  153. package/src/runtime/domain/subagents/catalog-host-admission.ts +19 -3
  154. package/src/runtime/domain/subagents/catalog-preferences.ts +1 -1
  155. package/src/runtime/domain/subagents/catalog-resolver.domain.mjs +35 -1
  156. package/src/runtime/domain/subagents/catalog-resolver.ts +35 -1
  157. package/src/runtime/domain/subagents/catalog-store.domain.mjs +20 -22
  158. package/src/runtime/domain/subagents/catalog-store.ts +27 -20
  159. package/src/runtime/domain/subagents/child-apply-patch.domain.mjs +13 -0
  160. package/src/runtime/domain/subagents/child-apply-patch.ts +13 -0
  161. package/src/runtime/domain/subagents/child-dependencies.mjs +27 -15
  162. package/src/runtime/domain/subagents/child-operations.domain.mjs +80 -2
  163. package/src/runtime/domain/subagents/child-operations.ts +80 -1
  164. package/src/runtime/domain/subagents/child-preflight.mjs +9 -2
  165. package/src/runtime/domain/subagents/child-process-list.domain.mjs +7 -0
  166. package/src/runtime/domain/subagents/child-process-list.ts +8 -0
  167. package/src/runtime/domain/subagents/config.domain.mjs +49 -2
  168. package/src/runtime/domain/subagents/config.ts +46 -2
  169. package/src/runtime/domain/subagents/continuation-authority.domain.mjs +5 -1
  170. package/src/runtime/domain/subagents/continuation-authority.ts +3 -1
  171. package/src/runtime/domain/subagents/continuation-runtime.domain.mjs +89 -0
  172. package/src/runtime/domain/subagents/continuation-runtime.ts +88 -0
  173. package/src/runtime/domain/subagents/extensions.mjs +11 -13
  174. package/src/runtime/domain/subagents/finalization.domain.mjs +12 -0
  175. package/src/runtime/domain/subagents/finalization.ts +15 -0
  176. package/src/runtime/domain/subagents/goal-provider.domain.mjs +44 -2
  177. package/src/runtime/domain/subagents/goal-provider.ts +44 -2
  178. package/src/runtime/domain/subagents/health-observation.domain.mjs +189 -190
  179. package/src/runtime/domain/subagents/health-observation.ts +43 -48
  180. package/src/runtime/domain/subagents/index.domain.mjs +296 -123
  181. package/src/runtime/domain/subagents/index.ts +257 -98
  182. package/src/runtime/domain/subagents/launch-context.domain.mjs +24 -0
  183. package/src/runtime/domain/subagents/launch-context.ts +23 -0
  184. package/src/runtime/domain/subagents/launch-digest.mjs +6 -0
  185. package/src/runtime/domain/subagents/log-cursor.domain.mjs +85 -16
  186. package/src/runtime/domain/subagents/log-cursor.ts +91 -15
  187. package/src/runtime/domain/subagents/managed-launch-bootstrap.mjs +2 -2
  188. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +6 -3
  189. package/src/runtime/domain/subagents/managed-launch-client.ts +6 -3
  190. package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +222 -14
  191. package/src/runtime/domain/subagents/managed-launch-host.ts +168 -15
  192. package/src/runtime/domain/subagents/managed-launch-journal.mjs +1 -5
  193. package/src/runtime/domain/subagents/managed-launch-port.ts +4 -0
  194. package/src/runtime/domain/subagents/operation-bridge-types.domain.mjs +27 -2
  195. package/src/runtime/domain/subagents/operation-bridge-types.ts +27 -2
  196. package/src/runtime/domain/subagents/owned-exit.domain.mjs +12 -0
  197. package/src/runtime/domain/subagents/owned-exit.ts +12 -0
  198. package/src/runtime/domain/subagents/package.json +1 -1
  199. package/src/runtime/domain/subagents/parse.domain.mjs +50 -5
  200. package/src/runtime/domain/subagents/parse.ts +48 -6
  201. package/src/runtime/domain/subagents/permission-policy.domain.mjs +32 -8
  202. package/src/runtime/domain/subagents/permission-policy.ts +41 -8
  203. package/src/runtime/domain/subagents/process-identity.mjs +33 -0
  204. package/src/runtime/domain/subagents/registry.domain.mjs +47 -33
  205. package/src/runtime/domain/subagents/registry.ts +54 -33
  206. package/src/runtime/domain/subagents/shared-callback-batcher.domain.mjs +8 -1
  207. package/src/runtime/domain/subagents/shared-callback-batcher.ts +11 -2
  208. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +6 -23
  209. package/src/runtime/domain/subagents/shared-catalog.ts +6 -14
  210. package/src/runtime/domain/subagents/shared-navigator-panels.domain.mjs +24 -2
  211. package/src/runtime/domain/subagents/shared-navigator-panels.ts +26 -4
  212. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +218 -13
  213. package/src/runtime/domain/subagents/shared-navigator.ts +197 -14
  214. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  215. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +53 -41
  216. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  217. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  218. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
  219. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  220. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
  221. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.ts +14 -3
  222. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
  223. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +5 -3
  224. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +44 -4
  225. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +50 -2
  226. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
  227. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +12 -0
  228. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.domain.mjs +2 -0
  229. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.ts +2 -0
  230. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +42 -21
  231. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +40 -24
  232. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +21 -3
  233. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +34 -8
  234. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
  235. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  236. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.domain.mjs +1 -1
  237. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.ts +5 -1
  238. package/src/runtime/domain/subagents/shared-sandbox-core.ts +1 -1
  239. package/src/runtime/domain/subagents/shared-task-exec.domain.mjs +14 -1
  240. package/src/runtime/domain/subagents/shared-task-exec.ts +12 -1
  241. package/src/runtime/domain/subagents/shared-task-process-identity.domain.mjs +140 -0
  242. package/src/runtime/domain/subagents/shared-task-process-identity.ts +126 -0
  243. package/src/runtime/domain/subagents/shared-task-process-list.domain.mjs +3 -2
  244. package/src/runtime/domain/subagents/shared-task-process-list.ts +8 -2
  245. package/src/runtime/domain/subagents/shared-task-sandbox.domain.mjs +4 -3
  246. package/src/runtime/domain/subagents/shared-task-sandbox.ts +5 -3
  247. package/src/runtime/domain/subagents/shared-task-tools.domain.mjs +8 -5
  248. package/src/runtime/domain/subagents/shared-task-tools.ts +8 -5
  249. package/src/runtime/domain/subagents/shared-work-client.mjs +174 -7
  250. package/src/runtime/domain/subagents/subagent-tools.domain.mjs +22 -38
  251. package/src/runtime/domain/subagents/subagent-tools.ts +28 -34
  252. package/src/runtime/domain/subagents/task-policy.domain.mjs +1 -1
  253. package/src/runtime/domain/subagents/task-policy.ts +3 -1
  254. package/src/runtime/domain/subagents/timing.domain.mjs +10 -1
  255. package/src/runtime/domain/subagents/timing.ts +10 -1
  256. package/src/runtime/domain/subagents/work-observation.domain.mjs +77 -16
  257. package/src/runtime/domain/subagents/work-observation.ts +71 -16
  258. package/src/runtime/domain/subagents/worker-operations-host.domain.mjs +9 -4
  259. package/src/runtime/domain/subagents/worker-operations-host.ts +12 -4
  260. package/src/runtime/domain/subagents/worker-waits.domain.mjs +89 -35
  261. package/src/runtime/domain/subagents/worker-waits.ts +93 -34
  262. package/src/runtime/health-config.ts +27 -11
  263. package/src/runtime/log-checkpoints.ts +117 -0
  264. package/src/runtime/mutation-store.ts +5 -4
  265. package/src/runtime/queries.ts +25 -2
  266. package/src/runtime/query-executor.ts +149 -28
  267. package/src/runtime/query-worker.mjs +106 -21
  268. package/src/runtime/read-model.ts +846 -120
  269. package/src/runtime/read-watchdog-probe.ts +4 -0
  270. package/src/runtime/result-supervision.ts +188 -16
  271. package/src/runtime/source-watch.ts +175 -0
  272. package/src/runtime/subagent-launch.ts +11 -4
  273. package/src/runtime/work-budget.ts +130 -0
  274. package/src/runtime/work-client.d.mts +8 -0
  275. package/src/runtime/work-client.mjs +150 -7
  276. package/src/server.ts +104 -23
  277. package/src/session-activity.ts +26 -4
  278. package/src/version.ts +1 -1
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import { mkdirSync, readFileSync, readdirSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import type { BackgroundTaskCallbackOrigin, BackgroundTaskMeta } from "./types.js";
@@ -11,7 +11,7 @@ const metaCache = new Map<string, BackgroundTaskMeta>();
11
11
  // cross-process index changes before any cached IDs are reused.
12
12
  const indexIdsCache = new Map<string, { ids: Set<string>; signature: string }>();
13
13
  const initializedIndexes = new Set<string>();
14
- const metaChangedListeners = new Set<() => void>();
14
+ const metaChangedListeners = new Set<(meta?: BackgroundTaskMeta) => void>();
15
15
  const registryIo = { fullDirectoryReads: 0, indexDirectoryReads: 0, metadataFileReads: 0, terminalMetadataFileReads: 0, indexRevisionChecks: 0 };
16
16
 
17
17
  export interface RegistryIoMetrics {
@@ -84,11 +84,11 @@ export function writeMeta(meta: BackgroundTaskMeta): void {
84
84
  metaCache.set(meta.id, meta);
85
85
  indexMeta(meta);
86
86
  for (const listener of metaChangedListeners) {
87
- try { listener(); } catch { /* best effort */ }
87
+ try { listener(meta); } catch { /* best effort */ }
88
88
  }
89
89
  }
90
90
 
91
- export function onMetaChanged(listener: () => void): () => void {
91
+ export function onMetaChanged(listener: (meta?: BackgroundTaskMeta) => void): () => void {
92
92
  metaChangedListeners.add(listener);
93
93
  return () => metaChangedListeners.delete(listener);
94
94
  }
@@ -190,8 +190,9 @@ export function removeMeta(meta: BackgroundTaskMeta): boolean {
190
190
  metaCache.delete(meta.id);
191
191
  removeIndexEntry(originIndexDir(originOf(meta)), meta.id);
192
192
  removeIndexEntry(originActiveIndexDir(originOf(meta)), meta.id);
193
+ removeIndexEntry(recentPath(originOf(meta)), meta.id);
193
194
  for (const listener of metaChangedListeners) {
194
- try { listener(); } catch { /* best effort */ }
195
+ try { listener(meta); } catch { /* best effort */ }
195
196
  }
196
197
  return true;
197
198
  } catch {
@@ -251,6 +252,7 @@ export function listActiveMetasForOrigin(origin: BackgroundTaskCallbackOrigin):
251
252
  export function observeMetasForOrigin(origin: BackgroundTaskCallbackOrigin, activeOnly = true): BackgroundTaskMeta[] {
252
253
  const directory = activeOnly ? originActiveIndexDir(origin) : originIndexDir(origin);
253
254
  let ids: string[];
255
+ registryIo.indexDirectoryReads++;
254
256
  try { ids = readdirSync(directory).filter(id => id !== ".initialized"); }
255
257
  catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
256
258
  return ids.map(id => {
@@ -261,6 +263,42 @@ export function observeMetasForOrigin(origin: BackgroundTaskCallbackOrigin, acti
261
263
  && (!activeOnly || meta.status === "running")).sort((a, b) => b.startedAt - a.startedAt);
262
264
  }
263
265
 
266
+ const RECENT_LIMIT = 256;
267
+ const RECENT_MS = 30000;
268
+ function recentPath(origin: BackgroundTaskCallbackOrigin): string {
269
+ return join(baseDir(), "by-origin-recent", originKey(origin));
270
+ }
271
+ function recentEntries(origin: BackgroundTaskCallbackOrigin): Array<{ id: string; observedAt: number }> {
272
+ const directory = recentPath(origin);
273
+ try {
274
+ registryIo.indexDirectoryReads++;
275
+ const entries = readdirSync(directory).filter(id => !id.startsWith(".")).flatMap(id => {
276
+ try { registryIo.indexRevisionChecks++; return [{ id, observedAt: statSync(join(directory, id)).mtimeMs }]; }
277
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
278
+ }).sort((a, b) => b.observedAt - a.observedAt || b.id.localeCompare(a.id));
279
+ return entries.filter(entry => Date.now() - entry.observedAt < RECENT_MS).slice(0, RECENT_LIMIT);
280
+ } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
281
+ }
282
+
283
+ export function recentMetaDeadline(origin: BackgroundTaskCallbackOrigin): number[] {
284
+ return recentEntries(origin).map(entry => entry.observedAt + RECENT_MS);
285
+ }
286
+
287
+ /** Exact cooperative source identity; no metadata or historical enumeration. */
288
+ export function observationRevisionForOrigin(origin: BackgroundTaskCallbackOrigin): string {
289
+ return [originActiveIndexDir(origin), recentPath(origin)].map(indexDirectorySignature).join(";");
290
+ }
291
+
292
+ /** Bounded cooperative writes, including results written before the first reader. */
293
+ export function observeRecentMetasForOrigin(origin: BackgroundTaskCallbackOrigin): BackgroundTaskMeta[] {
294
+ return recentEntries(origin).map(entry => {
295
+ const record = inspectMeta(entry.id);
296
+ if (record.found && !record.meta) throw new Error(`Unverified background task ${entry.id}: ${record.error}`);
297
+ return record.meta;
298
+ }).filter((meta): meta is BackgroundTaskMeta =>
299
+ !!meta && belongsToOrigin(meta, origin) && meta.dismissedAt === undefined);
300
+ }
301
+
264
302
  function readMetaForSweep(id: string): BackgroundTaskMeta | undefined {
265
303
  const cached = metaCache.get(id);
266
304
  if (cached && isTerminalStatus(cached.status)) return cached;
@@ -308,6 +346,16 @@ function indexMeta(meta: BackgroundTaskMeta): void {
308
346
  const activeDirectory = originActiveIndexDir(originOf(meta));
309
347
  if (meta.status === "running") writeIndexEntry(activeDirectory, meta.id);
310
348
  else removeIndexEntry(activeDirectory, meta.id);
349
+ const origin = originOf(meta), recentDirectory = recentPath(origin);
350
+ mkdirSync(recentDirectory, { recursive: true });
351
+ // Independent pointers preserve concurrent writers; prune only this bounded
352
+ // recent-write accelerator, never the authoritative metadata or history.
353
+ const candidates = readdirSync(recentDirectory).filter(id => !id.startsWith("."));
354
+ const retained = new Set(recentEntries(origin).filter(entry => entry.id !== meta.id).slice(0, RECENT_LIMIT - 1).map(entry => entry.id));
355
+ for (const id of candidates) if (id !== meta.id && !retained.has(id)) removeIndexEntry(recentDirectory, id);
356
+ const temporary = join(recentDirectory, `.${meta.id}.${process.pid}.next`);
357
+ writeFileSync(temporary, "");
358
+ renameSync(temporary, join(recentDirectory, meta.id));
311
359
  } catch {
312
360
  // Indexes are accelerators; meta.json remains authoritative.
313
361
  }
@@ -14,16 +14,16 @@ import { markFailureAttentionDelivered } from "./shared-failure-observations.dom
14
14
  import { getCallbackBatcher } from "./shared-callback-batcher.domain.mjs";
15
15
  import { formatCallbackFacts } from "./output.domain.mjs";
16
16
  import { observeTaskStallAttention } from "./stall-attention.domain.mjs";
17
- import { isTerminalStatus } from "./types.domain.mjs";
17
+ import { FIRST_WATCH_CHECK_WAIT_MS, isTerminalStatus } from "./types.domain.mjs";
18
18
  export const DEFAULT_WATCH_TIMEOUT_SECONDS = 15 * 60;
19
19
  /** Consecutive blind checks (exit 0, stderr, no condition matched) before a watch is flagged (#359). */
20
20
  export const DEFAULT_BLIND_CHECKS = 3;
21
21
  /** How long bg_task_watch waits for the first check before returning (#359). */
22
- export const FIRST_WATCH_CHECK_WAIT_MS = 15_000;
22
+ export { FIRST_WATCH_CHECK_WAIT_MS } from "./types.domain.mjs";
23
23
  /** How to fix a false alarm: some tools write progress or warnings to stderr on success. */
24
24
  export const BLIND_CHECK_HINT = "If the stderr is expected (progress or warnings), redirect it (2>/dev/null) or set blind_checks:0.";
25
25
  /** Each cached extension factory owns its scheduling and suspension state. */
26
- export function createBackgroundTaskRuntime(attention = createFailureAttention(), deliverCompletion, admission) {
26
+ export function createBackgroundTaskRuntime(attention = createFailureAttention(), deliverCompletion, admission, sourceWork = (_kind, _id, work) => work()) {
27
27
  const { resumeFailureAttention, scheduleFailureAttention, stopFailureAttention, suspendFailureAttention } = attention;
28
28
  const watcherTimers = new Map();
29
29
  const remoteSessionTimers = new Map();
@@ -432,7 +432,8 @@ export function createBackgroundTaskRuntime(attention = createFailureAttention()
432
432
  clearRemoteSessionTimer(id);
433
433
  if (scheduledWorkSuspended)
434
434
  return;
435
- const timer = setTimeout(() => void pollRemoteSession(pi, id, getActiveSession), delayMs);
435
+ const dueAt = Date.now() + delayMs;
436
+ const timer = setTimeout(() => void sourceWork("remote-poll", id, () => scheduledWorkSuspended ? undefined : pollRemoteSession(pi, id, getActiveSession), dueAt), delayMs);
436
437
  timer.unref();
437
438
  remoteSessionTimers.set(id, timer);
438
439
  }
@@ -637,6 +638,10 @@ export function createBackgroundTaskRuntime(attention = createFailureAttention()
637
638
  scheduleLogRetention(pi, meta.id, getActiveSession);
638
639
  const remoteTask = resolvePersistedRemoteTask(meta, dependencies.remoteRunner);
639
640
  if (meta.kind === "command_watch") {
641
+ // Shared display refreshes can revisit an already supervised watch. They
642
+ // must not replace its captured interval with a new immediate poll.
643
+ if (watcherTimers.has(meta.id) || activePolls.has(meta.id))
644
+ return meta;
640
645
  scheduleWatch(pi, meta.id, 0, getActiveSession, remoteTask
641
646
  ? (timeoutMs) => remoteTask.runOnce(undefined, timeoutMs)
642
647
  : dependencies.watchPollRunner);
@@ -714,7 +719,9 @@ export function createBackgroundTaskRuntime(attention = createFailureAttention()
714
719
  const arm = () => {
715
720
  if (scheduledWorkSuspended)
716
721
  return;
717
- const timer = setTimeout(check, delayMs);
722
+ const dueAt = Date.now() + delayMs;
723
+ const timer = setTimeout(() => sourceWork("handoff", id, () => { if (!scheduledWorkSuspended)
724
+ check(); }, dueAt), delayMs);
718
725
  timer.unref();
719
726
  handoffTimers.set(id, timer);
720
727
  };
@@ -847,7 +854,8 @@ export function createBackgroundTaskRuntime(attention = createFailureAttention()
847
854
  clearWatchTimer(id);
848
855
  if (scheduledWorkSuspended)
849
856
  return;
850
- const timer = setTimeout(() => void pollWatch(pi, id, getActiveSession, runOnce), delayMs);
857
+ const dueAt = Date.now() + delayMs;
858
+ const timer = setTimeout(() => void sourceWork("watch", id, () => scheduledWorkSuspended ? undefined : pollWatch(pi, id, getActiveSession, runOnce), dueAt), delayMs);
851
859
  timer.unref();
852
860
  watcherTimers.set(id, timer);
853
861
  }
@@ -1135,7 +1143,8 @@ export function createBackgroundTaskRuntime(attention = createFailureAttention()
1135
1143
  if (scheduledWorkSuspended)
1136
1144
  return;
1137
1145
  const delay = Math.max(0, deadlineAt - Date.now());
1138
- const timer = setTimeout(() => void timeoutProcess(pi, id, getActiveSession), delay);
1146
+ const dueAt = deadlineAt;
1147
+ const timer = setTimeout(() => void sourceWork("process-deadline", id, () => scheduledWorkSuspended ? undefined : timeoutProcess(pi, id, getActiveSession), dueAt), delay);
1139
1148
  timer.unref();
1140
1149
  processTimeoutTimers.set(id, timer);
1141
1150
  }
@@ -1329,16 +1338,23 @@ export function createBackgroundTaskRuntime(attention = createFailureAttention()
1329
1338
  stopLogRetention(id);
1330
1339
  if (scheduledWorkSuspended)
1331
1340
  return;
1341
+ let dueAt = Date.now() + LOG_RETENTION_CHECK_MS;
1332
1342
  const timer = setInterval(() => {
1333
- const meta = readMeta(id);
1334
- if (!meta || meta.status !== "running") {
1335
- stopLogRetention(id);
1336
- return;
1337
- }
1338
- if (meta.kind === "process")
1339
- enforceLogRetention(meta);
1340
- if (observeTaskStallAttention(meta))
1341
- scheduleFailureAttention(pi, id, getActiveSession);
1343
+ const due = dueAt;
1344
+ dueAt = Date.now() + LOG_RETENTION_CHECK_MS;
1345
+ return sourceWork("log-retention", id, () => {
1346
+ if (scheduledWorkSuspended)
1347
+ return;
1348
+ const meta = readMeta(id);
1349
+ if (!meta || meta.status !== "running") {
1350
+ stopLogRetention(id);
1351
+ return;
1352
+ }
1353
+ if (meta.kind === "process")
1354
+ enforceLogRetention(meta);
1355
+ if (observeTaskStallAttention(meta))
1356
+ scheduleFailureAttention(pi, id, getActiveSession);
1357
+ }, due);
1342
1358
  }, LOG_RETENTION_CHECK_MS);
1343
1359
  timer.unref();
1344
1360
  logRetentionTimers.set(id, timer);
@@ -27,7 +27,7 @@ import type {
27
27
  TerminalResult,
28
28
  } from "./types.js";
29
29
  import { observeTaskStallAttention } from "./stall-attention.js";
30
- import { isTerminalStatus } from "./types.js";
30
+ import { FIRST_WATCH_CHECK_WAIT_MS, isTerminalStatus } from "./types.js";
31
31
 
32
32
  export type ActiveSessionProvider = () => BackgroundTaskCallbackOrigin | undefined;
33
33
 
@@ -98,7 +98,7 @@ export const DEFAULT_WATCH_TIMEOUT_SECONDS = 15 * 60;
98
98
  /** Consecutive blind checks (exit 0, stderr, no condition matched) before a watch is flagged (#359). */
99
99
  export const DEFAULT_BLIND_CHECKS = 3;
100
100
  /** How long bg_task_watch waits for the first check before returning (#359). */
101
- export const FIRST_WATCH_CHECK_WAIT_MS = 15_000;
101
+ export { FIRST_WATCH_CHECK_WAIT_MS } from "./types.js";
102
102
  /** How to fix a false alarm: some tools write progress or warnings to stderr on success. */
103
103
  export const BLIND_CHECK_HINT = "If the stderr is expected (progress or warnings), redirect it (2>/dev/null) or set blind_checks:0.";
104
104
  /**
@@ -110,7 +110,8 @@ export type FirstCheckWaitEnd = "timeout" | "aborted" | "suspended";
110
110
  export type FirstCheckOutcome = FirstWatchCheck | { pending: FirstCheckWaitEnd; waitedMs: number } | undefined;
111
111
 
112
112
  /** Each cached extension factory owns its scheduling and suspension state. */
113
- export function createBackgroundTaskRuntime(attention = createFailureAttention(), deliverCompletion?: (origin: BackgroundTaskCallbackOrigin | undefined, event: Parameters<ReturnType<typeof getCallbackBatcher>["enqueue"]>[0]) => void, admission?: { assert(): void; prepared?(id: string): void }) {
113
+ export function createBackgroundTaskRuntime(attention = createFailureAttention(), deliverCompletion?: (origin: BackgroundTaskCallbackOrigin | undefined, event: Parameters<ReturnType<typeof getCallbackBatcher>["enqueue"]>[0]) => void, admission?: { assert(): void; prepared?(id: string): void },
114
+ sourceWork: (kind: string, id: string, work: () => unknown, dueAt?: number) => unknown = (_kind, _id, work) => work()) {
114
115
  const { resumeFailureAttention, scheduleFailureAttention, stopFailureAttention, suspendFailureAttention } = attention;
115
116
  const watcherTimers = new Map<string, ReturnType<typeof setTimeout>>();
116
117
  const remoteSessionTimers = new Map<string, ReturnType<typeof setTimeout>>();
@@ -517,7 +518,8 @@ function scheduleRemoteSessionPoll(
517
518
  ): void {
518
519
  clearRemoteSessionTimer(id);
519
520
  if (scheduledWorkSuspended) return;
520
- const timer = setTimeout(() => void pollRemoteSession(pi, id, getActiveSession), delayMs);
521
+ const dueAt = Date.now() + delayMs;
522
+ const timer = setTimeout(() => void sourceWork("remote-poll", id, () => scheduledWorkSuspended ? undefined : pollRemoteSession(pi, id, getActiveSession), dueAt), delayMs);
521
523
  timer.unref();
522
524
  remoteSessionTimers.set(id, timer);
523
525
  }
@@ -735,6 +737,9 @@ function resumeRunningTask(
735
737
  scheduleLogRetention(pi, meta.id, getActiveSession);
736
738
  const remoteTask = resolvePersistedRemoteTask(meta, dependencies.remoteRunner);
737
739
  if (meta.kind === "command_watch") {
740
+ // Shared display refreshes can revisit an already supervised watch. They
741
+ // must not replace its captured interval with a new immediate poll.
742
+ if (watcherTimers.has(meta.id) || activePolls.has(meta.id)) return meta;
738
743
  scheduleWatch(pi, meta.id, 0, getActiveSession, remoteTask
739
744
  ? (timeoutMs) => remoteTask.runOnce(undefined, timeoutMs)
740
745
  : dependencies.watchPollRunner);
@@ -814,7 +819,8 @@ function scheduleHandoff(
814
819
  };
815
820
  const arm = () => {
816
821
  if (scheduledWorkSuspended) return;
817
- const timer = setTimeout(check, delayMs);
822
+ const dueAt = Date.now() + delayMs;
823
+ const timer = setTimeout(() => sourceWork("handoff", id, () => { if (!scheduledWorkSuspended) check(); }, dueAt), delayMs);
818
824
  timer.unref();
819
825
  handoffTimers.set(id, timer);
820
826
  };
@@ -957,7 +963,8 @@ function scheduleWatch(
957
963
  ): void {
958
964
  clearWatchTimer(id);
959
965
  if (scheduledWorkSuspended) return;
960
- const timer = setTimeout(() => void pollWatch(pi, id, getActiveSession, runOnce), delayMs);
966
+ const dueAt = Date.now() + delayMs;
967
+ const timer = setTimeout(() => void sourceWork("watch", id, () => scheduledWorkSuspended ? undefined : pollWatch(pi, id, getActiveSession, runOnce), dueAt), delayMs);
961
968
  timer.unref();
962
969
  watcherTimers.set(id, timer);
963
970
  }
@@ -1260,7 +1267,8 @@ function scheduleProcessTimeout(
1260
1267
  clearProcessTimeout(id);
1261
1268
  if (scheduledWorkSuspended) return;
1262
1269
  const delay = Math.max(0, deadlineAt - Date.now());
1263
- const timer = setTimeout(() => void timeoutProcess(pi, id, getActiveSession), delay);
1270
+ const dueAt = deadlineAt;
1271
+ const timer = setTimeout(() => void sourceWork("process-deadline", id, () => scheduledWorkSuspended ? undefined : timeoutProcess(pi, id, getActiveSession), dueAt), delay);
1264
1272
  timer.unref();
1265
1273
  processTimeoutTimers.set(id, timer);
1266
1274
  }
@@ -1459,7 +1467,9 @@ function launchArgvOf(commandSpec: CommandSpec, launchSpec: CommandSpec): string
1459
1467
  function scheduleLogRetention(pi: ExtensionAPI, id: string, getActiveSession?: ActiveSessionProvider): void {
1460
1468
  stopLogRetention(id);
1461
1469
  if (scheduledWorkSuspended) return;
1462
- const timer = setInterval(() => {
1470
+ let dueAt = Date.now() + LOG_RETENTION_CHECK_MS;
1471
+ const timer = setInterval(() => { const due = dueAt; dueAt = Date.now() + LOG_RETENTION_CHECK_MS; return sourceWork("log-retention", id, () => {
1472
+ if (scheduledWorkSuspended) return;
1463
1473
  const meta = readMeta(id);
1464
1474
  if (!meta || meta.status !== "running") {
1465
1475
  stopLogRetention(id);
@@ -1467,7 +1477,7 @@ function scheduleLogRetention(pi: ExtensionAPI, id: string, getActiveSession?: A
1467
1477
  }
1468
1478
  if (meta.kind === "process") enforceLogRetention(meta);
1469
1479
  if (observeTaskStallAttention(meta)) scheduleFailureAttention(pi, id, getActiveSession);
1470
- }, LOG_RETENTION_CHECK_MS);
1480
+ }, due); }, LOG_RETENTION_CHECK_MS);
1471
1481
  timer.unref();
1472
1482
  logRetentionTimers.set(id, timer);
1473
1483
  }
@@ -242,6 +242,7 @@ function readPermissions(value) {
242
242
  projectFiles: p.projectFiles,
243
243
  outsideProject: p.outsideProject,
244
244
  storedCredentials: p.storedCredentials,
245
+ ...(p.processAccess === undefined ? {} : { processAccess: p.processAccess }),
245
246
  ...(p.shell === undefined ? {} : { shell: p.shell }),
246
247
  ...(p.commandTimeoutSeconds === undefined ? {} : { commandTimeoutSeconds: p.commandTimeoutSeconds }),
247
248
  });
@@ -264,22 +265,20 @@ export function observeForegroundSandboxPolicy(pi) {
264
265
  try {
265
266
  const published = data && typeof data === "object" ? data : undefined;
266
267
  const hasBackground = published && Object.hasOwn(published, "background");
267
- const policy = readPolicy(hasBackground ? published.background : data, hasBackground ? "Background tasks" : "Main");
268
- if (hasBackground && !policy)
268
+ const main = readPolicy(data);
269
+ const policy = hasBackground ? readPolicy(published.background, "Background tasks") : main;
270
+ if (hasBackground && (!main || !policy))
269
271
  throw new Error("Invalid Background tasks sandbox policy; update permissions in /sandbox.");
270
- const access = (value) => {
271
- if (!value || typeof value !== "object")
272
- return undefined;
273
- return value.permissions?.processAccess;
274
- };
275
- mirror.mainConfined = published?.state !== "disabled" && published?.state !== "inactive";
276
- mirror.processAccess = access(data) === "read" && access(hasBackground ? published.background : data) === "read" ? "read" : "off";
277
- if (policy)
278
- Object.assign(policy, { policySource: hasBackground ? "background" : "main-legacy" });
279
- if (policy) {
280
- mirror.policy = policy;
281
- mirror.error = undefined;
282
- }
272
+ if (!policy || !main)
273
+ return;
274
+ const isOff = (scope) => scope.state === "disabled" || scope.state === "inactive";
275
+ const allowsRead = (scope) => scope.permissions !== undefined &&
276
+ (isOff(scope) || scope.permissions.processAccess === "read");
277
+ mirror.mainConfined = !isOff(main);
278
+ mirror.processAccess = allowsRead(main) && allowsRead(policy) ? "read" : "off";
279
+ Object.assign(policy, { policySource: hasBackground ? "background" : "main-legacy" });
280
+ mirror.policy = policy;
281
+ mirror.error = undefined;
283
282
  }
284
283
  catch (error) {
285
284
  mirror.error = error;
@@ -214,7 +214,7 @@ export interface ForegroundSandboxPolicy {
214
214
  readonly denyWrite: readonly string[];
215
215
  /** Human-readable evidence for why `state` is what it is. */
216
216
  readonly reason: string;
217
- readonly permissions?: Readonly<SandboxPermissions & { enabled: boolean }>;
217
+ readonly permissions?: Readonly<SandboxPermissions & { enabled: boolean; processAccess?: "off" | "read" }>;
218
218
  readonly policySource?: "background" | "main-legacy";
219
219
  }
220
220
 
@@ -320,6 +320,7 @@ function readPermissions(value: unknown): ForegroundSandboxPolicy["permissions"]
320
320
  projectFiles: p.projectFiles as SandboxPermissions["projectFiles"],
321
321
  outsideProject: p.outsideProject as SandboxPermissions["outsideProject"],
322
322
  storedCredentials: p.storedCredentials as SandboxPermissions["storedCredentials"],
323
+ ...(p.processAccess === undefined ? {} : { processAccess: p.processAccess as "off" | "read" }),
323
324
  ...(p.shell === undefined ? {} : { shell: p.shell as boolean }),
324
325
  ...(p.commandTimeoutSeconds === undefined ? {} : { commandTimeoutSeconds: p.commandTimeoutSeconds as number | null }),
325
326
  });
@@ -343,16 +344,18 @@ export function observeForegroundSandboxPolicy(pi: unknown): void {
343
344
  try {
344
345
  const published = data && typeof data === "object" ? data as Record<string, unknown> : undefined;
345
346
  const hasBackground = published && Object.hasOwn(published, "background");
346
- const policy = readPolicy(hasBackground ? published.background : data, hasBackground ? "Background tasks" : "Main");
347
- if (hasBackground && !policy) throw new Error("Invalid Background tasks sandbox policy; update permissions in /sandbox.");
348
- const access = (value: unknown): unknown => {
349
- if (!value || typeof value !== "object") return undefined;
350
- return (value as { permissions?: { processAccess?: unknown } }).permissions?.processAccess;
351
- };
352
- mirror.mainConfined = published?.state !== "disabled" && published?.state !== "inactive";
353
- mirror.processAccess = access(data) === "read" && access(hasBackground ? published.background : data) === "read" ? "read" : "off";
354
- if (policy) Object.assign(policy, { policySource: hasBackground ? "background" : "main-legacy" });
355
- if (policy) { mirror.policy = policy; mirror.error = undefined; }
347
+ const main = readPolicy(data);
348
+ const policy = hasBackground ? readPolicy(published.background, "Background tasks") : main;
349
+ if (hasBackground && (!main || !policy)) throw new Error("Invalid Background tasks sandbox policy; update permissions in /sandbox.");
350
+ if (!policy || !main) return;
351
+ const isOff = (scope: ForegroundSandboxPolicy) => scope.state === "disabled" || scope.state === "inactive";
352
+ const allowsRead = (scope: ForegroundSandboxPolicy) => scope.permissions !== undefined &&
353
+ (isOff(scope) || scope.permissions.processAccess === "read");
354
+ mirror.mainConfined = !isOff(main);
355
+ mirror.processAccess = allowsRead(main) && allowsRead(policy) ? "read" : "off";
356
+ Object.assign(policy, { policySource: hasBackground ? "background" : "main-legacy" });
357
+ mirror.policy = policy;
358
+ mirror.error = undefined;
356
359
  } catch (error) {
357
360
  mirror.error = error as Error;
358
361
  mirror.processAccess = "off";
@@ -400,6 +400,7 @@ export function createCallbackBatcher(host, options = {}) {
400
400
  const pending = new Map();
401
401
  const inFlight = new Set();
402
402
  const urgentInFlight = new Set();
403
+ const urgentSettlements = new Set();
403
404
  const handedOff = new Map();
404
405
  const activeTools = new Set();
405
406
  let sequence = 0;
@@ -583,7 +584,9 @@ export function createCallbackBatcher(host, options = {}) {
583
584
  const handoff = host.sendMessage({ customType: event.customType, content: formatUrgentCallback(event, { maxBytes }), display: true,
584
585
  ...(event.receiptId ? { details: { urgentEventId: event.receiptId } } : {}) }, { deliverAs: "followUp", triggerTurn: true });
585
586
  if (isPromiseLike(handoff)) {
586
- return Promise.resolve(handoff).then(() => acknowledge(), () => false).finally(() => urgentInFlight.delete(key));
587
+ const settlement = Promise.resolve(handoff).then(() => acknowledge(), () => false).finally(() => { urgentInFlight.delete(key); urgentSettlements.delete(settlement); });
588
+ urgentSettlements.add(settlement);
589
+ return settlement;
587
590
  }
588
591
  const acknowledged = acknowledge();
589
592
  urgentInFlight.delete(key);
@@ -634,6 +637,10 @@ export function createCallbackBatcher(host, options = {}) {
634
637
  return pending.size > 0 ? api.flush() : true;
635
638
  },
636
639
  deliverUrgent,
640
+ async settled() {
641
+ await flushPromise;
642
+ await Promise.all([...urgentSettlements]);
643
+ },
637
644
  cancel() {
638
645
  cancelTimer();
639
646
  pending.clear();
@@ -210,6 +210,8 @@ export interface CallbackBatcher {
210
210
  toolEnded(toolCallId: string): Promise<boolean>;
211
211
  deliverUrgent(event: UrgentCallbackEvent): boolean | Promise<boolean>;
212
212
  cancel(): void;
213
+ /** Await already-started handoffs after the owner has cancelled scheduling. */
214
+ settled(): Promise<void>;
213
215
  pendingCount(): number;
214
216
  }
215
217
 
@@ -568,6 +570,7 @@ export function createCallbackBatcher(
568
570
  const pending = new Map<string, PendingEvent>();
569
571
  const inFlight = new Set<string>();
570
572
  const urgentInFlight = new Set<string>();
573
+ const urgentSettlements = new Set<Promise<boolean>>();
571
574
  const handedOff = new Map<string, number>();
572
575
  const activeTools = new Set<string>();
573
576
  let sequence = 0;
@@ -750,10 +753,12 @@ export function createCallbackBatcher(
750
753
  { deliverAs: "followUp", triggerTurn: true },
751
754
  );
752
755
  if (isPromiseLike(handoff)) {
753
- return Promise.resolve(handoff).then(
756
+ const settlement = Promise.resolve(handoff).then(
754
757
  () => acknowledge(),
755
758
  () => false,
756
- ).finally(() => urgentInFlight.delete(key));
759
+ ).finally(() => { urgentInFlight.delete(key); urgentSettlements.delete(settlement); });
760
+ urgentSettlements.add(settlement);
761
+ return settlement;
757
762
  }
758
763
  const acknowledged = acknowledge();
759
764
  urgentInFlight.delete(key);
@@ -800,6 +805,10 @@ export function createCallbackBatcher(
800
805
  return pending.size > 0 ? api.flush() : true;
801
806
  },
802
807
  deliverUrgent,
808
+ async settled() {
809
+ await flushPromise;
810
+ await Promise.all([...urgentSettlements]);
811
+ },
803
812
  cancel() {
804
813
  cancelTimer();
805
814
  pending.clear();
@@ -42,15 +42,34 @@ function buildPanels(s) {
42
42
  if (!s.tui || !s.theme)
43
43
  return;
44
44
  for (const panel of orderedPanels(s))
45
- panel.component ??= panel.factory(s.tui, s.theme);
45
+ panel.component ??= panel.factory(s.tui, s.theme, { availableRows: () => s.availableRows ?? Infinity });
46
+ }
47
+ // Count the editor, footer and other siblings following the host in regular mode.
48
+ // Never render ancestors here: they contain this host and would recurse.
49
+ function rowsAfter(root, target, width) {
50
+ if (root === target)
51
+ return 0;
52
+ const children = root.children;
53
+ if (!children)
54
+ return undefined;
55
+ for (let i = children.length - 1; i >= 0; i--) {
56
+ const after = rowsAfter(children[i], target, width);
57
+ if (after !== undefined)
58
+ return after + children.slice(i + 1).reduce((sum, child) => sum + child.render(width).length, 0);
59
+ }
60
+ return undefined;
46
61
  }
47
62
  function renderPanels(s, width) {
48
63
  buildPanels(s);
49
64
  const lines = [];
50
65
  s.ranges = [];
66
+ const after = s.sticky && s.tui && s.host ? rowsAfter(s.tui, s.host, width) : undefined;
67
+ const height = s.tui?.terminal?.rows;
68
+ const budget = after !== undefined && height ? Math.max(0, height - after) : Infinity;
51
69
  for (const panel of orderedPanels(s)) {
52
70
  if (!panel.component)
53
71
  continue;
72
+ s.availableRows = Math.max(0, budget - lines.length);
54
73
  const rendered = panel.component.render(width);
55
74
  s.ranges.push({ start: lines.length, end: lines.length + rendered.length, component: panel.component });
56
75
  lines.push(...rendered);
@@ -110,6 +129,7 @@ function clearHost(s) {
110
129
  disposePanels(s);
111
130
  s.mounted = false;
112
131
  s.tui = undefined;
132
+ s.host = undefined;
113
133
  s.theme = undefined;
114
134
  }
115
135
  function adoptContext(s, ctx) {
@@ -131,7 +151,7 @@ function mountHost(s) {
131
151
  s.tui = tui;
132
152
  s.theme = theme;
133
153
  buildPanels(s);
134
- return {
154
+ const host = {
135
155
  render(width) {
136
156
  const lines = renderPanels(s, width);
137
157
  if (s.sticky)
@@ -147,6 +167,8 @@ function mountHost(s) {
147
167
  },
148
168
  dispose() { disposePanels(s); s.mounted = false; },
149
169
  };
170
+ s.host = host;
171
+ return host;
150
172
  }, { placement: "aboveEditor" });
151
173
  }
152
174
  function changeSticky(value, ctx) {
@@ -9,7 +9,8 @@ export const NAVIGATOR_ENTRY_TYPE = "pi-better-harness-navigator-panels";
9
9
  export const NAVIGATOR_STICKY_SETTING_ID = "navigator-sticky";
10
10
  type MouseEvent = { type: string; button: string; x: number; y: number; width: number; shift?: boolean; alt?: boolean; ctrl?: boolean };
11
11
  type PanelComponent = Component & { dispose?(): void; handleMouse?(event: MouseEvent): { handled: true; render: boolean } | undefined };
12
- export type NavigatorPanelFactory = (tui: TUI, theme: Theme) => PanelComponent;
12
+ export type NavigatorPanelLayout = { availableRows(): number };
13
+ export type NavigatorPanelFactory = (tui: TUI, theme: Theme, layout: NavigatorPanelLayout) => PanelComponent;
13
14
  type Panel = { factory: NavigatorPanelFactory; component?: PanelComponent | undefined };
14
15
  type Preference = { version: 1; sticky: boolean };
15
16
  type Owner = { pi: ExtensionAPI; stop?: (() => void) | undefined };
@@ -23,6 +24,8 @@ type State = {
23
24
  mounted: boolean;
24
25
  tui?: TUI | undefined;
25
26
  theme?: Theme | undefined;
27
+ host?: Component | undefined;
28
+ availableRows?: number | undefined;
26
29
  anchor?: string | undefined;
27
30
  pendingAnchor: boolean;
28
31
  generation: number;
@@ -61,14 +64,30 @@ function orderedPanels(s: State): Panel[] {
61
64
  }
62
65
  function buildPanels(s: State): void {
63
66
  if (!s.tui || !s.theme) return;
64
- for (const panel of orderedPanels(s)) panel.component ??= panel.factory(s.tui, s.theme);
67
+ for (const panel of orderedPanels(s)) panel.component ??= panel.factory(s.tui, s.theme, { availableRows: () => s.availableRows ?? Infinity });
68
+ }
69
+ // Count the editor, footer and other siblings following the host in regular mode.
70
+ // Never render ancestors here: they contain this host and would recurse.
71
+ function rowsAfter(root: object, target: Component, width: number): number | undefined {
72
+ if (root === target) return 0;
73
+ const children = (root as Component & { children?: Component[] }).children;
74
+ if (!children) return undefined;
75
+ for (let i = children.length - 1; i >= 0; i--) {
76
+ const after = rowsAfter(children[i]!, target, width);
77
+ if (after !== undefined) return after + children.slice(i + 1).reduce((sum, child) => sum + child.render(width).length, 0);
78
+ }
79
+ return undefined;
65
80
  }
66
81
  function renderPanels(s: State, width: number): string[] {
67
82
  buildPanels(s);
68
83
  const lines: string[] = [];
69
84
  s.ranges = [];
85
+ const after = s.sticky && s.tui && s.host ? rowsAfter(s.tui, s.host, width) : undefined;
86
+ const height = s.tui?.terminal?.rows;
87
+ const budget = after !== undefined && height ? Math.max(0, height - after) : Infinity;
70
88
  for (const panel of orderedPanels(s)) {
71
89
  if (!panel.component) continue;
90
+ s.availableRows = Math.max(0, budget - lines.length);
72
91
  const rendered = panel.component.render(width);
73
92
  s.ranges.push({ start: lines.length, end: lines.length + rendered.length, component: panel.component });
74
93
  lines.push(...rendered);
@@ -115,6 +134,7 @@ function clearHost(s: State): void {
115
134
  disposePanels(s);
116
135
  s.mounted = false;
117
136
  s.tui = undefined;
137
+ s.host = undefined;
118
138
  s.theme = undefined;
119
139
  }
120
140
  function adoptContext(s: State, ctx: ExtensionContext): void {
@@ -134,7 +154,7 @@ function mountHost(s: State): void {
134
154
  s.tui = tui;
135
155
  s.theme = theme;
136
156
  buildPanels(s);
137
- return {
157
+ const host: PanelComponent = {
138
158
  render(width: number) {
139
159
  const lines = renderPanels(s, width);
140
160
  if (s.sticky) return lines;
@@ -147,6 +167,8 @@ function mountHost(s: State): void {
147
167
  },
148
168
  dispose() { disposePanels(s); s.mounted = false; },
149
169
  };
170
+ s.host = host;
171
+ return host;
150
172
  }, { placement: "aboveEditor" });
151
173
  }
152
174
  function changeSticky(value: string, ctx: ExtensionContext): void {
@@ -247,4 +269,4 @@ export function __resetNavigatorPanelsForTests(): void {
247
269
  s.anchor = undefined;
248
270
  s.sticky = true;
249
271
  s.control = undefined;
250
- }
272
+ }