@e4779/pi-fabric 0.131.4-fork.33 → 0.138.1-fork.1

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 (435) hide show
  1. package/README.md +8 -0
  2. package/dist/actors/context.d.ts.map +1 -1
  3. package/dist/agents/clone-first-worktree.d.ts +2 -0
  4. package/dist/agents/clone-first-worktree.d.ts.map +1 -1
  5. package/dist/agents/completion-inbox.d.ts +2 -1
  6. package/dist/agents/completion-inbox.d.ts.map +1 -1
  7. package/dist/agents/handoff.d.ts.map +1 -1
  8. package/dist/agents/manager.d.ts.map +1 -1
  9. package/dist/agents/worktree-manager.d.ts +4 -1
  10. package/dist/agents/worktree-manager.d.ts.map +1 -1
  11. package/dist/agents/worktree-paths.d.ts +8 -3
  12. package/dist/agents/worktree-paths.d.ts.map +1 -1
  13. package/dist/agents.js +6 -1
  14. package/dist/agents.js.map +1 -1
  15. package/dist/async-settlement.d.ts +1 -1
  16. package/dist/async-settlement.d.ts.map +1 -1
  17. package/dist/audit/details.d.ts.map +1 -1
  18. package/dist/capture/catalog.d.ts +2 -0
  19. package/dist/capture/catalog.d.ts.map +1 -1
  20. package/dist/capture/interceptor.d.ts.map +1 -1
  21. package/dist/chunks/{chunk-7N7IC3Z2.js → chunk-2CD7HLVP.js} +3 -84
  22. package/dist/chunks/chunk-2CD7HLVP.js.map +7 -0
  23. package/dist/chunks/{chunk-7YNE4NB2.js → chunk-2MELFQCQ.js} +2 -2
  24. package/dist/chunks/{chunk-HSEZPCL5.js → chunk-2OC4YJOL.js} +3 -3
  25. package/dist/chunks/{chunk-TXCNZCZP.js → chunk-2QJ4MNS6.js} +2 -2
  26. package/dist/chunks/{chunk-F6A6MQ6G.js → chunk-2WPTD6BI.js} +11 -15
  27. package/dist/chunks/chunk-2WPTD6BI.js.map +7 -0
  28. package/dist/chunks/{chunk-QOEOKW2X.js → chunk-3QH6JAE3.js} +2 -2
  29. package/dist/chunks/chunk-4U47NCP2.js +88 -0
  30. package/dist/chunks/chunk-4U47NCP2.js.map +7 -0
  31. package/dist/chunks/{chunk-OJ4HAALD.js → chunk-5VZEAAHD.js} +10 -9
  32. package/dist/chunks/chunk-5VZEAAHD.js.map +7 -0
  33. package/dist/chunks/{chunk-LKYLD5SN.js → chunk-6HM4TX7L.js} +10 -8
  34. package/dist/chunks/chunk-6HM4TX7L.js.map +7 -0
  35. package/dist/chunks/{chunk-L6H46CPY.js → chunk-6NNL5LOG.js} +2 -2
  36. package/dist/chunks/{chunk-7TB7NXSL.js → chunk-7CIQQOOD.js} +11 -3
  37. package/dist/chunks/{chunk-7TB7NXSL.js.map → chunk-7CIQQOOD.js.map} +2 -2
  38. package/dist/chunks/{chunk-RWKQ5SRW.js → chunk-7ZFPVOV2.js} +2 -2
  39. package/dist/chunks/{chunk-PUBHBEYO.js → chunk-B2FIGOPI.js} +2 -2
  40. package/dist/chunks/{chunk-HRDMBGMY.js → chunk-BLT66VHH.js} +331 -22
  41. package/dist/chunks/chunk-BLT66VHH.js.map +7 -0
  42. package/dist/chunks/{chunk-4WKD3YM3.js → chunk-C3UPHOJW.js} +3 -3
  43. package/dist/chunks/{chunk-G2DZJ5LK.js → chunk-CB72SLHB.js} +451 -134
  44. package/dist/chunks/chunk-CB72SLHB.js.map +7 -0
  45. package/dist/chunks/{chunk-B5L3X3ID.js → chunk-CCJ6PUZJ.js} +1 -1
  46. package/dist/chunks/{chunk-B5L3X3ID.js.map → chunk-CCJ6PUZJ.js.map} +1 -1
  47. package/dist/chunks/{chunk-FK73YJKV.js → chunk-DWM63MAJ.js} +21 -9
  48. package/dist/chunks/chunk-DWM63MAJ.js.map +7 -0
  49. package/dist/chunks/{chunk-56NMRVTV.js → chunk-FFJ7TV66.js} +32 -29
  50. package/dist/chunks/chunk-FFJ7TV66.js.map +7 -0
  51. package/dist/chunks/{chunk-LRSZFYUC.js → chunk-FUMALXYQ.js} +15 -15
  52. package/dist/chunks/chunk-FUMALXYQ.js.map +7 -0
  53. package/dist/chunks/{chunk-TJZYM2SP.js → chunk-G3RQ3HUK.js} +8 -3
  54. package/dist/chunks/{chunk-TJZYM2SP.js.map → chunk-G3RQ3HUK.js.map} +2 -2
  55. package/dist/chunks/{chunk-RAA3FAYZ.js → chunk-GNPTDN6K.js} +2 -2
  56. package/dist/chunks/{chunk-XFOSUGLU.js → chunk-JCGEW5OQ.js} +5 -5
  57. package/dist/chunks/{chunk-CXYJJ3HZ.js → chunk-LJ2MG6U2.js} +3 -3
  58. package/dist/chunks/{chunk-3MOY6WIB.js → chunk-LRBDEAKB.js} +3 -3
  59. package/dist/chunks/{chunk-2RWNVCFD.js → chunk-MPFBOVOD.js} +1 -1
  60. package/dist/chunks/{chunk-2RWNVCFD.js.map → chunk-MPFBOVOD.js.map} +1 -1
  61. package/dist/chunks/{chunk-NQ7IWEIF.js → chunk-MQGRQMVM.js} +2 -2
  62. package/dist/chunks/{chunk-3VK6UGAN.js → chunk-O5SHIUIL.js} +6 -1
  63. package/dist/chunks/chunk-O5SHIUIL.js.map +7 -0
  64. package/dist/chunks/{chunk-U6Y6TKJL.js → chunk-OK2EKY3M.js} +15 -11
  65. package/dist/chunks/chunk-OK2EKY3M.js.map +7 -0
  66. package/dist/chunks/{chunk-DGUXJSYA.js → chunk-OR44GYXD.js} +70 -3
  67. package/dist/chunks/chunk-OR44GYXD.js.map +7 -0
  68. package/dist/chunks/{chunk-DGERP4VL.js → chunk-P4TALNLX.js} +11 -10
  69. package/dist/chunks/chunk-P4TALNLX.js.map +7 -0
  70. package/dist/chunks/{chunk-4BYS4ZLY.js → chunk-PHGPOSCP.js} +267 -71
  71. package/dist/chunks/chunk-PHGPOSCP.js.map +7 -0
  72. package/dist/chunks/{chunk-3XT5WHSG.js → chunk-QAGEWWCJ.js} +260 -59
  73. package/dist/chunks/chunk-QAGEWWCJ.js.map +7 -0
  74. package/dist/chunks/{chunk-WKFRGICG.js → chunk-RBYRHS24.js} +2 -2
  75. package/dist/chunks/{chunk-ZHROHNEE.js → chunk-RFNYH7S7.js} +8 -8
  76. package/dist/chunks/{chunk-VGRUWTMG.js → chunk-RPZJVLML.js} +472 -466
  77. package/dist/chunks/chunk-RPZJVLML.js.map +7 -0
  78. package/dist/chunks/{chunk-H57KPL3V.js → chunk-S2JWFXW5.js} +2 -2
  79. package/dist/chunks/{chunk-LZ2ZXOCU.js → chunk-SSB2JN3I.js} +168 -5
  80. package/dist/chunks/chunk-SSB2JN3I.js.map +7 -0
  81. package/dist/chunks/{chunk-RKJPBTBB.js → chunk-SVQ7ZHEQ.js} +33 -16
  82. package/dist/chunks/chunk-SVQ7ZHEQ.js.map +7 -0
  83. package/dist/chunks/{chunk-MPMEK3IQ.js → chunk-TV5NCPPS.js} +6 -5
  84. package/dist/chunks/chunk-TV5NCPPS.js.map +7 -0
  85. package/dist/chunks/{chunk-XOBLUZMB.js → chunk-UIVMSMSQ.js} +10 -1
  86. package/dist/chunks/chunk-UIVMSMSQ.js.map +7 -0
  87. package/dist/chunks/{chunk-QGTD3LAZ.js → chunk-UYS5VZUU.js} +9 -3
  88. package/dist/chunks/chunk-UYS5VZUU.js.map +7 -0
  89. package/dist/chunks/{chunk-HRVYXRWZ.js → chunk-V5RZK45W.js} +37 -3
  90. package/dist/chunks/chunk-V5RZK45W.js.map +7 -0
  91. package/dist/chunks/{chunk-KIFOEBYJ.js → chunk-VEXCD3RA.js} +2 -2
  92. package/dist/chunks/{chunk-GS67KDMV.js → chunk-VN7AE3EY.js} +2 -2
  93. package/dist/chunks/{chunk-HFDJWLMS.js → chunk-WFGJUVTH.js} +106 -65
  94. package/dist/chunks/chunk-WFGJUVTH.js.map +7 -0
  95. package/dist/chunks/chunk-WMULZZER.js +196 -0
  96. package/dist/chunks/chunk-WMULZZER.js.map +7 -0
  97. package/dist/chunks/{chunk-QNMQJNXE.js → chunk-X4HDI7RT.js} +14 -4
  98. package/dist/chunks/chunk-X4HDI7RT.js.map +7 -0
  99. package/dist/chunks/{chunk-MX53BRAC.js → chunk-XBAOTA4U.js} +2 -2
  100. package/dist/chunks/{chunk-MSDL7U6Q.js → chunk-XQCNVH3Y.js} +4 -4
  101. package/dist/chunks/{chunk-4PBW54I2.js → chunk-YC6NV7FK.js} +88 -54
  102. package/dist/chunks/chunk-YC6NV7FK.js.map +7 -0
  103. package/dist/chunks/{chunk-6GWDGTHC.js → chunk-YLO62DWD.js} +4 -4
  104. package/dist/cli/decisions.js +2 -2
  105. package/dist/cli/mesh.js +3 -3
  106. package/dist/commands/fabric-handler.d.ts.map +1 -1
  107. package/dist/commands/fabric-handler.js +18 -4
  108. package/dist/commands/fabric-handler.js.map +2 -2
  109. package/dist/commands/fabric.d.ts.map +1 -1
  110. package/dist/compaction/branch-summary.d.ts.map +1 -1
  111. package/dist/compaction/claim-events.js +9 -9
  112. package/dist/compaction/hook.d.ts.map +1 -1
  113. package/dist/compaction/hook.js +6 -6
  114. package/dist/compaction/normalize.d.ts +9 -0
  115. package/dist/compaction/normalize.d.ts.map +1 -1
  116. package/dist/compaction/owner.js +7 -7
  117. package/dist/compaction/projections.d.ts +18 -2
  118. package/dist/compaction/projections.d.ts.map +1 -1
  119. package/dist/compaction/qa.d.ts +3 -2
  120. package/dist/compaction/qa.d.ts.map +1 -1
  121. package/dist/compaction/render.d.ts +3 -0
  122. package/dist/compaction/render.d.ts.map +1 -1
  123. package/dist/compaction/threshold.d.ts.map +1 -1
  124. package/dist/compaction/user-activity.d.ts +31 -0
  125. package/dist/compaction/user-activity.d.ts.map +1 -0
  126. package/dist/components/configuration.js +4 -4
  127. package/dist/config.d.ts +13 -6
  128. package/dist/config.d.ts.map +1 -1
  129. package/dist/core/action-registry.d.ts +1 -1
  130. package/dist/core/action-registry.d.ts.map +1 -1
  131. package/dist/core/action-registry.js +10 -9
  132. package/dist/core/approval-controller.d.ts +3 -0
  133. package/dist/core/approval-controller.d.ts.map +1 -1
  134. package/dist/core/atomic-write.d.ts +1 -0
  135. package/dist/core/atomic-write.d.ts.map +1 -1
  136. package/dist/core/attached-monitors.d.ts +39 -0
  137. package/dist/core/attached-monitors.d.ts.map +1 -0
  138. package/dist/core/control-abort.d.ts +3 -0
  139. package/dist/core/control-abort.d.ts.map +1 -0
  140. package/dist/core/crash-guard.d.ts +15 -0
  141. package/dist/core/crash-guard.d.ts.map +1 -0
  142. package/dist/core/execution-guidelines.d.ts +6 -0
  143. package/dist/core/execution-guidelines.d.ts.map +1 -0
  144. package/dist/core/guidance-delivery.d.ts +19 -0
  145. package/dist/core/guidance-delivery.d.ts.map +1 -0
  146. package/dist/core/lifecycle-settlement.d.ts +9 -0
  147. package/dist/core/lifecycle-settlement.d.ts.map +1 -0
  148. package/dist/core/observation-actions.d.ts +9 -0
  149. package/dist/core/observation-actions.d.ts.map +1 -0
  150. package/dist/core/pasted-images.d.ts +12 -0
  151. package/dist/core/pasted-images.d.ts.map +1 -0
  152. package/dist/core/pasted-images.js +139 -0
  153. package/dist/core/pasted-images.js.map +7 -0
  154. package/dist/core/permission-queue.d.ts +32 -0
  155. package/dist/core/permission-queue.d.ts.map +1 -0
  156. package/dist/core/permission-queue.js +104 -0
  157. package/dist/core/permission-queue.js.map +7 -0
  158. package/dist/core/prompt-guidance.d.ts +1 -0
  159. package/dist/core/prompt-guidance.d.ts.map +1 -1
  160. package/dist/core/prompt-guidance.js +52 -3
  161. package/dist/core/prompt-guidance.js.map +3 -3
  162. package/dist/core/provider-operations.js +1 -1
  163. package/dist/core/shell-inbox.d.ts +1 -1
  164. package/dist/core/shell-inbox.d.ts.map +1 -1
  165. package/dist/core/shell-jobs.d.ts +28 -1
  166. package/dist/core/shell-jobs.d.ts.map +1 -1
  167. package/dist/core/shell-monitor.d.ts +1 -0
  168. package/dist/core/shell-monitor.d.ts.map +1 -1
  169. package/dist/durable/worker.js +0 -42
  170. package/dist/durable/worker.js.map +3 -3
  171. package/dist/durable-extension.d.ts +2 -2
  172. package/dist/durable-extension.d.ts.map +1 -1
  173. package/dist/durable-extension.js +215 -1
  174. package/dist/durable-extension.js.map +3 -3
  175. package/dist/entropy/index.d.ts +2 -0
  176. package/dist/entropy/index.d.ts.map +1 -1
  177. package/dist/entropy/index.js +23 -13
  178. package/dist/entropy/pool-store.d.ts +8 -1
  179. package/dist/entropy/pool-store.d.ts.map +1 -1
  180. package/dist/entropy/pool-worker.d.ts +18 -0
  181. package/dist/entropy/pool-worker.d.ts.map +1 -0
  182. package/dist/entropy/pool-writer.d.ts +23 -0
  183. package/dist/entropy/pool-writer.d.ts.map +1 -0
  184. package/dist/entropy/pool.d.ts +11 -0
  185. package/dist/entropy/pool.d.ts.map +1 -1
  186. package/dist/entropy/sessions.d.ts +5 -0
  187. package/dist/entropy/sessions.d.ts.map +1 -1
  188. package/dist/execution-service.d.ts.map +1 -1
  189. package/dist/extension-bootstrap.d.ts.map +1 -1
  190. package/dist/extension-bootstrap.js +19 -19
  191. package/dist/extension.d.ts.map +1 -1
  192. package/dist/fabric-exec-tool.d.ts.map +1 -1
  193. package/dist/fabric-runtime-state.d.ts.map +1 -1
  194. package/dist/fabric-runtime-state.js +534 -261
  195. package/dist/fabric-runtime-state.js.map +4 -4
  196. package/dist/fabric-state.d.ts.map +1 -1
  197. package/dist/index.js +40 -30
  198. package/dist/index.js.map +1 -1
  199. package/dist/jev/client.js +2 -2
  200. package/dist/jev/observation.js +7 -6
  201. package/dist/jev.js +12 -11
  202. package/dist/main-agent.d.ts.map +1 -1
  203. package/dist/managed-host.d.ts +4 -0
  204. package/dist/managed-host.d.ts.map +1 -1
  205. package/dist/memory/discovery.js +6 -6
  206. package/dist/memory/expand-service.d.ts.map +1 -1
  207. package/dist/memory/file-worker.js +9 -8
  208. package/dist/memory/file-worker.js.map +1 -1
  209. package/dist/memory/history-paging.d.ts +9 -0
  210. package/dist/memory/history-paging.d.ts.map +1 -0
  211. package/dist/memory/history-paging.js +164 -0
  212. package/dist/memory/history-paging.js.map +7 -0
  213. package/dist/memory/index.d.ts.map +1 -1
  214. package/dist/memory/normalize.js +5 -5
  215. package/dist/memory/outline-service.d.ts +7 -0
  216. package/dist/memory/outline-service.d.ts.map +1 -0
  217. package/dist/memory/request-cache.d.ts +3 -1
  218. package/dist/memory/request-cache.d.ts.map +1 -1
  219. package/dist/memory/request-context.d.ts +1 -0
  220. package/dist/memory/request-context.d.ts.map +1 -1
  221. package/dist/memory/request-limits.d.ts +2 -0
  222. package/dist/memory/request-limits.d.ts.map +1 -1
  223. package/dist/memory/search.js +7 -6
  224. package/dist/memory/worker-provider.d.ts.map +1 -1
  225. package/dist/memory/worker-provider.js +10 -9
  226. package/dist/memory.d.ts +16 -1
  227. package/dist/memory.d.ts.map +1 -1
  228. package/dist/memory.js +64 -12
  229. package/dist/memory.js.map +1 -1
  230. package/dist/mesh/store.d.ts +2 -1
  231. package/dist/mesh/store.d.ts.map +1 -1
  232. package/dist/programs/host.js +2 -2
  233. package/dist/protocol.d.ts +5 -0
  234. package/dist/protocol.d.ts.map +1 -1
  235. package/dist/protocol.js +1 -1
  236. package/dist/providers/agents-actions.d.ts.map +1 -1
  237. package/dist/providers/agents-message-router.d.ts +1 -0
  238. package/dist/providers/agents-message-router.d.ts.map +1 -1
  239. package/dist/providers/agents-provider.d.ts +2 -0
  240. package/dist/providers/agents-provider.d.ts.map +1 -1
  241. package/dist/providers/jev-provider.js +12 -11
  242. package/dist/providers/memory-provider.d.ts +4 -0
  243. package/dist/providers/memory-provider.d.ts.map +1 -1
  244. package/dist/providers/memory-provider.js +9 -8
  245. package/dist/providers/pi-read-operations.d.ts +24 -0
  246. package/dist/providers/pi-read-operations.d.ts.map +1 -0
  247. package/dist/providers/pi-tools-provider.d.ts +7 -0
  248. package/dist/providers/pi-tools-provider.d.ts.map +1 -1
  249. package/dist/providers/sessions-provider.d.ts +1 -1
  250. package/dist/providers/sessions-provider.d.ts.map +1 -1
  251. package/dist/providers/tasks-provider.d.ts +3 -1
  252. package/dist/providers/tasks-provider.d.ts.map +1 -1
  253. package/dist/residency/actor-client.js +3 -3
  254. package/dist/residency/client.d.ts.map +1 -1
  255. package/dist/residency/host.d.ts.map +1 -1
  256. package/dist/residency/host.js +17 -16
  257. package/dist/residency/launcher.js +1 -1
  258. package/dist/residency/pi-entry.js +17 -16
  259. package/dist/residency/pi-entry.js.map +1 -1
  260. package/dist/residency/protocol.d.ts +2 -0
  261. package/dist/residency/protocol.d.ts.map +1 -1
  262. package/dist/runtime/core-override-guest-types.js +2 -2
  263. package/dist/runtime/cpython-runtime.d.ts.map +1 -1
  264. package/dist/runtime/cpython-runtime.js +7 -6
  265. package/dist/runtime/cpython-runtime.js.map +2 -2
  266. package/dist/runtime/guest-types.d.ts +1 -1
  267. package/dist/runtime/guest-types.d.ts.map +1 -1
  268. package/dist/runtime/guest-types.js +1 -1
  269. package/dist/runtime/monty-runtime.d.ts.map +1 -1
  270. package/dist/runtime/monty-runtime.js +7 -6
  271. package/dist/runtime/monty-runtime.js.map +2 -2
  272. package/dist/runtime/node-process-runtime.d.ts.map +1 -1
  273. package/dist/runtime/node-process-runtime.js +6 -6
  274. package/dist/runtime/quickjs-runtime.d.ts.map +1 -1
  275. package/dist/runtime/quickjs-runtime.js +4 -4
  276. package/dist/runtime/type-checker.d.ts.map +1 -1
  277. package/dist/runtime/type-checker.js +1 -1
  278. package/dist/runtime/typescript-kernel.js +10 -10
  279. package/dist/runtime-state-builtins.d.ts +2 -0
  280. package/dist/runtime-state-builtins.d.ts.map +1 -1
  281. package/dist/schema/policy.d.ts.map +1 -1
  282. package/dist/speculation/eligibility.d.ts.map +1 -1
  283. package/dist/speculation/store.d.ts.map +1 -1
  284. package/dist/topology/participant-directory.d.ts +1 -0
  285. package/dist/topology/participant-directory.d.ts.map +1 -1
  286. package/dist/topology/peer-presence.d.ts.map +1 -1
  287. package/dist/topology/provider-participants.d.ts +1 -0
  288. package/dist/topology/provider-participants.d.ts.map +1 -1
  289. package/dist/type-error-guidance.js +1 -1
  290. package/dist/ui/code-preview-shell.d.ts +1 -0
  291. package/dist/ui/code-preview-shell.d.ts.map +1 -1
  292. package/dist/ui/controller.d.ts.map +1 -1
  293. package/dist/ui/conversation-chrome.d.ts.map +1 -1
  294. package/dist/ui/conversation-chrome.js +2 -2
  295. package/dist/ui/conversation-feedback.d.ts +8 -0
  296. package/dist/ui/conversation-feedback.d.ts.map +1 -0
  297. package/dist/ui/conversation-latest.d.ts.map +1 -1
  298. package/dist/ui/conversation-native-reader.d.ts.map +1 -1
  299. package/dist/ui/conversation-native-reader.js +3 -3
  300. package/dist/ui/conversation-native-reader.js.map +2 -2
  301. package/dist/ui/conversation-render.d.ts.map +1 -1
  302. package/dist/ui/conversation.d.ts +1 -0
  303. package/dist/ui/conversation.d.ts.map +1 -1
  304. package/dist/ui/conversation.js +139 -86
  305. package/dist/ui/conversation.js.map +4 -4
  306. package/dist/ui/core-tool-render.d.ts.map +1 -1
  307. package/dist/ui/dashboard-fabric-graph.d.ts.map +1 -1
  308. package/dist/ui/dashboard.js +47 -48
  309. package/dist/ui/dashboard.js.map +3 -3
  310. package/dist/ui/fabric-render.d.ts.map +1 -1
  311. package/dist/ui/format.d.ts.map +1 -1
  312. package/dist/ui/highlight.d.ts.map +1 -1
  313. package/dist/ui/permissions.d.ts +18 -0
  314. package/dist/ui/permissions.d.ts.map +1 -0
  315. package/dist/ui/permissions.js +178 -0
  316. package/dist/ui/permissions.js.map +7 -0
  317. package/dist/ui/row-balance.d.ts +1 -1
  318. package/dist/ui/row-balance.d.ts.map +1 -1
  319. package/dist/ui/settings-sections-execution.d.ts.map +1 -1
  320. package/dist/ui/settings-values.d.ts.map +1 -1
  321. package/dist/ui/settings.js +37 -31
  322. package/dist/ui/settings.js.map +2 -2
  323. package/dist/ui/shell-hang-keys.d.ts.map +1 -1
  324. package/dist/ui/shell-tasks.d.ts.map +1 -1
  325. package/dist/ui/shell-tasks.js +28 -11
  326. package/dist/ui/shell-tasks.js.map +2 -2
  327. package/dist/ui/structured.d.ts.map +1 -1
  328. package/dist/ui/tool-display.d.ts +18 -2
  329. package/dist/ui/tool-display.d.ts.map +1 -1
  330. package/dist/ui/truncate.d.ts +3 -0
  331. package/dist/ui/truncate.d.ts.map +1 -0
  332. package/dist/ui/widget.d.ts +7 -2
  333. package/dist/ui/widget.d.ts.map +1 -1
  334. package/dist/verified/context.d.ts +35 -0
  335. package/dist/verified/context.d.ts.map +1 -0
  336. package/dist/verified/execution.d.ts +7 -0
  337. package/dist/verified/execution.d.ts.map +1 -0
  338. package/dist/verified/generated/context.d.ts +6 -0
  339. package/dist/verified/generated/context.js +51 -0
  340. package/dist/verified/generated/execution.d.ts +5 -0
  341. package/dist/verified/generated/execution.js +32 -0
  342. package/dist/verified/generated/manifest.json +34 -3
  343. package/dist/verified/generated/prompt-guidance.d.ts +4 -0
  344. package/dist/verified/generated/prompt-guidance.js +17 -0
  345. package/dist/worker/recovery-watchdog.d.ts +7 -0
  346. package/dist/worker/recovery-watchdog.d.ts.map +1 -1
  347. package/dist/worker/recovery-watchdog.js +66 -4
  348. package/dist/worker/recovery-watchdog.js.map +2 -2
  349. package/dist/worker.js +22 -3
  350. package/dist/worker.js.map +2 -2
  351. package/docs/agents.md +37 -4
  352. package/docs/architecture.md +13 -0
  353. package/docs/background-tasks.md +81 -5
  354. package/docs/benchmarks/cli-resume-2026-11-09.json +1260 -0
  355. package/docs/benchmarks/interactivity-2026-11-09.json +2280 -0
  356. package/docs/benchmarks/resume-latency-2026-11-09.json +12105 -0
  357. package/docs/benchmarks/resume-startup-fix-2026-11-09.json +5452 -0
  358. package/docs/benchmarks/session-memory-2026-11-09.json +1320 -0
  359. package/docs/benchmarks/session-memory-fix-2026-11-09.json +280 -0
  360. package/docs/compaction.md +59 -23
  361. package/docs/configuration.md +53 -11
  362. package/docs/entropy.md +4 -1
  363. package/docs/history-paging.md +99 -0
  364. package/docs/interactivity-investigation.md +109 -0
  365. package/docs/interface.md +2 -2
  366. package/docs/jev.md +1 -1
  367. package/docs/memory-recall.md +42 -1
  368. package/docs/providers.md +24 -1
  369. package/docs/resume-latency-investigation.md +249 -0
  370. package/docs/session-memory-investigation.md +223 -0
  371. package/docs/verified-kernels.md +56 -0
  372. package/package.json +211 -211
  373. package/proofs/context.ts +139 -0
  374. package/proofs/execution.ts +48 -0
  375. package/proofs/index.ts +6 -0
  376. package/proofs/prompt-guidance.ts +38 -0
  377. package/scripts/verified-kernels.ts +1 -1
  378. package/skillsets/python/fabric-council/SKILL.md +31 -21
  379. package/skillsets/python/fabric-exec/SKILL.md +1 -1
  380. package/skillsets/python/fabric-exec/references/agents.md +2 -0
  381. package/skillsets/python/fabric-guide/SKILL.md +1 -0
  382. package/skillsets/python/fabric-memory/SKILL.md +82 -0
  383. package/skillsets/typescript/fabric-council/SKILL.md +26 -17
  384. package/skillsets/typescript/fabric-exec/SKILL.md +3 -2
  385. package/skillsets/typescript/fabric-exec/references/agents.md +1 -0
  386. package/skillsets/typescript/fabric-guide/SKILL.md +1 -0
  387. package/skillsets/typescript/fabric-memory/SKILL.md +87 -0
  388. package/dist/chunks/chunk-3VK6UGAN.js.map +0 -7
  389. package/dist/chunks/chunk-3XT5WHSG.js.map +0 -7
  390. package/dist/chunks/chunk-4BYS4ZLY.js.map +0 -7
  391. package/dist/chunks/chunk-4PBW54I2.js.map +0 -7
  392. package/dist/chunks/chunk-56NMRVTV.js.map +0 -7
  393. package/dist/chunks/chunk-7N7IC3Z2.js.map +0 -7
  394. package/dist/chunks/chunk-DGERP4VL.js.map +0 -7
  395. package/dist/chunks/chunk-DGUXJSYA.js.map +0 -7
  396. package/dist/chunks/chunk-F6A6MQ6G.js.map +0 -7
  397. package/dist/chunks/chunk-FK73YJKV.js.map +0 -7
  398. package/dist/chunks/chunk-G2DZJ5LK.js.map +0 -7
  399. package/dist/chunks/chunk-HFDJWLMS.js.map +0 -7
  400. package/dist/chunks/chunk-HRDMBGMY.js.map +0 -7
  401. package/dist/chunks/chunk-HRVYXRWZ.js.map +0 -7
  402. package/dist/chunks/chunk-LKYLD5SN.js.map +0 -7
  403. package/dist/chunks/chunk-LRSZFYUC.js.map +0 -7
  404. package/dist/chunks/chunk-LZ2ZXOCU.js.map +0 -7
  405. package/dist/chunks/chunk-MPMEK3IQ.js.map +0 -7
  406. package/dist/chunks/chunk-OJ4HAALD.js.map +0 -7
  407. package/dist/chunks/chunk-QGTD3LAZ.js.map +0 -7
  408. package/dist/chunks/chunk-QNMQJNXE.js.map +0 -7
  409. package/dist/chunks/chunk-RKJPBTBB.js.map +0 -7
  410. package/dist/chunks/chunk-U6Y6TKJL.js.map +0 -7
  411. package/dist/chunks/chunk-VGRUWTMG.js.map +0 -7
  412. package/dist/chunks/chunk-XOBLUZMB.js.map +0 -7
  413. package/dist/durable/openai-sse-patch.d.ts +0 -21
  414. package/dist/durable/openai-sse-patch.d.ts.map +0 -1
  415. /package/dist/chunks/{chunk-7YNE4NB2.js.map → chunk-2MELFQCQ.js.map} +0 -0
  416. /package/dist/chunks/{chunk-HSEZPCL5.js.map → chunk-2OC4YJOL.js.map} +0 -0
  417. /package/dist/chunks/{chunk-TXCNZCZP.js.map → chunk-2QJ4MNS6.js.map} +0 -0
  418. /package/dist/chunks/{chunk-QOEOKW2X.js.map → chunk-3QH6JAE3.js.map} +0 -0
  419. /package/dist/chunks/{chunk-L6H46CPY.js.map → chunk-6NNL5LOG.js.map} +0 -0
  420. /package/dist/chunks/{chunk-RWKQ5SRW.js.map → chunk-7ZFPVOV2.js.map} +0 -0
  421. /package/dist/chunks/{chunk-PUBHBEYO.js.map → chunk-B2FIGOPI.js.map} +0 -0
  422. /package/dist/chunks/{chunk-4WKD3YM3.js.map → chunk-C3UPHOJW.js.map} +0 -0
  423. /package/dist/chunks/{chunk-RAA3FAYZ.js.map → chunk-GNPTDN6K.js.map} +0 -0
  424. /package/dist/chunks/{chunk-XFOSUGLU.js.map → chunk-JCGEW5OQ.js.map} +0 -0
  425. /package/dist/chunks/{chunk-CXYJJ3HZ.js.map → chunk-LJ2MG6U2.js.map} +0 -0
  426. /package/dist/chunks/{chunk-3MOY6WIB.js.map → chunk-LRBDEAKB.js.map} +0 -0
  427. /package/dist/chunks/{chunk-NQ7IWEIF.js.map → chunk-MQGRQMVM.js.map} +0 -0
  428. /package/dist/chunks/{chunk-WKFRGICG.js.map → chunk-RBYRHS24.js.map} +0 -0
  429. /package/dist/chunks/{chunk-ZHROHNEE.js.map → chunk-RFNYH7S7.js.map} +0 -0
  430. /package/dist/chunks/{chunk-H57KPL3V.js.map → chunk-S2JWFXW5.js.map} +0 -0
  431. /package/dist/chunks/{chunk-KIFOEBYJ.js.map → chunk-VEXCD3RA.js.map} +0 -0
  432. /package/dist/chunks/{chunk-GS67KDMV.js.map → chunk-VN7AE3EY.js.map} +0 -0
  433. /package/dist/chunks/{chunk-MX53BRAC.js.map → chunk-XBAOTA4U.js.map} +0 -0
  434. /package/dist/chunks/{chunk-MSDL7U6Q.js.map → chunk-XQCNVH3Y.js.map} +0 -0
  435. /package/dist/chunks/{chunk-6GWDGTHC.js.map → chunk-YLO62DWD.js.map} +0 -0
@@ -9,6 +9,10 @@ import {
9
9
  spawnDetached,
10
10
  workerCommand
11
11
  } from "./chunk-SVDHQUTM.js";
12
+ import {
13
+ mapVedaTools,
14
+ normalizeVedaModel
15
+ } from "./chunk-VPPIJRNZ.js";
12
16
  import {
13
17
  isInside,
14
18
  readWritePolicy
@@ -21,10 +25,6 @@ import {
21
25
  mapClaudeTools,
22
26
  normalizeClaudeModel
23
27
  } from "./chunk-PM5I335G.js";
24
- import {
25
- mapVedaTools,
26
- normalizeVedaModel
27
- } from "./chunk-VPPIJRNZ.js";
28
28
  import {
29
29
  peerLabelPrefix
30
30
  } from "./chunk-W5FEHVZA.js";
@@ -34,7 +34,7 @@ import {
34
34
  import {
35
35
  compileFabricSummary,
36
36
  rawContextTokens
37
- } from "./chunk-3XT5WHSG.js";
37
+ } from "./chunk-QAGEWWCJ.js";
38
38
  import {
39
39
  launchScope,
40
40
  normalizeScope,
@@ -42,13 +42,28 @@ import {
42
42
  senderStamp,
43
43
  senderTrusted
44
44
  } from "./chunk-JKQARSWR.js";
45
+ import {
46
+ WORKER_RECOVERY_FORMAT,
47
+ adoptedWorkerHandle,
48
+ authorizeWorkerRecovery,
49
+ hasWorkerRecovery,
50
+ probeWorker,
51
+ readWorkerRecovery,
52
+ readWorkerRecoveryAuthority,
53
+ removeWorkerRecovery,
54
+ workerRecoveryMismatch,
55
+ writeWorkerRecovery
56
+ } from "./chunk-WMULZZER.js";
45
57
  import {
46
58
  isModelPinFailure
47
59
  } from "./chunk-UD7LFV43.js";
48
60
  import {
49
61
  ownedStat,
50
62
  processAlive
51
- } from "./chunk-7YNE4NB2.js";
63
+ } from "./chunk-2MELFQCQ.js";
64
+ import {
65
+ readJsonlPage
66
+ } from "./chunk-CGPK5WHX.js";
52
67
  import {
53
68
  resolveAgentDir
54
69
  } from "./chunk-PBDDXBHY.js";
@@ -56,10 +71,10 @@ import {
56
71
  DEFAULT_FABRIC_CONFIG,
57
72
  MAX_AGENT_TIMEOUT_MS,
58
73
  MIN_AGENT_TIMEOUT_MS
59
- } from "./chunk-LRSZFYUC.js";
74
+ } from "./chunk-FUMALXYQ.js";
60
75
  import {
61
- readJsonlPage
62
- } from "./chunk-CGPK5WHX.js";
76
+ FABRIC_PEER_LABEL_SEQUENCE
77
+ } from "./chunk-MPFBOVOD.js";
63
78
  import {
64
79
  formatShortLockOwner,
65
80
  ownerHeartbeatFields,
@@ -70,10 +85,7 @@ import {
70
85
  releaseShortLock,
71
86
  tryAcquireShortLock,
72
87
  writeJsonAtomic
73
- } from "./chunk-F6A6MQ6G.js";
74
- import {
75
- FABRIC_PEER_LABEL_SEQUENCE
76
- } from "./chunk-2RWNVCFD.js";
88
+ } from "./chunk-2WPTD6BI.js";
77
89
  import {
78
90
  AgentAdmission,
79
91
  FABRIC_LIFECYCLE_SUBSCRIPTION_PREFIX,
@@ -305,9 +317,9 @@ function appendBudgetLedger(file, entry) {
305
317
 
306
318
  // src/agents/manager.ts
307
319
  import { randomUUID as randomUUID6 } from "node:crypto";
308
- import fs13 from "node:fs";
320
+ import fs12 from "node:fs";
309
321
  import os3 from "node:os";
310
- import path14 from "node:path";
322
+ import path13 from "node:path";
311
323
  import { fileURLToPath } from "node:url";
312
324
 
313
325
  // src/agents/hosted-run.ts
@@ -792,189 +804,10 @@ var removeTree = async (target, rm = defaultRemove) => {
792
804
  }
793
805
  };
794
806
 
795
- // src/agents/worker-recovery.ts
796
- import { execFileSync } from "node:child_process";
797
- import fs4 from "node:fs";
798
- import path4 from "node:path";
799
- import { isDeepStrictEqual } from "node:util";
800
- var WORKER_RECOVERY_FILE = "worker-recovery.json";
801
- var WORKER_RECOVERY_FORMAT = 1;
802
- var MAX_ARGUMENTS = 4096;
803
- var MAX_STRING = 1048576;
804
- var WORKER_RECOVERY_MAX_BYTES = 8 * 1048576;
805
- var boundedString = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_STRING;
806
- var workerRecoveryPath = (runDirectory) => path4.join(runDirectory, WORKER_RECOVERY_FILE);
807
- var writeWorkerRecovery = (runDirectory, record) => {
808
- writeJsonAtomic(workerRecoveryPath(runDirectory), record, { mode: 384 });
809
- };
810
- var workerRecoveryAuthorityRoot = (runRoot) => `${path4.resolve(runRoot)}.worker-launch-authority`;
811
- var authorityPath = (runDirectory) => path4.join(workerRecoveryAuthorityRoot(path4.dirname(runDirectory)), `${path4.basename(runDirectory)}.json`);
812
- var authorizeWorkerRecovery = (runDirectory, recovery, policy) => {
813
- fs4.mkdirSync(path4.dirname(authorityPath(runDirectory)), { recursive: true, mode: 448 });
814
- writeJsonAtomic(authorityPath(runDirectory), { recovery, policy }, { mode: 384 });
815
- };
816
- var readWorkerRecoveryAuthority = (runDirectory, policy) => {
817
- const content = readBounded(authorityPath(runDirectory));
818
- if (!content) return void 0;
819
- try {
820
- const receipt = JSON.parse(content);
821
- if (policy !== void 0 && receipt.policy !== policy) return void 0;
822
- return parseWorkerRecovery(JSON.stringify(receipt.recovery), runDirectory);
823
- } catch {
824
- return void 0;
825
- }
826
- };
827
- var removeWorkerRecovery = (runDirectory) => {
828
- fs4.rmSync(workerRecoveryPath(runDirectory), { force: true });
829
- fs4.rmSync(authorityPath(runDirectory), { force: true });
830
- try {
831
- fs4.rmdirSync(workerRecoveryAuthorityRoot(path4.dirname(runDirectory)));
832
- } catch {
833
- }
834
- };
835
- var hasWorkerRecovery = (runDirectory) => fs4.existsSync(workerRecoveryPath(runDirectory));
836
- var readBounded = (file) => {
837
- let descriptor;
838
- try {
839
- descriptor = fs4.openSync(file, fs4.constants.O_RDONLY | (fs4.constants.O_NOFOLLOW ?? 0) | (fs4.constants.O_NONBLOCK ?? 0));
840
- const stat = fs4.fstatSync(descriptor);
841
- if (!stat.isFile() || stat.size > WORKER_RECOVERY_MAX_BYTES) return void 0;
842
- const buffer = Buffer.alloc(stat.size);
843
- const bytes = fs4.readSync(descriptor, buffer, 0, buffer.length, 0);
844
- return buffer.subarray(0, bytes).toString("utf8");
845
- } catch {
846
- return void 0;
847
- } finally {
848
- if (descriptor !== void 0) fs4.closeSync(descriptor);
849
- }
850
- };
851
- var readWorkerRecovery = (runDirectory) => {
852
- const content = readBounded(workerRecoveryPath(runDirectory));
853
- if (content === void 0) return void 0;
854
- return parseWorkerRecovery(content, runDirectory);
855
- };
856
- var parseWorkerRecovery = (content, runDirectory) => {
857
- let raw;
858
- try {
859
- raw = JSON.parse(content);
860
- } catch {
861
- return void 0;
862
- }
863
- if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return void 0;
864
- const value = raw;
865
- const launch = value.launch;
866
- if (value.format !== WORKER_RECOVERY_FORMAT || !boundedString(value.id) || value.id !== path4.basename(runDirectory) || value.runner !== "pi-durable" || typeof value.deadlineAt !== "number" || !Number.isFinite(value.deadlineAt) || typeof value.pid !== "number" || !Number.isSafeInteger(value.pid) || value.pid <= 0 || typeof value.writtenAt !== "number" || !Number.isFinite(value.writtenAt) || typeof launch !== "object" || launch === null || Array.isArray(launch) || launch.id !== value.id || !boundedString(launch.name) || !boundedString(launch.cwd) || !boundedString(launch.workerPath) || !Array.isArray(launch.workerArguments) || launch.workerArguments.length > MAX_ARGUMENTS || launch.workerArguments.some((argument) => typeof argument !== "string" || argument.length > MAX_STRING)) {
867
- return void 0;
868
- }
869
- return {
870
- format: WORKER_RECOVERY_FORMAT,
871
- id: value.id,
872
- runner: "pi-durable",
873
- deadlineAt: value.deadlineAt,
874
- pid: value.pid,
875
- writtenAt: value.writtenAt,
876
- launch: {
877
- id: value.id,
878
- name: launch.name,
879
- cwd: launch.cwd,
880
- workerPath: launch.workerPath,
881
- workerArguments: [...launch.workerArguments]
882
- }
883
- };
884
- };
885
- var workerArgumentMap = (args) => {
886
- if (args.length % 2 !== 0) return void 0;
887
- const result = /* @__PURE__ */ new Map();
888
- for (let index = 0; index < args.length; index += 2) {
889
- const key = args[index];
890
- if (!key.startsWith("--")) return void 0;
891
- result.set(key.slice(2), args[index + 1]);
892
- }
893
- return result;
894
- };
895
- var insideDirectory = (directory, file) => {
896
- if (!path4.isAbsolute(file)) return false;
897
- const relative = path4.relative(path4.resolve(directory), path4.resolve(file));
898
- return relative !== "" && !relative.startsWith("..") && !path4.isAbsolute(relative);
899
- };
900
- var workerRecoveryMismatch = (recovery, expected) => {
901
- const authority = readWorkerRecoveryAuthority(expected.runDirectory, expected.policy);
902
- if (!authority || !isDeepStrictEqual(authority, recovery)) return "host launch receipt";
903
- const { launch } = recovery;
904
- if (path4.basename(expected.runDirectory) !== recovery.id || launch.id !== recovery.id) return "run id";
905
- if (path4.resolve(launch.workerPath) !== path4.resolve(expected.workerPath)) return "worker path";
906
- const args = workerArgumentMap(launch.workerArguments);
907
- if (!args) return "worker arguments";
908
- if (args.get("id") !== recovery.id) return "--id";
909
- if (!path4.isAbsolute(launch.cwd) || launch.cwd !== expected.cwd || args.get("cwd") !== launch.cwd) return "working directory";
910
- const pinned = [
911
- ["status-file", path4.join(expected.runDirectory, "status.json")],
912
- ["lifecycle-file", path4.join(expected.runDirectory, "lifecycle.jsonl")],
913
- ["task-file", void 0],
914
- ["log-file", void 0]
915
- ];
916
- for (const [name, exact] of pinned) {
917
- const value = args.get(name);
918
- if (value === void 0 || !insideDirectory(expected.runDirectory, value)) return `--${name}`;
919
- if (exact !== void 0 && path4.resolve(value) !== path4.resolve(exact)) return `--${name}`;
920
- }
921
- return void 0;
922
- };
923
- var signalProbe = (pid) => {
924
- try {
925
- process.kill(pid, 0);
926
- return "exists";
927
- } catch (error) {
928
- const code = error?.code;
929
- if (code === "ESRCH") return "missing";
930
- return "unknown";
931
- }
932
- };
933
- var commandLineProbe = (pid) => {
934
- try {
935
- if (process.platform === "linux") {
936
- return fs4.readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\0").join(" ");
937
- }
938
- return execFileSync("ps", ["-ww", "-o", "command=", "-p", String(pid)], {
939
- encoding: "utf8",
940
- timeout: 2e3,
941
- stdio: ["ignore", "pipe", "ignore"]
942
- });
943
- } catch {
944
- return void 0;
945
- }
946
- };
947
- var probeWorker = (pid, id, probes = {}) => {
948
- if (!Number.isSafeInteger(pid) || pid <= 0) return "dead";
949
- const signal = (probes.signal ?? signalProbe)(pid);
950
- if (signal === "missing") return "dead";
951
- if (signal === "unknown") return "unknown";
952
- const commandLine = (probes.commandLine ?? commandLineProbe)(pid);
953
- if (commandLine === void 0) return "unknown";
954
- const tokens = commandLine.trim().split(/\s+/);
955
- for (let index = 0; index < tokens.length - 1; index += 1) {
956
- if (tokens[index] === "--id" && tokens[index + 1] === id) return "alive";
957
- }
958
- return "dead";
959
- };
960
- var adoptedWorkerHandle = (pid, id, probes = {}) => ({
961
- kind: "process",
962
- sessionId: String(pid),
963
- livenessPollIntervalMs: 1e3,
964
- isAlive: async () => probeWorker(pid, id, probes) !== "dead",
965
- stop: async () => {
966
- if (probeWorker(pid, id, probes) !== "alive") return;
967
- try {
968
- process.kill(process.platform === "win32" ? pid : -pid, "SIGTERM");
969
- } catch {
970
- }
971
- }
972
- });
973
-
974
807
  // src/agents/transports/herdr-core-transport.ts
975
808
  import { randomUUID as randomUUID4 } from "node:crypto";
976
- import path5 from "node:path";
977
- import fs5 from "node:fs/promises";
809
+ import path4 from "node:path";
810
+ import fs4 from "node:fs/promises";
978
811
 
979
812
  // src/agents/constants.ts
980
813
  var AGENT_STATUS_POLL_INTERVAL_MS = 250;
@@ -1076,15 +909,15 @@ var HerdrCoreTransport = class {
1076
909
  const caller = this.environment.HC_TERMINAL_ID;
1077
910
  if (!caller) throw new Error("Herdr Core transport requires HC_TERMINAL_ID");
1078
911
  const argv = await scriptSpawnArgs(request.workerPath, request.workerArguments);
1079
- if (!path5.isAbsolute(argv[0])) {
1080
- const names = process.platform === "win32" && !path5.extname(argv[0]) ? [argv[0], ...(this.environment.PATHEXT ?? ".EXE;.CMD;.BAT").split(";").map((ext) => argv[0] + ext)] : [argv[0]];
912
+ if (!path4.isAbsolute(argv[0])) {
913
+ const names = process.platform === "win32" && !path4.extname(argv[0]) ? [argv[0], ...(this.environment.PATHEXT ?? ".EXE;.CMD;.BAT").split(";").map((ext) => argv[0] + ext)] : [argv[0]];
1081
914
  let resolved;
1082
- for (const directory of (this.environment.PATH ?? "").split(path5.delimiter).filter(Boolean)) {
915
+ for (const directory of (this.environment.PATH ?? "").split(path4.delimiter).filter(Boolean)) {
1083
916
  for (const name of names) {
1084
- const candidate = path5.resolve(directory.replace(/^"|"$/g, ""), name);
917
+ const candidate = path4.resolve(directory.replace(/^"|"$/g, ""), name);
1085
918
  try {
1086
- if ((await fs5.stat(candidate)).isFile()) {
1087
- await fs5.access(candidate, process.platform === "win32" ? fs5.constants.F_OK : fs5.constants.X_OK);
919
+ if ((await fs4.stat(candidate)).isFile()) {
920
+ await fs4.access(candidate, process.platform === "win32" ? fs4.constants.F_OK : fs4.constants.X_OK);
1088
921
  resolved = candidate;
1089
922
  break;
1090
923
  }
@@ -1362,16 +1195,16 @@ var TmuxTransport = class {
1362
1195
  };
1363
1196
 
1364
1197
  // src/agents/worktree-manager.ts
1365
- import fs9 from "node:fs";
1366
- import path9 from "node:path";
1367
-
1368
- // src/agents/clone-first-worktree.ts
1369
1198
  import fs8 from "node:fs";
1370
1199
  import path8 from "node:path";
1371
1200
 
1201
+ // src/agents/clone-first-worktree.ts
1202
+ import fs7 from "node:fs";
1203
+ import path7 from "node:path";
1204
+
1372
1205
  // src/agents/cow-clone.ts
1373
- import fs6 from "node:fs";
1374
- import path6 from "node:path";
1206
+ import fs5 from "node:fs";
1207
+ import path5 from "node:path";
1375
1208
  var CLONE_SKIP_PREFIXES = [".git", ".pi/fabric/worktrees"];
1376
1209
  var CowUnavailableError = class extends Error {
1377
1210
  constructor(message2, options) {
@@ -1387,11 +1220,11 @@ var isCowUnavailable = (error) => {
1387
1220
  };
1388
1221
  var cloneEntry = async (from, to) => {
1389
1222
  try {
1390
- await fs6.promises.cp(from, to, {
1223
+ await fs5.promises.cp(from, to, {
1391
1224
  recursive: true,
1392
1225
  verbatimSymlinks: true,
1393
1226
  force: false,
1394
- mode: fs6.constants.COPYFILE_FICLONE_FORCE
1227
+ mode: fs5.constants.COPYFILE_FICLONE_FORCE
1395
1228
  });
1396
1229
  } catch (error) {
1397
1230
  if (isCowUnavailable(error)) {
@@ -1411,13 +1244,13 @@ var hasNestedSkip = (rel, prefixes) => {
1411
1244
  return prefixes.some((prefix) => prefix.startsWith(`${value}/`));
1412
1245
  };
1413
1246
  var cloneLevel = async (source, dest, relBase, prefixes) => {
1414
- await fs6.promises.mkdir(dest, { recursive: true });
1415
- const entries = await fs6.promises.readdir(source, { withFileTypes: true });
1247
+ await fs5.promises.mkdir(dest, { recursive: true });
1248
+ const entries = await fs5.promises.readdir(source, { withFileTypes: true });
1416
1249
  for (const entry of entries) {
1417
1250
  const rel = relBase ? `${relBase}/${entry.name}` : entry.name;
1418
1251
  if (skipped(rel, prefixes)) continue;
1419
- const from = path6.join(source, entry.name);
1420
- const to = path6.join(dest, entry.name);
1252
+ const from = path5.join(source, entry.name);
1253
+ const to = path5.join(dest, entry.name);
1421
1254
  if (entry.isDirectory() && !entry.isSymbolicLink() && hasNestedSkip(rel, prefixes)) {
1422
1255
  await cloneLevel(from, to, rel, prefixes);
1423
1256
  continue;
@@ -1427,42 +1260,75 @@ var cloneLevel = async (source, dest, relBase, prefixes) => {
1427
1260
  }
1428
1261
  };
1429
1262
  var cloneTree = async (source, dest, prefixes = CLONE_SKIP_PREFIXES) => {
1430
- await fs6.promises.mkdir(dest, { recursive: true });
1431
- const [realSource, realDest] = await Promise.all([fs6.promises.realpath(source), fs6.promises.realpath(dest)]);
1432
- const relativeDest = path6.relative(realSource, realDest);
1263
+ await fs5.promises.mkdir(dest, { recursive: true });
1264
+ const [realSource, realDest] = await Promise.all([fs5.promises.realpath(source), fs5.promises.realpath(dest)]);
1265
+ const relativeDest = path5.relative(realSource, realDest);
1433
1266
  if (!relativeDest) throw new Error("Cannot clone a tree into itself");
1434
- const inside = relativeDest !== ".." && !relativeDest.startsWith(`..${path6.sep}`) && !path6.isAbsolute(relativeDest);
1267
+ const inside = relativeDest !== ".." && !relativeDest.startsWith(`..${path5.sep}`) && !path5.isAbsolute(relativeDest);
1435
1268
  await cloneLevel(realSource, realDest, "", inside ? [...prefixes, posixRel(relativeDest)] : prefixes);
1436
1269
  };
1437
1270
 
1438
1271
  // src/agents/worktree-paths.ts
1439
- import fs7 from "node:fs";
1440
- import path7 from "node:path";
1441
- var FABRIC_WORKTREE_SEGMENTS = [".pi", "fabric", "worktrees"];
1442
- var FABRIC_WORKTREE_EXCLUDE = ".pi/fabric/worktrees/";
1443
- var fabricWorktreePath = (gitRoot, id) => path7.join(gitRoot, ...FABRIC_WORKTREE_SEGMENTS, id);
1444
- var isFabricWorktreePath = (worktree, id) => {
1445
- const parts = worktree.split(/[\\/]/).filter(Boolean);
1446
- return parts.length >= 4 && parts.at(-1) === id && parts.at(-2) === "worktrees" && parts.at(-3) === "fabric" && parts.at(-4) === ".pi";
1447
- };
1448
- var ensureWorktreeExclude = async (gitRoot) => {
1272
+ import fs6 from "node:fs";
1273
+ import path6 from "node:path";
1274
+ var DEFAULT_WORKTREE_ROOT = ".pi/fabric/worktrees";
1275
+ var FABRIC_WORKTREE_EXCLUDE = `${DEFAULT_WORKTREE_ROOT}/`;
1276
+ var normalizeWorktreeRoot = (root = DEFAULT_WORKTREE_ROOT) => {
1277
+ const parts = root.split(/[\\/]/);
1278
+ if (!root.trim() || path6.posix.isAbsolute(root) || path6.win32.isAbsolute(root) || /[:\x00-\x1f\x7f]/.test(root) || parts.some((part) => {
1279
+ const portable = part.replace(/[. ]+$/g, "").toLowerCase();
1280
+ return !portable || /[. ]$/.test(part) || part === "." || part === ".." || portable === ".git";
1281
+ })) {
1282
+ throw new Error("agents.worktree.root must be a nonempty relative directory without traversal or .git components");
1283
+ }
1284
+ return parts.join("/");
1285
+ };
1286
+ var fabricWorktreePath = (gitRoot, id, root) => {
1287
+ if (!/^[a-zA-Z0-9_-]+$/.test(id)) throw new Error("Invalid worktree agent id");
1288
+ return path6.resolve(gitRoot, normalizeWorktreeRoot(root), id);
1289
+ };
1290
+ var assertWorktreePathSafe = (gitRoot, worktree) => {
1291
+ const relative = path6.relative(gitRoot, worktree);
1292
+ if (!relative || relative === ".." || relative.startsWith(`..${path6.sep}`) || path6.isAbsolute(relative)) {
1293
+ throw new Error("Worktree path must be inside its Git root");
1294
+ }
1295
+ let current = gitRoot;
1296
+ for (const part of relative.split(path6.sep)) {
1297
+ current = path6.join(current, part);
1298
+ try {
1299
+ if (fs6.lstatSync(current).isSymbolicLink()) throw new Error(`Worktree path contains a symlink: ${current}`);
1300
+ } catch (error) {
1301
+ if (error.code !== "ENOENT") throw error;
1302
+ }
1303
+ }
1304
+ };
1305
+ var isFabricWorktreePath = (worktree, id, gitRoot, root) => {
1306
+ try {
1307
+ if (gitRoot) return path6.resolve(worktree) === fabricWorktreePath(gitRoot, id, root);
1308
+ const suffix = `/${normalizeWorktreeRoot(root)}/${id}`;
1309
+ return worktree.replaceAll("\\", "/").endsWith(suffix);
1310
+ } catch {
1311
+ return false;
1312
+ }
1313
+ };
1314
+ var ensureWorktreeExclude = async (gitRoot, root) => {
1315
+ const normalized = normalizeWorktreeRoot(root);
1316
+ const entry = normalized === DEFAULT_WORKTREE_ROOT ? FABRIC_WORKTREE_EXCLUDE : `/${normalized.replace(/[\\*?\[\]#! ]/g, "\\$&")}/`;
1449
1317
  const located = await executeFile("git", ["rev-parse", "--git-path", "info/exclude"], {
1450
1318
  cwd: gitRoot,
1451
1319
  timeoutMs: 1e4
1452
1320
  });
1453
- const excludePath = path7.resolve(gitRoot, located.stdout.trim());
1454
- fs7.mkdirSync(path7.dirname(excludePath), { recursive: true });
1321
+ const excludePath = path6.resolve(gitRoot, located.stdout.trim());
1322
+ fs6.mkdirSync(path6.dirname(excludePath), { recursive: true });
1455
1323
  let current = "";
1456
1324
  try {
1457
- current = fs7.readFileSync(excludePath, "utf8");
1325
+ current = fs6.readFileSync(excludePath, "utf8");
1458
1326
  } catch (error) {
1459
- const code = error instanceof Error && "code" in error ? error.code : void 0;
1460
- if (code !== "ENOENT") throw error;
1327
+ if (error.code !== "ENOENT") throw error;
1461
1328
  }
1462
- const lines = current.split(/\r?\n/);
1463
- if (lines.some((line) => line.trim() === FABRIC_WORKTREE_EXCLUDE)) return;
1329
+ if (current.split(/\r?\n/).includes(entry)) return;
1464
1330
  const prefix = current.length === 0 || current.endsWith("\n") ? "" : "\n";
1465
- fs7.appendFileSync(excludePath, `${prefix}${FABRIC_WORKTREE_EXCLUDE}
1331
+ fs6.appendFileSync(excludePath, `${prefix}${entry}
1466
1332
  `);
1467
1333
  };
1468
1334
 
@@ -1473,10 +1339,12 @@ var worktreeRollbackError = (gitRoot, worktree, branch, error, cleanupError) =>
1473
1339
  };
1474
1340
  var addCloneFirstWorktree = async (options) => {
1475
1341
  const dest = options.dest;
1476
- if (isFabricWorktreePath(dest, path8.basename(dest))) {
1477
- await ensureWorktreeExclude(options.gitRoot);
1342
+ const managed = isFabricWorktreePath(dest, path7.basename(dest), options.gitRoot, options.worktreeRoot);
1343
+ if (managed) {
1344
+ assertWorktreePathSafe(options.gitRoot, dest);
1345
+ await ensureWorktreeExclude(options.gitRoot, options.worktreeRoot);
1478
1346
  }
1479
- fs8.mkdirSync(path8.dirname(dest), { recursive: true });
1347
+ fs7.mkdirSync(path7.dirname(dest), { recursive: true });
1480
1348
  const args = ["worktree", "add", "--no-checkout"];
1481
1349
  if (options.quiet) args.push("-q");
1482
1350
  if (options.detach) args.push("--detach");
@@ -1487,7 +1355,7 @@ var addCloneFirstWorktree = async (options) => {
1487
1355
  try {
1488
1356
  let cloned = false;
1489
1357
  try {
1490
- await cloneTree(options.gitRoot, dest, CLONE_SKIP_PREFIXES);
1358
+ await cloneTree(options.gitRoot, dest, managed ? [...CLONE_SKIP_PREFIXES, path7.relative(options.gitRoot, path7.dirname(dest)).split(path7.sep).join("/")] : CLONE_SKIP_PREFIXES);
1491
1359
  cloned = true;
1492
1360
  } catch (error) {
1493
1361
  if (!(error instanceof CowUnavailableError)) throw error;
@@ -1510,7 +1378,7 @@ var removeWorktree = async (gitRoot, worktree, branch) => {
1510
1378
  try {
1511
1379
  await executeFile("git", ["worktree", "remove", "--force", worktree], { cwd: gitRoot, timeoutMs: 6e4 });
1512
1380
  } catch (error) {
1513
- if (fs8.existsSync(worktree)) failure = error;
1381
+ if (fs7.existsSync(worktree)) failure = error;
1514
1382
  else await executeFile("git", ["worktree", "prune"], { cwd: gitRoot, timeoutMs: 3e4 }).catch(() => void 0);
1515
1383
  }
1516
1384
  if (branch) {
@@ -1534,9 +1402,9 @@ var SETUP_TIMEOUT_MS = 10 * 6e4;
1534
1402
  var SETUP_OUTPUT_TAIL_CHARS = 2e3;
1535
1403
  var countLines = (file) => {
1536
1404
  try {
1537
- const stat = fs9.statSync(file);
1405
+ const stat = fs8.statSync(file);
1538
1406
  if (!stat.isFile() || stat.size > MAX_COUNTED_BYTES) return 0;
1539
- const content = fs9.readFileSync(file);
1407
+ const content = fs8.readFileSync(file);
1540
1408
  if (content.length === 0 || content.includes(0)) return 0;
1541
1409
  let lines = 0;
1542
1410
  for (const byte of content) if (byte === 10) lines++;
@@ -1547,8 +1415,8 @@ var countLines = (file) => {
1547
1415
  };
1548
1416
  var safeLabel = (value) => value.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 30) || "agent";
1549
1417
  var isInside2 = (root, target) => {
1550
- const relative = path9.relative(root, target);
1551
- return relative === "" || relative !== ".." && !relative.startsWith(`..${path9.sep}`) && !path9.isAbsolute(relative);
1418
+ const relative = path8.relative(root, target);
1419
+ return relative === "" || relative !== ".." && !relative.startsWith(`..${path8.sep}`) && !path8.isAbsolute(relative);
1552
1420
  };
1553
1421
  var worktreePrefixParts = (prefix) => {
1554
1422
  const parts = prefix.split(/[\\/]+/).filter(Boolean);
@@ -1556,7 +1424,7 @@ var worktreePrefixParts = (prefix) => {
1556
1424
  };
1557
1425
  var WorktreeManager = class {
1558
1426
  #leases = /* @__PURE__ */ new Map();
1559
- async create(id, cwd, name, preserveSourceSubdirectory = false) {
1427
+ async create(id, cwd, name, preserveSourceSubdirectory = false, options = {}) {
1560
1428
  let gitRoot;
1561
1429
  let sourcePrefix = "";
1562
1430
  try {
@@ -1566,24 +1434,32 @@ var WorktreeManager = class {
1566
1434
  ]);
1567
1435
  const output = root.stdout.trim();
1568
1436
  if (!output) throw new Error("Git did not return a worktree root");
1569
- gitRoot = fs9.realpathSync(output);
1437
+ gitRoot = fs8.realpathSync(output);
1570
1438
  sourcePrefix = prefix2.stdout.trim();
1571
1439
  } catch (error) {
1572
1440
  const failure = error;
1573
1441
  const detail = (failure.stderr?.trim() || failure.message || String(error)).split("\n", 1)[0].slice(0, 500);
1574
1442
  throw new Error(`Worktree isolation requires a Git repository: ${detail}`, { cause: error });
1575
1443
  }
1576
- const branch = `pi-fabric/${safeLabel(name)}-${id.slice(0, 8)}`;
1577
- const worktreePath = fabricWorktreePath(gitRoot, id);
1444
+ const template = options.branch ?? "pi-fabric/{name}-{id8}";
1445
+ const values = { name: safeLabel(name), id, id8: id.slice(0, 8) };
1446
+ const branch = template.replace(/\{([^{}]+)\}/g, (token, key) => Object.hasOwn(values, key) ? values[key] : token);
1447
+ if (/[{}]/.test(branch) || !branch || branch.startsWith("-")) {
1448
+ throw new Error("Invalid agents.worktree.branch template (use {name}, {id}, {id8})");
1449
+ }
1450
+ await executeFile("git", ["check-ref-format", "--branch", branch], { cwd: gitRoot });
1451
+ const worktreePath = fabricWorktreePath(gitRoot, id, options.root);
1452
+ assertWorktreePathSafe(gitRoot, worktreePath);
1578
1453
  await addCloneFirstWorktree({
1579
1454
  gitRoot,
1580
1455
  dest: worktreePath,
1456
+ ...options.root !== void 0 ? { worktreeRoot: options.root } : {},
1581
1457
  branch: { flag: "-b", name: branch },
1582
1458
  startPoint: "HEAD"
1583
1459
  });
1584
1460
  let canonicalWorktreePath;
1585
1461
  try {
1586
- canonicalWorktreePath = fs9.realpathSync(worktreePath);
1462
+ canonicalWorktreePath = fs8.realpathSync(worktreePath);
1587
1463
  } catch (error) {
1588
1464
  try {
1589
1465
  await removeWorktree(gitRoot, worktreePath, branch);
@@ -1596,10 +1472,10 @@ var WorktreeManager = class {
1596
1472
  const prefix = preserveSourceSubdirectory ? worktreePrefixParts(sourcePrefix) : void 0;
1597
1473
  let effectiveCwd = canonicalWorktreePath;
1598
1474
  if (prefix && prefix.length > 0) {
1599
- const candidate = path9.resolve(canonicalWorktreePath, ...prefix);
1475
+ const candidate = path8.resolve(canonicalWorktreePath, ...prefix);
1600
1476
  try {
1601
- const canonicalCandidate = fs9.realpathSync(candidate);
1602
- if (fs9.statSync(canonicalCandidate).isDirectory() && isInside2(canonicalWorktreePath, canonicalCandidate)) {
1477
+ const canonicalCandidate = fs8.realpathSync(candidate);
1478
+ if (fs8.statSync(canonicalCandidate).isDirectory() && isInside2(canonicalWorktreePath, canonicalCandidate)) {
1603
1479
  effectiveCwd = canonicalCandidate;
1604
1480
  }
1605
1481
  } catch {
@@ -1638,7 +1514,7 @@ ${tail}` : ""}`);
1638
1514
  ...lease.baseRef ? { baseRef: lease.baseRef } : {},
1639
1515
  changedFiles: [],
1640
1516
  diffstat: { files: 0, insertions: 0, deletions: 0 },
1641
- kept: fs9.existsSync(lease.path)
1517
+ kept: fs8.existsSync(lease.path)
1642
1518
  };
1643
1519
  if (!result.kept) return result;
1644
1520
  try {
@@ -1658,7 +1534,7 @@ ${tail}` : ""}`);
1658
1534
  for (const file of untracked.stdout.split("\n")) {
1659
1535
  if (!file || files.has(file)) continue;
1660
1536
  files.add(file);
1661
- if (files.size <= MAX_CHANGED_FILES) result.diffstat.insertions += countLines(path9.join(lease.path, file));
1537
+ if (files.size <= MAX_CHANGED_FILES) result.diffstat.insertions += countLines(path8.join(lease.path, file));
1662
1538
  }
1663
1539
  result.diffstat.files = files.size;
1664
1540
  result.changedFiles = [...files].sort().slice(0, MAX_CHANGED_FILES);
@@ -1670,6 +1546,11 @@ ${tail}` : ""}`);
1670
1546
  async cleanup(id, deleteBranch = false) {
1671
1547
  const lease = this.#leases.get(id);
1672
1548
  if (!lease) return false;
1549
+ assertWorktreePathSafe(lease.gitRoot, lease.path);
1550
+ if (deleteBranch && fs8.existsSync(path8.join(lease.path, ".git"))) {
1551
+ const actualBranch = (await executeFile("git", ["symbolic-ref", "--quiet", "--short", "HEAD"], { cwd: lease.path, timeoutMs: GIT_SUMMARY_TIMEOUT_MS })).stdout.trim();
1552
+ if (actualBranch !== lease.branch) throw new Error("Refusing cleanup: worktree branch ownership changed");
1553
+ }
1673
1554
  await removeWorktree(lease.gitRoot, lease.path, deleteBranch ? lease.branch : void 0);
1674
1555
  if (this.#leases.get(id) === lease) this.#leases.delete(id);
1675
1556
  return true;
@@ -1678,8 +1559,8 @@ ${tail}` : ""}`);
1678
1559
 
1679
1560
  // src/agents/handoff.ts
1680
1561
  import { randomUUID as randomUUID5 } from "node:crypto";
1681
- import fs10 from "node:fs";
1682
- import path10 from "node:path";
1562
+ import fs9 from "node:fs";
1563
+ import path9 from "node:path";
1683
1564
 
1684
1565
  // src/core/host-sdk-runtime.ts
1685
1566
  var PiCodingAgent = await loadHostSdk();
@@ -1824,10 +1705,18 @@ var checkedHandoffCompaction = (value) => {
1824
1705
  var isToolCall = (value) => isRecord2(value) && value.type === "toolCall" && typeof value.id === "string" && typeof value.name === "string" && isRecord2(value.arguments);
1825
1706
  var activeFabricTurn = (source, outerToolCallId) => {
1826
1707
  const leafId = source.getLeafId();
1827
- const entry = leafId ? source.getEntry(leafId) : void 0;
1708
+ let entry = leafId ? source.getEntry(leafId) : void 0;
1709
+ const visited = /* @__PURE__ */ new Set();
1710
+ while (entry && (entry.type === "custom" || entry.type === "label" || entry.type === "session_info" || entry.type === "model_change" || entry.type === "thinking_level_change" || entry.type === "usage")) {
1711
+ if (visited.has(entry.id)) {
1712
+ throw new Error("Trajectory handoff encountered cyclic session metadata");
1713
+ }
1714
+ visited.add(entry.id);
1715
+ entry = entry.parentId ? source.getEntry(entry.parentId) : void 0;
1716
+ }
1828
1717
  if (entry?.type !== "message" || entry.message.role !== "assistant") {
1829
1718
  throw new Error(
1830
- "Trajectory handoff requires the active fabric_exec assistant turn to be the session leaf"
1719
+ "Trajectory handoff requires the active fabric_exec assistant turn to be the latest session message"
1831
1720
  );
1832
1721
  }
1833
1722
  const content = Array.isArray(entry.message.content) ? entry.message.content : [];
@@ -1866,7 +1755,8 @@ var snapshotHandoffSession = (source, currentModel, outerToolResult, outerToolCa
1866
1755
  return {
1867
1756
  sourceSessionId: source.getSessionId(),
1868
1757
  ...sourceSessionFile ? { sourceSessionFile } : {},
1869
- sourceBranchLeafId: active.id,
1758
+ // Preserve trailing metadata in persisted forks just as in-memory seeds do.
1759
+ sourceBranchLeafId: source.getLeafId() ?? active.id,
1870
1760
  ...!sourceSessionFile ? { sourceBranch: structuredClone(branch) } : {},
1871
1761
  ...model ? { sourceModel: model } : {},
1872
1762
  ...thinkingLevel ? { sourceThinkingLevel: thinkingLevel } : {},
@@ -1891,7 +1781,7 @@ var materializeBranch = (seed, cwd, directory, options = {}) => {
1891
1781
  throw new Error("In-memory trajectory handoff is missing its source branch");
1892
1782
  }
1893
1783
  const id = randomUUID5();
1894
- const sessionFile = path10.join(directory, `handoff-${id}.jsonl`);
1784
+ const sessionFile = path9.join(directory, `handoff-${id}.jsonl`);
1895
1785
  const header = {
1896
1786
  type: "session",
1897
1787
  version: PiCodingAgent.CURRENT_SESSION_VERSION,
@@ -1901,7 +1791,7 @@ var materializeBranch = (seed, cwd, directory, options = {}) => {
1901
1791
  ...seed.sourceSessionFile ? { parentSession: seed.sourceSessionFile } : {}
1902
1792
  };
1903
1793
  const entries = options.workerRole ? withWorkerRoot(seed.sourceBranch) : seed.sourceBranch;
1904
- fs10.writeFileSync(
1794
+ fs9.writeFileSync(
1905
1795
  sessionFile,
1906
1796
  `${[header, ...entries].map((entry) => JSON.stringify(entry)).join("\n")}
1907
1797
  `,
@@ -1910,13 +1800,13 @@ var materializeBranch = (seed, cwd, directory, options = {}) => {
1910
1800
  return PiCodingAgent.SessionManager.open(sessionFile, directory, cwd);
1911
1801
  };
1912
1802
  var insertWorkerRoot = (sessionFile) => {
1913
- if (!fs10.existsSync(sessionFile)) {
1803
+ if (!fs9.existsSync(sessionFile)) {
1914
1804
  throw new Error("Trajectory handoff session file was not written, so the worker role cannot be placed at its root");
1915
1805
  }
1916
- const [headerLine, ...entryLines] = fs10.readFileSync(sessionFile, "utf8").split("\n").filter((line) => line.length > 0);
1806
+ const [headerLine, ...entryLines] = fs9.readFileSync(sessionFile, "utf8").split("\n").filter((line) => line.length > 0);
1917
1807
  const entries = entryLines.map((line) => JSON.parse(line));
1918
1808
  const placed = withWorkerRoot(entries);
1919
- fs10.writeFileSync(
1809
+ fs9.writeFileSync(
1920
1810
  sessionFile,
1921
1811
  `${[headerLine, ...placed.map((entry) => JSON.stringify(entry))].join("\n")}
1922
1812
  `,
@@ -1959,7 +1849,7 @@ var synchronizeSourceSettings = (session, seed) => {
1959
1849
  }
1960
1850
  };
1961
1851
  var writeHandoffSession = (seed, cwd, directory, transfer, compaction, compactionBudget, options = {}) => {
1962
- fs10.mkdirSync(directory, { recursive: true, mode: 448 });
1852
+ fs9.mkdirSync(directory, { recursive: true, mode: 448 });
1963
1853
  const policy = transfer ? thinkingTransferPolicy(transfer) : "preserved";
1964
1854
  let session;
1965
1855
  const viaPiBranch = Boolean(seed.sourceSessionFile) && (!transfer || policy === "preserved");
@@ -2035,11 +1925,11 @@ var writeHandoffSession = (seed, cwd, directory, transfer, compaction, compactio
2035
1925
  const sessionFile = session.getSessionFile();
2036
1926
  if (!sessionFile) throw new Error("Trajectory handoff did not produce a Pi session file");
2037
1927
  if (options.workerRole && viaPiBranch) insertWorkerRoot(sessionFile);
2038
- fs10.chmodSync(sessionFile, 384);
1928
+ fs9.chmodSync(sessionFile, 384);
2039
1929
  return sessionFile;
2040
1930
  };
2041
1931
  var writeForkSession = (seed, cwd, directory, transfer, options = {}) => {
2042
- fs10.mkdirSync(directory, { recursive: true, mode: 448 });
1932
+ fs9.mkdirSync(directory, { recursive: true, mode: 448 });
2043
1933
  const policy = transfer ? thinkingTransferPolicy(transfer) : "preserved";
2044
1934
  const raw = structuredClone(seed.sourceBranch);
2045
1935
  const digest = policy === "stripped" && transfer ? buildThinkingDigest(raw, transfer) : void 0;
@@ -2063,13 +1953,13 @@ var writeForkSession = (seed, cwd, directory, transfer, options = {}) => {
2063
1953
  });
2064
1954
  const sessionFile = session.getSessionFile();
2065
1955
  if (!sessionFile) throw new Error("Branch seed did not produce a Pi session file");
2066
- fs10.chmodSync(sessionFile, 384);
1956
+ fs9.chmodSync(sessionFile, 384);
2067
1957
  return sessionFile;
2068
1958
  };
2069
1959
 
2070
1960
  // src/agents/child-env.ts
2071
- import fs11 from "node:fs";
2072
- import path11 from "node:path";
1961
+ import fs10 from "node:fs";
1962
+ import path10 from "node:path";
2073
1963
  var MAX_WRITABLE_ROOTS = 32;
2074
1964
  var MAX_ROOT_CHARS = 4096;
2075
1965
  var readAgentLineage = (raw = process.env.PI_FABRIC_LINEAGE) => {
@@ -2100,12 +1990,12 @@ var checkWritePolicyRequest = (request) => {
2100
1990
  };
2101
1991
  var nearestExisting = (target) => {
2102
1992
  let current = target;
2103
- while (!fs11.existsSync(current)) {
2104
- const parent = path11.dirname(current);
1993
+ while (!fs10.existsSync(current)) {
1994
+ const parent = path10.dirname(current);
2105
1995
  if (parent === current) break;
2106
1996
  current = parent;
2107
1997
  }
2108
- return path11.join(fs11.realpathSync(current), path11.relative(current, target));
1998
+ return path10.join(fs10.realpathSync(current), path10.relative(current, target));
2109
1999
  };
2110
2000
  var resolveChildWritePolicy = (request, parent, cwd) => {
2111
2001
  if (!requestsWritePolicy(request)) return parent;
@@ -2118,21 +2008,21 @@ var resolveChildWritePolicy = (request, parent, cwd) => {
2118
2008
  throw new Error('A shell-confined agent cannot launch a child with shell: "unconfined"');
2119
2009
  }
2120
2010
  if (readOnly) return { readOnly, writableRoots: [], shell };
2121
- const realCwd = fs11.realpathSync(cwd);
2011
+ const realCwd = fs10.realpathSync(cwd);
2122
2012
  const within = (target) => !parent || parent.writableRoots.some((root) => isInside(root, target));
2123
2013
  const roots = request.writableRoots ?? (parent ? parent.writableRoots : [cwd]);
2124
2014
  const resolved = /* @__PURE__ */ new Set();
2125
2015
  for (const root of roots) {
2126
- const absolute = path11.resolve(cwd, root);
2127
- if (!fs11.existsSync(absolute)) {
2016
+ const absolute = path10.resolve(cwd, root);
2017
+ if (!fs10.existsSync(absolute)) {
2128
2018
  const target = nearestExisting(absolute);
2129
2019
  if (!isInside(cwd, absolute) || !isInside(realCwd, target) || !within(target)) {
2130
2020
  throw new Error(`Writable root must exist or be creatable inside the agent cwd: ${root}`);
2131
2021
  }
2132
- fs11.mkdirSync(absolute, { recursive: true });
2022
+ fs10.mkdirSync(absolute, { recursive: true });
2133
2023
  }
2134
- const real = fs11.realpathSync(absolute);
2135
- if (!fs11.statSync(real).isDirectory()) throw new Error(`Writable root is not a directory: ${root}`);
2024
+ const real = fs10.realpathSync(absolute);
2025
+ if (!fs10.statSync(real).isDirectory()) throw new Error(`Writable root is not a directory: ${root}`);
2136
2026
  if (!within(real)) throw new Error(`Writable root is outside the caller's writable roots: ${root}`);
2137
2027
  resolved.add(real);
2138
2028
  }
@@ -2173,17 +2063,17 @@ var budgetAdmits = (spent, limit) => {
2173
2063
  };
2174
2064
 
2175
2065
  // src/storage/retention.ts
2176
- import fs12 from "node:fs";
2177
- import path12 from "node:path";
2066
+ import fs11 from "node:fs";
2067
+ import path11 from "node:path";
2178
2068
  var RUN_ROOT_OWNER_FILE = ".fabric-owner.json";
2179
2069
  var TERMINAL_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "stopped", "timed_out"]);
2180
2070
  var RUN_ROOT_HEARTBEAT_TTL_MS = 45 * 60 * 1e3;
2181
- var ownerPath = (root) => path12.join(root, RUN_ROOT_OWNER_FILE);
2071
+ var ownerPath = (root) => path11.join(root, RUN_ROOT_OWNER_FILE);
2182
2072
  var readJson = (file) => {
2183
2073
  try {
2184
2074
  const stat = ownedStat(file);
2185
2075
  if (!stat?.isFile() || stat.size > 1024 * 1024) return;
2186
- return JSON.parse(fs12.readFileSync(file, "utf8"));
2076
+ return JSON.parse(fs11.readFileSync(file, "utf8"));
2187
2077
  } catch {
2188
2078
  return;
2189
2079
  }
@@ -2191,9 +2081,9 @@ var readJson = (file) => {
2191
2081
  var time = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
2192
2082
  var validOwner = (owner) => !!owner && Number.isSafeInteger(owner.pid) && owner.pid > 0 && time(owner.startedAt) && time(owner.heartbeatAt) && (owner.closedAt === void 0 || time(owner.closedAt)) && (owner.orphanedAt === void 0 || time(owner.orphanedAt)) && (owner.childrenStopped === void 0 || typeof owner.childrenStopped === "boolean");
2193
2083
  var writeOwner = (root, owner) => {
2194
- if (fs12.existsSync(root) && !ownedStat(root)?.isDirectory()) throw new Error("Unsafe Fabric run root");
2084
+ if (fs11.existsSync(root) && !ownedStat(root)?.isDirectory()) throw new Error("Unsafe Fabric run root");
2195
2085
  const file = ownerPath(root);
2196
- if (fs12.existsSync(file)) {
2086
+ if (fs11.existsSync(file)) {
2197
2087
  const existing = readJson(file);
2198
2088
  if (!validOwner(existing) || existing.pid !== owner.pid) throw new Error("Unsafe Fabric run owner marker");
2199
2089
  }
@@ -2240,21 +2130,21 @@ var DURABLE_KEY = /^(?:initial|[0-9a-f]{64})$/;
2240
2130
  var DURABLE_LEASE_FILES = /* @__PURE__ */ new Set(["lease.sqlite", "lease.sqlite-journal"]);
2241
2131
  var DURABLE_STORE_FILE = /^(?:main|(?:doc|task)-(?:0|[1-9]\d*))\.jsonl(?:\.reclaim)?$/;
2242
2132
  var FABRIC_JOURNAL_FILE = /^[0-9a-f]{32}\.jsonl$/;
2243
- var onlyOwnedFiles = (directory, allowed) => fs12.readdirSync(directory).every((name) => allowed(name) && ownedStat(path12.join(directory, name))?.isFile() === true);
2133
+ var onlyOwnedFiles = (directory, allowed) => fs11.readdirSync(directory).every((name) => allowed(name) && ownedStat(path11.join(directory, name))?.isFile() === true);
2244
2134
  var DURABLE_SESSION_FILE = "session.jsonl";
2245
2135
  var DURABLE_SESSION_TEMP = /^tmp-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.jsonl$/;
2246
2136
  var DURABLE_SESSION_SIDECAR = /^session\.jsonl\.[A-Za-z0-9][A-Za-z0-9._-]*$/;
2247
2137
  var safeDurableSessionFolder = (directory) => {
2248
2138
  const uid = process.getuid?.();
2249
2139
  const stats = /* @__PURE__ */ new Map();
2250
- for (const name of fs12.readdirSync(directory)) {
2140
+ for (const name of fs11.readdirSync(directory)) {
2251
2141
  if (DURABLE_SESSION_SIDECAR.test(name)) {
2252
- const sidecar = fs12.lstatSync(path12.join(directory, name));
2142
+ const sidecar = fs11.lstatSync(path11.join(directory, name));
2253
2143
  if (!sidecar.isFile() || uid !== void 0 && sidecar.uid !== uid || sidecar.nlink !== 1) return false;
2254
2144
  continue;
2255
2145
  }
2256
2146
  if (name !== DURABLE_SESSION_FILE && !DURABLE_SESSION_TEMP.test(name)) return false;
2257
- const stat = fs12.lstatSync(path12.join(directory, name));
2147
+ const stat = fs11.lstatSync(path11.join(directory, name));
2258
2148
  if (!stat.isFile() || uid !== void 0 && stat.uid !== uid || stat.nlink > 2) return false;
2259
2149
  stats.set(name, stat);
2260
2150
  }
@@ -2265,11 +2155,11 @@ var safeDurableSessionFolder = (directory) => {
2265
2155
  const [temporary] = temporaries;
2266
2156
  return stats.size === 2 && session !== void 0 && temporaries.length === 1 && temporary !== void 0 && session.nlink === 2 && temporary[1].nlink === 2 && session.dev === temporary[1].dev && session.ino === temporary[1].ino;
2267
2157
  };
2268
- var safeDurableTree = (directory) => fs12.readdirSync(directory).every((key) => {
2269
- const conversation = path12.join(directory, key);
2158
+ var safeDurableTree = (directory) => fs11.readdirSync(directory).every((key) => {
2159
+ const conversation = path11.join(directory, key);
2270
2160
  if (!DURABLE_KEY.test(key) || !ownedStat(conversation)?.isDirectory()) return false;
2271
- return fs12.readdirSync(conversation).every((name) => {
2272
- const file = path12.join(conversation, name);
2161
+ return fs11.readdirSync(conversation).every((name) => {
2162
+ const file = path11.join(conversation, name);
2273
2163
  if (name === "store") return ownedStat(file)?.isDirectory() === true && onlyOwnedFiles(file, (child) => DURABLE_STORE_FILE.test(child));
2274
2164
  if (name === "fabric-journal") return ownedStat(file)?.isDirectory() === true && onlyOwnedFiles(file, (child) => FABRIC_JOURNAL_FILE.test(child));
2275
2165
  return DURABLE_LEASE_FILES.has(name) && ownedStat(file)?.isFile() === true;
@@ -2277,25 +2167,25 @@ var safeDurableTree = (directory) => fs12.readdirSync(directory).every((key) =>
2277
2167
  });
2278
2168
  var ownedTree = (directory, depth) => {
2279
2169
  if (depth > 32) return false;
2280
- return fs12.readdirSync(directory).every((name) => {
2281
- const stat = ownedStat(path12.join(directory, name));
2170
+ return fs11.readdirSync(directory).every((name) => {
2171
+ const stat = ownedStat(path11.join(directory, name));
2282
2172
  if (!stat || name.startsWith("hosted.json")) return false;
2283
- return stat.isFile() || stat.isDirectory() && ownedTree(path12.join(directory, name), depth + 1);
2173
+ return stat.isFile() || stat.isDirectory() && ownedTree(path11.join(directory, name), depth + 1);
2284
2174
  });
2285
2175
  };
2286
2176
  var safeRunTree = (root, childrenStopped, owner, depth = 0, anyContents = false) => {
2287
2177
  if (depth > 32 || !ownedStat(root)?.isDirectory()) return false;
2288
- const record = readJson(path12.join(root, "status.json"));
2178
+ const record = readJson(path11.join(root, "status.json"));
2289
2179
  const pid = record?.transport === "process" && typeof record.sessionId === "string" && /^\d+$/.test(record.sessionId) ? Number(record.sessionId) : void 0;
2290
2180
  if (pid !== void 0 && childAlive(owner, pid)) return false;
2291
2181
  const terminal2 = !!record?.status && TERMINAL_STATUSES.has(record.status);
2292
2182
  if (!terminal2) {
2293
2183
  if (!childrenStopped && pid === void 0) return false;
2294
- if (!ownedStat(path12.join(root, "task.txt"))?.isFile()) return false;
2184
+ if (!ownedStat(path11.join(root, "task.txt"))?.isFile()) return false;
2295
2185
  }
2296
2186
  try {
2297
- for (const name of fs12.readdirSync(root)) {
2298
- const file = path12.join(root, name);
2187
+ for (const name of fs11.readdirSync(root)) {
2188
+ const file = path11.join(root, name);
2299
2189
  const stat = ownedStat(file);
2300
2190
  if (!stat) return false;
2301
2191
  if (stat.isFile() && (runFiles.has(name) || name === OVERSIZED_EVENT_FILE || STATUS_TEMP_FILE.test(name))) continue;
@@ -2308,7 +2198,7 @@ var safeRunTree = (root, childrenStopped, owner, depth = 0, anyContents = false)
2308
2198
  continue;
2309
2199
  }
2310
2200
  if (stat.isDirectory() && name === "handoff-session") {
2311
- if (fs12.readdirSync(file).some((child) => !child.endsWith(".jsonl") || !ownedStat(path12.join(file, child))?.isFile())) return false;
2201
+ if (fs11.readdirSync(file).some((child) => !child.endsWith(".jsonl") || !ownedStat(path11.join(file, child))?.isFile())) return false;
2312
2202
  continue;
2313
2203
  }
2314
2204
  if (stat.isDirectory() && name === "durable-session") {
@@ -2320,7 +2210,7 @@ var safeRunTree = (root, childrenStopped, owner, depth = 0, anyContents = false)
2320
2210
  continue;
2321
2211
  }
2322
2212
  if (stat.isDirectory() && name === "nested") {
2323
- for (const child of fs12.readdirSync(file)) if (!safeRunTree(path12.join(file, child), false, owner, depth + 1, anyContents)) return false;
2213
+ for (const child of fs11.readdirSync(file)) if (!safeRunTree(path11.join(file, child), false, owner, depth + 1, anyContents)) return false;
2324
2214
  continue;
2325
2215
  }
2326
2216
  return false;
@@ -2332,7 +2222,7 @@ var safeRunTree = (root, childrenStopped, owner, depth = 0, anyContents = false)
2332
2222
  };
2333
2223
  var safeRootContents = (root, childrenStopped, owner, anyContents = false) => {
2334
2224
  try {
2335
- return fs12.readdirSync(root).every((name) => name === RUN_ROOT_OWNER_FILE || safeRunTree(path12.join(root, name), childrenStopped, owner, 0, anyContents));
2225
+ return fs11.readdirSync(root).every((name) => name === RUN_ROOT_OWNER_FILE || safeRunTree(path11.join(root, name), childrenStopped, owner, 0, anyContents));
2336
2226
  } catch {
2337
2227
  return false;
2338
2228
  }
@@ -2345,8 +2235,8 @@ var canRemoveManagedRunRoot = (root) => {
2345
2235
  var removeEmptyRunRoot = (root) => {
2346
2236
  try {
2347
2237
  if (!ownedStat(root)?.isDirectory() || !validOwner(readJson(ownerPath(root)))) return false;
2348
- if (fs12.readdirSync(root).some((name) => name !== RUN_ROOT_OWNER_FILE)) return false;
2349
- fs12.rmSync(root, { recursive: true, force: true });
2238
+ if (fs11.readdirSync(root).some((name) => name !== RUN_ROOT_OWNER_FILE)) return false;
2239
+ fs11.rmSync(root, { recursive: true, force: true });
2350
2240
  return true;
2351
2241
  } catch {
2352
2242
  return false;
@@ -2356,21 +2246,21 @@ var pruneClosedRunRoot = (root, owner, orphanMs, oneShotMs, now) => {
2356
2246
  const removed = [];
2357
2247
  let entries;
2358
2248
  try {
2359
- entries = fs12.readdirSync(root, { withFileTypes: true });
2249
+ entries = fs11.readdirSync(root, { withFileTypes: true });
2360
2250
  } catch {
2361
2251
  return removed;
2362
2252
  }
2363
2253
  for (const entry of entries) {
2364
2254
  if (!entry.isDirectory()) continue;
2365
- const directory = path12.join(root, entry.name);
2255
+ const directory = path11.join(root, entry.name);
2366
2256
  if (!safeRunTree(directory, owner.childrenStopped === true, owner)) continue;
2367
- const record = readJson(path12.join(directory, "status.json"));
2257
+ const record = readJson(path11.join(directory, "status.json"));
2368
2258
  const terminal2 = !!record?.status && TERMINAL_STATUSES.has(record.status);
2369
2259
  const reference = terminal2 ? recordAgeReference(record, ownedStat(directory)?.mtimeMs ?? now) : owner.closedAt;
2370
2260
  const retention = terminal2 && !record?.actorId ? oneShotMs : orphanMs;
2371
2261
  if (now - reference < retention) continue;
2372
2262
  try {
2373
- fs12.rmSync(directory, { recursive: true, force: true });
2263
+ fs11.rmSync(directory, { recursive: true, force: true });
2374
2264
  removed.push(directory);
2375
2265
  } catch {
2376
2266
  }
@@ -2382,14 +2272,14 @@ var sweepTempRunRoots = (options) => {
2382
2272
  const result = { removedRoots: [], removedRuns: [] };
2383
2273
  let entries;
2384
2274
  try {
2385
- entries = fs12.readdirSync(options.tempRoot, { withFileTypes: true });
2275
+ entries = fs11.readdirSync(options.tempRoot, { withFileTypes: true });
2386
2276
  } catch {
2387
2277
  return result;
2388
2278
  }
2389
2279
  for (const entry of entries) {
2390
2280
  if (!entry.isDirectory() || !/^pi-fabric-runs-[A-Za-z0-9_-]+$/.test(entry.name)) continue;
2391
- const root = path12.join(options.tempRoot, entry.name);
2392
- if (options.currentRoot && path12.resolve(root) === path12.resolve(options.currentRoot)) continue;
2281
+ const root = path11.join(options.tempRoot, entry.name);
2282
+ if (options.currentRoot && path11.resolve(root) === path11.resolve(options.currentRoot)) continue;
2393
2283
  if (!ownedStat(root)?.isDirectory()) continue;
2394
2284
  const owner = readJson(ownerPath(root));
2395
2285
  if (!validOwner(owner)) continue;
@@ -2408,7 +2298,7 @@ var sweepTempRunRoots = (options) => {
2408
2298
  }
2409
2299
  if (now - owner.orphanedAt < options.orphanedTempRunRetentionMs || !safeRootContents(root, false, owner, true)) continue;
2410
2300
  try {
2411
- fs12.rmSync(root, { recursive: true, force: true });
2301
+ fs11.rmSync(root, { recursive: true, force: true });
2412
2302
  result.removedRoots.push(root);
2413
2303
  } catch {
2414
2304
  }
@@ -2421,18 +2311,18 @@ var pruneActorRunArchives = (options) => {
2421
2311
  if (!ownedStat(options.runsDirectory)?.isDirectory()) return removed;
2422
2312
  let entries;
2423
2313
  try {
2424
- entries = fs12.readdirSync(options.runsDirectory, { withFileTypes: true });
2314
+ entries = fs11.readdirSync(options.runsDirectory, { withFileTypes: true });
2425
2315
  } catch {
2426
2316
  return removed;
2427
2317
  }
2428
2318
  for (const entry of entries) {
2429
2319
  if (!entry.isDirectory() || entry.name === options.latestRunId) continue;
2430
- const directory = path12.join(options.runsDirectory, entry.name);
2431
- const record = readJson(path12.join(directory, "status.json"));
2320
+ const directory = path11.join(options.runsDirectory, entry.name);
2321
+ const record = readJson(path11.join(directory, "status.json"));
2432
2322
  if (!record?.status || !TERMINAL_STATUSES.has(record.status) || !safeRunTree(directory, false)) continue;
2433
2323
  if (now - recordAgeReference(record, ownedStat(directory)?.mtimeMs ?? now) < options.retentionMs) continue;
2434
2324
  try {
2435
- fs12.rmSync(directory, { recursive: true, force: true });
2325
+ fs11.rmSync(directory, { recursive: true, force: true });
2436
2326
  removed.push(directory);
2437
2327
  } catch {
2438
2328
  }
@@ -2442,21 +2332,21 @@ var pruneActorRunArchives = (options) => {
2442
2332
 
2443
2333
  // src/agents/session-export.ts
2444
2334
  import os2 from "node:os";
2445
- import path13 from "node:path";
2335
+ import path12 from "node:path";
2446
2336
  var SESSION_EXPORT_ENV = "PI_FABRIC_AGENT_DIR";
2447
- var expandHome = (value) => value === "~" ? os2.homedir() : value.startsWith("~/") || value.startsWith(`~${path13.win32.sep}`) ? path13.join(os2.homedir(), value.slice(2)) : value;
2337
+ var expandHome = (value) => value === "~" ? os2.homedir() : value.startsWith("~/") || value.startsWith(`~${path12.win32.sep}`) ? path12.join(os2.homedir(), value.slice(2)) : value;
2448
2338
  var encodeSessionExportCwd = (cwd) => {
2449
- const absolute = path13.isAbsolute(cwd) || path13.win32.isAbsolute(cwd) ? cwd : path13.resolve(cwd);
2339
+ const absolute = path12.isAbsolute(cwd) || path12.win32.isAbsolute(cwd) ? cwd : path12.resolve(cwd);
2450
2340
  return `--${absolute.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
2451
2341
  };
2452
2342
  var resolveSessionExportDir = (config) => {
2453
2343
  if (!config.sessionExport) return void 0;
2454
- const raw = process.env[SESSION_EXPORT_ENV]?.trim() || config.sessionExportDir.trim() || path13.join(os2.homedir(), ".pi", "agent");
2344
+ const raw = process.env[SESSION_EXPORT_ENV]?.trim() || config.sessionExportDir.trim() || path12.join(os2.homedir(), ".pi", "agent");
2455
2345
  return expandHome(raw);
2456
2346
  };
2457
2347
  var sessionExportFileFor = (root, cwd, runId, at) => {
2458
2348
  const fileTimestamp = at.toISOString().replace(/[:.]/g, "-");
2459
- return path13.join(
2349
+ return path12.join(
2460
2350
  root,
2461
2351
  "sessions",
2462
2352
  ".fabric",
@@ -2497,11 +2387,11 @@ var resolveAgentCwd = (parentCwd, requestedCwd) => {
2497
2387
  if (typeof requested !== "string" || requested.trim().length === 0) {
2498
2388
  throw new Error(`Invalid Fabric agent cwd ${JSON.stringify(requested)}: path must not be empty`);
2499
2389
  }
2500
- const candidate = path14.isAbsolute(requested) ? requested : path14.resolve(parentCwd, requested);
2390
+ const candidate = path13.isAbsolute(requested) ? requested : path13.resolve(parentCwd, requested);
2501
2391
  try {
2502
- const canonical = fs13.realpathSync(candidate);
2503
- fs13.accessSync(canonical, fs13.constants.R_OK | fs13.constants.X_OK);
2504
- if (!fs13.statSync(canonical).isDirectory()) {
2392
+ const canonical = fs12.realpathSync(candidate);
2393
+ fs12.accessSync(canonical, fs12.constants.R_OK | fs12.constants.X_OK);
2394
+ if (!fs12.statSync(canonical).isDirectory()) {
2505
2395
  throw new Error("path is not a directory");
2506
2396
  }
2507
2397
  return canonical;
@@ -2535,7 +2425,7 @@ var queuedResult = (entry, status, error) => {
2535
2425
  };
2536
2426
  var fileSize = (filePath) => {
2537
2427
  try {
2538
- return fs13.statSync(filePath).size;
2428
+ return fs12.statSync(filePath).size;
2539
2429
  } catch {
2540
2430
  return 0;
2541
2431
  }
@@ -2586,7 +2476,7 @@ var runName = (request) => safeName(request.name ?? request.task.split("\n", 1)[
2586
2476
  var safeName = (value) => value.replace(/[\r\n\t]+/g, " ").trim().slice(0, MAX_NAME_LENGTH) || "Fabric agent";
2587
2477
  var readRecord = (filePath) => {
2588
2478
  try {
2589
- const parsed = JSON.parse(fs13.readFileSync(filePath, "utf8"));
2479
+ const parsed = JSON.parse(fs12.readFileSync(filePath, "utf8"));
2590
2480
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
2591
2481
  const record = parsed;
2592
2482
  return { ...record, runner: isFabricRunnerId(record.runner) ? record.runner : "pi" };
@@ -2638,24 +2528,24 @@ var reconcileNestedAgents = (records, owner) => records.map((record) => {
2638
2528
  });
2639
2529
  var readNestedAgents = (runDirectory, depth = 0) => {
2640
2530
  if (depth >= 8) return [];
2641
- const nestedRoot = path14.join(runDirectory, "nested");
2531
+ const nestedRoot = path13.join(runDirectory, "nested");
2642
2532
  let entries;
2643
2533
  try {
2644
- entries = fs13.readdirSync(nestedRoot);
2534
+ entries = fs12.readdirSync(nestedRoot);
2645
2535
  } catch {
2646
2536
  return [];
2647
2537
  }
2648
2538
  const agents = [];
2649
2539
  for (const entry of entries.slice(0, 200)) {
2650
- const runDirectory2 = path14.join(nestedRoot, entry);
2651
- const record = readRecord(path14.join(runDirectory2, "status.json"));
2540
+ const runDirectory2 = path13.join(nestedRoot, entry);
2541
+ const record = readRecord(path13.join(runDirectory2, "status.json"));
2652
2542
  if (!record) continue;
2653
2543
  const nestedAgents = readNestedAgents(runDirectory2, depth + 1);
2654
2544
  const { logFile: _logFile, nestedAgents: _nestedAgents, ...safeRecord } = record;
2655
2545
  agents.push(
2656
2546
  compactUiRecord({
2657
2547
  ...safeRecord,
2658
- logFile: path14.join(runDirectory2, "events.jsonl"),
2548
+ logFile: path13.join(runDirectory2, "events.jsonl"),
2659
2549
  ...nestedAgents.length > 0 ? { nestedAgents } : {}
2660
2550
  })
2661
2551
  );
@@ -2663,7 +2553,7 @@ var readNestedAgents = (runDirectory, depth = 0) => {
2663
2553
  return agents;
2664
2554
  };
2665
2555
  var summarizeRunLog = (runDirectory, lines) => {
2666
- const page = readJsonlPage(path14.join(runDirectory, "events.jsonl"), lines);
2556
+ const page = readJsonlPage(path13.join(runDirectory, "events.jsonl"), lines);
2667
2557
  const summary = [];
2668
2558
  for (const entry of page.lines) {
2669
2559
  const parsed = entry.parsed;
@@ -2716,8 +2606,8 @@ var AgentManager = class {
2716
2606
  this.config = config;
2717
2607
  this.#semaphore = new AgentAdmission(config.maxConcurrent, Infinity, config.maxDepth);
2718
2608
  this.#managedTempRoot = options.runRoot === void 0 && process.env.PI_FABRIC_RUN_ROOT === void 0;
2719
- this.#runRoot = options.runRoot ?? process.env.PI_FABRIC_RUN_ROOT ?? fs13.mkdtempSync(path14.join(os3.tmpdir(), "pi-fabric-runs-"));
2720
- this.#parentOwnedRunRoot = options.runRoot === void 0 && this.#parentLineage?.worker === true && this.#parentLineage.depth > 0 && path14.basename(this.#runRoot) === "nested" && path14.basename(path14.dirname(this.#runRoot)) === this.#parentLineage.runId;
2609
+ this.#runRoot = options.runRoot ?? process.env.PI_FABRIC_RUN_ROOT ?? fs12.mkdtempSync(path13.join(os3.tmpdir(), "pi-fabric-runs-"));
2610
+ this.#parentOwnedRunRoot = options.runRoot === void 0 && this.#parentLineage?.worker === true && this.#parentLineage.depth > 0 && path13.basename(this.#runRoot) === "nested" && path13.basename(path13.dirname(this.#runRoot)) === this.#parentLineage.runId;
2721
2611
  this.#retention = options.retention ?? DEFAULT_FABRIC_CONFIG.retention;
2722
2612
  this.#workerPath = options.workerPath ?? fileURLToPath(new URL("../worker.js", import.meta.url));
2723
2613
  this.#fabricExtensionPath = options.fabricExtensionPath ?? fileURLToPath(new URL("../index.js", import.meta.url));
@@ -3117,26 +3007,26 @@ var AgentManager = class {
3117
3007
  }
3118
3008
  const id = queued?.id ?? randomUUID6().replaceAll("-", "");
3119
3009
  const name = runName(request);
3120
- const runDirectory = path14.join(this.#runRoot, id);
3010
+ const runDirectory = path13.join(this.#runRoot, id);
3121
3011
  const durableSession = runner === "pi-durable" && this.config.durableWorkerSession === true;
3122
- const taskFile = path14.join(runDirectory, "task.txt");
3123
- const statusFile = path14.join(runDirectory, "status.json");
3124
- const lifecycleFile = path14.join(runDirectory, "lifecycle.jsonl");
3125
- const logFile = path14.join(runDirectory, "events.jsonl");
3126
- const steerFile = path14.join(runDirectory, "steer.jsonl");
3127
- const schemaFile = request.schema ? path14.join(runDirectory, "schema.json") : void 0;
3128
- const imagesFile = request.images && request.images.length > 0 ? path14.join(runDirectory, "images.json") : void 0;
3012
+ const taskFile = path13.join(runDirectory, "task.txt");
3013
+ const statusFile = path13.join(runDirectory, "status.json");
3014
+ const lifecycleFile = path13.join(runDirectory, "lifecycle.jsonl");
3015
+ const logFile = path13.join(runDirectory, "events.jsonl");
3016
+ const steerFile = path13.join(runDirectory, "steer.jsonl");
3017
+ const schemaFile = request.schema ? path13.join(runDirectory, "schema.json") : void 0;
3018
+ const imagesFile = request.images && request.images.length > 0 ? path13.join(runDirectory, "images.json") : void 0;
3129
3019
  try {
3130
- fs13.mkdirSync(runDirectory, durableSession ? { recursive: true, mode: 448 } : { recursive: true });
3131
- fs13.writeFileSync(taskFile, request.task, { encoding: "utf8", mode: 384 });
3020
+ fs12.mkdirSync(runDirectory, durableSession ? { recursive: true, mode: 448 } : { recursive: true });
3021
+ fs12.writeFileSync(taskFile, request.task, { encoding: "utf8", mode: 384 });
3132
3022
  if (imagesFile) {
3133
- fs13.writeFileSync(imagesFile, JSON.stringify(request.images), {
3023
+ fs12.writeFileSync(imagesFile, JSON.stringify(request.images), {
3134
3024
  encoding: "utf8",
3135
3025
  mode: 384
3136
3026
  });
3137
3027
  }
3138
3028
  if (schemaFile) {
3139
- fs13.writeFileSync(schemaFile, JSON.stringify(request.schema, null, 2), {
3029
+ fs12.writeFileSync(schemaFile, JSON.stringify(request.schema, null, 2), {
3140
3030
  encoding: "utf8",
3141
3031
  mode: 384
3142
3032
  });
@@ -3155,7 +3045,7 @@ var AgentManager = class {
3155
3045
  let worktree;
3156
3046
  if (request.worktree) {
3157
3047
  try {
3158
- const lease = await this.#worktrees.create(id, selectedCwd, name, request.cwd !== void 0);
3048
+ const lease = await this.#worktrees.create(id, selectedCwd, name, request.cwd !== void 0, this.config.worktree);
3159
3049
  agentCwd = lease.cwd;
3160
3050
  branch = lease.branch;
3161
3051
  worktree = lease.path;
@@ -3184,10 +3074,10 @@ var AgentManager = class {
3184
3074
  const seedOptions = durableSession ? { workerRole: true } : {};
3185
3075
  const handoffBudget = request.sessionSeed && request.handoffCompact ? await this.#resolveHandoffCompactionBudget?.(model, agentCwd) : void 0;
3186
3076
  admissionSignal.throwIfAborted();
3187
- const sessionFile = request.forkSeed ? writeForkSession(request.forkSeed, agentCwd, path14.join(runDirectory, "fork-session"), request.thinkingTransfer, seedOptions) : request.sessionSeed ? writeHandoffSession(
3077
+ const sessionFile = request.forkSeed ? writeForkSession(request.forkSeed, agentCwd, path13.join(runDirectory, "fork-session"), request.thinkingTransfer, seedOptions) : request.sessionSeed ? writeHandoffSession(
3188
3078
  request.sessionSeed,
3189
3079
  agentCwd,
3190
- path14.join(runDirectory, "handoff-session"),
3080
+ path13.join(runDirectory, "handoff-session"),
3191
3081
  request.thinkingTransfer,
3192
3082
  request.handoffCompact,
3193
3083
  handoffBudget,
@@ -3206,7 +3096,11 @@ var AgentManager = class {
3206
3096
  const inheritedSessionPins = (runner === "pi" || runner === "pi-durable") && extensions ? this.#inheritedSessionPins(request) : void 0;
3207
3097
  const inheritedFullCodeMode = capabilities2.recursiveFabric && this.#fullCodeMode && extensions;
3208
3098
  const componentGuidance = recursive ? void 0 : this.#resolveParticipantGuidance?.({ ...model ? { model } : {}, runner })?.trim();
3209
- const systemPrompt = [request.systemPrompt?.trim(), request.childSkills?.preload, componentGuidance].filter((section) => Boolean(section)).join("\n\n") || void 0;
3099
+ const mainGuidance = this.#mainAgentId ? [
3100
+ `Your owning Main peer (lineage root): ${this.#mainAgentId}.`,
3101
+ capabilities2.recursiveFabric && extensions && (recursive || inheritedFullCodeMode || requiresFabricKernel) ? `Use agents.self() for your participant identity and agents.main() for your owning Main. To report back, use agents.steer({ id: "main", message: "..." }) or agents.followUp({ id: "main", message: "..." }) in fabric_exec. The alias "main" always targets your lineage root, not another peer's Main. Use an exact discovered participant id to message another peer or worker; ownerHostId is a routing address, not a participant id.` : "Report results in your response; the host delivers them to your coordinator. This launch does not provide direct Fabric coordination tools."
3102
+ ].join("\n") : void 0;
3103
+ const systemPrompt = [request.systemPrompt?.trim(), request.childSkills?.preload, componentGuidance, mainGuidance].filter((section) => Boolean(section)).join("\n\n") || void 0;
3210
3104
  const sessionExportDir = resolveSessionExportDir(this.config);
3211
3105
  const sessionExportFile = sessionExportDir ? sessionExportFileFor(sessionExportDir, agentCwd, id, /* @__PURE__ */ new Date()) : void 0;
3212
3106
  const traceContext = this.#traceContext(request, { runId: id, runner, name });
@@ -3323,7 +3217,7 @@ var AgentManager = class {
3323
3217
  ...this.#identityId ? ["--owner-identity-id", this.#identityId] : [],
3324
3218
  ...request.runnerSessionId ? ["--runner-session-id", request.runnerSessionId] : [],
3325
3219
  "--run-root",
3326
- path14.join(runDirectory, "nested"),
3220
+ path13.join(runDirectory, "nested"),
3327
3221
  "--steer-file",
3328
3222
  steerFile,
3329
3223
  ...this.config.childQuestions === "route" && capabilities2.questions ? [
@@ -3475,7 +3369,7 @@ var AgentManager = class {
3475
3369
  const hosted = await HostedRun.prepare(
3476
3370
  adapter,
3477
3371
  { ...context, idempotencyKey: context.id },
3478
- { ...launch.files, stateFile: path14.join(context.runDirectory, HOSTED_STATE_FILE) },
3372
+ { ...launch.files, stateFile: path13.join(context.runDirectory, HOSTED_STATE_FILE) },
3479
3373
  record,
3480
3374
  this.#hostedHooks(() => managed, launch.request.holdQuestions === true)
3481
3375
  );
@@ -3562,17 +3456,17 @@ var AgentManager = class {
3562
3456
  async recoverHostedRuns() {
3563
3457
  let entries;
3564
3458
  try {
3565
- entries = fs13.readdirSync(this.#runRoot);
3459
+ entries = fs12.readdirSync(this.#runRoot);
3566
3460
  } catch {
3567
3461
  return [];
3568
3462
  }
3569
3463
  const recovered = [];
3570
3464
  for (const entry of entries) {
3571
3465
  if (this.#closing || this.#runs.has(entry) || !/^[0-9a-f]{32}$/.test(entry)) continue;
3572
- const runDirectory = path14.join(this.#runRoot, entry);
3573
- const statusFile = path14.join(runDirectory, "status.json");
3466
+ const runDirectory = path13.join(this.#runRoot, entry);
3467
+ const statusFile = path13.join(runDirectory, "status.json");
3574
3468
  const record = readRecord(statusFile);
3575
- const state = readHostedRunState(path14.join(runDirectory, HOSTED_STATE_FILE));
3469
+ const state = readHostedRunState(path13.join(runDirectory, HOSTED_STATE_FILE));
3576
3470
  if (!record?.hosted || !state || record.id !== entry || state.context.id !== entry || terminalStatuses.has(record.status)) {
3577
3471
  continue;
3578
3472
  }
@@ -3604,9 +3498,9 @@ var AgentManager = class {
3604
3498
  state,
3605
3499
  {
3606
3500
  statusFile,
3607
- lifecycleFile: path14.join(runDirectory, "lifecycle.jsonl"),
3608
- logFile: path14.join(runDirectory, "events.jsonl"),
3609
- stateFile: path14.join(runDirectory, HOSTED_STATE_FILE)
3501
+ lifecycleFile: path13.join(runDirectory, "lifecycle.jsonl"),
3502
+ logFile: path13.join(runDirectory, "events.jsonl"),
3503
+ stateFile: path13.join(runDirectory, HOSTED_STATE_FILE)
3610
3504
  },
3611
3505
  record,
3612
3506
  this.#hostedHooks(() => managed, state.holdQuestions === true)
@@ -3686,16 +3580,16 @@ var AgentManager = class {
3686
3580
  async recoverWorkerRuns() {
3687
3581
  let entries;
3688
3582
  try {
3689
- entries = fs13.readdirSync(this.#runRoot);
3583
+ entries = fs12.readdirSync(this.#runRoot);
3690
3584
  } catch {
3691
3585
  return [];
3692
3586
  }
3693
3587
  const recovered = [];
3694
3588
  for (const entry of entries) {
3695
3589
  if (this.#closing || this.#runs.has(entry) || !/^[0-9a-f]{32}$/.test(entry)) continue;
3696
- const runDirectory = path14.join(this.#runRoot, entry);
3590
+ const runDirectory = path13.join(this.#runRoot, entry);
3697
3591
  const recovery = readWorkerRecovery(runDirectory);
3698
- const statusFile = path14.join(runDirectory, "status.json");
3592
+ const statusFile = path13.join(runDirectory, "status.json");
3699
3593
  const record = readRecord(statusFile);
3700
3594
  if (!recovery || recovery.id !== entry) {
3701
3595
  if (!hasWorkerRecovery(runDirectory)) continue;
@@ -3783,7 +3677,7 @@ var AgentManager = class {
3783
3677
  indeterminate(`Fabric cannot verify whether worker process ${recovery.pid} is still running`);
3784
3678
  continue;
3785
3679
  }
3786
- if (liveness === "dead" && !fs13.existsSync(authority.launch.workerPath)) {
3680
+ if (liveness === "dead" && !fs12.existsSync(authority.launch.workerPath)) {
3787
3681
  indeterminate(`The worker entry ${recovery.launch.workerPath} no longer exists`);
3788
3682
  continue;
3789
3683
  }
@@ -3808,9 +3702,9 @@ var AgentManager = class {
3808
3702
  residency: "durable",
3809
3703
  cwd: record.cwd,
3810
3704
  statusFile,
3811
- lifecycleFile: path14.join(runDirectory, "lifecycle.jsonl"),
3705
+ lifecycleFile: path13.join(runDirectory, "lifecycle.jsonl"),
3812
3706
  // Events before this point reached the previous host's ledger.
3813
- lifecycleOffset: fileSize(path14.join(runDirectory, "lifecycle.jsonl")),
3707
+ lifecycleOffset: fileSize(path13.join(runDirectory, "lifecycle.jsonl")),
3814
3708
  lifecycleRemainder: Buffer.alloc(0),
3815
3709
  runDirectory,
3816
3710
  transport: adoptedWorkerHandle(authority.pid, entry),
@@ -4095,15 +3989,15 @@ var AgentManager = class {
4095
3989
  this.#runs.delete(id);
4096
3990
  this.#pruneRetainedUiRecords();
4097
3991
  this.#invalidateUiList();
4098
- return { cleaned: cleaned || !fs13.existsSync(managed.runDirectory) };
3992
+ return { cleaned: cleaned || !fs12.existsSync(managed.runDirectory) };
4099
3993
  }
4100
3994
  readLog(id, opts = {}) {
4101
3995
  const managed = this.#requireRun(id);
4102
3996
  const runDirectory = managed.runDirectory;
4103
- const logFile = path14.join(runDirectory, "events.jsonl");
3997
+ const logFile = path13.join(runDirectory, "events.jsonl");
4104
3998
  const lines = Math.max(1, Math.min(opts.lines ?? 200, 5e3));
4105
3999
  const page = readJsonlPage(logFile, lines, opts.before);
4106
- const statusRecord = readRecord(path14.join(runDirectory, "status.json"));
4000
+ const statusRecord = readRecord(path13.join(runDirectory, "status.json"));
4107
4001
  return {
4108
4002
  id,
4109
4003
  runDirectory,
@@ -4178,10 +4072,10 @@ var AgentManager = class {
4178
4072
  `Fabric agent ${id} already finished (${record.status}); steering has no target`
4179
4073
  );
4180
4074
  }
4181
- const steerFile = path14.join(managed.runDirectory, "steer.jsonl");
4075
+ const steerFile = path13.join(managed.runDirectory, "steer.jsonl");
4182
4076
  const messageId = randomUUID6();
4183
4077
  const line = JSON.stringify({ ...entry, id: messageId, ts: Date.now() }) + "\n";
4184
- fs13.appendFileSync(steerFile, line, { encoding: "utf8", mode: 384 });
4078
+ fs12.appendFileSync(steerFile, line, { encoding: "utf8", mode: 384 });
4185
4079
  return { queued: true, messageId };
4186
4080
  }
4187
4081
  close() {
@@ -4234,7 +4128,7 @@ var AgentManager = class {
4234
4128
  removeEmptyRunRoot(this.#runRoot);
4235
4129
  }
4236
4130
  if (storageSafe && this.#budgetOwned && this.#budget) {
4237
- await removeTree(path14.dirname(this.#budget.file)).catch(() => void 0);
4131
+ await removeTree(path13.dirname(this.#budget.file)).catch(() => void 0);
4238
4132
  }
4239
4133
  }
4240
4134
  if (this.#budgetOwned) clearOwnedBudgetEnv();
@@ -4276,7 +4170,7 @@ var AgentManager = class {
4276
4170
  });
4277
4171
  for (const managed of expired) {
4278
4172
  await removeTree(managed.runDirectory).catch(() => void 0);
4279
- if (!fs13.existsSync(managed.runDirectory)) this.#runs.delete(managed.id);
4173
+ if (!fs12.existsSync(managed.runDirectory)) this.#runs.delete(managed.id);
4280
4174
  }
4281
4175
  if (expired.length > 0) {
4282
4176
  this.#pruneRetainedUiRecords();
@@ -4380,7 +4274,7 @@ var AgentManager = class {
4380
4274
  );
4381
4275
  }
4382
4276
  if (resume) {
4383
- fs13.writeFileSync(path14.join(managed.runDirectory, "task.txt"), resume.task, {
4277
+ fs12.writeFileSync(path13.join(managed.runDirectory, "task.txt"), resume.task, {
4384
4278
  encoding: "utf8",
4385
4279
  mode: 384
4386
4280
  });
@@ -4403,10 +4297,10 @@ var AgentManager = class {
4403
4297
  }
4404
4298
  this.#drainLifecycle(managed);
4405
4299
  if (managed.settled || this.#closing || managed.stopRequested) return false;
4406
- fs13.rmSync(managed.statusFile, { force: true });
4300
+ fs12.rmSync(managed.statusFile, { force: true });
4407
4301
  managed.lifecycleOffset = 0;
4408
4302
  managed.lifecycleRemainder = Buffer.alloc(0);
4409
- fs13.rmSync(managed.lifecycleFile, { force: true });
4303
+ fs12.rmSync(managed.lifecycleFile, { force: true });
4410
4304
  managed.transport = await this.#launchTransport(managed.adapter, managed.launch);
4411
4305
  this.#unregisteredTransports.delete(managed.transport);
4412
4306
  if (managed.workerRecovery) this.#persistWorkerRecovery(managed);
@@ -4585,7 +4479,7 @@ var AgentManager = class {
4585
4479
  managed.questions?.abort(new Error("Agent run settled"));
4586
4480
  managed.hosted?.close();
4587
4481
  try {
4588
- fs13.rmSync(path14.join(managed.runDirectory, "images.json"), { force: true });
4482
+ fs12.rmSync(path13.join(managed.runDirectory, "images.json"), { force: true });
4589
4483
  } catch {
4590
4484
  }
4591
4485
  this.#emitLifecycle(managed, `run.${result.status}`, result.finishedAt ?? Date.now(), {
@@ -4620,7 +4514,7 @@ var AgentManager = class {
4620
4514
  #drainLifecycle(managed) {
4621
4515
  let content;
4622
4516
  try {
4623
- content = fs13.readFileSync(managed.lifecycleFile);
4517
+ content = fs12.readFileSync(managed.lifecycleFile);
4624
4518
  } catch {
4625
4519
  return;
4626
4520
  }
@@ -4673,8 +4567,8 @@ var AgentManager = class {
4673
4567
  const requestId = question.requestId;
4674
4568
  const steer = (command) => {
4675
4569
  try {
4676
- fs13.appendFileSync(
4677
- path14.join(managed.runDirectory, "steer.jsonl"),
4570
+ fs12.appendFileSync(
4571
+ path13.join(managed.runDirectory, "steer.jsonl"),
4678
4572
  `${JSON.stringify({ ...command, id: randomUUID6(), ts: Date.now() })}
4679
4573
  `,
4680
4574
  { encoding: "utf8", mode: 384 }
@@ -4890,7 +4784,7 @@ var AgentManager = class {
4890
4784
  // directories. Terminal-owner reconciliation prevents cached active ghosts.
4891
4785
  #nestedAgents(managed, force = false) {
4892
4786
  const now = Date.now();
4893
- const needsInitialDiscovery = managed.nestedSnapshot === void 0 && fs13.existsSync(path14.join(managed.runDirectory, "nested"));
4787
+ const needsInitialDiscovery = managed.nestedSnapshot === void 0 && fs12.existsSync(path13.join(managed.runDirectory, "nested"));
4894
4788
  if (!force && !needsInitialDiscovery && managed.nestedSnapshotAt !== void 0 && now - managed.nestedSnapshotAt < NESTED_SNAPSHOT_POLL_MS) {
4895
4789
  return managed.nestedSnapshot ? structuredClone(managed.nestedSnapshot) : [];
4896
4790
  }
@@ -4918,7 +4812,7 @@ var AgentManager = class {
4918
4812
  runner: managed.runner,
4919
4813
  ...managed.kernel ? { kernel: managed.kernel } : {},
4920
4814
  ...managed.residency === "durable" ? { residency: "durable" } : {},
4921
- logFile: path14.join(managed.runDirectory, "events.jsonl"),
4815
+ logFile: path13.join(managed.runDirectory, "events.jsonl"),
4922
4816
  ...nestedAgents.length > 0 ? { nestedAgents } : {},
4923
4817
  ...budget ? { budget } : {},
4924
4818
  ...model ? { model } : {},
@@ -4974,15 +4868,15 @@ var actorDeliveryNotice = (delivery, triggerTurn) => {
4974
4868
  };
4975
4869
 
4976
4870
  // src/actors/directory.ts
4977
- import fs20 from "node:fs";
4871
+ import fs19 from "node:fs";
4978
4872
 
4979
4873
  // src/actors/manager.ts
4980
4874
  import { randomUUID as randomUUID9 } from "node:crypto";
4981
- import fs19 from "node:fs";
4875
+ import fs18 from "node:fs";
4982
4876
 
4983
4877
  // src/actors/mesh-monitor.ts
4984
- import fs14 from "node:fs";
4985
- import path15 from "node:path";
4878
+ import fs13 from "node:fs";
4879
+ import path14 from "node:path";
4986
4880
  var MESH_WATCH_RECONCILE_MS = 2e3;
4987
4881
  var ActorMeshMonitor = class {
4988
4882
  constructor(mesh, config, callbacks) {
@@ -5009,8 +4903,8 @@ var ActorMeshMonitor = class {
5009
4903
  return;
5010
4904
  }
5011
4905
  try {
5012
- const watcher = fs14.watch(this.mesh.root, { persistent: false }, (_event, filename) => {
5013
- const name = filename == null ? void 0 : path15.basename(filename.toString());
4906
+ const watcher = fs13.watch(this.mesh.root, { persistent: false }, (_event, filename) => {
4907
+ const name = filename == null ? void 0 : path14.basename(filename.toString());
5014
4908
  if (name !== void 0 && name !== "events.jsonl" && name !== "schedules.json") return;
5015
4909
  this.schedule();
5016
4910
  });
@@ -5102,7 +4996,7 @@ var ActorMeshMonitor = class {
5102
4996
  #readCursor() {
5103
4997
  if (!this.callbacks.cursorPath) return void 0;
5104
4998
  try {
5105
- const value = JSON.parse(fs14.readFileSync(this.callbacks.cursorPath, "utf8"));
4999
+ const value = JSON.parse(fs13.readFileSync(this.callbacks.cursorPath, "utf8"));
5106
5000
  return value.format === 1 && typeof value.cursor === "number" && value.cursor >= 0 ? value.cursor : void 0;
5107
5001
  } catch {
5108
5002
  return void 0;
@@ -5119,11 +5013,11 @@ var ActorMeshMonitor = class {
5119
5013
 
5120
5014
  // src/actors/manager.ts
5121
5015
  import os4 from "node:os";
5122
- import path19 from "node:path";
5016
+ import path18 from "node:path";
5123
5017
 
5124
5018
  // src/actors/log-store.ts
5125
- import fs15 from "node:fs";
5126
- import path16 from "node:path";
5019
+ import fs14 from "node:fs";
5020
+ import path15 from "node:path";
5127
5021
  var ACTOR_MESSAGE_HISTORY_LIMIT = 100;
5128
5022
  var ACTOR_MESSAGE_ENVELOPE_BYTES = 4096;
5129
5023
  var ACTOR_TRUNCATION_SUFFIX = "\n[actor message truncated]";
@@ -5181,17 +5075,17 @@ var ActorLogStore = class {
5181
5075
  this.retention = retention;
5182
5076
  }
5183
5077
  async retainRun(actor, runId, runDirectory) {
5184
- if (!runDirectory || !fs15.existsSync(runDirectory)) return;
5185
- const dest = path16.join(path16.dirname(actor.sessionFile), "runs", runId);
5186
- fs15.mkdirSync(dest, { recursive: true, mode: 448 });
5078
+ if (!runDirectory || !fs14.existsSync(runDirectory)) return;
5079
+ const dest = path15.join(path15.dirname(actor.sessionFile), "runs", runId);
5080
+ fs14.mkdirSync(dest, { recursive: true, mode: 448 });
5187
5081
  for (const file of ["events.jsonl", "status.json", "task.txt"]) {
5188
- const src = path16.join(runDirectory, file);
5189
- if (fs15.existsSync(src)) fs15.copyFileSync(src, path16.join(dest, file));
5082
+ const src = path15.join(runDirectory, file);
5083
+ if (fs14.existsSync(src)) fs14.copyFileSync(src, path15.join(dest, file));
5190
5084
  }
5191
- const nested = path16.join(runDirectory, "nested");
5192
- if (fs15.existsSync(nested)) {
5085
+ const nested = path15.join(runDirectory, "nested");
5086
+ if (fs14.existsSync(nested)) {
5193
5087
  try {
5194
- fs15.cpSync(nested, path16.join(dest, "nested"), { recursive: true });
5088
+ fs14.cpSync(nested, path15.join(dest, "nested"), { recursive: true });
5195
5089
  } catch {
5196
5090
  }
5197
5091
  }
@@ -5199,16 +5093,16 @@ var ActorLogStore = class {
5199
5093
  }
5200
5094
  pruneRuns(actor, now = Date.now()) {
5201
5095
  pruneActorRunArchives({
5202
- runsDirectory: path16.join(path16.dirname(actor.sessionFile), "runs"),
5096
+ runsDirectory: path15.join(path15.dirname(actor.sessionFile), "runs"),
5203
5097
  ...actor.lastRunId ? { latestRunId: actor.lastRunId } : {},
5204
5098
  retentionMs: this.retention.actorRunArchiveMs,
5205
5099
  now
5206
5100
  });
5207
5101
  }
5208
5102
  retainedRunIds(actor) {
5209
- const runsDir = path16.join(path16.dirname(actor.sessionFile), "runs");
5103
+ const runsDir = path15.join(path15.dirname(actor.sessionFile), "runs");
5210
5104
  try {
5211
- return fs15.readdirSync(runsDir).sort();
5105
+ return fs14.readdirSync(runsDir).sort();
5212
5106
  } catch {
5213
5107
  return [];
5214
5108
  }
@@ -5358,11 +5252,11 @@ var evaluateActorValidWhile = async (source, facts) => {
5358
5252
 
5359
5253
  // src/actors/binding-store.ts
5360
5254
  import { createHash, randomUUID as randomUUID7 } from "node:crypto";
5361
- import fs17 from "node:fs";
5362
- import path17 from "node:path";
5255
+ import fs16 from "node:fs";
5256
+ import path16 from "node:path";
5363
5257
 
5364
5258
  // src/actors/store-read.ts
5365
- import fs16 from "node:fs";
5259
+ import fs15 from "node:fs";
5366
5260
  var ActorStoreReadError = class extends Error {
5367
5261
  filePath;
5368
5262
  constructor(filePath, detail, options) {
@@ -5374,7 +5268,7 @@ var ActorStoreReadError = class extends Error {
5374
5268
  var readStoreJson = (filePath) => {
5375
5269
  let text;
5376
5270
  try {
5377
- text = fs16.readFileSync(filePath, "utf8");
5271
+ text = fs15.readFileSync(filePath, "utf8");
5378
5272
  } catch (error) {
5379
5273
  if (error?.code === "ENOENT") return void 0;
5380
5274
  throw new ActorStoreReadError(
@@ -5403,7 +5297,7 @@ var delay2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
5403
5297
  var ActorBindingStore = class {
5404
5298
  constructor(sessionId, root) {
5405
5299
  this.sessionId = sessionId;
5406
- this.filePath = root ? path17.join(root, "bindings", bindingFileName(sessionId)) : void 0;
5300
+ this.filePath = root ? path16.join(root, "bindings", bindingFileName(sessionId)) : void 0;
5407
5301
  this.#sync(true);
5408
5302
  }
5409
5303
  #bindings = /* @__PURE__ */ new Map();
@@ -5536,7 +5430,7 @@ var ActorBindingStore = class {
5536
5430
  #currentFingerprint() {
5537
5431
  if (!this.filePath) return void 0;
5538
5432
  try {
5539
- const stat = fs17.statSync(this.filePath);
5433
+ const stat = fs16.statSync(this.filePath);
5540
5434
  return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}`;
5541
5435
  } catch {
5542
5436
  return void 0;
@@ -5556,7 +5450,7 @@ var ActorBindingStore = class {
5556
5450
  return false;
5557
5451
  }
5558
5452
  };
5559
- fs17.mkdirSync(path17.dirname(this.filePath), { recursive: true, mode: 448 });
5453
+ fs16.mkdirSync(path16.dirname(this.filePath), { recursive: true, mode: 448 });
5560
5454
  while (!tryAcquireShortLock(lockPath, formatShortLockOwner(token))) {
5561
5455
  if (reapStaleShortLock(lockPath, { staleMs: BINDING_STALE_LOCK_MS, legacyAlive: processAlive2 })) continue;
5562
5456
  if (Date.now() >= deadline) {
@@ -5574,8 +5468,8 @@ var ActorBindingStore = class {
5574
5468
 
5575
5469
  // src/actors/registry-store.ts
5576
5470
  import { randomUUID as randomUUID8 } from "node:crypto";
5577
- import fs18 from "node:fs";
5578
- import path18 from "node:path";
5471
+ import fs17 from "node:fs";
5472
+ import path17 from "node:path";
5579
5473
  import { setTimeout as delay3 } from "node:timers/promises";
5580
5474
  var ACTOR_REGISTRY_LOCK_TIMEOUT_MS = 5e3;
5581
5475
  var ACTOR_REGISTRY_STALE_LOCK_MS = 3e4;
@@ -5586,7 +5480,7 @@ var ActorRegistryStore = class {
5586
5480
  #actorRoot;
5587
5481
  constructor(actorRoot) {
5588
5482
  this.#actorRoot = actorRoot;
5589
- this.#registryPath = path18.join(actorRoot, "actors.json");
5483
+ this.#registryPath = path17.join(actorRoot, "actors.json");
5590
5484
  }
5591
5485
  /**
5592
5486
  * Every entry in actors.json, including entries without a valid identity, so
@@ -5620,7 +5514,7 @@ var ActorRegistryStore = class {
5620
5514
  return false;
5621
5515
  }
5622
5516
  };
5623
- fs18.mkdirSync(this.#actorRoot, { recursive: true, mode: 448 });
5517
+ fs17.mkdirSync(this.#actorRoot, { recursive: true, mode: 448 });
5624
5518
  signal?.throwIfAborted();
5625
5519
  while (!tryAcquireShortLock(lockPath, formatShortLockOwner(token))) {
5626
5520
  if (reapStaleShortLock(lockPath, { staleMs: ACTOR_REGISTRY_STALE_LOCK_MS, legacyAlive: processAlive2 })) continue;
@@ -5639,14 +5533,14 @@ var ActorRegistryStore = class {
5639
5533
  }
5640
5534
  fingerprint() {
5641
5535
  try {
5642
- const stat = fs18.statSync(this.#registryPath);
5536
+ const stat = fs17.statSync(this.#registryPath);
5643
5537
  return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}`;
5644
5538
  } catch {
5645
5539
  return void 0;
5646
5540
  }
5647
5541
  }
5648
5542
  read() {
5649
- return JSON.parse(fs18.readFileSync(this.#registryPath, "utf8"));
5543
+ return JSON.parse(fs17.readFileSync(this.#registryPath, "utf8"));
5650
5544
  }
5651
5545
  /** Call within withLock for read-modify-write operations. */
5652
5546
  write(actors) {
@@ -5684,7 +5578,7 @@ var normalizeCapabilityRequirements = (requirements = []) => {
5684
5578
  };
5685
5579
  var readRunRecord = (filePath) => {
5686
5580
  try {
5687
- const parsed = JSON.parse(fs19.readFileSync(filePath, "utf8"));
5581
+ const parsed = JSON.parse(fs18.readFileSync(filePath, "utf8"));
5688
5582
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
5689
5583
  return parsed;
5690
5584
  } catch {
@@ -5734,7 +5628,7 @@ var ActorManager = class {
5734
5628
  this.meshConfig = meshConfig;
5735
5629
  this.agents = agents;
5736
5630
  this.onDeliver = onDeliver;
5737
- this.#actorRoot = options.actorRoot ?? fs19.mkdtempSync(path19.join(os4.tmpdir(), "pi-fabric-actors-"));
5631
+ this.#actorRoot = options.actorRoot ?? fs18.mkdtempSync(path18.join(os4.tmpdir(), "pi-fabric-actors-"));
5738
5632
  this.#actorScope = options.actorScope ?? meshConfig.actorScope;
5739
5633
  this.#persistent = options.persistent ?? false;
5740
5634
  this.#mainAgent = options.mainAgent;
@@ -5907,7 +5801,7 @@ var ActorManager = class {
5907
5801
  }
5908
5802
  const principalScope = launchScope(void 0, request.principalScope);
5909
5803
  const id = randomUUID9().replaceAll("-", "");
5910
- const actorDirectory = path19.join(this.#actorRoot, id);
5804
+ const actorDirectory = path18.join(this.#actorRoot, id);
5911
5805
  const actor = {
5912
5806
  id,
5913
5807
  name,
@@ -5934,14 +5828,14 @@ var ActorManager = class {
5934
5828
  ...request.validWhile ? { validWhile: structuredClone(request.validWhile) } : {},
5935
5829
  ...principalScope ? { principalScope } : {},
5936
5830
  latestActivationSequence: 0,
5937
- sessionFile: path19.join(actorDirectory, "session.jsonl"),
5831
+ sessionFile: path18.join(actorDirectory, "session.jsonl"),
5938
5832
  queue: [],
5939
5833
  draining: false,
5940
5834
  messages: [],
5941
5835
  createdAt: Date.now(),
5942
5836
  updatedAt: Date.now()
5943
5837
  };
5944
- fs19.mkdirSync(actorDirectory, { recursive: true, mode: 448 });
5838
+ fs18.mkdirSync(actorDirectory, { recursive: true, mode: 448 });
5945
5839
  this.#actors.set(id, actor);
5946
5840
  this.#locallyCreated.add(id);
5947
5841
  this.#ownership.set(id, true);
@@ -6271,17 +6165,17 @@ var ActorManager = class {
6271
6165
  const type = opts.type ?? "session";
6272
6166
  const lines = Math.max(1, Math.min(opts.lines ?? 200, 5e3));
6273
6167
  const sessionFile = actor.sessionFile;
6274
- const logDir = path19.join(path19.dirname(sessionFile), "runs");
6168
+ const logDir = path18.join(path18.dirname(sessionFile), "runs");
6275
6169
  const sessionPage = type === "run" ? { lines: [], hasMore: false } : readJsonlPage(sessionFile, lines, opts.before);
6276
6170
  const session = sessionPage.lines;
6277
6171
  let run;
6278
6172
  if (type !== "session") {
6279
6173
  const targetRunId = opts.runId ?? actor.lastRunId;
6280
6174
  if (targetRunId) {
6281
- const runPath = path19.join(logDir, targetRunId);
6282
- if (fs19.existsSync(runPath)) {
6283
- const statusRecord = readRunRecord(path19.join(runPath, "status.json"));
6284
- const eventsFile = path19.join(runPath, "events.jsonl");
6175
+ const runPath = path18.join(logDir, targetRunId);
6176
+ if (fs18.existsSync(runPath)) {
6177
+ const statusRecord = readRunRecord(path18.join(runPath, "status.json"));
6178
+ const eventsFile = path18.join(runPath, "events.jsonl");
6285
6179
  const page = readJsonlPage(eventsFile, lines, opts.before);
6286
6180
  run = {
6287
6181
  runId: targetRunId,
@@ -6484,7 +6378,7 @@ var ActorManager = class {
6484
6378
  await this.#bindings.delete(actor.id);
6485
6379
  this.#actors.delete(actor.id);
6486
6380
  this.#emitChange();
6487
- fs19.rmSync(path19.dirname(actor.sessionFile), { recursive: true, force: true });
6381
+ fs18.rmSync(path18.dirname(actor.sessionFile), { recursive: true, force: true });
6488
6382
  await this.#saveActors(/* @__PURE__ */ new Set([actor.id]));
6489
6383
  await this.mesh.delete({ key: this.#presenceKey(actor.id) }).catch(() => ({ deleted: false }));
6490
6384
  if (retainedRunId) await this.agents.cleanup(retainedRunId).catch(() => ({ cleaned: false }));
@@ -6525,7 +6419,7 @@ var ActorManager = class {
6525
6419
  await Promise.allSettled(
6526
6420
  [...this.#actors.values()].map((actor) => actor.drain ?? Promise.resolve())
6527
6421
  );
6528
- fs19.rmSync(this.#actorRoot, { recursive: true, force: true });
6422
+ fs18.rmSync(this.#actorRoot, { recursive: true, force: true });
6529
6423
  }
6530
6424
  #enqueue(actor, source, payload, options = {}) {
6531
6425
  const canManage = options.ownershipChecked ? this.#canManageCached(actor.id) : this.#canManage(actor.id);
@@ -7197,7 +7091,7 @@ var ActorManager = class {
7197
7091
  ...record.validWhile?.version === 1 && typeof record.validWhile.source === "string" ? { validWhile: record.validWhile } : {},
7198
7092
  ...principalScope ? { principalScope } : {},
7199
7093
  latestActivationSequence: 0,
7200
- sessionFile: path19.join(this.#actorRoot, record.id, "session.jsonl"),
7094
+ sessionFile: path18.join(this.#actorRoot, record.id, "session.jsonl"),
7201
7095
  queue: [],
7202
7096
  draining: false,
7203
7097
  messages: [],
@@ -7302,7 +7196,7 @@ var ActorManager = class {
7302
7196
  ...actor.lastRunId ? { lastRunId: actor.lastRunId } : {},
7303
7197
  ...actor.lastError ? { lastError: actor.lastError } : {},
7304
7198
  sessionFile: actor.sessionFile,
7305
- logDir: path19.join(path19.dirname(actor.sessionFile), "runs")
7199
+ logDir: path18.join(path18.dirname(actor.sessionFile), "runs")
7306
7200
  };
7307
7201
  }
7308
7202
  validateDirectMessage(message2, data) {
@@ -7509,10 +7403,10 @@ var ActorDirectory = class extends ActorManager {
7509
7403
  delete options.actorRoot;
7510
7404
  delete options.meshCursorPath;
7511
7405
  const cursorPaths = meshCursorPath ? { project: `${meshCursorPath}.project`, session: `${meshCursorPath}.session` } : void 0;
7512
- if (meshCursorPath && fs20.existsSync(meshCursorPath)) {
7406
+ if (meshCursorPath && fs19.existsSync(meshCursorPath)) {
7513
7407
  for (const cursorPath of Object.values(cursorPaths)) {
7514
7408
  try {
7515
- if (!fs20.existsSync(cursorPath)) fs20.copyFileSync(meshCursorPath, cursorPath);
7409
+ if (!fs19.existsSync(cursorPath)) fs19.copyFileSync(meshCursorPath, cursorPath);
7516
7410
  } catch {
7517
7411
  }
7518
7412
  }
@@ -8424,6 +8318,8 @@ var PARTICIPANT_LEASE_MS = 15e3;
8424
8318
  var TOMBSTONE_PREFIX = "topology/tombstones/";
8425
8319
  var DEPARTED_LIMIT = 32;
8426
8320
  var DEPARTED_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
8321
+ var REAP_INTERVAL_MS = 5 * 60 * 1e3;
8322
+ var REAP_BATCH = 100;
8427
8323
  var keyFor = (prefix, id) => prefix + createHash3("sha256").update(id).digest("hex");
8428
8324
  var isObject4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
8429
8325
  var participantKind = (value) => value === "root" || value === "agent" || value === "actor" || value === "provider" ? value : void 0;
@@ -8579,6 +8475,7 @@ var legacyActorFromEntry = (entry, roots) => {
8579
8475
  stale: false
8580
8476
  };
8581
8477
  };
8478
+ var sameExceptUpdatedAt = (left, right) => isObject4(left) && isObject4(right) && JSON.stringify({ ...left, updatedAt: 0 }) === JSON.stringify({ ...right, updatedAt: 0 });
8582
8479
  var liveOwner = (participant, hosts, now) => {
8583
8480
  const owner = hosts.get(participant.ownerHostId);
8584
8481
  return !!owner && owner.expiresAt >= now && owner.identity.id === participant.ownerIdentityId && owner.rootId === participant.rootId;
@@ -8602,9 +8499,14 @@ var ParticipantDirectory = class {
8602
8499
  #timer;
8603
8500
  #closed = false;
8604
8501
  #refreshing;
8502
+ #refreshingRenews = false;
8503
+ /** When this host last stamped its lease and liveness timestamps. */
8504
+ #renewedAt = 0;
8605
8505
  #refreshScheduled = false;
8606
8506
  #refreshAgain = false;
8607
8507
  #quiescing = false;
8508
+ #reapedAt = 0;
8509
+ #reaping;
8608
8510
  registerSource(source) {
8609
8511
  this.#sources.add(source);
8610
8512
  if (this.#timer) this.scheduleRefresh();
@@ -8622,7 +8524,7 @@ var ParticipantDirectory = class {
8622
8524
  } catch (error) {
8623
8525
  initialError = error;
8624
8526
  }
8625
- if (this.options.enabled) {
8527
+ if (this.options.enabled && !this.#closed) {
8626
8528
  this.#timer = setInterval(() => void this.refresh().catch(() => void 0), this.#heartbeatMs);
8627
8529
  this.#timer.unref();
8628
8530
  }
@@ -8638,18 +8540,37 @@ var ParticipantDirectory = class {
8638
8540
  this.#refreshScheduled = true;
8639
8541
  queueMicrotask(() => {
8640
8542
  this.#refreshScheduled = false;
8641
- void this.refresh().catch(() => void 0);
8543
+ void this.#run(false).catch(() => void 0);
8642
8544
  });
8643
8545
  }
8546
+ /** Publish every record and renew this host's lease, as the heartbeat does. */
8644
8547
  async refresh() {
8548
+ return this.#run(true);
8549
+ }
8550
+ // An event refresh (scheduleRefresh) publishes changed records only. Nested
8551
+ // tool calls schedule one each, and re-stamping unchanged timestamps then
8552
+ // rewrote the whole project mesh state three times per call, synchronously,
8553
+ // on the interactive thread. Liveness stays with the heartbeat: a lease and
8554
+ // its timestamps are renewed by refresh(), or by any refresh once the last
8555
+ // renewal is a heartbeat old, so they are never older than before.
8556
+ async #run(renew) {
8645
8557
  if (this.#closed) return;
8646
- if (this.#refreshing) return this.#refreshing;
8647
- const operation = this.#refresh();
8558
+ if (this.#refreshing) {
8559
+ if (!renew || this.#refreshingRenews) return this.#refreshing;
8560
+ await this.#refreshing.catch(() => void 0);
8561
+ return this.#run(true);
8562
+ }
8563
+ const renewing = renew || Date.now() - this.#renewedAt >= this.#heartbeatMs;
8564
+ const operation = this.#refresh(renewing);
8648
8565
  this.#refreshing = operation;
8566
+ this.#refreshingRenews = renewing;
8649
8567
  try {
8650
8568
  await operation;
8651
8569
  } finally {
8652
- if (this.#refreshing === operation) this.#refreshing = void 0;
8570
+ if (this.#refreshing === operation) {
8571
+ this.#refreshing = void 0;
8572
+ this.#refreshingRenews = false;
8573
+ }
8653
8574
  if (this.#refreshAgain) {
8654
8575
  this.#refreshAgain = false;
8655
8576
  this.scheduleRefresh();
@@ -8697,7 +8618,7 @@ var ParticipantDirectory = class {
8697
8618
  }
8698
8619
  }
8699
8620
  if (!options.kinds || options.kinds.includes("actor")) {
8700
- for (const entry of this.mesh.listAll(LEGACY_ACTOR_PREFIX)) {
8621
+ for (const entry of this.#legacyActorEntries(legacyRoots)) {
8701
8622
  const actor = legacyActorFromEntry(entry, legacyRoots);
8702
8623
  if (actor && !byId.has(actor.id)) byId.set(actor.id, actor);
8703
8624
  }
@@ -8838,6 +8759,7 @@ var ParticipantDirectory = class {
8838
8759
  if (this.#timer) clearInterval(this.#timer);
8839
8760
  this.#timer = void 0;
8840
8761
  await this.#refreshing?.catch(() => void 0);
8762
+ await this.#reaping;
8841
8763
  if (!this.options.enabled) return;
8842
8764
  const owned = this.mesh.listAll(PARTICIPANT_PREFIX).flatMap((entry) => {
8843
8765
  const participant = participantFromEntry(entry);
@@ -8872,7 +8794,7 @@ var ParticipantDirectory = class {
8872
8794
  const prune = kept.filter(({ tombstone }, index) => !tombstone || tombstone.lastSeenAt < cutoff || index >= this.#departedLimit);
8873
8795
  await Promise.allSettled(prune.map(({ entry }) => this.mesh.delete({ key: entry.key, ifVersion: entry.version })));
8874
8796
  }
8875
- async #refresh() {
8797
+ async #refresh(renew) {
8876
8798
  const now = Date.now();
8877
8799
  const desired = /* @__PURE__ */ new Map();
8878
8800
  for (const source of this.#sources) {
@@ -8910,27 +8832,27 @@ var ParticipantDirectory = class {
8910
8832
  await this.mesh.delete({ key: legacy.key, ifVersion: legacy.version }).catch(() => void 0);
8911
8833
  }
8912
8834
  } else if (root && legacySessionKey && root.cwd && root.sessionId) {
8913
- await this.mesh.put({
8914
- key: legacySessionKey,
8915
- value: {
8916
- id: root.id,
8917
- name: root.label ?? `Peer ${root.sessionId.slice(0, 8)}`,
8918
- ...root.label ? { label: root.label } : {},
8919
- kind: "peer",
8920
- status: root.status === "running" ? "running" : "idle",
8921
- runner: "pi",
8922
- transport: "host",
8923
- cwd: root.cwd,
8924
- sessionId: root.sessionId,
8925
- ...root.model ? { model: root.model } : {},
8926
- ...root.thinking ? { thinking: root.thinking } : {},
8927
- startedAt: root.startedAt,
8928
- updatedAt: now,
8929
- pendingMessages: root.pendingMessages === true,
8930
- local: false
8931
- },
8932
- identity: this.options.identity
8933
- });
8835
+ const value = {
8836
+ id: root.id,
8837
+ name: root.label ?? `Peer ${root.sessionId.slice(0, 8)}`,
8838
+ ...root.label ? { label: root.label } : {},
8839
+ kind: "peer",
8840
+ status: root.status === "running" ? "running" : "idle",
8841
+ runner: "pi",
8842
+ transport: "host",
8843
+ cwd: root.cwd,
8844
+ sessionId: root.sessionId,
8845
+ ...root.model ? { model: root.model } : {},
8846
+ ...root.thinking ? { thinking: root.thinking } : {},
8847
+ startedAt: root.startedAt,
8848
+ updatedAt: now,
8849
+ pendingMessages: root.pendingMessages === true,
8850
+ local: false
8851
+ };
8852
+ const legacy = renew ? void 0 : this.mesh.get(legacySessionKey);
8853
+ if (!legacy || legacy.updatedBy.id !== this.options.identity.id || !sameExceptUpdatedAt(legacy.value, value)) {
8854
+ await this.mesh.put({ key: legacySessionKey, value, identity: this.options.identity });
8855
+ }
8934
8856
  }
8935
8857
  const existing = this.mesh.listAll(PARTICIPANT_PREFIX).flatMap((entry) => {
8936
8858
  const participant = participantFromEntry(entry);
@@ -8944,14 +8866,14 @@ var ParticipantDirectory = class {
8944
8866
  })
8945
8867
  );
8946
8868
  const legacyActorOwners = new Map(
8947
- this.mesh.listAll(LEGACY_ACTOR_PREFIX).flatMap((entry) => {
8869
+ this.#legacyActorEntries(legacyRoots).flatMap((entry) => {
8948
8870
  const actor = legacyActorFromEntry(entry, legacyRoots);
8949
8871
  return actor ? [[actor.id, actor.ownerIdentityId]] : [];
8950
8872
  })
8951
8873
  );
8952
8874
  for (const record of desired.values()) {
8953
8875
  const current = existingById.get(record.id);
8954
- if (current && JSON.stringify(current.participant) === JSON.stringify(record)) continue;
8876
+ if (current && (renew ? JSON.stringify(current.participant) === JSON.stringify(record) : sameExceptUpdatedAt(current.participant, record))) continue;
8955
8877
  const key = keyFor(PARTICIPANT_PREFIX, record.id);
8956
8878
  const occupied = current?.entry ?? this.mesh.get(key);
8957
8879
  const occupiedParticipant = occupied && participantFromEntry(occupied);
@@ -8982,6 +8904,7 @@ var ParticipantDirectory = class {
8982
8904
  if (desired.has(participant.id)) continue;
8983
8905
  await this.mesh.delete({ key: entry.key, ifVersion: entry.version }).catch(() => void 0);
8984
8906
  }
8907
+ if (!renew) return;
8985
8908
  const leaseAt = Date.now();
8986
8909
  const host = {
8987
8910
  format: 1,
@@ -8997,6 +8920,69 @@ var ParticipantDirectory = class {
8997
8920
  value: host,
8998
8921
  identity: this.options.identity
8999
8922
  });
8923
+ this.#renewedAt = leaseAt;
8924
+ if (!this.#closed && !this.#quiescing && !this.#reaping && leaseAt - this.#reapedAt >= REAP_INTERVAL_MS) {
8925
+ this.#reapedAt = leaseAt;
8926
+ this.#reaping = this.#reapDeparted(leaseAt).then((more) => {
8927
+ if (more) this.#reapedAt = 0;
8928
+ }).catch(() => void 0).finally(() => {
8929
+ this.#reaping = void 0;
8930
+ });
8931
+ }
8932
+ }
8933
+ /**
8934
+ * Delete records whose owner lease has been dead longer than the departed
8935
+ * window. Close removes a host's own records, but a killed or crashed host
8936
+ * never closes, and every heartbeat in the project re-reads what it left.
8937
+ * Lost roots inside the window stay, so departed() still reports them.
8938
+ * Returns true when records were left for a later batch.
8939
+ */
8940
+ async #reapDeparted(now) {
8941
+ const cutoff = now - this.#departedRetentionMs;
8942
+ const hosts = this.#hosts();
8943
+ const retainedOwners = /* @__PURE__ */ new Set();
8944
+ const reap = [];
8945
+ for (const entry of this.mesh.listAll(PARTICIPANT_PREFIX)) {
8946
+ const participant = participantFromEntry(entry);
8947
+ if (!participant) continue;
8948
+ const owner = hosts.get(participant.ownerHostId);
8949
+ const heartbeat = owner?.identity.id === participant.ownerIdentityId ? owner.updatedAt : 0;
8950
+ if (!liveOwner(participant, hosts, now) && Math.max(participant.updatedAt, heartbeat) < cutoff) {
8951
+ reap.push(entry);
8952
+ } else {
8953
+ retainedOwners.add(participant.ownerHostId);
8954
+ }
8955
+ }
8956
+ for (const entry of this.mesh.listAll(HOST_PREFIX)) {
8957
+ const host = hostFromEntry(entry);
8958
+ if (host && host.expiresAt < cutoff && !retainedOwners.has(host.id)) reap.push(entry);
8959
+ }
8960
+ for (const entry of reap.slice(0, REAP_BATCH)) {
8961
+ if (this.#closed || this.#quiescing) return false;
8962
+ try {
8963
+ await this.mesh.delete({ key: entry.key, ifVersion: entry.version }, (entries) => {
8964
+ if (this.#closed || this.#quiescing) return false;
8965
+ const currentNow = Date.now();
8966
+ const currentCutoff = currentNow - this.#departedRetentionMs;
8967
+ const participant = participantFromEntry(entry);
8968
+ if (participant) {
8969
+ const ownerKey = keyFor(HOST_PREFIX, participant.ownerHostId);
8970
+ const ownerEntry = entries.find((item) => item.key === ownerKey);
8971
+ const owner = ownerEntry && hostFromEntry(ownerEntry);
8972
+ if (ownerEntry && !owner) return false;
8973
+ const owners = new Map(owner ? [[owner.id, owner]] : []);
8974
+ const heartbeat = owner?.identity.id === participant.ownerIdentityId ? owner.updatedAt : 0;
8975
+ return !liveOwner(participant, owners, currentNow) && Math.max(participant.updatedAt, heartbeat) < currentCutoff;
8976
+ }
8977
+ const host = hostFromEntry(entry);
8978
+ return !!host && host.expiresAt < currentCutoff && !entries.some((item) => item.key.startsWith(PARTICIPANT_PREFIX) && isObject4(item.value) && item.value.ownerHostId === host.id);
8979
+ });
8980
+ } catch {
8981
+ if (this.mesh.get(entry.key)?.version === entry.version) return true;
8982
+ }
8983
+ await new Promise((resolve) => setImmediate(resolve));
8984
+ }
8985
+ return reap.length > REAP_BATCH;
9000
8986
  }
9001
8987
  /**
9002
8988
  * Mint missing labels for this host's root participants. Labels persist in
@@ -9069,6 +9055,26 @@ var ParticipantDirectory = class {
9069
9055
  }
9070
9056
  return void 0;
9071
9057
  }
9058
+ /**
9059
+ * The legacy actor entries `legacyActorFromEntry` can accept, in key order:
9060
+ * only those under a live legacy root's `actors/<sessionId>/`. Listing the
9061
+ * whole `actors/` prefix cloned every actor state in the project on every
9062
+ * refresh, which dominated presence work once a project held many actors.
9063
+ */
9064
+ #legacyActorEntries(roots) {
9065
+ const byKey = /* @__PURE__ */ new Map();
9066
+ for (const root of roots.values()) {
9067
+ if (!root.sessionId) continue;
9068
+ let entries;
9069
+ try {
9070
+ entries = this.mesh.listAll(`${LEGACY_ACTOR_PREFIX}${root.sessionId}/`);
9071
+ } catch {
9072
+ return this.mesh.listAll(LEGACY_ACTOR_PREFIX);
9073
+ }
9074
+ for (const entry of entries) byKey.set(entry.key, entry);
9075
+ }
9076
+ return [...byKey.values()].sort((left, right) => left.key.localeCompare(right.key));
9077
+ }
9072
9078
  #legacySessionKey() {
9073
9079
  if (this.options.identity.kind !== "main") return void 0;
9074
9080
  return `sessions/${this.options.identity.sessionId ?? this.options.identity.id}`;
@@ -9153,7 +9159,7 @@ export {
9153
9159
  resolvePiBinary,
9154
9160
  resolveInheritedSessionPins,
9155
9161
  withInheritedSessionPins,
9156
- hasWorkerRecovery,
9162
+ assertWorktreePathSafe,
9157
9163
  isFabricWorktreePath,
9158
9164
  addCloneFirstWorktree,
9159
9165
  PiCodingAgent,
@@ -9178,4 +9184,4 @@ export {
9178
9184
  agentParticipantRecords,
9179
9185
  actorParticipantRecord
9180
9186
  };
9181
- //# sourceMappingURL=chunk-VGRUWTMG.js.map
9187
+ //# sourceMappingURL=chunk-RPZJVLML.js.map