@graphrefly/graphrefly 0.43.0 → 0.44.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 (279) hide show
  1. package/dist/{cascading-CH-_VwG9.d.cts → cascading-BglDkMdX.d.cts} +2 -2
  2. package/dist/{cascading-OgKQZjsa.d.ts → cascading-MFgxu7Yo.d.ts} +2 -2
  3. package/dist/{chunk-KVV66NN2.js → chunk-2T7U5EU6.js} +1 -1
  4. package/dist/chunk-5M4CCMMD.js +45 -0
  5. package/dist/{chunk-I7IGYPSL.js → chunk-5XJ6B66J.js} +1 -1
  6. package/dist/{chunk-OFZG3TB3.js → chunk-6X7AFUJV.js} +1 -1
  7. package/dist/{chunk-EBW4V6JN.js → chunk-7K6PWTDQ.js} +1 -1
  8. package/dist/{chunk-D27JNOLZ.js → chunk-7LIAPXJB.js} +1 -1
  9. package/dist/{chunk-CLD3F4R5.js → chunk-7WPU3UHQ.js} +1 -1
  10. package/dist/{chunk-NNKJUORL.js → chunk-A5WCQ5NO.js} +1 -1
  11. package/dist/chunk-APPIWSGD.js +84 -0
  12. package/dist/{chunk-TZQPPQEQ.js → chunk-BEZWM2SY.js} +1 -1
  13. package/dist/{chunk-K2Q24F5T.js → chunk-CB676TKJ.js} +1 -1
  14. package/dist/{chunk-SUWT3ZON.js → chunk-CE6TI2TL.js} +1 -1
  15. package/dist/{chunk-VOPGGIL7.js → chunk-CLVB32RD.js} +1 -1
  16. package/dist/{chunk-V5A7M7RJ.js → chunk-CRVT7D2P.js} +1 -1
  17. package/dist/chunk-D7GPHKFH.js +1 -0
  18. package/dist/{chunk-OCKEEPRJ.js → chunk-DHRX7JX4.js} +1 -1
  19. package/dist/chunk-FZMYDOWV.js +1 -0
  20. package/dist/{chunk-35JTVPOX.js → chunk-GHBWHMRZ.js} +1 -1
  21. package/dist/{chunk-KGKJCHEK.js → chunk-GLERH466.js} +1 -1
  22. package/dist/{chunk-TPKQW72B.js → chunk-HIDYF36O.js} +1 -1
  23. package/dist/chunk-HITNVN6B.js +3 -0
  24. package/dist/{chunk-P6C4WHZO.js → chunk-HY4DJBA7.js} +1 -1
  25. package/dist/chunk-KZIEYVXN.js +1 -0
  26. package/dist/{chunk-O2BLLH7M.js → chunk-N4MQX6JU.js} +1 -1
  27. package/dist/{chunk-4YAN45KM.js → chunk-N7FHEL4D.js} +1 -1
  28. package/dist/chunk-NTEURFZH.js +1 -0
  29. package/dist/{chunk-OYJKFY7V.js → chunk-OIVP6KFV.js} +1 -1
  30. package/dist/{chunk-Q4U3A3L5.js → chunk-OPHBU3LG.js} +1 -1
  31. package/dist/{chunk-PT7W5FCD.js → chunk-OYQOZP2F.js} +1 -1
  32. package/dist/{chunk-6HOSXQKF.js → chunk-PTZK576G.js} +1 -1
  33. package/dist/{chunk-S3EEIPO7.js → chunk-ST7UXLWR.js} +1 -1
  34. package/dist/chunk-SVY7VUYU.js +1 -0
  35. package/dist/{chunk-QYVXF7GW.js → chunk-TK3NWWD4.js} +1 -1
  36. package/dist/chunk-UNGSTR4X.js +61 -0
  37. package/dist/{chunk-VQ4A6T2A.js → chunk-VV4N5P64.js} +1 -1
  38. package/dist/{chunk-FDQGFWLF.js → chunk-W3I423PS.js} +1 -1
  39. package/dist/{chunk-XG62INFA.js → chunk-WJR24TAG.js} +1 -1
  40. package/dist/{chunk-F3IGTWCQ.js → chunk-XTGKMHSW.js} +1 -1
  41. package/dist/{chunk-JQFH2DV6.js → chunk-YBB7ZGTY.js} +1 -1
  42. package/dist/{chunk-CUNIRONA.js → chunk-Z4NPUARF.js} +1 -1
  43. package/dist/{chunk-KRH66M4O.js → chunk-ZGNQRPDT.js} +1 -1
  44. package/dist/{chunk-JNWRYDJN.js → chunk-ZKPSFFKU.js} +1 -1
  45. package/dist/{chunk-FG4TKHMC.js → chunk-ZLV5SQSX.js} +1 -1
  46. package/dist/compat/index.cjs +5 -5
  47. package/dist/compat/index.d.cts +16 -16
  48. package/dist/compat/index.d.ts +16 -16
  49. package/dist/compat/index.js +1 -1
  50. package/dist/compat/jotai/index.cjs +1 -1
  51. package/dist/compat/jotai/index.d.cts +2 -2
  52. package/dist/compat/jotai/index.d.ts +2 -2
  53. package/dist/compat/jotai/index.js +1 -1
  54. package/dist/compat/nanostores/index.cjs +1 -1
  55. package/dist/compat/nanostores/index.d.cts +2 -2
  56. package/dist/compat/nanostores/index.d.ts +2 -2
  57. package/dist/compat/nanostores/index.js +1 -1
  58. package/dist/compat/nestjs/index.cjs +5 -5
  59. package/dist/compat/nestjs/index.d.cts +8 -8
  60. package/dist/compat/nestjs/index.d.ts +8 -8
  61. package/dist/compat/nestjs/index.js +1 -1
  62. package/dist/compat/react/index.d.cts +2 -2
  63. package/dist/compat/react/index.d.ts +2 -2
  64. package/dist/compat/solid/index.d.cts +2 -2
  65. package/dist/compat/solid/index.d.ts +2 -2
  66. package/dist/compat/svelte/index.d.cts +2 -2
  67. package/dist/compat/svelte/index.d.ts +2 -2
  68. package/dist/compat/vue/index.d.cts +2 -2
  69. package/dist/compat/vue/index.d.ts +2 -2
  70. package/dist/compat/zustand/index.cjs +3 -3
  71. package/dist/compat/zustand/index.d.cts +4 -4
  72. package/dist/compat/zustand/index.d.ts +4 -4
  73. package/dist/compat/zustand/index.js +1 -1
  74. package/dist/core/index.cjs +1 -1
  75. package/dist/core/index.d.cts +3 -4
  76. package/dist/core/index.d.ts +3 -4
  77. package/dist/core/index.js +1 -1
  78. package/dist/{decay-CdEBmDIs.d.ts → decay-BvOWTZ00.d.ts} +2 -2
  79. package/dist/{decay-2ZukgQ4o.d.cts → decay-CFlLvXUT.d.cts} +2 -2
  80. package/dist/extra/browser.cjs +1 -1
  81. package/dist/extra/browser.d.cts +1 -1
  82. package/dist/extra/browser.d.ts +1 -1
  83. package/dist/extra/browser.js +1 -1
  84. package/dist/extra/index.cjs +15 -15
  85. package/dist/extra/index.d.cts +10 -10
  86. package/dist/extra/index.d.ts +10 -10
  87. package/dist/extra/index.js +1 -1
  88. package/dist/extra/node.cjs +2 -2
  89. package/dist/extra/node.d.cts +1 -1
  90. package/dist/extra/node.d.ts +1 -1
  91. package/dist/extra/node.js +1 -1
  92. package/dist/extra/operators.cjs +1 -1
  93. package/dist/extra/operators.d.cts +9 -1
  94. package/dist/extra/operators.d.ts +9 -1
  95. package/dist/extra/operators.js +1 -1
  96. package/dist/extra/reactive.cjs +1 -1
  97. package/dist/extra/reactive.d.cts +3 -3
  98. package/dist/extra/reactive.d.ts +3 -3
  99. package/dist/extra/reactive.js +1 -1
  100. package/dist/extra/render/index.d.cts +3 -3
  101. package/dist/extra/render/index.d.ts +3 -3
  102. package/dist/extra/sources.cjs +3 -3
  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-Ctlj2tMY.d.cts → fallback-74oxi34l.d.cts} +1 -1
  111. package/dist/{fallback-CqYVLL6X.d.ts → fallback-DUyyBTBK.d.ts} +1 -1
  112. package/dist/graph/index.cjs +7 -7
  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-C4SHb3Ly.d.cts → graph-CWvEUQAq.d.cts} +196 -3
  117. package/dist/{graph-7VguS7a4.d.ts → graph-D9LFnda9.d.ts} +196 -3
  118. package/dist/{index-O7fucFrU.d.cts → index-5k1T6jl0.d.cts} +9 -9
  119. package/dist/{index-DyR7eU5S.d.cts → index-9770hRuQ.d.cts} +4 -4
  120. package/dist/{index-COD1kVoS.d.cts → index-B-_tFaqV.d.cts} +4 -4
  121. package/dist/{index-CLon-IWF.d.cts → index-B17QddL1.d.cts} +4 -4
  122. package/dist/{index-B-i4_g3k.d.ts → index-B1F8Enjf.d.ts} +61 -8
  123. package/dist/{index-DBevwHj_.d.ts → index-B5S8ULbU.d.ts} +3 -3
  124. package/dist/{index-Dgs8zcj7.d.ts → index-B8YnZpIR.d.ts} +2 -2
  125. package/dist/{index-DSZ3ZCHF.d.ts → index-BHskSB8v.d.ts} +28 -17
  126. package/dist/{index-CDXc9zKM.d.cts → index-BIYAkbAi.d.cts} +1 -1
  127. package/dist/{index-C9kSENB4.d.cts → index-BQSKmbuG.d.cts} +1 -1
  128. package/dist/{index-tJoTcnHh.d.cts → index-BaQaY_IQ.d.cts} +2 -2
  129. package/dist/{index-CJK1JkYy.d.ts → index-BmZXHqkE.d.ts} +1 -1
  130. package/dist/{index-K0_0eR8g.d.ts → index-BoJ5JHxI.d.ts} +3 -3
  131. package/dist/{index-JZUPJIJy.d.ts → index-BocU7pqs.d.ts} +4 -4
  132. package/dist/{index-ChOyVLKm.d.cts → index-BrPrLl4e.d.cts} +1 -1
  133. package/dist/{index-BiX1Nkgx.d.cts → index-BxNs2HB9.d.cts} +22 -8
  134. package/dist/{index-Bf7eqeSF.d.ts → index-Byu-OpX_.d.ts} +2 -2
  135. package/dist/{index-BoLv_OfD.d.cts → index-C1T3d7V-.d.cts} +61 -8
  136. package/dist/{index-BTQtTb_H.d.cts → index-C5ri2Axc.d.cts} +3 -3
  137. package/dist/{index-z96luz5O.d.cts → index-C5stwKcw.d.cts} +1 -1
  138. package/dist/{index-D4Y1cMG0.d.ts → index-C9l6OEBL.d.ts} +1 -1
  139. package/dist/{index-CCq87F7t.d.ts → index-CBBLl_rc.d.ts} +1 -1
  140. package/dist/{index-cm1GNcWE.d.ts → index-CBGUK09R.d.ts} +4 -4
  141. package/dist/{index-0rKFCVFp.d.cts → index-CC-AvFTy.d.cts} +3 -3
  142. package/dist/{index-C59mYFKp.d.ts → index-CJF1URuX.d.ts} +9 -9
  143. package/dist/{index-BJX94aud.d.cts → index-CK29LV56.d.cts} +1 -1
  144. package/dist/{index-BP8a88zx.d.ts → index-CMh5Rz1y.d.ts} +4 -4
  145. package/dist/{index-CvrqGfNS.d.ts → index-CPQlGA29.d.ts} +1 -1
  146. package/dist/{index-D-AEQVLo.d.ts → index-CR8QpwX8.d.ts} +49 -24
  147. package/dist/{index-Du7u1lSf.d.cts → index-CS0LTlB8.d.cts} +4 -4
  148. package/dist/{index-Bc41FuHp.d.cts → index-CSOmP7xT.d.cts} +2 -2
  149. package/dist/{index-BsT7F2et.d.ts → index-CYq8vAyV.d.ts} +2 -2
  150. package/dist/{index-CPT7C_f1.d.ts → index-CZ3r5Rxp.d.ts} +4 -4
  151. package/dist/{index-BojK2fwH.d.cts → index-CasX6Pfq.d.cts} +68 -9
  152. package/dist/{index-BG0BN3PB.d.ts → index-CdAlHFEt.d.ts} +1 -1
  153. package/dist/{index-wAzD9yVj.d.ts → index-CdTelp1M.d.ts} +8 -4
  154. package/dist/{index-CQG3D1cp.d.ts → index-CeFiHtAg.d.ts} +4 -4
  155. package/dist/{index-RV_yDjOX.d.cts → index-Cj3WohTd.d.cts} +8 -4
  156. package/dist/{index-BAOD98JD.d.cts → index-Climxqsu.d.cts} +4 -4
  157. package/dist/{index-O16yXPK4.d.cts → index-Co7uli2l.d.cts} +28 -17
  158. package/dist/{index-DIOoAZUX.d.ts → index-CviRnE4K.d.ts} +1 -1
  159. package/dist/{index-Dhc7a7Xo.d.cts → index-Cwv0KWcU.d.cts} +2 -2
  160. package/dist/{index-Dn-wI9g4.d.ts → index-CzLVrjxn.d.ts} +2 -2
  161. package/dist/{index-C9pjcz3l.d.cts → index-D0aciIex.d.cts} +3 -3
  162. package/dist/{index-DwigL4lY.d.ts → index-DHen9Klo.d.ts} +22 -8
  163. package/dist/{index-BwLvVVsy.d.cts → index-DV_1YuVk.d.cts} +40 -8
  164. package/dist/{index-BdGtBX-X.d.cts → index-Dc4AYqrJ.d.cts} +3 -3
  165. package/dist/{index-Dmqp7KjD.d.ts → index-Dgl1HpPn.d.ts} +1 -1
  166. package/dist/{index-CAC_rNzm.d.ts → index-DisjX8a-.d.ts} +40 -8
  167. package/dist/{index-B5iz82A3.d.cts → index-UPSiS-X7.d.cts} +49 -24
  168. package/dist/{index-CZQXo5tH.d.ts → index-Yq60JP3s.d.ts} +3 -3
  169. package/dist/{index-f5IivDUX.d.cts → index-ZVQhLa2i.d.cts} +1 -1
  170. package/dist/{index-hHcaFlJX.d.cts → index-_6ODbuOu.d.cts} +1 -1
  171. package/dist/{index-BVpm6noz.d.cts → index-hcDJ8PSI.d.cts} +1 -1
  172. package/dist/{index-DBHK8O6H.d.ts → index-nozs3fFC.d.ts} +3 -3
  173. package/dist/{index-Dh_HJ82K.d.ts → index-p09KSrTN.d.ts} +68 -9
  174. package/dist/{index-C7O6r5fV.d.ts → index-sqkqlb1p.d.ts} +1 -1
  175. package/dist/{index-CZjOhcBy.d.cts → index-tRCxuAXF.d.cts} +2 -2
  176. package/dist/index.cjs +48 -48
  177. package/dist/index.d.cts +42 -43
  178. package/dist/index.d.ts +42 -43
  179. package/dist/index.js +1 -1
  180. package/dist/{node-ClS5yC-B.d.cts → node-kK3CvTrR.d.cts} +1 -1
  181. package/dist/{node-ClS5yC-B.d.ts → node-kK3CvTrR.d.ts} +1 -1
  182. package/dist/{observable-BsBzUrcI.d.ts → observable-DWjNfLvC.d.ts} +1 -1
  183. package/dist/{observable-DLGPPtb8.d.cts → observable-e3eiPPFy.d.cts} +1 -1
  184. package/dist/patterns/ai/browser.cjs +5 -5
  185. package/dist/patterns/ai/browser.d.cts +4 -4
  186. package/dist/patterns/ai/browser.d.ts +4 -4
  187. package/dist/patterns/ai/browser.js +1 -1
  188. package/dist/patterns/ai/index.cjs +16 -16
  189. package/dist/patterns/ai/index.d.cts +16 -17
  190. package/dist/patterns/ai/index.d.ts +16 -17
  191. package/dist/patterns/ai/index.js +1 -1
  192. package/dist/patterns/ai/node.cjs +1 -1
  193. package/dist/patterns/ai/node.d.cts +4 -4
  194. package/dist/patterns/ai/node.d.ts +4 -4
  195. package/dist/patterns/ai/node.js +1 -1
  196. package/dist/patterns/cqrs/index.cjs +3 -3
  197. package/dist/patterns/cqrs/index.d.cts +6 -6
  198. package/dist/patterns/cqrs/index.d.ts +6 -6
  199. package/dist/patterns/cqrs/index.js +1 -1
  200. package/dist/patterns/demo-shell/index.cjs +5 -5
  201. package/dist/patterns/demo-shell/index.d.cts +5 -5
  202. package/dist/patterns/demo-shell/index.d.ts +5 -5
  203. package/dist/patterns/demo-shell/index.js +1 -1
  204. package/dist/patterns/domain-templates/index.cjs +3 -3
  205. package/dist/patterns/domain-templates/index.d.cts +4 -4
  206. package/dist/patterns/domain-templates/index.d.ts +4 -4
  207. package/dist/patterns/domain-templates/index.js +1 -1
  208. package/dist/patterns/graphspec/index.cjs +16 -16
  209. package/dist/patterns/graphspec/index.d.cts +5 -5
  210. package/dist/patterns/graphspec/index.d.ts +5 -5
  211. package/dist/patterns/graphspec/index.js +1 -1
  212. package/dist/patterns/harness/index.cjs +9 -9
  213. package/dist/patterns/harness/index.d.cts +10 -11
  214. package/dist/patterns/harness/index.d.ts +10 -11
  215. package/dist/patterns/harness/index.js +1 -1
  216. package/dist/patterns/inspect/index.cjs +3 -3
  217. package/dist/patterns/inspect/index.d.cts +7 -7
  218. package/dist/patterns/inspect/index.d.ts +7 -7
  219. package/dist/patterns/inspect/index.js +1 -1
  220. package/dist/patterns/job-queue/index.cjs +3 -3
  221. package/dist/patterns/job-queue/index.d.cts +6 -6
  222. package/dist/patterns/job-queue/index.d.ts +6 -6
  223. package/dist/patterns/job-queue/index.js +1 -1
  224. package/dist/patterns/memory/index.cjs +3 -3
  225. package/dist/patterns/memory/index.d.cts +6 -6
  226. package/dist/patterns/memory/index.d.ts +6 -6
  227. package/dist/patterns/memory/index.js +1 -1
  228. package/dist/patterns/messaging/index.cjs +3 -3
  229. package/dist/patterns/messaging/index.d.cts +5 -5
  230. package/dist/patterns/messaging/index.d.ts +5 -5
  231. package/dist/patterns/messaging/index.js +1 -1
  232. package/dist/patterns/orchestration/index.cjs +3 -3
  233. package/dist/patterns/orchestration/index.d.cts +6 -7
  234. package/dist/patterns/orchestration/index.d.ts +6 -7
  235. package/dist/patterns/orchestration/index.js +1 -1
  236. package/dist/patterns/process/index.cjs +3 -1
  237. package/dist/patterns/process/index.d.cts +7 -7
  238. package/dist/patterns/process/index.d.ts +7 -7
  239. package/dist/patterns/process/index.js +1 -1
  240. package/dist/patterns/reactive-layout/index.cjs +4 -4
  241. package/dist/patterns/reactive-layout/index.d.cts +5 -5
  242. package/dist/patterns/reactive-layout/index.d.ts +5 -5
  243. package/dist/patterns/reactive-layout/index.js +1 -1
  244. package/dist/patterns/reduction/index.cjs +3 -3
  245. package/dist/patterns/reduction/index.d.cts +4 -4
  246. package/dist/patterns/reduction/index.d.ts +4 -4
  247. package/dist/patterns/reduction/index.js +1 -1
  248. package/dist/patterns/surface/index.cjs +10 -10
  249. package/dist/patterns/surface/index.d.cts +6 -6
  250. package/dist/patterns/surface/index.d.ts +6 -6
  251. package/dist/patterns/surface/index.js +1 -1
  252. package/dist/{pipeline-graph-DPqKDk59.d.cts → pipeline-graph-CIKhynsF.d.cts} +11 -6
  253. package/dist/{pipeline-graph-loP57TBA.d.ts → pipeline-graph-Sgj0gCwn.d.ts} +11 -6
  254. package/dist/{reactive-layout-v7KPvxoc.d.ts → reactive-layout-DOTs9P3X.d.ts} +2 -2
  255. package/dist/{reactive-layout-Dsvob4zD.d.cts → reactive-layout-DgctbqZo.d.cts} +2 -2
  256. package/dist/{reactive-log-BezYsbA_.d.ts → reactive-log-BKALbfal.d.ts} +1 -1
  257. package/dist/{reactive-log-B00laMSQ.d.cts → reactive-log-DIGdYqQ6.d.cts} +1 -1
  258. package/dist/{reactive-map-48mnZ-nu.d.cts → reactive-map-CEFGp8TK.d.cts} +1 -1
  259. package/dist/{reactive-map-BVVPdvmi.d.ts → reactive-map-DS_SIAxv.d.ts} +1 -1
  260. package/dist/resilience-6LYQJAC5.js +1 -0
  261. package/dist/{sugar-DLwvMr3F.d.ts → sugar-DQjFmVqb.d.cts} +178 -2
  262. package/dist/{sugar-DyVGtczU.d.cts → sugar-fhLIE7TT.d.ts} +178 -2
  263. package/dist/{topology-tree-BSdfSwMi.d.cts → topology-tree-Bcz27hpF.d.cts} +1 -1
  264. package/dist/{topology-tree-BNGvuG82.d.ts → topology-tree-xvaD0fOX.d.ts} +1 -1
  265. package/dist/{types-B1jDWVsM.d.cts → types-C0_yquda.d.cts} +1 -1
  266. package/dist/{types-DkzUUs0H.d.ts → types-CWFysE9E.d.ts} +1 -1
  267. package/package.json +1 -1
  268. package/dist/chunk-3XDYJRYU.js +0 -1
  269. package/dist/chunk-4I45FVQS.js +0 -1
  270. package/dist/chunk-626TESAC.js +0 -3
  271. package/dist/chunk-INQD2KRQ.js +0 -1
  272. package/dist/chunk-LYCLF26R.js +0 -1
  273. package/dist/chunk-NON4NLIC.js +0 -45
  274. package/dist/chunk-QE4IGY7I.js +0 -61
  275. package/dist/chunk-VNC3TMVY.js +0 -1
  276. package/dist/chunk-Y4NI3X7O.js +0 -84
  277. package/dist/meta-BgVAsg9j.d.ts +0 -102
  278. package/dist/meta-vE8bxW1E.d.cts +0 -102
  279. package/dist/resilience-YIWPK4YC.js +0 -1
@@ -1,21 +1,21 @@
1
- "use strict";var $n=Object.defineProperty;var li=Object.getOwnPropertyDescriptor;var pi=Object.getOwnPropertyNames;var fi=Object.prototype.hasOwnProperty;var ne=(t,e)=>()=>(t&&(e=t(t=0)),e);var jn=(t,e)=>{for(var n in e)$n(t,n,{get:e[n],enumerable:!0})},mi=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of pi(e))!fi.call(t,o)&&o!==n&&$n(t,o,{get:()=>e[o],enumerable:!(r=li(e,o))||r.enumerable});return t};var gi=t=>mi($n({},"__esModule",{value:!0}),t);function so(t,e){let n=new TextEncoder().encode(t.name);if(n.length===0||n.length>255)throw new Error(`encodeEnvelope: codec name "${t.name}" encodes to ${n.length} bytes (must be 1\u2013255)`);let r=t.version;if(!Number.isInteger(r)||r<0||r>65535)throw new Error(`encodeEnvelope: codec.version ${r} out of u16 range (expected integer 0\u201365535)`);let o=2+n.length+2+e.length;if(o>4294967295)throw new Error(`encodeEnvelope: total envelope size ${o} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let s=new Uint8Array(o),a=0;return s[a++]=Bn,s[a++]=n.length,s.set(n,a),a+=n.length,s[a++]=r>>>8&255,s[a++]=r&255,s.set(e,a),s}function io(t,e){if(t.length<oo)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${oo})`);let n=0,r=t[n++];if(r!==Bn)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${Bn})`);let o=t[n++];if(o===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(n+o+2>t.length)throw new Error(`decodeEnvelope: envelope truncated (need ${n+o+2} bytes, have ${t.length})`);let s=new TextDecoder().decode(t.subarray(n,n+o));n+=o;let a=(t[n]<<8|t[n+1])>>>0;n+=2;let i=t.subarray(n),d=e.lookupCodec(s);if(d==null)throw new Error(`decodeEnvelope: codec "${s}" not registered (envelope codec_v=${a})`);return{codec:d,codecVersion:a,payload:i}}function ao(t){t.registerCodec(hi)}var hi,Bn,oo,Vn=ne(()=>{"use strict";hi={name:"json",version:1,contentType:"application/json",encode(t){let e=JSON.stringify(t);return new TextEncoder().encode(e)},decode(t,e){let n=new TextDecoder().decode(t);return JSON.parse(n)}},Bn=1,oo=4});function Ut(t){if(t==null)return ct;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var ct,qt=ne(()=>{"use strict";ct={type:"system",id:""}});function Wt(){return lt>0||_t}function uo(){return lt>0}function ft(t){lt>0?Mt.push(t):t()}function re(t){lt+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(lt-=1,lt===0)if(e){if(!_t){let n=Mt.splice(0);for(let r of n)try{r()}catch{}Ze.length=0,et.length=0,pt.length=0}}else yi()}}function yi(){let t=!_t;t&&(_t=!0);let e=[],n=0;try{for(;Ze.length>0||et.length>0||pt.length>0||t&&Mt.length>0;){if(t&&Mt.length>0){let s=Mt.splice(0);for(let a of s)try{a()}catch(i){e.push(i)}continue}if(n+=1,n>1e3)throw Ze.length=0,et.length=0,pt.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let o=(Ze.length>0?Ze:et.length>0?et:pt).splice(0);for(let s of o)try{s()}catch(a){e.push(a)}}}finally{t&&(_t=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function Ht(t,e,n){if(e.length===0)return;if(e.length===1){let u=n(e[0][0]);if(u<3||!Wt()){t(e);return}(u>=5?pt:u===4?et:Ze).push(()=>t(e));return}let r=e.length,o=r,s=r,a=r,i=0;for(;i<r&&n(e[i][0])<3;)i++;for(o=i;i<r&&n(e[i][0])===3;)i++;for(s=i;i<r&&n(e[i][0])===4;)i++;a=i;let d=Wt();if(o>0){let u=e.slice(0,o);t(u)}if(s>o){let u=e.slice(o,s);d?Ze.push(()=>t(u)):t(u)}if(a>s){let u=e.slice(s,a);d?et.push(()=>t(u)):t(u)}if(r>a){let u=e.slice(a,r);d?pt.push(()=>t(u)):t(u)}}var lt,_t,Ze,et,pt,Mt,Me=ne(()=>{"use strict";lt=0,_t=!1,Ze=[],et=[],pt=[],Mt=[]});function z(){return Math.trunc(performance.now()*1e6)}function ce(){return Date.now()*1e6}var ye=ne(()=>{"use strict"});var Be,D,X,U,Ce,Se,Le,fe,$,P,tt,Jt,co,Yt,lo,po,Qt,Kn,zn,Un,Xt,de=ne(()=>{"use strict";Be=Symbol.for("graphrefly/START"),D=Symbol.for("graphrefly/DATA"),X=Symbol.for("graphrefly/DIRTY"),U=Symbol.for("graphrefly/RESOLVED"),Ce=Symbol.for("graphrefly/INVALIDATE"),Se=Symbol.for("graphrefly/PAUSE"),Le=Symbol.for("graphrefly/RESUME"),fe=Symbol.for("graphrefly/TEARDOWN"),$=Symbol.for("graphrefly/COMPLETE"),P=Symbol.for("graphrefly/ERROR"),tt=Object.freeze([X]),Jt=Object.freeze([U]),co=Object.freeze([Ce]),Yt=Object.freeze([Be]),lo=Object.freeze([$]),po=Object.freeze([fe]),Qt=Object.freeze([tt]),Kn=Object.freeze([Jt]),zn=Object.freeze([co]),Un=Object.freeze([lo]),Xt=Object.freeze([po])});function fo(t){t.registerMessageType(Be,{tier:0,wireCrossing:!1}),t.registerMessageType(X,{tier:1,wireCrossing:!1}),t.registerMessageType(Ce,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(Se,{tier:2,wireCrossing:!1}),t.registerMessageType(Le,{tier:2,wireCrossing:!1}),t.registerMessageType(D,{tier:3,wireCrossing:!0}),t.registerMessageType(U,{tier:3,wireCrossing:!0}),t.registerMessageType($,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(P,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(fe,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var Zt,mo=ne(()=>{"use strict";de();Zt=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_rigorRecorder;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=n=>{let r=this._messageTypes.get(n);return r!=null?r.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}get rigorRecorder(){return this._rigorRecorder}set rigorRecorder(e){this._rigorRecorder=e}registerMessageType(e,n){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:n.tier,wireCrossing:n.wireCrossing??n.tier>=3,metaPassthrough:n.metaPassthrough??!0}),this}messageTier(e){let n=this._messageTypes.get(e);return n!=null?n.tier:1}isWireCrossing(e){let n=this._messageTypes.get(e);return n!=null?n.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let n=this._messageTypes.get(e);return n!=null?n.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 go(t){return Array.isArray(t)?[...t]:[t]}function bi(t,e){return t.has(e)||t.has("*")}function ho(t){let e=[];return t((o,s)=>{e.push({kind:"allow",actions:new Set(go(o)),where:s?.where??(()=>!0)})},(o,s)=>{e.push({kind:"deny",actions:new Set(go(o)),where:s?.where??(()=>!0)})}),(o,s)=>{let a=!1,i=!1;for(let d of e)bi(d.actions,s)&&d.where(o)&&(d.kind==="deny"?a=!0:i=!0);return a?!1:i}}function qn(t){let e=Ti.filter(n=>t({type:n,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(n=>n==="human"||n==="llm"||n==="system")?"both":e.length===1?e[0]:e.join("+")}var De,Ti,mt=ne(()=>{"use strict";De=class extends Error{actor;action;nodeName;constructor(e,n){super(n??`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}};Ti=["human","llm","wallet","system"]});function Wn(t){if(t===void 0)return null;if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`Cannot hash non-finite number: ${t}`);if(Number.isInteger(t)&&!Number.isSafeInteger(t))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${t}. Cross-language cid parity is not guaranteed for unsafe integers.`);return t}if(typeof t=="string"||typeof t=="boolean"||t===null)return t;if(Array.isArray(t))return t.map(Wn);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=Wn(t[n]);return e}return null}function ki(t){let e=wi.encode(t),n=e.length,r=n*8,o=n+9+63&-64,s=new Uint8Array(o);s.set(e),s[n]=128;let a=new DataView(s.buffer);a.setUint32(o-4,r>>>0,!1),a.setUint32(o-8,Math.floor(r/4294967296)>>>0,!1);let i=1779033703,d=3144134277,u=1013904242,c=2773480762,l=1359893119,p=2600822924,f=528734635,m=1541459225,h=new Uint32Array(64),g=(T,y)=>T>>>y|T<<32-y;for(let T=0;T<o;T+=64){for(let M=0;M<16;M++)h[M]=a.getUint32(T+M*4,!1);for(let M=16;M<64;M++){let L=h[M-15],S=h[M-2],O=g(L,7)^g(L,18)^L>>>3,I=g(S,17)^g(S,19)^S>>>10;h[M]=h[M-16]+O+h[M-7]+I>>>0}let y=i,v=d,k=u,N=c,w=l,R=p,x=f,_=m;for(let M=0;M<64;M++){let L=g(w,6)^g(w,11)^g(w,25),S=w&R^~w&x,O=_+L+S+vi[M]+h[M]>>>0,I=g(y,2)^g(y,13)^g(y,22),K=y&v^y&k^v&k,q=I+K>>>0;_=x,x=R,R=w,w=N+O>>>0,N=k,k=v,v=y,y=O+q>>>0}i=i+y>>>0,d=d+v>>>0,u=u+k>>>0,c=c+N>>>0,l=l+w>>>0,p=p+R>>>0,f=f+x>>>0,m=m+_>>>0}let b=T=>T.toString(16).padStart(8,"0");return b(i)+b(d)+b(u)+b(c)+b(l)+b(p)+b(f)+b(m)}function Hn(t){let e=Wn(t??null),n=JSON.stringify(e);return ki(n).slice(0,16)}function xi(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),n=e()+e()+e()+e();return`${n.slice(0,8)}-${n.slice(8,12)}-4${n.slice(13,16)}-${(parseInt(n.slice(16,17),16)&3|8).toString(16)}${n.slice(17,20)}-${n.slice(20,32)}`}function Jn(t,e,n){let r=n?.id??xi();if(t===0)return{id:r,version:0};let s=(n?.hash??Hn)(e);return{id:r,version:0,cid:s,prev:null}}function yo(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}var vi,wi,bo=ne(()=>{"use strict";vi=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]),wi=new TextEncoder});function wo(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function Yn(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function en(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function te(t,e,n){let r=ko(t)?t:[],o=typeof t=="function"?t:typeof e=="function"?e:void 0,s={};return ko(t)?s=(Qn(e)?e:n)??{}:Qn(t)?s=t:s=(Qn(e)?e:n)??{},new me(r,o,s)}var To,vo,Ri,Si,gt,me,ko,Qn,we=ne(()=>{"use strict";Vn();qt();Me();ye();mo();mt();de();bo();To=()=>{},vo=100;Ri=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},Si=(t,e,n,r)=>{let o=t;if(o._status==="completed"||o._status==="errored")return;let s=o._cached,a=s===void 0?[Yt]:[Yt,[D,s]];o._status==="dirty"&&a.push(tt),Ht(e,a,o._config.tierOf)},gt=new Zt({onMessage:Ri,onSubscribe:Si});fo(gt);ao(gt);me=class t{_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,n,r){this._config=r.config??gt,this._config.onMessage,this._optsName=r.name,this._describeKind=r.describeKind,this._equals=r.equals??Object.is,this._resubscribable=r.resubscribable??!1,this._resetOnTeardown=r.resetOnTeardown??!1,this._autoComplete=r.completeWhenDepsComplete??!0,this._autoError=r.errorWhenDepsError??!0,this._pausable=r.pausable??!0,this._guard=r.guard,this._fn=n,this._partial=r.partial??!1,this._cached=r.initial!==void 0?r.initial:void 0,this._status=e.length===0&&n==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=r.versioningHash??this._config.defaultHashFn??Hn;let o=r.versioning??this._config.defaultVersioning;this._versioningLevel=o,this._versioning=o!=null?Jn(o,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(wo);let s={};for(let[i,d]of Object.entries(r.meta??{})){let u={initial:d,name:`${r.name??"node"}:meta:${i}`,describeKind:"state",config:this._config};r.guard!=null&&(u.guard=r.guard),s[i]=new t([],void 0,u)}Object.freeze(s),this.meta=s,this._hasMeta=Object.keys(s).length>0;let a=this;this._actions={emit(i){a._emit([[D,i]])},down(i){a._emit(en(i))},up(i){a._emitUp(en(i))}},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,n){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 r=this._versioningLevel;if(r!=null&&e<=r)return;let o=n?.hash??this._hashFn;o!==this._hashFn&&(this._hashFn=o);let s=this._cached===void 0?void 0:this._cached,a=this._versioning,i=a?.id??n?.id,d=a?.version??0,u=Jn(e,s,{id:i,hash:o});u.version=d,this._versioning=u,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 n=Ut(e);if(this._guard!=null&&!this._guard(n,"observe"))return!1;if(this._extraGuards!=null){for(let r of this._extraGuards)if(!r(n,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let n=this._guard!=null||this._extraGuards!=null,r=e?.actor!=null;if(!n&&!r)return;let o=Ut(e?.actor),s=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(o,s))throw new De({actor:o,action:s,nodeName:this.name});if(this._extraGuards!=null){for(let a of this._extraGuards)if(!a(o,s))throw new De({actor:o,action:s,nodeName:this.name})}this._lastMutation={actor:o,timestamp_ns:ce()}}down(e,n){let r=en(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[D,e]])}up(e,n){if(this._deps.length===0)return;let r=en(e);if(r.length===0)return;this._checkGuard(n);let o=n??{internal:!0};this._validateUpTiers(r);for(let s of this._deps)s.node.up?.(r,o)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let n of this._deps)n.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let n=this._config.tierOf;for(let r of e){let o=n(r[0]);if(o===3||o===4)throw new Error(`Node "${this.name}": tier-${o} 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,n){if(n!=null&&this._guard!=null){let d=Ut(n);if(!this._guard(d,"observe"))throw new De({actor:d,action:"observe",nodeName:this.name})}let o=this._isTerminal&&this._resubscribable;if(o){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)Yn(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 s;try{s=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:o},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 s=="function")try{s()}catch{}throw d}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let i=!1;return()=>{i||(i=!0,this._sinkCount-=1,this._removeSink(e),typeof s=="function"&&s(),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[n]=this._sinks;this._sinks=n}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,n=0;try{for(let r=0;r<e;r++){let o=r,s=this._deps[r];s.unsub=To,s.unsub=s.node.subscribe(a=>{if(s.unsub===null)return;let i=this._config.tierOf,d=!1;for(let u of a)i(u[0])>=3&&(d=!0),this._config.onMessage(this,u,{direction:"down-in",depIndex:o},this._actions);d&&this._maybeRunFnOnSettlement()}),n++}}catch(r){this._deps[n].unsub=null;for(let o=0;o<n;o++){let s=this._deps[o];if(s.unsub!=null){let a=s.unsub;s.unsub=null;try{a()}catch{}Yn(s)}}throw this._dirtyDepCount=0,r}}_addDep(e){for(let o=0;o<this._deps.length;o++)if(this._deps[o].node===e)return o;let n=this._deps.length,r=wo(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Qt),r.unsub=To;try{r.unsub=e.subscribe(o=>{if(r.unsub===null)return;let s=this._config.tierOf,a=!1;for(let i of o)s(i[0])>=3&&(a=!0),this._config.onMessage(this,i,{direction:"down-in",depIndex:n},this._actions);a&&this._maybeRunFnOnSettlement()})}catch(o){throw r.unsub=null,this._deps.pop(),this._dirtyDepCount--,o}return n}_deactivate(e=!1){let n=this._cleanup;if(this._cleanup=void 0,typeof n=="function")try{n()}catch(r){this._emit([[P,this._wrapFnError("cleanup threw",r)]])}else if(n!=null&&typeof n=="object"){let r=n.deactivate;if(typeof r=="function")try{r()}catch(o){this._emit([[P,this._wrapFnError("cleanup.deactivate threw",o)]])}}for(let r of this._deps){if(r.unsub!=null){let o=r.unsub;r.unsub=null;try{o()}catch{}}Yn(r)}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,n){let r=this._deps[e],o=n[0];if(this._inspectorHooks!=null){let s={kind:"dep_message",depIndex:e,message:n};for(let a of this._inspectorHooks)a(s)}if(o!==Be){if(o===X){this._depDirtied(r);return}if(o===Ce){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(zn);return}if(o===Se||o===Le){this._emit([n]);return}if(o===fe){this._emit(Xt);return}if(o===D)this._depSettledAsData(r,n[1]);else if(o===U)this._depSettledAsResolved(r);else if(o===$)this._depSettledAsTerminal(r,!0);else if(o===P)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(o===D||o===U)&&this._emit([n]),(o===$||o===P)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Qt))}_depSettledAsData(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(n),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=n,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 n=this._deps[e];if(n.dataBatch.length===0&&n.prevData===void 0&&n.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(Kn),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(n=>n.terminal!==void 0&&n.terminal!==!0);if(e!=null){this._autoError&&this._emit([[P,e.terminal]]);return}this._autoComplete&&this._deps.every(n=>n.terminal!==void 0)&&this._emit(Un)}_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([[P,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(i){this._emit([[P,this._wrapFnError("cleanup.beforeRun threw",i)]]);return}}}let n=this._deps.map(a=>a.involvedThisWave?a.dataBatch.length>0?[...a.dataBatch]:[]:void 0),r=this._deps.map(a=>a.prevData);for(let a=0;a<this._deps.length;a++){let i=n[a];i!=null&&i.length>0&&(this._deps[a].prevData=i[i.length-1])}let o=this._deps.map(a=>a.terminal),s={prevData:r,terminalDeps:o,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let a={kind:"run",batchData:n,prevData:r};for(let i of this._inspectorHooks)i(a)}this._isExecutingFn=!0;try{let a=this._fn(n,this._actions,s);if(typeof a=="function")this._cleanup=a;else if(a!=null&&typeof a=="object"){let i=a;(typeof i.beforeRun=="function"||typeof i.deactivate=="function"||typeof i.invalidate=="function")&&(this._cleanup=a)}}catch(a){this._emit([[P,this._wrapFnError("fn threw",a)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>vo?(this._rerunDepth=0,this._emit([[P,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${vo} \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,n){let r=n instanceof Error?n.message:String(n);return new Error(`Node "${this.name}": ${e}: ${r}`,{cause:n})}_frameBatch(e){let n=this._config.tierOf;if(e.length===1)return n(e[0][0])===3&&this._status!=="dirty"?[tt,e[0]]:e;let r=!0,o=!1,s=!1,a=-1;for(let d of e){let u=n(d[0]);u<a&&(r=!1),u===3&&(o=!0),d[0]===X&&(s=!0),a=u}let i=e;if(!r){let d=e.map((u,c)=>({m:u,i:c,tier:n(u[0])}));d.sort((u,c)=>u.tier-c.tier||u.i-c.i),i=d.map(u=>u.m)}if(o&&!s&&this._status!=="dirty"){let d=0;for(;d<i.length&&n(i[d][0])===0;)d++;return d===0?[tt,...i]:[...i.slice(0,d),tt,...i.slice(d)]}return i}_emit(e){if(e.length===0)return;for(let i=0;i<e.length;i++){let d=e[i];if(d[0]===P&&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 n=e;if(this._isTerminal&&!this._resubscribable){let i=e.filter(d=>d[0]===fe||d[0]===Ce);if(i.length===0)return;n=i}n=this._frameBatch(n);let o=null;for(let i=0;i<n.length;i++){let d=n[i],u=d[0];if(u!==Se&&u!==Le){o?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${u===Se?"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 l=d[1];if(u===Se)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(l),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(l))c=!1;else if(this._pauseLocks.delete(l),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?o?.push(d):o==null&&(o=n.slice(0,i))}if(o!=null){if(o.length===0)return;n=o}if(this._hasMeta&&n.some(i=>i[0]===fe))for(let i of Object.keys(this.meta))try{this.meta[i]._emit(Xt)}catch{}let{finalMessages:s,equalsError:a}=this._updateState(n);if(s.length>0&&this._config.inspectorEnabled){let i=this._config.globalInspector;if(i!=null)try{i({kind:"emit",node:this,messages:s})}catch{}}if(s.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let i=this._config.tierOf,d=[];for(let u of s)i(u[0])===3?this._pauseBuffer.push(u):d.push(u);d.length>0&&this._dispatchOrAccumulate(d)}else this._dispatchOrAccumulate(s);a!=null&&this._emit([[P,a]])}_updateState(e){let n=this._config.tierOf,r,o,s=-1,a=0;for(let c of e)n(c[0])===3&&a++;let i=a<=1,d=-1;if(this._versioning!=null&&a>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===D){d=c;break}}for(let c=0;c<e.length;c++){let l=e[c],p=l[0];if(p===D){if(l.length>=2){let f=!1;if(i&&this._cached!==void 0)try{f=this._equals(this._cached,l[1])}catch(m){o=this._wrapFnError("equals threw",m),s=c;break}if(f){r==null&&(r=e.slice(0,c)),r.push(Jt),this._status="resolved";continue}this._cached=l[1],this._versioning!=null&&(d<0||c===d)&&yo(this._versioning,l[1],this._hashFn)}this._status="settled",r?.push(l)}else if(r?.push(l),p===X)this._status="dirty";else if(p===U)this._status="resolved";else if(p===$){this._status="completed";{let f=this._config.rigorRecorder;if(f!=null)try{f.onTerminalTransition(this,"completed",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===P){this._status="errored";{let f=this._config.rigorRecorder;if(f!=null)try{f.onTerminalTransition(this,"errored",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===Ce){if(this._cached!==void 0){let m=this._config.rigorRecorder;if(m!=null)try{m.onNonVacuousInvalidate(this,this._cached)}catch{}}this._cached=void 0,this._status="dirty";let f=this._cleanup;if(typeof f=="function"){this._cleanup=void 0;try{f()}catch{}}else if(f!=null&&typeof f=="object"){let m=f.invalidate;if(typeof m=="function")try{m()}catch{}}}else p===fe&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let u=s>=0?r??e.slice(0,s):r??e;return o!=null?{finalMessages:u,equalsError:o}:{finalMessages:u}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let n=[...this._sinks];for(let r of n)r(e)};_dispatchOrAccumulate(e){if(uo()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],ft(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}Ht(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let n=this._frameBatch(e);Ht(this._deliverToSinks,n,this._config.tierOf)}},ko=t=>Array.isArray(t),Qn=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function F(t,e){return te([],{...e,initial:t})}function se(t,e){return te((r,o,s)=>t(o,s)??void 0,{describeKind:"producer",...e})}function A(t,e,n){return te(t,(o,s,a)=>{let i=o.map((d,u)=>d!=null&&d.length>0?d.at(-1):a.prevData[u]);s.emit(e(i,a))},{describeKind:"derived",...n})}function Ne(t,e,n){return te(t,(o,s,a)=>{let i=o.map((d,u)=>d!=null&&d.length>0?d.at(-1):a.prevData[u]);return e(i,s,a)??void 0},{describeKind:"effect",...n})}var Q=ne(()=>{"use strict";we()});var Mo={};jn(Mo,{NS_PER_MS:()=>qe,NS_PER_SEC:()=>ht,constant:()=>xo,decorrelatedJitter:()=>_o,exponential:()=>So,fibonacci:()=>No,linear:()=>Ro,resolveBackoffPreset:()=>Zn,withMaxAttempts:()=>Oi});function nt(t){return t<0?0:t}function _i(t,e){return e==="none"?t:e==="full"?Math.random()*t:t/2+Math.random()*(t/2)}function Mi(t,e){return t+Math.random()*(e-t)}function xo(t){let e=nt(t);return()=>e}function Ro(t,e){let n=nt(t),r=e===void 0?n:nt(e);return o=>n+r*Math.max(0,o)}function So(t){let e=nt(t?.baseNs??1e8),n=t?.factor!==void 0&&t.factor<1?1:t?.factor??2,r=nt(t?.maxDelayNs??30*1e9),o=t?.jitter??"none";return s=>{let a;if(e===0)a=0;else if(n===1)a=e;else{let i=r/e,d=1;for(let u=0;u<Math.max(0,s);u++){if(d>=i){d=i;break}d*=n}a=e*d,a>r&&(a=r)}return _i(a,o)}}function No(t=100*1e6,e=30*1e9){let n=nt(t),r=nt(e);function o(s){if(s<=0)return 1;let a=1,i=2;for(let d=1;d<s;d++){let u=a+i;a=i,i=u}return i}return s=>{let a=o(s)*n;return a<=r?a:r}}function _o(t=100*1e6,e=30*1e9){return(n,r,o)=>{let a=Math.min(e,(o??t)*3);return Mi(t,a)}}function Oi(t,e){return(n,r,o)=>n>=e?null:t(n,r,o)}function Zn(t){if(t==="constant")return xo(1*1e9);if(t==="linear")return Ro(1*1e9);if(t==="exponential")return So();if(t==="fibonacci")return No();if(t==="decorrelatedJitter")return _o();throw new Error(`Unknown backoff preset: "${String(t)}". Use one of: constant, linear, exponential, fibonacci, decorrelatedJitter`)}var qe,ht,er=ne(()=>{"use strict";qe=1e6,ht=1e9});function nr(t,e){if(e!=null&&e.length>0)return new Set(e);switch(t){case"standard":return new Set(["type","status","value","deps","meta","v"]);case"full":return null;case"spec":return new Set(["type","deps","meta","value"]);default:return new Set(["type","deps"])}}function Ei(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function We(t){let e=new WeakSet,n={};for(let[r,o]of Oo(t))n[r]=tr(o,e);return n}function tr(t,e){if(t==null)return t;let n=typeof t;if(n==="boolean"||n==="number"||n==="string")return t;if(n==="function")return"<function>";if(Array.isArray(t))return e.has(t)?"<cycle>":(e.add(t),t.map(r=>tr(r,e)));if(n==="object"){let r=t;if(e.has(r))return"<cycle>";e.add(r);try{if(typeof r.subscribe=="function"&&"cache"in r)return"<Node>"}catch{return"<unserializable>"}let o={};for(let[s,a]of Oo(r))o[s]=tr(a,e);return o}return"<unserializable>"}function Oo(t){let e=[],n;try{n=Object.keys(t)}catch{return e}for(let r of n)try{e.push([r,t[r]])}catch{e.push([r,"<unserializable>"])}return e}function le(t,e){let n={factory:t};return e!==void 0&&(n.factoryArgs=e),n}function Ai(t){let e={};for(let[n,r]of Object.entries(t.meta))try{e[n]=r.cache}catch{}return e}function rr(t,e,n){let r=e==null,o=!r&&e!=null?[...e].filter(c=>c.startsWith("meta.")).map(c=>c.slice(5)):null,s=r||e.has("meta")||o!=null&&o.length>0,a="state",i=[];t instanceof me&&(a=Ei(t),i=t._deps.map(c=>c.node.name??""));let d={type:a,deps:i};(r||e.has("status"))&&(d.status=t.status);let u=t instanceof me?t._guard:void 0;if(s){let c={...Ai(t)};if(u!=null&&c.access===void 0&&(c.access=qn(u)),o!=null&&o.length>0&&!e.has("meta")){let l={};for(let p of o)p in c&&(l[p]=c[p]);d.meta=l}else d.meta=c}if(t.name!=null&&(d.name=t.name),(r||e.has("value"))&&(!n||a==="state")){t.status==="sentinel"&&(d.sentinel=!0);try{d.value=t.cache}catch{}}if((r||e.has("v"))&&t.v!=null){let c={id:t.v.id,version:t.v.version};"cid"in t.v&&(c.cid=t.v.cid,c.prev=t.v.prev),d.v=c}return(r||e.has("guard"))&&u!=null&&(d.guard=qn(u)),(r||e.has("lastMutation"))&&t.lastMutation!=null&&(d.lastMutation=t.lastMutation),d}var Oe=ne(()=>{"use strict";mt();we()});function ue(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}var He=ne(()=>{"use strict"});function Et(t,e,n){if(e.length===0)throw new RangeError("budgetGate requires at least one constraint");let r=e.map(f=>f.node),o=[t,...r],s=new or,a=!1,i=!1,d=Symbol("budget-gate"),u=new Array(e.length);function c(){return e.every((f,m)=>f.check(u[m]))}function l(f){for(;s.size>0&&c();){let m=s.shift();f.emit(m)}s.size===0&&i&&(i=!1,f.down([[U]]))}return te([],(f,m)=>{for(let g=0;g<e.length;g++)u[g]=e[g].node.cache;let h=[];for(let g=0;g<o.length;g++){let b=o[g];h.push(b.subscribe(T=>{for(let y of T)p(y,g,m)}))}return()=>{for(let g of h)g()}},{...n,describeKind:"derived",meta:ue("resilience","budget_gate",n?.meta)});function p(f,m,h){let g=f[0];if(m===0){if(g===D)return c()&&s.size===0?h.emit(f[1]):(s.push(f[1]),a||(a=!0,h.up([[Se,d]]))),!0;if(g===X)return h.down([[X]]),!0;if(g===U)return s.size===0?h.down([[U]]):i=!0,!0;if(g===$||g===P){for(;s.size>0;)h.emit(s.shift());return i=!1,a&&(a=!1,h.up([[Le,d]])),h.down([f]),!0}return!1}if(g===D&&(u[m-1]=f[1]),g===D||g===U){let b=c();return b&&s.size>0?(l(h),s.size===0&&a&&(a=!1,h.up([[Le,d]]))):!b&&!a&&s.size>0&&(a=!0,h.up([[Se,d]])),!0}return g===X?!0:g===P?(h.down([f]),!0):g===$}}var or,Eo=ne(()=>{"use strict";de();we();He();or=class{buf=[];head=0;get size(){return this.buf.length-this.head}push(e){this.buf.push(e)}shift(){if(this.head>=this.buf.length)return;let e=this.buf[this.head];return this.buf[this.head]=void 0,this.head++,this.head>32&&this.head*2>this.buf.length&&(this.buf=this.buf.slice(this.head),this.head=0),e}clear(){this.buf=[],this.head=0}}});function Ao(t){let e=new WeakSet,n=new WeakSet,r=[t],o=0;for(;r.length>0;){let s=r.pop();o+=Li(s,e,n,r)}return o}function Li(t,e,n,r){if(t==null)return 0;switch(typeof t){case"number":return be.number;case"boolean":return be.boolean;case"string":return be.string+t.length*2;case"bigint":return be.bigint+Di(t);case"symbol":return be.symbol;case"function":return e.has(t)?0:(e.add(t),be.function);case"undefined":return 0}let s=t;if(e.has(s))return 0;e.add(s);let a=s[Ci];if(typeof a=="function")try{let u=a.call(s);if(typeof u=="number"&&Number.isFinite(u))return u}catch{}if(s instanceof Date)return be.date;if(s instanceof RegExp)return be.regexp+s.source.length*2;if(s instanceof Error){let u=s.message?s.message.length*2:0,c=s.stack?s.stack.length*2:0;return be.error+u+c}if(typeof URL<"u"&&s instanceof URL)return be.url+s.href.length*2;if(typeof Promise<"u"&&s instanceof Promise)return be.promise;if(s instanceof WeakMap)return be.weakmap;if(s instanceof WeakSet)return be.weakset;if(s instanceof Map){let u=be.map;for(let[c,l]of s)u+=be.mapEntry,r.push(c),r.push(l);return u}if(s instanceof Set){let u=be.set;for(let c of s)u+=be.setEntry,r.push(c);return u}if(Array.isArray(s)){let u=be.array+s.length*8;for(let c of s)r.push(c);return u}if(s instanceof ArrayBuffer)return n.has(s)?0:(n.add(s),s.byteLength);if(ArrayBuffer.isView(s)){let u=s;return n.has(u.buffer)?48:(n.add(u.buffer),u.buffer.byteLength+48)}let i=be.object,d=Object.keys(s);for(let u of d){i+=be.string+u.length*2;try{r.push(s[u])}catch{}}return i}function Di(t){let e=t<0n?-t:t;if(e===0n)return 0;let n=e.toString(2).length;return Math.ceil(n/32)*8}var be,Ci,Co=ne(()=>{"use strict";be={object:56,array:64,string:40,number:8,boolean:4,null:0,undefined:0,symbol:40,bigint:16,function:120,map:72,set:72,mapEntry:40,setEntry:24,date:24,regexp:48,error:64,url:80,promise:48,weakmap:40,weakset:40},Ci=Symbol.for("sizeof")});function Lo(t,e,n,r={}){let o=e in t.nodes,s=n in t.nodes;if(!o)return tn(e,n,"no-such-from");if(!s)return tn(e,n,"no-such-to");let a=r.maxDepth;if(a!=null&&(!Number.isInteger(a)||a<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===n){if(r.findCycle===!0){let u=Ii(t,e,r);if(u!=null)return u}let d=nn(e,t.nodes[e],0,r);return rn(e,n,[d])}if(a===0)return tn(e,n,"no-path");let i=Do(t,e,n,a);return i.found?rn(e,n,Io(t,i.pathOrder,r)):tn(e,n,i.truncated?"max-depth-exceeded":"no-path")}function Do(t,e,n,r){let o=new Map,s=[{path:n,depth:0}],a=new Set([n]),i=0,d=!1;for(;i<s.length;){let l=s[i++];if(l.path===e)break;if(r!=null&&l.depth>=r){let h=t.nodes[l.path];h?.deps&&h.deps.length>0&&(d=!0);continue}let p=t.nodes[l.path];if(p==null)continue;let f=p.deps??[],m=new Map;for(let h=0;h<f.length;h++){let g=f[h];if(!g)continue;let b=m.get(g);b==null&&(b=[],m.set(g,b)),b.push(h)}for(let[h,g]of m)a.has(h)||(a.add(h),o.set(h,{from:l.path,depIndices:g}),s.push({path:h,depth:l.depth+1}))}if(!o.has(e))return{found:!1,pathOrder:[],truncated:d};let u=[{path:e}],c=e;for(;c!==n;){let l=o.get(c);if(l==null)return{found:!1,pathOrder:[],truncated:!1};u[u.length-1].depIndices=l.depIndices,u.push({path:l.from}),c=l.from}return{found:!0,pathOrder:u,truncated:!1}}function Ii(t,e,n){let r=t.nodes[e];if(r==null)return null;let o=r.deps??[],s=[];for(let i=0;i<o.length;i++)o[i]===e&&s.push(i);if(s.length>0){let i=nn(e,r,0,n);i.dep_index=s[0];let d=nn(e,r,1,n);return rn(e,e,[i,d])}let a=null;for(let i=0;i<o.length;i++){let d=o[i];if(!d||d===e)continue;let u=Do(t,d,e,n.maxDepth);u.found&&(a==null||u.pathOrder.length<a.pathOrder.length)&&(a=u,a={found:!0,pathOrder:[{path:e,depIndices:[i]},...u.pathOrder],truncated:!1})}return a==null?null:rn(e,e,Io(t,a.pathOrder,n))}function Io(t,e,n){return e.map((r,o)=>{let s=t.nodes[r.path],a=nn(r.path,s,o,n);return r.depIndices!=null&&r.depIndices.length>0&&(a.dep_index=r.depIndices[0],r.depIndices.length>1&&(a.dep_indices=[...r.depIndices])),a})}function nn(t,e,n,r){let o={path:t,type:e.type,hop:n};e.status!==void 0&&(o.status=e.status),"value"in e&&(o.value=e.value),e.v!=null&&(o.v=e.v);let s=r.annotations?.get(t)??e.annotation;s!=null&&(o.annotation=s);let a=r.lastMutations?.get(t)??e.lastMutation;return a!=null&&(o.lastMutation=a),o}function rn(t,e,n){return Po(t,e,!0,"ok",n)}function tn(t,e,n){return Po(t,e,!1,n,[])}function Po(t,e,n,r,o){let s=Pi(t,e,n,r,o);return{from:t,to:e,found:n,reason:r,steps:o,text:s,toJSON(){return{from:t,to:e,found:n,reason:r,steps:o}}}}function Pi(t,e,n,r,o){if(!n)switch(r){case"no-such-from":return`explainPath: no node named "${t}"`;case"no-such-to":return`explainPath: no node named "${e}"`;case"max-depth-exceeded":return`explainPath: no path from "${t}" to "${e}" within maxDepth`;default:return`explainPath: no path from "${t}" to "${e}"`}let s=[`Causal path: ${t} \u2192 ${e} (${o.length} step(s))`];for(let a of o){let d=` ${a.hop===0?"\xB7":"\u2193"} ${a.path} (${a.type}${a.status?`/${a.status}`:""})`;if(s.push(d),"value"in a&&s.push(` value: ${Gi(a.value)}`),a.annotation!=null&&s.push(` annotation: ${a.annotation}`),a.lastMutation!=null){let u=a.lastMutation.actor;s.push(` actor: ${u.type}${u.id?`:${u.id}`:""}`)}}return s.join(`
2
- `)}function Gi(t){if(t===void 0)return"<sentinel>";if(t===null)return"null";if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return e.length>80?`${e.slice(0,77)}...`:e}catch{return String(t)}}var Go=ne(()=>{"use strict"});function sr(t,e){if(Object.is(t,e))return!0;if(t==null||e==null||typeof t!="object"||typeof e!="object")return!1;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(let s=0;s<t.length;s++)if(!sr(t[s],e[s]))return!1;return!0}if(Array.isArray(e))return!1;let n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;let o=new Set(r);for(let s of n)if(!o.has(s)||!sr(t[s],e[s]))return!1;return!0}function Fo(t,e){return`${t}\0${e}`}function ir(t,e){let n=[],r=new Set(t.subgraphs),o=new Set(e.subgraphs),s=[];for(let g of o)r.has(g)||s.push(g);s.sort();for(let g of s)n.push({type:"subgraph-mounted",path:g});let a=new Set(Object.keys(t.nodes)),i=new Set(Object.keys(e.nodes)),d=[];for(let g of i)a.has(g)||d.push(g);d.sort();for(let g of d)n.push({type:"node-added",path:g,node:{...e.nodes[g]}});let u=[];for(let g of i){if(!a.has(g))continue;let b=t.nodes[g]?.meta,T=e.nodes[g]?.meta;b==null&&T==null||sr(b??{},T??{})||u.push(g)}u.sort();for(let g of u)n.push({type:"node-meta-changed",path:g,prevMeta:t.nodes[g]?.meta??{},nextMeta:e.nodes[g]?.meta??{}});let c=new Map;for(let g of t.edges)c.set(Fo(g.from,g.to),g);let l=new Map;for(let g of e.edges)l.set(Fo(g.from,g.to),g);let p=[];for(let[g,b]of l)c.has(g)||p.push(b);p.sort((g,b)=>g.from<b.from?-1:g.from>b.from?1:g.to<b.to?-1:g.to>b.to?1:0);for(let g of p)n.push({type:"edge-added",from:g.from,to:g.to});let f=[];for(let[g,b]of c)l.has(g)||f.push(b);f.sort((g,b)=>g.from<b.from?-1:g.from>b.from?1:g.to<b.to?-1:g.to>b.to?1:0);for(let g of f)n.push({type:"edge-removed",from:g.from,to:g.to});let m=[];for(let g of a)i.has(g)||m.push(g);m.sort();for(let g of m)n.push({type:"node-removed",path:g});let h=[];for(let g of r)o.has(g)||h.push(g);h.sort();for(let g of h)n.push({type:"subgraph-unmounted",path:g});return{events:n,flushedAt_ns:z()}}var $o=ne(()=>{"use strict";ye()});var ge,Ve=ne(()=>{"use strict";ge=class{_timer;_gen=0;start(e,n){this.cancel(),this._gen+=1;let r=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,r===this._gen&&n()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var rt,ar=ne(()=>{"use strict";rt=class{constructor(e){this.capacity=e;if(!Number.isInteger(e)||e<=0)throw new Error(`RingBuffer capacity must be a positive integer (got ${e})`);this.buf=new Array(e)}buf;head=0;_size=0;get size(){return this._size}get maxSize(){return this.capacity}push(e){let n=(this.head+this._size)%this.capacity;this.buf[n]=e,this._size<this.capacity?this._size++:this.head=(this.head+1)%this.capacity}shift(){if(this._size===0)return;let e=this.buf[this.head];return this.buf[this.head]=void 0,this.head=(this.head+1)%this.capacity,this._size--,e}at(e){if(this._size===0)return;let n=e<0?this._size+e:e;if(!(n<0||n>=this._size))return this.buf[(this.head+n)%this.capacity]}toArray(){let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this.buf[(this.head+n)%this.capacity];return e}clear(){for(let e=0;e<this._size;e++)this.buf[(this.head+e)%this.capacity]=void 0;this.head=0,this._size=0}}});function jo(t,e){let n=e?.topN??10,r=t.describe({detail:"standard"}),o=[],s=t._collectObserveTargets;typeof s=="function"&&s.call(t,"",o);let a=new Map;for(let[p,f]of o)a.set(p,f);let i=[];for(let[p,f]of Object.entries(r.nodes)){let m=a.get(p),h=m instanceof me?m:null,g=h?Ao(h.cache):0,b=h?h._sinkCount:0,T=f.deps?.length??0,y=f.type==="effect"&&b===0,v=b===0?f.type==="effect"?"orphan-effect":f.type==="derived"?"idle-derived":f.type==="producer"?"idle-producer":null:null;i.push({path:p,type:f.type,status:f.status??"unknown",valueSizeBytes:g,subscriberCount:b,depCount:T,isOrphanEffect:y,orphanKind:v})}let d=i.reduce((p,f)=>p+f.valueSizeBytes,0),u=(p,f)=>[...i].sort(f??((m,h)=>h[p]-m[p])).slice(0,n),c=i.filter(p=>p.orphanKind!=null),l=i.filter(p=>p.isOrphanEffect);return{nodeCount:i.length,edgeCount:r.edges.length,subgraphCount:r.subgraphs.length,nodes:i,totalValueSizeBytes:d,hotspots:{byValueSize:u("valueSizeBytes"),bySubscriberCount:u("subscriberCount"),byDepCount:u("depCount")},orphans:c,orphanEffects:l}}var Bo=ne(()=>{"use strict";we();Co()});function Vo(t,e){let n=Math.max(16,t.size*4),r=0;for(;t.size>0;){if(r++>=n){console.error(`[Graph "${e}".destroy] disposer drain exceeded cap (${n}); ${t.size} disposer(s) discarded`),t.clear();return}let o=t.values().next();if(o.done)return;let s=o.value;t.delete(s);try{s()}catch(a){console.error(`[Graph "${e}".destroy] disposer threw:`,a)}}}function Wo(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"&&typeof t.down=="function"}function Fi(t){if(t!=null)return Wo(t)?t.cache:t}function st(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"&&typeof t.down=="function"}function Je(t){return st(t)?t.cache??"":t}function Ko(t){return st(t)?t.cache??0:t}function zo(t){return st(t)?t.cache??!1:t}function $i(t){let e=[];for(let n of Object.keys(t).sort()){let r=t[n].v;r!=null&&e.push(`${n} ${r.id} ${r.version}`)}return e.join(`
3
- `)}function Uo(t){if(t.version!==ot)throw new Error(`unsupported snapshot version ${String(t.version)} (expected ${ot})`);for(let e of["name","nodes","edges","subgraphs"])if(!(e in t))throw new Error(`snapshot missing required key "${e}"`);if(typeof t.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof t.nodes!="object"||t.nodes===null||Array.isArray(t.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(t.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(t.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function ji(t,e){let n=new WeakMap,r=(o,s)=>{if(Object.is(o,s))return!0;if(o==null||s==null||typeof o!="object"||typeof s!="object")return!1;let a=n.get(o);if(a==null&&(a=new WeakSet,n.set(o,a)),a.has(s))return!0;a.add(s);let i=o.constructor,d=s.constructor;if(i!==d)return!1;if(o instanceof Date)return o.getTime()===s.getTime();if(o instanceof RegExp)return o.source===s.source&&o.flags===s.flags;if(Array.isArray(o)){let p=s;if(o.length!==p.length)return!1;for(let f=0;f<o.length;f++)if(!r(o[f],p[f]))return!1;return!0}if(o instanceof Map){let p=s;if(o.size!==p.size)return!1;for(let[f,m]of o)if(!p.has(f)||!r(m,p.get(f)))return!1;return!0}if(o instanceof Set){let p=s;if(o.size!==p.size)return!1;for(let f of o){let m=!1;for(let h of p)if(r(f,h)){m=!0;break}if(!m)return!1}return!0}if(ArrayBuffer.isView(o)){let p=o,f=s;if(p.length!==f.length)return!1;for(let m=0;m<p.length;m++)if(p[m]!==f[m])return!1;return!0}let u=Object.keys(o),c=Object.keys(s);if(u.length!==c.length)return!1;let l=new Set(c);for(let p of u)if(!l.has(p)||!r(o[p],s[p]))return!1;return!0};return r(t,e)}function Bi(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function on(t){let e="^";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="*"){e+=".*";continue}if(r==="?"){e+=".";continue}if(r==="["){let o=t.indexOf("]",n+1);if(o<=n+1){e+="\\[";continue}let s=t.slice(n+1,o);s.startsWith("!")&&(s=`^${s.slice(1)}`),s=s.replace(/\\/g,"\\\\"),e+=`[${s}]`,n=o;continue}e+=Bi(r)}return e+="$",new RegExp(e)}function dr(t){if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||t==null)return String(t);try{return JSON.stringify(t)}catch{return"[unserializable]"}}function zi(t){return t==="none"?Ki:t==="ansi"||t==null?Vi:{data:t.data??"",dirty:t.dirty??"",resolved:t.resolved??"",invalidate:t.invalidate??"",pause:t.pause??"",resume:t.resume??"",complete:t.complete??"",error:t.error??"",teardown:t.teardown??"",derived:t.derived??"",path:t.path??"",reset:t.reset??""}}function qo(t){if(t==null)return{};let e=t.detail;return e==="full"?{...t,structured:t.structured??!0,timeline:t.timeline??!0,causal:t.causal??!0,derived:t.derived??!0}:e==="minimal"?{...t,structured:t.structured??!0}:t.format==="stage-log"?{...t,structured:t.structured??!0,timeline:t.timeline??!0}:t}function Ui(t,e,n){for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);if(o<32||o===127)throw new Error(`Graph "${e}": ${n} "${t}" must not contain control character (U+${o.toString(16).padStart(4,"0").toUpperCase()} at index ${r})`)}}function ur(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(pe))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${pe}' (path separator)`);if(t===Ee)throw new Error(`Graph "${e}": ${n} name "${Ee}" is reserved for meta companion paths`);Ui(t,e,n)}function qi(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(pe);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function Wi(t,e){let n=!1;for(let o of t)if(!e.isMetaPassthrough(o[0])){n=!0;break}return n?t.filter(o=>e.isMetaPassthrough(o[0])):t}function Ho(t){for(let e of t._mounts.values())Ho(e);for(let e of t._nodes.values())try{e.down([[fe]],{internal:!0})}catch{}}function Jo(t,e){let n=ie.diff(t,e),r={};for(let o of n.nodesAdded){let s=e.nodes[o];s!=null&&(r[o]=s)}return{...n,nodesAddedFull:r}}function cr(t,e,n,r={}){let o={paths:[],depths:new Map,truncated:!1};if(!e)return r.withDetail?o:[];if(!r.both&&n!=="upstream"&&n!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let s=r.maxDepth;if(s!=null&&(!Number.isInteger(s)||s<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(s===0)return r.withDetail?o:[];let a=new Map,i=new Map,d=new Map,u=new Map,c=new Set;for(let[y,v]of Object.entries(t.nodes)){if(!y)continue;c.add(y);let k=v.deps??[];a.set(y,k);for(let N of k)N&&(c.add(N),i.has(N)||i.set(N,new Set),i.get(N).add(y))}for(let y of t.edges){if(y==null||typeof y!="object")continue;let v=typeof y.from=="string"?y.from:"",k=typeof y.to=="string"?y.to:"";!v||!k||(c.add(v),c.add(k),u.has(v)||u.set(v,new Set),u.get(v).add(k),d.has(k)||d.set(k,new Set),d.get(k).add(v))}if(!c.has(e))return r.withDetail?o:[];let l=r.both===!0,p=y=>{if(l){let w=a.get(y)??[],R=d.get(y),x=i.get(y),_=u.get(y),M=[...w];return R&&M.push(...R),x&&M.push(...x),_&&M.push(..._),M}if(n==="upstream"){let w=a.get(y)??[],R=d.get(y);return R?[...w,...R]:w}let v=i.get(y),k=u.get(y),N=v?[...v]:[];return k&&N.push(...k),N},f=new Set([e]),m=new Map,h=[{path:e,depth:0}],g=0,b=!1;for(;g<h.length;){let y=h[g++];if(s!=null&&y.depth>=s){p(y.path).length>0&&(b=!0);continue}for(let v of p(y.path))!v||f.has(v)||(f.add(v),m.set(v,y.depth+1),h.push({path:v,depth:y.depth+1}))}let T=[...m.keys()].sort((y,v)=>y<v?-1:y>v?1:0);return r.withDetail?{paths:T,depths:m,truncated:b}:T}function Hi(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.path!==o.path||r.type!==o.type||r.status!==o.status||r.hop!==o.hop||r.dep_index!==o.dep_index||r.annotation!==o.annotation||r.value!==o.value||r.lastMutation!==o.lastMutation)return!1;let s=r.v,a=o.v;if(s!==a&&(s==null||a==null||s.id!==a.id||s.version!==a.version))return!1}return!0}var pe,Ee,ot,Vi,Ki,ie,Ke=ne(()=>{"use strict";qt();Me();ye();mt();de();Oe();we();Q();$o();Z();Ve();ar();Vn();Go();Bo();pe="::",Ee="__meta__",ot=1;Vi={data:"\x1B[32m",dirty:"\x1B[33m",resolved:"\x1B[36m",invalidate:"\x1B[93m",pause:"\x1B[90m",resume:"\x1B[96m",complete:"\x1B[34m",error:"\x1B[31m",teardown:"\x1B[91m",derived:"\x1B[35m",path:"\x1B[90m",reset:"\x1B[0m"},Ki={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};ie=class t{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_destroyed=!1;_topology;_topologyEmitters=new Set;_factory;_factoryArgs;constructor(e,n){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(pe))throw new Error(`Graph name must not contain '${pe}' (got "${e}")`);if(e===Ee)throw new Error(`Graph name "${Ee}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??gt,this._traceRing=new rt(n?.traceCapacity??1e3),n?.versioning!=null&&this.setVersioning(n.versioning),typeof n?.factory=="string"&&(this._factory=n.factory,n.factoryArgs!==void 0&&(this._factoryArgs=n.factoryArgs))}tagFactory(e,n){return this._factory=e,this._factoryArgs=n,this}ancestors(e=!0){let n=[],r=e?this:this._parent;for(;r!=null;)n.push(r),r=r._parent;return n}get topology(){return this._topology==null&&(this._topology=se(e=>{let n=r=>{e.emit(r)};return this._topologyEmitters.add(n),()=>{this._topologyEmitters.delete(n)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let n of this._topologyEmitters)n(e)}nameOf(e){return this._nodeToName.get(e)}add(e,n){let r=e.name,o=n?.name??r;if(o==null||o==="")throw new Error(`Graph "${this.name}": graph.add requires a non-empty name \u2014 pass via opts.name or set it on the node (e.g. state(0, { name: "x" }))`);let s=o,a=n?.annotation;if(ur(s,this.name,"add"),this._mounts.has(s))throw new Error(`Graph "${this.name}": name "${s}" is already a mount point`);if(this._nodes.has(s))throw new Error(`Graph "${this.name}": node "${s}" already exists`);let i=this._nodeToName.get(e);if(i!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${i}"`);return this._nodes.set(s,e),this._nodeToName.set(e,s),this._emitTopology({kind:"added",name:s,nodeKind:"node"}),a!=null&&(this._annotations.set(s,a),this.config.inspectorEnabled&&this._traceRing.push({path:s,annotation:a,timestamp_ns:z()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof me&&n._applyVersioning(e)}remove(e){ur(e,this.name,"remove");let n=this._mounts.get(e);if(n){let s={kind:"mount",nodes:[],mounts:[]},a=[];n._collectObserveTargets("",a);for(let[i,d]of a)i.includes(`${pe}${Ee}${pe}`)||s.nodes.push(i);return s.nodes.sort(),s.mounts.push(e),s.mounts.push(...n._collectSubgraphs(`${e}${pe}`)),this._mounts.delete(e),n._parent=void 0,Ho(n),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:s}),s}let r=this._nodes.get(e);if(!r)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(r),r.down([[fe]],{internal:!0});let o={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:o}),o}removeAll(e){let n=typeof e=="function"?e:(()=>{let s=on(e);return a=>s.test(a)})(),r={kind:"mount",nodes:[],mounts:[]},o=[...this._nodes.keys(),...this._mounts.keys()].filter(s=>n(s));for(let s of o){let a=this.remove(s);r.nodes.push(...a.nodes),r.mounts.push(...a.mounts)}return r.nodes.sort(),r.mounts.sort(),r}[Symbol.iterator](){let e=[...this._nodes.keys()].sort(),n=this._nodes,r=0;return{[Symbol.iterator](){return this},next(){if(r>=e.length)return{value:void 0,done:!0};let o=e[r++];return{value:[o,n.get(o)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(pe))return this.resolve(e);let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return n}get(e){return this.node(e).cache}set(e,n,r){let o=r?.internal===!0;this.node(e).down([[D,n]],{actor:r?.actor,internal:o,delivery:"write"})}setAll(e,n){let r=Symbol.iterator in e?e:Object.entries(e);re(()=>{for(let[o,s]of r)this.set(o,s,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[Ce]],{actor:n?.actor,internal:r,delivery:"write"})}error(e,n,r){let o=r?.internal===!0;this.node(e).down([[P,n]],{actor:r?.actor,internal:o,delivery:"write"})}complete(e,n){let r=n?.internal===!0;this.node(e).down([[$]],{actor:n?.actor,internal:r,delivery:"write"})}edges(e){let n=e?.recursive===!0,r=new Map;if(!n){for(let[d,u]of this._nodes)r.set(u,d);let i=[];for(let[d,u]of this._nodes)if(u instanceof me)for(let c of u._deps){let l=r.get(c.node);l!=null&&i.push([l,d])}return i.sort((d,u)=>d[0]<u[0]?-1:d[0]>u[0]?1:d[1]<u[1]?-1:d[1]>u[1]?1:0),i}let o=[];this._collectObserveTargets("",o);let s=new Map;for(let[i,d]of o)s.set(d,i);let a=[];for(let[i,d]of o)if(d instanceof me)for(let u of d._deps){let c=s.get(u.node);c!=null&&a.push([c,i])}return a.sort((i,d)=>i[0]<d[0]?-1:i[0]>d[0]?1:i[1]<d[1]?-1:i[1]>d[1]?1:0),a}mount(e,n){if(n===void 0){let o=new t(e);return this.mount(e,o)}if(typeof n=="function"){let o=new t(e);return n(o),this.mount(e,o)}let r=n;if(ur(e,this.name,"mount"),this._nodes.has(e))throw new Error(`Graph "${this.name}": cannot mount at "${e}" \u2014 node with that name exists`);if(this._mounts.has(e))throw new Error(`Graph "${this.name}": mount "${e}" already exists`);if(r===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(r._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${r._parent.name}"`);for(let o=this;o!=null;o=o._parent)if(o===r)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,r),r._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),r}resolve(e){let n=qi(e,this.name);return this._resolveFromSegments(n)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let n=e;if(n[0]===this.name&&(n=n.slice(1),n.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let r=n[0],o=n.slice(1);if(o.length===0){let i=this._nodes.get(r);if(i)return i;throw this._mounts.has(r)?new Error(`Graph "${this.name}": path ends at subgraph "${r}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${r}"`)}let s=this._nodes.get(r);if(s&&o.length>0&&o[0]===Ee)return this._resolveMetaChainFromNode(s,o,n.join(pe));let a=this._mounts.get(r);if(!a)throw this._nodes.has(r)?new Error(`Graph "${this.name}": "${r}" is a node; trailing path "${o.join(pe)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return a.resolve(o.join(pe))}_resolveMetaChainFromNode(e,n,r){let o=e,s=0,a=[...n];for(;s<a.length;){if(a[s]!==Ee)throw new Error(`Graph "${this.name}": expected ${Ee} segment in meta path "${r}"`);if(s+1>=a.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${Ee} in "${r}"`);let i=a[s+1],d=o.meta[i];if(!d)throw new Error(`Graph "${this.name}": unknown meta "${i}" in path "${r}"`);o=d,s+=2}return o}signal(e,n){if(n?.internal!==!0){for(let o of e)if(this.config.messageTier(o[0])===3)throw new Error(`Graph "${this.name}": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). For per-node value writes, use Graph.set or graph.node(name).down(...).`)}let r=[];if(this._signalDeliver(e,n??{},new Set,r),r.length>0)throw r[0]}_signalDeliver(e,n,r,o){for(let d of this._mounts.values())d._signalDeliver(e,n,r,o);let a=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},i=Wi(e,this.config);for(let d of[...this._nodes.keys()].sort()){let u=this._nodes.get(d);if(!r.has(u)){r.add(u);try{u.down(e,a)}catch(c){if(c instanceof De)throw c;o.push(c)}i.length!==0&&this._signalMetaSubtree(u,i,r,a,o)}}}_signalMetaSubtree(e,n,r,o,s){for(let a of Object.keys(e.meta).sort()){let i=e.meta[a];if(!r.has(i)){r.add(i);try{i.down(n,o)}catch(d){if(d instanceof De)throw d;s.push(d)}this._signalMetaSubtree(i,n,r,o,s)}}}describe(e){if(e?.reactive==="diff")return this._describeReactiveDiff(e);if(e?.reactive===!0)return this._describeReactive(e);let n=Fi(e?.actor),r=e?.filter;if(e?.detail!=null&&e?.fields!=null)throw new TypeError("Graph.describe(): pass either `detail` or `fields`, not both. `detail: 'spec'` is the canonical spec projection; use `fields` only when you need a custom subset.");let o=nr(e?.detail,e?.fields),s=e?.detail==="spec",a=o,i=[];this._collectObserveTargets("",i);let d=new Map;for(let[v,k]of i)d.set(k,v);let u=[];{let v=i.map(([,w])=>w),k=new Set(d.values()),N=0;for(;v.length>0;){let w=v.shift();if(w instanceof me)for(let R of w._deps){let x=R.node;if(d.has(x))continue;let _=x.name??"",M=_;if(!M||k.has(M))if(_){let L=2;for(;k.has(`${_}#${L}`);)L++;M=`${_}#${L}`}else for(M=`__internal__/${N++}`;k.has(M);)M=`__internal__/${N++}`;d.set(x,M),k.add(M),u.push([M,x]),v.push(x)}}}let c=[...i,...u],l={};for(let[v,k]of c){if(n!=null&&!k.allowsObserve(n))continue;let N=rr(k,a,s),w=k instanceof me?k._deps.map(M=>d.get(M.node)??M.node.name??""):[],{name:R,...x}=N,_={...x,deps:w};if(!s){let M=this._annotations.get(v);M!=null&&(_.annotation=M)}if(r!=null)if(typeof r=="function"){let M=r;if(!(M.length>=2?M(v,_):M(_)))continue}else{let M=!0;for(let[L,S]of Object.entries(r)){let O=L==="deps_includes"?"depsIncludes":L==="meta_has"?"metaHas":L;if(O==="depsIncludes"){if(!_.deps.includes(String(S))){M=!1;break}continue}if(O==="metaHas"){if(!Object.hasOwn(_.meta??{},String(S))){M=!1;break}continue}if(_[O]!==S){M=!1;break}}if(!M)continue}l[v]=_}let p=new Set(Object.keys(l)),f=[];for(let[v,k]of c)if(k instanceof me)for(let N of k._deps){let w=d.get(N.node);w!=null&&f.push([w,v])}f.sort((v,k)=>v[0]<k[0]?-1:v[0]>k[0]?1:v[1]<k[1]?-1:v[1]>k[1]?1:0);let m=f.map(([v,k])=>({from:v,to:k}));(n!=null||r!=null)&&(m=m.filter(v=>p.has(v.from)&&p.has(v.to)));let h=this._collectSubgraphs(""),g=n!=null||r!=null?h.filter(v=>{let k=`${v}${pe}`;return[...p].some(N=>N===v||N.startsWith(k))}):h,b=this,T=e;return{name:this.name,nodes:l,edges:m,subgraphs:g,...this._factory!==void 0?{factory:this._factory}:{},...this._factoryArgs!==void 0?{factoryArgs:this._factoryArgs}:{},expand(v){let k={...T};return Array.isArray(v)?(k.fields=v,k.detail=void 0):(k.detail=v,k.fields=void 0),b.describe(k)}}}_collectSubgraphs(e){let n=[];for(let r of[...this._mounts.keys()].sort()){let o=e===""?r:`${e}${r}`;n.push(o),n.push(...this._mounts.get(r)._collectSubgraphs(`${o}${pe}`))}return n}resourceProfile(e){return jo(this,e)}reachable(e,n,r={}){return r.withDetail===!0?cr(this.describe(),e,n,{...r,withDetail:!0}):cr(this.describe(),e,n,r)}explain(e,n,r){return r?.reactive===!0?this._explainReactive(e,n,r):this._explainStatic(Je(e),Je(n),{...r?.maxDepth!==void 0?{maxDepth:Ko(r.maxDepth)}:{},...r?.findCycle!==void 0?{findCycle:zo(r.findCycle)}:{}})}_explainStatic(e,n,r){let o=this.describe({detail:"full"}),s=new Map(this._annotations),a=new Map;for(let[i,d]of Object.entries(o.nodes))d.lastMutation!=null&&a.set(i,d.lastMutation);return Lo(o,e,n,{...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{},annotations:s,lastMutations:a})}_describeReactive(e){let n={...e,reactive:!1},r=e.reactiveName??"describe",o=0,s=F(o,{name:`${r}_version`}),a=this.observe({timeline:!0,structured:!0}),i=!1,d=!1,u=()=>{i||d||(i=!0,ft(()=>{i=!1,!d&&(o+=1,s.emit(o))}))},c=a.onEvent(T=>{let y=T.type;y!=="data"&&y!=="error"&&y!=="complete"&&y!=="teardown"||u()}),l=[],p=new WeakSet,f=T=>{if(p.has(T)||d)return;p.add(T);let y=T.topology.subscribe(v=>{for(let k of v){if(k[0]!==D)continue;let N=k[1];if(u(),N.kind==="added"&&N.nodeKind==="mount"){let w=T._mounts.get(N.name);w!=null&&f(w)}}});l.push(y);for(let v of T._mounts.keys()){let k=T._mounts.get(v);k!=null&&f(k)}};f(this);let m,h=e.actor;Wo(h)&&(m=h.subscribe(T=>{let y=!1,v=!1;for(let k of T){let N=k[0];N===D?y=!0:(N===$||N===P||N===fe)&&(v=!0)}y&&u(),v&&(m?.(),m=void 0,u())}));let g;try{g=A([s],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(T,y)=>T===y})}catch(T){c(),m?.();for(let y of l)y();throw a.dispose(),T}let b=Y(g);return{node:g,dispose(){d=!0,c(),m?.();for(let T of l)T();l.length=0,a.dispose(),b()}}}_describeReactiveDiff(e){let n={...e,reactive:!1},r=e.reactiveName??"describe-diff",o={name:this.name,nodes:{},edges:[],subgraphs:[]},s=this.describe(n),a=ir(o,s),i=F(a,{name:r,meta:{domain:"audit",kind:"describe-diff"},equals:(p,f)=>p===f}),d=this._describeReactive({...e,reactiveName:void 0}),u=!1,c=d.node.subscribe(p=>{if(!u)for(let f of p){if(f[0]!==D)continue;let m=f[1],h=ir(s,m);s=m,h.events.length!==0&&i.emit(h)}}),l=Y(i);return{node:i,dispose(){u=!0,c(),d.dispose(),i.down([[fe,"describe-diff disposed"]]),l()}}}_explainReactive(e,n,r){let o=0,s=F(o,{name:"explain_version"}),a=this.observe({timeline:!0,structured:!0}),i=!1,d=!1,u=()=>{i||d||(i=!0,ft(()=>{i=!1,!d&&(o+=1,s.emit(o))}))},c=a.onEvent(T=>{let y=T.type;y!=="data"&&y!=="error"&&y!=="complete"&&y!=="teardown"||u()}),l=[];e!=null&&st(e)&&l.push(e),n!=null&&st(n)&&l.push(n),r?.maxDepth!=null&&st(r.maxDepth)&&l.push(r.maxDepth),r?.findCycle!=null&&st(r.findCycle)&&l.push(r.findCycle);let p=()=>{for(let T of l)if(T.cache===void 0)return!1;return!0},f=()=>{let T=Je(e),y=Je(n);return{from:T,to:y,found:!1,reason:"pending",steps:[],text:"(awaiting reactive args)",toJSON:()=>({from:T,to:y,found:!1,reason:"pending",steps:[]})}},m;try{m=A([s],()=>{if(!p())return f();let T=Je(e),y=Je(n),v={...r?.maxDepth!==void 0?{maxDepth:Ko(r.maxDepth)}:{},...r?.findCycle!==void 0?{findCycle:zo(r.findCycle)}:{}};return this._explainStatic(T,y,v)},{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:Je(e),to:Je(n)},equals:(T,y)=>T.found===y.found&&T.reason===y.reason&&T.steps.length===y.steps.length&&Hi(T.steps,y.steps)})}catch(T){throw c(),a.dispose(),T}let h=Y(m),g=[],b=T=>{let y;return y=T.subscribe(v=>{let k=!1,N=!1;for(let w of v){let R=w[0];R===D?k=!0:(R===$||R===P||R===fe)&&(N=!0)}(k||N)&&u(),N&&y&&(y(),y=void 0)}),()=>{y&&(y(),y=void 0)}};for(let T of l)g.push(b(T));return{node:m,dispose(){d=!0,c();for(let T of g)T?.();g.length=0,a.dispose(),h()}}}_pathsMatching(e){let n=on(e),r=[];return this._collectObserveTargets("",r),r.map(([o])=>o).filter(o=>n.test(o))}_collectObserveTargets(e,n){for(let r of[...this._mounts.keys()].sort()){let o=e===""?r:`${e}${pe}${r}`;this._mounts.get(r)._collectObserveTargets(o,n)}for(let r of[...this._nodes.keys()].sort()){let o=this._nodes.get(r),s=e===""?r:`${e}${pe}${r}`;n.push([s,o]),this._appendMetaObserveTargets(s,o,n)}}_appendMetaObserveTargets(e,n,r){for(let o of Object.keys(n.meta).sort()){let s=n.meta[o],a=`${e}${pe}${Ee}${pe}${o}`;r.push([a,s]),this._appendMetaObserveTargets(a,s,r)}}observe(e,n){let r=typeof e=="string",s=qo(r?n:e);if(s.reactive===!0)return this._observeReactive(r?e:void 0,s);let a=s.structured===!0||s.timeline===!0||s.causal===!0||s.derived===!0||s.detail==="minimal"||s.detail==="full"||s.format!=null,i=s.actor;if(r){let c=e,l=this.resolve(c);if(i!=null&&!l.allowsObserve(i))throw new De({actor:i,action:"observe",nodeName:c});return a?this._buildStructuredObserver([[c,l]],s,"one"):{subscribe(p){return l.subscribe(p)},up(p){try{l.up?.(p)}catch(f){if(f instanceof De)return;throw f}}}}let d=[];this._collectObserveTargets("",d),d.sort((c,l)=>c[0]<l[0]?-1:c[0]>l[0]?1:0);let u=i==null?d:d.filter(([,c])=>c.allowsObserve(i));return a?this._buildStructuredObserver(u,s,"all"):{subscribe:c=>{let l=u.map(([p,f])=>f.subscribe(m=>{c(p,m)}));return()=>{for(let p of l)p()}},up:(c,l)=>{try{this.resolve(c).up?.(l)}catch(p){if(p instanceof De)return;throw p}}}}_observeReactive(e,n){let r=n.tiers,o=r!=null?new Set(r):null,s=n.reactiveName??"observe";return se(a=>{let i=[],d=!1,u=!1,c=()=>{if(i.length===0||u)return;let h={events:i.slice(),flushedAt_ns:z()};i.length=0,a.emit(h)},l={...n,reactive:!1,structured:!0,timeline:!0},p=e!=null?this.observe(e,l):this.observe(l),f=h=>{u||(i.push(h),!d&&(d=!0,ft(()=>{d=!1,c()})))};for(let h of p.events)f(h);let m=p.onEvent(f);return()=>{u=!0,m(),p.dispose()}},{name:s,meta:{domain:"audit",kind:"observe-reactive"}})}_buildStructuredObserver(e,n,r){let o=r==="one"?e[0]?.[0]:void 0,s=a=>{if(r==="one"&&o!=null){let c=this.resolve(o);return this._buildStructuredObserver([[o,c]],a,"one")}let i=[];this._collectObserveTargets("",i),i.sort((c,l)=>c[0]<l[0]?-1:c[0]>l[0]?1:0);let d=a.actor,u=d==null?i:i.filter(([,c])=>c.allowsObserve(d));return this._buildStructuredObserver(u,a,"all")};return this._createObserveResult(e,n,s)}_createObserveResult(e,n,r){let o=n.timeline===!0,s=n.causal===!0,a=n.derived===!0,i=n.detail==="minimal",d=this.config.inspectorEnabled,u=(s||a)&&d,c=n.maxEvents,l=c!=null&&c>0?new rt(c):null,p=[],f=new Set,m=n.tiers!=null?new Set(n.tiers):null,h={},g=new Set,b=0,T=0,y=0,v=0,k=0,N=0,w=!1,R=!1,x=0,_=new Map,M=new Map,L=new Map,S=B=>{if(!(m!=null&&!m.has(B.type))){l?l.push(B):p.push(B);for(let ee of f)ee(B)}},O=B=>m==null||m.has(B),I=()=>o?{timestamp_ns:z(),in_batch:Wt(),batch_id:x}:{},K=(B,ee)=>{if(!(!u||!(B instanceof me)))return B._setInspectorHook(xe=>{if(xe.kind==="dep_message")_.set(B,xe.depIndex);else if(xe.kind==="run"){let Xe=xe.batchData.map((oe,Re)=>oe!=null&&oe.length>0?oe.at(-1):xe.prevData[Re]);M.set(B,Xe);let Ae=xe.batchData.map(oe=>oe!=null?[...oe]:void 0);L.set(B,Ae),a&&S({type:"derived",path:ee,dep_values:Xe,dep_batches:Ae,...I()})}})},q=B=>{let ee=_.get(B),xe=M.get(B);if(!s||xe==null)return{};let Ae=(ee!=null&&ee>=0&&B instanceof me?B._deps[ee]:void 0)?.node,oe=Ae?.v,Re=L.get(B);return{trigger_dep_index:ee,trigger_dep_name:Ae?.name,...oe!=null?{trigger_version:{id:oe.id,version:oe.version}}:{},dep_values:[...xe],...Re!=null?{dep_batches:Re}:{}}},H=[],G=[];for(let[B,ee]of e){let xe=K(ee,B);xe&&H.push(xe),G.push(ee.subscribe(Xe=>{x++;for(let Ae of Xe){let oe=Ae[0],Re=I();if(oe===D){h[B]=Ae[1];let Fn=ee instanceof me?ee.lastMutation?.actor??ct:ct;S({type:"data",path:B,data:Ae[1],actor:Fn,...Re,...q(ee)})}else if(i)oe===X?O("dirty")&&b++:oe===U?O("resolved")&&T++:oe===Ce?O("invalidate")&&y++:oe===Se?O("pause")&&v++:oe===Le?O("resume")&&k++:oe===fe?O("teardown")&&N++:oe===$&&!g.has(B)?O("complete")&&(w=!0):oe===P&&O("error")&&(R=!0,g.add(B));else if(oe===X)O("dirty")&&b++,S({type:"dirty",path:B,...Re});else if(oe===U)O("resolved")&&T++,S({type:"resolved",path:B,...Re,...q(ee)});else if(oe===Ce)O("invalidate")&&y++,S({type:"invalidate",path:B,...Re});else if(oe===Se)O("pause")&&v++,S({type:"pause",path:B,lockId:Ae[1],...Re});else if(oe===Le)O("resume")&&k++,S({type:"resume",path:B,lockId:Ae[1],...Re});else if(oe===$)O("complete")&&!g.has(B)&&(w=!0),S({type:"complete",path:B,...Re});else if(oe===P){O("error")&&(R=!0,g.add(B));let Fn=ee instanceof me?ee.lastMutation?.actor??ct:ct;S({type:"error",path:B,data:Ae[1],actor:Fn,...Re})}else oe===fe&&(O("teardown")&&N++,S({type:"teardown",path:B,...Re}))}}))}let j=!1,E=()=>{if(!j){j=!0;for(let B of G)B();for(let B of H)B();for(let B of J)B({value:void 0,done:!0});J.length=0}},C=[],J=[];f.add(B=>{let ee=J.shift();ee?ee({value:B,done:!1}):C.push(B)});let he={get values(){return h},get dirtyCount(){return b},get resolvedCount(){return T},get invalidateCount(){return y},get pauseCount(){return v},get resumeCount(){return k},get teardownCount(){return N},get events(){return l?l.toArray():[...p]},get anyCompletedCleanly(){return w},get anyErrored(){return R},get completedWithoutErrors(){return w&&!R},onEvent(B){return f.add(B),()=>f.delete(B)},dispose:E,expand(B){E();let ee={...n};return typeof B=="string"?ee.detail=B:Object.assign(ee,B),r(qo(ee))},[Symbol.asyncIterator](){return{next(){return C.length>0?Promise.resolve({value:C.shift(),done:!1}):j?Promise.resolve({value:void 0,done:!0}):new Promise(B=>J.push(B))},return(){return E(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(he,n),he}_attachFormatLogger(e,n){let r=n.format;if(r==null)return;let o=n.logger??(m=>console.log(m)),s=n.includeTypes?new Set(n.includeTypes):null,a=n.excludeTypes?new Set(n.excludeTypes):null,i=s==null&&a==null?()=>!0:m=>(s==null||s.has(m))&&(a==null||!a.has(m)),d=zi(n.theme),u=r==="stage-log"?z():0,c=m=>m==null?"":n.stageLabels?.[m]??m,l=(m,h)=>m.length>h?`${m.slice(0,h-1)}\u2026`:m,p=m=>m.type==="data"||m.type==="error"?l(dr(m.data),120):"",f=m=>{if(r==="stage-log"){let w=(z()-u)/1e9,R=c(m.path).padEnd(9);if(m.type==="data"){let x=p(m);return`[${w.toFixed(3)}s] ${R} \u2190${x?` ${x}`:""}`}if(m.type==="error"){let x=p(m);return`[${w.toFixed(3)}s] ${R} \u2717${x?` ${x}`:""}`}return m.type==="complete"?`[${w.toFixed(3)}s] ${R} \u25A0 complete`:`[${w.toFixed(3)}s] ${R} ${m.type}`}if(r==="json")try{return JSON.stringify(m)}catch{return JSON.stringify({type:m.type,path:m.path,data:"[unserializable]"})}let h=d[m.type]??"",g=m.path?`${d.path}${m.path}${d.reset} `:"",b=m.type==="data"||m.type==="error",T=m.type==="pause"||m.type==="resume",y=b?` ${dr(m.data)}`:T?` ${dr(m.lockId)}`:"",v=m.type==="data"||m.type==="resolved"||m.type==="derived"?m:void 0,k=v?.trigger_dep_name!=null?` <- ${v.trigger_dep_name}`:v?.trigger_dep_index!=null?` <- #${v.trigger_dep_index}`:"",N=m.in_batch?" [batch]":"";return`${g}${h}${m.type.toUpperCase()}${d.reset}${y}${k}${N}`};e.onEvent(m=>{i(m.type)&&o(f(m),m)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){Vo(this._disposers,this.name),this.signal([[fe]],{internal:!0}),Vo(this._storageDisposers,this.name);for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}get destroyed(){return this._destroyed}_destroyClearOnly(){for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}snapshot(e){let{expand:n,...r}=this.describe({detail:"full"}),o={};for(let i of Object.keys(r.nodes).sort()){let{lastMutation:d,guard:u,...c}=r.nodes[i];o[i]=c}let s=[...r.subgraphs].sort(),a={...r,version:1,nodes:o,subgraphs:s};if(e?.format==null)return a;if(e.format==="json-string")return JSON.stringify(a);if(e.format==="bytes"){if(e.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let i=this.config.lookupCodec(e.codec);if(i==null)throw new Error(`snapshot: codec "${e.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return so(i,i.encode(a))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??gt,{codec:o,codecVersion:s,payload:a}=io(e,r);return o.decode(a,s)}restore(e,n){if(Uo(e),e.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${e.name}" does not match this graph`);let r=n?.only==null?null:(Array.isArray(n.only)?n.only:[n.only]).map(s=>on(s)),o=n?.includeProducers===!0;for(let s of Object.keys(e.nodes).sort()){if(r!==null&&!r.some(i=>i.test(s)))continue;let a=e.nodes[s];if(a!==void 0){if(!("value"in a)||a.value===void 0){"value"in a&&a.value===void 0&&n?.onError?.(s,new Error(`restore: slice.value is undefined for "${s}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(a.type==="derived"||a.type==="effect")&&!(a.type==="producer"&&!o)){if(a.v!=null){let d=this.tryResolve(s)?.v;if(d!=null&&d.id===a.v.id&&d.version===a.v.version)continue}try{this.set(s,a.value)}catch(i){n?.onError?.(s,i)}}}}}static fromSnapshot(e,n){Uo(e);let r=typeof n=="function"?n:n?.build,o=typeof n=="function"?void 0:n?.factories,s=new t(e.name);if(r)return r(s),s.restore(e),s;for(let f of[...e.subgraphs].sort((m,h)=>{let g=m.split(pe).length,b=h.split(pe).length;return g!==b?g-b:m<h?-1:m>h?1:0})){let m=f.split(pe),h=s;for(let g of m)h._mounts.has(g)||h.mount(g,new t(g)),h=h._mounts.get(g)}let a=o?Object.entries(o).map(([f,m])=>({re:on(f),factory:m})):[],i=f=>{for(let m of a)if(m.re.test(f))return m.factory},d=f=>{let m=f.split(pe),h=m.pop();if(h==null||h.length===0)throw new Error(`invalid snapshot path "${f}"`);let g=s;for(let b of m){let T=g._mounts.get(b);if(!T)throw new Error(`unknown mount "${b}" in path "${f}"`);g=T}return[g,h]},u=Object.entries(e.nodes).filter(([f])=>!f.includes(`${pe}${Ee}${pe}`)).sort((f,m)=>f[0]<m[0]?-1:f[0]>m[0]?1:0),c=new Map(u),l=new Map,p=!0;for(;c.size>0&&p;){p=!1;for(let[f,m]of[...c.entries()]){let h=m?.deps??[];if(!h.every(k=>l.has(k)))continue;let[g,b]=d(f),T={...m?.meta??{}},y=i(f),v;if(m?.type==="state")v=F(m.value,{meta:T});else{if(y==null)continue;v=y(b,{path:f,type:m.type,value:m.value,meta:T,deps:h,resolvedDeps:h.map(k=>l.get(k))})}g.add(v,{name:b}),l.set(f,v),c.delete(f),p=!0}}if(c.size>0){let f=[...c.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${f}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return s.restore(e),s}toJSON(){return this.snapshot()}attachSnapshotStorage(e,n={}){let r=e.map(u=>({tier:u,debounceMs:Math.max(0,u.debounceMs??0),compactEvery:Math.max(1,u.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));n.autoRestore===!0&&this._cascadeRestore(e,n.onError);let o=(u,c)=>{if(u.disposed)return;let l=$i(c.nodes);if(u.lastSnapshot!=null&&l!==""&&l===u.lastFingerprint)return;let p=u.seq+1,f=ce(),g=u.lastSnapshot==null||p%u.compactEvery===0?{name:this.name,mode:"full",snapshot:c,seq:p,timestamp_ns:f,format_version:ot}:{name:this.name,mode:"diff",diff:Jo(u.lastSnapshot,c),seq:p,timestamp_ns:f,format_version:ot};if(u.tier.filter&&!u.tier.filter(g))return;let b;try{b=u.tier.save(g)}catch(T){n.onError?.(T,u.tier);return}if(b&&typeof b.then=="function"){let v=(u.savePending??Promise.resolve()).then(()=>b,()=>b).then(()=>{u.disposed||(u.seq=p,u.lastSnapshot=c,u.lastFingerprint=l)},k=>{n.onError?.(k,u.tier)});u.savePending=v.finally(()=>{u.savePending===v&&(u.savePending=void 0)})}else u.seq=p,u.lastSnapshot=c,u.lastFingerprint=l},s=(u,c)=>{try{o(u,c)}catch(l){n.onError?.(l,u.tier)}},a=(u,c)=>{if(!c.some(m=>{let h=this.config.messageTier(m[0]);return h>=3&&h<5}))return;if(n.filter){let m=this.tryResolve(u);if(m==null)return;let h=rr(m,nr("standard"));if(!n.filter(u,h))return}let p,f=()=>(p==null&&(p=this.snapshot()),p);for(let m of r)m.disposed||(m.debounceMs===0?s(m,f()):(m.timer==null&&(m.timer=new ge),m.timer.start(m.debounceMs,()=>{m.disposed||s(m,this.snapshot())})))},i;if(n.paths!=null){let c=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(l=>{let p=this.tryResolve(l);return p==null?()=>{}:p.subscribe(f=>a(l,f))});i=()=>{for(let l of c)l()}}else i=this.observe().subscribe((u,c)=>a(u,c));let d=()=>{i();for(let u of r)u.disposed=!0,u.timer?.cancel();this._storageDisposers.delete(d)};return this._storageDisposers.add(d),{dispose:d}}async _cascadeRestore(e,n){for(let r of e){let o;try{o=await r.load?.()}catch(a){n?.(a,r);continue}if(o==null||typeof o!="object"||Array.isArray(o))continue;let s=o;try{if(s.mode==="full"&&s.snapshot!=null)return this.restore(s.snapshot),!0;if(s.version===ot&&s.nodes!=null)return this.restore(s),!0}catch(a){n?.(a,r)}}return!1}static async fromStorage(e,n,r){for(let o of n){let s;try{s=await o.load?.()}catch(d){r?.onError?.(d,o);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let a=s,i=a.mode==="full"&&a.snapshot!=null?a.snapshot:a.version===ot&&a.nodes!=null?a:void 0;if(i!=null)try{return t.fromSnapshot(i,r)}catch(d){r?.onError?.(d,o)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${n.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,n,r){if(e!=null&&n!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,n),this.config.inspectorEnabled){let o={path:e,annotation:n,timestamp_ns:z(),...r?.actor!=null?{actor:r.actor}:{}};this._traceRing.push(o)}return}return e!=null?this.config.inspectorEnabled?this._annotations.get(e):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(e){return this._annotations.get(e)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(e){let n=this._traceRing.toArray().filter(o=>!e(o)),r=this._traceRing.size-n.length;this._traceRing.clear();for(let o of n)this._traceRing.push(o);return r}static diff(e,n){let r=new Set(Object.keys(e.nodes)),o=new Set(Object.keys(n.nodes)),s=[...o].filter(T=>!r.has(T)).sort(),a=[...r].filter(T=>!o.has(T)).sort(),i=[],d=[];for(let T of r){if(!o.has(T))continue;let y=e.nodes[T],v=n.nodes[T],k=y.v,N=v.v;k!=null&&N!=null&&k.id===N.id&&k.version!==N.version&&d.push({path:T,id:k.id,from:k.version,to:N.version});let w=k!=null&&N!=null&&k.id===N.id&&k.version===N.version;for(let R of["type","status","sentinel"]){let x=y[R],_=v[R];x!==_&&i.push({path:T,field:R,from:x,to:_})}if(!w)for(let R of["value","meta"]){let x=y[R],_=v[R];ji(x,_)||i.push({path:T,field:R,from:x,to:_})}}let u=T=>`${T.from} ${T.to}`,c=new Set(e.edges.map(u)),l=new Set(n.edges.map(u)),p=n.edges.filter(T=>!c.has(u(T))),f=e.edges.filter(T=>!l.has(u(T))),m=new Set(e.subgraphs),h=new Set(n.subgraphs),g=[...h].filter(T=>!m.has(T)).sort(),b=[...m].filter(T=>!h.has(T)).sort();return{nodesAdded:s,nodesRemoved:a,nodesChanged:i,versionChanges:d,edgesAdded:p,edgesRemoved:f,subgraphsAdded:g,subgraphsRemoved:b}}}});var lr=ne(()=>{"use strict";Ke()});function At(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&"down"in t}function Yo(t){if(t<=0)throw new RangeError("timeoutMs must be > 0");if(t>9e6)throw new RangeError("timeoutMs must be <= 9_000_000 (\u22482.5h) to stay within safe ns arithmetic")}function Qo(t,e={}){let n=new Ct(t,e);return n.tagFactory("resilientPipeline",We(e)),n}var Ct,Xo=ne(()=>{"use strict";Oe();lr();He();Ie();mr();Ct=class extends ie{output;status;lastError;breakerState;droppedCount;rateLimitState;constructor(e,n={}){super(n.name??"resilient_pipeline",n.graph);let r=e,o,s,a;if(n.rateLimit!=null)if(At(n.rateLimit)){let d=r,u=n.rateLimit;r=ae(u,c=>{let l={...c,maxBuffer:c.maxBuffer??1/0,meta:ue("resilient","rate-limit")};return an(d,l).node}),this.add(r,{name:"rateLimited"})}else{let d={...n.rateLimit,maxBuffer:n.rateLimit.maxBuffer??1/0,meta:ue("resilient","rate-limit")},u=an(r,d);r=u.node,o=u.droppedCount,s=u.rateLimitState,this.add(r,{name:"rateLimited"}),this.add(o,{name:"droppedCount"}),this.add(s,{name:"rateLimitState"})}if(n.budget!=null)if(At(n.budget)){let d=r,u=n.budget;r=ae(u,c=>c.length>0?Et(d,c,{meta:ue("resilient","budget")}):d),this.add(r,{name:"budgetGated"})}else n.budget.length>0&&(r=Et(r,n.budget,{meta:ue("resilient","budget")}),this.add(r,{name:"budgetGated"}));if(n.breaker!=null)if(At(n.breaker)){let d=r,u=n.breaker,c=n.breakerOnOpen??"skip";r=ae(u,l=>{let p=Ye(l);return sn(p,{onOpen:c,meta:ue("resilient","breaker")})(d).node}),this.add(r,{name:"breakerWrapped"})}else{let d=Ye(n.breaker),u=n.breakerOnOpen??"skip",c=sn(d,{onOpen:u,meta:ue("resilient","breaker")})(r);r=c.node,a=c.breakerState,this.add(r,{name:"breakerWrapped"}),this.add(a,{name:"breakerState"})}if(n.timeoutMs!=null)if(At(n.timeoutMs)){let d=r,u=n.timeoutMs;r=ae(u,c=>(Yo(c),dn(d,c*1e6,{meta:ue("resilient","timeout")}))),this.add(r,{name:"timeoutWrapped"})}else Yo(n.timeoutMs),r=dn(r,n.timeoutMs*1e6,{meta:ue("resilient","timeout")}),this.add(r,{name:"timeoutWrapped"});if(n.retry!=null)if(At(n.retry)){let d=r,u=n.retry;r=ae(u,c=>yt(d,{...c,meta:ue("resilient","retry")})),this.add(r,{name:"retryWrapped"})}else r=yt(r,{...n.retry,meta:ue("resilient","retry")}),this.add(r,{name:"retryWrapped"});n.fallback!==void 0&&(r=fr(r,n.fallback,{meta:ue("resilient","fallback")}),this.add(r,{name:"fallbackWrapped"}));let i=pr(r,{initialStatus:n.initialStatus??"pending",meta:ue("resilient","status")});this.output=i.node,this.status=i.status,this.lastError=i.error,this.breakerState=a,this.droppedCount=o,this.rateLimitState=s,this.add(this.output,{name:"output"}),this.add(this.status,{name:"status"}),this.add(this.lastError,{name:"lastError"})}}});function it(t){return{describeKind:"derived",...t}}function Ji(t){return t<0?0:t}function gr(t){return t[1]}function Yi(t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("backoff strategy must return a finite number");return t<0?0:t}function Zo(t){let e=t?.count,n=t?.backoff;if(n!==void 0&&e===void 0)throw new RangeError("retry({ backoff }) requires explicit count to prevent unbounded retries; pass { count: <n>, backoff: ... }");let r=e!==void 0?e:0;if(r<0)throw new RangeError("retry count must be >= 0");let o=n===void 0?null:typeof n=="string"?Zn(n):n;return{maxRetries:r,strategy:o}}function es(t){let e={};return t?.count!==void 0&&(e.count=t.count),typeof t?.backoff=="string"&&(e.backoff=t.backoff),Object.keys(e).length>0?e:void 0}function ts(t,e,n){let r=0,o=!1,s=null,a,i=new ge;function d(){a?.(),a=void 0}function u(l){if(o)return;if(r>=t.maxRetries){d(),n.down([[P,l]]);return}let p=t.strategy===null?0:t.strategy(r,l,s);if(p==null){d(),n.down([[P,l]]);return}let f;try{f=Yi(p)}catch{d(),n.down([[P,l]]);return}s=f,r+=1,d();let m=f>0?f/1e6:1;i.start(m,()=>{o||c()})}function c(){i.cancel(),d();let l;try{l=e()}catch(p){u(p);return}a=l.subscribe(p=>{if(!o)for(let f of p){let m=f[0];if(m===X)n.down([[X]]);else if(m===D)r=0,s=null,n.emit(f[1]);else if(m===U)n.down([[U]]);else if(m===$)d(),n.down([[$]]);else if(m===P){u(gr(f));return}else n.down([f])}})}return c(),()=>{o=!0,i.cancel(),d()}}function yt(t,e){return typeof t=="function"?Xi(t,e):Qi(t,e)}function Qi(t,e){let n=Zo(e);return se(r=>ts(n,()=>t,r),{...it(),initial:t.cache,meta:{...e?.meta??{},...le("retry",es(e))}})}function Xi(t,e){let n=Zo(e);return se(r=>ts(n,t,r),{...it(),initial:e?.initial,meta:{...e?.meta??{},...le("retry",es(e))}})}function Ye(t){let e=Math.max(1,t?.failureThreshold??5),n=Ji(t?.cooldownNs??30*1e9),r=t?.cooldown??null,o=Math.max(1,t?.halfOpenMax??1),s=t?.now??z,a="closed",i=0,d=0,u=0,c=n,l=0;function p(){if(!r)return n;let h=r(d);return h!==null?h:n}function f(){a="open",c=p(),u=s(),l=0}return{canExecute(){return a==="closed"?!0:a==="open"?s()-u>=c?(a="half-open",l=1,!0):!1:l<o?(l++,!0):!1},recordSuccess(){a==="half-open"?(a="closed",i=0,d=0):a==="closed"&&(i=0)},recordFailure(h){if(a==="half-open"){d++,f();return}a==="closed"&&(i++,i>=e&&f())},get state(){return a},get failureCount(){return i},reset(){a="closed",i=0,d=0,l=0}}}function sn(t,e){let n=e?.onOpen??"skip",r=e?.meta;return o=>{let s=te([],(a,i)=>{function d(){s.meta.breakerState.down([[D,t.state]])}let u=o.subscribe(c=>{for(let l of c){let p=l[0];p===X?i.down([[X]]):p===D?t.canExecute()?(d(),i.emit(l[1])):(d(),n==="error"?i.down([[P,new Qe]]):i.down([[U]])):p===U?i.down([[U]]):p===$?(t.recordSuccess(),d(),i.down([[$]])):p===P?(t.recordFailure(gr(l)),d(),i.down([l])):i.down([l])}});return d(),u},{...it(),meta:{...r??{},breakerState:t.state,...le("withBreaker",{onOpen:n})},completeWhenDepsComplete:!1,initial:o.cache});return{node:s,breakerState:s.meta.breakerState}}}function Lt(t,e,n){if(t<=0)throw new RangeError("capacity must be > 0");if(e<0)throw new RangeError("refillPerSecond must be >= 0");let r=n?.clock??z,o=t,s=r();function a(i){if(e>0){let d=i-s;o=Math.min(t,o+d/1e9*e)}s=i}return{available(){return a(r()),o},tryConsume(i=1){if(i<=0)return!0;let d=r();return a(d),o>=i?(o-=i,!0):!1},putBack(i=1){i<=0||(a(r()),o=Math.min(t,o+i))}}}function Zi(t,e){return t.droppedCount===e.droppedCount&&t.pendingCount===e.pendingCount&&t.paused===e.paused}function an(t,e){let{maxEvents:n,windowNs:r}=e;if(n<=0)throw new RangeError("maxEvents must be > 0");if(r<=0)throw new RangeError("windowNs must be > 0");let o=e.maxBuffer;if(o===void 0)throw new RangeError("rateLimiter requires explicit maxBuffer (use Infinity to opt in to unbounded)");let s=o===1/0;if(!s&&(!Number.isInteger(o)||o<1))throw new RangeError("maxBuffer must be a positive integer (or Infinity for unbounded)");let a=e.onOverflow??"drop-newest",i=n*1e9/r,d=se(u=>{let c=Lt(n,i),l=s?ta():ea(o),p=new ge,f=!1,m=0,h=1e9/i,g=d.meta.droppedCount,b=d.meta.rateLimitState,T=un;function y(){g.emit(m);let R={droppedCount:m,pendingCount:l.size,paused:l.size>0};Zi(T,R)||(T=R,b.emit(R))}T=un,g.emit(0),b.emit(un);function v(){for(;l.size>0;)if(c.tryConsume(1))u.emit(l.shift()),y();else{p.start(Math.max(1,h/1e6),v);return}}function k(){m+=1,y()}function N(){for(f=!0,p.cancel();l.size>0;)l.shift();m=0}let w=t.subscribe(R=>{for(let x of R){if(f)return;let _=x[0];if(_===X)u.down([[X]]);else if(_===D){if(!s&&l.size>=o)if(a==="drop-newest")k();else if(a==="drop-oldest")l.shift(),l.push(x[1]),k();else{k(),N(),u.down([[P,new cn(o)]]);return}else l.push(x[1]),y();v()}else if(_===U)u.down([[U]]);else if(_===$)N(),u.down([[$]]);else if(_===P)N(),u.down([x]);else if(_===fe){N(),u.down([x]);return}else u.down([x])}});return()=>{f=!0,p.cancel(),w()}},{...it(),initial:t.cache,meta:{...e.meta??{},droppedCount:0,rateLimitState:un,...le("rateLimiter",e)}});return{node:d,droppedCount:d.meta.droppedCount,rateLimitState:d.meta.rateLimitState}}function ea(t){let e=new rt(t);return{push:n=>e.push(n),shift:()=>e.shift(),get size(){return e.size}}}function ta(){let t=[];return{push:e=>{t.push(e)},shift:()=>t.shift(),get size(){return t.length}}}function pr(t,e){let n=e?.initialStatus??"pending",r=e?.meta,o=te([],(s,a)=>{let i=n;return o.meta.status.down([[D,n]]),o.meta.error.down([[D,null]]),t.subscribe(u=>{for(let c of u){let l=c[0];if(l===X)a.down([[X]]);else if(l===D)i==="errored"?re(()=>{o.meta.error.down([[D,null]]),o.meta.status.down([[D,"running"]])}):o.meta.status.down([[D,"running"]]),i="running",a.emit(c[1]);else if(l===U)a.down([[U]]);else if(l===$)o.meta.status.down([[D,"completed"]]),i="completed",a.down([[$]]);else if(l===P){let p=gr(c);re(()=>{o.meta.error.down([[D,p]]),o.meta.status.down([[D,"errored"]])}),i="errored",a.down([c])}else a.down([c])}})},{...it(),meta:{...r??{},status:n,error:null,...le("withStatus",{initialStatus:n})},completeWhenDepsComplete:!1,resubscribable:!0,initial:t.cache});return{node:o,status:o.meta.status,error:o.meta.error}}function na(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function ra(t){return t!=null&&typeof t.then=="function"}function oa(t){return t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function"}function fr(t,e,n){let r=n?.meta;return se(o=>{let s,a;function i(){a?.(),a=void 0,na(e)||ra(e)||oa(e)?s=V(e).subscribe(u=>{o.down(u);for(let c of u){let l=c[0];if(l===$||l===P||l===fe){s=void 0;return}}}):(o.emit(e),o.down([[$]]))}return a=t.subscribe(d=>{for(let u of d){let c=u[0];if(c===X)o.down([[X]]);else if(c===D)o.emit(u[1]);else if(c===U)o.down([[U]]);else if(c===$)o.down([[$]]);else if(c===P){i();return}else if(c===fe){s?.(),o.down([u]);return}else o.down([u])}}),()=>{a?.(),s?.()}},{...it(),initial:t.cache,meta:{...r??{},...le("fallback")}})}function dn(t,e,n){if(e<=0)throw new RangeError("timeoutNs must be > 0");let r=n?.meta;return se(o=>{let s=!1,a=new ge;function i(){let u=e/1e6;a.start(u,()=>{s||(s=!0,d(),o.down([[P,new ln(e)]]))})}let d=t.subscribe(u=>{for(let c of u){if(s)return;let l=c[0];if(l===X)o.down([[X]]);else if(l===D)i(),o.emit(c[1]);else if(l===U)o.down([[U]]);else if(l===$){a.cancel(),s=!0,o.down([[$]]);return}else if(l===P){a.cancel(),s=!0,o.down([c]);return}else if(l===fe){a.cancel(),s=!0,o.down([c]);return}else o.down([c])}});return i(),()=>{s=!0,a.cancel(),d()}},{...it(),initial:t.cache,meta:{...r??{},...le("timeout",{timeoutNs:e})}})}var Qe,cn,un,ln,mr=ne(()=>{"use strict";Eo();Xo();Me();ye();de();Oe();we();Q();er();Z();Ve();ar();Qe=class extends Error{name="CircuitOpenError";constructor(){super("Circuit breaker is open")}};cn=class extends Error{name="RateLimiterOverflowError";constructor(e){super(`rateLimiter buffer overflow (maxBuffer=${e})`)}};un=Object.freeze({droppedCount:0,pendingCount:0,paused:!1});ln=class extends Error{name="TimeoutError";constructor(e){super(`Timed out after ${e/1e6}ms`)}}});var ns={};jn(ns,{CircuitOpenError:()=>Qe,RateLimiterOverflowError:()=>cn,ResilientPipelineGraph:()=>Ct,TimeoutError:()=>ln,budgetGate:()=>Et,circuitBreaker:()=>Ye,fallback:()=>fr,rateLimiter:()=>an,resilientPipeline:()=>Qo,retry:()=>yt,timeout:()=>dn,tokenBucket:()=>Lt,withBreaker:()=>sn,withStatus:()=>pr});var bt=ne(()=>{"use strict";mr()});function pn(t){return{describeKind:"producer",...t}}function fn(t,e){let{signal:n,period:r,...o}=e??{};return se(s=>{let a=!1,i=0,d,u,c=()=>{a=!0,d!==void 0&&clearTimeout(d),u!==void 0&&clearInterval(u),n?.removeEventListener("abort",p)},l=()=>{a||(r!=null?(s.emit(i++),u=setInterval(()=>{a||s.emit(i++)},r)):(a=!0,n?.removeEventListener("abort",p),s.emit(i++),s.down([[$]])))},p=()=>{a||(c(),s.down([[P,n.reason]]))};if(n?.aborted){p();return}return d=setTimeout(l,t),n?.addEventListener("abort",p,{once:!0}),c},pn(o))}function ss(t,e){return se(n=>{let r=!1;try{for(let o of t){if(r)return;n.emit(o)}r||n.down([[$]])}catch(o){r||n.down([[P,o]])}return()=>{r=!0}},pn(e))}function sa(t){return t!=null&&typeof t.then=="function"}function mn(t,e){let{signal:n,...r}=e??{};return se(o=>{let s=!1,a=()=>{s||(s=!0,o.down([[P,n.reason]]))};if(n?.aborted){a();return}return n?.addEventListener("abort",a,{once:!0}),Promise.resolve(t).then(i=>{s||(s=!0,n?.removeEventListener("abort",a),o.emit(i),o.down([[$]]))},i=>{s||(s=!0,n?.removeEventListener("abort",a),o.down([[P,i]]))}),()=>{s=!0,n?.removeEventListener("abort",a)}},pn(r))}function yr(t,e){let{signal:n,...r}=e??{};return se(o=>{let s=new AbortController,a=()=>s.abort(n?.reason);n?.aborted?s.abort(n.reason):n?.addEventListener("abort",a,{once:!0});let i=n??s.signal,d=!1,u=t[Symbol.asyncIterator](),c=()=>{d||i.aborted||Promise.resolve(u.next()).then(l=>{if(!(d||i.aborted)){if(l.done){o.down([[$]]);return}o.emit(l.value),c()}},l=>{!d&&!i.aborted&&o.down([[P,l]])})};return c(),()=>{d=!0,n?.removeEventListener("abort",a),s.abort(),Promise.resolve(u.return?.()).catch(()=>{})}},pn(r))}function ia(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function V(t,e){if(ia(t))return t;if(sa(t))return mn(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return yr(t,e);if(typeof n[Symbol.iterator]=="function")return ss(t,e)}return aa(t)}function aa(...t){return ss(t,void 0)}function Dt(t,e,n){return te([t],(o,s)=>{let a=o[0];if(a!=null&&a.length>0)for(let i of a)e(i)},{describeKind:"effect",...n}).subscribe(()=>{})}function _e(t){return new Promise((e,n)=>{let r=!1,o=!1,s;s=t.subscribe(a=>{for(let i of a){if(r)return;if(i[0]===D){r=!0,e(i[1]),s?(s(),s=void 0):o=!0;return}if(i[0]===P){r=!0,n(i[1]),s?(s(),s=void 0):o=!0;return}if(i[0]===$){r=!0,n(new Error("completed without DATA")),s?(s(),s=void 0):o=!0;return}}}),o&&(s?.(),s=void 0)})}function rs(t,e,n){return new Promise((r,o)=>{let s=!1,a=!1,i,d=n?.skipCurrent===!0;i=t.subscribe(u=>{for(let c of u){if(s)return;if(!(d&&c[0]===D)){if(c[0]===D){let l=c[1];if(e(l)){s=!0,r(l),i?(i(),i=void 0):a=!0;return}}if(c[0]===P){s=!0,o(c[1]),i?(i(),i=void 0):a=!0;return}if(c[0]===$){s=!0,o(new Error("completed without matching value")),i?(i(),i=void 0):a=!0;return}}}}),d=!1,a&&(i?.(),i=void 0)})}async function is(t,e){let n=e?.predicate??(s=>s!=null),r=e?.skipCurrent;if(e?.timeoutMs==null||e.timeoutMs<=0)return await rs(t,n,{skipCurrent:r});if(hr===void 0){let[s,a]=await Promise.all([Promise.resolve().then(()=>(bt(),ns)),Promise.resolve().then(()=>(er(),Mo))]);hr=s.timeout,os=a.NS_PER_MS}let o=hr(t,e.timeoutMs*os);return await rs(o,n,{skipCurrent:r})}function as(t,e){let n=new AbortController,r=e?.reason??new Error("cancelled via nodeSignal"),o,s=!1,a=()=>{o?(o(),o=void 0):s=!0};return o=t.subscribe(i=>{if(!n.signal.aborted)for(let d of i){if(d[0]===D&&d[1]===!0){n.abort(r),a();return}if(d[0]===P){n.abort(d[1]),a();return}if(d[0]===$){a();return}}}),s&&(o?.(),o=void 0),{signal:n.signal,dispose:()=>{o&&(o(),o=void 0)}}}function Y(t){return t.subscribe(()=>{})}var hr,os,ds=ne(()=>{"use strict";de();we();Q()});var Z=ne(()=>{"use strict";ds()});function gn(t){return{describeKind:"derived",...t}}function da(t){return{describeKind:"derived",partial:!0,...t}}function us(t,e,n){return te([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[U]]);return}let a=!1;for(let i of s)e(i)&&(o.emit(i),a=!0);a||o.down([[U]])},{...gn(n),meta:{...le("filter"),...n?.meta??{}}})}function cs(t,e,n){let r=n?.where??(s=>s!=null),o=!1;return te([t],(s,a)=>{let i=s[0];if(i==null||i.length===0){a.down([[U]]);return}for(let d of i)!o&&r(d)&&(o=!0,e(d)),a.emit(d)},gn(n))}function ls(t,e,n){return te([t,e],(r,o,s)=>{let a=r[0],i=r[1],d=i!=null&&i.length>0?i.at(-1):s.prevData[1];if(a!=null&&a.length>0){if(!(i!=null&&i.length>0)&&s.prevData[1]===void 0){o.down([[U]]);return}for(let u of a)o.emit([u,d])}else o.down([[U]])},{...da(n),meta:{...le("withLatestFrom"),...n?.meta??{}}})}function ua(t,e,n){let r,o=!1,s=()=>{o||(o=!0,n())};return r=t.subscribe(a=>{let i=!1,d=!1;for(let u of a)u[0]!==Be&&(u[0]===D?e.emit(u[1]):u[0]===$?i=!0:u[0]===P?(d=!0,e.down([u])):(u[0]===X||u[0]===U)&&e.down([u]));d?(r?.(),r=void 0,s()):i&&s()}),()=>{r?.(),r=void 0}}function ae(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return te([t],(a,i,d)=>{if(d.terminalDeps[0]!=null&&d.terminalDeps[0]!==!0){s();return}if(d.terminalDeps[0]===!0){o=!0,r||i.down([[$]]);return}let u=a[0];if(!(u==null||u.length===0))return s(),r=ua(V(e(u[u.length-1])),i,()=>{s(),o&&i.down([[$]])}),{deactivate:()=>{s(),o=!1}}},{...gn(n),completeWhenDepsComplete:!1,meta:{...le("switchMap"),...n?.meta??{}}})}function ps(t,e,n){return se(r=>{let o=t.subscribe(s=>{for(let a of s)if(a[0]===D)r.emit(a[1]);else if(a[0]===P)try{r.emit(e(a[1]))}catch(i){r.down([[P,i]])}else a[0]===$&&r.down([[$]])});return()=>{o()}},gn(n))}var fs=ne(()=>{"use strict";de();Oe();we();Q();Z()});var Ie=ne(()=>{"use strict";fs()});var Ud={};jn(Ud,{AgentLoopGraph:()=>Pn,AllTiersExhaustedError:()=>Gt,BudgetExhaustedError:()=>Sn,ChatStreamGraph:()=>Cn,CircuitOpenError:()=>Qe,DEFAULT_DECAY_RATE:()=>Dn,FallbackMissError:()=>wa,LLMTimeoutError:()=>wt,ReplayCacheMissError:()=>ut,ToolRegistryGraph:()=>Ln,admissionFilter3D:()=>Rd,admissionScored:()=>Ks,agentLoop:()=>Od,agentMemory:()=>Ad,anthropicAdapter:()=>br,canonicalJson:()=>Rr,cascadingLlmAdapter:()=>Fr,chatStream:()=>Yr,composePricing:()=>Ba,computePrice:()=>Ar,contentGate:()=>bd,costMeterExtractor:()=>pd,createAdapter:()=>Ia,createCapabilitiesRegistry:()=>Ni,createPricingRegistry:()=>$a,dryRunAdapter:()=>at,fallbackAdapter:()=>Sr,frozenContext:()=>od,gatedStream:()=>ud,gaugesAsContext:()=>Cd,googleAdapter:()=>Nr,graphFromSpec:()=>di,graphFromSpecReactive:()=>$d,handoff:()=>vd,keywordFlagExtractor:()=>md,knobsAsTools:()=>Bd,llmConsolidator:()=>Ur,llmExtractor:()=>zr,memoryRetrieval:()=>ro,memoryWithKG:()=>to,memoryWithTiers:()=>no,memoryWithVectors:()=>eo,observableAdapter:()=>Ga,openAICompatAdapter:()=>Mr,parseRateLimitFromError:()=>Ir,pricingFor:()=>Va,promptCall:()=>Kr,promptNode:()=>Vr,redactor:()=>Td,registryPricing:()=>ja,resilientAdapter:()=>ed,streamExtractor:()=>gd,streamingPromptNode:()=>dd,suggestStrategy:()=>ui,suggestStrategyReactive:()=>Kd,systemPromptBuilder:()=>cd,tier:()=>Xa,toolCallExtractor:()=>yd,toolExecution:()=>Qr,toolRegistry:()=>Xr,toolSelector:()=>xd,validateGraphDef:()=>zd,withBreaker:()=>Cr,withBudgetGate:()=>Dr,withDryRun:()=>za,withRateLimiter:()=>Gr,withReplayCache:()=>It,withRetry:()=>$r,withTimeout:()=>jr,zeroPrice:()=>Rn});module.exports=gi(Ud);Q();Me();ye();de();Q();var Xn=class{_version=0;_store=new Map;_maxSize;_defaultTtl;constructor(e={}){let{maxSize:n,defaultTtl:r}=e;if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(r!==void 0&&r<=0)throw new RangeError("defaultTtl must be positive");this._maxSize=n,this._defaultTtl=r}get version(){return this._version}get size(){return this._store.size}has(e){let n=this._store.get(e);return n===void 0?!1:this._isExpired(n)?(this._store.delete(e),this._version+=1,!1):(this._touchLru(e,n),!0)}get(e){let n=this._store.get(e);if(n!==void 0){if(this._isExpired(n)){this._store.delete(e),this._version+=1;return}return this._touchLru(e,n),n.value}}set(e,n,r){let o=this._resolveExpiresAt(r);this._store.has(e)&&this._store.delete(e),this._store.set(e,{value:n,expiresAt:o}),this._evictLruWhileOver(),this._version+=1}setMany(e,n){let r=this._resolveExpiresAt(n),o=0;try{for(let[s,a]of e)this._store.has(s)&&this._store.delete(s),this._store.set(s,{value:a,expiresAt:r}),o+=1}finally{o>0&&(this._evictLruWhileOver(),this._version+=1)}}delete(e){let n=this._store.delete(e);return n&&(this._version+=1),n}deleteMany(e){let n=0;try{for(let r of e)this._store.delete(r)&&(n+=1)}finally{n>0&&(this._version+=1)}return n}clear(){let e=this._store.size;return e===0?0:(this._store.clear(),this._version+=1,e)}pruneExpired(){let e=z(),n=0;for(let[r,o]of this._store)this._isExpired(o,e)&&(this._store.delete(r),n+=1);return n>0&&(this._version+=1),n}toMap(){let e=z(),n=new Map;for(let[r,o]of this._store)this._isExpired(o,e)||n.set(r,o.value);return n}_resolveExpiresAt(e){let n=e??this._defaultTtl;if(n!==void 0){if(!Number.isFinite(n)||n<=0)throw new RangeError(`MapBackend: ttl must be a positive finite number (got ${n})`);return z()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??z())>=e.expiresAt}_touchLru(e,n){this._store.delete(e),this._store.set(e,n)}_evictLruWhileOver(){if(this._maxSize!==void 0)for(;this._store.size>this._maxSize;){let e=this._store.keys().next().value;if(e===void 0)break;this._store.delete(e)}}};function Ge(t={}){let{name:e,maxSize:n,defaultTtl:r,versioning:o,backend:s,retention:a}=t;if(a&&n!==void 0)throw new RangeError("reactiveMap: `maxSize` (LRU) and `retention` (score-based) are mutually exclusive. Pick one eviction policy.");if(a&&a.archiveThreshold===void 0&&a.maxSize===void 0)throw new RangeError("reactiveMap: `retention` requires at least one of `archiveThreshold` or `maxSize` to trigger archival.");let i=s??new Xn({maxSize:n,defaultTtl:r}),d=F(i.toMap(),{name:e,describeKind:"state",equals:(p,f)=>p===f,...o!=null?{versioning:o}:{}});function u(){let p=i.toMap();re(()=>{d.down([[X]]),d.down([[D,p]])})}function c(){if(!a)return;let p=i.toMap(),f=a.archiveThreshold,m=a.maxSize,h=[];for(let[b,T]of p)h.push({key:b,value:T,score:a.score(b,T)});h.sort((b,T)=>b.score-T.score);let g=new Set;if(f!==void 0)for(let b of h)if(b.score<f)g.add(b.key);else break;if(m!==void 0&&h.length-g.size>m)for(let b of h){if(h.length-g.size<=m)break;g.has(b.key)||g.add(b.key)}if(g.size!==0)for(let b of h)g.has(b.key)&&(a.onArchive?.(b.key,b.value,b.score),i.delete(b.key))}function l(p,f="mutation"){let m=i.version;try{return p()}finally{i.version!==m&&(f==="mutation"&&c(),u())}}return{entries:d,has(p){return l(()=>i.has(p),"read")},get(p){return l(()=>i.get(p),"read")},set(p,f,m){l(()=>i.set(p,f,m?.ttl))},setMany(p,f){l(()=>i.setMany(p,f?.ttl))},delete(p){l(()=>i.delete(p))},deleteMany(p){l(()=>i.deleteMany(p))},clear(){l(()=>i.clear())},pruneExpired(){l(()=>i.pruneExpired())},get size(){return i.size},dispose(){}}}function Ot(t,e){return`${t}::${e}`}function Ni(t){let e=Ge({name:"capabilitiesRegistry"}),n=u=>{e.set(Ot(u.provider,u.id),u)};if(t)for(let u of t)n(u);let r=(u,c)=>{let l=e.get(Ot(u,c));if(l)return l;let p=e.entries.cache;if(!p)return;let f;for(let[,m]of p){if(m.provider!==u)continue;let h=m.id;c.startsWith(h)&&(!f||h.length>f.id.length)&&(f=m)}return f},o=128,s=new Map,a=new Map,i=(u,c,l,p)=>{for(u.has(c)&&u.delete(c),u.set(c,l);u.size>p;){let f=u.keys().next().value;if(f===void 0)break;u.delete(f)}},d=A([e.entries],([u])=>u instanceof Map?Array.from(u.values()):[],{name:"capabilitiesRegistry/entries",initial:[]});return{register:n,lookup:r,remove(u,c){let l=e.has(Ot(u,c));return l&&e.delete(Ot(u,c)),l},entries(){let u=e.entries.cache;return(function*(){if(u)for(let c of u.values())yield c})()},lookupNode(u,c){let l=Ot(u,c),p=s.get(l);if(p)return s.delete(l),s.set(l,p),p;let f=A([e.entries],()=>r(u,c),{name:`capabilitiesRegistry/lookup/${u}::${c}`,initial:void 0});return i(s,l,f,o),f},entriesNode:d,byProvider(u){let c=a.get(u);if(c)return a.delete(u),a.set(u,c),c;let l=A([d],([p])=>p.filter(f=>f.provider===u),{name:`capabilitiesRegistry/byProvider/${u}`,initial:[]});return i(a,u,l,o),l}}}ye();async function*Tt(t,e){let n=e?.parse??(k=>k),r=e?.signal,o=new TextDecoder,s="",a="message",i=[],d,u,c=[],l=()=>{if(i.length===0&&a==="message"&&d===void 0){i=[];return}let k=i.join(`
4
- `);c.push({event:a,data:n(k),id:d,retry:u}),a="message",i=[],d=void 0,u=void 0},p=k=>{if(k===""){l();return}if(k.startsWith(":"))return;let N=k.indexOf(":"),w=N<0?k:k.slice(0,N),R=N<0?"":k.slice(N+1);switch(R.startsWith(" ")&&(R=R.slice(1)),w){case"event":a=R;break;case"data":i.push(R);break;case"id":R.includes("\0")||(d=R);break;case"retry":{let x=Number(R);Number.isFinite(x)&&(u=x);break}}},f=(k,N)=>{s+=o.decode(k,{stream:!N});let w=s.split(/\r?\n/);s=w.pop()??"";for(let R of w)p(R)},m=t,h=t instanceof ReadableStream?t:m&&typeof m=="object"&&m.body instanceof ReadableStream?m.body:null,g,b,T=!1,y=()=>{T||(T=!0,g&&g.cancel().catch(()=>{}),b&&typeof b.return=="function"&&Promise.resolve(b.return()).catch(()=>{}))},v=()=>{y()};if(r){if(r.aborted)return;r.addEventListener("abort",v,{once:!0})}try{if(h){for(g=h.getReader();!r?.aborted;){let{value:k,done:N}=await g.read();if(N)break;for(f(k,!1);c.length>0;)yield c.shift()}f(new Uint8Array,!0)}else{for(b=t[Symbol.asyncIterator]();!r?.aborted;){let N=await b.next();if(N.done)break;for(f(N.value,!1);c.length>0;)yield c.shift()}f(new Uint8Array,!0)}if(s.trim()){for(let k of s.split(/\r?\n/))p(k);l()}for(;c.length>0;)yield c.shift()}finally{r&&r.removeEventListener("abort",v),y()}}async function ze(t,e){let n;try{n=await t.text()}catch{n=""}let r=e??"HTTP",o=new Error(`${r} API ${t.status}: ${t.statusText}${n?` \u2014 ${n}`:""}`);return o.status=t.status,o.headers=t.headers,o}function br(t={}){return t.sdk?ma(t):fa(t)}function hn(t,e,n,r){let o=e?.model??n;if(!o)throw new Error("anthropicAdapter: model must be set via options.model or invokeOpts.model");let{system:s,chat:a}=ca(t,e?.systemPrompt),i={model:o,messages:a.map(la),max_tokens:e?.maxTokens??4096};return s&&(i.system=s),e?.temperature!=null&&(i.temperature=e.temperature),e?.tools&&e.tools.length>0&&(i.tools=e.tools.map(pa)),e?.maxReasoningTokens!=null&&(i.thinking={type:"enabled",budget_tokens:e.maxReasoningTokens}),e?.cacheHint,r&&(i.stream=!0),e?.providerExtras&&Object.assign(i,e.providerExtras),i}function ca(t,e){let n=[];e&&n.push(e);let r=[];for(let o of t)o.role==="system"?n.push(o.content):r.push(o);return{system:n.length>0?n.join(`
1
+ "use strict";var zn=Object.defineProperty;var mi=Object.getOwnPropertyDescriptor;var gi=Object.getOwnPropertyNames;var hi=Object.prototype.hasOwnProperty;var re=(t,e)=>()=>(t&&(e=t(t=0)),e);var Un=(t,e)=>{for(var n in e)zn(t,n,{get:e[n],enumerable:!0})},yi=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of gi(e))!hi.call(t,o)&&o!==n&&zn(t,o,{get:()=>e[o],enumerable:!(r=mi(e,o))||r.enumerable});return t};var bi=t=>yi(zn({},"__esModule",{value:!0}),t);function lo(t,e){let n=new TextEncoder().encode(t.name);if(n.length===0||n.length>255)throw new Error(`encodeEnvelope: codec name "${t.name}" encodes to ${n.length} bytes (must be 1\u2013255)`);let r=t.version;if(!Number.isInteger(r)||r<0||r>65535)throw new Error(`encodeEnvelope: codec.version ${r} out of u16 range (expected integer 0\u201365535)`);let o=2+n.length+2+e.length;if(o>4294967295)throw new Error(`encodeEnvelope: total envelope size ${o} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let s=new Uint8Array(o),a=0;return s[a++]=qn,s[a++]=n.length,s.set(n,a),a+=n.length,s[a++]=r>>>8&255,s[a++]=r&255,s.set(e,a),s}function po(t,e){if(t.length<co)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${co})`);let n=0,r=t[n++];if(r!==qn)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${qn})`);let o=t[n++];if(o===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(n+o+2>t.length)throw new Error(`decodeEnvelope: envelope truncated (need ${n+o+2} bytes, have ${t.length})`);let s=new TextDecoder().decode(t.subarray(n,n+o));n+=o;let a=(t[n]<<8|t[n+1])>>>0;n+=2;let i=t.subarray(n),d=e.lookupCodec(s);if(d==null)throw new Error(`decodeEnvelope: codec "${s}" not registered (envelope codec_v=${a})`);return{codec:d,codecVersion:a,payload:i}}function fo(t){t.registerCodec(Ti)}var Ti,qn,co,Wn=re(()=>{"use strict";Ti={name:"json",version:1,contentType:"application/json",encode(t){let e=JSON.stringify(t);return new TextEncoder().encode(e)},decode(t,e){let n=new TextDecoder().decode(t);return JSON.parse(n)}},qn=1,co=4});function Wt(t){if(t==null)return pt;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var pt,Ht=re(()=>{"use strict";pt={type:"system",id:""}});function Jt(){return ft>0||Ot}function mo(){return ft>0}function gt(t){ft>0?Et.push(t):t()}function te(t){ft+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(ft-=1,ft===0)if(e){if(!Ot){let n=Et.splice(0);for(let r of n)try{r()}catch{}tt.length=0,nt.length=0,mt.length=0}}else vi()}}function vi(){let t=!Ot;t&&(Ot=!0);let e=[],n=0;try{for(;tt.length>0||nt.length>0||mt.length>0||t&&Et.length>0;){if(t&&Et.length>0){let s=Et.splice(0);for(let a of s)try{a()}catch(i){e.push(i)}continue}if(n+=1,n>1e3)throw tt.length=0,nt.length=0,mt.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let o=(tt.length>0?tt:nt.length>0?nt:mt).splice(0);for(let s of o)try{s()}catch(a){e.push(a)}}}finally{t&&(Ot=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function Yt(t,e,n){if(e.length===0)return;if(e.length===1){let u=n(e[0][0]);if(u<3||!Jt()){t(e);return}(u>=5?mt:u===4?nt:tt).push(()=>t(e));return}let r=e.length,o=r,s=r,a=r,i=0;for(;i<r&&n(e[i][0])<3;)i++;for(o=i;i<r&&n(e[i][0])===3;)i++;for(s=i;i<r&&n(e[i][0])===4;)i++;a=i;let d=Jt();if(o>0){let u=e.slice(0,o);t(u)}if(s>o){let u=e.slice(o,s);d?tt.push(()=>t(u)):t(u)}if(a>s){let u=e.slice(s,a);d?nt.push(()=>t(u)):t(u)}if(r>a){let u=e.slice(a,r);d?mt.push(()=>t(u)):t(u)}}var ft,Ot,tt,nt,mt,Et,Oe=re(()=>{"use strict";ft=0,Ot=!1,tt=[],nt=[],mt=[],Et=[]});function z(){return Math.trunc(performance.now()*1e6)}function ce(){return Date.now()*1e6}var ye=re(()=>{"use strict"});var Ke,D,X,U,Le,Se,De,le,$,P,rt,Qt,go,Xt,ho,yo,Zt,Hn,Jn,Yn,en,ie=re(()=>{"use strict";Ke=Symbol.for("graphrefly/START"),D=Symbol.for("graphrefly/DATA"),X=Symbol.for("graphrefly/DIRTY"),U=Symbol.for("graphrefly/RESOLVED"),Le=Symbol.for("graphrefly/INVALIDATE"),Se=Symbol.for("graphrefly/PAUSE"),De=Symbol.for("graphrefly/RESUME"),le=Symbol.for("graphrefly/TEARDOWN"),$=Symbol.for("graphrefly/COMPLETE"),P=Symbol.for("graphrefly/ERROR"),rt=Object.freeze([X]),Qt=Object.freeze([U]),go=Object.freeze([Le]),Xt=Object.freeze([Ke]),ho=Object.freeze([$]),yo=Object.freeze([le]),Zt=Object.freeze([rt]),Hn=Object.freeze([Qt]),Jn=Object.freeze([go]),Yn=Object.freeze([ho]),en=Object.freeze([yo])});function bo(t){t.registerMessageType(Ke,{tier:0,wireCrossing:!1}),t.registerMessageType(X,{tier:1,wireCrossing:!1}),t.registerMessageType(Le,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(Se,{tier:2,wireCrossing:!1}),t.registerMessageType(De,{tier:2,wireCrossing:!1}),t.registerMessageType(D,{tier:3,wireCrossing:!0}),t.registerMessageType(U,{tier:3,wireCrossing:!0}),t.registerMessageType($,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(P,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(le,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var tn,To=re(()=>{"use strict";ie();tn=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_rigorRecorder;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=n=>{let r=this._messageTypes.get(n);return r!=null?r.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}get rigorRecorder(){return this._rigorRecorder}set rigorRecorder(e){this._rigorRecorder=e}registerMessageType(e,n){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:n.tier,wireCrossing:n.wireCrossing??n.tier>=3,metaPassthrough:n.metaPassthrough??!0}),this}messageTier(e){let n=this._messageTypes.get(e);return n!=null?n.tier:1}isWireCrossing(e){let n=this._messageTypes.get(e);return n!=null?n.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let n=this._messageTypes.get(e);return n!=null?n.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 vo(t){return Array.isArray(t)?[...t]:[t]}function wi(t,e){return t.has(e)||t.has("*")}function wo(t){let e=[];return t((o,s)=>{e.push({kind:"allow",actions:new Set(vo(o)),where:s?.where??(()=>!0)})},(o,s)=>{e.push({kind:"deny",actions:new Set(vo(o)),where:s?.where??(()=>!0)})}),(o,s)=>{let a=!1,i=!1;for(let d of e)wi(d.actions,s)&&d.where(o)&&(d.kind==="deny"?a=!0:i=!0);return a?!1:i}}function Qn(t){let e=ki.filter(n=>t({type:n,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(n=>n==="human"||n==="llm"||n==="system")?"both":e.length===1?e[0]:e.join("+")}var Ie,ki,ht=re(()=>{"use strict";Ie=class extends Error{actor;action;nodeName;constructor(e,n){super(n??`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}};ki=["human","llm","wallet","system"]});function Xn(t){if(t===void 0)return null;if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`Cannot hash non-finite number: ${t}`);if(Number.isInteger(t)&&!Number.isSafeInteger(t))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${t}. Cross-language cid parity is not guaranteed for unsafe integers.`);return t}if(typeof t=="string"||typeof t=="boolean"||t===null)return t;if(Array.isArray(t))return t.map(Xn);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=Xn(t[n]);return e}return null}function Ni(t){let e=Ri.encode(t),n=e.length,r=n*8,o=n+9+63&-64,s=new Uint8Array(o);s.set(e),s[n]=128;let a=new DataView(s.buffer);a.setUint32(o-4,r>>>0,!1),a.setUint32(o-8,Math.floor(r/4294967296)>>>0,!1);let i=1779033703,d=3144134277,u=1013904242,c=2773480762,l=1359893119,p=2600822924,f=528734635,m=1541459225,h=new Uint32Array(64),g=(v,b)=>v>>>b|v<<32-b;for(let v=0;v<o;v+=64){for(let M=0;M<16;M++)h[M]=a.getUint32(v+M*4,!1);for(let M=16;M<64;M++){let A=h[M-15],R=h[M-2],O=g(A,7)^g(A,18)^A>>>3,I=g(R,17)^g(R,19)^R>>>10;h[M]=h[M-16]+O+h[M-7]+I>>>0}let b=i,w=d,k=u,S=c,T=l,x=p,N=f,_=m;for(let M=0;M<64;M++){let A=g(T,6)^g(T,11)^g(T,25),R=T&x^~T&N,O=_+A+R+xi[M]+h[M]>>>0,I=g(b,2)^g(b,13)^g(b,22),K=b&w^b&k^w&k,q=I+K>>>0;_=N,N=x,x=T,T=S+O>>>0,S=k,k=w,w=b,b=O+q>>>0}i=i+b>>>0,d=d+w>>>0,u=u+k>>>0,c=c+S>>>0,l=l+T>>>0,p=p+x>>>0,f=f+N>>>0,m=m+_>>>0}let y=v=>v.toString(16).padStart(8,"0");return y(i)+y(d)+y(u)+y(c)+y(l)+y(p)+y(f)+y(m)}function Zn(t){let e=Xn(t??null),n=JSON.stringify(e);return Ni(n).slice(0,16)}function Si(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),n=e()+e()+e()+e();return`${n.slice(0,8)}-${n.slice(8,12)}-4${n.slice(13,16)}-${(parseInt(n.slice(16,17),16)&3|8).toString(16)}${n.slice(17,20)}-${n.slice(20,32)}`}function er(t,e,n){let r=n?.id??Si();if(t===0)return{id:r,version:0};let s=(n?.hash??Zn)(e);return{id:r,version:0,cid:s,prev:null}}function ko(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}var xi,Ri,xo=re(()=>{"use strict";xi=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]),Ri=new TextEncoder});function So(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function tr(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function nn(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function ne(t,e,n){let r=_o(t)?t:[],o=typeof t=="function"?t:typeof e=="function"?e:void 0,s={};return _o(t)?s=(nr(e)?e:n)??{}:nr(t)?s=t:s=(nr(e)?e:n)??{},new me(r,o,s)}var Ro,No,_i,Mi,yt,me,_o,nr,ke=re(()=>{"use strict";Wn();Ht();Oe();ye();To();ht();ie();xo();Ro=()=>{},No=100;_i=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},Mi=(t,e,n,r)=>{let o=t;if(o._status==="completed"||o._status==="errored")return;let s=o._cached,a=s===void 0?[Xt]:[Xt,[D,s]];o._status==="dirty"&&a.push(rt),Yt(e,a,o._config.tierOf)},yt=new tn({onMessage:_i,onSubscribe:Mi});bo(yt);fo(yt);me=class t{_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,n,r){this._config=r.config??yt,this._config.onMessage,this._optsName=r.name,this._describeKind=r.describeKind,this._equals=r.equals??Object.is,this._resubscribable=r.resubscribable??!1,this._resetOnTeardown=r.resetOnTeardown??!1,this._autoComplete=r.completeWhenDepsComplete??!0,this._autoError=r.errorWhenDepsError??!0,this._pausable=r.pausable??!0,this._guard=r.guard,this._fn=n,this._partial=r.partial??!1,this._cached=r.initial!==void 0?r.initial:void 0,this._status=e.length===0&&n==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=r.versioningHash??this._config.defaultHashFn??Zn;let o=r.versioning??this._config.defaultVersioning;this._versioningLevel=o,this._versioning=o!=null?er(o,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(So);let s={};for(let[i,d]of Object.entries(r.meta??{})){let u={initial:d,name:`${r.name??"node"}:meta:${i}`,describeKind:"state",config:this._config};r.guard!=null&&(u.guard=r.guard),r.resubscribable===!0&&(u.resubscribable=!0),s[i]=new t([],void 0,u)}Object.freeze(s),this.meta=s,this._hasMeta=Object.keys(s).length>0;let a=this;this._actions={emit(i){a._emit([[D,i]])},down(i){a._emit(nn(i))},up(i){a._emitUp(nn(i))}},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,n){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 r=this._versioningLevel;if(r!=null&&e<=r)return;let o=n?.hash??this._hashFn;o!==this._hashFn&&(this._hashFn=o);let s=this._cached===void 0?void 0:this._cached,a=this._versioning,i=a?.id??n?.id,d=a?.version??0,u=er(e,s,{id:i,hash:o});u.version=d,this._versioning=u,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 n=Wt(e);if(this._guard!=null&&!this._guard(n,"observe"))return!1;if(this._extraGuards!=null){for(let r of this._extraGuards)if(!r(n,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let n=this._guard!=null||this._extraGuards!=null,r=e?.actor!=null;if(!n&&!r)return;let o=Wt(e?.actor),s=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(o,s))throw new Ie({actor:o,action:s,nodeName:this.name});if(this._extraGuards!=null){for(let a of this._extraGuards)if(!a(o,s))throw new Ie({actor:o,action:s,nodeName:this.name})}this._lastMutation={actor:o,timestamp_ns:ce()}}down(e,n){let r=nn(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[D,e]])}up(e,n){if(this._deps.length===0)return;let r=nn(e);if(r.length===0)return;this._checkGuard(n);let o=n??{internal:!0};this._validateUpTiers(r);for(let s of this._deps)s.node.up?.(r,o)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let n of this._deps)n.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let n=this._config.tierOf;for(let r of e){let o=n(r[0]);if(o===3||o===4)throw new Error(`Node "${this.name}": tier-${o} 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,n){if(n!=null&&this._guard!=null){let d=Wt(n);if(!this._guard(d,"observe"))throw new Ie({actor:d,action:"observe",nodeName:this.name})}let o=this._isTerminal&&this._resubscribable;if(o){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)tr(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 s;try{s=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:o},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 s=="function")try{s()}catch{}throw d}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let i=!1;return()=>{i||(i=!0,this._sinkCount-=1,this._removeSink(e),typeof s=="function"&&s(),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[n]=this._sinks;this._sinks=n}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,n=0;try{for(let r=0;r<e;r++){let o=r,s=this._deps[r];s.unsub=Ro,s.unsub=s.node.subscribe(a=>{if(s.unsub===null)return;let i=this._config.tierOf,d=!1;for(let u of a)i(u[0])>=3&&(d=!0),this._config.onMessage(this,u,{direction:"down-in",depIndex:o},this._actions);d&&this._maybeRunFnOnSettlement()}),n++}}catch(r){this._deps[n].unsub=null;for(let o=0;o<n;o++){let s=this._deps[o];if(s.unsub!=null){let a=s.unsub;s.unsub=null;try{a()}catch{}tr(s)}}throw this._dirtyDepCount=0,r}}_addDep(e){for(let o=0;o<this._deps.length;o++)if(this._deps[o].node===e)return o;let n=this._deps.length,r=So(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Zt),r.unsub=Ro;try{r.unsub=e.subscribe(o=>{if(r.unsub===null)return;let s=this._config.tierOf,a=!1;for(let i of o)s(i[0])>=3&&(a=!0),this._config.onMessage(this,i,{direction:"down-in",depIndex:n},this._actions);a&&this._maybeRunFnOnSettlement()})}catch(o){throw r.unsub=null,this._deps.pop(),this._dirtyDepCount--,o}return n}_deactivate(e=!1){let n=this._cleanup;if(this._cleanup=void 0,typeof n=="function")try{n()}catch(r){this._emit([[P,this._wrapFnError("cleanup threw",r)]])}else if(n!=null&&typeof n=="object"){let r=n.deactivate;if(typeof r=="function")try{r()}catch(o){this._emit([[P,this._wrapFnError("cleanup.deactivate threw",o)]])}}for(let r of this._deps){if(r.unsub!=null){let o=r.unsub;r.unsub=null;try{o()}catch{}}tr(r)}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,n){let r=this._deps[e],o=n[0];if(this._inspectorHooks!=null){let s={kind:"dep_message",depIndex:e,message:n};for(let a of this._inspectorHooks)a(s)}if(o!==Ke){if(o===X){this._depDirtied(r);return}if(o===Le){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(Jn);return}if(o===Se||o===De){this._emit([n]);return}if(o===le){this._emit(en);return}if(o===D)this._depSettledAsData(r,n[1]);else if(o===U)this._depSettledAsResolved(r);else if(o===$)this._depSettledAsTerminal(r,!0);else if(o===P)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(o===D||o===U)&&this._emit([n]),(o===$||o===P)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Zt))}_depSettledAsData(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(n),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=n,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 n=this._deps[e];if(n.dataBatch.length===0&&n.prevData===void 0&&n.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(Hn),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(n=>n.terminal!==void 0&&n.terminal!==!0);if(e!=null){this._autoError&&this._emit([[P,e.terminal]]);return}this._autoComplete&&this._deps.every(n=>n.terminal!==void 0)&&this._emit(Yn)}_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([[P,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(i){this._emit([[P,this._wrapFnError("cleanup.beforeRun threw",i)]]);return}}}let n=this._deps.map(a=>a.involvedThisWave?a.dataBatch.length>0?[...a.dataBatch]:[]:void 0),r=this._deps.map(a=>a.prevData);for(let a=0;a<this._deps.length;a++){let i=n[a];i!=null&&i.length>0&&(this._deps[a].prevData=i[i.length-1])}let o=this._deps.map(a=>a.terminal),s={prevData:r,terminalDeps:o,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let a={kind:"run",batchData:n,prevData:r};for(let i of this._inspectorHooks)i(a)}this._isExecutingFn=!0;try{let a=this._fn(n,this._actions,s);if(typeof a=="function")this._cleanup=a;else if(a!=null&&typeof a=="object"){let i=a;(typeof i.beforeRun=="function"||typeof i.deactivate=="function"||typeof i.invalidate=="function")&&(this._cleanup=a)}}catch(a){this._emit([[P,this._wrapFnError("fn threw",a)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>No?(this._rerunDepth=0,this._emit([[P,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${No} \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,n){let r=n instanceof Error?n.message:String(n);return new Error(`Node "${this.name}": ${e}: ${r}`,{cause:n})}_frameBatch(e){let n=this._config.tierOf;if(e.length===1)return n(e[0][0])===3&&this._status!=="dirty"?[rt,e[0]]:e;let r=!0,o=!1,s=!1,a=-1;for(let d of e){let u=n(d[0]);u<a&&(r=!1),u===3&&(o=!0),d[0]===X&&(s=!0),a=u}let i=e;if(!r){let d=e.map((u,c)=>({m:u,i:c,tier:n(u[0])}));d.sort((u,c)=>u.tier-c.tier||u.i-c.i),i=d.map(u=>u.m)}if(o&&!s&&this._status!=="dirty"){let d=0;for(;d<i.length&&n(i[d][0])===0;)d++;return d===0?[rt,...i]:[...i.slice(0,d),rt,...i.slice(d)]}return i}_emit(e){if(e.length===0)return;for(let i=0;i<e.length;i++){let d=e[i];if(d[0]===P&&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 n=e;if(this._isTerminal&&!this._resubscribable){let i=e.filter(d=>d[0]===le||d[0]===Le);if(i.length===0)return;n=i}n=this._frameBatch(n);let o=null;for(let i=0;i<n.length;i++){let d=n[i],u=d[0];if(u!==Se&&u!==De){o?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${u===Se?"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 l=d[1];if(u===Se)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(l),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(l))c=!1;else if(this._pauseLocks.delete(l),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?o?.push(d):o==null&&(o=n.slice(0,i))}if(o!=null){if(o.length===0)return;n=o}if(this._hasMeta&&n.some(i=>i[0]===le))for(let i of Object.keys(this.meta))try{this.meta[i]._emit(en)}catch{}let{finalMessages:s,equalsError:a}=this._updateState(n);if(s.length>0&&this._config.inspectorEnabled){let i=this._config.globalInspector;if(i!=null)try{i({kind:"emit",node:this,messages:s})}catch{}}if(s.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let i=this._config.tierOf,d=[];for(let u of s)i(u[0])===3?this._pauseBuffer.push(u):d.push(u);d.length>0&&this._dispatchOrAccumulate(d)}else this._dispatchOrAccumulate(s);a!=null&&this._emit([[P,a]])}_updateState(e){let n=this._config.tierOf,r,o,s=-1,a=0;for(let c of e)n(c[0])===3&&a++;let i=a<=1,d=-1;if(this._versioning!=null&&a>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===D){d=c;break}}for(let c=0;c<e.length;c++){let l=e[c],p=l[0];if(p===D){if(l.length>=2){let f=!1;if(i&&this._cached!==void 0)try{f=this._equals(this._cached,l[1])}catch(m){o=this._wrapFnError("equals threw",m),s=c;break}if(f){r==null&&(r=e.slice(0,c)),r.push(Qt),this._status="resolved";continue}this._cached=l[1],this._versioning!=null&&(d<0||c===d)&&ko(this._versioning,l[1],this._hashFn)}this._status="settled",r?.push(l)}else if(r?.push(l),p===X)this._status="dirty";else if(p===U)this._status="resolved";else if(p===$){this._status="completed";{let f=this._config.rigorRecorder;if(f!=null)try{f.onTerminalTransition(this,"completed",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===P){this._status="errored";{let f=this._config.rigorRecorder;if(f!=null)try{f.onTerminalTransition(this,"errored",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===Le){if(this._cached!==void 0){let m=this._config.rigorRecorder;if(m!=null)try{m.onNonVacuousInvalidate(this,this._cached)}catch{}}this._cached=void 0,this._status="dirty";let f=this._cleanup;if(typeof f=="function"){this._cleanup=void 0;try{f()}catch{}}else if(f!=null&&typeof f=="object"){let m=f.invalidate;if(typeof m=="function")try{m()}catch{}}}else p===le&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let u=s>=0?r??e.slice(0,s):r??e;return o!=null?{finalMessages:u,equalsError:o}:{finalMessages:u}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let n=[...this._sinks];for(let r of n)r(e)};_dispatchOrAccumulate(e){if(mo()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],gt(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}Yt(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let n=this._frameBatch(e);Yt(this._deliverToSinks,n,this._config.tierOf)}},_o=t=>Array.isArray(t),nr=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function F(t,e){return ne([],{...e,initial:t})}function se(t,e){return ne((r,o,s)=>t(o,s)??void 0,{describeKind:"producer",...e})}function C(t,e,n){return ne(t,(o,s,a)=>{let i=o.map((d,u)=>d!=null&&d.length>0?d.at(-1):a.prevData[u]);s.emit(e(i,a))},{describeKind:"derived",...n})}function ve(t,e,n){return ne(t,(o,s,a)=>{let i=o.map((d,u)=>d!=null&&d.length>0?d.at(-1):a.prevData[u]);return e(i,s,a)??void 0},{describeKind:"effect",...n})}var Q=re(()=>{"use strict";ke()});var Lo={};Un(Lo,{NS_PER_MS:()=>He,NS_PER_SEC:()=>je,constant:()=>Mo,decorrelatedJitter:()=>Co,exponential:()=>Eo,fibonacci:()=>Ao,linear:()=>Oo,resolveBackoffPreset:()=>or,withMaxAttempts:()=>Ci});function ot(t){return t<0?0:t}function Ei(t,e){return e==="none"?t:e==="full"?Math.random()*t:t/2+Math.random()*(t/2)}function Ai(t,e){return t+Math.random()*(e-t)}function Mo(t){let e=ot(t);return()=>e}function Oo(t,e){let n=ot(t),r=e===void 0?n:ot(e);return o=>n+r*Math.max(0,o)}function Eo(t){let e=ot(t?.baseNs??1e8),n=t?.factor!==void 0&&t.factor<1?1:t?.factor??2,r=ot(t?.maxDelayNs??30*1e9),o=t?.jitter??"none";return s=>{let a;if(e===0)a=0;else if(n===1)a=e;else{let i=r/e,d=1;for(let u=0;u<Math.max(0,s);u++){if(d>=i){d=i;break}d*=n}a=e*d,a>r&&(a=r)}return Ei(a,o)}}function Ao(t=100*1e6,e=30*1e9){let n=ot(t),r=ot(e);function o(s){if(s<=0)return 1;let a=1,i=2;for(let d=1;d<s;d++){let u=a+i;a=i,i=u}return i}return s=>{let a=o(s)*n;return a<=r?a:r}}function Co(t=100*1e6,e=30*1e9){return(n,r,o)=>{let a=Math.min(e,(o??t)*3);return Ai(t,a)}}function Ci(t,e){return(n,r,o)=>n>=e?null:t(n,r,o)}function or(t){if(t==="constant")return Mo(1*1e9);if(t==="linear")return Oo(1*1e9);if(t==="exponential")return Eo();if(t==="fibonacci")return Ao();if(t==="decorrelatedJitter")return Co();throw new Error(`Unknown backoff preset: "${String(t)}". Use one of: constant, linear, exponential, fibonacci, decorrelatedJitter`)}var He,je,sr=re(()=>{"use strict";He=1e6,je=1e9});function ar(t,e){if(e!=null&&e.length>0)return new Set(e);switch(t){case"standard":return new Set(["type","status","value","deps","meta","v"]);case"full":return null;case"spec":return new Set(["type","deps","meta","value"]);default:return new Set(["type","deps"])}}function Li(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function Je(t){let e=new WeakSet,n={};for(let[r,o]of Do(t))n[r]=ir(o,e);return n}function ir(t,e){if(t==null)return t;let n=typeof t;if(n==="boolean"||n==="number"||n==="string")return t;if(n==="function")return"<function>";if(Array.isArray(t))return e.has(t)?"<cycle>":(e.add(t),t.map(r=>ir(r,e)));if(n==="object"){let r=t;if(e.has(r))return"<cycle>";e.add(r);try{if(typeof r.subscribe=="function"&&"cache"in r)return"<Node>"}catch{return"<unserializable>"}let o={};for(let[s,a]of Do(r))o[s]=ir(a,e);return o}return"<unserializable>"}function Do(t){let e=[],n;try{n=Object.keys(t)}catch{return e}for(let r of n)try{e.push([r,t[r]])}catch{e.push([r,"<unserializable>"])}return e}function pe(t,e){let n={factory:t};return e!==void 0&&(n.factoryArgs=e),n}function Di(t){let e={};for(let[n,r]of Object.entries(t.meta))try{e[n]=r.cache}catch{}return e}function dr(t,e,n){let r=e==null,o=!r&&e!=null?[...e].filter(c=>c.startsWith("meta.")).map(c=>c.slice(5)):null,s=r||e.has("meta")||o!=null&&o.length>0,a="state",i=[];t instanceof me&&(a=Li(t),i=t._deps.map(c=>c.node.name??""));let d={type:a,deps:i};(r||e.has("status"))&&(d.status=t.status);let u=t instanceof me?t._guard:void 0;if(s){let c={...Di(t)};if(u!=null&&c.access===void 0&&(c.access=Qn(u)),o!=null&&o.length>0&&!e.has("meta")){let l={};for(let p of o)p in c&&(l[p]=c[p]);d.meta=l}else d.meta=c}if(t.name!=null&&(d.name=t.name),(r||e.has("value"))&&(!n||a==="state")){t.status==="sentinel"&&(d.sentinel=!0);try{d.value=t.cache}catch{}}if((r||e.has("v"))&&t.v!=null){let c={id:t.v.id,version:t.v.version};"cid"in t.v&&(c.cid=t.v.cid,c.prev=t.v.prev),d.v=c}return(r||e.has("guard"))&&u!=null&&(d.guard=Qn(u)),(r||e.has("lastMutation"))&&t.lastMutation!=null&&(d.lastMutation=t.lastMutation),d}var Ee=re(()=>{"use strict";ht();ke()});function ue(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}var Ye=re(()=>{"use strict"});function Ct(t,e,n){if(e.length===0)throw new RangeError("budgetGate requires at least one constraint");let r=e.map(f=>f.node),o=[t,...r],s=new ur,a=!1,i=!1,d=Symbol("budget-gate"),u=new Array(e.length);function c(){return e.every((f,m)=>f.check(u[m]))}function l(f){for(;s.size>0&&c();){let m=s.shift();f.emit(m)}s.size===0&&i&&(i=!1,f.down([[U]]))}return ne([],(f,m)=>{for(let g=0;g<e.length;g++)u[g]=e[g].node.cache;let h=[];for(let g=0;g<o.length;g++){let y=o[g];h.push(y.subscribe(v=>{for(let b of v)p(b,g,m)}))}return()=>{for(let g of h)g()}},{...n,describeKind:"derived",meta:ue("resilience","budget_gate",n?.meta)});function p(f,m,h){let g=f[0];if(m===0){if(g===D)return c()&&s.size===0?h.emit(f[1]):(s.push(f[1]),a||(a=!0,h.up([[Se,d]]))),!0;if(g===X)return h.down([[X]]),!0;if(g===U)return s.size===0?h.down([[U]]):i=!0,!0;if(g===$||g===P){for(;s.size>0;)h.emit(s.shift());return i=!1,a&&(a=!1,h.up([[De,d]])),h.down([f]),!0}return!1}if(g===D&&(u[m-1]=f[1]),g===D||g===U){let y=c();return y&&s.size>0?(l(h),s.size===0&&a&&(a=!1,h.up([[De,d]]))):!y&&!a&&s.size>0&&(a=!0,h.up([[Se,d]])),!0}return g===X?!0:g===P?(h.down([f]),!0):g===$}}var ur,Io=re(()=>{"use strict";ie();ke();Ye();ur=class{buf=[];head=0;get size(){return this.buf.length-this.head}push(e){this.buf.push(e)}shift(){if(this.head>=this.buf.length)return;let e=this.buf[this.head];return this.buf[this.head]=void 0,this.head++,this.head>32&&this.head*2>this.buf.length&&(this.buf=this.buf.slice(this.head),this.head=0),e}clear(){this.buf=[],this.head=0}}});function Po(t){let e=new WeakSet,n=new WeakSet,r=[t],o=0;for(;r.length>0;){let s=r.pop();o+=Pi(s,e,n,r)}return o}function Pi(t,e,n,r){if(t==null)return 0;switch(typeof t){case"number":return be.number;case"boolean":return be.boolean;case"string":return be.string+t.length*2;case"bigint":return be.bigint+Gi(t);case"symbol":return be.symbol;case"function":return e.has(t)?0:(e.add(t),be.function);case"undefined":return 0}let s=t;if(e.has(s))return 0;e.add(s);let a=s[Ii];if(typeof a=="function")try{let u=a.call(s);if(typeof u=="number"&&Number.isFinite(u))return u}catch{}if(s instanceof Date)return be.date;if(s instanceof RegExp)return be.regexp+s.source.length*2;if(s instanceof Error){let u=s.message?s.message.length*2:0,c=s.stack?s.stack.length*2:0;return be.error+u+c}if(typeof URL<"u"&&s instanceof URL)return be.url+s.href.length*2;if(typeof Promise<"u"&&s instanceof Promise)return be.promise;if(s instanceof WeakMap)return be.weakmap;if(s instanceof WeakSet)return be.weakset;if(s instanceof Map){let u=be.map;for(let[c,l]of s)u+=be.mapEntry,r.push(c),r.push(l);return u}if(s instanceof Set){let u=be.set;for(let c of s)u+=be.setEntry,r.push(c);return u}if(Array.isArray(s)){let u=be.array+s.length*8;for(let c of s)r.push(c);return u}if(s instanceof ArrayBuffer)return n.has(s)?0:(n.add(s),s.byteLength);if(ArrayBuffer.isView(s)){let u=s;return n.has(u.buffer)?48:(n.add(u.buffer),u.buffer.byteLength+48)}let i=be.object,d=Object.keys(s);for(let u of d){i+=be.string+u.length*2;try{r.push(s[u])}catch{}}return i}function Gi(t){let e=t<0n?-t:t;if(e===0n)return 0;let n=e.toString(2).length;return Math.ceil(n/32)*8}var be,Ii,Go=re(()=>{"use strict";be={object:56,array:64,string:40,number:8,boolean:4,null:0,undefined:0,symbol:40,bigint:16,function:120,map:72,set:72,mapEntry:40,setEntry:24,date:24,regexp:48,error:64,url:80,promise:48,weakmap:40,weakset:40},Ii=Symbol.for("sizeof")});function Fo(t,e,n,r={}){let o=e in t.nodes,s=n in t.nodes;if(!o)return rn(e,n,"no-such-from");if(!s)return rn(e,n,"no-such-to");let a=r.maxDepth;if(a!=null&&(!Number.isInteger(a)||a<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===n){if(r.findCycle===!0){let u=Fi(t,e,r);if(u!=null)return u}let d=on(e,t.nodes[e],0,r);return sn(e,n,[d])}if(a===0)return rn(e,n,"no-path");let i=$o(t,e,n,a);return i.found?sn(e,n,jo(t,i.pathOrder,r)):rn(e,n,i.truncated?"max-depth-exceeded":"no-path")}function $o(t,e,n,r){let o=new Map,s=[{path:n,depth:0}],a=new Set([n]),i=0,d=!1;for(;i<s.length;){let l=s[i++];if(l.path===e)break;if(r!=null&&l.depth>=r){let h=t.nodes[l.path];h?.deps&&h.deps.length>0&&(d=!0);continue}let p=t.nodes[l.path];if(p==null)continue;let f=p.deps??[],m=new Map;for(let h=0;h<f.length;h++){let g=f[h];if(!g)continue;let y=m.get(g);y==null&&(y=[],m.set(g,y)),y.push(h)}for(let[h,g]of m)a.has(h)||(a.add(h),o.set(h,{from:l.path,depIndices:g}),s.push({path:h,depth:l.depth+1}))}if(!o.has(e))return{found:!1,pathOrder:[],truncated:d};let u=[{path:e}],c=e;for(;c!==n;){let l=o.get(c);if(l==null)return{found:!1,pathOrder:[],truncated:!1};u[u.length-1].depIndices=l.depIndices,u.push({path:l.from}),c=l.from}return{found:!0,pathOrder:u,truncated:!1}}function Fi(t,e,n){let r=t.nodes[e];if(r==null)return null;let o=r.deps??[],s=[];for(let i=0;i<o.length;i++)o[i]===e&&s.push(i);if(s.length>0){let i=on(e,r,0,n);i.dep_index=s[0];let d=on(e,r,1,n);return sn(e,e,[i,d])}let a=null;for(let i=0;i<o.length;i++){let d=o[i];if(!d||d===e)continue;let u=$o(t,d,e,n.maxDepth);u.found&&(a==null||u.pathOrder.length<a.pathOrder.length)&&(a=u,a={found:!0,pathOrder:[{path:e,depIndices:[i]},...u.pathOrder],truncated:!1})}return a==null?null:sn(e,e,jo(t,a.pathOrder,n))}function jo(t,e,n){return e.map((r,o)=>{let s=t.nodes[r.path],a=on(r.path,s,o,n);return r.depIndices!=null&&r.depIndices.length>0&&(a.dep_index=r.depIndices[0],r.depIndices.length>1&&(a.dep_indices=[...r.depIndices])),a})}function on(t,e,n,r){let o={path:t,type:e.type,hop:n};e.status!==void 0&&(o.status=e.status),"value"in e&&(o.value=e.value),e.v!=null&&(o.v=e.v);let s=r.annotations?.get(t)??e.annotation;s!=null&&(o.annotation=s);let a=r.lastMutations?.get(t)??e.lastMutation;return a!=null&&(o.lastMutation=a),o}function sn(t,e,n){return Bo(t,e,!0,"ok",n)}function rn(t,e,n){return Bo(t,e,!1,n,[])}function Bo(t,e,n,r,o){let s=$i(t,e,n,r,o);return{from:t,to:e,found:n,reason:r,steps:o,text:s,toJSON(){return{from:t,to:e,found:n,reason:r,steps:o}}}}function $i(t,e,n,r,o){if(!n)switch(r){case"no-such-from":return`explainPath: no node named "${t}"`;case"no-such-to":return`explainPath: no node named "${e}"`;case"max-depth-exceeded":return`explainPath: no path from "${t}" to "${e}" within maxDepth`;default:return`explainPath: no path from "${t}" to "${e}"`}let s=[`Causal path: ${t} \u2192 ${e} (${o.length} step(s))`];for(let a of o){let d=` ${a.hop===0?"\xB7":"\u2193"} ${a.path} (${a.type}${a.status?`/${a.status}`:""})`;if(s.push(d),"value"in a&&s.push(` value: ${ji(a.value)}`),a.annotation!=null&&s.push(` annotation: ${a.annotation}`),a.lastMutation!=null){let u=a.lastMutation.actor;s.push(` actor: ${u.type}${u.id?`:${u.id}`:""}`)}}return s.join(`
2
+ `)}function ji(t){if(t===void 0)return"<sentinel>";if(t===null)return"null";if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return e.length>80?`${e.slice(0,77)}...`:e}catch{return String(t)}}var Vo=re(()=>{"use strict"});function cr(t,e){if(Object.is(t,e))return!0;if(t==null||e==null||typeof t!="object"||typeof e!="object")return!1;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(let s=0;s<t.length;s++)if(!cr(t[s],e[s]))return!1;return!0}if(Array.isArray(e))return!1;let n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;let o=new Set(r);for(let s of n)if(!o.has(s)||!cr(t[s],e[s]))return!1;return!0}function Ko(t,e){return`${t}\0${e}`}function lr(t,e){let n=[],r=new Set(t.subgraphs),o=new Set(e.subgraphs),s=[];for(let g of o)r.has(g)||s.push(g);s.sort();for(let g of s)n.push({type:"subgraph-mounted",path:g});let a=new Set(Object.keys(t.nodes)),i=new Set(Object.keys(e.nodes)),d=[];for(let g of i)a.has(g)||d.push(g);d.sort();for(let g of d)n.push({type:"node-added",path:g,node:{...e.nodes[g]}});let u=[];for(let g of i){if(!a.has(g))continue;let y=t.nodes[g]?.meta,v=e.nodes[g]?.meta;y==null&&v==null||cr(y??{},v??{})||u.push(g)}u.sort();for(let g of u)n.push({type:"node-meta-changed",path:g,prevMeta:t.nodes[g]?.meta??{},nextMeta:e.nodes[g]?.meta??{}});let c=new Map;for(let g of t.edges)c.set(Ko(g.from,g.to),g);let l=new Map;for(let g of e.edges)l.set(Ko(g.from,g.to),g);let p=[];for(let[g,y]of l)c.has(g)||p.push(y);p.sort((g,y)=>g.from<y.from?-1:g.from>y.from?1:g.to<y.to?-1:g.to>y.to?1:0);for(let g of p)n.push({type:"edge-added",from:g.from,to:g.to});let f=[];for(let[g,y]of c)l.has(g)||f.push(y);f.sort((g,y)=>g.from<y.from?-1:g.from>y.from?1:g.to<y.to?-1:g.to>y.to?1:0);for(let g of f)n.push({type:"edge-removed",from:g.from,to:g.to});let m=[];for(let g of a)i.has(g)||m.push(g);m.sort();for(let g of m)n.push({type:"node-removed",path:g});let h=[];for(let g of r)o.has(g)||h.push(g);h.sort();for(let g of h)n.push({type:"subgraph-unmounted",path:g});return{events:n,flushedAt_ns:z()}}var zo=re(()=>{"use strict";ye()});var ge,ze=re(()=>{"use strict";ge=class{_timer;_gen=0;start(e,n){this.cancel(),this._gen+=1;let r=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,r===this._gen&&n()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var st,pr=re(()=>{"use strict";st=class{constructor(e){this.capacity=e;if(!Number.isInteger(e)||e<=0)throw new Error(`RingBuffer capacity must be a positive integer (got ${e})`);this.buf=new Array(e)}buf;head=0;_size=0;get size(){return this._size}get maxSize(){return this.capacity}push(e){let n=(this.head+this._size)%this.capacity;this.buf[n]=e,this._size<this.capacity?this._size++:this.head=(this.head+1)%this.capacity}shift(){if(this._size===0)return;let e=this.buf[this.head];return this.buf[this.head]=void 0,this.head=(this.head+1)%this.capacity,this._size--,e}at(e){if(this._size===0)return;let n=e<0?this._size+e:e;if(!(n<0||n>=this._size))return this.buf[(this.head+n)%this.capacity]}toArray(){let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this.buf[(this.head+n)%this.capacity];return e}clear(){for(let e=0;e<this._size;e++)this.buf[(this.head+e)%this.capacity]=void 0;this.head=0,this._size=0}}});function Uo(t,e){let n=e?.topN??10,r=t.describe({detail:"standard"}),o=[],s=t._collectObserveTargets;typeof s=="function"&&s.call(t,"",o);let a=new Map;for(let[p,f]of o)a.set(p,f);let i=[];for(let[p,f]of Object.entries(r.nodes)){let m=a.get(p),h=m instanceof me?m:null,g=h?Po(h.cache):0,y=h?h._sinkCount:0,v=f.deps?.length??0,b=f.type==="effect"&&y===0,w=y===0?f.type==="effect"?"orphan-effect":f.type==="derived"?"idle-derived":f.type==="producer"?"idle-producer":null:null;i.push({path:p,type:f.type,status:f.status??"unknown",valueSizeBytes:g,subscriberCount:y,depCount:v,isOrphanEffect:b,orphanKind:w})}let d=i.reduce((p,f)=>p+f.valueSizeBytes,0),u=(p,f)=>[...i].sort(f??((m,h)=>h[p]-m[p])).slice(0,n),c=i.filter(p=>p.orphanKind!=null),l=i.filter(p=>p.isOrphanEffect);return{nodeCount:i.length,edgeCount:r.edges.length,subgraphCount:r.subgraphs.length,nodes:i,totalValueSizeBytes:d,hotspots:{byValueSize:u("valueSizeBytes"),bySubscriberCount:u("subscriberCount"),byDepCount:u("depCount")},orphans:c,orphanEffects:l}}var qo=re(()=>{"use strict";ke();Go()});function an(t,e){let n=Math.max(16,t.size*4),r=0;for(;t.size>0;){if(r++>=n){console.error(`[Graph "${e}".destroy] disposer drain exceeded cap (${n}); ${t.size} disposer(s) discarded`),t.clear();return}let o=t.values().next();if(o.done)return;let s=o.value;t.delete(s);try{s()}catch(a){console.error(`[Graph "${e}".destroy] disposer threw:`,a)}}}function Qo(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"&&typeof t.down=="function"}function Bi(t){if(t!=null)return Qo(t)?t.cache:t}function at(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"&&typeof t.down=="function"}function Qe(t){return at(t)?t.cache??"":t}function Wo(t){return at(t)?t.cache??0:t}function Ho(t){return at(t)?t.cache??!1:t}function Vi(t){let e=[];for(let n of Object.keys(t).sort()){let r=t[n].v;r!=null&&e.push(`${n} ${r.id} ${r.version}`)}return e.join(`
3
+ `)}function Jo(t){if(t.version!==it)throw new Error(`unsupported snapshot version ${String(t.version)} (expected ${it})`);for(let e of["name","nodes","edges","subgraphs"])if(!(e in t))throw new Error(`snapshot missing required key "${e}"`);if(typeof t.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof t.nodes!="object"||t.nodes===null||Array.isArray(t.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(t.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(t.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function Ki(t,e){let n=new WeakMap,r=(o,s)=>{if(Object.is(o,s))return!0;if(o==null||s==null||typeof o!="object"||typeof s!="object")return!1;let a=n.get(o);if(a==null&&(a=new WeakSet,n.set(o,a)),a.has(s))return!0;a.add(s);let i=o.constructor,d=s.constructor;if(i!==d)return!1;if(o instanceof Date)return o.getTime()===s.getTime();if(o instanceof RegExp)return o.source===s.source&&o.flags===s.flags;if(Array.isArray(o)){let p=s;if(o.length!==p.length)return!1;for(let f=0;f<o.length;f++)if(!r(o[f],p[f]))return!1;return!0}if(o instanceof Map){let p=s;if(o.size!==p.size)return!1;for(let[f,m]of o)if(!p.has(f)||!r(m,p.get(f)))return!1;return!0}if(o instanceof Set){let p=s;if(o.size!==p.size)return!1;for(let f of o){let m=!1;for(let h of p)if(r(f,h)){m=!0;break}if(!m)return!1}return!0}if(ArrayBuffer.isView(o)){let p=o,f=s;if(p.length!==f.length)return!1;for(let m=0;m<p.length;m++)if(p[m]!==f[m])return!1;return!0}let u=Object.keys(o),c=Object.keys(s);if(u.length!==c.length)return!1;let l=new Set(c);for(let p of u)if(!l.has(p)||!r(o[p],s[p]))return!1;return!0};return r(t,e)}function zi(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function dn(t){let e="^";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="*"){e+=".*";continue}if(r==="?"){e+=".";continue}if(r==="["){let o=t.indexOf("]",n+1);if(o<=n+1){e+="\\[";continue}let s=t.slice(n+1,o);s.startsWith("!")&&(s=`^${s.slice(1)}`),s=s.replace(/\\/g,"\\\\"),e+=`[${s}]`,n=o;continue}e+=zi(r)}return e+="$",new RegExp(e)}function fr(t){if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||t==null)return String(t);try{return JSON.stringify(t)}catch{return"[unserializable]"}}function Wi(t){return t==="none"?qi:t==="ansi"||t==null?Ui:{data:t.data??"",dirty:t.dirty??"",resolved:t.resolved??"",invalidate:t.invalidate??"",pause:t.pause??"",resume:t.resume??"",complete:t.complete??"",error:t.error??"",teardown:t.teardown??"",derived:t.derived??"",path:t.path??"",reset:t.reset??""}}function Yo(t){if(t==null)return{};let e=t.detail;return e==="full"?{...t,structured:t.structured??!0,timeline:t.timeline??!0,causal:t.causal??!0,derived:t.derived??!0}:e==="minimal"?{...t,structured:t.structured??!0}:t.format==="stage-log"?{...t,structured:t.structured??!0,timeline:t.timeline??!0}:t}function Hi(t,e,n){for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);if(o<32||o===127)throw new Error(`Graph "${e}": ${n} "${t}" must not contain control character (U+${o.toString(16).padStart(4,"0").toUpperCase()} at index ${r})`)}}function mr(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(fe))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${fe}' (path separator)`);if(t===Ae)throw new Error(`Graph "${e}": ${n} name "${Ae}" is reserved for meta companion paths`);Hi(t,e,n)}function Ji(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(fe);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function Yi(t,e){let n=!1;for(let o of t)if(!e.isMetaPassthrough(o[0])){n=!0;break}return n?t.filter(o=>e.isMetaPassthrough(o[0])):t}function Xo(t){for(let e of t._mounts.values())Xo(e);for(let e of t._nodes.values())try{e.down([[le]],{internal:!0})}catch{}}function Zo(t,e){let n=ae.diff(t,e),r={};for(let o of n.nodesAdded){let s=e.nodes[o];s!=null&&(r[o]=s)}return{...n,nodesAddedFull:r}}function gr(t,e,n,r={}){let o={paths:[],depths:new Map,truncated:!1};if(!e)return r.withDetail?o:[];if(!r.both&&n!=="upstream"&&n!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let s=r.maxDepth;if(s!=null&&(!Number.isInteger(s)||s<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(s===0)return r.withDetail?o:[];let a=new Map,i=new Map,d=new Map,u=new Map,c=new Set;for(let[b,w]of Object.entries(t.nodes)){if(!b)continue;c.add(b);let k=w.deps??[];a.set(b,k);for(let S of k)S&&(c.add(S),i.has(S)||i.set(S,new Set),i.get(S).add(b))}for(let b of t.edges){if(b==null||typeof b!="object")continue;let w=typeof b.from=="string"?b.from:"",k=typeof b.to=="string"?b.to:"";!w||!k||(c.add(w),c.add(k),u.has(w)||u.set(w,new Set),u.get(w).add(k),d.has(k)||d.set(k,new Set),d.get(k).add(w))}if(!c.has(e))return r.withDetail?o:[];let l=r.both===!0,p=b=>{if(l){let T=a.get(b)??[],x=d.get(b),N=i.get(b),_=u.get(b),M=[...T];return x&&M.push(...x),N&&M.push(...N),_&&M.push(..._),M}if(n==="upstream"){let T=a.get(b)??[],x=d.get(b);return x?[...T,...x]:T}let w=i.get(b),k=u.get(b),S=w?[...w]:[];return k&&S.push(...k),S},f=new Set([e]),m=new Map,h=[{path:e,depth:0}],g=0,y=!1;for(;g<h.length;){let b=h[g++];if(s!=null&&b.depth>=s){p(b.path).length>0&&(y=!0);continue}for(let w of p(b.path))!w||f.has(w)||(f.add(w),m.set(w,b.depth+1),h.push({path:w,depth:b.depth+1}))}let v=[...m.keys()].sort((b,w)=>b<w?-1:b>w?1:0);return r.withDetail?{paths:v,depths:m,truncated:y}:v}function Qi(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.path!==o.path||r.type!==o.type||r.status!==o.status||r.hop!==o.hop||r.dep_index!==o.dep_index||r.annotation!==o.annotation||r.value!==o.value||r.lastMutation!==o.lastMutation)return!1;let s=r.v,a=o.v;if(s!==a&&(s==null||a==null||s.id!==a.id||s.version!==a.version))return!1}return!0}var fe,Ae,it,Ui,qi,ae,Ue=re(()=>{"use strict";Ht();Oe();ye();ht();ie();Ee();ke();Q();zo();Z();ze();pr();Wn();Vo();qo();fe="::",Ae="__meta__",it=1;Ui={data:"\x1B[32m",dirty:"\x1B[33m",resolved:"\x1B[36m",invalidate:"\x1B[93m",pause:"\x1B[90m",resume:"\x1B[96m",complete:"\x1B[34m",error:"\x1B[31m",teardown:"\x1B[91m",derived:"\x1B[35m",path:"\x1B[90m",reset:"\x1B[0m"},qi={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};ae=class t{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_destroyed=!1;_topology;_topologyEmitters=new Set;_factory;_factoryArgs;constructor(e,n){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(fe))throw new Error(`Graph name must not contain '${fe}' (got "${e}")`);if(e===Ae)throw new Error(`Graph name "${Ae}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??yt,this._traceRing=new st(n?.traceCapacity??1e3),n?.versioning!=null&&this.setVersioning(n.versioning),typeof n?.factory=="string"&&(this._factory=n.factory,n.factoryArgs!==void 0&&(this._factoryArgs=n.factoryArgs))}tagFactory(e,n){return this._factory=e,this._factoryArgs=n,this}ancestors(e=!0){let n=[],r=e?this:this._parent;for(;r!=null;)n.push(r),r=r._parent;return n}get topology(){return this._topology==null&&(this._topology=se(e=>{let n=r=>{e.emit(r)};return this._topologyEmitters.add(n),()=>{this._topologyEmitters.delete(n)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let n of this._topologyEmitters)n(e)}nameOf(e){return this._nodeToName.get(e)}add(e,n){let r=e.name,o=n?.name??r;if(o==null||o==="")throw new Error(`Graph "${this.name}": graph.add requires a non-empty name \u2014 pass via opts.name or set it on the node (e.g. state(0, { name: "x" }))`);let s=o,a=n?.annotation;if(mr(s,this.name,"add"),this._mounts.has(s))throw new Error(`Graph "${this.name}": name "${s}" is already a mount point`);if(this._nodes.has(s))throw new Error(`Graph "${this.name}": node "${s}" already exists`);let i=this._nodeToName.get(e);if(i!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${i}"`);return this._nodes.set(s,e),this._nodeToName.set(e,s),this._emitTopology({kind:"added",name:s,nodeKind:"node"}),a!=null&&(this._annotations.set(s,a),this.config.inspectorEnabled&&this._traceRing.push({path:s,annotation:a,timestamp_ns:z()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof me&&n._applyVersioning(e)}remove(e){mr(e,this.name,"remove");let n=this._mounts.get(e);if(n){let s={kind:"mount",nodes:[],mounts:[]},a=[];n._collectObserveTargets("",a);for(let[i,d]of a)i.includes(`${fe}${Ae}${fe}`)||s.nodes.push(i);return s.nodes.sort(),s.mounts.push(e),s.mounts.push(...n._collectSubgraphs(`${e}${fe}`)),this._mounts.delete(e),n._parent=void 0,Xo(n),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:s}),s}let r=this._nodes.get(e);if(!r)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(r),r.down([[le]],{internal:!0});let o={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:o}),o}removeAll(e){let n=typeof e=="function"?e:(()=>{let s=dn(e);return a=>s.test(a)})(),r={kind:"mount",nodes:[],mounts:[]},o=[...this._nodes.keys(),...this._mounts.keys()].filter(s=>n(s));for(let s of o){let a=this.remove(s);r.nodes.push(...a.nodes),r.mounts.push(...a.mounts)}return r.nodes.sort(),r.mounts.sort(),r}[Symbol.iterator](){let e=[...this._nodes.keys()].sort(),n=this._nodes,r=0;return{[Symbol.iterator](){return this},next(){if(r>=e.length)return{value:void 0,done:!0};let o=e[r++];return{value:[o,n.get(o)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(fe))return this.resolve(e);let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return n}get(e){return this.node(e).cache}set(e,n,r){let o=r?.internal===!0;this.node(e).down([[D,n]],{actor:r?.actor,internal:o,delivery:"write"})}setAll(e,n){let r=Symbol.iterator in e?e:Object.entries(e);te(()=>{for(let[o,s]of r)this.set(o,s,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[Le]],{actor:n?.actor,internal:r,delivery:"write"})}error(e,n,r){let o=r?.internal===!0;this.node(e).down([[P,n]],{actor:r?.actor,internal:o,delivery:"write"})}complete(e,n){let r=n?.internal===!0;this.node(e).down([[$]],{actor:n?.actor,internal:r,delivery:"write"})}_registerSelfPruningKeepalive(e){let n,r,o=()=>{n?.(),n=void 0,r?.(),r=void 0};n=e.subscribe(s=>{for(let a of s){let i=a[0];if(i===le||i===$||i===P){o();return}}}),r=this.addDisposer(o)}_wireSignalToRemove(e,n){if(n==null)return;let r=()=>{try{this.remove(e)}catch{}};if(n.aborted){r();return}n.addEventListener("abort",r,{once:!0}),this.addDisposer(()=>n.removeEventListener("abort",r))}derived(e,n,r,o){let s=n.map(f=>this.resolve(f)),{keepAlive:a,annotation:i,equals:d,initial:u,meta:c,signal:l}=o??{},p=C(s,r,{name:e,...d!=null?{equals:d}:{},...u!==void 0?{initial:u}:{},...c!=null?{meta:c}:{}});return this.add(p,{name:e,...i!=null?{annotation:i}:{}}),a===!0&&this._registerSelfPruningKeepalive(p),this._wireSignalToRemove(e,l),p}effect(e,n,r,o){let s=n.map(c=>this.resolve(c)),{annotation:a,meta:i,signal:d}=o??{},u=ve(s,r,{name:e,...i!=null?{meta:i}:{}});return this.add(u,{name:e,...a!=null?{annotation:a}:{}}),this._wireSignalToRemove(e,d),u}produce(e,n,r){if(n===void 0)throw new Error(`Graph "${this.name}".produce("${e}", \u2026): source must not be \`undefined\` \u2014 undefined is the global SENTINEL (spec \xA71.1). Pass \`null\` for nullary DATA, or a Promise/AsyncIterable/Iterable for async sources.`);if(n!==null&&typeof n=="object"&&"cache"in n&&typeof n.subscribe=="function")throw new Error(`Graph "${this.name}".produce("${e}", \u2026): Node sources are rejected. For Node\u2192Node, use graph.derived(name, [path], ([v]) => v, { keepAlive: true }) \u2014 fromAny passes Nodes through verbatim and silently drops opts.`);let{annotation:o,meta:s,equals:a,signal:i}=r??{},d=j(n,{name:e,...s!=null?{meta:s}:{},...a!=null?{equals:a}:{},...i!=null?{signal:i}:{}});return this.add(d,{name:e,...o!=null?{annotation:o}:{}}),this._wireSignalToRemove(e,i),d}batch(e){te(e)}edges(e){let n=e?.recursive===!0,r=new Map;if(!n){for(let[d,u]of this._nodes)r.set(u,d);let i=[];for(let[d,u]of this._nodes)if(u instanceof me)for(let c of u._deps){let l=r.get(c.node);l!=null&&i.push([l,d])}return i.sort((d,u)=>d[0]<u[0]?-1:d[0]>u[0]?1:d[1]<u[1]?-1:d[1]>u[1]?1:0),i}let o=[];this._collectObserveTargets("",o);let s=new Map;for(let[i,d]of o)s.set(d,i);let a=[];for(let[i,d]of o)if(d instanceof me)for(let u of d._deps){let c=s.get(u.node);c!=null&&a.push([c,i])}return a.sort((i,d)=>i[0]<d[0]?-1:i[0]>d[0]?1:i[1]<d[1]?-1:i[1]>d[1]?1:0),a}mount(e,n){if(n===void 0){let o=new t(e);return this.mount(e,o)}if(typeof n=="function"){let o=new t(e);return n(o),this.mount(e,o)}let r=n;if(mr(e,this.name,"mount"),this._nodes.has(e))throw new Error(`Graph "${this.name}": cannot mount at "${e}" \u2014 node with that name exists`);if(this._mounts.has(e))throw new Error(`Graph "${this.name}": mount "${e}" already exists`);if(r===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(r._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${r._parent.name}"`);for(let o=this;o!=null;o=o._parent)if(o===r)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,r),r._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),r}resolve(e){let n=Ji(e,this.name);return this._resolveFromSegments(n)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let n=e;if(n[0]===this.name&&(n=n.slice(1),n.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let r=n[0],o=n.slice(1);if(o.length===0){let i=this._nodes.get(r);if(i)return i;throw this._mounts.has(r)?new Error(`Graph "${this.name}": path ends at subgraph "${r}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${r}"`)}let s=this._nodes.get(r);if(s&&o.length>0&&o[0]===Ae)return this._resolveMetaChainFromNode(s,o,n.join(fe));let a=this._mounts.get(r);if(!a)throw this._nodes.has(r)?new Error(`Graph "${this.name}": "${r}" is a node; trailing path "${o.join(fe)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return a.resolve(o.join(fe))}_resolveMetaChainFromNode(e,n,r){let o=e,s=0,a=[...n];for(;s<a.length;){if(a[s]!==Ae)throw new Error(`Graph "${this.name}": expected ${Ae} segment in meta path "${r}"`);if(s+1>=a.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${Ae} in "${r}"`);let i=a[s+1],d=o.meta[i];if(!d)throw new Error(`Graph "${this.name}": unknown meta "${i}" in path "${r}"`);o=d,s+=2}return o}signal(e,n){if(n?.internal!==!0){for(let o of e)if(this.config.messageTier(o[0])===3)throw new Error(`Graph "${this.name}": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). For per-node value writes, use Graph.set or graph.node(name).down(...).`)}let r=[];if(this._signalDeliver(e,n??{},new Set,r),r.length>0)throw r[0]}_signalDeliver(e,n,r,o){for(let d of this._mounts.values())d._signalDeliver(e,n,r,o);let a=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},i=Yi(e,this.config);for(let d of[...this._nodes.keys()].sort()){let u=this._nodes.get(d);if(!r.has(u)){r.add(u);try{u.down(e,a)}catch(c){if(c instanceof Ie)throw c;o.push(c)}i.length!==0&&this._signalMetaSubtree(u,i,r,a,o)}}}_signalMetaSubtree(e,n,r,o,s){for(let a of Object.keys(e.meta).sort()){let i=e.meta[a];if(!r.has(i)){r.add(i);try{i.down(n,o)}catch(d){if(d instanceof Ie)throw d;s.push(d)}this._signalMetaSubtree(i,n,r,o,s)}}}describe(e){if(e?.reactive==="diff")return this._describeReactiveDiff(e);if(e?.reactive===!0)return this._describeReactive(e);let n=Bi(e?.actor),r=e?.filter;if(e?.detail!=null&&e?.fields!=null)throw new TypeError("Graph.describe(): pass either `detail` or `fields`, not both. `detail: 'spec'` is the canonical spec projection; use `fields` only when you need a custom subset.");let o=ar(e?.detail,e?.fields),s=e?.detail==="spec",a=o,i=[];this._collectObserveTargets("",i);let d=new Map;for(let[w,k]of i)d.set(k,w);let u=[];{let w=i.map(([,T])=>T),k=new Set(d.values()),S=0;for(;w.length>0;){let T=w.shift();if(T instanceof me)for(let x of T._deps){let N=x.node;if(d.has(N))continue;let _=N.name??"",M=_;if(!M||k.has(M))if(_){let A=2;for(;k.has(`${_}#${A}`);)A++;M=`${_}#${A}`}else for(M=`__internal__/${S++}`;k.has(M);)M=`__internal__/${S++}`;d.set(N,M),k.add(M),u.push([M,N]),w.push(N)}}}let c=[...i,...u],l={};for(let[w,k]of c){if(n!=null&&!k.allowsObserve(n))continue;let S=dr(k,a,s),T=k instanceof me?k._deps.map(M=>d.get(M.node)??M.node.name??""):[],{name:x,...N}=S,_={...N,deps:T};if(!s){let M=this._annotations.get(w);M!=null&&(_.annotation=M)}if(r!=null)if(typeof r=="function"){let M=r;if(!(M.length>=2?M(w,_):M(_)))continue}else{let M=!0;for(let[A,R]of Object.entries(r)){let O=A==="deps_includes"?"depsIncludes":A==="meta_has"?"metaHas":A;if(O==="depsIncludes"){if(!_.deps.includes(String(R))){M=!1;break}continue}if(O==="metaHas"){if(!Object.hasOwn(_.meta??{},String(R))){M=!1;break}continue}if(_[O]!==R){M=!1;break}}if(!M)continue}l[w]=_}let p=new Set(Object.keys(l)),f=[];for(let[w,k]of c)if(k instanceof me)for(let S of k._deps){let T=d.get(S.node);T!=null&&f.push([T,w])}f.sort((w,k)=>w[0]<k[0]?-1:w[0]>k[0]?1:w[1]<k[1]?-1:w[1]>k[1]?1:0);let m=f.map(([w,k])=>({from:w,to:k}));(n!=null||r!=null)&&(m=m.filter(w=>p.has(w.from)&&p.has(w.to)));let h=this._collectSubgraphs(""),g=n!=null||r!=null?h.filter(w=>{let k=`${w}${fe}`;return[...p].some(S=>S===w||S.startsWith(k))}):h,y=this,v=e;return{name:this.name,nodes:l,edges:m,subgraphs:g,...this._factory!==void 0?{factory:this._factory}:{},...this._factoryArgs!==void 0?{factoryArgs:this._factoryArgs}:{},expand(w){let k={...v};return Array.isArray(w)?(k.fields=w,k.detail=void 0):(k.detail=w,k.fields=void 0),y.describe(k)}}}_collectSubgraphs(e){let n=[];for(let r of[...this._mounts.keys()].sort()){let o=e===""?r:`${e}${r}`;n.push(o),n.push(...this._mounts.get(r)._collectSubgraphs(`${o}${fe}`))}return n}resourceProfile(e){return Uo(this,e)}reachable(e,n,r={}){return r.withDetail===!0?gr(this.describe(),e,n,{...r,withDetail:!0}):gr(this.describe(),e,n,r)}explain(e,n,r){return r?.reactive===!0?this._explainReactive(e,n,r):this._explainStatic(Qe(e),Qe(n),{...r?.maxDepth!==void 0?{maxDepth:Wo(r.maxDepth)}:{},...r?.findCycle!==void 0?{findCycle:Ho(r.findCycle)}:{}})}_explainStatic(e,n,r){let o=this.describe({detail:"full"}),s=new Map(this._annotations),a=new Map;for(let[i,d]of Object.entries(o.nodes))d.lastMutation!=null&&a.set(i,d.lastMutation);return Fo(o,e,n,{...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{},annotations:s,lastMutations:a})}_describeReactive(e){let n={...e,reactive:!1},r=e.reactiveName??"describe",o=0,s=F(o,{name:`${r}_version`}),a=this.observe({timeline:!0,structured:!0}),i=!1,d=!1,u=()=>{i||d||(i=!0,gt(()=>{i=!1,!d&&(o+=1,s.emit(o))}))},c=a.onEvent(v=>{let b=v.type;b!=="data"&&b!=="error"&&b!=="complete"&&b!=="teardown"||u()}),l=[],p=new WeakSet,f=v=>{if(p.has(v)||d)return;p.add(v);let b=v.topology.subscribe(w=>{for(let k of w){if(k[0]!==D)continue;let S=k[1];if(u(),S.kind==="added"&&S.nodeKind==="mount"){let T=v._mounts.get(S.name);T!=null&&f(T)}}});l.push(b);for(let w of v._mounts.keys()){let k=v._mounts.get(w);k!=null&&f(k)}};f(this);let m,h=e.actor;Qo(h)&&(m=h.subscribe(v=>{let b=!1,w=!1;for(let k of v){let S=k[0];S===D?b=!0:(S===$||S===P||S===le)&&(w=!0)}b&&u(),w&&(m?.(),m=void 0,u())}));let g;try{g=C([s],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(v,b)=>v===b})}catch(v){c(),m?.();for(let b of l)b();throw a.dispose(),v}let y=Y(g);return{node:g,dispose(){d=!0,c(),m?.();for(let v of l)v();l.length=0,a.dispose(),y()}}}_describeReactiveDiff(e){let n={...e,reactive:!1},r=e.reactiveName??"describe-diff",o={name:this.name,nodes:{},edges:[],subgraphs:[]},s=this.describe(n),a=lr(o,s),i=F(a,{name:r,meta:{domain:"audit",kind:"describe-diff"},equals:(p,f)=>p===f}),d=this._describeReactive({...e,reactiveName:void 0}),u=!1,c=d.node.subscribe(p=>{if(!u)for(let f of p){if(f[0]!==D)continue;let m=f[1],h=lr(s,m);s=m,h.events.length!==0&&i.emit(h)}}),l=Y(i);return{node:i,dispose(){u=!0,c(),d.dispose(),i.down([[le,"describe-diff disposed"]]),l()}}}_explainReactive(e,n,r){let o=0,s=F(o,{name:"explain_version"}),a=this.observe({timeline:!0,structured:!0}),i=!1,d=!1,u=()=>{i||d||(i=!0,gt(()=>{i=!1,!d&&(o+=1,s.emit(o))}))},c=a.onEvent(v=>{let b=v.type;b!=="data"&&b!=="error"&&b!=="complete"&&b!=="teardown"||u()}),l=[];e!=null&&at(e)&&l.push(e),n!=null&&at(n)&&l.push(n),r?.maxDepth!=null&&at(r.maxDepth)&&l.push(r.maxDepth),r?.findCycle!=null&&at(r.findCycle)&&l.push(r.findCycle);let p=()=>{for(let v of l)if(v.cache===void 0)return!1;return!0},f=()=>{let v=Qe(e),b=Qe(n);return{from:v,to:b,found:!1,reason:"pending",steps:[],text:"(awaiting reactive args)",toJSON:()=>({from:v,to:b,found:!1,reason:"pending",steps:[]})}},m;try{m=C([s],()=>{if(!p())return f();let v=Qe(e),b=Qe(n),w={...r?.maxDepth!==void 0?{maxDepth:Wo(r.maxDepth)}:{},...r?.findCycle!==void 0?{findCycle:Ho(r.findCycle)}:{}};return this._explainStatic(v,b,w)},{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:Qe(e),to:Qe(n)},equals:(v,b)=>v.found===b.found&&v.reason===b.reason&&v.steps.length===b.steps.length&&Qi(v.steps,b.steps)})}catch(v){throw c(),a.dispose(),v}let h=Y(m),g=[],y=v=>{let b;return b=v.subscribe(w=>{let k=!1,S=!1;for(let T of w){let x=T[0];x===D?k=!0:(x===$||x===P||x===le)&&(S=!0)}(k||S)&&u(),S&&b&&(b(),b=void 0)}),()=>{b&&(b(),b=void 0)}};for(let v of l)g.push(y(v));return{node:m,dispose(){d=!0,c();for(let v of g)v?.();g.length=0,a.dispose(),h()}}}_pathsMatching(e){let n=dn(e),r=[];return this._collectObserveTargets("",r),r.map(([o])=>o).filter(o=>n.test(o))}_collectObserveTargets(e,n){for(let r of[...this._mounts.keys()].sort()){let o=e===""?r:`${e}${fe}${r}`;this._mounts.get(r)._collectObserveTargets(o,n)}for(let r of[...this._nodes.keys()].sort()){let o=this._nodes.get(r),s=e===""?r:`${e}${fe}${r}`;n.push([s,o]),this._appendMetaObserveTargets(s,o,n)}}_appendMetaObserveTargets(e,n,r){for(let o of Object.keys(n.meta).sort()){let s=n.meta[o],a=`${e}${fe}${Ae}${fe}${o}`;r.push([a,s]),this._appendMetaObserveTargets(a,s,r)}}observe(e,n){let r=typeof e=="string",s=Yo(r?n:e);if(s.reactive===!0)return this._observeReactive(r?e:void 0,s);let a=s.structured===!0||s.timeline===!0||s.causal===!0||s.derived===!0||s.detail==="minimal"||s.detail==="full"||s.format!=null,i=s.actor;if(r){let c=e,l=this.resolve(c);if(i!=null&&!l.allowsObserve(i))throw new Ie({actor:i,action:"observe",nodeName:c});return a?this._buildStructuredObserver([[c,l]],s,"one"):{subscribe(p){return l.subscribe(p)},up(p){try{l.up?.(p)}catch(f){if(f instanceof Ie)return;throw f}}}}let d=[];this._collectObserveTargets("",d),d.sort((c,l)=>c[0]<l[0]?-1:c[0]>l[0]?1:0);let u=i==null?d:d.filter(([,c])=>c.allowsObserve(i));return a?this._buildStructuredObserver(u,s,"all"):{subscribe:c=>{let l=u.map(([p,f])=>f.subscribe(m=>{c(p,m)}));return()=>{for(let p of l)p()}},up:(c,l)=>{try{this.resolve(c).up?.(l)}catch(p){if(p instanceof Ie)return;throw p}}}}_observeReactive(e,n){let r=n.tiers,o=r!=null?new Set(r):null,s=n.reactiveName??"observe";return se(a=>{let i=[],d=!1,u=!1,c=()=>{if(i.length===0||u)return;let h={events:i.slice(),flushedAt_ns:z()};i.length=0,a.emit(h)},l={...n,reactive:!1,structured:!0,timeline:!0},p=e!=null?this.observe(e,l):this.observe(l),f=h=>{u||(i.push(h),!d&&(d=!0,gt(()=>{d=!1,c()})))};for(let h of p.events)f(h);let m=p.onEvent(f);return()=>{u=!0,m(),p.dispose()}},{name:s,meta:{domain:"audit",kind:"observe-reactive"}})}_buildStructuredObserver(e,n,r){let o=r==="one"?e[0]?.[0]:void 0,s=a=>{if(r==="one"&&o!=null){let c=this.resolve(o);return this._buildStructuredObserver([[o,c]],a,"one")}let i=[];this._collectObserveTargets("",i),i.sort((c,l)=>c[0]<l[0]?-1:c[0]>l[0]?1:0);let d=a.actor,u=d==null?i:i.filter(([,c])=>c.allowsObserve(d));return this._buildStructuredObserver(u,a,"all")};return this._createObserveResult(e,n,s)}_createObserveResult(e,n,r){let o=n.timeline===!0,s=n.causal===!0,a=n.derived===!0,i=n.detail==="minimal",d=this.config.inspectorEnabled,u=(s||a)&&d,c=n.maxEvents,l=c!=null&&c>0?new st(c):null,p=[],f=new Set,m=n.tiers!=null?new Set(n.tiers):null,h={},g=new Set,y=0,v=0,b=0,w=0,k=0,S=0,T=!1,x=!1,N=0,_=new Map,M=new Map,A=new Map,R=V=>{if(!(m!=null&&!m.has(V.type))){l?l.push(V):p.push(V);for(let ee of f)ee(V)}},O=V=>m==null||m.has(V),I=()=>o?{timestamp_ns:z(),in_batch:Jt(),batch_id:N}:{},K=(V,ee)=>{if(!(!u||!(V instanceof me)))return V._setInspectorHook(Re=>{if(Re.kind==="dep_message")_.set(V,Re.depIndex);else if(Re.kind==="run"){let et=Re.batchData.map((oe,Ne)=>oe!=null&&oe.length>0?oe.at(-1):Re.prevData[Ne]);M.set(V,et);let Ce=Re.batchData.map(oe=>oe!=null?[...oe]:void 0);A.set(V,Ce),a&&R({type:"derived",path:ee,dep_values:et,dep_batches:Ce,...I()})}})},q=V=>{let ee=_.get(V),Re=M.get(V);if(!s||Re==null)return{};let Ce=(ee!=null&&ee>=0&&V instanceof me?V._deps[ee]:void 0)?.node,oe=Ce?.v,Ne=A.get(V);return{trigger_dep_index:ee,trigger_dep_name:Ce?.name,...oe!=null?{trigger_version:{id:oe.id,version:oe.version}}:{},dep_values:[...Re],...Ne!=null?{dep_batches:Ne}:{}}},H=[],G=[];for(let[V,ee]of e){let Re=K(ee,V);Re&&H.push(Re),G.push(ee.subscribe(et=>{N++;for(let Ce of et){let oe=Ce[0],Ne=I();if(oe===D){h[V]=Ce[1];let Kn=ee instanceof me?ee.lastMutation?.actor??pt:pt;R({type:"data",path:V,data:Ce[1],actor:Kn,...Ne,...q(ee)})}else if(i)oe===X?O("dirty")&&y++:oe===U?O("resolved")&&v++:oe===Le?O("invalidate")&&b++:oe===Se?O("pause")&&w++:oe===De?O("resume")&&k++:oe===le?O("teardown")&&S++:oe===$&&!g.has(V)?O("complete")&&(T=!0):oe===P&&O("error")&&(x=!0,g.add(V));else if(oe===X)O("dirty")&&y++,R({type:"dirty",path:V,...Ne});else if(oe===U)O("resolved")&&v++,R({type:"resolved",path:V,...Ne,...q(ee)});else if(oe===Le)O("invalidate")&&b++,R({type:"invalidate",path:V,...Ne});else if(oe===Se)O("pause")&&w++,R({type:"pause",path:V,lockId:Ce[1],...Ne});else if(oe===De)O("resume")&&k++,R({type:"resume",path:V,lockId:Ce[1],...Ne});else if(oe===$)O("complete")&&!g.has(V)&&(T=!0),R({type:"complete",path:V,...Ne});else if(oe===P){O("error")&&(x=!0,g.add(V));let Kn=ee instanceof me?ee.lastMutation?.actor??pt:pt;R({type:"error",path:V,data:Ce[1],actor:Kn,...Ne})}else oe===le&&(O("teardown")&&S++,R({type:"teardown",path:V,...Ne}))}}))}let B=!1,E=()=>{if(!B){B=!0;for(let V of G)V();for(let V of H)V();for(let V of J)V({value:void 0,done:!0});J.length=0}},L=[],J=[];f.add(V=>{let ee=J.shift();ee?ee({value:V,done:!1}):L.push(V)});let he={get values(){return h},get dirtyCount(){return y},get resolvedCount(){return v},get invalidateCount(){return b},get pauseCount(){return w},get resumeCount(){return k},get teardownCount(){return S},get events(){return l?l.toArray():[...p]},get anyCompletedCleanly(){return T},get anyErrored(){return x},get completedWithoutErrors(){return T&&!x},onEvent(V){return f.add(V),()=>f.delete(V)},dispose:E,expand(V){E();let ee={...n};return typeof V=="string"?ee.detail=V:Object.assign(ee,V),r(Yo(ee))},[Symbol.asyncIterator](){return{next(){return L.length>0?Promise.resolve({value:L.shift(),done:!1}):B?Promise.resolve({value:void 0,done:!0}):new Promise(V=>J.push(V))},return(){return E(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(he,n),he}_attachFormatLogger(e,n){let r=n.format;if(r==null)return;let o=n.logger??(m=>console.log(m)),s=n.includeTypes?new Set(n.includeTypes):null,a=n.excludeTypes?new Set(n.excludeTypes):null,i=s==null&&a==null?()=>!0:m=>(s==null||s.has(m))&&(a==null||!a.has(m)),d=Wi(n.theme),u=r==="stage-log"?z():0,c=m=>m==null?"":n.stageLabels?.[m]??m,l=(m,h)=>m.length>h?`${m.slice(0,h-1)}\u2026`:m,p=m=>m.type==="data"||m.type==="error"?l(fr(m.data),120):"",f=m=>{if(r==="stage-log"){let T=(z()-u)/1e9,x=c(m.path).padEnd(9);if(m.type==="data"){let N=p(m);return`[${T.toFixed(3)}s] ${x} \u2190${N?` ${N}`:""}`}if(m.type==="error"){let N=p(m);return`[${T.toFixed(3)}s] ${x} \u2717${N?` ${N}`:""}`}return m.type==="complete"?`[${T.toFixed(3)}s] ${x} \u25A0 complete`:`[${T.toFixed(3)}s] ${x} ${m.type}`}if(r==="json")try{return JSON.stringify(m)}catch{return JSON.stringify({type:m.type,path:m.path,data:"[unserializable]"})}let h=d[m.type]??"",g=m.path?`${d.path}${m.path}${d.reset} `:"",y=m.type==="data"||m.type==="error",v=m.type==="pause"||m.type==="resume",b=y?` ${fr(m.data)}`:v?` ${fr(m.lockId)}`:"",w=m.type==="data"||m.type==="resolved"||m.type==="derived"?m:void 0,k=w?.trigger_dep_name!=null?` <- ${w.trigger_dep_name}`:w?.trigger_dep_index!=null?` <- #${w.trigger_dep_index}`:"",S=m.in_batch?" [batch]":"";return`${g}${h}${m.type.toUpperCase()}${d.reset}${b}${k}${S}`};e.onEvent(m=>{i(m.type)&&o(f(m),m)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){an(this._disposers,this.name),this.signal([[le]],{internal:!0}),an(this._storageDisposers,this.name);for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}get destroyed(){return this._destroyed}_destroyClearOnly(){an(this._disposers,this.name),an(this._storageDisposers,this.name);for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}snapshot(e){let{expand:n,...r}=this.describe({detail:"full"}),o={};for(let i of Object.keys(r.nodes).sort()){let{lastMutation:d,guard:u,...c}=r.nodes[i];o[i]=c}let s=[...r.subgraphs].sort(),a={...r,version:1,nodes:o,subgraphs:s};if(e?.format==null)return a;if(e.format==="json-string")return JSON.stringify(a);if(e.format==="bytes"){if(e.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let i=this.config.lookupCodec(e.codec);if(i==null)throw new Error(`snapshot: codec "${e.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return lo(i,i.encode(a))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??yt,{codec:o,codecVersion:s,payload:a}=po(e,r);return o.decode(a,s)}restore(e,n){if(Jo(e),e.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${e.name}" does not match this graph`);let r=n?.only==null?null:(Array.isArray(n.only)?n.only:[n.only]).map(s=>dn(s)),o=n?.includeProducers===!0;for(let s of Object.keys(e.nodes).sort()){if(r!==null&&!r.some(i=>i.test(s)))continue;let a=e.nodes[s];if(a!==void 0){if(!("value"in a)||a.value===void 0){"value"in a&&a.value===void 0&&n?.onError?.(s,new Error(`restore: slice.value is undefined for "${s}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(a.type==="derived"||a.type==="effect")&&!(a.type==="producer"&&!o)){if(a.v!=null){let d=this.tryResolve(s)?.v;if(d!=null&&d.id===a.v.id&&d.version===a.v.version)continue}try{this.set(s,a.value)}catch(i){n?.onError?.(s,i)}}}}}static fromSnapshot(e,n){Jo(e);let r=typeof n=="function"?n:n?.build,o=typeof n=="function"?void 0:n?.factories,s=new t(e.name);if(r)return r(s),s.restore(e),s;for(let f of[...e.subgraphs].sort((m,h)=>{let g=m.split(fe).length,y=h.split(fe).length;return g!==y?g-y:m<h?-1:m>h?1:0})){let m=f.split(fe),h=s;for(let g of m)h._mounts.has(g)||h.mount(g,new t(g)),h=h._mounts.get(g)}let a=o?Object.entries(o).map(([f,m])=>({re:dn(f),factory:m})):[],i=f=>{for(let m of a)if(m.re.test(f))return m.factory},d=f=>{let m=f.split(fe),h=m.pop();if(h==null||h.length===0)throw new Error(`invalid snapshot path "${f}"`);let g=s;for(let y of m){let v=g._mounts.get(y);if(!v)throw new Error(`unknown mount "${y}" in path "${f}"`);g=v}return[g,h]},u=Object.entries(e.nodes).filter(([f])=>!f.includes(`${fe}${Ae}${fe}`)).sort((f,m)=>f[0]<m[0]?-1:f[0]>m[0]?1:0),c=new Map(u),l=new Map,p=!0;for(;c.size>0&&p;){p=!1;for(let[f,m]of[...c.entries()]){let h=m?.deps??[];if(!h.every(k=>l.has(k)))continue;let[g,y]=d(f),v={...m?.meta??{}},b=i(f),w;if(m?.type==="state")w=F(m.value,{meta:v});else{if(b==null)continue;w=b(y,{path:f,type:m.type,value:m.value,meta:v,deps:h,resolvedDeps:h.map(k=>l.get(k))})}g.add(w,{name:y}),l.set(f,w),c.delete(f),p=!0}}if(c.size>0){let f=[...c.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${f}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return s.restore(e),s}toJSON(){return this.snapshot()}attachSnapshotStorage(e,n={}){let r=e.map(u=>({tier:u,debounceMs:Math.max(0,u.debounceMs??0),compactEvery:Math.max(1,u.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));n.autoRestore===!0&&this._cascadeRestore(e,n.onError);let o=(u,c)=>{if(u.disposed)return;let l=Vi(c.nodes);if(u.lastSnapshot!=null&&l!==""&&l===u.lastFingerprint)return;let p=u.seq+1,f=ce(),g=u.lastSnapshot==null||p%u.compactEvery===0?{name:this.name,mode:"full",snapshot:c,seq:p,timestamp_ns:f,format_version:it}:{name:this.name,mode:"diff",diff:Zo(u.lastSnapshot,c),seq:p,timestamp_ns:f,format_version:it};if(u.tier.filter&&!u.tier.filter(g))return;let y;try{y=u.tier.save(g)}catch(v){n.onError?.(v,u.tier);return}if(y&&typeof y.then=="function"){let w=(u.savePending??Promise.resolve()).then(()=>y,()=>y).then(()=>{u.disposed||(u.seq=p,u.lastSnapshot=c,u.lastFingerprint=l)},k=>{n.onError?.(k,u.tier)});u.savePending=w.finally(()=>{u.savePending===w&&(u.savePending=void 0)})}else u.seq=p,u.lastSnapshot=c,u.lastFingerprint=l},s=(u,c)=>{try{o(u,c)}catch(l){n.onError?.(l,u.tier)}},a=(u,c)=>{if(!c.some(m=>{let h=this.config.messageTier(m[0]);return h>=3&&h<5}))return;if(n.filter){let m=this.tryResolve(u);if(m==null)return;let h=dr(m,ar("standard"));if(!n.filter(u,h))return}let p,f=()=>(p==null&&(p=this.snapshot()),p);for(let m of r)m.disposed||(m.debounceMs===0?s(m,f()):(m.timer==null&&(m.timer=new ge),m.timer.start(m.debounceMs,()=>{m.disposed||s(m,this.snapshot())})))},i;if(n.paths!=null){let c=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(l=>{let p=this.tryResolve(l);return p==null?()=>{}:p.subscribe(f=>a(l,f))});i=()=>{for(let l of c)l()}}else i=this.observe().subscribe((u,c)=>a(u,c));let d=()=>{i();for(let u of r)u.disposed=!0,u.timer?.cancel();this._storageDisposers.delete(d)};return this._storageDisposers.add(d),{dispose:d}}async _cascadeRestore(e,n){for(let r of e){let o;try{o=await r.load?.()}catch(a){n?.(a,r);continue}if(o==null||typeof o!="object"||Array.isArray(o))continue;let s=o;try{if(s.mode==="full"&&s.snapshot!=null)return this.restore(s.snapshot),!0;if(s.version===it&&s.nodes!=null)return this.restore(s),!0}catch(a){n?.(a,r)}}return!1}static async fromStorage(e,n,r){for(let o of n){let s;try{s=await o.load?.()}catch(d){r?.onError?.(d,o);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let a=s,i=a.mode==="full"&&a.snapshot!=null?a.snapshot:a.version===it&&a.nodes!=null?a:void 0;if(i!=null)try{return t.fromSnapshot(i,r)}catch(d){r?.onError?.(d,o)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${n.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,n,r){if(e!=null&&n!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,n),this.config.inspectorEnabled){let o={path:e,annotation:n,timestamp_ns:z(),...r?.actor!=null?{actor:r.actor}:{}};this._traceRing.push(o)}return}return e!=null?this.config.inspectorEnabled?this._annotations.get(e):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(e){return this._annotations.get(e)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(e){let n=this._traceRing.toArray().filter(o=>!e(o)),r=this._traceRing.size-n.length;this._traceRing.clear();for(let o of n)this._traceRing.push(o);return r}static diff(e,n){let r=new Set(Object.keys(e.nodes)),o=new Set(Object.keys(n.nodes)),s=[...o].filter(v=>!r.has(v)).sort(),a=[...r].filter(v=>!o.has(v)).sort(),i=[],d=[];for(let v of r){if(!o.has(v))continue;let b=e.nodes[v],w=n.nodes[v],k=b.v,S=w.v;k!=null&&S!=null&&k.id===S.id&&k.version!==S.version&&d.push({path:v,id:k.id,from:k.version,to:S.version});let T=k!=null&&S!=null&&k.id===S.id&&k.version===S.version;for(let x of["type","status","sentinel"]){let N=b[x],_=w[x];N!==_&&i.push({path:v,field:x,from:N,to:_})}if(!T)for(let x of["value","meta"]){let N=b[x],_=w[x];Ki(N,_)||i.push({path:v,field:x,from:N,to:_})}}let u=v=>`${v.from} ${v.to}`,c=new Set(e.edges.map(u)),l=new Set(n.edges.map(u)),p=n.edges.filter(v=>!c.has(u(v))),f=e.edges.filter(v=>!l.has(u(v))),m=new Set(e.subgraphs),h=new Set(n.subgraphs),g=[...h].filter(v=>!m.has(v)).sort(),y=[...m].filter(v=>!h.has(v)).sort();return{nodesAdded:s,nodesRemoved:a,nodesChanged:i,versionChanges:d,edgesAdded:p,edgesRemoved:f,subgraphsAdded:g,subgraphsRemoved:y}}}});var hr=re(()=>{"use strict";Ue()});function Lt(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&"down"in t}function es(t){if(t<=0)throw new RangeError("timeoutMs must be > 0");if(t>9e6)throw new RangeError("timeoutMs must be <= 9_000_000 (\u22482.5h) to stay within safe ns arithmetic")}function ts(t,e={}){let n=new Dt(t,e);return n.tagFactory("resilientPipeline",Je(e)),n}var Dt,ns=re(()=>{"use strict";Ee();hr();Ye();Pe();Tr();Dt=class extends ae{output;status;lastError;breakerState;droppedCount;rateLimitState;constructor(e,n={}){super(n.name??"resilient_pipeline",n.graph);let r=e,o,s,a;if(n.rateLimit!=null)if(Lt(n.rateLimit)){let d=r,u=n.rateLimit;r=de(u,c=>{let l={...c,maxBuffer:c.maxBuffer??1/0,meta:ue("resilient","rate-limit")};return cn(d,l).node}),this.add(r,{name:"rateLimited"})}else{let d={...n.rateLimit,maxBuffer:n.rateLimit.maxBuffer??1/0,meta:ue("resilient","rate-limit")},u=cn(r,d);r=u.node,o=u.droppedCount,s=u.rateLimitState,this.add(r,{name:"rateLimited"}),this.add(o,{name:"droppedCount"}),this.add(s,{name:"rateLimitState"})}if(n.budget!=null)if(Lt(n.budget)){let d=r,u=n.budget;r=de(u,c=>c.length>0?Ct(d,c,{meta:ue("resilient","budget")}):d),this.add(r,{name:"budgetGated"})}else n.budget.length>0&&(r=Ct(r,n.budget,{meta:ue("resilient","budget")}),this.add(r,{name:"budgetGated"}));if(n.breaker!=null)if(Lt(n.breaker)){let d=r,u=n.breaker,c=n.breakerOnOpen??"skip";r=de(u,l=>{let p=Xe(l);return un(p,{onOpen:c,meta:ue("resilient","breaker")})(d).node}),this.add(r,{name:"breakerWrapped"})}else{let d=Xe(n.breaker),u=n.breakerOnOpen??"skip",c=un(d,{onOpen:u,meta:ue("resilient","breaker")})(r);r=c.node,a=c.breakerState,this.add(r,{name:"breakerWrapped"}),this.add(a,{name:"breakerState"})}if(n.timeoutMs!=null)if(Lt(n.timeoutMs)){let d=r,u=n.timeoutMs;r=de(u,c=>(es(c),ln(d,c*1e6,{meta:ue("resilient","timeout")}))),this.add(r,{name:"timeoutWrapped"})}else es(n.timeoutMs),r=ln(r,n.timeoutMs*1e6,{meta:ue("resilient","timeout")}),this.add(r,{name:"timeoutWrapped"});if(n.retry!=null)if(Lt(n.retry)){let d=r,u=n.retry;r=de(u,c=>bt(d,{...c,meta:ue("resilient","retry")})),this.add(r,{name:"retryWrapped"})}else r=bt(r,{...n.retry,meta:ue("resilient","retry")}),this.add(r,{name:"retryWrapped"});n.fallback!==void 0&&(r=br(r,n.fallback,{meta:ue("resilient","fallback")}),this.add(r,{name:"fallbackWrapped"}));let i=yr(r,{initialStatus:n.initialStatus??"pending",meta:ue("resilient","status")});this.output=i.node,this.status=i.status,this.lastError=i.error,this.breakerState=a,this.droppedCount=o,this.rateLimitState=s,this.add(this.output,{name:"output"}),this.add(this.status,{name:"status"}),this.add(this.lastError,{name:"lastError"})}}});function dt(t){return{describeKind:"derived",...t}}function Xi(t){return t<0?0:t}function vr(t){return t[1]}function Zi(t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("backoff strategy must return a finite number");return t<0?0:t}function fn(t){let e=t?.count,n=t?.backoff;if(n!==void 0&&e===void 0)throw new RangeError("retry({ backoff }) requires explicit count to prevent unbounded retries; pass { count: <n>, backoff: ... }");let r=e!==void 0?e:0;if(r<0)throw new RangeError("retry count must be >= 0");let o=n===void 0?null:typeof n=="string"?or(n):n;return{maxRetries:r,strategy:o}}function os(t){let e={};return t?.count!==void 0&&(e.count=t.count),typeof t?.backoff=="string"&&(e.backoff=t.backoff),Object.keys(e).length>0?e:void 0}function ss(t,e,n){let r=0,o=!1,s=null,a,i=new ge;function d(){a?.(),a=void 0}function u(l){if(o)return;let p=t();if(r>=p.maxRetries){d(),n.down([[P,l]]);return}let f=p.strategy===null?0:p.strategy(r,l,s);if(f==null){d(),n.down([[P,l]]);return}let m;try{m=Zi(f)}catch{d(),n.down([[P,l]]);return}s=m,r+=1,d();let h=m>0?m/1e6:1;i.start(h,()=>{o||c()})}function c(){i.cancel(),d();let l;try{l=e()}catch(p){u(p);return}a=l.subscribe(p=>{if(!o)for(let f of p){let m=f[0];if(m===X)n.down([[X]]);else if(m===D)r=0,s=null,n.emit(f[1]);else if(m===U)n.down([[U]]);else if(m===$)o=!0,d(),n.down([[$]]);else if(m===P){u(vr(f));return}else n.down([f])}})}return c(),()=>{o=!0,i.cancel(),d()}}function bt(t,e){return typeof t=="function"?ta(t,e):ea(t,e)}function ea(t,e){t._resubscribable===!1&&!rs.has(t)&&(rs.add(t),console.warn("retry(source, opts): source-mode requires `resubscribable: true` on the upstream node. Retries will be silent no-ops after the first ERROR. Either pass `resubscribable: true` to the source factory, OR use factory-mode retry `retry(() => buildSource(), opts)` so each attempt builds a fresh node."));let r=Fe(e)?void 0:e;return Fe(e)||fn(r),se(o=>{let s=It(e),i=ss(()=>fn(s.current()),()=>t,o);return()=>{i(),s.unsub()}},{...dt(),initial:t.cache,meta:{...r?.meta??{},...pe("retry",Fe(e)?{reactiveOpts:!0}:os(r))}})}function ta(t,e){let n=Fe(e)?void 0:e;return Fe(e)||fn(n),se(r=>{let o=It(e),a=ss(()=>fn(o.current()),t,r);return()=>{a(),o.unsub()}},{...dt(),initial:n?.initial,meta:{...n?.meta??{},...pe("retry",Fe(e)?{reactiveOpts:!0}:os(n))}})}function Xe(t){let e=5,n=30*1e9,r=null,o=1,s=z;function a(y){e=Math.max(1,y?.failureThreshold??5),n=Xi(y?.cooldownNs??30*1e9),r=y?.cooldown??null,o=Math.max(1,y?.halfOpenMax??1),s=y?.now??z}let i="closed",d=0,u=0,c=0,l=n,p=0,f=It(t,y=>{a(y),i="closed",d=0,u=0,p=0,l=n});a(f.current()),l=n;function m(){if(!r)return n;let y=r(u);return y!==null?y:n}function h(){i="open",l=m(),c=s(),p=0}return{canExecute(){return i==="closed"?!0:i==="open"?s()-c>=l?(i="half-open",p=1,!0):!1:p<o?(p++,!0):!1},recordSuccess(){i==="half-open"?(i="closed",d=0,u=0):i==="closed"&&(d=0)},recordFailure(y){if(i==="half-open"){u++,h();return}i==="closed"&&(d++,d>=e&&h())},get state(){return i},get failureCount(){return d},reset(){i="closed",d=0,u=0,p=0},dispose(){f.unsub()}}}function un(t,e){let n=e?.onOpen??"skip",r=e?.meta;return o=>{let s=ne([],(a,i)=>{function d(){s.meta.breakerState.down([[D,t.state]])}let u=o.subscribe(c=>{for(let l of c){let p=l[0];p===X?i.down([[X]]):p===D?t.canExecute()?(d(),i.emit(l[1])):(d(),n==="error"?i.down([[P,new Ze]]):i.down([[U]])):p===U?i.down([[U]]):p===$?(t.recordSuccess(),d(),i.down([[$]])):p===P?(t.recordFailure(vr(l)),d(),i.down([l])):i.down([l])}});return d(),u},{...dt(),meta:{...r??{},breakerState:t.state,...pe("withBreaker",{onOpen:n})},completeWhenDepsComplete:!1,initial:o.cache});return{node:s,breakerState:s.meta.breakerState}}}function Tt(t,e,n){if(t<=0)throw new RangeError("capacity must be > 0");if(e<0)throw new RangeError("refillPerSecond must be >= 0");let r=n?.clock??z,o=t,s=r();function a(i){if(e>0){let d=i-s;o=Math.min(t,o+d/1e9*e)}s=i}return{available(){return a(r()),o},tryConsume(i=1){if(i<=0)return!0;let d=r();return a(d),o>=i?(o-=i,!0):!1},putBack(i=1){i<=0||(a(r()),o=Math.min(t,o+i))}}}function na(t,e){return t.droppedCount===e.droppedCount&&t.pendingCount===e.pendingCount&&t.paused===e.paused}function cn(t,e){let n=Fe(e);if(!n){let i=e;if(i.maxEvents<=0)throw new RangeError("maxEvents must be > 0");if(i.windowNs<=0)throw new RangeError("windowNs must be > 0");if(i.maxBuffer===void 0)throw new RangeError("rateLimiter requires explicit maxBuffer (use Infinity to opt in to unbounded)");if(!(i.maxBuffer===1/0)&&(!Number.isInteger(i.maxBuffer)||i.maxBuffer<1))throw new RangeError("maxBuffer must be a positive integer (or Infinity for unbounded)")}let r=n?e.cache:e,o=r?.maxBuffer,s=o===1/0,a=se(i=>{let d=r?.maxEvents??1,u=r?.windowNs??1e9,c=o??1,l=r?.onOverflow??"drop-newest",p=d*1e9/u,f=1e9/p,m=Tt(d,p),h=s?oa():ra(Math.max(1,c)),g=new ge,y=!1,v=0,b=a.meta.droppedCount,w=a.meta.rateLimitState,k=pn;function S(){b.emit(v);let A={droppedCount:v,pendingCount:h.size,paused:h.size>0};na(k,A)||(k=A,w.emit(A))}k=pn,b.emit(0),w.emit(pn);let T=It(e,A=>{if(y||A==null||!(A.maxEvents>0)||!(A.windowNs>0))return;let R=A.maxBuffer;if(R===void 0)return;let O=R===1/0;if(O===s&&!(!O&&(!Number.isInteger(R)||R<1))){if(!O&&R>c){console.warn(`rateLimiter: reactive maxBuffer grow (${c} \u2192 ${R}) rejected. The pending ring buffer is allocated at construction; reactive maxBuffer is monotonically non-increasing. Recreate the rateLimiter with the larger cap if growth is required.`);return}if(d=A.maxEvents,u=A.windowNs,c=R,l=A.onOverflow??"drop-newest",p=d*1e9/u,f=1e9/p,m=Tt(d,p),!O)for(;h.size>c;)h.shift(),v+=1;S()}});function x(){for(;h.size>0;)if(m.tryConsume(1))i.emit(h.shift()),S();else{g.start(Math.max(1,f/1e6),x);return}}function N(){v+=1,S()}function _(){for(y=!0,g.cancel();h.size>0;)h.shift();v=0}let M=t.subscribe(A=>{for(let R of A){if(y)return;let O=R[0];if(O===X)i.down([[X]]);else if(O===D){if(!s&&h.size>=c)if(l==="drop-newest")N();else if(l==="drop-oldest")h.shift(),h.push(R[1]),N();else{N(),_(),i.down([[P,new mn(c)]]);return}else h.push(R[1]),S();x()}else if(O===U)i.down([[U]]);else if(O===$)_(),i.down([[$]]);else if(O===P)_(),i.down([R]);else if(O===le){_(),i.down([R]);return}else i.down([R])}});return()=>{y=!0,g.cancel(),M(),T.unsub()}},{...dt(),initial:t.cache,meta:{...n?{}:e.meta??{},droppedCount:0,rateLimitState:pn,...pe("rateLimiter",n?{reactiveOpts:!0}:e)}});return{node:a,droppedCount:a.meta.droppedCount,rateLimitState:a.meta.rateLimitState}}function ra(t){let e=new st(t);return{push:n=>e.push(n),shift:()=>e.shift(),get size(){return e.size}}}function oa(){let t=[];return{push:e=>{t.push(e)},shift:()=>t.shift(),get size(){return t.length}}}function yr(t,e){let n=e?.initialStatus??"pending",r=e?.meta,o=ne([],(s,a)=>{let i=n;return o.meta.status.down([[D,n]]),o.meta.error.down([[D,null]]),t.subscribe(u=>{for(let c of u){let l=c[0];if(l===X)a.down([[X]]);else if(l===D)i==="errored"?te(()=>{o.meta.error.down([[D,null]]),o.meta.status.down([[D,"running"]])}):o.meta.status.down([[D,"running"]]),i="running",a.emit(c[1]);else if(l===U)a.down([[U]]);else if(l===$)o.meta.status.down([[D,"completed"]]),i="completed",a.down([[$]]);else if(l===P){let p=vr(c);te(()=>{o.meta.error.down([[D,p]]),o.meta.status.down([[D,"errored"]])}),i="errored",a.down([c])}else a.down([c])}})},{...dt(),meta:{...r??{},status:n,error:null,...pe("withStatus",{initialStatus:n})},completeWhenDepsComplete:!1,resubscribable:!0,initial:t.cache});return{node:o,status:o.meta.status,error:o.meta.error}}function Fe(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function It(t,e){if(!Fe(t))return{current:()=>t,unsub:()=>{}};let n=t,r=n.cache,o=n.subscribe(s=>{for(let a of s)a[0]===D&&(r=a[1],e&&e(r))});return{current:()=>r,unsub:o}}function sa(t){return t!=null&&typeof t.then=="function"}function ia(t){return t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function"}function br(t,e,n){let r=n?.meta;return se(o=>{let s,a;function i(){a?.(),a=void 0,Fe(e)||sa(e)||ia(e)?s=j(e).subscribe(u=>{o.down(u);for(let c of u){let l=c[0];if(l===$||l===P||l===le){s=void 0;return}}}):(o.emit(e),o.down([[$]]))}return a=t.subscribe(d=>{for(let u of d){let c=u[0];if(c===X)o.down([[X]]);else if(c===D)o.emit(u[1]);else if(c===U)o.down([[U]]);else if(c===$)o.down([[$]]);else if(c===P){i();return}else if(c===le){s?.(),o.down([u]);return}else o.down([u])}}),()=>{a?.(),s?.()}},{...dt(),initial:t.cache,meta:{...r??{},...pe("fallback")}})}function ln(t,e,n){if(!Fe(e)&&e<=0)throw new RangeError("timeoutNs must be > 0");let r=n?.meta,o=Fe(e)?{timeoutNs:"Node<number>"}:{timeoutNs:e};return se(s=>{let a=!1,i=new ge,d=It(e),u=()=>{let p=d.current();return typeof p=="number"&&p>0?p:0};function c(){let p=u();if(p<=0)return;let f=p/1e6;i.start(f,()=>{a||(a=!0,l(),s.down([[P,new gn(p)]]))})}let l=t.subscribe(p=>{for(let f of p){if(a)return;let m=f[0];if(m===X)s.down([[X]]);else if(m===D)c(),s.emit(f[1]);else if(m===U)s.down([[U]]);else if(m===$){i.cancel(),a=!0,s.down([[$]]);return}else if(m===P){i.cancel(),a=!0,s.down([f]);return}else if(m===le){i.cancel(),a=!0,s.down([f]);return}else s.down([f])}});return c(),()=>{a=!0,i.cancel(),l(),d.unsub()}},{...dt(),initial:t.cache,meta:{...r??{},...pe("timeout",o)}})}var rs,Ze,mn,pn,gn,Tr=re(()=>{"use strict";Io();ns();Oe();ye();ie();Ee();ke();Q();sr();Z();ze();pr();rs=new WeakSet;Ze=class extends Error{name="CircuitOpenError";constructor(){super("Circuit breaker is open")}};mn=class extends Error{name="RateLimiterOverflowError";constructor(e){super(`rateLimiter buffer overflow (maxBuffer=${e})`)}};pn=Object.freeze({droppedCount:0,pendingCount:0,paused:!1});gn=class extends Error{name="TimeoutError";constructor(e){super(`Timed out after ${e/1e6}ms`)}}});var is={};Un(is,{CircuitOpenError:()=>Ze,RateLimiterOverflowError:()=>mn,ResilientPipelineGraph:()=>Dt,TimeoutError:()=>gn,budgetGate:()=>Ct,circuitBreaker:()=>Xe,fallback:()=>br,rateLimiter:()=>cn,resilientPipeline:()=>ts,retry:()=>bt,timeout:()=>ln,tokenBucket:()=>Tt,withBreaker:()=>un,withStatus:()=>yr});var vt=re(()=>{"use strict";Tr()});function hn(t){return{describeKind:"producer",...t}}function yn(t,e){let{signal:n,period:r,...o}=e??{};return se(s=>{let a=!1,i=0,d,u,c=()=>{a=!0,d!==void 0&&clearTimeout(d),u!==void 0&&clearInterval(u),n?.removeEventListener("abort",p)},l=()=>{a||(r!=null?(s.emit(i++),u=setInterval(()=>{a||s.emit(i++)},r)):(a=!0,n?.removeEventListener("abort",p),s.emit(i++),s.down([[$]])))},p=()=>{a||(c(),s.down([[P,n.reason]]))};if(n?.aborted){p();return}return d=setTimeout(l,t),n?.addEventListener("abort",p,{once:!0}),c},hn(o))}function us(t,e){return se(n=>{let r=!1;try{for(let o of t){if(r)return;n.emit(o)}r||n.down([[$]])}catch(o){r||n.down([[P,o]])}return()=>{r=!0}},hn(e))}function aa(t){return t!=null&&typeof t.then=="function"}function bn(t,e){let{signal:n,...r}=e??{};return se(o=>{let s=!1,a=()=>{s||(s=!0,o.down([[P,n.reason]]))};if(n?.aborted){a();return}return n?.addEventListener("abort",a,{once:!0}),Promise.resolve(t).then(i=>{s||(s=!0,n?.removeEventListener("abort",a),o.emit(i),o.down([[$]]))},i=>{s||(s=!0,n?.removeEventListener("abort",a),o.down([[P,i]]))}),()=>{s=!0,n?.removeEventListener("abort",a)}},hn(r))}function kr(t,e){let{signal:n,...r}=e??{};return se(o=>{let s=new AbortController,a=()=>s.abort(n?.reason);n?.aborted?s.abort(n.reason):n?.addEventListener("abort",a,{once:!0});let i=n??s.signal,d=!1,u=t[Symbol.asyncIterator](),c=()=>{d||i.aborted||Promise.resolve(u.next()).then(l=>{if(!(d||i.aborted)){if(l.done){o.down([[$]]);return}o.emit(l.value),c()}},l=>{!d&&!i.aborted&&o.down([[P,l]])})};return c(),()=>{d=!0,n?.removeEventListener("abort",a),s.abort(),Promise.resolve(u.return?.()).catch(()=>{})}},hn(r))}function da(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function j(t,e){if(da(t))return t;if(aa(t))return bn(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return kr(t,e);if(typeof n[Symbol.iterator]=="function")return us(t,e)}return ua(t)}function ua(...t){return us(t,void 0)}function Pt(t,e,n){return ne([t],(o,s)=>{let a=o[0];if(a!=null&&a.length>0)for(let i of a)e(i)},{describeKind:"effect",...n}).subscribe(()=>{})}function Me(t){return new Promise((e,n)=>{let r=!1,o=!1,s;s=t.subscribe(a=>{for(let i of a){if(r)return;if(i[0]===D){r=!0,e(i[1]),s?(s(),s=void 0):o=!0;return}if(i[0]===P){r=!0,n(i[1]),s?(s(),s=void 0):o=!0;return}if(i[0]===$){r=!0,n(new Error("completed without DATA")),s?(s(),s=void 0):o=!0;return}}}),o&&(s?.(),s=void 0)})}function as(t,e,n){return new Promise((r,o)=>{let s=!1,a=!1,i,d=n?.skipCurrent===!0;i=t.subscribe(u=>{for(let c of u){if(s)return;if(!(d&&c[0]===D)){if(c[0]===D){let l=c[1];if(e(l)){s=!0,r(l),i?(i(),i=void 0):a=!0;return}}if(c[0]===P){s=!0,o(c[1]),i?(i(),i=void 0):a=!0;return}if(c[0]===$){s=!0,o(new Error("completed without matching value")),i?(i(),i=void 0):a=!0;return}}}}),d=!1,a&&(i?.(),i=void 0)})}async function cs(t,e){let n=e?.predicate??(s=>s!=null),r=e?.skipCurrent;if(e?.timeoutMs==null||e.timeoutMs<=0)return await as(t,n,{skipCurrent:r});if(wr===void 0){let[s,a]=await Promise.all([Promise.resolve().then(()=>(vt(),is)),Promise.resolve().then(()=>(sr(),Lo))]);wr=s.timeout,ds=a.NS_PER_MS}let o=wr(t,e.timeoutMs*ds);return await as(o,n,{skipCurrent:r})}function ls(t,e){let n=new AbortController,r=e?.reason??new Error("cancelled via nodeSignal"),o,s=!1,a=()=>{o?(o(),o=void 0):s=!0};return o=t.subscribe(i=>{if(!n.signal.aborted)for(let d of i){if(d[0]===D&&d[1]===!0){n.abort(r),a();return}if(d[0]===P){n.abort(d[1]),a();return}if(d[0]===$){a();return}}}),s&&(o?.(),o=void 0),{signal:n.signal,dispose:()=>{o&&(o(),o=void 0)}}}function Y(t){return t.subscribe(()=>{})}var wr,ds,ps=re(()=>{"use strict";ie();ke();Q()});var Z=re(()=>{"use strict";ps()});function Tn(t){return{describeKind:"derived",...t}}function ca(t){return{describeKind:"derived",partial:!0,...t}}function fs(t,e,n){return ne([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[U]]);return}let a=!1;for(let i of s)e(i)&&(o.emit(i),a=!0);a||o.down([[U]])},{...Tn(n),meta:{...pe("filter"),...n?.meta??{}}})}function ms(t,e,n){let r=n?.where??(s=>s!=null),o=!1;return ne([t],(s,a)=>{let i=s[0];if(i==null||i.length===0){a.down([[U]]);return}for(let d of i)!o&&r(d)&&(o=!0,e(d)),a.emit(d)},Tn(n))}function gs(t,e,n){return ne([t,e],(r,o,s)=>{let a=r[0],i=r[1],d=i!=null&&i.length>0?i.at(-1):s.prevData[1];if(a!=null&&a.length>0){if(!(i!=null&&i.length>0)&&s.prevData[1]===void 0){o.down([[U]]);return}for(let u of a)o.emit([u,d])}else o.down([[U]])},{...ca(n),meta:{...pe("withLatestFrom"),...n?.meta??{}}})}function la(t,e,n){let r,o=!1,s=()=>{o||(o=!0,n())};return r=t.subscribe(a=>{let i=!1,d=!1;for(let u of a)u[0]!==Ke&&(u[0]===D?e.emit(u[1]):u[0]===$?i=!0:u[0]===P?(d=!0,e.down([u])):(u[0]===X||u[0]===U)&&e.down([u]));d?(r?.(),r=void 0,s()):i&&s()}),()=>{r?.(),r=void 0}}function de(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return ne([t],(a,i,d)=>{if(d.terminalDeps[0]!=null&&d.terminalDeps[0]!==!0){s();return}if(d.terminalDeps[0]===!0){o=!0,r||i.down([[$]]);return}let u=a[0];if(!(u==null||u.length===0))return s(),r=la(j(e(u[u.length-1])),i,()=>{s(),o&&i.down([[$]])}),{deactivate:()=>{s(),o=!1}}},{...Tn(n),completeWhenDepsComplete:!1,meta:{...pe("switchMap"),...n?.meta??{}}})}function hs(t,e,n){return se(r=>{let o=t.subscribe(s=>{for(let a of s)if(a[0]===D)r.emit(a[1]);else if(a[0]===P)try{r.emit(e(a[1]))}catch(i){r.down([[P,i]])}else a[0]===$&&r.down([[$]])});return()=>{o()}},Tn(n))}var ys=re(()=>{"use strict";ie();Ee();ke();Q();Z()});var Pe=re(()=>{"use strict";ys()});var Wd={};Un(Wd,{AgentLoopGraph:()=>Bn,AllTiersExhaustedError:()=>$t,BudgetExhaustedError:()=>On,ChatStreamGraph:()=>Pn,CircuitOpenError:()=>Ze,DEFAULT_DECAY_RATE:()=>$n,FallbackMissError:()=>xa,LLMTimeoutError:()=>xt,ReplayCacheMissError:()=>lt,ToolRegistryGraph:()=>Gn,admissionFilter3D:()=>Sd,admissionScored:()=>Ws,agentLoop:()=>Cd,agentMemory:()=>Ld,anthropicAdapter:()=>xr,canonicalJson:()=>Or,cascadingLlmAdapter:()=>Kr,chatStream:()=>to,composePricing:()=>Ka,computePrice:()=>Pr,contentGate:()=>vd,costMeterExtractor:()=>md,createAdapter:()=>Ga,createCapabilitiesRegistry:()=>Oi,createPricingRegistry:()=>Ba,dryRunAdapter:()=>ut,fallbackAdapter:()=>Er,frozenContext:()=>id,gatedStream:()=>ld,gaugesAsContext:()=>Dd,googleAdapter:()=>Ar,graphFromSpec:()=>li,graphFromSpecReactive:()=>Bd,handoff:()=>kd,keywordFlagExtractor:()=>hd,knobsAsTools:()=>Kd,llmConsolidator:()=>Yr,llmExtractor:()=>Jr,memoryRetrieval:()=>uo,memoryWithKG:()=>io,memoryWithTiers:()=>ao,memoryWithVectors:()=>so,observableAdapter:()=>$a,openAICompatAdapter:()=>Lr,parseRateLimitFromError:()=>jr,pricingFor:()=>za,promptCall:()=>Hr,promptNode:()=>Wr,redactor:()=>wd,registryPricing:()=>Va,resilientAdapter:()=>nd,streamExtractor:()=>yd,streamingPromptNode:()=>cd,suggestStrategy:()=>pi,suggestStrategyReactive:()=>Ud,systemPromptBuilder:()=>pd,tier:()=>ed,toolCallExtractor:()=>Td,toolExecution:()=>no,toolRegistry:()=>ro,toolSelector:()=>Nd,validateGraphDef:()=>qd,withBreaker:()=>Gr,withBudgetGate:()=>$r,withDryRun:()=>qa,withRateLimiter:()=>Vr,withReplayCache:()=>Gt,withRetry:()=>zr,withTimeout:()=>Ur,zeroPrice:()=>Mn});module.exports=bi(Wd);Q();Oe();ye();ie();Q();var rr=class{_version=0;_store=new Map;_maxSize;_defaultTtl;constructor(e={}){let{maxSize:n,defaultTtl:r}=e;if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(r!==void 0&&r<=0)throw new RangeError("defaultTtl must be positive");this._maxSize=n,this._defaultTtl=r}get version(){return this._version}get size(){return this._store.size}has(e){let n=this._store.get(e);return n===void 0?!1:this._isExpired(n)?(this._store.delete(e),this._version+=1,!1):(this._touchLru(e,n),!0)}get(e){let n=this._store.get(e);if(n!==void 0){if(this._isExpired(n)){this._store.delete(e),this._version+=1;return}return this._touchLru(e,n),n.value}}set(e,n,r){let o=this._resolveExpiresAt(r);this._store.has(e)&&this._store.delete(e),this._store.set(e,{value:n,expiresAt:o}),this._evictLruWhileOver(),this._version+=1}setMany(e,n){let r=this._resolveExpiresAt(n),o=0;try{for(let[s,a]of e)this._store.has(s)&&this._store.delete(s),this._store.set(s,{value:a,expiresAt:r}),o+=1}finally{o>0&&(this._evictLruWhileOver(),this._version+=1)}}delete(e){let n=this._store.delete(e);return n&&(this._version+=1),n}deleteMany(e){let n=0;try{for(let r of e)this._store.delete(r)&&(n+=1)}finally{n>0&&(this._version+=1)}return n}clear(){let e=this._store.size;return e===0?0:(this._store.clear(),this._version+=1,e)}pruneExpired(){let e=z(),n=0;for(let[r,o]of this._store)this._isExpired(o,e)&&(this._store.delete(r),n+=1);return n>0&&(this._version+=1),n}toMap(){let e=z(),n=new Map;for(let[r,o]of this._store)this._isExpired(o,e)||n.set(r,o.value);return n}_resolveExpiresAt(e){let n=e??this._defaultTtl;if(n!==void 0){if(!Number.isFinite(n)||n<=0)throw new RangeError(`MapBackend: ttl must be a positive finite number (got ${n})`);return z()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??z())>=e.expiresAt}_touchLru(e,n){this._store.delete(e),this._store.set(e,n)}_evictLruWhileOver(){if(this._maxSize!==void 0)for(;this._store.size>this._maxSize;){let e=this._store.keys().next().value;if(e===void 0)break;this._store.delete(e)}}};function _e(t={}){let{name:e,maxSize:n,defaultTtl:r,versioning:o,backend:s,retention:a}=t;if(a&&n!==void 0)throw new RangeError("reactiveMap: `maxSize` (LRU) and `retention` (score-based) are mutually exclusive. Pick one eviction policy.");if(a&&a.archiveThreshold===void 0&&a.maxSize===void 0)throw new RangeError("reactiveMap: `retention` requires at least one of `archiveThreshold` or `maxSize` to trigger archival.");let i=s??new rr({maxSize:n,defaultTtl:r}),d=F(i.toMap(),{name:e,describeKind:"state",equals:(p,f)=>p===f,...o!=null?{versioning:o}:{}});function u(){let p=i.toMap();te(()=>{d.down([[X]]),d.down([[D,p]])})}function c(){if(!a)return;let p=i.toMap(),f=a.archiveThreshold,m=a.maxSize,h=[];for(let[y,v]of p)h.push({key:y,value:v,score:a.score(y,v)});h.sort((y,v)=>y.score-v.score);let g=new Set;if(f!==void 0)for(let y of h)if(y.score<f)g.add(y.key);else break;if(m!==void 0&&h.length-g.size>m)for(let y of h){if(h.length-g.size<=m)break;g.has(y.key)||g.add(y.key)}if(g.size!==0)for(let y of h)g.has(y.key)&&(a.onArchive?.(y.key,y.value,y.score),i.delete(y.key))}function l(p,f="mutation"){let m=i.version;try{return p()}finally{i.version!==m&&(f==="mutation"&&c(),u())}}return{entries:d,has(p){return l(()=>i.has(p),"read")},get(p){return l(()=>i.get(p),"read")},set(p,f,m){l(()=>i.set(p,f,m?.ttl))},setMany(p,f){l(()=>i.setMany(p,f?.ttl))},delete(p){l(()=>i.delete(p))},deleteMany(p){l(()=>i.deleteMany(p))},clear(){l(()=>i.clear())},pruneExpired(){l(()=>i.pruneExpired())},get size(){return i.size},dispose(){}}}function At(t,e){return`${t}::${e}`}function Oi(t){let e=_e({name:"capabilitiesRegistry"}),n=u=>{e.set(At(u.provider,u.id),u)};if(t)for(let u of t)n(u);let r=(u,c)=>{let l=e.get(At(u,c));if(l)return l;let p=e.entries.cache;if(!p)return;let f;for(let[,m]of p){if(m.provider!==u)continue;let h=m.id;c.startsWith(h)&&(!f||h.length>f.id.length)&&(f=m)}return f},o=128,s=new Map,a=new Map,i=(u,c,l,p)=>{for(u.has(c)&&u.delete(c),u.set(c,l);u.size>p;){let f=u.keys().next().value;if(f===void 0)break;u.delete(f)}},d=C([e.entries],([u])=>u instanceof Map?Array.from(u.values()):[],{name:"capabilitiesRegistry/entries",initial:[]});return{register:n,lookup:r,remove(u,c){let l=e.has(At(u,c));return l&&e.delete(At(u,c)),l},entries(){let u=e.entries.cache;return(function*(){if(u)for(let c of u.values())yield c})()},lookupNode(u,c){let l=At(u,c),p=s.get(l);if(p)return s.delete(l),s.set(l,p),p;let f=C([e.entries],()=>r(u,c),{name:`capabilitiesRegistry/lookup/${u}::${c}`,initial:void 0});return i(s,l,f,o),f},entriesNode:d,byProvider(u){let c=a.get(u);if(c)return a.delete(u),a.set(u,c),c;let l=C([d],([p])=>p.filter(f=>f.provider===u),{name:`capabilitiesRegistry/byProvider/${u}`,initial:[]});return i(a,u,l,o),l}}}ye();async function*wt(t,e){let n=e?.parse??(k=>k),r=e?.signal,o=new TextDecoder,s="",a="message",i=[],d,u,c=[],l=()=>{if(i.length===0&&a==="message"&&d===void 0){i=[];return}let k=i.join(`
4
+ `);c.push({event:a,data:n(k),id:d,retry:u}),a="message",i=[],d=void 0,u=void 0},p=k=>{if(k===""){l();return}if(k.startsWith(":"))return;let S=k.indexOf(":"),T=S<0?k:k.slice(0,S),x=S<0?"":k.slice(S+1);switch(x.startsWith(" ")&&(x=x.slice(1)),T){case"event":a=x;break;case"data":i.push(x);break;case"id":x.includes("\0")||(d=x);break;case"retry":{let N=Number(x);Number.isFinite(N)&&(u=N);break}}},f=(k,S)=>{s+=o.decode(k,{stream:!S});let T=s.split(/\r?\n/);s=T.pop()??"";for(let x of T)p(x)},m=t,h=t instanceof ReadableStream?t:m&&typeof m=="object"&&m.body instanceof ReadableStream?m.body:null,g,y,v=!1,b=()=>{v||(v=!0,g&&g.cancel().catch(()=>{}),y&&typeof y.return=="function"&&Promise.resolve(y.return()).catch(()=>{}))},w=()=>{b()};if(r){if(r.aborted)return;r.addEventListener("abort",w,{once:!0})}try{if(h){for(g=h.getReader();!r?.aborted;){let{value:k,done:S}=await g.read();if(S)break;for(f(k,!1);c.length>0;)yield c.shift()}f(new Uint8Array,!0)}else{for(y=t[Symbol.asyncIterator]();!r?.aborted;){let S=await y.next();if(S.done)break;for(f(S.value,!1);c.length>0;)yield c.shift()}f(new Uint8Array,!0)}if(s.trim()){for(let k of s.split(/\r?\n/))p(k);l()}for(;c.length>0;)yield c.shift()}finally{r&&r.removeEventListener("abort",w),b()}}async function qe(t,e){let n;try{n=await t.text()}catch{n=""}let r=e??"HTTP",o=new Error(`${r} API ${t.status}: ${t.statusText}${n?` \u2014 ${n}`:""}`);return o.status=t.status,o.headers=t.headers,o}function xr(t={}){return t.sdk?ha(t):ga(t)}function vn(t,e,n,r){let o=e?.model??n;if(!o)throw new Error("anthropicAdapter: model must be set via options.model or invokeOpts.model");let{system:s,chat:a}=pa(t,e?.systemPrompt),i={model:o,messages:a.map(fa),max_tokens:e?.maxTokens??4096};return s&&(i.system=s),e?.temperature!=null&&(i.temperature=e.temperature),e?.tools&&e.tools.length>0&&(i.tools=e.tools.map(ma)),e?.maxReasoningTokens!=null&&(i.thinking={type:"enabled",budget_tokens:e.maxReasoningTokens}),e?.cacheHint,r&&(i.stream=!0),e?.providerExtras&&Object.assign(i,e.providerExtras),i}function pa(t,e){let n=[];e&&n.push(e);let r=[];for(let o of t)o.role==="system"?n.push(o.content):r.push(o);return{system:n.length>0?n.join(`
5
5
 
6
- `):void 0,chat:r}}function la(t){if(t.role==="tool")return{role:"user",content:[{type:"tool_result",tool_use_id:t.toolCallId,content:t.content}]};if(t.role==="assistant"&&t.toolCalls&&t.toolCalls.length>0){let e=[];t.content&&e.push({type:"text",text:t.content});for(let n of t.toolCalls)e.push({type:"tool_use",id:n.id,name:n.name,input:n.arguments});return{role:"assistant",content:e}}return{role:t.role,content:t.content}}function pa(t){return{name:t.name,description:t.description,input_schema:t.parameters}}function yn(t,e){if(!t)return{...e};let n={...t};return e.input_tokens!=null&&(n.input_tokens=e.input_tokens),e.output_tokens!=null&&(n.output_tokens=e.output_tokens),e.cache_read_input_tokens!=null&&(n.cache_read_input_tokens=e.cache_read_input_tokens),e.cache_creation_input_tokens!=null&&(n.cache_creation_input_tokens=e.cache_creation_input_tokens),e.cache_creation&&(n.cache_creation={...t.cache_creation??{},...e.cache_creation}),e.server_tool_use&&(n.server_tool_use={...t.server_tool_use??{},...e.server_tool_use}),n}function Tr(t){let e={input:{regular:t?.input_tokens??0},output:{regular:t?.output_tokens??0},raw:t};return t?.cache_read_input_tokens&&(e.input.cacheRead=t.cache_read_input_tokens),t?.cache_creation?(t.cache_creation.ephemeral_5m_input_tokens&&(e.input.cacheWrite5m=t.cache_creation.ephemeral_5m_input_tokens),t.cache_creation.ephemeral_1h_input_tokens&&(e.input.cacheWrite1h=t.cache_creation.ephemeral_1h_input_tokens)):t?.cache_creation_input_tokens&&(e.input.cacheWrite5m=t.cache_creation_input_tokens),t?.server_tool_use?.web_search_requests&&(e.auxiliary={webSearchRequests:t.server_tool_use.web_search_requests}),e}function ms(t,e){let n=[],r=[];for(let o of t.content)if(o.type==="text"&&typeof o.text=="string")n.push(o.text);else if(o.type==="tool_use"){let s=o;r.push({id:s.id,name:s.name,arguments:s.input??{}})}return{content:n.join(""),toolCalls:r.length>0?r:void 0,usage:Tr(t.usage),finishReason:t.stop_reason,latencyMs:e,model:t.model,provider:"anthropic"}}function fa(t){let e=t.apiKey??globalThis.process?.env?.ANTHROPIC_API_KEY,n=t.baseURL??"https://api.anthropic.com",r=t.anthropicVersion??"2023-06-01",o=t.fetchImpl??fetch,s=()=>{if(!e)throw new Error("anthropicAdapter: apiKey required for invoke/stream (or provide opts.sdk)");return{"x-api-key":e,"anthropic-version":r,"content-type":"application/json",...t.headers??{}}};return{provider:"anthropic",model:t.model,async invoke(a,i){let d=hn(a,i,t.model,!1),u=z(),c=await o(`${n}/v1/messages`,{method:"POST",headers:s(),body:JSON.stringify(d),signal:i?.signal});if(!c.ok)throw await ze(c,"Anthropic");let l=await c.json(),p=Math.max(0,(z()-u)/1e6);return ms(l,p)},async*stream(a,i){let d=hn(a,i,t.model,!0),u=await o(`${n}/v1/messages`,{method:"POST",headers:{...s(),accept:"text/event-stream"},body:JSON.stringify(d),signal:i?.signal});if(!u.ok)throw await ze(u,"Anthropic");if(!u.body)throw new Error("anthropicAdapter: streaming response has no body");let c,l,p=new Map;for await(let f of Tt(u.body,{signal:i?.signal})){let m=f.data;if(!m)continue;let h;try{h=JSON.parse(m)}catch{continue}switch(h.type){case"message_start":{c=yn(c,h.message.usage);break}case"content_block_start":{let g=h,b=g.content_block;b.type==="tool_use"&&(p.set(g.index,{id:String(b.id??""),name:String(b.name??""),argBuf:""}),yield{type:"tool-call-delta",delta:{id:String(b.id??""),name:String(b.name??"")}});break}case"content_block_delta":{let g=h,b=g.delta;if(b.type==="text_delta"&&typeof b.text=="string")yield{type:"token",delta:b.text};else if(b.type==="input_json_delta"&&typeof b.partial_json=="string"){let T=p.get(g.index);T&&(T.argBuf+=b.partial_json),yield{type:"tool-call-delta",delta:{argumentsDelta:b.partial_json}}}else b.type==="thinking_delta"&&typeof b.thinking=="string"&&(yield{type:"thinking",delta:b.thinking});break}case"message_delta":{let g=h;g.delta.stop_reason&&(l=g.delta.stop_reason),g.delta.usage&&(c=yn(c,g.delta.usage));break}case"message_stop":break}}c&&(yield{type:"usage",usage:Tr(c)}),yield{type:"finish",reason:l??"stop"}}}}function ma(t){let e=t.sdk;if(!e)throw new Error("sdkBackedAnthropic: sdk instance required");return{provider:"anthropic",model:t.model,async invoke(n,r){let o=hn(n,r,t.model,!1),s=z(),a=await e.messages.create(o,{signal:r?.signal}),i=Math.max(0,(z()-s)/1e6);return ms(a,i)},async*stream(n,r){if(!e.messages.stream)throw new Error("sdkBackedAnthropic: SDK instance does not expose .messages.stream");let o=hn(n,r,t.model,!0),s,a;for await(let i of e.messages.stream(o,{signal:r?.signal}))switch(i.type){case"message_start":s=yn(s,i.message.usage);break;case"content_block_delta":{let d=i.delta;d?.type==="text_delta"&&typeof d.text=="string"?yield{type:"token",delta:d.text}:d?.type==="input_json_delta"&&typeof d.partial_json=="string"?yield{type:"tool-call-delta",delta:{argumentsDelta:d.partial_json}}:d?.type==="thinking_delta"&&typeof d.thinking=="string"&&(yield{type:"thinking",delta:d.thinking});break}case"message_delta":{let d=i;d.delta.stop_reason&&(a=d.delta.stop_reason),d.delta.usage&&(s=yn(s,d.delta.usage));break}}s&&(yield{type:"usage",usage:Tr(s)}),yield{type:"finish",reason:a??"stop"}}}}Ve();function bn(){let t=new Error("aborted");return t.name="AbortError",t}function gs(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(bn()):new Promise((n,r)=>{let o=new ge,s,a=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{a(),n()}),e&&(s=()=>{a(),r(bn())},e.addEventListener("abort",s,{once:!0}))})}function at(t={}){let e=t.provider??"dry-run",n=t.model??"dry-run-v1",r=t.latencyMs??0,o=Math.max(1,t.streamChunkSize??16),s=t.respond??(i=>{let d=[...i].reverse().find(u=>u.role==="user");return d?`echo: ${d.content}`:"dry-run: no user message"}),a=t.usage??((i,d)=>{let u=i.reduce((c,l)=>c+l.content.length,0);return{input:{regular:Math.ceil(u/4)},output:{regular:Math.ceil(d.length/4)}}});return{provider:e,model:n,async invoke(i,d){if(await gs(r,d?.signal),d?.signal?.aborted)throw bn();let u=s(i,d),c=a(i,u);return{content:u,usage:c,finishReason:"stop",model:d?.model??n,provider:e,tier:d?.tier,metadata:{dryRun:!0}}},async*stream(i,d){let u=s(i,d),c=a(i,u),l=Math.ceil(u.length/o)||1,p=r>0?r/l:0;for(let f=0;f<u.length;f+=o){if(d?.signal?.aborted)throw bn();await gs(p,d?.signal),yield{type:"token",delta:u.slice(f,f+o)}}yield{type:"usage",usage:c},yield{type:"finish",reason:"stop"}}}}ye();async function Tn(t){let e=typeof t=="string"?new TextEncoder().encode(t):t,n=await globalThis.crypto.subtle.digest("SHA-256",e),r=new Uint8Array(n),o="";for(let s=0;s<r.length;s++)o+=hs[r[s]];return o}var hs=new Array(256);for(let t=0;t<256;t++)hs[t]=t.toString(16).padStart(2,"0");function vr(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(vr);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=vr(e[o]);return r}function ys(t){return JSON.stringify(vr(t),void 0,0)}var ga=new TextEncoder,ha=new TextDecoder("utf-8",{fatal:!0}),ya={name:"json",version:1,encode(t){return ga.encode(ys(t))},decode(t){return JSON.parse(ha.decode(t))}};function ba(){let t=new Map;return{name:"memory",read(e){let n=t.get(e);return n===void 0?void 0:new Uint8Array(n)},write(e,n){t.set(e,new Uint8Array(n))},delete(e){t.delete(e)},list(e){let n=[...t.keys()];return e?n.filter(r=>r.startsWith(e)).sort():n.sort()}}}function Ta(t,e={}){let n=e.codec??ya,r=e.name??t.name??"kv",o=e.compactEvery,s=new Map,a=0,i={name:r,debounceMs:e.debounceMs,compactEvery:o,filter:e.filter,save(u,c){if(!(e.filter&&!e.filter(u,c))&&(s.set(u,c),a+=1,o!==void 0&&a%o===0||!e.debounceMs))return d()},load(u){let c=t.read(u);if(c!==void 0)return c instanceof Uint8Array?c.length===0?void 0:n.decode(c):Promise.resolve(c).then(l=>l===void 0||l.length===0?void 0:n.decode(l))},delete(u){if(s.delete(u),!!t.delete)return t.delete(u)},list(u){return t.list?t.list(u):[]},async flush(){await d()},async rollback(){s=new Map}};function d(){if(s.size===0)return;let u=s;s=new Map;let c=[];for(let[l,p]of u){let f=n.encode(p),m=t.write(l,f);m instanceof Promise&&c.push(m)}if(c.length>0)return Promise.all(c).then(()=>{})}return i}function wr(t){return Ta(ba(),t)}ye();var kr=class extends Error{constructor(n,r){super(`content-addressed lookup miss in read-strict mode: ${n}`);this.key=n;this.context=r;this.name="ContentAddressedMissError"}};function xr(t){let e=new Set,n=r=>{if(r===null||typeof r!="object")return r;let o=r;if(e.has(o))return{__cycle:!0};e.add(o);try{if(Array.isArray(r))return r.map(n);let s={};for(let a of Object.keys(r).sort())s[a]=n(r[a]);return s}finally{e.delete(o)}};return JSON.stringify(n(t))}function bs(t){let{storage:e,keyContext:n,keyPrefix:r,mode:o="read-write"}=t,s=n??(i=>i);async function a(i){let d=xr(s(i)),u=await Tn(d);return r?`${r}:${u}`:u}return{keyFor:a,async lookup(i){if(o==="write")return;let d=await a(i),u=await e.load(d);if(u===void 0){if(o==="read-strict")throw new kr(d,i);return}return u},async store(i,d){if(o==="read")return;let u=await a(i);await e.save(u,d)},async forget(i){if(o==="read"||o==="write"||!e.delete)return;let d=await a(i);await e.delete(d)}}}Z();function Ts(t,e={}){let n=e.keyFn??(o=>String(o)),r=new Map;return o=>{let s=n(o),a=r.get(s);if(a)return a;let i=t(o),d;i!=null&&typeof i.then=="function"?d=Promise.resolve(i):i!=null&&typeof i=="object"&&"subscribe"in i&&"cache"in i?d=_e(i):i!=null&&typeof i=="object"&&Symbol.asyncIterator in i?d=(async()=>{let l=i[Symbol.asyncIterator]();try{let{value:p,done:f}=await l.next();if(f)throw new Error("singleFromAny: factory returned empty async iterable");return p}finally{await l.return?.()}})():i!=null&&typeof i=="object"&&Symbol.iterator in i?d=(async()=>{let l=i[Symbol.iterator]();try{let{value:p,done:f}=l.next();if(f)throw new Error("singleFromAny: factory returned empty iterable");return p}finally{l.return?.()}})():d=Promise.resolve(i);let u,c=()=>{r.get(s)===u&&r.delete(s)};return u=d.then(l=>(c(),l),l=>{throw c(),l}),r.set(s,u),u}}Z();Ve();function vs(t){let{storage:e,mode:n="read-write",keyFn:r,keyPrefix:o="llm-replay"}=t,a=bs({storage:e,keyPrefix:o,mode:n==="read-strict"?"read":n,keyContext:({messages:d,opts:u})=>{let{signal:c,keyContext:l,...p}=u??{};return{messages:d,opts:p}}});async function i(d,u){if(r){if(r.length<=1){let l={messages:d,opts:u,context:u?.keyContext},p=await r(l);return`${o}:${p}`}let c=await r(d,u);return`${o}:${c}`}return a.keyFor({messages:d,opts:u})}return{keyFor:i,async lookup(d,u){if(n!=="write"){if(r){let c=await i(d,u),l=await e.load(c);return l===void 0?void 0:l}return a.lookup({messages:d,opts:u})}},async store(d,u,c){if(n!=="read"){if(r){let l=await i(d,u);await e.save(l,c);return}await a.store({messages:d,opts:u},c)}},async forget(d,u){if(!(n==="read"||n==="write")&&e.delete){if(r){let c=await i(d,u);await e.delete(c);return}await a.forget({messages:d,opts:u})}}}}ye();de();Q();Ie();Z();function ve(t,e,n){return{provider:n?.provider??t.provider,model:n?.model??t.model,capabilities:n?.capabilities??t.capabilities?.bind(t),invoke:e.invoke,stream:e.stream}}function vn(t,e){let{onResp:n,onError:r,name:o}=e;if(t!=null&&typeof t.then=="function"){let u=t;return r?u.then(n).catch(c=>{throw r(c),c}):u.then(n)}if(t!=null&&typeof t=="object"&&"content"in t)return n(t);let s=V(t);if(r){let u=!1;s.subscribe(c=>{for(let l of c){if(u)return;l[0]===P&&(u=!0,r(l[1]))}})}let a,i=!1,d=cs(s,u=>{a=n(u),i=!0});return A([d],([u])=>u==null?null:i?a:n(u),{name:o??"adapt/invokeTap"})}function dt(t){let e=t.endNs??z();return{timestamp:e,wallClock:t.startWallClockNs??ce(),provider:t.provider,model:t.model,tier:t.tier,usage:t.usage,latencyMs:Math.max(0,(e-t.startNs)/1e6),method:t.method,...t.error?{error:t.error}:{}}}function $e(){return{input:{regular:0},output:{regular:0}}}var ws=Symbol.for("graphrefly.adapter.middlewareLayers");function Te(t,e,n){let o=[...n?va(n):[],e];return Object.defineProperty(t,ws,{value:Object.freeze(o),enumerable:!1,writable:!1,configurable:!1}),t}function va(t){let e=t[ws];return Array.isArray(e)?e:[]}var ut=class extends Error{constructor(n,r){super(`withReplayCache: no cached response for ${r} (key=${n}, mode=read-strict)`);this.key=n;this.method=r}name="ReplayCacheMissError"};function It(t,e){let n=e.mode??"read-write",r=e.cacheStreaming??!1,o=e.captureStreamCadence??!1,s=e.replaySpeed??1,a=e.keyPrefix??"llm-replay",i=n==="read"||n==="read-strict",d=vs({storage:e.storage,mode:n==="write-only"?"write":n,keyFn:e.keyFn,keyPrefix:a}),u=p=>p<=0?Promise.resolve():new Promise(f=>{new ge().start(p,()=>f())}),c=Ts(async({messages:p,invokeOpts:f})=>await _e(V(t.invoke(p,f))),{keyFn:({_precomputedKey:p})=>p}),l=ve(t,{async invoke(p,f){let m=await d.keyFor(p,f),h=await d.lookup(p,f);if(h?.response){let b=h.response;return{...b,metadata:{...b.metadata??{},replayCache:"hit"}}}if(n==="read-strict")throw new ut(m,"invoke");let g=await c({messages:p,invokeOpts:f,_precomputedKey:m});return i||await d.store(p,f,{response:g,storedAtNs:ce()}),g},async*stream(p,f){if(!r){for await(let N of t.stream(p,f))yield N;return}let m=await d.keyFor(p,f),h=await d.lookup(p,f);if(h){let N=h.response;if(h.streamChunks&&h.streamCadenceMs)for(let w=0;w<h.streamChunks.length;w++){let R=h.streamCadenceMs[w]??0,x=s>0?R/s:0;x>0&&await u(x),yield{type:"token",delta:h.streamChunks[w]?.delta??""}}else N.content&&(yield{type:"token",delta:N.content});N.usage&&(yield{type:"usage",usage:N.usage}),yield{type:"finish",reason:N.finishReason??"stop"};return}if(n==="read-strict")throw new ut(m,"stream");let g="",b,T,y=[],v=[],k;for await(let N of t.stream(p,f)){if(N.type==="token"&&(g+=N.delta,o)){let w=z(),R=k===void 0?0:(w-k)/1e6;v.push(R),k=w,y.push({delta:N.delta})}N.type==="usage"&&(b=N.usage),N.type==="finish"&&(T=N.reason),yield N}if((g||b)&&!i){let w={response:{content:g,usage:b??{input:{regular:0},output:{regular:0}},finishReason:T,model:t.model??f?.model??"",provider:t.provider},storedAtNs:ce(),...o?{streamChunks:y,streamCadenceMs:v}:{}};await d.store(p,f,w)}}});return Te(l,"withReplayCache",t),l}var Rr=xr;var wa=ut;function ks(t,e){return{content:"[fallback: no cached response available for this request]",usage:{input:{regular:0},output:{regular:0}},finishReason:"stop",model:e,provider:t,metadata:{degraded:!0,reason:"no-fixture"}}}function xs(t,e,n){return typeof t=="string"?{content:t,usage:{input:{regular:0},output:{regular:0}},finishReason:"stop",model:n,provider:e,metadata:{degraded:!0,reason:"respond"}}:t}async function ka(t,e){if("key"in t)return t.key;let n=Rr({messages:t.messages,opts:t.invokeOpts??{}}),r=await Tn(n);return`${e}:${r}`}function xa(t){let e={response:t.response,storedAtNs:ce()};if("key"in t&&t.stream){let n=t.stream.chunks.filter(r=>r.type==="token");return{...e,streamChunks:n.map(r=>({delta:r.delta})),streamCadenceMs:t.stream.delaysMs??n.map(()=>0)}}return e}function Ra(t,e){let n=[];if(t.fixtures!=null&&n.push("fixtures"),t.fixturesStorage!=null&&n.push("fixturesStorage"),n.length>1)throw new TypeError(`fallbackAdapter: \`fixtures\` and \`fixturesStorage\` are mutually exclusive; got both ${n.join(" and ")}. Pick one source. For filesystem directories use the node subpath's \`fallbackAdapter\`.`);if(t.fixtures){let r=wr(),o=t.fixtures,s=(async()=>{for(let a of o){let i=await ka(a,e);await r.save(i,xa(a))}})();return s.catch(()=>{}),{tier:r,seedReady:s}}return t.fixturesStorage?{tier:t.fixturesStorage,seedReady:Promise.resolve()}:{tier:void 0,seedReady:Promise.resolve()}}function Sr(t={}){let e=t.provider??"fallback",n=t.model??"fallback",r=t.onMiss??"respond",o=t.keyPrefix??"fallback",s=t.record?t.record.adapter:r==="throw"?at({provider:e,model:n,respond:()=>"[unreachable: read-strict mode throws on miss]"}):{provider:e,model:n,async invoke(c,l){let p=t.respond?t.respond(c,l):ks(e,n);return xs(p,e,n)},async*stream(c,l){let p=t.respond?t.respond(c,l):ks(e,n),f=xs(p,e,n);yield{type:"token",delta:f.content},f.usage&&(yield{type:"usage",usage:f.usage}),yield{type:"finish",reason:f.finishReason??"stop"}}},a,i=Promise.resolve();if(t.record){if(!t.record.storage)throw new TypeError("fallbackAdapter: `record.storage` is required in record mode. For filesystem `record.dir` convenience, use the node subpath's `fallbackAdapter`.");a=t.record.storage}else{let c=Ra(t,o);a=c.tier??wr(),i=c.seedReady}let d=t.record?"read-write":r==="throw"?"read-strict":"read",u=It(s,{storage:a,mode:d,keyPrefix:o,cacheStreaming:!0,captureStreamCadence:!0,replaySpeed:t.replaySpeed,...t.keyFn?{keyFn:t.keyFn}:{}});return{provider:e,model:n,capabilities:u.capabilities?.bind(u),async invoke(c,l){return await i,u.invoke(c,l)},async*stream(c,l){await i;for await(let p of u.stream(c,l))yield p}}}ye();function Nr(t={}){return t.sdk?Ma(t):_a(t)}function wn(t,e){let n=[],r=[];e?.systemPrompt&&n.push(e.systemPrompt);for(let a of t){if(a.role==="system"){n.push(a.content);continue}if(a.role==="tool"){r.push({role:"user",parts:[{functionResponse:{name:a.name??a.toolCallId??"tool",response:{result:a.content}}}]});continue}if(a.role==="assistant"&&a.toolCalls&&a.toolCalls.length>0){let i=[];a.content&&i.push({text:a.content});for(let d of a.toolCalls)i.push({functionCall:{name:d.name,args:d.arguments}});r.push({role:"model",parts:i});continue}r.push({role:a.role==="assistant"?"model":"user",parts:[{text:a.content}]})}let o={contents:r};n.length>0&&(o.systemInstruction={role:"system",parts:[{text:n.join(`
6
+ `):void 0,chat:r}}function fa(t){if(t.role==="tool")return{role:"user",content:[{type:"tool_result",tool_use_id:t.toolCallId,content:t.content}]};if(t.role==="assistant"&&t.toolCalls&&t.toolCalls.length>0){let e=[];t.content&&e.push({type:"text",text:t.content});for(let n of t.toolCalls)e.push({type:"tool_use",id:n.id,name:n.name,input:n.arguments});return{role:"assistant",content:e}}return{role:t.role,content:t.content}}function ma(t){return{name:t.name,description:t.description,input_schema:t.parameters}}function wn(t,e){if(!t)return{...e};let n={...t};return e.input_tokens!=null&&(n.input_tokens=e.input_tokens),e.output_tokens!=null&&(n.output_tokens=e.output_tokens),e.cache_read_input_tokens!=null&&(n.cache_read_input_tokens=e.cache_read_input_tokens),e.cache_creation_input_tokens!=null&&(n.cache_creation_input_tokens=e.cache_creation_input_tokens),e.cache_creation&&(n.cache_creation={...t.cache_creation??{},...e.cache_creation}),e.server_tool_use&&(n.server_tool_use={...t.server_tool_use??{},...e.server_tool_use}),n}function Rr(t){let e={input:{regular:t?.input_tokens??0},output:{regular:t?.output_tokens??0},raw:t};return t?.cache_read_input_tokens&&(e.input.cacheRead=t.cache_read_input_tokens),t?.cache_creation?(t.cache_creation.ephemeral_5m_input_tokens&&(e.input.cacheWrite5m=t.cache_creation.ephemeral_5m_input_tokens),t.cache_creation.ephemeral_1h_input_tokens&&(e.input.cacheWrite1h=t.cache_creation.ephemeral_1h_input_tokens)):t?.cache_creation_input_tokens&&(e.input.cacheWrite5m=t.cache_creation_input_tokens),t?.server_tool_use?.web_search_requests&&(e.auxiliary={webSearchRequests:t.server_tool_use.web_search_requests}),e}function bs(t,e){let n=[],r=[];for(let o of t.content)if(o.type==="text"&&typeof o.text=="string")n.push(o.text);else if(o.type==="tool_use"){let s=o;r.push({id:s.id,name:s.name,arguments:s.input??{}})}return{content:n.join(""),toolCalls:r.length>0?r:void 0,usage:Rr(t.usage),finishReason:t.stop_reason,latencyMs:e,model:t.model,provider:"anthropic"}}function ga(t){let e=t.apiKey??globalThis.process?.env?.ANTHROPIC_API_KEY,n=t.baseURL??"https://api.anthropic.com",r=t.anthropicVersion??"2023-06-01",o=t.fetchImpl??fetch,s=()=>{if(!e)throw new Error("anthropicAdapter: apiKey required for invoke/stream (or provide opts.sdk)");return{"x-api-key":e,"anthropic-version":r,"content-type":"application/json",...t.headers??{}}};return{provider:"anthropic",model:t.model,async invoke(a,i){let d=vn(a,i,t.model,!1),u=z(),c=await o(`${n}/v1/messages`,{method:"POST",headers:s(),body:JSON.stringify(d),signal:i?.signal});if(!c.ok)throw await qe(c,"Anthropic");let l=await c.json(),p=Math.max(0,(z()-u)/1e6);return bs(l,p)},async*stream(a,i){let d=vn(a,i,t.model,!0),u=await o(`${n}/v1/messages`,{method:"POST",headers:{...s(),accept:"text/event-stream"},body:JSON.stringify(d),signal:i?.signal});if(!u.ok)throw await qe(u,"Anthropic");if(!u.body)throw new Error("anthropicAdapter: streaming response has no body");let c,l,p=new Map;for await(let f of wt(u.body,{signal:i?.signal})){let m=f.data;if(!m)continue;let h;try{h=JSON.parse(m)}catch{continue}switch(h.type){case"message_start":{c=wn(c,h.message.usage);break}case"content_block_start":{let g=h,y=g.content_block;y.type==="tool_use"&&(p.set(g.index,{id:String(y.id??""),name:String(y.name??""),argBuf:""}),yield{type:"tool-call-delta",delta:{id:String(y.id??""),name:String(y.name??"")}});break}case"content_block_delta":{let g=h,y=g.delta;if(y.type==="text_delta"&&typeof y.text=="string")yield{type:"token",delta:y.text};else if(y.type==="input_json_delta"&&typeof y.partial_json=="string"){let v=p.get(g.index);v&&(v.argBuf+=y.partial_json),yield{type:"tool-call-delta",delta:{argumentsDelta:y.partial_json}}}else y.type==="thinking_delta"&&typeof y.thinking=="string"&&(yield{type:"thinking",delta:y.thinking});break}case"message_delta":{let g=h;g.delta.stop_reason&&(l=g.delta.stop_reason),g.delta.usage&&(c=wn(c,g.delta.usage));break}case"message_stop":break}}c&&(yield{type:"usage",usage:Rr(c)}),yield{type:"finish",reason:l??"stop"}}}}function ha(t){let e=t.sdk;if(!e)throw new Error("sdkBackedAnthropic: sdk instance required");return{provider:"anthropic",model:t.model,async invoke(n,r){let o=vn(n,r,t.model,!1),s=z(),a=await e.messages.create(o,{signal:r?.signal}),i=Math.max(0,(z()-s)/1e6);return bs(a,i)},async*stream(n,r){if(!e.messages.stream)throw new Error("sdkBackedAnthropic: SDK instance does not expose .messages.stream");let o=vn(n,r,t.model,!0),s,a;for await(let i of e.messages.stream(o,{signal:r?.signal}))switch(i.type){case"message_start":s=wn(s,i.message.usage);break;case"content_block_delta":{let d=i.delta;d?.type==="text_delta"&&typeof d.text=="string"?yield{type:"token",delta:d.text}:d?.type==="input_json_delta"&&typeof d.partial_json=="string"?yield{type:"tool-call-delta",delta:{argumentsDelta:d.partial_json}}:d?.type==="thinking_delta"&&typeof d.thinking=="string"&&(yield{type:"thinking",delta:d.thinking});break}case"message_delta":{let d=i;d.delta.stop_reason&&(a=d.delta.stop_reason),d.delta.usage&&(s=wn(s,d.delta.usage));break}}s&&(yield{type:"usage",usage:Rr(s)}),yield{type:"finish",reason:a??"stop"}}}}ze();function kn(){let t=new Error("aborted");return t.name="AbortError",t}function Ts(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(kn()):new Promise((n,r)=>{let o=new ge,s,a=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{a(),n()}),e&&(s=()=>{a(),r(kn())},e.addEventListener("abort",s,{once:!0}))})}function ut(t={}){let e=t.provider??"dry-run",n=t.model??"dry-run-v1",r=t.latencyMs??0,o=Math.max(1,t.streamChunkSize??16),s=t.respond??(i=>{let d=[...i].reverse().find(u=>u.role==="user");return d?`echo: ${d.content}`:"dry-run: no user message"}),a=t.usage??((i,d)=>{let u=i.reduce((c,l)=>c+l.content.length,0);return{input:{regular:Math.ceil(u/4)},output:{regular:Math.ceil(d.length/4)}}});return{provider:e,model:n,async invoke(i,d){if(await Ts(r,d?.signal),d?.signal?.aborted)throw kn();let u=s(i,d),c=a(i,u);return{content:u,usage:c,finishReason:"stop",model:d?.model??n,provider:e,tier:d?.tier,metadata:{dryRun:!0}}},async*stream(i,d){let u=s(i,d),c=a(i,u),l=Math.ceil(u.length/o)||1,p=r>0?r/l:0;for(let f=0;f<u.length;f+=o){if(d?.signal?.aborted)throw kn();await Ts(p,d?.signal),yield{type:"token",delta:u.slice(f,f+o)}}yield{type:"usage",usage:c},yield{type:"finish",reason:"stop"}}}}ye();async function xn(t){let e=typeof t=="string"?new TextEncoder().encode(t):t,n=await globalThis.crypto.subtle.digest("SHA-256",e),r=new Uint8Array(n),o="";for(let s=0;s<r.length;s++)o+=vs[r[s]];return o}var vs=new Array(256);for(let t=0;t<256;t++)vs[t]=t.toString(16).padStart(2,"0");function Nr(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(Nr);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=Nr(e[o]);return r}function ws(t){return JSON.stringify(Nr(t),void 0,0)}var ya=new TextEncoder,ba=new TextDecoder("utf-8",{fatal:!0}),Ta={name:"json",version:1,encode(t){return ya.encode(ws(t))},decode(t){return JSON.parse(ba.decode(t))}};function va(){let t=new Map;return{name:"memory",read(e){let n=t.get(e);return n===void 0?void 0:new Uint8Array(n)},write(e,n){t.set(e,new Uint8Array(n))},delete(e){t.delete(e)},list(e){let n=[...t.keys()];return e?n.filter(r=>r.startsWith(e)).sort():n.sort()}}}function wa(t,e={}){let n=e.codec??Ta,r=e.name??t.name??"kv",o=e.compactEvery,s=new Map,a=0,i={name:r,debounceMs:e.debounceMs,compactEvery:o,filter:e.filter,save(u,c){if(!(e.filter&&!e.filter(u,c))&&(s.set(u,c),a+=1,o!==void 0&&a%o===0||!e.debounceMs))return d()},load(u){let c=t.read(u);if(c!==void 0)return c instanceof Uint8Array?c.length===0?void 0:n.decode(c):Promise.resolve(c).then(l=>l===void 0||l.length===0?void 0:n.decode(l))},delete(u){if(s.delete(u),!!t.delete)return t.delete(u)},list(u){return t.list?t.list(u):[]},async flush(){await d()},async rollback(){s=new Map}};function d(){if(s.size===0)return;let u=s;s=new Map;let c=[];for(let[l,p]of u){let f=n.encode(p),m=t.write(l,f);m instanceof Promise&&c.push(m)}if(c.length>0)return Promise.all(c).then(()=>{})}return i}function Sr(t){return wa(va(),t)}ye();var _r=class extends Error{constructor(n,r){super(`content-addressed lookup miss in read-strict mode: ${n}`);this.key=n;this.context=r;this.name="ContentAddressedMissError"}};function Mr(t){let e=new Set,n=r=>{if(r===null||typeof r!="object")return r;let o=r;if(e.has(o))return{__cycle:!0};e.add(o);try{if(Array.isArray(r))return r.map(n);let s={};for(let a of Object.keys(r).sort())s[a]=n(r[a]);return s}finally{e.delete(o)}};return JSON.stringify(n(t))}function ks(t){let{storage:e,keyContext:n,keyPrefix:r,mode:o="read-write"}=t,s=n??(i=>i);async function a(i){let d=Mr(s(i)),u=await xn(d);return r?`${r}:${u}`:u}return{keyFor:a,async lookup(i){if(o==="write")return;let d=await a(i),u=await e.load(d);if(u===void 0){if(o==="read-strict")throw new _r(d,i);return}return u},async store(i,d){if(o==="read")return;let u=await a(i);await e.save(u,d)},async forget(i){if(o==="read"||o==="write"||!e.delete)return;let d=await a(i);await e.delete(d)}}}Z();function xs(t,e={}){let n=e.keyFn??(o=>String(o)),r=new Map;return o=>{let s=n(o),a=r.get(s);if(a)return a;let i=t(o),d;i!=null&&typeof i.then=="function"?d=Promise.resolve(i):i!=null&&typeof i=="object"&&"subscribe"in i&&"cache"in i?d=Me(i):i!=null&&typeof i=="object"&&Symbol.asyncIterator in i?d=(async()=>{let l=i[Symbol.asyncIterator]();try{let{value:p,done:f}=await l.next();if(f)throw new Error("singleFromAny: factory returned empty async iterable");return p}finally{await l.return?.()}})():i!=null&&typeof i=="object"&&Symbol.iterator in i?d=(async()=>{let l=i[Symbol.iterator]();try{let{value:p,done:f}=l.next();if(f)throw new Error("singleFromAny: factory returned empty iterable");return p}finally{l.return?.()}})():d=Promise.resolve(i);let u,c=()=>{r.get(s)===u&&r.delete(s)};return u=d.then(l=>(c(),l),l=>{throw c(),l}),r.set(s,u),u}}Z();ze();function Rs(t){let{storage:e,mode:n="read-write",keyFn:r,keyPrefix:o="llm-replay"}=t,a=ks({storage:e,keyPrefix:o,mode:n==="read-strict"?"read":n,keyContext:({messages:d,opts:u})=>{let{signal:c,keyContext:l,...p}=u??{};return{messages:d,opts:p}}});async function i(d,u){if(r){if(r.length<=1){let l={messages:d,opts:u,context:u?.keyContext},p=await r(l);return`${o}:${p}`}let c=await r(d,u);return`${o}:${c}`}return a.keyFor({messages:d,opts:u})}return{keyFor:i,async lookup(d,u){if(n!=="write"){if(r){let c=await i(d,u),l=await e.load(c);return l===void 0?void 0:l}return a.lookup({messages:d,opts:u})}},async store(d,u,c){if(n!=="read"){if(r){let l=await i(d,u);await e.save(l,c);return}await a.store({messages:d,opts:u},c)}},async forget(d,u){if(!(n==="read"||n==="write")&&e.delete){if(r){let c=await i(d,u);await e.delete(c);return}await a.forget({messages:d,opts:u})}}}}ye();ie();Q();Pe();Z();function we(t,e,n){return{provider:n?.provider??t.provider,model:n?.model??t.model,capabilities:n?.capabilities??t.capabilities?.bind(t),invoke:e.invoke,stream:e.stream}}function Rn(t,e){let{onResp:n,onError:r,name:o}=e;if(t!=null&&typeof t.then=="function"){let u=t;return r?u.then(n).catch(c=>{throw r(c),c}):u.then(n)}if(t!=null&&typeof t=="object"&&"content"in t)return n(t);let s=j(t);if(r){let u=!1;s.subscribe(c=>{for(let l of c){if(u)return;l[0]===P&&(u=!0,r(l[1]))}})}let a,i=!1,d=ms(s,u=>{a=n(u),i=!0});return C([d],([u])=>u==null?null:i?a:n(u),{name:o??"adapt/invokeTap"})}function ct(t){let e=t.endNs??z();return{timestamp:e,wallClock:t.startWallClockNs??ce(),provider:t.provider,model:t.model,tier:t.tier,usage:t.usage,latencyMs:Math.max(0,(e-t.startNs)/1e6),method:t.method,...t.error?{error:t.error}:{}}}function Be(){return{input:{regular:0},output:{regular:0}}}var Ns=Symbol.for("graphrefly.adapter.middlewareLayers");function Te(t,e,n){let o=[...n?ka(n):[],e];return Object.defineProperty(t,Ns,{value:Object.freeze(o),enumerable:!1,writable:!1,configurable:!1}),t}function ka(t){let e=t[Ns];return Array.isArray(e)?e:[]}var lt=class extends Error{constructor(n,r){super(`withReplayCache: no cached response for ${r} (key=${n}, mode=read-strict)`);this.key=n;this.method=r}name="ReplayCacheMissError"};function Gt(t,e){let n=e.mode??"read-write",r=e.cacheStreaming??!1,o=e.captureStreamCadence??!1,s=e.replaySpeed??1,a=e.keyPrefix??"llm-replay",i=n==="read"||n==="read-strict",d=Rs({storage:e.storage,mode:n==="write-only"?"write":n,keyFn:e.keyFn,keyPrefix:a}),u=p=>p<=0?Promise.resolve():new Promise(f=>{new ge().start(p,()=>f())}),c=xs(async({messages:p,invokeOpts:f})=>await Me(j(t.invoke(p,f))),{keyFn:({_precomputedKey:p})=>p}),l=we(t,{async invoke(p,f){let m=await d.keyFor(p,f),h=await d.lookup(p,f);if(h?.response){let y=h.response;return{...y,metadata:{...y.metadata??{},replayCache:"hit"}}}if(n==="read-strict")throw new lt(m,"invoke");let g=await c({messages:p,invokeOpts:f,_precomputedKey:m});return i||await d.store(p,f,{response:g,storedAtNs:ce()}),g},async*stream(p,f){if(!r){for await(let S of t.stream(p,f))yield S;return}let m=await d.keyFor(p,f),h=await d.lookup(p,f);if(h){let S=h.response;if(h.streamChunks&&h.streamCadenceMs)for(let T=0;T<h.streamChunks.length;T++){let x=h.streamCadenceMs[T]??0,N=s>0?x/s:0;N>0&&await u(N),yield{type:"token",delta:h.streamChunks[T]?.delta??""}}else S.content&&(yield{type:"token",delta:S.content});S.usage&&(yield{type:"usage",usage:S.usage}),yield{type:"finish",reason:S.finishReason??"stop"};return}if(n==="read-strict")throw new lt(m,"stream");let g="",y,v,b=[],w=[],k;for await(let S of t.stream(p,f)){if(S.type==="token"&&(g+=S.delta,o)){let T=z(),x=k===void 0?0:(T-k)/1e6;w.push(x),k=T,b.push({delta:S.delta})}S.type==="usage"&&(y=S.usage),S.type==="finish"&&(v=S.reason),yield S}if((g||y)&&!i){let T={response:{content:g,usage:y??{input:{regular:0},output:{regular:0}},finishReason:v,model:t.model??f?.model??"",provider:t.provider},storedAtNs:ce(),...o?{streamChunks:b,streamCadenceMs:w}:{}};await d.store(p,f,T)}}});return Te(l,"withReplayCache",t),l}var Or=Mr;var xa=lt;function Ss(t,e){return{content:"[fallback: no cached response available for this request]",usage:{input:{regular:0},output:{regular:0}},finishReason:"stop",model:e,provider:t,metadata:{degraded:!0,reason:"no-fixture"}}}function _s(t,e,n){return typeof t=="string"?{content:t,usage:{input:{regular:0},output:{regular:0}},finishReason:"stop",model:n,provider:e,metadata:{degraded:!0,reason:"respond"}}:t}async function Ra(t,e){if("key"in t)return t.key;let n=Or({messages:t.messages,opts:t.invokeOpts??{}}),r=await xn(n);return`${e}:${r}`}function Na(t){let e={response:t.response,storedAtNs:ce()};if("key"in t&&t.stream){let n=t.stream.chunks.filter(r=>r.type==="token");return{...e,streamChunks:n.map(r=>({delta:r.delta})),streamCadenceMs:t.stream.delaysMs??n.map(()=>0)}}return e}function Sa(t,e){let n=[];if(t.fixtures!=null&&n.push("fixtures"),t.fixturesStorage!=null&&n.push("fixturesStorage"),n.length>1)throw new TypeError(`fallbackAdapter: \`fixtures\` and \`fixturesStorage\` are mutually exclusive; got both ${n.join(" and ")}. Pick one source. For filesystem directories use the node subpath's \`fallbackAdapter\`.`);if(t.fixtures){let r=Sr(),o=t.fixtures,s=(async()=>{for(let a of o){let i=await Ra(a,e);await r.save(i,Na(a))}})();return s.catch(()=>{}),{tier:r,seedReady:s}}return t.fixturesStorage?{tier:t.fixturesStorage,seedReady:Promise.resolve()}:{tier:void 0,seedReady:Promise.resolve()}}function Er(t={}){let e=t.provider??"fallback",n=t.model??"fallback",r=t.onMiss??"respond",o=t.keyPrefix??"fallback",s=t.record?t.record.adapter:r==="throw"?ut({provider:e,model:n,respond:()=>"[unreachable: read-strict mode throws on miss]"}):{provider:e,model:n,async invoke(c,l){let p=t.respond?t.respond(c,l):Ss(e,n);return _s(p,e,n)},async*stream(c,l){let p=t.respond?t.respond(c,l):Ss(e,n),f=_s(p,e,n);yield{type:"token",delta:f.content},f.usage&&(yield{type:"usage",usage:f.usage}),yield{type:"finish",reason:f.finishReason??"stop"}}},a,i=Promise.resolve();if(t.record){if(!t.record.storage)throw new TypeError("fallbackAdapter: `record.storage` is required in record mode. For filesystem `record.dir` convenience, use the node subpath's `fallbackAdapter`.");a=t.record.storage}else{let c=Sa(t,o);a=c.tier??Sr(),i=c.seedReady}let d=t.record?"read-write":r==="throw"?"read-strict":"read",u=Gt(s,{storage:a,mode:d,keyPrefix:o,cacheStreaming:!0,captureStreamCadence:!0,replaySpeed:t.replaySpeed,...t.keyFn?{keyFn:t.keyFn}:{}});return{provider:e,model:n,capabilities:u.capabilities?.bind(u),async invoke(c,l){return await i,u.invoke(c,l)},async*stream(c,l){await i;for await(let p of u.stream(c,l))yield p}}}ye();function Ar(t={}){return t.sdk?Ea(t):Oa(t)}function Nn(t,e){let n=[],r=[];e?.systemPrompt&&n.push(e.systemPrompt);for(let a of t){if(a.role==="system"){n.push(a.content);continue}if(a.role==="tool"){r.push({role:"user",parts:[{functionResponse:{name:a.name??a.toolCallId??"tool",response:{result:a.content}}}]});continue}if(a.role==="assistant"&&a.toolCalls&&a.toolCalls.length>0){let i=[];a.content&&i.push({text:a.content});for(let d of a.toolCalls)i.push({functionCall:{name:d.name,args:d.arguments}});r.push({role:"model",parts:i});continue}r.push({role:a.role==="assistant"?"model":"user",parts:[{text:a.content}]})}let o={contents:r};n.length>0&&(o.systemInstruction={role:"system",parts:[{text:n.join(`
7
7
 
8
- `)}]});let s={};return e?.maxTokens!=null&&(s.maxOutputTokens=e.maxTokens),e?.temperature!=null&&(s.temperature=e.temperature),e?.maxReasoningTokens!=null&&(s.thinkingConfig={thinkingBudget:e.maxReasoningTokens}),Object.keys(s).length>0&&(o.generationConfig=s),e?.tools&&e.tools.length>0&&(o.tools=[{functionDeclarations:e.tools.map(Sa)}]),e?.providerExtras&&Object.assign(o,e.providerExtras),o}function Sa(t){return{name:t.name,description:t.description,parameters:t.parameters}}function Rs(t,e,n){let r={},o=t.generationConfig;o&&(typeof o.maxOutputTokens=="number"&&(r.maxOutputTokens=o.maxOutputTokens),typeof o.temperature=="number"&&(r.temperature=o.temperature),o.thinkingConfig&&(r.thinkingConfig=o.thinkingConfig)),t.systemInstruction&&(r.systemInstruction=t.systemInstruction),t.tools&&(r.tools=t.tools);for(let[s,a]of Object.entries(t))s==="contents"||s==="generationConfig"||s==="systemInstruction"||s==="tools"||s==="abortSignal"||s==="model"||(r[s]=a);return n&&(r.abortSignal=n),{model:e,contents:t.contents,config:Object.keys(r).length>0?r:void 0}}function _r(t){let e={input:{regular:0},output:{regular:0},raw:t};if(!t)return e;let n=t.promptTokenCount??0,r=t.cachedContentTokenCount??0;if(e.input.regular=Math.max(0,n-r),r>0&&(e.input.cacheRead=r),t.toolUsePromptTokenCount&&(e.input.toolUse=t.toolUsePromptTokenCount),t.promptTokensDetails)for(let o of t.promptTokensDetails){let s=o.modality?.toLowerCase();s==="image"?e.input.image=(e.input.image??0)+o.tokenCount:s==="audio"?e.input.audio=(e.input.audio??0)+o.tokenCount:s==="video"&&(e.input.video=(e.input.video??0)+o.tokenCount)}return e.output.regular=t.candidatesTokenCount??0,t.thoughtsTokenCount&&(e.output.reasoning=t.thoughtsTokenCount),e}function Ss(t,e){let n=t.candidates?.[0],r=n?.content?.parts??[],o=[],s=[],a=0;for(let i of r)typeof i.text=="string"&&o.push(i.text),i.functionCall&&s.push({id:`${i.functionCall.name}-${a++}`,name:i.functionCall.name,arguments:i.functionCall.args??{}});return{content:o.join(""),toolCalls:s.length>0?s:void 0,usage:_r(t.usageMetadata),finishReason:n?.finishReason,latencyMs:e,model:t.modelVersion,provider:"google"}}function Na(t){if(t.apiKey)return t.apiKey;let e=globalThis.process?.env;return e?.GOOGLE_API_KEY??e?.GEMINI_API_KEY}function _a(t){let e=t.baseURL??"https://generativelanguage.googleapis.com/v1beta",n=t.fetchImpl??fetch,r=s=>{let a=s?.model??t.model;if(!a)throw new Error("googleAdapter: model must be set via options.model or invokeOpts.model");return a},o=()=>{let s=Na(t);if(!s)throw new Error("googleAdapter: apiKey required for invoke/stream");return`key=${encodeURIComponent(s)}`};return{provider:"google",model:t.model,async invoke(s,a){let i=r(a),d=wn(s,a),u=z(),c=`${e}/models/${encodeURIComponent(i)}:generateContent?${o()}`,l=await n(c,{method:"POST",headers:{"content-type":"application/json",...t.headers??{}},body:JSON.stringify(d),signal:a?.signal});if(!l.ok)throw await ze(l,"Google");let p=await l.json(),f=Math.max(0,(z()-u)/1e6);return Ss(p,f)},async*stream(s,a){let i=r(a),d=wn(s,a),u=`${e}/models/${encodeURIComponent(i)}:streamGenerateContent?alt=sse&${o()}`,c=await n(u,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",...t.headers??{}},body:JSON.stringify(d),signal:a?.signal});if(!c.ok)throw await ze(c,"Google");if(!c.body)throw new Error("googleAdapter: streaming response has no body");let l,p;for await(let f of Tt(c.body,{signal:a?.signal})){if(!f.data)continue;let m;try{m=JSON.parse(f.data)}catch{continue}let h=m.candidates?.[0];for(let g of h?.content?.parts??[])typeof g.text=="string"&&(g.thought?yield{type:"thinking",delta:g.text}:yield{type:"token",delta:g.text}),g.functionCall&&(yield{type:"tool-call-delta",delta:{name:g.functionCall.name,argumentsDelta:JSON.stringify(g.functionCall.args??{})}});h?.finishReason&&(p=h.finishReason),m.usageMetadata&&(l=m.usageMetadata)}l&&(yield{type:"usage",usage:_r(l)}),yield{type:"finish",reason:p??"stop"}}}}function Ma(t){let e=t.sdk;if(!e)throw new Error("sdkBackedGoogle: sdk instance required");return{provider:"google",model:t.model,async invoke(n,r){let o=wn(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let a=Rs(o,s,r?.signal),i=z(),d=await e.models.generateContent(a),u=Math.max(0,(z()-i)/1e6);return Ss(d,u)},async*stream(n,r){if(!e.models.generateContentStream)throw new Error("sdkBackedGoogle: SDK instance does not expose generateContentStream");let o=wn(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let a=Rs(o,s,r?.signal),i,d,u=await e.models.generateContentStream(a);for await(let c of u){let l=c.candidates?.[0];for(let p of l?.content?.parts??[])typeof p.text=="string"&&(p.thought?yield{type:"thinking",delta:p.text}:yield{type:"token",delta:p.text}),p.functionCall&&(yield{type:"tool-call-delta",delta:{name:p.functionCall.name,argumentsDelta:JSON.stringify(p.functionCall.args??{})}});l?.finishReason&&(d=l.finishReason),c.usageMetadata&&(i=c.usageMetadata)}i&&(yield{type:"usage",usage:_r(i)}),yield{type:"finish",reason:d??"stop"}}}}ye();var Oa={openai:{baseURL:"https://api.openai.com/v1",apiKeyEnv:"OPENAI_API_KEY",provider:"openai"},openrouter:{baseURL:"https://openrouter.ai/api/v1",apiKeyEnv:"OPENROUTER_API_KEY",provider:"openrouter"},groq:{baseURL:"https://api.groq.com/openai/v1",apiKeyEnv:"GROQ_API_KEY",provider:"groq"},ollama:{baseURL:"http://localhost:11434/v1",provider:"ollama"},deepseek:{baseURL:"https://api.deepseek.com/v1",apiKeyEnv:"DEEPSEEK_API_KEY",provider:"deepseek"},xai:{baseURL:"https://api.x.ai/v1",apiKeyEnv:"XAI_API_KEY",provider:"xai"}};function Mr(t={}){return t.sdk?Da(t):La(t)}function kn(t,e,n,r,o){let s=e?.model??n;if(!s)throw new Error("openAICompatAdapter: model must be set via options.model or invokeOpts.model");let a=t.map(Ea);e?.systemPrompt&&!t.some(d=>d.role==="system")&&a.unshift({role:"system",content:e.systemPrompt});let i={model:s,messages:a};return e?.maxTokens!=null&&(i.max_tokens=e.maxTokens),e?.temperature!=null&&(i.temperature=e.temperature),e?.tools&&e.tools.length>0&&(i.tools=e.tools.map(Aa)),e?.maxReasoningTokens!=null&&(i.reasoning={max_tokens:e.maxReasoningTokens}),r&&(i.stream=!0,i.stream_options={include_usage:!0}),o&&Object.assign(i,o),e?.providerExtras&&Object.assign(i,e.providerExtras),i}function Ea(t){return t.role==="tool"?{role:"tool",tool_call_id:t.toolCallId,content:t.content}:t.role==="assistant"&&t.toolCalls&&t.toolCalls.length>0?{role:"assistant",content:t.content||null,tool_calls:t.toolCalls.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.arguments)}}))}:{role:t.role,content:t.content}}function Aa(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}}function Or(t){let e={input:{regular:0},output:{regular:0},raw:t};if(!t)return e;let n=t.prompt_tokens??0,r=t.prompt_tokens_details?.cached_tokens??0;t.prompt_cache_hit_tokens!=null?(r=t.prompt_cache_hit_tokens,e.input.regular=t.prompt_cache_miss_tokens??Math.max(0,n-r)):e.input.regular=Math.max(0,n-r),r>0&&(e.input.cacheRead=r),t.prompt_tokens_details?.audio_tokens&&(e.input.audio=t.prompt_tokens_details.audio_tokens);let o=t.completion_tokens??0,s=t.completion_tokens_details?.reasoning_tokens??0;return e.output.regular=Math.max(0,o-s),s>0&&(e.output.reasoning=s),t.completion_tokens_details?.audio_tokens&&(e.output.audio=t.completion_tokens_details.audio_tokens),t.completion_tokens_details?.accepted_prediction_tokens&&(e.output.predictionAccepted=t.completion_tokens_details.accepted_prediction_tokens),t.completion_tokens_details?.rejected_prediction_tokens&&(e.output.predictionRejected=t.completion_tokens_details.rejected_prediction_tokens),e}function Ns(t,e,n){let r=t.choices[0],o=r?.message,s=o?.content??"",a=(o?.tool_calls??[]).map(i=>({id:i.id,name:i.function.name,arguments:Ca(i.function.arguments)}));return{content:s,toolCalls:a.length>0?a:void 0,usage:Or(t.usage),finishReason:r?.finish_reason,latencyMs:e,model:t.model,provider:n}}function Ca(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!=null?e:{_raw:t}}catch{return{_raw:t}}}function _s(t){let e=t.preset??"openai",n=Oa[e],r=t.baseURL??n.baseURL,o=t.provider??n.provider,s=n.apiKeyEnv,a=t.apiKey??(s?globalThis.process?.env?.[s]:void 0);return{provider:o,baseURL:r,apiKey:a}}function La(t){let{provider:e,baseURL:n,apiKey:r}=_s(t),o=t.fetchImpl??fetch,s=e!=="ollama",a=()=>{let i={"content-type":"application/json",...t.headers??{}};if(s){if(!r)throw new Error(`openAICompatAdapter[${e}]: apiKey required for invoke/stream`);i.authorization=`Bearer ${r}`}return i};return{provider:e,model:t.model,async invoke(i,d){let u=kn(i,d,t.model,!1,t.bodyExtras),c=z(),l=await o(`${n}/chat/completions`,{method:"POST",headers:a(),body:JSON.stringify(u),signal:d?.signal});if(!l.ok)throw await ze(l,e);let p=await l.json(),f=Math.max(0,(z()-c)/1e6);return Ns(p,f,e)},async*stream(i,d){let u=kn(i,d,t.model,!0,t.bodyExtras),c=await o(`${n}/chat/completions`,{method:"POST",headers:{...a(),accept:"text/event-stream"},body:JSON.stringify(u),signal:d?.signal});if(!c.ok)throw await ze(c,e);if(!c.body)throw new Error(`openAICompatAdapter[${e}]: streaming response has no body`);let l,p;for await(let f of Tt(c.body,{signal:d?.signal})){if(!f.data||f.data==="[DONE]")continue;let m;try{m=JSON.parse(f.data)}catch{continue}let h=m.choices;if(h){let g=h[0];if(g?.delta?.content&&(yield{type:"token",delta:g.delta.content}),g?.delta?.reasoning_content&&(yield{type:"thinking",delta:g.delta.reasoning_content}),g?.delta?.tool_calls)for(let b of g.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:b.id,name:b.function?.name,argumentsDelta:b.function?.arguments}};g?.finish_reason&&(p=g.finish_reason)}m.usage&&(l=m.usage,yield{type:"usage",usage:Or(l)})}yield{type:"finish",reason:p??"stop"}}}}function Da(t){let e=t.sdk;if(!e)throw new Error("sdkBackedOpenAI: sdk instance required");let{provider:n}=_s(t);return{provider:n,model:t.model,async invoke(r,o){let s=kn(r,o,t.model,!1,t.bodyExtras),a=z(),i=await e.chat.completions.create(s,{signal:o?.signal}),d=Math.max(0,(z()-a)/1e6);return Ns(i,d,n)},async*stream(r,o){let s=kn(r,o,t.model,!0,t.bodyExtras),a=await e.chat.completions.create(s,{signal:o?.signal}),i,d;for await(let u of a){let c=u.choices;if(c){let p=c[0];if(p?.delta?.content&&(yield{type:"token",delta:p.delta.content}),p?.delta?.reasoning_content&&(yield{type:"thinking",delta:p.delta.reasoning_content}),p?.delta?.tool_calls)for(let f of p.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:f.id,name:f.function?.name,argumentsDelta:f.function?.arguments}};p?.finish_reason&&(d=p.finish_reason)}let l=u.usage;l&&(i=l,yield{type:"usage",usage:Or(l)})}yield{type:"finish",reason:d??"stop"}}}}function Ia(t){switch(t.provider){case"anthropic":{let e={apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return br(e)}case"google":{let e={apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return Nr(e)}case"dry-run":{let e={model:t.model,...t.extras};return at(e)}case"fallback":{let e={provider:t.provider,model:t.model,...t.extras};return Sr(e)}case"openai":case"openrouter":case"groq":case"ollama":case"deepseek":case"xai":{let e={preset:t.provider,apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,bodyExtras:t.bodyExtras,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return Mr(e)}default:{let e=t.provider;throw new Error(`createAdapter: unknown provider: ${String(e)}`)}}}ye();Q();Me();de();we();Q();var Er=class{_version=0;_maxSize;_buf;_head=0;_size=0;constructor(e,n){if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(this._maxSize=n,n!==void 0){if(this._buf=new Array(n),e&&e.length>0){let r=Math.min(e.length,n),o=e.length-r;for(let s=0;s<r;s++)this._buf[s]=e[o+s];this._size=r}}else this._buf=e?[...e]:[],this._size=this._buf.length}get version(){return this._version}get size(){return this._size}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._size+e;if(!(n<0||n>=this._size))return this._maxSize!==void 0?this._buf[(this._head+n)%this._maxSize]:this._buf[n]}append(e){this._rawAppend(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._maxSize!==void 0&&e.length>this._maxSize?e.length-this._maxSize:0;for(let r=n;r<e.length;r++)this._rawAppend(e[r]);this._version+=1}clear(){if(this._size===0)return 0;let e=this._size;if(this._maxSize===void 0)this._buf.length=0;else for(let n=0;n<e;n++)this._buf[(this._head+n)%this._maxSize]=void 0;return this._head=0,this._size=0,this._version+=1,e}trimHead(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`trimHead: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return 0;let n=Math.min(e,this._size);if(this._maxSize===void 0)this._buf.splice(0,n);else{for(let r=0;r<n;r++)this._buf[(this._head+r)%this._maxSize]=void 0;this._head=(this._head+n)%this._maxSize}return this._size-=n,this._version+=1,n}slice(e,n){if(!Number.isInteger(e)||e<0)throw new RangeError(`slice: start must be a non-negative integer (got ${e})`);if(n!==void 0&&(!Number.isInteger(n)||n<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${n})`);let r=n===void 0?this._size:Math.min(Math.max(n,0),this._size),o=Math.min(e,this._size);if(o>=r)return[];let s=r-o;if(this._maxSize===void 0)return this._buf.slice(o,r);let a=new Array(s);for(let i=0;i<s;i++)a[i]=this._buf[(this._head+o+i)%this._maxSize];return a}tail(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`tail: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return[];let n=Math.min(e,this._size);return this.slice(this._size-n,this._size)}toArray(){if(this._maxSize===void 0)return[...this._buf];let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this._buf[(this._head+n)%this._maxSize];return e}snapshot(){return this.toArray()}restore(e){if(this._maxSize===void 0){this._buf.length=0;for(let n=0;n<e.length;n++)this._buf.push(e[n]);this._size=this._buf.length}else{let n=this._maxSize;for(let s=0;s<n;s++)this._buf[s]=void 0;this._head=0;let r=Math.min(e.length,n),o=e.length-r;for(let s=0;s<r;s++)this._buf[s]=e[o+s];this._size=r}this._version+=1}_rawAppend(e){if(this._maxSize===void 0){this._buf.push(e),this._size=this._buf.length;return}this._size<this._maxSize?(this._buf[(this._head+this._size)%this._maxSize]=e,this._size+=1):(this._buf[this._head]=e,this._head=(this._head+1)%this._maxSize)}};function Pt(t){return t.subscribe(()=>{})}var Pa=64;function je(t,e={}){let{name:n,maxSize:r,versioning:o,guard:s,backend:a}=e,i=a??new Er(t,r),d=F(i.toArray(),{name:n,describeKind:"state",equals:(w,R)=>w===R,...o!=null?{versioning:o}:{},...s!=null?{guard:s}:{}});function u(){let w=i.toArray();re(()=>{d.down([[X]],{internal:!0}),d.down([[D,w]],{internal:!0})})}let c=new Map,l=new Map,p=new Map;function f(w,R){return`${w}:${R===void 0?"END":R}`}function m(w){if(w.size<Pa)return;let R=w.keys().next();if(R.done)return;let x=w.get(R.value);x!==void 0&&x.dispose(),w.delete(R.value)}function h(w){let R=i.version;try{return w()}finally{i.version!==R&&u()}}function g(w){if(!Number.isInteger(w)||w<0)throw new RangeError(`tail: n must be a non-negative integer (got ${w})`);let R=c.get(w);if(R!==void 0)return c.delete(w),c.set(w,R),R.node;m(c);let x=A([d],([M])=>{let L=M;return w===0||L.length===0?[]:L.slice(Math.max(0,L.length-w))},{initial:i.tail(w),describeKind:"derived"}),_=Pt(x);return c.set(w,{node:x,dispose:_}),x}function b(w,R){if(!Number.isInteger(w)||w<0)throw new RangeError(`slice: start must be a non-negative integer (got ${w})`);if(R!==void 0&&(!Number.isInteger(R)||R<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${R})`);let x=f(w,R),_=l.get(x);if(_!==void 0)return l.delete(x),l.set(x,_),_.node;m(l);let M=A([d],([S])=>{let O=S;return R===void 0?O.slice(w):O.slice(w,R)},{initial:i.slice(w,R),describeKind:"derived"}),L=Pt(M);return l.set(x,{node:M,dispose:L}),M}function T(w){let R=p.get(w);if(R!==void 0)return R.node;let x=A([d,w],([M,L])=>{let S=M,O=Math.max(0,Math.trunc(L??0));return S.slice(O)},{initial:[],describeKind:"derived"}),_=Pt(x);return p.set(w,{node:x,dispose:_}),x}let y,v;function k(){y===void 0&&(y=te([d],(w,R,x)=>{let _=w[0],L=_!=null&&_.length>0?_.at(-1):x.prevData[0];if(L==null||L.length===0){R.down([[U]]);return}R.emit(L[L.length-1])},{name:n!=null?`${n}::lastValue`:"lastValue",describeKind:"derived",initial:i.size===0?void 0:i.at(i.size-1)}),v=A([d],([w])=>w.length>0,{name:n!=null?`${n}::hasLatest`:"hasLatest",describeKind:"derived",initial:i.size>0}),Pt(y),Pt(v))}let N={entries:d,get size(){return i.size},at(w){return i.at(w)},append(w){h(()=>i.append(w))},appendMany(w){w.length!==0&&h(()=>i.appendMany(w))},clear(){h(()=>i.clear())},trimHead(w){h(()=>i.trimHead(w))},withLatest(){return k(),d},get lastValue(){return k(),y},get hasLatest(){return k(),v},view(w){switch(w.kind){case"tail":return g(w.n);case"slice":return b(w.start,w.stop);case"fromCursor":return T(w.cursor)}},attach(w){let R=w.subscribe(x=>{for(let _ of x)_[0]===D&&N.append(_[1])});return()=>R()},attachStorage(w){if(w.length===0)return()=>{};let R=new Map;for(let _ of w)R.set(_,i.size);(async()=>{for(let _ of w)if(typeof _.loadEntries=="function")try{let M=await Promise.resolve(_.loadEntries());M.entries.length>0&&i.size===0&&(i.restore(M.entries),R.set(_,M.entries.length),u());break}catch{}})();let x=d.subscribe(_=>{for(let M of _){if(M[0]!==D)continue;let L=M[1];for(let S of w){let O=R.get(S)??0;if(L.length<O){try{let K=S.appendEntries(L);K instanceof Promise&&K.catch(()=>{})}catch{}R.set(S,L.length);continue}if(L.length===O)continue;let I=L.slice(O);R.set(S,L.length);try{let K=S.appendEntries(I);K instanceof Promise&&K.catch(()=>{})}catch{}}}});return()=>x()},disposeAllViews(){for(let w of c.values())w.dispose();c.clear();for(let w of l.values())w.dispose();l.clear();for(let w of p.values())w.dispose();p.clear()},dispose(){for(let w of c.values())w.dispose();c.clear();for(let w of l.values())w.dispose();l.clear();for(let w of p.values())w.dispose();p.clear()}};return N}Z();function Fe(t){let e=t.input,n=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 n;let r=0;for(let o of Object.values(e.extensions))r+=o;return n+r}function Ue(t){let e=t.output,n=e.regular+(e.reasoning??0)+(e.audio??0)+(e.predictionAccepted??0)+(e.predictionRejected??0);if(!e.extensions)return n;let r=0;for(let o of Object.values(e.extensions))r+=o;return n+r}function Ms(){return{input:{regular:0},output:{regular:0}}}function Ga(t,e){let n=e?.logMax??1e3,r=je(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:n}),o=F(null,{name:"adapterStats/lastCall"}),s=A([r.entries],([h])=>h.length,{name:"adapterStats/totalCalls",initial:0}),a=A([r.entries],([h])=>h.reduce((g,b)=>g+Fe(b.usage),0),{name:"adapterStats/totalInputTokens",initial:0}),i=A([r.entries],([h])=>h.reduce((g,b)=>g+Ue(b.usage),0),{name:"adapterStats/totalOutputTokens",initial:0}),d=[Y(s),Y(a),Y(i)],u=h=>{r.append(h),o.emit(h)},c=()=>{r.clear(),o.emit(null)},l=ve(t,{invoke(h,g){let b=z(),T=ce(),y=t.model??g?.model??"",v=N=>(u(dt({provider:t.provider,model:t.model??g?.model??N.model??"",tier:g?.tier??N.tier,usage:N.usage??$e(),startNs:b,startWallClockNs:T,method:"invoke"})),N),k=N=>{let w=N;u(dt({provider:t.provider,model:y,tier:g?.tier,usage:$e(),startNs:b,startWallClockNs:T,method:"invoke",error:{type:w?.name??"Error",message:w?.message??String(N)}}))};return vn(t.invoke(h,g),{onResp:v,onError:k,name:"adapterStats/invokeTap"})},async*stream(h,g){let b=z(),T=ce(),y=t.model??g?.model??"",v;try{for await(let k of t.stream(h,g))k.type==="usage"&&(v=k.usage),yield k;u(dt({provider:t.provider,model:y,tier:g?.tier,usage:v??$e(),startNs:b,startWallClockNs:T,method:"stream"}))}catch(k){let N=k;throw u(dt({provider:t.provider,model:y,tier:g?.tier,usage:v??$e(),startNs:b,startWallClockNs:T,method:"stream",error:{type:N?.name??"Error",message:N?.message??String(k)}})),k}}});Te(l,"observableAdapter",t);let p=!1;return{adapter:l,stats:{lastCall:o,allCalls:r,totalCalls:s,totalInputTokens:a,totalOutputTokens:i,reset:c,dispose:()=>{if(!p){p=!0;for(let h of d)h();d.length=0}}}}}function Fa(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function Rn(t="USD"){return{total:0,currency:t}}function Ar(t,e,n){let r=Fe(t),o=e.currency??"USD",s=n?.withBreakdown===!0,a=s?{}:null,i=0,d=(g,b,T)=>{if(!b||T==null)return;let y=Fa(T,r),v=b*y/1e6;i+=v,s&&(a[g]=(a[g]??0)+v)},u=t.input,c=e.input;if(c&&(d("input.regular",u.regular,c.regular),d("input.cacheRead",u.cacheRead??0,c.cacheRead),d("input.cacheWrite5m",u.cacheWrite5m??0,c.cacheWrite5m),d("input.cacheWrite1h",u.cacheWrite1h??0,c.cacheWrite1h),d("input.cacheWriteOther",u.cacheWriteOther??0,c.cacheWriteOther),d("input.audio",u.audio??0,c.audio),d("input.image",u.image??0,c.image),d("input.video",u.video??0,c.video),d("input.toolUse",u.toolUse??0,c.toolUse),u.extensions&&c.extensions))for(let[g,b]of Object.entries(u.extensions))d(`input.ext.${g}`,b,c.extensions[g]);let l=t.output,p=e.output;if(p&&(d("output.regular",l.regular,p.regular),d("output.reasoning",l.reasoning??0,p.reasoning),d("output.audio",l.audio??0,p.audio),d("output.predictionAccepted",l.predictionAccepted??0,p.predictionAccepted),d("output.predictionRejected",l.predictionRejected??0,p.predictionRejected),l.extensions&&p.extensions))for(let[g,b]of Object.entries(l.extensions))d(`output.ext.${g}`,b,p.extensions[g]);let f=n?.tier;if(f&&e.tierMultipliers){let g=e.tierMultipliers[f];if(g!=null&&(i*=g,s))for(let b of Object.keys(a))a[b]*=g}let m=t.auxiliary,h=e.auxiliary;if(m&&h)for(let[g,b]of Object.entries(m)){let T=h[g];if(T==null||!b)continue;let y=b*T;i+=y,s&&(a[`auxiliary.${g}`]=y)}return s?{total:i,currency:o,breakdown:a}:{total:i,currency:o}}function xn(t,e){return`${t}::${e}`}function $a(t){let e=new Map,n=new Map,r=(o,s,a)=>{e.set(xn(o,s),{provider:o,model:s,pricing:a});let i=n.get(o);i||(i=new Set,n.set(o,i)),i.add(s)};if(t)for(let[o,s,a]of t)r(o,s,a);return{register:r,lookup(o,s){let a=e.get(xn(o,s));if(a)return a.pricing;let i=n.get(o);if(!i)return;let d;for(let u of i)if(s.startsWith(u)&&(!d||u.length>d.key.length)){let c=e.get(xn(o,u));c&&(d={key:u,pricing:c.pricing})}return d?.pricing},remove(o,s){let a=e.delete(xn(o,s));if(a){let i=n.get(o);i?.delete(s),i&&i.size===0&&n.delete(o)}return a},entries(){let o=e.values();return(function*(){for(let{provider:s,model:a,pricing:i}of o)yield[s,a,i]})()}}}function ja(t,e="USD"){return(n,r)=>{let o=t.lookup(r.provider,r.model);return o?Ar(n,o,{tier:r.tier,withBreakdown:r.withBreakdown}):Rn(e)}}function Ba(...t){return(e,n)=>{for(let r of t){let o=r(e,n);if(o.total!==0)return o}return t.length>0?t[0](e,n):Rn()}}function Va(t,e,n){return t?.pricing?Ar(e,t.pricing,n):Rn()}bt();Z();function Cr(t,e={}){let n=e.breaker??Ye(e),r=ve(t,{async invoke(o,s){if(!n.canExecute())throw new Qe;try{let a=await _e(V(t.invoke(o,s)));return n.recordSuccess(),a}catch(a){throw n.recordFailure(a),a}},async*stream(o,s){if(!n.canExecute())throw new Qe;try{for await(let a of t.stream(o,s))yield a;n.recordSuccess()}catch(a){throw n.recordFailure(a),a}}});return Te(r,"withBreaker",t),{adapter:r,breaker:n}}ye();de();Q();Z();var Sn=class extends Error{constructor(n,r,o){super(`Budget exhausted: ${n} (limit=${r}, observed=${o})`);this.which=n;this.limit=r;this.observed=o}name="BudgetExhaustedError"},Lr=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),Os=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function Dr(t,e){let n=je(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),r=F(Os(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=A([r],([u])=>{let c=u;return!(e.caps.calls!=null&&c.calls>=e.caps.calls||e.caps.inputTokens!=null&&c.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&c.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&c.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(Y(o),e.onExhausted!=null){let u=e.onExhausted,c=!1,l=!0;o.subscribe(p=>{for(let f of p)if(f[0]===D){let m=f[1];if(c&&l&&m===!1){let h=Es(r.cache??Lr,e.caps);h&&u(h)}l=m,c=!0}})}let s=()=>{if(o.cache===!1){let u=r.cache??Lr,c=Es(u,e.caps);return new Sn(c??"budget",e.caps[c??"calls"]??0,Ka(u,c??"calls"))}},a=(u,c)=>{let l=t.provider,p=dt({provider:l,model:c.model,tier:c.tier,usage:u,startNs:c.startNs,method:c.method,...c.error?{error:c.error}:{}});n.append(p);let f=r.cache??Lr,m=e.pricingFn?f.usd+e.pricingFn(u,{model:c.model,provider:l,tier:c.tier}).total:f.usd;r.emit({calls:f.calls+1,inputTokens:f.inputTokens+Fe(u),outputTokens:f.outputTokens+Ue(u),usd:m})},i=()=>{n.clear(),r.emit(Os())},d=ve(t,{invoke(u,c){let l=s();if(l)return Promise.reject(l);let p=z(),f=t.model??c?.model??"",m=g=>(a(g.usage??$e(),{model:t.model??c?.model??g.model??"",tier:c?.tier??g.tier,startNs:p,method:"invoke"}),g),h=g=>{let b=g;a($e(),{model:f,tier:c?.tier,startNs:p,method:"invoke",error:{type:b?.name??"Error",message:b?.message??String(g)}})};return vn(t.invoke(u,c),{onResp:m,onError:h,name:"budgetGate/invokeTap"})},async*stream(u,c){let l=s();if(l)throw l;let p=z(),f;try{for await(let m of t.stream(u,c))m.type==="usage"&&(f=m.usage),yield m;a(f??$e(),{model:t.model??c?.model??"",tier:c?.tier,startNs:p,method:"stream"})}catch(m){let h=m;throw a(f??$e(),{model:t.model??c?.model??"",tier:c?.tier,startNs:p,method:"stream",error:{type:h?.name??"Error",message:h?.message??String(m)}}),m}}});return Te(d,"withBudgetGate",t),{adapter:d,budget:{totals:r,isOpen:o,log:n,reset:i}}}function Es(t,e){if(e.calls!=null&&t.calls>=e.calls)return"calls";if(e.inputTokens!=null&&t.inputTokens>=e.inputTokens)return"inputTokens";if(e.outputTokens!=null&&t.outputTokens>=e.outputTokens)return"outputTokens";if(e.usd!=null&&t.usd>=e.usd)return"usd"}function Ka(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}Z();function za(t,e){let n=e.mock??at({provider:t.provider,model:t.model}),r=typeof e.enabled=="boolean"?e.enabled:void 0,o=r===void 0?V(e.enabled):void 0,s;o&&(s=Y(o));let a=()=>r!==void 0?r:!!o?.cache,i=ve(t,{invoke(u,c){return a()?n.invoke(u,c):t.invoke(u,c)},stream(u,c){return a()?n.stream(u,c):t.stream(u,c)}});return Te(i,"withDryRun",t),{adapter:i,dispose:()=>{s&&(s(),s=void 0)}}}function Ir(t){if(t==null||typeof t!="object")return;let e=t,n=e.status,r=Ua(e.headers);if(n!==429&&n!==503&&!Qa(e.message))return;let o={},s=r("retry-after"),a=Wa(s);a!=null&&(o.retryAfterMs=a);let i=r("anthropic-ratelimit-requests-reset");if(i){let f=As(i);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let d=r("anthropic-ratelimit-tokens-reset");if(d){let f=As(d);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let u=Nn(r,"x-ratelimit-limit-requests");u!=null&&(o.rpmCap=u);let c=Nn(r,"x-ratelimit-limit-tokens");c!=null&&(o.tpmCap=c);let l=Nn(r,"x-ratelimit-remaining-requests"),p=Nn(r,"x-ratelimit-remaining-tokens");if(l!=null&&u!=null&&u>0&&(o.usageHint??={},o.usageHint.rpm=1-l/u),p!=null&&c!=null&&c>0&&(o.usageHint??={},o.usageHint.tpm=1-p/c),o.retryAfterMs==null&&e.message){let f=Ja(e.message);f!=null&&(o.retryAfterMs=f)}return e.headers&&(o.metadata={headers:qa(e.headers)}),o.retryAfterMs==null&&o.rpmCap==null&&o.tpmCap==null&&o.usageHint==null?o.metadata?o:void 0:o}function Ua(t){if(!t)return()=>{};if(typeof t.get=="function"){let r=t;return o=>r.get(o)??r.get(o.toLowerCase())??void 0}let e=t,n={};for(let[r,o]of Object.entries(e)){let s=Array.isArray(o)?o.join(", "):o;s!=null&&(n[r.toLowerCase()]=s)}return r=>n[r.toLowerCase()]}function qa(t){let e={};if(typeof t.forEach=="function")return t.forEach((n,r)=>{e[r]=n}),e;for(let[n,r]of Object.entries(t))r!=null&&(e[n]=Array.isArray(r)?r.join(", "):r);return e}function Nn(t,e){let n=t(e);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function Wa(t){if(!t)return;let e=t.trim(),n=Number(e);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(e);if(Number.isFinite(r)){let o=r-Date.now();if(o>0)return o}}function As(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var Ha=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function Ja(t){let e=Ha.exec(t);if(!e)return;let n=Number(e[1]);if(!Number.isFinite(n))return;let r=(e[2]??"s").toLowerCase();if(r==="ms")return n;if(r.startsWith("s"))return n*1e3;if(r.startsWith("m"))return n*6e4}var Ya=/rate\s*limit|too\s*many\s*requests|quota|429/i;function Qa(t){return!!t&&Ya.test(t)}ye();de();Q();bt();Z();Ve();function Pr(t){let e=new Error(t);return e.name="AbortError",e}function Ls(t={}){let e=Math.max(1,t.burstMultiplier??1),n=t.clampCooldownMs??6e4,r=t.rpm!=null?V(t.rpm):F(Number.POSITIVE_INFINITY),o=t.tpm!=null?V(t.tpm):F(Number.POSITIVE_INFINITY),s=F(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),a=F(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),i=F({},{name:"adaptiveRateLimiter/lastSignal"}),d=A([r,s],([S,O])=>Math.min(Number(S??1/0),Number(O??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),u=A([o,a],([S,O])=>Math.min(Number(S??1/0),Number(O??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),c=vt(Number(r.cache??Number.POSITIVE_INFINITY),e),l=vt(Number(o.cache??Number.POSITIVE_INFINITY),e),p=!1,f=!1,m=d.subscribe(S=>{for(let O of S)if(O[0]===D){let I=Number(O[1]);Number.isFinite(I)&&I>0?(c=vt(I,e),p=!1):I===1/0?(c=vt(1/0,e),p=!1):I<=0&&(p=!0)}}),h=u.subscribe(S=>{for(let O of S)if(O[0]===D){let I=Number(O[1]);Number.isFinite(I)&&I>0?(l=vt(I,e),f=!1):I===1/0?(l=vt(1/0,e),f=!1):I<=0&&(f=!0)}}),g=0,b=new ge,T=new ge,y;t.adaptation!=null&&(y=V(t.adaptation).subscribe(O=>{for(let I of O)I[0]===D&&v(I[1])}));function v(S){if(i.emit(S),S.rpmCap!=null&&Number.isFinite(S.rpmCap)&&S.rpmCap>=0&&(s.emit(S.rpmCap),Number.isFinite(n)&&n>0&&b.start(n,()=>s.emit(Number.POSITIVE_INFINITY))),S.tpmCap!=null&&Number.isFinite(S.tpmCap)&&S.tpmCap>=0&&(a.emit(S.tpmCap),Number.isFinite(n)&&n>0&&T.start(n,()=>a.emit(Number.POSITIVE_INFINITY))),S.retryAfterMs!=null&&S.retryAfterMs>0){let O=z()+S.retryAfterMs*1e6;O>g&&(g=O)}}let k=F(0,{name:"adaptiveRateLimiter/pending"}),N=F(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),w=F(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),R=S=>{k.emit((k.cache??0)+S)},x=()=>{N.emit(c.available()),w.emit(l.available())};async function _(S={}){let O=S.requestCost??1,I=S.tokenCost??0,K=S.signal;R(1);try{for(;;){if(K?.aborted)throw Pr("AdaptiveRateLimiter.acquire aborted");let q=z();if(g>q){let C=Math.ceil((g-q)/1e6);await _n(C,K);continue}if(O>0&&p||I>0&&f){await _n(250,K);continue}let H=c,G=l;if(!H.tryConsume(O)){await _n(Cs(H,O),K);continue}if(!(I>0?G.tryConsume(I):!0)){H.putBack(O),await _n(Cs(G,I),K);continue}x();return}}finally{R(-1)}}function M(S){S>0?l.tryConsume(S):S<0&&l.putBack(-S),x()}function L(){m(),h(),y?.(),b.cancel(),T.cancel()}return{effectiveRpm:d,effectiveTpm:u,lastSignal:i,pending:k,rpmAvailable:N,tpmAvailable:w,acquire:_,recordUsage:M,recordSignal:v,dispose:L}}function vt(t,e){if(!Number.isFinite(t)||t===1/0)return Lt(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let n=Math.max(1,t*e),r=t/60;return Lt(n,r)}function Cs(t,e){let n=t.available(),r=Math.max(0,e-n);return r<=0?25:Math.min(5e3,Math.max(50,r*100))}function _n(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Pr("AdaptiveRateLimiter.acquire aborted")):new Promise((n,r)=>{let o=new ge,s,a=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{a(),n()}),e&&(s=()=>{a(),r(Pr("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",s,{once:!0}))})}Z();function Gr(t,e={}){let n=e.limiter??Ls({name:e.name??"rateLimiter",rpm:e.rpm,tpm:e.tpm,adaptation:e.adaptation,burstMultiplier:e.burstMultiplier}),r=(a,i)=>e.costFn?e.costFn(a,i):0,o=a=>{let i=Ir(a);i&&n.recordSignal(i)},s=ve(t,{async invoke(a,i){let d=r(a,i);await n.acquire({requestCost:1,tokenCost:d,signal:i?.signal});try{let u=await _e(V(t.invoke(a,i))),c=u.usage??Ms(),p=Fe(c)+Ue(c)-d;return p>0&&n.recordUsage(p),u}catch(u){throw o(u),u}},async*stream(a,i){let d=r(a,i);await n.acquire({requestCost:1,tokenCost:d,signal:i?.signal});try{let u=0;for await(let l of t.stream(a,i))l.type==="usage"&&(u=Fe(l.usage)+Ue(l.usage)),yield l;let c=u-d;c>0&&n.recordUsage(c)}catch(u){throw o(u),u}}});return Te(s,"withRateLimiter",t),{adapter:s,limiter:n}}bt();Z();var Gt=class extends Error{name="AllTiersExhaustedError";skipped;failed;constructor(e){let n=[];e.failed.size>0&&n.push(`failed=[${[...e.failed.keys()].join(",")}]`),e.skipped.length>0&&n.push(`skipped=[${e.skipped.map(r=>`${r.name}(${r.reason})`).join(",")}]`),super(`All LLM adapter tiers exhausted: ${n.join(" ")}`),this.skipped=e.skipped,this.failed=e.failed}};function Fr(t,e={}){if(t.length===0)throw new RangeError("cascadingLlmAdapter: tiers must be non-empty");let n=t.map(s=>({name:s.name,adapter:s.adapter,filter:s.filter,breaker:s.breaker?"canExecute"in s.breaker?s.breaker:Ye(s.breaker):void 0})),r=e.streamRetryBeforeFirstChunk??!0,o={provider:"cascading",model:void 0,async invoke(s,a){let i=[],d=new Map;for(let c=0;c<n.length;c++){let l=n[c];if(l.filter&&!l.filter(s,a)){i.push({name:l.name,reason:"filter"});continue}if(l.breaker&&!l.breaker.canExecute()){i.push({name:l.name,reason:"breaker"});continue}try{let p=await _e(V(l.adapter.invoke(s,a)));return l.breaker?.recordSuccess(),{...p,metadata:{...p.metadata??{},tier:l.name}}}catch(p){d.set(l.name,p),l.breaker?.recordFailure(p);let f=n[c+1];f&&e.onFallback?.(l.name,f.name,p)}}let u={skipped:i,failed:d};throw e.onExhausted?.(u),new Gt(u)},async*stream(s,a){let i=[],d=new Map;for(let c=0;c<n.length;c++){let l=n[c];if(l.filter&&!l.filter(s,a)){i.push({name:l.name,reason:"filter"});continue}if(l.breaker&&!l.breaker.canExecute()){i.push({name:l.name,reason:"breaker"});continue}let p=!1;try{for await(let f of l.adapter.stream(s,a))p=!0,yield f;l.breaker?.recordSuccess();return}catch(f){if(d.set(l.name,f),l.breaker?.recordFailure(f),p||!r)throw f;let m=n[c+1];m&&e.onFallback?.(l.name,m.name,f)}}let u={skipped:i,failed:d};throw e.onExhausted?.(u),new Gt(u)}};return Te(o,`cascade[${n.map(s=>s.name).join(",")}]`),o}function Xa(t,e,n){let r={name:t,adapter:e};return n?.breaker&&(r.breaker=n.breaker),n?.filter&&(r.filter=n.filter),r}Z();Ve();function Mn(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function Ds(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Mn()):new Promise((n,r)=>{let o=new ge,s,a=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{a(),n()}),e&&(s=()=>{a(),r(Mn())},e.addEventListener("abort",s,{once:!0}))})}function $r(t,e={}){let n=e.attempts??3,r=e.baseDelayMs??500,o=e.maxDelayMs??1e4,s=e.strategy??"decorrelated",a=e.jitter??!0,i=e.shouldRetry??Za,d=e.retryStreaming??!0,u=(l,p)=>{if(s==="decorrelated"){let g=Math.min(o,Math.max(r,p*3));return r+Math.random()*(g-r)}let f=s==="exp"?r*2**(l-1):r*l,m=Math.min(o,f);if(!a)return m;let h=m*(.5+Math.random());return Math.min(o,h)},c=ve(t,{async invoke(l,p){if(p?.signal?.aborted)throw Mn();let f,m=r;for(let h=1;h<=n;h++)try{return await _e(V(t.invoke(l,p)))}catch(g){if(f=g,h>=n||!i(g,h))throw g;let b=u(h,m);m=b,await Ds(b,p?.signal)}throw f},async*stream(l,p){if(p?.signal?.aborted)throw Mn();if(!d){for await(let h of t.stream(l,p))yield h;return}let f,m=r;for(let h=1;h<=n;h++){let g=!1;try{for await(let b of t.stream(l,p))g=!0,yield b;return}catch(b){if(f=b,g||h>=n||!i(b,h))throw b;let T=u(h,m);m=T,await Ds(T,p?.signal)}}throw f}});return Te(c,"withRetry",t),c}function Za(t,e){if(t==null)return!1;let n=t;return n.name==="LLMTimeoutError"?!0:n.name==="AbortError"||n.message==="aborted"||n.name==="DOMException"&&n.code!=null&&Number(n.code)===20||n.name==="BudgetExhaustedError"||n.name==="CircuitOpenError"?!1:n.status!=null?n.status===429||n.status>=500&&n.status<600:n.code&&typeof n.code=="string"&&/^E[A-Z]+$/.test(n.code)?!0:n.message?/network|timeout|socket|fetch|econn|eai_/i.test(n.message):!1}Z();Ve();var wt=class extends Error{constructor(n){super(`LLM call timed out after ${n}ms`);this.ms=n}name="LLMTimeoutError"};function jr(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let n=s=>{let a=new AbortController,i=!1,d,u=new ge;return s&&(s.aborted?a.abort(s.reason):(d=()=>{u.cancel(),a.abort(s.reason)},s.addEventListener("abort",d,{once:!0}))),u.start(e,()=>{i=!0,a.abort(new wt(e))}),{signal:a.signal,cancel:()=>{u.cancel(),s&&d&&s.removeEventListener("abort",d)},timedOut:()=>i}},r=(s,a)=>{if(!a||s instanceof wt)throw s;let i=s;if(i?.name==="AbortError"||i?.name==="DOMException"&&Number(i.code)===20||s?.message==="aborted"){let u=new wt(e);throw u.cause=s,u}throw s},o=ve(t,{async invoke(s,a){let{signal:i,cancel:d,timedOut:u}=n(a?.signal);try{return await _e(V(t.invoke(s,{...a,signal:i})))}catch(c){return r(c,u())}finally{d()}},async*stream(s,a){let{signal:i,cancel:d,timedOut:u}=n(a?.signal);try{for await(let c of t.stream(s,{...a,signal:i}))yield c}catch(c){r(c,u())}finally{d()}}});return Te(o,"withTimeout",t),o}function ed(t,e={}){let n={adapter:t},r=t;if(e.rateLimit){let o=Gr(r,e.rateLimit);r=o.adapter,n.rateLimiter=o.limiter}if(e.budget){let o=Dr(r,e.budget);r=o.adapter,n.budget=o.budget}if(e.breaker){let o=Cr(r,e.breaker);r=o.adapter,n.breaker=o.breaker}if(e.timeoutMs!=null&&(r=jr(r,e.timeoutMs)),e.retry&&(r=$r(r,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),r=Fr([{name:e.name??"primary",adapter:r},{name:"fallback",adapter:e.fallback}],o)}return e.cache&&(r=It(r,e.cache)),n.adapter=r,n}Oe();we();Z();de();He();Z();Ve();function W(t,e){return ue("ai",t,e)}function td(t){return t!=null&&typeof t.then=="function"}function Br(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function nd(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var rd=3e4;function Is(t,e){if(t.status==="settled"){let r=t.cache;if(r!==void 0)return Promise.resolve(r)}let n=e?.timeoutMs??rd;return new Promise((r,o)=>{let s=new ge,a=t.subscribe(i=>{for(let d of i){if(d[0]===D){s.cancel(),a(),r(d[1]);return}if(d[0]===P){s.cancel(),a(),o(d[1]);return}if(d[0]===$){s.cancel(),a(),o(new Error("firstDataFromNode: completed without producing a value"));return}}});s.start(n,()=>{a(),o(new Error(`firstDataFromNode: timed out after ${n}ms`))})})}async function Ft(t){return td(t)?Ft(await t):Br(t)?Is(t):nd(t)?Is(V(t)):t}function kt(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function od(t,e){let n=V(t),r=e?.refreshTrigger!=null?V(e.refreshTrigger):null,o=e?.name!==void 0?{name:e.name}:void 0,s=le("frozenContext",o);return r==null?te([n],(a,i,d)=>{if(d.store.emitted===!0)return;let c=a[0],l=c!=null&&c.length>0?c.at(-1):d.prevData[0];if(l!==void 0)return d.store.emitted=!0,i.emit(l),{invalidate:()=>{d.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:W("frozen_context",{...s})}):te([n,r],(a,i,d)=>{let u=a[1];if(!(u!=null&&u.length>0))return;let l=a[0],p=l!=null&&l.length>0?l.at(-1):d.prevData[0];i.emit(p)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:W("frozen_context",{...s})})}Q();de();Q();Ie();Z();function Ps(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function sd(t,e=200){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Vr(t,e,n,r){let o=r?.format??"text",s=r?.name??"prompt_node";r?.tools!==void 0&&o!=="raw"&&console.warn("promptNode: `tools` is set but `format !== 'raw'`. Tool calls in the response will be silently dropped \u2014 set `format: 'raw'` to receive the full LLMResponse with `toolCalls`.");let a=e.length,i=r?.tools!==void 0?[...e,r.tools]:e,d=A(i,c=>{let l=c.slice(0,a),p=r?.tools!==void 0?c[a]:void 0;if(l.some(m=>m==null))return{messages:[],tools:p};let f=typeof n=="string"?n:n(...l);return f?{messages:[{role:"user",content:f}],tools:p}:{messages:[],tools:p}},{name:`${s}::messages`,meta:W("prompt_node")});return ae(d,c=>{let{messages:l,tools:p}=c;return!l||l.length===0?F(null):se(f=>{let m=!1,h=!1,g,b={model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,...p!==void 0?{tools:p}:{}};if(r?.abort){let k=as(r.abort);b.signal=k.signal,g=k.dispose}let T;try{T=t.invoke(l,b)}catch(k){return m=!0,f.down([[P,k]]),()=>{g?.()}}let v=V(T).subscribe(k=>{if(!(h||m))for(let N of k){if(m)return;if(N[0]===D){let w=N[1];if(o==="raw")f.emit(w);else try{let R=Ps(w),x=o==="json"?JSON.parse(kt(R)):R;f.emit(x)}catch(R){let x=Ps(w),_=new Error(`promptNode: failed to parse LLM response as JSON: ${R.message}
9
- Raw content (first 200 chars): ${sd(x)}`);m=!0,f.down([[P,_]]);return}}else if(N[0]===P){m=!0,f.down([[P,N[1]]]);return}else if(N[0]===$){m=!0,f.down([[$]]);return}else f.down([N])}});return()=>{h=!0,v(),g?.()}},{name:`${s}::call`,meta:W("prompt_node::call")})},{name:`${s}::output`,meta:r?.meta?{...W("prompt_node::output"),...r.meta}:W("prompt_node::output")})}function Kr(t,e,n,r){let o=n.name??r;return s=>{let a=F(s);return Vr(n.adapter,[a],i=>e(i),{name:o,format:"json",systemPrompt:t,model:n.model,temperature:n.temperature??0,maxTokens:n.maxTokens})}}function zr(t,e){let n=e.maxExistingKeys??100,r=Kr(t,o=>JSON.stringify({input:o.raw,existingKeys:o.existingKeys}),e,"llmExtractor");return(o,s)=>{let a=n===Number.POSITIVE_INFINITY?[...s.keys()]:[...s.keys()].slice(0,n);return r({raw:o,existingKeys:a})}}function Ur(t,e){let n=Kr(t,r=>JSON.stringify({memories:r}),e,"llmConsolidator");return r=>{let o=[...r.entries()].map(([s,a])=>({key:s,value:a}));return n(o)}}Me();ye();Oe();Q();Ie();Z();qt();mt();de();Q();He();Me();ye();mt();de();Q();function Fs(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[X],[D,n+1]]),!0)}var id=ho((t,e)=>{t("observe"),t("signal"),e("write")});function xt(t){let e=je([],{name:t.name,maxSize:t.retainedLimit??1024,guard:t.guard??id,...t.versioning!=null?{versioning:t.versioning}:{}});return e.withLatest(),t.graph&&t.graph.add(e.entries,{name:t.name}),e}function qr(t){if(t===null||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.keys(t))qr(t[e]);return Object.freeze(t)}var Gs=new WeakSet;function $t(t){let e=t.cache,n=typeof e=="number"&&Number.isFinite(e);!n&&e!==void 0&&!Gs.has(t)&&(Gs.add(t),console.warn(`bumpCursor: cursor cache held a non-numeric value (${String(e)}); resetting to 0. Causes include: a snapshot codec round-tripping the cursor as a string / null / NaN, OR a malformed initial seed (e.g. state<number>(NaN)). Audit consumers may see colliding seq values after this point.`));let o=(n?e:0)+1;return t.down([[X],[D,o]]),o}function On(t,e,n,r,o,s){let a=e(n,r,o);if(a===void 0)return;let i=s!=null?{...a,handlerVersion:s}:a;t.append(i)}function ke(t,e){let n=e.freeze??!0;return function(...o){let s=n?o.map(qr):o,a=ce(),i=e.seq?$t(e.seq):void 0;try{let d=t(...s);return e.audit&&e.onSuccess&&On(e.audit,e.onSuccess,s,d,{t_ns:a,seq:i},e.handlerVersion),d}catch(d){if(e.audit&&e.onFailure){let u=d instanceof Error?d.name:typeof d;On(e.audit,e.onFailure,s,d,{t_ns:a,seq:i,errorType:u},e.handlerVersion)}throw d}}}function Rt(t,e){let n=e.freeze??!0;return function(...o){let s=n?o.map(qr):o,a=ce(),i,d,u=!1,c;try{re(()=>{e.seq&&(c=$t(e.seq));try{i=t(...s),e.audit&&e.onSuccess&&On(e.audit,e.onSuccess,s,i,{t_ns:a,seq:c},e.handlerVersion)}catch(l){throw d=l,u=!0,l}})}catch(l){if(u&&e.audit&&e.onFailure){let p=d instanceof Error?d.name:typeof d;On(e.audit,e.onFailure,s,d,{t_ns:a,seq:c,errorType:p},e.handlerVersion)}throw u?d:l}return i}}function En(t,e,n=0){let r=F(n,{name:e,describeKind:"state"});return t.add(r,{name:e}),r}Z();lr();function $s(t,e){return ue("messaging",t,e)}var ad=1024,Wr=class extends ie{_log;_publishImpl;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=je([],{name:"events",maxSize:n.retainedLimit??ad}),this._log.withLatest(),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=A([this.events],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:$s("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(Y(this.latest)),this.hasLatest=A([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:$s("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(Y(this.hasLatest)),this.addDisposer(()=>{this.events.down([[$]])}),this.addDisposer(()=>this._log.disposeAllViews()),this._publishImpl=ke(r=>{this._log.append(r)},{freeze:!1})}publish(e){if(e===void 0)throw new TypeError(`TopicGraph "${this.name}": publish(undefined) is not allowed (spec \xA75.12 SENTINEL).`);this._publishImpl(e)}attachEventStorage(e){return this._log.attachStorage(e)}retained(){return this.events.cache}get _logBundle(){return this._log}};function Hr(t,e){return new Wr(t,e)}Me();ye();de();Oe();we();Q();He();Ke();function jt(t,e){return ue("orchestration",t,e)}var An=class extends ie{constructor(e,n){super(e,n)}task(e,n,r={}){let o=(r.deps??[]).map(a=>this._resolveStep(a)),s=A(o,n,{name:e,describeKind:"derived",meta:jt("task",r.meta)});return this.add(s,{name:e}),s}classify(e,n,r,o={}){let s=this._resolveStep(n),a=A([s],([i])=>{try{return{tag:r(i),value:i}}catch(d){return{tag:"error",value:i,error:d}}},{name:e,describeKind:"derived",meta:jt("classify",o.meta)});return this.add(a,{name:e}),a}combine(e,n,r={}){let o=Object.keys(n),s=o.map(i=>this._resolveStep(n[i])),a=A(s,i=>{let d={};for(let u=0;u<o.length;u++)d[o[u]]=i[u];return d},{name:e,describeKind:"derived",meta:jt("combine",r.meta)});return this.add(a,{name:e}),a}approvalGate(e,n,r={}){let o=r.maxPending??1e3;if(o<1&&o!==Number.POSITIVE_INFINITY)throw new RangeError("approvalGate: maxPending must be >= 1");let s=r.startOpen??!1;typeof n!="string"&&this.nameOf(n)===void 0&&this.add(n,{name:`${e}/source`});let a=this._resolveStep(n),i=new ie(`${e}_state`),d=F([],{name:"pending",equals:()=>!1}),u=F(s,{name:"isOpen"}),c=A([d],([G])=>G.length,{name:"count"}),l=F(0,{name:"droppedCount"}),p=xt({name:"decisions",retainedLimit:1024,graph:i});i.add(d,{name:"pending"}),i.add(u,{name:"isOpen"}),i.add(c,{name:"count"}),i.add(l,{name:"droppedCount"}),this.mount(`${e}_state`,i);let f=[],m=!1,h=!1,g=s,b=u.subscribe(G=>{for(let j of G)j[0]===D&&(g=j[1])});this.addDisposer(b);function T(){d.emit([...f])}function y(G,j,E){p.append({action:G,t_ns:ce(),...j!==void 0?{items:j,count:j.length}:{},...E!==void 0?{unflushed:E}:{},...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}function v(G){if(f.push(G),f.length>o){let j=f.shift();l.emit(l.cache+1),y("drop",[j])}T()}function k(G){let j=f.splice(0,G);return T(),j}let N=te([a],(G,j,E)=>{let C=E.terminalDeps[0];if(C!==void 0){m=!0;let he=f.length;f=[],T(),y("teardown",void 0,he),j.down(C===!0?[[$]]:[[P,C]]);return}let J=G[0];if(J==null||J.length===0){j.down([[U]]);return}for(let he of J)g?j.emit(he):(v(he),j.down([[U]]))},{name:e,describeKind:"derived",meta:jt("approval_gate",r.meta)});if(this.add(N,{name:e}),r.approver!=null){r.approver.cache&&(u.emit(!0),g=!0,r.onceOnly&&(h=!0));let j=r.approver.subscribe(E=>{for(let C of E){if(C[0]!==D)continue;let J=!!C[1];if(J&&!g){if(r.onceOnly){if(h)continue;h=!0}re(()=>{u.emit(!0);let he=k(f.length);y("open",he);for(let B of he){if(m)break;N.emit(B)}})}else if(!J&&g){if(r.onceOnly&&h)continue;re(()=>{u.emit(!1),y("close")})}}});this.addDisposer(j)}let w=G=>{if(m)throw new Error(`approvalGate: ${G}() called after the gate was torn down`)},R=(G=1)=>{w("approve");let j=k(G);for(let E of j){if(m)break;N.emit(E)}},x=(G=1)=>{w("reject"),k(G)},_=(G,j=1)=>{w("modify");let E=[...f],C=k(j);for(let J=0;J<C.length&&!m;J++)N.emit(G(C[J],J,E))},M=()=>{w("open"),u.emit(!0);let G=k(f.length);for(let j of G){if(m)break;N.emit(j)}},L=()=>{w("close"),!(r.onceOnly&&h)&&u.emit(!1)},S=Rt(R,{audit:p,freeze:!1,onSuccess:(G,j,E)=>({action:"approve",count:G[0]??1,t_ns:E.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(G,j,E)=>({action:"drop",t_ns:E.t_ns,errorType:E.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),O=Rt(x,{audit:p,freeze:!1,onSuccess:(G,j,E)=>({action:"reject",count:G[0]??1,t_ns:E.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(G,j,E)=>({action:"drop",t_ns:E.t_ns,errorType:E.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),I=Rt(_,{audit:p,freeze:!1,onSuccess:(G,j,E)=>({action:"modify",count:G[1]??1,t_ns:E.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(G,j,E)=>({action:"drop",t_ns:E.t_ns,errorType:E.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),K=Rt(M,{audit:p,freeze:!1,onSuccess:(G,j,E)=>({action:"open",t_ns:E.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(G,j,E)=>({action:"drop",t_ns:E.t_ns,errorType:E.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),q=Rt(L,{audit:p,freeze:!1,onSuccess:(G,j,E)=>({action:"close",t_ns:E.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(G,j,E)=>({action:"drop",t_ns:E.t_ns,errorType:E.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})});return this.addDisposer(c.subscribe(()=>{})),{node:N,pending:d,count:c,isOpen:u,droppedCount:l,decisions:p,audit:p,approve:S,reject:O,modify:I,open:K,close:q}}approval(e,n,r,o={}){return this.approvalGate(e,n,{...o,approver:r,maxPending:1})}catch(e,n,r,o={}){let s=this._resolveStep(n),a=o.on??"errored",i=te([s],(d,u,c)=>{let l=c.terminalDeps[0];if(l!==void 0){let f=l===!0?{kind:"completed"}:{kind:"errored",error:l};if(a==="terminal"||a===f.kind){u.emit(r(f,u));return}u.down(f.kind==="completed"?[[$]]:[[P,f.error]]);return}let p=d[0];if(p==null||p.length===0){u.down([[U]]);return}for(let f of p)u.emit(f)},{name:e,describeKind:"derived",completeWhenDepsComplete:o.completeWhenDepsComplete??!(a==="completed"||a==="terminal"),errorWhenDepsError:!(a==="errored"||a==="terminal"),meta:jt("catch",o.meta)});return this.add(i,{name:e}),i}_resolveStep(e){if(typeof e=="string")return this.resolve(e);if(this.nameOf(e)===void 0)throw new Error(`PipelineGraph "${this.name}": Node dep is not registered. Pass a string path or call graph.add(node) first.`);return e}};function Jr(t,e){let n=new An(t,e),{factory:r,factoryArgs:o,...s}=e??{};return n.tagFactory("pipelineGraph",We(s)),n}async function js(t,e,n,r){let o="",s=0;for await(let a of t.stream(e,n))r.publish({...a,seq:s++,ts:ce()}),a.type==="token"&&(o+=a.delta);return o}function Bs(t,e){if(e==="json")try{return JSON.parse(kt(t))}catch(n){let r=t.slice(0,160);throw new Error(`streamingPromptNode: format:"json" \u2014 failed to parse accumulated text as JSON: ${n.message}; content preview: ${r}`)}return t}function Vs(t,e){return A([t.latest],([n],r)=>{let o=r.store;if(n==null)return o.acc??"";let s=n;return s.seq===0&&(o.acc=""),s.type==="token"&&(o.acc=(o.acc??"")+s.delta),o.acc??""},{name:e,meta:W("accumulated_text"),initial:""})}function dd(t,e,n,r){let o=r?.name??"llm",s=r?.format??"text",a=Hr(`${o}/stream`,{...r?.retainedLimit!=null?{retainedLimit:r.retainedLimit}:{}}),i=A(e,l=>{if(l.some(f=>f==null))return[];let p=typeof n=="string"?n:n(...l);return p?[{role:"user",content:p}]:[]},{name:`${o}::messages`,meta:W("prompt_node::messages"),initial:[]}),d=ae(i,l=>{let p=l;if(!p||p.length===0)return F(null);let f=new AbortController;async function*m(){try{let h=await js(t,p,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,signal:f.signal},a);yield Bs(h,s)}finally{f.abort()}}return V(m())},{meta:le("streamingPromptNode")}),u=Vs(a,`${o}::accumulatedText`),c=Y(d);return{output:d,deltaTopic:a,accumulatedText:u,dispose:()=>{c(),a.destroy()}}}function ud(t,e,n,r,o,s){let a=F(0,{name:`${e}/cancel`}),i=0,d=[...r,a],u=s?.name??e,c=s?.format??"text",l=Hr(`${u}/stream`,{...s?.retainedLimit!=null?{retainedLimit:s.retainedLimit}:{}}),p=A(d,w=>{let R=w.slice(0,-1);if(R.some(_=>_==null))return[];let x=typeof o=="string"?o:o(...R);return x?[{role:"user",content:x}]:[]},{name:`${u}::messages`,meta:W("prompt_node::messages"),initial:[]}),f=ae(p,w=>{let R=w;if(!R||R.length===0)return F(null);let x=new AbortController;async function*_(){try{let M=await js(n,R,{model:s?.model,temperature:s?.temperature,maxTokens:s?.maxTokens,systemPrompt:s?.systemPrompt,signal:x.signal},l);yield Bs(M,c)}finally{x.abort()}}return V(_())},{meta:le("gatedStream")}),m=Vs(l,`${u}::accumulatedText`),h=us(f,w=>w!=null);t.add(h,{name:`${e}/raw`});let g=Jr(`${e}/gate-graph`);t.mount(`${e}/gate-graph`,g),g.add(h,{name:`${e}/raw`});let b=g.approvalGate(`${e}/gate`,`${e}/raw`,s?.gate),T=Y(f),y=Y(b.node),v=Y(m);t.addDisposer(T),t.addDisposer(y),t.addDisposer(v);let k=b.reject.bind(b),N={...b,reject(w=1){re(()=>{k(w),a.emit(++i)})}};return{output:b.node,deltaTopic:l,accumulatedText:m,gate:N,dispose:()=>{T(),y(),v(),l.destroy()}}}Q();Z();function cd(t,e){let n=e?.separator??`
8
+ `)}]});let s={};return e?.maxTokens!=null&&(s.maxOutputTokens=e.maxTokens),e?.temperature!=null&&(s.temperature=e.temperature),e?.maxReasoningTokens!=null&&(s.thinkingConfig={thinkingBudget:e.maxReasoningTokens}),Object.keys(s).length>0&&(o.generationConfig=s),e?.tools&&e.tools.length>0&&(o.tools=[{functionDeclarations:e.tools.map(_a)}]),e?.providerExtras&&Object.assign(o,e.providerExtras),o}function _a(t){return{name:t.name,description:t.description,parameters:t.parameters}}function Ms(t,e,n){let r={},o=t.generationConfig;o&&(typeof o.maxOutputTokens=="number"&&(r.maxOutputTokens=o.maxOutputTokens),typeof o.temperature=="number"&&(r.temperature=o.temperature),o.thinkingConfig&&(r.thinkingConfig=o.thinkingConfig)),t.systemInstruction&&(r.systemInstruction=t.systemInstruction),t.tools&&(r.tools=t.tools);for(let[s,a]of Object.entries(t))s==="contents"||s==="generationConfig"||s==="systemInstruction"||s==="tools"||s==="abortSignal"||s==="model"||(r[s]=a);return n&&(r.abortSignal=n),{model:e,contents:t.contents,config:Object.keys(r).length>0?r:void 0}}function Cr(t){let e={input:{regular:0},output:{regular:0},raw:t};if(!t)return e;let n=t.promptTokenCount??0,r=t.cachedContentTokenCount??0;if(e.input.regular=Math.max(0,n-r),r>0&&(e.input.cacheRead=r),t.toolUsePromptTokenCount&&(e.input.toolUse=t.toolUsePromptTokenCount),t.promptTokensDetails)for(let o of t.promptTokensDetails){let s=o.modality?.toLowerCase();s==="image"?e.input.image=(e.input.image??0)+o.tokenCount:s==="audio"?e.input.audio=(e.input.audio??0)+o.tokenCount:s==="video"&&(e.input.video=(e.input.video??0)+o.tokenCount)}return e.output.regular=t.candidatesTokenCount??0,t.thoughtsTokenCount&&(e.output.reasoning=t.thoughtsTokenCount),e}function Os(t,e){let n=t.candidates?.[0],r=n?.content?.parts??[],o=[],s=[],a=0;for(let i of r)typeof i.text=="string"&&o.push(i.text),i.functionCall&&s.push({id:`${i.functionCall.name}-${a++}`,name:i.functionCall.name,arguments:i.functionCall.args??{}});return{content:o.join(""),toolCalls:s.length>0?s:void 0,usage:Cr(t.usageMetadata),finishReason:n?.finishReason,latencyMs:e,model:t.modelVersion,provider:"google"}}function Ma(t){if(t.apiKey)return t.apiKey;let e=globalThis.process?.env;return e?.GOOGLE_API_KEY??e?.GEMINI_API_KEY}function Oa(t){let e=t.baseURL??"https://generativelanguage.googleapis.com/v1beta",n=t.fetchImpl??fetch,r=s=>{let a=s?.model??t.model;if(!a)throw new Error("googleAdapter: model must be set via options.model or invokeOpts.model");return a},o=()=>{let s=Ma(t);if(!s)throw new Error("googleAdapter: apiKey required for invoke/stream");return`key=${encodeURIComponent(s)}`};return{provider:"google",model:t.model,async invoke(s,a){let i=r(a),d=Nn(s,a),u=z(),c=`${e}/models/${encodeURIComponent(i)}:generateContent?${o()}`,l=await n(c,{method:"POST",headers:{"content-type":"application/json",...t.headers??{}},body:JSON.stringify(d),signal:a?.signal});if(!l.ok)throw await qe(l,"Google");let p=await l.json(),f=Math.max(0,(z()-u)/1e6);return Os(p,f)},async*stream(s,a){let i=r(a),d=Nn(s,a),u=`${e}/models/${encodeURIComponent(i)}:streamGenerateContent?alt=sse&${o()}`,c=await n(u,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",...t.headers??{}},body:JSON.stringify(d),signal:a?.signal});if(!c.ok)throw await qe(c,"Google");if(!c.body)throw new Error("googleAdapter: streaming response has no body");let l,p;for await(let f of wt(c.body,{signal:a?.signal})){if(!f.data)continue;let m;try{m=JSON.parse(f.data)}catch{continue}let h=m.candidates?.[0];for(let g of h?.content?.parts??[])typeof g.text=="string"&&(g.thought?yield{type:"thinking",delta:g.text}:yield{type:"token",delta:g.text}),g.functionCall&&(yield{type:"tool-call-delta",delta:{name:g.functionCall.name,argumentsDelta:JSON.stringify(g.functionCall.args??{})}});h?.finishReason&&(p=h.finishReason),m.usageMetadata&&(l=m.usageMetadata)}l&&(yield{type:"usage",usage:Cr(l)}),yield{type:"finish",reason:p??"stop"}}}}function Ea(t){let e=t.sdk;if(!e)throw new Error("sdkBackedGoogle: sdk instance required");return{provider:"google",model:t.model,async invoke(n,r){let o=Nn(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let a=Ms(o,s,r?.signal),i=z(),d=await e.models.generateContent(a),u=Math.max(0,(z()-i)/1e6);return Os(d,u)},async*stream(n,r){if(!e.models.generateContentStream)throw new Error("sdkBackedGoogle: SDK instance does not expose generateContentStream");let o=Nn(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let a=Ms(o,s,r?.signal),i,d,u=await e.models.generateContentStream(a);for await(let c of u){let l=c.candidates?.[0];for(let p of l?.content?.parts??[])typeof p.text=="string"&&(p.thought?yield{type:"thinking",delta:p.text}:yield{type:"token",delta:p.text}),p.functionCall&&(yield{type:"tool-call-delta",delta:{name:p.functionCall.name,argumentsDelta:JSON.stringify(p.functionCall.args??{})}});l?.finishReason&&(d=l.finishReason),c.usageMetadata&&(i=c.usageMetadata)}i&&(yield{type:"usage",usage:Cr(i)}),yield{type:"finish",reason:d??"stop"}}}}ye();var Aa={openai:{baseURL:"https://api.openai.com/v1",apiKeyEnv:"OPENAI_API_KEY",provider:"openai"},openrouter:{baseURL:"https://openrouter.ai/api/v1",apiKeyEnv:"OPENROUTER_API_KEY",provider:"openrouter"},groq:{baseURL:"https://api.groq.com/openai/v1",apiKeyEnv:"GROQ_API_KEY",provider:"groq"},ollama:{baseURL:"http://localhost:11434/v1",provider:"ollama"},deepseek:{baseURL:"https://api.deepseek.com/v1",apiKeyEnv:"DEEPSEEK_API_KEY",provider:"deepseek"},xai:{baseURL:"https://api.x.ai/v1",apiKeyEnv:"XAI_API_KEY",provider:"xai"}};function Lr(t={}){return t.sdk?Pa(t):Ia(t)}function Sn(t,e,n,r,o){let s=e?.model??n;if(!s)throw new Error("openAICompatAdapter: model must be set via options.model or invokeOpts.model");let a=t.map(Ca);e?.systemPrompt&&!t.some(d=>d.role==="system")&&a.unshift({role:"system",content:e.systemPrompt});let i={model:s,messages:a};return e?.maxTokens!=null&&(i.max_tokens=e.maxTokens),e?.temperature!=null&&(i.temperature=e.temperature),e?.tools&&e.tools.length>0&&(i.tools=e.tools.map(La)),e?.maxReasoningTokens!=null&&(i.reasoning={max_tokens:e.maxReasoningTokens}),r&&(i.stream=!0,i.stream_options={include_usage:!0}),o&&Object.assign(i,o),e?.providerExtras&&Object.assign(i,e.providerExtras),i}function Ca(t){return t.role==="tool"?{role:"tool",tool_call_id:t.toolCallId,content:t.content}:t.role==="assistant"&&t.toolCalls&&t.toolCalls.length>0?{role:"assistant",content:t.content||null,tool_calls:t.toolCalls.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.arguments)}}))}:{role:t.role,content:t.content}}function La(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}}function Dr(t){let e={input:{regular:0},output:{regular:0},raw:t};if(!t)return e;let n=t.prompt_tokens??0,r=t.prompt_tokens_details?.cached_tokens??0;t.prompt_cache_hit_tokens!=null?(r=t.prompt_cache_hit_tokens,e.input.regular=t.prompt_cache_miss_tokens??Math.max(0,n-r)):e.input.regular=Math.max(0,n-r),r>0&&(e.input.cacheRead=r),t.prompt_tokens_details?.audio_tokens&&(e.input.audio=t.prompt_tokens_details.audio_tokens);let o=t.completion_tokens??0,s=t.completion_tokens_details?.reasoning_tokens??0;return e.output.regular=Math.max(0,o-s),s>0&&(e.output.reasoning=s),t.completion_tokens_details?.audio_tokens&&(e.output.audio=t.completion_tokens_details.audio_tokens),t.completion_tokens_details?.accepted_prediction_tokens&&(e.output.predictionAccepted=t.completion_tokens_details.accepted_prediction_tokens),t.completion_tokens_details?.rejected_prediction_tokens&&(e.output.predictionRejected=t.completion_tokens_details.rejected_prediction_tokens),e}function Es(t,e,n){let r=t.choices[0],o=r?.message,s=o?.content??"",a=(o?.tool_calls??[]).map(i=>({id:i.id,name:i.function.name,arguments:Da(i.function.arguments)}));return{content:s,toolCalls:a.length>0?a:void 0,usage:Dr(t.usage),finishReason:r?.finish_reason,latencyMs:e,model:t.model,provider:n}}function Da(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!=null?e:{_raw:t}}catch{return{_raw:t}}}function As(t){let e=t.preset??"openai",n=Aa[e],r=t.baseURL??n.baseURL,o=t.provider??n.provider,s=n.apiKeyEnv,a=t.apiKey??(s?globalThis.process?.env?.[s]:void 0);return{provider:o,baseURL:r,apiKey:a}}function Ia(t){let{provider:e,baseURL:n,apiKey:r}=As(t),o=t.fetchImpl??fetch,s=e!=="ollama",a=()=>{let i={"content-type":"application/json",...t.headers??{}};if(s){if(!r)throw new Error(`openAICompatAdapter[${e}]: apiKey required for invoke/stream`);i.authorization=`Bearer ${r}`}return i};return{provider:e,model:t.model,async invoke(i,d){let u=Sn(i,d,t.model,!1,t.bodyExtras),c=z(),l=await o(`${n}/chat/completions`,{method:"POST",headers:a(),body:JSON.stringify(u),signal:d?.signal});if(!l.ok)throw await qe(l,e);let p=await l.json(),f=Math.max(0,(z()-c)/1e6);return Es(p,f,e)},async*stream(i,d){let u=Sn(i,d,t.model,!0,t.bodyExtras),c=await o(`${n}/chat/completions`,{method:"POST",headers:{...a(),accept:"text/event-stream"},body:JSON.stringify(u),signal:d?.signal});if(!c.ok)throw await qe(c,e);if(!c.body)throw new Error(`openAICompatAdapter[${e}]: streaming response has no body`);let l,p;for await(let f of wt(c.body,{signal:d?.signal})){if(!f.data||f.data==="[DONE]")continue;let m;try{m=JSON.parse(f.data)}catch{continue}let h=m.choices;if(h){let g=h[0];if(g?.delta?.content&&(yield{type:"token",delta:g.delta.content}),g?.delta?.reasoning_content&&(yield{type:"thinking",delta:g.delta.reasoning_content}),g?.delta?.tool_calls)for(let y of g.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:y.id,name:y.function?.name,argumentsDelta:y.function?.arguments}};g?.finish_reason&&(p=g.finish_reason)}m.usage&&(l=m.usage,yield{type:"usage",usage:Dr(l)})}yield{type:"finish",reason:p??"stop"}}}}function Pa(t){let e=t.sdk;if(!e)throw new Error("sdkBackedOpenAI: sdk instance required");let{provider:n}=As(t);return{provider:n,model:t.model,async invoke(r,o){let s=Sn(r,o,t.model,!1,t.bodyExtras),a=z(),i=await e.chat.completions.create(s,{signal:o?.signal}),d=Math.max(0,(z()-a)/1e6);return Es(i,d,n)},async*stream(r,o){let s=Sn(r,o,t.model,!0,t.bodyExtras),a=await e.chat.completions.create(s,{signal:o?.signal}),i,d;for await(let u of a){let c=u.choices;if(c){let p=c[0];if(p?.delta?.content&&(yield{type:"token",delta:p.delta.content}),p?.delta?.reasoning_content&&(yield{type:"thinking",delta:p.delta.reasoning_content}),p?.delta?.tool_calls)for(let f of p.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:f.id,name:f.function?.name,argumentsDelta:f.function?.arguments}};p?.finish_reason&&(d=p.finish_reason)}let l=u.usage;l&&(i=l,yield{type:"usage",usage:Dr(l)})}yield{type:"finish",reason:d??"stop"}}}}function Ga(t){switch(t.provider){case"anthropic":{let e={apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return xr(e)}case"google":{let e={apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return Ar(e)}case"dry-run":{let e={model:t.model,...t.extras};return ut(e)}case"fallback":{let e={provider:t.provider,model:t.model,...t.extras};return Er(e)}case"openai":case"openrouter":case"groq":case"ollama":case"deepseek":case"xai":{let e={preset:t.provider,apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,bodyExtras:t.bodyExtras,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return Lr(e)}default:{let e=t.provider;throw new Error(`createAdapter: unknown provider: ${String(e)}`)}}}ye();Q();Oe();ie();ke();Q();var Ir=class{_version=0;_maxSize;_buf;_head=0;_size=0;constructor(e,n){if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(this._maxSize=n,n!==void 0){if(this._buf=new Array(n),e&&e.length>0){let r=Math.min(e.length,n),o=e.length-r;for(let s=0;s<r;s++)this._buf[s]=e[o+s];this._size=r}}else this._buf=e?[...e]:[],this._size=this._buf.length}get version(){return this._version}get size(){return this._size}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._size+e;if(!(n<0||n>=this._size))return this._maxSize!==void 0?this._buf[(this._head+n)%this._maxSize]:this._buf[n]}append(e){this._rawAppend(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._maxSize!==void 0&&e.length>this._maxSize?e.length-this._maxSize:0;for(let r=n;r<e.length;r++)this._rawAppend(e[r]);this._version+=1}clear(){if(this._size===0)return 0;let e=this._size;if(this._maxSize===void 0)this._buf.length=0;else for(let n=0;n<e;n++)this._buf[(this._head+n)%this._maxSize]=void 0;return this._head=0,this._size=0,this._version+=1,e}trimHead(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`trimHead: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return 0;let n=Math.min(e,this._size);if(this._maxSize===void 0)this._buf.splice(0,n);else{for(let r=0;r<n;r++)this._buf[(this._head+r)%this._maxSize]=void 0;this._head=(this._head+n)%this._maxSize}return this._size-=n,this._version+=1,n}slice(e,n){if(!Number.isInteger(e)||e<0)throw new RangeError(`slice: start must be a non-negative integer (got ${e})`);if(n!==void 0&&(!Number.isInteger(n)||n<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${n})`);let r=n===void 0?this._size:Math.min(Math.max(n,0),this._size),o=Math.min(e,this._size);if(o>=r)return[];let s=r-o;if(this._maxSize===void 0)return this._buf.slice(o,r);let a=new Array(s);for(let i=0;i<s;i++)a[i]=this._buf[(this._head+o+i)%this._maxSize];return a}tail(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`tail: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return[];let n=Math.min(e,this._size);return this.slice(this._size-n,this._size)}toArray(){if(this._maxSize===void 0)return[...this._buf];let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this._buf[(this._head+n)%this._maxSize];return e}snapshot(){return this.toArray()}restore(e){if(this._maxSize===void 0){this._buf.length=0;for(let n=0;n<e.length;n++)this._buf.push(e[n]);this._size=this._buf.length}else{let n=this._maxSize;for(let s=0;s<n;s++)this._buf[s]=void 0;this._head=0;let r=Math.min(e.length,n),o=e.length-r;for(let s=0;s<r;s++)this._buf[s]=e[o+s];this._size=r}this._version+=1}_rawAppend(e){if(this._maxSize===void 0){this._buf.push(e),this._size=this._buf.length;return}this._size<this._maxSize?(this._buf[(this._head+this._size)%this._maxSize]=e,this._size+=1):(this._buf[this._head]=e,this._head=(this._head+1)%this._maxSize)}};function Ft(t){return t.subscribe(()=>{})}var Fa=64;function Ve(t,e={}){let{name:n,maxSize:r,versioning:o,guard:s,backend:a}=e,i=a??new Ir(t,r),d=F(i.toArray(),{name:n,describeKind:"state",equals:(T,x)=>T===x,...o!=null?{versioning:o}:{},...s!=null?{guard:s}:{}});function u(){let T=i.toArray();te(()=>{d.down([[X]],{internal:!0}),d.down([[D,T]],{internal:!0})})}let c=new Map,l=new Map,p=new Map;function f(T,x){return`${T}:${x===void 0?"END":x}`}function m(T){if(T.size<Fa)return;let x=T.keys().next();if(x.done)return;let N=T.get(x.value);N!==void 0&&N.dispose(),T.delete(x.value)}function h(T){let x=i.version;try{return T()}finally{i.version!==x&&u()}}function g(T){if(!Number.isInteger(T)||T<0)throw new RangeError(`tail: n must be a non-negative integer (got ${T})`);let x=c.get(T);if(x!==void 0)return c.delete(T),c.set(T,x),x.node;m(c);let N=C([d],([M])=>{let A=M;return T===0||A.length===0?[]:A.slice(Math.max(0,A.length-T))},{initial:i.tail(T),describeKind:"derived"}),_=Ft(N);return c.set(T,{node:N,dispose:_}),N}function y(T,x){if(!Number.isInteger(T)||T<0)throw new RangeError(`slice: start must be a non-negative integer (got ${T})`);if(x!==void 0&&(!Number.isInteger(x)||x<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${x})`);let N=f(T,x),_=l.get(N);if(_!==void 0)return l.delete(N),l.set(N,_),_.node;m(l);let M=C([d],([R])=>{let O=R;return x===void 0?O.slice(T):O.slice(T,x)},{initial:i.slice(T,x),describeKind:"derived"}),A=Ft(M);return l.set(N,{node:M,dispose:A}),M}function v(T){let x=p.get(T);if(x!==void 0)return x.node;let N=C([d,T],([M,A])=>{let R=M,O=Math.max(0,Math.trunc(A??0));return R.slice(O)},{initial:[],describeKind:"derived"}),_=Ft(N);return p.set(T,{node:N,dispose:_}),N}let b,w;function k(){b===void 0&&(b=ne([d],(T,x,N)=>{let _=T[0],A=_!=null&&_.length>0?_.at(-1):N.prevData[0];if(A==null||A.length===0){x.down([[U]]);return}x.emit(A[A.length-1])},{name:n!=null?`${n}::lastValue`:"lastValue",describeKind:"derived",initial:i.size===0?void 0:i.at(i.size-1)}),w=C([d],([T])=>T.length>0,{name:n!=null?`${n}::hasLatest`:"hasLatest",describeKind:"derived",initial:i.size>0}),Ft(b),Ft(w))}let S={entries:d,get size(){return i.size},at(T){return i.at(T)},append(T){h(()=>i.append(T))},appendMany(T){T.length!==0&&h(()=>i.appendMany(T))},clear(){h(()=>i.clear())},trimHead(T){h(()=>i.trimHead(T))},withLatest(){return k(),d},get lastValue(){return k(),b},get hasLatest(){return k(),w},view(T){switch(T.kind){case"tail":return g(T.n);case"slice":return y(T.start,T.stop);case"fromCursor":return v(T.cursor)}},attach(T){let x=T.subscribe(N=>{for(let _ of N)_[0]===D&&S.append(_[1])});return()=>x()},attachStorage(T){if(T.length===0)return()=>{};let x=new Map;for(let _ of T)x.set(_,i.size);(async()=>{for(let _ of T)if(typeof _.loadEntries=="function")try{let M=await Promise.resolve(_.loadEntries());M.entries.length>0&&i.size===0&&(i.restore(M.entries),x.set(_,M.entries.length),u());break}catch{}})();let N=d.subscribe(_=>{for(let M of _){if(M[0]!==D)continue;let A=M[1];for(let R of T){let O=x.get(R)??0;if(A.length<O){try{let K=R.appendEntries(A);K instanceof Promise&&K.catch(()=>{})}catch{}x.set(R,A.length);continue}if(A.length===O)continue;let I=A.slice(O);x.set(R,A.length);try{let K=R.appendEntries(I);K instanceof Promise&&K.catch(()=>{})}catch{}}}});return()=>N()},disposeAllViews(){for(let T of c.values())T.dispose();c.clear();for(let T of l.values())T.dispose();l.clear();for(let T of p.values())T.dispose();p.clear()},dispose(){for(let T of c.values())T.dispose();c.clear();for(let T of l.values())T.dispose();l.clear();for(let T of p.values())T.dispose();p.clear()}};return S}Z();function $e(t){let e=t.input,n=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 n;let r=0;for(let o of Object.values(e.extensions))r+=o;return n+r}function We(t){let e=t.output,n=e.regular+(e.reasoning??0)+(e.audio??0)+(e.predictionAccepted??0)+(e.predictionRejected??0);if(!e.extensions)return n;let r=0;for(let o of Object.values(e.extensions))r+=o;return n+r}function Cs(){return{input:{regular:0},output:{regular:0}}}function $a(t,e){let n=e?.logMax??1e3,r=Ve(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:n}),o=F(null,{name:"adapterStats/lastCall"}),s=C([r.entries],([h])=>h.length,{name:"adapterStats/totalCalls",initial:0}),a=C([r.entries],([h])=>h.reduce((g,y)=>g+$e(y.usage),0),{name:"adapterStats/totalInputTokens",initial:0}),i=C([r.entries],([h])=>h.reduce((g,y)=>g+We(y.usage),0),{name:"adapterStats/totalOutputTokens",initial:0}),d=[Y(s),Y(a),Y(i)],u=h=>{r.append(h),o.emit(h)},c=()=>{r.clear(),o.emit(null)},l=we(t,{invoke(h,g){let y=z(),v=ce(),b=t.model??g?.model??"",w=S=>(u(ct({provider:t.provider,model:t.model??g?.model??S.model??"",tier:g?.tier??S.tier,usage:S.usage??Be(),startNs:y,startWallClockNs:v,method:"invoke"})),S),k=S=>{let T=S;u(ct({provider:t.provider,model:b,tier:g?.tier,usage:Be(),startNs:y,startWallClockNs:v,method:"invoke",error:{type:T?.name??"Error",message:T?.message??String(S)}}))};return Rn(t.invoke(h,g),{onResp:w,onError:k,name:"adapterStats/invokeTap"})},async*stream(h,g){let y=z(),v=ce(),b=t.model??g?.model??"",w;try{for await(let k of t.stream(h,g))k.type==="usage"&&(w=k.usage),yield k;u(ct({provider:t.provider,model:b,tier:g?.tier,usage:w??Be(),startNs:y,startWallClockNs:v,method:"stream"}))}catch(k){let S=k;throw u(ct({provider:t.provider,model:b,tier:g?.tier,usage:w??Be(),startNs:y,startWallClockNs:v,method:"stream",error:{type:S?.name??"Error",message:S?.message??String(k)}})),k}}});Te(l,"observableAdapter",t);let p=!1;return{adapter:l,stats:{lastCall:o,allCalls:r,totalCalls:s,totalInputTokens:a,totalOutputTokens:i,reset:c,dispose:()=>{if(!p){p=!0;for(let h of d)h();d.length=0}}}}}function ja(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function Mn(t="USD"){return{total:0,currency:t}}function Pr(t,e,n){let r=$e(t),o=e.currency??"USD",s=n?.withBreakdown===!0,a=s?{}:null,i=0,d=(g,y,v)=>{if(!y||v==null)return;let b=ja(v,r),w=y*b/1e6;i+=w,s&&(a[g]=(a[g]??0)+w)},u=t.input,c=e.input;if(c&&(d("input.regular",u.regular,c.regular),d("input.cacheRead",u.cacheRead??0,c.cacheRead),d("input.cacheWrite5m",u.cacheWrite5m??0,c.cacheWrite5m),d("input.cacheWrite1h",u.cacheWrite1h??0,c.cacheWrite1h),d("input.cacheWriteOther",u.cacheWriteOther??0,c.cacheWriteOther),d("input.audio",u.audio??0,c.audio),d("input.image",u.image??0,c.image),d("input.video",u.video??0,c.video),d("input.toolUse",u.toolUse??0,c.toolUse),u.extensions&&c.extensions))for(let[g,y]of Object.entries(u.extensions))d(`input.ext.${g}`,y,c.extensions[g]);let l=t.output,p=e.output;if(p&&(d("output.regular",l.regular,p.regular),d("output.reasoning",l.reasoning??0,p.reasoning),d("output.audio",l.audio??0,p.audio),d("output.predictionAccepted",l.predictionAccepted??0,p.predictionAccepted),d("output.predictionRejected",l.predictionRejected??0,p.predictionRejected),l.extensions&&p.extensions))for(let[g,y]of Object.entries(l.extensions))d(`output.ext.${g}`,y,p.extensions[g]);let f=n?.tier;if(f&&e.tierMultipliers){let g=e.tierMultipliers[f];if(g!=null&&(i*=g,s))for(let y of Object.keys(a))a[y]*=g}let m=t.auxiliary,h=e.auxiliary;if(m&&h)for(let[g,y]of Object.entries(m)){let v=h[g];if(v==null||!y)continue;let b=y*v;i+=b,s&&(a[`auxiliary.${g}`]=b)}return s?{total:i,currency:o,breakdown:a}:{total:i,currency:o}}function _n(t,e){return`${t}::${e}`}function Ba(t){let e=new Map,n=new Map,r=(o,s,a)=>{e.set(_n(o,s),{provider:o,model:s,pricing:a});let i=n.get(o);i||(i=new Set,n.set(o,i)),i.add(s)};if(t)for(let[o,s,a]of t)r(o,s,a);return{register:r,lookup(o,s){let a=e.get(_n(o,s));if(a)return a.pricing;let i=n.get(o);if(!i)return;let d;for(let u of i)if(s.startsWith(u)&&(!d||u.length>d.key.length)){let c=e.get(_n(o,u));c&&(d={key:u,pricing:c.pricing})}return d?.pricing},remove(o,s){let a=e.delete(_n(o,s));if(a){let i=n.get(o);i?.delete(s),i&&i.size===0&&n.delete(o)}return a},entries(){let o=e.values();return(function*(){for(let{provider:s,model:a,pricing:i}of o)yield[s,a,i]})()}}}function Va(t,e="USD"){return(n,r)=>{let o=t.lookup(r.provider,r.model);return o?Pr(n,o,{tier:r.tier,withBreakdown:r.withBreakdown}):Mn(e)}}function Ka(...t){return(e,n)=>{for(let r of t){let o=r(e,n);if(o.total!==0)return o}return t.length>0?t[0](e,n):Mn()}}function za(t,e,n){return t?.pricing?Pr(e,t.pricing,n):Mn()}vt();Z();function Gr(t,e={}){let n=e.breaker??Xe(e),r=we(t,{async invoke(o,s){if(!n.canExecute())throw new Ze;try{let a=await Me(j(t.invoke(o,s)));return n.recordSuccess(),a}catch(a){throw n.recordFailure(a),a}},async*stream(o,s){if(!n.canExecute())throw new Ze;try{for await(let a of t.stream(o,s))yield a;n.recordSuccess()}catch(a){throw n.recordFailure(a),a}}});return Te(r,"withBreaker",t),{adapter:r,breaker:n}}ye();ie();Q();Z();var On=class extends Error{constructor(n,r,o){super(`Budget exhausted: ${n} (limit=${r}, observed=${o})`);this.which=n;this.limit=r;this.observed=o}name="BudgetExhaustedError"},Fr=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),Ls=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function $r(t,e){let n=Ve(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),r=F(Ls(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=C([r],([u])=>{let c=u;return!(e.caps.calls!=null&&c.calls>=e.caps.calls||e.caps.inputTokens!=null&&c.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&c.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&c.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(Y(o),e.onExhausted!=null){let u=e.onExhausted,c=!1,l=!0;o.subscribe(p=>{for(let f of p)if(f[0]===D){let m=f[1];if(c&&l&&m===!1){let h=Ds(r.cache??Fr,e.caps);h&&u(h)}l=m,c=!0}})}let s=()=>{if(o.cache===!1){let u=r.cache??Fr,c=Ds(u,e.caps);return new On(c??"budget",e.caps[c??"calls"]??0,Ua(u,c??"calls"))}},a=(u,c)=>{let l=t.provider,p=ct({provider:l,model:c.model,tier:c.tier,usage:u,startNs:c.startNs,method:c.method,...c.error?{error:c.error}:{}});n.append(p);let f=r.cache??Fr,m=e.pricingFn?f.usd+e.pricingFn(u,{model:c.model,provider:l,tier:c.tier}).total:f.usd;r.emit({calls:f.calls+1,inputTokens:f.inputTokens+$e(u),outputTokens:f.outputTokens+We(u),usd:m})},i=()=>{n.clear(),r.emit(Ls())},d=we(t,{invoke(u,c){let l=s();if(l)return Promise.reject(l);let p=z(),f=t.model??c?.model??"",m=g=>(a(g.usage??Be(),{model:t.model??c?.model??g.model??"",tier:c?.tier??g.tier,startNs:p,method:"invoke"}),g),h=g=>{let y=g;a(Be(),{model:f,tier:c?.tier,startNs:p,method:"invoke",error:{type:y?.name??"Error",message:y?.message??String(g)}})};return Rn(t.invoke(u,c),{onResp:m,onError:h,name:"budgetGate/invokeTap"})},async*stream(u,c){let l=s();if(l)throw l;let p=z(),f;try{for await(let m of t.stream(u,c))m.type==="usage"&&(f=m.usage),yield m;a(f??Be(),{model:t.model??c?.model??"",tier:c?.tier,startNs:p,method:"stream"})}catch(m){let h=m;throw a(f??Be(),{model:t.model??c?.model??"",tier:c?.tier,startNs:p,method:"stream",error:{type:h?.name??"Error",message:h?.message??String(m)}}),m}}});return Te(d,"withBudgetGate",t),{adapter:d,budget:{totals:r,isOpen:o,log:n,reset:i}}}function Ds(t,e){if(e.calls!=null&&t.calls>=e.calls)return"calls";if(e.inputTokens!=null&&t.inputTokens>=e.inputTokens)return"inputTokens";if(e.outputTokens!=null&&t.outputTokens>=e.outputTokens)return"outputTokens";if(e.usd!=null&&t.usd>=e.usd)return"usd"}function Ua(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}Z();function qa(t,e){let n=e.mock??ut({provider:t.provider,model:t.model}),r=typeof e.enabled=="boolean"?e.enabled:void 0,o=r===void 0?j(e.enabled):void 0,s;o&&(s=Y(o));let a=()=>r!==void 0?r:!!o?.cache,i=we(t,{invoke(u,c){return a()?n.invoke(u,c):t.invoke(u,c)},stream(u,c){return a()?n.stream(u,c):t.stream(u,c)}});return Te(i,"withDryRun",t),{adapter:i,dispose:()=>{s&&(s(),s=void 0)}}}function jr(t){if(t==null||typeof t!="object")return;let e=t,n=e.status,r=Wa(e.headers);if(n!==429&&n!==503&&!Za(e.message))return;let o={},s=r("retry-after"),a=Ja(s);a!=null&&(o.retryAfterMs=a);let i=r("anthropic-ratelimit-requests-reset");if(i){let f=Is(i);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let d=r("anthropic-ratelimit-tokens-reset");if(d){let f=Is(d);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let u=En(r,"x-ratelimit-limit-requests");u!=null&&(o.rpmCap=u);let c=En(r,"x-ratelimit-limit-tokens");c!=null&&(o.tpmCap=c);let l=En(r,"x-ratelimit-remaining-requests"),p=En(r,"x-ratelimit-remaining-tokens");if(l!=null&&u!=null&&u>0&&(o.usageHint??={},o.usageHint.rpm=1-l/u),p!=null&&c!=null&&c>0&&(o.usageHint??={},o.usageHint.tpm=1-p/c),o.retryAfterMs==null&&e.message){let f=Qa(e.message);f!=null&&(o.retryAfterMs=f)}return e.headers&&(o.metadata={headers:Ha(e.headers)}),o.retryAfterMs==null&&o.rpmCap==null&&o.tpmCap==null&&o.usageHint==null?o.metadata?o:void 0:o}function Wa(t){if(!t)return()=>{};if(typeof t.get=="function"){let r=t;return o=>r.get(o)??r.get(o.toLowerCase())??void 0}let e=t,n={};for(let[r,o]of Object.entries(e)){let s=Array.isArray(o)?o.join(", "):o;s!=null&&(n[r.toLowerCase()]=s)}return r=>n[r.toLowerCase()]}function Ha(t){let e={};if(typeof t.forEach=="function")return t.forEach((n,r)=>{e[r]=n}),e;for(let[n,r]of Object.entries(t))r!=null&&(e[n]=Array.isArray(r)?r.join(", "):r);return e}function En(t,e){let n=t(e);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function Ja(t){if(!t)return;let e=t.trim(),n=Number(e);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(e);if(Number.isFinite(r)){let o=r-Date.now();if(o>0)return o}}function Is(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var Ya=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function Qa(t){let e=Ya.exec(t);if(!e)return;let n=Number(e[1]);if(!Number.isFinite(n))return;let r=(e[2]??"s").toLowerCase();if(r==="ms")return n;if(r.startsWith("s"))return n*1e3;if(r.startsWith("m"))return n*6e4}var Xa=/rate\s*limit|too\s*many\s*requests|quota|429/i;function Za(t){return!!t&&Xa.test(t)}ye();ie();Q();vt();Z();ze();function Br(t){let e=new Error(t);return e.name="AbortError",e}function Gs(t={}){let e=Math.max(1,t.burstMultiplier??1),n=t.clampCooldownMs??6e4,r=t.rpm!=null?j(t.rpm):F(Number.POSITIVE_INFINITY),o=t.tpm!=null?j(t.tpm):F(Number.POSITIVE_INFINITY),s=F(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),a=F(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),i=F({},{name:"adaptiveRateLimiter/lastSignal"}),d=C([r,s],([R,O])=>Math.min(Number(R??1/0),Number(O??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),u=C([o,a],([R,O])=>Math.min(Number(R??1/0),Number(O??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),c=kt(Number(r.cache??Number.POSITIVE_INFINITY),e),l=kt(Number(o.cache??Number.POSITIVE_INFINITY),e),p=!1,f=!1,m=d.subscribe(R=>{for(let O of R)if(O[0]===D){let I=Number(O[1]);Number.isFinite(I)&&I>0?(c=kt(I,e),p=!1):I===1/0?(c=kt(1/0,e),p=!1):I<=0&&(p=!0)}}),h=u.subscribe(R=>{for(let O of R)if(O[0]===D){let I=Number(O[1]);Number.isFinite(I)&&I>0?(l=kt(I,e),f=!1):I===1/0?(l=kt(1/0,e),f=!1):I<=0&&(f=!0)}}),g=0,y=new ge,v=new ge,b;t.adaptation!=null&&(b=j(t.adaptation).subscribe(O=>{for(let I of O)I[0]===D&&w(I[1])}));function w(R){if(i.emit(R),R.rpmCap!=null&&Number.isFinite(R.rpmCap)&&R.rpmCap>=0&&(s.emit(R.rpmCap),Number.isFinite(n)&&n>0&&y.start(n,()=>s.emit(Number.POSITIVE_INFINITY))),R.tpmCap!=null&&Number.isFinite(R.tpmCap)&&R.tpmCap>=0&&(a.emit(R.tpmCap),Number.isFinite(n)&&n>0&&v.start(n,()=>a.emit(Number.POSITIVE_INFINITY))),R.retryAfterMs!=null&&R.retryAfterMs>0){let O=z()+R.retryAfterMs*1e6;O>g&&(g=O)}}let k=F(0,{name:"adaptiveRateLimiter/pending"}),S=F(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),T=F(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),x=R=>{k.emit((k.cache??0)+R)},N=()=>{S.emit(c.available()),T.emit(l.available())};async function _(R={}){let O=R.requestCost??1,I=R.tokenCost??0,K=R.signal;x(1);try{for(;;){if(K?.aborted)throw Br("AdaptiveRateLimiter.acquire aborted");let q=z();if(g>q){let L=Math.ceil((g-q)/1e6);await An(L,K);continue}if(O>0&&p||I>0&&f){await An(250,K);continue}let H=c,G=l;if(!H.tryConsume(O)){await An(Ps(H,O),K);continue}if(!(I>0?G.tryConsume(I):!0)){H.putBack(O),await An(Ps(G,I),K);continue}N();return}}finally{x(-1)}}function M(R){R>0?l.tryConsume(R):R<0&&l.putBack(-R),N()}function A(){m(),h(),b?.(),y.cancel(),v.cancel()}return{effectiveRpm:d,effectiveTpm:u,lastSignal:i,pending:k,rpmAvailable:S,tpmAvailable:T,acquire:_,recordUsage:M,recordSignal:w,dispose:A}}function kt(t,e){if(!Number.isFinite(t)||t===1/0)return Tt(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let n=Math.max(1,t*e),r=t/60;return Tt(n,r)}function Ps(t,e){let n=t.available(),r=Math.max(0,e-n);return r<=0?25:Math.min(5e3,Math.max(50,r*100))}function An(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Br("AdaptiveRateLimiter.acquire aborted")):new Promise((n,r)=>{let o=new ge,s,a=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{a(),n()}),e&&(s=()=>{a(),r(Br("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",s,{once:!0}))})}Z();function Vr(t,e={}){let n=e.limiter??Gs({name:e.name??"rateLimiter",rpm:e.rpm,tpm:e.tpm,adaptation:e.adaptation,burstMultiplier:e.burstMultiplier}),r=(a,i)=>e.costFn?e.costFn(a,i):0,o=a=>{let i=jr(a);i&&n.recordSignal(i)},s=we(t,{async invoke(a,i){let d=r(a,i);await n.acquire({requestCost:1,tokenCost:d,signal:i?.signal});try{let u=await Me(j(t.invoke(a,i))),c=u.usage??Cs(),p=$e(c)+We(c)-d;return p>0&&n.recordUsage(p),u}catch(u){throw o(u),u}},async*stream(a,i){let d=r(a,i);await n.acquire({requestCost:1,tokenCost:d,signal:i?.signal});try{let u=0;for await(let l of t.stream(a,i))l.type==="usage"&&(u=$e(l.usage)+We(l.usage)),yield l;let c=u-d;c>0&&n.recordUsage(c)}catch(u){throw o(u),u}}});return Te(s,"withRateLimiter",t),{adapter:s,limiter:n}}vt();Z();var $t=class extends Error{name="AllTiersExhaustedError";skipped;failed;constructor(e){let n=[];e.failed.size>0&&n.push(`failed=[${[...e.failed.keys()].join(",")}]`),e.skipped.length>0&&n.push(`skipped=[${e.skipped.map(r=>`${r.name}(${r.reason})`).join(",")}]`),super(`All LLM adapter tiers exhausted: ${n.join(" ")}`),this.skipped=e.skipped,this.failed=e.failed}};function Kr(t,e={}){if(t.length===0)throw new RangeError("cascadingLlmAdapter: tiers must be non-empty");let n=t.map(s=>({name:s.name,adapter:s.adapter,filter:s.filter,breaker:s.breaker?"canExecute"in s.breaker?s.breaker:Xe(s.breaker):void 0})),r=e.streamRetryBeforeFirstChunk??!0,o={provider:"cascading",model:void 0,async invoke(s,a){let i=[],d=new Map;for(let c=0;c<n.length;c++){let l=n[c];if(l.filter&&!l.filter(s,a)){i.push({name:l.name,reason:"filter"});continue}if(l.breaker&&!l.breaker.canExecute()){i.push({name:l.name,reason:"breaker"});continue}try{let p=await Me(j(l.adapter.invoke(s,a)));return l.breaker?.recordSuccess(),{...p,metadata:{...p.metadata??{},tier:l.name}}}catch(p){d.set(l.name,p),l.breaker?.recordFailure(p);let f=n[c+1];f&&e.onFallback?.(l.name,f.name,p)}}let u={skipped:i,failed:d};throw e.onExhausted?.(u),new $t(u)},async*stream(s,a){let i=[],d=new Map;for(let c=0;c<n.length;c++){let l=n[c];if(l.filter&&!l.filter(s,a)){i.push({name:l.name,reason:"filter"});continue}if(l.breaker&&!l.breaker.canExecute()){i.push({name:l.name,reason:"breaker"});continue}let p=!1;try{for await(let f of l.adapter.stream(s,a))p=!0,yield f;l.breaker?.recordSuccess();return}catch(f){if(d.set(l.name,f),l.breaker?.recordFailure(f),p||!r)throw f;let m=n[c+1];m&&e.onFallback?.(l.name,m.name,f)}}let u={skipped:i,failed:d};throw e.onExhausted?.(u),new $t(u)}};return Te(o,`cascade[${n.map(s=>s.name).join(",")}]`),o}function ed(t,e,n){let r={name:t,adapter:e};return n?.breaker&&(r.breaker=n.breaker),n?.filter&&(r.filter=n.filter),r}Z();ze();function Cn(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function Fs(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Cn()):new Promise((n,r)=>{let o=new ge,s,a=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{a(),n()}),e&&(s=()=>{a(),r(Cn())},e.addEventListener("abort",s,{once:!0}))})}function zr(t,e={}){let n=e.attempts??3,r=e.baseDelayMs??500,o=e.maxDelayMs??1e4,s=e.strategy??"decorrelated",a=e.jitter??!0,i=e.shouldRetry??td,d=e.retryStreaming??!0,u=(l,p)=>{if(s==="decorrelated"){let g=Math.min(o,Math.max(r,p*3));return r+Math.random()*(g-r)}let f=s==="exp"?r*2**(l-1):r*l,m=Math.min(o,f);if(!a)return m;let h=m*(.5+Math.random());return Math.min(o,h)},c=we(t,{async invoke(l,p){if(p?.signal?.aborted)throw Cn();let f,m=r;for(let h=1;h<=n;h++)try{return await Me(j(t.invoke(l,p)))}catch(g){if(f=g,h>=n||!i(g,h))throw g;let y=u(h,m);m=y,await Fs(y,p?.signal)}throw f},async*stream(l,p){if(p?.signal?.aborted)throw Cn();if(!d){for await(let h of t.stream(l,p))yield h;return}let f,m=r;for(let h=1;h<=n;h++){let g=!1;try{for await(let y of t.stream(l,p))g=!0,yield y;return}catch(y){if(f=y,g||h>=n||!i(y,h))throw y;let v=u(h,m);m=v,await Fs(v,p?.signal)}}throw f}});return Te(c,"withRetry",t),c}function td(t,e){if(t==null)return!1;let n=t;return n.name==="LLMTimeoutError"?!0:n.name==="AbortError"||n.message==="aborted"||n.name==="DOMException"&&n.code!=null&&Number(n.code)===20||n.name==="BudgetExhaustedError"||n.name==="CircuitOpenError"?!1:n.status!=null?n.status===429||n.status>=500&&n.status<600:n.code&&typeof n.code=="string"&&/^E[A-Z]+$/.test(n.code)?!0:n.message?/network|timeout|socket|fetch|econn|eai_/i.test(n.message):!1}Z();ze();var xt=class extends Error{constructor(n){super(`LLM call timed out after ${n}ms`);this.ms=n}name="LLMTimeoutError"};function Ur(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let n=s=>{let a=new AbortController,i=!1,d,u=new ge;return s&&(s.aborted?a.abort(s.reason):(d=()=>{u.cancel(),a.abort(s.reason)},s.addEventListener("abort",d,{once:!0}))),u.start(e,()=>{i=!0,a.abort(new xt(e))}),{signal:a.signal,cancel:()=>{u.cancel(),s&&d&&s.removeEventListener("abort",d)},timedOut:()=>i}},r=(s,a)=>{if(!a||s instanceof xt)throw s;let i=s;if(i?.name==="AbortError"||i?.name==="DOMException"&&Number(i.code)===20||s?.message==="aborted"){let u=new xt(e);throw u.cause=s,u}throw s},o=we(t,{async invoke(s,a){let{signal:i,cancel:d,timedOut:u}=n(a?.signal);try{return await Me(j(t.invoke(s,{...a,signal:i})))}catch(c){return r(c,u())}finally{d()}},async*stream(s,a){let{signal:i,cancel:d,timedOut:u}=n(a?.signal);try{for await(let c of t.stream(s,{...a,signal:i}))yield c}catch(c){r(c,u())}finally{d()}}});return Te(o,"withTimeout",t),o}function nd(t,e={}){let n={adapter:t},r=t;if(e.rateLimit){let o=Vr(r,e.rateLimit);r=o.adapter,n.rateLimiter=o.limiter}if(e.budget){let o=$r(r,e.budget);r=o.adapter,n.budget=o.budget}if(e.breaker){let o=Gr(r,e.breaker);r=o.adapter,n.breaker=o.breaker}if(e.timeoutMs!=null&&(r=Ur(r,e.timeoutMs)),e.retry&&(r=zr(r,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),r=Kr([{name:e.name??"primary",adapter:r},{name:"fallback",adapter:e.fallback}],o)}return e.cache&&(r=Gt(r,e.cache)),n.adapter=r,n}Ee();ke();Z();ie();Ye();Z();ze();function W(t,e){return ue("ai",t,e)}function rd(t){return t!=null&&typeof t.then=="function"}function qr(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function od(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var sd=3e4;function $s(t,e){if(t.status==="settled"){let r=t.cache;if(r!==void 0)return Promise.resolve(r)}let n=e?.timeoutMs??sd;return new Promise((r,o)=>{let s=new ge,a=t.subscribe(i=>{for(let d of i){if(d[0]===D){s.cancel(),a(),r(d[1]);return}if(d[0]===P){s.cancel(),a(),o(d[1]);return}if(d[0]===$){s.cancel(),a(),o(new Error("firstDataFromNode: completed without producing a value"));return}}});s.start(n,()=>{a(),o(new Error(`firstDataFromNode: timed out after ${n}ms`))})})}async function jt(t){return rd(t)?jt(await t):qr(t)?$s(t):od(t)?$s(j(t)):t}function Rt(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function id(t,e){let n=j(t),r=e?.refreshTrigger!=null?j(e.refreshTrigger):null,o=e?.name!==void 0?{name:e.name}:void 0,s=pe("frozenContext",o);return r==null?ne([n],(a,i,d)=>{if(d.store.emitted===!0)return;let c=a[0],l=c!=null&&c.length>0?c.at(-1):d.prevData[0];if(l!==void 0)return d.store.emitted=!0,i.emit(l),{invalidate:()=>{d.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:W("frozen_context",{...s})}):ne([n,r],(a,i,d)=>{let u=a[1];if(!(u!=null&&u.length>0))return;let l=a[0],p=l!=null&&l.length>0?l.at(-1):d.prevData[0];i.emit(p)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:W("frozen_context",{...s})})}Q();ie();Q();Pe();Z();function js(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function ad(t,e=200){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Wr(t,e,n,r){let o=r?.format??"text",s=r?.name??"prompt_node";r?.tools!==void 0&&o!=="raw"&&console.warn("promptNode: `tools` is set but `format !== 'raw'`. Tool calls in the response will be silently dropped \u2014 set `format: 'raw'` to receive the full LLMResponse with `toolCalls`.");let a=e.length,i=r?.tools!==void 0?[...e,r.tools]:e,d=C(i,c=>{let l=c.slice(0,a),p=r?.tools!==void 0?c[a]:void 0;if(l.some(m=>m==null))return{messages:[],tools:p};let f=typeof n=="string"?n:n(...l);return f?{messages:[{role:"user",content:f}],tools:p}:{messages:[],tools:p}},{name:`${s}::messages`,meta:W("prompt_node")});return de(d,c=>{let{messages:l,tools:p}=c;return!l||l.length===0?F(null):se(f=>{let m=!1,h=!1,g,y={model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,...p!==void 0?{tools:p}:{}};if(r?.abort){let k=ls(r.abort);y.signal=k.signal,g=k.dispose}let v;try{v=t.invoke(l,y)}catch(k){return m=!0,f.down([[P,k]]),()=>{g?.()}}let w=j(v).subscribe(k=>{if(!(h||m))for(let S of k){if(m)return;if(S[0]===D){let T=S[1];if(o==="raw")f.emit(T);else try{let x=js(T),N=o==="json"?JSON.parse(Rt(x)):x;f.emit(N)}catch(x){let N=js(T),_=new Error(`promptNode: failed to parse LLM response as JSON: ${x.message}
9
+ Raw content (first 200 chars): ${ad(N)}`);m=!0,f.down([[P,_]]);return}}else if(S[0]===P){m=!0,f.down([[P,S[1]]]);return}else if(S[0]===$){m=!0,f.down([[$]]);return}else f.down([S])}});return()=>{h=!0,w(),g?.()}},{name:`${s}::call`,meta:W("prompt_node::call")})},{name:`${s}::output`,meta:r?.meta?{...W("prompt_node::output"),...r.meta}:W("prompt_node::output")})}function Hr(t,e,n,r){let o=n.name??r;return s=>{let a=F(s);return Wr(n.adapter,[a],i=>e(i),{name:o,format:"json",systemPrompt:t,model:n.model,temperature:n.temperature??0,maxTokens:n.maxTokens})}}function Jr(t,e){let n=e.maxExistingKeys??100,r=Hr(t,o=>JSON.stringify({input:o.raw,existingKeys:o.existingKeys}),e,"llmExtractor");return(o,s)=>{let a=n===Number.POSITIVE_INFINITY?[...s.keys()]:[...s.keys()].slice(0,n);return r({raw:o,existingKeys:a})}}function Yr(t,e){let n=Hr(t,r=>JSON.stringify({memories:r}),e,"llmConsolidator");return r=>{let o=[...r.entries()].map(([s,a])=>({key:s,value:a}));return n(o)}}Oe();ye();Ee();Q();Pe();Z();Ht();ht();ie();Q();Ye();Oe();ye();ht();ie();Q();function Vs(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[X],[D,n+1]]),!0)}var dd=wo((t,e)=>{t("observe"),t("signal"),e("write")});function Nt(t){let e=Ve([],{name:t.name,maxSize:t.retainedLimit??1024,guard:t.guard??dd,...t.versioning!=null?{versioning:t.versioning}:{}});return e.withLatest(),t.graph&&t.graph.add(e.entries,{name:t.name}),e}function Qr(t){if(t===null||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.keys(t))Qr(t[e]);return Object.freeze(t)}var Bs=new WeakSet;function Bt(t){let e=t.cache,n=typeof e=="number"&&Number.isFinite(e);!n&&e!==void 0&&!Bs.has(t)&&(Bs.add(t),console.warn(`bumpCursor: cursor cache held a non-numeric value (${String(e)}); resetting to 0. Causes include: a snapshot codec round-tripping the cursor as a string / null / NaN, OR a malformed initial seed (e.g. state<number>(NaN)). Audit consumers may see colliding seq values after this point.`));let o=(n?e:0)+1;return t.down([[X],[D,o]]),o}function Ln(t,e,n,r,o,s){let a=e(n,r,o);if(a===void 0)return;let i=s!=null?{...a,handlerVersion:s}:a;t.append(i)}function xe(t,e){let n=e.freeze??!0;return function(...o){let s=n?o.map(Qr):o,a=ce(),i=e.seq?Bt(e.seq):void 0;try{let d=t(...s);return e.audit&&e.onSuccess&&Ln(e.audit,e.onSuccess,s,d,{t_ns:a,seq:i},e.handlerVersion),d}catch(d){if(e.audit&&e.onFailure){let u=d instanceof Error?d.name:typeof d;Ln(e.audit,e.onFailure,s,d,{t_ns:a,seq:i,errorType:u},e.handlerVersion)}throw d}}}function St(t,e){let n=e.freeze??!0;return function(...o){let s=n?o.map(Qr):o,a=ce(),i,d,u=!1,c;try{te(()=>{e.seq&&(c=Bt(e.seq));try{i=t(...s),e.audit&&e.onSuccess&&Ln(e.audit,e.onSuccess,s,i,{t_ns:a,seq:c},e.handlerVersion)}catch(l){throw d=l,u=!0,l}})}catch(l){if(u&&e.audit&&e.onFailure){let p=d instanceof Error?d.name:typeof d;Ln(e.audit,e.onFailure,s,d,{t_ns:a,seq:c,errorType:p},e.handlerVersion)}throw u?d:l}return i}}function Dn(t,e,n=0){let r=F(n,{name:e,describeKind:"state"});return t.add(r,{name:e}),r}Z();hr();function Ks(t,e){return ue("messaging",t,e)}var ud=1024,Xr=class extends ae{_log;_publishImpl;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=Ve([],{name:"events",maxSize:n.retainedLimit??ud}),this._log.withLatest(),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=C([this.events],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:Ks("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(Y(this.latest)),this.hasLatest=C([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:Ks("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(Y(this.hasLatest)),this.addDisposer(()=>{this.events.down([[$]])}),this.addDisposer(()=>this._log.disposeAllViews()),this._publishImpl=xe(r=>{this._log.append(r)},{freeze:!1})}publish(e){if(e===void 0)throw new TypeError(`TopicGraph "${this.name}": publish(undefined) is not allowed (spec \xA75.12 SENTINEL).`);this._publishImpl(e)}attachEventStorage(e){return this._log.attachStorage(e)}retained(){return this.events.cache}get _logBundle(){return this._log}};function Zr(t,e){return new Xr(t,e)}Oe();ye();ie();Ee();ke();Q();Ye();Ue();function Vt(t,e){return ue("orchestration",t,e)}var In=class extends ae{constructor(e,n){super(e,n)}task(e,n,r={}){let o=(r.deps??[]).map(a=>this._resolveStep(a)),s=C(o,n,{name:e,describeKind:"derived",meta:Vt("task",r.meta)});return this.add(s,{name:e}),s}classify(e,n,r,o={}){let s=this._resolveStep(n),a=C([s],([i])=>{try{return{tag:r(i),value:i}}catch(d){return{tag:"error",value:i,error:d}}},{name:e,describeKind:"derived",meta:Vt("classify",o.meta)});return this.add(a,{name:e}),a}combine(e,n,r={}){let o=Object.keys(n),s=o.map(i=>this._resolveStep(n[i])),a=C(s,i=>{let d={};for(let u=0;u<o.length;u++)d[o[u]]=i[u];return d},{name:e,describeKind:"derived",meta:Vt("combine",r.meta)});return this.add(a,{name:e}),a}approvalGate(e,n,r={}){let o=r.maxPending??1e3;if(o<1&&o!==Number.POSITIVE_INFINITY)throw new RangeError("approvalGate: maxPending must be >= 1");let s=r.startOpen??!1;typeof n!="string"&&this.nameOf(n)===void 0&&this.add(n,{name:`${e}/source`});let a=this._resolveStep(n),i=new ae(`${e}_state`),d=F([],{name:"pending",equals:()=>!1}),u=F(s,{name:"isOpen"}),c=C([d],([G])=>G.length,{name:"count"}),l=F(0,{name:"droppedCount"}),p=Nt({name:"decisions",retainedLimit:1024,graph:i});i.add(d,{name:"pending"}),i.add(u,{name:"isOpen"}),i.add(c,{name:"count"}),i.add(l,{name:"droppedCount"}),this.mount(`${e}_state`,i);let f=[],m=!1,h=!1,g=s,y=u.subscribe(G=>{for(let B of G)B[0]===D&&(g=B[1])});this.addDisposer(y);function v(){d.emit([...f])}function b(G,B,E){p.append({action:G,t_ns:ce(),...B!==void 0?{items:B,count:B.length}:{},...E!==void 0?{unflushed:E}:{},...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}function w(G){if(f.push(G),f.length>o){let B=f.shift();l.emit(l.cache+1),b("drop",[B])}v()}function k(G){let B=f.splice(0,G);return v(),B}let S=ne([a],(G,B,E)=>{let L=E.terminalDeps[0];if(L!==void 0){m=!0;let he=f.length;f=[],v(),b("teardown",void 0,he),B.down(L===!0?[[$]]:[[P,L]]);return}let J=G[0];if(J==null||J.length===0){B.down([[U]]);return}for(let he of J)g?B.emit(he):(w(he),B.down([[U]]))},{name:e,describeKind:"derived",meta:Vt("approval_gate",r.meta)});if(this.add(S,{name:e}),r.approver!=null){r.approver.cache&&(u.emit(!0),g=!0,r.onceOnly&&(h=!0));let B=r.approver.subscribe(E=>{for(let L of E){if(L[0]!==D)continue;let J=!!L[1];if(J&&!g){if(r.onceOnly){if(h)continue;h=!0}te(()=>{u.emit(!0);let he=k(f.length);b("open",he);for(let V of he){if(m)break;S.emit(V)}})}else if(!J&&g){if(r.onceOnly&&h)continue;te(()=>{u.emit(!1),b("close")})}}});this.addDisposer(B)}let T=G=>{if(m)throw new Error(`approvalGate: ${G}() called after the gate was torn down`)},x=(G=1)=>{T("approve");let B=k(G);for(let E of B){if(m)break;S.emit(E)}},N=(G=1)=>{T("reject"),k(G)},_=(G,B=1)=>{T("modify");let E=[...f],L=k(B);for(let J=0;J<L.length&&!m;J++)S.emit(G(L[J],J,E))},M=()=>{T("open"),u.emit(!0);let G=k(f.length);for(let B of G){if(m)break;S.emit(B)}},A=()=>{T("close"),!(r.onceOnly&&h)&&u.emit(!1)},R=St(x,{audit:p,freeze:!1,onSuccess:(G,B,E)=>({action:"approve",count:G[0]??1,t_ns:E.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(G,B,E)=>({action:"drop",t_ns:E.t_ns,errorType:E.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),O=St(N,{audit:p,freeze:!1,onSuccess:(G,B,E)=>({action:"reject",count:G[0]??1,t_ns:E.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(G,B,E)=>({action:"drop",t_ns:E.t_ns,errorType:E.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),I=St(_,{audit:p,freeze:!1,onSuccess:(G,B,E)=>({action:"modify",count:G[1]??1,t_ns:E.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(G,B,E)=>({action:"drop",t_ns:E.t_ns,errorType:E.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),K=St(M,{audit:p,freeze:!1,onSuccess:(G,B,E)=>({action:"open",t_ns:E.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(G,B,E)=>({action:"drop",t_ns:E.t_ns,errorType:E.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),q=St(A,{audit:p,freeze:!1,onSuccess:(G,B,E)=>({action:"close",t_ns:E.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(G,B,E)=>({action:"drop",t_ns:E.t_ns,errorType:E.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})});return this.addDisposer(c.subscribe(()=>{})),{output:S,pending:d,count:c,isOpen:u,droppedCount:l,decisions:p,audit:p,approve:R,reject:O,modify:I,open:K,close:q}}approval(e,n,r,o={}){return this.approvalGate(e,n,{...o,approver:r,maxPending:1})}catch(e,n,r,o={}){let s=this._resolveStep(n),a=o.on??"errored",i=ne([s],(d,u,c)=>{let l=c.terminalDeps[0];if(l!==void 0){let f=l===!0?{kind:"completed"}:{kind:"errored",error:l};if(a==="terminal"||a===f.kind){u.emit(r(f,u));return}u.down(f.kind==="completed"?[[$]]:[[P,f.error]]);return}let p=d[0];if(p==null||p.length===0){u.down([[U]]);return}for(let f of p)u.emit(f)},{name:e,describeKind:"derived",completeWhenDepsComplete:o.completeWhenDepsComplete??!(a==="completed"||a==="terminal"),errorWhenDepsError:!(a==="errored"||a==="terminal"),meta:Vt("catch",o.meta)});return this.add(i,{name:e}),i}_resolveStep(e){if(typeof e=="string")return this.resolve(e);if(this.nameOf(e)===void 0)throw new Error(`PipelineGraph "${this.name}": Node dep is not registered. Pass a string path or call graph.add(node) first.`);return e}};function eo(t,e){let n=new In(t,e),{factory:r,factoryArgs:o,...s}=e??{};return n.tagFactory("pipelineGraph",Je(s)),n}async function zs(t,e,n,r){let o="",s=0;for await(let a of t.stream(e,n))r.publish({...a,seq:s++,ts:ce()}),a.type==="token"&&(o+=a.delta);return o}function Us(t,e){if(e==="json")try{return JSON.parse(Rt(t))}catch(n){let r=t.slice(0,160);throw new Error(`streamingPromptNode: format:"json" \u2014 failed to parse accumulated text as JSON: ${n.message}; content preview: ${r}`)}return t}function qs(t,e){return C([t.latest],([n],r)=>{let o=r.store;if(n==null)return o.acc??"";let s=n;return s.seq===0&&(o.acc=""),s.type==="token"&&(o.acc=(o.acc??"")+s.delta),o.acc??""},{name:e,meta:W("accumulated_text"),initial:""})}function cd(t,e,n,r){let o=r?.name??"llm",s=r?.format??"text",a=Zr(`${o}/stream`,{...r?.retainedLimit!=null?{retainedLimit:r.retainedLimit}:{}}),i=C(e,l=>{if(l.some(f=>f==null))return[];let p=typeof n=="string"?n:n(...l);return p?[{role:"user",content:p}]:[]},{name:`${o}::messages`,meta:W("prompt_node::messages"),initial:[]}),d=de(i,l=>{let p=l;if(!p||p.length===0)return F(null);let f=new AbortController;async function*m(){try{let h=await zs(t,p,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,signal:f.signal},a);yield Us(h,s)}finally{f.abort()}}return j(m())},{meta:pe("streamingPromptNode")}),u=qs(a,`${o}::accumulatedText`),c=Y(d);return{output:d,deltaTopic:a,accumulatedText:u,dispose:()=>{c(),a.destroy()}}}function ld(t,e,n,r,o,s){let a=F(0,{name:`${e}/cancel`}),i=0,d=[...r,a],u=s?.name??e,c=s?.format??"text",l=Zr(`${u}/stream`,{...s?.retainedLimit!=null?{retainedLimit:s.retainedLimit}:{}}),p=C(d,T=>{let x=T.slice(0,-1);if(x.some(_=>_==null))return[];let N=typeof o=="string"?o:o(...x);return N?[{role:"user",content:N}]:[]},{name:`${u}::messages`,meta:W("prompt_node::messages"),initial:[]}),f=de(p,T=>{let x=T;if(!x||x.length===0)return F(null);let N=new AbortController;async function*_(){try{let M=await zs(n,x,{model:s?.model,temperature:s?.temperature,maxTokens:s?.maxTokens,systemPrompt:s?.systemPrompt,signal:N.signal},l);yield Us(M,c)}finally{N.abort()}}return j(_())},{meta:pe("gatedStream")}),m=qs(l,`${u}::accumulatedText`),h=fs(f,T=>T!=null);t.add(h,{name:`${e}/raw`});let g=eo(`${e}/gate-graph`);t.mount(`${e}/gate-graph`,g),g.add(h,{name:`${e}/raw`});let y=g.approvalGate(`${e}/gate`,`${e}/raw`,s?.gate),v=Y(f),b=Y(y.output),w=Y(m);t.addDisposer(v),t.addDisposer(b),t.addDisposer(w);let k=y.reject.bind(y),S={...y,reject(T=1){te(()=>{k(T),a.emit(++i)})}};return{output:y.output,deltaTopic:l,accumulatedText:m,gate:S,dispose:()=>{v(),b(),w(),l.destroy()}}}Q();Z();function pd(t,e){let n=e?.separator??`
10
10
 
11
- `,r=t.map(a=>typeof a=="string"?F(a):V(a)),o=A(r,a=>a.filter(i=>i!=null&&i!=="").join(n),{name:e?.name??"systemPrompt",describeKind:"derived",meta:W("system_prompt"),initial:""}),s=Y(o);return Object.assign(o,{dispose:s})}Q();var ld=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens&&t.estimated===e.estimated;function pd(t,e){let n=e?.charsPerToken??4,r={chunkCount:0,charCount:0,estimatedTokens:0,estimated:!0};return A([t.latest],([o],s)=>{if(o==null)return r;let a=o;"chunkCount"in s.store||(s.store.chunkCount=0,s.store.charCount=0,s.store.usageTokens=0,s.store.sawUsage=!1);let i=s.store;a.type==="token"?(i.chunkCount+=1,i.charCount+=a.delta.length):a.type==="usage"&&(i.sawUsage=!0,i.usageTokens=Fe(a.usage)+Ue(a.usage));let d=i.sawUsage?i.usageTokens:Math.ceil(i.charCount/n);return{chunkCount:i.chunkCount,charCount:i.charCount,estimatedTokens:d,estimated:!i.sawUsage}},{name:e?.name??"cost-meter",describeKind:"derived",initial:r,meta:W("cost_meter_extractor"),equals:ld})}Q();var fd=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.label!==o.label||r.pattern!==o.pattern||r.match!==o.match||r.position!==o.position)return!1}return!0};function md(t,e){let n=e.maxPatternLength??128;for(let o of e.patterns)if(o.pattern.source.length>n)throw new Error(`keywordFlagExtractor: pattern "${o.label}" literal exceeds maxPatternLength (${o.pattern.source.length} > ${n}); raise the option or shorten the pattern.`);let r=e.patterns.map(o=>({label:o.label,pattern:o.pattern,compiled:new RegExp(o.pattern.source,`${o.pattern.flags.replace("g","")}g`)}));return A([t],([o],s)=>{if(o==null)return[];let a=o;"flags"in s.store||(s.store.flags=[],s.store.scannedTo=0);let i=s.store.flags,d=s.store.scannedTo,u=Math.max(0,d-n),c=a.slice(u),l=!1;for(let{pattern:p,label:f,compiled:m}of r){m.lastIndex=0;for(let h of c.matchAll(m)){let g=u+(h.index??0);g+h[0].length<=d||(i.push({label:f,pattern:p,match:h[0],position:g}),l=!0)}}return s.store.scannedTo=a.length,l?[...i]:i.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:W("keyword_flag_extractor"),equals:fd})}Q();function gd(t,e,n){return A([t],([r])=>r==null?null:e(r),{name:n?.name??"extractor",describeKind:"derived",initial:null,meta:W("stream_extractor"),...n?.equals?{equals:n.equals}:{}})}Q();var hd=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.startIndex!==o.startIndex||r.name!==o.name||r.raw!==o.raw)return!1}return!0};function yd(t,e){return A([t],([n],r)=>{if(n==null)return[];let o=n;"calls"in r.store||(r.store.calls=[],r.store.scanFrom=0);let s=r.store.calls,a=r.store.scanFrom,i=!1;for(;a<o.length;){let d=o.indexOf("{",a);if(d===-1){r.store.scanFrom=o.length;break}let u=0,c=-1,l=!1;for(let f=d;f<o.length;f++){let m=o[f];if(l)m==="\\"&&f+1<o.length?f++:m==='"'&&(l=!1);else if(m==='"')l=!0;else if(m==="{")u++;else if(m==="}"&&(u--,u===0)){c=f;break}}if(c===-1){r.store.scanFrom=d;break}let p=o.slice(d,c+1);try{let f=JSON.parse(p);typeof f.name=="string"&&f.arguments!=null&&typeof f.arguments=="object"&&(s.push({name:f.name,arguments:f.arguments,raw:p,startIndex:d}),i=!0)}catch{}a=c+1,r.store.scanFrom=a}return i?[...s]:s.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:W("tool_call_extractor"),equals:hd})}Q();function bd(t,e,n,r){let o=n*(r?.hardMultiplier??1.5),s=typeof e!="function",a=[t];return s&&a.push(e),A(a,i=>{let d=i[0]??"";if(d.length===0)return"allow";let u=s?i[1]??0:e(d);return u>=o?"block":u>=n?"review":"allow"},{name:r?.name??"content-gate",initial:"allow"})}Q();function Td(t,e,n,r){let o=n??(()=>"[REDACTED]");function s(a){let i=a;for(let d of e){let u=d.global?d:new RegExp(d.source,`${d.flags}g`);i=i.replace(u,c=>o(c,d))}return i}return A([t],([a])=>s(a??""),{name:r?.name??"redactor",initial:""})}Q();Z();Ke();var Cn=class extends ie{_log;messages;latest;messageCount;constructor(e,n={}){super(e,n.graph),this._log=je([],{name:"messages",maxSize:n.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=A([this.messages],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:W("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(Y(this.latest)),this.messageCount=A([this.messages],([r])=>r.length,{name:"messageCount",describeKind:"derived",meta:W("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(Y(this.messageCount))}append(e,n,r){this._log.append({role:e,content:n,...r})}appendToolResult(e,n){this._log.append({role:"tool",content:n,toolCallId:e})}clear(){this._log.clear()}allMessages(){return this.messages.cache}};function Yr(t,e){return new Cn(t,e)}Oe();Q();Ie();Z();function vd(t,e,n){let r=V(t),o=n?.condition!=null?V(n.condition):null,s=F(null,{name:n?.name?`${n.name}::null`:"handoff::null"});if(o==null)return ae(r,i=>{if(i==null)return s;let d=F(i);return e(d)},{meta:le("handoff")});let a=A([r,o],([i,d])=>({v:i,open:d===!0}),{name:n?.name?`${n.name}::router`:"handoff::router",describeKind:"derived"});return ae(a,({v:i,open:d})=>{if(i==null)return s;if(!d)return F(i);let u=F(i);return e(u)},{meta:le("handoff")})}Q();Ie();bt();function Qr(t){let{toolCalls:e,tools:n}=t,r=t.retryCount??1,o=t.onError??"rescue",s=(a,i)=>{if(a===i)return!0;if(a.length!==i.length)return!1;for(let d=0;d<a.length;d++){let u=a[d],c=i[d];if(u?.id!==c?.id||u?.content!==c?.content)return!1}return!0};return ae(e,a=>{if(a==null||a.length===0)throw new Error("toolExecution: received an empty tool-call batch as DATA \u2014 callers must upstream-filter empty batches (emit RESOLVED) so switchMap is only dispatched for non-empty batches.");let i=a.map(d=>wd(d,n,r,o));return A(i,d=>d,{name:"toolExecution::batch",equals:s})})}function wd(t,e,n,r){let o=yt(()=>e.executeReactive(t.name,t.arguments),{count:n}),s=A([o],([a])=>({id:t.id,content:typeof a=="string"?a:JSON.stringify(a)}));return r==="propagate"?s:ps(s,a=>({id:t.id,content:JSON.stringify({error:String(a)})}))}de();Q();Z();Ke();var Ln=class extends ie{definitions;schemas;_bundle;constructor(e,n={}){super(e,n.graph),this._bundle=Ge({name:"definitions"}),this.definitions=this._bundle.entries,this.add(this.definitions,{name:"definitions"}),this.schemas=A([this.definitions],([r])=>[...(r??new Map).values()],{name:"schemas",describeKind:"derived",meta:W("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(Y(this.schemas))}register(e){this._bundle.set(e.name,e)}unregister(e){this._bundle.delete(e)}executeReactive(e,n){let r=this._bundle.get(e);if(!r)throw new Error(`toolRegistry: unknown tool "${e}"`);return se(o=>{let s=new AbortController,a;try{let d=r.handler(n,{signal:s.signal});a=kd(d,s.signal)}catch(d){return o.down([[P,d]]),()=>{s.abort()}}let i=a.subscribe(d=>{o.down(d)});return()=>{s.abort(),i()}},{name:`executeReactive::${e}`,meta:W("tool_execute_reactive")})}getDefinition(e){return this._bundle.entries.cache?.get(e)}};function Xr(t,e){return new Ln(t,e)}function kd(t,e){return Br(t)?t:t!=null&&typeof t.then=="function"?mn(t,{signal:e}):t!=null&&typeof t=="object"&&Symbol.asyncIterator in t?yr(t,{signal:e}):mn(Promise.resolve(t),{signal:e})}Oe();Q();Z();function xd(t,e,n){let r=V(t),o=e.map(a=>V(a)),s=[r,...o];return A(s,a=>{let i=a[0]??[],d=a.slice(1);return i.filter(u=>{for(let c of d)if(c!=null&&!c(u))return!1;return!0})},{name:n?.name??"tool-selector",describeKind:"derived",meta:{...W("tool_selector"),...le("toolSelector")},equals:(a,i)=>{let d=a,u=i;if(d.length!==u.length)return!1;for(let c=0;c<d.length;c++)if(d[c]!==u[c])return!1;return!0}})}function Ks(t){let e=t.thresholds??{};return n=>{let r=t.scoreFn(n);for(let o of Object.keys(e)){let s=e[o];if(s===void 0)continue;let a=r[o];if((Number.isFinite(a)?a:Number.NEGATIVE_INFINITY)<s)return!1}return!0}}function Rd(t){let e={persistence:t.persistenceThreshold??.3,personalValue:t.personalValueThreshold??.3},n=Ks({scoreFn:t.scoreFn,thresholds:e});return t.requireStructured?r=>{if(!n(r))return!1;let o=t.scoreFn(r).structure;return Number.isFinite(o)&&o>0}:n}Me();ye();Q();Z();var Dn=Math.LN2/604800;function Bt(t,e,n,r=0){if(!Number.isFinite(t))return r;if(!Number.isFinite(e)||e<=0||!Number.isFinite(n)||n<=0)return Math.max(r,t);let o=t*Math.exp(-n*e);return Math.max(r,o)}ye();we();Q();He();Z();Ke();var Sd=1e9;function Pe(t,e){return ue("memory",t,e)}function Vt(t,e){return t instanceof me?t:F(t,e?{name:e}:void 0)}function zs(t,e){return(t-e)/Sd}function Zr(t,e){let n=Math.max(t.length,e.length),r=0,o=0,s=0;for(let i=0;i<n;i+=1){let d=t[i]??0,u=e[i]??0;r+=d*u,o+=d*d,s+=u*u}if(o===0||s===0)return 0;let a=r/Math.sqrt(o*s);return Number.isFinite(a)?a:0}function Nd(t,e){if(t===e)return!0;if(t==null||e==null||t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1){let r=t[n],o=e[n];if(r.id!==o.id||r.score!==o.score||r.meta!==o.meta)return!1}return!0}function _d(t,e){if(t===e)return!0;if(t==null||e==null||t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1){let r=t[n],o=e[n];if(r.id!==o.id||r.score!==o.score||r.lastAccessNs!==o.lastAccessNs||r.value!==o.value)return!1}return!0}function Hs(t,e={}){let n=e.maxSize,r=e.ranked??!0,o=r?e.decayRate??0:0,s=e.minScore??0;if(n!==void 0&&n<1)throw new RangeError("collection: maxSize must be >= 1");let a=()=>r?1:0,i=e.score??a,d=r&&i instanceof me?i:void 0,u=()=>d?d.cache??a:i,c=new ie(t),p=Ge({name:"items",...n!==void 0?{retention:{score:(S,O)=>r?Bt(O.baseScore,zs(z(),O.lastAccessNs),o,s):O.lastAccessNs,maxSize:n}}:{}});c.add(p.entries,{name:"items"});let f;if(r&&o>0){let S=e.refreshIntervalMs??Math.max(1,1e3*Math.LN2/(10*o)),O=fn(S,{period:S});f=A([O],()=>z(),{name:"refresh_tick_ns",describeKind:"derived",initial:z(),meta:Pe("clock")}),c.add(f,{name:"refresh_tick_ns"})}let m;if(r){let S=[p.entries];f&&S.push(f),d&&S.push(d),m=A(S,O=>{let I=O[0],K;if(f){let H=O[1];K=typeof H=="number"?H:z()}else K=z();if(!I||I.size===0)return[];let q=[];for(let H of I.values())q.push({...H,score:Bt(H.baseScore,zs(K,H.lastAccessNs),o,s)});return q.sort((H,G)=>G.score-H.score||G.lastAccessNs-H.lastAccessNs),q},{name:"ranked",describeKind:"derived",equals:_d,meta:Pe("ranked")}),c.add(m,{name:"ranked"})}else m=F([],{name:"ranked",describeKind:"state",meta:Pe("ranked_disabled")}),c.add(m,{name:"ranked"});let h=A([p.entries],([S])=>(S??new Map).size,{name:"size",describeKind:"derived",initial:0,meta:Pe("size")});c.add(h,{name:"size"}),c.addDisposer(Y(h));let g=xt({name:"events",retainedLimit:1024,graph:c}),b=En(c,"seq",0),T=(S,O,I)=>{let K=z(),q=p.get(S),H=I?.score??u()(O);p.set(S,{id:S,value:O,baseScore:H,createdAtNs:q?.createdAtNs??K,lastAccessNs:K})},y=S=>{p.has(S)&&p.delete(S)},v=()=>{p.size!==0&&p.clear()},k=()=>{if(!r)return;let S=u(),O=p.entries.cache;if(!O||O.size===0)return;let I=[];for(let K of O.values())I.push([K.id,{...K,baseScore:S(K.value)}]);p.setMany(I)},N=ke(T,{audit:g,seq:b,onSuccess:([S],O,I)=>({action:"upsert",id:S,t_ns:I.t_ns,seq:I.seq})}),w=ke(y,{audit:g,seq:b,onSuccess:([S],O,I)=>({action:"remove",id:S,t_ns:I.t_ns,seq:I.seq})}),R=ke(v,{audit:g,seq:b,onSuccess:(S,O,I)=>({action:"clear",t_ns:I.t_ns,seq:I.seq})}),x=ke(k,{audit:g,seq:b,onSuccess:(S,O,I)=>({action:"rescore",t_ns:I.t_ns,seq:I.seq})});function _(S){let O=Vt(S,"id");return A([p.entries,O],([I,K])=>I?.get(K),{describeKind:"derived",meta:Pe("collection_item")})}function M(S){let O=Vt(S,"id");return A([p.entries,O],([I,K])=>I?.has(K)??!1,{describeKind:"derived",meta:Pe("collection_has")})}return Object.assign(c,{events:g,items:p.entries,ranked:m,size:h,upsert:N,remove:w,clear:R,rescore:x,itemNode:_,hasNode:M})}function Js(t={}){let e=t.backend??"flat",n=t.dimension,r=t.strictDimension??!0,o=t.maxSize,s=t.retentionScore,a;if(e==="hnsw"&&(a=t.hnswFactory?.(),!a))throw new Error('vectorIndex backend "hnsw" requires an optional dependency adapter; install your HNSW package and provide `hnswFactory`.');let i=new ie(t.name??"vector_index"),d;function u(x){if(n!==void 0){if(x.length!==n)throw new RangeError(`vector dimension mismatch: expected ${n}, got ${x.length}`);return}if(r){if(d===void 0){d=x.length;return}if(x.length!==d)throw new RangeError(`vector dimension mismatch: inferred ${d} from first upsert, got ${x.length}. Pass \`strictDimension: false\` to opt into zero-pad behavior, or set an explicit \`dimension\`.`)}}let c=s??(x=>x.upsertedAtNs),l=!1,p=xt({name:"events",retainedLimit:1024,graph:i}),f=En(i,"seq",0),m=Ge({name:"entries",...o!==void 0?{retention:{score:(x,_)=>c(_),maxSize:o,onArchive:x=>{l||(e==="hnsw"&&a.remove(x),p.append({action:"evict",id:x,t_ns:ce(),seq:$t(f)}))}}}:{}});if(i.add(m.entries,{name:"entries"}),i.addDisposer(Y(m.entries)),a?.dispose){let x=a.dispose.bind(a);i.addDisposer(()=>x())}let h=(x,_,M)=>{u(_),e==="hnsw"&&a.upsert(x,_,M);let L=(()=>{if(M!==void 0)return M===null||typeof M!="object"?M:Array.isArray(M)?[...M]:{...M}})(),S={id:x,vector:[..._],...L!==void 0?{meta:L}:{},upsertedAtNs:z()};m.set(x,S)},g=x=>{m.has(x)&&(e==="hnsw"&&a.remove(x),m.delete(x))},b=()=>{if(m.size!==0){l=!0;try{m.clear(),e==="hnsw"&&a.clear()}finally{l=!1}d=void 0}},T=()=>{if(e!=="hnsw")return;let x=m.entries.cache;if(x){a.clear();for(let _ of x.values())a.upsert(_.id,_.vector,_.meta)}},y=ke(h,{audit:p,freeze:!1,seq:f,onSuccess:([x],_,M)=>({action:"upsert",id:x,t_ns:M.t_ns,seq:M.seq})}),v=ke(g,{audit:p,seq:f,onSuccess:([x],_,M)=>({action:"remove",id:x,t_ns:M.t_ns,seq:M.seq})}),k=ke(b,{audit:p,seq:f,onSuccess:(x,_,M)=>({action:"clear",t_ns:M.t_ns,seq:M.seq})}),N=ke(T,{audit:p,seq:f,onSuccess:(x,_,M)=>({action:"reindex",t_ns:M.t_ns,seq:M.seq})});function w(x,_=5){let M=Vt(_,"k");return A([m.entries,x,M],L=>{let S=L[0],O=L[1],I=L[2],K=Number.isFinite(I)?Math.max(0,Math.floor(I)):0;if(!S||S.size===0||K<=0)return[];if(O==null||O.length===0)return[];let q=n??(r?d:void 0);return q!==void 0&&O.length!==q?[]:e==="hnsw"?[...a.search(O,K)]:[...S.values()].map(G=>({id:G.id,score:Zr(O,G.vector),...G.meta!==void 0?{meta:G.meta}:{}})).sort((G,j)=>j.score-G.score).slice(0,K)},{describeKind:"derived",equals:(L,S)=>Nd(L,S),meta:Pe("vector_search")})}return Object.assign(i,{backend:e,events:p,entries:m.entries,upsert:y,remove:v,clear:k,reindex:N,searchNode:w})}var Us="\0";function In(t,e,n){return`${t}${Us}${e}${Us}${n}`}function qs(t,e){if(!t||t.size===0)return new Map;let n=new Map;for(let o of t.values()){let s=e==="from"?o.from:o.to,a=n.get(s);a||(a=[],n.set(s,a)),a.push(o)}let r=new Map;for(let[o,s]of n)r.set(o,Object.freeze(s));return r}function Ws(t,e){if(t===e)return!0;if(t==null||e==null||t.size!==e.size)return!1;for(let[n,r]of t){let o=e.get(n);if(!o||r.length!==o.length)return!1;for(let s=0;s<r.length;s+=1){let a=r[s],i=o[s];if(a.from!==i.from||a.to!==i.to||a.relation!==i.relation||a.weight!==i.weight)return!1}}return!0}function Ys(t,e={}){let n=e.orphanGC??"keep";if(e.entitiesMaxSize!==void 0&&e.entitiesMaxSize<1)throw new RangeError("knowledgeGraph: entitiesMaxSize must be >= 1");if(e.edgesMaxSize!==void 0&&e.edgesMaxSize<1)throw new RangeError("knowledgeGraph: edgesMaxSize must be >= 1");let r=new ie(t),o=Ge({name:"entities",...e.entitiesMaxSize!==void 0?{maxSize:e.entitiesMaxSize}:{}}),s=Ge({name:"edges",...e.edgesMaxSize!==void 0?{maxSize:e.edgesMaxSize}:{}});r.add(o.entries,{name:"entities"}),r.add(s.entries,{name:"edges"});let a=A([s.entries],([R])=>qs(R,"from"),{name:"adjacencyOut",describeKind:"derived",initial:new Map,equals:Ws,meta:Pe("adjacency_out")}),i=A([s.entries],([R])=>qs(R,"to"),{name:"adjacencyIn",describeKind:"derived",initial:new Map,equals:Ws,meta:Pe("adjacency_in")});r.add(a,{name:"adjacencyOut"}),r.add(i,{name:"adjacencyIn"}),r.addDisposer(Y(a)),r.addDisposer(Y(i));let d=A([o.entries],([R])=>(R??new Map).size,{name:"entityCount",describeKind:"derived",initial:0,meta:Pe("entity_count")}),u=A([s.entries],([R])=>(R??new Map).size,{name:"edgeCount",describeKind:"derived",initial:0,meta:Pe("edge_count")});r.add(d,{name:"entityCount"}),r.add(u,{name:"edgeCount"}),r.addDisposer(Y(d)),r.addDisposer(Y(u));let c=xt({name:"events",retainedLimit:1024,graph:r}),l=En(r,"seq",0);function p(R){let x=a.cache,_=i.cache;return(x?.get(R)?.length??0)>0||(_?.get(R)?.length??0)>0}function f(R){if(n==="remove")for(let x of R)o.has(x)&&(p(x)||(o.delete(x),c.append({action:"orphanRemove",id:x,t_ns:ce(),seq:$t(l)})))}let m=(R,x)=>{o.set(R,x)},h=R=>{let x=s.entries.cache,_=new Set;if(x){let M=[];for(let[L,S]of x)(S.from===R||S.to===R)&&(M.push(L),S.from!==R&&_.add(S.from),S.to!==R&&_.add(S.to));M.length>0&&s.deleteMany(M)}o.has(R)&&o.delete(R),f([..._])},g=(R,x,_,M=1)=>{s.set(In(R,x,_),{from:R,to:x,relation:_,weight:M})},b=(R,x,_)=>{if(_!==void 0)s.delete(In(R,x,_));else{let M=s.entries.cache;if(!M)return;let L=[];for(let[S,O]of M)O.from===R&&O.to===x&&L.push(S);L.length>0&&s.deleteMany(L)}f([R,x])},T=ke(m,{audit:c,seq:l,onSuccess:([R],x,_)=>({action:"upsertEntity",id:R,t_ns:_.t_ns,seq:_.seq})}),y=ke(h,{audit:c,seq:l,onSuccess:([R],x,_)=>({action:"removeEntity",id:R,t_ns:_.t_ns,seq:_.seq})}),v=ke(g,{audit:c,seq:l,onSuccess:([R,x,_,M],L,S)=>({action:"link",from:R,to:x,relation:_,weight:M??1,t_ns:S.t_ns,seq:S.seq})}),k=ke(b,{audit:c,seq:l,onSuccess:([R,x,_],M,L)=>({action:"unlink",from:R,to:x,..._!==void 0?{relation:_}:{},t_ns:L.t_ns,seq:L.seq})});function N(R,x){let _=Vt(R,"id"),M=x!==void 0?Vt(x,"relation"):void 0;return A(M?[a,i,_,M]:[a,i,_],S=>{let O=S[0],I=S[1],K=S[2],q=M?S[3]:void 0,H=O.get(K)??[],G=I.get(K)??[],j=new Set,E=[];for(let C of H){let J=In(C.from,C.to,C.relation);j.has(J)||q!==void 0&&C.relation!==q||(j.add(J),E.push(C))}for(let C of G){let J=In(C.from,C.to,C.relation);j.has(J)||q!==void 0&&C.relation!==q||(j.add(J),E.push(C))}return E},{describeKind:"derived",equals:(S,O)=>{let I=S,K=O;if(I===K)return!0;if(I==null||K==null||I.length!==K.length)return!1;for(let q=0;q<I.length;q+=1){let H=I[q],G=K[q];if(H.from!==G.from||H.to!==G.to||H.relation!==G.relation||H.weight!==G.weight)return!1}return!0},meta:Pe("related")})}return Object.assign(r,{events:c,entities:o.entries,edges:s.entries,adjacencyOut:a,adjacencyIn:i,entityCount:d,edgeCount:u,upsertEntity:T,removeEntity:y,link:v,unlink:k,relatedNode:N})}function eo(t,e,n){let r=Js({dimension:n.dimension});t.add(r.entries,{name:"vectorIndex"});let s=Ne([e.store.entries],([a])=>{let i=a??new Map;for(let[d,u]of i){let c=n.embedFn(u);c&&r.upsert(d,c,u)}}).subscribe(()=>{});return t.addDisposer(s),{vectors:r,dispose:()=>s()}}function to(t,e,n,r){let o=r.mountPath??n,s=Ys(`${n}-kg`);if(t.mount(o,s),!r.entityFn)return{kg:s,dispose:()=>{}};let a=r.entityFn,d=Ne([e.store.entries],([u])=>{let c=u??new Map;for(let[l,p]of c){let f=a(l,p);if(f){for(let m of f.entities??[])s.upsertEntity(m.id,m.value);for(let m of f.relations??[])s.link(m.from,m.to,m.relation,m.weight)}}}).subscribe(()=>{});return t.addDisposer(d),{kg:s,dispose:()=>d()}}function no(t,e,n){let r=n.decayRate??Dn,o=n.maxActive??1e3,s=n.archiveThreshold??.1,a=n.permanentFilter??(()=>!1),i=Hs("permanent",{ranked:!1});t.mount("permanent",i);let d=new Set,u=T=>d.has(T)?"permanent":(e.store.entries.cache??new Map).has(T)?"active":"archived",c=(T,y)=>{d.add(T),i.upsert(T,y)},l=new Map,p=e.store.entries,f=n.context?V(n.context):F(null),h=Ne([p,f],([T,y])=>{let v=T??new Map,k=z(),N=[],w=[];for(let[x,_]of v){if(l.has(x)||l.set(x,k),a(x,_)){w.push({key:x,value:_});continue}let M=n.score(_,y),L=l.get(x)??k,S=Number(k-L)/1e9;Bt(M,S,r)<s&&N.push(x)}for(let x of l.keys())v.has(x)||l.delete(x);for(let{key:x,value:_}of w)d.has(x)||c(x,_);let R=v.size-d.size;if(R>o){let x=[...v.entries()].filter(([M])=>!d.has(M)).map(([M,L])=>({key:M,score:n.score(L,y)})).sort((M,L)=>M.score-L.score),_=R-o;for(let M=0;M<_&&M<x.length;M++){let L=x[M].key;N.includes(L)||N.push(L)}}N.length>0&&re(()=>{for(let x of N)e.store.delete(x)})}).subscribe(()=>{}),g=null;n.archiveTier&&(g=t.attachSnapshotStorage([n.archiveTier],n.archiveStorageOptions??{}));let b=()=>{h(),g?.dispose()};return t.addDisposer(b),{tiers:{permanent:i,activeEntries:p,archiveHandle:g,tierOf:u,markPermanent:c},dispose:b}}function Md(t,e){if(!t||!e)return 0;let n=Math.min(t.length,e.length),r=0;for(;r<n&&t[r]===e[r];)r++;return r}function ro(t,e,n,r,o){let s=o.topK??20,a=o.graphDepth??1,i=o.budget??2e3,d=o.contextWeight??0,u=o.context?V(o.context):F(null),c=(g,b,T)=>{let y=new Map,v=[];if(n&&T.vector){let _=T.vector,M=n.entries.cache;if(M&&M.size>0&&s>0){v=[...M.values()].map(S=>({id:S.id,score:Zr(_,S.vector),...S.meta!==void 0?{meta:S.meta}:{}})).sort((S,O)=>O.score-S.score).slice(0,s);for(let S of v){let O=g.get(S.id);O&&y.set(S.id,{value:O,sources:new Set(["vector"])})}}}let k=[];if(r){let _=r.adjacencyOut.cache,M=r.adjacencyIn.cache,L=[...T.entityIds??[],...y.keys()],S=new Set,O=L;for(let I=0;I<a;I++){let K=[];for(let q of O){if(S.has(q))continue;S.add(q);let H=_?.get(q)??[],G=M?.get(q)??[];for(let j of H){let E=j.to;if(!S.has(E)){K.push(E);let C=g.get(E);if(C){let J=y.get(E);J?J.sources.add("graph"):y.set(E,{value:C,sources:new Set(["graph"])}),k.push(E)}}}for(let j of G){let E=j.from;if(!S.has(E)){K.push(E);let C=g.get(E);if(C){let J=y.get(E);J?J.sources.add("graph"):y.set(E,{value:C,sources:new Set(["graph"])}),k.push(E)}}}}O=K}}for(let[_,M]of g)y.has(_)||y.set(_,{value:M,sources:new Set(["store"])});let N=T.context?.length??0,w=[];for(let[_,{value:M,sources:L}]of y){let S=o.contextOf?o.contextOf(M):void 0,O=o.score(M,b);if(d>0&&N>0){let K=Md(T.context,S);K>0&&(O=O*(1+d*K/N))}let I=S?{key:_,value:M,score:O,sources:[...L],context:S}:{key:_,value:M,score:O,sources:[...L]};w.push(I)}w.sort((_,M)=>M.score-_.score);let R=[],x=0;for(let _ of w){let M=o.cost(_.value);if(x+M>i&&R.length>0)break;R.push(_),x+=M}return{packed:R,trace:{vectorCandidates:v,graphExpanded:k,ranked:w,packed:R}}},l=(g,b)=>{if(g===b)return!0;if(g.length!==b.length)return!1;for(let T=0;T<g.length;T++)if(g[T]!==b[T])return!1;return!0},p=F([],{name:"retrieval",describeKind:"state",meta:W("retrieval_pipeline"),equals:l});t.add(p,{name:"retrieval"});let f=F(null,{name:"retrievalTrace",describeKind:"state",meta:W("retrieval_trace")});return t.add(f,{name:"retrievalTrace"}),{retrieval:p,retrievalTrace:f,retrieve:g=>{let b=e.store.entries.cache??new Map,{packed:T,trace:y}=c(b,u.cache,g);return re(()=>{p.emit(T),f.emit(y)}),T},retrieveReactive:g=>{let b=V(g),T=A([e.store.entries,u,b],([k,N,w])=>{if(w==null)return{packed:[],trace:null};let R=k??new Map,{packed:x,trace:_}=c(R,N,w);return{packed:x,trace:_}},{name:"retrievalReactive::result",describeKind:"derived",meta:W("retrieval_reactive_result"),initial:{packed:[],trace:null}}),v=Ne([T],([k])=>{let N=k;re(()=>{p.emit(N.packed),N.trace&&f.emit(N.trace)})}).subscribe(()=>{});return t.addDisposer(v),A([T],([k])=>k.packed,{name:"retrievalReactive",describeKind:"derived",meta:W("retrieval_reactive"),initial:[],equals:l})}}}Me();de();Oe();we();Q();Ie();Z();Ke();var Pn=class extends ie{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;_terminalResult;_disposeRunWiring;_running=!1;_currentAbortController=null;constructor(e,n){if(super(e,n.graph),this.chat=Yr(`${e}-chat`,{maxMessages:n.maxMessages}),this.mount("chat",this.chat),this.tools=Xr(`${e}-tools`),this.mount("tools",this.tools),n.tools)for(let E of n.tools)this.tools.register(E);this.status=F("idle",{name:"status",describeKind:"state",meta:W("agent_status")}),this.add(this.status,{name:"status"}),this.turn=F(0,{name:"turn",describeKind:"state",meta:W("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.aborted=F(!1,{name:"aborted",describeKind:"state",meta:W("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let r=0,o=this.turn.subscribe(E=>{for(let C of E)C[0]===D&&(r=C[1])}),s=!1,a=this.aborted.subscribe(E=>{for(let C of E)C[0]===D&&(s=C[1])}),i=this.chat.messages.cache??[],d=this.chat.messages.subscribe(E=>{for(let C of E)C[0]===D&&(i=C[1])}),u=this.tools.schemas.cache??[],c=this.tools.schemas.subscribe(E=>{for(let C of E)C[0]===D&&(u=C[1])}),l=n.adapter,p=n.systemPrompt,f=n.model,m=n.temperature,h=n.maxTokens,g=n.maxTurns??10,b=n.stopWhen,T=this.chat,y=this.tools,v=this.status,k=this.turn,N=this.aborted,w=te([v],(E,C,J)=>{if(Kt(E,J.prevData,0,"idle")!=="thinking"||s||r>=g){C.down([[U]]);return}if(i.length===0){C.down([[U]]);return}C.emit({messages:i,tools:u})},{name:"promptInput",describeKind:"derived",meta:W("agent_prompt_input",{closureReads:["aborted","turn","chat.messages","tools.schemas"]})}),R=ae(w,E=>{let C=new AbortController;return this._currentAbortController=C,s&&C.abort(new Error("agentLoop: aborted")),V(l.invoke(E.messages,{tools:E.tools.length>0?E.tools:void 0,systemPrompt:p,model:f,temperature:m,maxTokens:h,signal:C.signal}),{signal:C.signal})},{equals:()=>!1}),x=F(null,{name:"lastResponse",describeKind:"state",meta:W("agent_last_response")});this.lastResponse=x;let _=te([x,v],(E,C,J)=>{let he=Kt(E,J.prevData,0,null);if(Kt(E,J.prevData,1,"idle")!=="acting"){C.down([[U]]);return}let ee=he?.toolCalls;if(ee==null||ee.length===0){C.down([[U]]);return}C.emit(ee)},{name:"toolCallsRaw",describeKind:"derived",meta:W("agent_tool_calls_raw")}),M=n.interceptToolCalls?n.interceptToolCalls(_):_;this.toolCalls=M;let L=Qr({toolCalls:M,tools:y,retryCount:1});this.toolResults=L;let S=Ne([R],([E])=>{if(s)return;let C=E,J=r+1,he=C.toolCalls!=null&&C.toolCalls.length>0,B=C.finishReason==="end_turn"&&(!C.toolCalls||C.toolCalls.length===0),ee=b?.(C)===!0,xe=J>=g,Xe=ee||B||!he||xe?"done":"acting";re(()=>{x.emit(C),v.emit(Xe),k.emit(J),T.append("assistant",C.content,{toolCalls:C.toolCalls})})}),O=Ne([L],([E])=>{if(s)return;let C=E;if(C.length===0)return;let J=r>=g?"done":"thinking";re(()=>{v.emit(J);for(let he of C)T.appendToolResult(he.id,he.content)})}),I=v.cache??"idle",K=v.subscribe(E=>{for(let C of E)C[0]===D&&(I=C[1])}),q=Ne([N],([E])=>{E===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),I!=="done"&&v.emit("done"))}),H=Y(S),G=Y(O),j=Y(q);this._terminalResult=te([v,x],(E,C,J)=>{let he=Kt(E,J.prevData,0,"idle"),B=Kt(E,J.prevData,1,null);if(he==="done"){if(B!=null){C.emit(B);return}let ee=new Error("agentLoop: aborted");ee.name="AbortError",C.down([[P,ee]]);return}if(he==="error"){C.down([[P,new Error("agentLoop: errored")]]);return}C.down([[U]])},{name:"terminalResult",describeKind:"derived",meta:W("agent_terminal_result")}),this.add(w,{name:"promptInput"}),this.add(R,{name:"llmResponse"}),this.add(this.lastResponse,{name:"lastResponse"}),this.toolCalls===_?this.add(this.toolCalls,{name:"toolCalls"}):(this.add(_,{name:"toolCallsRaw"}),this.add(this.toolCalls,{name:"toolCalls"})),this.add(L,{name:"toolResults"}),this.add(this._terminalResult,{name:"terminalResult"}),this.addDisposer(o),this.addDisposer(a),this.addDisposer(K),this.addDisposer(d),this.addDisposer(c),this.addDisposer(H),this.addDisposer(G),this.addDisposer(j),this._disposeRunWiring=()=>{}}async run(e,n){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 r;try{re(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle"),this.lastResponse.emit(null)}),e!=null&&this.chat.append("user",e);let o=is(this._terminalResult,{skipCurrent:!0});if(n!=null)if(n.aborted)this.aborted.emit(!0);else{let s=()=>this.aborted.emit(!0);n.addEventListener("abort",s,{once:!0}),r=()=>n.removeEventListener("abort",s)}return n?.aborted!==!0&&this.status.emit("thinking"),await o}finally{r?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function Kt(t,e,n,r){let o=t[n];if(o!=null&&o.length>0)return o[o.length-1];let s=e[n];return s!==void 0?s:r}function Od(t,e){let n=new Pn(t,e);return n.tagFactory("agentLoop",We(e)),n}de();Oe();Q();Me();de();Oe();Q();Ie();Z();function Ed(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function Qs(t){t.subscribe(()=>{})}function zt(t){return t instanceof Map?t:new Map}function Xs(t,e){if(!Array.isArray(e.upsert))throw new TypeError("distill extraction requires upsert: Array<{ key, value }>");re(()=>{for(let{key:n,value:r}of e.upsert)t.set(n,r);for(let n of e.remove??[])t.delete(n)})}function Zs(t,e,n){let r=V(t),o=Ge(n.mapOptions??{}),s=n.budget??2e3,i=n.context!==void 0&&n.context!==null?V(n.context):F(null),d=zt(o.entries.cache);o.entries.subscribe(f=>{for(let m of f)m[0]===D&&(d=zt(m[1]))});let u=V(e(r,o.entries));if(Dt(u,f=>{Xs(o,f)}),n.evict){let f=new Map,m=A([o.entries],([h])=>{let g=[],b=zt(h);for(let T of f.keys())b.has(T)||(f.get(T)(),f.delete(T));for(let[T,y]of b){let v=n.evict(T,y);if(Ed(v)){if(!f.has(T)){let k=Dt(v,N=>{N===!0&&o.has(T)&&o.delete(T)});f.set(T,k)}continue}if(typeof v=="boolean"){v&&g.push(T);continue}throw new TypeError("distill evict() must return boolean or Node<boolean>")}return g});Dt(m,h=>{for(let g of h)o.delete(g)})}let c=n.consolidateTrigger!==void 0&&n.consolidateTrigger!==null;if(n.consolidate&&c){let f=V(n.consolidateTrigger),m=ae(f,()=>n.consolidate(d));Dt(m,h=>{Xs(o,h)})}let l=A([o.entries,i],([f,m])=>{let g=[...zt(f).entries()].map(([y,v])=>({key:y,value:v,score:n.score(v,m),cost:n.cost(v)}));g.sort((y,v)=>v.score-y.score);let b=[],T=s;for(let y of g)y.cost<=T&&(b.push({key:y.key,value:y.value,score:y.score}),T-=y.cost);return b},{meta:{...le("distill",{budget:s})}}),p=A([o.entries],([f])=>zt(f).size);return Qs(l),Qs(p),{store:o,compact:l,size:p}}Ie();Z();Ke();function Ad(t,e,n){let r=new ie(t,n.graph);r.tagFactory("agentMemory",We(n));let o;if(n.extractFn)o=n.extractFn;else if(n.adapter&&n.extractPrompt)o=zr(n.extractPrompt,{adapter:n.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let s=(T,y)=>{let v=y.cache??new Map,k=y.subscribe(N=>{for(let w of N)w[0]===D&&(v=w[1])});return r.addDisposer(k),ae(T,N=>N==null?{upsert:[]}:o(N,v))},a=e;if(n.admissionFilter){let T=V(e),y=n.admissionFilter;a=A([T],([v])=>{if(y(v))return v},{name:"admissionFilter",describeKind:"derived"})}let i;n.consolidateFn?i=n.consolidateFn:n.adapter&&n.consolidatePrompt&&(i=Ur(n.consolidatePrompt,{adapter:n.adapter}));let d=n.consolidateTrigger;if(!d&&i&&n.reflection?.enabled!==!1){let T=n.reflection?.interval??3e5;d=fn(T,{period:T})}let u={score:n.score,cost:n.cost,budget:n.budget??2e3,context:n.context,consolidate:i,consolidateTrigger:d},c=Zs(a,s,u);r.add(c.store.entries,{name:"store"}),r.add(c.compact,{name:"compact"}),r.add(c.size,{name:"size"});let l=null;n.vectorDimensions&&n.vectorDimensions>0&&n.embedFn&&(l=eo(r,c,{dimension:n.vectorDimensions,embedFn:n.embedFn}).vectors);let p=null;n.enableKnowledgeGraph&&(p=to(r,c,t,{mountPath:"kg",entityFn:n.entityFn}).kg);let f=null;n.tiers&&(f=no(r,c,{...n.tiers,score:n.score,context:n.context}).tiers);let m=null,h=null,g=null,b=null;if(l||p){let T=ro(r,c,l,p,{score:n.score,cost:n.cost,budget:n.budget,topK:n.retrieval?.topK,graphDepth:n.retrieval?.graphDepth,contextOf:n.contextOf,contextWeight:n.contextWeight,context:n.context});m=T.retrieval,h=T.retrievalTrace,g=T.retrieve,b=T.retrieveReactive}return Object.assign(r,{distillBundle:c,compact:c.compact,size:c.size,vectors:l,kg:p,memoryTiers:f,retrieval:m,retrievalTrace:h,retrieve:g,retrieveReactive:b})}function Cd(t,e,n){let r=t.describe({actor:e,detail:"full"}),o=n?.groupByTags??!0,s=n?.separator??`
12
- `,a=[],i=n?.sinceVersion;for(let[d,u]of Object.entries(r.nodes)){let c=u.meta??{},l=c.description,p=c.format;if(!l&&!p)continue;if(i!=null&&u.v!=null){let b=i.get(d);if(b!=null&&b.id===u.v.id&&u.v.version<=b.version)continue}let f=l??d,m=u.value,h=c.unit,g;p==="currency"&&typeof m=="number"?g=`$${m.toFixed(2)}`:p==="percentage"&&typeof m=="number"?g=`${(m*100).toFixed(1)}%`:m==null?g="(no value)":g=String(m),h&&p!=="currency"&&p!=="percentage"&&(g=`${g} ${h}`),a.push({path:d,description:f,formatted:g})}if(a.length===0)return"";if(o){let d=new Map,u=[];for(let l of a){let f=r.nodes[l.path].meta?.tags;if(f&&f.length>0){let m=f[0],h=d.get(m);h||(h=[],d.set(m,h)),h.push(l)}else u.push(l)}if(d.size===0)return a.map(l=>`- ${l.description}: ${l.formatted}`).join(s);let c=[];for(let[l,p]of[...d.entries()].sort((f,m)=>f[0].localeCompare(m[0])))c.push(`[${l}]${s}${p.map(f=>`- ${f.description}: ${f.formatted}`).join(s)}`);return u.length>0&&c.push(u.map(l=>`- ${l.description}: ${l.formatted}`).join(s)),c.join(s+s)}return a.map(d=>`- ${d.description}: ${d.formatted}`).join(s)}de();Q();Ie();Z();Q();Ke();Me();de();we();Q();He();Z();function ei(t,e){return ue("reduction",t,e)}function ti(t,e,n,r){let o=r?.maxIterations??10,s=`__feedback_${e}`,a=F(0,{meta:ei("feedback_counter",{maxIterations:o,feedbackFrom:e,feedbackTo:n})});t.add(a,{name:s});let i=t.resolve(e),d=t.resolve(n),u=`__feedback_effect_${e}`,c=te([],(l,p)=>{let f=i.subscribe(m=>{for(let h of m){let g=h[0];if(g===D){let b=h[1];if(b==null)return;re(()=>{Fs(a,o)&&d.emit(b)})}else if(g===$||g===P){let b=g===P&&h.length>1?[P,h[1]]:[g];a.down([b])}}});return()=>f()},{name:u,describeKind:"effect",meta:{...ei("feedback_effect",{feedbackFrom:e,feedbackTo:n}),_internal:!0}});return t.add(c,{name:u}),t.addDisposer(Y(c)),t}function St(t){let e=t.meta?.factory;return typeof e=="string"?e:void 0}function Nt(t){let e=t.meta?.factoryArgs;return e!=null&&typeof e=="object"?e:{}}function ni(t){let e=Nt(t);return"initial"in e?e.initial:t.value}function oi(t){return typeof t=="object"&&t!==null&&"factory"in t}function si(t){return typeof t=="object"&&t!==null&&"factory"in t}function Ld(t){return oi(t)?t.factory:t}function Dd(t){return si(t)?t.factory:t}function Id(t,e){let n=[],r=new Set(Object.keys(e.fns??{})),o=new Set(Object.keys(e.sources??{}));for(let[s,a]of Object.entries(t.nodes)){if(a.type==="template")continue;let i=a,d=St(i);if(d==null)continue;let u=i.type==="producer";if(i.type==="state"&&d==="state")continue;if(u){let l=o.has(d),p=r.has(d);if(!l&&!p&&(o.size>0||r.size>0)){let f=Gn(d,o)??Gn(d,r);n.push(`Node "${s}": source "${d}" not found in catalog`+(f?`. Did you mean "${f}"?`:""))}}else if(r.size>0&&!r.has(d))if(o.has(d))n.push(`Node "${s}": fn "${d}" is a source, not a function. Use it as a producer source instead, or use a function from: ${[...r].join(", ")}`);else{let l=Gn(d,r);n.push(`Node "${s}": fn "${d}" not found in catalog`+(l?`. Did you mean "${l}"?`:""))}let c=Nt(i);if(!u&&e.fns?.[d]){let l=e.fns[d];if(oi(l)&&l.configSchema){for(let[p,f]of Object.entries(l.configSchema))if(f.required!==!1&&!(p in c)&&n.push(`Node "${s}": config missing required field "${p}"`),p in c&&f.enum){let m=c[p];f.enum.includes(m)||n.push(`Node "${s}": config.${p} = ${JSON.stringify(m)}, expected one of: ${f.enum.join(", ")}`)}}}if(u&&e.sources?.[d]){let l=e.sources[d];if(si(l)&&l.configSchema){for(let[p,f]of Object.entries(l.configSchema))if(f.required!==!1&&!(p in c)&&n.push(`Node "${s}": config missing required field "${p}"`),p in c&&f.enum){let m=c[p];f.enum.includes(m)||n.push(`Node "${s}": config.${p} = ${JSON.stringify(m)}, expected one of: ${f.enum.join(", ")}`)}}}}if(t.templates)for(let[s,a]of Object.entries(t.templates))for(let[i,d]of Object.entries(a.nodes)){let u=St(d);if(u!=null&&!(d.type==="state"&&u==="state")&&d.type!=="producer"&&r.size>0&&!r.has(u)){let c=Gn(u,r);n.push(`Template "${s}" node "${i}": fn "${u}" not found in catalog`+(c?`. Did you mean "${c}"?`:""))}}return{valid:n.length===0,errors:n,warnings:[]}}function Gn(t,e){let n=null,r=1/0,o=t.toLowerCase();for(let s of e){let a=Pd(o,s.toLowerCase());a<r&&a<=Math.max(3,Math.floor(t.length/2))&&(r=a,n=s)}return n}function Pd(t,e){let n=t.length,r=e.length,o=Array.from({length:n+1},(s,a)=>Array.from({length:r+1},(i,d)=>a===0?d:d===0?a:0));for(let s=1;s<=n;s++)for(let a=1;a<=r;a++)o[s][a]=t[s-1]===e[a-1]?o[s-1][a-1]:1+Math.min(o[s-1][a],o[s][a-1],o[s-1][a-1]);return o[n][r]}var ri=new Set(["state","producer","derived","effect","operator","template"]),Gd=new Set(["state","producer","derived","effect","operator"]);function Fd(t){let e=[],n=[];if(t==null||typeof t!="object")return{valid:!1,errors:["GraphSpec must be a non-null object"],warnings:n};let r=t;if((typeof r.name!="string"||r.name.length===0)&&e.push("Missing or empty 'name' field"),r.nodes==null||typeof r.nodes!="object"||Array.isArray(r.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e,warnings:n};let o=new Set(Object.keys(r.nodes)),s=new Map,a=new Map;if(r.templates!=null&&typeof r.templates=="object"&&!Array.isArray(r.templates)){for(let[i,d]of Object.entries(r.templates))if(d!=null&&typeof d=="object"){let u=d;a.set(i,{params:Array.isArray(u.params)?u.params:[]})}}if(r.templates!=null)if(typeof r.templates!="object"||Array.isArray(r.templates))e.push("'templates' must be an object");else for(let[i,d]of Object.entries(r.templates)){if(d==null||typeof d!="object"){e.push(`Template "${i}": must be an object`);continue}let u=d;if(Array.isArray(u.params)||e.push(`Template "${i}": missing 'params' array`),u.nodes==null||typeof u.nodes!="object"||Array.isArray(u.nodes))e.push(`Template "${i}": missing or invalid 'nodes' object`);else{let c=new Set(Array.isArray(u.params)?u.params:[]),l=new Set(Object.keys(u.nodes));for(let[p,f]of Object.entries(u.nodes)){if(f==null||typeof f!="object"){e.push(`Template "${i}" node "${p}": must be an object`);continue}let m=f;if((typeof m.type!="string"||!Gd.has(m.type))&&e.push(`Template "${i}" node "${p}": invalid type`),Array.isArray(m.deps))for(let h of m.deps)!l.has(h)&&!c.has(h)&&e.push(`Template "${i}" node "${p}": dep "${h}" is not an inner node or param`)}typeof u.output!="string"?e.push(`Template "${i}": missing 'output' string`):u.nodes[u.output]||e.push(`Template "${i}": output "${u.output}" is not a declared node`)}}for(let[i,d]of Object.entries(r.nodes)){if(d==null||typeof d!="object"){e.push(`Node "${i}": must be an object`);continue}let u=d;if(typeof u.type!="string"||!ri.has(u.type)){e.push(`Node "${i}": invalid type "${String(u.type)}" (expected: ${[...ri].join(", ")})`);continue}if(s.set(i,u.type),u.type==="template")if(typeof u.template!="string"||!a.has(u.template))e.push(`Node "${i}": template "${String(u.template)}" not found in templates`);else if(u.bind==null||typeof u.bind!="object"||Array.isArray(u.bind))e.push(`Node "${i}": template ref requires 'bind' object`);else{let c=a.get(u.template),l=u.bind;for(let p of c.params)p in l||e.push(`Node "${i}": template param "${p}" is not bound (template "${u.template}")`);for(let[,p]of Object.entries(l))typeof p=="string"&&!o.has(p)&&e.push(`Node "${i}": bind target "${p}" does not reference an existing node`)}else{if(Array.isArray(u.deps))for(let c of u.deps)c===i?e.push(`Node "${i}": self-referencing dep`):o.has(c)||e.push(`Node "${i}": dep "${c}" does not reference an existing node`);(u.type==="derived"||u.type==="effect"||u.type==="operator")&&!Array.isArray(u.deps)&&e.push(`Node "${i}": ${u.type} node should have a 'deps' array`)}}if(r.feedback!=null)if(!Array.isArray(r.feedback))e.push("'feedback' must be an array");else for(let i=0;i<r.feedback.length;i++){let d=r.feedback[i];if(d==null||typeof d!="object"){e.push(`Feedback [${i}]: must be an object`);continue}let u=d;typeof u.from!="string"||!o.has(u.from)?e.push(`Feedback [${i}]: 'from' "${String(u.from)}" does not reference an existing node`):s.get(u.from)==="effect"&&n.push(`Feedback [${i}]: 'from' "${u.from}" is an effect node \u2014 effects emit no DATA, so the feedback edge will never fire. Did you mean a derived/state node upstream?`),typeof u.from=="string"&&u.from===u.to&&e.push(`Feedback [${i}]: 'from' and 'to' must be different nodes`),typeof u.to!="string"||!o.has(u.to)?e.push(`Feedback [${i}]: 'to' "${String(u.to)}" does not reference an existing node`):typeof u.to=="string"&&s.get(u.to)!=="state"&&e.push(`Feedback [${i}]: 'to' node "${u.to}" must be a state node (got "${s.get(u.to)??"unknown"}")`)}return{valid:e.length===0,errors:e,warnings:n}}function ii(t,e){let n=Fd(t);if(!n.valid)throw new Error(`compileSpec: invalid GraphSpec:
11
+ `,r=t.map(a=>typeof a=="string"?F(a):j(a)),o=C(r,a=>a.filter(i=>i!=null&&i!=="").join(n),{name:e?.name??"systemPrompt",describeKind:"derived",meta:W("system_prompt"),initial:""}),s=Y(o);return Object.assign(o,{dispose:s})}Q();var fd=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens&&t.estimated===e.estimated;function md(t,e){let n=e?.charsPerToken??4,r={chunkCount:0,charCount:0,estimatedTokens:0,estimated:!0};return C([t.latest],([o],s)=>{if(o==null)return r;let a=o;"chunkCount"in s.store||(s.store.chunkCount=0,s.store.charCount=0,s.store.usageTokens=0,s.store.sawUsage=!1);let i=s.store;a.type==="token"?(i.chunkCount+=1,i.charCount+=a.delta.length):a.type==="usage"&&(i.sawUsage=!0,i.usageTokens=$e(a.usage)+We(a.usage));let d=i.sawUsage?i.usageTokens:Math.ceil(i.charCount/n);return{chunkCount:i.chunkCount,charCount:i.charCount,estimatedTokens:d,estimated:!i.sawUsage}},{name:e?.name??"cost-meter",describeKind:"derived",initial:r,meta:W("cost_meter_extractor"),equals:fd})}Q();var gd=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.label!==o.label||r.pattern!==o.pattern||r.match!==o.match||r.position!==o.position)return!1}return!0};function hd(t,e){let n=e.maxPatternLength??128;for(let o of e.patterns)if(o.pattern.source.length>n)throw new Error(`keywordFlagExtractor: pattern "${o.label}" literal exceeds maxPatternLength (${o.pattern.source.length} > ${n}); raise the option or shorten the pattern.`);let r=e.patterns.map(o=>({label:o.label,pattern:o.pattern,compiled:new RegExp(o.pattern.source,`${o.pattern.flags.replace("g","")}g`)}));return C([t],([o],s)=>{if(o==null)return[];let a=o;"flags"in s.store||(s.store.flags=[],s.store.scannedTo=0);let i=s.store.flags,d=s.store.scannedTo,u=Math.max(0,d-n),c=a.slice(u),l=!1;for(let{pattern:p,label:f,compiled:m}of r){m.lastIndex=0;for(let h of c.matchAll(m)){let g=u+(h.index??0);g+h[0].length<=d||(i.push({label:f,pattern:p,match:h[0],position:g}),l=!0)}}return s.store.scannedTo=a.length,l?[...i]:i.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:W("keyword_flag_extractor"),equals:gd})}Q();function yd(t,e,n){return C([t],([r])=>r==null?null:e(r),{name:n?.name??"extractor",describeKind:"derived",initial:null,meta:W("stream_extractor"),...n?.equals?{equals:n.equals}:{}})}Q();var bd=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.startIndex!==o.startIndex||r.name!==o.name||r.raw!==o.raw)return!1}return!0};function Td(t,e){return C([t],([n],r)=>{if(n==null)return[];let o=n;"calls"in r.store||(r.store.calls=[],r.store.scanFrom=0);let s=r.store.calls,a=r.store.scanFrom,i=!1;for(;a<o.length;){let d=o.indexOf("{",a);if(d===-1){r.store.scanFrom=o.length;break}let u=0,c=-1,l=!1;for(let f=d;f<o.length;f++){let m=o[f];if(l)m==="\\"&&f+1<o.length?f++:m==='"'&&(l=!1);else if(m==='"')l=!0;else if(m==="{")u++;else if(m==="}"&&(u--,u===0)){c=f;break}}if(c===-1){r.store.scanFrom=d;break}let p=o.slice(d,c+1);try{let f=JSON.parse(p);typeof f.name=="string"&&f.arguments!=null&&typeof f.arguments=="object"&&(s.push({name:f.name,arguments:f.arguments,raw:p,startIndex:d}),i=!0)}catch{}a=c+1,r.store.scanFrom=a}return i?[...s]:s.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:W("tool_call_extractor"),equals:bd})}Q();function vd(t,e,n,r){let o=n*(r?.hardMultiplier??1.5),s=typeof e!="function",a=[t];return s&&a.push(e),C(a,i=>{let d=i[0]??"";if(d.length===0)return"allow";let u=s?i[1]??0:e(d);return u>=o?"block":u>=n?"review":"allow"},{name:r?.name??"content-gate",initial:"allow"})}Q();function wd(t,e,n,r){let o=n??(()=>"[REDACTED]");function s(a){let i=a;for(let d of e){let u=d.global?d:new RegExp(d.source,`${d.flags}g`);i=i.replace(u,c=>o(c,d))}return i}return C([t],([a])=>s(a??""),{name:r?.name??"redactor",initial:""})}Q();Z();Ue();var Pn=class extends ae{_log;messages;latest;messageCount;constructor(e,n={}){super(e,n.graph),this._log=Ve([],{name:"messages",maxSize:n.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=C([this.messages],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:W("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(Y(this.latest)),this.messageCount=C([this.messages],([r])=>r.length,{name:"messageCount",describeKind:"derived",meta:W("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(Y(this.messageCount))}append(e,n,r){this._log.append({role:e,content:n,...r})}appendToolResult(e,n){this._log.append({role:"tool",content:n,toolCallId:e})}clear(){this._log.clear()}allMessages(){return this.messages.cache}};function to(t,e){return new Pn(t,e)}Ee();Q();Pe();Z();function kd(t,e,n){let r=j(t),o=n?.condition!=null?j(n.condition):null,s=F(null,{name:n?.name?`${n.name}::null`:"handoff::null"});if(o==null)return de(r,i=>{if(i==null)return s;let d=F(i);return e(d)},{meta:pe("handoff")});let a=C([r,o],([i,d])=>({v:i,open:d===!0}),{name:n?.name?`${n.name}::router`:"handoff::router",describeKind:"derived"});return de(a,({v:i,open:d})=>{if(i==null)return s;if(!d)return F(i);let u=F(i);return e(u)},{meta:pe("handoff")})}Q();Pe();vt();function no(t){let{toolCalls:e,tools:n}=t,r=t.retryCount??1,o=t.onError??"rescue",s=(a,i)=>{if(a===i)return!0;if(a.length!==i.length)return!1;for(let d=0;d<a.length;d++){let u=a[d],c=i[d];if(u?.id!==c?.id||u?.content!==c?.content)return!1}return!0};return de(e,a=>{if(a==null||a.length===0)throw new Error("toolExecution: received an empty tool-call batch as DATA \u2014 callers must upstream-filter empty batches (emit RESOLVED) so switchMap is only dispatched for non-empty batches.");let i=a.map(d=>xd(d,n,r,o));return C(i,d=>d,{name:"toolExecution::batch",equals:s})})}function xd(t,e,n,r){let o=bt(()=>e.executeReactive(t.name,t.arguments),{count:n}),s=C([o],([a])=>({id:t.id,content:typeof a=="string"?a:JSON.stringify(a)}));return r==="propagate"?s:hs(s,a=>({id:t.id,content:JSON.stringify({error:String(a)})}))}ie();Q();Z();Ue();var Gn=class extends ae{definitions;schemas;_bundle;constructor(e,n={}){super(e,n.graph),this._bundle=_e({name:"definitions"}),this.definitions=this._bundle.entries,this.add(this.definitions,{name:"definitions"}),this.schemas=C([this.definitions],([r])=>[...(r??new Map).values()],{name:"schemas",describeKind:"derived",meta:W("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(Y(this.schemas))}register(e){this._bundle.set(e.name,e)}unregister(e){this._bundle.delete(e)}executeReactive(e,n){let r=this._bundle.get(e);if(!r)throw new Error(`toolRegistry: unknown tool "${e}"`);return se(o=>{let s=new AbortController,a;try{let d=r.handler(n,{signal:s.signal});a=Rd(d,s.signal)}catch(d){return o.down([[P,d]]),()=>{s.abort()}}let i=a.subscribe(d=>{o.down(d)});return()=>{s.abort(),i()}},{name:`executeReactive::${e}`,meta:W("tool_execute_reactive")})}getDefinition(e){return this._bundle.entries.cache?.get(e)}};function ro(t,e){return new Gn(t,e)}function Rd(t,e){return qr(t)?t:t!=null&&typeof t.then=="function"?bn(t,{signal:e}):t!=null&&typeof t=="object"&&Symbol.asyncIterator in t?kr(t,{signal:e}):bn(Promise.resolve(t),{signal:e})}Ee();Q();Z();function Nd(t,e,n){let r=j(t),o=e.map(a=>j(a)),s=[r,...o];return C(s,a=>{let i=a[0]??[],d=a.slice(1);return i.filter(u=>{for(let c of d)if(c!=null&&!c(u))return!1;return!0})},{name:n?.name??"tool-selector",describeKind:"derived",meta:{...W("tool_selector"),...pe("toolSelector")},equals:(a,i)=>{let d=a,u=i;if(d.length!==u.length)return!1;for(let c=0;c<d.length;c++)if(d[c]!==u[c])return!1;return!0}})}function Ws(t){let e=t.thresholds??{};return n=>{let r=t.scoreFn(n);for(let o of Object.keys(e)){let s=e[o];if(s===void 0)continue;let a=r[o];if((Number.isFinite(a)?a:Number.NEGATIVE_INFINITY)<s)return!1}return!0}}function Sd(t){let e={persistence:t.persistenceThreshold??.3,personalValue:t.personalValueThreshold??.3},n=Ws({scoreFn:t.scoreFn,thresholds:e});return t.requireStructured?r=>{if(!n(r))return!1;let o=t.scoreFn(r).structure;return Number.isFinite(o)&&o>0}:n}Oe();ye();ie();Q();Oe();ie();Ee();Q();Pe();Z();function _d(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function Hs(t){t.subscribe(()=>{})}function Kt(t){return t instanceof Map?t:new Map}function Js(t,e){if(!Array.isArray(e.upsert))throw new TypeError("distill extraction requires upsert: Array<{ key, value }>");te(()=>{for(let{key:n,value:r}of e.upsert)t.set(n,r);for(let n of e.remove??[])t.delete(n)})}function Fn(t,e,n){let r=j(t),o=_e(n.mapOptions??{}),s=n.budget??2e3,i=n.context!==void 0&&n.context!==null?j(n.context):F(null),d=Kt(o.entries.cache);o.entries.subscribe(f=>{for(let m of f)m[0]===D&&(d=Kt(m[1]))});let u=j(e(r,o.entries));if(Pt(u,f=>{Js(o,f)}),n.evict){let f=new Map,m=C([o.entries],([h])=>{let g=[],y=Kt(h);for(let v of f.keys())y.has(v)||(f.get(v)(),f.delete(v));for(let[v,b]of y){let w=n.evict(v,b);if(_d(w)){if(!f.has(v)){let k=Pt(w,S=>{S===!0&&o.has(v)&&o.delete(v)});f.set(v,k)}continue}if(typeof w=="boolean"){w&&g.push(v);continue}throw new TypeError("distill evict() must return boolean or Node<boolean>")}return g});Pt(m,h=>{for(let g of h)o.delete(g)})}let c=n.consolidateTrigger!==void 0&&n.consolidateTrigger!==null;if(n.consolidate&&c){let f=j(n.consolidateTrigger),m=de(f,()=>n.consolidate(d));Pt(m,h=>{Js(o,h)})}let l=C([o.entries,i],([f,m])=>{let g=[...Kt(f).entries()].map(([b,w])=>({key:b,value:w,score:n.score(w,m),cost:n.cost(w)}));g.sort((b,w)=>w.score-b.score);let y=[],v=s;for(let b of g)b.cost<=v&&(y.push({key:b.key,value:b.value,score:b.score}),v-=b.cost);return y},{meta:{...pe("distill",{budget:s})}}),p=C([o.entries],([f])=>Kt(f).size);return Hs(l),Hs(p),{store:o,compact:l,size:p}}Z();var $n=Math.LN2/604800;function zt(t,e,n,r=0){if(!Number.isFinite(t))return r;if(!Number.isFinite(e)||e<=0||!Number.isFinite(n)||n<=0)return Math.max(r,t);let o=t*Math.exp(-n*e);return Math.max(r,o)}ye();ke();Q();Ye();Z();Ue();var Md=1e9;function Ge(t,e){return ue("memory",t,e)}function Ut(t,e){return t instanceof me?t:F(t,e?{name:e}:void 0)}function Ys(t,e){return(t-e)/Md}function oo(t,e){let n=Math.max(t.length,e.length),r=0,o=0,s=0;for(let i=0;i<n;i+=1){let d=t[i]??0,u=e[i]??0;r+=d*u,o+=d*d,s+=u*u}if(o===0||s===0)return 0;let a=r/Math.sqrt(o*s);return Number.isFinite(a)?a:0}function Od(t,e){if(t===e)return!0;if(t==null||e==null||t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1){let r=t[n],o=e[n];if(r.id!==o.id||r.score!==o.score||r.meta!==o.meta)return!1}return!0}function Ed(t,e){if(t===e)return!0;if(t==null||e==null||t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1){let r=t[n],o=e[n];if(r.id!==o.id||r.score!==o.score||r.lastAccessNs!==o.lastAccessNs||r.value!==o.value)return!1}return!0}function ei(t,e={}){let n=e.maxSize,r=e.ranked??!0,o=r?e.decayRate??0:0,s=e.minScore??0;if(n!==void 0&&n<1)throw new RangeError("collection: maxSize must be >= 1");let a=()=>r?1:0,i=e.score??a,d=r&&i instanceof me?i:void 0,u=()=>d?d.cache??a:i,c=new ae(t),p=_e({name:"items",...n!==void 0?{retention:{score:(R,O)=>r?zt(O.baseScore,Ys(z(),O.lastAccessNs),o,s):O.lastAccessNs,maxSize:n}}:{}});c.add(p.entries,{name:"items"});let f;if(r&&o>0){let R=e.refreshIntervalMs??Math.max(1,1e3*Math.LN2/(10*o)),O=yn(R,{period:R});f=C([O],()=>z(),{name:"refresh_tick_ns",describeKind:"derived",initial:z(),meta:Ge("clock")}),c.add(f,{name:"refresh_tick_ns"})}let m;if(r){let R=[p.entries];f&&R.push(f),d&&R.push(d),m=C(R,O=>{let I=O[0],K;if(f){let H=O[1];K=typeof H=="number"?H:z()}else K=z();if(!I||I.size===0)return[];let q=[];for(let H of I.values())q.push({...H,score:zt(H.baseScore,Ys(K,H.lastAccessNs),o,s)});return q.sort((H,G)=>G.score-H.score||G.lastAccessNs-H.lastAccessNs),q},{name:"ranked",describeKind:"derived",equals:Ed,meta:Ge("ranked")}),c.add(m,{name:"ranked"})}else m=F([],{name:"ranked",describeKind:"state",meta:Ge("ranked_disabled")}),c.add(m,{name:"ranked"});let h=C([p.entries],([R])=>(R??new Map).size,{name:"size",describeKind:"derived",initial:0,meta:Ge("size")});c.add(h,{name:"size"}),c.addDisposer(Y(h));let g=Nt({name:"events",retainedLimit:1024,graph:c}),y=Dn(c,"seq",0),v=(R,O,I)=>{let K=z(),q=p.get(R),H=I?.score??u()(O);p.set(R,{id:R,value:O,baseScore:H,createdAtNs:q?.createdAtNs??K,lastAccessNs:K})},b=R=>{p.has(R)&&p.delete(R)},w=()=>{p.size!==0&&p.clear()},k=()=>{if(!r)return;let R=u(),O=p.entries.cache;if(!O||O.size===0)return;let I=[];for(let K of O.values())I.push([K.id,{...K,baseScore:R(K.value)}]);p.setMany(I)},S=xe(v,{audit:g,seq:y,onSuccess:([R],O,I)=>({action:"upsert",id:R,t_ns:I.t_ns,seq:I.seq})}),T=xe(b,{audit:g,seq:y,onSuccess:([R],O,I)=>({action:"remove",id:R,t_ns:I.t_ns,seq:I.seq})}),x=xe(w,{audit:g,seq:y,onSuccess:(R,O,I)=>({action:"clear",t_ns:I.t_ns,seq:I.seq})}),N=xe(k,{audit:g,seq:y,onSuccess:(R,O,I)=>({action:"rescore",t_ns:I.t_ns,seq:I.seq})});function _(R){let O=Ut(R,"id");return C([p.entries,O],([I,K])=>I?.get(K),{describeKind:"derived",meta:Ge("collection_item")})}function M(R){let O=Ut(R,"id");return C([p.entries,O],([I,K])=>I?.has(K)??!1,{describeKind:"derived",meta:Ge("collection_has")})}return Object.assign(c,{events:g,items:p.entries,ranked:m,size:h,upsert:S,remove:T,clear:x,rescore:N,itemNode:_,hasNode:M})}function ti(t={}){let e=t.backend??"flat",n=t.dimension,r=t.strictDimension??!0,o=t.maxSize,s=t.retentionScore,a;if(e==="hnsw"&&(a=t.hnswFactory?.(),!a))throw new Error('vectorIndex backend "hnsw" requires an optional dependency adapter; install your HNSW package and provide `hnswFactory`.');let i=new ae(t.name??"vector_index"),d;function u(N){if(n!==void 0){if(N.length!==n)throw new RangeError(`vector dimension mismatch: expected ${n}, got ${N.length}`);return}if(r){if(d===void 0){d=N.length;return}if(N.length!==d)throw new RangeError(`vector dimension mismatch: inferred ${d} from first upsert, got ${N.length}. Pass \`strictDimension: false\` to opt into zero-pad behavior, or set an explicit \`dimension\`.`)}}let c=s??(N=>N.upsertedAtNs),l=!1,p=Nt({name:"events",retainedLimit:1024,graph:i}),f=Dn(i,"seq",0),m=_e({name:"entries",...o!==void 0?{retention:{score:(N,_)=>c(_),maxSize:o,onArchive:N=>{l||(e==="hnsw"&&a.remove(N),p.append({action:"evict",id:N,t_ns:ce(),seq:Bt(f)}))}}}:{}});if(i.add(m.entries,{name:"entries"}),i.addDisposer(Y(m.entries)),a?.dispose){let N=a.dispose.bind(a);i.addDisposer(()=>N())}let h=(N,_,M)=>{u(_),e==="hnsw"&&a.upsert(N,_,M);let A=(()=>{if(M!==void 0)return M===null||typeof M!="object"?M:Array.isArray(M)?[...M]:{...M}})(),R={id:N,vector:[..._],...A!==void 0?{meta:A}:{},upsertedAtNs:z()};m.set(N,R)},g=N=>{m.has(N)&&(e==="hnsw"&&a.remove(N),m.delete(N))},y=()=>{if(m.size!==0){l=!0;try{m.clear(),e==="hnsw"&&a.clear()}finally{l=!1}d=void 0}},v=()=>{if(e!=="hnsw")return;let N=m.entries.cache;if(N){a.clear();for(let _ of N.values())a.upsert(_.id,_.vector,_.meta)}},b=xe(h,{audit:p,freeze:!1,seq:f,onSuccess:([N],_,M)=>({action:"upsert",id:N,t_ns:M.t_ns,seq:M.seq})}),w=xe(g,{audit:p,seq:f,onSuccess:([N],_,M)=>({action:"remove",id:N,t_ns:M.t_ns,seq:M.seq})}),k=xe(y,{audit:p,seq:f,onSuccess:(N,_,M)=>({action:"clear",t_ns:M.t_ns,seq:M.seq})}),S=xe(v,{audit:p,seq:f,onSuccess:(N,_,M)=>({action:"reindex",t_ns:M.t_ns,seq:M.seq})});function T(N,_=5){let M=Ut(_,"k");return C([m.entries,N,M],A=>{let R=A[0],O=A[1],I=A[2],K=Number.isFinite(I)?Math.max(0,Math.floor(I)):0;if(!R||R.size===0||K<=0)return[];if(O==null||O.length===0)return[];let q=n??(r?d:void 0);return q!==void 0&&O.length!==q?[]:e==="hnsw"?[...a.search(O,K)]:[...R.values()].map(G=>({id:G.id,score:oo(O,G.vector),...G.meta!==void 0?{meta:G.meta}:{}})).sort((G,B)=>B.score-G.score).slice(0,K)},{describeKind:"derived",equals:(A,R)=>Od(A,R),meta:Ge("vector_search")})}return Object.assign(i,{backend:e,events:p,entries:m.entries,upsert:b,remove:w,clear:k,reindex:S,searchNode:T})}var Qs="\0";function jn(t,e,n){return`${t}${Qs}${e}${Qs}${n}`}function Xs(t,e){if(!t||t.size===0)return new Map;let n=new Map;for(let o of t.values()){let s=e==="from"?o.from:o.to,a=n.get(s);a||(a=[],n.set(s,a)),a.push(o)}let r=new Map;for(let[o,s]of n)r.set(o,Object.freeze(s));return r}function Zs(t,e){if(t===e)return!0;if(t==null||e==null||t.size!==e.size)return!1;for(let[n,r]of t){let o=e.get(n);if(!o||r.length!==o.length)return!1;for(let s=0;s<r.length;s+=1){let a=r[s],i=o[s];if(a.from!==i.from||a.to!==i.to||a.relation!==i.relation||a.weight!==i.weight)return!1}}return!0}function ni(t,e={}){let n=e.orphanGC??"keep";if(e.entitiesMaxSize!==void 0&&e.entitiesMaxSize<1)throw new RangeError("knowledgeGraph: entitiesMaxSize must be >= 1");if(e.edgesMaxSize!==void 0&&e.edgesMaxSize<1)throw new RangeError("knowledgeGraph: edgesMaxSize must be >= 1");let r=new ae(t),o=_e({name:"entities",...e.entitiesMaxSize!==void 0?{maxSize:e.entitiesMaxSize}:{}}),s=_e({name:"edges",...e.edgesMaxSize!==void 0?{maxSize:e.edgesMaxSize}:{}});r.add(o.entries,{name:"entities"}),r.add(s.entries,{name:"edges"});let a=C([s.entries],([x])=>Xs(x,"from"),{name:"adjacencyOut",describeKind:"derived",initial:new Map,equals:Zs,meta:Ge("adjacency_out")}),i=C([s.entries],([x])=>Xs(x,"to"),{name:"adjacencyIn",describeKind:"derived",initial:new Map,equals:Zs,meta:Ge("adjacency_in")});r.add(a,{name:"adjacencyOut"}),r.add(i,{name:"adjacencyIn"}),r.addDisposer(Y(a)),r.addDisposer(Y(i));let d=C([o.entries],([x])=>(x??new Map).size,{name:"entityCount",describeKind:"derived",initial:0,meta:Ge("entity_count")}),u=C([s.entries],([x])=>(x??new Map).size,{name:"edgeCount",describeKind:"derived",initial:0,meta:Ge("edge_count")});r.add(d,{name:"entityCount"}),r.add(u,{name:"edgeCount"}),r.addDisposer(Y(d)),r.addDisposer(Y(u));let c=Nt({name:"events",retainedLimit:1024,graph:r}),l=Dn(r,"seq",0);function p(x){let N=a.cache,_=i.cache;return(N?.get(x)?.length??0)>0||(_?.get(x)?.length??0)>0}function f(x){if(n==="remove")for(let N of x)o.has(N)&&(p(N)||(o.delete(N),c.append({action:"orphanRemove",id:N,t_ns:ce(),seq:Bt(l)})))}let m=(x,N)=>{o.set(x,N)},h=x=>{let N=s.entries.cache,_=new Set;if(N){let M=[];for(let[A,R]of N)(R.from===x||R.to===x)&&(M.push(A),R.from!==x&&_.add(R.from),R.to!==x&&_.add(R.to));M.length>0&&s.deleteMany(M)}o.has(x)&&o.delete(x),f([..._])},g=(x,N,_,M=1)=>{s.set(jn(x,N,_),{from:x,to:N,relation:_,weight:M})},y=(x,N,_)=>{if(_!==void 0)s.delete(jn(x,N,_));else{let M=s.entries.cache;if(!M)return;let A=[];for(let[R,O]of M)O.from===x&&O.to===N&&A.push(R);A.length>0&&s.deleteMany(A)}f([x,N])},v=xe(m,{audit:c,seq:l,onSuccess:([x],N,_)=>({action:"upsertEntity",id:x,t_ns:_.t_ns,seq:_.seq})}),b=xe(h,{audit:c,seq:l,onSuccess:([x],N,_)=>({action:"removeEntity",id:x,t_ns:_.t_ns,seq:_.seq})}),w=xe(g,{audit:c,seq:l,onSuccess:([x,N,_,M],A,R)=>({action:"link",from:x,to:N,relation:_,weight:M??1,t_ns:R.t_ns,seq:R.seq})}),k=xe(y,{audit:c,seq:l,onSuccess:([x,N,_],M,A)=>({action:"unlink",from:x,to:N,..._!==void 0?{relation:_}:{},t_ns:A.t_ns,seq:A.seq})});function S(x,N){let _=Ut(x,"id"),M=N!==void 0?Ut(N,"relation"):void 0;return C(M?[a,i,_,M]:[a,i,_],R=>{let O=R[0],I=R[1],K=R[2],q=M?R[3]:void 0,H=O.get(K)??[],G=I.get(K)??[],B=new Set,E=[];for(let L of H){let J=jn(L.from,L.to,L.relation);B.has(J)||q!==void 0&&L.relation!==q||(B.add(J),E.push(L))}for(let L of G){let J=jn(L.from,L.to,L.relation);B.has(J)||q!==void 0&&L.relation!==q||(B.add(J),E.push(L))}return E},{describeKind:"derived",equals:(R,O)=>{let I=R,K=O;if(I===K)return!0;if(I==null||K==null||I.length!==K.length)return!1;for(let q=0;q<I.length;q+=1){let H=I[q],G=K[q];if(H.from!==G.from||H.to!==G.to||H.relation!==G.relation||H.weight!==G.weight)return!1}return!0},meta:Ge("related")})}return Object.assign(r,{events:c,entities:o.entries,edges:s.entries,adjacencyOut:a,adjacencyIn:i,entityCount:d,edgeCount:u,upsertEntity:v,removeEntity:b,link:w,unlink:k,relatedNode:S})}function so(t,e,n){let r=ti({dimension:n.dimension});t.add(r.entries,{name:"vectorIndex"});let s=ve([e.store.entries],([a])=>{let i=a??new Map;for(let[d,u]of i){let c=n.embedFn(u);c&&r.upsert(d,c,u)}}).subscribe(()=>{});return t.addDisposer(s),{vectors:r,dispose:()=>s()}}function io(t,e,n,r){let o=r.mountPath??n,s=ni(`${n}-kg`);if(t.mount(o,s),!r.entityFn)return{kg:s,dispose:()=>{}};let a=r.entityFn,d=ve([e.store.entries],([u])=>{let c=u??new Map;for(let[l,p]of c){let f=a(l,p);if(f){for(let m of f.entities??[])s.upsertEntity(m.id,m.value);for(let m of f.relations??[])s.link(m.from,m.to,m.relation,m.weight)}}}).subscribe(()=>{});return t.addDisposer(d),{kg:s,dispose:()=>d()}}function ao(t,e,n,r){let o=r.decayRate??$n,s=r.maxActive??1e3,a=r.archiveThreshold??.1,i=r.permanentFilter??(()=>!1),d=ei("permanent",{ranked:!1});t.mount("permanent",d);let u=_e({name:"permanentKeys"});t.add(u.entries,{name:"permanentKeys"});let c=_e({name:"entryCreatedAtNs"});t.add(c.entries,{name:"entryCreatedAtNs"});let l=r.context?j(r.context):F(null),p=l.cache,f=l.subscribe(T=>{for(let x of T)x[0]===D&&(p=x[1])}),m={score:(T,x)=>{if(i(T,x)||u.has(T))return Number.POSITIVE_INFINITY;let N=z(),_=c.get(T);_===void 0&&(_=N,c.set(T,N));let M=Number(N-_)/1e9;return zt(r.score(x,p),M,o)},archiveThreshold:a,maxSize:s},h=Fn(e,n,{score:r.score,cost:r.cost,...r.budget!==void 0?{budget:r.budget}:{},...r.evict!==void 0?{evict:r.evict}:{},...r.consolidate!==void 0?{consolidate:r.consolidate}:{},...r.consolidateTrigger!==void 0?{consolidateTrigger:r.consolidateTrigger}:{},...r.context!==void 0?{context:r.context}:{},mapOptions:{retention:m}}),g=T=>u.has(T)?"permanent":(h.store.entries.cache??new Map).has(T)?"active":"archived",y=(T,x)=>{u.set(T,!0),d.upsert(T,x)},v=h.store.entries.subscribe(T=>{for(let x of T){if(x[0]!==D)continue;let N=x[1],_=c.entries.cache;if(_==null)continue;let M=[];for(let A of _.keys())N.has(A)||M.push(A);M.length>0&&te(()=>{for(let A of M)c.delete(A)})}}),w=ve([h.store.entries],([T])=>{let x=T??new Map;for(let[N,_]of x)u.has(N)||i(N,_)&&te(()=>{y(N,_)})}).subscribe(()=>{}),k=null;r.archiveTier&&(k=t.attachSnapshotStorage([r.archiveTier],r.archiveStorageOptions??{}));let S=()=>{w(),v(),f(),k?.dispose()};return t.addDisposer(S),{store:h,tiers:{permanent:d,activeEntries:h.store.entries,archiveHandle:k,tierOf:g,markPermanent:y},dispose:S}}function Ad(t,e){if(!t||!e)return 0;let n=Math.min(t.length,e.length),r=0;for(;r<n&&t[r]===e[r];)r++;return r}function uo(t,e,n,r,o){let s=o.topK??20,a=o.graphDepth??1,i=o.budget??2e3,d=o.contextWeight??0,u=o.context?j(o.context):F(null),c=(g,y,v)=>{let b=new Map,w=[];if(n&&v.vector){let _=v.vector,M=n.entries.cache;if(M&&M.size>0&&s>0){w=[...M.values()].map(R=>({id:R.id,score:oo(_,R.vector),...R.meta!==void 0?{meta:R.meta}:{}})).sort((R,O)=>O.score-R.score).slice(0,s);for(let R of w){let O=g.get(R.id);O&&b.set(R.id,{value:O,sources:new Set(["vector"])})}}}let k=[];if(r){let _=r.adjacencyOut.cache,M=r.adjacencyIn.cache,A=[...v.entityIds??[],...b.keys()],R=new Set,O=A;for(let I=0;I<a;I++){let K=[];for(let q of O){if(R.has(q))continue;R.add(q);let H=_?.get(q)??[],G=M?.get(q)??[];for(let B of H){let E=B.to;if(!R.has(E)){K.push(E);let L=g.get(E);if(L){let J=b.get(E);J?J.sources.add("graph"):b.set(E,{value:L,sources:new Set(["graph"])}),k.push(E)}}}for(let B of G){let E=B.from;if(!R.has(E)){K.push(E);let L=g.get(E);if(L){let J=b.get(E);J?J.sources.add("graph"):b.set(E,{value:L,sources:new Set(["graph"])}),k.push(E)}}}}O=K}}for(let[_,M]of g)b.has(_)||b.set(_,{value:M,sources:new Set(["store"])});let S=v.context?.length??0,T=[];for(let[_,{value:M,sources:A}]of b){let R=o.contextOf?o.contextOf(M):void 0,O=o.score(M,y);if(d>0&&S>0){let K=Ad(v.context,R);K>0&&(O=O*(1+d*K/S))}let I=R?{key:_,value:M,score:O,sources:[...A],context:R}:{key:_,value:M,score:O,sources:[...A]};T.push(I)}T.sort((_,M)=>M.score-_.score);let x=[],N=0;for(let _ of T){let M=o.cost(_.value);if(N+M>i&&x.length>0)break;x.push(_),N+=M}return{packed:x,trace:{vectorCandidates:w,graphExpanded:k,ranked:T,packed:x}}},l=(g,y)=>{if(g===y)return!0;if(g.length!==y.length)return!1;for(let v=0;v<g.length;v++)if(g[v]!==y[v])return!1;return!0},p=F([],{name:"retrieval",describeKind:"state",meta:W("retrieval_pipeline"),equals:l});t.add(p,{name:"retrieval"});let f=F(null,{name:"retrievalTrace",describeKind:"state",meta:W("retrieval_trace")});return t.add(f,{name:"retrievalTrace"}),{retrieval:p,retrievalTrace:f,retrieve:g=>{let y=e.store.entries.cache??new Map,{packed:v,trace:b}=c(y,u.cache,g);return te(()=>{p.emit(v),f.emit(b)}),v},retrieveReactive:g=>{let y=j(g),v=C([e.store.entries,u,y],([k,S,T])=>{if(T==null)return{packed:[],trace:null};let x=k??new Map,{packed:N,trace:_}=c(x,S,T);return{packed:N,trace:_}},{name:"retrievalReactive::result",describeKind:"derived",meta:W("retrieval_reactive_result"),initial:{packed:[],trace:null}}),w=ve([v],([k])=>{let S=k;te(()=>{p.emit(S.packed),S.trace&&f.emit(S.trace)})}).subscribe(()=>{});return t.addDisposer(w),C([v],([k])=>k.packed,{name:"retrievalReactive",describeKind:"derived",meta:W("retrieval_reactive"),initial:[],equals:l})}}}Oe();ie();Ee();ke();Q();Pe();Z();Ue();var Bn=class extends ae{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;_terminalResult;_disposeRunWiring;_running=!1;_currentAbortController=null;constructor(e,n){if(super(e,n.graph),this.chat=to(`${e}-chat`,{maxMessages:n.maxMessages}),this.mount("chat",this.chat),this.tools=ro(`${e}-tools`),this.mount("tools",this.tools),n.tools)for(let E of n.tools)this.tools.register(E);this.status=F("idle",{name:"status",describeKind:"state",meta:W("agent_status")}),this.add(this.status,{name:"status"}),this.turn=F(0,{name:"turn",describeKind:"state",meta:W("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.aborted=F(!1,{name:"aborted",describeKind:"state",meta:W("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let r=0,o=this.turn.subscribe(E=>{for(let L of E)L[0]===D&&(r=L[1])}),s=!1,a=this.aborted.subscribe(E=>{for(let L of E)L[0]===D&&(s=L[1])}),i=this.chat.messages.cache??[],d=this.chat.messages.subscribe(E=>{for(let L of E)L[0]===D&&(i=L[1])}),u=this.tools.schemas.cache??[],c=this.tools.schemas.subscribe(E=>{for(let L of E)L[0]===D&&(u=L[1])}),l=n.adapter,p=n.systemPrompt,f=n.model,m=n.temperature,h=n.maxTokens,g=n.maxTurns??10,y=n.stopWhen,v=this.chat,b=this.tools,w=this.status,k=this.turn,S=this.aborted,T=ne([w],(E,L,J)=>{if(qt(E,J.prevData,0,"idle")!=="thinking"||s||r>=g){L.down([[U]]);return}if(i.length===0){L.down([[U]]);return}L.emit({messages:i,tools:u})},{name:"promptInput",describeKind:"derived",meta:W("agent_prompt_input",{closureReads:["aborted","turn","chat.messages","tools.schemas"]})}),x=de(T,E=>{let L=new AbortController;return this._currentAbortController=L,s&&L.abort(new Error("agentLoop: aborted")),j(l.invoke(E.messages,{tools:E.tools.length>0?E.tools:void 0,systemPrompt:p,model:f,temperature:m,maxTokens:h,signal:L.signal}),{signal:L.signal})},{equals:()=>!1}),N=F(null,{name:"lastResponse",describeKind:"state",meta:W("agent_last_response")});this.lastResponse=N;let _=ne([N,w],(E,L,J)=>{let he=qt(E,J.prevData,0,null);if(qt(E,J.prevData,1,"idle")!=="acting"){L.down([[U]]);return}let ee=he?.toolCalls;if(ee==null||ee.length===0){L.down([[U]]);return}L.emit(ee)},{name:"toolCallsRaw",describeKind:"derived",meta:W("agent_tool_calls_raw")}),M=n.interceptToolCalls?n.interceptToolCalls(_):_;this.toolCalls=M;let A=no({toolCalls:M,tools:b,retryCount:1});this.toolResults=A;let R=ve([x],([E])=>{if(s)return;let L=E,J=r+1,he=L.toolCalls!=null&&L.toolCalls.length>0,V=L.finishReason==="end_turn"&&(!L.toolCalls||L.toolCalls.length===0),ee=y?.(L)===!0,Re=J>=g,et=ee||V||!he||Re?"done":"acting";te(()=>{N.emit(L),w.emit(et),k.emit(J),v.append("assistant",L.content,{toolCalls:L.toolCalls})})}),O=ve([A],([E])=>{if(s)return;let L=E;if(L.length===0)return;let J=r>=g?"done":"thinking";te(()=>{w.emit(J);for(let he of L)v.appendToolResult(he.id,he.content)})}),I=w.cache??"idle",K=w.subscribe(E=>{for(let L of E)L[0]===D&&(I=L[1])}),q=ve([S],([E])=>{E===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),I!=="done"&&w.emit("done"))}),H=Y(R),G=Y(O),B=Y(q);this._terminalResult=ne([w,N],(E,L,J)=>{let he=qt(E,J.prevData,0,"idle"),V=qt(E,J.prevData,1,null);if(he==="done"){if(V!=null){L.emit(V);return}let ee=new Error("agentLoop: aborted");ee.name="AbortError",L.down([[P,ee]]);return}if(he==="error"){L.down([[P,new Error("agentLoop: errored")]]);return}L.down([[U]])},{name:"terminalResult",describeKind:"derived",meta:W("agent_terminal_result")}),this.add(T,{name:"promptInput"}),this.add(x,{name:"llmResponse"}),this.add(this.lastResponse,{name:"lastResponse"}),this.toolCalls===_?this.add(this.toolCalls,{name:"toolCalls"}):(this.add(_,{name:"toolCallsRaw"}),this.add(this.toolCalls,{name:"toolCalls"})),this.add(A,{name:"toolResults"}),this.add(this._terminalResult,{name:"terminalResult"}),this.addDisposer(o),this.addDisposer(a),this.addDisposer(K),this.addDisposer(d),this.addDisposer(c),this.addDisposer(H),this.addDisposer(G),this.addDisposer(B),this._disposeRunWiring=()=>{}}async run(e,n){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 r;try{te(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle"),this.lastResponse.emit(null)}),e!=null&&this.chat.append("user",e);let o=cs(this._terminalResult,{skipCurrent:!0});if(n!=null)if(n.aborted)this.aborted.emit(!0);else{let s=()=>this.aborted.emit(!0);n.addEventListener("abort",s,{once:!0}),r=()=>n.removeEventListener("abort",s)}return n?.aborted!==!0&&this.status.emit("thinking"),await o}finally{r?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function qt(t,e,n,r){let o=t[n];if(o!=null&&o.length>0)return o[o.length-1];let s=e[n];return s!==void 0?s:r}function Cd(t,e){let n=new Bn(t,e);return n.tagFactory("agentLoop",Je(e)),n}ie();Ee();Q();Pe();Z();Ue();function Ld(t,e,n){let r=new ae(t,n.graph);r.tagFactory("agentMemory",Je(n));let o;if(n.extractFn)o=n.extractFn;else if(n.adapter&&n.extractPrompt)o=Jr(n.extractPrompt,{adapter:n.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let s=(v,b)=>{let w=b.cache??new Map,k=b.subscribe(S=>{for(let T of S)T[0]===D&&(w=T[1])});return r.addDisposer(k),de(v,S=>S==null?{upsert:[]}:o(S,w))},a=e;if(n.admissionFilter){let v=j(e),b=n.admissionFilter;a=C([v],([w])=>{if(b(w))return w},{name:"admissionFilter",describeKind:"derived"})}let i;n.consolidateFn?i=n.consolidateFn:n.adapter&&n.consolidatePrompt&&(i=Yr(n.consolidatePrompt,{adapter:n.adapter}));let d=n.consolidateTrigger;if(!d&&i&&n.reflection?.enabled!==!1){let v=n.reflection?.interval??3e5;d=yn(v,{period:v})}let u={score:n.score,cost:n.cost,budget:n.budget??2e3,context:n.context,consolidate:i,consolidateTrigger:d},c,l=null;if(n.tiers){let v=ao(r,a,s,{...n.tiers,score:n.score,cost:n.cost,...n.budget!==void 0?{budget:n.budget}:{budget:2e3},...n.context!==void 0?{context:n.context}:{},...i!==void 0?{consolidate:i}:{},...d!==void 0?{consolidateTrigger:d}:{}});c=v.store,l=v.tiers}else c=Fn(a,s,u);r.add(c.store.entries,{name:"store"}),r.add(c.compact,{name:"compact"}),r.add(c.size,{name:"size"});let p=null;n.vectorDimensions&&n.vectorDimensions>0&&n.embedFn&&(p=so(r,c,{dimension:n.vectorDimensions,embedFn:n.embedFn}).vectors);let f=null;n.enableKnowledgeGraph&&(f=io(r,c,t,{mountPath:"kg",entityFn:n.entityFn}).kg);let m=null,h=null,g=null,y=null;if(p||f){let v=uo(r,c,p,f,{score:n.score,cost:n.cost,budget:n.budget,topK:n.retrieval?.topK,graphDepth:n.retrieval?.graphDepth,contextOf:n.contextOf,contextWeight:n.contextWeight,context:n.context});m=v.retrieval,h=v.retrievalTrace,g=v.retrieve,y=v.retrieveReactive}return Object.assign(r,{distillBundle:c,compact:c.compact,size:c.size,vectors:p,kg:f,memoryTiers:l,retrieval:m,retrievalTrace:h,retrieve:g,retrieveReactive:y})}function Dd(t,e,n){let r=t.describe({actor:e,detail:"full"}),o=n?.groupByTags??!0,s=n?.separator??`
12
+ `,a=[],i=n?.sinceVersion;for(let[d,u]of Object.entries(r.nodes)){let c=u.meta??{},l=c.description,p=c.format;if(!l&&!p)continue;if(i!=null&&u.v!=null){let y=i.get(d);if(y!=null&&y.id===u.v.id&&u.v.version<=y.version)continue}let f=l??d,m=u.value,h=c.unit,g;p==="currency"&&typeof m=="number"?g=`$${m.toFixed(2)}`:p==="percentage"&&typeof m=="number"?g=`${(m*100).toFixed(1)}%`:m==null?g="(no value)":g=String(m),h&&p!=="currency"&&p!=="percentage"&&(g=`${g} ${h}`),a.push({path:d,description:f,formatted:g})}if(a.length===0)return"";if(o){let d=new Map,u=[];for(let l of a){let f=r.nodes[l.path].meta?.tags;if(f&&f.length>0){let m=f[0],h=d.get(m);h||(h=[],d.set(m,h)),h.push(l)}else u.push(l)}if(d.size===0)return a.map(l=>`- ${l.description}: ${l.formatted}`).join(s);let c=[];for(let[l,p]of[...d.entries()].sort((f,m)=>f[0].localeCompare(m[0])))c.push(`[${l}]${s}${p.map(f=>`- ${f.description}: ${f.formatted}`).join(s)}`);return u.length>0&&c.push(u.map(l=>`- ${l.description}: ${l.formatted}`).join(s)),c.join(s+s)}return a.map(d=>`- ${d.description}: ${d.formatted}`).join(s)}ie();Q();Pe();Z();Q();Ue();Oe();ie();ke();Q();Ye();Z();function ri(t,e){return ue("reduction",t,e)}function oi(t,e,n,r){let o=r?.maxIterations??10,s=`__feedback_${e}`,a=F(0,{meta:ri("feedback_counter",{maxIterations:o,feedbackFrom:e,feedbackTo:n})});t.add(a,{name:s});let i=t.resolve(e),d=t.resolve(n),u=`__feedback_effect_${e}`,c=ne([],(l,p)=>{let f=i.subscribe(m=>{for(let h of m){let g=h[0];if(g===D){let y=h[1];if(y==null)return;te(()=>{Vs(a,o)&&d.emit(y)})}else if(g===$||g===P){let y=g===P&&h.length>1?[P,h[1]]:[g];a.down([y])}}});return()=>f()},{name:u,describeKind:"effect",meta:{...ri("feedback_effect",{feedbackFrom:e,feedbackTo:n}),_internal:!0}});return t.add(c,{name:u}),t.addDisposer(Y(c)),t}function _t(t){let e=t.meta?.factory;return typeof e=="string"?e:void 0}function Mt(t){let e=t.meta?.factoryArgs;return e!=null&&typeof e=="object"?e:{}}function si(t){let e=Mt(t);return"initial"in e?e.initial:t.value}function ai(t){return typeof t=="object"&&t!==null&&"factory"in t}function di(t){return typeof t=="object"&&t!==null&&"factory"in t}function Id(t){return ai(t)?t.factory:t}function Pd(t){return di(t)?t.factory:t}function Gd(t,e){let n=[],r=new Set(Object.keys(e.fns??{})),o=new Set(Object.keys(e.sources??{}));for(let[s,a]of Object.entries(t.nodes)){if(a.type==="template")continue;let i=a,d=_t(i);if(d==null)continue;let u=i.type==="producer";if(i.type==="state"&&d==="state")continue;if(u){let l=o.has(d),p=r.has(d);if(!l&&!p&&(o.size>0||r.size>0)){let f=Vn(d,o)??Vn(d,r);n.push(`Node "${s}": source "${d}" not found in catalog`+(f?`. Did you mean "${f}"?`:""))}}else if(r.size>0&&!r.has(d))if(o.has(d))n.push(`Node "${s}": fn "${d}" is a source, not a function. Use it as a producer source instead, or use a function from: ${[...r].join(", ")}`);else{let l=Vn(d,r);n.push(`Node "${s}": fn "${d}" not found in catalog`+(l?`. Did you mean "${l}"?`:""))}let c=Mt(i);if(!u&&e.fns?.[d]){let l=e.fns[d];if(ai(l)&&l.configSchema){for(let[p,f]of Object.entries(l.configSchema))if(f.required!==!1&&!(p in c)&&n.push(`Node "${s}": config missing required field "${p}"`),p in c&&f.enum){let m=c[p];f.enum.includes(m)||n.push(`Node "${s}": config.${p} = ${JSON.stringify(m)}, expected one of: ${f.enum.join(", ")}`)}}}if(u&&e.sources?.[d]){let l=e.sources[d];if(di(l)&&l.configSchema){for(let[p,f]of Object.entries(l.configSchema))if(f.required!==!1&&!(p in c)&&n.push(`Node "${s}": config missing required field "${p}"`),p in c&&f.enum){let m=c[p];f.enum.includes(m)||n.push(`Node "${s}": config.${p} = ${JSON.stringify(m)}, expected one of: ${f.enum.join(", ")}`)}}}}if(t.templates)for(let[s,a]of Object.entries(t.templates))for(let[i,d]of Object.entries(a.nodes)){let u=_t(d);if(u!=null&&!(d.type==="state"&&u==="state")&&d.type!=="producer"&&r.size>0&&!r.has(u)){let c=Vn(u,r);n.push(`Template "${s}" node "${i}": fn "${u}" not found in catalog`+(c?`. Did you mean "${c}"?`:""))}}return{valid:n.length===0,errors:n,warnings:[]}}function Vn(t,e){let n=null,r=1/0,o=t.toLowerCase();for(let s of e){let a=Fd(o,s.toLowerCase());a<r&&a<=Math.max(3,Math.floor(t.length/2))&&(r=a,n=s)}return n}function Fd(t,e){let n=t.length,r=e.length,o=Array.from({length:n+1},(s,a)=>Array.from({length:r+1},(i,d)=>a===0?d:d===0?a:0));for(let s=1;s<=n;s++)for(let a=1;a<=r;a++)o[s][a]=t[s-1]===e[a-1]?o[s-1][a-1]:1+Math.min(o[s-1][a],o[s][a-1],o[s-1][a-1]);return o[n][r]}var ii=new Set(["state","producer","derived","effect","operator","template"]),$d=new Set(["state","producer","derived","effect","operator"]);function jd(t){let e=[],n=[];if(t==null||typeof t!="object")return{valid:!1,errors:["GraphSpec must be a non-null object"],warnings:n};let r=t;if((typeof r.name!="string"||r.name.length===0)&&e.push("Missing or empty 'name' field"),r.nodes==null||typeof r.nodes!="object"||Array.isArray(r.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e,warnings:n};let o=new Set(Object.keys(r.nodes)),s=new Map,a=new Map;if(r.templates!=null&&typeof r.templates=="object"&&!Array.isArray(r.templates)){for(let[i,d]of Object.entries(r.templates))if(d!=null&&typeof d=="object"){let u=d;a.set(i,{params:Array.isArray(u.params)?u.params:[]})}}if(r.templates!=null)if(typeof r.templates!="object"||Array.isArray(r.templates))e.push("'templates' must be an object");else for(let[i,d]of Object.entries(r.templates)){if(d==null||typeof d!="object"){e.push(`Template "${i}": must be an object`);continue}let u=d;if(Array.isArray(u.params)||e.push(`Template "${i}": missing 'params' array`),u.nodes==null||typeof u.nodes!="object"||Array.isArray(u.nodes))e.push(`Template "${i}": missing or invalid 'nodes' object`);else{let c=new Set(Array.isArray(u.params)?u.params:[]),l=new Set(Object.keys(u.nodes));for(let[p,f]of Object.entries(u.nodes)){if(f==null||typeof f!="object"){e.push(`Template "${i}" node "${p}": must be an object`);continue}let m=f;if((typeof m.type!="string"||!$d.has(m.type))&&e.push(`Template "${i}" node "${p}": invalid type`),Array.isArray(m.deps))for(let h of m.deps)!l.has(h)&&!c.has(h)&&e.push(`Template "${i}" node "${p}": dep "${h}" is not an inner node or param`)}typeof u.output!="string"?e.push(`Template "${i}": missing 'output' string`):u.nodes[u.output]||e.push(`Template "${i}": output "${u.output}" is not a declared node`)}}for(let[i,d]of Object.entries(r.nodes)){if(d==null||typeof d!="object"){e.push(`Node "${i}": must be an object`);continue}let u=d;if(typeof u.type!="string"||!ii.has(u.type)){e.push(`Node "${i}": invalid type "${String(u.type)}" (expected: ${[...ii].join(", ")})`);continue}if(s.set(i,u.type),u.type==="template")if(typeof u.template!="string"||!a.has(u.template))e.push(`Node "${i}": template "${String(u.template)}" not found in templates`);else if(u.bind==null||typeof u.bind!="object"||Array.isArray(u.bind))e.push(`Node "${i}": template ref requires 'bind' object`);else{let c=a.get(u.template),l=u.bind;for(let p of c.params)p in l||e.push(`Node "${i}": template param "${p}" is not bound (template "${u.template}")`);for(let[,p]of Object.entries(l))typeof p=="string"&&!o.has(p)&&e.push(`Node "${i}": bind target "${p}" does not reference an existing node`)}else{if(Array.isArray(u.deps))for(let c of u.deps)c===i?e.push(`Node "${i}": self-referencing dep`):o.has(c)||e.push(`Node "${i}": dep "${c}" does not reference an existing node`);(u.type==="derived"||u.type==="effect"||u.type==="operator")&&!Array.isArray(u.deps)&&e.push(`Node "${i}": ${u.type} node should have a 'deps' array`)}}if(r.feedback!=null)if(!Array.isArray(r.feedback))e.push("'feedback' must be an array");else for(let i=0;i<r.feedback.length;i++){let d=r.feedback[i];if(d==null||typeof d!="object"){e.push(`Feedback [${i}]: must be an object`);continue}let u=d;typeof u.from!="string"||!o.has(u.from)?e.push(`Feedback [${i}]: 'from' "${String(u.from)}" does not reference an existing node`):s.get(u.from)==="effect"&&n.push(`Feedback [${i}]: 'from' "${u.from}" is an effect node \u2014 effects emit no DATA, so the feedback edge will never fire. Did you mean a derived/state node upstream?`),typeof u.from=="string"&&u.from===u.to&&e.push(`Feedback [${i}]: 'from' and 'to' must be different nodes`),typeof u.to!="string"||!o.has(u.to)?e.push(`Feedback [${i}]: 'to' "${String(u.to)}" does not reference an existing node`):typeof u.to=="string"&&s.get(u.to)!=="state"&&e.push(`Feedback [${i}]: 'to' node "${u.to}" must be a state node (got "${s.get(u.to)??"unknown"}")`)}return{valid:e.length===0,errors:e,warnings:n}}function ui(t,e){let n=jd(t);if(!n.valid)throw new Error(`compileSpec: invalid GraphSpec:
13
13
  ${n.errors.join(`
14
- `)}`);let r=t.factory,o=t.factoryArgs;if(typeof r=="string"){let y=e?.catalog?.graphFactories?.[r];if(y)return y(o)}let s=e?.catalog??{},a=e?.onMissing??"placeholder",i=new ie(t.name),d=t.templates??{},u=Id(t,s);if(!u.valid)throw new Error(`compileSpec: catalog validation errors:
14
+ `)}`);let r=t.factory,o=t.factoryArgs;if(typeof r=="string"){let b=e?.catalog?.graphFactories?.[r];if(b)return b(o)}let s=e?.catalog??{},a=e?.onMissing??"placeholder",i=new ae(t.name),d=t.templates??{},u=Gd(t,s);if(!u.valid)throw new Error(`compileSpec: catalog validation errors:
15
15
  ${u.errors.join(`
16
- `)}`);let c=[],l=(y,v,k)=>{c.push({path:y,kind:v,name:k})},p=y=>{let v=s.fns?.[y];return v?Ld(v):void 0},f=y=>{let v=s.sources?.[y];return v?Dd(v):void 0},m=y=>{if(!y)return;let v={};for(let[k,N]of Object.entries(y))k==="factory"||k==="factoryArgs"||(v[k]=N);return Object.keys(v).length>0?v:void 0},h=new Map,g=[];for(let[y,v]of Object.entries(t.nodes)){if(v.type==="template")continue;let k=v,N=St(k),w=Nt(k);if(k.type==="state"){let R=ni(k),x=F(R,{name:y,meta:m(k.meta)});i.add(x,{name:y}),h.set(y,x)}else if(k.type==="producer"){let R=N?f(N):void 0,x=N?p(N):void 0;if(R){let _=R(w);i.add(_,{name:y}),h.set(y,_)}else if(x){let _=x([],w);i.add(_,{name:y}),h.set(y,_)}else{N&&l(y,"source",N);let _=se(()=>{},{name:y,meta:{...m(k.meta),_specSource:N}});i.add(_,{name:y}),h.set(y,_)}}else g.push([y,k])}let b=!0,T=new Map(g);for(;T.size>0&&b;){b=!1;for(let[y,v]of[...T.entries()]){let k=v.deps??[];if(!k.every(M=>h.has(M)))continue;let N=k.map(M=>h.get(M)),w=St(v),R=Nt(v),x=w?p(w):void 0,_;x?_=x(N,R):v.type==="effect"?(w&&l(y,"fn",w),_=Ne(N,()=>{})):(w&&l(y,"fn",w),_=A(N,M=>M[0])),i.add(_,{name:y}),h.set(y,_),T.delete(y),b=!0}}if(T.size>0){let y=[...T.keys()].sort().join(", ");throw new Error(`compileSpec: unresolvable deps for nodes: ${y}`)}for(let[y,v]of Object.entries(t.nodes)){if(v.type!=="template")continue;let k=v,N=d[k.template],w=new ie(y),R=new Map,x=[];for(let[S,O]of Object.entries(N.nodes)){let I=(O.deps??[]).map(G=>G.startsWith("$")&&k.bind[G]?k.bind[G]:G),K={...O,deps:I},q=St(O),H=Nt(O);if(O.type==="state"){let G=ni(O),j=F(G,{name:S,meta:m(O.meta)});w.add(j,{name:S}),R.set(S,j)}else if(O.type==="producer"){let G=q?f(q):void 0,j=q?p(q):void 0;if(G){let E=G(H);w.add(E,{name:S}),R.set(S,E)}else if(j){let E=j([],H);w.add(E,{name:S}),R.set(S,E)}else{q&&l(`${y}.${S}`,"source",q);let E=se(()=>{},{name:S,meta:{...m(O.meta),_specSource:q}});w.add(E,{name:S}),R.set(S,E)}}else x.push([S,K])}let _=!0,M=new Map(x);for(;M.size>0&&_;){_=!1;for(let[S,O]of[...M.entries()]){let I=O.deps??[];if(!I.every(C=>R.has(C)||h.has(C)))continue;let q=I.map(C=>R.get(C)??h.get(C)),H=St(O),G=Nt(O),j=H?p(H):void 0,E;j?E=j(q,G):O.type==="effect"?(H&&l(`${y}.${S}`,"fn",H),E=Ne(q,()=>{})):(H&&l(`${y}.${S}`,"fn",H),E=A(q,C=>C[0])),w.add(E,{name:S}),R.set(S,E),M.delete(S),_=!0}}if(M.size>0){let S=[...M.keys()].sort().join(", ");throw new Error(`compileSpec: template "${k.template}" has unresolvable deps: ${S}`)}i.mount(y,w);let L=`${y}::${N.output}`;h.set(y,i.resolve(L));try{let S=i.resolve(L);S.meta._templateName?.emit(k.template),S.meta._templateBind?.emit(k.bind)}catch{}}for(let y of t.feedback??[])ti(i,y.from,y.to,{maxIterations:y.maxIterations});if(c.length>0){if(a==="error"){let y=c.map(v=>` - ${v.path}: missing ${v.kind} "${v.name}"`);throw new Error(`compileSpec: ${c.length} catalog entr${c.length===1?"y":"ies"} missing \u2014 pass them via opts.catalog or set opts.onMissing to "warn"/"placeholder":
17
- ${y.join(`
18
- `)}`)}if(a==="warn"){let y=e?.onWarn??(v=>console.warn(v));for(let v of c)y(`compileSpec: ${v.path} references missing ${v.kind} "${v.name}" \u2014 substituted placeholder`)}}return i}var ai=`You are a graph architect for GraphReFly, a reactive graph protocol.
16
+ `)}`);let c=[],l=(b,w,k)=>{c.push({path:b,kind:w,name:k})},p=b=>{let w=s.fns?.[b];return w?Id(w):void 0},f=b=>{let w=s.sources?.[b];return w?Pd(w):void 0},m=b=>{if(!b)return;let w={};for(let[k,S]of Object.entries(b))k==="factory"||k==="factoryArgs"||(w[k]=S);return Object.keys(w).length>0?w:void 0},h=new Map,g=[];for(let[b,w]of Object.entries(t.nodes)){if(w.type==="template")continue;let k=w,S=_t(k),T=Mt(k);if(k.type==="state"){let x=si(k),N=F(x,{name:b,meta:m(k.meta)});i.add(N,{name:b}),h.set(b,N)}else if(k.type==="producer"){let x=S?f(S):void 0,N=S?p(S):void 0;if(x){let _=x(T);i.add(_,{name:b}),h.set(b,_)}else if(N){let _=N([],T);i.add(_,{name:b}),h.set(b,_)}else{S&&l(b,"source",S);let _=se(()=>{},{name:b,meta:{...m(k.meta),_specSource:S}});i.add(_,{name:b}),h.set(b,_)}}else g.push([b,k])}let y=!0,v=new Map(g);for(;v.size>0&&y;){y=!1;for(let[b,w]of[...v.entries()]){let k=w.deps??[];if(!k.every(M=>h.has(M)))continue;let S=k.map(M=>h.get(M)),T=_t(w),x=Mt(w),N=T?p(T):void 0,_;N?_=N(S,x):w.type==="effect"?(T&&l(b,"fn",T),_=ve(S,()=>{})):(T&&l(b,"fn",T),_=C(S,M=>M[0])),i.add(_,{name:b}),h.set(b,_),v.delete(b),y=!0}}if(v.size>0){let b=[...v.keys()].sort().join(", ");throw new Error(`compileSpec: unresolvable deps for nodes: ${b}`)}for(let[b,w]of Object.entries(t.nodes)){if(w.type!=="template")continue;let k=w,S=d[k.template],T=new ae(b),x=new Map,N=[];for(let[R,O]of Object.entries(S.nodes)){let I=(O.deps??[]).map(G=>G.startsWith("$")&&k.bind[G]?k.bind[G]:G),K={...O,deps:I},q=_t(O),H=Mt(O);if(O.type==="state"){let G=si(O),B=F(G,{name:R,meta:m(O.meta)});T.add(B,{name:R}),x.set(R,B)}else if(O.type==="producer"){let G=q?f(q):void 0,B=q?p(q):void 0;if(G){let E=G(H);T.add(E,{name:R}),x.set(R,E)}else if(B){let E=B([],H);T.add(E,{name:R}),x.set(R,E)}else{q&&l(`${b}.${R}`,"source",q);let E=se(()=>{},{name:R,meta:{...m(O.meta),_specSource:q}});T.add(E,{name:R}),x.set(R,E)}}else N.push([R,K])}let _=!0,M=new Map(N);for(;M.size>0&&_;){_=!1;for(let[R,O]of[...M.entries()]){let I=O.deps??[];if(!I.every(L=>x.has(L)||h.has(L)))continue;let q=I.map(L=>x.get(L)??h.get(L)),H=_t(O),G=Mt(O),B=H?p(H):void 0,E;B?E=B(q,G):O.type==="effect"?(H&&l(`${b}.${R}`,"fn",H),E=ve(q,()=>{})):(H&&l(`${b}.${R}`,"fn",H),E=C(q,L=>L[0])),T.add(E,{name:R}),x.set(R,E),M.delete(R),_=!0}}if(M.size>0){let R=[...M.keys()].sort().join(", ");throw new Error(`compileSpec: template "${k.template}" has unresolvable deps: ${R}`)}i.mount(b,T);let A=`${b}::${S.output}`;h.set(b,i.resolve(A));try{let R=i.resolve(A);R.meta._templateName?.emit(k.template),R.meta._templateBind?.emit(k.bind)}catch{}}for(let b of t.feedback??[])oi(i,b.from,b.to,{maxIterations:b.maxIterations});if(c.length>0){if(a==="error"){let b=c.map(w=>` - ${w.path}: missing ${w.kind} "${w.name}"`);throw new Error(`compileSpec: ${c.length} catalog entr${c.length===1?"y":"ies"} missing \u2014 pass them via opts.catalog or set opts.onMissing to "warn"/"placeholder":
17
+ ${b.join(`
18
+ `)}`)}if(a==="warn"){let b=e?.onWarn??(w=>console.warn(w));for(let w of c)b(`compileSpec: ${w.path} references missing ${w.kind} "${w.name}" \u2014 substituted placeholder`)}}return i}var ci=`You are a graph architect for GraphReFly, a reactive graph protocol.
19
19
 
20
20
  Given a natural-language description, produce a JSON graph specification with this structure:
21
21
 
@@ -48,9 +48,9 @@ Rules:
48
48
  - "operator" nodes are parameterized transformations with deps.
49
49
  - Use "deps" inside each node to declare dependencies \u2014 no separate "edges" array.
50
50
  - meta.description is required for every node.
51
- - Return ONLY valid JSON, no markdown fences or commentary.`;async function di(t,e,n){let o=[{role:"system",content:n?.systemPromptExtra?`${ai}
51
+ - Return ONLY valid JSON, no markdown fences or commentary.`;async function li(t,e,n){let o=[{role:"system",content:n?.systemPromptExtra?`${ci}
52
52
 
53
- ${n.systemPromptExtra}`:ai},{role:"user",content:t}],s=e.invoke(o,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens,signal:n?.signal}),i=(await Ft(s)).content.trim();i.startsWith("```")&&(i=kt(i));let d;try{d=JSON.parse(i)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${i.slice(0,200)}`)}return ii(d,{catalog:n?.catalog})}function $d(t,e,n){let r=V(t);return ae(r,o=>!o||typeof o!="string"||o.trim().length===0?F(null):se(s=>{let a=new AbortController,i=!1;return di(o,e,{...n,signal:a.signal}).then(d=>{if(i){d.destroy();return}s.emit(d),s.down([[$]])}).catch(d=>{i||s.down([[P,d]])}),()=>{i=!0,a.abort()}},{name:"graphFromSpec::call"}))}function jd(t){let e={},n=t.type;return n==="enum"&&Array.isArray(t.values)?(e.type="string",e.enum=t.values):n==="integer"?e.type="integer":n==="number"?e.type="number":n==="boolean"?e.type="boolean":n==="string"?e.type="string":e.type=["string","number","boolean"],Array.isArray(t.range)&&t.range.length===2&&(e.minimum=t.range[0],e.maximum=t.range[1]),typeof t.format=="string"&&(e.description=`Format: ${t.format}`),typeof t.unit=="string"&&(e.description?e.description+=` (${t.unit})`:e.description=`Unit: ${t.unit}`),e}function Bd(t,e){let n=t.describe({actor:e,detail:"full"}),r=[],o=[],s=[];for(let[a,i]of Object.entries(n.nodes)){if(i.type!=="state"||a.includes("::__meta__::")||i.status==="completed"||i.status==="errored")continue;let d=i.meta??{},u=d.access;if(u==="human"||u==="system")continue;let c=d.description??`Set the value of ${a}`,l=jd(d),p={type:"object",required:["value"],properties:{value:l},additionalProperties:!1},f=a.replace(/::/g,"__");r.push({type:"function",function:{name:f,description:c,parameters:p}}),o.push({name:a,description:c,inputSchema:p});let m=t,h=e,g=i.v;s.push({name:a,description:c,parameters:p,handler(b){return m.set(a,b.value,h?{actor:h}:void 0),b.value},...g!=null?{version:{id:g.id,version:g.version}}:{}})}return{openai:r,mcp:o,definitions:s}}de();Q();Ie();Z();var Vd=`You are a reactive graph optimizer for GraphReFly.
53
+ ${n.systemPromptExtra}`:ci},{role:"user",content:t}],s=e.invoke(o,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens,signal:n?.signal}),i=(await jt(s)).content.trim();i.startsWith("```")&&(i=Rt(i));let d;try{d=JSON.parse(i)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${i.slice(0,200)}`)}return ui(d,{catalog:n?.catalog})}function Bd(t,e,n){let r=j(t);return de(r,o=>!o||typeof o!="string"||o.trim().length===0?F(null):se(s=>{let a=new AbortController,i=!1;return li(o,e,{...n,signal:a.signal}).then(d=>{if(i){d.destroy();return}s.emit(d),s.down([[$]])}).catch(d=>{i||s.down([[P,d]])}),()=>{i=!0,a.abort()}},{name:"graphFromSpec::call"}))}function Vd(t){let e={},n=t.type;return n==="enum"&&Array.isArray(t.values)?(e.type="string",e.enum=t.values):n==="integer"?e.type="integer":n==="number"?e.type="number":n==="boolean"?e.type="boolean":n==="string"?e.type="string":e.type=["string","number","boolean"],Array.isArray(t.range)&&t.range.length===2&&(e.minimum=t.range[0],e.maximum=t.range[1]),typeof t.format=="string"&&(e.description=`Format: ${t.format}`),typeof t.unit=="string"&&(e.description?e.description+=` (${t.unit})`:e.description=`Unit: ${t.unit}`),e}function Kd(t,e){let n=t.describe({actor:e,detail:"full"}),r=[],o=[],s=[];for(let[a,i]of Object.entries(n.nodes)){if(i.type!=="state"||a.includes("::__meta__::")||i.status==="completed"||i.status==="errored")continue;let d=i.meta??{},u=d.access;if(u==="human"||u==="system")continue;let c=d.description??`Set the value of ${a}`,l=Vd(d),p={type:"object",required:["value"],properties:{value:l},additionalProperties:!1},f=a.replace(/::/g,"__");r.push({type:"function",function:{name:f,description:c,parameters:p}}),o.push({name:a,description:c,inputSchema:p});let m=t,h=e,g=i.v;s.push({name:a,description:c,parameters:p,handler(y){return m.set(a,y.value,h?{actor:h}:void 0),y.value},...g!=null?{version:{id:g.id,version:g.version}}:{}})}return{openai:r,mcp:o,definitions:s}}ie();Q();Pe();Z();var zd=`You are a reactive graph optimizer for GraphReFly.
54
54
 
55
55
  Given a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.
56
56
 
@@ -71,4 +71,4 @@ Return ONLY valid JSON with this structure:
71
71
  Rules:
72
72
  - Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).
73
73
  - Keep changes minimal \u2014 prefer the smallest set of operations that solves the problem.
74
- - Return ONLY valid JSON, no markdown fences or commentary.`;async function ui(t,e,n,r){let{expand:o,...s}=t.describe({actor:r?.actor,detail:"standard"}),a=[{role:"system",content:Vd},{role:"user",content:JSON.stringify({graph:s,problem:e})}],i=n.invoke(a,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens,signal:r?.signal}),u=(await Ft(i)).content.trim();u.startsWith("```")&&(u=u.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let c;try{c=JSON.parse(u)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${u.slice(0,200)}`)}let l=c;if(typeof l.summary!="string")throw new Error("suggestStrategy: missing 'summary' in response");if(typeof l.reasoning!="string")throw new Error("suggestStrategy: missing 'reasoning' in response");if(!Array.isArray(l.operations))throw new Error("suggestStrategy: missing 'operations' array in response");return{summary:l.summary,reasoning:l.reasoning,operations:l.operations}}function Kd(t,e,n,r){let o=V(e),s=ls(o,t);return ae(s,a=>{if(a==null)return F(null);let[i,d]=a;return!d||!i||typeof i!="string"||i.trim().length===0?F(null):d.destroyed?F(null):se(u=>{let c=new AbortController,l=!1;return ui(d,i,n,{...r,signal:c.signal}).then(p=>{l||(u.emit(p),u.down([[$]]))}).catch(p=>{l||u.down([[P,p]])}),()=>{l=!0,c.abort()}},{name:"suggestStrategy::call"})})}var ci=new Set(["state","derived","producer","operator","effect"]);function zd(t){let e=[];if(t==null||typeof t!="object")return{valid:!1,errors:["Definition must be a non-null object"]};let n=t;if((typeof n.name!="string"||n.name.length===0)&&e.push("Missing or empty 'name' field"),n.nodes==null||typeof n.nodes!="object"||Array.isArray(n.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e};let r=new Set(Object.keys(n.nodes));for(let[o,s]of Object.entries(n.nodes)){if(s==null||typeof s!="object"){e.push(`Node "${o}": must be an object`);continue}let a=s;if((typeof a.type!="string"||!ci.has(a.type))&&e.push(`Node "${o}": invalid type "${String(a.type)}" (expected: ${[...ci].join(", ")})`),Array.isArray(a.deps))for(let i of a.deps)typeof i=="string"&&!r.has(i)&&e.push(`Node "${o}": dep "${i}" does not reference an existing node`)}if(!Array.isArray(n.edges))n.edges!==void 0&&e.push("'edges' must be an array");else{let o=new Set;for(let s=0;s<n.edges.length;s++){let a=n.edges[s];if(a==null||typeof a!="object"){e.push(`Edge [${s}]: must be an object`);continue}let i=a;(typeof i.from!="string"||!r.has(i.from))&&e.push(`Edge [${s}]: 'from' "${String(i.from)}" does not reference an existing node`),(typeof i.to!="string"||!r.has(i.to))&&e.push(`Edge [${s}]: 'to' "${String(i.to)}" does not reference an existing node`);let d=`${i.from}->${i.to}`;o.has(d)&&e.push(`Edge [${s}]: duplicate edge ${d}`),o.add(d)}}return{valid:e.length===0,errors:e}}0&&(module.exports={AgentLoopGraph,AllTiersExhaustedError,BudgetExhaustedError,ChatStreamGraph,CircuitOpenError,DEFAULT_DECAY_RATE,FallbackMissError,LLMTimeoutError,ReplayCacheMissError,ToolRegistryGraph,admissionFilter3D,admissionScored,agentLoop,agentMemory,anthropicAdapter,canonicalJson,cascadingLlmAdapter,chatStream,composePricing,computePrice,contentGate,costMeterExtractor,createAdapter,createCapabilitiesRegistry,createPricingRegistry,dryRunAdapter,fallbackAdapter,frozenContext,gatedStream,gaugesAsContext,googleAdapter,graphFromSpec,graphFromSpecReactive,handoff,keywordFlagExtractor,knobsAsTools,llmConsolidator,llmExtractor,memoryRetrieval,memoryWithKG,memoryWithTiers,memoryWithVectors,observableAdapter,openAICompatAdapter,parseRateLimitFromError,pricingFor,promptCall,promptNode,redactor,registryPricing,resilientAdapter,streamExtractor,streamingPromptNode,suggestStrategy,suggestStrategyReactive,systemPromptBuilder,tier,toolCallExtractor,toolExecution,toolRegistry,toolSelector,validateGraphDef,withBreaker,withBudgetGate,withDryRun,withRateLimiter,withReplayCache,withRetry,withTimeout,zeroPrice});
74
+ - Return ONLY valid JSON, no markdown fences or commentary.`;async function pi(t,e,n,r){let{expand:o,...s}=t.describe({actor:r?.actor,detail:"standard"}),a=[{role:"system",content:zd},{role:"user",content:JSON.stringify({graph:s,problem:e})}],i=n.invoke(a,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens,signal:r?.signal}),u=(await jt(i)).content.trim();u.startsWith("```")&&(u=u.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let c;try{c=JSON.parse(u)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${u.slice(0,200)}`)}let l=c;if(typeof l.summary!="string")throw new Error("suggestStrategy: missing 'summary' in response");if(typeof l.reasoning!="string")throw new Error("suggestStrategy: missing 'reasoning' in response");if(!Array.isArray(l.operations))throw new Error("suggestStrategy: missing 'operations' array in response");return{summary:l.summary,reasoning:l.reasoning,operations:l.operations}}function Ud(t,e,n,r){let o=j(e),s=gs(o,t);return de(s,a=>{if(a==null)return F(null);let[i,d]=a;return!d||!i||typeof i!="string"||i.trim().length===0?F(null):d.destroyed?F(null):se(u=>{let c=new AbortController,l=!1;return pi(d,i,n,{...r,signal:c.signal}).then(p=>{l||(u.emit(p),u.down([[$]]))}).catch(p=>{l||u.down([[P,p]])}),()=>{l=!0,c.abort()}},{name:"suggestStrategy::call"})})}var fi=new Set(["state","derived","producer","operator","effect"]);function qd(t){let e=[];if(t==null||typeof t!="object")return{valid:!1,errors:["Definition must be a non-null object"]};let n=t;if((typeof n.name!="string"||n.name.length===0)&&e.push("Missing or empty 'name' field"),n.nodes==null||typeof n.nodes!="object"||Array.isArray(n.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e};let r=new Set(Object.keys(n.nodes));for(let[o,s]of Object.entries(n.nodes)){if(s==null||typeof s!="object"){e.push(`Node "${o}": must be an object`);continue}let a=s;if((typeof a.type!="string"||!fi.has(a.type))&&e.push(`Node "${o}": invalid type "${String(a.type)}" (expected: ${[...fi].join(", ")})`),Array.isArray(a.deps))for(let i of a.deps)typeof i=="string"&&!r.has(i)&&e.push(`Node "${o}": dep "${i}" does not reference an existing node`)}if(!Array.isArray(n.edges))n.edges!==void 0&&e.push("'edges' must be an array");else{let o=new Set;for(let s=0;s<n.edges.length;s++){let a=n.edges[s];if(a==null||typeof a!="object"){e.push(`Edge [${s}]: must be an object`);continue}let i=a;(typeof i.from!="string"||!r.has(i.from))&&e.push(`Edge [${s}]: 'from' "${String(i.from)}" does not reference an existing node`),(typeof i.to!="string"||!r.has(i.to))&&e.push(`Edge [${s}]: 'to' "${String(i.to)}" does not reference an existing node`);let d=`${i.from}->${i.to}`;o.has(d)&&e.push(`Edge [${s}]: duplicate edge ${d}`),o.add(d)}}return{valid:e.length===0,errors:e}}0&&(module.exports={AgentLoopGraph,AllTiersExhaustedError,BudgetExhaustedError,ChatStreamGraph,CircuitOpenError,DEFAULT_DECAY_RATE,FallbackMissError,LLMTimeoutError,ReplayCacheMissError,ToolRegistryGraph,admissionFilter3D,admissionScored,agentLoop,agentMemory,anthropicAdapter,canonicalJson,cascadingLlmAdapter,chatStream,composePricing,computePrice,contentGate,costMeterExtractor,createAdapter,createCapabilitiesRegistry,createPricingRegistry,dryRunAdapter,fallbackAdapter,frozenContext,gatedStream,gaugesAsContext,googleAdapter,graphFromSpec,graphFromSpecReactive,handoff,keywordFlagExtractor,knobsAsTools,llmConsolidator,llmExtractor,memoryRetrieval,memoryWithKG,memoryWithTiers,memoryWithVectors,observableAdapter,openAICompatAdapter,parseRateLimitFromError,pricingFor,promptCall,promptNode,redactor,registryPricing,resilientAdapter,streamExtractor,streamingPromptNode,suggestStrategy,suggestStrategyReactive,systemPromptBuilder,tier,toolCallExtractor,toolExecution,toolRegistry,toolSelector,validateGraphDef,withBreaker,withBudgetGate,withDryRun,withRateLimiter,withReplayCache,withRetry,withTimeout,zeroPrice});