@e4779/pi-fabric 0.117.2-fork.30 → 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
@@ -26,11 +26,9 @@ import {
26
26
  restoreFabricWritePreviews,
27
27
  restoreLegacyBashCommands,
28
28
  safeTerminalText,
29
+ shellBackgroundShortcut,
29
30
  singleCallProgressLine
30
- } from "./chunk-3UGN25XS.js";
31
- import {
32
- FabricModelSelector
33
- } from "./chunk-J7ZQERKA.js";
31
+ } from "./chunk-WWTGWGH7.js";
34
32
  import {
35
33
  configureHighlighting,
36
34
  highlightCode,
@@ -40,22 +38,19 @@ import {
40
38
  activeStatuses,
41
39
  isActiveStatus,
42
40
  orderAgentsByCreation
43
- } from "./chunk-UTOBAZ5T.js";
44
- import {
45
- buildModelSource
46
- } from "./chunk-CQFP2RCP.js";
41
+ } from "./chunk-37NIOSVU.js";
47
42
  import {
48
43
  animationFitsViewport,
49
44
  observeAnimationRows,
50
- spinnerFrame,
51
45
  updateSpinner
52
46
  } from "./chunk-O4A5UOXU.js";
53
47
  import {
48
+ borderBadge,
54
49
  formatCost,
55
50
  formatDuration,
56
51
  formatTokens,
57
52
  safeText
58
- } from "./chunk-IR3PIHJM.js";
53
+ } from "./chunk-FK73YJKV.js";
59
54
  import {
60
55
  repairFabricGuestCode
61
56
  } from "./chunk-VXZZJ44D.js";
@@ -83,76 +78,55 @@ import {
83
78
  resolveFabricIdentity,
84
79
  setModelSafely,
85
80
  withTrajectoryRearmDirective
86
- } from "./chunk-C7Z6F3SO.js";
81
+ } from "./chunk-ZFWICFNJ.js";
82
+ import {
83
+ AgentTranscriptReader
84
+ } from "./chunk-YHFWMAQ5.js";
87
85
  import {
88
- AgentTranscriptReader,
89
86
  countNewlines,
87
+ editDistance,
90
88
  truncateMiddle
91
- } from "./chunk-EKODKR6Y.js";
92
- import {
93
- FileLockTimeoutError
94
- } from "./chunk-DK35W6U7.js";
95
- import {
96
- FABRIC_COMPONENT_REGISTER_EVENT,
97
- FABRIC_NESTED_TOOL_CALL_ID_PREFIX,
98
- FABRIC_PEER_AWAIT_SETTLE_EVENT,
99
- FABRIC_PEER_CARDS_EVENT,
100
- FABRIC_PREWALK_REQUEST_EVENT,
101
- FABRIC_PROGRAM_RUN_EVENT,
102
- FABRIC_PROVIDER_REGISTER_EVENT,
103
- FABRIC_PROVIDER_WITHDRAW_EVENT,
104
- FABRIC_TOOL_PLACEMENT_EVENT,
105
- readFabricPeerAwaitSettleRequestV1,
106
- readFabricPeerCardsRequestV1,
107
- readFabricPrewalkRequestV1,
108
- readFabricProviderWithdrawalV1,
109
- readFabricToolPlacementRequestV1
110
- } from "./chunk-Q2JQ3RYZ.js";
89
+ } from "./chunk-P3DCXKL3.js";
111
90
  import {
112
- awaitPeerSettle,
113
- buildPeerCards,
114
- readChildToolAllowlist
115
- } from "./chunk-PYFJW3HC.js";
91
+ closeScratch,
92
+ createScratch
93
+ } from "./chunk-7YNE4NB2.js";
116
94
  import {
117
95
  resolveAgentDir
118
96
  } from "./chunk-PBDDXBHY.js";
119
- import {
120
- closeScratch,
121
- createScratch
122
- } from "./chunk-5XBYFSI5.js";
123
97
  import {
124
98
  DEFAULT_FABRIC_CONFIG,
99
+ MAX_FOREGROUND_TOOLS,
125
100
  NO_FOREGROUND,
126
101
  effectiveToolCaptureConfig,
102
+ foregroundConfigValue,
127
103
  formatForeground,
104
+ ineffectiveKeepVisible,
128
105
  loadFabricConfig,
129
106
  loadFabricConfigForScope,
130
- resolveForegroundTools,
131
- saveFabricConfig
132
- } from "./chunk-K7J2ABAZ.js";
107
+ resolveForegroundTools
108
+ } from "./chunk-4KX6BIPL.js";
133
109
  import {
134
110
  defaultCodePreviewSettings
135
111
  } from "./chunk-OKOHRXGF.js";
136
112
  import {
137
113
  compactAtConfiguredThreshold,
138
- fabricExecTitleHintCached,
139
- normalizeRunDisplay,
140
- registerCompactionHook
141
- } from "./chunk-ROTCDDOV.js";
114
+ fabricExecTitleHintCached
115
+ } from "./chunk-3VK6UGAN.js";
142
116
  import {
143
117
  fabricWriteBindings
144
118
  } from "./chunk-SZUXWOO7.js";
145
119
  import {
146
- FABRIC_EXECUTION_GUIDANCE_SLOT,
147
- resolveFabricModelGuidance
148
- } from "./chunk-UKMQK5VP.js";
120
+ FileLockTimeoutError
121
+ } from "./chunk-WKFRGICG.js";
149
122
  import {
150
- FABRIC_ACTOR_PI_HOST_EVENTS
151
- } from "./chunk-IIPKG52D.js";
123
+ ACTION_POLICY_HOOK_NAME_PATTERN,
124
+ FabricActionPolicyHooks
125
+ } from "./chunk-N7ZAK2PB.js";
152
126
  import {
153
- FABRIC_THINKING_BOUNDS_ENV,
154
- FABRIC_THINKING_ENTRY_TYPE
155
- } from "./chunk-V73NIH6B.js";
127
+ PI_CORE_TOOL_NAMES,
128
+ PI_CORE_TOOL_NAME_SET
129
+ } from "./chunk-YU62DDKK.js";
156
130
  import {
157
131
  registerJevAuth
158
132
  } from "./chunk-5X35KXBV.js";
@@ -160,19 +134,62 @@ import {
160
134
  ApprovalController,
161
135
  FabricAutoApprovalClassifier,
162
136
  FabricSessionApprovals
163
- } from "./chunk-UOM37PE4.js";
137
+ } from "./chunk-4PBW54I2.js";
164
138
  import {
165
139
  getActiveRepairCompiler,
166
140
  setActiveCompiledSurface
167
- } from "./chunk-53N2I4QA.js";
141
+ } from "./chunk-TXCNZCZP.js";
142
+ import {
143
+ FABRIC_ACTION_POLICY_REGISTER_EVENT,
144
+ FABRIC_COMPACTION_OWNER_EVENT,
145
+ FABRIC_COMPONENT_REGISTER_EVENT,
146
+ FABRIC_DECISIONS_CAPABILITY_EVENT,
147
+ FABRIC_DECISION_REQUEST_EVENT,
148
+ FABRIC_EXECUTION_GUIDANCE_SLOT,
149
+ FABRIC_HOST_POLICY_EVENT,
150
+ FABRIC_HOST_POLICY_FIELDS,
151
+ FABRIC_NESTED_TOOL_CALL_ID_PREFIX,
152
+ FABRIC_PEER_AWAIT_SETTLE_EVENT,
153
+ FABRIC_PEER_CARDS_EVENT,
154
+ FABRIC_PREWALK_REQUEST_EVENT,
155
+ FABRIC_PROGRAM_RUN_EVENT,
156
+ FABRIC_PROVIDER_REGISTER_EVENT,
157
+ FABRIC_PROVIDER_WITHDRAW_EVENT,
158
+ FABRIC_QUESTION_RENDERER_REGISTER_EVENT,
159
+ FABRIC_TOOL_PLACEMENT_EVENT,
160
+ readFabricActionPolicyRegistrationV1,
161
+ readFabricDecisionRequestV1,
162
+ readFabricDecisionsCapabilityRequestV1,
163
+ readFabricHostPolicyRequestV1,
164
+ readFabricPeerAwaitSettleRequestV1,
165
+ readFabricPeerCardsRequestV1,
166
+ readFabricPrewalkRequestV1,
167
+ readFabricProviderWithdrawalV1,
168
+ readFabricQuestionRendererRegistrationV1,
169
+ readFabricToolPlacementRequestV1,
170
+ resolveFabricModelGuidance,
171
+ snapshotFabricProgramRunRequestV1
172
+ } from "./chunk-2RWNVCFD.js";
173
+ import {
174
+ normalizeRunDisplay
175
+ } from "./chunk-OZCJU3PZ.js";
168
176
  import {
169
177
  isFabricExecutionTraceV1,
170
178
  readFabricExecutionTraceV1
171
- } from "./chunk-MLLYR3Y6.js";
179
+ } from "./chunk-PUBHBEYO.js";
172
180
  import {
173
- PI_CORE_TOOL_NAMES,
174
- PI_CORE_TOOL_NAME_SET
175
- } from "./chunk-YU62DDKK.js";
181
+ stableJsonHash
182
+ } from "./chunk-3YZUQESG.js";
183
+ import {
184
+ FABRIC_ACTOR_PI_HOST_EVENTS
185
+ } from "./chunk-IIPKG52D.js";
186
+ import {
187
+ FABRIC_THINKING_BOUNDS_ENV,
188
+ FABRIC_THINKING_ENTRY_TYPE
189
+ } from "./chunk-V73NIH6B.js";
190
+ import {
191
+ readChildToolAllowlist
192
+ } from "./chunk-6OGYPHNQ.js";
176
193
 
177
194
  // src/audit/details.ts
178
195
  var FABRIC_EXECUTION_DETAILS_MAX_BYTES = 512 * 1024;
@@ -207,7 +224,13 @@ var createFabricPersistedExecutionDetails = (input) => {
207
224
  ...input.outputFormatLines !== void 0 ? { outputFormatLines: Math.max(0, Math.floor(input.outputFormatLines)) } : {}
208
225
  };
209
226
  while (serializedBytes(details) > FABRIC_EXECUTION_DETAILS_MAX_BYTES && details.audits.length > 0) {
210
- details.audits.pop();
227
+ const dropped = details.audits.pop();
228
+ const omitted = details.omittedCalls ?? { count: 0, done: 0 };
229
+ details.omittedCalls = {
230
+ count: omitted.count + 1,
231
+ done: omitted.done + (dropped.success !== void 0 ? 1 : 0),
232
+ ...(omitted.failed ?? 0) + (dropped.success === false ? 1 : 0) > 0 ? { failed: (omitted.failed ?? 0) + (dropped.success === false ? 1 : 0) } : {}
233
+ };
211
234
  }
212
235
  while (serializedBytes(details) > FABRIC_EXECUTION_DETAILS_MAX_BYTES && details.assessment && details.assessment.operations.length > 0) {
213
236
  details.assessment.operations.pop();
@@ -273,8 +296,98 @@ var readFabricExecutionRenderDetails = (value) => {
273
296
  ...typeof value.outputFormatStartLine === "number" && Number.isFinite(value.outputFormatStartLine) && value.outputFormatStartLine >= 0 ? { outputFormatStartLine: Math.floor(value.outputFormatStartLine) } : {},
274
297
  ...typeof value.outputFormatLines === "number" && Number.isFinite(value.outputFormatLines) && value.outputFormatLines >= 0 ? { outputFormatLines: Math.floor(value.outputFormatLines) } : {},
275
298
  phases: oldPhases ?? trace?.phases ?? [],
276
- audits: oldAudits ?? trace?.operations.map(auditFromOperation) ?? []
299
+ audits: oldAudits ?? trace?.operations.map(auditFromOperation) ?? [],
300
+ ...omittedCalls(value.omittedCalls) ?? {}
301
+ };
302
+ };
303
+ var omittedCalls = (value) => {
304
+ if (!isRecord(value)) return void 0;
305
+ const { count, done, failed } = value;
306
+ if (typeof count !== "number" || !Number.isInteger(count) || count <= 0) return void 0;
307
+ const finished = typeof done === "number" && Number.isInteger(done) ? Math.min(Math.max(0, done), count) : 0;
308
+ const failures = typeof failed === "number" && Number.isInteger(failed) ? Math.min(Math.max(0, failed), finished) : 0;
309
+ return { omittedCalls: { count, done: finished, ...failures > 0 ? { failed: failures } : {} } };
310
+ };
311
+ var FABRIC_PARTIAL_AUDITS_MAX_BYTES = 128 * 1024;
312
+ var FABRIC_PARTIAL_UPDATE_MAX_BYTES = 256 * 1024;
313
+ var PARTIAL_HEAD_AUDITS = 30;
314
+ var PARTIAL_TAIL_AUDITS = 30;
315
+ var PARTIAL_PHASES = 64;
316
+ var PARTIAL_PROGRESS_CHARS = 8e3;
317
+ var SLIM_ARG_KEYS = 8;
318
+ var SLIM_TEXT_CHARS = 240;
319
+ var clipText = (value, max) => value.length <= max ? value : `${value.slice(0, max)}\u2026`;
320
+ var slimAudit = (audit) => {
321
+ const args = {};
322
+ for (const [key, value] of Object.entries(audit.args ?? {}).slice(0, SLIM_ARG_KEYS)) {
323
+ if (typeof value === "string") args[key] = clipText(value, SLIM_TEXT_CHARS);
324
+ else if (typeof value === "number" || typeof value === "boolean" || value === null) args[key] = value;
325
+ }
326
+ return {
327
+ ref: audit.ref,
328
+ ...audit.nestedToolCallId !== void 0 ? { nestedToolCallId: audit.nestedToolCallId } : {},
329
+ ...audit.tool !== void 0 ? { tool: audit.tool } : {},
330
+ ...audit.provider !== void 0 ? { provider: audit.provider } : {},
331
+ ...audit.success !== void 0 ? { success: audit.success } : {},
332
+ ...audit.error !== void 0 ? { error: clipText(audit.error, SLIM_TEXT_CHARS) } : {},
333
+ ...Object.keys(args).length > 0 ? { args } : {},
334
+ ...audit.startedAt !== void 0 ? { startedAt: audit.startedAt } : {},
335
+ ...audit.endedAt !== void 0 ? { endedAt: audit.endedAt } : {}
336
+ };
337
+ };
338
+ var createFabricPartialExecutionDetails = (input) => {
339
+ const total = input.audits.length;
340
+ const running = [];
341
+ for (let index = 0; index < total; index++) {
342
+ if (input.audits[index].success === void 0) running.push(index);
343
+ }
344
+ const candidates = new Set(running.slice(-PARTIAL_TAIL_AUDITS).reverse());
345
+ for (let index = total - 1; index >= Math.max(0, total - PARTIAL_TAIL_AUDITS); index--) candidates.add(index);
346
+ for (let index = 0; index < Math.min(total, PARTIAL_HEAD_AUDITS); index++) candidates.add(index);
347
+ const kept = /* @__PURE__ */ new Map();
348
+ let used = 0;
349
+ for (const index of candidates) {
350
+ const full = persistableAudit(input.audits[index]);
351
+ const fullBytes = serializedBytes(full);
352
+ if (used + fullBytes <= FABRIC_PARTIAL_AUDITS_MAX_BYTES) {
353
+ kept.set(index, full);
354
+ used += fullBytes;
355
+ continue;
356
+ }
357
+ const slim = slimAudit(full);
358
+ const slimBytes = serializedBytes(slim);
359
+ if (used + slimBytes <= FABRIC_PARTIAL_AUDITS_MAX_BYTES) {
360
+ kept.set(index, slim);
361
+ used += slimBytes;
362
+ }
363
+ }
364
+ const audits = [...kept.keys()].sort((left, right) => left - right).map((index) => kept.get(index));
365
+ let omittedDone = 0;
366
+ let omittedFailed = 0;
367
+ for (let index = 0; index < total; index++) {
368
+ if (!kept.has(index)) {
369
+ if (input.audits[index].success !== void 0) omittedDone++;
370
+ if (input.audits[index].success === false) omittedFailed++;
371
+ }
372
+ }
373
+ const omitted = total - audits.length;
374
+ const progress = input.progress === void 0 || input.progress.length <= PARTIAL_PROGRESS_CHARS ? input.progress : `\u2026${input.progress.slice(-PARTIAL_PROGRESS_CHARS)}`;
375
+ const details = {
376
+ ...progress !== void 0 ? { progress } : {},
377
+ ...input.deadlineAt !== void 0 ? { deadlineAt: input.deadlineAt } : {},
378
+ phases: [],
379
+ audits,
380
+ ...omitted > 0 ? { omittedCalls: { count: omitted, done: omittedDone, ...omittedFailed > 0 ? { failed: omittedFailed } : {} } } : {}
277
381
  };
382
+ let bytes = serializedBytes({ content: [{ type: "text", text: progress ?? "" }], details });
383
+ for (let index = input.phases.length - 1; index >= Math.max(0, input.phases.length - PARTIAL_PHASES); index--) {
384
+ const phase = clipText(input.phases[index], SLIM_TEXT_CHARS);
385
+ const extra = serializedBytes(phase) + (details.phases.length > 0 ? 1 : 0);
386
+ if (bytes + extra > FABRIC_PARTIAL_UPDATE_MAX_BYTES) break;
387
+ details.phases.unshift(phase);
388
+ bytes += extra;
389
+ }
390
+ return details;
278
391
  };
279
392
 
280
393
  // src/ui/code-preview-shell.ts
@@ -771,6 +884,10 @@ var installRegisteredToolCapture = async (options) => {
771
884
  };
772
885
  };
773
886
 
887
+ // src/ui/widget-keys.ts
888
+ var FABRIC_WIDGET_FOCUS_SHORTCUT = "ctrl+shift+e";
889
+ var FABRIC_WIDGET_FOCUS_HINT = "\u2193 to manage";
890
+
774
891
  // src/prewalk/arm.ts
775
892
  var armFabricPrewalkSession = async (state, context, pi, input) => {
776
893
  const { prewalk } = state.config;
@@ -948,193 +1065,23 @@ var settleInPlacePrewalk = async (controller, extension, context, options) => {
948
1065
  return true;
949
1066
  };
950
1067
 
951
- // src/ui/conversation-shortcut.ts
952
- var FABRIC_CONVERSATION_SHORTCUT = "ctrl+shift+a";
953
- var FABRIC_CONVERSATION_HINT = "ctrl+shift+a chat";
954
-
955
- // src/ui/widget-activity.ts
956
- import { truncateToWidth as truncateToWidth2, visibleWidth as visibleWidth2, wrapTextWithAnsi } from "@earendil-works/pi-tui";
957
- var FABRIC_WIDGET_FOCUS_SHORTCUT = "ctrl+shift+e";
958
- var FABRIC_WIDGET_FOCUS_HINT = "ctrl+shift+e expand";
959
- var WIDGET_ACTIVITY_ROWS = 12;
960
- var WIDGET_ACTIVITY_LOG_LINES = 600;
961
- var ENTRY_TEXT_LINES = 4;
962
- var toolGlyph = (theme, status) => status === "running" ? theme.fg("accent", "\u25D0") : status === "failed" ? theme.fg("error", "\u2717") : theme.fg("success", "\u2713");
963
- var oneLine = (value) => safeText(value ?? "").replace(/\s+/g, " ").trim();
964
- var tailLines = (text, width, count) => {
965
- const wrapped = text.split("\n").flatMap((paragraph) => wrapTextWithAnsi(paragraph, Math.max(1, width))).filter((line) => line.trim().length > 0);
966
- return wrapped.slice(-count);
967
- };
968
- var entryLines = (theme, entry, width, hideThinking) => {
969
- const inner = Math.max(1, width - 4);
970
- const body = (text, color) => text ? tailLines(safeText(text), inner, ENTRY_TEXT_LINES).map((line) => ` ${theme.fg(color, line)}`) : [];
971
- switch (entry.kind) {
972
- case "thinking":
973
- return [
974
- ` ${theme.fg("dim", entry.status === "running" ? "\u2234 thinking\u2026" : "\u2234 thinking")}`,
975
- // Pi's hideThinkingBlock keeps the marker and drops the reasoning text, as in its own chat.
976
- ...hideThinking ? [] : body(entry.text, "dim")
977
- ];
978
- case "tool": {
979
- const args = oneLine(entry.text);
980
- return [
981
- ` ${toolGlyph(theme, entry.status)} ${theme.fg("toolTitle", theme.bold(safeText(entry.toolName ?? entry.label)))}${args ? theme.fg("dim", ` ${args}`) : ""}`
982
- ];
983
- }
984
- case "assistant":
985
- return [` ${theme.fg("accent", "\u25C6")} ${theme.fg("accent", safeText(entry.label))}`, ...body(entry.text, "muted")];
986
- case "user":
987
- return [` ${theme.fg("muted", "\u203A")} ${theme.fg("muted", oneLine(entry.text) || safeText(entry.label))}`];
988
- case "error":
989
- return [` ${theme.fg("error", "\u2717")} ${theme.fg("error", safeText(entry.label))}`, ...body(entry.text, "muted")];
990
- default:
991
- return [` ${theme.fg("dim", "\xB7")} ${theme.fg("dim", `${safeText(entry.label)}${entry.text ? ` ${oneLine(entry.text)}` : ""}`)}`];
992
- }
993
- };
994
- var widgetActivityLines = (theme, transcript, width, rows, scroll, hideThinking = false) => {
995
- if (!transcript || transcript.entries.length === 0) {
996
- return { lines: [` ${theme.fg("dim", "Waiting for activity\u2026")}`], maxScroll: 0 };
997
- }
998
- const all = transcript.entries.flatMap((entry) => entryLines(theme, entry, width, hideThinking));
999
- const maxScroll = Math.max(0, all.length - rows);
1000
- const offset = Math.max(0, Math.min(scroll, maxScroll));
1001
- const end = all.length - offset;
1002
- const lines = all.slice(Math.max(0, end - rows), end).map((line) => truncateToWidth2(line, width, "\u2026"));
1003
- return { lines, maxScroll };
1004
- };
1005
- var widgetDivider = (theme, width, label = "") => {
1006
- const text = label ? ` ${label} ` : "";
1007
- return theme.fg("border", `\u2500\u2500${text}${"\u2500".repeat(Math.max(0, width - 2 - visibleWidth2(text)))}`);
1008
- };
1009
-
1010
1068
  // src/commands/fabric.ts
1011
- import fs from "node:fs";
1012
- import path2 from "node:path";
1013
- var extractContentText = (content) => {
1014
- if (typeof content === "string") return content;
1015
- if (Array.isArray(content)) {
1016
- return content.map((part) => {
1017
- if (typeof part !== "object" || part === null) return "";
1018
- const p = part;
1019
- return typeof p.text === "string" ? p.text : typeof p.type === "string" ? p.type : "";
1020
- }).filter(Boolean).join(" ");
1021
- }
1022
- return "";
1023
- };
1024
- var summarizeLogLine = (entry) => {
1025
- if (typeof entry !== "object" || entry === null) return truncateMiddle(String(entry), 200);
1026
- const record = entry;
1027
- const type = typeof record.type === "string" ? record.type : void 0;
1028
- const tool = typeof record.toolName === "string" ? record.toolName : void 0;
1029
- const msg = record.message;
1030
- if (typeof msg === "object" && msg !== null && !Array.isArray(msg)) {
1031
- const m = msg;
1032
- const role = typeof m.role === "string" ? m.role : "message";
1033
- const model = typeof m.model === "string" ? m.model : void 0;
1034
- const text = extractContentText(m.content);
1035
- const body = (text || JSON.stringify(m)).replace(/\s+/g, " ");
1036
- return `${role}${model ? ` [${model}]` : ""}: ${truncateMiddle(body, 160)}`;
1037
- }
1038
- if (type) {
1039
- const bits = [type];
1040
- if (tool) bits.push(tool);
1041
- const model = typeof record.modelId === "string" ? record.modelId : void 0;
1042
- const provider = typeof record.provider === "string" && !model ? record.provider : void 0;
1043
- if (provider) bits.push(provider);
1044
- if (model) bits.push(model);
1045
- return bits.join(" ");
1046
- }
1047
- return truncateMiddle(JSON.stringify(record), 160);
1048
- };
1049
- var resolvePrewalkModel = async (state, context) => {
1050
- const configured = state.config.prewalk.model?.trim();
1051
- if (configured) {
1052
- if (configured.includes("/")) return configured;
1053
- context.ui.notify(
1054
- "prewalk.model must use provider/model form.",
1055
- "error"
1056
- );
1057
- return void 0;
1058
- }
1059
- let models = [];
1060
- try {
1061
- models = context.modelRegistry.getAvailable();
1062
- } catch {
1063
- models = [];
1064
- }
1065
- const keys = models.map((model) => `${model.provider}/${model.id}`).sort((left, right) => left.localeCompare(right));
1066
- if (keys.length === 0) {
1067
- context.ui.notify(
1068
- "Prewalk needs an explicit Pi executor model. Configure prewalk.model in /fabric settings.",
1069
- "error"
1070
- );
1071
- return void 0;
1072
- }
1073
- if (!context.hasUI) {
1074
- context.ui.notify(
1075
- "Prewalk needs prewalk.model in non-interactive mode.",
1076
- "error"
1077
- );
1078
- return void 0;
1079
- }
1080
- if (typeof context.ui.custom === "function") {
1081
- try {
1082
- const picked = await context.ui.custom(
1083
- (_tui, theme, _keybindings, done) => new FabricModelSelector({
1084
- theme,
1085
- source: buildModelSource(context.modelRegistry, resolveAgentDir()),
1086
- currentValue: "",
1087
- headerText: "Prewalk executor model. Fabric hands off at the next matching mutation boundary; Main continues on the picked model.",
1088
- inheritRow: false,
1089
- onSelect: (value) => done({ model: value }),
1090
- onCancel: () => done({ model: void 0 })
1091
- })
1092
- );
1093
- if (picked !== void 0) return picked.model;
1094
- } catch {
1095
- }
1096
- }
1097
- return context.ui.select("Prewalk executor model", keys);
1098
- };
1099
- var armPrewalk = async (state, context, pi, task = "") => {
1100
- if (state.config.prewalk.enabled === false) {
1101
- const error = "Fabric prewalk is disabled; re-enable with /fabric prewalk --enable or /fabric settings.";
1102
- context.ui.notify(error, "error");
1103
- return { ok: false, error };
1104
- }
1105
- if (!state.config.fullCodeMode || state.config.schema.mode === "enforce") {
1106
- const error = "Fabric prewalk requires full code mode and Schema enforce mode disabled.";
1107
- context.ui.notify(error, "error");
1108
- return { ok: false, error };
1109
- }
1110
- if (state.config.prewalk.mode === "trajectory" && !state.config.agents.enabled) {
1111
- const error = "Trajectory prewalk requires enabled agents. Choose in-place mode or enable agents.";
1112
- context.ui.notify(error, "error");
1113
- return { ok: false, error };
1114
- }
1115
- const model = await resolvePrewalkModel(state, context);
1116
- if (!model) return { ok: false, error: "Fabric prewalk was not armed." };
1117
- await armFabricPrewalkSession(state, context, pi, {
1118
- model,
1119
- ...task ? { task } : {}
1120
- });
1121
- const modeLabel = state.config.prewalk.mode === "in-place" ? "Main will continue in place" : "the trajectory will move to a visible child executor";
1122
- context.ui.notify(
1123
- task ? `Fabric prewalk armed for the next matching Fabric boundary; ${modeLabel} with ${model}${state.config.prewalk.alwaysRearm ? "; always re-arm enabled" : ""}` : `Fabric prewalk armed for the next task; ${modeLabel} with ${model}${state.config.prewalk.alwaysRearm ? "; always re-arm enabled" : ""}`,
1124
- "info"
1125
- );
1126
- if (task) pi.sendUserMessage(task);
1127
- return { ok: true };
1069
+ var commandHost = {
1070
+ armFabricPrewalkSession,
1071
+ restoreBorrowedInPlaceMain,
1072
+ setActiveCompiledSurface,
1073
+ truncateMiddle
1128
1074
  };
1129
1075
  function registerFabricCommand(pi, deps) {
1130
- const { state, fabricUi, capturedTools, applyFabricMode, suspendToolCapture } = deps;
1076
+ const { state, fabricUi } = deps;
1131
1077
  const unsubscribePrewalkRequests = pi.events?.on?.(FABRIC_PREWALK_REQUEST_EVENT, (value) => {
1132
1078
  const request = readFabricPrewalkRequestV1(value);
1133
1079
  if (!request || !request.claim()) return;
1134
1080
  void (async () => {
1135
1081
  try {
1136
1082
  await state.ensure(request.context);
1137
- request.respond(await armPrewalk(state, request.context, pi));
1083
+ const { armPrewalk } = await import("../commands/fabric-handler.js");
1084
+ request.respond(await armPrewalk(commandHost, state, request.context, pi));
1138
1085
  } catch (error) {
1139
1086
  request.respond({
1140
1087
  ok: false,
@@ -1152,6 +1099,7 @@ function registerFabricCommand(pi, deps) {
1152
1099
  void (async () => {
1153
1100
  try {
1154
1101
  await state.ensure(request.context);
1102
+ const { buildPeerCards } = await import("../topology/peer-settle.js");
1155
1103
  request.respond({ ok: true, cards: buildPeerCards(state.peerInfos()) });
1156
1104
  } catch (error) {
1157
1105
  request.respond({
@@ -1171,6 +1119,7 @@ function registerFabricCommand(pi, deps) {
1171
1119
  request.respond({ ok: false, error: "Fabric mesh is disabled; peers cannot be observed" });
1172
1120
  return;
1173
1121
  }
1122
+ const { awaitPeerSettle } = await import("../topology/peer-settle.js");
1174
1123
  request.respond(await awaitPeerSettle({
1175
1124
  poll: () => state.peerInfos(),
1176
1125
  ...request.selector !== void 0 ? { selector: request.selector } : {},
@@ -1192,52 +1141,43 @@ function registerFabricCommand(pi, deps) {
1192
1141
  unsubscribePeerAwait?.();
1193
1142
  });
1194
1143
  }
1195
- const formatRepairStatus = (status) => {
1196
- const top = status.fingerprints.slice(0, 8).map((entry) => ` ${entry.count}\xD7 ${entry.fingerprint}`).join("\n");
1197
- const rows = status.repairs.slice(0, 12).map(
1198
- (repair) => repair.kind === "keyAlias" ? ` ${repair.ref}: ${repair.from} \u2192 ${repair.to}` : ` ${repair.provider}.${repair.from} \u2192 ${repair.to}`
1199
- ).join("\n");
1200
- return [
1201
- `repairs: ${status.enabled ? "on" : "off"} \xB7 digest ${status.catalogDigest.slice(0, 12) || "none"}`,
1202
- `table: ${status.repairCount} \xB7 apply hits ${status.applyHits} \xB7 invocation ${status.invocationErrors} \xB7 effect dropped ${status.effectDropped}`,
1203
- status.repairs.length > 0 ? `current:
1204
- ${rows}` : "current: (empty)",
1205
- ...status.storeError ? [`store: ${status.storeError}`] : [],
1206
- top ? `fingerprints:
1207
- ${top}` : "fingerprints: (none this session)"
1208
- ].join("\n");
1144
+ const resolveDecisions = async (context) => {
1145
+ await state.ensure(context);
1146
+ if (!state.config.mesh.enabled) return { reason: "Fabric mesh is disabled; durable decisions are unavailable" };
1147
+ const store = state.decisionStore();
1148
+ return store ? { store } : { reason: "Durable decisions are unavailable in this Fabric host" };
1209
1149
  };
1210
- pi.registerShortcut?.(FABRIC_CONVERSATION_SHORTCUT, {
1211
- description: "Open Fabric conversation or return to Main",
1212
- handler: async (context) => {
1213
- if (context.mode !== "tui") return;
1214
- try {
1215
- await state.ensure(context);
1216
- await fabricUi.openConversation(context);
1217
- } catch (error) {
1218
- context.ui.notify(safeText(error instanceof Error ? error.message : String(error)), "error");
1219
- }
1220
- }
1150
+ const unsubscribeDecisionsCapability = pi.events?.on?.(FABRIC_DECISIONS_CAPABILITY_EVENT, (value) => {
1151
+ const request = readFabricDecisionsCapabilityRequestV1(value);
1152
+ if (!request || !request.claim()) return;
1153
+ void import("../decisions/events.js").then(
1154
+ ({ answerFabricDecisionsCapability }) => answerFabricDecisionsCapability(request, resolveDecisions),
1155
+ (error) => request.respond({ ok: false, error: `Fabric decisions unavailable: ${String(error)}` })
1156
+ );
1157
+ });
1158
+ const decisionRequests = new AbortController();
1159
+ const unsubscribeDecisionRequest = pi.events?.on?.(FABRIC_DECISION_REQUEST_EVENT, (value) => {
1160
+ const request = readFabricDecisionRequestV1(value);
1161
+ if (!request || !request.claim()) return;
1162
+ void import("../decisions/events.js").then(
1163
+ ({ answerFabricDecisionRequest }) => answerFabricDecisionRequest(request, resolveDecisions, decisionRequests.signal),
1164
+ (error) => request.respond({ ok: false, error: `Fabric decisions unavailable: ${String(error)}` })
1165
+ );
1221
1166
  });
1167
+ if (unsubscribeDecisionsCapability || unsubscribeDecisionRequest) {
1168
+ pi.on("session_shutdown", () => {
1169
+ unsubscribeDecisionsCapability?.();
1170
+ unsubscribeDecisionRequest?.();
1171
+ decisionRequests.abort();
1172
+ });
1173
+ }
1222
1174
  pi.registerShortcut?.(FABRIC_WIDGET_FOCUS_SHORTCUT, {
1223
- description: "Focus the Fabric widget to expand an agent's live activity",
1175
+ description: "Focus the Fabric agent list",
1224
1176
  handler: async (context) => {
1225
1177
  if (context.mode !== "tui") return;
1226
1178
  fabricUi.focusWidget(context);
1227
1179
  }
1228
1180
  });
1229
- pi.registerShortcut?.("ctrl+alt+t", {
1230
- description: "Inspect Fabric background shell tasks",
1231
- handler: async (context) => {
1232
- if (context.mode !== "tui") return;
1233
- try {
1234
- await state.ensure(context);
1235
- await fabricUi.openTasks(context);
1236
- } catch (error) {
1237
- context.ui.notify(safeText(error instanceof Error ? error.message : String(error)), "error");
1238
- }
1239
- }
1240
- });
1241
1181
  pi.registerCommand("fabric", {
1242
1182
  description: "Open Fabric dashboard, chat or tasks, arm prewalk, reload, or manage agents and actors",
1243
1183
  getArgumentCompletions: (argumentPrefix) => {
@@ -1372,742 +1312,16 @@ ${top}` : "fingerprints: (none this session)"
1372
1312
  const filtered = items.filter((item) => item.value.startsWith(idPrefix));
1373
1313
  return filtered.length > 0 ? filtered : null;
1374
1314
  },
1315
+ // The subcommands load at first use, not while registering the command.
1375
1316
  async handler(argumentsText, context) {
1376
- await state.ensure(context);
1377
- const [command = "dashboard", ...argumentsList] = argumentsText.trim().split(/\s+/).filter(Boolean);
1378
- if (command === "reload") {
1379
- fabricUi.stop();
1380
- suspendToolCapture();
1381
- try {
1382
- await state.initialize(context);
1383
- } catch (error) {
1384
- fabricUi.stop();
1385
- suspendToolCapture();
1386
- throw error;
1387
- }
1388
- if (state.kernelReloadRequired) {
1389
- await context.reload();
1390
- return;
1391
- }
1392
- await restoreBorrowedInPlaceMain(state.prewalk, pi, context);
1393
- context.ui.notify("Pi Fabric reloaded", "info");
1394
- deps.refreshToolDisplay?.();
1395
- return;
1396
- }
1397
- if (command === "settings") {
1398
- const { openFabricSettings } = await import("../ui/settings.js");
1399
- await openFabricSettings(context, {
1400
- reloadResources: () => context.reload(),
1401
- state,
1402
- applyFabricMode,
1403
- capturedTools,
1404
- // Only card-affecting preferences pay for a transcript refresh:
1405
- // refreshToolDisplay re-renders every fabric_exec card, so gating it
1406
- // on the display sections keeps unrelated saves off the transcript.
1407
- onConfigApplied: (id) => {
1408
- if (id.startsWith("codePreview.")) {
1409
- deps.refreshCodePreviewSettings?.();
1410
- deps.refreshToolDisplay?.();
1411
- } else if (id === "ui.toolDisplay" || id === "ui.showAgentToolPreview") {
1412
- deps.refreshToolDisplay?.();
1413
- }
1414
- }
1415
- });
1416
- return;
1417
- }
1418
- if (command === "schema") {
1419
- const requested = argumentsList[0];
1420
- if (requested === void 0) {
1421
- const status = state.schemaStatus(context);
1422
- context.ui.notify(
1423
- `Schema mode: ${status.mode} (${status.source}) \xB7 executor: ${status.executorRuntime} \xB7 /fabric schema [off|audit|enforce] overrides this session only`,
1424
- "info"
1425
- );
1426
- return;
1427
- }
1428
- if (requested !== "off" && requested !== "audit" && requested !== "enforce") {
1429
- context.ui.notify("Usage: /fabric schema [off|audit|enforce]", "warning");
1430
- return;
1431
- }
1432
- try {
1433
- state.setSchemaMode(context, requested);
1434
- } catch (error) {
1435
- context.ui.notify(
1436
- error instanceof Error ? error.message : String(error),
1437
- "error"
1438
- );
1439
- return;
1440
- }
1441
- context.ui.notify(
1442
- `Schema mode set to ${requested} for this session (config file unchanged; the next session starts from the configured mode)`,
1443
- "info"
1444
- );
1445
- return;
1446
- }
1447
- if (command === "prewalk") {
1448
- const option = argumentsList[0];
1449
- if (option === "--disable" || option === "--enable") {
1450
- const enabled = option === "--enable";
1451
- try {
1452
- const projectTrusted = context.isProjectTrusted();
1453
- const saved = saveFabricConfig(
1454
- {
1455
- cwd: context.cwd,
1456
- agentDir: resolveAgentDir(),
1457
- projectTrusted,
1458
- scope: projectTrusted ? "project" : "global"
1459
- },
1460
- { prewalk: { enabled } }
1461
- );
1462
- state.reloadConfig(context);
1463
- if (!enabled) {
1464
- state.prewalk.cancel();
1465
- state.prewalkDrift.drop(context.sessionManager.getSessionId());
1466
- context.ui.setStatus("fabric-prewalk", void 0);
1467
- await restoreBorrowedInPlaceMain(state.prewalk, pi, context);
1468
- }
1469
- context.ui.notify(
1470
- `Fabric prewalk ${enabled ? "enabled" : "disabled"} (${saved.scope}: ${saved.path})`,
1471
- "info"
1472
- );
1473
- } catch (error) {
1474
- context.ui.notify(
1475
- `Failed to update Fabric prewalk setting: ${error instanceof Error ? error.message : String(error)}`,
1476
- "error"
1477
- );
1478
- }
1479
- return;
1480
- }
1481
- if (option === "--off" || option === "--cancel") {
1482
- state.prewalk.cancel();
1483
- state.prewalkDrift.drop(context.sessionManager.getSessionId());
1484
- context.ui.setStatus("fabric-prewalk", void 0);
1485
- await restoreBorrowedInPlaceMain(state.prewalk, pi, context);
1486
- context.ui.notify("Fabric prewalk cancelled", "info");
1487
- return;
1488
- }
1489
- if (option === "--status") {
1490
- const status = state.prewalk.status();
1491
- context.ui.notify(
1492
- status.state === "idle" ? "Fabric prewalk is idle" : `Fabric prewalk ${status.state} (${status.mode}) \u2192 ${status.model}${status.task ? `
1493
- Task: ${status.task}` : ""}`,
1494
- "info"
1495
- );
1496
- return;
1497
- }
1498
- const task = argumentsText.trim().slice(command.length).trim();
1499
- await armPrewalk(state, context, pi, task);
1500
- return;
1501
- }
1502
- if (command === "tasks") {
1503
- await fabricUi.openTasks(context, argumentsList[0]);
1504
- return;
1505
- }
1506
- if (command === "chat") {
1507
- await fabricUi.openConversation(context, argumentsList.join(" ") || void 0);
1508
- return;
1509
- }
1510
- if (command === "focus") {
1511
- fabricUi.focusWidget(context);
1512
- return;
1513
- }
1514
- if (command === "decisions") {
1515
- const { openFabricDecisions } = await import("../decisions/command.js");
1516
- await openFabricDecisions(state.mesh, context, argumentsList[0]);
1517
- return;
1518
- }
1519
- if (command === "programs" || command === "run") {
1520
- const { runFabricProgramsCommand } = await import("../programs/host.js");
1521
- await runFabricProgramsCommand({ state, pi }, context, command, argumentsText.trim().slice(command.length));
1522
- return;
1523
- }
1524
- if (command === "dashboard" || command === "ui") {
1525
- await fabricUi.openDashboard(context);
1526
- return;
1527
- }
1528
- if (command === "providers") {
1529
- const providers = state.registry.providers();
1530
- context.ui.notify(
1531
- providers.map((provider) => `${provider.name} \u2014 ${provider.description}`).join("\n"),
1532
- "info"
1533
- );
1534
- return;
1535
- }
1536
- if (command === "captured") {
1537
- const query = argumentsList.join(" ").toLowerCase();
1538
- const tools = capturedTools.list().filter(
1539
- (tool) => !query || `${tool.name} ${tool.definition.description} ${tool.sourceInfo.path}`.toLowerCase().includes(query)
1540
- );
1541
- const shown = tools.slice(0, 100);
1542
- context.ui.notify(
1543
- shown.length > 0 ? [
1544
- ...shown.map((tool) => `${tool.name} [${tool.risk}] \u2014 ${tool.sourceInfo.path}`),
1545
- ...tools.length > shown.length ? [`\u2026 ${tools.length - shown.length} more captured tools`] : []
1546
- ].join("\n") : query ? `No captured extension tools matching ${JSON.stringify(query)}` : "No extension tools captured",
1547
- "info"
1548
- );
1549
- return;
1550
- }
1551
- if (command === "agents") {
1552
- const agents = state.agents.list();
1553
- context.ui.notify(
1554
- agents.length > 0 ? agents.map(
1555
- (agent) => `${agent.id.slice(0, 8)} ${agent.status} ${agent.runner}/${agent.transport} \u2014 ${agent.name}`
1556
- ).join("\n") : "No Fabric agents",
1557
- "info"
1558
- );
1559
- return;
1560
- }
1561
- if (command === "actors") {
1562
- const actors = state.actors.list();
1563
- context.ui.notify(
1564
- actors.length > 0 ? actors.map(
1565
- (actor) => `${actor.id.slice(0, 8)} ${actor.status} ${actor.runner} q:${actor.queued} \u2014 ${actor.name}`
1566
- ).join("\n") : "No Fabric actors",
1567
- "info"
1568
- );
1569
- return;
1570
- }
1571
- if (command === "messages") {
1572
- const id = argumentsList[0];
1573
- if (!id) {
1574
- context.ui.notify("Usage: /fabric messages <actor-id>", "warning");
1575
- return;
1576
- }
1577
- try {
1578
- const actor = state.actors.status(id);
1579
- const messages = state.actors.messages(actor.id, 20);
1580
- const shortId = actor.id.slice(0, 8);
1581
- const body = messages.length > 0 ? messages.map((message) => {
1582
- const value = message.text ?? message.error ?? message.action ?? "data";
1583
- const summary = truncateMiddle(value.replace(/\s+/g, " "), 500);
1584
- const runTag = message.runId ? ` [${message.runId.slice(0, 8)}]` : "";
1585
- const usageTag = message.usage ? ` \xB7 ${message.usage.input + message.usage.output} tok` : "";
1586
- return `${message.direction === "in" ? "\u2192" : "\u2190"} ${message.source}${runTag}: ${summary}${usageTag}`;
1587
- }).join("\n") : `No messages for ${actor.name}`;
1588
- const footer = `
1589
- Inspect LLM I/O: /fabric log ${shortId} \xB7 Export: /fabric export-log ${actor.name}`;
1590
- context.ui.notify(`${body}${footer}`, "info");
1591
- } catch (error) {
1592
- context.ui.notify(error instanceof Error ? error.message : String(error), "error");
1593
- }
1594
- return;
1595
- }
1596
- if (command === "log") {
1597
- const id = argumentsList[0];
1598
- if (!id) {
1599
- context.ui.notify(
1600
- "Usage: /fabric log <id> [session|run|all] [--lines N] [--run <runId>]",
1601
- "warning"
1602
- );
1603
- return;
1604
- }
1605
- let type = "session";
1606
- let lines = 40;
1607
- let runId;
1608
- for (let i = 1; i < argumentsList.length; i++) {
1609
- const arg = argumentsList[i];
1610
- if (arg === "session" || arg === "run" || arg === "all") type = arg;
1611
- else if ((arg === "--lines" || arg === "-n") && i + 1 < argumentsList.length) {
1612
- const n = Number(argumentsList[++i]);
1613
- if (n > 0) lines = Math.min(n, 5e3);
1614
- } else if (arg === "--run" && i + 1 < argumentsList.length) {
1615
- runId = argumentsList[++i];
1616
- }
1617
- }
1618
- try {
1619
- const actor = state.actors.status(id);
1620
- const log = state.actors.readLog(actor.id, { type, lines, ...runId ? { runId } : {} });
1621
- const parts = [`Actor ${actor.name} \xB7 ${log.sessionFile}`];
1622
- if (log.session.length > 0) {
1623
- parts.push(`\u2500\u2500 session (last ${log.session.length} lines) \u2500\u2500`);
1624
- for (const line of log.session) parts.push(summarizeLogLine(line.parsed ?? line.raw));
1625
- }
1626
- if (log.run) {
1627
- parts.push(
1628
- `\u2500\u2500 run ${log.run.runId.slice(0, 8)} (${log.run.status?.status ?? "?"}) \u2500\u2500`
1629
- );
1630
- for (const line of log.run.events) parts.push(summarizeLogLine(line.parsed ?? line.raw));
1631
- }
1632
- if (log.retainedRuns.length > 0) {
1633
- parts.push(
1634
- `retained runs: ${log.retainedRuns.map((r) => r.slice(0, 8)).join(" ")}`
1635
- );
1636
- }
1637
- context.ui.notify(
1638
- parts.length > 1 ? truncateMiddle(parts.join("\n"), 8e3) : `No log found for ${actor.name}`,
1639
- "info"
1640
- );
1641
- } catch (error) {
1642
- context.ui.notify(error instanceof Error ? error.message : String(error), "error");
1643
- }
1644
- return;
1645
- }
1646
- if (command === "export-log") {
1647
- const id = argumentsList[0];
1648
- const destArg = argumentsList.slice(1).join(" ");
1649
- if (!id) {
1650
- context.ui.notify("Usage: /fabric export-log <id> [path]", "warning");
1651
- return;
1652
- }
1653
- try {
1654
- const dest = path2.resolve(
1655
- destArg || path2.join("fabric-logs", `export-${Date.now()}`)
1656
- );
1657
- fs.mkdirSync(dest, { recursive: true });
1658
- const actor = state.actors.list().find((candidate) => candidate.id.startsWith(id) || candidate.name === id);
1659
- let label;
1660
- let copied = [];
1661
- if (actor) {
1662
- const full = state.actors.status(actor.id);
1663
- label = actor.name;
1664
- if (full.sessionFile && fs.existsSync(full.sessionFile)) {
1665
- fs.copyFileSync(full.sessionFile, path2.join(dest, "session.jsonl"));
1666
- copied.push("session.jsonl");
1667
- }
1668
- if (full.logDir && fs.existsSync(full.logDir)) {
1669
- fs.cpSync(full.logDir, path2.join(dest, "runs"), { recursive: true });
1670
- copied.push("runs/");
1671
- }
1672
- } else {
1673
- const runDir = state.agents.runDirectory(id);
1674
- const status = state.agents.status(id);
1675
- label = status.name;
1676
- if (runDir && fs.existsSync(runDir)) {
1677
- fs.cpSync(runDir, dest, { recursive: true });
1678
- copied.push("run/");
1679
- }
1680
- }
1681
- if (copied.length === 0) {
1682
- context.ui.notify(`No log files found for ${label}`, "warning");
1683
- return;
1684
- }
1685
- context.ui.notify(`Exported ${label} log \u2192 ${dest} (${copied.join(", ")})`, "info");
1686
- } catch (error) {
1687
- context.ui.notify(error instanceof Error ? error.message : String(error), "error");
1688
- }
1689
- return;
1690
- }
1691
- if (command === "clear-messages") {
1692
- const id = argumentsList[0];
1693
- if (!id) {
1694
- context.ui.notify("Usage: /fabric clear-messages <actor-id>", "warning");
1695
- return;
1696
- }
1697
- try {
1698
- const actor = state.actors.status(id);
1699
- await state.actors.clearMessages(actor.id);
1700
- context.ui.notify(`Cleared message history for ${actor.name}`, "info");
1701
- } catch (error) {
1702
- context.ui.notify(error instanceof Error ? error.message : String(error), "error");
1703
- }
1704
- return;
1705
- }
1706
- if (command === "events") {
1707
- const id = argumentsList[0];
1708
- if (!id) {
1709
- context.ui.notify("Usage: /fabric events <actor-id> [event...]", "warning");
1710
- return;
1711
- }
1712
- try {
1713
- const actor = state.actors.status(id);
1714
- const events = argumentsList.slice(1);
1715
- await state.actors.setEvents(actor.id, events);
1716
- context.ui.notify(
1717
- `Set ${actor.name} events: ${events.join(", ") || "(none)"}`,
1718
- "info"
1719
- );
1720
- } catch (error) {
1721
- context.ui.notify(error instanceof Error ? error.message : String(error), "error");
1722
- }
1723
- return;
1724
- }
1725
- if (command === "stop") {
1726
- const id = argumentsList[0];
1727
- if (!id) {
1728
- context.ui.notify("Usage: /fabric stop <id>", "warning");
1729
- return;
1730
- }
1731
- const actor = state.actors.list().find((candidate) => candidate.id.startsWith(id) || candidate.name === id);
1732
- if (actor) {
1733
- await state.actors.stop(actor.id);
1734
- context.ui.notify(`Stopped Fabric actor ${actor.id.slice(0, 8)}`, "info");
1735
- return;
1736
- }
1737
- const agent = state.agents.list().find((candidate) => candidate.id.startsWith(id));
1738
- if (!agent) {
1739
- context.ui.notify(`Unknown Fabric actor or agent: ${id}`, "error");
1740
- return;
1741
- }
1742
- await state.agents.stop(agent.id);
1743
- context.ui.notify(`Stopped Fabric agent ${agent.id.slice(0, 8)}`, "info");
1744
- return;
1745
- }
1746
- if (command === "remove" || command === "kill") {
1747
- const id = argumentsList[0];
1748
- if (!id) {
1749
- context.ui.notify("Usage: /fabric remove <id>", "warning");
1750
- return;
1751
- }
1752
- const actor = state.actors.list().find((candidate) => candidate.id.startsWith(id) || candidate.name === id);
1753
- if (actor) {
1754
- await state.actors.remove(actor.id);
1755
- context.ui.notify(`Removed Fabric actor ${actor.id.slice(0, 8)} (${actor.name})`, "info");
1756
- return;
1757
- }
1758
- const agent = state.agents.list().find((candidate) => candidate.id.startsWith(id));
1759
- if (!agent) {
1760
- context.ui.notify(`Unknown Fabric actor or agent: ${id}`, "error");
1761
- return;
1762
- }
1763
- await state.agents.stop(agent.id);
1764
- await state.agents.cleanup(agent.id);
1765
- context.ui.notify(`Removed Fabric agent ${agent.id.slice(0, 8)}`, "info");
1766
- return;
1767
- }
1768
- if (command === "attach") {
1769
- const id = argumentsList[0];
1770
- const agent = id ? state.agents.list().find((candidate) => candidate.id.startsWith(id)) : void 0;
1771
- if (!agent?.attachCommand) {
1772
- context.ui.notify("No attachable Fabric agent found", "warning");
1773
- return;
1774
- }
1775
- context.ui.notify(agent.attachCommand, "info");
1776
- return;
1777
- }
1778
- if (command === "global") {
1779
- const templates = state.globalActors.list();
1780
- context.ui.notify(
1781
- templates.length > 0 ? templates.map((template) => `${template.id.slice(0, 8)} global ${template.runner} \u2014 ${template.name}`).join("\n") : "No global Fabric actor templates",
1782
- "info"
1783
- );
1784
- return;
1785
- }
1786
- if (command === "import") {
1787
- const key = argumentsList[0];
1788
- if (!key) {
1789
- context.ui.notify("Usage: /fabric import <global-actor-name-or-id> [as <new-name>]", "warning");
1790
- return;
1791
- }
1792
- try {
1793
- const def = state.globalActors.resolve(key);
1794
- if (!def) {
1795
- context.ui.notify(`Unknown global actor: ${key}`, "error");
1796
- return;
1797
- }
1798
- const asIndex = argumentsList.indexOf("as");
1799
- const as = asIndex >= 0 && argumentsList[asIndex + 1] ? argumentsList[asIndex + 1] : void 0;
1800
- const actor = await state.actors.create(state.globalActors.toRequest(def, as));
1801
- context.ui.notify(`Imported global actor "${def.name}" as ${actor.name}`, "info");
1802
- } catch (error) {
1803
- context.ui.notify(error instanceof Error ? error.message : String(error), "error");
1804
- }
1805
- return;
1806
- }
1807
- if (command === "export") {
1808
- const id = argumentsList[0];
1809
- const overwrite = argumentsList.includes("--overwrite") || argumentsList.includes("-f");
1810
- if (!id) {
1811
- context.ui.notify("Usage: /fabric export <actor-id> [--overwrite]", "warning");
1812
- return;
1813
- }
1814
- try {
1815
- const actor = state.actors.list().find((candidate) => candidate.id.startsWith(id) || candidate.name === id);
1816
- if (!actor) {
1817
- context.ui.notify(`Unknown Fabric actor: ${id}`, "error");
1818
- return;
1819
- }
1820
- const def = state.actors.definition(actor.id);
1821
- const template = state.globalActors.create(def, overwrite);
1822
- context.ui.notify(`Exported "${template.name}" to global actors`, "info");
1823
- } catch (error) {
1824
- context.ui.notify(error instanceof Error ? error.message : String(error), "error");
1825
- }
1826
- return;
1827
- }
1828
- if (command === "repairs") {
1829
- if (argumentsList[0] !== void 0) {
1830
- context.ui.notify("Usage: /fabric repairs", "warning");
1831
- return;
1832
- }
1833
- context.ui.notify(formatRepairStatus(state.repairs.status()), "info");
1834
- return;
1835
- }
1836
- if (command === "entropy") {
1837
- const {
1838
- ENTROPY_METRIC_VERSION,
1839
- entropySurfaceHash,
1840
- liveSurfaceSnapshot,
1841
- surfaceFreedomReport,
1842
- machineSessionFilesAsync,
1843
- measureSessionCorpusAsync,
1844
- projectSessionFilesAsync,
1845
- sessionWindowEvidenceAsync,
1846
- measureEntropyAsync,
1847
- entropyRepairRows,
1848
- entropyReviewSignals,
1849
- formatEntropyReviewSignal,
1850
- loadObservationPoolAsync,
1851
- mergeObservationWindowAsync,
1852
- poolToValueObservations,
1853
- applyCompiledSurface,
1854
- normalFormEvidenceSummary,
1855
- loadCompiledSurfaceAsync,
1856
- parseCompiledSurfaceArtifact,
1857
- saveCompiledSurfaceAsync,
1858
- formatEntropyCommandHints,
1859
- formatEntropyMetric,
1860
- mergeCompiledSurfaces
1861
- } = await import("../entropy/index.js");
1862
- const exportArtifactIndex = argumentsList.indexOf("export-artifact");
1863
- if (exportArtifactIndex >= 0) {
1864
- const target = argumentsList[exportArtifactIndex + 1];
1865
- try {
1866
- const loaded = await loadCompiledSurfaceAsync(resolveAgentDir());
1867
- if (loaded.error) {
1868
- context.ui.notify(loaded.error, "error");
1869
- return;
1870
- }
1871
- if (!loaded.file) {
1872
- context.ui.notify(
1873
- "No compiled surface to export; wait for a compile to pass its gate",
1874
- "warning"
1875
- );
1876
- return;
1877
- }
1878
- const dest = path2.resolve(
1879
- target ?? path2.join(resolveAgentDir(), "fabric", "entropy", "artifact.json")
1880
- );
1881
- await fs.promises.mkdir(path2.dirname(dest), { recursive: true });
1882
- await fs.promises.writeFile(dest, `${JSON.stringify(loaded.file, null, 2)}
1883
- `, {
1884
- encoding: "utf-8",
1885
- mode: 384
1886
- });
1887
- context.ui.notify(
1888
- `Exported compiled surface (${loaded.file.normalizations?.length ?? 0} normal-form plans; legacy restrictions inert) \u2192 ${dest}`,
1889
- "info"
1890
- );
1891
- } catch (error) {
1892
- context.ui.notify(
1893
- error instanceof Error ? error.message : String(error),
1894
- "error"
1895
- );
1896
- }
1897
- return;
1898
- }
1899
- const importIndex = argumentsList.indexOf("import");
1900
- if (importIndex >= 0) {
1901
- const source = argumentsList[importIndex + 1];
1902
- if (!source) {
1903
- context.ui.notify("Usage: /fabric entropy import <artifact.json>", "warning");
1904
- return;
1905
- }
1906
- try {
1907
- const raw = JSON.parse(
1908
- await fs.promises.readFile(path2.resolve(source), "utf-8")
1909
- );
1910
- const incoming = parseCompiledSurfaceArtifact(raw);
1911
- if (!incoming) {
1912
- context.ui.notify(`Artifact is invalid: ${source}`, "error");
1913
- return;
1914
- }
1915
- const agentDir = resolveAgentDir();
1916
- const localLoaded = await loadCompiledSurfaceAsync(agentDir);
1917
- if (localLoaded.error) {
1918
- context.ui.notify(localLoaded.error, "error");
1919
- return;
1920
- }
1921
- const live = await liveSurfaceSnapshot({
1922
- registry: state.registry,
1923
- extensionContext: context,
1924
- cwd: state.cwd ?? context.cwd
1925
- });
1926
- const merged = mergeCompiledSurfaces(localLoaded.file, incoming, live);
1927
- const saved = await saveCompiledSurfaceAsync(agentDir, merged.file);
1928
- if (state.config.entropy.compile) setActiveCompiledSurface(saved.file);
1929
- context.ui.notify(
1930
- `Imported compiled surface: ${merged.file.normalizations?.length ?? 0} normal-form plans \xB7 ${merged.droppedOverlays + merged.droppedQuarantines + merged.droppedNormalizations} dropped (unproved rules or legacy restrictions)`,
1931
- "info"
1932
- );
1933
- } catch (error) {
1934
- context.ui.notify(
1935
- error instanceof Error ? error.message : String(error),
1936
- "error"
1937
- );
1938
- }
1939
- return;
1940
- }
1941
- const exportIndex = argumentsList.indexOf("export");
1942
- if (exportIndex >= 0) {
1943
- const target = argumentsList[exportIndex + 1];
1944
- try {
1945
- const snapshot = await liveSurfaceSnapshot({
1946
- registry: state.registry,
1947
- extensionContext: context,
1948
- cwd: state.cwd ?? context.cwd
1949
- });
1950
- const dest = path2.resolve(
1951
- target ?? path2.join(resolveAgentDir(), "fabric", "entropy", "surface.json")
1952
- );
1953
- await fs.promises.mkdir(path2.dirname(dest), { recursive: true });
1954
- await fs.promises.writeFile(dest, `${JSON.stringify(snapshot, null, 2)}
1955
- `, {
1956
- encoding: "utf8",
1957
- mode: 384
1958
- });
1959
- context.ui.notify(
1960
- `Exported ${snapshot.actions.length} surface actions \u2192 ${dest}`,
1961
- "info"
1962
- );
1963
- } catch (error) {
1964
- context.ui.notify(
1965
- error instanceof Error ? error.message : String(error),
1966
- "error"
1967
- );
1968
- }
1969
- return;
1970
- }
1971
- const projectScope = argumentsList.includes("--project");
1972
- const scopedArguments = argumentsList.filter((argument) => argument !== "--project");
1973
- if (scopedArguments[0] !== void 0) {
1974
- context.ui.notify(
1975
- "Usage: /fabric entropy [--project] [export [path] | export-artifact [path] | import <path>]",
1976
- "warning"
1977
- );
1978
- return;
1979
- }
1980
- try {
1981
- const status = state.repairs.status();
1982
- const agentDir = resolveAgentDir();
1983
- const scopeCwd = state.cwd ?? context.cwd;
1984
- const [loadedCompiled, live, files] = await Promise.all([
1985
- loadCompiledSurfaceAsync(agentDir),
1986
- liveSurfaceSnapshot({
1987
- registry: state.registry,
1988
- extensionContext: context,
1989
- cwd: scopeCwd
1990
- }),
1991
- projectScope ? projectSessionFilesAsync(agentDir, scopeCwd) : machineSessionFilesAsync(agentDir, scopeCwd)
1992
- ]);
1993
- const snapshot = loadedCompiled.file ? applyCompiledSurface(live, loadedCompiled.file) : live;
1994
- const freedom = surfaceFreedomReport(snapshot);
1995
- const surfaceDigest = entropySurfaceHash(snapshot);
1996
- const corpus = await measureSessionCorpusAsync({
1997
- files,
1998
- surface: snapshot,
1999
- catalogDigest: surfaceDigest
2000
- });
2001
- const formatFreedom = (value) => String(Math.round(value * 100) / 100);
2002
- const worst = freedom.actions.slice(0, 4).map((action) => `${action.ref} ${formatFreedom(action.freedom)}`).join(" \xB7 ");
2003
- const latest = corpus.latest;
2004
- const sessionsLine = corpus.sessions.length === 0 || latest === void 0 ? `session entropy (observed): no fabric_exec traces in the latest ${files.length} ${projectScope ? "project" : "machine"} sessions` : `session entropy (observed): ${corpus.sessions.length} sessions \xB7 latest ${latest.totals.operations} ops \xB7 invocation rejection rate ${formatEntropyMetric(latest.score)} \xB7 ${formatEntropyMetric(latest.totals.invocationRejectionsPer1k)}/1k calls \xB7 lower is better \xB7 slope ${formatEntropyMetric(corpus.trend.slopePerStep)}/session \xB7 ${latest.totals.invocationRejectionsPer1k === 0 && corpus.trend.slopePerStep <= 0 ? "no invocation rejections" : "invocation friction remains"}`;
2005
- const modelsLine = corpus.models.length > 1 ? `models: ${corpus.models.map(
2006
- (model) => `${model.model} behavioral ${formatEntropyMetric(model.latestBehavioralScore)} \xB7 slope ${formatEntropyMetric(model.slopePerSession)}`
2007
- ).join(" \xB7 ")}` : void 0;
2008
- const compiledLine = loadedCompiled.error ? `compiled: unavailable \u2014 ${loadedCompiled.error}` : loadedCompiled.file ? `compiled: artifact v${loadedCompiled.file.version} \xB7 ${loadedCompiled.file.normalizations?.length ?? 0} normal-form plans \xB7 canonical capabilities preserved${loadedCompiled.file.version === 1 ? " \xB7 legacy restrictions inert (migration pending)" : ""}` : "compiled: none";
2009
- let reviewLine;
2010
- let normalizationLine = "normal forms: no witness evidence";
2011
- try {
2012
- const [windowEvidence, poolLoaded] = await Promise.all([
2013
- sessionWindowEvidenceAsync(files),
2014
- loadObservationPoolAsync(agentDir)
2015
- ]);
2016
- const normal = normalFormEvidenceSummary(windowEvidence.traces);
2017
- normalizationLine = `normal forms: ${normal.normalizedCalls} calls normalized \xB7 ${normal.rulesApplied} rules applied \xB7 ${normal.succeeded} succeeded \xB7 ${normal.subsequentFailures} subsequent failures (not masked)`;
2018
- if (poolLoaded.error) {
2019
- reviewLine = `review: unavailable \u2014 ${poolLoaded.error}`;
2020
- } else if (windowEvidence.traces.length === 0) {
2021
- reviewLine = "review: no window evidence";
2022
- } else {
2023
- const mergedPool = await mergeObservationWindowAsync(
2024
- poolLoaded.file,
2025
- windowEvidence.observationWindows
2026
- );
2027
- const signals = entropyReviewSignals({
2028
- report: await measureEntropyAsync({
2029
- traces: windowEvidence.traces,
2030
- surface: snapshot,
2031
- catalogDigest: surfaceDigest
2032
- }),
2033
- traces: windowEvidence.traces,
2034
- surface: snapshot,
2035
- repairs: entropyRepairRows(state.repairs.repairs),
2036
- valueObservations: poolToValueObservations(mergedPool.file)
2037
- });
2038
- reviewLine = signals.length === 0 ? "review: none" : `review: ${signals.length} suggestion${signals.length === 1 ? "" : "s"} \xB7 ${signals.slice(0, 4).map(formatEntropyReviewSignal).join(" \xB7 ")}${signals.length > 4 ? ` \xB7 +${signals.length - 4} more` : ""}`;
2039
- }
2040
- } catch {
2041
- reviewLine = "review: unavailable";
2042
- }
2043
- context.ui.notify(
2044
- [
2045
- `entropy: metric v${ENTROPY_METRIC_VERSION} \xB7 surface ${surfaceDigest.slice(0, 12)} \xB7 ${freedom.actions.length} actions`,
2046
- `live: invocation errors ${status.invocationErrors} \xB7 effect dropped ${status.effectDropped} \xB7 aliases ${status.repairCount} \xB7 alias hits ${status.applyHits}`,
2047
- compiledLine,
2048
- normalizationLine,
2049
- reviewLine,
2050
- `surface freedom (diagnostic, not objective): mean ${formatFreedom(freedom.mean)}${worst ? ` \xB7 worst ${worst}` : ""}`,
2051
- sessionsLine,
2052
- ...modelsLine ? [modelsLine] : [],
2053
- ...formatEntropyCommandHints()
2054
- ].join("\n"),
2055
- "info"
2056
- );
2057
- } catch (error) {
2058
- context.ui.notify(
2059
- error instanceof Error ? error.message : String(error),
2060
- "error"
2061
- );
2062
- }
2063
- return;
2064
- }
2065
- if (command !== "status") {
2066
- context.ui.notify(
2067
- "Usage: /fabric [status|dashboard|chat [id-or-name]|focus|prewalk [task]|prewalk --off|--disable|--enable|reload|providers|agents|actors|global|import <name> [as <new>]|export <id> [--overwrite]|messages <id>|clear-messages <id>|events <id> [event...]|log <id>|export-log <id>|attach <id>|stop <id>|remove <id>|kill <id>|repairs|entropy|decisions [id]|programs [promote|retire <ref>]|run <ref> [json]]",
2068
- "warning"
2069
- );
2070
- return;
2071
- }
2072
- const config = state.config;
2073
- context.ui.notify(
2074
- [
2075
- `cwd: ${state.cwd}`,
2076
- `mode: ${config.fullCodeMode ? "full code (Fabric-owned core tools)" : "orchestration-only (native Pi tools)"}`,
2077
- `providers: ${state.registry.providers().map((provider) => provider.name).join(", ")}`,
2078
- `runner: ${config.agents.runner} \xB7 transport: ${config.agents.transport} \xB7 model: ${config.agents.runner === "claude" ? config.agents.claude.model || "Claude default" : config.agents.runner === "veda" ? `${config.agents.veda.model || "Veda default"} \xB7 backend ${config.agents.veda.backend} \xB7 persona ${config.agents.veda.persona}` : config.agents.model || "inherit"}`,
2079
- `agent limits: concurrency ${config.agents.maxConcurrent}, per execution ${config.agents.maxPerExecution}, depth ${config.agents.maxDepth}`,
2080
- (() => {
2081
- const prewalk = state.prewalk.status();
2082
- return prewalk.state === "idle" ? `prewalk: idle \xB7 ${config.prewalk.mode} \xB7 model ${config.prewalk.model || "Ask each time"} \xB7 auto-arm & re-arm ${config.prewalk.alwaysRearm ? "on" : "off"}` : `prewalk: ${prewalk.state} \xB7 ${prewalk.mode} \u2192 ${prewalk.model}${prewalk.alwaysRearm ? " \xB7 always re-arm" : ""}`;
2083
- })(),
2084
- config.fullCodeMode && config.capture.enabled ? `captured tools: ${capturedTools.size} \xB7 model visibility: ${config.capture.hideFromModel ? "hidden" : "visible"}` : "captured tools: disabled (native registry preserved)",
2085
- ...config.foreground.tools.length > 0 ? [`foreground: ${formatForeground(state.foregroundTools())}`] : [],
2086
- `actors: ${state.actors.list().length} \xB7 mesh: ${config.mesh.enabled ? state.mesh.root : "disabled"}`,
2087
- `MCP: ${config.mcp.enabled ? "enabled" : "disabled"}`,
2088
- `UI: ${config.ui.enabled ? `${config.ui.widget} widget above chat` : "disabled"}`
2089
- ].join("\n"),
2090
- "info"
2091
- );
1317
+ const { runFabricCommand } = await import("../commands/fabric-handler.js");
1318
+ await runFabricCommand(pi, deps, commandHost, argumentsText, context);
2092
1319
  }
2093
1320
  });
2094
1321
  }
2095
1322
 
2096
1323
  // src/agents/runner-notice.ts
2097
1324
  var BUILT_IN_RUNNERS = ["pi", "pi-durable", "claude", "veda"];
2098
- var editDistance = (left, right) => {
2099
- const row = Array.from({ length: right.length + 1 }, (_, index) => index);
2100
- for (let i = 1; i <= left.length; i += 1) {
2101
- let diagonal = row[0];
2102
- row[0] = i;
2103
- for (let j = 1; j <= right.length; j += 1) {
2104
- const above = row[j];
2105
- row[j] = Math.min(above + 1, row[j - 1] + 1, diagonal + (left[i - 1] === right[j - 1] ? 0 : 1));
2106
- diagonal = above;
2107
- }
2108
- }
2109
- return row[right.length];
2110
- };
2111
1325
  var unregisteredRunnerNotice = (runner, registered) => {
2112
1326
  const known = [.../* @__PURE__ */ new Set([...BUILT_IN_RUNNERS, ...registered])];
2113
1327
  if (known.includes(runner)) return void 0;
@@ -2120,7 +1334,7 @@ var unregisteredRunnerNotice = (runner, registered) => {
2120
1334
  };
2121
1335
 
2122
1336
  // src/core/tool-ownership.ts
2123
- import path3 from "node:path";
1337
+ import path2 from "node:path";
2124
1338
  var fabricToolLoadout = (loadout, exclusive, foreground = []) => {
2125
1339
  if (!exclusive) return void 0;
2126
1340
  const hiddenDeclarations = loadout.registered.map((tool) => tool.name).filter((name) => name !== "fabric_exec" && !foreground.includes(name));
@@ -2177,7 +1391,7 @@ var fabricModelContext = (messages, tools) => {
2177
1391
  var FABRIC_TOOL_NAME = "fabric_exec";
2178
1392
  var TOP_LEVEL_SCHEMA_REF_PREFIX = "schema.top_level_tool.";
2179
1393
  var ownsFabricToolSource = (tools, extensionEntryPath) => tools.some(
2180
- (tool) => tool.name === FABRIC_TOOL_NAME && path3.resolve(tool.sourceInfo.path) === path3.resolve(extensionEntryPath)
1394
+ (tool) => tool.name === FABRIC_TOOL_NAME && path2.resolve(tool.sourceInfo.path) === path2.resolve(extensionEntryPath)
2181
1395
  );
2182
1396
  var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2183
1397
  var finalFabricDetailsFailed = (details) => {
@@ -2262,99 +1476,106 @@ var FabricToolOwnership = class {
2262
1476
  }
2263
1477
  };
2264
1478
 
2265
- // src/core/core-override-guidance.ts
2266
- var coreOverridePromptGuidance = (catalog) => {
2267
- const sections = [];
2268
- for (const name of PI_CORE_TOOL_NAMES) {
2269
- const entry = catalog.get(name);
2270
- if (!entry) continue;
2271
- const lines = [];
2272
- if (entry.definition.promptSnippet) {
2273
- lines.push(`Additional guidance for \`pi.${name}\`: ${entry.definition.promptSnippet}`);
1479
+ // src/core/host-policy.ts
1480
+ import { createHash } from "node:crypto";
1481
+ var HOOKED_PROVIDERS = /* @__PURE__ */ new Set(["pi", "extensions"]);
1482
+ var FABRIC_BUILTIN_READ_REFS = /* @__PURE__ */ new Set([
1483
+ "cache.status",
1484
+ "compact.pressure",
1485
+ "compact.status",
1486
+ "components.describe",
1487
+ "components.graph",
1488
+ "components.list",
1489
+ "components.status",
1490
+ "memory.expand",
1491
+ "memory.recall",
1492
+ "memory.sessions",
1493
+ "programs.get",
1494
+ "programs.list",
1495
+ "schema.status",
1496
+ "state.get",
1497
+ "state.history",
1498
+ "thinking.status"
1499
+ ]);
1500
+ var refMatches = (pattern, ref) => pattern.endsWith(".*") ? ref.startsWith(pattern.slice(0, -1)) : pattern === ref;
1501
+ var FabricHostPolicy = class {
1502
+ #policy;
1503
+ #sealed = false;
1504
+ /** True once a policy is in force. Does not seal. */
1505
+ get active() {
1506
+ return this.#policy !== void 0;
1507
+ }
1508
+ get sealed() {
1509
+ return this.#sealed;
1510
+ }
1511
+ /** Accept the policy only while nothing has run; otherwise refuse it. */
1512
+ apply(policy) {
1513
+ if (this.#sealed) {
1514
+ return { version: 1, accepted: false, reason: "Fabric host policy is sealed: this instance already ran a program or provider call" };
2274
1515
  }
2275
- const guidelines = entry.definition.promptGuidelines ?? [];
2276
- if (guidelines.length > 0) {
2277
- lines.push(`Guidelines for \`pi.${name}\`:`);
2278
- lines.push(...guidelines.map((guideline) => `- ${guideline}`));
1516
+ if (this.#policy) {
1517
+ return { version: 1, accepted: false, reason: `Fabric host policy is already set by ${this.#policy.owner}` };
2279
1518
  }
2280
- if (lines.length > 0) sections.push(lines.join("\n"));
1519
+ const copy = structuredClone(policy);
1520
+ this.#policy = copy;
1521
+ return { version: 1, accepted: true, digest: hostPolicyDigest(copy), enforced: [...FABRIC_HOST_POLICY_FIELDS] };
2281
1522
  }
2282
- return sections.length > 0 ? `
2283
-
2284
- Effective compatible core override guidance:
2285
- ${sections.join("\n")}` : "";
2286
- };
2287
-
2288
- // src/core/system-guidance.ts
2289
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
2290
- import * as path4 from "node:path";
2291
- var SHELL_COMPOSITION_GUIDANCE = " tasks.read (byte offset/next, waitMs long-poll) and tasks.watch with {id, match} read or filter any background task without a monitor." + (process.platform === "win32" ? "" : " With jev-fabric (see tasks/sessions via tools.describe): pi.bash durable:true outlives Pi and reattaches on resume; sessions.open/write/read/stop drive interactive children (a Jev program's end with it).");
2292
- var fabricExecutionKernelGuidance = (fullCodeMode, kernel = "typescript", pythonRuntime = "monty", profile = "additive") => [
2293
- kernel === "python" ? `Configured fabric_exec kernel: Python (${pythonRuntime === "monty" ? "Monty sandboxed subset" : "CPython"}). Write Python only in \`code\`: top-level await/return, dicts, True/False/None, and asyncio.gather. There is no per-call language switch.` : profile === "native" ? "Configured fabric_exec kernel: TypeScript with native Pi codemode API. Write JavaScript async function bodies; top-level await and return work. Native source is not type-checked or repaired." : "Configured fabric_exec kernel: TypeScript. Write TypeScript only in `code`; top-level await and return are supported.",
2294
- "The configured kernel is exclusive for Fabric orchestration, including when skills or earlier messages show another language. Do not invoke another interpreter through shell tools or native subprocesses merely to run Fabric orchestration in a different language. Project builds, tests, and explicitly requested interpreter work remain legitimate shell commands.",
2295
- fullCodeMode ? "Pi Fabric full code mode: `fabric_exec` is the only way to call Pi core tools \u2014 use them as `pi.*` inside `code`." : "Pi Fabric is in orchestration-only mode. Pi core and registered extension tools stay on their native direct execution path; inside fabric_exec, `pi.*` and `extensions.*` are unavailable.",
2296
- // Files the model has not opened (images in particular) must be read before
2297
- // use; this line rides the turn-stable kernel guidance so provider prefix
2298
- // caches stay warm.
2299
- `Read every file the user provides (images, screenshots, code, text) with the ${fullCodeMode ? "`pi.read`" : "`read`"} tool before responding \u2014 never assume its contents.`
2300
- ].join(" ");
2301
- var defaultFabricExecutionGuidance = (fullCodeMode, kernel = "typescript", pythonRuntime = "monty", profile = "additive") => kernel === "typescript" && profile === "native" ? "Native Pi codemode profile: tools.<name>(args) and nativeTools.<name>(args) use native results, including schema-backed error envelopes. searchTools/ALL_TOOLS return callable identifiers; describeTool returns a declaration string. image() emits images and saves host-side temporary artifacts. store/load share Pi codemode-store entries on this branch. Fabric discovery remains fabric.tools; pi.*, mcp.* and extensions.* keep Fabric result semantics. Policies and limits are unchanged. " + defaultFabricExecutionGuidance(fullCodeMode, kernel, pythonRuntime).replaceAll("tools.", "fabric.tools.").replaceAll("`tools`", "`fabric.tools`") : kernel === "python" ? (pythonRuntime === "monty" ? "Python backend: Monty sandboxed subset, not CPython. Native filesystem/network/environment access and arbitrary imports are unavailable; use host tools for effects. Supply acyclic JSON host arguments; recursive containers are unsupported. Underscore-prefixed direct capability attributes are unavailable: use tools.call with the exact discovered ref instead. \u03C0 is an attribute object; payloads is a dict, not the same identity. " : "Python backend: CPython; native standard-library imports are available. ") + 'Python fabric_exec: write an async function body with `await` and `return`; each invocation starts fresh. Use imports supported by the configured backend, such as `import asyncio`. Host methods accept one dict or keyword arguments: `await tools.search(query="example")`, `await tools.call(ref="provider.action", args={"key": "value"})`; discover with tools.search instead of enumerating: tools.list is a capped page (default 100, hard cap 1000) with no truncation marker, so a short result never proves an action is absent (tools.list(envelope=True) reports totals). Known actions use mcp.<server>.<tool>, memory.*, state.*, schema.*, compact.*, components.*, agents.*, or mesh.*. Responses are native Python dicts/lists, not attribute objects. Use `asyncio.gather` for independent calls. `\u03C0.key` and `payloads["key"]` contain only the exact top-level payload keys. Return JSON-compatible data (convert sets, bytes, paths, and datetimes explicitly); print output is bounded. JavaScript callback helpers (workflow, memory.walk, and predicate callbacks) are not Python APIs; page with ordinary await/loops instead. Provider argument validation and approvals remain host-enforced. Schema enforce retains host gates and requires the selected runtime\u2019s isolation; no unrestricted fallback.' + (fullCodeMode ? ` \`await pi.read("/x")\`, \`await pi.grep(pattern="TODO", path="src")\`, \`await pi.find(pattern="*.py", path="src")\`, and \`await pi.ls("src")\` return strings. \`await pi.bash(command="ls")\`, \`await pi.edit(path="/x", oldText="a", newText="b")\`, and \`await pi.write(path="/y", content=\u03C0.body)\` return dicts; read \`r["output"]\`. Shell nonzero exits raise; \`settle=True\` returns a failure dict instead. Cancellation, timeout, approval and security errors still raise. A nested shell that exceeds executor.shellHangMs still resolves ok with a still-running notice, pid, and live output path; background=True detaches immediately. Detached results include details.taskId; completion notifies this session. Use tools.call(ref='tasks.list', args={}), tasks.get or tasks.stop with {'id': taskId}; pi.read can read the bounded log. Bounded controllers can await tasks.wait or tasks.watch (monitor batches, after cursor) without polling; timeout/cancellation affects only the observation. Opt-in monitor={'delivery':'wake','match':'literal','timeoutMs':300000,'intervalMs':5000} (choose delivery 'ui' or 'wake') also detaches: UI-only never wakes the agent, wake sends coalesced line events. Monitors expire and are not automatically renewed.` + SHELL_COMPOSITION_GUIDANCE + " Captured tools are `await extensions.<name>(...)`." : " Pi core and extensions are unavailable inside fabric_exec in orchestration-only mode.") : fullCodeMode ? "Examples and returns: `pi.read('/x')`, `pi.grep('TODO','src')` / `pi.grep({pattern:'TODO', path:'src', ignoreCase:true, context:2})`, `pi.find({pattern:'*.ts', path:'src', limit:20})`, and `pi.ls('src')` return strings; `pi.bash({cmd:'ls'})` (or `pi.powershell` on Windows), `pi.edit({path:'/x', old:'a', new:'b'})`, and `pi.write({path:'/y', text:'z'})` return `{ok, output, details}` (read `.output`); failed core calls reject, including shell tools on an ordinary nonzero exit; pass `settle: true` to `pi.bash` or `pi.powershell` to get `{ ok: false, exitCode, output, error }` instead. Timeout, cancellation, approval, and security failures still reject. A nested shell that exceeds `executor.shellHangMs` still resolves `ok: true` with a still-running notice, pid, and live output path; `background: true` detaches immediately. Detached results include `details.taskId`; completion notifies this session, without polling. Use `tools.call({ref:'tasks.list',args:{}})` or `tasks.get`/`tasks.stop` with `{id: taskId}`; `pi.read` can read the bounded log. Bounded controllers can await `tasks.wait` or `tasks.watch` (monitor batches, `after` cursor) without polling; timeout/cancellation affects only the observation. Opt-in `monitor:{delivery:'ui'|'wake',match:'literal',timeoutMs:300000,intervalMs:5000}` also detaches: UI-only never wakes the agent, wake sends coalesced line events. Monitors expire and are not automatically renewed." + SHELL_COMPOSITION_GUIDANCE + "\n`tools` exposes discovery/generic calls (`providers`/`catalog`/`list`/`search`/`describe`/`call`) plus the native `models` namespace. `models === tools.models`; `tools.models()` retains legacy model listing. Use `await models.getAvailableOfType('classifier')` (or `'image'`), then `models.classify(model,{state,questions})` or `models.generateImages(model,{input})`. Check native `stopReason`/`errorMessage`; classifier yes/no questions use `type:'bool'` and return `probability`. Call known MCP tools as `mcp.<sanitized_server>.<sanitized_tool>(args)`, captured tools as `extensions.<tool>(args)`, and stable providers as `memory.*`, `state.*`, `schema.*`, or `compact.*`. Use `tools.call({ref,args})` for computed refs. `pi` is the core tools; `\u03C0.<key>` reads named `strings` (not a tool)." : "Call known actions through `mcp.<sanitized_server>.<sanitized_tool>(args)`, `memory.*`, `state.*`, `schema.*`, `components.*`, `compact.*`, `agents.*`, or `mesh.*`; use `tools.catalog`/`search`/`describe`/`list` for discovery and `tools.call({ref,args})` for computed refs. Other surfaces are opt-in via user-loaded skills.";
2302
- var manifestNameCache = /* @__PURE__ */ new Map();
2303
- var packageNameFromManifest = (startPath) => {
2304
- if (!startPath) return void 0;
2305
- let directory = path4.dirname(path4.resolve(startPath));
2306
- while (true) {
2307
- if (manifestNameCache.has(directory)) return manifestNameCache.get(directory);
2308
- const manifestPath = path4.join(directory, "package.json");
2309
- let name;
2310
- if (existsSync2(manifestPath)) {
2311
- try {
2312
- const manifest = JSON.parse(readFileSync2(manifestPath, "utf8"));
2313
- if (typeof manifest.name === "string" && manifest.name.trim()) name = manifest.name.trim();
2314
- } catch {
2315
- }
1523
+ /** Refusal message for `provider.name`, or undefined when the policy allows it. Seals. */
1524
+ refDenial(provider, name) {
1525
+ this.#sealed = true;
1526
+ return this.previewDenial(provider, name);
1527
+ }
1528
+ /**
1529
+ * The same decision as refDenial without sealing, for answers that admit no
1530
+ * work, such as which tools a program can reach.
1531
+ */
1532
+ previewDenial(provider, name) {
1533
+ const policy = this.#policy;
1534
+ if (!policy) return void 0;
1535
+ const ref = `${provider}.${name}`;
1536
+ const prefix = `${ref} is refused by the Fabric host policy from ${policy.owner}`;
1537
+ if (policy.deniedProviders?.includes(provider)) {
1538
+ return `${prefix}: provider ${provider} is unavailable here (${policy.reason})`;
2316
1539
  }
2317
- manifestNameCache.set(directory, name);
2318
- if (name) return name;
2319
- const parent = path4.dirname(directory);
2320
- if (parent === directory) return void 0;
2321
- directory = parent;
1540
+ if (HOOKED_PROVIDERS.has(provider)) {
1541
+ return policy.deniedTools?.includes(name) ? `${prefix}: tool ${name} is unavailable here (${policy.reason})` : void 0;
1542
+ }
1543
+ if (FABRIC_BUILTIN_READ_REFS.has(ref)) return void 0;
1544
+ if (policy.allowedRefs?.some((pattern) => refMatches(pattern, ref))) return void 0;
1545
+ return `${prefix}: actions outside pi.* and extensions.* need a host allowedRefs entry (${policy.reason})`;
2322
1546
  }
2323
- };
2324
- var extensionToolRosterGuidance = (tools, coreToolNames, nativeProfile = false) => {
2325
- const extensionTools = tools.filter((tool) => !coreToolNames.has(tool.name));
2326
- if (extensionTools.length === 0) return void 0;
2327
- const namespaceLabel = (tool) => {
2328
- const source = tool.sourceInfo?.source?.trim();
2329
- if (source?.startsWith("npm:")) return source.slice("npm:".length) || source;
2330
- const manifestName = packageNameFromManifest(tool.sourceInfo?.path) ?? packageNameFromManifest(source && /[\\/]/.test(source) ? source : void 0);
2331
- if (manifestName) return manifestName;
2332
- if (source && !/[\\/]/.test(source)) return source;
2333
- const parts = (tool.sourceInfo?.path ?? source ?? "").split(/[\\/]/).filter(Boolean);
2334
- const base = parts.at(-1)?.trim() ?? "";
2335
- if (/^index\./i.test(base)) return parts.at(-2)?.trim() || base;
2336
- return base || "extensions";
2337
- };
2338
- const groups = /* @__PURE__ */ new Map();
2339
- for (const tool of [...extensionTools].sort((left, right) => left.name.localeCompare(right.name))) {
2340
- const label = namespaceLabel(tool);
2341
- const names = groups.get(label);
2342
- if (names) names.push(tool.name);
2343
- else groups.set(label, [tool.name]);
1547
+ /** True when the policy refuses every action of a provider, so Fabric never lists it. Seals. */
1548
+ providerHidden(provider) {
1549
+ this.#sealed = true;
1550
+ return this.previewProviderHidden(provider);
1551
+ }
1552
+ /** Provider visibility without admitting work or sealing the policy. */
1553
+ previewProviderHidden(provider) {
1554
+ const policy = this.#policy;
1555
+ if (!policy) return false;
1556
+ if (policy.deniedProviders?.includes(provider)) return true;
1557
+ if (HOOKED_PROVIDERS.has(provider)) return false;
1558
+ const head = `${provider}.`;
1559
+ return ![...FABRIC_BUILTIN_READ_REFS].some((ref) => ref.startsWith(head)) && !(policy.allowedRefs ?? []).some((pattern) => pattern.startsWith(head));
1560
+ }
1561
+ /** Native executors run outside every tool hook, so any policy refuses them. Seals. */
1562
+ executorDenial() {
1563
+ this.#sealed = true;
1564
+ const policy = this.#policy;
1565
+ if (!policy) return void 0;
1566
+ return `Fabric host policy from ${policy.owner} refuses native executors (CPython, node-process, bun-process): ${policy.reason}`;
2344
1567
  }
2345
- return [
2346
- `Registered extension tools are callable inside fabric_exec as \`extensions.<name>(args)\`; run \`${nativeProfile ? "fabric.tools" : "tools"}.list\` for full descriptions and schemas before re-implementing an effect with pi.bash.`,
2347
- ...[...groups.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([label, names]) => "- " + label + ": " + names.join(", "))
2348
- ].join("\n");
2349
1568
  };
2350
- var fabricSchemaGuidance = (mode) => {
2351
- if (mode === "enforce") {
2352
- return "Schema enforce mode is fixed for this session. Reads remain available, but protected-workspace changes must use schema.hypothesize \u2192 schema.verify \u2192 schema.commit in the same fabric_exec invocation. Direct pi.edit/write/bash/powershell, agents, state/mesh writes, compaction requests, MCP, extensions, and external providers are blocked by the host gate.";
2353
- }
2354
- if (mode === "audit") {
2355
- return "Schema audit mode reports actions that enforce mode would block, but preserves their current behavior.";
2356
- }
2357
- return void 0;
1569
+ var hostPolicyDigest = (policy) => {
1570
+ const sorted = (values) => values ? [...values].sort() : null;
1571
+ const canonical = JSON.stringify([
1572
+ policy.owner,
1573
+ policy.reason,
1574
+ sorted(policy.deniedTools),
1575
+ sorted(policy.deniedProviders),
1576
+ sorted(policy.allowedRefs)
1577
+ ]);
1578
+ return `sha256:${createHash("sha256").update(canonical).digest("hex")}`;
2358
1579
  };
2359
1580
 
2360
1581
  // src/core/skill-prompt.ts
@@ -2362,10 +1583,10 @@ var SKILL_SECTION_HEADING = "The following skills provide specialized instructio
2362
1583
  var PI_SKILL_LOAD_INSTRUCTION = "Use the read tool to load a skill's file when the task matches its description.";
2363
1584
  var FABRIC_SKILL_LOAD_INSTRUCTION = "Use `pi.read` inside `fabric_exec` to load a skill's file when the task matches its description.";
2364
1585
  var CWD_MARKER = "\nCurrent working directory:";
2365
- var restoreSkillsForFullCodePrompt = (systemPrompt, skills, fullCodeMode = true) => {
1586
+ var restoreSkillsForFullCodePrompt = (systemPrompt, skills, fullCodeMode = true, skillReader = void 0) => {
2366
1587
  const section = formatSkillsForPrompt([...skills]).replace(
2367
1588
  PI_SKILL_LOAD_INSTRUCTION,
2368
- fullCodeMode ? FABRIC_SKILL_LOAD_INSTRUCTION : PI_SKILL_LOAD_INSTRUCTION
1589
+ skillReader === null ? "" : skillReader !== void 0 ? `Use \`${skillReader}\` inside \`fabric_exec\` to load a skill's file when the task matches its description.` : fullCodeMode ? FABRIC_SKILL_LOAD_INSTRUCTION : PI_SKILL_LOAD_INSTRUCTION
2369
1590
  );
2370
1591
  const start = systemPrompt.indexOf(SKILL_SECTION_HEADING);
2371
1592
  const end = start < 0 ? -1 : systemPrompt.indexOf("</available_skills>", start);
@@ -2380,9 +1601,9 @@ var restoreSkillsForFullCodePrompt = (systemPrompt, skills, fullCodeMode = true)
2380
1601
 
2381
1602
  // src/core/kernel-skills.ts
2382
1603
  import { statSync } from "node:fs";
2383
- import path5 from "node:path";
1604
+ import path3 from "node:path";
2384
1605
  var fabricSkillPaths = (root, kernel) => {
2385
- const selected = path5.join(root, kernel);
1606
+ const selected = path3.join(root, kernel);
2386
1607
  if (!statSync(selected, { throwIfNoEntry: false })?.isDirectory()) {
2387
1608
  throw new Error(`Missing Fabric ${kernel} skill tree: ${selected}. Reinstall Fabric; no other-kernel fallback is available.`);
2388
1609
  }
@@ -2523,38 +1744,6 @@ var FabricDirectToolApproval = class {
2523
1744
  }
2524
1745
  };
2525
1746
 
2526
- // src/core/skill-references.ts
2527
- var INVOCATION_VERB = /^\s*(?:[-*]\s*)?(?:(?:then|next|first|always|must|you must)\s+)?(?:run|invoke|load|start|follow|use)\b/i;
2528
- var NEGATED_INVOCATION = /^\s*(?:[-*]\s*)?(?:do not|don't|never)\s+(?:run|invoke|load|start|follow|use)\b/i;
2529
- var escapeRegex2 = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2530
- var referencesSkill = (line, skillName) => {
2531
- const name = escapeRegex2(skillName);
2532
- return new RegExp(`/(?:skill:)?${name}(?=[\\s\`'".,;:!?<>)\\]}]|$)`, "i").test(line);
2533
- };
2534
- var buildSkillReferenceGuidance = (prompt, skills) => {
2535
- const active = skills.find(
2536
- (skill) => prompt.startsWith(`<skill name="${skill.name}" location="${skill.filePath}">`)
2537
- );
2538
- if (!active) return void 0;
2539
- const closingTag = prompt.indexOf("</skill>");
2540
- if (closingTag < 0) return void 0;
2541
- const openingEnd = prompt.indexOf("\n\n");
2542
- if (openingEnd < 0 || openingEnd >= closingTag) return void 0;
2543
- const body = prompt.slice(openingEnd + 2, closingTag);
2544
- const invocationLines = body.split("\n").filter((line) => INVOCATION_VERB.test(line) && !NEGATED_INVOCATION.test(line));
2545
- const referenced = skills.filter(
2546
- (skill) => skill.name !== active.name && skill.disableModelInvocation !== true && invocationLines.some((line) => referencesSkill(line, skill.name))
2547
- );
2548
- if (referenced.length === 0) return void 0;
2549
- const mappings = referenced.map((skill) => `- /${skill.name} -> ${JSON.stringify(skill.filePath)}`).join("\n");
2550
- return [
2551
- `The active skill ${JSON.stringify(active.name)} is already expanded; do not reread ${JSON.stringify(active.filePath)}.`,
2552
- "Resolve the skill invocations below before task exploration:",
2553
- mappings,
2554
- "Load each mapped SKILL.md through pi.read inside fabric_exec and follow it. Skill loading is a dependency, not task exploration. Continue the active workflow after tool results and later user replies until it completes."
2555
- ].join("\n");
2556
- };
2557
-
2558
1747
  // src/fabric-exec-tool.ts
2559
1748
  import { Container as Container2, Text as Text2 } from "@earendil-works/pi-tui";
2560
1749
  import { Type } from "typebox";
@@ -2574,8 +1763,8 @@ var formatFailureProgress = (trace) => {
2574
1763
  );
2575
1764
  if (completed.length === 0) return void 0;
2576
1765
  const summaries = completed.slice(0, MAX_COMPLETED_CALLS).map((operation) => {
2577
- const path11 = operation.args.path;
2578
- return typeof path11 === "string" ? `${operation.ref}(${compactPath(path11)})` : operation.ref;
1766
+ const path9 = operation.args.path;
1767
+ return typeof path9 === "string" ? `${operation.ref}(${compactPath(path9)})` : operation.ref;
2579
1768
  });
2580
1769
  const omitted = completed.length - summaries.length;
2581
1770
  return [
@@ -2595,7 +1784,8 @@ var OPTIONAL_FABRIC_EXEC_KEYS = [
2595
1784
  "timeout_ms",
2596
1785
  "maxOutputTokens",
2597
1786
  "max_output_tokens",
2598
- "display"
1787
+ "display",
1788
+ "background"
2599
1789
  ];
2600
1790
  var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2601
1791
  var looksLikeJsonObject = (text) => text.startsWith("{") && text.endsWith("}");
@@ -2694,17 +1884,18 @@ var FabricRepeatGuard = class {
2694
1884
  this.warnAt = warnAt;
2695
1885
  this.blockAt = blockAt;
2696
1886
  }
2697
- #code;
1887
+ #fingerprint;
2698
1888
  #count = 0;
2699
- observe(code) {
2700
- this.#count = code === this.#code ? this.#count + 1 : 1;
2701
- this.#code = code;
1889
+ observe(code, payloads) {
1890
+ const fingerprint = stableJsonHash([code, payloads ?? {}]);
1891
+ this.#count = fingerprint === this.#fingerprint ? this.#count + 1 : 1;
1892
+ this.#fingerprint = fingerprint;
2702
1893
  return { count: this.#count, blocked: this.#count >= this.blockAt, warn: this.#count >= this.warnAt };
2703
1894
  }
2704
1895
  };
2705
1896
 
2706
1897
  // src/ui/row-balance.ts
2707
- import { truncateToWidth as truncateToWidth3 } from "@earendil-works/pi-tui";
1898
+ import { truncateToWidth as truncateToWidth2 } from "@earendil-works/pi-tui";
2708
1899
  var HiddenRowBorrowingComponent = class {
2709
1900
  constructor(baseLimit, maxLimit, renderLimit, balance) {
2710
1901
  this.baseLimit = baseLimit;
@@ -2736,7 +1927,7 @@ var HiddenRowBorrowingComponent = class {
2736
1927
  }
2737
1928
  this.#cachedWidth = width;
2738
1929
  this.#cachedDeficit = deficit;
2739
- this.#cachedRows = best.map((row) => truncateToWidth3(row, Math.max(1, width)));
1930
+ this.#cachedRows = best.map((row) => truncateToWidth2(row, Math.max(1, width)));
2740
1931
  return this.#cachedRows;
2741
1932
  }
2742
1933
  invalidate() {
@@ -2785,19 +1976,19 @@ var PartialResultObserver = class {
2785
1976
  };
2786
1977
 
2787
1978
  // src/output-budget.ts
2788
- import fs2 from "node:fs/promises";
2789
- import path6 from "node:path";
1979
+ import fs from "node:fs/promises";
1980
+ import path4 from "node:path";
2790
1981
  var MAX_FAILURE_MODEL_OUTPUT_CHARS = 2e4;
2791
1982
  var modelOutputBudget = (configuredMaxChars, success) => success ? configuredMaxChars : Math.min(configuredMaxChars, MAX_FAILURE_MODEL_OUTPUT_CHARS);
2792
1983
  var writeOutputArtifact = async (content) => {
2793
1984
  const directory = createScratch("output");
2794
1985
  try {
2795
- const artifactPath = path6.join(directory, "output.txt");
2796
- await fs2.writeFile(artifactPath, content, { encoding: "utf8", mode: 384, flag: "wx" });
1986
+ const artifactPath = path4.join(directory, "output.txt");
1987
+ await fs.writeFile(artifactPath, content, { encoding: "utf8", mode: 384, flag: "wx" });
2797
1988
  closeScratch(directory);
2798
1989
  return artifactPath;
2799
1990
  } catch (error) {
2800
- await fs2.rm(directory, { recursive: true, force: true }).catch(() => void 0);
1991
+ await fs.rm(directory, { recursive: true, force: true }).catch(() => void 0);
2801
1992
  throw error;
2802
1993
  }
2803
1994
  };
@@ -2840,16 +2031,19 @@ var RESULT_FORMATS = ["auto", "yaml", "json", "text"];
2840
2031
  var MAX_FABRIC_CODE_TRANSFER_LINES = 12;
2841
2032
  var toolDisplayMode = (state) => state.bootstrapped ? state.config.ui.toolDisplay : "full";
2842
2033
  var toolKernel = (state) => state.bootstrapped ? state.config.executor?.kernel ?? "typescript" : "typescript";
2843
- var compactResultHeader = (theme, audits, failed) => {
2844
- const failedCalls = audits.filter((audit) => audit.success === false).length;
2034
+ var compactResultHeader = (theme, audits, failed, omittedCalls2 = 0, omittedFailed = 0) => {
2035
+ const failedCalls = audits.filter((audit) => audit.success === false).length + omittedFailed;
2845
2036
  const isFailed = failed || failedCalls > 0;
2846
2037
  return theme.fg(isFailed ? "error" : "success", `${isFailed ? "\u2717" : "\u2713"} Tools`) + theme.fg(
2847
2038
  "dim",
2848
- ` \xB7 ${countLabel(audits.length, "call")}${failedCalls > 0 ? ` \xB7 ${failedCalls} failed` : ""}`
2039
+ ` \xB7 ${countLabel(audits.length + omittedCalls2, "call")}${failedCalls > 0 ? ` \xB7 ${failedCalls} failed` : ""}`
2849
2040
  );
2850
2041
  };
2851
2042
  var countLabel = (count, singular) => `${count} ${count === 1 ? singular : `${singular}s`}`;
2852
- var createFabricExecTool = (state, codePreviewSettings, pendingHandoffs, decorateShell = withCodePreviewShell, toolDisplay) => {
2043
+ var FABRIC_DETACHED_OUTPUT_CHARS = 6e3;
2044
+ var fabricDetachedText = (taskId, elapsedMs, requested) => `[fabric_exec ${requested ? "started in the background" : `moved to the background by the user after ${Math.max(1, Math.round(elapsedMs / 1e3))}s`} as task ${taskId}. It keeps running with its tools, child agents, and approvals; its result arrives automatically as a background task event when it finishes. Continue independent work, or end this turn if you need the result. Do not start the same program again. The user can now steer you while it runs. Inspect with tools.call({ref:'tasks.get',args:{id}}); stop with tasks.stop. Its child agents stay steerable with agents.steer.]`;
2045
+ var createFabricExecTool = (state, codePreviewSettings, pendingHandoffs, decorateShell = withCodePreviewShell, toolDisplay, terminalTitle) => {
2046
+ const managedHost = state.managedHostOptions;
2853
2047
  const python = toolKernel(state) === "python";
2854
2048
  const monty = python && state.config.executor.pythonRuntime === "monty";
2855
2049
  const repeatGuard = new FabricRepeatGuard(FABRIC_REPEAT_WARN, FABRIC_REPEAT_BLOCK);
@@ -2867,9 +2061,11 @@ var createFabricExecTool = (state, codePreviewSettings, pendingHandoffs, decorat
2867
2061
  );
2868
2062
  },
2869
2063
  label: "Fabric",
2870
- description: python ? monty ? "Execute Python through Fabric's configured Monty sandbox. Monty runs a Python subset with VM resource limits, no native filesystem/network/environment access, and only host-mediated tools. Each invocation starts fresh. This is the exclusive model tool path in full code mode and Schema enforce mode." : "Execute Python through Fabric\u2019s configured CPython kernel for Pi core tools, MCP, providers, discovery, and extensions. Each call uses a fresh process. Native execution is trusted code; Schema enforce requires OS isolation. This is the exclusive model tool path in full code mode and Schema enforce mode." : "Execute code through Fabric's TypeScript kernel: type-checked TypeScript by default, unmodified JavaScript with executor.codemodeProfile native. Both support nativeTools; native mode places Pi-compatible calls on tools and Fabric discovery on fabric.tools. Compose Pi core tools, MCP, Fabric providers, discovery, and extensions. QuickJS is isolated by default; the optional Node/Bun process is an unsafe trusted-code escape hatch. In full code mode, and always in Schema enforce mode, this is the exclusive model tool path.",
2871
- promptSnippet: "Pi core tools, MCP, Fabric providers, discovery, and extensions",
2872
- promptGuidelines: [
2064
+ description: managedHost ? "Execute type-checked TypeScript in the managed QuickJS runtime. See the managed execution guidance for authorized tool contracts." : python ? monty ? "Execute Python through Fabric's configured Monty sandbox. Monty runs a Python subset with VM resource limits, no native filesystem/network/environment access, and only host-mediated tools. Each invocation starts fresh. This is the exclusive model tool path in full code mode and Schema enforce mode." : "Execute Python through Fabric\u2019s configured CPython kernel for Pi core tools, MCP, providers, discovery, and extensions. Each call uses a fresh process. Native execution is trusted code; Schema enforce requires OS isolation. This is the exclusive model tool path in full code mode and Schema enforce mode." : "Execute code through Fabric's TypeScript kernel: type-checked TypeScript by default, unmodified JavaScript with executor.codemodeProfile native. Both support nativeTools; native mode places Pi-compatible calls on tools and Fabric discovery on fabric.tools. Compose Pi core tools, MCP, Fabric providers, discovery, and extensions. QuickJS is isolated by default; the optional Node/Bun process is an unsafe trusted-code escape hatch. In full code mode, and always in Schema enforce mode, this is the exclusive model tool path.",
2065
+ promptSnippet: managedHost ? `Authorized host tools (${managedHost.providers.join(", ") || "none"}) and deterministic computation` : "Pi core tools, MCP, Fabric providers, discovery, and extensions",
2066
+ promptGuidelines: managedHost ? [
2067
+ "Batch independent operations with bounded concurrency, keep dependent calls ordered, inspect results, and return compact evidence."
2068
+ ] : [
2873
2069
  python ? "Batch independent operations in one `fabric_exec` Python program with `asyncio.gather`; await dependent/conditional steps sequentially. Coalesce independent replacements into one `await pi.edit(path=..., edits=[...])`. Return only the compact final JSON-compatible value." : "Batch independent operations in one `fabric_exec` program (`Promise.all` for parallel, sequential `await` for ordered), not one call per tool; keep dependent/conditional steps sequential. Coalesce non-dependent replacements from one file snapshot into one `pi.edit({path, edits:[...]})`; use `all:true` only for intentional repeated exact anchors. Return only the compact final value; intermediate results stay in the sandbox.",
2874
2070
  python ? "Search before reading with `await pi.grep(pattern=..., path=...)` or `await pi.find(pattern=..., path=...)`, then `await pi.read(path=..., offset=..., limit=...)`. Use Python dict syntax, `True`/`False`/`None`, and bounded searches; unbounded reads cap at 2000 lines or 50KB. Read continuation notices when needed." : "Search before reading: use `pi.grep`/`pi.find` to locate relevant lines, then `pi.read({path, offset, limit})` that range. Escape regex metacharacters, or use `literal:true` for exact punctuated text. Keep fan-out search limits small and widen only on misses. An unbounded `pi.read` returns at most 2000 lines or 50KB and, when truncated, ends with a `Use offset=\u2026` continuation notice; reserve whole-file reads for small files you will use in full.",
2875
2071
  "Keep the acceptance ledger in reasoning or concise progress notes (no tool call): define concrete checks, trace execution before editing, implement end to end, then run targeted tests and direct behavioral probes. Confirm requested public symbols, registrations, and configuration entries. Use the smallest checks that cover the ledger; escalate only for failures or cross-cutting risk. Inspect failures and iterate instead of rerunning unchanged passing checks. A build alone is not completion.",
@@ -2895,7 +2091,7 @@ var createFabricExecTool = (state, codePreviewSettings, pendingHandoffs, decorat
2895
2091
  // back to Record<string, string> before Pi validates.
2896
2092
  parameters: Type.Object({
2897
2093
  code: Type.String({
2898
- description: python ? monty ? "Python async function body executed by Monty, a sandboxed Python subset (not CPython). Top-level await/return and asyncio.gather are supported. Use only Monty's supported syntax/modules; native imports, filesystem, network, and environment are unavailable. Host globals: tools, mcp, memory, state, schema, compact, cache, thinking, components, agents, mesh; full-code mode adds pi and extensions. Await dict/keyword calls; use native dict results r['output']. Payloads: \u03C0.key or payloads['key']. Return JSON-compatible data; each invocation starts fresh." : "Python async function body executed by CPython. Top-level await and return are supported; standard-library imports are available. Globals: tools, mcp, memory, state, schema, compact, cache, thinking, components, agents, mesh; full-code mode adds pi and extensions. Await host calls using a dict or keyword arguments. Results are native dicts/lists: r['output'], not r.output. Use asyncio.gather for concurrency. Named payloads are \u03C0.key or payloads['key']. Return a JSON-compatible value. Each call starts fresh." : "TypeScript function body. Top-level await and return are supported. Globals include `tools`, `mcp`, `memory`, `state`, `schema`, `compact`, `cache`, `thinking`, `agents`, `mesh`, `print`, and `\u03C0`; full-code mode adds `pi` and `extensions`. `\u03C0` contains only the exact keys supplied by this call's `payloads`. See session guidance / `fabric-exec` skill for exact signatures."
2094
+ description: managedHost ? "TypeScript async function body. Top-level await and return are supported. Named payloads are available as \u03C0.key. Follow the managed execution guidance for discovery and tool calls." : python ? monty ? "Python async function body executed by Monty, a sandboxed Python subset (not CPython). Top-level await/return and asyncio.gather are supported. Use only Monty's supported syntax/modules; native imports, filesystem, network, and environment are unavailable. Host globals: tools, mcp, memory, state, schema, compact, cache, thinking, components, agents, mesh; full-code mode adds pi and extensions. Await dict/keyword calls; use native dict results r['output']. Payloads: \u03C0.key or payloads['key']. Return JSON-compatible data; each invocation starts fresh." : "Python async function body executed by CPython. Top-level await and return are supported; standard-library imports are available. Globals: tools, mcp, memory, state, schema, compact, cache, thinking, components, agents, mesh; full-code mode adds pi and extensions. Await host calls using a dict or keyword arguments. Results are native dicts/lists: r['output'], not r.output. Use asyncio.gather for concurrency. Named payloads are \u03C0.key or payloads['key']. Return a JSON-compatible value. Each call starts fresh." : "TypeScript function body. Top-level await and return are supported. Globals include `tools`, `mcp`, `memory`, `state`, `schema`, `compact`, `cache`, `thinking`, `agents`, `mesh`, `print`, and `\u03C0`; full-code mode adds `pi` and `extensions`. `\u03C0` contains only the exact keys supplied by this call's `payloads`. See session guidance / `fabric-exec` skill for exact signatures."
2899
2095
  }),
2900
2096
  payloads: Type.Optional(
2901
2097
  Type.Record(Type.String(), Type.String(), {
@@ -2923,6 +2119,9 @@ var createFabricExecTool = (state, codePreviewSettings, pendingHandoffs, decorat
2923
2119
  description: "Optional whole-program deadline in ms for this invocation; raises (never lowers) the configured executor.timeoutMs, capped by executor.maxTimeoutMs"
2924
2120
  })
2925
2121
  ),
2122
+ background: Type.Optional(Type.Boolean({
2123
+ description: "Run the program as a background task and return at once; its result arrives as a background task event. Use for long workflows (many agents) whose result you do not need before continuing."
2124
+ })),
2926
2125
  timeout_ms: Type.Optional(Type.Integer({ minimum: 1, description: "Hard whole-script deadline in milliseconds; cannot be extended or paused, capped by executor.maxTimeoutMs." })),
2927
2126
  maxOutputTokens: Type.Optional(Type.Integer({ minimum: 1, description: "Per-call output token budget (estimated at four characters per token), capped by executor.maxOutputChars." })),
2928
2127
  max_output_tokens: Type.Optional(Type.Integer({ minimum: 1, description: "Alias of maxOutputTokens." })),
@@ -3133,16 +2332,19 @@ ${preview}` : ""}${hiddenHint}`,
3133
2332
  };
3134
2333
  if (isPartial) {
3135
2334
  const progress = details.progress;
3136
- if (audits.length === 0) {
2335
+ if (audits.length === 0 && !details.omittedCalls) {
3137
2336
  const label = compact ? "Running\u2026" : progress ?? "Running Fabric program\u2026";
3138
2337
  return trackRows(
3139
2338
  new Text2(theme.fg("warning", `\u25C6 ${safeTerminalText(label)}`), 0, 0)
3140
2339
  );
3141
2340
  }
3142
- if (audits.length === 1) {
2341
+ if (audits.length === 1 && !details.omittedCalls) {
3143
2342
  const audit = audits[0];
3144
2343
  const glyph = audit.success === void 0 ? theme.fg("warning", spinner) : audit.success === false ? theme.fg("error", "\u2717") : theme.fg("dim", "\u203A");
3145
2344
  let text2 = `${glyph} ${nestedCallTitle(audit, theme, context?.invalidate, corePreviewContext)}`;
2345
+ if (shellBackgroundShortcut(audit)) {
2346
+ text2 += nl + theme.fg("dim", "Ctrl+B twice \xB7 background waiting shell");
2347
+ }
3146
2348
  const previewLines = renderAgentToolPreviewLines(audit, theme, {
3147
2349
  expanded,
3148
2350
  showTools: showAgentToolPreview,
@@ -3203,6 +2405,7 @@ ${preview}` : ""}${hiddenHint}`,
3203
2405
  progress,
3204
2406
  expanded,
3205
2407
  preview,
2408
+ omittedCalls: details.omittedCalls,
3206
2409
  core: corePreviewContext,
3207
2410
  showAgentToolPreview,
3208
2411
  spinner,
@@ -3243,7 +2446,8 @@ ${preview}` : ""}${hiddenHint}`,
3243
2446
  ];
3244
2447
  };
3245
2448
  const failed = details.success === false;
3246
- if (audits.length === 0) {
2449
+ const omittedCalls2 = details.omittedCalls?.count ?? 0;
2450
+ if (audits.length === 0 && omittedCalls2 === 0) {
3247
2451
  if (failed && details.error) {
3248
2452
  return trackRows(
3249
2453
  new Text2(
@@ -3275,7 +2479,7 @@ ${preview}` : ""}${hiddenHint}`,
3275
2479
  renderBoundedLines(text2.split(nl), theme, codePreviewSettings.diffIntensity)
3276
2480
  );
3277
2481
  }
3278
- if (audits.length === 1) {
2482
+ if (audits.length === 1 && omittedCalls2 === 0) {
3279
2483
  const audit = audits[0];
3280
2484
  let text2 = compact ? `${compactResultHeader(theme, audits, failed)}${nl}${nestedCallTitle(
3281
2485
  audit,
@@ -3333,15 +2537,15 @@ ${preview}` : ""}${hiddenHint}`,
3333
2537
  }
3334
2538
  const failedCalls = audits.filter(
3335
2539
  (audit) => audit.success === false
3336
- ).length;
2540
+ ).length + (details.omittedCalls?.failed ?? 0);
3337
2541
  const status = failed ? "failed" : "complete";
3338
2542
  const statusColor = failed ? "error" : "success";
3339
2543
  const metadata = [
3340
- countLabel(audits.length, "nested call"),
2544
+ countLabel(audits.length + omittedCalls2, "nested call"),
3341
2545
  failedCalls > 0 ? `${failedCalls} failed` : void 0,
3342
2546
  phases.length > 0 ? countLabel(phases.length, "phase") : void 0
3343
2547
  ].filter((value) => Boolean(value));
3344
- let text = compact ? compactResultHeader(theme, audits, failed) : theme.fg(
2548
+ let text = compact ? compactResultHeader(theme, audits, failed, omittedCalls2, details.omittedCalls?.failed ?? 0) : theme.fg(
3345
2549
  statusColor,
3346
2550
  `${failed ? "\u2717" : "\u2713"} Fabric ${status}`
3347
2551
  );
@@ -3350,7 +2554,7 @@ ${preview}` : ""}${hiddenHint}`,
3350
2554
  text += nl + theme.fg("dim", phases.map((phase) => `\u25C6 ${phase}`).join(" "));
3351
2555
  const callLimit = fabricMulticallCallLimit(expanded);
3352
2556
  const callsShown = audits.slice(0, callLimit);
3353
- const callsHidden = audits.length - callsShown.length;
2557
+ const callsHidden = audits.length + omittedCalls2 - callsShown.length;
3354
2558
  let collapsedPreview;
3355
2559
  if (!expanded) {
3356
2560
  for (let index = callsShown.length - 1; index >= 0; index--) {
@@ -3444,7 +2648,8 @@ ${preview}` : ""}${hiddenHint}`,
3444
2648
  await state.ensure(context);
3445
2649
  const joined = Array.isArray(params.code) ? params.code.join("\n") : params.code;
3446
2650
  const code = state.config.executor.kernel === "python" ? joined : repairFabricGuestCode(joined);
3447
- const repeat = repeatGuard.observe(code);
2651
+ const strings = resolveFabricExecPayloads(params);
2652
+ const repeat = repeatGuard.observe(code, strings);
3448
2653
  if (repeat.blocked) {
3449
2654
  return {
3450
2655
  content: [{ type: "text", text: fabricRepeatBlockText(repeat.count) }],
@@ -3453,12 +2658,20 @@ ${preview}` : ""}${hiddenHint}`,
3453
2658
  };
3454
2659
  }
3455
2660
  const runDisplay = normalizeRunDisplay(params.display);
3456
- const strings = resolveFabricExecPayloads(params);
3457
2661
  const tokenBudget = "tokenBudget" in params && typeof params.tokenBudget === "number" ? params.tokenBudget : void 0;
3458
- const result = await state.execution.execute({
2662
+ terminalTitle?.show(context, runDisplay?.name);
2663
+ const program = state.programTasks?.begin({
2664
+ code,
2665
+ ...runDisplay?.name ? { description: runDisplay.name } : {},
2666
+ cwd: context.cwd,
2667
+ ...signal ? { parentSignal: signal } : {},
2668
+ jobs: () => state.shellJobs
2669
+ });
2670
+ if (params.background === true) program?.detach();
2671
+ const execution = state.execution.execute({
3459
2672
  code,
3460
2673
  ...strings ? { strings } : {},
3461
- signal,
2674
+ signal: program?.signal ?? signal,
3462
2675
  parentToolCallId: toolCallId,
3463
2676
  context,
3464
2677
  ...tokenBudget !== void 0 ? { tokenBudget } : {},
@@ -3472,132 +2685,157 @@ ${preview}` : ""}${hiddenHint}`,
3472
2685
  }
3473
2686
  } : {},
3474
2687
  onPartial(snapshot) {
3475
- onUpdate?.({
3476
- content: [{ type: "text", text: snapshot.progress ?? "" }],
3477
- details: {
3478
- progress: snapshot.progress,
3479
- audits: snapshot.audits,
3480
- phases: snapshot.phases
3481
- }
2688
+ program?.progress(snapshot.progress);
2689
+ if (program?.job || !onUpdate) return;
2690
+ const details = createFabricPartialExecutionDetails(snapshot);
2691
+ onUpdate({
2692
+ content: [{ type: "text", text: details.progress ?? "" }],
2693
+ details
3482
2694
  });
3483
2695
  }
3484
2696
  });
3485
- const selectedResultFormat = params.resultFormat ?? state.config.executor.resultFormat;
3486
- const boundarySessionId = context.sessionManager.getSessionId();
3487
- const pendingHandoff = await state.claimHandoff(
3488
- result,
3489
- boundarySessionId,
3490
- selectedResultFormat,
3491
- toolCallId
3492
- );
3493
- if (pendingHandoff) {
3494
- pendingHandoffs.set(toolCallId, pendingHandoff);
3495
- context.ui.setStatus(
3496
- "fabric-prewalk",
3497
- `waiting for fabric_exec boundary \u2192 ${String(pendingHandoff.args.model ?? "executor")}`
2697
+ const finishExecution = async (result, detached) => {
2698
+ const selectedResultFormat = params.resultFormat ?? state.config.executor.resultFormat;
2699
+ const boundarySessionId = context.sessionManager.getSessionId();
2700
+ const pendingHandoff = detached ? void 0 : await state.claimHandoff(
2701
+ result,
2702
+ boundarySessionId,
2703
+ selectedResultFormat,
2704
+ toolCallId
3498
2705
  );
3499
- if (pendingHandoff.readiness?.kind === "unplanned") {
3500
- context.ui.notify(
3501
- `Prewalk: handing off without a recorded plan after ${pendingHandoff.readiness.prompts} reminders.`,
3502
- "warning"
2706
+ if (pendingHandoff) {
2707
+ pendingHandoffs.set(toolCallId, pendingHandoff);
2708
+ context.ui.setStatus(
2709
+ "fabric-prewalk",
2710
+ `waiting for fabric_exec boundary \u2192 ${String(pendingHandoff.args.model ?? "executor")}`
2711
+ );
2712
+ if (pendingHandoff.readiness?.kind === "unplanned") {
2713
+ context.ui.notify(
2714
+ `Prewalk: handing off without a recorded plan after ${pendingHandoff.readiness.prompts} reminders.`,
2715
+ "warning"
2716
+ );
2717
+ }
2718
+ } else if (!detached && state.prewalk.planRequired(boundarySessionId)) {
2719
+ const prewalkStatus = state.prewalk.status();
2720
+ context.ui.setStatus(
2721
+ "fabric-prewalk",
2722
+ prewalkStatus.state === "armed" ? `plan awaited \u2192 ${prewalkStatus.model}` : void 0
3503
2723
  );
3504
2724
  }
3505
- } else if (state.prewalk.planRequired(boundarySessionId)) {
3506
- const prewalkStatus = state.prewalk.status();
3507
- context.ui.setStatus(
3508
- "fabric-prewalk",
3509
- prewalkStatus.state === "armed" ? `plan awaited \u2192 ${prewalkStatus.model}` : void 0
3510
- );
3511
- }
3512
- const fullFormattedValue = formatFabricValue(result.value, selectedResultFormat);
3513
- const failureProgress = formatFailureProgress(result.trace);
3514
- const fullSections = [...result.logs];
3515
- if (fullFormattedValue.text) fullSections.push(fullFormattedValue.text);
3516
- if (result.error) fullSections.push(`Runtime error: ${result.error}`);
3517
- if (failureProgress) fullSections.push(failureProgress);
3518
- if (repeat.warn) fullSections.push(fabricRepeatWarnText(repeat.count, FABRIC_REPEAT_BLOCK));
3519
- const fullRawOutput = fullSections.join("\n\n");
3520
- const outputBudget = modelOutputBudget(
3521
- Math.min(state.config.executor.maxOutputChars, (params.maxOutputTokens ?? params.max_output_tokens ?? Infinity) * 4),
3522
- result.success
3523
- );
3524
- const outputWillTruncate = fullRawOutput.length > outputBudget;
3525
- const formattedValue = outputWillTruncate ? formatFabricValue(
3526
- result.value,
3527
- selectedResultFormat,
3528
- outputBudget
3529
- ) : fullFormattedValue;
3530
- const sections = [...result.logs];
3531
- const logPrefix = result.logs.join("\n\n");
3532
- if (formattedValue.text) sections.push(formattedValue.text);
3533
- if (result.error) sections.push(`Runtime error: ${result.error}`);
3534
- if (failureProgress) sections.push(failureProgress);
3535
- if (repeat.warn) sections.push(fabricRepeatWarnText(repeat.count, FABRIC_REPEAT_BLOCK));
3536
- const rawOutput = sections.join("\n\n");
3537
- const outputFormat = formattedValue.language && formattedValue.text && (result.logs.length === 0 || !outputWillTruncate) ? formattedValue.language : void 0;
3538
- const outputFormatStartLine = result.logs.length > 0 ? countNewlines(logPrefix) + 2 : 0;
3539
- const persistedRenderDetails = () => createFabricPersistedExecutionDetails({
3540
- ...result,
3541
- ...outputFormat ? { outputFormat, outputFormatStartLine } : {},
3542
- ...outputFormat ? {
3543
- outputFormatLines: formattedValue.highlightedLineCount ?? countNewlines(formattedValue.text) + 1
3544
- } : {}
3545
- });
3546
- if (result.typeErrors) {
3547
- const text = result.typeErrors.map(
3548
- (error) => error.line > 0 ? `Line ${error.line}:${error.column} \u2014 ${error.message}` : error.message
3549
- ).join("\n");
3550
- const { typeErrorRecoveryHint } = await import("../type-error-guidance.js");
3551
- const recoveryHint = typeErrorRecoveryHint(code, result.typeErrors);
3552
- const bounded = await boundModelOutput(
3553
- `Type errors; code was not executed:
2725
+ const fullFormattedValue = formatFabricValue(result.value, selectedResultFormat);
2726
+ const failureProgress = formatFailureProgress(result.trace);
2727
+ const fullSections = [...result.logs];
2728
+ if (fullFormattedValue.text) fullSections.push(fullFormattedValue.text);
2729
+ if (result.error) fullSections.push(`Runtime error: ${result.error}`);
2730
+ if (failureProgress) fullSections.push(failureProgress);
2731
+ if (repeat.warn) fullSections.push(fabricRepeatWarnText(repeat.count, FABRIC_REPEAT_BLOCK));
2732
+ const fullRawOutput = fullSections.join("\n\n");
2733
+ const outputBudget = modelOutputBudget(
2734
+ Math.min(
2735
+ state.config.executor.maxOutputChars,
2736
+ (params.maxOutputTokens ?? params.max_output_tokens ?? Infinity) * 4,
2737
+ detached ? FABRIC_DETACHED_OUTPUT_CHARS : Infinity
2738
+ ),
2739
+ result.success
2740
+ );
2741
+ const outputWillTruncate = fullRawOutput.length > outputBudget;
2742
+ const formattedValue = outputWillTruncate ? formatFabricValue(
2743
+ result.value,
2744
+ selectedResultFormat,
2745
+ outputBudget
2746
+ ) : fullFormattedValue;
2747
+ const sections = [...result.logs];
2748
+ const logPrefix = result.logs.join("\n\n");
2749
+ if (formattedValue.text) sections.push(formattedValue.text);
2750
+ if (result.error) sections.push(`Runtime error: ${result.error}`);
2751
+ if (failureProgress) sections.push(failureProgress);
2752
+ if (repeat.warn) sections.push(fabricRepeatWarnText(repeat.count, FABRIC_REPEAT_BLOCK));
2753
+ const rawOutput = sections.join("\n\n");
2754
+ const outputFormat = formattedValue.language && formattedValue.text && (result.logs.length === 0 || !outputWillTruncate) ? formattedValue.language : void 0;
2755
+ const outputFormatStartLine = result.logs.length > 0 ? countNewlines(logPrefix) + 2 : 0;
2756
+ const persistedRenderDetails = () => createFabricPersistedExecutionDetails({
2757
+ ...result,
2758
+ ...outputFormat ? { outputFormat, outputFormatStartLine } : {},
2759
+ ...outputFormat ? {
2760
+ outputFormatLines: formattedValue.highlightedLineCount ?? countNewlines(formattedValue.text) + 1
2761
+ } : {}
2762
+ });
2763
+ if (result.typeErrors) {
2764
+ const text = result.typeErrors.map(
2765
+ (error) => error.line > 0 ? `Line ${error.line}:${error.column} \u2014 ${error.message}` : error.message
2766
+ ).join("\n");
2767
+ const { typeErrorRecoveryHint } = await import("../type-error-guidance.js");
2768
+ const recoveryHint = typeErrorRecoveryHint(code, result.typeErrors);
2769
+ const bounded = await boundModelOutput(
2770
+ `Type errors; code was not executed:
3554
2771
  ${text}${recoveryHint ? `
3555
2772
 
3556
2773
  ${recoveryHint}` : ""}`,
3557
- outputBudget
3558
- );
2774
+ outputBudget
2775
+ );
2776
+ return {
2777
+ content: [{ type: "text", text: bounded.text }],
2778
+ details: persistedRenderDetails(),
2779
+ isError: true
2780
+ };
2781
+ }
2782
+ const output = (await boundModelOutput(
2783
+ rawOutput || "(no output)",
2784
+ outputBudget,
2785
+ fullRawOutput || "(no output)"
2786
+ )).text;
2787
+ const inPlaceContinuation = pendingHandoff?.kind === "prewalk-in-place";
2788
+ const nestedTerminate = result.success && result.audits.some((audit) => audit.terminate === true && audit.success === true);
2789
+ const terminate = !inPlaceContinuation && (pendingHandoff !== void 0 || nestedTerminate || result.success && typeof result.value === "object" && result.value !== null && "terminate" in result.value && result.value.terminate === true);
2790
+ const mediaBlocks = [];
2791
+ for (const block of result.media ?? []) mediaBlocks.push(block);
2792
+ for (const audit of result.audits) {
2793
+ if (audit.media) mediaBlocks.push(...audit.media);
2794
+ }
2795
+ const singleAudit = result.audits.length === 1 ? result.audits[0] : void 0;
2796
+ const mediaNote = singleAudit?.mediaNote;
2797
+ for (const audit of result.audits) {
2798
+ delete audit.media;
2799
+ delete audit.mediaNote;
2800
+ }
2801
+ const content = [];
2802
+ if (mediaBlocks.length > 0) {
2803
+ const textOutput = singleAudit && mediaNote ? mediaNote : output === "(no output)" ? "" : output;
2804
+ if (textOutput) content.push({ type: "text", text: textOutput });
2805
+ for (const block of mediaBlocks) content.push(block);
2806
+ if (singleAudit && mediaNote) {
2807
+ singleAudit.result = mediaNote;
2808
+ }
2809
+ } else {
2810
+ content.push({ type: "text", text: output });
2811
+ }
3559
2812
  return {
3560
- content: [{ type: "text", text: bounded.text }],
2813
+ content,
3561
2814
  details: persistedRenderDetails(),
3562
- isError: true
2815
+ ...result.usage ? { usage: result.usage } : {},
2816
+ ...terminate ? { terminate: true } : {},
2817
+ ...result.success ? {} : { isError: true }
3563
2818
  };
3564
- }
3565
- const output = (await boundModelOutput(
3566
- rawOutput || "(no output)",
3567
- outputBudget,
3568
- fullRawOutput || "(no output)"
3569
- )).text;
3570
- const inPlaceContinuation = pendingHandoff?.kind === "prewalk-in-place";
3571
- const terminate = !inPlaceContinuation && (pendingHandoff !== void 0 || result.success && typeof result.value === "object" && result.value !== null && "terminate" in result.value && result.value.terminate === true);
3572
- const mediaBlocks = [];
3573
- for (const block of result.media ?? []) mediaBlocks.push(block);
3574
- for (const audit of result.audits) {
3575
- if (audit.media) mediaBlocks.push(...audit.media);
3576
- }
3577
- const singleAudit = result.audits.length === 1 ? result.audits[0] : void 0;
3578
- const mediaNote = singleAudit?.mediaNote;
3579
- for (const audit of result.audits) {
3580
- delete audit.media;
3581
- delete audit.mediaNote;
3582
- }
3583
- const content = [];
3584
- if (mediaBlocks.length > 0) {
3585
- const textOutput = singleAudit && mediaNote ? mediaNote : output === "(no output)" ? "" : output;
3586
- if (textOutput) content.push({ type: "text", text: textOutput });
3587
- for (const block of mediaBlocks) content.push(block);
3588
- if (singleAudit && mediaNote) {
3589
- singleAudit.result = mediaNote;
3590
- }
3591
- } else {
3592
- content.push({ type: "text", text: output });
3593
- }
3594
- return {
3595
- content,
3596
- details: persistedRenderDetails(),
3597
- ...result.usage ? { usage: result.usage } : {},
3598
- ...terminate ? { terminate: true } : {},
3599
- ...result.success ? {} : { isError: true }
3600
2819
  };
2820
+ const raced = program ? await program.race(execution) : { detached: false, value: await execution };
2821
+ if (raced.detached) {
2822
+ void execution.then(
2823
+ async (result) => {
2824
+ const finished = await finishExecution(result, true);
2825
+ const text = finished.content.map((part) => part.type === "text" ? part.text : "[image omitted]").join("\n");
2826
+ await program.complete(text, !finished.isError);
2827
+ },
2828
+ (error) => program.complete(
2829
+ `Runtime error: ${error instanceof Error ? error.message : String(error)}`,
2830
+ false
2831
+ )
2832
+ ).catch(() => void 0);
2833
+ return {
2834
+ content: [{ type: "text", text: fabricDetachedText(raced.job.id, raced.elapsedMs, params.background === true) }],
2835
+ details: void 0
2836
+ };
2837
+ }
2838
+ return finishExecution(raced.value, false);
3601
2839
  }
3602
2840
  }),
3603
2841
  {
@@ -3608,18 +2846,28 @@ ${recoveryHint}` : ""}`,
3608
2846
  };
3609
2847
 
3610
2848
  // src/fabric-state.ts
3611
- import fs3 from "node:fs";
3612
- import path7 from "node:path";
2849
+ import fs2 from "node:fs";
2850
+ import path5 from "node:path";
3613
2851
 
3614
2852
  // src/managed-host.ts
3615
2853
  var REPLACEABLE = /* @__PURE__ */ new Set(["agents", "memory", "compact", "schema", "state", "mesh", "mcp"]);
3616
2854
  var FabricManagedHost = class {
2855
+ options;
3617
2856
  #allowed;
3618
2857
  #providers = /* @__PURE__ */ new Map();
3619
2858
  #retired = /* @__PURE__ */ new Set();
3620
2859
  #sealed = false;
3621
2860
  constructor(options) {
3622
- this.#allowed = new Set(options.providers);
2861
+ const foreground = options.foreground ?? [];
2862
+ foregroundConfigValue({ tools: foreground.map((name) => ({ name, owner: "managed-host", reason: "human-input" })), maxTools: MAX_FOREGROUND_TOOLS });
2863
+ if (foreground.length > MAX_FOREGROUND_TOOLS) throw new Error(`managedHost.foreground accepts at most ${MAX_FOREGROUND_TOOLS} tools`);
2864
+ if (options.skillReader !== void 0 && !/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/.test(options.skillReader)) throw new Error("managedHost.skillReader must be a dotted callable name");
2865
+ if (options.guidance !== void 0 && typeof options.guidance !== "string") throw new Error("managedHost.guidance must be a string");
2866
+ if (options.compaction !== void 0 && !["fabric", "pi"].includes(options.compaction)) throw new Error("Invalid managedHost.compaction");
2867
+ const maxCpuSliceMs = options.executor?.maxCpuSliceMs ?? 1e3;
2868
+ if (!Number.isSafeInteger(maxCpuSliceMs) || maxCpuSliceMs <= 0) throw new Error("managedHost.executor.maxCpuSliceMs must be a positive safe integer");
2869
+ this.options = Object.freeze({ ...options, providers: Object.freeze([...options.providers]), foreground: Object.freeze([...foreground]), executor: Object.freeze({ maxCpuSliceMs }) });
2870
+ this.#allowed = new Set(this.options.providers);
3623
2871
  for (const name of this.#allowed) if (!REPLACEABLE.has(name)) throw new Error(`Managed host cannot replace provider: ${name}`);
3624
2872
  }
3625
2873
  register(provider, overwrite = false) {
@@ -3669,6 +2917,8 @@ var FabricManagedHost = class {
3669
2917
  config.fullCodeMode = true;
3670
2918
  config.executor.kernel = "typescript";
3671
2919
  config.executor.runtime = "quickjs";
2920
+ config.executor.maxCpuSliceMs = this.options.executor.maxCpuSliceMs;
2921
+ config.foreground = { tools: this.options.foreground.map((name) => ({ name, owner: "managed-host", reason: "human-input" })), maxTools: MAX_FOREGROUND_TOOLS };
3672
2922
  config.mcp.enabled = false;
3673
2923
  config.mcp.allowDynamicServers = false;
3674
2924
  config.mesh.enabled = false;
@@ -3679,11 +2929,12 @@ var FabricManagedHost = class {
3679
2929
  config.repairs.enabled = false;
3680
2930
  config.entropy.compile = false;
3681
2931
  config.speculation.enabled = false;
2932
+ config.jev.enabled = false;
3682
2933
  config.ui.enabled = false;
3683
2934
  config.schema.mode = "off";
3684
2935
  config.schema.trustedCommands = {};
3685
2936
  config.components = [];
3686
- config.compaction.engine = "fabric";
2937
+ config.compaction.engine = this.options.compaction ?? "fabric";
3687
2938
  config.approvals = { ...config.approvals, read: "allow", write: "allow", execute: "allow", agent: "allow", network: "deny" };
3688
2939
  return config;
3689
2940
  }
@@ -3695,6 +2946,114 @@ var FabricManagedHost = class {
3695
2946
  }
3696
2947
  };
3697
2948
 
2949
+ // src/core/program-tasks.ts
2950
+ var FabricProgramRun = class {
2951
+ constructor(owner, options) {
2952
+ this.owner = owner;
2953
+ this.options = options;
2954
+ const parent = options.parentSignal;
2955
+ if (parent?.aborted) this.#onParentAbort();
2956
+ else parent?.addEventListener("abort", this.#onParentAbort, { once: true });
2957
+ }
2958
+ #relay = new AbortController();
2959
+ #startedAt = Date.now();
2960
+ #onParentAbort = () => {
2961
+ if (!this.#job) this.#relay.abort(this.options.parentSignal?.reason ?? new Error("fabric_exec aborted"));
2962
+ };
2963
+ #job;
2964
+ #settled = false;
2965
+ #progress;
2966
+ #wake;
2967
+ get signal() {
2968
+ return this.#relay.signal;
2969
+ }
2970
+ get job() {
2971
+ return this.#job;
2972
+ }
2973
+ get waiting() {
2974
+ return !this.#job && !this.#settled && !this.#relay.signal.aborted;
2975
+ }
2976
+ /** Moves the program into the session task store; false when it cannot leave. */
2977
+ detach() {
2978
+ if (!this.waiting) return false;
2979
+ const jobs = this.options.jobs();
2980
+ if (!jobs) return false;
2981
+ let job;
2982
+ try {
2983
+ job = jobs.begin("fabric_exec", this.options.code, {
2984
+ ...this.options.description ? { description: this.options.description } : {},
2985
+ ...this.options.cwd ? { cwd: this.options.cwd } : {}
2986
+ });
2987
+ } catch {
2988
+ return false;
2989
+ }
2990
+ this.#job = job;
2991
+ this.options.parentSignal?.removeEventListener("abort", this.#onParentAbort);
2992
+ job.abort.signal.addEventListener("abort", () => this.#relay.abort(job.abort.signal.reason), { once: true });
2993
+ if (this.#progress) job.append(Buffer.from(`${this.#progress}
2994
+ `));
2995
+ job.spill();
2996
+ void job.persistLog().catch(() => void 0);
2997
+ this.owner.release(this);
2998
+ this.#wake?.();
2999
+ return true;
3000
+ }
3001
+ /** Mirrors changed progress into the task's output once detached. */
3002
+ progress(text) {
3003
+ if (!text || text === this.#progress) return;
3004
+ this.#progress = text;
3005
+ this.#job?.append(Buffer.from(`${text}
3006
+ `));
3007
+ }
3008
+ /** Settles with the program, or earlier when it is detached. */
3009
+ async race(work) {
3010
+ const detached = new Promise((resolve) => {
3011
+ this.#wake = () => resolve("detached");
3012
+ if (this.#job) resolve("detached");
3013
+ });
3014
+ const first = await Promise.race([
3015
+ work.then((value) => ({ value }), (error) => ({ error })),
3016
+ detached
3017
+ ]);
3018
+ if (first === "detached") return { detached: true, job: this.#job, elapsedMs: Date.now() - this.#startedAt };
3019
+ this.#settled = true;
3020
+ this.owner.release(this);
3021
+ if ("error" in first) throw first.error;
3022
+ return { detached: false, value: first.value };
3023
+ }
3024
+ /** Records the program's final model-facing text and ends the task. */
3025
+ async complete(text, success) {
3026
+ this.#settled = true;
3027
+ const job = this.#job;
3028
+ if (!job || job.finished) return;
3029
+ job.append(Buffer.from(`${text}
3030
+ `));
3031
+ job.exitCode = success ? 0 : 1;
3032
+ await job.finish(job.exitCode);
3033
+ }
3034
+ };
3035
+ var FabricProgramTasks = class {
3036
+ #waiting = /* @__PURE__ */ new Set();
3037
+ begin(options) {
3038
+ const run = new FabricProgramRun(this, options);
3039
+ this.#waiting.add(run);
3040
+ return run;
3041
+ }
3042
+ release(run) {
3043
+ this.#waiting.delete(run);
3044
+ }
3045
+ waiting() {
3046
+ let count = 0;
3047
+ for (const run of this.#waiting) if (run.waiting) count++;
3048
+ return count;
3049
+ }
3050
+ detachWaiting() {
3051
+ let count = 0;
3052
+ for (const run of [...this.#waiting]) if (run.detach()) count++;
3053
+ return count;
3054
+ }
3055
+ };
3056
+
3698
3057
  // src/fabric-state.ts
3699
3058
  var FabricState = class {
3700
3059
  constructor(pi, capturedTools, options = {}) {
@@ -3728,6 +3087,12 @@ var FabricState = class {
3728
3087
  prewalk = new PrewalkController();
3729
3088
  prewalkDrift = new PrewalkDriftTracker();
3730
3089
  sessionApprovals = new FabricSessionApprovals();
3090
+ /** Extension hooks registered over pi.events; consulted only when approvals.policyHooks is true. */
3091
+ actionPolicyHooks = new FabricActionPolicyHooks();
3092
+ /** Question renderers registered over pi.events; consulted only when ui.questionRenderers is true. */
3093
+ questionRenderers = new FabricQuestionRenderers();
3094
+ /** Foreground `fabric_exec` programs the Ctrl+B chord can move to the background. */
3095
+ programTasks = new FabricProgramTasks();
3731
3096
  // agent_end must revert an override even before activation; the controller
3732
3097
  // itself loads only when an override can exist.
3733
3098
  thinking;
@@ -3752,6 +3117,9 @@ var FabricState = class {
3752
3117
  if (!this.#config) throw new Error("Pi Fabric has not bootstrapped");
3753
3118
  return this.#config;
3754
3119
  }
3120
+ get managedHostOptions() {
3121
+ return this.#managedHost?.options;
3122
+ }
3755
3123
  get cwd() {
3756
3124
  return this.#cwd;
3757
3125
  }
@@ -3763,6 +3131,7 @@ var FabricState = class {
3763
3131
  policy: config.foreground,
3764
3132
  mode: config.schema.mode === "enforce" ? "enforce" : config.fullCodeMode ? "full-code" : "orchestration",
3765
3133
  managedHost: this.#managedHost !== void 0,
3134
+ managedForeground: this.#managedHost?.options.foreground,
3766
3135
  registered: this.pi.getAllTools(),
3767
3136
  active: new Set(active ?? this.pi.getActiveTools()),
3768
3137
  allowlist: readChildToolAllowlist()
@@ -3869,15 +3238,15 @@ var FabricState = class {
3869
3238
  const sessionId = context.sessionManager.getSessionId();
3870
3239
  if (resolveFabricIdentity(sessionId).identity.kind !== "main") return false;
3871
3240
  const projectRoot = process.env.PI_FABRIC_PROJECT_ROOT ?? context.cwd;
3872
- const meshRoot = process.env.PI_FABRIC_MESH_ROOT ?? (this.config.mesh.root ? path7.resolve(projectRoot, this.config.mesh.root) : path7.join(projectRoot, ".pi", "fabric", "mesh"));
3241
+ const meshRoot = process.env.PI_FABRIC_MESH_ROOT ?? (this.config.mesh.root ? path5.resolve(projectRoot, this.config.mesh.root) : path5.join(projectRoot, ".pi", "fabric", "mesh"));
3873
3242
  const fabricSessionId = process.env.PI_FABRIC_SESSION_ID?.trim() || sessionId;
3874
3243
  const actorRoots = [
3875
- path7.join(meshRoot, "actors"),
3876
- path7.join(meshRoot, "actors", fabricSessionId)
3244
+ path5.join(meshRoot, "actors"),
3245
+ path5.join(meshRoot, "actors", fabricSessionId)
3877
3246
  ];
3878
3247
  return actorRoots.some((actorRoot) => {
3879
3248
  try {
3880
- const registry = JSON.parse(fs3.readFileSync(path7.join(actorRoot, "actors.json"), "utf8"));
3249
+ const registry = JSON.parse(fs2.readFileSync(path5.join(actorRoot, "actors.json"), "utf8"));
3881
3250
  if (typeof registry !== "object" || registry === null || Array.isArray(registry)) return false;
3882
3251
  const actors = registry.actors;
3883
3252
  return Array.isArray(actors) && actors.some((value) => {
@@ -3896,6 +3265,16 @@ var FabricState = class {
3896
3265
  peerInfos() {
3897
3266
  return this.#current()?.peerInfos() ?? [];
3898
3267
  }
3268
+ sessionLabel() {
3269
+ return this.#current()?.sessionLabel();
3270
+ }
3271
+ sessionLabelPending() {
3272
+ return this.#current()?.sessionLabelPending() ?? false;
3273
+ }
3274
+ /** Managed hosts do not expose decisions, matching the `decisions.*` provider. */
3275
+ decisionStore() {
3276
+ return this.#managedHost ? void 0 : this.#current()?.decisionStore();
3277
+ }
3899
3278
  componentGraph() {
3900
3279
  return this.#current()?.componentGraph() ?? { components: [], edges: [], cycles: [] };
3901
3280
  }
@@ -3905,6 +3284,9 @@ var FabricState = class {
3905
3284
  participantInfos(options = {}) {
3906
3285
  return this.#current()?.participantInfos(options) ?? [];
3907
3286
  }
3287
+ residentAgentForUi(id) {
3288
+ return this.#current()?.residentAgentForUi(id);
3289
+ }
3908
3290
  queueUserMessage(targetId, message, delivery) {
3909
3291
  return this.#required().queueUserMessage(targetId, message, delivery);
3910
3292
  }
@@ -4141,10 +3523,14 @@ var FabricState = class {
4141
3523
  prewalk: this.prewalk,
4142
3524
  prewalkDrift: this.prewalkDrift,
4143
3525
  sessionApprovals: this.sessionApprovals,
3526
+ actionPolicyHooks: this.actionPolicyHooks,
3527
+ questionRenderers: this.questionRenderers,
4144
3528
  thinking: await this.thinking.load(),
4145
3529
  ...this.#options.paths ? { paths: this.#options.paths } : {},
4146
3530
  ...this.#entryIdentity ? { entryIdentity: this.#entryIdentity } : {},
4147
- foregroundTools: () => this.foregroundTools().tools
3531
+ foregroundTools: () => this.foregroundTools().tools,
3532
+ compactionOwner: this.#options.compactionOwner,
3533
+ ...this.#options.hostPolicy ? { hostPolicy: this.#options.hostPolicy } : {}
4148
3534
  }
4149
3535
  );
4150
3536
  }
@@ -4157,6 +3543,39 @@ var FabricState = class {
4157
3543
  return runtime;
4158
3544
  }
4159
3545
  };
3546
+ var FabricQuestionRenderers = class {
3547
+ #renderers = /* @__PURE__ */ new Map();
3548
+ get size() {
3549
+ return this.#renderers.size;
3550
+ }
3551
+ /**
3552
+ * Register `render` under `name`; the same name replaces an earlier
3553
+ * renderer in its original position, so a reloaded extension does not stack
3554
+ * copies. The returned function removes only this registration.
3555
+ */
3556
+ register(name, render) {
3557
+ if (!ACTION_POLICY_HOOK_NAME_PATTERN.test(name)) {
3558
+ throw new Error("Question renderer name must match [A-Za-z0-9@][A-Za-z0-9@._/-]{0,63}");
3559
+ }
3560
+ if (typeof render !== "function") throw new Error("Question renderer must be a function");
3561
+ const registration = { render };
3562
+ this.#renderers.set(name, registration);
3563
+ return () => {
3564
+ if (this.#renderers.get(name) === registration) this.#renderers.delete(name);
3565
+ };
3566
+ }
3567
+ clear() {
3568
+ this.#renderers.clear();
3569
+ }
3570
+ /** A snapshot in registration order. */
3571
+ list() {
3572
+ return [...this.#renderers].map(([name, { render }]) => ({ name, render }));
3573
+ }
3574
+ /** This registry when `ui.questionRenderers` is true and a renderer is registered; otherwise undefined. */
3575
+ active(enabled) {
3576
+ return enabled === true && this.size > 0 ? this : void 0;
3577
+ }
3578
+ };
4160
3579
  var branchHasThinkingOverride = (context) => {
4161
3580
  const branch = context.sessionManager.getBranch();
4162
3581
  for (let index = branch.length - 1; index >= 0; index -= 1) {
@@ -4365,8 +3784,8 @@ var classifyToolResult = (input) => {
4365
3784
  };
4366
3785
 
4367
3786
  // src/host-compatibility.ts
4368
- import { existsSync as existsSync3, readFileSync as readFileSync3, realpathSync as realpathSync2 } from "node:fs";
4369
- import path8 from "node:path";
3787
+ import { existsSync as existsSync2, readFileSync as readFileSync2, realpathSync as realpathSync2 } from "node:fs";
3788
+ import path6 from "node:path";
4370
3789
  var MINIMUM_PI_HOST_VERSION = "1.0.0";
4371
3790
  var PI_HOST_PACKAGE_NAMES = /* @__PURE__ */ new Set([
4372
3791
  "@earendil-works/pi-coding-agent",
@@ -4397,22 +3816,22 @@ var detectPiHostVersion = (cliPath = process.argv[1]) => {
4397
3816
  if (!cliPath) return void 0;
4398
3817
  let directory;
4399
3818
  try {
4400
- directory = path8.dirname(realpathSync2(cliPath));
3819
+ directory = path6.dirname(realpathSync2(cliPath));
4401
3820
  } catch {
4402
3821
  return void 0;
4403
3822
  }
4404
3823
  while (true) {
4405
- const manifestPath = path8.join(directory, "package.json");
4406
- if (existsSync3(manifestPath)) {
3824
+ const manifestPath = path6.join(directory, "package.json");
3825
+ if (existsSync2(manifestPath)) {
4407
3826
  try {
4408
- const manifest = JSON.parse(readFileSync3(manifestPath, "utf8"));
3827
+ const manifest = JSON.parse(readFileSync2(manifestPath, "utf8"));
4409
3828
  if (typeof manifest.name === "string" && PI_HOST_PACKAGE_NAMES.has(manifest.name) && typeof manifest.version === "string") {
4410
3829
  return manifest.version;
4411
3830
  }
4412
3831
  } catch {
4413
3832
  }
4414
3833
  }
4415
- const parent = path8.dirname(directory);
3834
+ const parent = path6.dirname(directory);
4416
3835
  if (parent === directory) return void 0;
4417
3836
  directory = parent;
4418
3837
  }
@@ -4425,7 +3844,8 @@ var piHostCompatibilityWarning = (version = detectPiHostVersion()) => {
4425
3844
  };
4426
3845
 
4427
3846
  // src/ui/controller.ts
4428
- import path9 from "node:path";
3847
+ import path7 from "node:path";
3848
+ import { matchesKey as matchesKey2 } from "@earendil-works/pi-tui";
4429
3849
 
4430
3850
  // src/ui/snapshot.ts
4431
3851
  import { isDeepStrictEqual } from "node:util";
@@ -4491,15 +3911,30 @@ var createDashboardSnapshot = (state, events, context, activityRuns, cache, immu
4491
3911
  const actorRecords = state.actors.list();
4492
3912
  const main = state.mainAgentInfo(context);
4493
3913
  const peers = typeof state.peerInfos === "function" ? state.peerInfos() : [];
4494
- const globalActors = state.globalActors.list();
3914
+ let globalActors;
3915
+ try {
3916
+ globalActors = state.globalActors.list();
3917
+ } catch {
3918
+ globalActors = [];
3919
+ }
4495
3920
  const componentGraph = typeof state.componentGraph === "function" ? state.componentGraph() : { components: [], edges: [], cycles: [] };
4496
3921
  const meshEntries = state.config.mesh.enabled ? state.mesh.list("", 200) : [];
4497
3922
  const shells = state.shellJobs?.list().filter((job) => job.spilledAt !== void 0 || job.monitor) ?? [];
3923
+ const sessionLabel = typeof state.sessionLabel === "function" ? state.sessionLabel() : void 0;
3924
+ const residentLogs = {};
3925
+ if (typeof state.residentAgentForUi === "function") {
3926
+ for (const participant of participants) {
3927
+ if (participant.kind !== "agent" || participant.rootId !== main.id || participant.residency !== "durable") continue;
3928
+ const record = state.residentAgentForUi(participant.id);
3929
+ if (record && isRunRecord(record) && record.logFile) residentLogs[participant.id] = record.logFile;
3930
+ }
3931
+ }
4498
3932
  const inputs = {
4499
3933
  runs,
4500
3934
  agentRecords,
4501
3935
  actorRecords,
4502
3936
  participants,
3937
+ residentLogs,
4503
3938
  main,
4504
3939
  peers,
4505
3940
  shells,
@@ -4507,7 +3942,8 @@ var createDashboardSnapshot = (state, events, context, activityRuns, cache, immu
4507
3942
  componentGraph,
4508
3943
  meshEntries,
4509
3944
  events,
4510
- widgetDismissedAt: state.widgetDismissedAt
3945
+ widgetDismissedAt: state.widgetDismissedAt,
3946
+ sessionLabel
4511
3947
  };
4512
3948
  const previous = cache?.get(inputs);
4513
3949
  if (previous) return previous;
@@ -4556,6 +3992,7 @@ var createDashboardSnapshot = (state, events, context, activityRuns, cache, immu
4556
3992
  updatedAt: record.updatedAt,
4557
3993
  ...record.finishedAt !== void 0 ? { finishedAt: record.finishedAt } : {},
4558
3994
  ...record.currentTool ? { currentTool: record.currentTool } : {},
3995
+ ...record.milestone ? { milestone: record.milestone } : {},
4559
3996
  turns: record.turns,
4560
3997
  toolCalls: record.toolCalls,
4561
3998
  usage: { ...record.usage },
@@ -4618,6 +4055,7 @@ var createDashboardSnapshot = (state, events, context, activityRuns, cache, immu
4618
4055
  cwd: participant.cwd ?? "",
4619
4056
  ...participant.model ? { model: participant.model } : {},
4620
4057
  ...participant.thinking ? { thinking: participant.thinking } : {},
4058
+ ...residentLogs[participant.id] ? { logFile: residentLogs[participant.id] } : {},
4621
4059
  ...participant.currentTool ? { currentTool: participant.currentTool } : {},
4622
4060
  startedAt: participant.startedAt,
4623
4061
  updatedAt: participant.updatedAt,
@@ -4658,6 +4096,7 @@ var createDashboardSnapshot = (state, events, context, activityRuns, cache, immu
4658
4096
  main,
4659
4097
  peers,
4660
4098
  participants,
4099
+ ...sessionLabel ? { sessionLabel } : {},
4661
4100
  widgetDismissedAt: state.widgetDismissedAt,
4662
4101
  globalActors,
4663
4102
  agents: visibleAgents,
@@ -4675,7 +4114,7 @@ var createDashboardSnapshot = (state, events, context, activityRuns, cache, immu
4675
4114
  };
4676
4115
 
4677
4116
  // src/ui/widget.ts
4678
- import { matchesKey, truncateToWidth as truncateToWidth4, visibleWidth as visibleWidth3 } from "@earendil-works/pi-tui";
4117
+ import { matchesKey, truncateToWidth as truncateToWidth3, visibleWidth as visibleWidth2 } from "@earendil-works/pi-tui";
4679
4118
 
4680
4119
  // src/ui/retention.ts
4681
4120
  var WIDGET_FINISHED_RETENTION_MS = 3e4;
@@ -4732,15 +4171,7 @@ var FabricWidgetRetention = class {
4732
4171
  };
4733
4172
 
4734
4173
  // src/ui/widget.ts
4735
- var statusGlyph = (status) => {
4736
- if (status === "completed" || status === "done" || status === "exited") return "\u2713";
4737
- if (status === "failed" || status === "timed_out") return "\u2717";
4738
- if (status === "blocked") return "!";
4739
- if (status === "stopped" || status === "cancelled" || status === "killed") return "\u25A0";
4740
- if (status === "queued" || status === "pending" || status === "ready") return "\u25CB";
4741
- if (status === "idle" || status === "state") return "\xB7";
4742
- return spinnerFrame();
4743
- };
4174
+ var circle = (selected) => selected ? "\u25CF" : "\u25CB";
4744
4175
  var colorStatus = (theme, status, value) => {
4745
4176
  if (status === "completed" || status === "done" || status === "exited") return theme.fg("success", value);
4746
4177
  if (status === "failed" || status === "timed_out") return theme.fg("error", value);
@@ -4762,23 +4193,65 @@ var totalTokens = (snapshot, run) => snapshot.agents.filter((agent) => run ? age
4762
4193
  0
4763
4194
  );
4764
4195
  var totalCost = (snapshot, run) => snapshot.agents.filter((agent) => run ? agent.runId === run.id : isActiveStatus(agent.status)).reduce((sum, agent) => sum + (agent.usage?.cost ?? 0), 0);
4765
- var agentLines = (theme, agent, now) => {
4766
- const status = colorStatus(theme, agent.status, statusGlyph(agent.status));
4767
- const activity = agent.currentTool ?? (agent.error ? `error: ${truncateToWidth4(safeText(agent.error), 48)}` : agent.text && !isActiveStatus(agent.status) ? `result: ${truncateToWidth4(safeText(agent.text), 48)}` : agent.status === "running" ? "thinking" : agent.status);
4196
+ var modelName = (model) => model ? safeText(model.slice(model.lastIndexOf("/") + 1)).trim() || void 0 : void 0;
4197
+ var fitLine = (theme, width, lead, flexible, detail, hints) => {
4198
+ const separator = theme.fg("dim", " \xB7 ");
4199
+ const compose = (flex2, details2, hintCount2) => {
4200
+ const tail = [...detail.slice(0, details2), ...hints.slice(0, hintCount2)];
4201
+ return `${lead}${flex2 ? `${flexible.gap}${theme.fg(flexible.color, flex2)}` : ""}${tail.length > 0 ? `${separator}${tail.map((part) => theme.fg("dim", part)).join(separator)}` : ""}`;
4202
+ };
4203
+ let details = detail.length;
4204
+ let hintCount = hints.length;
4205
+ let flex = flexible?.text;
4206
+ while (details > 0 && visibleWidth2(compose(flex, details, hintCount)) > width) details--;
4207
+ if (flex && visibleWidth2(compose(flex, details, hintCount)) > width) {
4208
+ const room = width - visibleWidth2(compose(void 0, details, hintCount)) - visibleWidth2(flexible.gap);
4209
+ flex = room >= 6 ? truncateToWidth3(flex, room, "\u2026") : void 0;
4210
+ }
4211
+ while (hintCount > 0 && visibleWidth2(compose(flex, details, hintCount)) > width) hintCount--;
4212
+ return truncateToWidth3(compose(flex, details, hintCount), width, "\u2026");
4213
+ };
4214
+ var treeOrder = (agents) => {
4215
+ const ids = new Set(agents.map((agent) => agent.id));
4216
+ const children = /* @__PURE__ */ new Map();
4217
+ const roots = [];
4218
+ for (const agent of agents) {
4219
+ const parentId = agent.parentId;
4220
+ if (parentId && parentId !== agent.id && ids.has(parentId)) {
4221
+ children.set(parentId, [...children.get(parentId) ?? [], agent]);
4222
+ } else roots.push(agent);
4223
+ }
4224
+ const ordered = [];
4225
+ const seen = /* @__PURE__ */ new Set();
4226
+ const visit = (agent, depth) => {
4227
+ if (seen.has(agent.id)) return;
4228
+ seen.add(agent.id);
4229
+ ordered.push({ agent, depth });
4230
+ for (const child of children.get(agent.id) ?? []) visit(child, depth + 1);
4231
+ };
4232
+ for (const root of roots) visit(root, 0);
4233
+ for (const agent of agents) visit(agent, 0);
4234
+ return ordered;
4235
+ };
4236
+ var agentLine = (theme, agent, now, depth, selected, width) => {
4237
+ const status = colorStatus(theme, agent.status, circle(selected));
4238
+ const live = isActiveStatus(agent.status);
4239
+ const activity = live ? agent.milestone ?? agent.currentTool ?? (agent.status === "running" ? "thinking" : agent.status) : agent.error ? `error: ${safeText(agent.error)}` : agent.text ? `result: ${safeText(agent.text)}` : agent.status;
4768
4240
  const metrics = [
4769
- agent.toolCalls !== void 0 ? `${agent.toolCalls} calls` : void 0,
4241
+ modelName(agent.model),
4242
+ agent.toolCalls !== void 0 ? `${agent.toolCalls} call${agent.toolCalls === 1 ? "" : "s"}` : void 0,
4770
4243
  agent.usage ? `${formatTokens(agent.usage.input + agent.usage.output)} tok` : void 0,
4771
4244
  agent.startedAt ? formatDuration((agent.finishedAt ?? now) - agent.startedAt) : void 0
4772
4245
  ].filter((value) => Boolean(value));
4773
- const indent = " ".repeat(1 + Math.max(0, agent.nestingDepth ?? 0));
4774
- return [
4775
- `${indent}${status} ${theme.fg("muted", safeText(agent.name))} ${theme.fg("muted", safeText(activity))}${metrics.length > 0 ? theme.fg("dim", ` \xB7 ${metrics.join(" \xB7 ")}`) : ""}`
4776
- ];
4246
+ const name = safeText(agent.name);
4247
+ const lead = `${" ".repeat(depth)}${status} ${selected ? theme.bold(name) : theme.fg("muted", name)}`;
4248
+ return fitLine(theme, width, lead, { text: safeText(activity).replace(/\s+/g, " ").trim(), gap: " ", color: "muted" }, metrics, []);
4777
4249
  };
4778
4250
  var shouldShowFabricWidget = (snapshot, mode, retention = new FabricWidgetRetention()) => {
4779
4251
  if (mode === "hidden") return false;
4780
4252
  if (mode === "always") return true;
4781
4253
  retention.sync(snapshot);
4254
+ if (snapshot.sessionLabel) return true;
4782
4255
  if (snapshot.shells?.some((job) => job.finishedAt === void 0 || isRecentWidgetCompletion(job.finishedAt, snapshot.now))) return true;
4783
4256
  if (snapshot.agents.some((agent) => retention.visible(agent, snapshot))) return true;
4784
4257
  if (snapshot.actors.some((actor) => actor.status !== "stopped")) return true;
@@ -4797,13 +4270,12 @@ var widgetRowLimit = (maxRows, terminalRows) => {
4797
4270
  const paneShare = Math.floor(terminalRows * WIDGET_TERMINAL_ROW_SHARE);
4798
4271
  return Math.max(1, Math.min(configured, paneShare));
4799
4272
  };
4800
- var widgetExpandedRowLimit = (maxRows, terminalRows) => {
4273
+ var widgetFocusedRowLimit = (maxRows, terminalRows) => {
4801
4274
  const limit = widgetRowLimit(maxRows, terminalRows);
4802
- if (terminalRows === void 0 || !Number.isFinite(terminalRows) || terminalRows <= 0) {
4803
- return limit + 2 + WIDGET_ACTIVITY_ROWS;
4804
- }
4275
+ if (terminalRows === void 0 || !Number.isFinite(terminalRows) || terminalRows <= 0) return limit;
4805
4276
  return Math.max(limit, Math.floor(terminalRows * WIDGET_TERMINAL_ROW_SHARE));
4806
4277
  };
4278
+ var HEADER_ROW = "\0main";
4807
4279
  var FabricWidget = class {
4808
4280
  constructor(theme, snapshot, maxRows, terminalRows, retention = new FabricWidgetRetention(), interaction) {
4809
4281
  this.theme = theme;
@@ -4816,51 +4288,49 @@ var FabricWidget = class {
4816
4288
  /** Set by the TUI when the widget gains or loses keyboard focus. */
4817
4289
  focused = false;
4818
4290
  #selectedId;
4819
- #expandedId;
4820
- #activityScroll = 0;
4821
- #activityMaxScroll = 0;
4822
- #paneRows = WIDGET_ACTIVITY_ROWS;
4823
- /** Participant rows of the last render, with their line index in the output. */
4291
+ /** Row under the pointer; it draws like the selection, as Claude Code's hover does. */
4292
+ #hoveredId;
4293
+ /** Selectable rows of the last render, with their line index below the spacer. */
4824
4294
  #rows = [];
4825
- #renderedFocus = false;
4826
- #renderedSelection;
4827
- #renderedExpansion;
4828
- /** Id of the row whose activity pane is open, if any. */
4829
- get expandedId() {
4830
- return this.#expandedId;
4831
- }
4832
- /** Select the first participant row; used when focus arrives from the keyboard. */
4295
+ /** Rows above the header in the last render: the spacer, or none on a one-row budget. */
4296
+ #spacerRows = 1;
4297
+ #renderedInteraction;
4298
+ /** Select the row on screen, or the first row; used when focus arrives from the keyboard. */
4833
4299
  selectDefault() {
4834
4300
  const rows = this.#selectableRows();
4835
- if (!rows.some((row) => row.id === this.#selectedId)) this.#selectedId = this.#expandedId ?? rows[0]?.id;
4301
+ if (rows.some((row) => row.id === this.#selectedId)) return;
4302
+ const viewing = this.interaction?.viewing?.();
4303
+ this.#selectedId = rows.find((row) => row.id === viewing)?.id ?? rows[0]?.id;
4304
+ }
4305
+ /** Select the top row; ↓ from the editor lands on the row next to it. */
4306
+ selectFirst() {
4307
+ this.#selectedId = this.#selectableRows()[0]?.id;
4308
+ }
4309
+ /** True while at least one row can take focus. */
4310
+ hasRows() {
4311
+ return this.#selectableRows().length > 0;
4836
4312
  }
4837
4313
  #interactionKey() {
4838
- return `${this.focused}|${this.#selectedId ?? ""}|${this.#expandedId ?? ""}|${this.#activityScroll}`;
4314
+ return `${this.focused}|${this.#selectedId ?? ""}|${this.#hoveredId ?? ""}|${this.interaction?.viewing?.() ?? ""}|${this.interaction?.collapseIdle?.() ?? ""}`;
4839
4315
  }
4840
4316
  handleInput(data) {
4317
+ this.#hoveredId = void 0;
4841
4318
  const rows = this.#selectableRows();
4842
4319
  const index = Math.max(0, rows.findIndex((row) => row.id === this.#selectedId));
4843
4320
  const select = (next) => {
4844
4321
  const row = rows[Math.max(0, Math.min(rows.length - 1, next))];
4845
- if (!row) return;
4846
- this.#selectedId = row.id;
4847
- if (this.#expandedId && this.#expandedId !== row.id) this.#expand(row.id);
4322
+ if (row) this.#selectedId = row.id;
4848
4323
  };
4849
4324
  if (matchesKey(data, "escape") || matchesKey(data, FABRIC_WIDGET_FOCUS_SHORTCUT)) {
4850
- if (this.#expandedId && matchesKey(data, "escape")) this.#expandedId = void 0;
4851
- else this.interaction?.release();
4325
+ this.interaction?.release();
4852
4326
  } else if (matchesKey(data, "up") || data === "k") {
4853
- select(index - 1);
4327
+ if (index === 0 && matchesKey(data, "up")) this.interaction?.release();
4328
+ else select(index - 1);
4854
4329
  } else if (matchesKey(data, "down") || data === "j") {
4855
4330
  select(index + 1);
4856
- } else if (matchesKey(data, "enter") || data === " ") {
4857
- if (this.#selectedId) this.#toggle(this.#selectedId);
4858
- } else if (this.#expandedId && (matchesKey(data, "pageUp") || data === "K")) {
4859
- this.#activityScroll = Math.min(this.#activityMaxScroll, this.#activityScroll + Math.max(1, this.#paneRows - 1));
4860
- } else if (this.#expandedId && (matchesKey(data, "pageDown") || data === "J")) {
4861
- this.#activityScroll = Math.max(0, this.#activityScroll - Math.max(1, this.#paneRows - 1));
4862
- } else if (this.#expandedId && (matchesKey(data, "end") || data === "G")) {
4863
- this.#activityScroll = 0;
4331
+ } else if (matchesKey(data, "enter")) {
4332
+ const row = rows[index];
4333
+ if (row) this.interaction?.open?.(row);
4864
4334
  } else {
4865
4335
  this.interaction?.release(data);
4866
4336
  return;
@@ -4869,43 +4339,38 @@ var FabricWidget = class {
4869
4339
  }
4870
4340
  handleMouse(event) {
4871
4341
  if (!this.interaction) return void 0;
4872
- if (event.type === "wheel" && this.#expandedId) {
4873
- const delta = Math.sign(event.wheelDelta ?? 0);
4874
- this.#activityScroll = Math.max(0, Math.min(this.#activityMaxScroll, this.#activityScroll - delta * 3));
4342
+ const row = this.#rows.find((candidate) => candidate.line === event.y - this.#spacerRows);
4343
+ if (event.type === "move") {
4344
+ const header = event.y === this.#spacerRows && (this.#lastLines?.length ?? 0) > this.#spacerRows;
4345
+ const hoveredId = row?.id ?? (header ? HEADER_ROW : void 0);
4346
+ if (hoveredId === this.#hoveredId) return { handled: true };
4347
+ this.#hoveredId = hoveredId;
4875
4348
  return { handled: true, render: true };
4876
4349
  }
4877
4350
  if (event.type === "press") return { handled: true };
4878
4351
  if (event.type !== "click" || event.button !== "left") return void 0;
4879
- const row = this.#rows.find((candidate) => candidate.line === event.y);
4352
+ this.#hoveredId = void 0;
4880
4353
  if (!row) return void 0;
4881
4354
  this.#selectedId = row.id;
4882
- this.#toggle(row.id);
4355
+ if (this.interaction.open) {
4356
+ this.interaction.open(row);
4357
+ return { handled: true, render: true };
4358
+ }
4883
4359
  return { focus: true, render: true };
4884
4360
  }
4885
- #toggle(id) {
4886
- if (this.#expandedId === id) this.#expandedId = void 0;
4887
- else this.#expand(id);
4888
- }
4889
- #expand(id) {
4890
- this.#expandedId = id;
4891
- this.#activityScroll = 0;
4892
- }
4893
- /** Rows a user can select: the participant rows the widget shows, in drawing order. */
4361
+ /** Focused keyboard traversal can scroll; pointer targets remain viewport-only. */
4894
4362
  #selectableRows() {
4895
- const { lines, rows } = this.#content(this.snapshot());
4896
- const { listLimit } = this.#layout(lines.length, this.#expandedId !== void 0, this.#rowLimit());
4897
- return rows.filter((row) => row.line < listLimit);
4898
- }
4899
- /** List and pane heights; the pane exists only while a row is expanded. */
4900
- #layout(listLength, expanded, limit) {
4901
- if (!expanded) return { listLimit: limit, paneRows: 0 };
4902
- const budget = widgetExpandedRowLimit(this.maxRows, this.terminalRows?.());
4903
- const listLimit = Math.max(2, Math.min(listLength, limit, budget - 5));
4904
- const paneRows = Math.max(1, Math.min(WIDGET_ACTIVITY_ROWS, budget - Math.min(listLength, listLimit) - 2));
4905
- return { listLimit, paneRows };
4906
- }
4907
- #rowLimit() {
4908
- return widgetRowLimit(this.maxRows, this.terminalRows?.());
4363
+ const budget = this.#rowLimit();
4364
+ if (budget === 0) return [];
4365
+ const { lines, rows } = this.#content(this.snapshot(), Number.MAX_SAFE_INTEGER);
4366
+ const body = Math.max(1, budget - (budget >= 2 ? 1 : 0));
4367
+ const visible = body >= 3 && lines.length > body ? body - 1 : body;
4368
+ return this.focused && body > 1 ? rows : rows.filter((row) => row.line < visible);
4369
+ }
4370
+ #rowLimit(width = this.#lastWidth) {
4371
+ const limit = this.focused ? widgetFocusedRowLimit(this.maxRows, this.terminalRows?.()) : widgetRowLimit(this.maxRows, this.terminalRows?.());
4372
+ const available = width === void 0 ? void 0 : this.interaction?.availableRows?.(width);
4373
+ return available === void 0 || !Number.isFinite(available) ? limit : Math.min(limit, Math.max(0, Math.floor(available)));
4909
4374
  }
4910
4375
  #lastWidth;
4911
4376
  #lastLimit;
@@ -4915,18 +4380,17 @@ var FabricWidget = class {
4915
4380
  render(width) {
4916
4381
  if (width <= 0) return [];
4917
4382
  const snapshot = this.snapshot();
4918
- const limit = this.#rowLimit();
4919
- const interactionChanged = this.#renderedFocus !== this.focused || this.#renderedSelection !== this.#selectedId || this.#renderedExpansion !== this.#interactionKey();
4383
+ const limit = this.#rowLimit(width);
4384
+ const interactionChanged = this.#renderedInteraction !== this.#interactionKey();
4920
4385
  if (interactionChanged) this.#pending = void 0;
4921
- const lines = !interactionChanged && this.#pending?.width === width && this.#pending.limit === limit && this.#pending.snapshot === snapshot ? this.#pending.lines : !interactionChanged && !this.#expandedId && this.#lastWidth === width && this.#lastLimit === limit && this.#lastSnapshot === snapshot && this.#lastLines ? this.#lastLines : this.#renderLines(snapshot, width, limit);
4386
+ const lines = !interactionChanged && this.#pending?.width === width && this.#pending.limit === limit && this.#pending.snapshot === snapshot ? this.#pending.lines : !interactionChanged && this.#lastWidth === width && this.#lastLimit === limit && this.#lastSnapshot === snapshot && this.#lastLines ? this.#lastLines : this.#renderLines(snapshot, width, limit);
4922
4387
  this.#pending = void 0;
4923
- this.#renderedFocus = this.focused;
4924
- this.#renderedSelection = this.#selectedId;
4925
- this.#renderedExpansion = this.#interactionKey();
4388
+ this.#renderedInteraction = this.#interactionKey();
4926
4389
  this.#lastWidth = width;
4927
4390
  this.#lastLimit = limit;
4928
4391
  this.#lastSnapshot = snapshot;
4929
4392
  this.#lastLines = lines;
4393
+ this.interaction?.rendered?.();
4930
4394
  return lines;
4931
4395
  }
4932
4396
  hasChanged() {
@@ -4944,52 +4408,68 @@ var FabricWidget = class {
4944
4408
  this.#lastSnapshot = void 0;
4945
4409
  this.#lastLines = void 0;
4946
4410
  }
4411
+ /**
4412
+ * A blank row separates the list from the footer above it, as in Claude
4413
+ * Code. It counts toward the row budget like any other row, so a one-row
4414
+ * budget drops it and keeps the header.
4415
+ */
4947
4416
  #renderLines(snapshot, width, limit) {
4948
- const { lines, rows } = this.#content(snapshot);
4949
- if (this.#selectedId && !rows.some((row) => row.id === this.#selectedId)) this.#selectedId = rows[0]?.id;
4950
- const expanded = rows.find((row) => row.id === this.#expandedId);
4951
- if (this.#expandedId && !expanded) this.#expandedId = void 0;
4952
- const marked = lines.map((line, index) => {
4953
- const row = rows.find((candidate) => candidate.line === index);
4954
- if (!row || !this.focused || row.id !== this.#selectedId) return line;
4955
- return `${this.theme.fg("accent", "\u25B8")}${line.replace(/^ /, "")}`;
4956
- });
4957
- const { listLimit, paneRows } = this.#layout(lines.length, expanded !== void 0, limit);
4958
- this.#rows = rows.filter((row) => row.line < listLimit);
4959
- if (!expanded) return this.#boundContent(this.#withFocusHint(marked, rows.length > 0), width, limit);
4960
- const list = this.#boundContent(this.#withFocusHint(marked, true), width, listLimit);
4961
- this.#paneRows = paneRows;
4962
- const activity = widgetActivityLines(
4963
- this.theme,
4964
- this.interaction?.activity(expanded),
4965
- width,
4966
- paneRows,
4967
- this.#activityScroll,
4968
- this.interaction?.hideThinking?.() ?? false
4969
- );
4970
- this.#activityMaxScroll = activity.maxScroll;
4971
- this.#activityScroll = Math.min(this.#activityScroll, activity.maxScroll);
4972
- const position = this.#activityScroll > 0 ? ` \xB7 \u2191${this.#activityScroll}` : " \xB7 live";
4973
- const help = this.focused ? "\u2191\u2193 switch \xB7 PgUp/PgDn scroll \xB7 \u23CE/click collapse \xB7 esc close" : `click or ${FABRIC_WIDGET_FOCUS_SHORTCUT} to focus`;
4974
- return [
4975
- ...list,
4976
- widgetDivider(this.theme, width, this.theme.fg("accent", `${safeText(expanded.name)} activity${position}`)),
4977
- ...activity.lines,
4978
- widgetDivider(this.theme, width, this.theme.fg("dim", help))
4979
- ].map((line) => truncateToWidth4(line, width));
4980
- }
4981
- /** Advertise the expand shortcut on the header while participant rows exist. */
4982
- #withFocusHint(lines, hasRows) {
4983
- if (!this.interaction || lines.length === 0 || !hasRows) return lines;
4984
- const hint = this.focused ? "\u2191\u2193 select \xB7 \u23CE expand \xB7 esc back" : FABRIC_WIDGET_FOCUS_HINT;
4985
- return [`${lines[0]} \xB7 ${this.theme.fg("dim", hint)}`, ...lines.slice(1)];
4986
- }
4987
- #content(snapshot) {
4417
+ if (limit === 0) {
4418
+ this.#rows = [];
4419
+ this.#spacerRows = 0;
4420
+ return [];
4421
+ }
4422
+ const spacer = limit >= 2 ? 1 : 0;
4423
+ const body = Math.max(1, limit - spacer);
4424
+ let { lines, rows } = this.#content(snapshot, width);
4425
+ if (this.#selectedId !== void 0 && !rows.some((row) => row.id === this.#selectedId)) {
4426
+ this.#selectedId = rows[0]?.id;
4427
+ if (this.focused) ({ lines, rows } = this.#content(snapshot, width));
4428
+ }
4429
+ if (this.#hoveredId !== void 0 && this.#hoveredId !== HEADER_ROW && !rows.some((row) => row.id === this.#hoveredId)) {
4430
+ this.#hoveredId = void 0;
4431
+ }
4432
+ const selectedLine = this.focused && body > 1 ? rows.find((row) => row.id === this.#selectedId)?.line ?? 0 : 0;
4433
+ let capacity = body - 1;
4434
+ let start = Math.max(1, selectedLine - capacity + 1);
4435
+ let below = Math.max(0, lines.length - start - capacity);
4436
+ if (below > 0 && body >= 3) {
4437
+ capacity--;
4438
+ start = Math.max(1, selectedLine - capacity + 1);
4439
+ below = Math.max(0, lines.length - start - capacity);
4440
+ }
4441
+ const above = start - 1;
4442
+ const upLabel = above > 0 ? `\u2191 ${above} more` : void 0;
4443
+ const downLabel = body < 3 && below > 0 ? `\u2193 ${below} more` : void 0;
4444
+ let label = upLabel ?? downLabel;
4445
+ if (upLabel && downLabel) {
4446
+ const identityWidth = 2 + visibleWidth2(safeText(snapshot.sessionLabel ?? "Fabric"));
4447
+ const candidates = [`${upLabel} \xB7 ${downLabel}`, `\u2191 ${above} \xB7 \u2193 ${below}`, upLabel, `\u2191 ${above}`];
4448
+ const fits = (candidate, identity) => visibleWidth2(candidate) + 1 + identity <= width;
4449
+ label = candidates.find((candidate) => fits(candidate, identityWidth)) ?? candidates.find((candidate) => fits(candidate, Math.min(identityWidth, 8)));
4450
+ }
4451
+ const headerWidth = label && width >= visibleWidth2(label) + 2 ? width - visibleWidth2(label) - 1 : width;
4452
+ const header = headerWidth === width ? lines[0] ?? "" : this.#content(snapshot, width, headerWidth).lines[0] ?? "";
4453
+ const boundedHeader = label ? this.#withRightLabel(header, label, width) : truncateToWidth3(header, width);
4454
+ const visibleLines = [boundedHeader, ...lines.slice(start, start + capacity).map((line) => truncateToWidth3(line, width))];
4455
+ if (below > 0 && body >= 3) visibleLines.push(truncateToWidth3(this.theme.fg("dim", `\u2193 ${below} more`), width));
4456
+ this.#rows = rows.filter((row) => row.line === 0 || row.line >= start && row.line < start + capacity).map((row) => ({ ...row, line: row.line === 0 ? 0 : row.line - start + 1 }));
4457
+ if (rows.length === 0 && this.interaction?.collapseIdle?.()) return [];
4458
+ this.#spacerRows = spacer;
4459
+ return [...spacer ? [""] : [], ...visibleLines];
4460
+ }
4461
+ /** Key hints for the header, most important first; the line fitter drops them from the end. */
4462
+ #hints(hasRows) {
4463
+ if (!this.interaction || this.interaction.hints === false) return [];
4464
+ if (this.focused) return [...this.interaction.open ? ["\u23CE open"] : [], "\u2191\u2193 select", "esc back"];
4465
+ return hasRows ? [FABRIC_WIDGET_FOCUS_HINT] : [];
4466
+ }
4467
+ #content(snapshot, width, headerWidth = width) {
4988
4468
  const rows = [];
4989
- const lines = this.#buildContent(snapshot, rows);
4469
+ const lines = this.#buildContent(snapshot, rows, width, headerWidth);
4990
4470
  return { lines, rows };
4991
4471
  }
4992
- #buildContent(snapshot, rows = []) {
4472
+ #buildContent(snapshot, rows, width, headerWidth) {
4993
4473
  const candidateRun = snapshot.runs[0];
4994
4474
  const candidateFinishedAt = candidateRun?.finishedAt ?? candidateRun?.updatedAt ?? 0;
4995
4475
  const run = candidateRun && (candidateRun.status === "running" || candidateFinishedAt > (snapshot.widgetDismissedAt ?? 0)) ? candidateRun : void 0;
@@ -5002,10 +4482,10 @@ var FabricWidget = class {
5002
4482
  const activeActorWorkers = visibleActors.filter((actor) => actor.worker && isActiveStatus(actor.worker.status)).map((actor) => ({ ...actor.worker, name: actor.name, actorId: actor.id }));
5003
4483
  const terminalActorWorkers = visibleActors.filter((actor) => actor.worker && !isActiveStatus(actor.worker.status)).map((actor) => ({ ...actor.worker, name: actor.name, actorId: actor.id }));
5004
4484
  const nestedCalls = run?.calls.filter((call) => call.kind !== "agent" && call.kind !== "actor") ?? [];
5005
- const title = run?.name ?? "Fabric session";
5006
4485
  const shells = snapshot.shells ?? [];
5007
4486
  const liveShells = shells.filter((job) => job.finishedAt === void 0);
5008
4487
  const recentShells = shells.filter((job) => job.finishedAt !== void 0 && isRecentWidgetCompletion(job.finishedAt, snapshot.now));
4488
+ const listedShells = [...liveShells, ...recentShells];
5009
4489
  const headerStatus = run?.status ?? (activeAgents.length > 0 || activeActorWorkers.length > 0 || liveShells.length > 0 ? "running" : "idle");
5010
4490
  const parts = [];
5011
4491
  const callTotal = nestedCalls.length;
@@ -5025,59 +4505,228 @@ var FabricWidget = class {
5025
4505
  );
5026
4506
  }
5027
4507
  }
5028
- if (liveShells.length > 0) parts.push(`${liveShells.length} shell${liveShells.length === 1 ? "" : "s"}`);
5029
4508
  if (activeAgents.length > 0) parts.push(`${activeAgents.length} running`);
5030
4509
  if (visibleActors.length > 0) parts.push(`${visibleActors.length} actor${visibleActors.length === 1 ? "" : "s"}`);
4510
+ if (liveShells.length > 0) parts.push(`${liveShells.length} shell${liveShells.length === 1 ? "" : "s"}`);
5031
4511
  const tokens = totalTokens(snapshot, run);
5032
4512
  if (tokens > 0) parts.push(`${formatTokens(tokens)} tok`);
5033
4513
  const cost = totalCost(snapshot, run);
5034
4514
  if (cost > 0) parts.push(formatCost(cost));
5035
4515
  const elapsed = run && formatDuration((run.finishedAt ?? snapshot.now) - run.startedAt);
5036
4516
  if (elapsed) parts.push(elapsed);
5037
- const glyph = colorStatus(this.theme, headerStatus, statusGlyph(headerStatus));
5038
- const header = `${glyph} ${this.theme.fg("accent", "Fabric")} ${this.theme.fg(
5039
- "muted",
5040
- safeText(title)
5041
- )}${parts.length > 0 ? this.theme.fg("dim", ` \xB7 ${parts.join(" \xB7 ")}`) : ""}`;
5042
- const hasActiveConversations = activeAgents.some((agent) => !agent.stale) || activeActorWorkers.length > 0 || visibleActors.some((actor) => isActiveStatus(actor.status));
5043
- const taskHint = liveShells.length || recentShells.length ? this.theme.fg("dim", " \xB7 /fabric tasks \xB7 ctrl+alt+t") : "";
5044
- const taskHeader = taskHint ? `${glyph} ${this.theme.fg("accent", "Fabric")}${taskHint}${parts.length ? this.theme.fg("dim", ` \xB7 ${parts.join(" \xB7 ")}`) : ""}` : header;
5045
- const lines = [hasActiveConversations ? `${taskHeader} \xB7 ${this.theme.fg("dim", FABRIC_CONVERSATION_HINT)}` : taskHeader];
5046
- for (const job of [...liveShells, ...recentShells].slice(0, 3)) {
5047
- const elapsed2 = formatDuration((job.finishedAt ?? snapshot.now) - job.startedAt) || "0s";
5048
- const status = job.stopping ? "stopping" : job.status;
5049
- const label = job.monitor && job.finishedAt === void 0 && !job.stopping ? `monitor:${job.monitor.delivery}` : status;
5050
- const glyph2 = colorStatus(this.theme, status, statusGlyph(status));
5051
- lines.push(
5052
- ` ${glyph2} ${this.theme.fg("muted", job.id.slice(0, 8))} ${this.theme.fg("muted", label)}${this.theme.fg("dim", ` \xB7 ${elapsed2} \xB7 `)}${this.theme.fg("muted", safeText(job.description ?? job.command))}`
5053
- );
5054
- }
5055
- if (liveShells.length + recentShells.length > 3) lines.push(this.theme.fg("dim", ` +${liveShells.length + recentShells.length - 3} more shell tasks`));
5056
- const pushParticipant = (agent, kind) => {
4517
+ const headerId = this.interaction?.mainId ?? HEADER_ROW;
4518
+ const marked = this.#hoveredId ?? (this.focused && this.#selectedId !== void 0 ? this.#selectedId : this.interaction?.viewing?.() ?? headerId);
4519
+ const participants = [...activeAgents, ...terminalAgents, ...activeActorWorkers, ...terminalActorWorkers];
4520
+ const lines = [];
4521
+ const label = safeText(snapshot.sessionLabel ?? "Fabric");
4522
+ if (this.interaction?.mainId !== void 0) rows.push({ id: headerId, kind: "main", name: label, line: 0 });
4523
+ const hasRows = participants.length > 0 || listedShells.length > 0 || this.interaction?.mainId !== void 0;
4524
+ lines.push(fitLine(
4525
+ this.theme,
4526
+ headerWidth,
4527
+ `${colorStatus(this.theme, headerStatus, circle(marked === headerId))} ${this.theme.fg("accent", this.theme.bold(label))}`,
4528
+ run?.name ? { text: safeText(run.name), gap: " ", color: "muted" } : void 0,
4529
+ parts,
4530
+ this.#hints(hasRows)
4531
+ ));
4532
+ const pushParticipant = (agent, kind, depth = 0) => {
5057
4533
  const id = kind === "actor" ? agent.actorId ?? agent.id : agent.id;
5058
- rows.push({ id, kind, name: agent.name, line: lines.length });
5059
- lines.push(...agentLines(this.theme, agent, snapshot.now));
4534
+ rows.push({
4535
+ id,
4536
+ kind,
4537
+ name: agent.name,
4538
+ ...agent.model ? { model: agent.model } : {},
4539
+ line: lines.length
4540
+ });
4541
+ lines.push(agentLine(this.theme, agent, snapshot.now, depth, id === marked, width));
5060
4542
  };
5061
- for (const agent of activeAgents) pushParticipant(agent, "agent");
4543
+ const liveTrees = [];
4544
+ const settledTrees = [];
4545
+ let liveRoot = false;
4546
+ for (const entry of treeOrder([...activeAgents, ...terminalAgents])) {
4547
+ if (entry.depth === 0) liveRoot = isActiveStatus(entry.agent.status);
4548
+ (liveRoot ? liveTrees : settledTrees).push(entry);
4549
+ }
4550
+ for (const { agent, depth } of liveTrees) pushParticipant(agent, "agent", depth);
5062
4551
  for (const agent of activeActorWorkers) pushParticipant(agent, "actor");
5063
4552
  for (const agent of terminalActorWorkers) pushParticipant(agent, "actor");
5064
- for (const agent of terminalAgents) pushParticipant(agent, "agent");
4553
+ for (const { agent, depth } of settledTrees) pushParticipant(agent, "agent", depth);
4554
+ const shellLine = (job, name, detail, id) => {
4555
+ const status = job.stopping ? "stopping" : job.status;
4556
+ const elapsed2 = formatDuration((job.finishedAt ?? snapshot.now) - job.startedAt) || "0s";
4557
+ const selected = id === marked;
4558
+ return fitLine(
4559
+ this.theme,
4560
+ width,
4561
+ `${colorStatus(this.theme, status, circle(selected))} ${selected ? this.theme.bold(name) : this.theme.fg("muted", name)}${detail ? ` ${this.theme.fg("muted", detail)}` : ""}`,
4562
+ { text: safeText(job.description ?? job.command), gap: this.theme.fg("dim", ` \xB7 ${elapsed2} \xB7 `), color: "muted" },
4563
+ [],
4564
+ []
4565
+ );
4566
+ };
4567
+ for (const job of listedShells) {
4568
+ const status = job.stopping ? "stopping" : job.status;
4569
+ const label2 = job.monitor && job.finishedAt === void 0 && !job.stopping ? `monitor:${job.monitor.delivery}` : status;
4570
+ rows.push({ id: job.id, kind: "shell", name: safeText(job.description ?? job.command), line: lines.length });
4571
+ lines.push(shellLine(job, job.id.slice(0, 8), label2, job.id));
4572
+ }
5065
4573
  return lines;
5066
4574
  }
5067
- #boundContent(content, width, limit) {
5068
- const bounded = content.slice(0, limit);
5069
- if (content.length > bounded.length && bounded.length > 0) {
5070
- const marker = this.theme.fg("dim", `+${content.length - bounded.length}`);
5071
- const available = Math.max(0, width - visibleWidth3(marker) - 1);
5072
- const last = truncateToWidth4(bounded[bounded.length - 1] ?? "", available, "");
5073
- bounded[bounded.length - 1] = `${last} ${marker}`;
4575
+ #withRightLabel(line, label, width) {
4576
+ const labelWidth = visibleWidth2(label);
4577
+ if (width < labelWidth + 2) return truncateToWidth3(line, width);
4578
+ const left = truncateToWidth3(line, width - labelWidth - 1, "");
4579
+ return `${left}${" ".repeat(width - visibleWidth2(left) - labelWidth)}${this.theme.fg("dim", label)}`;
4580
+ }
4581
+ };
4582
+
4583
+ // src/ui/footer-dock.ts
4584
+ import { stripVTControlCharacters } from "node:util";
4585
+ import { sliceByColumn, truncateToWidth as truncateToWidth4, visibleWidth as visibleWidth3 } from "@earendil-works/pi-tui";
4586
+ var childrenOf = (node) => {
4587
+ const children = node?.children;
4588
+ return Array.isArray(children) ? children : [];
4589
+ };
4590
+ var parentOf = (owner, nodes, target, depth) => {
4591
+ if (nodes.includes(target)) return owner;
4592
+ if (depth <= 0) return void 0;
4593
+ for (const node of nodes) {
4594
+ const found = parentOf(node, childrenOf(node), target, depth - 1);
4595
+ if (found) return found;
4596
+ }
4597
+ return void 0;
4598
+ };
4599
+ var withBorderBadge = (lines, label) => {
4600
+ if (!label) return lines;
4601
+ const index = lines.findIndex((line2) => stripVTControlCharacters(line2).startsWith("\u2500"));
4602
+ const line = lines[index];
4603
+ if (line === void 0) return lines;
4604
+ const badge = borderBadge(line, label);
4605
+ const width = visibleWidth3(line);
4606
+ const badgeWidth = visibleWidth3(badge);
4607
+ const plain = stripVTControlCharacters(line);
4608
+ if (badgeWidth + 6 > width || !/^─+$/.test(plain.slice(-(badgeWidth + 4)))) return lines;
4609
+ const next = [...lines];
4610
+ next[index] = truncateToWidth4(line, width - badgeWidth - 2, "") + badge + sliceByColumn(line, width - 2, 2);
4611
+ return next;
4612
+ };
4613
+ var FooterDock = class {
4614
+ constructor(tui, anchor, component, badge) {
4615
+ this.tui = tui;
4616
+ this.anchor = anchor;
4617
+ this.component = component;
4618
+ this.badge = badge;
4619
+ }
4620
+ #parent;
4621
+ #holder;
4622
+ /**
4623
+ * Pi's editor container while its render carries the badge: the render it
4624
+ * had, the wrapper installed over it, and whether that wrapper still badges.
4625
+ */
4626
+ #editor;
4627
+ /** Pi's editor drew the badge in its last frame; a border too narrow or busy for it did not. */
4628
+ #badgeDrawn = false;
4629
+ /**
4630
+ * True while the editor border shows the badge. Pi renders its editor before
4631
+ * the docked list in every frame, so the list reads this frame's outcome.
4632
+ */
4633
+ get badgeShown() {
4634
+ return this.#editor !== void 0 && this.#badgeDrawn;
4635
+ }
4636
+ /**
4637
+ * Fullscreen stacks shrink every input-dock child when overfull, including
4638
+ * one-line status widgets. Give our list only the rows left after Pi's own
4639
+ * editor, widgets and footer, reserving the transcript's native minimum row.
4640
+ * Regular mode scrolls the transcript instead and needs no extra cap.
4641
+ */
4642
+ availableRows(width) {
4643
+ const parent = this.#parent;
4644
+ const rows = this.tui.terminal?.rows;
4645
+ if (!parent || parent === this.tui || !this.#docked(this.#roots()) || rows === void 0 || !Number.isFinite(rows) || rows <= 0) return;
4646
+ const occupied = childrenOf(parent).reduce((total, child) => {
4647
+ if (child === this.component) return total;
4648
+ const sibling = child;
4649
+ return total + (typeof sibling?.render === "function" ? sibling.render(width).length : 0);
4650
+ }, 0);
4651
+ return Math.max(0, Math.floor(rows) - 1 - occupied);
4652
+ }
4653
+ /**
4654
+ * Keep the component after the footer: `docked` when it already is, `moved`
4655
+ * when this call placed it, `unavailable` when the layout is not Pi's.
4656
+ */
4657
+ sync() {
4658
+ const roots = this.#roots();
4659
+ if (this.#docked(roots)) {
4660
+ this.#decorateEditor();
4661
+ return "docked";
5074
4662
  }
5075
- return bounded.map((line) => truncateToWidth4(line, width));
4663
+ this.detach();
4664
+ const holder = parentOf(this.tui, roots, this.anchor, 3);
4665
+ const parent = holder === void 0 ? void 0 : parentOf(this.tui, roots, holder, 2);
4666
+ if (!parent || typeof parent.addChild !== "function") return "unavailable";
4667
+ const siblings = childrenOf(parent);
4668
+ if (siblings.indexOf(holder) !== siblings.length - 2) return "unavailable";
4669
+ parent.addChild(this.component, { shrink: 1, minSize: 0 });
4670
+ this.#parent = parent;
4671
+ this.#holder = holder;
4672
+ this.#decorateEditor();
4673
+ return "moved";
4674
+ }
4675
+ detach() {
4676
+ this.#restoreEditor();
4677
+ const parent = this.#parent;
4678
+ this.#parent = void 0;
4679
+ this.#holder = void 0;
4680
+ if (parent && childrenOf(parent).includes(this.component)) parent.removeChild?.(this.component);
4681
+ }
4682
+ /** Pi mounts its editor container straight before the below-editor widgets. */
4683
+ #decorateEditor() {
4684
+ if (!this.badge || !this.#parent) return;
4685
+ const siblings = childrenOf(this.#parent);
4686
+ const editor = siblings[siblings.indexOf(this.#holder) - 1];
4687
+ if (!editor || typeof editor.render !== "function") return this.#restoreEditor();
4688
+ if (this.#editor?.node === editor) return;
4689
+ this.#restoreEditor();
4690
+ const render = editor.render;
4691
+ const badge = this.badge;
4692
+ const live = { on: true };
4693
+ const wrapper = (width) => {
4694
+ const lines = render.call(editor, width);
4695
+ if (!live.on) return lines;
4696
+ const badged = withBorderBadge(lines, badge());
4697
+ this.#badgeDrawn = badged !== lines;
4698
+ return badged;
4699
+ };
4700
+ this.#editor = { node: editor, render, wrapper, live };
4701
+ editor.render = wrapper;
4702
+ }
4703
+ #restoreEditor() {
4704
+ const editor = this.#editor;
4705
+ this.#editor = void 0;
4706
+ this.#badgeDrawn = false;
4707
+ if (!editor) return;
4708
+ editor.live.on = false;
4709
+ if (editor.node.render === editor.wrapper) editor.node.render = editor.render;
4710
+ }
4711
+ #roots() {
4712
+ const tui = this.tui;
4713
+ return typeof tui.getMountedRoots === "function" ? tui.getMountedRoots() : childrenOf(this.tui);
4714
+ }
4715
+ /** Still last after the footer, beside the anchor's container, in a mounted tree. */
4716
+ #docked(roots) {
4717
+ const parent = this.#parent;
4718
+ if (!parent) return false;
4719
+ const siblings = childrenOf(parent);
4720
+ if (siblings.at(-1) !== this.component || siblings.at(-3) !== this.#holder) return false;
4721
+ if (!childrenOf(this.#holder).includes(this.anchor)) return false;
4722
+ return parent === this.tui || roots.some((root) => root === parent || childrenOf(root).includes(parent));
5076
4723
  }
5077
4724
  };
5078
4725
 
5079
4726
  // src/ui/controller.ts
5080
4727
  var WIDGET_ID = "pi-fabric";
4728
+ var WIDGET_PLACEMENT = { placement: "belowEditor" };
4729
+ var WIDGET_REORDER_INTERVAL_MS = 1e3;
5081
4730
  var ACTIVITY_REFRESH_MS = 100;
5082
4731
  var emptySnapshot = () => {
5083
4732
  const now = Date.now();
@@ -5121,6 +4770,7 @@ var FabricUiController = class {
5121
4770
  #actorUnsubscribe;
5122
4771
  #agentUnsubscribe;
5123
4772
  #shellUnsubscribe;
4773
+ #arrowEntryUnsubscribe;
5124
4774
  #tasksOpen = false;
5125
4775
  #tasksView;
5126
4776
  #closeTasks;
@@ -5129,11 +4779,15 @@ var FabricUiController = class {
5129
4779
  #dashboardTui;
5130
4780
  #widgetMounted = false;
5131
4781
  #widget;
4782
+ #widgetReorderedAt = 0;
4783
+ /** Row whose view is opening or open from the list; it keeps the filled circle meanwhile. */
4784
+ #widgetOpenRow;
4785
+ #widgetReorderPending = false;
4786
+ /** Places the list after Pi's footer; undefined once this mount fell back to the editor slot. */
4787
+ #footerDock;
4788
+ #footerDockPending = false;
5132
4789
  /** Component that had focus before the widget took it (normally the editor). */
5133
4790
  #widgetReturnFocus;
5134
- /** Pi's hideThinkingBlock for the widget pane; read once, at the first expansion. */
5135
- #widgetHideThinking;
5136
- #widgetHideThinkingLoad;
5137
4791
  #lastRefreshErrorAt = 0;
5138
4792
  #lastRefreshAt = 0;
5139
4793
  #dashboardOpen = false;
@@ -5152,8 +4806,6 @@ var FabricUiController = class {
5152
4806
  #activityRuns = [];
5153
4807
  #activityView;
5154
4808
  #transcripts = new AgentTranscriptReader();
5155
- /** Deeper pages for the widget's activity pane, so a turn's early thinking and tool calls stay visible. */
5156
- #widgetTranscripts = new AgentTranscriptReader(WIDGET_ACTIVITY_LOG_LINES);
5157
4809
  #conversationReaders = /* @__PURE__ */ new Map();
5158
4810
  #activeConversationReader;
5159
4811
  #snapshotCache = new FabricDashboardSnapshotCache();
@@ -5171,6 +4823,7 @@ var FabricUiController = class {
5171
4823
  this.#actorUnsubscribe = this.state.actors.subscribe(() => this.#scheduleRefresh());
5172
4824
  this.#agentUnsubscribe = this.state.agents.subscribeUi(() => this.#scheduleRefresh());
5173
4825
  this.#shellUnsubscribe = this.state.shellJobs?.subscribe(() => this.#scheduleRefresh());
4826
+ this.#arrowEntryUnsubscribe = context.ui.onTerminalInput?.((data) => matchesKey2(data, "down") && this.#enterWidgetFromEditor() ? { consume: true } : void 0);
5174
4827
  this.#refresh();
5175
4828
  this.#schedulePoll();
5176
4829
  }
@@ -5183,6 +4836,8 @@ var FabricUiController = class {
5183
4836
  this.#tasksOpen = false;
5184
4837
  this.#shellUnsubscribe?.();
5185
4838
  this.#shellUnsubscribe = void 0;
4839
+ this.#arrowEntryUnsubscribe?.();
4840
+ this.#arrowEntryUnsubscribe = void 0;
5186
4841
  this.#closeConversation?.();
5187
4842
  this.#closeConversation = void 0;
5188
4843
  this.#conversationView?.dispose();
@@ -5196,10 +4851,10 @@ var FabricUiController = class {
5196
4851
  this.#timer = void 0;
5197
4852
  this.#scheduledRefresh = void 0;
5198
4853
  this.#releaseWidget();
4854
+ this.#undockWidget();
5199
4855
  this.#widgetReturnFocus = void 0;
5200
- this.#widgetHideThinking = void 0;
5201
- this.#widgetHideThinkingLoad = void 0;
5202
4856
  this.#widget = void 0;
4857
+ this.#footerDock = void 0;
5203
4858
  this.#activityUnsubscribe?.();
5204
4859
  this.#activityUnsubscribe = void 0;
5205
4860
  this.#actorUnsubscribe?.();
@@ -5225,7 +4880,6 @@ var FabricUiController = class {
5225
4880
  this.#activityRuns = [];
5226
4881
  this.#activityView = void 0;
5227
4882
  this.#transcripts.clear();
5228
- this.#widgetTranscripts.clear();
5229
4883
  for (const reader of this.#conversationReaders.values()) reader.clear();
5230
4884
  this.#conversationReaders.clear();
5231
4885
  this.#activeConversationReader = void 0;
@@ -5251,6 +4905,46 @@ var FabricUiController = class {
5251
4905
  tui.setFocus(widget);
5252
4906
  tui.requestRender();
5253
4907
  }
4908
+ /**
4909
+ * ↓ in an empty editor moves into the participant list below it, as in Claude
4910
+ * Code. The editor has no use for ↓ there: history browsing ends at empty text.
4911
+ */
4912
+ #enterWidgetFromEditor() {
4913
+ if (this.ownsInput) return false;
4914
+ const tui = this.#widgetTui;
4915
+ const widget = this.#widget;
4916
+ if (!tui || !widget || tui.hasOverlay() || !widget.hasRows()) return false;
4917
+ const editor = tui.getFocusedComponent?.();
4918
+ if (!editor || editor === widget || typeof editor.getText !== "function") return false;
4919
+ if (editor.getText() !== "" || editor.isShowingAutocomplete?.()) return false;
4920
+ this.#widgetReturnFocus = editor;
4921
+ widget.selectFirst();
4922
+ tui.setFocus(widget);
4923
+ tui.requestRender();
4924
+ return true;
4925
+ }
4926
+ /**
4927
+ * Enter on a widget row: open the participant's conversation, or the tasks
4928
+ * view for a shell row, then come back to the list.
4929
+ */
4930
+ async #openFromWidget(context, row) {
4931
+ this.#widgetOpenRow = row.id;
4932
+ this.#releaseWidget();
4933
+ const epoch = this.#epoch;
4934
+ try {
4935
+ if (row.kind === "shell") await this.openTasks(context, row.id);
4936
+ else await this.openConversation(context, row.id);
4937
+ if (epoch !== this.#epoch || this.ownsInput) return;
4938
+ const tui = this.#widgetTui;
4939
+ const widget = this.#widget;
4940
+ if (!tui || !widget?.hasRows() || tui.getFocusedComponent?.() !== this.#widgetReturnFocus) return;
4941
+ widget.selectDefault();
4942
+ tui.setFocus(widget);
4943
+ tui.requestRender();
4944
+ } finally {
4945
+ if (epoch === this.#epoch && this.#widgetOpenRow === row.id) this.#widgetOpenRow = void 0;
4946
+ }
4947
+ }
5254
4948
  /** Return focus to the editor; a `forward` key the widget did not use goes to the editor too. */
5255
4949
  #releaseWidget(forward) {
5256
4950
  const tui = this.#widgetTui;
@@ -5260,26 +4954,9 @@ var FabricUiController = class {
5260
4954
  if (forward !== void 0) target?.handleInput?.(forward);
5261
4955
  tui.requestRender();
5262
4956
  }
5263
- /** Read Pi's hideThinkingBlock off the startup path, then redraw the pane. */
5264
- #widgetHidesThinking(context, tui) {
5265
- if (this.#widgetHideThinking !== void 0) return this.#widgetHideThinking;
5266
- const epoch = this.#epoch;
5267
- this.#widgetHideThinkingLoad ??= (async () => {
5268
- let hidden = false;
5269
- try {
5270
- const { loadHostSdk } = await import("../core/host-sdk.js");
5271
- const { SettingsManager } = await loadHostSdk();
5272
- hidden = SettingsManager.create(context.cwd, resolveAgentDir(), { projectTrusted: context.isProjectTrusted?.() ?? false }).getHideThinkingBlock();
5273
- } catch {
5274
- }
5275
- if (epoch !== this.#epoch) return;
5276
- this.#widgetHideThinking = hidden;
5277
- tui.requestRender();
5278
- })();
5279
- return true;
5280
- }
4957
+ /** Without an ID, focus the footer list; explicit IDs open single-task detail. */
5281
4958
  async openTasks(context, query) {
5282
- if (this.ownsInput) return;
4959
+ if (this.#tasksOpen || this.#dashboardOpen || this.#widget?.focused === true) return;
5283
4960
  const jobs = this.state.shellJobs;
5284
4961
  if (!jobs) {
5285
4962
  context.ui.notify("No shell task store in this session", "info");
@@ -5300,6 +4977,11 @@ var FabricUiController = class {
5300
4977
  return;
5301
4978
  }
5302
4979
  if (!this.#context) this.start(context);
4980
+ if (!query) {
4981
+ this.focusWidget(context);
4982
+ return;
4983
+ }
4984
+ const id = candidates[0].id;
5303
4985
  this.#tasksOpen = true;
5304
4986
  const epoch = this.#epoch;
5305
4987
  try {
@@ -5307,7 +4989,6 @@ var FabricUiController = class {
5307
4989
  if (epoch !== this.#epoch) return;
5308
4990
  await imageSafeCustom(context.ui, (tui, theme, keys, done) => {
5309
4991
  this.#closeTasks = () => done();
5310
- const id = candidates[0]?.id;
5311
4992
  this.#tasksView = new ShellTasksView({
5312
4993
  jobs,
5313
4994
  theme,
@@ -5315,7 +4996,7 @@ var FabricUiController = class {
5315
4996
  done: () => done(),
5316
4997
  requestRender: () => tui.requestRender(),
5317
4998
  rows: () => tui.terminal?.rows ?? 24,
5318
- ...id ? { id } : {}
4999
+ id
5319
5000
  });
5320
5001
  return this.#tasksView;
5321
5002
  }, { overlay: true, overlayOptions: { width: "94%", maxHeight: "90%", anchor: "center", margin: 1 } });
@@ -5451,6 +5132,16 @@ var FabricUiController = class {
5451
5132
  this.#closeConversation = () => done(void 0);
5452
5133
  const view = new FabricConversationView(tui, theme, {
5453
5134
  targets,
5135
+ openTasks: (id) => void this.openTasks(context, id),
5136
+ // The same agent list as the main screen, at the bottom of the window.
5137
+ participants: (interaction) => new FabricWidget(
5138
+ theme,
5139
+ () => this.#snapshot,
5140
+ this.state.config.ui.maxRows,
5141
+ () => tui.terminal?.rows ?? process.stdout.rows,
5142
+ this.#widgetRetention,
5143
+ interaction
5144
+ ),
5454
5145
  onTargetChange: (id) => {
5455
5146
  if (this.#activeConversationReader !== id) this.#suspendConversationReader();
5456
5147
  },
@@ -5528,8 +5219,8 @@ var FabricUiController = class {
5528
5219
  if (!this.#context) this.start(context);
5529
5220
  this.#dashboardOpen = true;
5530
5221
  this.#refresh();
5531
- const [{ FabricDashboard }, { buildClaudeModelSource, buildModelSource: buildModelSource2 }, { imageSafeCustom }] = await Promise.all([import("../ui/dashboard.js"), import("../ui/model-picker.js"), import("../ui/image-overlays.js")]);
5532
- const modelSource = buildModelSource2(context.modelRegistry, resolveAgentDir());
5222
+ const [{ FabricDashboard }, { buildClaudeModelSource, buildModelSource }, { imageSafeCustom }] = await Promise.all([import("../ui/dashboard.js"), import("../ui/model-picker.js"), import("../ui/image-overlays.js")]);
5223
+ const modelSource = buildModelSource(context.modelRegistry, resolveAgentDir());
5533
5224
  let claudeModelSource;
5534
5225
  if (this.#snapshot.actors.some((actor) => actor.runner === "claude")) {
5535
5226
  try {
@@ -5617,14 +5308,18 @@ var FabricUiController = class {
5617
5308
  }
5618
5309
  };
5619
5310
  const onImportActor = (globalActorId) => {
5620
- const def = this.state.globalActors.resolve(globalActorId);
5621
- if (!def) return;
5622
- this.state.actors.create(this.state.globalActors.toRequest(def)).then((actor) => {
5623
- context.ui.notify(`Imported global actor "${def.name}" as ${actor.name}`, "info");
5624
- this.#refresh();
5625
- }).catch(
5626
- (error) => context.ui.notify(error instanceof Error ? error.message : String(error), "error")
5627
- );
5311
+ try {
5312
+ const def = this.state.globalActors.resolve(globalActorId);
5313
+ if (!def) return;
5314
+ this.state.actors.create(this.state.globalActors.toRequest(def)).then((actor) => {
5315
+ context.ui.notify(`Imported global actor "${def.name}" as ${actor.name}`, "info");
5316
+ this.#refresh();
5317
+ }).catch(
5318
+ (error) => context.ui.notify(error instanceof Error ? error.message : String(error), "error")
5319
+ );
5320
+ } catch (error) {
5321
+ context.ui.notify(error instanceof Error ? error.message : String(error), "error");
5322
+ }
5628
5323
  };
5629
5324
  const onExportActor = (actorId) => {
5630
5325
  try {
@@ -5721,7 +5416,8 @@ var FabricUiController = class {
5721
5416
  }
5722
5417
  if (this.#timer || !this.#context) return;
5723
5418
  const expiryDelay = this.#widgetRetention.nextExpiryDelay(this.#snapshot, Date.now());
5724
- const active = expiryDelay !== void 0 || this.#snapshot.shells?.some((job) => job.finishedAt === void 0) || this.#snapshot.runs.some((run) => run.status === "running") || this.#snapshot.peers.length > 0 || this.#snapshot.agents.some((agent) => isActiveStatus(agent.status)) || this.#snapshot.actors.some(
5419
+ const labelPending = this.#snapshot.sessionLabel === void 0 && typeof this.state.sessionLabelPending === "function" && this.state.sessionLabelPending();
5420
+ const active = labelPending || expiryDelay !== void 0 || this.#snapshot.shells?.some((job) => job.finishedAt === void 0) || this.#snapshot.runs.some((run) => run.status === "running") || this.#snapshot.peers.length > 0 || this.#snapshot.agents.some((agent) => isActiveStatus(agent.status)) || this.#snapshot.actors.some(
5725
5421
  (actor) => isActiveStatus(actor.status) || Boolean(actor.worker && isActiveStatus(actor.worker.status))
5726
5422
  );
5727
5423
  if (!this.ownsInput && !active) return;
@@ -5757,7 +5453,7 @@ var FabricUiController = class {
5757
5453
  logFile: actor.worker.logFile
5758
5454
  };
5759
5455
  }
5760
- const retained = actor.lastRunId && actor.logDir ? path9.join(actor.logDir, actor.lastRunId, "events.jsonl") : void 0;
5456
+ const retained = actor.lastRunId && actor.logDir ? path7.join(actor.logDir, actor.lastRunId, "events.jsonl") : void 0;
5761
5457
  if (retained) return { id: actor.id, status: actor.status, logFile: retained };
5762
5458
  if (actor.sessionFile) {
5763
5459
  return { id: actor.id, status: actor.status, logFile: actor.sessionFile };
@@ -5824,6 +5520,59 @@ var FabricUiController = class {
5824
5520
  const limit = this.state.config.ui.eventHistory;
5825
5521
  if (this.#events.length > limit) this.#events.splice(0, this.#events.length - limit);
5826
5522
  }
5523
+ /**
5524
+ * Dock the list after the footer outside the render pass that found it
5525
+ * missing. When Pi's layout is not the one the dock knows, the list falls
5526
+ * back to the below-editor slot for the rest of this mount.
5527
+ */
5528
+ #syncFooterDock(context, widget) {
5529
+ const dock = this.#footerDock;
5530
+ if (!dock || this.#footerDockPending || this.#widget !== widget) return;
5531
+ this.#footerDockPending = true;
5532
+ const epoch = this.#epoch;
5533
+ queueMicrotask(() => {
5534
+ this.#footerDockPending = false;
5535
+ if (epoch !== this.#epoch || this.#widget !== widget || this.#footerDock !== dock) return;
5536
+ const placement = dock.sync();
5537
+ if (placement === "moved") this.#widgetTui?.requestRender();
5538
+ if (placement === "unavailable") this.#fallBackToEditorSlot(context);
5539
+ });
5540
+ }
5541
+ /** Draw the list in the below-editor slot itself for the rest of this mount. */
5542
+ #fallBackToEditorSlot(context) {
5543
+ const widget = this.#widget;
5544
+ this.#footerDock = void 0;
5545
+ if (widget) context.ui.setWidget(WIDGET_ID, () => widget, WIDGET_PLACEMENT);
5546
+ }
5547
+ #undockWidget(widget = this.#widget) {
5548
+ if (widget !== this.#widget) return;
5549
+ this.#footerDock?.detach();
5550
+ }
5551
+ /**
5552
+ * Keep the list last among the widgets below the editor when it falls back
5553
+ * to that slot. Pi draws them in
5554
+ * the order they were last set, so a status line set after the list would
5555
+ * sit under it, and the dock clips from the bottom when it runs short of
5556
+ * rows. Setting the same component again moves it to the end and keeps its
5557
+ * focus and selection.
5558
+ */
5559
+ #keepWidgetLast(context) {
5560
+ if (this.#widgetReorderPending) return;
5561
+ const tui = this.#widgetTui;
5562
+ const widget = this.#widget;
5563
+ if (!tui || !widget) return;
5564
+ const parent = tui.children?.find((child) => child.children?.includes(widget));
5565
+ if (!parent || parent.children.at(-1) === widget) return;
5566
+ const wait = this.#widgetReorderedAt + WIDGET_REORDER_INTERVAL_MS - Date.now();
5567
+ this.#widgetReorderPending = true;
5568
+ const epoch = this.#epoch;
5569
+ setTimeout(() => {
5570
+ this.#widgetReorderPending = false;
5571
+ if (epoch !== this.#epoch || this.#widget !== widget || !this.#widgetMounted) return;
5572
+ this.#widgetReorderedAt = Date.now();
5573
+ context.ui.setWidget(WIDGET_ID, () => widget, WIDGET_PLACEMENT);
5574
+ }, Math.max(0, wait)).unref?.();
5575
+ }
5827
5576
  #renderWidget(context) {
5828
5577
  const config = this.state.config.ui;
5829
5578
  const shouldShow = context.mode === "tui" && shouldShowFabricWidget(this.#snapshot, config.widget, this.#widgetRetention);
@@ -5843,27 +5592,45 @@ var FabricUiController = class {
5843
5592
  () => tui.terminal?.rows ?? process.stdout.rows,
5844
5593
  this.#widgetRetention,
5845
5594
  {
5846
- activity: (row) => {
5847
- const target = row.kind === "actor" ? this.#snapshot.actors.find((actor) => actor.id === row.id) : this.#snapshot.agents.find((agent) => agent.id === row.id);
5848
- return target ? this.#widgetTranscripts.read(this.#transcriptSource(target)) : void 0;
5849
- },
5595
+ open: (row) => void this.#openFromWidget(context, row),
5596
+ viewing: () => this.#widgetOpenRow,
5597
+ // Nothing to select: collapse, unless a label would then have nowhere to show.
5598
+ collapseIdle: () => this.#snapshot.sessionLabel === void 0 || this.#footerDock?.badgeShown === true,
5850
5599
  release: (forward) => this.#releaseWidget(forward),
5851
5600
  requestRender: () => tui.requestRender(),
5852
- hideThinking: () => this.#widgetHidesThinking(context, tui)
5601
+ rendered: () => this.#keepWidgetLast(context),
5602
+ availableRows: (width) => this.#footerDock?.availableRows(width)
5853
5603
  }
5854
5604
  );
5855
- return this.#widget;
5605
+ const widget = this.#widget;
5606
+ const anchor = {
5607
+ render: () => {
5608
+ this.#syncFooterDock(context, widget);
5609
+ return [];
5610
+ },
5611
+ invalidate: () => {
5612
+ },
5613
+ dispose: () => this.#undockWidget(widget)
5614
+ };
5615
+ this.#footerDock = new FooterDock(tui, anchor, widget, () => {
5616
+ const label = this.#snapshot.sessionLabel;
5617
+ return label ? safeText(label) : void 0;
5618
+ });
5619
+ return anchor;
5856
5620
  },
5857
- { placement: "aboveEditor" }
5621
+ WIDGET_PLACEMENT
5858
5622
  );
5623
+ if (this.#footerDock?.sync() === "unavailable") this.#fallBackToEditorSlot(context);
5859
5624
  return;
5860
5625
  }
5861
5626
  if (!this.#widgetMounted) return;
5862
5627
  this.#releaseWidget();
5628
+ this.#undockWidget();
5863
5629
  context.ui.setWidget(WIDGET_ID, void 0);
5864
5630
  this.#widgetMounted = false;
5865
5631
  this.#widgetTui = void 0;
5866
5632
  this.#widget = void 0;
5633
+ this.#footerDock = void 0;
5867
5634
  }
5868
5635
  };
5869
5636
 
@@ -5929,7 +5696,9 @@ function installFabricShellHangKeys(context, options) {
5929
5696
  return void 0;
5930
5697
  }
5931
5698
  const jobs = options.jobs();
5932
- if (!jobs || jobs.waiting().length === 0) {
5699
+ const shells = jobs?.waiting().length ?? 0;
5700
+ const programs = shells === 0 && data === CTRL_B && editorEmpty(context) ? options.programs?.() : void 0;
5701
+ if (!jobs || shells === 0 && !programs?.waiting()) {
5933
5702
  chordArmedAt = 0;
5934
5703
  return void 0;
5935
5704
  }
@@ -5937,6 +5706,16 @@ function installFabricShellHangKeys(context, options) {
5937
5706
  const now = Date.now();
5938
5707
  if (chordArmedAt > 0 && now - chordArmedAt <= CTRL_B_CHORD_MS) {
5939
5708
  chordArmedAt = 0;
5709
+ if (programs) {
5710
+ const count2 = programs.detachWaiting();
5711
+ if (count2 > 0) {
5712
+ context.ui.notify(
5713
+ count2 === 1 ? "Fabric: program moved to the background \xB7 /fabric tasks" : `Fabric: ${count2} programs moved to the background \xB7 /fabric tasks`,
5714
+ "info"
5715
+ );
5716
+ }
5717
+ return { consume: true };
5718
+ }
5940
5719
  const count = jobs.spillWaiting();
5941
5720
  if (count > 0) {
5942
5721
  context.ui.notify(
@@ -5947,6 +5726,7 @@ function installFabricShellHangKeys(context, options) {
5947
5726
  return { consume: true };
5948
5727
  }
5949
5728
  chordArmedAt = now;
5729
+ if (shells > 0) context.ui.notify("Fabric: press Ctrl+B again to background the waiting shell", "info");
5950
5730
  return { consume: true };
5951
5731
  }
5952
5732
  chordArmedAt = 0;
@@ -5967,6 +5747,13 @@ function installFabricShellHangKeys(context, options) {
5967
5747
  unsubscribe();
5968
5748
  };
5969
5749
  }
5750
+ var editorEmpty = (context) => {
5751
+ try {
5752
+ return (context.ui.getEditorText?.() ?? "") === "";
5753
+ } catch {
5754
+ return false;
5755
+ }
5756
+ };
5970
5757
 
5971
5758
  // src/ui/tool-display.ts
5972
5759
  var FabricToolDisplayController = class {
@@ -6020,18 +5807,99 @@ var registerHandoffCompletionRenderer = (extension) => {
6020
5807
  });
6021
5808
  };
6022
5809
 
5810
+ // src/ui/terminal-title.ts
5811
+ var MAX_TERMINAL_TITLE_CHARS = 120;
5812
+ var terminalTitleText = (value) => {
5813
+ const text = safeText(value);
5814
+ if (text.length <= MAX_TERMINAL_TITLE_CHARS) return text;
5815
+ return `${Array.from(text).slice(0, MAX_TERMINAL_TITLE_CHARS - 1).join("").trimEnd()}\u2026`;
5816
+ };
5817
+ var TERMINAL_TITLE_ENTRY_TYPE = "pi-fabric-terminal-title";
5818
+ var recordedTitle = (context) => {
5819
+ const entries = context.sessionManager?.getEntries?.() ?? [];
5820
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
5821
+ const entry = entries[index];
5822
+ if (entry?.type !== "custom" || entry.customType !== TERMINAL_TITLE_ENTRY_TYPE) continue;
5823
+ const recorded = entry.data?.title;
5824
+ const text = typeof recorded === "string" ? terminalTitleText(recorded) : "";
5825
+ if (text) return text;
5826
+ }
5827
+ return void 0;
5828
+ };
5829
+ var FabricTerminalTitle = class {
5830
+ #host;
5831
+ #enabled;
5832
+ #title;
5833
+ constructor(host, enabled) {
5834
+ this.#host = host;
5835
+ this.#enabled = enabled;
5836
+ }
5837
+ /** Adopt the title this session recorded, after Pi applies its own. */
5838
+ resume(context) {
5839
+ if (!this.#enabled()) return;
5840
+ const recorded = recordedTitle(context);
5841
+ if (!recorded) return;
5842
+ this.#title = recorded;
5843
+ this.#write(context, recorded);
5844
+ }
5845
+ /** Show the declared display title for a run and record it for resumes. */
5846
+ show(context, title) {
5847
+ if (!this.#enabled()) return;
5848
+ const text = terminalTitleText(title);
5849
+ if (!text || text === this.#title) return;
5850
+ this.#title = text;
5851
+ this.#write(context, text);
5852
+ try {
5853
+ this.#host.appendEntry(TERMINAL_TITLE_ENTRY_TYPE, { version: 1, title: text });
5854
+ } catch {
5855
+ }
5856
+ }
5857
+ /** Put the sticky title back after Pi rewrites its own. */
5858
+ reassert(context) {
5859
+ if (!this.#enabled() || !this.#title) return;
5860
+ this.#write(context, this.#title);
5861
+ }
5862
+ /** The title currently held, for callers that need to compare. */
5863
+ current() {
5864
+ return this.#title;
5865
+ }
5866
+ #write(context, text) {
5867
+ if (context.mode !== "tui" || !context.hasUI) return;
5868
+ try {
5869
+ context.ui.setTitle(text);
5870
+ } catch {
5871
+ }
5872
+ }
5873
+ };
5874
+ var installTerminalTitle = (pi, title) => {
5875
+ const later = (action) => (_event, context) => {
5876
+ if (!context) return;
5877
+ setImmediate(() => {
5878
+ try {
5879
+ action(context);
5880
+ } catch {
5881
+ }
5882
+ });
5883
+ };
5884
+ pi.on("session_start", later((context) => title.resume(context)));
5885
+ pi.on("session_tree", later((context) => title.resume(context)));
5886
+ pi.on("session_info_changed", later((context) => title.reassert(context)));
5887
+ pi.on("agent_settled", later((context) => title.reassert(context)));
5888
+ };
5889
+
6023
5890
  // src/extension.ts
6024
- import path10 from "node:path";
5891
+ import path8 from "node:path";
6025
5892
  import { fileURLToPath } from "node:url";
6026
- var FABRIC_MANAGED_HOST_VERSION = 1;
5893
+ var FABRIC_MANAGED_HOST_VERSION = 2;
5894
+ var userPromptText = (event) => event.messageType === "custom" || typeof event.prompt !== "string" ? void 0 : event.prompt;
6027
5895
  function createFabricExtension(entryUrl) {
6028
- const FABRIC_EXTENSION_ENTRY_PATH = path10.resolve(fileURLToPath(entryUrl));
6029
- const FABRIC_ENTRY_DIR = path10.dirname(FABRIC_EXTENSION_ENTRY_PATH);
5896
+ const FABRIC_EXTENSION_ENTRY_PATH = path8.resolve(fileURLToPath(entryUrl));
5897
+ const FABRIC_ENTRY_DIR = path8.dirname(FABRIC_EXTENSION_ENTRY_PATH);
6030
5898
  const FABRIC_RUNTIME_PATHS = {
6031
5899
  extension: FABRIC_EXTENSION_ENTRY_PATH,
6032
- worker: path10.join(FABRIC_ENTRY_DIR, "worker.js"),
6033
- residentHost: path10.join(FABRIC_ENTRY_DIR, "residency", "launcher.js"),
6034
- skills: path10.resolve(FABRIC_ENTRY_DIR, "..", "skillsets")
5900
+ worker: path8.join(FABRIC_ENTRY_DIR, "worker.js"),
5901
+ residentHost: path8.join(FABRIC_ENTRY_DIR, "residency", "launcher.js"),
5902
+ skills: path8.resolve(FABRIC_ENTRY_DIR, "..", "skillsets")
6035
5903
  };
6036
5904
  const FABRIC_SKILLS_DIR = FABRIC_RUNTIME_PATHS.skills;
6037
5905
  const FABRIC_ENTRY_IDENTITY = captureLoadedFileIdentity(entryUrl);
@@ -6055,6 +5923,14 @@ function createFabricExtension(entryUrl) {
6055
5923
  };
6056
5924
  const SKILL_REFERENCE_CUSTOM_TYPE = "pi-fabric-skill-reference";
6057
5925
  return async function piFabric(pi, options = {}) {
5926
+ const namesExtension = process.argv.some((argument) => argument === "-e" || argument === "--extension");
5927
+ const preferredCopy = options.managedHost || !namesExtension ? void 0 : (await import("../extension-copy.js")).commandLineFabricCopy(FABRIC_EXTENSION_ENTRY_PATH);
5928
+ if (preferredCopy) {
5929
+ console.warn(
5930
+ `[pi-fabric] ${FABRIC_EXTENSION_ENTRY_PATH} is inactive: the command line loads Fabric from ${preferredCopy}`
5931
+ );
5932
+ return;
5933
+ }
6058
5934
  if (!options.managedHost) registerJevAuth(pi);
6059
5935
  const codePreviewSettings = defaultCodePreviewSettings();
6060
5936
  const decorateShell = withCodePreviewShell;
@@ -6080,7 +5956,13 @@ function createFabricExtension(entryUrl) {
6080
5956
  );
6081
5957
  const capturedTools = new CapturedToolCatalog();
6082
5958
  const proxyContract = new ProxyContractLedger();
5959
+ const ownerSlot = { closed: false, yielded: false };
5960
+ const compactionOwner = () => ownerSlot.host?.active;
5961
+ let ownerCode;
5962
+ const hostPolicy = new FabricHostPolicy();
6083
5963
  const state = new FabricState(pi, capturedTools, {
5964
+ compactionOwner,
5965
+ hostPolicy,
6084
5966
  paths: FABRIC_RUNTIME_PATHS,
6085
5967
  ...FABRIC_ENTRY_IDENTITY ? { entryIdentity: FABRIC_ENTRY_IDENTITY } : {},
6086
5968
  ...options.managedHost ? { managedHost: options.managedHost } : {}
@@ -6148,6 +6030,36 @@ function createFabricExtension(entryUrl) {
6148
6030
  }
6149
6031
  }
6150
6032
  );
6033
+ const unsubscribeActionPolicyRegistration = pi.events.on(
6034
+ FABRIC_ACTION_POLICY_REGISTER_EVENT,
6035
+ (value) => {
6036
+ const registration = readFabricActionPolicyRegistrationV1(value);
6037
+ if (!registration) throw new Error("Invalid Pi Fabric action policy hook registration");
6038
+ let unregister;
6039
+ try {
6040
+ unregister = state.actionPolicyHooks.register(registration.name, registration.hook);
6041
+ } catch (error) {
6042
+ registration.respond?.({ ok: false, error: error instanceof Error ? error.message : String(error) });
6043
+ return;
6044
+ }
6045
+ registration.respond?.({ ok: true, unregister });
6046
+ }
6047
+ );
6048
+ const unsubscribeQuestionRendererRegistration = pi.events.on(
6049
+ FABRIC_QUESTION_RENDERER_REGISTER_EVENT,
6050
+ (value) => {
6051
+ const registration = readFabricQuestionRendererRegistrationV1(value);
6052
+ if (!registration) throw new Error("Invalid Pi Fabric question renderer registration");
6053
+ let unregister;
6054
+ try {
6055
+ unregister = state.questionRenderers.register(registration.name, registration.render);
6056
+ } catch (error) {
6057
+ registration.respond?.({ ok: false, error: error instanceof Error ? error.message : String(error) });
6058
+ return;
6059
+ }
6060
+ registration.respond?.({ ok: true, unregister });
6061
+ }
6062
+ );
6151
6063
  const programReachable = (registered) => {
6152
6064
  if (!state.initialized) return () => false;
6153
6065
  const allowlist = readChildToolAllowlist();
@@ -6155,6 +6067,7 @@ function createFabricExtension(entryUrl) {
6155
6067
  return (name) => {
6156
6068
  if (allowlist && !allowlist.has(name)) return false;
6157
6069
  const captured = capturedTools.get(name) !== void 0;
6070
+ if (hostPolicy.previewDenial(PI_CORE_TOOL_NAME_SET.has(name) ? "pi" : "extensions", name)) return false;
6158
6071
  if (PI_CORE_TOOL_NAME_SET.has(name)) {
6159
6072
  if (!registry.has("pi")) return false;
6160
6073
  if (options.managedHost) return captured;
@@ -6181,25 +6094,53 @@ function createFabricExtension(entryUrl) {
6181
6094
  }));
6182
6095
  }
6183
6096
  );
6097
+ const unsubscribeHostPolicy = pi.events.on(FABRIC_HOST_POLICY_EVENT, (value) => {
6098
+ const read = readFabricHostPolicyRequestV1(value);
6099
+ if (!read) return;
6100
+ if (!read.ok) {
6101
+ read.reply({ version: 1, accepted: false, reason: `Invalid Pi Fabric host policy: ${read.reason}` });
6102
+ return;
6103
+ }
6104
+ read.request.reply(hostPolicy.apply(read.request.policy));
6105
+ });
6184
6106
  let programRunContext;
6185
6107
  const unsubscribeProgramRun = pi.events.on(FABRIC_PROGRAM_RUN_EVENT, (value) => {
6186
- const reply = value?.reply;
6187
- if (typeof reply !== "function") throw new Error("Invalid Pi Fabric program run request");
6108
+ const request = snapshotFabricProgramRunRequestV1(value);
6109
+ if (!request) return;
6188
6110
  void import("../programs/host.js").then(
6189
- ({ handleFabricProgramRunEvent }) => handleFabricProgramRunEvent(value, { state, pi, context: programRunContext }),
6190
- (error) => reply({ ok: false, error: `Fabric program host unavailable: ${String(error)}` })
6111
+ ({ handleFabricProgramRunEvent }) => handleFabricProgramRunEvent(request, { state, pi, context: programRunContext }),
6112
+ (error) => request.respond({ ok: false, error: `Fabric program host unavailable: ${String(error)}` })
6191
6113
  );
6192
6114
  });
6115
+ const unsubscribeOwner = pi.events.on(FABRIC_COMPACTION_OWNER_EVENT, (value) => (ownerCode ??= import("../compaction/claim-events.js")).then(
6116
+ ({ handleCompactionOwnerMessage }) => handleCompactionOwnerMessage(ownerSlot, value, state, () => programRunContext),
6117
+ (error) => {
6118
+ ownerCode = void 0;
6119
+ try {
6120
+ value?.reply?.({
6121
+ ok: false,
6122
+ error: `Fabric compaction owner support failed to load: ${String(error)}`
6123
+ });
6124
+ } catch {
6125
+ }
6126
+ }
6127
+ ));
6193
6128
  pi.on("resources_discover", async (_event, context) => {
6194
6129
  if (!state.bootstrapped) await state.bootstrap(context);
6130
+ if (state.managedHostOptions || process.env.PI_FABRIC_CHILD_SKILLS === "selected") return { skillPaths: [] };
6195
6131
  return { skillPaths: fabricSkillPaths(FABRIC_SKILLS_DIR, state.config.executor.kernel) };
6196
6132
  });
6133
+ const fabricTerminalTitle = new FabricTerminalTitle(pi, () => {
6134
+ const ui = state.bootstrapped ? state.config.ui : DEFAULT_FABRIC_CONFIG.ui;
6135
+ return ui.enabled && ui.terminalTitle;
6136
+ });
6197
6137
  const fabricTool = createFabricExecTool(
6198
6138
  state,
6199
6139
  codePreviewSettings,
6200
6140
  pendingHandoffs,
6201
6141
  decorateShell,
6202
- toolDisplay
6142
+ toolDisplay,
6143
+ fabricTerminalTitle
6203
6144
  );
6204
6145
  const refreshCodePreviewSettings = () => {
6205
6146
  Object.assign(codePreviewSettings, state.config.codePreview);
@@ -6236,7 +6177,14 @@ function createFabricExtension(entryUrl) {
6236
6177
  toolCapture.setPolicy(capturePolicy());
6237
6178
  Object.assign(
6238
6179
  fabricTool,
6239
- createFabricExecTool(state, codePreviewSettings, pendingHandoffs, decorateShell, toolDisplay)
6180
+ createFabricExecTool(
6181
+ state,
6182
+ codePreviewSettings,
6183
+ pendingHandoffs,
6184
+ decorateShell,
6185
+ toolDisplay,
6186
+ fabricTerminalTitle
6187
+ )
6240
6188
  );
6241
6189
  pi.registerTool(fabricTool);
6242
6190
  toolOwnership.apply(
@@ -6274,7 +6222,8 @@ function createFabricExtension(entryUrl) {
6274
6222
  shellHangKeysUnsubscribe = installFabricShellHangKeys(context, {
6275
6223
  enabled: () => state.initialized,
6276
6224
  ownsInput: () => fabricUi.ownsInput,
6277
- jobs: () => state.shellJobs
6225
+ jobs: () => state.shellJobs,
6226
+ programs: () => state.programTasks
6278
6227
  });
6279
6228
  };
6280
6229
  const refreshProxyLedger = (context) => {
@@ -6324,9 +6273,7 @@ function createFabricExtension(entryUrl) {
6324
6273
  const entropy = await import("../entropy/index.js");
6325
6274
  if (!current()) return false;
6326
6275
  const {
6327
- comparableCompiledSurfaceScore,
6328
6276
  entropyRepairRows,
6329
- formatEntropyCompileNotice,
6330
6277
  liveSurfaceSnapshot,
6331
6278
  loadCompiledSurfaceAsync,
6332
6279
  saveCompiledSurfaceAsync,
@@ -6368,14 +6315,6 @@ function createFabricExtension(entryUrl) {
6368
6315
  const saved = await saveCompiledSurfaceAsync(agentDir, outcome.artifact);
6369
6316
  if (current()) {
6370
6317
  setActiveCompiledSurface(saved.file);
6371
- const previousScore = comparableCompiledSurfaceScore(loaded.file, saved.file.metricVersion);
6372
- if (previousScore !== void 0 && outcome.report.score < previousScore && context.hasUI) {
6373
- context.ui.notify(formatEntropyCompileNotice({
6374
- beforeScore: previousScore,
6375
- afterScore: outcome.report.score,
6376
- normalizations: saved.file.normalizations?.length ?? 0
6377
- }), "info");
6378
- }
6379
6318
  }
6380
6319
  } catch (error) {
6381
6320
  if (!(error instanceof FileLockTimeoutError)) throw error;
@@ -6390,7 +6329,7 @@ function createFabricExtension(entryUrl) {
6390
6329
  const task = (async () => {
6391
6330
  try {
6392
6331
  if (request.delayMs > 0) {
6393
- await new Promise((resolve2) => setTimeout(resolve2, request.delayMs));
6332
+ await new Promise((resolve) => setTimeout(resolve, request.delayMs));
6394
6333
  }
6395
6334
  retry = await compileEntropyNow(request.context, request.epoch);
6396
6335
  } catch (error) {
@@ -6506,8 +6445,13 @@ function createFabricExtension(entryUrl) {
6506
6445
  }
6507
6446
  });
6508
6447
  pi.on("agent_settled", async (event, context) => {
6448
+ if (state.managedHostOptions) {
6449
+ if (state.config.compaction.engine === "fabric") await compactAtConfiguredThreshold(context, state.config);
6450
+ if (state.initialized) await state.publishHostLifecycle("pi.agent_settled", event);
6451
+ return;
6452
+ }
6509
6453
  if (!state.initialized) {
6510
- await compactAtConfiguredThreshold(context, state.config);
6454
+ if (!compactionOwner()) await compactAtConfiguredThreshold(context, state.config);
6511
6455
  return;
6512
6456
  }
6513
6457
  const sessionId = context.sessionManager.getSessionId();
@@ -6528,11 +6472,13 @@ function createFabricExtension(entryUrl) {
6528
6472
  state.prewalkDrift.drop(sessionId);
6529
6473
  }
6530
6474
  await state.compact.maybeCommit(context);
6531
- await compactAtConfiguredThreshold(
6532
- context,
6533
- state.config,
6534
- (trigger, committed) => state.compact.noteAutoCompaction(trigger, committed)
6535
- );
6475
+ if (!compactionOwner()) {
6476
+ await compactAtConfiguredThreshold(
6477
+ context,
6478
+ state.config,
6479
+ (trigger, committed) => state.compact.noteAutoCompaction(trigger, committed)
6480
+ );
6481
+ }
6536
6482
  await state.publishHostLifecycle("pi.agent_settled", event);
6537
6483
  });
6538
6484
  pi.on("message_start", () => {
@@ -6629,14 +6575,13 @@ function createFabricExtension(entryUrl) {
6629
6575
  }
6630
6576
  });
6631
6577
  let compactionOwners;
6632
- let compactionYieldPending = false;
6633
6578
  pi.on("session_compact", async (event, context) => {
6634
- const fabricEngine = (state.bootstrapped ? state.config : DEFAULT_FABRIC_CONFIG).compaction.engine === "fabric";
6579
+ const fabricEngine = !compactionOwner() && (state.bootstrapped ? state.config : DEFAULT_FABRIC_CONFIG).compaction.engine === "fabric";
6635
6580
  const observer = await (compactionOwners ??= import("../compaction/owner.js").then(
6636
6581
  (module) => new module.CompactionOwnerObserver()
6637
6582
  ));
6638
- if (compactionYieldPending) {
6639
- compactionYieldPending = false;
6583
+ if (ownerSlot.yielded) {
6584
+ ownerSlot.yielded = false;
6640
6585
  observer.noteDeliberateYield();
6641
6586
  }
6642
6587
  const { warning } = observer.observe(
@@ -6651,15 +6596,25 @@ function createFabricExtension(entryUrl) {
6651
6596
  if (!state.initialized) return;
6652
6597
  await state.publishHostLifecycle("pi.session_compact", event);
6653
6598
  });
6654
- registerCompactionHook(pi, {
6599
+ let compaction;
6600
+ const compactionHandlers = () => compaction ??= import("../compaction/hook.js").then((module) => module.compactionHandlers({
6655
6601
  getEngine: () => state.cwd ? state.config.compaction.engine : DEFAULT_FABRIC_CONFIG.compaction.engine,
6656
6602
  getTargetContextRatio: () => state.cwd ? state.config.compaction.targetContextRatio : DEFAULT_FABRIC_CONFIG.compaction.targetContextRatio,
6657
6603
  getThresholdContextRatio: (modelKey) => state.cwd ? state.config.compaction.thresholds[modelKey] : DEFAULT_FABRIC_CONFIG.compaction.thresholds[modelKey],
6658
6604
  getThresholdTokens: (modelKey) => state.cwd ? state.config.compaction.tokenThresholds[modelKey] : DEFAULT_FABRIC_CONFIG.compaction.tokenThresholds[modelKey],
6659
6605
  getOutputReserveTokens: () => state.bootstrapped ? state.config.compaction.outputReserveTokens : DEFAULT_FABRIC_CONFIG.compaction.outputReserveTokens,
6660
6606
  onYield: () => {
6661
- compactionYieldPending = true;
6662
- }
6607
+ ownerSlot.yielded = true;
6608
+ },
6609
+ getOwnerClaim: compactionOwner
6610
+ }));
6611
+ pi.on("session_before_compact", async (event, context) => {
6612
+ if (state.managedHostOptions?.compaction === "pi") return;
6613
+ return (await compactionHandlers()).beforeCompact(event, context);
6614
+ });
6615
+ pi.on("session_before_tree", async (event, context) => {
6616
+ if (state.managedHostOptions?.compaction === "pi") return;
6617
+ return (await compactionHandlers()).beforeTree(event, context);
6663
6618
  });
6664
6619
  let extractiveHistory;
6665
6620
  let extractiveEpoch = 0;
@@ -6681,13 +6636,18 @@ function createFabricExtension(entryUrl) {
6681
6636
  invalidateExtractive(true);
6682
6637
  return;
6683
6638
  }
6639
+ const prompt = userPromptText(event);
6640
+ if (prompt === void 0) {
6641
+ invalidateExtractive();
6642
+ return;
6643
+ }
6684
6644
  const epoch = ++extractiveEpoch;
6685
6645
  const sessionId = context.sessionManager.getSessionId();
6686
6646
  const leaf = context.sessionManager.getLeafId();
6687
6647
  const { ExtractiveHistory } = await import("../memory/extractive-history.js");
6688
6648
  if (epoch !== extractiveEpoch || !extractiveConfig()?.enabled || context.signal?.aborted || context.sessionManager.getSessionId() !== sessionId || context.sessionManager.getLeafId() !== leaf) return;
6689
6649
  extractiveHistory ??= new ExtractiveHistory(extractiveConfig);
6690
- await extractiveHistory.prepare(context, event.messageType !== "custom" ? event.prompt : "");
6650
+ await extractiveHistory.prepare(context, prompt);
6691
6651
  });
6692
6652
  pi.on("context", async (event, context) => {
6693
6653
  const sessionId = context.sessionManager.getSessionId();
@@ -6736,46 +6696,65 @@ function createFabricExtension(entryUrl) {
6736
6696
  const projected = extractiveHistory?.inject(context, messages) ?? messages;
6737
6697
  return projected !== messages || messages.length !== event.messages.length ? { messages: projected } : void 0;
6738
6698
  });
6699
+ let promptGuidance;
6739
6700
  pi.on("before_agent_start", async (event, context) => {
6740
6701
  const config = state.bootstrapped ? state.config : DEFAULT_FABRIC_CONFIG;
6741
6702
  const fullCodeMode = config.fullCodeMode;
6742
6703
  const schemaMode = config.schema.mode;
6743
6704
  const effectiveFullCodeMode = fullCodeMode || schemaMode === "enforce";
6744
6705
  if (!pi.getActiveTools().includes("fabric_exec")) return;
6706
+ const {
6707
+ buildSkillReferenceGuidance,
6708
+ coreOverridePromptGuidance,
6709
+ defaultFabricExecutionGuidance,
6710
+ extensionToolRosterGuidance,
6711
+ fabricExecutionKernelGuidance,
6712
+ managedHostExecutionGuidance,
6713
+ managedHostKernelGuidance,
6714
+ fabricSchemaGuidance
6715
+ } = await (promptGuidance ??= import("../core/prompt-guidance.js"));
6745
6716
  const skills = event.systemPromptOptions.skills ?? [];
6746
6717
  const captureSnapshot = state.bootstrapped ? capturePolicy() : void 0;
6747
- const systemPrompt = restoreSkillsForFullCodePrompt(event.systemPrompt, skills, effectiveFullCodeMode);
6748
- const skillReferenceGuidance = effectiveFullCodeMode ? buildSkillReferenceGuidance(event.messageType !== "custom" ? event.prompt : "", skills) : void 0;
6718
+ const managedHost = state.managedHostOptions;
6719
+ const skillReader = managedHost ? managedHost.skillReader ?? null : void 0;
6720
+ const sections = event.systemPromptOptions.forceSystemPrompt === void 0 ? event.systemPromptOptions.sections : void 0;
6721
+ const systemPrompt = sections ? "" : restoreSkillsForFullCodePrompt(event.systemPrompt, skills, effectiveFullCodeMode, skillReader);
6722
+ const prompt = userPromptText(event);
6723
+ const skillReferenceGuidance = effectiveFullCodeMode && prompt !== void 0 ? buildSkillReferenceGuidance(prompt, skills, skillReader) : void 0;
6749
6724
  const currentModel = context.model ? `${context.model.provider}/${context.model.id}` : void 0;
6750
6725
  const resolvedGuidance = resolveFabricModelGuidance(state.modelGuidance(), {
6751
6726
  ...currentModel ? { model: currentModel } : {},
6752
6727
  target: process.env.PI_FABRIC_PARENT_RUN ? "participant" : "main",
6753
6728
  defaults: [{
6754
6729
  slot: FABRIC_EXECUTION_GUIDANCE_SLOT,
6755
- content: defaultFabricExecutionGuidance(effectiveFullCodeMode, config.executor.kernel, config.executor.pythonRuntime, config.executor.codemodeProfile)
6730
+ content: managedHost ? managedHostExecutionGuidance(managedHost) : defaultFabricExecutionGuidance(effectiveFullCodeMode, config.executor.kernel, config.executor.pythonRuntime, config.executor.codemodeProfile)
6756
6731
  }]
6757
6732
  });
6758
- const overrideGuidance = effectiveFullCodeMode ? coreOverridePromptGuidance(capturedTools).trim() : void 0;
6759
- const extensionRoster = effectiveFullCodeMode ? extensionToolRosterGuidance(capturedTools.list().filter(
6760
- (entry) => !state.config.mcp.enabled || !isSelectedNativeMcpTool(entry.definition, state.config.mcp.nativeServers)
6733
+ const toolAllowlist = readChildToolAllowlist();
6734
+ const overrideGuidance = effectiveFullCodeMode && !managedHost ? coreOverridePromptGuidance(capturedTools, toolAllowlist).trim() : void 0;
6735
+ const extensionRoster = effectiveFullCodeMode && !managedHost ? extensionToolRosterGuidance(capturedTools.list().filter(
6736
+ (entry) => (toolAllowlist === void 0 || toolAllowlist.has(entry.name)) && (!config.mcp.enabled || !isSelectedNativeMcpTool(entry.definition, config.mcp.nativeServers))
6761
6737
  ), new Set(PI_CORE_TOOL_NAMES), config.executor.kernel === "typescript" && config.executor.codemodeProfile === "native") : void 0;
6762
6738
  const guidance = [
6763
- fabricExecutionKernelGuidance(effectiveFullCodeMode, config.executor.kernel, config.executor.pythonRuntime, config.executor.codemodeProfile),
6739
+ managedHost ? managedHostKernelGuidance(managedHost) : fabricExecutionKernelGuidance(effectiveFullCodeMode, config.executor.kernel, config.executor.pythonRuntime, config.executor.codemodeProfile),
6764
6740
  resolvedGuidance.slotText,
6765
6741
  fabricSchemaGuidance(schemaMode),
6766
6742
  overrideGuidance,
6767
6743
  extensionRoster,
6768
- resolvedGuidance.appendText
6744
+ resolvedGuidance.appendText,
6745
+ managedHost?.guidance
6769
6746
  ].filter((section) => Boolean(section)).join("\n\n");
6770
- if (!skillReferenceGuidance) return {
6771
- systemPrompt: `${systemPrompt}
6747
+ if (sections) {
6748
+ const catalog = restoreSkillsForFullCodePrompt("", skills, effectiveFullCodeMode, skillReader).trim();
6749
+ if (catalog) sections.skills = catalog;
6750
+ sections.fabric = guidance;
6751
+ }
6752
+ const forced = sections ? {} : { systemPrompt: `${systemPrompt}
6772
6753
 
6773
- ${guidance}`
6774
- };
6754
+ ${guidance}` };
6755
+ if (!skillReferenceGuidance) return sections ? void 0 : forced;
6775
6756
  return {
6776
- systemPrompt: `${systemPrompt}
6777
-
6778
- ${guidance}`,
6757
+ ...forced,
6779
6758
  message: {
6780
6759
  customType: SKILL_REFERENCE_CUSTOM_TYPE,
6781
6760
  content: skillReferenceGuidance,
@@ -6786,6 +6765,8 @@ ${guidance}`,
6786
6765
  });
6787
6766
  pi.on("before_agent_start", (event) => {
6788
6767
  if (!pi.getActiveTools().includes("fabric_exec")) return;
6768
+ const prompt = userPromptText(event);
6769
+ if (prompt === void 0) return;
6789
6770
  const captureSnapshot = state.cwd ? capturePolicy() : void 0;
6790
6771
  if (!captureSnapshot?.enabled || !captureSnapshot.hideFromModel || !fabricOwnsModelTools()) {
6791
6772
  return;
@@ -6793,7 +6774,7 @@ ${guidance}`,
6793
6774
  const names = rewritableHiddenCapturedToolNames(hiddenCapturedToolNames());
6794
6775
  if (names.length === 0) return;
6795
6776
  const mentioned = proxyContractMentionsInSkills(
6796
- event.messageType !== "custom" ? event.prompt : "",
6777
+ prompt,
6797
6778
  event.systemPrompt,
6798
6779
  names
6799
6780
  );
@@ -6812,7 +6793,11 @@ ${guidance}`,
6812
6793
  if (!state.initialized) return;
6813
6794
  state.dispatchHostEvent(eventName, event, context);
6814
6795
  });
6796
+ installTerminalTitle(pi, fabricTerminalTitle);
6815
6797
  pi.on("session_shutdown", async (_event, context) => {
6798
+ unsubscribeOwner();
6799
+ ownerSlot.closed = true;
6800
+ ownerSlot.host?.clear();
6816
6801
  entropyStopping = true;
6817
6802
  clearEntropyRetry();
6818
6803
  if (entropyEvidenceThisTurn) {
@@ -6827,7 +6812,12 @@ ${guidance}`,
6827
6812
  unsubscribeProviderRegistration();
6828
6813
  unsubscribeProviderWithdrawal();
6829
6814
  unsubscribeToolPlacement();
6815
+ unsubscribeHostPolicy();
6830
6816
  unsubscribeProgramRun();
6817
+ unsubscribeActionPolicyRegistration();
6818
+ state.actionPolicyHooks.clear();
6819
+ unsubscribeQuestionRendererRegistration();
6820
+ state.questionRenderers.clear();
6831
6821
  programRunContext = void 0;
6832
6822
  pendingHandoffs.clear();
6833
6823
  directToolApproval.clear();
@@ -6856,6 +6846,19 @@ ${guidance}`,
6856
6846
  if (context.hasUI) context.ui.notify(notice, "warning");
6857
6847
  else console.warn(`[pi-fabric] ${notice}`);
6858
6848
  });
6849
+ let keepVisibleNoticeKey;
6850
+ pi.on("before_agent_start", (_event, context) => {
6851
+ if (!state.bootstrapped) return;
6852
+ const ignored = ineffectiveKeepVisible(state.config, state.foregroundTools().tools);
6853
+ if (ignored.length === 0) return;
6854
+ const enforce = state.config.schema.mode === "enforce";
6855
+ const key = `${context.sessionManager?.getSessionId?.() ?? ""}\0${ignored.join(",")}`;
6856
+ if (keepVisibleNoticeKey === key) return;
6857
+ keepVisibleNoticeKey = key;
6858
+ const notice = `Fabric capture.keepVisible has no effect in ${enforce ? "Schema enforce" : "full code"} mode; ${ignored.join(", ")} stay hidden from the model${enforce ? "" : ". Use foreground.tools to declare a tool beside fabric_exec"}.`;
6859
+ if (context.hasUI) context.ui.notify(notice, "warning");
6860
+ else console.warn(`[pi-fabric] ${notice}`);
6861
+ });
6859
6862
  let runnerNoticeKey;
6860
6863
  pi.on("before_agent_start", (_event, context) => {
6861
6864
  if (!state.bootstrapped) return;
@@ -6902,4 +6905,4 @@ export {
6902
6905
  FABRIC_MANAGED_HOST_VERSION,
6903
6906
  createFabricExtension
6904
6907
  };
6905
- //# sourceMappingURL=chunk-XCEEQ5AB.js.map
6908
+ //# sourceMappingURL=chunk-WGMCNCP6.js.map