@graphrefly/graphrefly 0.32.0 → 0.33.0

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 (288) hide show
  1. package/dist/{cascading-D3sapjue.d.ts → cascading-Bg0a4VSf.d.ts} +2 -2
  2. package/dist/{cascading-BfQmSmjU.d.cts → cascading-DKIb6Pk8.d.cts} +2 -2
  3. package/dist/{chunk-4JBKKUCJ.js → chunk-2JO6LXFT.js} +1 -1
  4. package/dist/{chunk-FTA5TB2A.js → chunk-2LZ6DL45.js} +1 -1
  5. package/dist/{chunk-WQ7I7JVU.js → chunk-4F564IPP.js} +1 -1
  6. package/dist/{chunk-M2VFLRPJ.js → chunk-4NYSEUKV.js} +1 -1
  7. package/dist/{chunk-N2KKISCE.js → chunk-533RQFF6.js} +1 -1
  8. package/dist/{chunk-BU4SUZSA.js → chunk-55T3K37W.js} +1 -1
  9. package/dist/chunk-6HQ6HVTF.js +1 -0
  10. package/dist/{chunk-4VXL3UZK.js → chunk-7Q2WPFQ7.js} +1 -1
  11. package/dist/{chunk-5PBXUVHI.js → chunk-BY4WKPKM.js} +1 -1
  12. package/dist/{chunk-JYMNVEH6.js → chunk-C5DINHNP.js} +1 -1
  13. package/dist/{chunk-7QS77X6G.js → chunk-CJMFZXIZ.js} +1 -1
  14. package/dist/{chunk-W6FQIFVE.js → chunk-CLD3F4R5.js} +1 -1
  15. package/dist/chunk-DUK7LTJO.js +43 -0
  16. package/dist/{chunk-RWGJQQLT.js → chunk-FKRPIRE6.js} +1 -1
  17. package/dist/{chunk-UXEB35L4.js → chunk-GAOX6OPT.js} +1 -1
  18. package/dist/{chunk-TOCCHQI6.js → chunk-GCUYSIM4.js} +1 -1
  19. package/dist/chunk-HIJ2RKVP.js +1 -0
  20. package/dist/{chunk-XRSHMHEG.js → chunk-HTBOCKVD.js} +1 -1
  21. package/dist/{chunk-LJGPOJHS.js → chunk-IB64M7VP.js} +1 -1
  22. package/dist/{chunk-Q2SY7M7K.js → chunk-IJFSR4NU.js} +1 -1
  23. package/dist/{chunk-X4OOM6QU.js → chunk-INXDSJRC.js} +1 -1
  24. package/dist/{chunk-4YGJ7KZ6.js → chunk-IPNJDNE7.js} +1 -1
  25. package/dist/{chunk-4UUDNFYG.js → chunk-KGKJCHEK.js} +1 -1
  26. package/dist/{chunk-A4JT4SAD.js → chunk-KRH66M4O.js} +1 -1
  27. package/dist/{chunk-K54OKWNY.js → chunk-L3KUKDZC.js} +1 -1
  28. package/dist/{chunk-Y26UN6J5.js → chunk-LOF5HSD3.js} +1 -1
  29. package/dist/chunk-LYCLF26R.js +1 -0
  30. package/dist/{chunk-CZVYLXFK.js → chunk-M27MVZCP.js} +1 -1
  31. package/dist/{chunk-DWIAG62L.js → chunk-NNKJUORL.js} +1 -1
  32. package/dist/{chunk-PNTBXOQ6.js → chunk-O2WY22L7.js} +1 -1
  33. package/dist/{chunk-WF3V5X2L.js → chunk-PBN426RU.js} +1 -1
  34. package/dist/{chunk-MFNOZ5E6.js → chunk-Q46YJCQH.js} +1 -1
  35. package/dist/{chunk-KD3IYBTD.js → chunk-SFIM774L.js} +1 -1
  36. package/dist/{chunk-VXJX3ZZP.js → chunk-T2TB37TW.js} +1 -1
  37. package/dist/{chunk-UMH3HSP7.js → chunk-T7EQPKOP.js} +1 -1
  38. package/dist/{chunk-JAHAJU4G.js → chunk-TONEKQM3.js} +1 -1
  39. package/dist/{chunk-CNXUW2CU.js → chunk-TZLEMGAK.js} +1 -1
  40. package/dist/{chunk-LWGLBCMU.js → chunk-TZQPPQEQ.js} +1 -1
  41. package/dist/{chunk-7JZ3YORY.js → chunk-U2T2XWDA.js} +1 -1
  42. package/dist/{chunk-WE32AFFA.js → chunk-UF746BQ4.js} +1 -1
  43. package/dist/{chunk-7QMVU3IX.js → chunk-WBWBY6LI.js} +1 -1
  44. package/dist/{chunk-7EMUF2RY.js → chunk-Y63GWRHO.js} +1 -1
  45. package/dist/{chunk-PWKLZ2XU.js → chunk-YDWTVO4E.js} +1 -1
  46. package/dist/{chunk-EIFHFDFD.js → chunk-YUBV7EEE.js} +1 -1
  47. package/dist/chunk-Z4GXBOWO.js +61 -0
  48. package/dist/compat/index.cjs +5 -5
  49. package/dist/compat/index.d.cts +14 -14
  50. package/dist/compat/index.d.ts +14 -14
  51. package/dist/compat/index.js +1 -1
  52. package/dist/compat/jotai/index.cjs +1 -1
  53. package/dist/compat/jotai/index.d.cts +2 -2
  54. package/dist/compat/jotai/index.d.ts +2 -2
  55. package/dist/compat/jotai/index.js +1 -1
  56. package/dist/compat/nanostores/index.cjs +1 -1
  57. package/dist/compat/nanostores/index.d.cts +2 -2
  58. package/dist/compat/nanostores/index.d.ts +2 -2
  59. package/dist/compat/nanostores/index.js +1 -1
  60. package/dist/compat/nestjs/index.cjs +5 -5
  61. package/dist/compat/nestjs/index.d.cts +6 -6
  62. package/dist/compat/nestjs/index.d.ts +6 -6
  63. package/dist/compat/nestjs/index.js +1 -1
  64. package/dist/compat/react/index.d.cts +2 -2
  65. package/dist/compat/react/index.d.ts +2 -2
  66. package/dist/compat/solid/index.d.cts +2 -2
  67. package/dist/compat/solid/index.d.ts +2 -2
  68. package/dist/compat/svelte/index.d.cts +2 -2
  69. package/dist/compat/svelte/index.d.ts +2 -2
  70. package/dist/compat/vue/index.d.cts +2 -2
  71. package/dist/compat/vue/index.d.ts +2 -2
  72. package/dist/compat/zustand/index.cjs +3 -3
  73. package/dist/compat/zustand/index.d.cts +4 -4
  74. package/dist/compat/zustand/index.d.ts +4 -4
  75. package/dist/compat/zustand/index.js +1 -1
  76. package/dist/{composite-BY9hMxN7.d.ts → composite-BPDU_XV1.d.ts} +2 -2
  77. package/dist/{composite-CH0S8DFn.d.cts → composite-CmvdhTJe.d.cts} +2 -2
  78. package/dist/core/index.cjs +1 -1
  79. package/dist/core/index.d.cts +4 -4
  80. package/dist/core/index.d.ts +4 -4
  81. package/dist/core/index.js +1 -1
  82. package/dist/extra/browser.cjs +1 -1
  83. package/dist/extra/browser.d.cts +1 -1
  84. package/dist/extra/browser.d.ts +1 -1
  85. package/dist/extra/browser.js +1 -1
  86. package/dist/extra/index.cjs +16 -16
  87. package/dist/extra/index.d.cts +9 -9
  88. package/dist/extra/index.d.ts +9 -9
  89. package/dist/extra/index.js +1 -1
  90. package/dist/extra/node.cjs +1 -1
  91. package/dist/extra/node.d.cts +1 -1
  92. package/dist/extra/node.d.ts +1 -1
  93. package/dist/extra/node.js +1 -1
  94. package/dist/extra/operators.cjs +1 -1
  95. package/dist/extra/operators.d.cts +1 -1
  96. package/dist/extra/operators.d.ts +1 -1
  97. package/dist/extra/operators.js +1 -1
  98. package/dist/extra/reactive.cjs +1 -1
  99. package/dist/extra/reactive.d.cts +3 -3
  100. package/dist/extra/reactive.d.ts +3 -3
  101. package/dist/extra/reactive.js +1 -1
  102. package/dist/extra/sources.cjs +1 -1
  103. package/dist/extra/sources.d.cts +1 -1
  104. package/dist/extra/sources.d.ts +1 -1
  105. package/dist/extra/sources.js +1 -1
  106. package/dist/extra/storage-browser.cjs +1 -1
  107. package/dist/extra/storage-browser.d.cts +1 -1
  108. package/dist/extra/storage-browser.d.ts +1 -1
  109. package/dist/extra/storage-browser.js +1 -1
  110. package/dist/{fallback-Cb3GH1O7.d.cts → fallback-9YznPvPP.d.cts} +1 -1
  111. package/dist/{fallback-DRjJ_ZM8.d.ts → fallback-mYSd8vQo.d.ts} +1 -1
  112. package/dist/graph/index.cjs +4 -4
  113. package/dist/graph/index.d.cts +5 -5
  114. package/dist/graph/index.d.ts +5 -5
  115. package/dist/graph/index.js +1 -1
  116. package/dist/{graph-BOhEGJ6E.d.ts → graph-BROUZPG9.d.ts} +2 -2
  117. package/dist/{graph-CdJeX7O7.d.cts → graph-DaoydJ_u.d.cts} +2 -2
  118. package/dist/{index-CNyiYQWF.d.ts → index--BTb6HUO.d.ts} +332 -108
  119. package/dist/{index-BmZb8fNF.d.cts → index-B-KCkW4M.d.cts} +4 -4
  120. package/dist/{index-CDK5RsV5.d.cts → index-B1hFhK1K.d.cts} +1 -1
  121. package/dist/{index-C7RqYbOZ.d.ts → index-B5eS17Bz.d.ts} +7 -7
  122. package/dist/{index-DSawGt8n.d.cts → index-BDEhWLF4.d.cts} +3 -3
  123. package/dist/{index-CZUzi6Dy.d.ts → index-BFHpNSsV.d.ts} +4 -4
  124. package/dist/{index-DDo-eqQ4.d.cts → index-BO6t0HjV.d.cts} +1 -1
  125. package/dist/{index-CrC7urhX.d.ts → index-BRisOxlx.d.ts} +1 -1
  126. package/dist/{index-CHfBm51k.d.ts → index-BUtCR0k6.d.ts} +4 -4
  127. package/dist/{index-BydMDMf7.d.cts → index-BVTjuKeP.d.cts} +1 -1
  128. package/dist/{index-BX22kvjh.d.ts → index-BWiX5foT.d.ts} +1 -1
  129. package/dist/{index-Dxk-pUQI.d.ts → index-Bd2AjMQY.d.ts} +2 -2
  130. package/dist/{index-Dbmj0iYR.d.ts → index-Bi4ZP6Hc.d.ts} +2 -2
  131. package/dist/{index-j33Lfb1G.d.cts → index-BkfL5MXh.d.cts} +3 -3
  132. package/dist/{index-CnjUhRbs.d.cts → index-BpjQanLs.d.cts} +2 -2
  133. package/dist/{index-LGzAYqdR.d.ts → index-BsxqmV6u.d.ts} +2 -2
  134. package/dist/{index-CCdg0JLX.d.cts → index-C2Dey3L-.d.cts} +12 -3
  135. package/dist/{index-gXTVbSax.d.ts → index-C5uMGVJw.d.ts} +4 -4
  136. package/dist/{index-C-Gsh-0a.d.cts → index-C8_bnDBZ.d.cts} +3 -3
  137. package/dist/{index-C9qCLIN4.d.ts → index-CD7qmvSf.d.ts} +3 -3
  138. package/dist/{index-wIx1Jisk.d.ts → index-CI5fULSz.d.ts} +1 -1
  139. package/dist/{index-BUZPTPSQ.d.ts → index-CNxdDb2e.d.ts} +3 -3
  140. package/dist/{index-FBqTfL_S.d.cts → index-CQ1gt4rn.d.cts} +1 -1
  141. package/dist/{index-C22aTC1X.d.cts → index-C_cXlbu0.d.cts} +332 -108
  142. package/dist/{index-BDLy6CQ9.d.cts → index-Ccv_61jG.d.cts} +2 -2
  143. package/dist/{index-MV2yGIAq.d.ts → index-Ced0dphF.d.ts} +9 -9
  144. package/dist/{index-BzxU4yhV.d.cts → index-ChZvMC4M.d.cts} +4 -4
  145. package/dist/{index-zMQIQuDu.d.ts → index-Chi9IiHJ.d.ts} +3 -3
  146. package/dist/{index-DUkuH3jP.d.cts → index-ClJUZAOr.d.cts} +18 -3
  147. package/dist/{index-D7XxY1Ff.d.cts → index-ClKm7CFB.d.cts} +1 -1
  148. package/dist/{index-D3HcdZ4d.d.cts → index-Cn3taOmp.d.cts} +2 -2
  149. package/dist/{index-C4QTaDli.d.cts → index-CoR-tOZA.d.cts} +4 -4
  150. package/dist/{index-BpFWP7Bq.d.cts → index-Cp91Sxbo.d.cts} +5 -4
  151. package/dist/{index-DD1czHj3.d.ts → index-Cq7Uqgu4.d.ts} +2 -2
  152. package/dist/{index-EGjF6iSY.d.cts → index-D23g00HE.d.cts} +4 -4
  153. package/dist/{index-Bnmttu35.d.ts → index-D80nGRb9.d.ts} +3 -3
  154. package/dist/{index-DhlAMlm9.d.ts → index-DDf8PoPO.d.ts} +149 -52
  155. package/dist/{index-DY2QbdoP.d.cts → index-DR3XqZlV.d.cts} +1 -1
  156. package/dist/{index-BANwzwBV.d.ts → index-Db21wuaD.d.ts} +5 -4
  157. package/dist/{index-BuN2wGJs.d.cts → index-Dgcd59CJ.d.cts} +149 -52
  158. package/dist/{index-CIXaiYDE.d.cts → index-DhWrMTI6.d.cts} +1 -1
  159. package/dist/{index-Dp_pS7Bw.d.ts → index-DheNs40A.d.ts} +2 -2
  160. package/dist/{index-CVevMZ0n.d.ts → index-Dia4yc2y.d.ts} +3 -3
  161. package/dist/{index-_BXz9K7b.d.cts → index-Ds3Rz9m9.d.cts} +3 -3
  162. package/dist/{index-Ckl03Q0s.d.ts → index-Dtpr2FIB.d.ts} +18 -3
  163. package/dist/{index-ByPnK85n.d.ts → index-DupIl9wI.d.ts} +1 -1
  164. package/dist/{index-CEoU-r-g.d.ts → index-DuvQAU02.d.ts} +2 -2
  165. package/dist/{index-D0C_USMR.d.ts → index-DxEcY7Om.d.ts} +1 -1
  166. package/dist/{index-eYHRkoK-.d.ts → index-HvJ90_tX.d.ts} +12 -3
  167. package/dist/{index-LzCJ0kMT.d.cts → index-Jgl7ev9I.d.cts} +9 -9
  168. package/dist/{index-DlGaEBW5.d.cts → index-RJX4snyi.d.cts} +2 -2
  169. package/dist/{index-DNhTQReY.d.cts → index-ZIQaKIdY.d.cts} +7 -7
  170. package/dist/{index-lpGUhTBn.d.ts → index-b4a6Sg0R.d.ts} +4 -4
  171. package/dist/{index-BiGeETJs.d.cts → index-iKsmdnq6.d.cts} +2 -2
  172. package/dist/{index-CmSjld-4.d.ts → index-nP13Qe6T.d.ts} +1 -1
  173. package/dist/{index-BJDXj9Wf.d.cts → index-p0bkNfby.d.cts} +3 -3
  174. package/dist/{index-aBqZUx3B.d.cts → index-wcfc7W-f.d.cts} +2 -2
  175. package/dist/{index-BwdPDWI4.d.cts → index-yJY9thRY.d.cts} +2 -2
  176. package/dist/{index-BbcSZCAG.d.ts → index-ygRFoyrN.d.ts} +2 -2
  177. package/dist/{index-Ip3q9T9x.d.ts → index-zA1uVtk0.d.ts} +1 -1
  178. package/dist/index.cjs +48 -48
  179. package/dist/index.d.cts +44 -44
  180. package/dist/index.d.ts +44 -44
  181. package/dist/index.js +1 -1
  182. package/dist/{meta-COtmHLwT.d.cts → meta-BdjSt8ky.d.cts} +1 -1
  183. package/dist/{meta-BMwx3ExI.d.ts → meta-CtDjj7cU.d.ts} +1 -1
  184. package/dist/{node-BVV7G1bq.d.cts → node-8qx0kgYt.d.cts} +49 -1
  185. package/dist/{node-BVV7G1bq.d.ts → node-8qx0kgYt.d.ts} +49 -1
  186. package/dist/{observable-BrUAPeH_.d.cts → observable-B6Ba-TTI.d.cts} +1 -1
  187. package/dist/{observable-ITikPXz3.d.ts → observable-DOniYM2B.d.ts} +1 -1
  188. package/dist/patterns/ai/browser.cjs +4 -4
  189. package/dist/patterns/ai/browser.d.cts +4 -4
  190. package/dist/patterns/ai/browser.d.ts +4 -4
  191. package/dist/patterns/ai/browser.js +1 -1
  192. package/dist/patterns/ai/index.cjs +19 -19
  193. package/dist/patterns/ai/index.d.cts +16 -16
  194. package/dist/patterns/ai/index.d.ts +16 -16
  195. package/dist/patterns/ai/index.js +1 -1
  196. package/dist/patterns/ai/node.cjs +2 -2
  197. package/dist/patterns/ai/node.d.cts +4 -4
  198. package/dist/patterns/ai/node.d.ts +4 -4
  199. package/dist/patterns/ai/node.js +1 -1
  200. package/dist/patterns/audit/index.cjs +7 -7
  201. package/dist/patterns/audit/index.d.cts +5 -5
  202. package/dist/patterns/audit/index.d.ts +5 -5
  203. package/dist/patterns/audit/index.js +1 -1
  204. package/dist/patterns/cqrs/index.cjs +3 -3
  205. package/dist/patterns/cqrs/index.d.cts +4 -4
  206. package/dist/patterns/cqrs/index.d.ts +4 -4
  207. package/dist/patterns/cqrs/index.js +1 -1
  208. package/dist/patterns/demo-shell/index.cjs +6 -6
  209. package/dist/patterns/demo-shell/index.d.cts +5 -5
  210. package/dist/patterns/demo-shell/index.d.ts +5 -5
  211. package/dist/patterns/demo-shell/index.js +1 -1
  212. package/dist/patterns/domain-templates/index.cjs +6 -6
  213. package/dist/patterns/domain-templates/index.d.cts +4 -4
  214. package/dist/patterns/domain-templates/index.d.ts +4 -4
  215. package/dist/patterns/domain-templates/index.js +1 -1
  216. package/dist/patterns/graphspec/index.cjs +8 -8
  217. package/dist/patterns/graphspec/index.d.cts +5 -5
  218. package/dist/patterns/graphspec/index.d.ts +5 -5
  219. package/dist/patterns/graphspec/index.js +1 -1
  220. package/dist/patterns/guarded-execution/index.cjs +7 -7
  221. package/dist/patterns/guarded-execution/index.d.cts +6 -6
  222. package/dist/patterns/guarded-execution/index.d.ts +6 -6
  223. package/dist/patterns/guarded-execution/index.js +1 -1
  224. package/dist/patterns/harness/index.cjs +12 -12
  225. package/dist/patterns/harness/index.d.cts +10 -9
  226. package/dist/patterns/harness/index.d.ts +10 -9
  227. package/dist/patterns/harness/index.js +1 -1
  228. package/dist/patterns/job-queue/index.cjs +7 -7
  229. package/dist/patterns/job-queue/index.d.cts +4 -4
  230. package/dist/patterns/job-queue/index.d.ts +4 -4
  231. package/dist/patterns/job-queue/index.js +1 -1
  232. package/dist/patterns/lens/index.cjs +5 -5
  233. package/dist/patterns/lens/index.d.cts +6 -6
  234. package/dist/patterns/lens/index.d.ts +6 -6
  235. package/dist/patterns/lens/index.js +1 -1
  236. package/dist/patterns/memory/index.cjs +4 -4
  237. package/dist/patterns/memory/index.d.cts +4 -4
  238. package/dist/patterns/memory/index.d.ts +4 -4
  239. package/dist/patterns/memory/index.js +1 -1
  240. package/dist/patterns/messaging/index.cjs +4 -4
  241. package/dist/patterns/messaging/index.d.cts +4 -4
  242. package/dist/patterns/messaging/index.d.ts +4 -4
  243. package/dist/patterns/messaging/index.js +1 -1
  244. package/dist/patterns/orchestration/index.cjs +4 -4
  245. package/dist/patterns/orchestration/index.d.cts +5 -5
  246. package/dist/patterns/orchestration/index.d.ts +5 -5
  247. package/dist/patterns/orchestration/index.js +1 -1
  248. package/dist/patterns/reactive-layout/index.cjs +1 -1
  249. package/dist/patterns/reactive-layout/index.d.cts +5 -5
  250. package/dist/patterns/reactive-layout/index.d.ts +5 -5
  251. package/dist/patterns/reactive-layout/index.js +1 -1
  252. package/dist/patterns/reduction/index.cjs +1 -1
  253. package/dist/patterns/reduction/index.d.cts +4 -4
  254. package/dist/patterns/reduction/index.d.ts +4 -4
  255. package/dist/patterns/reduction/index.js +1 -1
  256. package/dist/patterns/refine-loop/index.cjs +7 -7
  257. package/dist/patterns/refine-loop/index.d.cts +5 -5
  258. package/dist/patterns/refine-loop/index.d.ts +5 -5
  259. package/dist/patterns/refine-loop/index.js +1 -1
  260. package/dist/patterns/resilient-pipeline/index.cjs +1 -1
  261. package/dist/patterns/resilient-pipeline/index.d.cts +6 -6
  262. package/dist/patterns/resilient-pipeline/index.d.ts +6 -6
  263. package/dist/patterns/resilient-pipeline/index.js +1 -1
  264. package/dist/patterns/surface/index.cjs +7 -7
  265. package/dist/patterns/surface/index.d.cts +6 -6
  266. package/dist/patterns/surface/index.d.ts +6 -6
  267. package/dist/patterns/surface/index.js +1 -1
  268. package/dist/{reactive-layout-Bq0rA2Wb.d.ts → reactive-layout-DBJ3Vz-m.d.ts} +2 -2
  269. package/dist/{reactive-layout-Dhhe54Oj.d.cts → reactive-layout-Dk9AOQb_.d.cts} +2 -2
  270. package/dist/{reactive-log-5jFeNRmd.d.cts → reactive-log-CWC7jO4J.d.cts} +1 -1
  271. package/dist/{reactive-log-BOJDCI5x.d.ts → reactive-log-CqaBg8nf.d.ts} +1 -1
  272. package/dist/{reactive-map-IJIfZxoh.d.cts → reactive-map-Cm89Hk0c.d.cts} +1 -1
  273. package/dist/{reactive-map-CtRaCddO.d.ts → reactive-map-LjwjcFaW.d.ts} +1 -1
  274. package/dist/{resilience-IVNDYORD.js → resilience-7UZHSSGC.js} +1 -1
  275. package/dist/{resilience-Q6Bt_7y0.d.cts → resilience-N_VtLf7W.d.cts} +1 -1
  276. package/dist/{resilience-CludlzcP.d.ts → resilience-RjDIHZNZ.d.ts} +1 -1
  277. package/dist/{sugar-BHbAACDG.d.ts → sugar-CQkn_rxB.d.ts} +1 -1
  278. package/dist/{sugar-CqR6DJ7v.d.cts → sugar-DVEYhR7a.d.cts} +1 -1
  279. package/dist/{topology-tree-CpSjvIXp.d.cts → topology-tree-BB6oJxMz.d.cts} +1 -1
  280. package/dist/{topology-tree-DAbCV2Yw.d.ts → topology-tree-CAFOG5S5.d.ts} +1 -1
  281. package/dist/{types-CdfO2QTt.d.ts → types-B2LfBvNc.d.ts} +16 -2
  282. package/dist/{types-BgMqbc7N.d.cts → types-Cp_4coR_.d.cts} +16 -2
  283. package/package.json +1 -1
  284. package/dist/chunk-2JNT5NDF.js +0 -61
  285. package/dist/chunk-2RH4QNDQ.js +0 -1
  286. package/dist/chunk-7AJKUA36.js +0 -1
  287. package/dist/chunk-LG73TUF4.js +0 -43
  288. package/dist/chunk-ZWETYYQG.js +0 -1
@@ -1,5 +1,5 @@
1
- import { a as Node } from './node-BVV7G1bq.js';
2
- import { G as Graph } from './graph-BOhEGJ6E.js';
1
+ import { a as Node } from './node-8qx0kgYt.js';
2
+ import { G as Graph } from './graph-BROUZPG9.js';
3
3
 
4
4
  /** Pluggable measurement backend. */
5
5
  interface MeasurementAdapter {
@@ -1,5 +1,5 @@
1
- import { a as Node } from './node-BVV7G1bq.cjs';
2
- import { G as Graph } from './graph-CdJeX7O7.cjs';
1
+ import { a as Node } from './node-8qx0kgYt.cjs';
2
+ import { G as Graph } from './graph-DaoydJ_u.cjs';
3
3
 
4
4
  /** Pluggable measurement backend. */
5
5
  interface MeasurementAdapter {
@@ -1,4 +1,4 @@
1
- import { a as Node, V as VersioningLevel } from './node-BVV7G1bq.cjs';
1
+ import { a as Node, V as VersioningLevel } from './node-8qx0kgYt.cjs';
2
2
 
3
3
  type ReactiveLogOptions<T> = {
4
4
  name?: string;
@@ -1,4 +1,4 @@
1
- import { a as Node, V as VersioningLevel } from './node-BVV7G1bq.js';
1
+ import { a as Node, V as VersioningLevel } from './node-8qx0kgYt.js';
2
2
 
3
3
  type ReactiveLogOptions<T> = {
4
4
  name?: string;
@@ -1,4 +1,4 @@
1
- import { a as Node, V as VersioningLevel, N as NodeOptions } from './node-BVV7G1bq.cjs';
1
+ import { a as Node, V as VersioningLevel, N as NodeOptions } from './node-8qx0kgYt.cjs';
2
2
 
3
3
  type ReactiveMapOptions<K, V> = {
4
4
  /** Optional registry name for `describe()` / debugging. */
@@ -1,4 +1,4 @@
1
- import { a as Node, V as VersioningLevel, N as NodeOptions } from './node-BVV7G1bq.js';
1
+ import { a as Node, V as VersioningLevel, N as NodeOptions } from './node-8qx0kgYt.js';
2
2
 
3
3
  type ReactiveMapOptions<K, V> = {
4
4
  /** Optional registry name for `describe()` / debugging. */
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g,h,i,j,k,l}from"./chunk-RWGJQQLT.js";import"./chunk-ESMPEKEV.js";import"./chunk-4VVTGLXJ.js";import"./chunk-UMH3HSP7.js";import"./chunk-7AJKUA36.js";import"./chunk-CK2E7BTU.js";import"./chunk-QYADASLV.js";export{c as CircuitOpenError,g as RateLimiterOverflowError,j as TimeoutError,d as circuitBreaker,k as fallback,h as rateLimiter,a as retry,b as retrySource,l as timeout,f as tokenBucket,e as withBreaker,i as withStatus};
1
+ import{a,b,c,d,e,f,g,h,i,j,k,l}from"./chunk-FKRPIRE6.js";import"./chunk-ESMPEKEV.js";import"./chunk-4VVTGLXJ.js";import"./chunk-T7EQPKOP.js";import"./chunk-LYCLF26R.js";import"./chunk-CK2E7BTU.js";import"./chunk-QYADASLV.js";export{c as CircuitOpenError,g as RateLimiterOverflowError,j as TimeoutError,d as circuitBreaker,k as fallback,h as rateLimiter,a as retry,b as retrySource,l as timeout,f as tokenBucket,e as withBreaker,i as withStatus};
@@ -1,4 +1,4 @@
1
- import { a as Node } from './node-BVV7G1bq.cjs';
1
+ import { a as Node } from './node-8qx0kgYt.cjs';
2
2
 
3
3
  /**
4
4
  * Backoff strategies for {@link retry} (roadmap §3.1). Delays are in **nanoseconds**.
@@ -1,4 +1,4 @@
1
- import { a as Node } from './node-BVV7G1bq.js';
1
+ import { a as Node } from './node-8qx0kgYt.js';
2
2
 
3
3
  /**
4
4
  * Backoff strategies for {@link retry} (roadmap §3.1). Delays are in **nanoseconds**.
@@ -1,4 +1,4 @@
1
- import { N as NodeOptions, F as FnCtx, a as Node, c as NodeActions, d as NodeFnCleanup } from './node-BVV7G1bq.js';
1
+ import { N as NodeOptions, F as FnCtx, a as Node, c as NodeActions, d as NodeFnCleanup } from './node-8qx0kgYt.js';
2
2
 
3
3
  /**
4
4
  * Sugar constructors over the raw `node()` primitive.
@@ -1,4 +1,4 @@
1
- import { N as NodeOptions, F as FnCtx, a as Node, c as NodeActions, d as NodeFnCleanup } from './node-BVV7G1bq.cjs';
1
+ import { N as NodeOptions, F as FnCtx, a as Node, c as NodeActions, d as NodeFnCleanup } from './node-8qx0kgYt.cjs';
2
2
 
3
3
  /**
4
4
  * Sugar constructors over the raw `node()` primitive.
@@ -1,4 +1,4 @@
1
- import { G as Graph, T as TopologyEvent } from './graph-CdJeX7O7.cjs';
1
+ import { G as Graph, T as TopologyEvent } from './graph-DaoydJ_u.cjs';
2
2
 
3
3
  /**
4
4
  * Subscribe to structural changes across `graph` and every transitively
@@ -1,4 +1,4 @@
1
- import { G as Graph, T as TopologyEvent } from './graph-BOhEGJ6E.js';
1
+ import { G as Graph, T as TopologyEvent } from './graph-BROUZPG9.js';
2
2
 
3
3
  /**
4
4
  * Subscribe to structural changes across `graph` and every transitively
@@ -1,4 +1,4 @@
1
- import { a as Node } from './node-BVV7G1bq.js';
1
+ import { a as Node } from './node-8qx0kgYt.js';
2
2
  import { NodeInput } from './extra/sources.js';
3
3
 
4
4
  /**
@@ -309,7 +309,21 @@ type ToolDefinition = {
309
309
  readonly name: string;
310
310
  readonly description: string;
311
311
  readonly parameters: Record<string, unknown>;
312
- readonly handler: (args: Record<string, unknown>) => NodeInput<unknown>;
312
+ /**
313
+ * Handler invoked when the LLM requests this tool.
314
+ *
315
+ * The optional `opts.signal` fires when the reactive surface that owns
316
+ * this invocation is torn down (e.g. the agent's `switchMap` over
317
+ * `toolCalls` superseded with a fresh batch, the agent was aborted, or
318
+ * the parent graph destroyed). Signal-aware handlers should thread it
319
+ * into `fetch(url, {signal})`, child-process kill, DB cancel, etc., so
320
+ * in-flight side effects actually stop. Handlers that ignore the
321
+ * signal still work — but their work continues to completion regardless
322
+ * of supersede.
323
+ */
324
+ readonly handler: (args: Record<string, unknown>, opts?: {
325
+ signal?: AbortSignal;
326
+ }) => NodeInput<unknown>;
313
327
  /**
314
328
  * V0 version of the backing node at tool-definition-creation time.
315
329
  * Snapshot — re-create the tool definition to refresh.
@@ -1,4 +1,4 @@
1
- import { a as Node } from './node-BVV7G1bq.cjs';
1
+ import { a as Node } from './node-8qx0kgYt.cjs';
2
2
  import { NodeInput } from './extra/sources.cjs';
3
3
 
4
4
  /**
@@ -309,7 +309,21 @@ type ToolDefinition = {
309
309
  readonly name: string;
310
310
  readonly description: string;
311
311
  readonly parameters: Record<string, unknown>;
312
- readonly handler: (args: Record<string, unknown>) => NodeInput<unknown>;
312
+ /**
313
+ * Handler invoked when the LLM requests this tool.
314
+ *
315
+ * The optional `opts.signal` fires when the reactive surface that owns
316
+ * this invocation is torn down (e.g. the agent's `switchMap` over
317
+ * `toolCalls` superseded with a fresh batch, the agent was aborted, or
318
+ * the parent graph destroyed). Signal-aware handlers should thread it
319
+ * into `fetch(url, {signal})`, child-process kill, DB cancel, etc., so
320
+ * in-flight side effects actually stop. Handlers that ignore the
321
+ * signal still work — but their work continues to completion regardless
322
+ * of supersede.
323
+ */
324
+ readonly handler: (args: Record<string, unknown>, opts?: {
325
+ signal?: AbortSignal;
326
+ }) => NodeInput<unknown>;
313
327
  /**
314
328
  * V0 version of the backing node at tool-definition-creation time.
315
329
  * Snapshot — re-create the tool definition to refresh.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@graphrefly/graphrefly",
3
- "version": "0.32.0",
3
+ "version": "0.33.0",
4
4
  "packageManager": "pnpm@10.33.0+sha512.10568bb4a6afb58c9eb3630da90cc9516417abebd3fabbe6739f0ae795728da1491e9db5a544c76ad8eb7570f5c4bb3d6c637b2cb41bfdcdb47fa823c8649319",
5
5
  "description": "Reactive harness layer for agent workflows. Describe automations in plain language, trace every decision, enforce policies, persist checkpoints. Zero dependencies.",
6
6
  "repository": {
@@ -1,61 +0,0 @@
1
- import{a as Pe,b as Fe,d as je,e as Ge}from"./chunk-TOCCHQI6.js";import{e as wt}from"./chunk-ZWETYYQG.js";import{h as Lt}from"./chunk-7JZ3YORY.js";import{e as Ze}from"./chunk-VXJX3ZZP.js";import{a as qt,b as Xt,c as Zt,d as er,e as tr,f as Xe,g as rr}from"./chunk-PNTBXOQ6.js";import{a as Je,b as ee,c as _e,d as fe,e as se,f as te,g as zt,h as Qe,i as Yt,j as Jt,k as Qt}from"./chunk-FTA5TB2A.js";import{c as Mt}from"./chunk-K54OKWNY.js";import{b as xt}from"./chunk-7QMVU3IX.js";import{b as yt,c as Oe,d as ht,f as Ye}from"./chunk-RWGJQQLT.js";import{b as De}from"./chunk-LWGLBCMU.js";import{b as ve}from"./chunk-XRSHMHEG.js";import{j as ce}from"./chunk-4JBKKUCJ.js";import{a as ae}from"./chunk-ESMPEKEV.js";import{R as Rt,s as kt,x as z}from"./chunk-WQ7I7JVU.js";import{B as V,f as bt,m as x,w as ue,y as Tt,z as vt}from"./chunk-UMH3HSP7.js";import{D as pe,E as w,F as Te,G as k,H as ne,m as Z,o as re,p as Ne}from"./chunk-7AJKUA36.js";import{b as Q,d as be,i as le,j as X}from"./chunk-CK2E7BTU.js";import{b as Ht}from"./chunk-QYADASLV.js";var on={};Ht(on,{AgentLoopGraph:()=>ze,AllTiersExhaustedError:()=>tr,BudgetExhaustedError:()=>We,ChatStreamGraph:()=>He,CircuitOpenError:()=>Oe,DEFAULT_DECAY_RATE:()=>Ce,FallbackMissError:()=>Jt,LLMTimeoutError:()=>ke,ReplayCacheMissError:()=>zt,ToolRegistryGraph:()=>qe,admissionFilter3D:()=>Vr,admissionScored:()=>Gt,agentLoop:()=>$r,agentMemory:()=>Ur,anthropicAdapter:()=>qt,canonicalJson:()=>Yt,cascadingLlmAdapter:()=>Xe,chatStream:()=>ut,composePricing:()=>lr,computePrice:()=>et,contentGate:()=>jr,costMeterExtractor:()=>Ir,createAdapter:()=>er,createCapabilitiesRegistry:()=>nr,createPricingRegistry:()=>sr,dryRunAdapter:()=>Je,fallbackAdapter:()=>Qt,fromLLM:()=>Mr,frozenContext:()=>Lr,gatedStream:()=>Sr,gaugesAsContext:()=>Qr,googleAdapter:()=>Xt,graphFromSpec:()=>Wt,graphFromSpecReactive:()=>Xr,handoff:()=>Wr,keywordFlagExtractor:()=>Dr,knobsAsTools:()=>en,llmConsolidator:()=>pt,llmExtractor:()=>mt,memoryRetrieval:()=>Jr,memoryWithKG:()=>qr,memoryWithTiers:()=>zr,memoryWithVectors:()=>Hr,observableAdapter:()=>or,openAICompatAdapter:()=>Zt,parseRateLimitFromError:()=>ot,pricingFor:()=>dr,promptNode:()=>dt,redactor:()=>Gr,registryPricing:()=>ir,resilientAdapter:()=>vr,streamExtractor:()=>_r,streamingPromptNode:()=>Ar,suggestStrategy:()=>Kt,suggestStrategyReactive:()=>rn,systemPromptBuilder:()=>Cr,tier:()=>rr,toolCallExtractor:()=>Fr,toolRegistry:()=>ct,toolSelector:()=>Kr,validateGraphDef:()=>nn,withBreaker:()=>tt,withBudgetGate:()=>nt,withDryRun:()=>cr,withRateLimiter:()=>st,withReplayCache:()=>Qe,withRetry:()=>it,withTimeout:()=>lt,zeroPrice:()=>$e});function Ae(r,e){return`${r}::${e}`}function nr(r){let e=De({name:"capabilitiesRegistry"}),t=i=>{e.set(Ae(i.provider,i.id),i)};if(r)for(let i of r)t(i);let n=(i,d)=>{let c=e.get(Ae(i,d));if(c)return c;let m=e.entries.cache;if(!m)return;let p;for(let[,h]of m){if(h.provider!==i)continue;let g=h.id;d.startsWith(g)&&(!p||g.length>p.id.length)&&(p=h)}return p},o=128,a=new Map,s=new Map,l=(i,d,c,m)=>{for(i.has(d)&&i.delete(d),i.set(d,c);i.size>m;){let p=i.keys().next().value;if(p===void 0)break;i.delete(p)}},u=k([e.entries],([i])=>Array.from(i.values()),{name:"capabilitiesRegistry/entries",initial:[]});return{register:t,lookup:n,remove(i,d){let c=e.has(Ae(i,d));return c&&e.delete(Ae(i,d)),c},entries(){let i=e.entries.cache;return(function*(){if(i)for(let d of i.values())yield d})()},lookupNode(i,d){let c=Ae(i,d),m=a.get(c);if(m)return a.delete(c),a.set(c,m),m;let p=k([e.entries],()=>n(i,d),{name:`capabilitiesRegistry/lookup/${i}::${d}`,initial:void 0});return l(a,c,p,o),p},entriesNode:u,byProvider(i){let d=s.get(i);if(d)return s.delete(i),s.set(i,d),d;let c=k([u],([m])=>m.filter(p=>p.provider===i),{name:`capabilitiesRegistry/byProvider/${i}`,initial:[]});return l(s,i,c,o),c}}}function oe(r){let e=r.input,t=e.regular+(e.cacheRead??0)+(e.cacheWrite5m??0)+(e.cacheWrite1h??0)+(e.cacheWriteOther??0)+(e.audio??0)+(e.image??0)+(e.video??0)+(e.toolUse??0);if(!e.extensions)return t;let n=0;for(let o of Object.values(e.extensions))n+=o;return t+n}function de(r){let e=r.output,t=e.regular+(e.reasoning??0)+(e.audio??0)+(e.predictionAccepted??0)+(e.predictionRejected??0);if(!e.extensions)return t;let n=0;for(let o of Object.values(e.extensions))n+=o;return t+n}function Nt(){return{input:{regular:0},output:{regular:0}}}function or(r,e){let t=e?.logMax??1e3,n=ve(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:t}),o=w(null,{name:"adapterStats/lastCall"}),a=k([n.entries],([g])=>g.length,{name:"adapterStats/totalCalls",initial:0}),s=k([n.entries],([g])=>g.reduce((f,b)=>f+oe(b.usage),0),{name:"adapterStats/totalInputTokens",initial:0}),l=k([n.entries],([g])=>g.reduce((f,b)=>f+de(b.usage),0),{name:"adapterStats/totalOutputTokens",initial:0}),u=[V(a),V(s),V(l)],i=g=>{n.append(g),o.emit(g)},d=()=>{n.clear(),o.emit(null)},c=ee(r,{invoke(g,f){let b=re(),M=Ne(),v=r.model??f?.model??"",L=A=>(i(fe({provider:r.provider,model:r.model??f?.model??A.model??"",tier:f?.tier??A.tier,usage:A.usage??se(),startNs:b,startWallClockNs:M,method:"invoke"})),A),R=A=>{let G=A;i(fe({provider:r.provider,model:v,tier:f?.tier,usage:se(),startNs:b,startWallClockNs:M,method:"invoke",error:{type:G?.name??"Error",message:G?.message??String(A)}}))};return _e(r.invoke(g,f),{onResp:L,onError:R,name:"adapterStats/invokeTap"})},async*stream(g,f){let b=re(),M=Ne(),v=r.model??f?.model??"",L;try{for await(let R of r.stream(g,f))R.type==="usage"&&(L=R.usage),yield R;i(fe({provider:r.provider,model:v,tier:f?.tier,usage:L??se(),startNs:b,startWallClockNs:M,method:"stream"}))}catch(R){let A=R;throw i(fe({provider:r.provider,model:v,tier:f?.tier,usage:L??se(),startNs:b,startWallClockNs:M,method:"stream",error:{type:A?.name??"Error",message:A?.message??String(R)}})),R}}});te(c,"observableAdapter",r);let m=!1;return{adapter:c,stats:{lastCall:o,allCalls:n,totalCalls:a,totalInputTokens:s,totalOutputTokens:l,reset:d,dispose:()=>{if(!m){m=!0;for(let g of u)g();u.length=0}}}}}function ar(r,e){return r==null?0:typeof r=="number"?r:r.thresholdTokens!=null&&r.pricePerMillionAbove!=null&&e>r.thresholdTokens?r.pricePerMillionAbove:r.pricePerMillion}function $e(r="USD"){return{total:0,currency:r}}function et(r,e,t){let n=oe(r),o=e.currency??"USD",a=t?.withBreakdown===!0,s=a?{}:null,l=0,u=(f,b,M)=>{if(!b||M==null)return;let v=ar(M,n),L=b*v/1e6;l+=L,a&&(s[f]=(s[f]??0)+L)},i=r.input,d=e.input;if(d&&(u("input.regular",i.regular,d.regular),u("input.cacheRead",i.cacheRead??0,d.cacheRead),u("input.cacheWrite5m",i.cacheWrite5m??0,d.cacheWrite5m),u("input.cacheWrite1h",i.cacheWrite1h??0,d.cacheWrite1h),u("input.cacheWriteOther",i.cacheWriteOther??0,d.cacheWriteOther),u("input.audio",i.audio??0,d.audio),u("input.image",i.image??0,d.image),u("input.video",i.video??0,d.video),u("input.toolUse",i.toolUse??0,d.toolUse),i.extensions&&d.extensions))for(let[f,b]of Object.entries(i.extensions))u(`input.ext.${f}`,b,d.extensions[f]);let c=r.output,m=e.output;if(m&&(u("output.regular",c.regular,m.regular),u("output.reasoning",c.reasoning??0,m.reasoning),u("output.audio",c.audio??0,m.audio),u("output.predictionAccepted",c.predictionAccepted??0,m.predictionAccepted),u("output.predictionRejected",c.predictionRejected??0,m.predictionRejected),c.extensions&&m.extensions))for(let[f,b]of Object.entries(c.extensions))u(`output.ext.${f}`,b,m.extensions[f]);let p=t?.tier;if(p&&e.tierMultipliers){let f=e.tierMultipliers[p];if(f!=null&&(l*=f,a))for(let b of Object.keys(s))s[b]*=f}let h=r.auxiliary,g=e.auxiliary;if(h&&g)for(let[f,b]of Object.entries(h)){let M=g[f];if(M==null||!b)continue;let v=b*M;l+=v,a&&(s[`auxiliary.${f}`]=v)}return a?{total:l,currency:o,breakdown:s}:{total:l,currency:o}}function Be(r,e){return`${r}::${e}`}function sr(r){let e=new Map,t=new Map,n=(o,a,s)=>{e.set(Be(o,a),{provider:o,model:a,pricing:s});let l=t.get(o);l||(l=new Set,t.set(o,l)),l.add(a)};if(r)for(let[o,a,s]of r)n(o,a,s);return{register:n,lookup(o,a){let s=e.get(Be(o,a));if(s)return s.pricing;let l=t.get(o);if(!l)return;let u;for(let i of l)if(a.startsWith(i)&&(!u||i.length>u.key.length)){let d=e.get(Be(o,i));d&&(u={key:i,pricing:d.pricing})}return u?.pricing},remove(o,a){let s=e.delete(Be(o,a));if(s){let l=t.get(o);l?.delete(a),l&&l.size===0&&t.delete(o)}return s},entries(){let o=e.values();return(function*(){for(let{provider:a,model:s,pricing:l}of o)yield[a,s,l]})()}}}function ir(r,e="USD"){return(t,n)=>{let o=r.lookup(n.provider,n.model);return o?et(t,o,{tier:n.tier,withBreakdown:n.withBreakdown}):$e(e)}}function lr(...r){return(e,t)=>{for(let n of r){let o=n(e,t);if(o.total!==0)return o}return r.length>0?r[0](e,t):$e()}}function dr(r,e,t){return r?.pricing?et(e,r.pricing,t):$e()}function tt(r,e={}){let t=e.breaker??ht(e),n=ee(r,{async invoke(o,a){if(!t.canExecute())throw new Oe;try{let s=await ue(x(r.invoke(o,a)));return t.recordSuccess(),s}catch(s){throw t.recordFailure(s),s}},async*stream(o,a){if(!t.canExecute())throw new Oe;try{for await(let s of r.stream(o,a))yield s;t.recordSuccess()}catch(s){throw t.recordFailure(s),s}}});return te(n,"withBreaker",r),{adapter:n,breaker:t}}var We=class extends Error{constructor(t,n,o){super(`Budget exhausted: ${t} (limit=${n}, observed=${o})`);this.which=t;this.limit=n;this.observed=o}name="BudgetExhaustedError"},rt=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),At=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function nt(r,e){let t=ve(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),n=w(At(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=k([n],([i])=>{let d=i;return!(e.caps.calls!=null&&d.calls>=e.caps.calls||e.caps.inputTokens!=null&&d.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&d.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&d.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(V(o),e.onExhausted!=null){let i=e.onExhausted,d=!1,c=!0;o.subscribe(m=>{for(let p of m)if(p[0]===Q){let h=p[1];if(d&&c&&h===!1){let g=St(n.cache??rt,e.caps);g&&i(g)}c=h,d=!0}})}let a=()=>{if(o.cache===!1){let i=n.cache??rt,d=St(i,e.caps);return new We(d??"budget",e.caps[d??"calls"]??0,ur(i,d??"calls"))}},s=(i,d)=>{let c=r.provider,m=fe({provider:c,model:d.model,tier:d.tier,usage:i,startNs:d.startNs,method:d.method,...d.error?{error:d.error}:{}});t.append(m);let p=n.cache??rt,h=e.pricingFn?p.usd+e.pricingFn(i,{model:d.model,provider:c,tier:d.tier}).total:p.usd;n.emit({calls:p.calls+1,inputTokens:p.inputTokens+oe(i),outputTokens:p.outputTokens+de(i),usd:h})},l=()=>{t.clear(),n.emit(At())},u=ee(r,{invoke(i,d){let c=a();if(c)return Promise.reject(c);let m=re(),p=r.model??d?.model??"",h=f=>(s(f.usage??se(),{model:r.model??d?.model??f.model??"",tier:d?.tier??f.tier,startNs:m,method:"invoke"}),f),g=f=>{let b=f;s(se(),{model:p,tier:d?.tier,startNs:m,method:"invoke",error:{type:b?.name??"Error",message:b?.message??String(f)}})};return _e(r.invoke(i,d),{onResp:h,onError:g,name:"budgetGate/invokeTap"})},async*stream(i,d){let c=a();if(c)throw c;let m=re(),p;try{for await(let h of r.stream(i,d))h.type==="usage"&&(p=h.usage),yield h;s(p??se(),{model:r.model??d?.model??"",tier:d?.tier,startNs:m,method:"stream"})}catch(h){let g=h;throw s(p??se(),{model:r.model??d?.model??"",tier:d?.tier,startNs:m,method:"stream",error:{type:g?.name??"Error",message:g?.message??String(h)}}),h}}});return te(u,"withBudgetGate",r),{adapter:u,budget:{totals:n,isOpen:o,log:t,reset:l}}}function St(r,e){if(e.calls!=null&&r.calls>=e.calls)return"calls";if(e.inputTokens!=null&&r.inputTokens>=e.inputTokens)return"inputTokens";if(e.outputTokens!=null&&r.outputTokens>=e.outputTokens)return"outputTokens";if(e.usd!=null&&r.usd>=e.usd)return"usd"}function ur(r,e){switch(e){case"calls":return r.calls;case"inputTokens":return r.inputTokens;case"outputTokens":return r.outputTokens;case"usd":return r.usd}}function cr(r,e){let t=e.mock??Je({provider:r.provider,model:r.model}),n=typeof e.enabled=="boolean"?e.enabled:void 0,o=n===void 0?x(e.enabled):void 0,a;o&&(a=V(o));let s=()=>n!==void 0?n:!!o?.cache,l=ee(r,{invoke(i,d){return s()?t.invoke(i,d):r.invoke(i,d)},stream(i,d){return s()?t.stream(i,d):r.stream(i,d)}});return te(l,"withDryRun",r),{adapter:l,dispose:()=>{a&&(a(),a=void 0)}}}function ot(r){if(r==null||typeof r!="object")return;let e=r,t=e.status,n=mr(e.headers);if(t!==429&&t!==503&&!br(e.message))return;let o={},a=n("retry-after"),s=fr(a);s!=null&&(o.retryAfterMs=s);let l=n("anthropic-ratelimit-requests-reset");if(l){let p=Ct(l);p!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,p))}let u=n("anthropic-ratelimit-tokens-reset");if(u){let p=Ct(u);p!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,p))}let i=Ke(n,"x-ratelimit-limit-requests");i!=null&&(o.rpmCap=i);let d=Ke(n,"x-ratelimit-limit-tokens");d!=null&&(o.tpmCap=d);let c=Ke(n,"x-ratelimit-remaining-requests"),m=Ke(n,"x-ratelimit-remaining-tokens");if(c!=null&&i!=null&&i>0&&(o.usageHint??={},o.usageHint.rpm=1-c/i),m!=null&&d!=null&&d>0&&(o.usageHint??={},o.usageHint.tpm=1-m/d),o.retryAfterMs==null&&e.message){let p=yr(e.message);p!=null&&(o.retryAfterMs=p)}return e.headers&&(o.metadata={headers:pr(e.headers)}),o.retryAfterMs==null&&o.rpmCap==null&&o.tpmCap==null&&o.usageHint==null?o.metadata?o:void 0:o}function mr(r){if(!r)return()=>{};if(typeof r.get=="function"){let n=r;return o=>n.get(o)??n.get(o.toLowerCase())??void 0}let e=r,t={};for(let[n,o]of Object.entries(e)){let a=Array.isArray(o)?o.join(", "):o;a!=null&&(t[n.toLowerCase()]=a)}return n=>t[n.toLowerCase()]}function pr(r){let e={};if(typeof r.forEach=="function")return r.forEach((t,n)=>{e[n]=t}),e;for(let[t,n]of Object.entries(r))n!=null&&(e[t]=Array.isArray(n)?n.join(", "):n);return e}function Ke(r,e){let t=r(e);if(t==null)return;let n=Number(t);return Number.isFinite(n)?n:void 0}function fr(r){if(!r)return;let e=r.trim(),t=Number(e);if(Number.isFinite(t)&&t>=0)return t*1e3;let n=Date.parse(e);if(Number.isFinite(n)){let o=n-Date.now();if(o>0)return o}}function Ct(r){if(!r)return;let e=Date.parse(r);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var gr=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function yr(r){let e=gr.exec(r);if(!e)return;let t=Number(e[1]);if(!Number.isFinite(t))return;let n=(e[2]??"s").toLowerCase();if(n==="ms")return t;if(n.startsWith("s"))return t*1e3;if(n.startsWith("m"))return t*6e4}var hr=/rate\s*limit|too\s*many\s*requests|quota|429/i;function br(r){return!!r&&hr.test(r)}function at(r){let e=new Error(r);return e.name="AbortError",e}function It(r={}){let e=Math.max(1,r.burstMultiplier??1),t=r.clampCooldownMs??6e4,n=r.rpm!=null?x(r.rpm):w(Number.POSITIVE_INFINITY),o=r.tpm!=null?x(r.tpm):w(Number.POSITIVE_INFINITY),a=w(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),s=w(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),l=w({},{name:"adaptiveRateLimiter/lastSignal"}),u=k([n,a],([N,D])=>Math.min(Number(N??1/0),Number(D??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),i=k([o,s],([N,D])=>Math.min(Number(N??1/0),Number(D??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),d=Me(Number(n.cache??Number.POSITIVE_INFINITY),e),c=Me(Number(o.cache??Number.POSITIVE_INFINITY),e),m=!1,p=!1,h=u.subscribe(N=>{for(let D of N)if(D[0]===Q){let F=Number(D[1]);Number.isFinite(F)&&F>0?(d=Me(F,e),m=!1):F===1/0?(d=Me(1/0,e),m=!1):F<=0&&(m=!0)}}),g=i.subscribe(N=>{for(let D of N)if(D[0]===Q){let F=Number(D[1]);Number.isFinite(F)&&F>0?(c=Me(F,e),p=!1):F===1/0?(c=Me(1/0,e),p=!1):F<=0&&(p=!0)}}),f=0,b=new ae,M=new ae,v;r.adaptation!=null&&(v=x(r.adaptation).subscribe(D=>{for(let F of D)F[0]===Q&&L(F[1])}));function L(N){if(l.emit(N),N.rpmCap!=null&&Number.isFinite(N.rpmCap)&&N.rpmCap>=0&&(a.emit(N.rpmCap),Number.isFinite(t)&&t>0&&b.start(t,()=>a.emit(Number.POSITIVE_INFINITY))),N.tpmCap!=null&&Number.isFinite(N.tpmCap)&&N.tpmCap>=0&&(s.emit(N.tpmCap),Number.isFinite(t)&&t>0&&M.start(t,()=>s.emit(Number.POSITIVE_INFINITY))),N.retryAfterMs!=null&&N.retryAfterMs>0){let D=re()+N.retryAfterMs*1e6;D>f&&(f=D)}}let R=w(0,{name:"adaptiveRateLimiter/pending"}),A=w(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),G=w(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),W=N=>{R.emit((R.cache??0)+N)},I=()=>{A.emit(d.available()),G.emit(c.available())};async function O(N={}){let D=N.requestCost??1,F=N.tokenCost??0,Y=N.signal;W(1);try{for(;;){if(Y?.aborted)throw at("AdaptiveRateLimiter.acquire aborted");let P=re();if(f>P){let B=Math.ceil((f-P)/1e6);await Ve(B,Y);continue}if(D>0&&m||F>0&&p){await Ve(250,Y);continue}let T=d,y=c;if(!T.tryConsume(D)){await Ve(Et(T,D),Y);continue}if(!(F>0?y.tryConsume(F):!0)){T.putBack(D),await Ve(Et(y,F),Y);continue}I();return}}finally{W(-1)}}function S(N){N>0?c.tryConsume(N):N<0&&c.putBack(-N),I()}function _(){h(),g(),v?.(),b.cancel(),M.cancel()}return{effectiveRpm:u,effectiveTpm:i,lastSignal:l,pending:R,rpmAvailable:A,tpmAvailable:G,acquire:O,recordUsage:S,recordSignal:L,dispose:_}}function Me(r,e){if(!Number.isFinite(r)||r===1/0)return Ye(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let t=Math.max(1,r*e),n=r/60;return Ye(t,n)}function Et(r,e){let t=r.available(),n=Math.max(0,e-t);return n<=0?25:Math.min(5e3,Math.max(50,n*100))}function Ve(r,e){return r<=0?Promise.resolve():e?.aborted?Promise.reject(at("AdaptiveRateLimiter.acquire aborted")):new Promise((t,n)=>{let o=new ae,a,s=()=>{o.cancel(),e&&a&&e.removeEventListener("abort",a)};o.start(r,()=>{s(),t()}),e&&(a=()=>{s(),n(at("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",a,{once:!0}))})}function st(r,e={}){let t=e.limiter??It({name:e.name??"rateLimiter",rpm:e.rpm,tpm:e.tpm,adaptation:e.adaptation,burstMultiplier:e.burstMultiplier}),n=(s,l)=>e.costFn?e.costFn(s,l):0,o=s=>{let l=ot(s);l&&t.recordSignal(l)},a=ee(r,{async invoke(s,l){let u=n(s,l);await t.acquire({requestCost:1,tokenCost:u,signal:l?.signal});try{let i=await ue(x(r.invoke(s,l))),d=i.usage??Nt(),m=oe(d)+de(d)-u;return m>0&&t.recordUsage(m),i}catch(i){throw o(i),i}},async*stream(s,l){let u=n(s,l);await t.acquire({requestCost:1,tokenCost:u,signal:l?.signal});try{let i=0;for await(let c of r.stream(s,l))c.type==="usage"&&(i=oe(c.usage)+de(c.usage)),yield c;let d=i-u;d>0&&t.recordUsage(d)}catch(i){throw o(i),i}}});return te(a,"withRateLimiter",r),{adapter:a,limiter:t}}function Ue(r="aborted"){let e=new Error(r);return e.name="AbortError",e}function Ot(r,e){return r<=0?Promise.resolve():e?.aborted?Promise.reject(Ue()):new Promise((t,n)=>{let o=new ae,a,s=()=>{o.cancel(),e&&a&&e.removeEventListener("abort",a)};o.start(r,()=>{s(),t()}),e&&(a=()=>{s(),n(Ue())},e.addEventListener("abort",a,{once:!0}))})}function it(r,e={}){let t=e.attempts??3,n=e.baseDelayMs??500,o=e.maxDelayMs??1e4,a=e.strategy??"decorrelated",s=e.jitter??!0,l=e.shouldRetry??Tr,u=e.retryStreaming??!0,i=(c,m)=>{if(a==="decorrelated"){let f=Math.min(o,Math.max(n,m*3));return n+Math.random()*(f-n)}let p=a==="exp"?n*2**(c-1):n*c,h=Math.min(o,p);if(!s)return h;let g=h*(.5+Math.random());return Math.min(o,g)},d=ee(r,{async invoke(c,m){if(m?.signal?.aborted)throw Ue();let p,h=n;for(let g=1;g<=t;g++)try{return await ue(x(r.invoke(c,m)))}catch(f){if(p=f,g>=t||!l(f,g))throw f;let b=i(g,h);h=b,await Ot(b,m?.signal)}throw p},async*stream(c,m){if(m?.signal?.aborted)throw Ue();if(!u){for await(let g of r.stream(c,m))yield g;return}let p,h=n;for(let g=1;g<=t;g++){let f=!1;try{for await(let b of r.stream(c,m))f=!0,yield b;return}catch(b){if(p=b,f||g>=t||!l(b,g))throw b;let M=i(g,h);h=M,await Ot(M,m?.signal)}}throw p}});return te(d,"withRetry",r),d}function Tr(r,e){if(r==null)return!1;let t=r;return t.name==="LLMTimeoutError"?!0:t.name==="AbortError"||t.message==="aborted"||t.name==="DOMException"&&t.code!=null&&Number(t.code)===20||t.name==="BudgetExhaustedError"||t.name==="CircuitOpenError"?!1:t.status!=null?t.status===429||t.status>=500&&t.status<600:t.code&&typeof t.code=="string"&&/^E[A-Z]+$/.test(t.code)?!0:t.message?/network|timeout|socket|fetch|econn|eai_/i.test(t.message):!1}var ke=class extends Error{constructor(t){super(`LLM call timed out after ${t}ms`);this.ms=t}name="LLMTimeoutError"};function lt(r,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let t=a=>{let s=new AbortController,l=!1,u,i=new ae;return a&&(a.aborted?s.abort(a.reason):(u=()=>{i.cancel(),s.abort(a.reason)},a.addEventListener("abort",u,{once:!0}))),i.start(e,()=>{l=!0,s.abort(new ke(e))}),{signal:s.signal,cancel:()=>{i.cancel(),a&&u&&a.removeEventListener("abort",u)},timedOut:()=>l}},n=(a,s)=>{if(!s||a instanceof ke)throw a;let l=a;if(l?.name==="AbortError"||l?.name==="DOMException"&&Number(l.code)===20||a?.message==="aborted"){let i=new ke(e);throw i.cause=a,i}throw a},o=ee(r,{async invoke(a,s){let{signal:l,cancel:u,timedOut:i}=t(s?.signal);try{return await ue(x(r.invoke(a,{...s,signal:l})))}catch(d){return n(d,i())}finally{u()}},async*stream(a,s){let{signal:l,cancel:u,timedOut:i}=t(s?.signal);try{for await(let d of r.stream(a,{...s,signal:l}))yield d}catch(d){n(d,i())}finally{u()}}});return te(o,"withTimeout",r),o}function vr(r,e={}){let t={adapter:r},n=r;if(e.rateLimit){let o=st(n,e.rateLimit);n=o.adapter,t.rateLimiter=o.limiter}if(e.budget){let o=nt(n,e.budget);n=o.adapter,t.budget=o.budget}if(e.breaker){let o=tt(n,e.breaker);n=o.adapter,t.breaker=o.breaker}if(e.timeoutMs!=null&&(n=lt(n,e.timeoutMs)),e.retry&&(n=it(n,e.retry)),e.fallback){if(e.name==="fallback")throw new RangeError('resilientAdapter: `name` cannot be "fallback" \u2014 collides with the secondary tier label.');let o={};e.onFallback&&(o.onFallback=e.onFallback),e.onExhausted&&(o.onExhausted=e.onExhausted),n=Xe([{name:e.name??"primary",adapter:n},{name:"fallback",adapter:e.fallback}],o)}return e.cache&&(n=Qe(n,e.cache)),t.adapter=n,t}function Mr(r,e,t){let n=x(e);return z(n,a=>{if(!a||a.length===0)return w(null);let s=t?.tools;return r.invoke(a,{model:t?.model,temperature:t?.temperature,maxTokens:t?.maxTokens,tools:s,systemPrompt:t?.systemPrompt})})}function C(r,e){return Mt("ai",r,e)}function kr(r){return r!=null&&typeof r.then=="function"}function Rr(r){return typeof r=="object"&&r!==null&&"subscribe"in r&&typeof r.subscribe=="function"&&"cache"in r}function xr(r){return r!=null&&typeof r=="object"&&Symbol.asyncIterator in r&&typeof r[Symbol.asyncIterator]=="function"}var wr=3e4;function Dt(r,e){if(r.status==="settled"){let n=r.cache;if(n!==void 0)return Promise.resolve(n)}let t=e?.timeoutMs??wr;return new Promise((n,o)=>{let a=new ae,s=r.subscribe(l=>{for(let u of l){if(u[0]===Q){a.cancel(),s(),n(u[1]);return}if(u[0]===X){a.cancel(),s(),o(u[1]);return}if(u[0]===le){a.cancel(),s(),o(new Error("firstDataFromNode: completed without producing a value"));return}}});a.start(t,()=>{s(),o(new Error(`firstDataFromNode: timed out after ${t}ms`))})})}async function ge(r){return kr(r)?ge(await r):Rr(r)?Dt(r):xr(r)?Dt(x(r)):r}function Re(r){let e=r.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:r}function Lr(r,e){let t=x(r),n=e?.refreshTrigger!=null?x(e.refreshTrigger):null;return n==null?pe([t],(o,a,s)=>{if(s.store.emitted===!0)return;let u=o[0],i=u!=null&&u.length>0?u.at(-1):s.prevData[0];if(i!==void 0)return s.store.emitted=!0,a.emit(i),{invalidate:()=>{s.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:C("frozen_context")}):pe([t,n],(o,a,s)=>{let l=o[1];if(!(l!=null&&l.length>0))return;let i=o[0],d=i!=null&&i.length>0?i.at(-1):s.prevData[0];a.emit(d)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:C("frozen_context")})}function _t(r){return r!=null&&typeof r=="object"&&"content"in r?String(r.content):typeof r=="string"?r:String(r)}function Nr(r,e=200){return r.length<=e?r:`${r.slice(0,e)}\u2026`}function dt(r,e,t,n){let o=n?.format??"text",a=n?.name??"prompt_node",s=k(e,u=>{if(u.some(d=>d==null))return[];let i=typeof t=="string"?t:t(...u);return i?[{role:"user",content:i}]:[]},{name:`${a}::messages`,meta:C("prompt_node")});return z(s,u=>!u||u.length===0?w(null):Te(i=>{let d=!1,c=!1,m,p={model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,systemPrompt:n?.systemPrompt};if(n?.abort){let b=vt(n.abort);p.signal=b.signal,m=b.dispose}let h;try{h=r.invoke(u,p)}catch(b){return d=!0,i.down([[X,b]]),()=>{m?.()}}let f=x(h).subscribe(b=>{if(!(c||d))for(let M of b){if(d)return;if(M[0]===Q){let v=M[1];try{let L=_t(v),R=o==="json"?JSON.parse(Re(L)):L;i.emit(R)}catch(L){let R=_t(v),A=new Error(`promptNode: failed to parse LLM response as JSON: ${L.message}
2
- Raw content (first 200 chars): ${Nr(R)}`);d=!0,i.down([[X,A]]);return}}else if(M[0]===X){d=!0,i.down([[X,M[1]]]);return}else if(M[0]===le){d=!0,i.down([[le]]);return}else i.down([M])}});return()=>{c=!0,f(),m?.()}},{name:`${a}::call`,meta:C("prompt_node::call")}),{name:`${a}::output`,meta:n?.meta?{...C("prompt_node::output"),...n.meta}:C("prompt_node::output")})}async function Pt(r,e,t,n){let o="",a=0;for await(let s of r.stream(e,t))n.publish({...s,seq:a++,ts:Ne()}),s.type==="token"&&(o+=s.delta);return o}function Ft(r,e){if(e==="json")try{return JSON.parse(Re(r))}catch(t){let n=r.slice(0,160);throw new Error(`streamingPromptNode: format:"json" \u2014 failed to parse accumulated text as JSON: ${t.message}; content preview: ${n}`)}return r}function jt(r,e){return k([r.latest],([t],n)=>{let o=n.store;if(t==null)return o.acc??"";let a=t;return a.seq===0&&(o.acc=""),a.type==="token"&&(o.acc=(o.acc??"")+a.delta),o.acc??""},{name:e,meta:C("accumulated_text"),initial:""})}function Ar(r,e,t,n){let o=n?.name??"llm",a=n?.format??"text",s=Ze(`${o}/stream`,{...n?.retainedLimit!=null?{retainedLimit:n.retainedLimit}:{}}),l=k(e,c=>{if(c.some(p=>p==null))return[];let m=typeof t=="string"?t:t(...c);return m?[{role:"user",content:m}]:[]},{name:`${o}::messages`,meta:C("prompt_node::messages"),initial:[]}),u=z(l,c=>{let m=c;if(!m||m.length===0)return w(null);let p=new AbortController;async function*h(){try{let g=await Pt(r,m,{model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,systemPrompt:n?.systemPrompt,signal:p.signal},s);yield Ft(g,a)}finally{p.abort()}}return x(h())}),i=jt(s,`${o}::accumulatedText`),d=V(u);return{output:u,deltaTopic:s,accumulatedText:i,dispose:()=>{d(),s.destroy()}}}function Sr(r,e,t,n,o,a){let s=w(0,{name:`${e}/cancel`}),l=0,u=[...n,s],i=a?.name??e,d=a?.format??"text",c=Ze(`${i}/stream`,{...a?.retainedLimit!=null?{retainedLimit:a.retainedLimit}:{}}),m=k(u,L=>{let R=L.slice(0,-1);if(R.some(G=>G==null))return[];let A=typeof o=="string"?o:o(...R);return A?[{role:"user",content:A}]:[]},{name:`${i}::messages`,meta:C("prompt_node::messages"),initial:[]}),p=z(m,L=>{let R=L;if(!R||R.length===0)return w(null);let A=new AbortController;async function*G(){try{let W=await Pt(t,R,{model:a?.model,temperature:a?.temperature,maxTokens:a?.maxTokens,systemPrompt:a?.systemPrompt,signal:A.signal},c);yield Ft(W,d)}finally{A.abort()}}return x(G())}),h=jt(c,`${i}::accumulatedText`),g=k([p],([L])=>{if(L!=null)return L},{name:`${e}/filter`});r.add(g,{name:`${e}/raw`});let f=wt(r,`${e}/gate`,`${e}/raw`,a?.gate),b=V(p),M=f.reject.bind(f),v={...f,reject(L=1){Z(()=>{M(L),s.emit(++l)})}};return{output:f.node,deltaTopic:c,accumulatedText:h,gate:v,dispose:()=>{b(),c.destroy()}}}function Cr(r,e){let t=e?.separator??`
3
-
4
- `,n=r.map(s=>typeof s=="string"?w(s):x(s)),o=k(n,s=>s.filter(l=>l!=null&&l!=="").join(t),{name:e?.name??"systemPrompt",describeKind:"derived",meta:C("system_prompt"),initial:""}),a=V(o);return Object.assign(o,{dispose:a})}var Er=(r,e)=>r===e?!0:r.chunkCount===e.chunkCount&&r.charCount===e.charCount&&r.estimatedTokens===e.estimatedTokens&&r.estimated===e.estimated;function Ir(r,e){let t=e?.charsPerToken??4,n={chunkCount:0,charCount:0,estimatedTokens:0,estimated:!0};return k([r.latest],([o],a)=>{if(o==null)return n;let s=o;"chunkCount"in a.store||(a.store.chunkCount=0,a.store.charCount=0,a.store.usageTokens=0,a.store.sawUsage=!1);let l=a.store;s.type==="token"?(l.chunkCount+=1,l.charCount+=s.delta.length):s.type==="usage"&&(l.sawUsage=!0,l.usageTokens=oe(s.usage)+de(s.usage));let u=l.sawUsage?l.usageTokens:Math.ceil(l.charCount/t);return{chunkCount:l.chunkCount,charCount:l.charCount,estimatedTokens:u,estimated:!l.sawUsage}},{name:e?.name??"cost-meter",describeKind:"derived",initial:n,meta:C("cost_meter_extractor"),equals:Er})}var Or=(r,e)=>{if(r===e)return!0;if(r==null||e==null)return r===e;if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++){let n=r[t],o=e[t];if(n.label!==o.label||n.pattern!==o.pattern||n.match!==o.match||n.position!==o.position)return!1}return!0};function Dr(r,e){let t=e.maxPatternLength??128;for(let o of e.patterns)if(o.pattern.source.length>t)throw new Error(`keywordFlagExtractor: pattern "${o.label}" literal exceeds maxPatternLength (${o.pattern.source.length} > ${t}); raise the option or shorten the pattern.`);let n=e.patterns.map(o=>({label:o.label,pattern:o.pattern,compiled:new RegExp(o.pattern.source,`${o.pattern.flags.replace("g","")}g`)}));return k([r],([o],a)=>{if(o==null)return[];let s=o;"flags"in a.store||(a.store.flags=[],a.store.scannedTo=0);let l=a.store.flags,u=a.store.scannedTo,i=Math.max(0,u-t),d=s.slice(i),c=!1;for(let{pattern:m,label:p,compiled:h}of n){h.lastIndex=0;for(let g of d.matchAll(h)){let f=i+(g.index??0);f+g[0].length<=u||(l.push({label:p,pattern:m,match:g[0],position:f}),c=!0)}}return a.store.scannedTo=s.length,c?[...l]:l.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:C("keyword_flag_extractor"),equals:Or})}function _r(r,e,t){return k([r],([n])=>n==null?null:e(n),{name:t?.name??"extractor",describeKind:"derived",initial:null,meta:C("stream_extractor"),...t?.equals?{equals:t.equals}:{}})}var Pr=(r,e)=>{if(r===e)return!0;if(r==null||e==null)return r===e;if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++){let n=r[t],o=e[t];if(n.startIndex!==o.startIndex||n.name!==o.name||n.raw!==o.raw)return!1}return!0};function Fr(r,e){return k([r],([t],n)=>{if(t==null)return[];let o=t;"calls"in n.store||(n.store.calls=[],n.store.scanFrom=0);let a=n.store.calls,s=n.store.scanFrom,l=!1;for(;s<o.length;){let u=o.indexOf("{",s);if(u===-1){n.store.scanFrom=o.length;break}let i=0,d=-1,c=!1;for(let p=u;p<o.length;p++){let h=o[p];if(c)h==="\\"&&p+1<o.length?p++:h==='"'&&(c=!1);else if(h==='"')c=!0;else if(h==="{")i++;else if(h==="}"&&(i--,i===0)){d=p;break}}if(d===-1){n.store.scanFrom=u;break}let m=o.slice(u,d+1);try{let p=JSON.parse(m);typeof p.name=="string"&&p.arguments!=null&&typeof p.arguments=="object"&&(a.push({name:p.name,arguments:p.arguments,raw:m,startIndex:u}),l=!0)}catch{}s=d+1,n.store.scanFrom=s}return l?[...a]:a.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:C("tool_call_extractor"),equals:Pr})}function jr(r,e,t,n){let o=t*(n?.hardMultiplier??1.5),a=typeof e!="function",s=[r];return a&&s.push(e),k(s,l=>{let u=l[0]??"";if(u.length===0)return"allow";let i=a?l[1]??0:e(u);return i>=o?"block":i>=t?"review":"allow"},{name:n?.name??"content-gate",initial:"allow"})}function Gr(r,e,t,n){let o=t??(()=>"[REDACTED]");function a(s){let l=s;for(let u of e){let i=u.global?u:new RegExp(u.source,`${u.flags}g`);l=l.replace(i,d=>o(d,u))}return l}return k([r],([s])=>a(s??""),{name:n?.name??"redactor",initial:""})}var He=class extends ce{_log;messages;latest;messageCount;constructor(e,t={}){super(e,t.graph),this._log=ve([],{name:"messages",maxSize:t.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=k([this.messages],([n])=>{let o=n;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:C("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(V(this.latest)),this.messageCount=k([this.messages],([n])=>n.length,{name:"messageCount",describeKind:"derived",meta:C("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(V(this.messageCount))}append(e,t,n){this._log.append({role:e,content:t,...n})}appendToolResult(e,t){this._log.append({role:"tool",content:t,toolCallId:e})}clear(){this._log.clear()}allMessages(){return this.messages.cache}};function ut(r,e){return new He(r,e)}var qe=class extends ce{definitions;schemas;_bundle;constructor(e,t={}){super(e,t.graph),this._bundle=De({name:"definitions"}),this.definitions=this._bundle.entries,this.add(this.definitions,{name:"definitions"}),this.schemas=k([this.definitions],([n])=>[...(n??new Map).values()],{name:"schemas",describeKind:"derived",meta:C("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(V(this.schemas))}register(e){this._bundle.set(e.name,e)}unregister(e){this._bundle.delete(e)}async execute(e,t){let n=this._bundle.get(e);if(!n)throw new Error(`toolRegistry: unknown tool "${e}"`);let o=n.handler(t);return ge(o)}executeReactive(e,t){let n=this._bundle.get(e);if(!n)throw new Error(`toolRegistry: unknown tool "${e}"`);return x(n.handler(t))}getDefinition(e){return this._bundle.entries.cache?.get(e)}};function ct(r,e){return new qe(r,e)}var ze=class extends ce{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;_terminalResult;_disposeRunWiring;_runVersion=0;_running=!1;_currentAbortController=null;constructor(e,t){if(super(e,t.graph),this.chat=ut(`${e}-chat`,{maxMessages:t.maxMessages}),this.mount("chat",this.chat),this.tools=ct(`${e}-tools`),this.mount("tools",this.tools),t.tools)for(let T of t.tools)this.tools.register(T);this.status=w("idle",{name:"status",describeKind:"state",meta:C("agent_status")}),this.add(this.status,{name:"status"}),this.turn=w(0,{name:"turn",describeKind:"state",meta:C("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.aborted=w(!1,{name:"aborted",describeKind:"state",meta:C("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let n=0,o=this.turn.subscribe(T=>{for(let y of T)y[0]===Q&&(n=y[1])}),a=!1,s=this.aborted.subscribe(T=>{for(let y of T)y[0]===Q&&(a=y[1])}),l=t.adapter,u=t.systemPrompt,i=t.model,d=t.temperature,c=t.maxTokens,m=t.maxTurns??10,p=t.stopWhen,h=this.chat,g=this.tools,f=this.status,b=this.turn,M=this.aborted,v=pe([f],(T,y,E)=>{if(Se(T,E.prevData,0,"idle")!=="thinking"||a||n>=m){y.down([[be]]);return}let B=h.allMessages();if(B.length===0){y.down([[be]]);return}let K=g.schemas.cache??[];y.emit({messages:B,tools:K})},{name:"promptInput",describeKind:"derived",meta:C("agent_prompt_input")}),L=z(v,T=>{let y=new AbortController;return this._currentAbortController=y,a&&y.abort(new Error("agentLoop: aborted")),x(l.invoke(T.messages,{tools:T.tools.length>0?T.tools:void 0,systemPrompt:u,model:i,temperature:d,maxTokens:c,signal:y.signal}),{signal:y.signal})},{equals:()=>!1}),R=w(null,{name:"lastResponse",describeKind:"state",meta:C("agent_last_response")});this.lastResponse=R;let A=pe([R,f],(T,y,E)=>{let j=Se(T,E.prevData,0,null);if(Se(T,E.prevData,1,"idle")!=="acting"){y.down([[be]]);return}let K=j?.toolCalls;if(K==null||K.length===0){y.down([[be]]);return}y.emit(K)},{name:"toolCallsRaw",describeKind:"derived",meta:C("agent_tool_calls_raw")}),G=t.interceptToolCalls?t.interceptToolCalls(A):A;this.toolCalls=G;let W=(T,y)=>{if(T===y)return!0;if(T.length!==y.length)return!1;for(let E=0;E<T.length;E++){let j=T[E],B=y[E];if(j?.id!==B?.id||j?.content!==B?.content)return!1}return!0},I=z(G,T=>{if(T==null||T.length===0)throw new Error("agentLoop: toolResultsNode received an empty tool-call batch as DATA \u2014 toolCallsRaw gating invariant broken (should emit RESOLVED for empty). Audit toolCallsRaw.");let y=T.map(E=>Br(E,g));return k(y,E=>E.map((j,B)=>{let K=j;return K!=null&&typeof K=="object"&&"id"in K&&"content"in K?K:{id:T[B].id,content:JSON.stringify(j??null)}}),{name:"toolResults_batch",equals:W})});this.toolResults=I;let O=ne([L],([T])=>{if(a)return;let y=T,E=n+1,j=y.toolCalls!=null&&y.toolCalls.length>0,B=y.finishReason==="end_turn"&&(!y.toolCalls||y.toolCalls.length===0),K=p?.(y)===!0,$=E>=m,J=K||B||!j||$?"done":"acting";Z(()=>{R.emit(y),f.emit(J),b.emit(E),h.append("assistant",y.content,{toolCalls:y.toolCalls})})}),S=ne([I],([T])=>{if(a)return;let y=T;if(y.length===0)return;let E=n>=m?"done":"thinking";Z(()=>{f.emit(E);for(let j of y)h.appendToolResult(j.id,j.content)})}),_=f.cache??"idle",N=f.subscribe(T=>{for(let y of T)y[0]===Q&&(_=y[1])}),D=ne([M],([T])=>{T===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),_!=="done"&&f.emit("done"))}),F=V(O),Y=V(S),P=V(D);this._terminalResult=pe([f,R],(T,y,E)=>{let j=Se(T,E.prevData,0,"idle"),B=Se(T,E.prevData,1,null);if(j==="done"){if(B!=null){y.emit({response:B,runVersion:this._runVersion});return}let K=new Error("agentLoop: aborted");K.name="AbortError",y.down([[X,K]]);return}if(j==="error"){y.down([[X,new Error("agentLoop: errored")]]);return}y.down([[be]])},{name:"terminalResult",describeKind:"derived",meta:C("agent_terminal_result")}),this.add(v,{name:"promptInput"}),this.add(L,{name:"llmResponse"}),this.add(this.lastResponse,{name:"lastResponse"}),this.toolCalls===A?this.add(this.toolCalls,{name:"toolCalls"}):(this.add(A,{name:"toolCallsRaw"}),this.add(this.toolCalls,{name:"toolCalls"})),this.add(I,{name:"toolResults"}),this.add(this._terminalResult,{name:"terminalResult"}),this.addDisposer(o),this.addDisposer(s),this.addDisposer(N),this.addDisposer(F),this.addDisposer(Y),this.addDisposer(P),this._disposeRunWiring=()=>{}}async run(e,t){if(this._running)throw new RangeError(`agentLoop "${this.name}": run() called while a previous run() is still pending \u2014 await the previous run before starting another, or call abort() first`);this._running=!0;let n=++this._runVersion;Z(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle")}),e!=null&&this.chat.append("user",e),this.status.emit("thinking");let o;if(t!=null)if(t.aborted)this.aborted.emit(!0);else{let a=()=>this.aborted.emit(!0);t.addEventListener("abort",a,{once:!0}),o=()=>t.removeEventListener("abort",a)}try{return(await Tt(this._terminalResult,{predicate:s=>s!=null&&typeof s=="object"&&s.runVersion===n})).response}finally{o?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function Br(r,e){let t=yt(()=>x(Promise.resolve().then(()=>e.execute(r.name,r.arguments))),{count:1}),n=k([t],([o])=>({id:r.id,content:typeof o=="string"?o:JSON.stringify(o)}));return Rt(n,o=>({id:r.id,content:JSON.stringify({error:String(o)})}))}function Se(r,e,t,n){let o=r[t];if(o!=null&&o.length>0)return o[o.length-1];let a=e[t];return a!==void 0?a:n}function $r(r,e){return new ze(r,e)}function Wr(r,e,t){let n=x(r),o=t?.condition!=null?x(t.condition):null,a=w(null,{name:t?.name?`${t.name}::null`:"handoff::null"});if(o==null)return z(n,l=>{if(l==null)return a;let u=w(l);return e(u)});let s=k([n,o],([l,u])=>({v:l,open:u===!0}),{name:t?.name?`${t.name}::router`:"handoff::router",describeKind:"derived"});return z(s,({v:l,open:u})=>{if(l==null)return a;if(!u)return w(l);let i=w(l);return e(i)})}function Kr(r,e,t){let n=x(r),o=e.map(s=>x(s)),a=[n,...o];return k(a,s=>{let l=s[0]??[],u=s.slice(1);return l.filter(i=>{for(let d of u)if(d!=null&&!d(i))return!1;return!0})},{name:t?.name??"tool-selector",describeKind:"derived",meta:C("tool_selector"),equals:(s,l)=>{let u=s,i=l;if(u.length!==i.length)return!1;for(let d=0;d<u.length;d++)if(u[d]!==i[d])return!1;return!0}})}function Gt(r){let e=r.thresholds??{};return t=>{let n=r.scoreFn(t);for(let o of Object.keys(e)){let a=e[o];if(a===void 0)continue;let s=n[o];if((Number.isFinite(s)?s:Number.NEGATIVE_INFINITY)<a)return!1}return!0}}function Vr(r){let e={persistence:r.persistenceThreshold??.3,personalValue:r.personalValueThreshold??.3},t=Gt({scoreFn:r.scoreFn,thresholds:e});return r.requireStructured?n=>{if(!t(n))return!1;let o=r.scoreFn(n).structure;return Number.isFinite(o)&&o>0}:t}function Bt(r,e,t,n){let o=t.name??n;return a=>{let s=w(a);return dt(t.adapter,[s],l=>e(l),{name:o,format:"json",systemPrompt:r,model:t.model,temperature:t.temperature??0,maxTokens:t.maxTokens})}}function mt(r,e){let t=e.maxExistingKeys??100,n=Bt(r,o=>JSON.stringify({input:o.raw,existingKeys:o.existingKeys}),e,"llmExtractor");return(o,a)=>{let s=t===Number.POSITIVE_INFINITY?[...a.keys()]:[...a.keys()].slice(0,t);return n({raw:o,existingKeys:s})}}function pt(r,e){let t=Bt(r,n=>JSON.stringify({memories:n}),e,"llmConsolidator");return n=>{let o=[...n.entries()].map(([a,s])=>({key:a,value:s}));return t(o)}}var Ce=Math.LN2/604800;function Ee(r){return r instanceof Map?r:new Map}function Ur(r,e,t){let n=new ce(r,t.graph),o=[],a;if(t.extractFn)a=t.extractFn;else if(t.adapter&&t.extractPrompt)a=mt(t.extractPrompt,{adapter:t.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let s=(v,L)=>v==null?{upsert:[]}:a(v,L),l=e;if(t.admissionFilter){let v=x(e),L=t.admissionFilter;l=k([v],([R])=>{if(L(R))return R},{name:"admissionFilter",describeKind:"derived"})}let u;t.consolidateFn?u=t.consolidateFn:t.adapter&&t.consolidatePrompt&&(u=pt(t.consolidatePrompt,{adapter:t.adapter}));let i=t.consolidateTrigger;if(!i&&u&&t.reflection?.enabled!==!1){let v=t.reflection?.interval??3e5;i=bt(v,{period:v})}let d={score:t.score,cost:t.cost,budget:t.budget??2e3,context:t.context,consolidate:u,consolidateTrigger:i},c=xt(l,s,d);n.add(c.store.entries,{name:"store"}),n.add(c.compact,{name:"compact"}),n.add(c.size,{name:"size"});let m=null;t.vectorDimensions&&t.vectorDimensions>0&&t.embedFn&&(m=je({dimension:t.vectorDimensions}),n.add(m.entries,{name:"vectorIndex"}));let p=null;t.enableKnowledgeGraph&&(p=Ge(`${r}-kg`),n.mount("kg",p));let h=null;if(t.tiers){let v=t.tiers,L=v.decayRate??Ce,R=v.maxActive??1e3,A=v.archiveThreshold??.1,G=v.permanentFilter??(()=>!1),W=Fe({name:"permanent"});n.add(W.entries,{name:"permanent"});let I=new Set,O=P=>I.has(P)?"permanent":Ee(c.store.entries.cache).has(P)?"active":"archived",S=(P,T)=>{I.add(P),W.upsert(P,T)},_=new Map,N=c.store.entries,D=t.context?x(t.context):w(null),F=ne([N,D],([P,T])=>{let y=Ee(P),E=re(),j=[],B=[];for(let[$,J]of y){if(_.has($)||_.set($,E),G($,J)){B.push({key:$,value:J});continue}let H=t.score(J,T),ie=_.get($)??E,q=Number(E-ie)/1e9;Pe(H,q,L)<A&&j.push($)}for(let $ of _.keys())y.has($)||_.delete($);for(let{key:$,value:J}of B)I.has($)||S($,J);let K=y.size-I.size;if(K>R){let $=[...y.entries()].filter(([H])=>!I.has(H)).map(([H,ie])=>({key:H,score:t.score(ie,T)})).sort((H,ie)=>H.score-ie.score),J=K-R;for(let H=0;H<J&&H<$.length;H++){let ie=$[H].key;j.includes(ie)||j.push(ie)}}j.length>0&&Z(()=>{for(let $ of j)c.store.delete($)})});o.push(F.subscribe(()=>{}));let Y=null;v.archiveTier&&(Y=n.attachStorage([v.archiveTier],v.archiveStorageOptions??{})),h={permanent:W,activeEntries:N,archiveHandle:Y,tierOf:O,markPermanent:S}}if(m||p){let v=t.embedFn,L=t.entityFn,R=c.store.entries,A=ne([R],([G])=>{let W=Ee(G);for(let[I,O]of W){if(m&&v){let S=v(O);S&&m.upsert(I,S,O)}if(p&&L){let S=L(I,O);if(S){for(let _ of S.entities??[])p.upsertEntity(_.id,_.value);for(let _ of S.relations??[])p.link(_.from,_.to,_.relation,_.weight)}}}});o.push(A.subscribe(()=>{}))}let g=null,f=null,b=null,M=null;if(m||p){let v=t.retrieval?.topK??20,L=t.retrieval?.graphDepth??1,R=t.budget??2e3,A=t.cost,G=t.score,W=t.contextOf,I=t.contextWeight??0,O=t.context?x(t.context):w(null),S=(P,T)=>{if(!P||!T)return 0;let y=Math.min(P.length,T.length),E=0;for(;E<y&&P[E]===T[E];)E++;return E},_=(P,T,y)=>{let E=new Map,j=[];if(m&&y.vector){j=m.search(y.vector,v);for(let q of j){let U=P.get(q.id);U&&E.set(q.id,{value:U,sources:new Set(["vector"])})}}let B=[];if(p){let q=[...y.entityIds??[],...E.keys()],U=new Set,we=q;for(let ye=0;ye<L;ye++){let me=[];for(let Le of we){if(U.has(Le))continue;U.add(Le);let Ie=p.related(Le);for(let Ut of Ie){let he=Ut.to;if(!U.has(he)){me.push(he);let ft=P.get(he);if(ft){let gt=E.get(he);gt?gt.sources.add("graph"):E.set(he,{value:ft,sources:new Set(["graph"])}),B.push(he)}}}}we=me}}for(let[q,U]of P)E.has(q)||E.set(q,{value:U,sources:new Set(["store"])});let K=y.context?.length??0,$=[];for(let[q,{value:U,sources:we}]of E){let ye=W?W(U):void 0,me=G(U,T);if(I>0&&K>0){let Ie=S(y.context,ye);Ie>0&&(me=me*(1+I*Ie/K))}let Le=ye?{key:q,value:U,score:me,sources:[...we],context:ye}:{key:q,value:U,score:me,sources:[...we]};$.push(Le)}$.sort((q,U)=>U.score-q.score);let J=[],H=0;for(let q of $){let U=A(q.value);if(H+U>R&&J.length>0)break;J.push(q),H+=U}return{packed:J,trace:{vectorCandidates:j,graphExpanded:B,ranked:$,packed:J}}},N=(P,T)=>{if(P===T)return!0;if(P.length!==T.length)return!1;for(let y=0;y<P.length;y++)if(P[y]!==T[y])return!1;return!0},D=w([],{name:"retrieval",describeKind:"state",meta:C("retrieval_pipeline"),equals:N});n.add(D,{name:"retrieval"}),g=D;let F=w(null,{name:"retrievalTrace",describeKind:"state",meta:C("retrieval_trace")});n.add(F,{name:"retrievalTrace"}),f=F,b=P=>{let T=Ee(c.store.entries.cache),{packed:y,trace:E}=_(T,O.cache,P);return Z(()=>{D.emit(y),F.emit(E)}),y},M=P=>{let T=x(P),y=k([c.store.entries,O,T],([j,B,K])=>{if(K==null)return{packed:[],trace:null};let $=Ee(j),{packed:J,trace:H}=_($,B,K);return{packed:J,trace:H}},{name:"retrievalReactive::result",describeKind:"derived",meta:C("retrieval_reactive_result"),initial:{packed:[],trace:null}}),E=ne([y],([j])=>{let B=j;Z(()=>{D.emit(B.packed),B.trace&&F.emit(B.trace)})});return o.push(E.subscribe(()=>{})),k([y],([j])=>j.packed,{name:"retrievalReactive",describeKind:"derived",meta:C("retrieval_reactive"),initial:[],equals:N})}}return n.addDisposer(()=>{for(let v of o)v();o.length=0}),Object.assign(n,{distillBundle:c,compact:c.compact,size:c.size,vectors:m,kg:p,memoryTiers:h,retrieval:g,retrievalTrace:f,retrieve:b,retrieveReactive:M})}function xe(r){return r instanceof Map?r:new Map}function Hr(r,e,t){let n=je({dimension:t.dimension});r.add(n.entries,{name:"vectorIndex"});let a=ne([e.store.entries],([s])=>{let l=xe(s);for(let[u,i]of l){let d=t.embedFn(i);d&&n.upsert(u,d,i)}}).subscribe(()=>{});return r.addDisposer(a),{vectors:n,dispose:()=>a()}}function qr(r,e,t,n){let o=Ge(`${t}-kg`);r.mount(t,o);let s=ne([e.store.entries],([l])=>{let u=xe(l);for(let[i,d]of u){let c=n.entityFn(i,d);if(c){for(let m of c.entities??[])o.upsertEntity(m.id,m.value);for(let m of c.relations??[])o.link(m.from,m.to,m.relation,m.weight)}}}).subscribe(()=>{});return r.addDisposer(s),{kg:o,dispose:()=>s()}}function zr(r,e,t){let n=t.decayRate??Ce,o=t.maxActive??1e3,a=t.archiveThreshold??.1,s=t.permanentFilter??(()=>!1),l=Fe({name:"permanent"});r.add(l.entries,{name:"permanent"});let u=new Set,i=M=>u.has(M)?"permanent":xe(e.store.entries.cache).has(M)?"active":"archived",d=(M,v)=>{u.add(M),l.upsert(M,v)},c=new Map,m=e.store.entries,p=t.context?x(t.context):w(null),g=ne([m,p],([M,v])=>{let L=xe(M),R=re(),A=[],G=[];for(let[I,O]of L){if(c.has(I)||c.set(I,R),s(I,O)){G.push({key:I,value:O});continue}let S=t.score(O,v),_=c.get(I)??R,N=Number(R-_)/1e9;Pe(S,N,n)<a&&A.push(I)}for(let I of c.keys())L.has(I)||c.delete(I);for(let{key:I,value:O}of G)u.has(I)||d(I,O);let W=L.size-u.size;if(W>o){let I=[...L.entries()].filter(([S])=>!u.has(S)).map(([S,_])=>({key:S,score:t.score(_,v)})).sort((S,_)=>S.score-_.score),O=W-o;for(let S=0;S<O&&S<I.length;S++){let _=I[S].key;A.includes(_)||A.push(_)}}A.length>0&&Z(()=>{for(let I of A)e.store.delete(I)})}).subscribe(()=>{}),f=null;t.archiveTier&&(f=r.attachStorage([t.archiveTier],t.archiveStorageOptions??{}));let b=()=>{g(),f?.dispose()};return r.addDisposer(b),{tiers:{permanent:l,activeEntries:m,archiveHandle:f,tierOf:i,markPermanent:d},dispose:b}}function Yr(r,e){if(!r||!e)return 0;let t=Math.min(r.length,e.length),n=0;for(;n<t&&r[n]===e[n];)n++;return n}function Jr(r,e,t,n,o){let a=o.topK??20,s=o.graphDepth??1,l=o.budget??2e3,u=o.contextWeight??0,i=o.context?x(o.context):w(null),d=(f,b,M)=>{let v=new Map,L=[];if(t&&M.vector){L=t.search(M.vector,a);for(let O of L){let S=f.get(O.id);S&&v.set(O.id,{value:S,sources:new Set(["vector"])})}}let R=[];if(n){let O=[...M.entityIds??[],...v.keys()],S=new Set,_=O;for(let N=0;N<s;N++){let D=[];for(let F of _)if(!S.has(F)){S.add(F);for(let Y of n.related(F)){let P=Y.to;if(!S.has(P)){D.push(P);let T=f.get(P);if(T){let y=v.get(P);y?y.sources.add("graph"):v.set(P,{value:T,sources:new Set(["graph"])}),R.push(P)}}}}_=D}}for(let[O,S]of f)v.has(O)||v.set(O,{value:S,sources:new Set(["store"])});let A=M.context?.length??0,G=[];for(let[O,{value:S,sources:_}]of v){let N=o.contextOf?o.contextOf(S):void 0,D=o.score(S,b);if(u>0&&A>0){let Y=Yr(M.context,N);Y>0&&(D=D*(1+u*Y/A))}let F=N?{key:O,value:S,score:D,sources:[..._],context:N}:{key:O,value:S,score:D,sources:[..._]};G.push(F)}G.sort((O,S)=>S.score-O.score);let W=[],I=0;for(let O of G){let S=o.cost(O.value);if(I+S>l&&W.length>0)break;W.push(O),I+=S}return{packed:W,trace:{vectorCandidates:L,graphExpanded:R,ranked:G,packed:W}}},c=(f,b)=>{if(f===b)return!0;if(f.length!==b.length)return!1;for(let M=0;M<f.length;M++)if(f[M]!==b[M])return!1;return!0},m=w([],{name:"retrieval",describeKind:"state",meta:C("retrieval_pipeline"),equals:c});r.add(m,{name:"retrieval"});let p=w(null,{name:"retrievalTrace",describeKind:"state",meta:C("retrieval_trace")});return r.add(p,{name:"retrievalTrace"}),{retrieval:m,retrievalTrace:p,retrieve:f=>{let b=xe(e.store.entries.cache),{packed:M,trace:v}=d(b,i.cache,f);return Z(()=>{m.emit(M),p.emit(v)}),M},retrieveReactive:f=>{let b=x(f),M=k([e.store.entries,i,b],([R,A,G])=>{if(G==null)return{packed:[],trace:null};let W=xe(R),{packed:I,trace:O}=d(W,A,G);return{packed:I,trace:O}},{name:"retrievalReactive::result",describeKind:"derived",meta:C("retrieval_reactive_result"),initial:{packed:[],trace:null}}),L=ne([M],([R])=>{let A=R;Z(()=>{m.emit(A.packed),A.trace&&p.emit(A.trace)})}).subscribe(()=>{});return r.addDisposer(L),k([M],([R])=>R.packed,{name:"retrievalReactive",describeKind:"derived",meta:C("retrieval_reactive"),initial:[],equals:c})}}}function Qr(r,e,t){let n=r.describe({actor:e,detail:"full"}),o=t?.groupByTags??!0,a=t?.separator??`
5
- `,s=[],l=t?.sinceVersion;for(let[u,i]of Object.entries(n.nodes)){let d=i.meta??{},c=d.description,m=d.format;if(!c&&!m)continue;if(l!=null&&i.v!=null){let b=l.get(u);if(b!=null&&b.id===i.v.id&&i.v.version<=b.version)continue}let p=c??u,h=i.value,g=d.unit,f;m==="currency"&&typeof h=="number"?f=`$${h.toFixed(2)}`:m==="percentage"&&typeof h=="number"?f=`${(h*100).toFixed(1)}%`:h==null?f="(no value)":f=String(h),g&&m!=="currency"&&m!=="percentage"&&(f=`${f} ${g}`),s.push({path:u,description:p,formatted:f})}if(s.length===0)return"";if(o){let u=new Map,i=[];for(let c of s){let p=n.nodes[c.path].meta?.tags;if(p&&p.length>0){let h=p[0],g=u.get(h);g||(g=[],u.set(h,g)),g.push(c)}else i.push(c)}if(u.size===0)return s.map(c=>`- ${c.description}: ${c.formatted}`).join(a);let d=[];for(let[c,m]of[...u.entries()].sort((p,h)=>p[0].localeCompare(h[0])))d.push(`[${c}]${a}${m.map(p=>`- ${p.description}: ${p.formatted}`).join(a)}`);return i.length>0&&d.push(i.map(c=>`- ${c.description}: ${c.formatted}`).join(a)),d.join(a+a)}return s.map(u=>`- ${u.description}: ${u.formatted}`).join(a)}var $t=`You are a graph architect for GraphReFly, a reactive graph protocol.
6
-
7
- Given a natural-language description, produce a JSON graph specification with this structure:
8
-
9
- {
10
- "name": "<graph_name>",
11
- "nodes": {
12
- "<node_name>": {
13
- "type": "state" | "derived" | "producer" | "effect" | "operator",
14
- "initial": <initial_value_for_state_nodes>,
15
- "deps": ["<dep_node_name>", ...],
16
- "meta": {
17
- "description": "<human-readable purpose>",
18
- "type": "string" | "number" | "boolean" | "integer" | "enum",
19
- "range": [min, max],
20
- "values": ["a", "b"],
21
- "format": "currency" | "percentage" | "status",
22
- "access": "human" | "llm" | "both" | "system",
23
- "unit": "<unit>",
24
- "tags": ["<tag>"]
25
- }
26
- }
27
- }
28
- }
29
-
30
- Rules:
31
- - "state" nodes have no deps and hold user/LLM-writable values (knobs). Use "initial" for the starting value.
32
- - "derived" nodes have deps and compute from them (pure, no side effects).
33
- - "effect" nodes have deps but produce side effects (no return value).
34
- - "producer" nodes have no deps but generate values asynchronously.
35
- - "operator" nodes are parameterized transformations with deps.
36
- - Use "deps" inside each node to declare dependencies \u2014 no separate "edges" array.
37
- - meta.description is required for every node.
38
- - Return ONLY valid JSON, no markdown fences or commentary.`;async function Wt(r,e,t){let o=[{role:"system",content:t?.systemPromptExtra?`${$t}
39
-
40
- ${t.systemPromptExtra}`:$t},{role:"user",content:r}],a=e.invoke(o,{model:t?.model,temperature:t?.temperature??0,maxTokens:t?.maxTokens,signal:t?.signal}),l=(await ge(a)).content.trim();l.startsWith("```")&&(l=Re(l));let u;try{u=JSON.parse(l)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${l.slice(0,200)}`)}return Lt(u,{catalog:t?.catalog})}function Xr(r,e,t){let n=x(r);return z(n,o=>!o||typeof o!="string"||o.trim().length===0?w(null):Te(a=>{let s=new AbortController,l=!1;return Wt(o,e,{...t,signal:s.signal}).then(u=>{if(l){u.destroy();return}a.emit(u),a.down([[le]])}).catch(u=>{l||a.down([[X,u]])}),()=>{l=!0,s.abort()}},{name:"graphFromSpec::call"}))}function Zr(r){let e={},t=r.type;return t==="enum"&&Array.isArray(r.values)?(e.type="string",e.enum=r.values):t==="integer"?e.type="integer":t==="number"?e.type="number":t==="boolean"?e.type="boolean":t==="string"?e.type="string":e.type=["string","number","boolean"],Array.isArray(r.range)&&r.range.length===2&&(e.minimum=r.range[0],e.maximum=r.range[1]),typeof r.format=="string"&&(e.description=`Format: ${r.format}`),typeof r.unit=="string"&&(e.description?e.description+=` (${r.unit})`:e.description=`Unit: ${r.unit}`),e}function en(r,e){let t=r.describe({actor:e,detail:"full"}),n=[],o=[],a=[];for(let[s,l]of Object.entries(t.nodes)){if(l.type!=="state"||s.includes("::__meta__::")||l.status==="completed"||l.status==="errored")continue;let u=l.meta??{},i=u.access;if(i==="human"||i==="system")continue;let d=u.description??`Set the value of ${s}`,c=Zr(u),m={type:"object",required:["value"],properties:{value:c},additionalProperties:!1},p=s.replace(/::/g,"__");n.push({type:"function",function:{name:p,description:d,parameters:m}}),o.push({name:s,description:d,inputSchema:m});let h=r,g=e,f=l.v;a.push({name:s,description:d,parameters:m,handler(b){return h.set(s,b.value,g?{actor:g}:void 0),b.value},...f!=null?{version:{id:f.id,version:f.version}}:{}})}return{openai:n,mcp:o,definitions:a}}var tn=`You are a reactive graph optimizer for GraphReFly.
41
-
42
- Given a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.
43
-
44
- Return ONLY valid JSON with this structure:
45
- {
46
- "summary": "<one-line summary of the strategy>",
47
- "reasoning": "<explanation of why these changes help>",
48
- "operations": [
49
- { "type": "add_node", "name": "<name>", "nodeType": "state|derived|effect|producer|operator", "meta": {...}, "initial": <value> },
50
- { "type": "remove_node", "name": "<name>" },
51
- { "type": "connect", "from": "<source>", "to": "<target>" },
52
- { "type": "disconnect", "from": "<source>", "to": "<target>" },
53
- { "type": "set_value", "name": "<name>", "value": <new_value> },
54
- { "type": "update_meta", "name": "<name>", "key": "<meta_key>", "value": <new_value> }
55
- ]
56
- }
57
-
58
- Rules:
59
- - Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).
60
- - Keep changes minimal \u2014 prefer the smallest set of operations that solves the problem.
61
- - Return ONLY valid JSON, no markdown fences or commentary.`;async function Kt(r,e,t,n){let{expand:o,...a}=r.describe({actor:n?.actor,detail:"standard"}),s=[{role:"system",content:tn},{role:"user",content:JSON.stringify({graph:a,problem:e})}],l=t.invoke(s,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens,signal:n?.signal}),i=(await ge(l)).content.trim();i.startsWith("```")&&(i=i.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let d;try{d=JSON.parse(i)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${i.slice(0,200)}`)}let c=d;if(typeof c.summary!="string")throw new Error("suggestStrategy: missing 'summary' in response");if(typeof c.reasoning!="string")throw new Error("suggestStrategy: missing 'reasoning' in response");if(!Array.isArray(c.operations))throw new Error("suggestStrategy: missing 'operations' array in response");return{summary:c.summary,reasoning:c.reasoning,operations:c.operations}}function rn(r,e,t,n){let o=x(e),a=kt(o,r);return z(a,s=>{if(s==null)return w(null);let[l,u]=s;return!u||!l||typeof l!="string"||l.trim().length===0?w(null):u.destroyed?w(null):Te(i=>{let d=new AbortController,c=!1;return Kt(u,l,t,{...n,signal:d.signal}).then(m=>{c||(i.emit(m),i.down([[le]]))}).catch(m=>{c||i.down([[X,m]])}),()=>{c=!0,d.abort()}},{name:"suggestStrategy::call"})})}var Vt=new Set(["state","derived","producer","operator","effect"]);function nn(r){let e=[];if(r==null||typeof r!="object")return{valid:!1,errors:["Definition must be a non-null object"]};let t=r;if((typeof t.name!="string"||t.name.length===0)&&e.push("Missing or empty 'name' field"),t.nodes==null||typeof t.nodes!="object"||Array.isArray(t.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e};let n=new Set(Object.keys(t.nodes));for(let[o,a]of Object.entries(t.nodes)){if(a==null||typeof a!="object"){e.push(`Node "${o}": must be an object`);continue}let s=a;if((typeof s.type!="string"||!Vt.has(s.type))&&e.push(`Node "${o}": invalid type "${String(s.type)}" (expected: ${[...Vt].join(", ")})`),Array.isArray(s.deps))for(let l of s.deps)typeof l=="string"&&!n.has(l)&&e.push(`Node "${o}": dep "${l}" does not reference an existing node`)}if(!Array.isArray(t.edges))t.edges!==void 0&&e.push("'edges' must be an array");else{let o=new Set;for(let a=0;a<t.edges.length;a++){let s=t.edges[a];if(s==null||typeof s!="object"){e.push(`Edge [${a}]: must be an object`);continue}let l=s;(typeof l.from!="string"||!n.has(l.from))&&e.push(`Edge [${a}]: 'from' "${String(l.from)}" does not reference an existing node`),(typeof l.to!="string"||!n.has(l.to))&&e.push(`Edge [${a}]: 'to' "${String(l.to)}" does not reference an existing node`);let u=`${l.from}->${l.to}`;o.has(u)&&e.push(`Edge [${a}]: duplicate edge ${u}`),o.add(u)}}return{valid:e.length===0,errors:e}}export{nr as a,or as b,$e as c,et as d,sr as e,ir as f,lr as g,dr as h,tt as i,We as j,nt as k,cr as l,ot as m,st as n,it as o,ke as p,lt as q,vr as r,Mr as s,Lr as t,dt as u,Ar as v,Sr as w,Cr as x,Ir as y,Dr as z,_r as A,Fr as B,jr as C,Gr as D,He as E,ut as F,qe as G,ct as H,ze as I,$r as J,Wr as K,Kr as L,Gt as M,Vr as N,mt as O,pt as P,Ce as Q,Ur as R,Hr as S,qr as T,zr as U,Jr as V,Qr as W,Wt as X,Xr as Y,en as Z,Kt as _,rn as $,nn as aa,on as ba};
@@ -1 +0,0 @@
1
- import{c as q}from"./chunk-K54OKWNY.js";import{b as v}from"./chunk-4UUDNFYG.js";import{b as T}from"./chunk-LWGLBCMU.js";import{b as y}from"./chunk-XRSHMHEG.js";import{j as g}from"./chunk-4JBKKUCJ.js";import{B as d}from"./chunk-UMH3HSP7.js";import{D as w,G as h}from"./chunk-7AJKUA36.js";import{b as N}from"./chunk-QYADASLV.js";var $={};N($,{JobFlowGraph:()=>u,JobQueueGraph:()=>p,jobFlow:()=>k,jobQueue:()=>E});var x=2147483647;function J(s,e){if(!Number.isFinite(s)||!Number.isInteger(s)||s<0)throw new Error(`${e} must be a non-negative integer`);return s}function c(s,e){return q("job_queue",s,e)}var p=class extends g{_pending;_jobs;_seq=0;pending;jobs;depth;constructor(e,t={}){super(e,t.graph),this._pending=v([],{name:"pending"}),this._jobs=T({name:"jobs"}),this.pending=this._pending.items,this.jobs=this._jobs.entries,this.add(this.pending,{name:"pending"}),this.add(this.jobs,{name:"jobs"}),this.depth=h([this.pending],([n])=>n.length,{name:"depth",describeKind:"derived",meta:c("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(d(this.depth))}enqueue(e,t={}){let n=t.id??`${this.name}-${++this._seq}`;if(this._jobs.get(n)!==void 0)throw new Error(`jobQueue("${this.name}"): duplicate job id "${n}"`);let m={id:n,payload:e,attempts:0,metadata:Object.freeze({...t.metadata??{}}),state:"queued"};return this._jobs.set(n,m),this._pending.append(n),n}claim(e=1){let t=J(e,"job queue claim limit");if(t===0)return[];let n=[];for(;n.length<t&&this.pending.cache.length!==0;){let a=this._pending.pop(0),o=this._jobs.get(a);if(!o||o.state!=="queued")continue;let i={...o,state:"inflight",attempts:o.attempts+1};this._jobs.set(a,i),n.push(i)}return n}ack(e){let t=this._jobs.get(e);return!t||t.state!=="inflight"?!1:(this._jobs.delete(e),!0)}nack(e,t={}){let n=this._jobs.get(e);return!n||n.state!=="inflight"?!1:t.requeue??!0?(this._jobs.set(e,{...n,state:"queued"}),this._pending.append(e),!0):(this._jobs.delete(e),!0)}},u=class extends g{_stageNames;_queues=new Map;_completed;completed;completedCount;constructor(e,t={}){super(e,t.graph);let n=(t.stages??["incoming","processing","done"]).map(o=>o.trim());if(n.length<2)throw new Error(`jobFlow("${e}"): requires at least 2 stages`);if(new Set(n).size!==n.length)throw new Error(`jobFlow("${e}"): stage names must be unique`);this._stageNames=Object.freeze([...n]);for(let o of this._stageNames){let i=E(`${e}-${o}`);this._queues.set(o,i),this.mount(o,i)}this._completed=y([],{name:"completed"}),this.completed=this._completed.entries,this.add(this.completed,{name:"completed"}),this.completedCount=h([this.completed],([o])=>o.length,{name:"completedCount",describeKind:"derived",meta:c("job_flow_completed_count"),initial:0}),this.add(this.completedCount,{name:"completedCount"}),this.addDisposer(d(this.completedCount));let a=Math.max(1,J(t.maxPerPump??x,"job flow maxPerPump"));for(let o=0;o<this._stageNames.length;o+=1){let i=this._stageNames[o],l=this.queue(i),b=o+1<this._stageNames.length?this.queue(this._stageNames[o+1]):null,_=w([l.pending],()=>{let f=0;for(;f<a;){let j=l.claim(1);if(j.length===0)break;let r=j[0];if(!r)break;b?b.enqueue(r.payload,{metadata:{...r.metadata,job_flow_from:i}}):this._completed.append(r),l.ack(r.id),f+=1}},{name:`pump_${i}`,describeKind:"effect",meta:c("job_flow_pump")});this.add(_,{name:`pump_${i}`}),this.addDisposer(d(_))}}stages(){return this._stageNames}queue(e){let t=this._queues.get(e);if(!t)throw new Error(`jobFlow("${this.name}"): unknown stage "${e}"`);return t}enqueue(e,t={}){return this.queue(this._stageNames[0]).enqueue(e,t)}retainedCompleted(){return this.completed.cache}};function E(s,e){return new p(s,e)}function k(s,e){return new u(s,e)}export{p as a,u as b,E as c,k as d,$ as e};
@@ -1 +0,0 @@
1
- import{a as Y,b as m,c as M,d as S,e as C,f as N,g as L,h as k,i as D,j as _,k as P,l as he,n as se,q as ie,r as fe,s as pe,t as _e,u as re}from"./chunk-CK2E7BTU.js";var De={name:"json",version:1,contentType:"application/json",encode(n){let e=JSON.stringify(n);return new TextEncoder().encode(e)},decode(n,e){let t=new TextDecoder().decode(n);return JSON.parse(t)}};function $e(n){return{name:"dag-cbor",version:1,contentType:"application/dag-cbor",encode:e=>n.encode(e),decode:(e,t)=>n.decode(e)}}function je(n,e){return{name:"dag-cbor-zstd",version:1,contentType:"application/dag-cbor+zstd",encode:t=>e.compressSync(n.encode(t)),decode:(t,s)=>n.decode(e.decompressSync(t))}}var oe=1,ge=4;function ze(n,e){let t=new TextEncoder().encode(n.name);if(t.length===0||t.length>255)throw new Error(`encodeEnvelope: codec name "${n.name}" encodes to ${t.length} bytes (must be 1\u2013255)`);let s=n.version;if(!Number.isInteger(s)||s<0||s>65535)throw new Error(`encodeEnvelope: codec.version ${s} out of u16 range (expected integer 0\u201365535)`);let i=2+t.length+2+e.length;if(i>4294967295)throw new Error(`encodeEnvelope: total envelope size ${i} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let r=new Uint8Array(i),a=0;return r[a++]=oe,r[a++]=t.length,r.set(t,a),a+=t.length,r[a++]=s>>>8&255,r[a++]=s&255,r.set(e,a),r}function qe(n,e){if(n.length<ge)throw new Error(`decodeEnvelope: bytes too short (${n.length} < ${ge})`);let t=0,s=n[t++];if(s!==oe)throw new Error(`decodeEnvelope: unsupported envelope version ${s} (expected ${oe})`);let i=n[t++];if(i===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(t+i+2>n.length)throw new Error(`decodeEnvelope: envelope truncated (need ${t+i+2} bytes, have ${n.length})`);let r=new TextDecoder().decode(n.subarray(t,t+i));t+=i;let a=(n[t]<<8|n[t+1])>>>0;t+=2;let o=n.subarray(t),d=e.lookupCodec(r);if(d==null)throw new Error(`decodeEnvelope: codec "${r}" not registered (envelope codec_v=${a})`);return{codec:d,codecVersion:a,payload:o}}function ye(n){n.registerCodec(De)}function Ke(n){if(n.length===0)throw new Error("WAL is empty \u2014 need at least one full snapshot");let e=n[0];if(e.mode!=="full")throw new Error("WAL must start with a full record carrying a baseline snapshot");let t=JSON.parse(JSON.stringify(e.snapshot)),s=e.seq;for(let i=1;i<n.length;i++){let r=n[i];if(r.seq<=s)throw new Error(`WAL chain broken at index ${i}: seq=${r.seq} must exceed prev seq=${s}`);if(r.mode==="full"){t=JSON.parse(JSON.stringify(r.snapshot)),s=r.seq;continue}let a=r.diff;for(let d of a.nodesRemoved)delete t.nodes[d];let o=a.nodesAddedFull;if(o!=null)for(let[d,l]of Object.entries(o))t.nodes[d]=JSON.parse(JSON.stringify(l));for(let d of a.nodesChanged){let l=t.nodes[d.path];l!=null&&(l[d.field]=d.to)}s=r.seq}return t}var Oe={type:"system",id:""};function J(n){if(n==null)return Oe;let{type:e,id:t,...s}=n;return{type:e??"system",id:t??"",...s}}var O=0,U=!1,A=[],E=[],R=[],W=[];function me(){return O>0||U}function be(){return O>0}function ve(n){O>0?W.push(n):n()}function Xe(n){O+=1;let e=!1;try{n()}catch(t){throw e=!0,t}finally{if(O-=1,O===0)if(e){if(!U){let t=W.splice(0);for(let s of t)try{s()}catch{}A.length=0,E.length=0,R.length=0}}else Re()}}function Re(){let n=!U;n&&(U=!0);let e=[],t=0;try{for(;A.length>0||E.length>0||R.length>0||n&&W.length>0;){if(n&&W.length>0){let r=W.splice(0);for(let a of r)try{a()}catch(o){e.push(o)}continue}if(t+=1,t>1e3)throw A.length=0,E.length=0,R.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let i=(A.length>0?A:E.length>0?E:R).splice(0);for(let r of i)try{r()}catch(a){e.push(a)}}}finally{n&&(U=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function X(n,e,t){if(e.length===0)return;if(e.length===1){let l=t(e[0][0]);if(l<3||!me()){n(e);return}(l>=5?R:l===4?E:A).push(()=>n(e));return}let s=e.length,i=s,r=s,a=s,o=0;for(;o<s&&t(e[o][0])<3;)o++;for(i=o;o<s&&t(e[o][0])===3;)o++;for(r=o;o<s&&t(e[o][0])===4;)o++;a=o;let d=me();if(i>0){let l=e.slice(0,i);n(l)}if(r>i){let l=e.slice(i,r);d?A.push(()=>n(l)):n(l)}if(a>r){let l=e.slice(r,a);d?E.push(()=>n(l)):n(l)}if(s>a){let l=e.slice(a,s);d?R.push(()=>n(l)):n(l)}}function Qe(){return Math.trunc(performance.now()*1e6)}function we(){return Date.now()*1e6}var Z=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=t=>{let s=this._messageTypes.get(t);return s!=null?s.tier:1}}get onMessage(){return this._frozen=!0,this._onMessage}get onSubscribe(){return this._frozen=!0,this._onSubscribe}set onMessage(e){this._assertUnfrozen(),this._onMessage=e}set onSubscribe(e){this._assertUnfrozen(),this._onSubscribe=e}get defaultVersioning(){return this._defaultVersioning}set defaultVersioning(e){this._assertUnfrozen(),this._defaultVersioning=e}get defaultHashFn(){return this._defaultHashFn}set defaultHashFn(e){this._assertUnfrozen(),this._defaultHashFn=e}get inspectorEnabled(){return this._inspectorEnabled}set inspectorEnabled(e){this._inspectorEnabled=e}get globalInspector(){return this._globalInspector}set globalInspector(e){this._globalInspector=e}registerMessageType(e,t){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:t.tier,wireCrossing:t.wireCrossing??t.tier>=3,metaPassthrough:t.metaPassthrough??!0}),this}messageTier(e){let t=this._messageTypes.get(e);return t!=null?t.tier:1}isWireCrossing(e){let t=this._messageTypes.get(e);return t!=null?t.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let t=this._messageTypes.get(e);return t!=null?t.metaPassthrough:!0}isKnownMessageType(e){return this._messageTypes.has(e)}registerCodec(e){return this._assertUnfrozen(),this._codecs.set(e.name,e),this}lookupCodec(e){return this._codecs.get(e)}_isFrozen(){return this._frozen}_assertUnfrozen(){if(this._frozen)throw new Error("GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node.")}};function xe(n){n.registerMessageType(Y,{tier:0,wireCrossing:!1}),n.registerMessageType(M,{tier:1,wireCrossing:!1}),n.registerMessageType(C,{tier:1,wireCrossing:!1,metaPassthrough:!1}),n.registerMessageType(N,{tier:2,wireCrossing:!1}),n.registerMessageType(L,{tier:2,wireCrossing:!1}),n.registerMessageType(m,{tier:3,wireCrossing:!0}),n.registerMessageType(S,{tier:3,wireCrossing:!0}),n.registerMessageType(D,{tier:4,wireCrossing:!0,metaPassthrough:!1}),n.registerMessageType(_,{tier:4,wireCrossing:!0,metaPassthrough:!1}),n.registerMessageType(k,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var F=class extends Error{actor;action;nodeName;constructor(e,t){super(t??`GuardDenied: action "${String(e.action)}" denied for actor type "${String(e.actor.type)}"`),this.name="GuardDenied",this.actor=e.actor,this.action=e.action,this.nodeName=e.nodeName}get node(){return this.nodeName}};function Te(n){return Array.isArray(n)?[...n]:[n]}function Fe(n,e){return n.has(e)||n.has("*")}function Ge(n){let e=[];return n((i,r)=>{e.push({kind:"allow",actions:new Set(Te(i)),where:r?.where??(()=>!0)})},(i,r)=>{e.push({kind:"deny",actions:new Set(Te(i)),where:r?.where??(()=>!0)})}),(i,r)=>{let a=!1,o=!1;for(let d of e)Fe(d.actions,r)&&d.where(i)&&(d.kind==="deny"?a=!0:o=!0);return a?!1:o}}function st(n){return Ge((e,t)=>{for(let s of n){let i=s.actorType==null?null:new Set(Array.isArray(s.actorType)?s.actorType:[s.actorType]),r=s.actorId==null?null:new Set(Array.isArray(s.actorId)?s.actorId:[s.actorId]),a=Object.entries(s.claims??{}),o=d=>{if(i!==null&&!i.has(String(d.type))||r!==null&&!r.has(String(d.id??"")))return!1;for(let[l,c]of a)if(d[l]!==c)return!1;return!0};s.effect==="deny"?t(s.action,{where:o}):e(s.action,{where:o})}})}var Ie=["human","llm","wallet","system"];function it(n){let e=Ie.filter(t=>n({type:t,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(t=>t==="human"||t==="llm"||t==="system")?"both":e.length===1?e[0]:e.join("+")}function ae(n){if(n===void 0)return null;if(typeof n=="number"){if(!Number.isFinite(n))throw new TypeError(`Cannot hash non-finite number: ${n}`);if(Number.isInteger(n)&&!Number.isSafeInteger(n))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${n}. Cross-language cid parity is not guaranteed for unsafe integers.`);return n}if(typeof n=="string"||typeof n=="boolean"||n===null)return n;if(Array.isArray(n))return n.map(ae);if(typeof n=="object"&&n!==null){let e={};for(let t of Object.keys(n).sort())e[t]=ae(n[t]);return e}return null}var He=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ve=new TextEncoder;function Le(n){let e=Ve.encode(n),t=e.length,s=t*8,i=t+9+63&-64,r=new Uint8Array(i);r.set(e),r[t]=128;let a=new DataView(r.buffer);a.setUint32(i-4,s>>>0,!1),a.setUint32(i-8,Math.floor(s/4294967296)>>>0,!1);let o=1779033703,d=3144134277,l=1013904242,c=2773480762,u=1359893119,p=2600822924,h=528734635,b=1541459225,T=new Uint32Array(64),y=(w,g)=>w>>>g|w<<32-g;for(let w=0;w<i;w+=64){for(let f=0;f<16;f++)T[f]=a.getUint32(w+f*4,!1);for(let f=16;f<64;f++){let H=T[f-15],V=T[f-2],K=y(H,7)^y(H,18)^H>>>3,ne=y(V,17)^y(V,19)^V>>>10;T[f]=T[f-16]+K+T[f-7]+ne>>>0}let g=o,G=d,I=l,ee=c,x=u,z=p,q=h,te=b;for(let f=0;f<64;f++){let H=y(x,6)^y(x,11)^y(x,25),V=x&z^~x&q,K=te+H+V+He[f]+T[f]>>>0,ne=y(g,2)^y(g,13)^y(g,22),Se=g&G^g&I^G&I,Ce=ne+Se>>>0;te=q,q=z,z=x,x=ee+K>>>0,ee=I,I=G,G=g,g=K+Ce>>>0}o=o+g>>>0,d=d+G>>>0,l=l+I>>>0,c=c+ee>>>0,u=u+x>>>0,p=p+z>>>0,h=h+q>>>0,b=b+te>>>0}let v=w=>w.toString(16).padStart(8,"0");return v(o)+v(d)+v(l)+v(c)+v(u)+v(p)+v(h)+v(b)}function de(n){let e=ae(n??null),t=JSON.stringify(e);return Le(t).slice(0,16)}function Pe(){let n=globalThis.crypto;if(n?.randomUUID)return n.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),t=e()+e()+e()+e();return`${t.slice(0,8)}-${t.slice(8,12)}-4${t.slice(13,16)}-${(parseInt(t.slice(16,17),16)&3|8).toString(16)}${t.slice(17,20)}-${t.slice(20,32)}`}function le(n,e,t){let s=t?.id??Pe();if(n===0)return{id:s,version:0};let r=(t?.hash??de)(e);return{id:s,version:0,cid:r,prev:null}}function Ne(n,e,t){n.version+=1,"cid"in n&&(n.prev=n.cid,n.cid=t(e))}function ot(n){return"cid"in n}var ke=()=>{},Ae=100;function Ee(n){return{node:n,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function ce(n){n.prevData=void 0,n.dirty=!1,n.involvedThisWave=!1,n.dataBatch.length=0,n.terminal=void 0}function Q(n){return n.length===0?n:typeof n[0]=="symbol"?[n]:n}var Ue=(n,e,t,s)=>{t.direction==="down-in"&&n._onDepMessage(t.depIndex,e)},We=(n,e,t,s)=>{let i=n;if(i._status==="completed"||i._status==="errored")return;let r=i._cached,a=r===void 0?[se]:[se,[m,r]];i._status==="dirty"&&a.push(P),X(e,a,i._config.tierOf)},B=new Z({onMessage:Ue,onSubscribe:We});xe(B);ye(B);function gt(n){if(B._isFrozen())throw new Error("configure() called after a node was created \u2014 the default GraphReFlyConfig is frozen. Call configure(...) at application startup, before any node factories run.");n(B)}var $=class n{_optsName;_describeKind;meta;_hasMeta;_config;_deps;_sinks=null;_sinkCount=0;_cached;_status;_cleanup;_store={};_waveHasNewData=!1;_hasNewTerminal=!1;_hasCalledFnOnce=!1;_paused=!1;_pendingWave=!1;_isExecutingFn=!1;_pendingRerun=!1;_rerunDepth=0;_dirtyDepCount=0;_batchPendingMessages=null;_pauseLocks=null;_pauseBuffer=null;_fn;_equals;_resubscribable;_resetOnTeardown;_autoComplete;_autoError;_pausable;_partial;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,t,s){this._config=s.config??B,this._config.onMessage,this._optsName=s.name,this._describeKind=s.describeKind,this._equals=s.equals??Object.is,this._resubscribable=s.resubscribable??!1,this._resetOnTeardown=s.resetOnTeardown??!1,this._autoComplete=s.completeWhenDepsComplete??!0,this._autoError=s.errorWhenDepsError??!0,this._pausable=s.pausable??!0,this._guard=s.guard,this._fn=t,this._partial=s.partial??!1,this._cached=s.initial!==void 0?s.initial:void 0,this._status=e.length===0&&t==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=s.versioningHash??this._config.defaultHashFn??de;let i=s.versioning??this._config.defaultVersioning;this._versioningLevel=i,this._versioning=i!=null?le(i,this._cached===void 0?void 0:this._cached,{id:s.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(Ee);let r={};for(let[o,d]of Object.entries(s.meta??{})){let l={initial:d,name:`${s.name??"node"}:meta:${o}`,describeKind:"state",config:this._config};s.guard!=null&&(l.guard=s.guard),r[o]=new n([],void 0,l)}Object.freeze(r),this.meta=r,this._hasMeta=Object.keys(r).length>0;let a=this;this._actions={emit(o){a._emit([[m,o]])},down(o){a._emit(Q(o))},up(o){a._emitUp(Q(o))}},this.down=this.down.bind(this),this.up=this.up.bind(this)}get _isTerminal(){return this._status==="completed"||this._status==="errored"}get name(){return this._optsName}get status(){return this._status}get cache(){return this._cached===void 0?void 0:this._cached}get lastMutation(){return this._lastMutation}get v(){return this._versioning}hasGuard(){return this._guard!=null}_applyVersioning(e,t){if(this._isExecutingFn)throw new Error(`Node "${this.name}": _applyVersioning cannot run mid-fn \u2014 call it outside of \`_execFn\` (typically at graph setup time before the first subscribe).`);let s=this._versioningLevel;if(s!=null&&e<=s)return;let i=t?.hash??this._hashFn;i!==this._hashFn&&(this._hashFn=i);let r=this._cached===void 0?void 0:this._cached,a=this._versioning,o=a?.id??t?.id,d=a?.version??0,l=le(e,r,{id:o,hash:i});l.version=d,this._versioning=l,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let t=J(e);if(this._guard!=null&&!this._guard(t,"observe"))return!1;if(this._extraGuards!=null){for(let s of this._extraGuards)if(!s(t,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let t=this._guard!=null||this._extraGuards!=null,s=e?.actor!=null;if(!t&&!s)return;let i=J(e?.actor),r=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(i,r))throw new F({actor:i,action:r,nodeName:this.name});if(this._extraGuards!=null){for(let a of this._extraGuards)if(!a(i,r))throw new F({actor:i,action:r,nodeName:this.name})}this._lastMutation={actor:i,timestamp_ns:we()}}down(e,t){let s=Q(e);s.length!==0&&(this._checkGuard(t),this._emit(s))}emit(e,t){this._checkGuard(t),this._emit([[m,e]])}up(e,t){if(this._deps.length===0)return;let s=Q(e);if(s.length===0)return;this._checkGuard(t);let i=t??{internal:!0};this._validateUpTiers(s);for(let r of this._deps)r.node.up?.(s,i)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let t of this._deps)t.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let t=this._config.tierOf;for(let s of e){let i=t(s[0]);if(i===3||i===4)throw new Error(`Node "${this.name}": tier-${i} messages cannot flow up \u2014 DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \`down(...)\` for value delivery; \`up(...)\` is for control signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).`)}}subscribe(e,t){if(t!=null&&this._guard!=null){let d=J(t);if(!this._guard(d,"observe"))throw new F({actor:d,action:"observe",nodeName:this.name})}let i=this._isTerminal&&this._resubscribable;if(i){this._cached=void 0,this._status="sentinel",this._store={},this._hasCalledFnOnce=!1,this._waveHasNewData=!1,this._hasNewTerminal=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._isExecutingFn=!1,this._rerunDepth=0,this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null;for(let d of this._deps)ce(d);if(this._partial===!1){for(let d of this._deps)if(d.prevData!==void 0||d.dataBatch.length!==0||d.terminal!==void 0||d.dirty)throw new Error(`resubscribable-reset invariant: DepRecord not fully reset for node ${this._optsName??"(anonymous)"}`)}}this._sinkCount+=1;let r;try{r=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:i},this._actions)}catch(d){throw this._sinkCount-=1,d}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let a=this._isTerminal;if(this._sinkCount===1&&!a)try{this._activate()}catch(d){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof r=="function")try{r()}catch{}throw d}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let o=!1;return()=>{o||(o=!0,this._sinkCount-=1,this._removeSink(e),typeof r=="function"&&r(),this._sinks==null&&this._deactivate())}}_removeSink(e){if(this._sinks===e)this._sinks=null;else if(this._sinks!=null&&typeof this._sinks!="function")if(this._sinks.delete(e),this._sinks.size===1){let[t]=this._sinks;this._sinks=t}else this._sinks.size===0&&(this._sinks=null)}_activate(){if(this._deps.length===0){this._fn&&this._execFn();return}this._dirtyDepCount=0;let e=this._deps.length,t=0;try{for(let s=0;s<e;s++){let i=s,r=this._deps[s];r.unsub=ke,r.unsub=r.node.subscribe(a=>{if(r.unsub===null)return;let o=this._config.tierOf,d=!1;for(let l of a)o(l[0])>=3&&(d=!0),this._config.onMessage(this,l,{direction:"down-in",depIndex:i},this._actions);d&&this._maybeRunFnOnSettlement()}),t++}}catch(s){this._deps[t].unsub=null;for(let i=0;i<t;i++){let r=this._deps[i];if(r.unsub!=null){let a=r.unsub;r.unsub=null;try{a()}catch{}ce(r)}}throw this._dirtyDepCount=0,s}}_addDep(e){for(let i=0;i<this._deps.length;i++)if(this._deps[i].node===e)return i;let t=this._deps.length,s=Ee(e);if(this._deps.push(s),this._sinks==null)return t;s.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(ie),s.unsub=ke;try{s.unsub=e.subscribe(i=>{if(s.unsub===null)return;let r=this._config.tierOf,a=!1;for(let o of i)r(o[0])>=3&&(a=!0),this._config.onMessage(this,o,{direction:"down-in",depIndex:t},this._actions);a&&this._maybeRunFnOnSettlement()})}catch(i){throw s.unsub=null,this._deps.pop(),this._dirtyDepCount--,i}return t}_deactivate(e=!1){let t=this._cleanup;if(this._cleanup=void 0,typeof t=="function")try{t()}catch(s){this._emit([[_,this._wrapFnError("cleanup threw",s)]])}else if(t!=null&&typeof t=="object"){let s=t.deactivate;if(typeof s=="function")try{s()}catch(i){this._emit([[_,this._wrapFnError("cleanup.deactivate threw",i)]])}}for(let s of this._deps){if(s.unsub!=null){let i=s.unsub;s.unsub=null;try{i()}catch{}}ce(s)}this._waveHasNewData=!1,this._hasNewTerminal=!1,this._hasCalledFnOnce=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._rerunDepth=0,this._store={},this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null,this._fn!=null&&(this._cached=void 0),e||(this._fn!=null||this._deps.length>0)&&(!this._isTerminal||this._resubscribable)&&(this._status="sentinel")}_onDepMessage(e,t){let s=this._deps[e],i=t[0];if(this._inspectorHooks!=null){let r={kind:"dep_message",depIndex:e,message:t};for(let a of this._inspectorHooks)a(r)}if(i!==Y){if(i===M){this._depDirtied(s);return}if(i===C){if(this._depInvalidated(s),this._cached===void 0)return;this._emit(pe);return}if(i===N||i===L){this._emit([t]);return}if(i===k){this._emit(re);return}if(i===m)this._depSettledAsData(s,t[1]);else if(i===S)this._depSettledAsResolved(s);else if(i===D)this._depSettledAsTerminal(s,!0);else if(i===_)this._depSettledAsTerminal(s,t[1]);else{this._emit([t]);return}if(!this._fn){(i===m||i===S)&&this._emit([t]),(i===D||i===_)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(ie))}_depSettledAsData(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(t),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=t,e.involvedThisWave=!0,this._hasNewTerminal=!0}_depInvalidated(e){e.prevData=void 0,e.terminal=void 0,e.dataBatch.length=0,e.dirty?e.involvedThisWave=!1:(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++)}_maybeRunFnOnSettlement(){if(!(this._isTerminal&&!this._resubscribable)&&!(this._dirtyDepCount>0)){if(!this._partial&&!this._hasCalledFnOnce)for(let e=0;e<this._deps.length;e++){let t=this._deps[e];if(t.dataBatch.length===0&&t.prevData===void 0&&t.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(fe),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(t=>t.terminal!==void 0&&t.terminal!==!0);if(e!=null){this._autoError&&this._emit([[_,e.terminal]]);return}this._autoComplete&&this._deps.every(t=>t.terminal!==void 0)&&this._emit(_e)}_execFn(){if(!this._fn||this._isTerminal&&!this._resubscribable)return;if(this._isExecutingFn){this._pendingRerun=!0;return}let e=this._cleanup;if(typeof e=="function"){this._cleanup=void 0;try{e()}catch(a){this._emit([[_,this._wrapFnError("cleanup threw",a)]]);return}}else if(e!=null&&typeof e=="object"){let a=e.beforeRun;if(typeof a=="function"){e.beforeRun=void 0;try{a()}catch(o){this._emit([[_,this._wrapFnError("cleanup.beforeRun threw",o)]]);return}}}let t=this._deps.map(a=>a.involvedThisWave?a.dataBatch.length>0?[...a.dataBatch]:[]:void 0),s=this._deps.map(a=>a.prevData);for(let a=0;a<this._deps.length;a++){let o=t[a];o!=null&&o.length>0&&(this._deps[a].prevData=o[o.length-1])}let i=this._deps.map(a=>a.terminal),r={prevData:s,terminalDeps:i,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let a={kind:"run",batchData:t,prevData:s};for(let o of this._inspectorHooks)o(a)}this._isExecutingFn=!0;try{let a=this._fn(t,this._actions,r);if(typeof a=="function")this._cleanup=a;else if(a!=null&&typeof a=="object"){let o=a;(typeof o.beforeRun=="function"||typeof o.deactivate=="function"||typeof o.invalidate=="function")&&(this._cleanup=a)}}catch(a){this._emit([[_,this._wrapFnError("fn threw",a)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>Ae?(this._rerunDepth=0,this._emit([[_,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${Ae} \u2014 likely a reactive cycle`)]])):this._maybeRunFnOnSettlement()):this._rerunDepth=0,this._clearWaveFlags()}}_clearWaveFlags(){this._waveHasNewData=!1,this._hasNewTerminal=!1;for(let e of this._deps)e.involvedThisWave=!1,e.dataBatch.length=0}_wrapFnError(e,t){let s=t instanceof Error?t.message:String(t);return new Error(`Node "${this.name}": ${e}: ${s}`,{cause:t})}_frameBatch(e){let t=this._config.tierOf;if(e.length===1)return t(e[0][0])===3&&this._status!=="dirty"?[P,e[0]]:e;let s=!0,i=!1,r=!1,a=-1;for(let d of e){let l=t(d[0]);l<a&&(s=!1),l===3&&(i=!0),d[0]===M&&(r=!0),a=l}let o=e;if(!s){let d=e.map((l,c)=>({m:l,i:c,tier:t(l[0])}));d.sort((l,c)=>l.tier-c.tier||l.i-c.i),o=d.map(l=>l.m)}if(i&&!r&&this._status!=="dirty"){let d=0;for(;d<o.length&&t(o[d][0])===0;)d++;return d===0?[P,...o]:[...o.slice(0,d),P,...o.slice(d)]}return o}_emit(e){if(e.length===0)return;for(let o=0;o<e.length;o++){let d=e[o];if(d[0]===_&&d[1]===void 0)throw new TypeError('[ERROR, payload] requires a non-undefined payload (spec \xA71.2). Pass an Error object or domain tag instead \u2014 e.g. node.down([[ERROR, new Error("reason")]])')}let t=e;if(this._isTerminal&&!this._resubscribable){let o=e.filter(d=>d[0]===k||d[0]===C);if(o.length===0)return;t=o}t=this._frameBatch(t);let i=null;for(let o=0;o<t.length;o++){let d=t[o],l=d[0];if(l!==N&&l!==L){i?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${l===N?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let c=!0;if(this._pausable!==!1){let u=d[1];if(l===N)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(u),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(u))c=!1;else if(this._pauseLocks.delete(u),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let p=this._pauseBuffer;this._pauseBuffer=[],this._emit(p)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?i?.push(d):i==null&&(i=t.slice(0,o))}if(i!=null){if(i.length===0)return;t=i}if(this._hasMeta&&t.some(o=>o[0]===k))for(let o of Object.keys(this.meta))try{this.meta[o]._emit(re)}catch{}let{finalMessages:r,equalsError:a}=this._updateState(t);if(r.length>0&&this._config.inspectorEnabled){let o=this._config.globalInspector;if(o!=null)try{o({kind:"emit",node:this,messages:r})}catch{}}if(r.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let o=this._config.tierOf,d=[];for(let l of r)o(l[0])===3?this._pauseBuffer.push(l):d.push(l);d.length>0&&this._dispatchOrAccumulate(d)}else this._dispatchOrAccumulate(r);a!=null&&this._emit([[_,a]])}_updateState(e){let t=this._config.tierOf,s,i,r=-1,a=0;for(let c of e)t(c[0])===3&&a++;let o=a<=1,d=-1;if(this._versioning!=null&&a>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===m){d=c;break}}for(let c=0;c<e.length;c++){let u=e[c],p=u[0];if(p===m){if(u.length>=2){let h=!1;if(o&&this._cached!==void 0)try{h=this._equals(this._cached,u[1])}catch(b){i=this._wrapFnError("equals threw",b),r=c;break}if(h){s==null&&(s=e.slice(0,c)),s.push(he),this._status="resolved";continue}this._cached=u[1],this._versioning!=null&&(d<0||c===d)&&Ne(this._versioning,u[1],this._hashFn)}this._status="settled",s?.push(u)}else if(s?.push(u),p===M)this._status="dirty";else if(p===S)this._status="resolved";else if(p===D)this._status="completed";else if(p===_)this._status="errored";else if(p===C){this._cached=void 0,this._status="dirty";let h=this._cleanup;if(typeof h=="function"){this._cleanup=void 0;try{h()}catch{}}else if(h!=null&&typeof h=="object"){let b=h.invalidate;if(typeof b=="function")try{b()}catch{}}}else p===k&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let l=r>=0?s??e.slice(0,r):s??e;return i!=null?{finalMessages:l,equalsError:i}:{finalMessages:l}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let t=[...this._sinks];for(let s of t)s(e)};_dispatchOrAccumulate(e){if(be()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],ve(()=>this._flushBatchPending()));for(let t of e)this._batchPendingMessages.push(t);return}X(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let t=this._frameBatch(e);X(this._deliverToSinks,t,this._config.tierOf)}},Me=n=>Array.isArray(n),ue=n=>typeof n=="object"&&n!=null&&!Array.isArray(n);function j(n,e,t){let s=Me(n)?n:[],i=typeof n=="function"?n:typeof e=="function"?e:void 0,r={};return Me(n)?r=(ue(e)?e:t)??{}:ue(n)?r=n:r=(ue(e)?e:t)??{},new $(s,i,r)}function bt(n,e){return j([],{...e,initial:n})}function vt(n,e){return j((s,i,r)=>n(i,r)??void 0,{describeKind:"producer",...e})}function Be(n,e,t){return j(n,(i,r,a)=>{let o=i.map((d,l)=>d!=null&&d.length>0?d.at(-1):a.prevData[l]);r.emit(e(o,a))},{describeKind:"derived",...t})}function wt(n,e,t){return j(n,(i,r,a)=>{let o=i.map((d,l)=>d!=null&&d.length>0?d.at(-1):a.prevData[l]);return e(o,r,a)??void 0},{describeKind:"effect",...t})}function xt(n,e,t){let s=new Map;return n.forEach((i,r)=>{s.set(i,r)}),Be(n,(i,r)=>e(o=>{let d=s.get(o);if(d==null)throw new Error(`dynamicNode: untracked dep "${o.name??"<unnamed>"}"`);return i[d]},r),t)}function Tt(n,e){let t,s=new Map,i=(r,a,o)=>{let d=!1,l=c=>{let u=s.get(c);if(u!==void 0){if(u<r.length){let h=r[u];return h!=null&&h.length>0?h.at(-1):o.prevData[u]}return c.cache}d=!0;let p=t._addDep(c);return s.set(c,p),c.cache};try{let c=n(l,o);d||(a.emit(c),o.store.__autoTrackLastDiscoveryError!=null&&delete o.store.__autoTrackLastDiscoveryError)}catch(c){if(!d)throw c;o.store.__autoTrackLastDiscoveryError=c}};return t=new $([],i,{describeKind:"derived",...e}),t}function Nt(n,...e){let t=n;for(let s of e)t=s(t);return t}export{De as a,$e as b,je as c,oe as d,ze as e,qe as f,ye as g,Ke as h,Oe as i,J as j,me as k,ve as l,Xe as m,X as n,Qe as o,we as p,Z as q,xe as r,F as s,Ge as t,st as u,it as v,de as w,le as x,Ne as y,ot as z,B as A,gt as B,$ as C,j as D,bt as E,vt as F,Be as G,wt as H,xt as I,Tt as J,Nt as K};
@@ -1,43 +0,0 @@
1
- import{a as me}from"./chunk-KD3IYBTD.js";import{u as Q}from"./chunk-2JNT5NDF.js";import{a as pe}from"./chunk-TOCCHQI6.js";import{e as fe}from"./chunk-ZWETYYQG.js";import{a as M}from"./chunk-VXJX3ZZP.js";import{b as J,d as K}from"./chunk-K54OKWNY.js";import{b as de}from"./chunk-LWGLBCMU.js";import{f as le,j as Y}from"./chunk-4JBKKUCJ.js";import{b as A,s as G,t as ce,x as $}from"./chunk-WQ7I7JVU.js";import{m as ue}from"./chunk-UMH3HSP7.js";import{D as ie,E as b,G as k,H as C,o as L}from"./chunk-7AJKUA36.js";import{b as Ie}from"./chunk-QYADASLV.js";var Ye={};Ie(Ye,{DEFAULT_DECAY_RATE:()=>X,DEFAULT_QUEUE_CONFIGS:()=>Z,DEFAULT_SEVERITY_WEIGHTS:()=>z,HarnessGraph:()=>U,QUEUE_NAMES:()=>N,affectedTaskFilter:()=>Oe,beforeAfterCompare:()=>we,codeChangeBridge:()=>Ce,createIntakeBridge:()=>be,defaultErrorClassifier:()=>W,defaultLlmExecutor:()=>ge,defaultLlmVerifier:()=>ye,evalIntakeBridge:()=>Ne,evalSource:()=>Se,evalVerifier:()=>Le,harnessLoop:()=>Fe,harnessProfile:()=>De,harnessTrace:()=>Be,notifyEffect:()=>_e,priorityScore:()=>Ge,refineExecutor:()=>Qe,strategyKey:()=>P,strategyModel:()=>ee});function be(t,e,r,n){return C([t],([a])=>{if(a==null)return;let d=r(a);for(let i of d)e.publish(i)},{name:n?.name??"intake-bridge"})}function Ne(t,e,r){let n=r?.defaultSeverity??"medium";return C([t],([a])=>{if(a==null)return;let d=Array.isArray(a)?a:[a];for(let i of d)for(let o of i.tasks)if(!(o.valid&&o.judge_scores?.every(s=>s.pass))){if(!o.valid&&(!o.judge_scores||o.judge_scores.length===0)){e.publish({source:"eval",summary:`Task ${o.task_id} invalid (model: ${i.model})`,evidence:`Run ${i.run_id}: task produced invalid output`,affectsAreas:["graphspec"],affectsEvalTasks:[o.task_id],severity:n});continue}if(o.judge_scores)for(let s of o.judge_scores)s.pass||e.publish({source:"eval",summary:`${o.task_id}: ${s.claim} (model: ${i.model})`,evidence:s.reasoning,affectsAreas:["graphspec"],affectsEvalTasks:[o.task_id],severity:n})}},{name:r?.name??"eval-intake-bridge"})}function Se(t,e){return $(t,()=>ue(e()))}function we(t,e){return k([t,e],([r,n])=>{let a=r,d=n,i=new Map(a.tasks.map(c=>[c.task_id,c])),o=new Map(d.tasks.map(c=>[c.task_id,c])),s=new Set([...i.keys(),...o.keys()]),u=[],f=[],l=[];for(let c of s){let m=i.get(c),I=o.get(c),g=m?.valid??!1,E=I?.valid??!1,T=m?.judge_scores?m.judge_scores.filter(j=>j.pass).length:void 0,h=I?.judge_scores?I.judge_scores.filter(j=>j.pass).length:void 0,S=T!==void 0&&h!==void 0?h-T:void 0;u.push({taskId:c,before:g,after:E,scoreDiff:S}),g&&!E&&f.push(c),!g&&E&&l.push(c)}return{newFailures:f,resolved:l,taskDeltas:u,overallImproved:l.length>f.length}},{name:"eval-delta"})}function Oe(t,e){let r=e==null?null:Array.isArray(e)?b(e):e,n=[t];return r&&n.push(r),k(n,a=>{let d=a[0],i=r?new Set(a[1]):null,o=new Set;for(let s of d)for(let u of s.affectsEvalTasks??[])(i==null||i.has(u))&&o.add(u);return[...o].sort()},{name:"affected-task-filter"})}function Ce(t,e,r,n){let a=n?.defaultSeverity??"high";function d(o){let s=[];for(let u of o.lintErrors??[])s.push({source:"code-change",summary:`Lint: ${u.rule} in ${u.file}:${u.line}`,evidence:u.message,affectsAreas:[u.file],severity:a});for(let u of o.testFailures??[])s.push({source:"test",summary:`Test failure: ${u.testId}`,evidence:u.message,affectsAreas:[u.file],affectsEvalTasks:[u.testId],severity:a});return s}let i=r??d;return C([t],([o])=>{if(o!=null)for(let s of i(o))e.publish(s)},{name:n?.name??"code-change-bridge"})}function _e(t,e,r){return C([t.latest],([n])=>{n!=null&&e(n)},{name:r?.name??"notify-effect"})}function Ae(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let r of t)e+=r.score;return e/t.length}function $e(t){let{passCount:e,total:r,meanScore:n,threshold:a,missingArtifact:d}=t,i=Number.isFinite(n)?n.toFixed(3):String(n),o=!d&&r>0&&n>=a,s=d?["EXECUTE stage did not emit an artifact; cannot verify reactively"]:o?[`${e}/${r} eval tasks passed; mean score ${i} \u2265 ${a}`]:r===0?["No eval tasks were selected for this item \u2014 cannot verify"]:[`${e}/${r} eval tasks passed; mean score ${i} < threshold ${a}`];return o?{verified:!0,findings:s}:{verified:!1,findings:s,errorClass:"structural"}}function Ve(t){return t.artifact}function Le(t){let e=t.name??"eval-verifier",r=t.threshold??.5,n=t.toOutput??$e,a=t.extractArtifact??Ve;return d=>{let i=A(d,s=>s!=null&&s[0]!=null&&s[1]!=null),o=$(i,([s,u])=>{let f=a(s,u);if(f==null)return b(n({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:r,missingArtifact:!0}));let l=b([f],{name:`${e}/candidates`}),c=b(t.datasetFor(u),{name:`${e}/dataset`}),m=t.evaluator(l,c);return k([m],([I])=>{let g=I;if(g==null)return null;let E=Ae(g),T=g.filter(h=>h.score>=r).length;return n({scores:g,meanScore:E,passCount:T,total:g.length,threshold:r})},{name:`${e}/output`})},{name:e});return A(o,s=>s!=null)}}var N=["auto-fix","needs-decision","investigation","backlog"];function P(t,e){return`${t}\u2192${e}`}function W(t){let e=t.detail.toLowerCase();return e.includes("parse")||e.includes("json")||e.includes("config")||e.includes("validation")||e.includes("syntax")?"self-correctable":"structural"}var z={critical:100,high:70,medium:40,low:10},X=Math.LN2/(168*3600),Z={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1,startOpen:!1}};function ee(){let t=de({name:"strategy-entries"}),e=k([t.entries],([i])=>{let o=i;return new Map(o)},{name:"strategy-model",equals:(i,o)=>{let s=i,u=o;if(s.size!==u.size)return!1;for(let[f,l]of s){let c=u.get(f);if(!c||l.attempts!==c.attempts||l.successes!==c.successes)return!1}return!0}});function r(i,o,s){let u=P(i,o),f=t.get(u),l=(f?.attempts??0)+1,c=(f?.successes??0)+(s?1:0);t.set(u,{rootCause:i,intervention:o,attempts:l,successes:c,successRate:c/l})}function n(i,o){return t.get(P(i,o))}let a=e.subscribe(()=>{});function d(){a()}return{node:e,record:r,lookup:n,dispose:d}}function Ge(t,e,r,n,a){let d={...z,...a?.severityWeights},i=a?.decayRate??X,o=a?.effectivenessThreshold??.7,s=a?.effectivenessBoost??15,u=[t,e,r];return n&&u.push(n),k(u,f=>{let l=f[0],c=f[1],m=f[2],I=n?f[3]:0,g=d[l.severity??"medium"],E=(L()-m)/1e9,T=pe(g,E,i,0),h=P(l.rootCause,l.intervention),S=c.get(h);return S&&S.successRate>=o&&(T+=s),T+=I*20,T},{name:"priority-score"})}var Me=`You are a triage classifier for a reactive collaboration harness.
2
-
3
- Given an intake item, classify it and output JSON:
4
- {
5
- "rootCause": "composition" | "missing-fn" | "bad-docs" | "schema-gap" | "regression" | "unknown",
6
- "intervention": "template" | "catalog-fn" | "docs" | "wrapper" | "schema-change" | "investigate",
7
- "route": "auto-fix" | "needs-decision" | "investigation" | "backlog",
8
- "priority": <number 0-100>,
9
- "triageReasoning": "<one sentence>"
10
- }
11
-
12
- Strategy model (past effectiveness):
13
- {{strategy}}
14
-
15
- Intake item:
16
- {{item}}`,Pe=`You are an implementation agent.
17
-
18
- Given a triaged issue with root cause and intervention type, produce a fix.
19
-
20
- Issue:
21
- {{item}}
22
-
23
- Output JSON:
24
- {
25
- "outcome": "success" | "failure" | "partial",
26
- "detail": "<description of what was done or what failed>"
27
- }`,je=`You are a QA reviewer.
28
-
29
- Given an execution result, verify whether the fix is correct.
30
-
31
- Execution:
32
- {{execution}}
33
-
34
- Original issue:
35
- {{item}}
36
-
37
- Output JSON:
38
- {
39
- "verified": true/false,
40
- "findings": ["<finding1>", ...],
41
- "errorClass": "self-correctable" | "structural" // only if verified=false
42
- }`;function ge(t,e){let r=e??(n=>Pe.replace("{{item}}",JSON.stringify(n)));return n=>Q(t,[n],r,{name:"execute",format:"json"})}function ye(t,e){let r=e??(n=>{let[a,d]=n;return je.replace("{{execution}}",JSON.stringify(a)).replace("{{item}}",JSON.stringify(d))});return n=>Q(t,[n],r,{name:"verify",format:"json"})}var U=class extends Y{intake;queues;gates;strategy;verifyResults;totalRetries;totalReingestions;constructor(e,r,n,a,d,i,o,s){super(e),this.intake=r,this.queues=n,this.gates=a,this.strategy=d,this.verifyResults=i,this.totalRetries=o,this.totalReingestions=s}};function Fe(t,e){let r=e.adapter,n=e.maxRetries??2,a=e.retainedLimit??1e3,d=e.errorClassifier??W,i=new Map;for(let p of N)i.set(p,{...Z[p],...e.queues?.[p]});let o=new M("intake",{retainedLimit:a}),s=ee(),u=G(o.latest,s.node),f=Q(r,[u],e.triagePrompt??(p=>{let[x,R]=p;return x?Me.replace("{{strategy}}",JSON.stringify(Array.from(R.entries()))).replace("{{item}}",JSON.stringify(x)):""}),{name:"triage",format:"json"}),l=new Map;for(let p of N)l.set(p,new M(`queue/${p}`,{retainedLimit:a}));let c=G(f,u),I=C([c],([p])=>{if(p==null)return;let[x,R]=p;if(!x?.route)return;let _=R?.[0],w={...x,..._},D=l.get(w.route);D&&D.publish(w)}).subscribe(()=>{}),g=new Y("gates"),E=new Map;for(let p of N){let x=i.get(p),R=l.get(p);if(x.gated){g.add(R.latest,{name:`${p}/source`});let _=fe(g,`${p}/gate`,`${p}/source`,{maxPending:x.maxPending,startOpen:x.startOpen});E.set(p,_)}}let T=new M("retry-input",{retainedLimit:a}),h=[];for(let p of N)i.get(p).gated&&E.has(p)?h.push(E.get(p).node):h.push(l.get(p).latest);h.push(T.latest);let S=ce(...h),te=(e.executor??ge(r,e.executePrompt))(S),re=G(te,S),F=new M("verify-results",{retainedLimit:a}),ne=(e.verifier??ye(r,e.verifyPrompt))(re),xe=G(ne,re),oe=e.maxReingestions??1,Ee=Math.min(e.maxTotalRetries??n*10,100),Te=Math.min(e.maxTotalReingestions??oe*10,100),se=b(0),ae=b(0),he=ie([xe],(p,x)=>{let R=p[0];if(R==null||R.length===0)return;let _=R[R.length-1];if(_==null)return;let[w,D]=_,[B,y]=D??[null,null];if(!w||!y)return;let Re={item:y,outcome:B?.outcome??"failure",detail:B?.detail??"unknown",artifact:B?.artifact},O={item:y,execution:Re,verified:w.verified,findings:w.findings??[],errorClass:w.errorClass};if(O.verified){s.record(y.rootCause,y.intervention,!0),F.publish(O);return}let ke=O.errorClass??d({item:y,outcome:"failure",detail:O.findings.join("; ")}),q=y._retries??0;if(ke==="self-correctable"&&q<n&&J(se,Ee)){let V=K(y),H={...y,_retries:q+1,summary:`[RETRY ${q+1}/${n}] ${V} \u2014 Previous attempt failed: ${O.findings.join("; ")}`,relatedTo:[V]};T.publish(H)}else{s.record(y.rootCause,y.intervention,!1),F.publish(O);let V=K(y),H=y._reingestions??0;H<oe&&J(ae,Te)&&o.publish({source:"eval",summary:`Verification failed for: ${V}`,evidence:O.findings.join(`
43
- `),affectsAreas:y.affectsAreas,affectsEvalTasks:y.affectsEvalTasks,severity:"high",relatedTo:[V],_reingestions:H+1})}}).subscribe(()=>{}),v=new U(t,o,l,E,s,F,se,ae);v.addDisposer(I),v.addDisposer(he),v.addDisposer(s.dispose),v.add(f,{name:"triage"}),v.add(te,{name:"execute"}),v.add(ne,{name:"verify"}),v.add(s.node,{name:"strategy"}),v.mount("intake",o);for(let[p,x]of l)v.mount(`queue/${p}`,x);return v.mount("gates",g),v.mount("retry-input",T),v.mount("verify-results",F),v}function De(t,e){let r=le(t,e),n={};for(let[a,d]of t.queues)n[a]=d.retained().length;return{...r,queueDepths:n,strategyEntries:t.strategy.node.cache?.size??0,totalRetries:t.totalRetries.cache??0,totalReingestions:t.totalReingestions.cache??0}}function He(t){let{best:e,score:r,status:n}=t,a=Number.isFinite(r)?r.toFixed(3):String(r);return n==="converged"?{outcome:"success",detail:`refineLoop converged at score ${a}`,artifact:e}:n==="budget"?{outcome:"partial",detail:`refineLoop hit budget at score ${a}`,artifact:e}:{outcome:"failure",detail:`refineLoop errored (status=${n})`,artifact:e}}function Qe(t){let e=t.name??"refine-executor",r=t.toOutput??He;return n=>{let a=A(n,i=>i!=null),d=$(a,i=>{let o=me(t.seedFrom(i),t.evaluator,t.strategy,{...t.refine,dataset:t.datasetFor(i),name:`${e}/inner`});return k([o.status,o.best,o.score],([s,u,f])=>{let l=s;return l!=="converged"&&l!=="budget"&&l!=="errored"?null:r({best:u,score:f,status:l})},{name:`${e}/output`})},{name:e});return A(d,i=>i!=null)}}function Ue(t){let e={"intake::latest":"INTAKE",triage:"TRIAGE",execute:"EXECUTE","verify-results::latest":"VERIFY",strategy:"STRATEGY"};for(let r of N)e[`queue/${r}::latest`]="QUEUE";for(let[r]of t.gates)e[`gates::${r}/gate`]="GATE";return e}function Be(t,e){let r=e?.logger===null?null:e?.logger??console.log,n=e?.detail??"summary",a=L(),d=[],i=[],o=Ue(t);function s(){return(L()-a)/1e9}function u(f,l,c){let m={elapsed:s(),stage:f,type:l};n!=="summary"&&(m.summary=qe(c)),n==="full"&&(m.data=c),i.push(m)}for(let[f,l]of Object.entries(o))try{let c=t.observe(f,{format:"stage-log",stageLabels:o,logger:r?m=>r(m):()=>{},includeTypes:["data","error","complete"]});c.onEvent(m=>{m.type==="data"?u(l,"data",m.data):m.type==="error"?u(l,"error",m.data):m.type==="complete"&&u(l,"complete",void 0)}),d.push(c)}catch(c){let m=c instanceof Error?c.message:String(c);u(l,"error",`observe-unavailable: ${f} \u2014 ${m}`),r&&r(`[${s().toFixed(3)}s] ${l.padEnd(9)} \u2717 observe-unavailable: ${m}`)}return{get events(){return i},dispose(){for(let f of d)f.dispose();d.length=0}}}function qe(t){if(t==null)return"null";if(typeof t=="string")return ve(t,80);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return ve(e,120)}catch{return String(t)}}function ve(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}export{be as a,Ne as b,Se as c,we as d,Oe as e,Ce as f,_e as g,Le as h,N as i,P as j,W as k,z as l,X as m,Z as n,ee as o,Ge as p,ge as q,ye as r,U as s,Fe as t,De as u,Qe as v,Be as w,Ye as x};
@@ -1 +0,0 @@
1
- import{c as I}from"./chunk-K54OKWNY.js";import{g as _,j as P}from"./chunk-4JBKKUCJ.js";import{D as y,E as K,G as E,m as F}from"./chunk-7AJKUA36.js";import{b as j,d as x,i as A,j as D}from"./chunk-CK2E7BTU.js";import{b as B}from"./chunk-QYADASLV.js";var ee={};B(ee,{approval:()=>V,branch:()=>U,gate:()=>z,join:()=>J,loop:()=>Q,onFailure:()=>Z,pipeline:()=>L,sensor:()=>Y,subPipeline:()=>X,task:()=>H});function O(e,n){if(typeof n=="string")return{node:e.resolve(n),path:n};let o=$(e,n);if(!o)throw new Error("orchestration dep node must already be registered in the graph so explicit edges can be recorded; pass a string path or register the node first");return{node:n,path:o}}function $(e,n){let o=e.describe(),r=`::${_}::`;for(let t of Object.keys(o.nodes).sort())if(!t.includes(r))try{if(e.resolve(t)===n)return t}catch{}}function w(e,n,o,r){e.add(o,{name:n})}function N(e,n){return I("orchestration",e,n)}function W(e){let n=r=>{let t=r.trim();return t.length===0?0:Number(t)},o;return typeof e=="string"?o=n(e):e===null?o=0:o=Number(e),Number.isFinite(o)?Math.max(0,Math.trunc(o)):1}function L(e,n){return new P(e,n)}function H(e,n,o,r){let a=(r?.deps??[]).map(i=>O(e,i)),{deps:s,...p}=r??{},T=(i,f,c)=>{let l=i.map((h,g)=>h!=null&&h.length>0?h.at(-1):c.prevData[g]);f.emit(o(l,c))},d=y(a.map(i=>i.node),T,{...p,name:n,describeKind:"derived",meta:N("task",r?.meta)});return w(e,n,d,a.flatMap(i=>i.path?[i.path]:[])),d}function U(e,n,o,r,t){let a=O(e,o),s=E([a.node],([p])=>({branch:r(p)?"then":"else",value:p}),{...t,name:n,meta:N("branch",t?.meta)});return w(e,n,s,a.path?[a.path]:[]),s}function V(e,n,o,r,t){let a=O(e,o),s=O(e,r),p=t?.isApproved??(d=>!!d),T=y([a.node,s.node],(d,i,f)=>{let c=d[0],l=d[1],h=l!=null&&l.length>0?l.at(-1):f.prevData[1];if(h===void 0||!p(h)){i.down([[x]]);return}if(c==null||c.length===0){l!=null&&l.length>0&&f.prevData[0]!==void 0?i.emit(f.prevData[0]):i.down([[x]]);return}for(let g of c)i.emit(g)},{...t,name:n,describeKind:"derived",meta:N("approval",t?.meta)});return w(e,n,T,[a.path,s.path].filter(d=>typeof d=="string")),T}function z(e,n,o,r){let t=r?.maxPending??1/0;if(t<1&&t!==1/0)throw new RangeError("gate: maxPending must be >= 1");let a=r?.startOpen??!1,s=O(e,o),p=K([],{name:"pending",equals:()=>!1}),T=K(a,{name:"isOpen"}),d=E([p],([u])=>u.length,{name:"count"}),i=[],f=!1,c=a,l=T.subscribe(u=>{for(let m of u)m[0]===j&&(c=m[1])});function h(){p.emit([...i])}function g(u){i.push(u),i.length>t&&i.shift(),h()}function R(u){let m=i.splice(0,u);return h(),m}function k(u){if(f)throw new Error(`gate: ${u}() called after gate was torn down`)}let b=y([s.node],(u,m,S)=>{let G=S.terminalDeps[0];if(G!==void 0){f=!0,i=[],h(),m.down(G===!0?[[A]]:[[D,G]]);return}let v=u[0];if(v==null||v.length===0){m.down([[x]]);return}for(let C of v)c?m.emit(C):(g(C),m.down([[x]]))},{name:n,describeKind:"derived",meta:N("gate",r?.meta)}),q={node:b,pending:p,count:d,isOpen:T,approve(u=1){k("approve");let m=R(u);for(let S of m){if(f)break;b.emit(S)}},reject(u=1){k("reject"),R(u)},modify(u,m=1){k("modify");let S=[...i],G=R(m);for(let v=0;v<G.length&&!f;v++)b.emit(u(G[v],v,S))},open(){k("open"),F(()=>{T.emit(!0);let u=R(i.length);for(let m of u){if(f)break;b.emit(m)}})},close(){k("close"),T.emit(!1)}};e.addDisposer(d.subscribe(()=>{})),e.addDisposer(l),w(e,n,b,s.path?[s.path]:[]);let M=new P(`${n}_state`);return M.add(p,{name:"pending"}),M.add(T,{name:"isOpen"}),M.add(d,{name:"count"}),e.mount(`${n}_state`,M),q}function J(e,n,o,r){let t=o.map(s=>O(e,s)),a=E(t.map(s=>s.node),s=>s,{...r,name:n,meta:N("join",r?.meta)});return w(e,n,a,t.flatMap(s=>s.path?[s.path]:[])),a}function Q(e,n,o,r,t){let a=O(e,o),s=t?.iterations,p=typeof s=="number"||s===void 0?void 0:O(e,s),T=typeof s=="number"?s:void 0,d=y(p?[a.node,p.node]:[a.node],(i,f,c)=>{let l=i[0],h=l!=null&&l.length>0?l.at(-1):c.prevData[0],g=p?i[1]:void 0,R=T??(p?g!=null&&g.length>0?g.at(-1):c.prevData[1]:1),k=W(R);for(let b=0;b<k;b+=1)h=r(h,b,f);f.emit(h)},{...t,name:n,describeKind:"derived",meta:N("loop",t?.meta)});return w(e,n,d,[a.path,p?.path].filter(i=>typeof i=="string")),d}function X(e,n,o,r){let t=o instanceof P?o:L(n,r);return typeof o=="function"&&o(t),e.mount(n,t),t}function Y(e,n,o,r){let t=y([],()=>{},{...r,name:n,initial:o,describeKind:"producer",meta:N("sensor",r?.meta)});return w(e,n,t,[]),{node:t,push(a){t.emit(a)},error(a){t.down([[D,a]])},complete(){t.down([[A]])}}}function Z(e,n,o,r,t){let a=O(e,o),s=!1,p=y([],(T,d)=>{let i=a.node.subscribe(f=>{for(let c of f){if(s)return;if(c[0]===D)try{d.emit(r(c[1],d))}catch(l){s=!0,d.down([[D,l]])}else d.down([c]),c[0]===A&&(s=!0)}});return()=>i()},{...t,name:n,describeKind:"derived",completeWhenDepsComplete:!1,errorWhenDepsError:!1,meta:N("onFailure",t?.meta)});return w(e,n,p,a.path?[a.path]:[]),p}export{L as a,H as b,U as c,V as d,z as e,J as f,Q as g,X as h,Y as i,Z as j,ee as k};