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,8 +1,8 @@
1
1
  /**
2
2
  * Filesystem catalog: project, personal, and bundled sources.
3
3
  *
4
- * Discovery is deterministic and reads the disk on every call. There is no
5
- * launch cache. Callers that launch a batch must retain the returned snapshot
4
+ * Discovery is deterministic. Direct callers read disk on every call; the server
5
+ * can supply bounded source reuse after admission. Callers launching a batch retain the snapshot
6
6
  * and reuse that object for every job.
7
7
  *
8
8
  * Project files are read only when `projectTrusted` is true. Pass Pi's
@@ -51,6 +51,13 @@ export const DEFAULT_PROJECT_CONFIG_DIR_NAME = ".pi";
51
51
  export const SOURCE_PRECEDENCE = ["project", "user", "bundled"] as const;
52
52
 
53
53
  export interface LoadCatalogInput {
54
+ /** Server-owned, bounded source reuse. Admission and discovery still run first. */
55
+ sources?: {
56
+ read(path: string): string;
57
+ parse(raw: string, path: string): ParseResult;
58
+ entry?(entry: CatalogEntry): CatalogEntry;
59
+ preferences?(root: string): ReturnType<typeof readCatalogPreferences>;
60
+ };
54
61
  cwd: string;
55
62
  /** Host trust decision. Untrusted projects do not contribute definitions. */
56
63
  projectTrusted: boolean;
@@ -195,13 +202,13 @@ export function listScopedAgents(input: LoadCatalogInput, scope: "user" | "proje
195
202
  if (!isSafeConfigDirName(config)) throw new Error("Unsafe project config directory");
196
203
  const directory = scope === "project" ? projectCatalogPaths(input.cwd, config).agents : userCatalogPaths(input.userRoot).agents;
197
204
  const occurrences = new Map<string, Occurrence[]>();
198
- collectDirectory(directory, scope, "agent", occurrences, diagnostics);
205
+ collectDirectory(directory, scope, "agent", occurrences, diagnostics, input.sources);
199
206
  const agents = [...occurrences.values()].flat().flatMap(item => item.parse.definition?.kind === "agent"
200
207
  ? [{ path: item.path, definition: item.parse.definition }] : []);
201
208
  return { agents, diagnostics };
202
209
  }
203
210
 
204
- /** Read every source again. Identical bytes produce the same digest and a new object. */
211
+ /** Discover authorized sources. Identical bytes produce the same content digest. */
205
212
  export function loadCatalog(input: LoadCatalogInput): CatalogSnapshot {
206
213
  const loadedAt = new Date().toISOString();
207
214
  const diagnostics: Diagnostic[] = [];
@@ -219,8 +226,8 @@ export function loadCatalog(input: LoadCatalogInput): CatalogSnapshot {
219
226
 
220
227
  if (input.projectTrusted) {
221
228
  const project = projectCatalogPaths(input.cwd, configDirName);
222
- collectDirectory(project.roles, "project", "role", groups.get("project")!, diagnostics);
223
- collectDirectory(project.agents, "project", "agent", groups.get("project")!, diagnostics);
229
+ collectDirectory(project.roles, "project", "role", groups.get("project")!, diagnostics, input.sources);
230
+ collectDirectory(project.agents, "project", "agent", groups.get("project")!, diagnostics, input.sources);
224
231
  } else {
225
232
  const project = projectCatalogPaths(input.cwd, configDirName);
226
233
  if (pathExists(project.roles) || pathExists(project.agents) || pathExists(project.root)) {
@@ -233,8 +240,8 @@ export function loadCatalog(input: LoadCatalogInput): CatalogSnapshot {
233
240
  }
234
241
 
235
242
  const user = userCatalogPaths(input.userRoot);
236
- collectDirectory(user.roles, "user", "role", groups.get("user")!, diagnostics);
237
- collectDirectory(user.agents, "user", "agent", groups.get("user")!, diagnostics);
243
+ collectDirectory(user.roles, "user", "role", groups.get("user")!, diagnostics, input.sources);
244
+ collectDirectory(user.agents, "user", "agent", groups.get("user")!, diagnostics, input.sources);
238
245
 
239
246
  const bundledRoles = input.bundledRoot ?? bundledRolesRoot();
240
247
  if (!existsSync(bundledRoles)) {
@@ -246,24 +253,22 @@ export function loadCatalog(input: LoadCatalogInput): CatalogSnapshot {
246
253
  severity: "warning",
247
254
  }));
248
255
  } else {
249
- collectDirectory(bundledRoles, "bundled", "role", groups.get("bundled")!, diagnostics);
256
+ collectDirectory(bundledRoles, "bundled", "role", groups.get("bundled")!, diagnostics, input.sources);
250
257
  }
251
258
  if (input.bundledAgentsRoot) {
252
- collectDirectory(input.bundledAgentsRoot, "bundled", "agent", groups.get("bundled")!, diagnostics);
259
+ collectDirectory(input.bundledAgentsRoot, "bundled", "agent", groups.get("bundled")!, diagnostics, input.sources);
253
260
  }
254
261
 
255
262
  const { entries, blocked } = selectIdentities(groups, diagnostics);
256
263
  const savedSettings: Record<string, { model?: string | null; effort?: ThinkingLevel | null }> = {};
257
264
  const preferenceSources: Record<string, Partial<Record<"model" | "effort", { scope: "user" | "project"; path: string; bundled?: boolean }>>> = {};
258
- const preferenceDigests: string[] = [];
259
265
  const scopes = [
260
266
  { scope: "user" as const, root: user.root },
261
267
  ...(input.projectTrusted ? [{ scope: "project" as const, root: projectCatalogPaths(input.cwd, configDirName).root }] : []),
262
268
  ];
263
269
  for (const { scope, root } of scopes) {
264
270
  try {
265
- const preferences = readCatalogPreferences(root);
266
- preferenceDigests.push(preferences.digest);
271
+ const preferences = input.sources?.preferences?.(root) ?? readCatalogPreferences(root);
267
272
  for (const entry of entries) {
268
273
  if (scope === "user" && entry.scope === "project") continue;
269
274
  const own = preferences.settings[entry.id];
@@ -272,8 +277,8 @@ export function loadCatalog(input: LoadCatalogInput): CatalogSnapshot {
272
277
  if (own.bundled) {
273
278
  const fallbacks = entry.scope === "bundled" ? [entry] : entry.unused.filter(source => source.scope === "bundled");
274
279
  const fallback = fallbacks.length === 1 ? fallbacks[0] : undefined;
275
- const raw = fallback ? readFileSync(fallback.path, "utf8") : undefined;
276
- const parsed = raw === undefined ? undefined : parseDefinition(raw, fallback!.path);
280
+ const raw = fallback ? (input.sources?.read(fallback.path) ?? readFileSync(fallback.path, "utf8")) : undefined;
281
+ const parsed = raw === undefined ? undefined : (input.sources?.parse(raw, fallback!.path) ?? parseDefinition(raw, fallback!.path));
277
282
  if (!fallback || !parsed?.ok || parsed.definition?.id !== entry.id || parsed.diagnostics.some(item => item.blocking)
278
283
  || contentDigest(raw!) !== fallback.contentDigest) {
279
284
  const failure = diagnostic("catalog-preferences", `Cannot inherit bundled runtime defaults for ${entry.id}: a single valid bundled definition is required.`, {
@@ -309,8 +314,8 @@ export function loadCatalog(input: LoadCatalogInput): CatalogSnapshot {
309
314
  }
310
315
  }
311
316
  }
312
- const snapshot = finishSnapshot(entries, blocked, diagnostics, loadedAt);
313
- const digest = contentDigest(JSON.stringify([snapshot.digest, preferenceDigests, savedSettings, preferenceSources]));
317
+ const snapshot = finishSnapshot(entries, blocked, diagnostics, loadedAt, input.sources);
318
+ const digest = contentDigest(JSON.stringify([snapshot.digest, savedSettings, preferenceSources]));
314
319
  return deepFreeze({ ...snapshot, digest, revision: digest, savedSettings, preferenceSources });
315
320
  }
316
321
 
@@ -526,6 +531,7 @@ function collectDirectory(
526
531
  directoryKind: CatalogKind,
527
532
  into: Map<string, Occurrence[]>,
528
533
  diagnostics: Diagnostic[],
534
+ sources?: LoadCatalogInput["sources"],
529
535
  ): void {
530
536
  let stats;
531
537
  try {
@@ -602,7 +608,7 @@ function collectDirectory(
602
608
  if (!fileStats.isFile()) continue;
603
609
  let raw: string;
604
610
  try {
605
- raw = readFileSync(path, "utf8");
611
+ raw = sources?.read(path) ?? readFileSync(path, "utf8");
606
612
  } catch (error) {
607
613
  diagnostics.push(diagnostic(DiagnosticCodes.ioError, `Could not read ${path}: ${(error as Error).message}`, {
608
614
  scope,
@@ -614,7 +620,7 @@ function collectDirectory(
614
620
  }
615
621
  let parse: ParseResult;
616
622
  try {
617
- parse = parseDefinition(raw, path);
623
+ parse = sources?.parse(raw, path) ?? parseDefinition(raw, path);
618
624
  } catch (error) {
619
625
  const detail = error instanceof Error ? error.message : String(error);
620
626
  diagnostics.push(diagnostic(
@@ -765,11 +771,12 @@ function finishSnapshot(
765
771
  blocked: CatalogEntry[],
766
772
  diagnostics: Diagnostic[],
767
773
  loadedAt: string,
774
+ sources?: LoadCatalogInput["sources"],
768
775
  ): CatalogSnapshot {
769
776
  const roleEntries: Array<readonly [string, CatalogEntry]> = [];
770
777
  const agentEntries: Array<readonly [string, CatalogEntry]> = [];
771
778
  for (const entry of entries) {
772
- const frozen = deepFreeze(cloneEntry(entry));
779
+ const frozen = sources?.entry?.(entry) ?? deepFreeze(cloneEntry(entry));
773
780
  if (frozen.kind === "role") roleEntries.push([frozen.id, frozen]);
774
781
  else agentEntries.push([frozen.id, frozen]);
775
782
  }
@@ -0,0 +1,13 @@
1
+ // Generated fixed launch domain from packages/pi-better-subagents/child-apply-patch.ts. Do not edit directly.
2
+ import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
3
+ import { createApplyPatchToolDefinition } from "./shared-task-apply-patch.domain.mjs";
4
+ import { createTaskFileOperations } from "./shared-task-files.domain.mjs";
5
+ /** Ordinary worker implementation. Confined workers install their own guarded definition. */
6
+ export default function childApplyPatch(pi) {
7
+ const files = createTaskFileOperations({ requireLaunchPlan: () => ({ confined: false }) });
8
+ const tool = createApplyPatchToolDefinition(process.cwd(), {
9
+ readFile: files.read.readFile, writeFile: files.write.writeFile, mkdir: files.write.mkdir,
10
+ remove: files.remove.remove, checkWrite: files.check.write, checkRemove: files.check.remove,
11
+ }, withFileMutationQueue);
12
+ pi.registerTool(tool);
13
+ }
@@ -0,0 +1,13 @@
1
+ import { withFileMutationQueue, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { createApplyPatchToolDefinition } from "./shared-task-apply-patch.ts";
3
+ import { createTaskFileOperations } from "./shared-task-files.ts";
4
+
5
+ /** Ordinary worker implementation. Confined workers install their own guarded definition. */
6
+ export default function childApplyPatch(pi: ExtensionAPI): void {
7
+ const files = createTaskFileOperations({ requireLaunchPlan: () => ({ confined: false }) });
8
+ const tool = createApplyPatchToolDefinition(process.cwd(), {
9
+ readFile: files.read.readFile, writeFile: files.write.writeFile, mkdir: files.write.mkdir,
10
+ remove: files.remove.remove, checkWrite: files.check.write, checkRemove: files.check.remove,
11
+ }, withFileMutationQueue);
12
+ pi.registerTool(tool as Parameters<ExtensionAPI["registerTool"]>[0]);
13
+ }
@@ -71,34 +71,39 @@ export function configSnapshot(directories) {
71
71
  export async function resolveChildClosure({ resolution, model, virtual = false, config = {}, resolvePath, load = loadContract, configPaths = [] }) {
72
72
  const result = { ...resolution, specs: [], reasons: { ...resolution.reasons }, paths: {}, declarations: [],
73
73
  providers: [], modelGroups: [], fingerprints: configPaths.map(path => ({ path, hash: fingerprint(path) })) };
74
+ function requiredPath(spec, from) {
75
+ const path = resolvePath(spec, from);
76
+ if (path)
77
+ return path;
78
+ const reason = (resolution.reasons[spec] ?? []).join(', ');
79
+ throw new Error(`Child dependency ${spec}${from ? ` required by ${from}` : ''} is not installed.${reason ? ` Selected for ${reason}.` : ''}`);
80
+ }
74
81
  if (resolution.mode !== 'isolated') {
75
82
  if (virtual)
76
83
  throw new Error(`Virtual model ${model} requires isolated mode with a declared supplier; ${resolution.mode} mode is unsupported.`);
77
- return { ...result, specs: resolution.specs, paths: Object.fromEntries(resolution.specs.map(spec => {
78
- const path = resolvePath(spec);
79
- if (!path)
80
- throw new Error(`Child dependency ${spec} is not installed.`);
81
- return [spec, path];
82
- })) };
84
+ return { ...result, specs: resolution.specs, paths: Object.fromEntries(resolution.specs.map(spec => [spec, requiredPath(spec)])) };
83
85
  }
84
86
  const providerMap = { ...BUILTIN_PROVIDER_EXTENSIONS, ...(config.providerExtensions ?? {}) };
85
- const active = [], done = new Set();
87
+ const active = [], done = new Set(), entrypoints = new Set();
86
88
  let ownsVirtual = false;
87
89
  const visit = async (spec, from) => {
88
- const path = resolvePath(spec, from);
89
- if (!path)
90
- throw new Error(`Child dependency ${spec}${from ? ` required by ${from}` : ''} is not installed.`);
90
+ const path = requiredPath(spec, from);
91
91
  const root = packageRoot(path);
92
92
  const identity = root ?? realpathSync(path);
93
93
  if (active.includes(identity))
94
94
  throw new Error(`Child dependency cycle: ${[...active, identity].join(' -> ')}`);
95
- if (done.has(identity))
95
+ // Different tool entrypoints can share a package and its dependency manifest.
96
+ const entrypoint = realpathSync(path);
97
+ if (entrypoints.has(entrypoint))
96
98
  return;
97
- active.push(identity);
99
+ entrypoints.add(entrypoint);
98
100
  // Two packages may declare the same relative spec against different roots.
99
101
  const key = result.paths[spec] && result.paths[spec] !== path ? path : spec;
100
102
  result.specs.push(key);
101
103
  result.paths[key] = path;
104
+ if (done.has(identity))
105
+ return;
106
+ active.push(identity);
102
107
  if (root) {
103
108
  const manifestPath = join(root, 'package.json');
104
109
  const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
@@ -151,7 +156,7 @@ export async function resolveChildLaunch(options, trustedPaths = []) {
151
156
  return { resolution, fullResolution };
152
157
  }
153
158
  /** Validate actual child registration, never the parent's catalog. Groups require one physical candidate. */
154
- export async function checkChildPreflight(plan, { registry, tools, model }, load = loadContract) {
159
+ export async function checkChildPreflight(plan, { registry, tools, registeredTools = [], model }, load = loadContract) {
155
160
  if (plan.configSnapshot && JSON.stringify(configSnapshot(plan.configSnapshot.map(item => item.dir))) !== JSON.stringify(plan.configSnapshot))
156
161
  throw new Error('Child configuration drift: agent or project JSON configuration changed. Launch again.');
157
162
  for (const item of plan.fingerprints)
@@ -175,7 +180,14 @@ export async function checkChildPreflight(plan, { registry, tools, model }, load
175
180
  if (!available.some(m => m.provider === group.provider && m.api !== 'pi-virtual' &&
176
181
  (group.ids.includes(m.id) || (group.prefix && m.id.startsWith(group.prefix)))))
177
182
  throw new Error(`Child has no available candidate for ${group.provider}: ${group.ids.join(', ')}${group.prefix ? ` (prefix ${group.prefix})` : ''}. Check extension, models and credentials.`);
178
- for (const tool of plan.tools)
179
- if (!tools.includes(tool))
183
+ const inactive = [];
184
+ for (const tool of plan.tools) {
185
+ if (tools.includes(tool))
186
+ continue;
187
+ if (!plan.optionalTrustedTools?.includes(tool) || !registeredTools.includes(tool)) {
180
188
  throw new Error(`Child requested tool ${tool} is unavailable.`);
189
+ }
190
+ inactive.push(tool);
191
+ }
192
+ return inactive;
181
193
  }
@@ -20,7 +20,8 @@ import { readFileSync, realpathSync } from "node:fs";
20
20
  import { connect } from "node:net";
21
21
  import * as piSdk from "@earendil-works/pi-coding-agent";
22
22
  import { captureParkCheckpoint } from "./park-checkpoint.domain.mjs";
23
- import { ACKNOWLEDGE_OPERATION_TOOL, OPERATION_BRIDGE_ENV_KEYS, OPERATION_BRIDGE_TOOL_NAMES, OPERATION_BRIDGE_VERSION, OPERATIONS_ATTEMPT_ID_ENV, OPERATIONS_CHILD_ID_ENV, OPERATIONS_CONVERSATION_ID_ENV, OPERATIONS_ENABLED_ENV, OPERATIONS_ENDPOINT_ENV, OPERATIONS_RUN_ID_ENV, OPERATIONS_TOKEN_ENV, OPERATIONS_WRITER_LEASE_ID_ENV, WAIT_OPERATIONS_TOOL, OperationBridgeError, OperationToolError, cloneJson, deepFreeze, descriptorFingerprint, findBridgeEnvironmentKey, isLaunchTool, normalizeWaitForOperationsResult, requiresParkCheckpoint, parseBridgeEndpoint, validateJsonSchemaSupport, redactSecret, } from "./operation-bridge-types.domain.mjs";
23
+ import { supportsPromptSections } from "./shared-execution-policy.domain.mjs";
24
+ import { ACKNOWLEDGE_OPERATION_TOOL, OPERATION_BRIDGE_ENV_KEYS, OPERATION_BRIDGE_TOOL_NAMES, OPERATION_BRIDGE_VERSION, OPERATIONS_ATTEMPT_ID_ENV, OPERATIONS_CHILD_ID_ENV, OPERATIONS_CONVERSATION_ID_ENV, OPERATIONS_DEADLINE_AT_ENV, OPERATIONS_ENABLED_ENV, OPERATIONS_ENDPOINT_ENV, OPERATIONS_RUN_ID_ENV, OPERATIONS_TOKEN_ENV, OPERATIONS_WRITER_LEASE_ID_ENV, WAIT_OPERATIONS_TOOL, assertWaitToolDependencies, OperationBridgeError, OperationToolError, cloneJson, deepFreeze, descriptorFingerprint, findBridgeEnvironmentKey, isLaunchTool, normalizeWaitForOperationsResult, requiresParkCheckpoint, parseBridgeEndpoint, validateJsonSchemaSupport, validateJsonSchema, redactSecret, } from "./operation-bridge-types.domain.mjs";
24
25
  const ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,255}$/;
25
26
  /** Namespace access keeps an older SDK without a VERSION export from failing at import time. */
26
27
  const PI_CODING_AGENT_VERSION = piSdk.VERSION;
@@ -66,6 +67,10 @@ export function readChildOperationBridgeConfig(env = process.env) {
66
67
  const token = env[OPERATIONS_TOKEN_ENV];
67
68
  const runId = env[OPERATIONS_RUN_ID_ENV];
68
69
  const conversationId = env[OPERATIONS_CONVERSATION_ID_ENV];
70
+ const deadline = env[OPERATIONS_DEADLINE_AT_ENV];
71
+ if (deadline !== undefined && (!/^\d+$/.test(deadline) || !Number.isSafeInteger(Number(deadline)))) {
72
+ return { status: "invalid", reason: "operation bridge assignment deadline is invalid" };
73
+ }
69
74
  try {
70
75
  parseBridgeEndpoint(endpoint);
71
76
  }
@@ -85,6 +90,7 @@ export function readChildOperationBridgeConfig(env = process.env) {
85
90
  token,
86
91
  runId,
87
92
  conversationId,
93
+ ...(deadline !== undefined ? { deadlineAt: Number(deadline) || null } : {}),
88
94
  ...(env[OPERATIONS_ATTEMPT_ID_ENV] ? { attemptId: env[OPERATIONS_ATTEMPT_ID_ENV] } : {}),
89
95
  ...(env[OPERATIONS_WRITER_LEASE_ID_ENV] ? { writerLeaseId: env[OPERATIONS_WRITER_LEASE_ID_ENV] } : {}),
90
96
  ...(env[OPERATIONS_CHILD_ID_ENV] ? { childId: env[OPERATIONS_CHILD_ID_ENV] } : {}),
@@ -402,6 +408,7 @@ export function verifyDescriptor(value, config) {
402
408
  }));
403
409
  }
404
410
  const capabilities = validateCapabilities(record.capabilities);
411
+ assertWaitToolDependencies(capabilities, [...seen]);
405
412
  if (seen.has(WAIT_OPERATIONS_TOOL) && !(capabilities.wait && capabilities.parking)) {
406
413
  throw new OperationBridgeError("invalid-request", "parent exposed wait_for_operations without a parking capability");
407
414
  }
@@ -621,7 +628,17 @@ export function installChildOperationBridge(pi, options = {}) {
621
628
  let installed = false;
622
629
  let starting;
623
630
  let completingPark = false;
631
+ let completion = { correctionUsed: false, reported: false };
632
+ let reportError;
633
+ let bridgeConfig;
624
634
  const env = options.env ?? process.env;
635
+ const completionEntryType = "pi-subagent-completion";
636
+ const canCorrectCompletion = (signal) => state.status === "ready"
637
+ && !completion.correctionUsed && !completion.reported && !signal?.aborted
638
+ && (bridgeConfig?.deadlineAt == null || Date.now() < bridgeConfig.deadlineAt);
639
+ function saveCompletion() {
640
+ pi.appendEntry(completionEntryType, { attemptId: bridgeConfig?.attemptId ?? bridgeConfig?.runId, ...completion });
641
+ }
625
642
  const handle = {
626
643
  getState: () => ({ ...state, ...(state.descriptor ? { descriptor: state.descriptor } : {}) }),
627
644
  };
@@ -655,7 +672,7 @@ export function installChildOperationBridge(pi, options = {}) {
655
672
  if (activeToolExecutions === 0)
656
673
  restoreBridgeEnvironment();
657
674
  });
658
- pi.on("session_start", async (_event, _ctx) => {
675
+ pi.on("session_start", async (_event, ctx) => {
659
676
  if (installed || starting)
660
677
  return starting;
661
678
  starting = (async () => {
@@ -669,6 +686,7 @@ export function installChildOperationBridge(pi, options = {}) {
669
686
  return;
670
687
  }
671
688
  state.status = "connecting";
689
+ bridgeConfig = read.config;
672
690
  options.onDiagnostic?.({ event: "connecting" });
673
691
  const active = (options.clientFactory ?? ((config) => createOperationBridgeClient(config, {
674
692
  requestTimeoutMs: options.requestTimeoutMs,
@@ -686,6 +704,19 @@ export function installChildOperationBridge(pi, options = {}) {
686
704
  }
687
705
  client = active;
688
706
  state.descriptor = descriptor;
707
+ if (descriptor.capabilities.reportAssignment) {
708
+ const entries = ctx.sessionManager.getEntries();
709
+ for (let index = entries.length - 1; index >= 0; index--) {
710
+ const entry = entries[index];
711
+ if (entry.type !== "custom" || entry.customType !== completionEntryType)
712
+ continue;
713
+ const data = entry.data;
714
+ if (data?.attemptId !== (read.config.attemptId ?? read.config.runId))
715
+ continue;
716
+ completion = { correctionUsed: data.correctionUsed === true, reported: data.reported === true };
717
+ break;
718
+ }
719
+ }
689
720
  try {
690
721
  registerTools(descriptor, state.parkingSupported === true);
691
722
  }
@@ -703,6 +734,33 @@ export function installChildOperationBridge(pi, options = {}) {
703
734
  })().finally(() => { starting = undefined; });
704
735
  return starting;
705
736
  });
737
+ pi.on("before_agent_start", (event, ctx) => {
738
+ if (!state.descriptor?.capabilities.reportAssignment)
739
+ return;
740
+ const instruction = `Assignment completion: call report_assignment_result before returning. Evidence sources must resolve inside this assigned workspace: ${JSON.stringify(ctx.cwd)}. A sibling output directory is outside that boundary; use an existing workspace file or place the reportable artifact inside the workspace. Use offset and max_bytes for evidence larger than 65536 bytes. Continue remaining local work within the existing deadline, or report a concrete blocker; do not infer a tool-call budget from the number of calls you have made.`;
741
+ if (!supportsPromptSections(event.systemPromptOptions))
742
+ return { systemPrompt: `${event.systemPrompt}\n\n${instruction}` };
743
+ const prompt = event.systemPromptOptions;
744
+ (prompt.sections ??= {}).assignment_completion = instruction;
745
+ });
746
+ pi.on("agent_end", (event, ctx) => {
747
+ if (!state.descriptor?.capabilities.reportAssignment || !canCorrectCompletion(ctx.signal))
748
+ return;
749
+ let last;
750
+ for (let index = event.messages.length - 1; index >= 0; index--) {
751
+ const message = event.messages[index];
752
+ if (message.role !== "assistant")
753
+ continue;
754
+ last = message;
755
+ break;
756
+ }
757
+ if (last?.stopReason !== "stop")
758
+ return;
759
+ completion.correctionUsed = true;
760
+ saveCompletion();
761
+ pi.sendMessage({ customType: "assignment-completion-correction", display: false,
762
+ content: `The assignment has no accepted report. ${reportError ? `The latest report was refused: ${reportError}. ` : ""}This is the one completion correction for this execution attempt, within its original authority and deadline. Finish available remaining work, inspect and acknowledge any outstanding operation evidence, then call report_assignment_result with workspace evidence. If progress is blocked or work remains, report incomplete with remaining_work and the concrete blocker. Do not claim completion from process exit or final prose.` }, { deliverAs: "followUp", triggerTurn: true });
763
+ });
706
764
  pi.on("message_end", (event) => {
707
765
  const message = event.message;
708
766
  if (message.role !== "assistant" || !Array.isArray(message.content))
@@ -777,6 +835,8 @@ export function installChildOperationBridge(pi, options = {}) {
777
835
  return await invokeTool(tool, toolCallId, params, signal);
778
836
  }
779
837
  catch (error) {
838
+ if (tool.name === "report_assignment_result")
839
+ reportError = redactSecret(error instanceof Error ? error.message : String(error)).slice(0, 2048);
780
840
  return toolErrorResult(error);
781
841
  }
782
842
  },
@@ -790,6 +850,13 @@ export function installChildOperationBridge(pi, options = {}) {
790
850
  throw new OperationToolError("tool parameters must be an object");
791
851
  }
792
852
  const params = rawParams;
853
+ if (tool.name === "report_assignment_result" && params.status === "incomplete" && !params.blocker
854
+ && Array.isArray(params.remaining_work) && params.remaining_work.length > 0
855
+ && validateJsonSchema(tool.parameters, params).ok && canCorrectCompletion(signal)) {
856
+ completion.correctionUsed = true;
857
+ saveCompletion();
858
+ throw new OperationToolError("The incomplete report has not been accepted. Use the one completion correction to continue the listed remaining local work within the original authority and deadline, then report the result. If blocked or still incomplete, report that explicitly; no further automatic correction will be requested.");
859
+ }
793
860
  if (isLaunchTool(tool.name, params)) {
794
861
  const bridgeEnvironmentField = findBridgeEnvironmentKey(params);
795
862
  if (bridgeEnvironmentField) {
@@ -797,6 +864,17 @@ export function installChildOperationBridge(pi, options = {}) {
797
864
  }
798
865
  }
799
866
  const raw = await client.request(tool.name, params, { signal });
867
+ if (tool.name === "report_assignment_result" && raw && typeof raw === "object"
868
+ && ["complete", "incomplete"].includes(String(raw.status))) {
869
+ completion.reported = true;
870
+ reportError = undefined;
871
+ saveCompletion();
872
+ }
873
+ if (tool.name === ACKNOWLEDGE_OPERATION_TOOL && params.disposition === "assignment-complete"
874
+ && raw && typeof raw === "object" && raw.phase === "consumed") {
875
+ completion.reported = true;
876
+ saveCompletion();
877
+ }
800
878
  if (tool.name === WAIT_OPERATIONS_TOOL) {
801
879
  return waitToolResult(toolCallId, raw);
802
880
  }
@@ -20,6 +20,7 @@ import { connect, type Socket } from "node:net";
20
20
  import * as piSdk from "@earendil-works/pi-coding-agent";
21
21
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
22
22
  import { captureParkCheckpoint, type ParkCheckpoint } from "./park-checkpoint.ts";
23
+ import { supportsPromptSections } from "./shared-execution-policy.ts";
23
24
  import {
24
25
  ACKNOWLEDGE_OPERATION_TOOL,
25
26
  OPERATION_BRIDGE_ENV_KEYS,
@@ -28,12 +29,14 @@ import {
28
29
  OPERATIONS_ATTEMPT_ID_ENV,
29
30
  OPERATIONS_CHILD_ID_ENV,
30
31
  OPERATIONS_CONVERSATION_ID_ENV,
32
+ OPERATIONS_DEADLINE_AT_ENV,
31
33
  OPERATIONS_ENABLED_ENV,
32
34
  OPERATIONS_ENDPOINT_ENV,
33
35
  OPERATIONS_RUN_ID_ENV,
34
36
  OPERATIONS_TOKEN_ENV,
35
37
  OPERATIONS_WRITER_LEASE_ID_ENV,
36
38
  WAIT_OPERATIONS_TOOL,
39
+ assertWaitToolDependencies,
37
40
  OperationBridgeError,
38
41
  OperationToolError,
39
42
  type JsonRecord,
@@ -54,6 +57,7 @@ import {
54
57
  requiresParkCheckpoint,
55
58
  parseBridgeEndpoint,
56
59
  validateJsonSchemaSupport,
60
+ validateJsonSchema,
57
61
  redactSecret,
58
62
  } from "./operation-bridge-types.ts";
59
63
 
@@ -67,6 +71,7 @@ export interface ChildOperationBridgeConfig {
67
71
  attemptId?: string;
68
72
  writerLeaseId?: string;
69
73
  childId?: string;
74
+ deadlineAt?: number | null;
70
75
  requestTimeoutMs?: number;
71
76
  }
72
77
 
@@ -120,6 +125,10 @@ export function readChildOperationBridgeConfig(env: NodeJS.ProcessEnv = process.
120
125
  const token = env[OPERATIONS_TOKEN_ENV]!;
121
126
  const runId = env[OPERATIONS_RUN_ID_ENV]!;
122
127
  const conversationId = env[OPERATIONS_CONVERSATION_ID_ENV]!;
128
+ const deadline = env[OPERATIONS_DEADLINE_AT_ENV];
129
+ if (deadline !== undefined && (!/^\d+$/.test(deadline) || !Number.isSafeInteger(Number(deadline)))) {
130
+ return { status: "invalid", reason: "operation bridge assignment deadline is invalid" };
131
+ }
123
132
  try {
124
133
  parseBridgeEndpoint(endpoint);
125
134
  } catch {
@@ -138,6 +147,7 @@ export function readChildOperationBridgeConfig(env: NodeJS.ProcessEnv = process.
138
147
  token,
139
148
  runId,
140
149
  conversationId,
150
+ ...(deadline !== undefined ? { deadlineAt: Number(deadline) || null } : {}),
141
151
  ...(env[OPERATIONS_ATTEMPT_ID_ENV] ? { attemptId: env[OPERATIONS_ATTEMPT_ID_ENV]! } : {}),
142
152
  ...(env[OPERATIONS_WRITER_LEASE_ID_ENV] ? { writerLeaseId: env[OPERATIONS_WRITER_LEASE_ID_ENV]! } : {}),
143
153
  ...(env[OPERATIONS_CHILD_ID_ENV] ? { childId: env[OPERATIONS_CHILD_ID_ENV]! } : {}),
@@ -488,6 +498,7 @@ export function verifyDescriptor(value: unknown, config: Pick<ChildOperationBrid
488
498
  }));
489
499
  }
490
500
  const capabilities = validateCapabilities(record.capabilities);
501
+ assertWaitToolDependencies(capabilities, [...seen]);
491
502
  if (seen.has(WAIT_OPERATIONS_TOOL) && !(capabilities.wait && capabilities.parking)) {
492
503
  throw new OperationBridgeError("invalid-request", "parent exposed wait_for_operations without a parking capability");
493
504
  }
@@ -809,7 +820,19 @@ export function installChildOperationBridge(
809
820
  let installed = false;
810
821
  let starting: Promise<void> | undefined;
811
822
  let completingPark = false;
823
+ let completion = { correctionUsed: false, reported: false };
824
+ let reportError: string | undefined;
825
+ let bridgeConfig: ChildOperationBridgeConfig | undefined;
812
826
  const env = options.env ?? process.env;
827
+ const completionEntryType = "pi-subagent-completion";
828
+
829
+ const canCorrectCompletion = (signal?: AbortSignal): boolean => state.status === "ready"
830
+ && !completion.correctionUsed && !completion.reported && !signal?.aborted
831
+ && (bridgeConfig?.deadlineAt == null || Date.now() < bridgeConfig.deadlineAt);
832
+
833
+ function saveCompletion(): void {
834
+ pi.appendEntry(completionEntryType, { attemptId: bridgeConfig?.attemptId ?? bridgeConfig?.runId, ...completion });
835
+ }
813
836
 
814
837
  const handle: ChildOperationBridgeHandle = {
815
838
  getState: () => ({ ...state, ...(state.descriptor ? { descriptor: state.descriptor } : {}) }),
@@ -843,7 +866,7 @@ export function installChildOperationBridge(
843
866
  if (activeToolExecutions === 0) restoreBridgeEnvironment();
844
867
  });
845
868
 
846
- pi.on("session_start", async (_event, _ctx) => {
869
+ pi.on("session_start", async (_event, ctx) => {
847
870
  if (installed || starting) return starting;
848
871
  starting = (async () => {
849
872
  const read = options.config
@@ -856,6 +879,7 @@ export function installChildOperationBridge(
856
879
  return;
857
880
  }
858
881
  state.status = "connecting";
882
+ bridgeConfig = read.config;
859
883
  options.onDiagnostic?.({ event: "connecting" });
860
884
  const active = (options.clientFactory ?? ((config) => createOperationBridgeClient(config, {
861
885
  requestTimeoutMs: options.requestTimeoutMs,
@@ -872,6 +896,17 @@ export function installChildOperationBridge(
872
896
  }
873
897
  client = active;
874
898
  state.descriptor = descriptor;
899
+ if (descriptor.capabilities.reportAssignment) {
900
+ const entries = ctx.sessionManager.getEntries();
901
+ for (let index = entries.length - 1; index >= 0; index--) {
902
+ const entry = entries[index]!;
903
+ if (entry.type !== "custom" || entry.customType !== completionEntryType) continue;
904
+ const data = entry.data as { attemptId?: string; correctionUsed?: boolean; reported?: boolean } | undefined;
905
+ if (data?.attemptId !== (read.config.attemptId ?? read.config.runId)) continue;
906
+ completion = { correctionUsed: data.correctionUsed === true, reported: data.reported === true };
907
+ break;
908
+ }
909
+ }
875
910
  try {
876
911
  registerTools(descriptor, state.parkingSupported === true);
877
912
  } catch (error) {
@@ -889,6 +924,31 @@ export function installChildOperationBridge(
889
924
  return starting;
890
925
  });
891
926
 
927
+ pi.on("before_agent_start", (event, ctx) => {
928
+ if (!state.descriptor?.capabilities.reportAssignment) return;
929
+ const instruction = `Assignment completion: call report_assignment_result before returning. Evidence sources must resolve inside this assigned workspace: ${JSON.stringify(ctx.cwd)}. A sibling output directory is outside that boundary; use an existing workspace file or place the reportable artifact inside the workspace. Use offset and max_bytes for evidence larger than 65536 bytes. Continue remaining local work within the existing deadline, or report a concrete blocker; do not infer a tool-call budget from the number of calls you have made.`;
930
+ if (!supportsPromptSections(event.systemPromptOptions)) return { systemPrompt: `${event.systemPrompt}\n\n${instruction}` };
931
+ const prompt = event.systemPromptOptions as { sections?: Record<string, string> };
932
+ (prompt.sections ??= {}).assignment_completion = instruction;
933
+ });
934
+
935
+ pi.on("agent_end", (event, ctx) => {
936
+ if (!state.descriptor?.capabilities.reportAssignment || !canCorrectCompletion(ctx.signal)) return;
937
+ let last;
938
+ for (let index = event.messages.length - 1; index >= 0; index--) {
939
+ const message = event.messages[index]!;
940
+ if (message.role !== "assistant") continue;
941
+ last = message;
942
+ break;
943
+ }
944
+ if (last?.stopReason !== "stop") return;
945
+ completion.correctionUsed = true;
946
+ saveCompletion();
947
+ pi.sendMessage({ customType: "assignment-completion-correction", display: false,
948
+ content: `The assignment has no accepted report. ${reportError ? `The latest report was refused: ${reportError}. ` : ""}This is the one completion correction for this execution attempt, within its original authority and deadline. Finish available remaining work, inspect and acknowledge any outstanding operation evidence, then call report_assignment_result with workspace evidence. If progress is blocked or work remains, report incomplete with remaining_work and the concrete blocker. Do not claim completion from process exit or final prose.` },
949
+ { deliverAs: "followUp", triggerTurn: true });
950
+ });
951
+
892
952
  pi.on("message_end", (event) => {
893
953
  const message = event.message as { role?: string; content?: unknown };
894
954
  if (message.role !== "assistant" || !Array.isArray(message.content)) return;
@@ -963,6 +1023,7 @@ export function installChildOperationBridge(
963
1023
  try {
964
1024
  return await invokeTool(tool, toolCallId, params, signal);
965
1025
  } catch (error) {
1026
+ if (tool.name === "report_assignment_result") reportError = redactSecret(error instanceof Error ? error.message : String(error)).slice(0, 2048);
966
1027
  return toolErrorResult(error);
967
1028
  }
968
1029
  },
@@ -981,6 +1042,13 @@ export function installChildOperationBridge(
981
1042
  throw new OperationToolError("tool parameters must be an object");
982
1043
  }
983
1044
  const params = rawParams as JsonRecord;
1045
+ if (tool.name === "report_assignment_result" && params.status === "incomplete" && !params.blocker
1046
+ && Array.isArray(params.remaining_work) && params.remaining_work.length > 0
1047
+ && validateJsonSchema(tool.parameters, params).ok && canCorrectCompletion(signal)) {
1048
+ completion.correctionUsed = true;
1049
+ saveCompletion();
1050
+ throw new OperationToolError("The incomplete report has not been accepted. Use the one completion correction to continue the listed remaining local work within the original authority and deadline, then report the result. If blocked or still incomplete, report that explicitly; no further automatic correction will be requested.");
1051
+ }
984
1052
  if (isLaunchTool(tool.name, params)) {
985
1053
  const bridgeEnvironmentField = findBridgeEnvironmentKey(params);
986
1054
  if (bridgeEnvironmentField) {
@@ -991,6 +1059,17 @@ export function installChildOperationBridge(
991
1059
  }
992
1060
  }
993
1061
  const raw = await client.request(tool.name, params, { signal });
1062
+ if (tool.name === "report_assignment_result" && raw && typeof raw === "object"
1063
+ && ["complete", "incomplete"].includes(String((raw as JsonRecord).status))) {
1064
+ completion.reported = true;
1065
+ reportError = undefined;
1066
+ saveCompletion();
1067
+ }
1068
+ if (tool.name === ACKNOWLEDGE_OPERATION_TOOL && params.disposition === "assignment-complete"
1069
+ && raw && typeof raw === "object" && (raw as JsonRecord).phase === "consumed") {
1070
+ completion.reported = true;
1071
+ saveCompletion();
1072
+ }
994
1073
  if (tool.name === WAIT_OPERATIONS_TOOL) {
995
1074
  return waitToolResult(toolCallId, raw);
996
1075
  }
@@ -15,12 +15,19 @@ export default function childPreflight(pi) {
15
15
  catch (error) {
16
16
  fail(error);
17
17
  }
18
+ const reported = new Set();
18
19
  // The task guard activates its adapters on session_start. Check after every
19
20
  // startup handler has finished, before the first request (and subsequent runs).
20
21
  const check = async (ctx, tools) => {
21
22
  try {
22
- await checkChildPreflight({ ...plan, tools }, { registry: ctx.modelRegistry,
23
- tools: pi.getActiveTools(), model: ctx.model });
23
+ const inactive = await checkChildPreflight({ ...plan, tools }, { registry: ctx.modelRegistry,
24
+ tools: pi.getActiveTools(), registeredTools: pi.getAllTools?.().map(tool => tool.name), model: ctx.model });
25
+ const newlyInactive = inactive.filter(tool => !reported.has(tool));
26
+ if (newlyInactive.length) {
27
+ for (const tool of newlyInactive)
28
+ reported.add(tool);
29
+ process.stderr.write(`Subagent child preflight: inherited trusted tools are inactive in this child: ${newlyInactive.join(', ')}. Continuing without them.\n`);
30
+ }
24
31
  }
25
32
  catch (error) {
26
33
  fail(error);
@@ -0,0 +1,7 @@
1
+ // Generated fixed launch domain from packages/pi-better-subagents/child-process-list.ts. Do not edit directly.
2
+ import { createProcessListToolDefinition } from "./shared-task-process-list.domain.mjs";
3
+ /** Keep the fixed, bounded inventory contract when no task sandbox is active. */
4
+ export default function childProcessList(pi) {
5
+ const tool = createProcessListToolDefinition(process.cwd(), { requireLaunchPlan: () => ({ confined: false }) }, () => "read");
6
+ pi.registerTool(tool);
7
+ }