pi-better-server 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (340) hide show
  1. package/package.json +7 -3
  2. package/scripts/copy-pi-test-providers.mjs +10 -0
  3. package/scripts/event-publication/README.md +26 -0
  4. package/scripts/event-publication/commit.mjs +21 -0
  5. package/scripts/event-publication/measure.mjs +37 -5
  6. package/scripts/event-publication/writer.mjs +3 -8
  7. package/scripts/measure-full-runtime/frontend.ts +10 -2
  8. package/scripts/measure-full-runtime/probe.mjs +4 -2
  9. package/scripts/measure-full-runtime/recovery-trace-loader.mjs +51 -0
  10. package/scripts/measure-full-runtime/recovery-trace.mjs +16 -0
  11. package/scripts/measure-full-runtime.mjs +2 -0
  12. package/scripts/measure-shared-reads.mjs +2 -1
  13. package/scripts/private-runtime/package-lock.json +18 -0
  14. package/scripts/private-runtime/package.json +4 -1
  15. package/scripts/source-provenance.mjs +2 -2
  16. package/scripts/test-on-pi.sh +2 -9
  17. package/src/handshake.ts +1 -1
  18. package/src/hosted-session.ts +32 -4
  19. package/src/maintenance.ts +35 -7
  20. package/src/registry.ts +28 -4
  21. package/src/runtime/attempt-invalidation.ts +54 -0
  22. package/src/runtime/background-history.ts +151 -45
  23. package/src/runtime/background-policy.ts +9 -4
  24. package/src/runtime/background-tools.ts +181 -27
  25. package/src/runtime/background.ts +365 -70
  26. package/src/runtime/cancellation.ts +28 -7
  27. package/src/runtime/catalog-sources.ts +199 -0
  28. package/src/runtime/catalog.ts +53 -21
  29. package/src/runtime/client.ts +22 -2
  30. package/src/runtime/domain/assignment-inbox.mjs +119 -0
  31. package/src/runtime/domain/assignment-observation.d.mts +1 -1
  32. package/src/runtime/domain/assignment-observation.mjs +43 -35
  33. package/src/runtime/domain/background/process-identity.mjs +20 -2
  34. package/src/runtime/domain/background/process.mjs +52 -14
  35. package/src/runtime/domain/background/registry.mjs +61 -3
  36. package/src/runtime/domain/background/supervisor/store.mjs +3 -3
  37. package/src/runtime/domain/background/supervisor/supervisor.mjs +9 -3
  38. package/src/runtime/domain/background/types.mjs +1 -0
  39. package/src/runtime/domain/background-service/adapter-contract.domain.mjs +1 -1
  40. package/src/runtime/domain/background-service/adapter-contract.ts +1 -1
  41. package/src/runtime/domain/background-service/goal-provider.domain.mjs +35 -16
  42. package/src/runtime/domain/background-service/goal-provider.ts +31 -16
  43. package/src/runtime/domain/background-service/index.domain.mjs +25 -9
  44. package/src/runtime/domain/background-service/index.ts +25 -9
  45. package/src/runtime/domain/background-service/managed-authority.domain.mjs +6 -3
  46. package/src/runtime/domain/background-service/managed-authority.ts +5 -3
  47. package/src/runtime/domain/background-service/managed-client.domain.mjs +21 -7
  48. package/src/runtime/domain/background-service/managed-client.ts +20 -7
  49. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +159 -19
  50. package/src/runtime/domain/background-service/managed-frontend.ts +135 -19
  51. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +21 -5
  52. package/src/runtime/domain/background-service/navigator-provider.ts +19 -5
  53. package/src/runtime/domain/background-service/observed-wait-client.domain.mjs +6 -0
  54. package/src/runtime/domain/background-service/observed-wait-client.ts +10 -0
  55. package/src/runtime/domain/background-service/observed-waits.domain.mjs +372 -57
  56. package/src/runtime/domain/background-service/observed-waits.ts +321 -53
  57. package/src/runtime/domain/background-service/process-identity.domain.mjs +20 -2
  58. package/src/runtime/domain/background-service/process-identity.ts +18 -2
  59. package/src/runtime/domain/background-service/process.domain.mjs +52 -14
  60. package/src/runtime/domain/background-service/process.ts +48 -14
  61. package/src/runtime/domain/background-service/registry.domain.mjs +61 -3
  62. package/src/runtime/domain/background-service/registry.ts +53 -5
  63. package/src/runtime/domain/background-service/review-settings.domain.mjs +16 -0
  64. package/src/runtime/domain/background-service/review-settings.ts +18 -0
  65. package/src/runtime/domain/background-service/runtime.domain.mjs +40 -86
  66. package/src/runtime/domain/background-service/runtime.ts +27 -82
  67. package/src/runtime/domain/background-service/sandbox.domain.mjs +14 -15
  68. package/src/runtime/domain/background-service/sandbox.ts +14 -11
  69. package/src/runtime/domain/background-service/shared-callback-batcher.domain.mjs +8 -1
  70. package/src/runtime/domain/background-service/shared-callback-batcher.ts +11 -2
  71. package/src/runtime/domain/background-service/shared-navigator-panels.domain.mjs +24 -2
  72. package/src/runtime/domain/background-service/shared-navigator-panels.ts +26 -4
  73. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +273 -41
  74. package/src/runtime/domain/background-service/shared-navigator.ts +244 -40
  75. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  76. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +53 -41
  77. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  78. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  79. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
  80. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  81. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
  82. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.ts +14 -3
  83. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
  84. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +5 -3
  85. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +44 -4
  86. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +50 -2
  87. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  88. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +9 -0
  89. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
  90. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +12 -0
  91. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.domain.mjs +2 -0
  92. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.ts +2 -0
  93. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +42 -21
  94. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +40 -24
  95. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +26 -4
  96. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +40 -8
  97. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
  98. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  99. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.domain.mjs +1 -1
  100. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.ts +5 -1
  101. package/src/runtime/domain/background-service/shared-sandbox-core.ts +1 -1
  102. package/src/runtime/domain/background-service/shared-work-client.mjs +174 -7
  103. package/src/runtime/domain/background-service/stall.domain.mjs +5 -3
  104. package/src/runtime/domain/background-service/stall.ts +7 -4
  105. package/src/runtime/domain/background-service/supervised-progress.domain.mjs +42 -0
  106. package/src/runtime/domain/background-service/supervised-progress.ts +43 -0
  107. package/src/runtime/domain/background-service/supervisor/README.md +1 -4
  108. package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
  109. package/src/runtime/domain/background-service/supervisor/generated/process-identity.mjs +20 -2
  110. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +52 -14
  111. package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +47 -4
  112. package/src/runtime/domain/background-service/supervisor/generated/store.mjs +3 -3
  113. package/src/runtime/domain/background-service/supervisor/generated/watch-fingerprint.mjs +69 -0
  114. package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +47 -4
  115. package/src/runtime/domain/background-service/supervisor/runner.ts +38 -3
  116. package/src/runtime/domain/background-service/supervisor/store.domain.mjs +3 -3
  117. package/src/runtime/domain/background-service/supervisor/store.ts +3 -3
  118. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +9 -3
  119. package/src/runtime/domain/background-service/supervisor/supervisor.ts +6 -3
  120. package/src/runtime/domain/background-service/task-diagnostics.domain.mjs +1 -1
  121. package/src/runtime/domain/background-service/task-diagnostics.ts +1 -1
  122. package/src/runtime/domain/background-service/tools.domain.mjs +53 -40
  123. package/src/runtime/domain/background-service/tools.ts +67 -54
  124. package/src/runtime/domain/background-service/types.domain.mjs +1 -0
  125. package/src/runtime/domain/background-service/types.ts +7 -3
  126. package/src/runtime/domain/background-service/watch-fingerprint.domain.mjs +67 -0
  127. package/src/runtime/domain/background-service/watch-fingerprint.ts +70 -0
  128. package/src/runtime/domain/background-service/work-observation.domain.mjs +46 -20
  129. package/src/runtime/domain/background-service/work-observation.ts +46 -19
  130. package/src/runtime/domain/catalog/catalog-store.d.mts +9 -1
  131. package/src/runtime/domain/catalog/catalog-store.mjs +20 -22
  132. package/src/runtime/domain/coordinator/src/assignment-changes.mjs +75 -0
  133. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +2 -0
  134. package/src/runtime/domain/coordinator/src/background-requests.mjs +11 -2
  135. package/src/runtime/domain/coordinator/src/discovery.mjs +4 -2
  136. package/src/runtime/domain/coordinator/src/operations.mjs +44 -4
  137. package/src/runtime/domain/coordinator/src/outbox.mjs +7 -0
  138. package/src/runtime/domain/coordinator/src/result-supervision.mjs +12 -0
  139. package/src/runtime/domain/coordinator/src/rows.mjs +2 -0
  140. package/src/runtime/domain/coordinator/src/schema.mjs +42 -21
  141. package/src/runtime/domain/coordinator/src/store.mjs +26 -4
  142. package/src/runtime/domain/coordinator/src/subagent-launch.mjs +23 -1
  143. package/src/runtime/domain/coordinator/src/types.mjs +1 -1
  144. package/src/runtime/domain/health-observation.d.mts +3 -1
  145. package/src/runtime/domain/health-observation.mjs +189 -190
  146. package/src/runtime/domain/log-cursor.d.mts +2 -0
  147. package/src/runtime/domain/log-cursor.mjs +85 -16
  148. package/src/runtime/domain/log-paths.mjs +8 -1
  149. package/src/runtime/domain/parse.d.mts +4 -1
  150. package/src/runtime/domain/parse.mjs +58 -9
  151. package/src/runtime/domain/sandbox-policy/README.md +63 -65
  152. package/src/runtime/domain/sandbox-policy/commands.domain.mjs +11 -8
  153. package/src/runtime/domain/sandbox-policy/commands.ts +12 -7
  154. package/src/runtime/domain/sandbox-policy/index.domain.mjs +53 -9
  155. package/src/runtime/domain/sandbox-policy/index.ts +52 -9
  156. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  157. package/src/runtime/domain/sandbox-policy/permission-settings.domain.mjs +5 -2
  158. package/src/runtime/domain/sandbox-policy/permission-settings.ts +9 -2
  159. package/src/runtime/domain/sandbox-policy/permissions-page.domain.mjs +56 -137
  160. package/src/runtime/domain/sandbox-policy/permissions-page.ts +52 -130
  161. package/src/runtime/domain/sandbox-policy/permissions.domain.mjs +1 -6
  162. package/src/runtime/domain/sandbox-policy/permissions.ts +1 -6
  163. package/src/runtime/domain/sandbox-policy/shared-sandbox-core.ts +1 -1
  164. package/src/runtime/domain/sandbox-policy/shared-task-exec.domain.mjs +14 -1
  165. package/src/runtime/domain/sandbox-policy/shared-task-exec.ts +12 -1
  166. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.domain.mjs +140 -0
  167. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.ts +126 -0
  168. package/src/runtime/domain/sandbox-policy/shared-task-process-list.domain.mjs +3 -2
  169. package/src/runtime/domain/sandbox-policy/shared-task-process-list.ts +8 -2
  170. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.domain.mjs +4 -3
  171. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.ts +5 -3
  172. package/src/runtime/domain/sandbox-policy/shared-task-tools.domain.mjs +8 -5
  173. package/src/runtime/domain/sandbox-policy/shared-task-tools.ts +8 -5
  174. package/src/runtime/domain/session-store.mjs +7 -0
  175. package/src/runtime/domain/subagents/README.md +13 -11
  176. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +10 -7
  177. package/src/runtime/domain/subagents/assignment-outcomes.ts +9 -6
  178. package/src/runtime/domain/subagents/assignment-report.domain.mjs +109 -24
  179. package/src/runtime/domain/subagents/assignment-report.ts +103 -19
  180. package/src/runtime/domain/subagents/batch.mjs +13 -5
  181. package/src/runtime/domain/subagents/catalog-host-admission.domain.mjs +21 -3
  182. package/src/runtime/domain/subagents/catalog-host-admission.ts +19 -3
  183. package/src/runtime/domain/subagents/catalog-preferences.ts +1 -1
  184. package/src/runtime/domain/subagents/catalog-resolver.domain.mjs +35 -1
  185. package/src/runtime/domain/subagents/catalog-resolver.ts +35 -1
  186. package/src/runtime/domain/subagents/catalog-store.domain.mjs +20 -22
  187. package/src/runtime/domain/subagents/catalog-store.ts +27 -20
  188. package/src/runtime/domain/subagents/child-apply-patch.domain.mjs +13 -0
  189. package/src/runtime/domain/subagents/child-apply-patch.ts +13 -0
  190. package/src/runtime/domain/subagents/child-dependencies.mjs +27 -15
  191. package/src/runtime/domain/subagents/child-operations.domain.mjs +80 -2
  192. package/src/runtime/domain/subagents/child-operations.ts +80 -1
  193. package/src/runtime/domain/subagents/child-preflight.mjs +9 -2
  194. package/src/runtime/domain/subagents/child-process-list.domain.mjs +7 -0
  195. package/src/runtime/domain/subagents/child-process-list.ts +8 -0
  196. package/src/runtime/domain/subagents/cleanup.domain.mjs +11 -2
  197. package/src/runtime/domain/subagents/cleanup.ts +10 -2
  198. package/src/runtime/domain/subagents/config.domain.mjs +54 -2
  199. package/src/runtime/domain/subagents/config.ts +53 -3
  200. package/src/runtime/domain/subagents/continuation-authority.domain.mjs +5 -1
  201. package/src/runtime/domain/subagents/continuation-authority.ts +3 -1
  202. package/src/runtime/domain/subagents/continuation-runtime.domain.mjs +89 -0
  203. package/src/runtime/domain/subagents/continuation-runtime.ts +88 -0
  204. package/src/runtime/domain/subagents/continuation.domain.mjs +4 -2
  205. package/src/runtime/domain/subagents/continuation.ts +4 -2
  206. package/src/runtime/domain/subagents/extensions.mjs +11 -13
  207. package/src/runtime/domain/subagents/failures.domain.mjs +11 -2
  208. package/src/runtime/domain/subagents/failures.ts +10 -2
  209. package/src/runtime/domain/subagents/finalization.domain.mjs +16 -1
  210. package/src/runtime/domain/subagents/finalization.ts +21 -1
  211. package/src/runtime/domain/subagents/goal-provider.domain.mjs +44 -2
  212. package/src/runtime/domain/subagents/goal-provider.ts +44 -2
  213. package/src/runtime/domain/subagents/health-observation.domain.mjs +189 -190
  214. package/src/runtime/domain/subagents/health-observation.ts +43 -48
  215. package/src/runtime/domain/subagents/index.domain.mjs +457 -182
  216. package/src/runtime/domain/subagents/index.ts +417 -155
  217. package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +515 -0
  218. package/src/runtime/domain/subagents/isolated-workspace.ts +557 -0
  219. package/src/runtime/domain/subagents/launch-context.domain.mjs +24 -0
  220. package/src/runtime/domain/subagents/launch-context.ts +23 -0
  221. package/src/runtime/domain/subagents/launch-digest.mjs +6 -0
  222. package/src/runtime/domain/subagents/list.mjs +2 -2
  223. package/src/runtime/domain/subagents/log-cursor.domain.mjs +85 -16
  224. package/src/runtime/domain/subagents/log-cursor.ts +91 -15
  225. package/src/runtime/domain/subagents/managed-launch-bootstrap.mjs +2 -2
  226. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +27 -7
  227. package/src/runtime/domain/subagents/managed-launch-client.ts +28 -8
  228. package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +222 -14
  229. package/src/runtime/domain/subagents/managed-launch-host.ts +168 -15
  230. package/src/runtime/domain/subagents/managed-launch-journal.mjs +1 -5
  231. package/src/runtime/domain/subagents/managed-launch-port.ts +4 -0
  232. package/src/runtime/domain/subagents/operation-bridge-types.domain.mjs +27 -2
  233. package/src/runtime/domain/subagents/operation-bridge-types.ts +27 -2
  234. package/src/runtime/domain/subagents/output-payload.domain.mjs +24 -9
  235. package/src/runtime/domain/subagents/output-payload.ts +26 -12
  236. package/src/runtime/domain/subagents/owned-exit.domain.mjs +12 -0
  237. package/src/runtime/domain/subagents/owned-exit.ts +12 -0
  238. package/src/runtime/domain/subagents/package.json +4 -2
  239. package/src/runtime/domain/subagents/parse.domain.mjs +58 -9
  240. package/src/runtime/domain/subagents/parse.ts +57 -10
  241. package/src/runtime/domain/subagents/permission-policy.domain.mjs +32 -8
  242. package/src/runtime/domain/subagents/permission-policy.ts +41 -8
  243. package/src/runtime/domain/subagents/process-identity.mjs +33 -0
  244. package/src/runtime/domain/subagents/registry.domain.mjs +71 -51
  245. package/src/runtime/domain/subagents/registry.ts +77 -38
  246. package/src/runtime/domain/subagents/retained-result.domain.mjs +56 -0
  247. package/src/runtime/domain/subagents/retained-result.ts +65 -0
  248. package/src/runtime/domain/subagents/session-selection.domain.mjs +3 -1
  249. package/src/runtime/domain/subagents/session-selection.ts +2 -1
  250. package/src/runtime/domain/subagents/session-store.domain.mjs +7 -0
  251. package/src/runtime/domain/subagents/session-store.ts +9 -0
  252. package/src/runtime/domain/subagents/settings-page.domain.mjs +151 -107
  253. package/src/runtime/domain/subagents/settings-page.ts +147 -108
  254. package/src/runtime/domain/subagents/shared-callback-batcher.domain.mjs +8 -1
  255. package/src/runtime/domain/subagents/shared-callback-batcher.ts +11 -2
  256. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +28 -29
  257. package/src/runtime/domain/subagents/shared-catalog.ts +29 -21
  258. package/src/runtime/domain/subagents/shared-navigator-panels.domain.mjs +24 -2
  259. package/src/runtime/domain/subagents/shared-navigator-panels.ts +26 -4
  260. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +273 -41
  261. package/src/runtime/domain/subagents/shared-navigator.ts +244 -40
  262. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  263. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +53 -41
  264. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  265. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  266. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
  267. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  268. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
  269. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.ts +14 -3
  270. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
  271. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +5 -3
  272. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +44 -4
  273. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +50 -2
  274. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  275. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +9 -0
  276. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
  277. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +12 -0
  278. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.domain.mjs +2 -0
  279. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.ts +2 -0
  280. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +42 -21
  281. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +40 -24
  282. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +26 -4
  283. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +40 -8
  284. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
  285. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  286. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.domain.mjs +1 -1
  287. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.ts +5 -1
  288. package/src/runtime/domain/subagents/shared-sandbox-core.ts +1 -1
  289. package/src/runtime/domain/subagents/shared-task-exec.domain.mjs +14 -1
  290. package/src/runtime/domain/subagents/shared-task-exec.ts +12 -1
  291. package/src/runtime/domain/subagents/shared-task-process-identity.domain.mjs +140 -0
  292. package/src/runtime/domain/subagents/shared-task-process-identity.ts +126 -0
  293. package/src/runtime/domain/subagents/shared-task-process-list.domain.mjs +3 -2
  294. package/src/runtime/domain/subagents/shared-task-process-list.ts +8 -2
  295. package/src/runtime/domain/subagents/shared-task-sandbox.domain.mjs +4 -3
  296. package/src/runtime/domain/subagents/shared-task-sandbox.ts +5 -3
  297. package/src/runtime/domain/subagents/shared-task-tools.domain.mjs +8 -5
  298. package/src/runtime/domain/subagents/shared-task-tools.ts +8 -5
  299. package/src/runtime/domain/subagents/shared-work-client.mjs +174 -7
  300. package/src/runtime/domain/subagents/subagent-tools.domain.mjs +22 -38
  301. package/src/runtime/domain/subagents/subagent-tools.ts +28 -34
  302. package/src/runtime/domain/subagents/task-guard.domain.mjs +14 -1
  303. package/src/runtime/domain/subagents/task-guard.ts +13 -1
  304. package/src/runtime/domain/subagents/task-policy.domain.mjs +3 -2
  305. package/src/runtime/domain/subagents/task-policy.ts +8 -2
  306. package/src/runtime/domain/subagents/timing.domain.mjs +10 -1
  307. package/src/runtime/domain/subagents/timing.ts +10 -1
  308. package/src/runtime/domain/subagents/tools.domain.mjs +4 -8
  309. package/src/runtime/domain/subagents/tools.ts +4 -7
  310. package/src/runtime/domain/subagents/work-observation.domain.mjs +102 -17
  311. package/src/runtime/domain/subagents/work-observation.ts +91 -17
  312. package/src/runtime/domain/subagents/worker-operations-host.domain.mjs +9 -4
  313. package/src/runtime/domain/subagents/worker-operations-host.ts +12 -4
  314. package/src/runtime/domain/subagents/worker-waits.domain.mjs +89 -35
  315. package/src/runtime/domain/subagents/worker-waits.ts +93 -34
  316. package/src/runtime/domain/subagents/workspace-files.domain.mjs +103 -0
  317. package/src/runtime/domain/subagents/workspace-files.ts +114 -0
  318. package/src/runtime/domain/subagents/workspace-scope.domain.d.mts +38 -0
  319. package/src/runtime/domain/subagents/workspace-scope.domain.mjs +5 -0
  320. package/src/runtime/domain/subagents/workspace-scope.ts +6 -0
  321. package/src/runtime/domain/subagents/worktree-feedback.domain.mjs +55 -0
  322. package/src/runtime/domain/subagents/worktree-feedback.ts +77 -0
  323. package/src/runtime/health-config.ts +27 -11
  324. package/src/runtime/log-checkpoints.ts +117 -0
  325. package/src/runtime/mutation-store.ts +5 -4
  326. package/src/runtime/queries.ts +25 -2
  327. package/src/runtime/query-executor.ts +149 -28
  328. package/src/runtime/query-worker.mjs +106 -21
  329. package/src/runtime/read-model.ts +849 -121
  330. package/src/runtime/read-watchdog-probe.ts +4 -0
  331. package/src/runtime/result-supervision.ts +188 -16
  332. package/src/runtime/root.ts +5 -2
  333. package/src/runtime/source-watch.ts +175 -0
  334. package/src/runtime/subagent-launch.ts +11 -4
  335. package/src/runtime/work-budget.ts +130 -0
  336. package/src/runtime/work-client.d.mts +8 -0
  337. package/src/runtime/work-client.mjs +150 -7
  338. package/src/server.ts +104 -23
  339. package/src/session-activity.ts +26 -4
  340. package/src/version.ts +1 -1
@@ -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
+ }
@@ -0,0 +1,8 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { createProcessListToolDefinition } from "./shared-task-process-list.ts";
3
+
4
+ /** Keep the fixed, bounded inventory contract when no task sandbox is active. */
5
+ export default function childProcessList(pi: ExtensionAPI): void {
6
+ const tool = createProcessListToolDefinition(process.cwd(), { requireLaunchPlan: () => ({ confined: false }) }, () => "read");
7
+ pi.registerTool(tool as Parameters<ExtensionAPI["registerTool"]>[0]);
8
+ }
@@ -453,7 +453,7 @@ function removeAgedRunArtifacts(meta, cutoff, retained, scope, errors) {
453
453
  const fresh = readMeta(meta.id) ?? meta;
454
454
  if (!ageSweepEligible(fresh, cutoff, retained, scope))
455
455
  return false;
456
- if (removeMetaArtifacts(fresh, { keepWorkspace: scope.persistent.has(fresh.sessionId) }))
456
+ if (removeMetaArtifacts(fresh, { keepWorkspace: scope.persistent.has(fresh.sessionId), errors }))
457
457
  return true;
458
458
  errors.push(`${runDir(meta.id)}: could not remove run artifacts`);
459
459
  return false;
@@ -686,6 +686,7 @@ export function collectSizeCapEntries() {
686
686
  return [];
687
687
  }
688
688
  const entries = [];
689
+ const workspaces = new Map();
689
690
  for (const id of ids) {
690
691
  const dir = runDir(id);
691
692
  const meta = readMeta(id);
@@ -696,7 +697,15 @@ export function collectSizeCapEntries() {
696
697
  dirMtimeMs: safeStatMtime(dir) ?? 0,
697
698
  bytes: dirBytes(dir),
698
699
  });
700
+ const workspace = meta?.recipe?.workspace;
701
+ if (workspace && meta && meta.startedAt >= (workspaces.get(workspace.owner)?.started ?? 0)) {
702
+ workspaces.set(workspace.owner, { root: workspace.root, started: meta.startedAt, entry: entries[entries.length - 1] });
703
+ }
699
704
  }
705
+ // A restored conversation may have outlived its first attempt. Charge its
706
+ // one shared checkout to the most recent writer still in the registry.
707
+ for (const { root, entry } of workspaces.values())
708
+ entry.bytes += dirBytes(root);
700
709
  return entries;
701
710
  }
702
711
  /**
@@ -798,7 +807,7 @@ function removeSizeCappedRun(id, scope, errors) {
798
807
  return "retained";
799
808
  if (scope.occupancy.runIds.has(fresh.id))
800
809
  return "retained";
801
- if (removeMetaArtifacts(fresh, { keepWorkspace: scope.persistent.has(fresh.sessionId) }))
810
+ if (removeMetaArtifacts(fresh, { keepWorkspace: scope.persistent.has(fresh.sessionId), errors }))
802
811
  return "removed";
803
812
  errors.push(`${runDir(id)}: could not remove run artifacts`);
804
813
  return "failed";
@@ -615,7 +615,7 @@ function removeAgedRunArtifacts(
615
615
  if (!conversationQuiescentUnderLock(meta.sessionId, runIds)) return false;
616
616
  const fresh = readMeta(meta.id) ?? meta;
617
617
  if (!ageSweepEligible(fresh, cutoff, retained, scope)) return false;
618
- if (removeMetaArtifacts(fresh, { keepWorkspace: scope.persistent.has(fresh.sessionId) })) return true;
618
+ if (removeMetaArtifacts(fresh, { keepWorkspace: scope.persistent.has(fresh.sessionId), errors })) return true;
619
619
  errors.push(`${runDir(meta.id)}: could not remove run artifacts`);
620
620
  return false;
621
621
  }, () => false);
@@ -867,6 +867,7 @@ export function collectSizeCapEntries(): SizeCapEntry[] {
867
867
  return [];
868
868
  }
869
869
  const entries: SizeCapEntry[] = [];
870
+ const workspaces = new Map<string, { root: string; started: number; entry: SizeCapEntry }>();
870
871
  for (const id of ids) {
871
872
  const dir = runDir(id);
872
873
  const meta = readMeta(id);
@@ -877,7 +878,14 @@ export function collectSizeCapEntries(): SizeCapEntry[] {
877
878
  dirMtimeMs: safeStatMtime(dir) ?? 0,
878
879
  bytes: dirBytes(dir),
879
880
  });
881
+ const workspace = meta?.recipe?.workspace;
882
+ if (workspace && meta && meta.startedAt >= (workspaces.get(workspace.owner)?.started ?? 0)) {
883
+ workspaces.set(workspace.owner, { root: workspace.root, started: meta.startedAt, entry: entries[entries.length - 1]! });
884
+ }
880
885
  }
886
+ // A restored conversation may have outlived its first attempt. Charge its
887
+ // one shared checkout to the most recent writer still in the registry.
888
+ for (const { root, entry } of workspaces.values()) entry.bytes += dirBytes(root);
881
889
  return entries;
882
890
  }
883
891
 
@@ -999,7 +1007,7 @@ function removeSizeCappedRun(
999
1007
  if (!TERMINAL_CLEANUP_STATUSES.has(fresh.status)) return "retained";
1000
1008
  if (outcomeProtected(fresh)) return "retained";
1001
1009
  if (scope.occupancy.runIds.has(fresh.id)) return "retained";
1002
- if (removeMetaArtifacts(fresh, { keepWorkspace: scope.persistent.has(fresh.sessionId) })) return "removed";
1010
+ if (removeMetaArtifacts(fresh, { keepWorkspace: scope.persistent.has(fresh.sessionId), errors })) return "removed";
1003
1011
  errors.push(`${runDir(id)}: could not remove run artifacts`);
1004
1012
  return "failed";
1005
1013
  }, () => "retained");
@@ -9,12 +9,13 @@
9
9
  * `defaultTools` absent → the built-in SAFE_DEFAULT_TOOLS.
10
10
  * `defaultSkills` absent → the child discovers the user-level skills catalog.
11
11
  */
12
- import { existsSync, readFileSync, statSync } from "node:fs";
12
+ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
13
13
  import { fileURLToPath } from "node:url";
14
14
  import { dirname, isAbsolute, join } from "node:path";
15
15
  import { homedir } from "node:os";
16
+ import { toolPackage, supportsChildProvider } from "./shared-task-tools.domain.mjs";
16
17
  import { SELF_SPEC } from "./extensions.domain.mjs";
17
- import { installedPackage } from "./child-dependencies.mjs";
18
+ import { installedPackage, packageRoot } from "./child-dependencies.mjs";
18
19
  import { isDelegationMode } from "./delegation.domain.mjs";
19
20
  import { normalizeSkillExposure } from "./skills.domain.mjs";
20
21
  import { validatedTimingMinutes } from "./timing.domain.mjs";
@@ -131,6 +132,11 @@ export function writeSubagentSettings(settings, path = configPath()) {
131
132
  delegationMode: settings.delegationMode,
132
133
  maxConcurrent: settings.maxConcurrent,
133
134
  };
135
+ if (settings.gitWorkspace !== undefined) {
136
+ if (settings.gitWorkspace !== "clone" && settings.gitWorkspace !== "worktree")
137
+ throw new Error("Unknown Git workspace mode.");
138
+ next.gitWorkspace = settings.gitWorkspace;
139
+ }
134
140
  if (settings.maxMinutes !== undefined) {
135
141
  next.maxMinutes = validatedTimingMinutes(settings.maxMinutes, "maxMinutes");
136
142
  }
@@ -169,6 +175,52 @@ function writeConfigSettings(settings, path) {
169
175
  export function normalizeTools(list) {
170
176
  return list.split(",").map((t) => t.trim()).filter(Boolean).join(",");
171
177
  }
178
+ export const ORDINARY_TOOL_PROVIDERS = {
179
+ apply_patch: join(selfDir(), "child-apply-patch.ts"),
180
+ process_list: join(selfDir(), "child-process-list.ts"),
181
+ };
182
+ /** Check the owning package even when a mapping points directly to one of its files. */
183
+ export function supportedChildEntrypoint(name, pkg, path) {
184
+ return supportsChildProvider(name, pkg, packageRoot(path) ?? path);
185
+ }
186
+ /** Capture exact user-installed entrypoints already active in the foreground. */
187
+ export function activeChildProviders(pi) {
188
+ const active = new Set(pi.getActiveTools?.() ?? []);
189
+ const paths = new Map();
190
+ const seen = new Set();
191
+ for (const tool of pi.getAllTools?.() ?? []) {
192
+ if (!active.has(tool.name))
193
+ continue;
194
+ // The SDK reports active names. Conflicting registrations have no unique owner.
195
+ if (seen.has(tool.name)) {
196
+ paths.delete(tool.name);
197
+ continue;
198
+ }
199
+ seen.add(tool.name);
200
+ if (tool.sourceInfo?.scope !== "user")
201
+ continue;
202
+ const owner = toolPackage(tool);
203
+ if (!owner || !supportsChildProvider(tool.name, owner.package, owner.root))
204
+ continue;
205
+ try {
206
+ const path = realpathSync(tool.sourceInfo.path);
207
+ if (!statSync(path).isFile() || !supportedChildEntrypoint(tool.name, owner.package, path))
208
+ continue;
209
+ paths.set(tool.name, path);
210
+ }
211
+ catch { /* An unavailable entrypoint cannot supply a new worker. */ }
212
+ }
213
+ return Object.fromEntries(paths);
214
+ }
215
+ export function ordinaryChildConfig(config, activeProviders = {}) {
216
+ const packaged = config.toolExtensions === null ? undefined : bundledConfig().toolExtensions;
217
+ return { ...config, toolExtensions: { ...activeProviders, ...ORDINARY_TOOL_PROVIDERS, ...packaged, ...config.toolExtensions } };
218
+ }
219
+ export function addEditablePatch(names, excluded) {
220
+ const editable = names.some(name => (name === "edit" || name === "write") && !excluded.has(name));
221
+ if (editable && !excluded.has("apply_patch") && !names.includes("apply_patch"))
222
+ names.push("apply_patch");
223
+ }
172
224
  /** This package's own root — the extension dir, which is also `self`. */
173
225
  export function selfDir() {
174
226
  return dirname(fileURLToPath(import.meta.url));
@@ -9,12 +9,14 @@
9
9
  * `defaultSkills` absent → the child discovers the user-level skills catalog.
10
10
  */
11
11
 
12
- import { existsSync, readFileSync, statSync } from "node:fs";
12
+ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
13
13
  import { fileURLToPath } from "node:url";
14
14
  import { dirname, isAbsolute, join } from "node:path";
15
15
  import { homedir } from "node:os";
16
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
17
+ import { toolPackage, supportsChildProvider } from "./shared-task-tools.ts";
16
18
  import { SELF_SPEC } from "./extensions.ts";
17
- import { installedPackage } from "./child-dependencies.mjs";
19
+ import { installedPackage, packageRoot } from "./child-dependencies.mjs";
18
20
  import { isDelegationMode, type DelegationMode } from "./delegation.ts";
19
21
  import { normalizeSkillExposure } from "./skills.ts";
20
22
  import { validatedTimingMinutes, type TimingSettings } from "./timing.ts";
@@ -23,6 +25,7 @@ import { harnessSettingsPath, readHarnessSetting, updateHarnessSetting } from ".
23
25
  export interface SubagentConfig extends TimingSettings {
24
26
  /** Foreground delegation policy; /subagents mode overrides this for the current session. */
25
27
  delegationMode?: DelegationMode | null;
28
+ gitWorkspace?: "clone" | "worktree";
26
29
  defaultModel?: string | null;
27
30
  defaultTools?: string | null;
28
31
  /**
@@ -195,6 +198,7 @@ export function writeSubagentSettings(
195
198
  settings: {
196
199
  delegationMode: DelegationMode;
197
200
  maxConcurrent: number;
201
+ gitWorkspace?: "clone" | "worktree";
198
202
  maxMinutes?: number;
199
203
  /** Omit to preserve the saved value; `null` explicitly records discovery. */
200
204
  defaultSkills?: string[] | null;
@@ -209,11 +213,15 @@ export function writeSubagentSettings(
209
213
  if (!isConcurrencyCap(settings.maxConcurrent)) throw new Error("Concurrent subagents must be a positive whole number.");
210
214
  const next: {
211
215
  delegationMode: DelegationMode; maxConcurrent: number; maxMinutes?: number; defaultSkills?: string[] | null;
212
- toolWaitMinutes?: number; stuckMinutes?: number;
216
+ toolWaitMinutes?: number; stuckMinutes?: number; gitWorkspace?: "clone" | "worktree";
213
217
  } = {
214
218
  delegationMode: settings.delegationMode,
215
219
  maxConcurrent: settings.maxConcurrent,
216
220
  };
221
+ if (settings.gitWorkspace !== undefined) {
222
+ if (settings.gitWorkspace !== "clone" && settings.gitWorkspace !== "worktree") throw new Error("Unknown Git workspace mode.");
223
+ next.gitWorkspace = settings.gitWorkspace;
224
+ }
217
225
  if (settings.maxMinutes !== undefined) {
218
226
  next.maxMinutes = validatedTimingMinutes(settings.maxMinutes, "maxMinutes");
219
227
  }
@@ -251,6 +259,48 @@ export function normalizeTools(list: string): string {
251
259
  return list.split(",").map((t) => t.trim()).filter(Boolean).join(",");
252
260
  }
253
261
 
262
+ export const ORDINARY_TOOL_PROVIDERS: Readonly<Record<string, string>> = {
263
+ apply_patch: join(selfDir(), "child-apply-patch.ts"),
264
+ process_list: join(selfDir(), "child-process-list.ts"),
265
+ };
266
+
267
+ /** Check the owning package even when a mapping points directly to one of its files. */
268
+ export function supportedChildEntrypoint(name: string, pkg: string, path: string): boolean {
269
+ return supportsChildProvider(name, pkg, packageRoot(path) ?? path);
270
+ }
271
+
272
+ /** Capture exact user-installed entrypoints already active in the foreground. */
273
+ export function activeChildProviders(pi: Pick<ExtensionAPI, "getActiveTools" | "getAllTools">): Record<string, string> {
274
+ const active = new Set(pi.getActiveTools?.() ?? []);
275
+ const paths = new Map<string, string>();
276
+ const seen = new Set<string>();
277
+ for (const tool of pi.getAllTools?.() ?? []) {
278
+ if (!active.has(tool.name)) continue;
279
+ // The SDK reports active names. Conflicting registrations have no unique owner.
280
+ if (seen.has(tool.name)) { paths.delete(tool.name); continue; }
281
+ seen.add(tool.name);
282
+ if (tool.sourceInfo?.scope !== "user") continue;
283
+ const owner = toolPackage(tool);
284
+ if (!owner || !supportsChildProvider(tool.name, owner.package, owner.root)) continue;
285
+ try {
286
+ const path = realpathSync(tool.sourceInfo.path);
287
+ if (!statSync(path).isFile() || !supportedChildEntrypoint(tool.name, owner.package, path)) continue;
288
+ paths.set(tool.name, path);
289
+ } catch { /* An unavailable entrypoint cannot supply a new worker. */ }
290
+ }
291
+ return Object.fromEntries(paths);
292
+ }
293
+
294
+ export function ordinaryChildConfig(config: SubagentConfig, activeProviders: Record<string, string> = {}): SubagentConfig {
295
+ const packaged = config.toolExtensions === null ? undefined : bundledConfig().toolExtensions;
296
+ return { ...config, toolExtensions: { ...activeProviders, ...ORDINARY_TOOL_PROVIDERS, ...packaged, ...config.toolExtensions } };
297
+ }
298
+
299
+ export function addEditablePatch(names: string[], excluded: ReadonlySet<string>): void {
300
+ const editable = names.some(name => (name === "edit" || name === "write") && !excluded.has(name));
301
+ if (editable && !excluded.has("apply_patch") && !names.includes("apply_patch")) names.push("apply_patch");
302
+ }
303
+
254
304
  /** This package's own root — the extension dir, which is also `self`. */
255
305
  export function selfDir(): string {
256
306
  return dirname(fileURLToPath(import.meta.url));
@@ -13,8 +13,12 @@ export function intersectContinuationPermissions(captured, current) {
13
13
  const intersect = (old, fresh) => {
14
14
  if (!old || !fresh)
15
15
  throw new Error("Continuation permission profile unavailable");
16
+ if (!fresh.enabled)
17
+ return old.enabled ? { ...old } : { ...fresh };
18
+ if (!old.enabled)
19
+ return { ...fresh };
16
20
  const access = ["off", "read", "write", "read-write"];
17
- const value = { ...fresh, enabled: old.enabled || fresh.enabled };
21
+ const value = { ...fresh };
18
22
  for (const key of ["projectFiles", "outsideProject", "storedCredentials"]) {
19
23
  if (!access.includes(old[key]) || !access.includes(fresh[key]))
20
24
  throw new Error("Invalid continuation permission profile");
@@ -10,8 +10,10 @@ export function intersectContinuationPermissions(captured: any, current: any): a
10
10
  .sort((a, b) => a.name.localeCompare(b.name) || a.package.localeCompare(b.package)) };
11
11
  const intersect = (old: any, fresh: any) => {
12
12
  if (!old || !fresh) throw new Error("Continuation permission profile unavailable");
13
+ if (!fresh.enabled) return old.enabled ? { ...old } : { ...fresh };
14
+ if (!old.enabled) return { ...fresh };
13
15
  const access = ["off", "read", "write", "read-write"];
14
- const value = { ...fresh, enabled: old.enabled || fresh.enabled };
16
+ const value = { ...fresh };
15
17
  for (const key of ["projectFiles", "outsideProject", "storedCredentials"]) {
16
18
  if (!access.includes(old[key]) || !access.includes(fresh[key])) throw new Error("Invalid continuation permission profile");
17
19
  value[key] = access[Math.min(access.indexOf(old[key]), access.indexOf(fresh[key]))];
@@ -0,0 +1,89 @@
1
+ // Generated fixed launch domain from packages/pi-better-subagents/continuation-runtime.ts. Do not edit directly.
2
+ /** Select a saved, installed worker closure without changing the server owner. */
3
+ import { readFileSync, realpathSync, statSync } from "node:fs";
4
+ import { basename, dirname, join, normalize, sep } from "node:path";
5
+ const DOMAIN = join("src", "runtime", "domain", "subagents");
6
+ export function managedRuntimeRoot(domain) {
7
+ if (!domain.endsWith(`${sep}${DOMAIN}`))
8
+ return undefined;
9
+ const root = domain.slice(0, -(DOMAIN.length + 1));
10
+ return basename(dirname(root)) === "releases" && /^[a-f0-9]{64}$/.test(basename(root)) ? root : undefined;
11
+ }
12
+ /**
13
+ * Only sibling, published releases are eligible. User extensions retain their
14
+ * original identity check. Permission policy is still generated by the current
15
+ * server; a saved runtime does not grandfather its previous permission grants.
16
+ * Published releases are retained by the installer (it removes staging only).
17
+ * Any future release GC must treat LaunchRecipe.runtimeRoot as a reference.
18
+ */
19
+ export function selectContinuationRuntime(options) {
20
+ const current = managedRuntimeRoot(options.currentDir);
21
+ if (!current || !options.recipe)
22
+ return undefined;
23
+ const recipe = options.recipe;
24
+ // Upgrade recipes written before runtimeRoot existed using the mandatory
25
+ // harness control, never a user-selected/custom extension path.
26
+ const args = recipe.baseExtensionArgs ?? recipe.extensionArgs ?? [];
27
+ const steer = args.find((value, index) => args[index - 1] === "--extension" && value.endsWith(`${sep}${DOMAIN}${sep}child-steer.ts`));
28
+ const saved = recipe.runtimeRoot ?? (steer ? managedRuntimeRoot(dirname(steer)) : undefined);
29
+ if (!saved || saved === current)
30
+ return undefined;
31
+ const unavailable = (detail) => {
32
+ throw new Error(`Cannot resume: saved runtime ${basename(saved)} unavailable (${detail}). Restore that release or explicitly launch a replacement conversation; no worker was started.`);
33
+ };
34
+ if (normalize(saved) !== saved || dirname(saved) !== dirname(current) || !/^[a-f0-9]{64}$/.test(basename(saved))) {
35
+ return unavailable("not a sibling managed release");
36
+ }
37
+ function manifest(root) {
38
+ let value;
39
+ try {
40
+ if (realpathSync(root) !== root)
41
+ return unavailable("release path is not canonical");
42
+ value = JSON.parse(readFileSync(join(root, "runtime.json"), "utf8"));
43
+ }
44
+ catch {
45
+ return unavailable("missing or unreadable release manifest");
46
+ }
47
+ if (value.format !== 1 || value.root !== root || value.build?.contentId !== basename(root)
48
+ || value.node !== join(root, "node/bin/node") || value.installRoot !== dirname(dirname(root))) {
49
+ return unavailable("invalid release manifest");
50
+ }
51
+ return value;
52
+ }
53
+ const before = manifest(saved), now = manifest(current);
54
+ // These releases share the existing v1 worker admission/policy/bridge wire
55
+ // formats. Refuse SDK, Node, platform or protocol transitions rather than
56
+ // assuming that a new server can host any historic worker.
57
+ if (before.build.protocolVersion !== 1 || now.build.protocolVersion !== 1
58
+ || ["piSdkVersion", "nodeVersion", "platform"].some(key => !before.build[key] || before.build[key] !== now.build[key])) {
59
+ throw new Error(`Cannot resume: saved runtime ${basename(saved)} is incompatible with the current worker protocol, SDK or platform. Explicit replacement is required; no worker was started.`);
60
+ }
61
+ function required(path, directory = false) {
62
+ try {
63
+ const stat = statSync(path);
64
+ if (realpathSync(path) !== path || !(stat.isFile() || directory && stat.isDirectory()))
65
+ return unavailable("worker file is missing or redirected");
66
+ }
67
+ catch {
68
+ return unavailable("worker file is missing or unreadable");
69
+ }
70
+ return path;
71
+ }
72
+ const node = required(before.node);
73
+ const mapPath = (path) => path.startsWith(`${current}${sep}`)
74
+ ? required(join(saved, path.slice(current.length + 1)), true) : path;
75
+ return {
76
+ root: saved,
77
+ mapPath,
78
+ mapArgs: values => values.map((value, index) => values[index - 1] === "--extension" ? mapPath(value) : value),
79
+ command: command => {
80
+ // Only executable slots are rewritten. A prompt or arbitrary CLI
81
+ // value that happens to contain a runtime path must stay untouched.
82
+ const fileArgs = [...command.fileArgs];
83
+ fileArgs[0] = mapPath(fileArgs[0]);
84
+ if (basename(fileArgs[0]) === "task-runtime.mjs")
85
+ fileArgs[1] = mapPath(fileArgs[1]);
86
+ return { file: node, fileArgs };
87
+ },
88
+ };
89
+ }