@graphrefly/ts 0.0.1 → 0.0.3

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 (333) hide show
  1. package/README.md +197 -117
  2. package/dist/actions-types-CH-XCU9O.d.cts +657 -0
  3. package/dist/actions-types-w2iPQTkv.d.ts +657 -0
  4. package/dist/adapters/index.cjs +5157 -2951
  5. package/dist/adapters/index.cjs.map +1 -1
  6. package/dist/adapters/index.d.cts +207 -70
  7. package/dist/adapters/index.d.ts +207 -70
  8. package/dist/adapters/index.js +3738 -1688
  9. package/dist/adapters/index.js.map +1 -1
  10. package/dist/adapters/nestjs/microservices.cjs +841 -0
  11. package/dist/adapters/nestjs/microservices.cjs.map +1 -0
  12. package/dist/adapters/nestjs/microservices.d.cts +45 -0
  13. package/dist/adapters/nestjs/microservices.d.ts +45 -0
  14. package/dist/adapters/nestjs/microservices.js +206 -0
  15. package/dist/adapters/nestjs/microservices.js.map +1 -0
  16. package/dist/adapters/nestjs/native.cjs +1391 -0
  17. package/dist/adapters/nestjs/native.cjs.map +1 -0
  18. package/dist/adapters/nestjs/native.d.cts +111 -0
  19. package/dist/adapters/nestjs/native.d.ts +111 -0
  20. package/dist/adapters/nestjs/native.js +577 -0
  21. package/dist/adapters/nestjs/native.js.map +1 -0
  22. package/dist/adapters/nestjs/websockets.cjs +924 -0
  23. package/dist/adapters/nestjs/websockets.cjs.map +1 -0
  24. package/dist/adapters/nestjs/websockets.d.cts +47 -0
  25. package/dist/adapters/nestjs/websockets.d.ts +47 -0
  26. package/dist/adapters/nestjs/websockets.js +286 -0
  27. package/dist/adapters/nestjs/websockets.js.map +1 -0
  28. package/dist/adapters/nestjs.cjs +1085 -0
  29. package/dist/adapters/nestjs.cjs.map +1 -0
  30. package/dist/adapters/nestjs.d.cts +385 -0
  31. package/dist/adapters/nestjs.d.ts +385 -0
  32. package/dist/adapters/nestjs.js +112 -0
  33. package/dist/adapters/nestjs.js.map +1 -0
  34. package/dist/adapters/observe-storage.d.cts +3 -3
  35. package/dist/adapters/observe-storage.d.ts +3 -3
  36. package/dist/adapters/observe-storage.js +4 -4
  37. package/dist/adapters/react.cjs.map +1 -1
  38. package/dist/adapters/react.d.cts +2 -2
  39. package/dist/adapters/react.d.ts +2 -2
  40. package/dist/adapters/react.js +1 -1
  41. package/dist/adapters/solid.cjs.map +1 -1
  42. package/dist/adapters/solid.d.cts +2 -2
  43. package/dist/adapters/solid.d.ts +2 -2
  44. package/dist/adapters/solid.js +1 -1
  45. package/dist/adapters/svelte.cjs.map +1 -1
  46. package/dist/adapters/svelte.d.cts +2 -2
  47. package/dist/adapters/svelte.d.ts +2 -2
  48. package/dist/adapters/svelte.js +1 -1
  49. package/dist/adapters/vue.cjs.map +1 -1
  50. package/dist/adapters/vue.d.cts +2 -2
  51. package/dist/adapters/vue.d.ts +2 -2
  52. package/dist/adapters/vue.js +1 -1
  53. package/dist/{agent-runtime-BesGDZcB.d.ts → agent-runtime-types-core-CKwrBDyi.d.ts} +171 -320
  54. package/dist/{agent-runtime-DZTJ3C-p.d.cts → agent-runtime-types-core-bfl4m0vM.d.cts} +171 -320
  55. package/dist/agent-runtime-types-tool-BLPV3azj.d.cts +695 -0
  56. package/dist/agent-runtime-types-tool-hwqvVqNt.d.ts +695 -0
  57. package/dist/agentic-memory-retention-CLwI76JK.d.ts +14 -0
  58. package/dist/agentic-memory-retention-Cz8GR6ie.d.cts +14 -0
  59. package/dist/{agentic-memory-DfuVZ-lY.d.cts → agentic-memory-types-JDr7MPhh.d.cts} +13 -57
  60. package/dist/{agentic-memory-BmRCvh0d.d.ts → agentic-memory-types-khYJgzKL.d.ts} +13 -57
  61. package/dist/{capability-admission-B0BzqAm5.d.cts → capability-admission-B8RNFyaZ.d.cts} +3 -3
  62. package/dist/{capability-admission-g0mn9hpq.d.ts → capability-admission-Dkw1Xz3r.d.ts} +3 -3
  63. package/dist/chunk-2KUAG2GZ.js +9693 -0
  64. package/dist/chunk-2KUAG2GZ.js.map +1 -0
  65. package/dist/{chunk-CZNV3VXM.js → chunk-3J7UPZL5.js} +11 -11
  66. package/dist/{chunk-HKK2JD7Z.js → chunk-3LYI6ADX.js} +12 -125
  67. package/dist/chunk-3LYI6ADX.js.map +1 -0
  68. package/dist/{chunk-YXMZ2N6J.js → chunk-4M37FH2I.js} +1071 -1025
  69. package/dist/chunk-4M37FH2I.js.map +1 -0
  70. package/dist/{chunk-YDSIVHRR.js → chunk-4NWSNI4K.js} +1598 -1584
  71. package/dist/chunk-4NWSNI4K.js.map +1 -0
  72. package/dist/{chunk-Z2ANQ6JW.js → chunk-4Q77MMJY.js} +2 -2
  73. package/dist/{chunk-SS2A464I.js → chunk-54WPEODM.js} +3 -3
  74. package/dist/chunk-54WPEODM.js.map +1 -0
  75. package/dist/chunk-6E76H4OU.js +132 -0
  76. package/dist/chunk-6E76H4OU.js.map +1 -0
  77. package/dist/chunk-7GOTIIQ7.js +819 -0
  78. package/dist/chunk-7GOTIIQ7.js.map +1 -0
  79. package/dist/{chunk-V7CIJE4B.js → chunk-DKFWDTVY.js} +92 -9
  80. package/dist/chunk-DKFWDTVY.js.map +1 -0
  81. package/dist/{chunk-FBUU43PM.js → chunk-E4QCH32M.js} +448 -446
  82. package/dist/chunk-E4QCH32M.js.map +1 -0
  83. package/dist/{chunk-XKXWK2KP.js → chunk-GXU6WFEJ.js} +1157 -1021
  84. package/dist/chunk-GXU6WFEJ.js.map +1 -0
  85. package/dist/{chunk-K3FXTC3I.js → chunk-HJACH5PU.js} +3 -3
  86. package/dist/{chunk-GTPCOEOZ.js → chunk-IDMLXLLG.js} +3 -3
  87. package/dist/{chunk-DKP56CSW.js → chunk-JKAYLDQV.js} +2 -2
  88. package/dist/{chunk-4VLAQHZI.js → chunk-K7FB3JTD.js} +17 -1
  89. package/dist/chunk-K7FB3JTD.js.map +1 -0
  90. package/dist/{chunk-43BKLFZU.js → chunk-KFURM6FM.js} +10 -10
  91. package/dist/{chunk-H75VXTGT.js → chunk-L6LDXRWE.js} +3 -3
  92. package/dist/{chunk-H75VXTGT.js.map → chunk-L6LDXRWE.js.map} +1 -1
  93. package/dist/chunk-MCOFHMUU.js +4131 -0
  94. package/dist/chunk-MCOFHMUU.js.map +1 -0
  95. package/dist/chunk-MQEQMS7B.js +1009 -0
  96. package/dist/chunk-MQEQMS7B.js.map +1 -0
  97. package/dist/chunk-MTELVIYR.js +1421 -0
  98. package/dist/chunk-MTELVIYR.js.map +1 -0
  99. package/dist/{chunk-3JR3EDB2.js → chunk-NNDIFUKX.js} +121 -115
  100. package/dist/chunk-NNDIFUKX.js.map +1 -0
  101. package/dist/{chunk-2747WN4Y.js → chunk-PUSRRALM.js} +3 -3
  102. package/dist/{chunk-QFY4AFY4.js → chunk-PVC7WDKI.js} +58 -52
  103. package/dist/chunk-PVC7WDKI.js.map +1 -0
  104. package/dist/{chunk-VTHLCFN4.js → chunk-RAHNUYA5.js} +2 -2
  105. package/dist/chunk-TQPCAIQI.js +612 -0
  106. package/dist/chunk-TQPCAIQI.js.map +1 -0
  107. package/dist/{chunk-IXZBUWSP.js → chunk-UEMN5URK.js} +2 -2
  108. package/dist/chunk-WOS7RJYZ.js +1320 -0
  109. package/dist/chunk-WOS7RJYZ.js.map +1 -0
  110. package/dist/{chunk-6PHB5CJS.js → chunk-ZLFRB6FI.js} +2 -2
  111. package/dist/composition/index.cjs +1228 -1076
  112. package/dist/composition/index.cjs.map +1 -1
  113. package/dist/composition/index.d.cts +3 -3
  114. package/dist/composition/index.d.ts +3 -3
  115. package/dist/composition/index.js +4 -4
  116. package/dist/core/index.cjs +1198 -1046
  117. package/dist/core/index.cjs.map +1 -1
  118. package/dist/core/index.d.cts +23 -2
  119. package/dist/core/index.d.ts +23 -2
  120. package/dist/core/index.js +2 -2
  121. package/dist/cqrs/index.d.cts +3 -3
  122. package/dist/cqrs/index.d.ts +3 -3
  123. package/dist/cqrs/messaging.d.cts +4 -4
  124. package/dist/cqrs/messaging.d.ts +4 -4
  125. package/dist/cqrs/work-queue.d.cts +5 -5
  126. package/dist/cqrs/work-queue.d.ts +5 -5
  127. package/dist/data-structures/index.cjs +1226 -1074
  128. package/dist/data-structures/index.cjs.map +1 -1
  129. package/dist/data-structures/index.d.cts +8 -7
  130. package/dist/data-structures/index.d.ts +8 -7
  131. package/dist/data-structures/index.js +6 -5
  132. package/dist/{describe-DYMw_l1C.d.cts → describe-BumQ-3_0.d.cts} +1 -1
  133. package/dist/{describe-BpyJuWkw.d.ts → describe-cYr_Z5zm.d.ts} +1 -1
  134. package/dist/executors/tool-provider-adapters.cjs +3091 -0
  135. package/dist/executors/tool-provider-adapters.cjs.map +1 -0
  136. package/dist/executors/tool-provider-adapters.d.cts +174 -0
  137. package/dist/executors/tool-provider-adapters.d.ts +174 -0
  138. package/dist/executors/tool-provider-adapters.js +1336 -0
  139. package/dist/executors/tool-provider-adapters.js.map +1 -0
  140. package/dist/executors/tool-provider-runtime.cjs +5178 -0
  141. package/dist/executors/tool-provider-runtime.cjs.map +1 -0
  142. package/dist/executors/tool-provider-runtime.d.cts +17 -0
  143. package/dist/executors/tool-provider-runtime.d.ts +17 -0
  144. package/dist/executors/tool-provider-runtime.js +15 -0
  145. package/dist/executors/tool-provider-runtime.js.map +1 -0
  146. package/dist/executors/tool-provider.cjs +6392 -0
  147. package/dist/executors/tool-provider.cjs.map +1 -0
  148. package/dist/executors/tool-provider.d.cts +60 -0
  149. package/dist/executors/tool-provider.d.ts +60 -0
  150. package/dist/executors/tool-provider.js +89 -0
  151. package/dist/executors/tool-provider.js.map +1 -0
  152. package/dist/executors/work-queue.d.cts +6 -6
  153. package/dist/executors/work-queue.d.ts +6 -6
  154. package/dist/graph/index.cjs +1499 -1341
  155. package/dist/graph/index.cjs.map +1 -1
  156. package/dist/graph/index.d.cts +9 -8
  157. package/dist/graph/index.d.ts +9 -8
  158. package/dist/graph/index.js +23 -22
  159. package/dist/{graph-DCEWh4T2.d.cts → graph-C1C-wb0L.d.cts} +266 -137
  160. package/dist/{graph-D-1-SQeC.d.ts → graph-CS0b4V9B.d.ts} +266 -137
  161. package/dist/{index-72VZC0-E.d.cts → index-DLrNopda.d.cts} +151 -10
  162. package/dist/{index-Bmxeu0nK.d.ts → index-DzJni3_6.d.ts} +151 -10
  163. package/dist/index.cjs +3397 -3140
  164. package/dist/index.cjs.map +1 -1
  165. package/dist/index.d.cts +12 -9
  166. package/dist/index.d.ts +12 -9
  167. package/dist/index.js +110 -109
  168. package/dist/inspection/boundary.d.cts +4 -4
  169. package/dist/inspection/boundary.d.ts +4 -4
  170. package/dist/measurements-BWAnochv.d.ts +294 -0
  171. package/dist/measurements-B_gJfD8h.d.cts +294 -0
  172. package/dist/messaging/index.cjs +57 -51
  173. package/dist/messaging/index.cjs.map +1 -1
  174. package/dist/messaging/index.d.cts +11 -276
  175. package/dist/messaging/index.d.ts +11 -276
  176. package/dist/messaging/index.js +1 -1
  177. package/dist/operators/index.cjs +1228 -1076
  178. package/dist/operators/index.cjs.map +1 -1
  179. package/dist/operators/index.d.cts +5 -5
  180. package/dist/operators/index.d.ts +5 -5
  181. package/dist/operators/index.js +5 -5
  182. package/dist/orchestration/index.cjs +8844 -6071
  183. package/dist/orchestration/index.cjs.map +1 -1
  184. package/dist/orchestration/index.d.cts +171 -224
  185. package/dist/orchestration/index.d.ts +171 -224
  186. package/dist/orchestration/index.js +42 -991
  187. package/dist/orchestration/index.js.map +1 -1
  188. package/dist/orchestration/messaging.d.cts +5 -8
  189. package/dist/orchestration/messaging.d.ts +5 -8
  190. package/dist/orchestration/work-queue.cjs +1243 -5
  191. package/dist/orchestration/work-queue.cjs.map +1 -1
  192. package/dist/orchestration/work-queue.d.cts +121 -10
  193. package/dist/orchestration/work-queue.d.ts +121 -10
  194. package/dist/orchestration/work-queue.js +1067 -4
  195. package/dist/orchestration/work-queue.js.map +1 -1
  196. package/dist/patterns/event-flow.cjs +6 -20
  197. package/dist/patterns/event-flow.cjs.map +1 -1
  198. package/dist/patterns/event-flow.d.cts +4 -4
  199. package/dist/patterns/event-flow.d.ts +4 -4
  200. package/dist/patterns/event-flow.js +2 -2
  201. package/dist/patterns/index.cjs +453 -465
  202. package/dist/patterns/index.cjs.map +1 -1
  203. package/dist/patterns/index.d.cts +6 -5
  204. package/dist/patterns/index.d.ts +6 -5
  205. package/dist/patterns/index.js +3 -3
  206. package/dist/process-types-BB7oRhX3.d.cts +200 -0
  207. package/dist/process-types-QNhyoYJ8.d.ts +200 -0
  208. package/dist/{reactive-collection-DNV0-gFi.d.cts → reactive-collection-BYlWvtnp.d.cts} +4 -34
  209. package/dist/{reactive-collection-BAmfrGjd.d.ts → reactive-collection-efOEdGFN.d.ts} +4 -34
  210. package/dist/{reactive-collection-storage-BNEldDyi.d.cts → reactive-collection-storage-BjoLsoiC.d.cts} +5 -5
  211. package/dist/{reactive-collection-storage-YZsAQsWK.d.ts → reactive-collection-storage-DwW6UuK_.d.ts} +5 -5
  212. package/dist/{reactive-map-DRD1LJ2H.d.cts → reactive-map-BHacbIqz.d.cts} +7 -2
  213. package/dist/{reactive-map-EsDiCmJk.d.ts → reactive-map-DN4Jyqnf.d.ts} +7 -2
  214. package/dist/render/index.d.cts +2 -2
  215. package/dist/render/index.d.ts +2 -2
  216. package/dist/scheduled-readiness-BmqXxnzX.d.ts +91 -0
  217. package/dist/scheduled-readiness-CYSw7KDE.d.cts +91 -0
  218. package/dist/semantic-memory-graph-B_LwbM-E.d.cts +30 -0
  219. package/dist/semantic-memory-graph-rsFNNhwn.d.ts +30 -0
  220. package/dist/{semantic-memory-graph-DKuNzuWw.d.cts → semantic-memory-graph-types-Y73bbwVI.d.cts} +2 -28
  221. package/dist/{semantic-memory-graph-uwbwJdhe.d.ts → semantic-memory-graph-types-safmPkuX.d.ts} +2 -28
  222. package/dist/solutions/index.cjs +6353 -6169
  223. package/dist/solutions/index.cjs.map +1 -1
  224. package/dist/solutions/index.d.cts +12 -10
  225. package/dist/solutions/index.d.ts +12 -10
  226. package/dist/solutions/index.js +5 -5
  227. package/dist/solutions/reactive-layout/browser/index.cjs +116 -108
  228. package/dist/solutions/reactive-layout/browser/index.cjs.map +1 -1
  229. package/dist/solutions/reactive-layout/browser/index.d.cts +4 -4
  230. package/dist/solutions/reactive-layout/browser/index.d.ts +4 -4
  231. package/dist/solutions/reactive-layout/browser/index.js +3 -3
  232. package/dist/solutions/reactive-layout/index.cjs +3578 -3350
  233. package/dist/solutions/reactive-layout/index.cjs.map +1 -1
  234. package/dist/solutions/reactive-layout/index.d.cts +32 -576
  235. package/dist/solutions/reactive-layout/index.d.ts +32 -576
  236. package/dist/solutions/reactive-layout/index.js +65 -5
  237. package/dist/solutions/reactive-layout/node-canvas/index.cjs +127 -117
  238. package/dist/solutions/reactive-layout/node-canvas/index.cjs.map +1 -1
  239. package/dist/solutions/reactive-layout/node-canvas/index.d.cts +4 -4
  240. package/dist/solutions/reactive-layout/node-canvas/index.d.ts +4 -4
  241. package/dist/solutions/reactive-layout/node-canvas/index.js +3 -3
  242. package/dist/solutions/reactive-layout/react-native/index.cjs +127 -117
  243. package/dist/solutions/reactive-layout/react-native/index.cjs.map +1 -1
  244. package/dist/solutions/reactive-layout/react-native/index.d.cts +4 -4
  245. package/dist/solutions/reactive-layout/react-native/index.d.ts +4 -4
  246. package/dist/solutions/reactive-layout/react-native/index.js +3 -3
  247. package/dist/solutions/reactive-layout/skia/index.cjs +127 -117
  248. package/dist/solutions/reactive-layout/skia/index.cjs.map +1 -1
  249. package/dist/solutions/reactive-layout/skia/index.d.cts +4 -4
  250. package/dist/solutions/reactive-layout/skia/index.d.ts +4 -4
  251. package/dist/solutions/reactive-layout/skia/index.js +3 -3
  252. package/dist/solutions/work-item/actions.cjs +1609 -1428
  253. package/dist/solutions/work-item/actions.cjs.map +1 -1
  254. package/dist/solutions/work-item/actions.d.cts +23 -184
  255. package/dist/solutions/work-item/actions.d.ts +23 -184
  256. package/dist/solutions/work-item/actions.js +1558 -934
  257. package/dist/solutions/work-item/actions.js.map +1 -1
  258. package/dist/solutions/work-item/scheduling.cjs +9181 -1838
  259. package/dist/solutions/work-item/scheduling.cjs.map +1 -1
  260. package/dist/solutions/work-item/scheduling.d.cts +1763 -328
  261. package/dist/solutions/work-item/scheduling.d.ts +1763 -328
  262. package/dist/solutions/work-item/scheduling.js +117 -3
  263. package/dist/solutions/work-item/work-queue.d.cts +7 -7
  264. package/dist/solutions/work-item/work-queue.d.ts +7 -7
  265. package/dist/sources/browser.cjs +1318 -1083
  266. package/dist/sources/browser.cjs.map +1 -1
  267. package/dist/sources/browser.d.cts +22 -6
  268. package/dist/sources/browser.d.ts +22 -6
  269. package/dist/sources/browser.js +4 -4
  270. package/dist/sources/browser.js.map +1 -1
  271. package/dist/sources/index.cjs +1318 -1083
  272. package/dist/sources/index.cjs.map +1 -1
  273. package/dist/sources/index.d.cts +4 -4
  274. package/dist/sources/index.d.ts +4 -4
  275. package/dist/sources/index.js +4 -4
  276. package/dist/sources/node.d.cts +3 -3
  277. package/dist/sources/node.d.ts +3 -3
  278. package/dist/storage/browser.cjs +16 -0
  279. package/dist/storage/browser.cjs.map +1 -1
  280. package/dist/storage/browser.js +3 -3
  281. package/dist/storage/index.cjs +16 -0
  282. package/dist/storage/index.cjs.map +1 -1
  283. package/dist/storage/index.d.cts +5 -4
  284. package/dist/storage/index.d.ts +5 -4
  285. package/dist/storage/index.js +6 -6
  286. package/dist/storage/node.cjs +16 -0
  287. package/dist/storage/node.cjs.map +1 -1
  288. package/dist/storage/node.js +3 -3
  289. package/dist/{store-C-joM4gh.d.ts → store-6_CHF6Ge.d.ts} +1 -1
  290. package/dist/{store-CNJwmT-h.d.cts → store-BljX8RkQ.d.cts} +1 -1
  291. package/dist/types-BAw2QVVE.d.cts +274 -0
  292. package/dist/types-BUbbbh4f.d.cts +34 -0
  293. package/dist/types-CMnzoL54.d.cts +457 -0
  294. package/dist/{types-CcPIn7sy.d.cts → types-CTN3XoMl.d.cts} +57 -108
  295. package/dist/types-CV_ohy5T.d.cts +357 -0
  296. package/dist/{types-BsJvElYZ.d.ts → types-DChxk1vK.d.ts} +57 -108
  297. package/dist/types-DRu7SnLV.d.ts +274 -0
  298. package/dist/types-DeID_FRl.d.ts +34 -0
  299. package/dist/types-IhKH0hGW.d.ts +357 -0
  300. package/dist/types-ePlD2uyT.d.ts +457 -0
  301. package/dist/{work-item-runtime-qaVgsL0T.d.cts → work-item-runtime-types-BTxLskN5.d.cts} +3 -93
  302. package/dist/{work-item-runtime-C3M79vE9.d.ts → work-item-runtime-types-DAsZbb2y.d.ts} +3 -93
  303. package/dist/work-queue/index.cjs +957 -953
  304. package/dist/work-queue/index.cjs.map +1 -1
  305. package/dist/work-queue/index.d.cts +9 -357
  306. package/dist/work-queue/index.d.ts +9 -357
  307. package/dist/work-queue/index.js +957 -953
  308. package/dist/work-queue/index.js.map +1 -1
  309. package/package.json +611 -513
  310. package/dist/chunk-3JR3EDB2.js.map +0 -1
  311. package/dist/chunk-4VLAQHZI.js.map +0 -1
  312. package/dist/chunk-6XAIOL3X.js +0 -2407
  313. package/dist/chunk-6XAIOL3X.js.map +0 -1
  314. package/dist/chunk-FBUU43PM.js.map +0 -1
  315. package/dist/chunk-HKK2JD7Z.js.map +0 -1
  316. package/dist/chunk-PC3BTTBE.js +0 -3217
  317. package/dist/chunk-PC3BTTBE.js.map +0 -1
  318. package/dist/chunk-QFY4AFY4.js.map +0 -1
  319. package/dist/chunk-SS2A464I.js.map +0 -1
  320. package/dist/chunk-V7CIJE4B.js.map +0 -1
  321. package/dist/chunk-XKXWK2KP.js.map +0 -1
  322. package/dist/chunk-YDSIVHRR.js.map +0 -1
  323. package/dist/chunk-YXMZ2N6J.js.map +0 -1
  324. /package/dist/{chunk-CZNV3VXM.js.map → chunk-3J7UPZL5.js.map} +0 -0
  325. /package/dist/{chunk-Z2ANQ6JW.js.map → chunk-4Q77MMJY.js.map} +0 -0
  326. /package/dist/{chunk-K3FXTC3I.js.map → chunk-HJACH5PU.js.map} +0 -0
  327. /package/dist/{chunk-GTPCOEOZ.js.map → chunk-IDMLXLLG.js.map} +0 -0
  328. /package/dist/{chunk-DKP56CSW.js.map → chunk-JKAYLDQV.js.map} +0 -0
  329. /package/dist/{chunk-43BKLFZU.js.map → chunk-KFURM6FM.js.map} +0 -0
  330. /package/dist/{chunk-2747WN4Y.js.map → chunk-PUSRRALM.js.map} +0 -0
  331. /package/dist/{chunk-VTHLCFN4.js.map → chunk-RAHNUYA5.js.map} +0 -0
  332. /package/dist/{chunk-IXZBUWSP.js.map → chunk-UEMN5URK.js.map} +0 -0
  333. /package/dist/{chunk-6PHB5CJS.js.map → chunk-ZLFRB6FI.js.map} +0 -0
@@ -0,0 +1,4131 @@
1
+ import {
2
+ requestToolProviderAdapterRun,
3
+ runRequestIdentityIssues
4
+ } from "./chunk-7GOTIIQ7.js";
5
+ import {
6
+ boundPublicText,
7
+ canonicalPublicSourceRefs,
8
+ cloneGraphVisibleMaterial,
9
+ dataIssue,
10
+ forEachDepBatch,
11
+ isRecord,
12
+ maxPublicReasonChars,
13
+ projectRuntimeFact,
14
+ publicMaterialForbiddenKeys,
15
+ ref,
16
+ sanitizeAdapterInputIssue,
17
+ sanitizeAdapterInputSourceRefs,
18
+ sanitizeGraphVisibleRecord,
19
+ sanitizeProviderGraphVisibleRecord,
20
+ stableJsonStringify,
21
+ uniqueSourceRefs
22
+ } from "./chunk-TQPCAIQI.js";
23
+ import {
24
+ timeout
25
+ } from "./chunk-PUSRRALM.js";
26
+ import {
27
+ nextRetryDelayMs,
28
+ retryPolicy,
29
+ shouldRetry
30
+ } from "./chunk-OOEN33FB.js";
31
+ import {
32
+ depBatch
33
+ } from "./chunk-WQIA3GFB.js";
34
+
35
+ // src/orchestration/agent-runtime-effect-completion.ts
36
+ function effectRunCompletionProjector(graph, opts) {
37
+ const name = opts.name ?? "effectRunCompletion";
38
+ const decisions = opts.decisions ?? [];
39
+ const requestStatuses = opts.requestStatuses ?? [];
40
+ const requestFacts = opts.requestFacts ?? [];
41
+ const resultCandidates = opts.resultCandidates ?? [];
42
+ const deps = [
43
+ opts.effectRuns,
44
+ ...decisions,
45
+ ...requestStatuses,
46
+ ...requestFacts,
47
+ ...resultCandidates
48
+ ];
49
+ const decisionStart = 1;
50
+ const requestStatusStart = decisionStart + decisions.length;
51
+ const requestFactStart = requestStatusStart + requestStatuses.length;
52
+ const resultCandidateStart = requestFactStart + requestFacts.length;
53
+ const now = opts.now ?? Date.now;
54
+ const runtime = graph.node(
55
+ deps,
56
+ (ctx) => {
57
+ const state = ctx.state.get() ?? emptyEffectRunCompletionState();
58
+ const touchedEffectRunIds = /* @__PURE__ */ new Set();
59
+ for (const raw of depBatch(ctx, 0) ?? []) {
60
+ const run = raw;
61
+ state.runs.set(run.effectRunId, run);
62
+ touchedEffectRunIds.add(run.effectRunId);
63
+ }
64
+ forEachDepBatch(ctx, requestFactStart, requestFacts.length, (raw) => {
65
+ const fact = raw;
66
+ if (fact.kind === "issued") {
67
+ state.requests.set(fact.requestId, fact);
68
+ touchedEffectRunIds.add(fact.effectRunId);
69
+ const existingStatus = state.statusByRequest.get(fact.requestId);
70
+ if (existingStatus !== void 0 && !statusMatchesRequest(existingStatus, fact)) {
71
+ emitEffectRunIssue(
72
+ ctx,
73
+ state,
74
+ "stale-request-status",
75
+ `AgentRequest status for '${fact.requestId}' did not match its issued effectRun/operation identity`,
76
+ fact.effectRunId,
77
+ [ref("agent-request", fact.requestId)]
78
+ );
79
+ }
80
+ const result = state.resultsByEffectRun.get(fact.effectRunId);
81
+ if (result !== void 0 && fact.required) {
82
+ state.issueSeq += 1;
83
+ const issue = dataIssue(
84
+ "late-required-request-after-effect-run-result",
85
+ `Required request '${fact.requestId}' arrived after EffectRun '${fact.effectRunId}' already had a terminal result`,
86
+ {
87
+ subjectId: fact.effectRunId,
88
+ refs: [
89
+ ref("agent-request", fact.requestId),
90
+ ref("effect-run-result", result.resultId)
91
+ ]
92
+ }
93
+ );
94
+ ctx.down([
95
+ ["DATA", { kind: "issue", issue }],
96
+ [
97
+ "DATA",
98
+ {
99
+ kind: "audit",
100
+ audit: {
101
+ id: `${fact.effectRunId}:late-required-request:${state.issueSeq}`,
102
+ kind: "late-required-request-after-effect-run-result",
103
+ subjectId: fact.effectRunId,
104
+ issueCode: issue.code,
105
+ sourceRefs: [
106
+ ref("agent-request", fact.requestId),
107
+ ref("effect-run-result", result.resultId)
108
+ ]
109
+ }
110
+ }
111
+ ]
112
+ ]);
113
+ }
114
+ } else if (fact.kind === "status") {
115
+ acceptRequestStatus(ctx, state, fact);
116
+ touchedEffectRunIds.add(fact.effectRunId);
117
+ }
118
+ });
119
+ forEachDepBatch(ctx, requestStatusStart, requestStatuses.length, (raw) => {
120
+ const status = raw;
121
+ acceptRequestStatus(ctx, state, status);
122
+ touchedEffectRunIds.add(status.effectRunId);
123
+ });
124
+ forEachDepBatch(ctx, resultCandidateStart, resultCandidates.length, (raw) => {
125
+ acceptEffectRunResultCandidate(ctx, state, raw);
126
+ });
127
+ forEachDepBatch(ctx, decisionStart, decisions.length, (raw) => {
128
+ const decision = raw;
129
+ state.decisions.set(decision.decisionId, decision);
130
+ touchedEffectRunIds.add(decision.effectRunId);
131
+ });
132
+ for (const decision of state.decisions.values()) {
133
+ if (state.resultsByEffectRun.has(decision.effectRunId)) continue;
134
+ const candidate = candidateFromDecision(decision, state, now());
135
+ if (candidate === void 0) continue;
136
+ acceptEffectRunResultCandidate(ctx, state, candidate);
137
+ }
138
+ for (const effectRunId of touchedEffectRunIds) {
139
+ if (!state.resultsByEffectRun.has(effectRunId)) {
140
+ emitEffectRunStatus(
141
+ ctx,
142
+ effectRunId,
143
+ "pending",
144
+ requiredPendingRequests(effectRunId, state),
145
+ requiredTerminalRequests(effectRunId, state)
146
+ );
147
+ }
148
+ }
149
+ ctx.state.set(state);
150
+ },
151
+ { name: `${name}/runtime`, factory: "effectRunCompletionProjector" }
152
+ );
153
+ return {
154
+ results: projectRuntimeFact(
155
+ graph,
156
+ runtime,
157
+ `${name}/results`,
158
+ "effectRunCompletionResults",
159
+ (fact) => fact.kind === "result" ? fact.result : void 0
160
+ ),
161
+ status: projectRuntimeFact(
162
+ graph,
163
+ runtime,
164
+ `${name}/status`,
165
+ "effectRunCompletionStatus",
166
+ (fact) => fact.kind === "status" ? fact.status : void 0
167
+ ),
168
+ issues: projectRuntimeFact(
169
+ graph,
170
+ runtime,
171
+ `${name}/issues`,
172
+ "effectRunCompletionIssues",
173
+ (fact) => fact.kind === "issue" ? fact.issue : void 0
174
+ ),
175
+ audit: projectRuntimeFact(
176
+ graph,
177
+ runtime,
178
+ `${name}/audit`,
179
+ "effectRunCompletionAudit",
180
+ (fact) => fact.kind === "audit" ? fact.audit : void 0
181
+ )
182
+ };
183
+ }
184
+ function acceptEffectRunResultCandidate(ctx, state, candidate) {
185
+ if (!state.runs.has(candidate.effectRunId)) {
186
+ emitEffectRunIssue(
187
+ ctx,
188
+ state,
189
+ "unknown-effect-run-result-candidate",
190
+ `EffectRunResult candidate '${candidate.resultId}' references unknown EffectRun '${candidate.effectRunId}'`,
191
+ candidate.effectRunId,
192
+ candidate.sourceRefs
193
+ );
194
+ return;
195
+ }
196
+ const existing = state.resultsByEffectRun.get(candidate.effectRunId);
197
+ if (existing !== void 0) {
198
+ state.issueSeq += 1;
199
+ const duplicate = sameTerminalResult(existing, candidate);
200
+ const code = duplicate ? "duplicate-effect-run-result" : "conflicting-effect-run-result";
201
+ const issue = dataIssue(
202
+ code,
203
+ `EffectRun '${candidate.effectRunId}' already has a terminal result`,
204
+ {
205
+ subjectId: candidate.effectRunId,
206
+ refs: candidate.sourceRefs
207
+ }
208
+ );
209
+ ctx.down([
210
+ ["DATA", { kind: "issue", issue }],
211
+ [
212
+ "DATA",
213
+ {
214
+ kind: "audit",
215
+ audit: {
216
+ id: `${candidate.effectRunId}:${code}:${state.issueSeq}`,
217
+ kind: duplicate ? "effect-run-result-duplicate" : "effect-run-result-conflict",
218
+ subjectId: candidate.effectRunId,
219
+ issueCode: issue.code,
220
+ sourceRefs: candidate.sourceRefs
221
+ }
222
+ }
223
+ ]
224
+ ]);
225
+ return;
226
+ }
227
+ state.resultsByEffectRun.set(candidate.effectRunId, candidate);
228
+ ctx.down([
229
+ ["DATA", { kind: "result", result: candidate }],
230
+ [
231
+ "DATA",
232
+ {
233
+ kind: "status",
234
+ status: {
235
+ effectRunId: candidate.effectRunId,
236
+ state: candidate.status,
237
+ requiredPending: [],
238
+ requiredTerminal: requiredTerminalRequests(candidate.effectRunId, state),
239
+ sourceRefs: candidate.sourceRefs
240
+ }
241
+ }
242
+ ],
243
+ [
244
+ "DATA",
245
+ {
246
+ kind: "audit",
247
+ audit: {
248
+ id: `${candidate.effectRunId}:terminal-result`,
249
+ kind: "effect-run-terminal-result",
250
+ subjectId: candidate.effectRunId,
251
+ sourceRefs: candidate.sourceRefs,
252
+ metadata: { status: candidate.status }
253
+ }
254
+ }
255
+ ]
256
+ ]);
257
+ }
258
+ function emitEffectRunStatus(ctx, effectRunId, state, requiredPending, requiredTerminal) {
259
+ ctx.down([
260
+ [
261
+ "DATA",
262
+ {
263
+ kind: "status",
264
+ status: { effectRunId, state, requiredPending, requiredTerminal }
265
+ }
266
+ ]
267
+ ]);
268
+ }
269
+ function requiredPendingRequests(effectRunId, state) {
270
+ const pending = [];
271
+ for (const request of state.requests.values()) {
272
+ if (request.effectRunId !== effectRunId || !request.required) continue;
273
+ const statusFact = matchingStatusForRequest(state, request);
274
+ const status = statusFact?.status;
275
+ if (status === void 0 || !isTerminalRequestStatus(status)) pending.push(request.requestId);
276
+ }
277
+ return pending;
278
+ }
279
+ function requiredTerminalRequests(effectRunId, state) {
280
+ const terminal = [];
281
+ for (const request of state.requests.values()) {
282
+ if (request.effectRunId !== effectRunId || !request.required) continue;
283
+ const statusFact = matchingStatusForRequest(state, request);
284
+ const status = statusFact?.status;
285
+ if (status !== void 0 && isTerminalRequestStatus(status)) terminal.push(request.requestId);
286
+ }
287
+ return terminal;
288
+ }
289
+ function isTerminalRequestStatus(status) {
290
+ return status === "completed" || status === "failed" || status === "blocked" || status === "canceled" || status === "timeout" || status === "waived" || status === "retry-exhausted";
291
+ }
292
+ function decisionSourceRequestTerminal(decision, state) {
293
+ const request = state.requests.get(decision.source.requestId);
294
+ if (request === void 0) return false;
295
+ if (request.effectRunId !== decision.effectRunId || request.operationId !== decision.source.operationId) {
296
+ return false;
297
+ }
298
+ const status = matchingStatusForRequest(state, request)?.status;
299
+ return status !== void 0 && isTerminalRequestStatus(status);
300
+ }
301
+ function acceptRequestStatus(ctx, state, status) {
302
+ const request = state.requests.get(status.requestId);
303
+ if (request !== void 0 && !statusMatchesRequest(status, request)) {
304
+ emitEffectRunIssue(
305
+ ctx,
306
+ state,
307
+ "stale-request-status",
308
+ `AgentRequest status for '${status.requestId}' did not match its issued effectRun/operation identity`,
309
+ request.effectRunId,
310
+ [ref("agent-request", status.requestId)]
311
+ );
312
+ return;
313
+ }
314
+ state.statusByRequest.set(status.requestId, status);
315
+ }
316
+ function matchingStatusForRequest(state, request) {
317
+ const status = state.statusByRequest.get(request.requestId);
318
+ if (status === void 0) return void 0;
319
+ return statusMatchesRequest(status, request) ? status : void 0;
320
+ }
321
+ function statusMatchesRequest(status, request) {
322
+ return status.effectRunId === request.effectRunId && (status.operationId === void 0 || status.operationId === request.operationId);
323
+ }
324
+ function emitEffectRunIssue(ctx, state, code, message, subjectId, sourceRefs) {
325
+ state.issueSeq += 1;
326
+ const issue = dataIssue(code, message, { subjectId, refs: sourceRefs });
327
+ ctx.down([
328
+ ["DATA", { kind: "issue", issue }],
329
+ [
330
+ "DATA",
331
+ {
332
+ kind: "audit",
333
+ audit: {
334
+ id: `${subjectId ?? "effect-run"}:${code}:${state.issueSeq}`,
335
+ kind: "effect-run-issue",
336
+ subjectId,
337
+ issueCode: code,
338
+ message,
339
+ sourceRefs
340
+ }
341
+ }
342
+ ]
343
+ ]);
344
+ }
345
+ function sameTerminalResult(a, b) {
346
+ return a.status === b.status && a.resultId === b.resultId && JSON.stringify(a) === JSON.stringify(b);
347
+ }
348
+ function emptyEffectRunCompletionState() {
349
+ return {
350
+ runs: /* @__PURE__ */ new Map(),
351
+ requests: /* @__PURE__ */ new Map(),
352
+ statusByRequest: /* @__PURE__ */ new Map(),
353
+ decisions: /* @__PURE__ */ new Map(),
354
+ resultsByEffectRun: /* @__PURE__ */ new Map(),
355
+ issueSeq: 0
356
+ };
357
+ }
358
+
359
+ // src/orchestration/agent-runtime-decision-interpreter.ts
360
+ function structuredAgentDecisionInterpreter(graph, outcomes, opts = {}) {
361
+ const name = opts.name ?? "structuredAgentDecisionInterpreter";
362
+ const requestFacts = opts.requestFacts ?? [];
363
+ const runtime = graph.node(
364
+ [outcomes, ...requestFacts],
365
+ (ctx) => {
366
+ const state = ctx.state.get() ?? {
367
+ requests: /* @__PURE__ */ new Map(),
368
+ issueSeq: 0
369
+ };
370
+ forEachDepBatch(ctx, 1, requestFacts.length, (raw) => {
371
+ const fact = raw;
372
+ if (fact.kind === "issued") state.requests.set(fact.requestId, fact);
373
+ });
374
+ for (const raw of depBatch(ctx, 0) ?? []) {
375
+ const outcome = raw;
376
+ if (outcome.kind !== "result") {
377
+ state.issueSeq += 1;
378
+ emitInterpreterIssue(
379
+ ctx,
380
+ state.issueSeq,
381
+ outcome,
382
+ "non-result-outcome",
383
+ "Only result outcomes can carry AgentDecision envelopes"
384
+ );
385
+ continue;
386
+ }
387
+ const value = outcome.result.value;
388
+ if (!isRecord(value)) {
389
+ state.issueSeq += 1;
390
+ emitInterpreterIssue(
391
+ ctx,
392
+ state.issueSeq,
393
+ outcome,
394
+ "malformed-agent-decision",
395
+ "ExecutorOutcome result must carry a structured agent-decision envelope"
396
+ );
397
+ continue;
398
+ }
399
+ const envelope = value;
400
+ if (envelope.kind !== "agent-decision" || !isRecord(envelope.decision)) {
401
+ state.issueSeq += 1;
402
+ emitInterpreterIssue(
403
+ ctx,
404
+ state.issueSeq,
405
+ outcome,
406
+ "malformed-agent-decision",
407
+ "Structured agent-decision envelope is missing kind or decision"
408
+ );
409
+ continue;
410
+ }
411
+ if (typeof envelope.schemaRef !== "string" || envelope.schemaRef.length === 0) {
412
+ state.issueSeq += 1;
413
+ emitInterpreterIssue(
414
+ ctx,
415
+ state.issueSeq,
416
+ outcome,
417
+ "missing-agent-decision-schema",
418
+ "Structured agent-decision envelope must carry schemaRef evidence"
419
+ );
420
+ continue;
421
+ }
422
+ if (opts.schemaRef !== void 0 && envelope.schemaRef !== opts.schemaRef) {
423
+ state.issueSeq += 1;
424
+ emitInterpreterIssue(
425
+ ctx,
426
+ state.issueSeq,
427
+ outcome,
428
+ "agent-decision-schema-mismatch",
429
+ "Structured agent-decision envelope schemaRef did not match"
430
+ );
431
+ continue;
432
+ }
433
+ const decision = validateAgentDecision(envelope.decision, outcome);
434
+ if (typeof decision === "string") {
435
+ state.issueSeq += 1;
436
+ emitInterpreterIssue(ctx, state.issueSeq, outcome, "malformed-agent-decision", decision);
437
+ continue;
438
+ }
439
+ const request = state.requests.get(decision.source.requestId);
440
+ if (request === void 0) {
441
+ state.issueSeq += 1;
442
+ emitInterpreterIssue(
443
+ ctx,
444
+ state.issueSeq,
445
+ outcome,
446
+ "missing-agent-decision-request",
447
+ "AgentDecision source request must be present in the request ledger"
448
+ );
449
+ continue;
450
+ }
451
+ if (request.effectRunId !== decision.effectRunId || request.operationId !== decision.source.operationId) {
452
+ state.issueSeq += 1;
453
+ emitInterpreterIssue(
454
+ ctx,
455
+ state.issueSeq,
456
+ outcome,
457
+ "stale-agent-decision-source",
458
+ "AgentDecision source request/effectRun/operation identity did not match the request ledger"
459
+ );
460
+ continue;
461
+ }
462
+ ctx.down([
463
+ ["DATA", { kind: "decision", decision }],
464
+ [
465
+ "DATA",
466
+ {
467
+ kind: "audit",
468
+ audit: {
469
+ id: `${outcome.outcomeId}:agent-decision-interpreted`,
470
+ kind: "agent-decision-interpreted",
471
+ subjectId: decision.effectRunId,
472
+ sourceRefs: [ref("executor-outcome", outcome.outcomeId)]
473
+ }
474
+ }
475
+ ]
476
+ ]);
477
+ }
478
+ ctx.state.set(state);
479
+ },
480
+ { name: `${name}/runtime`, factory: "structuredAgentDecisionInterpreter" }
481
+ );
482
+ return {
483
+ decisions: projectRuntimeFact(
484
+ graph,
485
+ runtime,
486
+ `${name}/decisions`,
487
+ "structuredAgentDecisions",
488
+ (fact) => fact.kind === "decision" ? fact.decision : void 0
489
+ ),
490
+ issues: projectRuntimeFact(
491
+ graph,
492
+ runtime,
493
+ `${name}/issues`,
494
+ "structuredAgentDecisionIssues",
495
+ (fact) => fact.kind === "issue" ? fact.issue : void 0
496
+ ),
497
+ audit: projectRuntimeFact(
498
+ graph,
499
+ runtime,
500
+ `${name}/audit`,
501
+ "structuredAgentDecisionAudit",
502
+ (fact) => fact.kind === "audit" ? fact.audit : void 0
503
+ )
504
+ };
505
+ }
506
+ function emitInterpreterIssue(ctx, seq, outcome, code, message) {
507
+ const issue = dataIssue(code, message, {
508
+ subjectId: outcome.requestId,
509
+ refs: [ref("executor-outcome", outcome.outcomeId)]
510
+ });
511
+ ctx.down([
512
+ ["DATA", { kind: "issue", issue }],
513
+ [
514
+ "DATA",
515
+ {
516
+ kind: "audit",
517
+ audit: {
518
+ id: `${outcome.outcomeId}:agent-decision-issue:${seq}`,
519
+ kind: "agent-decision-issue",
520
+ subjectId: outcome.requestId,
521
+ issueCode: code,
522
+ message,
523
+ sourceRefs: [ref("executor-outcome", outcome.outcomeId)]
524
+ }
525
+ }
526
+ ]
527
+ ]);
528
+ }
529
+ function validateAgentDecision(raw, outcome) {
530
+ if (!isRecord(raw)) return "AgentDecision must be an object";
531
+ const kind = raw.kind;
532
+ if (kind !== "continue" && kind !== "final" && kind !== "blocked") {
533
+ return "AgentDecision kind must be continue, final, or blocked";
534
+ }
535
+ if (typeof raw.decisionId !== "string" || raw.decisionId.length === 0)
536
+ return "AgentDecision decisionId must be a non-empty string";
537
+ if (raw.effectRunId === void 0 || typeof raw.effectRunId !== "string" || raw.effectRunId.length === 0)
538
+ return "AgentDecision effectRunId must be a non-empty string";
539
+ if (typeof raw.agentRunId !== "string" || raw.agentRunId.length === 0)
540
+ return "AgentDecision agentRunId must be a non-empty string";
541
+ const source = raw.source;
542
+ if (!isRecord(source) || source.requestId !== outcome.requestId || source.operationId !== outcome.operationId || source.outcomeId !== outcome.outcomeId) {
543
+ return "AgentDecision source must match the ExecutorOutcome requestId, operationId, and outcomeId";
544
+ }
545
+ if (kind === "continue") {
546
+ if (!Array.isArray(raw.next)) return "AgentDecision.continue next must be an array";
547
+ for (const proposal of raw.next) {
548
+ if (!isAgentRequestProposalLike(proposal, raw.effectRunId)) {
549
+ return "AgentDecision.continue next entries must be AgentRequestProposal-like objects";
550
+ }
551
+ }
552
+ return raw;
553
+ }
554
+ if (kind === "final") {
555
+ if (!isRecord(raw.output) || typeof raw.output.kind !== "string")
556
+ return "AgentDecision.final output must be an envelope with kind";
557
+ return raw;
558
+ }
559
+ if (!Array.isArray(raw.needs)) return "AgentDecision.blocked needs must be an array";
560
+ for (const need of raw.needs) {
561
+ if (!isAgentNeedLike(need))
562
+ return "AgentDecision.blocked needs entries must be AgentNeed-like objects";
563
+ }
564
+ return raw;
565
+ }
566
+ function isAgentRequestProposalLike(value, effectRunId) {
567
+ if (!isRecord(value)) return false;
568
+ if (value.kind !== "proposal") return false;
569
+ if (typeof value.proposalId !== "string" || value.proposalId.length === 0) return false;
570
+ if (value.effectRunId !== effectRunId) return false;
571
+ return value.requestKind === "context" || value.requestKind === "prompt" || value.requestKind === "executor";
572
+ }
573
+ function isAgentNeedLike(value) {
574
+ return isRecord(value) && typeof value.kind === "string" && value.kind.length > 0;
575
+ }
576
+ function candidateFromDecision(decision, state, completedAtMs) {
577
+ const run = state.runs.get(decision.effectRunId);
578
+ if (run === void 0) return void 0;
579
+ if (!decisionSourceRequestTerminal(decision, state)) return void 0;
580
+ const requiredPending = requiredPendingRequests(decision.effectRunId, state);
581
+ if (decision.kind === "final") {
582
+ if (requiredPending.length > 0) {
583
+ return void 0;
584
+ }
585
+ return {
586
+ kind: "effect-run-result",
587
+ resultId: `${decision.effectRunId}:result`,
588
+ status: "completed",
589
+ effectRunId: decision.effectRunId,
590
+ subjectRefs: run.subjectRefs,
591
+ operationId: decision.source.operationId,
592
+ sourceRefs: [
593
+ ref("agent-decision", decision.decisionId),
594
+ ref("executor-outcome", decision.source.outcomeId)
595
+ ],
596
+ completedAtMs,
597
+ output: decision.output
598
+ };
599
+ }
600
+ if (decision.kind === "blocked" && requiredPending.length === 0) {
601
+ return {
602
+ kind: "effect-run-result",
603
+ resultId: `${decision.effectRunId}:result`,
604
+ status: "blocked",
605
+ effectRunId: decision.effectRunId,
606
+ subjectRefs: run.subjectRefs,
607
+ operationId: decision.source.operationId,
608
+ sourceRefs: [
609
+ ref("agent-decision", decision.decisionId),
610
+ ref("executor-outcome", decision.source.outcomeId)
611
+ ],
612
+ completedAtMs,
613
+ needs: decision.needs
614
+ };
615
+ }
616
+ return void 0;
617
+ }
618
+
619
+ // src/orchestration/agent-runtime-fakes.ts
620
+ function fakeExecutorResult(opts) {
621
+ return { kind: "result", ...opts };
622
+ }
623
+ function fakeExecutorFailure(opts) {
624
+ return { kind: "failure", ...opts };
625
+ }
626
+ function fakeExecutorBlocked(opts) {
627
+ return { kind: "blocked", ...opts };
628
+ }
629
+ function fakeExecutorTimeout(opts) {
630
+ return { kind: "timeout", ...opts };
631
+ }
632
+ function fakeExecutorCanceled(opts) {
633
+ return { kind: "canceled", ...opts };
634
+ }
635
+
636
+ // src/orchestration/agent-runtime-request-ledger.ts
637
+ function agentRequestProposalFromDecision(decision, proposal) {
638
+ return {
639
+ kind: "proposal",
640
+ ...proposal,
641
+ effectRunId: decision.effectRunId,
642
+ agentRunId: decision.agentRunId,
643
+ sourceDecisionId: decision.decisionId,
644
+ evidenceRefs: proposal.evidenceRefs ?? decision.evidenceRefs
645
+ };
646
+ }
647
+ function admitAgentRequestProposal(proposal, opts) {
648
+ const sourceRefs = opts.sourceRefs === void 0 ? void 0 : sanitizeAdapterInputSourceRefs(opts.sourceRefs);
649
+ const metadata = sanitizeProviderGraphVisibleRecord(opts.metadata);
650
+ return {
651
+ kind: "admitted",
652
+ proposalId: proposal.proposalId,
653
+ requestId: opts.requestId,
654
+ operationId: opts.operationId,
655
+ effectRunId: proposal.effectRunId,
656
+ agentRunId: proposal.agentRunId,
657
+ admittedAtMs: opts.admittedAtMs,
658
+ ...opts.reason === void 0 ? {} : { reason: boundPublicText(opts.reason, maxPublicReasonChars()).text },
659
+ ...sourceRefs === void 0 || sourceRefs.length === 0 ? {} : { sourceRefs },
660
+ ...metadata === void 0 ? {} : { metadata }
661
+ };
662
+ }
663
+ function issueAgentRequest(proposal, admission, opts = {}) {
664
+ const input = sanitizeAgentRequestInput(proposal.input);
665
+ const payload = sanitizeAgentRequestMaterial(proposal.payload);
666
+ const sourceRefs = sanitizeAdapterInputSourceRefs(opts.sourceRefs ?? admission.sourceRefs ?? []);
667
+ const metadata = sanitizeProviderGraphVisibleRecord(proposal.metadata);
668
+ return {
669
+ kind: "issued",
670
+ requestId: admission.requestId,
671
+ operationId: admission.operationId,
672
+ effectRunId: admission.effectRunId,
673
+ agentRunId: admission.agentRunId,
674
+ proposalId: proposal.proposalId,
675
+ parentRequestId: proposal.parentRequestId,
676
+ requestKind: proposal.requestKind,
677
+ required: proposal.required ?? true,
678
+ ...input === void 0 ? {} : { input },
679
+ ...payload === void 0 ? {} : { payload },
680
+ issuedAtMs: opts.issuedAtMs,
681
+ ...sourceRefs.length === 0 ? {} : { sourceRefs },
682
+ ...metadata === void 0 ? {} : { metadata }
683
+ };
684
+ }
685
+ function sanitizeAgentRequestInput(input) {
686
+ if (input === void 0) return void 0;
687
+ const {
688
+ value: rawValue,
689
+ subjectRefs: rawSubjectRefs,
690
+ metadata: rawMetadata,
691
+ ...inputFields
692
+ } = input;
693
+ const value = sanitizeAgentRequestMaterial(rawValue);
694
+ const subjectRefs = rawSubjectRefs === void 0 ? void 0 : sanitizeAdapterInputSourceRefs(rawSubjectRefs);
695
+ const metadata = sanitizeProviderGraphVisibleRecord(rawMetadata);
696
+ return Object.freeze({
697
+ ...inputFields,
698
+ ...value === void 0 ? {} : { value },
699
+ ...subjectRefs === void 0 || subjectRefs.length === 0 ? {} : { subjectRefs },
700
+ ...metadata === void 0 ? {} : { metadata }
701
+ });
702
+ }
703
+ function sanitizeAgentRequestMaterial(value) {
704
+ if (value === void 0) return void 0;
705
+ if (publicMaterialForbiddenKeys(value, "provider").length > 0) return void 0;
706
+ return cloneGraphVisibleMaterial(value);
707
+ }
708
+ function sanitizeAgentRequestIssued(request) {
709
+ const input = sanitizeAgentRequestInput(request.input);
710
+ const payload = sanitizeAgentRequestMaterial(request.payload);
711
+ const sourceRefs = request.sourceRefs === void 0 ? void 0 : sanitizeAdapterInputSourceRefs(request.sourceRefs);
712
+ const metadata = sanitizeProviderGraphVisibleRecord(request.metadata);
713
+ return Object.freeze({
714
+ kind: "issued",
715
+ requestId: request.requestId,
716
+ operationId: request.operationId,
717
+ effectRunId: request.effectRunId,
718
+ ...request.agentRunId === void 0 ? {} : { agentRunId: request.agentRunId },
719
+ ...request.proposalId === void 0 ? {} : { proposalId: request.proposalId },
720
+ ...request.parentRequestId === void 0 ? {} : { parentRequestId: request.parentRequestId },
721
+ requestKind: request.requestKind,
722
+ required: request.required,
723
+ ...input === void 0 ? {} : { input },
724
+ ...payload === void 0 ? {} : { payload },
725
+ ...request.issuedAtMs === void 0 ? {} : { issuedAtMs: request.issuedAtMs },
726
+ ...sourceRefs === void 0 || sourceRefs.length === 0 ? {} : { sourceRefs },
727
+ ...metadata === void 0 ? {} : { metadata }
728
+ });
729
+ }
730
+ function agentRequestLedgerViews(graph, facts, opts = {}) {
731
+ const name = opts.name ?? "agentRequests";
732
+ const views = graph.node(
733
+ [facts],
734
+ (ctx) => {
735
+ const prev = ctx.state.get() ?? emptyAgentRequestViewsState();
736
+ const next = cloneAgentRequestViewsState(prev);
737
+ for (const raw of depBatch(ctx, 0) ?? []) {
738
+ const fact = raw;
739
+ reduceAgentRequestViews(next, fact);
740
+ }
741
+ ctx.state.set(next);
742
+ ctx.down([["DATA", freezeAgentRequestViews(next)]]);
743
+ },
744
+ { name: `${name}/views`, factory: "agentRequestLedgerViews" }
745
+ );
746
+ const issues = graph.node(
747
+ [facts],
748
+ (ctx) => {
749
+ for (const raw of depBatch(ctx, 0) ?? []) {
750
+ const fact = raw;
751
+ if (fact.kind === "rejected") ctx.down([["DATA", sanitizeAdapterInputIssue(fact.issue)]]);
752
+ if (fact.kind === "status") {
753
+ for (const issue of fact.issues ?? []) {
754
+ ctx.down([["DATA", sanitizeAdapterInputIssue(issue)]]);
755
+ }
756
+ }
757
+ }
758
+ },
759
+ { name: `${name}/issues`, factory: "agentRequestLedgerIssues" }
760
+ );
761
+ const audit = graph.node(
762
+ [facts],
763
+ (ctx) => {
764
+ let seq = ctx.state.get() ?? 0;
765
+ for (const raw of depBatch(ctx, 0) ?? []) {
766
+ seq += 1;
767
+ const fact = raw;
768
+ ctx.down([
769
+ [
770
+ "DATA",
771
+ {
772
+ id: `${name}:ledger:${seq}`,
773
+ kind: `agent-request-${fact.kind}`,
774
+ subjectId: "requestId" in fact ? fact.requestId : fact.proposalId
775
+ }
776
+ ]
777
+ ]);
778
+ }
779
+ ctx.state.set(seq);
780
+ },
781
+ { name: `${name}/audit`, factory: "agentRequestLedgerAudit" }
782
+ );
783
+ return { views, issues, audit };
784
+ }
785
+ function emptyAgentRequestViewsState() {
786
+ return {
787
+ requestsById: /* @__PURE__ */ new Map(),
788
+ requestsByEffectRun: /* @__PURE__ */ new Map(),
789
+ statusByRequest: /* @__PURE__ */ new Map(),
790
+ issues: [],
791
+ audit: [],
792
+ auditSeq: 0
793
+ };
794
+ }
795
+ function cloneAgentRequestViewsState(state) {
796
+ return {
797
+ requestsById: new Map(state.requestsById),
798
+ requestsByEffectRun: new Map(Array.from(state.requestsByEffectRun, ([k, v]) => [k, [...v]])),
799
+ statusByRequest: new Map(state.statusByRequest),
800
+ issues: [...state.issues],
801
+ audit: [...state.audit],
802
+ auditSeq: state.auditSeq
803
+ };
804
+ }
805
+ function reduceAgentRequestViews(state, fact) {
806
+ state.auditSeq += 1;
807
+ if (fact.kind === "issued") {
808
+ const request = sanitizeAgentRequestIssued(fact);
809
+ state.requestsById.set(request.requestId, request);
810
+ const requestIds = state.requestsByEffectRun.get(request.effectRunId) ?? [];
811
+ if (!requestIds.includes(request.requestId)) requestIds.push(request.requestId);
812
+ state.requestsByEffectRun.set(request.effectRunId, requestIds);
813
+ state.statusByRequest.set(request.requestId, {
814
+ kind: "status",
815
+ requestId: request.requestId,
816
+ operationId: request.operationId,
817
+ effectRunId: request.effectRunId,
818
+ status: "issued",
819
+ sourceRefs: [ref("agent-request", request.requestId)]
820
+ });
821
+ } else if (fact.kind === "status") {
822
+ const status = sanitizeAgentRequestStatusChanged(fact);
823
+ state.statusByRequest.set(status.requestId, status);
824
+ if (status.issues !== void 0) state.issues.push(...status.issues);
825
+ } else if (fact.kind === "rejected") {
826
+ state.issues.push(sanitizeAdapterInputIssue(fact.issue));
827
+ }
828
+ state.audit.push({
829
+ id: `agent-request-ledger:${state.auditSeq}`,
830
+ kind: `agent-request-${fact.kind}`,
831
+ subjectId: "requestId" in fact ? fact.requestId : fact.proposalId
832
+ });
833
+ }
834
+ function sanitizeAgentRequestStatusChanged(status) {
835
+ const sourceRefs = status.sourceRefs === void 0 ? void 0 : sanitizeAdapterInputSourceRefs(status.sourceRefs);
836
+ const issues = status.issues === void 0 ? void 0 : Object.freeze(status.issues.map((issue) => sanitizeAdapterInputIssue(issue)));
837
+ const metadata = sanitizeProviderGraphVisibleRecord(status.metadata);
838
+ return Object.freeze({
839
+ kind: "status",
840
+ requestId: status.requestId,
841
+ ...status.operationId === void 0 ? {} : { operationId: status.operationId },
842
+ effectRunId: status.effectRunId,
843
+ status: status.status,
844
+ ...sourceRefs === void 0 || sourceRefs.length === 0 ? {} : { sourceRefs },
845
+ ...issues === void 0 || issues.length === 0 ? {} : { issues },
846
+ ...metadata === void 0 ? {} : { metadata }
847
+ });
848
+ }
849
+ function freezeAgentRequestViews(state) {
850
+ const pending = Array.from(state.requestsById.values()).filter((request) => {
851
+ const status = state.statusByRequest.get(request.requestId)?.status;
852
+ return status === void 0 || !isTerminalRequestStatus(status);
853
+ });
854
+ const awaitingProvider = pending.filter(
855
+ (request) => state.statusByRequest.get(request.requestId)?.status === "awaiting-provider"
856
+ );
857
+ return {
858
+ requestsById: new Map(state.requestsById),
859
+ requestsByEffectRun: new Map(
860
+ Array.from(state.requestsByEffectRun, ([key, value]) => [key, Object.freeze([...value])])
861
+ ),
862
+ statusByRequest: new Map(state.statusByRequest),
863
+ pending: Object.freeze(pending),
864
+ awaitingProvider: Object.freeze(awaitingProvider),
865
+ issues: Object.freeze([...state.issues]),
866
+ audit: Object.freeze([...state.audit])
867
+ };
868
+ }
869
+
870
+ // src/orchestration/agent-runtime-request-satisfaction.ts
871
+ function requestSatisfactionProjector(graph, opts) {
872
+ const name = opts.name ?? "requestSatisfaction";
873
+ const profileDeps = opts.executorProfiles ?? [];
874
+ const routeDeps = opts.executorRoutes ?? [];
875
+ const outcomeDeps = opts.executorOutcomes ?? [];
876
+ const contextDeps = opts.contextContributions ?? [];
877
+ const promptDeps = opts.promptBundles ?? [];
878
+ const deps = [
879
+ opts.requestFacts,
880
+ ...profileDeps,
881
+ ...routeDeps,
882
+ ...outcomeDeps,
883
+ ...contextDeps,
884
+ ...promptDeps
885
+ ];
886
+ const profileStart = 1;
887
+ const routeStart = profileStart + profileDeps.length;
888
+ const outcomeStart = routeStart + routeDeps.length;
889
+ const contextStart = outcomeStart + outcomeDeps.length;
890
+ const promptStart = contextStart + contextDeps.length;
891
+ const runtime = graph.node(
892
+ deps,
893
+ (ctx) => {
894
+ const state = ctx.state.get() ?? {
895
+ requests: /* @__PURE__ */ new Map(),
896
+ profiles: /* @__PURE__ */ new Map(),
897
+ routes: /* @__PURE__ */ new Map(),
898
+ outcomes: /* @__PURE__ */ new Map(),
899
+ contexts: /* @__PURE__ */ new Map(),
900
+ prompts: /* @__PURE__ */ new Map(),
901
+ compatibleRoutesByRouteId: /* @__PURE__ */ new Map(),
902
+ terminalRequests: /* @__PURE__ */ new Set(),
903
+ acceptedTerminalFactIds: /* @__PURE__ */ new Set(),
904
+ issueKeys: /* @__PURE__ */ new Set(),
905
+ statusKeys: /* @__PURE__ */ new Set(),
906
+ issueSeq: 0,
907
+ auditSeq: 0
908
+ };
909
+ for (const fact of depBatch(ctx, 0) ?? []) {
910
+ if (fact.kind === "issued") {
911
+ const request = fact;
912
+ state.requests.set(request.requestId, request);
913
+ emitStatus(ctx, state, request, initialRequestStatus(request), [
914
+ ref("agent-request", request.requestId)
915
+ ]);
916
+ }
917
+ }
918
+ forEachDepBatch(ctx, profileStart, profileDeps.length, (raw) => {
919
+ const profile = raw;
920
+ state.profiles.set(profile.profileId, profile);
921
+ });
922
+ forEachDepBatch(ctx, routeStart, routeDeps.length, (raw) => {
923
+ const route = raw;
924
+ state.routes.set(route.routeId, route);
925
+ });
926
+ forEachDepBatch(ctx, outcomeStart, outcomeDeps.length, (raw) => {
927
+ const outcome = raw;
928
+ state.outcomes.set(outcome.outcomeId, outcome);
929
+ });
930
+ forEachDepBatch(ctx, contextStart, contextDeps.length, (raw) => {
931
+ const contribution = raw;
932
+ state.contexts.set(contribution.contributionId, contribution);
933
+ });
934
+ forEachDepBatch(ctx, promptStart, promptDeps.length, (raw) => {
935
+ const prompt = raw;
936
+ state.prompts.set(prompt.promptId, prompt);
937
+ });
938
+ evaluateRequestSatisfaction(ctx, state);
939
+ ctx.state.set(state);
940
+ },
941
+ { name: `${name}/runtime`, factory: "requestSatisfactionProjector" }
942
+ );
943
+ const status = graph.node(
944
+ [runtime],
945
+ (ctx) => {
946
+ for (const fact of depBatch(ctx, 0) ?? []) {
947
+ const typed = fact;
948
+ if (typed.kind === "status") ctx.down([["DATA", typed.status]]);
949
+ }
950
+ },
951
+ { name: `${name}/status`, factory: "requestSatisfactionStatus" }
952
+ );
953
+ const issues = graph.node(
954
+ [runtime],
955
+ (ctx) => {
956
+ for (const fact of depBatch(ctx, 0) ?? []) {
957
+ const typed = fact;
958
+ if (typed.kind === "issue") ctx.down([["DATA", typed.issue]]);
959
+ }
960
+ },
961
+ { name: `${name}/issues`, factory: "requestSatisfactionIssues" }
962
+ );
963
+ const audit = graph.node(
964
+ [runtime],
965
+ (ctx) => {
966
+ for (const fact of depBatch(ctx, 0) ?? []) {
967
+ const typed = fact;
968
+ if (typed.kind === "audit") ctx.down([["DATA", typed.audit]]);
969
+ }
970
+ },
971
+ { name: `${name}/audit`, factory: "requestSatisfactionAudit" }
972
+ );
973
+ return { status, issues, audit };
974
+ }
975
+ function initialRequestStatus(request) {
976
+ if (request.requestKind === "context") return "awaiting-context";
977
+ if (request.requestKind === "prompt") return "awaiting-prompt";
978
+ return "awaiting-route";
979
+ }
980
+ function evaluateRequestSatisfaction(ctx, state) {
981
+ for (const route of state.routes.values()) handleRoute(ctx, state, route);
982
+ for (const contribution of state.contexts.values())
983
+ handleContextContribution(ctx, state, contribution);
984
+ for (const prompt of state.prompts.values()) handlePromptBundle(ctx, state, prompt);
985
+ for (const outcome of state.outcomes.values()) handleExecutorOutcome(ctx, state, outcome);
986
+ }
987
+ function handleRoute(ctx, state, route) {
988
+ const request = state.requests.get(route.requestId);
989
+ if (request === void 0) {
990
+ return;
991
+ }
992
+ if (state.terminalRequests.has(request.requestId)) {
993
+ if (state.compatibleRoutesByRouteId.get(route.routeId)?.requestId !== request.requestId) {
994
+ emitIssueOnce(
995
+ ctx,
996
+ state,
997
+ `late-route:${route.routeId}`,
998
+ "late-route-after-terminal",
999
+ `ExecutorRoute '${route.routeId}' arrived after request '${request.requestId}' was already terminal`,
1000
+ request.requestId,
1001
+ [ref("executor-route", route.routeId), ref("agent-request", request.requestId)]
1002
+ );
1003
+ }
1004
+ return;
1005
+ }
1006
+ if (request.operationId !== route.operationId) {
1007
+ emitIssueOnce(
1008
+ ctx,
1009
+ state,
1010
+ `stale-route:${route.routeId}`,
1011
+ "stale-route-operation",
1012
+ `ExecutorRoute '${route.routeId}' operationId does not match request '${request.requestId}'`,
1013
+ request.requestId,
1014
+ [ref("executor-route", route.routeId), ref("agent-request", request.requestId)]
1015
+ );
1016
+ return;
1017
+ }
1018
+ const profile = state.profiles.get(route.profileId);
1019
+ if (profile === void 0) {
1020
+ return;
1021
+ }
1022
+ const compatibilityIssue = routeCompatibilityIssue(request, route, profile);
1023
+ if (compatibilityIssue !== void 0) {
1024
+ emitIssueOnce(
1025
+ ctx,
1026
+ state,
1027
+ `route-incompatible:${route.routeId}:${compatibilityIssue}`,
1028
+ compatibilityIssue,
1029
+ `ExecutorRoute '${route.routeId}' is incompatible with request '${request.requestId}'`,
1030
+ request.requestId,
1031
+ [
1032
+ ref("executor-route", route.routeId),
1033
+ ref("executor-profile", profile.profileId),
1034
+ ref("agent-request", request.requestId)
1035
+ ]
1036
+ );
1037
+ return;
1038
+ }
1039
+ state.compatibleRoutesByRouteId.set(route.routeId, route);
1040
+ emitStatusOnce(
1041
+ ctx,
1042
+ state,
1043
+ `route:${route.routeId}:awaiting-provider`,
1044
+ request,
1045
+ "awaiting-provider",
1046
+ [
1047
+ ref("executor-route", route.routeId),
1048
+ ref("executor-profile", profile.profileId),
1049
+ ref("agent-request", request.requestId)
1050
+ ]
1051
+ );
1052
+ }
1053
+ function handleExecutorOutcome(ctx, state, outcome) {
1054
+ const request = state.requests.get(outcome.requestId);
1055
+ if (request === void 0) {
1056
+ return;
1057
+ }
1058
+ if (request.operationId !== outcome.operationId) {
1059
+ emitIssueOnce(
1060
+ ctx,
1061
+ state,
1062
+ `stale-outcome:${outcome.outcomeId}`,
1063
+ "stale-outcome-operation",
1064
+ `ExecutorOutcome '${outcome.outcomeId}' operationId does not match request '${request.requestId}'`,
1065
+ request.requestId,
1066
+ [ref("executor-outcome", outcome.outcomeId), ref("agent-request", request.requestId)]
1067
+ );
1068
+ return;
1069
+ }
1070
+ const route = state.compatibleRoutesByRouteId.get(outcome.routeId);
1071
+ if (route === void 0 || route.requestId !== request.requestId) {
1072
+ emitIssueOnce(
1073
+ ctx,
1074
+ state,
1075
+ `missing-route:${outcome.outcomeId}`,
1076
+ "missing-compatible-route",
1077
+ `ExecutorOutcome '${outcome.outcomeId}' has no compatible route for request '${request.requestId}'`,
1078
+ request.requestId,
1079
+ [ref("executor-outcome", outcome.outcomeId), ref("agent-request", request.requestId)]
1080
+ );
1081
+ return;
1082
+ }
1083
+ const outcomeIssue = outcomeCompatibilityIssue(request, route, outcome);
1084
+ if (outcomeIssue !== void 0) {
1085
+ emitIssueOnce(
1086
+ ctx,
1087
+ state,
1088
+ `outcome-incompatible:${outcome.outcomeId}:${outcomeIssue}`,
1089
+ outcomeIssue,
1090
+ `ExecutorOutcome '${outcome.outcomeId}' is incompatible with route '${route.routeId}' for request '${request.requestId}'`,
1091
+ request.requestId,
1092
+ [
1093
+ ref("executor-outcome", outcome.outcomeId),
1094
+ ref("executor-route", route.routeId),
1095
+ ref("agent-request", request.requestId)
1096
+ ]
1097
+ );
1098
+ return;
1099
+ }
1100
+ if (state.terminalRequests.has(request.requestId)) {
1101
+ if (state.acceptedTerminalFactIds.has(`outcome:${outcome.outcomeId}`)) return;
1102
+ emitIssueOnce(
1103
+ ctx,
1104
+ state,
1105
+ `duplicate-outcome:${outcome.outcomeId}`,
1106
+ "duplicate-terminal-outcome",
1107
+ `ExecutorOutcome '${outcome.outcomeId}' arrived after request '${request.requestId}' was already terminal`,
1108
+ request.requestId,
1109
+ [ref("executor-outcome", outcome.outcomeId), ref("agent-request", request.requestId)]
1110
+ );
1111
+ return;
1112
+ }
1113
+ state.terminalRequests.add(request.requestId);
1114
+ state.acceptedTerminalFactIds.add(`outcome:${outcome.outcomeId}`);
1115
+ const status = outcomeStatus(outcome);
1116
+ emitStatus(ctx, state, request, status, [
1117
+ ref("executor-outcome", outcome.outcomeId),
1118
+ ref("executor-route", route.routeId),
1119
+ ref("agent-request", request.requestId)
1120
+ ]);
1121
+ }
1122
+ function handleContextContribution(ctx, state, contribution) {
1123
+ const request = state.requests.get(contribution.requestId);
1124
+ if (request === void 0) return;
1125
+ if (request.operationId !== contribution.operationId) {
1126
+ emitIssueOnce(
1127
+ ctx,
1128
+ state,
1129
+ `stale-context:${contribution.contributionId}`,
1130
+ "stale-context-operation",
1131
+ `ContextContribution '${contribution.contributionId}' operationId does not match request '${request.requestId}'`,
1132
+ request.requestId,
1133
+ [ref("context-contribution", contribution.contributionId)]
1134
+ );
1135
+ return;
1136
+ }
1137
+ if (request.requestKind !== "context") {
1138
+ emitIssueOnce(
1139
+ ctx,
1140
+ state,
1141
+ `wrong-context-kind:${contribution.contributionId}`,
1142
+ "wrong-kind-context-satisfaction",
1143
+ `ContextContribution '${contribution.contributionId}' cannot satisfy ${request.requestKind} request '${request.requestId}'`,
1144
+ request.requestId,
1145
+ [ref("context-contribution", contribution.contributionId)]
1146
+ );
1147
+ return;
1148
+ }
1149
+ if (state.terminalRequests.has(request.requestId)) {
1150
+ if (state.acceptedTerminalFactIds.has(`context:${contribution.contributionId}`) || state.statusKeys.has(`context:${contribution.contributionId}:awaiting-context`)) {
1151
+ return;
1152
+ }
1153
+ emitIssueOnce(
1154
+ ctx,
1155
+ state,
1156
+ `duplicate-context:${contribution.contributionId}`,
1157
+ "duplicate-terminal-context",
1158
+ `ContextContribution '${contribution.contributionId}' arrived after request '${request.requestId}' was already terminal`,
1159
+ request.requestId,
1160
+ [
1161
+ ref("context-contribution", contribution.contributionId),
1162
+ ref("agent-request", request.requestId)
1163
+ ]
1164
+ );
1165
+ return;
1166
+ }
1167
+ if (contribution.status === "pending")
1168
+ emitStatusOnce(
1169
+ ctx,
1170
+ state,
1171
+ `context:${contribution.contributionId}:awaiting-context`,
1172
+ request,
1173
+ "awaiting-context",
1174
+ [ref("context-contribution", contribution.contributionId)]
1175
+ );
1176
+ else {
1177
+ state.terminalRequests.add(request.requestId);
1178
+ state.acceptedTerminalFactIds.add(`context:${contribution.contributionId}`);
1179
+ emitStatus(
1180
+ ctx,
1181
+ state,
1182
+ request,
1183
+ contribution.status === "ready" ? "completed" : "failed",
1184
+ [ref("context-contribution", contribution.contributionId)],
1185
+ contribution.issues
1186
+ );
1187
+ }
1188
+ }
1189
+ function handlePromptBundle(ctx, state, prompt) {
1190
+ const request = state.requests.get(prompt.requestId);
1191
+ if (request === void 0) return;
1192
+ if (request.operationId !== prompt.operationId) {
1193
+ emitIssueOnce(
1194
+ ctx,
1195
+ state,
1196
+ `stale-prompt:${prompt.promptId}`,
1197
+ "stale-prompt-operation",
1198
+ `PromptBundle '${prompt.promptId}' operationId does not match request '${request.requestId}'`,
1199
+ request.requestId,
1200
+ [ref("prompt-bundle", prompt.promptId)]
1201
+ );
1202
+ return;
1203
+ }
1204
+ if (request.requestKind !== "prompt") {
1205
+ emitIssueOnce(
1206
+ ctx,
1207
+ state,
1208
+ `wrong-prompt-kind:${prompt.promptId}`,
1209
+ "wrong-kind-prompt-satisfaction",
1210
+ `PromptBundle '${prompt.promptId}' cannot satisfy ${request.requestKind} request '${request.requestId}'`,
1211
+ request.requestId,
1212
+ [ref("prompt-bundle", prompt.promptId)]
1213
+ );
1214
+ return;
1215
+ }
1216
+ if (state.terminalRequests.has(request.requestId)) {
1217
+ if (state.acceptedTerminalFactIds.has(`prompt:${prompt.promptId}`) || state.statusKeys.has(`prompt:${prompt.promptId}:awaiting-prompt`)) {
1218
+ return;
1219
+ }
1220
+ emitIssueOnce(
1221
+ ctx,
1222
+ state,
1223
+ `duplicate-prompt:${prompt.promptId}`,
1224
+ "duplicate-terminal-prompt",
1225
+ `PromptBundle '${prompt.promptId}' arrived after request '${request.requestId}' was already terminal`,
1226
+ request.requestId,
1227
+ [ref("prompt-bundle", prompt.promptId), ref("agent-request", request.requestId)]
1228
+ );
1229
+ return;
1230
+ }
1231
+ if (prompt.status === "ready") {
1232
+ state.terminalRequests.add(request.requestId);
1233
+ state.acceptedTerminalFactIds.add(`prompt:${prompt.promptId}`);
1234
+ emitStatus(ctx, state, request, "completed", [ref("prompt-bundle", prompt.promptId)]);
1235
+ } else if (prompt.status === "issue") {
1236
+ state.terminalRequests.add(request.requestId);
1237
+ state.acceptedTerminalFactIds.add(`prompt:${prompt.promptId}`);
1238
+ emitStatus(
1239
+ ctx,
1240
+ state,
1241
+ request,
1242
+ "failed",
1243
+ [ref("prompt-bundle", prompt.promptId)],
1244
+ prompt.issues
1245
+ );
1246
+ } else {
1247
+ emitStatusOnce(
1248
+ ctx,
1249
+ state,
1250
+ `prompt:${prompt.promptId}:awaiting-prompt`,
1251
+ request,
1252
+ "awaiting-prompt",
1253
+ [ref("prompt-bundle", prompt.promptId)],
1254
+ prompt.issues
1255
+ );
1256
+ }
1257
+ }
1258
+ function routeCompatibilityIssue(request, route, profile) {
1259
+ if (request.requestKind !== "executor") return "route-for-non-executor-request";
1260
+ if (route.executorId !== profile.executorId) return "route-profile-executor-mismatch";
1261
+ if (request.input?.inputId !== void 0 && route.inputId !== void 0 && request.input.inputId !== route.inputId) {
1262
+ return "route-input-mismatch";
1263
+ }
1264
+ if (request.input?.inputKind !== void 0 && route.inputKind !== void 0 && request.input.inputKind !== route.inputKind) {
1265
+ return "route-input-kind-mismatch";
1266
+ }
1267
+ const inputKind = request.input?.inputKind ?? route.inputKind;
1268
+ if (inputKind !== void 0 && !profileKindAcceptsInput(profile.kind, inputKind))
1269
+ return "profile-kind-input-incompatible";
1270
+ if (inputKind !== void 0 && profile.acceptedInputKinds !== void 0 && !profile.acceptedInputKinds.includes(inputKind)) {
1271
+ return "profile-rejects-input-kind";
1272
+ }
1273
+ if (request.input?.schemaRef !== void 0 && profile.acceptedSchemaRefs !== void 0 && !profile.acceptedSchemaRefs.includes(request.input.schemaRef)) {
1274
+ return "profile-rejects-schema";
1275
+ }
1276
+ return void 0;
1277
+ }
1278
+ function outcomeCompatibilityIssue(request, route, outcome) {
1279
+ if (outcome.executorId !== route.executorId) return "outcome-route-executor-mismatch";
1280
+ if (outcome.profileId !== route.profileId) return "outcome-route-profile-mismatch";
1281
+ if (route.inputId !== void 0 && (outcome.inputId === void 0 || outcome.inputId !== route.inputId)) {
1282
+ return "outcome-route-input-mismatch";
1283
+ }
1284
+ if (request.input?.inputId !== void 0 && outcome.inputId !== void 0 && outcome.inputId !== request.input.inputId) {
1285
+ return "outcome-request-input-mismatch";
1286
+ }
1287
+ if (route.inputKind !== void 0 && (outcome.inputKind === void 0 || outcome.inputKind !== route.inputKind)) {
1288
+ return "outcome-route-input-kind-mismatch";
1289
+ }
1290
+ if (request.input?.inputKind !== void 0 && outcome.inputKind !== void 0 && outcome.inputKind !== request.input.inputKind) {
1291
+ return "outcome-request-input-kind-mismatch";
1292
+ }
1293
+ return void 0;
1294
+ }
1295
+ function profileKindAcceptsInput(kind, inputKind) {
1296
+ if (kind === "llm") return inputKind === "llm-call";
1297
+ if (kind === "tool") return inputKind === "tool-call";
1298
+ if (kind === "human") return inputKind === "human-task";
1299
+ return inputKind === "agent-task";
1300
+ }
1301
+ function outcomeStatus(outcome) {
1302
+ if (outcome.kind === "result") return "completed";
1303
+ if (outcome.kind === "failure") return "failed";
1304
+ if (outcome.kind === "timeout") return "timeout";
1305
+ if (outcome.kind === "canceled") return "canceled";
1306
+ return "blocked";
1307
+ }
1308
+ function emitStatus(ctx, state, request, status, sourceRefs, issues) {
1309
+ const cleanSourceRefs = sourceRefs === void 0 ? void 0 : sanitizeAdapterInputSourceRefs(sourceRefs);
1310
+ const cleanIssues = issues === void 0 ? void 0 : Object.freeze(issues.map((issue) => sanitizeAdapterInputIssue(issue)));
1311
+ const fact = {
1312
+ kind: "status",
1313
+ requestId: request.requestId,
1314
+ operationId: request.operationId,
1315
+ effectRunId: request.effectRunId,
1316
+ status,
1317
+ sourceRefs: cleanSourceRefs,
1318
+ issues: cleanIssues
1319
+ };
1320
+ state.auditSeq += 1;
1321
+ ctx.down([
1322
+ ["DATA", { kind: "status", status: fact }],
1323
+ [
1324
+ "DATA",
1325
+ {
1326
+ kind: "audit",
1327
+ audit: {
1328
+ id: `${request.requestId}:status:${state.auditSeq}`,
1329
+ kind: "agent-request-status",
1330
+ subjectId: request.requestId,
1331
+ sourceRefs: cleanSourceRefs,
1332
+ metadata: { status }
1333
+ }
1334
+ }
1335
+ ]
1336
+ ]);
1337
+ }
1338
+ function emitStatusOnce(ctx, state, key, request, status, sourceRefs, issues) {
1339
+ if (state.statusKeys.has(key)) return;
1340
+ state.statusKeys.add(key);
1341
+ emitStatus(ctx, state, request, status, sourceRefs, issues);
1342
+ }
1343
+ function emitIssue(ctx, state, code, message, subjectId, refs) {
1344
+ state.issueSeq += 1;
1345
+ const issue = dataIssue(code, message, { subjectId, refs });
1346
+ state.auditSeq += 1;
1347
+ ctx.down([
1348
+ ["DATA", { kind: "issue", issue }],
1349
+ [
1350
+ "DATA",
1351
+ {
1352
+ kind: "audit",
1353
+ audit: {
1354
+ id: `${subjectId ?? "request"}:issue:${state.auditSeq}`,
1355
+ kind: "agent-request-issue",
1356
+ subjectId,
1357
+ issueCode: code,
1358
+ message,
1359
+ sourceRefs: refs
1360
+ }
1361
+ }
1362
+ ]
1363
+ ]);
1364
+ }
1365
+ function emitIssueOnce(ctx, state, key, code, message, subjectId, refs) {
1366
+ if (state.issueKeys.has(key)) return;
1367
+ state.issueKeys.add(key);
1368
+ emitIssue(ctx, state, code, message, subjectId, refs);
1369
+ }
1370
+
1371
+ // src/orchestration/agent-runtime-tool-provider-run-admission.ts
1372
+ function toolProviderRunAdmissionProjector(graph, opts) {
1373
+ const name = opts.name ?? "toolProviderRunAdmission";
1374
+ const decisionDeps = opts.decisions ?? [];
1375
+ const runtime = graph.node(
1376
+ [opts.inputs, ...opts.runRequests, ...decisionDeps],
1377
+ (ctx) => {
1378
+ const state = ctx.state.get() ?? {
1379
+ inputs: /* @__PURE__ */ new Map(),
1380
+ proposalsById: /* @__PURE__ */ new Map(),
1381
+ proposalsByRun: /* @__PURE__ */ new Map(),
1382
+ decisionsByProposal: /* @__PURE__ */ new Map(),
1383
+ admissionsByProposal: /* @__PURE__ */ new Map(),
1384
+ admissionsByRun: /* @__PURE__ */ new Map(),
1385
+ proposalKeys: /* @__PURE__ */ new Set(),
1386
+ admissionKeys: /* @__PURE__ */ new Set(),
1387
+ approvedRunKeys: /* @__PURE__ */ new Set(),
1388
+ statusKeys: /* @__PURE__ */ new Set(),
1389
+ issueKeys: /* @__PURE__ */ new Set(),
1390
+ auditSeq: 0
1391
+ };
1392
+ for (const raw of depBatch(ctx, 0) ?? []) {
1393
+ const input = raw;
1394
+ state.inputs.set(input.adapterInputId, input);
1395
+ }
1396
+ forEachDepBatch(ctx, 1, opts.runRequests.length, (raw) => {
1397
+ const request = raw;
1398
+ const input = state.inputs.get(request.adapterInputId);
1399
+ if (input === void 0) {
1400
+ emitAdmissionIssue(
1401
+ ctx,
1402
+ state,
1403
+ dataIssue(
1404
+ "tool-provider-run-admission-missing-input",
1405
+ "Tool provider run admission request references an unknown adapter input.",
1406
+ {
1407
+ subjectId: request.adapterInputId,
1408
+ refs: sanitizeAdapterInputSourceRefs([
1409
+ ref("tool-provider-adapter-run", request.runId),
1410
+ ...request.sourceRefs ?? []
1411
+ ])
1412
+ }
1413
+ )
1414
+ );
1415
+ emitAdmissionStatus(ctx, state, {
1416
+ kind: "tool-provider-run-admission-status",
1417
+ proposalId: `${request.runId}:admission-proposal`,
1418
+ runId: request.runId,
1419
+ adapterInputId: request.adapterInputId,
1420
+ requestId: request.requestId,
1421
+ operationId: request.operationId,
1422
+ state: "issue",
1423
+ sourceRefs: request.sourceRefs
1424
+ });
1425
+ return;
1426
+ }
1427
+ handleRunRequest(ctx, state, input, request, opts.now);
1428
+ });
1429
+ forEachDepBatch(ctx, 1 + opts.runRequests.length, decisionDeps.length, (raw) => {
1430
+ const decision = sanitizeAdmissionDecision(raw);
1431
+ state.decisionsByProposal.set(decision.proposalId, decision);
1432
+ const internal = state.proposalsById.get(decision.proposalId);
1433
+ if (internal !== void 0) applyDecision(ctx, state, internal, decision, opts.now);
1434
+ });
1435
+ ctx.down([["DATA", { kind: "views", views: buildAdmissionViews(state) }]]);
1436
+ ctx.state.set(state);
1437
+ },
1438
+ { name: `${name}/runtime`, factory: "toolProviderRunAdmissionProjector", partial: true }
1439
+ );
1440
+ return {
1441
+ proposals: projectRuntimeFact(
1442
+ graph,
1443
+ runtime,
1444
+ `${name}/proposals`,
1445
+ "toolProviderRunAdmissionProposals",
1446
+ (fact) => fact.kind === "proposal" ? fact.proposal : void 0
1447
+ ),
1448
+ admissions: projectRuntimeFact(
1449
+ graph,
1450
+ runtime,
1451
+ `${name}/admissions`,
1452
+ "toolProviderRunAdmissions",
1453
+ (fact) => fact.kind === "admission" ? fact.admission : void 0
1454
+ ),
1455
+ approvedRunRequests: projectRuntimeFact(
1456
+ graph,
1457
+ runtime,
1458
+ `${name}/approvedRunRequests`,
1459
+ "toolProviderRunAdmissionApprovedRunRequests",
1460
+ (fact) => fact.kind === "approved-run-request" ? fact.request : void 0
1461
+ ),
1462
+ status: projectRuntimeFact(
1463
+ graph,
1464
+ runtime,
1465
+ `${name}/status`,
1466
+ "toolProviderRunAdmissionStatus",
1467
+ (fact) => fact.kind === "status" ? fact.status : void 0
1468
+ ),
1469
+ issues: projectRuntimeFact(
1470
+ graph,
1471
+ runtime,
1472
+ `${name}/issues`,
1473
+ "toolProviderRunAdmissionIssues",
1474
+ (fact) => fact.kind === "issue" ? fact.issue : void 0
1475
+ ),
1476
+ audit: projectRuntimeFact(
1477
+ graph,
1478
+ runtime,
1479
+ `${name}/audit`,
1480
+ "toolProviderRunAdmissionAudit",
1481
+ (fact) => fact.kind === "audit" ? fact.audit : void 0
1482
+ ),
1483
+ views: projectRuntimeFact(
1484
+ graph,
1485
+ runtime,
1486
+ `${name}/views`,
1487
+ "toolProviderRunAdmissionViews",
1488
+ (fact) => fact.kind === "views" ? fact.views : void 0
1489
+ )
1490
+ };
1491
+ }
1492
+ function handleRunRequest(ctx, state, input, request, now) {
1493
+ const issues = runRequestIdentityIssues(request, input);
1494
+ if (input.status !== "ready") {
1495
+ issues.push(
1496
+ dataIssue(
1497
+ "tool-provider-run-admission-input-not-ready",
1498
+ "Tool provider run admission requires a ready adapter input.",
1499
+ {
1500
+ subjectId: input.requestId,
1501
+ refs: [ref("tool-provider-adapter-input", input.adapterInputId)],
1502
+ details: { status: input.status }
1503
+ }
1504
+ )
1505
+ );
1506
+ }
1507
+ if (issues.length > 0) {
1508
+ for (const issue of issues) emitAdmissionIssue(ctx, state, issue);
1509
+ emitAdmissionStatus(ctx, state, {
1510
+ kind: "tool-provider-run-admission-status",
1511
+ proposalId: `${request.runId}:admission-proposal`,
1512
+ runId: request.runId,
1513
+ adapterInputId: request.adapterInputId,
1514
+ requestId: request.requestId,
1515
+ operationId: request.operationId,
1516
+ state: "issue",
1517
+ issues: Object.freeze(issues),
1518
+ sourceRefs: request.sourceRefs
1519
+ });
1520
+ emitAdmissionAudit(ctx, state, "tool-provider-run-admission-request-rejected", request, {
1521
+ issueCodes: issues.map((issue) => issue.code)
1522
+ });
1523
+ return;
1524
+ }
1525
+ const approval = resolveApprovalPolicy(input);
1526
+ const proposal = admissionProposal(input, request, approval);
1527
+ const internal = { proposal, request, input };
1528
+ state.proposalsById.set(proposal.proposalId, internal);
1529
+ pushMapArrayBy(state.proposalsByRun, request.runId, proposal, (entry) => entry.proposalId);
1530
+ emitProposal(ctx, state, proposal);
1531
+ emitAdmissionAudit(ctx, state, "tool-provider-run-admission-proposed", proposal, {
1532
+ approvalMode: proposal.approvalMode
1533
+ });
1534
+ if (proposal.approvalMode === "auto") {
1535
+ admit(ctx, state, internal, void 0, now);
1536
+ return;
1537
+ }
1538
+ if (proposal.approvalMode === "never") {
1539
+ recordAdmission(ctx, state, internal, "blocked", {
1540
+ reason: "blocked by tool provider approval policy",
1541
+ now
1542
+ });
1543
+ return;
1544
+ }
1545
+ const decision = state.decisionsByProposal.get(proposal.proposalId);
1546
+ if (decision === void 0) {
1547
+ emitAdmissionStatus(ctx, state, {
1548
+ kind: "tool-provider-run-admission-status",
1549
+ proposalId: proposal.proposalId,
1550
+ runId: request.runId,
1551
+ adapterInputId: request.adapterInputId,
1552
+ requestId: request.requestId,
1553
+ operationId: request.operationId,
1554
+ state: "waiting",
1555
+ sourceRefs: proposal.sourceRefs
1556
+ });
1557
+ return;
1558
+ }
1559
+ applyDecision(ctx, state, internal, decision, now);
1560
+ }
1561
+ function applyDecision(ctx, state, internal, decision, now) {
1562
+ const existing = state.admissionsByProposal.get(internal.proposal.proposalId);
1563
+ if (existing !== void 0) {
1564
+ if (existing.decisionId === decision.decisionId) return;
1565
+ const issue = dataIssue(
1566
+ "tool-provider-run-admission-duplicate-decision",
1567
+ "Tool provider run admission proposal already has a terminal admission decision.",
1568
+ {
1569
+ subjectId: internal.input.requestId,
1570
+ refs: admissionSourceRefs(internal, decision),
1571
+ severity: "warning",
1572
+ details: {
1573
+ proposalId: internal.proposal.proposalId,
1574
+ existingDecisionId: existing.decisionId,
1575
+ rejectedDecisionId: decision.decisionId
1576
+ }
1577
+ }
1578
+ );
1579
+ emitAdmissionIssue(ctx, state, issue);
1580
+ emitAdmissionStatus(ctx, state, {
1581
+ kind: "tool-provider-run-admission-status",
1582
+ proposalId: internal.proposal.proposalId,
1583
+ runId: internal.request.runId,
1584
+ adapterInputId: internal.input.adapterInputId,
1585
+ requestId: internal.input.requestId,
1586
+ operationId: internal.input.operationId,
1587
+ state: "issue",
1588
+ issues: Object.freeze([issue]),
1589
+ sourceRefs: admissionSourceRefs(internal, decision)
1590
+ });
1591
+ emitAdmissionAudit(ctx, state, "tool-provider-run-admission-duplicate-decision", decision, {
1592
+ proposalId: internal.proposal.proposalId,
1593
+ existingDecisionId: existing.decisionId
1594
+ });
1595
+ return;
1596
+ }
1597
+ if (decision.outcome === "admit") {
1598
+ admit(ctx, state, internal, decision, now);
1599
+ return;
1600
+ }
1601
+ recordAdmission(ctx, state, internal, admissionStateForOutcome(decision.outcome), {
1602
+ decision,
1603
+ reason: decision.reason,
1604
+ now
1605
+ });
1606
+ }
1607
+ function admit(ctx, state, internal, decision, now) {
1608
+ const approvedRunId = decision?.approvedRunId ?? (decision === void 0 ? `${internal.request.runId}:admitted` : `${internal.request.runId}:admitted:${decision.decisionId}`);
1609
+ const admission = recordAdmission(ctx, state, internal, "admitted", {
1610
+ decision,
1611
+ approvedRunId,
1612
+ reason: decision?.reason,
1613
+ now
1614
+ });
1615
+ const approvedRequest = requestToolProviderAdapterRun(internal.input, {
1616
+ runId: approvedRunId,
1617
+ attempt: internal.request.attempt,
1618
+ reason: internal.request.reason,
1619
+ retryOfOutcomeId: internal.request.retryOfOutcomeId,
1620
+ policyRefs: internal.request.policyRefs ?? internal.input.policyRefs,
1621
+ sourceRefs: uniqueSourceRefs([
1622
+ ref("tool-provider-adapter-run", internal.request.runId),
1623
+ ref("tool-provider-run-admission-proposal", internal.proposal.proposalId),
1624
+ ref("tool-provider-run-admission", admission.admissionId),
1625
+ ...decision === void 0 ? [] : [ref("tool-provider-run-admission-decision", decision.decisionId)],
1626
+ ...internal.request.sourceRefs ?? []
1627
+ ]),
1628
+ metadata: {
1629
+ ...internal.request.metadata ?? {},
1630
+ approval: "granted",
1631
+ approvalGranted: true,
1632
+ admissionId: admission.admissionId,
1633
+ proposalId: internal.proposal.proposalId,
1634
+ approvedFromRunId: internal.request.runId,
1635
+ ...decision === void 0 ? {} : { decisionId: decision.decisionId }
1636
+ },
1637
+ requestedAtMs: now?.()
1638
+ });
1639
+ emitApprovedRunRequest(ctx, state, approvedRequest);
1640
+ emitAdmissionAudit(
1641
+ ctx,
1642
+ state,
1643
+ "tool-provider-run-admission-approved-run-requested",
1644
+ {
1645
+ proposalId: internal.proposal.proposalId,
1646
+ runId: approvedRequest.runId
1647
+ },
1648
+ {
1649
+ approvedFromRunId: internal.request.runId,
1650
+ decisionId: decision?.decisionId
1651
+ }
1652
+ );
1653
+ }
1654
+ function recordAdmission(ctx, state, internal, admissionState, opts) {
1655
+ const admissionId = opts.decision?.admissionId ?? `${internal.proposal.proposalId}:admission`;
1656
+ const sourceRefs = admissionSourceRefs(internal, opts.decision);
1657
+ const admission = Object.freeze({
1658
+ kind: "tool-provider-run-admission",
1659
+ admissionId,
1660
+ proposalId: internal.proposal.proposalId,
1661
+ runId: internal.request.runId,
1662
+ adapterInputId: internal.input.adapterInputId,
1663
+ requestId: internal.input.requestId,
1664
+ operationId: internal.input.operationId,
1665
+ state: admissionState,
1666
+ ...opts.decision === void 0 ? {} : { decisionId: opts.decision.decisionId },
1667
+ ...opts.approvedRunId === void 0 ? {} : { approvedRunId: opts.approvedRunId },
1668
+ ...opts.reason === void 0 ? {} : { reason: opts.reason },
1669
+ sourceRefs,
1670
+ metadata: sanitizeProviderGraphVisibleRecord({
1671
+ approvalMode: internal.proposal.approvalMode,
1672
+ occurredAtMs: opts.now?.()
1673
+ })
1674
+ });
1675
+ state.admissionsByProposal.set(admission.proposalId, admission);
1676
+ pushMapArrayBy(state.admissionsByRun, admission.runId, admission, (entry) => entry.admissionId);
1677
+ emitAdmission(ctx, state, admission);
1678
+ if (admissionState === "blocked") {
1679
+ emitAdmissionIssue(
1680
+ ctx,
1681
+ state,
1682
+ dataIssue(
1683
+ "tool-provider-run-admission-blocked",
1684
+ "Tool provider run admission blocked the candidate run request.",
1685
+ {
1686
+ subjectId: internal.input.requestId,
1687
+ refs: sourceRefs,
1688
+ severity: "warning",
1689
+ details: { approvalMode: internal.proposal.approvalMode }
1690
+ }
1691
+ )
1692
+ );
1693
+ }
1694
+ emitAdmissionStatus(ctx, state, {
1695
+ kind: "tool-provider-run-admission-status",
1696
+ proposalId: admission.proposalId,
1697
+ runId: admission.runId,
1698
+ adapterInputId: admission.adapterInputId,
1699
+ requestId: admission.requestId,
1700
+ operationId: admission.operationId,
1701
+ state: admission.state,
1702
+ admissionId: admission.admissionId,
1703
+ ...admission.decisionId === void 0 ? {} : { decisionId: admission.decisionId },
1704
+ ...admission.approvedRunId === void 0 ? {} : { approvedRunId: admission.approvedRunId },
1705
+ sourceRefs
1706
+ });
1707
+ emitAdmissionAudit(ctx, state, `tool-provider-run-admission-${admissionState}`, admission, {
1708
+ decisionId: opts.decision?.decisionId
1709
+ });
1710
+ return admission;
1711
+ }
1712
+ function admissionProposal(input, request, approval) {
1713
+ const sourceRefs = uniqueSourceRefs([
1714
+ ref("tool-provider-adapter-run", request.runId),
1715
+ ref("tool-provider-adapter-input", input.adapterInputId),
1716
+ ...request.sourceRefs ?? [],
1717
+ ...input.sourceRefs ?? [],
1718
+ ...approval.policy?.approval?.sourceRefs ?? [],
1719
+ ...approval.policy?.sourceRefs ?? []
1720
+ ]);
1721
+ return Object.freeze({
1722
+ kind: "tool-provider-run-admission-proposal",
1723
+ proposalId: `${request.runId}:admission-proposal`,
1724
+ runId: request.runId,
1725
+ adapterInputId: input.adapterInputId,
1726
+ requestId: input.requestId,
1727
+ operationId: input.operationId,
1728
+ routeId: input.routeId,
1729
+ providerId: input.providerId,
1730
+ executorId: input.executorId,
1731
+ profileId: input.profileId,
1732
+ toolName: input.toolName,
1733
+ operation: input.operation,
1734
+ attempt: request.attempt,
1735
+ reason: request.reason,
1736
+ approvalMode: approval.mode,
1737
+ policyRefs: sanitizeAdapterInputSourceRefs([
1738
+ ...request.policyRefs ?? [],
1739
+ ...input.policyRefs ?? [],
1740
+ ...approval.policy === void 0 ? [] : [ref("tool-provider-execution-policy", approval.policy.policyId)]
1741
+ ]),
1742
+ sourceRefs: sanitizeAdapterInputSourceRefs(sourceRefs),
1743
+ needs: approval.mode === "require" || approval.mode === "custom" ? approvalNeeds(approval.policy?.approval) : void 0,
1744
+ metadata: sanitizeProviderGraphVisibleRecord({
1745
+ approvalPolicyId: approval.policy?.policyId,
1746
+ approvalMode: approval.mode
1747
+ })
1748
+ });
1749
+ }
1750
+ function resolveApprovalPolicy(input) {
1751
+ for (const policy of input.policies ?? []) {
1752
+ const approval = policy.approval;
1753
+ const mode = approval?.mode ?? "auto";
1754
+ if (matchesApprovalSelector(input, approval)) return { mode, policy };
1755
+ }
1756
+ return { mode: "auto" };
1757
+ }
1758
+ function matchesApprovalSelector(input, approval) {
1759
+ if (approval === void 0) return true;
1760
+ const names = approval.requiredForToolNames;
1761
+ const operations = approval.requiredForOperations;
1762
+ const matchesName = names === void 0 || input.toolName !== void 0 && names.includes(input.toolName);
1763
+ const matchesOperation = operations === void 0 || input.operation !== void 0 && operations.includes(input.operation);
1764
+ return matchesName && matchesOperation;
1765
+ }
1766
+ function approvalNeeds(approval) {
1767
+ return Object.freeze([
1768
+ {
1769
+ kind: "approval",
1770
+ message: "Tool provider run requires graph-visible admission.",
1771
+ refs: sanitizeAdapterInputSourceRefs(approval?.approverRefs ?? []),
1772
+ metadata: sanitizeProviderGraphVisibleRecord({ approvalMode: approval?.mode ?? "require" })
1773
+ }
1774
+ ]);
1775
+ }
1776
+ function admissionStateForOutcome(outcome) {
1777
+ if (outcome === "admit") return "admitted";
1778
+ if (outcome === "defer") return "deferred";
1779
+ return "blocked";
1780
+ }
1781
+ function admissionSourceRefs(internal, decision) {
1782
+ return sanitizeAdapterInputSourceRefs([
1783
+ ref("tool-provider-run-admission-proposal", internal.proposal.proposalId),
1784
+ ref("tool-provider-adapter-run", internal.request.runId),
1785
+ ref("tool-provider-adapter-input", internal.input.adapterInputId),
1786
+ ...decision === void 0 ? [] : [ref("tool-provider-run-admission-decision", decision.decisionId)],
1787
+ ...decision?.sourceRefs ?? []
1788
+ ]);
1789
+ }
1790
+ function sanitizeAdmissionDecision(decision) {
1791
+ return Object.freeze({
1792
+ kind: "tool-provider-run-admission-decision",
1793
+ decisionId: decision.decisionId,
1794
+ proposalId: decision.proposalId,
1795
+ admissionId: decision.admissionId,
1796
+ outcome: decision.outcome,
1797
+ ...decision.approvedRunId === void 0 ? {} : { approvedRunId: decision.approvedRunId },
1798
+ ...decision.reason === void 0 ? {} : { reason: decision.reason },
1799
+ ...decision.decidedByRef === void 0 ? {} : { decidedByRef: sanitizeAdapterInputSourceRefs([decision.decidedByRef])[0] },
1800
+ ...decision.sourceRefs === void 0 ? {} : { sourceRefs: sanitizeAdapterInputSourceRefs(decision.sourceRefs) },
1801
+ metadata: sanitizeProviderGraphVisibleRecord(decision.metadata)
1802
+ });
1803
+ }
1804
+ function emitProposal(ctx, state, proposal) {
1805
+ const key = `proposal:${proposal.proposalId}`;
1806
+ if (state.proposalKeys.has(key)) return;
1807
+ state.proposalKeys.add(key);
1808
+ ctx.down([["DATA", { kind: "proposal", proposal }]]);
1809
+ }
1810
+ function emitAdmission(ctx, state, admission) {
1811
+ const key = `admission:${admission.admissionId}:${admission.state}:${admission.decisionId ?? ""}:${admission.approvedRunId ?? ""}`;
1812
+ if (state.admissionKeys.has(key)) return;
1813
+ state.admissionKeys.add(key);
1814
+ ctx.down([["DATA", { kind: "admission", admission }]]);
1815
+ }
1816
+ function emitApprovedRunRequest(ctx, state, request) {
1817
+ const key = `approved-run:${request.runId}`;
1818
+ if (state.approvedRunKeys.has(key)) return;
1819
+ state.approvedRunKeys.add(key);
1820
+ ctx.down([["DATA", { kind: "approved-run-request", request }]]);
1821
+ }
1822
+ function emitAdmissionStatus(ctx, state, status) {
1823
+ const key = `status:${status.proposalId}:${status.state}:${status.admissionId ?? ""}:${status.decisionId ?? ""}:${status.approvedRunId ?? ""}`;
1824
+ if (state.statusKeys.has(key)) return;
1825
+ state.statusKeys.add(key);
1826
+ ctx.down([["DATA", { kind: "status", status }]]);
1827
+ }
1828
+ function emitAdmissionIssue(ctx, state, issue) {
1829
+ const key = `issue:${issue.code}:${issue.subjectId ?? ""}:${JSON.stringify(issue.details ?? {})}`;
1830
+ if (state.issueKeys.has(key)) return;
1831
+ state.issueKeys.add(key);
1832
+ ctx.down([["DATA", { kind: "issue", issue }]]);
1833
+ }
1834
+ function emitAdmissionAudit(ctx, state, kind, subject, metadata) {
1835
+ state.auditSeq += 1;
1836
+ ctx.down([
1837
+ [
1838
+ "DATA",
1839
+ {
1840
+ kind: "audit",
1841
+ audit: Object.freeze({
1842
+ id: `tool-provider-run-admission-audit-${state.auditSeq}`,
1843
+ kind,
1844
+ message: kind,
1845
+ sourceRefs: [],
1846
+ metadata: sanitizeProviderGraphVisibleRecord({
1847
+ ...metadata,
1848
+ subject
1849
+ })
1850
+ })
1851
+ }
1852
+ ]
1853
+ ]);
1854
+ }
1855
+ function buildAdmissionViews(state) {
1856
+ return Object.freeze({
1857
+ admissionsByProposal: new Map(state.admissionsByProposal),
1858
+ admissionsByRun: new Map(
1859
+ Array.from(state.admissionsByRun.entries()).map(([key, value]) => [
1860
+ key,
1861
+ Object.freeze([...value])
1862
+ ])
1863
+ ),
1864
+ proposalsByRun: new Map(
1865
+ Array.from(state.proposalsByRun.entries()).map(([key, value]) => [
1866
+ key,
1867
+ Object.freeze([...value])
1868
+ ])
1869
+ )
1870
+ });
1871
+ }
1872
+ function pushMapArrayBy(map, key, value, entryKey) {
1873
+ const existing = map.get(key);
1874
+ if (existing === void 0) {
1875
+ map.set(key, [value]);
1876
+ return;
1877
+ }
1878
+ const valueKey = entryKey(value);
1879
+ if (existing.some((entry) => entryKey(entry) === valueKey)) return;
1880
+ existing.push(value);
1881
+ }
1882
+
1883
+ // src/orchestration/agent-runtime-tool-provider-run-retry.ts
1884
+ function toolProviderRunRetryProjector(graph, opts) {
1885
+ const name = opts.name ?? "toolProviderRunRetry";
1886
+ const policyDeps = opts.policies ?? [];
1887
+ const nowDeps = opts.nowMs === void 0 ? [] : [opts.nowMs];
1888
+ const readinessDeps = opts.readiness ?? [];
1889
+ const outcomeDepIndex = 1 + policyDeps.length;
1890
+ const nowDepIndex = outcomeDepIndex + 1;
1891
+ const readinessDepStart = nowDepIndex + nowDeps.length;
1892
+ const runtime = graph.node(
1893
+ [opts.inputs, ...policyDeps, opts.outcomes, ...nowDeps, ...readinessDeps],
1894
+ (ctx) => {
1895
+ const state = ctx.state.get() ?? initialRetryState();
1896
+ state.usesSharedReadiness = readinessDeps.length > 0;
1897
+ for (const raw of depBatch(ctx, 0) ?? []) {
1898
+ const input = raw;
1899
+ state.inputsById.set(input.adapterInputId, input);
1900
+ let inputIds = state.inputIdsByRequest.get(input.requestId);
1901
+ if (inputIds === void 0) {
1902
+ inputIds = /* @__PURE__ */ new Set();
1903
+ state.inputIdsByRequest.set(input.requestId, inputIds);
1904
+ }
1905
+ inputIds.add(input.adapterInputId);
1906
+ }
1907
+ forEachDepBatch(ctx, 1, policyDeps.length, (raw) => {
1908
+ const policy = sanitizeToolProviderRunRetryPolicy(raw);
1909
+ state.policies.set(policy.policyId, policy);
1910
+ });
1911
+ for (const rawNow of depBatch(ctx, nowDepIndex) ?? []) {
1912
+ if (typeof rawNow === "number" && Number.isFinite(rawNow)) state.nowMs = rawNow;
1913
+ }
1914
+ forEachDepBatch(ctx, readinessDepStart, readinessDeps.length, (raw) => {
1915
+ const ready = sanitizeRetryReadinessReady(raw);
1916
+ if (!ready.ok) {
1917
+ emitIssue2(ctx, state, ready.issue);
1918
+ return;
1919
+ }
1920
+ state.readinessBySchedule.set(ready.scheduleId, ready);
1921
+ });
1922
+ for (const raw of depBatch(ctx, outcomeDepIndex) ?? []) {
1923
+ retainOutcome(state, raw);
1924
+ }
1925
+ evaluateOutcomes(ctx, state);
1926
+ processDueRetries(ctx, state);
1927
+ ctx.down([["DATA", { kind: "views", views: buildRetryViews(state) }]]);
1928
+ ctx.state.set(state);
1929
+ },
1930
+ { name: `${name}/runtime`, factory: "toolProviderRunRetryProjector", partial: true }
1931
+ );
1932
+ return {
1933
+ proposals: projectRuntimeFact(
1934
+ graph,
1935
+ runtime,
1936
+ `${name}/proposals`,
1937
+ "toolProviderRunRetryProposals",
1938
+ (fact) => fact.kind === "proposal" ? fact.proposal : void 0
1939
+ ),
1940
+ scheduled: projectRuntimeFact(
1941
+ graph,
1942
+ runtime,
1943
+ `${name}/scheduled`,
1944
+ "toolProviderRunRetryScheduled",
1945
+ (fact) => fact.kind === "scheduled" ? fact.scheduled : void 0
1946
+ ),
1947
+ readinessSchedules: projectRuntimeFact(
1948
+ graph,
1949
+ runtime,
1950
+ `${name}/readinessSchedules`,
1951
+ "toolProviderRunRetryReadinessSchedules",
1952
+ (fact) => fact.kind === "readiness-schedule" ? fact.schedule : void 0
1953
+ ),
1954
+ runRequests: projectRuntimeFact(
1955
+ graph,
1956
+ runtime,
1957
+ `${name}/runRequests`,
1958
+ "toolProviderRunRetryRunRequests",
1959
+ (fact) => fact.kind === "run-request" ? fact.request : void 0
1960
+ ),
1961
+ status: projectRuntimeFact(
1962
+ graph,
1963
+ runtime,
1964
+ `${name}/status`,
1965
+ "toolProviderRunRetryStatus",
1966
+ (fact) => fact.kind === "status" ? fact.status : void 0
1967
+ ),
1968
+ issues: projectRuntimeFact(
1969
+ graph,
1970
+ runtime,
1971
+ `${name}/issues`,
1972
+ "toolProviderRunRetryIssues",
1973
+ (fact) => fact.kind === "issue" ? fact.issue : void 0
1974
+ ),
1975
+ audit: projectRuntimeFact(
1976
+ graph,
1977
+ runtime,
1978
+ `${name}/audit`,
1979
+ "toolProviderRunRetryAudit",
1980
+ (fact) => fact.kind === "audit" ? fact.audit : void 0
1981
+ ),
1982
+ views: projectRuntimeFact(
1983
+ graph,
1984
+ runtime,
1985
+ `${name}/views`,
1986
+ "toolProviderRunRetryViews",
1987
+ (fact) => fact.kind === "views" ? fact.views : void 0
1988
+ )
1989
+ };
1990
+ }
1991
+ function initialRetryState() {
1992
+ return {
1993
+ inputIdsByRequest: /* @__PURE__ */ new Map(),
1994
+ inputsById: /* @__PURE__ */ new Map(),
1995
+ policies: /* @__PURE__ */ new Map(),
1996
+ outcomesById: /* @__PURE__ */ new Map(),
1997
+ proposalsByOutcome: /* @__PURE__ */ new Map(),
1998
+ scheduledByOutcome: /* @__PURE__ */ new Map(),
1999
+ readinessSchedulesByOutcome: /* @__PURE__ */ new Map(),
2000
+ readinessBySchedule: /* @__PURE__ */ new Map(),
2001
+ nextRequestsByOutcome: /* @__PURE__ */ new Map(),
2002
+ statusByOutcome: /* @__PURE__ */ new Map(),
2003
+ proposalKeys: /* @__PURE__ */ new Set(),
2004
+ scheduledKeys: /* @__PURE__ */ new Set(),
2005
+ readinessScheduleKeys: /* @__PURE__ */ new Set(),
2006
+ requestKeys: /* @__PURE__ */ new Set(),
2007
+ statusKeys: /* @__PURE__ */ new Set(),
2008
+ issueKeys: /* @__PURE__ */ new Set(),
2009
+ auditSeq: 0,
2010
+ nowMs: void 0,
2011
+ usesSharedReadiness: false
2012
+ };
2013
+ }
2014
+ function retainOutcome(state, outcome) {
2015
+ if (!state.outcomesById.has(outcome.outcomeId))
2016
+ state.outcomesById.set(outcome.outcomeId, outcome);
2017
+ }
2018
+ function inputForOutcome(state, outcome) {
2019
+ if (typeof outcome.inputId === "string" && outcome.inputId.length > 0) {
2020
+ const exactInput = state.inputsById.get(outcome.inputId);
2021
+ if (exactInput !== void 0) return { ok: true, input: exactInput };
2022
+ return {
2023
+ ok: false,
2024
+ issue: dataIssue(
2025
+ "tool-provider-run-retry-missing-input",
2026
+ "Tool provider run retry requires the retained adapter input identified by the outcome.",
2027
+ {
2028
+ subjectId: outcome.inputId,
2029
+ refs: [ref("executor-outcome", outcome.outcomeId)]
2030
+ }
2031
+ )
2032
+ };
2033
+ }
2034
+ const inputIds = state.inputIdsByRequest.get(outcome.requestId);
2035
+ if (inputIds === void 0 || inputIds.size === 0) {
2036
+ return {
2037
+ ok: false,
2038
+ issue: dataIssue(
2039
+ "tool-provider-run-retry-missing-input",
2040
+ "Tool provider run retry requires a retained adapter input for the outcome request.",
2041
+ { subjectId: outcome.requestId, refs: [ref("executor-outcome", outcome.outcomeId)] }
2042
+ )
2043
+ };
2044
+ }
2045
+ if (inputIds.size > 1) {
2046
+ return {
2047
+ ok: false,
2048
+ issue: dataIssue(
2049
+ "tool-provider-run-retry-ambiguous-input",
2050
+ "Tool provider run retry requires an exact outcome inputId when multiple adapter inputs share a request.",
2051
+ {
2052
+ subjectId: outcome.requestId,
2053
+ refs: [ref("executor-outcome", outcome.outcomeId)],
2054
+ details: { inputIds: [...inputIds].sort() }
2055
+ }
2056
+ )
2057
+ };
2058
+ }
2059
+ const [inputId] = inputIds;
2060
+ const input = inputId === void 0 ? void 0 : state.inputsById.get(inputId);
2061
+ if (input !== void 0) return { ok: true, input };
2062
+ return {
2063
+ ok: false,
2064
+ issue: dataIssue(
2065
+ "tool-provider-run-retry-missing-input",
2066
+ "Tool provider run retry requires a retained adapter input for the outcome request.",
2067
+ { subjectId: outcome.requestId, refs: [ref("executor-outcome", outcome.outcomeId)] }
2068
+ )
2069
+ };
2070
+ }
2071
+ function evaluateOutcomes(ctx, state) {
2072
+ for (const outcome of state.outcomesById.values()) evaluateOutcome(ctx, state, outcome);
2073
+ }
2074
+ function evaluateOutcome(ctx, state, outcome) {
2075
+ const inputResolution = inputForOutcome(state, outcome);
2076
+ if (!inputResolution.ok) {
2077
+ emitIssue2(ctx, state, inputResolution.issue);
2078
+ emitStatus2(ctx, state, statusForMissingInput(outcome, "blocked", [inputResolution.issue]));
2079
+ return;
2080
+ }
2081
+ const input = inputResolution.input;
2082
+ if (input.status !== "ready") {
2083
+ const issue = dataIssue(
2084
+ "tool-provider-run-retry-input-not-ready",
2085
+ "Tool provider run retry requires a ready adapter input.",
2086
+ {
2087
+ subjectId: input.adapterInputId,
2088
+ refs: [
2089
+ ref("executor-outcome", outcome.outcomeId),
2090
+ ref("tool-provider-adapter-input", input.adapterInputId)
2091
+ ],
2092
+ details: { status: input.status }
2093
+ }
2094
+ );
2095
+ emitIssue2(ctx, state, issue);
2096
+ emitStatus2(ctx, state, statusForOutcome(outcome, input, "blocked", { issues: [issue] }));
2097
+ return;
2098
+ }
2099
+ if (!isRetryableOutcome(outcome)) {
2100
+ emitStatus2(ctx, state, statusForOutcome(outcome, input, "not-retryable"));
2101
+ return;
2102
+ }
2103
+ if (state.scheduledByOutcome.has(outcome.outcomeId) || state.nextRequestsByOutcome.has(outcome.outcomeId)) {
2104
+ return;
2105
+ }
2106
+ const choice = chooseRetryPolicy(state, input, outcome);
2107
+ if (choice === void 0) {
2108
+ const issue = dataIssue(
2109
+ "tool-provider-run-retry-policy-missing",
2110
+ "Tool provider run retry requires an explicit retry policy fact.",
2111
+ {
2112
+ subjectId: input.adapterInputId,
2113
+ refs: [
2114
+ ref("executor-outcome", outcome.outcomeId),
2115
+ ref("tool-provider-adapter-input", input.adapterInputId)
2116
+ ]
2117
+ }
2118
+ );
2119
+ emitIssue2(ctx, state, issue);
2120
+ emitStatus2(ctx, state, statusForOutcome(outcome, input, "not-retryable", { issues: [issue] }));
2121
+ return;
2122
+ }
2123
+ if (!shouldRetry(choice.policy.retryPolicy, outcome.attempt)) {
2124
+ const issue = dataIssue(
2125
+ "tool-provider-run-retry-exhausted",
2126
+ "Tool provider run retry policy exhausted available attempts.",
2127
+ {
2128
+ subjectId: input.adapterInputId,
2129
+ refs: retrySourceRefs(input, outcome, choice.policy),
2130
+ severity: "warning",
2131
+ details: {
2132
+ attempt: outcome.attempt,
2133
+ maxAttempts: choice.policy.retryPolicy.maxAttempts
2134
+ }
2135
+ }
2136
+ );
2137
+ emitIssue2(ctx, state, issue);
2138
+ emitStatus2(
2139
+ ctx,
2140
+ state,
2141
+ statusForOutcome(outcome, input, "exhausted", { choice, issues: [issue] })
2142
+ );
2143
+ return;
2144
+ }
2145
+ const nextAttempt = outcome.attempt + 1;
2146
+ const delayMs = nextRetryDelayMs(choice.policy.retryPolicy, nextAttempt);
2147
+ if (delayMs === void 0) {
2148
+ const issue = dataIssue(
2149
+ "tool-provider-run-retry-delay-unavailable",
2150
+ "Tool provider run retry could not compute a delay for the next attempt.",
2151
+ {
2152
+ subjectId: input.adapterInputId,
2153
+ refs: retrySourceRefs(input, outcome, choice.policy)
2154
+ }
2155
+ );
2156
+ emitIssue2(ctx, state, issue);
2157
+ emitStatus2(
2158
+ ctx,
2159
+ state,
2160
+ statusForOutcome(outcome, input, "blocked", { choice, issues: [issue] })
2161
+ );
2162
+ return;
2163
+ }
2164
+ const proposal = retryProposal(input, outcome, choice, delayMs);
2165
+ state.proposalsByOutcome.set(outcome.outcomeId, proposal);
2166
+ emitProposal2(ctx, state, proposal);
2167
+ if (delayMs <= 0) {
2168
+ emitRunRequest(ctx, state, input, proposal, "immediate");
2169
+ return;
2170
+ }
2171
+ if (state.nowMs === void 0) {
2172
+ const issue = dataIssue(
2173
+ "tool-provider-run-retry-now-missing",
2174
+ "Tool provider delayed retry requires a graph-visible nowMs input.",
2175
+ {
2176
+ subjectId: input.adapterInputId,
2177
+ refs: retrySourceRefs(input, outcome, choice.policy)
2178
+ }
2179
+ );
2180
+ emitIssue2(ctx, state, issue);
2181
+ emitStatus2(
2182
+ ctx,
2183
+ state,
2184
+ statusForOutcome(outcome, input, "blocked", { choice, proposal, issues: [issue], delayMs })
2185
+ );
2186
+ return;
2187
+ }
2188
+ const scheduled = retryScheduled(input, outcome, proposal, state.nowMs + delayMs, delayMs);
2189
+ state.scheduledByOutcome.set(outcome.outcomeId, scheduled);
2190
+ emitScheduled(ctx, state, scheduled);
2191
+ const readinessSchedule = retryReadinessSchedule(input, outcome, proposal, scheduled);
2192
+ state.readinessSchedulesByOutcome.set(outcome.outcomeId, readinessSchedule);
2193
+ emitReadinessSchedule(ctx, state, readinessSchedule);
2194
+ emitStatus2(
2195
+ ctx,
2196
+ state,
2197
+ statusForOutcome(outcome, input, "scheduled", {
2198
+ choice,
2199
+ proposal,
2200
+ delayMs,
2201
+ retryAtMs: scheduled.retryAtMs
2202
+ })
2203
+ );
2204
+ }
2205
+ function processDueRetries(ctx, state) {
2206
+ for (const [outcomeId, scheduled] of state.scheduledByOutcome) {
2207
+ const readiness = state.readinessBySchedule.get(
2208
+ scheduled.readinessScheduleId ?? scheduled.scheduleId
2209
+ );
2210
+ const readinessSchedule = state.readinessSchedulesByOutcome.get(outcomeId);
2211
+ const readyByReadiness = readiness !== void 0 && readiness.readyAtMs === scheduled.retryAtMs && readiness.nowMs >= scheduled.retryAtMs && readinessSchedule !== void 0 && readinessMatchesSchedule(readiness, readinessSchedule);
2212
+ if (readiness !== void 0 && !readyByReadiness) {
2213
+ emitIssue2(
2214
+ ctx,
2215
+ state,
2216
+ dataIssue(
2217
+ "tool-provider-run-retry-readiness-mismatch",
2218
+ "Tool provider delayed retry readiness fact does not match the scheduled retry eligibility.",
2219
+ {
2220
+ subjectId: scheduled.scheduleId,
2221
+ refs: sanitizeAdapterInputSourceRefs([
2222
+ ref("tool-provider-run-retry-scheduled", scheduled.scheduleId),
2223
+ ref("scheduled-readiness-ready", readiness.scheduleId)
2224
+ ]),
2225
+ details: {
2226
+ retryAtMs: scheduled.retryAtMs,
2227
+ readyAtMs: readiness.readyAtMs,
2228
+ nowMs: readiness.nowMs
2229
+ }
2230
+ }
2231
+ )
2232
+ );
2233
+ }
2234
+ const readyByClock = !state.usesSharedReadiness && state.nowMs !== void 0 && scheduled.retryAtMs <= state.nowMs;
2235
+ if (!readyByReadiness && !readyByClock) continue;
2236
+ if (state.nextRequestsByOutcome.has(outcomeId)) continue;
2237
+ const proposal = state.proposalsByOutcome.get(outcomeId);
2238
+ if (proposal === void 0) continue;
2239
+ const input = state.inputsById.get(proposal.adapterInputId);
2240
+ if (input === void 0) continue;
2241
+ emitRunRequest(ctx, state, input, proposal, "scheduled", readiness);
2242
+ }
2243
+ }
2244
+ function sanitizeRetryReadinessReady(raw) {
2245
+ if (!isRecord(raw) || raw.kind !== "scheduled-readiness-ready" || typeof raw.scheduleId !== "string" || raw.scheduleId.length === 0 || typeof raw.readyAtMs !== "number" || !Number.isFinite(raw.readyAtMs) || typeof raw.nowMs !== "number" || !Number.isFinite(raw.nowMs) || !Array.isArray(raw.subjectRefs) || raw.sourceRefs !== void 0 && !Array.isArray(raw.sourceRefs)) {
2246
+ return {
2247
+ ok: false,
2248
+ issue: dataIssue(
2249
+ "tool-provider-run-retry-readiness-malformed",
2250
+ "Tool provider delayed retry readiness fact must be graph-visible scheduled readiness material.",
2251
+ {
2252
+ subjectId: isRecord(raw) && typeof raw.scheduleId === "string" ? raw.scheduleId : "unknown-scheduled-readiness"
2253
+ }
2254
+ )
2255
+ };
2256
+ }
2257
+ return Object.freeze({
2258
+ ok: true,
2259
+ kind: "scheduled-readiness-ready",
2260
+ scheduleId: raw.scheduleId,
2261
+ subjectRefs: sanitizeAdapterInputSourceRefs(
2262
+ raw.subjectRefs.flatMap((entry) => {
2263
+ const sourceRef = sourceRefOrUndefined(entry);
2264
+ return sourceRef === void 0 ? [] : [sourceRef];
2265
+ })
2266
+ ),
2267
+ readyAtMs: raw.readyAtMs,
2268
+ ...typeof raw.deadlineMs === "number" && Number.isFinite(raw.deadlineMs) ? { deadlineMs: raw.deadlineMs } : {},
2269
+ nowMs: raw.nowMs,
2270
+ ...raw.sourceRefs === void 0 ? {} : {
2271
+ sourceRefs: sanitizeAdapterInputSourceRefs(
2272
+ raw.sourceRefs.flatMap((entry) => {
2273
+ const sourceRef = sourceRefOrUndefined(entry);
2274
+ return sourceRef === void 0 ? [] : [sourceRef];
2275
+ })
2276
+ )
2277
+ },
2278
+ ...isRecord(raw.metadata) ? { metadata: sanitizeProviderGraphVisibleRecord(raw.metadata) } : {}
2279
+ });
2280
+ }
2281
+ function readinessMatchesSchedule(readiness, schedule) {
2282
+ const subjectRefs = sanitizeAdapterInputSourceRefs(schedule.subjectRefs);
2283
+ const readySubjectRefs = sanitizeAdapterInputSourceRefs(readiness.subjectRefs);
2284
+ if (!sourceRefsContainAll(readySubjectRefs, subjectRefs)) return false;
2285
+ return sourceRefsContainAll(sanitizeAdapterInputSourceRefs(readiness.sourceRefs ?? []), [
2286
+ ref("scheduled-readiness", schedule.scheduleId),
2287
+ ...schedule.sourceRefs ?? []
2288
+ ]);
2289
+ }
2290
+ function sourceRefsContainAll(actual, expected) {
2291
+ const actualKeys = new Set(actual.map(sourceRefKey));
2292
+ return expected.every((sourceRef) => actualKeys.has(sourceRefKey(sourceRef)));
2293
+ }
2294
+ function sourceRefKey(sourceRef) {
2295
+ return `${sourceRef.kind}:${sourceRef.id}`;
2296
+ }
2297
+ function sourceRefOrUndefined(value) {
2298
+ if (!isRecord(value)) return void 0;
2299
+ if (typeof value.kind !== "string" || value.kind.length === 0) return void 0;
2300
+ if (typeof value.id !== "string" || value.id.length === 0) return void 0;
2301
+ return isRecord(value.metadata) ? { kind: value.kind, id: value.id, metadata: value.metadata } : { kind: value.kind, id: value.id };
2302
+ }
2303
+ function sanitizeToolProviderRunRetryPolicy(raw) {
2304
+ const metadata = sanitizeProviderGraphVisibleRecord(raw.metadata);
2305
+ return Object.freeze({
2306
+ kind: "tool-provider-run-retry-policy",
2307
+ policyId: raw.policyId,
2308
+ retryPolicy: sanitizeRetryPolicy(raw.retryPolicy),
2309
+ ...raw.runId === void 0 ? {} : { runId: raw.runId },
2310
+ ...raw.requestId === void 0 ? {} : { requestId: raw.requestId },
2311
+ ...raw.adapterInputId === void 0 ? {} : { adapterInputId: raw.adapterInputId },
2312
+ sourceRefs: sanitizeAdapterInputSourceRefs(raw.sourceRefs ?? []),
2313
+ ...metadata === void 0 ? {} : { metadata }
2314
+ });
2315
+ }
2316
+ function sanitizeRetryPolicy(policy) {
2317
+ if (!Number.isInteger(policy.maxAttempts) || policy.maxAttempts <= 0) {
2318
+ return Object.freeze({ maxAttempts: 1, backoff: { kind: "none" } });
2319
+ }
2320
+ return Object.freeze(policy);
2321
+ }
2322
+ function chooseRetryPolicy(state, input, outcome) {
2323
+ let best;
2324
+ for (const policy of state.policies.values()) {
2325
+ const score = retryPolicyScore(policy, input, outcome);
2326
+ if (score === void 0) continue;
2327
+ if (best === void 0 || score > best.score) best = { policy, score };
2328
+ }
2329
+ return best;
2330
+ }
2331
+ function retryPolicyScore(policy, input, outcome) {
2332
+ let score = 0;
2333
+ if (policy.adapterInputId !== void 0) {
2334
+ if (policy.adapterInputId !== input.adapterInputId) return void 0;
2335
+ score += 8;
2336
+ }
2337
+ if (policy.requestId !== void 0) {
2338
+ if (policy.requestId !== outcome.requestId) return void 0;
2339
+ score += 4;
2340
+ }
2341
+ if (policy.runId !== void 0) {
2342
+ if (policy.runId !== outcomeRunId(outcome)) return void 0;
2343
+ score += 2;
2344
+ }
2345
+ return score;
2346
+ }
2347
+ function retryProposal(input, outcome, choice, delayMs) {
2348
+ const fromRunId = outcomeRunId(outcome);
2349
+ const nextAttempt = outcome.attempt + 1;
2350
+ const policyRefs = retryPolicyRefs(input, choice.policy);
2351
+ const sourceRefs = retrySourceRefs(input, outcome, choice.policy);
2352
+ return Object.freeze({
2353
+ kind: "tool-provider-run-retry-proposal",
2354
+ proposalId: `${outcome.outcomeId}:retry-proposal`,
2355
+ outcomeId: outcome.outcomeId,
2356
+ fromRunId,
2357
+ fromRequestId: outcome.requestId,
2358
+ fromAttempt: outcome.attempt,
2359
+ nextAttempt,
2360
+ nextRunId: `${fromRunId}:retry-${nextAttempt}`,
2361
+ adapterInputId: input.adapterInputId,
2362
+ requestId: input.requestId,
2363
+ operationId: input.operationId,
2364
+ policyId: choice.policy.policyId,
2365
+ policyRefs,
2366
+ maxAttempts: choice.policy.retryPolicy.maxAttempts,
2367
+ nextDelayMs: delayMs,
2368
+ sourceRefs,
2369
+ metadata: sanitizeProviderGraphVisibleRecord({ policyScore: choice.score })
2370
+ });
2371
+ }
2372
+ function retryScheduled(input, outcome, proposal, retryAtMs, delayMs) {
2373
+ return Object.freeze({
2374
+ kind: "tool-provider-run-retry-scheduled",
2375
+ scheduleId: `${proposal.proposalId}:scheduled`,
2376
+ readinessScheduleId: `${proposal.proposalId}:scheduled-readiness`,
2377
+ outcomeId: outcome.outcomeId,
2378
+ proposalId: proposal.proposalId,
2379
+ fromRunId: proposal.fromRunId,
2380
+ nextRunId: proposal.nextRunId,
2381
+ nextAttempt: proposal.nextAttempt,
2382
+ retryAtMs,
2383
+ retryAfterMs: delayMs,
2384
+ sourceRefs: sanitizeAdapterInputSourceRefs([
2385
+ ref("executor-outcome", outcome.outcomeId),
2386
+ ref("tool-provider-run-retry-proposal", proposal.proposalId),
2387
+ ref("tool-provider-adapter-input", input.adapterInputId)
2388
+ ])
2389
+ });
2390
+ }
2391
+ function retryReadinessSchedule(input, outcome, proposal, scheduled) {
2392
+ return Object.freeze({
2393
+ kind: "scheduled-readiness-requested",
2394
+ scheduleId: scheduled.readinessScheduleId ?? scheduled.scheduleId,
2395
+ subjectRefs: sanitizeAdapterInputSourceRefs([
2396
+ ref("tool-provider-run-retry-proposal", proposal.proposalId),
2397
+ ref("tool-provider-run-retry-scheduled", scheduled.scheduleId),
2398
+ ref("tool-provider-adapter-input", input.adapterInputId)
2399
+ ]),
2400
+ readyAtMs: scheduled.retryAtMs,
2401
+ reason: "tool-provider-retry",
2402
+ policyRefs: proposal.policyRefs,
2403
+ sourceRefs: sanitizeAdapterInputSourceRefs([
2404
+ ref("executor-outcome", outcome.outcomeId),
2405
+ ref("tool-provider-run-retry-proposal", proposal.proposalId),
2406
+ ref("tool-provider-run-retry-scheduled", scheduled.scheduleId),
2407
+ ...scheduled.sourceRefs ?? []
2408
+ ]),
2409
+ metadata: sanitizeProviderGraphVisibleRecord({
2410
+ outcomeId: outcome.outcomeId,
2411
+ nextRunId: proposal.nextRunId,
2412
+ nextAttempt: proposal.nextAttempt,
2413
+ retryAfterMs: scheduled.retryAfterMs
2414
+ })
2415
+ });
2416
+ }
2417
+ function emitRunRequest(ctx, state, input, proposal, mode, readiness) {
2418
+ const key = `request:${proposal.outcomeId}:${proposal.nextRunId}`;
2419
+ if (state.requestKeys.has(key)) return;
2420
+ state.requestKeys.add(key);
2421
+ const request = requestToolProviderAdapterRun(input, {
2422
+ runId: proposal.nextRunId,
2423
+ attempt: proposal.nextAttempt,
2424
+ reason: "retry",
2425
+ retryOfOutcomeId: proposal.outcomeId,
2426
+ policyRefs: proposal.policyRefs,
2427
+ sourceRefs: uniqueSourceRefs([
2428
+ ...proposal.sourceRefs ?? [],
2429
+ ref("tool-provider-run-retry-proposal", proposal.proposalId),
2430
+ ...mode === "scheduled" ? [ref("tool-provider-run-retry-scheduled", `${proposal.proposalId}:scheduled`)] : [],
2431
+ ...readiness === void 0 ? [] : [
2432
+ ref("scheduled-readiness-ready", readiness.scheduleId),
2433
+ ...readiness.sourceRefs ?? []
2434
+ ]
2435
+ ]),
2436
+ metadata: {
2437
+ retryMode: mode,
2438
+ retryProposalId: proposal.proposalId,
2439
+ retryOfOutcomeId: proposal.outcomeId,
2440
+ ...readiness === void 0 ? {} : { readinessScheduleId: readiness.scheduleId }
2441
+ }
2442
+ });
2443
+ state.nextRequestsByOutcome.set(proposal.outcomeId, request);
2444
+ emitStatus2(ctx, state, statusForProposal(input, proposal, "ready"));
2445
+ emitAudit(ctx, state, "tool-provider-run-retry-run-requested", {
2446
+ subjectId: request.requestId,
2447
+ sourceRefs: request.sourceRefs,
2448
+ metadata: {
2449
+ runId: request.runId,
2450
+ adapterInputId: request.adapterInputId,
2451
+ attempt: request.attempt,
2452
+ retryOfOutcomeId: request.retryOfOutcomeId,
2453
+ retryMode: mode
2454
+ }
2455
+ });
2456
+ ctx.down([["DATA", { kind: "run-request", request }]]);
2457
+ }
2458
+ function emitProposal2(ctx, state, proposal) {
2459
+ const key = `proposal:${proposal.proposalId}`;
2460
+ if (state.proposalKeys.has(key)) return;
2461
+ state.proposalKeys.add(key);
2462
+ emitAudit(ctx, state, "tool-provider-run-retry-proposed", {
2463
+ subjectId: proposal.requestId,
2464
+ sourceRefs: proposal.sourceRefs,
2465
+ metadata: {
2466
+ proposalId: proposal.proposalId,
2467
+ outcomeId: proposal.outcomeId,
2468
+ nextAttempt: proposal.nextAttempt,
2469
+ nextDelayMs: proposal.nextDelayMs
2470
+ }
2471
+ });
2472
+ ctx.down([["DATA", { kind: "proposal", proposal }]]);
2473
+ }
2474
+ function emitScheduled(ctx, state, scheduled) {
2475
+ const key = `scheduled:${scheduled.scheduleId}`;
2476
+ if (state.scheduledKeys.has(key)) return;
2477
+ state.scheduledKeys.add(key);
2478
+ emitAudit(ctx, state, "tool-provider-run-retry-scheduled", {
2479
+ sourceRefs: scheduled.sourceRefs,
2480
+ metadata: {
2481
+ scheduleId: scheduled.scheduleId,
2482
+ outcomeId: scheduled.outcomeId,
2483
+ nextAttempt: scheduled.nextAttempt,
2484
+ retryAtMs: scheduled.retryAtMs
2485
+ }
2486
+ });
2487
+ ctx.down([["DATA", { kind: "scheduled", scheduled }]]);
2488
+ }
2489
+ function emitReadinessSchedule(ctx, state, schedule) {
2490
+ const key = `readiness-schedule:${schedule.scheduleId}`;
2491
+ if (state.readinessScheduleKeys.has(key)) return;
2492
+ state.readinessScheduleKeys.add(key);
2493
+ emitAudit(ctx, state, "tool-provider-run-retry-readiness-scheduled", {
2494
+ sourceRefs: schedule.sourceRefs,
2495
+ metadata: {
2496
+ scheduleId: schedule.scheduleId,
2497
+ readyAtMs: schedule.readyAtMs
2498
+ }
2499
+ });
2500
+ ctx.down([["DATA", { kind: "readiness-schedule", schedule }]]);
2501
+ }
2502
+ function emitStatus2(ctx, state, status) {
2503
+ const key = `${status.outcomeId}:${status.state}:${status.nextAttempt ?? ""}:${status.nextRetryAtMs ?? ""}:${(status.issueCodes ?? []).join(",")}`;
2504
+ if (state.statusKeys.has(key)) return;
2505
+ state.statusKeys.add(key);
2506
+ state.statusByOutcome.set(status.outcomeId, status);
2507
+ ctx.down([["DATA", { kind: "status", status }]]);
2508
+ }
2509
+ function emitIssue2(ctx, state, issue) {
2510
+ const sanitized = sanitizeAdapterInputIssue(issue);
2511
+ const key = `${sanitized.code}:${sanitized.subjectId ?? ""}:${JSON.stringify(sanitized.details ?? {})}`;
2512
+ if (state.issueKeys.has(key)) return;
2513
+ state.issueKeys.add(key);
2514
+ ctx.down([["DATA", { kind: "issue", issue: sanitized }]]);
2515
+ }
2516
+ function emitAudit(ctx, state, kind, opts = {}) {
2517
+ state.auditSeq += 1;
2518
+ const metadata = sanitizeProviderGraphVisibleRecord(opts.metadata);
2519
+ ctx.down([
2520
+ [
2521
+ "DATA",
2522
+ {
2523
+ kind: "audit",
2524
+ audit: Object.freeze({
2525
+ id: `tool-provider-run-retry-audit-${state.auditSeq}`,
2526
+ kind,
2527
+ ...opts.subjectId === void 0 ? {} : { subjectId: opts.subjectId },
2528
+ ...opts.sourceRefs === void 0 ? {} : { sourceRefs: sanitizeAdapterInputSourceRefs(opts.sourceRefs) },
2529
+ ...metadata === void 0 ? {} : { metadata }
2530
+ })
2531
+ }
2532
+ ]
2533
+ ]);
2534
+ }
2535
+ function statusForOutcome(outcome, input, state, opts = {}) {
2536
+ const proposal = opts.proposal;
2537
+ const nextAttempt = proposal?.nextAttempt ?? (opts.choice === void 0 ? void 0 : outcome.attempt + 1);
2538
+ return Object.freeze({
2539
+ kind: "tool-provider-run-retry-status",
2540
+ statusId: `${outcome.outcomeId}:retry-status:${state}`,
2541
+ outcomeId: outcome.outcomeId,
2542
+ proposalId: proposal?.proposalId ?? `${outcome.outcomeId}:retry-proposal`,
2543
+ fromRunId: outcomeRunId(outcome),
2544
+ adapterInputId: input.adapterInputId,
2545
+ requestId: input.requestId,
2546
+ operationId: input.operationId,
2547
+ ...proposal?.nextRunId === void 0 ? {} : { nextRunId: proposal.nextRunId },
2548
+ ...nextAttempt === void 0 ? {} : { nextAttempt },
2549
+ ...opts.retryAtMs === void 0 ? {} : { nextRetryAtMs: opts.retryAtMs },
2550
+ state,
2551
+ sourceRefs: retrySourceRefs(input, outcome, opts.choice?.policy),
2552
+ ...opts.issues === void 0 || opts.issues.length === 0 ? {} : { issueCodes: Object.freeze(opts.issues.map((issue) => issue.code)) },
2553
+ ...optionalMetadata({
2554
+ ...opts.delayMs === void 0 ? {} : { delayMs: opts.delayMs },
2555
+ ...opts.choice === void 0 ? {} : { maxAttempts: opts.choice.policy.retryPolicy.maxAttempts }
2556
+ })
2557
+ });
2558
+ }
2559
+ function statusForProposal(input, proposal, state) {
2560
+ return Object.freeze({
2561
+ kind: "tool-provider-run-retry-status",
2562
+ statusId: `${proposal.outcomeId}:retry-status:${state}`,
2563
+ outcomeId: proposal.outcomeId,
2564
+ proposalId: proposal.proposalId,
2565
+ fromRunId: proposal.fromRunId,
2566
+ adapterInputId: input.adapterInputId,
2567
+ requestId: input.requestId,
2568
+ operationId: input.operationId,
2569
+ nextRunId: proposal.nextRunId,
2570
+ nextAttempt: proposal.nextAttempt,
2571
+ state,
2572
+ sourceRefs: proposal.sourceRefs,
2573
+ ...optionalMetadata({ maxAttempts: proposal.maxAttempts })
2574
+ });
2575
+ }
2576
+ function statusForMissingInput(outcome, state, issues) {
2577
+ return Object.freeze({
2578
+ kind: "tool-provider-run-retry-status",
2579
+ statusId: `${outcome.outcomeId}:retry-status:${state}`,
2580
+ outcomeId: outcome.outcomeId,
2581
+ proposalId: `${outcome.outcomeId}:retry-proposal`,
2582
+ fromRunId: outcomeRunId(outcome),
2583
+ adapterInputId: outcome.inputId ?? outcome.requestId,
2584
+ requestId: outcome.requestId,
2585
+ operationId: outcome.operationId,
2586
+ state,
2587
+ sourceRefs: [ref("executor-outcome", outcome.outcomeId)],
2588
+ issueCodes: Object.freeze(issues.map((issue) => issue.code))
2589
+ });
2590
+ }
2591
+ function isRetryableOutcome(outcome) {
2592
+ return (outcome.kind === "failure" || outcome.kind === "timeout") && outcome.retryable === true;
2593
+ }
2594
+ function retryPolicyRefs(input, policy) {
2595
+ return sanitizeAdapterInputSourceRefs([
2596
+ ref("tool-provider-run-retry-policy", policy.policyId),
2597
+ ...policy.sourceRefs ?? [],
2598
+ ...input.policyRefs ?? []
2599
+ ]);
2600
+ }
2601
+ function retrySourceRefs(input, outcome, policy) {
2602
+ return sanitizeAdapterInputSourceRefs([
2603
+ ref("executor-outcome", outcome.outcomeId),
2604
+ ref("tool-provider-adapter-input", input.adapterInputId),
2605
+ ...outcome.evidenceRefs ?? [],
2606
+ ...input.sourceRefs ?? [],
2607
+ ...policy === void 0 ? [] : retryPolicyRefs(input, policy)
2608
+ ]);
2609
+ }
2610
+ function outcomeRunId(outcome) {
2611
+ const runId = isRecord(outcome.metadata) ? outcome.metadata.runId : void 0;
2612
+ if (typeof runId === "string" && runId.length > 0) return runId;
2613
+ return `${outcome.requestId}:attempt-${outcome.attempt}`;
2614
+ }
2615
+ function optionalMetadata(value) {
2616
+ const metadata = sanitizeProviderGraphVisibleRecord(value);
2617
+ return metadata === void 0 ? {} : { metadata };
2618
+ }
2619
+ function buildRetryViews(state) {
2620
+ return Object.freeze({
2621
+ proposalsByOutcome: new Map(state.proposalsByOutcome),
2622
+ scheduledByOutcome: new Map(state.scheduledByOutcome),
2623
+ readinessSchedulesByOutcome: new Map(state.readinessSchedulesByOutcome),
2624
+ readinessBySchedule: new Map(state.readinessBySchedule),
2625
+ nextRunRequestsByOutcome: new Map(state.nextRequestsByOutcome),
2626
+ statusByOutcome: new Map(state.statusByOutcome)
2627
+ });
2628
+ }
2629
+
2630
+ // src/orchestration/agent-runtime-types-core.ts
2631
+ function effectRun(opts) {
2632
+ return {
2633
+ kind: "effect-run",
2634
+ effectRunId: opts.effectRunId,
2635
+ agentRunId: opts.agentRunId,
2636
+ subjectRefs: opts.subjectRefs,
2637
+ goal: opts.goal,
2638
+ sourceRefs: opts.sourceRefs,
2639
+ policyRefs: opts.policyRefs,
2640
+ limits: opts.limits,
2641
+ createdBy: opts.createdBy,
2642
+ createdAtMs: opts.createdAtMs,
2643
+ metadata: opts.metadata
2644
+ };
2645
+ }
2646
+
2647
+ // src/orchestration/process-utils.ts
2648
+ function cloneProcessState(state) {
2649
+ if (typeof state !== "object" || state === null) return { ok: true, value: state };
2650
+ try {
2651
+ if (typeof globalThis.structuredClone === "function") {
2652
+ return { ok: true, value: globalThis.structuredClone(state) };
2653
+ }
2654
+ return { ok: true, value: JSON.parse(JSON.stringify(state)) };
2655
+ } catch (error) {
2656
+ return {
2657
+ ok: false,
2658
+ message: `processBundle: state must be cloneable before reducer execution (${errorMessage(error)})`
2659
+ };
2660
+ }
2661
+ }
2662
+ function readTimestampMs(now) {
2663
+ try {
2664
+ const timestampMs = now();
2665
+ if (!Number.isFinite(timestampMs)) return "processBundle: now() must return a finite number";
2666
+ return timestampMs;
2667
+ } catch (error) {
2668
+ return errorMessage(error);
2669
+ }
2670
+ }
2671
+ function rethrowGraphRuntimeInvariant(error) {
2672
+ const message = errorMessage(error);
2673
+ if (message.includes("R-reentrancy") || message.includes("R-rewire") || message.includes("R-graph-domain") || message.includes("D37") || message.includes("D22") || message.includes("different graph") || message.includes("cross-graph") || message.includes("wire bridge") || message.includes("mid-fn topology mutation") || message.includes("reentrant dep mutation") || message.includes("feedback cycle")) {
2674
+ throw error;
2675
+ }
2676
+ }
2677
+ function isObjectRecord(value) {
2678
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2679
+ }
2680
+ function errorMessage(error) {
2681
+ return error instanceof Error ? error.message : String(error);
2682
+ }
2683
+
2684
+ // src/orchestration/process.ts
2685
+ var processCommandSources = /* @__PURE__ */ new WeakMap();
2686
+ function processBundle(graph, opts) {
2687
+ if (typeof opts.reduce !== "function") {
2688
+ throw new TypeError("processBundle: reduce must be a function");
2689
+ }
2690
+ if (opts.initialState === void 0) {
2691
+ throw new TypeError("processBundle: initialState must not be undefined");
2692
+ }
2693
+ const name = opts.name ?? "process";
2694
+ const now = opts.now ?? Date.now;
2695
+ const topology = graph.topologyGroup({ name: `${name}.process` });
2696
+ const command = topology.node([], null, {
2697
+ name: `${name}/command`,
2698
+ factory: "processCommand",
2699
+ completeWhenDepsComplete: false,
2700
+ errorWhenDepsError: false
2701
+ });
2702
+ const runtime = topology.node(
2703
+ [command],
2704
+ (ctx) => {
2705
+ let state2 = ctx.state.get() ?? {
2706
+ eventSeq: 0,
2707
+ effectSeq: 0,
2708
+ commandCount: 0,
2709
+ errorCount: 0,
2710
+ auditSeq: 0,
2711
+ seenEventIds: [],
2712
+ seenEffectIds: [],
2713
+ state: opts.initialState
2714
+ };
2715
+ ctx.state.persist(true);
2716
+ for (const raw of depBatch(ctx, 0) ?? []) {
2717
+ state2 = reduceProcessCommandFact(
2718
+ raw,
2719
+ state2,
2720
+ opts.reduce,
2721
+ now,
2722
+ (fact) => ctx.down([["DATA", fact]])
2723
+ );
2724
+ ctx.state.set(state2);
2725
+ }
2726
+ },
2727
+ {
2728
+ name: `${name}/runtime`,
2729
+ factory: "processRuntime",
2730
+ meta: { process: "facts-plus-reducer", d: "D136" },
2731
+ completeWhenDepsComplete: false,
2732
+ errorWhenDepsError: false
2733
+ }
2734
+ );
2735
+ const events = processProjection(
2736
+ topology,
2737
+ runtime,
2738
+ `${name}/events`,
2739
+ "processEvents",
2740
+ (fact) => fact.kind === "event" ? fact.event : void 0
2741
+ );
2742
+ const state = processProjection(
2743
+ topology,
2744
+ runtime,
2745
+ `${name}/state`,
2746
+ "processState",
2747
+ (fact) => fact.kind === "state" ? fact.state : void 0
2748
+ );
2749
+ const audit = processProjection(
2750
+ topology,
2751
+ runtime,
2752
+ `${name}/audit`,
2753
+ "processAudit",
2754
+ (fact) => fact.kind === "audit" ? fact.audit : void 0
2755
+ );
2756
+ const effectRequests = processProjection(
2757
+ topology,
2758
+ runtime,
2759
+ `${name}/effectRequests`,
2760
+ "processEffectRequests",
2761
+ (fact) => fact.kind === "effect-request" ? fact.effect : void 0
2762
+ );
2763
+ const status = processProjection(
2764
+ topology,
2765
+ runtime,
2766
+ `${name}/status`,
2767
+ "processStatus",
2768
+ (fact) => fact.kind === "status" ? fact.status : void 0
2769
+ );
2770
+ const errors = processProjection(
2771
+ topology,
2772
+ runtime,
2773
+ `${name}/errors`,
2774
+ "processErrors",
2775
+ (fact) => fact.kind === "error" ? fact.error : void 0
2776
+ );
2777
+ const cursor = processProjection(
2778
+ topology,
2779
+ runtime,
2780
+ `${name}/cursor`,
2781
+ "processCursor",
2782
+ (fact) => fact.kind === "cursor" ? fact.cursor : void 0
2783
+ );
2784
+ const retainProcessNodes = () => [
2785
+ graph.retain(runtime, { reason: `${name}.process.runtime` }),
2786
+ graph.retain(events, { reason: `${name}.process.events` }),
2787
+ graph.retain(state, { reason: `${name}.process.state` }),
2788
+ graph.retain(audit, { reason: `${name}.process.audit` }),
2789
+ graph.retain(effectRequests, { reason: `${name}.process.effectRequests` }),
2790
+ graph.retain(status, { reason: `${name}.process.status` }),
2791
+ graph.retain(errors, { reason: `${name}.process.errors` }),
2792
+ graph.retain(cursor, { reason: `${name}.process.cursor` })
2793
+ ];
2794
+ let releaseRetains = retainProcessNodes();
2795
+ let released = false;
2796
+ const bundle = {
2797
+ command,
2798
+ events,
2799
+ state,
2800
+ audit,
2801
+ effectRequests,
2802
+ status,
2803
+ errors,
2804
+ cursor,
2805
+ dispatch(next) {
2806
+ command.down([["DATA", next]]);
2807
+ return next;
2808
+ },
2809
+ release() {
2810
+ if (released) return;
2811
+ const activeRetains = releaseRetains;
2812
+ releaseRetains = [];
2813
+ for (const releaseRetain of activeRetains) releaseRetain();
2814
+ try {
2815
+ topology.release({ reason: `${name}.process.release` });
2816
+ released = true;
2817
+ processCommandSources.delete(
2818
+ bundle
2819
+ );
2820
+ } catch (error) {
2821
+ releaseRetains = retainProcessNodes();
2822
+ throw error;
2823
+ }
2824
+ }
2825
+ };
2826
+ processCommandSources.set(
2827
+ bundle,
2828
+ { sources: [] }
2829
+ );
2830
+ return bundle;
2831
+ }
2832
+ function processEffectRunner(graph, process, opts) {
2833
+ if (opts.outcomes.length === 0) {
2834
+ throw new RangeError("processEffectRunner: outcomes must contain at least one node");
2835
+ }
2836
+ const name = opts.name ?? "processEffectRunner";
2837
+ const topology = graph.topologyGroup({ name: `${name}.effectRunner` });
2838
+ const requests = topology.node(
2839
+ [process.effectRequests],
2840
+ (ctx) => {
2841
+ for (const request of depBatch(ctx, 0) ?? []) {
2842
+ ctx.down([["DATA", request]]);
2843
+ }
2844
+ },
2845
+ {
2846
+ name: `${name}/requests`,
2847
+ factory: "processEffectRunnerRequests",
2848
+ partial: true,
2849
+ completeWhenDepsComplete: false,
2850
+ errorWhenDepsError: false
2851
+ }
2852
+ );
2853
+ const runtime = topology.node(
2854
+ [...opts.outcomes],
2855
+ (ctx) => {
2856
+ for (let i = 0; i < opts.outcomes.length; i += 1) {
2857
+ for (const raw of depBatch(ctx, i) ?? []) {
2858
+ const parsed = parseProcessEffectOutcome(raw);
2859
+ if (typeof parsed === "string") {
2860
+ const error = {
2861
+ code: "malformed-outcome",
2862
+ message: parsed,
2863
+ outcome: raw
2864
+ };
2865
+ ctx.down([["DATA", { kind: "error", error }]]);
2866
+ continue;
2867
+ }
2868
+ const outcome = parsed;
2869
+ const command = processEffectOutcomeCommand(outcome);
2870
+ ctx.down([["DATA", { kind: "outcome", outcome }]]);
2871
+ ctx.down([["DATA", { kind: "command", command }]]);
2872
+ }
2873
+ }
2874
+ },
2875
+ {
2876
+ name: `${name}/runtime`,
2877
+ factory: "processEffectRunner",
2878
+ meta: { process: "effect-runner", d: "D156" },
2879
+ partial: true,
2880
+ completeWhenDepsComplete: false,
2881
+ errorWhenDepsError: false
2882
+ }
2883
+ );
2884
+ const outcomes = processEffectRunnerProjection(
2885
+ topology,
2886
+ runtime,
2887
+ `${name}/outcomes`,
2888
+ "processEffectRunnerOutcomes",
2889
+ (fact) => fact.kind === "outcome" ? fact.outcome : void 0
2890
+ );
2891
+ const commands = processEffectRunnerProjection(
2892
+ topology,
2893
+ runtime,
2894
+ `${name}/commands`,
2895
+ "processEffectRunnerCommands",
2896
+ (fact) => fact.kind === "command" ? fact.command : void 0
2897
+ );
2898
+ const errors = processEffectRunnerProjection(
2899
+ topology,
2900
+ runtime,
2901
+ `${name}/errors`,
2902
+ "processEffectRunnerErrors",
2903
+ (fact) => fact.kind === "error" ? fact.error : void 0
2904
+ );
2905
+ const status = topology.node(
2906
+ [requests, runtime],
2907
+ (ctx) => {
2908
+ let state = ctx.state.get() ?? { requested: 0, commanded: 0, rejected: 0 };
2909
+ for (const request of depBatch(ctx, 0) ?? []) {
2910
+ state = { ...state, requested: state.requested + 1 };
2911
+ const typedRequest = request;
2912
+ ctx.down([
2913
+ [
2914
+ "DATA",
2915
+ {
2916
+ state: "requested",
2917
+ effectId: typedRequest.id,
2918
+ effectType: typedRequest.type,
2919
+ requested: state.requested,
2920
+ commanded: state.commanded,
2921
+ rejected: state.rejected
2922
+ }
2923
+ ]
2924
+ ]);
2925
+ }
2926
+ for (const fact of depBatch(ctx, 1) ?? []) {
2927
+ const typedFact = fact;
2928
+ if (typedFact.kind === "command") {
2929
+ state = { ...state, commanded: state.commanded + 1 };
2930
+ ctx.down([
2931
+ [
2932
+ "DATA",
2933
+ {
2934
+ state: "commanded",
2935
+ effectId: typedFact.command.payload.effectId,
2936
+ effectType: typedFact.command.payload.effectType,
2937
+ commandId: typedFact.command.id,
2938
+ commandType: typedFact.command.type,
2939
+ requested: state.requested,
2940
+ commanded: state.commanded,
2941
+ rejected: state.rejected
2942
+ }
2943
+ ]
2944
+ ]);
2945
+ }
2946
+ if (typedFact.kind === "error") {
2947
+ state = { ...state, rejected: state.rejected + 1 };
2948
+ ctx.down([
2949
+ [
2950
+ "DATA",
2951
+ {
2952
+ state: "rejected",
2953
+ effectId: typedFact.error.effectId,
2954
+ effectType: typedFact.error.effectType,
2955
+ requested: state.requested,
2956
+ commanded: state.commanded,
2957
+ rejected: state.rejected
2958
+ }
2959
+ ]
2960
+ ]);
2961
+ }
2962
+ }
2963
+ ctx.state.set(state);
2964
+ },
2965
+ {
2966
+ name: `${name}/status`,
2967
+ factory: "processEffectRunnerStatus",
2968
+ partial: true,
2969
+ completeWhenDepsComplete: false,
2970
+ errorWhenDepsError: false
2971
+ }
2972
+ );
2973
+ const retainRunnerNodes = () => [
2974
+ graph.retain(requests, { reason: `${name}.effectRunner.requests` }),
2975
+ graph.retain(outcomes, { reason: `${name}.effectRunner.outcomes` }),
2976
+ graph.retain(commands, { reason: `${name}.effectRunner.commands` }),
2977
+ graph.retain(status, { reason: `${name}.effectRunner.status` }),
2978
+ graph.retain(errors, { reason: `${name}.effectRunner.errors` })
2979
+ ];
2980
+ let releaseRetains = retainRunnerNodes();
2981
+ try {
2982
+ attachProcessCommandSource(process, commands);
2983
+ } catch (error) {
2984
+ for (const releaseRetain of releaseRetains) releaseRetain();
2985
+ releaseRetains = [];
2986
+ topology.release({ reason: `${name}.effectRunner.failedAttach` });
2987
+ throw error;
2988
+ }
2989
+ let released = false;
2990
+ return {
2991
+ requests,
2992
+ outcomes,
2993
+ commands,
2994
+ status,
2995
+ errors,
2996
+ release() {
2997
+ if (released) return;
2998
+ const activeRetains = releaseRetains;
2999
+ releaseRetains = [];
3000
+ for (const releaseRetain of activeRetains) releaseRetain();
3001
+ detachProcessCommandSource(process, commands);
3002
+ try {
3003
+ topology.release({ reason: `${name}.effectRunner.release` });
3004
+ released = true;
3005
+ } catch (error) {
3006
+ attachProcessCommandSource(process, commands);
3007
+ releaseRetains = retainRunnerNodes();
3008
+ throw error;
3009
+ }
3010
+ }
3011
+ };
3012
+ }
3013
+ function processEffectRunnerProjection(topology, runtime, name, factory, pick) {
3014
+ return topology.node(
3015
+ [runtime],
3016
+ (ctx) => {
3017
+ for (const fact of depBatch(ctx, 0) ?? []) {
3018
+ const value = pick(fact);
3019
+ if (value !== void 0) ctx.down([["DATA", value]]);
3020
+ }
3021
+ },
3022
+ {
3023
+ name,
3024
+ factory,
3025
+ partial: true,
3026
+ completeWhenDepsComplete: false,
3027
+ errorWhenDepsError: false
3028
+ }
3029
+ );
3030
+ }
3031
+ function parseProcessEffectOutcome(raw) {
3032
+ if (!isObjectRecord(raw)) return "processEffectRunner: outcome must be an object";
3033
+ if (typeof raw.kind !== "string") {
3034
+ return "processEffectRunner: outcome kind must be a string";
3035
+ }
3036
+ if (raw.kind !== "result" && raw.kind !== "failure" && raw.kind !== "cancel" && raw.kind !== "timeout") {
3037
+ return "processEffectRunner: outcome kind must be result, failure, cancel, or timeout";
3038
+ }
3039
+ if (typeof raw.effectId !== "string" || raw.effectId.length === 0) {
3040
+ return "processEffectRunner: outcome effectId must be a non-empty string";
3041
+ }
3042
+ if (typeof raw.effectType !== "string" || raw.effectType.length === 0) {
3043
+ return "processEffectRunner: outcome effectType must be a non-empty string";
3044
+ }
3045
+ if ("commandId" in raw && raw.commandId !== void 0) {
3046
+ if (typeof raw.commandId !== "string" || raw.commandId.length === 0) {
3047
+ return "processEffectRunner: outcome commandId must be a non-empty string";
3048
+ }
3049
+ }
3050
+ for (const key of ["processId", "correlationId", "causationId"]) {
3051
+ if (key in raw && raw[key] !== void 0 && typeof raw[key] !== "string") {
3052
+ return `processEffectRunner: outcome ${key} must be a string`;
3053
+ }
3054
+ }
3055
+ if ("metadata" in raw && raw.metadata !== void 0 && !isObjectRecord(raw.metadata)) {
3056
+ return "processEffectRunner: outcome metadata must be a plain object";
3057
+ }
3058
+ if (raw.kind === "result" && !("value" in raw)) {
3059
+ return "processEffectRunner: result outcome must carry value";
3060
+ }
3061
+ if ((raw.kind === "failure" || raw.kind === "timeout") && !("error" in raw)) {
3062
+ return `processEffectRunner: ${raw.kind} outcome must carry error`;
3063
+ }
3064
+ if (raw.kind === "cancel" && "reason" in raw && raw.reason !== void 0 && typeof raw.reason !== "string") {
3065
+ return "processEffectRunner: cancel outcome reason must be a string";
3066
+ }
3067
+ return raw;
3068
+ }
3069
+ function processEffectOutcomeCommand(outcome) {
3070
+ const commandType = processEffectCommandType(outcome.kind);
3071
+ return {
3072
+ id: outcome.commandId ?? `${outcome.effectId}:${commandType}`,
3073
+ type: commandType,
3074
+ payload: processEffectCommandPayload(outcome),
3075
+ processId: outcome.processId,
3076
+ correlationId: outcome.correlationId,
3077
+ causationId: outcome.causationId,
3078
+ metadata: outcome.metadata
3079
+ };
3080
+ }
3081
+ function processEffectCommandType(kind) {
3082
+ switch (kind) {
3083
+ case "result":
3084
+ return "effect.result";
3085
+ case "failure":
3086
+ return "effect.failure";
3087
+ case "cancel":
3088
+ return "effect.cancel";
3089
+ case "timeout":
3090
+ return "effect.timeout";
3091
+ }
3092
+ }
3093
+ function processEffectCommandPayload(outcome) {
3094
+ const base = {
3095
+ effectId: outcome.effectId,
3096
+ effectType: outcome.effectType,
3097
+ processId: outcome.processId,
3098
+ correlationId: outcome.correlationId,
3099
+ causationId: outcome.causationId,
3100
+ metadata: outcome.metadata
3101
+ };
3102
+ switch (outcome.kind) {
3103
+ case "result":
3104
+ return { ...base, kind: "result", value: outcome.value };
3105
+ case "failure":
3106
+ return { ...base, kind: "failure", error: outcome.error };
3107
+ case "cancel":
3108
+ return { ...base, kind: "cancel", reason: outcome.reason };
3109
+ case "timeout":
3110
+ return { ...base, kind: "timeout", error: outcome.error };
3111
+ }
3112
+ }
3113
+ function attachProcessCommandSource(process, source) {
3114
+ const attached = processCommandSources.get(process);
3115
+ if (attached === void 0) {
3116
+ throw new Error("processEffectRunner: process command source registry missing");
3117
+ }
3118
+ const sources = attached.sources;
3119
+ const previousSources = [...sources];
3120
+ if (!sources.includes(source)) sources.push(source);
3121
+ try {
3122
+ process.command.replaceDeps([...sources], processCommandSourceFn(sources.length));
3123
+ } catch (error) {
3124
+ sources.splice(0, sources.length, ...previousSources);
3125
+ process.command.replaceDeps(
3126
+ [...previousSources],
3127
+ processCommandSourceFn(previousSources.length)
3128
+ );
3129
+ throw error;
3130
+ }
3131
+ }
3132
+ function detachProcessCommandSource(process, source) {
3133
+ const attached = processCommandSources.get(process);
3134
+ if (attached === void 0) {
3135
+ throw new Error("processEffectRunner: process command source registry missing");
3136
+ }
3137
+ const sources = attached.sources;
3138
+ if (!sources.includes(source)) return;
3139
+ const previousSources = [...sources];
3140
+ const nextSources = sources.filter((candidate) => candidate !== source);
3141
+ sources.splice(0, sources.length, ...nextSources);
3142
+ try {
3143
+ process.command.replaceDeps([...nextSources], processCommandSourceFn(nextSources.length));
3144
+ } catch (error) {
3145
+ sources.splice(0, sources.length, ...previousSources);
3146
+ process.command.replaceDeps(
3147
+ [...previousSources],
3148
+ processCommandSourceFn(previousSources.length)
3149
+ );
3150
+ throw error;
3151
+ }
3152
+ }
3153
+ function processCommandSourceFn(sourceCount) {
3154
+ return (ctx) => {
3155
+ for (let i = 0; i < sourceCount; i += 1) {
3156
+ for (const command of depBatch(ctx, i) ?? []) {
3157
+ ctx.down([["DATA", command]]);
3158
+ }
3159
+ }
3160
+ };
3161
+ }
3162
+ function processRuntimeDraft(state) {
3163
+ return {
3164
+ eventSeq: state.eventSeq,
3165
+ effectSeq: state.effectSeq,
3166
+ commandCount: state.commandCount,
3167
+ errorCount: state.errorCount,
3168
+ auditSeq: state.auditSeq,
3169
+ seenEventIds: [...state.seenEventIds],
3170
+ seenEffectIds: [...state.seenEffectIds],
3171
+ state: state.state
3172
+ };
3173
+ }
3174
+ function reduceProcessCommandFact(raw, state, reduce, now, emit) {
3175
+ const draft = processRuntimeDraft(state);
3176
+ draft.commandCount += 1;
3177
+ const parsed = parseProcessCommand(raw);
3178
+ if (typeof parsed === "string") {
3179
+ emitProcessFailure(draft, emit, raw, void 0, "malformed-command", parsed);
3180
+ return draft;
3181
+ }
3182
+ const command = parsed;
3183
+ let reduction;
3184
+ const reducerState = cloneProcessState(state.state);
3185
+ if (!reducerState.ok) {
3186
+ emitProcessFailure(draft, emit, command, command, "malformed-state", reducerState.message);
3187
+ return draft;
3188
+ }
3189
+ try {
3190
+ reduction = reduce(command, reducerState.value);
3191
+ } catch (error) {
3192
+ rethrowGraphRuntimeInvariant(error);
3193
+ emitProcessFailure(draft, emit, command, command, "reducer-threw", errorMessage(error));
3194
+ return draft;
3195
+ }
3196
+ if (!isObjectRecord(reduction) || !("state" in reduction)) {
3197
+ emitProcessFailure(
3198
+ draft,
3199
+ emit,
3200
+ command,
3201
+ command,
3202
+ "malformed-state",
3203
+ "processBundle: reducer must return { state, events?, effects? }"
3204
+ );
3205
+ return draft;
3206
+ }
3207
+ if (reduction.state === void 0) {
3208
+ emitProcessFailure(
3209
+ draft,
3210
+ emit,
3211
+ command,
3212
+ command,
3213
+ "malformed-state",
3214
+ "processBundle: reducer state must not be undefined"
3215
+ );
3216
+ return draft;
3217
+ }
3218
+ const privateState = cloneProcessState(reduction.state);
3219
+ if (!privateState.ok) {
3220
+ emitProcessFailure(draft, emit, command, command, "malformed-state", privateState.message);
3221
+ return draft;
3222
+ }
3223
+ const visibleState = cloneProcessState(privateState.value);
3224
+ if (!visibleState.ok) {
3225
+ emitProcessFailure(draft, emit, command, command, "malformed-state", visibleState.message);
3226
+ return draft;
3227
+ }
3228
+ const preparedEvents = prepareProcessEvents(command, draft, reduction.events ?? []);
3229
+ if (typeof preparedEvents === "string") {
3230
+ emitProcessFailure(draft, emit, command, command, "malformed-event", preparedEvents);
3231
+ return draft;
3232
+ }
3233
+ const preparedEffects = prepareProcessEffects(command, draft, reduction.effects ?? []);
3234
+ if (typeof preparedEffects === "string") {
3235
+ emitProcessFailure(draft, emit, command, command, "malformed-effect", preparedEffects);
3236
+ return draft;
3237
+ }
3238
+ const timestampMs = readTimestampMs(now);
3239
+ if (typeof timestampMs === "string") {
3240
+ emitProcessFailure(draft, emit, command, command, "clock-threw", timestampMs);
3241
+ return draft;
3242
+ }
3243
+ draft.state = privateState.value;
3244
+ emit({ kind: "state", state: visibleState.value, cursor: processCursorOf(draft) });
3245
+ const events = [];
3246
+ for (const eventDraft of preparedEvents) {
3247
+ draft.eventSeq += 1;
3248
+ draft.seenEventIds.push(eventDraft.id);
3249
+ const event = {
3250
+ id: eventDraft.id,
3251
+ type: eventDraft.type,
3252
+ seq: draft.eventSeq,
3253
+ cursor: draft.eventSeq,
3254
+ commandId: command.id,
3255
+ commandType: command.type,
3256
+ payload: eventDraft.payload,
3257
+ timestampMs,
3258
+ ...eventDraft.processId === void 0 ? {} : { processId: eventDraft.processId },
3259
+ ...eventDraft.correlationId === void 0 ? {} : { correlationId: eventDraft.correlationId },
3260
+ ...eventDraft.causationId === void 0 ? {} : { causationId: eventDraft.causationId },
3261
+ ...eventDraft.metadata === void 0 ? {} : { metadata: eventDraft.metadata }
3262
+ };
3263
+ events.push(event);
3264
+ emit({ kind: "event", event });
3265
+ }
3266
+ const effects = [];
3267
+ for (const effectDraft of preparedEffects) {
3268
+ draft.effectSeq += 1;
3269
+ draft.seenEffectIds.push(effectDraft.id);
3270
+ const effect = {
3271
+ id: effectDraft.id,
3272
+ type: effectDraft.type,
3273
+ seq: draft.effectSeq,
3274
+ cursor: draft.effectSeq,
3275
+ commandId: command.id,
3276
+ commandType: command.type,
3277
+ payload: effectDraft.payload,
3278
+ timestampMs,
3279
+ ...effectDraft.processId === void 0 ? {} : { processId: effectDraft.processId },
3280
+ ...effectDraft.correlationId === void 0 ? {} : { correlationId: effectDraft.correlationId },
3281
+ ...effectDraft.causationId === void 0 ? {} : { causationId: effectDraft.causationId },
3282
+ ...effectDraft.metadata === void 0 ? {} : { metadata: effectDraft.metadata }
3283
+ };
3284
+ effects.push(effect);
3285
+ emit({ kind: "effect-request", effect });
3286
+ }
3287
+ emitProcessStatus(draft, emit, command, "accepted", events.length, effects.length);
3288
+ emitProcessAudit(draft, emit, command, "success", events, effects, void 0, void 0);
3289
+ emit({ kind: "cursor", cursor: processCursorOf(draft) });
3290
+ return draft;
3291
+ }
3292
+ function processProjection(graph, runtime, name, factory, select) {
3293
+ return graph.node(
3294
+ [runtime],
3295
+ (ctx) => {
3296
+ for (const raw of depBatch(ctx, 0) ?? []) {
3297
+ const selected = select(raw);
3298
+ if (selected !== void 0) ctx.down([["DATA", selected]]);
3299
+ }
3300
+ },
3301
+ { name, factory, completeWhenDepsComplete: false, errorWhenDepsError: false }
3302
+ );
3303
+ }
3304
+ function parseProcessCommand(value) {
3305
+ if (!isObjectRecord(value)) return "processBundle: command fact must be an object";
3306
+ if (typeof value.id !== "string" || value.id.length === 0) {
3307
+ return "processBundle: command id must be a non-empty string";
3308
+ }
3309
+ if (typeof value.type !== "string" || value.type.length === 0) {
3310
+ return "processBundle: command type must be a non-empty string";
3311
+ }
3312
+ return {
3313
+ id: value.id,
3314
+ type: value.type,
3315
+ payload: value.payload,
3316
+ ...typeof value.processId === "string" ? { processId: value.processId } : {},
3317
+ ...typeof value.correlationId === "string" ? { correlationId: value.correlationId } : {},
3318
+ ...typeof value.causationId === "string" ? { causationId: value.causationId } : {},
3319
+ ...isObjectRecord(value.metadata) ? { metadata: value.metadata } : {}
3320
+ };
3321
+ }
3322
+ function prepareProcessEvents(command, state, drafts) {
3323
+ if (!Array.isArray(drafts)) return "processBundle: events must be an array";
3324
+ const seen = /* @__PURE__ */ new Set();
3325
+ const out = [];
3326
+ for (let i = 0; i < drafts.length; i += 1) {
3327
+ const draft = drafts[i];
3328
+ if (!isObjectRecord(draft) || typeof draft.type !== "string" || draft.type.length === 0) {
3329
+ return "processBundle: event draft must have a non-empty type";
3330
+ }
3331
+ const id = typeof draft.id === "string" && draft.id.length > 0 ? draft.id : `${command.id}:event:${state.eventSeq + i + 1}`;
3332
+ if (seen.has(id)) return `processBundle: duplicate event '${id}'`;
3333
+ if (state.seenEventIds.includes(id)) return `processBundle: duplicate event '${id}'`;
3334
+ seen.add(id);
3335
+ out.push({
3336
+ id,
3337
+ type: draft.type,
3338
+ payload: draft.payload,
3339
+ ...typeof draft.processId === "string" ? { processId: draft.processId } : {},
3340
+ ...typeof draft.correlationId === "string" ? { correlationId: draft.correlationId } : {},
3341
+ ...typeof draft.causationId === "string" ? { causationId: draft.causationId } : {},
3342
+ ...isObjectRecord(draft.metadata) ? { metadata: draft.metadata } : {}
3343
+ });
3344
+ }
3345
+ return out;
3346
+ }
3347
+ function prepareProcessEffects(command, state, drafts) {
3348
+ if (!Array.isArray(drafts)) return "processBundle: effects must be an array";
3349
+ const seen = /* @__PURE__ */ new Set();
3350
+ const out = [];
3351
+ for (let i = 0; i < drafts.length; i += 1) {
3352
+ const draft = drafts[i];
3353
+ if (!isObjectRecord(draft) || typeof draft.type !== "string" || draft.type.length === 0) {
3354
+ return "processBundle: effect draft must have a non-empty type";
3355
+ }
3356
+ const id = typeof draft.id === "string" && draft.id.length > 0 ? draft.id : `${command.id}:effect:${state.effectSeq + i + 1}`;
3357
+ if (seen.has(id)) return `processBundle: duplicate effect '${id}'`;
3358
+ if (state.seenEffectIds.includes(id)) return `processBundle: duplicate effect '${id}'`;
3359
+ seen.add(id);
3360
+ out.push({
3361
+ id,
3362
+ type: draft.type,
3363
+ payload: draft.payload,
3364
+ ...typeof draft.processId === "string" ? { processId: draft.processId } : {},
3365
+ ...typeof draft.correlationId === "string" ? { correlationId: draft.correlationId } : {},
3366
+ ...typeof draft.causationId === "string" ? { causationId: draft.causationId } : {},
3367
+ ...isObjectRecord(draft.metadata) ? { metadata: draft.metadata } : {}
3368
+ });
3369
+ }
3370
+ return out;
3371
+ }
3372
+ function emitProcessFailure(state, emit, raw, command, code, message) {
3373
+ state.errorCount += 1;
3374
+ const cursor = processCursorOf(state);
3375
+ const error = {
3376
+ code,
3377
+ message,
3378
+ command: raw,
3379
+ ...command === void 0 ? {} : { commandId: command.id, commandType: command.type },
3380
+ cursor
3381
+ };
3382
+ emit({ kind: "error", error });
3383
+ emitProcessStatus(state, emit, command, "rejected", 0, 0, code);
3384
+ emitProcessAudit(state, emit, command, "failure", [], [], code, message);
3385
+ emit({ kind: "cursor", cursor: processCursorOf(state) });
3386
+ }
3387
+ function emitProcessStatus(state, emit, command, statusState, eventCount, effectCount, errorCode) {
3388
+ emit({
3389
+ kind: "status",
3390
+ status: {
3391
+ state: statusState,
3392
+ ...command === void 0 ? {} : { commandId: command.id, commandType: command.type },
3393
+ eventCount,
3394
+ effectCount,
3395
+ ...errorCode === void 0 ? {} : { errorCode },
3396
+ cursor: processCursorOf(state)
3397
+ }
3398
+ });
3399
+ }
3400
+ function emitProcessAudit(state, emit, command, outcome, events, effects, errorCode, errorMessage2) {
3401
+ state.auditSeq += 1;
3402
+ emit({
3403
+ kind: "audit",
3404
+ audit: {
3405
+ seq: state.auditSeq,
3406
+ ...command === void 0 ? {} : { commandId: command.id, commandType: command.type },
3407
+ outcome,
3408
+ eventIds: events.map((event) => event.id),
3409
+ eventTypes: events.map((event) => event.type),
3410
+ effectIds: effects.map((effect) => effect.id),
3411
+ effectTypes: effects.map((effect) => effect.type),
3412
+ ...errorCode === void 0 ? {} : { errorCode },
3413
+ ...errorMessage2 === void 0 ? {} : { errorMessage: errorMessage2 },
3414
+ cursor: processCursorOf(state)
3415
+ }
3416
+ });
3417
+ }
3418
+ function processCursorOf(state) {
3419
+ return {
3420
+ eventSeq: state.eventSeq,
3421
+ effectSeq: state.effectSeq,
3422
+ commandCount: state.commandCount,
3423
+ errorCount: state.errorCount,
3424
+ auditSeq: state.auditSeq
3425
+ };
3426
+ }
3427
+
3428
+ // src/orchestration/resilience-bundles.ts
3429
+ function retryStatusBundle(graph, events, opts = {}) {
3430
+ const policy = opts.policy ?? retryPolicy();
3431
+ const name = opts.name ?? "retry";
3432
+ const status = graph.node(
3433
+ [events],
3434
+ (ctx) => {
3435
+ let next = ctx.state.get() ?? { state: "idle", attempt: 0, maxAttempts: policy.maxAttempts };
3436
+ for (const raw of depBatch(ctx, 0) ?? []) {
3437
+ const event = raw;
3438
+ if (event.kind === "attempt") {
3439
+ next = { state: "running", attempt: event.attempt, maxAttempts: policy.maxAttempts };
3440
+ } else if (event.kind === "retry") {
3441
+ next = {
3442
+ state: "waiting",
3443
+ attempt: event.attempt,
3444
+ maxAttempts: policy.maxAttempts,
3445
+ delayMs: event.delayMs
3446
+ };
3447
+ } else if (event.kind === "success") {
3448
+ next = {
3449
+ state: "succeeded",
3450
+ attempt: event.attempt ?? next.attempt,
3451
+ maxAttempts: policy.maxAttempts
3452
+ };
3453
+ } else if (event.kind === "failure") {
3454
+ const attempt = event.attempt ?? next.attempt;
3455
+ next = {
3456
+ state: shouldRetry(policy, attempt) ? "failed" : "exhausted",
3457
+ attempt,
3458
+ maxAttempts: policy.maxAttempts,
3459
+ delayMs: shouldRetry(policy, attempt) ? nextRetryDelayMs(policy, attempt + 1) : void 0
3460
+ };
3461
+ } else {
3462
+ next = {
3463
+ state: "exhausted",
3464
+ attempt: event.attempt,
3465
+ maxAttempts: policy.maxAttempts
3466
+ };
3467
+ }
3468
+ }
3469
+ ctx.state.set(next);
3470
+ ctx.down([["DATA", next]]);
3471
+ },
3472
+ { name: `${name}/status`, factory: "retryStatus" }
3473
+ );
3474
+ const errors = graph.node(
3475
+ [events],
3476
+ (ctx) => {
3477
+ for (const raw of depBatch(ctx, 0) ?? []) {
3478
+ const event = raw;
3479
+ if ("error" in event) ctx.down([["DATA", event.error]]);
3480
+ }
3481
+ },
3482
+ { name: `${name}/errors`, factory: "retryErrors" }
3483
+ );
3484
+ return { status, errors };
3485
+ }
3486
+ function breakerBundle(graph, events, opts) {
3487
+ if (!Number.isInteger(opts.failureThreshold) || opts.failureThreshold <= 0) {
3488
+ throw new RangeError("breakerBundle: failureThreshold must be a positive integer");
3489
+ }
3490
+ const name = opts.name ?? "breaker";
3491
+ const now = opts.now ?? Date.now;
3492
+ const status = graph.node(
3493
+ [events],
3494
+ (ctx) => {
3495
+ let next = ctx.state.get() ?? { state: "closed", failures: 0 };
3496
+ if (next.state === "open" && opts.resetAfterMs !== void 0 && next.openedAtMs !== void 0 && now() - next.openedAtMs >= opts.resetAfterMs) {
3497
+ next = { ...next, state: "half-open" };
3498
+ }
3499
+ for (const raw of depBatch(ctx, 0) ?? []) {
3500
+ const event = raw;
3501
+ if (event.kind === "success") {
3502
+ next = { state: "closed", failures: 0 };
3503
+ } else if (event.kind === "failure" || event.kind === "exhausted") {
3504
+ const failures = next.failures + 1;
3505
+ next = failures >= opts.failureThreshold ? { state: "open", failures, openedAtMs: now() } : { ...next, failures };
3506
+ }
3507
+ }
3508
+ ctx.state.set(next);
3509
+ ctx.down([["DATA", next]]);
3510
+ },
3511
+ { name: `${name}/status`, factory: "breakerStatus" }
3512
+ );
3513
+ const allowed = graph.node(
3514
+ [status],
3515
+ (ctx) => {
3516
+ const statusBatch = depBatch(ctx, 0) ?? [];
3517
+ for (const value of statusBatch) {
3518
+ ctx.down([["DATA", value.state !== "open"]]);
3519
+ }
3520
+ },
3521
+ { name: `${name}/allowed`, factory: "breakerAllowed" }
3522
+ );
3523
+ return { status, allowed };
3524
+ }
3525
+ function rateLimitBundle(graph, source, opts) {
3526
+ if (!Number.isInteger(opts.max) || opts.max <= 0) {
3527
+ throw new RangeError("rateLimitBundle: max must be a positive integer");
3528
+ }
3529
+ if (!Number.isFinite(opts.windowMs) || opts.windowMs <= 0) {
3530
+ throw new RangeError("rateLimitBundle: windowMs must be positive");
3531
+ }
3532
+ const now = opts.now ?? Date.now;
3533
+ const name = opts.name ?? "rateLimit";
3534
+ const events = graph.node(
3535
+ [source],
3536
+ (ctx) => {
3537
+ const current = now();
3538
+ let state = ctx.state.get() ?? { count: 0, resetAtMs: current + opts.windowMs, allowed: 0, dropped: 0 };
3539
+ if (current >= state.resetAtMs) {
3540
+ state = { ...state, count: 0, resetAtMs: current + opts.windowMs };
3541
+ }
3542
+ for (const value of depBatch(ctx, 0) ?? []) {
3543
+ const allowed2 = state.count < opts.max;
3544
+ state = allowed2 ? { ...state, count: state.count + 1, allowed: state.allowed + 1 } : { ...state, dropped: state.dropped + 1 };
3545
+ const status2 = {
3546
+ allowed: state.allowed,
3547
+ dropped: state.dropped,
3548
+ remaining: Math.max(0, opts.max - state.count),
3549
+ resetAtMs: state.resetAtMs
3550
+ };
3551
+ ctx.down([
3552
+ [
3553
+ "DATA",
3554
+ allowed2 ? { kind: "allowed", value, status: status2 } : { kind: "dropped", value, status: status2 }
3555
+ ]
3556
+ ]);
3557
+ }
3558
+ ctx.state.set(state);
3559
+ },
3560
+ { name: `${name}/events`, factory: "rateLimitEvents" }
3561
+ );
3562
+ const allowed = graph.node(
3563
+ [events],
3564
+ (ctx) => {
3565
+ for (const event of depBatch(ctx, 0) ?? []) {
3566
+ const typed = event;
3567
+ if (typed.kind === "allowed") ctx.down([["DATA", typed.value]]);
3568
+ }
3569
+ },
3570
+ { name: `${name}/allowed`, factory: "rateLimitAllowed" }
3571
+ );
3572
+ const dropped = graph.node(
3573
+ [events],
3574
+ (ctx) => {
3575
+ for (const event of depBatch(ctx, 0) ?? []) {
3576
+ const typed = event;
3577
+ if (typed.kind === "dropped") ctx.down([["DATA", typed.value]]);
3578
+ }
3579
+ },
3580
+ { name: `${name}/dropped`, factory: "rateLimitDropped" }
3581
+ );
3582
+ const status = graph.node(
3583
+ [events],
3584
+ (ctx) => {
3585
+ for (const event of depBatch(ctx, 0) ?? []) {
3586
+ ctx.down([["DATA", event.status]]);
3587
+ }
3588
+ },
3589
+ { name: `${name}/status`, factory: "rateLimitStatus" }
3590
+ );
3591
+ return { allowed, dropped, status };
3592
+ }
3593
+ function timeoutBundle(graph, source, ms, opts = {}) {
3594
+ const name = opts.name ?? "timeout";
3595
+ const node = timeout(source, ms);
3596
+ const status = graph.node(
3597
+ [node],
3598
+ (ctx) => {
3599
+ const terminal = ctx.terminal[0];
3600
+ if (terminal === true) ctx.down([["DATA", "completed"]]);
3601
+ else if (terminal !== false && terminal !== void 0) ctx.down([["DATA", "errored"]]);
3602
+ else if ((depBatch(ctx, 0) ?? []).length > 0) ctx.down([["DATA", "running"]]);
3603
+ },
3604
+ { name: `${name}/status`, factory: "timeoutStatus" }
3605
+ );
3606
+ const errors = graph.node(
3607
+ [node],
3608
+ (ctx) => {
3609
+ const terminal = ctx.terminal[0];
3610
+ if (terminal !== true && terminal !== false && terminal !== void 0) {
3611
+ ctx.down([["DATA", terminal]]);
3612
+ }
3613
+ },
3614
+ { name: `${name}/errors`, factory: "timeoutErrors" }
3615
+ );
3616
+ return { node, status, errors };
3617
+ }
3618
+ function constantBackoff(delayMs) {
3619
+ return { kind: "constant", delayMs };
3620
+ }
3621
+
3622
+ // src/orchestration/scheduled-readiness.ts
3623
+ function scheduledReadinessProjector(graph, opts) {
3624
+ const name = opts.name ?? "scheduledReadiness";
3625
+ const clockDeps = opts.clocks ?? [];
3626
+ const runtime = graph.node(
3627
+ [...opts.schedules, ...clockDeps],
3628
+ (ctx) => {
3629
+ const state = ctx.state.get() ?? initialState();
3630
+ forEachDepBatch(ctx, 0, opts.schedules.length, (raw) => {
3631
+ const retained = sanitizeSchedule(raw);
3632
+ if (retained.ok) {
3633
+ const existing = state.schedules.get(retained.schedule.scheduleId);
3634
+ if (existing === void 0) {
3635
+ state.schedules.set(retained.schedule.scheduleId, retained.schedule);
3636
+ } else if (scheduleIdentity(existing) !== scheduleIdentity(retained.schedule)) {
3637
+ const issue = dataIssue(
3638
+ "scheduled-readiness-schedule-conflict",
3639
+ "Scheduled readiness scheduleId was replayed with conflicting schedule material; the first valid schedule was retained.",
3640
+ {
3641
+ subjectId: retained.schedule.scheduleId,
3642
+ refs: scheduleSourceRefs(retained.schedule, state.clockSourceRefs),
3643
+ details: {
3644
+ existingReadyAtMs: readinessMs(existing),
3645
+ incomingReadyAtMs: readinessMs(retained.schedule),
3646
+ existingDeadlineMs: existing.deadlineMs,
3647
+ incomingDeadlineMs: retained.schedule.deadlineMs
3648
+ }
3649
+ }
3650
+ );
3651
+ emitIssue3(ctx, state, issue);
3652
+ emitStatus3(ctx, state, {
3653
+ kind: "scheduled-readiness-status",
3654
+ statusId: `${retained.schedule.scheduleId}:scheduled-readiness-status:issue`,
3655
+ scheduleId: retained.schedule.scheduleId,
3656
+ state: "issue",
3657
+ subjectRefs: scheduleSubjectRefs(existing),
3658
+ readyAtMs: readinessMs(existing),
3659
+ ...existing.deadlineMs === void 0 ? {} : { deadlineMs: existing.deadlineMs },
3660
+ nowMs: state.nowMs,
3661
+ sourceRefs: scheduleSourceRefs(existing, state.clockSourceRefs),
3662
+ issueCodes: [issue.code]
3663
+ });
3664
+ }
3665
+ } else {
3666
+ emitIssue3(ctx, state, retained.issue);
3667
+ emitStatus3(ctx, state, {
3668
+ kind: "scheduled-readiness-status",
3669
+ statusId: `${retained.scheduleId}:scheduled-readiness-status:issue`,
3670
+ scheduleId: retained.scheduleId,
3671
+ state: "issue",
3672
+ sourceRefs: retained.sourceRefs,
3673
+ issueCodes: [retained.issue.code]
3674
+ });
3675
+ }
3676
+ });
3677
+ forEachDepBatch(ctx, opts.schedules.length, clockDeps.length, (raw) => {
3678
+ const clock = sanitizeClock(raw);
3679
+ if (clock.ok) {
3680
+ if (state.nowMs !== void 0 && clock.clock.nowMs < state.nowMs) {
3681
+ emitIssue3(
3682
+ ctx,
3683
+ state,
3684
+ dataIssue(
3685
+ "scheduled-readiness-clock-rollback",
3686
+ "Scheduled readiness clock facts must be monotonic; rollback was ignored.",
3687
+ {
3688
+ subjectId: clock.clock.clockId,
3689
+ refs: clock.clock.sourceRefs,
3690
+ severity: "warning",
3691
+ details: { nowMs: clock.clock.nowMs, previousNowMs: state.nowMs }
3692
+ }
3693
+ )
3694
+ );
3695
+ return;
3696
+ }
3697
+ state.nowMs = clock.clock.nowMs;
3698
+ state.clockSourceRefs = clock.clock.sourceRefs;
3699
+ } else {
3700
+ emitIssue3(ctx, state, clock.issue);
3701
+ }
3702
+ });
3703
+ evaluateSchedules(ctx, state);
3704
+ ctx.down([["DATA", { kind: "views", views: buildViews(state) }]]);
3705
+ ctx.state.set(state);
3706
+ },
3707
+ { name: `${name}/runtime`, factory: "scheduledReadinessProjector", partial: true }
3708
+ );
3709
+ return {
3710
+ pending: projectRuntimeFact(
3711
+ graph,
3712
+ runtime,
3713
+ `${name}/pending`,
3714
+ "scheduledReadinessPending",
3715
+ (fact) => fact.kind === "pending" ? fact.pending : void 0
3716
+ ),
3717
+ ready: projectRuntimeFact(
3718
+ graph,
3719
+ runtime,
3720
+ `${name}/ready`,
3721
+ "scheduledReadinessReady",
3722
+ (fact) => fact.kind === "ready" ? fact.ready : void 0
3723
+ ),
3724
+ overdue: projectRuntimeFact(
3725
+ graph,
3726
+ runtime,
3727
+ `${name}/overdue`,
3728
+ "scheduledReadinessOverdue",
3729
+ (fact) => fact.kind === "overdue" ? fact.overdue : void 0
3730
+ ),
3731
+ status: projectRuntimeFact(
3732
+ graph,
3733
+ runtime,
3734
+ `${name}/status`,
3735
+ "scheduledReadinessStatus",
3736
+ (fact) => fact.kind === "status" ? fact.status : void 0
3737
+ ),
3738
+ issues: projectRuntimeFact(
3739
+ graph,
3740
+ runtime,
3741
+ `${name}/issues`,
3742
+ "scheduledReadinessIssues",
3743
+ (fact) => fact.kind === "issue" ? fact.issue : void 0
3744
+ ),
3745
+ audit: projectRuntimeFact(
3746
+ graph,
3747
+ runtime,
3748
+ `${name}/audit`,
3749
+ "scheduledReadinessAudit",
3750
+ (fact) => fact.kind === "audit" ? fact.audit : void 0
3751
+ ),
3752
+ views: projectRuntimeFact(
3753
+ graph,
3754
+ runtime,
3755
+ `${name}/views`,
3756
+ "scheduledReadinessViews",
3757
+ (fact) => fact.kind === "views" ? fact.views : void 0
3758
+ )
3759
+ };
3760
+ }
3761
+ function initialState() {
3762
+ return {
3763
+ schedules: /* @__PURE__ */ new Map(),
3764
+ pendingById: /* @__PURE__ */ new Map(),
3765
+ readyById: /* @__PURE__ */ new Map(),
3766
+ overdueById: /* @__PURE__ */ new Map(),
3767
+ statusById: /* @__PURE__ */ new Map(),
3768
+ emittedKeys: /* @__PURE__ */ new Set(),
3769
+ issueKeys: /* @__PURE__ */ new Set(),
3770
+ auditSeq: 0,
3771
+ nowMs: void 0,
3772
+ clockSourceRefs: void 0
3773
+ };
3774
+ }
3775
+ function evaluateSchedules(ctx, state) {
3776
+ for (const schedule of state.schedules.values()) {
3777
+ const readyAtMs = readinessMs(schedule);
3778
+ const subjectRefs = scheduleSubjectRefs(schedule);
3779
+ const sourceRefs = scheduleSourceRefs(schedule, state.clockSourceRefs);
3780
+ const baseMetadata = sanitizeScheduledReadinessMetadata({
3781
+ ...schedule.reason === void 0 ? {} : { reason: schedule.reason },
3782
+ ...schedule.metadata ?? {}
3783
+ });
3784
+ if (state.nowMs === void 0 || state.nowMs < readyAtMs) {
3785
+ const pending = Object.freeze({
3786
+ kind: "scheduled-readiness-pending",
3787
+ scheduleId: schedule.scheduleId,
3788
+ subjectRefs,
3789
+ readyAtMs,
3790
+ ...schedule.deadlineMs === void 0 ? {} : { deadlineMs: schedule.deadlineMs },
3791
+ ...state.nowMs === void 0 ? {} : { nowMs: state.nowMs },
3792
+ sourceRefs,
3793
+ ...baseMetadata === void 0 ? {} : { metadata: baseMetadata }
3794
+ });
3795
+ emitPending(ctx, state, pending);
3796
+ emitStatus3(
3797
+ ctx,
3798
+ state,
3799
+ statusFor(schedule, "pending", {
3800
+ subjectRefs,
3801
+ readyAtMs,
3802
+ sourceRefs,
3803
+ nowMs: state.nowMs
3804
+ })
3805
+ );
3806
+ continue;
3807
+ }
3808
+ const ready = Object.freeze({
3809
+ kind: "scheduled-readiness-ready",
3810
+ scheduleId: schedule.scheduleId,
3811
+ subjectRefs,
3812
+ readyAtMs,
3813
+ ...schedule.deadlineMs === void 0 ? {} : { deadlineMs: schedule.deadlineMs },
3814
+ nowMs: state.nowMs,
3815
+ sourceRefs,
3816
+ ...baseMetadata === void 0 ? {} : { metadata: baseMetadata }
3817
+ });
3818
+ emitReady(ctx, state, ready);
3819
+ emitStatus3(
3820
+ ctx,
3821
+ state,
3822
+ statusFor(schedule, "ready", {
3823
+ subjectRefs,
3824
+ readyAtMs,
3825
+ sourceRefs,
3826
+ nowMs: state.nowMs
3827
+ })
3828
+ );
3829
+ if (schedule.deadlineMs !== void 0 && state.nowMs > schedule.deadlineMs) {
3830
+ const overdue = Object.freeze({
3831
+ kind: "scheduled-readiness-overdue",
3832
+ scheduleId: schedule.scheduleId,
3833
+ subjectRefs,
3834
+ readyAtMs,
3835
+ deadlineMs: schedule.deadlineMs,
3836
+ nowMs: state.nowMs,
3837
+ sourceRefs,
3838
+ ...baseMetadata === void 0 ? {} : { metadata: baseMetadata }
3839
+ });
3840
+ emitOverdue(ctx, state, overdue);
3841
+ emitStatus3(
3842
+ ctx,
3843
+ state,
3844
+ statusFor(schedule, "overdue", {
3845
+ subjectRefs,
3846
+ readyAtMs,
3847
+ sourceRefs,
3848
+ nowMs: state.nowMs
3849
+ })
3850
+ );
3851
+ }
3852
+ }
3853
+ }
3854
+ function sanitizeSchedule(raw) {
3855
+ if (!isPlainRecord(raw)) {
3856
+ return {
3857
+ ok: false,
3858
+ scheduleId: "unknown-scheduled-readiness",
3859
+ sourceRefs: [],
3860
+ issue: dataIssue(
3861
+ "scheduled-readiness-malformed-schedule",
3862
+ "Scheduled readiness requires a stable scheduleId, subjectRefs array, and finite readyAtMs.",
3863
+ { subjectId: "unknown-scheduled-readiness", refs: [] }
3864
+ )
3865
+ };
3866
+ }
3867
+ const scheduleId = typeof raw.scheduleId === "string" && raw.scheduleId.length > 0 ? raw.scheduleId : "unknown-scheduled-readiness";
3868
+ const refs = sourceRefArray(raw.sourceRefs);
3869
+ const hasDeadlineMs = Object.hasOwn(raw, "deadlineMs");
3870
+ const readyAtMs = finiteNumberOrUndefined(raw.readyAtMs);
3871
+ const deadlineMs = finiteNumberOrUndefined(raw.deadlineMs);
3872
+ if (raw.kind !== "scheduled-readiness-requested" || typeof raw.scheduleId !== "string" || raw.scheduleId.length === 0 || readyAtMs === void 0 || hasDeadlineMs && deadlineMs === void 0 || raw.subjectRef !== void 0 || !Array.isArray(raw.subjectRefs) || raw.notBeforeMs !== void 0 || raw.policyRefs !== void 0 && !Array.isArray(raw.policyRefs) || raw.sourceRefs !== void 0 && !Array.isArray(raw.sourceRefs)) {
3873
+ return {
3874
+ ok: false,
3875
+ scheduleId,
3876
+ sourceRefs: refs,
3877
+ issue: dataIssue(
3878
+ "scheduled-readiness-malformed-schedule",
3879
+ "Scheduled readiness requires a stable scheduleId, subjectRefs array, and finite readyAtMs.",
3880
+ { subjectId: scheduleId, refs }
3881
+ )
3882
+ };
3883
+ }
3884
+ const subjectRefs = sourceRefArray(raw.subjectRefs);
3885
+ const policyRefs = sourceRefArray(raw.policyRefs);
3886
+ const metadata = sanitizeScheduledReadinessMetadata(
3887
+ isPlainRecord(raw.metadata) ? raw.metadata : void 0
3888
+ );
3889
+ return {
3890
+ ok: true,
3891
+ schedule: Object.freeze({
3892
+ kind: "scheduled-readiness-requested",
3893
+ scheduleId: raw.scheduleId,
3894
+ subjectRefs,
3895
+ readyAtMs,
3896
+ ...deadlineMs === void 0 ? {} : { deadlineMs },
3897
+ ...typeof raw.reason === "string" ? { reason: raw.reason } : {},
3898
+ ...policyRefs.length === 0 ? {} : { policyRefs },
3899
+ sourceRefs: refs,
3900
+ ...metadata === void 0 ? {} : { metadata }
3901
+ })
3902
+ };
3903
+ }
3904
+ function sanitizeClock(raw) {
3905
+ if (!isPlainRecord(raw)) {
3906
+ return {
3907
+ ok: false,
3908
+ issue: dataIssue(
3909
+ "scheduled-readiness-malformed-clock",
3910
+ "Scheduled readiness clock facts require a stable clockId and finite nowMs.",
3911
+ { subjectId: "unknown-scheduled-readiness-clock", refs: [] }
3912
+ )
3913
+ };
3914
+ }
3915
+ const refs = sourceRefArray(raw.sourceRefs);
3916
+ const nowMs = finiteNumberOrUndefined(raw.nowMs);
3917
+ if (raw.kind !== "scheduled-readiness-clock" || typeof raw.clockId !== "string" || raw.clockId.length === 0 || nowMs === void 0 || raw.sourceRefs !== void 0 && !Array.isArray(raw.sourceRefs)) {
3918
+ const clockSubjectId = typeof raw.clockId === "string" && raw.clockId.length > 0 ? raw.clockId : "unknown-scheduled-readiness-clock";
3919
+ return {
3920
+ ok: false,
3921
+ issue: dataIssue(
3922
+ "scheduled-readiness-malformed-clock",
3923
+ "Scheduled readiness clock facts require a stable clockId and finite nowMs.",
3924
+ { subjectId: clockSubjectId, refs }
3925
+ )
3926
+ };
3927
+ }
3928
+ const metadata = sanitizeScheduledReadinessMetadata(
3929
+ isPlainRecord(raw.metadata) ? raw.metadata : void 0
3930
+ );
3931
+ return {
3932
+ ok: true,
3933
+ clock: Object.freeze({
3934
+ kind: "scheduled-readiness-clock",
3935
+ clockId: raw.clockId,
3936
+ nowMs,
3937
+ sourceRefs: refs,
3938
+ ...metadata === void 0 ? {} : { metadata }
3939
+ })
3940
+ };
3941
+ }
3942
+ function emitPending(ctx, state, pending) {
3943
+ state.pendingById.set(pending.scheduleId, pending);
3944
+ const key = `pending:${pending.scheduleId}`;
3945
+ if (state.emittedKeys.has(key)) return;
3946
+ state.emittedKeys.add(key);
3947
+ ctx.down([["DATA", { kind: "pending", pending }]]);
3948
+ }
3949
+ function emitReady(ctx, state, ready) {
3950
+ const key = `ready:${ready.scheduleId}`;
3951
+ if (state.emittedKeys.has(key)) return;
3952
+ state.emittedKeys.add(key);
3953
+ state.readyById.set(ready.scheduleId, ready);
3954
+ state.pendingById.delete(ready.scheduleId);
3955
+ emitAudit2(ctx, state, "scheduled-readiness-ready", {
3956
+ subjectId: ready.scheduleId,
3957
+ sourceRefs: ready.sourceRefs,
3958
+ metadata: { nowMs: ready.nowMs, readyAtMs: ready.readyAtMs }
3959
+ });
3960
+ ctx.down([["DATA", { kind: "ready", ready }]]);
3961
+ }
3962
+ function emitOverdue(ctx, state, overdue) {
3963
+ const key = `overdue:${overdue.scheduleId}`;
3964
+ if (state.emittedKeys.has(key)) return;
3965
+ state.emittedKeys.add(key);
3966
+ state.overdueById.set(overdue.scheduleId, overdue);
3967
+ emitAudit2(ctx, state, "scheduled-readiness-overdue", {
3968
+ subjectId: overdue.scheduleId,
3969
+ sourceRefs: overdue.sourceRefs,
3970
+ metadata: {
3971
+ nowMs: overdue.nowMs,
3972
+ readyAtMs: overdue.readyAtMs,
3973
+ deadlineMs: overdue.deadlineMs
3974
+ }
3975
+ });
3976
+ ctx.down([["DATA", { kind: "overdue", overdue }]]);
3977
+ }
3978
+ function emitStatus3(ctx, state, status) {
3979
+ state.statusById.set(status.scheduleId, status);
3980
+ const key = `status:${stableJsonStringify(status)}`;
3981
+ if (state.emittedKeys.has(key)) return;
3982
+ state.emittedKeys.add(key);
3983
+ ctx.down([["DATA", { kind: "status", status }]]);
3984
+ }
3985
+ function emitIssue3(ctx, state, issue) {
3986
+ const key = `${issue.code}:${issue.subjectId ?? ""}:${JSON.stringify(issue.details ?? {})}`;
3987
+ if (state.issueKeys.has(key)) return;
3988
+ state.issueKeys.add(key);
3989
+ ctx.down([["DATA", { kind: "issue", issue }]]);
3990
+ }
3991
+ function emitAudit2(ctx, state, kind, opts = {}) {
3992
+ state.auditSeq += 1;
3993
+ const metadata = sanitizeGraphVisibleRecord(opts.metadata);
3994
+ ctx.down([
3995
+ [
3996
+ "DATA",
3997
+ {
3998
+ kind: "audit",
3999
+ audit: Object.freeze({
4000
+ id: `scheduled-readiness-audit-${state.auditSeq}`,
4001
+ kind,
4002
+ ...opts.subjectId === void 0 ? {} : { subjectId: opts.subjectId },
4003
+ ...opts.sourceRefs === void 0 ? {} : { sourceRefs: canonicalPublicSourceRefs(opts.sourceRefs) },
4004
+ ...metadata === void 0 ? {} : { metadata }
4005
+ })
4006
+ }
4007
+ ]
4008
+ ]);
4009
+ }
4010
+ function statusFor(schedule, state, opts) {
4011
+ const metadata = sanitizeGraphVisibleRecord({
4012
+ ...schedule.reason === void 0 ? {} : { reason: schedule.reason }
4013
+ });
4014
+ return Object.freeze({
4015
+ kind: "scheduled-readiness-status",
4016
+ statusId: `${schedule.scheduleId}:scheduled-readiness-status:${state}`,
4017
+ scheduleId: schedule.scheduleId,
4018
+ state,
4019
+ subjectRefs: opts.subjectRefs,
4020
+ readyAtMs: opts.readyAtMs,
4021
+ ...schedule.deadlineMs === void 0 ? {} : { deadlineMs: schedule.deadlineMs },
4022
+ ...opts.nowMs === void 0 ? {} : { nowMs: opts.nowMs },
4023
+ sourceRefs: opts.sourceRefs,
4024
+ ...metadata === void 0 ? {} : { metadata }
4025
+ });
4026
+ }
4027
+ function readinessMs(schedule) {
4028
+ return schedule.readyAtMs;
4029
+ }
4030
+ function scheduleIdentity(schedule) {
4031
+ return stableJsonStringify({
4032
+ scheduleId: schedule.scheduleId,
4033
+ subjectRefs: schedule.subjectRefs,
4034
+ readyAtMs: schedule.readyAtMs,
4035
+ deadlineMs: schedule.deadlineMs,
4036
+ reason: schedule.reason,
4037
+ policyRefs: schedule.policyRefs,
4038
+ sourceRefs: schedule.sourceRefs,
4039
+ metadata: schedule.metadata
4040
+ });
4041
+ }
4042
+ function scheduleSubjectRefs(schedule) {
4043
+ return canonicalPublicSourceRefs(uniqueSourceRefs(schedule.subjectRefs));
4044
+ }
4045
+ function scheduleSourceRefs(schedule, clockSourceRefs) {
4046
+ return canonicalPublicSourceRefs(
4047
+ uniqueSourceRefs([
4048
+ ref("scheduled-readiness", schedule.scheduleId),
4049
+ ...schedule.sourceRefs ?? [],
4050
+ ...schedule.policyRefs ?? [],
4051
+ ...clockSourceRefs ?? []
4052
+ ])
4053
+ );
4054
+ }
4055
+ function sanitizeScheduledReadinessMetadata(value) {
4056
+ const filtered = omitRuntimeMetadata(value);
4057
+ return sanitizeGraphVisibleRecord(filtered);
4058
+ }
4059
+ function omitRuntimeMetadata(value) {
4060
+ if (!isPlainRecord(value)) return void 0;
4061
+ const out = {};
4062
+ for (const [key, child] of Object.entries(value)) {
4063
+ if (isRuntimeMetadataKey(key)) continue;
4064
+ const filteredChild = Array.isArray(child) ? child.map((entry) => isPlainRecord(entry) ? omitRuntimeMetadata(entry) : entry) : isPlainRecord(child) ? omitRuntimeMetadata(child) : child;
4065
+ if (filteredChild !== void 0) out[key] = filteredChild;
4066
+ }
4067
+ return Object.keys(out).length === 0 ? void 0 : out;
4068
+ }
4069
+ function isPlainRecord(value) {
4070
+ return value !== null && typeof value === "object" && !Array.isArray(value);
4071
+ }
4072
+ function finiteNumberOrUndefined(value) {
4073
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
4074
+ }
4075
+ function sourceRefArray(value) {
4076
+ if (!Array.isArray(value)) return [];
4077
+ return canonicalPublicSourceRefs(
4078
+ value.flatMap((entry) => {
4079
+ const sourceRef = sourceRefOrUndefined2(entry);
4080
+ return sourceRef === void 0 ? [] : [sourceRef];
4081
+ })
4082
+ );
4083
+ }
4084
+ function sourceRefOrUndefined2(value) {
4085
+ if (!isPlainRecord(value)) return void 0;
4086
+ if (typeof value.kind !== "string" || value.kind.length === 0) return void 0;
4087
+ if (typeof value.id !== "string" || value.id.length === 0) return void 0;
4088
+ return isPlainRecord(value.metadata) ? { kind: value.kind, id: value.id, metadata: value.metadata } : { kind: value.kind, id: value.id };
4089
+ }
4090
+ function isRuntimeMetadataKey(key) {
4091
+ return /^(apiKey|api_key|secret|client|transport|subprocess|sdk|oauth|credential|credentials|accessToken|access_token|refreshToken|refresh_token|idToken|id_token|token|password|passphrase|authorization|authHeader|auth_header|bearer|privateKey|private_key|sessionCookie|session_cookie|cookie|stdout|stderr|stack|stackTrace|stack_trace|providerRaw|provider_raw|rawResponse|raw_response|rawResponseBody|raw_response_body|diff|patch|fileContents|file_contents|binary|media)$/i.test(
4092
+ key
4093
+ );
4094
+ }
4095
+ function buildViews(state) {
4096
+ return Object.freeze({
4097
+ schedulesById: new Map(state.schedules),
4098
+ pendingById: new Map(state.pendingById),
4099
+ readyById: new Map(state.readyById),
4100
+ overdueById: new Map(state.overdueById),
4101
+ statusById: new Map(state.statusById),
4102
+ ...state.nowMs === void 0 ? {} : { nowMs: state.nowMs }
4103
+ });
4104
+ }
4105
+
4106
+ export {
4107
+ effectRunCompletionProjector,
4108
+ structuredAgentDecisionInterpreter,
4109
+ fakeExecutorResult,
4110
+ fakeExecutorFailure,
4111
+ fakeExecutorBlocked,
4112
+ fakeExecutorTimeout,
4113
+ fakeExecutorCanceled,
4114
+ agentRequestProposalFromDecision,
4115
+ admitAgentRequestProposal,
4116
+ issueAgentRequest,
4117
+ agentRequestLedgerViews,
4118
+ requestSatisfactionProjector,
4119
+ toolProviderRunAdmissionProjector,
4120
+ toolProviderRunRetryProjector,
4121
+ effectRun,
4122
+ processBundle,
4123
+ processEffectRunner,
4124
+ retryStatusBundle,
4125
+ breakerBundle,
4126
+ rateLimitBundle,
4127
+ timeoutBundle,
4128
+ constantBackoff,
4129
+ scheduledReadinessProjector
4130
+ };
4131
+ //# sourceMappingURL=chunk-MCOFHMUU.js.map