@e4779/pi-fabric 0.117.2-fork.31 → 0.131.4-fork.33

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 (811) hide show
  1. package/README.md +13 -6
  2. package/THIRD_PARTY_NOTICES.md +6 -14
  3. package/dist/activity/store.d.ts +2 -1
  4. package/dist/activity/store.d.ts.map +1 -1
  5. package/dist/actors/binding-store.d.ts +13 -0
  6. package/dist/actors/binding-store.d.ts.map +1 -1
  7. package/dist/actors/directory.d.ts.map +1 -1
  8. package/dist/actors/feedback.d.ts +5 -0
  9. package/dist/actors/feedback.d.ts.map +1 -0
  10. package/dist/actors/global-registry.d.ts +8 -0
  11. package/dist/actors/global-registry.d.ts.map +1 -1
  12. package/dist/actors/host-event-payload.d.ts +14 -0
  13. package/dist/actors/host-event-payload.d.ts.map +1 -1
  14. package/dist/actors/manager.d.ts +4 -3
  15. package/dist/actors/manager.d.ts.map +1 -1
  16. package/dist/actors/mesh-monitor.d.ts +2 -0
  17. package/dist/actors/mesh-monitor.d.ts.map +1 -1
  18. package/dist/actors/name-policy.d.ts +3 -0
  19. package/dist/actors/name-policy.d.ts.map +1 -0
  20. package/dist/actors/registry-store.d.ts +14 -5
  21. package/dist/actors/registry-store.d.ts.map +1 -1
  22. package/dist/actors/store-read.d.ts +16 -0
  23. package/dist/actors/store-read.d.ts.map +1 -0
  24. package/dist/agents/agent-files.d.ts +80 -0
  25. package/dist/agents/agent-files.d.ts.map +1 -0
  26. package/dist/agents/agent-files.js +327 -0
  27. package/dist/agents/agent-files.js.map +7 -0
  28. package/dist/agents/child-skills.d.ts +60 -0
  29. package/dist/agents/child-skills.d.ts.map +1 -0
  30. package/dist/agents/child-skills.js +94 -0
  31. package/dist/agents/child-skills.js.map +7 -0
  32. package/dist/agents/clone-first-worktree.d.ts +6 -0
  33. package/dist/agents/clone-first-worktree.d.ts.map +1 -1
  34. package/dist/agents/completion-inbox.d.ts.map +1 -1
  35. package/dist/agents/cow-clone.d.ts.map +1 -1
  36. package/dist/agents/handoff.d.ts +12 -2
  37. package/dist/agents/handoff.d.ts.map +1 -1
  38. package/dist/agents/herdr-status.d.ts +26 -0
  39. package/dist/agents/herdr-status.d.ts.map +1 -0
  40. package/dist/agents/herdr-status.js +161 -0
  41. package/dist/agents/herdr-status.js.map +7 -0
  42. package/dist/agents/hosted-run.d.ts +20 -4
  43. package/dist/agents/hosted-run.d.ts.map +1 -1
  44. package/dist/agents/manager.d.ts +18 -2
  45. package/dist/agents/manager.d.ts.map +1 -1
  46. package/dist/agents/model-pin-guard.d.ts +27 -0
  47. package/dist/agents/model-pin-guard.d.ts.map +1 -0
  48. package/dist/agents/model-pin-guard.js +86 -0
  49. package/dist/agents/model-pin-guard.js.map +7 -0
  50. package/dist/agents/model-pin.d.ts +25 -0
  51. package/dist/agents/model-pin.d.ts.map +1 -0
  52. package/dist/agents/provider-bridge.d.ts +7 -6
  53. package/dist/agents/provider-bridge.d.ts.map +1 -1
  54. package/dist/agents/provider-bridge.js +33 -5
  55. package/dist/agents/provider-bridge.js.map +3 -3
  56. package/dist/agents/request.d.ts.map +1 -1
  57. package/dist/agents/result.d.ts.map +1 -1
  58. package/dist/agents/result.js +1 -1
  59. package/dist/agents/runner-notice.d.ts.map +1 -1
  60. package/dist/agents/runner-protocol.d.ts +8 -0
  61. package/dist/agents/runner-protocol.d.ts.map +1 -1
  62. package/dist/agents/service-schema.d.ts.map +1 -1
  63. package/dist/agents/transports/herdr-core-socket.d.ts +13 -0
  64. package/dist/agents/transports/herdr-core-socket.d.ts.map +1 -0
  65. package/dist/agents/transports/herdr-core-transport.d.ts +10 -0
  66. package/dist/agents/transports/herdr-core-transport.d.ts.map +1 -0
  67. package/dist/agents/transports/herdr-socket.d.ts +12 -0
  68. package/dist/agents/transports/herdr-socket.d.ts.map +1 -0
  69. package/dist/agents/transports/herdr-transport.d.ts.map +1 -1
  70. package/dist/agents/types.d.ts +51 -0
  71. package/dist/agents/types.d.ts.map +1 -1
  72. package/dist/agents/worker-recovery.d.ts +75 -0
  73. package/dist/agents/worker-recovery.d.ts.map +1 -0
  74. package/dist/agents/worktree-manager.d.ts.map +1 -1
  75. package/dist/agents.js +12 -11
  76. package/dist/agents.js.map +2 -2
  77. package/dist/audit/details.d.ts +38 -1
  78. package/dist/audit/details.d.ts.map +1 -1
  79. package/dist/audit/projection.d.ts.map +1 -1
  80. package/dist/audit/trace-schema.d.ts +50 -0
  81. package/dist/audit/trace-schema.d.ts.map +1 -0
  82. package/dist/audit/trace.d.ts +2 -48
  83. package/dist/audit/trace.d.ts.map +1 -1
  84. package/dist/chunks/chunk-2RWNVCFD.js +483 -0
  85. package/dist/chunks/chunk-2RWNVCFD.js.map +7 -0
  86. package/dist/chunks/chunk-2SCMGO2Z.js +16 -0
  87. package/dist/chunks/chunk-2SCMGO2Z.js.map +7 -0
  88. package/dist/chunks/chunk-35EEGOH3.js +324 -0
  89. package/dist/chunks/chunk-35EEGOH3.js.map +7 -0
  90. package/dist/chunks/{chunk-UTOBAZ5T.js → chunk-37NIOSVU.js} +1 -1
  91. package/dist/chunks/chunk-37NIOSVU.js.map +7 -0
  92. package/dist/chunks/chunk-3IJEQBFS.js +25 -0
  93. package/dist/chunks/chunk-3IJEQBFS.js.map +7 -0
  94. package/dist/chunks/{chunk-EHQQ4KCX.js → chunk-3MOY6WIB.js} +84 -19
  95. package/dist/chunks/chunk-3MOY6WIB.js.map +7 -0
  96. package/dist/chunks/chunk-3VK6UGAN.js +64 -0
  97. package/dist/chunks/chunk-3VK6UGAN.js.map +7 -0
  98. package/dist/chunks/{chunk-ROTCDDOV.js → chunk-3XT5WHSG.js} +59 -119
  99. package/dist/chunks/chunk-3XT5WHSG.js.map +7 -0
  100. package/dist/chunks/{chunk-FIDUHKMM.js → chunk-4BYS4ZLY.js} +16 -16
  101. package/dist/chunks/chunk-4BYS4ZLY.js.map +7 -0
  102. package/dist/chunks/{chunk-UOM37PE4.js → chunk-4PBW54I2.js} +162 -92
  103. package/dist/chunks/chunk-4PBW54I2.js.map +7 -0
  104. package/dist/chunks/{chunk-ZEXCKK4K.js → chunk-4WKD3YM3.js} +3 -3
  105. package/dist/chunks/{chunk-PK4NIJEV.js → chunk-4XMXFHAR.js} +62 -3
  106. package/dist/chunks/chunk-4XMXFHAR.js.map +7 -0
  107. package/dist/chunks/{chunk-4EW7GVUR.js → chunk-56NMRVTV.js} +589 -377
  108. package/dist/chunks/chunk-56NMRVTV.js.map +7 -0
  109. package/dist/chunks/chunk-5QJFDKPN.js +179 -0
  110. package/dist/chunks/chunk-5QJFDKPN.js.map +7 -0
  111. package/dist/chunks/{chunk-P7CBPPHY.js → chunk-6GWDGTHC.js} +5 -5
  112. package/dist/chunks/{chunk-P7CBPPHY.js.map → chunk-6GWDGTHC.js.map} +1 -1
  113. package/dist/chunks/chunk-6HO2IUQ5.js +104 -0
  114. package/dist/chunks/chunk-6HO2IUQ5.js.map +7 -0
  115. package/dist/chunks/chunk-6OGYPHNQ.js +62 -0
  116. package/dist/chunks/chunk-6OGYPHNQ.js.map +7 -0
  117. package/dist/chunks/{chunk-G4TLWHRS.js → chunk-7N7IC3Z2.js} +4 -3
  118. package/dist/chunks/{chunk-G4TLWHRS.js.map → chunk-7N7IC3Z2.js.map} +2 -2
  119. package/dist/chunks/{chunk-5XBYFSI5.js → chunk-7YNE4NB2.js} +2 -2
  120. package/dist/chunks/chunk-ASOJYFKU.js +1316 -0
  121. package/dist/chunks/chunk-ASOJYFKU.js.map +7 -0
  122. package/dist/chunks/{chunk-NTC2MCB6.js → chunk-B5L3X3ID.js} +1 -1
  123. package/dist/chunks/{chunk-NTC2MCB6.js.map → chunk-B5L3X3ID.js.map} +1 -1
  124. package/dist/chunks/chunk-BIBRWZWQ.js +325 -0
  125. package/dist/chunks/chunk-BIBRWZWQ.js.map +7 -0
  126. package/dist/chunks/{chunk-K6QXUGS5.js → chunk-BMAEZNZ5.js} +2 -1
  127. package/dist/chunks/{chunk-FSB2VIRZ.js → chunk-CBIV747V.js} +14 -3
  128. package/dist/chunks/chunk-CBIV747V.js.map +7 -0
  129. package/dist/chunks/{chunk-CCHZXF6K.js → chunk-CXYJJ3HZ.js} +3 -3
  130. package/dist/chunks/{chunk-R2XQ6AHT.js → chunk-DGERP4VL.js} +22 -10
  131. package/dist/chunks/chunk-DGERP4VL.js.map +7 -0
  132. package/dist/chunks/{chunk-C7Z6F3SO.js → chunk-DGUXJSYA.js} +64 -33
  133. package/dist/chunks/chunk-DGUXJSYA.js.map +7 -0
  134. package/dist/chunks/chunk-F2LGSRIN.js +38 -0
  135. package/dist/chunks/chunk-F2LGSRIN.js.map +7 -0
  136. package/dist/chunks/chunk-F6A6MQ6G.js +609 -0
  137. package/dist/chunks/chunk-F6A6MQ6G.js.map +7 -0
  138. package/dist/chunks/{chunk-IR3PIHJM.js → chunk-FK73YJKV.js} +67 -2
  139. package/dist/chunks/chunk-FK73YJKV.js.map +7 -0
  140. package/dist/chunks/{chunk-XCEEQ5AB.js → chunk-G2DZJ5LK.js} +1607 -1567
  141. package/dist/chunks/chunk-G2DZJ5LK.js.map +7 -0
  142. package/dist/chunks/{chunk-VYQV5JRT.js → chunk-GJVKEHDL.js} +2 -2
  143. package/dist/chunks/chunk-GJVKEHDL.js.map +7 -0
  144. package/dist/chunks/{chunk-TIIIHPHF.js → chunk-GS67KDMV.js} +2 -2
  145. package/dist/chunks/{chunk-D5NYNIST.js → chunk-H57KPL3V.js} +5 -5
  146. package/dist/chunks/{chunk-KVYNGDGC.js → chunk-HFDJWLMS.js} +6 -6
  147. package/dist/chunks/{chunk-KVYNGDGC.js.map → chunk-HFDJWLMS.js.map} +1 -1
  148. package/dist/chunks/{chunk-INRXG4J5.js → chunk-HGD75NZY.js} +2 -2
  149. package/dist/chunks/{chunk-CRRUW26I.js → chunk-HRDMBGMY.js} +12 -12
  150. package/dist/chunks/{chunk-CRRUW26I.js.map → chunk-HRDMBGMY.js.map} +2 -2
  151. package/dist/chunks/{chunk-GO32KSEZ.js → chunk-HRVYXRWZ.js} +85 -10
  152. package/dist/chunks/chunk-HRVYXRWZ.js.map +7 -0
  153. package/dist/chunks/{chunk-MLLYR3Y6.js → chunk-HSEZPCL5.js} +19 -78
  154. package/dist/chunks/chunk-HSEZPCL5.js.map +7 -0
  155. package/dist/chunks/chunk-JMUUNW2H.js +65 -0
  156. package/dist/chunks/chunk-JMUUNW2H.js.map +7 -0
  157. package/dist/chunks/{chunk-UXIBKMUM.js → chunk-KIFOEBYJ.js} +4 -4
  158. package/dist/chunks/{chunk-3FJUP3GV.js → chunk-L6H46CPY.js} +2 -2
  159. package/dist/chunks/{chunk-SPCJXN4K.js → chunk-LKYLD5SN.js} +298 -65
  160. package/dist/chunks/chunk-LKYLD5SN.js.map +7 -0
  161. package/dist/chunks/{chunk-K7J2ABAZ.js → chunk-LRSZFYUC.js} +92 -32
  162. package/dist/chunks/chunk-LRSZFYUC.js.map +7 -0
  163. package/dist/chunks/{chunk-GIK2WNAK.js → chunk-LZ2ZXOCU.js} +112 -23
  164. package/dist/chunks/chunk-LZ2ZXOCU.js.map +7 -0
  165. package/dist/chunks/{chunk-FUY6XVRX.js → chunk-MPMEK3IQ.js} +2 -2
  166. package/dist/chunks/{chunk-HP5P7NBO.js → chunk-MSDL7U6Q.js} +4 -4
  167. package/dist/chunks/{chunk-ASSLHWZS.js → chunk-MX53BRAC.js} +2 -2
  168. package/dist/chunks/chunk-N7ZAK2PB.js +132 -0
  169. package/dist/chunks/chunk-N7ZAK2PB.js.map +7 -0
  170. package/dist/chunks/{chunk-VSDUSNIA.js → chunk-NBIYYMKS.js} +8 -2
  171. package/dist/chunks/chunk-NBIYYMKS.js.map +7 -0
  172. package/dist/chunks/chunk-NENQZCGW.js +45 -0
  173. package/dist/chunks/chunk-NENQZCGW.js.map +7 -0
  174. package/dist/chunks/chunk-NJHJKINP.js +47 -0
  175. package/dist/chunks/chunk-NJHJKINP.js.map +7 -0
  176. package/dist/chunks/{chunk-U366I5K2.js → chunk-NQ7IWEIF.js} +18 -6
  177. package/dist/chunks/chunk-NQ7IWEIF.js.map +7 -0
  178. package/dist/chunks/{chunk-ZQMBS5SH.js → chunk-OJ4HAALD.js} +15 -12
  179. package/dist/chunks/chunk-OJ4HAALD.js.map +7 -0
  180. package/dist/chunks/chunk-OZCJU3PZ.js +33 -0
  181. package/dist/chunks/chunk-OZCJU3PZ.js.map +7 -0
  182. package/dist/chunks/chunk-P3DCXKL3.js +40 -0
  183. package/dist/chunks/chunk-P3DCXKL3.js.map +7 -0
  184. package/dist/chunks/chunk-P7YSPKTM.js +294 -0
  185. package/dist/chunks/chunk-P7YSPKTM.js.map +7 -0
  186. package/dist/chunks/chunk-PQVUMJ5J.js +223 -0
  187. package/dist/chunks/chunk-PQVUMJ5J.js.map +7 -0
  188. package/dist/chunks/chunk-PUBHBEYO.js +84 -0
  189. package/dist/chunks/chunk-PUBHBEYO.js.map +7 -0
  190. package/dist/chunks/{chunk-P4KH4S4S.js → chunk-QGTD3LAZ.js} +5 -20
  191. package/dist/chunks/chunk-QGTD3LAZ.js.map +7 -0
  192. package/dist/chunks/{chunk-TIJ3YQXX.js → chunk-QOEOKW2X.js} +2 -2
  193. package/dist/chunks/{chunk-TIJ3YQXX.js.map → chunk-QOEOKW2X.js.map} +1 -1
  194. package/dist/chunks/{chunk-QT4W5YVB.js → chunk-RAA3FAYZ.js} +2 -2
  195. package/dist/chunks/{chunk-3UGN25XS.js → chunk-RKJPBTBB.js} +98 -1664
  196. package/dist/chunks/chunk-RKJPBTBB.js.map +7 -0
  197. package/dist/chunks/{chunk-WJJXODAB.js → chunk-RLKRZXSX.js} +8 -1
  198. package/dist/chunks/{chunk-WJJXODAB.js.map → chunk-RLKRZXSX.js.map} +2 -2
  199. package/dist/chunks/chunk-RWKQ5SRW.js +129 -0
  200. package/dist/chunks/chunk-RWKQ5SRW.js.map +7 -0
  201. package/dist/chunks/chunk-SW25R47N.js +71 -0
  202. package/dist/chunks/chunk-SW25R47N.js.map +7 -0
  203. package/dist/chunks/{chunk-EKODKR6Y.js → chunk-TEMKDJJY.js} +148 -72
  204. package/dist/chunks/chunk-TEMKDJJY.js.map +7 -0
  205. package/dist/chunks/{chunk-EFETPXU2.js → chunk-TJZYM2SP.js} +118 -237
  206. package/dist/chunks/chunk-TJZYM2SP.js.map +7 -0
  207. package/dist/chunks/{chunk-53N2I4QA.js → chunk-TXCNZCZP.js} +2 -2
  208. package/dist/chunks/{chunk-LNASO4VT.js → chunk-U6Y6TKJL.js} +45 -20
  209. package/dist/chunks/chunk-U6Y6TKJL.js.map +7 -0
  210. package/dist/chunks/chunk-UD7LFV43.js +28 -0
  211. package/dist/chunks/chunk-UD7LFV43.js.map +7 -0
  212. package/dist/chunks/{chunk-7QKKLBHJ.js → chunk-UPMWLOKL.js} +10 -1
  213. package/dist/chunks/{chunk-7QKKLBHJ.js.map → chunk-UPMWLOKL.js.map} +2 -2
  214. package/dist/chunks/chunk-V4OW2ULC.js +422 -0
  215. package/dist/chunks/chunk-V4OW2ULC.js.map +7 -0
  216. package/dist/chunks/{chunk-FE6NOAO7.js → chunk-VGRUWTMG.js} +1993 -659
  217. package/dist/chunks/chunk-VGRUWTMG.js.map +7 -0
  218. package/dist/chunks/{chunk-PYFJW3HC.js → chunk-W5FEHVZA.js} +2 -16
  219. package/dist/chunks/{chunk-PYFJW3HC.js.map → chunk-W5FEHVZA.js.map} +3 -3
  220. package/dist/chunks/chunk-WKFRGICG.js +101 -0
  221. package/dist/chunks/chunk-WKFRGICG.js.map +7 -0
  222. package/dist/chunks/{chunk-LEU5CDSL.js → chunk-XFOSUGLU.js} +5 -5
  223. package/dist/chunks/{chunk-MZUC6LLH.js → chunk-XMYG2TKR.js} +4 -4
  224. package/dist/chunks/{chunk-MZUC6LLH.js.map → chunk-XMYG2TKR.js.map} +1 -1
  225. package/dist/chunks/chunk-YC65P7ZO.js +57 -0
  226. package/dist/chunks/chunk-YC65P7ZO.js.map +7 -0
  227. package/dist/chunks/{chunk-5UBRGTVN.js → chunk-ZHROHNEE.js} +31 -15
  228. package/dist/chunks/chunk-ZHROHNEE.js.map +7 -0
  229. package/dist/cli/decisions.d.ts.map +1 -1
  230. package/dist/cli/decisions.js +15 -3
  231. package/dist/cli/decisions.js.map +2 -2
  232. package/dist/cli/mesh.js +4 -3
  233. package/dist/cli/mesh.js.map +1 -1
  234. package/dist/commands/fabric-handler.d.ts +7 -0
  235. package/dist/commands/fabric-handler.d.ts.map +1 -0
  236. package/dist/commands/fabric-handler.js +916 -0
  237. package/dist/commands/fabric-handler.js.map +7 -0
  238. package/dist/commands/fabric.d.ts +11 -1
  239. package/dist/commands/fabric.d.ts.map +1 -1
  240. package/dist/compaction/claim-events.d.ts +61 -0
  241. package/dist/compaction/claim-events.d.ts.map +1 -0
  242. package/dist/compaction/claim-events.js +210 -0
  243. package/dist/compaction/claim-events.js.map +7 -0
  244. package/dist/compaction/claim.d.ts +51 -0
  245. package/dist/compaction/claim.d.ts.map +1 -0
  246. package/dist/compaction/hook.d.ts +28 -2
  247. package/dist/compaction/hook.d.ts.map +1 -1
  248. package/dist/compaction/hook.js +12 -7
  249. package/dist/compaction/owner.js +9 -8
  250. package/dist/compaction/trace-events.d.ts +1 -1
  251. package/dist/compaction/trace-events.d.ts.map +1 -1
  252. package/dist/components/configuration.js +6 -6
  253. package/dist/components/effect-scope.d.ts.map +1 -1
  254. package/dist/config.d.ts +40 -3
  255. package/dist/config.d.ts.map +1 -1
  256. package/dist/core/action-arguments.d.ts.map +1 -1
  257. package/dist/core/action-policy-hooks.d.ts +69 -0
  258. package/dist/core/action-policy-hooks.d.ts.map +1 -0
  259. package/dist/core/action-registry.d.ts +31 -10
  260. package/dist/core/action-registry.d.ts.map +1 -1
  261. package/dist/core/action-registry.js +12 -9
  262. package/dist/core/approval-controller.d.ts +23 -3
  263. package/dist/core/approval-controller.d.ts.map +1 -1
  264. package/dist/core/atomic-write.d.ts +164 -0
  265. package/dist/core/atomic-write.d.ts.map +1 -1
  266. package/dist/core/call-presentation.d.ts +14 -0
  267. package/dist/core/call-presentation.d.ts.map +1 -0
  268. package/dist/core/child-tool-allowlist.d.ts +17 -1
  269. package/dist/core/child-tool-allowlist.d.ts.map +1 -1
  270. package/dist/core/compact-controller.d.ts +34 -0
  271. package/dist/core/compact-controller.d.ts.map +1 -1
  272. package/dist/core/core-override-guidance.d.ts +3 -1
  273. package/dist/core/core-override-guidance.d.ts.map +1 -1
  274. package/dist/core/file-lock.d.ts.map +1 -1
  275. package/dist/core/foreground-tools.d.ts +4 -1
  276. package/dist/core/foreground-tools.d.ts.map +1 -1
  277. package/dist/core/host-policy.d.ts +43 -0
  278. package/dist/core/host-policy.d.ts.map +1 -0
  279. package/dist/core/host-sdk-runtime.d.ts.map +1 -1
  280. package/dist/core/host-sdk.d.ts.map +1 -1
  281. package/dist/core/host-sdk.js +1 -1
  282. package/dist/core/managed-host-guidance.d.ts +5 -0
  283. package/dist/core/managed-host-guidance.d.ts.map +1 -0
  284. package/dist/core/model-aliases.d.ts +22 -0
  285. package/dist/core/model-aliases.d.ts.map +1 -0
  286. package/dist/core/model-resolution.d.ts +41 -20
  287. package/dist/core/model-resolution.d.ts.map +1 -1
  288. package/dist/core/native-tool-result.d.ts +1 -0
  289. package/dist/core/native-tool-result.d.ts.map +1 -1
  290. package/dist/core/program-tasks.d.ts +52 -0
  291. package/dist/core/program-tasks.d.ts.map +1 -0
  292. package/dist/core/prompt-guidance.d.ts +5 -0
  293. package/dist/core/prompt-guidance.d.ts.map +1 -0
  294. package/dist/core/prompt-guidance.js +159 -0
  295. package/dist/core/prompt-guidance.js.map +7 -0
  296. package/dist/core/provider-operations.d.ts.map +1 -1
  297. package/dist/core/provider-operations.js +60 -108
  298. package/dist/core/provider-operations.js.map +3 -3
  299. package/dist/core/shell-inbox.d.ts.map +1 -1
  300. package/dist/core/shell-jobs.d.ts +7 -5
  301. package/dist/core/shell-jobs.d.ts.map +1 -1
  302. package/dist/core/shell-timing.d.ts.map +1 -1
  303. package/dist/core/skill-prompt.d.ts +1 -1
  304. package/dist/core/skill-prompt.d.ts.map +1 -1
  305. package/dist/core/skill-references.d.ts +1 -1
  306. package/dist/core/skill-references.d.ts.map +1 -1
  307. package/dist/core/system-guidance.d.ts.map +1 -1
  308. package/dist/core/tool-result-proxy.d.ts.map +1 -1
  309. package/dist/decisions/command.d.ts +2 -1
  310. package/dist/decisions/command.d.ts.map +1 -1
  311. package/dist/decisions/command.js +40 -12
  312. package/dist/decisions/command.js.map +2 -2
  313. package/dist/decisions/events.d.ts +12 -0
  314. package/dist/decisions/events.d.ts.map +1 -0
  315. package/dist/decisions/events.js +130 -0
  316. package/dist/decisions/events.js.map +7 -0
  317. package/dist/decisions/host.d.ts +31 -3
  318. package/dist/decisions/host.d.ts.map +1 -1
  319. package/dist/decisions/render.d.ts +44 -0
  320. package/dist/decisions/render.d.ts.map +1 -0
  321. package/dist/decisions/store.d.ts +8 -0
  322. package/dist/decisions/store.d.ts.map +1 -1
  323. package/dist/durable/agent.d.ts +8 -0
  324. package/dist/durable/agent.d.ts.map +1 -1
  325. package/dist/durable/extension-load-error.d.ts +8 -0
  326. package/dist/durable/extension-load-error.d.ts.map +1 -0
  327. package/dist/durable/session.d.ts +1 -0
  328. package/dist/durable/session.d.ts.map +1 -1
  329. package/dist/durable/worker-host.d.ts +10 -1
  330. package/dist/durable/worker-host.d.ts.map +1 -1
  331. package/dist/durable/worker-host.js +10 -1181
  332. package/dist/durable/worker-host.js.map +4 -4
  333. package/dist/durable/worker-options.d.ts +3 -0
  334. package/dist/durable/worker-options.d.ts.map +1 -1
  335. package/dist/durable/worker-role-seed.d.ts +82 -0
  336. package/dist/durable/worker-role-seed.d.ts.map +1 -0
  337. package/dist/durable/worker.js +43 -4
  338. package/dist/durable/worker.js.map +2 -2
  339. package/dist/durable-controls.d.ts.map +1 -1
  340. package/dist/durable-extension-wasm.d.ts +8 -0
  341. package/dist/durable-extension-wasm.d.ts.map +1 -0
  342. package/dist/durable-extension-wasm.js +32 -0
  343. package/dist/durable-extension-wasm.js.map +7 -0
  344. package/dist/durable-extension.d.ts +94 -0
  345. package/dist/durable-extension.d.ts.map +1 -0
  346. package/dist/durable-extension.js +649 -0
  347. package/dist/durable-extension.js.map +7 -0
  348. package/dist/durable-host.d.ts +8 -0
  349. package/dist/durable-host.d.ts.map +1 -0
  350. package/dist/durable-host.js +20 -0
  351. package/dist/durable-host.js.map +7 -0
  352. package/dist/durable-journal.d.ts +94 -0
  353. package/dist/durable-journal.d.ts.map +1 -0
  354. package/dist/durable.d.ts.map +1 -1
  355. package/dist/durable.js +13 -10
  356. package/dist/durable.js.map +2 -2
  357. package/dist/entropy/index.js +12 -10
  358. package/dist/entropy/pool-store.d.ts.map +1 -1
  359. package/dist/execution-service.d.ts +14 -0
  360. package/dist/execution-service.d.ts.map +1 -1
  361. package/dist/extension-bootstrap.d.ts.map +1 -1
  362. package/dist/extension-bootstrap.js +28 -27
  363. package/dist/extension-bootstrap.js.map +2 -2
  364. package/dist/extension-copy.d.ts +21 -0
  365. package/dist/extension-copy.d.ts.map +1 -0
  366. package/dist/extension-copy.js +90 -0
  367. package/dist/extension-copy.js.map +7 -0
  368. package/dist/extension.d.ts +1 -1
  369. package/dist/extension.d.ts.map +1 -1
  370. package/dist/fabric-exec-arguments.d.ts.map +1 -1
  371. package/dist/fabric-exec-tool.d.ts +2 -1
  372. package/dist/fabric-exec-tool.d.ts.map +1 -1
  373. package/dist/fabric-runtime-state.d.ts +19 -0
  374. package/dist/fabric-runtime-state.d.ts.map +1 -1
  375. package/dist/fabric-runtime-state.js +2205 -839
  376. package/dist/fabric-runtime-state.js.map +4 -4
  377. package/dist/fabric-state.d.ts +44 -1
  378. package/dist/fabric-state.d.ts.map +1 -1
  379. package/dist/feedback.d.ts +5 -0
  380. package/dist/feedback.d.ts.map +1 -0
  381. package/dist/index.d.ts +5 -3
  382. package/dist/index.d.ts.map +1 -1
  383. package/dist/index.js +88 -53
  384. package/dist/index.js.map +2 -2
  385. package/dist/jev/client.js +2 -2
  386. package/dist/jev/manager.d.ts +3 -0
  387. package/dist/jev/manager.d.ts.map +1 -1
  388. package/dist/jev/observation.d.ts +1 -1
  389. package/dist/jev/observation.js +6 -6
  390. package/dist/jev-fabric/bridge.d.ts.map +1 -1
  391. package/dist/jev.js +11 -12
  392. package/dist/main-agent.d.ts +2 -1
  393. package/dist/main-agent.d.ts.map +1 -1
  394. package/dist/managed-host.d.ts +13 -0
  395. package/dist/managed-host.d.ts.map +1 -1
  396. package/dist/memory/digest.js +2 -2
  397. package/dist/memory/discovery.js +6 -7
  398. package/dist/memory/file-worker.js +10 -11
  399. package/dist/memory/file-worker.js.map +1 -1
  400. package/dist/memory/normalize.js +5 -6
  401. package/dist/memory/search.js +7 -8
  402. package/dist/memory/worker-provider.js +11 -12
  403. package/dist/memory.js +11 -12
  404. package/dist/memory.js.map +1 -1
  405. package/dist/mesh/grants.d.ts +3 -3
  406. package/dist/mesh/grants.d.ts.map +1 -1
  407. package/dist/mesh/store.d.ts +8 -0
  408. package/dist/mesh/store.d.ts.map +1 -1
  409. package/dist/native-codemode.d.ts.map +1 -1
  410. package/dist/native-tool-catalog.d.ts.map +1 -1
  411. package/dist/native-tool-catalog.js +12 -3
  412. package/dist/native-tool-catalog.js.map +2 -2
  413. package/dist/programs/host.d.ts +18 -6
  414. package/dist/programs/host.d.ts.map +1 -1
  415. package/dist/programs/host.js +71 -47
  416. package/dist/programs/host.js.map +2 -2
  417. package/dist/programs/source.d.ts +11 -0
  418. package/dist/programs/source.d.ts.map +1 -1
  419. package/dist/programs/store.d.ts.map +1 -1
  420. package/dist/protocol.d.ts +504 -8
  421. package/dist/protocol.d.ts.map +1 -1
  422. package/dist/protocol.js +41 -11
  423. package/dist/provider-globals.d.ts +13 -0
  424. package/dist/provider-globals.d.ts.map +1 -0
  425. package/dist/providers/agents-actions.d.ts.map +1 -1
  426. package/dist/providers/agents-provider.d.ts +3 -0
  427. package/dist/providers/agents-provider.d.ts.map +1 -1
  428. package/dist/providers/captured-tools-provider.d.ts +5 -0
  429. package/dist/providers/captured-tools-provider.d.ts.map +1 -1
  430. package/dist/providers/compact-provider.d.ts +4 -1
  431. package/dist/providers/compact-provider.d.ts.map +1 -1
  432. package/dist/providers/components-provider.d.ts.map +1 -1
  433. package/dist/providers/decisions-provider.d.ts +9 -1
  434. package/dist/providers/decisions-provider.d.ts.map +1 -1
  435. package/dist/providers/jev-provider.d.ts +1 -1
  436. package/dist/providers/jev-provider.js +11 -12
  437. package/dist/providers/memory-provider.js +10 -11
  438. package/dist/providers/pi-tools-provider.d.ts +14 -0
  439. package/dist/providers/pi-tools-provider.d.ts.map +1 -1
  440. package/dist/providers/programs-provider.d.ts.map +1 -1
  441. package/dist/providers/sessions-provider.d.ts +7 -0
  442. package/dist/providers/sessions-provider.d.ts.map +1 -1
  443. package/dist/repeat-guard.d.ts +7 -6
  444. package/dist/repeat-guard.d.ts.map +1 -1
  445. package/dist/residency/actor-client.js +3 -3
  446. package/dist/residency/client.d.ts +15 -0
  447. package/dist/residency/client.d.ts.map +1 -1
  448. package/dist/residency/host.d.ts.map +1 -1
  449. package/dist/residency/host.js +34 -23
  450. package/dist/residency/launcher.js +1 -1
  451. package/dist/residency/pi-entry.js +34 -23
  452. package/dist/residency/pi-entry.js.map +1 -1
  453. package/dist/residency/protocol.d.ts +2 -0
  454. package/dist/residency/protocol.d.ts.map +1 -1
  455. package/dist/runners.js +11 -1
  456. package/dist/runners.js.map +2 -2
  457. package/dist/runtime/core-override-guest-types.js +2 -2
  458. package/dist/runtime/cpython-child-source.d.ts.map +1 -1
  459. package/dist/runtime/cpython-runtime.d.ts.map +1 -1
  460. package/dist/runtime/cpython-runtime.js +51 -21
  461. package/dist/runtime/cpython-runtime.js.map +2 -2
  462. package/dist/runtime/deadline-pause.d.ts +2 -0
  463. package/dist/runtime/deadline-pause.d.ts.map +1 -1
  464. package/dist/runtime/dynamic-guest-types.d.ts.map +1 -1
  465. package/dist/runtime/dynamic-guest-types.js +2 -1
  466. package/dist/runtime/exec-journal.d.ts +73 -0
  467. package/dist/runtime/exec-journal.d.ts.map +1 -0
  468. package/dist/runtime/exec-journal.js +335 -0
  469. package/dist/runtime/exec-journal.js.map +7 -0
  470. package/dist/runtime/guest-types.d.ts +3 -2
  471. package/dist/runtime/guest-types.d.ts.map +1 -1
  472. package/dist/runtime/guest-types.js +1 -1
  473. package/dist/runtime/journal-shim.d.ts +3 -0
  474. package/dist/runtime/journal-shim.d.ts.map +1 -0
  475. package/dist/runtime/kernel.d.ts +95 -1
  476. package/dist/runtime/kernel.d.ts.map +1 -1
  477. package/dist/runtime/monty-bridge.d.ts +6 -2
  478. package/dist/runtime/monty-bridge.d.ts.map +1 -1
  479. package/dist/runtime/monty-runtime.d.ts.map +1 -1
  480. package/dist/runtime/monty-runtime.js +27 -15
  481. package/dist/runtime/monty-runtime.js.map +2 -2
  482. package/dist/runtime/native-codemode-guest.d.ts.map +1 -1
  483. package/dist/runtime/node-process-runtime.d.ts.map +1 -1
  484. package/dist/runtime/node-process-runtime.js +7 -5
  485. package/dist/runtime/quickjs-runtime.d.ts +7 -1
  486. package/dist/runtime/quickjs-runtime.d.ts.map +1 -1
  487. package/dist/runtime/quickjs-runtime.js +5 -4
  488. package/dist/runtime/sha256.d.ts +4 -0
  489. package/dist/runtime/sha256.d.ts.map +1 -0
  490. package/dist/runtime/transpile.d.ts +8 -0
  491. package/dist/runtime/transpile.d.ts.map +1 -0
  492. package/dist/runtime/type-checker.d.ts +1 -7
  493. package/dist/runtime/type-checker.d.ts.map +1 -1
  494. package/dist/runtime/type-checker.js +4 -2
  495. package/dist/runtime/typescript-kernel.js +13 -10
  496. package/dist/runtime/typescript-kernel.js.map +1 -1
  497. package/dist/runtime-state-builtins.d.ts.map +1 -1
  498. package/dist/speculation/scanner.js +1 -1
  499. package/dist/speculation/store.d.ts +7 -16
  500. package/dist/speculation/store.d.ts.map +1 -1
  501. package/dist/speculation/types.d.ts +1 -0
  502. package/dist/speculation/types.d.ts.map +1 -1
  503. package/dist/storage/retention.d.ts.map +1 -1
  504. package/dist/topology/participant-directory.d.ts +26 -1
  505. package/dist/topology/participant-directory.d.ts.map +1 -1
  506. package/dist/topology/peer-presence.d.ts.map +1 -1
  507. package/dist/topology/peer-settle.js +11 -0
  508. package/dist/topology/peer-settle.js.map +7 -0
  509. package/dist/topology/session-label-settings.d.ts +13 -0
  510. package/dist/topology/session-label-settings.d.ts.map +1 -0
  511. package/dist/topology/session-label.d.ts +60 -0
  512. package/dist/topology/session-label.d.ts.map +1 -0
  513. package/dist/topology/types.d.ts +27 -0
  514. package/dist/topology/types.d.ts.map +1 -1
  515. package/dist/type-error-guidance.js +1 -1
  516. package/dist/ui/controller.d.ts +1 -0
  517. package/dist/ui/controller.d.ts.map +1 -1
  518. package/dist/ui/conversation-chrome.d.ts.map +1 -1
  519. package/dist/ui/conversation-chrome.js +3 -2
  520. package/dist/ui/conversation-commands.d.ts +1 -1
  521. package/dist/ui/conversation-commands.d.ts.map +1 -1
  522. package/dist/ui/conversation-native-reader.js +2 -2
  523. package/dist/ui/conversation-selection.d.ts +4 -1
  524. package/dist/ui/conversation-selection.d.ts.map +1 -1
  525. package/dist/ui/conversation-targets.d.ts.map +1 -1
  526. package/dist/ui/conversation-targets.js +2 -2
  527. package/dist/ui/conversation.d.ts +25 -24
  528. package/dist/ui/conversation.d.ts.map +1 -1
  529. package/dist/ui/conversation.js +170 -339
  530. package/dist/ui/conversation.js.map +2 -2
  531. package/dist/ui/core-tool-render.d.ts +1 -0
  532. package/dist/ui/core-tool-render.d.ts.map +1 -1
  533. package/dist/ui/dashboard-model.d.ts.map +1 -1
  534. package/dist/ui/dashboard.d.ts.map +1 -1
  535. package/dist/ui/dashboard.js +23 -16
  536. package/dist/ui/dashboard.js.map +2 -2
  537. package/dist/ui/fabric-render.d.ts +7 -0
  538. package/dist/ui/fabric-render.d.ts.map +1 -1
  539. package/dist/ui/footer-dock.d.ts +48 -0
  540. package/dist/ui/footer-dock.d.ts.map +1 -0
  541. package/dist/ui/format.d.ts +7 -0
  542. package/dist/ui/format.d.ts.map +1 -1
  543. package/dist/ui/settings-sections-lifecycle.d.ts.map +1 -1
  544. package/dist/ui/settings-sections-presentation.d.ts.map +1 -1
  545. package/dist/ui/settings-values.d.ts +2 -1
  546. package/dist/ui/settings-values.d.ts.map +1 -1
  547. package/dist/ui/settings.js +60 -19
  548. package/dist/ui/settings.js.map +2 -2
  549. package/dist/ui/shell-hang-keys.d.ts +8 -1
  550. package/dist/ui/shell-hang-keys.d.ts.map +1 -1
  551. package/dist/ui/shell-tasks.d.ts +2 -2
  552. package/dist/ui/shell-tasks.d.ts.map +1 -1
  553. package/dist/ui/shell-tasks.js +27 -94
  554. package/dist/ui/shell-tasks.js.map +2 -2
  555. package/dist/ui/snapshot.d.ts.map +1 -1
  556. package/dist/ui/terminal-title.d.ts +41 -0
  557. package/dist/ui/terminal-title.d.ts.map +1 -0
  558. package/dist/ui/types.d.ts +4 -0
  559. package/dist/ui/types.d.ts.map +1 -1
  560. package/dist/ui/widget-keys.d.ts +5 -0
  561. package/dist/ui/widget-keys.d.ts.map +1 -0
  562. package/dist/ui/widget.d.ts +40 -18
  563. package/dist/ui/widget.d.ts.map +1 -1
  564. package/dist/ui/word-diff/line-emphasis.js +1603 -0
  565. package/dist/ui/word-diff/line-emphasis.js.map +7 -0
  566. package/dist/util.d.ts +2 -0
  567. package/dist/util.d.ts.map +1 -1
  568. package/dist/verified/authority.d.ts +2 -2
  569. package/dist/verified/authority.d.ts.map +1 -1
  570. package/dist/verified/budget.d.ts +4 -0
  571. package/dist/verified/budget.d.ts.map +1 -0
  572. package/dist/verified/generated/actor-name.d.ts +4 -0
  573. package/dist/verified/generated/actor-name.js +17 -0
  574. package/dist/verified/generated/authority.d.ts +4 -0
  575. package/dist/verified/generated/authority.js +28 -0
  576. package/dist/verified/generated/budget.d.ts +4 -0
  577. package/dist/verified/generated/budget.js +17 -0
  578. package/dist/verified/generated/compaction.d.ts +4 -0
  579. package/dist/verified/generated/compaction.js +19 -0
  580. package/dist/verified/generated/grants.d.ts +4 -0
  581. package/dist/verified/generated/grants.js +17 -0
  582. package/dist/verified/generated/lifecycle.d.ts +4 -0
  583. package/dist/verified/generated/lifecycle.js +50 -0
  584. package/dist/verified/generated/manifest.json +137 -48
  585. package/dist/verified/generated/policy.d.ts +17 -0
  586. package/dist/verified/generated/policy.js +211 -0
  587. package/dist/verified/generated/provider.d.ts +4 -0
  588. package/dist/verified/generated/provider.js +18 -0
  589. package/dist/verified/generated/resources.d.ts +6 -0
  590. package/dist/verified/generated/resources.js +73 -0
  591. package/dist/verified/generated/speculation.d.ts +6 -0
  592. package/dist/verified/generated/speculation.js +48 -0
  593. package/dist/verified/generated/storage.d.ts +4 -0
  594. package/dist/verified/generated/storage.js +18 -0
  595. package/dist/verified/grants.d.ts +22 -0
  596. package/dist/verified/grants.d.ts.map +1 -0
  597. package/dist/verified/lifecycle.d.ts +31 -0
  598. package/dist/verified/lifecycle.d.ts.map +1 -0
  599. package/dist/verified/machine.d.ts +18 -0
  600. package/dist/verified/machine.d.ts.map +1 -0
  601. package/dist/verified/memory.d.ts +1 -1
  602. package/dist/verified/memory.d.ts.map +1 -1
  603. package/dist/verified/nat.d.ts +1 -1
  604. package/dist/verified/nat.d.ts.map +1 -1
  605. package/dist/verified/policy.d.ts +17 -5
  606. package/dist/verified/policy.d.ts.map +1 -1
  607. package/dist/verified/provider.d.ts +22 -0
  608. package/dist/verified/provider.d.ts.map +1 -0
  609. package/dist/verified/resources.d.ts +21 -7
  610. package/dist/verified/resources.d.ts.map +1 -1
  611. package/dist/verified/speculation.d.ts +36 -0
  612. package/dist/verified/speculation.d.ts.map +1 -0
  613. package/dist/verified/storage.d.ts.map +1 -1
  614. package/dist/worker/missing-install.d.ts +8 -0
  615. package/dist/worker/missing-install.d.ts.map +1 -0
  616. package/dist/worker/options.d.ts.map +1 -1
  617. package/dist/worker/options.js +25 -0
  618. package/dist/worker/options.js.map +2 -2
  619. package/dist/worker/prompt-lifecycle.d.ts +16 -0
  620. package/dist/worker/prompt-lifecycle.d.ts.map +1 -0
  621. package/dist/worker/prompt-lifecycle.js +90 -0
  622. package/dist/worker/prompt-lifecycle.js.map +7 -0
  623. package/dist/worker/questions.d.ts +15 -3
  624. package/dist/worker/questions.d.ts.map +1 -1
  625. package/dist/worker/questions.js +53 -8
  626. package/dist/worker/questions.js.map +2 -2
  627. package/dist/worker/recovery-watchdog.d.ts +22 -0
  628. package/dist/worker/recovery-watchdog.d.ts.map +1 -1
  629. package/dist/worker/recovery-watchdog.js +116 -1
  630. package/dist/worker/recovery-watchdog.js.map +2 -2
  631. package/dist/worker/result.js +1 -1
  632. package/dist/worker/result.js.map +2 -2
  633. package/dist/worker.js +131 -21
  634. package/dist/worker.js.map +2 -2
  635. package/docs/actor-name-policy-handoff.md +5 -0
  636. package/docs/agents.md +172 -22
  637. package/docs/architecture.md +5 -1
  638. package/docs/audit-trace.md +2 -1
  639. package/docs/background-tasks.md +126 -28
  640. package/docs/codemode-parity.md +2 -2
  641. package/docs/compaction.md +21 -5
  642. package/docs/components.md +1 -1
  643. package/docs/configuration.md +113 -66
  644. package/docs/decisions.md +92 -10
  645. package/docs/durable-extension.md +121 -0
  646. package/docs/durable-pi.md +306 -6
  647. package/docs/extractive-history.md +3 -1
  648. package/docs/interface.md +22 -17
  649. package/docs/jev.md +2 -2
  650. package/docs/kernels.md +1 -1
  651. package/{node_modules/pi-coralbricks-provider/LICENSE → docs/licenses/gdp-wired-mit.txt} +1 -1
  652. package/docs/managed-host-migration.md +50 -0
  653. package/docs/programmatic-compaction.md +216 -6
  654. package/docs/programs.md +23 -1
  655. package/docs/prompt-cache.md +4 -2
  656. package/docs/provider-capabilities.md +15 -14
  657. package/docs/providers.md +99 -3
  658. package/docs/shell-composition.md +15 -0
  659. package/docs/short-lock-protocol.md +90 -0
  660. package/docs/skills.md +5 -1
  661. package/docs/speculation.md +6 -0
  662. package/docs/verified-kernels.md +309 -220
  663. package/package.json +45 -24
  664. package/proofs/actor-name.ts +27 -0
  665. package/proofs/authority.ts +62 -0
  666. package/proofs/budget.ts +24 -0
  667. package/proofs/compaction.ts +51 -0
  668. package/proofs/grants.ts +39 -0
  669. package/proofs/index.ts +40 -0
  670. package/proofs/kernel.ts +44 -0
  671. package/proofs/lifecycle.ts +128 -0
  672. package/proofs/policy.ts +195 -0
  673. package/proofs/provider.ts +52 -0
  674. package/proofs/resources.ts +160 -0
  675. package/proofs/speculation.ts +69 -0
  676. package/proofs/storage.ts +66 -0
  677. package/scripts/verified-kernels.ts +141 -0
  678. package/skillsets/python/fabric-council/SKILL.md +94 -20
  679. package/skillsets/python/fabric-exec/SKILL.md +2 -2
  680. package/skillsets/python/fabric-exec/references/agents.md +10 -4
  681. package/skillsets/python/fabric-fusion/SKILL.md +1 -1
  682. package/skillsets/python/fabric-guide/SKILL.md +1 -1
  683. package/skillsets/typescript/fabric-council/SKILL.md +110 -22
  684. package/skillsets/typescript/fabric-exec/SKILL.md +7 -7
  685. package/skillsets/typescript/fabric-exec/references/agents.md +17 -8
  686. package/skillsets/typescript/fabric-fusion/SKILL.md +1 -1
  687. package/skillsets/typescript/fabric-guide/SKILL.md +1 -1
  688. package/LAWS.bend +0 -502
  689. package/PROOF.bend +0 -452
  690. package/dist/chunks/chunk-3UGN25XS.js.map +0 -7
  691. package/dist/chunks/chunk-4EW7GVUR.js.map +0 -7
  692. package/dist/chunks/chunk-5UBRGTVN.js.map +0 -7
  693. package/dist/chunks/chunk-BN7F52EG.js +0 -525
  694. package/dist/chunks/chunk-BN7F52EG.js.map +0 -7
  695. package/dist/chunks/chunk-C7Z6F3SO.js.map +0 -7
  696. package/dist/chunks/chunk-DK35W6U7.js +0 -259
  697. package/dist/chunks/chunk-DK35W6U7.js.map +0 -7
  698. package/dist/chunks/chunk-EFETPXU2.js.map +0 -7
  699. package/dist/chunks/chunk-EHQQ4KCX.js.map +0 -7
  700. package/dist/chunks/chunk-EKODKR6Y.js.map +0 -7
  701. package/dist/chunks/chunk-FE6NOAO7.js.map +0 -7
  702. package/dist/chunks/chunk-FIDUHKMM.js.map +0 -7
  703. package/dist/chunks/chunk-FSB2VIRZ.js.map +0 -7
  704. package/dist/chunks/chunk-GIK2WNAK.js.map +0 -7
  705. package/dist/chunks/chunk-GO32KSEZ.js.map +0 -7
  706. package/dist/chunks/chunk-IR3PIHJM.js.map +0 -7
  707. package/dist/chunks/chunk-ITVLKXCI.js +0 -266
  708. package/dist/chunks/chunk-ITVLKXCI.js.map +0 -7
  709. package/dist/chunks/chunk-K7J2ABAZ.js.map +0 -7
  710. package/dist/chunks/chunk-KJZAOENY.js +0 -212
  711. package/dist/chunks/chunk-KJZAOENY.js.map +0 -7
  712. package/dist/chunks/chunk-LNASO4VT.js.map +0 -7
  713. package/dist/chunks/chunk-MLLYR3Y6.js.map +0 -7
  714. package/dist/chunks/chunk-P4KH4S4S.js.map +0 -7
  715. package/dist/chunks/chunk-PK4NIJEV.js.map +0 -7
  716. package/dist/chunks/chunk-Q2JQ3RYZ.js +0 -99
  717. package/dist/chunks/chunk-Q2JQ3RYZ.js.map +0 -7
  718. package/dist/chunks/chunk-R2XQ6AHT.js.map +0 -7
  719. package/dist/chunks/chunk-ROTCDDOV.js.map +0 -7
  720. package/dist/chunks/chunk-SPCJXN4K.js.map +0 -7
  721. package/dist/chunks/chunk-U366I5K2.js.map +0 -7
  722. package/dist/chunks/chunk-UKMQK5VP.js +0 -231
  723. package/dist/chunks/chunk-UKMQK5VP.js.map +0 -7
  724. package/dist/chunks/chunk-UOM37PE4.js.map +0 -7
  725. package/dist/chunks/chunk-UTOBAZ5T.js.map +0 -7
  726. package/dist/chunks/chunk-VSDUSNIA.js.map +0 -7
  727. package/dist/chunks/chunk-VTK2FEH7.js +0 -229
  728. package/dist/chunks/chunk-VTK2FEH7.js.map +0 -7
  729. package/dist/chunks/chunk-VYQV5JRT.js.map +0 -7
  730. package/dist/chunks/chunk-XCEEQ5AB.js.map +0 -7
  731. package/dist/chunks/chunk-ZLNJDTCN.js +0 -226
  732. package/dist/chunks/chunk-ZLNJDTCN.js.map +0 -7
  733. package/dist/chunks/chunk-ZQMBS5SH.js.map +0 -7
  734. package/dist/ui/conversation-shortcut.d.ts +0 -3
  735. package/dist/ui/conversation-shortcut.d.ts.map +0 -1
  736. package/dist/ui/widget-activity.d.ts +0 -21
  737. package/dist/ui/widget-activity.d.ts.map +0 -1
  738. package/dist/verified/generated/authority-kernel.d.ts +0 -10
  739. package/dist/verified/generated/authority-kernel.js +0 -127
  740. package/dist/verified/generated/kernel.d.ts +0 -31
  741. package/dist/verified/generated/kernel.js +0 -389
  742. package/dist/verified/generated/lifecycle-kernel.d.ts +0 -7
  743. package/dist/verified/generated/lifecycle-kernel.js +0 -164
  744. package/dist/verified/generated/provider-kernel.d.ts +0 -9
  745. package/dist/verified/generated/provider-kernel.js +0 -87
  746. package/dist/verified/generated/storage-kernel.d.ts +0 -11
  747. package/dist/verified/generated/storage-kernel.js +0 -107
  748. package/docs/licenses/bend-apache-2.0.txt +0 -202
  749. package/node_modules/pi-coralbricks-provider/README.md +0 -306
  750. package/node_modules/pi-coralbricks-provider/auth.ts +0 -30
  751. package/node_modules/pi-coralbricks-provider/custom-models.json +0 -1
  752. package/node_modules/pi-coralbricks-provider/deprecated-models.json +0 -1
  753. package/node_modules/pi-coralbricks-provider/guard.ts +0 -155
  754. package/node_modules/pi-coralbricks-provider/index.ts +0 -662
  755. package/node_modules/pi-coralbricks-provider/models.json +0 -88
  756. package/node_modules/pi-coralbricks-provider/package.json +0 -74
  757. package/node_modules/pi-coralbricks-provider/park.ts +0 -122
  758. package/node_modules/pi-coralbricks-provider/patch.json +0 -34
  759. package/node_modules/pi-coralbricks-provider/scripts/update-models.js +0 -658
  760. package/node_modules/pi-coralbricks-provider/settings.ts +0 -143
  761. package/node_modules/pi-coralbricks-provider/sync-policy.ts +0 -309
  762. package/proofs/abi.json +0 -308
  763. package/proofs/authority-abi.json +0 -7
  764. package/proofs/authority-kernel.bend +0 -23
  765. package/proofs/authority-proof.bend +0 -74
  766. package/proofs/authority-spec.bend +0 -30
  767. package/proofs/authority-state.bend +0 -43
  768. package/proofs/authority-types.d.ts +0 -3
  769. package/proofs/kernel.bend +0 -139
  770. package/proofs/lifecycle-abi.json +0 -3
  771. package/proofs/lifecycle-kernel.bend +0 -11
  772. package/proofs/lifecycle-proof.bend +0 -249
  773. package/proofs/lifecycle-spec.bend +0 -261
  774. package/proofs/lifecycle-types.d.ts +0 -4
  775. package/proofs/lifecycle.bend +0 -119
  776. package/proofs/provider-abi.json +0 -4
  777. package/proofs/provider-kernel.bend +0 -14
  778. package/proofs/provider-plans.bend +0 -28
  779. package/proofs/provider-spec.bend +0 -14
  780. package/proofs/provider-types.d.ts +0 -5
  781. package/proofs/resource-proof.bend +0 -633
  782. package/proofs/resource-spec.bend +0 -133
  783. package/proofs/resources.bend +0 -160
  784. package/proofs/state-kernel.bend +0 -17
  785. package/proofs/state-plans.bend +0 -40
  786. package/proofs/state-proof.bend +0 -42
  787. package/proofs/state-spec.bend +0 -26
  788. package/proofs/storage-abi.json +0 -3
  789. package/proofs/storage-kernel.bend +0 -11
  790. package/proofs/storage-plans.bend +0 -100
  791. package/proofs/storage-proof.bend +0 -176
  792. package/proofs/storage-spec.bend +0 -70
  793. package/proofs/storage-types.d.ts +0 -8
  794. package/proofs/types.d.ts +0 -7
  795. package/scripts/test-verified-kernels.mjs +0 -107
  796. package/scripts/verified-kernels.mjs +0 -176
  797. /package/dist/chunks/{chunk-ZEXCKK4K.js.map → chunk-4WKD3YM3.js.map} +0 -0
  798. /package/dist/chunks/{chunk-5XBYFSI5.js.map → chunk-7YNE4NB2.js.map} +0 -0
  799. /package/dist/chunks/{chunk-K6QXUGS5.js.map → chunk-BMAEZNZ5.js.map} +0 -0
  800. /package/dist/chunks/{chunk-CCHZXF6K.js.map → chunk-CXYJJ3HZ.js.map} +0 -0
  801. /package/dist/chunks/{chunk-TIIIHPHF.js.map → chunk-GS67KDMV.js.map} +0 -0
  802. /package/dist/chunks/{chunk-D5NYNIST.js.map → chunk-H57KPL3V.js.map} +0 -0
  803. /package/dist/chunks/{chunk-INRXG4J5.js.map → chunk-HGD75NZY.js.map} +0 -0
  804. /package/dist/chunks/{chunk-UXIBKMUM.js.map → chunk-KIFOEBYJ.js.map} +0 -0
  805. /package/dist/chunks/{chunk-3FJUP3GV.js.map → chunk-L6H46CPY.js.map} +0 -0
  806. /package/dist/chunks/{chunk-FUY6XVRX.js.map → chunk-MPMEK3IQ.js.map} +0 -0
  807. /package/dist/chunks/{chunk-HP5P7NBO.js.map → chunk-MSDL7U6Q.js.map} +0 -0
  808. /package/dist/chunks/{chunk-ASSLHWZS.js.map → chunk-MX53BRAC.js.map} +0 -0
  809. /package/dist/chunks/{chunk-QT4W5YVB.js.map → chunk-RAA3FAYZ.js.map} +0 -0
  810. /package/dist/chunks/{chunk-53N2I4QA.js.map → chunk-TXCNZCZP.js.map} +0 -0
  811. /package/dist/chunks/{chunk-LEU5CDSL.js.map → chunk-XFOSUGLU.js.map} +0 -0
@@ -9,6 +9,13 @@ import {
9
9
  spawnDetached,
10
10
  workerCommand
11
11
  } from "./chunk-SVDHQUTM.js";
12
+ import {
13
+ isInside,
14
+ readWritePolicy
15
+ } from "./chunk-2USMWEE6.js";
16
+ import {
17
+ loadHostSdk
18
+ } from "./chunk-RLKRZXSX.js";
12
19
  import {
13
20
  discoverClaudeModels,
14
21
  mapClaudeTools,
@@ -19,12 +26,15 @@ import {
19
26
  normalizeVedaModel
20
27
  } from "./chunk-VPPIJRNZ.js";
21
28
  import {
22
- isInside,
23
- readWritePolicy
24
- } from "./chunk-2USMWEE6.js";
29
+ peerLabelPrefix
30
+ } from "./chunk-W5FEHVZA.js";
25
31
  import {
26
- loadHostSdk
27
- } from "./chunk-WJJXODAB.js";
32
+ herdrSocketRequest
33
+ } from "./chunk-JMUUNW2H.js";
34
+ import {
35
+ compileFabricSummary,
36
+ rawContextTokens
37
+ } from "./chunk-3XT5WHSG.js";
28
38
  import {
29
39
  launchScope,
30
40
  normalizeScope,
@@ -33,43 +43,43 @@ import {
33
43
  senderTrusted
34
44
  } from "./chunk-JKQARSWR.js";
35
45
  import {
36
- peerLabelPrefix,
37
- readChildToolAllowlist
38
- } from "./chunk-PYFJW3HC.js";
39
- import {
40
- resolveAgentDir
41
- } from "./chunk-PBDDXBHY.js";
46
+ isModelPinFailure
47
+ } from "./chunk-UD7LFV43.js";
42
48
  import {
43
49
  ownedStat,
44
50
  processAlive
45
- } from "./chunk-5XBYFSI5.js";
51
+ } from "./chunk-7YNE4NB2.js";
52
+ import {
53
+ resolveAgentDir
54
+ } from "./chunk-PBDDXBHY.js";
46
55
  import {
47
56
  DEFAULT_FABRIC_CONFIG,
48
57
  MAX_AGENT_TIMEOUT_MS,
49
58
  MIN_AGENT_TIMEOUT_MS
50
- } from "./chunk-K7J2ABAZ.js";
59
+ } from "./chunk-LRSZFYUC.js";
51
60
  import {
52
61
  readJsonlPage
53
62
  } from "./chunk-CGPK5WHX.js";
54
63
  import {
55
- compileFabricSummary,
56
- rawContextTokens
57
- } from "./chunk-ROTCDDOV.js";
58
- import {
59
- SHORT_LOCK_MAX_HOLD_MS,
60
- encodeOwnerIdentityLine,
61
- lockOwnerLiveness,
64
+ formatShortLockOwner,
62
65
  ownerHeartbeatFields,
63
66
  ownerIdentityFields,
64
67
  ownerLiveness,
68
+ reapStaleShortLock,
65
69
  recordOwnerLiveness,
70
+ releaseShortLock,
71
+ tryAcquireShortLock,
66
72
  writeJsonAtomic
67
- } from "./chunk-ITVLKXCI.js";
73
+ } from "./chunk-F6A6MQ6G.js";
74
+ import {
75
+ FABRIC_PEER_LABEL_SEQUENCE
76
+ } from "./chunk-2RWNVCFD.js";
68
77
  import {
69
78
  AgentAdmission,
70
79
  FABRIC_LIFECYCLE_SUBSCRIPTION_PREFIX,
71
80
  FABRIC_PARTICIPANT_LIFECYCLE_TOPIC,
72
81
  assertAgentTask,
82
+ assertExactModelRequest,
73
83
  beginAgentSettlement,
74
84
  createAgentLifecycle,
75
85
  finishAgentSettlement,
@@ -79,7 +89,14 @@ import {
79
89
  lifecycleSubscriptionFromValue,
80
90
  terminalAgentStatuses,
81
91
  tokenUsagePayloadFromValue
82
- } from "./chunk-KJZAOENY.js";
92
+ } from "./chunk-V4OW2ULC.js";
93
+ import {
94
+ validateAgentResult
95
+ } from "./chunk-GJVKEHDL.js";
96
+ import {
97
+ compactionRequestBoundsError,
98
+ encodeCompactionRequest
99
+ } from "./chunk-HGD75NZY.js";
83
100
  import {
84
101
  FABRIC_ACTOR_HOST_EVENTS
85
102
  } from "./chunk-IIPKG52D.js";
@@ -89,16 +106,20 @@ import {
89
106
  isFabricThinking,
90
107
  serializeThinkingBounds
91
108
  } from "./chunk-V73NIH6B.js";
92
- import {
93
- compactionRequestBoundsError,
94
- encodeCompactionRequest
95
- } from "./chunk-INRXG4J5.js";
96
109
  import {
97
110
  BUILT_IN_RUNNER_IDS,
98
111
  getAgentRunner,
99
112
  isFabricRunnerId,
100
113
  requireAgentRunner
101
114
  } from "./chunk-6QVQXGMR.js";
115
+ import {
116
+ freshEntryId,
117
+ workerRoleEntry
118
+ } from "./chunk-5QJFDKPN.js";
119
+ import {
120
+ constrainChildToolSelection,
121
+ readChildToolAllowlist
122
+ } from "./chunk-6OGYPHNQ.js";
102
123
 
103
124
  // src/core/model-usage.ts
104
125
  import { readFileSync } from "node:fs";
@@ -283,10 +304,10 @@ function appendBudgetLedger(file, entry) {
283
304
  }
284
305
 
285
306
  // src/agents/manager.ts
286
- import { randomUUID as randomUUID5 } from "node:crypto";
287
- import fs11 from "node:fs";
307
+ import { randomUUID as randomUUID6 } from "node:crypto";
308
+ import fs13 from "node:fs";
288
309
  import os3 from "node:os";
289
- import path12 from "node:path";
310
+ import path14 from "node:path";
290
311
  import { fileURLToPath } from "node:url";
291
312
 
292
313
  // src/agents/hosted-run.ts
@@ -354,6 +375,8 @@ var readHostedRunState = (filePath) => {
354
375
  };
355
376
  var boundedText = (value, max) => value.length <= max ? value : value.slice(-max);
356
377
  var questionText = (value, max) => typeof value === "string" ? value.slice(0, max) : void 0;
378
+ var unanswered = () => new Promise(() => {
379
+ });
357
380
  var HostedRun = class _HostedRun {
358
381
  constructor(adapter, locator, context, files, record, hooks) {
359
382
  this.adapter = adapter;
@@ -385,7 +408,9 @@ var HostedRun = class _HostedRun {
385
408
  #released = false;
386
409
  #detached = false;
387
410
  #shutdown = false;
388
- #pendingQuestions = 0;
411
+ /** Routed questions in flight, oldest first, with the decision backing each once raised. */
412
+ #questions = [];
413
+ #blockedSince;
389
414
  #deliveries = Promise.resolve();
390
415
  lastLiveness = "running";
391
416
  reporter;
@@ -393,14 +418,27 @@ var HostedRun = class _HostedRun {
393
418
  static async prepare(adapter, context, files, record, hooks) {
394
419
  const locator = checkedLocator(adapter.id, await withTimeout(() => adapter.prepare(context), `${adapter.id}.prepare`));
395
420
  const run = new _HostedRun(adapter, locator, context, files, { ...record, hosted: { locator } }, hooks);
396
- const state = { version: 1, runner: adapter.id, locator, context };
421
+ const state = {
422
+ version: 1,
423
+ runner: adapter.id,
424
+ locator,
425
+ context,
426
+ ...hooks.holdQuestions ? { holdQuestions: true } : {}
427
+ };
397
428
  writeJsonAtomic(files.stateFile, state, { space: 2 });
398
429
  run.#write();
399
430
  return run;
400
431
  }
401
- /** Rebuild a run persisted by `prepare`; never calls `start`. */
432
+ /**
433
+ * Rebuild a run persisted by `prepare`; never calls `start`. No question is
434
+ * routed through this host yet, so a `blockedOn` left by an earlier host is
435
+ * dropped; the runner asks again through the new reporter.
436
+ */
402
437
  static recover(adapter, state, files, record, hooks) {
403
- return new _HostedRun(adapter, state.locator, state.context, files, { ...record, hosted: { locator: state.locator } }, hooks);
438
+ const { blockedOn, ...rest } = record;
439
+ const run = new _HostedRun(adapter, state.locator, state.context, files, { ...rest, hosted: { locator: state.locator } }, hooks);
440
+ if (blockedOn) run.#write();
441
+ return run;
404
442
  }
405
443
  get record() {
406
444
  return this.#record;
@@ -474,8 +512,17 @@ var HostedRun = class _HostedRun {
474
512
  this.#settle({ status: "failed", error });
475
513
  this.#closed = true;
476
514
  }
477
- /** Keep the remote run alive and stop observing it; recovery re-attaches. */
515
+ /**
516
+ * Keep the remote run alive and stop observing it; recovery re-attaches. The
517
+ * manager cancels the decisions behind open questions, so the record stops
518
+ * naming one. Pending and later `question` calls never settle: the runner
519
+ * sees no answer and asks again through the next host's reporter.
520
+ */
478
521
  detach() {
522
+ if (!this.#closed && !this.terminal && this.#record.blockedOn?.decisionId) {
523
+ this.#record.blockedOn = { since: this.#record.blockedOn.since };
524
+ this.#write();
525
+ }
479
526
  this.#closed = true;
480
527
  this.#released = true;
481
528
  this.#detached = true;
@@ -576,20 +623,19 @@ var HostedRun = class _HostedRun {
576
623
  }
577
624
  const options = Array.isArray(question.options) ? question.options.filter((option) => typeof option === "string").slice(0, MAX_QUESTION_OPTIONS) : void 0;
578
625
  if (method === "select" && !options?.length) throw new Error("A select question needs options");
626
+ if (this.#detached) return unanswered();
579
627
  if (this.#closed || this.terminal || !this.hooks.ask) return { cancelled: true };
580
- const timeout = Math.min(
581
- typeof question.timeoutMs === "number" && question.timeoutMs > 0 ? Math.floor(question.timeoutMs) : this.hooks.questionTimeoutMs,
582
- MAX_QUESTION_TIMEOUT_MS
583
- );
628
+ const requested = typeof question.timeoutMs === "number" && question.timeoutMs > 0 ? Math.floor(question.timeoutMs) : void 0;
629
+ const hold = this.hooks.holdQuestions === true && requested === void 0;
630
+ const timeout = hold ? MAX_QUESTION_TIMEOUT_MS : Math.min(requested ?? this.hooks.questionTimeoutMs, MAX_QUESTION_TIMEOUT_MS);
584
631
  const messageText = questionText(question.message, MAX_QUESTION_TEXT_CHARS);
585
632
  const placeholder = questionText(question.placeholder, MAX_QUESTION_TEXT_CHARS);
586
633
  const prefill = questionText(question.prefill, MAX_QUESTION_TEXT_CHARS);
587
- if (this.#pendingQuestions++ === 0) {
588
- this.#record.blockedOn = { since: Date.now() };
589
- this.#write();
590
- }
634
+ const pending = {};
635
+ this.#questions.push(pending);
636
+ this.#writeBlockedOn();
591
637
  try {
592
- const response = await withTimeout(() => this.hooks.ask({
638
+ const ask = () => this.hooks.ask({
593
639
  requestId: randomUUID2(),
594
640
  method,
595
641
  title: questionText(question.title, MAX_QUESTION_TITLE_CHARS) ?? "",
@@ -597,39 +643,82 @@ var HostedRun = class _HostedRun {
597
643
  ...options ? { options } : {},
598
644
  ...placeholder !== void 0 ? { placeholder } : {},
599
645
  ...prefill !== void 0 ? { prefill } : {},
600
- timeout
601
- }), "Hosted runner question", timeout + 1e3).catch(() => ({ cancelled: true }));
646
+ timeout,
647
+ ...hold ? { hold: true } : {}
648
+ }, (decisionId) => {
649
+ pending.decisionId = decisionId;
650
+ this.#writeBlockedOn();
651
+ });
652
+ const response = await (hold ? ask() : withTimeout(ask, "Hosted runner question", timeout + 1e3)).catch(() => ({ cancelled: true }));
653
+ if (this.#detached) return unanswered();
602
654
  if (method === "confirm") return "confirmed" in response ? response : { cancelled: true };
603
655
  if (!("value" in response) || method === "select" && !options.includes(response.value)) {
604
656
  return { cancelled: true };
605
657
  }
606
658
  return response;
607
659
  } finally {
608
- if (--this.#pendingQuestions === 0 && !this.#closed && !this.terminal) {
609
- delete this.#record.blockedOn;
610
- this.#write();
611
- }
660
+ this.#questions.splice(this.#questions.indexOf(pending), 1);
661
+ this.#writeBlockedOn();
662
+ }
663
+ }
664
+ /**
665
+ * `blockedOn` while any routed question is open: `since` the first opened, and
666
+ * the decision of the oldest question that has one. Written only on change.
667
+ */
668
+ #writeBlockedOn() {
669
+ if (this.#closed || this.terminal) return;
670
+ const current = this.#record.blockedOn;
671
+ if (this.#questions.length === 0) {
672
+ this.#blockedSince = void 0;
673
+ if (!current) return;
674
+ delete this.#record.blockedOn;
675
+ this.#write();
676
+ return;
612
677
  }
678
+ this.#blockedSince ??= Date.now();
679
+ const decisionId = this.#questions.find((question) => question.decisionId)?.decisionId;
680
+ if (current?.since === this.#blockedSince && current.decisionId === decisionId) return;
681
+ this.#record.blockedOn = { since: this.#blockedSince, ...decisionId ? { decisionId } : {} };
682
+ this.#write();
613
683
  }
614
684
  #finish(result) {
615
685
  if (this.#closed || this.terminal || typeof result !== "object" || result === null) return;
616
686
  const status = result.status === "failed" || result.status === "stopped" ? result.status : "completed";
617
687
  const output = typeof result.output === "string" ? result.output : "";
618
688
  let value;
689
+ let truncated;
619
690
  if (result.structured !== void 0) {
620
691
  try {
621
692
  const serialized = JSON.stringify(result.structured);
622
- value = serialized !== void 0 && Buffer.byteLength(serialized) <= MAX_STRUCTURED_BYTES ? JSON.parse(serialized) : { fabricTruncated: true };
693
+ if (serialized !== void 0 && Buffer.byteLength(serialized) <= MAX_STRUCTURED_BYTES) {
694
+ value = JSON.parse(serialized);
695
+ } else {
696
+ truncated = `structured value was truncated at the ${MAX_STRUCTURED_BYTES}-byte limit`;
697
+ }
623
698
  } catch {
624
- value = { fabricTruncated: true };
699
+ truncated = "structured value could not be serialized as JSON and was truncated";
625
700
  }
701
+ if (truncated) value = { fabricTruncated: true };
626
702
  }
627
- this.#settle({
703
+ const settled = {
628
704
  status,
629
705
  text: output,
630
706
  ...value !== void 0 ? { value } : {},
631
707
  ...status === "completed" ? {} : { error: output.slice(0, MAX_ERROR_CHARS) || `Hosted run ${status}` }
632
- });
708
+ };
709
+ if (truncated && status === "completed" && this.context.schema) {
710
+ settled.status = "failed";
711
+ settled.error = `Structured agent output was invalid: ${truncated}`;
712
+ } else {
713
+ const fromText = settled.value === void 0;
714
+ validateAgentResult(settled, this.context.schema);
715
+ if (fromText && settled.status === "completed" && settled.value !== void 0 && Buffer.byteLength(JSON.stringify(settled.value) ?? "") > MAX_STRUCTURED_BYTES) {
716
+ settled.status = "failed";
717
+ settled.value = { fabricTruncated: true };
718
+ settled.error = `Structured agent output was invalid: value parsed from the output was truncated at the ${MAX_STRUCTURED_BYTES}-byte limit`;
719
+ }
720
+ }
721
+ this.#settle(settled);
633
722
  }
634
723
  #fail(failure) {
635
724
  if (this.#closed || this.terminal) return;
@@ -703,9 +792,189 @@ var removeTree = async (target, rm = defaultRemove) => {
703
792
  }
704
793
  };
705
794
 
706
- // src/agents/transports/herdr-transport.ts
707
- import net from "node:net";
708
- import { randomUUID as randomUUID3 } from "node:crypto";
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
+ // src/agents/transports/herdr-core-transport.ts
975
+ import { randomUUID as randomUUID4 } from "node:crypto";
976
+ import path5 from "node:path";
977
+ import fs5 from "node:fs/promises";
709
978
 
710
979
  // src/agents/constants.ts
711
980
  var AGENT_STATUS_POLL_INTERVAL_MS = 250;
@@ -715,15 +984,163 @@ var AGENT_STARTUP_RETRY_BASE_DELAY_MS = 500;
715
984
  var AGENT_RESUME_MAX_ATTEMPTS = 3;
716
985
  var AGENT_RESUME_RETRY_BASE_DELAY_MS = 1e3;
717
986
 
718
- // src/agents/transports/herdr-transport.ts
719
- var REQUEST_TIMEOUT_MS = 3e3;
720
- var MAX_RESPONSE_BYTES = 1 * 1024 * 1024;
721
- var endpointFor = (socketPath) => process.platform === "win32" ? `\\\\.\\pipe\\${socketPath}` : socketPath;
722
- var responseError = (response) => {
723
- if (!response.error) return void 0;
724
- const code = response.error.code ? `${response.error.code}: ` : "";
725
- return new Error(`Herdr API request failed: ${code}${response.error.message ?? "unknown error"}`);
987
+ // src/agents/transports/herdr-core-socket.ts
988
+ import net from "node:net";
989
+ import { randomUUID as randomUUID3 } from "node:crypto";
990
+ var HerdrCoreRpcError = class extends Error {
991
+ constructor(code, message2, kind) {
992
+ super(`Herdr Core API: ${code}: ${message2}`);
993
+ this.code = code;
994
+ this.kind = kind;
995
+ this.name = "HerdrCoreRpcError";
996
+ }
997
+ };
998
+ var herdrCoreEndpoint = (socket, platform = process.platform) => platform === "win32" && !socket.startsWith("\\\\.\\pipe\\") ? `\\\\.\\pipe\\${socket}` : socket;
999
+ var herdrCoreSocketRequest = (socketPath, method, params, options = {}) => new Promise((resolve, reject) => {
1000
+ const id = `pi-fabric:${randomUUID3()}`;
1001
+ const socket = net.createConnection(herdrCoreEndpoint(socketPath));
1002
+ const chunks = [];
1003
+ let bytes = 0;
1004
+ let settled = false;
1005
+ const finish = (error, result) => {
1006
+ if (settled) return;
1007
+ settled = true;
1008
+ clearTimeout(timer);
1009
+ socket.destroy();
1010
+ if (error) reject(error);
1011
+ else resolve(result);
1012
+ };
1013
+ const timer = setTimeout(() => finish(new Error("Herdr Core API request timed out")), options.timeoutMs ?? 5e3);
1014
+ timer.unref?.();
1015
+ socket.on("connect", () => socket.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}
1016
+ `));
1017
+ socket.on("data", (chunk) => {
1018
+ const newline = chunk.indexOf(10);
1019
+ const captured = newline < 0 ? chunk : chunk.subarray(0, newline);
1020
+ bytes += captured.length;
1021
+ if (bytes > (options.maxResponseBytes ?? 1024 * 1024)) {
1022
+ finish(new Error("Herdr Core API response exceeds byte limit"));
1023
+ return;
1024
+ }
1025
+ chunks.push(captured);
1026
+ if (newline < 0) return;
1027
+ try {
1028
+ const value = JSON.parse(Buffer.concat(chunks).toString("utf8"));
1029
+ if (!value || value.jsonrpc !== "2.0" || value.id !== id || Object.hasOwn(value, "result") === Object.hasOwn(value, "error")) {
1030
+ throw new Error("uncorrelated or invalid JSON-RPC envelope");
1031
+ }
1032
+ if (Object.hasOwn(value, "error")) {
1033
+ const error = value.error;
1034
+ if (!error || !Number.isInteger(error.code) || typeof error.message !== "string") {
1035
+ throw new Error("invalid JSON-RPC error");
1036
+ }
1037
+ finish(new HerdrCoreRpcError(
1038
+ error.code,
1039
+ error.message,
1040
+ typeof error.data?.kind === "string" ? error.data.kind : void 0
1041
+ ));
1042
+ } else finish(void 0, value.result);
1043
+ } catch (error) {
1044
+ finish(new Error(`Invalid Herdr Core API response: ${error instanceof Error ? error.message : String(error)}`));
1045
+ }
1046
+ });
1047
+ socket.on("error", (error) => finish(error));
1048
+ socket.on("end", () => finish(new Error("Herdr Core API closed without a complete response")));
1049
+ socket.on("close", () => finish(new Error("Herdr Core API socket closed")));
1050
+ });
1051
+
1052
+ // src/agents/transports/herdr-core-transport.ts
1053
+ var missing = (error) => error instanceof HerdrCoreRpcError && error.kind === "not_found";
1054
+ var terminal = (value) => {
1055
+ const result = value;
1056
+ if (!result || typeof result.address !== "string" || !/^t[0-9a-z]+$/.test(result.address) || result.state !== "live" && result.state !== "finished") {
1057
+ throw new Error("Herdr Core returned an invalid terminal");
1058
+ }
1059
+ return { address: result.address, state: result.state };
1060
+ };
1061
+ var HerdrCoreTransport = class {
1062
+ constructor(environment = process.env) {
1063
+ this.environment = environment;
1064
+ }
1065
+ kind = "herdr-core";
1066
+ async available() {
1067
+ if (!this.environment.HC_TERMINAL_ID || !this.environment.HC_TERMINAL_SOCKET) return false;
1068
+ try {
1069
+ const hello = await this.#request("hello", { generation: 1, framed: false });
1070
+ return hello?.generation === 1 && hello.framed === false && Array.isArray(hello.methods) && ["terminal.run", "terminal.get", "terminal.kill"].every((method) => hello.methods.includes(method));
1071
+ } catch {
1072
+ return false;
1073
+ }
1074
+ }
1075
+ async launch(request) {
1076
+ const caller = this.environment.HC_TERMINAL_ID;
1077
+ if (!caller) throw new Error("Herdr Core transport requires HC_TERMINAL_ID");
1078
+ 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]];
1081
+ let resolved;
1082
+ for (const directory of (this.environment.PATH ?? "").split(path5.delimiter).filter(Boolean)) {
1083
+ for (const name of names) {
1084
+ const candidate = path5.resolve(directory.replace(/^"|"$/g, ""), name);
1085
+ try {
1086
+ if ((await fs5.stat(candidate)).isFile()) {
1087
+ await fs5.access(candidate, process.platform === "win32" ? fs5.constants.F_OK : fs5.constants.X_OK);
1088
+ resolved = candidate;
1089
+ break;
1090
+ }
1091
+ } catch {
1092
+ }
1093
+ }
1094
+ if (resolved) break;
1095
+ }
1096
+ if (!resolved) throw new Error("Herdr Core could not resolve an absolute worker runtime");
1097
+ argv[0] = resolved;
1098
+ }
1099
+ const prefix = request.name.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").slice(0, 7) || "agent";
1100
+ const child = terminal(await this.#request("terminal.run", {
1101
+ argv,
1102
+ cwd: request.cwd,
1103
+ name: `${prefix}-${randomUUID4().replaceAll("-", "").slice(0, 24)}`,
1104
+ caller,
1105
+ parent: caller,
1106
+ no_notify: true,
1107
+ wait: false,
1108
+ keep: false,
1109
+ outlive_parent: false
1110
+ }));
1111
+ const params = { terminal: child.address, caller };
1112
+ return {
1113
+ kind: this.kind,
1114
+ sessionId: child.address,
1115
+ attachCommand: `hc attach ${child.address}`,
1116
+ livenessPollIntervalMs: EXTERNAL_TRANSPORT_LIVENESS_POLL_INTERVAL_MS,
1117
+ isAlive: async () => {
1118
+ try {
1119
+ const current = terminal(await this.#request("terminal.get", params));
1120
+ if (current.address !== child.address) throw new Error("Herdr Core terminal address changed");
1121
+ return current.state === "live";
1122
+ } catch (error) {
1123
+ if (missing(error)) return false;
1124
+ throw error;
1125
+ }
1126
+ },
1127
+ stop: async () => {
1128
+ try {
1129
+ await this.#request("terminal.kill", params);
1130
+ } catch (error) {
1131
+ if (!missing(error)) throw error;
1132
+ }
1133
+ }
1134
+ };
1135
+ }
1136
+ #request(method, params) {
1137
+ const socket = this.environment.HC_TERMINAL_SOCKET;
1138
+ if (!socket) return Promise.reject(new Error("Herdr Core transport requires HC_TERMINAL_SOCKET"));
1139
+ return herdrCoreSocketRequest(socket, method, params);
1140
+ }
726
1141
  };
1142
+
1143
+ // src/agents/transports/herdr-transport.ts
727
1144
  var HerdrTransport = class {
728
1145
  constructor(environment = process.env) {
729
1146
  this.environment = environment;
@@ -792,54 +1209,7 @@ var HerdrTransport = class {
792
1209
  };
793
1210
  }
794
1211
  #request(request) {
795
- const socketPath = this.environment.HERDR_SOCKET_PATH;
796
- if (!socketPath) return Promise.reject(new Error("Herdr transport requires HERDR_SOCKET_PATH"));
797
- const payload = JSON.stringify({ id: `pi-fabric:${randomUUID3()}`, ...request });
798
- return new Promise((resolve, reject) => {
799
- const socket = net.createConnection(endpointFor(socketPath));
800
- const responseChunks = [];
801
- let responseBytes = 0;
802
- let settled = false;
803
- const finish = (error, value) => {
804
- if (settled) return;
805
- settled = true;
806
- clearTimeout(timeout);
807
- socket.destroy();
808
- if (error) reject(error);
809
- else resolve(value);
810
- };
811
- const timeout = setTimeout(
812
- () => finish(new Error(`Herdr API request timed out after ${REQUEST_TIMEOUT_MS}ms`)),
813
- REQUEST_TIMEOUT_MS
814
- );
815
- timeout.unref?.();
816
- socket.setEncoding("utf8");
817
- socket.on("connect", () => socket.write(`${payload}
818
- `));
819
- socket.on("data", (chunk) => {
820
- const newline = chunk.indexOf("\n");
821
- const captured = newline < 0 ? chunk : chunk.slice(0, newline);
822
- responseBytes += Buffer.byteLength(captured, "utf8");
823
- if (responseBytes > MAX_RESPONSE_BYTES) {
824
- finish(new Error(`Herdr API response exceeds ${MAX_RESPONSE_BYTES} bytes`));
825
- return;
826
- }
827
- responseChunks.push(captured);
828
- if (newline < 0) return;
829
- try {
830
- const response = JSON.parse(responseChunks.join(""));
831
- finish(responseError(response), response);
832
- } catch (error) {
833
- finish(
834
- new Error(
835
- `Invalid Herdr API response: ${error instanceof Error ? error.message : String(error)}`
836
- )
837
- );
838
- }
839
- });
840
- socket.on("error", (error) => finish(error));
841
- socket.on("end", () => finish(new Error("Herdr API closed without a response")));
842
- });
1212
+ return herdrSocketRequest(this.environment.HERDR_SOCKET_PATH, request, "Herdr transport");
843
1213
  }
844
1214
  };
845
1215
 
@@ -992,16 +1362,16 @@ var TmuxTransport = class {
992
1362
  };
993
1363
 
994
1364
  // src/agents/worktree-manager.ts
995
- import fs7 from "node:fs";
996
- import path7 from "node:path";
1365
+ import fs9 from "node:fs";
1366
+ import path9 from "node:path";
997
1367
 
998
1368
  // src/agents/clone-first-worktree.ts
999
- import fs6 from "node:fs";
1000
- import path6 from "node:path";
1369
+ import fs8 from "node:fs";
1370
+ import path8 from "node:path";
1001
1371
 
1002
1372
  // src/agents/cow-clone.ts
1003
- import fs4 from "node:fs";
1004
- import path4 from "node:path";
1373
+ import fs6 from "node:fs";
1374
+ import path6 from "node:path";
1005
1375
  var CLONE_SKIP_PREFIXES = [".git", ".pi/fabric/worktrees"];
1006
1376
  var CowUnavailableError = class extends Error {
1007
1377
  constructor(message2, options) {
@@ -1013,15 +1383,15 @@ var posixRel = (value) => value.replaceAll("\\", "/");
1013
1383
  var isCowUnavailable = (error) => {
1014
1384
  if (typeof error !== "object" || error === null || !("code" in error)) return false;
1015
1385
  const code = error.code;
1016
- return code === "ENOTSUP" || code === "EOPNOTSUPP" || code === "EXDEV" || code === "ENOTSUPP";
1386
+ return code === "ENOTSUP" || code === "EOPNOTSUPP" || code === "EXDEV" || code === "ENOTSUPP" || code === "ENOSYS" || code === "ENOTTY";
1017
1387
  };
1018
1388
  var cloneEntry = async (from, to) => {
1019
1389
  try {
1020
- await fs4.promises.cp(from, to, {
1390
+ await fs6.promises.cp(from, to, {
1021
1391
  recursive: true,
1022
1392
  verbatimSymlinks: true,
1023
1393
  force: false,
1024
- mode: fs4.constants.COPYFILE_FICLONE_FORCE
1394
+ mode: fs6.constants.COPYFILE_FICLONE_FORCE
1025
1395
  });
1026
1396
  } catch (error) {
1027
1397
  if (isCowUnavailable(error)) {
@@ -1041,13 +1411,13 @@ var hasNestedSkip = (rel, prefixes) => {
1041
1411
  return prefixes.some((prefix) => prefix.startsWith(`${value}/`));
1042
1412
  };
1043
1413
  var cloneLevel = async (source, dest, relBase, prefixes) => {
1044
- await fs4.promises.mkdir(dest, { recursive: true });
1045
- const entries = await fs4.promises.readdir(source, { withFileTypes: true });
1414
+ await fs6.promises.mkdir(dest, { recursive: true });
1415
+ const entries = await fs6.promises.readdir(source, { withFileTypes: true });
1046
1416
  for (const entry of entries) {
1047
1417
  const rel = relBase ? `${relBase}/${entry.name}` : entry.name;
1048
1418
  if (skipped(rel, prefixes)) continue;
1049
- const from = path4.join(source, entry.name);
1050
- const to = path4.join(dest, entry.name);
1419
+ const from = path6.join(source, entry.name);
1420
+ const to = path6.join(dest, entry.name);
1051
1421
  if (entry.isDirectory() && !entry.isSymbolicLink() && hasNestedSkip(rel, prefixes)) {
1052
1422
  await cloneLevel(from, to, rel, prefixes);
1053
1423
  continue;
@@ -1057,15 +1427,20 @@ var cloneLevel = async (source, dest, relBase, prefixes) => {
1057
1427
  }
1058
1428
  };
1059
1429
  var cloneTree = async (source, dest, prefixes = CLONE_SKIP_PREFIXES) => {
1060
- await cloneLevel(source, dest, "", 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);
1433
+ if (!relativeDest) throw new Error("Cannot clone a tree into itself");
1434
+ const inside = relativeDest !== ".." && !relativeDest.startsWith(`..${path6.sep}`) && !path6.isAbsolute(relativeDest);
1435
+ await cloneLevel(realSource, realDest, "", inside ? [...prefixes, posixRel(relativeDest)] : prefixes);
1061
1436
  };
1062
1437
 
1063
1438
  // src/agents/worktree-paths.ts
1064
- import fs5 from "node:fs";
1065
- import path5 from "node:path";
1439
+ import fs7 from "node:fs";
1440
+ import path7 from "node:path";
1066
1441
  var FABRIC_WORKTREE_SEGMENTS = [".pi", "fabric", "worktrees"];
1067
1442
  var FABRIC_WORKTREE_EXCLUDE = ".pi/fabric/worktrees/";
1068
- var fabricWorktreePath = (gitRoot, id) => path5.join(gitRoot, ...FABRIC_WORKTREE_SEGMENTS, id);
1443
+ var fabricWorktreePath = (gitRoot, id) => path7.join(gitRoot, ...FABRIC_WORKTREE_SEGMENTS, id);
1069
1444
  var isFabricWorktreePath = (worktree, id) => {
1070
1445
  const parts = worktree.split(/[\\/]/).filter(Boolean);
1071
1446
  return parts.length >= 4 && parts.at(-1) === id && parts.at(-2) === "worktrees" && parts.at(-3) === "fabric" && parts.at(-4) === ".pi";
@@ -1075,11 +1450,11 @@ var ensureWorktreeExclude = async (gitRoot) => {
1075
1450
  cwd: gitRoot,
1076
1451
  timeoutMs: 1e4
1077
1452
  });
1078
- const excludePath = path5.resolve(gitRoot, located.stdout.trim());
1079
- fs5.mkdirSync(path5.dirname(excludePath), { recursive: true });
1453
+ const excludePath = path7.resolve(gitRoot, located.stdout.trim());
1454
+ fs7.mkdirSync(path7.dirname(excludePath), { recursive: true });
1080
1455
  let current = "";
1081
1456
  try {
1082
- current = fs5.readFileSync(excludePath, "utf8");
1457
+ current = fs7.readFileSync(excludePath, "utf8");
1083
1458
  } catch (error) {
1084
1459
  const code = error instanceof Error && "code" in error ? error.code : void 0;
1085
1460
  if (code !== "ENOENT") throw error;
@@ -1087,17 +1462,21 @@ var ensureWorktreeExclude = async (gitRoot) => {
1087
1462
  const lines = current.split(/\r?\n/);
1088
1463
  if (lines.some((line) => line.trim() === FABRIC_WORKTREE_EXCLUDE)) return;
1089
1464
  const prefix = current.length === 0 || current.endsWith("\n") ? "" : "\n";
1090
- fs5.appendFileSync(excludePath, `${prefix}${FABRIC_WORKTREE_EXCLUDE}
1465
+ fs7.appendFileSync(excludePath, `${prefix}${FABRIC_WORKTREE_EXCLUDE}
1091
1466
  `);
1092
1467
  };
1093
1468
 
1094
1469
  // src/agents/clone-first-worktree.ts
1470
+ var worktreeRollbackError = (gitRoot, worktree, branch, error, cleanupError) => {
1471
+ const detail = (value) => value instanceof Error ? `${value.message}${value.stderr ? `: ${value.stderr}` : ""}` : String(value);
1472
+ return new AggregateError([error, cleanupError], `Worktree operation failed: ${detail(error)}; rollback failed: ${detail(cleanupError)}. Manual cleanup required in repository ${JSON.stringify(gitRoot)}, worktree ${JSON.stringify(worktree)}${branch ? `, branch ${JSON.stringify(branch)}` : ""}.`);
1473
+ };
1095
1474
  var addCloneFirstWorktree = async (options) => {
1096
1475
  const dest = options.dest;
1097
- if (isFabricWorktreePath(dest, path6.basename(dest))) {
1476
+ if (isFabricWorktreePath(dest, path8.basename(dest))) {
1098
1477
  await ensureWorktreeExclude(options.gitRoot);
1099
1478
  }
1100
- fs6.mkdirSync(path6.dirname(dest), { recursive: true });
1479
+ fs8.mkdirSync(path8.dirname(dest), { recursive: true });
1101
1480
  const args = ["worktree", "add", "--no-checkout"];
1102
1481
  if (options.quiet) args.push("-q");
1103
1482
  if (options.detach) args.push("--detach");
@@ -1105,17 +1484,46 @@ var addCloneFirstWorktree = async (options) => {
1105
1484
  args.push(dest);
1106
1485
  if (options.startPoint) args.push(options.startPoint);
1107
1486
  const added = await executeFile("git", args, { cwd: options.gitRoot, timeoutMs: 6e4 });
1108
- let cloned = false;
1109
1487
  try {
1110
- await cloneTree(options.gitRoot, dest, CLONE_SKIP_PREFIXES);
1111
- cloned = true;
1488
+ let cloned = false;
1489
+ try {
1490
+ await cloneTree(options.gitRoot, dest, CLONE_SKIP_PREFIXES);
1491
+ cloned = true;
1492
+ } catch (error) {
1493
+ if (!(error instanceof CowUnavailableError)) throw error;
1494
+ }
1495
+ await executeFile("git", ["reset", "--hard", "HEAD"], { cwd: dest, timeoutMs: 6e4 });
1496
+ await executeFile("git", ["clean", "-fd"], { cwd: dest, timeoutMs: 6e4 });
1497
+ return { cloned, message: added.stdout.trim() };
1112
1498
  } catch (error) {
1113
- cloned = false;
1114
- if (!(error instanceof CowUnavailableError) && !(error instanceof Error)) throw error;
1499
+ const branch = options.branch?.flag === "-b" ? options.branch.name : void 0;
1500
+ try {
1501
+ await removeWorktree(options.gitRoot, dest, branch);
1502
+ } catch (cleanupError) {
1503
+ throw worktreeRollbackError(options.gitRoot, dest, branch, error, cleanupError);
1504
+ }
1505
+ throw error;
1115
1506
  }
1116
- await executeFile("git", ["reset", "--hard", "HEAD"], { cwd: dest, timeoutMs: 6e4 });
1117
- await executeFile("git", ["clean", "-fd"], { cwd: dest, timeoutMs: 6e4 });
1118
- return { cloned, message: added.stdout.trim() };
1507
+ };
1508
+ var removeWorktree = async (gitRoot, worktree, branch) => {
1509
+ let failure;
1510
+ try {
1511
+ await executeFile("git", ["worktree", "remove", "--force", worktree], { cwd: gitRoot, timeoutMs: 6e4 });
1512
+ } catch (error) {
1513
+ if (fs8.existsSync(worktree)) failure = error;
1514
+ else await executeFile("git", ["worktree", "prune"], { cwd: gitRoot, timeoutMs: 3e4 }).catch(() => void 0);
1515
+ }
1516
+ if (branch) {
1517
+ try {
1518
+ const existing = await executeFile("git", ["branch", "--list", branch], { cwd: gitRoot, timeoutMs: 3e4 });
1519
+ if (existing.stdout.trim()) {
1520
+ await executeFile("git", ["branch", "-D", branch], { cwd: gitRoot, timeoutMs: 3e4 });
1521
+ }
1522
+ } catch (error) {
1523
+ failure ??= error;
1524
+ }
1525
+ }
1526
+ if (failure !== void 0) throw failure;
1119
1527
  };
1120
1528
 
1121
1529
  // src/agents/worktree-manager.ts
@@ -1126,9 +1534,9 @@ var SETUP_TIMEOUT_MS = 10 * 6e4;
1126
1534
  var SETUP_OUTPUT_TAIL_CHARS = 2e3;
1127
1535
  var countLines = (file) => {
1128
1536
  try {
1129
- const stat = fs7.statSync(file);
1537
+ const stat = fs9.statSync(file);
1130
1538
  if (!stat.isFile() || stat.size > MAX_COUNTED_BYTES) return 0;
1131
- const content = fs7.readFileSync(file);
1539
+ const content = fs9.readFileSync(file);
1132
1540
  if (content.length === 0 || content.includes(0)) return 0;
1133
1541
  let lines = 0;
1134
1542
  for (const byte of content) if (byte === 10) lines++;
@@ -1139,8 +1547,8 @@ var countLines = (file) => {
1139
1547
  };
1140
1548
  var safeLabel = (value) => value.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 30) || "agent";
1141
1549
  var isInside2 = (root, target) => {
1142
- const relative = path7.relative(root, target);
1143
- return relative === "" || relative !== ".." && !relative.startsWith(`..${path7.sep}`) && !path7.isAbsolute(relative);
1550
+ const relative = path9.relative(root, target);
1551
+ return relative === "" || relative !== ".." && !relative.startsWith(`..${path9.sep}`) && !path9.isAbsolute(relative);
1144
1552
  };
1145
1553
  var worktreePrefixParts = (prefix) => {
1146
1554
  const parts = prefix.split(/[\\/]+/).filter(Boolean);
@@ -1158,10 +1566,12 @@ var WorktreeManager = class {
1158
1566
  ]);
1159
1567
  const output = root.stdout.trim();
1160
1568
  if (!output) throw new Error("Git did not return a worktree root");
1161
- gitRoot = fs7.realpathSync(output);
1569
+ gitRoot = fs9.realpathSync(output);
1162
1570
  sourcePrefix = prefix2.stdout.trim();
1163
- } catch {
1164
- throw new Error("Worktree isolation requires a Git repository");
1571
+ } catch (error) {
1572
+ const failure = error;
1573
+ const detail = (failure.stderr?.trim() || failure.message || String(error)).split("\n", 1)[0].slice(0, 500);
1574
+ throw new Error(`Worktree isolation requires a Git repository: ${detail}`, { cause: error });
1165
1575
  }
1166
1576
  const branch = `pi-fabric/${safeLabel(name)}-${id.slice(0, 8)}`;
1167
1577
  const worktreePath = fabricWorktreePath(gitRoot, id);
@@ -1171,15 +1581,25 @@ var WorktreeManager = class {
1171
1581
  branch: { flag: "-b", name: branch },
1172
1582
  startPoint: "HEAD"
1173
1583
  });
1174
- const canonicalWorktreePath = fs7.realpathSync(worktreePath);
1584
+ let canonicalWorktreePath;
1585
+ try {
1586
+ canonicalWorktreePath = fs9.realpathSync(worktreePath);
1587
+ } catch (error) {
1588
+ try {
1589
+ await removeWorktree(gitRoot, worktreePath, branch);
1590
+ } catch (cleanupError) {
1591
+ throw worktreeRollbackError(gitRoot, worktreePath, branch, error, cleanupError);
1592
+ }
1593
+ throw error;
1594
+ }
1175
1595
  const baseRef = await executeFile("git", ["rev-parse", "HEAD"], { cwd: worktreePath, timeoutMs: GIT_SUMMARY_TIMEOUT_MS }).then((result) => result.stdout.trim() || void 0, () => void 0);
1176
1596
  const prefix = preserveSourceSubdirectory ? worktreePrefixParts(sourcePrefix) : void 0;
1177
1597
  let effectiveCwd = canonicalWorktreePath;
1178
1598
  if (prefix && prefix.length > 0) {
1179
- const candidate = path7.resolve(canonicalWorktreePath, ...prefix);
1599
+ const candidate = path9.resolve(canonicalWorktreePath, ...prefix);
1180
1600
  try {
1181
- const canonicalCandidate = fs7.realpathSync(candidate);
1182
- if (fs7.statSync(canonicalCandidate).isDirectory() && isInside2(canonicalWorktreePath, canonicalCandidate)) {
1601
+ const canonicalCandidate = fs9.realpathSync(candidate);
1602
+ if (fs9.statSync(canonicalCandidate).isDirectory() && isInside2(canonicalWorktreePath, canonicalCandidate)) {
1183
1603
  effectiveCwd = canonicalCandidate;
1184
1604
  }
1185
1605
  } catch {
@@ -1218,7 +1638,7 @@ ${tail}` : ""}`);
1218
1638
  ...lease.baseRef ? { baseRef: lease.baseRef } : {},
1219
1639
  changedFiles: [],
1220
1640
  diffstat: { files: 0, insertions: 0, deletions: 0 },
1221
- kept: fs7.existsSync(lease.path)
1641
+ kept: fs9.existsSync(lease.path)
1222
1642
  };
1223
1643
  if (!result.kept) return result;
1224
1644
  try {
@@ -1238,7 +1658,7 @@ ${tail}` : ""}`);
1238
1658
  for (const file of untracked.stdout.split("\n")) {
1239
1659
  if (!file || files.has(file)) continue;
1240
1660
  files.add(file);
1241
- if (files.size <= MAX_CHANGED_FILES) result.diffstat.insertions += countLines(path7.join(lease.path, file));
1661
+ if (files.size <= MAX_CHANGED_FILES) result.diffstat.insertions += countLines(path9.join(lease.path, file));
1242
1662
  }
1243
1663
  result.diffstat.files = files.size;
1244
1664
  result.changedFiles = [...files].sort().slice(0, MAX_CHANGED_FILES);
@@ -1250,25 +1670,16 @@ ${tail}` : ""}`);
1250
1670
  async cleanup(id, deleteBranch = false) {
1251
1671
  const lease = this.#leases.get(id);
1252
1672
  if (!lease) return false;
1253
- await executeFile("git", ["worktree", "remove", "--force", lease.path], {
1254
- cwd: lease.gitRoot,
1255
- timeoutMs: 6e4
1256
- });
1257
- if (deleteBranch) {
1258
- await executeFile("git", ["branch", "-D", lease.branch], {
1259
- cwd: lease.gitRoot,
1260
- timeoutMs: 3e4
1261
- });
1262
- }
1263
- this.#leases.delete(id);
1673
+ await removeWorktree(lease.gitRoot, lease.path, deleteBranch ? lease.branch : void 0);
1674
+ if (this.#leases.get(id) === lease) this.#leases.delete(id);
1264
1675
  return true;
1265
1676
  }
1266
1677
  };
1267
1678
 
1268
1679
  // src/agents/handoff.ts
1269
- import { randomUUID as randomUUID4 } from "node:crypto";
1270
- import fs8 from "node:fs";
1271
- import path8 from "node:path";
1680
+ import { randomUUID as randomUUID5 } from "node:crypto";
1681
+ import fs10 from "node:fs";
1682
+ import path10 from "node:path";
1272
1683
 
1273
1684
  // src/core/host-sdk-runtime.ts
1274
1685
  var PiCodingAgent = await loadHostSdk();
@@ -1462,12 +1873,25 @@ var snapshotHandoffSession = (source, currentModel, outerToolResult, outerToolCa
1462
1873
  outerToolResult: structuredClone(outerToolResult)
1463
1874
  };
1464
1875
  };
1465
- var materializeBranch = (seed, cwd, directory) => {
1876
+ var withWorkerRoot = (entries) => {
1877
+ const policy = workerRoleEntry(
1878
+ freshEntryId(new Set(entries.map((entry) => entry.id))),
1879
+ null,
1880
+ (/* @__PURE__ */ new Date()).toISOString()
1881
+ );
1882
+ return [policy, ...entries.map((entry) => {
1883
+ if (entry.parentId !== null) return entry;
1884
+ const root = structuredClone(entry);
1885
+ root.parentId = policy.id;
1886
+ return root;
1887
+ })];
1888
+ };
1889
+ var materializeBranch = (seed, cwd, directory, options = {}) => {
1466
1890
  if (!seed.sourceBranch) {
1467
1891
  throw new Error("In-memory trajectory handoff is missing its source branch");
1468
1892
  }
1469
- const id = randomUUID4();
1470
- const sessionFile = path8.join(directory, `handoff-${id}.jsonl`);
1893
+ const id = randomUUID5();
1894
+ const sessionFile = path10.join(directory, `handoff-${id}.jsonl`);
1471
1895
  const header = {
1472
1896
  type: "session",
1473
1897
  version: PiCodingAgent.CURRENT_SESSION_VERSION,
@@ -1476,16 +1900,31 @@ var materializeBranch = (seed, cwd, directory) => {
1476
1900
  cwd,
1477
1901
  ...seed.sourceSessionFile ? { parentSession: seed.sourceSessionFile } : {}
1478
1902
  };
1479
- fs8.writeFileSync(
1903
+ const entries = options.workerRole ? withWorkerRoot(seed.sourceBranch) : seed.sourceBranch;
1904
+ fs10.writeFileSync(
1480
1905
  sessionFile,
1481
- `${[header, ...seed.sourceBranch].map((entry) => JSON.stringify(entry)).join("\n")}
1906
+ `${[header, ...entries].map((entry) => JSON.stringify(entry)).join("\n")}
1482
1907
  `,
1483
1908
  { encoding: "utf8", mode: 384, flag: "wx" }
1484
1909
  );
1485
1910
  return PiCodingAgent.SessionManager.open(sessionFile, directory, cwd);
1486
1911
  };
1487
- var forkBranch = (seed, cwd, directory) => {
1488
- if (!seed.sourceSessionFile) return materializeBranch(seed, cwd, directory);
1912
+ var insertWorkerRoot = (sessionFile) => {
1913
+ if (!fs10.existsSync(sessionFile)) {
1914
+ throw new Error("Trajectory handoff session file was not written, so the worker role cannot be placed at its root");
1915
+ }
1916
+ const [headerLine, ...entryLines] = fs10.readFileSync(sessionFile, "utf8").split("\n").filter((line) => line.length > 0);
1917
+ const entries = entryLines.map((line) => JSON.parse(line));
1918
+ const placed = withWorkerRoot(entries);
1919
+ fs10.writeFileSync(
1920
+ sessionFile,
1921
+ `${[headerLine, ...placed.map((entry) => JSON.stringify(entry))].join("\n")}
1922
+ `,
1923
+ { encoding: "utf8", mode: 384 }
1924
+ );
1925
+ };
1926
+ var forkBranch = (seed, cwd, directory, options = {}) => {
1927
+ if (!seed.sourceSessionFile) return materializeBranch(seed, cwd, directory, options);
1489
1928
  const fork = PiCodingAgent.SessionManager.open(seed.sourceSessionFile, directory, cwd);
1490
1929
  if (!fork.getEntry(seed.sourceBranchLeafId)) {
1491
1930
  throw new Error(
@@ -1519,14 +1958,15 @@ var synchronizeSourceSettings = (session, seed) => {
1519
1958
  session.appendThinkingLevelChange(seed.sourceThinkingLevel);
1520
1959
  }
1521
1960
  };
1522
- var writeHandoffSession = (seed, cwd, directory, transfer, compaction, compactionBudget) => {
1523
- fs8.mkdirSync(directory, { recursive: true, mode: 448 });
1961
+ var writeHandoffSession = (seed, cwd, directory, transfer, compaction, compactionBudget, options = {}) => {
1962
+ fs10.mkdirSync(directory, { recursive: true, mode: 448 });
1524
1963
  const policy = transfer ? thinkingTransferPolicy(transfer) : "preserved";
1525
1964
  let session;
1965
+ const viaPiBranch = Boolean(seed.sourceSessionFile) && (!transfer || policy === "preserved");
1526
1966
  let report;
1527
1967
  let digest;
1528
1968
  if (!transfer || policy === "preserved") {
1529
- session = forkBranch(seed, cwd, directory);
1969
+ session = forkBranch(seed, cwd, directory, options);
1530
1970
  } else {
1531
1971
  const rawBranch = seed.sourceSessionFile ? persistedBranch(seed, cwd, directory) : structuredClone(seed.sourceBranch ?? (() => {
1532
1972
  throw new Error("Trajectory handoff transfer is missing its source branch");
@@ -1534,7 +1974,7 @@ var writeHandoffSession = (seed, cwd, directory, transfer, compaction, compactio
1534
1974
  if (policy === "stripped") digest = buildThinkingDigest(rawBranch, transfer);
1535
1975
  const translated = translateThinkingForExecutor(rawBranch, policy);
1536
1976
  report = translated.report;
1537
- session = materializeBranch({ ...seed, sourceBranch: translated.entries }, cwd, directory);
1977
+ session = materializeBranch({ ...seed, sourceBranch: translated.entries }, cwd, directory, options);
1538
1978
  }
1539
1979
  synchronizeSourceSettings(session, seed);
1540
1980
  session.appendMessage(seed.outerToolResult);
@@ -1594,11 +2034,12 @@ var writeHandoffSession = (seed, cwd, directory, transfer, compaction, compactio
1594
2034
  });
1595
2035
  const sessionFile = session.getSessionFile();
1596
2036
  if (!sessionFile) throw new Error("Trajectory handoff did not produce a Pi session file");
1597
- fs8.chmodSync(sessionFile, 384);
2037
+ if (options.workerRole && viaPiBranch) insertWorkerRoot(sessionFile);
2038
+ fs10.chmodSync(sessionFile, 384);
1598
2039
  return sessionFile;
1599
2040
  };
1600
- var writeForkSession = (seed, cwd, directory, transfer) => {
1601
- fs8.mkdirSync(directory, { recursive: true, mode: 448 });
2041
+ var writeForkSession = (seed, cwd, directory, transfer, options = {}) => {
2042
+ fs10.mkdirSync(directory, { recursive: true, mode: 448 });
1602
2043
  const policy = transfer ? thinkingTransferPolicy(transfer) : "preserved";
1603
2044
  const raw = structuredClone(seed.sourceBranch);
1604
2045
  const digest = policy === "stripped" && transfer ? buildThinkingDigest(raw, transfer) : void 0;
@@ -1606,7 +2047,8 @@ var writeForkSession = (seed, cwd, directory, transfer) => {
1606
2047
  const session = materializeBranch(
1607
2048
  { sourceBranch: entries, ...seed.sourceSessionFile ? { sourceSessionFile: seed.sourceSessionFile } : {} },
1608
2049
  cwd,
1609
- directory
2050
+ directory,
2051
+ options
1610
2052
  );
1611
2053
  if (digest) {
1612
2054
  session.appendCustomMessageEntry(THINKING_DIGEST_CUSTOM_TYPE, digest.content, false, {
@@ -1621,13 +2063,13 @@ var writeForkSession = (seed, cwd, directory, transfer) => {
1621
2063
  });
1622
2064
  const sessionFile = session.getSessionFile();
1623
2065
  if (!sessionFile) throw new Error("Branch seed did not produce a Pi session file");
1624
- fs8.chmodSync(sessionFile, 384);
2066
+ fs10.chmodSync(sessionFile, 384);
1625
2067
  return sessionFile;
1626
2068
  };
1627
2069
 
1628
2070
  // src/agents/child-env.ts
1629
- import fs9 from "node:fs";
1630
- import path9 from "node:path";
2071
+ import fs11 from "node:fs";
2072
+ import path11 from "node:path";
1631
2073
  var MAX_WRITABLE_ROOTS = 32;
1632
2074
  var MAX_ROOT_CHARS = 4096;
1633
2075
  var readAgentLineage = (raw = process.env.PI_FABRIC_LINEAGE) => {
@@ -1658,12 +2100,12 @@ var checkWritePolicyRequest = (request) => {
1658
2100
  };
1659
2101
  var nearestExisting = (target) => {
1660
2102
  let current = target;
1661
- while (!fs9.existsSync(current)) {
1662
- const parent = path9.dirname(current);
2103
+ while (!fs11.existsSync(current)) {
2104
+ const parent = path11.dirname(current);
1663
2105
  if (parent === current) break;
1664
2106
  current = parent;
1665
2107
  }
1666
- return path9.join(fs9.realpathSync(current), path9.relative(current, target));
2108
+ return path11.join(fs11.realpathSync(current), path11.relative(current, target));
1667
2109
  };
1668
2110
  var resolveChildWritePolicy = (request, parent, cwd) => {
1669
2111
  if (!requestsWritePolicy(request)) return parent;
@@ -1676,39 +2118,72 @@ var resolveChildWritePolicy = (request, parent, cwd) => {
1676
2118
  throw new Error('A shell-confined agent cannot launch a child with shell: "unconfined"');
1677
2119
  }
1678
2120
  if (readOnly) return { readOnly, writableRoots: [], shell };
1679
- const realCwd = fs9.realpathSync(cwd);
2121
+ const realCwd = fs11.realpathSync(cwd);
1680
2122
  const within = (target) => !parent || parent.writableRoots.some((root) => isInside(root, target));
1681
2123
  const roots = request.writableRoots ?? (parent ? parent.writableRoots : [cwd]);
1682
2124
  const resolved = /* @__PURE__ */ new Set();
1683
2125
  for (const root of roots) {
1684
- const absolute = path9.resolve(cwd, root);
1685
- if (!fs9.existsSync(absolute)) {
2126
+ const absolute = path11.resolve(cwd, root);
2127
+ if (!fs11.existsSync(absolute)) {
1686
2128
  const target = nearestExisting(absolute);
1687
2129
  if (!isInside(cwd, absolute) || !isInside(realCwd, target) || !within(target)) {
1688
2130
  throw new Error(`Writable root must exist or be creatable inside the agent cwd: ${root}`);
1689
2131
  }
1690
- fs9.mkdirSync(absolute, { recursive: true });
2132
+ fs11.mkdirSync(absolute, { recursive: true });
1691
2133
  }
1692
- const real = fs9.realpathSync(absolute);
1693
- if (!fs9.statSync(real).isDirectory()) throw new Error(`Writable root is not a directory: ${root}`);
2134
+ const real = fs11.realpathSync(absolute);
2135
+ if (!fs11.statSync(real).isDirectory()) throw new Error(`Writable root is not a directory: ${root}`);
1694
2136
  if (!within(real)) throw new Error(`Writable root is outside the caller's writable roots: ${root}`);
1695
2137
  resolved.add(real);
1696
2138
  }
1697
2139
  return { readOnly, writableRoots: [...resolved].sort(), shell };
1698
2140
  };
1699
2141
 
2142
+ // src/verified/generated/budget.js
2143
+ function $n(v, what) {
2144
+ if (typeof v !== "number" || !Number.isSafeInteger(v) || v < 0) throw new RangeError(what + " must be a natural below 2^53, not " + v);
2145
+ return v;
2146
+ }
2147
+ var budgetAdmission = /* @__PURE__ */ (() => {
2148
+ function init(params) {
2149
+ const env = {}, s = {};
2150
+ return { scalars: { "out.admitted": 0 }, maps: {} };
2151
+ }
2152
+ function step(params, state, input) {
2153
+ const env = { "valid": $n(input["valid"], "input valid"), "spentHigh": $n(input["spentHigh"], "input spentHigh"), "spentLow": $n(input["spentLow"], "input spentLow"), "limitHigh": $n(input["limitHigh"], "input limitHigh"), "limitLow": $n(input["limitLow"], "input limitLow") }, s = state.scalars, dft = { ...state.defaults }, maps = state.maps;
2154
+ if (!(env["valid"] <= 1)) throw new RangeError("budget admission: the request fails the rule's assumption, so no proof covers the step it would take");
2155
+ const scalars = { ...s, "out.admitted": env["valid"] === 1 && (env["spentHigh"] < env["limitHigh"] || env["spentHigh"] === env["limitHigh"] && env["spentLow"] < env["limitLow"]) ? 1 : 0 };
2156
+ return Object.keys(dft).length ? { scalars, maps: state.maps, defaults: dft } : { scalars, maps: state.maps };
2157
+ }
2158
+ return { init, step };
2159
+ })();
2160
+
2161
+ // src/verified/budget.ts
2162
+ var orderedWords = (value) => {
2163
+ const view = new DataView(new ArrayBuffer(8));
2164
+ view.setFloat64(0, value === 0 ? 0 : value);
2165
+ const high = view.getUint32(0), low = view.getUint32(4);
2166
+ return (high & 2147483648) !== 0 ? [~high >>> 0, ~low >>> 0] : [(high ^ 2147483648) >>> 0, low];
2167
+ };
2168
+ var budgetAdmits = (spent, limit) => {
2169
+ const valid = Number.isFinite(spent) && Number.isFinite(limit) && limit > 0;
2170
+ const [spentHigh, spentLow] = orderedWords(valid ? spent : 0);
2171
+ const [limitHigh, limitLow] = orderedWords(valid ? limit : 0);
2172
+ return budgetAdmission.step({}, budgetAdmission.init({}), { valid: valid ? 1 : 0, spentHigh, spentLow, limitHigh, limitLow }).scalars["out.admitted"] === 1;
2173
+ };
2174
+
1700
2175
  // src/storage/retention.ts
1701
- import fs10 from "node:fs";
1702
- import path10 from "node:path";
2176
+ import fs12 from "node:fs";
2177
+ import path12 from "node:path";
1703
2178
  var RUN_ROOT_OWNER_FILE = ".fabric-owner.json";
1704
2179
  var TERMINAL_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "stopped", "timed_out"]);
1705
2180
  var RUN_ROOT_HEARTBEAT_TTL_MS = 45 * 60 * 1e3;
1706
- var ownerPath = (root) => path10.join(root, RUN_ROOT_OWNER_FILE);
2181
+ var ownerPath = (root) => path12.join(root, RUN_ROOT_OWNER_FILE);
1707
2182
  var readJson = (file) => {
1708
2183
  try {
1709
2184
  const stat = ownedStat(file);
1710
2185
  if (!stat?.isFile() || stat.size > 1024 * 1024) return;
1711
- return JSON.parse(fs10.readFileSync(file, "utf8"));
2186
+ return JSON.parse(fs12.readFileSync(file, "utf8"));
1712
2187
  } catch {
1713
2188
  return;
1714
2189
  }
@@ -1716,9 +2191,9 @@ var readJson = (file) => {
1716
2191
  var time = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
1717
2192
  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");
1718
2193
  var writeOwner = (root, owner) => {
1719
- if (fs10.existsSync(root) && !ownedStat(root)?.isDirectory()) throw new Error("Unsafe Fabric run root");
2194
+ if (fs12.existsSync(root) && !ownedStat(root)?.isDirectory()) throw new Error("Unsafe Fabric run root");
1720
2195
  const file = ownerPath(root);
1721
- if (fs10.existsSync(file)) {
2196
+ if (fs12.existsSync(file)) {
1722
2197
  const existing = readJson(file);
1723
2198
  if (!validOwner(existing) || existing.pid !== owner.pid) throw new Error("Unsafe Fabric run owner marker");
1724
2199
  }
@@ -1746,36 +2221,98 @@ var childAlive = (owner, pid) => {
1746
2221
  };
1747
2222
  var recordAgeReference = (record, fallback) => time(record.finishedAt) ? record.finishedAt : time(record.updatedAt) ? record.updatedAt : fallback;
1748
2223
  var runFiles = /* @__PURE__ */ new Set(["task.txt", "status.json", "events.jsonl", "lifecycle.jsonl", "steer.jsonl", "schema.json", "images.json"]);
2224
+ var UUID_V4 = "[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}";
2225
+ var UUID_V7 = "[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}";
2226
+ var PID = "[1-9]\\d*";
2227
+ var HANDOFF_FILE = new RegExp(`^handoff-${UUID_V4}\\.jsonl$`);
2228
+ var PI_BRANCH_FILE = new RegExp(`^(\\d{4}-\\d{2}-\\d{2})T(\\d{2})-(\\d{2})-(\\d{2})-(\\d{3})Z_${UUID_V7}\\.jsonl$`);
2229
+ var piBranchFile = (name) => {
2230
+ const match = PI_BRANCH_FILE.exec(name);
2231
+ if (!match) return false;
2232
+ const iso = `${match[1]}T${match[2]}:${match[3]}:${match[4]}.${match[5]}Z`;
2233
+ const instant = new Date(iso);
2234
+ return !Number.isNaN(instant.getTime()) && instant.toISOString() === iso;
2235
+ };
2236
+ var forkSessionFile = (name) => HANDOFF_FILE.test(name) || piBranchFile(name);
2237
+ var STATUS_TEMP_FILE = new RegExp(`^status\\.json\\.${PID}(?:\\.${UUID_V4})?\\.tmp$`);
2238
+ var OVERSIZED_EVENT_FILE = "oversized-event-prefix.txt";
1749
2239
  var DURABLE_KEY = /^(?:initial|[0-9a-f]{64})$/;
1750
2240
  var DURABLE_LEASE_FILES = /* @__PURE__ */ new Set(["lease.sqlite", "lease.sqlite-journal"]);
1751
2241
  var DURABLE_STORE_FILE = /^(?:main|(?:doc|task)-(?:0|[1-9]\d*))\.jsonl(?:\.reclaim)?$/;
1752
- var onlyOwnedFiles = (directory, allowed) => fs10.readdirSync(directory).every((name) => allowed(name) && ownedStat(path10.join(directory, name))?.isFile() === true);
1753
- var safeDurableTree = (directory) => fs10.readdirSync(directory).every((key) => {
1754
- const conversation = path10.join(directory, key);
2242
+ 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);
2244
+ var DURABLE_SESSION_FILE = "session.jsonl";
2245
+ 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
+ var DURABLE_SESSION_SIDECAR = /^session\.jsonl\.[A-Za-z0-9][A-Za-z0-9._-]*$/;
2247
+ var safeDurableSessionFolder = (directory) => {
2248
+ const uid = process.getuid?.();
2249
+ const stats = /* @__PURE__ */ new Map();
2250
+ for (const name of fs12.readdirSync(directory)) {
2251
+ if (DURABLE_SESSION_SIDECAR.test(name)) {
2252
+ const sidecar = fs12.lstatSync(path12.join(directory, name));
2253
+ if (!sidecar.isFile() || uid !== void 0 && sidecar.uid !== uid || sidecar.nlink !== 1) return false;
2254
+ continue;
2255
+ }
2256
+ if (name !== DURABLE_SESSION_FILE && !DURABLE_SESSION_TEMP.test(name)) return false;
2257
+ const stat = fs12.lstatSync(path12.join(directory, name));
2258
+ if (!stat.isFile() || uid !== void 0 && stat.uid !== uid || stat.nlink > 2) return false;
2259
+ stats.set(name, stat);
2260
+ }
2261
+ const linked = [...stats.entries()].filter(([, stat]) => stat.nlink !== 1);
2262
+ if (linked.length === 0) return true;
2263
+ const session = stats.get(DURABLE_SESSION_FILE);
2264
+ const temporaries = [...stats.entries()].filter(([name]) => name !== DURABLE_SESSION_FILE);
2265
+ const [temporary] = temporaries;
2266
+ 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
+ };
2268
+ var safeDurableTree = (directory) => fs12.readdirSync(directory).every((key) => {
2269
+ const conversation = path12.join(directory, key);
1755
2270
  if (!DURABLE_KEY.test(key) || !ownedStat(conversation)?.isDirectory()) return false;
1756
- return fs10.readdirSync(conversation).every((name) => {
1757
- const file = path10.join(conversation, name);
2271
+ return fs12.readdirSync(conversation).every((name) => {
2272
+ const file = path12.join(conversation, name);
1758
2273
  if (name === "store") return ownedStat(file)?.isDirectory() === true && onlyOwnedFiles(file, (child) => DURABLE_STORE_FILE.test(child));
2274
+ if (name === "fabric-journal") return ownedStat(file)?.isDirectory() === true && onlyOwnedFiles(file, (child) => FABRIC_JOURNAL_FILE.test(child));
1759
2275
  return DURABLE_LEASE_FILES.has(name) && ownedStat(file)?.isFile() === true;
1760
2276
  });
1761
2277
  });
1762
- var safeRunTree = (root, childrenStopped, owner, depth = 0) => {
2278
+ var ownedTree = (directory, depth) => {
2279
+ if (depth > 32) return false;
2280
+ return fs12.readdirSync(directory).every((name) => {
2281
+ const stat = ownedStat(path12.join(directory, name));
2282
+ if (!stat || name.startsWith("hosted.json")) return false;
2283
+ return stat.isFile() || stat.isDirectory() && ownedTree(path12.join(directory, name), depth + 1);
2284
+ });
2285
+ };
2286
+ var safeRunTree = (root, childrenStopped, owner, depth = 0, anyContents = false) => {
1763
2287
  if (depth > 32 || !ownedStat(root)?.isDirectory()) return false;
1764
- const record = readJson(path10.join(root, "status.json"));
2288
+ const record = readJson(path12.join(root, "status.json"));
1765
2289
  const pid = record?.transport === "process" && typeof record.sessionId === "string" && /^\d+$/.test(record.sessionId) ? Number(record.sessionId) : void 0;
1766
2290
  if (pid !== void 0 && childAlive(owner, pid)) return false;
1767
- if (!record?.status || !TERMINAL_STATUSES.has(record.status)) {
2291
+ const terminal2 = !!record?.status && TERMINAL_STATUSES.has(record.status);
2292
+ if (!terminal2) {
1768
2293
  if (!childrenStopped && pid === void 0) return false;
1769
- if (!ownedStat(path10.join(root, "task.txt"))?.isFile()) return false;
2294
+ if (!ownedStat(path12.join(root, "task.txt"))?.isFile()) return false;
1770
2295
  }
1771
2296
  try {
1772
- for (const name of fs10.readdirSync(root)) {
1773
- const file = path10.join(root, name);
2297
+ for (const name of fs12.readdirSync(root)) {
2298
+ const file = path12.join(root, name);
1774
2299
  const stat = ownedStat(file);
1775
2300
  if (!stat) return false;
1776
- if (stat.isFile() && runFiles.has(name)) continue;
2301
+ if (stat.isFile() && (runFiles.has(name) || name === OVERSIZED_EVENT_FILE || STATUS_TEMP_FILE.test(name))) continue;
2302
+ if (anyContents && name !== "nested" && !name.startsWith("hosted.json")) {
2303
+ if (stat.isFile() || stat.isDirectory() && ownedTree(file, depth + 1)) continue;
2304
+ return false;
2305
+ }
2306
+ if (stat.isDirectory() && name === "fork-session") {
2307
+ if (!onlyOwnedFiles(file, (child) => forkSessionFile(child))) return false;
2308
+ continue;
2309
+ }
1777
2310
  if (stat.isDirectory() && name === "handoff-session") {
1778
- if (fs10.readdirSync(file).some((child) => !child.endsWith(".jsonl") || !ownedStat(path10.join(file, child))?.isFile())) return false;
2311
+ if (fs12.readdirSync(file).some((child) => !child.endsWith(".jsonl") || !ownedStat(path12.join(file, child))?.isFile())) return false;
2312
+ continue;
2313
+ }
2314
+ if (stat.isDirectory() && name === "durable-session") {
2315
+ if (!safeDurableSessionFolder(file)) return false;
1779
2316
  continue;
1780
2317
  }
1781
2318
  if (stat.isDirectory() && name === "durable") {
@@ -1783,7 +2320,7 @@ var safeRunTree = (root, childrenStopped, owner, depth = 0) => {
1783
2320
  continue;
1784
2321
  }
1785
2322
  if (stat.isDirectory() && name === "nested") {
1786
- for (const child of fs10.readdirSync(file)) if (!safeRunTree(path10.join(file, child), false, owner, depth + 1)) return false;
2323
+ for (const child of fs12.readdirSync(file)) if (!safeRunTree(path12.join(file, child), false, owner, depth + 1, anyContents)) return false;
1787
2324
  continue;
1788
2325
  }
1789
2326
  return false;
@@ -1793,9 +2330,9 @@ var safeRunTree = (root, childrenStopped, owner, depth = 0) => {
1793
2330
  return false;
1794
2331
  }
1795
2332
  };
1796
- var safeRootContents = (root, childrenStopped, owner) => {
2333
+ var safeRootContents = (root, childrenStopped, owner, anyContents = false) => {
1797
2334
  try {
1798
- return fs10.readdirSync(root).every((name) => name === RUN_ROOT_OWNER_FILE || safeRunTree(path10.join(root, name), childrenStopped, owner));
2335
+ return fs12.readdirSync(root).every((name) => name === RUN_ROOT_OWNER_FILE || safeRunTree(path12.join(root, name), childrenStopped, owner, 0, anyContents));
1799
2336
  } catch {
1800
2337
  return false;
1801
2338
  }
@@ -1808,8 +2345,8 @@ var canRemoveManagedRunRoot = (root) => {
1808
2345
  var removeEmptyRunRoot = (root) => {
1809
2346
  try {
1810
2347
  if (!ownedStat(root)?.isDirectory() || !validOwner(readJson(ownerPath(root)))) return false;
1811
- if (fs10.readdirSync(root).some((name) => name !== RUN_ROOT_OWNER_FILE)) return false;
1812
- fs10.rmSync(root, { recursive: true, force: true });
2348
+ if (fs12.readdirSync(root).some((name) => name !== RUN_ROOT_OWNER_FILE)) return false;
2349
+ fs12.rmSync(root, { recursive: true, force: true });
1813
2350
  return true;
1814
2351
  } catch {
1815
2352
  return false;
@@ -1819,21 +2356,21 @@ var pruneClosedRunRoot = (root, owner, orphanMs, oneShotMs, now) => {
1819
2356
  const removed = [];
1820
2357
  let entries;
1821
2358
  try {
1822
- entries = fs10.readdirSync(root, { withFileTypes: true });
2359
+ entries = fs12.readdirSync(root, { withFileTypes: true });
1823
2360
  } catch {
1824
2361
  return removed;
1825
2362
  }
1826
2363
  for (const entry of entries) {
1827
2364
  if (!entry.isDirectory()) continue;
1828
- const directory = path10.join(root, entry.name);
2365
+ const directory = path12.join(root, entry.name);
1829
2366
  if (!safeRunTree(directory, owner.childrenStopped === true, owner)) continue;
1830
- const record = readJson(path10.join(directory, "status.json"));
1831
- const terminal = !!record?.status && TERMINAL_STATUSES.has(record.status);
1832
- const reference = terminal ? recordAgeReference(record, ownedStat(directory)?.mtimeMs ?? now) : owner.closedAt;
1833
- const retention = terminal && !record?.actorId ? oneShotMs : orphanMs;
2367
+ const record = readJson(path12.join(directory, "status.json"));
2368
+ const terminal2 = !!record?.status && TERMINAL_STATUSES.has(record.status);
2369
+ const reference = terminal2 ? recordAgeReference(record, ownedStat(directory)?.mtimeMs ?? now) : owner.closedAt;
2370
+ const retention = terminal2 && !record?.actorId ? oneShotMs : orphanMs;
1834
2371
  if (now - reference < retention) continue;
1835
2372
  try {
1836
- fs10.rmSync(directory, { recursive: true, force: true });
2373
+ fs12.rmSync(directory, { recursive: true, force: true });
1837
2374
  removed.push(directory);
1838
2375
  } catch {
1839
2376
  }
@@ -1845,14 +2382,14 @@ var sweepTempRunRoots = (options) => {
1845
2382
  const result = { removedRoots: [], removedRuns: [] };
1846
2383
  let entries;
1847
2384
  try {
1848
- entries = fs10.readdirSync(options.tempRoot, { withFileTypes: true });
2385
+ entries = fs12.readdirSync(options.tempRoot, { withFileTypes: true });
1849
2386
  } catch {
1850
2387
  return result;
1851
2388
  }
1852
2389
  for (const entry of entries) {
1853
2390
  if (!entry.isDirectory() || !/^pi-fabric-runs-[A-Za-z0-9_-]+$/.test(entry.name)) continue;
1854
- const root = path10.join(options.tempRoot, entry.name);
1855
- if (options.currentRoot && path10.resolve(root) === path10.resolve(options.currentRoot)) continue;
2391
+ const root = path12.join(options.tempRoot, entry.name);
2392
+ if (options.currentRoot && path12.resolve(root) === path12.resolve(options.currentRoot)) continue;
1856
2393
  if (!ownedStat(root)?.isDirectory()) continue;
1857
2394
  const owner = readJson(ownerPath(root));
1858
2395
  if (!validOwner(owner)) continue;
@@ -1869,9 +2406,9 @@ var sweepTempRunRoots = (options) => {
1869
2406
  }
1870
2407
  continue;
1871
2408
  }
1872
- if (now - owner.orphanedAt < options.orphanedTempRunRetentionMs || !safeRootContents(root, false, owner)) continue;
2409
+ if (now - owner.orphanedAt < options.orphanedTempRunRetentionMs || !safeRootContents(root, false, owner, true)) continue;
1873
2410
  try {
1874
- fs10.rmSync(root, { recursive: true, force: true });
2411
+ fs12.rmSync(root, { recursive: true, force: true });
1875
2412
  result.removedRoots.push(root);
1876
2413
  } catch {
1877
2414
  }
@@ -1884,18 +2421,18 @@ var pruneActorRunArchives = (options) => {
1884
2421
  if (!ownedStat(options.runsDirectory)?.isDirectory()) return removed;
1885
2422
  let entries;
1886
2423
  try {
1887
- entries = fs10.readdirSync(options.runsDirectory, { withFileTypes: true });
2424
+ entries = fs12.readdirSync(options.runsDirectory, { withFileTypes: true });
1888
2425
  } catch {
1889
2426
  return removed;
1890
2427
  }
1891
2428
  for (const entry of entries) {
1892
2429
  if (!entry.isDirectory() || entry.name === options.latestRunId) continue;
1893
- const directory = path10.join(options.runsDirectory, entry.name);
1894
- const record = readJson(path10.join(directory, "status.json"));
2430
+ const directory = path12.join(options.runsDirectory, entry.name);
2431
+ const record = readJson(path12.join(directory, "status.json"));
1895
2432
  if (!record?.status || !TERMINAL_STATUSES.has(record.status) || !safeRunTree(directory, false)) continue;
1896
2433
  if (now - recordAgeReference(record, ownedStat(directory)?.mtimeMs ?? now) < options.retentionMs) continue;
1897
2434
  try {
1898
- fs10.rmSync(directory, { recursive: true, force: true });
2435
+ fs12.rmSync(directory, { recursive: true, force: true });
1899
2436
  removed.push(directory);
1900
2437
  } catch {
1901
2438
  }
@@ -1905,21 +2442,21 @@ var pruneActorRunArchives = (options) => {
1905
2442
 
1906
2443
  // src/agents/session-export.ts
1907
2444
  import os2 from "node:os";
1908
- import path11 from "node:path";
2445
+ import path13 from "node:path";
1909
2446
  var SESSION_EXPORT_ENV = "PI_FABRIC_AGENT_DIR";
1910
- var expandHome = (value) => value === "~" ? os2.homedir() : value.startsWith("~/") || value.startsWith(`~${path11.win32.sep}`) ? path11.join(os2.homedir(), value.slice(2)) : value;
2447
+ var expandHome = (value) => value === "~" ? os2.homedir() : value.startsWith("~/") || value.startsWith(`~${path13.win32.sep}`) ? path13.join(os2.homedir(), value.slice(2)) : value;
1911
2448
  var encodeSessionExportCwd = (cwd) => {
1912
- const absolute = path11.isAbsolute(cwd) || path11.win32.isAbsolute(cwd) ? cwd : path11.resolve(cwd);
2449
+ const absolute = path13.isAbsolute(cwd) || path13.win32.isAbsolute(cwd) ? cwd : path13.resolve(cwd);
1913
2450
  return `--${absolute.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
1914
2451
  };
1915
2452
  var resolveSessionExportDir = (config) => {
1916
2453
  if (!config.sessionExport) return void 0;
1917
- const raw = process.env[SESSION_EXPORT_ENV]?.trim() || config.sessionExportDir.trim() || path11.join(os2.homedir(), ".pi", "agent");
2454
+ const raw = process.env[SESSION_EXPORT_ENV]?.trim() || config.sessionExportDir.trim() || path13.join(os2.homedir(), ".pi", "agent");
1918
2455
  return expandHome(raw);
1919
2456
  };
1920
2457
  var sessionExportFileFor = (root, cwd, runId, at) => {
1921
2458
  const fileTimestamp = at.toISOString().replace(/[:.]/g, "-");
1922
- return path11.join(
2459
+ return path13.join(
1923
2460
  root,
1924
2461
  "sessions",
1925
2462
  ".fabric",
@@ -1960,11 +2497,11 @@ var resolveAgentCwd = (parentCwd, requestedCwd) => {
1960
2497
  if (typeof requested !== "string" || requested.trim().length === 0) {
1961
2498
  throw new Error(`Invalid Fabric agent cwd ${JSON.stringify(requested)}: path must not be empty`);
1962
2499
  }
1963
- const candidate = path12.isAbsolute(requested) ? requested : path12.resolve(parentCwd, requested);
2500
+ const candidate = path14.isAbsolute(requested) ? requested : path14.resolve(parentCwd, requested);
1964
2501
  try {
1965
- const canonical = fs11.realpathSync(candidate);
1966
- fs11.accessSync(canonical, fs11.constants.R_OK | fs11.constants.X_OK);
1967
- if (!fs11.statSync(canonical).isDirectory()) {
2502
+ const canonical = fs13.realpathSync(candidate);
2503
+ fs13.accessSync(canonical, fs13.constants.R_OK | fs13.constants.X_OK);
2504
+ if (!fs13.statSync(canonical).isDirectory()) {
1968
2505
  throw new Error("path is not a directory");
1969
2506
  }
1970
2507
  return canonical;
@@ -1974,6 +2511,35 @@ var resolveAgentCwd = (parentCwd, requestedCwd) => {
1974
2511
  }
1975
2512
  };
1976
2513
  var terminalStatuses = terminalAgentStatuses;
2514
+ var queuedResult = (entry, status, error) => {
2515
+ const now = Date.now();
2516
+ return {
2517
+ id: entry.id,
2518
+ name: entry.name,
2519
+ task: entry.task,
2520
+ status,
2521
+ runner: entry.runner,
2522
+ ...entry.kernel ? { kernel: entry.kernel } : {},
2523
+ transport: entry.transport,
2524
+ cwd: entry.cwd,
2525
+ ...entry.model ? { model: entry.model } : {},
2526
+ startedAt: entry.queuedAt,
2527
+ updatedAt: now,
2528
+ finishedAt: now,
2529
+ turns: 0,
2530
+ toolCalls: 0,
2531
+ text: "",
2532
+ error,
2533
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 }
2534
+ };
2535
+ };
2536
+ var fileSize = (filePath) => {
2537
+ try {
2538
+ return fs13.statSync(filePath).size;
2539
+ } catch {
2540
+ return 0;
2541
+ }
2542
+ };
1977
2543
  var HOSTED_TRANSPORT = {
1978
2544
  kind: "process",
1979
2545
  available: async () => false,
@@ -2020,7 +2586,7 @@ var runName = (request) => safeName(request.name ?? request.task.split("\n", 1)[
2020
2586
  var safeName = (value) => value.replace(/[\r\n\t]+/g, " ").trim().slice(0, MAX_NAME_LENGTH) || "Fabric agent";
2021
2587
  var readRecord = (filePath) => {
2022
2588
  try {
2023
- const parsed = JSON.parse(fs11.readFileSync(filePath, "utf8"));
2589
+ const parsed = JSON.parse(fs13.readFileSync(filePath, "utf8"));
2024
2590
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
2025
2591
  const record = parsed;
2026
2592
  return { ...record, runner: isFabricRunnerId(record.runner) ? record.runner : "pi" };
@@ -2072,24 +2638,24 @@ var reconcileNestedAgents = (records, owner) => records.map((record) => {
2072
2638
  });
2073
2639
  var readNestedAgents = (runDirectory, depth = 0) => {
2074
2640
  if (depth >= 8) return [];
2075
- const nestedRoot = path12.join(runDirectory, "nested");
2641
+ const nestedRoot = path14.join(runDirectory, "nested");
2076
2642
  let entries;
2077
2643
  try {
2078
- entries = fs11.readdirSync(nestedRoot);
2644
+ entries = fs13.readdirSync(nestedRoot);
2079
2645
  } catch {
2080
2646
  return [];
2081
2647
  }
2082
2648
  const agents = [];
2083
2649
  for (const entry of entries.slice(0, 200)) {
2084
- const runDirectory2 = path12.join(nestedRoot, entry);
2085
- const record = readRecord(path12.join(runDirectory2, "status.json"));
2650
+ const runDirectory2 = path14.join(nestedRoot, entry);
2651
+ const record = readRecord(path14.join(runDirectory2, "status.json"));
2086
2652
  if (!record) continue;
2087
2653
  const nestedAgents = readNestedAgents(runDirectory2, depth + 1);
2088
2654
  const { logFile: _logFile, nestedAgents: _nestedAgents, ...safeRecord } = record;
2089
2655
  agents.push(
2090
2656
  compactUiRecord({
2091
2657
  ...safeRecord,
2092
- logFile: path12.join(runDirectory2, "events.jsonl"),
2658
+ logFile: path14.join(runDirectory2, "events.jsonl"),
2093
2659
  ...nestedAgents.length > 0 ? { nestedAgents } : {}
2094
2660
  })
2095
2661
  );
@@ -2097,7 +2663,7 @@ var readNestedAgents = (runDirectory, depth = 0) => {
2097
2663
  return agents;
2098
2664
  };
2099
2665
  var summarizeRunLog = (runDirectory, lines) => {
2100
- const page = readJsonlPage(path12.join(runDirectory, "events.jsonl"), lines);
2666
+ const page = readJsonlPage(path14.join(runDirectory, "events.jsonl"), lines);
2101
2667
  const summary = [];
2102
2668
  for (const entry of page.lines) {
2103
2669
  const parsed = entry.parsed;
@@ -2150,8 +2716,8 @@ var AgentManager = class {
2150
2716
  this.config = config;
2151
2717
  this.#semaphore = new AgentAdmission(config.maxConcurrent, Infinity, config.maxDepth);
2152
2718
  this.#managedTempRoot = options.runRoot === void 0 && process.env.PI_FABRIC_RUN_ROOT === void 0;
2153
- this.#runRoot = options.runRoot ?? process.env.PI_FABRIC_RUN_ROOT ?? fs11.mkdtempSync(path12.join(os3.tmpdir(), "pi-fabric-runs-"));
2154
- this.#parentOwnedRunRoot = options.runRoot === void 0 && this.#parentLineage?.worker === true && this.#parentLineage.depth > 0 && path12.basename(this.#runRoot) === "nested" && path12.basename(path12.dirname(this.#runRoot)) === this.#parentLineage.runId;
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;
2155
2721
  this.#retention = options.retention ?? DEFAULT_FABRIC_CONFIG.retention;
2156
2722
  this.#workerPath = options.workerPath ?? fileURLToPath(new URL("../worker.js", import.meta.url));
2157
2723
  this.#fabricExtensionPath = options.fabricExtensionPath ?? fileURLToPath(new URL("../index.js", import.meta.url));
@@ -2188,7 +2754,8 @@ var AgentManager = class {
2188
2754
  new TmuxTransport(),
2189
2755
  new ScreenTransport(),
2190
2756
  new LocaltermTransport(),
2191
- new HerdrTransport()
2757
+ new HerdrTransport(),
2758
+ new HerdrCoreTransport()
2192
2759
  ];
2193
2760
  this.#transports = new Map(adapters.map((adapter) => [adapter.kind, adapter]));
2194
2761
  if (this.#managedTempRoot) {
@@ -2248,14 +2815,16 @@ var AgentManager = class {
2248
2815
  #closePromise;
2249
2816
  #closeAbort = new AbortController();
2250
2817
  #spawns = /* @__PURE__ */ new Set();
2818
+ /** spawn({ queue: true }) runs that hold an id but no slot yet, or that ended before they started. */
2819
+ #queued = /* @__PURE__ */ new Map();
2251
2820
  #unregisteredTransports = /* @__PURE__ */ new Set();
2252
2821
  #launches = /* @__PURE__ */ new Set();
2253
- async #prepareModel(model) {
2822
+ async #prepareModel(model, modelMatch) {
2254
2823
  if (!this.#preparePiModel) return model;
2255
- const key = model?.trim() || "<session-default>";
2824
+ const key = `${modelMatch ?? ""}|${model?.trim() || "<session-default>"}`;
2256
2825
  const existing = this.#piModelPreparations.get(key);
2257
2826
  if (existing) return existing;
2258
- const preparation = this.#preparePiModel(model).then((prepared) => {
2827
+ const preparation = (modelMatch ? this.#preparePiModel(model, { modelMatch }) : this.#preparePiModel(model)).then((prepared) => {
2259
2828
  if (typeof prepared !== "string") return model;
2260
2829
  return prepared.trim() || model;
2261
2830
  });
@@ -2275,6 +2844,10 @@ var AgentManager = class {
2275
2844
  resolveCwd(requestedCwd) {
2276
2845
  return resolveAgentCwd(this.cwd, requestedCwd);
2277
2846
  }
2847
+ /** The project root Fabric already uses for the mesh; named agent files live under its .pi folder. */
2848
+ get projectRoot() {
2849
+ return this.#projectRoot;
2850
+ }
2278
2851
  #inheritedSessionPins(request) {
2279
2852
  const explicit = request.inheritedSessionPins;
2280
2853
  if (explicit && explicit.length > 0) return explicit;
@@ -2328,6 +2901,7 @@ var AgentManager = class {
2328
2901
  }
2329
2902
  spawn(request, signal) {
2330
2903
  if (this.#closing) return Promise.reject(new Error("Fabric agent manager is closing"));
2904
+ if (request.queue === true) return this.#spawnQueued(request);
2331
2905
  const pending = this.#spawn(request, signal);
2332
2906
  this.#spawns.add(pending);
2333
2907
  void pending.then(() => this.#spawns.delete(pending), () => this.#spawns.delete(pending));
@@ -2349,7 +2923,73 @@ var AgentManager = class {
2349
2923
  childThinkingBounds(requested) {
2350
2924
  return childThinkingBounds(this.#thinkingBounds?.() ?? {}, requested);
2351
2925
  }
2352
- async #spawn(request, signal) {
2926
+ /**
2927
+ * Validate now, return a queued handle, and launch when a slot frees. The
2928
+ * caller's signal is not used: a queued run outlives the program that
2929
+ * spawned it, like a detached running one. agents.stop cancels it.
2930
+ */
2931
+ #spawnQueued(request) {
2932
+ if (request.residency === "durable") {
2933
+ return Promise.reject(new Error('queue: true is not supported with residency: "durable"'));
2934
+ }
2935
+ const id = randomUUID6().replaceAll("-", "");
2936
+ const control = new AbortController();
2937
+ return new Promise((resolve, reject) => {
2938
+ let entry;
2939
+ const launch = this.#spawn(request, void 0, {
2940
+ id,
2941
+ signal: control.signal,
2942
+ onQueued: (snapshot) => {
2943
+ let settle;
2944
+ const outcome = new Promise((done) => {
2945
+ settle = done;
2946
+ });
2947
+ entry = { ...snapshot, id, queuedAt: Date.now(), control, outcome, settle, background: false, stopRequested: false };
2948
+ this.#queued.set(id, entry);
2949
+ this.#invalidateUiList();
2950
+ resolve(this.#queuedHandle(entry));
2951
+ }
2952
+ });
2953
+ this.#spawns.add(launch);
2954
+ void launch.then(() => this.#spawns.delete(launch), () => this.#spawns.delete(launch));
2955
+ launch.then(
2956
+ () => {
2957
+ if (!entry) return;
2958
+ this.#queued.delete(id);
2959
+ const managed = this.#runs.get(id);
2960
+ if (managed && entry.background) this.#detach(managed, "queued run started detached");
2961
+ entry.settle({ launched: true });
2962
+ this.#invalidateUiList();
2963
+ },
2964
+ (error) => {
2965
+ if (!entry) {
2966
+ reject(error);
2967
+ return;
2968
+ }
2969
+ const stopped = entry.stopRequested || this.#closing;
2970
+ const message2 = entry.stopRequested ? "Agent stopped before it started" : this.#closing ? "Fabric agent manager is closing" : error instanceof Error ? error.message : String(error);
2971
+ const result = queuedResult(entry, stopped ? "stopped" : "failed", message2);
2972
+ entry.result = result;
2973
+ entry.settle({ result });
2974
+ this.#invalidateUiList();
2975
+ this.#notifyBackgroundComplete(entry, result);
2976
+ }
2977
+ );
2978
+ });
2979
+ }
2980
+ #queuedHandle(entry) {
2981
+ return {
2982
+ id: entry.id,
2983
+ name: entry.name,
2984
+ status: "queued",
2985
+ runner: entry.runner,
2986
+ ...entry.kernel ? { kernel: entry.kernel } : {},
2987
+ transport: entry.transport,
2988
+ cwd: entry.cwd,
2989
+ ...entry.model ? { model: entry.model } : {}
2990
+ };
2991
+ }
2992
+ async #spawn(request, signal, queued) {
2353
2993
  if (!this.config.enabled) throw new Error("Agents are disabled in Fabric configuration");
2354
2994
  if (this.#currentDepth >= this.config.maxDepth) {
2355
2995
  throw new Error(`Fabric agent depth limit reached (${this.config.maxDepth})`);
@@ -2366,12 +3006,16 @@ var AgentManager = class {
2366
3006
  throw new Error(`Invalid Fabric agent residency: ${String(request.residency)}`);
2367
3007
  }
2368
3008
  const runner = request.runner ?? this.config.runner;
3009
+ assertExactModelRequest({ modelMatch: request.modelMatch, runner, model: request.model });
2369
3010
  const runnerAdapter = requireAgentRunner(runner);
2370
3011
  const capabilities2 = runnerAdapter.capabilities;
2371
3012
  const hostedAdapter = runnerAdapter.kind === "hosted" ? runnerAdapter : void 0;
2372
3013
  if (request.persona && runner !== "veda") {
2373
3014
  throw new Error(`The persona option is only supported by the Veda runner, not ${runner}`);
2374
3015
  }
3016
+ if (request.childSkills && runner !== "pi" && runner !== "pi-durable") {
3017
+ throw new Error(`The skills option is supported only by the Pi runners, not ${runner}`);
3018
+ }
2375
3019
  if (request.persistSession === true && runner !== "claude") {
2376
3020
  throw new Error("persistSession is only supported by the Claude runner");
2377
3021
  }
@@ -2413,6 +3057,12 @@ var AgentManager = class {
2413
3057
  if (worktreeSetup !== void 0 && (typeof worktreeSetup !== "string" || worktreeSetup.length > 8192)) {
2414
3058
  throw new Error("worktreeSetup must be a shell command of at most 8192 characters");
2415
3059
  }
3060
+ if (request.holdQuestions !== void 0) {
3061
+ if (request.holdQuestions !== true) throw new Error("holdQuestions must be true when given");
3062
+ if (this.config.childQuestions !== "route" || !capabilities2.questions) {
3063
+ throw new Error('holdQuestions requires agents.childQuestions "route" and a runner that declares questions');
3064
+ }
3065
+ }
2416
3066
  const scope = launchScope(request.scope, request.inheritedScope);
2417
3067
  checkedTraceContext(request);
2418
3068
  const thinkingBounds = this.childThinkingBounds(request.thinkingBounds);
@@ -2433,53 +3083,73 @@ var AgentManager = class {
2433
3083
  }
2434
3084
  if (model && runnerAdapter.normalizeModel) model = await runnerAdapter.normalizeModel(model);
2435
3085
  }
2436
- if (this.#budget) {
3086
+ const checkBudget = () => {
3087
+ if (!this.#budget) return;
2437
3088
  const spent = readBudgetLedger(this.#budget.file).cost;
2438
- if (spent >= this.#budget.budget) {
3089
+ if (!budgetAdmits(spent, this.#budget.budget)) {
2439
3090
  throw new Error(
2440
3091
  `Fabric recursion budget exceeded: spent $${spent.toFixed(6)} of $${this.#budget.budget.toFixed(6)}. Increase agents.budgetUsd or simplify the task.`
2441
3092
  );
2442
3093
  }
2443
- }
2444
- const admissionSignal = signal ? AbortSignal.any([signal, this.#closeAbort.signal]) : this.#closeAbort.signal;
3094
+ };
3095
+ checkBudget();
3096
+ const callerSignal = queued?.signal ?? signal;
3097
+ const admissionSignal = callerSignal ? AbortSignal.any([callerSignal, this.#closeAbort.signal]) : this.#closeAbort.signal;
3098
+ queued?.onQueued({
3099
+ name: runName(request),
3100
+ task: request.task,
3101
+ runner,
3102
+ ...kernel ? { kernel } : {},
3103
+ transport: hostedAdapter ? "hosted" : request.transport ?? this.config.transport,
3104
+ cwd: selectedCwd,
3105
+ ...model ? { model } : {}
3106
+ });
2445
3107
  const release = await this.#semaphore.acquire("native", admissionSignal);
2446
3108
  try {
2447
- if (runner === "pi" || runner === "pi-durable") model = await this.#prepareModel(model);
3109
+ if (runner === "pi" || runner === "pi-durable") model = await this.#prepareModel(model, request.modelMatch);
3110
+ queued?.signal.throwIfAborted();
2448
3111
  if (this.#closing) throw new Error("Fabric agent manager is closing");
3112
+ checkBudget();
2449
3113
  this.#semaphore.admit(this.#currentDepth + 1);
2450
3114
  } catch (error) {
2451
3115
  release();
2452
3116
  throw error;
2453
3117
  }
2454
- const id = randomUUID5().replaceAll("-", "");
3118
+ const id = queued?.id ?? randomUUID6().replaceAll("-", "");
2455
3119
  const name = runName(request);
2456
- const runDirectory = path12.join(this.#runRoot, id);
2457
- fs11.mkdirSync(runDirectory, { recursive: true });
3120
+ const runDirectory = path14.join(this.#runRoot, id);
3121
+ 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;
3129
+ try {
3130
+ fs13.mkdirSync(runDirectory, durableSession ? { recursive: true, mode: 448 } : { recursive: true });
3131
+ fs13.writeFileSync(taskFile, request.task, { encoding: "utf8", mode: 384 });
3132
+ if (imagesFile) {
3133
+ fs13.writeFileSync(imagesFile, JSON.stringify(request.images), {
3134
+ encoding: "utf8",
3135
+ mode: 384
3136
+ });
3137
+ }
3138
+ if (schemaFile) {
3139
+ fs13.writeFileSync(schemaFile, JSON.stringify(request.schema, null, 2), {
3140
+ encoding: "utf8",
3141
+ mode: 384
3142
+ });
3143
+ }
3144
+ } catch (error) {
3145
+ release();
3146
+ throw error;
3147
+ }
2458
3148
  if (this.#managedTempRoot && !this.#retentionTimer) {
2459
3149
  this.#retentionTimer = setInterval(() => this.#scheduleRetentionSweep(), RETENTION_SWEEP_INTERVAL_MS);
2460
3150
  this.#retentionTimer.unref();
2461
3151
  this.#scheduleRetentionSweep();
2462
3152
  }
2463
- const taskFile = path12.join(runDirectory, "task.txt");
2464
- const statusFile = path12.join(runDirectory, "status.json");
2465
- const lifecycleFile = path12.join(runDirectory, "lifecycle.jsonl");
2466
- const logFile = path12.join(runDirectory, "events.jsonl");
2467
- const steerFile = path12.join(runDirectory, "steer.jsonl");
2468
- const schemaFile = request.schema ? path12.join(runDirectory, "schema.json") : void 0;
2469
- const imagesFile = request.images && request.images.length > 0 ? path12.join(runDirectory, "images.json") : void 0;
2470
- fs11.writeFileSync(taskFile, request.task, { encoding: "utf8", mode: 384 });
2471
- if (imagesFile) {
2472
- fs11.writeFileSync(imagesFile, JSON.stringify(request.images), {
2473
- encoding: "utf8",
2474
- mode: 384
2475
- });
2476
- }
2477
- if (schemaFile) {
2478
- fs11.writeFileSync(schemaFile, JSON.stringify(request.schema, null, 2), {
2479
- encoding: "utf8",
2480
- mode: 384
2481
- });
2482
- }
2483
3153
  let agentCwd = selectedCwd;
2484
3154
  let branch;
2485
3155
  let worktree;
@@ -2495,7 +3165,9 @@ var AgentManager = class {
2495
3165
  }
2496
3166
  }
2497
3167
  try {
3168
+ admissionSignal.throwIfAborted();
2498
3169
  if (worktree && worktreeSetup?.trim()) await this.#worktrees.setup(id, worktreeSetup);
3170
+ admissionSignal.throwIfAborted();
2499
3171
  const writePolicy = capabilities2.writePolicy ? resolveChildWritePolicy(request, this.#parentWritePolicy, agentCwd) : void 0;
2500
3172
  const parentSessionId = this.#sessionId?.();
2501
3173
  const parentRunId = this.#parentLineage?.runId ?? (this.#currentDepth > 0 ? process.env.PI_FABRIC_PARENT_RUN : void 0);
@@ -2509,13 +3181,17 @@ var AgentManager = class {
2509
3181
  childIndex: this.#childIndex++,
2510
3182
  worker: true
2511
3183
  };
2512
- const sessionFile = request.forkSeed ? writeForkSession(request.forkSeed, agentCwd, path12.join(runDirectory, "fork-session"), request.thinkingTransfer) : request.sessionSeed ? writeHandoffSession(
3184
+ const seedOptions = durableSession ? { workerRole: true } : {};
3185
+ const handoffBudget = request.sessionSeed && request.handoffCompact ? await this.#resolveHandoffCompactionBudget?.(model, agentCwd) : void 0;
3186
+ admissionSignal.throwIfAborted();
3187
+ const sessionFile = request.forkSeed ? writeForkSession(request.forkSeed, agentCwd, path14.join(runDirectory, "fork-session"), request.thinkingTransfer, seedOptions) : request.sessionSeed ? writeHandoffSession(
2513
3188
  request.sessionSeed,
2514
3189
  agentCwd,
2515
- path12.join(runDirectory, "handoff-session"),
3190
+ path14.join(runDirectory, "handoff-session"),
2516
3191
  request.thinkingTransfer,
2517
3192
  request.handoffCompact,
2518
- request.handoffCompact ? await this.#resolveHandoffCompactionBudget?.(model, agentCwd) : void 0
3193
+ handoffBudget,
3194
+ seedOptions
2519
3195
  ) : request.sessionFile;
2520
3196
  const timeoutMs = effectiveAgentTimeoutMs(
2521
3197
  this.config.timeoutMs,
@@ -2530,7 +3206,7 @@ var AgentManager = class {
2530
3206
  const inheritedSessionPins = (runner === "pi" || runner === "pi-durable") && extensions ? this.#inheritedSessionPins(request) : void 0;
2531
3207
  const inheritedFullCodeMode = capabilities2.recursiveFabric && this.#fullCodeMode && extensions;
2532
3208
  const componentGuidance = recursive ? void 0 : this.#resolveParticipantGuidance?.({ ...model ? { model } : {}, runner })?.trim();
2533
- const systemPrompt = [request.systemPrompt?.trim(), componentGuidance].filter((section) => Boolean(section)).join("\n\n") || void 0;
3209
+ const systemPrompt = [request.systemPrompt?.trim(), request.childSkills?.preload, componentGuidance].filter((section) => Boolean(section)).join("\n\n") || void 0;
2534
3210
  const sessionExportDir = resolveSessionExportDir(this.config);
2535
3211
  const sessionExportFile = sessionExportDir ? sessionExportFileFor(sessionExportDir, agentCwd, id, /* @__PURE__ */ new Date()) : void 0;
2536
3212
  const traceContext = this.#traceContext(request, { runId: id, runner, name });
@@ -2563,7 +3239,7 @@ var AgentManager = class {
2563
3239
  return await this.#startHosted(hostedAdapter, launchContext, {
2564
3240
  request,
2565
3241
  release,
2566
- signal,
3242
+ signal: callerSignal,
2567
3243
  timeoutMs,
2568
3244
  files: { statusFile, lifecycleFile, logFile },
2569
3245
  ...clampedFrom ? { requestedThinking: clampedFrom } : {},
@@ -2572,6 +3248,7 @@ var AgentManager = class {
2572
3248
  });
2573
3249
  }
2574
3250
  const adapter = await this.#resolveTransport(request.transport ?? this.config.transport);
3251
+ admissionSignal.throwIfAborted();
2575
3252
  const workerArguments = [
2576
3253
  "--id",
2577
3254
  id,
@@ -2624,10 +3301,14 @@ var AgentManager = class {
2624
3301
  ...thinking ? ["--thinking", thinking] : [],
2625
3302
  ...serializedThinkingBounds ? ["--thinking-bounds", serializedThinkingBounds] : [],
2626
3303
  ...systemPrompt ? ["--system-prompt", systemPrompt] : [],
3304
+ ...request.childSkills ? ["--skills", JSON.stringify(request.childSkills.catalog)] : [],
2627
3305
  "--persist-session",
2628
3306
  String(request.persistSession === true),
3307
+ ...durableSession ? ["--durable-session", "true"] : [],
2629
3308
  "--model-admission",
2630
- this.config.modelAdmission ?? "strict",
3309
+ // An exact request is always strict: permissive admission accepts another model.
3310
+ request.modelMatch === "exact" ? "strict" : this.config.modelAdmission ?? "strict",
3311
+ ...request.modelMatch === "exact" ? ["--model-match", "exact"] : [],
2631
3312
  ...sessionFile ? ["--session-file", sessionFile] : [],
2632
3313
  ...sessionExportFile ? ["--session-export-file", sessionExportFile] : [],
2633
3314
  ...inheritedSessionPins && inheritedSessionPins.length > 0 ? ["--inherited-session-pins", serializeInheritedSessionPins(inheritedSessionPins)] : [],
@@ -2642,10 +3323,14 @@ var AgentManager = class {
2642
3323
  ...this.#identityId ? ["--owner-identity-id", this.#identityId] : [],
2643
3324
  ...request.runnerSessionId ? ["--runner-session-id", request.runnerSessionId] : [],
2644
3325
  "--run-root",
2645
- path12.join(runDirectory, "nested"),
3326
+ path14.join(runDirectory, "nested"),
2646
3327
  "--steer-file",
2647
3328
  steerFile,
2648
- ...this.config.childQuestions === "route" && capabilities2.questions ? ["--child-questions", String(this.config.childQuestionTimeoutMs ?? DEFAULT_CHILD_QUESTION_TIMEOUT_MS)] : [],
3329
+ ...this.config.childQuestions === "route" && capabilities2.questions ? [
3330
+ "--child-questions",
3331
+ String(this.config.childQuestionTimeoutMs ?? DEFAULT_CHILD_QUESTION_TIMEOUT_MS),
3332
+ ...request.holdQuestions === true ? ["--child-questions-hold", "1"] : []
3333
+ ] : [],
2649
3334
  ...schemaFile ? ["--schema-file", schemaFile] : [],
2650
3335
  ...branch ? ["--branch", branch] : [],
2651
3336
  ...worktree ? ["--worktree", worktree] : [],
@@ -2678,10 +3363,12 @@ var AgentManager = class {
2678
3363
  workerPath: runnerLaunch.workerPath,
2679
3364
  workerArguments: [...runnerLaunch.workerArguments]
2680
3365
  };
3366
+ admissionSignal.throwIfAborted();
2681
3367
  if (this.#closing) throw new Error("Fabric agent manager is closing");
3368
+ const recoveryPolicy = this.config.durableWorkerRecovery === true && residency === "durable" && runner === "pi-durable" && adapter.kind === "process" && process.platform !== "win32" ? this.#workerRecoveryPolicy() : void 0;
2682
3369
  const transport = await this.#launchTransport(adapter, launch);
2683
3370
  const lifecycle = createAgentLifecycle(release);
2684
- if (signal?.aborted || this.#closing) {
3371
+ if (admissionSignal.aborted || this.#closing) {
2685
3372
  await transport.stop();
2686
3373
  if (!await transport.isAlive().catch(() => true)) this.#unregisteredTransports.delete(transport);
2687
3374
  throw new Error("Agent launch aborted");
@@ -2706,9 +3393,11 @@ var AgentManager = class {
2706
3393
  launch,
2707
3394
  startupAttempts: 1,
2708
3395
  ...lifecycle,
2709
- abortSignal: signal,
3396
+ abortSignal: callerSignal,
2710
3397
  abortHandler: void 0,
2711
3398
  ...model ? { model } : {},
3399
+ ...request.modelMatch ? { modelMatch: request.modelMatch } : {},
3400
+ ...request.holdQuestions === true ? { holdQuestions: true } : {},
2712
3401
  ...thinking ? { thinking } : {},
2713
3402
  ...clampedFrom ? { requestedThinking: clampedFrom } : {},
2714
3403
  ...request.actorId ? { actorId: request.actorId } : {},
@@ -2731,18 +3420,29 @@ var AgentManager = class {
2731
3420
  },
2732
3421
  usageEmitted: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 }
2733
3422
  };
2734
- if (signal) {
3423
+ if (callerSignal) {
2735
3424
  managed.abortHandler = () => this.#handleCallerAbort(id);
2736
- signal.addEventListener("abort", managed.abortHandler, { once: true });
3425
+ callerSignal.addEventListener("abort", managed.abortHandler, { once: true });
2737
3426
  }
2738
3427
  this.#runs.set(id, managed);
2739
3428
  this.#unregisteredTransports.delete(transport);
3429
+ if (recoveryPolicy !== void 0) {
3430
+ managed.workerRecovery = { deadlineAt: Date.now() + timeoutMs, policy: recoveryPolicy };
3431
+ this.#persistWorkerRecovery(managed);
3432
+ }
2740
3433
  this.#invalidateUiList();
2741
3434
  void this.#monitor(managed, timeoutMs);
2742
3435
  return this.#handleInfo(managed, "running");
2743
3436
  } catch (error) {
2744
3437
  release();
2745
- if (worktree) await this.#worktrees.cleanup(id, true).catch(() => false);
3438
+ if (worktree) {
3439
+ const lease = this.#worktrees.get(id);
3440
+ try {
3441
+ await this.#worktrees.cleanup(id, true);
3442
+ } catch (cleanupError) {
3443
+ throw worktreeRollbackError(lease?.gitRoot ?? selectedCwd, worktree, branch, error, cleanupError);
3444
+ }
3445
+ }
2746
3446
  throw error;
2747
3447
  }
2748
3448
  }
@@ -2775,9 +3475,9 @@ var AgentManager = class {
2775
3475
  const hosted = await HostedRun.prepare(
2776
3476
  adapter,
2777
3477
  { ...context, idempotencyKey: context.id },
2778
- { ...launch.files, stateFile: path12.join(context.runDirectory, HOSTED_STATE_FILE) },
3478
+ { ...launch.files, stateFile: path14.join(context.runDirectory, HOSTED_STATE_FILE) },
2779
3479
  record,
2780
- this.#hostedHooks(() => managed)
3480
+ this.#hostedHooks(() => managed, launch.request.holdQuestions === true)
2781
3481
  );
2782
3482
  if (launch.signal?.aborted || this.#closing) {
2783
3483
  hosted.abandon("Agent launch aborted before the hosted run was submitted");
@@ -2793,13 +3493,14 @@ var AgentManager = class {
2793
3493
  void this.#monitor(managed, launch.timeoutMs);
2794
3494
  return this.#handleInfo(managed, "running");
2795
3495
  }
2796
- #hostedHooks(managed) {
3496
+ #hostedHooks(managed, holdQuestions = false) {
2797
3497
  return {
2798
3498
  questionTimeoutMs: this.config.childQuestionTimeoutMs ?? DEFAULT_CHILD_QUESTION_TIMEOUT_MS,
3499
+ ...holdQuestions ? { holdQuestions: true } : {},
2799
3500
  ...this.config.childQuestions === "route" && this.#onChildQuestion ? {
2800
- ask: (question) => {
3501
+ ask: (question, onDecision) => {
2801
3502
  const run = managed();
2802
- return run ? this.#askParent(run, question) : Promise.resolve({ cancelled: true });
3503
+ return run ? this.#askParent(run, question, onDecision) : Promise.resolve({ cancelled: true });
2803
3504
  }
2804
3505
  } : {}
2805
3506
  };
@@ -2835,6 +3536,7 @@ var AgentManager = class {
2835
3536
  ...options.requestedThinking ? { requestedThinking: options.requestedThinking } : {},
2836
3537
  ...record.branch ? { branch: record.branch } : {},
2837
3538
  ...record.worktree ? { worktree: record.worktree } : {},
3539
+ ...hosted.hooks.holdQuestions ? { holdQuestions: true } : {},
2838
3540
  settled: false,
2839
3541
  background: recovered,
2840
3542
  lastLivenessCheckAt: 0,
@@ -2860,17 +3562,17 @@ var AgentManager = class {
2860
3562
  async recoverHostedRuns() {
2861
3563
  let entries;
2862
3564
  try {
2863
- entries = fs11.readdirSync(this.#runRoot);
3565
+ entries = fs13.readdirSync(this.#runRoot);
2864
3566
  } catch {
2865
3567
  return [];
2866
3568
  }
2867
3569
  const recovered = [];
2868
3570
  for (const entry of entries) {
2869
3571
  if (this.#closing || this.#runs.has(entry) || !/^[0-9a-f]{32}$/.test(entry)) continue;
2870
- const runDirectory = path12.join(this.#runRoot, entry);
2871
- const statusFile = path12.join(runDirectory, "status.json");
3572
+ const runDirectory = path14.join(this.#runRoot, entry);
3573
+ const statusFile = path14.join(runDirectory, "status.json");
2872
3574
  const record = readRecord(statusFile);
2873
- const state = readHostedRunState(path12.join(runDirectory, HOSTED_STATE_FILE));
3575
+ const state = readHostedRunState(path14.join(runDirectory, HOSTED_STATE_FILE));
2874
3576
  if (!record?.hosted || !state || record.id !== entry || state.context.id !== entry || terminalStatuses.has(record.status)) {
2875
3577
  continue;
2876
3578
  }
@@ -2902,12 +3604,12 @@ var AgentManager = class {
2902
3604
  state,
2903
3605
  {
2904
3606
  statusFile,
2905
- lifecycleFile: path12.join(runDirectory, "lifecycle.jsonl"),
2906
- logFile: path12.join(runDirectory, "events.jsonl"),
2907
- stateFile: path12.join(runDirectory, HOSTED_STATE_FILE)
3607
+ lifecycleFile: path14.join(runDirectory, "lifecycle.jsonl"),
3608
+ logFile: path14.join(runDirectory, "events.jsonl"),
3609
+ stateFile: path14.join(runDirectory, HOSTED_STATE_FILE)
2908
3610
  },
2909
3611
  record,
2910
- this.#hostedHooks(() => managed)
3612
+ this.#hostedHooks(() => managed, state.holdQuestions === true)
2911
3613
  );
2912
3614
  managed = this.#adoptHosted(hosted, { release: () => {
2913
3615
  }, recovered: true });
@@ -2917,6 +3619,241 @@ var AgentManager = class {
2917
3619
  }
2918
3620
  return recovered;
2919
3621
  }
3622
+ #workerRecoveryPolicy() {
3623
+ return JSON.stringify({
3624
+ config: this.config,
3625
+ worker: this.#workerPath,
3626
+ pi: this.#piBinary,
3627
+ claude: this.#claudeBinary,
3628
+ veda: this.#vedaBinary,
3629
+ extension: this.#fabricExtensionPath,
3630
+ project: this.#projectRoot,
3631
+ mesh: this.#meshRoot,
3632
+ host: this.#hostId,
3633
+ identity: this.#identityId,
3634
+ depth: this.#currentDepth,
3635
+ fullCodeMode: this.#fullCodeMode,
3636
+ writePolicy: this.#parentWritePolicy,
3637
+ lineage: this.#parentLineage,
3638
+ thinkingBounds: this.#thinkingBounds?.(),
3639
+ kernel: this.#kernel(),
3640
+ pythonRuntime: this.#pythonRuntime(),
3641
+ executor: this.#executorRuntime?.(),
3642
+ inheritedTools: this.#inheritedToolAllowlist?.entries,
3643
+ // Exact fabric_exec authority is stored outside entries; pin both so
3644
+ // revoking recursion cannot reuse an otherwise identical launch receipt.
3645
+ inheritedFabricExec: this.#inheritedToolAllowlist?.fabricExec
3646
+ });
3647
+ }
3648
+ #persistWorkerRecovery(managed) {
3649
+ if (!managed.workerRecovery) return;
3650
+ if (managed.stopRequested || managed.settled) {
3651
+ removeWorkerRecovery(managed.runDirectory);
3652
+ return;
3653
+ }
3654
+ const pid = Number(managed.transport.sessionId);
3655
+ if (!Number.isSafeInteger(pid) || pid <= 0) {
3656
+ delete managed.workerRecovery;
3657
+ removeWorkerRecovery(managed.runDirectory);
3658
+ return;
3659
+ }
3660
+ const recovery = {
3661
+ format: WORKER_RECOVERY_FORMAT,
3662
+ id: managed.id,
3663
+ runner: "pi-durable",
3664
+ deadlineAt: managed.workerRecovery.deadlineAt,
3665
+ pid,
3666
+ launch: {
3667
+ id: managed.launch.id,
3668
+ name: managed.launch.name,
3669
+ cwd: managed.launch.cwd,
3670
+ workerPath: managed.launch.workerPath,
3671
+ workerArguments: [...managed.launch.workerArguments]
3672
+ },
3673
+ writtenAt: Date.now()
3674
+ };
3675
+ authorizeWorkerRecovery(managed.runDirectory, recovery, managed.workerRecovery.policy);
3676
+ writeWorkerRecovery(managed.runDirectory, recovery);
3677
+ }
3678
+ /**
3679
+ * Re-attach opted-in pi-durable worker runs (agents.durableWorkerRecovery)
3680
+ * left unfinished under this run root by an earlier host. A verified live
3681
+ * worker is adopted; a dead one is relaunched on its own durable journal
3682
+ * with its progress carried over; a run whose deadline passed, or whose
3683
+ * worker Fabric cannot verify either way, settles failed with outcome
3684
+ * "indeterminate" instead of being guessed at.
3685
+ */
3686
+ async recoverWorkerRuns() {
3687
+ let entries;
3688
+ try {
3689
+ entries = fs13.readdirSync(this.#runRoot);
3690
+ } catch {
3691
+ return [];
3692
+ }
3693
+ const recovered = [];
3694
+ for (const entry of entries) {
3695
+ if (this.#closing || this.#runs.has(entry) || !/^[0-9a-f]{32}$/.test(entry)) continue;
3696
+ const runDirectory = path14.join(this.#runRoot, entry);
3697
+ const recovery = readWorkerRecovery(runDirectory);
3698
+ const statusFile = path14.join(runDirectory, "status.json");
3699
+ const record = readRecord(statusFile);
3700
+ if (!recovery || recovery.id !== entry) {
3701
+ if (!hasWorkerRecovery(runDirectory)) continue;
3702
+ removeWorkerRecovery(runDirectory);
3703
+ if (record?.id === entry && !record.hosted && (!terminalStatuses.has(record.status) || record.status === "stopped")) {
3704
+ const { currentTool: _tool, blockedOn: _blocked, sleeping: _sleeping, ...rest } = record;
3705
+ const now2 = Date.now();
3706
+ writeRecord(statusFile, {
3707
+ ...rest,
3708
+ status: "failed",
3709
+ outcome: "indeterminate",
3710
+ error: "Invalid durable worker recovery marker; the run outcome is indeterminate",
3711
+ updatedAt: now2,
3712
+ finishedAt: now2
3713
+ });
3714
+ }
3715
+ continue;
3716
+ }
3717
+ if (!record || record.id !== entry) {
3718
+ const now2 = Date.now();
3719
+ removeWorkerRecovery(runDirectory);
3720
+ writeRecord(statusFile, {
3721
+ id: entry,
3722
+ name: recovery.launch.name,
3723
+ task: "",
3724
+ runner: "pi-durable",
3725
+ cwd: recovery.launch.cwd,
3726
+ residency: "durable",
3727
+ transport: "process",
3728
+ status: "failed",
3729
+ outcome: "indeterminate",
3730
+ error: "Durable worker recovery has no valid initial status; the run outcome is indeterminate",
3731
+ startedAt: recovery.writtenAt,
3732
+ updatedAt: now2,
3733
+ finishedAt: now2,
3734
+ turns: 0,
3735
+ toolCalls: 0,
3736
+ text: "",
3737
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 }
3738
+ });
3739
+ continue;
3740
+ }
3741
+ if (record.hosted) continue;
3742
+ if (terminalStatuses.has(record.status) && record.status !== "stopped") {
3743
+ removeWorkerRecovery(runDirectory);
3744
+ continue;
3745
+ }
3746
+ const now = Date.now();
3747
+ const indeterminate = (reason) => {
3748
+ const { currentTool: _tool, blockedOn: _blocked, sleeping: _sleeping, ...rest } = record;
3749
+ removeWorkerRecovery(runDirectory);
3750
+ writeRecord(statusFile, {
3751
+ ...rest,
3752
+ status: "failed",
3753
+ error: `${reason}; the run outcome is indeterminate`,
3754
+ outcome: "indeterminate",
3755
+ finishedAt: now,
3756
+ updatedAt: now
3757
+ });
3758
+ };
3759
+ const runnerAdapter = getAgentRunner("pi-durable");
3760
+ if (runnerAdapter?.kind !== "worker") {
3761
+ indeterminate("The pi-durable runner is not registered in this process");
3762
+ continue;
3763
+ }
3764
+ const policy = this.#workerRecoveryPolicy();
3765
+ const authority = readWorkerRecoveryAuthority(runDirectory, policy);
3766
+ if (!authority || workerRecoveryMismatch(recovery, { runDirectory, workerPath: this.#workerPath, cwd: record.cwd, policy })) {
3767
+ indeterminate("The recovery file does not match this host");
3768
+ continue;
3769
+ }
3770
+ if (authority.deadlineAt <= now) {
3771
+ indeterminate("The durable worker run passed its deadline while no resident host owned it");
3772
+ continue;
3773
+ }
3774
+ let liveness = probeWorker(authority.pid, entry);
3775
+ if (record.status === "stopped" && liveness === "alive") {
3776
+ liveness = await this.#waitForWorkerExit(authority.pid, entry);
3777
+ if (liveness === "alive") {
3778
+ indeterminate(`Worker process ${recovery.pid} recorded a stop but did not exit`);
3779
+ continue;
3780
+ }
3781
+ }
3782
+ if (liveness === "unknown") {
3783
+ indeterminate(`Fabric cannot verify whether worker process ${recovery.pid} is still running`);
3784
+ continue;
3785
+ }
3786
+ if (liveness === "dead" && !fs13.existsSync(authority.launch.workerPath)) {
3787
+ indeterminate(`The worker entry ${recovery.launch.workerPath} no longer exists`);
3788
+ continue;
3789
+ }
3790
+ const argument = (name) => {
3791
+ const index = authority.launch.workerArguments.indexOf(`--${name}`);
3792
+ return index < 0 ? void 0 : authority.launch.workerArguments[index + 1];
3793
+ };
3794
+ const kernel = argument("kernel");
3795
+ const model = argument("model");
3796
+ const thinking = argument("thinking");
3797
+ const branch = argument("branch");
3798
+ const worktree = argument("worktree");
3799
+ const adapter = await this.#resolveTransport("process");
3800
+ const managed = {
3801
+ id: entry,
3802
+ name: record.name,
3803
+ task: record.task,
3804
+ runner: "pi-durable",
3805
+ runnerAdapter,
3806
+ ...kernel === "typescript" || kernel === "python" ? { kernel } : {},
3807
+ recursive: JSON.parse(argument("granted-risks") ?? "[]").includes("agent"),
3808
+ residency: "durable",
3809
+ cwd: record.cwd,
3810
+ statusFile,
3811
+ lifecycleFile: path14.join(runDirectory, "lifecycle.jsonl"),
3812
+ // Events before this point reached the previous host's ledger.
3813
+ lifecycleOffset: fileSize(path14.join(runDirectory, "lifecycle.jsonl")),
3814
+ lifecycleRemainder: Buffer.alloc(0),
3815
+ runDirectory,
3816
+ transport: adoptedWorkerHandle(authority.pid, entry),
3817
+ adapter,
3818
+ launch: authority.launch,
3819
+ startupAttempts: 1,
3820
+ ...createAgentLifecycle(() => {
3821
+ }),
3822
+ abortSignal: void 0,
3823
+ abortHandler: void 0,
3824
+ ...model ? { model } : {},
3825
+ ...thinking ? { thinking } : {},
3826
+ ...branch ? { branch } : {},
3827
+ ...worktree ? { worktree } : {},
3828
+ workerRecovery: { deadlineAt: authority.deadlineAt, policy },
3829
+ settled: false,
3830
+ background: true,
3831
+ lastLivenessCheckAt: 0,
3832
+ resumeAttempts: 0,
3833
+ stopRequested: false,
3834
+ observedProgress: { turns: record.turns, toolCalls: record.toolCalls, usage: { ...record.usage } },
3835
+ usageEmitted: { ...record.usage }
3836
+ };
3837
+ this.#runs.set(entry, managed);
3838
+ this.#invalidateUiList();
3839
+ if (liveness === "dead") {
3840
+ managed.resumeAttempts += 1;
3841
+ const { turns, toolCalls, usage } = managed.observedProgress;
3842
+ const relaunched = await this.#relaunch(managed, record, {
3843
+ task: managed.task,
3844
+ carryOver: { turns, toolCalls, usage: { ...usage } }
3845
+ });
3846
+ if (!relaunched) {
3847
+ const failed = readRecord(statusFile) ?? record;
3848
+ this.#settle(managed, this.#withTransportMetadata(failed, managed));
3849
+ continue;
3850
+ }
3851
+ }
3852
+ void this.#monitor(managed, Math.max(0, recovery.deadlineAt - Date.now()));
3853
+ recovered.push(entry);
3854
+ }
3855
+ return recovered;
3856
+ }
2920
3857
  /** Park or resume a hosted run whose runner declares `sleep`. */
2921
3858
  async sleep(id) {
2922
3859
  await this.#requireHosted(id, "sleep").park("sleep");
@@ -2934,6 +3871,15 @@ var AgentManager = class {
2934
3871
  return this.wait(handle.id);
2935
3872
  }
2936
3873
  async wait(id) {
3874
+ const queued = this.#queued.get(id);
3875
+ if (queued) {
3876
+ queued.background = false;
3877
+ const outcome = await queued.outcome;
3878
+ if ("result" in outcome) {
3879
+ this.#onResultConsumed?.(id);
3880
+ return structuredClone(outcome.result);
3881
+ }
3882
+ }
2937
3883
  const managed = this.#requireRun(id);
2938
3884
  managed.background = false;
2939
3885
  if (!managed.settled) {
@@ -2942,7 +3888,7 @@ var AgentManager = class {
2942
3888
  this.#onResultConsumed?.(id);
2943
3889
  return result;
2944
3890
  }
2945
- const record = readRecord(managed.statusFile) ?? managed.latestRecord;
3891
+ const record = this.#readManagedRecord(managed);
2946
3892
  if (!record || !terminalStatuses.has(record.status)) {
2947
3893
  throw new Error(`Agent ${id} settled without a result`);
2948
3894
  }
@@ -2950,10 +3896,18 @@ var AgentManager = class {
2950
3896
  return this.#withTransportMetadata(record, managed);
2951
3897
  }
2952
3898
  markForeground(id) {
2953
- this.#requireRun(id).background = false;
3899
+ const queued = this.#runs.has(id) ? void 0 : this.#queued.get(id);
3900
+ if (queued) queued.background = false;
3901
+ else this.#requireRun(id).background = false;
2954
3902
  this.#onResultConsumed?.(id);
2955
3903
  }
2956
3904
  detachSignal(id) {
3905
+ const queued = this.#queued.get(id);
3906
+ if (queued) {
3907
+ queued.background = true;
3908
+ if (queued.result) this.#notifyBackgroundComplete(queued, queued.result);
3909
+ return;
3910
+ }
2957
3911
  this.#detach(this.#requireRun(id), "caller detached; the run continues");
2958
3912
  }
2959
3913
  /**
@@ -2982,7 +3936,7 @@ var AgentManager = class {
2982
3936
  if (managed.background) return;
2983
3937
  managed.background = true;
2984
3938
  if (managed.settled) {
2985
- const record = readRecord(managed.statusFile) ?? managed.latestRecord;
3939
+ const record = this.#readManagedRecord(managed);
2986
3940
  if (record && terminalStatuses.has(record.status)) {
2987
3941
  this.#notifyBackgroundComplete(managed, this.#withTransportMetadata(record, managed));
2988
3942
  }
@@ -3010,9 +3964,17 @@ var AgentManager = class {
3010
3964
  if (record.usage[key] > seen.usage[key]) seen.usage[key] = record.usage[key];
3011
3965
  }
3012
3966
  }
3967
+ #readManagedRecord(managed) {
3968
+ if (managed.settled && !managed.hosted && managed.unpersistedResult) {
3969
+ return managed.unpersistedResult;
3970
+ }
3971
+ return managed.settled ? readRecord(managed.statusFile) ?? managed.latestRecord : managed.latestRecord ?? readRecord(managed.statusFile);
3972
+ }
3013
3973
  status(id) {
3974
+ const queued = this.#runs.has(id) ? void 0 : this.#queued.get(id);
3975
+ if (queued) return queued.result ? structuredClone(queued.result) : this.#queuedHandle(queued);
3014
3976
  const managed = this.#requireRun(id);
3015
- const record = managed.settled ? readRecord(managed.statusFile) ?? managed.latestRecord : managed.latestRecord ?? readRecord(managed.statusFile);
3977
+ const record = this.#readManagedRecord(managed);
3016
3978
  if (!record) return this.#handleInfo(managed, "running");
3017
3979
  managed.latestRecord = record;
3018
3980
  if (!managed.latestUiRecord) {
@@ -3024,7 +3986,18 @@ var AgentManager = class {
3024
3986
  return result;
3025
3987
  }
3026
3988
  list() {
3027
- return [...this.#runs.keys()].map((id) => this.status(id));
3989
+ return [.../* @__PURE__ */ new Set([...this.#runs.keys(), ...this.#queued.keys()])].map((id) => this.status(id));
3990
+ }
3991
+ /** Unsettled runs, each with the title of a child question it waits on. */
3992
+ activity() {
3993
+ return [
3994
+ ...[...this.#runs.values()].filter((managed) => !managed.settled).map((managed) => ({
3995
+ id: managed.id,
3996
+ name: managed.actorName ?? managed.name,
3997
+ ...managed.openQuestions?.length ? { question: managed.openQuestions.at(-1).title } : {}
3998
+ })),
3999
+ ...[...this.#queued.values()].filter((queued) => !queued.result && !this.#runs.has(queued.id)).map((queued) => ({ id: queued.id, name: queued.name }))
4000
+ ];
3028
4001
  }
3029
4002
  listForUi() {
3030
4003
  if (this.#uiListCache?.revision === this.#uiListRevision) {
@@ -3039,7 +4012,7 @@ var AgentManager = class {
3039
4012
  const value = runs.filter((managed) => visible.has(managed)).map((managed) => {
3040
4013
  let record = managed.latestUiRecord;
3041
4014
  if (!record) {
3042
- const latest = managed.latestRecord ?? readRecord(managed.statusFile);
4015
+ const latest = managed.latestRecord ?? this.#readManagedRecord(managed);
3043
4016
  if (!latest) return this.#handleInfo(managed, "running");
3044
4017
  managed.latestRecord = latest;
3045
4018
  record = compactUiRecord(latest);
@@ -3049,6 +4022,11 @@ var AgentManager = class {
3049
4022
  compactUiRecord(this.#withTransportMetadata(record, managed))
3050
4023
  );
3051
4024
  });
4025
+ for (const queued of this.#queued.values()) {
4026
+ if (!this.#runs.has(queued.id)) {
4027
+ value.push(queued.result ? compactUiRecord(structuredClone(queued.result)) : this.#queuedHandle(queued));
4028
+ }
4029
+ }
3052
4030
  this.#uiListCache = { revision: this.#uiListRevision, value };
3053
4031
  return value;
3054
4032
  }
@@ -3068,8 +4046,17 @@ var AgentManager = class {
3068
4046
  return structuredClone(value);
3069
4047
  }
3070
4048
  async stop(id) {
4049
+ const queued = this.#runs.has(id) ? void 0 : this.#queued.get(id);
4050
+ if (queued) {
4051
+ queued.background = false;
4052
+ queued.stopRequested = true;
4053
+ queued.control.abort();
4054
+ const outcome = await queued.outcome;
4055
+ if ("result" in outcome) return structuredClone(outcome.result);
4056
+ }
3071
4057
  const managed = this.#requireRun(id);
3072
4058
  managed.stopRequested = true;
4059
+ if (managed.workerRecovery) removeWorkerRecovery(managed.runDirectory);
3073
4060
  if (managed.settled) return this.wait(id);
3074
4061
  managed.background = false;
3075
4062
  const existing = readRecord(managed.statusFile);
@@ -3082,14 +4069,22 @@ var AgentManager = class {
3082
4069
  await this.#stopWorkerRunner(managed);
3083
4070
  await managed.transport.stop();
3084
4071
  await this.#waitForTransportExit(managed);
3085
- const terminal = readRecord(managed.statusFile);
3086
- const record = terminal && terminalStatuses.has(terminal.status) ? this.#withTransportMetadata(terminal, managed) : failedRecord(managed, "stopped", "Agent stopped");
3087
- if (!terminal || !terminalStatuses.has(terminal.status)) writeRecord(managed.statusFile, record);
4072
+ const terminal2 = readRecord(managed.statusFile);
4073
+ const record = terminal2 && terminalStatuses.has(terminal2.status) ? this.#withTransportMetadata(terminal2, managed) : failedRecord(managed, "stopped", "Agent stopped");
4074
+ if (!terminal2 || !terminalStatuses.has(terminal2.status)) writeRecord(managed.statusFile, record);
3088
4075
  await this.#captureWorktree(managed);
3089
4076
  this.#settle(managed, record);
3090
4077
  return record;
3091
4078
  }
3092
4079
  async cleanup(id, deleteBranch = false) {
4080
+ const queued = this.#runs.has(id) ? void 0 : this.#queued.get(id);
4081
+ if (queued) {
4082
+ if (!queued.result) throw new Error("Cannot clean up a queued agent; stop it first");
4083
+ this.#onResultConsumed?.(id);
4084
+ this.#queued.delete(id);
4085
+ this.#invalidateUiList();
4086
+ return { cleaned: true };
4087
+ }
3093
4088
  const managed = this.#requireRun(id);
3094
4089
  if (!managed.settled) throw new Error("Cannot clean up a running agent");
3095
4090
  this.markForeground(id);
@@ -3100,15 +4095,15 @@ var AgentManager = class {
3100
4095
  this.#runs.delete(id);
3101
4096
  this.#pruneRetainedUiRecords();
3102
4097
  this.#invalidateUiList();
3103
- return { cleaned: cleaned || !fs11.existsSync(managed.runDirectory) };
4098
+ return { cleaned: cleaned || !fs13.existsSync(managed.runDirectory) };
3104
4099
  }
3105
4100
  readLog(id, opts = {}) {
3106
4101
  const managed = this.#requireRun(id);
3107
4102
  const runDirectory = managed.runDirectory;
3108
- const logFile = path12.join(runDirectory, "events.jsonl");
4103
+ const logFile = path14.join(runDirectory, "events.jsonl");
3109
4104
  const lines = Math.max(1, Math.min(opts.lines ?? 200, 5e3));
3110
4105
  const page = readJsonlPage(logFile, lines, opts.before);
3111
- const statusRecord = readRecord(path12.join(runDirectory, "status.json"));
4106
+ const statusRecord = readRecord(path14.join(runDirectory, "status.json"));
3112
4107
  return {
3113
4108
  id,
3114
4109
  runDirectory,
@@ -3183,10 +4178,10 @@ var AgentManager = class {
3183
4178
  `Fabric agent ${id} already finished (${record.status}); steering has no target`
3184
4179
  );
3185
4180
  }
3186
- const steerFile = path12.join(managed.runDirectory, "steer.jsonl");
3187
- const messageId = randomUUID5();
4181
+ const steerFile = path14.join(managed.runDirectory, "steer.jsonl");
4182
+ const messageId = randomUUID6();
3188
4183
  const line = JSON.stringify({ ...entry, id: messageId, ts: Date.now() }) + "\n";
3189
- fs11.appendFileSync(steerFile, line, { encoding: "utf8", mode: 384 });
4184
+ fs13.appendFileSync(steerFile, line, { encoding: "utf8", mode: 384 });
3190
4185
  return { queued: true, messageId };
3191
4186
  }
3192
4187
  close() {
@@ -3202,14 +4197,26 @@ var AgentManager = class {
3202
4197
  const detached = [...this.#runs.values()].filter(
3203
4198
  (managed) => !managed.settled && managed.hosted && managed.residency === "durable"
3204
4199
  );
3205
- for (const managed of detached) managed.hosted.detach();
4200
+ for (const managed of detached) {
4201
+ managed.hosted.detach();
4202
+ managed.questions?.abort(new Error("Fabric resident host detached the run"));
4203
+ }
4204
+ await Promise.allSettled(detached.flatMap((managed) => [...managed.asks ?? []]));
4205
+ for (const managed of this.#runs.values()) {
4206
+ if (!managed.settled && !managed.stopRequested && managed.workerRecovery && managed.residency === "durable") {
4207
+ managed.workerDetached = true;
4208
+ detached.push(managed);
4209
+ }
4210
+ }
3206
4211
  const running = [...this.#runs.values()].filter((managed) => !managed.settled && !detached.includes(managed));
3207
4212
  for (const managed of running) managed.hosted?.markShutdown();
3208
4213
  await Promise.allSettled(running.map((managed) => this.stop(managed.id)));
3209
4214
  await Promise.allSettled([...this.#spawns]);
3210
4215
  await Promise.allSettled([...this.#launches]);
3211
4216
  const all = [...this.#runs.values()];
3212
- await Promise.allSettled(all.map((managed) => this.#waitForTransportExit(managed)));
4217
+ await Promise.allSettled(
4218
+ all.filter((managed) => !managed.workerDetached).map((managed) => this.#waitForTransportExit(managed))
4219
+ );
3213
4220
  const transports2 = [...all.map((managed) => managed.transport), ...this.#unregisteredTransports];
3214
4221
  const alive = await Promise.all(transports2.map((transport) => transport.isAlive().catch(() => true)));
3215
4222
  if (detached.length === 0 && !alive.some(Boolean)) {
@@ -3227,7 +4234,7 @@ var AgentManager = class {
3227
4234
  removeEmptyRunRoot(this.#runRoot);
3228
4235
  }
3229
4236
  if (storageSafe && this.#budgetOwned && this.#budget) {
3230
- await removeTree(path12.dirname(this.#budget.file)).catch(() => void 0);
4237
+ await removeTree(path14.dirname(this.#budget.file)).catch(() => void 0);
3231
4238
  }
3232
4239
  }
3233
4240
  if (this.#budgetOwned) clearOwnedBudgetEnv();
@@ -3263,13 +4270,13 @@ var AgentManager = class {
3263
4270
  }
3264
4271
  const expired = [...this.#runs.values()].filter((managed) => {
3265
4272
  if (!managed.settled || managed.actorId) return false;
3266
- const record = readRecord(managed.statusFile) ?? managed.latestRecord;
4273
+ const record = this.#readManagedRecord(managed);
3267
4274
  const finishedAt = record?.finishedAt ?? record?.updatedAt;
3268
4275
  return typeof finishedAt === "number" && now - finishedAt >= this.#retention.oneShotRunMs;
3269
4276
  });
3270
4277
  for (const managed of expired) {
3271
4278
  await removeTree(managed.runDirectory).catch(() => void 0);
3272
- if (!fs11.existsSync(managed.runDirectory)) this.#runs.delete(managed.id);
4279
+ if (!fs13.existsSync(managed.runDirectory)) this.#runs.delete(managed.id);
3273
4280
  }
3274
4281
  if (expired.length > 0) {
3275
4282
  this.#pruneRetainedUiRecords();
@@ -3282,6 +4289,16 @@ var AgentManager = class {
3282
4289
  if (runner.kind !== "worker" || !runner.stop) return;
3283
4290
  await Promise.resolve().then(() => runner.stop({ id: managed.id, runDirectory: managed.runDirectory })).catch(() => void 0);
3284
4291
  }
4292
+ /** Bounded like #waitForTransportExit; returns the last liveness seen. */
4293
+ async #waitForWorkerExit(pid, id) {
4294
+ const deadline = Date.now() + TRANSPORT_EXIT_GRACE_MS * 7;
4295
+ let liveness = probeWorker(pid, id);
4296
+ while (liveness === "alive" && Date.now() < deadline && !this.#closing) {
4297
+ await delay(AGENT_STATUS_POLL_INTERVAL_MS);
4298
+ liveness = probeWorker(pid, id);
4299
+ }
4300
+ return liveness;
4301
+ }
3285
4302
  async #waitForTransportExit(managed) {
3286
4303
  const deadline = Date.now() + TRANSPORT_EXIT_GRACE_MS * 7;
3287
4304
  const pollIntervalMs = managed.transport.livenessPollIntervalMs ?? AGENT_STATUS_POLL_INTERVAL_MS;
@@ -3290,7 +4307,10 @@ var AgentManager = class {
3290
4307
  }
3291
4308
  }
3292
4309
  async #retryStartup(managed, record, deadline) {
3293
- if (managed.hosted || // A custom worker that already made progress is never re-run blind.
4310
+ if (managed.hosted || // Decided first, from the exit status and the fixed prefix: no text
4311
+ // classifier below may see a pin error, because a model id can spell
4312
+ // "missing credentials".
4313
+ managed.modelMatch === "exact" && isModelPinFailure(record) || // A custom worker that already made progress is never re-run blind.
3294
4314
  !BUILT_IN_RUNNER_IDS.has(managed.runner) && this.#observedWork(managed) || managed.startupAttempts >= AGENT_STARTUP_MAX_ATTEMPTS || managed.settled || this.#closing || managed.abortSignal?.aborted || record.status !== "failed" || !((managed.runner === "pi" || managed.runner === "pi-durable") && retryablePiStartupError(record.error) || transportExitedWithoutResult(record.error)) || record.turns !== 0 || record.toolCalls !== 0 || record.usage.input !== 0 || record.usage.output !== 0 || record.usage.cacheRead !== 0 || record.usage.cacheWrite !== 0) {
3295
4315
  return false;
3296
4316
  }
@@ -3314,7 +4334,7 @@ var AgentManager = class {
3314
4334
  if (
3315
4335
  // Fabric never re-prompts a hosted run, and only its own worker
3316
4336
  // understands the continuation task and --carry-over prefix.
3317
- managed.hosted || !BUILT_IN_RUNNER_IDS.has(managed.runner) || managed.settled || this.#closing || managed.stopRequested || managed.resumeAttempts >= AGENT_RESUME_MAX_ATTEMPTS || !this.#observedWork(managed) || !recoverableStop(record)
4337
+ managed.hosted || managed.modelMatch === "exact" && isModelPinFailure(record) || !BUILT_IN_RUNNER_IDS.has(managed.runner) || managed.settled || this.#closing || managed.stopRequested || managed.resumeAttempts >= AGENT_RESUME_MAX_ATTEMPTS || !this.#observedWork(managed) || !recoverableStop(record)
3318
4338
  ) {
3319
4339
  return false;
3320
4340
  }
@@ -3341,7 +4361,7 @@ var AgentManager = class {
3341
4361
  async #relaunch(managed, record, resume) {
3342
4362
  try {
3343
4363
  if (managed.runner === "pi" || managed.runner === "pi-durable") {
3344
- const model = await this.#prepareModel(managed.model);
4364
+ const model = await this.#prepareModel(managed.model, managed.modelMatch);
3345
4365
  const modelIndex = managed.launch.workerArguments.indexOf("--model");
3346
4366
  if (model) {
3347
4367
  if (modelIndex >= 0) managed.launch.workerArguments[modelIndex + 1] = model;
@@ -3352,8 +4372,15 @@ var AgentManager = class {
3352
4372
  delete managed.model;
3353
4373
  }
3354
4374
  }
4375
+ if (managed.workerRecovery) {
4376
+ setWorkerArgument(
4377
+ managed.launch.workerArguments,
4378
+ "timeout-ms",
4379
+ String(Math.max(1, managed.workerRecovery.deadlineAt - Date.now()))
4380
+ );
4381
+ }
3355
4382
  if (resume) {
3356
- fs11.writeFileSync(path12.join(managed.runDirectory, "task.txt"), resume.task, {
4383
+ fs13.writeFileSync(path14.join(managed.runDirectory, "task.txt"), resume.task, {
3357
4384
  encoding: "utf8",
3358
4385
  mode: 384
3359
4386
  });
@@ -3375,10 +4402,14 @@ var AgentManager = class {
3375
4402
  }
3376
4403
  }
3377
4404
  this.#drainLifecycle(managed);
3378
- fs11.rmSync(managed.statusFile, { force: true });
3379
4405
  if (managed.settled || this.#closing || managed.stopRequested) return false;
4406
+ fs13.rmSync(managed.statusFile, { force: true });
4407
+ managed.lifecycleOffset = 0;
4408
+ managed.lifecycleRemainder = Buffer.alloc(0);
4409
+ fs13.rmSync(managed.lifecycleFile, { force: true });
3380
4410
  managed.transport = await this.#launchTransport(managed.adapter, managed.launch);
3381
4411
  this.#unregisteredTransports.delete(managed.transport);
4412
+ if (managed.workerRecovery) this.#persistWorkerRecovery(managed);
3382
4413
  if (managed.settled || this.#closing || managed.stopRequested) {
3383
4414
  await managed.transport.stop().catch(() => void 0);
3384
4415
  return false;
@@ -3386,9 +4417,6 @@ var AgentManager = class {
3386
4417
  delete managed.latestRecord;
3387
4418
  delete managed.latestUiRecord;
3388
4419
  managed.lastLivenessCheckAt = 0;
3389
- managed.lifecycleOffset = 0;
3390
- managed.lifecycleRemainder = Buffer.alloc(0);
3391
- fs11.rmSync(managed.lifecycleFile, { force: true });
3392
4420
  if (resume) {
3393
4421
  this.#emitLifecycle(managed, "run.resumed", Date.now(), {
3394
4422
  data: {
@@ -3417,11 +4445,32 @@ var AgentManager = class {
3417
4445
  return false;
3418
4446
  }
3419
4447
  }
4448
+ /**
4449
+ * Monitors start detached, so a throw here would leave the run unsettled and
4450
+ * every wait() pending forever. Settle such a run as failed instead.
4451
+ */
3420
4452
  async #monitor(managed, timeoutMs) {
4453
+ try {
4454
+ await this.#watch(managed, timeoutMs);
4455
+ } catch (error) {
4456
+ if (managed.settled) return;
4457
+ const message2 = error instanceof Error ? error.message : String(error);
4458
+ const failed = failedRecord(managed, "failed", `Agent monitor failed: ${message2}`);
4459
+ await managed.transport.stop().catch(() => void 0);
4460
+ try {
4461
+ writeRecord(managed.statusFile, failed);
4462
+ } catch {
4463
+ if (!managed.hosted) managed.unpersistedResult = failed;
4464
+ }
4465
+ this.#settle(managed, failed);
4466
+ }
4467
+ }
4468
+ async #watch(managed, timeoutMs) {
3421
4469
  const deadline = Date.now() + timeoutMs + TRANSPORT_EXIT_GRACE_MS;
3422
4470
  let firstObservedDeadAt;
3423
4471
  while (!managed.settled) {
3424
4472
  if (managed.hosted?.detached) return;
4473
+ if (managed.workerDetached) return;
3425
4474
  this.#drainLifecycle(managed);
3426
4475
  const record = readRecord(managed.statusFile);
3427
4476
  if (record) {
@@ -3527,6 +4576,7 @@ var AgentManager = class {
3527
4576
  }
3528
4577
  #settle(managed, result) {
3529
4578
  if (managed.settled) return;
4579
+ if (managed.workerRecovery) removeWorkerRecovery(managed.runDirectory);
3530
4580
  if (managed.worktreeResult) result.worktreeResult = managed.worktreeResult;
3531
4581
  const nested = this.#nestedAgents(managed, true);
3532
4582
  if (nested.length > 0) result.nestedAgents = reconcileNestedAgents(nested, result);
@@ -3534,7 +4584,10 @@ var AgentManager = class {
3534
4584
  if (!beginAgentSettlement(managed)) return;
3535
4585
  managed.questions?.abort(new Error("Agent run settled"));
3536
4586
  managed.hosted?.close();
3537
- fs11.rmSync(path12.join(managed.runDirectory, "images.json"), { force: true });
4587
+ try {
4588
+ fs13.rmSync(path14.join(managed.runDirectory, "images.json"), { force: true });
4589
+ } catch {
4590
+ }
3538
4591
  this.#emitLifecycle(managed, `run.${result.status}`, result.finishedAt ?? Date.now(), {
3539
4592
  status: result.status
3540
4593
  });
@@ -3567,7 +4620,7 @@ var AgentManager = class {
3567
4620
  #drainLifecycle(managed) {
3568
4621
  let content;
3569
4622
  try {
3570
- content = fs11.readFileSync(managed.lifecycleFile);
4623
+ content = fs13.readFileSync(managed.lifecycleFile);
3571
4624
  } catch {
3572
4625
  return;
3573
4626
  }
@@ -3617,44 +4670,58 @@ var AgentManager = class {
3617
4670
  #routeChildQuestion(managed, data) {
3618
4671
  if (typeof data !== "object" || data === null || typeof data.requestId !== "string") return;
3619
4672
  const question = data;
3620
- const respond = (response) => {
4673
+ const requestId = question.requestId;
4674
+ const steer = (command) => {
3621
4675
  try {
3622
- fs11.appendFileSync(
3623
- path12.join(managed.runDirectory, "steer.jsonl"),
3624
- `${JSON.stringify({ type: "ui_response", requestId: question.requestId, ...response, id: randomUUID5(), ts: Date.now() })}
4676
+ fs13.appendFileSync(
4677
+ path14.join(managed.runDirectory, "steer.jsonl"),
4678
+ `${JSON.stringify({ ...command, id: randomUUID6(), ts: Date.now() })}
3625
4679
  `,
3626
4680
  { encoding: "utf8", mode: 384 }
3627
4681
  );
3628
4682
  } catch {
3629
4683
  }
3630
4684
  };
4685
+ const respond = (response) => steer({ type: "ui_response", requestId, ...response });
3631
4686
  if (!managed.runnerAdapter.capabilities.questions) {
3632
4687
  respond({ cancelled: true });
3633
4688
  return;
3634
4689
  }
3635
- void this.#askParent(managed, question).then((response) => {
4690
+ void this.#askParent(managed, question, (decisionId) => {
4691
+ if (!managed.settled) steer({ type: "ui_decision", requestId, decisionId });
4692
+ }).then((response) => {
3636
4693
  if (!managed.settled) respond(response);
3637
4694
  });
3638
4695
  }
3639
4696
  /** One routed dialog for a worker or hosted run; any failure cancels it. */
3640
- #askParent(managed, question) {
4697
+ #askParent(managed, question, onDecision) {
3641
4698
  if (!this.#onChildQuestion || managed.settled) return Promise.resolve({ cancelled: true });
3642
4699
  managed.questions ??= new AbortController();
3643
- return this.#onChildQuestion({
4700
+ const title = typeof question.title === "string" && question.title.trim() ? question.title.trim() : "question";
4701
+ const open = { title };
4702
+ (managed.openQuestions ??= []).push(open);
4703
+ this.#invalidateUiList();
4704
+ const asked = this.#onChildQuestion({
3644
4705
  runId: managed.id,
3645
4706
  name: managed.actorName ?? managed.name,
3646
4707
  ...managed.actorId ? { actorId: managed.actorId } : {},
4708
+ // Both sides must agree: the run asked to hold, and this question carries no deadline of its own.
4709
+ ...managed.holdQuestions && question.hold === true ? { hold: true } : {},
3647
4710
  question,
3648
4711
  signal: managed.questions.signal,
3649
4712
  onDecision: (decisionId) => {
3650
- managed.questionDecisionId = decisionId;
4713
+ open.decisionId = decisionId;
4714
+ onDecision?.(decisionId);
3651
4715
  this.#invalidateUiList();
3652
4716
  }
3653
4717
  }).catch(() => ({ cancelled: true })).then((response) => {
3654
- delete managed.questionDecisionId;
4718
+ managed.openQuestions.splice(managed.openQuestions.indexOf(open), 1);
4719
+ managed.asks?.delete(asked);
3655
4720
  this.#invalidateUiList();
3656
4721
  return response;
3657
4722
  });
4723
+ (managed.asks ??= /* @__PURE__ */ new Set()).add(asked);
4724
+ return asked;
3658
4725
  }
3659
4726
  #appendAttributedBudgetLedger(managed, tokens, cost) {
3660
4727
  if (!this.#budget || tokens <= 0 && cost <= 0) return;
@@ -3715,12 +4782,19 @@ var AgentManager = class {
3715
4782
  }
3716
4783
  #inheritedToolAllowlist = readChildToolAllowlist();
3717
4784
  #childTools(request, runner, requiresFabricKernel = false) {
3718
- const tools = [...request.tools ?? this.config.defaultTools].filter(
4785
+ const requested = request.tools ?? this.config.defaultTools;
4786
+ const nativePi = runner.id === "pi" || runner.id === "pi-durable";
4787
+ const tools = nativePi ? constrainChildToolSelection(requested, this.#inheritedToolAllowlist) : requested.filter(
3719
4788
  (tool) => tool !== "fabric_exec" && (this.#inheritedToolAllowlist === void 0 || this.#inheritedToolAllowlist.has(tool))
3720
4789
  );
3721
4790
  const extensions = request.recursive === true ? true : request.extensions ?? this.config.extensions;
3722
- if (runner.capabilities.recursiveFabric && (request.recursive || (this.#fullCodeMode || requiresFabricKernel) && extensions)) {
3723
- tools.push("fabric_exec");
4791
+ if (this.config.childQuestions === "route" && (runner.id === "pi" || runner.id === "pi-durable") && runner.capabilities.questions && extensions && requested.length > 0 && !requested.some((tool) => tool.startsWith("+") || tool.startsWith("-"))) {
4792
+ for (const tool of this.config.childQuestionTools ?? ["ask"]) {
4793
+ if (this.#inheritedToolAllowlist === void 0 || this.#inheritedToolAllowlist.has(tool)) tools.push(tool);
4794
+ }
4795
+ }
4796
+ if (request.recursiveToolAuthority === void 0 && !requested.includes("-fabric_exec") && (this.#inheritedToolAllowlist === void 0 || this.#inheritedToolAllowlist.fabricExec) && runner.capabilities.recursiveFabric && (request.recursive || (this.#fullCodeMode || requiresFabricKernel) && extensions)) {
4797
+ tools.push(nativePi && tools.some((tool) => tool.startsWith("+") || tool.startsWith("-")) ? "+fabric_exec" : "fabric_exec");
3724
4798
  }
3725
4799
  return [...new Set(tools)];
3726
4800
  }
@@ -3748,7 +4822,7 @@ var AgentManager = class {
3748
4822
  }
3749
4823
  return adapter;
3750
4824
  }
3751
- for (const kind of ["herdr", "localterm", "tmux", "screen", "process"]) {
4825
+ for (const kind of ["herdr-core", "herdr", "localterm", "tmux", "screen", "process"]) {
3752
4826
  const adapter = this.#transports.get(kind);
3753
4827
  if (adapter && await adapter.available()) return adapter;
3754
4828
  }
@@ -3779,6 +4853,9 @@ var AgentManager = class {
3779
4853
  }
3780
4854
  #requireRun(id) {
3781
4855
  const managed = this.#runs.get(id);
4856
+ if (!managed && this.#queued.has(id)) {
4857
+ throw new Error(`Fabric agent ${id} is queued and has not started`);
4858
+ }
3782
4859
  if (!managed) throw new Error(`Unknown Fabric agent: ${id}`);
3783
4860
  return managed;
3784
4861
  }
@@ -3813,7 +4890,7 @@ var AgentManager = class {
3813
4890
  // directories. Terminal-owner reconciliation prevents cached active ghosts.
3814
4891
  #nestedAgents(managed, force = false) {
3815
4892
  const now = Date.now();
3816
- const needsInitialDiscovery = managed.nestedSnapshot === void 0 && fs11.existsSync(path12.join(managed.runDirectory, "nested"));
4893
+ const needsInitialDiscovery = managed.nestedSnapshot === void 0 && fs13.existsSync(path14.join(managed.runDirectory, "nested"));
3817
4894
  if (!force && !needsInitialDiscovery && managed.nestedSnapshotAt !== void 0 && now - managed.nestedSnapshotAt < NESTED_SNAPSHOT_POLL_MS) {
3818
4895
  return managed.nestedSnapshot ? structuredClone(managed.nestedSnapshot) : [];
3819
4896
  }
@@ -3834,13 +4911,14 @@ var AgentManager = class {
3834
4911
  const { logFile: _logFile, nestedAgents: _nestedAgents, ...safeRecord } = record;
3835
4912
  const model = record.model ?? managed.model;
3836
4913
  const thinking = record.thinking ?? managed.thinking;
4914
+ const blockingDecision = managed.openQuestions?.find((open) => open.decisionId)?.decisionId;
3837
4915
  return {
3838
4916
  ...safeRecord,
3839
4917
  cwd: managed.cwd,
3840
4918
  runner: managed.runner,
3841
4919
  ...managed.kernel ? { kernel: managed.kernel } : {},
3842
4920
  ...managed.residency === "durable" ? { residency: "durable" } : {},
3843
- logFile: path12.join(managed.runDirectory, "events.jsonl"),
4921
+ logFile: path14.join(managed.runDirectory, "events.jsonl"),
3844
4922
  ...nestedAgents.length > 0 ? { nestedAgents } : {},
3845
4923
  ...budget ? { budget } : {},
3846
4924
  ...model ? { model } : {},
@@ -3857,7 +4935,7 @@ var AgentManager = class {
3857
4935
  ...managed.branch ? { branch: managed.branch } : {},
3858
4936
  ...managed.worktree ? { worktree: managed.worktree } : {},
3859
4937
  ...managed.worktreeResult ? { worktreeResult: managed.worktreeResult } : {},
3860
- ...record.blockedOn && managed.questionDecisionId ? { blockedOn: { ...record.blockedOn, decisionId: managed.questionDecisionId } } : {}
4938
+ ...record.blockedOn && blockingDecision ? { blockedOn: { ...record.blockedOn, decisionId: blockingDecision } } : {}
3861
4939
  };
3862
4940
  }
3863
4941
  };
@@ -3896,15 +4974,15 @@ var actorDeliveryNotice = (delivery, triggerTurn) => {
3896
4974
  };
3897
4975
 
3898
4976
  // src/actors/directory.ts
3899
- import fs17 from "node:fs";
4977
+ import fs20 from "node:fs";
3900
4978
 
3901
4979
  // src/actors/manager.ts
3902
- import { randomUUID as randomUUID8 } from "node:crypto";
3903
- import fs16 from "node:fs";
4980
+ import { randomUUID as randomUUID9 } from "node:crypto";
4981
+ import fs19 from "node:fs";
3904
4982
 
3905
4983
  // src/actors/mesh-monitor.ts
3906
- import fs12 from "node:fs";
3907
- import path13 from "node:path";
4984
+ import fs14 from "node:fs";
4985
+ import path15 from "node:path";
3908
4986
  var MESH_WATCH_RECONCILE_MS = 2e3;
3909
4987
  var ActorMeshMonitor = class {
3910
4988
  constructor(mesh, config, callbacks) {
@@ -3931,8 +5009,8 @@ var ActorMeshMonitor = class {
3931
5009
  return;
3932
5010
  }
3933
5011
  try {
3934
- const watcher = fs12.watch(this.mesh.root, { persistent: false }, (_event, filename) => {
3935
- const name = filename == null ? void 0 : path13.basename(filename.toString());
5012
+ const watcher = fs14.watch(this.mesh.root, { persistent: false }, (_event, filename) => {
5013
+ const name = filename == null ? void 0 : path15.basename(filename.toString());
3936
5014
  if (name !== void 0 && name !== "events.jsonl" && name !== "schedules.json") return;
3937
5015
  this.schedule();
3938
5016
  });
@@ -3986,7 +5064,10 @@ var ActorMeshMonitor = class {
3986
5064
  }
3987
5065
  #startTimer(delay4) {
3988
5066
  if (this.#timer) clearInterval(this.#timer);
3989
- this.#timer = setInterval(() => this.schedule(), delay4);
5067
+ this.#timer = setInterval(() => {
5068
+ this.callbacks.onReconcile?.();
5069
+ this.schedule();
5070
+ }, delay4);
3990
5071
  this.#timer.unref();
3991
5072
  }
3992
5073
  async #poll() {
@@ -4021,7 +5102,7 @@ var ActorMeshMonitor = class {
4021
5102
  #readCursor() {
4022
5103
  if (!this.callbacks.cursorPath) return void 0;
4023
5104
  try {
4024
- const value = JSON.parse(fs12.readFileSync(this.callbacks.cursorPath, "utf8"));
5105
+ const value = JSON.parse(fs14.readFileSync(this.callbacks.cursorPath, "utf8"));
4025
5106
  return value.format === 1 && typeof value.cursor === "number" && value.cursor >= 0 ? value.cursor : void 0;
4026
5107
  } catch {
4027
5108
  return void 0;
@@ -4038,11 +5119,11 @@ var ActorMeshMonitor = class {
4038
5119
 
4039
5120
  // src/actors/manager.ts
4040
5121
  import os4 from "node:os";
4041
- import path17 from "node:path";
5122
+ import path19 from "node:path";
4042
5123
 
4043
5124
  // src/actors/log-store.ts
4044
- import fs13 from "node:fs";
4045
- import path14 from "node:path";
5125
+ import fs15 from "node:fs";
5126
+ import path16 from "node:path";
4046
5127
  var ACTOR_MESSAGE_HISTORY_LIMIT = 100;
4047
5128
  var ACTOR_MESSAGE_ENVELOPE_BYTES = 4096;
4048
5129
  var ACTOR_TRUNCATION_SUFFIX = "\n[actor message truncated]";
@@ -4100,17 +5181,17 @@ var ActorLogStore = class {
4100
5181
  this.retention = retention;
4101
5182
  }
4102
5183
  async retainRun(actor, runId, runDirectory) {
4103
- if (!runDirectory || !fs13.existsSync(runDirectory)) return;
4104
- const dest = path14.join(path14.dirname(actor.sessionFile), "runs", runId);
4105
- fs13.mkdirSync(dest, { recursive: true, mode: 448 });
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 });
4106
5187
  for (const file of ["events.jsonl", "status.json", "task.txt"]) {
4107
- const src = path14.join(runDirectory, file);
4108
- if (fs13.existsSync(src)) fs13.copyFileSync(src, path14.join(dest, file));
5188
+ const src = path16.join(runDirectory, file);
5189
+ if (fs15.existsSync(src)) fs15.copyFileSync(src, path16.join(dest, file));
4109
5190
  }
4110
- const nested = path14.join(runDirectory, "nested");
4111
- if (fs13.existsSync(nested)) {
5191
+ const nested = path16.join(runDirectory, "nested");
5192
+ if (fs15.existsSync(nested)) {
4112
5193
  try {
4113
- fs13.cpSync(nested, path14.join(dest, "nested"), { recursive: true });
5194
+ fs15.cpSync(nested, path16.join(dest, "nested"), { recursive: true });
4114
5195
  } catch {
4115
5196
  }
4116
5197
  }
@@ -4118,16 +5199,16 @@ var ActorLogStore = class {
4118
5199
  }
4119
5200
  pruneRuns(actor, now = Date.now()) {
4120
5201
  pruneActorRunArchives({
4121
- runsDirectory: path14.join(path14.dirname(actor.sessionFile), "runs"),
5202
+ runsDirectory: path16.join(path16.dirname(actor.sessionFile), "runs"),
4122
5203
  ...actor.lastRunId ? { latestRunId: actor.lastRunId } : {},
4123
5204
  retentionMs: this.retention.actorRunArchiveMs,
4124
5205
  now
4125
5206
  });
4126
5207
  }
4127
5208
  retainedRunIds(actor) {
4128
- const runsDir = path14.join(path14.dirname(actor.sessionFile), "runs");
5209
+ const runsDir = path16.join(path16.dirname(actor.sessionFile), "runs");
4129
5210
  try {
4130
- return fs13.readdirSync(runsDir).sort();
5211
+ return fs15.readdirSync(runsDir).sort();
4131
5212
  } catch {
4132
5213
  return [];
4133
5214
  }
@@ -4180,6 +5261,34 @@ var ActorLogStore = class {
4180
5261
  }
4181
5262
  };
4182
5263
 
5264
+ // src/verified/generated/actor-name.js
5265
+ function $n2(v, what) {
5266
+ if (typeof v !== "number" || !Number.isSafeInteger(v) || v < 0) throw new RangeError(what + " must be a natural below 2^53, not " + v);
5267
+ return v;
5268
+ }
5269
+ var actorName = /* @__PURE__ */ (() => {
5270
+ function init(params) {
5271
+ const env = {}, s = {};
5272
+ return { scalars: { "out.active": 0, "out.stopped": 0, "out.available": 0 }, maps: {} };
5273
+ }
5274
+ function step(params, state, input) {
5275
+ const env = { "hasActive": $n2(input["hasActive"], "input hasActive"), "hasStopped": $n2(input["hasStopped"], "input hasStopped") }, s = state.scalars, dft = { ...state.defaults }, maps = state.maps;
5276
+ if (!(env["hasActive"] <= 1 && env["hasStopped"] <= 1)) throw new RangeError("actor name decision: the request fails the rule's assumption, so no proof covers the step it would take");
5277
+ const scalars = { ...s, "out.active": env["hasActive"] === 1 ? 1 : 0, "out.stopped": !(env["hasActive"] === 1) && env["hasStopped"] === 1 ? 1 : 0, "out.available": !(env["hasActive"] === 1) && !(env["hasStopped"] === 1) ? 1 : 0 };
5278
+ return Object.keys(dft).length ? { scalars, maps: state.maps, defaults: dft } : { scalars, maps: state.maps };
5279
+ }
5280
+ return { init, step };
5281
+ })();
5282
+
5283
+ // src/actors/name-policy.ts
5284
+ function actorNameDecision(hasActive, hasStopped) {
5285
+ const result = actorName.step({}, actorName.init({}), { hasActive: hasActive ? 1 : 0, hasStopped: hasStopped ? 1 : 0 }).scalars;
5286
+ if (result["out.active"] === 1) return "active";
5287
+ if (result["out.stopped"] === 1) return "stopped";
5288
+ if (result["out.available"] === 1) return "available";
5289
+ throw new Error("Invalid verified actor name decision");
5290
+ }
5291
+
4183
5292
  // src/actors/predicate.ts
4184
5293
  var PREDICATE_VERSION = 1;
4185
5294
  var MAX_PREDICATE_SOURCE_CHARS = 16e3;
@@ -4248,24 +5357,63 @@ var evaluateActorValidWhile = async (source, facts) => {
4248
5357
  };
4249
5358
 
4250
5359
  // src/actors/binding-store.ts
4251
- import { createHash, randomUUID as randomUUID6 } from "node:crypto";
4252
- import fs14 from "node:fs";
4253
- import path15 from "node:path";
5360
+ import { createHash, randomUUID as randomUUID7 } from "node:crypto";
5361
+ import fs17 from "node:fs";
5362
+ import path17 from "node:path";
5363
+
5364
+ // src/actors/store-read.ts
5365
+ import fs16 from "node:fs";
5366
+ var ActorStoreReadError = class extends Error {
5367
+ filePath;
5368
+ constructor(filePath, detail, options) {
5369
+ super(`Cannot read Fabric actor store ${filePath}: ${detail}`, options);
5370
+ this.name = "ActorStoreReadError";
5371
+ this.filePath = filePath;
5372
+ }
5373
+ };
5374
+ var readStoreJson = (filePath) => {
5375
+ let text;
5376
+ try {
5377
+ text = fs16.readFileSync(filePath, "utf8");
5378
+ } catch (error) {
5379
+ if (error?.code === "ENOENT") return void 0;
5380
+ throw new ActorStoreReadError(
5381
+ filePath,
5382
+ error instanceof Error ? error.message : String(error),
5383
+ { cause: error }
5384
+ );
5385
+ }
5386
+ try {
5387
+ return JSON.parse(text);
5388
+ } catch (error) {
5389
+ throw new ActorStoreReadError(
5390
+ filePath,
5391
+ `invalid JSON (${error instanceof Error ? error.message : String(error)})`,
5392
+ { cause: error }
5393
+ );
5394
+ }
5395
+ };
5396
+
5397
+ // src/actors/binding-store.ts
4254
5398
  var BINDING_LOCK_TIMEOUT_MS = 5e3;
4255
5399
  var BINDING_STALE_LOCK_MS = 3e4;
4256
5400
  var bindingFileName = (sessionId) => `${createHash("sha256").update(sessionId).digest("hex")}.json`;
4257
5401
  var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4258
- var errorCode = (error) => error instanceof Error && "code" in error ? String(error.code) : void 0;
4259
5402
  var delay2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
4260
5403
  var ActorBindingStore = class {
4261
5404
  constructor(sessionId, root) {
4262
5405
  this.sessionId = sessionId;
4263
- this.filePath = root ? path15.join(root, "bindings", bindingFileName(sessionId)) : void 0;
5406
+ this.filePath = root ? path17.join(root, "bindings", bindingFileName(sessionId)) : void 0;
4264
5407
  this.#sync(true);
4265
5408
  }
4266
5409
  #bindings = /* @__PURE__ */ new Map();
4267
5410
  #fingerprint;
5411
+ #readError;
4268
5412
  filePath;
5413
+ /** The error from the latest failed read, or undefined after a good read. */
5414
+ get readError() {
5415
+ return this.#readError;
5416
+ }
4269
5417
  get(actorId) {
4270
5418
  this.#sync();
4271
5419
  const binding = this.#bindings.get(actorId);
@@ -4285,10 +5433,10 @@ var ActorBindingStore = class {
4285
5433
  });
4286
5434
  }
4287
5435
  async delete(actorId) {
4288
- return this.#mutate((bindings) => bindings.delete(actorId));
5436
+ return this.#mutate(actorId, (bindings) => bindings.delete(actorId));
4289
5437
  }
4290
5438
  async #update(actorId, mutate) {
4291
- return this.#mutate((bindings) => {
5439
+ return this.#mutate(actorId, (bindings) => {
4292
5440
  const binding = bindings.get(actorId) ?? { updatedAt: Date.now() };
4293
5441
  mutate(binding);
4294
5442
  if (!binding.model && !binding.thinking) {
@@ -4300,16 +5448,24 @@ var ActorBindingStore = class {
4300
5448
  return { ...binding };
4301
5449
  });
4302
5450
  }
4303
- async #mutate(operation) {
5451
+ async #mutate(actorId, operation) {
4304
5452
  if (!this.filePath) {
4305
5453
  const result = operation(this.#bindings);
4306
5454
  return result;
4307
5455
  }
4308
5456
  return this.#withLock(() => {
4309
- const bindings = this.#read();
4310
- const result = operation(bindings);
4311
- this.#save(bindings);
4312
- this.#replace(bindings);
5457
+ let snapshot;
5458
+ try {
5459
+ snapshot = this.#read();
5460
+ } catch (error) {
5461
+ if (error instanceof ActorStoreReadError) this.#readError = error;
5462
+ throw error;
5463
+ }
5464
+ this.#readError = void 0;
5465
+ const result = operation(snapshot.bindings);
5466
+ snapshot.unloaded.delete(actorId);
5467
+ this.#save(snapshot);
5468
+ this.#replace(snapshot.bindings);
4313
5469
  this.#fingerprint = this.#currentFingerprint();
4314
5470
  return result;
4315
5471
  });
@@ -4317,35 +5473,45 @@ var ActorBindingStore = class {
4317
5473
  #sync(force = false) {
4318
5474
  if (!this.filePath) return;
4319
5475
  const fingerprint = this.#currentFingerprint();
4320
- if (!force && fingerprint === this.#fingerprint) return;
4321
- this.#replace(this.#read());
5476
+ if (!force && !this.#readError && fingerprint === this.#fingerprint) return;
5477
+ try {
5478
+ this.#replace(this.#read().bindings);
5479
+ } catch (error) {
5480
+ if (!(error instanceof ActorStoreReadError)) throw error;
5481
+ this.#readError = error;
5482
+ return;
5483
+ }
5484
+ this.#readError = void 0;
4322
5485
  this.#fingerprint = fingerprint;
4323
5486
  }
4324
5487
  #read() {
4325
- const bindings = /* @__PURE__ */ new Map();
4326
- if (!this.filePath) return bindings;
4327
- let parsed;
4328
- try {
4329
- parsed = JSON.parse(fs14.readFileSync(this.filePath, "utf8"));
4330
- } catch {
4331
- return bindings;
5488
+ const snapshot = { bindings: /* @__PURE__ */ new Map(), unloaded: /* @__PURE__ */ new Map() };
5489
+ if (!this.filePath) return snapshot;
5490
+ const parsed = readStoreJson(this.filePath);
5491
+ if (parsed === void 0) return snapshot;
5492
+ if (!isObject(parsed) || parsed.format !== 1 || !isObject(parsed.bindings)) {
5493
+ throw new ActorStoreReadError(
5494
+ this.filePath,
5495
+ "expected a format 1 object with a bindings object"
5496
+ );
4332
5497
  }
4333
- if (!isObject(parsed) || parsed.format !== 1 || parsed.sessionId !== this.sessionId) {
4334
- return bindings;
5498
+ if (parsed.sessionId !== this.sessionId) {
5499
+ throw new ActorStoreReadError(this.filePath, "the file belongs to another session");
4335
5500
  }
4336
- if (!isObject(parsed.bindings)) return bindings;
4337
5501
  for (const [actorId, value] of Object.entries(parsed.bindings)) {
4338
- if (!isObject(value) || typeof value.updatedAt !== "number") continue;
4339
- const model = typeof value.model === "string" ? value.model.trim() : "";
4340
- const thinking = isFabricThinking(value.thinking) ? value.thinking : void 0;
4341
- if (!model && !thinking) continue;
4342
- bindings.set(actorId, {
5502
+ const model = isObject(value) && typeof value.model === "string" ? value.model.trim() : "";
5503
+ const thinking = isObject(value) && isFabricThinking(value.thinking) ? value.thinking : void 0;
5504
+ if (!isObject(value) || typeof value.updatedAt !== "number" || !model && !thinking) {
5505
+ snapshot.unloaded.set(actorId, value);
5506
+ continue;
5507
+ }
5508
+ snapshot.bindings.set(actorId, {
4343
5509
  ...model ? { model } : {},
4344
5510
  ...thinking ? { thinking } : {},
4345
5511
  updatedAt: value.updatedAt
4346
5512
  });
4347
5513
  }
4348
- return bindings;
5514
+ return snapshot;
4349
5515
  }
4350
5516
  #replace(bindings) {
4351
5517
  this.#bindings.clear();
@@ -4353,13 +5519,16 @@ var ActorBindingStore = class {
4353
5519
  this.#bindings.set(actorId, { ...binding });
4354
5520
  }
4355
5521
  }
4356
- #save(bindings) {
5522
+ #save({ bindings, unloaded }) {
4357
5523
  if (!this.filePath) return;
4358
5524
  const value = {
4359
5525
  format: 1,
4360
5526
  sessionId: this.sessionId,
4361
5527
  bindings: Object.fromEntries(
4362
- [...bindings.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([actorId, binding]) => [actorId, { ...binding }])
5528
+ [
5529
+ ...[...bindings.entries()].map(([actorId, binding]) => [actorId, { ...binding }]),
5530
+ ...unloaded.entries()
5531
+ ].sort(([left], [right]) => left.localeCompare(right))
4363
5532
  )
4364
5533
  };
4365
5534
  writeJsonAtomic(this.filePath, value, { space: 2, newline: true });
@@ -4367,7 +5536,7 @@ var ActorBindingStore = class {
4367
5536
  #currentFingerprint() {
4368
5537
  if (!this.filePath) return void 0;
4369
5538
  try {
4370
- const stat = fs14.statSync(this.filePath);
5539
+ const stat = fs17.statSync(this.filePath);
4371
5540
  return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}`;
4372
5541
  } catch {
4373
5542
  return void 0;
@@ -4376,9 +5545,8 @@ var ActorBindingStore = class {
4376
5545
  async #withLock(operation) {
4377
5546
  if (!this.filePath) return operation();
4378
5547
  const lockPath = `${this.filePath}.lock`;
4379
- const ownerPath2 = path15.join(lockPath, "owner");
4380
5548
  const deadline = Date.now() + BINDING_LOCK_TIMEOUT_MS;
4381
- const token = randomUUID6();
5549
+ const token = randomUUID7();
4382
5550
  const processAlive2 = (pid) => {
4383
5551
  if (!Number.isSafeInteger(pid) || pid <= 0) return false;
4384
5552
  try {
@@ -4388,90 +5556,61 @@ var ActorBindingStore = class {
4388
5556
  return false;
4389
5557
  }
4390
5558
  };
4391
- fs14.mkdirSync(path15.dirname(this.filePath), { recursive: true, mode: 448 });
4392
- while (true) {
4393
- try {
4394
- fs14.mkdirSync(lockPath, { mode: 448 });
4395
- fs14.writeFileSync(ownerPath2, `${token}
4396
- ${process.pid}
4397
- ${Date.now()}
4398
- ${encodeOwnerIdentityLine()}
4399
- `, {
4400
- encoding: "utf8",
4401
- mode: 384
4402
- });
4403
- break;
4404
- } catch (error) {
4405
- if (errorCode(error) !== "EEXIST") throw error;
4406
- try {
4407
- const firstOwner = fs14.readFileSync(ownerPath2, "utf8");
4408
- const [, pidText, createdText, identityLine] = firstOwner.trim().split("\n");
4409
- const stale = Date.now() - Number(createdText) > BINDING_STALE_LOCK_MS;
4410
- if (stale && lockOwnerLiveness(Number(pidText), Number(createdText), identityLine, {
4411
- legacyAlive: processAlive2,
4412
- maxHoldMs: Math.max(SHORT_LOCK_MAX_HOLD_MS, BINDING_STALE_LOCK_MS)
4413
- }) === "dead") {
4414
- const secondOwner = fs14.readFileSync(ownerPath2, "utf8");
4415
- if (secondOwner === firstOwner) {
4416
- fs14.rmSync(lockPath, { recursive: true, force: true });
4417
- continue;
4418
- }
4419
- }
4420
- } catch {
4421
- }
4422
- if (Date.now() >= deadline) {
4423
- throw new Error("Timed out waiting for the Fabric actor binding lock");
4424
- }
4425
- await delay2(10);
5559
+ fs17.mkdirSync(path17.dirname(this.filePath), { recursive: true, mode: 448 });
5560
+ while (!tryAcquireShortLock(lockPath, formatShortLockOwner(token))) {
5561
+ if (reapStaleShortLock(lockPath, { staleMs: BINDING_STALE_LOCK_MS, legacyAlive: processAlive2 })) continue;
5562
+ if (Date.now() >= deadline) {
5563
+ throw new Error("Timed out waiting for the Fabric actor binding lock");
4426
5564
  }
5565
+ await delay2(10);
4427
5566
  }
4428
5567
  try {
4429
5568
  return operation();
4430
5569
  } finally {
4431
- try {
4432
- const owner = fs14.readFileSync(ownerPath2, "utf8");
4433
- if (owner.startsWith(`${token}
4434
- `)) {
4435
- fs14.rmSync(lockPath, { recursive: true, force: true });
4436
- }
4437
- } catch {
4438
- }
5570
+ releaseShortLock(lockPath, token);
4439
5571
  }
4440
5572
  }
4441
5573
  };
4442
5574
 
4443
5575
  // src/actors/registry-store.ts
4444
- import { randomUUID as randomUUID7 } from "node:crypto";
4445
- import fs15 from "node:fs";
4446
- import path16 from "node:path";
5576
+ import { randomUUID as randomUUID8 } from "node:crypto";
5577
+ import fs18 from "node:fs";
5578
+ import path18 from "node:path";
5579
+ import { setTimeout as delay3 } from "node:timers/promises";
4447
5580
  var ACTOR_REGISTRY_LOCK_TIMEOUT_MS = 5e3;
4448
5581
  var ACTOR_REGISTRY_STALE_LOCK_MS = 3e4;
4449
- var delay3 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
4450
- var errorCode2 = (error) => error instanceof Error && "code" in error ? String(error.code) : void 0;
5582
+ var isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5583
+ var isActorRegistryRecord = (entry) => isObject2(entry) && typeof entry.id === "string";
4451
5584
  var ActorRegistryStore = class {
4452
5585
  #registryPath;
4453
5586
  #actorRoot;
4454
5587
  constructor(actorRoot) {
4455
5588
  this.#actorRoot = actorRoot;
4456
- this.#registryPath = path16.join(actorRoot, "actors.json");
5589
+ this.#registryPath = path18.join(actorRoot, "actors.json");
4457
5590
  }
4458
- records() {
4459
- try {
4460
- const parsed = JSON.parse(fs15.readFileSync(this.#registryPath, "utf8"));
4461
- if (!Array.isArray(parsed.actors)) return [];
4462
- return parsed.actors.flatMap(
4463
- (record) => typeof record === "object" && record !== null && !Array.isArray(record) && typeof record.id === "string" ? [record] : []
4464
- );
4465
- } catch {
4466
- return [];
5591
+ /**
5592
+ * Every entry in actors.json, including entries without a valid identity, so
5593
+ * a rewrite can keep them. A missing file reads as empty; any other read or
5594
+ * parse failure throws ActorStoreReadError, and callers must not write.
5595
+ */
5596
+ entries() {
5597
+ const parsed = readStoreJson(this.#registryPath);
5598
+ if (parsed === void 0) return [];
5599
+ const actors = isObject2(parsed) ? parsed.actors : void 0;
5600
+ if (!Array.isArray(actors)) {
5601
+ throw new ActorStoreReadError(this.#registryPath, "expected an object with an actors array");
4467
5602
  }
5603
+ return actors;
5604
+ }
5605
+ /** The entries that carry a string id. Throws like entries(). */
5606
+ records() {
5607
+ return this.entries().filter(isActorRegistryRecord);
4468
5608
  }
4469
5609
  /** The callback must be synchronous: release precedes promise assimilation. */
4470
- async withLock(operation) {
5610
+ async withLock(operation, signal) {
4471
5611
  const lockPath = `${this.#registryPath}.lock`;
4472
- const ownerPath2 = path16.join(lockPath, "owner");
4473
5612
  const deadline = Date.now() + ACTOR_REGISTRY_LOCK_TIMEOUT_MS;
4474
- const token = randomUUID7();
5613
+ const token = randomUUID8();
4475
5614
  const processAlive2 = (pid) => {
4476
5615
  if (!Number.isSafeInteger(pid) || pid <= 0) return false;
4477
5616
  try {
@@ -4481,66 +5620,33 @@ var ActorRegistryStore = class {
4481
5620
  return false;
4482
5621
  }
4483
5622
  };
4484
- fs15.mkdirSync(this.#actorRoot, { recursive: true, mode: 448 });
4485
- while (true) {
4486
- try {
4487
- fs15.mkdirSync(lockPath, { mode: 448 });
4488
- fs15.writeFileSync(ownerPath2, `${token}
4489
- ${process.pid}
4490
- ${Date.now()}
4491
- ${encodeOwnerIdentityLine()}
4492
- `, {
4493
- encoding: "utf8",
4494
- mode: 384
4495
- });
4496
- break;
4497
- } catch (error) {
4498
- if (errorCode2(error) !== "EEXIST") throw error;
4499
- try {
4500
- const firstOwner = fs15.readFileSync(ownerPath2, "utf8");
4501
- const [, pidText, createdText, identityLine] = firstOwner.trim().split("\n");
4502
- const stale = Date.now() - Number(createdText) > ACTOR_REGISTRY_STALE_LOCK_MS;
4503
- if (stale && lockOwnerLiveness(Number(pidText), Number(createdText), identityLine, {
4504
- legacyAlive: processAlive2,
4505
- maxHoldMs: Math.max(SHORT_LOCK_MAX_HOLD_MS, ACTOR_REGISTRY_STALE_LOCK_MS)
4506
- }) === "dead") {
4507
- const secondOwner = fs15.readFileSync(ownerPath2, "utf8");
4508
- if (secondOwner === firstOwner) {
4509
- fs15.rmSync(lockPath, { recursive: true, force: true });
4510
- continue;
4511
- }
4512
- }
4513
- } catch {
4514
- }
4515
- if (Date.now() >= deadline) {
4516
- throw new Error("Timed out waiting for the Fabric actor registry lock");
4517
- }
4518
- await delay3(10);
5623
+ fs18.mkdirSync(this.#actorRoot, { recursive: true, mode: 448 });
5624
+ signal?.throwIfAborted();
5625
+ while (!tryAcquireShortLock(lockPath, formatShortLockOwner(token))) {
5626
+ if (reapStaleShortLock(lockPath, { staleMs: ACTOR_REGISTRY_STALE_LOCK_MS, legacyAlive: processAlive2 })) continue;
5627
+ if (Date.now() >= deadline) {
5628
+ throw new Error("Timed out waiting for the Fabric actor registry lock");
4519
5629
  }
5630
+ await delay3(10, void 0, { signal });
5631
+ signal?.throwIfAborted();
4520
5632
  }
4521
5633
  try {
5634
+ signal?.throwIfAborted();
4522
5635
  return operation();
4523
5636
  } finally {
4524
- try {
4525
- const owner = fs15.readFileSync(ownerPath2, "utf8");
4526
- if (owner.startsWith(`${token}
4527
- `)) {
4528
- fs15.rmSync(lockPath, { recursive: true, force: true });
4529
- }
4530
- } catch {
4531
- }
5637
+ releaseShortLock(lockPath, token);
4532
5638
  }
4533
5639
  }
4534
5640
  fingerprint() {
4535
5641
  try {
4536
- const stat = fs15.statSync(this.#registryPath);
5642
+ const stat = fs18.statSync(this.#registryPath);
4537
5643
  return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}`;
4538
5644
  } catch {
4539
5645
  return void 0;
4540
5646
  }
4541
5647
  }
4542
5648
  read() {
4543
- return JSON.parse(fs15.readFileSync(this.#registryPath, "utf8"));
5649
+ return JSON.parse(fs18.readFileSync(this.#registryPath, "utf8"));
4544
5650
  }
4545
5651
  /** Call within withLock for read-modify-write operations. */
4546
5652
  write(actors) {
@@ -4578,7 +5684,7 @@ var normalizeCapabilityRequirements = (requirements = []) => {
4578
5684
  };
4579
5685
  var readRunRecord = (filePath) => {
4580
5686
  try {
4581
- const parsed = JSON.parse(fs16.readFileSync(filePath, "utf8"));
5687
+ const parsed = JSON.parse(fs19.readFileSync(filePath, "utf8"));
4582
5688
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
4583
5689
  return parsed;
4584
5690
  } catch {
@@ -4628,7 +5734,7 @@ var ActorManager = class {
4628
5734
  this.meshConfig = meshConfig;
4629
5735
  this.agents = agents;
4630
5736
  this.onDeliver = onDeliver;
4631
- this.#actorRoot = options.actorRoot ?? fs16.mkdtempSync(path17.join(os4.tmpdir(), "pi-fabric-actors-"));
5737
+ this.#actorRoot = options.actorRoot ?? fs19.mkdtempSync(path19.join(os4.tmpdir(), "pi-fabric-actors-"));
4632
5738
  this.#actorScope = options.actorScope ?? meshConfig.actorScope;
4633
5739
  this.#persistent = options.persistent ?? false;
4634
5740
  this.#mainAgent = options.mainAgent;
@@ -4660,6 +5766,9 @@ var ActorManager = class {
4660
5766
  this.#retentionTimer.unref();
4661
5767
  this.#meshMonitor = new ActorMeshMonitor(mesh, meshConfig, {
4662
5768
  cursorPath: options.meshCursorPath,
5769
+ onReconcile: () => {
5770
+ this.#adoptionDeferred = false;
5771
+ },
4663
5772
  beforePoll: () => {
4664
5773
  this.#syncActorsFromRegistry();
4665
5774
  this.#refreshOwnership();
@@ -4695,8 +5804,11 @@ var ActorManager = class {
4695
5804
  // Adoption compares against this snapshot so two racing adopters cannot
4696
5805
  // both move the same dead lineage: only the first fenced write succeeds.
4697
5806
  #persistedRoots = /* @__PURE__ */ new Map();
4698
- // In-flight fenced adoption attempts, one per actor.
4699
- #adoptionPending = /* @__PURE__ */ new Set();
5807
+ // One attempt at a time; failures wait for mesh reconciliation.
5808
+ #adoptionAbort = new AbortController();
5809
+ #adoptionPending = false;
5810
+ #adoptionDeferred = false;
5811
+ #lastAdoptionId;
4700
5812
  #adoptionGraceMs;
4701
5813
  #listeners = /* @__PURE__ */ new Set();
4702
5814
  #retentionTimer;
@@ -4711,6 +5823,7 @@ var ActorManager = class {
4711
5823
  #mainIdle = true;
4712
5824
  #reloadingOwnership = false;
4713
5825
  #registryFingerprint;
5826
+ #createTail = Promise.resolve();
4714
5827
  subscribe(listener) {
4715
5828
  this.#listeners.add(listener);
4716
5829
  return () => this.#listeners.delete(listener);
@@ -4730,6 +5843,19 @@ var ActorManager = class {
4730
5843
  * request while a transferred actor still advertises its creating host.
4731
5844
  */
4732
5845
  async create(request, { asRegistryOwner = false } = {}) {
5846
+ const previous = this.#createTail;
5847
+ let release;
5848
+ this.#createTail = new Promise((resolve) => {
5849
+ release = resolve;
5850
+ });
5851
+ await previous;
5852
+ try {
5853
+ return await this.#createActor(request, asRegistryOwner);
5854
+ } finally {
5855
+ release();
5856
+ }
5857
+ }
5858
+ async #createActor(request, asRegistryOwner) {
4733
5859
  this.#refreshOwnership();
4734
5860
  const registryOwnerCreate = asRegistryOwner && request.residency === "durable";
4735
5861
  if (!registryOwnerCreate && [...this.#actors.values()].some(
@@ -4740,11 +5866,11 @@ var ActorManager = class {
4740
5866
  if (!this.meshConfig.enabled) throw new Error("Fabric mesh and actors are disabled");
4741
5867
  const name = request.name.trim();
4742
5868
  if (!ACTOR_NAME_PATTERN.test(name)) throw new Error(`Invalid Fabric actor name: ${name}`);
4743
- const sameName = [...this.#actors.values()].find((actor2) => actor2.name === name);
4744
- if (sameName && sameName.status !== "stopped") {
4745
- throw new Error(`A Fabric actor named ${name} is already active (${sameName.id})`);
4746
- }
4747
- if (sameName?.status === "stopped") await this.remove(sameName.id);
5869
+ const namesakes = [...this.#actors.values()].filter((actor2) => actor2.name === name);
5870
+ const active = namesakes.find((actor2) => actor2.status !== "stopped");
5871
+ const decision = actorNameDecision(Boolean(active), namesakes.some((actor2) => actor2.status === "stopped"));
5872
+ if (decision === "active") throw new Error(`A Fabric actor named ${name} is already active (${active.id})`);
5873
+ if (decision === "stopped") throw new Error(`A stopped Fabric actor named ${name} already exists (${namesakes[0].id}); remove it explicitly before creating another`);
4748
5874
  if (!request.instructions.trim()) throw new Error("Actor instructions must not be empty");
4749
5875
  if (Buffer.byteLength(request.instructions, "utf8") > this.meshConfig.maxEventBytes) {
4750
5876
  throw new Error(`Actor instructions exceed ${this.meshConfig.maxEventBytes} bytes`);
@@ -4780,9 +5906,8 @@ var ActorManager = class {
4780
5906
  throw new Error("This Fabric host cannot commit actor capability requirements");
4781
5907
  }
4782
5908
  const principalScope = launchScope(void 0, request.principalScope);
4783
- const id = randomUUID8().replaceAll("-", "");
4784
- const actorDirectory = path17.join(this.#actorRoot, id);
4785
- fs16.mkdirSync(actorDirectory, { recursive: true, mode: 448 });
5909
+ const id = randomUUID9().replaceAll("-", "");
5910
+ const actorDirectory = path19.join(this.#actorRoot, id);
4786
5911
  const actor = {
4787
5912
  id,
4788
5913
  name,
@@ -4809,13 +5934,14 @@ var ActorManager = class {
4809
5934
  ...request.validWhile ? { validWhile: structuredClone(request.validWhile) } : {},
4810
5935
  ...principalScope ? { principalScope } : {},
4811
5936
  latestActivationSequence: 0,
4812
- sessionFile: path17.join(actorDirectory, "session.jsonl"),
5937
+ sessionFile: path19.join(actorDirectory, "session.jsonl"),
4813
5938
  queue: [],
4814
5939
  draining: false,
4815
5940
  messages: [],
4816
5941
  createdAt: Date.now(),
4817
5942
  updatedAt: Date.now()
4818
5943
  };
5944
+ fs19.mkdirSync(actorDirectory, { recursive: true, mode: 448 });
4819
5945
  this.#actors.set(id, actor);
4820
5946
  this.#locallyCreated.add(id);
4821
5947
  this.#ownership.set(id, true);
@@ -4841,6 +5967,7 @@ var ActorManager = class {
4841
5967
  const actor = this.#requireActor(id);
4842
5968
  this.#ceded.add(actor.id);
4843
5969
  this.#ownership.set(actor.id, false);
5970
+ this.#registryFingerprint = void 0;
4844
5971
  actor.abortController?.abort();
4845
5972
  for (const item of actor.queue.splice(0)) {
4846
5973
  item.reject?.(
@@ -5144,17 +6271,17 @@ var ActorManager = class {
5144
6271
  const type = opts.type ?? "session";
5145
6272
  const lines = Math.max(1, Math.min(opts.lines ?? 200, 5e3));
5146
6273
  const sessionFile = actor.sessionFile;
5147
- const logDir = path17.join(path17.dirname(sessionFile), "runs");
6274
+ const logDir = path19.join(path19.dirname(sessionFile), "runs");
5148
6275
  const sessionPage = type === "run" ? { lines: [], hasMore: false } : readJsonlPage(sessionFile, lines, opts.before);
5149
6276
  const session = sessionPage.lines;
5150
6277
  let run;
5151
6278
  if (type !== "session") {
5152
6279
  const targetRunId = opts.runId ?? actor.lastRunId;
5153
6280
  if (targetRunId) {
5154
- const runPath = path17.join(logDir, targetRunId);
5155
- if (fs16.existsSync(runPath)) {
5156
- const statusRecord = readRunRecord(path17.join(runPath, "status.json"));
5157
- const eventsFile = path17.join(runPath, "events.jsonl");
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");
5158
6285
  const page = readJsonlPage(eventsFile, lines, opts.before);
5159
6286
  run = {
5160
6287
  runId: targetRunId,
@@ -5320,9 +6447,10 @@ var ActorManager = class {
5320
6447
  * reject every queued message so subsequent execution is cancelled. Unlike
5321
6448
  * stop(), actors stay alive and idle — they keep their identity, session,
5322
6449
  * and subscriptions, and resume responding to future events. Returns the
5323
- * number of actors that had work to cancel. Also arms a short cooldown that
5324
- * suppresses host-event dispatch so the interrupt's own turn_end /
5325
- * agent_settled events do not immediately re-enqueue the actors.
6450
+ * number of actors that had work to cancel. Also arms the stop-the-world
6451
+ * gate, which suppresses host-event and mesh dispatch until the user sends
6452
+ * a new message (the "input" host event), so the interrupt's own turn_end /
6453
+ * agent_settled events do not re-enqueue the actors.
5326
6454
  */
5327
6455
  haltAll() {
5328
6456
  if (!this.meshConfig.enabled) return { halted: 0 };
@@ -5356,7 +6484,7 @@ var ActorManager = class {
5356
6484
  await this.#bindings.delete(actor.id);
5357
6485
  this.#actors.delete(actor.id);
5358
6486
  this.#emitChange();
5359
- fs16.rmSync(path17.dirname(actor.sessionFile), { recursive: true, force: true });
6487
+ fs19.rmSync(path19.dirname(actor.sessionFile), { recursive: true, force: true });
5360
6488
  await this.#saveActors(/* @__PURE__ */ new Set([actor.id]));
5361
6489
  await this.mesh.delete({ key: this.#presenceKey(actor.id) }).catch(() => ({ deleted: false }));
5362
6490
  if (retainedRunId) await this.agents.cleanup(retainedRunId).catch(() => ({ cleaned: false }));
@@ -5365,6 +6493,7 @@ var ActorManager = class {
5365
6493
  async close() {
5366
6494
  if (this.#closing) return;
5367
6495
  this.#closing = true;
6496
+ this.#adoptionAbort.abort();
5368
6497
  this.#meshMonitor.close();
5369
6498
  if (this.#retentionTimer) clearInterval(this.#retentionTimer);
5370
6499
  this.#retentionTimer = void 0;
@@ -5383,7 +6512,7 @@ var ActorManager = class {
5383
6512
  }
5384
6513
  }
5385
6514
  await Promise.allSettled(
5386
- owned.map((actor) => actor.drain ?? Promise.resolve())
6515
+ [...this.#actors.values()].map((actor) => actor.drain ?? Promise.resolve())
5387
6516
  );
5388
6517
  for (const actor of owned) {
5389
6518
  if (actor.status !== "stopped") actor.status = "idle";
@@ -5396,7 +6525,7 @@ var ActorManager = class {
5396
6525
  await Promise.allSettled(
5397
6526
  [...this.#actors.values()].map((actor) => actor.drain ?? Promise.resolve())
5398
6527
  );
5399
- fs16.rmSync(this.#actorRoot, { recursive: true, force: true });
6528
+ fs19.rmSync(this.#actorRoot, { recursive: true, force: true });
5400
6529
  }
5401
6530
  #enqueue(actor, source, payload, options = {}) {
5402
6531
  const canManage = options.ownershipChecked ? this.#canManageCached(actor.id) : this.#canManage(actor.id);
@@ -5439,7 +6568,7 @@ var ActorManager = class {
5439
6568
  `Fabric actor queue limit reached for ${actor.name} (${this.meshConfig.actorQueueLimit})`
5440
6569
  );
5441
6570
  }
5442
- const itemId = randomUUID8();
6571
+ const itemId = randomUUID9();
5443
6572
  const item = {
5444
6573
  id: itemId,
5445
6574
  source,
@@ -5485,10 +6614,16 @@ var ActorManager = class {
5485
6614
  const drain = this.#drain(actor);
5486
6615
  actor.drain = drain;
5487
6616
  const release = () => {
5488
- if (actor.drain === drain) delete actor.drain;
6617
+ if (actor.drain === drain) {
6618
+ delete actor.drain;
6619
+ if (!this.#ownership.get(actor.id)) this.#registryFingerprint = void 0;
6620
+ }
5489
6621
  };
5490
6622
  drain.then(release, release);
5491
6623
  }
6624
+ // Presence saves inside the drain are best-effort, like the enqueue-time
6625
+ // publish: a refused registry save (an unreadable actors.json, a lock
6626
+ // timeout) must not strand a dequeued item or abandon the rest of the queue.
5492
6627
  async #drain(actor) {
5493
6628
  try {
5494
6629
  while (actor.queue.length > 0 && actor.status !== "stopped" && !this.#closing && this.#canManage(actor.id)) {
@@ -5499,14 +6634,14 @@ var ActorManager = class {
5499
6634
  delete actor.lastError;
5500
6635
  const abortController = new AbortController();
5501
6636
  actor.abortController = abortController;
5502
- await this.#publishPresence(actor);
6637
+ await this.#publishPresence(actor).catch(() => void 0);
5503
6638
  const beforeRun = await this.#validity(actor, item);
5504
6639
  if (!beforeRun.valid) {
5505
6640
  this.#recordStale(actor, item, beforeRun.reason);
5506
6641
  delete actor.abortController;
5507
6642
  actor.status = actor.queue.length > 0 ? "queued" : "idle";
5508
6643
  actor.updatedAt = Date.now();
5509
- await this.#publishPresence(actor);
6644
+ await this.#publishPresence(actor).catch(() => void 0);
5510
6645
  continue;
5511
6646
  }
5512
6647
  let runId;
@@ -5526,7 +6661,7 @@ var ActorManager = class {
5526
6661
  actor.queue.unshift(item);
5527
6662
  actor.status = "queued";
5528
6663
  actor.updatedAt = Date.now();
5529
- await this.#publishPresence(actor);
6664
+ await this.#publishPresence(actor).catch(() => void 0);
5530
6665
  break;
5531
6666
  }
5532
6667
  delete actor.missingCapabilities;
@@ -5546,14 +6681,14 @@ var ActorManager = class {
5546
6681
  actor.lastRunId = result.id;
5547
6682
  if (actor.runner === "claude" && result.runnerSessionId) {
5548
6683
  actor.runnerSessionId = result.runnerSessionId;
5549
- await this.#saveActors();
6684
+ await this.#saveActors().catch(() => void 0);
5550
6685
  }
5551
6686
  runCompleted = result.status === "completed";
5552
6687
  if (result.status !== "completed") {
5553
6688
  if (actor.responseMode === "directive") {
5554
6689
  const reason = result.error || `Actor run ${result.status}`;
5555
6690
  const silent = {
5556
- id: randomUUID8(),
6691
+ id: randomUUID9(),
5557
6692
  actorId: actor.id,
5558
6693
  actorName: actor.name,
5559
6694
  direction: "out",
@@ -5619,7 +6754,7 @@ var ActorManager = class {
5619
6754
  }
5620
6755
  actor.lastError = message2;
5621
6756
  const failed = {
5622
- id: randomUUID8(),
6757
+ id: randomUUID9(),
5623
6758
  actorId: actor.id,
5624
6759
  actorName: actor.name,
5625
6760
  direction: "out",
@@ -5643,7 +6778,7 @@ var ActorManager = class {
5643
6778
  delete actor.abortController;
5644
6779
  actor.updatedAt = Date.now();
5645
6780
  if (actor.status !== "stopped") actor.status = actor.queue.length > 0 ? "queued" : "idle";
5646
- if (this.#canManage(actor.id)) await this.#publishPresence(actor);
6781
+ if (this.#canManage(actor.id)) await this.#publishPresence(actor).catch(() => void 0);
5647
6782
  }
5648
6783
  }
5649
6784
  } finally {
@@ -5711,7 +6846,7 @@ var ActorManager = class {
5711
6846
  if (actor.responseMode === "directive") {
5712
6847
  const directive = asDirective(result);
5713
6848
  return {
5714
- id: randomUUID8(),
6849
+ id: randomUUID9(),
5715
6850
  actorId: actor.id,
5716
6851
  actorName: actor.name,
5717
6852
  direction: "out",
@@ -5725,7 +6860,7 @@ var ActorManager = class {
5725
6860
  };
5726
6861
  }
5727
6862
  return {
5728
- id: randomUUID8(),
6863
+ id: randomUUID9(),
5729
6864
  actorId: actor.id,
5730
6865
  actorName: actor.name,
5731
6866
  direction: "out",
@@ -5780,7 +6915,7 @@ var ActorManager = class {
5780
6915
  }
5781
6916
  #recordStale(actor, item, reason = "validWhile returned false", runId, usage) {
5782
6917
  const message2 = {
5783
- id: randomUUID8(),
6918
+ id: randomUUID9(),
5784
6919
  actorId: actor.id,
5785
6920
  actorName: actor.name,
5786
6921
  direction: "out",
@@ -5940,14 +7075,16 @@ var ActorManager = class {
5940
7075
  (actor) => this.#ownershipDecision(actor.id)
5941
7076
  );
5942
7077
  const replaced = /* @__PURE__ */ new Set([...removedIds, ...owned.map((actor) => actor.id)]);
5943
- const preserved = this.#registry.records().filter((record) => !replaced.has(record.id));
7078
+ const preserved = this.#registry.entries().filter((entry) => !isActorRegistryRecord(entry) || !replaced.has(entry.id));
5944
7079
  const actors = [...preserved, ...owned.map((actor) => this.#serializedActor(actor))];
5945
7080
  this.#registry.write(actors);
5946
7081
  this.#registryFingerprint = this.#registry.fingerprint();
5947
7082
  for (const id of removedIds) this.#persistedRoots.delete(id);
5948
7083
  for (const actor of owned) this.#persistedRoots.set(actor.id, actor.rootId);
5949
7084
  for (const record of preserved) {
5950
- if (typeof record.rootId === "string") this.#persistedRoots.set(record.id, record.rootId);
7085
+ if (isActorRegistryRecord(record) && typeof record.rootId === "string") {
7086
+ this.#persistedRoots.set(record.id, record.rootId);
7087
+ }
5951
7088
  }
5952
7089
  });
5953
7090
  this.#registryFingerprint = void 0;
@@ -5957,22 +7094,17 @@ var ActorManager = class {
5957
7094
  if (!this.#persistent || this.#closing || this.#reloadingOwnership) return;
5958
7095
  const fingerprint = this.#registry.fingerprint();
5959
7096
  if (!fingerprint || fingerprint === this.#registryFingerprint) return;
5960
- this.#registryFingerprint = fingerprint;
5961
- const ownsAny = [...this.#actors.keys()].some((id) => this.#ownershipDecision(id));
5962
- if (!ownsAny) {
5963
- for (const actor of this.#actors.values()) actor.abortController?.abort();
5964
- this.#actors.clear();
5965
- this.#ownership.clear();
5966
- this.#locallyCreated.clear();
5967
- this.#loadActors();
5968
- for (const actor of this.#actors.values()) {
5969
- this.#ownership.set(actor.id, this.#ownershipDecision(actor.id));
5970
- }
7097
+ let parsed;
7098
+ try {
7099
+ parsed = this.#registry.read();
7100
+ if (typeof parsed !== "object" || parsed === null || !Array.isArray(parsed.actors)) return;
7101
+ } catch {
5971
7102
  return;
5972
7103
  }
7104
+ this.#registryFingerprint = fingerprint;
5973
7105
  const owned = /* @__PURE__ */ new Set();
5974
7106
  for (const [id, actor] of this.#actors) {
5975
- if (this.#ownershipDecision(id)) {
7107
+ if (this.#ownershipDecision(id) || this.#ownership.get(id) || actor.drain) {
5976
7108
  owned.add(id);
5977
7109
  continue;
5978
7110
  }
@@ -5981,30 +7113,33 @@ var ActorManager = class {
5981
7113
  this.#ownership.delete(id);
5982
7114
  this.#locallyCreated.delete(id);
5983
7115
  }
5984
- this.#loadActors(true);
7116
+ this.#loadActors(true, parsed);
5985
7117
  for (const actor of this.#actors.values()) {
5986
7118
  if (!owned.has(actor.id)) {
5987
7119
  this.#ownership.set(actor.id, this.#ownershipDecision(actor.id));
5988
7120
  }
5989
7121
  }
5990
7122
  }
5991
- #loadActors(onlyMissing = false) {
7123
+ #loadActors(onlyMissing = false, snapshot, adoption) {
5992
7124
  let added = 0;
5993
- let parsed;
5994
- try {
5995
- parsed = this.#registry.read();
5996
- } catch (error) {
5997
- if (error instanceof Error && "code" in error && error.code === "ENOENT") return;
5998
- return;
7125
+ let parsed = snapshot;
7126
+ if (snapshot === void 0) {
7127
+ try {
7128
+ parsed = this.#registry.read();
7129
+ } catch {
7130
+ return false;
7131
+ }
5999
7132
  }
6000
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return;
7133
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return false;
6001
7134
  const records = parsed.actors;
6002
- if (!Array.isArray(records)) return;
6003
- for (const value of records) {
6004
- if (typeof value !== "object" || value === null || Array.isArray(value)) continue;
6005
- const record = value;
6006
- if (typeof record.id === "string" && typeof record.rootId === "string") {
6007
- this.#persistedRoots.set(record.id, record.rootId);
7135
+ if (!Array.isArray(records)) return false;
7136
+ if (!adoption) {
7137
+ for (const value of records) {
7138
+ if (typeof value !== "object" || value === null || Array.isArray(value)) continue;
7139
+ const record = value;
7140
+ if (typeof record.id === "string" && typeof record.rootId === "string") {
7141
+ this.#persistedRoots.set(record.id, record.rootId);
7142
+ }
6008
7143
  }
6009
7144
  }
6010
7145
  for (const value of records) {
@@ -6054,7 +7189,7 @@ var ActorManager = class {
6054
7189
  ...typeof record.model === "string" ? { model: record.model } : {},
6055
7190
  ...isFabricThinking(record.thinking) ? { thinking: record.thinking } : {},
6056
7191
  ...Array.isArray(record.tools) ? { tools: record.tools.filter((tool) => typeof tool === "string") } : {},
6057
- ...record.transport === "auto" || record.transport === "process" || record.transport === "tmux" || record.transport === "screen" || record.transport === "localterm" || record.transport === "herdr" ? { transport: record.transport } : {},
7192
+ ...record.transport === "auto" || record.transport === "process" || record.transport === "tmux" || record.transport === "screen" || record.transport === "localterm" || record.transport === "herdr" || record.transport === "herdr-core" ? { transport: record.transport } : {},
6058
7193
  ...typeof record.timeoutMs === "number" ? { timeoutMs: record.timeoutMs } : {},
6059
7194
  ...typeof record.extensions === "boolean" ? { extensions: record.extensions } : {},
6060
7195
  requirements,
@@ -6062,7 +7197,7 @@ var ActorManager = class {
6062
7197
  ...record.validWhile?.version === 1 && typeof record.validWhile.source === "string" ? { validWhile: record.validWhile } : {},
6063
7198
  ...principalScope ? { principalScope } : {},
6064
7199
  latestActivationSequence: 0,
6065
- sessionFile: path17.join(this.#actorRoot, record.id, "session.jsonl"),
7200
+ sessionFile: path19.join(this.#actorRoot, record.id, "session.jsonl"),
6066
7201
  queue: [],
6067
7202
  draining: false,
6068
7203
  messages: [],
@@ -6077,11 +7212,21 @@ var ActorManager = class {
6077
7212
  }
6078
7213
  }
6079
7214
  }
7215
+ if (adoption) {
7216
+ if (actor.id !== adoption.target.id) continue;
7217
+ adoption.commit();
7218
+ const target = adoption.target;
7219
+ for (const key of ["kernel", "pythonRuntime", "runnerSessionId", "model", "thinking", "tools", "transport", "timeoutMs", "extensions", "capabilityDigest", "validWhile", "principalScope", "lastRunId"]) delete target[key];
7220
+ Object.assign(target, actor);
7221
+ this.#ownership.set(target.id, this.#ownershipDecision(target.id));
7222
+ return true;
7223
+ }
6080
7224
  this.#actors.set(actor.id, actor);
6081
7225
  added++;
6082
7226
  void this.#publishPresence(actor).catch(() => void 0);
6083
7227
  }
6084
7228
  if (added > 0) this.#emitChange();
7229
+ return !adoption;
6085
7230
  }
6086
7231
  #resolvedModel(runner, model) {
6087
7232
  return (runner === "pi" || runner === "pi-durable") && this.#resolvePiModel ? this.#resolvePiModel(model) : model;
@@ -6157,7 +7302,7 @@ var ActorManager = class {
6157
7302
  ...actor.lastRunId ? { lastRunId: actor.lastRunId } : {},
6158
7303
  ...actor.lastError ? { lastError: actor.lastError } : {},
6159
7304
  sessionFile: actor.sessionFile,
6160
- logDir: path17.join(path17.dirname(actor.sessionFile), "runs")
7305
+ logDir: path19.join(path19.dirname(actor.sessionFile), "runs")
6161
7306
  };
6162
7307
  }
6163
7308
  validateDirectMessage(message2, data) {
@@ -6186,10 +7331,10 @@ var ActorManager = class {
6186
7331
  return this.#canManageActor === void 0;
6187
7332
  }
6188
7333
  #maybeAdoptOrphan(actor) {
6189
- if (!this.#persistent || this.#closing || !this.#canManageActor || this.#claimResidency === void 0 || this.#adoptionPending.has(actor.id)) {
7334
+ if (!this.#persistent || this.#closing || !this.#canManageActor || this.#claimResidency === void 0 || this.#adoptionPending || this.#adoptionDeferred) {
6190
7335
  return;
6191
7336
  }
6192
- if (actor.rootId === this.#rootId) return;
7337
+ if (actor.rootId === this.#rootId || actor.drain) return;
6193
7338
  if (actor.residency !== this.#claimResidency) return;
6194
7339
  if (this.#canManageActor(actor.id) !== void 0) return;
6195
7340
  if (this.#lineageAlive?.(actor.rootId) === true) return;
@@ -6200,12 +7345,16 @@ var ActorManager = class {
6200
7345
  void this.#confirmAdoption(actor).catch(() => void 0);
6201
7346
  }
6202
7347
  async #confirmAdoption(actor) {
6203
- if (this.#adoptionPending.has(actor.id)) return;
6204
- this.#adoptionPending.add(actor.id);
7348
+ if (this.#adoptionPending) return;
7349
+ this.#adoptionPending = true;
7350
+ this.#lastAdoptionId = actor.id;
7351
+ let adopted = false;
6205
7352
  try {
6206
7353
  const expectedRootId = actor.rootId;
6207
- const adopted = await this.#registry.withLock(() => {
6208
- const records = this.#registry.records();
7354
+ adopted = await this.#registry.withLock(() => {
7355
+ if (this.#closing || this.#actors.get(actor.id) !== actor || actor.drain) return false;
7356
+ const entries = this.#registry.entries();
7357
+ const records = entries.filter(isActorRegistryRecord);
6209
7358
  const current = records.find((record) => record.id === actor.id);
6210
7359
  if (!current || current.rootId !== expectedRootId) return false;
6211
7360
  if (this.#canManageActor?.(actor.id) !== void 0) return false;
@@ -6213,17 +7362,21 @@ var ActorManager = class {
6213
7362
  if (typeof current.adoptedAt === "number" && Date.now() - current.adoptedAt < this.#adoptionGraceMs) {
6214
7363
  return false;
6215
7364
  }
7365
+ const candidate = { ...current, rootId: this.#rootId, adoptedAt: Date.now(), updatedAt: Date.now() };
7366
+ const preserved = entries.filter(
7367
+ (entry) => !isActorRegistryRecord(entry) || entry.id !== actor.id
7368
+ );
7369
+ const hydrated = this.#loadActors(false, { actors: [candidate] }, {
7370
+ target: actor,
7371
+ commit: () => this.#registry.write([...preserved, candidate])
7372
+ });
7373
+ if (!hydrated) return false;
6216
7374
  for (const record of records) {
6217
7375
  if (typeof record.rootId === "string") this.#persistedRoots.set(record.id, record.rootId);
6218
7376
  }
6219
- actor.rootId = this.#rootId;
6220
- actor.adoptedAt = Date.now();
6221
- actor.updatedAt = Date.now();
6222
- const preserved = records.filter((record) => record.id !== actor.id);
6223
- this.#registry.write([...preserved, this.#serializedActor(actor)]);
6224
- this.#registryFingerprint = this.#registry.fingerprint();
6225
7377
  return true;
6226
- });
7378
+ }, this.#adoptionAbort.signal);
7379
+ if (this.#closing) return;
6227
7380
  if (adopted) {
6228
7381
  this.#persistedRoots.set(actor.id, this.#rootId);
6229
7382
  } else {
@@ -6238,19 +7391,41 @@ var ActorManager = class {
6238
7391
  }
6239
7392
  } catch {
6240
7393
  } finally {
6241
- this.#adoptionPending.delete(actor.id);
7394
+ this.#adoptionPending = false;
7395
+ }
7396
+ if (this.#closing) return;
7397
+ if (!adopted) {
7398
+ this.#adoptionDeferred = true;
7399
+ } else {
7400
+ this.#registryFingerprint = void 0;
7401
+ this.#syncActorsFromRegistry();
7402
+ this.#refreshOwnership();
7403
+ if (this.#actors.get(actor.id) === actor && this.#canManageCached(actor.id)) {
7404
+ void this.#publishPresence(actor).catch(() => void 0);
7405
+ }
6242
7406
  }
6243
- this.#refreshOwnership();
6244
7407
  this.#emitChange();
6245
7408
  }
7409
+ #scheduleAdoptions() {
7410
+ if (this.#closing || this.#adoptionPending || this.#adoptionDeferred || !this.#persistent || !this.#canManageActor || this.#claimResidency === void 0) return;
7411
+ const ids = [...this.#actors.keys()];
7412
+ const start = (ids.indexOf(this.#lastAdoptionId ?? "") + 1) % (ids.length || 1);
7413
+ for (let i = 0; i < ids.length; i++) {
7414
+ const id = ids[(start + i) % ids.length];
7415
+ const actor = this.#actors.get(id);
7416
+ if (actor && !this.#ownership.get(id)) this.#maybeAdoptOrphan(actor);
7417
+ if (this.#adoptionPending) return;
7418
+ }
7419
+ }
6246
7420
  #refreshOwnership() {
6247
7421
  if (!this.#canManageActor || this.#reloadingOwnership) return;
6248
- let acquired = false;
7422
+ const acquired = [];
6249
7423
  for (const actor of this.#actors.values()) {
6250
7424
  const previous = this.#ownership.get(actor.id) ?? false;
6251
7425
  const next = this.#ownershipDecision(actor.id);
6252
- this.#ownership.set(actor.id, next);
6253
7426
  if (previous && !next) {
7427
+ this.#ownership.set(actor.id, false);
7428
+ this.#registryFingerprint = void 0;
6254
7429
  actor.abortController?.abort();
6255
7430
  for (const item of actor.queue.splice(0)) {
6256
7431
  item.reject?.(
@@ -6261,20 +7436,28 @@ var ActorManager = class {
6261
7436
  }
6262
7437
  if (actor.status !== "stopped") actor.status = "idle";
6263
7438
  } else if (!previous && next) {
6264
- acquired = true;
7439
+ acquired.push(actor);
6265
7440
  }
6266
- if (!next) this.#maybeAdoptOrphan(actor);
6267
7441
  }
6268
- if (!acquired || !this.#persistent || this.#closing) return;
7442
+ this.#scheduleAdoptions();
7443
+ if (acquired.length === 0 || this.#closing) return;
7444
+ if (!this.#persistent) {
7445
+ for (const actor of acquired) this.#ownership.set(actor.id, true);
7446
+ return;
7447
+ }
7448
+ let snapshot;
7449
+ try {
7450
+ snapshot = this.#registry.read();
7451
+ if (typeof snapshot !== "object" || snapshot === null || Array.isArray(snapshot) || !Array.isArray(snapshot.actors)) return;
7452
+ } catch {
7453
+ return;
7454
+ }
6269
7455
  this.#reloadingOwnership = true;
6270
7456
  try {
6271
- for (const actor of this.#actors.values()) actor.abortController?.abort();
6272
- this.#actors.clear();
6273
- this.#ownership.clear();
6274
- this.#locallyCreated.clear();
6275
- this.#loadActors();
6276
- for (const actor of this.#actors.values()) {
6277
- this.#ownership.set(actor.id, this.#ownershipDecision(actor.id));
7457
+ for (const actor of acquired) {
7458
+ if (actor.drain) continue;
7459
+ this.#loadActors(false, snapshot, { target: actor, commit: () => {
7460
+ } });
6278
7461
  }
6279
7462
  } finally {
6280
7463
  this.#reloadingOwnership = false;
@@ -6319,16 +7502,17 @@ var ActorManager = class {
6319
7502
  var ActorDirectory = class extends ActorManager {
6320
7503
  #secondary;
6321
7504
  #defaultScope;
7505
+ #directoryCreateTail = Promise.resolve();
6322
7506
  constructor(base, roots, defaultScope) {
6323
7507
  const options = { ...base[6] ?? {} };
6324
7508
  const meshCursorPath = options.meshCursorPath;
6325
7509
  delete options.actorRoot;
6326
7510
  delete options.meshCursorPath;
6327
7511
  const cursorPaths = meshCursorPath ? { project: `${meshCursorPath}.project`, session: `${meshCursorPath}.session` } : void 0;
6328
- if (meshCursorPath && fs17.existsSync(meshCursorPath)) {
7512
+ if (meshCursorPath && fs20.existsSync(meshCursorPath)) {
6329
7513
  for (const cursorPath of Object.values(cursorPaths)) {
6330
7514
  try {
6331
- if (!fs17.existsSync(cursorPath)) fs17.copyFileSync(meshCursorPath, cursorPath);
7515
+ if (!fs20.existsSync(cursorPath)) fs20.copyFileSync(meshCursorPath, cursorPath);
6332
7516
  } catch {
6333
7517
  }
6334
7518
  }
@@ -6372,6 +7556,19 @@ var ActorDirectory = class extends ActorManager {
6372
7556
  this.#secondary.retryCapabilityWaiters();
6373
7557
  }
6374
7558
  async create(request, options = {}) {
7559
+ const previous = this.#directoryCreateTail;
7560
+ let release;
7561
+ this.#directoryCreateTail = new Promise((resolve) => {
7562
+ release = resolve;
7563
+ });
7564
+ await previous;
7565
+ try {
7566
+ return await this.#createInScope(request, options);
7567
+ } finally {
7568
+ release();
7569
+ }
7570
+ }
7571
+ async #createInScope(request, options) {
6375
7572
  const scope = request.scope ?? this.#defaultScope;
6376
7573
  if (scope !== "project" && scope !== "session") {
6377
7574
  throw new Error(`Invalid Fabric actor storage scope: ${String(scope)}`);
@@ -6379,8 +7576,9 @@ var ActorDirectory = class extends ActorManager {
6379
7576
  const name = request.name.trim();
6380
7577
  const sameName = this.list().filter((actor) => actor.name === name);
6381
7578
  const existing = sameName.find((actor) => actor.status !== "stopped");
6382
- if (existing) throw new Error(`A Fabric actor named ${name} is already active (${existing.id})`);
6383
- for (const actor of sameName) await this.remove(actor.id);
7579
+ const decision = actorNameDecision(Boolean(existing), sameName.some((actor) => actor.status === "stopped"));
7580
+ if (decision === "active") throw new Error(`A Fabric actor named ${name} is already active (${existing.id})`);
7581
+ if (decision === "stopped") throw new Error(`A stopped Fabric actor named ${name} already exists (${sameName[0].id}); remove it explicitly before creating another`);
6384
7582
  return scope === this.#defaultScope ? super.create(request, options) : this.#secondary.create(request, options);
6385
7583
  }
6386
7584
  list() {
@@ -6479,12 +7677,14 @@ var ActorDirectory = class extends ActorManager {
6479
7677
  return this.#isPrimary(args[0]) ? super.remove(...args) : this.#secondary.remove(...args);
6480
7678
  }
6481
7679
  async close() {
6482
- await Promise.all([super.close(), this.#secondary.close()]);
7680
+ const [primary, secondary] = await Promise.allSettled([super.close(), this.#secondary.close()]);
7681
+ if (primary.status === "rejected") throw primary.reason;
7682
+ if (secondary.status === "rejected") throw secondary.reason;
6483
7683
  }
6484
7684
  };
6485
7685
 
6486
7686
  // src/lifecycle/broker.ts
6487
- import { randomUUID as randomUUID9 } from "node:crypto";
7687
+ import { randomUUID as randomUUID10 } from "node:crypto";
6488
7688
  var subscriptionKey = (id) => FABRIC_LIFECYCLE_SUBSCRIPTION_PREFIX + id;
6489
7689
  var LifecycleBroker = class {
6490
7690
  constructor(mesh, identity, participants, options, deliver) {
@@ -6563,7 +7763,7 @@ var LifecycleBroker = class {
6563
7763
  const now = Date.now();
6564
7764
  const subscription = {
6565
7765
  format: 1,
6566
- id: randomUUID9().replaceAll("-", ""),
7766
+ id: randomUUID10().replaceAll("-", ""),
6567
7767
  from,
6568
7768
  events,
6569
7769
  to,
@@ -6733,7 +7933,7 @@ var LifecycleBroker = class {
6733
7933
  };
6734
7934
 
6735
7935
  // src/topology/control-plane.ts
6736
- import { createHash as createHash2, randomUUID as randomUUID10 } from "node:crypto";
7936
+ import { createHash as createHash2, randomUUID as randomUUID11 } from "node:crypto";
6737
7937
  var CONTROL_TOPIC = "fabric.control.command";
6738
7938
  var ACK_TOPIC = "fabric.control.ack";
6739
7939
  var CONTROL_SEEN_PREFIX = "topology/control-seen/";
@@ -6744,13 +7944,13 @@ var MAX_CONTROL_TIMEOUT_MS = 24 * 60 * 60 * 1e3 + 6e4;
6744
7944
  var MAX_INCARNATION_LENGTH = 128;
6745
7945
  var STALE_INCARNATION_ERROR = "Fabric control command targets a previous owner incarnation; the owner restarted. Re-resolve the participant and retry.";
6746
7946
  var controlSeenKey = (hostId, commandId) => CONTROL_SEEN_PREFIX + createHash2("sha256").update(`${hostId}\0${commandId}`).digest("hex");
6747
- var isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
7947
+ var isObject3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6748
7948
  var isIncarnation = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_INCARNATION_LENGTH;
6749
7949
  var controlAcceptanceBytes = (acceptance) => Buffer.byteLength(JSON.stringify(acceptance), "utf8");
6750
7950
  var commandFromEvent = (event) => {
6751
- if (!isObject2(event.data) || event.data.version !== 1) return void 0;
7951
+ if (!isObject3(event.data) || event.data.version !== 1) return void 0;
6752
7952
  const data = event.data;
6753
- if (data.version !== 1 || typeof data.commandId !== "string" || typeof data.targetId !== "string" || data.operation !== "steer" && data.operation !== "followUp" && data.operation !== "stop" && data.operation !== "ask" && data.operation !== "cancel" || typeof data.replyTo !== "string" || typeof data.requestedAt !== "number" || data.deadlineAt !== void 0 && typeof data.deadlineAt !== "number" || data.operation === "cancel" && typeof data.cancelCommandId !== "string" || data.ownerIncarnation !== void 0 && !isIncarnation(data.ownerIncarnation) || data.binding !== void 0 && (!isObject2(data.binding) || data.binding.model !== void 0 && typeof data.binding.model !== "string" || data.binding.thinking !== void 0 && typeof data.binding.thinking !== "string")) {
7953
+ if (data.version !== 1 || typeof data.commandId !== "string" || typeof data.targetId !== "string" || data.operation !== "steer" && data.operation !== "followUp" && data.operation !== "stop" && data.operation !== "ask" && data.operation !== "cancel" || typeof data.replyTo !== "string" || typeof data.requestedAt !== "number" || data.deadlineAt !== void 0 && typeof data.deadlineAt !== "number" || data.operation === "cancel" && typeof data.cancelCommandId !== "string" || data.ownerIncarnation !== void 0 && !isIncarnation(data.ownerIncarnation) || data.binding !== void 0 && (!isObject3(data.binding) || data.binding.model !== void 0 && typeof data.binding.model !== "string" || data.binding.thinking !== void 0 && typeof data.binding.thinking !== "string")) {
6754
7954
  return void 0;
6755
7955
  }
6756
7956
  const { sender: _forged, ...command } = data;
@@ -6760,7 +7960,7 @@ var commandFromEvent = (event) => {
6760
7960
  };
6761
7961
  };
6762
7962
  var controlSeenRecord = (value) => {
6763
- if (!isObject2(value) || value.format !== 1) return void 0;
7963
+ if (!isObject3(value) || value.format !== 1) return void 0;
6764
7964
  if (typeof value.hostId !== "string" || typeof value.commandId !== "string" || typeof value.targetId !== "string" || typeof value.expiresAt !== "number" || value.ownerIncarnation !== void 0 && !isIncarnation(value.ownerIncarnation)) {
6765
7965
  return void 0;
6766
7966
  }
@@ -6781,7 +7981,7 @@ var FabricControlPlane = class {
6781
7981
  #activeHandlers = /* @__PURE__ */ new Set();
6782
7982
  #pollMs;
6783
7983
  #ackTimeoutMs;
6784
- #incarnation = randomUUID10();
7984
+ #incarnation = randomUUID11();
6785
7985
  #offset;
6786
7986
  #lastSequence;
6787
7987
  #timer;
@@ -6843,7 +8043,7 @@ var FabricControlPlane = class {
6843
8043
  this.#pollMs * 4,
6844
8044
  Math.min(MAX_CONTROL_TIMEOUT_MS, Math.floor(options.timeoutMs ?? this.#ackTimeoutMs))
6845
8045
  );
6846
- const commandId = randomUUID10();
8046
+ const commandId = randomUUID11();
6847
8047
  const requestedAt = Date.now();
6848
8048
  let pendingRequest;
6849
8049
  const acceptance = new Promise((resolve, reject) => {
@@ -6937,7 +8137,7 @@ var FabricControlPlane = class {
6937
8137
  to: pending.ownerHostId,
6938
8138
  data: {
6939
8139
  version: 1,
6940
- commandId: randomUUID10(),
8140
+ commandId: randomUUID11(),
6941
8141
  targetId: pending.targetId,
6942
8142
  operation: "cancel",
6943
8143
  cancelCommandId: commandId,
@@ -6992,7 +8192,7 @@ var FabricControlPlane = class {
6992
8192
  }
6993
8193
  }
6994
8194
  #acceptAcknowledgement(event) {
6995
- if (!isObject2(event.data) || typeof event.data.commandId !== "string") return;
8195
+ if (!isObject3(event.data) || typeof event.data.commandId !== "string") return;
6996
8196
  const pending = this.#pending.get(event.data.commandId);
6997
8197
  if (!pending || event.data.version !== 1 || event.data.targetId !== pending.targetId || event.from.id !== pending.ownerIdentityId) {
6998
8198
  return;
@@ -7179,7 +8379,7 @@ var FabricControlPlane = class {
7179
8379
  while (sought.size > retained.size) {
7180
8380
  const page = this.mesh.tail(offset, this.mesh.maxReadEvents);
7181
8381
  for (const event of page.events) {
7182
- if (event.topic !== CONTROL_TOPIC || !isObject2(event.data)) continue;
8382
+ if (event.topic !== CONTROL_TOPIC || !isObject3(event.data)) continue;
7183
8383
  const commandId = event.data.commandId;
7184
8384
  if (typeof commandId === "string" && sought.has(commandId)) retained.add(commandId);
7185
8385
  }
@@ -7214,14 +8414,18 @@ var FabricControlPlane = class {
7214
8414
  // src/topology/participant-directory.ts
7215
8415
  import { createHash as createHash3 } from "node:crypto";
7216
8416
  var PARTICIPANT_PREFIX = "topology/participants/";
7217
- var PEER_SEQ_KEY = "topology/peer-seq";
8417
+ var PEER_SEQ_KEY = `topology/peer-seq/${FABRIC_PEER_LABEL_SEQUENCE}`;
8418
+ var MAX_HELD_LABEL_SKIPS = 64;
7218
8419
  var HOST_PREFIX = "topology/hosts/";
7219
8420
  var LEGACY_SESSION_PREFIX = "sessions/";
7220
8421
  var LEGACY_ACTOR_PREFIX = "actors/";
7221
8422
  var PARTICIPANT_HEARTBEAT_MS = 5e3;
7222
8423
  var PARTICIPANT_LEASE_MS = 15e3;
8424
+ var TOMBSTONE_PREFIX = "topology/tombstones/";
8425
+ var DEPARTED_LIMIT = 32;
8426
+ var DEPARTED_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
7223
8427
  var keyFor = (prefix, id) => prefix + createHash3("sha256").update(id).digest("hex");
7224
- var isObject3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
8428
+ var isObject4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
7225
8429
  var participantKind = (value) => value === "root" || value === "agent" || value === "actor" || value === "provider" ? value : void 0;
7226
8430
  var RUNNER_ID_PATTERN = /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/;
7227
8431
  var isRunnerId = (value) => typeof value === "string" && value.length <= 64 && RUNNER_ID_PATTERN.test(value);
@@ -7233,7 +8437,8 @@ var transports = /* @__PURE__ */ new Set([
7233
8437
  "tmux",
7234
8438
  "screen",
7235
8439
  "localterm",
7236
- "herdr"
8440
+ "herdr",
8441
+ "herdr-core"
7237
8442
  ]);
7238
8443
  var capabilities = /* @__PURE__ */ new Set([
7239
8444
  "steer",
@@ -7245,7 +8450,7 @@ var capabilities = /* @__PURE__ */ new Set([
7245
8450
  "fabric"
7246
8451
  ]);
7247
8452
  var participantFromEntry = (entry) => {
7248
- if (!isObject3(entry.value) || entry.value.format !== 1) return void 0;
8453
+ if (!isObject4(entry.value) || entry.value.format !== 1) return void 0;
7249
8454
  const value = entry.value;
7250
8455
  const kind = participantKind(value.kind);
7251
8456
  if (!kind || typeof value.id !== "string" || entry.key !== keyFor(PARTICIPANT_PREFIX, value.id) || typeof value.rootId !== "string" || typeof value.ownerHostId !== "string" || typeof value.ownerIdentityId !== "string" || entry.updatedBy.id !== value.ownerIdentityId || value.ownerIncarnation !== void 0 && (typeof value.ownerIncarnation !== "string" || value.ownerIncarnation.length === 0 || value.ownerIncarnation.length > 128) || typeof value.name !== "string" || typeof value.status !== "string" || (kind === "provider" ? value.runner !== void 0 || typeof value.provider !== "string" : !isRunnerId(value.runner)) || typeof value.transport !== "string" || !transports.has(value.transport) || !Array.isArray(value.capabilities) || !value.capabilities.every(
@@ -7256,13 +8461,38 @@ var participantFromEntry = (entry) => {
7256
8461
  return value;
7257
8462
  };
7258
8463
  var hostFromEntry = (entry) => {
7259
- if (!isObject3(entry.value) || entry.value.format !== 1) return void 0;
8464
+ if (!isObject4(entry.value) || entry.value.format !== 1) return void 0;
8465
+ const value = entry.value;
8466
+ if (typeof value.id !== "string" || entry.key !== keyFor(HOST_PREFIX, value.id) || typeof value.rootId !== "string" || !isObject4(value.identity) || typeof value.identity.id !== "string" || typeof value.identity.name !== "string" || entry.updatedBy.id !== value.identity.id || value.identity.kind !== "main" && value.identity.kind !== "agent" && value.identity.kind !== "actor" || typeof value.startedAt !== "number" || typeof value.updatedAt !== "number" || typeof value.expiresAt !== "number") {
8467
+ return void 0;
8468
+ }
8469
+ return value;
8470
+ };
8471
+ var optionalString = (value) => value === void 0 || typeof value === "string";
8472
+ var tombstoneFromEntry = (entry) => {
8473
+ if (!isObject4(entry.value) || entry.value.format !== 1) return void 0;
7260
8474
  const value = entry.value;
7261
- if (typeof value.id !== "string" || entry.key !== keyFor(HOST_PREFIX, value.id) || typeof value.rootId !== "string" || !isObject3(value.identity) || typeof value.identity.id !== "string" || typeof value.identity.name !== "string" || entry.updatedBy.id !== value.identity.id || value.identity.kind !== "main" && value.identity.kind !== "agent" && value.identity.kind !== "actor" || typeof value.startedAt !== "number" || typeof value.updatedAt !== "number" || typeof value.expiresAt !== "number") {
8475
+ if (value.kind !== "root" || value.status !== "stopped" || typeof value.id !== "string" || entry.key !== keyFor(TOMBSTONE_PREFIX, value.id) || typeof value.rootId !== "string" || typeof value.ownerHostId !== "string" || typeof value.ownerIdentityId !== "string" || entry.updatedBy.id !== value.ownerIdentityId || typeof value.name !== "string" || !optionalString(value.ownerIncarnation) || !optionalString(value.label) || !optionalString(value.cwd) || !optionalString(value.sessionId) || typeof value.startedAt !== "number" || typeof value.lastSeenAt !== "number") {
7262
8476
  return void 0;
7263
8477
  }
7264
8478
  return value;
7265
8479
  };
8480
+ var departedFromRoot = (participant, status, lastSeenAt) => ({
8481
+ format: 1,
8482
+ id: participant.id,
8483
+ kind: "root",
8484
+ rootId: participant.rootId,
8485
+ ownerHostId: participant.ownerHostId,
8486
+ ownerIdentityId: participant.ownerIdentityId,
8487
+ ...participant.ownerIncarnation ? { ownerIncarnation: participant.ownerIncarnation } : {},
8488
+ name: participant.name,
8489
+ ...participant.label ? { label: participant.label } : {},
8490
+ ...participant.cwd ? { cwd: participant.cwd } : {},
8491
+ ...participant.sessionId ? { sessionId: participant.sessionId } : {},
8492
+ status,
8493
+ startedAt: participant.startedAt,
8494
+ lastSeenAt
8495
+ });
7266
8496
  var peerFromParticipant = (participant) => {
7267
8497
  if (participant.kind !== "root" || !participant.cwd || !participant.sessionId || participant.status !== "idle" && participant.status !== "running") {
7268
8498
  return void 0;
@@ -7286,7 +8516,7 @@ var peerFromParticipant = (participant) => {
7286
8516
  };
7287
8517
  };
7288
8518
  var legacyRootFromEntry = (entry, localRootId, now) => {
7289
- if (now - entry.updatedAt > PARTICIPANT_LEASE_MS || !isObject3(entry.value)) return void 0;
8519
+ if (now - entry.updatedAt > PARTICIPANT_LEASE_MS || !isObject4(entry.value)) return void 0;
7290
8520
  const value = entry.value;
7291
8521
  if (typeof value.id !== "string" || value.id === localRootId || typeof value.sessionId !== "string" || entry.key !== `${LEGACY_SESSION_PREFIX}${value.sessionId}` || entry.updatedBy.id !== value.id || typeof value.cwd !== "string" || typeof value.startedAt !== "number" || value.status !== "idle" && value.status !== "running") {
7292
8522
  return void 0;
@@ -7316,7 +8546,7 @@ var legacyRootFromEntry = (entry, localRootId, now) => {
7316
8546
  };
7317
8547
  };
7318
8548
  var legacyActorFromEntry = (entry, roots) => {
7319
- if (!isObject3(entry.value)) return void 0;
8549
+ if (!isObject4(entry.value)) return void 0;
7320
8550
  const value = entry.value;
7321
8551
  if (typeof value.id !== "string" || typeof value.name !== "string" || !isRunnerId(value.runner) || typeof value.status !== "string") {
7322
8552
  return void 0;
@@ -7349,17 +8579,25 @@ var legacyActorFromEntry = (entry, roots) => {
7349
8579
  stale: false
7350
8580
  };
7351
8581
  };
8582
+ var liveOwner = (participant, hosts, now) => {
8583
+ const owner = hosts.get(participant.ownerHostId);
8584
+ return !!owner && owner.expiresAt >= now && owner.identity.id === participant.ownerIdentityId && owner.rootId === participant.rootId;
8585
+ };
7352
8586
  var ParticipantDirectory = class {
7353
8587
  constructor(mesh, options) {
7354
8588
  this.mesh = mesh;
7355
8589
  this.options = options;
7356
8590
  this.#heartbeatMs = Math.max(100, options.heartbeatMs ?? PARTICIPANT_HEARTBEAT_MS);
7357
8591
  this.#leaseMs = Math.max(this.#heartbeatMs * 2, options.leaseMs ?? PARTICIPANT_LEASE_MS);
8592
+ this.#departedLimit = Math.max(0, Math.floor(options.departedLimit ?? DEPARTED_LIMIT));
8593
+ this.#departedRetentionMs = Math.max(0, options.departedRetentionMs ?? DEPARTED_RETENTION_MS);
7358
8594
  }
7359
8595
  #sources = /* @__PURE__ */ new Set();
7360
8596
  #startedAt = Date.now();
7361
8597
  #heartbeatMs;
7362
8598
  #leaseMs;
8599
+ #departedLimit;
8600
+ #departedRetentionMs;
7363
8601
  #localRecords = /* @__PURE__ */ new Map();
7364
8602
  #timer;
7365
8603
  #closed = false;
@@ -7430,18 +8668,12 @@ var ParticipantDirectory = class {
7430
8668
  if (!options.kinds || options.kinds.includes(self2.kind)) byId2.set(self2.id, self2);
7431
8669
  return [...byId2.values()];
7432
8670
  }
7433
- const hosts = new Map(
7434
- this.mesh.listAll(HOST_PREFIX).flatMap((entry) => {
7435
- const host = hostFromEntry(entry);
7436
- return host ? [[host.id, host]] : [];
7437
- })
7438
- );
8671
+ const hosts = this.#hosts();
7439
8672
  const byId = /* @__PURE__ */ new Map();
7440
8673
  for (const entry of this.mesh.listAll(PARTICIPANT_PREFIX)) {
7441
8674
  const participant = participantFromEntry(entry);
7442
8675
  if (!participant) continue;
7443
- const owner = hosts.get(participant.ownerHostId);
7444
- const stale = !owner || owner.expiresAt < now || owner.identity.id !== participant.ownerIdentityId || owner.rootId !== participant.rootId;
8676
+ const stale = !liveOwner(participant, hosts, now);
7445
8677
  if (stale && !options.includeStale) continue;
7446
8678
  if (options.scope === "local" && participant.ownerHostId !== this.options.hostId) continue;
7447
8679
  if (options.scope === "lineage" && participant.rootId !== this.options.rootId) continue;
@@ -7481,10 +8713,25 @@ var ParticipantDirectory = class {
7481
8713
  }
7482
8714
  get(id, now = Date.now()) {
7483
8715
  const target = id === "main" ? this.options.rootId : id;
8716
+ if (this.options.enabled) {
8717
+ const participant = this.#participant(target);
8718
+ if (participant) {
8719
+ const entry = this.mesh.get(keyFor(HOST_PREFIX, participant.ownerHostId));
8720
+ const owner = entry && hostFromEntry(entry);
8721
+ if (owner && liveOwner(participant, /* @__PURE__ */ new Map([[owner.id, owner]]), now)) {
8722
+ return { ...participant, local: participant.ownerHostId === this.options.hostId, stale: false };
8723
+ }
8724
+ }
8725
+ }
7484
8726
  return this.list({ scope: "project" }, now).find((participant) => participant.id === target);
7485
8727
  }
8728
+ #participant(id) {
8729
+ const entry = this.mesh.get(keyFor(PARTICIPANT_PREFIX, id));
8730
+ const participant = entry && participantFromEntry(entry);
8731
+ return participant?.id === id ? participant : void 0;
8732
+ }
7486
8733
  self(now = Date.now()) {
7487
- const existing = this.#localRecords.get(this.options.identity.id) ?? this.mesh.listAll(PARTICIPANT_PREFIX).map(participantFromEntry).find((participant) => participant?.id === this.options.identity.id);
8734
+ const existing = this.#localRecords.get(this.options.identity.id) ?? this.#participant(this.options.identity.id);
7488
8735
  if (existing) {
7489
8736
  return {
7490
8737
  ...existing,
@@ -7524,6 +8771,38 @@ var ParticipantDirectory = class {
7524
8771
  return peer ? [peer] : [];
7525
8772
  });
7526
8773
  }
8774
+ /**
8775
+ * Root sessions that are no longer live, newest first: `stopped` from the
8776
+ * tombstone a clean close wrote, `lost` from a root record whose owner
8777
+ * lease expired without one. Explicit opt-in only; live queries never read
8778
+ * tombstones. Pure read: never writes or prunes.
8779
+ */
8780
+ departed(options = {}, now = Date.now()) {
8781
+ if (!this.options.enabled) return [];
8782
+ const hosts = this.#hosts();
8783
+ const live = /* @__PURE__ */ new Set([this.options.rootId]);
8784
+ const byId = /* @__PURE__ */ new Map();
8785
+ for (const entry of this.mesh.listAll(PARTICIPANT_PREFIX)) {
8786
+ const participant = participantFromEntry(entry);
8787
+ if (participant?.kind !== "root") continue;
8788
+ if (liveOwner(participant, hosts, now)) {
8789
+ live.add(participant.id);
8790
+ continue;
8791
+ }
8792
+ const owner = hosts.get(participant.ownerHostId);
8793
+ const heartbeat = owner?.identity.id === participant.ownerIdentityId ? owner.updatedAt : 0;
8794
+ byId.set(participant.id, departedFromRoot(participant, "lost", Math.max(participant.updatedAt, heartbeat)));
8795
+ }
8796
+ for (const entry of this.mesh.listAll(TOMBSTONE_PREFIX)) {
8797
+ const tombstone = tombstoneFromEntry(entry);
8798
+ if (!tombstone) continue;
8799
+ const lost = byId.get(tombstone.id);
8800
+ if (!lost || tombstone.lastSeenAt >= lost.lastSeenAt) byId.set(tombstone.id, tombstone);
8801
+ }
8802
+ const cutoff = now - this.#departedRetentionMs;
8803
+ const limit = Math.max(0, Math.floor(options.limit ?? (this.#departedLimit || DEPARTED_LIMIT)));
8804
+ return [...byId.values()].filter((participant) => !live.has(participant.id) && participant.lastSeenAt >= cutoff).sort((left, right) => right.lastSeenAt - left.lastSeenAt || left.id.localeCompare(right.id)).slice(0, limit);
8805
+ }
7527
8806
  root(main) {
7528
8807
  return {
7529
8808
  format: 1,
@@ -7560,8 +8839,12 @@ var ParticipantDirectory = class {
7560
8839
  this.#timer = void 0;
7561
8840
  await this.#refreshing?.catch(() => void 0);
7562
8841
  if (!this.options.enabled) return;
7563
- const owned = this.mesh.listAll(PARTICIPANT_PREFIX).filter((entry) => participantFromEntry(entry)?.ownerHostId === this.options.hostId);
7564
- await Promise.allSettled(owned.map((entry) => this.mesh.delete({ key: entry.key, ifVersion: entry.version })));
8842
+ const owned = this.mesh.listAll(PARTICIPANT_PREFIX).flatMap((entry) => {
8843
+ const participant = participantFromEntry(entry);
8844
+ return participant?.ownerHostId === this.options.hostId ? [{ entry, participant }] : [];
8845
+ });
8846
+ await this.#writeTombstones(owned.map((item) => item.participant)).catch(() => void 0);
8847
+ await Promise.allSettled(owned.map(({ entry }) => this.mesh.delete({ key: entry.key, ifVersion: entry.version })));
7565
8848
  const legacySessionKey = this.#legacySessionKey();
7566
8849
  if (legacySessionKey) {
7567
8850
  const legacy = this.mesh.get(legacySessionKey);
@@ -7572,6 +8855,23 @@ var ParticipantDirectory = class {
7572
8855
  const hostEntry = this.mesh.get(keyFor(HOST_PREFIX, this.options.hostId));
7573
8856
  if (hostEntry) await this.mesh.delete({ key: hostEntry.key, ifVersion: hostEntry.version }).catch(() => void 0);
7574
8857
  }
8858
+ /** Replace this host's root records with stopped tombstones, then prune by age and count. */
8859
+ async #writeTombstones(owned) {
8860
+ if (this.#departedLimit === 0) return;
8861
+ const now = Date.now();
8862
+ for (const participant of owned) {
8863
+ if (participant.kind !== "root") continue;
8864
+ await this.mesh.put({
8865
+ key: keyFor(TOMBSTONE_PREFIX, participant.id),
8866
+ value: departedFromRoot(participant, "stopped", now),
8867
+ identity: this.options.identity
8868
+ }).catch(() => void 0);
8869
+ }
8870
+ const cutoff = now - this.#departedRetentionMs;
8871
+ const kept = this.mesh.listAll(TOMBSTONE_PREFIX).map((entry) => ({ entry, tombstone: tombstoneFromEntry(entry) })).sort((left, right) => (right.tombstone?.lastSeenAt ?? 0) - (left.tombstone?.lastSeenAt ?? 0));
8872
+ const prune = kept.filter(({ tombstone }, index) => !tombstone || tombstone.lastSeenAt < cutoff || index >= this.#departedLimit);
8873
+ await Promise.allSettled(prune.map(({ entry }) => this.mesh.delete({ key: entry.key, ifVersion: entry.version })));
8874
+ }
7575
8875
  async #refresh() {
7576
8876
  const now = Date.now();
7577
8877
  const desired = /* @__PURE__ */ new Map();
@@ -7713,15 +9013,46 @@ var ParticipantDirectory = class {
7713
9013
  record.label = existing.label;
7714
9014
  continue;
7715
9015
  }
7716
- const seq = await this.#claimPeerSeq();
7717
- if (seq !== void 0) record.label = `${peerLabelPrefix(record.cwd)}-${seq}`;
9016
+ const recorded = this.options.recordedLabel?.();
9017
+ if (recorded && this.#reusableLabel(recorded, record)) {
9018
+ record.label = recorded;
9019
+ continue;
9020
+ }
9021
+ if (this.options.labelWanted?.() === false) continue;
9022
+ for (let attempt = 0; attempt < MAX_HELD_LABEL_SKIPS; attempt += 1) {
9023
+ const seq = await this.#claimPeerSeq();
9024
+ if (seq === void 0) break;
9025
+ const label = `${peerLabelPrefix(record.cwd)}-${seq}`;
9026
+ if (this.#heldByOther(label, record.id)) continue;
9027
+ record.label = label;
9028
+ break;
9029
+ }
7718
9030
  }
7719
9031
  }
9032
+ /** A recorded label fits this project and no other participant holds it. */
9033
+ #reusableLabel(label, record) {
9034
+ return new RegExp(`^${peerLabelPrefix(record.cwd)}-[1-9][0-9]*$`).test(label) && !this.#heldByOther(label, record.id);
9035
+ }
9036
+ /** A live participant of another id holds the label; a dead session's leftover record does not. */
9037
+ #heldByOther(label, id) {
9038
+ const hosts = this.#hosts();
9039
+ const now = Date.now();
9040
+ return this.mesh.listAll(PARTICIPANT_PREFIX).some((entry) => {
9041
+ const participant = participantFromEntry(entry);
9042
+ return participant !== void 0 && participant.id !== id && participant.label === label && liveOwner(participant, hosts, now);
9043
+ });
9044
+ }
9045
+ #hosts() {
9046
+ return new Map(this.mesh.listAll(HOST_PREFIX).flatMap((entry) => {
9047
+ const host = hostFromEntry(entry);
9048
+ return host ? [[host.id, host]] : [];
9049
+ }));
9050
+ }
7720
9051
  /** CAS-claim the next project-wide peer sequence number. ifVersion 0 creates. */
7721
9052
  async #claimPeerSeq() {
7722
9053
  for (let attempt = 0; attempt < 8; attempt += 1) {
7723
9054
  const entry = this.mesh.get(PEER_SEQ_KEY);
7724
- const current = entry && isObject3(entry.value) && typeof entry.value.next === "number" && Number.isInteger(entry.value.next) && entry.value.next >= 1 ? entry.value.next : 0;
9055
+ const current = entry && isObject4(entry.value) && typeof entry.value.next === "number" && Number.isInteger(entry.value.next) && entry.value.next >= 1 ? entry.value.next : 0;
7725
9056
  try {
7726
9057
  await this.mesh.put({
7727
9058
  key: PEER_SEQ_KEY,
@@ -7822,6 +9153,7 @@ export {
7822
9153
  resolvePiBinary,
7823
9154
  resolveInheritedSessionPins,
7824
9155
  withInheritedSessionPins,
9156
+ hasWorkerRecovery,
7825
9157
  isFabricWorktreePath,
7826
9158
  addCloneFirstWorktree,
7827
9159
  PiCodingAgent,
@@ -7836,6 +9168,8 @@ export {
7836
9168
  AgentManager,
7837
9169
  resolveActorDeliveryPolicy,
7838
9170
  actorDeliveryNotice,
9171
+ ActorStoreReadError,
9172
+ readStoreJson,
7839
9173
  ActorRegistryOwnershipError,
7840
9174
  ActorDirectory,
7841
9175
  LifecycleBroker,
@@ -7844,4 +9178,4 @@ export {
7844
9178
  agentParticipantRecords,
7845
9179
  actorParticipantRecord
7846
9180
  };
7847
- //# sourceMappingURL=chunk-FE6NOAO7.js.map
9181
+ //# sourceMappingURL=chunk-VGRUWTMG.js.map