@e4779/pi-fabric 0.102.0-fork.16 → 0.105.0-fork.22

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 (562) hide show
  1. package/README.md +44 -13
  2. package/THIRD_PARTY_NOTICES.md +10 -2
  3. package/dist/activity/store.d.ts +3 -0
  4. package/dist/activity/store.d.ts.map +1 -1
  5. package/dist/activity/workflow-items.d.ts +33 -0
  6. package/dist/activity/workflow-items.d.ts.map +1 -0
  7. package/dist/actors/binding-store.d.ts.map +1 -1
  8. package/dist/actors/manager.d.ts +6 -0
  9. package/dist/actors/manager.d.ts.map +1 -1
  10. package/dist/actors/mesh-monitor.d.ts +2 -2
  11. package/dist/actors/mesh-monitor.d.ts.map +1 -1
  12. package/dist/actors/registry-store.d.ts.map +1 -1
  13. package/dist/actors/types.d.ts +11 -0
  14. package/dist/actors/types.d.ts.map +1 -1
  15. package/dist/agents/child-env.d.ts +29 -0
  16. package/dist/agents/child-env.d.ts.map +1 -0
  17. package/dist/agents/fork-seed.d.ts +21 -0
  18. package/dist/agents/fork-seed.d.ts.map +1 -0
  19. package/dist/agents/handoff.d.ts +7 -1
  20. package/dist/agents/handoff.d.ts.map +1 -1
  21. package/dist/agents/hosted-run.d.ts +63 -0
  22. package/dist/agents/hosted-run.d.ts.map +1 -0
  23. package/dist/agents/manager.d.ts +21 -1
  24. package/dist/agents/manager.d.ts.map +1 -1
  25. package/dist/agents/request.d.ts.map +1 -1
  26. package/dist/agents/runner-notice.d.ts +7 -0
  27. package/dist/agents/runner-notice.d.ts.map +1 -0
  28. package/dist/agents/runner-protocol.d.ts +158 -0
  29. package/dist/agents/runner-protocol.d.ts.map +1 -0
  30. package/dist/agents/runner-registry.d.ts +223 -0
  31. package/dist/agents/runner-registry.d.ts.map +1 -0
  32. package/dist/agents/transports/process-transport.d.ts.map +1 -1
  33. package/dist/agents/transports/process-utils.d.ts +4 -1
  34. package/dist/agents/transports/process-utils.d.ts.map +1 -1
  35. package/dist/agents/types.d.ts +89 -4
  36. package/dist/agents/types.d.ts.map +1 -1
  37. package/dist/agents/worktree-manager.d.ts +21 -0
  38. package/dist/agents/worktree-manager.d.ts.map +1 -1
  39. package/dist/agents/write-guard.d.ts +16 -0
  40. package/dist/agents/write-guard.d.ts.map +1 -0
  41. package/dist/agents/write-guard.js +13 -0
  42. package/dist/agents/write-guard.js.map +7 -0
  43. package/dist/agents.js +13 -12
  44. package/dist/agents.js.map +1 -1
  45. package/dist/assessment.d.ts +3 -0
  46. package/dist/assessment.d.ts.map +1 -0
  47. package/dist/assessment.js +15 -0
  48. package/dist/assessment.js.map +7 -0
  49. package/dist/audit/assessment.d.ts +74 -0
  50. package/dist/audit/assessment.d.ts.map +1 -0
  51. package/dist/audit/details.d.ts +4 -0
  52. package/dist/audit/details.d.ts.map +1 -1
  53. package/dist/audit/index.d.ts +1 -0
  54. package/dist/audit/index.d.ts.map +1 -1
  55. package/dist/audit/projection.d.ts +2 -1
  56. package/dist/audit/projection.d.ts.map +1 -1
  57. package/dist/audit/trace.d.ts +16 -1
  58. package/dist/audit/trace.d.ts.map +1 -1
  59. package/dist/cache/leases.d.ts +2 -1
  60. package/dist/cache/leases.d.ts.map +1 -1
  61. package/dist/capture/interceptor.d.ts.map +1 -1
  62. package/dist/chunks/chunk-2USMWEE6.js +81 -0
  63. package/dist/chunks/chunk-2USMWEE6.js.map +7 -0
  64. package/dist/chunks/chunk-2Y24ML7H.js +115 -0
  65. package/dist/chunks/chunk-2Y24ML7H.js.map +7 -0
  66. package/dist/chunks/chunk-3GJJG2FV.js +1329 -0
  67. package/dist/chunks/chunk-3GJJG2FV.js.map +7 -0
  68. package/dist/chunks/{chunk-5VTBHJN3.js → chunk-3KDUMDPZ.js} +153 -29
  69. package/dist/chunks/chunk-3KDUMDPZ.js.map +7 -0
  70. package/dist/chunks/chunk-4RTHQGES.js +189 -0
  71. package/dist/chunks/chunk-4RTHQGES.js.map +7 -0
  72. package/dist/chunks/{chunk-ZZ66L3W5.js → chunk-5MNLVHF5.js} +30 -7
  73. package/dist/chunks/chunk-5MNLVHF5.js.map +7 -0
  74. package/dist/chunks/{chunk-RAO6TQFP.js → chunk-5XBYFSI5.js} +26 -6
  75. package/dist/chunks/chunk-5XBYFSI5.js.map +7 -0
  76. package/dist/chunks/{chunk-J2HV2URQ.js → chunk-7EYJE4TW.js} +1 -1
  77. package/dist/chunks/{chunk-J2HV2URQ.js.map → chunk-7EYJE4TW.js.map} +2 -2
  78. package/dist/chunks/{chunk-57CMH4SW.js → chunk-7JU7Z4XQ.js} +2 -2
  79. package/dist/chunks/chunk-7QKKLBHJ.js +33 -0
  80. package/dist/chunks/chunk-7QKKLBHJ.js.map +7 -0
  81. package/dist/chunks/chunk-7XRUMDV7.js +235 -0
  82. package/dist/chunks/chunk-7XRUMDV7.js.map +7 -0
  83. package/dist/chunks/{chunk-DUJ46TIP.js → chunk-ABJCSNZO.js} +4 -4
  84. package/dist/chunks/chunk-B2Y4364O.js +78 -0
  85. package/dist/chunks/chunk-B2Y4364O.js.map +7 -0
  86. package/dist/chunks/{chunk-4TKPBEPB.js → chunk-BVJBYFHD.js} +9 -3
  87. package/dist/chunks/{chunk-4TKPBEPB.js.map → chunk-BVJBYFHD.js.map} +2 -2
  88. package/dist/chunks/{chunk-KP4ANT6L.js → chunk-C7EEG6SM.js} +2 -2
  89. package/dist/chunks/{chunk-NHMICIEU.js → chunk-CCHZXF6K.js} +3 -3
  90. package/dist/chunks/{chunk-W63E3WEO.js → chunk-CXTTLBUV.js} +3 -2
  91. package/dist/chunks/chunk-CXTTLBUV.js.map +7 -0
  92. package/dist/chunks/{chunk-HOX6VW45.js → chunk-CYMDX3XP.js} +1 -1
  93. package/dist/chunks/{chunk-HOX6VW45.js.map → chunk-CYMDX3XP.js.map} +1 -1
  94. package/dist/chunks/chunk-DK35W6U7.js +259 -0
  95. package/dist/chunks/chunk-DK35W6U7.js.map +7 -0
  96. package/dist/chunks/{chunk-5JN5AWNV.js → chunk-DZ4WN5XJ.js} +3 -3
  97. package/dist/chunks/chunk-EXWS4ZS3.js +6490 -0
  98. package/dist/chunks/chunk-EXWS4ZS3.js.map +7 -0
  99. package/dist/chunks/{chunk-QHYBSIIO.js → chunk-FB24AOIJ.js} +39 -37
  100. package/dist/chunks/{chunk-QHYBSIIO.js.map → chunk-FB24AOIJ.js.map} +1 -1
  101. package/dist/chunks/chunk-FSB2VIRZ.js +435 -0
  102. package/dist/chunks/chunk-FSB2VIRZ.js.map +7 -0
  103. package/dist/chunks/{chunk-PNDYFU64.js → chunk-GJVPP3NN.js} +81 -11
  104. package/dist/chunks/chunk-GJVPP3NN.js.map +7 -0
  105. package/dist/chunks/{chunk-B5D6GA77.js → chunk-GYPDGW27.js} +100 -92
  106. package/dist/chunks/chunk-GYPDGW27.js.map +7 -0
  107. package/dist/chunks/{chunk-LEFBW2GK.js → chunk-IAFI4A2I.js} +44 -2
  108. package/dist/chunks/{chunk-LEFBW2GK.js.map → chunk-IAFI4A2I.js.map} +3 -3
  109. package/dist/chunks/{chunk-PWS2OXLV.js → chunk-IIPKG52D.js} +1 -1
  110. package/dist/chunks/chunk-IIPKG52D.js.map +7 -0
  111. package/dist/chunks/chunk-ITVLKXCI.js +266 -0
  112. package/dist/chunks/chunk-ITVLKXCI.js.map +7 -0
  113. package/dist/chunks/chunk-JKQARSWR.js +265 -0
  114. package/dist/chunks/chunk-JKQARSWR.js.map +7 -0
  115. package/dist/chunks/{chunk-AYBIR4YV.js → chunk-KJZAOENY.js} +6 -4
  116. package/dist/chunks/chunk-KJZAOENY.js.map +7 -0
  117. package/dist/chunks/{chunk-74BA4VSX.js → chunk-KQ6R5EWR.js} +1462 -1405
  118. package/dist/chunks/chunk-KQ6R5EWR.js.map +7 -0
  119. package/dist/chunks/chunk-L22K5BWU.js +180 -0
  120. package/dist/chunks/chunk-L22K5BWU.js.map +7 -0
  121. package/dist/chunks/{chunk-7XJB2USB.js → chunk-LOLCTWJF.js} +4 -4
  122. package/dist/chunks/{chunk-QETG2GVX.js → chunk-M5IN6DMF.js} +34 -31
  123. package/dist/chunks/chunk-M5IN6DMF.js.map +7 -0
  124. package/dist/chunks/{chunk-64O5L7EW.js → chunk-M6IRQ3QT.js} +2 -2
  125. package/dist/chunks/{chunk-TX6E5W7H.js → chunk-NTC2MCB6.js} +1 -1
  126. package/dist/chunks/chunk-NTC2MCB6.js.map +7 -0
  127. package/dist/chunks/{chunk-EPYLZWJV.js → chunk-OVBKQCYL.js} +2 -2
  128. package/dist/chunks/{chunk-YV2PHCDB.js → chunk-PYFJW3HC.js} +16 -2
  129. package/dist/chunks/{chunk-YV2PHCDB.js.map → chunk-PYFJW3HC.js.map} +3 -3
  130. package/dist/chunks/{chunk-Z5Y65YBX.js → chunk-PYQM7KPL.js} +3 -2
  131. package/dist/chunks/{chunk-BEJF2JX2.js → chunk-QLFDPXK7.js} +33 -2
  132. package/dist/chunks/chunk-QLFDPXK7.js.map +7 -0
  133. package/dist/chunks/chunk-QUWC6YCN.js +125 -0
  134. package/dist/chunks/chunk-QUWC6YCN.js.map +7 -0
  135. package/dist/chunks/{chunk-DKVJREDI.js → chunk-QY7YK7M6.js} +2 -2
  136. package/dist/chunks/{chunk-WMJ2AVQQ.js → chunk-R5F6CHW2.js} +34 -18
  137. package/dist/chunks/chunk-R5F6CHW2.js.map +7 -0
  138. package/dist/chunks/chunk-S3IRPDSO.js +57 -0
  139. package/dist/chunks/chunk-S3IRPDSO.js.map +7 -0
  140. package/dist/chunks/{chunk-7BG5COXB.js → chunk-SVDHQUTM.js} +21 -4
  141. package/dist/chunks/chunk-SVDHQUTM.js.map +7 -0
  142. package/dist/chunks/{chunk-HG4DMARW.js → chunk-T5CU2GPZ.js} +116 -26
  143. package/dist/chunks/chunk-T5CU2GPZ.js.map +7 -0
  144. package/dist/chunks/{chunk-RIFG4HS6.js → chunk-TFFZVLR2.js} +141 -9
  145. package/dist/chunks/chunk-TFFZVLR2.js.map +7 -0
  146. package/dist/chunks/{chunk-BUQZBG6O.js → chunk-U2UBUKNQ.js} +136 -136
  147. package/dist/chunks/chunk-U2UBUKNQ.js.map +7 -0
  148. package/dist/chunks/chunk-U366I5K2.js +363 -0
  149. package/dist/chunks/chunk-U366I5K2.js.map +7 -0
  150. package/dist/chunks/{chunk-4NF3S3NM.js → chunk-UTOBAZ5T.js} +1 -1
  151. package/dist/chunks/chunk-UTOBAZ5T.js.map +7 -0
  152. package/dist/chunks/chunk-V73NIH6B.js +127 -0
  153. package/dist/chunks/chunk-V73NIH6B.js.map +7 -0
  154. package/dist/chunks/{chunk-PN4EKNRE.js → chunk-VON4TSO3.js} +132 -12
  155. package/dist/chunks/chunk-VON4TSO3.js.map +7 -0
  156. package/dist/chunks/{chunk-5ZJV4LAX.js → chunk-VPRJOD4Y.js} +4 -4
  157. package/dist/chunks/{chunk-FDIEQEXS.js → chunk-VSDUSNIA.js} +4 -4
  158. package/dist/chunks/chunk-VSDUSNIA.js.map +7 -0
  159. package/dist/chunks/{chunk-RG22JKIC.js → chunk-W7X4XEQU.js} +2 -2
  160. package/dist/chunks/{chunk-LV4IT75S.js → chunk-WLLXKS6I.js} +2 -2
  161. package/dist/chunks/chunk-WOLUDZVR.js +197 -0
  162. package/dist/chunks/chunk-WOLUDZVR.js.map +7 -0
  163. package/dist/chunks/{chunk-YVDBHS4C.js → chunk-WREA4RNR.js} +3 -3
  164. package/dist/chunks/{chunk-QE2JFB7F.js → chunk-WYUV6WL3.js} +16 -6
  165. package/dist/chunks/chunk-WYUV6WL3.js.map +7 -0
  166. package/dist/chunks/{chunk-NGGI6LDC.js → chunk-X2TRSE7D.js} +2 -2
  167. package/dist/chunks/{chunk-VRAGOMN4.js → chunk-YRDCJZZW.js} +34 -1
  168. package/dist/chunks/chunk-YRDCJZZW.js.map +7 -0
  169. package/dist/chunks/{chunk-CC63CY6R.js → chunk-YYSZBD7S.js} +17 -261
  170. package/dist/chunks/chunk-YYSZBD7S.js.map +7 -0
  171. package/dist/chunks/{chunk-A4VP7HDF.js → chunk-ZLNJDTCN.js} +2 -2
  172. package/dist/chunks/{chunk-G4CSXNBT.js → chunk-ZXKYU6CH.js} +42 -5
  173. package/dist/chunks/chunk-ZXKYU6CH.js.map +7 -0
  174. package/dist/cli/decisions.d.ts +8 -0
  175. package/dist/cli/decisions.d.ts.map +1 -0
  176. package/dist/cli/decisions.js +131 -0
  177. package/dist/cli/decisions.js.map +7 -0
  178. package/dist/cli/index.d.ts +3 -0
  179. package/dist/cli/index.d.ts.map +1 -0
  180. package/dist/cli/index.js +56 -0
  181. package/dist/cli/index.js.map +7 -0
  182. package/dist/cli/mesh.d.ts +3 -0
  183. package/dist/cli/mesh.d.ts.map +1 -0
  184. package/dist/cli/mesh.js +126 -0
  185. package/dist/cli/mesh.js.map +7 -0
  186. package/dist/commands/fabric.d.ts.map +1 -1
  187. package/dist/compaction/carry.d.ts +23 -0
  188. package/dist/compaction/carry.d.ts.map +1 -0
  189. package/dist/compaction/hook.d.ts +9 -0
  190. package/dist/compaction/hook.d.ts.map +1 -1
  191. package/dist/compaction/hook.js +6 -6
  192. package/dist/compaction/orphan-repair.d.ts +11 -0
  193. package/dist/compaction/orphan-repair.d.ts.map +1 -0
  194. package/dist/compaction/orphan-repair.js +75 -0
  195. package/dist/compaction/orphan-repair.js.map +7 -0
  196. package/dist/compaction/owner.d.ts +26 -0
  197. package/dist/compaction/owner.d.ts.map +1 -0
  198. package/dist/compaction/owner.js +26 -0
  199. package/dist/compaction/owner.js.map +7 -0
  200. package/dist/compaction/pressure.d.ts +19 -0
  201. package/dist/compaction/pressure.d.ts.map +1 -0
  202. package/dist/compaction/render.d.ts +4 -0
  203. package/dist/compaction/render.d.ts.map +1 -1
  204. package/dist/compaction/threshold.d.ts +6 -1
  205. package/dist/compaction/threshold.d.ts.map +1 -1
  206. package/dist/components/configuration.js +6 -6
  207. package/dist/components/provider-component.d.ts +1 -1
  208. package/dist/components/provider-component.d.ts.map +1 -1
  209. package/dist/config.d.ts +45 -2
  210. package/dist/config.d.ts.map +1 -1
  211. package/dist/core/action-registry.d.ts +5 -1
  212. package/dist/core/action-registry.d.ts.map +1 -1
  213. package/dist/core/action-registry.js +8 -8
  214. package/dist/core/approval-controller.d.ts +5 -1
  215. package/dist/core/approval-controller.d.ts.map +1 -1
  216. package/dist/core/approval-overrides.d.ts +11 -0
  217. package/dist/core/approval-overrides.d.ts.map +1 -0
  218. package/dist/core/atomic-write.d.ts +77 -0
  219. package/dist/core/atomic-write.d.ts.map +1 -1
  220. package/dist/core/compact-controller.d.ts +8 -0
  221. package/dist/core/compact-controller.d.ts.map +1 -1
  222. package/dist/core/file-lock.d.ts.map +1 -1
  223. package/dist/core/foreground-tools.d.ts +45 -0
  224. package/dist/core/foreground-tools.d.ts.map +1 -0
  225. package/dist/core/provider-bindings.d.ts +10 -1
  226. package/dist/core/provider-bindings.d.ts.map +1 -1
  227. package/dist/core/provider-operations.js.map +1 -1
  228. package/dist/core/tool-ownership.d.ts +18 -2
  229. package/dist/core/tool-ownership.d.ts.map +1 -1
  230. package/dist/decisions/command.d.ts +5 -0
  231. package/dist/decisions/command.d.ts.map +1 -0
  232. package/dist/decisions/command.js +74 -0
  233. package/dist/decisions/command.js.map +7 -0
  234. package/dist/decisions/host.d.ts +24 -0
  235. package/dist/decisions/host.d.ts.map +1 -0
  236. package/dist/decisions/store.d.ts +147 -0
  237. package/dist/decisions/store.d.ts.map +1 -0
  238. package/dist/durable.d.ts +38 -0
  239. package/dist/durable.d.ts.map +1 -0
  240. package/dist/durable.js +274 -0
  241. package/dist/durable.js.map +7 -0
  242. package/dist/entropy/index.js +10 -9
  243. package/dist/execution-service.d.ts +41 -1
  244. package/dist/execution-service.d.ts.map +1 -1
  245. package/dist/extension-bootstrap.d.ts +7 -0
  246. package/dist/extension-bootstrap.d.ts.map +1 -0
  247. package/dist/extension-bootstrap.js +51 -0
  248. package/dist/extension-bootstrap.js.map +7 -0
  249. package/dist/extension.d.ts +8 -0
  250. package/dist/extension.d.ts.map +1 -0
  251. package/dist/fabric-exec-tool.d.ts.map +1 -1
  252. package/dist/fabric-runtime-state.d.ts +8 -0
  253. package/dist/fabric-runtime-state.d.ts.map +1 -1
  254. package/dist/fabric-runtime-state.js +2432 -346
  255. package/dist/fabric-runtime-state.js.map +4 -4
  256. package/dist/fabric-state.d.ts +22 -0
  257. package/dist/fabric-state.d.ts.map +1 -1
  258. package/dist/host-compatibility.d.ts +1 -1
  259. package/dist/host-compatibility.d.ts.map +1 -1
  260. package/dist/index.d.ts +5 -6
  261. package/dist/index.d.ts.map +1 -1
  262. package/dist/index.js +68 -6250
  263. package/dist/index.js.map +4 -4
  264. package/dist/jev/observation.js +5 -5
  265. package/dist/jev-fabric/bridge.d.ts +15 -0
  266. package/dist/jev-fabric/bridge.d.ts.map +1 -1
  267. package/dist/jev-fabric/client.js +1 -1
  268. package/dist/jev-fabric/client.js.map +2 -2
  269. package/dist/jev-fabric/operations.d.ts +2 -0
  270. package/dist/jev-fabric/operations.d.ts.map +1 -1
  271. package/dist/jev-fabric/operations.js +1 -1
  272. package/dist/jev-fabric/operations.js.map +2 -2
  273. package/dist/jev-fabric/resolve.js +1 -1
  274. package/dist/jev-fabric/resolve.js.map +2 -2
  275. package/dist/jev.js +9 -9
  276. package/dist/lifecycle/types.d.ts.map +1 -1
  277. package/dist/memory/client.d.ts +3 -0
  278. package/dist/memory/client.d.ts.map +1 -1
  279. package/dist/memory/digest.js +2 -2
  280. package/dist/memory/discovery.js +6 -6
  281. package/dist/memory/expand-service.d.ts.map +1 -1
  282. package/dist/memory/file-worker.d.ts.map +1 -1
  283. package/dist/memory/file-worker.js +10 -9
  284. package/dist/memory/file-worker.js.map +2 -2
  285. package/dist/memory/host-source.d.ts +2 -1
  286. package/dist/memory/host-source.d.ts.map +1 -1
  287. package/dist/memory/normalize.js +5 -5
  288. package/dist/memory/portable.d.ts +3 -1
  289. package/dist/memory/portable.d.ts.map +1 -1
  290. package/dist/memory/request-cache.d.ts +4 -2
  291. package/dist/memory/request-cache.d.ts.map +1 -1
  292. package/dist/memory/request-context.d.ts +3 -0
  293. package/dist/memory/request-context.d.ts.map +1 -1
  294. package/dist/memory/search.js +7 -7
  295. package/dist/memory/worker-provider.d.ts.map +1 -1
  296. package/dist/memory/worker-provider.js +10 -10
  297. package/dist/memory.js +14 -13
  298. package/dist/memory.js.map +2 -2
  299. package/dist/mesh/grants.d.ts +86 -0
  300. package/dist/mesh/grants.d.ts.map +1 -0
  301. package/dist/mesh/store.d.ts +89 -0
  302. package/dist/mesh/store.d.ts.map +1 -1
  303. package/dist/programs/host.d.ts +22 -0
  304. package/dist/programs/host.d.ts.map +1 -0
  305. package/dist/programs/host.js +171 -0
  306. package/dist/programs/host.js.map +7 -0
  307. package/dist/programs/source.d.ts +16 -0
  308. package/dist/programs/source.d.ts.map +1 -0
  309. package/dist/programs/store.d.ts +81 -0
  310. package/dist/programs/store.d.ts.map +1 -0
  311. package/dist/protocol.d.ts +153 -0
  312. package/dist/protocol.d.ts.map +1 -1
  313. package/dist/protocol.js +15 -1
  314. package/dist/providers/agents-actions.d.ts.map +1 -1
  315. package/dist/providers/agents-message-router.d.ts.map +1 -1
  316. package/dist/providers/agents-progress.d.ts.map +1 -1
  317. package/dist/providers/agents-provider.d.ts +3 -0
  318. package/dist/providers/agents-provider.d.ts.map +1 -1
  319. package/dist/providers/cache-provider.d.ts +1 -1
  320. package/dist/providers/cache-provider.d.ts.map +1 -1
  321. package/dist/providers/compact-provider.d.ts +13 -1
  322. package/dist/providers/compact-provider.d.ts.map +1 -1
  323. package/dist/providers/decisions-provider.d.ts +17 -0
  324. package/dist/providers/decisions-provider.d.ts.map +1 -0
  325. package/dist/providers/jev-provider.js +9 -9
  326. package/dist/providers/memory-provider.d.ts.map +1 -1
  327. package/dist/providers/memory-provider.js +9 -9
  328. package/dist/providers/mesh-provider.d.ts +4 -0
  329. package/dist/providers/mesh-provider.d.ts.map +1 -1
  330. package/dist/providers/pi-native-mcp.d.ts.map +1 -1
  331. package/dist/providers/pi-tools-provider.d.ts.map +1 -1
  332. package/dist/providers/programs-provider.d.ts +18 -0
  333. package/dist/providers/programs-provider.d.ts.map +1 -0
  334. package/dist/providers/state-provider.d.ts +4 -1
  335. package/dist/providers/state-provider.d.ts.map +1 -1
  336. package/dist/providers/thinking-provider.d.ts +15 -0
  337. package/dist/providers/thinking-provider.d.ts.map +1 -0
  338. package/dist/residency/actor-client.js +3 -3
  339. package/dist/residency/client.d.ts.map +1 -1
  340. package/dist/residency/host.d.ts +21 -0
  341. package/dist/residency/host.d.ts.map +1 -1
  342. package/dist/residency/host.js +28 -22
  343. package/dist/residency/launcher-owner.d.ts +2 -0
  344. package/dist/residency/launcher-owner.d.ts.map +1 -1
  345. package/dist/residency/launcher.js +35 -20
  346. package/dist/residency/launcher.js.map +3 -3
  347. package/dist/residency/pi-entry.js +26 -22
  348. package/dist/residency/pi-entry.js.map +1 -1
  349. package/dist/residency/protocol.d.ts +12 -2
  350. package/dist/residency/protocol.d.ts.map +1 -1
  351. package/dist/runners.d.ts +9 -0
  352. package/dist/runners.d.ts.map +1 -0
  353. package/dist/runners.js +182 -0
  354. package/dist/runners.js.map +7 -0
  355. package/dist/runtime/core-override-guest-types.js +2 -2
  356. package/dist/runtime/cpython-child-source.d.ts.map +1 -1
  357. package/dist/runtime/cpython-runtime.d.ts.map +1 -1
  358. package/dist/runtime/cpython-runtime.js +35 -7
  359. package/dist/runtime/cpython-runtime.js.map +2 -2
  360. package/dist/runtime/deadline-pause.d.ts +26 -0
  361. package/dist/runtime/deadline-pause.d.ts.map +1 -0
  362. package/dist/runtime/guest-types.d.ts +1 -1
  363. package/dist/runtime/guest-types.d.ts.map +1 -1
  364. package/dist/runtime/guest-types.js +1 -1
  365. package/dist/runtime/kernel.d.ts +3 -0
  366. package/dist/runtime/kernel.d.ts.map +1 -1
  367. package/dist/runtime/monty-runtime.d.ts.map +1 -1
  368. package/dist/runtime/monty-runtime.js +33 -12
  369. package/dist/runtime/monty-runtime.js.map +2 -2
  370. package/dist/runtime/node-process-runtime.d.ts.map +1 -1
  371. package/dist/runtime/node-process-runtime.js +4 -3
  372. package/dist/runtime/orchestration.d.ts.map +1 -1
  373. package/dist/runtime/quickjs-runtime.d.ts.map +1 -1
  374. package/dist/runtime/quickjs-runtime.js +2 -1
  375. package/dist/runtime/typescript-kernel.js +8 -7
  376. package/dist/runtime/typescript-kernel.js.map +1 -1
  377. package/dist/runtime-state-builtins.d.ts.map +1 -1
  378. package/dist/schema/controller.d.ts.map +1 -1
  379. package/dist/schema/policy.d.ts.map +1 -1
  380. package/dist/scope.d.ts +69 -0
  381. package/dist/scope.d.ts.map +1 -0
  382. package/dist/scope.js +37 -0
  383. package/dist/scope.js.map +7 -0
  384. package/dist/speculation/eligibility.d.ts.map +1 -1
  385. package/dist/speculation/python-scanner.js +1 -1
  386. package/dist/speculation/python-scanner.js.map +2 -2
  387. package/dist/speculation/scanner.js +1 -1
  388. package/dist/speculation/scanner.js.map +2 -2
  389. package/dist/state/binding.d.ts +17 -0
  390. package/dist/state/binding.d.ts.map +1 -0
  391. package/dist/state/store.d.ts +8 -2
  392. package/dist/state/store.d.ts.map +1 -1
  393. package/dist/state/types.d.ts +23 -2
  394. package/dist/state/types.d.ts.map +1 -1
  395. package/dist/storage/retention.d.ts +7 -0
  396. package/dist/storage/retention.d.ts.map +1 -1
  397. package/dist/storage/scratch.d.ts.map +1 -1
  398. package/dist/thinking-control.d.ts +64 -0
  399. package/dist/thinking-control.d.ts.map +1 -0
  400. package/dist/thinking-control.js +15 -0
  401. package/dist/thinking-control.js.map +7 -0
  402. package/dist/thinking.d.ts +61 -0
  403. package/dist/thinking.d.ts.map +1 -1
  404. package/dist/topology/control-plane.d.ts +13 -0
  405. package/dist/topology/control-plane.d.ts.map +1 -1
  406. package/dist/topology/participant-directory.d.ts +2 -0
  407. package/dist/topology/participant-directory.d.ts.map +1 -1
  408. package/dist/topology/provider-participants.d.ts +72 -0
  409. package/dist/topology/provider-participants.d.ts.map +1 -0
  410. package/dist/topology/records.d.ts.map +1 -1
  411. package/dist/topology/types.d.ts +13 -3
  412. package/dist/topology/types.d.ts.map +1 -1
  413. package/dist/type-error-guidance.js +170 -0
  414. package/dist/type-error-guidance.js.map +7 -0
  415. package/dist/ui/controller.d.ts.map +1 -1
  416. package/dist/ui/conversation-chrome.d.ts +2 -0
  417. package/dist/ui/conversation-chrome.d.ts.map +1 -1
  418. package/dist/ui/conversation-chrome.js +1 -1
  419. package/dist/ui/conversation-latest.d.ts +10 -0
  420. package/dist/ui/conversation-latest.d.ts.map +1 -0
  421. package/dist/ui/conversation-native-reader.js +2 -1
  422. package/dist/ui/conversation-native-reader.js.map +1 -1
  423. package/dist/ui/conversation-render.d.ts +2 -1
  424. package/dist/ui/conversation-render.d.ts.map +1 -1
  425. package/dist/ui/conversation-scrollbar.d.ts +22 -0
  426. package/dist/ui/conversation-scrollbar.d.ts.map +1 -0
  427. package/dist/ui/conversation-selection.d.ts +2 -2
  428. package/dist/ui/conversation-selection.d.ts.map +1 -1
  429. package/dist/ui/conversation-targets.d.ts.map +1 -1
  430. package/dist/ui/conversation-targets.js +2 -2
  431. package/dist/ui/conversation.d.ts +3 -0
  432. package/dist/ui/conversation.d.ts.map +1 -1
  433. package/dist/ui/conversation.js +253 -34
  434. package/dist/ui/conversation.js.map +4 -4
  435. package/dist/ui/dashboard-fabric-graph.d.ts.map +1 -1
  436. package/dist/ui/dashboard.js +14 -15
  437. package/dist/ui/dashboard.js.map +2 -2
  438. package/dist/ui/image-overlays.d.ts +16 -0
  439. package/dist/ui/image-overlays.d.ts.map +1 -0
  440. package/dist/ui/image-overlays.js +10 -0
  441. package/dist/ui/image-overlays.js.map +7 -0
  442. package/dist/ui/kitty-viewport.d.ts +24 -0
  443. package/dist/ui/kitty-viewport.d.ts.map +1 -0
  444. package/dist/ui/retention.d.ts +14 -0
  445. package/dist/ui/retention.d.ts.map +1 -0
  446. package/dist/ui/settings-sections-execution.d.ts.map +1 -1
  447. package/dist/ui/settings.d.ts.map +1 -1
  448. package/dist/ui/settings.js +27 -16
  449. package/dist/ui/settings.js.map +2 -2
  450. package/dist/ui/transcript.d.ts +2 -1
  451. package/dist/ui/transcript.d.ts.map +1 -1
  452. package/dist/ui/types.d.ts +2 -1
  453. package/dist/ui/types.d.ts.map +1 -1
  454. package/dist/ui/widget.d.ts +4 -2
  455. package/dist/ui/widget.d.ts.map +1 -1
  456. package/dist/verified/generated/authority-kernel.js +1 -1
  457. package/dist/verified/generated/kernel.js +1 -1
  458. package/dist/verified/generated/lifecycle-kernel.js +1 -1
  459. package/dist/verified/generated/manifest.json +7 -7
  460. package/dist/verified/generated/provider-kernel.js +1 -1
  461. package/dist/verified/generated/storage-kernel.js +1 -1
  462. package/dist/worker/options.d.ts.map +1 -1
  463. package/dist/worker/options.js +14 -0
  464. package/dist/worker/options.js.map +2 -2
  465. package/dist/worker/questions.d.ts +46 -0
  466. package/dist/worker/questions.d.ts.map +1 -0
  467. package/dist/worker/questions.js +87 -0
  468. package/dist/worker/questions.js.map +7 -0
  469. package/dist/worker/result.d.ts +3 -0
  470. package/dist/worker/result.d.ts.map +1 -0
  471. package/dist/worker/result.js +7493 -0
  472. package/dist/worker/result.js.map +7 -0
  473. package/dist/worker/run-record.js +10 -113
  474. package/dist/worker/run-record.js.map +3 -3
  475. package/dist/worker/startup.d.ts +8 -0
  476. package/dist/worker/startup.d.ts.map +1 -0
  477. package/dist/worker.js +111 -22
  478. package/dist/worker.js.map +4 -4
  479. package/docs/agents.md +197 -3
  480. package/docs/architecture.md +8 -1
  481. package/docs/audit-trace.md +36 -1
  482. package/docs/background-tasks.md +25 -1
  483. package/docs/certification.md +1 -1
  484. package/docs/compaction.md +64 -0
  485. package/docs/components.md +1 -0
  486. package/docs/configuration.md +105 -10
  487. package/docs/decisions.md +144 -0
  488. package/docs/durable-pi.md +186 -0
  489. package/docs/interface.md +10 -1
  490. package/docs/kitty-images.md +89 -0
  491. package/docs/licenses/typebox-mit.txt +23 -0
  492. package/docs/memory-recall.md +5 -3
  493. package/docs/programmatic-compaction.md +67 -11
  494. package/docs/programs.md +137 -0
  495. package/docs/provider-capabilities.md +23 -1
  496. package/docs/providers.md +158 -0
  497. package/docs/residency-runtime.md +64 -0
  498. package/docs/schema-enforcement.md +5 -3
  499. package/docs/shell-composition.md +6 -6
  500. package/docs/skills.md +2 -1
  501. package/docs/speculation.md +2 -1
  502. package/docs/state-layer.md +26 -4
  503. package/docs/thinking.md +48 -0
  504. package/docs/verified-kernels.md +1 -1
  505. package/package.json +48 -12
  506. package/scripts/test-verified-kernels.mjs +1 -1
  507. package/scripts/verified-kernels.mjs +1 -1
  508. package/skillsets/python/fabric-exec/SKILL.md +2 -2
  509. package/skillsets/python/fabric-exec/references/agents.md +9 -4
  510. package/skillsets/python/fabric-exec/references/mesh.md +9 -0
  511. package/skillsets/python/fabric-graph/SKILL.md +109 -0
  512. package/skillsets/python/fabric-guide/SKILL.md +2 -1
  513. package/skillsets/typescript/fabric-exec/SKILL.md +20 -2
  514. package/skillsets/typescript/fabric-exec/references/agents.md +10 -4
  515. package/skillsets/typescript/fabric-exec/references/mesh.md +10 -0
  516. package/skillsets/typescript/fabric-graph/SKILL.md +112 -0
  517. package/skillsets/typescript/fabric-guide/SKILL.md +2 -1
  518. package/skillsets/typescript/fabric-workflow/SKILL.md +1 -1
  519. package/dist/chunks/chunk-4NF3S3NM.js.map +0 -7
  520. package/dist/chunks/chunk-5VTBHJN3.js.map +0 -7
  521. package/dist/chunks/chunk-74BA4VSX.js.map +0 -7
  522. package/dist/chunks/chunk-7BG5COXB.js.map +0 -7
  523. package/dist/chunks/chunk-AYBIR4YV.js.map +0 -7
  524. package/dist/chunks/chunk-B5D6GA77.js.map +0 -7
  525. package/dist/chunks/chunk-BEJF2JX2.js.map +0 -7
  526. package/dist/chunks/chunk-BUQZBG6O.js.map +0 -7
  527. package/dist/chunks/chunk-CC63CY6R.js.map +0 -7
  528. package/dist/chunks/chunk-FDIEQEXS.js.map +0 -7
  529. package/dist/chunks/chunk-G4CSXNBT.js.map +0 -7
  530. package/dist/chunks/chunk-HG4DMARW.js.map +0 -7
  531. package/dist/chunks/chunk-KAD7UWT2.js +0 -99
  532. package/dist/chunks/chunk-KAD7UWT2.js.map +0 -7
  533. package/dist/chunks/chunk-MGWQOKBV.js +0 -30
  534. package/dist/chunks/chunk-MGWQOKBV.js.map +0 -7
  535. package/dist/chunks/chunk-PN4EKNRE.js.map +0 -7
  536. package/dist/chunks/chunk-PNDYFU64.js.map +0 -7
  537. package/dist/chunks/chunk-PWS2OXLV.js.map +0 -7
  538. package/dist/chunks/chunk-QE2JFB7F.js.map +0 -7
  539. package/dist/chunks/chunk-QETG2GVX.js.map +0 -7
  540. package/dist/chunks/chunk-RAO6TQFP.js.map +0 -7
  541. package/dist/chunks/chunk-RIFG4HS6.js.map +0 -7
  542. package/dist/chunks/chunk-TX6E5W7H.js.map +0 -7
  543. package/dist/chunks/chunk-VRAGOMN4.js.map +0 -7
  544. package/dist/chunks/chunk-W63E3WEO.js.map +0 -7
  545. package/dist/chunks/chunk-WMJ2AVQQ.js.map +0 -7
  546. package/dist/chunks/chunk-ZZ66L3W5.js.map +0 -7
  547. /package/dist/chunks/{chunk-57CMH4SW.js.map → chunk-7JU7Z4XQ.js.map} +0 -0
  548. /package/dist/chunks/{chunk-DUJ46TIP.js.map → chunk-ABJCSNZO.js.map} +0 -0
  549. /package/dist/chunks/{chunk-KP4ANT6L.js.map → chunk-C7EEG6SM.js.map} +0 -0
  550. /package/dist/chunks/{chunk-NHMICIEU.js.map → chunk-CCHZXF6K.js.map} +0 -0
  551. /package/dist/chunks/{chunk-5JN5AWNV.js.map → chunk-DZ4WN5XJ.js.map} +0 -0
  552. /package/dist/chunks/{chunk-7XJB2USB.js.map → chunk-LOLCTWJF.js.map} +0 -0
  553. /package/dist/chunks/{chunk-64O5L7EW.js.map → chunk-M6IRQ3QT.js.map} +0 -0
  554. /package/dist/chunks/{chunk-EPYLZWJV.js.map → chunk-OVBKQCYL.js.map} +0 -0
  555. /package/dist/chunks/{chunk-Z5Y65YBX.js.map → chunk-PYQM7KPL.js.map} +0 -0
  556. /package/dist/chunks/{chunk-DKVJREDI.js.map → chunk-QY7YK7M6.js.map} +0 -0
  557. /package/dist/chunks/{chunk-5ZJV4LAX.js.map → chunk-VPRJOD4Y.js.map} +0 -0
  558. /package/dist/chunks/{chunk-RG22JKIC.js.map → chunk-W7X4XEQU.js.map} +0 -0
  559. /package/dist/chunks/{chunk-LV4IT75S.js.map → chunk-WLLXKS6I.js.map} +0 -0
  560. /package/dist/chunks/{chunk-YVDBHS4C.js.map → chunk-WREA4RNR.js.map} +0 -0
  561. /package/dist/chunks/{chunk-NGGI6LDC.js.map → chunk-X2TRSE7D.js.map} +0 -0
  562. /package/dist/chunks/{chunk-A4VP7HDF.js.map → chunk-ZLNJDTCN.js.map} +0 -0
@@ -13,13 +13,54 @@ import {
13
13
  componentEntries,
14
14
  validateComponentConfig,
15
15
  watchComponentConfiguration
16
- } from "./chunks/chunk-EPYLZWJV.js";
16
+ } from "./chunks/chunk-OVBKQCYL.js";
17
+ import {
18
+ MAX_PROGRAM_CODE_CHARS,
19
+ MAX_PROGRAM_DESCRIPTION_CHARS,
20
+ MAX_PROGRAM_NAME_CHARS,
21
+ MAX_PROGRAM_REF_CHARS,
22
+ ProgramStore,
23
+ normalizeProgramInput,
24
+ programInputError,
25
+ programRef,
26
+ programSourceWithInput,
27
+ programsDirectory
28
+ } from "./chunks/chunk-U366I5K2.js";
17
29
  import {
18
30
  WorkerMemoryProvider
19
- } from "./chunks/chunk-4TKPBEPB.js";
31
+ } from "./chunks/chunk-BVJBYFHD.js";
20
32
  import {
21
- ResidentActorClient
22
- } from "./chunks/chunk-NHMICIEU.js";
33
+ MESH_GRANT_MAX_TTL_MS,
34
+ MESH_GRANT_MAX_USES,
35
+ MESH_GRANT_MIN_TTL_MS,
36
+ createMeshGrant,
37
+ listMeshGrants,
38
+ meshCliArgv,
39
+ meshPostCommand,
40
+ revokeMeshGrant,
41
+ wrapDurableNotifyScript
42
+ } from "./chunks/chunk-7XRUMDV7.js";
43
+ import {
44
+ DecisionStore,
45
+ MAX_DECISION_BODY_CHARS,
46
+ MAX_DECISION_DEADLINE_MS,
47
+ MAX_DECISION_OPTIONS,
48
+ MAX_DECISION_TEXT_CHARS,
49
+ MAX_DECISION_TITLE_CHARS,
50
+ MAX_ESCALATION_HOPS,
51
+ MAX_ESCALATION_HOP_MS,
52
+ MAX_ESCALATION_REASON_CHARS,
53
+ MIN_ESCALATION_HOP_MS,
54
+ assertDecisionId
55
+ } from "./chunks/chunk-FSB2VIRZ.js";
56
+ import {
57
+ FabricThinkingController,
58
+ MAX_THINKING_OVERRIDE_TURNS,
59
+ MAX_THINKING_REASON_CHARS
60
+ } from "./chunks/chunk-L22K5BWU.js";
61
+ import {
62
+ ownerFromContext
63
+ } from "./chunks/chunk-S3IRPDSO.js";
23
64
  import {
24
65
  ActionRegistry,
25
66
  FabricComponentIndependenceError,
@@ -32,10 +73,70 @@ import {
32
73
  scoreActionSearch,
33
74
  summarizeEffects,
34
75
  trackedRegistration
35
- } from "./chunks/chunk-WMJ2AVQQ.js";
76
+ } from "./chunks/chunk-R5F6CHW2.js";
36
77
  import {
37
78
  formatFabricEffectConflict
38
79
  } from "./chunks/chunk-LMAVZN7J.js";
80
+ import {
81
+ FabricAssessmentRecorder,
82
+ readFabricAssessmentUsage
83
+ } from "./chunks/chunk-WOLUDZVR.js";
84
+ import {
85
+ ActorDirectory,
86
+ ActorRegistryOwnershipError,
87
+ AgentManager,
88
+ FabricControlPlane,
89
+ LifecycleBroker,
90
+ ParticipantDirectory,
91
+ actorDeliveryNotice,
92
+ actorParticipantRecord,
93
+ addCloneFirstWorktree,
94
+ agentParticipantRecords,
95
+ buildThinkingDigest,
96
+ checkedHandoffCompaction,
97
+ effectiveAgentTimeoutMs,
98
+ isFabricWorktreePath,
99
+ loadModelUsage,
100
+ readAgentLineage,
101
+ resolveActorDeliveryPolicy,
102
+ resolveAgentCwd,
103
+ resolveInheritedSessionPins,
104
+ resolvePiBinary,
105
+ snapshotHandoffSession,
106
+ thinkingTransferPolicy,
107
+ withInheritedSessionPins
108
+ } from "./chunks/chunk-KQ6R5EWR.js";
109
+ import {
110
+ executeFile,
111
+ processIsAlive,
112
+ spawnDetached
113
+ } from "./chunks/chunk-SVDHQUTM.js";
114
+ import "./chunks/chunk-2USMWEE6.js";
115
+ import "./chunks/chunk-PM5I335G.js";
116
+ import "./chunks/chunk-VPPIJRNZ.js";
117
+ import {
118
+ MESH_MAX_PENDING_SCHEDULES,
119
+ MESH_MAX_SCHEDULE_AHEAD_MS,
120
+ MeshStore
121
+ } from "./chunks/chunk-3GJJG2FV.js";
122
+ import {
123
+ childScope,
124
+ sessionScope
125
+ } from "./chunks/chunk-JKQARSWR.js";
126
+ import {
127
+ ResidentActorClient
128
+ } from "./chunks/chunk-CCHZXF6K.js";
129
+ import {
130
+ RESIDENT_HOST_FORMAT,
131
+ abandonResidentRequest,
132
+ residentDeliveryPrefix,
133
+ residentHostId,
134
+ residentRoot,
135
+ sleepUnlessAborted
136
+ } from "./chunks/chunk-NTC2MCB6.js";
137
+ import {
138
+ loadCompiledSurface
139
+ } from "./chunks/chunk-YYSZBD7S.js";
39
140
  import {
40
141
  FABRIC_COMPONENT_PROVIDER_NAMES,
41
142
  FABRIC_PROVIDER_COMPONENT_PREFIX,
@@ -45,82 +146,31 @@ import {
45
146
  PREWALK_CONTINUE_MESSAGE_TYPE,
46
147
  PrewalkController,
47
148
  PrewalkDriftTracker,
149
+ WORKFLOW_ITEM_ID_MAX_CHARS,
48
150
  builtinModelGuidance,
49
151
  captureLoadedFileIdentity,
50
152
  createProviderComponent,
51
153
  deliverPrewalkPlanCheckpoint,
52
154
  expandSkillDirMarkersForRead,
53
155
  isSelectedNativeMcpTool,
156
+ isWorkflowItemId,
54
157
  nativeMcpIdentity,
55
158
  queueHandoffCompletion,
56
159
  resolveFabricIdentity,
57
160
  runtimeIdentityStatus,
58
161
  setModelSafely
59
- } from "./chunks/chunk-B5D6GA77.js";
162
+ } from "./chunks/chunk-GYPDGW27.js";
60
163
  import {
61
164
  AgentTranscriptReader,
62
165
  MAX_WRITE_DIFF_BYTES,
63
166
  countContentLines,
64
167
  recentTranscriptTools,
65
168
  writeContentForPreview
66
- } from "./chunks/chunk-J2HV2URQ.js";
169
+ } from "./chunks/chunk-7EYJE4TW.js";
67
170
  import "./chunks/chunk-DLXPTBPL.js";
68
171
  import {
69
- loadCompiledSurface,
70
172
  withExclusiveFileLockAsync
71
- } from "./chunks/chunk-CC63CY6R.js";
72
- import {
73
- createConfiguredMemorySourceRegistry
74
- } from "./chunks/chunk-5JN5AWNV.js";
75
- import "./chunks/chunk-QETG2GVX.js";
76
- import "./chunks/chunk-7XJB2USB.js";
77
- import "./chunks/chunk-57CMH4SW.js";
78
- import "./chunks/chunk-64O5L7EW.js";
79
- import "./chunks/chunk-YVDBHS4C.js";
80
- import {
81
- McpProvider,
82
- mcpToolDescriptor,
83
- normalizeMcpResult
84
- } from "./chunks/chunk-SGFH5PYA.js";
85
- import {
86
- McpDescriptorCacheStore,
87
- mcpDescriptorCachePath
88
- } from "./chunks/chunk-Z64PRP7A.js";
89
- import {
90
- sanitizeMcpRefPart
91
- } from "./chunks/chunk-IGVDD2HT.js";
92
- import {
93
- AGENTS_ACTION_DESCRIPTORS,
94
- normalizeAgentRunRequest
95
- } from "./chunks/chunk-PNDYFU64.js";
96
- import {
97
- actionArgNormalizer,
98
- uniqueDeclaredKeyForSpelling
99
- } from "./chunks/chunk-NQOEHX62.js";
100
- import {
101
- prepareFabricActorHostPayload,
102
- sanitizeFabricMediaText,
103
- sanitizeFabricMediaValue
104
- } from "./chunks/chunk-CGL7QP4A.js";
105
- import {
106
- validationMessage
107
- } from "./chunks/chunk-KP4ANT6L.js";
108
- import {
109
- runAbortable,
110
- throwIfAborted
111
- } from "./chunks/chunk-7TB7NXSL.js";
112
- import {
113
- ApprovalController,
114
- FabricAutoApprovalClassifier,
115
- FabricSessionApprovals
116
- } from "./chunks/chunk-QE2JFB7F.js";
117
- import "./chunks/chunk-XB3RJVT4.js";
118
- import {
119
- clearActiveCompiledSurface,
120
- clearActiveRepairCompiler,
121
- setActiveCompiledSurface,
122
- setActiveRepairCompiler
123
- } from "./chunks/chunk-DKVJREDI.js";
173
+ } from "./chunks/chunk-DK35W6U7.js";
124
174
  import {
125
175
  FABRIC_BASH_MIDDLEWARE,
126
176
  FABRIC_COMPONENT_DISCOVER_EVENT,
@@ -128,104 +178,149 @@ import {
128
178
  FABRIC_PROVIDER_DISCOVER_EVENT,
129
179
  FABRIC_SHELL_TIMING_EVENT,
130
180
  FABRIC_TOOL_RESULT_PROXY_KIND,
181
+ FABRIC_WORKFLOW_ITEM_EVENT,
131
182
  readFabricToolResultProxyDetailsV1
132
- } from "./chunks/chunk-VRAGOMN4.js";
133
- import {
134
- ActorDirectory,
135
- ActorRegistryOwnershipError,
136
- AgentManager,
137
- FabricControlPlane,
138
- LifecycleBroker,
139
- MeshStore,
140
- ParticipantDirectory,
141
- actorDeliveryNotice,
142
- actorParticipantRecord,
143
- addCloneFirstWorktree,
144
- agentParticipantRecords,
145
- buildThinkingDigest,
146
- checkedHandoffCompaction,
147
- effectiveAgentTimeoutMs,
148
- isFabricWorktreePath,
149
- loadModelUsage,
150
- readChildToolAllowlist,
151
- resolveActorDeliveryPolicy,
152
- resolveAgentCwd,
153
- resolveInheritedSessionPins,
154
- resolvePiBinary,
155
- snapshotHandoffSession,
156
- thinkingTransferPolicy,
157
- withInheritedSessionPins
158
- } from "./chunks/chunk-74BA4VSX.js";
183
+ } from "./chunks/chunk-YRDCJZZW.js";
159
184
  import {
160
- executeFile,
161
- processIsAlive,
162
- spawnDetached
163
- } from "./chunks/chunk-7BG5COXB.js";
164
- import "./chunks/chunk-VPPIJRNZ.js";
165
- import "./chunks/chunk-PM5I335G.js";
166
- import {
167
- RESIDENT_HOST_FORMAT,
168
- abandonResidentRequest,
169
- residentDeliveryPrefix,
170
- residentHostId,
171
- residentRoot,
172
- sleepUnlessAborted
173
- } from "./chunks/chunk-TX6E5W7H.js";
174
- import "./chunks/chunk-YV2PHCDB.js";
185
+ readChildToolAllowlist
186
+ } from "./chunks/chunk-PYFJW3HC.js";
175
187
  import {
176
188
  resolveAgentDir
177
189
  } from "./chunks/chunk-PXAICAUT.js";
178
190
  import {
179
191
  closeScratch,
180
192
  createScratch
181
- } from "./chunks/chunk-RAO6TQFP.js";
182
- import {
183
- readJsonlPage
184
- } from "./chunks/chunk-CGPK5WHX.js";
193
+ } from "./chunks/chunk-5XBYFSI5.js";
185
194
  import {
186
195
  DEFAULT_FABRIC_CONFIG,
187
196
  DEFAULT_SHELL_HANG_MS,
188
197
  MAX_AGENT_TIMEOUT_MS,
189
198
  MIN_AGENT_TIMEOUT_MS,
190
199
  loadFabricConfig
191
- } from "./chunks/chunk-PN4EKNRE.js";
200
+ } from "./chunks/chunk-VON4TSO3.js";
192
201
  import "./chunks/chunk-OKOHRXGF.js";
193
202
  import {
194
- fabricExecTitleHintCached
195
- } from "./chunks/chunk-HG4DMARW.js";
203
+ readJsonlPage
204
+ } from "./chunks/chunk-CGPK5WHX.js";
205
+ import {
206
+ COMPACTION_CARRY_ENTRY_TYPE,
207
+ MAX_CARRY_ITEMS,
208
+ MAX_CARRY_ITEM_CHARS,
209
+ applyCarryUpdate,
210
+ fabricExecTitleHintCached,
211
+ isCarryUpdate,
212
+ latestCarryItems,
213
+ modelCompactionKey,
214
+ outputReserveBreached,
215
+ sameCarryItems
216
+ } from "./chunks/chunk-T5CU2GPZ.js";
196
217
  import "./chunks/chunk-SZUXWOO7.js";
197
218
  import {
219
+ MAX_FABRIC_MODEL_GUIDANCE_PER_COMPONENT,
220
+ MAX_FABRIC_MODEL_GUIDANCE_REGISTRATIONS,
221
+ MAX_FABRIC_MODEL_GUIDANCE_SNAPSHOT_CHARS,
222
+ MAX_FABRIC_MODEL_GUIDANCE_TOTAL_CHARS,
223
+ compareFabricOwnedModelGuidance,
224
+ fabricModelGuidanceInfo,
225
+ normalizeFabricModelGuidance,
226
+ resolveFabricModelGuidance
227
+ } from "./chunks/chunk-UKMQK5VP.js";
228
+ import {
229
+ ownerHeartbeatFields,
230
+ recordOwnerLiveness,
231
+ startOwnerHeartbeat,
232
+ writeFileAtomic,
198
233
  writeJsonAtomic,
199
234
  writeJsonAtomicAsync
200
- } from "./chunks/chunk-KAD7UWT2.js";
201
- import "./chunks/chunk-NGGI6LDC.js";
235
+ } from "./chunks/chunk-ITVLKXCI.js";
236
+ import {
237
+ createConfiguredMemorySourceRegistry
238
+ } from "./chunks/chunk-DZ4WN5XJ.js";
239
+ import "./chunks/chunk-M5IN6DMF.js";
240
+ import "./chunks/chunk-LOLCTWJF.js";
241
+ import "./chunks/chunk-7JU7Z4XQ.js";
242
+ import "./chunks/chunk-M6IRQ3QT.js";
243
+ import "./chunks/chunk-WREA4RNR.js";
244
+ import "./chunks/chunk-X2TRSE7D.js";
245
+ import {
246
+ McpProvider,
247
+ mcpToolDescriptor,
248
+ normalizeMcpResult
249
+ } from "./chunks/chunk-SGFH5PYA.js";
250
+ import {
251
+ McpDescriptorCacheStore,
252
+ mcpDescriptorCachePath
253
+ } from "./chunks/chunk-Z64PRP7A.js";
254
+ import {
255
+ sanitizeMcpRefPart
256
+ } from "./chunks/chunk-IGVDD2HT.js";
257
+ import {
258
+ AGENTS_ACTION_DESCRIPTORS,
259
+ normalizeAgentRunRequest
260
+ } from "./chunks/chunk-GJVPP3NN.js";
202
261
  import {
203
262
  FABRIC_PARTICIPANT_LIFECYCLE_TOPIC,
204
263
  isFabricLifecycleEventType,
205
264
  lifecycleSourceIdentity,
206
265
  terminalAgentStatuses
207
- } from "./chunks/chunk-AYBIR4YV.js";
266
+ } from "./chunks/chunk-KJZAOENY.js";
208
267
  import {
209
268
  FABRIC_ACTOR_HOST_EVENTS,
210
269
  isFabricActorHostEvent
211
- } from "./chunks/chunk-PWS2OXLV.js";
270
+ } from "./chunks/chunk-IIPKG52D.js";
212
271
  import {
213
272
  FUZZY_RESOLUTION_MARKERS,
214
273
  aliasThinking,
215
274
  resolveAvailablePiModel,
216
275
  resolveFabricModel
217
- } from "./chunks/chunk-A4VP7HDF.js";
276
+ } from "./chunks/chunk-ZLNJDTCN.js";
218
277
  import {
278
+ THINKING_LEVELS,
219
279
  isFabricThinking
220
- } from "./chunks/chunk-MGWQOKBV.js";
280
+ } from "./chunks/chunk-V73NIH6B.js";
221
281
  import {
222
282
  MAX_COMPACTION_INSTRUCTIONS_CHARS,
223
283
  MAX_PRESERVE_ITEMS,
224
284
  MAX_PRESERVE_ITEM_CHARS,
225
285
  compactionRequestBoundsError,
226
286
  encodeCompactionRequest
227
- } from "./chunks/chunk-Z5Y65YBX.js";
228
- import "./chunks/chunk-LEFBW2GK.js";
287
+ } from "./chunks/chunk-PYQM7KPL.js";
288
+ import {
289
+ actionArgNormalizer,
290
+ uniqueDeclaredKeyForSpelling
291
+ } from "./chunks/chunk-NQOEHX62.js";
292
+ import {
293
+ BUILT_IN_RUNNER_IDS,
294
+ isFabricRunnerId,
295
+ requireAgentRunner
296
+ } from "./chunks/chunk-4RTHQGES.js";
297
+ import {
298
+ prepareFabricActorHostPayload,
299
+ sanitizeFabricMediaText,
300
+ sanitizeFabricMediaValue
301
+ } from "./chunks/chunk-CGL7QP4A.js";
302
+ import {
303
+ validationMessage
304
+ } from "./chunks/chunk-C7EEG6SM.js";
305
+ import {
306
+ runAbortable,
307
+ throwIfAborted
308
+ } from "./chunks/chunk-7TB7NXSL.js";
309
+ import {
310
+ ApprovalController,
311
+ FabricAutoApprovalClassifier,
312
+ FabricSessionApprovals
313
+ } from "./chunks/chunk-WYUV6WL3.js";
314
+ import "./chunks/chunk-XB3RJVT4.js";
315
+ import {
316
+ clearActiveCompiledSurface,
317
+ clearActiveRepairCompiler,
318
+ setActiveCompiledSurface,
319
+ setActiveRepairCompiler
320
+ } from "./chunks/chunk-QY7YK7M6.js";
321
+ import {
322
+ actionApprovalOverride
323
+ } from "./chunks/chunk-IAFI4A2I.js";
229
324
  import {
230
325
  resolveJevModelRoute
231
326
  } from "./chunks/chunk-B54Z662X.js";
@@ -233,14 +328,17 @@ import {
233
328
  FabricExecutionTraceRecorder,
234
329
  FabricTraceSafeError,
235
330
  executionOutcomeFromError
236
- } from "./chunks/chunk-G4CSXNBT.js";
331
+ } from "./chunks/chunk-ZXKYU6CH.js";
237
332
  import {
238
333
  PI_CORE_TOOL_NAMES,
239
334
  PI_CORE_TOOL_NAME_SET,
240
335
  isPiShellRef,
241
336
  isPiShellToolName
242
337
  } from "./chunks/chunk-YU62DDKK.js";
243
- import "./chunks/chunk-DUJ46TIP.js";
338
+ import "./chunks/chunk-ABJCSNZO.js";
339
+ import {
340
+ stableJsonHash
341
+ } from "./chunks/chunk-3YZUQESG.js";
244
342
  import {
245
343
  $t,
246
344
  De,
@@ -248,20 +346,7 @@ import {
248
346
  assertCertificateFacts,
249
347
  boundedEffectResources,
250
348
  gt
251
- } from "./chunks/chunk-HOX6VW45.js";
252
- import {
253
- MAX_FABRIC_MODEL_GUIDANCE_PER_COMPONENT,
254
- MAX_FABRIC_MODEL_GUIDANCE_REGISTRATIONS,
255
- MAX_FABRIC_MODEL_GUIDANCE_SNAPSHOT_CHARS,
256
- MAX_FABRIC_MODEL_GUIDANCE_TOTAL_CHARS,
257
- compareFabricOwnedModelGuidance,
258
- fabricModelGuidanceInfo,
259
- normalizeFabricModelGuidance,
260
- resolveFabricModelGuidance
261
- } from "./chunks/chunk-UKMQK5VP.js";
262
- import {
263
- stableJsonHash
264
- } from "./chunks/chunk-3YZUQESG.js";
349
+ } from "./chunks/chunk-CYMDX3XP.js";
265
350
 
266
351
  // src/fabric-runtime-state.ts
267
352
  import path16 from "node:path";
@@ -3468,6 +3553,7 @@ var checkedPreserve = (value) => {
3468
3553
  var CompactController = class {
3469
3554
  #pending;
3470
3555
  #last;
3556
+ #lastAuto;
3471
3557
  #inFlight;
3472
3558
  #hooks;
3473
3559
  constructor(hooks = {}) {
@@ -3500,10 +3586,15 @@ var CompactController = class {
3500
3586
  cancel() {
3501
3587
  this.#pending = void 0;
3502
3588
  }
3589
+ // Recorded by the host after a threshold or headroom compaction attempt.
3590
+ noteAutoCompaction(trigger, committed) {
3591
+ this.#lastAuto = { at: Date.now(), trigger, committed };
3592
+ }
3503
3593
  status() {
3504
3594
  return {
3505
3595
  ...this.#pending ? { pending: this.#pending } : {},
3506
- ...this.#last ? { last: this.#last } : {}
3596
+ ...this.#last ? { last: this.#last } : {},
3597
+ ...this.#lastAuto ? { lastAuto: this.#lastAuto } : {}
3507
3598
  };
3508
3599
  }
3509
3600
  // Commit the pending intent at a safe boundary. Called and awaited from the
@@ -3651,6 +3742,109 @@ var FabricToolResultProxy = class {
3651
3742
  }
3652
3743
  };
3653
3744
 
3745
+ // src/activity/workflow-items.ts
3746
+ var WORKFLOW_ITEM_META_MAX_BYTES = 2 * 1024;
3747
+ var MAX_META_DEPTH = 8;
3748
+ var MAX_LABEL_CHARS = 120;
3749
+ var statuses = /* @__PURE__ */ new Set([
3750
+ "pending",
3751
+ "running",
3752
+ "completed",
3753
+ "failed",
3754
+ "blocked",
3755
+ "stopped"
3756
+ ]);
3757
+ var legacyItemId = (value) => {
3758
+ if (typeof value !== "string") return void 0;
3759
+ const safe = value.trim().slice(0, WORKFLOW_ITEM_ID_MAX_CHARS).replace(/[^a-zA-Z0-9._:-]+/g, "-").replace(/^-+|-+$/g, "");
3760
+ return safe || void 0;
3761
+ };
3762
+ var isPlainData = (value, depth) => {
3763
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
3764
+ if (typeof value === "number") return Number.isFinite(value);
3765
+ if (typeof value !== "object" || depth >= MAX_META_DEPTH) return false;
3766
+ if (Array.isArray(value)) return value.every((entry) => isPlainData(entry, depth + 1));
3767
+ const prototype = Object.getPrototypeOf(value);
3768
+ if (prototype !== Object.prototype && prototype !== null) return false;
3769
+ return Object.values(value).every((entry) => isPlainData(entry, depth + 1));
3770
+ };
3771
+ var validateWorkflowItemInput = (args, defaultId) => {
3772
+ const id2 = isWorkflowItemId(args.id) ? args.id : legacyItemId(args.id) ?? defaultId();
3773
+ const status = args.status ?? "running";
3774
+ if (!statuses.has(status)) {
3775
+ throw new Error(`workflow.item status must be one of ${[...statuses].join(", ")}`);
3776
+ }
3777
+ if (args.meta === void 0) return { id: id2, status };
3778
+ const meta = args.meta;
3779
+ if (typeof meta !== "object" || meta === null || Array.isArray(meta) || !isPlainData(meta, 0)) {
3780
+ throw new Error("workflow.item meta must be a plain JSON object");
3781
+ }
3782
+ const serialized = JSON.stringify(meta);
3783
+ if (Buffer.byteLength(serialized, "utf8") > WORKFLOW_ITEM_META_MAX_BYTES) {
3784
+ throw new Error(
3785
+ `workflow.item meta must serialize to at most ${WORKFLOW_ITEM_META_MAX_BYTES} bytes`
3786
+ );
3787
+ }
3788
+ return {
3789
+ id: id2,
3790
+ status,
3791
+ meta: JSON.parse(serialized)
3792
+ };
3793
+ };
3794
+ var FabricWorkflowItemTransitions = class {
3795
+ constructor(invocationId, emit, sessionId) {
3796
+ this.invocationId = invocationId;
3797
+ this.emit = emit;
3798
+ this.sessionId = sessionId;
3799
+ }
3800
+ #statuses = /* @__PURE__ */ new Map();
3801
+ #labels = /* @__PURE__ */ new Map();
3802
+ /** Matches the activity store's historical `item-<n>` fallback. */
3803
+ nextDefaultId() {
3804
+ return `item-${this.#statuses.size + 1}`;
3805
+ }
3806
+ record(input, label) {
3807
+ const from = this.#statuses.get(input.id);
3808
+ this.#statuses.set(input.id, input.status);
3809
+ if (typeof label === "string" && label.trim()) {
3810
+ this.#labels.set(input.id, label.trim().slice(0, MAX_LABEL_CHARS));
3811
+ }
3812
+ if (from === input.status) return;
3813
+ this.#send(input.id, from, input.status, input.meta);
3814
+ }
3815
+ /** Mirrors the activity store: only running items settle with the run. */
3816
+ finish(success) {
3817
+ const to = success ? "completed" : "failed";
3818
+ for (const [id2, status] of this.#statuses) {
3819
+ if (status !== "running") continue;
3820
+ this.#statuses.set(id2, to);
3821
+ this.#send(id2, status, to);
3822
+ }
3823
+ }
3824
+ #send(itemId, from, to, meta) {
3825
+ if (!this.emit) return;
3826
+ const label = this.#labels.get(itemId);
3827
+ const event = {
3828
+ version: 1,
3829
+ invocationId: this.invocationId,
3830
+ ...this.sessionId ? { sessionId: this.sessionId } : {},
3831
+ itemId,
3832
+ ...label ? { label } : {},
3833
+ ...from ? { from } : {},
3834
+ to,
3835
+ at: Date.now(),
3836
+ ...meta ? { meta } : {}
3837
+ };
3838
+ try {
3839
+ this.emit(FABRIC_WORKFLOW_ITEM_EVENT, event);
3840
+ } catch (error) {
3841
+ console.warn(
3842
+ `[pi-fabric] workflow item event listener failed: ${error instanceof Error ? error.message : String(error)}`
3843
+ );
3844
+ }
3845
+ }
3846
+ };
3847
+
3654
3848
  // src/runtime/python-error-guidance.ts
3655
3849
  function pythonErrorRecoveryHint(code, error, backend) {
3656
3850
  const text = error.slice(0, 8e3) + "\n" + error.slice(-8e3);
@@ -3906,45 +4100,401 @@ var BLOCKING_ORCHESTRATION_REFS = /* @__PURE__ */ new Set([
3906
4100
  "agents.ask",
3907
4101
  "jev.run",
3908
4102
  "jev.wait",
3909
- "jev.join"
4103
+ "jev.join",
4104
+ "programs.run"
3910
4105
  ]);
3911
4106
  var isBlockingOrchestrationRef = (ref) => BLOCKING_ORCHESTRATION_REFS.has(ref);
3912
- var ORCHESTRATION_RE = /\b(?:workflow\.agent|agents\.(?:run|wait|join|ask)|jev\.(?:run|wait|join)|council\.run|rlm\.query)\s*(?:<[^<>]*>)?\s*\(|(?<!\.)\bagent\s*(?:<[^<>]*>)?\s*\(/;
4107
+ var ORCHESTRATION_RE = /\b(?:workflow\.agent|agents\.(?:run|wait|join|ask)|jev\.(?:run|wait|join)|programs\.run|council\.run|rlm\.query)\s*(?:<[^<>]*>)?\s*\(|(?<!\.)\bagent\s*(?:<[^<>]*>)?\s*\(/;
3913
4108
  var codeUsesOrchestration = (code) => ORCHESTRATION_RE.test(code);
3914
4109
 
3915
- // src/execution-service.ts
3916
- var executionOutcomeFromTermination = (reason) => {
3917
- switch (reason) {
3918
- case "completed":
3919
- return "succeeded";
3920
- case "aborted":
3921
- return "aborted";
3922
- case "timed_out":
3923
- return "timed_out";
3924
- case "runtime_error":
3925
- return "failed";
3926
- }
4110
+ // src/topology/provider-participants.ts
4111
+ import { randomUUID as randomUUID3 } from "node:crypto";
4112
+ var PROVIDER_PARTICIPANT_PREFIX = "provider:";
4113
+ var PROGRAM_CANCELLED_REASON = "program_cancelled";
4114
+ var OWNED_WORK_STOP_TIMEOUT_MS = 5e3;
4115
+ var ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/;
4116
+ var KIND_PATTERN = /^[a-z][a-z0-9._-]{0,31}$/;
4117
+ var MAX_LABEL_CHARS2 = 120;
4118
+ var MAX_PHASE_CHARS = 64;
4119
+ var MAX_MESSAGE_CHARS = 500;
4120
+ var MAX_SUMMARY_CHARS = 2e3;
4121
+ var MAX_CONTROL_MESSAGE_CHARS = 2e4;
4122
+ var MAX_ACTIVE = 256;
4123
+ var MAX_SETTLED = 64;
4124
+ var SETTLED_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "stopped"]);
4125
+ var isProviderParticipantRef = (value) => value.startsWith(PROVIDER_PARTICIPANT_PREFIX);
4126
+ var boundedText = (value, field, max, required = false) => {
4127
+ if (value === void 0 && !required) return void 0;
4128
+ if (typeof value !== "string") throw new TypeError(`Fabric participant ${field} must be a string`);
4129
+ const text = value.trim();
4130
+ if (required && !text) throw new TypeError(`Fabric participant ${field} must not be empty`);
4131
+ if (text.length > max) throw new RangeError(`Fabric participant ${field} exceeds ${max} characters`);
4132
+ return text || void 0;
3927
4133
  };
3928
- var aggregateUsage = (usages) => ({
3929
- input: usages.reduce((total, usage) => total + usage.input, 0),
3930
- output: usages.reduce((total, usage) => total + usage.output, 0),
3931
- cacheRead: usages.reduce((total, usage) => total + usage.cacheRead, 0),
3932
- cacheWrite: usages.reduce((total, usage) => total + usage.cacheWrite, 0),
3933
- ...usages.some((usage) => usage.cacheWrite1h !== void 0) ? { cacheWrite1h: usages.reduce((total, usage) => total + (usage.cacheWrite1h ?? 0), 0) } : {},
3934
- ...usages.some((usage) => usage.reasoning !== void 0) ? { reasoning: usages.reduce((total, usage) => total + (usage.reasoning ?? 0), 0) } : {},
3935
- totalTokens: usages.reduce((total, usage) => total + usage.totalTokens, 0),
3936
- cost: {
3937
- input: usages.reduce((total, usage) => total + usage.cost.input, 0),
3938
- output: usages.reduce((total, usage) => total + usage.cost.output, 0),
3939
- cacheRead: usages.reduce((total, usage) => total + usage.cost.cacheRead, 0),
3940
- cacheWrite: usages.reduce((total, usage) => total + usage.cost.cacheWrite, 0),
3941
- total: usages.reduce((total, usage) => total + usage.cost.total, 0)
4134
+ var usageFrom = (value) => {
4135
+ if (value === void 0) return void 0;
4136
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
4137
+ throw new TypeError("Fabric participant usage must be an object");
3942
4138
  }
3943
- });
3944
- var FabricExecutionService = class {
3945
- constructor(registry, config, activity, authorizer, autoApprovalClassifier = new FabricAutoApprovalClassifier(() => config.jev), sessionApprovals = new FabricSessionApprovals(), capturedTools, brokeredNetwork) {
3946
- this.registry = registry;
3947
- this.config = config;
4139
+ const record = value;
4140
+ const usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
4141
+ for (const key of Object.keys(record)) {
4142
+ if (!(key in usage)) throw new TypeError(`Unknown Fabric participant usage field: ${key}`);
4143
+ const amount = record[key];
4144
+ if (amount === void 0) continue;
4145
+ if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0) {
4146
+ throw new RangeError(`Fabric participant usage.${key} must be a non-negative finite number`);
4147
+ }
4148
+ usage[key] = amount;
4149
+ }
4150
+ return usage;
4151
+ };
4152
+ var capabilitiesOf = (entry) => entry.status !== "running" ? [] : [
4153
+ ...entry.spec.steer ? ["steer"] : [],
4154
+ ...entry.spec.followUp ? ["followUp"] : [],
4155
+ "stop"
4156
+ ];
4157
+ var activityOf = (entry) => {
4158
+ const text = entry.status === "running" ? entry.phase && entry.message ? `${entry.phase}: ${entry.message}` : entry.phase ?? entry.message : entry.summary;
4159
+ return text ? text.slice(0, 160) : void 0;
4160
+ };
4161
+ var ProviderParticipantRegistry = class {
4162
+ #entries = /* @__PURE__ */ new Map();
4163
+ #listeners = /* @__PURE__ */ new Set();
4164
+ /** Per-invocation, provider-bound registration view handed to `invoke`. */
4165
+ view(provider, invocationId) {
4166
+ return Object.freeze({
4167
+ register: (spec) => this.#register(provider, invocationId, spec)
4168
+ });
4169
+ }
4170
+ subscribe(listener) {
4171
+ this.#listeners.add(listener);
4172
+ return () => this.#listeners.delete(listener);
4173
+ }
4174
+ has(ref) {
4175
+ return this.#entries.has(ref);
4176
+ }
4177
+ get(ref) {
4178
+ const entry = this.#entries.get(ref);
4179
+ return entry ? this.#info(entry) : void 0;
4180
+ }
4181
+ list() {
4182
+ return [...this.#entries.values()].map((entry) => this.#info(entry));
4183
+ }
4184
+ /** Directory records; the directory stamps owner host and identity on publish. */
4185
+ records(rootId, ownerHostId, ownerIdentityId) {
4186
+ return [...this.#entries.values()].map((entry) => {
4187
+ const activity = activityOf(entry);
4188
+ return {
4189
+ format: 1,
4190
+ id: entry.ref,
4191
+ kind: "provider",
4192
+ rootId,
4193
+ ownerHostId,
4194
+ ownerIdentityId,
4195
+ parentId: rootId,
4196
+ name: entry.label,
4197
+ status: entry.status,
4198
+ residency: "session",
4199
+ provider: entry.provider,
4200
+ transport: "host",
4201
+ capabilities: capabilitiesOf(entry),
4202
+ startedAt: entry.startedAt,
4203
+ updatedAt: entry.updatedAt,
4204
+ ...entry.finishedAt !== void 0 ? { finishedAt: entry.finishedAt } : {},
4205
+ ...activity ? { currentTool: activity } : {},
4206
+ ...entry.usage ? { usage: { ...entry.usage } } : {},
4207
+ controlProtocol: "v1"
4208
+ };
4209
+ });
4210
+ }
4211
+ async stop(ref, reason = "stopped") {
4212
+ const entry = this.#require(ref);
4213
+ if (entry.status !== "running") throw new Error(`Fabric participant ${ref} is already ${entry.status}`);
4214
+ return this.#stop(entry, reason, void 0);
4215
+ }
4216
+ async deliver(ref, operation, message2) {
4217
+ const entry = this.#require(ref);
4218
+ if (entry.status !== "running") throw new Error(`Fabric participant ${ref} is already ${entry.status}`);
4219
+ const deliver = entry.spec[operation];
4220
+ if (!deliver) throw new Error(`Fabric participant ${ref} does not support ${operation}`);
4221
+ const text = boundedText(message2, "message", MAX_CONTROL_MESSAGE_CHARS, true);
4222
+ await deliver.call(entry.spec, text);
4223
+ }
4224
+ /**
4225
+ * Stop every unsettled, non-detached participant registered during the
4226
+ * invocation, in parallel, within one shared deadline.
4227
+ */
4228
+ async cancelInvocation(invocationId, reason = PROGRAM_CANCELLED_REASON, timeoutMs = OWNED_WORK_STOP_TIMEOUT_MS) {
4229
+ const owned = [...this.#entries.values()].filter(
4230
+ (entry) => entry.invocationId === invocationId && !entry.detached && entry.status === "running"
4231
+ );
4232
+ if (owned.length === 0) return [];
4233
+ let timer;
4234
+ const deadline = new Promise((resolve2) => {
4235
+ timer = setTimeout(() => resolve2("timeout"), Math.max(0, timeoutMs));
4236
+ timer.unref?.();
4237
+ });
4238
+ try {
4239
+ return await Promise.all(owned.map((entry) => this.#stop(entry, reason, deadline)));
4240
+ } finally {
4241
+ if (timer) clearTimeout(timer);
4242
+ }
4243
+ }
4244
+ /** Forget a withdrawn provider's participants; their handles become inert. */
4245
+ releaseProvider(provider) {
4246
+ let released = 0;
4247
+ for (const [ref, entry] of this.#entries) {
4248
+ if (entry.provider !== provider) continue;
4249
+ this.#entries.delete(ref);
4250
+ released++;
4251
+ }
4252
+ if (released > 0) this.#notify();
4253
+ return released;
4254
+ }
4255
+ /** Session shutdown: forget every participant without calling providers. */
4256
+ releaseAll() {
4257
+ const had = this.#entries.size > 0;
4258
+ this.#entries.clear();
4259
+ if (had) this.#notify();
4260
+ this.#listeners.clear();
4261
+ }
4262
+ #register(provider, invocationId, spec) {
4263
+ if (typeof spec !== "object" || spec === null) throw new TypeError("Fabric participant spec must be an object");
4264
+ if (typeof spec.id !== "string" || !ID_PATTERN.test(spec.id)) {
4265
+ throw new TypeError("Fabric participant id must match [A-Za-z0-9][A-Za-z0-9._:-]{0,63}");
4266
+ }
4267
+ const label = boundedText(spec.label, "label", MAX_LABEL_CHARS2, true);
4268
+ if (spec.kind !== void 0 && (typeof spec.kind !== "string" || !KIND_PATTERN.test(spec.kind))) {
4269
+ throw new TypeError("Fabric participant kind must match [a-z][a-z0-9._-]{0,31}");
4270
+ }
4271
+ if (spec.detached !== void 0 && typeof spec.detached !== "boolean") {
4272
+ throw new TypeError("Fabric participant detached must be a boolean");
4273
+ }
4274
+ if (typeof spec.stop !== "function") throw new TypeError("Fabric participant stop must be a function");
4275
+ for (const optional of ["steer", "followUp"]) {
4276
+ if (spec[optional] !== void 0 && typeof spec[optional] !== "function") {
4277
+ throw new TypeError(`Fabric participant ${optional} must be a function`);
4278
+ }
4279
+ }
4280
+ const ref = `${PROVIDER_PARTICIPANT_PREFIX}${provider}:${spec.id}`;
4281
+ const existing = this.#entries.get(ref);
4282
+ if (existing?.status === "running") throw new Error(`Fabric participant ${ref} is already registered`);
4283
+ if (existing) this.#entries.delete(ref);
4284
+ const active = [...this.#entries.values()].filter((entry2) => entry2.status === "running").length;
4285
+ if (active >= MAX_ACTIVE) throw new Error(`Fabric participant limit reached (${MAX_ACTIVE} active)`);
4286
+ const now = Date.now();
4287
+ const entry = {
4288
+ ref,
4289
+ provider,
4290
+ id: spec.id,
4291
+ label,
4292
+ kind: spec.kind,
4293
+ detached: spec.detached === true,
4294
+ invocationId,
4295
+ // Freeze the callbacks at registration so later spec mutation cannot
4296
+ // change what a stop or steer reaches.
4297
+ spec: Object.freeze({
4298
+ id: spec.id,
4299
+ label,
4300
+ stop: spec.stop.bind(spec),
4301
+ ...spec.steer ? { steer: spec.steer.bind(spec) } : {},
4302
+ ...spec.followUp ? { followUp: spec.followUp.bind(spec) } : {}
4303
+ }),
4304
+ startedAt: now,
4305
+ status: "running",
4306
+ updatedAt: now
4307
+ };
4308
+ this.#entries.set(ref, entry);
4309
+ this.#notify();
4310
+ const live = () => this.#entries.get(ref) === entry;
4311
+ return Object.freeze({
4312
+ ref,
4313
+ update: (progress) => {
4314
+ if (!live() || entry.status !== "running") return;
4315
+ if (typeof progress !== "object" || progress === null) {
4316
+ throw new TypeError("Fabric participant progress must be an object");
4317
+ }
4318
+ const phase = boundedText(progress.phase, "phase", MAX_PHASE_CHARS);
4319
+ const message2 = boundedText(progress.message, "message", MAX_MESSAGE_CHARS);
4320
+ const usage = usageFrom(progress.usage);
4321
+ if (progress.phase !== void 0) {
4322
+ if (phase) entry.phase = phase;
4323
+ else delete entry.phase;
4324
+ }
4325
+ if (progress.message !== void 0) {
4326
+ if (message2) entry.message = message2;
4327
+ else delete entry.message;
4328
+ }
4329
+ if (usage) entry.usage = usage;
4330
+ entry.updatedAt = Date.now();
4331
+ this.#notify();
4332
+ },
4333
+ settle: (result) => {
4334
+ if (typeof result !== "object" || result === null || !SETTLED_STATUSES.has(result.status)) {
4335
+ throw new TypeError('Fabric participant settle status must be "completed", "failed", or "stopped"');
4336
+ }
4337
+ const summary = boundedText(result.summary, "summary", MAX_SUMMARY_CHARS);
4338
+ if (!live() || entry.status !== "running") return;
4339
+ this.#settle(entry, result.status, summary);
4340
+ },
4341
+ dispose: () => {
4342
+ if (!live()) return;
4343
+ this.#entries.delete(ref);
4344
+ this.#notify();
4345
+ }
4346
+ });
4347
+ }
4348
+ async #stop(entry, reason, deadline) {
4349
+ let settled;
4350
+ try {
4351
+ const request = Promise.resolve().then(() => entry.spec.stop(reason));
4352
+ settled = await (deadline ? Promise.race([request, deadline]) : request);
4353
+ } catch {
4354
+ settled = "error";
4355
+ }
4356
+ if (settled === "timeout" || settled === "error") {
4357
+ return { ref: entry.ref, outcome: "unconfirmed", detail: settled };
4358
+ }
4359
+ if (typeof settled !== "object" || settled === null || settled.confirmed !== true) {
4360
+ return { ref: entry.ref, outcome: "unconfirmed", detail: "declined" };
4361
+ }
4362
+ if (this.#entries.get(entry.ref) === entry && entry.status === "running") {
4363
+ this.#settle(entry, "stopped", void 0);
4364
+ }
4365
+ return { ref: entry.ref, outcome: "confirmed" };
4366
+ }
4367
+ #settle(entry, status, summary) {
4368
+ entry.status = status;
4369
+ if (summary) entry.summary = summary;
4370
+ entry.finishedAt = entry.updatedAt = Date.now();
4371
+ const settled = [...this.#entries.values()].filter((candidate) => candidate.status !== "running");
4372
+ for (const stale of settled.slice(0, Math.max(0, settled.length - MAX_SETTLED))) {
4373
+ this.#entries.delete(stale.ref);
4374
+ }
4375
+ this.#notify();
4376
+ }
4377
+ #require(ref) {
4378
+ const entry = this.#entries.get(ref);
4379
+ if (!entry) throw new Error(`Unknown Fabric participant: ${ref}`);
4380
+ return entry;
4381
+ }
4382
+ #info(entry) {
4383
+ return {
4384
+ ref: entry.ref,
4385
+ provider: entry.provider,
4386
+ id: entry.id,
4387
+ label: entry.label,
4388
+ ...entry.kind ? { kind: entry.kind } : {},
4389
+ detached: entry.detached,
4390
+ status: entry.status,
4391
+ startedAt: entry.startedAt,
4392
+ updatedAt: entry.updatedAt,
4393
+ ...entry.finishedAt !== void 0 ? { finishedAt: entry.finishedAt } : {},
4394
+ ...entry.phase ? { phase: entry.phase } : {},
4395
+ ...entry.message ? { message: entry.message } : {},
4396
+ ...entry.summary ? { summary: entry.summary } : {},
4397
+ ...entry.usage ? { usage: { ...entry.usage } } : {},
4398
+ capabilities: capabilitiesOf(entry)
4399
+ };
4400
+ }
4401
+ #notify() {
4402
+ for (const listener of this.#listeners) {
4403
+ try {
4404
+ listener();
4405
+ } catch {
4406
+ }
4407
+ }
4408
+ }
4409
+ };
4410
+ var controlProviderParticipant = async (registry, directory, control, ref, operation, message2, data) => {
4411
+ if (operation !== "stop" && data !== void 0) {
4412
+ throw new Error(`Fabric participant ${ref} does not accept message data`);
4413
+ }
4414
+ if (registry?.has(ref)) {
4415
+ if (operation === "stop") return registry.stop(ref);
4416
+ await registry.deliver(ref, operation, message2 ?? "");
4417
+ return { queued: true, messageId: randomUUID3(), routed: "local" };
4418
+ }
4419
+ const participant = directory.get(ref);
4420
+ if (!participant || participant.kind !== "provider" || participant.local) {
4421
+ throw new Error(`Unknown Fabric participant: ${ref}`);
4422
+ }
4423
+ if (!participant.capabilities.includes(operation)) {
4424
+ throw new Error(`Fabric participant ${ref} does not support ${operation}`);
4425
+ }
4426
+ if (!control) throw new Error("Fabric control plane is unavailable");
4427
+ return control.request(
4428
+ participant.ownerHostId,
4429
+ participant.id,
4430
+ operation,
4431
+ {
4432
+ ...operation === "stop" ? {} : { message: message2 ?? "" },
4433
+ ...participant.ownerIncarnation ? { ownerIncarnation: participant.ownerIncarnation } : {}
4434
+ },
4435
+ participant.ownerIdentityId
4436
+ );
4437
+ };
4438
+ var acceptProviderParticipantControl = async (registry, command) => {
4439
+ const ref = command.targetId;
4440
+ if (!registry?.has(ref)) return { accepted: false, error: `Owner does not control Fabric participant ${ref}` };
4441
+ try {
4442
+ if (command.operation === "stop") {
4443
+ return { accepted: true, messageId: command.commandId, result: await registry.stop(ref) };
4444
+ }
4445
+ if (command.operation === "steer" || command.operation === "followUp") {
4446
+ await registry.deliver(ref, command.operation, command.message ?? "");
4447
+ return { accepted: true, messageId: command.commandId };
4448
+ }
4449
+ return { accepted: false, error: `Fabric participant ${ref} does not support ${command.operation}` };
4450
+ } catch (error) {
4451
+ return { accepted: false, error: error instanceof Error ? error.message : String(error) };
4452
+ }
4453
+ };
4454
+
4455
+ // src/execution-service.ts
4456
+ var executionOutcomeFromTermination = (reason) => {
4457
+ switch (reason) {
4458
+ case "completed":
4459
+ return "succeeded";
4460
+ case "aborted":
4461
+ return "aborted";
4462
+ case "timed_out":
4463
+ return "timed_out";
4464
+ case "runtime_error":
4465
+ return "failed";
4466
+ }
4467
+ };
4468
+ var aggregateUsage = (usages) => ({
4469
+ input: usages.reduce((total, usage) => total + usage.input, 0),
4470
+ output: usages.reduce((total, usage) => total + usage.output, 0),
4471
+ cacheRead: usages.reduce((total, usage) => total + usage.cacheRead, 0),
4472
+ cacheWrite: usages.reduce((total, usage) => total + usage.cacheWrite, 0),
4473
+ ...usages.some((usage) => usage.cacheWrite1h !== void 0) ? { cacheWrite1h: usages.reduce((total, usage) => total + (usage.cacheWrite1h ?? 0), 0) } : {},
4474
+ ...usages.some((usage) => usage.reasoning !== void 0) ? { reasoning: usages.reduce((total, usage) => total + (usage.reasoning ?? 0), 0) } : {},
4475
+ totalTokens: usages.reduce((total, usage) => total + usage.totalTokens, 0),
4476
+ cost: {
4477
+ input: usages.reduce((total, usage) => total + usage.cost.input, 0),
4478
+ output: usages.reduce((total, usage) => total + usage.cost.output, 0),
4479
+ cacheRead: usages.reduce((total, usage) => total + usage.cost.cacheRead, 0),
4480
+ cacheWrite: usages.reduce((total, usage) => total + usage.cost.cacheWrite, 0),
4481
+ total: usages.reduce((total, usage) => total + usage.cost.total, 0)
4482
+ }
4483
+ });
4484
+ var stopOwnedWork = async (participants, invocationId, trace) => {
4485
+ const outcomes = await participants.cancelInvocation(invocationId, PROGRAM_CANCELLED_REASON);
4486
+ for (const stop of outcomes) {
4487
+ const operation = trace.issueCall("fabric.participant.stop", { ref: stop.ref, reason: PROGRAM_CANCELLED_REASON });
4488
+ if (stop.outcome === "confirmed") operation.succeed(stop);
4489
+ else operation.fail("invoke", void 0, "failed", stop);
4490
+ }
4491
+ return outcomes;
4492
+ };
4493
+ var MAX_NESTED_PROGRAM_RUNS = 16;
4494
+ var FabricExecutionService = class {
4495
+ constructor(registry, config, activity, authorizer, autoApprovalClassifier = new FabricAutoApprovalClassifier(() => config.jev), sessionApprovals = new FabricSessionApprovals(), capturedTools, brokeredNetwork) {
4496
+ this.registry = registry;
4497
+ this.config = config;
3948
4498
  this.activity = activity;
3949
4499
  this.authorizer = authorizer;
3950
4500
  this.autoApprovalClassifier = autoApprovalClassifier;
@@ -3955,12 +4505,51 @@ var FabricExecutionService = class {
3955
4505
  #runtime;
3956
4506
  #runtimeKind;
3957
4507
  #capabilityView;
4508
+ #emitEvent;
4509
+ #headlessApproval;
4510
+ #participants;
4511
+ #nestedRunners = /* @__PURE__ */ new Map();
3958
4512
  setCapabilityView(view) {
3959
4513
  this.#capabilityView = view;
3960
4514
  }
4515
+ /** Host event bus for observation-only events such as workflow item transitions. */
4516
+ setEventEmitter(emit) {
4517
+ this.#emitEvent = emit;
4518
+ }
4519
+ /** Session registry behind `context.participants` and owned-work cancellation. */
4520
+ setParticipantRegistry(registry) {
4521
+ this.#participants = registry;
4522
+ }
4523
+ /** The nested program runner of the active execution with this outer call id. */
4524
+ nestedProgramRunner(parentToolCallId) {
4525
+ return this.#nestedRunners.get(parentToolCallId);
4526
+ }
4527
+ /** No-UI approval fallback used when approvals.headless is "decision". */
4528
+ setHeadlessApproval(handler) {
4529
+ this.#headlessApproval = handler;
4530
+ }
3961
4531
  async execute(options) {
4532
+ const executor = this.config.executor;
4533
+ if (process.env.PI_FABRIC_WRITE_POLICY && (executor.kernel === "python" ? executor.pythonRuntime !== "monty" : this.config.schema.mode !== "enforce" && executor.runtime !== "quickjs")) {
4534
+ const { readWritePolicy } = await import("./agents/write-guard.js");
4535
+ if (readWritePolicy()?.shell !== "unconfined") {
4536
+ throw new Error('Fabric write policy refuses native executors (CPython, node-process, bun-process); the parent must request shell: "unconfined"');
4537
+ }
4538
+ }
3962
4539
  const startedAt = performance.now();
3963
- const traceRecorder = new FabricExecutionTraceRecorder();
4540
+ const assessment = this.config.trace.assessment ? new FabricAssessmentRecorder() : void 0;
4541
+ const traceRecorder = new FabricExecutionTraceRecorder(assessment);
4542
+ let sessionId;
4543
+ try {
4544
+ sessionId = options.context.sessionManager?.getSessionId?.() || void 0;
4545
+ } catch {
4546
+ sessionId = void 0;
4547
+ }
4548
+ const itemTransitions = new FabricWorkflowItemTransitions(
4549
+ options.parentToolCallId,
4550
+ this.#emitEvent,
4551
+ sessionId
4552
+ );
3964
4553
  this.activity?.start(
3965
4554
  options.parentToolCallId,
3966
4555
  options.display,
@@ -3988,6 +4577,7 @@ var FabricExecutionService = class {
3988
4577
  }
3989
4578
  let code = options.code;
3990
4579
  let checked2 = { errors: [] };
4580
+ let guestTypeSources = {};
3991
4581
  const unavailable = new Map(
3992
4582
  this.registry.unavailableProviders().map((entry) => [entry.name, entry.reason])
3993
4583
  );
@@ -3997,7 +4587,7 @@ var FabricExecutionService = class {
3997
4587
  })) ?? [];
3998
4588
  const piToolCanonicalFields = Object.fromEntries(coreOverrides.filter((entry) => PI_CORE_TOOL_NAME_SET.has(entry.name)).map((entry) => [entry.name, Object.keys(entry.inputSchema.properties ?? {})]));
3999
4589
  if (!python) {
4000
- const guestTypeSources = await this.registry.guestTypeSources({
4590
+ guestTypeSources = await this.registry.guestTypeSources({
4001
4591
  cwd: options.context.cwd,
4002
4592
  signal: options.signal,
4003
4593
  parentToolCallId: options.parentToolCallId,
@@ -4024,6 +4614,11 @@ var FabricExecutionService = class {
4024
4614
  }
4025
4615
  }
4026
4616
  this.activity?.finish(options.parentToolCallId, false, "Type checking failed");
4617
+ const failedTrace = traceRecorder.seal(
4618
+ "failed",
4619
+ [],
4620
+ `Type checking failed (${checked2.errors.length} ${checked2.errors.length === 1 ? "error" : "errors"})`
4621
+ );
4027
4622
  return {
4028
4623
  success: false,
4029
4624
  kernel: "typescript",
@@ -4031,11 +4626,8 @@ var FabricExecutionService = class {
4031
4626
  logs: [],
4032
4627
  audits: [],
4033
4628
  phases: [],
4034
- trace: traceRecorder.seal(
4035
- "failed",
4036
- [],
4037
- `Type checking failed (${checked2.errors.length} ${checked2.errors.length === 1 ? "error" : "errors"})`
4038
- ),
4629
+ trace: failedTrace,
4630
+ ...assessment ? { assessment: assessment.seal("failed") } : {},
4039
4631
  elapsedMs: performance.now() - startedAt,
4040
4632
  typeErrors: checked2.errors
4041
4633
  };
@@ -4047,7 +4639,15 @@ var FabricExecutionService = class {
4047
4639
  risk: audit.risk
4048
4640
  });
4049
4641
  operation.succeed(audit);
4050
- if (decision) classifierUsages.push(decision.usage);
4642
+ if (decision) {
4643
+ classifierUsages.push(decision.usage);
4644
+ const usage = readFabricAssessmentUsage(decision.usage);
4645
+ assessment?.attribute(operation.sequence, {
4646
+ source: "classifier",
4647
+ ...audit.model ? { model: audit.model } : {},
4648
+ ...usage ? { usage } : {}
4649
+ });
4650
+ }
4051
4651
  };
4052
4652
  const approval = new ApprovalController(
4053
4653
  this.config.approvals,
@@ -4055,7 +4655,8 @@ var FabricExecutionService = class {
4055
4655
  this.sessionApprovals,
4056
4656
  this.autoApprovalClassifier,
4057
4657
  recordAutoDecision,
4058
- this.brokeredNetwork
4658
+ this.brokeredNetwork,
4659
+ this.#headlessApproval ? (action, reason) => this.#headlessApproval(action, reason, options.signal) : void 0
4059
4660
  );
4060
4661
  const audits = [];
4061
4662
  const phases = [];
@@ -4184,6 +4785,8 @@ var FabricExecutionService = class {
4184
4785
  ) : 0;
4185
4786
  return Math.max(orchestrationTimeoutMs, requestedTimeoutMs2);
4186
4787
  };
4788
+ const humanWaitRefs = new Set(this.config.executor.humanWaitRefs);
4789
+ const isHumanWaitHostCall = (ref, args) => humanWaitRefs.has(ref === "fabric.$call" && typeof args.ref === "string" ? args.ref : ref);
4187
4790
  const traceAttempt = async (ref, args, signal, run) => {
4188
4791
  const operation = traceRecorder.issueCall(ref, args);
4189
4792
  let stage = "invoke";
@@ -4211,8 +4814,13 @@ var FabricExecutionService = class {
4211
4814
  );
4212
4815
  throw error;
4213
4816
  }
4817
+ const participants = this.#participants;
4818
+ const separator = ref.indexOf(".");
4214
4819
  return this.registry.invoke(ref, args, {
4215
4820
  ...callContext,
4821
+ // The registry resolves `provider.action` by this exact prefix, so the
4822
+ // view is bound to the provider that receives it.
4823
+ ...participants && separator > 0 ? { participants: participants.view(ref.slice(0, separator), options.parentToolCallId) } : {},
4216
4824
  ...ref === "agents.handoff" ? {
4217
4825
  deferHandoff(request) {
4218
4826
  if (handoffRequest) {
@@ -4246,10 +4854,95 @@ var FabricExecutionService = class {
4246
4854
  });
4247
4855
  };
4248
4856
  let sandboxResult;
4857
+ let hostCall;
4858
+ const sandboxBase = {
4859
+ cwd: options.context.cwd,
4860
+ memoryLimitBytes: this.config.executor.memoryLimitBytes,
4861
+ maxLogChars: this.config.executor.maxOutputChars,
4862
+ minimumTimeoutMsForHostCall,
4863
+ ...humanWaitRefs.size > 0 ? { isHumanWaitHostCall } : {},
4864
+ ...!python ? { piToolCanonicalFields } : {},
4865
+ ...options.tokenBudget !== void 0 ? { tokenBudget: options.tokenBudget } : {}
4866
+ };
4867
+ const nestedLogs = [];
4868
+ let nestedLogChars = 0;
4869
+ let nestedRuns = 0;
4870
+ const preparedPrograms = /* @__PURE__ */ new Map();
4871
+ const runNestedProgram = async (request, signal) => {
4872
+ const bridge = hostCall;
4873
+ if (!bridge) throw new Error("Fabric program runs need an active execution");
4874
+ nestedRuns++;
4875
+ if (nestedRuns > MAX_NESTED_PROGRAM_RUNS) {
4876
+ throw new FabricTraceSafeError(`Fabric nested program budget exhausted (${MAX_NESTED_PROGRAM_RUNS} per execution)`);
4877
+ }
4878
+ const operation = traceRecorder.issueCall("fabric.program.run", {
4879
+ program: request.program,
4880
+ ...options.invokedBy ? { invokedBy: options.invokedBy } : {}
4881
+ });
4882
+ const runSignal = signal ?? new AbortController().signal;
4883
+ let stage = "invoke";
4884
+ try {
4885
+ if (request.call) {
4886
+ const value = await bridge(request.call.ref, request.call.args, runSignal);
4887
+ operation.succeed(void 0);
4888
+ return value;
4889
+ }
4890
+ let source = request.code ?? "";
4891
+ let prepared = { errors: [] };
4892
+ if (!python) {
4893
+ stage = "prepare";
4894
+ const cached = preparedPrograms.get(source);
4895
+ const next = cached ?? runtime.prepare(
4896
+ source,
4897
+ effectiveFullCodeMode,
4898
+ [...unavailable.keys()],
4899
+ guestTypeSources,
4900
+ coreOverrides
4901
+ );
4902
+ if (!cached) preparedPrograms.set(source, next);
4903
+ ({ code: source, checked: prepared } = next);
4904
+ if (prepared.errors.length > 0) {
4905
+ throw new Error(`Program ${request.program} has type errors: ${prepared.errors.slice(0, 5).map((error) => error.line > 0 ? `line ${error.line}:${error.column} ${error.message}` : error.message).join("; ")}`);
4906
+ }
4907
+ stage = "invoke";
4908
+ }
4909
+ const spanPrefix = `program-${nestedRuns}:`;
4910
+ const nestedBridge = (ref, args, callSignal) => (ref === "fabric.$spanStart" || ref === "fabric.$spanEnd") && typeof args.id === "string" ? bridge(ref, { ...args, id: `${spanPrefix}${args.id}` }, callSignal) : bridge(ref, args, callSignal);
4911
+ const result = await runtime.execute(source, nestedBridge, {
4912
+ ...sandboxBase,
4913
+ timeoutMs: codeUsesOrchestration(source) ? orchestrationTimeoutMs : this.config.executor.timeoutMs,
4914
+ ...prepared.javascript ? { transpiledCode: prepared.javascript } : {},
4915
+ ...prepared.sourceMap ? { transpiledSourceMap: prepared.sourceMap } : {},
4916
+ signal: runSignal
4917
+ });
4918
+ for (const line of result.logs) {
4919
+ if (nestedLogChars > this.config.executor.maxOutputChars) break;
4920
+ nestedLogChars += line.length;
4921
+ nestedLogs.push(nestedLogChars > this.config.executor.maxOutputChars ? `[${request.program}] (nested program logs truncated)` : `[${request.program}] ${line}`);
4922
+ }
4923
+ if (result.terminationReason !== "completed") {
4924
+ const outcome = executionOutcomeFromTermination(result.terminationReason);
4925
+ throw Object.assign(
4926
+ new Error(`Program ${request.program} ${outcome.replace("_", " ")}: ${result.error ?? "no result"}`),
4927
+ { programOutcome: outcome }
4928
+ );
4929
+ }
4930
+ operation.succeed(void 0);
4931
+ return result.value;
4932
+ } catch (error) {
4933
+ const outcome = error.programOutcome ?? executionOutcomeFromError(error, runSignal);
4934
+ operation.fail(stage, error, outcome);
4935
+ throw error;
4936
+ }
4937
+ };
4938
+ this.#nestedRunners.set(options.parentToolCallId, {
4939
+ kernel: python ? "python" : "typescript",
4940
+ run: runNestedProgram
4941
+ });
4249
4942
  try {
4250
4943
  sandboxResult = await runtime.execute(
4251
4944
  code,
4252
- async (ref, args, runtimeSignal) => {
4945
+ hostCall = async (ref, args, runtimeSignal) => {
4253
4946
  const callContext = { ...baseContext, signal: runtimeSignal };
4254
4947
  switch (ref) {
4255
4948
  case "fabric.$providers":
@@ -4505,9 +5198,18 @@ var FabricExecutionService = class {
4505
5198
  "fabric.workflow.item",
4506
5199
  args,
4507
5200
  runtimeSignal,
4508
- () => {
4509
- const item = args;
4510
- return this.activity?.upsertItem(options.parentToolCallId, item) ?? item;
5201
+ (setStage) => {
5202
+ setStage("validate");
5203
+ const transition = validateWorkflowItemInput(
5204
+ args,
5205
+ () => itemTransitions.nextDefaultId()
5206
+ );
5207
+ setStage("invoke");
5208
+ const { meta: _meta, ...rest } = args;
5209
+ const item = { ...rest, id: transition.id };
5210
+ const stored = this.activity?.upsertItem(options.parentToolCallId, item) ?? item;
5211
+ itemTransitions.record(transition, stored.label);
5212
+ return stored;
4511
5213
  }
4512
5214
  );
4513
5215
  case "fabric.$event":
@@ -4551,24 +5253,24 @@ var FabricExecutionService = class {
4551
5253
  }
4552
5254
  },
4553
5255
  {
5256
+ ...sandboxBase,
4554
5257
  timeoutMs: effectiveTimeoutMs,
4555
- cwd: options.context.cwd,
4556
- memoryLimitBytes: this.config.executor.memoryLimitBytes,
4557
- maxLogChars: this.config.executor.maxOutputChars,
4558
- minimumTimeoutMsForHostCall,
4559
- ...!python ? { piToolCanonicalFields } : {},
4560
5258
  ...checked2.javascript ? { transpiledCode: checked2.javascript } : {},
4561
5259
  ...checked2.sourceMap ? { transpiledSourceMap: checked2.sourceMap } : {},
4562
5260
  ...options.strings ? { strings: options.strings } : {},
4563
- ...options.tokenBudget !== void 0 ? { tokenBudget: options.tokenBudget } : {},
4564
5261
  ...options.signal ? { signal: options.signal } : {}
4565
5262
  }
4566
5263
  );
4567
5264
  } catch (error) {
4568
5265
  const message2 = error instanceof Error ? error.message : String(error);
4569
5266
  this.activity?.finish(options.parentToolCallId, false, message2);
5267
+ itemTransitions.finish(false);
5268
+ if (options.signal?.aborted) {
5269
+ await this.#participants?.cancelInvocation(options.parentToolCallId).catch(() => void 0);
5270
+ }
4570
5271
  throw error;
4571
5272
  } finally {
5273
+ this.#nestedRunners.delete(options.parentToolCallId);
4572
5274
  await this.registry.endInvocation(options.parentToolCallId);
4573
5275
  flushEmit();
4574
5276
  }
@@ -4580,22 +5282,31 @@ Recovery hint: ${hint}`;
4580
5282
  }
4581
5283
  const runOutcome = executionOutcomeFromTermination(sandboxResult.terminationReason);
4582
5284
  const succeeded = runOutcome === "succeeded";
5285
+ const ownedWork = (runOutcome === "aborted" || runOutcome === "timed_out") && this.#participants ? await stopOwnedWork(this.#participants, options.parentToolCallId, traceRecorder) : [];
5286
+ if (ownedWork.length > 0) {
5287
+ const summary = `Owned work stopped: ${ownedWork.map((stop) => `${stop.ref} ${stop.outcome}${stop.detail ? ` (${stop.detail})` : ""}`).join("; ")}`;
5288
+ sandboxResult.error = sandboxResult.error ? `${sandboxResult.error}
5289
+ ${summary}` : summary;
5290
+ }
4583
5291
  this.activity?.finish(options.parentToolCallId, succeeded, sandboxResult.error);
5292
+ itemTransitions.finish(succeeded);
4584
5293
  const sanitizedValue = sanitizeFabricMediaValue(sandboxResult.value);
4585
5294
  return {
4586
5295
  success: succeeded,
4587
5296
  kernel: python ? "python" : "typescript",
4588
5297
  value: sanitizedValue.value,
4589
- logs: sandboxResult.logs.map(sanitizeFabricMediaText),
5298
+ logs: [...sandboxResult.logs, ...nestedLogs].map(sanitizeFabricMediaText),
4590
5299
  ...sanitizedValue.images.length > 0 ? { media: sanitizedValue.images } : {},
4591
5300
  audits,
4592
5301
  phases,
4593
5302
  // Guest and provider error text may embed tool output or source
4594
5303
  // literals, so the durable trace records only safe causes.
4595
5304
  trace: traceRecorder.seal(runOutcome, phases),
5305
+ ...assessment ? { assessment: assessment.seal(runOutcome) } : {},
4596
5306
  elapsedMs: performance.now() - startedAt,
4597
5307
  ...sandboxResult.error ? { error: sanitizeFabricMediaText(sandboxResult.error) } : {},
4598
5308
  ...handoffRequest ? { handoffRequest } : {},
5309
+ ...ownedWork.length > 0 ? { ownedWork } : {},
4599
5310
  ...classifierUsages.length > 0 ? { usage: aggregateUsage(classifierUsages) } : {}
4600
5311
  };
4601
5312
  }
@@ -5022,8 +5733,14 @@ var TIER_A_SPECULATION_REFS = /* @__PURE__ */ new Set([
5022
5733
  "state.get",
5023
5734
  "state.history",
5024
5735
  "state.complexity",
5736
+ "mesh.scheduled",
5025
5737
  "schema.status",
5026
5738
  "compact.status",
5739
+ "compact.pressure",
5740
+ "thinking.status",
5741
+ "decisions.list",
5742
+ "programs.list",
5743
+ "programs.get",
5027
5744
  "components.list",
5028
5745
  "components.status",
5029
5746
  "components.graph"
@@ -5560,8 +6277,15 @@ var allowedEnforceRefs = /* @__PURE__ */ new Set([
5560
6277
  "mesh.members",
5561
6278
  "mesh.get",
5562
6279
  "mesh.list",
6280
+ "decisions.list",
6281
+ "programs.list",
6282
+ "programs.get",
6283
+ "mesh.scheduled",
6284
+ "mesh.grants",
5563
6285
  "compact.status",
6286
+ "compact.pressure",
5564
6287
  "cache.status",
6288
+ "thinking.status",
5565
6289
  "components.list",
5566
6290
  "components.describe",
5567
6291
  "components.status",
@@ -5574,8 +6298,127 @@ var allowedEnforceRefs = /* @__PURE__ */ new Set([
5574
6298
  ]);
5575
6299
  var schemaRefAllowedInEnforce = (ref) => allowedEnforceRefs.has(ref);
5576
6300
 
6301
+ // src/decisions/host.ts
6302
+ var DEFAULT_HEADLESS_APPROVAL_TIMEOUT_MS = 3e5;
6303
+ var DEFAULT_CHILD_QUESTION_TIMEOUT_MS = 6e5;
6304
+ var CANCELLED = { cancelled: true };
6305
+ var clip2 = (value, max) => value.length <= max ? value : `${value.slice(0, max - 1)}\u2026`;
6306
+ var raiseAndWait = async (store, input, raisedBy, signal, onRaised) => {
6307
+ const record = await store.raise(input, raisedBy);
6308
+ onRaised?.(record.id);
6309
+ try {
6310
+ return await store.wait(record.id, signal ? { signal } : {});
6311
+ } catch (error) {
6312
+ await store.cancel(record.id, { answeredBy: store.identity.id, via: "abort" }).catch(() => void 0);
6313
+ throw error;
6314
+ }
6315
+ };
6316
+ var requestHeadlessApproval = async (store, action, options = {}) => {
6317
+ const settled = await raiseAndWait(store, {
6318
+ kind: "approval",
6319
+ title: clip2(`${action.ref} requests ${action.risk} access`, MAX_DECISION_TITLE_CHARS),
6320
+ body: clip2([action.description, options.reason].filter(Boolean).join("\n\n"), MAX_DECISION_BODY_CHARS),
6321
+ options: [
6322
+ { id: "approve", label: "Approve once" },
6323
+ { id: "deny", label: "Deny" }
6324
+ ],
6325
+ holder: "user",
6326
+ timeoutMs: options.timeoutMs ?? DEFAULT_HEADLESS_APPROVAL_TIMEOUT_MS,
6327
+ onExpire: "cancel"
6328
+ }, {}, options.signal);
6329
+ return settled.status === "answered" && settled.answer?.optionId === "approve";
6330
+ };
6331
+ var parseChildQuestion = (value) => {
6332
+ const method = value.method;
6333
+ if (method !== "select" && method !== "confirm" && method !== "input" && method !== "editor") return void 0;
6334
+ const options = Array.isArray(value.options) ? value.options.filter((option) => typeof option === "string") : void 0;
6335
+ if (method === "select" && !options?.length) return void 0;
6336
+ const string = (field) => typeof field === "string" ? field : void 0;
6337
+ const message2 = string(value.message);
6338
+ const placeholder = string(value.placeholder);
6339
+ const prefill = string(value.prefill);
6340
+ return {
6341
+ method,
6342
+ title: string(value.title) ?? "",
6343
+ ...message2 !== void 0 ? { message: message2 } : {},
6344
+ ...options && method === "select" ? { options } : {},
6345
+ ...placeholder !== void 0 ? { placeholder } : {},
6346
+ ...prefill !== void 0 ? { prefill } : {},
6347
+ timeout: typeof value.timeout === "number" && Number.isFinite(value.timeout) && value.timeout >= 1e3 ? Math.floor(value.timeout) : DEFAULT_CHILD_QUESTION_TIMEOUT_MS
6348
+ };
6349
+ };
6350
+ var askViaUi = async (ui, label, question, signal) => {
6351
+ const dialog = { signal, timeout: question.timeout };
6352
+ if (question.method === "select") {
6353
+ const value = await ui.select(label, question.options, dialog);
6354
+ return value !== void 0 && question.options.includes(value) ? { value } : CANCELLED;
6355
+ }
6356
+ if (question.method === "confirm") {
6357
+ return { confirmed: await ui.confirm(label, question.message ?? "", dialog) };
6358
+ }
6359
+ if (question.method === "input") {
6360
+ const value = await ui.input(label, question.placeholder, dialog);
6361
+ return value === void 0 ? CANCELLED : { value };
6362
+ }
6363
+ let timer;
6364
+ let onAbort;
6365
+ const stop = new Promise((resolve2) => {
6366
+ timer = setTimeout(() => resolve2(void 0), question.timeout);
6367
+ onAbort = () => resolve2(void 0);
6368
+ signal.addEventListener("abort", onAbort, { once: true });
6369
+ });
6370
+ try {
6371
+ const value = await Promise.race([ui.editor(label, question.prefill), stop]);
6372
+ return value === void 0 ? CANCELLED : { value };
6373
+ } finally {
6374
+ clearTimeout(timer);
6375
+ if (onAbort) signal.removeEventListener("abort", onAbort);
6376
+ }
6377
+ };
6378
+ var responseFromDecision = (question, decision) => {
6379
+ if (decision.status !== "answered" || !decision.answer) return CANCELLED;
6380
+ const { optionId, text } = decision.answer;
6381
+ if (question.method === "confirm") return { confirmed: optionId === "yes" };
6382
+ if (question.method === "select") {
6383
+ const index = optionId?.startsWith("o") ? Number(optionId.slice(1)) - 1 : -1;
6384
+ const value = question.options?.[index];
6385
+ return value === void 0 ? CANCELLED : { value };
6386
+ }
6387
+ return text === void 0 ? CANCELLED : { value: text };
6388
+ };
6389
+ var routeChildQuestion = async (request, deps) => {
6390
+ const question = parseChildQuestion(request.question);
6391
+ if (!question || request.signal.aborted) return CANCELLED;
6392
+ const label = `${request.name}: ${question.title || "question"}`;
6393
+ if (deps.context.hasUI) return askViaUi(deps.context.ui, label, question, request.signal);
6394
+ if (!deps.store) return CANCELLED;
6395
+ const input = {
6396
+ kind: "question",
6397
+ title: clip2(label, MAX_DECISION_TITLE_CHARS),
6398
+ ...question.message ? { body: clip2(question.message, MAX_DECISION_BODY_CHARS) } : {},
6399
+ ...question.method === "select" ? {
6400
+ input: "select",
6401
+ options: question.options.slice(0, MAX_DECISION_OPTIONS).map((option, index) => ({
6402
+ id: `o${index + 1}`,
6403
+ label: clip2(option || `Option ${index + 1}`, MAX_DECISION_TITLE_CHARS)
6404
+ }))
6405
+ } : { input: question.method === "input" ? "text" : question.method },
6406
+ holder: "root",
6407
+ timeoutMs: Math.max(1e3, question.timeout),
6408
+ onExpire: "cancel"
6409
+ };
6410
+ const decision = await raiseAndWait(
6411
+ deps.store,
6412
+ input,
6413
+ { participantId: request.actorId ?? request.runId, runId: request.runId },
6414
+ request.signal,
6415
+ request.onDecision
6416
+ );
6417
+ return responseFromDecision(question, decision);
6418
+ };
6419
+
5577
6420
  // src/prewalk/handoff.ts
5578
- import { randomUUID as randomUUID3 } from "node:crypto";
6421
+ import { randomUUID as randomUUID4 } from "node:crypto";
5579
6422
 
5580
6423
  // src/agents/handoff-continuation.ts
5581
6424
  var HANDOFF_CONTINUATION_MESSAGE_TYPE = "pi-fabric-handoff-continuation";
@@ -5740,7 +6583,7 @@ var buildPrewalkPending = (claim, resultFormat) => {
5740
6583
  claim.arm.task,
5741
6584
  ...!inPlace && readiness.kind === "planned" ? [prewalkPlanText(readiness.plan)] : []
5742
6585
  ].filter(Boolean).join("\n\n");
5743
- const nestedToolCallId = `${FABRIC_NESTED_TOOL_CALL_ID_PREFIX}prewalk_${randomUUID3()}`;
6586
+ const nestedToolCallId = `${FABRIC_NESTED_TOOL_CALL_ID_PREFIX}prewalk_${randomUUID4()}`;
5744
6587
  const args = {
5745
6588
  model: claim.arm.model,
5746
6589
  name: inPlace ? "In-place Prewalk" : "Prewalk trajectory executor",
@@ -5808,7 +6651,7 @@ var runInPlacePrewalk = async (controller, extension, pending, context) => {
5808
6651
  const returnModel = context.model;
5809
6652
  if (!returnModel) throw new Error("Prewalk cannot determine Main return model");
5810
6653
  const returnModelKey = `${returnModel.provider}/${returnModel.id}`;
5811
- const continuationId = randomUUID3();
6654
+ const continuationId = randomUUID4();
5812
6655
  const switched = await extension.setModel(model);
5813
6656
  if (!switched) {
5814
6657
  throw new Error(`No authentication configured for prewalk model: ${modelKey}`);
@@ -6063,8 +6906,77 @@ var LifecycleDeliveryScheduler = class {
6063
6906
  }
6064
6907
  };
6065
6908
 
6909
+ // src/agents/fork-seed.ts
6910
+ var DEFAULT_SEED_MESSAGES = 12;
6911
+ var MAX_SEED_MESSAGES = 50;
6912
+ var MAX_SNIPPET_MESSAGE_CHARS = 4e3;
6913
+ var checkedSeed = (seed, seedMessages) => {
6914
+ if (seed !== void 0 && seed !== "task" && seed !== "branch" && seed !== "snippet") {
6915
+ throw new Error('seed must be "task", "branch", or "snippet"');
6916
+ }
6917
+ if (seedMessages !== void 0) {
6918
+ if (seed !== "snippet") throw new Error('seedMessages applies only to seed: "snippet"');
6919
+ if (typeof seedMessages !== "number" || !Number.isInteger(seedMessages) || seedMessages < 1 || seedMessages > MAX_SEED_MESSAGES) {
6920
+ throw new Error(`seedMessages must be an integer from 1 to ${MAX_SEED_MESSAGES}`);
6921
+ }
6922
+ }
6923
+ return {
6924
+ seed: seed ?? "task",
6925
+ seedMessages: seedMessages ?? DEFAULT_SEED_MESSAGES
6926
+ };
6927
+ };
6928
+ var isMessage2 = (entry) => entry.type === "message";
6929
+ var toolCallIds = (entry) => {
6930
+ const message2 = entry.message;
6931
+ if (message2.role !== "assistant" || !Array.isArray(message2.content)) return [];
6932
+ return message2.content.filter((part) => typeof part === "object" && part !== null && part.type === "toolCall" && typeof part.id === "string").map((part) => part.id);
6933
+ };
6934
+ var completedBranchPrefix = (branch) => {
6935
+ const resolved = /* @__PURE__ */ new Set();
6936
+ for (let index = branch.length - 1; index >= 0; index--) {
6937
+ const entry = branch[index];
6938
+ if (!isMessage2(entry)) continue;
6939
+ const message2 = entry.message;
6940
+ if (message2.role === "user") break;
6941
+ if (message2.role === "toolResult" && typeof message2.toolCallId === "string") {
6942
+ resolved.add(message2.toolCallId);
6943
+ continue;
6944
+ }
6945
+ if (toolCallIds(entry).some((id2) => !resolved.has(id2))) return branch.slice(0, index);
6946
+ }
6947
+ return [...branch];
6948
+ };
6949
+ var messageText = (content) => {
6950
+ if (typeof content === "string") return content;
6951
+ if (!Array.isArray(content)) return "";
6952
+ return content.filter((part) => typeof part === "object" && part !== null && part.type === "text" && typeof part.text === "string").map((part) => part.text).join("\n");
6953
+ };
6954
+ var snippetTask = (branch, count2, task) => {
6955
+ const messages = [];
6956
+ for (const entry of completedBranchPrefix(branch)) {
6957
+ if (!isMessage2(entry)) continue;
6958
+ const message2 = entry.message;
6959
+ if (message2.role !== "user" && message2.role !== "assistant") continue;
6960
+ let text = messageText(message2.content).trim();
6961
+ if (!text) continue;
6962
+ if (text.length > MAX_SNIPPET_MESSAGE_CHARS) text = `${text.slice(0, MAX_SNIPPET_MESSAGE_CHARS)}\u2026`;
6963
+ messages.push(`[${message2.role}]
6964
+ ${text}`);
6965
+ }
6966
+ const recent = messages.slice(-count2);
6967
+ if (recent.length === 0) return task;
6968
+ return [
6969
+ `<inherited-conversation messages="${recent.length}">`,
6970
+ recent.join("\n\n"),
6971
+ "</inherited-conversation>",
6972
+ "",
6973
+ "Task:",
6974
+ task
6975
+ ].join("\n");
6976
+ };
6977
+
6066
6978
  // src/residency/client.ts
6067
- import { randomUUID as randomUUID4 } from "node:crypto";
6979
+ import { randomUUID as randomUUID5 } from "node:crypto";
6068
6980
  import fs5 from "node:fs";
6069
6981
  import path5 from "node:path";
6070
6982
  import { fileURLToPath } from "node:url";
@@ -6223,7 +7135,7 @@ var ResidencyClient = class {
6223
7135
  const response = await this.#command({
6224
7136
  format: RESIDENT_HOST_FORMAT,
6225
7137
  operation: "createActor",
6226
- requestId: randomUUID4(),
7138
+ requestId: randomUUID5(),
6227
7139
  rootId: this.options.config.rootId,
6228
7140
  request,
6229
7141
  createdAt: Date.now()
@@ -6234,6 +7146,11 @@ var ResidencyClient = class {
6234
7146
  }
6235
7147
  async spawnAgent(request, signal) {
6236
7148
  const resolvedRequest = request.cwd === void 0 ? request : { ...request, cwd: resolveAgentCwd(this.options.config.cwd, request.cwd) };
7149
+ const runner = request.runner ?? this.options.config.agents.runner;
7150
+ const runnerModule = BUILT_IN_RUNNER_IDS.has(runner) ? void 0 : requireAgentRunner(runner).residentModule;
7151
+ if (!BUILT_IN_RUNNER_IDS.has(runner) && !runnerModule) {
7152
+ throw new Error(`Fabric runner ${runner} declares no residentModule; durable residency needs one`);
7153
+ }
6237
7154
  const allowedTools = this.#inheritedToolAllowlist;
6238
7155
  const tools = allowedTools === void 0 ? void 0 : (request.tools ?? this.options.config.agents.defaultTools).filter((tool) => allowedTools.has(tool));
6239
7156
  await this.ensureHost();
@@ -6241,9 +7158,10 @@ var ResidencyClient = class {
6241
7158
  {
6242
7159
  format: RESIDENT_HOST_FORMAT,
6243
7160
  operation: "spawn",
6244
- requestId: randomUUID4(),
7161
+ requestId: randomUUID5(),
6245
7162
  rootId: this.options.config.rootId,
6246
7163
  request: { ...resolvedRequest, ...tools ? { tools } : {}, residency: "durable" },
7164
+ ...runnerModule ? { runnerModule } : {},
6247
7165
  createdAt: Date.now()
6248
7166
  },
6249
7167
  signal
@@ -6326,7 +7244,7 @@ var ResidencyClient = class {
6326
7244
  await this.#command({
6327
7245
  format: RESIDENT_HOST_FORMAT,
6328
7246
  operation: "removeActor",
6329
- requestId: randomUUID4(),
7247
+ requestId: randomUUID5(),
6330
7248
  rootId: this.options.config.rootId,
6331
7249
  id: id2,
6332
7250
  createdAt: Date.now()
@@ -6342,7 +7260,7 @@ var ResidencyClient = class {
6342
7260
  response = await this.#command({
6343
7261
  format: RESIDENT_HOST_FORMAT,
6344
7262
  operation: "cleanup",
6345
- requestId: randomUUID4(),
7263
+ requestId: randomUUID5(),
6346
7264
  rootId: this.options.config.rootId,
6347
7265
  id: id2,
6348
7266
  deleteBranch,
@@ -6439,7 +7357,8 @@ var ResidencyClient = class {
6439
7357
  }
6440
7358
  #liveOwner() {
6441
7359
  const owner = readJson(this.#ownerPath);
6442
- if (owner?.format !== RESIDENT_HOST_FORMAT || owner.hostId !== this.hostId || !Number.isSafeInteger(owner.pid) || !processIsAlive(owner.pid)) {
7360
+ if (owner?.format !== RESIDENT_HOST_FORMAT || owner.hostId !== this.hostId || !Number.isSafeInteger(owner.pid) || // A host in another PID namespace is judged by its heartbeat.
7361
+ recordOwnerLiveness(owner, { legacyAlive: processIsAlive }) === "dead") {
6443
7362
  return void 0;
6444
7363
  }
6445
7364
  return owner;
@@ -6605,7 +7524,7 @@ var waitWithProgress = async (manager, transcripts, id2, context, agentToolPrevi
6605
7524
  );
6606
7525
  if (revision === lastPreviewRevision) return;
6607
7526
  lastPreviewRevision = revision;
6608
- const currentTool = "currentTool" in status && status.currentTool ? ` \xB7 ${status.currentTool}` : "";
7527
+ const currentTool = "blockedOn" in status && status.blockedOn ? " \xB7 waiting_for_answer" : "currentTool" in status && status.currentTool ? ` \xB7 ${status.currentTool}` : "";
6609
7528
  const displayName = status.actorName ?? status.name;
6610
7529
  context.update(`Agent ${displayName}: ${status.status}${currentTool}`);
6611
7530
  if ("usage" in status) {
@@ -6701,7 +7620,8 @@ var AgentMessageRouter = class {
6701
7620
  {
6702
7621
  message: message2,
6703
7622
  data,
6704
- ...typeof options.triggerTurn === "boolean" ? { triggerTurn: options.triggerTurn } : {}
7623
+ ...typeof options.triggerTurn === "boolean" ? { triggerTurn: options.triggerTurn } : {},
7624
+ ...participant2.ownerIncarnation ? { ownerIncarnation: participant2.ownerIncarnation } : {}
6705
7625
  },
6706
7626
  participant2.ownerIdentityId
6707
7627
  );
@@ -6729,7 +7649,8 @@ var AgentMessageRouter = class {
6729
7649
  {
6730
7650
  message: message2,
6731
7651
  data,
6732
- ...typeof options.triggerTurn === "boolean" ? { triggerTurn: options.triggerTurn } : {}
7652
+ ...typeof options.triggerTurn === "boolean" ? { triggerTurn: options.triggerTurn } : {},
7653
+ ...remoteRoot.ownerIncarnation ? { ownerIncarnation: remoteRoot.ownerIncarnation } : {}
6733
7654
  },
6734
7655
  remoteRoot.ownerIdentityId
6735
7656
  );
@@ -6780,7 +7701,8 @@ var AgentMessageRouter = class {
6780
7701
  message: message2,
6781
7702
  data,
6782
7703
  ...typeof options.triggerTurn === "boolean" ? { triggerTurn: options.triggerTurn } : {},
6783
- ...needsBinding && resolvedBinding ? { binding: resolvedBinding } : {}
7704
+ ...needsBinding && resolvedBinding ? { binding: resolvedBinding } : {},
7705
+ ...participant.ownerIncarnation ? { ownerIncarnation: participant.ownerIncarnation } : {}
6784
7706
  },
6785
7707
  participant.ownerIdentityId
6786
7708
  );
@@ -6832,7 +7754,7 @@ var AgentMessageRouter = class {
6832
7754
  message2,
6833
7755
  command.data,
6834
7756
  signal,
6835
- command.binding !== void 0 ? { binding: command.binding } : {}
7757
+ { ...command.binding !== void 0 ? { binding: command.binding } : {}, sender: command.sender ?? null }
6836
7758
  );
6837
7759
  return { accepted: true, messageId: result.id, result };
6838
7760
  } catch (error) {
@@ -6871,7 +7793,7 @@ var AgentMessageRouter = class {
6871
7793
  actor.id,
6872
7794
  message2,
6873
7795
  command.data,
6874
- command.binding !== void 0 ? { binding: command.binding } : {}
7796
+ { ...command.binding !== void 0 ? { binding: command.binding } : {}, sender: command.sender ?? null }
6875
7797
  );
6876
7798
  return { accepted: true, messageId: result.messageId };
6877
7799
  } catch (error) {
@@ -6946,6 +7868,11 @@ var longerTimeoutOverride = (value, manager) => {
6946
7868
  const effective = effectiveAgentTimeoutMs(manager.config.timeoutMs, value);
6947
7869
  return effective > manager.config.timeoutMs ? effective : void 0;
6948
7870
  };
7871
+ var checkedRunner = (value, fallback) => {
7872
+ if (value === void 0) return fallback;
7873
+ if (!isFabricRunnerId(value)) throw new Error(`Invalid Fabric agent runner: ${JSON.stringify(value)}`);
7874
+ return value;
7875
+ };
6949
7876
  var checkedKernel = (value) => {
6950
7877
  if (value === void 0 || value === "inherit" || value === "typescript" || value === "python") return value;
6951
7878
  throw new Error(`Invalid Fabric agent kernel: ${String(value)}`);
@@ -7011,10 +7938,11 @@ var actorRequest = (args, context, manager, inheritModel = true) => {
7011
7938
  ) : void 0;
7012
7939
  const timeoutMs = longerTimeoutOverride(args.timeoutMs, manager);
7013
7940
  const validWhile = typeof args.validWhile === "object" && args.validWhile !== null && !Array.isArray(args.validWhile) && args.validWhile.version === 1 && typeof args.validWhile.source === "string" ? { version: 1, source: args.validWhile.source } : void 0;
7014
- const runner = args.runner === "pi" || args.runner === "claude" || args.runner === "veda" ? args.runner : manager.config.runner;
7015
- if (runner === "veda") {
7941
+ const runner = checkedRunner(args.runner, manager.config.runner);
7942
+ const runnerAdapter = requireAgentRunner(runner);
7943
+ if (!runnerAdapter.capabilities.persistentSessions) {
7016
7944
  throw new Error(
7017
- 'The Veda runner does not support persistent actors: Veda executes one headless prompt per invocation. Use a Pi or Claude actor, or agents.run({ runner: "veda" }).'
7945
+ runner === "veda" ? 'The Veda runner does not support persistent actors: Veda executes one headless prompt per invocation. Use a Pi or Claude actor, or agents.run({ runner: "veda" }).' : `The ${runnerAdapter.label} runner does not declare persistentSessions; use agents.run() or a runner that supports persistent actors.`
7018
7946
  );
7019
7947
  }
7020
7948
  const requestedKernel = checkedKernel(args.kernel);
@@ -7084,6 +8012,8 @@ var AgentsProvider = class {
7084
8012
  #transcripts = new AgentTranscriptReader();
7085
8013
  #router;
7086
8014
  name = "agents";
8015
+ /** Session registry of `provider:` participants; stop/steer/followUp route there. */
8016
+ providerParticipants;
7087
8017
  description = "The user-facing Main target, one-shot Pi or Claude Code agents, and persistent mailbox actors over process, tmux, screen, LocalTerm, or Herdr";
7088
8018
  #lifecycleScheduler;
7089
8019
  #lifecycleMessage(event) {
@@ -7129,7 +8059,7 @@ var AgentsProvider = class {
7129
8059
  return `${resolved.provider}/${resolved.id}`;
7130
8060
  }
7131
8061
  #resolvePiModelArgs(args, context, runnerOverride) {
7132
- const runner = runnerOverride ?? (args.runner === "pi" || args.runner === "claude" || args.runner === "veda" ? args.runner : this.manager.config.runner);
8062
+ const runner = runnerOverride ?? checkedRunner(args.runner, this.manager.config.runner);
7133
8063
  if (runner !== "pi") return args;
7134
8064
  const model = typeof args.model === "string" ? args.model.trim() : "";
7135
8065
  if (!model) return args;
@@ -7238,7 +8168,11 @@ var AgentsProvider = class {
7238
8168
  switch (actionName) {
7239
8169
  case "run": {
7240
8170
  const handle = await this.manager.spawn(
7241
- runRequest(this.#resolvePiModelArgs(args, context), context, this.manager, this.modelsConfig()),
8171
+ this.#applySeed(
8172
+ args,
8173
+ runRequest(this.#resolvePiModelArgs(args, context), context, this.manager, this.modelsConfig()),
8174
+ context
8175
+ ),
7242
8176
  context.signal
7243
8177
  );
7244
8178
  this.participants.scheduleRefresh();
@@ -7260,14 +8194,25 @@ var AgentsProvider = class {
7260
8194
  case "handoff":
7261
8195
  return this.handoff(args, context);
7262
8196
  case "spawn": {
7263
- const request = runRequest(this.#resolvePiModelArgs(args, context), context, this.manager, this.modelsConfig());
8197
+ const request = this.#applySeed(
8198
+ args,
8199
+ runRequest(this.#resolvePiModelArgs(args, context), context, this.manager, this.modelsConfig()),
8200
+ context
8201
+ );
8202
+ if (request.residency === "durable") this.#assertUnconfinedDurable();
7264
8203
  const kernel = this.manager.resolveKernel(request);
7265
- const { kernel: _requestedKernel, ...baseRequest } = request;
8204
+ const { kernel: _requestedKernel, ...requestWithScope } = request;
8205
+ const inheritedScope = request.residency === "durable" ? childScope(request.scope) : void 0;
8206
+ const { scope: _narrowing, ...unscopedRequest } = requestWithScope;
8207
+ const baseRequest = request.residency === "durable" ? unscopedRequest : requestWithScope;
7266
8208
  const durableRequest = withInheritedSessionPins({
7267
8209
  ...baseRequest,
8210
+ ...inheritedScope ? { inheritedScope } : {},
7268
8211
  ...kernel ? { kernel, pythonRuntime: this.manager.resolvePythonRuntime() } : {},
7269
8212
  extensions: request.extensions ?? this.manager.config.extensions,
7270
- ...request.residency === "durable" && request.cwd !== void 0 ? { cwd: this.manager.resolveCwd(request.cwd) } : {}
8213
+ ...request.residency === "durable" && request.cwd !== void 0 ? { cwd: this.manager.resolveCwd(request.cwd) } : {},
8214
+ // The resident host does not know this session's bounds: send them narrowed.
8215
+ ...request.residency === "durable" ? { thinkingBounds: this.manager.childThinkingBounds(request.thinkingBounds) } : {}
7271
8216
  }, context.extensionContext.sessionManager?.getEntries?.() ?? []);
7272
8217
  const handle = durableRequest.residency === "durable" ? await this.#resident().spawnAgent(durableRequest, context.signal) : await this.manager.spawn(durableRequest, context.signal);
7273
8218
  if (request.residency !== "durable") this.manager.detachSignal(handle.id);
@@ -7343,8 +8288,11 @@ var AgentsProvider = class {
7343
8288
  ...args.includeStale === true ? { includeStale: true } : {}
7344
8289
  });
7345
8290
  }
7346
- case "self":
7347
- return this.participants.self();
8291
+ case "self": {
8292
+ const self = await this.participants.self();
8293
+ const lineage = readAgentLineage();
8294
+ return lineage ? { ...self, lineage } : self;
8295
+ }
7348
8296
  case "main":
7349
8297
  return this.mainAgent.info(context.extensionContext);
7350
8298
  case "sessions":
@@ -7379,7 +8327,11 @@ var AgentsProvider = class {
7379
8327
  case "unsubscribe":
7380
8328
  return this.lifecycle.unsubscribe(String(args.id));
7381
8329
  case "models": {
7382
- const runner = args.runner === "pi" || args.runner === "claude" || args.runner === "veda" ? args.runner : this.manager.config.runner;
8330
+ const runner = checkedRunner(args.runner, this.manager.config.runner);
8331
+ const runnerAdapter = requireAgentRunner(runner);
8332
+ if (!BUILT_IN_RUNNER_IDS.has(runner)) {
8333
+ return runnerAdapter.models ? [...await runnerAdapter.models({ cwd: this.manager.cwd, refresh: args.refresh === true })] : [];
8334
+ }
7383
8335
  if (runner === "veda") {
7384
8336
  return [];
7385
8337
  }
@@ -7545,7 +8497,8 @@ var AgentsProvider = class {
7545
8497
  {
7546
8498
  message: message2,
7547
8499
  ...args.data === void 0 ? {} : { data: args.data },
7548
- ...needsBinding ? { binding } : {}
8500
+ ...needsBinding ? { binding } : {},
8501
+ ...participant.ownerIncarnation ? { ownerIncarnation: participant.ownerIncarnation } : {}
7549
8502
  },
7550
8503
  participant.ownerIdentityId,
7551
8504
  {
@@ -7724,6 +8677,17 @@ var AgentsProvider = class {
7724
8677
  }
7725
8678
  }
7726
8679
  async routeMessage(id2, message2, data, kind, context, options = {}) {
8680
+ if (isProviderParticipantRef(id2)) {
8681
+ return controlProviderParticipant(
8682
+ this.providerParticipants,
8683
+ this.participants,
8684
+ this.control,
8685
+ id2,
8686
+ kind,
8687
+ message2,
8688
+ data
8689
+ );
8690
+ }
7727
8691
  return this.#router.routeMessage(id2, message2, data, kind, context, options);
7728
8692
  }
7729
8693
  /** Flush pending coalesced lifecycle deliveries; used by tests and shutdown. */
@@ -7734,6 +8698,9 @@ var AgentsProvider = class {
7734
8698
  this.#lifecycleScheduler.schedule(subscription.to, { subscription, event });
7735
8699
  }
7736
8700
  async acceptControl(command, from, signal) {
8701
+ if (isProviderParticipantRef(command.targetId)) {
8702
+ return acceptProviderParticipantControl(this.providerParticipants, command);
8703
+ }
7737
8704
  return this.#router.acceptControl(command, from, signal);
7738
8705
  }
7739
8706
  #resolveActorTarget(id2) {
@@ -7742,14 +8709,17 @@ var AgentsProvider = class {
7742
8709
  async #createActor(request) {
7743
8710
  const extensions = request.extensions ?? true;
7744
8711
  const kernel = this.manager.resolveKernel({ ...request, extensions });
7745
- const { kernel: _requestedKernel, ...baseRequest } = request;
8712
+ const { kernel: _requestedKernel, principalScope: _forged, ...baseRequest } = request;
8713
+ const principalScope = sessionScope();
7746
8714
  request = {
7747
8715
  ...baseRequest,
7748
8716
  runner: request.runner ?? this.manager.config.runner,
7749
8717
  extensions,
7750
- ...kernel ? { kernel, pythonRuntime: this.manager.resolvePythonRuntime(request.pythonRuntime) } : {}
8718
+ ...kernel ? { kernel, pythonRuntime: this.manager.resolvePythonRuntime(request.pythonRuntime) } : {},
8719
+ ...principalScope ? { principalScope } : {}
7751
8720
  };
7752
8721
  if (request.residency !== "durable") return this.actorManager.create(request);
8722
+ this.#assertUnconfinedDurable();
7753
8723
  if (!this.residency) return this.#residentActorClient().createActor(request);
7754
8724
  await this.residency.ensureHost();
7755
8725
  let actor;
@@ -7762,6 +8732,44 @@ var AgentsProvider = class {
7762
8732
  await this.#activateDurableActor(actor);
7763
8733
  return actor;
7764
8734
  }
8735
+ // The shared resident host cannot inherit this process's write confinement;
8736
+ // scope travels with the request (inheritedScope, principalScope) instead.
8737
+ #assertUnconfinedDurable() {
8738
+ if (process.env.PI_FABRIC_WRITE_POLICY) {
8739
+ throw new Error("A write-confined agent cannot start durable agents or actors");
8740
+ }
8741
+ }
8742
+ /** seed: "branch" forks the caller's completed turns; "snippet" prefixes recent text. */
8743
+ #applySeed(args, request, context) {
8744
+ const { seed, seedMessages } = checkedSeed(args.seed, args.seedMessages);
8745
+ if (seed === "task") return request;
8746
+ if ((request.runner ?? this.manager.config.runner) !== "pi") {
8747
+ throw new Error(`seed: "${seed}" requires the Pi runner`);
8748
+ }
8749
+ const session = context.extensionContext.sessionManager;
8750
+ const branch = session?.getBranch?.();
8751
+ if (!session || !branch) throw new Error(`seed: "${seed}" requires a Pi session`);
8752
+ if (seed === "snippet") return { ...request, task: snippetTask(branch, seedMessages, request.task) };
8753
+ if (request.residency === "durable") {
8754
+ throw new Error('seed: "branch" is unavailable for durable agents; use seed: "snippet"');
8755
+ }
8756
+ const model = context.extensionContext.model;
8757
+ const sourceSessionFile = session.getSessionFile?.();
8758
+ const thinkingTransfer = request.model ? resolveThinkingTransfer(
8759
+ context.extensionContext,
8760
+ request.model,
8761
+ model ? { provider: model.provider, modelId: model.id } : void 0
8762
+ ) : void 0;
8763
+ return {
8764
+ ...request,
8765
+ forkSeed: {
8766
+ sourceSessionId: session.getSessionId(),
8767
+ ...sourceSessionFile ? { sourceSessionFile } : {},
8768
+ sourceBranch: completedBranchPrefix(branch)
8769
+ },
8770
+ ...thinkingTransfer ? { thinkingTransfer } : {}
8771
+ };
8772
+ }
7765
8773
  #residentActorClient() {
7766
8774
  const client = ResidentActorClient.fromEnv();
7767
8775
  if (client) return client;
@@ -7820,6 +8828,9 @@ var AgentsProvider = class {
7820
8828
  return value === "local" || value === "lineage" || value === "project" ? value : fallback;
7821
8829
  }
7822
8830
  async stopParticipant(id2) {
8831
+ if (isProviderParticipantRef(id2)) {
8832
+ return controlProviderParticipant(this.providerParticipants, this.participants, this.control, id2, "stop");
8833
+ }
7823
8834
  try {
7824
8835
  const result2 = await this.manager.stop(id2);
7825
8836
  this.participants.scheduleRefresh();
@@ -7848,7 +8859,7 @@ var AgentsProvider = class {
7848
8859
  participant.ownerHostId,
7849
8860
  participant.id,
7850
8861
  "stop",
7851
- {},
8862
+ participant.ownerIncarnation ? { ownerIncarnation: participant.ownerIncarnation } : {},
7852
8863
  participant.ownerIdentityId
7853
8864
  );
7854
8865
  if (this.residency?.hasAgent(id2)) this.residency.acknowledgeCompletion(id2);
@@ -7875,6 +8886,39 @@ var AgentsProvider = class {
7875
8886
  // src/providers/compact-provider.ts
7876
8887
  import { Type } from "typebox";
7877
8888
  import { Value as Value2 } from "typebox/value";
8889
+
8890
+ // src/compaction/pressure.ts
8891
+ var positiveWindow = (value) => typeof value === "number" && Number.isFinite(value) && value > 0 ? value : void 0;
8892
+ var compactionPressure = (context, config) => {
8893
+ let usage;
8894
+ try {
8895
+ usage = context?.getContextUsage?.();
8896
+ } catch {
8897
+ usage = void 0;
8898
+ }
8899
+ const modelKey = modelCompactionKey(context?.model);
8900
+ const thresholdTokens = modelKey === void 0 ? void 0 : config.tokenThresholds[modelKey];
8901
+ const thresholdFraction = modelKey === void 0 || thresholdTokens !== void 0 ? void 0 : config.thresholds[modelKey];
8902
+ const contextWindow = positiveWindow(usage?.contextWindow) ?? positiveWindow(context?.model?.contextWindow);
8903
+ const tokens = typeof usage?.tokens === "number" && Number.isFinite(usage.tokens) ? usage.tokens : null;
8904
+ const known = tokens !== null && contextWindow !== void 0;
8905
+ const fraction = known ? tokens / contextWindow : null;
8906
+ const headroomTokens = known ? contextWindow - tokens : null;
8907
+ const band = fraction === null ? "unknown" : fraction >= config.pressureBands.urgent || outputReserveBreached({ tokens, contextWindow }, config.outputReserveTokens) ? "urgent" : fraction >= config.pressureBands.warn ? "warn" : "ok";
8908
+ return {
8909
+ tokens,
8910
+ contextWindow: contextWindow ?? null,
8911
+ fraction,
8912
+ headroomTokens,
8913
+ band,
8914
+ outputReserveTokens: config.outputReserveTokens,
8915
+ ...thresholdFraction !== void 0 ? { thresholdFraction } : {},
8916
+ ...thresholdTokens !== void 0 ? { thresholdTokens } : {},
8917
+ owner: ownerFromContext(context)
8918
+ };
8919
+ };
8920
+
8921
+ // src/providers/compact-provider.ts
7878
8922
  var requestSchema = Type.Object({
7879
8923
  reason: Type.Optional(Type.String({
7880
8924
  maxLength: 1024,
@@ -7920,6 +8964,23 @@ var emptySchema = {
7920
8964
  properties: {},
7921
8965
  additionalProperties: false
7922
8966
  };
8967
+ var carryItemsSchema = (description) => Type.Optional(Type.Array(
8968
+ Type.String({ minLength: 1, maxLength: MAX_CARRY_ITEM_CHARS }),
8969
+ { maxItems: MAX_CARRY_ITEMS, description }
8970
+ ));
8971
+ var carrySchema = Type.Object({
8972
+ items: carryItemsSchema("Replace the carry-forward list"),
8973
+ add: carryItemsSchema("Append items not already present"),
8974
+ remove: carryItemsSchema("Remove exact items"),
8975
+ clear: Type.Optional(Type.Boolean({ description: "Empty the list before applying items/add" }))
8976
+ }, { additionalProperties: false });
8977
+ var checkedCarryArguments = (args) => {
8978
+ if (!Value2.Check(carrySchema, args)) {
8979
+ const message2 = [...Value2.Errors(carrySchema, args)].slice(0, 5).map((error) => error.message).join("; ");
8980
+ throw new Error(`Invalid compact.carry arguments: ${message2}`);
8981
+ }
8982
+ return args;
8983
+ };
7923
8984
  var descriptors = [
7924
8985
  {
7925
8986
  name: "request",
@@ -7933,6 +8994,20 @@ var descriptors = [
7933
8994
  inputSchema: emptySchema,
7934
8995
  risk: "read"
7935
8996
  },
8997
+ {
8998
+ name: "pressure",
8999
+ description: "Read host context pressure: tokens, window, fraction, headroom, band (ok/warn/urgent/unknown), output reserve, configured threshold, and the observed compaction owner",
9000
+ inputSchema: emptySchema,
9001
+ risk: "read"
9002
+ },
9003
+ {
9004
+ name: "carry",
9005
+ description: "Read or update the persistent carry-forward focus list that Fabric's compactor renders in every summary until cleared. No arguments reads it.",
9006
+ inputSchema: carrySchema,
9007
+ // A persisted session entry that changes every later summary: a control
9008
+ // write, classified like request.
9009
+ risk: "write"
9010
+ },
7936
9011
  {
7937
9012
  name: "cancel",
7938
9013
  description: "Clear a pending compaction intent before the host commits it",
@@ -7944,12 +9019,41 @@ var descriptors = [
7944
9019
  }
7945
9020
  ];
7946
9021
  var normalizeCompactArgs = actionArgNormalizer(() => descriptors);
9022
+ var branchOf = (context) => {
9023
+ try {
9024
+ const branch = context.extensionContext?.sessionManager?.getBranch?.();
9025
+ return Array.isArray(branch) ? branch : void 0;
9026
+ } catch {
9027
+ return void 0;
9028
+ }
9029
+ };
7947
9030
  var CompactProvider = class {
7948
- constructor(controller) {
9031
+ constructor(controller, options = {}) {
7949
9032
  this.controller = controller;
9033
+ this.options = options;
7950
9034
  }
7951
9035
  name = "compact";
7952
9036
  description = "Programmatic, advisory-then-committed context compaction for the host Pi session";
9037
+ #config() {
9038
+ return this.options.config?.() ?? DEFAULT_FABRIC_CONFIG.compaction;
9039
+ }
9040
+ #carry(update, context) {
9041
+ const branch = branchOf(context);
9042
+ const current = branch ? latestCarryItems(branch) : [];
9043
+ if (!isCarryUpdate(update)) return { items: current };
9044
+ if (!branch || !this.options.appendEntry) {
9045
+ throw new Error("compact.carry cannot persist: no host session is available");
9046
+ }
9047
+ const items = applyCarryUpdate(current, update);
9048
+ if (!sameCarryItems(current, items)) {
9049
+ this.options.appendEntry(COMPACTION_CARRY_ENTRY_TYPE, { version: 1, items });
9050
+ context.activity?.({
9051
+ type: "progress",
9052
+ message: items.length > 0 ? `Compaction carry-forward: ${items.length} item${items.length === 1 ? "" : "s"}` : "Compaction carry-forward cleared"
9053
+ });
9054
+ }
9055
+ return { items };
9056
+ }
7953
9057
  async list(request, _context) {
7954
9058
  const query = request.query?.toLowerCase();
7955
9059
  return query ? descriptors.filter(
@@ -7985,7 +9089,15 @@ var CompactProvider = class {
7985
9089
  return { requested: true, intent };
7986
9090
  }
7987
9091
  case "status":
7988
- return this.controller.status();
9092
+ return {
9093
+ ...this.controller.status(),
9094
+ owner: ownerFromContext(context.extensionContext),
9095
+ outputReserveTokens: this.#config().outputReserveTokens
9096
+ };
9097
+ case "pressure":
9098
+ return compactionPressure(context.extensionContext, this.#config());
9099
+ case "carry":
9100
+ return this.#carry(checkedCarryArguments(args), context);
7989
9101
  case "cancel":
7990
9102
  this.controller.cancel();
7991
9103
  context.activity?.({ type: "progress", message: "Compaction request cancelled" });
@@ -7997,13 +9109,16 @@ var CompactProvider = class {
7997
9109
  };
7998
9110
 
7999
9111
  // src/cache/leases.ts
8000
- import { createHash as createHash2, randomUUID as randomUUID5 } from "node:crypto";
9112
+ import { createHash as createHash2, randomUUID as randomUUID6 } from "node:crypto";
8001
9113
  var MAX_CACHE_LEASE_MS = 30 * 6e4;
8002
9114
  var MAX_CACHE_LEASES = 128;
8003
9115
  var CacheLeases = class {
8004
- constructor(pi, sessionId) {
9116
+ // Full code mode keeps tools active but hides declarations, so the declared
9117
+ // foreground set is a fence input beside the active names.
9118
+ constructor(pi, sessionId, foregroundTools = () => []) {
8005
9119
  this.pi = pi;
8006
9120
  this.sessionId = sessionId;
9121
+ this.foregroundTools = foregroundTools;
8007
9122
  }
8008
9123
  #leases = /* @__PURE__ */ new Map();
8009
9124
  #unsubscribe = [];
@@ -8028,7 +9143,8 @@ var CacheLeases = class {
8028
9143
  context.model?.id,
8029
9144
  context.thinkingLevel ?? this.pi.getThinkingLevel(),
8030
9145
  context.getSystemPrompt(),
8031
- [...this.pi.getActiveTools()].sort()
9146
+ [...this.pi.getActiveTools()].sort(),
9147
+ [...this.foregroundTools()].sort()
8032
9148
  ])).digest("hex");
8033
9149
  }
8034
9150
  reconcile(context) {
@@ -8087,7 +9203,7 @@ var CacheLeases = class {
8087
9203
  }
8088
9204
  }
8089
9205
  const value = {
8090
- id: randomUUID5(),
9206
+ id: randomUUID6(),
8091
9207
  scope,
8092
9208
  sessionId: this.sessionId,
8093
9209
  model: `${context.model.provider}/${context.model.id}`,
@@ -8279,10 +9395,10 @@ function checked(action, args) {
8279
9395
  if (error) throw new Error(`Invalid cache.${action} arguments: ${error}`);
8280
9396
  }
8281
9397
  var CacheProvider = class {
8282
- constructor(pi, context, isMain) {
9398
+ constructor(pi, context, isMain, foregroundTools) {
8283
9399
  this.isMain = isMain;
8284
9400
  this.#sessionId = context.sessionManager.getSessionId();
8285
- this.#leases = new CacheLeases(pi, this.#sessionId);
9401
+ this.#leases = new CacheLeases(pi, this.#sessionId, foregroundTools);
8286
9402
  }
8287
9403
  name = "cache";
8288
9404
  description = "Observed prompt-cache usage and optional native scoped warming; not a key/value or tool-result cache";
@@ -8349,9 +9465,226 @@ var CacheProvider = class {
8349
9465
  }
8350
9466
  };
8351
9467
 
8352
- // src/providers/prewalk-provider.ts
9468
+ // src/providers/thinking-provider.ts
8353
9469
  var emptySchema2 = { type: "object", properties: {}, additionalProperties: false };
9470
+ var setSchema = {
9471
+ type: "object",
9472
+ required: ["level"],
9473
+ additionalProperties: false,
9474
+ properties: {
9475
+ level: { type: "string", enum: [...THINKING_LEVELS], description: "Requested level; clamped into thinking.bounds and the model's supported levels" },
9476
+ scope: {
9477
+ type: "string",
9478
+ enum: ["turn", "turns", "session"],
9479
+ description: "turn (default) reverts at the next agent_end; turns reverts after `turns` agent_end events (the current run counts); session lasts until thinking.reset()"
9480
+ },
9481
+ turns: { type: "integer", minimum: 1, maximum: MAX_THINKING_OVERRIDE_TURNS, description: 'Required with scope "turns"; invalid otherwise' },
9482
+ reason: { type: "string", maxLength: MAX_THINKING_REASON_CHARS }
9483
+ }
9484
+ };
9485
+ var resource = ["pi:thinking-level"];
8354
9486
  var descriptors3 = [
9487
+ {
9488
+ name: "status",
9489
+ description: "Read the host session's thinking level, model-supported levels inside the effective bounds, the baseline, and any active Fabric override",
9490
+ inputSchema: emptySchema2,
9491
+ risk: "read",
9492
+ effect: { kind: "none", resources: resource, ordering: "commutative" }
9493
+ },
9494
+ {
9495
+ name: "set",
9496
+ description: "Temporarily change the host session's thinking level for this turn, N turns, or the session. Clamped into bounds and model support (reports clamped/requested). Reverts to the baseline at agent_end; restored after reload.",
9497
+ inputSchema: setSchema,
9498
+ risk: "write",
9499
+ effect: { kind: "emission", resources: resource, ordering: "ordered" }
9500
+ },
9501
+ {
9502
+ name: "reset",
9503
+ description: "End any Fabric thinking override and restore the baseline level",
9504
+ inputSchema: emptySchema2,
9505
+ risk: "write",
9506
+ effect: { kind: "emission", resources: resource, ordering: "ordered" }
9507
+ }
9508
+ ];
9509
+ var normalizeThinkingArgs = actionArgNormalizer(() => descriptors3);
9510
+ var ThinkingProvider = class {
9511
+ constructor(controller, sessionId) {
9512
+ this.controller = controller;
9513
+ this.sessionId = sessionId;
9514
+ }
9515
+ name = "thinking";
9516
+ description = "Bounded host-session thinking (reasoning effort) control";
9517
+ async list(request) {
9518
+ const query = request.query?.toLowerCase();
9519
+ return descriptors3.filter((action) => !query || `${action.name} ${action.description}`.toLowerCase().includes(query));
9520
+ }
9521
+ async describe(name) {
9522
+ return descriptors3.find((action) => action.name === name);
9523
+ }
9524
+ prepareArguments(name, args) {
9525
+ return normalizeThinkingArgs(name, args);
9526
+ }
9527
+ async invoke(name, args, context) {
9528
+ const descriptor = descriptors3.find((action) => action.name === name);
9529
+ if (!descriptor) throw new Error(`Unknown thinking action: ${name}`);
9530
+ const error = validationMessage(descriptor.inputSchema, args);
9531
+ if (error) throw new Error(`Invalid thinking.${name} arguments: ${error}`);
9532
+ const host = context.extensionContext;
9533
+ if (host.sessionManager.getSessionId() !== this.sessionId) {
9534
+ throw new Error("Thinking provider belongs to a different session");
9535
+ }
9536
+ if (name === "status") return this.controller.status(host);
9537
+ if (name === "reset") {
9538
+ const status = this.controller.reset(host);
9539
+ context.activity?.({ type: "progress", message: `Thinking level reset to ${status.level}` });
9540
+ return status;
9541
+ }
9542
+ const result = this.controller.set(args, host);
9543
+ context.activity?.({
9544
+ type: "progress",
9545
+ message: result.clamped ? `Thinking level ${result.level} (requested ${result.requested}, clamped)` : `Thinking level ${result.level} (${result.override?.scope ?? "turn"})`
9546
+ });
9547
+ return result;
9548
+ }
9549
+ };
9550
+
9551
+ // src/providers/programs-provider.ts
9552
+ var resource2 = ["fabric:programs"];
9553
+ var refSchema = { type: "string", minLength: 1, maxLength: MAX_PROGRAM_REF_CHARS };
9554
+ var descriptors4 = [
9555
+ {
9556
+ name: "save",
9557
+ description: 'Save a program as a content-addressed candidate; identical content returns the same ref. Returns { ref: "name@digest12", digest }',
9558
+ inputSchema: {
9559
+ type: "object",
9560
+ required: ["name"],
9561
+ additionalProperties: false,
9562
+ properties: {
9563
+ name: { type: "string", minLength: 1, maxLength: MAX_PROGRAM_NAME_CHARS, pattern: "^[a-z0-9][a-z0-9._-]*$" },
9564
+ kind: { type: "string", enum: ["fabric", "jev"] },
9565
+ kernel: { type: "string", enum: ["typescript", "python"] },
9566
+ code: { type: "string", minLength: 1, maxLength: MAX_PROGRAM_CODE_CHARS },
9567
+ jevProgram: { type: "object" },
9568
+ description: { type: "string", maxLength: MAX_PROGRAM_DESCRIPTION_CHARS },
9569
+ inputSchema: { type: "object" }
9570
+ }
9571
+ },
9572
+ risk: "write",
9573
+ namespace: "programs",
9574
+ effect: { kind: "transactional", resources: resource2, ordering: "ordered" }
9575
+ },
9576
+ {
9577
+ name: "list",
9578
+ description: "List saved programs newest first per name, optionally by name and status (candidate, promoted, retired)",
9579
+ inputSchema: {
9580
+ type: "object",
9581
+ additionalProperties: false,
9582
+ properties: {
9583
+ name: { type: "string", minLength: 1, maxLength: MAX_PROGRAM_NAME_CHARS },
9584
+ status: { type: "string", enum: ["candidate", "promoted", "retired"] }
9585
+ }
9586
+ },
9587
+ risk: "read",
9588
+ namespace: "programs",
9589
+ effect: { kind: "none", resources: resource2, ordering: "commutative" }
9590
+ },
9591
+ {
9592
+ name: "get",
9593
+ description: "Read one saved program by ref: name (latest promoted, else latest candidate), name@<digest prefix \u226512>, or a full digest",
9594
+ inputSchema: {
9595
+ type: "object",
9596
+ required: ["ref"],
9597
+ additionalProperties: false,
9598
+ properties: { ref: refSchema }
9599
+ },
9600
+ risk: "read",
9601
+ namespace: "programs",
9602
+ effect: { kind: "none", resources: resource2, ordering: "commutative" }
9603
+ },
9604
+ {
9605
+ name: "run",
9606
+ description: "Run a saved program nested in this execution with the caller's capabilities and approvals; input becomes the program's `input` global. Returns the program's result",
9607
+ inputSchema: {
9608
+ type: "object",
9609
+ required: ["ref"],
9610
+ additionalProperties: false,
9611
+ properties: {
9612
+ ref: refSchema,
9613
+ input: {},
9614
+ requirePromoted: { type: "boolean" }
9615
+ }
9616
+ },
9617
+ risk: "execute",
9618
+ namespace: "programs"
9619
+ }
9620
+ ];
9621
+ var normalizeProgramsArgs = actionArgNormalizer(() => descriptors4);
9622
+ var ProgramsProvider = class {
9623
+ constructor(store, defaultKernel, nestedRunner) {
9624
+ this.store = store;
9625
+ this.defaultKernel = defaultKernel;
9626
+ this.nestedRunner = nestedRunner;
9627
+ }
9628
+ name = "programs";
9629
+ description = "Content-addressed saved programs run nested in the caller's execution";
9630
+ async list(request) {
9631
+ const query = request.query?.toLowerCase();
9632
+ return descriptors4.filter((action) => !query || `${action.name} ${action.description}`.toLowerCase().includes(query));
9633
+ }
9634
+ async describe(name) {
9635
+ return descriptors4.find((action) => action.name === name);
9636
+ }
9637
+ prepareArguments(name, args) {
9638
+ return normalizeProgramsArgs(name, args);
9639
+ }
9640
+ async invoke(name, args, context) {
9641
+ const descriptor = descriptors4.find((action) => action.name === name);
9642
+ if (!descriptor) throw new Error(`Unknown programs action: ${name}`);
9643
+ const error = validationMessage(descriptor.inputSchema, args);
9644
+ if (error) throw new Error(`Invalid programs.${name} arguments: ${error}`);
9645
+ switch (name) {
9646
+ case "save": {
9647
+ const { record, created } = await this.store.save(args, this.defaultKernel());
9648
+ if (created) context.activity?.({ type: "progress", message: `Program saved: ${programRef(record)}` });
9649
+ return { ref: programRef(record), digest: record.digest };
9650
+ }
9651
+ case "list":
9652
+ return this.store.list({
9653
+ ...typeof args.name === "string" ? { name: args.name } : {},
9654
+ ...typeof args.status === "string" ? { status: args.status } : {}
9655
+ });
9656
+ case "get": {
9657
+ const record = await this.store.resolve(args.ref);
9658
+ return { ref: programRef(record), ...record };
9659
+ }
9660
+ case "run":
9661
+ return this.#run(args, context);
9662
+ default:
9663
+ throw new Error(`Unknown programs action: ${name}`);
9664
+ }
9665
+ }
9666
+ async #run(args, context) {
9667
+ const runner = this.nestedRunner(context.parentToolCallId);
9668
+ if (!runner) throw new Error("programs.run runs only inside a fabric_exec program or a host program run");
9669
+ const record = await this.store.resolve(args.ref, { requirePromoted: args.requirePromoted === true });
9670
+ const label = programRef(record, true);
9671
+ if (record.status === "retired") throw new Error(`Program ${label} is retired; a user can promote it again with /fabric programs promote`);
9672
+ const input = normalizeProgramInput(args.input);
9673
+ const invalid = programInputError(record, input);
9674
+ if (invalid) throw new Error(`Invalid input for program ${label}: ${invalid}`);
9675
+ if (record.kind === "jev") {
9676
+ return runner.run({ program: label, call: { ref: "jev.run", args: { program: record.jevProgram, input: input ?? null } } }, context.signal);
9677
+ }
9678
+ if (record.kernel !== runner.kernel) {
9679
+ throw new Error(`Program ${label} is a ${record.kernel} program; this session's kernel is ${runner.kernel}`);
9680
+ }
9681
+ return runner.run({ program: label, code: programSourceWithInput(record.code ?? "", runner.kernel, input) }, context.signal);
9682
+ }
9683
+ };
9684
+
9685
+ // src/providers/prewalk-provider.ts
9686
+ var emptySchema3 = { type: "object", properties: {}, additionalProperties: false };
9687
+ var descriptors5 = [
8355
9688
  {
8356
9689
  name: "plan",
8357
9690
  description: "Submit the executor handoff plan only when this session is awaiting one and Fabric's armed advisory or checkpoint requests it. Not a general task planner, checklist, or acceptance-ledger store. Include the outcome, ordered steps with exact files and checks, verification, and risks. Fabric delivers the recorded plan directly to the executor even if this action's return is discarded.",
@@ -8361,11 +9694,11 @@ var descriptors3 = [
8361
9694
  {
8362
9695
  name: "status",
8363
9696
  description: "Report the prewalk arm, plan readiness, the readiness kind claimed by an in-flight handoff, and the loaded build identity of the extension entry and lazy runtime versus the files currently on disk",
8364
- inputSchema: emptySchema2,
9697
+ inputSchema: emptySchema3,
8365
9698
  risk: "read"
8366
9699
  }
8367
9700
  ];
8368
- var normalizePrewalkArgs = actionArgNormalizer(() => descriptors3);
9701
+ var normalizePrewalkArgs = actionArgNormalizer(() => descriptors5);
8369
9702
  var PrewalkProvider = class {
8370
9703
  constructor(controller, options = {}) {
8371
9704
  this.controller = controller;
@@ -8378,7 +9711,7 @@ var PrewalkProvider = class {
8378
9711
  const planRequired = this.controller.planRequired(
8379
9712
  context.extensionContext.sessionManager.getSessionId()
8380
9713
  );
8381
- return descriptors3.filter(
9714
+ return descriptors5.filter(
8382
9715
  (descriptor) => (descriptor.name !== "plan" || planRequired) && (!query || `${descriptor.name} ${descriptor.description}`.toLowerCase().includes(query))
8383
9716
  );
8384
9717
  }
@@ -8447,7 +9780,7 @@ var changeProperties = {
8447
9780
  remove: { type: "array", items: { type: "string" }, maxItems: 256 },
8448
9781
  reset: { type: "array", items: { type: "string" }, maxItems: 256, description: "Session only: remove overlays and use trusted file configuration for these IDs." }
8449
9782
  };
8450
- var descriptors4 = [
9783
+ var descriptors6 = [
8451
9784
  {
8452
9785
  name: "list",
8453
9786
  description: "List registered component definitions and configured component instances.",
@@ -8523,16 +9856,16 @@ var ComponentsProvider = class {
8523
9856
  description = "Supervised component lifecycle, exact capability dependencies, effect cleanup, and reload diagnostics.";
8524
9857
  async list(request, _context) {
8525
9858
  const query = request.query?.normalize("NFKC").trim().toLowerCase();
8526
- const filtered = query ? descriptors4.filter(
9859
+ const filtered = query ? descriptors6.filter(
8527
9860
  (descriptor) => `${descriptor.name} ${descriptor.description}`.toLowerCase().includes(query)
8528
- ) : descriptors4;
9861
+ ) : descriptors6;
8529
9862
  return filtered.slice(0, Math.max(1, Math.min(request.limit ?? 100, 100)));
8530
9863
  }
8531
9864
  async describe(actionName, _context) {
8532
- return descriptors4.find((descriptor) => descriptor.name === actionName);
9865
+ return descriptors6.find((descriptor) => descriptor.name === actionName);
8533
9866
  }
8534
9867
  async invoke(actionName, args, context) {
8535
- const descriptor = descriptors4.find((action) => action.name === actionName);
9868
+ const descriptor = descriptors6.find((action) => action.name === actionName);
8536
9869
  if (descriptor) {
8537
9870
  const invalid = validationMessage(descriptor.inputSchema, args);
8538
9871
  if (invalid) throw new Error(`Invalid components.${actionName} arguments: ${invalid}`);
@@ -8638,11 +9971,11 @@ var CapturedToolsProvider = class {
8638
9971
  #allowedTools = readChildToolAllowlist();
8639
9972
  async list(request, _context) {
8640
9973
  const query = request.query?.trim().toLowerCase();
8641
- const descriptors10 = this.catalog.list().filter(
9974
+ const descriptors13 = this.catalog.list().filter(
8642
9975
  (entry) => (!this.#allowedTools || this.#allowedTools.has(entry.name)) && !this.omitFromDiscovery(entry)
8643
9976
  ).map(descriptorFrom);
8644
- if (!query) return descriptors10;
8645
- return descriptors10.filter(
9977
+ if (!query) return descriptors13;
9978
+ return descriptors13.filter(
8646
9979
  (descriptor) => `${descriptor.name} ${descriptor.description} ${descriptor.namespace ?? ""}`.toLowerCase().includes(query)
8647
9980
  );
8648
9981
  }
@@ -8902,7 +10235,11 @@ var PiNativeMcpTools = class {
8902
10235
  return this.#tools(server).map((entry) => this.#descriptor(entry)).filter((entry) => !query || `${entry.name} ${entry.description}`.toLowerCase().includes(query));
8903
10236
  }
8904
10237
  serverInfo() {
8905
- const tools = this.#tools();
10238
+ let tools = this.#tools();
10239
+ const indexed = new Set(tools.map((tool) => tool.server));
10240
+ if (this.servers.some((name) => !indexed.has(name)) && this.#pollLiveRegistrations()) {
10241
+ tools = this.#tools();
10242
+ }
8906
10243
  return this.servers.map((name) => {
8907
10244
  const selected = tools.filter((tool) => tool.server === name);
8908
10245
  return {
@@ -8915,17 +10252,35 @@ var PiNativeMcpTools = class {
8915
10252
  });
8916
10253
  }
8917
10254
  #resolve(server, requested) {
8918
- this.#refreshIndex();
8919
- const visible = this.#visibility();
8920
- const index = this.#indexes.get(server);
8921
- if (index) this.#checkMetadata(index, visible);
8922
- const candidates = index?.exact.get(requested) ?? index?.aliases.get(requested) ?? [];
8923
- const matches = candidates.filter((entry) => visible(entry.registered));
10255
+ const attempt = () => {
10256
+ this.#refreshIndex();
10257
+ const visible = this.#visibility();
10258
+ const index = this.#indexes.get(server);
10259
+ if (index) this.#checkMetadata(index, visible);
10260
+ const candidates = index?.exact.get(requested) ?? index?.aliases.get(requested) ?? [];
10261
+ return candidates.filter((entry) => visible(entry.registered));
10262
+ };
10263
+ let matches = attempt();
10264
+ if (matches.length !== 1 && this.#pollLiveRegistrations()) matches = attempt();
8924
10265
  if (matches.length !== 1) {
8925
10266
  throw new Error(`Unknown or ambiguous Pi MCP tool: ${server}.${requested}. Check /mcp and the tool exposure; no mcporter fallback was attempted.`);
8926
10267
  }
8927
10268
  return matches[0];
8928
10269
  }
10270
+ // Mirrors Pi's "waits for the servers it names" semantics inside the borrow
10271
+ // layer: never polls on a timer, only once per failed lookup, and reports
10272
+ // change only when the capture catalog actually moved.
10273
+ #pollLiveRegistrations() {
10274
+ const runner = this.catalog.runner;
10275
+ if (typeof runner?.getAllRegisteredTools !== "function") return false;
10276
+ const before = this.catalog.registeredTools();
10277
+ try {
10278
+ runner.getAllRegisteredTools();
10279
+ } catch {
10280
+ return false;
10281
+ }
10282
+ return this.catalog.registeredTools() !== before;
10283
+ }
8929
10284
  describe(server, tool) {
8930
10285
  return this.#descriptor(this.#resolve(server, tool));
8931
10286
  }
@@ -8966,11 +10321,35 @@ var PiNativeMcpTools = class {
8966
10321
  };
8967
10322
 
8968
10323
  // src/providers/mesh-provider.ts
8969
- var emptySchema3 = { type: "object", properties: {}, additionalProperties: false };
8970
- var INTERNAL_STATE_PREFIXES = ["topology/", "sessions/", "actors/", "residency/"];
10324
+ var emptySchema4 = { type: "object", properties: {}, additionalProperties: false };
10325
+ var INTERNAL_STATE_PREFIXES = ["topology/", "sessions/", "actors/", "residency/", "decisions/"];
8971
10326
  var PRIVATE_STATE_PREFIXES = ["residency/"];
8972
10327
  var INTERNAL_CONTROL_PREFIX = "fabric.control.";
8973
10328
  var INTERNAL_HOST_EVENT_TOPIC = "fabric.actor.host-event";
10329
+ var assertPublicMeshTopic = (topic) => {
10330
+ if (topic.startsWith(INTERNAL_CONTROL_PREFIX) || topic === INTERNAL_HOST_EVENT_TOPIC || topic === FABRIC_PARTICIPANT_LIFECYCLE_TOPIC) {
10331
+ throw new Error(`Fabric mesh topic is reserved for host coordination: ${topic}`);
10332
+ }
10333
+ return topic;
10334
+ };
10335
+ var meshScheduleDueAt = (args, now = Date.now()) => {
10336
+ if (args.notBefore !== void 0 && args.afterMs !== void 0) {
10337
+ throw new Error("mesh.publish accepts notBefore or afterMs, not both");
10338
+ }
10339
+ if (args.afterMs !== void 0) {
10340
+ const afterMs = args.afterMs;
10341
+ if (typeof afterMs !== "number" || !Number.isFinite(afterMs) || afterMs < 0) {
10342
+ throw new Error("mesh.publish afterMs must be a nonnegative number of milliseconds");
10343
+ }
10344
+ return now + Math.ceil(afterMs);
10345
+ }
10346
+ if (args.notBefore === void 0) return void 0;
10347
+ const dueAt = typeof args.notBefore === "number" ? args.notBefore : typeof args.notBefore === "string" && /^\d{4}-\d{2}-\d{2}T/.test(args.notBefore) ? Date.parse(args.notBefore) : Number.NaN;
10348
+ if (!Number.isFinite(dueAt) || dueAt < 0) {
10349
+ throw new Error("mesh.publish notBefore must be epoch milliseconds or an ISO 8601 date-time");
10350
+ }
10351
+ return Math.ceil(dueAt);
10352
+ };
8974
10353
  var assertPublicStateKey = (key) => {
8975
10354
  if (INTERNAL_STATE_PREFIXES.some((prefix) => key.startsWith(prefix))) {
8976
10355
  throw new Error(`Fabric mesh key is reserved for host coordination: ${key}`);
@@ -8981,17 +10360,17 @@ var assertReadableStateKey = (key) => {
8981
10360
  throw new Error(`Fabric mesh key is private host state: ${key}`);
8982
10361
  }
8983
10362
  };
8984
- var descriptors5 = [
10363
+ var descriptors7 = [
8985
10364
  {
8986
10365
  name: "self",
8987
10366
  description: "Return this Fabric participant's mesh identity",
8988
- inputSchema: emptySchema3,
10367
+ inputSchema: emptySchema4,
8989
10368
  risk: "read",
8990
10369
  namespace: "coordination"
8991
10370
  },
8992
10371
  {
8993
10372
  name: "publish",
8994
- description: "Append a durable event to a mesh topic, optionally addressed to one actor",
10373
+ description: "Append a durable event to a mesh topic, optionally addressed to one actor. notBefore (epoch ms or ISO) or afterMs schedules it instead; key makes the schedule replaceable",
8995
10374
  inputSchema: {
8996
10375
  type: "object",
8997
10376
  properties: {
@@ -8999,7 +10378,10 @@ var descriptors5 = [
8999
10378
  kind: { type: "string" },
9000
10379
  to: { type: "string" },
9001
10380
  text: { type: "string" },
9002
- data: {}
10381
+ data: {},
10382
+ notBefore: { anyOf: [{ type: "number", minimum: 0 }, { type: "string", maxLength: 64 }] },
10383
+ afterMs: { type: "number", minimum: 0, maximum: MESH_MAX_SCHEDULE_AHEAD_MS },
10384
+ key: { type: "string", minLength: 1, maxLength: 128 }
9003
10385
  },
9004
10386
  required: ["topic"],
9005
10387
  additionalProperties: false
@@ -9007,6 +10389,69 @@ var descriptors5 = [
9007
10389
  risk: "agent",
9008
10390
  namespace: "coordination"
9009
10391
  },
10392
+ {
10393
+ name: "scheduled",
10394
+ description: "List pending scheduled mesh events by due time",
10395
+ inputSchema: {
10396
+ type: "object",
10397
+ properties: {
10398
+ topic: { type: "string" },
10399
+ limit: { type: "number", minimum: 1, maximum: MESH_MAX_PENDING_SCHEDULES }
10400
+ },
10401
+ additionalProperties: false
10402
+ },
10403
+ risk: "read",
10404
+ namespace: "coordination"
10405
+ },
10406
+ {
10407
+ name: "unschedule",
10408
+ description: "Cancel a pending scheduled mesh event by key",
10409
+ inputSchema: {
10410
+ type: "object",
10411
+ properties: { key: { type: "string", minLength: 1, maxLength: 128 } },
10412
+ required: ["key"],
10413
+ additionalProperties: false
10414
+ },
10415
+ risk: "agent",
10416
+ namespace: "coordination"
10417
+ },
10418
+ {
10419
+ name: "grant",
10420
+ description: "Mint a scoped token that lets an outside process post untrusted events to one topic through `pi-fabric mesh post`",
10421
+ inputSchema: {
10422
+ type: "object",
10423
+ properties: {
10424
+ topic: { type: "string" },
10425
+ ttlMs: { type: "number", minimum: MESH_GRANT_MIN_TTL_MS, maximum: MESH_GRANT_MAX_TTL_MS },
10426
+ uses: { type: "number", minimum: 1, maximum: MESH_GRANT_MAX_USES },
10427
+ kind: { type: "string", minLength: 1, maxLength: 128 }
10428
+ },
10429
+ required: ["topic", "ttlMs"],
10430
+ additionalProperties: false
10431
+ },
10432
+ // Opens an ingress for principals outside this session: the most conservative fitting class.
10433
+ risk: "network",
10434
+ namespace: "coordination"
10435
+ },
10436
+ {
10437
+ name: "revoke",
10438
+ description: "Revoke a scoped external mesh grant",
10439
+ inputSchema: {
10440
+ type: "object",
10441
+ properties: { grantId: { type: "string", minLength: 1, maxLength: 64 } },
10442
+ required: ["grantId"],
10443
+ additionalProperties: false
10444
+ },
10445
+ risk: "write",
10446
+ namespace: "coordination"
10447
+ },
10448
+ {
10449
+ name: "grants",
10450
+ description: "List unexpired external mesh grants (never tokens)",
10451
+ inputSchema: emptySchema4,
10452
+ risk: "read",
10453
+ namespace: "coordination"
10454
+ },
9010
10455
  {
9011
10456
  name: "read",
9012
10457
  description: "Read durable mesh events after a sequence cursor",
@@ -9100,7 +10545,7 @@ var descriptors5 = [
9100
10545
  namespace: "coordination"
9101
10546
  }
9102
10547
  ];
9103
- var normalizeMeshArgs = actionArgNormalizer(() => descriptors5);
10548
+ var normalizeMeshArgs = actionArgNormalizer(() => descriptors7);
9104
10549
  var MeshProvider = class {
9105
10550
  constructor(store, identity, participants) {
9106
10551
  this.store = store;
@@ -9111,12 +10556,12 @@ var MeshProvider = class {
9111
10556
  description = "Durable topics and compare-and-swap shared state for emergent agent coordination";
9112
10557
  async list(request, _context) {
9113
10558
  const query = request.query?.toLowerCase();
9114
- return query ? descriptors5.filter(
10559
+ return query ? descriptors7.filter(
9115
10560
  (descriptor) => `${descriptor.name} ${descriptor.description}`.toLowerCase().includes(query)
9116
- ) : descriptors5;
10561
+ ) : descriptors7;
9117
10562
  }
9118
10563
  async describe(actionName, _context) {
9119
- return descriptors5.find((descriptor) => descriptor.name === actionName);
10564
+ return descriptors7.find((descriptor) => descriptor.name === actionName);
9120
10565
  }
9121
10566
  prepareArguments(actionName, args) {
9122
10567
  return normalizeMeshArgs(actionName, args);
@@ -9126,20 +10571,59 @@ var MeshProvider = class {
9126
10571
  case "self":
9127
10572
  return this.identity;
9128
10573
  case "publish": {
9129
- const topic = String(args.topic);
9130
- if (topic.startsWith(INTERNAL_CONTROL_PREFIX) || topic === INTERNAL_HOST_EVENT_TOPIC || topic === FABRIC_PARTICIPANT_LIFECYCLE_TOPIC) {
9131
- throw new Error(`Fabric mesh topic is reserved for host coordination: ${topic}`);
9132
- }
9133
- return this.store.publish({
10574
+ const topic = assertPublicMeshTopic(String(args.topic));
10575
+ const message2 = {
9134
10576
  topic,
9135
10577
  from: this.identity,
9136
10578
  ...typeof args.kind === "string" ? { kind: args.kind } : {},
9137
10579
  ...typeof args.to === "string" ? { to: args.to } : {},
9138
10580
  ...typeof args.text === "string" ? { text: args.text } : {},
9139
10581
  ...args.data !== void 0 ? { data: args.data } : {}
10582
+ };
10583
+ const dueAt = meshScheduleDueAt(args);
10584
+ if (dueAt === void 0) {
10585
+ if (args.key !== void 0) throw new Error("mesh.publish key requires notBefore or afterMs");
10586
+ return this.store.publish(message2);
10587
+ }
10588
+ const schedule = await this.store.schedule({
10589
+ ...message2,
10590
+ dueAt,
10591
+ ...typeof args.key === "string" ? { key: args.key } : {}
10592
+ });
10593
+ return { scheduled: true, ...schedule };
10594
+ }
10595
+ case "scheduled":
10596
+ return this.store.scheduled({
10597
+ ...typeof args.topic === "string" ? { topic: args.topic } : {},
10598
+ ...typeof args.limit === "number" ? { limit: args.limit } : {}
10599
+ });
10600
+ case "unschedule":
10601
+ return this.store.unschedule(String(args.key));
10602
+ case "grant": {
10603
+ const topic = assertPublicMeshTopic(String(args.topic));
10604
+ const { grant, token } = await createMeshGrant(this.store, {
10605
+ topic,
10606
+ ttlMs: Number(args.ttlMs),
10607
+ ...typeof args.uses === "number" ? { uses: args.uses } : {},
10608
+ ...typeof args.kind === "string" ? { kind: args.kind } : {},
10609
+ createdBy: this.identity
9140
10610
  });
10611
+ return {
10612
+ ...grant,
10613
+ token,
10614
+ command: meshPostCommand(meshCliArgv(), {
10615
+ root: this.store.root,
10616
+ token,
10617
+ ...grant.kind !== void 0 ? { kind: grant.kind } : {}
10618
+ })
10619
+ };
9141
10620
  }
10621
+ case "revoke":
10622
+ return revokeMeshGrant(this.store, String(args.grantId));
10623
+ case "grants":
10624
+ return listMeshGrants(this.store);
9142
10625
  case "read":
10626
+ await this.store.releaseDueSchedules().catch(() => void 0);
9143
10627
  return this.store.read({
9144
10628
  ...typeof args.after === "number" ? { after: args.after } : {},
9145
10629
  ...typeof args.topic === "string" ? { topic: args.topic } : {},
@@ -9203,6 +10687,240 @@ var MeshProvider = class {
9203
10687
  }
9204
10688
  };
9205
10689
 
10690
+ // src/providers/decisions-provider.ts
10691
+ var resource3 = ["fabric:decisions"];
10692
+ var idSchema = { type: "string", minLength: 8, maxLength: 72 };
10693
+ var holderSchema = { type: "string", maxLength: 139 };
10694
+ var descriptors8 = [
10695
+ {
10696
+ name: "raise",
10697
+ description: "Create a durable open decision (approval, question, or escalation) for a human or holder to answer; returns { id }",
10698
+ inputSchema: {
10699
+ type: "object",
10700
+ required: ["title"],
10701
+ additionalProperties: false,
10702
+ properties: {
10703
+ kind: { type: "string", enum: ["approval", "question", "escalation"] },
10704
+ title: { type: "string", minLength: 1, maxLength: MAX_DECISION_TITLE_CHARS },
10705
+ body: { type: "string", maxLength: MAX_DECISION_BODY_CHARS },
10706
+ options: {
10707
+ type: "array",
10708
+ minItems: 1,
10709
+ maxItems: MAX_DECISION_OPTIONS,
10710
+ items: {
10711
+ type: "object",
10712
+ required: ["id", "label"],
10713
+ additionalProperties: false,
10714
+ properties: {
10715
+ id: { type: "string", minLength: 1, maxLength: 64 },
10716
+ label: { type: "string", minLength: 1, maxLength: MAX_DECISION_TITLE_CHARS }
10717
+ }
10718
+ }
10719
+ },
10720
+ input: { type: "string", enum: ["text", "confirm", "select", "editor"] },
10721
+ holder: {
10722
+ type: "string",
10723
+ maxLength: 139,
10724
+ description: '"user" (default, human only), "root" (root session), or "supervisor:<participantId>"'
10725
+ },
10726
+ deadline: { type: "number", description: "Epoch ms; at most 30 days ahead" },
10727
+ timeoutMs: { type: "integer", minimum: 1e3, maximum: MAX_DECISION_DEADLINE_MS },
10728
+ onExpire: { type: "string", enum: ["cancel", "default", "escalate"] },
10729
+ defaultOptionId: { type: "string", maxLength: 64 },
10730
+ escalation: {
10731
+ type: "object",
10732
+ additionalProperties: false,
10733
+ description: 'With onExpire "escalate": holders in order (default climbs supervisor -> root -> user), per-hop timeout, and what the last expiry does',
10734
+ properties: {
10735
+ chain: { type: "array", minItems: 1, maxItems: MAX_ESCALATION_HOPS, items: holderSchema },
10736
+ hopTimeoutMs: { type: "integer", minimum: MIN_ESCALATION_HOP_MS, maximum: MAX_ESCALATION_HOP_MS },
10737
+ onFinal: { type: "string", enum: ["cancel", "default"] }
10738
+ }
10739
+ }
10740
+ }
10741
+ },
10742
+ risk: "agent",
10743
+ namespace: "coordination",
10744
+ effect: { kind: "emission", resources: resource3, ordering: "ordered" }
10745
+ },
10746
+ {
10747
+ name: "wait",
10748
+ description: "Wait until a decision is answered, expires, or is cancelled (or timeoutMs passes) and return its record",
10749
+ inputSchema: {
10750
+ type: "object",
10751
+ required: ["id"],
10752
+ additionalProperties: false,
10753
+ properties: {
10754
+ id: idSchema,
10755
+ timeoutMs: { type: "integer", minimum: 0, maximum: MAX_DECISION_DEADLINE_MS }
10756
+ }
10757
+ },
10758
+ risk: "read",
10759
+ namespace: "coordination"
10760
+ },
10761
+ {
10762
+ name: "list",
10763
+ description: "List decisions newest first, optionally by status and current holder",
10764
+ inputSchema: {
10765
+ type: "object",
10766
+ additionalProperties: false,
10767
+ properties: {
10768
+ status: { type: "string", enum: ["open", "answered", "expired", "cancelled"] },
10769
+ holder: holderSchema,
10770
+ limit: { type: "integer", minimum: 1, maximum: 200 }
10771
+ }
10772
+ },
10773
+ risk: "read",
10774
+ namespace: "coordination",
10775
+ effect: { kind: "none", resources: resource3, ordering: "commutative" }
10776
+ },
10777
+ {
10778
+ name: "answer",
10779
+ description: 'Answer an open decision held by this participant (root or supervisor:<id>); never decisions held by "user"',
10780
+ inputSchema: {
10781
+ type: "object",
10782
+ required: ["id"],
10783
+ additionalProperties: false,
10784
+ properties: {
10785
+ id: idSchema,
10786
+ optionId: { type: "string", maxLength: 64 },
10787
+ text: { type: "string", maxLength: MAX_DECISION_TEXT_CHARS }
10788
+ }
10789
+ },
10790
+ risk: "agent",
10791
+ namespace: "coordination",
10792
+ effect: { kind: "emission", resources: resource3, ordering: "ordered" }
10793
+ },
10794
+ {
10795
+ name: "escalate",
10796
+ description: "Pass an open decision this participant holds to the next holder in its escalation chain now",
10797
+ inputSchema: {
10798
+ type: "object",
10799
+ required: ["id"],
10800
+ additionalProperties: false,
10801
+ properties: {
10802
+ id: idSchema,
10803
+ reason: { type: "string", maxLength: MAX_ESCALATION_REASON_CHARS }
10804
+ }
10805
+ },
10806
+ risk: "agent",
10807
+ namespace: "coordination",
10808
+ effect: { kind: "emission", resources: resource3, ordering: "ordered" }
10809
+ },
10810
+ {
10811
+ name: "cancel",
10812
+ description: "Cancel an open decision this participant raised or holds",
10813
+ inputSchema: {
10814
+ type: "object",
10815
+ required: ["id"],
10816
+ additionalProperties: false,
10817
+ properties: { id: idSchema }
10818
+ },
10819
+ risk: "agent",
10820
+ namespace: "coordination",
10821
+ effect: { kind: "emission", resources: resource3, ordering: "ordered" }
10822
+ }
10823
+ ];
10824
+ var normalizeDecisionsArgs = actionArgNormalizer(() => descriptors8);
10825
+ var MAX_TRACKED_CALLS = 64;
10826
+ var DecisionsProvider = class {
10827
+ constructor(store, identity) {
10828
+ this.store = store;
10829
+ this.identity = identity;
10830
+ }
10831
+ name = "decisions";
10832
+ description = "Durable pending decisions answered by a human or an authorized holder";
10833
+ // fabric_exec call id -> decisions raised inside that call (self-answer guard).
10834
+ #raisedInCall = /* @__PURE__ */ new Map();
10835
+ async list(request) {
10836
+ const query = request.query?.toLowerCase();
10837
+ return descriptors8.filter((action) => !query || `${action.name} ${action.description}`.toLowerCase().includes(query));
10838
+ }
10839
+ async describe(name) {
10840
+ return descriptors8.find((action) => action.name === name);
10841
+ }
10842
+ prepareArguments(name, args) {
10843
+ return normalizeDecisionsArgs(name, args);
10844
+ }
10845
+ async invoke(name, args, context) {
10846
+ const descriptor = descriptors8.find((action) => action.name === name);
10847
+ if (!descriptor) throw new Error(`Unknown decisions action: ${name}`);
10848
+ const error = validationMessage(descriptor.inputSchema, args);
10849
+ if (error) throw new Error(`Invalid decisions.${name} arguments: ${error}`);
10850
+ switch (name) {
10851
+ case "raise": {
10852
+ const runId = process.env.PI_FABRIC_PARENT_RUN?.trim();
10853
+ const record = await this.store.raise(args, runId ? { runId } : {});
10854
+ this.#trackRaised(context.parentToolCallId, record.id);
10855
+ context.activity?.({ type: "progress", message: `Decision raised: ${record.title}` });
10856
+ return { id: record.id };
10857
+ }
10858
+ case "wait":
10859
+ return this.store.wait(assertDecisionId(args.id), {
10860
+ ...typeof args.timeoutMs === "number" ? { timeoutMs: args.timeoutMs } : {},
10861
+ ...context.signal ? { signal: context.signal } : {}
10862
+ });
10863
+ case "list":
10864
+ return this.store.list({
10865
+ ...typeof args.status === "string" ? { status: args.status } : {},
10866
+ ...typeof args.holder === "string" ? { holder: args.holder } : {},
10867
+ ...typeof args.limit === "number" ? { limit: args.limit } : {}
10868
+ });
10869
+ case "answer": {
10870
+ const id2 = assertDecisionId(args.id);
10871
+ await this.#requireOpen(id2);
10872
+ this.#assertNotRaisedHere(id2, context, "answer");
10873
+ return this.store.answer(id2, args, { answeredBy: this.identity.id, via: "program" }, (record) => this.#assertHolder(record));
10874
+ }
10875
+ case "escalate": {
10876
+ const id2 = assertDecisionId(args.id);
10877
+ await this.#requireOpen(id2);
10878
+ this.#assertNotRaisedHere(id2, context, "escalate");
10879
+ return this.store.escalate(id2, args, { escalatedBy: this.identity.id }, (record) => this.#assertHolder(record));
10880
+ }
10881
+ case "cancel": {
10882
+ const id2 = assertDecisionId(args.id);
10883
+ await this.#requireOpen(id2);
10884
+ return this.store.cancel(id2, { answeredBy: this.identity.id, via: "program" }, (record) => {
10885
+ if (record.raisedBy.participantId !== this.identity.id) this.#assertHolder(record);
10886
+ });
10887
+ }
10888
+ default:
10889
+ throw new Error(`Unknown decisions action: ${name}`);
10890
+ }
10891
+ }
10892
+ async #requireOpen(id2) {
10893
+ const record = await this.store.get(id2);
10894
+ if (!record) throw new Error(`Unknown decision: ${id2}`);
10895
+ if (record.status !== "open") throw new Error(`Decision ${id2} is ${record.status}, not open`);
10896
+ return record;
10897
+ }
10898
+ #assertNotRaisedHere(id2, context, verb) {
10899
+ if (this.#raisedInCall.get(context.parentToolCallId)?.has(id2)) {
10900
+ throw new Error(`Decision ${id2} was raised by this same program; it cannot ${verb} it itself`);
10901
+ }
10902
+ }
10903
+ #assertHolder(record) {
10904
+ if (record.holder === "user") {
10905
+ throw new Error(`Decision ${record.id} is held by the user; answer it with /fabric decisions or the pi-fabric decisions CLI`);
10906
+ }
10907
+ if (record.holder === "root" && this.identity.kind === "main") return;
10908
+ if (record.holder === `supervisor:${this.identity.id}`) return;
10909
+ throw new Error(`Decision ${record.id} is held by ${record.holder}, not this participant`);
10910
+ }
10911
+ #trackRaised(callId, id2) {
10912
+ let raised = this.#raisedInCall.get(callId);
10913
+ if (!raised) {
10914
+ if (this.#raisedInCall.size >= MAX_TRACKED_CALLS) {
10915
+ this.#raisedInCall.delete(this.#raisedInCall.keys().next().value);
10916
+ }
10917
+ raised = /* @__PURE__ */ new Set();
10918
+ this.#raisedInCall.set(callId, raised);
10919
+ }
10920
+ raised.add(id2);
10921
+ }
10922
+ };
10923
+
9206
10924
  // src/providers/pi-tools-provider.ts
9207
10925
  import { readFileSync } from "node:fs";
9208
10926
  import path9 from "node:path";
@@ -9535,6 +11253,16 @@ var closedPiInputSchema = (name, source) => {
9535
11253
  type: "boolean",
9536
11254
  description: "Run as a durable background task owned by jev-fabric (the user's install or the bundled package). It keeps running if Pi exits and reattaches to this session on resume; other harnesses sharing the store can see it. Implies background. Use for dev servers and long jobs that must outlive the session; stop explicitly with tasks.stop."
9537
11255
  };
11256
+ properties.notify = {
11257
+ type: "object",
11258
+ description: "With durable:true: when the command exits, publish {kind (default task.completed), data:{taskId, exitCode, description?}} to this mesh topic, even if no session is attached.",
11259
+ properties: {
11260
+ topic: { type: "string", minLength: 1, maxLength: 128 },
11261
+ kind: { type: "string", minLength: 1, maxLength: 128 }
11262
+ },
11263
+ required: ["topic"],
11264
+ additionalProperties: false
11265
+ };
9538
11266
  }
9539
11267
  if (name === "edit") {
9540
11268
  properties.all = { type: "boolean", description: "Apply every replacement to all matching occurrences." };
@@ -9550,6 +11278,18 @@ var closedPiInputSchema = (name, source) => {
9550
11278
  }
9551
11279
  return { ...schema, properties, additionalProperties: false };
9552
11280
  };
11281
+ var NOTIFY_FIELD_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._:/-]{0,127}$/;
11282
+ var parseDurableNotify = (value) => {
11283
+ if (value === void 0) return void 0;
11284
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("notify must be an object");
11285
+ const input = value;
11286
+ if (Object.keys(input).some((key) => key !== "topic" && key !== "kind")) throw new Error("Unknown notify option");
11287
+ if (typeof input.topic !== "string" || !NOTIFY_FIELD_PATTERN.test(input.topic)) throw new Error("notify.topic must be a valid mesh topic");
11288
+ if (input.kind !== void 0 && (typeof input.kind !== "string" || !NOTIFY_FIELD_PATTERN.test(input.kind))) {
11289
+ throw new Error("notify.kind must be a mesh event kind of at most 128 characters");
11290
+ }
11291
+ return { topic: input.topic, ...typeof input.kind === "string" ? { kind: input.kind } : {} };
11292
+ };
9553
11293
  var MAX_RENDERER_ARGUMENT_CHARS = 2e5;
9554
11294
  var MAX_REPLACE_ALL_FILE_CHARS = 2e6;
9555
11295
  var DEFAULT_HOST_CAPABILITIES = {
@@ -9693,10 +11433,10 @@ var PiToolsProvider = class {
9693
11433
  }
9694
11434
  async list(request, _context) {
9695
11435
  const query = request.query?.toLowerCase();
9696
- const descriptors10 = await Promise.all(
11436
+ const descriptors13 = await Promise.all(
9697
11437
  PI_CORE_TOOL_NAMES.map((name) => this.describe(name, _context))
9698
11438
  );
9699
- return descriptors10.filter((descriptor) => descriptor !== void 0).filter(
11439
+ return descriptors13.filter((descriptor) => descriptor !== void 0).filter(
9700
11440
  (descriptor) => query ? `${descriptor.name} ${descriptor.description}`.toLowerCase().includes(query) : true
9701
11441
  );
9702
11442
  }
@@ -9805,7 +11545,7 @@ var PiToolsProvider = class {
9805
11545
  const value = this.#getShellHangMs?.() ?? DEFAULT_SHELL_HANG_MS;
9806
11546
  return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : DEFAULT_SHELL_HANG_MS;
9807
11547
  }
9808
- async #trackedShellDefinition(name, args, job, middleware) {
11548
+ async #trackedShellDefinition(name, args, job, middleware, notify) {
9809
11549
  const cwd = typeof args[PI_BASH_CWD_KEY] === "string" ? args[PI_BASH_CWD_KEY] : this.#cwd;
9810
11550
  if (name === "bash") {
9811
11551
  const options = middleware?.options;
@@ -9815,7 +11555,8 @@ var PiToolsProvider = class {
9815
11555
  filtered: middleware !== void 0,
9816
11556
  command: typeof args.command === "string" ? args.command : "",
9817
11557
  cwd,
9818
- ownerId: job.options.ownerId
11558
+ ownerId: job.options.ownerId,
11559
+ notify
9819
11560
  }) : createLocalBashOperations(options?.shellPath !== void 0 ? { shellPath: options.shellPath } : void 0);
9820
11561
  const operations = middleware ? middleware.wrapOperations(local) : local;
9821
11562
  if (!operations || typeof operations.exec !== "function") {
@@ -9862,8 +11603,10 @@ var PiToolsProvider = class {
9862
11603
  if (args.background === false) throw new Error("durable runs in the background; omit background:false");
9863
11604
  if (process.platform === "win32" || !this.#shellJobs.durable) throw new Error("Durable shell tasks need jev-fabric on macOS or Linux in a Fabric full-code session");
9864
11605
  }
11606
+ const notify = parseDurableNotify(args.notify);
11607
+ if (notify && !durable) throw new Error("notify requires durable:true");
9865
11608
  const background = args.background === true || monitor !== void 0 || durable;
9866
- const { background: _background, monitor: _monitor, description: _description, durable: _durable, ...executeArgs } = args;
11609
+ const { background: _background, monitor: _monitor, description: _description, durable: _durable, notify: _notify, ...executeArgs } = args;
9867
11610
  const job = this.#shellJobs.begin(name, command, {
9868
11611
  ...durable ? { durable: { home: this.#shellJobs.durable.home } } : {},
9869
11612
  cwd: typeof args[PI_BASH_CWD_KEY] === "string" ? args[PI_BASH_CWD_KEY] : this.#cwd,
@@ -9873,7 +11616,7 @@ var PiToolsProvider = class {
9873
11616
  });
9874
11617
  let tool;
9875
11618
  try {
9876
- tool = await this.#trackedShellDefinition(name, executeArgs, job, middleware);
11619
+ tool = await this.#trackedShellDefinition(name, executeArgs, job, middleware, notify);
9877
11620
  } catch (error) {
9878
11621
  await job.finish(null);
9879
11622
  throw error;
@@ -9932,18 +11675,36 @@ var PiToolsProvider = class {
9932
11675
  async invoke(actionName, args, context) {
9933
11676
  const name = actionName;
9934
11677
  this.#assertAllowed(name);
11678
+ if (process.env.PI_FABRIC_WRITE_POLICY) {
11679
+ const guard = await import("./agents/write-guard.js");
11680
+ const policy = guard.readWritePolicy();
11681
+ const denial = policy && guard.writePolicyDenial(policy, name, args, context.extensionContext?.cwd || this.#cwd);
11682
+ if (denial) throw new Error(denial);
11683
+ }
9935
11684
  if (!this.#requireCapturedOverrides && !this.#tools[name]) throw new Error(`Unknown Pi tool: ${actionName}`);
9936
- if (name === "bash" && !this.#requireCapturedOverrides && !this.#catalog?.get(name)) {
11685
+ const middleware = this.#bashMiddleware(name);
11686
+ const runner = this.#catalog?.runner;
11687
+ if (this.#catalog && !runner && !this.#requireCapturedOverrides && riskForTool(name) !== "read") {
11688
+ throw new Error(
11689
+ `Pi tool ${name} is unavailable until extension tool hooks initialize; retry once tools are ready`
11690
+ );
11691
+ }
11692
+ let preflightEmitted = false;
11693
+ if (name === "bash" && !this.#requireCapturedOverrides && !this.#catalog?.get(name) && typeof args.command === "string" && parseGitWorktreeAdd(args.command) !== void 0) {
11694
+ if (runner) {
11695
+ await this.#emitToolCallPreflight(name, args, context, runner);
11696
+ preflightEmitted = true;
11697
+ }
9937
11698
  const intercepted = await tryExecuteGitWorktreeAdd(args, this.#cwd);
9938
11699
  if (intercepted) {
9939
11700
  this.#attachPreview(name, intercepted, args, context);
9940
11701
  return this.#normalizeResult(name, intercepted, args);
9941
11702
  }
9942
11703
  }
9943
- const middleware = this.#bashMiddleware(name);
9944
11704
  if (this.#catalog?.get(name) && !middleware) {
9945
11705
  if (isPiShellToolName(name) && args.monitor !== void 0) throw new Error("Shell monitors are unavailable for opaque shell overrides; a Fabric-compatible middleware adapter is required");
9946
11706
  if (isPiShellToolName(name) && args.durable === true) throw new Error("Durable shell tasks are unavailable for opaque shell overrides; a Fabric-compatible middleware adapter is required");
11707
+ if (isPiShellToolName(name) && args.notify !== void 0) throw new Error("notify requires durable:true");
9947
11708
  const { durable: _durable, ...overrideArgs } = args;
9948
11709
  const result = await this.#capturedTools.invoke(name, overrideArgs, context);
9949
11710
  this.#attachReadMedia(name, result, context);
@@ -9952,7 +11713,6 @@ var PiToolsProvider = class {
9952
11713
  return this.#normalizeResult(name, result, args);
9953
11714
  }
9954
11715
  const tool = this.#definitionFor(name, args);
9955
- const runner = this.#catalog?.runner;
9956
11716
  if (!runner) {
9957
11717
  const result = await this.#runExecute(
9958
11718
  name,
@@ -9971,7 +11731,22 @@ var PiToolsProvider = class {
9971
11731
  this.#attachPreview(name, result, args, context);
9972
11732
  return this.#normalizeResult(name, result, args);
9973
11733
  }
9974
- return this.#invokeWithEvents(name, tool, args, context, runner, middleware);
11734
+ return this.#invokeWithEvents(name, tool, args, context, runner, middleware, preflightEmitted);
11735
+ }
11736
+ // Emit the tool_call preflight for a nested pi.* call and enforce a block.
11737
+ // Shared by #invokeWithEvents and the git-worktree-add intercept so both obey
11738
+ // the same extension policy through one code path (no duplicated enforcement).
11739
+ async #emitToolCallPreflight(name, args, context, runner) {
11740
+ const preflight = await runAbortable(context.signal, () => runner.emitToolCall({
11741
+ type: "tool_call",
11742
+ toolName: name,
11743
+ toolCallId: context.nestedToolCallId,
11744
+ input: args
11745
+ }));
11746
+ context.updateArguments?.(args);
11747
+ if (preflight?.block) {
11748
+ throw new Error(preflight.reason || `Pi tool ${name} was blocked`);
11749
+ }
9975
11750
  }
9976
11751
  // Replay the agent-core tool-execution lifecycle for a nested pi.* call, so
9977
11752
  // extensions that hook tool_call / tool_result / tool_execution_* see pi
@@ -9981,7 +11756,7 @@ var PiToolsProvider = class {
9981
11756
  // tools. tool_result patches (content/details/isError) are applied, so
9982
11757
  // extensions like pi-vision-handoff can replace image blocks with text
9983
11758
  // descriptions before the result returns to the sandbox.
9984
- async #invokeWithEvents(name, tool, args, context, runner, middleware) {
11759
+ async #invokeWithEvents(name, tool, args, context, runner, middleware, preflightEmitted = false) {
9985
11760
  const toolCallId = context.nestedToolCallId;
9986
11761
  await runAbortable(context.signal, () => runner.emit({
9987
11762
  type: "tool_execution_start",
@@ -9995,16 +11770,7 @@ var PiToolsProvider = class {
9995
11770
  let executionStarted = false;
9996
11771
  let updateTail = Promise.resolve();
9997
11772
  try {
9998
- const preflight = await runAbortable(context.signal, () => runner.emitToolCall({
9999
- type: "tool_call",
10000
- toolName: name,
10001
- toolCallId,
10002
- input: args
10003
- }));
10004
- context.updateArguments?.(args);
10005
- if (preflight?.block) {
10006
- throw new Error(preflight.reason || `Pi tool ${name} was blocked`);
10007
- }
11773
+ if (!preflightEmitted) await this.#emitToolCallPreflight(name, args, context, runner);
10008
11774
  executionStarted = true;
10009
11775
  result = await this.#runExecute(
10010
11776
  name,
@@ -10175,7 +11941,7 @@ var DAY_MS = 24 * 36e5;
10175
11941
  var id = { type: "string", minLength: 1, maxLength: 128, description: "Session ID from sessions.open (`s-\u2026` for session lifetime) or a durable jev-fabric job ID." };
10176
11942
  var idOnly = { type: "object", properties: { id }, required: ["id"], additionalProperties: false };
10177
11943
  var waitMs = { type: "integer", minimum: 1, maximum: 3e5, description: "Long-poll ceiling; ready evidence returns at once. Never stops the child." };
10178
- var descriptors6 = [
11944
+ var descriptors9 = [
10179
11945
  {
10180
11946
  name: "open",
10181
11947
  description: "Start an interactive child with its stdin kept open, owned by jev-fabric (macOS/Linux). Lifetime session (default) ends with this Pi session, or with the Jev program that opened it; durable: true keeps it in the jev-fabric store after Pi exits. Give argv (literal, no shell) or cmd (run by bash -c). Returns id, lifetime and state. Drive it with write/read; stop it explicitly.",
@@ -10242,10 +12008,10 @@ var SessionsProvider = class {
10242
12008
  #closed = false;
10243
12009
  async list(request) {
10244
12010
  const query = request.query?.toLowerCase();
10245
- return query ? descriptors6.filter((d) => `${d.name} ${d.description}`.toLowerCase().includes(query)) : descriptors6;
12011
+ return query ? descriptors9.filter((d) => `${d.name} ${d.description}`.toLowerCase().includes(query)) : descriptors9;
10246
12012
  }
10247
12013
  async describe(name) {
10248
- return descriptors6.find((d) => d.name === name);
12014
+ return descriptors9.find((d) => d.name === name);
10249
12015
  }
10250
12016
  #connect() {
10251
12017
  if (this.#closed) return Promise.reject(new Error("Sessions provider is closed"));
@@ -10334,9 +12100,9 @@ var SessionsProvider = class {
10334
12100
  var pick = (args, keys) => Object.fromEntries(keys.filter((key) => args[key] !== void 0).map((key) => [key, args[key]]));
10335
12101
 
10336
12102
  // src/providers/tasks-provider.ts
10337
- var idSchema = { type: "object", properties: { id: { type: "string", minLength: 1 } }, required: ["id"], additionalProperties: false };
10338
- var waitSchema = { ...idSchema, properties: {
10339
- ...idSchema.properties,
12103
+ var idSchema2 = { type: "object", properties: { id: { type: "string", minLength: 1 } }, required: ["id"], additionalProperties: false };
12104
+ var waitSchema = { ...idSchema2, properties: {
12105
+ ...idSchema2.properties,
10340
12106
  timeoutMs: { type: "integer", minimum: 1, maximum: 3e5, description: "Observation ceiling in milliseconds, not a delay or process deadline. Timeout never cancels the task." }
10341
12107
  } };
10342
12108
  var watchSchema = { ...waitSchema, properties: {
@@ -10344,8 +12110,8 @@ var watchSchema = { ...waitSchema, properties: {
10344
12110
  after: { type: "integer", minimum: 0, maximum: Number.MAX_SAFE_INTEGER, description: "Previously returned nextCursor; default 0. With match it is a byte offset; otherwise a monitor line cursor. Lost positions are disclosed." },
10345
12111
  match: { type: "string", minLength: 1, maxLength: 256, description: "Case-sensitive literal chosen at watch time; works on any background task, like jev-fabric watch <id> <literal>. Omit to read a launch-time monitor." }
10346
12112
  } };
10347
- var readSchema = { ...idSchema, properties: {
10348
- ...idSchema.properties,
12113
+ var readSchema = { ...idSchema2, properties: {
12114
+ ...idSchema2.properties,
10349
12115
  offset: { type: "integer", minimum: 0, maximum: Number.MAX_SAFE_INTEGER, description: "Byte offset into the task's combined output since launch; default 0. Pass the returned next." },
10350
12116
  max: { type: "integer", minimum: 1, maximum: SHELL_READ_MAX_BYTES, description: "Largest page in bytes; default 65536." },
10351
12117
  waitMs: { type: "integer", minimum: 1, maximum: 3e5, description: "Long-poll ceiling: return as soon as bytes past offset exist or the task ends. Never stops the task." },
@@ -10354,13 +12120,13 @@ var readSchema = { ...idSchema, properties: {
10354
12120
  var WATCH_LINES = 64;
10355
12121
  var WATCH_LINE_CHARS = 2048;
10356
12122
  var clean = (line) => line.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").trim();
10357
- var descriptors7 = [
12123
+ var descriptors10 = [
10358
12124
  { name: "list", description: "List this session's tracked shell tasks and monitors, with IDs, command, cwd, state, timestamps, and bounded monitor events. No output polling is needed: detached completions notify the owning agent.", inputSchema: { type: "object", properties: {}, additionalProperties: false }, risk: "read", effect: { kind: "none", ordering: "commutative" } },
10359
- { name: "get", description: "Inspect one shell task by ID, returning metadata and a bounded output tail. Acknowledges its pending notification after a successful read. Full retained output is at logPath (bounded, not an archive).", inputSchema: idSchema, risk: "read", effect: { kind: "emission", ordering: "ordered" } },
12125
+ { name: "get", description: "Inspect one shell task by ID, returning metadata and a bounded output tail. Acknowledges its pending notification after a successful read. Full retained output is at logPath (bounded, not an archive).", inputSchema: idSchema2, risk: "read", effect: { kind: "emission", ordering: "ordered" } },
10360
12126
  { name: "wait", description: "Wait without polling for a session-owned shell task to finish, default 30 seconds. Returns task metadata, a bounded output tail and timedOut. Inspect status and exitCode; an exited task is not goal verification. Timeout or cancellation stops only this wait.", inputSchema: waitSchema, risk: "read", effect: { kind: "emission", ordering: "ordered" } },
10361
12127
  { name: "read", description: "Read a background task's combined output by byte offset, in jev-fabric's read record shape: offset, bytes, omittedBytes, text (or base64 data), next, eof, state. Optional waitMs long-polls for new bytes. The live window is 1 MiB; 32 KiB stays readable after exit. Never consumes or stops anything.", inputSchema: readSchema, risk: "read", effect: { kind: "none", ordering: "commutative" } },
10362
12128
  { name: "watch", description: "Wait without polling for matching lines, task exit, or timeout (default 5 seconds). With match (any background task, chosen now): returns complete output lines containing that literal after the byte cursor, omittedBytes, more and nextCursor. Without match: reads a launch-time monitor (pi.bash monitor with delivery ui). Returns reason, up to 64 lines after the cursor, losses (burst/evicted cursor ranges), omitted, more and nextCursor with task metadata; pass nextCursor as after, immediately again while more is true. The latest 256 positions are replayable. No inference, wakeup, renewal or cancellation of the task. Not a lossless RPC stream.", inputSchema: watchSchema, risk: "read", effect: { kind: "none", ordering: "commutative" } },
10363
- { name: "stop", description: "Stop one session-owned shell task or monitor by ID using its existing abort controller, not an arbitrary PID. A durable task is stopped through jev-fabric. Cancellation does not wake the owning agent.", inputSchema: idSchema, risk: "execute", effect: { kind: "emission", ordering: "ordered" } },
12129
+ { name: "stop", description: "Stop one session-owned shell task or monitor by ID using its existing abort controller, not an arbitrary PID. A durable task is stopped through jev-fabric. Cancellation does not wake the owning agent.", inputSchema: idSchema2, risk: "execute", effect: { kind: "emission", ordering: "ordered" } },
10364
12130
  { name: "external", description: "List jev-fabric jobs in this session's durable store that no task here tracks, for example dev servers started by another harness or an earlier session. Returns id, state, label and start time; read-only.", inputSchema: { type: "object", properties: {}, additionalProperties: false }, risk: "read", effect: { kind: "none", ordering: "commutative" } },
10365
12131
  { name: "adopt", description: "Attach an existing jev-fabric job from tasks.external to this session as a durable task: its output, completion notification, wait/stop and inspector row. Adopting does not restart or signal the process.", inputSchema: { type: "object", properties: { jobId: { type: "string", minLength: 1, maxLength: 128 }, description: { type: "string", minLength: 1, maxLength: 120 } }, required: ["jobId"], additionalProperties: false }, risk: "read", effect: { kind: "emission", ordering: "ordered" } }
10366
12132
  ];
@@ -10373,11 +12139,11 @@ var TasksProvider = class {
10373
12139
  description = "Session-owned shell orchestration with bounded wait/watch and explicit stop";
10374
12140
  async list(request) {
10375
12141
  const query = request.query?.toLowerCase();
10376
- const available = this.jobs.durable ? descriptors7 : descriptors7.filter((d) => !durableOnly.has(d.name));
12142
+ const available = this.jobs.durable ? descriptors10 : descriptors10.filter((d) => !durableOnly.has(d.name));
10377
12143
  return query ? available.filter((d) => `${d.name} ${d.description}`.toLowerCase().includes(query)) : available;
10378
12144
  }
10379
12145
  async describe(name) {
10380
- return this.jobs.durable || !durableOnly.has(name) ? descriptors7.find((d) => d.name === name) : void 0;
12146
+ return this.jobs.durable || !durableOnly.has(name) ? descriptors10.find((d) => d.name === name) : void 0;
10381
12147
  }
10382
12148
  async invoke(name, args, context) {
10383
12149
  const descriptor = await this.describe(name);
@@ -10450,6 +12216,113 @@ var TasksProvider = class {
10450
12216
  }
10451
12217
  };
10452
12218
 
12219
+ // src/state/binding.ts
12220
+ import { execFile } from "node:child_process";
12221
+ var STATE_BINDING_MAX_KEYS = 16;
12222
+ var STATE_BINDING_VALUE_MAX_CHARS = 512;
12223
+ var STATE_BINDING_KEY = /^[a-z][a-zA-Z0-9_.-]{0,63}$/;
12224
+ var GIT_OBJECT_NAME = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
12225
+ var GIT_PROBE_TIMEOUT_MS = 5e3;
12226
+ var GIT_HEAD_MAX_BUFFER = 1024;
12227
+ var GIT_STATUS_MAX_BUFFER = 64 * 1024;
12228
+ var SCHEMA_MODES = /* @__PURE__ */ new Set(["off", "audit", "enforce"]);
12229
+ var normalizeStateBinding = (value) => {
12230
+ if (value === void 0) return void 0;
12231
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
12232
+ throw new Error("state.verify binding must be an object of string values");
12233
+ }
12234
+ const keys = Object.keys(value);
12235
+ if (keys.length > STATE_BINDING_MAX_KEYS) {
12236
+ throw new Error(
12237
+ `state.verify binding has ${keys.length} keys; at most ${STATE_BINDING_MAX_KEYS} are allowed`
12238
+ );
12239
+ }
12240
+ const binding = {};
12241
+ for (const key of keys.sort()) {
12242
+ if (!STATE_BINDING_KEY.test(key)) {
12243
+ throw new Error(
12244
+ `state.verify binding key ${JSON.stringify(key.slice(0, 80))} must match [a-z][a-zA-Z0-9_.-]{0,63}`
12245
+ );
12246
+ }
12247
+ const item = value[key];
12248
+ if (typeof item !== "string") {
12249
+ throw new Error(`state.verify binding.${key} must be a string`);
12250
+ }
12251
+ if (item.length > STATE_BINDING_VALUE_MAX_CHARS) {
12252
+ throw new Error(
12253
+ `state.verify binding.${key} exceeds ${STATE_BINDING_VALUE_MAX_CHARS} characters`
12254
+ );
12255
+ }
12256
+ binding[key] = item;
12257
+ }
12258
+ return keys.length > 0 ? binding : void 0;
12259
+ };
12260
+ var toStateBinding = (value) => {
12261
+ try {
12262
+ return normalizeStateBinding(value);
12263
+ } catch {
12264
+ return void 0;
12265
+ }
12266
+ };
12267
+ var toStateObserved = (value) => {
12268
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
12269
+ const raw = value;
12270
+ const observed = {
12271
+ ...typeof raw.commit === "string" && GIT_OBJECT_NAME.test(raw.commit) ? { commit: raw.commit } : {},
12272
+ ...typeof raw.dirty === "boolean" ? { dirty: raw.dirty } : {}
12273
+ };
12274
+ return observed.commit !== void 0 || observed.dirty !== void 0 ? observed : void 0;
12275
+ };
12276
+ var toStateRequester = (value) => value === "program" || value === "host" ? value : void 0;
12277
+ var toStateSchemaMode = (value) => typeof value === "string" && SCHEMA_MODES.has(value) ? value : void 0;
12278
+ var runGit = (cwd, args, maxBuffer, signal) => new Promise((resolve2) => {
12279
+ try {
12280
+ execFile(
12281
+ "git",
12282
+ ["-C", cwd, ...args],
12283
+ {
12284
+ encoding: "utf8",
12285
+ maxBuffer,
12286
+ timeout: GIT_PROBE_TIMEOUT_MS,
12287
+ windowsHide: true,
12288
+ // Observation must not take the index lock or refresh stat data.
12289
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" },
12290
+ ...signal ? { signal } : {}
12291
+ },
12292
+ (error, stdout) => {
12293
+ if (!error) {
12294
+ resolve2({ stdout, overflow: false });
12295
+ return;
12296
+ }
12297
+ const code = error.code;
12298
+ if (code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") {
12299
+ resolve2({ stdout, overflow: true });
12300
+ return;
12301
+ }
12302
+ resolve2(void 0);
12303
+ }
12304
+ );
12305
+ } catch {
12306
+ resolve2(void 0);
12307
+ }
12308
+ });
12309
+ var observeGitWorkspace = async (cwd, signal) => {
12310
+ if (signal?.aborted) return void 0;
12311
+ const head = await runGit(cwd, ["rev-parse", "--verify", "--quiet", "HEAD"], GIT_HEAD_MAX_BUFFER, signal);
12312
+ const commit = head && !head.overflow ? head.stdout.trim().toLowerCase() : "";
12313
+ if (!GIT_OBJECT_NAME.test(commit)) return void 0;
12314
+ const status = await runGit(
12315
+ cwd,
12316
+ ["status", "--porcelain", "--untracked-files=normal"],
12317
+ GIT_STATUS_MAX_BUFFER,
12318
+ signal
12319
+ );
12320
+ return {
12321
+ commit,
12322
+ ...status ? { dirty: status.overflow || status.stdout.trim().length > 0 } : {}
12323
+ };
12324
+ };
12325
+
10453
12326
  // src/state/store.ts
10454
12327
  import { createHash as createHash4 } from "node:crypto";
10455
12328
  import path12 from "node:path";
@@ -11047,6 +12920,19 @@ var latestTransitionOutcomes = (events) => {
11047
12920
  }
11048
12921
  return latest;
11049
12922
  };
12923
+ var toBindingFields = (data) => {
12924
+ const binding = toStateBinding(data.binding);
12925
+ const observed = toStateObserved(data.observed);
12926
+ const requestedBy = toStateRequester(data.requestedBy);
12927
+ const schemaMode = toStateSchemaMode(data.schemaMode);
12928
+ return {
12929
+ ...binding !== void 0 ? { binding } : {},
12930
+ ...observed !== void 0 ? { observed } : {},
12931
+ ...data.issuer === "host" ? { issuer: "host" } : {},
12932
+ ...requestedBy !== void 0 ? { requestedBy } : {},
12933
+ ...schemaMode !== void 0 ? { schemaMode } : {}
12934
+ };
12935
+ };
11050
12936
  var toCertificate = (event, currentHead, latestOutcomes) => {
11051
12937
  if (event.kind !== "state.certified") return void 0;
11052
12938
  const data = event.data;
@@ -11068,7 +12954,8 @@ var toCertificate = (event, currentHead, latestOutcomes) => {
11068
12954
  evidenceDigest: data.evidenceDigest,
11069
12955
  resultDigest: data.resultDigest,
11070
12956
  ts: typeof data.ts === "number" ? data.ts : event.createdAt,
11071
- current
12957
+ current,
12958
+ ...toBindingFields(data)
11072
12959
  };
11073
12960
  };
11074
12961
  var durableCurrentCertificate = (head, latestOutcomes) => {
@@ -11085,11 +12972,20 @@ var durableCurrentCertificate = (head, latestOutcomes) => {
11085
12972
  if (!target2 || certificateHead === null || certificateHead.transitionId !== head.transitionId || (certificateHead.labelDigest ? certificateHead.labelDigest !== digest(head.label) : certificateHead.label !== head.label) || (certificateHead.toDigest ? certificateHead.toDigest !== digest(head.to) : certificateHead.to !== head.to) || certificateHead.version !== head.version || latestOutcome !== void 0 && (latestOutcome.phase !== "certified" || latestOutcome.event.sequence !== certificate.sequence)) {
11086
12973
  return void 0;
11087
12974
  }
12975
+ const {
12976
+ binding: _binding,
12977
+ observed: _observed,
12978
+ issuer: _issuer,
12979
+ requestedBy: _requestedBy,
12980
+ schemaMode: _schemaMode,
12981
+ ...baseCertificate
12982
+ } = certificate;
11088
12983
  return {
11089
- ...certificate,
12984
+ ...baseCertificate,
11090
12985
  targets,
11091
12986
  head: certificateHead,
11092
- current: true
12987
+ current: true,
12988
+ ...toBindingFields(certificate)
11093
12989
  };
11094
12990
  };
11095
12991
  var toVerifyResult = (claim, command, result) => {
@@ -11759,6 +13655,16 @@ var StateStore = class {
11759
13655
  }
11760
13656
  }
11761
13657
  async verify(input) {
13658
+ const binding = normalizeStateBinding(input.binding);
13659
+ const requestedBy = input.requestedBy ?? "host";
13660
+ const observed = await observeGitWorkspace(input.cwd, input.signal);
13661
+ const bindingFields = {
13662
+ ...binding !== void 0 ? { binding } : {},
13663
+ ...observed !== void 0 ? { observed } : {},
13664
+ issuer: "host",
13665
+ requestedBy,
13666
+ ...input.schemaMode !== void 0 ? { schemaMode: input.schemaMode } : {}
13667
+ };
11762
13668
  const verificationHead = this.getHead();
11763
13669
  const boundedHeadLabel = verificationHead ? truncateUtf83(verificationHead.label, EVENT_TEXT_MAX_BYTES) : void 0;
11764
13670
  const boundedHeadTo = verificationHead ? truncateUtf83(verificationHead.to, EVENT_TEXT_MAX_BYTES) : void 0;
@@ -11813,13 +13719,28 @@ var StateStore = class {
11813
13719
  );
11814
13720
  const results = [];
11815
13721
  const failures = [];
13722
+ const boundCommit = binding?.commit;
13723
+ if (boundCommit !== void 0) {
13724
+ if (observed?.commit === void 0) {
13725
+ failures.push({
13726
+ reason: "binding-unobserved",
13727
+ message: "binding.commit cannot be checked: the verification cwd is not a git work tree with a HEAD commit"
13728
+ });
13729
+ } else if (boundCommit.trim().toLowerCase() !== observed.commit) {
13730
+ failures.push({
13731
+ reason: "binding-mismatch",
13732
+ message: `binding.commit ${truncateUtf83(boundCommit, 128).value} does not match observed HEAD ${observed.commit}`
13733
+ });
13734
+ }
13735
+ }
13736
+ const bindingFailed = failures.length > 0;
11816
13737
  if (targets.length === 0) {
11817
13738
  failures.push({
11818
13739
  reason: "missing-target",
11819
13740
  message: input.labels === void 0 ? "No current state transition is available to verify" : "No active state transitions matched the requested labels"
11820
13741
  });
11821
13742
  }
11822
- for (const target2 of targets) {
13743
+ for (const target2 of bindingFailed ? [] : targets) {
11823
13744
  const evidence = target2.evidence ?? [];
11824
13745
  if (evidence.length === 0) {
11825
13746
  failures.push({
@@ -11892,6 +13813,7 @@ var StateStore = class {
11892
13813
  omittedResultCount: Math.max(0, nonConfirmed.length - EVENT_RESULT_LIMIT),
11893
13814
  reasons: index === 0 ? failures.slice(0, EVENT_RESULT_LIMIT).map(toEventFailure) : [],
11894
13815
  omittedReasonCount: Math.max(0, failures.length - EVENT_RESULT_LIMIT),
13816
+ ...bindingFields,
11895
13817
  ts: Date.now()
11896
13818
  }
11897
13819
  });
@@ -11913,6 +13835,11 @@ var StateStore = class {
11913
13835
  const publishError = await publishViolation();
11914
13836
  return [revocationError, publishError].filter((value) => value !== void 0).join("; ") || void 0;
11915
13837
  };
13838
+ const reportBinding = {
13839
+ ...binding !== void 0 ? { binding } : {},
13840
+ ...observed !== void 0 ? { observed } : {},
13841
+ requestedBy
13842
+ };
11916
13843
  if (!certified) {
11917
13844
  const reportingError = await recordViolation();
11918
13845
  return {
@@ -11923,7 +13850,8 @@ var StateStore = class {
11923
13850
  evidenceDigest,
11924
13851
  resultDigest,
11925
13852
  failures,
11926
- ...reportingError ? { reportingError } : {}
13853
+ ...reportingError ? { reportingError } : {},
13854
+ ...reportBinding
11927
13855
  };
11928
13856
  }
11929
13857
  const ts = Date.now();
@@ -11942,6 +13870,7 @@ var StateStore = class {
11942
13870
  head: headIdentity,
11943
13871
  evidenceDigest,
11944
13872
  resultDigest,
13873
+ ...bindingFields,
11945
13874
  ts
11946
13875
  }
11947
13876
  });
@@ -11967,7 +13896,8 @@ var StateStore = class {
11967
13896
  evidenceDigest,
11968
13897
  resultDigest,
11969
13898
  failures,
11970
- certificate: durableCertificate
13899
+ certificate: durableCertificate,
13900
+ ...reportBinding
11971
13901
  };
11972
13902
  } catch (error) {
11973
13903
  certified = false;
@@ -11988,7 +13918,8 @@ var StateStore = class {
11988
13918
  evidenceDigest,
11989
13919
  resultDigest,
11990
13920
  failures,
11991
- reportingError
13921
+ reportingError,
13922
+ ...reportBinding
11992
13923
  };
11993
13924
  }
11994
13925
  }
@@ -12055,7 +13986,13 @@ var verifySchema = {
12055
13986
  type: "boolean",
12056
13987
  description: "Also replay evidence from labels before the last representation transition."
12057
13988
  },
12058
- timeoutMs: { type: "number", minimum: 1, description: "Per-command timeout (default 30s)" }
13989
+ timeoutMs: { type: "number", minimum: 1, description: "Per-command timeout (default 30s)" },
13990
+ binding: {
13991
+ type: "object",
13992
+ maxProperties: STATE_BINDING_MAX_KEYS,
13993
+ additionalProperties: { type: "string", maxLength: STATE_BINDING_VALUE_MAX_CHARS },
13994
+ description: "Claims the certificate is bound to; keys match [a-z][a-zA-Z0-9_.-]{0,63}. Well-known: commit (checked against the observed git HEAD; a mismatch fails closed), specDigest, nodeAddress, criteriaDigest."
13995
+ }
12059
13996
  },
12060
13997
  additionalProperties: false
12061
13998
  };
@@ -12099,8 +14036,8 @@ var checkGoalSchema = {
12099
14036
  properties: { timeoutMs: { type: "number", minimum: 1 } },
12100
14037
  additionalProperties: false
12101
14038
  };
12102
- var emptySchema4 = { type: "object", properties: {}, additionalProperties: false };
12103
- var descriptors8 = [
14039
+ var emptySchema5 = { type: "object", properties: {}, additionalProperties: false };
14040
+ var descriptors11 = [
12104
14041
  {
12105
14042
  name: "transition",
12106
14043
  description: "Append a labeled, validated state transition and compare-and-swap advance the head",
@@ -12111,7 +14048,7 @@ var descriptors8 = [
12111
14048
  {
12112
14049
  name: "get",
12113
14050
  description: "Return the current state head, goal, compact complexity summary, recent labels, and current/recent certification state",
12114
- inputSchema: emptySchema4,
14051
+ inputSchema: emptySchema5,
12115
14052
  risk: "read",
12116
14053
  namespace: "state"
12117
14054
  },
@@ -12151,27 +14088,29 @@ var descriptors8 = [
12151
14088
  namespace: "state"
12152
14089
  }
12153
14090
  ];
12154
- var normalizeStateArgs = actionArgNormalizer(() => descriptors8);
14091
+ var normalizeStateArgs = actionArgNormalizer(() => descriptors11);
12155
14092
  var StateProvider = class {
12156
14093
  name = "state";
12157
14094
  description = "Schema-style labeled transition layer: an append-only timeline of validated transitions with a compare-and-swap head and evidence-based certification over mesh storage";
12158
14095
  #store;
12159
14096
  #identity;
12160
- constructor(store, identity) {
14097
+ #schemaMode;
14098
+ constructor(store, identity, options = {}) {
12161
14099
  this.#store = new StateStore(store);
12162
14100
  this.#identity = identity;
14101
+ this.#schemaMode = options.schemaMode;
12163
14102
  }
12164
14103
  get state() {
12165
14104
  return this.#store;
12166
14105
  }
12167
14106
  async list(request, _context) {
12168
14107
  const query = request.query?.toLowerCase();
12169
- return query ? descriptors8.filter(
14108
+ return query ? descriptors11.filter(
12170
14109
  (descriptor) => `${descriptor.name} ${descriptor.description}`.toLowerCase().includes(query)
12171
- ) : descriptors8;
14110
+ ) : descriptors11;
12172
14111
  }
12173
14112
  async describe(actionName, _context) {
12174
- return descriptors8.find((descriptor) => descriptor.name === actionName);
14113
+ return descriptors11.find((descriptor) => descriptor.name === actionName);
12175
14114
  }
12176
14115
  prepareArguments(actionName, args) {
12177
14116
  return normalizeStateArgs(actionName, args);
@@ -12240,6 +14179,7 @@ var StateProvider = class {
12240
14179
  const labels = Array.isArray(args.labels) ? args.labels.filter((item) => typeof item === "string") : void 0;
12241
14180
  const timeoutMs = typeof args.timeoutMs === "number" ? args.timeoutMs : void 0;
12242
14181
  const includeArchived = args.includeArchived === true;
14182
+ const binding = args.binding;
12243
14183
  context.activity?.({
12244
14184
  type: "entity",
12245
14185
  id: STATE_ENTITY_ID,
@@ -12252,7 +14192,10 @@ var StateProvider = class {
12252
14192
  cwd: context.cwd,
12253
14193
  ...timeoutMs !== void 0 ? { timeoutMs } : {},
12254
14194
  ...context.signal ? { signal: context.signal } : {},
12255
- identity: this.#identity
14195
+ identity: this.#identity,
14196
+ ...binding !== void 0 ? { binding } : {},
14197
+ requestedBy: "program",
14198
+ ...this.#schemaMode !== void 0 ? { schemaMode: this.#schemaMode } : {}
12256
14199
  });
12257
14200
  context.update(
12258
14201
  result.certified ? `State certified: ${result.results.length} evidence command(s) confirmed` : result.reportingError ? `State certification blocked; violation reporting failed: ${result.reportingError}` : "State certification blocked; violation details were published"
@@ -12392,12 +14335,19 @@ var RuntimeStateBuiltins = class {
12392
14335
  provider: "state",
12393
14336
  description: "Labeled world state over the project mesh",
12394
14337
  requires: ["mesh.get"],
12395
- create: () => new StateProvider(mesh, identity)
14338
+ create: () => new StateProvider(mesh, identity, { schemaMode: config.schema.mode })
14339
+ }));
14340
+ await this.install(createProviderComponent({
14341
+ provider: "decisions",
14342
+ description: "Durable pending decisions over the project mesh",
14343
+ requires: ["mesh.get"],
14344
+ create: () => new DecisionsProvider(new DecisionStore(mesh, identity), identity)
12396
14345
  }));
12397
14346
  } else {
12398
14347
  const meshDisabled = 'disabled by configuration (mesh.enabled=false); set "mesh": { "enabled": true } in .pi/fabric.json or the agent fabric.json';
12399
14348
  this.registry.markUnavailable("mesh", `${meshDisabled} to enable mesh.* actions`);
12400
14349
  this.registry.markUnavailable("state", `${meshDisabled}; state.* actions run on the mesh`);
14350
+ this.registry.markUnavailable("decisions", `${meshDisabled}; decisions.* actions run on the mesh`);
12401
14351
  }
12402
14352
  }
12403
14353
  async memory(context, config, sessionId) {
@@ -12437,9 +14387,10 @@ var RuntimeStateBuiltins = class {
12437
14387
  ...config.fullCodeMode && config.capture.enabled && config.schema.mode !== "enforce" ? ["extensions"] : [],
12438
14388
  "mcp",
12439
14389
  ...config.mesh.enabled ? ["mesh", "state"] : ["mesh", "state"].filter((name) => this.managedHost?.has(name)),
14390
+ ...config.mesh.enabled && !this.managedHost ? ["decisions"] : [],
12440
14391
  "schema",
12441
14392
  "compact",
12442
- ...!this.managedHost ? ["cache"] : [],
14393
+ ...!this.managedHost ? ["cache", "thinking", "programs"] : [],
12443
14394
  "prewalk",
12444
14395
  "agents",
12445
14396
  ...!this.managedHost && config.jev.enabled && config.schema.mode !== "enforce" ? ["jev"] : [],
@@ -12451,7 +14402,7 @@ var RuntimeStateBuiltins = class {
12451
14402
 
12452
14403
  // src/schema/controller.ts
12453
14404
  import { spawn as spawn2 } from "node:child_process";
12454
- import { createHash as createHash6, randomBytes, randomUUID as randomUUID6 } from "node:crypto";
14405
+ import { createHash as createHash6, randomBytes, randomUUID as randomUUID7 } from "node:crypto";
12455
14406
  import fs10 from "node:fs";
12456
14407
  import path14 from "node:path";
12457
14408
 
@@ -12713,7 +14664,7 @@ var SchemaController = class {
12713
14664
  const generation = this.#generation();
12714
14665
  const now = Date.now();
12715
14666
  const record = {
12716
- id: randomUUID6(),
14667
+ id: randomUUID7(),
12717
14668
  label: input.label,
12718
14669
  summary: input.summary,
12719
14670
  evidence: input.evidence,
@@ -12855,7 +14806,7 @@ var SchemaController = class {
12855
14806
  }
12856
14807
  this.#assertPayloadBound(input);
12857
14808
  const release = this.#acquireCommitLock();
12858
- const transactionId = randomUUID6();
14809
+ const transactionId = randomUUID7();
12859
14810
  const journalPath = path14.join(this.#journalRoot, `${transactionId}.json`);
12860
14811
  let journal;
12861
14812
  let consumed = false;
@@ -13304,13 +15255,20 @@ var SchemaController = class {
13304
15255
  #publish(kind, data) {
13305
15256
  return this.mesh.publish({ topic: SCHEMA_TOPIC, kind, from: this.identity, data });
13306
15257
  }
15258
+ // `pid\ncreated\n{identity, heartbeatAt}\n`: the third line is additive and
15259
+ // refreshed while the transaction runs, since postconditions can be slow.
13307
15260
  #acquireCommitLock() {
13308
15261
  fs10.mkdirSync(this.#journalRoot, { recursive: true, mode: 448 });
13309
- try {
13310
- const descriptor = fs10.openSync(this.#lockPath, "wx", 384);
13311
- fs10.writeFileSync(descriptor, `${process.pid}
15262
+ const lockPath = this.#lockPath;
15263
+ const prefix = `${process.pid}
13312
15264
  ${Date.now()}
13313
- `);
15265
+ `;
15266
+ const { identity, heartbeatAt } = ownerHeartbeatFields();
15267
+ const contents = (beat) => `${prefix}${JSON.stringify({ ...identity, heartbeatAt: beat })}
15268
+ `;
15269
+ try {
15270
+ const descriptor = fs10.openSync(lockPath, "wx", 384);
15271
+ fs10.writeFileSync(descriptor, contents(heartbeatAt));
13314
15272
  fs10.closeSync(descriptor);
13315
15273
  } catch (error) {
13316
15274
  if (error instanceof Error && "code" in error && error.code === "EEXIST") {
@@ -13318,19 +15276,41 @@ ${Date.now()}
13318
15276
  }
13319
15277
  throw error;
13320
15278
  }
13321
- return () => fs10.rmSync(this.#lockPath, { force: true });
15279
+ const stopHeartbeat = startOwnerHeartbeat((beat) => {
15280
+ if (fs10.readFileSync(lockPath, "utf8").startsWith(prefix)) writeFileAtomic(lockPath, contents(beat));
15281
+ });
15282
+ return () => {
15283
+ stopHeartbeat();
15284
+ fs10.rmSync(lockPath, { force: true });
15285
+ };
13322
15286
  }
13323
15287
  #recoverJournals() {
13324
15288
  fs10.mkdirSync(this.#journalRoot, { recursive: true, mode: 448 });
13325
15289
  try {
13326
- const [pidText] = fs10.readFileSync(this.#lockPath, "utf8").split("\n");
15290
+ const [pidText, , ownerLine] = fs10.readFileSync(this.#lockPath, "utf8").split("\n");
13327
15291
  const pid = Number(pidText);
13328
15292
  if (Number.isSafeInteger(pid) && pid > 0) {
15293
+ let owner;
13329
15294
  try {
13330
- process.kill(pid, 0);
13331
- return;
15295
+ owner = ownerLine && ownerLine.length <= 2048 ? JSON.parse(ownerLine) : void 0;
13332
15296
  } catch {
15297
+ owner = void 0;
13333
15298
  }
15299
+ const liveness = recordOwnerLiveness({
15300
+ pid,
15301
+ identity: owner,
15302
+ ...typeof owner === "object" && owner !== null && "heartbeatAt" in owner ? { heartbeatAt: owner.heartbeatAt } : {}
15303
+ }, {
15304
+ legacyAlive: (candidate) => {
15305
+ try {
15306
+ process.kill(candidate, 0);
15307
+ return true;
15308
+ } catch {
15309
+ return false;
15310
+ }
15311
+ }
15312
+ });
15313
+ if (liveness !== "dead") return;
13334
15314
  }
13335
15315
  fs10.rmSync(this.#lockPath, { force: true });
13336
15316
  } catch (error) {
@@ -13458,7 +15438,7 @@ var operationSchema = {
13458
15438
  }
13459
15439
  ]
13460
15440
  };
13461
- var descriptors9 = [
15441
+ var descriptors12 = [
13462
15442
  {
13463
15443
  name: "status",
13464
15444
  description: "Read the fixed session Schema mode, transaction bounds, generation, and invocation hypotheses",
@@ -13528,7 +15508,7 @@ var descriptors9 = [
13528
15508
  namespace: "schema"
13529
15509
  }
13530
15510
  ];
13531
- var normalizeSchemaArgs = actionArgNormalizer(() => descriptors9);
15511
+ var normalizeSchemaArgs = actionArgNormalizer(() => descriptors12);
13532
15512
  var SchemaProvider = class {
13533
15513
  constructor(controller) {
13534
15514
  this.controller = controller;
@@ -13537,12 +15517,12 @@ var SchemaProvider = class {
13537
15517
  description = "Host-owned, opt-in Schema verification and bounded local-file transaction control plane";
13538
15518
  async list(request, _context) {
13539
15519
  const query = request.query?.toLowerCase();
13540
- return query ? descriptors9.filter(
15520
+ return query ? descriptors12.filter(
13541
15521
  (descriptor) => `${descriptor.name} ${descriptor.description}`.toLowerCase().includes(query)
13542
- ) : descriptors9;
15522
+ ) : descriptors12;
13543
15523
  }
13544
15524
  async describe(actionName, _context) {
13545
- return descriptors9.find((descriptor) => descriptor.name === actionName);
15525
+ return descriptors12.find((descriptor) => descriptor.name === actionName);
13546
15526
  }
13547
15527
  prepareArguments(actionName, args) {
13548
15528
  return normalizeSchemaArgs(actionName, args);
@@ -13596,7 +15576,7 @@ var SUMMARY_CHARS = 4e3;
13596
15576
  var BATCH_CHARS = 16e3;
13597
15577
  var IDLE_BATCH_MS = 40;
13598
15578
  var oneLine = (text) => text.replace(/[\u0000-\u001f\u007f]/g, " ");
13599
- var clip2 = (text, limit) => text.length > limit ? `${text.slice(0, limit)}
15579
+ var clip3 = (text, limit) => text.length > limit ? `${text.slice(0, limit)}
13600
15580
  [truncated; use agents.wait({id}) for the full result]` : text;
13601
15581
  var AgentCompletionInbox = class {
13602
15582
  constructor(pi, context) {
@@ -13663,8 +15643,8 @@ var AgentCompletionInbox = class {
13663
15643
  status: result.status,
13664
15644
  startedAt: result.startedAt,
13665
15645
  ...result.finishedAt !== void 0 ? { finishedAt: result.finishedAt } : {},
13666
- text: clip2(result.text, SUMMARY_CHARS),
13667
- ...result.error !== void 0 ? { error: clip2(result.error, SUMMARY_CHARS) } : {}
15646
+ text: clip3(result.text, SUMMARY_CHARS),
15647
+ ...result.error !== void 0 ? { error: clip3(result.error, SUMMARY_CHARS) } : {}
13668
15648
  },
13669
15649
  delivered
13670
15650
  });
@@ -13711,7 +15691,7 @@ var AgentCompletionInbox = class {
13711
15691
  const seconds = Math.round(Math.max(0, (result.finishedAt ?? Date.now()) - result.startedAt) / 1e3);
13712
15692
  const summary = [result.error, result.text].filter(Boolean).join("\n");
13713
15693
  return `Agent ${oneLine(result.name).slice(0, 80)} (${result.id}) ${result.status} after ${seconds}s:
13714
- ${clip2(summary || "no result", perResult)}`;
15694
+ ${clip3(summary || "no result", perResult)}`;
13715
15695
  })
13716
15696
  ].join("\n\n");
13717
15697
  deliver({
@@ -14004,6 +15984,16 @@ var DurableShellBridge = class _DurableShellBridge {
14004
15984
  const settings = this.options.settings();
14005
15985
  const home = this.home;
14006
15986
  const scriptDirectory = path15.join(this.#stateDirectory, "durable-shell");
15987
+ let wrapScript;
15988
+ if (options.notify) {
15989
+ if (!this.options.notify) throw new Error("pi.bash notify requires an enabled Fabric mesh");
15990
+ wrapScript = await this.options.notify({
15991
+ topic: options.notify.topic,
15992
+ kind: options.notify.kind,
15993
+ taskId: job.id,
15994
+ description: options.label
15995
+ });
15996
+ }
14007
15997
  return operations.createJevFabricBashOperations({
14008
15998
  cli,
14009
15999
  taskId: job.id,
@@ -14013,6 +16003,7 @@ var DurableShellBridge = class _DurableShellBridge {
14013
16003
  defaultTimeoutMs: Math.min(settings.timeoutMs, JEV_FABRIC_START_MAX_MS),
14014
16004
  maxTimeoutMs: JEV_FABRIC_START_MAX_MS,
14015
16005
  label: options.label,
16006
+ wrapScript,
14016
16007
  onStarted: async (jobId, scriptPath) => {
14017
16008
  if (job.durable) job.durable.jobId = jobId;
14018
16009
  if (!options.ownerId) return;
@@ -14070,9 +16061,9 @@ var DurableShellBridge = class _DurableShellBridge {
14070
16061
  const existing = this.jobs.list().find((job) => job.durable?.jobId === jobId);
14071
16062
  if (existing) return existing;
14072
16063
  const status = await cli.status(jobId);
14073
- const { randomUUID: randomUUID7 } = await import("node:crypto");
16064
+ const { randomUUID: randomUUID8 } = await import("node:crypto");
14074
16065
  const record = {
14075
- taskId: randomUUID7(),
16066
+ taskId: randomUUID8(),
14076
16067
  jobId,
14077
16068
  home: this.home,
14078
16069
  ownerId: this.options.ownerId ?? "",
@@ -14159,9 +16150,11 @@ var FabricRuntimeState = class {
14159
16150
  this.prewalk = options.prewalk ?? new PrewalkController();
14160
16151
  this.prewalkDrift = options.prewalkDrift ?? new PrewalkDriftTracker();
14161
16152
  this.sessionApprovals = options.sessionApprovals ?? new FabricSessionApprovals();
16153
+ this.thinking = options.thinking ?? new FabricThinkingController(pi, () => this.#config?.thinking?.bounds ?? {});
14162
16154
  this.#paths = options.paths;
14163
16155
  this.#managedHost = options.managedHost;
14164
16156
  this.#entryIdentity = options.entryIdentity;
16157
+ this.#foregroundTools = options.foregroundTools;
14165
16158
  }
14166
16159
  #registry;
14167
16160
  #config;
@@ -14177,8 +16170,11 @@ var FabricRuntimeState = class {
14177
16170
  #globalActors;
14178
16171
  #mesh;
14179
16172
  #identity;
16173
+ /** Durable decisions for headless approvals and routed child dialogs; mesh-enabled sessions only. */
16174
+ #decisions;
14180
16175
  #mainAgent;
14181
16176
  #participants;
16177
+ #providerParticipants = new ProviderParticipantRegistry();
14182
16178
  #control;
14183
16179
  #lifecycle;
14184
16180
  #residency;
@@ -14206,9 +16202,11 @@ var FabricRuntimeState = class {
14206
16202
  prewalk;
14207
16203
  prewalkDrift;
14208
16204
  sessionApprovals;
16205
+ thinking;
14209
16206
  #paths;
14210
16207
  #managedHost;
14211
16208
  #entryIdentity;
16209
+ #foregroundTools;
14212
16210
  #widgetDismissedAt = 0;
14213
16211
  #suppressResidentGuidanceSync = false;
14214
16212
  get initialized() {
@@ -14338,7 +16336,29 @@ var FabricRuntimeState = class {
14338
16336
  agentDir: resolveAgentDir(),
14339
16337
  ownerId: context.sessionManager?.getSessionId?.(),
14340
16338
  settings: () => (this.#config ?? DEFAULT_FABRIC_CONFIG).executor.jevFabric,
14341
- middleware: () => readFabricBashMiddleware(this.capturedTools.get("bash")?.definition)
16339
+ middleware: () => readFabricBashMiddleware(this.capturedTools.get("bash")?.definition),
16340
+ notify: async ({ topic, kind, taskId, description }) => {
16341
+ const mesh = this.#mesh;
16342
+ if (!mesh || !this.#identity || !this.#config?.mesh.enabled) {
16343
+ throw new Error("pi.bash notify requires an enabled Fabric mesh");
16344
+ }
16345
+ const { token } = await createMeshGrant(mesh, {
16346
+ topic: assertPublicMeshTopic(topic),
16347
+ kind: kind ?? "task.completed",
16348
+ ttlMs: Math.max(JEV_FABRIC_START_MAX_MS, 7 * 24 * 36e5),
16349
+ uses: 1,
16350
+ createdBy: this.#identity
16351
+ });
16352
+ const argv = meshCliArgv();
16353
+ return (command) => wrapDurableNotifyScript(command, {
16354
+ argv,
16355
+ root: mesh.root,
16356
+ token,
16357
+ kind: kind ?? "task.completed",
16358
+ taskId,
16359
+ ...description !== void 0 ? { description } : {}
16360
+ });
16361
+ }
14342
16362
  });
14343
16363
  }
14344
16364
  this.#registry = new ActionRegistry(
@@ -14433,6 +16453,9 @@ var FabricRuntimeState = class {
14433
16453
  if (this.#managedHost) {
14434
16454
  this.#registry.markUnavailable("jev", "Jev programs are unavailable in managed hosts");
14435
16455
  this.#registry.markUnavailable("cache", "Native prompt-cache access is unavailable in managed hosts");
16456
+ this.#registry.markUnavailable("thinking", "Host thinking control is unavailable in managed hosts");
16457
+ this.#registry.markUnavailable("decisions", "Durable decisions are unavailable in managed hosts");
16458
+ this.#registry.markUnavailable("programs", "Saved programs are unavailable in managed hosts");
14436
16459
  for (const name of ["agents", "schema", "compact", "memory", "mesh", "state"]) {
14437
16460
  if (["agents", "schema", "compact"].includes(name) || this.#managedHost.has(name)) {
14438
16461
  await builtins.install(createProviderComponent({
@@ -14451,7 +16474,21 @@ var FabricRuntimeState = class {
14451
16474
  await builtins.install(createProviderComponent({
14452
16475
  provider: "cache",
14453
16476
  description: "Local prompt-cache observations and scoped native warming",
14454
- create: () => new CacheProvider(this.pi, context, identity.kind === "main")
16477
+ create: () => new CacheProvider(this.pi, context, identity.kind === "main", this.#foregroundTools)
16478
+ }));
16479
+ await builtins.install(createProviderComponent({
16480
+ provider: "thinking",
16481
+ description: "Bounded host-session thinking control",
16482
+ create: () => new ThinkingProvider(this.thinking, sessionId)
16483
+ }));
16484
+ await builtins.install(createProviderComponent({
16485
+ provider: "programs",
16486
+ description: "Content-addressed saved programs",
16487
+ create: () => new ProgramsProvider(
16488
+ new ProgramStore(programsDirectory(context.cwd)),
16489
+ () => (this.#config ?? DEFAULT_FABRIC_CONFIG).executor.kernel,
16490
+ (parentToolCallId) => this.#execution?.nestedProgramRunner(parentToolCallId)
16491
+ )
14455
16492
  }));
14456
16493
  const fabricSessionId = process.env.PI_FABRIC_SESSION_ID?.trim() || sessionId;
14457
16494
  const ownsPersistentActorRegistry = identity.kind === "main" && !enforceSchema && projectTrusted && this.#config.mesh.enabled;
@@ -14472,20 +16509,22 @@ var FabricRuntimeState = class {
14472
16509
  this.#config.mesh.maxReadEvents
14473
16510
  );
14474
16511
  const hostId = identity.kind === "main" ? mainAgentId : `runtime:${sessionId}`;
16512
+ this.#control = new FabricControlPlane(this.#mesh, identity, {
16513
+ enabled: this.#config.mesh.enabled,
16514
+ hostId,
16515
+ pollMs: this.#config.mesh.actorPollMs
16516
+ });
14475
16517
  this.#participants = new ParticipantDirectory(this.#mesh, {
14476
16518
  enabled: this.#config.mesh.enabled,
14477
16519
  hostId,
14478
16520
  rootId: mainAgentId,
14479
16521
  identity,
16522
+ ownerIncarnation: this.#control.incarnation,
14480
16523
  ...process.env.PI_FABRIC_OWNER_HOST_ID ? { selfOwnerHostId: process.env.PI_FABRIC_OWNER_HOST_ID } : {},
14481
16524
  ...process.env.PI_FABRIC_OWNER_IDENTITY_ID ? { selfOwnerIdentityId: process.env.PI_FABRIC_OWNER_IDENTITY_ID } : {}
14482
16525
  });
14483
- this.#control = new FabricControlPlane(this.#mesh, identity, {
14484
- enabled: this.#config.mesh.enabled,
14485
- hostId,
14486
- pollMs: this.#config.mesh.actorPollMs
14487
- });
14488
16526
  await builtins.mesh(this.#config, this.#mesh, identity, this.#participants);
16527
+ this.#decisions = this.#config.mesh.enabled ? new DecisionStore(this.#mesh, identity) : void 0;
14489
16528
  this.#schema = new SchemaController(
14490
16529
  context.cwd,
14491
16530
  this.#config.schema,
@@ -14506,7 +16545,10 @@ var FabricRuntimeState = class {
14506
16545
  await builtins.install(createProviderComponent({
14507
16546
  provider: "compact",
14508
16547
  description: "Host context compaction controller",
14509
- create: () => new CompactProvider(this.#compact)
16548
+ create: () => new CompactProvider(this.#compact, {
16549
+ config: () => (this.#config ?? DEFAULT_FABRIC_CONFIG).compaction,
16550
+ appendEntry: (customType, data) => this.pi.appendEntry(customType, data)
16551
+ })
14510
16552
  }));
14511
16553
  const agentConfig = enforceSchema ? { ...this.#config.agents, enabled: false } : this.#config.agents;
14512
16554
  const modelsConfig = this.#config.models;
@@ -14567,6 +16609,9 @@ var FabricRuntimeState = class {
14567
16609
  fabricExtensionPath: this.#paths.extension
14568
16610
  } : {},
14569
16611
  resolveInheritedSessionPins: () => resolveInheritedSessionPins(context.sessionManager?.getEntries?.() ?? []),
16612
+ thinkingBounds: () => this.#config?.thinking?.bounds ?? {},
16613
+ sessionId: () => context.sessionManager?.getSessionId?.(),
16614
+ executorRuntime: () => this.#config?.schema.mode === "enforce" ? "quickjs" : this.#config?.executor.runtime,
14570
16615
  resolveParticipantGuidance: ({ model, runner }) => {
14571
16616
  const targetModel = model ?? (runner === "pi" && context.model ? `${context.model.provider}/${context.model.id}` : void 0);
14572
16617
  if (!targetModel) return void 0;
@@ -14600,7 +16645,8 @@ var FabricRuntimeState = class {
14600
16645
  if (lifecycle) void lifecycle.publish(event).catch(() => void 0);
14601
16646
  },
14602
16647
  onBackgroundComplete: (result) => completionInbox.enqueue(result),
14603
- onResultConsumed: (id2) => completionInbox.acknowledge(id2)
16648
+ onResultConsumed: (id2) => completionInbox.acknowledge(id2),
16649
+ onChildQuestion: (request) => routeChildQuestion(request, { context, ...this.#decisions ? { store: this.#decisions } : {} })
14604
16650
  });
14605
16651
  const canManageActor = (actorId) => {
14606
16652
  const participant = this.#participants?.get(actorId);
@@ -14746,6 +16792,9 @@ ${escapeXmlText(text)}
14746
16792
  );
14747
16793
  this.#agents.subscribeUi(() => this.#participants?.scheduleRefresh());
14748
16794
  this.#actors.subscribe(() => this.#participants?.scheduleRefresh());
16795
+ const providerParticipants = this.#providerParticipants;
16796
+ this.#participants.registerSource(() => providerParticipants.records(mainAgentId, hostId, identity.id));
16797
+ providerParticipants.subscribe(() => this.#participants?.scheduleRefresh());
14749
16798
  const agentsProvider = new AgentsProvider(
14750
16799
  this.#agents,
14751
16800
  this.#actors,
@@ -14759,6 +16808,7 @@ ${escapeXmlText(text)}
14759
16808
  false,
14760
16809
  () => this.#config?.models ?? DEFAULT_FABRIC_CONFIG.models
14761
16810
  );
16811
+ agentsProvider.providerParticipants = providerParticipants;
14762
16812
  this.#agentsProvider = agentsProvider;
14763
16813
  this.#control.start((command, from, signal) => agentsProvider.acceptControl(command, from, signal));
14764
16814
  try {
@@ -14887,6 +16937,17 @@ ${escapeXmlText(advice.message)}
14887
16937
  this.capturedTools,
14888
16938
  this.#managedHost ? (name) => this.#managedHost.ownsProvider(name) : void 0
14889
16939
  );
16940
+ this.#execution.setParticipantRegistry(this.#providerParticipants);
16941
+ const events = this.pi.events;
16942
+ if (events) this.#execution.setEventEmitter((channel, data) => events.emit(channel, data));
16943
+ const decisions = this.#decisions;
16944
+ if (decisions) {
16945
+ this.#execution.setHeadlessApproval((action, reason, signal) => requestHeadlessApproval(decisions, action, {
16946
+ ...reason ? { reason } : {},
16947
+ ...this.#config?.approvals.headlessTimeoutMs ? { timeoutMs: this.#config.approvals.headlessTimeoutMs } : {},
16948
+ ...signal ? { signal } : {}
16949
+ }));
16950
+ }
14890
16951
  const discovery = {
14891
16952
  version: 1,
14892
16953
  register: (provider, options) => this.registerExternal(provider, options)
@@ -14966,7 +17027,8 @@ ${escapeXmlText(advice.message)}
14966
17027
  () => this.#sessionCapabilityLease?.view,
14967
17028
  (ref) => {
14968
17029
  const current = this.#config;
14969
- if (current.approvals[ref.startsWith("mcp.") ? "network" : "read"] !== "allow") return false;
17030
+ const mode = actionApprovalOverride(current.approvals.actions, ref) ?? current.approvals[ref.startsWith("mcp.") ? "network" : "read"];
17031
+ if (mode !== "allow") return false;
14970
17032
  if (ref.startsWith("pi.") && !current.fullCodeMode && current.schema.mode !== "enforce") return false;
14971
17033
  return current.schema.mode !== "enforce" || schemaRefAllowedInEnforce(ref);
14972
17034
  },
@@ -15137,7 +17199,7 @@ ${escapeXmlText(advice.message)}
15137
17199
  name: self.name,
15138
17200
  kind: self.kind,
15139
17201
  rootId: self.rootId,
15140
- runner: self.runner,
17202
+ runner: self.runner ?? "pi",
15141
17203
  ownerHostId: self.ownerHostId,
15142
17204
  ownerIdentityId: self.ownerIdentityId
15143
17205
  },
@@ -15160,6 +17222,23 @@ ${escapeXmlText(advice.message)}
15160
17222
  this.#externalProviders.set(provider.name, provider);
15161
17223
  if (this.#registry) this.#registry.register(provider, options);
15162
17224
  }
17225
+ /** Withdraw a direct registration through the same retire/release path a
17226
+ * component lease uses. The host owns the instance, so it is not closed. */
17227
+ withdrawExternal(name, generation) {
17228
+ if (this.#managedHost) return false;
17229
+ const provider = this.#externalProviders.get(name);
17230
+ if (!provider) return false;
17231
+ const registry = this.#registry;
17232
+ const withdrawn = registry?.unregister(name, {
17233
+ provider,
17234
+ ...generation !== void 0 ? { generation } : {},
17235
+ keepProviderOpen: true
17236
+ });
17237
+ if (!withdrawn && generation !== void 0) return false;
17238
+ this.#externalProviders.delete(name);
17239
+ this.#providerParticipants.releaseProvider(name);
17240
+ return true;
17241
+ }
15163
17242
  registerExternalComponent(component, options = {}) {
15164
17243
  if (this.#managedHost) throw new Error("Managed host component registration is disabled");
15165
17244
  if (component.name.startsWith(FABRIC_PROVIDER_COMPONENT_PREFIX)) {
@@ -15181,6 +17260,7 @@ ${escapeXmlText(advice.message)}
15181
17260
  this.#suppressResidentGuidanceSync = true;
15182
17261
  await this.#deactivateRepairs();
15183
17262
  clearActiveCompiledSurface();
17263
+ this.#releaseProviderParticipants();
15184
17264
  await this.#participants?.quiesce().catch(() => void 0);
15185
17265
  this.#stopComponentWatch?.();
15186
17266
  this.#stopComponentWatch = void 0;
@@ -15257,6 +17337,11 @@ ${escapeXmlText(advice.message)}
15257
17337
  capturedTools: this.capturedTools.list().map((entry) => entry.name)
15258
17338
  });
15259
17339
  }
17340
+ // Session teardown forgets provider participants; providers own their work.
17341
+ #releaseProviderParticipants() {
17342
+ this.#providerParticipants.releaseAll();
17343
+ this.#providerParticipants = new ProviderParticipantRegistry();
17344
+ }
15260
17345
  async #deactivateRepairs() {
15261
17346
  const repairs = this.#repairs;
15262
17347
  this.#repairs = void 0;
@@ -15273,6 +17358,7 @@ ${escapeXmlText(advice.message)}
15273
17358
  await this.shellJobs.close();
15274
17359
  await this.#deactivateRepairs();
15275
17360
  if (!this.#registry) return;
17361
+ this.#releaseProviderParticipants();
15276
17362
  await this.#participants?.quiesce().catch(() => void 0);
15277
17363
  this.#stopComponentWatch?.();
15278
17364
  this.#stopComponentWatch = void 0;