@e4779/pi-fabric 0.117.2-fork.31 → 0.131.0-fork.32

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 (796) hide show
  1. package/README.md +12 -5
  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/global-registry.d.ts +8 -0
  9. package/dist/actors/global-registry.d.ts.map +1 -1
  10. package/dist/actors/host-event-payload.d.ts +14 -0
  11. package/dist/actors/host-event-payload.d.ts.map +1 -1
  12. package/dist/actors/manager.d.ts +4 -3
  13. package/dist/actors/manager.d.ts.map +1 -1
  14. package/dist/actors/mesh-monitor.d.ts +2 -0
  15. package/dist/actors/mesh-monitor.d.ts.map +1 -1
  16. package/dist/actors/name-policy.d.ts +3 -0
  17. package/dist/actors/name-policy.d.ts.map +1 -0
  18. package/dist/actors/registry-store.d.ts +14 -5
  19. package/dist/actors/registry-store.d.ts.map +1 -1
  20. package/dist/actors/store-read.d.ts +16 -0
  21. package/dist/actors/store-read.d.ts.map +1 -0
  22. package/dist/agents/agent-files.d.ts +80 -0
  23. package/dist/agents/agent-files.d.ts.map +1 -0
  24. package/dist/agents/agent-files.js +327 -0
  25. package/dist/agents/agent-files.js.map +7 -0
  26. package/dist/agents/child-skills.d.ts +60 -0
  27. package/dist/agents/child-skills.d.ts.map +1 -0
  28. package/dist/agents/child-skills.js +94 -0
  29. package/dist/agents/child-skills.js.map +7 -0
  30. package/dist/agents/clone-first-worktree.d.ts +6 -0
  31. package/dist/agents/clone-first-worktree.d.ts.map +1 -1
  32. package/dist/agents/cow-clone.d.ts.map +1 -1
  33. package/dist/agents/handoff.d.ts +12 -2
  34. package/dist/agents/handoff.d.ts.map +1 -1
  35. package/dist/agents/herdr-status.d.ts +26 -0
  36. package/dist/agents/herdr-status.d.ts.map +1 -0
  37. package/dist/agents/herdr-status.js +161 -0
  38. package/dist/agents/herdr-status.js.map +7 -0
  39. package/dist/agents/hosted-run.d.ts +20 -4
  40. package/dist/agents/hosted-run.d.ts.map +1 -1
  41. package/dist/agents/manager.d.ts +18 -2
  42. package/dist/agents/manager.d.ts.map +1 -1
  43. package/dist/agents/model-pin-guard.d.ts +27 -0
  44. package/dist/agents/model-pin-guard.d.ts.map +1 -0
  45. package/dist/agents/model-pin-guard.js +86 -0
  46. package/dist/agents/model-pin-guard.js.map +7 -0
  47. package/dist/agents/model-pin.d.ts +25 -0
  48. package/dist/agents/model-pin.d.ts.map +1 -0
  49. package/dist/agents/provider-bridge.d.ts +7 -6
  50. package/dist/agents/provider-bridge.d.ts.map +1 -1
  51. package/dist/agents/provider-bridge.js +33 -5
  52. package/dist/agents/provider-bridge.js.map +3 -3
  53. package/dist/agents/request.d.ts.map +1 -1
  54. package/dist/agents/result.d.ts.map +1 -1
  55. package/dist/agents/result.js +1 -1
  56. package/dist/agents/runner-notice.d.ts.map +1 -1
  57. package/dist/agents/runner-protocol.d.ts +8 -0
  58. package/dist/agents/runner-protocol.d.ts.map +1 -1
  59. package/dist/agents/service-schema.d.ts.map +1 -1
  60. package/dist/agents/transports/herdr-socket.d.ts +12 -0
  61. package/dist/agents/transports/herdr-socket.d.ts.map +1 -0
  62. package/dist/agents/transports/herdr-transport.d.ts.map +1 -1
  63. package/dist/agents/types.d.ts +51 -0
  64. package/dist/agents/types.d.ts.map +1 -1
  65. package/dist/agents/worker-recovery.d.ts +75 -0
  66. package/dist/agents/worker-recovery.d.ts.map +1 -0
  67. package/dist/agents/worktree-manager.d.ts.map +1 -1
  68. package/dist/agents.js +12 -11
  69. package/dist/agents.js.map +2 -2
  70. package/dist/audit/details.d.ts +36 -1
  71. package/dist/audit/details.d.ts.map +1 -1
  72. package/dist/audit/projection.d.ts.map +1 -1
  73. package/dist/audit/trace-schema.d.ts +50 -0
  74. package/dist/audit/trace-schema.d.ts.map +1 -0
  75. package/dist/audit/trace.d.ts +2 -48
  76. package/dist/audit/trace.d.ts.map +1 -1
  77. package/dist/chunks/chunk-2RWNVCFD.js +483 -0
  78. package/dist/chunks/chunk-2RWNVCFD.js.map +7 -0
  79. package/dist/chunks/chunk-2SCMGO2Z.js +16 -0
  80. package/dist/chunks/chunk-2SCMGO2Z.js.map +7 -0
  81. package/dist/chunks/chunk-35EEGOH3.js +324 -0
  82. package/dist/chunks/chunk-35EEGOH3.js.map +7 -0
  83. package/dist/chunks/{chunk-3FJUP3GV.js → chunk-36XQFTEN.js} +2 -2
  84. package/dist/chunks/{chunk-UTOBAZ5T.js → chunk-37NIOSVU.js} +1 -1
  85. package/dist/chunks/chunk-37NIOSVU.js.map +7 -0
  86. package/dist/chunks/chunk-3IJEQBFS.js +25 -0
  87. package/dist/chunks/chunk-3IJEQBFS.js.map +7 -0
  88. package/dist/chunks/{chunk-EHQQ4KCX.js → chunk-3MOY6WIB.js} +84 -19
  89. package/dist/chunks/chunk-3MOY6WIB.js.map +7 -0
  90. package/dist/chunks/chunk-3PKZSIRA.js +1312 -0
  91. package/dist/chunks/chunk-3PKZSIRA.js.map +7 -0
  92. package/dist/chunks/chunk-3VK6UGAN.js +64 -0
  93. package/dist/chunks/chunk-3VK6UGAN.js.map +7 -0
  94. package/dist/chunks/{chunk-ROTCDDOV.js → chunk-3XT5WHSG.js} +59 -119
  95. package/dist/chunks/chunk-3XT5WHSG.js.map +7 -0
  96. package/dist/chunks/{chunk-FIDUHKMM.js → chunk-4BYS4ZLY.js} +16 -16
  97. package/dist/chunks/chunk-4BYS4ZLY.js.map +7 -0
  98. package/dist/chunks/{chunk-K7J2ABAZ.js → chunk-4KX6BIPL.js} +91 -31
  99. package/dist/chunks/chunk-4KX6BIPL.js.map +7 -0
  100. package/dist/chunks/{chunk-UOM37PE4.js → chunk-4PBW54I2.js} +162 -92
  101. package/dist/chunks/chunk-4PBW54I2.js.map +7 -0
  102. package/dist/chunks/{chunk-ZEXCKK4K.js → chunk-4WKD3YM3.js} +3 -3
  103. package/dist/chunks/{chunk-PK4NIJEV.js → chunk-4XMXFHAR.js} +62 -3
  104. package/dist/chunks/chunk-4XMXFHAR.js.map +7 -0
  105. package/dist/chunks/{chunk-4EW7GVUR.js → chunk-56NMRVTV.js} +589 -377
  106. package/dist/chunks/chunk-56NMRVTV.js.map +7 -0
  107. package/dist/chunks/{chunk-GIK2WNAK.js → chunk-5BOTHX47.js} +109 -20
  108. package/dist/chunks/chunk-5BOTHX47.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-GO32KSEZ.js → chunk-7CIES6X2.js} +84 -9
  118. package/dist/chunks/chunk-7CIES6X2.js.map +7 -0
  119. package/dist/chunks/{chunk-G4TLWHRS.js → chunk-7N7IC3Z2.js} +4 -3
  120. package/dist/chunks/{chunk-G4TLWHRS.js.map → chunk-7N7IC3Z2.js.map} +2 -2
  121. package/dist/chunks/{chunk-5XBYFSI5.js → chunk-7YNE4NB2.js} +2 -2
  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-F2LGSRIN.js +38 -0
  133. package/dist/chunks/chunk-F2LGSRIN.js.map +7 -0
  134. package/dist/chunks/chunk-F6A6MQ6G.js +609 -0
  135. package/dist/chunks/chunk-F6A6MQ6G.js.map +7 -0
  136. package/dist/chunks/{chunk-IR3PIHJM.js → chunk-FK73YJKV.js} +67 -2
  137. package/dist/chunks/chunk-FK73YJKV.js.map +7 -0
  138. package/dist/chunks/{chunk-VYQV5JRT.js → chunk-GJVKEHDL.js} +2 -2
  139. package/dist/chunks/chunk-GJVKEHDL.js.map +7 -0
  140. package/dist/chunks/{chunk-TIIIHPHF.js → chunk-GS67KDMV.js} +2 -2
  141. package/dist/chunks/{chunk-D5NYNIST.js → chunk-H57KPL3V.js} +5 -5
  142. package/dist/chunks/{chunk-KVYNGDGC.js → chunk-HFDJWLMS.js} +6 -6
  143. package/dist/chunks/{chunk-KVYNGDGC.js.map → chunk-HFDJWLMS.js.map} +1 -1
  144. package/dist/chunks/{chunk-INRXG4J5.js → chunk-HGD75NZY.js} +2 -2
  145. package/dist/chunks/{chunk-CRRUW26I.js → chunk-HRDMBGMY.js} +12 -12
  146. package/dist/chunks/{chunk-CRRUW26I.js.map → chunk-HRDMBGMY.js.map} +2 -2
  147. package/dist/chunks/{chunk-MLLYR3Y6.js → chunk-HSEZPCL5.js} +19 -78
  148. package/dist/chunks/chunk-HSEZPCL5.js.map +7 -0
  149. package/dist/chunks/{chunk-LNASO4VT.js → chunk-IOGDTIGN.js} +44 -19
  150. package/dist/chunks/chunk-IOGDTIGN.js.map +7 -0
  151. package/dist/chunks/chunk-JMUUNW2H.js +65 -0
  152. package/dist/chunks/chunk-JMUUNW2H.js.map +7 -0
  153. package/dist/chunks/{chunk-UXIBKMUM.js → chunk-KIFOEBYJ.js} +4 -4
  154. package/dist/chunks/{chunk-SPCJXN4K.js → chunk-LKYLD5SN.js} +298 -65
  155. package/dist/chunks/chunk-LKYLD5SN.js.map +7 -0
  156. package/dist/chunks/{chunk-FUY6XVRX.js → chunk-MPMEK3IQ.js} +2 -2
  157. package/dist/chunks/{chunk-HP5P7NBO.js → chunk-MSDL7U6Q.js} +4 -4
  158. package/dist/chunks/chunk-N7ZAK2PB.js +132 -0
  159. package/dist/chunks/chunk-N7ZAK2PB.js.map +7 -0
  160. package/dist/chunks/{chunk-VSDUSNIA.js → chunk-NBIYYMKS.js} +8 -2
  161. package/dist/chunks/chunk-NBIYYMKS.js.map +7 -0
  162. package/dist/chunks/chunk-NENQZCGW.js +45 -0
  163. package/dist/chunks/chunk-NENQZCGW.js.map +7 -0
  164. package/dist/chunks/chunk-NJHJKINP.js +47 -0
  165. package/dist/chunks/chunk-NJHJKINP.js.map +7 -0
  166. package/dist/chunks/{chunk-U366I5K2.js → chunk-NQ7IWEIF.js} +18 -6
  167. package/dist/chunks/chunk-NQ7IWEIF.js.map +7 -0
  168. package/dist/chunks/{chunk-ZQMBS5SH.js → chunk-OJ4HAALD.js} +15 -12
  169. package/dist/chunks/chunk-OJ4HAALD.js.map +7 -0
  170. package/dist/chunks/chunk-OZCJU3PZ.js +33 -0
  171. package/dist/chunks/chunk-OZCJU3PZ.js.map +7 -0
  172. package/dist/chunks/chunk-P3DCXKL3.js +40 -0
  173. package/dist/chunks/chunk-P3DCXKL3.js.map +7 -0
  174. package/dist/chunks/chunk-P7YSPKTM.js +294 -0
  175. package/dist/chunks/chunk-P7YSPKTM.js.map +7 -0
  176. package/dist/chunks/chunk-PQVUMJ5J.js +223 -0
  177. package/dist/chunks/chunk-PQVUMJ5J.js.map +7 -0
  178. package/dist/chunks/chunk-PUBHBEYO.js +84 -0
  179. package/dist/chunks/chunk-PUBHBEYO.js.map +7 -0
  180. package/dist/chunks/{chunk-P4KH4S4S.js → chunk-QGTD3LAZ.js} +5 -20
  181. package/dist/chunks/chunk-QGTD3LAZ.js.map +7 -0
  182. package/dist/chunks/{chunk-TIJ3YQXX.js → chunk-QOEOKW2X.js} +2 -2
  183. package/dist/chunks/{chunk-TIJ3YQXX.js.map → chunk-QOEOKW2X.js.map} +1 -1
  184. package/dist/chunks/{chunk-QT4W5YVB.js → chunk-RAA3FAYZ.js} +2 -2
  185. package/dist/chunks/{chunk-WJJXODAB.js → chunk-RLKRZXSX.js} +8 -1
  186. package/dist/chunks/{chunk-WJJXODAB.js.map → chunk-RLKRZXSX.js.map} +2 -2
  187. package/dist/chunks/chunk-RWKQ5SRW.js +129 -0
  188. package/dist/chunks/chunk-RWKQ5SRW.js.map +7 -0
  189. package/dist/chunks/chunk-SW25R47N.js +71 -0
  190. package/dist/chunks/chunk-SW25R47N.js.map +7 -0
  191. package/dist/chunks/{chunk-EFETPXU2.js → chunk-TJZYM2SP.js} +118 -237
  192. package/dist/chunks/chunk-TJZYM2SP.js.map +7 -0
  193. package/dist/chunks/{chunk-53N2I4QA.js → chunk-TXCNZCZP.js} +2 -2
  194. package/dist/chunks/chunk-UD7LFV43.js +28 -0
  195. package/dist/chunks/chunk-UD7LFV43.js.map +7 -0
  196. package/dist/chunks/{chunk-ASSLHWZS.js → chunk-UFMYN5TA.js} +2 -2
  197. package/dist/chunks/{chunk-7QKKLBHJ.js → chunk-UPMWLOKL.js} +10 -1
  198. package/dist/chunks/{chunk-7QKKLBHJ.js.map → chunk-UPMWLOKL.js.map} +2 -2
  199. package/dist/chunks/chunk-V4OW2ULC.js +422 -0
  200. package/dist/chunks/chunk-V4OW2ULC.js.map +7 -0
  201. package/dist/chunks/{chunk-FE6NOAO7.js → chunk-VNWQIGQL.js} +1820 -649
  202. package/dist/chunks/chunk-VNWQIGQL.js.map +7 -0
  203. package/dist/chunks/{chunk-PYFJW3HC.js → chunk-W5FEHVZA.js} +2 -16
  204. package/dist/chunks/{chunk-PYFJW3HC.js.map → chunk-W5FEHVZA.js.map} +3 -3
  205. package/dist/chunks/{chunk-XCEEQ5AB.js → chunk-WGMCNCP6.js} +1567 -1564
  206. package/dist/chunks/chunk-WGMCNCP6.js.map +7 -0
  207. package/dist/chunks/chunk-WKFRGICG.js +101 -0
  208. package/dist/chunks/chunk-WKFRGICG.js.map +7 -0
  209. package/dist/chunks/{chunk-3UGN25XS.js → chunk-WWTGWGH7.js} +80 -1662
  210. package/dist/chunks/chunk-WWTGWGH7.js.map +7 -0
  211. package/dist/chunks/{chunk-5UBRGTVN.js → chunk-X7QETPBC.js} +31 -15
  212. package/dist/chunks/chunk-X7QETPBC.js.map +7 -0
  213. package/dist/chunks/{chunk-LEU5CDSL.js → chunk-XFOSUGLU.js} +5 -5
  214. package/dist/chunks/{chunk-MZUC6LLH.js → chunk-XMYG2TKR.js} +4 -4
  215. package/dist/chunks/{chunk-MZUC6LLH.js.map → chunk-XMYG2TKR.js.map} +1 -1
  216. package/dist/chunks/chunk-YC65P7ZO.js +57 -0
  217. package/dist/chunks/chunk-YC65P7ZO.js.map +7 -0
  218. package/dist/chunks/{chunk-EKODKR6Y.js → chunk-YHFWMAQ5.js} +1 -24
  219. package/dist/chunks/chunk-YHFWMAQ5.js.map +7 -0
  220. package/dist/chunks/{chunk-C7Z6F3SO.js → chunk-ZFWICFNJ.js} +27 -20
  221. package/dist/chunks/{chunk-C7Z6F3SO.js.map → chunk-ZFWICFNJ.js.map} +2 -2
  222. package/dist/cli/decisions.d.ts.map +1 -1
  223. package/dist/cli/decisions.js +15 -3
  224. package/dist/cli/decisions.js.map +2 -2
  225. package/dist/cli/mesh.js +4 -3
  226. package/dist/cli/mesh.js.map +1 -1
  227. package/dist/commands/fabric-handler.d.ts +7 -0
  228. package/dist/commands/fabric-handler.d.ts.map +1 -0
  229. package/dist/commands/fabric-handler.js +916 -0
  230. package/dist/commands/fabric-handler.js.map +7 -0
  231. package/dist/commands/fabric.d.ts +11 -1
  232. package/dist/commands/fabric.d.ts.map +1 -1
  233. package/dist/compaction/claim-events.d.ts +61 -0
  234. package/dist/compaction/claim-events.d.ts.map +1 -0
  235. package/dist/compaction/claim-events.js +210 -0
  236. package/dist/compaction/claim-events.js.map +7 -0
  237. package/dist/compaction/claim.d.ts +51 -0
  238. package/dist/compaction/claim.d.ts.map +1 -0
  239. package/dist/compaction/hook.d.ts +28 -2
  240. package/dist/compaction/hook.d.ts.map +1 -1
  241. package/dist/compaction/hook.js +12 -7
  242. package/dist/compaction/owner.js +9 -8
  243. package/dist/compaction/trace-events.d.ts +1 -1
  244. package/dist/compaction/trace-events.d.ts.map +1 -1
  245. package/dist/components/configuration.js +6 -6
  246. package/dist/components/effect-scope.d.ts.map +1 -1
  247. package/dist/config.d.ts +39 -2
  248. package/dist/config.d.ts.map +1 -1
  249. package/dist/core/action-arguments.d.ts.map +1 -1
  250. package/dist/core/action-policy-hooks.d.ts +69 -0
  251. package/dist/core/action-policy-hooks.d.ts.map +1 -0
  252. package/dist/core/action-registry.d.ts +31 -10
  253. package/dist/core/action-registry.d.ts.map +1 -1
  254. package/dist/core/action-registry.js +12 -9
  255. package/dist/core/approval-controller.d.ts +23 -3
  256. package/dist/core/approval-controller.d.ts.map +1 -1
  257. package/dist/core/atomic-write.d.ts +164 -0
  258. package/dist/core/atomic-write.d.ts.map +1 -1
  259. package/dist/core/child-tool-allowlist.d.ts +17 -1
  260. package/dist/core/child-tool-allowlist.d.ts.map +1 -1
  261. package/dist/core/compact-controller.d.ts +34 -0
  262. package/dist/core/compact-controller.d.ts.map +1 -1
  263. package/dist/core/core-override-guidance.d.ts +3 -1
  264. package/dist/core/core-override-guidance.d.ts.map +1 -1
  265. package/dist/core/file-lock.d.ts.map +1 -1
  266. package/dist/core/foreground-tools.d.ts +4 -1
  267. package/dist/core/foreground-tools.d.ts.map +1 -1
  268. package/dist/core/host-policy.d.ts +43 -0
  269. package/dist/core/host-policy.d.ts.map +1 -0
  270. package/dist/core/host-sdk-runtime.d.ts.map +1 -1
  271. package/dist/core/host-sdk.d.ts.map +1 -1
  272. package/dist/core/host-sdk.js +1 -1
  273. package/dist/core/managed-host-guidance.d.ts +5 -0
  274. package/dist/core/managed-host-guidance.d.ts.map +1 -0
  275. package/dist/core/model-aliases.d.ts +22 -0
  276. package/dist/core/model-aliases.d.ts.map +1 -0
  277. package/dist/core/model-resolution.d.ts +41 -20
  278. package/dist/core/model-resolution.d.ts.map +1 -1
  279. package/dist/core/native-tool-result.d.ts +1 -0
  280. package/dist/core/native-tool-result.d.ts.map +1 -1
  281. package/dist/core/program-tasks.d.ts +52 -0
  282. package/dist/core/program-tasks.d.ts.map +1 -0
  283. package/dist/core/prompt-guidance.d.ts +5 -0
  284. package/dist/core/prompt-guidance.d.ts.map +1 -0
  285. package/dist/core/prompt-guidance.js +159 -0
  286. package/dist/core/prompt-guidance.js.map +7 -0
  287. package/dist/core/provider-operations.d.ts.map +1 -1
  288. package/dist/core/provider-operations.js +60 -108
  289. package/dist/core/provider-operations.js.map +3 -3
  290. package/dist/core/shell-inbox.d.ts.map +1 -1
  291. package/dist/core/shell-jobs.d.ts +7 -5
  292. package/dist/core/shell-jobs.d.ts.map +1 -1
  293. package/dist/core/shell-timing.d.ts.map +1 -1
  294. package/dist/core/skill-prompt.d.ts +1 -1
  295. package/dist/core/skill-prompt.d.ts.map +1 -1
  296. package/dist/core/skill-references.d.ts +1 -1
  297. package/dist/core/skill-references.d.ts.map +1 -1
  298. package/dist/core/system-guidance.d.ts.map +1 -1
  299. package/dist/core/tool-result-proxy.d.ts.map +1 -1
  300. package/dist/decisions/command.d.ts +2 -1
  301. package/dist/decisions/command.d.ts.map +1 -1
  302. package/dist/decisions/command.js +40 -12
  303. package/dist/decisions/command.js.map +2 -2
  304. package/dist/decisions/events.d.ts +12 -0
  305. package/dist/decisions/events.d.ts.map +1 -0
  306. package/dist/decisions/events.js +130 -0
  307. package/dist/decisions/events.js.map +7 -0
  308. package/dist/decisions/host.d.ts +31 -3
  309. package/dist/decisions/host.d.ts.map +1 -1
  310. package/dist/decisions/render.d.ts +44 -0
  311. package/dist/decisions/render.d.ts.map +1 -0
  312. package/dist/decisions/store.d.ts +8 -0
  313. package/dist/decisions/store.d.ts.map +1 -1
  314. package/dist/durable/agent.d.ts +8 -0
  315. package/dist/durable/agent.d.ts.map +1 -1
  316. package/dist/durable/extension-load-error.d.ts +8 -0
  317. package/dist/durable/extension-load-error.d.ts.map +1 -0
  318. package/dist/durable/session.d.ts +1 -0
  319. package/dist/durable/session.d.ts.map +1 -1
  320. package/dist/durable/worker-host.d.ts +10 -1
  321. package/dist/durable/worker-host.d.ts.map +1 -1
  322. package/dist/durable/worker-host.js +10 -1181
  323. package/dist/durable/worker-host.js.map +4 -4
  324. package/dist/durable/worker-options.d.ts +3 -0
  325. package/dist/durable/worker-options.d.ts.map +1 -1
  326. package/dist/durable/worker-role-seed.d.ts +82 -0
  327. package/dist/durable/worker-role-seed.d.ts.map +1 -0
  328. package/dist/durable/worker.js +43 -4
  329. package/dist/durable/worker.js.map +2 -2
  330. package/dist/durable-controls.d.ts.map +1 -1
  331. package/dist/durable-extension-wasm.d.ts +8 -0
  332. package/dist/durable-extension-wasm.d.ts.map +1 -0
  333. package/dist/durable-extension-wasm.js +32 -0
  334. package/dist/durable-extension-wasm.js.map +7 -0
  335. package/dist/durable-extension.d.ts +94 -0
  336. package/dist/durable-extension.d.ts.map +1 -0
  337. package/dist/durable-extension.js +649 -0
  338. package/dist/durable-extension.js.map +7 -0
  339. package/dist/durable-host.d.ts +8 -0
  340. package/dist/durable-host.d.ts.map +1 -0
  341. package/dist/durable-host.js +20 -0
  342. package/dist/durable-host.js.map +7 -0
  343. package/dist/durable-journal.d.ts +94 -0
  344. package/dist/durable-journal.d.ts.map +1 -0
  345. package/dist/durable.d.ts.map +1 -1
  346. package/dist/durable.js +10 -8
  347. package/dist/durable.js.map +2 -2
  348. package/dist/entropy/index.js +12 -10
  349. package/dist/entropy/pool-store.d.ts.map +1 -1
  350. package/dist/execution-service.d.ts +14 -0
  351. package/dist/execution-service.d.ts.map +1 -1
  352. package/dist/extension-bootstrap.d.ts.map +1 -1
  353. package/dist/extension-bootstrap.js +28 -27
  354. package/dist/extension-bootstrap.js.map +2 -2
  355. package/dist/extension-copy.d.ts +21 -0
  356. package/dist/extension-copy.d.ts.map +1 -0
  357. package/dist/extension-copy.js +90 -0
  358. package/dist/extension-copy.js.map +7 -0
  359. package/dist/extension.d.ts +1 -1
  360. package/dist/extension.d.ts.map +1 -1
  361. package/dist/fabric-exec-arguments.d.ts.map +1 -1
  362. package/dist/fabric-exec-tool.d.ts +2 -1
  363. package/dist/fabric-exec-tool.d.ts.map +1 -1
  364. package/dist/fabric-runtime-state.d.ts +19 -0
  365. package/dist/fabric-runtime-state.d.ts.map +1 -1
  366. package/dist/fabric-runtime-state.js +2125 -786
  367. package/dist/fabric-runtime-state.js.map +4 -4
  368. package/dist/fabric-state.d.ts +44 -1
  369. package/dist/fabric-state.d.ts.map +1 -1
  370. package/dist/index.d.ts +5 -3
  371. package/dist/index.d.ts.map +1 -1
  372. package/dist/index.js +88 -53
  373. package/dist/index.js.map +2 -2
  374. package/dist/jev/client.js +2 -2
  375. package/dist/jev/manager.d.ts +3 -0
  376. package/dist/jev/manager.d.ts.map +1 -1
  377. package/dist/jev/observation.d.ts +1 -1
  378. package/dist/jev/observation.js +6 -6
  379. package/dist/jev-fabric/bridge.d.ts.map +1 -1
  380. package/dist/jev.js +11 -12
  381. package/dist/managed-host.d.ts +13 -0
  382. package/dist/managed-host.d.ts.map +1 -1
  383. package/dist/memory/digest.js +2 -2
  384. package/dist/memory/discovery.js +6 -7
  385. package/dist/memory/file-worker.js +10 -11
  386. package/dist/memory/file-worker.js.map +1 -1
  387. package/dist/memory/normalize.js +5 -6
  388. package/dist/memory/search.js +7 -8
  389. package/dist/memory/worker-provider.js +11 -12
  390. package/dist/memory.js +11 -12
  391. package/dist/memory.js.map +1 -1
  392. package/dist/mesh/grants.d.ts +3 -3
  393. package/dist/mesh/grants.d.ts.map +1 -1
  394. package/dist/mesh/store.d.ts +8 -0
  395. package/dist/mesh/store.d.ts.map +1 -1
  396. package/dist/native-codemode.d.ts.map +1 -1
  397. package/dist/native-tool-catalog.d.ts.map +1 -1
  398. package/dist/native-tool-catalog.js +12 -3
  399. package/dist/native-tool-catalog.js.map +2 -2
  400. package/dist/programs/host.d.ts +18 -6
  401. package/dist/programs/host.d.ts.map +1 -1
  402. package/dist/programs/host.js +71 -47
  403. package/dist/programs/host.js.map +2 -2
  404. package/dist/programs/source.d.ts +11 -0
  405. package/dist/programs/source.d.ts.map +1 -1
  406. package/dist/programs/store.d.ts.map +1 -1
  407. package/dist/protocol.d.ts +504 -8
  408. package/dist/protocol.d.ts.map +1 -1
  409. package/dist/protocol.js +41 -11
  410. package/dist/provider-globals.d.ts +13 -0
  411. package/dist/provider-globals.d.ts.map +1 -0
  412. package/dist/providers/agents-actions.d.ts.map +1 -1
  413. package/dist/providers/agents-provider.d.ts +3 -0
  414. package/dist/providers/agents-provider.d.ts.map +1 -1
  415. package/dist/providers/captured-tools-provider.d.ts +5 -0
  416. package/dist/providers/captured-tools-provider.d.ts.map +1 -1
  417. package/dist/providers/compact-provider.d.ts +4 -1
  418. package/dist/providers/compact-provider.d.ts.map +1 -1
  419. package/dist/providers/components-provider.d.ts.map +1 -1
  420. package/dist/providers/decisions-provider.d.ts +9 -1
  421. package/dist/providers/decisions-provider.d.ts.map +1 -1
  422. package/dist/providers/jev-provider.d.ts +1 -1
  423. package/dist/providers/jev-provider.js +11 -12
  424. package/dist/providers/memory-provider.js +10 -11
  425. package/dist/providers/pi-tools-provider.d.ts +14 -0
  426. package/dist/providers/pi-tools-provider.d.ts.map +1 -1
  427. package/dist/providers/programs-provider.d.ts.map +1 -1
  428. package/dist/providers/sessions-provider.d.ts +7 -0
  429. package/dist/providers/sessions-provider.d.ts.map +1 -1
  430. package/dist/repeat-guard.d.ts +7 -6
  431. package/dist/repeat-guard.d.ts.map +1 -1
  432. package/dist/residency/actor-client.js +3 -3
  433. package/dist/residency/client.d.ts +15 -0
  434. package/dist/residency/client.d.ts.map +1 -1
  435. package/dist/residency/host.d.ts.map +1 -1
  436. package/dist/residency/host.js +34 -23
  437. package/dist/residency/launcher.js +1 -1
  438. package/dist/residency/pi-entry.js +34 -23
  439. package/dist/residency/pi-entry.js.map +1 -1
  440. package/dist/residency/protocol.d.ts +2 -0
  441. package/dist/residency/protocol.d.ts.map +1 -1
  442. package/dist/runners.js +11 -1
  443. package/dist/runners.js.map +2 -2
  444. package/dist/runtime/core-override-guest-types.js +2 -2
  445. package/dist/runtime/cpython-child-source.d.ts.map +1 -1
  446. package/dist/runtime/cpython-runtime.d.ts.map +1 -1
  447. package/dist/runtime/cpython-runtime.js +51 -21
  448. package/dist/runtime/cpython-runtime.js.map +2 -2
  449. package/dist/runtime/deadline-pause.d.ts +2 -0
  450. package/dist/runtime/deadline-pause.d.ts.map +1 -1
  451. package/dist/runtime/dynamic-guest-types.d.ts.map +1 -1
  452. package/dist/runtime/dynamic-guest-types.js +2 -1
  453. package/dist/runtime/exec-journal.d.ts +73 -0
  454. package/dist/runtime/exec-journal.d.ts.map +1 -0
  455. package/dist/runtime/exec-journal.js +335 -0
  456. package/dist/runtime/exec-journal.js.map +7 -0
  457. package/dist/runtime/guest-types.d.ts +3 -2
  458. package/dist/runtime/guest-types.d.ts.map +1 -1
  459. package/dist/runtime/guest-types.js +1 -1
  460. package/dist/runtime/journal-shim.d.ts +3 -0
  461. package/dist/runtime/journal-shim.d.ts.map +1 -0
  462. package/dist/runtime/kernel.d.ts +95 -1
  463. package/dist/runtime/kernel.d.ts.map +1 -1
  464. package/dist/runtime/monty-bridge.d.ts +6 -2
  465. package/dist/runtime/monty-bridge.d.ts.map +1 -1
  466. package/dist/runtime/monty-runtime.d.ts.map +1 -1
  467. package/dist/runtime/monty-runtime.js +27 -15
  468. package/dist/runtime/monty-runtime.js.map +2 -2
  469. package/dist/runtime/native-codemode-guest.d.ts.map +1 -1
  470. package/dist/runtime/node-process-runtime.d.ts.map +1 -1
  471. package/dist/runtime/node-process-runtime.js +7 -5
  472. package/dist/runtime/quickjs-runtime.d.ts +7 -1
  473. package/dist/runtime/quickjs-runtime.d.ts.map +1 -1
  474. package/dist/runtime/quickjs-runtime.js +5 -4
  475. package/dist/runtime/sha256.d.ts +4 -0
  476. package/dist/runtime/sha256.d.ts.map +1 -0
  477. package/dist/runtime/transpile.d.ts +8 -0
  478. package/dist/runtime/transpile.d.ts.map +1 -0
  479. package/dist/runtime/type-checker.d.ts +1 -7
  480. package/dist/runtime/type-checker.d.ts.map +1 -1
  481. package/dist/runtime/type-checker.js +4 -2
  482. package/dist/runtime/typescript-kernel.js +13 -10
  483. package/dist/runtime/typescript-kernel.js.map +1 -1
  484. package/dist/runtime-state-builtins.d.ts.map +1 -1
  485. package/dist/speculation/scanner.js +1 -1
  486. package/dist/speculation/store.d.ts +7 -16
  487. package/dist/speculation/store.d.ts.map +1 -1
  488. package/dist/speculation/types.d.ts +1 -0
  489. package/dist/speculation/types.d.ts.map +1 -1
  490. package/dist/storage/retention.d.ts.map +1 -1
  491. package/dist/topology/participant-directory.d.ts +26 -1
  492. package/dist/topology/participant-directory.d.ts.map +1 -1
  493. package/dist/topology/peer-presence.d.ts.map +1 -1
  494. package/dist/topology/peer-settle.js +11 -0
  495. package/dist/topology/peer-settle.js.map +7 -0
  496. package/dist/topology/session-label-settings.d.ts +13 -0
  497. package/dist/topology/session-label-settings.d.ts.map +1 -0
  498. package/dist/topology/session-label.d.ts +60 -0
  499. package/dist/topology/session-label.d.ts.map +1 -0
  500. package/dist/topology/types.d.ts +27 -0
  501. package/dist/topology/types.d.ts.map +1 -1
  502. package/dist/type-error-guidance.js +1 -1
  503. package/dist/ui/controller.d.ts +1 -0
  504. package/dist/ui/controller.d.ts.map +1 -1
  505. package/dist/ui/conversation-chrome.d.ts.map +1 -1
  506. package/dist/ui/conversation-chrome.js +3 -2
  507. package/dist/ui/conversation-commands.d.ts +1 -1
  508. package/dist/ui/conversation-commands.d.ts.map +1 -1
  509. package/dist/ui/conversation-native-reader.js +2 -2
  510. package/dist/ui/conversation-selection.d.ts +4 -1
  511. package/dist/ui/conversation-selection.d.ts.map +1 -1
  512. package/dist/ui/conversation-targets.d.ts.map +1 -1
  513. package/dist/ui/conversation-targets.js +2 -2
  514. package/dist/ui/conversation.d.ts +25 -24
  515. package/dist/ui/conversation.d.ts.map +1 -1
  516. package/dist/ui/conversation.js +170 -339
  517. package/dist/ui/conversation.js.map +2 -2
  518. package/dist/ui/core-tool-render.d.ts +1 -0
  519. package/dist/ui/core-tool-render.d.ts.map +1 -1
  520. package/dist/ui/dashboard.d.ts.map +1 -1
  521. package/dist/ui/dashboard.js +17 -13
  522. package/dist/ui/dashboard.js.map +2 -2
  523. package/dist/ui/fabric-render.d.ts +6 -0
  524. package/dist/ui/fabric-render.d.ts.map +1 -1
  525. package/dist/ui/footer-dock.d.ts +48 -0
  526. package/dist/ui/footer-dock.d.ts.map +1 -0
  527. package/dist/ui/format.d.ts +7 -0
  528. package/dist/ui/format.d.ts.map +1 -1
  529. package/dist/ui/settings-sections-lifecycle.d.ts.map +1 -1
  530. package/dist/ui/settings-sections-presentation.d.ts.map +1 -1
  531. package/dist/ui/settings-values.d.ts +1 -0
  532. package/dist/ui/settings-values.d.ts.map +1 -1
  533. package/dist/ui/settings.js +59 -18
  534. package/dist/ui/settings.js.map +2 -2
  535. package/dist/ui/shell-hang-keys.d.ts +8 -1
  536. package/dist/ui/shell-hang-keys.d.ts.map +1 -1
  537. package/dist/ui/shell-tasks.d.ts +2 -2
  538. package/dist/ui/shell-tasks.d.ts.map +1 -1
  539. package/dist/ui/shell-tasks.js +27 -94
  540. package/dist/ui/shell-tasks.js.map +2 -2
  541. package/dist/ui/snapshot.d.ts.map +1 -1
  542. package/dist/ui/terminal-title.d.ts +41 -0
  543. package/dist/ui/terminal-title.d.ts.map +1 -0
  544. package/dist/ui/types.d.ts +4 -0
  545. package/dist/ui/types.d.ts.map +1 -1
  546. package/dist/ui/widget-keys.d.ts +5 -0
  547. package/dist/ui/widget-keys.d.ts.map +1 -0
  548. package/dist/ui/widget.d.ts +34 -16
  549. package/dist/ui/widget.d.ts.map +1 -1
  550. package/dist/ui/word-diff/line-emphasis.js +1603 -0
  551. package/dist/ui/word-diff/line-emphasis.js.map +7 -0
  552. package/dist/util.d.ts +2 -0
  553. package/dist/util.d.ts.map +1 -1
  554. package/dist/verified/authority.d.ts +2 -2
  555. package/dist/verified/authority.d.ts.map +1 -1
  556. package/dist/verified/budget.d.ts +4 -0
  557. package/dist/verified/budget.d.ts.map +1 -0
  558. package/dist/verified/generated/actor-name.d.ts +4 -0
  559. package/dist/verified/generated/actor-name.js +17 -0
  560. package/dist/verified/generated/authority.d.ts +4 -0
  561. package/dist/verified/generated/authority.js +28 -0
  562. package/dist/verified/generated/budget.d.ts +4 -0
  563. package/dist/verified/generated/budget.js +17 -0
  564. package/dist/verified/generated/compaction.d.ts +4 -0
  565. package/dist/verified/generated/compaction.js +19 -0
  566. package/dist/verified/generated/grants.d.ts +4 -0
  567. package/dist/verified/generated/grants.js +17 -0
  568. package/dist/verified/generated/lifecycle.d.ts +4 -0
  569. package/dist/verified/generated/lifecycle.js +50 -0
  570. package/dist/verified/generated/manifest.json +137 -48
  571. package/dist/verified/generated/policy.d.ts +17 -0
  572. package/dist/verified/generated/policy.js +211 -0
  573. package/dist/verified/generated/provider.d.ts +4 -0
  574. package/dist/verified/generated/provider.js +18 -0
  575. package/dist/verified/generated/resources.d.ts +6 -0
  576. package/dist/verified/generated/resources.js +73 -0
  577. package/dist/verified/generated/speculation.d.ts +6 -0
  578. package/dist/verified/generated/speculation.js +48 -0
  579. package/dist/verified/generated/storage.d.ts +4 -0
  580. package/dist/verified/generated/storage.js +18 -0
  581. package/dist/verified/grants.d.ts +22 -0
  582. package/dist/verified/grants.d.ts.map +1 -0
  583. package/dist/verified/lifecycle.d.ts +31 -0
  584. package/dist/verified/lifecycle.d.ts.map +1 -0
  585. package/dist/verified/machine.d.ts +18 -0
  586. package/dist/verified/machine.d.ts.map +1 -0
  587. package/dist/verified/memory.d.ts +1 -1
  588. package/dist/verified/memory.d.ts.map +1 -1
  589. package/dist/verified/nat.d.ts +1 -1
  590. package/dist/verified/nat.d.ts.map +1 -1
  591. package/dist/verified/policy.d.ts +17 -5
  592. package/dist/verified/policy.d.ts.map +1 -1
  593. package/dist/verified/provider.d.ts +22 -0
  594. package/dist/verified/provider.d.ts.map +1 -0
  595. package/dist/verified/resources.d.ts +21 -7
  596. package/dist/verified/resources.d.ts.map +1 -1
  597. package/dist/verified/speculation.d.ts +36 -0
  598. package/dist/verified/speculation.d.ts.map +1 -0
  599. package/dist/verified/storage.d.ts.map +1 -1
  600. package/dist/worker/missing-install.d.ts +8 -0
  601. package/dist/worker/missing-install.d.ts.map +1 -0
  602. package/dist/worker/options.d.ts.map +1 -1
  603. package/dist/worker/options.js +25 -0
  604. package/dist/worker/options.js.map +2 -2
  605. package/dist/worker/prompt-lifecycle.d.ts +16 -0
  606. package/dist/worker/prompt-lifecycle.d.ts.map +1 -0
  607. package/dist/worker/prompt-lifecycle.js +90 -0
  608. package/dist/worker/prompt-lifecycle.js.map +7 -0
  609. package/dist/worker/questions.d.ts +15 -3
  610. package/dist/worker/questions.d.ts.map +1 -1
  611. package/dist/worker/questions.js +53 -8
  612. package/dist/worker/questions.js.map +2 -2
  613. package/dist/worker/recovery-watchdog.d.ts +22 -0
  614. package/dist/worker/recovery-watchdog.d.ts.map +1 -1
  615. package/dist/worker/recovery-watchdog.js +116 -1
  616. package/dist/worker/recovery-watchdog.js.map +2 -2
  617. package/dist/worker/result.js +1 -1
  618. package/dist/worker/result.js.map +2 -2
  619. package/dist/worker.js +131 -21
  620. package/dist/worker.js.map +2 -2
  621. package/docs/actor-name-policy-handoff.md +5 -0
  622. package/docs/agents.md +164 -17
  623. package/docs/architecture.md +5 -1
  624. package/docs/audit-trace.md +2 -1
  625. package/docs/background-tasks.md +102 -16
  626. package/docs/codemode-parity.md +2 -2
  627. package/docs/compaction.md +21 -5
  628. package/docs/components.md +1 -1
  629. package/docs/configuration.md +111 -66
  630. package/docs/decisions.md +92 -10
  631. package/docs/durable-extension.md +121 -0
  632. package/docs/durable-pi.md +306 -6
  633. package/docs/extractive-history.md +3 -1
  634. package/docs/interface.md +20 -17
  635. package/docs/jev.md +1 -1
  636. package/docs/kernels.md +1 -1
  637. package/{node_modules/pi-coralbricks-provider/LICENSE → docs/licenses/gdp-wired-mit.txt} +1 -1
  638. package/docs/managed-host-migration.md +50 -0
  639. package/docs/programmatic-compaction.md +216 -6
  640. package/docs/programs.md +23 -1
  641. package/docs/prompt-cache.md +4 -2
  642. package/docs/provider-capabilities.md +15 -14
  643. package/docs/providers.md +99 -3
  644. package/docs/shell-composition.md +15 -0
  645. package/docs/short-lock-protocol.md +90 -0
  646. package/docs/skills.md +5 -1
  647. package/docs/speculation.md +6 -0
  648. package/docs/verified-kernels.md +309 -220
  649. package/package.json +45 -24
  650. package/proofs/actor-name.ts +27 -0
  651. package/proofs/authority.ts +62 -0
  652. package/proofs/budget.ts +24 -0
  653. package/proofs/compaction.ts +51 -0
  654. package/proofs/grants.ts +39 -0
  655. package/proofs/index.ts +40 -0
  656. package/proofs/kernel.ts +44 -0
  657. package/proofs/lifecycle.ts +128 -0
  658. package/proofs/policy.ts +195 -0
  659. package/proofs/provider.ts +52 -0
  660. package/proofs/resources.ts +160 -0
  661. package/proofs/speculation.ts +69 -0
  662. package/proofs/storage.ts +66 -0
  663. package/scripts/verified-kernels.ts +141 -0
  664. package/skillsets/python/fabric-council/SKILL.md +92 -20
  665. package/skillsets/python/fabric-exec/SKILL.md +2 -2
  666. package/skillsets/python/fabric-exec/references/agents.md +10 -4
  667. package/skillsets/python/fabric-fusion/SKILL.md +1 -1
  668. package/skillsets/python/fabric-guide/SKILL.md +1 -1
  669. package/skillsets/typescript/fabric-council/SKILL.md +109 -22
  670. package/skillsets/typescript/fabric-exec/SKILL.md +7 -7
  671. package/skillsets/typescript/fabric-exec/references/agents.md +12 -3
  672. package/skillsets/typescript/fabric-fusion/SKILL.md +1 -1
  673. package/skillsets/typescript/fabric-guide/SKILL.md +1 -1
  674. package/LAWS.bend +0 -502
  675. package/PROOF.bend +0 -452
  676. package/dist/chunks/chunk-3UGN25XS.js.map +0 -7
  677. package/dist/chunks/chunk-4EW7GVUR.js.map +0 -7
  678. package/dist/chunks/chunk-5UBRGTVN.js.map +0 -7
  679. package/dist/chunks/chunk-BN7F52EG.js +0 -525
  680. package/dist/chunks/chunk-BN7F52EG.js.map +0 -7
  681. package/dist/chunks/chunk-DK35W6U7.js +0 -259
  682. package/dist/chunks/chunk-DK35W6U7.js.map +0 -7
  683. package/dist/chunks/chunk-EFETPXU2.js.map +0 -7
  684. package/dist/chunks/chunk-EHQQ4KCX.js.map +0 -7
  685. package/dist/chunks/chunk-EKODKR6Y.js.map +0 -7
  686. package/dist/chunks/chunk-FE6NOAO7.js.map +0 -7
  687. package/dist/chunks/chunk-FIDUHKMM.js.map +0 -7
  688. package/dist/chunks/chunk-FSB2VIRZ.js.map +0 -7
  689. package/dist/chunks/chunk-GIK2WNAK.js.map +0 -7
  690. package/dist/chunks/chunk-GO32KSEZ.js.map +0 -7
  691. package/dist/chunks/chunk-IR3PIHJM.js.map +0 -7
  692. package/dist/chunks/chunk-ITVLKXCI.js +0 -266
  693. package/dist/chunks/chunk-ITVLKXCI.js.map +0 -7
  694. package/dist/chunks/chunk-K7J2ABAZ.js.map +0 -7
  695. package/dist/chunks/chunk-KJZAOENY.js +0 -212
  696. package/dist/chunks/chunk-KJZAOENY.js.map +0 -7
  697. package/dist/chunks/chunk-LNASO4VT.js.map +0 -7
  698. package/dist/chunks/chunk-MLLYR3Y6.js.map +0 -7
  699. package/dist/chunks/chunk-P4KH4S4S.js.map +0 -7
  700. package/dist/chunks/chunk-PK4NIJEV.js.map +0 -7
  701. package/dist/chunks/chunk-Q2JQ3RYZ.js +0 -99
  702. package/dist/chunks/chunk-Q2JQ3RYZ.js.map +0 -7
  703. package/dist/chunks/chunk-R2XQ6AHT.js.map +0 -7
  704. package/dist/chunks/chunk-ROTCDDOV.js.map +0 -7
  705. package/dist/chunks/chunk-SPCJXN4K.js.map +0 -7
  706. package/dist/chunks/chunk-U366I5K2.js.map +0 -7
  707. package/dist/chunks/chunk-UKMQK5VP.js +0 -231
  708. package/dist/chunks/chunk-UKMQK5VP.js.map +0 -7
  709. package/dist/chunks/chunk-UOM37PE4.js.map +0 -7
  710. package/dist/chunks/chunk-UTOBAZ5T.js.map +0 -7
  711. package/dist/chunks/chunk-VSDUSNIA.js.map +0 -7
  712. package/dist/chunks/chunk-VTK2FEH7.js +0 -229
  713. package/dist/chunks/chunk-VTK2FEH7.js.map +0 -7
  714. package/dist/chunks/chunk-VYQV5JRT.js.map +0 -7
  715. package/dist/chunks/chunk-XCEEQ5AB.js.map +0 -7
  716. package/dist/chunks/chunk-ZLNJDTCN.js +0 -226
  717. package/dist/chunks/chunk-ZLNJDTCN.js.map +0 -7
  718. package/dist/chunks/chunk-ZQMBS5SH.js.map +0 -7
  719. package/dist/ui/conversation-shortcut.d.ts +0 -3
  720. package/dist/ui/conversation-shortcut.d.ts.map +0 -1
  721. package/dist/ui/widget-activity.d.ts +0 -21
  722. package/dist/ui/widget-activity.d.ts.map +0 -1
  723. package/dist/verified/generated/authority-kernel.d.ts +0 -10
  724. package/dist/verified/generated/authority-kernel.js +0 -127
  725. package/dist/verified/generated/kernel.d.ts +0 -31
  726. package/dist/verified/generated/kernel.js +0 -389
  727. package/dist/verified/generated/lifecycle-kernel.d.ts +0 -7
  728. package/dist/verified/generated/lifecycle-kernel.js +0 -164
  729. package/dist/verified/generated/provider-kernel.d.ts +0 -9
  730. package/dist/verified/generated/provider-kernel.js +0 -87
  731. package/dist/verified/generated/storage-kernel.d.ts +0 -11
  732. package/dist/verified/generated/storage-kernel.js +0 -107
  733. package/docs/licenses/bend-apache-2.0.txt +0 -202
  734. package/node_modules/pi-coralbricks-provider/README.md +0 -306
  735. package/node_modules/pi-coralbricks-provider/auth.ts +0 -30
  736. package/node_modules/pi-coralbricks-provider/custom-models.json +0 -1
  737. package/node_modules/pi-coralbricks-provider/deprecated-models.json +0 -1
  738. package/node_modules/pi-coralbricks-provider/guard.ts +0 -155
  739. package/node_modules/pi-coralbricks-provider/index.ts +0 -662
  740. package/node_modules/pi-coralbricks-provider/models.json +0 -88
  741. package/node_modules/pi-coralbricks-provider/package.json +0 -74
  742. package/node_modules/pi-coralbricks-provider/park.ts +0 -122
  743. package/node_modules/pi-coralbricks-provider/patch.json +0 -34
  744. package/node_modules/pi-coralbricks-provider/scripts/update-models.js +0 -658
  745. package/node_modules/pi-coralbricks-provider/settings.ts +0 -143
  746. package/node_modules/pi-coralbricks-provider/sync-policy.ts +0 -309
  747. package/proofs/abi.json +0 -308
  748. package/proofs/authority-abi.json +0 -7
  749. package/proofs/authority-kernel.bend +0 -23
  750. package/proofs/authority-proof.bend +0 -74
  751. package/proofs/authority-spec.bend +0 -30
  752. package/proofs/authority-state.bend +0 -43
  753. package/proofs/authority-types.d.ts +0 -3
  754. package/proofs/kernel.bend +0 -139
  755. package/proofs/lifecycle-abi.json +0 -3
  756. package/proofs/lifecycle-kernel.bend +0 -11
  757. package/proofs/lifecycle-proof.bend +0 -249
  758. package/proofs/lifecycle-spec.bend +0 -261
  759. package/proofs/lifecycle-types.d.ts +0 -4
  760. package/proofs/lifecycle.bend +0 -119
  761. package/proofs/provider-abi.json +0 -4
  762. package/proofs/provider-kernel.bend +0 -14
  763. package/proofs/provider-plans.bend +0 -28
  764. package/proofs/provider-spec.bend +0 -14
  765. package/proofs/provider-types.d.ts +0 -5
  766. package/proofs/resource-proof.bend +0 -633
  767. package/proofs/resource-spec.bend +0 -133
  768. package/proofs/resources.bend +0 -160
  769. package/proofs/state-kernel.bend +0 -17
  770. package/proofs/state-plans.bend +0 -40
  771. package/proofs/state-proof.bend +0 -42
  772. package/proofs/state-spec.bend +0 -26
  773. package/proofs/storage-abi.json +0 -3
  774. package/proofs/storage-kernel.bend +0 -11
  775. package/proofs/storage-plans.bend +0 -100
  776. package/proofs/storage-proof.bend +0 -176
  777. package/proofs/storage-spec.bend +0 -70
  778. package/proofs/storage-types.d.ts +0 -8
  779. package/proofs/types.d.ts +0 -7
  780. package/scripts/test-verified-kernels.mjs +0 -107
  781. package/scripts/verified-kernels.mjs +0 -176
  782. /package/dist/chunks/{chunk-3FJUP3GV.js.map → chunk-36XQFTEN.js.map} +0 -0
  783. /package/dist/chunks/{chunk-ZEXCKK4K.js.map → chunk-4WKD3YM3.js.map} +0 -0
  784. /package/dist/chunks/{chunk-5XBYFSI5.js.map → chunk-7YNE4NB2.js.map} +0 -0
  785. /package/dist/chunks/{chunk-K6QXUGS5.js.map → chunk-BMAEZNZ5.js.map} +0 -0
  786. /package/dist/chunks/{chunk-CCHZXF6K.js.map → chunk-CXYJJ3HZ.js.map} +0 -0
  787. /package/dist/chunks/{chunk-TIIIHPHF.js.map → chunk-GS67KDMV.js.map} +0 -0
  788. /package/dist/chunks/{chunk-D5NYNIST.js.map → chunk-H57KPL3V.js.map} +0 -0
  789. /package/dist/chunks/{chunk-INRXG4J5.js.map → chunk-HGD75NZY.js.map} +0 -0
  790. /package/dist/chunks/{chunk-UXIBKMUM.js.map → chunk-KIFOEBYJ.js.map} +0 -0
  791. /package/dist/chunks/{chunk-FUY6XVRX.js.map → chunk-MPMEK3IQ.js.map} +0 -0
  792. /package/dist/chunks/{chunk-HP5P7NBO.js.map → chunk-MSDL7U6Q.js.map} +0 -0
  793. /package/dist/chunks/{chunk-QT4W5YVB.js.map → chunk-RAA3FAYZ.js.map} +0 -0
  794. /package/dist/chunks/{chunk-53N2I4QA.js.map → chunk-TXCNZCZP.js.map} +0 -0
  795. /package/dist/chunks/{chunk-ASSLHWZS.js.map → chunk-UFMYN5TA.js.map} +0 -0
  796. /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-4KX6BIPL.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 randomUUID4 } from "node:crypto";
308
+ import fs12 from "node:fs";
288
309
  import os3 from "node:os";
289
- import path12 from "node:path";
310
+ import path13 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();
612
662
  }
613
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;
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();
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,184 @@ 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
+ });
709
973
 
710
974
  // src/agents/constants.ts
711
975
  var AGENT_STATUS_POLL_INTERVAL_MS = 250;
@@ -716,14 +980,6 @@ var AGENT_RESUME_MAX_ATTEMPTS = 3;
716
980
  var AGENT_RESUME_RETRY_BASE_DELAY_MS = 1e3;
717
981
 
718
982
  // 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"}`);
726
- };
727
983
  var HerdrTransport = class {
728
984
  constructor(environment = process.env) {
729
985
  this.environment = environment;
@@ -792,54 +1048,7 @@ var HerdrTransport = class {
792
1048
  };
793
1049
  }
794
1050
  #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
- });
1051
+ return herdrSocketRequest(this.environment.HERDR_SOCKET_PATH, request, "Herdr transport");
843
1052
  }
844
1053
  };
845
1054
 
@@ -992,16 +1201,16 @@ var TmuxTransport = class {
992
1201
  };
993
1202
 
994
1203
  // src/agents/worktree-manager.ts
995
- import fs7 from "node:fs";
996
- import path7 from "node:path";
1204
+ import fs8 from "node:fs";
1205
+ import path8 from "node:path";
997
1206
 
998
1207
  // src/agents/clone-first-worktree.ts
999
- import fs6 from "node:fs";
1000
- import path6 from "node:path";
1208
+ import fs7 from "node:fs";
1209
+ import path7 from "node:path";
1001
1210
 
1002
1211
  // src/agents/cow-clone.ts
1003
- import fs4 from "node:fs";
1004
- import path4 from "node:path";
1212
+ import fs5 from "node:fs";
1213
+ import path5 from "node:path";
1005
1214
  var CLONE_SKIP_PREFIXES = [".git", ".pi/fabric/worktrees"];
1006
1215
  var CowUnavailableError = class extends Error {
1007
1216
  constructor(message2, options) {
@@ -1013,15 +1222,15 @@ var posixRel = (value) => value.replaceAll("\\", "/");
1013
1222
  var isCowUnavailable = (error) => {
1014
1223
  if (typeof error !== "object" || error === null || !("code" in error)) return false;
1015
1224
  const code = error.code;
1016
- return code === "ENOTSUP" || code === "EOPNOTSUPP" || code === "EXDEV" || code === "ENOTSUPP";
1225
+ return code === "ENOTSUP" || code === "EOPNOTSUPP" || code === "EXDEV" || code === "ENOTSUPP" || code === "ENOSYS" || code === "ENOTTY";
1017
1226
  };
1018
1227
  var cloneEntry = async (from, to) => {
1019
1228
  try {
1020
- await fs4.promises.cp(from, to, {
1229
+ await fs5.promises.cp(from, to, {
1021
1230
  recursive: true,
1022
1231
  verbatimSymlinks: true,
1023
1232
  force: false,
1024
- mode: fs4.constants.COPYFILE_FICLONE_FORCE
1233
+ mode: fs5.constants.COPYFILE_FICLONE_FORCE
1025
1234
  });
1026
1235
  } catch (error) {
1027
1236
  if (isCowUnavailable(error)) {
@@ -1041,13 +1250,13 @@ var hasNestedSkip = (rel, prefixes) => {
1041
1250
  return prefixes.some((prefix) => prefix.startsWith(`${value}/`));
1042
1251
  };
1043
1252
  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 });
1253
+ await fs5.promises.mkdir(dest, { recursive: true });
1254
+ const entries = await fs5.promises.readdir(source, { withFileTypes: true });
1046
1255
  for (const entry of entries) {
1047
1256
  const rel = relBase ? `${relBase}/${entry.name}` : entry.name;
1048
1257
  if (skipped(rel, prefixes)) continue;
1049
- const from = path4.join(source, entry.name);
1050
- const to = path4.join(dest, entry.name);
1258
+ const from = path5.join(source, entry.name);
1259
+ const to = path5.join(dest, entry.name);
1051
1260
  if (entry.isDirectory() && !entry.isSymbolicLink() && hasNestedSkip(rel, prefixes)) {
1052
1261
  await cloneLevel(from, to, rel, prefixes);
1053
1262
  continue;
@@ -1057,15 +1266,20 @@ var cloneLevel = async (source, dest, relBase, prefixes) => {
1057
1266
  }
1058
1267
  };
1059
1268
  var cloneTree = async (source, dest, prefixes = CLONE_SKIP_PREFIXES) => {
1060
- await cloneLevel(source, dest, "", prefixes);
1269
+ await fs5.promises.mkdir(dest, { recursive: true });
1270
+ const [realSource, realDest] = await Promise.all([fs5.promises.realpath(source), fs5.promises.realpath(dest)]);
1271
+ const relativeDest = path5.relative(realSource, realDest);
1272
+ if (!relativeDest) throw new Error("Cannot clone a tree into itself");
1273
+ const inside = relativeDest !== ".." && !relativeDest.startsWith(`..${path5.sep}`) && !path5.isAbsolute(relativeDest);
1274
+ await cloneLevel(realSource, realDest, "", inside ? [...prefixes, posixRel(relativeDest)] : prefixes);
1061
1275
  };
1062
1276
 
1063
1277
  // src/agents/worktree-paths.ts
1064
- import fs5 from "node:fs";
1065
- import path5 from "node:path";
1278
+ import fs6 from "node:fs";
1279
+ import path6 from "node:path";
1066
1280
  var FABRIC_WORKTREE_SEGMENTS = [".pi", "fabric", "worktrees"];
1067
1281
  var FABRIC_WORKTREE_EXCLUDE = ".pi/fabric/worktrees/";
1068
- var fabricWorktreePath = (gitRoot, id) => path5.join(gitRoot, ...FABRIC_WORKTREE_SEGMENTS, id);
1282
+ var fabricWorktreePath = (gitRoot, id) => path6.join(gitRoot, ...FABRIC_WORKTREE_SEGMENTS, id);
1069
1283
  var isFabricWorktreePath = (worktree, id) => {
1070
1284
  const parts = worktree.split(/[\\/]/).filter(Boolean);
1071
1285
  return parts.length >= 4 && parts.at(-1) === id && parts.at(-2) === "worktrees" && parts.at(-3) === "fabric" && parts.at(-4) === ".pi";
@@ -1075,11 +1289,11 @@ var ensureWorktreeExclude = async (gitRoot) => {
1075
1289
  cwd: gitRoot,
1076
1290
  timeoutMs: 1e4
1077
1291
  });
1078
- const excludePath = path5.resolve(gitRoot, located.stdout.trim());
1079
- fs5.mkdirSync(path5.dirname(excludePath), { recursive: true });
1292
+ const excludePath = path6.resolve(gitRoot, located.stdout.trim());
1293
+ fs6.mkdirSync(path6.dirname(excludePath), { recursive: true });
1080
1294
  let current = "";
1081
1295
  try {
1082
- current = fs5.readFileSync(excludePath, "utf8");
1296
+ current = fs6.readFileSync(excludePath, "utf8");
1083
1297
  } catch (error) {
1084
1298
  const code = error instanceof Error && "code" in error ? error.code : void 0;
1085
1299
  if (code !== "ENOENT") throw error;
@@ -1087,17 +1301,21 @@ var ensureWorktreeExclude = async (gitRoot) => {
1087
1301
  const lines = current.split(/\r?\n/);
1088
1302
  if (lines.some((line) => line.trim() === FABRIC_WORKTREE_EXCLUDE)) return;
1089
1303
  const prefix = current.length === 0 || current.endsWith("\n") ? "" : "\n";
1090
- fs5.appendFileSync(excludePath, `${prefix}${FABRIC_WORKTREE_EXCLUDE}
1304
+ fs6.appendFileSync(excludePath, `${prefix}${FABRIC_WORKTREE_EXCLUDE}
1091
1305
  `);
1092
1306
  };
1093
1307
 
1094
1308
  // src/agents/clone-first-worktree.ts
1309
+ var worktreeRollbackError = (gitRoot, worktree, branch, error, cleanupError) => {
1310
+ const detail = (value) => value instanceof Error ? `${value.message}${value.stderr ? `: ${value.stderr}` : ""}` : String(value);
1311
+ 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)}` : ""}.`);
1312
+ };
1095
1313
  var addCloneFirstWorktree = async (options) => {
1096
1314
  const dest = options.dest;
1097
- if (isFabricWorktreePath(dest, path6.basename(dest))) {
1315
+ if (isFabricWorktreePath(dest, path7.basename(dest))) {
1098
1316
  await ensureWorktreeExclude(options.gitRoot);
1099
1317
  }
1100
- fs6.mkdirSync(path6.dirname(dest), { recursive: true });
1318
+ fs7.mkdirSync(path7.dirname(dest), { recursive: true });
1101
1319
  const args = ["worktree", "add", "--no-checkout"];
1102
1320
  if (options.quiet) args.push("-q");
1103
1321
  if (options.detach) args.push("--detach");
@@ -1105,17 +1323,46 @@ var addCloneFirstWorktree = async (options) => {
1105
1323
  args.push(dest);
1106
1324
  if (options.startPoint) args.push(options.startPoint);
1107
1325
  const added = await executeFile("git", args, { cwd: options.gitRoot, timeoutMs: 6e4 });
1108
- let cloned = false;
1109
1326
  try {
1110
- await cloneTree(options.gitRoot, dest, CLONE_SKIP_PREFIXES);
1111
- cloned = true;
1327
+ let cloned = false;
1328
+ try {
1329
+ await cloneTree(options.gitRoot, dest, CLONE_SKIP_PREFIXES);
1330
+ cloned = true;
1331
+ } catch (error) {
1332
+ if (!(error instanceof CowUnavailableError)) throw error;
1333
+ }
1334
+ await executeFile("git", ["reset", "--hard", "HEAD"], { cwd: dest, timeoutMs: 6e4 });
1335
+ await executeFile("git", ["clean", "-fd"], { cwd: dest, timeoutMs: 6e4 });
1336
+ return { cloned, message: added.stdout.trim() };
1112
1337
  } catch (error) {
1113
- cloned = false;
1114
- if (!(error instanceof CowUnavailableError) && !(error instanceof Error)) throw error;
1338
+ const branch = options.branch?.flag === "-b" ? options.branch.name : void 0;
1339
+ try {
1340
+ await removeWorktree(options.gitRoot, dest, branch);
1341
+ } catch (cleanupError) {
1342
+ throw worktreeRollbackError(options.gitRoot, dest, branch, error, cleanupError);
1343
+ }
1344
+ throw error;
1115
1345
  }
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() };
1346
+ };
1347
+ var removeWorktree = async (gitRoot, worktree, branch) => {
1348
+ let failure;
1349
+ try {
1350
+ await executeFile("git", ["worktree", "remove", "--force", worktree], { cwd: gitRoot, timeoutMs: 6e4 });
1351
+ } catch (error) {
1352
+ if (fs7.existsSync(worktree)) failure = error;
1353
+ else await executeFile("git", ["worktree", "prune"], { cwd: gitRoot, timeoutMs: 3e4 }).catch(() => void 0);
1354
+ }
1355
+ if (branch) {
1356
+ try {
1357
+ const existing = await executeFile("git", ["branch", "--list", branch], { cwd: gitRoot, timeoutMs: 3e4 });
1358
+ if (existing.stdout.trim()) {
1359
+ await executeFile("git", ["branch", "-D", branch], { cwd: gitRoot, timeoutMs: 3e4 });
1360
+ }
1361
+ } catch (error) {
1362
+ failure ??= error;
1363
+ }
1364
+ }
1365
+ if (failure !== void 0) throw failure;
1119
1366
  };
1120
1367
 
1121
1368
  // src/agents/worktree-manager.ts
@@ -1126,9 +1373,9 @@ var SETUP_TIMEOUT_MS = 10 * 6e4;
1126
1373
  var SETUP_OUTPUT_TAIL_CHARS = 2e3;
1127
1374
  var countLines = (file) => {
1128
1375
  try {
1129
- const stat = fs7.statSync(file);
1376
+ const stat = fs8.statSync(file);
1130
1377
  if (!stat.isFile() || stat.size > MAX_COUNTED_BYTES) return 0;
1131
- const content = fs7.readFileSync(file);
1378
+ const content = fs8.readFileSync(file);
1132
1379
  if (content.length === 0 || content.includes(0)) return 0;
1133
1380
  let lines = 0;
1134
1381
  for (const byte of content) if (byte === 10) lines++;
@@ -1139,8 +1386,8 @@ var countLines = (file) => {
1139
1386
  };
1140
1387
  var safeLabel = (value) => value.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 30) || "agent";
1141
1388
  var isInside2 = (root, target) => {
1142
- const relative = path7.relative(root, target);
1143
- return relative === "" || relative !== ".." && !relative.startsWith(`..${path7.sep}`) && !path7.isAbsolute(relative);
1389
+ const relative = path8.relative(root, target);
1390
+ return relative === "" || relative !== ".." && !relative.startsWith(`..${path8.sep}`) && !path8.isAbsolute(relative);
1144
1391
  };
1145
1392
  var worktreePrefixParts = (prefix) => {
1146
1393
  const parts = prefix.split(/[\\/]+/).filter(Boolean);
@@ -1158,10 +1405,12 @@ var WorktreeManager = class {
1158
1405
  ]);
1159
1406
  const output = root.stdout.trim();
1160
1407
  if (!output) throw new Error("Git did not return a worktree root");
1161
- gitRoot = fs7.realpathSync(output);
1408
+ gitRoot = fs8.realpathSync(output);
1162
1409
  sourcePrefix = prefix2.stdout.trim();
1163
- } catch {
1164
- throw new Error("Worktree isolation requires a Git repository");
1410
+ } catch (error) {
1411
+ const failure = error;
1412
+ const detail = (failure.stderr?.trim() || failure.message || String(error)).split("\n", 1)[0].slice(0, 500);
1413
+ throw new Error(`Worktree isolation requires a Git repository: ${detail}`, { cause: error });
1165
1414
  }
1166
1415
  const branch = `pi-fabric/${safeLabel(name)}-${id.slice(0, 8)}`;
1167
1416
  const worktreePath = fabricWorktreePath(gitRoot, id);
@@ -1171,15 +1420,25 @@ var WorktreeManager = class {
1171
1420
  branch: { flag: "-b", name: branch },
1172
1421
  startPoint: "HEAD"
1173
1422
  });
1174
- const canonicalWorktreePath = fs7.realpathSync(worktreePath);
1423
+ let canonicalWorktreePath;
1424
+ try {
1425
+ canonicalWorktreePath = fs8.realpathSync(worktreePath);
1426
+ } catch (error) {
1427
+ try {
1428
+ await removeWorktree(gitRoot, worktreePath, branch);
1429
+ } catch (cleanupError) {
1430
+ throw worktreeRollbackError(gitRoot, worktreePath, branch, error, cleanupError);
1431
+ }
1432
+ throw error;
1433
+ }
1175
1434
  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
1435
  const prefix = preserveSourceSubdirectory ? worktreePrefixParts(sourcePrefix) : void 0;
1177
1436
  let effectiveCwd = canonicalWorktreePath;
1178
1437
  if (prefix && prefix.length > 0) {
1179
- const candidate = path7.resolve(canonicalWorktreePath, ...prefix);
1438
+ const candidate = path8.resolve(canonicalWorktreePath, ...prefix);
1180
1439
  try {
1181
- const canonicalCandidate = fs7.realpathSync(candidate);
1182
- if (fs7.statSync(canonicalCandidate).isDirectory() && isInside2(canonicalWorktreePath, canonicalCandidate)) {
1440
+ const canonicalCandidate = fs8.realpathSync(candidate);
1441
+ if (fs8.statSync(canonicalCandidate).isDirectory() && isInside2(canonicalWorktreePath, canonicalCandidate)) {
1183
1442
  effectiveCwd = canonicalCandidate;
1184
1443
  }
1185
1444
  } catch {
@@ -1218,7 +1477,7 @@ ${tail}` : ""}`);
1218
1477
  ...lease.baseRef ? { baseRef: lease.baseRef } : {},
1219
1478
  changedFiles: [],
1220
1479
  diffstat: { files: 0, insertions: 0, deletions: 0 },
1221
- kept: fs7.existsSync(lease.path)
1480
+ kept: fs8.existsSync(lease.path)
1222
1481
  };
1223
1482
  if (!result.kept) return result;
1224
1483
  try {
@@ -1238,7 +1497,7 @@ ${tail}` : ""}`);
1238
1497
  for (const file of untracked.stdout.split("\n")) {
1239
1498
  if (!file || files.has(file)) continue;
1240
1499
  files.add(file);
1241
- if (files.size <= MAX_CHANGED_FILES) result.diffstat.insertions += countLines(path7.join(lease.path, file));
1500
+ if (files.size <= MAX_CHANGED_FILES) result.diffstat.insertions += countLines(path8.join(lease.path, file));
1242
1501
  }
1243
1502
  result.diffstat.files = files.size;
1244
1503
  result.changedFiles = [...files].sort().slice(0, MAX_CHANGED_FILES);
@@ -1250,25 +1509,16 @@ ${tail}` : ""}`);
1250
1509
  async cleanup(id, deleteBranch = false) {
1251
1510
  const lease = this.#leases.get(id);
1252
1511
  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);
1512
+ await removeWorktree(lease.gitRoot, lease.path, deleteBranch ? lease.branch : void 0);
1513
+ if (this.#leases.get(id) === lease) this.#leases.delete(id);
1264
1514
  return true;
1265
1515
  }
1266
1516
  };
1267
1517
 
1268
1518
  // src/agents/handoff.ts
1269
- import { randomUUID as randomUUID4 } from "node:crypto";
1270
- import fs8 from "node:fs";
1271
- import path8 from "node:path";
1519
+ import { randomUUID as randomUUID3 } from "node:crypto";
1520
+ import fs9 from "node:fs";
1521
+ import path9 from "node:path";
1272
1522
 
1273
1523
  // src/core/host-sdk-runtime.ts
1274
1524
  var PiCodingAgent = await loadHostSdk();
@@ -1462,12 +1712,25 @@ var snapshotHandoffSession = (source, currentModel, outerToolResult, outerToolCa
1462
1712
  outerToolResult: structuredClone(outerToolResult)
1463
1713
  };
1464
1714
  };
1465
- var materializeBranch = (seed, cwd, directory) => {
1715
+ var withWorkerRoot = (entries) => {
1716
+ const policy = workerRoleEntry(
1717
+ freshEntryId(new Set(entries.map((entry) => entry.id))),
1718
+ null,
1719
+ (/* @__PURE__ */ new Date()).toISOString()
1720
+ );
1721
+ return [policy, ...entries.map((entry) => {
1722
+ if (entry.parentId !== null) return entry;
1723
+ const root = structuredClone(entry);
1724
+ root.parentId = policy.id;
1725
+ return root;
1726
+ })];
1727
+ };
1728
+ var materializeBranch = (seed, cwd, directory, options = {}) => {
1466
1729
  if (!seed.sourceBranch) {
1467
1730
  throw new Error("In-memory trajectory handoff is missing its source branch");
1468
1731
  }
1469
- const id = randomUUID4();
1470
- const sessionFile = path8.join(directory, `handoff-${id}.jsonl`);
1732
+ const id = randomUUID3();
1733
+ const sessionFile = path9.join(directory, `handoff-${id}.jsonl`);
1471
1734
  const header = {
1472
1735
  type: "session",
1473
1736
  version: PiCodingAgent.CURRENT_SESSION_VERSION,
@@ -1476,16 +1739,31 @@ var materializeBranch = (seed, cwd, directory) => {
1476
1739
  cwd,
1477
1740
  ...seed.sourceSessionFile ? { parentSession: seed.sourceSessionFile } : {}
1478
1741
  };
1479
- fs8.writeFileSync(
1742
+ const entries = options.workerRole ? withWorkerRoot(seed.sourceBranch) : seed.sourceBranch;
1743
+ fs9.writeFileSync(
1480
1744
  sessionFile,
1481
- `${[header, ...seed.sourceBranch].map((entry) => JSON.stringify(entry)).join("\n")}
1745
+ `${[header, ...entries].map((entry) => JSON.stringify(entry)).join("\n")}
1482
1746
  `,
1483
1747
  { encoding: "utf8", mode: 384, flag: "wx" }
1484
1748
  );
1485
1749
  return PiCodingAgent.SessionManager.open(sessionFile, directory, cwd);
1486
1750
  };
1487
- var forkBranch = (seed, cwd, directory) => {
1488
- if (!seed.sourceSessionFile) return materializeBranch(seed, cwd, directory);
1751
+ var insertWorkerRoot = (sessionFile) => {
1752
+ if (!fs9.existsSync(sessionFile)) {
1753
+ throw new Error("Trajectory handoff session file was not written, so the worker role cannot be placed at its root");
1754
+ }
1755
+ const [headerLine, ...entryLines] = fs9.readFileSync(sessionFile, "utf8").split("\n").filter((line) => line.length > 0);
1756
+ const entries = entryLines.map((line) => JSON.parse(line));
1757
+ const placed = withWorkerRoot(entries);
1758
+ fs9.writeFileSync(
1759
+ sessionFile,
1760
+ `${[headerLine, ...placed.map((entry) => JSON.stringify(entry))].join("\n")}
1761
+ `,
1762
+ { encoding: "utf8", mode: 384 }
1763
+ );
1764
+ };
1765
+ var forkBranch = (seed, cwd, directory, options = {}) => {
1766
+ if (!seed.sourceSessionFile) return materializeBranch(seed, cwd, directory, options);
1489
1767
  const fork = PiCodingAgent.SessionManager.open(seed.sourceSessionFile, directory, cwd);
1490
1768
  if (!fork.getEntry(seed.sourceBranchLeafId)) {
1491
1769
  throw new Error(
@@ -1519,14 +1797,15 @@ var synchronizeSourceSettings = (session, seed) => {
1519
1797
  session.appendThinkingLevelChange(seed.sourceThinkingLevel);
1520
1798
  }
1521
1799
  };
1522
- var writeHandoffSession = (seed, cwd, directory, transfer, compaction, compactionBudget) => {
1523
- fs8.mkdirSync(directory, { recursive: true, mode: 448 });
1800
+ var writeHandoffSession = (seed, cwd, directory, transfer, compaction, compactionBudget, options = {}) => {
1801
+ fs9.mkdirSync(directory, { recursive: true, mode: 448 });
1524
1802
  const policy = transfer ? thinkingTransferPolicy(transfer) : "preserved";
1525
1803
  let session;
1804
+ const viaPiBranch = Boolean(seed.sourceSessionFile) && (!transfer || policy === "preserved");
1526
1805
  let report;
1527
1806
  let digest;
1528
1807
  if (!transfer || policy === "preserved") {
1529
- session = forkBranch(seed, cwd, directory);
1808
+ session = forkBranch(seed, cwd, directory, options);
1530
1809
  } else {
1531
1810
  const rawBranch = seed.sourceSessionFile ? persistedBranch(seed, cwd, directory) : structuredClone(seed.sourceBranch ?? (() => {
1532
1811
  throw new Error("Trajectory handoff transfer is missing its source branch");
@@ -1534,7 +1813,7 @@ var writeHandoffSession = (seed, cwd, directory, transfer, compaction, compactio
1534
1813
  if (policy === "stripped") digest = buildThinkingDigest(rawBranch, transfer);
1535
1814
  const translated = translateThinkingForExecutor(rawBranch, policy);
1536
1815
  report = translated.report;
1537
- session = materializeBranch({ ...seed, sourceBranch: translated.entries }, cwd, directory);
1816
+ session = materializeBranch({ ...seed, sourceBranch: translated.entries }, cwd, directory, options);
1538
1817
  }
1539
1818
  synchronizeSourceSettings(session, seed);
1540
1819
  session.appendMessage(seed.outerToolResult);
@@ -1594,11 +1873,12 @@ var writeHandoffSession = (seed, cwd, directory, transfer, compaction, compactio
1594
1873
  });
1595
1874
  const sessionFile = session.getSessionFile();
1596
1875
  if (!sessionFile) throw new Error("Trajectory handoff did not produce a Pi session file");
1597
- fs8.chmodSync(sessionFile, 384);
1876
+ if (options.workerRole && viaPiBranch) insertWorkerRoot(sessionFile);
1877
+ fs9.chmodSync(sessionFile, 384);
1598
1878
  return sessionFile;
1599
1879
  };
1600
- var writeForkSession = (seed, cwd, directory, transfer) => {
1601
- fs8.mkdirSync(directory, { recursive: true, mode: 448 });
1880
+ var writeForkSession = (seed, cwd, directory, transfer, options = {}) => {
1881
+ fs9.mkdirSync(directory, { recursive: true, mode: 448 });
1602
1882
  const policy = transfer ? thinkingTransferPolicy(transfer) : "preserved";
1603
1883
  const raw = structuredClone(seed.sourceBranch);
1604
1884
  const digest = policy === "stripped" && transfer ? buildThinkingDigest(raw, transfer) : void 0;
@@ -1606,7 +1886,8 @@ var writeForkSession = (seed, cwd, directory, transfer) => {
1606
1886
  const session = materializeBranch(
1607
1887
  { sourceBranch: entries, ...seed.sourceSessionFile ? { sourceSessionFile: seed.sourceSessionFile } : {} },
1608
1888
  cwd,
1609
- directory
1889
+ directory,
1890
+ options
1610
1891
  );
1611
1892
  if (digest) {
1612
1893
  session.appendCustomMessageEntry(THINKING_DIGEST_CUSTOM_TYPE, digest.content, false, {
@@ -1621,13 +1902,13 @@ var writeForkSession = (seed, cwd, directory, transfer) => {
1621
1902
  });
1622
1903
  const sessionFile = session.getSessionFile();
1623
1904
  if (!sessionFile) throw new Error("Branch seed did not produce a Pi session file");
1624
- fs8.chmodSync(sessionFile, 384);
1905
+ fs9.chmodSync(sessionFile, 384);
1625
1906
  return sessionFile;
1626
1907
  };
1627
1908
 
1628
1909
  // src/agents/child-env.ts
1629
- import fs9 from "node:fs";
1630
- import path9 from "node:path";
1910
+ import fs10 from "node:fs";
1911
+ import path10 from "node:path";
1631
1912
  var MAX_WRITABLE_ROOTS = 32;
1632
1913
  var MAX_ROOT_CHARS = 4096;
1633
1914
  var readAgentLineage = (raw = process.env.PI_FABRIC_LINEAGE) => {
@@ -1658,12 +1939,12 @@ var checkWritePolicyRequest = (request) => {
1658
1939
  };
1659
1940
  var nearestExisting = (target) => {
1660
1941
  let current = target;
1661
- while (!fs9.existsSync(current)) {
1662
- const parent = path9.dirname(current);
1942
+ while (!fs10.existsSync(current)) {
1943
+ const parent = path10.dirname(current);
1663
1944
  if (parent === current) break;
1664
1945
  current = parent;
1665
1946
  }
1666
- return path9.join(fs9.realpathSync(current), path9.relative(current, target));
1947
+ return path10.join(fs10.realpathSync(current), path10.relative(current, target));
1667
1948
  };
1668
1949
  var resolveChildWritePolicy = (request, parent, cwd) => {
1669
1950
  if (!requestsWritePolicy(request)) return parent;
@@ -1676,39 +1957,72 @@ var resolveChildWritePolicy = (request, parent, cwd) => {
1676
1957
  throw new Error('A shell-confined agent cannot launch a child with shell: "unconfined"');
1677
1958
  }
1678
1959
  if (readOnly) return { readOnly, writableRoots: [], shell };
1679
- const realCwd = fs9.realpathSync(cwd);
1960
+ const realCwd = fs10.realpathSync(cwd);
1680
1961
  const within = (target) => !parent || parent.writableRoots.some((root) => isInside(root, target));
1681
1962
  const roots = request.writableRoots ?? (parent ? parent.writableRoots : [cwd]);
1682
1963
  const resolved = /* @__PURE__ */ new Set();
1683
1964
  for (const root of roots) {
1684
- const absolute = path9.resolve(cwd, root);
1685
- if (!fs9.existsSync(absolute)) {
1965
+ const absolute = path10.resolve(cwd, root);
1966
+ if (!fs10.existsSync(absolute)) {
1686
1967
  const target = nearestExisting(absolute);
1687
1968
  if (!isInside(cwd, absolute) || !isInside(realCwd, target) || !within(target)) {
1688
1969
  throw new Error(`Writable root must exist or be creatable inside the agent cwd: ${root}`);
1689
1970
  }
1690
- fs9.mkdirSync(absolute, { recursive: true });
1971
+ fs10.mkdirSync(absolute, { recursive: true });
1691
1972
  }
1692
- const real = fs9.realpathSync(absolute);
1693
- if (!fs9.statSync(real).isDirectory()) throw new Error(`Writable root is not a directory: ${root}`);
1973
+ const real = fs10.realpathSync(absolute);
1974
+ if (!fs10.statSync(real).isDirectory()) throw new Error(`Writable root is not a directory: ${root}`);
1694
1975
  if (!within(real)) throw new Error(`Writable root is outside the caller's writable roots: ${root}`);
1695
1976
  resolved.add(real);
1696
1977
  }
1697
1978
  return { readOnly, writableRoots: [...resolved].sort(), shell };
1698
1979
  };
1699
1980
 
1981
+ // src/verified/generated/budget.js
1982
+ function $n(v, what) {
1983
+ if (typeof v !== "number" || !Number.isSafeInteger(v) || v < 0) throw new RangeError(what + " must be a natural below 2^53, not " + v);
1984
+ return v;
1985
+ }
1986
+ var budgetAdmission = /* @__PURE__ */ (() => {
1987
+ function init(params) {
1988
+ const env = {}, s = {};
1989
+ return { scalars: { "out.admitted": 0 }, maps: {} };
1990
+ }
1991
+ function step(params, state, input) {
1992
+ 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;
1993
+ 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");
1994
+ const scalars = { ...s, "out.admitted": env["valid"] === 1 && (env["spentHigh"] < env["limitHigh"] || env["spentHigh"] === env["limitHigh"] && env["spentLow"] < env["limitLow"]) ? 1 : 0 };
1995
+ return Object.keys(dft).length ? { scalars, maps: state.maps, defaults: dft } : { scalars, maps: state.maps };
1996
+ }
1997
+ return { init, step };
1998
+ })();
1999
+
2000
+ // src/verified/budget.ts
2001
+ var orderedWords = (value) => {
2002
+ const view = new DataView(new ArrayBuffer(8));
2003
+ view.setFloat64(0, value === 0 ? 0 : value);
2004
+ const high = view.getUint32(0), low = view.getUint32(4);
2005
+ return (high & 2147483648) !== 0 ? [~high >>> 0, ~low >>> 0] : [(high ^ 2147483648) >>> 0, low];
2006
+ };
2007
+ var budgetAdmits = (spent, limit) => {
2008
+ const valid = Number.isFinite(spent) && Number.isFinite(limit) && limit > 0;
2009
+ const [spentHigh, spentLow] = orderedWords(valid ? spent : 0);
2010
+ const [limitHigh, limitLow] = orderedWords(valid ? limit : 0);
2011
+ return budgetAdmission.step({}, budgetAdmission.init({}), { valid: valid ? 1 : 0, spentHigh, spentLow, limitHigh, limitLow }).scalars["out.admitted"] === 1;
2012
+ };
2013
+
1700
2014
  // src/storage/retention.ts
1701
- import fs10 from "node:fs";
1702
- import path10 from "node:path";
2015
+ import fs11 from "node:fs";
2016
+ import path11 from "node:path";
1703
2017
  var RUN_ROOT_OWNER_FILE = ".fabric-owner.json";
1704
2018
  var TERMINAL_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "stopped", "timed_out"]);
1705
2019
  var RUN_ROOT_HEARTBEAT_TTL_MS = 45 * 60 * 1e3;
1706
- var ownerPath = (root) => path10.join(root, RUN_ROOT_OWNER_FILE);
2020
+ var ownerPath = (root) => path11.join(root, RUN_ROOT_OWNER_FILE);
1707
2021
  var readJson = (file) => {
1708
2022
  try {
1709
2023
  const stat = ownedStat(file);
1710
2024
  if (!stat?.isFile() || stat.size > 1024 * 1024) return;
1711
- return JSON.parse(fs10.readFileSync(file, "utf8"));
2025
+ return JSON.parse(fs11.readFileSync(file, "utf8"));
1712
2026
  } catch {
1713
2027
  return;
1714
2028
  }
@@ -1716,9 +2030,9 @@ var readJson = (file) => {
1716
2030
  var time = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
1717
2031
  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
2032
  var writeOwner = (root, owner) => {
1719
- if (fs10.existsSync(root) && !ownedStat(root)?.isDirectory()) throw new Error("Unsafe Fabric run root");
2033
+ if (fs11.existsSync(root) && !ownedStat(root)?.isDirectory()) throw new Error("Unsafe Fabric run root");
1720
2034
  const file = ownerPath(root);
1721
- if (fs10.existsSync(file)) {
2035
+ if (fs11.existsSync(file)) {
1722
2036
  const existing = readJson(file);
1723
2037
  if (!validOwner(existing) || existing.pid !== owner.pid) throw new Error("Unsafe Fabric run owner marker");
1724
2038
  }
@@ -1746,36 +2060,98 @@ var childAlive = (owner, pid) => {
1746
2060
  };
1747
2061
  var recordAgeReference = (record, fallback) => time(record.finishedAt) ? record.finishedAt : time(record.updatedAt) ? record.updatedAt : fallback;
1748
2062
  var runFiles = /* @__PURE__ */ new Set(["task.txt", "status.json", "events.jsonl", "lifecycle.jsonl", "steer.jsonl", "schema.json", "images.json"]);
2063
+ 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}";
2064
+ 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}";
2065
+ var PID = "[1-9]\\d*";
2066
+ var HANDOFF_FILE = new RegExp(`^handoff-${UUID_V4}\\.jsonl$`);
2067
+ 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$`);
2068
+ var piBranchFile = (name) => {
2069
+ const match = PI_BRANCH_FILE.exec(name);
2070
+ if (!match) return false;
2071
+ const iso = `${match[1]}T${match[2]}:${match[3]}:${match[4]}.${match[5]}Z`;
2072
+ const instant = new Date(iso);
2073
+ return !Number.isNaN(instant.getTime()) && instant.toISOString() === iso;
2074
+ };
2075
+ var forkSessionFile = (name) => HANDOFF_FILE.test(name) || piBranchFile(name);
2076
+ var STATUS_TEMP_FILE = new RegExp(`^status\\.json\\.${PID}(?:\\.${UUID_V4})?\\.tmp$`);
2077
+ var OVERSIZED_EVENT_FILE = "oversized-event-prefix.txt";
1749
2078
  var DURABLE_KEY = /^(?:initial|[0-9a-f]{64})$/;
1750
2079
  var DURABLE_LEASE_FILES = /* @__PURE__ */ new Set(["lease.sqlite", "lease.sqlite-journal"]);
1751
2080
  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);
2081
+ var FABRIC_JOURNAL_FILE = /^[0-9a-f]{32}\.jsonl$/;
2082
+ var onlyOwnedFiles = (directory, allowed) => fs11.readdirSync(directory).every((name) => allowed(name) && ownedStat(path11.join(directory, name))?.isFile() === true);
2083
+ var DURABLE_SESSION_FILE = "session.jsonl";
2084
+ 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$/;
2085
+ var DURABLE_SESSION_SIDECAR = /^session\.jsonl\.[A-Za-z0-9][A-Za-z0-9._-]*$/;
2086
+ var safeDurableSessionFolder = (directory) => {
2087
+ const uid = process.getuid?.();
2088
+ const stats = /* @__PURE__ */ new Map();
2089
+ for (const name of fs11.readdirSync(directory)) {
2090
+ if (DURABLE_SESSION_SIDECAR.test(name)) {
2091
+ const sidecar = fs11.lstatSync(path11.join(directory, name));
2092
+ if (!sidecar.isFile() || uid !== void 0 && sidecar.uid !== uid || sidecar.nlink !== 1) return false;
2093
+ continue;
2094
+ }
2095
+ if (name !== DURABLE_SESSION_FILE && !DURABLE_SESSION_TEMP.test(name)) return false;
2096
+ const stat = fs11.lstatSync(path11.join(directory, name));
2097
+ if (!stat.isFile() || uid !== void 0 && stat.uid !== uid || stat.nlink > 2) return false;
2098
+ stats.set(name, stat);
2099
+ }
2100
+ const linked = [...stats.entries()].filter(([, stat]) => stat.nlink !== 1);
2101
+ if (linked.length === 0) return true;
2102
+ const session = stats.get(DURABLE_SESSION_FILE);
2103
+ const temporaries = [...stats.entries()].filter(([name]) => name !== DURABLE_SESSION_FILE);
2104
+ const [temporary] = temporaries;
2105
+ 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;
2106
+ };
2107
+ var safeDurableTree = (directory) => fs11.readdirSync(directory).every((key) => {
2108
+ const conversation = path11.join(directory, key);
1755
2109
  if (!DURABLE_KEY.test(key) || !ownedStat(conversation)?.isDirectory()) return false;
1756
- return fs10.readdirSync(conversation).every((name) => {
1757
- const file = path10.join(conversation, name);
2110
+ return fs11.readdirSync(conversation).every((name) => {
2111
+ const file = path11.join(conversation, name);
1758
2112
  if (name === "store") return ownedStat(file)?.isDirectory() === true && onlyOwnedFiles(file, (child) => DURABLE_STORE_FILE.test(child));
2113
+ if (name === "fabric-journal") return ownedStat(file)?.isDirectory() === true && onlyOwnedFiles(file, (child) => FABRIC_JOURNAL_FILE.test(child));
1759
2114
  return DURABLE_LEASE_FILES.has(name) && ownedStat(file)?.isFile() === true;
1760
2115
  });
1761
2116
  });
1762
- var safeRunTree = (root, childrenStopped, owner, depth = 0) => {
2117
+ var ownedTree = (directory, depth) => {
2118
+ if (depth > 32) return false;
2119
+ return fs11.readdirSync(directory).every((name) => {
2120
+ const stat = ownedStat(path11.join(directory, name));
2121
+ if (!stat || name.startsWith("hosted.json")) return false;
2122
+ return stat.isFile() || stat.isDirectory() && ownedTree(path11.join(directory, name), depth + 1);
2123
+ });
2124
+ };
2125
+ var safeRunTree = (root, childrenStopped, owner, depth = 0, anyContents = false) => {
1763
2126
  if (depth > 32 || !ownedStat(root)?.isDirectory()) return false;
1764
- const record = readJson(path10.join(root, "status.json"));
2127
+ const record = readJson(path11.join(root, "status.json"));
1765
2128
  const pid = record?.transport === "process" && typeof record.sessionId === "string" && /^\d+$/.test(record.sessionId) ? Number(record.sessionId) : void 0;
1766
2129
  if (pid !== void 0 && childAlive(owner, pid)) return false;
1767
- if (!record?.status || !TERMINAL_STATUSES.has(record.status)) {
2130
+ const terminal = !!record?.status && TERMINAL_STATUSES.has(record.status);
2131
+ if (!terminal) {
1768
2132
  if (!childrenStopped && pid === void 0) return false;
1769
- if (!ownedStat(path10.join(root, "task.txt"))?.isFile()) return false;
2133
+ if (!ownedStat(path11.join(root, "task.txt"))?.isFile()) return false;
1770
2134
  }
1771
2135
  try {
1772
- for (const name of fs10.readdirSync(root)) {
1773
- const file = path10.join(root, name);
2136
+ for (const name of fs11.readdirSync(root)) {
2137
+ const file = path11.join(root, name);
1774
2138
  const stat = ownedStat(file);
1775
2139
  if (!stat) return false;
1776
- if (stat.isFile() && runFiles.has(name)) continue;
2140
+ if (stat.isFile() && (runFiles.has(name) || name === OVERSIZED_EVENT_FILE || STATUS_TEMP_FILE.test(name))) continue;
2141
+ if (anyContents && name !== "nested" && !name.startsWith("hosted.json")) {
2142
+ if (stat.isFile() || stat.isDirectory() && ownedTree(file, depth + 1)) continue;
2143
+ return false;
2144
+ }
2145
+ if (stat.isDirectory() && name === "fork-session") {
2146
+ if (!onlyOwnedFiles(file, (child) => forkSessionFile(child))) return false;
2147
+ continue;
2148
+ }
1777
2149
  if (stat.isDirectory() && name === "handoff-session") {
1778
- if (fs10.readdirSync(file).some((child) => !child.endsWith(".jsonl") || !ownedStat(path10.join(file, child))?.isFile())) return false;
2150
+ if (fs11.readdirSync(file).some((child) => !child.endsWith(".jsonl") || !ownedStat(path11.join(file, child))?.isFile())) return false;
2151
+ continue;
2152
+ }
2153
+ if (stat.isDirectory() && name === "durable-session") {
2154
+ if (!safeDurableSessionFolder(file)) return false;
1779
2155
  continue;
1780
2156
  }
1781
2157
  if (stat.isDirectory() && name === "durable") {
@@ -1783,7 +2159,7 @@ var safeRunTree = (root, childrenStopped, owner, depth = 0) => {
1783
2159
  continue;
1784
2160
  }
1785
2161
  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;
2162
+ for (const child of fs11.readdirSync(file)) if (!safeRunTree(path11.join(file, child), false, owner, depth + 1, anyContents)) return false;
1787
2163
  continue;
1788
2164
  }
1789
2165
  return false;
@@ -1793,9 +2169,9 @@ var safeRunTree = (root, childrenStopped, owner, depth = 0) => {
1793
2169
  return false;
1794
2170
  }
1795
2171
  };
1796
- var safeRootContents = (root, childrenStopped, owner) => {
2172
+ var safeRootContents = (root, childrenStopped, owner, anyContents = false) => {
1797
2173
  try {
1798
- return fs10.readdirSync(root).every((name) => name === RUN_ROOT_OWNER_FILE || safeRunTree(path10.join(root, name), childrenStopped, owner));
2174
+ return fs11.readdirSync(root).every((name) => name === RUN_ROOT_OWNER_FILE || safeRunTree(path11.join(root, name), childrenStopped, owner, 0, anyContents));
1799
2175
  } catch {
1800
2176
  return false;
1801
2177
  }
@@ -1808,8 +2184,8 @@ var canRemoveManagedRunRoot = (root) => {
1808
2184
  var removeEmptyRunRoot = (root) => {
1809
2185
  try {
1810
2186
  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 });
2187
+ if (fs11.readdirSync(root).some((name) => name !== RUN_ROOT_OWNER_FILE)) return false;
2188
+ fs11.rmSync(root, { recursive: true, force: true });
1813
2189
  return true;
1814
2190
  } catch {
1815
2191
  return false;
@@ -1819,21 +2195,21 @@ var pruneClosedRunRoot = (root, owner, orphanMs, oneShotMs, now) => {
1819
2195
  const removed = [];
1820
2196
  let entries;
1821
2197
  try {
1822
- entries = fs10.readdirSync(root, { withFileTypes: true });
2198
+ entries = fs11.readdirSync(root, { withFileTypes: true });
1823
2199
  } catch {
1824
2200
  return removed;
1825
2201
  }
1826
2202
  for (const entry of entries) {
1827
2203
  if (!entry.isDirectory()) continue;
1828
- const directory = path10.join(root, entry.name);
2204
+ const directory = path11.join(root, entry.name);
1829
2205
  if (!safeRunTree(directory, owner.childrenStopped === true, owner)) continue;
1830
- const record = readJson(path10.join(directory, "status.json"));
2206
+ const record = readJson(path11.join(directory, "status.json"));
1831
2207
  const terminal = !!record?.status && TERMINAL_STATUSES.has(record.status);
1832
2208
  const reference = terminal ? recordAgeReference(record, ownedStat(directory)?.mtimeMs ?? now) : owner.closedAt;
1833
2209
  const retention = terminal && !record?.actorId ? oneShotMs : orphanMs;
1834
2210
  if (now - reference < retention) continue;
1835
2211
  try {
1836
- fs10.rmSync(directory, { recursive: true, force: true });
2212
+ fs11.rmSync(directory, { recursive: true, force: true });
1837
2213
  removed.push(directory);
1838
2214
  } catch {
1839
2215
  }
@@ -1845,14 +2221,14 @@ var sweepTempRunRoots = (options) => {
1845
2221
  const result = { removedRoots: [], removedRuns: [] };
1846
2222
  let entries;
1847
2223
  try {
1848
- entries = fs10.readdirSync(options.tempRoot, { withFileTypes: true });
2224
+ entries = fs11.readdirSync(options.tempRoot, { withFileTypes: true });
1849
2225
  } catch {
1850
2226
  return result;
1851
2227
  }
1852
2228
  for (const entry of entries) {
1853
2229
  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;
2230
+ const root = path11.join(options.tempRoot, entry.name);
2231
+ if (options.currentRoot && path11.resolve(root) === path11.resolve(options.currentRoot)) continue;
1856
2232
  if (!ownedStat(root)?.isDirectory()) continue;
1857
2233
  const owner = readJson(ownerPath(root));
1858
2234
  if (!validOwner(owner)) continue;
@@ -1869,9 +2245,9 @@ var sweepTempRunRoots = (options) => {
1869
2245
  }
1870
2246
  continue;
1871
2247
  }
1872
- if (now - owner.orphanedAt < options.orphanedTempRunRetentionMs || !safeRootContents(root, false, owner)) continue;
2248
+ if (now - owner.orphanedAt < options.orphanedTempRunRetentionMs || !safeRootContents(root, false, owner, true)) continue;
1873
2249
  try {
1874
- fs10.rmSync(root, { recursive: true, force: true });
2250
+ fs11.rmSync(root, { recursive: true, force: true });
1875
2251
  result.removedRoots.push(root);
1876
2252
  } catch {
1877
2253
  }
@@ -1884,18 +2260,18 @@ var pruneActorRunArchives = (options) => {
1884
2260
  if (!ownedStat(options.runsDirectory)?.isDirectory()) return removed;
1885
2261
  let entries;
1886
2262
  try {
1887
- entries = fs10.readdirSync(options.runsDirectory, { withFileTypes: true });
2263
+ entries = fs11.readdirSync(options.runsDirectory, { withFileTypes: true });
1888
2264
  } catch {
1889
2265
  return removed;
1890
2266
  }
1891
2267
  for (const entry of entries) {
1892
2268
  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"));
2269
+ const directory = path11.join(options.runsDirectory, entry.name);
2270
+ const record = readJson(path11.join(directory, "status.json"));
1895
2271
  if (!record?.status || !TERMINAL_STATUSES.has(record.status) || !safeRunTree(directory, false)) continue;
1896
2272
  if (now - recordAgeReference(record, ownedStat(directory)?.mtimeMs ?? now) < options.retentionMs) continue;
1897
2273
  try {
1898
- fs10.rmSync(directory, { recursive: true, force: true });
2274
+ fs11.rmSync(directory, { recursive: true, force: true });
1899
2275
  removed.push(directory);
1900
2276
  } catch {
1901
2277
  }
@@ -1905,21 +2281,21 @@ var pruneActorRunArchives = (options) => {
1905
2281
 
1906
2282
  // src/agents/session-export.ts
1907
2283
  import os2 from "node:os";
1908
- import path11 from "node:path";
2284
+ import path12 from "node:path";
1909
2285
  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;
2286
+ var expandHome = (value) => value === "~" ? os2.homedir() : value.startsWith("~/") || value.startsWith(`~${path12.win32.sep}`) ? path12.join(os2.homedir(), value.slice(2)) : value;
1911
2287
  var encodeSessionExportCwd = (cwd) => {
1912
- const absolute = path11.isAbsolute(cwd) || path11.win32.isAbsolute(cwd) ? cwd : path11.resolve(cwd);
2288
+ const absolute = path12.isAbsolute(cwd) || path12.win32.isAbsolute(cwd) ? cwd : path12.resolve(cwd);
1913
2289
  return `--${absolute.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
1914
2290
  };
1915
2291
  var resolveSessionExportDir = (config) => {
1916
2292
  if (!config.sessionExport) return void 0;
1917
- const raw = process.env[SESSION_EXPORT_ENV]?.trim() || config.sessionExportDir.trim() || path11.join(os2.homedir(), ".pi", "agent");
2293
+ const raw = process.env[SESSION_EXPORT_ENV]?.trim() || config.sessionExportDir.trim() || path12.join(os2.homedir(), ".pi", "agent");
1918
2294
  return expandHome(raw);
1919
2295
  };
1920
2296
  var sessionExportFileFor = (root, cwd, runId, at) => {
1921
2297
  const fileTimestamp = at.toISOString().replace(/[:.]/g, "-");
1922
- return path11.join(
2298
+ return path12.join(
1923
2299
  root,
1924
2300
  "sessions",
1925
2301
  ".fabric",
@@ -1960,11 +2336,11 @@ var resolveAgentCwd = (parentCwd, requestedCwd) => {
1960
2336
  if (typeof requested !== "string" || requested.trim().length === 0) {
1961
2337
  throw new Error(`Invalid Fabric agent cwd ${JSON.stringify(requested)}: path must not be empty`);
1962
2338
  }
1963
- const candidate = path12.isAbsolute(requested) ? requested : path12.resolve(parentCwd, requested);
2339
+ const candidate = path13.isAbsolute(requested) ? requested : path13.resolve(parentCwd, requested);
1964
2340
  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()) {
2341
+ const canonical = fs12.realpathSync(candidate);
2342
+ fs12.accessSync(canonical, fs12.constants.R_OK | fs12.constants.X_OK);
2343
+ if (!fs12.statSync(canonical).isDirectory()) {
1968
2344
  throw new Error("path is not a directory");
1969
2345
  }
1970
2346
  return canonical;
@@ -1974,6 +2350,35 @@ var resolveAgentCwd = (parentCwd, requestedCwd) => {
1974
2350
  }
1975
2351
  };
1976
2352
  var terminalStatuses = terminalAgentStatuses;
2353
+ var queuedResult = (entry, status, error) => {
2354
+ const now = Date.now();
2355
+ return {
2356
+ id: entry.id,
2357
+ name: entry.name,
2358
+ task: entry.task,
2359
+ status,
2360
+ runner: entry.runner,
2361
+ ...entry.kernel ? { kernel: entry.kernel } : {},
2362
+ transport: entry.transport,
2363
+ cwd: entry.cwd,
2364
+ ...entry.model ? { model: entry.model } : {},
2365
+ startedAt: entry.queuedAt,
2366
+ updatedAt: now,
2367
+ finishedAt: now,
2368
+ turns: 0,
2369
+ toolCalls: 0,
2370
+ text: "",
2371
+ error,
2372
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 }
2373
+ };
2374
+ };
2375
+ var fileSize = (filePath) => {
2376
+ try {
2377
+ return fs12.statSync(filePath).size;
2378
+ } catch {
2379
+ return 0;
2380
+ }
2381
+ };
1977
2382
  var HOSTED_TRANSPORT = {
1978
2383
  kind: "process",
1979
2384
  available: async () => false,
@@ -2020,7 +2425,7 @@ var runName = (request) => safeName(request.name ?? request.task.split("\n", 1)[
2020
2425
  var safeName = (value) => value.replace(/[\r\n\t]+/g, " ").trim().slice(0, MAX_NAME_LENGTH) || "Fabric agent";
2021
2426
  var readRecord = (filePath) => {
2022
2427
  try {
2023
- const parsed = JSON.parse(fs11.readFileSync(filePath, "utf8"));
2428
+ const parsed = JSON.parse(fs12.readFileSync(filePath, "utf8"));
2024
2429
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
2025
2430
  const record = parsed;
2026
2431
  return { ...record, runner: isFabricRunnerId(record.runner) ? record.runner : "pi" };
@@ -2072,24 +2477,24 @@ var reconcileNestedAgents = (records, owner) => records.map((record) => {
2072
2477
  });
2073
2478
  var readNestedAgents = (runDirectory, depth = 0) => {
2074
2479
  if (depth >= 8) return [];
2075
- const nestedRoot = path12.join(runDirectory, "nested");
2480
+ const nestedRoot = path13.join(runDirectory, "nested");
2076
2481
  let entries;
2077
2482
  try {
2078
- entries = fs11.readdirSync(nestedRoot);
2483
+ entries = fs12.readdirSync(nestedRoot);
2079
2484
  } catch {
2080
2485
  return [];
2081
2486
  }
2082
2487
  const agents = [];
2083
2488
  for (const entry of entries.slice(0, 200)) {
2084
- const runDirectory2 = path12.join(nestedRoot, entry);
2085
- const record = readRecord(path12.join(runDirectory2, "status.json"));
2489
+ const runDirectory2 = path13.join(nestedRoot, entry);
2490
+ const record = readRecord(path13.join(runDirectory2, "status.json"));
2086
2491
  if (!record) continue;
2087
2492
  const nestedAgents = readNestedAgents(runDirectory2, depth + 1);
2088
2493
  const { logFile: _logFile, nestedAgents: _nestedAgents, ...safeRecord } = record;
2089
2494
  agents.push(
2090
2495
  compactUiRecord({
2091
2496
  ...safeRecord,
2092
- logFile: path12.join(runDirectory2, "events.jsonl"),
2497
+ logFile: path13.join(runDirectory2, "events.jsonl"),
2093
2498
  ...nestedAgents.length > 0 ? { nestedAgents } : {}
2094
2499
  })
2095
2500
  );
@@ -2097,7 +2502,7 @@ var readNestedAgents = (runDirectory, depth = 0) => {
2097
2502
  return agents;
2098
2503
  };
2099
2504
  var summarizeRunLog = (runDirectory, lines) => {
2100
- const page = readJsonlPage(path12.join(runDirectory, "events.jsonl"), lines);
2505
+ const page = readJsonlPage(path13.join(runDirectory, "events.jsonl"), lines);
2101
2506
  const summary = [];
2102
2507
  for (const entry of page.lines) {
2103
2508
  const parsed = entry.parsed;
@@ -2150,8 +2555,8 @@ var AgentManager = class {
2150
2555
  this.config = config;
2151
2556
  this.#semaphore = new AgentAdmission(config.maxConcurrent, Infinity, config.maxDepth);
2152
2557
  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;
2558
+ this.#runRoot = options.runRoot ?? process.env.PI_FABRIC_RUN_ROOT ?? fs12.mkdtempSync(path13.join(os3.tmpdir(), "pi-fabric-runs-"));
2559
+ this.#parentOwnedRunRoot = options.runRoot === void 0 && this.#parentLineage?.worker === true && this.#parentLineage.depth > 0 && path13.basename(this.#runRoot) === "nested" && path13.basename(path13.dirname(this.#runRoot)) === this.#parentLineage.runId;
2155
2560
  this.#retention = options.retention ?? DEFAULT_FABRIC_CONFIG.retention;
2156
2561
  this.#workerPath = options.workerPath ?? fileURLToPath(new URL("../worker.js", import.meta.url));
2157
2562
  this.#fabricExtensionPath = options.fabricExtensionPath ?? fileURLToPath(new URL("../index.js", import.meta.url));
@@ -2248,14 +2653,16 @@ var AgentManager = class {
2248
2653
  #closePromise;
2249
2654
  #closeAbort = new AbortController();
2250
2655
  #spawns = /* @__PURE__ */ new Set();
2656
+ /** spawn({ queue: true }) runs that hold an id but no slot yet, or that ended before they started. */
2657
+ #queued = /* @__PURE__ */ new Map();
2251
2658
  #unregisteredTransports = /* @__PURE__ */ new Set();
2252
2659
  #launches = /* @__PURE__ */ new Set();
2253
- async #prepareModel(model) {
2660
+ async #prepareModel(model, modelMatch) {
2254
2661
  if (!this.#preparePiModel) return model;
2255
- const key = model?.trim() || "<session-default>";
2662
+ const key = `${modelMatch ?? ""}|${model?.trim() || "<session-default>"}`;
2256
2663
  const existing = this.#piModelPreparations.get(key);
2257
2664
  if (existing) return existing;
2258
- const preparation = this.#preparePiModel(model).then((prepared) => {
2665
+ const preparation = (modelMatch ? this.#preparePiModel(model, { modelMatch }) : this.#preparePiModel(model)).then((prepared) => {
2259
2666
  if (typeof prepared !== "string") return model;
2260
2667
  return prepared.trim() || model;
2261
2668
  });
@@ -2275,6 +2682,10 @@ var AgentManager = class {
2275
2682
  resolveCwd(requestedCwd) {
2276
2683
  return resolveAgentCwd(this.cwd, requestedCwd);
2277
2684
  }
2685
+ /** The project root Fabric already uses for the mesh; named agent files live under its .pi folder. */
2686
+ get projectRoot() {
2687
+ return this.#projectRoot;
2688
+ }
2278
2689
  #inheritedSessionPins(request) {
2279
2690
  const explicit = request.inheritedSessionPins;
2280
2691
  if (explicit && explicit.length > 0) return explicit;
@@ -2328,6 +2739,7 @@ var AgentManager = class {
2328
2739
  }
2329
2740
  spawn(request, signal) {
2330
2741
  if (this.#closing) return Promise.reject(new Error("Fabric agent manager is closing"));
2742
+ if (request.queue === true) return this.#spawnQueued(request);
2331
2743
  const pending = this.#spawn(request, signal);
2332
2744
  this.#spawns.add(pending);
2333
2745
  void pending.then(() => this.#spawns.delete(pending), () => this.#spawns.delete(pending));
@@ -2349,7 +2761,73 @@ var AgentManager = class {
2349
2761
  childThinkingBounds(requested) {
2350
2762
  return childThinkingBounds(this.#thinkingBounds?.() ?? {}, requested);
2351
2763
  }
2352
- async #spawn(request, signal) {
2764
+ /**
2765
+ * Validate now, return a queued handle, and launch when a slot frees. The
2766
+ * caller's signal is not used: a queued run outlives the program that
2767
+ * spawned it, like a detached running one. agents.stop cancels it.
2768
+ */
2769
+ #spawnQueued(request) {
2770
+ if (request.residency === "durable") {
2771
+ return Promise.reject(new Error('queue: true is not supported with residency: "durable"'));
2772
+ }
2773
+ const id = randomUUID4().replaceAll("-", "");
2774
+ const control = new AbortController();
2775
+ return new Promise((resolve, reject) => {
2776
+ let entry;
2777
+ const launch = this.#spawn(request, void 0, {
2778
+ id,
2779
+ signal: control.signal,
2780
+ onQueued: (snapshot) => {
2781
+ let settle;
2782
+ const outcome = new Promise((done) => {
2783
+ settle = done;
2784
+ });
2785
+ entry = { ...snapshot, id, queuedAt: Date.now(), control, outcome, settle, background: false, stopRequested: false };
2786
+ this.#queued.set(id, entry);
2787
+ this.#invalidateUiList();
2788
+ resolve(this.#queuedHandle(entry));
2789
+ }
2790
+ });
2791
+ this.#spawns.add(launch);
2792
+ void launch.then(() => this.#spawns.delete(launch), () => this.#spawns.delete(launch));
2793
+ launch.then(
2794
+ () => {
2795
+ if (!entry) return;
2796
+ this.#queued.delete(id);
2797
+ const managed = this.#runs.get(id);
2798
+ if (managed && entry.background) this.#detach(managed, "queued run started detached");
2799
+ entry.settle({ launched: true });
2800
+ this.#invalidateUiList();
2801
+ },
2802
+ (error) => {
2803
+ if (!entry) {
2804
+ reject(error);
2805
+ return;
2806
+ }
2807
+ const stopped = entry.stopRequested || this.#closing;
2808
+ const message2 = entry.stopRequested ? "Agent stopped before it started" : this.#closing ? "Fabric agent manager is closing" : error instanceof Error ? error.message : String(error);
2809
+ const result = queuedResult(entry, stopped ? "stopped" : "failed", message2);
2810
+ entry.result = result;
2811
+ entry.settle({ result });
2812
+ this.#invalidateUiList();
2813
+ this.#notifyBackgroundComplete(entry, result);
2814
+ }
2815
+ );
2816
+ });
2817
+ }
2818
+ #queuedHandle(entry) {
2819
+ return {
2820
+ id: entry.id,
2821
+ name: entry.name,
2822
+ status: "queued",
2823
+ runner: entry.runner,
2824
+ ...entry.kernel ? { kernel: entry.kernel } : {},
2825
+ transport: entry.transport,
2826
+ cwd: entry.cwd,
2827
+ ...entry.model ? { model: entry.model } : {}
2828
+ };
2829
+ }
2830
+ async #spawn(request, signal, queued) {
2353
2831
  if (!this.config.enabled) throw new Error("Agents are disabled in Fabric configuration");
2354
2832
  if (this.#currentDepth >= this.config.maxDepth) {
2355
2833
  throw new Error(`Fabric agent depth limit reached (${this.config.maxDepth})`);
@@ -2366,12 +2844,16 @@ var AgentManager = class {
2366
2844
  throw new Error(`Invalid Fabric agent residency: ${String(request.residency)}`);
2367
2845
  }
2368
2846
  const runner = request.runner ?? this.config.runner;
2847
+ assertExactModelRequest({ modelMatch: request.modelMatch, runner, model: request.model });
2369
2848
  const runnerAdapter = requireAgentRunner(runner);
2370
2849
  const capabilities2 = runnerAdapter.capabilities;
2371
2850
  const hostedAdapter = runnerAdapter.kind === "hosted" ? runnerAdapter : void 0;
2372
2851
  if (request.persona && runner !== "veda") {
2373
2852
  throw new Error(`The persona option is only supported by the Veda runner, not ${runner}`);
2374
2853
  }
2854
+ if (request.childSkills && runner !== "pi" && runner !== "pi-durable") {
2855
+ throw new Error(`The skills option is supported only by the Pi runners, not ${runner}`);
2856
+ }
2375
2857
  if (request.persistSession === true && runner !== "claude") {
2376
2858
  throw new Error("persistSession is only supported by the Claude runner");
2377
2859
  }
@@ -2413,6 +2895,12 @@ var AgentManager = class {
2413
2895
  if (worktreeSetup !== void 0 && (typeof worktreeSetup !== "string" || worktreeSetup.length > 8192)) {
2414
2896
  throw new Error("worktreeSetup must be a shell command of at most 8192 characters");
2415
2897
  }
2898
+ if (request.holdQuestions !== void 0) {
2899
+ if (request.holdQuestions !== true) throw new Error("holdQuestions must be true when given");
2900
+ if (this.config.childQuestions !== "route" || !capabilities2.questions) {
2901
+ throw new Error('holdQuestions requires agents.childQuestions "route" and a runner that declares questions');
2902
+ }
2903
+ }
2416
2904
  const scope = launchScope(request.scope, request.inheritedScope);
2417
2905
  checkedTraceContext(request);
2418
2906
  const thinkingBounds = this.childThinkingBounds(request.thinkingBounds);
@@ -2433,53 +2921,73 @@ var AgentManager = class {
2433
2921
  }
2434
2922
  if (model && runnerAdapter.normalizeModel) model = await runnerAdapter.normalizeModel(model);
2435
2923
  }
2436
- if (this.#budget) {
2924
+ const checkBudget = () => {
2925
+ if (!this.#budget) return;
2437
2926
  const spent = readBudgetLedger(this.#budget.file).cost;
2438
- if (spent >= this.#budget.budget) {
2927
+ if (!budgetAdmits(spent, this.#budget.budget)) {
2439
2928
  throw new Error(
2440
2929
  `Fabric recursion budget exceeded: spent $${spent.toFixed(6)} of $${this.#budget.budget.toFixed(6)}. Increase agents.budgetUsd or simplify the task.`
2441
2930
  );
2442
2931
  }
2443
- }
2444
- const admissionSignal = signal ? AbortSignal.any([signal, this.#closeAbort.signal]) : this.#closeAbort.signal;
2932
+ };
2933
+ checkBudget();
2934
+ const callerSignal = queued?.signal ?? signal;
2935
+ const admissionSignal = callerSignal ? AbortSignal.any([callerSignal, this.#closeAbort.signal]) : this.#closeAbort.signal;
2936
+ queued?.onQueued({
2937
+ name: runName(request),
2938
+ task: request.task,
2939
+ runner,
2940
+ ...kernel ? { kernel } : {},
2941
+ transport: hostedAdapter ? "hosted" : request.transport ?? this.config.transport,
2942
+ cwd: selectedCwd,
2943
+ ...model ? { model } : {}
2944
+ });
2445
2945
  const release = await this.#semaphore.acquire("native", admissionSignal);
2446
2946
  try {
2447
- if (runner === "pi" || runner === "pi-durable") model = await this.#prepareModel(model);
2947
+ if (runner === "pi" || runner === "pi-durable") model = await this.#prepareModel(model, request.modelMatch);
2948
+ queued?.signal.throwIfAborted();
2448
2949
  if (this.#closing) throw new Error("Fabric agent manager is closing");
2950
+ checkBudget();
2449
2951
  this.#semaphore.admit(this.#currentDepth + 1);
2450
2952
  } catch (error) {
2451
2953
  release();
2452
2954
  throw error;
2453
2955
  }
2454
- const id = randomUUID5().replaceAll("-", "");
2956
+ const id = queued?.id ?? randomUUID4().replaceAll("-", "");
2455
2957
  const name = runName(request);
2456
- const runDirectory = path12.join(this.#runRoot, id);
2457
- fs11.mkdirSync(runDirectory, { recursive: true });
2958
+ const runDirectory = path13.join(this.#runRoot, id);
2959
+ const durableSession = runner === "pi-durable" && this.config.durableWorkerSession === true;
2960
+ const taskFile = path13.join(runDirectory, "task.txt");
2961
+ const statusFile = path13.join(runDirectory, "status.json");
2962
+ const lifecycleFile = path13.join(runDirectory, "lifecycle.jsonl");
2963
+ const logFile = path13.join(runDirectory, "events.jsonl");
2964
+ const steerFile = path13.join(runDirectory, "steer.jsonl");
2965
+ const schemaFile = request.schema ? path13.join(runDirectory, "schema.json") : void 0;
2966
+ const imagesFile = request.images && request.images.length > 0 ? path13.join(runDirectory, "images.json") : void 0;
2967
+ try {
2968
+ fs12.mkdirSync(runDirectory, durableSession ? { recursive: true, mode: 448 } : { recursive: true });
2969
+ fs12.writeFileSync(taskFile, request.task, { encoding: "utf8", mode: 384 });
2970
+ if (imagesFile) {
2971
+ fs12.writeFileSync(imagesFile, JSON.stringify(request.images), {
2972
+ encoding: "utf8",
2973
+ mode: 384
2974
+ });
2975
+ }
2976
+ if (schemaFile) {
2977
+ fs12.writeFileSync(schemaFile, JSON.stringify(request.schema, null, 2), {
2978
+ encoding: "utf8",
2979
+ mode: 384
2980
+ });
2981
+ }
2982
+ } catch (error) {
2983
+ release();
2984
+ throw error;
2985
+ }
2458
2986
  if (this.#managedTempRoot && !this.#retentionTimer) {
2459
2987
  this.#retentionTimer = setInterval(() => this.#scheduleRetentionSweep(), RETENTION_SWEEP_INTERVAL_MS);
2460
2988
  this.#retentionTimer.unref();
2461
2989
  this.#scheduleRetentionSweep();
2462
2990
  }
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
2991
  let agentCwd = selectedCwd;
2484
2992
  let branch;
2485
2993
  let worktree;
@@ -2495,7 +3003,9 @@ var AgentManager = class {
2495
3003
  }
2496
3004
  }
2497
3005
  try {
3006
+ admissionSignal.throwIfAborted();
2498
3007
  if (worktree && worktreeSetup?.trim()) await this.#worktrees.setup(id, worktreeSetup);
3008
+ admissionSignal.throwIfAborted();
2499
3009
  const writePolicy = capabilities2.writePolicy ? resolveChildWritePolicy(request, this.#parentWritePolicy, agentCwd) : void 0;
2500
3010
  const parentSessionId = this.#sessionId?.();
2501
3011
  const parentRunId = this.#parentLineage?.runId ?? (this.#currentDepth > 0 ? process.env.PI_FABRIC_PARENT_RUN : void 0);
@@ -2509,13 +3019,17 @@ var AgentManager = class {
2509
3019
  childIndex: this.#childIndex++,
2510
3020
  worker: true
2511
3021
  };
2512
- const sessionFile = request.forkSeed ? writeForkSession(request.forkSeed, agentCwd, path12.join(runDirectory, "fork-session"), request.thinkingTransfer) : request.sessionSeed ? writeHandoffSession(
3022
+ const seedOptions = durableSession ? { workerRole: true } : {};
3023
+ const handoffBudget = request.sessionSeed && request.handoffCompact ? await this.#resolveHandoffCompactionBudget?.(model, agentCwd) : void 0;
3024
+ admissionSignal.throwIfAborted();
3025
+ const sessionFile = request.forkSeed ? writeForkSession(request.forkSeed, agentCwd, path13.join(runDirectory, "fork-session"), request.thinkingTransfer, seedOptions) : request.sessionSeed ? writeHandoffSession(
2513
3026
  request.sessionSeed,
2514
3027
  agentCwd,
2515
- path12.join(runDirectory, "handoff-session"),
3028
+ path13.join(runDirectory, "handoff-session"),
2516
3029
  request.thinkingTransfer,
2517
3030
  request.handoffCompact,
2518
- request.handoffCompact ? await this.#resolveHandoffCompactionBudget?.(model, agentCwd) : void 0
3031
+ handoffBudget,
3032
+ seedOptions
2519
3033
  ) : request.sessionFile;
2520
3034
  const timeoutMs = effectiveAgentTimeoutMs(
2521
3035
  this.config.timeoutMs,
@@ -2530,7 +3044,7 @@ var AgentManager = class {
2530
3044
  const inheritedSessionPins = (runner === "pi" || runner === "pi-durable") && extensions ? this.#inheritedSessionPins(request) : void 0;
2531
3045
  const inheritedFullCodeMode = capabilities2.recursiveFabric && this.#fullCodeMode && extensions;
2532
3046
  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;
3047
+ const systemPrompt = [request.systemPrompt?.trim(), request.childSkills?.preload, componentGuidance].filter((section) => Boolean(section)).join("\n\n") || void 0;
2534
3048
  const sessionExportDir = resolveSessionExportDir(this.config);
2535
3049
  const sessionExportFile = sessionExportDir ? sessionExportFileFor(sessionExportDir, agentCwd, id, /* @__PURE__ */ new Date()) : void 0;
2536
3050
  const traceContext = this.#traceContext(request, { runId: id, runner, name });
@@ -2563,7 +3077,7 @@ var AgentManager = class {
2563
3077
  return await this.#startHosted(hostedAdapter, launchContext, {
2564
3078
  request,
2565
3079
  release,
2566
- signal,
3080
+ signal: callerSignal,
2567
3081
  timeoutMs,
2568
3082
  files: { statusFile, lifecycleFile, logFile },
2569
3083
  ...clampedFrom ? { requestedThinking: clampedFrom } : {},
@@ -2572,6 +3086,7 @@ var AgentManager = class {
2572
3086
  });
2573
3087
  }
2574
3088
  const adapter = await this.#resolveTransport(request.transport ?? this.config.transport);
3089
+ admissionSignal.throwIfAborted();
2575
3090
  const workerArguments = [
2576
3091
  "--id",
2577
3092
  id,
@@ -2624,10 +3139,14 @@ var AgentManager = class {
2624
3139
  ...thinking ? ["--thinking", thinking] : [],
2625
3140
  ...serializedThinkingBounds ? ["--thinking-bounds", serializedThinkingBounds] : [],
2626
3141
  ...systemPrompt ? ["--system-prompt", systemPrompt] : [],
3142
+ ...request.childSkills ? ["--skills", JSON.stringify(request.childSkills.catalog)] : [],
2627
3143
  "--persist-session",
2628
3144
  String(request.persistSession === true),
3145
+ ...durableSession ? ["--durable-session", "true"] : [],
2629
3146
  "--model-admission",
2630
- this.config.modelAdmission ?? "strict",
3147
+ // An exact request is always strict: permissive admission accepts another model.
3148
+ request.modelMatch === "exact" ? "strict" : this.config.modelAdmission ?? "strict",
3149
+ ...request.modelMatch === "exact" ? ["--model-match", "exact"] : [],
2631
3150
  ...sessionFile ? ["--session-file", sessionFile] : [],
2632
3151
  ...sessionExportFile ? ["--session-export-file", sessionExportFile] : [],
2633
3152
  ...inheritedSessionPins && inheritedSessionPins.length > 0 ? ["--inherited-session-pins", serializeInheritedSessionPins(inheritedSessionPins)] : [],
@@ -2642,10 +3161,14 @@ var AgentManager = class {
2642
3161
  ...this.#identityId ? ["--owner-identity-id", this.#identityId] : [],
2643
3162
  ...request.runnerSessionId ? ["--runner-session-id", request.runnerSessionId] : [],
2644
3163
  "--run-root",
2645
- path12.join(runDirectory, "nested"),
3164
+ path13.join(runDirectory, "nested"),
2646
3165
  "--steer-file",
2647
3166
  steerFile,
2648
- ...this.config.childQuestions === "route" && capabilities2.questions ? ["--child-questions", String(this.config.childQuestionTimeoutMs ?? DEFAULT_CHILD_QUESTION_TIMEOUT_MS)] : [],
3167
+ ...this.config.childQuestions === "route" && capabilities2.questions ? [
3168
+ "--child-questions",
3169
+ String(this.config.childQuestionTimeoutMs ?? DEFAULT_CHILD_QUESTION_TIMEOUT_MS),
3170
+ ...request.holdQuestions === true ? ["--child-questions-hold", "1"] : []
3171
+ ] : [],
2649
3172
  ...schemaFile ? ["--schema-file", schemaFile] : [],
2650
3173
  ...branch ? ["--branch", branch] : [],
2651
3174
  ...worktree ? ["--worktree", worktree] : [],
@@ -2678,10 +3201,12 @@ var AgentManager = class {
2678
3201
  workerPath: runnerLaunch.workerPath,
2679
3202
  workerArguments: [...runnerLaunch.workerArguments]
2680
3203
  };
3204
+ admissionSignal.throwIfAborted();
2681
3205
  if (this.#closing) throw new Error("Fabric agent manager is closing");
3206
+ const recoveryPolicy = this.config.durableWorkerRecovery === true && residency === "durable" && runner === "pi-durable" && adapter.kind === "process" && process.platform !== "win32" ? this.#workerRecoveryPolicy() : void 0;
2682
3207
  const transport = await this.#launchTransport(adapter, launch);
2683
3208
  const lifecycle = createAgentLifecycle(release);
2684
- if (signal?.aborted || this.#closing) {
3209
+ if (admissionSignal.aborted || this.#closing) {
2685
3210
  await transport.stop();
2686
3211
  if (!await transport.isAlive().catch(() => true)) this.#unregisteredTransports.delete(transport);
2687
3212
  throw new Error("Agent launch aborted");
@@ -2706,9 +3231,11 @@ var AgentManager = class {
2706
3231
  launch,
2707
3232
  startupAttempts: 1,
2708
3233
  ...lifecycle,
2709
- abortSignal: signal,
3234
+ abortSignal: callerSignal,
2710
3235
  abortHandler: void 0,
2711
3236
  ...model ? { model } : {},
3237
+ ...request.modelMatch ? { modelMatch: request.modelMatch } : {},
3238
+ ...request.holdQuestions === true ? { holdQuestions: true } : {},
2712
3239
  ...thinking ? { thinking } : {},
2713
3240
  ...clampedFrom ? { requestedThinking: clampedFrom } : {},
2714
3241
  ...request.actorId ? { actorId: request.actorId } : {},
@@ -2731,18 +3258,29 @@ var AgentManager = class {
2731
3258
  },
2732
3259
  usageEmitted: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 }
2733
3260
  };
2734
- if (signal) {
3261
+ if (callerSignal) {
2735
3262
  managed.abortHandler = () => this.#handleCallerAbort(id);
2736
- signal.addEventListener("abort", managed.abortHandler, { once: true });
3263
+ callerSignal.addEventListener("abort", managed.abortHandler, { once: true });
2737
3264
  }
2738
3265
  this.#runs.set(id, managed);
2739
3266
  this.#unregisteredTransports.delete(transport);
3267
+ if (recoveryPolicy !== void 0) {
3268
+ managed.workerRecovery = { deadlineAt: Date.now() + timeoutMs, policy: recoveryPolicy };
3269
+ this.#persistWorkerRecovery(managed);
3270
+ }
2740
3271
  this.#invalidateUiList();
2741
3272
  void this.#monitor(managed, timeoutMs);
2742
3273
  return this.#handleInfo(managed, "running");
2743
3274
  } catch (error) {
2744
3275
  release();
2745
- if (worktree) await this.#worktrees.cleanup(id, true).catch(() => false);
3276
+ if (worktree) {
3277
+ const lease = this.#worktrees.get(id);
3278
+ try {
3279
+ await this.#worktrees.cleanup(id, true);
3280
+ } catch (cleanupError) {
3281
+ throw worktreeRollbackError(lease?.gitRoot ?? selectedCwd, worktree, branch, error, cleanupError);
3282
+ }
3283
+ }
2746
3284
  throw error;
2747
3285
  }
2748
3286
  }
@@ -2775,9 +3313,9 @@ var AgentManager = class {
2775
3313
  const hosted = await HostedRun.prepare(
2776
3314
  adapter,
2777
3315
  { ...context, idempotencyKey: context.id },
2778
- { ...launch.files, stateFile: path12.join(context.runDirectory, HOSTED_STATE_FILE) },
3316
+ { ...launch.files, stateFile: path13.join(context.runDirectory, HOSTED_STATE_FILE) },
2779
3317
  record,
2780
- this.#hostedHooks(() => managed)
3318
+ this.#hostedHooks(() => managed, launch.request.holdQuestions === true)
2781
3319
  );
2782
3320
  if (launch.signal?.aborted || this.#closing) {
2783
3321
  hosted.abandon("Agent launch aborted before the hosted run was submitted");
@@ -2793,13 +3331,14 @@ var AgentManager = class {
2793
3331
  void this.#monitor(managed, launch.timeoutMs);
2794
3332
  return this.#handleInfo(managed, "running");
2795
3333
  }
2796
- #hostedHooks(managed) {
3334
+ #hostedHooks(managed, holdQuestions = false) {
2797
3335
  return {
2798
3336
  questionTimeoutMs: this.config.childQuestionTimeoutMs ?? DEFAULT_CHILD_QUESTION_TIMEOUT_MS,
3337
+ ...holdQuestions ? { holdQuestions: true } : {},
2799
3338
  ...this.config.childQuestions === "route" && this.#onChildQuestion ? {
2800
- ask: (question) => {
3339
+ ask: (question, onDecision) => {
2801
3340
  const run = managed();
2802
- return run ? this.#askParent(run, question) : Promise.resolve({ cancelled: true });
3341
+ return run ? this.#askParent(run, question, onDecision) : Promise.resolve({ cancelled: true });
2803
3342
  }
2804
3343
  } : {}
2805
3344
  };
@@ -2835,6 +3374,7 @@ var AgentManager = class {
2835
3374
  ...options.requestedThinking ? { requestedThinking: options.requestedThinking } : {},
2836
3375
  ...record.branch ? { branch: record.branch } : {},
2837
3376
  ...record.worktree ? { worktree: record.worktree } : {},
3377
+ ...hosted.hooks.holdQuestions ? { holdQuestions: true } : {},
2838
3378
  settled: false,
2839
3379
  background: recovered,
2840
3380
  lastLivenessCheckAt: 0,
@@ -2860,17 +3400,17 @@ var AgentManager = class {
2860
3400
  async recoverHostedRuns() {
2861
3401
  let entries;
2862
3402
  try {
2863
- entries = fs11.readdirSync(this.#runRoot);
3403
+ entries = fs12.readdirSync(this.#runRoot);
2864
3404
  } catch {
2865
3405
  return [];
2866
3406
  }
2867
3407
  const recovered = [];
2868
3408
  for (const entry of entries) {
2869
3409
  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");
3410
+ const runDirectory = path13.join(this.#runRoot, entry);
3411
+ const statusFile = path13.join(runDirectory, "status.json");
2872
3412
  const record = readRecord(statusFile);
2873
- const state = readHostedRunState(path12.join(runDirectory, HOSTED_STATE_FILE));
3413
+ const state = readHostedRunState(path13.join(runDirectory, HOSTED_STATE_FILE));
2874
3414
  if (!record?.hosted || !state || record.id !== entry || state.context.id !== entry || terminalStatuses.has(record.status)) {
2875
3415
  continue;
2876
3416
  }
@@ -2902,12 +3442,12 @@ var AgentManager = class {
2902
3442
  state,
2903
3443
  {
2904
3444
  statusFile,
2905
- lifecycleFile: path12.join(runDirectory, "lifecycle.jsonl"),
2906
- logFile: path12.join(runDirectory, "events.jsonl"),
2907
- stateFile: path12.join(runDirectory, HOSTED_STATE_FILE)
3445
+ lifecycleFile: path13.join(runDirectory, "lifecycle.jsonl"),
3446
+ logFile: path13.join(runDirectory, "events.jsonl"),
3447
+ stateFile: path13.join(runDirectory, HOSTED_STATE_FILE)
2908
3448
  },
2909
3449
  record,
2910
- this.#hostedHooks(() => managed)
3450
+ this.#hostedHooks(() => managed, state.holdQuestions === true)
2911
3451
  );
2912
3452
  managed = this.#adoptHosted(hosted, { release: () => {
2913
3453
  }, recovered: true });
@@ -2917,6 +3457,241 @@ var AgentManager = class {
2917
3457
  }
2918
3458
  return recovered;
2919
3459
  }
3460
+ #workerRecoveryPolicy() {
3461
+ return JSON.stringify({
3462
+ config: this.config,
3463
+ worker: this.#workerPath,
3464
+ pi: this.#piBinary,
3465
+ claude: this.#claudeBinary,
3466
+ veda: this.#vedaBinary,
3467
+ extension: this.#fabricExtensionPath,
3468
+ project: this.#projectRoot,
3469
+ mesh: this.#meshRoot,
3470
+ host: this.#hostId,
3471
+ identity: this.#identityId,
3472
+ depth: this.#currentDepth,
3473
+ fullCodeMode: this.#fullCodeMode,
3474
+ writePolicy: this.#parentWritePolicy,
3475
+ lineage: this.#parentLineage,
3476
+ thinkingBounds: this.#thinkingBounds?.(),
3477
+ kernel: this.#kernel(),
3478
+ pythonRuntime: this.#pythonRuntime(),
3479
+ executor: this.#executorRuntime?.(),
3480
+ inheritedTools: this.#inheritedToolAllowlist?.entries,
3481
+ // Exact fabric_exec authority is stored outside entries; pin both so
3482
+ // revoking recursion cannot reuse an otherwise identical launch receipt.
3483
+ inheritedFabricExec: this.#inheritedToolAllowlist?.fabricExec
3484
+ });
3485
+ }
3486
+ #persistWorkerRecovery(managed) {
3487
+ if (!managed.workerRecovery) return;
3488
+ if (managed.stopRequested || managed.settled) {
3489
+ removeWorkerRecovery(managed.runDirectory);
3490
+ return;
3491
+ }
3492
+ const pid = Number(managed.transport.sessionId);
3493
+ if (!Number.isSafeInteger(pid) || pid <= 0) {
3494
+ delete managed.workerRecovery;
3495
+ removeWorkerRecovery(managed.runDirectory);
3496
+ return;
3497
+ }
3498
+ const recovery = {
3499
+ format: WORKER_RECOVERY_FORMAT,
3500
+ id: managed.id,
3501
+ runner: "pi-durable",
3502
+ deadlineAt: managed.workerRecovery.deadlineAt,
3503
+ pid,
3504
+ launch: {
3505
+ id: managed.launch.id,
3506
+ name: managed.launch.name,
3507
+ cwd: managed.launch.cwd,
3508
+ workerPath: managed.launch.workerPath,
3509
+ workerArguments: [...managed.launch.workerArguments]
3510
+ },
3511
+ writtenAt: Date.now()
3512
+ };
3513
+ authorizeWorkerRecovery(managed.runDirectory, recovery, managed.workerRecovery.policy);
3514
+ writeWorkerRecovery(managed.runDirectory, recovery);
3515
+ }
3516
+ /**
3517
+ * Re-attach opted-in pi-durable worker runs (agents.durableWorkerRecovery)
3518
+ * left unfinished under this run root by an earlier host. A verified live
3519
+ * worker is adopted; a dead one is relaunched on its own durable journal
3520
+ * with its progress carried over; a run whose deadline passed, or whose
3521
+ * worker Fabric cannot verify either way, settles failed with outcome
3522
+ * "indeterminate" instead of being guessed at.
3523
+ */
3524
+ async recoverWorkerRuns() {
3525
+ let entries;
3526
+ try {
3527
+ entries = fs12.readdirSync(this.#runRoot);
3528
+ } catch {
3529
+ return [];
3530
+ }
3531
+ const recovered = [];
3532
+ for (const entry of entries) {
3533
+ if (this.#closing || this.#runs.has(entry) || !/^[0-9a-f]{32}$/.test(entry)) continue;
3534
+ const runDirectory = path13.join(this.#runRoot, entry);
3535
+ const recovery = readWorkerRecovery(runDirectory);
3536
+ const statusFile = path13.join(runDirectory, "status.json");
3537
+ const record = readRecord(statusFile);
3538
+ if (!recovery || recovery.id !== entry) {
3539
+ if (!hasWorkerRecovery(runDirectory)) continue;
3540
+ removeWorkerRecovery(runDirectory);
3541
+ if (record?.id === entry && !record.hosted && (!terminalStatuses.has(record.status) || record.status === "stopped")) {
3542
+ const { currentTool: _tool, blockedOn: _blocked, sleeping: _sleeping, ...rest } = record;
3543
+ const now2 = Date.now();
3544
+ writeRecord(statusFile, {
3545
+ ...rest,
3546
+ status: "failed",
3547
+ outcome: "indeterminate",
3548
+ error: "Invalid durable worker recovery marker; the run outcome is indeterminate",
3549
+ updatedAt: now2,
3550
+ finishedAt: now2
3551
+ });
3552
+ }
3553
+ continue;
3554
+ }
3555
+ if (!record || record.id !== entry) {
3556
+ const now2 = Date.now();
3557
+ removeWorkerRecovery(runDirectory);
3558
+ writeRecord(statusFile, {
3559
+ id: entry,
3560
+ name: recovery.launch.name,
3561
+ task: "",
3562
+ runner: "pi-durable",
3563
+ cwd: recovery.launch.cwd,
3564
+ residency: "durable",
3565
+ transport: "process",
3566
+ status: "failed",
3567
+ outcome: "indeterminate",
3568
+ error: "Durable worker recovery has no valid initial status; the run outcome is indeterminate",
3569
+ startedAt: recovery.writtenAt,
3570
+ updatedAt: now2,
3571
+ finishedAt: now2,
3572
+ turns: 0,
3573
+ toolCalls: 0,
3574
+ text: "",
3575
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 }
3576
+ });
3577
+ continue;
3578
+ }
3579
+ if (record.hosted) continue;
3580
+ if (terminalStatuses.has(record.status) && record.status !== "stopped") {
3581
+ removeWorkerRecovery(runDirectory);
3582
+ continue;
3583
+ }
3584
+ const now = Date.now();
3585
+ const indeterminate = (reason) => {
3586
+ const { currentTool: _tool, blockedOn: _blocked, sleeping: _sleeping, ...rest } = record;
3587
+ removeWorkerRecovery(runDirectory);
3588
+ writeRecord(statusFile, {
3589
+ ...rest,
3590
+ status: "failed",
3591
+ error: `${reason}; the run outcome is indeterminate`,
3592
+ outcome: "indeterminate",
3593
+ finishedAt: now,
3594
+ updatedAt: now
3595
+ });
3596
+ };
3597
+ const runnerAdapter = getAgentRunner("pi-durable");
3598
+ if (runnerAdapter?.kind !== "worker") {
3599
+ indeterminate("The pi-durable runner is not registered in this process");
3600
+ continue;
3601
+ }
3602
+ const policy = this.#workerRecoveryPolicy();
3603
+ const authority = readWorkerRecoveryAuthority(runDirectory, policy);
3604
+ if (!authority || workerRecoveryMismatch(recovery, { runDirectory, workerPath: this.#workerPath, cwd: record.cwd, policy })) {
3605
+ indeterminate("The recovery file does not match this host");
3606
+ continue;
3607
+ }
3608
+ if (authority.deadlineAt <= now) {
3609
+ indeterminate("The durable worker run passed its deadline while no resident host owned it");
3610
+ continue;
3611
+ }
3612
+ let liveness = probeWorker(authority.pid, entry);
3613
+ if (record.status === "stopped" && liveness === "alive") {
3614
+ liveness = await this.#waitForWorkerExit(authority.pid, entry);
3615
+ if (liveness === "alive") {
3616
+ indeterminate(`Worker process ${recovery.pid} recorded a stop but did not exit`);
3617
+ continue;
3618
+ }
3619
+ }
3620
+ if (liveness === "unknown") {
3621
+ indeterminate(`Fabric cannot verify whether worker process ${recovery.pid} is still running`);
3622
+ continue;
3623
+ }
3624
+ if (liveness === "dead" && !fs12.existsSync(authority.launch.workerPath)) {
3625
+ indeterminate(`The worker entry ${recovery.launch.workerPath} no longer exists`);
3626
+ continue;
3627
+ }
3628
+ const argument = (name) => {
3629
+ const index = authority.launch.workerArguments.indexOf(`--${name}`);
3630
+ return index < 0 ? void 0 : authority.launch.workerArguments[index + 1];
3631
+ };
3632
+ const kernel = argument("kernel");
3633
+ const model = argument("model");
3634
+ const thinking = argument("thinking");
3635
+ const branch = argument("branch");
3636
+ const worktree = argument("worktree");
3637
+ const adapter = await this.#resolveTransport("process");
3638
+ const managed = {
3639
+ id: entry,
3640
+ name: record.name,
3641
+ task: record.task,
3642
+ runner: "pi-durable",
3643
+ runnerAdapter,
3644
+ ...kernel === "typescript" || kernel === "python" ? { kernel } : {},
3645
+ recursive: JSON.parse(argument("granted-risks") ?? "[]").includes("agent"),
3646
+ residency: "durable",
3647
+ cwd: record.cwd,
3648
+ statusFile,
3649
+ lifecycleFile: path13.join(runDirectory, "lifecycle.jsonl"),
3650
+ // Events before this point reached the previous host's ledger.
3651
+ lifecycleOffset: fileSize(path13.join(runDirectory, "lifecycle.jsonl")),
3652
+ lifecycleRemainder: Buffer.alloc(0),
3653
+ runDirectory,
3654
+ transport: adoptedWorkerHandle(authority.pid, entry),
3655
+ adapter,
3656
+ launch: authority.launch,
3657
+ startupAttempts: 1,
3658
+ ...createAgentLifecycle(() => {
3659
+ }),
3660
+ abortSignal: void 0,
3661
+ abortHandler: void 0,
3662
+ ...model ? { model } : {},
3663
+ ...thinking ? { thinking } : {},
3664
+ ...branch ? { branch } : {},
3665
+ ...worktree ? { worktree } : {},
3666
+ workerRecovery: { deadlineAt: authority.deadlineAt, policy },
3667
+ settled: false,
3668
+ background: true,
3669
+ lastLivenessCheckAt: 0,
3670
+ resumeAttempts: 0,
3671
+ stopRequested: false,
3672
+ observedProgress: { turns: record.turns, toolCalls: record.toolCalls, usage: { ...record.usage } },
3673
+ usageEmitted: { ...record.usage }
3674
+ };
3675
+ this.#runs.set(entry, managed);
3676
+ this.#invalidateUiList();
3677
+ if (liveness === "dead") {
3678
+ managed.resumeAttempts += 1;
3679
+ const { turns, toolCalls, usage } = managed.observedProgress;
3680
+ const relaunched = await this.#relaunch(managed, record, {
3681
+ task: managed.task,
3682
+ carryOver: { turns, toolCalls, usage: { ...usage } }
3683
+ });
3684
+ if (!relaunched) {
3685
+ const failed = readRecord(statusFile) ?? record;
3686
+ this.#settle(managed, this.#withTransportMetadata(failed, managed));
3687
+ continue;
3688
+ }
3689
+ }
3690
+ void this.#monitor(managed, Math.max(0, recovery.deadlineAt - Date.now()));
3691
+ recovered.push(entry);
3692
+ }
3693
+ return recovered;
3694
+ }
2920
3695
  /** Park or resume a hosted run whose runner declares `sleep`. */
2921
3696
  async sleep(id) {
2922
3697
  await this.#requireHosted(id, "sleep").park("sleep");
@@ -2934,6 +3709,15 @@ var AgentManager = class {
2934
3709
  return this.wait(handle.id);
2935
3710
  }
2936
3711
  async wait(id) {
3712
+ const queued = this.#queued.get(id);
3713
+ if (queued) {
3714
+ queued.background = false;
3715
+ const outcome = await queued.outcome;
3716
+ if ("result" in outcome) {
3717
+ this.#onResultConsumed?.(id);
3718
+ return structuredClone(outcome.result);
3719
+ }
3720
+ }
2937
3721
  const managed = this.#requireRun(id);
2938
3722
  managed.background = false;
2939
3723
  if (!managed.settled) {
@@ -2942,7 +3726,7 @@ var AgentManager = class {
2942
3726
  this.#onResultConsumed?.(id);
2943
3727
  return result;
2944
3728
  }
2945
- const record = readRecord(managed.statusFile) ?? managed.latestRecord;
3729
+ const record = this.#readManagedRecord(managed);
2946
3730
  if (!record || !terminalStatuses.has(record.status)) {
2947
3731
  throw new Error(`Agent ${id} settled without a result`);
2948
3732
  }
@@ -2950,10 +3734,18 @@ var AgentManager = class {
2950
3734
  return this.#withTransportMetadata(record, managed);
2951
3735
  }
2952
3736
  markForeground(id) {
2953
- this.#requireRun(id).background = false;
3737
+ const queued = this.#runs.has(id) ? void 0 : this.#queued.get(id);
3738
+ if (queued) queued.background = false;
3739
+ else this.#requireRun(id).background = false;
2954
3740
  this.#onResultConsumed?.(id);
2955
3741
  }
2956
3742
  detachSignal(id) {
3743
+ const queued = this.#queued.get(id);
3744
+ if (queued) {
3745
+ queued.background = true;
3746
+ if (queued.result) this.#notifyBackgroundComplete(queued, queued.result);
3747
+ return;
3748
+ }
2957
3749
  this.#detach(this.#requireRun(id), "caller detached; the run continues");
2958
3750
  }
2959
3751
  /**
@@ -2982,7 +3774,7 @@ var AgentManager = class {
2982
3774
  if (managed.background) return;
2983
3775
  managed.background = true;
2984
3776
  if (managed.settled) {
2985
- const record = readRecord(managed.statusFile) ?? managed.latestRecord;
3777
+ const record = this.#readManagedRecord(managed);
2986
3778
  if (record && terminalStatuses.has(record.status)) {
2987
3779
  this.#notifyBackgroundComplete(managed, this.#withTransportMetadata(record, managed));
2988
3780
  }
@@ -3010,9 +3802,17 @@ var AgentManager = class {
3010
3802
  if (record.usage[key] > seen.usage[key]) seen.usage[key] = record.usage[key];
3011
3803
  }
3012
3804
  }
3805
+ #readManagedRecord(managed) {
3806
+ if (managed.settled && !managed.hosted && managed.unpersistedResult) {
3807
+ return managed.unpersistedResult;
3808
+ }
3809
+ return managed.settled ? readRecord(managed.statusFile) ?? managed.latestRecord : managed.latestRecord ?? readRecord(managed.statusFile);
3810
+ }
3013
3811
  status(id) {
3812
+ const queued = this.#runs.has(id) ? void 0 : this.#queued.get(id);
3813
+ if (queued) return queued.result ? structuredClone(queued.result) : this.#queuedHandle(queued);
3014
3814
  const managed = this.#requireRun(id);
3015
- const record = managed.settled ? readRecord(managed.statusFile) ?? managed.latestRecord : managed.latestRecord ?? readRecord(managed.statusFile);
3815
+ const record = this.#readManagedRecord(managed);
3016
3816
  if (!record) return this.#handleInfo(managed, "running");
3017
3817
  managed.latestRecord = record;
3018
3818
  if (!managed.latestUiRecord) {
@@ -3024,7 +3824,18 @@ var AgentManager = class {
3024
3824
  return result;
3025
3825
  }
3026
3826
  list() {
3027
- return [...this.#runs.keys()].map((id) => this.status(id));
3827
+ return [.../* @__PURE__ */ new Set([...this.#runs.keys(), ...this.#queued.keys()])].map((id) => this.status(id));
3828
+ }
3829
+ /** Unsettled runs, each with the title of a child question it waits on. */
3830
+ activity() {
3831
+ return [
3832
+ ...[...this.#runs.values()].filter((managed) => !managed.settled).map((managed) => ({
3833
+ id: managed.id,
3834
+ name: managed.actorName ?? managed.name,
3835
+ ...managed.openQuestions?.length ? { question: managed.openQuestions.at(-1).title } : {}
3836
+ })),
3837
+ ...[...this.#queued.values()].filter((queued) => !queued.result && !this.#runs.has(queued.id)).map((queued) => ({ id: queued.id, name: queued.name }))
3838
+ ];
3028
3839
  }
3029
3840
  listForUi() {
3030
3841
  if (this.#uiListCache?.revision === this.#uiListRevision) {
@@ -3039,7 +3850,7 @@ var AgentManager = class {
3039
3850
  const value = runs.filter((managed) => visible.has(managed)).map((managed) => {
3040
3851
  let record = managed.latestUiRecord;
3041
3852
  if (!record) {
3042
- const latest = managed.latestRecord ?? readRecord(managed.statusFile);
3853
+ const latest = managed.latestRecord ?? this.#readManagedRecord(managed);
3043
3854
  if (!latest) return this.#handleInfo(managed, "running");
3044
3855
  managed.latestRecord = latest;
3045
3856
  record = compactUiRecord(latest);
@@ -3049,6 +3860,11 @@ var AgentManager = class {
3049
3860
  compactUiRecord(this.#withTransportMetadata(record, managed))
3050
3861
  );
3051
3862
  });
3863
+ for (const queued of this.#queued.values()) {
3864
+ if (!this.#runs.has(queued.id)) {
3865
+ value.push(queued.result ? compactUiRecord(structuredClone(queued.result)) : this.#queuedHandle(queued));
3866
+ }
3867
+ }
3052
3868
  this.#uiListCache = { revision: this.#uiListRevision, value };
3053
3869
  return value;
3054
3870
  }
@@ -3068,8 +3884,17 @@ var AgentManager = class {
3068
3884
  return structuredClone(value);
3069
3885
  }
3070
3886
  async stop(id) {
3887
+ const queued = this.#runs.has(id) ? void 0 : this.#queued.get(id);
3888
+ if (queued) {
3889
+ queued.background = false;
3890
+ queued.stopRequested = true;
3891
+ queued.control.abort();
3892
+ const outcome = await queued.outcome;
3893
+ if ("result" in outcome) return structuredClone(outcome.result);
3894
+ }
3071
3895
  const managed = this.#requireRun(id);
3072
3896
  managed.stopRequested = true;
3897
+ if (managed.workerRecovery) removeWorkerRecovery(managed.runDirectory);
3073
3898
  if (managed.settled) return this.wait(id);
3074
3899
  managed.background = false;
3075
3900
  const existing = readRecord(managed.statusFile);
@@ -3090,6 +3915,14 @@ var AgentManager = class {
3090
3915
  return record;
3091
3916
  }
3092
3917
  async cleanup(id, deleteBranch = false) {
3918
+ const queued = this.#runs.has(id) ? void 0 : this.#queued.get(id);
3919
+ if (queued) {
3920
+ if (!queued.result) throw new Error("Cannot clean up a queued agent; stop it first");
3921
+ this.#onResultConsumed?.(id);
3922
+ this.#queued.delete(id);
3923
+ this.#invalidateUiList();
3924
+ return { cleaned: true };
3925
+ }
3093
3926
  const managed = this.#requireRun(id);
3094
3927
  if (!managed.settled) throw new Error("Cannot clean up a running agent");
3095
3928
  this.markForeground(id);
@@ -3100,15 +3933,15 @@ var AgentManager = class {
3100
3933
  this.#runs.delete(id);
3101
3934
  this.#pruneRetainedUiRecords();
3102
3935
  this.#invalidateUiList();
3103
- return { cleaned: cleaned || !fs11.existsSync(managed.runDirectory) };
3936
+ return { cleaned: cleaned || !fs12.existsSync(managed.runDirectory) };
3104
3937
  }
3105
3938
  readLog(id, opts = {}) {
3106
3939
  const managed = this.#requireRun(id);
3107
3940
  const runDirectory = managed.runDirectory;
3108
- const logFile = path12.join(runDirectory, "events.jsonl");
3941
+ const logFile = path13.join(runDirectory, "events.jsonl");
3109
3942
  const lines = Math.max(1, Math.min(opts.lines ?? 200, 5e3));
3110
3943
  const page = readJsonlPage(logFile, lines, opts.before);
3111
- const statusRecord = readRecord(path12.join(runDirectory, "status.json"));
3944
+ const statusRecord = readRecord(path13.join(runDirectory, "status.json"));
3112
3945
  return {
3113
3946
  id,
3114
3947
  runDirectory,
@@ -3183,10 +4016,10 @@ var AgentManager = class {
3183
4016
  `Fabric agent ${id} already finished (${record.status}); steering has no target`
3184
4017
  );
3185
4018
  }
3186
- const steerFile = path12.join(managed.runDirectory, "steer.jsonl");
3187
- const messageId = randomUUID5();
4019
+ const steerFile = path13.join(managed.runDirectory, "steer.jsonl");
4020
+ const messageId = randomUUID4();
3188
4021
  const line = JSON.stringify({ ...entry, id: messageId, ts: Date.now() }) + "\n";
3189
- fs11.appendFileSync(steerFile, line, { encoding: "utf8", mode: 384 });
4022
+ fs12.appendFileSync(steerFile, line, { encoding: "utf8", mode: 384 });
3190
4023
  return { queued: true, messageId };
3191
4024
  }
3192
4025
  close() {
@@ -3202,14 +4035,26 @@ var AgentManager = class {
3202
4035
  const detached = [...this.#runs.values()].filter(
3203
4036
  (managed) => !managed.settled && managed.hosted && managed.residency === "durable"
3204
4037
  );
3205
- for (const managed of detached) managed.hosted.detach();
4038
+ for (const managed of detached) {
4039
+ managed.hosted.detach();
4040
+ managed.questions?.abort(new Error("Fabric resident host detached the run"));
4041
+ }
4042
+ await Promise.allSettled(detached.flatMap((managed) => [...managed.asks ?? []]));
4043
+ for (const managed of this.#runs.values()) {
4044
+ if (!managed.settled && !managed.stopRequested && managed.workerRecovery && managed.residency === "durable") {
4045
+ managed.workerDetached = true;
4046
+ detached.push(managed);
4047
+ }
4048
+ }
3206
4049
  const running = [...this.#runs.values()].filter((managed) => !managed.settled && !detached.includes(managed));
3207
4050
  for (const managed of running) managed.hosted?.markShutdown();
3208
4051
  await Promise.allSettled(running.map((managed) => this.stop(managed.id)));
3209
4052
  await Promise.allSettled([...this.#spawns]);
3210
4053
  await Promise.allSettled([...this.#launches]);
3211
4054
  const all = [...this.#runs.values()];
3212
- await Promise.allSettled(all.map((managed) => this.#waitForTransportExit(managed)));
4055
+ await Promise.allSettled(
4056
+ all.filter((managed) => !managed.workerDetached).map((managed) => this.#waitForTransportExit(managed))
4057
+ );
3213
4058
  const transports2 = [...all.map((managed) => managed.transport), ...this.#unregisteredTransports];
3214
4059
  const alive = await Promise.all(transports2.map((transport) => transport.isAlive().catch(() => true)));
3215
4060
  if (detached.length === 0 && !alive.some(Boolean)) {
@@ -3227,7 +4072,7 @@ var AgentManager = class {
3227
4072
  removeEmptyRunRoot(this.#runRoot);
3228
4073
  }
3229
4074
  if (storageSafe && this.#budgetOwned && this.#budget) {
3230
- await removeTree(path12.dirname(this.#budget.file)).catch(() => void 0);
4075
+ await removeTree(path13.dirname(this.#budget.file)).catch(() => void 0);
3231
4076
  }
3232
4077
  }
3233
4078
  if (this.#budgetOwned) clearOwnedBudgetEnv();
@@ -3263,13 +4108,13 @@ var AgentManager = class {
3263
4108
  }
3264
4109
  const expired = [...this.#runs.values()].filter((managed) => {
3265
4110
  if (!managed.settled || managed.actorId) return false;
3266
- const record = readRecord(managed.statusFile) ?? managed.latestRecord;
4111
+ const record = this.#readManagedRecord(managed);
3267
4112
  const finishedAt = record?.finishedAt ?? record?.updatedAt;
3268
4113
  return typeof finishedAt === "number" && now - finishedAt >= this.#retention.oneShotRunMs;
3269
4114
  });
3270
4115
  for (const managed of expired) {
3271
4116
  await removeTree(managed.runDirectory).catch(() => void 0);
3272
- if (!fs11.existsSync(managed.runDirectory)) this.#runs.delete(managed.id);
4117
+ if (!fs12.existsSync(managed.runDirectory)) this.#runs.delete(managed.id);
3273
4118
  }
3274
4119
  if (expired.length > 0) {
3275
4120
  this.#pruneRetainedUiRecords();
@@ -3282,6 +4127,16 @@ var AgentManager = class {
3282
4127
  if (runner.kind !== "worker" || !runner.stop) return;
3283
4128
  await Promise.resolve().then(() => runner.stop({ id: managed.id, runDirectory: managed.runDirectory })).catch(() => void 0);
3284
4129
  }
4130
+ /** Bounded like #waitForTransportExit; returns the last liveness seen. */
4131
+ async #waitForWorkerExit(pid, id) {
4132
+ const deadline = Date.now() + TRANSPORT_EXIT_GRACE_MS * 7;
4133
+ let liveness = probeWorker(pid, id);
4134
+ while (liveness === "alive" && Date.now() < deadline && !this.#closing) {
4135
+ await delay(AGENT_STATUS_POLL_INTERVAL_MS);
4136
+ liveness = probeWorker(pid, id);
4137
+ }
4138
+ return liveness;
4139
+ }
3285
4140
  async #waitForTransportExit(managed) {
3286
4141
  const deadline = Date.now() + TRANSPORT_EXIT_GRACE_MS * 7;
3287
4142
  const pollIntervalMs = managed.transport.livenessPollIntervalMs ?? AGENT_STATUS_POLL_INTERVAL_MS;
@@ -3290,7 +4145,10 @@ var AgentManager = class {
3290
4145
  }
3291
4146
  }
3292
4147
  async #retryStartup(managed, record, deadline) {
3293
- if (managed.hosted || // A custom worker that already made progress is never re-run blind.
4148
+ if (managed.hosted || // Decided first, from the exit status and the fixed prefix: no text
4149
+ // classifier below may see a pin error, because a model id can spell
4150
+ // "missing credentials".
4151
+ managed.modelMatch === "exact" && isModelPinFailure(record) || // A custom worker that already made progress is never re-run blind.
3294
4152
  !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
4153
  return false;
3296
4154
  }
@@ -3314,7 +4172,7 @@ var AgentManager = class {
3314
4172
  if (
3315
4173
  // Fabric never re-prompts a hosted run, and only its own worker
3316
4174
  // 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)
4175
+ 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
4176
  ) {
3319
4177
  return false;
3320
4178
  }
@@ -3341,7 +4199,7 @@ var AgentManager = class {
3341
4199
  async #relaunch(managed, record, resume) {
3342
4200
  try {
3343
4201
  if (managed.runner === "pi" || managed.runner === "pi-durable") {
3344
- const model = await this.#prepareModel(managed.model);
4202
+ const model = await this.#prepareModel(managed.model, managed.modelMatch);
3345
4203
  const modelIndex = managed.launch.workerArguments.indexOf("--model");
3346
4204
  if (model) {
3347
4205
  if (modelIndex >= 0) managed.launch.workerArguments[modelIndex + 1] = model;
@@ -3352,8 +4210,15 @@ var AgentManager = class {
3352
4210
  delete managed.model;
3353
4211
  }
3354
4212
  }
4213
+ if (managed.workerRecovery) {
4214
+ setWorkerArgument(
4215
+ managed.launch.workerArguments,
4216
+ "timeout-ms",
4217
+ String(Math.max(1, managed.workerRecovery.deadlineAt - Date.now()))
4218
+ );
4219
+ }
3355
4220
  if (resume) {
3356
- fs11.writeFileSync(path12.join(managed.runDirectory, "task.txt"), resume.task, {
4221
+ fs12.writeFileSync(path13.join(managed.runDirectory, "task.txt"), resume.task, {
3357
4222
  encoding: "utf8",
3358
4223
  mode: 384
3359
4224
  });
@@ -3375,10 +4240,14 @@ var AgentManager = class {
3375
4240
  }
3376
4241
  }
3377
4242
  this.#drainLifecycle(managed);
3378
- fs11.rmSync(managed.statusFile, { force: true });
3379
4243
  if (managed.settled || this.#closing || managed.stopRequested) return false;
4244
+ fs12.rmSync(managed.statusFile, { force: true });
4245
+ managed.lifecycleOffset = 0;
4246
+ managed.lifecycleRemainder = Buffer.alloc(0);
4247
+ fs12.rmSync(managed.lifecycleFile, { force: true });
3380
4248
  managed.transport = await this.#launchTransport(managed.adapter, managed.launch);
3381
4249
  this.#unregisteredTransports.delete(managed.transport);
4250
+ if (managed.workerRecovery) this.#persistWorkerRecovery(managed);
3382
4251
  if (managed.settled || this.#closing || managed.stopRequested) {
3383
4252
  await managed.transport.stop().catch(() => void 0);
3384
4253
  return false;
@@ -3386,9 +4255,6 @@ var AgentManager = class {
3386
4255
  delete managed.latestRecord;
3387
4256
  delete managed.latestUiRecord;
3388
4257
  managed.lastLivenessCheckAt = 0;
3389
- managed.lifecycleOffset = 0;
3390
- managed.lifecycleRemainder = Buffer.alloc(0);
3391
- fs11.rmSync(managed.lifecycleFile, { force: true });
3392
4258
  if (resume) {
3393
4259
  this.#emitLifecycle(managed, "run.resumed", Date.now(), {
3394
4260
  data: {
@@ -3417,11 +4283,32 @@ var AgentManager = class {
3417
4283
  return false;
3418
4284
  }
3419
4285
  }
4286
+ /**
4287
+ * Monitors start detached, so a throw here would leave the run unsettled and
4288
+ * every wait() pending forever. Settle such a run as failed instead.
4289
+ */
3420
4290
  async #monitor(managed, timeoutMs) {
4291
+ try {
4292
+ await this.#watch(managed, timeoutMs);
4293
+ } catch (error) {
4294
+ if (managed.settled) return;
4295
+ const message2 = error instanceof Error ? error.message : String(error);
4296
+ const failed = failedRecord(managed, "failed", `Agent monitor failed: ${message2}`);
4297
+ await managed.transport.stop().catch(() => void 0);
4298
+ try {
4299
+ writeRecord(managed.statusFile, failed);
4300
+ } catch {
4301
+ if (!managed.hosted) managed.unpersistedResult = failed;
4302
+ }
4303
+ this.#settle(managed, failed);
4304
+ }
4305
+ }
4306
+ async #watch(managed, timeoutMs) {
3421
4307
  const deadline = Date.now() + timeoutMs + TRANSPORT_EXIT_GRACE_MS;
3422
4308
  let firstObservedDeadAt;
3423
4309
  while (!managed.settled) {
3424
4310
  if (managed.hosted?.detached) return;
4311
+ if (managed.workerDetached) return;
3425
4312
  this.#drainLifecycle(managed);
3426
4313
  const record = readRecord(managed.statusFile);
3427
4314
  if (record) {
@@ -3527,6 +4414,7 @@ var AgentManager = class {
3527
4414
  }
3528
4415
  #settle(managed, result) {
3529
4416
  if (managed.settled) return;
4417
+ if (managed.workerRecovery) removeWorkerRecovery(managed.runDirectory);
3530
4418
  if (managed.worktreeResult) result.worktreeResult = managed.worktreeResult;
3531
4419
  const nested = this.#nestedAgents(managed, true);
3532
4420
  if (nested.length > 0) result.nestedAgents = reconcileNestedAgents(nested, result);
@@ -3534,7 +4422,10 @@ var AgentManager = class {
3534
4422
  if (!beginAgentSettlement(managed)) return;
3535
4423
  managed.questions?.abort(new Error("Agent run settled"));
3536
4424
  managed.hosted?.close();
3537
- fs11.rmSync(path12.join(managed.runDirectory, "images.json"), { force: true });
4425
+ try {
4426
+ fs12.rmSync(path13.join(managed.runDirectory, "images.json"), { force: true });
4427
+ } catch {
4428
+ }
3538
4429
  this.#emitLifecycle(managed, `run.${result.status}`, result.finishedAt ?? Date.now(), {
3539
4430
  status: result.status
3540
4431
  });
@@ -3567,7 +4458,7 @@ var AgentManager = class {
3567
4458
  #drainLifecycle(managed) {
3568
4459
  let content;
3569
4460
  try {
3570
- content = fs11.readFileSync(managed.lifecycleFile);
4461
+ content = fs12.readFileSync(managed.lifecycleFile);
3571
4462
  } catch {
3572
4463
  return;
3573
4464
  }
@@ -3617,44 +4508,58 @@ var AgentManager = class {
3617
4508
  #routeChildQuestion(managed, data) {
3618
4509
  if (typeof data !== "object" || data === null || typeof data.requestId !== "string") return;
3619
4510
  const question = data;
3620
- const respond = (response) => {
4511
+ const requestId = question.requestId;
4512
+ const steer = (command) => {
3621
4513
  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() })}
4514
+ fs12.appendFileSync(
4515
+ path13.join(managed.runDirectory, "steer.jsonl"),
4516
+ `${JSON.stringify({ ...command, id: randomUUID4(), ts: Date.now() })}
3625
4517
  `,
3626
4518
  { encoding: "utf8", mode: 384 }
3627
4519
  );
3628
4520
  } catch {
3629
4521
  }
3630
4522
  };
4523
+ const respond = (response) => steer({ type: "ui_response", requestId, ...response });
3631
4524
  if (!managed.runnerAdapter.capabilities.questions) {
3632
4525
  respond({ cancelled: true });
3633
4526
  return;
3634
4527
  }
3635
- void this.#askParent(managed, question).then((response) => {
4528
+ void this.#askParent(managed, question, (decisionId) => {
4529
+ if (!managed.settled) steer({ type: "ui_decision", requestId, decisionId });
4530
+ }).then((response) => {
3636
4531
  if (!managed.settled) respond(response);
3637
4532
  });
3638
4533
  }
3639
4534
  /** One routed dialog for a worker or hosted run; any failure cancels it. */
3640
- #askParent(managed, question) {
4535
+ #askParent(managed, question, onDecision) {
3641
4536
  if (!this.#onChildQuestion || managed.settled) return Promise.resolve({ cancelled: true });
3642
4537
  managed.questions ??= new AbortController();
3643
- return this.#onChildQuestion({
4538
+ const title = typeof question.title === "string" && question.title.trim() ? question.title.trim() : "question";
4539
+ const open = { title };
4540
+ (managed.openQuestions ??= []).push(open);
4541
+ this.#invalidateUiList();
4542
+ const asked = this.#onChildQuestion({
3644
4543
  runId: managed.id,
3645
4544
  name: managed.actorName ?? managed.name,
3646
4545
  ...managed.actorId ? { actorId: managed.actorId } : {},
4546
+ // Both sides must agree: the run asked to hold, and this question carries no deadline of its own.
4547
+ ...managed.holdQuestions && question.hold === true ? { hold: true } : {},
3647
4548
  question,
3648
4549
  signal: managed.questions.signal,
3649
4550
  onDecision: (decisionId) => {
3650
- managed.questionDecisionId = decisionId;
4551
+ open.decisionId = decisionId;
4552
+ onDecision?.(decisionId);
3651
4553
  this.#invalidateUiList();
3652
4554
  }
3653
4555
  }).catch(() => ({ cancelled: true })).then((response) => {
3654
- delete managed.questionDecisionId;
4556
+ managed.openQuestions.splice(managed.openQuestions.indexOf(open), 1);
4557
+ managed.asks?.delete(asked);
3655
4558
  this.#invalidateUiList();
3656
4559
  return response;
3657
4560
  });
4561
+ (managed.asks ??= /* @__PURE__ */ new Set()).add(asked);
4562
+ return asked;
3658
4563
  }
3659
4564
  #appendAttributedBudgetLedger(managed, tokens, cost) {
3660
4565
  if (!this.#budget || tokens <= 0 && cost <= 0) return;
@@ -3715,12 +4620,19 @@ var AgentManager = class {
3715
4620
  }
3716
4621
  #inheritedToolAllowlist = readChildToolAllowlist();
3717
4622
  #childTools(request, runner, requiresFabricKernel = false) {
3718
- const tools = [...request.tools ?? this.config.defaultTools].filter(
4623
+ const requested = request.tools ?? this.config.defaultTools;
4624
+ const nativePi = runner.id === "pi" || runner.id === "pi-durable";
4625
+ const tools = nativePi ? constrainChildToolSelection(requested, this.#inheritedToolAllowlist) : requested.filter(
3719
4626
  (tool) => tool !== "fabric_exec" && (this.#inheritedToolAllowlist === void 0 || this.#inheritedToolAllowlist.has(tool))
3720
4627
  );
3721
4628
  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");
4629
+ 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("-"))) {
4630
+ for (const tool of this.config.childQuestionTools ?? ["ask"]) {
4631
+ if (this.#inheritedToolAllowlist === void 0 || this.#inheritedToolAllowlist.has(tool)) tools.push(tool);
4632
+ }
4633
+ }
4634
+ 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)) {
4635
+ tools.push(nativePi && tools.some((tool) => tool.startsWith("+") || tool.startsWith("-")) ? "+fabric_exec" : "fabric_exec");
3724
4636
  }
3725
4637
  return [...new Set(tools)];
3726
4638
  }
@@ -3779,6 +4691,9 @@ var AgentManager = class {
3779
4691
  }
3780
4692
  #requireRun(id) {
3781
4693
  const managed = this.#runs.get(id);
4694
+ if (!managed && this.#queued.has(id)) {
4695
+ throw new Error(`Fabric agent ${id} is queued and has not started`);
4696
+ }
3782
4697
  if (!managed) throw new Error(`Unknown Fabric agent: ${id}`);
3783
4698
  return managed;
3784
4699
  }
@@ -3813,7 +4728,7 @@ var AgentManager = class {
3813
4728
  // directories. Terminal-owner reconciliation prevents cached active ghosts.
3814
4729
  #nestedAgents(managed, force = false) {
3815
4730
  const now = Date.now();
3816
- const needsInitialDiscovery = managed.nestedSnapshot === void 0 && fs11.existsSync(path12.join(managed.runDirectory, "nested"));
4731
+ const needsInitialDiscovery = managed.nestedSnapshot === void 0 && fs12.existsSync(path13.join(managed.runDirectory, "nested"));
3817
4732
  if (!force && !needsInitialDiscovery && managed.nestedSnapshotAt !== void 0 && now - managed.nestedSnapshotAt < NESTED_SNAPSHOT_POLL_MS) {
3818
4733
  return managed.nestedSnapshot ? structuredClone(managed.nestedSnapshot) : [];
3819
4734
  }
@@ -3834,13 +4749,14 @@ var AgentManager = class {
3834
4749
  const { logFile: _logFile, nestedAgents: _nestedAgents, ...safeRecord } = record;
3835
4750
  const model = record.model ?? managed.model;
3836
4751
  const thinking = record.thinking ?? managed.thinking;
4752
+ const blockingDecision = managed.openQuestions?.find((open) => open.decisionId)?.decisionId;
3837
4753
  return {
3838
4754
  ...safeRecord,
3839
4755
  cwd: managed.cwd,
3840
4756
  runner: managed.runner,
3841
4757
  ...managed.kernel ? { kernel: managed.kernel } : {},
3842
4758
  ...managed.residency === "durable" ? { residency: "durable" } : {},
3843
- logFile: path12.join(managed.runDirectory, "events.jsonl"),
4759
+ logFile: path13.join(managed.runDirectory, "events.jsonl"),
3844
4760
  ...nestedAgents.length > 0 ? { nestedAgents } : {},
3845
4761
  ...budget ? { budget } : {},
3846
4762
  ...model ? { model } : {},
@@ -3857,7 +4773,7 @@ var AgentManager = class {
3857
4773
  ...managed.branch ? { branch: managed.branch } : {},
3858
4774
  ...managed.worktree ? { worktree: managed.worktree } : {},
3859
4775
  ...managed.worktreeResult ? { worktreeResult: managed.worktreeResult } : {},
3860
- ...record.blockedOn && managed.questionDecisionId ? { blockedOn: { ...record.blockedOn, decisionId: managed.questionDecisionId } } : {}
4776
+ ...record.blockedOn && blockingDecision ? { blockedOn: { ...record.blockedOn, decisionId: blockingDecision } } : {}
3861
4777
  };
3862
4778
  }
3863
4779
  };
@@ -3896,15 +4812,15 @@ var actorDeliveryNotice = (delivery, triggerTurn) => {
3896
4812
  };
3897
4813
 
3898
4814
  // src/actors/directory.ts
3899
- import fs17 from "node:fs";
4815
+ import fs19 from "node:fs";
3900
4816
 
3901
4817
  // src/actors/manager.ts
3902
- import { randomUUID as randomUUID8 } from "node:crypto";
3903
- import fs16 from "node:fs";
4818
+ import { randomUUID as randomUUID7 } from "node:crypto";
4819
+ import fs18 from "node:fs";
3904
4820
 
3905
4821
  // src/actors/mesh-monitor.ts
3906
- import fs12 from "node:fs";
3907
- import path13 from "node:path";
4822
+ import fs13 from "node:fs";
4823
+ import path14 from "node:path";
3908
4824
  var MESH_WATCH_RECONCILE_MS = 2e3;
3909
4825
  var ActorMeshMonitor = class {
3910
4826
  constructor(mesh, config, callbacks) {
@@ -3931,8 +4847,8 @@ var ActorMeshMonitor = class {
3931
4847
  return;
3932
4848
  }
3933
4849
  try {
3934
- const watcher = fs12.watch(this.mesh.root, { persistent: false }, (_event, filename) => {
3935
- const name = filename == null ? void 0 : path13.basename(filename.toString());
4850
+ const watcher = fs13.watch(this.mesh.root, { persistent: false }, (_event, filename) => {
4851
+ const name = filename == null ? void 0 : path14.basename(filename.toString());
3936
4852
  if (name !== void 0 && name !== "events.jsonl" && name !== "schedules.json") return;
3937
4853
  this.schedule();
3938
4854
  });
@@ -3986,7 +4902,10 @@ var ActorMeshMonitor = class {
3986
4902
  }
3987
4903
  #startTimer(delay4) {
3988
4904
  if (this.#timer) clearInterval(this.#timer);
3989
- this.#timer = setInterval(() => this.schedule(), delay4);
4905
+ this.#timer = setInterval(() => {
4906
+ this.callbacks.onReconcile?.();
4907
+ this.schedule();
4908
+ }, delay4);
3990
4909
  this.#timer.unref();
3991
4910
  }
3992
4911
  async #poll() {
@@ -4021,7 +4940,7 @@ var ActorMeshMonitor = class {
4021
4940
  #readCursor() {
4022
4941
  if (!this.callbacks.cursorPath) return void 0;
4023
4942
  try {
4024
- const value = JSON.parse(fs12.readFileSync(this.callbacks.cursorPath, "utf8"));
4943
+ const value = JSON.parse(fs13.readFileSync(this.callbacks.cursorPath, "utf8"));
4025
4944
  return value.format === 1 && typeof value.cursor === "number" && value.cursor >= 0 ? value.cursor : void 0;
4026
4945
  } catch {
4027
4946
  return void 0;
@@ -4038,11 +4957,11 @@ var ActorMeshMonitor = class {
4038
4957
 
4039
4958
  // src/actors/manager.ts
4040
4959
  import os4 from "node:os";
4041
- import path17 from "node:path";
4960
+ import path18 from "node:path";
4042
4961
 
4043
4962
  // src/actors/log-store.ts
4044
- import fs13 from "node:fs";
4045
- import path14 from "node:path";
4963
+ import fs14 from "node:fs";
4964
+ import path15 from "node:path";
4046
4965
  var ACTOR_MESSAGE_HISTORY_LIMIT = 100;
4047
4966
  var ACTOR_MESSAGE_ENVELOPE_BYTES = 4096;
4048
4967
  var ACTOR_TRUNCATION_SUFFIX = "\n[actor message truncated]";
@@ -4100,17 +5019,17 @@ var ActorLogStore = class {
4100
5019
  this.retention = retention;
4101
5020
  }
4102
5021
  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 });
5022
+ if (!runDirectory || !fs14.existsSync(runDirectory)) return;
5023
+ const dest = path15.join(path15.dirname(actor.sessionFile), "runs", runId);
5024
+ fs14.mkdirSync(dest, { recursive: true, mode: 448 });
4106
5025
  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));
5026
+ const src = path15.join(runDirectory, file);
5027
+ if (fs14.existsSync(src)) fs14.copyFileSync(src, path15.join(dest, file));
4109
5028
  }
4110
- const nested = path14.join(runDirectory, "nested");
4111
- if (fs13.existsSync(nested)) {
5029
+ const nested = path15.join(runDirectory, "nested");
5030
+ if (fs14.existsSync(nested)) {
4112
5031
  try {
4113
- fs13.cpSync(nested, path14.join(dest, "nested"), { recursive: true });
5032
+ fs14.cpSync(nested, path15.join(dest, "nested"), { recursive: true });
4114
5033
  } catch {
4115
5034
  }
4116
5035
  }
@@ -4118,16 +5037,16 @@ var ActorLogStore = class {
4118
5037
  }
4119
5038
  pruneRuns(actor, now = Date.now()) {
4120
5039
  pruneActorRunArchives({
4121
- runsDirectory: path14.join(path14.dirname(actor.sessionFile), "runs"),
5040
+ runsDirectory: path15.join(path15.dirname(actor.sessionFile), "runs"),
4122
5041
  ...actor.lastRunId ? { latestRunId: actor.lastRunId } : {},
4123
5042
  retentionMs: this.retention.actorRunArchiveMs,
4124
5043
  now
4125
5044
  });
4126
5045
  }
4127
5046
  retainedRunIds(actor) {
4128
- const runsDir = path14.join(path14.dirname(actor.sessionFile), "runs");
5047
+ const runsDir = path15.join(path15.dirname(actor.sessionFile), "runs");
4129
5048
  try {
4130
- return fs13.readdirSync(runsDir).sort();
5049
+ return fs14.readdirSync(runsDir).sort();
4131
5050
  } catch {
4132
5051
  return [];
4133
5052
  }
@@ -4180,6 +5099,34 @@ var ActorLogStore = class {
4180
5099
  }
4181
5100
  };
4182
5101
 
5102
+ // src/verified/generated/actor-name.js
5103
+ function $n2(v, what) {
5104
+ if (typeof v !== "number" || !Number.isSafeInteger(v) || v < 0) throw new RangeError(what + " must be a natural below 2^53, not " + v);
5105
+ return v;
5106
+ }
5107
+ var actorName = /* @__PURE__ */ (() => {
5108
+ function init(params) {
5109
+ const env = {}, s = {};
5110
+ return { scalars: { "out.active": 0, "out.stopped": 0, "out.available": 0 }, maps: {} };
5111
+ }
5112
+ function step(params, state, input) {
5113
+ const env = { "hasActive": $n2(input["hasActive"], "input hasActive"), "hasStopped": $n2(input["hasStopped"], "input hasStopped") }, s = state.scalars, dft = { ...state.defaults }, maps = state.maps;
5114
+ 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");
5115
+ 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 };
5116
+ return Object.keys(dft).length ? { scalars, maps: state.maps, defaults: dft } : { scalars, maps: state.maps };
5117
+ }
5118
+ return { init, step };
5119
+ })();
5120
+
5121
+ // src/actors/name-policy.ts
5122
+ function actorNameDecision(hasActive, hasStopped) {
5123
+ const result = actorName.step({}, actorName.init({}), { hasActive: hasActive ? 1 : 0, hasStopped: hasStopped ? 1 : 0 }).scalars;
5124
+ if (result["out.active"] === 1) return "active";
5125
+ if (result["out.stopped"] === 1) return "stopped";
5126
+ if (result["out.available"] === 1) return "available";
5127
+ throw new Error("Invalid verified actor name decision");
5128
+ }
5129
+
4183
5130
  // src/actors/predicate.ts
4184
5131
  var PREDICATE_VERSION = 1;
4185
5132
  var MAX_PREDICATE_SOURCE_CHARS = 16e3;
@@ -4248,24 +5195,63 @@ var evaluateActorValidWhile = async (source, facts) => {
4248
5195
  };
4249
5196
 
4250
5197
  // 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";
5198
+ import { createHash, randomUUID as randomUUID5 } from "node:crypto";
5199
+ import fs16 from "node:fs";
5200
+ import path16 from "node:path";
5201
+
5202
+ // src/actors/store-read.ts
5203
+ import fs15 from "node:fs";
5204
+ var ActorStoreReadError = class extends Error {
5205
+ filePath;
5206
+ constructor(filePath, detail, options) {
5207
+ super(`Cannot read Fabric actor store ${filePath}: ${detail}`, options);
5208
+ this.name = "ActorStoreReadError";
5209
+ this.filePath = filePath;
5210
+ }
5211
+ };
5212
+ var readStoreJson = (filePath) => {
5213
+ let text;
5214
+ try {
5215
+ text = fs15.readFileSync(filePath, "utf8");
5216
+ } catch (error) {
5217
+ if (error?.code === "ENOENT") return void 0;
5218
+ throw new ActorStoreReadError(
5219
+ filePath,
5220
+ error instanceof Error ? error.message : String(error),
5221
+ { cause: error }
5222
+ );
5223
+ }
5224
+ try {
5225
+ return JSON.parse(text);
5226
+ } catch (error) {
5227
+ throw new ActorStoreReadError(
5228
+ filePath,
5229
+ `invalid JSON (${error instanceof Error ? error.message : String(error)})`,
5230
+ { cause: error }
5231
+ );
5232
+ }
5233
+ };
5234
+
5235
+ // src/actors/binding-store.ts
4254
5236
  var BINDING_LOCK_TIMEOUT_MS = 5e3;
4255
5237
  var BINDING_STALE_LOCK_MS = 3e4;
4256
5238
  var bindingFileName = (sessionId) => `${createHash("sha256").update(sessionId).digest("hex")}.json`;
4257
5239
  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
5240
  var delay2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
4260
5241
  var ActorBindingStore = class {
4261
5242
  constructor(sessionId, root) {
4262
5243
  this.sessionId = sessionId;
4263
- this.filePath = root ? path15.join(root, "bindings", bindingFileName(sessionId)) : void 0;
5244
+ this.filePath = root ? path16.join(root, "bindings", bindingFileName(sessionId)) : void 0;
4264
5245
  this.#sync(true);
4265
5246
  }
4266
5247
  #bindings = /* @__PURE__ */ new Map();
4267
5248
  #fingerprint;
5249
+ #readError;
4268
5250
  filePath;
5251
+ /** The error from the latest failed read, or undefined after a good read. */
5252
+ get readError() {
5253
+ return this.#readError;
5254
+ }
4269
5255
  get(actorId) {
4270
5256
  this.#sync();
4271
5257
  const binding = this.#bindings.get(actorId);
@@ -4285,10 +5271,10 @@ var ActorBindingStore = class {
4285
5271
  });
4286
5272
  }
4287
5273
  async delete(actorId) {
4288
- return this.#mutate((bindings) => bindings.delete(actorId));
5274
+ return this.#mutate(actorId, (bindings) => bindings.delete(actorId));
4289
5275
  }
4290
5276
  async #update(actorId, mutate) {
4291
- return this.#mutate((bindings) => {
5277
+ return this.#mutate(actorId, (bindings) => {
4292
5278
  const binding = bindings.get(actorId) ?? { updatedAt: Date.now() };
4293
5279
  mutate(binding);
4294
5280
  if (!binding.model && !binding.thinking) {
@@ -4300,16 +5286,24 @@ var ActorBindingStore = class {
4300
5286
  return { ...binding };
4301
5287
  });
4302
5288
  }
4303
- async #mutate(operation) {
5289
+ async #mutate(actorId, operation) {
4304
5290
  if (!this.filePath) {
4305
5291
  const result = operation(this.#bindings);
4306
5292
  return result;
4307
5293
  }
4308
5294
  return this.#withLock(() => {
4309
- const bindings = this.#read();
4310
- const result = operation(bindings);
4311
- this.#save(bindings);
4312
- this.#replace(bindings);
5295
+ let snapshot;
5296
+ try {
5297
+ snapshot = this.#read();
5298
+ } catch (error) {
5299
+ if (error instanceof ActorStoreReadError) this.#readError = error;
5300
+ throw error;
5301
+ }
5302
+ this.#readError = void 0;
5303
+ const result = operation(snapshot.bindings);
5304
+ snapshot.unloaded.delete(actorId);
5305
+ this.#save(snapshot);
5306
+ this.#replace(snapshot.bindings);
4313
5307
  this.#fingerprint = this.#currentFingerprint();
4314
5308
  return result;
4315
5309
  });
@@ -4317,35 +5311,45 @@ var ActorBindingStore = class {
4317
5311
  #sync(force = false) {
4318
5312
  if (!this.filePath) return;
4319
5313
  const fingerprint = this.#currentFingerprint();
4320
- if (!force && fingerprint === this.#fingerprint) return;
4321
- this.#replace(this.#read());
5314
+ if (!force && !this.#readError && fingerprint === this.#fingerprint) return;
5315
+ try {
5316
+ this.#replace(this.#read().bindings);
5317
+ } catch (error) {
5318
+ if (!(error instanceof ActorStoreReadError)) throw error;
5319
+ this.#readError = error;
5320
+ return;
5321
+ }
5322
+ this.#readError = void 0;
4322
5323
  this.#fingerprint = fingerprint;
4323
5324
  }
4324
5325
  #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;
5326
+ const snapshot = { bindings: /* @__PURE__ */ new Map(), unloaded: /* @__PURE__ */ new Map() };
5327
+ if (!this.filePath) return snapshot;
5328
+ const parsed = readStoreJson(this.filePath);
5329
+ if (parsed === void 0) return snapshot;
5330
+ if (!isObject(parsed) || parsed.format !== 1 || !isObject(parsed.bindings)) {
5331
+ throw new ActorStoreReadError(
5332
+ this.filePath,
5333
+ "expected a format 1 object with a bindings object"
5334
+ );
4332
5335
  }
4333
- if (!isObject(parsed) || parsed.format !== 1 || parsed.sessionId !== this.sessionId) {
4334
- return bindings;
5336
+ if (parsed.sessionId !== this.sessionId) {
5337
+ throw new ActorStoreReadError(this.filePath, "the file belongs to another session");
4335
5338
  }
4336
- if (!isObject(parsed.bindings)) return bindings;
4337
5339
  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, {
5340
+ const model = isObject(value) && typeof value.model === "string" ? value.model.trim() : "";
5341
+ const thinking = isObject(value) && isFabricThinking(value.thinking) ? value.thinking : void 0;
5342
+ if (!isObject(value) || typeof value.updatedAt !== "number" || !model && !thinking) {
5343
+ snapshot.unloaded.set(actorId, value);
5344
+ continue;
5345
+ }
5346
+ snapshot.bindings.set(actorId, {
4343
5347
  ...model ? { model } : {},
4344
5348
  ...thinking ? { thinking } : {},
4345
5349
  updatedAt: value.updatedAt
4346
5350
  });
4347
5351
  }
4348
- return bindings;
5352
+ return snapshot;
4349
5353
  }
4350
5354
  #replace(bindings) {
4351
5355
  this.#bindings.clear();
@@ -4353,13 +5357,16 @@ var ActorBindingStore = class {
4353
5357
  this.#bindings.set(actorId, { ...binding });
4354
5358
  }
4355
5359
  }
4356
- #save(bindings) {
5360
+ #save({ bindings, unloaded }) {
4357
5361
  if (!this.filePath) return;
4358
5362
  const value = {
4359
5363
  format: 1,
4360
5364
  sessionId: this.sessionId,
4361
5365
  bindings: Object.fromEntries(
4362
- [...bindings.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([actorId, binding]) => [actorId, { ...binding }])
5366
+ [
5367
+ ...[...bindings.entries()].map(([actorId, binding]) => [actorId, { ...binding }]),
5368
+ ...unloaded.entries()
5369
+ ].sort(([left], [right]) => left.localeCompare(right))
4363
5370
  )
4364
5371
  };
4365
5372
  writeJsonAtomic(this.filePath, value, { space: 2, newline: true });
@@ -4367,7 +5374,7 @@ var ActorBindingStore = class {
4367
5374
  #currentFingerprint() {
4368
5375
  if (!this.filePath) return void 0;
4369
5376
  try {
4370
- const stat = fs14.statSync(this.filePath);
5377
+ const stat = fs16.statSync(this.filePath);
4371
5378
  return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}`;
4372
5379
  } catch {
4373
5380
  return void 0;
@@ -4376,9 +5383,8 @@ var ActorBindingStore = class {
4376
5383
  async #withLock(operation) {
4377
5384
  if (!this.filePath) return operation();
4378
5385
  const lockPath = `${this.filePath}.lock`;
4379
- const ownerPath2 = path15.join(lockPath, "owner");
4380
5386
  const deadline = Date.now() + BINDING_LOCK_TIMEOUT_MS;
4381
- const token = randomUUID6();
5387
+ const token = randomUUID5();
4382
5388
  const processAlive2 = (pid) => {
4383
5389
  if (!Number.isSafeInteger(pid) || pid <= 0) return false;
4384
5390
  try {
@@ -4388,90 +5394,61 @@ var ActorBindingStore = class {
4388
5394
  return false;
4389
5395
  }
4390
5396
  };
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);
5397
+ fs16.mkdirSync(path16.dirname(this.filePath), { recursive: true, mode: 448 });
5398
+ while (!tryAcquireShortLock(lockPath, formatShortLockOwner(token))) {
5399
+ if (reapStaleShortLock(lockPath, { staleMs: BINDING_STALE_LOCK_MS, legacyAlive: processAlive2 })) continue;
5400
+ if (Date.now() >= deadline) {
5401
+ throw new Error("Timed out waiting for the Fabric actor binding lock");
4426
5402
  }
5403
+ await delay2(10);
4427
5404
  }
4428
5405
  try {
4429
5406
  return operation();
4430
5407
  } 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
- }
5408
+ releaseShortLock(lockPath, token);
4439
5409
  }
4440
5410
  }
4441
5411
  };
4442
5412
 
4443
5413
  // 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";
5414
+ import { randomUUID as randomUUID6 } from "node:crypto";
5415
+ import fs17 from "node:fs";
5416
+ import path17 from "node:path";
5417
+ import { setTimeout as delay3 } from "node:timers/promises";
4447
5418
  var ACTOR_REGISTRY_LOCK_TIMEOUT_MS = 5e3;
4448
5419
  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;
5420
+ var isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5421
+ var isActorRegistryRecord = (entry) => isObject2(entry) && typeof entry.id === "string";
4451
5422
  var ActorRegistryStore = class {
4452
5423
  #registryPath;
4453
5424
  #actorRoot;
4454
5425
  constructor(actorRoot) {
4455
5426
  this.#actorRoot = actorRoot;
4456
- this.#registryPath = path16.join(actorRoot, "actors.json");
5427
+ this.#registryPath = path17.join(actorRoot, "actors.json");
4457
5428
  }
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 [];
5429
+ /**
5430
+ * Every entry in actors.json, including entries without a valid identity, so
5431
+ * a rewrite can keep them. A missing file reads as empty; any other read or
5432
+ * parse failure throws ActorStoreReadError, and callers must not write.
5433
+ */
5434
+ entries() {
5435
+ const parsed = readStoreJson(this.#registryPath);
5436
+ if (parsed === void 0) return [];
5437
+ const actors = isObject2(parsed) ? parsed.actors : void 0;
5438
+ if (!Array.isArray(actors)) {
5439
+ throw new ActorStoreReadError(this.#registryPath, "expected an object with an actors array");
4467
5440
  }
5441
+ return actors;
5442
+ }
5443
+ /** The entries that carry a string id. Throws like entries(). */
5444
+ records() {
5445
+ return this.entries().filter(isActorRegistryRecord);
4468
5446
  }
4469
5447
  /** The callback must be synchronous: release precedes promise assimilation. */
4470
- async withLock(operation) {
5448
+ async withLock(operation, signal) {
4471
5449
  const lockPath = `${this.#registryPath}.lock`;
4472
- const ownerPath2 = path16.join(lockPath, "owner");
4473
5450
  const deadline = Date.now() + ACTOR_REGISTRY_LOCK_TIMEOUT_MS;
4474
- const token = randomUUID7();
5451
+ const token = randomUUID6();
4475
5452
  const processAlive2 = (pid) => {
4476
5453
  if (!Number.isSafeInteger(pid) || pid <= 0) return false;
4477
5454
  try {
@@ -4481,66 +5458,33 @@ var ActorRegistryStore = class {
4481
5458
  return false;
4482
5459
  }
4483
5460
  };
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);
5461
+ fs17.mkdirSync(this.#actorRoot, { recursive: true, mode: 448 });
5462
+ signal?.throwIfAborted();
5463
+ while (!tryAcquireShortLock(lockPath, formatShortLockOwner(token))) {
5464
+ if (reapStaleShortLock(lockPath, { staleMs: ACTOR_REGISTRY_STALE_LOCK_MS, legacyAlive: processAlive2 })) continue;
5465
+ if (Date.now() >= deadline) {
5466
+ throw new Error("Timed out waiting for the Fabric actor registry lock");
4519
5467
  }
5468
+ await delay3(10, void 0, { signal });
5469
+ signal?.throwIfAborted();
4520
5470
  }
4521
5471
  try {
5472
+ signal?.throwIfAborted();
4522
5473
  return operation();
4523
5474
  } 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
- }
5475
+ releaseShortLock(lockPath, token);
4532
5476
  }
4533
5477
  }
4534
5478
  fingerprint() {
4535
5479
  try {
4536
- const stat = fs15.statSync(this.#registryPath);
5480
+ const stat = fs17.statSync(this.#registryPath);
4537
5481
  return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}`;
4538
5482
  } catch {
4539
5483
  return void 0;
4540
5484
  }
4541
5485
  }
4542
5486
  read() {
4543
- return JSON.parse(fs15.readFileSync(this.#registryPath, "utf8"));
5487
+ return JSON.parse(fs17.readFileSync(this.#registryPath, "utf8"));
4544
5488
  }
4545
5489
  /** Call within withLock for read-modify-write operations. */
4546
5490
  write(actors) {
@@ -4578,7 +5522,7 @@ var normalizeCapabilityRequirements = (requirements = []) => {
4578
5522
  };
4579
5523
  var readRunRecord = (filePath) => {
4580
5524
  try {
4581
- const parsed = JSON.parse(fs16.readFileSync(filePath, "utf8"));
5525
+ const parsed = JSON.parse(fs18.readFileSync(filePath, "utf8"));
4582
5526
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
4583
5527
  return parsed;
4584
5528
  } catch {
@@ -4628,7 +5572,7 @@ var ActorManager = class {
4628
5572
  this.meshConfig = meshConfig;
4629
5573
  this.agents = agents;
4630
5574
  this.onDeliver = onDeliver;
4631
- this.#actorRoot = options.actorRoot ?? fs16.mkdtempSync(path17.join(os4.tmpdir(), "pi-fabric-actors-"));
5575
+ this.#actorRoot = options.actorRoot ?? fs18.mkdtempSync(path18.join(os4.tmpdir(), "pi-fabric-actors-"));
4632
5576
  this.#actorScope = options.actorScope ?? meshConfig.actorScope;
4633
5577
  this.#persistent = options.persistent ?? false;
4634
5578
  this.#mainAgent = options.mainAgent;
@@ -4660,6 +5604,9 @@ var ActorManager = class {
4660
5604
  this.#retentionTimer.unref();
4661
5605
  this.#meshMonitor = new ActorMeshMonitor(mesh, meshConfig, {
4662
5606
  cursorPath: options.meshCursorPath,
5607
+ onReconcile: () => {
5608
+ this.#adoptionDeferred = false;
5609
+ },
4663
5610
  beforePoll: () => {
4664
5611
  this.#syncActorsFromRegistry();
4665
5612
  this.#refreshOwnership();
@@ -4695,8 +5642,11 @@ var ActorManager = class {
4695
5642
  // Adoption compares against this snapshot so two racing adopters cannot
4696
5643
  // both move the same dead lineage: only the first fenced write succeeds.
4697
5644
  #persistedRoots = /* @__PURE__ */ new Map();
4698
- // In-flight fenced adoption attempts, one per actor.
4699
- #adoptionPending = /* @__PURE__ */ new Set();
5645
+ // One attempt at a time; failures wait for mesh reconciliation.
5646
+ #adoptionAbort = new AbortController();
5647
+ #adoptionPending = false;
5648
+ #adoptionDeferred = false;
5649
+ #lastAdoptionId;
4700
5650
  #adoptionGraceMs;
4701
5651
  #listeners = /* @__PURE__ */ new Set();
4702
5652
  #retentionTimer;
@@ -4711,6 +5661,7 @@ var ActorManager = class {
4711
5661
  #mainIdle = true;
4712
5662
  #reloadingOwnership = false;
4713
5663
  #registryFingerprint;
5664
+ #createTail = Promise.resolve();
4714
5665
  subscribe(listener) {
4715
5666
  this.#listeners.add(listener);
4716
5667
  return () => this.#listeners.delete(listener);
@@ -4730,6 +5681,19 @@ var ActorManager = class {
4730
5681
  * request while a transferred actor still advertises its creating host.
4731
5682
  */
4732
5683
  async create(request, { asRegistryOwner = false } = {}) {
5684
+ const previous = this.#createTail;
5685
+ let release;
5686
+ this.#createTail = new Promise((resolve) => {
5687
+ release = resolve;
5688
+ });
5689
+ await previous;
5690
+ try {
5691
+ return await this.#createActor(request, asRegistryOwner);
5692
+ } finally {
5693
+ release();
5694
+ }
5695
+ }
5696
+ async #createActor(request, asRegistryOwner) {
4733
5697
  this.#refreshOwnership();
4734
5698
  const registryOwnerCreate = asRegistryOwner && request.residency === "durable";
4735
5699
  if (!registryOwnerCreate && [...this.#actors.values()].some(
@@ -4740,11 +5704,11 @@ var ActorManager = class {
4740
5704
  if (!this.meshConfig.enabled) throw new Error("Fabric mesh and actors are disabled");
4741
5705
  const name = request.name.trim();
4742
5706
  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);
5707
+ const namesakes = [...this.#actors.values()].filter((actor2) => actor2.name === name);
5708
+ const active = namesakes.find((actor2) => actor2.status !== "stopped");
5709
+ const decision = actorNameDecision(Boolean(active), namesakes.some((actor2) => actor2.status === "stopped"));
5710
+ if (decision === "active") throw new Error(`A Fabric actor named ${name} is already active (${active.id})`);
5711
+ if (decision === "stopped") throw new Error(`A stopped Fabric actor named ${name} already exists (${namesakes[0].id}); remove it explicitly before creating another`);
4748
5712
  if (!request.instructions.trim()) throw new Error("Actor instructions must not be empty");
4749
5713
  if (Buffer.byteLength(request.instructions, "utf8") > this.meshConfig.maxEventBytes) {
4750
5714
  throw new Error(`Actor instructions exceed ${this.meshConfig.maxEventBytes} bytes`);
@@ -4780,9 +5744,8 @@ var ActorManager = class {
4780
5744
  throw new Error("This Fabric host cannot commit actor capability requirements");
4781
5745
  }
4782
5746
  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 });
5747
+ const id = randomUUID7().replaceAll("-", "");
5748
+ const actorDirectory = path18.join(this.#actorRoot, id);
4786
5749
  const actor = {
4787
5750
  id,
4788
5751
  name,
@@ -4809,13 +5772,14 @@ var ActorManager = class {
4809
5772
  ...request.validWhile ? { validWhile: structuredClone(request.validWhile) } : {},
4810
5773
  ...principalScope ? { principalScope } : {},
4811
5774
  latestActivationSequence: 0,
4812
- sessionFile: path17.join(actorDirectory, "session.jsonl"),
5775
+ sessionFile: path18.join(actorDirectory, "session.jsonl"),
4813
5776
  queue: [],
4814
5777
  draining: false,
4815
5778
  messages: [],
4816
5779
  createdAt: Date.now(),
4817
5780
  updatedAt: Date.now()
4818
5781
  };
5782
+ fs18.mkdirSync(actorDirectory, { recursive: true, mode: 448 });
4819
5783
  this.#actors.set(id, actor);
4820
5784
  this.#locallyCreated.add(id);
4821
5785
  this.#ownership.set(id, true);
@@ -4841,6 +5805,7 @@ var ActorManager = class {
4841
5805
  const actor = this.#requireActor(id);
4842
5806
  this.#ceded.add(actor.id);
4843
5807
  this.#ownership.set(actor.id, false);
5808
+ this.#registryFingerprint = void 0;
4844
5809
  actor.abortController?.abort();
4845
5810
  for (const item of actor.queue.splice(0)) {
4846
5811
  item.reject?.(
@@ -5144,17 +6109,17 @@ var ActorManager = class {
5144
6109
  const type = opts.type ?? "session";
5145
6110
  const lines = Math.max(1, Math.min(opts.lines ?? 200, 5e3));
5146
6111
  const sessionFile = actor.sessionFile;
5147
- const logDir = path17.join(path17.dirname(sessionFile), "runs");
6112
+ const logDir = path18.join(path18.dirname(sessionFile), "runs");
5148
6113
  const sessionPage = type === "run" ? { lines: [], hasMore: false } : readJsonlPage(sessionFile, lines, opts.before);
5149
6114
  const session = sessionPage.lines;
5150
6115
  let run;
5151
6116
  if (type !== "session") {
5152
6117
  const targetRunId = opts.runId ?? actor.lastRunId;
5153
6118
  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");
6119
+ const runPath = path18.join(logDir, targetRunId);
6120
+ if (fs18.existsSync(runPath)) {
6121
+ const statusRecord = readRunRecord(path18.join(runPath, "status.json"));
6122
+ const eventsFile = path18.join(runPath, "events.jsonl");
5158
6123
  const page = readJsonlPage(eventsFile, lines, opts.before);
5159
6124
  run = {
5160
6125
  runId: targetRunId,
@@ -5320,9 +6285,10 @@ var ActorManager = class {
5320
6285
  * reject every queued message so subsequent execution is cancelled. Unlike
5321
6286
  * stop(), actors stay alive and idle — they keep their identity, session,
5322
6287
  * 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.
6288
+ * number of actors that had work to cancel. Also arms the stop-the-world
6289
+ * gate, which suppresses host-event and mesh dispatch until the user sends
6290
+ * a new message (the "input" host event), so the interrupt's own turn_end /
6291
+ * agent_settled events do not re-enqueue the actors.
5326
6292
  */
5327
6293
  haltAll() {
5328
6294
  if (!this.meshConfig.enabled) return { halted: 0 };
@@ -5356,7 +6322,7 @@ var ActorManager = class {
5356
6322
  await this.#bindings.delete(actor.id);
5357
6323
  this.#actors.delete(actor.id);
5358
6324
  this.#emitChange();
5359
- fs16.rmSync(path17.dirname(actor.sessionFile), { recursive: true, force: true });
6325
+ fs18.rmSync(path18.dirname(actor.sessionFile), { recursive: true, force: true });
5360
6326
  await this.#saveActors(/* @__PURE__ */ new Set([actor.id]));
5361
6327
  await this.mesh.delete({ key: this.#presenceKey(actor.id) }).catch(() => ({ deleted: false }));
5362
6328
  if (retainedRunId) await this.agents.cleanup(retainedRunId).catch(() => ({ cleaned: false }));
@@ -5365,6 +6331,7 @@ var ActorManager = class {
5365
6331
  async close() {
5366
6332
  if (this.#closing) return;
5367
6333
  this.#closing = true;
6334
+ this.#adoptionAbort.abort();
5368
6335
  this.#meshMonitor.close();
5369
6336
  if (this.#retentionTimer) clearInterval(this.#retentionTimer);
5370
6337
  this.#retentionTimer = void 0;
@@ -5383,7 +6350,7 @@ var ActorManager = class {
5383
6350
  }
5384
6351
  }
5385
6352
  await Promise.allSettled(
5386
- owned.map((actor) => actor.drain ?? Promise.resolve())
6353
+ [...this.#actors.values()].map((actor) => actor.drain ?? Promise.resolve())
5387
6354
  );
5388
6355
  for (const actor of owned) {
5389
6356
  if (actor.status !== "stopped") actor.status = "idle";
@@ -5396,7 +6363,7 @@ var ActorManager = class {
5396
6363
  await Promise.allSettled(
5397
6364
  [...this.#actors.values()].map((actor) => actor.drain ?? Promise.resolve())
5398
6365
  );
5399
- fs16.rmSync(this.#actorRoot, { recursive: true, force: true });
6366
+ fs18.rmSync(this.#actorRoot, { recursive: true, force: true });
5400
6367
  }
5401
6368
  #enqueue(actor, source, payload, options = {}) {
5402
6369
  const canManage = options.ownershipChecked ? this.#canManageCached(actor.id) : this.#canManage(actor.id);
@@ -5439,7 +6406,7 @@ var ActorManager = class {
5439
6406
  `Fabric actor queue limit reached for ${actor.name} (${this.meshConfig.actorQueueLimit})`
5440
6407
  );
5441
6408
  }
5442
- const itemId = randomUUID8();
6409
+ const itemId = randomUUID7();
5443
6410
  const item = {
5444
6411
  id: itemId,
5445
6412
  source,
@@ -5485,10 +6452,16 @@ var ActorManager = class {
5485
6452
  const drain = this.#drain(actor);
5486
6453
  actor.drain = drain;
5487
6454
  const release = () => {
5488
- if (actor.drain === drain) delete actor.drain;
6455
+ if (actor.drain === drain) {
6456
+ delete actor.drain;
6457
+ if (!this.#ownership.get(actor.id)) this.#registryFingerprint = void 0;
6458
+ }
5489
6459
  };
5490
6460
  drain.then(release, release);
5491
6461
  }
6462
+ // Presence saves inside the drain are best-effort, like the enqueue-time
6463
+ // publish: a refused registry save (an unreadable actors.json, a lock
6464
+ // timeout) must not strand a dequeued item or abandon the rest of the queue.
5492
6465
  async #drain(actor) {
5493
6466
  try {
5494
6467
  while (actor.queue.length > 0 && actor.status !== "stopped" && !this.#closing && this.#canManage(actor.id)) {
@@ -5499,14 +6472,14 @@ var ActorManager = class {
5499
6472
  delete actor.lastError;
5500
6473
  const abortController = new AbortController();
5501
6474
  actor.abortController = abortController;
5502
- await this.#publishPresence(actor);
6475
+ await this.#publishPresence(actor).catch(() => void 0);
5503
6476
  const beforeRun = await this.#validity(actor, item);
5504
6477
  if (!beforeRun.valid) {
5505
6478
  this.#recordStale(actor, item, beforeRun.reason);
5506
6479
  delete actor.abortController;
5507
6480
  actor.status = actor.queue.length > 0 ? "queued" : "idle";
5508
6481
  actor.updatedAt = Date.now();
5509
- await this.#publishPresence(actor);
6482
+ await this.#publishPresence(actor).catch(() => void 0);
5510
6483
  continue;
5511
6484
  }
5512
6485
  let runId;
@@ -5526,7 +6499,7 @@ var ActorManager = class {
5526
6499
  actor.queue.unshift(item);
5527
6500
  actor.status = "queued";
5528
6501
  actor.updatedAt = Date.now();
5529
- await this.#publishPresence(actor);
6502
+ await this.#publishPresence(actor).catch(() => void 0);
5530
6503
  break;
5531
6504
  }
5532
6505
  delete actor.missingCapabilities;
@@ -5546,14 +6519,14 @@ var ActorManager = class {
5546
6519
  actor.lastRunId = result.id;
5547
6520
  if (actor.runner === "claude" && result.runnerSessionId) {
5548
6521
  actor.runnerSessionId = result.runnerSessionId;
5549
- await this.#saveActors();
6522
+ await this.#saveActors().catch(() => void 0);
5550
6523
  }
5551
6524
  runCompleted = result.status === "completed";
5552
6525
  if (result.status !== "completed") {
5553
6526
  if (actor.responseMode === "directive") {
5554
6527
  const reason = result.error || `Actor run ${result.status}`;
5555
6528
  const silent = {
5556
- id: randomUUID8(),
6529
+ id: randomUUID7(),
5557
6530
  actorId: actor.id,
5558
6531
  actorName: actor.name,
5559
6532
  direction: "out",
@@ -5619,7 +6592,7 @@ var ActorManager = class {
5619
6592
  }
5620
6593
  actor.lastError = message2;
5621
6594
  const failed = {
5622
- id: randomUUID8(),
6595
+ id: randomUUID7(),
5623
6596
  actorId: actor.id,
5624
6597
  actorName: actor.name,
5625
6598
  direction: "out",
@@ -5643,7 +6616,7 @@ var ActorManager = class {
5643
6616
  delete actor.abortController;
5644
6617
  actor.updatedAt = Date.now();
5645
6618
  if (actor.status !== "stopped") actor.status = actor.queue.length > 0 ? "queued" : "idle";
5646
- if (this.#canManage(actor.id)) await this.#publishPresence(actor);
6619
+ if (this.#canManage(actor.id)) await this.#publishPresence(actor).catch(() => void 0);
5647
6620
  }
5648
6621
  }
5649
6622
  } finally {
@@ -5711,7 +6684,7 @@ var ActorManager = class {
5711
6684
  if (actor.responseMode === "directive") {
5712
6685
  const directive = asDirective(result);
5713
6686
  return {
5714
- id: randomUUID8(),
6687
+ id: randomUUID7(),
5715
6688
  actorId: actor.id,
5716
6689
  actorName: actor.name,
5717
6690
  direction: "out",
@@ -5725,7 +6698,7 @@ var ActorManager = class {
5725
6698
  };
5726
6699
  }
5727
6700
  return {
5728
- id: randomUUID8(),
6701
+ id: randomUUID7(),
5729
6702
  actorId: actor.id,
5730
6703
  actorName: actor.name,
5731
6704
  direction: "out",
@@ -5780,7 +6753,7 @@ var ActorManager = class {
5780
6753
  }
5781
6754
  #recordStale(actor, item, reason = "validWhile returned false", runId, usage) {
5782
6755
  const message2 = {
5783
- id: randomUUID8(),
6756
+ id: randomUUID7(),
5784
6757
  actorId: actor.id,
5785
6758
  actorName: actor.name,
5786
6759
  direction: "out",
@@ -5940,14 +6913,16 @@ var ActorManager = class {
5940
6913
  (actor) => this.#ownershipDecision(actor.id)
5941
6914
  );
5942
6915
  const replaced = /* @__PURE__ */ new Set([...removedIds, ...owned.map((actor) => actor.id)]);
5943
- const preserved = this.#registry.records().filter((record) => !replaced.has(record.id));
6916
+ const preserved = this.#registry.entries().filter((entry) => !isActorRegistryRecord(entry) || !replaced.has(entry.id));
5944
6917
  const actors = [...preserved, ...owned.map((actor) => this.#serializedActor(actor))];
5945
6918
  this.#registry.write(actors);
5946
6919
  this.#registryFingerprint = this.#registry.fingerprint();
5947
6920
  for (const id of removedIds) this.#persistedRoots.delete(id);
5948
6921
  for (const actor of owned) this.#persistedRoots.set(actor.id, actor.rootId);
5949
6922
  for (const record of preserved) {
5950
- if (typeof record.rootId === "string") this.#persistedRoots.set(record.id, record.rootId);
6923
+ if (isActorRegistryRecord(record) && typeof record.rootId === "string") {
6924
+ this.#persistedRoots.set(record.id, record.rootId);
6925
+ }
5951
6926
  }
5952
6927
  });
5953
6928
  this.#registryFingerprint = void 0;
@@ -5957,22 +6932,17 @@ var ActorManager = class {
5957
6932
  if (!this.#persistent || this.#closing || this.#reloadingOwnership) return;
5958
6933
  const fingerprint = this.#registry.fingerprint();
5959
6934
  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
- }
6935
+ let parsed;
6936
+ try {
6937
+ parsed = this.#registry.read();
6938
+ if (typeof parsed !== "object" || parsed === null || !Array.isArray(parsed.actors)) return;
6939
+ } catch {
5971
6940
  return;
5972
6941
  }
6942
+ this.#registryFingerprint = fingerprint;
5973
6943
  const owned = /* @__PURE__ */ new Set();
5974
6944
  for (const [id, actor] of this.#actors) {
5975
- if (this.#ownershipDecision(id)) {
6945
+ if (this.#ownershipDecision(id) || this.#ownership.get(id) || actor.drain) {
5976
6946
  owned.add(id);
5977
6947
  continue;
5978
6948
  }
@@ -5981,30 +6951,33 @@ var ActorManager = class {
5981
6951
  this.#ownership.delete(id);
5982
6952
  this.#locallyCreated.delete(id);
5983
6953
  }
5984
- this.#loadActors(true);
6954
+ this.#loadActors(true, parsed);
5985
6955
  for (const actor of this.#actors.values()) {
5986
6956
  if (!owned.has(actor.id)) {
5987
6957
  this.#ownership.set(actor.id, this.#ownershipDecision(actor.id));
5988
6958
  }
5989
6959
  }
5990
6960
  }
5991
- #loadActors(onlyMissing = false) {
6961
+ #loadActors(onlyMissing = false, snapshot, adoption) {
5992
6962
  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;
6963
+ let parsed = snapshot;
6964
+ if (snapshot === void 0) {
6965
+ try {
6966
+ parsed = this.#registry.read();
6967
+ } catch {
6968
+ return false;
6969
+ }
5999
6970
  }
6000
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return;
6971
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return false;
6001
6972
  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);
6973
+ if (!Array.isArray(records)) return false;
6974
+ if (!adoption) {
6975
+ for (const value of records) {
6976
+ if (typeof value !== "object" || value === null || Array.isArray(value)) continue;
6977
+ const record = value;
6978
+ if (typeof record.id === "string" && typeof record.rootId === "string") {
6979
+ this.#persistedRoots.set(record.id, record.rootId);
6980
+ }
6008
6981
  }
6009
6982
  }
6010
6983
  for (const value of records) {
@@ -6062,7 +7035,7 @@ var ActorManager = class {
6062
7035
  ...record.validWhile?.version === 1 && typeof record.validWhile.source === "string" ? { validWhile: record.validWhile } : {},
6063
7036
  ...principalScope ? { principalScope } : {},
6064
7037
  latestActivationSequence: 0,
6065
- sessionFile: path17.join(this.#actorRoot, record.id, "session.jsonl"),
7038
+ sessionFile: path18.join(this.#actorRoot, record.id, "session.jsonl"),
6066
7039
  queue: [],
6067
7040
  draining: false,
6068
7041
  messages: [],
@@ -6077,11 +7050,21 @@ var ActorManager = class {
6077
7050
  }
6078
7051
  }
6079
7052
  }
7053
+ if (adoption) {
7054
+ if (actor.id !== adoption.target.id) continue;
7055
+ adoption.commit();
7056
+ const target = adoption.target;
7057
+ for (const key of ["kernel", "pythonRuntime", "runnerSessionId", "model", "thinking", "tools", "transport", "timeoutMs", "extensions", "capabilityDigest", "validWhile", "principalScope", "lastRunId"]) delete target[key];
7058
+ Object.assign(target, actor);
7059
+ this.#ownership.set(target.id, this.#ownershipDecision(target.id));
7060
+ return true;
7061
+ }
6080
7062
  this.#actors.set(actor.id, actor);
6081
7063
  added++;
6082
7064
  void this.#publishPresence(actor).catch(() => void 0);
6083
7065
  }
6084
7066
  if (added > 0) this.#emitChange();
7067
+ return !adoption;
6085
7068
  }
6086
7069
  #resolvedModel(runner, model) {
6087
7070
  return (runner === "pi" || runner === "pi-durable") && this.#resolvePiModel ? this.#resolvePiModel(model) : model;
@@ -6157,7 +7140,7 @@ var ActorManager = class {
6157
7140
  ...actor.lastRunId ? { lastRunId: actor.lastRunId } : {},
6158
7141
  ...actor.lastError ? { lastError: actor.lastError } : {},
6159
7142
  sessionFile: actor.sessionFile,
6160
- logDir: path17.join(path17.dirname(actor.sessionFile), "runs")
7143
+ logDir: path18.join(path18.dirname(actor.sessionFile), "runs")
6161
7144
  };
6162
7145
  }
6163
7146
  validateDirectMessage(message2, data) {
@@ -6186,10 +7169,10 @@ var ActorManager = class {
6186
7169
  return this.#canManageActor === void 0;
6187
7170
  }
6188
7171
  #maybeAdoptOrphan(actor) {
6189
- if (!this.#persistent || this.#closing || !this.#canManageActor || this.#claimResidency === void 0 || this.#adoptionPending.has(actor.id)) {
7172
+ if (!this.#persistent || this.#closing || !this.#canManageActor || this.#claimResidency === void 0 || this.#adoptionPending || this.#adoptionDeferred) {
6190
7173
  return;
6191
7174
  }
6192
- if (actor.rootId === this.#rootId) return;
7175
+ if (actor.rootId === this.#rootId || actor.drain) return;
6193
7176
  if (actor.residency !== this.#claimResidency) return;
6194
7177
  if (this.#canManageActor(actor.id) !== void 0) return;
6195
7178
  if (this.#lineageAlive?.(actor.rootId) === true) return;
@@ -6200,12 +7183,16 @@ var ActorManager = class {
6200
7183
  void this.#confirmAdoption(actor).catch(() => void 0);
6201
7184
  }
6202
7185
  async #confirmAdoption(actor) {
6203
- if (this.#adoptionPending.has(actor.id)) return;
6204
- this.#adoptionPending.add(actor.id);
7186
+ if (this.#adoptionPending) return;
7187
+ this.#adoptionPending = true;
7188
+ this.#lastAdoptionId = actor.id;
7189
+ let adopted = false;
6205
7190
  try {
6206
7191
  const expectedRootId = actor.rootId;
6207
- const adopted = await this.#registry.withLock(() => {
6208
- const records = this.#registry.records();
7192
+ adopted = await this.#registry.withLock(() => {
7193
+ if (this.#closing || this.#actors.get(actor.id) !== actor || actor.drain) return false;
7194
+ const entries = this.#registry.entries();
7195
+ const records = entries.filter(isActorRegistryRecord);
6209
7196
  const current = records.find((record) => record.id === actor.id);
6210
7197
  if (!current || current.rootId !== expectedRootId) return false;
6211
7198
  if (this.#canManageActor?.(actor.id) !== void 0) return false;
@@ -6213,17 +7200,21 @@ var ActorManager = class {
6213
7200
  if (typeof current.adoptedAt === "number" && Date.now() - current.adoptedAt < this.#adoptionGraceMs) {
6214
7201
  return false;
6215
7202
  }
7203
+ const candidate = { ...current, rootId: this.#rootId, adoptedAt: Date.now(), updatedAt: Date.now() };
7204
+ const preserved = entries.filter(
7205
+ (entry) => !isActorRegistryRecord(entry) || entry.id !== actor.id
7206
+ );
7207
+ const hydrated = this.#loadActors(false, { actors: [candidate] }, {
7208
+ target: actor,
7209
+ commit: () => this.#registry.write([...preserved, candidate])
7210
+ });
7211
+ if (!hydrated) return false;
6216
7212
  for (const record of records) {
6217
7213
  if (typeof record.rootId === "string") this.#persistedRoots.set(record.id, record.rootId);
6218
7214
  }
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
7215
  return true;
6226
- });
7216
+ }, this.#adoptionAbort.signal);
7217
+ if (this.#closing) return;
6227
7218
  if (adopted) {
6228
7219
  this.#persistedRoots.set(actor.id, this.#rootId);
6229
7220
  } else {
@@ -6238,19 +7229,41 @@ var ActorManager = class {
6238
7229
  }
6239
7230
  } catch {
6240
7231
  } finally {
6241
- this.#adoptionPending.delete(actor.id);
7232
+ this.#adoptionPending = false;
7233
+ }
7234
+ if (this.#closing) return;
7235
+ if (!adopted) {
7236
+ this.#adoptionDeferred = true;
7237
+ } else {
7238
+ this.#registryFingerprint = void 0;
7239
+ this.#syncActorsFromRegistry();
7240
+ this.#refreshOwnership();
7241
+ if (this.#actors.get(actor.id) === actor && this.#canManageCached(actor.id)) {
7242
+ void this.#publishPresence(actor).catch(() => void 0);
7243
+ }
6242
7244
  }
6243
- this.#refreshOwnership();
6244
7245
  this.#emitChange();
6245
7246
  }
7247
+ #scheduleAdoptions() {
7248
+ if (this.#closing || this.#adoptionPending || this.#adoptionDeferred || !this.#persistent || !this.#canManageActor || this.#claimResidency === void 0) return;
7249
+ const ids = [...this.#actors.keys()];
7250
+ const start = (ids.indexOf(this.#lastAdoptionId ?? "") + 1) % (ids.length || 1);
7251
+ for (let i = 0; i < ids.length; i++) {
7252
+ const id = ids[(start + i) % ids.length];
7253
+ const actor = this.#actors.get(id);
7254
+ if (actor && !this.#ownership.get(id)) this.#maybeAdoptOrphan(actor);
7255
+ if (this.#adoptionPending) return;
7256
+ }
7257
+ }
6246
7258
  #refreshOwnership() {
6247
7259
  if (!this.#canManageActor || this.#reloadingOwnership) return;
6248
- let acquired = false;
7260
+ const acquired = [];
6249
7261
  for (const actor of this.#actors.values()) {
6250
7262
  const previous = this.#ownership.get(actor.id) ?? false;
6251
7263
  const next = this.#ownershipDecision(actor.id);
6252
- this.#ownership.set(actor.id, next);
6253
7264
  if (previous && !next) {
7265
+ this.#ownership.set(actor.id, false);
7266
+ this.#registryFingerprint = void 0;
6254
7267
  actor.abortController?.abort();
6255
7268
  for (const item of actor.queue.splice(0)) {
6256
7269
  item.reject?.(
@@ -6261,20 +7274,28 @@ var ActorManager = class {
6261
7274
  }
6262
7275
  if (actor.status !== "stopped") actor.status = "idle";
6263
7276
  } else if (!previous && next) {
6264
- acquired = true;
7277
+ acquired.push(actor);
6265
7278
  }
6266
- if (!next) this.#maybeAdoptOrphan(actor);
6267
7279
  }
6268
- if (!acquired || !this.#persistent || this.#closing) return;
7280
+ this.#scheduleAdoptions();
7281
+ if (acquired.length === 0 || this.#closing) return;
7282
+ if (!this.#persistent) {
7283
+ for (const actor of acquired) this.#ownership.set(actor.id, true);
7284
+ return;
7285
+ }
7286
+ let snapshot;
7287
+ try {
7288
+ snapshot = this.#registry.read();
7289
+ if (typeof snapshot !== "object" || snapshot === null || Array.isArray(snapshot) || !Array.isArray(snapshot.actors)) return;
7290
+ } catch {
7291
+ return;
7292
+ }
6269
7293
  this.#reloadingOwnership = true;
6270
7294
  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));
7295
+ for (const actor of acquired) {
7296
+ if (actor.drain) continue;
7297
+ this.#loadActors(false, snapshot, { target: actor, commit: () => {
7298
+ } });
6278
7299
  }
6279
7300
  } finally {
6280
7301
  this.#reloadingOwnership = false;
@@ -6319,16 +7340,17 @@ var ActorManager = class {
6319
7340
  var ActorDirectory = class extends ActorManager {
6320
7341
  #secondary;
6321
7342
  #defaultScope;
7343
+ #directoryCreateTail = Promise.resolve();
6322
7344
  constructor(base, roots, defaultScope) {
6323
7345
  const options = { ...base[6] ?? {} };
6324
7346
  const meshCursorPath = options.meshCursorPath;
6325
7347
  delete options.actorRoot;
6326
7348
  delete options.meshCursorPath;
6327
7349
  const cursorPaths = meshCursorPath ? { project: `${meshCursorPath}.project`, session: `${meshCursorPath}.session` } : void 0;
6328
- if (meshCursorPath && fs17.existsSync(meshCursorPath)) {
7350
+ if (meshCursorPath && fs19.existsSync(meshCursorPath)) {
6329
7351
  for (const cursorPath of Object.values(cursorPaths)) {
6330
7352
  try {
6331
- if (!fs17.existsSync(cursorPath)) fs17.copyFileSync(meshCursorPath, cursorPath);
7353
+ if (!fs19.existsSync(cursorPath)) fs19.copyFileSync(meshCursorPath, cursorPath);
6332
7354
  } catch {
6333
7355
  }
6334
7356
  }
@@ -6372,6 +7394,19 @@ var ActorDirectory = class extends ActorManager {
6372
7394
  this.#secondary.retryCapabilityWaiters();
6373
7395
  }
6374
7396
  async create(request, options = {}) {
7397
+ const previous = this.#directoryCreateTail;
7398
+ let release;
7399
+ this.#directoryCreateTail = new Promise((resolve) => {
7400
+ release = resolve;
7401
+ });
7402
+ await previous;
7403
+ try {
7404
+ return await this.#createInScope(request, options);
7405
+ } finally {
7406
+ release();
7407
+ }
7408
+ }
7409
+ async #createInScope(request, options) {
6375
7410
  const scope = request.scope ?? this.#defaultScope;
6376
7411
  if (scope !== "project" && scope !== "session") {
6377
7412
  throw new Error(`Invalid Fabric actor storage scope: ${String(scope)}`);
@@ -6379,8 +7414,9 @@ var ActorDirectory = class extends ActorManager {
6379
7414
  const name = request.name.trim();
6380
7415
  const sameName = this.list().filter((actor) => actor.name === name);
6381
7416
  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);
7417
+ const decision = actorNameDecision(Boolean(existing), sameName.some((actor) => actor.status === "stopped"));
7418
+ if (decision === "active") throw new Error(`A Fabric actor named ${name} is already active (${existing.id})`);
7419
+ if (decision === "stopped") throw new Error(`A stopped Fabric actor named ${name} already exists (${sameName[0].id}); remove it explicitly before creating another`);
6384
7420
  return scope === this.#defaultScope ? super.create(request, options) : this.#secondary.create(request, options);
6385
7421
  }
6386
7422
  list() {
@@ -6479,12 +7515,14 @@ var ActorDirectory = class extends ActorManager {
6479
7515
  return this.#isPrimary(args[0]) ? super.remove(...args) : this.#secondary.remove(...args);
6480
7516
  }
6481
7517
  async close() {
6482
- await Promise.all([super.close(), this.#secondary.close()]);
7518
+ const [primary, secondary] = await Promise.allSettled([super.close(), this.#secondary.close()]);
7519
+ if (primary.status === "rejected") throw primary.reason;
7520
+ if (secondary.status === "rejected") throw secondary.reason;
6483
7521
  }
6484
7522
  };
6485
7523
 
6486
7524
  // src/lifecycle/broker.ts
6487
- import { randomUUID as randomUUID9 } from "node:crypto";
7525
+ import { randomUUID as randomUUID8 } from "node:crypto";
6488
7526
  var subscriptionKey = (id) => FABRIC_LIFECYCLE_SUBSCRIPTION_PREFIX + id;
6489
7527
  var LifecycleBroker = class {
6490
7528
  constructor(mesh, identity, participants, options, deliver) {
@@ -6563,7 +7601,7 @@ var LifecycleBroker = class {
6563
7601
  const now = Date.now();
6564
7602
  const subscription = {
6565
7603
  format: 1,
6566
- id: randomUUID9().replaceAll("-", ""),
7604
+ id: randomUUID8().replaceAll("-", ""),
6567
7605
  from,
6568
7606
  events,
6569
7607
  to,
@@ -6733,7 +7771,7 @@ var LifecycleBroker = class {
6733
7771
  };
6734
7772
 
6735
7773
  // src/topology/control-plane.ts
6736
- import { createHash as createHash2, randomUUID as randomUUID10 } from "node:crypto";
7774
+ import { createHash as createHash2, randomUUID as randomUUID9 } from "node:crypto";
6737
7775
  var CONTROL_TOPIC = "fabric.control.command";
6738
7776
  var ACK_TOPIC = "fabric.control.ack";
6739
7777
  var CONTROL_SEEN_PREFIX = "topology/control-seen/";
@@ -6744,13 +7782,13 @@ var MAX_CONTROL_TIMEOUT_MS = 24 * 60 * 60 * 1e3 + 6e4;
6744
7782
  var MAX_INCARNATION_LENGTH = 128;
6745
7783
  var STALE_INCARNATION_ERROR = "Fabric control command targets a previous owner incarnation; the owner restarted. Re-resolve the participant and retry.";
6746
7784
  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);
7785
+ var isObject3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6748
7786
  var isIncarnation = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_INCARNATION_LENGTH;
6749
7787
  var controlAcceptanceBytes = (acceptance) => Buffer.byteLength(JSON.stringify(acceptance), "utf8");
6750
7788
  var commandFromEvent = (event) => {
6751
- if (!isObject2(event.data) || event.data.version !== 1) return void 0;
7789
+ if (!isObject3(event.data) || event.data.version !== 1) return void 0;
6752
7790
  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")) {
7791
+ 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
7792
  return void 0;
6755
7793
  }
6756
7794
  const { sender: _forged, ...command } = data;
@@ -6760,7 +7798,7 @@ var commandFromEvent = (event) => {
6760
7798
  };
6761
7799
  };
6762
7800
  var controlSeenRecord = (value) => {
6763
- if (!isObject2(value) || value.format !== 1) return void 0;
7801
+ if (!isObject3(value) || value.format !== 1) return void 0;
6764
7802
  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
7803
  return void 0;
6766
7804
  }
@@ -6781,7 +7819,7 @@ var FabricControlPlane = class {
6781
7819
  #activeHandlers = /* @__PURE__ */ new Set();
6782
7820
  #pollMs;
6783
7821
  #ackTimeoutMs;
6784
- #incarnation = randomUUID10();
7822
+ #incarnation = randomUUID9();
6785
7823
  #offset;
6786
7824
  #lastSequence;
6787
7825
  #timer;
@@ -6843,7 +7881,7 @@ var FabricControlPlane = class {
6843
7881
  this.#pollMs * 4,
6844
7882
  Math.min(MAX_CONTROL_TIMEOUT_MS, Math.floor(options.timeoutMs ?? this.#ackTimeoutMs))
6845
7883
  );
6846
- const commandId = randomUUID10();
7884
+ const commandId = randomUUID9();
6847
7885
  const requestedAt = Date.now();
6848
7886
  let pendingRequest;
6849
7887
  const acceptance = new Promise((resolve, reject) => {
@@ -6937,7 +7975,7 @@ var FabricControlPlane = class {
6937
7975
  to: pending.ownerHostId,
6938
7976
  data: {
6939
7977
  version: 1,
6940
- commandId: randomUUID10(),
7978
+ commandId: randomUUID9(),
6941
7979
  targetId: pending.targetId,
6942
7980
  operation: "cancel",
6943
7981
  cancelCommandId: commandId,
@@ -6992,7 +8030,7 @@ var FabricControlPlane = class {
6992
8030
  }
6993
8031
  }
6994
8032
  #acceptAcknowledgement(event) {
6995
- if (!isObject2(event.data) || typeof event.data.commandId !== "string") return;
8033
+ if (!isObject3(event.data) || typeof event.data.commandId !== "string") return;
6996
8034
  const pending = this.#pending.get(event.data.commandId);
6997
8035
  if (!pending || event.data.version !== 1 || event.data.targetId !== pending.targetId || event.from.id !== pending.ownerIdentityId) {
6998
8036
  return;
@@ -7179,7 +8217,7 @@ var FabricControlPlane = class {
7179
8217
  while (sought.size > retained.size) {
7180
8218
  const page = this.mesh.tail(offset, this.mesh.maxReadEvents);
7181
8219
  for (const event of page.events) {
7182
- if (event.topic !== CONTROL_TOPIC || !isObject2(event.data)) continue;
8220
+ if (event.topic !== CONTROL_TOPIC || !isObject3(event.data)) continue;
7183
8221
  const commandId = event.data.commandId;
7184
8222
  if (typeof commandId === "string" && sought.has(commandId)) retained.add(commandId);
7185
8223
  }
@@ -7214,14 +8252,18 @@ var FabricControlPlane = class {
7214
8252
  // src/topology/participant-directory.ts
7215
8253
  import { createHash as createHash3 } from "node:crypto";
7216
8254
  var PARTICIPANT_PREFIX = "topology/participants/";
7217
- var PEER_SEQ_KEY = "topology/peer-seq";
8255
+ var PEER_SEQ_KEY = `topology/peer-seq/${FABRIC_PEER_LABEL_SEQUENCE}`;
8256
+ var MAX_HELD_LABEL_SKIPS = 64;
7218
8257
  var HOST_PREFIX = "topology/hosts/";
7219
8258
  var LEGACY_SESSION_PREFIX = "sessions/";
7220
8259
  var LEGACY_ACTOR_PREFIX = "actors/";
7221
8260
  var PARTICIPANT_HEARTBEAT_MS = 5e3;
7222
8261
  var PARTICIPANT_LEASE_MS = 15e3;
8262
+ var TOMBSTONE_PREFIX = "topology/tombstones/";
8263
+ var DEPARTED_LIMIT = 32;
8264
+ var DEPARTED_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
7223
8265
  var keyFor = (prefix, id) => prefix + createHash3("sha256").update(id).digest("hex");
7224
- var isObject3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
8266
+ var isObject4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
7225
8267
  var participantKind = (value) => value === "root" || value === "agent" || value === "actor" || value === "provider" ? value : void 0;
7226
8268
  var RUNNER_ID_PATTERN = /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/;
7227
8269
  var isRunnerId = (value) => typeof value === "string" && value.length <= 64 && RUNNER_ID_PATTERN.test(value);
@@ -7245,7 +8287,7 @@ var capabilities = /* @__PURE__ */ new Set([
7245
8287
  "fabric"
7246
8288
  ]);
7247
8289
  var participantFromEntry = (entry) => {
7248
- if (!isObject3(entry.value) || entry.value.format !== 1) return void 0;
8290
+ if (!isObject4(entry.value) || entry.value.format !== 1) return void 0;
7249
8291
  const value = entry.value;
7250
8292
  const kind = participantKind(value.kind);
7251
8293
  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 +8298,38 @@ var participantFromEntry = (entry) => {
7256
8298
  return value;
7257
8299
  };
7258
8300
  var hostFromEntry = (entry) => {
7259
- if (!isObject3(entry.value) || entry.value.format !== 1) return void 0;
8301
+ if (!isObject4(entry.value) || entry.value.format !== 1) return void 0;
8302
+ const value = entry.value;
8303
+ 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") {
8304
+ return void 0;
8305
+ }
8306
+ return value;
8307
+ };
8308
+ var optionalString = (value) => value === void 0 || typeof value === "string";
8309
+ var tombstoneFromEntry = (entry) => {
8310
+ if (!isObject4(entry.value) || entry.value.format !== 1) return void 0;
7260
8311
  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") {
8312
+ 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
8313
  return void 0;
7263
8314
  }
7264
8315
  return value;
7265
8316
  };
8317
+ var departedFromRoot = (participant, status, lastSeenAt) => ({
8318
+ format: 1,
8319
+ id: participant.id,
8320
+ kind: "root",
8321
+ rootId: participant.rootId,
8322
+ ownerHostId: participant.ownerHostId,
8323
+ ownerIdentityId: participant.ownerIdentityId,
8324
+ ...participant.ownerIncarnation ? { ownerIncarnation: participant.ownerIncarnation } : {},
8325
+ name: participant.name,
8326
+ ...participant.label ? { label: participant.label } : {},
8327
+ ...participant.cwd ? { cwd: participant.cwd } : {},
8328
+ ...participant.sessionId ? { sessionId: participant.sessionId } : {},
8329
+ status,
8330
+ startedAt: participant.startedAt,
8331
+ lastSeenAt
8332
+ });
7266
8333
  var peerFromParticipant = (participant) => {
7267
8334
  if (participant.kind !== "root" || !participant.cwd || !participant.sessionId || participant.status !== "idle" && participant.status !== "running") {
7268
8335
  return void 0;
@@ -7286,7 +8353,7 @@ var peerFromParticipant = (participant) => {
7286
8353
  };
7287
8354
  };
7288
8355
  var legacyRootFromEntry = (entry, localRootId, now) => {
7289
- if (now - entry.updatedAt > PARTICIPANT_LEASE_MS || !isObject3(entry.value)) return void 0;
8356
+ if (now - entry.updatedAt > PARTICIPANT_LEASE_MS || !isObject4(entry.value)) return void 0;
7290
8357
  const value = entry.value;
7291
8358
  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
8359
  return void 0;
@@ -7316,7 +8383,7 @@ var legacyRootFromEntry = (entry, localRootId, now) => {
7316
8383
  };
7317
8384
  };
7318
8385
  var legacyActorFromEntry = (entry, roots) => {
7319
- if (!isObject3(entry.value)) return void 0;
8386
+ if (!isObject4(entry.value)) return void 0;
7320
8387
  const value = entry.value;
7321
8388
  if (typeof value.id !== "string" || typeof value.name !== "string" || !isRunnerId(value.runner) || typeof value.status !== "string") {
7322
8389
  return void 0;
@@ -7349,17 +8416,25 @@ var legacyActorFromEntry = (entry, roots) => {
7349
8416
  stale: false
7350
8417
  };
7351
8418
  };
8419
+ var liveOwner = (participant, hosts, now) => {
8420
+ const owner = hosts.get(participant.ownerHostId);
8421
+ return !!owner && owner.expiresAt >= now && owner.identity.id === participant.ownerIdentityId && owner.rootId === participant.rootId;
8422
+ };
7352
8423
  var ParticipantDirectory = class {
7353
8424
  constructor(mesh, options) {
7354
8425
  this.mesh = mesh;
7355
8426
  this.options = options;
7356
8427
  this.#heartbeatMs = Math.max(100, options.heartbeatMs ?? PARTICIPANT_HEARTBEAT_MS);
7357
8428
  this.#leaseMs = Math.max(this.#heartbeatMs * 2, options.leaseMs ?? PARTICIPANT_LEASE_MS);
8429
+ this.#departedLimit = Math.max(0, Math.floor(options.departedLimit ?? DEPARTED_LIMIT));
8430
+ this.#departedRetentionMs = Math.max(0, options.departedRetentionMs ?? DEPARTED_RETENTION_MS);
7358
8431
  }
7359
8432
  #sources = /* @__PURE__ */ new Set();
7360
8433
  #startedAt = Date.now();
7361
8434
  #heartbeatMs;
7362
8435
  #leaseMs;
8436
+ #departedLimit;
8437
+ #departedRetentionMs;
7363
8438
  #localRecords = /* @__PURE__ */ new Map();
7364
8439
  #timer;
7365
8440
  #closed = false;
@@ -7430,18 +8505,12 @@ var ParticipantDirectory = class {
7430
8505
  if (!options.kinds || options.kinds.includes(self2.kind)) byId2.set(self2.id, self2);
7431
8506
  return [...byId2.values()];
7432
8507
  }
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
- );
8508
+ const hosts = this.#hosts();
7439
8509
  const byId = /* @__PURE__ */ new Map();
7440
8510
  for (const entry of this.mesh.listAll(PARTICIPANT_PREFIX)) {
7441
8511
  const participant = participantFromEntry(entry);
7442
8512
  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;
8513
+ const stale = !liveOwner(participant, hosts, now);
7445
8514
  if (stale && !options.includeStale) continue;
7446
8515
  if (options.scope === "local" && participant.ownerHostId !== this.options.hostId) continue;
7447
8516
  if (options.scope === "lineage" && participant.rootId !== this.options.rootId) continue;
@@ -7481,10 +8550,25 @@ var ParticipantDirectory = class {
7481
8550
  }
7482
8551
  get(id, now = Date.now()) {
7483
8552
  const target = id === "main" ? this.options.rootId : id;
8553
+ if (this.options.enabled) {
8554
+ const participant = this.#participant(target);
8555
+ if (participant) {
8556
+ const entry = this.mesh.get(keyFor(HOST_PREFIX, participant.ownerHostId));
8557
+ const owner = entry && hostFromEntry(entry);
8558
+ if (owner && liveOwner(participant, /* @__PURE__ */ new Map([[owner.id, owner]]), now)) {
8559
+ return { ...participant, local: participant.ownerHostId === this.options.hostId, stale: false };
8560
+ }
8561
+ }
8562
+ }
7484
8563
  return this.list({ scope: "project" }, now).find((participant) => participant.id === target);
7485
8564
  }
8565
+ #participant(id) {
8566
+ const entry = this.mesh.get(keyFor(PARTICIPANT_PREFIX, id));
8567
+ const participant = entry && participantFromEntry(entry);
8568
+ return participant?.id === id ? participant : void 0;
8569
+ }
7486
8570
  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);
8571
+ const existing = this.#localRecords.get(this.options.identity.id) ?? this.#participant(this.options.identity.id);
7488
8572
  if (existing) {
7489
8573
  return {
7490
8574
  ...existing,
@@ -7524,6 +8608,38 @@ var ParticipantDirectory = class {
7524
8608
  return peer ? [peer] : [];
7525
8609
  });
7526
8610
  }
8611
+ /**
8612
+ * Root sessions that are no longer live, newest first: `stopped` from the
8613
+ * tombstone a clean close wrote, `lost` from a root record whose owner
8614
+ * lease expired without one. Explicit opt-in only; live queries never read
8615
+ * tombstones. Pure read: never writes or prunes.
8616
+ */
8617
+ departed(options = {}, now = Date.now()) {
8618
+ if (!this.options.enabled) return [];
8619
+ const hosts = this.#hosts();
8620
+ const live = /* @__PURE__ */ new Set([this.options.rootId]);
8621
+ const byId = /* @__PURE__ */ new Map();
8622
+ for (const entry of this.mesh.listAll(PARTICIPANT_PREFIX)) {
8623
+ const participant = participantFromEntry(entry);
8624
+ if (participant?.kind !== "root") continue;
8625
+ if (liveOwner(participant, hosts, now)) {
8626
+ live.add(participant.id);
8627
+ continue;
8628
+ }
8629
+ const owner = hosts.get(participant.ownerHostId);
8630
+ const heartbeat = owner?.identity.id === participant.ownerIdentityId ? owner.updatedAt : 0;
8631
+ byId.set(participant.id, departedFromRoot(participant, "lost", Math.max(participant.updatedAt, heartbeat)));
8632
+ }
8633
+ for (const entry of this.mesh.listAll(TOMBSTONE_PREFIX)) {
8634
+ const tombstone = tombstoneFromEntry(entry);
8635
+ if (!tombstone) continue;
8636
+ const lost = byId.get(tombstone.id);
8637
+ if (!lost || tombstone.lastSeenAt >= lost.lastSeenAt) byId.set(tombstone.id, tombstone);
8638
+ }
8639
+ const cutoff = now - this.#departedRetentionMs;
8640
+ const limit = Math.max(0, Math.floor(options.limit ?? (this.#departedLimit || DEPARTED_LIMIT)));
8641
+ 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);
8642
+ }
7527
8643
  root(main) {
7528
8644
  return {
7529
8645
  format: 1,
@@ -7560,8 +8676,12 @@ var ParticipantDirectory = class {
7560
8676
  this.#timer = void 0;
7561
8677
  await this.#refreshing?.catch(() => void 0);
7562
8678
  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 })));
8679
+ const owned = this.mesh.listAll(PARTICIPANT_PREFIX).flatMap((entry) => {
8680
+ const participant = participantFromEntry(entry);
8681
+ return participant?.ownerHostId === this.options.hostId ? [{ entry, participant }] : [];
8682
+ });
8683
+ await this.#writeTombstones(owned.map((item) => item.participant)).catch(() => void 0);
8684
+ await Promise.allSettled(owned.map(({ entry }) => this.mesh.delete({ key: entry.key, ifVersion: entry.version })));
7565
8685
  const legacySessionKey = this.#legacySessionKey();
7566
8686
  if (legacySessionKey) {
7567
8687
  const legacy = this.mesh.get(legacySessionKey);
@@ -7572,6 +8692,23 @@ var ParticipantDirectory = class {
7572
8692
  const hostEntry = this.mesh.get(keyFor(HOST_PREFIX, this.options.hostId));
7573
8693
  if (hostEntry) await this.mesh.delete({ key: hostEntry.key, ifVersion: hostEntry.version }).catch(() => void 0);
7574
8694
  }
8695
+ /** Replace this host's root records with stopped tombstones, then prune by age and count. */
8696
+ async #writeTombstones(owned) {
8697
+ if (this.#departedLimit === 0) return;
8698
+ const now = Date.now();
8699
+ for (const participant of owned) {
8700
+ if (participant.kind !== "root") continue;
8701
+ await this.mesh.put({
8702
+ key: keyFor(TOMBSTONE_PREFIX, participant.id),
8703
+ value: departedFromRoot(participant, "stopped", now),
8704
+ identity: this.options.identity
8705
+ }).catch(() => void 0);
8706
+ }
8707
+ const cutoff = now - this.#departedRetentionMs;
8708
+ const kept = this.mesh.listAll(TOMBSTONE_PREFIX).map((entry) => ({ entry, tombstone: tombstoneFromEntry(entry) })).sort((left, right) => (right.tombstone?.lastSeenAt ?? 0) - (left.tombstone?.lastSeenAt ?? 0));
8709
+ const prune = kept.filter(({ tombstone }, index) => !tombstone || tombstone.lastSeenAt < cutoff || index >= this.#departedLimit);
8710
+ await Promise.allSettled(prune.map(({ entry }) => this.mesh.delete({ key: entry.key, ifVersion: entry.version })));
8711
+ }
7575
8712
  async #refresh() {
7576
8713
  const now = Date.now();
7577
8714
  const desired = /* @__PURE__ */ new Map();
@@ -7713,15 +8850,46 @@ var ParticipantDirectory = class {
7713
8850
  record.label = existing.label;
7714
8851
  continue;
7715
8852
  }
7716
- const seq = await this.#claimPeerSeq();
7717
- if (seq !== void 0) record.label = `${peerLabelPrefix(record.cwd)}-${seq}`;
8853
+ const recorded = this.options.recordedLabel?.();
8854
+ if (recorded && this.#reusableLabel(recorded, record)) {
8855
+ record.label = recorded;
8856
+ continue;
8857
+ }
8858
+ if (this.options.labelWanted?.() === false) continue;
8859
+ for (let attempt = 0; attempt < MAX_HELD_LABEL_SKIPS; attempt += 1) {
8860
+ const seq = await this.#claimPeerSeq();
8861
+ if (seq === void 0) break;
8862
+ const label = `${peerLabelPrefix(record.cwd)}-${seq}`;
8863
+ if (this.#heldByOther(label, record.id)) continue;
8864
+ record.label = label;
8865
+ break;
8866
+ }
7718
8867
  }
7719
8868
  }
8869
+ /** A recorded label fits this project and no other participant holds it. */
8870
+ #reusableLabel(label, record) {
8871
+ return new RegExp(`^${peerLabelPrefix(record.cwd)}-[1-9][0-9]*$`).test(label) && !this.#heldByOther(label, record.id);
8872
+ }
8873
+ /** A live participant of another id holds the label; a dead session's leftover record does not. */
8874
+ #heldByOther(label, id) {
8875
+ const hosts = this.#hosts();
8876
+ const now = Date.now();
8877
+ return this.mesh.listAll(PARTICIPANT_PREFIX).some((entry) => {
8878
+ const participant = participantFromEntry(entry);
8879
+ return participant !== void 0 && participant.id !== id && participant.label === label && liveOwner(participant, hosts, now);
8880
+ });
8881
+ }
8882
+ #hosts() {
8883
+ return new Map(this.mesh.listAll(HOST_PREFIX).flatMap((entry) => {
8884
+ const host = hostFromEntry(entry);
8885
+ return host ? [[host.id, host]] : [];
8886
+ }));
8887
+ }
7720
8888
  /** CAS-claim the next project-wide peer sequence number. ifVersion 0 creates. */
7721
8889
  async #claimPeerSeq() {
7722
8890
  for (let attempt = 0; attempt < 8; attempt += 1) {
7723
8891
  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;
8892
+ 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
8893
  try {
7726
8894
  await this.mesh.put({
7727
8895
  key: PEER_SEQ_KEY,
@@ -7822,6 +8990,7 @@ export {
7822
8990
  resolvePiBinary,
7823
8991
  resolveInheritedSessionPins,
7824
8992
  withInheritedSessionPins,
8993
+ hasWorkerRecovery,
7825
8994
  isFabricWorktreePath,
7826
8995
  addCloneFirstWorktree,
7827
8996
  PiCodingAgent,
@@ -7836,6 +9005,8 @@ export {
7836
9005
  AgentManager,
7837
9006
  resolveActorDeliveryPolicy,
7838
9007
  actorDeliveryNotice,
9008
+ ActorStoreReadError,
9009
+ readStoreJson,
7839
9010
  ActorRegistryOwnershipError,
7840
9011
  ActorDirectory,
7841
9012
  LifecycleBroker,
@@ -7844,4 +9015,4 @@ export {
7844
9015
  agentParticipantRecords,
7845
9016
  actorParticipantRecord
7846
9017
  };
7847
- //# sourceMappingURL=chunk-FE6NOAO7.js.map
9018
+ //# sourceMappingURL=chunk-VNWQIGQL.js.map