@graphrefly/graphrefly 0.28.0 → 0.30.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 (284) hide show
  1. package/dist/{cascading-D9WG1-9L.d.ts → cascading-BszPheHD.d.ts} +1 -1
  2. package/dist/{cascading-B-5zmAUv.d.cts → cascading-dNCtjW8j.d.cts} +1 -1
  3. package/dist/{chunk-OAWLCNJJ.js → chunk-2GQREQ6C.js} +1 -1
  4. package/dist/{chunk-DBGGMN3D.js → chunk-33FA6V4B.js} +1 -1
  5. package/dist/chunk-3NEPQO2E.js +43 -0
  6. package/dist/{chunk-UWJE5FQA.js → chunk-4C2OR2GH.js} +11 -11
  7. package/dist/chunk-4JJCCD5S.js +2 -0
  8. package/dist/{chunk-GHJJR5P4.js → chunk-4OFIQ66T.js} +1 -1
  9. package/dist/{chunk-PIOGHC63.js → chunk-567NWZ3T.js} +1 -1
  10. package/dist/chunk-5JDE5JHE.js +1 -0
  11. package/dist/{chunk-ETWTCCJI.js → chunk-5Z4HDCO6.js} +1 -1
  12. package/dist/{chunk-Y2EMPB3I.js → chunk-73Z3W2RN.js} +1 -1
  13. package/dist/{chunk-CRXTH3SH.js → chunk-7JDLFI6N.js} +1 -1
  14. package/dist/{chunk-DQA3UIQ2.js → chunk-7TDOES3L.js} +1 -1
  15. package/dist/{chunk-LBTDSCCO.js → chunk-AMBYCIOH.js} +1 -1
  16. package/dist/{chunk-D7A7DBE4.js → chunk-AUY2YKCO.js} +1 -1
  17. package/dist/{chunk-FNYWM6JC.js → chunk-AV3PIDFQ.js} +1 -1
  18. package/dist/{chunk-UMBIDLJ4.js → chunk-BA5URFYW.js} +1 -1
  19. package/dist/chunk-BKPLTBL5.js +1 -0
  20. package/dist/{chunk-UPXUCFMX.js → chunk-BZP5T4X6.js} +1 -1
  21. package/dist/{chunk-WQ2BN6X6.js → chunk-DDPYNMGG.js} +1 -1
  22. package/dist/{chunk-LQ3Y5NJS.js → chunk-GJR3P6JG.js} +1 -1
  23. package/dist/{chunk-3R5HFPX7.js → chunk-GLSM33ZM.js} +1 -1
  24. package/dist/{chunk-2FOAM3OR.js → chunk-GNCBXARM.js} +1 -1
  25. package/dist/{chunk-K2GNMCQT.js → chunk-ISCENNXS.js} +1 -1
  26. package/dist/{chunk-UPHHLMHE.js → chunk-IUK4EFCE.js} +1 -1
  27. package/dist/{chunk-ERLIRFPA.js → chunk-KA6MMXIY.js} +1 -1
  28. package/dist/{chunk-2PMCKKRK.js → chunk-KASHOCF5.js} +1 -1
  29. package/dist/chunk-LI3E75VE.js +64 -0
  30. package/dist/chunk-MGKAO4EK.js +7 -0
  31. package/dist/{chunk-ZV2DXV5A.js → chunk-NSG4C6BF.js} +1 -1
  32. package/dist/{chunk-4GKB4OUJ.js → chunk-OL33ZI6R.js} +1 -1
  33. package/dist/{chunk-76A3HVQE.js → chunk-P7JXGKDO.js} +1 -1
  34. package/dist/{chunk-U3AICJKU.js → chunk-RD52SNH2.js} +1 -1
  35. package/dist/{chunk-CWLN3X3N.js → chunk-SHYH5SXV.js} +1 -1
  36. package/dist/{chunk-VTPVOGHH.js → chunk-SLMYTGTU.js} +1 -1
  37. package/dist/{chunk-OYHGKYQM.js → chunk-T5SHIKJD.js} +1 -1
  38. package/dist/{chunk-VPYBOXVT.js → chunk-TWMEGG45.js} +1 -1
  39. package/dist/chunk-VIEUJSTT.js +1 -0
  40. package/dist/{chunk-SC3U7ETD.js → chunk-VWPRPPKR.js} +1 -1
  41. package/dist/chunk-W4TSQ6RJ.js +1 -0
  42. package/dist/{chunk-OBKQQA5I.js → chunk-WANIEEKV.js} +1 -1
  43. package/dist/{chunk-XAUNPIMX.js → chunk-XHVB6G6M.js} +1 -1
  44. package/dist/{chunk-MIQTDPY4.js → chunk-XQAXYVXX.js} +1 -1
  45. package/dist/{chunk-MTTAAPCK.js → chunk-Y32RJO24.js} +1 -1
  46. package/dist/{chunk-S35VARIR.js → chunk-Y36UZ5VS.js} +1 -1
  47. package/dist/compat/index.cjs +13 -12
  48. package/dist/compat/index.d.cts +14 -14
  49. package/dist/compat/index.d.ts +14 -14
  50. package/dist/compat/index.js +1 -1
  51. package/dist/compat/jotai/index.cjs +1 -1
  52. package/dist/compat/jotai/index.d.cts +2 -2
  53. package/dist/compat/jotai/index.d.ts +2 -2
  54. package/dist/compat/jotai/index.js +1 -1
  55. package/dist/compat/nanostores/index.cjs +1 -1
  56. package/dist/compat/nanostores/index.d.cts +2 -2
  57. package/dist/compat/nanostores/index.d.ts +2 -2
  58. package/dist/compat/nanostores/index.js +1 -1
  59. package/dist/compat/nestjs/index.cjs +13 -12
  60. package/dist/compat/nestjs/index.d.cts +6 -6
  61. package/dist/compat/nestjs/index.d.ts +6 -6
  62. package/dist/compat/nestjs/index.js +1 -1
  63. package/dist/compat/react/index.d.cts +2 -2
  64. package/dist/compat/react/index.d.ts +2 -2
  65. package/dist/compat/solid/index.d.cts +2 -2
  66. package/dist/compat/solid/index.d.ts +2 -2
  67. package/dist/compat/svelte/index.d.cts +2 -2
  68. package/dist/compat/svelte/index.d.ts +2 -2
  69. package/dist/compat/vue/index.d.cts +2 -2
  70. package/dist/compat/vue/index.d.ts +2 -2
  71. package/dist/compat/zustand/index.cjs +7 -6
  72. package/dist/compat/zustand/index.d.cts +4 -4
  73. package/dist/compat/zustand/index.d.ts +4 -4
  74. package/dist/compat/zustand/index.js +1 -1
  75. package/dist/{composite-BhbKHbOS.d.ts → composite-DGspwCqk.d.ts} +2 -2
  76. package/dist/{composite-B-xqw4Kk.d.cts → composite-nrRumJ7l.d.cts} +2 -2
  77. package/dist/core/index.cjs +1 -1
  78. package/dist/core/index.d.cts +4 -4
  79. package/dist/core/index.d.ts +4 -4
  80. package/dist/core/index.js +1 -1
  81. package/dist/extra/browser.cjs +1 -1
  82. package/dist/extra/browser.d.cts +1 -1
  83. package/dist/extra/browser.d.ts +1 -1
  84. package/dist/extra/browser.js +1 -1
  85. package/dist/extra/index.cjs +20 -19
  86. package/dist/extra/index.d.cts +9 -9
  87. package/dist/extra/index.d.ts +9 -9
  88. package/dist/extra/index.js +1 -1
  89. package/dist/extra/node.cjs +3 -3
  90. package/dist/extra/node.d.cts +1 -1
  91. package/dist/extra/node.d.ts +1 -1
  92. package/dist/extra/node.js +1 -1
  93. package/dist/extra/operators.cjs +1 -1
  94. package/dist/extra/operators.d.cts +1 -1
  95. package/dist/extra/operators.d.ts +1 -1
  96. package/dist/extra/operators.js +1 -1
  97. package/dist/extra/reactive.cjs +1 -1
  98. package/dist/extra/reactive.d.cts +3 -3
  99. package/dist/extra/reactive.d.ts +3 -3
  100. package/dist/extra/reactive.js +1 -1
  101. package/dist/extra/sources.cjs +1 -1
  102. package/dist/extra/sources.d.cts +1 -1
  103. package/dist/extra/sources.d.ts +1 -1
  104. package/dist/extra/sources.js +1 -1
  105. package/dist/extra/storage-browser.cjs +1 -1
  106. package/dist/extra/storage-browser.d.cts +1 -1
  107. package/dist/extra/storage-browser.d.ts +1 -1
  108. package/dist/extra/storage-browser.js +1 -1
  109. package/dist/graph/index.cjs +7 -6
  110. package/dist/graph/index.d.cts +5 -5
  111. package/dist/graph/index.d.ts +5 -5
  112. package/dist/graph/index.js +1 -1
  113. package/dist/{graph-D48Qw9Cg.d.cts → graph-C4Uxwv0T.d.cts} +22 -6
  114. package/dist/{graph-BZGRXwOm.d.ts → graph-CWeI0aHd.d.ts} +22 -6
  115. package/dist/{index-u15meRxL.d.cts → index-9iguV3bF.d.cts} +2 -2
  116. package/dist/{index-DyxjtScX.d.cts → index-B-z8WaSd.d.cts} +2 -2
  117. package/dist/{index-BgyGlizc.d.ts → index-B2HBxvMb.d.ts} +4 -4
  118. package/dist/{index-CzobVSMr.d.ts → index-B5iVOD7w.d.ts} +2 -2
  119. package/dist/{index-rX8HBM5h.d.cts → index-B8Aj_z8S.d.cts} +2 -2
  120. package/dist/{index-D-YB-Vl3.d.ts → index-BANwzwBV.d.ts} +3 -3
  121. package/dist/{index-HDpJe9hX.d.ts → index-BBINVimG.d.ts} +3 -3
  122. package/dist/{index-8FSVk4Uf.d.ts → index-BEpRsvhg.d.ts} +4 -4
  123. package/dist/{index-CHEswufn.d.cts → index-BHu_Wba0.d.cts} +4 -4
  124. package/dist/{index-ZftwfxJM.d.ts → index-BJHQUCZx.d.ts} +7 -7
  125. package/dist/{index-DUqMOlKZ.d.cts → index-BS220yqj.d.cts} +7 -7
  126. package/dist/{index-BWJV63ti.d.ts → index-BX22kvjh.d.ts} +1 -1
  127. package/dist/{index-DfyOkTvs.d.ts → index-BXbQUn4n.d.ts} +2 -2
  128. package/dist/{index-O6TgGUBV.d.cts → index-BpFWP7Bq.d.cts} +3 -3
  129. package/dist/{index-BxJ86YZZ.d.cts → index-Bs3-LC83.d.cts} +3 -3
  130. package/dist/{index-DiOXyAwt.d.ts → index-Bvi5uJxX.d.ts} +1 -1
  131. package/dist/{index-Bqachn9_.d.ts → index-ByPnK85n.d.ts} +1 -1
  132. package/dist/{index-CRO83MmV.d.cts → index-BydMDMf7.d.cts} +1 -1
  133. package/dist/{index-ROpQmGjE.d.ts → index-C5Ghnp5B.d.ts} +3 -3
  134. package/dist/{index-umtoWT8K.d.ts → index-C6NBfXj-.d.ts} +6 -5
  135. package/dist/{index-pXrDMpRO.d.cts → index-C98oJsEs.d.cts} +2 -2
  136. package/dist/{index-B2pwesl9.d.cts → index-CDK5RsV5.d.cts} +1 -1
  137. package/dist/{index-Czq6ynh8.d.ts → index-CFW32Dy1.d.ts} +3 -3
  138. package/dist/{index-Cyojz0AE.d.cts → index-CIXaiYDE.d.cts} +1 -1
  139. package/dist/{index-Oi8d8w4R.d.cts → index-CRAkoq-y.d.cts} +1 -1
  140. package/dist/{index-CpgYhnrG.d.ts → index-Cc8VQIgL.d.ts} +2 -2
  141. package/dist/{index-vscRDkjW.d.cts → index-CcpEvuPl.d.cts} +2 -2
  142. package/dist/{index-BpA5c4G9.d.ts → index-CfFYyLR8.d.ts} +4 -4
  143. package/dist/{index-9oDeHH2u.d.cts → index-ClB7TCfL.d.cts} +2 -2
  144. package/dist/{index-BHvIquRZ.d.ts → index-ClgKmOHe.d.ts} +592 -492
  145. package/dist/{index-DpHe5e0Q.d.ts → index-CotRMjtJ.d.ts} +2 -2
  146. package/dist/{index-B1AmmSlb.d.ts → index-CrC7urhX.d.ts} +1 -1
  147. package/dist/{index-B0c4cmIO.d.ts → index-CvS9IuTG.d.ts} +2 -2
  148. package/dist/{index-rHJSKsU8.d.cts → index-Cy7eFeIX.d.cts} +2 -2
  149. package/dist/{index-BVHOrDwO.d.ts → index-D0C_USMR.d.ts} +1 -1
  150. package/dist/{index-DEwTb_fm.d.cts → index-D6ajK8Mh.d.cts} +592 -492
  151. package/dist/{index-DL-rYJrx.d.cts → index-D7XxY1Ff.d.cts} +1 -1
  152. package/dist/{index-DAlweici.d.ts → index-D9HrBx2J.d.ts} +2 -2
  153. package/dist/{index-fM6y00vT.d.cts → index-D9Y_u6BG.d.cts} +3 -3
  154. package/dist/{index-DcXZBF5a.d.cts → index-DBQUKh59.d.cts} +4 -4
  155. package/dist/{index-D_NwnRYS.d.cts → index-DDo-eqQ4.d.cts} +1 -1
  156. package/dist/{index-m-yHof5p.d.ts → index-DGb1awva.d.ts} +4 -4
  157. package/dist/{index-DxsnAMWD.d.cts → index-DR3gf_DG.d.cts} +9 -9
  158. package/dist/{index-dtN7YA2x.d.cts → index-DVNLe3pS.d.cts} +3 -3
  159. package/dist/{index-Btib9rsU.d.ts → index-Dljd76bC.d.ts} +275 -9
  160. package/dist/{index-DP4ZTkdw.d.ts → index-DnrZghBB.d.ts} +3 -3
  161. package/dist/{index-DaLJvH8Z.d.ts → index-Docdiu9a.d.ts} +3 -3
  162. package/dist/{index-BpIFjILY.d.cts → index-DylQCKEL.d.cts} +4 -4
  163. package/dist/{index-B_agccPe.d.cts → index-FBqTfL_S.d.cts} +1 -1
  164. package/dist/{index-DraikLjn.d.ts → index-FrYrV-Vf.d.ts} +2 -2
  165. package/dist/{index-sm373fsH.d.ts → index-IZ3l_vQ9.d.ts} +2 -2
  166. package/dist/{index-BwM9BEkt.d.ts → index-Ip3q9T9x.d.ts} +1 -1
  167. package/dist/{index-CloUk1kY.d.ts → index-RQg6lTrN.d.ts} +9 -9
  168. package/dist/{index-CEXXwWVH.d.cts → index-SSGqF8mI.d.cts} +2 -2
  169. package/dist/{index-rnwQly8X.d.cts → index-UZO988ox.d.cts} +6 -5
  170. package/dist/{index-C73n7lo-.d.cts → index-iBp74eGU.d.cts} +3 -3
  171. package/dist/{index-tbf2gKHd.d.cts → index-lKuLYmHO.d.cts} +3 -3
  172. package/dist/{index-CMn8S8Hw.d.ts → index-wIx1Jisk.d.ts} +1 -1
  173. package/dist/{index-cByzxQIC.d.cts → index-yIdWFo2b.d.cts} +4 -4
  174. package/dist/{index-RukJ4DLS.d.cts → index-ybtSyjWB.d.cts} +275 -9
  175. package/dist/index.cjs +53 -52
  176. package/dist/index.d.cts +42 -42
  177. package/dist/index.d.ts +42 -42
  178. package/dist/index.js +1 -1
  179. package/dist/{meta-CwesDrMD.d.ts → meta-BMwx3ExI.d.ts} +1 -1
  180. package/dist/{meta-Cgj6zeji.d.cts → meta-COtmHLwT.d.cts} +1 -1
  181. package/dist/{node-Cc1TniY8.d.ts → node-BVV7G1bq.d.cts} +59 -2
  182. package/dist/{node-Cc1TniY8.d.cts → node-BVV7G1bq.d.ts} +59 -2
  183. package/dist/{observable-glXQoGj2.d.cts → observable-BrUAPeH_.d.cts} +1 -1
  184. package/dist/{observable-Ct-gJ9jI.d.ts → observable-ITikPXz3.d.ts} +1 -1
  185. package/dist/patterns/ai/browser.d.cts +3 -3
  186. package/dist/patterns/ai/browser.d.ts +3 -3
  187. package/dist/patterns/ai/browser.js +1 -1
  188. package/dist/patterns/ai/index.cjs +25 -24
  189. package/dist/patterns/ai/index.d.cts +15 -15
  190. package/dist/patterns/ai/index.d.ts +15 -15
  191. package/dist/patterns/ai/index.js +1 -1
  192. package/dist/patterns/ai/node.d.cts +1 -1
  193. package/dist/patterns/ai/node.d.ts +1 -1
  194. package/dist/patterns/ai/node.js +1 -1
  195. package/dist/patterns/audit/index.cjs +7 -6
  196. package/dist/patterns/audit/index.d.cts +5 -5
  197. package/dist/patterns/audit/index.d.ts +5 -5
  198. package/dist/patterns/audit/index.js +1 -1
  199. package/dist/patterns/cqrs/index.cjs +7 -6
  200. package/dist/patterns/cqrs/index.d.cts +4 -4
  201. package/dist/patterns/cqrs/index.d.ts +4 -4
  202. package/dist/patterns/cqrs/index.js +1 -1
  203. package/dist/patterns/demo-shell/index.cjs +8 -7
  204. package/dist/patterns/demo-shell/index.d.cts +5 -5
  205. package/dist/patterns/demo-shell/index.d.ts +5 -5
  206. package/dist/patterns/demo-shell/index.js +1 -1
  207. package/dist/patterns/domain-templates/index.cjs +7 -6
  208. package/dist/patterns/domain-templates/index.d.cts +4 -4
  209. package/dist/patterns/domain-templates/index.d.ts +4 -4
  210. package/dist/patterns/domain-templates/index.js +1 -1
  211. package/dist/patterns/graphspec/index.cjs +26 -25
  212. package/dist/patterns/graphspec/index.d.cts +4 -4
  213. package/dist/patterns/graphspec/index.d.ts +4 -4
  214. package/dist/patterns/graphspec/index.js +1 -1
  215. package/dist/patterns/guarded-execution/index.cjs +7 -6
  216. package/dist/patterns/guarded-execution/index.d.cts +6 -6
  217. package/dist/patterns/guarded-execution/index.d.ts +6 -6
  218. package/dist/patterns/guarded-execution/index.js +1 -1
  219. package/dist/patterns/harness/index.cjs +11 -10
  220. package/dist/patterns/harness/index.d.cts +10 -7
  221. package/dist/patterns/harness/index.d.ts +10 -7
  222. package/dist/patterns/harness/index.js +1 -1
  223. package/dist/patterns/job-queue/index.cjs +7 -6
  224. package/dist/patterns/job-queue/index.d.cts +4 -4
  225. package/dist/patterns/job-queue/index.d.ts +4 -4
  226. package/dist/patterns/job-queue/index.js +1 -1
  227. package/dist/patterns/lens/index.cjs +7 -6
  228. package/dist/patterns/lens/index.d.cts +6 -6
  229. package/dist/patterns/lens/index.d.ts +6 -6
  230. package/dist/patterns/lens/index.js +1 -1
  231. package/dist/patterns/memory/index.cjs +7 -6
  232. package/dist/patterns/memory/index.d.cts +4 -4
  233. package/dist/patterns/memory/index.d.ts +4 -4
  234. package/dist/patterns/memory/index.js +1 -1
  235. package/dist/patterns/messaging/index.cjs +7 -6
  236. package/dist/patterns/messaging/index.d.cts +4 -4
  237. package/dist/patterns/messaging/index.d.ts +4 -4
  238. package/dist/patterns/messaging/index.js +1 -1
  239. package/dist/patterns/orchestration/index.cjs +7 -6
  240. package/dist/patterns/orchestration/index.d.cts +5 -5
  241. package/dist/patterns/orchestration/index.d.ts +5 -5
  242. package/dist/patterns/orchestration/index.js +1 -1
  243. package/dist/patterns/reactive-layout/index.cjs +8 -7
  244. package/dist/patterns/reactive-layout/index.d.cts +5 -5
  245. package/dist/patterns/reactive-layout/index.d.ts +5 -5
  246. package/dist/patterns/reactive-layout/index.js +1 -1
  247. package/dist/patterns/reduction/index.cjs +7 -6
  248. package/dist/patterns/reduction/index.d.cts +4 -4
  249. package/dist/patterns/reduction/index.d.ts +4 -4
  250. package/dist/patterns/reduction/index.js +1 -1
  251. package/dist/patterns/refine-loop/index.cjs +9 -8
  252. package/dist/patterns/refine-loop/index.d.cts +5 -5
  253. package/dist/patterns/refine-loop/index.d.ts +5 -5
  254. package/dist/patterns/refine-loop/index.js +1 -1
  255. package/dist/patterns/resilient-pipeline/index.cjs +1 -1
  256. package/dist/patterns/resilient-pipeline/index.d.cts +6 -6
  257. package/dist/patterns/resilient-pipeline/index.d.ts +6 -6
  258. package/dist/patterns/resilient-pipeline/index.js +1 -1
  259. package/dist/patterns/surface/index.cjs +14 -13
  260. package/dist/patterns/surface/index.d.cts +5 -5
  261. package/dist/patterns/surface/index.d.ts +5 -5
  262. package/dist/patterns/surface/index.js +1 -1
  263. package/dist/{reactive-layout-CpYb5qLP.d.cts → reactive-layout-5oEn8lHM.d.cts} +2 -2
  264. package/dist/{reactive-layout-D8u4wuUR.d.ts → reactive-layout-BAr6-_o5.d.ts} +2 -2
  265. package/dist/{reactive-log-DPzuUDj5.d.cts → reactive-log-5jFeNRmd.d.cts} +1 -1
  266. package/dist/{reactive-log-YuH9VYN8.d.ts → reactive-log-BOJDCI5x.d.ts} +1 -1
  267. package/dist/{reactive-map-CdbNoSgP.d.ts → reactive-map-BvDrRuwt.d.ts} +1 -1
  268. package/dist/{reactive-map-DUeRmb9d.d.cts → reactive-map-CmlPPKHN.d.cts} +1 -1
  269. package/dist/{resilience-CGRzhnD3.d.ts → resilience-CludlzcP.d.ts} +1 -1
  270. package/dist/{resilience-Ba5-b4WD.d.cts → resilience-Q6Bt_7y0.d.cts} +1 -1
  271. package/dist/{resilience-QAHKANT5.js → resilience-XRUF267O.js} +1 -1
  272. package/dist/{sugar-BV0htudb.d.cts → sugar-BHbAACDG.d.ts} +10 -12
  273. package/dist/{sugar-Dtyrq2_q.d.ts → sugar-CqR6DJ7v.d.cts} +10 -12
  274. package/dist/{topology-tree-DROUdq5B.d.cts → topology-tree-CVREibAc.d.cts} +1 -1
  275. package/dist/{topology-tree-CYHOwQZ_.d.ts → topology-tree-CkjojcB6.d.ts} +1 -1
  276. package/package.json +1 -1
  277. package/dist/chunk-6V3SEX2I.js +0 -1
  278. package/dist/chunk-7H6LGFUG.js +0 -64
  279. package/dist/chunk-CKCSDI7T.js +0 -6
  280. package/dist/chunk-QWAPKG3O.js +0 -2
  281. package/dist/chunk-RHESUC3V.js +0 -43
  282. package/dist/chunk-V6YQICXZ.js +0 -1
  283. package/dist/chunk-Z4HDAS2Q.js +0 -1
  284. package/dist/chunk-ZB5EHBIO.js +0 -1
package/dist/index.cjs CHANGED
@@ -1,59 +1,60 @@
1
- "use strict";var rp=Object.create;var yn=Object.defineProperty;var Xa=Object.getOwnPropertyDescriptor;var op=Object.getOwnPropertyNames;var sp=Object.prototype.hasOwnProperty;var Za=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),Yn=t=>{throw TypeError(t)};var ip=(t,e,n)=>e in t?yn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Ja=(t,e)=>yn(t,"name",{value:e,configurable:!0});var We=(t,e)=>()=>(t&&(e=t(t=0)),e);var he=(t,e)=>{for(var n in e)yn(t,n,{get:e[n],enumerable:!0})},ap=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of op(e))!sp.call(t,o)&&o!==n&&yn(t,o,{get:()=>e[o],enumerable:!(r=Xa(e,o))||r.enumerable});return t};var up=t=>ap(yn({},"__esModule",{value:!0}),t);var eu=t=>[,,,rp(t?.[Za("metadata")]??null)],tu=["class","method","getter","setter","accessor","field","value","get","set"],Jn=t=>t!==void 0&&typeof t!="function"?Yn("Function expected"):t,cp=(t,e,n,r,o)=>({kind:tu[t],name:e,metadata:r,addInitializer:s=>n._?Yn("Already initialized"):o.push(Jn(s||null))}),dp=(t,e)=>ip(e,Za("metadata"),t[3]),nu=(t,e,n,r)=>{for(var o=0,s=t[e>>1],i=s&&s.length;o<i;o++)e&1?s[o].call(n):r=s[o].call(n,r);return r},ru=(t,e,n,r,o,s)=>{var i,a,u,c,d,l=e&7,f=!!(e&8),p=!!(e&16),m=l>3?t.length+1:l?f?1:2:0,h=tu[l+5],g=l>3&&(t[m-1]=[]),y=t[m]||(t[m]=[]),b=l&&(!p&&!f&&(o=o.prototype),l<5&&(l>3||!p)&&Xa(l<4?o:{get[n](){return Ya(this,s)},set[n](T){return Qa(this,s,T)}},n));l?p&&l<4&&Ja(s,(l>2?"set ":l>1?"get ":"")+n):Ja(o,n);for(var v=r.length-1;v>=0;v--)c=cp(l,n,u={},t[3],y),l&&(c.static=f,c.private=p,d=c.access={has:p?T=>lp(o,T):T=>n in T},l^3&&(d.get=p?T=>(l^1?Ya:pp)(T,o,l^4?s:b.get):T=>T[n]),l>2&&(d.set=p?(T,w)=>Qa(T,o,w,l^4?s:b.set):(T,w)=>T[n]=w)),a=(0,r[v])(l?l<4?p?s:b[h]:l>4?void 0:{get:b.get,set:b.set}:o,c),u._=1,l^4||a===void 0?Jn(a)&&(l>4?g.unshift(a):l?p?s=a:b[h]=a:o=a):typeof a!="object"||a===null?Yn("Object expected"):(Jn(i=a.get)&&(b.get=i),Jn(i=a.set)&&(b.set=i),Jn(i=a.init)&&g.unshift(i));return l||dp(t,o),b&&yn(o,n,b),p?l^4?s:b:o};var Zs=(t,e,n)=>e.has(t)||Yn("Cannot "+n),lp=(t,e)=>Object(e)!==e?Yn('Cannot use the "in" operator on this value'):t.has(e),Ya=(t,e,n)=>(Zs(t,e,"read from private field"),n?n.call(t):e.get(t));var Qa=(t,e,n,r)=>(Zs(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),pp=(t,e,n)=>(Zs(t,e,"access private method"),n);var ct,R,Z,$,Ve,Ae,Pe,de,M,O,gt,bn,Jr,vn,Yr,Qr,Tn,Qn,Xn,Zn,wn,ie=We(()=>{"use strict";ct=Symbol.for("graphrefly/START"),R=Symbol.for("graphrefly/DATA"),Z=Symbol.for("graphrefly/DIRTY"),$=Symbol.for("graphrefly/RESOLVED"),Ve=Symbol.for("graphrefly/INVALIDATE"),Ae=Symbol.for("graphrefly/PAUSE"),Pe=Symbol.for("graphrefly/RESUME"),de=Symbol.for("graphrefly/TEARDOWN"),M=Symbol.for("graphrefly/COMPLETE"),O=Symbol.for("graphrefly/ERROR"),gt=Object.freeze([Z]),bn=Object.freeze([$]),Jr=Object.freeze([Ve]),vn=Object.freeze([ct]),Yr=Object.freeze([M]),Qr=Object.freeze([de]),Tn=Object.freeze([gt]),Qn=Object.freeze([bn]),Xn=Object.freeze([Jr]),Zn=Object.freeze([Yr]),wn=Object.freeze([Qr])});function ei(t){return{name:"dag-cbor",version:1,contentType:"application/dag-cbor",encode:e=>t.encode(e),decode:(e,n)=>t.decode(e)}}function ti(t,e){return{name:"dag-cbor-zstd",version:1,contentType:"application/dag-cbor+zstd",encode:n=>e.compressSync(t.encode(n)),decode:(n,r)=>t.decode(e.decompressSync(n))}}function er(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),i=0;return s[i++]=kn,s[i++]=n.length,s.set(n,i),i+=n.length,s[i++]=r>>>8&255,s[i++]=r&255,s.set(e,i),s}function tr(t,e){if(t.length<ou)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${ou})`);let n=0,r=t[n++];if(r!==kn)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${kn})`);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 i=(t[n]<<8|t[n+1])>>>0;n+=2;let a=t.subarray(n),u=e.lookupCodec(s);if(u==null)throw new Error(`decodeEnvelope: codec "${s}" not registered (envelope codec_v=${i})`);return{codec:u,codecVersion:i,payload:a}}function nr(t){t.registerCodec(Xr)}function ni(t){if(t.length===0)throw new Error("WAL is empty \u2014 need at least one full snapshot");let e=t[0];if(e.mode!=="full")throw new Error("WAL must start with a full record carrying a baseline snapshot");let n=JSON.parse(JSON.stringify(e.snapshot)),r=e.seq;for(let o=1;o<t.length;o++){let s=t[o];if(s.seq<=r)throw new Error(`WAL chain broken at index ${o}: seq=${s.seq} must exceed prev seq=${r}`);if(s.mode==="full"){n=JSON.parse(JSON.stringify(s.snapshot)),r=s.seq;continue}let i=s.diff;for(let u of i.nodesRemoved)delete n.nodes[u];let a=i.nodesAddedFull;if(a!=null)for(let[u,c]of Object.entries(a))n.nodes[u]=JSON.parse(JSON.stringify(c));for(let u of i.nodesChanged){let c=n.nodes[u.path];c!=null&&(c[u.field]=u.to)}r=s.seq}return n}var Xr,kn,ou,Zr=We(()=>{"use strict";Xr={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)}};kn=1,ou=4});function yt(t){if(t==null)return dt;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var dt,rr=We(()=>{"use strict";dt={type:"system",id:""}});function Wt(){return xn>0||or}function su(){return xn>0}function ir(t){xn>0?sr.push(t):t()}function ee(t){xn+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(xn-=1,xn===0)if(e){if(!or){let n=sr.splice(0);for(let r of n)try{r()}catch{}qt.length=0,Ht.length=0,Rn.length=0}}else fp()}}function fp(){let t=!or;t&&(or=!0);let e=[],n=0;try{for(;qt.length>0||Ht.length>0||Rn.length>0||t&&sr.length>0;){if(t&&sr.length>0){let s=sr.splice(0);for(let i of s)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw qt.length=0,Ht.length=0,Rn.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let o=(qt.length>0?qt:Ht.length>0?Ht:Rn).splice(0);for(let s of o)try{s()}catch(i){e.push(i)}}}finally{t&&(or=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function bt(t,e,n){if(e.length===0)return;if(e.length===1){let c=n(e[0][0]);if(c<3||!Wt()){t(e);return}(c>=5?Rn:c===4?Ht:qt).push(()=>t(e));return}let r=e.length,o=r,s=r,i=r,a=0;for(;a<r&&n(e[a][0])<3;)a++;for(o=a;a<r&&n(e[a][0])===3;)a++;for(s=a;a<r&&n(e[a][0])===4;)a++;i=a;let u=Wt();if(o>0){let c=e.slice(0,o);t(c)}if(s>o){let c=e.slice(o,s);u?qt.push(()=>t(c)):t(c)}if(i>s){let c=e.slice(s,i);u?Ht.push(()=>t(c)):t(c)}if(r>i){let c=e.slice(i,r);u?Rn.push(()=>t(c)):t(c)}}var xn,or,qt,Ht,Rn,sr,Se=We(()=>{"use strict";xn=0,or=!1,qt=[],Ht=[],Rn=[],sr=[]});function B(){return Math.trunc(performance.now()*1e6)}function pe(){return Date.now()*1e6}var Te=We(()=>{"use strict"});function ar(t){t.registerMessageType(ct,{tier:0,wireCrossing:!1}),t.registerMessageType(Z,{tier:1,wireCrossing:!1}),t.registerMessageType(Ve,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(Ae,{tier:2,wireCrossing:!1}),t.registerMessageType(Pe,{tier:2,wireCrossing:!1}),t.registerMessageType(R,{tier:3,wireCrossing:!0}),t.registerMessageType($,{tier:3,wireCrossing:!0}),t.registerMessageType(M,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(O,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(de,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var Ut,ri=We(()=>{"use strict";ie();Ut=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=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}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 iu(t){return Array.isArray(t)?[...t]:[t]}function mp(t,e){return t.has(e)||t.has("*")}function zt(t){let e=[];return t((o,s)=>{e.push({kind:"allow",actions:new Set(iu(o)),where:s?.where??(()=>!0)})},(o,s)=>{e.push({kind:"deny",actions:new Set(iu(o)),where:s?.where??(()=>!0)})}),(o,s)=>{let i=!1,a=!1;for(let u of e)mp(u.actions,s)&&u.where(o)&&(u.kind==="deny"?i=!0:a=!0);return i?!1:a}}function ur(t){return zt((e,n)=>{for(let r of t){let o=r.actorType==null?null:new Set(Array.isArray(r.actorType)?r.actorType:[r.actorType]),s=r.actorId==null?null:new Set(Array.isArray(r.actorId)?r.actorId:[r.actorId]),i=Object.entries(r.claims??{}),a=u=>{if(o!==null&&!o.has(String(u.type))||s!==null&&!s.has(String(u.id??"")))return!1;for(let[c,d]of i)if(u[c]!==d)return!1;return!0};r.effect==="deny"?n(r.action,{where:a}):e(r.action,{where:a})}})}function cr(t){let e=hp.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 Je,hp,Jt=We(()=>{"use strict";Je=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}};hp=["human","llm","wallet","system"]});function oi(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(oi);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=oi(t[n]);return e}return null}function bp(t){let e=yp.encode(t),n=e.length,r=n*8,o=n+9+63&-64,s=new Uint8Array(o);s.set(e),s[n]=128;let i=new DataView(s.buffer);i.setUint32(o-4,r>>>0,!1),i.setUint32(o-8,Math.floor(r/4294967296)>>>0,!1);let a=1779033703,u=3144134277,c=1013904242,d=2773480762,l=1359893119,f=2600822924,p=528734635,m=1541459225,h=new Uint32Array(64),g=(b,v)=>b>>>v|b<<32-v;for(let b=0;b<o;b+=64){for(let L=0;L<16;L++)h[L]=i.getUint32(b+L*4,!1);for(let L=16;L<64;L++){let D=h[L-15],C=h[L-2],K=g(D,7)^g(D,18)^D>>>3,ne=g(C,17)^g(C,19)^C>>>10;h[L]=h[L-16]+K+h[L-7]+ne>>>0}let v=a,T=u,w=c,k=d,x=l,S=f,_=p,F=m;for(let L=0;L<64;L++){let D=g(x,6)^g(x,11)^g(x,25),C=x&S^~x&_,K=F+D+C+gp[L]+h[L]>>>0,ne=g(v,2)^g(v,13)^g(v,22),P=v&T^v&w^T&w,E=ne+P>>>0;F=_,_=S,S=x,x=k+K>>>0,k=w,w=T,T=v,v=K+E>>>0}a=a+v>>>0,u=u+T>>>0,c=c+w>>>0,d=d+k>>>0,l=l+x>>>0,f=f+S>>>0,p=p+_>>>0,m=m+F>>>0}let y=b=>b.toString(16).padStart(8,"0");return y(a)+y(u)+y(c)+y(d)+y(l)+y(f)+y(p)+y(m)}function Mt(t){let e=oi(t??null),n=JSON.stringify(e);return bp(n).slice(0,16)}function vp(){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 Sn(t,e,n){let r=n?.id??vp();if(t===0)return{id:r,version:0};let s=(n?.hash??Mt)(e);return{id:r,version:0,cid:s,prev:null}}function dr(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}function si(t){return"cid"in t}var gp,yp,eo=We(()=>{"use strict";gp=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]),yp=new TextEncoder});function cu(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function ii(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function to(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function ui(t){if(Me._isFrozen())throw new Error("configure() called after a node was created \u2014 the default GraphReFlyConfig is frozen. Call configure(...) at application startup, before any node factories run.");t(Me)}function q(t,e,n){let r=du(t)?t:[],o=typeof t=="function"?t:typeof e=="function"?e:void 0,s={};return du(t)?s=(ai(e)?e:n)??{}:ai(t)?s=t:s=(ai(e)?e:n)??{},new xe(r,o,s)}var au,uu,Tp,wp,Me,xe,du,ai,we=We(()=>{"use strict";Zr();rr();Se();Te();ri();Jt();ie();eo();au=()=>{},uu=100;Tp=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},wp=(t,e,n,r)=>{let o=t;if(o._status==="completed"||o._status==="errored")return;let s=o._cached,i=s===void 0?[vn]:[vn,[R,s]];o._status==="dirty"&&i.push(gt),bt(e,i,o._config.tierOf)},Me=new Ut({onMessage:Tp,onSubscribe:wp});ar(Me);nr(Me);xe=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;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,n,r){this._config=r.config??Me,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._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??Mt;let o=r.versioning??this._config.defaultVersioning;this._versioningLevel=o,this._versioning=o!=null?Sn(o,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(cu);let s={};for(let[a,u]of Object.entries(r.meta??{})){let c={initial:u,name:`${r.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};r.guard!=null&&(c.guard=r.guard),s[a]=new t([],void 0,c)}Object.freeze(s),this.meta=s,this._hasMeta=Object.keys(s).length>0;let i=this;this._actions={emit(a){i._emit([[R,a]])},down(a){i._emit(to(a))},up(a){i._emitUp(to(a))}},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,i=this._versioning,a=i?.id??n?.id,u=i?.version??0,c=Sn(e,s,{id:a,hash:o});c.version=u,this._versioning=c,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=yt(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=yt(e?.actor),s=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(o,s))throw new Je({actor:o,action:s,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(o,s))throw new Je({actor:o,action:s,nodeName:this.name})}this._lastMutation={actor:o,timestamp_ns:pe()}}down(e,n){let r=to(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[R,e]])}up(e,n){if(this._deps.length===0)return;let r=to(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 u=yt(n);if(!this._guard(u,"observe"))throw new Je({actor:u,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 u of this._deps)ii(u)}this._sinkCount+=1;let s;try{s=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:o},this._actions)}catch(u){throw this._sinkCount-=1,u}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let i=this._isTerminal;if(this._sinkCount===1&&!i)try{this._activate()}catch(u){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof s=="function")try{s()}catch{}throw u}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let a=!1;return()=>{a||(a=!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=au,s.unsub=s.node.subscribe(i=>{if(s.unsub===null)return;let a=this._config.tierOf,u=!1;for(let c of i)a(c[0])>=3&&(u=!0),this._config.onMessage(this,c,{direction:"down-in",depIndex:o},this._actions);u&&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 i=s.unsub;s.unsub=null;try{i()}catch{}ii(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=cu(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Tn),r.unsub=au;try{r.unsub=e.subscribe(o=>{if(r.unsub===null)return;let s=this._config.tierOf,i=!1;for(let a of o)s(a[0])>=3&&(i=!0),this._config.onMessage(this,a,{direction:"down-in",depIndex:n},this._actions);i&&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([[O,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([[O,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{}}ii(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 i of this._inspectorHooks)i(s)}if(o!==ct){if(o===Z){this._depDirtied(r);return}if(o===Ve){this._depInvalidated(r),this._emit(Xn);return}if(o===Ae||o===Pe){this._emit([n]);return}if(o===de){this._emit(wn);return}if(o===R)this._depSettledAsData(r,n[1]);else if(o===$)this._depSettledAsResolved(r);else if(o===M)this._depSettledAsTerminal(r,!0);else if(o===O)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(o===R||o===$)&&this._emit([n]),(o===M||o===O)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Tn))}_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._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(Qn),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([[O,e.terminal]]);return}this._autoComplete&&this._deps.every(n=>n.terminal!==void 0)&&this._emit(Zn)}_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(i){this._emit([[O,this._wrapFnError("cleanup threw",i)]]);return}}else if(e!=null&&typeof e=="object"){let i=e.beforeRun;if(typeof i=="function"){e.beforeRun=void 0;try{i()}catch(a){this._emit([[O,this._wrapFnError("cleanup.beforeRun threw",a)]]);return}}}let n=this._deps.map(i=>i.involvedThisWave?i.dataBatch.length>0?[...i.dataBatch]:[]:void 0),r=this._deps.map(i=>i.prevData);for(let i=0;i<this._deps.length;i++){let a=n[i];a!=null&&a.length>0&&(this._deps[i].prevData=a[a.length-1])}let o=this._deps.map(i=>i.terminal),s={prevData:r,terminalDeps:o,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let i={kind:"run",batchData:n,prevData:r};for(let a of this._inspectorHooks)a(i)}this._isExecutingFn=!0;try{let i=this._fn(n,this._actions,s);if(typeof i=="function")this._cleanup=i;else if(i!=null&&typeof i=="object"){let a=i;(typeof a.beforeRun=="function"||typeof a.deactivate=="function"||typeof a.invalidate=="function")&&(this._cleanup=i)}}catch(i){this._emit([[O,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>uu?(this._rerunDepth=0,this._emit([[O,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${uu} \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"?[gt,e[0]]:e;let r=!0,o=!1,s=!1,i=-1;for(let u of e){let c=n(u[0]);c<i&&(r=!1),c===3&&(o=!0),u[0]===Z&&(s=!0),i=c}let a=e;if(!r){let u=e.map((c,d)=>({m:c,i:d,tier:n(c[0])}));u.sort((c,d)=>c.tier-d.tier||c.i-d.i),a=u.map(c=>c.m)}if(o&&!s&&this._status!=="dirty"){let u=0;for(;u<a.length&&n(a[u][0])===0;)u++;return u===0?[gt,...a]:[...a.slice(0,u),gt,...a.slice(u)]}return a}_emit(e){if(e.length===0)return;let n=e;if(this._isTerminal&&!this._resubscribable){let a=e.filter(u=>u[0]===de||u[0]===Ve);if(a.length===0)return;n=a}n=this._frameBatch(n);let o=null;for(let a=0;a<n.length;a++){let u=n[a],c=u[0];if(c!==Ae&&c!==Pe){o?.push(u);continue}if(u.length<2)throw new Error(`Node "${this.name}": [[${c===Ae?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let d=!0;if(this._pausable!==!1){let l=u[1];if(c===Ae)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))d=!1;else if(this._pauseLocks.delete(l),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let f=this._pauseBuffer;this._pauseBuffer=[],this._emit(f)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}d?o?.push(u):o==null&&(o=n.slice(0,a))}if(o!=null){if(o.length===0)return;n=o}if(this._hasMeta&&n.some(a=>a[0]===de))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(wn)}catch{}let{finalMessages:s,equalsError:i}=this._updateState(n);if(s.length>0&&this._config.inspectorEnabled){let a=this._config.globalInspector;if(a!=null)try{a({kind:"emit",node:this,messages:s})}catch{}}if(s.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let a=this._config.tierOf,u=[];for(let c of s){let d=a(c[0]);d<3||d===5?u.push(c):this._pauseBuffer.push(c)}u.length>0&&this._dispatchOrAccumulate(u)}else this._dispatchOrAccumulate(s);i!=null&&this._emit([[O,i]])}_updateState(e){let n=this._config.tierOf,r,o,s=-1,i=0;for(let d of e)n(d[0])===3&&i++;let a=i<=1,u=-1;if(this._versioning!=null&&i>1){for(let d=e.length-1;d>=0;d--)if(e[d][0]===R){u=d;break}}for(let d=0;d<e.length;d++){let l=e[d],f=l[0];if(f===R){if(l.length>=2){let p=!1;if(a&&this._cached!==void 0)try{p=this._equals(this._cached,l[1])}catch(m){o=this._wrapFnError("equals threw",m),s=d;break}if(p){r==null&&(r=e.slice(0,d)),r.push(bn),this._status="resolved";continue}this._cached=l[1],this._versioning!=null&&(u<0||d===u)&&dr(this._versioning,l[1],this._hashFn)}this._status="settled",r?.push(l)}else if(r?.push(l),f===Z)this._status="dirty";else if(f===$)this._status="resolved";else if(f===M)this._status="completed";else if(f===O)this._status="errored";else if(f===Ve){this._cached=void 0,this._status="dirty";let p=this._cleanup;if(typeof p=="function"){this._cleanup=void 0;try{p()}catch{}}else if(p!=null&&typeof p=="object"){let m=p.invalidate;if(typeof m=="function")try{m()}catch{}}}else f===de&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let c=s>=0?r??e.slice(0,s):r??e;return o!=null?{finalMessages:c,equalsError:o}:{finalMessages:c}}_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(su()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],ir(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}bt(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);bt(this._deliverToSinks,n,this._config.tierOf)}},du=t=>Array.isArray(t),ai=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function lu(t,e,n){return n?!1:t.some((r,o)=>!(r!=null&&r.length>0)&&e.prevData[o]===void 0)}function N(t,e){return q([],{...e,initial:t})}function H(t,e){return q((r,o,s)=>t(o,s)??void 0,{describeKind:"producer",...e})}function A(t,e,n){let r=n?.partial??!1;return q(t,(s,i,a)=>{if(lu(s,a,r)){i.down([[$]]);return}let u=s.map((c,d)=>c!=null&&c.length>0?c.at(-1):a.prevData[d]);i.emit(e(u,a))},{describeKind:"derived",...n})}function fe(t,e,n){let r=n?.partial??!1;return q(t,(s,i,a)=>{if(lu(s,a,r)){i.down([[$]]);return}let u=s.map((c,d)=>c!=null&&c.length>0?c.at(-1):a.prevData[d]);return e(u,i,a)??void 0},{describeKind:"effect",...n})}function lr(t,e,n){let r=new Map;return t.forEach((o,s)=>{r.set(o,s)}),A(t,(o,s)=>e(a=>{let u=r.get(a);if(u==null)throw new Error(`dynamicNode: untracked dep "${a.name??"<unnamed>"}"`);return o[u]},s),n)}function Yt(t,e){let n,r=new Map,o=e?.partial??!1,s=(i,a,u)=>{let c=!1,d=l=>{let f=r.get(l);if(f!==void 0){if(f<i.length){let m=i[f];return m!=null&&m.length>0?m.at(-1):u.prevData[f]}return l.cache}c=!0;let p=n._addDep(l);return r.set(l,p),l.cache};if(!o&&r.size>0){for(let[,l]of r)if(l<i.length){let f=i[l];if(!(f!=null&&f.length>0)&&u.prevData[l]===void 0){a.down([[$]]);return}}}try{let l=t(d,u);c||(a.emit(l),u.store.__autoTrackLastDiscoveryError!=null&&delete u.store.__autoTrackLastDiscoveryError)}catch(l){if(!c)throw l;u.store.__autoTrackLastDiscoveryError=l}};return n=new xe([],s,{describeKind:"derived",...e}),n}function ci(t,...e){let n=t;for(let r of e)n=r(n);return n}var le=We(()=>{"use strict";ie();we()});function mr(t,e,n){let r=new Set;for(let o of t.split(",")){let[s,i]=o.split("/"),a=i?Number.parseInt(i,10):1;if(Number.isNaN(a)||a<1)throw new Error(`Invalid cron step: ${o}`);let u,c;if(s==="*")u=e,c=n;else if(s.includes("-")){let[d,l]=s.split("-");u=Number.parseInt(d,10),c=Number.parseInt(l,10)}else u=Number.parseInt(s,10),c=u;if(Number.isNaN(u)||Number.isNaN(c))throw new Error(`Invalid cron field: ${t}`);if(u<e||c>n)throw new Error(`Cron field out of range: ${t} (${e}-${n})`);if(u>c)throw new Error(`Invalid cron range: ${u}-${c} in ${t}`);for(let d=u;d<=c;d+=a)r.add(d)}return r}function uo(t){let e=t.trim().split(/\s+/);if(e.length!==5)throw new Error(`Invalid cron: expected 5 fields, got ${e.length}`);return{minutes:mr(e[0],0,59),hours:mr(e[1],0,23),daysOfMonth:mr(e[2],1,31),months:mr(e[3],1,12),daysOfWeek:mr(e[4],0,6)}}function co(t,e){return t.minutes.has(e.getMinutes())&&t.hours.has(e.getHours())&&t.daysOfMonth.has(e.getDate())&&t.months.has(e.getMonth()+1)&&t.daysOfWeek.has(e.getDay())}var pi=We(()=>{"use strict"});var Eu={};he(Eu,{NS_PER_MS:()=>De,NS_PER_SEC:()=>Qe,constant:()=>lo,decorrelatedJitter:()=>ho,exponential:()=>fo,fibonacci:()=>mo,linear:()=>po,resolveBackoffPreset:()=>Ot,withMaxAttempts:()=>fi});function Xt(t){return t<0?0:t}function Op(t,e){return e==="none"?t:e==="full"?Math.random()*t:t/2+Math.random()*(t/2)}function Cp(t,e){return t+Math.random()*(e-t)}function lo(t){let e=Xt(t);return()=>e}function po(t,e){let n=Xt(t),r=e===void 0?n:Xt(e);return o=>n+r*Math.max(0,o)}function fo(t){let e=Xt(t?.baseNs??1e8),n=t?.factor!==void 0&&t.factor<1?1:t?.factor??2,r=Xt(t?.maxDelayNs??30*1e9),o=t?.jitter??"none";return s=>{let i;if(e===0)i=0;else if(n===1)i=e;else{let a=r/e,u=1;for(let c=0;c<Math.max(0,s);c++){if(u>=a){u=a;break}u*=n}i=e*u,i>r&&(i=r)}return Op(i,o)}}function mo(t=100*1e6,e=30*1e9){let n=Xt(t),r=Xt(e);function o(s){if(s<=0)return 1;let i=1,a=2;for(let u=1;u<s;u++){let c=i+a;i=a,a=c}return a}return s=>{let i=o(s)*n;return i<=r?i:r}}function ho(t=100*1e6,e=30*1e9){return(n,r,o)=>{let i=Math.min(e,(o??t)*3);return Cp(t,i)}}function fi(t,e){return(n,r,o)=>n>=e?null:t(n,r,o)}function Ot(t){if(t==="constant")return lo(1*1e9);if(t==="linear")return po(1*1e9);if(t==="exponential")return fo();if(t==="fibonacci")return mo();if(t==="decorrelatedJitter")return ho();throw new Error(`Unknown backoff preset: "${String(t)}". Use one of: constant, linear, exponential, fibonacci, decorrelatedJitter`)}var De,Qe,Ln=We(()=>{"use strict";De=1e6,Qe=1e9});var Re,lt=We(()=>{"use strict";Re=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 Mu={};he(Mu,{CircuitOpenError:()=>st,RateLimiterOverflowError:()=>Zt,TimeoutError:()=>en,circuitBreaker:()=>pt,fallback:()=>Gn,rateLimiter:()=>Dn,retry:()=>In,retrySource:()=>Ct,timeout:()=>Fn,tokenBucket:()=>At,withBreaker:()=>Pn,withStatus:()=>Lt});function tn(t){return{describeKind:"derived",...t}}function Ap(t){return t<0?0:t}function go(t){return t[1]}function _u(t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("backoff strategy must return a finite number");return t<0?0:t}function In(t,e){let n=e?.count,r=e?.backoff,o=n!==void 0?n:r===void 0?0:2147483647;if(o<0)throw new RangeError("retry count must be >= 0");let s=r===void 0?null:typeof r=="string"?Ot(r):r;return H(i=>{let a=0,u=!1,c=null,d,l=new Re;function f(){d?.(),d=void 0}function p(h){if(u)return;if(a>=o){f(),i.down([[O,h]]);return}let g=s===null?0:s(a,h,c);if(g==null){f(),i.down([[O,h]]);return}let y;try{y=_u(g)}catch{f(),i.down([[O,h]]);return}c=y,a+=1,f();let b=y>0?y/1e6:1;l.start(b,()=>{u||m()})}function m(){l.cancel(),f(),d=t.subscribe(h=>{if(!u)for(let g of h){let y=g[0];if(y===Z)i.down([[Z]]);else if(y===R)a=0,c=null,i.emit(g[1]);else if(y===$)i.down([[$]]);else if(y===M)f(),i.down([[M]]);else if(y===O){p(go(g));return}else i.down([g])}})}return m(),()=>{u=!0,l.cancel(),f()}},{...tn(),initial:t.cache})}function Ct(t,e){let n=e?.count,r=e?.backoff,o=n!==void 0?n:r===void 0?0:2147483647;if(o<0)throw new RangeError("retry count must be >= 0");let s=r===void 0?null:typeof r=="string"?Ot(r):r;return H(i=>{let a=0,u=!1,c=null,d,l=new Re;function f(){d?.(),d=void 0}function p(h){if(u)return;if(a>=o){f(),i.down([[O,h]]);return}let g=s===null?0:s(a,h,c);if(g==null){f(),i.down([[O,h]]);return}let y;try{y=_u(g)}catch{f(),i.down([[O,h]]);return}c=y,a+=1,f();let b=y>0?y/1e6:1;l.start(b,()=>{u||m()})}function m(){l.cancel(),f();let h;try{h=t()}catch(g){p(g);return}d=h.subscribe(g=>{if(!u)for(let y of g){let b=y[0];if(b===Z)i.down([[Z]]);else if(b===R)a=0,c=null,i.emit(y[1]);else if(b===$)i.down([[$]]);else if(b===M)f(),i.down([[M]]);else if(b===O){p(go(y));return}else i.down([y])}})}return m(),()=>{u=!0,l.cancel(),f()}},{...tn(),initial:e?.initial})}function pt(t){let e=Math.max(1,t?.failureThreshold??5),n=Ap(t?.cooldownNs??30*1e9),r=t?.cooldown??null,o=Math.max(1,t?.halfOpenMax??1),s=t?.now??B,i="closed",a=0,u=0,c=0,d=n,l=0;function f(){if(!r)return n;let h=r(u);return h!==null?h:n}function p(){i="open",d=f(),c=s(),l=0}return{canExecute(){return i==="closed"?!0:i==="open"?s()-c>=d?(i="half-open",l=1,!0):!1:l<o?(l++,!0):!1},recordSuccess(){i==="half-open"?(i="closed",a=0,u=0):i==="closed"&&(a=0)},recordFailure(h){if(i==="half-open"){u++,p();return}i==="closed"&&(a++,a>=e&&p())},get state(){return i},get failureCount(){return a},reset(){i="closed",a=0,u=0,l=0}}}function Pn(t,e){let n=e?.onOpen??"skip";return r=>{let o=q([],(s,i)=>{function a(){o.meta.breakerState.down([[R,t.state]])}let u=r.subscribe(c=>{for(let d of c){let l=d[0];l===Z?i.down([[Z]]):l===R?t.canExecute()?(a(),i.emit(d[1])):(a(),n==="error"?i.down([[O,new st]]):i.down([[$]])):l===$?i.down([[$]]):l===M?(t.recordSuccess(),a(),i.down([[M]])):l===O?(t.recordFailure(go(d)),a(),i.down([d])):i.down([d])}});return a(),u},{...tn(),meta:{breakerState:t.state},completeWhenDepsComplete:!1,initial:r.cache});return{node:o,breakerState:o.meta.breakerState}}}function At(t,e){if(t<=0)throw new RangeError("capacity must be > 0");if(e<0)throw new RangeError("refillPerSecond must be >= 0");let n=t,r=B();function o(s){if(e>0){let i=s-r;n=Math.min(t,n+i/1e9*e)}r=s}return{available(){return o(B()),n},tryConsume(s=1){if(s<=0)return!0;let i=B();return o(i),n>=s?(n-=s,!0):!1},putBack(s=1){s<=0||(o(B()),n=Math.min(t,n+s))}}}function Dn(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&&o<1)throw new RangeError("maxBuffer must be >= 1");let s=e.onOverflow??"drop-newest",i=n*1e9/r;return H(a=>{let u=At(n,i),c=[],d=new Re,l=!1,f=1e9/i;function p(){for(;c.length>0;)if(u.tryConsume(1))a.emit(c.shift());else{d.start(Math.max(1,f/1e6),p);return}}let m=t.subscribe(h=>{for(let g of h){if(l)return;let y=g[0];if(y===Z)a.down([[Z]]);else if(y===R){if(o!==void 0&&c.length>=o){if(s!=="drop-newest")if(s==="drop-oldest")c.shift(),c.push(g[1]);else{l=!0,d.cancel(),c.length=0,a.down([[O,new Zt(o)]]);return}}else c.push(g[1]);p()}else if(y===$)a.down([[$]]);else if(y===M)l=!0,d.cancel(),c.length=0,a.down([[M]]);else if(y===O)l=!0,d.cancel(),c.length=0,a.down([g]);else if(y===de){l=!0,d.cancel(),c.length=0,a.down([g]);return}else a.down([g])}});return()=>{l=!0,d.cancel(),m()}},{...tn(),initial:t.cache})}function Lt(t,e){let n=e?.initialStatus??"pending",r=q([],(o,s)=>{let i=n;return r.meta.status.down([[R,n]]),r.meta.error.down([[R,null]]),t.subscribe(u=>{for(let c of u){let d=c[0];if(d===Z)s.down([[Z]]);else if(d===R)i==="errored"?ee(()=>{r.meta.error.down([[R,null]]),r.meta.status.down([[R,"active"]])}):r.meta.status.down([[R,"active"]]),i="active",s.emit(c[1]);else if(d===$)s.down([[$]]);else if(d===M)r.meta.status.down([[R,"completed"]]),i="completed",s.down([[M]]);else if(d===O){let l=go(c);ee(()=>{r.meta.error.down([[R,l]]),r.meta.status.down([[R,"errored"]])}),i="errored",s.down([c])}else s.down([c])}})},{...tn(),meta:{status:n,error:null},completeWhenDepsComplete:!1,resubscribable:!0,initial:t.cache});return{node:r,status:r.meta.status,error:r.meta.error}}function Lp(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function Ip(t){return t!=null&&typeof t.then=="function"}function Pp(t){return t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function"}function Gn(t,e){return H(n=>{let r,o;function s(){o?.(),o=void 0,Lp(e)||Ip(e)||Pp(e)?r=re(e).subscribe(a=>{n.down(a)}):(n.emit(e),n.down([[M]]))}return o=t.subscribe(i=>{for(let a of i){let u=a[0];if(u===Z)n.down([[Z]]);else if(u===R)n.emit(a[1]);else if(u===$)n.down([[$]]);else if(u===M)n.down([[M]]);else if(u===O){s();return}else if(u===de){r?.(),n.down([a]);return}else n.down([a])}}),()=>{o?.(),r?.()}},{...tn(),initial:t.cache})}function Fn(t,e){if(e<=0)throw new RangeError("timeoutNs must be > 0");return H(n=>{let r=!1,o=new Re;function s(){let a=e/1e6;o.start(a,()=>{r||(r=!0,i(),n.down([[O,new en(e)]]))})}let i=t.subscribe(a=>{for(let u of a){if(r)return;let c=u[0];if(c===Z)n.down([[Z]]);else if(c===R)s(),n.emit(u[1]);else if(c===$)n.down([[$]]);else if(c===M){o.cancel(),r=!0,n.down([[M]]);return}else if(c===O){o.cancel(),r=!0,n.down([u]);return}else if(c===de){o.cancel(),r=!0,n.down([u]);return}else n.down([u])}});return s(),()=>{r=!0,o.cancel(),i()}},{...tn(),initial:t.cache})}var st,Zt,en,vt=We(()=>{"use strict";Se();Te();ie();we();le();Ln();$e();lt();st=class extends Error{name="CircuitOpenError";constructor(){super("Circuit breaker is open")}};Zt=class extends Error{name="RateLimiterOverflowError";constructor(e){super(`rateLimiter buffer overflow (maxBuffer=${e})`)}};en=class extends Error{name="TimeoutError";constructor(e){super(`Timed out after ${e/1e6}ms`)}}});function Ze(t){return{describeKind:"producer",...t}}function hi(t){return/[\\^$+?.()|[\]{}]/.test(t)?`\\${t}`:t}function Cu(t){let e="^";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="*"){t[n+1]==="*"?(e+=".*",n+=1):e+="[^/]*";continue}e+=hi(r)}return e+="$",new RegExp(e)}function Au(t,e){for(let n of e)if(n.test(t))return!0;return!1}function Dp(t,e){let n=q([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[$]]);return}for(let a of i)s.emit(a)},{describeKind:"derived",initial:t.cache}),r=n.subscribe.bind(n);return n.subscribe=(o,s)=>(e(o),r(o,s)),n}function et(t,e){let{signal:n,period:r,...o}=e??{};return H(s=>{let i=!1,a=0,u,c,d=()=>{i=!0,u!==void 0&&clearTimeout(u),c!==void 0&&clearInterval(c),n?.removeEventListener("abort",f)},l=()=>{i||(r!=null?(s.emit(a++),c=setInterval(()=>{i||s.emit(a++)},r)):(i=!0,n?.removeEventListener("abort",f),s.emit(a++),s.down([[M]])))},f=()=>{i||(d(),s.down([[O,n.reason]]))};if(n?.aborted){f();return}return u=setTimeout(l,t),n?.addEventListener("abort",f,{once:!0}),d},Ze(o))}function Lu(t){let{signal:e,...n}=t??{};return H(r=>{let o=!1,s,i,a=!1,u=!1,c=typeof requestAnimationFrame=="function"?requestAnimationFrame:void 0,d=typeof cancelAnimationFrame=="function"?cancelAnimationFrame:void 0,l=typeof document<"u"?document:void 0,f=()=>{s!==void 0&&d&&d(s),i!==void 0&&clearTimeout(i),s=void 0,i=void 0},p=()=>{o=!0,f(),a&&(e?.removeEventListener("abort",m),a=!1),u&&l&&(l.removeEventListener("visibilitychange",y),u=!1)},m=()=>{o||(p(),r.down([[O,e.reason]]))},h=b=>{o||(r.emit(b),g())},g=()=>{o||(c&&(!l||l.visibilityState!=="hidden")?s=c(h):i=setTimeout(()=>h(performance.now()),16))},y=()=>{o||(f(),g())};return e?.aborted?(m(),p):(e?.addEventListener("abort",m,{once:!0}),a=e!==void 0,l&&c&&(l.addEventListener("visibilitychange",y),u=!0),g(),p)},Ze(n))}function bo(t,e){let n=uo(t),{tickMs:r,output:o,...s}=e??{},i=r??6e4,a=o==="date";return H(u=>{let c=-1,d=()=>{let f=new Date,p=f.getFullYear()*1e8+(f.getMonth()+1)*1e6+f.getDate()*1e4+f.getHours()*100+f.getMinutes();p!==c&&co(n,f)&&(c=p,u.emit(a?f:pe()))};d();let l=setInterval(d,i);return()=>clearInterval(l)},{...Ze(s),name:s.name??`cron:${t}`})}function Iu(t,e,n){let{capture:r,passive:o,once:s,...i}=n??{};return H(a=>{let u=d=>{a.emit(d)},c={capture:r,passive:o,once:s};return t.addEventListener(e,u,c),()=>t.removeEventListener(e,u,c)},Ze(i))}function vo(t,e){return H(n=>{let r=!1;try{for(let o of t){if(r)return;n.emit(o)}r||n.down([[M]])}catch(o){r||n.down([[O,o]])}return()=>{r=!0}},Ze(e))}function Gp(t){return t!=null&&typeof t.then=="function"}function gi(t,e){let{signal:n,...r}=e??{};return H(o=>{let s=!1,i=()=>{s||(s=!0,o.down([[O,n.reason]]))};if(n?.aborted){i();return}return n?.addEventListener("abort",i,{once:!0}),Promise.resolve(t).then(a=>{s||(s=!0,n?.removeEventListener("abort",i),o.emit(a),o.down([[M]]))},a=>{s||(s=!0,n?.removeEventListener("abort",i),o.down([[O,a]]))}),()=>{s=!0,n?.removeEventListener("abort",i)}},Ze(r))}function yi(t,e){let{signal:n,...r}=e??{};return H(o=>{let s=new AbortController,i=()=>s.abort(n?.reason);n?.aborted?s.abort(n.reason):n?.addEventListener("abort",i,{once:!0});let a=n??s.signal,u=!1,c=t[Symbol.asyncIterator](),d=()=>{u||a.aborted||Promise.resolve(c.next()).then(l=>{if(!(u||a.aborted)){if(l.done){o.down([[M]]);return}o.emit(l.value),d()}},l=>{!u&&!a.aborted&&o.down([[O,l]])})};return d(),()=>{u=!0,n?.removeEventListener("abort",i),s.abort(),Promise.resolve(c.return?.()).catch(()=>{})}},Ze(r))}function Fp(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function re(t,e){if(Fp(t))return t;if(Gp(t))return gi(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return yi(t,e);if(typeof n[Symbol.iterator]=="function")return vo(t,e)}return bi(t)}function bi(...t){return vo(t,void 0)}function Pu(t){return H(e=>{e.down([[M]])},Ze(t))}function Du(t){return H(()=>{},Ze(t))}function Gu(t,e){return H(n=>{n.down([[O,t]])},Ze(e))}function It(t,e,n){return q([t],(o,s)=>{let i=o[0];if(i!=null&&i.length>0)for(let a of i)e(a)},{describeKind:"effect",...n}).subscribe(()=>{})}function Fu(t,e){return q([t],(n,r,o)=>{o.store.buf||(o.store.buf=[]);let s=o.store.buf,i=n[0];if(i!=null&&i.length>0)for(let a of i)s.push(a);if(o.terminalDeps[0]===!0){r.emit([...s]),r.down([[M]]);return}(i==null||i.length===0)&&r.down([[$]])},{describeKind:"derived",completeWhenDepsComplete:!1,...e})}function $u(t,e){return H(n=>t.subscribe(r=>{n.down(r)}),{...Ze(e),initial:t.cache})}function To(t,e,n){if(e<1)throw new RangeError("replay expects bufferSize >= 1");let r=[],o=H(s=>t.subscribe(i=>{for(let a of i)a[0]===R&&(r.push(a[1]),r.length>e&&r.shift());s.down(i)}),{...Ze(n),initial:t.cache});return Dp(o,s=>{for(let i of r)s([[R,i]])})}function Bu(t,e){return To(t,1,e)}function $n(t){return new Promise((e,n)=>{let r=!1,o=!1,s;s=t.subscribe(i=>{for(let a of i){if(r)return;if(a[0]===R){r=!0,e(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===O){r=!0,n(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===M){r=!0,n(new Error("completed without DATA")),s?(s(),s=void 0):o=!0;return}}}),o&&(s?.(),s=void 0)})}function yo(t,e){return new Promise((n,r)=>{let o=!1,s=!1,i;i=t.subscribe(a=>{for(let u of a){if(o)return;if(u[0]===R){let c=u[1];if(e(c)){o=!0,n(c),i?(i(),i=void 0):s=!0;return}}if(u[0]===O){o=!0,r(u[1]),i?(i(),i=void 0):s=!0;return}if(u[0]===M){o=!0,r(new Error("completed without matching value")),i?(i(),i=void 0):s=!0;return}}}),s&&(i?.(),i=void 0)})}async function wo(t,e){let n=e?.predicate??(o=>o!=null);if(e?.timeoutMs==null||e.timeoutMs<=0)return await yo(t,n);if(mi===void 0){let[o,s]=await Promise.all([Promise.resolve().then(()=>(vt(),Mu)),Promise.resolve().then(()=>(Ln(),Eu))]);mi=o.timeout,Ou=s.NS_PER_MS}let r=mi(t,e.timeoutMs*Ou);return await yo(r,n)}function oe(t){return t.subscribe(()=>{})}function vi(t){let e=N(0);return{node:e,increment(){let n=e.cache??0;return n>=t?!1:(e.down([[Z],[R,n+1]]),!0)},get(){return e.cache??0},atCap(){return(e.cache??0)>=t}}}var mi,Ou,ju,$e=We(()=>{"use strict";Te();ie();we();le();pi();ju=To});var Bg={};he(Bg,{COMPLETE:()=>M,COMPLETE_MSG:()=>Yr,COMPLETE_ONLY_BATCH:()=>Zn,CircuitOpenError:()=>st,DATA:()=>R,DEFAULT_ACTOR:()=>dt,DIRTY:()=>Z,DIRTY_MSG:()=>gt,DIRTY_ONLY_BATCH:()=>Tn,ENVELOPE_VERSION:()=>kn,ERROR:()=>O,GRAPH_META_SEGMENT:()=>Be,Graph:()=>z,GraphReFlyConfig:()=>Ut,GuardDenied:()=>Je,INVALIDATE:()=>Ve,INVALIDATE_MSG:()=>Jr,INVALIDATE_ONLY_BATCH:()=>Xn,JsonCodec:()=>Xr,NS_PER_MS:()=>De,NS_PER_SEC:()=>Qe,NativeIndexBackend:()=>Or,NativeListBackend:()=>Cr,NativeLogBackend:()=>vr,NativeMapBackend:()=>Er,NativePubSubBackend:()=>Mr,NodeImpl:()=>xe,PAUSE:()=>Ae,RESOLVED:()=>$,RESOLVED_MSG:()=>bn,RESOLVED_ONLY_BATCH:()=>Qn,RESUME:()=>Pe,RateLimiterOverflowError:()=>Zt,ResettableTimer:()=>Re,SIZEOF_OVERHEAD:()=>Oe,SIZEOF_SYMBOL:()=>Eo,SNAPSHOT_VERSION:()=>it,SNAPSHOT_WIRE_VERSION:()=>zr,START:()=>ct,START_MSG:()=>vn,SurfaceError:()=>ve,TEARDOWN:()=>de,TEARDOWN_MSG:()=>Qr,TEARDOWN_ONLY_BATCH:()=>wn,TimeoutError:()=>en,accessHintForGuard:()=>cr,accountability:()=>Rs,advanceVersion:()=>dr,ai:()=>ws,asSurfaceError:()=>Vs,audit:()=>_c,autoTrackNode:()=>Yt,awaitSettled:()=>wo,batch:()=>ee,buffer:()=>Mc,bufferCount:()=>Oc,bufferTime:()=>Ac,cached:()=>Bu,cascadingCache:()=>Bd,catchError:()=>Kc,checkpointToRedis:()=>Ad,checkpointToS3:()=>Cd,circuitBreaker:()=>pt,combine:()=>Fi,combineLatest:()=>$c,compat:()=>Di,concat:()=>wc,concatMap:()=>Rc,configure:()=>ui,constant:()=>lo,core:()=>Si,cqrs:()=>Io,createDagCborCodec:()=>ei,createDagCborZstdCodec:()=>ti,createGraph:()=>zn,createTransport:()=>Gt,createVersioning:()=>Sn,createWatermarkController:()=>Bn,csvRows:()=>fd,debounce:()=>Bi,debounceTime:()=>Bc,decodeEnvelope:()=>tr,decorrelatedJitter:()=>ho,defaultConfig:()=>Me,defaultHash:()=>Mt,delay:()=>Nc,deleteSnapshot:()=>Ys,demoShell:()=>Ns,derived:()=>A,deserializeError:()=>ln,dictStorage:()=>Yd,diffForWAL:()=>Co,diffSnapshots:()=>zs,distill:()=>Uo,distinctUntilChanged:()=>bc,domainTemplates:()=>Ms,downWithBatch:()=>bt,dynamicNode:()=>lr,effect:()=>fe,elementAt:()=>gc,empty:()=>Pu,encodeEnvelope:()=>er,escapeRegexChar:()=>hi,exhaustMap:()=>xc,explainPath:()=>yr,exponential:()=>fo,externalBundle:()=>qo,externalProducer:()=>an,extra:()=>Qi,fallback:()=>Gn,fibonacci:()=>mo,filter:()=>xr,find:()=>hc,first:()=>Ho,firstValueFrom:()=>$n,firstWhere:()=>yo,flatMap:()=>Sc,forEach:()=>It,fromAny:()=>re,fromAsyncIter:()=>yi,fromCSV:()=>pd,fromClickHouseWatch:()=>yd,fromCron:()=>bo,fromDrizzle:()=>Gd,fromEvent:()=>Iu,fromHTTP:()=>Hi,fromHTTPPoll:()=>Xc,fromHTTPStream:()=>Qc,fromIter:()=>vo,fromKafka:()=>ud,fromKysely:()=>Fd,fromMCP:()=>td,fromNATS:()=>Td,fromNDJSON:()=>gd,fromOTel:()=>nd,fromPrisma:()=>Dd,fromPrometheus:()=>ad,fromPromise:()=>gi,fromPulsar:()=>bd,fromRabbitMQ:()=>kd,fromRaf:()=>Lu,fromRedisStream:()=>dd,fromSSE:()=>Yc,fromSqlite:()=>Ld,fromSqliteCursor:()=>Id,fromStatsD:()=>sd,fromSyslog:()=>rd,fromTimer:()=>et,fromWebSocket:()=>qi,fromWebSocketReconnect:()=>ed,fromWebhook:()=>Vc,globToRegExp:()=>Cu,graph:()=>Ei,graphProfile:()=>on,graphspec:()=>Os,guarded:()=>As,harness:()=>Is,interval:()=>Pc,isBatching:()=>Wt,isV1:()=>si,jobQueue:()=>Gs,jotai:()=>no,keepalive:()=>oe,last:()=>mc,layout:()=>Bs,lens:()=>$s,linear:()=>po,listSnapshots:()=>Js,lru:()=>zi,map:()=>kr,matchesAnyPattern:()=>Au,matchesCron:()=>co,memory:()=>Qo,memoryStorage:()=>Lr,merge:()=>ft,mergeMap:()=>$i,mermaidLiveUrl:()=>Oo,messaging:()=>ts,monotonicNs:()=>B,nameToSignal:()=>cn,nanostores:()=>io,ndjsonRows:()=>md,nestjs:()=>Do,never:()=>Du,node:()=>q,normalizeActor:()=>yt,of:()=>bi,orchestration:()=>ns,pairwise:()=>vc,parseCron:()=>uo,parsePrometheusText:()=>Wi,parseStatsD:()=>id,parseSyslog:()=>od,patterns:()=>Ua,pausable:()=>Gc,pipe:()=>ci,policy:()=>zt,policyFromRules:()=>ur,producer:()=>H,pubsub:()=>qd,race:()=>kc,rateLimiter:()=>Dn,reachable:()=>sn,react:()=>Go,reactiveCounter:()=>vi,reactiveIndex:()=>Ud,reactiveList:()=>zo,reactiveLog:()=>je,reactiveMap:()=>tt,reactiveSink:()=>Ge,reduce:()=>lc,reduction:()=>_s,refine:()=>js,registerBuiltinCodecs:()=>nr,registerBuiltins:()=>ar,repeat:()=>Dc,replay:()=>To,replayWAL:()=>ni,rescue:()=>Sr,resilientPipeline:()=>Ks,resolveBackoffPreset:()=>Ot,resolveDescribeFields:()=>Tt,restoreSnapshot:()=>Us,retry:()=>In,retrySource:()=>Ct,runReduction:()=>qs,sample:()=>Ec,saveSnapshot:()=>Ws,scan:()=>dc,serializeError:()=>dn,share:()=>$u,shareReplay:()=>ju,signalToName:()=>Dt,signals:()=>$o,singleFromAny:()=>Jo,singleNodeFromAny:()=>zd,sizeof:()=>br,skip:()=>Gi,solid:()=>Bo,sortJsonValue:()=>Ar,stableJsonString:()=>Jd,state:()=>N,stratify:()=>Ir,surface:()=>Qs,svelte:()=>jo,switchMap:()=>_e,take:()=>Rr,takeUntil:()=>fc,takeWhile:()=>pc,tap:()=>yc,throttle:()=>ji,throttleTime:()=>jc,throwError:()=>Gu,timeout:()=>Fn,toArray:()=>Fu,toCSV:()=>Rd,toClickHouse:()=>Sd,toFile:()=>Ui,toHTTP:()=>qc,toKafka:()=>cd,toLoki:()=>Md,toMongo:()=>_d,toNATS:()=>wd,toObservable:()=>ao,toPostgres:()=>Ed,toPulsar:()=>vd,toRabbitMQ:()=>xd,toReadableStream:()=>Jc,toRedisStream:()=>ld,toS3:()=>Nd,toSSE:()=>Uc,toSSEBytes:()=>zc,toSqlite:()=>Pd,toTempo:()=>Od,toWebSocket:()=>Zc,tokenBucket:()=>At,validateGraphObservability:()=>Ni,valve:()=>Fc,verifiable:()=>Vd,version:()=>$g,vue:()=>Ko,wallClockNs:()=>pe,watchTopologyTree:()=>wt,window:()=>Ic,windowCount:()=>Cc,windowTime:()=>Lc,withBreaker:()=>Pn,withLatestFrom:()=>un,withMaxAttempts:()=>fi,withStatus:()=>Lt,workerBridge:()=>Ji,workerSelf:()=>Yi,zip:()=>Tc,zustand:()=>Vo});module.exports=up(Bg);var Di={};he(Di,{jotai:()=>no,nanostores:()=>io,nestjs:()=>Do,react:()=>Go,signals:()=>$o,solid:()=>Bo,svelte:()=>jo,vue:()=>Ko,zustand:()=>Vo});var no={};he(no,{atom:()=>kp});ie();le();function kp(t,e,n){if(typeof t=="function"){let r=t;return typeof e=="function"?pu(r,e,n):pu(r,void 0,e)}return xp(t,e)}function pr(t){let e=t.cache,n;if(t.subscribe(o=>{for(let[s,i]of o)s===R&&(e=i),s===O&&(n=i)})(),n)throw n;return e}function xp(t,e){let n=N(t,{...e,resubscribable:!0,resetOnTeardown:!0});return{get:()=>n.status==="sentinel"?pr(n):n.cache,set:r=>n.emit(r),update:r=>{let o=n.status==="sentinel"?pr(n):n.cache;n.emit(r(o))},subscribe:r=>{let o=!0;return n.subscribe(s=>{for(let[i,a]of s)if(i===R){if(o){o=!1;continue}r(a)}})},meta:n.meta,_node:n}}function pu(t,e,n){let r=Yt(s=>t(i=>{let a=i._node;return a.status==="sentinel"&&pr(a),s(a)}),{...n,resubscribable:!0,resetOnTeardown:!0}),o={get:()=>r.status==="sentinel"?pr(r):r.cache,subscribe:s=>{let i=!0;return r.subscribe(a=>{for(let[u,c]of a)if(u===R){if(i){i=!1;continue}s(c)}})},meta:r.meta,_node:r};if(e){let s=u=>u.get(),i=(u,c)=>u.set(c),a=o;return a.set=u=>e(s,i,u),a.update=u=>{let c=r.status==="sentinel"?pr(r):r.cache;return e(s,i,u(c))},a}return o}var io={};he(io,{action:()=>Mp,atom:()=>Rp,computed:()=>Sp,getValue:()=>Ep,map:()=>Np,onMount:()=>_p,onStart:()=>hu,onStop:()=>gu});Se();ie();le();var oo=new WeakMap,so=new WeakMap;function ro(t,e){let n=e.get(t);if(n)for(let r of n)r()}function di(t,e={}){let n=0;return{...e,get:()=>mu(t),subscribe:o=>{n===0&&ro(t,oo),n++;let s=t.subscribe(i=>{for(let[a,u]of i)a===R&&o(u)});return()=>{s(),n--,n===0&&ro(t,so)}},listen:o=>{n===0&&ro(t,oo),n++;let s=!0,i=t.subscribe(a=>{for(let[u,c]of a)if(u===R){if(s){s=!1;continue}o(c)}});return()=>{i(),n--,n===0&&ro(t,so)}},_node:t}}function fu(t){let e=t.cache,n;if(t.subscribe(o=>{for(let[s,i]of o)s===R&&(e=i),s===O&&(n=i)})(),n)throw n;return e}function mu(t){return t.status==="sentinel"?fu(t):t.cache}function Rp(t){let e=N(t,{resubscribable:!0,resetOnTeardown:!0});return di(e,{set:n=>e.emit(n)})}function Sp(t,e){let n=Array.isArray(t)?t:[t],r=n.map(s=>s._node),o=lr(r,s=>{let i=n.map(a=>{let u=a._node;return u.status==="sentinel"&&fu(u),s(u)});return e(...i)},{resubscribable:!0,resetOnTeardown:!0,equals:Object.is});return di(o)}function Np(t){let e=N(t,{resubscribable:!0,resetOnTeardown:!0,equals:()=>!1});return di(e,{set:n=>e.emit(n),setKey:(n,r)=>{let o=mu(e);e.emit({...o,[n]:r})}})}function Ep(t){return t.get()}function hu(t,e){let n=t._node,r=oo.get(n);r||(r=new Set,oo.set(n,r)),r.add(e)}function gu(t,e){let n=t._node,r=so.get(n);r||(r=new Set,so.set(n,r)),r.add(e)}function _p(t,e){hu(t,()=>{let n=e();typeof n=="function"&&gu(t,n)})}function Mp(t,e,n){return(...r)=>{let o;return ee(()=>{o=n(...r)}),o}}var Do={};he(Do,{ACTOR_KEY:()=>xo,COMMAND_HANDLERS:()=>Mn,CQRS_EVENT_HANDLERS:()=>On,CRON_HANDLERS:()=>_n,CommandHandler:()=>xu,EVENT_HANDLERS:()=>Nn,EventHandler:()=>Ru,GRAPHREFLY_REQUEST_GRAPH:()=>Qt,GRAPHREFLY_ROOT_GRAPH:()=>Xe,GraphCron:()=>ku,GraphInterval:()=>wu,GraphReflyEventExplorer:()=>nn,GraphReflyGuard:()=>Uu,GraphReflyGuardImpl:()=>hr,GraphReflyModule:()=>Po,INTERVAL_HANDLERS:()=>En,InjectCqrsGraph:()=>bu,InjectGraph:()=>yu,InjectNode:()=>vu,ObserveGateway:()=>ko,OnGraphEvent:()=>Tu,QUERY_HANDLERS:()=>Cn,QueryHandler:()=>Su,SAGA_HANDLERS:()=>An,SagaHandler:()=>Nu,fromHeader:()=>Hu,fromJwtPayload:()=>ki,getActor:()=>Wu,getGraphToken:()=>Ye,getNodeToken:()=>ot,observeSSE:()=>Vu,observeSubscription:()=>qu,toObservable:()=>ao});var li=require("rxjs");ie();function ao(t,e){return e?.raw?new li.Observable(n=>t.subscribe(o=>{if(!n.closed){n.next(o);for(let s of o){if(s[0]===O){n.error(s[1]);return}if(s[0]===M){n.complete();return}}}})):new li.Observable(n=>t.subscribe(o=>{for(let s of o){if(n.closed)return;if(s[0]===R)n.next(s[1]);else if(s[0]===O){n.error(s[1]);return}else if(s[0]===M){n.complete();return}}}))}var fr=require("@nestjs/common");var Xe=Symbol.for("graphrefly:root-graph");var Qt=Symbol.for("graphrefly:request-graph");function Ye(t){return Symbol.for(`graphrefly:graph:${t}`)}function ot(t){return Symbol.for(`graphrefly:node:${t}`)}var Nn=new Map,En=new Map,_n=new Map,Mn=new Map,On=new Map,Cn=new Map,An=new Map;function yu(t){return t==="request"?(0,fr.Inject)(Qt):(0,fr.Inject)(t?Ye(t):Xe)}function bu(t){return(0,fr.Inject)(Ye(t))}function vu(t){return(0,fr.Inject)(ot(t))}function Tu(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=Nn.get(o)??[];s.push({nodeName:t,methodKey:r}),Nn.set(o,s)})}}function wu(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=En.get(o)??[];s.push({ms:t,methodKey:r}),En.set(o,s)})}}function ku(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=_n.get(o)??[];s.push({expr:t,methodKey:r}),_n.set(o,s)})}}function xu(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=Mn.get(s)??[];i.push({cqrsName:t,commandName:e,methodKey:o}),Mn.set(s,i)})}}function Ru(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=On.get(s)??[];i.push({cqrsName:t,eventName:e,methodKey:o}),On.set(s,i)})}}function Su(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=Cn.get(s)??[];i.push({cqrsName:t,projectionName:e,methodKey:o}),Cn.set(s,i)})}}function Nu(t,e,n){return(r,o)=>{let s=o.name;o.addInitializer(function(){let i=this.constructor,a=An.get(i)??[];a.push({cqrsName:t,eventNames:n,sagaName:e,methodKey:s}),An.set(i,a)})}}ie();$e();var Ku=0,nn=class{constructor(e,n){this.graph=e;this.moduleRef=n}disposers=[];scheduleNodeNames=[];onModuleInit(){this.wireEvents(),this.wireIntervals(),this.wireCrons(),this.wireCqrsCommands(),this.wireCqrsEvents(),this.wireCqrsQueries(),this.wireCqrsSagas()}onModuleDestroy(){for(let e of this.disposers)e();this.disposers.length=0;for(let e of this.scheduleNodeNames)try{this.graph.remove(e)}catch{}this.scheduleNodeNames.length=0}wireEvents(){for(let[e,n]of Nn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireEventHandler(r,o)}}wireEventHandler(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),i=this.observeNode(n.nodeName).subscribe(a=>{for(let u of a)u[0]===R&&o(u[1])});this.disposers.push(i)}wireIntervals(){for(let[e,n]of En){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireIntervalHandler(r,e,o)}}wireIntervalHandler(e,n,r){let o=e[r.methodKey];if(typeof o!="function")return;let s=o.bind(e),a=`__schedule__.${n.name??"anonymous"}.${String(r.methodKey)}.${Ku++}`,u=et(r.ms,{period:r.ms,name:a});this.graph.add(u),this.scheduleNodeNames.push(a);let d=this.observeNode(a).subscribe(l=>{for(let f of l)f[0]===R&&s(f[1])});this.disposers.push(d)}wireCrons(){for(let[e,n]of _n){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCronHandler(r,e,o)}}wireCronHandler(e,n,r){let o=e[r.methodKey];if(typeof o!="function")return;let s=o.bind(e),a=`__schedule__.${n.name??"anonymous"}.${String(r.methodKey)}.${Ku++}`,u=bo(r.expr,{name:a});this.graph.add(u),this.scheduleNodeNames.push(a);let d=this.observeNode(a).subscribe(l=>{for(let f of l)f[0]===R&&s(f[1])});this.disposers.push(d)}wireCqrsCommands(){for(let[e,n]of Mn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsCommand(r,o)}}wireCqrsCommand(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);s&&s.command(n.commandName,o)}wireCqrsEvents(){for(let[e,n]of On){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsEventHandler(r,o)}}wireCqrsEventHandler(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);if(!s)return;s.event(n.eventName);let a=s.resolve(n.eventName).cache,u=a&&a.length>0?a[a.length-1].seq:0,d=this.observeNodeOn(s,n.eventName).subscribe(l=>{for(let f of l)if(f[0]===R){let p=f[1];for(let m of p)m.seq>u&&(o(m),u=m.seq)}});this.disposers.push(d)}wireCqrsQueries(){for(let[e,n]of Cn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsQuery(r,o)}}wireCqrsQuery(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);if(!s)return;let a=this.observeNodeOn(s,n.projectionName).subscribe(u=>{for(let c of u)c[0]===R&&o(c[1])});this.disposers.push(a)}wireCqrsSagas(){for(let[e,n]of An){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsSaga(r,o)}}wireCqrsSaga(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);s&&s.saga(n.sagaName,n.eventNames,o)}observeNode(e){return this.graph.observe(e)}observeNodeOn(e,n){return e.observe(n)}resolveCqrsGraph(e){try{return this.moduleRef.get(Ye(e),{strict:!1})}catch{return console.warn(`[GraphReFly] CqrsGraph "${e}" not found in DI \u2014 did you import GraphReflyModule.forCqrs({ name: "${e}" })?`),null}}resolveInstance(e){try{return this.moduleRef.get(e,{strict:!1})}catch{return null}}};ie();ie();var $p=0;function Bn(t,e){if(e.highWaterMark<1)throw new RangeError("highWaterMark must be >= 1");if(e.lowWaterMark<0)throw new RangeError("lowWaterMark must be >= 0");if(e.lowWaterMark>=e.highWaterMark)throw new RangeError("lowWaterMark must be < highWaterMark");let n=Symbol(`bp-${++$p}`),r=0,o=!1;return{onEnqueue(){return r+=1,!o&&r>=e.highWaterMark?(o=!0,t([[Ae,n]]),!0):!1},onDequeue(){return r>0&&(r-=1),o&&r<=e.lowWaterMark?(o=!1,t([[Pe,n]]),!0):!1},get pending(){return r},get paused(){return o},dispose(){o&&(o=!1,t([[Pe,n]]))}}}function Vu(t,e,n){let{actor:r,serialize:o=Bp,keepAliveMs:s,signal:i}=n??{},a=new TextEncoder,u,c=n?.highWaterMark!=null,d,l,f=[],p=!1;return new ReadableStream({start(m){let h,g=()=>{},y=()=>{if(!p){p=!0,h!==void 0&&clearInterval(h),i?.removeEventListener("abort",b),g(),d?.dispose(),l?.(),l=void 0;for(let T of f)m.enqueue(T.frame);f.length=0,m.close()}};u=y;let b=()=>y(),v=t.observe(e,{actor:r});c&&(d=Bn(T=>v.up(T),{highWaterMark:n.highWaterMark,lowWaterMark:n.lowWaterMark??Math.floor(n.highWaterMark/2)})),g=v.subscribe(T=>{for(let w of T){if(p)return;let k=w[0];if(k===R){let x=a.encode(Ti("data",o(w[1])));c?(f.push({frame:x,counted:!0}),d.onEnqueue(),l?.(),l=void 0):m.enqueue(x)}else if(k===O){let x=a.encode(Ti("error",o(w[1])));c?(f.push({frame:x,counted:!1}),l?.(),l=void 0):m.enqueue(x),y();return}else if(k===M||k===de){if(k===M){let x=a.encode(Ti("complete"));c?(f.push({frame:x,counted:!1}),l?.(),l=void 0):m.enqueue(x)}y();return}}}),s!==void 0&&s>0&&(h=setInterval(()=>{p||(c?(f.push({frame:a.encode(`: keepalive
1
+ "use strict";var xp=Object.create;var wn=Object.defineProperty;var du=Object.getOwnPropertyDescriptor;var Rp=Object.getOwnPropertyNames;var Sp=Object.prototype.hasOwnProperty;var lu=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),tr=t=>{throw TypeError(t)};var Np=(t,e,n)=>e in t?wn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var au=(t,e)=>wn(t,"name",{value:e,configurable:!0});var Ue=(t,e)=>()=>(t&&(e=t(t=0)),e);var he=(t,e)=>{for(var n in e)wn(t,n,{get:e[n],enumerable:!0})},Ep=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Rp(e))!Sp.call(t,o)&&o!==n&&wn(t,o,{get:()=>e[o],enumerable:!(r=du(e,o))||r.enumerable});return t};var _p=t=>Ep(wn({},"__esModule",{value:!0}),t);var pu=t=>[,,,xp(t?.[lu("metadata")]??null)],fu=["class","method","getter","setter","accessor","field","value","get","set"],er=t=>t!==void 0&&typeof t!="function"?tr("Function expected"):t,Mp=(t,e,n,r,o)=>({kind:fu[t],name:e,metadata:r,addInitializer:s=>n._?tr("Already initialized"):o.push(er(s||null))}),Op=(t,e)=>Np(e,lu("metadata"),t[3]),mu=(t,e,n,r)=>{for(var o=0,s=t[e>>1],i=s&&s.length;o<i;o++)e&1?s[o].call(n):r=s[o].call(n,r);return r},hu=(t,e,n,r,o,s)=>{var i,a,u,c,d,l=e&7,f=!!(e&8),p=!!(e&16),m=l>3?t.length+1:l?f?1:2:0,h=fu[l+5],g=l>3&&(t[m-1]=[]),y=t[m]||(t[m]=[]),b=l&&(!p&&!f&&(o=o.prototype),l<5&&(l>3||!p)&&du(l<4?o:{get[n](){return uu(this,s)},set[n](T){return cu(this,s,T)}},n));l?p&&l<4&&au(s,(l>2?"set ":l>1?"get ":"")+n):au(o,n);for(var v=r.length-1;v>=0;v--)c=Mp(l,n,u={},t[3],y),l&&(c.static=f,c.private=p,d=c.access={has:p?T=>Cp(o,T):T=>n in T},l^3&&(d.get=p?T=>(l^1?uu:Ap)(T,o,l^4?s:b.get):T=>T[n]),l>2&&(d.set=p?(T,w)=>cu(T,o,w,l^4?s:b.set):(T,w)=>T[n]=w)),a=(0,r[v])(l?l<4?p?s:b[h]:l>4?void 0:{get:b.get,set:b.set}:o,c),u._=1,l^4||a===void 0?er(a)&&(l>4?g.unshift(a):l?p?s=a:b[h]=a:o=a):typeof a!="object"||a===null?tr("Object expected"):(er(i=a.get)&&(b.get=i),er(i=a.set)&&(b.set=i),er(i=a.init)&&g.unshift(i));return l||Op(t,o),b&&wn(o,n,b),p?l^4?s:b:o};var ri=(t,e,n)=>e.has(t)||tr("Cannot "+n),Cp=(t,e)=>Object(e)!==e?tr('Cannot use the "in" operator on this value'):t.has(e),uu=(t,e,n)=>(ri(t,e,"read from private field"),n?n.call(t):e.get(t));var cu=(t,e,n,r)=>(ri(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),Ap=(t,e,n)=>(ri(t,e,"access private method"),n);var dt,S,ee,B,He,Ie,Ge,de,_,M,yt,kn,Zr,xn,eo,to,Rn,nr,rr,or,Sn,ie=Ue(()=>{"use strict";dt=Symbol.for("graphrefly/START"),S=Symbol.for("graphrefly/DATA"),ee=Symbol.for("graphrefly/DIRTY"),B=Symbol.for("graphrefly/RESOLVED"),He=Symbol.for("graphrefly/INVALIDATE"),Ie=Symbol.for("graphrefly/PAUSE"),Ge=Symbol.for("graphrefly/RESUME"),de=Symbol.for("graphrefly/TEARDOWN"),_=Symbol.for("graphrefly/COMPLETE"),M=Symbol.for("graphrefly/ERROR"),yt=Object.freeze([ee]),kn=Object.freeze([B]),Zr=Object.freeze([He]),xn=Object.freeze([dt]),eo=Object.freeze([_]),to=Object.freeze([de]),Rn=Object.freeze([yt]),nr=Object.freeze([kn]),rr=Object.freeze([Zr]),or=Object.freeze([eo]),Sn=Object.freeze([to])});function oi(t){return{name:"dag-cbor",version:1,contentType:"application/dag-cbor",encode:e=>t.encode(e),decode:(e,n)=>t.decode(e)}}function si(t,e){return{name:"dag-cbor-zstd",version:1,contentType:"application/dag-cbor+zstd",encode:n=>e.compressSync(t.encode(n)),decode:(n,r)=>t.decode(e.decompressSync(n))}}function sr(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),i=0;return s[i++]=Nn,s[i++]=n.length,s.set(n,i),i+=n.length,s[i++]=r>>>8&255,s[i++]=r&255,s.set(e,i),s}function ir(t,e){if(t.length<gu)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${gu})`);let n=0,r=t[n++];if(r!==Nn)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${Nn})`);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 i=(t[n]<<8|t[n+1])>>>0;n+=2;let a=t.subarray(n),u=e.lookupCodec(s);if(u==null)throw new Error(`decodeEnvelope: codec "${s}" not registered (envelope codec_v=${i})`);return{codec:u,codecVersion:i,payload:a}}function ar(t){t.registerCodec(no)}function ii(t){if(t.length===0)throw new Error("WAL is empty \u2014 need at least one full snapshot");let e=t[0];if(e.mode!=="full")throw new Error("WAL must start with a full record carrying a baseline snapshot");let n=JSON.parse(JSON.stringify(e.snapshot)),r=e.seq;for(let o=1;o<t.length;o++){let s=t[o];if(s.seq<=r)throw new Error(`WAL chain broken at index ${o}: seq=${s.seq} must exceed prev seq=${r}`);if(s.mode==="full"){n=JSON.parse(JSON.stringify(s.snapshot)),r=s.seq;continue}let i=s.diff;for(let u of i.nodesRemoved)delete n.nodes[u];let a=i.nodesAddedFull;if(a!=null)for(let[u,c]of Object.entries(a))n.nodes[u]=JSON.parse(JSON.stringify(c));for(let u of i.nodesChanged){let c=n.nodes[u.path];c!=null&&(c[u.field]=u.to)}r=s.seq}return n}var no,Nn,gu,ro=Ue(()=>{"use strict";no={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)}};Nn=1,gu=4});function bt(t){if(t==null)return lt;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var lt,ur=Ue(()=>{"use strict";lt={type:"system",id:""}});function zt(){return En>0||cr}function yu(){return En>0}function lr(t){En>0?dr.push(t):t()}function te(t){En+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(En-=1,En===0)if(e){if(!cr){let n=dr.splice(0);for(let r of n)try{r()}catch{}qt.length=0,Ut.length=0,_n.length=0}}else Lp()}}function Lp(){let t=!cr;t&&(cr=!0);let e=[],n=0;try{for(;qt.length>0||Ut.length>0||_n.length>0||t&&dr.length>0;){if(t&&dr.length>0){let s=dr.splice(0);for(let i of s)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw qt.length=0,Ut.length=0,_n.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let o=(qt.length>0?qt:Ut.length>0?Ut:_n).splice(0);for(let s of o)try{s()}catch(i){e.push(i)}}}finally{t&&(cr=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function vt(t,e,n){if(e.length===0)return;if(e.length===1){let c=n(e[0][0]);if(c<3||!zt()){t(e);return}(c>=5?_n:c===4?Ut:qt).push(()=>t(e));return}let r=e.length,o=r,s=r,i=r,a=0;for(;a<r&&n(e[a][0])<3;)a++;for(o=a;a<r&&n(e[a][0])===3;)a++;for(s=a;a<r&&n(e[a][0])===4;)a++;i=a;let u=zt();if(o>0){let c=e.slice(0,o);t(c)}if(s>o){let c=e.slice(o,s);u?qt.push(()=>t(c)):t(c)}if(i>s){let c=e.slice(s,i);u?Ut.push(()=>t(c)):t(c)}if(r>i){let c=e.slice(i,r);u?_n.push(()=>t(c)):t(c)}}var En,cr,qt,Ut,_n,dr,Ne=Ue(()=>{"use strict";En=0,cr=!1,qt=[],Ut=[],_n=[],dr=[]});function $(){return Math.trunc(performance.now()*1e6)}function pe(){return Date.now()*1e6}var ke=Ue(()=>{"use strict"});function pr(t){t.registerMessageType(dt,{tier:0,wireCrossing:!1}),t.registerMessageType(ee,{tier:1,wireCrossing:!1}),t.registerMessageType(He,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(Ie,{tier:2,wireCrossing:!1}),t.registerMessageType(Ge,{tier:2,wireCrossing:!1}),t.registerMessageType(S,{tier:3,wireCrossing:!0}),t.registerMessageType(B,{tier:3,wireCrossing:!0}),t.registerMessageType(_,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(M,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(de,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var Jt,ai=Ue(()=>{"use strict";ie();Jt=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=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}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 bu(t){return Array.isArray(t)?[...t]:[t]}function Ip(t,e){return t.has(e)||t.has("*")}function Yt(t){let e=[];return t((o,s)=>{e.push({kind:"allow",actions:new Set(bu(o)),where:s?.where??(()=>!0)})},(o,s)=>{e.push({kind:"deny",actions:new Set(bu(o)),where:s?.where??(()=>!0)})}),(o,s)=>{let i=!1,a=!1;for(let u of e)Ip(u.actions,s)&&u.where(o)&&(u.kind==="deny"?i=!0:a=!0);return i?!1:a}}function fr(t){return Yt((e,n)=>{for(let r of t){let o=r.actorType==null?null:new Set(Array.isArray(r.actorType)?r.actorType:[r.actorType]),s=r.actorId==null?null:new Set(Array.isArray(r.actorId)?r.actorId:[r.actorId]),i=Object.entries(r.claims??{}),a=u=>{if(o!==null&&!o.has(String(u.type))||s!==null&&!s.has(String(u.id??"")))return!1;for(let[c,d]of i)if(u[c]!==d)return!1;return!0};r.effect==="deny"?n(r.action,{where:a}):e(r.action,{where:a})}})}function mr(t){let e=Pp.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 Je,Pp,Qt=Ue(()=>{"use strict";Je=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}};Pp=["human","llm","wallet","system"]});function ui(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(ui);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=ui(t[n]);return e}return null}function Fp(t){let e=Gp.encode(t),n=e.length,r=n*8,o=n+9+63&-64,s=new Uint8Array(o);s.set(e),s[n]=128;let i=new DataView(s.buffer);i.setUint32(o-4,r>>>0,!1),i.setUint32(o-8,Math.floor(r/4294967296)>>>0,!1);let a=1779033703,u=3144134277,c=1013904242,d=2773480762,l=1359893119,f=2600822924,p=528734635,m=1541459225,h=new Uint32Array(64),g=(b,v)=>b>>>v|b<<32-v;for(let b=0;b<o;b+=64){for(let L=0;L<16;L++)h[L]=i.getUint32(b+L*4,!1);for(let L=16;L<64;L++){let P=h[L-15],C=h[L-2],V=g(P,7)^g(P,18)^P>>>3,ne=g(C,17)^g(C,19)^C>>>10;h[L]=h[L-16]+V+h[L-7]+ne>>>0}let v=a,T=u,w=c,k=d,x=l,R=f,E=p,G=m;for(let L=0;L<64;L++){let P=g(x,6)^g(x,11)^g(x,25),C=x&R^~x&E,V=G+P+C+Dp[L]+h[L]>>>0,ne=g(v,2)^g(v,13)^g(v,22),F=v&T^v&w^T&w,A=ne+F>>>0;G=E,E=R,R=x,x=k+V>>>0,k=w,w=T,T=v,v=V+A>>>0}a=a+v>>>0,u=u+T>>>0,c=c+w>>>0,d=d+k>>>0,l=l+x>>>0,f=f+R>>>0,p=p+E>>>0,m=m+G>>>0}let y=b=>b.toString(16).padStart(8,"0");return y(a)+y(u)+y(c)+y(d)+y(l)+y(f)+y(p)+y(m)}function Ot(t){let e=ui(t??null),n=JSON.stringify(e);return Fp(n).slice(0,16)}function $p(){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 Mn(t,e,n){let r=n?.id??$p();if(t===0)return{id:r,version:0};let s=(n?.hash??Ot)(e);return{id:r,version:0,cid:s,prev:null}}function hr(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}function ci(t){return"cid"in t}var Dp,Gp,oo=Ue(()=>{"use strict";Dp=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]),Gp=new TextEncoder});function wu(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function di(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function so(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function pi(t){if(Ae._isFrozen())throw new Error("configure() called after a node was created \u2014 the default GraphReFlyConfig is frozen. Call configure(...) at application startup, before any node factories run.");t(Ae)}function K(t,e,n){let r=ku(t)?t:[],o=typeof t=="function"?t:typeof e=="function"?e:void 0,s={};return ku(t)?s=(li(e)?e:n)??{}:li(t)?s=t:s=(li(e)?e:n)??{},new Ee(r,o,s)}var vu,Tu,Bp,jp,Ae,Ee,ku,li,xe=Ue(()=>{"use strict";ro();ur();Ne();ke();ai();Qt();ie();oo();vu=()=>{},Tu=100;Bp=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},jp=(t,e,n,r)=>{let o=t;if(o._status==="completed"||o._status==="errored")return;let s=o._cached,i=s===void 0?[xn]:[xn,[S,s]];o._status==="dirty"&&i.push(yt),vt(e,i,o._config.tierOf)},Ae=new Jt({onMessage:Bp,onSubscribe:jp});pr(Ae);ar(Ae);Ee=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??Ae,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??Ot;let o=r.versioning??this._config.defaultVersioning;this._versioningLevel=o,this._versioning=o!=null?Mn(o,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(wu);let s={};for(let[a,u]of Object.entries(r.meta??{})){let c={initial:u,name:`${r.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};r.guard!=null&&(c.guard=r.guard),s[a]=new t([],void 0,c)}Object.freeze(s),this.meta=s,this._hasMeta=Object.keys(s).length>0;let i=this;this._actions={emit(a){i._emit([[S,a]])},down(a){i._emit(so(a))},up(a){i._emitUp(so(a))}},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,i=this._versioning,a=i?.id??n?.id,u=i?.version??0,c=Mn(e,s,{id:a,hash:o});c.version=u,this._versioning=c,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=bt(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=bt(e?.actor),s=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(o,s))throw new Je({actor:o,action:s,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(o,s))throw new Je({actor:o,action:s,nodeName:this.name})}this._lastMutation={actor:o,timestamp_ns:pe()}}down(e,n){let r=so(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[S,e]])}up(e,n){if(this._deps.length===0)return;let r=so(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 u=bt(n);if(!this._guard(u,"observe"))throw new Je({actor:u,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 u of this._deps)di(u);if(this._partial===!1){for(let u of this._deps)if(u.prevData!==void 0||u.dataBatch.length!==0||u.terminal!==void 0||u.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(u){throw this._sinkCount-=1,u}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let i=this._isTerminal;if(this._sinkCount===1&&!i)try{this._activate()}catch(u){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof s=="function")try{s()}catch{}throw u}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let a=!1;return()=>{a||(a=!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=vu,s.unsub=s.node.subscribe(i=>{if(s.unsub===null)return;let a=this._config.tierOf,u=!1;for(let c of i)a(c[0])>=3&&(u=!0),this._config.onMessage(this,c,{direction:"down-in",depIndex:o},this._actions);u&&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 i=s.unsub;s.unsub=null;try{i()}catch{}di(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=wu(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Rn),r.unsub=vu;try{r.unsub=e.subscribe(o=>{if(r.unsub===null)return;let s=this._config.tierOf,i=!1;for(let a of o)s(a[0])>=3&&(i=!0),this._config.onMessage(this,a,{direction:"down-in",depIndex:n},this._actions);i&&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([[M,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([[M,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{}}di(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 i of this._inspectorHooks)i(s)}if(o!==dt){if(o===ee){this._depDirtied(r);return}if(o===He){this._depInvalidated(r),this._emit(rr);return}if(o===Ie||o===Ge){this._emit([n]);return}if(o===de){this._emit(Sn);return}if(o===S)this._depSettledAsData(r,n[1]);else if(o===B)this._depSettledAsResolved(r);else if(o===_)this._depSettledAsTerminal(r,!0);else if(o===M)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(o===S||o===B)&&this._emit([n]),(o===_||o===M)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Rn))}_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(nr),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([[M,e.terminal]]);return}this._autoComplete&&this._deps.every(n=>n.terminal!==void 0)&&this._emit(or)}_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(i){this._emit([[M,this._wrapFnError("cleanup threw",i)]]);return}}else if(e!=null&&typeof e=="object"){let i=e.beforeRun;if(typeof i=="function"){e.beforeRun=void 0;try{i()}catch(a){this._emit([[M,this._wrapFnError("cleanup.beforeRun threw",a)]]);return}}}let n=this._deps.map(i=>i.involvedThisWave?i.dataBatch.length>0?[...i.dataBatch]:[]:void 0),r=this._deps.map(i=>i.prevData);for(let i=0;i<this._deps.length;i++){let a=n[i];a!=null&&a.length>0&&(this._deps[i].prevData=a[a.length-1])}let o=this._deps.map(i=>i.terminal),s={prevData:r,terminalDeps:o,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let i={kind:"run",batchData:n,prevData:r};for(let a of this._inspectorHooks)a(i)}this._isExecutingFn=!0;try{let i=this._fn(n,this._actions,s);if(typeof i=="function")this._cleanup=i;else if(i!=null&&typeof i=="object"){let a=i;(typeof a.beforeRun=="function"||typeof a.deactivate=="function"||typeof a.invalidate=="function")&&(this._cleanup=i)}}catch(i){this._emit([[M,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>Tu?(this._rerunDepth=0,this._emit([[M,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${Tu} \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"?[yt,e[0]]:e;let r=!0,o=!1,s=!1,i=-1;for(let u of e){let c=n(u[0]);c<i&&(r=!1),c===3&&(o=!0),u[0]===ee&&(s=!0),i=c}let a=e;if(!r){let u=e.map((c,d)=>({m:c,i:d,tier:n(c[0])}));u.sort((c,d)=>c.tier-d.tier||c.i-d.i),a=u.map(c=>c.m)}if(o&&!s&&this._status!=="dirty"){let u=0;for(;u<a.length&&n(a[u][0])===0;)u++;return u===0?[yt,...a]:[...a.slice(0,u),yt,...a.slice(u)]}return a}_emit(e){if(e.length===0)return;for(let a=0;a<e.length;a++){let u=e[a];if(u[0]===M&&u[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 a=e.filter(u=>u[0]===de||u[0]===He);if(a.length===0)return;n=a}n=this._frameBatch(n);let o=null;for(let a=0;a<n.length;a++){let u=n[a],c=u[0];if(c!==Ie&&c!==Ge){o?.push(u);continue}if(u.length<2)throw new Error(`Node "${this.name}": [[${c===Ie?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let d=!0;if(this._pausable!==!1){let l=u[1];if(c===Ie)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))d=!1;else if(this._pauseLocks.delete(l),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let f=this._pauseBuffer;this._pauseBuffer=[],this._emit(f)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}d?o?.push(u):o==null&&(o=n.slice(0,a))}if(o!=null){if(o.length===0)return;n=o}if(this._hasMeta&&n.some(a=>a[0]===de))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(Sn)}catch{}let{finalMessages:s,equalsError:i}=this._updateState(n);if(s.length>0&&this._config.inspectorEnabled){let a=this._config.globalInspector;if(a!=null)try{a({kind:"emit",node:this,messages:s})}catch{}}if(s.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let a=this._config.tierOf,u=[];for(let c of s)a(c[0])===3?this._pauseBuffer.push(c):u.push(c);u.length>0&&this._dispatchOrAccumulate(u)}else this._dispatchOrAccumulate(s);i!=null&&this._emit([[M,i]])}_updateState(e){let n=this._config.tierOf,r,o,s=-1,i=0;for(let d of e)n(d[0])===3&&i++;let a=i<=1,u=-1;if(this._versioning!=null&&i>1){for(let d=e.length-1;d>=0;d--)if(e[d][0]===S){u=d;break}}for(let d=0;d<e.length;d++){let l=e[d],f=l[0];if(f===S){if(l.length>=2){let p=!1;if(a&&this._cached!==void 0)try{p=this._equals(this._cached,l[1])}catch(m){o=this._wrapFnError("equals threw",m),s=d;break}if(p){r==null&&(r=e.slice(0,d)),r.push(kn),this._status="resolved";continue}this._cached=l[1],this._versioning!=null&&(u<0||d===u)&&hr(this._versioning,l[1],this._hashFn)}this._status="settled",r?.push(l)}else if(r?.push(l),f===ee)this._status="dirty";else if(f===B)this._status="resolved";else if(f===_)this._status="completed";else if(f===M)this._status="errored";else if(f===He){this._cached=void 0,this._status="dirty";let p=this._cleanup;if(typeof p=="function"){this._cleanup=void 0;try{p()}catch{}}else if(p!=null&&typeof p=="object"){let m=p.invalidate;if(typeof m=="function")try{m()}catch{}}}else f===de&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let c=s>=0?r??e.slice(0,s):r??e;return o!=null?{finalMessages:c,equalsError:o}:{finalMessages:c}}_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(yu()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],lr(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}vt(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);vt(this._deliverToSinks,n,this._config.tierOf)}},ku=t=>Array.isArray(t),li=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function N(t,e){return K([],{...e,initial:t})}function W(t,e){return K((r,o,s)=>t(o,s)??void 0,{describeKind:"producer",...e})}function O(t,e,n){return K(t,(o,s,i)=>{let a=o.map((u,c)=>u!=null&&u.length>0?u.at(-1):i.prevData[c]);s.emit(e(a,i))},{describeKind:"derived",...n})}function fe(t,e,n){return K(t,(o,s,i)=>{let a=o.map((u,c)=>u!=null&&u.length>0?u.at(-1):i.prevData[c]);return e(a,s,i)??void 0},{describeKind:"effect",...n})}function gr(t,e,n){let r=new Map;return t.forEach((o,s)=>{r.set(o,s)}),O(t,(o,s)=>e(a=>{let u=r.get(a);if(u==null)throw new Error(`dynamicNode: untracked dep "${a.name??"<unnamed>"}"`);return o[u]},s),n)}function Xt(t,e){let n,r=new Map,o=(s,i,a)=>{let u=!1,c=d=>{let l=r.get(d);if(l!==void 0){if(l<s.length){let p=s[l];return p!=null&&p.length>0?p.at(-1):a.prevData[l]}return d.cache}u=!0;let f=n._addDep(d);return r.set(d,f),d.cache};try{let d=t(c,a);u||(i.emit(d),a.store.__autoTrackLastDiscoveryError!=null&&delete a.store.__autoTrackLastDiscoveryError)}catch(d){if(!u)throw d;a.store.__autoTrackLastDiscoveryError=d}};return n=new Ee([],o,{describeKind:"derived",...e}),n}function fi(t,...e){let n=t;for(let r of e)n=r(n);return n}var oe=Ue(()=>{"use strict";xe()});function vr(t,e,n){let r=new Set;for(let o of t.split(",")){let[s,i]=o.split("/"),a=i?Number.parseInt(i,10):1;if(Number.isNaN(a)||a<1)throw new Error(`Invalid cron step: ${o}`);let u,c;if(s==="*")u=e,c=n;else if(s.includes("-")){let[d,l]=s.split("-");u=Number.parseInt(d,10),c=Number.parseInt(l,10)}else u=Number.parseInt(s,10),c=u;if(Number.isNaN(u)||Number.isNaN(c))throw new Error(`Invalid cron field: ${t}`);if(u<e||c>n)throw new Error(`Cron field out of range: ${t} (${e}-${n})`);if(u>c)throw new Error(`Invalid cron range: ${u}-${c} in ${t}`);for(let d=u;d<=c;d+=a)r.add(d)}return r}function fo(t){let e=t.trim().split(/\s+/);if(e.length!==5)throw new Error(`Invalid cron: expected 5 fields, got ${e.length}`);return{minutes:vr(e[0],0,59),hours:vr(e[1],0,23),daysOfMonth:vr(e[2],1,31),months:vr(e[3],1,12),daysOfWeek:vr(e[4],0,6)}}function mo(t,e){return t.minutes.has(e.getMinutes())&&t.hours.has(e.getHours())&&t.daysOfMonth.has(e.getDate())&&t.months.has(e.getMonth()+1)&&t.daysOfWeek.has(e.getDay())}var gi=Ue(()=>{"use strict"});var Fu={};he(Fu,{NS_PER_MS:()=>Fe,NS_PER_SEC:()=>Qe,constant:()=>ho,decorrelatedJitter:()=>vo,exponential:()=>yo,fibonacci:()=>bo,linear:()=>go,resolveBackoffPreset:()=>Ct,withMaxAttempts:()=>yi});function en(t){return t<0?0:t}function Yp(t,e){return e==="none"?t:e==="full"?Math.random()*t:t/2+Math.random()*(t/2)}function Qp(t,e){return t+Math.random()*(e-t)}function ho(t){let e=en(t);return()=>e}function go(t,e){let n=en(t),r=e===void 0?n:en(e);return o=>n+r*Math.max(0,o)}function yo(t){let e=en(t?.baseNs??1e8),n=t?.factor!==void 0&&t.factor<1?1:t?.factor??2,r=en(t?.maxDelayNs??30*1e9),o=t?.jitter??"none";return s=>{let i;if(e===0)i=0;else if(n===1)i=e;else{let a=r/e,u=1;for(let c=0;c<Math.max(0,s);c++){if(u>=a){u=a;break}u*=n}i=e*u,i>r&&(i=r)}return Yp(i,o)}}function bo(t=100*1e6,e=30*1e9){let n=en(t),r=en(e);function o(s){if(s<=0)return 1;let i=1,a=2;for(let u=1;u<s;u++){let c=i+a;i=a,a=c}return a}return s=>{let i=o(s)*n;return i<=r?i:r}}function vo(t=100*1e6,e=30*1e9){return(n,r,o)=>{let i=Math.min(e,(o??t)*3);return Qp(t,i)}}function yi(t,e){return(n,r,o)=>n>=e?null:t(n,r,o)}function Ct(t){if(t==="constant")return ho(1*1e9);if(t==="linear")return go(1*1e9);if(t==="exponential")return yo();if(t==="fibonacci")return bo();if(t==="decorrelatedJitter")return vo();throw new Error(`Unknown backoff preset: "${String(t)}". Use one of: constant, linear, exponential, fibonacci, decorrelatedJitter`)}var Fe,Qe,Gn=Ue(()=>{"use strict";Fe=1e6,Qe=1e9});var _e,pt=Ue(()=>{"use strict";_e=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 Bu={};he(Bu,{CircuitOpenError:()=>st,RateLimiterOverflowError:()=>tn,TimeoutError:()=>nn,circuitBreaker:()=>ft,fallback:()=>jn,rateLimiter:()=>Bn,retry:()=>Fn,retrySource:()=>At,timeout:()=>Vn,tokenBucket:()=>Lt,withBreaker:()=>$n,withStatus:()=>It});function rn(t){return{describeKind:"derived",...t}}function Xp(t){return t<0?0:t}function To(t){return t[1]}function $u(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,e){let n=e?.count,r=e?.backoff,o=n!==void 0?n:r===void 0?0:2147483647;if(o<0)throw new RangeError("retry count must be >= 0");let s=r===void 0?null:typeof r=="string"?Ct(r):r;return W(i=>{let a=0,u=!1,c=null,d,l=new _e;function f(){d?.(),d=void 0}function p(h){if(u)return;if(a>=o){f(),i.down([[M,h]]);return}let g=s===null?0:s(a,h,c);if(g==null){f(),i.down([[M,h]]);return}let y;try{y=$u(g)}catch{f(),i.down([[M,h]]);return}c=y,a+=1,f();let b=y>0?y/1e6:1;l.start(b,()=>{u||m()})}function m(){l.cancel(),f(),d=t.subscribe(h=>{if(!u)for(let g of h){let y=g[0];if(y===ee)i.down([[ee]]);else if(y===S)a=0,c=null,i.emit(g[1]);else if(y===B)i.down([[B]]);else if(y===_)f(),i.down([[_]]);else if(y===M){p(To(g));return}else i.down([g])}})}return m(),()=>{u=!0,l.cancel(),f()}},{...rn(),initial:t.cache})}function At(t,e){let n=e?.count,r=e?.backoff,o=n!==void 0?n:r===void 0?0:2147483647;if(o<0)throw new RangeError("retry count must be >= 0");let s=r===void 0?null:typeof r=="string"?Ct(r):r;return W(i=>{let a=0,u=!1,c=null,d,l=new _e;function f(){d?.(),d=void 0}function p(h){if(u)return;if(a>=o){f(),i.down([[M,h]]);return}let g=s===null?0:s(a,h,c);if(g==null){f(),i.down([[M,h]]);return}let y;try{y=$u(g)}catch{f(),i.down([[M,h]]);return}c=y,a+=1,f();let b=y>0?y/1e6:1;l.start(b,()=>{u||m()})}function m(){l.cancel(),f();let h;try{h=t()}catch(g){p(g);return}d=h.subscribe(g=>{if(!u)for(let y of g){let b=y[0];if(b===ee)i.down([[ee]]);else if(b===S)a=0,c=null,i.emit(y[1]);else if(b===B)i.down([[B]]);else if(b===_)f(),i.down([[_]]);else if(b===M){p(To(y));return}else i.down([y])}})}return m(),()=>{u=!0,l.cancel(),f()}},{...rn(),initial:e?.initial})}function ft(t){let e=Math.max(1,t?.failureThreshold??5),n=Xp(t?.cooldownNs??30*1e9),r=t?.cooldown??null,o=Math.max(1,t?.halfOpenMax??1),s=t?.now??$,i="closed",a=0,u=0,c=0,d=n,l=0;function f(){if(!r)return n;let h=r(u);return h!==null?h:n}function p(){i="open",d=f(),c=s(),l=0}return{canExecute(){return i==="closed"?!0:i==="open"?s()-c>=d?(i="half-open",l=1,!0):!1:l<o?(l++,!0):!1},recordSuccess(){i==="half-open"?(i="closed",a=0,u=0):i==="closed"&&(a=0)},recordFailure(h){if(i==="half-open"){u++,p();return}i==="closed"&&(a++,a>=e&&p())},get state(){return i},get failureCount(){return a},reset(){i="closed",a=0,u=0,l=0}}}function $n(t,e){let n=e?.onOpen??"skip";return r=>{let o=K([],(s,i)=>{function a(){o.meta.breakerState.down([[S,t.state]])}let u=r.subscribe(c=>{for(let d of c){let l=d[0];l===ee?i.down([[ee]]):l===S?t.canExecute()?(a(),i.emit(d[1])):(a(),n==="error"?i.down([[M,new st]]):i.down([[B]])):l===B?i.down([[B]]):l===_?(t.recordSuccess(),a(),i.down([[_]])):l===M?(t.recordFailure(To(d)),a(),i.down([d])):i.down([d])}});return a(),u},{...rn(),meta:{breakerState:t.state},completeWhenDepsComplete:!1,initial:r.cache});return{node:o,breakerState:o.meta.breakerState}}}function Lt(t,e){if(t<=0)throw new RangeError("capacity must be > 0");if(e<0)throw new RangeError("refillPerSecond must be >= 0");let n=t,r=$();function o(s){if(e>0){let i=s-r;n=Math.min(t,n+i/1e9*e)}r=s}return{available(){return o($()),n},tryConsume(s=1){if(s<=0)return!0;let i=$();return o(i),n>=s?(n-=s,!0):!1},putBack(s=1){s<=0||(o($()),n=Math.min(t,n+s))}}}function Bn(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&&o<1)throw new RangeError("maxBuffer must be >= 1");let s=e.onOverflow??"drop-newest",i=n*1e9/r;return W(a=>{let u=Lt(n,i),c=[],d=new _e,l=!1,f=1e9/i;function p(){for(;c.length>0;)if(u.tryConsume(1))a.emit(c.shift());else{d.start(Math.max(1,f/1e6),p);return}}let m=t.subscribe(h=>{for(let g of h){if(l)return;let y=g[0];if(y===ee)a.down([[ee]]);else if(y===S){if(o!==void 0&&c.length>=o){if(s!=="drop-newest")if(s==="drop-oldest")c.shift(),c.push(g[1]);else{l=!0,d.cancel(),c.length=0,a.down([[M,new tn(o)]]);return}}else c.push(g[1]);p()}else if(y===B)a.down([[B]]);else if(y===_)l=!0,d.cancel(),c.length=0,a.down([[_]]);else if(y===M)l=!0,d.cancel(),c.length=0,a.down([g]);else if(y===de){l=!0,d.cancel(),c.length=0,a.down([g]);return}else a.down([g])}});return()=>{l=!0,d.cancel(),m()}},{...rn(),initial:t.cache})}function It(t,e){let n=e?.initialStatus??"pending",r=K([],(o,s)=>{let i=n;return r.meta.status.down([[S,n]]),r.meta.error.down([[S,null]]),t.subscribe(u=>{for(let c of u){let d=c[0];if(d===ee)s.down([[ee]]);else if(d===S)i==="errored"?te(()=>{r.meta.error.down([[S,null]]),r.meta.status.down([[S,"active"]])}):r.meta.status.down([[S,"active"]]),i="active",s.emit(c[1]);else if(d===B)s.down([[B]]);else if(d===_)r.meta.status.down([[S,"completed"]]),i="completed",s.down([[_]]);else if(d===M){let l=To(c);te(()=>{r.meta.error.down([[S,l]]),r.meta.status.down([[S,"errored"]])}),i="errored",s.down([c])}else s.down([c])}})},{...rn(),meta:{status:n,error:null},completeWhenDepsComplete:!1,resubscribable:!0,initial:t.cache});return{node:r,status:r.meta.status,error:r.meta.error}}function Zp(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function ef(t){return t!=null&&typeof t.then=="function"}function tf(t){return t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function"}function jn(t,e){return W(n=>{let r,o;function s(){o?.(),o=void 0,Zp(e)||ef(e)||tf(e)?r=re(e).subscribe(a=>{n.down(a)}):(n.emit(e),n.down([[_]]))}return o=t.subscribe(i=>{for(let a of i){let u=a[0];if(u===ee)n.down([[ee]]);else if(u===S)n.emit(a[1]);else if(u===B)n.down([[B]]);else if(u===_)n.down([[_]]);else if(u===M){s();return}else if(u===de){r?.(),n.down([a]);return}else n.down([a])}}),()=>{o?.(),r?.()}},{...rn(),initial:t.cache})}function Vn(t,e){if(e<=0)throw new RangeError("timeoutNs must be > 0");return W(n=>{let r=!1,o=new _e;function s(){let a=e/1e6;o.start(a,()=>{r||(r=!0,i(),n.down([[M,new nn(e)]]))})}let i=t.subscribe(a=>{for(let u of a){if(r)return;let c=u[0];if(c===ee)n.down([[ee]]);else if(c===S)s(),n.emit(u[1]);else if(c===B)n.down([[B]]);else if(c===_){o.cancel(),r=!0,n.down([[_]]);return}else if(c===M){o.cancel(),r=!0,n.down([u]);return}else if(c===de){o.cancel(),r=!0,n.down([u]);return}else n.down([u])}});return s(),()=>{r=!0,o.cancel(),i()}},{...rn(),initial:t.cache})}var st,tn,nn,Tt=Ue(()=>{"use strict";Ne();ke();ie();xe();oe();Gn();Re();pt();st=class extends Error{name="CircuitOpenError";constructor(){super("Circuit breaker is open")}};tn=class extends Error{name="RateLimiterOverflowError";constructor(e){super(`rateLimiter buffer overflow (maxBuffer=${e})`)}};nn=class extends Error{name="TimeoutError";constructor(e){super(`Timed out after ${e/1e6}ms`)}}});function Ze(t){return{describeKind:"producer",...t}}function vi(t){return/[\\^$+?.()|[\]{}]/.test(t)?`\\${t}`:t}function Vu(t){let e="^";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="*"){t[n+1]==="*"?(e+=".*",n+=1):e+="[^/]*";continue}e+=vi(r)}return e+="$",new RegExp(e)}function Ku(t,e){for(let n of e)if(n.test(t))return!0;return!1}function nf(t,e){let n=K([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[B]]);return}for(let a of i)s.emit(a)},{describeKind:"derived",initial:t.cache}),r=n.subscribe.bind(n);return n.subscribe=(o,s)=>(e(o),r(o,s)),n}function et(t,e){let{signal:n,period:r,...o}=e??{};return W(s=>{let i=!1,a=0,u,c,d=()=>{i=!0,u!==void 0&&clearTimeout(u),c!==void 0&&clearInterval(c),n?.removeEventListener("abort",f)},l=()=>{i||(r!=null?(s.emit(a++),c=setInterval(()=>{i||s.emit(a++)},r)):(i=!0,n?.removeEventListener("abort",f),s.emit(a++),s.down([[_]])))},f=()=>{i||(d(),s.down([[M,n.reason]]))};if(n?.aborted){f();return}return u=setTimeout(l,t),n?.addEventListener("abort",f,{once:!0}),d},Ze(o))}function Hu(t){let{signal:e,...n}=t??{};return W(r=>{let o=!1,s,i,a=!1,u=!1,c=typeof requestAnimationFrame=="function"?requestAnimationFrame:void 0,d=typeof cancelAnimationFrame=="function"?cancelAnimationFrame:void 0,l=typeof document<"u"?document:void 0,f=()=>{s!==void 0&&d&&d(s),i!==void 0&&clearTimeout(i),s=void 0,i=void 0},p=()=>{o=!0,f(),a&&(e?.removeEventListener("abort",m),a=!1),u&&l&&(l.removeEventListener("visibilitychange",y),u=!1)},m=()=>{o||(p(),r.down([[M,e.reason]]))},h=b=>{o||(r.emit(b),g())},g=()=>{o||(c&&(!l||l.visibilityState!=="hidden")?s=c(h):i=setTimeout(()=>h(performance.now()),16))},y=()=>{o||(f(),g())};return e?.aborted?(m(),p):(e?.addEventListener("abort",m,{once:!0}),a=e!==void 0,l&&c&&(l.addEventListener("visibilitychange",y),u=!0),g(),p)},Ze(n))}function ko(t,e){let n=fo(t),{tickMs:r,output:o,...s}=e??{},i=r??6e4,a=o==="date";return W(u=>{let c=-1,d=()=>{let f=new Date,p=f.getFullYear()*1e8+(f.getMonth()+1)*1e6+f.getDate()*1e4+f.getHours()*100+f.getMinutes();p!==c&&mo(n,f)&&(c=p,u.emit(a?f:pe()))};d();let l=setInterval(d,i);return()=>clearInterval(l)},{...Ze(s),name:s.name??`cron:${t}`})}function Wu(t,e,n){let{capture:r,passive:o,once:s,...i}=n??{};return W(a=>{let u=d=>{a.emit(d)},c={capture:r,passive:o,once:s};return t.addEventListener(e,u,c),()=>t.removeEventListener(e,u,c)},Ze(i))}function xo(t,e){return W(n=>{let r=!1;try{for(let o of t){if(r)return;n.emit(o)}r||n.down([[_]])}catch(o){r||n.down([[M,o]])}return()=>{r=!0}},Ze(e))}function rf(t){return t!=null&&typeof t.then=="function"}function Ti(t,e){let{signal:n,...r}=e??{};return W(o=>{let s=!1,i=()=>{s||(s=!0,o.down([[M,n.reason]]))};if(n?.aborted){i();return}return n?.addEventListener("abort",i,{once:!0}),Promise.resolve(t).then(a=>{s||(s=!0,n?.removeEventListener("abort",i),o.emit(a),o.down([[_]]))},a=>{s||(s=!0,n?.removeEventListener("abort",i),o.down([[M,a]]))}),()=>{s=!0,n?.removeEventListener("abort",i)}},Ze(r))}function wi(t,e){let{signal:n,...r}=e??{};return W(o=>{let s=new AbortController,i=()=>s.abort(n?.reason);n?.aborted?s.abort(n.reason):n?.addEventListener("abort",i,{once:!0});let a=n??s.signal,u=!1,c=t[Symbol.asyncIterator](),d=()=>{u||a.aborted||Promise.resolve(c.next()).then(l=>{if(!(u||a.aborted)){if(l.done){o.down([[_]]);return}o.emit(l.value),d()}},l=>{!u&&!a.aborted&&o.down([[M,l]])})};return d(),()=>{u=!0,n?.removeEventListener("abort",i),s.abort(),Promise.resolve(c.return?.()).catch(()=>{})}},Ze(r))}function of(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function re(t,e){if(of(t))return t;if(rf(t))return Ti(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return wi(t,e);if(typeof n[Symbol.iterator]=="function")return xo(t,e)}return ki(t)}function ki(...t){return xo(t,void 0)}function qu(t){return W(e=>{e.down([[_]])},Ze(t))}function Uu(t){return W(()=>{},Ze(t))}function zu(t,e){return W(n=>{n.down([[M,t]])},Ze(e))}function Pt(t,e,n){return K([t],(o,s)=>{let i=o[0];if(i!=null&&i.length>0)for(let a of i)e(a)},{describeKind:"effect",...n}).subscribe(()=>{})}function Ju(t,e){return K([t],(n,r,o)=>{o.store.buf||(o.store.buf=[]);let s=o.store.buf,i=n[0];if(i!=null&&i.length>0)for(let a of i)s.push(a);if(o.terminalDeps[0]===!0){r.emit([...s]),r.down([[_]]);return}(i==null||i.length===0)&&r.down([[B]])},{describeKind:"derived",completeWhenDepsComplete:!1,...e})}function Yu(t,e){return W(n=>t.subscribe(r=>{n.down(r)}),{...Ze(e),initial:t.cache})}function Ro(t,e,n){if(e<1)throw new RangeError("replay expects bufferSize >= 1");let r=[],o=W(s=>t.subscribe(i=>{for(let a of i)a[0]===S&&(r.push(a[1]),r.length>e&&r.shift());s.down(i)}),{...Ze(n),initial:t.cache});return nf(o,s=>{for(let i of r)s([[S,i]])})}function Qu(t,e){return Ro(t,1,e)}function Kn(t){return new Promise((e,n)=>{let r=!1,o=!1,s;s=t.subscribe(i=>{for(let a of i){if(r)return;if(a[0]===S){r=!0,e(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===M){r=!0,n(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===_){r=!0,n(new Error("completed without DATA")),s?(s(),s=void 0):o=!0;return}}}),o&&(s?.(),s=void 0)})}function wo(t,e){return new Promise((n,r)=>{let o=!1,s=!1,i;i=t.subscribe(a=>{for(let u of a){if(o)return;if(u[0]===S){let c=u[1];if(e(c)){o=!0,n(c),i?(i(),i=void 0):s=!0;return}}if(u[0]===M){o=!0,r(u[1]),i?(i(),i=void 0):s=!0;return}if(u[0]===_){o=!0,r(new Error("completed without matching value")),i?(i(),i=void 0):s=!0;return}}}),s&&(i?.(),i=void 0)})}async function So(t,e){let n=e?.predicate??(o=>o!=null);if(e?.timeoutMs==null||e.timeoutMs<=0)return await wo(t,n);if(bi===void 0){let[o,s]=await Promise.all([Promise.resolve().then(()=>(Tt(),Bu)),Promise.resolve().then(()=>(Gn(),Fu))]);bi=o.timeout,ju=s.NS_PER_MS}let r=bi(t,e.timeoutMs*ju);return await wo(r,n)}function se(t){return t.subscribe(()=>{})}function xi(t){let e=N(0);return{node:e,increment(){let n=e.cache??0;return n>=t?!1:(e.down([[ee],[S,n+1]]),!0)},get(){return e.cache??0},atCap(){return(e.cache??0)>=t}}}var bi,ju,Xu,Re=Ue(()=>{"use strict";ke();ie();xe();oe();gi();Xu=Ro});var Cy={};he(Cy,{COMPLETE:()=>_,COMPLETE_MSG:()=>eo,COMPLETE_ONLY_BATCH:()=>or,CircuitOpenError:()=>st,DATA:()=>S,DEFAULT_ACTOR:()=>lt,DIRTY:()=>ee,DIRTY_MSG:()=>yt,DIRTY_ONLY_BATCH:()=>Rn,ENVELOPE_VERSION:()=>Nn,ERROR:()=>M,GRAPH_META_SEGMENT:()=>je,Graph:()=>q,GraphReFlyConfig:()=>Jt,GuardDenied:()=>Je,INVALIDATE:()=>He,INVALIDATE_MSG:()=>Zr,INVALIDATE_ONLY_BATCH:()=>rr,JsonCodec:()=>no,NS_PER_MS:()=>Fe,NS_PER_SEC:()=>Qe,NativeIndexBackend:()=>Ir,NativeListBackend:()=>Pr,NativeLogBackend:()=>Rr,NativeMapBackend:()=>Cr,NativePubSubBackend:()=>Lr,NodeImpl:()=>Ee,PAUSE:()=>Ie,RESOLVED:()=>B,RESOLVED_MSG:()=>kn,RESOLVED_ONLY_BATCH:()=>nr,RESUME:()=>Ge,RateLimiterOverflowError:()=>tn,ResettableTimer:()=>_e,SIZEOF_OVERHEAD:()=>Le,SIZEOF_SYMBOL:()=>Lo,SNAPSHOT_VERSION:()=>it,SNAPSHOT_WIRE_VERSION:()=>Xr,START:()=>dt,START_MSG:()=>xn,SurfaceError:()=>we,TEARDOWN:()=>de,TEARDOWN_MSG:()=>to,TEARDOWN_ONLY_BATCH:()=>Sn,TimeoutError:()=>nn,accessHintForGuard:()=>mr,accountability:()=>_s,advanceVersion:()=>hr,ai:()=>Ss,asSurfaceError:()=>Us,audit:()=>Qc,autoTrackNode:()=>Xt,awaitSettled:()=>So,batch:()=>te,buffer:()=>Xc,bufferCount:()=>Zc,bufferTime:()=>td,cached:()=>Qu,cascadingCache:()=>cl,catchError:()=>ld,checkpointToRedis:()=>tl,checkpointToS3:()=>el,circuitBreaker:()=>ft,combine:()=>Ki,combineLatest:()=>ud,compat:()=>ji,concat:()=>Hc,concatMap:()=>Uc,configure:()=>pi,constant:()=>ho,core:()=>Oi,cqrs:()=>Bo,createDagCborCodec:()=>oi,createDagCborZstdCodec:()=>si,createGraph:()=>Zn,createTransport:()=>$t,createVersioning:()=>Mn,createWatermarkController:()=>Hn,csvRows:()=>Dd,debounce:()=>Wi,debounceTime:()=>cd,decodeEnvelope:()=>ir,decorrelatedJitter:()=>vo,defaultConfig:()=>Ae,defaultHash:()=>Ot,delay:()=>Jc,deleteSnapshot:()=>ei,demoShell:()=>Os,derived:()=>O,deserializeError:()=>fn,dictStorage:()=>vl,diffForWAL:()=>Go,diffSnapshots:()=>Xs,distill:()=>Zo,distinctUntilChanged:()=>jc,domainTemplates:()=>Ls,downWithBatch:()=>vt,dynamicNode:()=>gr,effect:()=>fe,elementAt:()=>$c,empty:()=>qu,encodeEnvelope:()=>sr,escapeRegexChar:()=>vi,exhaustMap:()=>qc,explainPath:()=>kr,exponential:()=>yo,externalBundle:()=>Yo,externalProducer:()=>cn,extra:()=>na,fallback:()=>jn,fibonacci:()=>bo,filter:()=>ut,find:()=>Fc,first:()=>Qo,firstValueFrom:()=>Kn,firstWhere:()=>wo,flatMap:()=>zc,forEach:()=>Pt,fromAny:()=>re,fromAsyncIter:()=>wi,fromCSV:()=>Pd,fromClickHouseWatch:()=>Bd,fromCron:()=>ko,fromDrizzle:()=>il,fromEvent:()=>Wu,fromHTTP:()=>Yi,fromHTTPPoll:()=>wd,fromHTTPStream:()=>Td,fromIter:()=>xo,fromKafka:()=>Cd,fromKysely:()=>al,fromMCP:()=>Rd,fromNATS:()=>Kd,fromNDJSON:()=>$d,fromOTel:()=>Sd,fromPrisma:()=>sl,fromPrometheus:()=>Od,fromPromise:()=>Ti,fromPulsar:()=>jd,fromRabbitMQ:()=>Wd,fromRaf:()=>Hu,fromRedisStream:()=>Ld,fromSSE:()=>vd,fromSqlite:()=>nl,fromSqliteCursor:()=>rl,fromStatsD:()=>_d,fromSyslog:()=>Nd,fromTimer:()=>et,fromWebSocket:()=>Ji,fromWebSocketReconnect:()=>xd,fromWebhook:()=>pd,globToRegExp:()=>Vu,graph:()=>Ai,graphProfile:()=>an,graphspec:()=>Is,guarded:()=>Ds,harness:()=>$s,interval:()=>od,isBatching:()=>zt,isV1:()=>ci,jobQueue:()=>Vs,jotai:()=>io,keepalive:()=>se,last:()=>Gc,layout:()=>Ws,lens:()=>Hs,linear:()=>go,listSnapshots:()=>Zs,lru:()=>Zi,map:()=>Er,matchesAnyPattern:()=>Ku,matchesCron:()=>mo,memory:()=>Rs,memoryStorage:()=>Gr,merge:()=>mt,mergeMap:()=>Hi,mermaidLiveUrl:()=>Do,messaging:()=>bs,monotonicNs:()=>$,nameToSignal:()=>ln,nanostores:()=>lo,ndjsonRows:()=>Gd,nestjs:()=>Vo,never:()=>Uu,node:()=>K,normalizeActor:()=>bt,of:()=>ki,orchestration:()=>vs,pairwise:()=>Vc,parseCron:()=>fo,parsePrometheusText:()=>Qi,parseStatsD:()=>Md,parseSyslog:()=>Ed,patterns:()=>su,pausable:()=>id,pipe:()=>fi,policy:()=>Yt,policyFromRules:()=>fr,producer:()=>W,pubsub:()=>fl,race:()=>Wc,rateLimiter:()=>Bn,reachable:()=>un,react:()=>Ko,reactiveCounter:()=>xi,reactiveIndex:()=>gl,reactiveList:()=>es,reactiveLog:()=>Ve,reactiveMap:()=>tt,reactiveSink:()=>$e,reduce:()=>Ic,reduction:()=>As,refine:()=>Fs,registerBuiltinCodecs:()=>ar,registerBuiltins:()=>pr,repeat:()=>sd,replay:()=>Ro,replayWAL:()=>ii,rescue:()=>Mr,resilientPipeline:()=>qs,resolveBackoffPreset:()=>Ct,resolveDescribeFields:()=>wt,restoreSnapshot:()=>Qs,retry:()=>Fn,retrySource:()=>At,runReduction:()=>zs,sample:()=>Yc,saveSnapshot:()=>Ys,scan:()=>Lc,serializeError:()=>pn,share:()=>Yu,shareReplay:()=>Xu,signalToName:()=>Ft,signals:()=>Wo,singleFromAny:()=>ts,singleNodeFromAny:()=>yl,sizeof:()=>xr,skip:()=>Vi,solid:()=>qo,sortJsonValue:()=>Dr,stableJsonString:()=>bl,state:()=>N,stratify:()=>Fr,surface:()=>ti,svelte:()=>Uo,switchMap:()=>be,take:()=>_r,takeUntil:()=>Dc,takeWhile:()=>Pc,tap:()=>Bc,throttle:()=>qi,throttleTime:()=>dd,throwError:()=>zu,timeout:()=>Vn,toArray:()=>Ju,toCSV:()=>Ud,toClickHouse:()=>zd,toFile:()=>Xi,toHTTP:()=>fd,toKafka:()=>Ad,toLoki:()=>Xd,toMongo:()=>Qd,toNATS:()=>Hd,toObservable:()=>po,toPostgres:()=>Yd,toPulsar:()=>Vd,toRabbitMQ:()=>qd,toReadableStream:()=>bd,toRedisStream:()=>Id,toS3:()=>Jd,toSSE:()=>gd,toSSEBytes:()=>yd,toSqlite:()=>ol,toTempo:()=>Zd,toWebSocket:()=>kd,tokenBucket:()=>Lt,validateGraphObservability:()=>Ci,valve:()=>ad,verifiable:()=>pl,version:()=>Oy,vue:()=>zo,wallClockNs:()=>pe,watchTopologyTree:()=>kt,window:()=>rd,windowCount:()=>ed,windowTime:()=>nd,withBreaker:()=>$n,withLatestFrom:()=>dn,withMaxAttempts:()=>yi,withStatus:()=>It,workerBridge:()=>ea,workerSelf:()=>ta,zip:()=>Kc,zustand:()=>Jo});module.exports=_p(Cy);var ji={};he(ji,{jotai:()=>io,nanostores:()=>lo,nestjs:()=>Vo,react:()=>Ko,signals:()=>Wo,solid:()=>qo,svelte:()=>Uo,vue:()=>zo,zustand:()=>Jo});var io={};he(io,{atom:()=>Vp});ie();oe();function Vp(t,e,n){if(typeof t=="function"){let r=t;return typeof e=="function"?xu(r,e,n):xu(r,void 0,e)}return Kp(t,e)}function yr(t){let e=t.cache,n;if(t.subscribe(o=>{for(let[s,i]of o)s===S&&(e=i),s===M&&(n=i)})(),n)throw n;return e}function Kp(t,e){let n=N(t,{...e,resubscribable:!0,resetOnTeardown:!0});return{get:()=>n.status==="sentinel"?yr(n):n.cache,set:r=>n.emit(r),update:r=>{let o=n.status==="sentinel"?yr(n):n.cache;n.emit(r(o))},subscribe:r=>{let o=!0;return n.subscribe(s=>{for(let[i,a]of s)if(i===S){if(o){o=!1;continue}r(a)}})},meta:n.meta,_node:n}}function xu(t,e,n){let r=Xt(s=>t(i=>{let a=i._node;return a.status==="sentinel"&&yr(a),s(a)}),{...n,resubscribable:!0,resetOnTeardown:!0}),o={get:()=>r.status==="sentinel"?yr(r):r.cache,subscribe:s=>{let i=!0;return r.subscribe(a=>{for(let[u,c]of a)if(u===S){if(i){i=!1;continue}s(c)}})},meta:r.meta,_node:r};if(e){let s=u=>u.get(),i=(u,c)=>u.set(c),a=o;return a.set=u=>e(s,i,u),a.update=u=>{let c=r.status==="sentinel"?yr(r):r.cache;return e(s,i,u(c))},a}return o}var lo={};he(lo,{action:()=>Jp,atom:()=>Hp,computed:()=>Wp,getValue:()=>Up,map:()=>qp,onMount:()=>zp,onStart:()=>Nu,onStop:()=>Eu});Ne();ie();oe();var uo=new WeakMap,co=new WeakMap;function ao(t,e){let n=e.get(t);if(n)for(let r of n)r()}function mi(t,e={}){let n=0;return{...e,get:()=>Su(t),subscribe:o=>{n===0&&ao(t,uo),n++;let s=t.subscribe(i=>{for(let[a,u]of i)a===S&&o(u)});return()=>{s(),n--,n===0&&ao(t,co)}},listen:o=>{n===0&&ao(t,uo),n++;let s=!0,i=t.subscribe(a=>{for(let[u,c]of a)if(u===S){if(s){s=!1;continue}o(c)}});return()=>{i(),n--,n===0&&ao(t,co)}},_node:t}}function Ru(t){let e=t.cache,n;if(t.subscribe(o=>{for(let[s,i]of o)s===S&&(e=i),s===M&&(n=i)})(),n)throw n;return e}function Su(t){return t.status==="sentinel"?Ru(t):t.cache}function Hp(t){let e=N(t,{resubscribable:!0,resetOnTeardown:!0});return mi(e,{set:n=>e.emit(n)})}function Wp(t,e){let n=Array.isArray(t)?t:[t],r=n.map(s=>s._node),o=gr(r,s=>{let i=n.map(a=>{let u=a._node;return u.status==="sentinel"&&Ru(u),s(u)});return e(...i)},{resubscribable:!0,resetOnTeardown:!0,equals:Object.is});return mi(o)}function qp(t){let e=N(t,{resubscribable:!0,resetOnTeardown:!0,equals:()=>!1});return mi(e,{set:n=>e.emit(n),setKey:(n,r)=>{let o=Su(e);e.emit({...o,[n]:r})}})}function Up(t){return t.get()}function Nu(t,e){let n=t._node,r=uo.get(n);r||(r=new Set,uo.set(n,r)),r.add(e)}function Eu(t,e){let n=t._node,r=co.get(n);r||(r=new Set,co.set(n,r)),r.add(e)}function zp(t,e){Nu(t,()=>{let n=e();typeof n=="function"&&Eu(t,n)})}function Jp(t,e,n){return(...r)=>{let o;return te(()=>{o=n(...r)}),o}}var Vo={};he(Vo,{ACTOR_KEY:()=>Eo,COMMAND_HANDLERS:()=>Ln,CQRS_EVENT_HANDLERS:()=>In,CRON_HANDLERS:()=>An,CommandHandler:()=>Iu,EVENT_HANDLERS:()=>On,EventHandler:()=>Pu,GRAPHREFLY_REQUEST_GRAPH:()=>Zt,GRAPHREFLY_ROOT_GRAPH:()=>Xe,GraphCron:()=>Lu,GraphInterval:()=>Au,GraphReflyEventExplorer:()=>on,GraphReflyGuard:()=>oc,GraphReflyGuardImpl:()=>Tr,GraphReflyModule:()=>jo,INTERVAL_HANDLERS:()=>Cn,InjectCqrsGraph:()=>Mu,InjectGraph:()=>_u,InjectNode:()=>Ou,ObserveGateway:()=>No,OnGraphEvent:()=>Cu,QUERY_HANDLERS:()=>Pn,QueryHandler:()=>Du,SAGA_HANDLERS:()=>Dn,SagaHandler:()=>Gu,fromHeader:()=>nc,fromJwtPayload:()=>Ni,getActor:()=>rc,getGraphToken:()=>Ye,getNodeToken:()=>ot,observeSSE:()=>ec,observeSubscription:()=>tc,toObservable:()=>po});var hi=require("rxjs");ie();function po(t,e){return e?.raw?new hi.Observable(n=>t.subscribe(o=>{if(!n.closed){n.next(o);for(let s of o){if(s[0]===M){n.error(s[1]);return}if(s[0]===_){n.complete();return}}}})):new hi.Observable(n=>t.subscribe(o=>{for(let s of o){if(n.closed)return;if(s[0]===S)n.next(s[1]);else if(s[0]===M){n.error(s[1]);return}else if(s[0]===_){n.complete();return}}}))}var br=require("@nestjs/common");var Xe=Symbol.for("graphrefly:root-graph");var Zt=Symbol.for("graphrefly:request-graph");function Ye(t){return Symbol.for(`graphrefly:graph:${t}`)}function ot(t){return Symbol.for(`graphrefly:node:${t}`)}var On=new Map,Cn=new Map,An=new Map,Ln=new Map,In=new Map,Pn=new Map,Dn=new Map;function _u(t){return t==="request"?(0,br.Inject)(Zt):(0,br.Inject)(t?Ye(t):Xe)}function Mu(t){return(0,br.Inject)(Ye(t))}function Ou(t){return(0,br.Inject)(ot(t))}function Cu(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=On.get(o)??[];s.push({nodeName:t,methodKey:r}),On.set(o,s)})}}function Au(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=Cn.get(o)??[];s.push({ms:t,methodKey:r}),Cn.set(o,s)})}}function Lu(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=An.get(o)??[];s.push({expr:t,methodKey:r}),An.set(o,s)})}}function Iu(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=Ln.get(s)??[];i.push({cqrsName:t,commandName:e,methodKey:o}),Ln.set(s,i)})}}function Pu(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=In.get(s)??[];i.push({cqrsName:t,eventName:e,methodKey:o}),In.set(s,i)})}}function Du(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=Pn.get(s)??[];i.push({cqrsName:t,projectionName:e,methodKey:o}),Pn.set(s,i)})}}function Gu(t,e,n){return(r,o)=>{let s=o.name;o.addInitializer(function(){let i=this.constructor,a=Dn.get(i)??[];a.push({cqrsName:t,eventNames:n,sagaName:e,methodKey:s}),Dn.set(i,a)})}}ie();Re();var Zu=0,on=class{constructor(e,n){this.graph=e;this.moduleRef=n}disposers=[];scheduleNodeNames=[];onModuleInit(){this.wireEvents(),this.wireIntervals(),this.wireCrons(),this.wireCqrsCommands(),this.wireCqrsEvents(),this.wireCqrsQueries(),this.wireCqrsSagas()}onModuleDestroy(){for(let e of this.disposers)e();this.disposers.length=0;for(let e of this.scheduleNodeNames)try{this.graph.remove(e)}catch{}this.scheduleNodeNames.length=0}wireEvents(){for(let[e,n]of On){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireEventHandler(r,o)}}wireEventHandler(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),i=this.observeNode(n.nodeName).subscribe(a=>{for(let u of a)u[0]===S&&o(u[1])});this.disposers.push(i)}wireIntervals(){for(let[e,n]of Cn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireIntervalHandler(r,e,o)}}wireIntervalHandler(e,n,r){let o=e[r.methodKey];if(typeof o!="function")return;let s=o.bind(e),a=`__schedule__.${n.name??"anonymous"}.${String(r.methodKey)}.${Zu++}`,u=et(r.ms,{period:r.ms,name:a});this.graph.add(u),this.scheduleNodeNames.push(a);let d=this.observeNode(a).subscribe(l=>{for(let f of l)f[0]===S&&s(f[1])});this.disposers.push(d)}wireCrons(){for(let[e,n]of An){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCronHandler(r,e,o)}}wireCronHandler(e,n,r){let o=e[r.methodKey];if(typeof o!="function")return;let s=o.bind(e),a=`__schedule__.${n.name??"anonymous"}.${String(r.methodKey)}.${Zu++}`,u=ko(r.expr,{name:a});this.graph.add(u),this.scheduleNodeNames.push(a);let d=this.observeNode(a).subscribe(l=>{for(let f of l)f[0]===S&&s(f[1])});this.disposers.push(d)}wireCqrsCommands(){for(let[e,n]of Ln){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsCommand(r,o)}}wireCqrsCommand(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);s&&s.command(n.commandName,o)}wireCqrsEvents(){for(let[e,n]of In){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsEventHandler(r,o)}}wireCqrsEventHandler(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);if(!s)return;s.event(n.eventName);let a=s.resolve(n.eventName).cache,u=a&&a.length>0?a[a.length-1].seq:0,d=this.observeNodeOn(s,n.eventName).subscribe(l=>{for(let f of l)if(f[0]===S){let p=f[1];for(let m of p)m.seq>u&&(o(m),u=m.seq)}});this.disposers.push(d)}wireCqrsQueries(){for(let[e,n]of Pn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsQuery(r,o)}}wireCqrsQuery(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);if(!s)return;let a=this.observeNodeOn(s,n.projectionName).subscribe(u=>{for(let c of u)c[0]===S&&o(c[1])});this.disposers.push(a)}wireCqrsSagas(){for(let[e,n]of Dn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsSaga(r,o)}}wireCqrsSaga(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);s&&s.saga(n.sagaName,n.eventNames,o)}observeNode(e){return this.graph.observe(e)}observeNodeOn(e,n){return e.observe(n)}resolveCqrsGraph(e){try{return this.moduleRef.get(Ye(e),{strict:!1})}catch{return console.warn(`[GraphReFly] CqrsGraph "${e}" not found in DI \u2014 did you import GraphReflyModule.forCqrs({ name: "${e}" })?`),null}}resolveInstance(e){try{return this.moduleRef.get(e,{strict:!1})}catch{return null}}};ie();ie();var sf=0;function Hn(t,e){if(e.highWaterMark<1)throw new RangeError("highWaterMark must be >= 1");if(e.lowWaterMark<0)throw new RangeError("lowWaterMark must be >= 0");if(e.lowWaterMark>=e.highWaterMark)throw new RangeError("lowWaterMark must be < highWaterMark");let n=Symbol(`bp-${++sf}`),r=0,o=!1;return{onEnqueue(){return r+=1,!o&&r>=e.highWaterMark?(o=!0,t([[Ie,n]]),!0):!1},onDequeue(){return r>0&&(r-=1),o&&r<=e.lowWaterMark?(o=!1,t([[Ge,n]]),!0):!1},get pending(){return r},get paused(){return o},dispose(){o&&(o=!1,t([[Ge,n]]))}}}function ec(t,e,n){let{actor:r,serialize:o=af,keepAliveMs:s,signal:i}=n??{},a=new TextEncoder,u,c=n?.highWaterMark!=null,d,l,f=[],p=!1;return new ReadableStream({start(m){let h,g=()=>{},y=()=>{if(!p){p=!0,h!==void 0&&clearInterval(h),i?.removeEventListener("abort",b),g(),d?.dispose(),l?.(),l=void 0;for(let T of f)m.enqueue(T.frame);f.length=0,m.close()}};u=y;let b=()=>y(),v=t.observe(e,{actor:r});c&&(d=Hn(T=>v.up(T),{highWaterMark:n.highWaterMark,lowWaterMark:n.lowWaterMark??Math.floor(n.highWaterMark/2)})),g=v.subscribe(T=>{for(let w of T){if(p)return;let k=w[0];if(k===S){let x=a.encode(Ri("data",o(w[1])));c?(f.push({frame:x,counted:!0}),d.onEnqueue(),l?.(),l=void 0):m.enqueue(x)}else if(k===M){let x=a.encode(Ri("error",o(w[1])));c?(f.push({frame:x,counted:!1}),l?.(),l=void 0):m.enqueue(x),y();return}else if(k===_||k===de){if(k===_){let x=a.encode(Ri("complete"));c?(f.push({frame:x,counted:!1}),l?.(),l=void 0):m.enqueue(x)}y();return}}}),s!==void 0&&s>0&&(h=setInterval(()=>{p||(c?(f.push({frame:a.encode(`: keepalive
2
2
 
3
3
  `),counted:!1}),l?.(),l=void 0):m.enqueue(a.encode(`: keepalive
4
4
 
5
- `)))},s)),i?.aborted?b():i?.addEventListener("abort",b,{once:!0})},pull(m){if(c&&!p){if(f.length>0){let h=f.shift();m.enqueue(h.frame),h.counted&&d.onDequeue();return}return new Promise(h=>{l=h})}},cancel(){try{u?.()}catch{}}})}function qu(t,e,n){let{actor:r,filter:o}=n??{},s=[],i=[],a=!1,u=t.observe(e,{actor:r}),c=n?.highWaterMark!=null?Bn(m=>u.up(m),{highWaterMark:n.highWaterMark,lowWaterMark:n.lowWaterMark??Math.floor(n.highWaterMark/2)}):void 0,d=()=>{a||(a=!0,c?.dispose(),f())},l=m=>{if(!a)if(i.length>0){let h=i.shift();m.done&&m.error?h.reject(m.error):m.done?h.resolve({done:!0,value:void 0}):h.resolve({done:!1,value:m.value})}else s.push(m),m.done||c?.onEnqueue()},f=u.subscribe(m=>{for(let h of m){let g=h[0];if(g===R){let y=h[1];if(o&&!o(y))continue;l({done:!1,value:y})}else if(g===O){let y=h[1]instanceof Error?h[1]:new Error(String(h[1]));l({done:!0,error:y}),d();return}else if(g===M||g===de){l({done:!0}),d();return}}});return{next(){if(s.length>0){let m=s.shift();return m.done||c?.onDequeue(),m.done&&m.error?Promise.reject(m.error):Promise.resolve(m.done?{done:!0,value:void 0}:{done:!1,value:m.value})}return a?Promise.resolve({done:!0,value:void 0}):new Promise((m,h)=>{i.push({resolve:m,reject:h})})},return(){d();for(let m of i)m.resolve({done:!0,value:void 0});return i.length=0,Promise.resolve({done:!0,value:void 0})},throw(m){return d(),Promise.reject(m)},[Symbol.asyncIterator](){return this}}}var ko=class{constructor(e,n){this.graph=e;this.extractActor=n?.extractActor??(()=>{}),this.parse=n?.parse??jp,this.highWaterMark=n?.highWaterMark,this.lowWaterMark=n?.lowWaterMark}clients=new Map;extractActor;parse;highWaterMark;lowWaterMark;handleConnection(e){this.clients.has(e)||this.clients.set(e,new Map)}handleDisconnect(e){let n=this.clients.get(e);if(n){for(let r of n.values())r.wm?.dispose(),r.unsub();this.clients.delete(e)}}handleMessage(e,n,r){let o=r??Kp.bind(null,e),s;try{s=typeof n=="string"?this.parse(n):n}catch{o({type:"err",message:"invalid command"});return}s.type==="subscribe"?this.subscribe(e,s.path,o):s.type==="unsubscribe"?this.unsubscribe(e,s.path,o):s.type==="ack"?this.ack(e,s.path,s.count??1):o({type:"err",message:`unknown command type: ${s.type}`})}subscriptionCount(e){return this.clients.get(e)?.size??0}destroy(){for(let[e]of this.clients)this.handleDisconnect(e)}subscribe(e,n,r){let o=this.clients.get(e);if(o||(o=new Map,this.clients.set(e,o)),o.has(n)){r({type:"subscribed",path:n});return}let s=this.extractActor(e),i;try{i=this.graph.observe(n,{actor:s})}catch(d){let l=d instanceof Error?d.message:String(d);r({type:"err",message:l});return}let a=this.highWaterMark!=null?Bn(d=>i.up(d),{highWaterMark:this.highWaterMark,lowWaterMark:this.lowWaterMark??Math.floor(this.highWaterMark/2)}):void 0,u=()=>{a?.dispose(),c(),o.delete(n)},c=i.subscribe(d=>{for(let l of d){let f=l[0];if(f===R)a?.onEnqueue(),wi(r,{type:"data",path:n,value:l[1]});else if(f===O){let p=l[1]instanceof Error?l[1].message:String(l[1]);wi(r,{type:"error",path:n,error:p}),u();return}else if(f===M||f===de){wi(r,{type:"complete",path:n}),u();return}}});o.set(n,{unsub:c,wm:a}),r({type:"subscribed",path:n})}unsubscribe(e,n,r){let o=this.clients.get(e),s=o?.get(n);s&&(s.wm?.dispose(),s.unsub(),o.delete(n)),r({type:"unsubscribed",path:n})}ack(e,n,r){let o=this.clients.get(e)?.get(n);if(!o?.wm)return;let s=Math.min(Math.max(0,Math.floor(r)),1024);for(let i=0;i<s;i++)o.wm.onDequeue()}};function Bp(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)}catch{return String(t)}}function Ti(t,e){let n=`event: ${t}
5
+ `)))},s)),i?.aborted?b():i?.addEventListener("abort",b,{once:!0})},pull(m){if(c&&!p){if(f.length>0){let h=f.shift();m.enqueue(h.frame),h.counted&&d.onDequeue();return}return new Promise(h=>{l=h})}},cancel(){try{u?.()}catch{}}})}function tc(t,e,n){let{actor:r,filter:o}=n??{},s=[],i=[],a=!1,u=t.observe(e,{actor:r}),c=n?.highWaterMark!=null?Hn(m=>u.up(m),{highWaterMark:n.highWaterMark,lowWaterMark:n.lowWaterMark??Math.floor(n.highWaterMark/2)}):void 0,d=()=>{a||(a=!0,c?.dispose(),f())},l=m=>{if(!a)if(i.length>0){let h=i.shift();m.done&&m.error?h.reject(m.error):m.done?h.resolve({done:!0,value:void 0}):h.resolve({done:!1,value:m.value})}else s.push(m),m.done||c?.onEnqueue()},f=u.subscribe(m=>{for(let h of m){let g=h[0];if(g===S){let y=h[1];if(o&&!o(y))continue;l({done:!1,value:y})}else if(g===M){let y=h[1]instanceof Error?h[1]:new Error(String(h[1]));l({done:!0,error:y}),d();return}else if(g===_||g===de){l({done:!0}),d();return}}});return{next(){if(s.length>0){let m=s.shift();return m.done||c?.onDequeue(),m.done&&m.error?Promise.reject(m.error):Promise.resolve(m.done?{done:!0,value:void 0}:{done:!1,value:m.value})}return a?Promise.resolve({done:!0,value:void 0}):new Promise((m,h)=>{i.push({resolve:m,reject:h})})},return(){d();for(let m of i)m.resolve({done:!0,value:void 0});return i.length=0,Promise.resolve({done:!0,value:void 0})},throw(m){return d(),Promise.reject(m)},[Symbol.asyncIterator](){return this}}}var No=class{constructor(e,n){this.graph=e;this.extractActor=n?.extractActor??(()=>{}),this.parse=n?.parse??uf,this.highWaterMark=n?.highWaterMark,this.lowWaterMark=n?.lowWaterMark}clients=new Map;extractActor;parse;highWaterMark;lowWaterMark;handleConnection(e){this.clients.has(e)||this.clients.set(e,new Map)}handleDisconnect(e){let n=this.clients.get(e);if(n){for(let r of n.values())r.wm?.dispose(),r.unsub();this.clients.delete(e)}}handleMessage(e,n,r){let o=r??cf.bind(null,e),s;try{s=typeof n=="string"?this.parse(n):n}catch{o({type:"err",message:"invalid command"});return}s.type==="subscribe"?this.subscribe(e,s.path,o):s.type==="unsubscribe"?this.unsubscribe(e,s.path,o):s.type==="ack"?this.ack(e,s.path,s.count??1):o({type:"err",message:`unknown command type: ${s.type}`})}subscriptionCount(e){return this.clients.get(e)?.size??0}destroy(){for(let[e]of this.clients)this.handleDisconnect(e)}subscribe(e,n,r){let o=this.clients.get(e);if(o||(o=new Map,this.clients.set(e,o)),o.has(n)){r({type:"subscribed",path:n});return}let s=this.extractActor(e),i;try{i=this.graph.observe(n,{actor:s})}catch(d){let l=d instanceof Error?d.message:String(d);r({type:"err",message:l});return}let a=this.highWaterMark!=null?Hn(d=>i.up(d),{highWaterMark:this.highWaterMark,lowWaterMark:this.lowWaterMark??Math.floor(this.highWaterMark/2)}):void 0,u=()=>{a?.dispose(),c(),o.delete(n)},c=i.subscribe(d=>{for(let l of d){let f=l[0];if(f===S)a?.onEnqueue(),Si(r,{type:"data",path:n,value:l[1]});else if(f===M){let p=l[1]instanceof Error?l[1].message:String(l[1]);Si(r,{type:"error",path:n,error:p}),u();return}else if(f===_||f===de){Si(r,{type:"complete",path:n}),u();return}}});o.set(n,{unsub:c,wm:a}),r({type:"subscribed",path:n})}unsubscribe(e,n,r){let o=this.clients.get(e),s=o?.get(n);s&&(s.wm?.dispose(),s.unsub(),o.delete(n)),r({type:"unsubscribed",path:n})}ack(e,n,r){let o=this.clients.get(e)?.get(n);if(!o?.wm)return;let s=Math.min(Math.max(0,Math.floor(r)),1024);for(let i=0;i<s;i++)o.wm.onDequeue()}};function af(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)}catch{return String(t)}}function Ri(t,e){let n=`event: ${t}
6
6
  `;if(e!==void 0)for(let r of e.split(`
7
7
  `))n+=`data: ${r}
8
8
  `;return n+=`
9
- `,n}function jp(t){return JSON.parse(t)}function Kp(t,e){try{t.send(JSON.stringify(e))}catch{}}function wi(t,e){try{t(e)}catch{}}rr();var xo="graphReflyActor";function ki(t){return e=>{let r=e.switchToHttp().getRequest()?.user;if(r!=null)return t?t(r):r}}function Hu(t="x-graphrefly-actor"){return e=>{let r=e.switchToHttp().getRequest()?.headers?.[t.toLowerCase()];if(!(typeof r!="string"||r.length===0))try{return JSON.parse(r)}catch{return}}}function Wu(t){let e=t?.[xo];return e!=null?yt(e):dt}var hr=class{constructor(e){this.extractor=e}canActivate(e){let n=yt(this.extractor(e)),r=e.switchToHttp().getRequest();return r!=null&&(r[xo]=n),!0}};function Uu(t){return new hr(t??ki())}var wr=require("@nestjs/common"),ic=require("@nestjs/core");rr();Se();Te();Jt();ie();Jt();we();function Tt(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;default:return new Set(["type","deps"])}}function Vp(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function qp(t){let e={};for(let[n,r]of Object.entries(t.meta))try{e[n]=r.cache}catch{}return e}function gr(t,e){let n=e==null,r=!n&&e!=null?[...e].filter(c=>c.startsWith("meta.")).map(c=>c.slice(5)):null,o=n||e.has("meta")||r!=null&&r.length>0,s="state",i=[];t instanceof xe&&(s=Vp(t),i=t._deps.map(c=>c.node.name??""));let a={type:s,deps:i};(n||e.has("status"))&&(a.status=t.status);let u=t instanceof xe?t._guard:void 0;if(o){let c={...qp(t)};if(u!=null&&c.access===void 0&&(c.access=cr(u)),r!=null&&r.length>0&&!e.has("meta")){let d={};for(let l of r)l in c&&(d[l]=c[l]);a.meta=d}else a.meta=c}if(t.name!=null&&(a.name=t.name),n||e.has("value")){t.status==="sentinel"&&(a.sentinel=!0);try{a.value=t.cache}catch{}}if((n||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),a.v=c}return(n||e.has("guard"))&&u!=null&&(a.guard=cr(u)),(n||e.has("lastMutation"))&&t.lastMutation!=null&&(a.lastMutation=t.lastMutation),a}we();le();$e();lt();var rn=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}};Zr();function yr(t,e,n,r={}){let o=e in t.nodes,s=n in t.nodes;if(!o)return Ro(e,n,"no-such-from");if(!s)return Ro(e,n,"no-such-to");let i=r.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===n){if(r.findCycle===!0){let c=Hp(t,e,r);if(c!=null)return c}let u=So(e,t.nodes[e],0,r);return No(e,n,[u])}if(i===0)return Ro(e,n,"no-path");let a=zu(t,e,n,i);return a.found?No(e,n,Ju(t,a.pathOrder,r)):Ro(e,n,a.truncated?"max-depth-exceeded":"no-path")}function zu(t,e,n,r){let o=new Map,s=[{path:n,depth:0}],i=new Set([n]),a=0,u=!1;for(;a<s.length;){let l=s[a++];if(l.path===e)break;if(r!=null&&l.depth>=r){let h=t.nodes[l.path];h?.deps&&h.deps.length>0&&(u=!0);continue}let f=t.nodes[l.path];if(f==null)continue;let p=f.deps??[],m=new Map;for(let h=0;h<p.length;h++){let g=p[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)i.has(h)||(i.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:u};let c=[{path:e}],d=e;for(;d!==n;){let l=o.get(d);if(l==null)return{found:!1,pathOrder:[],truncated:!1};c[c.length-1].depIndices=l.depIndices,c.push({path:l.from}),d=l.from}return{found:!0,pathOrder:c,truncated:!1}}function Hp(t,e,n){let r=t.nodes[e];if(r==null)return null;let o=r.deps??[],s=[];for(let a=0;a<o.length;a++)o[a]===e&&s.push(a);if(s.length>0){let a=So(e,r,0,n);a.dep_index=s[0];let u=So(e,r,1,n);return No(e,e,[a,u])}let i=null;for(let a=0;a<o.length;a++){let u=o[a];if(!u||u===e)continue;let c=zu(t,u,e,n.maxDepth);c.found&&(i==null||c.pathOrder.length<i.pathOrder.length)&&(i=c,i={found:!0,pathOrder:[{path:e,depIndices:[a]},...c.pathOrder],truncated:!1})}return i==null?null:No(e,e,Ju(t,i.pathOrder,n))}function Ju(t,e,n){return e.map((r,o)=>{let s=t.nodes[r.path],i=So(r.path,s,o,n);return r.depIndices!=null&&r.depIndices.length>0&&(i.dep_index=r.depIndices[0],r.depIndices.length>1&&(i.dep_indices=[...r.depIndices])),i})}function So(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 i=r.lastMutations?.get(t)??e.lastMutation;return i!=null&&(o.lastMutation=i),o}function No(t,e,n){return Yu(t,e,!0,"ok",n)}function Ro(t,e,n){return Yu(t,e,!1,n,[])}function Yu(t,e,n,r,o){let s=Wp(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 Wp(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 i of o){let u=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(s.push(u),"value"in i&&s.push(` value: ${Up(i.value)}`),i.annotation!=null&&s.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let c=i.lastMutation.actor;s.push(` actor: ${c.type}${c.id?`:${c.id}`:""}`)}}return s.join(`
10
- `)}function Up(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)}}we();var Oe={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},Eo=Symbol.for("sizeof");function br(t){let e=new WeakSet,n=new WeakSet,r=[t],o=0;for(;r.length>0;){let s=r.pop();o+=zp(s,e,n,r)}return o}function zp(t,e,n,r){if(t==null)return 0;switch(typeof t){case"number":return Oe.number;case"boolean":return Oe.boolean;case"string":return Oe.string+t.length*2;case"bigint":return Oe.bigint+Jp(t);case"symbol":return Oe.symbol;case"function":return e.has(t)?0:(e.add(t),Oe.function);case"undefined":return 0}let s=t;if(e.has(s))return 0;e.add(s);let i=s[Eo];if(typeof i=="function")try{let c=i.call(s);if(typeof c=="number"&&Number.isFinite(c))return c}catch{}if(s instanceof Date)return Oe.date;if(s instanceof RegExp)return Oe.regexp+s.source.length*2;if(s instanceof Error){let c=s.message?s.message.length*2:0,d=s.stack?s.stack.length*2:0;return Oe.error+c+d}if(typeof URL<"u"&&s instanceof URL)return Oe.url+s.href.length*2;if(typeof Promise<"u"&&s instanceof Promise)return Oe.promise;if(s instanceof WeakMap)return Oe.weakmap;if(s instanceof WeakSet)return Oe.weakset;if(s instanceof Map){let c=Oe.map;for(let[d,l]of s)c+=Oe.mapEntry,r.push(d),r.push(l);return c}if(s instanceof Set){let c=Oe.set;for(let d of s)c+=Oe.setEntry,r.push(d);return c}if(Array.isArray(s)){let c=Oe.array+s.length*8;for(let d of s)r.push(d);return c}if(s instanceof ArrayBuffer)return n.has(s)?0:(n.add(s),s.byteLength);if(ArrayBuffer.isView(s)){let c=s;return n.has(c.buffer)?48:(n.add(c.buffer),c.buffer.byteLength+48)}let a=Oe.object,u=Object.keys(s);for(let c of u){a+=Oe.string+c.length*2;try{r.push(s[c])}catch{}}return a}function Jp(t){let e=t<0n?-t:t;if(e===0n)return 0;let n=e.toString(2).length;return Math.ceil(n/32)*8}function on(t,e){let n=e?.topN??10,r=t.describe({detail:"standard"}),o=[],s=t._collectObserveTargets;typeof s=="function"&&s.call(t,"",o);let i=new Map;for(let[f,p]of o)i.set(f,p);let a=[];for(let[f,p]of Object.entries(r.nodes)){let m=i.get(f),h=m instanceof xe?m:null,g=h?br(h.cache):0,y=h?h._sinkCount:0,b=p.deps?.length??0,v=p.type==="effect"&&y===0,T=y===0?p.type==="effect"?"orphan-effect":p.type==="derived"?"idle-derived":p.type==="producer"?"idle-producer":null:null;a.push({path:f,type:p.type,status:p.status??"unknown",valueSizeBytes:g,subscriberCount:y,depCount:b,isOrphanEffect:v,orphanKind:T})}let u=a.reduce((f,p)=>f+p.valueSizeBytes,0),c=(f,p)=>[...a].sort(p??((m,h)=>h[f]-m[f])).slice(0,n),d=a.filter(f=>f.orphanKind!=null),l=a.filter(f=>f.isOrphanEffect);return{nodeCount:a.length,edgeCount:r.edges.length,subgraphCount:r.subgraphs.length,nodes:a,totalValueSizeBytes:u,hotspots:{byValueSize:c("valueSizeBytes"),bySubscriberCount:c("subscriberCount"),byDepCount:c("depCount")},orphans:d,orphanEffects:l}}var Ee="::",Be="__meta__",it=1;function Qu(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(i){console.error(`[Graph "${e}".destroy] disposer threw:`,i)}}}function Yp(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(`
11
- `)}function Xu(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 Qp(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 i=n.get(o);if(i==null&&(i=new WeakSet,n.set(o,i)),i.has(s))return!0;i.add(s);let a=o.constructor,u=s.constructor;if(a!==u)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 f=s;if(o.length!==f.length)return!1;for(let p=0;p<o.length;p++)if(!r(o[p],f[p]))return!1;return!0}if(o instanceof Map){let f=s;if(o.size!==f.size)return!1;for(let[p,m]of o)if(!f.has(p)||!r(m,f.get(p)))return!1;return!0}if(o instanceof Set){let f=s;if(o.size!==f.size)return!1;for(let p of o){let m=!1;for(let h of f)if(r(p,h)){m=!0;break}if(!m)return!1}return!0}if(ArrayBuffer.isView(o)){let f=o,p=s;if(f.length!==p.length)return!1;for(let m=0;m<f.length;m++)if(f[m]!==p[m])return!1;return!0}let c=Object.keys(o),d=Object.keys(s);if(c.length!==d.length)return!1;let l=new Set(d);for(let f of c)if(!l.has(f)||!r(o[f],s[f]))return!1;return!0};return r(t,e)}function Ri(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(Ri);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=Ri(e[o]);return r}function Xp(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Zp(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function ef(t){return t==="TD"?"down":t==="BT"?"up":t==="RL"?"left":"right"}function ec(t){let e=new Set,n=[];function r(o,s){let i=`${o}\0${s}`;e.has(i)||(e.add(i),n.push([o,s]))}for(let[o,s]of Object.entries(t.nodes)){let i=s.deps;if(i)for(let a of i)r(a,o)}for(let o of t.edges)r(o.from,o.to);return n}function tc(t){if(t===void 0)return"LR";if(t==="TD"||t==="LR"||t==="BT"||t==="RL")return t;throw new Error(`invalid diagram direction ${String(t)}; expected one of: TD, LR, BT, RL`)}function tf(t,e){let n=e.includeEdges??!0,r=e.includeSubgraphs??!0,{expand:o,...s}=t,i={...s,edges:n?t.edges:[],subgraphs:r?t.subgraphs:[]},a=JSON.stringify(Ri(i),null,e.indent??2);return e.logger?.(a),a}function nf(t,e){let n=e.includeEdges??!0,r=e.includeSubgraphs??!0,o=[];o.push(`Graph ${t.name}`),o.push("Nodes:");for(let i of Object.keys(t.nodes).sort()){let a=t.nodes[i];o.push(`- ${i} (${a.type}/${a.status}): ${Mo(a.value)}`)}if(n){o.push("Edges:");for(let i of t.edges)o.push(`- ${i.from} -> ${i.to}`)}if(r){o.push("Subgraphs:");for(let i of t.subgraphs)o.push(`- ${i}`)}let s=o.join(`
12
- `);return e.logger?.(s),s}function nc(t,e){let n=tc(e.direction),r=Object.keys(t.nodes).sort(),o=new Map;for(let i=0;i<r.length;i+=1)o.set(r[i],`n${i}`);let s=[`flowchart ${n}`];for(let i of r){let a=o.get(i);s.push(` ${a}["${Xp(i)}"]`)}for(let[i,a]of ec(t)){let u=o.get(i),c=o.get(a);!u||!c||s.push(` ${u} --> ${c}`)}return s.join(`
13
- `)}function rf(t,e){let n=nc(t,e);return Oo(n)}function Oo(t,e){let n=e?.theme??"default",r=e?.autoSync??!0,s=JSON.stringify({code:t,mermaid:{theme:n},autoSync:r}),i=new TextEncoder().encode(s),a="";for(let c=0;c<i.length;c++)a+=String.fromCharCode(i[c]);return`https://mermaid.live/edit#base64:${globalThis.btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`}function of(t,e){let n=tc(e.direction),r=Object.keys(t.nodes).sort(),o=new Map;for(let i=0;i<r.length;i+=1)o.set(r[i],`n${i}`);let s=[`direction: ${ef(n)}`];for(let i of r){let a=o.get(i);s.push(`${a}: "${Zp(i)}"`)}for(let[i,a]of ec(t)){let u=o.get(i),c=o.get(a);!u||!c||s.push(`${u} -> ${c}`)}return s.join(`
14
- `)}function sf(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _o(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+=sf(r)}return e+="$",new RegExp(e)}var af={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"},uf={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function Mo(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 cf(t){return t==="none"?uf:t==="ansi"||t==null?af:{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 Zu(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 df(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 xi(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(Ee))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${Ee}' (path separator)`);if(t===Be)throw new Error(`Graph "${e}": ${n} name "${Be}" is reserved for meta companion paths`);df(t,e,n)}function lf(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(Ee);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function pf(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 rc(t){for(let e of t._mounts.values())rc(e);for(let e of t._nodes.values())try{e.down([[de]],{internal:!0})}catch{}}var z=class t{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_topology;_topologyEmitters=new Set;constructor(e,n){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(Ee))throw new Error(`Graph name must not contain '${Ee}' (got "${e}")`);if(e===Be)throw new Error(`Graph name "${Be}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??Me,this._traceRing=new rn(n?.traceCapacity??1e3),n?.versioning!=null&&this.setVersioning(n.versioning)}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=H(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)}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,i=n?.annotation;if(xi(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 a=this._nodeToName.get(e);if(a!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${a}"`);return this._nodes.set(s,e),this._nodeToName.set(e,s),this._emitTopology({kind:"added",name:s,nodeKind:"node"}),i!=null&&(this._annotations.set(s,i),this.config.inspectorEnabled&&this._traceRing.push({path:s,annotation:i,timestamp_ns:B()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof xe&&n._applyVersioning(e)}remove(e){xi(e,this.name,"remove");let n=this._mounts.get(e);if(n){let s={kind:"mount",nodes:[],mounts:[]},i=[];n._collectObserveTargets("",i);for(let[a,u]of i)a.includes(`${Ee}${Be}${Ee}`)||s.nodes.push(a);return s.nodes.sort(),s.mounts.push(e),s.mounts.push(...n._collectSubgraphs(`${e}${Ee}`)),this._mounts.delete(e),n._parent=void 0,rc(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([[de]],{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=_o(e);return i=>s.test(i)})(),r={kind:"mount",nodes:[],mounts:[]},o=[...this._nodes.keys(),...this._mounts.keys()].filter(s=>n(s));for(let s of o){let i=this.remove(s);r.nodes.push(...i.nodes),r.mounts.push(...i.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(Ee))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([[R,n]],{actor:r?.actor,internal:o,delivery:"write"})}setAll(e,n){let r=Symbol.iterator in e?e:Object.entries(e);ee(()=>{for(let[o,s]of r)this.set(o,s,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[Ve]],{actor:n?.actor,internal:r,delivery:"write"})}error(e,n,r){let o=r?.internal===!0;this.node(e).down([[O,n]],{actor:r?.actor,internal:o,delivery:"write"})}complete(e,n){let r=n?.internal===!0;this.node(e).down([[M]],{actor:n?.actor,internal:r,delivery:"write"})}edges(e){let n=e?.recursive===!0,r=new Map;if(!n){for(let[u,c]of this._nodes)r.set(c,u);let a=[];for(let[u,c]of this._nodes)if(c instanceof xe)for(let d of c._deps){let l=r.get(d.node);l!=null&&a.push([l,u])}return a.sort((u,c)=>u[0]<c[0]?-1:u[0]>c[0]?1:u[1]<c[1]?-1:u[1]>c[1]?1:0),a}let o=[];this._collectObserveTargets("",o);let s=new Map;for(let[a,u]of o)s.set(u,a);let i=[];for(let[a,u]of o)if(u instanceof xe)for(let c of u._deps){let d=s.get(c.node);d!=null&&i.push([d,a])}return i.sort((a,u)=>a[0]<u[0]?-1:a[0]>u[0]?1:a[1]<u[1]?-1:a[1]>u[1]?1:0),i}mount(e,n){if(xi(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(n===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(n._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${n._parent.name}"`);for(let r=this;r!=null;r=r._parent)if(r===n)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,n),n._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),n}resolve(e){let n=lf(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 a=this._nodes.get(r);if(a)return a;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]===Be)return this._resolveMetaChainFromNode(s,o,n.join(Ee));let i=this._mounts.get(r);if(!i)throw this._nodes.has(r)?new Error(`Graph "${this.name}": "${r}" is a node; trailing path "${o.join(Ee)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(o.join(Ee))}_resolveMetaChainFromNode(e,n,r){let o=e,s=0,i=[...n];for(;s<i.length;){if(i[s]!==Be)throw new Error(`Graph "${this.name}": expected ${Be} segment in meta path "${r}"`);if(s+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${Be} in "${r}"`);let a=i[s+1],u=o.meta[a];if(!u)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${r}"`);o=u,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 u of this._mounts.values())u._signalDeliver(e,n,r,o);let i=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},a=pf(e,this.config);for(let u of[...this._nodes.keys()].sort()){let c=this._nodes.get(u);if(!r.has(c)){r.add(c);try{c.down(e,i)}catch(d){if(d instanceof Je)throw d;o.push(d)}a.length!==0&&this._signalMetaSubtree(c,a,r,i,o)}}}_signalMetaSubtree(e,n,r,o,s){for(let i of Object.keys(e.meta).sort()){let a=e.meta[i];if(!r.has(a)){r.add(a);try{a.down(n,o)}catch(u){if(u instanceof Je)throw u;s.push(u)}this._signalMetaSubtree(a,n,r,o,s)}}}describe(e){if(e?.reactive===!0)return this._describeReactive(e);let n=e?.actor,r=e?.filter,o=Tt(e?.detail,e?.fields),s=e?.format==="spec",i=s?Tt("minimal"):o,a=[];this._collectObserveTargets("",a);let u=new Map;for(let[k,x]of a)u.set(x,k);let c=[];{let k=a.map(([,_])=>_),x=new Set(u.values()),S=0;for(;k.length>0;){let _=k.shift();if(_ instanceof xe)for(let F of _._deps){let L=F.node;if(u.has(L))continue;let D=L.name??"",C=D;if(!C||x.has(C))if(D){let K=2;for(;x.has(`${D}#${K}`);)K++;C=`${D}#${K}`}else for(C=`__internal__/${S++}`;x.has(C);)C=`__internal__/${S++}`;u.set(L,C),x.add(C),c.push([C,L]),k.push(L)}}}let d=[...a,...c],l={};for(let[k,x]of d){if(n!=null&&!x.allowsObserve(n))continue;let S=gr(x,i),_=x instanceof xe?x._deps.map(C=>u.get(C.node)??C.node.name??""):[],{name:F,...L}=S,D={...L,deps:_};if(!s){let C=this._annotations.get(k);C!=null&&(D.annotation=C)}if(r!=null)if(typeof r=="function"){let C=r;if(!(C.length>=2?C(k,D):C(D)))continue}else{let C=!0;for(let[K,ne]of Object.entries(r)){let P=K==="deps_includes"?"depsIncludes":K==="meta_has"?"metaHas":K;if(P==="depsIncludes"){if(!D.deps.includes(String(ne))){C=!1;break}continue}if(P==="metaHas"){if(!Object.hasOwn(D.meta??{},String(ne))){C=!1;break}continue}if(D[P]!==ne){C=!1;break}}if(!C)continue}l[k]=D}let f=new Set(Object.keys(l)),p=[];for(let[k,x]of d)if(x instanceof xe)for(let S of x._deps){let _=u.get(S.node);_!=null&&p.push([_,k])}p.sort((k,x)=>k[0]<x[0]?-1:k[0]>x[0]?1:k[1]<x[1]?-1:k[1]>x[1]?1:0);let m=p.map(([k,x])=>({from:k,to:x}));(n!=null||r!=null)&&(m=m.filter(k=>f.has(k.from)&&f.has(k.to)));let h=this._collectSubgraphs(""),g=n!=null||r!=null?h.filter(k=>{let x=`${k}${Ee}`;return[...f].some(S=>S===k||S.startsWith(x))}):h,y=this,b=e,v={name:this.name,nodes:l,edges:m,subgraphs:g,expand(k){let x={...b,format:void 0};return Array.isArray(k)?(x.fields=k,x.detail=void 0):(x.detail=k,x.fields=void 0),y.describe(x)}},T=e??{},w=T.format;return w==="json"?tf(v,T):w==="pretty"?nf(v,T):w==="mermaid"?nc(v,T):w==="mermaid-url"?rf(v,T):w==="d2"?of(v,T):v}_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}${Ee}`))}return n}resourceProfile(e){return on(this,e)}reachable(e,n,r={}){return r.withDetail===!0?sn(this.describe(),e,n,{...r,withDetail:!0}):sn(this.describe(),e,n,r)}explain(e,n,r){return r?.reactive===!0?this._explainReactive(e,n,r):this._explainStatic(e,n,r)}_explainStatic(e,n,r){let o=this.describe({detail:"full"}),s=new Map(this._annotations),i=new Map;for(let[a,u]of Object.entries(o.nodes))u.lastMutation!=null&&i.set(a,u.lastMutation);return yr(o,e,n,{...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{},annotations:s,lastMutations:i})}_describeReactive(e){let n={...e,reactive:!1},r=e.reactiveName??"describe",o=0,s=N(o,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,u=!1,c=()=>{a||u||(a=!0,ir(()=>{a=!1,!u&&(o+=1,s.emit(o))}))},d=i.onEvent(g=>{let y=g.type;y!=="data"&&y!=="error"&&y!=="complete"&&y!=="teardown"||c()}),l=[],f=new WeakSet,p=g=>{if(f.has(g)||u)return;f.add(g);let y=g.topology.subscribe(b=>{for(let v of b){if(v[0]!==R)continue;let T=v[1];if(c(),T.kind==="added"&&T.nodeKind==="mount"){let w=g._mounts.get(T.name);w!=null&&p(w)}}});l.push(y);for(let b of g._mounts.keys()){let v=g._mounts.get(b);v!=null&&p(v)}};p(this);let m;try{m=A([s],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(g,y)=>g===y})}catch(g){d();for(let y of l)y();throw i.dispose(),g}let h=oe(m);return{node:m,dispose(){u=!0,d();for(let g of l)g();l.length=0,i.dispose(),h()}}}_explainReactive(e,n,r){let o=0,s=N(o,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,u=!1,c=i.onEvent(p=>{let m=p.type;m!=="data"&&m!=="error"&&m!=="complete"&&m!=="teardown"||a||u||(a=!0,ir(()=>{a=!1,!u&&(o+=1,s.emit(o))}))}),d={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},l;try{l=A([s],()=>this._explainStatic(e,n,d),{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:e,to:n},equals:(p,m)=>p.found===m.found&&p.reason===m.reason&&p.steps.length===m.steps.length&&ff(p.steps,m.steps)})}catch(p){throw c(),i.dispose(),p}let f=oe(l);return{node:l,dispose(){u=!0,c(),i.dispose(),f()}}}_pathsMatching(e){let n=_o(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}${Ee}${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}${Ee}${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],i=`${e}${Ee}${Be}${Ee}${o}`;r.push([i,s]),this._appendMetaObserveTargets(i,s,r)}}observe(e,n){let r=typeof e=="string",s=Zu(r?n:e),i=s.structured===!0||s.timeline===!0||s.causal===!0||s.derived===!0||s.detail==="minimal"||s.detail==="full"||s.format!=null,a=s.actor;if(r){let d=e,l=this.resolve(d);if(a!=null&&!l.allowsObserve(a))throw new Je({actor:a,action:"observe",nodeName:d});return i?this._buildStructuredObserver([[d,l]],s,"one"):{subscribe(f){return l.subscribe(f)},up(f){try{l.up?.(f)}catch(p){if(p instanceof Je)return;throw p}}}}let u=[];this._collectObserveTargets("",u),u.sort((d,l)=>d[0]<l[0]?-1:d[0]>l[0]?1:0);let c=a==null?u:u.filter(([,d])=>d.allowsObserve(a));return i?this._buildStructuredObserver(c,s,"all"):{subscribe:d=>{let l=c.map(([f,p])=>p.subscribe(m=>{d(f,m)}));return()=>{for(let f of l)f()}},up:(d,l)=>{try{this.resolve(d).up?.(l)}catch(f){if(f instanceof Je)return;throw f}}}}_buildStructuredObserver(e,n,r){let o=r==="one"?e[0]?.[0]:void 0,s=i=>{if(r==="one"&&o!=null){let d=this.resolve(o);return this._buildStructuredObserver([[o,d]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((d,l)=>d[0]<l[0]?-1:d[0]>l[0]?1:0);let u=i.actor,c=u==null?a:a.filter(([,d])=>d.allowsObserve(u));return this._buildStructuredObserver(c,i,"all")};return this._createObserveResult(e,n,s)}_createObserveResult(e,n,r){let o=n.timeline===!0,s=n.causal===!0,i=n.derived===!0,a=n.detail==="minimal",u=this.config.inspectorEnabled,c=(s||i)&&u,d=n.maxEvents,l=d!=null&&d>0?new rn(d):null,f=[],p=new Set,m={},h=new Set,g=0,y=0,b=0,v=0,T=0,w=0,k=!1,x=!1,S=0,_=new Map,F=new Map,L=new Map,D=j=>{l?l.push(j):f.push(j);for(let V of p)V(j)},C=()=>o?{timestamp_ns:B(),in_batch:Wt(),batch_id:S}:{},K=(j,V)=>{if(!(!c||!(j instanceof xe)))return j._setInspectorHook(J=>{if(J.kind==="dep_message")_.set(j,J.depIndex);else if(J.kind==="run"){let Y=J.batchData.map((W,ae)=>W!=null&&W.length>0?W.at(-1):J.prevData[ae]);F.set(j,Y);let Q=J.batchData.map(W=>W!=null?[...W]:void 0);L.set(j,Q),i&&D({type:"derived",path:V,dep_values:Y,dep_batches:Q,...C()})}})},ne=j=>{let V=_.get(j),J=F.get(j);if(!s||J==null)return{};let Q=(V!=null&&V>=0&&j instanceof xe?j._deps[V]:void 0)?.node,W=Q?.v,ae=L.get(j);return{trigger_dep_index:V,trigger_dep_name:Q?.name,...W!=null?{trigger_version:{id:W.id,version:W.version}}:{},dep_values:[...J],...ae!=null?{dep_batches:ae}:{}}},P=[],E=[];for(let[j,V]of e){let J=K(V,j);J&&P.push(J),E.push(V.subscribe(Y=>{S++;for(let Q of Y){let W=Q[0],ae=C();if(W===R){m[j]=Q[1];let ye=V instanceof xe?V.lastMutation?.actor??dt:dt;D({type:"data",path:j,data:Q[1],actor:ye,...ae,...ne(V)})}else if(a)W===Z?g++:W===$?y++:W===Ve?b++:W===Ae?v++:W===Pe?T++:W===de?w++:W===M&&!h.has(j)?k=!0:W===O&&(x=!0,h.add(j));else if(W===Z)g++,D({type:"dirty",path:j,...ae});else if(W===$)y++,D({type:"resolved",path:j,...ae,...ne(V)});else if(W===Ve)b++,D({type:"invalidate",path:j,...ae});else if(W===Ae)v++,D({type:"pause",path:j,lockId:Q[1],...ae});else if(W===Pe)T++,D({type:"resume",path:j,lockId:Q[1],...ae});else if(W===M)h.has(j)||(k=!0),D({type:"complete",path:j,...ae});else if(W===O){x=!0,h.add(j);let ye=V instanceof xe?V.lastMutation?.actor??dt:dt;D({type:"error",path:j,data:Q[1],actor:ye,...ae})}else W===de&&(w++,D({type:"teardown",path:j,...ae}))}}))}let I=!1,G=()=>{if(!I){I=!0;for(let j of E)j();for(let j of P)j();for(let j of U)j({value:void 0,done:!0});U.length=0}},te=[],U=[];p.add(j=>{let V=U.shift();V?V({value:j,done:!1}):te.push(j)});let ce={get values(){return m},get dirtyCount(){return g},get resolvedCount(){return y},get invalidateCount(){return b},get pauseCount(){return v},get resumeCount(){return T},get teardownCount(){return w},get events(){return l?l.toArray():[...f]},get anyCompletedCleanly(){return k},get anyErrored(){return x},get completedWithoutErrors(){return k&&!x},onEvent(j){return p.add(j),()=>p.delete(j)},dispose:G,expand(j){G();let V={...n};return typeof j=="string"?V.detail=j:Object.assign(V,j),r(Zu(V))},[Symbol.asyncIterator](){return{next(){return te.length>0?Promise.resolve({value:te.shift(),done:!1}):I?Promise.resolve({value:void 0,done:!0}):new Promise(j=>U.push(j))},return(){return G(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(ce,n),ce}_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,i=n.excludeTypes?new Set(n.excludeTypes):null,a=s==null&&i==null?()=>!0:m=>(s==null||s.has(m))&&(i==null||!i.has(m)),u=cf(n.theme),c=r==="stage-log"?B():0,d=m=>m==null?"":n.stageLabels?.[m]??m,l=(m,h)=>m.length>h?`${m.slice(0,h-1)}\u2026`:m,f=m=>m.type==="data"||m.type==="error"?l(Mo(m.data),120):"",p=m=>{if(r==="stage-log"){let x=(B()-c)/1e9,S=d(m.path).padEnd(9);if(m.type==="data"){let _=f(m);return`[${x.toFixed(3)}s] ${S} \u2190${_?` ${_}`:""}`}if(m.type==="error"){let _=f(m);return`[${x.toFixed(3)}s] ${S} \u2717${_?` ${_}`:""}`}return m.type==="complete"?`[${x.toFixed(3)}s] ${S} \u25A0 complete`:`[${x.toFixed(3)}s] ${S} ${m.type}`}if(r==="json")try{return JSON.stringify(m)}catch{return JSON.stringify({type:m.type,path:m.path,data:"[unserializable]"})}let h=u[m.type]??"",g=m.path?`${u.path}${m.path}${u.reset} `:"",y=m.type==="data"||m.type==="error",b=m.type==="pause"||m.type==="resume",v=y?` ${Mo(m.data)}`:b?` ${Mo(m.lockId)}`:"",T=m.type==="data"||m.type==="resolved"||m.type==="derived"?m:void 0,w=T?.trigger_dep_name!=null?` <- ${T.trigger_dep_name}`:T?.trigger_dep_index!=null?` <- #${T.trigger_dep_index}`:"",k=m.in_batch?" [batch]":"";return`${g}${h}${m.type.toUpperCase()}${u.reset}${v}${w}${k}`};e.onEvent(m=>{a(m.type)&&o(p(m),m)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){Qu(this._disposers,this.name),this.signal([[de]],{internal:!0}),Qu(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}_destroyClearOnly(){for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0}snapshot(e){let{expand:n,...r}=this.describe({detail:"full"}),o={};for(let a of Object.keys(r.nodes).sort()){let{lastMutation:u,guard:c,...d}=r.nodes[a];o[a]=d}let s=[...r.subgraphs].sort(),i={...r,version:1,nodes:o,subgraphs:s};if(e?.format==null)return i;if(e.format==="json-string")return JSON.stringify(i);if(e.format==="bytes"){if(e.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let a=this.config.lookupCodec(e.codec);if(a==null)throw new Error(`snapshot: codec "${e.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return er(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??Me,{codec:o,codecVersion:s,payload:i}=tr(e,r);return o.decode(i,s)}restore(e,n){if(Xu(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=>_o(s)),o=n?.includeProducers===!0;for(let s of Object.keys(e.nodes).sort()){if(r!==null&&!r.some(a=>a.test(s)))continue;let i=e.nodes[s];if(i!==void 0){if(!("value"in i)||i.value===void 0){"value"in i&&i.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(!(i.type==="derived"||i.type==="effect")&&!(i.type==="producer"&&!o)){if(i.v!=null){let u=this.tryResolve(s)?.v;if(u!=null&&u.id===i.v.id&&u.version===i.v.version)continue}try{this.set(s,i.value)}catch(a){n?.onError?.(s,a)}}}}}static fromSnapshot(e,n){Xu(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 p of[...e.subgraphs].sort((m,h)=>{let g=m.split(Ee).length,y=h.split(Ee).length;return g!==y?g-y:m<h?-1:m>h?1:0})){let m=p.split(Ee),h=s;for(let g of m)h._mounts.has(g)||h.mount(g,new t(g)),h=h._mounts.get(g)}let i=o?Object.entries(o).map(([p,m])=>({re:_o(p),factory:m})):[],a=p=>{for(let m of i)if(m.re.test(p))return m.factory},u=p=>{let m=p.split(Ee),h=m.pop();if(h==null||h.length===0)throw new Error(`invalid snapshot path "${p}"`);let g=s;for(let y of m){let b=g._mounts.get(y);if(!b)throw new Error(`unknown mount "${y}" in path "${p}"`);g=b}return[g,h]},c=Object.entries(e.nodes).filter(([p])=>!p.includes(`${Ee}${Be}${Ee}`)).sort((p,m)=>p[0]<m[0]?-1:p[0]>m[0]?1:0),d=new Map(c),l=new Map,f=!0;for(;d.size>0&&f;){f=!1;for(let[p,m]of[...d.entries()]){let h=m?.deps??[];if(!h.every(w=>l.has(w)))continue;let[g,y]=u(p),b={...m?.meta??{}},v=a(p),T;if(m?.type==="state")T=N(m.value,{meta:b});else{if(v==null)continue;T=v(y,{path:p,type:m.type,value:m.value,meta:b,deps:h,resolvedDeps:h.map(w=>l.get(w))})}g.add(T,{name:y}),l.set(p,T),d.delete(p),f=!0}}if(d.size>0){let p=[...d.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${p}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return s.restore(e),s}toJSON(){return this.snapshot()}attachStorage(e,n={}){let r=e.map(c=>({tier:c,debounceMs:Math.max(0,c.debounceMs??0),compactEvery:Math.max(1,c.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=(c,d)=>{if(c.disposed)return;let l=Yp(d.nodes);if(c.lastSnapshot!=null&&l!==""&&l===c.lastFingerprint)return;let f=c.seq+1,p=pe(),g=c.lastSnapshot==null||f%c.compactEvery===0?{mode:"full",snapshot:d,seq:f,timestamp_ns:p,format_version:it}:{mode:"diff",diff:Co(c.lastSnapshot,d),seq:f,timestamp_ns:p,format_version:it};if(c.tier.filter&&!c.tier.filter(this.name,g))return;let y;try{y=c.tier.save(this.name,g)}catch(b){n.onError?.(b,c.tier);return}if(y&&typeof y.then=="function"){let T=(c.savePending??Promise.resolve()).then(()=>y,()=>y).then(()=>{c.disposed||(c.seq=f,c.lastSnapshot=d,c.lastFingerprint=l)},w=>{n.onError?.(w,c.tier)});c.savePending=T.finally(()=>{c.savePending===T&&(c.savePending=void 0)})}else c.seq=f,c.lastSnapshot=d,c.lastFingerprint=l},s=(c,d)=>{try{o(c,d)}catch(l){n.onError?.(l,c.tier)}},i=(c,d)=>{if(!d.some(m=>{let h=this.config.messageTier(m[0]);return h>=3&&h<5}))return;if(n.filter){let m=this.tryResolve(c);if(m==null)return;let h=gr(m,Tt("standard"));if(!n.filter(c,h))return}let f,p=()=>(f==null&&(f=this.snapshot()),f);for(let m of r)m.disposed||(m.debounceMs===0?s(m,p()):(m.timer==null&&(m.timer=new Re),m.timer.start(m.debounceMs,()=>{m.disposed||s(m,this.snapshot())})))},a;if(n.paths!=null){let d=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(l=>{let f=this.tryResolve(l);return f==null?()=>{}:f.subscribe(p=>i(l,p))});a=()=>{for(let l of d)l()}}else a=this.observe().subscribe((c,d)=>i(c,d));let u=()=>{a();for(let c of r)c.disposed=!0,c.timer?.cancel();this._storageDisposers.delete(u)};return this._storageDisposers.add(u),{dispose:u}}async _cascadeRestore(e,n){for(let r of e){let o;try{o=await r.load(this.name)}catch(i){n?.(i,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(i){n?.(i,r)}}return!1}static async fromStorage(e,n,r){for(let o of n){let s;try{s=await o.load(e)}catch(u){r?.onError?.(u,o);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let i=s,a=i.mode==="full"&&i.snapshot!=null?i.snapshot:i.version===it&&i.nodes!=null?i:void 0;if(a!=null)try{return t.fromSnapshot(a,r)}catch(u){r?.onError?.(u,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:B(),...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(b=>!r.has(b)).sort(),i=[...r].filter(b=>!o.has(b)).sort(),a=[],u=[];for(let b of r){if(!o.has(b))continue;let v=e.nodes[b],T=n.nodes[b],w=v.v,k=T.v;w!=null&&k!=null&&w.id===k.id&&w.version!==k.version&&u.push({path:b,id:w.id,from:w.version,to:k.version});let x=w!=null&&k!=null&&w.id===k.id&&w.version===k.version;for(let S of["type","status","sentinel"]){let _=v[S],F=T[S];_!==F&&a.push({path:b,field:S,from:_,to:F})}if(!x)for(let S of["value","meta"]){let _=v[S],F=T[S];Qp(_,F)||a.push({path:b,field:S,from:_,to:F})}}let c=b=>`${b.from} ${b.to}`,d=new Set(e.edges.map(c)),l=new Set(n.edges.map(c)),f=n.edges.filter(b=>!d.has(c(b))),p=e.edges.filter(b=>!l.has(c(b))),m=new Set(e.subgraphs),h=new Set(n.subgraphs),g=[...h].filter(b=>!m.has(b)).sort(),y=[...m].filter(b=>!h.has(b)).sort();return{nodesAdded:s,nodesRemoved:i,nodesChanged:a,versionChanges:u,edgesAdded:f,edgesRemoved:p,subgraphsAdded:g,subgraphsRemoved:y}}};function Co(t,e){let n=z.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 sn(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 i=new Map,a=new Map,u=new Map,c=new Map,d=new Set;for(let[v,T]of Object.entries(t.nodes)){if(!v)continue;d.add(v);let w=T.deps??[];i.set(v,w);for(let k of w)k&&(d.add(k),a.has(k)||a.set(k,new Set),a.get(k).add(v))}for(let v of t.edges){if(v==null||typeof v!="object")continue;let T=typeof v.from=="string"?v.from:"",w=typeof v.to=="string"?v.to:"";!T||!w||(d.add(T),d.add(w),c.has(T)||c.set(T,new Set),c.get(T).add(w),u.has(w)||u.set(w,new Set),u.get(w).add(T))}if(!d.has(e))return r.withDetail?o:[];let l=r.both===!0,f=v=>{if(l){let x=i.get(v)??[],S=u.get(v),_=a.get(v),F=c.get(v),L=[...x];return S&&L.push(...S),_&&L.push(..._),F&&L.push(...F),L}if(n==="upstream"){let x=i.get(v)??[],S=u.get(v);return S?[...x,...S]:x}let T=a.get(v),w=c.get(v),k=T?[...T]:[];return w&&k.push(...w),k},p=new Set([e]),m=new Map,h=[{path:e,depth:0}],g=0,y=!1;for(;g<h.length;){let v=h[g++];if(s!=null&&v.depth>=s){f(v.path).length>0&&(y=!0);continue}for(let T of f(v.path))!T||p.has(T)||(p.add(T),m.set(T,v.depth+1),h.push({path:T,depth:v.depth+1}))}let b=[...m.keys()].sort((v,T)=>v<T?-1:v>T?1:0);return r.withDetail?{paths:b,depths:m,truncated:y}:b}function ff(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,i=o.v;if(s!==i&&(s==null||i==null||s.id!==i.id||s.version!==i.version))return!1}return!0}var Io={};he(Io,{CqrsGraph:()=>Lo,MemoryEventStore:()=>Mi,cqrs:()=>Oi});Se();Te();Jt();var Si={};he(Si,{COMPLETE:()=>M,COMPLETE_MSG:()=>Yr,COMPLETE_ONLY_BATCH:()=>Zn,DATA:()=>R,DEFAULT_ACTOR:()=>dt,DIRTY:()=>Z,DIRTY_MSG:()=>gt,DIRTY_ONLY_BATCH:()=>Tn,ERROR:()=>O,GraphReFlyConfig:()=>Ut,GuardDenied:()=>Je,INVALIDATE:()=>Ve,INVALIDATE_MSG:()=>Jr,INVALIDATE_ONLY_BATCH:()=>Xn,NodeImpl:()=>xe,PAUSE:()=>Ae,RESOLVED:()=>$,RESOLVED_MSG:()=>bn,RESOLVED_ONLY_BATCH:()=>Qn,RESUME:()=>Pe,START:()=>ct,START_MSG:()=>vn,TEARDOWN:()=>de,TEARDOWN_MSG:()=>Qr,TEARDOWN_ONLY_BATCH:()=>wn,accessHintForGuard:()=>cr,advanceVersion:()=>dr,autoTrackNode:()=>Yt,batch:()=>ee,configure:()=>ui,createVersioning:()=>Sn,defaultConfig:()=>Me,defaultHash:()=>Mt,derived:()=>A,downWithBatch:()=>bt,dynamicNode:()=>lr,effect:()=>fe,isBatching:()=>Wt,isV1:()=>si,monotonicNs:()=>B,node:()=>q,normalizeActor:()=>yt,pipe:()=>ci,policy:()=>zt,policyFromRules:()=>ur,producer:()=>H,registerBuiltins:()=>ar,resolveDescribeFields:()=>Tt,state:()=>N,wallClockNs:()=>pe});rr();Se();Te();ri();Jt();ie();we();le();eo();Se();ie();le();var vr=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 i=new Array(s);for(let a=0;a<s;a++)i[a]=this._buf[(this._head+o+a)%this._maxSize];return i}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}_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 oc(t){return t.subscribe(()=>{})}var mf=64;function je(t,e={}){let{name:n,maxSize:r,versioning:o,backend:s}=e,i=s??new vr(t,r),a=N(i.toArray(),{name:n,describeKind:"state",equals:(m,h)=>m===h,...o!=null?{versioning:o}:{}});function u(){let m=i.toArray();ee(()=>{a.down([[Z]]),a.down([[R,m]])})}let c=new Map,d=new Map;function l(m,h){return`${m}:${h===void 0?"END":h}`}function f(m){if(m.size<mf)return;let h=m.keys().next();if(h.done)return;let g=m.get(h.value);g!==void 0&&g.dispose(),m.delete(h.value)}function p(m){let h=i.version;try{return m()}finally{i.version!==h&&u()}}return{entries:a,get size(){return i.size},at(m){return i.at(m)},append(m){p(()=>i.append(m))},appendMany(m){m.length!==0&&p(()=>i.appendMany(m))},clear(){p(()=>i.clear())},trimHead(m){p(()=>i.trimHead(m))},tail(m){if(!Number.isInteger(m)||m<0)throw new RangeError(`tail: n must be a non-negative integer (got ${m})`);let h=c.get(m);if(h!==void 0)return c.delete(m),c.set(m,h),h.node;f(c);let g=A([a],([b])=>{let v=b;return m===0||v.length===0?[]:v.slice(Math.max(0,v.length-m))},{initial:i.tail(m),describeKind:"derived"}),y=oc(g);return c.set(m,{node:g,dispose:y}),g},slice(m,h){if(!Number.isInteger(m)||m<0)throw new RangeError(`slice: start must be a non-negative integer (got ${m})`);if(h!==void 0&&(!Number.isInteger(h)||h<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${h})`);let g=l(m,h),y=d.get(g);if(y!==void 0)return d.delete(g),d.set(g,y),y.node;f(d);let b=A([a],([T])=>{let w=T;return h===void 0?w.slice(m):w.slice(m,h)},{initial:i.slice(m,h),describeKind:"derived"}),v=oc(b);return d.set(g,{node:b,dispose:v}),b},disposeTail(m){let h=c.get(m);return h===void 0?!1:(h.dispose(),c.delete(m),!0)},disposeSlice(m,h){let g=l(m,h),y=d.get(g);return y===void 0?!1:(y.dispose(),d.delete(g),!0)},disposeAllViews(){for(let m of c.values())m.dispose();c.clear();for(let m of d.values())m.dispose();d.clear()},dispose(){for(let m of c.values())m.dispose();c.clear();for(let m of d.values())m.dispose();d.clear()}}}var Ei={};he(Ei,{ENVELOPE_VERSION:()=>kn,GRAPH_META_SEGMENT:()=>Be,Graph:()=>z,JsonCodec:()=>Xr,SIZEOF_OVERHEAD:()=>Oe,SIZEOF_SYMBOL:()=>Eo,SNAPSHOT_VERSION:()=>it,createDagCborCodec:()=>ei,createDagCborZstdCodec:()=>ti,decodeEnvelope:()=>tr,diffForWAL:()=>Co,encodeEnvelope:()=>er,explainPath:()=>yr,graphProfile:()=>on,mermaidLiveUrl:()=>Oo,reachable:()=>sn,registerBuiltinCodecs:()=>nr,replayWAL:()=>ni,sizeof:()=>br,validateGraphObservability:()=>Ni,watchTopologyTree:()=>wt});Zr();ie();function wt(t,e){let n=new Map,r=(o,s)=>{if(n.has(o))return;let i={off:()=>{},prefix:s};n.set(o,i);let a=o.topology.subscribe(u=>{for(let c of u){if(c[0]!==R)continue;let d=c[1];if(e(d,o,s),d.kind==="added"&&d.nodeKind==="mount"){let l=o._mounts.get(d.name);if(l instanceof z){let f=`${s}${d.name}::`;r(l,f)}}else if(d.kind==="removed"&&d.nodeKind==="mount"){let l=`${s}${d.name}::`;for(let[f,p]of Array.from(n.entries()))f!==t&&p.prefix.startsWith(l)&&(p.off(),n.delete(f))}}});i.off=a;for(let[u,c]of o._mounts)if(c instanceof z){let d=`${s}${u}::`;r(c,d)}};return r(t,""),()=>{for(let o of n.values())o.off();n.clear()}}function Ni(t,e={}){let n=[],r=e.requireFound??!0;if(e.skipDescribe!==!0)try{let c=t.describe(),d=new Set(Object.keys(c.nodes)),l=[];for(let[f,p]of Object.entries(c.nodes))for(let m of p.deps)m!==""&&!d.has(m)&&l.push(`${f} \u2192 ${m}`);for(let f of c.edges)d.has(f.from)||l.push(`edge.from: ${f.from}`),d.has(f.to)||l.push(`edge.to: ${f.to}`);l.length>0?n.push({kind:"describe",ok:!1,reason:`describe() has ${l.length} dangling pointer(s); nodes \u2289 deps`,danglingDeps:l}):n.push({kind:"describe",ok:!0,nodeCount:d.size,edgeCount:c.edges.length})}catch(c){n.push({kind:"describe",ok:!1,reason:`describe() threw: ${c instanceof Error?c.message:String(c)}`})}for(let c of e.formats??[])try{let d=t.describe({format:c});typeof d!="string"||d.length===0?n.push({kind:"describe-format",ok:!1,format:c,reason:`describe({ format: "${c}" }) returned empty or non-string output`}):n.push({kind:"describe-format",ok:!0,format:c,length:d.length})}catch(d){n.push({kind:"describe-format",ok:!1,format:c,reason:d instanceof Error?d.message:String(d)})}for(let c of e.paths??[])try{t.resolve(c),n.push({kind:"observe",ok:!0,path:c})}catch(d){n.push({kind:"observe",ok:!1,path:c,reason:d instanceof Error?d.message:String(d)})}for(let[c,d]of e.pairs??[])try{let l=t.explain(c,d);r&&l.found===!1?n.push({kind:"explain",ok:!1,from:c,to:d,reason:`explain(${c} \u2192 ${d}) found no path${l.reason?`: ${l.reason}`:""}`}):n.push({kind:"explain",ok:!0,from:c,to:d,found:l.found,steps:l.steps.length})}catch(l){n.push({kind:"explain",ok:!1,from:c,to:d,reason:l instanceof Error?l.message:String(l)})}let o=n.filter(c=>!c.ok),s=o.length===0,i=e.paths?.length??0,a=e.pairs?.length??0,u=e.formats?.length??0;return{ok:s,checks:n,failures:o,summary(){let c=[e.skipDescribe===!0?null:"describe",u>0?`${u} format${u===1?"":"s"}`:null,i>0?`${i} observe path${i===1?"":"s"}`:null,a>0?`${a} explain pair${a===1?"":"s"}`:null].filter(l=>l!=null),d=c.length>0?c.join(", "):"describe-only";return s?`validateGraphObservability: OK (${d})`:`validateGraphObservability: ${o.length} failure(s) across ${d}`}}}Se();ie();we();$e();function at(t,e){t!=null&&bt(n=>t.down(n),[[R,e]],Me.tierOf)}function Tr(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[Z],[R,n+1]]),!0)}function Ke(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}function _i(t){return t.relatedTo?.[0]??t.summary}var hf=zt((t,e)=>{t("write"),t("signal"),e("observe")}),gf=zt((t,e)=>{t("observe"),t("signal"),e("write")}),yf=zt((t,e)=>{t("observe"),t("signal"),e("write")});function Ao(t,e){return Ke("cqrs",t,e)}var Mi=class{_store=new Map;persist(e){let n=this._store.get(e.type);n||(n=[],this._store.set(e.type,n)),n.push(e)}loadEvents(e,n){let r=this._store.get(e)??[],o=n?.timestampNs,s=n?.seq,i=o==null?[...r]:r.filter(u=>u.timestampNs>o||u.timestampNs===o&&u.seq>(s??-1)),a=i.length>0?i[i.length-1]:void 0;return{events:i,cursor:a?{timestampNs:a.timestampNs,seq:a.seq}:n}}clear(){this._store.clear()}},Lo=class extends z{_eventLogs=new Map;_commandHandlers=new Map;_projections=new Set;_sagas=new Set;_keepaliveDisposers=[];_eventStore;_seq=0;constructor(e,n={}){super(e,n.graph)}destroy(){for(let e of this._keepaliveDisposers)e();this._keepaliveDisposers.length=0,super.destroy()}event(e){let n=this._eventLogs.get(e);if(n)return n.node;let r=je([],{name:e,versioning:0}),o=r.entries,s=A([o],([i])=>i,{name:e,describeKind:"state",meta:Ao("event",{event_name:e}),guard:yf,initial:o.cache});return this.add(s,{name:e}),this._keepaliveDisposers.push(oe(s)),this._eventLogs.set(e,{log:r,node:s}),s}_appendEvent(e,n){let r=this._eventLogs.get(e);if(r||(this.event(e),r=this._eventLogs.get(e)),r.node.status==="completed"||r.node.status==="errored")throw new Error(`Cannot dispatch to terminated event stream "${e}" (status: ${r.node.status}).`);let o=r.log.entries.v,s={type:e,payload:n,timestampNs:pe(),seq:++this._seq,...o!=null?{v0:{id:o.id,version:o.version}}:{}};r.log.append(s),this._eventStore&&this._eventStore.persist(s)}command(e,n){let r=N(void 0,{name:e,describeKind:"state",meta:{...Ao("command",{command_name:e}),error:null},guard:hf});return this.add(r,{name:e}),this._commandHandlers.set(e,n),r}dispatch(e,n){let r=this._commandHandlers.get(e);if(!r)throw new Error(`Unknown command: "${e}". Register with .command() first.`);let o=this.resolve(e);ee(()=>{o.emit(n,{internal:!0});try{r(n,{emit:(s,i)=>this._appendEvent(s,i)}),o.meta.error.emit(null,{internal:!0})}catch(s){throw o.meta.error.emit(s,{internal:!0}),s}})}projection(e,n,r,o){let s=n.map(a=>(this._eventLogs.has(a)||this.event(a),this._eventLogs.get(a).node)),i=A(s,a=>{let u=[];for(let c of a){let d=c;u.push(...d)}return u.sort((c,d)=>c.timestampNs-d.timestampNs||c.seq-d.seq),r(o,u)},{name:e,describeKind:"derived",meta:Ao("projection",{projection_name:e,source_events:n}),guard:gf,initial:o});return this.add(i,{name:e}),this._keepaliveDisposers.push(oe(i)),this._projections.add(e),i}saga(e,n,r){let o=n.map(u=>(this._eventLogs.has(u)||this.event(u),this._eventLogs.get(u).node)),s=new Map,i={},a=q(o,(u,c)=>{let d=i.n.meta.error;for(let l=0;l<u.length;l++){let f=u[l];if(f==null||f.length===0)continue;let p=f.at(-1);if(!p)continue;let m=n[l],h=s.get(m)??0;if(p.length>h){let g=p.slice(h);for(let y of g)try{r(y),d.emit(null,{internal:!0})}catch(b){d.emit(b,{internal:!0})}s.set(m,p.length)}}},{name:e,describeKind:"effect",meta:{...Ao("saga",{saga_name:e,source_events:n}),error:null}});return i.n=a,this.add(a,{name:e}),this._keepaliveDisposers.push(oe(a)),this._sagas.add(e),a}useEventStore(e){this._eventStore=e}async rebuildProjection(e,n,r){if(!this._eventStore)throw new Error("No event store wired. Call useEventStore() first.");let o=[];for(let s of e){let i=await this._eventStore.loadEvents(s);o.push(...i.events)}return o.sort((s,i)=>s.timestampNs-i.timestampNs||s.seq-i.seq),n(r,o)}};function Oi(t,e){return new Lo(t,e)}var Ai=class{constructor(e){this.graph=e}onModuleDestroy(){this.graph.destroy()}},Li=class{graph=new z("request");onModuleDestroy(){this.graph.destroy()}},sc,Ci;sc=[(0,wr.Module)({})];var Pt=class Pt{static forRoot(e){let n=e??{},r=n.name??"root",o=[{provide:Xe,useFactory:()=>{let s=new z(r);return n.build&&n.build(s),n.snapshot&&s.restore(n.snapshot),s}},{provide:Symbol.for("graphrefly:root-lifecycle"),useFactory:s=>new Ai(s),inject:[Xe]},{provide:nn,useFactory:(s,i)=>new nn(s,i),inject:[Xe,ic.ModuleRef]}];if(n.nodes)for(let s of n.nodes)o.push({provide:ot(s),useFactory:i=>i.resolve(s),inject:[Xe]});return n.requestScope&&o.push({provide:Symbol.for("graphrefly:request-lifecycle"),useFactory:()=>new Li,scope:wr.Scope.REQUEST},{provide:Qt,useFactory:s=>s.graph,inject:[Symbol.for("graphrefly:request-lifecycle")],scope:wr.Scope.REQUEST}),{module:Pt,global:!0,providers:o,exports:[Xe,...(n.nodes??[]).map(ot),...n.requestScope?[Qt]:[]]}}static forFeature(e){let n=[{provide:Ye(e.name),useFactory:r=>{let o=new z(e.name);return e.build&&e.build(o),e.snapshot&&o.restore(e.snapshot),r.mount(e.name,o),o},inject:[Xe]}];if(e.nodes)for(let r of e.nodes)n.push({provide:ot(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[Ye(e.name)]});return{module:Pt,providers:n,exports:[Ye(e.name),...(e.nodes??[]).map(r=>ot(`${e.name}::${r}`))]}}static forCqrs(e){let n=[{provide:Ye(e.name),useFactory:r=>{let o=Oi(e.name,e.cqrs);return e.eventStore&&o.useEventStore(e.eventStore),e.build&&e.build(o),r.mount(e.name,o),o},inject:[Xe]}];if(e.nodes)for(let r of e.nodes)n.push({provide:ot(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[Ye(e.name)]});return{module:Pt,providers:n,exports:[Ye(e.name),...(e.nodes??[]).map(r=>ot(`${e.name}::${r}`))]}}};Ci=eu(null),Pt=ru(Ci,0,"GraphReflyModule",sc,Pt),nu(Ci,1,Pt);var Po=Pt;var Go={};he(Go,{useStore:()=>bf,useSubscribe:()=>ac,useSubscribeRecord:()=>vf});var kt=require("react");ie();function ac(t){return(0,kt.useSyncExternalStore)(e=>{let n=!1,r=t.subscribe(()=>{n||e()});return()=>{n=!0,r()}},()=>t.cache,()=>t.cache)}function bf(t){let e=ac(t),n=(0,kt.useCallback)(r=>{t.down([[Z],[R,r]])},[t]);return[e,n]}function vf(t,e){let n=(0,kt.useRef)(e);n.current=e;let r=(0,kt.useMemo)(()=>{let o=()=>{let i={},a=t.cache??[];for(let u of a){let c=n.current(u),d={};for(let l of Object.keys(c))d[l]=c[l].cache;i[u]=d}return i},s=o();return{subscribe:i=>{let a=!1,u=[],c=()=>{for(let f of u)f();u=[]},d=f=>{c();for(let p of f){let m=n.current(p);for(let h of Object.keys(m)){let g=m[h].subscribe(()=>{s=o(),a||i()});u.push(g)}}s=o(),a||i()},l=t.subscribe(f=>{let p=f.some(m=>m[0]===R||m[0]===$);!a&&p&&d(t.cache??[])});return d(t.cache??[]),()=>{a=!0,l(),c()}},getSnapshot:()=>s}},[t]);return(0,kt.useSyncExternalStore)(r.subscribe,r.getSnapshot,r.getSnapshot)}var $o={};he($o,{Signal:()=>Tf});Se();ie();le();var jn=[];function Fo(t){let e=t.cache;return t.subscribe(r=>{for(let[o,s]of r)o===R&&(e=s)})(),e}var Ii=class{_node;_equals;constructor(e,n){this._equals=n?.equals??Object.is,this._node=N(e,{...n,resubscribable:!0,resetOnTeardown:!0})}get(){let e=jn[jn.length-1];return e?(this._node.status==="sentinel"&&Fo(this._node),e(this._node)):this._node.status==="sentinel"?Fo(this._node):this._node.cache}set(e){this._equals(this.get(),e)||ee(()=>{this._node.down([[Z],[R,e]])})}},Pi=class{_node;constructor(e,n){this._node=Yt(r=>{jn.push(r);try{return e()}finally{jn.pop()}},{...n,describeKind:"derived",resubscribable:!0,resetOnTeardown:!0})}get(){let e=jn[jn.length-1];return e?(this._node.status==="sentinel"&&Fo(this._node),e(this._node)):this._node.status==="sentinel"?Fo(this._node):this._node.cache}},Tf={State:Ii,Computed:Pi,sub:(t,e)=>{let n=typeof e=="function"?{data:e,error:void 0,complete:void 0}:e,r=!0;return t._node.subscribe(o=>{for(let[s,i]of o){if(s===R){if(r){r=!1;continue}n.data?.(i)}s===O&&n.error?.(i),s===M&&n.complete?.()}})}};var Bo={};he(Bo,{useStore:()=>wf,useSubscribe:()=>uc,useSubscribeRecord:()=>kf});var xt=require("solid-js");ie();function uc(t){let[e,n]=(0,xt.createSignal)(t.cache,{equals:!1}),r=t.subscribe(()=>{n(()=>t.cache)});return(0,xt.getOwner)()?(0,xt.onCleanup)(()=>r()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Solid reactive owner \u2014 subscription will not be auto-disposed."),e}function wf(t){return[uc(t),r=>{t.down([[Z],[R,r]])}]}function kf(t,e){let[n,r]=(0,xt.createSignal)({},{equals:!1}),o=[],s=()=>{for(let c of o)c();o=[]},i=()=>{let c={};for(let d of t.cache??[]){let l=e(d),f={};for(let p of Object.keys(l))f[p]=l[p].cache;c[d]=f}return c},a=c=>{s();for(let d of c){let l=e(d);for(let f of Object.keys(l)){let p=l[f].subscribe(()=>{r(()=>i())});o.push(p)}}r(()=>i())},u=t.subscribe(c=>{c.some(d=>d[0]===R||d[0]===$)&&a(t.cache??[])});return a(t.cache??[]),(0,xt.getOwner)()?(0,xt.onCleanup)(()=>{u(),s()}):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribeRecord called outside a Solid reactive owner \u2014 subscription will not be auto-disposed."),n}var jo={};he(jo,{useStore:()=>Rf,useSubscribe:()=>xf,useSubscribeRecord:()=>Sf});ie();function xf(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n}}}function Rf(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n},set(e){t.down([[Z],[R,e]])},update(e){let n=e(t.cache);t.down([[Z],[R,n]])}}}function Sf(t,e){return{subscribe(n){let r=[],o=()=>{for(let u of r)u();r=[]},s=()=>{let u={};for(let c of t.cache??[]){let d=e(c),l={};for(let f of Object.keys(d))l[f]=d[f].cache;u[c]=l}return u},i=u=>{o();for(let c of u){let d=e(c);for(let l of Object.keys(d)){let f=d[l].subscribe(()=>{n(s())});r.push(f)}}n(s())},a=t.subscribe(u=>{u.some(c=>c[0]===R||c[0]===$)&&i(t.cache??[])});return i(t.cache??[]),()=>{a(),o()}}}}var Ko={};he(Ko,{useStore:()=>Ef,useSubscribe:()=>Nf,useSubscribeRecord:()=>_f});var Le=require("vue");ie();function Nf(t){let e=(0,Le.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,Le.getCurrentScope)()?(0,Le.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Le.readonly)(e)}function Ef(t){let e=(0,Le.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,Le.getCurrentScope)()?(0,Le.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useStore called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Le.computed)({get:()=>e.value,set:r=>{t.down([[Z],[R,r]])}})}function _f(t,e){let n=(0,Le.shallowRef)({}),r=new Map;function o(){let a={};for(let[u,c]of r)a[u]={...c.values};n.value=a}function s(a){for(let c of r.values())for(let d of c.subs)d();r.clear();for(let c of a){let d=e(c),l=Object.keys(d),f={},p=[];for(let m of l){let h=d[m];f[m]=h.cache;let g=h.subscribe(()=>{f[m]=h.cache,o()});p.push(g)}r.set(c,{subs:p,values:f})}let u={};for(let[c,d]of r)u[c]={...d.values};n.value=u}return(0,Le.watch)(()=>[...(typeof t=="function"?t():(0,Le.isRef)(t)?t.value:t)??[]],a=>s(a??[]),{immediate:!0}),(0,Le.getCurrentScope)()?(0,Le.onScopeDispose)(()=>{for(let a of r.values())for(let u of a.subs)u();r.clear()}):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribeRecord called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Le.readonly)(n)}var Vo={};he(Vo,{create:()=>Of});ie();le();var Mf=()=>!1;function Of(t){let e=new z("zustand"),n=N(void 0,{name:"state",equals:Mf});e.add(n,{name:"state"});let r=()=>n.cache,o=(a,u)=>{let c=n.cache,d=typeof a=="function"?a(c):a;n.emit(u?d:{...c,...d})},s={getState:r,setState:o,getInitialState:()=>i,subscribe:a=>{let u=!0,c=n.cache;return n.subscribe(d=>{for(let[l,f]of d)if(l===R){if(u){u=!1;continue}a(f,c),c=f}})},destroy:e.destroy.bind(e)},i=t(o,r,s);return n.emit(i),Object.assign(e,s)}var Qi={};he(Qi,{CircuitOpenError:()=>st,NS_PER_MS:()=>De,NS_PER_SEC:()=>Qe,NativeIndexBackend:()=>Or,NativeListBackend:()=>Cr,NativeLogBackend:()=>vr,NativeMapBackend:()=>Er,NativePubSubBackend:()=>Mr,RateLimiterOverflowError:()=>Zt,ResettableTimer:()=>Re,TimeoutError:()=>en,audit:()=>_c,awaitSettled:()=>wo,buffer:()=>Mc,bufferCount:()=>Oc,bufferTime:()=>Ac,cached:()=>Bu,cascadingCache:()=>Bd,catchError:()=>Kc,checkpointToRedis:()=>Ad,checkpointToS3:()=>Cd,circuitBreaker:()=>pt,combine:()=>Fi,combineLatest:()=>$c,concat:()=>wc,concatMap:()=>Rc,constant:()=>lo,createTransport:()=>Gt,createWatermarkController:()=>Bn,csvRows:()=>fd,debounce:()=>Bi,debounceTime:()=>Bc,decorrelatedJitter:()=>ho,delay:()=>Nc,deserializeError:()=>ln,dictStorage:()=>Yd,distill:()=>Uo,distinctUntilChanged:()=>bc,elementAt:()=>gc,empty:()=>Pu,escapeRegexChar:()=>hi,exhaustMap:()=>xc,exponential:()=>fo,externalBundle:()=>qo,externalProducer:()=>an,fallback:()=>Gn,fibonacci:()=>mo,filter:()=>xr,find:()=>hc,first:()=>Ho,firstValueFrom:()=>$n,firstWhere:()=>yo,flatMap:()=>Sc,forEach:()=>It,fromAny:()=>re,fromAsyncIter:()=>yi,fromCSV:()=>pd,fromClickHouseWatch:()=>yd,fromCron:()=>bo,fromDrizzle:()=>Gd,fromEvent:()=>Iu,fromHTTP:()=>Hi,fromHTTPPoll:()=>Xc,fromHTTPStream:()=>Qc,fromIter:()=>vo,fromKafka:()=>ud,fromKysely:()=>Fd,fromMCP:()=>td,fromNATS:()=>Td,fromNDJSON:()=>gd,fromOTel:()=>nd,fromPrisma:()=>Dd,fromPrometheus:()=>ad,fromPromise:()=>gi,fromPulsar:()=>bd,fromRabbitMQ:()=>kd,fromRaf:()=>Lu,fromRedisStream:()=>dd,fromSSE:()=>Yc,fromSqlite:()=>Ld,fromSqliteCursor:()=>Id,fromStatsD:()=>sd,fromSyslog:()=>rd,fromTimer:()=>et,fromWebSocket:()=>qi,fromWebSocketReconnect:()=>ed,fromWebhook:()=>Vc,globToRegExp:()=>Cu,interval:()=>Pc,keepalive:()=>oe,last:()=>mc,linear:()=>po,lru:()=>zi,map:()=>kr,matchesAnyPattern:()=>Au,matchesCron:()=>co,memoryStorage:()=>Lr,merge:()=>ft,mergeMap:()=>$i,nameToSignal:()=>cn,ndjsonRows:()=>md,never:()=>Du,of:()=>bi,pairwise:()=>vc,parseCron:()=>uo,parsePrometheusText:()=>Wi,parseStatsD:()=>id,parseSyslog:()=>od,pausable:()=>Gc,pubsub:()=>qd,race:()=>kc,rateLimiter:()=>Dn,reactiveCounter:()=>vi,reactiveIndex:()=>Ud,reactiveList:()=>zo,reactiveLog:()=>je,reactiveMap:()=>tt,reactiveSink:()=>Ge,reduce:()=>lc,repeat:()=>Dc,replay:()=>To,rescue:()=>Sr,resolveBackoffPreset:()=>Ot,retry:()=>In,retrySource:()=>Ct,sample:()=>Ec,scan:()=>dc,serializeError:()=>dn,share:()=>$u,shareReplay:()=>ju,signalToName:()=>Dt,singleFromAny:()=>Jo,singleNodeFromAny:()=>zd,skip:()=>Gi,sortJsonValue:()=>Ar,stableJsonString:()=>Jd,stratify:()=>Ir,switchMap:()=>_e,take:()=>Rr,takeUntil:()=>fc,takeWhile:()=>pc,tap:()=>yc,throttle:()=>ji,throttleTime:()=>jc,throwError:()=>Gu,timeout:()=>Fn,toArray:()=>Fu,toCSV:()=>Rd,toClickHouse:()=>Sd,toFile:()=>Ui,toHTTP:()=>qc,toKafka:()=>cd,toLoki:()=>Md,toMongo:()=>_d,toNATS:()=>wd,toObservable:()=>ao,toPostgres:()=>Ed,toPulsar:()=>vd,toRabbitMQ:()=>xd,toReadableStream:()=>Jc,toRedisStream:()=>ld,toS3:()=>Nd,toSSE:()=>Uc,toSSEBytes:()=>zc,toSqlite:()=>Pd,toTempo:()=>Od,toWebSocket:()=>Zc,tokenBucket:()=>At,valve:()=>Fc,verifiable:()=>Vd,window:()=>Ic,windowCount:()=>Cc,windowTime:()=>Lc,withBreaker:()=>Pn,withLatestFrom:()=>un,withMaxAttempts:()=>fi,withStatus:()=>Lt,workerBridge:()=>Ji,workerSelf:()=>Yi,zip:()=>Tc});Se();Te();ie();we();le();Se();ie();le();function cc(t){return{describeKind:"producer",...t}}function an(t,e){return H(n=>{let r=!0,o={emit(i){r&&n.emit(i)},error(i){r&&(r=!1,n.down([[O,i]]))},complete(){r&&(r=!1,n.down([[M]]))}},s;try{let i=t(o);s=typeof i=="function"?i:void 0}catch(i){return o.error(i),()=>{r=!1}}return()=>{r=!1;try{s?.()}catch{}}},cc(e))}function qo(t,e,n){let r=!0,o,s=0,i=0,a={},u=[],c=()=>{let p=o;o=void 0;try{p?.()}catch{}};for(let p of e){let m=n?.name?`${n.name}::${p}`:p,h=n?.channelOpts?.[p],g=H(y=>(s++,()=>{i++,s>0&&i>=s&&i>=e.length&&c()}),cc({...h,name:m}));a[p]=g,u.push(g)}let d={};for(let p of e)d[p]=m=>{r&&a[p].down([[R,m]])};d.error=p=>{r&&(r=!1,ee(()=>{for(let m of u)m.down([[O,p]])}),c())},d.complete=()=>{r&&(r=!1,ee(()=>{for(let p of u)p.down([[M]])}),c())};let l=t(d);return o=typeof l=="function"?l:void 0,Object.assign(a,{dispose:()=>{r&&(r=!1,ee(()=>{for(let p of u)try{p.down([[M]])}catch{}}),c())}})}Te();ie();we();le();$e();function se(t){return{describeKind:"derived",...t}}function kr(t,e,n){return q([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[$]]);return}for(let i of s)o.emit(e(i))},se(n))}function xr(t,e,n){return q([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[$]]);return}let i=!1;for(let a of s)e(a)&&(o.emit(a),i=!0);i||o.down([[$]])},se(n))}function dc(t,e,n,r){return q([t],(o,s,i)=>{"acc"in i.store||(i.store.acc=n);let a=o[0];if(a==null||a.length===0){s.down([[$]]);return}for(let u of a)i.store.acc=e(i.store.acc,u),s.emit(i.store.acc)},{...se(r),initial:n,resetOnTeardown:!0})}function lc(t,e,n,r){return q([t],(o,s,i)=>{if("acc"in i.store||(i.store.acc=n),i.terminalDeps[0]===!0){s.emit(i.store.acc),s.down([[M]]);return}let a=o[0];if(a==null||a.length===0){s.down([[$]]);return}for(let u of a)i.store.acc=e(i.store.acc,u)},{...se(r),completeWhenDepsComplete:!1})}function Rr(t,e,n){return e<=0?q([t],(r,o,s)=>{s.store.completed||(s.store.completed=!0,o.down([[M]]))},{...se(n),completeWhenDepsComplete:!1}):q([t],(r,o,s)=>{if("taken"in s.store||(s.store.taken=0),s.store.done){o.down([[$]]);return}if(s.terminalDeps[0]===!0){s.store.done=!0,o.down([[M]]);return}let i=r[0];if(i==null||i.length===0){o.down([[$]]);return}for(let a of i)if(s.store.taken++,o.emit(a),s.store.taken>=e){s.store.done=!0,o.down([[M]]);return}},{...se(n),completeWhenDepsComplete:!1})}function Gi(t,e,n){return q([t],(r,o,s)=>{"skipped"in s.store||(s.store.skipped=0);let i=r[0];if(i==null||i.length===0){o.down([[$]]);return}let a=!1;for(let u of i)s.store.skipped++,s.store.skipped<=e||(o.emit(u),a=!0);a||o.down([[$]])},se(n))}function pc(t,e,n){return q([t],(r,o,s)=>{if(s.store.done){o.down([[$]]);return}let i=r[0];if(i==null||i.length===0){o.down([[$]]);return}for(let a of i){if(!e(a)){s.store.done=!0,o.down([[M]]);return}o.emit(a)}},{...se(n),completeWhenDepsComplete:!1})}function fc(t,e,n){let r=n?.predicate??(i=>i[0]===R),{predicate:o,...s}=n??{};return H(i=>{let a=!1,u=t.subscribe(d=>{if(!a)for(let l of d){if(a)return;l[0]===R?i.emit(l[1]):(l[0]===M||l[0]===O)&&(a=!0,i.down([l]))}}),c=e.subscribe(d=>{if(!a)for(let l of d){if(a)return;if(r(l)){a=!0,i.down([[M]]);return}}});return()=>{u(),c()}},se(s))}function Ho(t,e){return Rr(t,1,e)}function mc(t,e){let{defaultValue:n,...r}=e??{},o=e!=null&&Object.hasOwn(e,"defaultValue");return q([t],(s,i,a)=>{if(a.terminalDeps[0]===!0){a.store.has?i.emit(a.store.latest):o&&i.emit(n),i.down([[M]]);return}let u=s[0];if(u==null||u.length===0){i.down([[$]]);return}a.store.latest=u.at(-1),a.store.has=!0},{...se(r),completeWhenDepsComplete:!1})}function hc(t,e,n){return Rr(xr(t,e,n),1,n)}function gc(t,e,n){return Rr(Gi(t,e,n),1,n)}function yc(t,e,n){if(typeof e=="function")return q([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[$]]);return}for(let a of i)e(a),s.emit(a)},se(n));let r=e;return q([t],(o,s,i)=>{if(i.terminalDeps[0]!==void 0){i.terminalDeps[0]===!0?(r.complete?.(),s.down([[M]])):(r.error?.(i.terminalDeps[0]),s.down([[O,i.terminalDeps[0]]]));return}let a=o[0];if(a==null||a.length===0){s.down([[$]]);return}for(let u of a)r.data?.(u),s.emit(u)},{...se(n),completeWhenDepsComplete:!1})}function bc(t,e=Object.is,n){return q([t],(r,o,s)=>{let i=r[0];if(i==null||i.length===0){o.down([[$]]);return}let a=!1;for(let u of i)s.store.hasPrev&&e(s.store.prev,u)||(s.store.prev=u,s.store.hasPrev=!0,o.emit(u),a=!0);a||o.down([[$]])},se(n))}function vc(t,e){return q([t],(n,r,o)=>{let s=n[0];if(s==null||s.length===0){r.down([[$]]);return}let i=!1;for(let a of s)if(!o.store.hasPrev)o.store.prev=a,o.store.hasPrev=!0;else{let u=[o.store.prev,a];o.store.prev=a,r.emit(u),i=!0}i||r.down([[$]])},se(e))}function Fi(...t){let e=[...t];return A(e,n=>n,{...se(),equals:(n,r)=>{if(n.length!==r.length)return!1;for(let o=0;o<n.length;o++)if(!Object.is(n[o],r[o]))return!1;return!0}})}function un(t,e,n){return q([t,e],(r,o,s)=>{let i=r[0],a=r[1],u=a!=null&&a.length>0?a.at(-1):s.prevData[1];if(i!=null&&i.length>0){if(!(a!=null&&a.length>0)&&s.prevData[1]===void 0){o.down([[$]]);return}for(let c of i)o.emit([c,u])}else o.down([[$]])},se(n))}function ft(...t){return t.length===0?H(e=>{e.down([[M]])},se()):H(e=>{let n=t.length,r=0,o=[];for(let s of t){let i=s.subscribe(a=>{for(let u of a)u[0]===R?e.emit(u[1]):u[0]===M?(r+=1,r>=n&&e.down([[M]])):u[0]===O&&e.down([u])});o.push(i)}return()=>{for(let s of o)s()}},se())}function Tc(...t){let e=t.length;return e===0?H(n=>{n.emit([]),n.down([[M]])},se()):H(n=>{let r=Array.from({length:e},()=>[]),o=e;function s(){for(;r.every(a=>a.length>0);){let a=r.map(u=>u.shift());n.emit(a)}}let i=[];for(let a=0;a<e;a++){let u=a,c=t[a].subscribe(d=>{for(let l of d)l[0]===R?(r[u].push(l[1]),s()):l[0]===M?(o-=1,(o===0||r[u].length===0)&&n.down([[M]])):l[0]===O&&n.down([l])});i.push(c)}return()=>{for(let a of i)a()}},se())}function wc(t,e,n){return H(r=>{let o=0,s=[],i,a;return a=e.subscribe(u=>{for(let c of u)o===0?c[0]===R?s.push(c[1]):c[0]===O&&r.down([c]):c[0]===R?r.emit(c[1]):(c[0]===M||c[0]===O)&&r.down([c])}),i=t.subscribe(u=>{for(let c of u)if(o===0)if(c[0]===R)r.emit(c[1]);else if(c[0]===M){o=1;for(let d of s)r.emit(d);s.length=0}else c[0]===O&&r.down([c])}),()=>{i?.(),a?.()}},se(n))}function kc(...t){return t.length===0?H(e=>{e.down([[M]])},se()):t.length===1?q([t[0]],(e,n)=>{let r=e[0];if(r==null||r.length===0){n.down([[$]]);return}for(let o of r)n.emit(o)},se()):H(e=>{let n=null,r=[];for(let o=0;o<t.length;o++){let s=o,i=t[o].subscribe(a=>{for(let u of a){if(n!==null&&s!==n)return;u[0]===R?(n===null&&(n=s),e.emit(u[1])):(u[0]===M||u[0]===O)&&(n===null||s===n)&&e.down([u])}});r.push(i)}return()=>{for(let o of r)o()}},se())}function Wo(t,e,n){let r,o=!1,s=()=>{o||(o=!0,n())};return r=t.subscribe(i=>{let a=!1,u=!1;for(let c of i)c[0]!==ct&&(c[0]===R?e.emit(c[1]):c[0]===M?a=!0:c[0]===O?(u=!0,e.down([c])):(c[0]===Z||c[0]===$)&&e.down([c]));u?(r?.(),r=void 0,s()):a&&s()}),()=>{r?.(),r=void 0}}function _e(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return q([t],(i,a,u)=>{if(u.terminalDeps[0]!=null&&u.terminalDeps[0]!==!0){s();return}if(u.terminalDeps[0]===!0){o=!0,r||a.down([[M]]);return}let c=i[0];if(!(c==null||c.length===0))return s(),r=Wo(re(e(c[c.length-1])),a,()=>{s(),o&&a.down([[M]])}),{deactivate:()=>{s(),o=!1}}},{...se(n),completeWhenDepsComplete:!1})}function xc(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return q([t],(i,a,u)=>{if(u.terminalDeps[0]!=null&&u.terminalDeps[0]!==!0){s();return}if(u.terminalDeps[0]===!0){o=!0,r||a.down([[M]]);return}let c=i[0];if(!(c==null||c.length===0))return r===void 0?r=Wo(re(e(c[0])),a,()=>{s(),o&&a.down([[M]])}):a.down([[$]]),{deactivate:()=>{s(),o=!1}}},{...se(n),completeWhenDepsComplete:!1})}function Rc(t,e,n){let{maxBuffer:r,...o}=n??{},s=[],i,a=!1,u;function c(){i?.(),i=void 0}function d(){if(!u||i!==void 0)return;if(s.length===0){a&&u.down([[M]]);return}let f=s.shift();i=Wo(re(e(f)),u,()=>{c(),d()})}function l(f){r&&r>0&&s.length>=r&&s.shift(),s.push(f),d()}return q([t],(f,p,m)=>{if(u=p,m.terminalDeps[0]!=null&&m.terminalDeps[0]!==!0){c(),s.length=0;return}if(m.terminalDeps[0]===!0){a=!0,d();return}let h=f[0];if(!(h==null||h.length===0)){for(let g of h)l(g);return{deactivate:()=>{c(),s.length=0,a=!1}}}},{...se(o),completeWhenDepsComplete:!1})}function $i(t,e,n){let{concurrent:r,...o}=n??{},s=r!=null&&r>0?r:Number.POSITIVE_INFINITY,i=0,a=!1,u=new Set,c=[],d;function l(){a&&i===0&&c.length===0&&d&&d.down([[M]])}function f(g){if(!d)return;i++;let y;y=Wo(re(e(g)),d,()=>{y&&u.delete(y),i--,p(),l()}),u.add(y)}function p(){for(;c.length>0&&i<s;)f(c.shift())}function m(g){i<s?f(g):c.push(g)}function h(){for(let g of u)g();u.clear(),i=0,c.length=0}return q([t],(g,y,b)=>{if(d=y,b.terminalDeps[0]!=null&&b.terminalDeps[0]!==!0){h();return}if(b.terminalDeps[0]===!0){a=!0,l();return}let v=g[0];if(!(v==null||v.length===0)){for(let T of v)m(T);return{deactivate:()=>{h(),a=!1}}}},{...se(o),completeWhenDepsComplete:!1})}var Sc=$i;function Nc(t,e,n){return H(r=>{let o=new Set;function s(){for(let a of o)clearTimeout(a);o.clear()}let i=t.subscribe(a=>{for(let u of a)if(u[0]===R){let c=setTimeout(()=>{o.delete(c),r.emit(u[1])},e);o.add(c)}else if(u[0]===M){let c=setTimeout(()=>{o.delete(c),r.down([[M]])},e);o.add(c)}else u[0]===O&&(s(),r.down([u]))});return()=>{i(),s()}},se(n))}function Bi(t,e,n){return H(r=>{let o,s;function i(){o!==void 0&&(clearTimeout(o),o=void 0)}let a=t.subscribe(u=>{for(let c of u)c[0]===R?(i(),s=c[1],o=setTimeout(()=>{o=void 0,r.emit(s)},e)):c[0]===M?(o!==void 0&&(i(),r.emit(s)),r.down([[M]])):c[0]===O&&(i(),r.down([c]))});return()=>{a(),i()}},se(n))}function ji(t,e,n){let{leading:r,trailing:o,...s}=n??{},i=r!==!1,a=o===!0,u=e*1e6;return H(c=>{let d,l=-1/0,f,p=!1;function m(){d!==void 0&&(clearTimeout(d),d=void 0)}let h=t.subscribe(g=>{for(let y of g)if(y[0]===R){let b=y[1],v=B();if(i&&v-l>=u)l=v,c.emit(b),m(),a&&(d=setTimeout(()=>{d=void 0,p&&(l=B(),c.emit(f),p=!1)},e));else if(a&&(f=b,p=!0,d===void 0)){let T=(v-l)/1e6;d=setTimeout(()=>{d=void 0,p&&(l=B(),c.emit(f),p=!1)},Math.max(0,e-T))}}else(y[0]===M||y[0]===O)&&(m(),c.down([y]))});return()=>{h(),m()}},se(s))}function Ec(t,e,n){return H(r=>{let o,s=!1,i=!1,a=t.subscribe(c=>{if(!s)for(let d of c){if(s)return;d[0]===R?o={v:d[1]}:d[0]===O?(s=!0,r.down([d])):d[0]===M&&(i=!0,o=void 0)}}),u=e.subscribe(c=>{if(!s)for(let d of c){if(s)return;d[0]===R?o!==void 0&&!i&&r.emit(o.v):d[0]===O?(s=!0,r.down([d])):d[0]===M&&(s=!0,r.down([[M]]))}});return()=>{a(),u()}},se(n))}function _c(t,e,n){return H(r=>{let o,s,i=!1;function a(){o!==void 0&&(clearTimeout(o),o=void 0)}let u=t.subscribe(c=>{for(let d of c)d[0]===R?(s=d[1],i=!0,a(),o=setTimeout(()=>{o=void 0,i&&(i=!1,r.emit(s))},e)):(d[0]===M||d[0]===O)&&(a(),r.down([d]))});return()=>{u(),a()}},se(n))}function Mc(t,e,n){return H(r=>{let o=[],s=t.subscribe(a=>{for(let u of a)u[0]===R?o.push(u[1]):u[0]===M?(o.length>0&&r.emit([...o]),o.length=0,r.down([[M]])):u[0]===O&&r.down([u])}),i=e.subscribe(a=>{for(let u of a)u[0]===R?o.length>0&&(r.emit([...o]),o.length=0):u[0]===M?r.down([[M]]):u[0]===O&&r.down([u])});return()=>{s(),i(),o.length=0}},se(n))}function Oc(t,e,n){if(e<=0)throw new RangeError("bufferCount expects count > 0");return H(r=>{let o=[],s=t.subscribe(i=>{for(let a of i)a[0]===R?(o.push(a[1]),o.length>=e&&r.emit(o.splice(0,o.length))):a[0]===M?(o.length>0&&r.emit([...o]),o.length=0,r.down([[M]])):a[0]===O&&r.down([a])});return()=>{s(),o.length=0}},se(n))}function Cc(t,e,n){if(e<=0)throw new RangeError("windowCount expects count > 0");return H(r=>{let o,s=0;function i(){let u=H(c=>(o=c.down.bind(c),()=>{o=void 0}),se());s=0,r.emit(u)}let a=t.subscribe(u=>{for(let c of u)c[0]===R?(o||i(),o?.([[R,c[1]]]),s+=1,s>=e&&(o?.([[M]]),o=void 0)):c[0]===M?(o?.([[M]]),o=void 0,r.down([[M]])):c[0]===O&&(o?.([c]),o=void 0,r.down([c]))});return()=>{a(),o?.([[M]]),o=void 0}},se(n))}function Ac(t,e,n){return H(r=>{let o=[],s=setInterval(()=>{o.length>0&&(r.emit([...o]),o.length=0)},e),i=t.subscribe(a=>{for(let u of a)u[0]===R?o.push(u[1]):u[0]===M?(clearInterval(s),o.length>0&&r.emit([...o]),o.length=0,r.down([[M]])):u[0]===O&&(clearInterval(s),r.down([u]))});return()=>{i(),clearInterval(s),o.length=0}},se(n))}function Lc(t,e,n){return H(r=>{let o;function s(){o?.([[M]]),o=void 0}function i(){let c=H(d=>(o=d.down.bind(d),()=>{o=void 0}),se());r.emit(c)}i();let a=setInterval(()=>{s(),i()},e),u=t.subscribe(c=>{for(let d of c)d[0]===R?o?.([[R,d[1]]]):d[0]===M?(clearInterval(a),s(),r.down([[M]])):d[0]===O&&(clearInterval(a),o?.([d]),s(),r.down([d]))});return()=>{u(),clearInterval(a),s()}},se(n))}function Ic(t,e,n){return H(r=>{let o;function s(){o?.([[M]]),o=void 0}function i(){let c=H(d=>(o=d.down.bind(d),()=>{o=void 0}),se());r.emit(c)}let a=t.subscribe(c=>{for(let d of c)d[0]===R?(o||i(),o?.([[R,d[1]]])):d[0]===M?(s(),r.down([[M]])):d[0]===O&&(o?.([d]),o=void 0,r.down([d]))}),u=e.subscribe(c=>{for(let d of c)d[0]===R&&(s(),i())});return()=>{a(),u(),s()}},se(n))}function Pc(t,e){return H((n,r)=>{"n"in r.store||(r.store.n=0);let o=setInterval(()=>{n.emit(r.store.n),r.store.n=r.store.n+1},t);return()=>clearInterval(o)},se(e))}function Dc(t,e,n){if(e<=0)throw new RangeError("repeat expects count > 0");return H(r=>{let o=e,s,i=()=>{s?.(),s=t.subscribe(a=>{let u=!1,c=[];for(let d of a)d[0]===M?u=!0:c.push(d);c.length>0&&r.down(c),u&&(s?.(),s=void 0,o-=1,o>0?i():r.down([[M]]))})};return i(),()=>{s?.()}},se(n))}function Gc(t,e){return q([t],(n,r)=>{let o=n[0];if(o==null||o.length===0){r.down([[$]]);return}for(let s of o)r.emit(s)},se(e))}function Sr(t,e,n){return H(r=>{let o=t.subscribe(s=>{for(let i of s)if(i[0]===R)r.emit(i[1]);else if(i[0]===O)try{r.emit(e(i[1]))}catch(a){r.down([[O,a]])}else i[0]===M&&r.down([[M]])});return()=>{o()}},se(n))}function Fc(t,e,n){return q([t,e],(r,o,s)=>{let i=r[1];if(!(i!=null&&i.length>0?i.at(-1):s.prevData[1])){o.down([[$]]);return}let u=r[0];if(u!=null&&u.length>0){for(let c of u)o.emit(c);return}if(i!=null&&i.length>0&&s.prevData[0]!==void 0){o.emit(s.prevData[0]);return}o.down([[$]])},se(n))}var $c=Fi,Bc=Bi,jc=ji,Kc=Sr;ie();we();le();Ln();var Ki=class{ring;arr;constructor(e){e===Number.POSITIVE_INFINITY||e<=0?(this.arr=[],this.ring=null):(this.ring=new rn(e),this.arr=null)}get length(){return this.ring!=null?this.ring.size:this.arr.length}push(e){this.ring!=null?this.ring.push(e):this.arr.push(e)}shift(){return this.ring!=null?this.ring.shift():this.arr.shift()}drain(){if(this.ring!=null){let n=this.ring.toArray();return this.ring.clear(),n}let e=this.arr;return this.arr=[],e}};function Nr(t){return t instanceof Error?t:new Error(String(t))}function Cf(t){return t===void 0?null:typeof t=="string"?Ot(t):t}function Ge(t,e){let{name:n,onTransportError:r,retry:o,backpressure:s,batchSize:i=Number.POSITIVE_INFINITY,flushIntervalMs:a=0,serialize:u,stopOn:c,onUpstreamMessage:d,onDispose:l,send:f,sendBatch:p,ctx:m}=e;if(!f&&!p)throw new Error("reactiveSink: `send` or `sendBatch` must be provided");let h=m,g=Math.max(1,o?.maxAttempts??1),y=Cf(o?.backoff??(g>1?"exponential":void 0)),b=o?.shouldRetry??(()=>!0),v=p!==void 0||i<Number.POSITIVE_INFINITY||a>0,T=X=>n?`${n}::${X}`:void 0,w=N(void 0,{equals:()=>!1,name:T("sent")}),k=N(null,{name:T("failed")}),x=N(0,{name:T("inFlight")}),S=N(null,{name:T("errors")}),_=v?N(0,{name:T("buffered")}):void 0,F=s?N(!1,{name:T("paused")}):void 0,L=0,D=X=>{L+=X,x.down([[R,L]])},C=X=>{try{r?.(X)}catch{}try{S.down([[R,X]])}catch{}},K=new Set,ne=X=>{K.add(X);let ue=()=>K.delete(X);X.then(ue,ue)},P=(X,ue,me)=>{let ke=y?y(ue-1,me,null):0,Ie=ke==null?0:typeof ke=="number"&&ke>0?ke:0,He=Math.max(1,Math.ceil(Ie/1e6));return new Promise(be=>{setTimeout(()=>be(X()),He)})},E=X=>X!=null&&typeof X=="object"&&typeof X.then=="function",I=X=>{let ue;try{ue=u?u(X):X}catch(be){let ge=Nr(be);return C({stage:"serialize",error:ge,value:X}),k.down([[R,{value:X,error:ge,attempts:0}]]),Promise.resolve()}let me=0,ke=be=>{D(-1);let ge=Nr(be);if(C({stage:"send",error:ge,value:X,attempt:me}),!(me<g&&b(ge,me))){k.down([[R,{value:X,error:ge,attempts:me}]]);return}return P(He,me,ge)},Ie=()=>{D(-1),w.down([[R,X]])};function He(){me+=1,D(1);let be;try{be=f(ue,h)}catch(ge){return ke(ge)??Promise.resolve()}return E(be)?be.then(Ie,ge=>ke(ge)):(Ie(),Promise.resolve())}return He()},G=s?.maxBuffer??Number.POSITIVE_INFINITY,te=new Ki(G),U,ce=!1,j=()=>{_?.down([[R,te.length]])},V=X=>{F&&F.down([[R,X]])},J=s?.strategy??"drop-oldest",Y=(X,ue)=>{let me={value:X,payload:ue};if(te.length<G)return te.push(me),j(),!0;if(J==="drop-oldest"){let Ie=te.shift();return te.push(me),j(),V(!0),k.down([[R,{value:Ie.value,error:new Error("backpressure: buffer overflow \u2014 dropped oldest"),attempts:0}]]),!0}if(J==="drop-newest")return V(!0),k.down([[R,{value:X,error:new Error("backpressure: buffer overflow \u2014 dropped newest"),attempts:0}]]),!1;let ke=new Error("backpressure: buffer overflow");return C({stage:"send",error:ke,value:X}),k.down([[R,{value:X,error:ke,attempts:0}]]),V(!0),!1},Q=X=>{let ue=0,me=X.map(be=>be.payload),ke=be=>{D(-1);let ge=Nr(be);if(C({stage:"send",error:ge,value:X.map(Xs=>Xs.value),attempt:ue}),!(ue<g&&b(ge,ue))){for(let{value:Xs}of X)k.down([[R,{value:Xs,error:ge,attempts:ue}]]);return}return P(He,ue,ge)},Ie=()=>{D(-1);for(let{value:be}of X)w.down([[R,be]])};function He(){ue+=1,D(1);let be;try{be=p(me,h)}catch(ge){return ke(ge)??Promise.resolve()}return E(be)?be.then(Ie,ge=>ke(ge)):(Ie(),Promise.resolve())}return He()},W=async X=>{for(let ue of X)await ae(ue.value,ue.payload)},ae=(X,ue)=>{let me=0,ke=be=>{D(-1);let ge=Nr(be);if(C({stage:"send",error:ge,value:X,attempt:me}),!(me<g&&b(ge,me))){k.down([[R,{value:X,error:ge,attempts:me}]]);return}return P(He,me,ge)},Ie=()=>{D(-1),w.down([[R,X]])};function He(){me+=1,D(1);let be;try{be=f(ue,h)}catch(ge){return ke(ge)??Promise.resolve()}return E(be)?be.then(Ie,ge=>ke(ge)):(Ie(),Promise.resolve())}return He()},ye=()=>{if(ce||te.length===0)return Promise.resolve();let X=te.drain();if(j(),V(!1),p!==void 0){let me=Q(X);return ne(me),me}let ue=W(X);return ne(ue),ue},Fe=()=>{U!==void 0||ce||a<=0||(U=setTimeout(()=>{U=void 0,ye()},a))},ze=t.subscribe(X=>{for(let ue of X){let me=ue[0];if(me!==R)try{d?.(ue)}catch{}if(me===R){let ke=ue[1];if(v){let Ie;if(u)try{Ie=u(ke)}catch(be){let ge=Nr(be);C({stage:"serialize",error:ge,value:ke}),k.down([[R,{value:ke,error:ge,attempts:0}]]);continue}else Ie=ke;if(!Y(ke,Ie))continue;te.length>=i?ye():Fe()}else{let Ie=I(ke);ne(Ie)}}else Me.messageTier(me)>=3&&v&&(U!==void 0&&(clearTimeout(U),U=void 0),ye())}}),ht;if(c){let X=!1;ht=c.subscribe(ue=>{if(!X){X=!0;return}ue.length>0&&!Vt&&rt()})}let Vt=!1,rt=()=>{if(Vt)return;Vt=!0,U!==void 0&&(clearTimeout(U),U=void 0),v&&ye(),ce=!0,ht?.(),ze();let X=ue=>{try{ue.down([[de]])}catch{}};X(S),X(k),X(w),X(x),_&&X(_),F&&X(F);try{l?.()}catch{}},qe={dispose:rt,sent:w,failed:k,inFlight:x,errors:S};return v&&(qe.buffered=_,qe.flush=async()=>{ce||(await ye(),await Promise.all(K))}),F&&(qe.paused=F),qe}vt();$e();function ut(t){return{describeKind:"producer",...t}}function qi(t,e){let{parse:n,closeOnTeardown:r=!1,...o}=e??{};return H(s=>{let i=!0,a,u=()=>{let y=a;a=void 0,y?.()},c=y=>{i&&(i=!1,s.down([y]),u())},d=(y,b=y)=>{if(i)try{let v=y!==null&&typeof y=="object"&&"data"in y?y.data:y,T=n?n(v,b):v;s.emit(T)}catch(v){c([O,v])}},l=y=>{c([O,y])},f=()=>{c([M])};if(typeof t=="function"){try{if(a=t(d,l,f),typeof a!="function")throw new Error("fromWebSocket register contract violation: register must return cleanup callable")}catch(y){c([O,y])}return()=>{i=!1,u()}}let p=t,m=y=>d(y,y),h=y=>l(y),g=()=>f();return p.addEventListener("message",m),p.addEventListener("error",h),p.addEventListener("close",g),a=()=>{p.removeEventListener("message",m),p.removeEventListener("error",h),p.removeEventListener("close",g),r&&p.close()},()=>{i=!1,u()}},ut(o))}function Vc(t,e){return an(t,e)}function Hi(t,e){let{method:n="GET",headers:r,body:o,transform:s=v=>v.json(),timeoutNs:i=30*1e9,signal:a,completeAfterFetch:u=!1,refetchOnSubscribe:c=!1,...d}=e??{},l=N(0,{name:`${d.name??"http"}/fetchCount`}),f=N(0,{name:`${d.name??"http"}/lastUpdated`}),p=N(!1,{name:`${d.name??"http"}/fetched`}),m=0,h=o!==void 0?typeof o=="string"?o:JSON.stringify(o):void 0,g=v=>{let T=new AbortController,w=!0;if(a?.aborted)return w=!1,v.down([[O,a.reason??new Error("Aborted")]]),()=>{};a?.addEventListener("abort",()=>T.abort(a.reason),{once:!0});let k=setTimeout(()=>T.abort(new Error("Request timeout")),Math.ceil(i/1e6));return fetch(t,{method:n,headers:r,body:h,signal:T.signal}).then(async x=>{if(clearTimeout(k),!w)return;if(!x.ok)throw new Error(`HTTP ${x.status}: ${x.statusText}`);let S=await s(x);w&&(ee(()=>{m+=1,l.down([[R,m]]),f.down([[R,pe()]]),p.down([[R,!0]]),v.emit(S)}),u&&v.down([[M]]))}).catch(x=>{clearTimeout(k),w&&(x&&x.name==="AbortError"||v.down([[O,x]]))}),()=>{w=!1,T.abort()}},y=H(v=>g({emit:T=>v.emit(T),down:T=>v.down(T)}),{...ut(d),resubscribable:c});return{...Lt(y),fetchCount:l,lastUpdated:f,fetched:p}}function qc(t,e,n){let{method:r="POST",headers:o={"Content-Type":"application/json"},serialize:s=m=>JSON.stringify(m),timeoutNs:i,batchFormat:a="json-array",batchSize:u,flushIntervalMs:c,retry:d,onTransportError:l}=n??{},f=async m=>{let h=i!==void 0?new AbortController:void 0,g;h&&i!==void 0&&(g=setTimeout(()=>h.abort(new Error("Request timeout")),Math.ceil(i/1e6)));try{let y=await fetch(e,{method:r,headers:o,body:m,signal:h?.signal}),b=async()=>{try{await y.arrayBuffer?.()}catch{}};if(!y.ok)throw await b(),new Error(`HTTP ${y.status}: ${y.statusText}`);await b()}finally{g!==void 0&&clearTimeout(g)}};return u!==void 0||c!==void 0?Ge(t,{onTransportError:l,retry:d,batchSize:u,flushIntervalMs:c,sendBatch:async m=>{let h;a==="ndjson"?h=m.map(g=>{let y=s(g);return typeof y=="string"?y:new TextDecoder().decode(y)}).join(`
15
- `):h=JSON.stringify(m),await f(h)}}):Ge(t,{onTransportError:l,retry:d,serialize:s,send:async m=>{await f(m)}})}function Hc(t){return Symbol.keyFor(t)??t.description??"message"}function Kn(t,e){return typeof t=="string"?t:e(t)}function Wc(t,e){let n=`event: ${t}
9
+ `,n}function uf(t){return JSON.parse(t)}function cf(t,e){try{t.send(JSON.stringify(e))}catch{}}function Si(t,e){try{t(e)}catch{}}ur();var Eo="graphReflyActor";function Ni(t){return e=>{let r=e.switchToHttp().getRequest()?.user;if(r!=null)return t?t(r):r}}function nc(t="x-graphrefly-actor"){return e=>{let r=e.switchToHttp().getRequest()?.headers?.[t.toLowerCase()];if(!(typeof r!="string"||r.length===0))try{return JSON.parse(r)}catch{return}}}function rc(t){let e=t?.[Eo];return e!=null?bt(e):lt}var Tr=class{constructor(e){this.extractor=e}canActivate(e){let n=bt(this.extractor(e)),r=e.switchToHttp().getRequest();return r!=null&&(r[Eo]=n),!0}};function oc(t){return new Tr(t??Ni())}var Nr=require("@nestjs/common"),_c=require("@nestjs/core");ur();Ne();ke();Qt();ie();Qt();xe();function wt(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;default:return new Set(["type","deps"])}}function df(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function lf(t){let e={};for(let[n,r]of Object.entries(t.meta))try{e[n]=r.cache}catch{}return e}function wr(t,e){let n=e==null,r=!n&&e!=null?[...e].filter(c=>c.startsWith("meta.")).map(c=>c.slice(5)):null,o=n||e.has("meta")||r!=null&&r.length>0,s="state",i=[];t instanceof Ee&&(s=df(t),i=t._deps.map(c=>c.node.name??""));let a={type:s,deps:i};(n||e.has("status"))&&(a.status=t.status);let u=t instanceof Ee?t._guard:void 0;if(o){let c={...lf(t)};if(u!=null&&c.access===void 0&&(c.access=mr(u)),r!=null&&r.length>0&&!e.has("meta")){let d={};for(let l of r)l in c&&(d[l]=c[l]);a.meta=d}else a.meta=c}if(t.name!=null&&(a.name=t.name),n||e.has("value")){t.status==="sentinel"&&(a.sentinel=!0);try{a.value=t.cache}catch{}}if((n||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),a.v=c}return(n||e.has("guard"))&&u!=null&&(a.guard=mr(u)),(n||e.has("lastMutation"))&&t.lastMutation!=null&&(a.lastMutation=t.lastMutation),a}xe();oe();Re();pt();var sn=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}};ro();function Ei(t){return t>=768&&t<=879||t>=1155&&t<=1161||t>=1425&&t<=1469||t>=1552&&t<=1562||t>=1611&&t<=1631||t>=1648&&t===1648||t>=1750&&t<=1756||t>=1759&&t<=1764||t>=1767&&t<=1768||t>=1770&&t<=1773||t>=1840&&t<=1866||t>=1958&&t<=1968||t>=2304&&t<=2307||t>=2362&&t<=2383||t>=2385&&t<=2391||t>=2402&&t<=2403||t>=2433&&t<=2435||t>=2492&&t<=2509||t>=2561&&t<=2563||t>=2620&&t<=2641||t>=2672&&t<=2673||t>=2677&&t===2677||t>=3633&&t===3633||t>=3636&&t<=3642||t>=3655&&t<=3662||t>=3761&&t===3761||t>=3764&&t<=3772||t>=3784&&t<=3790||t>=7616&&t<=7679||t>=8400&&t<=8447||t>=65024&&t<=65039||t>=65056&&t<=65071||t===8205?0:t>=4352&&t<=4447||t>=8986&&t<=8987||t>=9001&&t<=9002||t>=9193&&t<=9203||t>=9208&&t<=9210||t>=9725&&t<=9726||t>=9748&&t<=9749||t>=9800&&t<=9811||t===9855||t===9875||t===9889||t>=9898&&t<=9899||t>=9917&&t<=9918||t>=9924&&t<=9925||t===9934||t===9940||t===9962||t>=9970&&t<=9971||t===9973||t===9978||t===9981||t===9986||t===9989||t>=9992&&t<=9997||t===9999||t>=10067&&t<=10069||t===10071||t>=10133&&t<=10135||t===10160||t===10175||t>=10548&&t<=10549||t>=11013&&t<=11015||t>=11035&&t<=11036||t===11088||t===11093||t>=11904&&t<=12350||t>=12352&&t<=12447||t>=12448&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12784&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=19968&&t<=40959||t>=43360&&t<=43388||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65131||t>=65281&&t<=65376||t>=65504&&t<=65510||t>=126980&&t===126980||t===127183||t>=127344&&t<=127345||t===127358||t===127359||t===127374||t>=127377&&t<=127386||t>=127456&&t<=127487||t>=127488&&t<=127490||t===127514||t===127535||t>=127538&&t<=127546||t>=127568&&t<=127569||t>=127744&&t<=129535||t>=129536&&t<=129791||t>=129792&&t<=130047||t>=131072&&t<=196605||t>=196608&&t<=262141?2:1}function Wn(t){let e=0;for(let n of t)e+=Ei(n.codePointAt(0));return e}function sc(t,e){if(e<=0)return"";let n=0,r="";for(let o of t){let s=Ei(o.codePointAt(0));if(n+s>e){if(e<=1)return"\u2026";for(;n+1>e&&r.length>0;){let i=[...r].pop();r=r.slice(0,-i.length),n-=Ei(i.codePointAt(0))}return`${r}\u2026`}r+=o,n+=s}return r}var pf={horizontal:"\u2500",vertical:"\u2502",cornerTL:"\u250C",cornerTR:"\u2510",cornerBL:"\u2514",cornerBR:"\u2518",tDown:"\u252C",tUp:"\u2534",tRight:"\u251C",tLeft:"\u2524",cross:"\u253C",arrowRight:"\u25B6",arrowDown:"\u25BC",arrowLeft:"\u25C0",arrowUp:"\u25B2",boxTL:"\u250C",boxTR:"\u2510",boxBL:"\u2514",boxBR:"\u2518",boxH:"\u2500",boxV:"\u2502"},ff={horizontal:"-",vertical:"|",cornerTL:"+",cornerTR:"+",cornerBL:"+",cornerBR:"+",tDown:"+",tUp:"+",tRight:"+",tLeft:"+",cross:"+",arrowRight:">",arrowDown:"v",arrowLeft:"<",arrowUp:"^",boxTL:"+",boxTR:"+",boxBL:"+",boxBR:"+",boxH:"-",boxV:"|"};function cc(t,e){let n=e.charset==="ascii"?ff:pf,r=t.width,o=t.height,s=Array.from({length:o},()=>Array.from({length:r},()=>" ")),i=Array.from({length:o},()=>Array.from({length:r},()=>"empty"));for(let a of t.edges)hf(s,i,n,a);for(let a of t.boxes)mf(s,i,n,a,e.labelOf(a.id));return s.map(a=>vf(a.join(""))).join(`
10
+ `)}function mf(t,e,n,r,o){let{x:s,y:i,w:a,h:u}=r;if(a<2||u<2){u>0&&ic(t,e,s,i,a,o);return}Dt(t,e,s,i,n.boxTL);for(let d=s+1;d<s+a-1;d+=1)Dt(t,e,d,i,n.boxH);Dt(t,e,s+a-1,i,n.boxTR);for(let d=i+1;d<i+u-1;d+=1){Dt(t,e,s,d,n.boxV);for(let l=s+1;l<s+a-1;l+=1)dc(t,e,l,d," ","empty");Dt(t,e,s+a-1,d,n.boxV)}Dt(t,e,s,i+u-1,n.boxBL);for(let d=s+1;d<s+a-1;d+=1)Dt(t,e,d,i+u-1,n.boxH);Dt(t,e,s+a-1,i+u-1,n.boxBR);let c=i+Math.floor(u/2);ic(t,e,s+1,c,a-2,o)}function Dt(t,e,n,r,o){dc(t,e,n,r,o,o===" "?"empty":o==="\u2500"||o==="-"?"boxH":o==="\u2502"||o==="|"?"boxV":"boxCorner")}function dc(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];n<0||n>=i.length||(i[n]=o,e[r][n]=s)}function ic(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=n,a=o;for(let u of s){let c=Wn(u);if(c!==0){if(a<c)break;i>=0&&i<t[r].length&&(t[r][i]=u,e[r][i]="label",c===2&&i+1<t[r].length&&(t[r][i+1]="",e[r][i+1]="label")),i+=c,a-=c}}for(;a>0;)i>=0&&i<t[r].length&&(t[r][i]=" ",e[r][i]="empty"),i+=1,a-=1}function hf(t,e,n,r){let o=r.points;if(o.length<2)return;for(let u=0;u+1<o.length;u+=1)gf(t,e,n,o[u],o[u+1]);for(let u=1;u+1<o.length;u+=1){let c=o[u-1],d=o[u],l=o[u+1],f=yf(c,d,l,n);f&&uc(t,e,d.x,d.y,f,"edgeCorner")}let s=o[o.length-1],i=o[o.length-2],a=bf(i,s,n);a&&uc(t,e,s.x,s.y,a,"arrow")}function gf(t,e,n,r,o){if(!(r.x===o.x&&r.y===o.y)){if(r.y===o.y){let s=r.y,i=Math.min(r.x,o.x),a=Math.max(r.x,o.x);for(let u=i;u<=a;u+=1)ac(t,e,u,s,n,"h")}else if(r.x===o.x){let s=r.x,i=Math.min(r.y,o.y),a=Math.max(r.y,o.y);for(let u=i;u<=a;u+=1)ac(t,e,s,u,n,"v")}}}function ac(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];if(!(a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label")){if(a==="empty"){i[n]=s==="h"?o.horizontal:o.vertical,e[r][n]=s==="h"?"edgeH":"edgeV";return}if(a==="edgeH"&&s==="v"){i[n]=o.cross,e[r][n]="edgeCorner";return}if(a==="edgeV"&&s==="h"){i[n]=o.cross,e[r][n]="edgeCorner";return}}}function uc(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label"||(i[n]=o,e[r][n]=s)}function yf(t,e,n,r){let o=t.y===e.y,s=e.y===n.y;if(o===s)return;if(o){let u=t.x<e.x,c=n.y>e.y;return u&&c?r.cornerTR:u&&!c?r.cornerBR:!u&&c?r.cornerTL:r.cornerBL}let i=t.y<e.y,a=n.x>e.x;return i&&a?r.cornerBL:i&&!a?r.cornerBR:!i&&a?r.cornerTL:r.cornerTR}function bf(t,e,n){if(e.x>t.x)return n.arrowRight;if(e.x<t.x)return n.arrowLeft;if(e.y>t.y)return n.arrowDown;if(e.y<t.y)return n.arrowUp}function vf(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}function fc(t){let e=Tf(t);wf(e),kf(e),xf(e),Rf(e,t);let n=Ef(e,t),{width:r,height:o}=Mf(e),s=[];for(let i of e.layers)for(let a of i)a.isVirtual||s.push({id:a.id,layer:a.layer,order:a.order,x:a.x,y:a.y,w:a.w,h:a.h});return{boxes:s,edges:n,width:r,height:o}}function Tf(t){let e=new Map;for(let o of t.nodes)e.set(o,{id:o,isVirtual:!1,layer:-1,order:0,x:0,y:0,w:t.widthCells(o),h:t.heightCells(o),in:[],out:[]});let n=[],r=0;for(let o of t.edges){if(o.from===o.to)continue;let s=e.get(o.from),i=e.get(o.to);if(!s||!i)continue;let a={chainId:r++,chainFrom:o.from,chainTo:o.to,fromId:o.from,toId:o.to,hopIndex:0,chainLen:1};s.out.push(a),i.in.push(a),n.push(a)}return{nodes:e,layers:[],hops:n}}function wf(t){let e=new Map;for(let s of t.nodes.values())e.set(s.id,s.in.length);let n=[];for(let s of t.nodes.values())(e.get(s.id)??0)===0&&(s.layer=0,n.push(s));let r=new Set,o=0;for(;o<n.length;){let s=n[o++];if(!r.has(s.id)){r.add(s.id);for(let i of s.out){let a=t.nodes.get(i.toId);a.layer=Math.max(a.layer,s.layer+1);let u=(e.get(a.id)??0)-1;e.set(a.id,u),u<=0&&n.push(a)}}}for(let s of t.nodes.values())s.layer<0&&(s.layer=0)}function kf(t){let e=Math.max(0,...Array.from(t.nodes.values(),s=>s.layer)),n=Array.from({length:e+1},()=>[]);for(let s of t.nodes.values())n[s.layer].push(s);let r=[],o=0;for(let s of t.hops){let i=t.nodes.get(s.fromId),a=t.nodes.get(s.toId),u=a.layer-i.layer;if(u<=0){i.out=i.out.filter(l=>l!==s),a.in=a.in.filter(l=>l!==s);continue}if(u===1){s.hopIndex=0,s.chainLen=1,r.push(s);continue}i.out=i.out.filter(l=>l!==s),a.in=a.in.filter(l=>l!==s);let c=i;for(let l=1;l<u;l+=1){let f=`__virt_${o++}__`,p={id:f,isVirtual:!0,layer:i.layer+l,order:0,x:0,y:0,w:0,h:1,in:[],out:[]};t.nodes.set(f,p),n[p.layer].push(p);let m={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:c.id,toId:f,hopIndex:l-1,chainLen:u};c.out.push(m),p.in.push(m),r.push(m),c=p}let d={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:c.id,toId:a.id,hopIndex:u-1,chainLen:u};c.out.push(d),a.in.push(d),r.push(d)}for(let s of n)for(let i=0;i<s.length;i+=1)s[i].order=i;t.layers=n,t.hops=r}function xf(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)lc(t,t.layers[r],"in"),_o(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)lc(t,t.layers[r],"out"),_o(t.layers[r])}for(let n=0;n<2;n+=1){let r=!1;for(let o=1;o<t.layers.length;o+=1){let s=t.layers[o];for(let i=0;i+1<s.length;i+=1){let a=pc(t,s[i],s[i+1],"in");[s[i],s[i+1]]=[s[i+1],s[i]],_o(s),pc(t,s[i],s[i+1],"in")<a?r=!0:([s[i],s[i+1]]=[s[i+1],s[i]],_o(s))}}if(!r)break}}function lc(t,e,n){let r=new Map;for(let o of e){let s=n==="in"?o.in:o.out;if(s.length===0){r.set(o.id,o.order);continue}let i=0,a=0;for(let u of s){let c=t.nodes.get(n==="in"?u.fromId:u.toId);c&&(i+=c.order,a+=1)}r.set(o.id,a===0?o.order:i/a)}e.sort((o,s)=>{let i=r.get(o.id),a=r.get(s.id);return i!==a?i-a:o.order-s.order})}function _o(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function pc(t,e,n,r){let o=r==="in"?e.in:e.out,s=r==="in"?n.in:n.out,i=0;for(let a of o)for(let u of s){let c=t.nodes.get(r==="in"?a.fromId:a.toId)?.order??0,d=t.nodes.get(r==="in"?u.fromId:u.toId)?.order??0;(e.order<n.order&&c>d||e.order>n.order&&c<d)&&(i+=1)}return i}function Rf(t,e){e.direction==="LR"?Sf(t,e):Nf(t,e)}function Sf(t,e){let n=[],r=0;for(let o=0;o<t.layers.length;o+=1){n.push(r);let s=0;for(let i of t.layers[o])s=Math.max(s,i.w);r+=s+e.layerGap}for(let o=0;o<t.layers.length;o+=1)for(let s of t.layers[o])s.x=n[o];for(let o of t.layers){let s=0;for(let i of o)i.y=s,s+=i.h+e.nodeGap}mc(t,e,"y")}function Nf(t,e){let n=[],r=0;for(let o=0;o<t.layers.length;o+=1){n.push(r);let s=0;for(let i of t.layers[o])s=Math.max(s,i.h);r+=s+e.layerGap}for(let o=0;o<t.layers.length;o+=1)for(let s of t.layers[o])s.y=n[o];for(let o of t.layers){let s=0;for(let i of o)i.x=s,s+=i.w+e.nodeGap}mc(t,e,"x")}function mc(t,e,n){let r=s=>n==="y"?s.h:s.w,o=e.nodeGap;for(let s=0;s<2;s+=1){let i=s===0?t.layers.slice(1):t.layers.slice(0,-1).reverse();for(let a of i){let u=new Map;for(let d of a){let l=s===0?d.in:d.out;if(l.length===0)continue;let f=[];for(let m of l){let h=t.nodes.get(s===0?m.fromId:m.toId);if(!h)continue;let g=n==="y"?h.y:h.x;f.push(g+Math.floor(r(h)/2))}if(f.length===0)continue;f.sort((m,h)=>m-h);let p=f[Math.floor(f.length/2)];u.set(d.id,p-Math.floor(r(d)/2))}let c=0;for(let d of a){let l=u.get(d.id),f=n==="y"?d.y:d.x,m=Math.max(l??f,c);n==="y"?d.y=m:d.x=m,c=m+r(d)+o}}}}function Ef(t,e){let n=new Map;for(let c of t.hops){let d=n.get(c.chainId);d?d.push(c):n.set(c.chainId,[c])}for(let c of n.values())c.sort((d,l)=>d.hopIndex-l.hopIndex);let r=e.direction==="LR",o=c=>r?c.x:c.y,s=c=>r?c.w:c.h,i=c=>r?c.y+Math.floor(c.h/2):c.x+Math.floor(c.w/2),a=new Map;for(let c=0;c+1<t.layers.length;c+=1){let d=t.layers[c],l=t.layers[c+1],f=0;for(let R of d)f=Math.max(f,o(R)+s(R));let p=Number.POSITIVE_INFINITY;for(let R of l)p=Math.min(p,o(R));let m=Number.isFinite(p)?p-1:f,h=Math.max(1,m-f+1),g=[];for(let R of d)for(let E of R.out)g.push(E);g.sort((R,E)=>{let G=i(t.nodes.get(R.fromId)),L=i(t.nodes.get(E.fromId));if(G!==L)return G-L;let P=i(t.nodes.get(R.toId)),C=i(t.nodes.get(E.toId));return P-C});let y=[],b=new Map;for(let R of g){let E=i(t.nodes.get(R.fromId)),G=i(t.nodes.get(R.toId)),L=Math.min(E,G),P=Math.max(E,G),C=-1;for(let V=0;V<y.length;V+=1){let ne=y[V],F=!0;for(let A of ne)if(A.lo<=P&&L<=A.hi){F=!1;break}if(F){ne.push({lo:L,hi:P}),C=V;break}}C<0&&(y.push([{lo:L,hi:P}]),C=y.length-1),b.set(R,C)}let v=y.length,T=h>=Math.max(3,v+2),w=T?f+1:f,k=T?m-1:m,x=Math.max(1,k-w+1);for(let R of g){let E=b.get(R),G;if(v<=1)G=w+Math.floor(x/2);else{let L=(x-1)/(v-1);G=w+Math.floor(E*L)}a.set(R,Math.max(f,Math.min(m,G)))}}let u=[];for(let[,c]of n){let d=[];for(let f=0;f<c.length;f+=1){let p=c[f],m=t.nodes.get(p.fromId),h=t.nodes.get(p.toId),g=a.get(p),y=m.isVirtual?o(m):o(m)+s(m),b=h.isVirtual?o(h):o(h)-1,v=i(m),T=i(h);f===0&&Mo(d,r,y,v),v!==T&&(Mo(d,r,g,v),Mo(d,r,g,T)),Mo(d,r,b,T)}let l=c[0];u.push({from:l.chainFrom,to:l.chainTo,points:_f(d)})}return u}function Mo(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function _f(t){let e=[];for(let n of t){let r=e[e.length-1];(!r||r.x!==n.x||r.y!==n.y)&&e.push(n)}return e}function Mf(t){let e=0,n=0;for(let r of t.layers)for(let o of r)e=Math.max(e,o.x+o.w),n=Math.max(n,o.y+o.h);return{width:e,height:n}}var Of=24,Cf=4,Af=1,Lf=3;function hc(t,e){let n=If(e.direction),r=Math.max(3,e.maxLabelWidth??Of),o=e.asciiCharset??"unicode",s=Object.keys(t.nodes).sort(),i=new Set(s),a=t.edges.filter(p=>i.has(p.from)&&i.has(p.to)),u=new Map,c=new Map;for(let p of s){let m=sc(p,r);u.set(p,m),c.set(p,Wn(m)+4)}let d=fc({nodes:s,edges:a,widthCells:p=>c.get(p)??3,heightCells:()=>Lf,layerGap:Cf,nodeGap:Af,direction:n}),l=cc(d,{charset:o,labelOf:p=>u.get(p)??p}),f=e.logger;return f&&f(l),l}function If(t){if(t===void 0||t==="LR")return"LR";if(t==="TD")return"TD";throw new Error(`ascii describe supports direction "LR" or "TD" only; got ${String(t)}`)}function kr(t,e,n,r={}){let o=e in t.nodes,s=n in t.nodes;if(!o)return Oo(e,n,"no-such-from");if(!s)return Oo(e,n,"no-such-to");let i=r.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===n){if(r.findCycle===!0){let c=Pf(t,e,r);if(c!=null)return c}let u=Co(e,t.nodes[e],0,r);return Ao(e,n,[u])}if(i===0)return Oo(e,n,"no-path");let a=gc(t,e,n,i);return a.found?Ao(e,n,yc(t,a.pathOrder,r)):Oo(e,n,a.truncated?"max-depth-exceeded":"no-path")}function gc(t,e,n,r){let o=new Map,s=[{path:n,depth:0}],i=new Set([n]),a=0,u=!1;for(;a<s.length;){let l=s[a++];if(l.path===e)break;if(r!=null&&l.depth>=r){let h=t.nodes[l.path];h?.deps&&h.deps.length>0&&(u=!0);continue}let f=t.nodes[l.path];if(f==null)continue;let p=f.deps??[],m=new Map;for(let h=0;h<p.length;h++){let g=p[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)i.has(h)||(i.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:u};let c=[{path:e}],d=e;for(;d!==n;){let l=o.get(d);if(l==null)return{found:!1,pathOrder:[],truncated:!1};c[c.length-1].depIndices=l.depIndices,c.push({path:l.from}),d=l.from}return{found:!0,pathOrder:c,truncated:!1}}function Pf(t,e,n){let r=t.nodes[e];if(r==null)return null;let o=r.deps??[],s=[];for(let a=0;a<o.length;a++)o[a]===e&&s.push(a);if(s.length>0){let a=Co(e,r,0,n);a.dep_index=s[0];let u=Co(e,r,1,n);return Ao(e,e,[a,u])}let i=null;for(let a=0;a<o.length;a++){let u=o[a];if(!u||u===e)continue;let c=gc(t,u,e,n.maxDepth);c.found&&(i==null||c.pathOrder.length<i.pathOrder.length)&&(i=c,i={found:!0,pathOrder:[{path:e,depIndices:[a]},...c.pathOrder],truncated:!1})}return i==null?null:Ao(e,e,yc(t,i.pathOrder,n))}function yc(t,e,n){return e.map((r,o)=>{let s=t.nodes[r.path],i=Co(r.path,s,o,n);return r.depIndices!=null&&r.depIndices.length>0&&(i.dep_index=r.depIndices[0],r.depIndices.length>1&&(i.dep_indices=[...r.depIndices])),i})}function Co(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 i=r.lastMutations?.get(t)??e.lastMutation;return i!=null&&(o.lastMutation=i),o}function Ao(t,e,n){return bc(t,e,!0,"ok",n)}function Oo(t,e,n){return bc(t,e,!1,n,[])}function bc(t,e,n,r,o){let s=Df(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 Df(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 i of o){let u=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(s.push(u),"value"in i&&s.push(` value: ${Gf(i.value)}`),i.annotation!=null&&s.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let c=i.lastMutation.actor;s.push(` actor: ${c.type}${c.id?`:${c.id}`:""}`)}}return s.join(`
11
+ `)}function Gf(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)}}xe();var Le={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},Lo=Symbol.for("sizeof");function xr(t){let e=new WeakSet,n=new WeakSet,r=[t],o=0;for(;r.length>0;){let s=r.pop();o+=Ff(s,e,n,r)}return o}function Ff(t,e,n,r){if(t==null)return 0;switch(typeof t){case"number":return Le.number;case"boolean":return Le.boolean;case"string":return Le.string+t.length*2;case"bigint":return Le.bigint+$f(t);case"symbol":return Le.symbol;case"function":return e.has(t)?0:(e.add(t),Le.function);case"undefined":return 0}let s=t;if(e.has(s))return 0;e.add(s);let i=s[Lo];if(typeof i=="function")try{let c=i.call(s);if(typeof c=="number"&&Number.isFinite(c))return c}catch{}if(s instanceof Date)return Le.date;if(s instanceof RegExp)return Le.regexp+s.source.length*2;if(s instanceof Error){let c=s.message?s.message.length*2:0,d=s.stack?s.stack.length*2:0;return Le.error+c+d}if(typeof URL<"u"&&s instanceof URL)return Le.url+s.href.length*2;if(typeof Promise<"u"&&s instanceof Promise)return Le.promise;if(s instanceof WeakMap)return Le.weakmap;if(s instanceof WeakSet)return Le.weakset;if(s instanceof Map){let c=Le.map;for(let[d,l]of s)c+=Le.mapEntry,r.push(d),r.push(l);return c}if(s instanceof Set){let c=Le.set;for(let d of s)c+=Le.setEntry,r.push(d);return c}if(Array.isArray(s)){let c=Le.array+s.length*8;for(let d of s)r.push(d);return c}if(s instanceof ArrayBuffer)return n.has(s)?0:(n.add(s),s.byteLength);if(ArrayBuffer.isView(s)){let c=s;return n.has(c.buffer)?48:(n.add(c.buffer),c.buffer.byteLength+48)}let a=Le.object,u=Object.keys(s);for(let c of u){a+=Le.string+c.length*2;try{r.push(s[c])}catch{}}return a}function $f(t){let e=t<0n?-t:t;if(e===0n)return 0;let n=e.toString(2).length;return Math.ceil(n/32)*8}function an(t,e){let n=e?.topN??10,r=t.describe({detail:"standard"}),o=[],s=t._collectObserveTargets;typeof s=="function"&&s.call(t,"",o);let i=new Map;for(let[f,p]of o)i.set(f,p);let a=[];for(let[f,p]of Object.entries(r.nodes)){let m=i.get(f),h=m instanceof Ee?m:null,g=h?xr(h.cache):0,y=h?h._sinkCount:0,b=p.deps?.length??0,v=p.type==="effect"&&y===0,T=y===0?p.type==="effect"?"orphan-effect":p.type==="derived"?"idle-derived":p.type==="producer"?"idle-producer":null:null;a.push({path:f,type:p.type,status:p.status??"unknown",valueSizeBytes:g,subscriberCount:y,depCount:b,isOrphanEffect:v,orphanKind:T})}let u=a.reduce((f,p)=>f+p.valueSizeBytes,0),c=(f,p)=>[...a].sort(p??((m,h)=>h[f]-m[f])).slice(0,n),d=a.filter(f=>f.orphanKind!=null),l=a.filter(f=>f.isOrphanEffect);return{nodeCount:a.length,edgeCount:r.edges.length,subgraphCount:r.subgraphs.length,nodes:a,totalValueSizeBytes:u,hotspots:{byValueSize:c("valueSizeBytes"),bySubscriberCount:c("subscriberCount"),byDepCount:c("depCount")},orphans:d,orphanEffects:l}}var Ce="::",je="__meta__",it=1;function vc(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(i){console.error(`[Graph "${e}".destroy] disposer threw:`,i)}}}function Bf(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(`
12
+ `)}function Tc(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 jf(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 i=n.get(o);if(i==null&&(i=new WeakSet,n.set(o,i)),i.has(s))return!0;i.add(s);let a=o.constructor,u=s.constructor;if(a!==u)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 f=s;if(o.length!==f.length)return!1;for(let p=0;p<o.length;p++)if(!r(o[p],f[p]))return!1;return!0}if(o instanceof Map){let f=s;if(o.size!==f.size)return!1;for(let[p,m]of o)if(!f.has(p)||!r(m,f.get(p)))return!1;return!0}if(o instanceof Set){let f=s;if(o.size!==f.size)return!1;for(let p of o){let m=!1;for(let h of f)if(r(p,h)){m=!0;break}if(!m)return!1}return!0}if(ArrayBuffer.isView(o)){let f=o,p=s;if(f.length!==p.length)return!1;for(let m=0;m<f.length;m++)if(f[m]!==p[m])return!1;return!0}let c=Object.keys(o),d=Object.keys(s);if(c.length!==d.length)return!1;let l=new Set(d);for(let f of c)if(!l.has(f)||!r(o[f],s[f]))return!1;return!0};return r(t,e)}function Mi(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(Mi);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=Mi(e[o]);return r}function Vf(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Kf(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Hf(t){return t==="TD"?"down":t==="BT"?"up":t==="RL"?"left":"right"}function kc(t){let e=new Set,n=[];function r(o,s){let i=`${o}\0${s}`;e.has(i)||(e.add(i),n.push([o,s]))}for(let[o,s]of Object.entries(t.nodes)){let i=s.deps;if(i)for(let a of i)r(a,o)}for(let o of t.edges)r(o.from,o.to);return n}function xc(t){if(t===void 0)return"LR";if(t==="TD"||t==="LR"||t==="BT"||t==="RL")return t;throw new Error(`invalid diagram direction ${String(t)}; expected one of: TD, LR, BT, RL`)}function Wf(t,e){let n=e.includeEdges??!0,r=e.includeSubgraphs??!0,{expand:o,...s}=t,i={...s,edges:n?t.edges:[],subgraphs:r?t.subgraphs:[]},a=JSON.stringify(Mi(i),null,e.indent??2);return e.logger?.(a),a}function qf(t,e){let n=e.includeEdges??!0,r=e.includeSubgraphs??!0,o=[];o.push(`Graph ${t.name}`),o.push("Nodes:");for(let i of Object.keys(t.nodes).sort()){let a=t.nodes[i];o.push(`- ${i} (${a.type}/${a.status}): ${Po(a.value)}`)}if(n){o.push("Edges:");for(let i of t.edges)o.push(`- ${i.from} -> ${i.to}`)}if(r){o.push("Subgraphs:");for(let i of t.subgraphs)o.push(`- ${i}`)}let s=o.join(`
13
+ `);return e.logger?.(s),s}function Rc(t,e){let n=xc(e.direction),r=Object.keys(t.nodes).sort(),o=new Map;for(let i=0;i<r.length;i+=1)o.set(r[i],`n${i}`);let s=[`flowchart ${n}`];for(let i of r){let a=o.get(i);s.push(` ${a}["${Vf(i)}"]`)}for(let[i,a]of kc(t)){let u=o.get(i),c=o.get(a);!u||!c||s.push(` ${u} --> ${c}`)}return s.join(`
14
+ `)}function Uf(t,e){let n=Rc(t,e);return Do(n)}function Do(t,e){let n=e?.theme??"default",r=e?.autoSync??!0,s=JSON.stringify({code:t,mermaid:{theme:n},autoSync:r}),i=new TextEncoder().encode(s),a="";for(let c=0;c<i.length;c++)a+=String.fromCharCode(i[c]);return`https://mermaid.live/edit#base64:${globalThis.btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`}function zf(t,e){let n=xc(e.direction),r=Object.keys(t.nodes).sort(),o=new Map;for(let i=0;i<r.length;i+=1)o.set(r[i],`n${i}`);let s=[`direction: ${Hf(n)}`];for(let i of r){let a=o.get(i);s.push(`${a}: "${Kf(i)}"`)}for(let[i,a]of kc(t)){let u=o.get(i),c=o.get(a);!u||!c||s.push(`${u} -> ${c}`)}return s.join(`
15
+ `)}function Jf(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Io(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+=Jf(r)}return e+="$",new RegExp(e)}var Yf={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"},Qf={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function Po(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 Xf(t){return t==="none"?Qf:t==="ansi"||t==null?Yf:{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 wc(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 Zf(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 _i(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(Ce))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${Ce}' (path separator)`);if(t===je)throw new Error(`Graph "${e}": ${n} name "${je}" is reserved for meta companion paths`);Zf(t,e,n)}function em(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(Ce);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function tm(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 Sc(t){for(let e of t._mounts.values())Sc(e);for(let e of t._nodes.values())try{e.down([[de]],{internal:!0})}catch{}}var q=class t{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_topology;_topologyEmitters=new Set;constructor(e,n){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(Ce))throw new Error(`Graph name must not contain '${Ce}' (got "${e}")`);if(e===je)throw new Error(`Graph name "${je}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??Ae,this._traceRing=new sn(n?.traceCapacity??1e3),n?.versioning!=null&&this.setVersioning(n.versioning)}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=W(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)}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,i=n?.annotation;if(_i(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 a=this._nodeToName.get(e);if(a!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${a}"`);return this._nodes.set(s,e),this._nodeToName.set(e,s),this._emitTopology({kind:"added",name:s,nodeKind:"node"}),i!=null&&(this._annotations.set(s,i),this.config.inspectorEnabled&&this._traceRing.push({path:s,annotation:i,timestamp_ns:$()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof Ee&&n._applyVersioning(e)}remove(e){_i(e,this.name,"remove");let n=this._mounts.get(e);if(n){let s={kind:"mount",nodes:[],mounts:[]},i=[];n._collectObserveTargets("",i);for(let[a,u]of i)a.includes(`${Ce}${je}${Ce}`)||s.nodes.push(a);return s.nodes.sort(),s.mounts.push(e),s.mounts.push(...n._collectSubgraphs(`${e}${Ce}`)),this._mounts.delete(e),n._parent=void 0,Sc(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([[de]],{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=Io(e);return i=>s.test(i)})(),r={kind:"mount",nodes:[],mounts:[]},o=[...this._nodes.keys(),...this._mounts.keys()].filter(s=>n(s));for(let s of o){let i=this.remove(s);r.nodes.push(...i.nodes),r.mounts.push(...i.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(Ce))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([[S,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([[He]],{actor:n?.actor,internal:r,delivery:"write"})}error(e,n,r){let o=r?.internal===!0;this.node(e).down([[M,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[u,c]of this._nodes)r.set(c,u);let a=[];for(let[u,c]of this._nodes)if(c instanceof Ee)for(let d of c._deps){let l=r.get(d.node);l!=null&&a.push([l,u])}return a.sort((u,c)=>u[0]<c[0]?-1:u[0]>c[0]?1:u[1]<c[1]?-1:u[1]>c[1]?1:0),a}let o=[];this._collectObserveTargets("",o);let s=new Map;for(let[a,u]of o)s.set(u,a);let i=[];for(let[a,u]of o)if(u instanceof Ee)for(let c of u._deps){let d=s.get(c.node);d!=null&&i.push([d,a])}return i.sort((a,u)=>a[0]<u[0]?-1:a[0]>u[0]?1:a[1]<u[1]?-1:a[1]>u[1]?1:0),i}mount(e,n){if(_i(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(n===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(n._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${n._parent.name}"`);for(let r=this;r!=null;r=r._parent)if(r===n)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,n),n._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),n}resolve(e){let n=em(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 a=this._nodes.get(r);if(a)return a;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]===je)return this._resolveMetaChainFromNode(s,o,n.join(Ce));let i=this._mounts.get(r);if(!i)throw this._nodes.has(r)?new Error(`Graph "${this.name}": "${r}" is a node; trailing path "${o.join(Ce)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(o.join(Ce))}_resolveMetaChainFromNode(e,n,r){let o=e,s=0,i=[...n];for(;s<i.length;){if(i[s]!==je)throw new Error(`Graph "${this.name}": expected ${je} segment in meta path "${r}"`);if(s+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${je} in "${r}"`);let a=i[s+1],u=o.meta[a];if(!u)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${r}"`);o=u,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 u of this._mounts.values())u._signalDeliver(e,n,r,o);let i=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},a=tm(e,this.config);for(let u of[...this._nodes.keys()].sort()){let c=this._nodes.get(u);if(!r.has(c)){r.add(c);try{c.down(e,i)}catch(d){if(d instanceof Je)throw d;o.push(d)}a.length!==0&&this._signalMetaSubtree(c,a,r,i,o)}}}_signalMetaSubtree(e,n,r,o,s){for(let i of Object.keys(e.meta).sort()){let a=e.meta[i];if(!r.has(a)){r.add(a);try{a.down(n,o)}catch(u){if(u instanceof Je)throw u;s.push(u)}this._signalMetaSubtree(a,n,r,o,s)}}}describe(e){if(e?.reactive===!0)return this._describeReactive(e);let n=e?.actor,r=e?.filter,o=wt(e?.detail,e?.fields),s=e?.format==="spec",i=s?wt("minimal"):o,a=[];this._collectObserveTargets("",a);let u=new Map;for(let[k,x]of a)u.set(x,k);let c=[];{let k=a.map(([,E])=>E),x=new Set(u.values()),R=0;for(;k.length>0;){let E=k.shift();if(E instanceof Ee)for(let G of E._deps){let L=G.node;if(u.has(L))continue;let P=L.name??"",C=P;if(!C||x.has(C))if(P){let V=2;for(;x.has(`${P}#${V}`);)V++;C=`${P}#${V}`}else for(C=`__internal__/${R++}`;x.has(C);)C=`__internal__/${R++}`;u.set(L,C),x.add(C),c.push([C,L]),k.push(L)}}}let d=[...a,...c],l={};for(let[k,x]of d){if(n!=null&&!x.allowsObserve(n))continue;let R=wr(x,i),E=x instanceof Ee?x._deps.map(C=>u.get(C.node)??C.node.name??""):[],{name:G,...L}=R,P={...L,deps:E};if(!s){let C=this._annotations.get(k);C!=null&&(P.annotation=C)}if(r!=null)if(typeof r=="function"){let C=r;if(!(C.length>=2?C(k,P):C(P)))continue}else{let C=!0;for(let[V,ne]of Object.entries(r)){let F=V==="deps_includes"?"depsIncludes":V==="meta_has"?"metaHas":V;if(F==="depsIncludes"){if(!P.deps.includes(String(ne))){C=!1;break}continue}if(F==="metaHas"){if(!Object.hasOwn(P.meta??{},String(ne))){C=!1;break}continue}if(P[F]!==ne){C=!1;break}}if(!C)continue}l[k]=P}let f=new Set(Object.keys(l)),p=[];for(let[k,x]of d)if(x instanceof Ee)for(let R of x._deps){let E=u.get(R.node);E!=null&&p.push([E,k])}p.sort((k,x)=>k[0]<x[0]?-1:k[0]>x[0]?1:k[1]<x[1]?-1:k[1]>x[1]?1:0);let m=p.map(([k,x])=>({from:k,to:x}));(n!=null||r!=null)&&(m=m.filter(k=>f.has(k.from)&&f.has(k.to)));let h=this._collectSubgraphs(""),g=n!=null||r!=null?h.filter(k=>{let x=`${k}${Ce}`;return[...f].some(R=>R===k||R.startsWith(x))}):h,y=this,b=e,v={name:this.name,nodes:l,edges:m,subgraphs:g,expand(k){let x={...b,format:void 0};return Array.isArray(k)?(x.fields=k,x.detail=void 0):(x.detail=k,x.fields=void 0),y.describe(x)}},T=e??{},w=T.format;return w==="json"?Wf(v,T):w==="pretty"?qf(v,T):w==="mermaid"?Rc(v,T):w==="mermaid-url"?Uf(v,T):w==="d2"?zf(v,T):w==="ascii"?hc(v,T):v}_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}${Ce}`))}return n}resourceProfile(e){return an(this,e)}reachable(e,n,r={}){return r.withDetail===!0?un(this.describe(),e,n,{...r,withDetail:!0}):un(this.describe(),e,n,r)}explain(e,n,r){return r?.reactive===!0?this._explainReactive(e,n,r):this._explainStatic(e,n,r)}_explainStatic(e,n,r){let o=this.describe({detail:"full"}),s=new Map(this._annotations),i=new Map;for(let[a,u]of Object.entries(o.nodes))u.lastMutation!=null&&i.set(a,u.lastMutation);return kr(o,e,n,{...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{},annotations:s,lastMutations:i})}_describeReactive(e){let n={...e,reactive:!1},r=e.reactiveName??"describe",o=0,s=N(o,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,u=!1,c=()=>{a||u||(a=!0,lr(()=>{a=!1,!u&&(o+=1,s.emit(o))}))},d=i.onEvent(g=>{let y=g.type;y!=="data"&&y!=="error"&&y!=="complete"&&y!=="teardown"||c()}),l=[],f=new WeakSet,p=g=>{if(f.has(g)||u)return;f.add(g);let y=g.topology.subscribe(b=>{for(let v of b){if(v[0]!==S)continue;let T=v[1];if(c(),T.kind==="added"&&T.nodeKind==="mount"){let w=g._mounts.get(T.name);w!=null&&p(w)}}});l.push(y);for(let b of g._mounts.keys()){let v=g._mounts.get(b);v!=null&&p(v)}};p(this);let m;try{m=O([s],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(g,y)=>g===y})}catch(g){d();for(let y of l)y();throw i.dispose(),g}let h=se(m);return{node:m,dispose(){u=!0,d();for(let g of l)g();l.length=0,i.dispose(),h()}}}_explainReactive(e,n,r){let o=0,s=N(o,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,u=!1,c=i.onEvent(p=>{let m=p.type;m!=="data"&&m!=="error"&&m!=="complete"&&m!=="teardown"||a||u||(a=!0,lr(()=>{a=!1,!u&&(o+=1,s.emit(o))}))}),d={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},l;try{l=O([s],()=>this._explainStatic(e,n,d),{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:e,to:n},equals:(p,m)=>p.found===m.found&&p.reason===m.reason&&p.steps.length===m.steps.length&&nm(p.steps,m.steps)})}catch(p){throw c(),i.dispose(),p}let f=se(l);return{node:l,dispose(){u=!0,c(),i.dispose(),f()}}}_pathsMatching(e){let n=Io(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}${Ce}${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}${Ce}${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],i=`${e}${Ce}${je}${Ce}${o}`;r.push([i,s]),this._appendMetaObserveTargets(i,s,r)}}observe(e,n){let r=typeof e=="string",s=wc(r?n:e),i=s.structured===!0||s.timeline===!0||s.causal===!0||s.derived===!0||s.detail==="minimal"||s.detail==="full"||s.format!=null,a=s.actor;if(r){let d=e,l=this.resolve(d);if(a!=null&&!l.allowsObserve(a))throw new Je({actor:a,action:"observe",nodeName:d});return i?this._buildStructuredObserver([[d,l]],s,"one"):{subscribe(f){return l.subscribe(f)},up(f){try{l.up?.(f)}catch(p){if(p instanceof Je)return;throw p}}}}let u=[];this._collectObserveTargets("",u),u.sort((d,l)=>d[0]<l[0]?-1:d[0]>l[0]?1:0);let c=a==null?u:u.filter(([,d])=>d.allowsObserve(a));return i?this._buildStructuredObserver(c,s,"all"):{subscribe:d=>{let l=c.map(([f,p])=>p.subscribe(m=>{d(f,m)}));return()=>{for(let f of l)f()}},up:(d,l)=>{try{this.resolve(d).up?.(l)}catch(f){if(f instanceof Je)return;throw f}}}}_buildStructuredObserver(e,n,r){let o=r==="one"?e[0]?.[0]:void 0,s=i=>{if(r==="one"&&o!=null){let d=this.resolve(o);return this._buildStructuredObserver([[o,d]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((d,l)=>d[0]<l[0]?-1:d[0]>l[0]?1:0);let u=i.actor,c=u==null?a:a.filter(([,d])=>d.allowsObserve(u));return this._buildStructuredObserver(c,i,"all")};return this._createObserveResult(e,n,s)}_createObserveResult(e,n,r){let o=n.timeline===!0,s=n.causal===!0,i=n.derived===!0,a=n.detail==="minimal",u=this.config.inspectorEnabled,c=(s||i)&&u,d=n.maxEvents,l=d!=null&&d>0?new sn(d):null,f=[],p=new Set,m={},h=new Set,g=0,y=0,b=0,v=0,T=0,w=0,k=!1,x=!1,R=0,E=new Map,G=new Map,L=new Map,P=j=>{l?l.push(j):f.push(j);for(let Y of p)Y(j)},C=()=>o?{timestamp_ns:$(),in_batch:zt(),batch_id:R}:{},V=(j,Y)=>{if(!(!c||!(j instanceof Ee)))return j._setInspectorHook(J=>{if(J.kind==="dep_message")E.set(j,J.depIndex);else if(J.kind==="run"){let z=J.batchData.map((H,le)=>H!=null&&H.length>0?H.at(-1):J.prevData[le]);G.set(j,z);let X=J.batchData.map(H=>H!=null?[...H]:void 0);L.set(j,X),i&&P({type:"derived",path:Y,dep_values:z,dep_batches:X,...C()})}})},ne=j=>{let Y=E.get(j),J=G.get(j);if(!s||J==null)return{};let X=(Y!=null&&Y>=0&&j instanceof Ee?j._deps[Y]:void 0)?.node,H=X?.v,le=L.get(j);return{trigger_dep_index:Y,trigger_dep_name:X?.name,...H!=null?{trigger_version:{id:H.id,version:H.version}}:{},dep_values:[...J],...le!=null?{dep_batches:le}:{}}},F=[],A=[];for(let[j,Y]of e){let J=V(Y,j);J&&F.push(J),A.push(Y.subscribe(z=>{R++;for(let X of z){let H=X[0],le=C();if(H===S){m[j]=X[1];let ve=Y instanceof Ee?Y.lastMutation?.actor??lt:lt;P({type:"data",path:j,data:X[1],actor:ve,...le,...ne(Y)})}else if(a)H===ee?g++:H===B?y++:H===He?b++:H===Ie?v++:H===Ge?T++:H===de?w++:H===_&&!h.has(j)?k=!0:H===M&&(x=!0,h.add(j));else if(H===ee)g++,P({type:"dirty",path:j,...le});else if(H===B)y++,P({type:"resolved",path:j,...le,...ne(Y)});else if(H===He)b++,P({type:"invalidate",path:j,...le});else if(H===Ie)v++,P({type:"pause",path:j,lockId:X[1],...le});else if(H===Ge)T++,P({type:"resume",path:j,lockId:X[1],...le});else if(H===_)h.has(j)||(k=!0),P({type:"complete",path:j,...le});else if(H===M){x=!0,h.add(j);let ve=Y instanceof Ee?Y.lastMutation?.actor??lt:lt;P({type:"error",path:j,data:X[1],actor:ve,...le})}else H===de&&(w++,P({type:"teardown",path:j,...le}))}}))}let D=!1,I=()=>{if(!D){D=!0;for(let j of A)j();for(let j of F)j();for(let j of U)j({value:void 0,done:!0});U.length=0}},Q=[],U=[];p.add(j=>{let Y=U.shift();Y?Y({value:j,done:!1}):Q.push(j)});let ae={get values(){return m},get dirtyCount(){return g},get resolvedCount(){return y},get invalidateCount(){return b},get pauseCount(){return v},get resumeCount(){return T},get teardownCount(){return w},get events(){return l?l.toArray():[...f]},get anyCompletedCleanly(){return k},get anyErrored(){return x},get completedWithoutErrors(){return k&&!x},onEvent(j){return p.add(j),()=>p.delete(j)},dispose:I,expand(j){I();let Y={...n};return typeof j=="string"?Y.detail=j:Object.assign(Y,j),r(wc(Y))},[Symbol.asyncIterator](){return{next(){return Q.length>0?Promise.resolve({value:Q.shift(),done:!1}):D?Promise.resolve({value:void 0,done:!0}):new Promise(j=>U.push(j))},return(){return I(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(ae,n),ae}_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,i=n.excludeTypes?new Set(n.excludeTypes):null,a=s==null&&i==null?()=>!0:m=>(s==null||s.has(m))&&(i==null||!i.has(m)),u=Xf(n.theme),c=r==="stage-log"?$():0,d=m=>m==null?"":n.stageLabels?.[m]??m,l=(m,h)=>m.length>h?`${m.slice(0,h-1)}\u2026`:m,f=m=>m.type==="data"||m.type==="error"?l(Po(m.data),120):"",p=m=>{if(r==="stage-log"){let x=($()-c)/1e9,R=d(m.path).padEnd(9);if(m.type==="data"){let E=f(m);return`[${x.toFixed(3)}s] ${R} \u2190${E?` ${E}`:""}`}if(m.type==="error"){let E=f(m);return`[${x.toFixed(3)}s] ${R} \u2717${E?` ${E}`:""}`}return m.type==="complete"?`[${x.toFixed(3)}s] ${R} \u25A0 complete`:`[${x.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=u[m.type]??"",g=m.path?`${u.path}${m.path}${u.reset} `:"",y=m.type==="data"||m.type==="error",b=m.type==="pause"||m.type==="resume",v=y?` ${Po(m.data)}`:b?` ${Po(m.lockId)}`:"",T=m.type==="data"||m.type==="resolved"||m.type==="derived"?m:void 0,w=T?.trigger_dep_name!=null?` <- ${T.trigger_dep_name}`:T?.trigger_dep_index!=null?` <- #${T.trigger_dep_index}`:"",k=m.in_batch?" [batch]":"";return`${g}${h}${m.type.toUpperCase()}${u.reset}${v}${w}${k}`};e.onEvent(m=>{a(m.type)&&o(p(m),m)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){vc(this._disposers,this.name),this.signal([[de]],{internal:!0}),vc(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}_destroyClearOnly(){for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0}snapshot(e){let{expand:n,...r}=this.describe({detail:"full"}),o={};for(let a of Object.keys(r.nodes).sort()){let{lastMutation:u,guard:c,...d}=r.nodes[a];o[a]=d}let s=[...r.subgraphs].sort(),i={...r,version:1,nodes:o,subgraphs:s};if(e?.format==null)return i;if(e.format==="json-string")return JSON.stringify(i);if(e.format==="bytes"){if(e.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let a=this.config.lookupCodec(e.codec);if(a==null)throw new Error(`snapshot: codec "${e.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return sr(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??Ae,{codec:o,codecVersion:s,payload:i}=ir(e,r);return o.decode(i,s)}restore(e,n){if(Tc(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=>Io(s)),o=n?.includeProducers===!0;for(let s of Object.keys(e.nodes).sort()){if(r!==null&&!r.some(a=>a.test(s)))continue;let i=e.nodes[s];if(i!==void 0){if(!("value"in i)||i.value===void 0){"value"in i&&i.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(!(i.type==="derived"||i.type==="effect")&&!(i.type==="producer"&&!o)){if(i.v!=null){let u=this.tryResolve(s)?.v;if(u!=null&&u.id===i.v.id&&u.version===i.v.version)continue}try{this.set(s,i.value)}catch(a){n?.onError?.(s,a)}}}}}static fromSnapshot(e,n){Tc(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 p of[...e.subgraphs].sort((m,h)=>{let g=m.split(Ce).length,y=h.split(Ce).length;return g!==y?g-y:m<h?-1:m>h?1:0})){let m=p.split(Ce),h=s;for(let g of m)h._mounts.has(g)||h.mount(g,new t(g)),h=h._mounts.get(g)}let i=o?Object.entries(o).map(([p,m])=>({re:Io(p),factory:m})):[],a=p=>{for(let m of i)if(m.re.test(p))return m.factory},u=p=>{let m=p.split(Ce),h=m.pop();if(h==null||h.length===0)throw new Error(`invalid snapshot path "${p}"`);let g=s;for(let y of m){let b=g._mounts.get(y);if(!b)throw new Error(`unknown mount "${y}" in path "${p}"`);g=b}return[g,h]},c=Object.entries(e.nodes).filter(([p])=>!p.includes(`${Ce}${je}${Ce}`)).sort((p,m)=>p[0]<m[0]?-1:p[0]>m[0]?1:0),d=new Map(c),l=new Map,f=!0;for(;d.size>0&&f;){f=!1;for(let[p,m]of[...d.entries()]){let h=m?.deps??[];if(!h.every(w=>l.has(w)))continue;let[g,y]=u(p),b={...m?.meta??{}},v=a(p),T;if(m?.type==="state")T=N(m.value,{meta:b});else{if(v==null)continue;T=v(y,{path:p,type:m.type,value:m.value,meta:b,deps:h,resolvedDeps:h.map(w=>l.get(w))})}g.add(T,{name:y}),l.set(p,T),d.delete(p),f=!0}}if(d.size>0){let p=[...d.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${p}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return s.restore(e),s}toJSON(){return this.snapshot()}attachStorage(e,n={}){let r=e.map(c=>({tier:c,debounceMs:Math.max(0,c.debounceMs??0),compactEvery:Math.max(1,c.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=(c,d)=>{if(c.disposed)return;let l=Bf(d.nodes);if(c.lastSnapshot!=null&&l!==""&&l===c.lastFingerprint)return;let f=c.seq+1,p=pe(),g=c.lastSnapshot==null||f%c.compactEvery===0?{mode:"full",snapshot:d,seq:f,timestamp_ns:p,format_version:it}:{mode:"diff",diff:Go(c.lastSnapshot,d),seq:f,timestamp_ns:p,format_version:it};if(c.tier.filter&&!c.tier.filter(this.name,g))return;let y;try{y=c.tier.save(this.name,g)}catch(b){n.onError?.(b,c.tier);return}if(y&&typeof y.then=="function"){let T=(c.savePending??Promise.resolve()).then(()=>y,()=>y).then(()=>{c.disposed||(c.seq=f,c.lastSnapshot=d,c.lastFingerprint=l)},w=>{n.onError?.(w,c.tier)});c.savePending=T.finally(()=>{c.savePending===T&&(c.savePending=void 0)})}else c.seq=f,c.lastSnapshot=d,c.lastFingerprint=l},s=(c,d)=>{try{o(c,d)}catch(l){n.onError?.(l,c.tier)}},i=(c,d)=>{if(!d.some(m=>{let h=this.config.messageTier(m[0]);return h>=3&&h<5}))return;if(n.filter){let m=this.tryResolve(c);if(m==null)return;let h=wr(m,wt("standard"));if(!n.filter(c,h))return}let f,p=()=>(f==null&&(f=this.snapshot()),f);for(let m of r)m.disposed||(m.debounceMs===0?s(m,p()):(m.timer==null&&(m.timer=new _e),m.timer.start(m.debounceMs,()=>{m.disposed||s(m,this.snapshot())})))},a;if(n.paths!=null){let d=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(l=>{let f=this.tryResolve(l);return f==null?()=>{}:f.subscribe(p=>i(l,p))});a=()=>{for(let l of d)l()}}else a=this.observe().subscribe((c,d)=>i(c,d));let u=()=>{a();for(let c of r)c.disposed=!0,c.timer?.cancel();this._storageDisposers.delete(u)};return this._storageDisposers.add(u),{dispose:u}}async _cascadeRestore(e,n){for(let r of e){let o;try{o=await r.load(this.name)}catch(i){n?.(i,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(i){n?.(i,r)}}return!1}static async fromStorage(e,n,r){for(let o of n){let s;try{s=await o.load(e)}catch(u){r?.onError?.(u,o);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let i=s,a=i.mode==="full"&&i.snapshot!=null?i.snapshot:i.version===it&&i.nodes!=null?i:void 0;if(a!=null)try{return t.fromSnapshot(a,r)}catch(u){r?.onError?.(u,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:$(),...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(b=>!r.has(b)).sort(),i=[...r].filter(b=>!o.has(b)).sort(),a=[],u=[];for(let b of r){if(!o.has(b))continue;let v=e.nodes[b],T=n.nodes[b],w=v.v,k=T.v;w!=null&&k!=null&&w.id===k.id&&w.version!==k.version&&u.push({path:b,id:w.id,from:w.version,to:k.version});let x=w!=null&&k!=null&&w.id===k.id&&w.version===k.version;for(let R of["type","status","sentinel"]){let E=v[R],G=T[R];E!==G&&a.push({path:b,field:R,from:E,to:G})}if(!x)for(let R of["value","meta"]){let E=v[R],G=T[R];jf(E,G)||a.push({path:b,field:R,from:E,to:G})}}let c=b=>`${b.from} ${b.to}`,d=new Set(e.edges.map(c)),l=new Set(n.edges.map(c)),f=n.edges.filter(b=>!d.has(c(b))),p=e.edges.filter(b=>!l.has(c(b))),m=new Set(e.subgraphs),h=new Set(n.subgraphs),g=[...h].filter(b=>!m.has(b)).sort(),y=[...m].filter(b=>!h.has(b)).sort();return{nodesAdded:s,nodesRemoved:i,nodesChanged:a,versionChanges:u,edgesAdded:f,edgesRemoved:p,subgraphsAdded:g,subgraphsRemoved:y}}};function Go(t,e){let n=q.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 un(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 i=new Map,a=new Map,u=new Map,c=new Map,d=new Set;for(let[v,T]of Object.entries(t.nodes)){if(!v)continue;d.add(v);let w=T.deps??[];i.set(v,w);for(let k of w)k&&(d.add(k),a.has(k)||a.set(k,new Set),a.get(k).add(v))}for(let v of t.edges){if(v==null||typeof v!="object")continue;let T=typeof v.from=="string"?v.from:"",w=typeof v.to=="string"?v.to:"";!T||!w||(d.add(T),d.add(w),c.has(T)||c.set(T,new Set),c.get(T).add(w),u.has(w)||u.set(w,new Set),u.get(w).add(T))}if(!d.has(e))return r.withDetail?o:[];let l=r.both===!0,f=v=>{if(l){let x=i.get(v)??[],R=u.get(v),E=a.get(v),G=c.get(v),L=[...x];return R&&L.push(...R),E&&L.push(...E),G&&L.push(...G),L}if(n==="upstream"){let x=i.get(v)??[],R=u.get(v);return R?[...x,...R]:x}let T=a.get(v),w=c.get(v),k=T?[...T]:[];return w&&k.push(...w),k},p=new Set([e]),m=new Map,h=[{path:e,depth:0}],g=0,y=!1;for(;g<h.length;){let v=h[g++];if(s!=null&&v.depth>=s){f(v.path).length>0&&(y=!0);continue}for(let T of f(v.path))!T||p.has(T)||(p.add(T),m.set(T,v.depth+1),h.push({path:T,depth:v.depth+1}))}let b=[...m.keys()].sort((v,T)=>v<T?-1:v>T?1:0);return r.withDetail?{paths:b,depths:m,truncated:y}:b}function nm(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,i=o.v;if(s!==i&&(s==null||i==null||s.id!==i.id||s.version!==i.version))return!1}return!0}var Bo={};he(Bo,{CqrsGraph:()=>$o,MemoryEventStore:()=>Ii,cqrs:()=>Pi});Ne();ke();Qt();var Oi={};he(Oi,{COMPLETE:()=>_,COMPLETE_MSG:()=>eo,COMPLETE_ONLY_BATCH:()=>or,DATA:()=>S,DEFAULT_ACTOR:()=>lt,DIRTY:()=>ee,DIRTY_MSG:()=>yt,DIRTY_ONLY_BATCH:()=>Rn,ERROR:()=>M,GraphReFlyConfig:()=>Jt,GuardDenied:()=>Je,INVALIDATE:()=>He,INVALIDATE_MSG:()=>Zr,INVALIDATE_ONLY_BATCH:()=>rr,NodeImpl:()=>Ee,PAUSE:()=>Ie,RESOLVED:()=>B,RESOLVED_MSG:()=>kn,RESOLVED_ONLY_BATCH:()=>nr,RESUME:()=>Ge,START:()=>dt,START_MSG:()=>xn,TEARDOWN:()=>de,TEARDOWN_MSG:()=>to,TEARDOWN_ONLY_BATCH:()=>Sn,accessHintForGuard:()=>mr,advanceVersion:()=>hr,autoTrackNode:()=>Xt,batch:()=>te,configure:()=>pi,createVersioning:()=>Mn,defaultConfig:()=>Ae,defaultHash:()=>Ot,derived:()=>O,downWithBatch:()=>vt,dynamicNode:()=>gr,effect:()=>fe,isBatching:()=>zt,isV1:()=>ci,monotonicNs:()=>$,node:()=>K,normalizeActor:()=>bt,pipe:()=>fi,policy:()=>Yt,policyFromRules:()=>fr,producer:()=>W,registerBuiltins:()=>pr,resolveDescribeFields:()=>wt,state:()=>N,wallClockNs:()=>pe});ur();Ne();ke();ai();Qt();ie();xe();oe();oo();Ne();ie();oe();var Rr=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 i=new Array(s);for(let a=0;a<s;a++)i[a]=this._buf[(this._head+o+a)%this._maxSize];return i}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}_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 Nc(t){return t.subscribe(()=>{})}var rm=64;function Ve(t,e={}){let{name:n,maxSize:r,versioning:o,backend:s}=e,i=s??new Rr(t,r),a=N(i.toArray(),{name:n,describeKind:"state",equals:(m,h)=>m===h,...o!=null?{versioning:o}:{}});function u(){let m=i.toArray();te(()=>{a.down([[ee]]),a.down([[S,m]])})}let c=new Map,d=new Map;function l(m,h){return`${m}:${h===void 0?"END":h}`}function f(m){if(m.size<rm)return;let h=m.keys().next();if(h.done)return;let g=m.get(h.value);g!==void 0&&g.dispose(),m.delete(h.value)}function p(m){let h=i.version;try{return m()}finally{i.version!==h&&u()}}return{entries:a,get size(){return i.size},at(m){return i.at(m)},append(m){p(()=>i.append(m))},appendMany(m){m.length!==0&&p(()=>i.appendMany(m))},clear(){p(()=>i.clear())},trimHead(m){p(()=>i.trimHead(m))},tail(m){if(!Number.isInteger(m)||m<0)throw new RangeError(`tail: n must be a non-negative integer (got ${m})`);let h=c.get(m);if(h!==void 0)return c.delete(m),c.set(m,h),h.node;f(c);let g=O([a],([b])=>{let v=b;return m===0||v.length===0?[]:v.slice(Math.max(0,v.length-m))},{initial:i.tail(m),describeKind:"derived"}),y=Nc(g);return c.set(m,{node:g,dispose:y}),g},slice(m,h){if(!Number.isInteger(m)||m<0)throw new RangeError(`slice: start must be a non-negative integer (got ${m})`);if(h!==void 0&&(!Number.isInteger(h)||h<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${h})`);let g=l(m,h),y=d.get(g);if(y!==void 0)return d.delete(g),d.set(g,y),y.node;f(d);let b=O([a],([T])=>{let w=T;return h===void 0?w.slice(m):w.slice(m,h)},{initial:i.slice(m,h),describeKind:"derived"}),v=Nc(b);return d.set(g,{node:b,dispose:v}),b},disposeTail(m){let h=c.get(m);return h===void 0?!1:(h.dispose(),c.delete(m),!0)},disposeSlice(m,h){let g=l(m,h),y=d.get(g);return y===void 0?!1:(y.dispose(),d.delete(g),!0)},disposeAllViews(){for(let m of c.values())m.dispose();c.clear();for(let m of d.values())m.dispose();d.clear()},dispose(){for(let m of c.values())m.dispose();c.clear();for(let m of d.values())m.dispose();d.clear()}}}var Ai={};he(Ai,{ENVELOPE_VERSION:()=>Nn,GRAPH_META_SEGMENT:()=>je,Graph:()=>q,JsonCodec:()=>no,SIZEOF_OVERHEAD:()=>Le,SIZEOF_SYMBOL:()=>Lo,SNAPSHOT_VERSION:()=>it,createDagCborCodec:()=>oi,createDagCborZstdCodec:()=>si,decodeEnvelope:()=>ir,diffForWAL:()=>Go,encodeEnvelope:()=>sr,explainPath:()=>kr,graphProfile:()=>an,mermaidLiveUrl:()=>Do,reachable:()=>un,registerBuiltinCodecs:()=>ar,replayWAL:()=>ii,sizeof:()=>xr,validateGraphObservability:()=>Ci,watchTopologyTree:()=>kt});ro();ie();function kt(t,e){let n=new Map,r=(o,s)=>{if(n.has(o))return;let i={off:()=>{},prefix:s};n.set(o,i);let a=o.topology.subscribe(u=>{for(let c of u){if(c[0]!==S)continue;let d=c[1];if(e(d,o,s),d.kind==="added"&&d.nodeKind==="mount"){let l=o._mounts.get(d.name);if(l instanceof q){let f=`${s}${d.name}::`;r(l,f)}}else if(d.kind==="removed"&&d.nodeKind==="mount"){let l=`${s}${d.name}::`;for(let[f,p]of Array.from(n.entries()))f!==t&&p.prefix.startsWith(l)&&(p.off(),n.delete(f))}}});i.off=a;for(let[u,c]of o._mounts)if(c instanceof q){let d=`${s}${u}::`;r(c,d)}};return r(t,""),()=>{for(let o of n.values())o.off();n.clear()}}function Ci(t,e={}){let n=[],r=e.requireFound??!0;if(e.skipDescribe!==!0)try{let c=t.describe(),d=new Set(Object.keys(c.nodes)),l=[];for(let[f,p]of Object.entries(c.nodes))for(let m of p.deps)m!==""&&!d.has(m)&&l.push(`${f} \u2192 ${m}`);for(let f of c.edges)d.has(f.from)||l.push(`edge.from: ${f.from}`),d.has(f.to)||l.push(`edge.to: ${f.to}`);l.length>0?n.push({kind:"describe",ok:!1,reason:`describe() has ${l.length} dangling pointer(s); nodes \u2289 deps`,danglingDeps:l}):n.push({kind:"describe",ok:!0,nodeCount:d.size,edgeCount:c.edges.length})}catch(c){n.push({kind:"describe",ok:!1,reason:`describe() threw: ${c instanceof Error?c.message:String(c)}`})}for(let c of e.formats??[])try{let d=t.describe({format:c});typeof d!="string"||d.length===0?n.push({kind:"describe-format",ok:!1,format:c,reason:`describe({ format: "${c}" }) returned empty or non-string output`}):n.push({kind:"describe-format",ok:!0,format:c,length:d.length})}catch(d){n.push({kind:"describe-format",ok:!1,format:c,reason:d instanceof Error?d.message:String(d)})}for(let c of e.paths??[])try{t.resolve(c),n.push({kind:"observe",ok:!0,path:c})}catch(d){n.push({kind:"observe",ok:!1,path:c,reason:d instanceof Error?d.message:String(d)})}for(let[c,d]of e.pairs??[])try{let l=t.explain(c,d);r&&l.found===!1?n.push({kind:"explain",ok:!1,from:c,to:d,reason:`explain(${c} \u2192 ${d}) found no path${l.reason?`: ${l.reason}`:""}`}):n.push({kind:"explain",ok:!0,from:c,to:d,found:l.found,steps:l.steps.length})}catch(l){n.push({kind:"explain",ok:!1,from:c,to:d,reason:l instanceof Error?l.message:String(l)})}let o=n.filter(c=>!c.ok),s=o.length===0,i=e.paths?.length??0,a=e.pairs?.length??0,u=e.formats?.length??0;return{ok:s,checks:n,failures:o,summary(){let c=[e.skipDescribe===!0?null:"describe",u>0?`${u} format${u===1?"":"s"}`:null,i>0?`${i} observe path${i===1?"":"s"}`:null,a>0?`${a} explain pair${a===1?"":"s"}`:null].filter(l=>l!=null),d=c.length>0?c.join(", "):"describe-only";return s?`validateGraphObservability: OK (${d})`:`validateGraphObservability: ${o.length} failure(s) across ${d}`}}}Ne();ie();xe();Re();function at(t,e){t!=null&&vt(n=>t.down(n),[[S,e]],Ae.tierOf)}function Sr(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[ee],[S,n+1]]),!0)}function Ke(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}function Li(t){return t.relatedTo?.[0]??t.summary}var om=Yt((t,e)=>{t("write"),t("signal"),e("observe")}),sm=Yt((t,e)=>{t("observe"),t("signal"),e("write")}),im=Yt((t,e)=>{t("observe"),t("signal"),e("write")});function Fo(t,e){return Ke("cqrs",t,e)}var Ii=class{_store=new Map;persist(e){let n=this._store.get(e.type);n||(n=[],this._store.set(e.type,n)),n.push(e)}loadEvents(e,n){let r=this._store.get(e)??[],o=n?.timestampNs,s=n?.seq,i=o==null?[...r]:r.filter(u=>u.timestampNs>o||u.timestampNs===o&&u.seq>(s??-1)),a=i.length>0?i[i.length-1]:void 0;return{events:i,cursor:a?{timestampNs:a.timestampNs,seq:a.seq}:n}}clear(){this._store.clear()}},$o=class extends q{_eventLogs=new Map;_commandHandlers=new Map;_projections=new Set;_sagas=new Set;_keepaliveDisposers=[];_eventStore;_seq=0;constructor(e,n={}){super(e,n.graph)}destroy(){for(let e of this._keepaliveDisposers)e();this._keepaliveDisposers.length=0,super.destroy()}event(e){let n=this._eventLogs.get(e);if(n)return n.node;let r=Ve([],{name:e,versioning:0}),o=r.entries,s=O([o],([i])=>i,{name:e,describeKind:"state",meta:Fo("event",{event_name:e}),guard:im,initial:o.cache});return this.add(s,{name:e}),this._keepaliveDisposers.push(se(s)),this._eventLogs.set(e,{log:r,node:s}),s}_appendEvent(e,n){let r=this._eventLogs.get(e);if(r||(this.event(e),r=this._eventLogs.get(e)),r.node.status==="completed"||r.node.status==="errored")throw new Error(`Cannot dispatch to terminated event stream "${e}" (status: ${r.node.status}).`);let o=r.log.entries.v,s={type:e,payload:n,timestampNs:pe(),seq:++this._seq,...o!=null?{v0:{id:o.id,version:o.version}}:{}};r.log.append(s),this._eventStore&&this._eventStore.persist(s)}command(e,n){let r=N(void 0,{name:e,describeKind:"state",meta:{...Fo("command",{command_name:e}),error:null},guard:om});return this.add(r,{name:e}),this._commandHandlers.set(e,n),r}dispatch(e,n){let r=this._commandHandlers.get(e);if(!r)throw new Error(`Unknown command: "${e}". Register with .command() first.`);let o=this.resolve(e);te(()=>{o.emit(n,{internal:!0});try{r(n,{emit:(s,i)=>this._appendEvent(s,i)}),o.meta.error.emit(null,{internal:!0})}catch(s){throw o.meta.error.emit(s,{internal:!0}),s}})}projection(e,n,r,o){let s=n.map(a=>(this._eventLogs.has(a)||this.event(a),this._eventLogs.get(a).node)),i=O(s,a=>{let u=[];for(let c of a){let d=c;u.push(...d)}return u.sort((c,d)=>c.timestampNs-d.timestampNs||c.seq-d.seq),r(o,u)},{name:e,describeKind:"derived",meta:Fo("projection",{projection_name:e,source_events:n}),guard:sm,initial:o});return this.add(i,{name:e}),this._keepaliveDisposers.push(se(i)),this._projections.add(e),i}saga(e,n,r){let o=n.map(u=>(this._eventLogs.has(u)||this.event(u),this._eventLogs.get(u).node)),s=new Map,i={},a=K(o,(u,c)=>{let d=i.n.meta.error;for(let l=0;l<u.length;l++){let f=u[l];if(f==null||f.length===0)continue;let p=f.at(-1);if(!p)continue;let m=n[l],h=s.get(m)??0;if(p.length>h){let g=p.slice(h);for(let y of g)try{r(y),d.emit(null,{internal:!0})}catch(b){d.emit(b,{internal:!0})}s.set(m,p.length)}}},{name:e,describeKind:"effect",meta:{...Fo("saga",{saga_name:e,source_events:n}),error:null}});return i.n=a,this.add(a,{name:e}),this._keepaliveDisposers.push(se(a)),this._sagas.add(e),a}useEventStore(e){this._eventStore=e}async rebuildProjection(e,n,r){if(!this._eventStore)throw new Error("No event store wired. Call useEventStore() first.");let o=[];for(let s of e){let i=await this._eventStore.loadEvents(s);o.push(...i.events)}return o.sort((s,i)=>s.timestampNs-i.timestampNs||s.seq-i.seq),n(r,o)}};function Pi(t,e){return new $o(t,e)}var Gi=class{constructor(e){this.graph=e}onModuleDestroy(){this.graph.destroy()}},Fi=class{graph=new q("request");onModuleDestroy(){this.graph.destroy()}},Ec,Di;Ec=[(0,Nr.Module)({})];var Gt=class Gt{static forRoot(e){let n=e??{},r=n.name??"root",o=[{provide:Xe,useFactory:()=>{let s=new q(r);return n.build&&n.build(s),n.snapshot&&s.restore(n.snapshot),s}},{provide:Symbol.for("graphrefly:root-lifecycle"),useFactory:s=>new Gi(s),inject:[Xe]},{provide:on,useFactory:(s,i)=>new on(s,i),inject:[Xe,_c.ModuleRef]}];if(n.nodes)for(let s of n.nodes)o.push({provide:ot(s),useFactory:i=>i.resolve(s),inject:[Xe]});return n.requestScope&&o.push({provide:Symbol.for("graphrefly:request-lifecycle"),useFactory:()=>new Fi,scope:Nr.Scope.REQUEST},{provide:Zt,useFactory:s=>s.graph,inject:[Symbol.for("graphrefly:request-lifecycle")],scope:Nr.Scope.REQUEST}),{module:Gt,global:!0,providers:o,exports:[Xe,...(n.nodes??[]).map(ot),...n.requestScope?[Zt]:[]]}}static forFeature(e){let n=[{provide:Ye(e.name),useFactory:r=>{let o=new q(e.name);return e.build&&e.build(o),e.snapshot&&o.restore(e.snapshot),r.mount(e.name,o),o},inject:[Xe]}];if(e.nodes)for(let r of e.nodes)n.push({provide:ot(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[Ye(e.name)]});return{module:Gt,providers:n,exports:[Ye(e.name),...(e.nodes??[]).map(r=>ot(`${e.name}::${r}`))]}}static forCqrs(e){let n=[{provide:Ye(e.name),useFactory:r=>{let o=Pi(e.name,e.cqrs);return e.eventStore&&o.useEventStore(e.eventStore),e.build&&e.build(o),r.mount(e.name,o),o},inject:[Xe]}];if(e.nodes)for(let r of e.nodes)n.push({provide:ot(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[Ye(e.name)]});return{module:Gt,providers:n,exports:[Ye(e.name),...(e.nodes??[]).map(r=>ot(`${e.name}::${r}`))]}}};Di=pu(null),Gt=hu(Di,0,"GraphReflyModule",Ec,Gt),mu(Di,1,Gt);var jo=Gt;var Ko={};he(Ko,{useStore:()=>am,useSubscribe:()=>Mc,useSubscribeRecord:()=>um});var xt=require("react");ie();function Mc(t){return(0,xt.useSyncExternalStore)(e=>{let n=!1,r=t.subscribe(()=>{n||e()});return()=>{n=!0,r()}},()=>t.cache,()=>t.cache)}function am(t){let e=Mc(t),n=(0,xt.useCallback)(r=>{t.down([[ee],[S,r]])},[t]);return[e,n]}function um(t,e){let n=(0,xt.useRef)(e);n.current=e;let r=(0,xt.useMemo)(()=>{let o=()=>{let i={},a=t.cache??[];for(let u of a){let c=n.current(u),d={};for(let l of Object.keys(c))d[l]=c[l].cache;i[u]=d}return i},s=o();return{subscribe:i=>{let a=!1,u=[],c=()=>{for(let f of u)f();u=[]},d=f=>{c();for(let p of f){let m=n.current(p);for(let h of Object.keys(m)){let g=m[h].subscribe(()=>{s=o(),a||i()});u.push(g)}}s=o(),a||i()},l=t.subscribe(f=>{let p=f.some(m=>m[0]===S||m[0]===B);!a&&p&&d(t.cache??[])});return d(t.cache??[]),()=>{a=!0,l(),c()}},getSnapshot:()=>s}},[t]);return(0,xt.useSyncExternalStore)(r.subscribe,r.getSnapshot,r.getSnapshot)}var Wo={};he(Wo,{Signal:()=>cm});Ne();ie();oe();var qn=[];function Ho(t){let e=t.cache;return t.subscribe(r=>{for(let[o,s]of r)o===S&&(e=s)})(),e}var $i=class{_node;_equals;constructor(e,n){this._equals=n?.equals??Object.is,this._node=N(e,{...n,resubscribable:!0,resetOnTeardown:!0})}get(){let e=qn[qn.length-1];return e?(this._node.status==="sentinel"&&Ho(this._node),e(this._node)):this._node.status==="sentinel"?Ho(this._node):this._node.cache}set(e){this._equals(this.get(),e)||te(()=>{this._node.down([[ee],[S,e]])})}},Bi=class{_node;constructor(e,n){this._node=Xt(r=>{qn.push(r);try{return e()}finally{qn.pop()}},{...n,describeKind:"derived",resubscribable:!0,resetOnTeardown:!0})}get(){let e=qn[qn.length-1];return e?(this._node.status==="sentinel"&&Ho(this._node),e(this._node)):this._node.status==="sentinel"?Ho(this._node):this._node.cache}},cm={State:$i,Computed:Bi,sub:(t,e)=>{let n=typeof e=="function"?{data:e,error:void 0,complete:void 0}:e,r=!0;return t._node.subscribe(o=>{for(let[s,i]of o){if(s===S){if(r){r=!1;continue}n.data?.(i)}s===M&&n.error?.(i),s===_&&n.complete?.()}})}};var qo={};he(qo,{useStore:()=>dm,useSubscribe:()=>Oc,useSubscribeRecord:()=>lm});var Rt=require("solid-js");ie();function Oc(t){let[e,n]=(0,Rt.createSignal)(t.cache,{equals:!1}),r=t.subscribe(()=>{n(()=>t.cache)});return(0,Rt.getOwner)()?(0,Rt.onCleanup)(()=>r()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Solid reactive owner \u2014 subscription will not be auto-disposed."),e}function dm(t){return[Oc(t),r=>{t.down([[ee],[S,r]])}]}function lm(t,e){let[n,r]=(0,Rt.createSignal)({},{equals:!1}),o=[],s=()=>{for(let c of o)c();o=[]},i=()=>{let c={};for(let d of t.cache??[]){let l=e(d),f={};for(let p of Object.keys(l))f[p]=l[p].cache;c[d]=f}return c},a=c=>{s();for(let d of c){let l=e(d);for(let f of Object.keys(l)){let p=l[f].subscribe(()=>{r(()=>i())});o.push(p)}}r(()=>i())},u=t.subscribe(c=>{c.some(d=>d[0]===S||d[0]===B)&&a(t.cache??[])});return a(t.cache??[]),(0,Rt.getOwner)()?(0,Rt.onCleanup)(()=>{u(),s()}):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribeRecord called outside a Solid reactive owner \u2014 subscription will not be auto-disposed."),n}var Uo={};he(Uo,{useStore:()=>fm,useSubscribe:()=>pm,useSubscribeRecord:()=>mm});ie();function pm(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n}}}function fm(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n},set(e){t.down([[ee],[S,e]])},update(e){let n=e(t.cache);t.down([[ee],[S,n]])}}}function mm(t,e){return{subscribe(n){let r=[],o=()=>{for(let u of r)u();r=[]},s=()=>{let u={};for(let c of t.cache??[]){let d=e(c),l={};for(let f of Object.keys(d))l[f]=d[f].cache;u[c]=l}return u},i=u=>{o();for(let c of u){let d=e(c);for(let l of Object.keys(d)){let f=d[l].subscribe(()=>{n(s())});r.push(f)}}n(s())},a=t.subscribe(u=>{u.some(c=>c[0]===S||c[0]===B)&&i(t.cache??[])});return i(t.cache??[]),()=>{a(),o()}}}}var zo={};he(zo,{useStore:()=>gm,useSubscribe:()=>hm,useSubscribeRecord:()=>ym});var Pe=require("vue");ie();function hm(t){let e=(0,Pe.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,Pe.getCurrentScope)()?(0,Pe.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Pe.readonly)(e)}function gm(t){let e=(0,Pe.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,Pe.getCurrentScope)()?(0,Pe.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useStore called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Pe.computed)({get:()=>e.value,set:r=>{t.down([[ee],[S,r]])}})}function ym(t,e){let n=(0,Pe.shallowRef)({}),r=new Map;function o(){let a={};for(let[u,c]of r)a[u]={...c.values};n.value=a}function s(a){for(let c of r.values())for(let d of c.subs)d();r.clear();for(let c of a){let d=e(c),l=Object.keys(d),f={},p=[];for(let m of l){let h=d[m];f[m]=h.cache;let g=h.subscribe(()=>{f[m]=h.cache,o()});p.push(g)}r.set(c,{subs:p,values:f})}let u={};for(let[c,d]of r)u[c]={...d.values};n.value=u}return(0,Pe.watch)(()=>[...(typeof t=="function"?t():(0,Pe.isRef)(t)?t.value:t)??[]],a=>s(a??[]),{immediate:!0}),(0,Pe.getCurrentScope)()?(0,Pe.onScopeDispose)(()=>{for(let a of r.values())for(let u of a.subs)u();r.clear()}):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribeRecord called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Pe.readonly)(n)}var Jo={};he(Jo,{create:()=>vm});ie();oe();var bm=()=>!1;function vm(t){let e=new q("zustand"),n=N(void 0,{name:"state",equals:bm});e.add(n,{name:"state"});let r=()=>n.cache,o=(a,u)=>{let c=n.cache,d=typeof a=="function"?a(c):a;n.emit(u?d:{...c,...d})},s={getState:r,setState:o,getInitialState:()=>i,subscribe:a=>{let u=!0,c=n.cache;return n.subscribe(d=>{for(let[l,f]of d)if(l===S){if(u){u=!1;continue}a(f,c),c=f}})},destroy:e.destroy.bind(e)},i=t(o,r,s);return n.emit(i),Object.assign(e,s)}var na={};he(na,{CircuitOpenError:()=>st,NS_PER_MS:()=>Fe,NS_PER_SEC:()=>Qe,NativeIndexBackend:()=>Ir,NativeListBackend:()=>Pr,NativeLogBackend:()=>Rr,NativeMapBackend:()=>Cr,NativePubSubBackend:()=>Lr,RateLimiterOverflowError:()=>tn,ResettableTimer:()=>_e,TimeoutError:()=>nn,audit:()=>Qc,awaitSettled:()=>So,buffer:()=>Xc,bufferCount:()=>Zc,bufferTime:()=>td,cached:()=>Qu,cascadingCache:()=>cl,catchError:()=>ld,checkpointToRedis:()=>tl,checkpointToS3:()=>el,circuitBreaker:()=>ft,combine:()=>Ki,combineLatest:()=>ud,concat:()=>Hc,concatMap:()=>Uc,constant:()=>ho,createTransport:()=>$t,createWatermarkController:()=>Hn,csvRows:()=>Dd,debounce:()=>Wi,debounceTime:()=>cd,decorrelatedJitter:()=>vo,delay:()=>Jc,deserializeError:()=>fn,dictStorage:()=>vl,distill:()=>Zo,distinctUntilChanged:()=>jc,elementAt:()=>$c,empty:()=>qu,escapeRegexChar:()=>vi,exhaustMap:()=>qc,exponential:()=>yo,externalBundle:()=>Yo,externalProducer:()=>cn,fallback:()=>jn,fibonacci:()=>bo,filter:()=>ut,find:()=>Fc,first:()=>Qo,firstValueFrom:()=>Kn,firstWhere:()=>wo,flatMap:()=>zc,forEach:()=>Pt,fromAny:()=>re,fromAsyncIter:()=>wi,fromCSV:()=>Pd,fromClickHouseWatch:()=>Bd,fromCron:()=>ko,fromDrizzle:()=>il,fromEvent:()=>Wu,fromHTTP:()=>Yi,fromHTTPPoll:()=>wd,fromHTTPStream:()=>Td,fromIter:()=>xo,fromKafka:()=>Cd,fromKysely:()=>al,fromMCP:()=>Rd,fromNATS:()=>Kd,fromNDJSON:()=>$d,fromOTel:()=>Sd,fromPrisma:()=>sl,fromPrometheus:()=>Od,fromPromise:()=>Ti,fromPulsar:()=>jd,fromRabbitMQ:()=>Wd,fromRaf:()=>Hu,fromRedisStream:()=>Ld,fromSSE:()=>vd,fromSqlite:()=>nl,fromSqliteCursor:()=>rl,fromStatsD:()=>_d,fromSyslog:()=>Nd,fromTimer:()=>et,fromWebSocket:()=>Ji,fromWebSocketReconnect:()=>xd,fromWebhook:()=>pd,globToRegExp:()=>Vu,interval:()=>od,keepalive:()=>se,last:()=>Gc,linear:()=>go,lru:()=>Zi,map:()=>Er,matchesAnyPattern:()=>Ku,matchesCron:()=>mo,memoryStorage:()=>Gr,merge:()=>mt,mergeMap:()=>Hi,nameToSignal:()=>ln,ndjsonRows:()=>Gd,never:()=>Uu,of:()=>ki,pairwise:()=>Vc,parseCron:()=>fo,parsePrometheusText:()=>Qi,parseStatsD:()=>Md,parseSyslog:()=>Ed,pausable:()=>id,pubsub:()=>fl,race:()=>Wc,rateLimiter:()=>Bn,reactiveCounter:()=>xi,reactiveIndex:()=>gl,reactiveList:()=>es,reactiveLog:()=>Ve,reactiveMap:()=>tt,reactiveSink:()=>$e,reduce:()=>Ic,repeat:()=>sd,replay:()=>Ro,rescue:()=>Mr,resolveBackoffPreset:()=>Ct,retry:()=>Fn,retrySource:()=>At,sample:()=>Yc,scan:()=>Lc,serializeError:()=>pn,share:()=>Yu,shareReplay:()=>Xu,signalToName:()=>Ft,singleFromAny:()=>ts,singleNodeFromAny:()=>yl,skip:()=>Vi,sortJsonValue:()=>Dr,stableJsonString:()=>bl,stratify:()=>Fr,switchMap:()=>be,take:()=>_r,takeUntil:()=>Dc,takeWhile:()=>Pc,tap:()=>Bc,throttle:()=>qi,throttleTime:()=>dd,throwError:()=>zu,timeout:()=>Vn,toArray:()=>Ju,toCSV:()=>Ud,toClickHouse:()=>zd,toFile:()=>Xi,toHTTP:()=>fd,toKafka:()=>Ad,toLoki:()=>Xd,toMongo:()=>Qd,toNATS:()=>Hd,toObservable:()=>po,toPostgres:()=>Yd,toPulsar:()=>Vd,toRabbitMQ:()=>qd,toReadableStream:()=>bd,toRedisStream:()=>Id,toS3:()=>Jd,toSSE:()=>gd,toSSEBytes:()=>yd,toSqlite:()=>ol,toTempo:()=>Zd,toWebSocket:()=>kd,tokenBucket:()=>Lt,valve:()=>ad,verifiable:()=>pl,window:()=>rd,windowCount:()=>ed,windowTime:()=>nd,withBreaker:()=>$n,withLatestFrom:()=>dn,withMaxAttempts:()=>yi,withStatus:()=>It,workerBridge:()=>ea,workerSelf:()=>ta,zip:()=>Kc});Ne();ke();ie();xe();oe();Ne();ie();oe();function Cc(t){return{describeKind:"producer",...t}}function cn(t,e){return W(n=>{let r=!0,o={emit(i){r&&n.emit(i)},error(i){r&&(r=!1,n.down([[M,i]]))},complete(){r&&(r=!1,n.down([[_]]))}},s;try{let i=t(o);s=typeof i=="function"?i:void 0}catch(i){return o.error(i),()=>{r=!1}}return()=>{r=!1;try{s?.()}catch{}}},Cc(e))}function Yo(t,e,n){let r=!0,o,s=0,i=0,a={},u=[],c=()=>{let p=o;o=void 0;try{p?.()}catch{}};for(let p of e){let m=n?.name?`${n.name}::${p}`:p,h=n?.channelOpts?.[p],g=W(y=>(s++,()=>{i++,s>0&&i>=s&&i>=e.length&&c()}),Cc({...h,name:m}));a[p]=g,u.push(g)}let d={};for(let p of e)d[p]=m=>{r&&a[p].down([[S,m]])};d.error=p=>{r&&(r=!1,te(()=>{for(let m of u)m.down([[M,p]])}),c())},d.complete=()=>{r&&(r=!1,te(()=>{for(let p of u)p.down([[_]])}),c())};let l=t(d);return o=typeof l=="function"?l:void 0,Object.assign(a,{dispose:()=>{r&&(r=!1,te(()=>{for(let p of u)try{p.down([[_]])}catch{}}),c())}})}ke();ie();xe();oe();Re();function ce(t){return{describeKind:"derived",...t}}function Ac(t){return{describeKind:"derived",partial:!0,...t}}function Er(t,e,n){return K([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[B]]);return}for(let i of s)o.emit(e(i))},ce(n))}function ut(t,e,n){return K([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[B]]);return}let i=!1;for(let a of s)e(a)&&(o.emit(a),i=!0);i||o.down([[B]])},ce(n))}function Lc(t,e,n,r){return K([t],(o,s,i)=>{"acc"in i.store||(i.store.acc=n);let a=o[0];if(a==null||a.length===0){s.down([[B]]);return}for(let u of a)i.store.acc=e(i.store.acc,u),s.emit(i.store.acc)},{...ce(r),initial:n,resetOnTeardown:!0})}function Ic(t,e,n,r){return K([t],(o,s,i)=>{if("acc"in i.store||(i.store.acc=n),i.terminalDeps[0]===!0){s.emit(i.store.acc),s.down([[_]]);return}let a=o[0];if(a==null||a.length===0){s.down([[B]]);return}for(let u of a)i.store.acc=e(i.store.acc,u)},{...ce(r),completeWhenDepsComplete:!1})}function _r(t,e,n){return e<=0?K([t],(r,o,s)=>{s.store.completed||(s.store.completed=!0,o.down([[_]]))},{...ce(n),completeWhenDepsComplete:!1}):K([t],(r,o,s)=>{if("taken"in s.store||(s.store.taken=0),s.store.done){o.down([[B]]);return}if(s.terminalDeps[0]===!0){s.store.done=!0,o.down([[_]]);return}let i=r[0];if(i==null||i.length===0){o.down([[B]]);return}for(let a of i)if(s.store.taken++,o.emit(a),s.store.taken>=e){s.store.done=!0,o.down([[_]]);return}},{...ce(n),completeWhenDepsComplete:!1})}function Vi(t,e,n){return K([t],(r,o,s)=>{"skipped"in s.store||(s.store.skipped=0);let i=r[0];if(i==null||i.length===0){o.down([[B]]);return}let a=!1;for(let u of i)s.store.skipped++,s.store.skipped<=e||(o.emit(u),a=!0);a||o.down([[B]])},ce(n))}function Pc(t,e,n){return K([t],(r,o,s)=>{if(s.store.done){o.down([[B]]);return}let i=r[0];if(i==null||i.length===0){o.down([[B]]);return}for(let a of i){if(!e(a)){s.store.done=!0,o.down([[_]]);return}o.emit(a)}},{...ce(n),completeWhenDepsComplete:!1})}function Dc(t,e,n){let r=n?.predicate??(i=>i[0]===S),{predicate:o,...s}=n??{};return W(i=>{let a=!1,u=t.subscribe(d=>{if(!a)for(let l of d){if(a)return;l[0]===S?i.emit(l[1]):(l[0]===_||l[0]===M)&&(a=!0,i.down([l]))}}),c=e.subscribe(d=>{if(!a)for(let l of d){if(a)return;if(r(l)){a=!0,i.down([[_]]);return}}});return()=>{u(),c()}},ce(s))}function Qo(t,e){return _r(t,1,e)}function Gc(t,e){let{defaultValue:n,...r}=e??{},o=e!=null&&Object.hasOwn(e,"defaultValue");return K([t],(s,i,a)=>{if(a.terminalDeps[0]===!0){a.store.has?i.emit(a.store.latest):o&&i.emit(n),i.down([[_]]);return}let u=s[0];if(u==null||u.length===0){i.down([[B]]);return}a.store.latest=u.at(-1),a.store.has=!0},{...ce(r),completeWhenDepsComplete:!1})}function Fc(t,e,n){return _r(ut(t,e,n),1,n)}function $c(t,e,n){return _r(Vi(t,e,n),1,n)}function Bc(t,e,n){if(typeof e=="function")return K([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[B]]);return}for(let a of i)e(a),s.emit(a)},ce(n));let r=e;return K([t],(o,s,i)=>{if(i.terminalDeps[0]!==void 0){i.terminalDeps[0]===!0?(r.complete?.(),s.down([[_]])):(r.error?.(i.terminalDeps[0]),s.down([[M,i.terminalDeps[0]]]));return}let a=o[0];if(a==null||a.length===0){s.down([[B]]);return}for(let u of a)r.data?.(u),s.emit(u)},{...ce(n),completeWhenDepsComplete:!1})}function jc(t,e=Object.is,n){return K([t],(r,o,s)=>{let i=r[0];if(i==null||i.length===0){o.down([[B]]);return}let a=!1;for(let u of i)s.store.hasPrev&&e(s.store.prev,u)||(s.store.prev=u,s.store.hasPrev=!0,o.emit(u),a=!0);a||o.down([[B]])},ce(n))}function Vc(t,e){return K([t],(n,r,o)=>{let s=n[0];if(s==null||s.length===0){r.down([[B]]);return}let i=!1;for(let a of s)if(!o.store.hasPrev)o.store.prev=a,o.store.hasPrev=!0;else{let u=[o.store.prev,a];o.store.prev=a,r.emit(u),i=!0}i||r.down([[B]])},ce(e))}function Ki(...t){let e=[...t];return O(e,n=>n,{...ce(),equals:(n,r)=>{if(n.length!==r.length)return!1;for(let o=0;o<n.length;o++)if(!Object.is(n[o],r[o]))return!1;return!0}})}function dn(t,e,n){return K([t,e],(r,o,s)=>{let i=r[0],a=r[1],u=a!=null&&a.length>0?a.at(-1):s.prevData[1];if(i!=null&&i.length>0){if(!(a!=null&&a.length>0)&&s.prevData[1]===void 0){o.down([[B]]);return}for(let c of i)o.emit([c,u])}else o.down([[B]])},Ac(n))}function mt(...t){return t.length===0?W(e=>{e.down([[_]])},ce()):W(e=>{let n=t.length,r=0,o=[];for(let s of t){let i=s.subscribe(a=>{for(let u of a)u[0]===S?e.emit(u[1]):u[0]===_?(r+=1,r>=n&&e.down([[_]])):u[0]===M&&e.down([u])});o.push(i)}return()=>{for(let s of o)s()}},ce())}function Kc(...t){let e=t.length;return e===0?W(n=>{n.emit([]),n.down([[_]])},ce()):W(n=>{let r=Array.from({length:e},()=>[]),o=e;function s(){for(;r.every(a=>a.length>0);){let a=r.map(u=>u.shift());n.emit(a)}}let i=[];for(let a=0;a<e;a++){let u=a,c=t[a].subscribe(d=>{for(let l of d)l[0]===S?(r[u].push(l[1]),s()):l[0]===_?(o-=1,(o===0||r[u].length===0)&&n.down([[_]])):l[0]===M&&n.down([l])});i.push(c)}return()=>{for(let a of i)a()}},ce())}function Hc(t,e,n){return W(r=>{let o=0,s=[],i,a;return a=e.subscribe(u=>{for(let c of u)o===0?c[0]===S?s.push(c[1]):c[0]===M&&r.down([c]):c[0]===S?r.emit(c[1]):(c[0]===_||c[0]===M)&&r.down([c])}),i=t.subscribe(u=>{for(let c of u)if(o===0)if(c[0]===S)r.emit(c[1]);else if(c[0]===_){o=1;for(let d of s)r.emit(d);s.length=0}else c[0]===M&&r.down([c])}),()=>{i?.(),a?.()}},ce(n))}function Wc(...t){return t.length===0?W(e=>{e.down([[_]])},ce()):t.length===1?K([t[0]],(e,n)=>{let r=e[0];if(r==null||r.length===0){n.down([[B]]);return}for(let o of r)n.emit(o)},ce()):W(e=>{let n=null,r=[];for(let o=0;o<t.length;o++){let s=o,i=t[o].subscribe(a=>{for(let u of a){if(n!==null&&s!==n)return;u[0]===S?(n===null&&(n=s),e.emit(u[1])):(u[0]===_||u[0]===M)&&(n===null||s===n)&&e.down([u])}});r.push(i)}return()=>{for(let o of r)o()}},ce())}function Xo(t,e,n){let r,o=!1,s=()=>{o||(o=!0,n())};return r=t.subscribe(i=>{let a=!1,u=!1;for(let c of i)c[0]!==dt&&(c[0]===S?e.emit(c[1]):c[0]===_?a=!0:c[0]===M?(u=!0,e.down([c])):(c[0]===ee||c[0]===B)&&e.down([c]));u?(r?.(),r=void 0,s()):a&&s()}),()=>{r?.(),r=void 0}}function be(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return K([t],(i,a,u)=>{if(u.terminalDeps[0]!=null&&u.terminalDeps[0]!==!0){s();return}if(u.terminalDeps[0]===!0){o=!0,r||a.down([[_]]);return}let c=i[0];if(!(c==null||c.length===0))return s(),r=Xo(re(e(c[c.length-1])),a,()=>{s(),o&&a.down([[_]])}),{deactivate:()=>{s(),o=!1}}},{...ce(n),completeWhenDepsComplete:!1})}function qc(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return K([t],(i,a,u)=>{if(u.terminalDeps[0]!=null&&u.terminalDeps[0]!==!0){s();return}if(u.terminalDeps[0]===!0){o=!0,r||a.down([[_]]);return}let c=i[0];if(!(c==null||c.length===0))return r===void 0?r=Xo(re(e(c[0])),a,()=>{s(),o&&a.down([[_]])}):a.down([[B]]),{deactivate:()=>{s(),o=!1}}},{...ce(n),completeWhenDepsComplete:!1})}function Uc(t,e,n){let{maxBuffer:r,...o}=n??{},s=[],i,a=!1,u;function c(){i?.(),i=void 0}function d(){if(!u||i!==void 0)return;if(s.length===0){a&&u.down([[_]]);return}let f=s.shift();i=Xo(re(e(f)),u,()=>{c(),d()})}function l(f){r&&r>0&&s.length>=r&&s.shift(),s.push(f),d()}return K([t],(f,p,m)=>{if(u=p,m.terminalDeps[0]!=null&&m.terminalDeps[0]!==!0){c(),s.length=0;return}if(m.terminalDeps[0]===!0){a=!0,d();return}let h=f[0];if(!(h==null||h.length===0)){for(let g of h)l(g);return{deactivate:()=>{c(),s.length=0,a=!1}}}},{...ce(o),completeWhenDepsComplete:!1})}function Hi(t,e,n){let{concurrent:r,...o}=n??{},s=r!=null&&r>0?r:Number.POSITIVE_INFINITY,i=0,a=!1,u=new Set,c=[],d;function l(){a&&i===0&&c.length===0&&d&&d.down([[_]])}function f(g){if(!d)return;i++;let y;y=Xo(re(e(g)),d,()=>{y&&u.delete(y),i--,p(),l()}),u.add(y)}function p(){for(;c.length>0&&i<s;)f(c.shift())}function m(g){i<s?f(g):c.push(g)}function h(){for(let g of u)g();u.clear(),i=0,c.length=0}return K([t],(g,y,b)=>{if(d=y,b.terminalDeps[0]!=null&&b.terminalDeps[0]!==!0){h();return}if(b.terminalDeps[0]===!0){a=!0,l();return}let v=g[0];if(!(v==null||v.length===0)){for(let T of v)m(T);return{deactivate:()=>{h(),a=!1}}}},{...ce(o),completeWhenDepsComplete:!1})}var zc=Hi;function Jc(t,e,n){return W(r=>{let o=new Set;function s(){for(let a of o)clearTimeout(a);o.clear()}let i=t.subscribe(a=>{for(let u of a)if(u[0]===S){let c=setTimeout(()=>{o.delete(c),r.emit(u[1])},e);o.add(c)}else if(u[0]===_){let c=setTimeout(()=>{o.delete(c),r.down([[_]])},e);o.add(c)}else u[0]===M&&(s(),r.down([u]))});return()=>{i(),s()}},ce(n))}function Wi(t,e,n){return W(r=>{let o,s;function i(){o!==void 0&&(clearTimeout(o),o=void 0)}let a=t.subscribe(u=>{for(let c of u)c[0]===S?(i(),s=c[1],o=setTimeout(()=>{o=void 0,r.emit(s)},e)):c[0]===_?(o!==void 0&&(i(),r.emit(s)),r.down([[_]])):c[0]===M&&(i(),r.down([c]))});return()=>{a(),i()}},ce(n))}function qi(t,e,n){let{leading:r,trailing:o,...s}=n??{},i=r!==!1,a=o===!0,u=e*1e6;return W(c=>{let d,l=-1/0,f,p=!1;function m(){d!==void 0&&(clearTimeout(d),d=void 0)}let h=t.subscribe(g=>{for(let y of g)if(y[0]===S){let b=y[1],v=$();if(i&&v-l>=u)l=v,c.emit(b),m(),a&&(d=setTimeout(()=>{d=void 0,p&&(l=$(),c.emit(f),p=!1)},e));else if(a&&(f=b,p=!0,d===void 0)){let T=(v-l)/1e6;d=setTimeout(()=>{d=void 0,p&&(l=$(),c.emit(f),p=!1)},Math.max(0,e-T))}}else(y[0]===_||y[0]===M)&&(m(),c.down([y]))});return()=>{h(),m()}},ce(s))}function Yc(t,e,n){return W(r=>{let o,s=!1,i=!1,a=t.subscribe(c=>{if(!s)for(let d of c){if(s)return;d[0]===S?o={v:d[1]}:d[0]===M?(s=!0,r.down([d])):d[0]===_&&(i=!0,o=void 0)}}),u=e.subscribe(c=>{if(!s)for(let d of c){if(s)return;d[0]===S?o!==void 0&&!i&&r.emit(o.v):d[0]===M?(s=!0,r.down([d])):d[0]===_&&(s=!0,r.down([[_]]))}});return()=>{a(),u()}},ce(n))}function Qc(t,e,n){return W(r=>{let o,s,i=!1;function a(){o!==void 0&&(clearTimeout(o),o=void 0)}let u=t.subscribe(c=>{for(let d of c)d[0]===S?(s=d[1],i=!0,a(),o=setTimeout(()=>{o=void 0,i&&(i=!1,r.emit(s))},e)):(d[0]===_||d[0]===M)&&(a(),r.down([d]))});return()=>{u(),a()}},ce(n))}function Xc(t,e,n){return W(r=>{let o=[],s=t.subscribe(a=>{for(let u of a)u[0]===S?o.push(u[1]):u[0]===_?(o.length>0&&r.emit([...o]),o.length=0,r.down([[_]])):u[0]===M&&r.down([u])}),i=e.subscribe(a=>{for(let u of a)u[0]===S?o.length>0&&(r.emit([...o]),o.length=0):u[0]===_?r.down([[_]]):u[0]===M&&r.down([u])});return()=>{s(),i(),o.length=0}},ce(n))}function Zc(t,e,n){if(e<=0)throw new RangeError("bufferCount expects count > 0");return W(r=>{let o=[],s=t.subscribe(i=>{for(let a of i)a[0]===S?(o.push(a[1]),o.length>=e&&r.emit(o.splice(0,o.length))):a[0]===_?(o.length>0&&r.emit([...o]),o.length=0,r.down([[_]])):a[0]===M&&r.down([a])});return()=>{s(),o.length=0}},ce(n))}function ed(t,e,n){if(e<=0)throw new RangeError("windowCount expects count > 0");return W(r=>{let o,s=0;function i(){let u=W(c=>(o=c.down.bind(c),()=>{o=void 0}),ce());s=0,r.emit(u)}let a=t.subscribe(u=>{for(let c of u)c[0]===S?(o||i(),o?.([[S,c[1]]]),s+=1,s>=e&&(o?.([[_]]),o=void 0)):c[0]===_?(o?.([[_]]),o=void 0,r.down([[_]])):c[0]===M&&(o?.([c]),o=void 0,r.down([c]))});return()=>{a(),o?.([[_]]),o=void 0}},ce(n))}function td(t,e,n){return W(r=>{let o=[],s=setInterval(()=>{o.length>0&&(r.emit([...o]),o.length=0)},e),i=t.subscribe(a=>{for(let u of a)u[0]===S?o.push(u[1]):u[0]===_?(clearInterval(s),o.length>0&&r.emit([...o]),o.length=0,r.down([[_]])):u[0]===M&&(clearInterval(s),r.down([u]))});return()=>{i(),clearInterval(s),o.length=0}},ce(n))}function nd(t,e,n){return W(r=>{let o;function s(){o?.([[_]]),o=void 0}function i(){let c=W(d=>(o=d.down.bind(d),()=>{o=void 0}),ce());r.emit(c)}i();let a=setInterval(()=>{s(),i()},e),u=t.subscribe(c=>{for(let d of c)d[0]===S?o?.([[S,d[1]]]):d[0]===_?(clearInterval(a),s(),r.down([[_]])):d[0]===M&&(clearInterval(a),o?.([d]),s(),r.down([d]))});return()=>{u(),clearInterval(a),s()}},ce(n))}function rd(t,e,n){return W(r=>{let o;function s(){o?.([[_]]),o=void 0}function i(){let c=W(d=>(o=d.down.bind(d),()=>{o=void 0}),ce());r.emit(c)}let a=t.subscribe(c=>{for(let d of c)d[0]===S?(o||i(),o?.([[S,d[1]]])):d[0]===_?(s(),r.down([[_]])):d[0]===M&&(o?.([d]),o=void 0,r.down([d]))}),u=e.subscribe(c=>{for(let d of c)d[0]===S&&(s(),i())});return()=>{a(),u(),s()}},ce(n))}function od(t,e){return W((n,r)=>{"n"in r.store||(r.store.n=0);let o=setInterval(()=>{n.emit(r.store.n),r.store.n=r.store.n+1},t);return()=>clearInterval(o)},ce(e))}function sd(t,e,n){if(e<=0)throw new RangeError("repeat expects count > 0");return W(r=>{let o=e,s,i=()=>{s?.(),s=t.subscribe(a=>{let u=!1,c=[];for(let d of a)d[0]===_?u=!0:c.push(d);c.length>0&&r.down(c),u&&(s?.(),s=void 0,o-=1,o>0?i():r.down([[_]]))})};return i(),()=>{s?.()}},ce(n))}function id(t,e){return K([t],(n,r)=>{let o=n[0];if(o==null||o.length===0){r.down([[B]]);return}for(let s of o)r.emit(s)},ce(e))}function Mr(t,e,n){return W(r=>{let o=t.subscribe(s=>{for(let i of s)if(i[0]===S)r.emit(i[1]);else if(i[0]===M)try{r.emit(e(i[1]))}catch(a){r.down([[M,a]])}else i[0]===_&&r.down([[_]])});return()=>{o()}},ce(n))}function ad(t,e,n){return K([t,e],(r,o,s)=>{let i=r[1];if(!(i!=null&&i.length>0?i.at(-1):s.prevData[1])){o.down([[B]]);return}let u=r[0];if(u!=null&&u.length>0){for(let c of u)o.emit(c);return}if(i!=null&&i.length>0&&s.prevData[0]!==void 0){o.emit(s.prevData[0]);return}o.down([[B]])},Ac(n))}var ud=Ki,cd=Wi,dd=qi,ld=Mr;ie();xe();oe();Gn();var Ui=class{ring;arr;constructor(e){e===Number.POSITIVE_INFINITY||e<=0?(this.arr=[],this.ring=null):(this.ring=new sn(e),this.arr=null)}get length(){return this.ring!=null?this.ring.size:this.arr.length}push(e){this.ring!=null?this.ring.push(e):this.arr.push(e)}shift(){return this.ring!=null?this.ring.shift():this.arr.shift()}drain(){if(this.ring!=null){let n=this.ring.toArray();return this.ring.clear(),n}let e=this.arr;return this.arr=[],e}};function Or(t){return t instanceof Error?t:new Error(String(t))}function Tm(t){return t===void 0?null:typeof t=="string"?Ct(t):t}function $e(t,e){let{name:n,onTransportError:r,retry:o,backpressure:s,batchSize:i=Number.POSITIVE_INFINITY,flushIntervalMs:a=0,serialize:u,stopOn:c,onUpstreamMessage:d,onDispose:l,send:f,sendBatch:p,ctx:m}=e;if(!f&&!p)throw new Error("reactiveSink: `send` or `sendBatch` must be provided");let h=m,g=Math.max(1,o?.maxAttempts??1),y=Tm(o?.backoff??(g>1?"exponential":void 0)),b=o?.shouldRetry??(()=>!0),v=p!==void 0||i<Number.POSITIVE_INFINITY||a>0,T=Z=>n?`${n}::${Z}`:void 0,w=N(void 0,{equals:()=>!1,name:T("sent")}),k=N(null,{name:T("failed")}),x=N(0,{name:T("inFlight")}),R=N(null,{name:T("errors")}),E=v?N(0,{name:T("buffered")}):void 0,G=s?N(!1,{name:T("paused")}):void 0,L=0,P=Z=>{L+=Z,x.down([[S,L]])},C=Z=>{try{r?.(Z)}catch{}try{R.down([[S,Z]])}catch{}},V=new Set,ne=Z=>{V.add(Z);let ue=()=>V.delete(Z);Z.then(ue,ue)},F=(Z,ue,me)=>{let Se=y?y(ue-1,me,null):0,De=Se==null?0:typeof Se=="number"&&Se>0?Se:0,qe=Math.max(1,Math.ceil(De/1e6));return new Promise(Te=>{setTimeout(()=>Te(Z()),qe)})},A=Z=>Z!=null&&typeof Z=="object"&&typeof Z.then=="function",D=Z=>{let ue;try{ue=u?u(Z):Z}catch(Te){let ye=Or(Te);return C({stage:"serialize",error:ye,value:Z}),k.down([[S,{value:Z,error:ye,attempts:0}]]),Promise.resolve()}let me=0,Se=Te=>{P(-1);let ye=Or(Te);if(C({stage:"send",error:ye,value:Z,attempt:me}),!(me<g&&b(ye,me))){k.down([[S,{value:Z,error:ye,attempts:me}]]);return}return F(qe,me,ye)},De=()=>{P(-1),w.down([[S,Z]])};function qe(){me+=1,P(1);let Te;try{Te=f(ue,h)}catch(ye){return Se(ye)??Promise.resolve()}return A(Te)?Te.then(De,ye=>Se(ye)):(De(),Promise.resolve())}return qe()},I=s?.maxBuffer??Number.POSITIVE_INFINITY,Q=new Ui(I),U,ae=!1,j=()=>{E?.down([[S,Q.length]])},Y=Z=>{G&&G.down([[S,Z]])},J=s?.strategy??"drop-oldest",z=(Z,ue)=>{let me={value:Z,payload:ue};if(Q.length<I)return Q.push(me),j(),!0;if(J==="drop-oldest"){let De=Q.shift();return Q.push(me),j(),Y(!0),k.down([[S,{value:De.value,error:new Error("backpressure: buffer overflow \u2014 dropped oldest"),attempts:0}]]),!0}if(J==="drop-newest")return Y(!0),k.down([[S,{value:Z,error:new Error("backpressure: buffer overflow \u2014 dropped newest"),attempts:0}]]),!1;let Se=new Error("backpressure: buffer overflow");return C({stage:"send",error:Se,value:Z}),k.down([[S,{value:Z,error:Se,attempts:0}]]),Y(!0),!1},X=Z=>{let ue=0,me=Z.map(Te=>Te.payload),Se=Te=>{P(-1);let ye=Or(Te);if(C({stage:"send",error:ye,value:Z.map(ni=>ni.value),attempt:ue}),!(ue<g&&b(ye,ue))){for(let{value:ni}of Z)k.down([[S,{value:ni,error:ye,attempts:ue}]]);return}return F(qe,ue,ye)},De=()=>{P(-1);for(let{value:Te}of Z)w.down([[S,Te]])};function qe(){ue+=1,P(1);let Te;try{Te=p(me,h)}catch(ye){return Se(ye)??Promise.resolve()}return A(Te)?Te.then(De,ye=>Se(ye)):(De(),Promise.resolve())}return qe()},H=async Z=>{for(let ue of Z)await le(ue.value,ue.payload)},le=(Z,ue)=>{let me=0,Se=Te=>{P(-1);let ye=Or(Te);if(C({stage:"send",error:ye,value:Z,attempt:me}),!(me<g&&b(ye,me))){k.down([[S,{value:Z,error:ye,attempts:me}]]);return}return F(qe,me,ye)},De=()=>{P(-1),w.down([[S,Z]])};function qe(){me+=1,P(1);let Te;try{Te=f(ue,h)}catch(ye){return Se(ye)??Promise.resolve()}return A(Te)?Te.then(De,ye=>Se(ye)):(De(),Promise.resolve())}return qe()},ve=()=>{if(ae||Q.length===0)return Promise.resolve();let Z=Q.drain();if(j(),Y(!1),p!==void 0){let me=X(Z);return ne(me),me}let ue=H(Z);return ne(ue),ue},Oe=()=>{U!==void 0||ae||a<=0||(U=setTimeout(()=>{U=void 0,ve()},a))},Be=t.subscribe(Z=>{for(let ue of Z){let me=ue[0];if(me!==S)try{d?.(ue)}catch{}if(me===S){let Se=ue[1];if(v){let De;if(u)try{De=u(Se)}catch(Te){let ye=Or(Te);C({stage:"serialize",error:ye,value:Se}),k.down([[S,{value:Se,error:ye,attempts:0}]]);continue}else De=Se;if(!z(Se,De))continue;Q.length>=i?ve():Oe()}else{let De=D(Se);ne(De)}}else Ae.messageTier(me)>=3&&v&&(U!==void 0&&(clearTimeout(U),U=void 0),ve())}}),gt;if(c){let Z=!1;gt=c.subscribe(ue=>{if(!Z){Z=!0;return}ue.length>0&&!Wt&&rt()})}let Wt=!1,rt=()=>{if(Wt)return;Wt=!0,U!==void 0&&(clearTimeout(U),U=void 0),v&&ve(),ae=!0,gt?.(),Be();let Z=ue=>{try{ue.down([[de]])}catch{}};Z(R),Z(k),Z(w),Z(x),E&&Z(E),G&&Z(G);try{l?.()}catch{}},We={dispose:rt,sent:w,failed:k,inFlight:x,errors:R};return v&&(We.buffered=E,We.flush=async()=>{ae||(await ve(),await Promise.all(V))}),G&&(We.paused=G),We}Tt();Re();function ct(t){return{describeKind:"producer",...t}}function Ji(t,e){let{parse:n,closeOnTeardown:r=!1,...o}=e??{};return W(s=>{let i=!0,a,u=()=>{let y=a;a=void 0,y?.()},c=y=>{i&&(i=!1,s.down([y]),u())},d=(y,b=y)=>{if(i)try{let v=y!==null&&typeof y=="object"&&"data"in y?y.data:y,T=n?n(v,b):v;s.emit(T)}catch(v){c([M,v])}},l=y=>{c([M,y])},f=()=>{c([_])};if(typeof t=="function"){try{if(a=t(d,l,f),typeof a!="function")throw new Error("fromWebSocket register contract violation: register must return cleanup callable")}catch(y){c([M,y])}return()=>{i=!1,u()}}let p=t,m=y=>d(y,y),h=y=>l(y),g=()=>f();return p.addEventListener("message",m),p.addEventListener("error",h),p.addEventListener("close",g),a=()=>{p.removeEventListener("message",m),p.removeEventListener("error",h),p.removeEventListener("close",g),r&&p.close()},()=>{i=!1,u()}},ct(o))}function pd(t,e){return cn(t,e)}function Yi(t,e){let{method:n="GET",headers:r,body:o,transform:s=v=>v.json(),timeoutNs:i=30*1e9,signal:a,completeAfterFetch:u=!1,refetchOnSubscribe:c=!1,...d}=e??{},l=N(0,{name:`${d.name??"http"}/fetchCount`}),f=N(0,{name:`${d.name??"http"}/lastUpdated`}),p=N(!1,{name:`${d.name??"http"}/fetched`}),m=0,h=o!==void 0?typeof o=="string"?o:JSON.stringify(o):void 0,g=v=>{let T=new AbortController,w=!0;if(a?.aborted)return w=!1,v.down([[M,a.reason??new Error("Aborted")]]),()=>{};a?.addEventListener("abort",()=>T.abort(a.reason),{once:!0});let k=setTimeout(()=>T.abort(new Error("Request timeout")),Math.ceil(i/1e6));return fetch(t,{method:n,headers:r,body:h,signal:T.signal}).then(async x=>{if(clearTimeout(k),!w)return;if(!x.ok)throw new Error(`HTTP ${x.status}: ${x.statusText}`);let R=await s(x);w&&(te(()=>{m+=1,l.down([[S,m]]),f.down([[S,pe()]]),p.down([[S,!0]]),v.emit(R)}),u&&v.down([[_]]))}).catch(x=>{clearTimeout(k),w&&(x&&x.name==="AbortError"||v.down([[M,x]]))}),()=>{w=!1,T.abort()}},y=W(v=>g({emit:T=>v.emit(T),down:T=>v.down(T)}),{...ct(d),resubscribable:c});return{...It(y),fetchCount:l,lastUpdated:f,fetched:p}}function fd(t,e,n){let{method:r="POST",headers:o={"Content-Type":"application/json"},serialize:s=m=>JSON.stringify(m),timeoutNs:i,batchFormat:a="json-array",batchSize:u,flushIntervalMs:c,retry:d,onTransportError:l}=n??{},f=async m=>{let h=i!==void 0?new AbortController:void 0,g;h&&i!==void 0&&(g=setTimeout(()=>h.abort(new Error("Request timeout")),Math.ceil(i/1e6)));try{let y=await fetch(e,{method:r,headers:o,body:m,signal:h?.signal}),b=async()=>{try{await y.arrayBuffer?.()}catch{}};if(!y.ok)throw await b(),new Error(`HTTP ${y.status}: ${y.statusText}`);await b()}finally{g!==void 0&&clearTimeout(g)}};return u!==void 0||c!==void 0?$e(t,{onTransportError:l,retry:d,batchSize:u,flushIntervalMs:c,sendBatch:async m=>{let h;a==="ndjson"?h=m.map(g=>{let y=s(g);return typeof y=="string"?y:new TextDecoder().decode(y)}).join(`
16
+ `):h=JSON.stringify(m),await f(h)}}):$e(t,{onTransportError:l,retry:d,serialize:s,send:async m=>{await f(m)}})}function md(t){return Symbol.keyFor(t)??t.description??"message"}function Un(t,e){return typeof t=="string"?t:e(t)}function hd(t,e){let n=`event: ${t}
16
17
  `;if(e!==void 0){let r=e.split(/\r?\n/);for(let o of r)n+=`data: ${o}
17
18
  `}return`${n}
18
- `}function Uc(t,e){let{serialize:n=p=>{if(p instanceof Error)return p.message;try{return JSON.stringify(p)}catch{return String(p)}},dataEvent:r="data",errorEvent:o="error",completeEvent:s="complete",includeResolved:i=!1,includeDirty:a=!1,keepAliveMs:u,signal:c,eventNameResolver:d=Hc}=e??{},l=new TextEncoder,f;return new ReadableStream({start(p){let m=!1,h,g=()=>{},y=()=>{m||(m=!0,h!==void 0&&clearInterval(h),c?.removeEventListener("abort",v),g(),p.close())};f=y;let b=(T,w)=>{m||p.enqueue(l.encode(Wc(T,w)))},v=()=>{m||y()};g=t.subscribe(T=>{for(let w of T){let k=w[0];if(!(Me.isLocalOnly(k)&&!(k===Z&&a))){if(k===R){b(r,Kn(w[1],n));continue}if(k===O){b(o,Kn(w[1],n)),y();return}if(k===M){b(s),y();return}!i&&k===$||b(d(k),w.length>1?Kn(w[1],n):void 0)}}}),u!==void 0&&u>0&&(h=setInterval(()=>{m||p.enqueue(l.encode(`: keepalive
19
+ `}function gd(t,e){let{serialize:n=p=>{if(p instanceof Error)return p.message;try{return JSON.stringify(p)}catch{return String(p)}},dataEvent:r="data",errorEvent:o="error",completeEvent:s="complete",includeResolved:i=!1,includeDirty:a=!1,keepAliveMs:u,signal:c,eventNameResolver:d=md}=e??{},l=new TextEncoder,f;return new ReadableStream({start(p){let m=!1,h,g=()=>{},y=()=>{m||(m=!0,h!==void 0&&clearInterval(h),c?.removeEventListener("abort",v),g(),p.close())};f=y;let b=(T,w)=>{m||p.enqueue(l.encode(hd(T,w)))},v=()=>{m||y()};g=t.subscribe(T=>{for(let w of T){let k=w[0];if(!(Ae.isLocalOnly(k)&&!(k===ee&&a))){if(k===S){b(r,Un(w[1],n));continue}if(k===M){b(o,Un(w[1],n)),y();return}if(k===_){b(s),y();return}!i&&k===B||b(d(k),w.length>1?Un(w[1],n):void 0)}}}),u!==void 0&&u>0&&(h=setInterval(()=>{m||p.enqueue(l.encode(`: keepalive
19
20
 
20
- `))},u)),c?.aborted?v():c?.addEventListener("abort",v,{once:!0})},cancel(){f?.()}})}function zc(t,e){let{serialize:n=f=>{if(f instanceof Error)return f.message;try{return JSON.stringify(f)}catch{return String(f)}},dataEvent:r="data",errorEvent:o="error",completeEvent:s="complete",includeResolved:i=!1,includeDirty:a=!1,keepAliveMs:u,signal:c,eventNameResolver:d=Hc}=e??{},l=new TextEncoder;return H(f=>{let p=!0,m,h=(b,v)=>{p&&f.emit(l.encode(Wc(b,v)))},g=()=>{p&&(p=!1,f.down([[M]]))},y=t.subscribe(b=>{if(p)for(let v of b){let T=v[0];if(!(Me.isLocalOnly(T)&&!(T===Z&&a))){if(T===R){h(r,Kn(v[1],n));continue}if(T===O){h(o,Kn(v[1],n)),p=!1,f.down([[M]]);return}if(T===M){h(s),p=!1,f.down([[M]]);return}!i&&T===$||h(d(T),v.length>1?Kn(v[1],n):void 0)}}});return u!==void 0&&u>0&&(m=setInterval(()=>{p&&f.emit(l.encode(`: keepalive
21
+ `))},u)),c?.aborted?v():c?.addEventListener("abort",v,{once:!0})},cancel(){f?.()}})}function yd(t,e){let{serialize:n=f=>{if(f instanceof Error)return f.message;try{return JSON.stringify(f)}catch{return String(f)}},dataEvent:r="data",errorEvent:o="error",completeEvent:s="complete",includeResolved:i=!1,includeDirty:a=!1,keepAliveMs:u,signal:c,eventNameResolver:d=md}=e??{},l=new TextEncoder;return W(f=>{let p=!0,m,h=(b,v)=>{p&&f.emit(l.encode(hd(b,v)))},g=()=>{p&&(p=!1,f.down([[_]]))},y=t.subscribe(b=>{if(p)for(let v of b){let T=v[0];if(!(Ae.isLocalOnly(T)&&!(T===ee&&a))){if(T===S){h(r,Un(v[1],n));continue}if(T===M){h(o,Un(v[1],n)),p=!1,f.down([[_]]);return}if(T===_){h(s),p=!1,f.down([[_]]);return}!i&&T===B||h(d(T),v.length>1?Un(v[1],n):void 0)}}});return u!==void 0&&u>0&&(m=setInterval(()=>{p&&f.emit(l.encode(`: keepalive
21
22
 
22
- `))},u)),c?.aborted?g():c?.addEventListener("abort",g,{once:!0}),()=>{p=!1,m!==void 0&&clearInterval(m),c?.removeEventListener("abort",g),y()}})}function Jc(t){let e,n=!1;return new ReadableStream({start(r){e=t.subscribe(o=>{for(let s of o){let i=s[0];if(n)return;if(i===R)try{r.enqueue(s[1])}catch{n=!0,e?.()}else if(i===O){n=!0;try{r.error(s[1])}catch{}return}else if(i===M){n=!0;try{r.close()}catch{}return}}})},cancel(){n=!0,e?.()}})}function Yc(t,e){let{parse:n=o=>o,...r}=e??{};return H(o=>{let s=!0,i=new TextDecoder,a="",u="message",c=[],d,l,f=()=>{if(c.length===0&&u==="message"&&d===void 0){c=[];return}let b=c.join(`
23
- `);o.emit({event:u,data:n(b),id:d,retry:l}),u="message",c=[],d=void 0,l=void 0},p=b=>{if(b===""){f();return}if(b.startsWith(":"))return;let v=b.indexOf(":"),T=v<0?b:b.slice(0,v),w=v<0?"":b.slice(v+1);switch(w.startsWith(" ")&&(w=w.slice(1)),T){case"event":u=w;break;case"data":c.push(w);break;case"id":w.includes("\0")||(d=w);break;case"retry":{let k=Number(w);Number.isFinite(k)&&(l=k);break}}},m=(b,v)=>{if(!s)return;a+=i.decode(b,{stream:!v});let T=a.split(/\r?\n/);a=T.pop()??"";for(let w of T)p(w)},h,g;return(async()=>{try{let b=t,v=t instanceof ReadableStream?t:b&&typeof b=="object"&&b.body instanceof ReadableStream?b.body:null;if(v){for(h=v.getReader();s;){let{value:T,done:w}=await h.read();if(w)break;m(T,!1)}m(new Uint8Array,!0)}else{for(g=t[Symbol.asyncIterator]();s;){let w=await g.next();if(w.done)break;m(w.value,!1)}m(new Uint8Array,!0)}if(a.trim()){for(let T of a.split(/\r?\n/))p(T);f()}s&&o.down([[M]])}catch(b){s&&o.down([[O,b]])}})(),()=>{s=!1,h&&h.cancel().catch(()=>{}),g&&typeof g.return=="function"&&Promise.resolve(g.return()).catch(()=>{})}},ut(r))}function Qc(t,e){let{method:n="GET",headers:r,body:o,signal:s,...i}=e??{};return H(a=>{let u=!0,c=new AbortController;if(s?.aborted)return a.down([[O,s.reason??new Error("Aborted")]]),()=>{};s?.addEventListener("abort",()=>c.abort(s.reason),{once:!0});let d=o!==void 0?typeof o=="string"?o:JSON.stringify(o):void 0;return(async()=>{try{let f=await fetch(t,{method:n,headers:r,body:d,signal:c.signal});if(!u)return;if(!f.ok)throw new Error(`HTTP ${f.status}: ${f.statusText}`);if(!f.body)throw new Error("HTTP response has no body");let p=f.body.getReader();for(;u;){let{value:m,done:h}=await p.read();if(h)break;m&&a.emit(m)}u&&a.down([[M]])}catch(f){if(!u||f&&f.name==="AbortError")return;a.down([[O,f]])}})(),()=>{u=!1,c.abort()}},ut(i))}function Xc(t,e){let{intervalMs:n=5e3,...r}=e??{};return _e(et(n,{period:n}),()=>Hi(t,{...r,completeAfterFetch:!0}).node)}function Zc(t,e,n){let{serialize:r=y=>{if(typeof y=="string"||y instanceof Blob||y instanceof ArrayBuffer||ArrayBuffer.isView(y))return y;try{return JSON.stringify(y)}catch{return String(y)}},closeOnComplete:o=!0,closeOnError:s=!0,closeCode:i,closeReason:a,onTransportError:u,retry:c,backpressure:d,stopOn:l}=n??{},f=!1,p=y=>{if(!f){f=!0;try{e.close(i,a)}catch(b){let v=b instanceof Error?b:new Error(String(b));try{u?.({stage:"close",error:v,value:void 0,message:y})}catch{}}}},m=null,g=Ge(t,{onTransportError:u,serialize:y=>{let b=r(y);if(b===void 0)throw new Error("serialize returned undefined");return b},retry:c,backpressure:d,stopOn:l,onDispose:()=>{if(m){try{e.removeEventListener("close",m)}catch{}m=null}},send:y=>{e.send(y)},onUpstreamMessage:y=>{(y[0]===M&&o||y[0]===O&&s)&&p(y)}});return m=()=>{f=!0,g.dispose()},e.addEventListener("close",m),g}function ed(t,e){let{parse:n,maxRetries:r,backoff:o="exponential",closeOnTeardown:s=!0,...i}=e??{};return Ct(()=>qi(t(),{parse:n,closeOnTeardown:s,...i}),{count:r,backoff:o})}function td(t,e){let{method:n="notifications/message",onDisconnect:r,...o}=e??{};return an(({emit:s,error:i})=>(t.setNotificationHandler(n,a=>s(a)),r?.(a=>i(a??new Error("MCP client disconnected"))),()=>t.setNotificationHandler(n,()=>{})),o)}function nd(t,e){return qo(({traces:r,metrics:o,logs:s,error:i})=>t({onTraces:a=>{ee(()=>{for(let u of a)r(u)})},onMetrics:a=>{ee(()=>{for(let u of a)o(u)})},onLogs:a=>{ee(()=>{for(let u of a)s(u)})},onError:i})??void 0,["traces","metrics","logs"],e?.name?{name:e.name}:void 0)}function rd(t,e){return an(t,e)}function od(t){let e=t.match(/^<(\d{1,3})>\d?\s*(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s*(.*)/s);if(!e){let r=pe();return{facility:1,severity:6,timestamp:new Date(Math.floor(r/1e6)).toISOString(),hostname:"-",appName:"-",procId:"-",msgId:"-",message:t.trim(),timestampNs:r}}let n=Number(e[1]);return{facility:n>>3,severity:n&7,timestamp:e[2],hostname:e[3],appName:e[4],procId:e[5],msgId:e[6],message:(e[7]??"").trim(),timestampNs:pe()}}function sd(t,e){return an(t,e)}var Af={c:"counter",g:"gauge",ms:"timer",h:"histogram",s:"set",d:"distribution"};function id(t){let e=t.split("|"),[n,r]=(e[0]??"").split(":");if(!n||r===void 0)throw new Error(`Invalid StatsD line: ${t}`);let o=e[1]?.trim()??"c",s=Af[o]??"counter",i=s==="set"?0:Number(r),a,u={};for(let c=2;c<e.length;c++){let d=e[c].trim();if(d.startsWith("@"))a=Number(d.slice(1));else if(d.startsWith("#"))for(let l of d.slice(1).split(",")){let[f,p]=l.split(":");f&&(u[f]=p??"")}}return{name:n.trim(),value:i,type:s,sampleRate:a,tags:u,timestampNs:pe()}}function ad(t,e){let{intervalNs:n=15*1e9,headers:r,timeoutNs:o=10*1e9,signal:s,maxConsecutiveErrors:i=1}=e??{},a=Math.ceil(n/1e6),u=0;return _e(et(0,{period:a,signal:s}),()=>H(c=>{let d=!0,l=new AbortController,f=setTimeout(()=>l.abort(new Error("Scrape timeout")),Math.ceil(o/1e6));return(async()=>{try{let m=await fetch(t,{headers:{Accept:"text/plain",...r},signal:l.signal});if(clearTimeout(f),!d)return;if(!m.ok)throw new Error(`Prometheus scrape ${m.status}: ${m.statusText}`);let h=await m.text();if(!d)return;let g=Wi(h);for(let y of g)c.emit(y);u=0,c.down([[M]])}catch(m){if(clearTimeout(f),!d||m instanceof Error&&m.name==="AbortError")return;u+=1,u>=i&&c.down([[O,m]])}})(),()=>{d=!1,clearTimeout(f),l.abort()}}))}function Wi(t){let e=[],n=new Map,r=new Map;for(let o of t.split(`
24
- `)){let s=o.trim();if(!s)continue;if(s.startsWith("# TYPE ")){let f=s.slice(7),p=f.indexOf(" ");p>0&&n.set(f.slice(0,p),f.slice(p+1).trim());continue}if(s.startsWith("# HELP ")){let f=s.slice(7),p=f.indexOf(" ");p>0&&r.set(f.slice(0,p),f.slice(p+1).trim());continue}if(s.startsWith("#"))continue;let i,a={},u,c,d=s.indexOf("{");if(d>=0){i=s.slice(0,d);let f=s.indexOf("}",d);if(f<0)continue;let p=s.slice(d+1,f);a=Lf(p);let m=s.slice(f+1).trim().split(/\s+/);u=m[0]??"",c=m[1]}else{let f=s.split(/\s+/);i=f[0]??"",u=f[1]??"",c=f[2]}if(!i||!u)continue;let l=i.replace(/(_total|_count|_sum|_bucket|_created|_info)$/,"");e.push({name:i,labels:a,value:Number(u),timestampMs:c?Number(c):void 0,type:n.get(l)??n.get(i),help:r.get(l)??r.get(i),timestampNs:pe()})}return e}function Lf(t){let e={},n=/(\w+)="((?:[^"\\]|\\.)*)"/g,r=n.exec(t);for(;r!==null;)e[r[1]]=r[2].replace(/\\(.)/g,"$1"),r=n.exec(t);return e}function ud(t,e,n){let{fromBeginning:r=!1,deserialize:o=i=>{if(i===null)return null;try{return JSON.parse(i.toString())}catch{return i.toString()}},...s}=n??{};return H(i=>{let a=!0;return(async()=>{try{await t.subscribe({topic:e,fromBeginning:r}),await t.run({eachMessage:async({topic:c,partition:d,message:l})=>{if(!a)return;let f={};if(l.headers)for(let[p,m]of Object.entries(l.headers))m!==void 0&&(f[p]=typeof m=="string"?m:m.toString());i.emit({topic:c,partition:d,key:l.key?.toString()??null,value:o(l.value),headers:f,offset:l.offset,timestamp:l.timestamp,timestampNs:pe()})}})}catch(c){a&&i.down([[O,c]])}})(),()=>{a=!1}},ut(s))}function cd(t,e,n,r){let{serialize:o=a=>JSON.stringify(a),keyExtractor:s,onTransportError:i}=r??{};return Ge(t,{onTransportError:i,send:async a=>{let u=s?.(a)??null,c=o(a);await e.send({topic:n,messages:[{key:u,value:Buffer.from(c)}]})}})}function dd(t,e,n){let{blockMs:r=5e3,startId:o="$",parse:s=a=>{for(let c=0;c<a.length;c+=2)if(a[c]==="data")try{return JSON.parse(a[c+1])}catch{return a[c+1]}let u={};for(let c=0;c<a.length;c+=2)u[a[c]]=a[c+1];return u},...i}=n??{};return H(a=>{let u=!0,c=o;return(async()=>{for(;u;)try{let l=await t.xread("BLOCK",r,"STREAMS",e,c);if(!u)return;if(l)for(let[f,p]of l)for(let[m,h]of p)c=m,a.emit({id:m,key:e,data:s(h),timestampNs:pe()})}catch(l){if(!u)return;a.down([[O,l]]);return}})(),()=>{u=!1}},ut(i))}function ld(t,e,n,r){let{serialize:o=a=>["data",JSON.stringify(a)],maxLen:s,onTransportError:i}=r??{};return Ge(t,{onTransportError:i,send:async a=>{let u=o(a);await(s!==void 0?e.xadd(n,"MAXLEN","~",String(s),"*",...u):e.xadd(n,"*",...u))}})}function pd(t,e){let{delimiter:n=",",hasHeader:r=!0,columns:o,parseLine:s,...i}=e??{},a=s??(u=>hd(u,n));return H(u=>{let c=!1;return(async()=>{try{let l=o,f="";for await(let p of t){if(c)return;f+=p;let m=f.split(/\r?\n/);f=m.pop()??"";for(let h of m){if(c)return;if(!h.trim())continue;let g=a(h);if(!l&&r){l=g;continue}l||(l=g.map((b,v)=>`col${v}`));let y={};for(let b=0;b<l.length;b++)y[l[b]]=g[b]??"";u.emit(y)}}if(!c&&f.trim()){let p=a(f);if(l){let m={};for(let h=0;h<l.length;h++)m[l[h]]=p[h]??"";u.emit(m)}}c||u.down([[M]])}catch(l){c||u.down([[O,l]])}})(),()=>{c=!0}},ut(i))}function fd(t,e){let{delimiter:n=",",hasHeader:r=!0,columns:o,parseLine:s,...i}=e??{},a=s??(u=>hd(u,n));return q([t],(u,c,d)=>{let l=u[0];if(l==null||l.length===0)return;let f=d.store;typeof f.buffer!="string"&&(f.buffer=""),f.headers===void 0&&o&&(f.headers=o.slice());for(let p of l){f.buffer=f.buffer+p;let m=f.buffer.split(/\r?\n/);f.buffer=m.pop()??"";for(let h of m){if(!h.trim())continue;let g=a(h);if(!f.headers&&r){f.headers=g;continue}f.headers||(f.headers=g.map((b,v)=>`col${v}`));let y={};for(let b=0;b<f.headers.length;b++)y[f.headers[b]]=g[b]??"";c.emit(y)}}},{describeKind:"derived",...i})}function md(t,e){return q([t],(n,r,o)=>{let s=n[0];if(s==null||s.length===0)return;let i=o.store;typeof i.buffer!="string"&&(i.buffer="");for(let a of s){i.buffer=i.buffer+a;let u=i.buffer.split(/\r?\n/);i.buffer=u.pop()??"";for(let c of u)if(c.trim())try{r.emit(JSON.parse(c))}catch(d){r.down([[O,d]]);return}}},{describeKind:"derived",...e??{}})}function hd(t,e){let n=[],r="",o=!1;for(let s=0;s<t.length;s++){let i=t[s];o?i==='"'?t[s+1]==='"'?(r+='"',s++):o=!1:r+=i:i==='"'?o=!0:i===e?(n.push(r),r=""):r+=i}return n.push(r),n}function gd(t,e){return H(n=>{let r=!1;return(async()=>{try{let s="";for await(let i of t){if(r)return;s+=i;let a=s.split(/\r?\n/);s=a.pop()??"";for(let u of a){if(r)return;let c=u.trim();c&&n.emit(JSON.parse(c))}}!r&&s.trim()&&n.emit(JSON.parse(s.trim())),r||n.down([[M]])}catch(s){r||n.down([[O,s]])}})(),()=>{r=!0}},ut(e))}function yd(t,e,n){let{intervalNs:r=5*1e9,format:o="JSONEachRow",signal:s,maxConsecutiveErrors:i=1}=n??{},a=Math.ceil(r/1e6),u=0;return _e(et(0,{period:a,signal:s}),()=>H(c=>{let d=!0;return(async()=>{try{let f=await t.query({query:e,format:o});if(!d)return;let p=await f.json();if(!d)return;for(let m of p)c.emit(m);u=0,c.down([[M]])}catch(f){if(!d)return;u+=1,u>=i&&c.down([[O,f]])}})(),()=>{d=!1}}))}function bd(t,e){let{autoAck:n=!0,deserialize:r=a=>{try{return JSON.parse(a.toString())}catch{return a.toString()}},onAckError:o,...s}=e??{},i=a=>{if(o)try{o(a instanceof Error?a:new Error(String(a)))}catch{}};return H(a=>{let u=!0;return(async()=>{for(;u;)try{let d=await t.receive();if(!u)return;let l={topic:d.getTopicName(),messageId:d.getMessageId().toString(),key:d.getPartitionKey(),value:r(d.getData()),properties:d.getProperties(),publishTime:d.getPublishTimestamp(),eventTime:d.getEventTimestamp(),timestampNs:pe()};if(n)a.emit(l),t.acknowledge(d).catch(i);else{let f=!1,p={value:l,ack(){f||(f=!0,t.acknowledge(d).catch(i))},nack(m){if(f)return;f=!0;let h=t;try{let g=h.negativeAcknowledge?.(d);g&&typeof g.then=="function"&&g.catch(i)}catch(g){i(g)}}};a.emit(p)}}catch(d){u&&a.down([[O,d]]);return}})(),()=>{u=!1}},ut(s))}function vd(t,e,n){let{serialize:r=a=>Buffer.from(JSON.stringify(a)),keyExtractor:o,propertiesExtractor:s,onTransportError:i}=n??{};return Ge(t,{onTransportError:i,send:async a=>{await e.send({data:r(a),partitionKey:o?.(a),properties:s?.(a)})}})}function Td(t,e,n){let r=new TextDecoder,{queue:o,deserialize:s=a=>{let u=r.decode(a);try{return JSON.parse(u)}catch{return u}},...i}=n??{};return H(a=>{let u=!0,c=t.subscribe(e,o?{queue:o}:void 0);return(async()=>{try{for await(let l of c){if(!u)return;let f={};if(l.headers)for(let p of l.headers.keys())f[p]=l.headers.get(p);a.emit({subject:l.subject,data:s(l.data),headers:f,reply:l.reply,sid:l.sid,timestampNs:pe()})}u&&a.down([[M]])}catch(l){u&&a.down([[O,l]])}})(),()=>{u=!1}},ut(i))}function wd(t,e,n,r){let o=new TextEncoder,{serialize:s=a=>o.encode(JSON.stringify(a)),onTransportError:i}=r??{};return Ge(t,{onTransportError:i,send:a=>{e.publish(n,s(a))}})}function kd(t,e,n){let{autoAck:r=!0,deserialize:o=u=>{try{return JSON.parse(u.toString())}catch{return u.toString()}},onAckError:s,...i}=n??{},a=u=>{if(s)try{s(u instanceof Error?u:new Error(String(u)))}catch{}};return H(u=>{let c=!0,d;return(async()=>{try{d=(await t.consume(e,p=>{if(!c)return;if(p===null){c&&u.down([[O,new Error("Consumer cancelled by broker")]]);return}let m={queue:e,routingKey:p.fields.routingKey,exchange:p.fields.exchange,content:o(p.content),properties:p.properties,deliveryTag:p.fields.deliveryTag,redelivered:p.fields.redelivered,timestampNs:pe()};if(r){u.emit(m);try{t.ack(p)}catch(h){a(h)}}else{let h=!1,g=t,y={value:m,ack(){if(!h){h=!0;try{t.ack(p)}catch(b){a(b)}}},nack(b){if(h)return;h=!0;let v=b?.requeue;if(!g.nack){a(new Error("RabbitMQ channel does not expose `nack`; cannot negative-ack"));return}try{g.nack(p,!1,v)}catch(T){a(T)}}};u.emit(y)}},{noAck:!1})).consumerTag}catch(f){c&&u.down([[O,f]])}})(),()=>{c=!1,d!==void 0&&t.cancel(d)}},ut(i))}function xd(t,e,n,r){let{serialize:o=a=>Buffer.from(JSON.stringify(a)),routingKeyExtractor:s=()=>"",onTransportError:i}=r??{};return Ge(t,{onTransportError:i,send:a=>{let u=s(a),c=o(a);e.publish(n,u,c)}})}function Ui(t,e,n){let{serialize:r=l=>`${JSON.stringify(l)}
25
- `,flushIntervalMs:o=0,batchSize:s=Number.POSITIVE_INFINITY,onTransportError:i,mode:a}=n??{},c=o>0||s<Number.POSITIVE_INFINITY?Ge(t,{onTransportError:i,batchSize:s,flushIntervalMs:o,serialize:r,sendBatch:l=>{e.write(l.join(""))}}):Ge(t,{onTransportError:i,serialize:r,send:l=>{e.write(l)}}),d=c.dispose;return c.dispose=()=>{d();try{e.end()}catch{}},c}function Vi(t,e){return t.includes(e)||t.includes('"')||t.includes(`
26
- `)?`"${t.replace(/"/g,'""')}"`:t}function Rd(t,e,n){let{columns:r,delimiter:o=",",writeHeader:s=!0,cellExtractor:i=(p,m)=>String(p[m]??""),flushIntervalMs:a=0,batchSize:u=Number.POSITIVE_INFINITY,onTransportError:c,...d}=n,l=!1;return Ui(t,e,{serialize:p=>{if(!l&&s){l=!0;let m=r.map(g=>Vi(g,o)).join(o),h=r.map(g=>Vi(i(p,g),o)).join(o);return`${m}
23
+ `))},u)),c?.aborted?g():c?.addEventListener("abort",g,{once:!0}),()=>{p=!1,m!==void 0&&clearInterval(m),c?.removeEventListener("abort",g),y()}})}function bd(t){let e,n=!1;return new ReadableStream({start(r){e=t.subscribe(o=>{for(let s of o){let i=s[0];if(n)return;if(i===S)try{r.enqueue(s[1])}catch{n=!0,e?.()}else if(i===M){n=!0;try{r.error(s[1])}catch{}return}else if(i===_){n=!0;try{r.close()}catch{}return}}})},cancel(){n=!0,e?.()}})}function vd(t,e){let{parse:n=o=>o,...r}=e??{};return W(o=>{let s=!0,i=new TextDecoder,a="",u="message",c=[],d,l,f=()=>{if(c.length===0&&u==="message"&&d===void 0){c=[];return}let b=c.join(`
24
+ `);o.emit({event:u,data:n(b),id:d,retry:l}),u="message",c=[],d=void 0,l=void 0},p=b=>{if(b===""){f();return}if(b.startsWith(":"))return;let v=b.indexOf(":"),T=v<0?b:b.slice(0,v),w=v<0?"":b.slice(v+1);switch(w.startsWith(" ")&&(w=w.slice(1)),T){case"event":u=w;break;case"data":c.push(w);break;case"id":w.includes("\0")||(d=w);break;case"retry":{let k=Number(w);Number.isFinite(k)&&(l=k);break}}},m=(b,v)=>{if(!s)return;a+=i.decode(b,{stream:!v});let T=a.split(/\r?\n/);a=T.pop()??"";for(let w of T)p(w)},h,g;return(async()=>{try{let b=t,v=t instanceof ReadableStream?t:b&&typeof b=="object"&&b.body instanceof ReadableStream?b.body:null;if(v){for(h=v.getReader();s;){let{value:T,done:w}=await h.read();if(w)break;m(T,!1)}m(new Uint8Array,!0)}else{for(g=t[Symbol.asyncIterator]();s;){let w=await g.next();if(w.done)break;m(w.value,!1)}m(new Uint8Array,!0)}if(a.trim()){for(let T of a.split(/\r?\n/))p(T);f()}s&&o.down([[_]])}catch(b){s&&o.down([[M,b]])}})(),()=>{s=!1,h&&h.cancel().catch(()=>{}),g&&typeof g.return=="function"&&Promise.resolve(g.return()).catch(()=>{})}},ct(r))}function Td(t,e){let{method:n="GET",headers:r,body:o,signal:s,...i}=e??{};return W(a=>{let u=!0,c=new AbortController;if(s?.aborted)return a.down([[M,s.reason??new Error("Aborted")]]),()=>{};s?.addEventListener("abort",()=>c.abort(s.reason),{once:!0});let d=o!==void 0?typeof o=="string"?o:JSON.stringify(o):void 0;return(async()=>{try{let f=await fetch(t,{method:n,headers:r,body:d,signal:c.signal});if(!u)return;if(!f.ok)throw new Error(`HTTP ${f.status}: ${f.statusText}`);if(!f.body)throw new Error("HTTP response has no body");let p=f.body.getReader();for(;u;){let{value:m,done:h}=await p.read();if(h)break;m&&a.emit(m)}u&&a.down([[_]])}catch(f){if(!u||f&&f.name==="AbortError")return;a.down([[M,f]])}})(),()=>{u=!1,c.abort()}},ct(i))}function wd(t,e){let{intervalMs:n=5e3,...r}=e??{};return be(et(n,{period:n}),()=>Yi(t,{...r,completeAfterFetch:!0}).node)}function kd(t,e,n){let{serialize:r=y=>{if(typeof y=="string"||y instanceof Blob||y instanceof ArrayBuffer||ArrayBuffer.isView(y))return y;try{return JSON.stringify(y)}catch{return String(y)}},closeOnComplete:o=!0,closeOnError:s=!0,closeCode:i,closeReason:a,onTransportError:u,retry:c,backpressure:d,stopOn:l}=n??{},f=!1,p=y=>{if(!f){f=!0;try{e.close(i,a)}catch(b){let v=b instanceof Error?b:new Error(String(b));try{u?.({stage:"close",error:v,value:void 0,message:y})}catch{}}}},m=null,g=$e(t,{onTransportError:u,serialize:y=>{let b=r(y);if(b===void 0)throw new Error("serialize returned undefined");return b},retry:c,backpressure:d,stopOn:l,onDispose:()=>{if(m){try{e.removeEventListener("close",m)}catch{}m=null}},send:y=>{e.send(y)},onUpstreamMessage:y=>{(y[0]===_&&o||y[0]===M&&s)&&p(y)}});return m=()=>{f=!0,g.dispose()},e.addEventListener("close",m),g}function xd(t,e){let{parse:n,maxRetries:r,backoff:o="exponential",closeOnTeardown:s=!0,...i}=e??{};return At(()=>Ji(t(),{parse:n,closeOnTeardown:s,...i}),{count:r,backoff:o})}function Rd(t,e){let{method:n="notifications/message",onDisconnect:r,...o}=e??{};return cn(({emit:s,error:i})=>(t.setNotificationHandler(n,a=>s(a)),r?.(a=>i(a??new Error("MCP client disconnected"))),()=>t.setNotificationHandler(n,()=>{})),o)}function Sd(t,e){return Yo(({traces:r,metrics:o,logs:s,error:i})=>t({onTraces:a=>{te(()=>{for(let u of a)r(u)})},onMetrics:a=>{te(()=>{for(let u of a)o(u)})},onLogs:a=>{te(()=>{for(let u of a)s(u)})},onError:i})??void 0,["traces","metrics","logs"],e?.name?{name:e.name}:void 0)}function Nd(t,e){return cn(t,e)}function Ed(t){let e=t.match(/^<(\d{1,3})>\d?\s*(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s*(.*)/s);if(!e){let r=pe();return{facility:1,severity:6,timestamp:new Date(Math.floor(r/1e6)).toISOString(),hostname:"-",appName:"-",procId:"-",msgId:"-",message:t.trim(),timestampNs:r}}let n=Number(e[1]);return{facility:n>>3,severity:n&7,timestamp:e[2],hostname:e[3],appName:e[4],procId:e[5],msgId:e[6],message:(e[7]??"").trim(),timestampNs:pe()}}function _d(t,e){return cn(t,e)}var wm={c:"counter",g:"gauge",ms:"timer",h:"histogram",s:"set",d:"distribution"};function Md(t){let e=t.split("|"),[n,r]=(e[0]??"").split(":");if(!n||r===void 0)throw new Error(`Invalid StatsD line: ${t}`);let o=e[1]?.trim()??"c",s=wm[o]??"counter",i=s==="set"?0:Number(r),a,u={};for(let c=2;c<e.length;c++){let d=e[c].trim();if(d.startsWith("@"))a=Number(d.slice(1));else if(d.startsWith("#"))for(let l of d.slice(1).split(",")){let[f,p]=l.split(":");f&&(u[f]=p??"")}}return{name:n.trim(),value:i,type:s,sampleRate:a,tags:u,timestampNs:pe()}}function Od(t,e){let{intervalNs:n=15*1e9,headers:r,timeoutNs:o=10*1e9,signal:s,maxConsecutiveErrors:i=1}=e??{},a=Math.ceil(n/1e6),u=0;return be(et(0,{period:a,signal:s}),()=>W(c=>{let d=!0,l=new AbortController,f=setTimeout(()=>l.abort(new Error("Scrape timeout")),Math.ceil(o/1e6));return(async()=>{try{let m=await fetch(t,{headers:{Accept:"text/plain",...r},signal:l.signal});if(clearTimeout(f),!d)return;if(!m.ok)throw new Error(`Prometheus scrape ${m.status}: ${m.statusText}`);let h=await m.text();if(!d)return;let g=Qi(h);for(let y of g)c.emit(y);u=0,c.down([[_]])}catch(m){if(clearTimeout(f),!d||m instanceof Error&&m.name==="AbortError")return;u+=1,u>=i&&c.down([[M,m]])}})(),()=>{d=!1,clearTimeout(f),l.abort()}}))}function Qi(t){let e=[],n=new Map,r=new Map;for(let o of t.split(`
25
+ `)){let s=o.trim();if(!s)continue;if(s.startsWith("# TYPE ")){let f=s.slice(7),p=f.indexOf(" ");p>0&&n.set(f.slice(0,p),f.slice(p+1).trim());continue}if(s.startsWith("# HELP ")){let f=s.slice(7),p=f.indexOf(" ");p>0&&r.set(f.slice(0,p),f.slice(p+1).trim());continue}if(s.startsWith("#"))continue;let i,a={},u,c,d=s.indexOf("{");if(d>=0){i=s.slice(0,d);let f=s.indexOf("}",d);if(f<0)continue;let p=s.slice(d+1,f);a=km(p);let m=s.slice(f+1).trim().split(/\s+/);u=m[0]??"",c=m[1]}else{let f=s.split(/\s+/);i=f[0]??"",u=f[1]??"",c=f[2]}if(!i||!u)continue;let l=i.replace(/(_total|_count|_sum|_bucket|_created|_info)$/,"");e.push({name:i,labels:a,value:Number(u),timestampMs:c?Number(c):void 0,type:n.get(l)??n.get(i),help:r.get(l)??r.get(i),timestampNs:pe()})}return e}function km(t){let e={},n=/(\w+)="((?:[^"\\]|\\.)*)"/g,r=n.exec(t);for(;r!==null;)e[r[1]]=r[2].replace(/\\(.)/g,"$1"),r=n.exec(t);return e}function Cd(t,e,n){let{fromBeginning:r=!1,deserialize:o=i=>{if(i===null)return null;try{return JSON.parse(i.toString())}catch{return i.toString()}},...s}=n??{};return W(i=>{let a=!0;return(async()=>{try{await t.subscribe({topic:e,fromBeginning:r}),await t.run({eachMessage:async({topic:c,partition:d,message:l})=>{if(!a)return;let f={};if(l.headers)for(let[p,m]of Object.entries(l.headers))m!==void 0&&(f[p]=typeof m=="string"?m:m.toString());i.emit({topic:c,partition:d,key:l.key?.toString()??null,value:o(l.value),headers:f,offset:l.offset,timestamp:l.timestamp,timestampNs:pe()})}})}catch(c){a&&i.down([[M,c]])}})(),()=>{a=!1}},ct(s))}function Ad(t,e,n,r){let{serialize:o=a=>JSON.stringify(a),keyExtractor:s,onTransportError:i}=r??{};return $e(t,{onTransportError:i,send:async a=>{let u=s?.(a)??null,c=o(a);await e.send({topic:n,messages:[{key:u,value:Buffer.from(c)}]})}})}function Ld(t,e,n){let{blockMs:r=5e3,startId:o="$",parse:s=a=>{for(let c=0;c<a.length;c+=2)if(a[c]==="data")try{return JSON.parse(a[c+1])}catch{return a[c+1]}let u={};for(let c=0;c<a.length;c+=2)u[a[c]]=a[c+1];return u},...i}=n??{};return W(a=>{let u=!0,c=o;return(async()=>{for(;u;)try{let l=await t.xread("BLOCK",r,"STREAMS",e,c);if(!u)return;if(l)for(let[f,p]of l)for(let[m,h]of p)c=m,a.emit({id:m,key:e,data:s(h),timestampNs:pe()})}catch(l){if(!u)return;a.down([[M,l]]);return}})(),()=>{u=!1}},ct(i))}function Id(t,e,n,r){let{serialize:o=a=>["data",JSON.stringify(a)],maxLen:s,onTransportError:i}=r??{};return $e(t,{onTransportError:i,send:async a=>{let u=o(a);await(s!==void 0?e.xadd(n,"MAXLEN","~",String(s),"*",...u):e.xadd(n,"*",...u))}})}function Pd(t,e){let{delimiter:n=",",hasHeader:r=!0,columns:o,parseLine:s,...i}=e??{},a=s??(u=>Fd(u,n));return W(u=>{let c=!1;return(async()=>{try{let l=o,f="";for await(let p of t){if(c)return;f+=p;let m=f.split(/\r?\n/);f=m.pop()??"";for(let h of m){if(c)return;if(!h.trim())continue;let g=a(h);if(!l&&r){l=g;continue}l||(l=g.map((b,v)=>`col${v}`));let y={};for(let b=0;b<l.length;b++)y[l[b]]=g[b]??"";u.emit(y)}}if(!c&&f.trim()){let p=a(f);if(l){let m={};for(let h=0;h<l.length;h++)m[l[h]]=p[h]??"";u.emit(m)}}c||u.down([[_]])}catch(l){c||u.down([[M,l]])}})(),()=>{c=!0}},ct(i))}function Dd(t,e){let{delimiter:n=",",hasHeader:r=!0,columns:o,parseLine:s,...i}=e??{},a=s??(u=>Fd(u,n));return K([t],(u,c,d)=>{let l=u[0];if(l==null||l.length===0)return;let f=d.store;typeof f.buffer!="string"&&(f.buffer=""),f.headers===void 0&&o&&(f.headers=o.slice());for(let p of l){f.buffer=f.buffer+p;let m=f.buffer.split(/\r?\n/);f.buffer=m.pop()??"";for(let h of m){if(!h.trim())continue;let g=a(h);if(!f.headers&&r){f.headers=g;continue}f.headers||(f.headers=g.map((b,v)=>`col${v}`));let y={};for(let b=0;b<f.headers.length;b++)y[f.headers[b]]=g[b]??"";c.emit(y)}}},{describeKind:"derived",...i})}function Gd(t,e){return K([t],(n,r,o)=>{let s=n[0];if(s==null||s.length===0)return;let i=o.store;typeof i.buffer!="string"&&(i.buffer="");for(let a of s){i.buffer=i.buffer+a;let u=i.buffer.split(/\r?\n/);i.buffer=u.pop()??"";for(let c of u)if(c.trim())try{r.emit(JSON.parse(c))}catch(d){r.down([[M,d]]);return}}},{describeKind:"derived",...e??{}})}function Fd(t,e){let n=[],r="",o=!1;for(let s=0;s<t.length;s++){let i=t[s];o?i==='"'?t[s+1]==='"'?(r+='"',s++):o=!1:r+=i:i==='"'?o=!0:i===e?(n.push(r),r=""):r+=i}return n.push(r),n}function $d(t,e){return W(n=>{let r=!1;return(async()=>{try{let s="";for await(let i of t){if(r)return;s+=i;let a=s.split(/\r?\n/);s=a.pop()??"";for(let u of a){if(r)return;let c=u.trim();c&&n.emit(JSON.parse(c))}}!r&&s.trim()&&n.emit(JSON.parse(s.trim())),r||n.down([[_]])}catch(s){r||n.down([[M,s]])}})(),()=>{r=!0}},ct(e))}function Bd(t,e,n){let{intervalNs:r=5*1e9,format:o="JSONEachRow",signal:s,maxConsecutiveErrors:i=1}=n??{},a=Math.ceil(r/1e6),u=0;return be(et(0,{period:a,signal:s}),()=>W(c=>{let d=!0;return(async()=>{try{let f=await t.query({query:e,format:o});if(!d)return;let p=await f.json();if(!d)return;for(let m of p)c.emit(m);u=0,c.down([[_]])}catch(f){if(!d)return;u+=1,u>=i&&c.down([[M,f]])}})(),()=>{d=!1}}))}function jd(t,e){let{autoAck:n=!0,deserialize:r=a=>{try{return JSON.parse(a.toString())}catch{return a.toString()}},onAckError:o,...s}=e??{},i=a=>{if(o)try{o(a instanceof Error?a:new Error(String(a)))}catch{}};return W(a=>{let u=!0;return(async()=>{for(;u;)try{let d=await t.receive();if(!u)return;let l={topic:d.getTopicName(),messageId:d.getMessageId().toString(),key:d.getPartitionKey(),value:r(d.getData()),properties:d.getProperties(),publishTime:d.getPublishTimestamp(),eventTime:d.getEventTimestamp(),timestampNs:pe()};if(n)a.emit(l),t.acknowledge(d).catch(i);else{let f=!1,p={value:l,ack(){f||(f=!0,t.acknowledge(d).catch(i))},nack(m){if(f)return;f=!0;let h=t;try{let g=h.negativeAcknowledge?.(d);g&&typeof g.then=="function"&&g.catch(i)}catch(g){i(g)}}};a.emit(p)}}catch(d){u&&a.down([[M,d]]);return}})(),()=>{u=!1}},ct(s))}function Vd(t,e,n){let{serialize:r=a=>Buffer.from(JSON.stringify(a)),keyExtractor:o,propertiesExtractor:s,onTransportError:i}=n??{};return $e(t,{onTransportError:i,send:async a=>{await e.send({data:r(a),partitionKey:o?.(a),properties:s?.(a)})}})}function Kd(t,e,n){let r=new TextDecoder,{queue:o,deserialize:s=a=>{let u=r.decode(a);try{return JSON.parse(u)}catch{return u}},...i}=n??{};return W(a=>{let u=!0,c=t.subscribe(e,o?{queue:o}:void 0);return(async()=>{try{for await(let l of c){if(!u)return;let f={};if(l.headers)for(let p of l.headers.keys())f[p]=l.headers.get(p);a.emit({subject:l.subject,data:s(l.data),headers:f,reply:l.reply,sid:l.sid,timestampNs:pe()})}u&&a.down([[_]])}catch(l){u&&a.down([[M,l]])}})(),()=>{u=!1}},ct(i))}function Hd(t,e,n,r){let o=new TextEncoder,{serialize:s=a=>o.encode(JSON.stringify(a)),onTransportError:i}=r??{};return $e(t,{onTransportError:i,send:a=>{e.publish(n,s(a))}})}function Wd(t,e,n){let{autoAck:r=!0,deserialize:o=u=>{try{return JSON.parse(u.toString())}catch{return u.toString()}},onAckError:s,...i}=n??{},a=u=>{if(s)try{s(u instanceof Error?u:new Error(String(u)))}catch{}};return W(u=>{let c=!0,d;return(async()=>{try{d=(await t.consume(e,p=>{if(!c)return;if(p===null){c&&u.down([[M,new Error("Consumer cancelled by broker")]]);return}let m={queue:e,routingKey:p.fields.routingKey,exchange:p.fields.exchange,content:o(p.content),properties:p.properties,deliveryTag:p.fields.deliveryTag,redelivered:p.fields.redelivered,timestampNs:pe()};if(r){u.emit(m);try{t.ack(p)}catch(h){a(h)}}else{let h=!1,g=t,y={value:m,ack(){if(!h){h=!0;try{t.ack(p)}catch(b){a(b)}}},nack(b){if(h)return;h=!0;let v=b?.requeue;if(!g.nack){a(new Error("RabbitMQ channel does not expose `nack`; cannot negative-ack"));return}try{g.nack(p,!1,v)}catch(T){a(T)}}};u.emit(y)}},{noAck:!1})).consumerTag}catch(f){c&&u.down([[M,f]])}})(),()=>{c=!1,d!==void 0&&t.cancel(d)}},ct(i))}function qd(t,e,n,r){let{serialize:o=a=>Buffer.from(JSON.stringify(a)),routingKeyExtractor:s=()=>"",onTransportError:i}=r??{};return $e(t,{onTransportError:i,send:a=>{let u=s(a),c=o(a);e.publish(n,u,c)}})}function Xi(t,e,n){let{serialize:r=l=>`${JSON.stringify(l)}
26
+ `,flushIntervalMs:o=0,batchSize:s=Number.POSITIVE_INFINITY,onTransportError:i,mode:a}=n??{},c=o>0||s<Number.POSITIVE_INFINITY?$e(t,{onTransportError:i,batchSize:s,flushIntervalMs:o,serialize:r,sendBatch:l=>{e.write(l.join(""))}}):$e(t,{onTransportError:i,serialize:r,send:l=>{e.write(l)}}),d=c.dispose;return c.dispose=()=>{d();try{e.end()}catch{}},c}function zi(t,e){return t.includes(e)||t.includes('"')||t.includes(`
27
+ `)?`"${t.replace(/"/g,'""')}"`:t}function Ud(t,e,n){let{columns:r,delimiter:o=",",writeHeader:s=!0,cellExtractor:i=(p,m)=>String(p[m]??""),flushIntervalMs:a=0,batchSize:u=Number.POSITIVE_INFINITY,onTransportError:c,...d}=n,l=!1;return Xi(t,e,{serialize:p=>{if(!l&&s){l=!0;let m=r.map(g=>zi(g,o)).join(o),h=r.map(g=>zi(i(p,g),o)).join(o);return`${m}
27
28
  ${h}
28
- `}return`${r.map(m=>Vi(i(p,m),o)).join(o)}
29
- `},flushIntervalMs:a,batchSize:u,onTransportError:c,...d})}function Sd(t,e,n,r){let{batchSize:o=1e3,flushIntervalMs:s=5e3,format:i="JSONEachRow",transform:a=c=>c,onTransportError:u}=r??{};return Ge(t,{onTransportError:u,batchSize:o,flushIntervalMs:s,serialize:a,sendBatch:async c=>{await e.insert({table:n,values:c,format:i})}})}function Nd(t,e,n,r){let{format:o="ndjson",keyGenerator:s=(f,p)=>{let m=Math.floor(p/1e6);return`data/${new Date(m).toISOString().replace(/[:.]/g,"-")}-${f}.${o==="ndjson"?"ndjson":"json"}`},batchSize:i=1e3,flushIntervalMs:a=1e4,transform:u=f=>f,onTransportError:c}=r??{},d=o==="ndjson"?"application/x-ndjson":"application/json",l=0;return Ge(t,{onTransportError:c,batchSize:i,flushIntervalMs:a,serialize:u,sendBatch:async f=>{l+=1;let p=o==="ndjson"?`${f.map(h=>JSON.stringify(h)).join(`
29
+ `}return`${r.map(m=>zi(i(p,m),o)).join(o)}
30
+ `},flushIntervalMs:a,batchSize:u,onTransportError:c,...d})}function zd(t,e,n,r){let{batchSize:o=1e3,flushIntervalMs:s=5e3,format:i="JSONEachRow",transform:a=c=>c,onTransportError:u}=r??{};return $e(t,{onTransportError:u,batchSize:o,flushIntervalMs:s,serialize:a,sendBatch:async c=>{await e.insert({table:n,values:c,format:i})}})}function Jd(t,e,n,r){let{format:o="ndjson",keyGenerator:s=(f,p)=>{let m=Math.floor(p/1e6);return`data/${new Date(m).toISOString().replace(/[:.]/g,"-")}-${f}.${o==="ndjson"?"ndjson":"json"}`},batchSize:i=1e3,flushIntervalMs:a=1e4,transform:u=f=>f,onTransportError:c}=r??{},d=o==="ndjson"?"application/x-ndjson":"application/json",l=0;return $e(t,{onTransportError:c,batchSize:i,flushIntervalMs:a,serialize:u,sendBatch:async f=>{l+=1;let p=o==="ndjson"?`${f.map(h=>JSON.stringify(h)).join(`
30
31
  `)}
31
- `:JSON.stringify(f),m=s(l,pe());await e.putObject({Bucket:n,Key:m,Body:p,ContentType:d})}})}function Ed(t,e,n,r){let{toSQL:o=(i,a)=>({sql:`INSERT INTO "${a.replace(/"/g,'""')}" (data) VALUES ($1)`,params:[JSON.stringify(i)]}),onTransportError:s}=r??{};return Ge(t,{onTransportError:s,serialize:i=>o(i,n),send:async i=>{let a=i;await e.query(a.sql,a.params)}})}function _d(t,e,n){let{toDocument:r=s=>s,onTransportError:o}=n??{};return Ge(t,{onTransportError:o,serialize:r,send:async s=>{await e.insertOne(s)}})}function Md(t,e,n){let{labels:r={},toLine:o=a=>JSON.stringify(a),toLabels:s,onTransportError:i}=n??{};return Ge(t,{onTransportError:i,serialize:a=>({line:o(a),labels:s?{...r,...s(a)}:r}),send:async a=>{let{line:u,labels:c}=a,d=`${pe()}`;await e.push({streams:[{stream:c,values:[[d,u]]}]})}})}function Od(t,e,n){let{toResourceSpans:r=s=>[s],onTransportError:o}=n??{};return Ge(t,{onTransportError:o,serialize:r,send:async s=>{await e.push({resourceSpans:s})}})}function Cd(t,e,n,r){let{prefix:o="checkpoints/",debounceMs:s=500,compactEvery:i=10,onError:a}=r??{},u={debounceMs:s,compactEvery:i,save(c,d){let l=Math.floor(pe()/1e6),f=`${o}${t.name}/checkpoint-${l}.json`,p;try{p=JSON.stringify(d)}catch(m){a?.(m);return}e.putObject({Bucket:n,Key:f,Body:p,ContentType:"application/json"}).catch(m=>a?.(m))},load(){return null}};return t.attachStorage([u],{onError:c=>a?.(c)})}function Ad(t,e,n){let{prefix:r="graphrefly:checkpoint:",debounceMs:o=500,compactEvery:s=10,onError:i}=n??{},a=`${r}${t.name}`,u={debounceMs:o,compactEvery:s,save(c,d){let l;try{l=JSON.stringify(d)}catch(f){i?.(f);return}e.set(a,l).catch(f=>i?.(f))},async load(){let c=await e.get(a);if(c==null)return null;try{return JSON.parse(c)}catch{return null}}};return t.attachStorage([u],{onError:c=>i?.(c)})}function Ld(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return H(i=>{try{let u=t.query(e,o).map(r);i.emit(u),i.down([[M]])}catch(a){i.down([[O,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...s})}function Id(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return H(i=>{try{let a=t.iterate(e,o);ee(()=>{for(let u of a)i.emit(r(u));i.down([[M]])})}catch(a){i.down([[O,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...s})}function Pd(t,e,n,r){if(n.includes("\0")||n.length===0)throw new Error(`toSqlite: invalid table name: ${JSON.stringify(n)}`);let{toSQL:o=(C,K)=>({sql:`INSERT INTO "${K.replace(/"/g,'""')}" (data) VALUES (?)`,params:[JSON.stringify(C)]}),onTransportError:s,batchInsert:i=!1,maxBatchSize:a=1e3,flushIntervalMs:u=0}=r??{},c=C=>o(C,n);if(!i)return Ge(t,{onTransportError:s,serialize:c,send:C=>{let K=C;e.query(K.sql,K.params)}});let d=N(null),l=N(void 0,{equals:()=>!1}),f=N(null),p=N(0),m=N(0),h=C=>{try{s?.(C)}catch{}try{d.down([[R,C]])}catch{}},g=[],y=!1,b,v=!1,T=()=>m.down([[R,g.length]]),w=C=>{v||l.down([[R,C]])},k=C=>{v||f.down([[R,C]])},x=C=>{v||p.down([[R,C]])},S=C=>{v||h(C)},_=()=>{if(g.length===0||y)return;y=!0,x(1);try{e.query("BEGIN",[])}catch(P){y=!1,x(0),S({stage:"send",error:P instanceof Error?P:new Error(String(P)),value:void 0});return}let C=g;g=[],T();let K,ne=0;for(let P of C)try{e.query(P.query.sql,P.query.params),ne+=1}catch(E){K=E instanceof Error?E:new Error(String(E));break}if(K){try{e.query("ROLLBACK",[])}catch{}S({stage:"send",error:K,value:void 0});for(let P of C)k({value:P.value,error:K,attempts:1})}else try{e.query("COMMIT",[]);for(let P of C)w(P.value)}catch(P){let E=P instanceof Error?P:new Error(String(P));S({stage:"send",error:E,value:void 0});for(let I=0;I<ne;I++)k({value:C[I].value,error:E,attempts:1})}y=!1,x(0)},F=()=>{u>0&&b===void 0&&!v&&(b=setTimeout(()=>{b=void 0,_()},u))},L=t.subscribe(C=>{for(let K of C){let ne=K[0];if(ne===R){let P=K[1],E;try{E=c(P)}catch(I){let G=I instanceof Error?I:new Error(String(I));h({stage:"serialize",error:G,value:P}),f.down([[R,{value:P,error:G,attempts:0}]]);continue}g.push({value:P,query:E}),T(),g.length>=a?_():F()}else Me.messageTier(ne)>=3&&_()}});return{dispose:()=>{if(!v){b!==void 0&&(clearTimeout(b),b=void 0),_(),v=!0,L();for(let C of[d,l,f,p,m])try{C.down([[de]])}catch{}}},sent:l,failed:f,inFlight:p,errors:d,buffered:m,flush:async()=>{v||_()}}}function Dd(t,e){let{args:n,mapRow:r=s=>s,...o}=e??{};return H(s=>{let i=!0;return t.findMany(n).then(a=>{i&&(s.emit(a.map(r)),s.down([[M]]))}).catch(a=>{if(i)try{s.down([[O,a instanceof Error?a:new Error(String(a))]])}catch{}}),()=>{i=!1}},{...o,describeKind:"producer",completeWhenDepsComplete:!1})}function Gd(t,e){let{mapRow:n=o=>o,...r}=e??{};return H(o=>{let s=!0;return t.execute().then(i=>{s&&(o.emit(i.map(n)),o.down([[M]]))}).catch(i=>{if(s)try{o.down([[O,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{s=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}function Fd(t,e){let{mapRow:n=o=>o,...r}=e??{};return H(o=>{let s=!0;return t.execute().then(i=>{s&&(o.emit(i.map(n)),o.down([[M]]))}).catch(i=>{if(s)try{o.down([[O,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{s=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}Ln();ie();le();function zi(){let t=new Map,e=null,n=null;function r(s){s.prev?s.prev.next=s.next:e=s.next,s.next?s.next.prev=s.prev:n=s.prev,s.prev=null,s.next=null}function o(s){s.next=e,s.prev=null,e&&(e.prev=s),e=s,n===null&&(n=s)}return{insert(s){if(t.has(s)){this.touch(s);return}let i={key:s,prev:null,next:null};t.set(s,i),o(i)},touch(s){let i=t.get(s);i&&(r(i),o(i))},delete(s){let i=t.get(s);i&&(r(i),t.delete(s))},evict(s){let i=[];for(let a=0;a<s&&n!==null;a++){let u=n;i.push(u.key),r(u),t.delete(u.key)}return i},size(){return t.size}}}function $d(t){return t!=null&&typeof t.then=="function"}function Vn(t){$d(t)&&t.catch(()=>{})}function Bd(t,e){let n=new Map,r=e?.maxSize??0,o=r>0?e?.eviction??zi():null,s=e?.writeThrough??!1;function i(c,d,l){for(let f=0;f<l;f++)try{Vn(t[f].save(c,d))}catch{}}function a(c,d,l=0){for(let f=l;f<t.length;f++){let p;try{p=t[f].load(c)}catch{continue}if($d(p)){let m=f;p.then(h=>{h!=null?(d.down([[R,h]]),i(c,h,m)):a(c,d,m+1)},()=>{a(c,d,m+1)});return}if(p!=null){d.down([[R,p]]),i(c,p,f);return}}}function u(){if(!(!o||r<=0))for(;o.size()>=r;){let c=o.evict(1);if(c.length===0)break;for(let d of c){let l=n.get(d);if(l){let f=l.cache;if(l.status!=="sentinel"&&t.length>0){let p=t.length-1;try{Vn(t[p].save(d,f))}catch{}for(let m=0;m<p;m++)try{let h=t[m].clear;h&&Vn(h.call(t[m],d))}catch{}}l.down([[de]])}n.delete(d)}}}return{load(c){let d=n.get(c);if(d)return o?.touch(c),d;o&&r>0&&o.size()>=r&&u();let l=N(void 0);return n.set(c,l),o?.insert(c),a(c,l),l},save(c,d){if(s)for(let f of t)try{Vn(f.save(c,d))}catch{}else if(t[0])try{Vn(t[0].save(c,d))}catch{}let l=n.get(c);if(l)l.down([[R,d]]),o?.touch(c);else{o&&r>0&&o.size()>=r&&u();let f=N(d);n.set(c,f),o?.insert(c)}},invalidate(c){let d=n.get(c);d&&a(c,d)},delete(c){o?.delete(c);let d=n.get(c);d&&d.down([[de]]),n.delete(c);for(let l of t)try{let f=l.clear;f&&Vn(f.call(l,c))}catch{}},has(c){return n.has(c)},get size(){return n.size}}}Se();ie();le();Se();Te();ie();le();var Er=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,i]of e)this._store.has(s)&&this._store.delete(s),this._store.set(s,{value:i,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=B(),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=B(),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 B()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??B())>=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 tt(t={}){let{name:e,maxSize:n,defaultTtl:r,versioning:o,backend:s}=t,i=s??new Er({maxSize:n,defaultTtl:r}),a=N(i.toMap(),{name:e,describeKind:"state",equals:(d,l)=>d===l,...o!=null?{versioning:o}:{}});function u(){let d=i.toMap();ee(()=>{a.down([[Z]]),a.down([[R,d]])})}function c(d){let l=i.version;try{return d()}finally{i.version!==l&&u()}}return{entries:a,has(d){return c(()=>i.has(d))},get(d){return c(()=>i.get(d))},set(d,l,f){c(()=>i.set(d,l,f?.ttl))},setMany(d,l){c(()=>i.setMany(d,l?.ttl))},delete(d){c(()=>i.delete(d))},deleteMany(d){c(()=>i.deleteMany(d))},clear(){c(()=>i.clear())},pruneExpired(){c(()=>i.pruneExpired())},get size(){return i.size},dispose(){}}}$e();function If(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function Vd(t,e,n){let r=re(t),o=r.v!=null,s=N(n?.initialVerified??null,{...o?{meta:{sourceVersion:null}}:{}}),i=n?.trigger!==void 0&&n.trigger!==null,a=null;if(i&&n?.autoVerify?a=ft(re(n.trigger),r):i?a=re(n.trigger):n?.autoVerify&&(a=r),a!==null){let u;if(a===r)u=_e(r,c=>e(c));else{let c=r.cache;r.subscribe(d=>{for(let l of d)l[0]===R&&(c=l[1])}),u=_e(a,()=>e(c))}It(u,c=>{ee(()=>{if(s.down([[R,c]]),o){let d=r.v;d!=null&&s.meta.sourceVersion.down([[R,{id:d.id,version:d.version}]])}})})}return{node:r,verified:s,trigger:a}}function jd(t){t.subscribe(()=>{})}function _r(t){return t instanceof Map?t:new Map}function Kd(t,e){if(!Array.isArray(e.upsert))throw new TypeError("distill extraction requires upsert: Array<{ key, value }>");ee(()=>{for(let{key:n,value:r}of e.upsert)t.set(n,r);for(let n of e.remove??[])t.delete(n)})}function Uo(t,e,n){let r=re(t),o=tt(n.mapOptions??{}),s=n.budget??2e3,a=n.context!==void 0&&n.context!==null?re(n.context):N(null),u=_r(o.entries.cache);o.entries.subscribe(p=>{for(let m of p)m[0]===R&&(u=_r(m[1]))});let c=_e(r,p=>e(p,u));if(It(c,p=>{Kd(o,p)}),n.evict){let p=new Map,m=A([o.entries],([h])=>{let g=[],y=_r(h);for(let b of p.keys())y.has(b)||(p.get(b)(),p.delete(b));for(let[b,v]of y){let T=n.evict(b,v);if(If(T)){if(!p.has(b)){let w=It(T,k=>{k===!0&&o.has(b)&&o.delete(b)});p.set(b,w)}continue}if(typeof T=="boolean"){T&&g.push(b);continue}throw new TypeError("distill evict() must return boolean or Node<boolean>")}return g});It(m,h=>{for(let g of h)o.delete(g)})}let d=n.consolidateTrigger!==void 0&&n.consolidateTrigger!==null;if(n.consolidate&&d){let p=re(n.consolidateTrigger),m=_e(p,()=>n.consolidate(u));It(m,h=>{Kd(o,h)})}let l=A([o.entries,a],([p,m])=>{let h=[..._r(p).entries()].map(([b,v])=>({key:b,value:v,score:n.score(v,m),cost:n.cost(v)}));h.sort((b,v)=>v.score-b.score);let g=[],y=s;for(let b of h)b.cost<=y&&(g.push({key:b.key,value:b.value,score:b.score}),y-=b.cost);return g}),f=A([o.entries],([p])=>_r(p).size);return jd(l),jd(f),{store:o,compact:l,size:f}}pi();Se();ie();we();var Mr=class{_version=0;_topics=new Set;get version(){return this._version}get topicCount(){return this._topics.size}hasTopic(e){return this._topics.has(e)}topicNames(){return this._topics.values()}createTopic(e){return this._topics.has(e)?!1:(this._topics.add(e),this._version+=1,!0)}removeTopic(e){let n=this._topics.delete(e);return n&&(this._version+=1),n}};function qd(t={}){let{backend:e}=t,n=e??new Mr,r=new Map;function o(s){let i=r.get(s);return i===void 0&&(i=q({describeKind:"state"}),r.set(s,i),n.createTopic(s)),i}return{topic(s){return o(s)},publish(s,i){o(s).emit(i)},publishMany(s){ee(()=>{for(let[i,a]of s)o(i).emit(a)})},removeTopic(s){let i=r.get(s);return i===void 0?!1:(r.delete(s),n.removeTopic(s),i.down([[de]]),!0)},has(s){return n.hasTopic(s)},get size(){return n.topicCount},topicNames(){return n.topicNames()}}}Se();ie();le();function Hd(t,e){if(t===e)return 0;let n=typeof t;if(n===typeof e&&(n==="number"||n==="string"||n==="boolean"||n==="bigint")){let o=t,s=e;return o<s?-1:o>s?1:0}return String(t).localeCompare(String(e))}function Pf(t,e){let n=Hd(t[0],e[0]);return n!==0?n:Hd(t[1],e[1])}function Wd(t){return[t.secondary,t.primary]}function qn(t,e){let n=Wd(e),r=0,o=t.length;for(;r<o;){let s=r+o>>1;Pf(n,Wd(t[s]))>0?r=s+1:o=s}return r}var Or=class{_version=0;_buf=[];_byPrimary=new Map;get version(){return this._version}get size(){return this._buf.length}has(e){return this._byPrimary.has(e)}get(e){return this._byPrimary.get(e)?.value}upsert(e,n,r,o){let s=this._byPrimary.get(e),i={primary:e,secondary:n,value:r};if(s!==void 0&&o?.equals?.(s,i))return!1;if(s!==void 0){let u=qn(this._buf,s);this._buf.splice(u,1)}let a=qn(this._buf,i);return this._buf.splice(a,0,i),this._byPrimary.set(e,i),this._version+=1,s===void 0}upsertMany(e,n){let r=0;try{for(let o of e){let s=this._byPrimary.get(o.primary),i={primary:o.primary,secondary:o.secondary,value:o.value};if(s!==void 0&&n?.equals?.(s,i))continue;if(s!==void 0){let u=qn(this._buf,s);this._buf.splice(u,1)}let a=qn(this._buf,i);this._buf.splice(a,0,i),this._byPrimary.set(o.primary,i),r+=1}}finally{r>0&&(this._version+=1)}return r}delete(e){let n=this._byPrimary.get(e);if(n===void 0)return!1;let r=qn(this._buf,n);return this._buf.splice(r,1),this._byPrimary.delete(e),this._version+=1,!0}deleteMany(e){let n=0;try{for(let r of e){let o=this._byPrimary.get(r);if(o===void 0)continue;let s=qn(this._buf,o);this._buf.splice(s,1),this._byPrimary.delete(r),n+=1}}finally{n>0&&(this._version+=1)}return n}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._byPrimary.clear(),this._version+=1,e)}toArray(){return[...this._buf]}toPrimaryMap(){let e=new Map;for(let n of this._buf)e.set(n.primary,n.value);return e}};function Df(t){return t.subscribe(()=>{})}function Ud(t={}){let{name:e,versioning:n,equals:r,backend:o}=t,s=o??new Or;function i(p){return p?.equals!==void 0||r===void 0?p:{...p,equals:r}}let a=N([],{name:e,describeKind:"state",equals:(p,m)=>p===m,...n!=null?{versioning:n}:{}}),u=A([a],([p])=>{let m=p,h=new Map;for(let g of m)h.set(g.primary,g.value);return h},{initial:s.toPrimaryMap(),describeKind:"derived"}),c=Df(u),d=!1;function l(){let p=s.toArray();ee(()=>{a.down([[Z]]),a.down([[R,p]])})}function f(p){let m=s.version;try{return p()}finally{s.version!==m&&l()}}return{ordered:a,byPrimary:u,has(p){return s.has(p)},get(p){return s.get(p)},get size(){return s.size},upsert(p,m,h,g){return f(()=>s.upsert(p,m,h,i(g)))},upsertMany(p,m){let h=[...p];h.length!==0&&f(()=>s.upsertMany(h,i(m)))},delete(p){f(()=>s.delete(p))},deleteMany(p){let m=[...p];m.length!==0&&f(()=>s.deleteMany(m))},clear(){f(()=>s.clear())},dispose(){d||(d=!0,c())}}}Se();ie();le();var Cr=class{_version=0;_buf;constructor(e){this._buf=e?[...e]:[]}get version(){return this._version}get size(){return this._buf.length}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._buf.length+e;if(!(n<0||n>=this._buf.length))return this._buf[n]}append(e){this._buf.push(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._buf.length;this._buf.length=n+e.length;for(let r=0;r<e.length;r++)this._buf[n+r]=e[r];this._version+=1}insert(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insert: index ${e} out of range [0, ${this._buf.length}]`);this._buf.splice(e,0,n),this._version+=1}insertMany(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insertMany: index ${e} out of range [0, ${this._buf.length}]`);n.length!==0&&(this._buf.splice(e,0,...n),this._version+=1)}pop(e){if(this._buf.length===0)throw new RangeError("pop from empty list");if(!Number.isInteger(e))throw new RangeError(`pop: index ${e} must be an integer`);let n=e>=0?e:this._buf.length+e;if(n<0||n>=this._buf.length)throw new RangeError(`pop: index ${e} out of range`);let[r]=this._buf.splice(n,1);return this._version+=1,r}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._version+=1,e)}toArray(){return[...this._buf]}};function zo(t,e={}){let{name:n,versioning:r,backend:o}=e,s=o??new Cr(t),i=N(s.toArray(),{name:n,describeKind:"state",equals:(c,d)=>c===d,...r!=null?{versioning:r}:{}});function a(){let c=s.toArray();ee(()=>{i.down([[Z]]),i.down([[R,c]])})}function u(c){let d=s.version;try{return c()}finally{s.version!==d&&a()}}return{items:i,get size(){return s.size},at(c){return s.at(c)},append(c){u(()=>s.append(c))},appendMany(c){u(()=>s.appendMany(c))},insert(c,d){u(()=>s.insert(c,d))},insertMany(c,d){u(()=>s.insertMany(c,d))},pop(c=-1){return u(()=>s.pop(c))},clear(){u(()=>s.clear())},dispose(){}}}vt();ie();$e();function Jo(t,e={}){let n=e.keyFn??(o=>String(o)),r=new Map;return o=>{let s=n(o),i=r.get(s);if(i)return i;let a=t(o),u;a!=null&&typeof a.then=="function"?u=Promise.resolve(a):a!=null&&typeof a=="object"&&"subscribe"in a&&"cache"in a?u=$n(a):a!=null&&typeof a=="object"&&Symbol.asyncIterator in a?u=(async()=>{let l=a[Symbol.asyncIterator]();try{let{value:f,done:p}=await l.next();if(p)throw new Error("singleFromAny: factory returned empty async iterable");return f}finally{await l.return?.()}})():a!=null&&typeof a=="object"&&Symbol.iterator in a?u=(async()=>{let l=a[Symbol.iterator]();try{let{value:f,done:p}=l.next();if(p)throw new Error("singleFromAny: factory returned empty iterable");return f}finally{l.return?.()}})():u=Promise.resolve(a);let c,d=()=>{r.get(s)===c&&r.delete(s)};return c=u.then(l=>(d(),l),l=>{throw d(),l}),r.set(s,c),c}}function zd(t,e={}){let n=e.keyFn??(o=>String(o)),r=new Map;return o=>{let s=n(o),i=r.get(s);if(i)return i;let a=re(t(o));r.set(s,a);let u=a.subscribe(c=>{for(let d of c)if(d[0]===O||d[0]===M){r.get(s)===a&&r.delete(s),u();return}});return a}}$e();function Ar(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(Ar);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=Ar(e[o]);return r}function Jd(t){return JSON.stringify(Ar(t),void 0,0)}function Lr(){let t=new Map;return{save(e,n){t.set(e,JSON.parse(JSON.stringify(n)))},load(e){let n=t.get(e);return n===void 0?null:JSON.parse(JSON.stringify(n))},clear(e){t.delete(e)},list(){return[...t.keys()].sort()}}}function Yd(t){return{save(e,n){t[e]=JSON.parse(JSON.stringify(n))},load(e){let n=t[e];return n===void 0?null:JSON.parse(JSON.stringify(n))},clear(e){delete t[e]},list(){return Object.keys(t).sort()}}}ie();we();le();function Ir(t,e,n,r){let o=new z(t,r);o.add(e,{name:"source"});let s=N(n,{meta:{kind:"stratify_rules"}});o.add(s,{name:"rules"});for(let i of n)Gf(o,e,s,i);return o}function Gf(t,e,n,r){let o=`branch/${r.name}`,s=Symbol("noValue"),i=!1,a=!1,u=!1,c=s,d=!1,l=n.cache??[];function f(h){if(u){u=!1;let g=c;if(c=s,g!==s){let y=l.find(v=>v.name===r.name),b=!1;try{b=y?.classify(g)??!1}catch{b=!1}b?(d=!1,h.emit(g)):d&&(d=!1,h.down([[Z],[$]]))}else d?(d=!1,h.down([[Z],[$]])):h.down([[$]])}}let p=q([],(h,g)=>{let y=e.subscribe(v=>{for(let T of v)m(T,0,g)}),b=n.subscribe(v=>{for(let T of v)m(T,1,g)});return()=>{y(),b()}},{describeKind:"derived",meta:{kind:"stratify_branch",branch:r.name},completeWhenDepsComplete:!1});function m(h,g,y){let b=h[0];return b===Z?(g===0?(i=!0,d=!0):a=!0,!0):b===R||b===$?(g===0?(i=!1,u=!0,c=b===R?h[1]:s):(b===R&&(l=h[1]),a=!1),i||a||f(y),!0):b===M||b===O||b===de?(i=!1,a=!1,u=!1,c=s,d=!1,g===0&&y.down([h]),!0):g===1}if(t.add(p,{name:o}),r.ops){let h=r.ops(p),g=`branch/${r.name}/out`;t.add(h,{name:g})}}lt();Se();ie();we();le();$e();ie();var Ff=new Map([[Ve,"INVALIDATE"],[Ae,"PAUSE"],[Pe,"RESUME"],[de,"TEARDOWN"],[M,"COMPLETE"],[O,"ERROR"]]),$f=new Map([["INVALIDATE",Ve],["PAUSE",Ae],["RESUME",Pe],["TEARDOWN",de],["COMPLETE",M],["ERROR",O]]);function Dt(t){let e=Ff.get(t);return e||(Symbol.keyFor(t)??"UNKNOWN")}function cn(t){let e=$f.get(t);if(e)return e;if(t&&t!=="UNKNOWN")return Symbol.for(t)}function dn(t){return t instanceof Error?{message:t.message,name:t.name,stack:t.stack}:{message:String(t),name:"Error"}}function ln(t){let e=new Error(t.message);return e.name=t.name,t.stack&&(e.stack=t.stack),e}function Gt(t){if(typeof MessagePort<"u"&&t instanceof MessagePort)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),t.start(),()=>t.removeEventListener("message",n)},terminate(){t.close()}};if(typeof SharedWorker<"u"&&t instanceof SharedWorker)return Gt(t.port);if(typeof Worker<"u"&&t instanceof Worker)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),()=>t.removeEventListener("message",n)},terminate(){t.terminate()}};if(typeof BroadcastChannel<"u"&&t instanceof BroadcastChannel)return{post(e,n){n&&n.length>0&&console.warn("[graphrefly] WorkerTransport: BroadcastChannel does not support Transferable objects. The transfer argument is ignored and objects will be cloned instead."),t.postMessage(e)},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),()=>t.removeEventListener("message",n)},terminate(){t.close()}};if(typeof ServiceWorker<"u"&&t instanceof ServiceWorker)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>{r.source===t&&e(r.data)};return navigator.serviceWorker.addEventListener("message",n),()=>navigator.serviceWorker.removeEventListener("message",n)}};throw new Error("createTransport: unsupported target type. Expected Worker, SharedWorker, ServiceWorker, BroadcastChannel, or MessagePort.")}function Bf(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function Ji(t,e){let n=Bf(t)?t:Gt(t),r=e.name??"workerBridge",o=Object.entries(e.expose??{}),s=e.import??[],i=e.transfer??{},a=N("connecting",{name:`${r}::meta::status`}),u=N(null,{name:`${r}::meta::error`}),c=new Map,d=new Map;for(let b of s){let v=N(void 0,{name:`${r}::${b}`});c.set(b,v)}let l;if(o.length>0){let b=o.map(([,w])=>w),v=q(b,(w,k)=>{let x={};for(let S=0;S<o.length;S++){let[_]=o[S],F=w[S];F!=null&&F.length>0&&(x[_]=F.at(-1))}Object.keys(x).length!==0&&k.emit(x)},{name:`${r}::aggregated`});l=fe([v],w=>{let k=w[0];if(k==null||Object.keys(k).length===0)return;let x=[];for(let F of Object.keys(k)){let L=i[F];L&&x.push(...L(k[F]))}let S;for(let[F,L]of o)F in k&&L.v!=null&&(S==null&&(S={}),S[F]=L.v.version);let _={t:"b",u:k,...S?{v:S}:{}};try{n.post(_,x.length>0?x:void 0)}catch(F){u.down([[R,F instanceof Error?F:new Error(String(F))]])}}).subscribe(()=>{})}let f=!1,p=n.listen(b=>{if(f)return;let v=b;switch(v.t){case"r":{ee(()=>{for(let[w,k]of Object.entries(v.stores)){let x=c.get(w);x&&x.down([[R,k]])}}),a.down([[R,"connected"]]);let T={};for(let[w,k]of o)T[w]=k.cache;n.post({t:"i",stores:T});break}case"v":{let T=c.get(v.s);T&&T.down([[R,v.d]]);break}case"b":{ee(()=>{for(let[T,w]of Object.entries(v.u)){let k=v.v?.[T];if(k!=null){let S=d.get(T);if(S!=null&&k<=S)continue;d.set(T,k)}let x=c.get(T);x&&x.down([[R,w]])}});break}case"e":{let T=c.get(v.s);T&&T.down([[O,ln(v.err)]]);break}case"s":{let T=cn(v.sig);if(!T)break;let w=v.s==="*"?[...c.values()]:c.has(v.s)?[c.get(v.s)]:[];for(let k of w)k.down(v.d===void 0?[[T]]:[[T,v.d]]);break}}}),m=[];for(let[b,v]of o){let T=v.subscribe((w=>{if(!f)for(let k of w){let x=k[0];x!==R&&(Me.isLocalOnly(x)||(x===O?n.post({t:"e",s:b,err:dn(k[1])}):n.post({t:"s",s:b,sig:Dt(x),d:k.length>1?k[1]:void 0})))}}));m.push(T)}let h;if(e.timeoutMs!=null&&e.timeoutMs>0){let b=et(e.timeoutMs),v=xr(a,w=>w==="connected");h=Ho(ft(kr(b,()=>"timeout"),kr(v,()=>"ready"))).subscribe(w=>{for(let k of w)k[0]===R&&k[1]==="timeout"&&(u.down([[R,new Error("Worker bridge handshake timeout")]]),g())})}function g(){if(!f){f=!0,h?.(),n.post({t:"s",s:"*",sig:Dt(de)}),l&&l();for(let b of m)b();m.length=0,p(),a.down([[R,"closed"]]),d.clear(),c.clear()}}let y={meta:{status:a,error:u},destroy:g};for(let[b,v]of c)y[b]=v;return y}Se();ie();we();le();function jf(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function Yi(t,e){let n=jf(t)?t:Gt(t),r=e.import??[],o=e.transfer??{},s=new Map,i=new Map,a={};for(let g of r){let y=N(void 0,{name:`worker::${g}`});s.set(g,y),a[g]=y}let u=e.expose(a),c=Object.entries(u),d,l=!1;if(c.length>0){let g=c.map(([,v])=>v),y=q(g,(v,T)=>{let w={};for(let k=0;k<c.length;k++){let[x]=c[k],S=v[k];S!=null&&S.length>0&&(w[x]=S.at(-1))}Object.keys(w).length!==0&&T.emit(w)},{name:"workerSelf::aggregated"});d=fe([y],v=>{if(l)return;let T=v[0];if(T==null||Object.keys(T).length===0)return;let w=[];for(let S of Object.keys(T)){let _=o[S];_&&w.push(..._(T[S]))}let k;for(let[S,_]of c)S in T&&_.v!=null&&(k==null&&(k={}),k[S]=_.v.version);let x={t:"b",u:T,...k?{v:k}:{}};try{n.post(x,w.length>0?w:void 0)}catch{}}).subscribe(()=>{})}let f=[];for(let[g,y]of c){let b=y.subscribe((v=>{if(!l)for(let T of v){let w=T[0];w!==R&&(Me.isLocalOnly(w)||(w===O?n.post({t:"e",s:g,err:dn(T[1])}):n.post({t:"s",s:g,sig:Dt(w),d:T.length>1?T[1]:void 0})))}}));f.push(b)}let p=n.listen(g=>{if(l)return;let y=g;switch(y.t){case"i":{ee(()=>{for(let[b,v]of Object.entries(y.stores)){let T=s.get(b);T&&T.down([[R,v]])}});break}case"v":{let b=s.get(y.s);b&&b.down([[R,y.d]]);break}case"b":{ee(()=>{for(let[b,v]of Object.entries(y.u)){let T=y.v?.[b];if(T!=null){let k=i.get(b);if(k!=null&&T<=k)continue;i.set(b,T)}let w=s.get(b);w&&w.down([[R,v]])}});break}case"e":{let b=s.get(y.s);b&&b.down([[O,ln(y.err)]]);break}case"s":{let b=cn(y.sig);if(!b)break;if(b===de&&y.s==="*"){h();return}let v=y.s==="*"?[...s.values()]:s.has(y.s)?[s.get(y.s)]:[];for(let T of v)T.down(y.d===void 0?[[b]]:[[b,y.d]]);break}}}),m={};for(let[g,y]of c)m[g]=y.cache;n.post({t:"r",stores:m});function h(){if(!l){l=!0,d&&d();for(let g of f)g();f.length=0,p(),n.terminate?.(),i.clear(),s.clear()}}return{destroy:h}}var Ua={};he(Ua,{SNAPSHOT_WIRE_VERSION:()=>zr,SurfaceError:()=>ve,accountability:()=>Rs,ai:()=>ws,asSurfaceError:()=>Vs,cqrs:()=>Io,createGraph:()=>zn,deleteSnapshot:()=>Ys,demoShell:()=>Ns,diffSnapshots:()=>zs,domainTemplates:()=>Ms,graphspec:()=>Os,guarded:()=>As,harness:()=>Is,jobQueue:()=>Gs,layout:()=>Bs,lens:()=>$s,listSnapshots:()=>Js,memory:()=>Qo,messaging:()=>ts,orchestration:()=>ns,reduction:()=>_s,refine:()=>js,resilientPipeline:()=>Ks,restoreSnapshot:()=>Us,runReduction:()=>qs,saveSnapshot:()=>Ws,surface:()=>Qs});var ws={};he(ws,{AgentLoopGraph:()=>bs,AllTiersExhaustedError:()=>Gr,BudgetExhaustedError:()=>ps,ChatStreamGraph:()=>gs,CircuitOpenError:()=>st,FallbackMissError:()=>lm,LLMTimeoutError:()=>Wn,ReplayCacheMissError:()=>mn,ToolRegistryGraph:()=>ys,admissionFilter3D:()=>mh,agentLoop:()=>bh,agentMemory:()=>gh,anthropicAdapter:()=>ta,canonicalJson:()=>us,cascadingLlmAdapter:()=>ya,chatStream:()=>_l,composePricing:()=>Am,computePrice:()=>bl,contentGate:()=>ah,costMeterExtractor:()=>sh,createAdapter:()=>Em,createCapabilitiesRegistry:()=>rm,createPricingRegistry:()=>Om,dryRunAdapter:()=>Nt,dryRunPreset:()=>Hm,fallbackAdapter:()=>oa,fromLLM:()=>Qm,frozenContext:()=>Ym,gatedStream:()=>uh,gaugesAsContext:()=>wh,googleAdapter:()=>sa,graphFromSpec:()=>kh,handoff:()=>dh,keywordFlagExtractor:()=>th,knobsAsTools:()=>Th,llmConsolidator:()=>Cl,llmExtractor:()=>Ol,observableAdapter:()=>_m,openAICompatAdapter:()=>aa,parseRateLimitFromError:()=>ma,promptNode:()=>Br,redactor:()=>ih,registryPricing:()=>Cm,resilientAdapter:()=>qm,streamExtractor:()=>Zm,streamingPromptNode:()=>Xm,suggestStrategy:()=>Rh,systemPromptBuilder:()=>ph,toolCallExtractor:()=>rh,toolRegistry:()=>Ml,toolSelector:()=>lh,validateGraphDef:()=>Al,withBreaker:()=>la,withBudgetGate:()=>fa,withDryRun:()=>Im,withRateLimiter:()=>ga,withReplayCache:()=>ra,withRetry:()=>ba,withTimeout:()=>va,zeroPrice:()=>da});Se();Te();ie();we();le();vt();$e();lt();var Qo={};he(Qo,{collection:()=>Vf,decay:()=>pn,knowledgeGraph:()=>ea,lightCollection:()=>Xi,vectorIndex:()=>Zi});Te();le();function pn(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)}function Qd(t){if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1")}function mt(t){return new Map(t)}function Ue(t){return t.cache??new Map}function Yo(t){return t.cache??[]}function Kf(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 a=t[i]??0,u=e[i]??0;r+=a*u,o+=a*a,s+=u*u}return o===0||s===0?0:r/Math.sqrt(o*s)}function Xi(t={}){let e=t.maxSize,n=t.policy??"fifo";Qd(e);let r=N(new Map,{name:t.name,describeKind:"state"});function o(i){if(e!==void 0)for(;i.size>e;){let a;for(let u of i.values()){if(!a){a=u;continue}let c=n==="lru"?u.lastAccessNs:u.createdAtNs,d=n==="lru"?a.lastAccessNs:a.createdAtNs;c<d&&(a=u)}if(!a)break;i.delete(a.id)}}function s(i){r.emit(i)}return{entries:r,upsert(i,a){let u=B(),c=Ue(r),d=c.get(i),l=mt(c);l.set(i,{id:i,value:a,createdAtNs:d?.createdAtNs??u,lastAccessNs:u}),o(l),s(l)},remove(i){let a=mt(Ue(r));a.delete(i)&&s(a)},clear(){Ue(r).size!==0&&s(new Map)},get(i){let a=Ue(r),u=a.get(i);if(u){if(n==="lru"){let c=B(),d=mt(a);d.set(i,{...u,lastAccessNs:c}),s(d)}return u.value}},has(i){return Ue(r).has(i)}}}function Vf(t,e={}){let n=e.maxSize,r=e.policy??"lru",o=e.decayRate??0,s=e.minScore??0,i=e.score??(()=>1);Qd(n);let a=new z(t),u=N(new Map,{name:"items",describeKind:"state"}),c=A([u],([h])=>{let g=h??new Map,y=B(),b=[...g.values()].map(v=>{let T=(y-v.lastAccessNs)/1e9;return{...v,score:pn(v.baseScore,T,o,s)}});return b.sort((v,T)=>T.score-v.score||T.lastAccessNs-v.lastAccessNs),b},{name:"ranked",describeKind:"derived"}),d=A([u],([h])=>(h??new Map).size,{name:"size",describeKind:"derived",initial:0});c.subscribe(()=>{}),d.subscribe(()=>{}),a.add(u,{name:"items"}),a.add(c,{name:"ranked"}),a.add(d,{name:"size"});function l(h,g){let y=(g-h.lastAccessNs)/1e9;return pn(h.baseScore,y,o,s)}function f(h){if(n!==void 0)for(;h.size>n;){let g=B(),y,b=Number.POSITIVE_INFINITY;for(let v of h.values()){let T=l(v,g);if(T<b){y=v,b=T;continue}if(T===b&&y){let w=r==="lru"?v.lastAccessNs:v.createdAtNs,k=r==="lru"?y.lastAccessNs:y.createdAtNs;w<k&&(y=v)}}if(!y)break;h.delete(y.id)}}function p(h){u.emit(h)}return Object.assign(a,{upsert(h,g,y){let b=B(),v=Ue(u),T=v.get(h),w=y?.score??i(g),k=mt(v);k.set(h,{id:h,value:g,baseScore:w,createdAtNs:T?.createdAtNs??b,lastAccessNs:b}),f(k),p(k)},remove(h){let g=mt(Ue(u));g.delete(h)&&p(g)},clear(){Ue(u).size!==0&&p(new Map)},getItem(h){let g=Ue(u),y=g.get(h);if(y){if(r==="lru"){let b=mt(g);b.set(h,{...y,lastAccessNs:B()}),p(b)}return y}}})}function Zi(t={}){let e=t.backend??"flat",n=t.dimension,r;if(e==="hnsw"&&(r=t.hnswFactory?.(),!r))throw new Error('vectorIndex backend "hnsw" requires an optional dependency adapter; install your HNSW package and provide `hnswFactory`.');let o=N(new Map,{describeKind:"state",name:"vector-index"});function s(a){if(n!==void 0&&a.length!==n)throw new RangeError(`vector dimension mismatch: expected ${n}, got ${a.length}`)}function i(a){o.emit(a)}return{backend:e,entries:o,upsert(a,u,c){s(u);let d=mt(Ue(o));d.set(a,{id:a,vector:[...u],meta:c}),e==="hnsw"&&r.upsert(a,u,c),i(d)},remove(a){let u=mt(Ue(o));u.delete(a)&&(e==="hnsw"&&r.remove(a),i(u))},clear(){Ue(o).size!==0&&(e==="hnsw"&&r.clear(),i(new Map))},search(a,u=5){return s(a),u<=0?[]:e==="hnsw"?r.search(a,u):[...Ue(o).values()].map(d=>({id:d.id,score:Kf(a,d.vector),meta:d.meta})).sort((d,l)=>l.score-d.score).slice(0,u)}}}function ea(t){let e=new z(t),n=N(new Map,{name:"entities",describeKind:"state"}),r=N([],{name:"edges",describeKind:"state"}),o=A([r],([u])=>{let c=u??[],d=new Map;for(let l of c){let f=d.get(l.from)??[];d.set(l.from,Object.freeze([...f,l]))}return d},{name:"adjacency",describeKind:"derived",initial:new Map});o.subscribe(()=>{}),e.add(n,{name:"entities"}),e.add(r,{name:"edges"}),e.add(o,{name:"adjacency"});function s(u){n.emit(u)}function i(u){r.emit(u)}return Object.assign(e,{upsertEntity(u,c){let d=mt(Ue(n));d.set(u,c),s(d)},removeEntity(u){let c=mt(Ue(n)),d=c.delete(u),l=Yo(r),f=l.filter(p=>p.from!==u&&p.to!==u);!d&&f.length===l.length||(s(c),i(f))},link(u,c,d,l=1){let f=`${u}\0${c}\0${d}`,p=Yo(r),m=new Set(p.map(g=>`${g.from}\0${g.to}\0${g.relation}`)),h=[...p];if(m.has(f))for(let g=0;g<h.length;g+=1){let y=h[g];if(y.from===u&&y.to===c&&y.relation===d){h[g]={...y,weight:l};break}}else h.push({from:u,to:c,relation:d,weight:l});i(h)},unlink(u,c,d){let l=Yo(r),f=l.filter(p=>d===void 0?!(p.from===u&&p.to===c):!(p.from===u&&p.to===c&&p.relation===d));f.length!==l.length&&i(f)},related(u,c){return Yo(r).filter(d=>(d.from===u||d.to===u)&&(c===void 0||d.relation===c))}})}var ts={};he(ts,{MessagingHubGraph:()=>es,SubscriptionGraph:()=>Pr,TopicBridgeGraph:()=>Zo,TopicGraph:()=>nt,messagingHub:()=>Hf,subscription:()=>Xd,topic:()=>Rt,topicBridge:()=>Wf});we();var qf=2147483647;function Xo(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function fn(t,e){return Ke("messaging",t,e)}var nt=class extends z{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=je([],{name:"events",maxSize:n.retainedLimit}),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:fn("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(oe(this.latest)),this.hasLatest=A([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:fn("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(oe(this.hasLatest)),this.addDisposer(()=>{this.events.down([[M]])}),this.addDisposer(()=>this._log.disposeAllViews())}publish(e){this._log.append(e)}retained(){return this.events.cache}},Pr=class extends z{source;cursor;available;topic;constructor(e,n,r={}){super(e,r.graph);let o=Xo(r.cursor??0,"subscription cursor");this.topic=n;let s=n.events;this.source=A([s],([i])=>i,{name:"source",describeKind:"derived",meta:fn("subscription_source"),initial:s.cache}),this.add(this.source,{name:"source"}),this.cursor=N(o,{name:"cursor",describeKind:"state",meta:fn("subscription_cursor")}),this.add(this.cursor,{name:"cursor"}),this.available=A([this.source,this.cursor],([i,a])=>{let u=i,c=Math.max(0,Math.trunc(a??0));return u.slice(c)},{name:"available",describeKind:"derived",meta:fn("subscription_available"),initial:[]}),this.add(this.available,{name:"available"}),this.addDisposer(oe(this.source)),this.addDisposer(oe(this.available))}ack(e){let n=this.available.cache,r=e===void 0?n.length:Xo(e,"subscription ack count"),o=Math.min(r,n.length);if(o<=0)return this.cursor.cache;let s=this.cursor.cache+o;return this.cursor.emit(s),s}pull(e,n={}){let r=this.available.cache,o=e===void 0?r.length:Xo(e,"subscription pull limit"),s=r.slice(0,o);return n.ack&&s.length>0&&this.ack(s.length),s}},Zo=class extends z{_sourceSub;_target;bridgedCount;constructor(e,n,r,o={}){super(e,o.graph),this._sourceSub=Xd(`${e}-subscription`,n,{cursor:o.cursor}),this._target=r,this.mount("subscription",this._sourceSub),this.bridgedCount=N(0,{name:"bridgedCount",describeKind:"state",meta:fn("topic_bridge_count")}),this.add(this.bridgedCount,{name:"bridgedCount"});let s=Math.max(1,Xo(o.maxPerPump??qf,"topic bridge maxPerPump")),i=o.map??(u=>u),a=q([this._sourceSub.available],()=>{let u=this._sourceSub.pull(s,{ack:!0});if(u.length===0)return;let c=0;for(let d of u){let l=i(d);l!==void 0&&(this._target.publish(l),c+=1)}if(c>0){let d=this.bridgedCount.cache;this.bridgedCount.emit(d+c)}},{name:"pump",describeKind:"effect",meta:fn("topic_bridge_pump")});this.add(a,{name:"pump"}),this.addDisposer(oe(a))}},es=class extends z{_topics=new Map;_version=0;_defaultTopicOptions;constructor(e,n={}){super(e,n.graph),this._defaultTopicOptions={...n.defaultTopicOptions??{}}}get version(){return this._version}get size(){return this._topics.size}has(e){return this._topics.has(e)}topicNames(){return this._topics.keys()}topic(e,n){let r=this._topics.get(e);if(r===void 0){let o={...this._defaultTopicOptions,...n??{}};r=new nt(e,o),this._topics.set(e,r),this.mount(e,r),this._version+=1}return r}publish(e,n){this.topic(e).publish(n)}publishMany(e){ee(()=>{for(let[n,r]of e)this.topic(n).publish(r)})}subscribe(e,n,r){let o=this.topic(n);return new Pr(e,o,r)}removeTopic(e){if(!this._topics.has(e))return!1;try{this.remove(e)}finally{this._topics.delete(e),this._version+=1}return!0}};function Rt(t,e){return new nt(t,e)}function Hf(t,e){return new es(t,e)}function Xd(t,e,n){return new Pr(t,e,n)}function Wf(t,e,n,r){return new Zo(t,e,n,r)}var ns={};he(ns,{approval:()=>Qf,branch:()=>Yf,gate:()=>Dr,join:()=>Xf,loop:()=>Zf,onFailure:()=>nm,pipeline:()=>Zd,sensor:()=>tm,subPipeline:()=>em,task:()=>Jf});Se();ie();we();le();function St(t,e){if(typeof e=="string")return{node:t.resolve(e),path:e};let n=Uf(t,e);if(!n)throw new Error("orchestration dep node must already be registered in the graph so explicit edges can be recorded; pass a string path or register the node first");return{node:e,path:n}}function Uf(t,e){let n=t.describe(),r=`::${Be}::`;for(let o of Object.keys(n.nodes).sort())if(!o.includes(r))try{if(t.resolve(o)===e)return o}catch{}}function Ft(t,e,n,r){t.add(n,{name:e})}function $t(t,e){return Ke("orchestration",t,e)}function zf(t){let e=r=>{let o=r.trim();return o.length===0?0:Number(o)},n;return typeof t=="string"?n=e(t):t===null?n=0:n=Number(t),Number.isFinite(n)?Math.max(0,Math.trunc(n)):1}function Zd(t,e){return new z(t,e)}function Jf(t,e,n,r){let s=(r?.deps??[]).map(d=>St(t,d)),{deps:i,...a}=r??{},u=(d,l,f)=>{let p=d.map((m,h)=>m!=null&&m.length>0?m.at(-1):f.prevData[h]);l.emit(n(p,f))},c=q(s.map(d=>d.node),u,{...a,name:e,describeKind:"derived",meta:$t("task",r?.meta)});return Ft(t,e,c,s.flatMap(d=>d.path?[d.path]:[])),c}function Yf(t,e,n,r,o){let s=St(t,n),i=A([s.node],([a])=>({branch:r(a)?"then":"else",value:a}),{...o,name:e,meta:$t("branch",o?.meta)});return Ft(t,e,i,s.path?[s.path]:[]),i}function Qf(t,e,n,r,o){let s=St(t,n),i=St(t,r),a=o?.isApproved??(c=>!!c),u=q([s.node,i.node],(c,d,l)=>{let f=c[0],p=c[1],m=p!=null&&p.length>0?p.at(-1):l.prevData[1];if(m===void 0||!a(m)){d.down([[$]]);return}if(f==null||f.length===0){p!=null&&p.length>0&&l.prevData[0]!==void 0?d.emit(l.prevData[0]):d.down([[$]]);return}for(let h of f)d.emit(h)},{...o,name:e,describeKind:"derived",meta:$t("approval",o?.meta)});return Ft(t,e,u,[s.path,i.path].filter(c=>typeof c=="string")),u}function Dr(t,e,n,r){let o=r?.maxPending??1/0;if(o<1&&o!==1/0)throw new RangeError("gate: maxPending must be >= 1");let s=r?.startOpen??!1,i=St(t,n),a=N([],{name:"pending",equals:()=>!1}),u=N(s,{name:"isOpen"}),c=A([a],([w])=>w.length,{name:"count"}),d=[],l=!1,f=s,p=u.subscribe(w=>{for(let k of w)k[0]===R&&(f=k[1])});function m(){a.emit([...d])}function h(w){d.push(w),d.length>o&&d.shift(),m()}function g(w){let k=d.splice(0,w);return m(),k}function y(w){if(l)throw new Error(`gate: ${w}() called after gate was torn down`)}let b=q([i.node],(w,k,x)=>{let S=x.terminalDeps[0];if(S!==void 0){l=!0,d=[],m(),k.down(S===!0?[[M]]:[[O,S]]);return}let _=w[0];if(_==null||_.length===0){k.down([[$]]);return}for(let F of _)f?k.emit(F):(h(F),k.down([[$]]))},{name:e,describeKind:"derived",meta:$t("gate",r?.meta)}),v={node:b,pending:a,count:c,isOpen:u,approve(w=1){y("approve");let k=g(w);for(let x of k){if(l)break;b.emit(x)}},reject(w=1){y("reject"),g(w)},modify(w,k=1){y("modify");let x=[...d],S=g(k);for(let _=0;_<S.length&&!l;_++)b.emit(w(S[_],_,x))},open(){y("open"),ee(()=>{u.emit(!0);let w=g(d.length);for(let k of w){if(l)break;b.emit(k)}})},close(){y("close"),u.emit(!1)}};t.addDisposer(c.subscribe(()=>{})),t.addDisposer(p),Ft(t,e,b,i.path?[i.path]:[]);let T=new z(`${e}_state`);return T.add(a,{name:"pending"}),T.add(u,{name:"isOpen"}),T.add(c,{name:"count"}),t.mount(`${e}_state`,T),v}function Xf(t,e,n,r){let o=n.map(i=>St(t,i)),s=A(o.map(i=>i.node),i=>i,{...r,name:e,meta:$t("join",r?.meta)});return Ft(t,e,s,o.flatMap(i=>i.path?[i.path]:[])),s}function Zf(t,e,n,r,o){let s=St(t,n),i=o?.iterations,a=typeof i=="number"||i===void 0?void 0:St(t,i),u=typeof i=="number"?i:void 0,c=q(a?[s.node,a.node]:[s.node],(d,l,f)=>{let p=d[0],m=p!=null&&p.length>0?p.at(-1):f.prevData[0],h=a?d[1]:void 0,g=u??(a?h!=null&&h.length>0?h.at(-1):f.prevData[1]:1),y=zf(g);for(let b=0;b<y;b+=1)m=r(m,b,l);l.emit(m)},{...o,name:e,describeKind:"derived",meta:$t("loop",o?.meta)});return Ft(t,e,c,[s.path,a?.path].filter(d=>typeof d=="string")),c}function em(t,e,n,r){let o=n instanceof z?n:Zd(e,r);return typeof n=="function"&&n(o),t.mount(e,o),o}function tm(t,e,n,r){let o=q([],()=>{},{...r,name:e,initial:n,describeKind:"producer",meta:$t("sensor",r?.meta)});return Ft(t,e,o,[]),{node:o,push(s){o.emit(s)},error(s){o.down([[O,s]])},complete(){o.down([[M]])}}}function nm(t,e,n,r,o){let s=St(t,n),i=!1,a=q([],(u,c)=>{let d=s.node.subscribe(l=>{for(let f of l){if(i)return;if(f[0]===O)try{c.emit(r(f[1],c))}catch(p){i=!0,c.down([[O,p]])}else c.down([f]),f[0]===M&&(i=!0)}});return()=>d()},{...o,name:e,describeKind:"derived",completeWhenDepsComplete:!1,errorWhenDepsError:!1,meta:$t("onFailure",o?.meta)});return Ft(t,e,a,s.path?[s.path]:[]),a}function rs(t,e){return`${t}::${e}`}function rm(t){let e=new Map,n=new Map,r=o=>{e.set(rs(o.provider,o.id),o);let s=n.get(o.provider);s||(s=new Set,n.set(o.provider,s)),s.add(o.id)};if(t)for(let o of t)r(o);return{register:r,lookup(o,s){let i=e.get(rs(o,s));if(i)return i;let a=n.get(o);if(!a)return;let u;for(let c of a)if(s.startsWith(c)&&(!u||c.length>u.key.length)){let d=e.get(rs(o,c));d&&(u={key:c,cap:d})}return u?.cap},remove(o,s){let i=e.delete(rs(o,s));if(i){let a=n.get(o);a?.delete(s),a&&a.size===0&&n.delete(o)}return i},entries(){return e.values()}}}Te();function ta(t={}){return t.sdk?um(t):am(t)}function os(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:i}=om(t,e?.systemPrompt),a={model:o,messages:i.map(sm),max_tokens:e?.maxTokens??4096};return s&&(a.system=s),e?.temperature!=null&&(a.temperature=e.temperature),e?.tools&&e.tools.length>0&&(a.tools=e.tools.map(im)),e?.maxReasoningTokens!=null&&(a.thinking={type:"enabled",budget_tokens:e.maxReasoningTokens}),e?.cacheHint,r&&(a.stream=!0),e?.providerExtras&&Object.assign(a,e.providerExtras),a}function om(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(`
32
+ `:JSON.stringify(f),m=s(l,pe());await e.putObject({Bucket:n,Key:m,Body:p,ContentType:d})}})}function Yd(t,e,n,r){let{toSQL:o=(i,a)=>({sql:`INSERT INTO "${a.replace(/"/g,'""')}" (data) VALUES ($1)`,params:[JSON.stringify(i)]}),onTransportError:s}=r??{};return $e(t,{onTransportError:s,serialize:i=>o(i,n),send:async i=>{let a=i;await e.query(a.sql,a.params)}})}function Qd(t,e,n){let{toDocument:r=s=>s,onTransportError:o}=n??{};return $e(t,{onTransportError:o,serialize:r,send:async s=>{await e.insertOne(s)}})}function Xd(t,e,n){let{labels:r={},toLine:o=a=>JSON.stringify(a),toLabels:s,onTransportError:i}=n??{};return $e(t,{onTransportError:i,serialize:a=>({line:o(a),labels:s?{...r,...s(a)}:r}),send:async a=>{let{line:u,labels:c}=a,d=`${pe()}`;await e.push({streams:[{stream:c,values:[[d,u]]}]})}})}function Zd(t,e,n){let{toResourceSpans:r=s=>[s],onTransportError:o}=n??{};return $e(t,{onTransportError:o,serialize:r,send:async s=>{await e.push({resourceSpans:s})}})}function el(t,e,n,r){let{prefix:o="checkpoints/",debounceMs:s=500,compactEvery:i=10,onError:a}=r??{},u={debounceMs:s,compactEvery:i,save(c,d){let l=Math.floor(pe()/1e6),f=`${o}${t.name}/checkpoint-${l}.json`,p;try{p=JSON.stringify(d)}catch(m){a?.(m);return}e.putObject({Bucket:n,Key:f,Body:p,ContentType:"application/json"}).catch(m=>a?.(m))},load(){return null}};return t.attachStorage([u],{onError:c=>a?.(c)})}function tl(t,e,n){let{prefix:r="graphrefly:checkpoint:",debounceMs:o=500,compactEvery:s=10,onError:i}=n??{},a=`${r}${t.name}`,u={debounceMs:o,compactEvery:s,save(c,d){let l;try{l=JSON.stringify(d)}catch(f){i?.(f);return}e.set(a,l).catch(f=>i?.(f))},async load(){let c=await e.get(a);if(c==null)return null;try{return JSON.parse(c)}catch{return null}}};return t.attachStorage([u],{onError:c=>i?.(c)})}function nl(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return W(i=>{try{let u=t.query(e,o).map(r);i.emit(u),i.down([[_]])}catch(a){i.down([[M,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...s})}function rl(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return W(i=>{try{let a=t.iterate(e,o);te(()=>{for(let u of a)i.emit(r(u));i.down([[_]])})}catch(a){i.down([[M,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...s})}function ol(t,e,n,r){if(n.includes("\0")||n.length===0)throw new Error(`toSqlite: invalid table name: ${JSON.stringify(n)}`);let{toSQL:o=(C,V)=>({sql:`INSERT INTO "${V.replace(/"/g,'""')}" (data) VALUES (?)`,params:[JSON.stringify(C)]}),onTransportError:s,batchInsert:i=!1,maxBatchSize:a=1e3,flushIntervalMs:u=0}=r??{},c=C=>o(C,n);if(!i)return $e(t,{onTransportError:s,serialize:c,send:C=>{let V=C;e.query(V.sql,V.params)}});let d=N(null),l=N(void 0,{equals:()=>!1}),f=N(null),p=N(0),m=N(0),h=C=>{try{s?.(C)}catch{}try{d.down([[S,C]])}catch{}},g=[],y=!1,b,v=!1,T=()=>m.down([[S,g.length]]),w=C=>{v||l.down([[S,C]])},k=C=>{v||f.down([[S,C]])},x=C=>{v||p.down([[S,C]])},R=C=>{v||h(C)},E=()=>{if(g.length===0||y)return;y=!0,x(1);try{e.query("BEGIN",[])}catch(F){y=!1,x(0),R({stage:"send",error:F instanceof Error?F:new Error(String(F)),value:void 0});return}let C=g;g=[],T();let V,ne=0;for(let F of C)try{e.query(F.query.sql,F.query.params),ne+=1}catch(A){V=A instanceof Error?A:new Error(String(A));break}if(V){try{e.query("ROLLBACK",[])}catch{}R({stage:"send",error:V,value:void 0});for(let F of C)k({value:F.value,error:V,attempts:1})}else try{e.query("COMMIT",[]);for(let F of C)w(F.value)}catch(F){let A=F instanceof Error?F:new Error(String(F));R({stage:"send",error:A,value:void 0});for(let D=0;D<ne;D++)k({value:C[D].value,error:A,attempts:1})}y=!1,x(0)},G=()=>{u>0&&b===void 0&&!v&&(b=setTimeout(()=>{b=void 0,E()},u))},L=t.subscribe(C=>{for(let V of C){let ne=V[0];if(ne===S){let F=V[1],A;try{A=c(F)}catch(D){let I=D instanceof Error?D:new Error(String(D));h({stage:"serialize",error:I,value:F}),f.down([[S,{value:F,error:I,attempts:0}]]);continue}g.push({value:F,query:A}),T(),g.length>=a?E():G()}else Ae.messageTier(ne)>=3&&E()}});return{dispose:()=>{if(!v){b!==void 0&&(clearTimeout(b),b=void 0),E(),v=!0,L();for(let C of[d,l,f,p,m])try{C.down([[de]])}catch{}}},sent:l,failed:f,inFlight:p,errors:d,buffered:m,flush:async()=>{v||E()}}}function sl(t,e){let{args:n,mapRow:r=s=>s,...o}=e??{};return W(s=>{let i=!0;return t.findMany(n).then(a=>{i&&(s.emit(a.map(r)),s.down([[_]]))}).catch(a=>{if(i)try{s.down([[M,a instanceof Error?a:new Error(String(a))]])}catch{}}),()=>{i=!1}},{...o,describeKind:"producer",completeWhenDepsComplete:!1})}function il(t,e){let{mapRow:n=o=>o,...r}=e??{};return W(o=>{let s=!0;return t.execute().then(i=>{s&&(o.emit(i.map(n)),o.down([[_]]))}).catch(i=>{if(s)try{o.down([[M,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{s=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}function al(t,e){let{mapRow:n=o=>o,...r}=e??{};return W(o=>{let s=!0;return t.execute().then(i=>{s&&(o.emit(i.map(n)),o.down([[_]]))}).catch(i=>{if(s)try{o.down([[M,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{s=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}Gn();ie();oe();function Zi(){let t=new Map,e=null,n=null;function r(s){s.prev?s.prev.next=s.next:e=s.next,s.next?s.next.prev=s.prev:n=s.prev,s.prev=null,s.next=null}function o(s){s.next=e,s.prev=null,e&&(e.prev=s),e=s,n===null&&(n=s)}return{insert(s){if(t.has(s)){this.touch(s);return}let i={key:s,prev:null,next:null};t.set(s,i),o(i)},touch(s){let i=t.get(s);i&&(r(i),o(i))},delete(s){let i=t.get(s);i&&(r(i),t.delete(s))},evict(s){let i=[];for(let a=0;a<s&&n!==null;a++){let u=n;i.push(u.key),r(u),t.delete(u.key)}return i},size(){return t.size}}}function ul(t){return t!=null&&typeof t.then=="function"}function zn(t){ul(t)&&t.catch(()=>{})}function cl(t,e){let n=new Map,r=e?.maxSize??0,o=r>0?e?.eviction??Zi():null,s=e?.writeThrough??!1;function i(c,d,l){for(let f=0;f<l;f++)try{zn(t[f].save(c,d))}catch{}}function a(c,d,l=0){for(let f=l;f<t.length;f++){let p;try{p=t[f].load(c)}catch{continue}if(ul(p)){let m=f;p.then(h=>{h!=null?(d.down([[S,h]]),i(c,h,m)):a(c,d,m+1)},()=>{a(c,d,m+1)});return}if(p!=null){d.down([[S,p]]),i(c,p,f);return}}}function u(){if(!(!o||r<=0))for(;o.size()>=r;){let c=o.evict(1);if(c.length===0)break;for(let d of c){let l=n.get(d);if(l){let f=l.cache;if(l.status!=="sentinel"&&t.length>0){let p=t.length-1;try{zn(t[p].save(d,f))}catch{}for(let m=0;m<p;m++)try{let h=t[m].clear;h&&zn(h.call(t[m],d))}catch{}}l.down([[de]])}n.delete(d)}}}return{load(c){let d=n.get(c);if(d)return o?.touch(c),d;o&&r>0&&o.size()>=r&&u();let l=N(void 0);return n.set(c,l),o?.insert(c),a(c,l),l},save(c,d){if(s)for(let f of t)try{zn(f.save(c,d))}catch{}else if(t[0])try{zn(t[0].save(c,d))}catch{}let l=n.get(c);if(l)l.down([[S,d]]),o?.touch(c);else{o&&r>0&&o.size()>=r&&u();let f=N(d);n.set(c,f),o?.insert(c)}},invalidate(c){let d=n.get(c);d&&a(c,d)},delete(c){o?.delete(c);let d=n.get(c);d&&d.down([[de]]),n.delete(c);for(let l of t)try{let f=l.clear;f&&zn(f.call(l,c))}catch{}},has(c){return n.has(c)},get size(){return n.size}}}Ne();ie();oe();Ne();ke();ie();oe();var Cr=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,i]of e)this._store.has(s)&&this._store.delete(s),this._store.set(s,{value:i,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=$(),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=$(),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 $()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??$())>=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 tt(t={}){let{name:e,maxSize:n,defaultTtl:r,versioning:o,backend:s}=t,i=s??new Cr({maxSize:n,defaultTtl:r}),a=N(i.toMap(),{name:e,describeKind:"state",equals:(d,l)=>d===l,...o!=null?{versioning:o}:{}});function u(){let d=i.toMap();te(()=>{a.down([[ee]]),a.down([[S,d]])})}function c(d){let l=i.version;try{return d()}finally{i.version!==l&&u()}}return{entries:a,has(d){return c(()=>i.has(d))},get(d){return c(()=>i.get(d))},set(d,l,f){c(()=>i.set(d,l,f?.ttl))},setMany(d,l){c(()=>i.setMany(d,l?.ttl))},delete(d){c(()=>i.delete(d))},deleteMany(d){c(()=>i.deleteMany(d))},clear(){c(()=>i.clear())},pruneExpired(){c(()=>i.pruneExpired())},get size(){return i.size},dispose(){}}}Re();function xm(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function pl(t,e,n){let r=re(t),o=r.v!=null,s=N(n?.initialVerified??null,{...o?{meta:{sourceVersion:null}}:{}}),i=n?.trigger!==void 0&&n.trigger!==null,a=null;if(i&&n?.autoVerify?a=mt(re(n.trigger),r):i?a=re(n.trigger):n?.autoVerify&&(a=r),a!==null){let u;if(a===r)u=be(r,c=>e(c));else{let c=r.cache;r.subscribe(d=>{for(let l of d)l[0]===S&&(c=l[1])}),u=be(a,()=>e(c))}Pt(u,c=>{te(()=>{if(s.down([[S,c]]),o){let d=r.v;d!=null&&s.meta.sourceVersion.down([[S,{id:d.id,version:d.version}]])}})})}return{node:r,verified:s,trigger:a}}function dl(t){t.subscribe(()=>{})}function Ar(t){return t instanceof Map?t:new Map}function ll(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 Zo(t,e,n){let r=re(t),o=tt(n.mapOptions??{}),s=n.budget??2e3,a=n.context!==void 0&&n.context!==null?re(n.context):N(null),u=Ar(o.entries.cache);o.entries.subscribe(p=>{for(let m of p)m[0]===S&&(u=Ar(m[1]))});let c=be(r,p=>e(p,u));if(Pt(c,p=>{ll(o,p)}),n.evict){let p=new Map,m=O([o.entries],([h])=>{let g=[],y=Ar(h);for(let b of p.keys())y.has(b)||(p.get(b)(),p.delete(b));for(let[b,v]of y){let T=n.evict(b,v);if(xm(T)){if(!p.has(b)){let w=Pt(T,k=>{k===!0&&o.has(b)&&o.delete(b)});p.set(b,w)}continue}if(typeof T=="boolean"){T&&g.push(b);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 d=n.consolidateTrigger!==void 0&&n.consolidateTrigger!==null;if(n.consolidate&&d){let p=re(n.consolidateTrigger),m=be(p,()=>n.consolidate(u));Pt(m,h=>{ll(o,h)})}let l=O([o.entries,a],([p,m])=>{let h=[...Ar(p).entries()].map(([b,v])=>({key:b,value:v,score:n.score(v,m),cost:n.cost(v)}));h.sort((b,v)=>v.score-b.score);let g=[],y=s;for(let b of h)b.cost<=y&&(g.push({key:b.key,value:b.value,score:b.score}),y-=b.cost);return g}),f=O([o.entries],([p])=>Ar(p).size);return dl(l),dl(f),{store:o,compact:l,size:f}}gi();Ne();ie();xe();var Lr=class{_version=0;_topics=new Set;get version(){return this._version}get topicCount(){return this._topics.size}hasTopic(e){return this._topics.has(e)}topicNames(){return this._topics.values()}createTopic(e){return this._topics.has(e)?!1:(this._topics.add(e),this._version+=1,!0)}removeTopic(e){let n=this._topics.delete(e);return n&&(this._version+=1),n}};function fl(t={}){let{backend:e}=t,n=e??new Lr,r=new Map;function o(s){let i=r.get(s);return i===void 0&&(i=K({describeKind:"state"}),r.set(s,i),n.createTopic(s)),i}return{topic(s){return o(s)},publish(s,i){o(s).emit(i)},publishMany(s){te(()=>{for(let[i,a]of s)o(i).emit(a)})},removeTopic(s){let i=r.get(s);return i===void 0?!1:(r.delete(s),n.removeTopic(s),i.down([[de]]),!0)},has(s){return n.hasTopic(s)},get size(){return n.topicCount},topicNames(){return n.topicNames()}}}Ne();ie();oe();function ml(t,e){if(t===e)return 0;let n=typeof t;if(n===typeof e&&(n==="number"||n==="string"||n==="boolean"||n==="bigint")){let o=t,s=e;return o<s?-1:o>s?1:0}return String(t).localeCompare(String(e))}function Rm(t,e){let n=ml(t[0],e[0]);return n!==0?n:ml(t[1],e[1])}function hl(t){return[t.secondary,t.primary]}function Jn(t,e){let n=hl(e),r=0,o=t.length;for(;r<o;){let s=r+o>>1;Rm(n,hl(t[s]))>0?r=s+1:o=s}return r}var Ir=class{_version=0;_buf=[];_byPrimary=new Map;get version(){return this._version}get size(){return this._buf.length}has(e){return this._byPrimary.has(e)}get(e){return this._byPrimary.get(e)?.value}upsert(e,n,r,o){let s=this._byPrimary.get(e),i={primary:e,secondary:n,value:r};if(s!==void 0&&o?.equals?.(s,i))return!1;if(s!==void 0){let u=Jn(this._buf,s);this._buf.splice(u,1)}let a=Jn(this._buf,i);return this._buf.splice(a,0,i),this._byPrimary.set(e,i),this._version+=1,s===void 0}upsertMany(e,n){let r=0;try{for(let o of e){let s=this._byPrimary.get(o.primary),i={primary:o.primary,secondary:o.secondary,value:o.value};if(s!==void 0&&n?.equals?.(s,i))continue;if(s!==void 0){let u=Jn(this._buf,s);this._buf.splice(u,1)}let a=Jn(this._buf,i);this._buf.splice(a,0,i),this._byPrimary.set(o.primary,i),r+=1}}finally{r>0&&(this._version+=1)}return r}delete(e){let n=this._byPrimary.get(e);if(n===void 0)return!1;let r=Jn(this._buf,n);return this._buf.splice(r,1),this._byPrimary.delete(e),this._version+=1,!0}deleteMany(e){let n=0;try{for(let r of e){let o=this._byPrimary.get(r);if(o===void 0)continue;let s=Jn(this._buf,o);this._buf.splice(s,1),this._byPrimary.delete(r),n+=1}}finally{n>0&&(this._version+=1)}return n}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._byPrimary.clear(),this._version+=1,e)}toArray(){return[...this._buf]}toPrimaryMap(){let e=new Map;for(let n of this._buf)e.set(n.primary,n.value);return e}};function Sm(t){return t.subscribe(()=>{})}function gl(t={}){let{name:e,versioning:n,equals:r,backend:o}=t,s=o??new Ir;function i(p){return p?.equals!==void 0||r===void 0?p:{...p,equals:r}}let a=N([],{name:e,describeKind:"state",equals:(p,m)=>p===m,...n!=null?{versioning:n}:{}}),u=O([a],([p])=>{let m=p,h=new Map;for(let g of m)h.set(g.primary,g.value);return h},{initial:s.toPrimaryMap(),describeKind:"derived"}),c=Sm(u),d=!1;function l(){let p=s.toArray();te(()=>{a.down([[ee]]),a.down([[S,p]])})}function f(p){let m=s.version;try{return p()}finally{s.version!==m&&l()}}return{ordered:a,byPrimary:u,has(p){return s.has(p)},get(p){return s.get(p)},get size(){return s.size},upsert(p,m,h,g){return f(()=>s.upsert(p,m,h,i(g)))},upsertMany(p,m){let h=[...p];h.length!==0&&f(()=>s.upsertMany(h,i(m)))},delete(p){f(()=>s.delete(p))},deleteMany(p){let m=[...p];m.length!==0&&f(()=>s.deleteMany(m))},clear(){f(()=>s.clear())},dispose(){d||(d=!0,c())}}}Ne();ie();oe();var Pr=class{_version=0;_buf;constructor(e){this._buf=e?[...e]:[]}get version(){return this._version}get size(){return this._buf.length}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._buf.length+e;if(!(n<0||n>=this._buf.length))return this._buf[n]}append(e){this._buf.push(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._buf.length;this._buf.length=n+e.length;for(let r=0;r<e.length;r++)this._buf[n+r]=e[r];this._version+=1}insert(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insert: index ${e} out of range [0, ${this._buf.length}]`);this._buf.splice(e,0,n),this._version+=1}insertMany(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insertMany: index ${e} out of range [0, ${this._buf.length}]`);n.length!==0&&(this._buf.splice(e,0,...n),this._version+=1)}pop(e){if(this._buf.length===0)throw new RangeError("pop from empty list");if(!Number.isInteger(e))throw new RangeError(`pop: index ${e} must be an integer`);let n=e>=0?e:this._buf.length+e;if(n<0||n>=this._buf.length)throw new RangeError(`pop: index ${e} out of range`);let[r]=this._buf.splice(n,1);return this._version+=1,r}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._version+=1,e)}toArray(){return[...this._buf]}};function es(t,e={}){let{name:n,versioning:r,backend:o}=e,s=o??new Pr(t),i=N(s.toArray(),{name:n,describeKind:"state",equals:(c,d)=>c===d,...r!=null?{versioning:r}:{}});function a(){let c=s.toArray();te(()=>{i.down([[ee]]),i.down([[S,c]])})}function u(c){let d=s.version;try{return c()}finally{s.version!==d&&a()}}return{items:i,get size(){return s.size},at(c){return s.at(c)},append(c){u(()=>s.append(c))},appendMany(c){u(()=>s.appendMany(c))},insert(c,d){u(()=>s.insert(c,d))},insertMany(c,d){u(()=>s.insertMany(c,d))},pop(c=-1){return u(()=>s.pop(c))},clear(){u(()=>s.clear())},dispose(){}}}Tt();ie();Re();function ts(t,e={}){let n=e.keyFn??(o=>String(o)),r=new Map;return o=>{let s=n(o),i=r.get(s);if(i)return i;let a=t(o),u;a!=null&&typeof a.then=="function"?u=Promise.resolve(a):a!=null&&typeof a=="object"&&"subscribe"in a&&"cache"in a?u=Kn(a):a!=null&&typeof a=="object"&&Symbol.asyncIterator in a?u=(async()=>{let l=a[Symbol.asyncIterator]();try{let{value:f,done:p}=await l.next();if(p)throw new Error("singleFromAny: factory returned empty async iterable");return f}finally{await l.return?.()}})():a!=null&&typeof a=="object"&&Symbol.iterator in a?u=(async()=>{let l=a[Symbol.iterator]();try{let{value:f,done:p}=l.next();if(p)throw new Error("singleFromAny: factory returned empty iterable");return f}finally{l.return?.()}})():u=Promise.resolve(a);let c,d=()=>{r.get(s)===c&&r.delete(s)};return c=u.then(l=>(d(),l),l=>{throw d(),l}),r.set(s,c),c}}function yl(t,e={}){let n=e.keyFn??(o=>String(o)),r=new Map;return o=>{let s=n(o),i=r.get(s);if(i)return i;let a=re(t(o));r.set(s,a);let u=a.subscribe(c=>{for(let d of c)if(d[0]===M||d[0]===_){r.get(s)===a&&r.delete(s),u();return}});return a}}Re();function Dr(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(Dr);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=Dr(e[o]);return r}function bl(t){return JSON.stringify(Dr(t),void 0,0)}function Gr(){let t=new Map;return{save(e,n){t.set(e,JSON.parse(JSON.stringify(n)))},load(e){let n=t.get(e);return n===void 0?null:JSON.parse(JSON.stringify(n))},clear(e){t.delete(e)},list(){return[...t.keys()].sort()}}}function vl(t){return{save(e,n){t[e]=JSON.parse(JSON.stringify(n))},load(e){let n=t[e];return n===void 0?null:JSON.parse(JSON.stringify(n))},clear(e){delete t[e]},list(){return Object.keys(t).sort()}}}ie();xe();oe();function Fr(t,e,n,r){let o=new q(t,r);o.add(e,{name:"source"});let s=N(n,{meta:{kind:"stratify_rules"}});o.add(s,{name:"rules"});for(let i of n)Nm(o,e,s,i);return o}function Nm(t,e,n,r){let o=`branch/${r.name}`,s=Symbol("noValue"),i=!1,a=!1,u=!1,c=s,d=!1,l=n.cache??[];function f(h){if(u){u=!1;let g=c;if(c=s,g!==s){let y=l.find(v=>v.name===r.name),b=!1;try{b=y?.classify(g)??!1}catch{b=!1}b?(d=!1,h.emit(g)):d&&(d=!1,h.down([[ee],[B]]))}else d?(d=!1,h.down([[ee],[B]])):h.down([[B]])}}let p=K([],(h,g)=>{let y=e.subscribe(v=>{for(let T of v)m(T,0,g)}),b=n.subscribe(v=>{for(let T of v)m(T,1,g)});return()=>{y(),b()}},{describeKind:"derived",meta:{kind:"stratify_branch",branch:r.name},completeWhenDepsComplete:!1});function m(h,g,y){let b=h[0];return b===ee?(g===0?(i=!0,d=!0):a=!0,!0):b===S||b===B?(g===0?(i=!1,u=!0,c=b===S?h[1]:s):(b===S&&(l=h[1]),a=!1),i||a||f(y),!0):b===_||b===M||b===de?(i=!1,a=!1,u=!1,c=s,d=!1,g===0&&y.down([h]),!0):g===1}if(t.add(p,{name:o}),r.ops){let h=r.ops(p),g=`branch/${r.name}/out`;t.add(h,{name:g})}}pt();Ne();ie();xe();oe();Re();ie();var Em=new Map([[He,"INVALIDATE"],[Ie,"PAUSE"],[Ge,"RESUME"],[de,"TEARDOWN"],[_,"COMPLETE"],[M,"ERROR"]]),_m=new Map([["INVALIDATE",He],["PAUSE",Ie],["RESUME",Ge],["TEARDOWN",de],["COMPLETE",_],["ERROR",M]]);function Ft(t){let e=Em.get(t);return e||(Symbol.keyFor(t)??"UNKNOWN")}function ln(t){let e=_m.get(t);if(e)return e;if(t&&t!=="UNKNOWN")return Symbol.for(t)}function pn(t){return t instanceof Error?{message:t.message,name:t.name,stack:t.stack}:{message:String(t),name:"Error"}}function fn(t){let e=new Error(t.message);return e.name=t.name,t.stack&&(e.stack=t.stack),e}function $t(t){if(typeof MessagePort<"u"&&t instanceof MessagePort)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),t.start(),()=>t.removeEventListener("message",n)},terminate(){t.close()}};if(typeof SharedWorker<"u"&&t instanceof SharedWorker)return $t(t.port);if(typeof Worker<"u"&&t instanceof Worker)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),()=>t.removeEventListener("message",n)},terminate(){t.terminate()}};if(typeof BroadcastChannel<"u"&&t instanceof BroadcastChannel)return{post(e,n){n&&n.length>0&&console.warn("[graphrefly] WorkerTransport: BroadcastChannel does not support Transferable objects. The transfer argument is ignored and objects will be cloned instead."),t.postMessage(e)},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),()=>t.removeEventListener("message",n)},terminate(){t.close()}};if(typeof ServiceWorker<"u"&&t instanceof ServiceWorker)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>{r.source===t&&e(r.data)};return navigator.serviceWorker.addEventListener("message",n),()=>navigator.serviceWorker.removeEventListener("message",n)}};throw new Error("createTransport: unsupported target type. Expected Worker, SharedWorker, ServiceWorker, BroadcastChannel, or MessagePort.")}function Mm(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function ea(t,e){let n=Mm(t)?t:$t(t),r=e.name??"workerBridge",o=Object.entries(e.expose??{}),s=e.import??[],i=e.transfer??{},a=N("connecting",{name:`${r}::meta::status`}),u=N(null,{name:`${r}::meta::error`}),c=new Map,d=new Map;for(let b of s){let v=N(void 0,{name:`${r}::${b}`});c.set(b,v)}let l;if(o.length>0){let b=o.map(([,w])=>w),v=K(b,(w,k)=>{let x={};for(let R=0;R<o.length;R++){let[E]=o[R],G=w[R];G!=null&&G.length>0&&(x[E]=G.at(-1))}Object.keys(x).length!==0&&k.emit(x)},{name:`${r}::aggregated`,partial:!0});l=fe([v],w=>{let k=w[0];if(k==null||Object.keys(k).length===0)return;let x=[];for(let G of Object.keys(k)){let L=i[G];L&&x.push(...L(k[G]))}let R;for(let[G,L]of o)G in k&&L.v!=null&&(R==null&&(R={}),R[G]=L.v.version);let E={t:"b",u:k,...R?{v:R}:{}};try{n.post(E,x.length>0?x:void 0)}catch(G){u.down([[S,G instanceof Error?G:new Error(String(G))]])}}).subscribe(()=>{})}let f=!1,p=n.listen(b=>{if(f)return;let v=b;switch(v.t){case"r":{te(()=>{for(let[w,k]of Object.entries(v.stores)){let x=c.get(w);x&&x.down([[S,k]])}}),a.down([[S,"connected"]]);let T={};for(let[w,k]of o)T[w]=k.cache;n.post({t:"i",stores:T});break}case"v":{let T=c.get(v.s);T&&T.down([[S,v.d]]);break}case"b":{te(()=>{for(let[T,w]of Object.entries(v.u)){let k=v.v?.[T];if(k!=null){let R=d.get(T);if(R!=null&&k<=R)continue;d.set(T,k)}let x=c.get(T);x&&x.down([[S,w]])}});break}case"e":{let T=c.get(v.s);T&&T.down([[M,fn(v.err)]]);break}case"s":{let T=ln(v.sig);if(!T)break;let w=v.s==="*"?[...c.values()]:c.has(v.s)?[c.get(v.s)]:[];for(let k of w)k.down(v.d===void 0?[[T]]:[[T,v.d]]);break}}}),m=[];for(let[b,v]of o){let T=v.subscribe((w=>{if(!f)for(let k of w){let x=k[0];x!==S&&(Ae.isLocalOnly(x)||(x===M?n.post({t:"e",s:b,err:pn(k[1])}):n.post({t:"s",s:b,sig:Ft(x),d:k.length>1?k[1]:void 0})))}}));m.push(T)}let h;if(e.timeoutMs!=null&&e.timeoutMs>0){let b=et(e.timeoutMs),v=ut(a,w=>w==="connected");h=Qo(mt(Er(b,()=>"timeout"),Er(v,()=>"ready"))).subscribe(w=>{for(let k of w)k[0]===S&&k[1]==="timeout"&&(u.down([[S,new Error("Worker bridge handshake timeout")]]),g())})}function g(){if(!f){f=!0,h?.(),n.post({t:"s",s:"*",sig:Ft(de)}),l&&l();for(let b of m)b();m.length=0,p(),a.down([[S,"closed"]]),d.clear(),c.clear()}}let y={meta:{status:a,error:u},destroy:g};for(let[b,v]of c)y[b]=v;return y}Ne();ie();xe();oe();function Om(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function ta(t,e){let n=Om(t)?t:$t(t),r=e.import??[],o=e.transfer??{},s=new Map,i=new Map,a={};for(let g of r){let y=N(void 0,{name:`worker::${g}`});s.set(g,y),a[g]=y}let u=e.expose(a),c=Object.entries(u),d,l=!1;if(c.length>0){let g=c.map(([,v])=>v),y=K(g,(v,T)=>{let w={};for(let k=0;k<c.length;k++){let[x]=c[k],R=v[k];R!=null&&R.length>0&&(w[x]=R.at(-1))}Object.keys(w).length!==0&&T.emit(w)},{name:"workerSelf::aggregated",partial:!0});d=fe([y],v=>{if(l)return;let T=v[0];if(T==null||Object.keys(T).length===0)return;let w=[];for(let R of Object.keys(T)){let E=o[R];E&&w.push(...E(T[R]))}let k;for(let[R,E]of c)R in T&&E.v!=null&&(k==null&&(k={}),k[R]=E.v.version);let x={t:"b",u:T,...k?{v:k}:{}};try{n.post(x,w.length>0?w:void 0)}catch{}}).subscribe(()=>{})}let f=[];for(let[g,y]of c){let b=y.subscribe((v=>{if(!l)for(let T of v){let w=T[0];w!==S&&(Ae.isLocalOnly(w)||(w===M?n.post({t:"e",s:g,err:pn(T[1])}):n.post({t:"s",s:g,sig:Ft(w),d:T.length>1?T[1]:void 0})))}}));f.push(b)}let p=n.listen(g=>{if(l)return;let y=g;switch(y.t){case"i":{te(()=>{for(let[b,v]of Object.entries(y.stores)){let T=s.get(b);T&&T.down([[S,v]])}});break}case"v":{let b=s.get(y.s);b&&b.down([[S,y.d]]);break}case"b":{te(()=>{for(let[b,v]of Object.entries(y.u)){let T=y.v?.[b];if(T!=null){let k=i.get(b);if(k!=null&&T<=k)continue;i.set(b,T)}let w=s.get(b);w&&w.down([[S,v]])}});break}case"e":{let b=s.get(y.s);b&&b.down([[M,fn(y.err)]]);break}case"s":{let b=ln(y.sig);if(!b)break;if(b===de&&y.s==="*"){h();return}let v=y.s==="*"?[...s.values()]:s.has(y.s)?[s.get(y.s)]:[];for(let T of v)T.down(y.d===void 0?[[b]]:[[b,y.d]]);break}}}),m={};for(let[g,y]of c)m[g]=y.cache;n.post({t:"r",stores:m});function h(){if(!l){l=!0,d&&d();for(let g of f)g();f.length=0,p(),n.terminate?.(),i.clear(),s.clear()}}return{destroy:h}}var su={};he(su,{SNAPSHOT_WIRE_VERSION:()=>Xr,SurfaceError:()=>we,accountability:()=>_s,ai:()=>Ss,asSurfaceError:()=>Us,cqrs:()=>Bo,createGraph:()=>Zn,deleteSnapshot:()=>ei,demoShell:()=>Os,diffSnapshots:()=>Xs,domainTemplates:()=>Ls,graphspec:()=>Is,guarded:()=>Ds,harness:()=>$s,jobQueue:()=>Vs,layout:()=>Ws,lens:()=>Hs,listSnapshots:()=>Zs,memory:()=>Rs,messaging:()=>bs,orchestration:()=>vs,reduction:()=>As,refine:()=>Fs,resilientPipeline:()=>qs,restoreSnapshot:()=>Qs,runReduction:()=>zs,saveSnapshot:()=>Ys,surface:()=>ti});var Ss={};he(Ss,{AgentLoopGraph:()=>ks,AllTiersExhaustedError:()=>$r,BudgetExhaustedError:()=>ls,ChatStreamGraph:()=>Ts,CircuitOpenError:()=>st,DEFAULT_DECAY_RATE:()=>Ma,FallbackMissError:()=>$m,LLMTimeoutError:()=>Qn,ReplayCacheMissError:()=>mn,ToolRegistryGraph:()=>ws,admissionFilter3D:()=>rg,agentLoop:()=>Zh,agentMemory:()=>ig,anthropicAdapter:()=>ra,canonicalJson:()=>as,cascadingLlmAdapter:()=>va,chatStream:()=>ka,composePricing:()=>ih,computePrice:()=>Fl,contentGate:()=>Yh,costMeterExtractor:()=>Hh,createAdapter:()=>th,createCapabilitiesRegistry:()=>Cm,createPricingRegistry:()=>oh,dryRunAdapter:()=>St,dryRunPreset:()=>vh,fallbackAdapter:()=>ia,fromLLM:()=>Th,frozenContext:()=>Sh,gatedStream:()=>jh,gaugesAsContext:()=>ag,googleAdapter:()=>aa,graphFromSpec:()=>ug,handoff:()=>eg,keywordFlagExtractor:()=>qh,knobsAsTools:()=>dg,llmConsolidator:()=>_a,llmExtractor:()=>Ea,observableAdapter:()=>nh,openAICompatAdapter:()=>ca,parseRateLimitFromError:()=>ga,promptNode:()=>Br,redactor:()=>Qh,registryPricing:()=>sh,resilientAdapter:()=>bh,streamExtractor:()=>Uh,streamingPromptNode:()=>Bh,suggestStrategy:()=>pg,systemPromptBuilder:()=>Vh,toolCallExtractor:()=>Jh,toolRegistry:()=>xa,toolSelector:()=>tg,validateGraphDef:()=>Oa,withBreaker:()=>fa,withBudgetGate:()=>ha,withDryRun:()=>uh,withRateLimiter:()=>ba,withReplayCache:()=>sa,withRetry:()=>Ta,withTimeout:()=>wa,zeroPrice:()=>pa});function ns(t,e){return`${t}::${e}`}function Cm(t){let e=new Map,n=new Map,r=o=>{e.set(ns(o.provider,o.id),o);let s=n.get(o.provider);s||(s=new Set,n.set(o.provider,s)),s.add(o.id)};if(t)for(let o of t)r(o);return{register:r,lookup(o,s){let i=e.get(ns(o,s));if(i)return i;let a=n.get(o);if(!a)return;let u;for(let c of a)if(s.startsWith(c)&&(!u||c.length>u.key.length)){let d=e.get(ns(o,c));d&&(u={key:c,cap:d})}return u?.cap},remove(o,s){let i=e.delete(ns(o,s));if(i){let a=n.get(o);a?.delete(s),a&&a.size===0&&n.delete(o)}return i},entries(){return e.values()}}}ke();function ra(t={}){return t.sdk?Dm(t):Pm(t)}function rs(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:i}=Am(t,e?.systemPrompt),a={model:o,messages:i.map(Lm),max_tokens:e?.maxTokens??4096};return s&&(a.system=s),e?.temperature!=null&&(a.temperature=e.temperature),e?.tools&&e.tools.length>0&&(a.tools=e.tools.map(Im)),e?.maxReasoningTokens!=null&&(a.thinking={type:"enabled",budget_tokens:e.maxReasoningTokens}),e?.cacheHint,r&&(a.stream=!0),e?.providerExtras&&Object.assign(a,e.providerExtras),a}function Am(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(`
32
33
 
33
- `):void 0,chat:r}}function sm(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 im(t){return{name:t.name,description:t.description,input_schema:t.parameters}}function ss(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 na(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 rl(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:na(t.usage),finishReason:t.stop_reason,latencyMs:e,model:t.model,provider:"anthropic"}}function am(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(i,a){let u=os(i,a,t.model,!1),c=B(),d=await o(`${n}/v1/messages`,{method:"POST",headers:s(),body:JSON.stringify(u),signal:a?.signal});if(!d.ok)throw await nl(d);let l=await d.json(),f=Math.max(0,(B()-c)/1e6);return rl(l,f)},async*stream(i,a){let u=os(i,a,t.model,!0),c=await o(`${n}/v1/messages`,{method:"POST",headers:{...s(),accept:"text/event-stream"},body:JSON.stringify(u),signal:a?.signal});if(!c.ok)throw await nl(c);if(!c.body)throw new Error("anthropicAdapter: streaming response has no body");let d,l,f=new Map;for await(let p of cm(c.body)){let m=p.data;if(!m)continue;let h;try{h=JSON.parse(m)}catch{continue}switch(h.type){case"message_start":{d=ss(d,h.message.usage);break}case"content_block_start":{let g=h,y=g.content_block;y.type==="tool_use"&&(f.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 b=f.get(g.index);b&&(b.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&&(d=ss(d,g.delta.usage));break}case"message_stop":break}}d&&(yield{type:"usage",usage:na(d)}),yield{type:"finish",reason:l??"stop"}}}}function um(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=os(n,r,t.model,!1),s=B(),i=await e.messages.create(o,{signal:r?.signal}),a=Math.max(0,(B()-s)/1e6);return rl(i,a)},async*stream(n,r){if(!e.messages.stream)throw new Error("sdkBackedAnthropic: SDK instance does not expose .messages.stream");let o=os(n,r,t.model,!0),s,i;for await(let a of e.messages.stream(o,{signal:r?.signal}))switch(a.type){case"message_start":s=ss(s,a.message.usage);break;case"content_block_delta":{let u=a.delta;u?.type==="text_delta"&&typeof u.text=="string"?yield{type:"token",delta:u.text}:u?.type==="input_json_delta"&&typeof u.partial_json=="string"?yield{type:"tool-call-delta",delta:{argumentsDelta:u.partial_json}}:u?.type==="thinking_delta"&&typeof u.thinking=="string"&&(yield{type:"thinking",delta:u.thinking});break}case"message_delta":{let u=a;u.delta.stop_reason&&(i=u.delta.stop_reason),u.delta.usage&&(s=ss(s,u.delta.usage));break}}s&&(yield{type:"usage",usage:na(s)}),yield{type:"finish",reason:i??"stop"}}}}async function*cm(t){let e=t.getReader(),n=new TextDecoder,r="";try{for(;;){let{done:o,value:s}=await e.read();if(o){r.length>0&&(yield el(r));return}r+=n.decode(s,{stream:!0});let i=tl(r);for(;i!==null;){let a=r.slice(0,i.index);r=r.slice(i.index+i.length);let u=el(a);(u.data||u.event)&&(yield u),i=tl(r)}}}finally{e.releaseLock()}}function el(t){let e={},n=[];for(let r of t.split(`
34
+ `):void 0,chat:r}}function Lm(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 Im(t){return{name:t.name,description:t.description,input_schema:t.parameters}}function os(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 oa(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 xl(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:oa(t.usage),finishReason:t.stop_reason,latencyMs:e,model:t.model,provider:"anthropic"}}function Pm(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(i,a){let u=rs(i,a,t.model,!1),c=$(),d=await o(`${n}/v1/messages`,{method:"POST",headers:s(),body:JSON.stringify(u),signal:a?.signal});if(!d.ok)throw await kl(d);let l=await d.json(),f=Math.max(0,($()-c)/1e6);return xl(l,f)},async*stream(i,a){let u=rs(i,a,t.model,!0),c=await o(`${n}/v1/messages`,{method:"POST",headers:{...s(),accept:"text/event-stream"},body:JSON.stringify(u),signal:a?.signal});if(!c.ok)throw await kl(c);if(!c.body)throw new Error("anthropicAdapter: streaming response has no body");let d,l,f=new Map;for await(let p of Gm(c.body)){let m=p.data;if(!m)continue;let h;try{h=JSON.parse(m)}catch{continue}switch(h.type){case"message_start":{d=os(d,h.message.usage);break}case"content_block_start":{let g=h,y=g.content_block;y.type==="tool_use"&&(f.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 b=f.get(g.index);b&&(b.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&&(d=os(d,g.delta.usage));break}case"message_stop":break}}d&&(yield{type:"usage",usage:oa(d)}),yield{type:"finish",reason:l??"stop"}}}}function Dm(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=rs(n,r,t.model,!1),s=$(),i=await e.messages.create(o,{signal:r?.signal}),a=Math.max(0,($()-s)/1e6);return xl(i,a)},async*stream(n,r){if(!e.messages.stream)throw new Error("sdkBackedAnthropic: SDK instance does not expose .messages.stream");let o=rs(n,r,t.model,!0),s,i;for await(let a of e.messages.stream(o,{signal:r?.signal}))switch(a.type){case"message_start":s=os(s,a.message.usage);break;case"content_block_delta":{let u=a.delta;u?.type==="text_delta"&&typeof u.text=="string"?yield{type:"token",delta:u.text}:u?.type==="input_json_delta"&&typeof u.partial_json=="string"?yield{type:"tool-call-delta",delta:{argumentsDelta:u.partial_json}}:u?.type==="thinking_delta"&&typeof u.thinking=="string"&&(yield{type:"thinking",delta:u.thinking});break}case"message_delta":{let u=a;u.delta.stop_reason&&(i=u.delta.stop_reason),u.delta.usage&&(s=os(s,u.delta.usage));break}}s&&(yield{type:"usage",usage:oa(s)}),yield{type:"finish",reason:i??"stop"}}}}async function*Gm(t){let e=t.getReader(),n=new TextDecoder,r="";try{for(;;){let{done:o,value:s}=await e.read();if(o){r.length>0&&(yield Tl(r));return}r+=n.decode(s,{stream:!0});let i=wl(r);for(;i!==null;){let a=r.slice(0,i.index);r=r.slice(i.index+i.length);let u=Tl(a);(u.data||u.event)&&(yield u),i=wl(r)}}}finally{e.releaseLock()}}function Tl(t){let e={},n=[];for(let r of t.split(`
34
35
  `)){let o=r.endsWith("\r")?r.slice(0,-1):r;if(!o||o.startsWith(":"))continue;let s=o.indexOf(":"),i=s===-1?o:o.slice(0,s),a=s===-1?"":o.slice(s+1).replace(/^ /,"");i==="data"?n.push(a):i==="event"?e.event=a:i==="id"&&(e.id=a)}return n.length>0&&(e.data=n.join(`
35
- `)),e}function tl(t){let e=t.indexOf(`\r
36
+ `)),e}function wl(t){let e=t.indexOf(`\r
36
37
  \r
37
38
  `),n=t.indexOf(`
38
39
 
39
- `),r=null;return e!==-1&&(r={index:e,length:4}),n!==-1&&(r===null||n<r.index)&&(r={index:n,length:2}),r}async function nl(t){let e;try{e=await t.text()}catch{e=""}let n=new Error(`Anthropic API ${t.status}: ${t.statusText}${e?` \u2014 ${e}`:""}`);return n.status=t.status,n.headers=t.headers,n}lt();function is(){let t=new Error("aborted");return t.name="AbortError",t}function ol(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(is()):new Promise((n,r)=>{let o=new Re,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(is())},e.addEventListener("abort",s,{once:!0}))})}function Nt(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??(a=>{let u=[...a].reverse().find(c=>c.role==="user");return u?`echo: ${u.content}`:"dry-run: no user message"}),i=t.usage??((a,u)=>{let c=a.reduce((d,l)=>d+l.content.length,0);return{input:{regular:Math.ceil(c/4)},output:{regular:Math.ceil(u.length/4)}}});return{provider:e,model:n,async invoke(a,u){if(await ol(r,u?.signal),u?.signal?.aborted)throw is();let c=s(a,u),d=i(a,c);return{content:c,usage:d,finishReason:"stop",model:u?.model??n,provider:e,tier:u?.tier,metadata:{dryRun:!0}}},async*stream(a,u){let c=s(a,u),d=i(a,c),l=Math.ceil(c.length/o)||1,f=r>0?r/l:0;for(let p=0;p<c.length;p+=o){if(u?.signal?.aborted)throw is();await ol(f,u?.signal),yield{type:"token",delta:c.slice(p,p+o)}}yield{type:"usage",usage:d},yield{type:"finish",reason:"stop"}}}}Te();async function as(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+=sl[r[s]];return o}var sl=new Array(256);for(let t=0;t<256;t++)sl[t]=t.toString(16).padStart(2,"0");Te();lt();var mn=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 ra(t,e){let n=e.mode??"read-write",r=e.cacheStreaming??!1,o=e.captureStreamCadence??!1,s=e.replaySpeed??1,i=e.keyPrefix??"llm-replay",a=e.storage,u=n==="read"||n==="read-strict",c=async(h,g)=>{if(e.keyFn){let k=e.keyFn;if(k.length<=1){let S={messages:h,opts:g,context:g?.keyContext},_=await k(S);return`${i}:${_}`}let x=await k(h,g);return`${i}:${x}`}let{signal:y,keyContext:b,...v}=g??{},T=us({messages:h,opts:v}),w=await as(T);return`${i}:${w}`},d=async h=>{if(n==="write-only")return;let g=await a.load(h);if(g!=null)try{return typeof g=="string"?JSON.parse(g):g}catch{return}},l=async h=>(await d(h))?.response,f=async(h,g,y)=>{if(u)return;let b={response:g,storedAtNs:pe(),...y?{streamChunks:y.chunks,streamCadenceMs:y.delaysMs}:{}};await a.save(h,b)},p=h=>h<=0?Promise.resolve():new Promise(g=>{new Re().start(h,()=>g())}),m=Jo(async({messages:h,invokeOpts:g})=>{let y=t.invoke(h,g);return await dm(y)},{keyFn:({_precomputedKey:h})=>h});return{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(h,g){let y=await c(h,g),b=await l(y);if(b)return{...b,metadata:{...b.metadata??{},replayCache:"hit"}};if(n==="read-strict")throw new mn(y,"invoke");let v=await m({messages:h,invokeOpts:g,_precomputedKey:y});return await f(y,v),v},async*stream(h,g){if(!r){for await(let _ of t.stream(h,g))yield _;return}let y=await c(h,g),b=await d(y);if(b){let _=b.response;if(b.streamChunks&&b.streamCadenceMs)for(let F=0;F<b.streamChunks.length;F++){let L=b.streamCadenceMs[F]??0,D=s>0?L/s:0;D>0&&await p(D),yield{type:"token",delta:b.streamChunks[F]?.delta??""}}else _.content&&(yield{type:"token",delta:_.content});_.usage&&(yield{type:"usage",usage:_.usage}),yield{type:"finish",reason:_.finishReason??"stop"};return}if(n==="read-strict")throw new mn(y,"stream");let v="",T,w,k=[],x=[],S;for await(let _ of t.stream(h,g)){if(_.type==="token"&&(v+=_.delta,o)){let F=B(),L=S===void 0?0:(F-S)/1e6;x.push(L),S=F,k.push({delta:_.delta})}_.type==="usage"&&(T=_.usage),_.type==="finish"&&(w=_.reason),yield _}if(v||T){let _={content:v,usage:T??{input:{regular:0},output:{regular:0}},finishReason:w,model:t.model??g?.model??"",provider:t.provider};await f(y,_,o?{chunks:k,delaysMs:x}:void 0)}}}}function us(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 i of Object.keys(r).sort())s[i]=n(r[i]);return s}finally{e.delete(o)}};return JSON.stringify(n(t))}async function dm(t){if(t!=null&&typeof t.then=="function")return await t;if(t&&typeof t=="object"&&"content"in t)return t;throw new Error("withReplayCache: adapter.invoke must return Promise or LLMResponse (Node input not supported in cache path)")}var lm=mn;function il(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 al(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 pm(t,e){if("key"in t)return t.key;let n=us({messages:t.messages,opts:t.invokeOpts??{}}),r=await as(n);return`${e}:${r}`}function fm(t){let e={response:t.response,storedAtNs:pe()};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 mm(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=Lr(),o=t.fixtures,s=(async()=>{for(let i of o){let a=await pm(i,e);await r.save(a,fm(i))}})();return s.catch(()=>{}),{tier:r,seedReady:s}}return t.fixturesStorage?{tier:t.fixturesStorage,seedReady:Promise.resolve()}:{tier:void 0,seedReady:Promise.resolve()}}function oa(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"?Nt({provider:e,model:n,respond:()=>"[unreachable: read-strict mode throws on miss]"}):{provider:e,model:n,async invoke(d,l){let f=t.respond?t.respond(d,l):il(e,n);return al(f,e,n)},async*stream(d,l){let f=t.respond?t.respond(d,l):il(e,n),p=al(f,e,n);yield{type:"token",delta:p.content},p.usage&&(yield{type:"usage",usage:p.usage}),yield{type:"finish",reason:p.finishReason??"stop"}}},i,a=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`.");i=t.record.storage}else{let d=mm(t,o);i=d.tier??Lr(),a=d.seedReady}let u=t.record?"read-write":r==="throw"?"read-strict":"read",c=ra(s,{storage:i,mode:u,keyPrefix:o,cacheStreaming:!0,captureStreamCadence:!0,replaySpeed:t.replaySpeed,...t.keyFn?{keyFn:t.keyFn}:{}});return{provider:e,model:n,capabilities:c.capabilities?.bind(c),async invoke(d,l){return await a,c.invoke(d,l)},async*stream(d,l){await a;for await(let f of c.stream(d,l))yield f}}}Te();function sa(t={}){return t.sdk?bm(t):ym(t)}function cs(t,e){let n=[],r=[];e?.systemPrompt&&n.push(e.systemPrompt);for(let i of t){if(i.role==="system"){n.push(i.content);continue}if(i.role==="tool"){r.push({role:"user",parts:[{functionResponse:{name:i.name??i.toolCallId??"tool",response:{result:i.content}}}]});continue}if(i.role==="assistant"&&i.toolCalls&&i.toolCalls.length>0){let a=[];i.content&&a.push({text:i.content});for(let u of i.toolCalls)a.push({functionCall:{name:u.name,args:u.arguments}});r.push({role:"model",parts:a});continue}r.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let o={contents:r};n.length>0&&(o.systemInstruction={role:"system",parts:[{text:n.join(`
40
+ `),r=null;return e!==-1&&(r={index:e,length:4}),n!==-1&&(r===null||n<r.index)&&(r={index:n,length:2}),r}async function kl(t){let e;try{e=await t.text()}catch{e=""}let n=new Error(`Anthropic API ${t.status}: ${t.statusText}${e?` \u2014 ${e}`:""}`);return n.status=t.status,n.headers=t.headers,n}pt();function ss(){let t=new Error("aborted");return t.name="AbortError",t}function Rl(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(ss()):new Promise((n,r)=>{let o=new _e,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(ss())},e.addEventListener("abort",s,{once:!0}))})}function St(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??(a=>{let u=[...a].reverse().find(c=>c.role==="user");return u?`echo: ${u.content}`:"dry-run: no user message"}),i=t.usage??((a,u)=>{let c=a.reduce((d,l)=>d+l.content.length,0);return{input:{regular:Math.ceil(c/4)},output:{regular:Math.ceil(u.length/4)}}});return{provider:e,model:n,async invoke(a,u){if(await Rl(r,u?.signal),u?.signal?.aborted)throw ss();let c=s(a,u),d=i(a,c);return{content:c,usage:d,finishReason:"stop",model:u?.model??n,provider:e,tier:u?.tier,metadata:{dryRun:!0}}},async*stream(a,u){let c=s(a,u),d=i(a,c),l=Math.ceil(c.length/o)||1,f=r>0?r/l:0;for(let p=0;p<c.length;p+=o){if(u?.signal?.aborted)throw ss();await Rl(f,u?.signal),yield{type:"token",delta:c.slice(p,p+o)}}yield{type:"usage",usage:d},yield{type:"finish",reason:"stop"}}}}ke();async function is(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+=Sl[r[s]];return o}var Sl=new Array(256);for(let t=0;t<256;t++)Sl[t]=t.toString(16).padStart(2,"0");ke();pt();var mn=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 sa(t,e){let n=e.mode??"read-write",r=e.cacheStreaming??!1,o=e.captureStreamCadence??!1,s=e.replaySpeed??1,i=e.keyPrefix??"llm-replay",a=e.storage,u=n==="read"||n==="read-strict",c=async(h,g)=>{if(e.keyFn){let k=e.keyFn;if(k.length<=1){let R={messages:h,opts:g,context:g?.keyContext},E=await k(R);return`${i}:${E}`}let x=await k(h,g);return`${i}:${x}`}let{signal:y,keyContext:b,...v}=g??{},T=as({messages:h,opts:v}),w=await is(T);return`${i}:${w}`},d=async h=>{if(n==="write-only")return;let g=await a.load(h);if(g!=null)try{return typeof g=="string"?JSON.parse(g):g}catch{return}},l=async h=>(await d(h))?.response,f=async(h,g,y)=>{if(u)return;let b={response:g,storedAtNs:pe(),...y?{streamChunks:y.chunks,streamCadenceMs:y.delaysMs}:{}};await a.save(h,b)},p=h=>h<=0?Promise.resolve():new Promise(g=>{new _e().start(h,()=>g())}),m=ts(async({messages:h,invokeOpts:g})=>{let y=t.invoke(h,g);return await Fm(y)},{keyFn:({_precomputedKey:h})=>h});return{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(h,g){let y=await c(h,g),b=await l(y);if(b)return{...b,metadata:{...b.metadata??{},replayCache:"hit"}};if(n==="read-strict")throw new mn(y,"invoke");let v=await m({messages:h,invokeOpts:g,_precomputedKey:y});return await f(y,v),v},async*stream(h,g){if(!r){for await(let E of t.stream(h,g))yield E;return}let y=await c(h,g),b=await d(y);if(b){let E=b.response;if(b.streamChunks&&b.streamCadenceMs)for(let G=0;G<b.streamChunks.length;G++){let L=b.streamCadenceMs[G]??0,P=s>0?L/s:0;P>0&&await p(P),yield{type:"token",delta:b.streamChunks[G]?.delta??""}}else E.content&&(yield{type:"token",delta:E.content});E.usage&&(yield{type:"usage",usage:E.usage}),yield{type:"finish",reason:E.finishReason??"stop"};return}if(n==="read-strict")throw new mn(y,"stream");let v="",T,w,k=[],x=[],R;for await(let E of t.stream(h,g)){if(E.type==="token"&&(v+=E.delta,o)){let G=$(),L=R===void 0?0:(G-R)/1e6;x.push(L),R=G,k.push({delta:E.delta})}E.type==="usage"&&(T=E.usage),E.type==="finish"&&(w=E.reason),yield E}if(v||T){let E={content:v,usage:T??{input:{regular:0},output:{regular:0}},finishReason:w,model:t.model??g?.model??"",provider:t.provider};await f(y,E,o?{chunks:k,delaysMs:x}:void 0)}}}}function as(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 i of Object.keys(r).sort())s[i]=n(r[i]);return s}finally{e.delete(o)}};return JSON.stringify(n(t))}async function Fm(t){if(t!=null&&typeof t.then=="function")return await t;if(t&&typeof t=="object"&&"content"in t)return t;throw new Error("withReplayCache: adapter.invoke must return Promise or LLMResponse (Node input not supported in cache path)")}var $m=mn;function Nl(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 El(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 Bm(t,e){if("key"in t)return t.key;let n=as({messages:t.messages,opts:t.invokeOpts??{}}),r=await is(n);return`${e}:${r}`}function jm(t){let e={response:t.response,storedAtNs:pe()};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 Vm(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=Gr(),o=t.fixtures,s=(async()=>{for(let i of o){let a=await Bm(i,e);await r.save(a,jm(i))}})();return s.catch(()=>{}),{tier:r,seedReady:s}}return t.fixturesStorage?{tier:t.fixturesStorage,seedReady:Promise.resolve()}:{tier:void 0,seedReady:Promise.resolve()}}function ia(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"?St({provider:e,model:n,respond:()=>"[unreachable: read-strict mode throws on miss]"}):{provider:e,model:n,async invoke(d,l){let f=t.respond?t.respond(d,l):Nl(e,n);return El(f,e,n)},async*stream(d,l){let f=t.respond?t.respond(d,l):Nl(e,n),p=El(f,e,n);yield{type:"token",delta:p.content},p.usage&&(yield{type:"usage",usage:p.usage}),yield{type:"finish",reason:p.finishReason??"stop"}}},i,a=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`.");i=t.record.storage}else{let d=Vm(t,o);i=d.tier??Gr(),a=d.seedReady}let u=t.record?"read-write":r==="throw"?"read-strict":"read",c=sa(s,{storage:i,mode:u,keyPrefix:o,cacheStreaming:!0,captureStreamCadence:!0,replaySpeed:t.replaySpeed,...t.keyFn?{keyFn:t.keyFn}:{}});return{provider:e,model:n,capabilities:c.capabilities?.bind(c),async invoke(d,l){return await a,c.invoke(d,l)},async*stream(d,l){await a;for await(let f of c.stream(d,l))yield f}}}ke();function aa(t={}){return t.sdk?qm(t):Wm(t)}function us(t,e){let n=[],r=[];e?.systemPrompt&&n.push(e.systemPrompt);for(let i of t){if(i.role==="system"){n.push(i.content);continue}if(i.role==="tool"){r.push({role:"user",parts:[{functionResponse:{name:i.name??i.toolCallId??"tool",response:{result:i.content}}}]});continue}if(i.role==="assistant"&&i.toolCalls&&i.toolCalls.length>0){let a=[];i.content&&a.push({text:i.content});for(let u of i.toolCalls)a.push({functionCall:{name:u.name,args:u.arguments}});r.push({role:"model",parts:a});continue}r.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let o={contents:r};n.length>0&&(o.systemInstruction={role:"system",parts:[{text:n.join(`
40
41
 
41
- `)}]});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(hm)}]),e?.providerExtras&&Object.assign(o,e.providerExtras),o}function hm(t){return{name:t.name,description:t.description,parameters:t.parameters}}function ia(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 ll(t,e){let n=t.candidates?.[0],r=n?.content?.parts??[],o=[],s=[],i=0;for(let a of r)typeof a.text=="string"&&o.push(a.text),a.functionCall&&s.push({id:`${a.functionCall.name}-${i++}`,name:a.functionCall.name,arguments:a.functionCall.args??{}});return{content:o.join(""),toolCalls:s.length>0?s:void 0,usage:ia(t.usageMetadata),finishReason:n?.finishReason,latencyMs:e,model:t.modelVersion,provider:"google"}}function gm(t){if(t.apiKey)return t.apiKey;let e=globalThis.process?.env;return e?.GOOGLE_API_KEY??e?.GEMINI_API_KEY}function ym(t){let e=t.baseURL??"https://generativelanguage.googleapis.com/v1beta",n=t.fetchImpl??fetch,r=s=>{let i=s?.model??t.model;if(!i)throw new Error("googleAdapter: model must be set via options.model or invokeOpts.model");return i},o=()=>{let s=gm(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,i){let a=r(i),u=cs(s,i),c=B(),d=`${e}/models/${encodeURIComponent(a)}:generateContent?${o()}`,l=await n(d,{method:"POST",headers:{"content-type":"application/json",...t.headers??{}},body:JSON.stringify(u),signal:i?.signal});if(!l.ok)throw await dl(l);let f=await l.json(),p=Math.max(0,(B()-c)/1e6);return ll(f,p)},async*stream(s,i){let a=r(i),u=cs(s,i),c=`${e}/models/${encodeURIComponent(a)}:streamGenerateContent?alt=sse&${o()}`,d=await n(c,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",...t.headers??{}},body:JSON.stringify(u),signal:i?.signal});if(!d.ok)throw await dl(d);if(!d.body)throw new Error("googleAdapter: streaming response has no body");let l,f;for await(let p of vm(d.body)){if(!p.data)continue;let m;try{m=JSON.parse(p.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&&(f=h.finishReason),m.usageMetadata&&(l=m.usageMetadata)}l&&(yield{type:"usage",usage:ia(l)}),yield{type:"finish",reason:f??"stop"}}}}function bm(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=cs(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=B(),a=await e.models.generateContent({...o,model:s},{signal:r?.signal}),u=Math.max(0,(B()-i)/1e6);return ll(a,u)},async*stream(n,r){if(!e.models.generateContentStream)throw new Error("sdkBackedGoogle: SDK instance does not expose generateContentStream");let o=cs(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i,a;for await(let u of e.models.generateContentStream({...o,model:s},{signal:r?.signal})){let c=u.candidates?.[0];for(let d of c?.content?.parts??[])typeof d.text=="string"&&(d.thought?yield{type:"thinking",delta:d.text}:yield{type:"token",delta:d.text}),d.functionCall&&(yield{type:"tool-call-delta",delta:{name:d.functionCall.name,argumentsDelta:JSON.stringify(d.functionCall.args??{})}});c?.finishReason&&(a=c.finishReason),u.usageMetadata&&(i=u.usageMetadata)}i&&(yield{type:"usage",usage:ia(i)}),yield{type:"finish",reason:a??"stop"}}}}async function*vm(t){let e=t.getReader(),n=new TextDecoder,r="";try{for(;;){let{done:o,value:s}=await e.read();if(o){r.length>0&&(yield ul(r));return}r+=n.decode(s,{stream:!0});let i=cl(r);for(;i!==null;){let a=r.slice(0,i.index);r=r.slice(i.index+i.length);let u=ul(a);(u.data||u.event)&&(yield u),i=cl(r)}}}finally{e.releaseLock()}}function ul(t){let e={},n=[];for(let r of t.split(`
42
+ `)}]});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(Km)}]),e?.providerExtras&&Object.assign(o,e.providerExtras),o}function Km(t){return{name:t.name,description:t.description,parameters:t.parameters}}function ua(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 Cl(t,e){let n=t.candidates?.[0],r=n?.content?.parts??[],o=[],s=[],i=0;for(let a of r)typeof a.text=="string"&&o.push(a.text),a.functionCall&&s.push({id:`${a.functionCall.name}-${i++}`,name:a.functionCall.name,arguments:a.functionCall.args??{}});return{content:o.join(""),toolCalls:s.length>0?s:void 0,usage:ua(t.usageMetadata),finishReason:n?.finishReason,latencyMs:e,model:t.modelVersion,provider:"google"}}function Hm(t){if(t.apiKey)return t.apiKey;let e=globalThis.process?.env;return e?.GOOGLE_API_KEY??e?.GEMINI_API_KEY}function Wm(t){let e=t.baseURL??"https://generativelanguage.googleapis.com/v1beta",n=t.fetchImpl??fetch,r=s=>{let i=s?.model??t.model;if(!i)throw new Error("googleAdapter: model must be set via options.model or invokeOpts.model");return i},o=()=>{let s=Hm(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,i){let a=r(i),u=us(s,i),c=$(),d=`${e}/models/${encodeURIComponent(a)}:generateContent?${o()}`,l=await n(d,{method:"POST",headers:{"content-type":"application/json",...t.headers??{}},body:JSON.stringify(u),signal:i?.signal});if(!l.ok)throw await Ol(l);let f=await l.json(),p=Math.max(0,($()-c)/1e6);return Cl(f,p)},async*stream(s,i){let a=r(i),u=us(s,i),c=`${e}/models/${encodeURIComponent(a)}:streamGenerateContent?alt=sse&${o()}`,d=await n(c,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",...t.headers??{}},body:JSON.stringify(u),signal:i?.signal});if(!d.ok)throw await Ol(d);if(!d.body)throw new Error("googleAdapter: streaming response has no body");let l,f;for await(let p of Um(d.body)){if(!p.data)continue;let m;try{m=JSON.parse(p.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&&(f=h.finishReason),m.usageMetadata&&(l=m.usageMetadata)}l&&(yield{type:"usage",usage:ua(l)}),yield{type:"finish",reason:f??"stop"}}}}function qm(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=us(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=$(),a=await e.models.generateContent({...o,model:s},{signal:r?.signal}),u=Math.max(0,($()-i)/1e6);return Cl(a,u)},async*stream(n,r){if(!e.models.generateContentStream)throw new Error("sdkBackedGoogle: SDK instance does not expose generateContentStream");let o=us(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i,a;for await(let u of e.models.generateContentStream({...o,model:s},{signal:r?.signal})){let c=u.candidates?.[0];for(let d of c?.content?.parts??[])typeof d.text=="string"&&(d.thought?yield{type:"thinking",delta:d.text}:yield{type:"token",delta:d.text}),d.functionCall&&(yield{type:"tool-call-delta",delta:{name:d.functionCall.name,argumentsDelta:JSON.stringify(d.functionCall.args??{})}});c?.finishReason&&(a=c.finishReason),u.usageMetadata&&(i=u.usageMetadata)}i&&(yield{type:"usage",usage:ua(i)}),yield{type:"finish",reason:a??"stop"}}}}async function*Um(t){let e=t.getReader(),n=new TextDecoder,r="";try{for(;;){let{done:o,value:s}=await e.read();if(o){r.length>0&&(yield _l(r));return}r+=n.decode(s,{stream:!0});let i=Ml(r);for(;i!==null;){let a=r.slice(0,i.index);r=r.slice(i.index+i.length);let u=_l(a);(u.data||u.event)&&(yield u),i=Ml(r)}}}finally{e.releaseLock()}}function _l(t){let e={},n=[];for(let r of t.split(`
42
43
  `)){let o=r.endsWith("\r")?r.slice(0,-1):r;if(!o||o.startsWith(":"))continue;let s=o.indexOf(":"),i=s===-1?o:o.slice(0,s),a=s===-1?"":o.slice(s+1).replace(/^ /,"");i==="data"?n.push(a):i==="event"?e.event=a:i==="id"&&(e.id=a)}return n.length>0&&(e.data=n.join(`
43
- `)),e}function cl(t){let e=t.indexOf(`\r
44
+ `)),e}function Ml(t){let e=t.indexOf(`\r
44
45
  \r
45
46
  `),n=t.indexOf(`
46
47
 
47
- `),r=null;return e!==-1&&(r={index:e,length:4}),n!==-1&&(r===null||n<r.index)&&(r={index:n,length:2}),r}async function dl(t){let e;try{e=await t.text()}catch{e=""}let n=new Error(`Google API ${t.status}: ${t.statusText}${e?` \u2014 ${e}`:""}`);return n.status=t.status,n.headers=t.headers,n}Te();var Tm={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 aa(t={}){return t.sdk?Sm(t):Rm(t)}function ds(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 i=t.map(wm);e?.systemPrompt&&!t.some(u=>u.role==="system")&&i.unshift({role:"system",content:e.systemPrompt});let a={model:s,messages:i};return e?.maxTokens!=null&&(a.max_tokens=e.maxTokens),e?.temperature!=null&&(a.temperature=e.temperature),e?.tools&&e.tools.length>0&&(a.tools=e.tools.map(km)),e?.maxReasoningTokens!=null&&(a.reasoning={max_tokens:e.maxReasoningTokens}),r&&(a.stream=!0,a.stream_options={include_usage:!0}),o&&Object.assign(a,o),e?.providerExtras&&Object.assign(a,e.providerExtras),a}function wm(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 km(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}}function ua(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 hl(t,e,n){let r=t.choices[0],o=r?.message,s=o?.content??"",i=(o?.tool_calls??[]).map(a=>({id:a.id,name:a.function.name,arguments:xm(a.function.arguments)}));return{content:s,toolCalls:i.length>0?i:void 0,usage:ua(t.usage),finishReason:r?.finish_reason,latencyMs:e,model:t.model,provider:n}}function xm(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!=null?e:{_raw:t}}catch{return{_raw:t}}}function gl(t){let e=t.preset??"openai",n=Tm[e],r=t.baseURL??n.baseURL,o=t.provider??n.provider,s=n.apiKeyEnv,i=t.apiKey??(s?globalThis.process?.env?.[s]:void 0);return{provider:o,baseURL:r,apiKey:i}}function Rm(t){let{provider:e,baseURL:n,apiKey:r}=gl(t),o=t.fetchImpl??fetch,s=e!=="ollama",i=()=>{let a={"content-type":"application/json",...t.headers??{}};if(s){if(!r)throw new Error(`openAICompatAdapter[${e}]: apiKey required for invoke/stream`);a.authorization=`Bearer ${r}`}return a};return{provider:e,model:t.model,async invoke(a,u){let c=ds(a,u,t.model,!1,t.bodyExtras),d=B(),l=await o(`${n}/chat/completions`,{method:"POST",headers:i(),body:JSON.stringify(c),signal:u?.signal});if(!l.ok)throw await ml(l,e);let f=await l.json(),p=Math.max(0,(B()-d)/1e6);return hl(f,p,e)},async*stream(a,u){let c=ds(a,u,t.model,!0,t.bodyExtras),d=await o(`${n}/chat/completions`,{method:"POST",headers:{...i(),accept:"text/event-stream"},body:JSON.stringify(c),signal:u?.signal});if(!d.ok)throw await ml(d,e);if(!d.body)throw new Error(`openAICompatAdapter[${e}]: streaming response has no body`);let l,f;for await(let p of Nm(d.body)){if(!p.data||p.data==="[DONE]")continue;let m;try{m=JSON.parse(p.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&&(f=g.finish_reason)}m.usage&&(l=m.usage,yield{type:"usage",usage:ua(l)})}yield{type:"finish",reason:f??"stop"}}}}function Sm(t){let e=t.sdk;if(!e)throw new Error("sdkBackedOpenAI: sdk instance required");let{provider:n}=gl(t);return{provider:n,model:t.model,async invoke(r,o){let s=ds(r,o,t.model,!1,t.bodyExtras),i=B(),a=await e.chat.completions.create(s,{signal:o?.signal}),u=Math.max(0,(B()-i)/1e6);return hl(a,u,n)},async*stream(r,o){let s=ds(r,o,t.model,!0,t.bodyExtras),i=await e.chat.completions.create(s,{signal:o?.signal}),a,u;for await(let c of i){let d=c.choices;if(d){let f=d[0];if(f?.delta?.content&&(yield{type:"token",delta:f.delta.content}),f?.delta?.reasoning_content&&(yield{type:"thinking",delta:f.delta.reasoning_content}),f?.delta?.tool_calls)for(let p of f.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:p.id,name:p.function?.name,argumentsDelta:p.function?.arguments}};f?.finish_reason&&(u=f.finish_reason)}let l=c.usage;l&&(a=l,yield{type:"usage",usage:ua(l)})}yield{type:"finish",reason:u??"stop"}}}}async function*Nm(t){let e=t.getReader(),n=new TextDecoder,r="";try{for(;;){let{done:o,value:s}=await e.read();if(o){r.length>0&&(yield pl(r));return}r+=n.decode(s,{stream:!0});let i=fl(r);for(;i!==null;){let a=r.slice(0,i.index);r=r.slice(i.index+i.length);let u=pl(a);(u.data||u.event)&&(yield u),i=fl(r)}}}finally{e.releaseLock()}}function pl(t){let e={},n=[];for(let r of t.split(`
48
+ `),r=null;return e!==-1&&(r={index:e,length:4}),n!==-1&&(r===null||n<r.index)&&(r={index:n,length:2}),r}async function Ol(t){let e;try{e=await t.text()}catch{e=""}let n=new Error(`Google API ${t.status}: ${t.statusText}${e?` \u2014 ${e}`:""}`);return n.status=t.status,n.headers=t.headers,n}ke();var zm={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 ca(t={}){return t.sdk?Zm(t):Xm(t)}function cs(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 i=t.map(Jm);e?.systemPrompt&&!t.some(u=>u.role==="system")&&i.unshift({role:"system",content:e.systemPrompt});let a={model:s,messages:i};return e?.maxTokens!=null&&(a.max_tokens=e.maxTokens),e?.temperature!=null&&(a.temperature=e.temperature),e?.tools&&e.tools.length>0&&(a.tools=e.tools.map(Ym)),e?.maxReasoningTokens!=null&&(a.reasoning={max_tokens:e.maxReasoningTokens}),r&&(a.stream=!0,a.stream_options={include_usage:!0}),o&&Object.assign(a,o),e?.providerExtras&&Object.assign(a,e.providerExtras),a}function Jm(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 Ym(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}}function da(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 Pl(t,e,n){let r=t.choices[0],o=r?.message,s=o?.content??"",i=(o?.tool_calls??[]).map(a=>({id:a.id,name:a.function.name,arguments:Qm(a.function.arguments)}));return{content:s,toolCalls:i.length>0?i:void 0,usage:da(t.usage),finishReason:r?.finish_reason,latencyMs:e,model:t.model,provider:n}}function Qm(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!=null?e:{_raw:t}}catch{return{_raw:t}}}function Dl(t){let e=t.preset??"openai",n=zm[e],r=t.baseURL??n.baseURL,o=t.provider??n.provider,s=n.apiKeyEnv,i=t.apiKey??(s?globalThis.process?.env?.[s]:void 0);return{provider:o,baseURL:r,apiKey:i}}function Xm(t){let{provider:e,baseURL:n,apiKey:r}=Dl(t),o=t.fetchImpl??fetch,s=e!=="ollama",i=()=>{let a={"content-type":"application/json",...t.headers??{}};if(s){if(!r)throw new Error(`openAICompatAdapter[${e}]: apiKey required for invoke/stream`);a.authorization=`Bearer ${r}`}return a};return{provider:e,model:t.model,async invoke(a,u){let c=cs(a,u,t.model,!1,t.bodyExtras),d=$(),l=await o(`${n}/chat/completions`,{method:"POST",headers:i(),body:JSON.stringify(c),signal:u?.signal});if(!l.ok)throw await Il(l,e);let f=await l.json(),p=Math.max(0,($()-d)/1e6);return Pl(f,p,e)},async*stream(a,u){let c=cs(a,u,t.model,!0,t.bodyExtras),d=await o(`${n}/chat/completions`,{method:"POST",headers:{...i(),accept:"text/event-stream"},body:JSON.stringify(c),signal:u?.signal});if(!d.ok)throw await Il(d,e);if(!d.body)throw new Error(`openAICompatAdapter[${e}]: streaming response has no body`);let l,f;for await(let p of eh(d.body)){if(!p.data||p.data==="[DONE]")continue;let m;try{m=JSON.parse(p.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&&(f=g.finish_reason)}m.usage&&(l=m.usage,yield{type:"usage",usage:da(l)})}yield{type:"finish",reason:f??"stop"}}}}function Zm(t){let e=t.sdk;if(!e)throw new Error("sdkBackedOpenAI: sdk instance required");let{provider:n}=Dl(t);return{provider:n,model:t.model,async invoke(r,o){let s=cs(r,o,t.model,!1,t.bodyExtras),i=$(),a=await e.chat.completions.create(s,{signal:o?.signal}),u=Math.max(0,($()-i)/1e6);return Pl(a,u,n)},async*stream(r,o){let s=cs(r,o,t.model,!0,t.bodyExtras),i=await e.chat.completions.create(s,{signal:o?.signal}),a,u;for await(let c of i){let d=c.choices;if(d){let f=d[0];if(f?.delta?.content&&(yield{type:"token",delta:f.delta.content}),f?.delta?.reasoning_content&&(yield{type:"thinking",delta:f.delta.reasoning_content}),f?.delta?.tool_calls)for(let p of f.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:p.id,name:p.function?.name,argumentsDelta:p.function?.arguments}};f?.finish_reason&&(u=f.finish_reason)}let l=c.usage;l&&(a=l,yield{type:"usage",usage:da(l)})}yield{type:"finish",reason:u??"stop"}}}}async function*eh(t){let e=t.getReader(),n=new TextDecoder,r="";try{for(;;){let{done:o,value:s}=await e.read();if(o){r.length>0&&(yield Al(r));return}r+=n.decode(s,{stream:!0});let i=Ll(r);for(;i!==null;){let a=r.slice(0,i.index);r=r.slice(i.index+i.length);let u=Al(a);(u.data||u.event)&&(yield u),i=Ll(r)}}}finally{e.releaseLock()}}function Al(t){let e={},n=[];for(let r of t.split(`
48
49
  `)){let o=r.endsWith("\r")?r.slice(0,-1):r;if(!o||o.startsWith(":"))continue;let s=o.indexOf(":"),i=s===-1?o:o.slice(0,s),a=s===-1?"":o.slice(s+1).replace(/^ /,"");i==="data"?n.push(a):i==="event"?e.event=a:i==="id"&&(e.id=a)}return n.length>0&&(e.data=n.join(`
49
- `)),e}function fl(t){let e=t.indexOf(`\r
50
+ `)),e}function Ll(t){let e=t.indexOf(`\r
50
51
  \r
51
52
  `),n=t.indexOf(`
52
53
 
53
- `),r=null;return e!==-1&&(r={index:e,length:4}),n!==-1&&(r===null||n<r.index)&&(r={index:n,length:2}),r}async function ml(t,e){let n;try{n=await t.text()}catch{n=""}let r=new Error(`${e} API ${t.status}: ${t.statusText}${n?` \u2014 ${n}`:""}`);return r.status=t.status,r.headers=t.headers,r}function Em(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 ta(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 sa(e)}case"dry-run":{let e={model:t.model,...t.extras};return Nt(e)}case"fallback":{let e={provider:t.provider,model:t.model,...t.extras};return oa(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 aa(e)}default:{let e=t.provider;throw new Error(`createAdapter: unknown provider: ${String(e)}`)}}}Te();le();$e();function Et(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 hn(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 yl(){return{input:{regular:0},output:{regular:0}}}function _m(t,e){let n=e?.logMax??1e3,r=je(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:n}),o=N(null,{name:"adapterStats/lastCall"}),s=N(0,{name:"adapterStats/totalCalls"}),i=N(0,{name:"adapterStats/totalInputTokens"}),a=N(0,{name:"adapterStats/totalOutputTokens"}),u=f=>{r.append(f),o.emit(f),s.emit((s.cache??0)+1),i.emit((i.cache??0)+Et(f.usage)),a.emit((a.cache??0)+hn(f.usage))},c=()=>{r.clear(),o.emit(null),s.emit(0),i.emit(0),a.emit(0)};return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),invoke(f,p){let m=B(),h=pe(),g=t.invoke(f,p),y=v=>{let T=B();return u({timestamp:T,wallClock:h,provider:t.provider,model:t.model??p?.model??v.model??"",tier:p?.tier??v.tier,usage:v.usage??ca(),latencyMs:Math.max(0,(T-m)/1e6),method:"invoke"}),v};if(g!=null&&typeof g.then=="function")return g.then(y);if(g!=null&&typeof g=="object"&&"content"in g)return y(g);let b=!1;return A([re(g)],([v])=>v==null||b?v:(b=!0,y(v)),{name:"adapterStats/invokeTap"})},async*stream(f,p){let m=B(),h=pe(),g;try{for await(let b of t.stream(f,p))b.type==="usage"&&(g=b.usage),yield b;let y=B();u({timestamp:y,wallClock:h,provider:t.provider,model:t.model??p?.model??"",tier:p?.tier,usage:g??ca(),latencyMs:Math.max(0,(y-m)/1e6),method:"stream"})}catch(y){let b=B(),v=y;throw u({timestamp:b,wallClock:h,provider:t.provider,model:t.model??p?.model??"",tier:p?.tier,usage:g??ca(),latencyMs:Math.max(0,(b-m)/1e6),method:"stream",error:{type:v?.name??"Error",message:v?.message??String(y)}}),y}}},stats:{lastCall:o,allCalls:r,totalCalls:s,totalInputTokens:i,totalOutputTokens:a,reset:c}}}function ca(){return{input:{regular:0},output:{regular:0}}}function Mm(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function da(t="USD"){return{total:0,currency:t}}function bl(t,e,n){let r=Et(t),o=e.currency??"USD",s=n?.withBreakdown===!0,i=s?{}:null,a=0,u=(g,y,b)=>{if(!y||b==null)return;let v=Mm(b,r),T=y*v/1e6;a+=T,s&&(i[g]=(i[g]??0)+T)},c=t.input,d=e.input;if(d&&(u("input.regular",c.regular,d.regular),u("input.cacheRead",c.cacheRead??0,d.cacheRead),u("input.cacheWrite5m",c.cacheWrite5m??0,d.cacheWrite5m),u("input.cacheWrite1h",c.cacheWrite1h??0,d.cacheWrite1h),u("input.cacheWriteOther",c.cacheWriteOther??0,d.cacheWriteOther),u("input.audio",c.audio??0,d.audio),u("input.image",c.image??0,d.image),u("input.video",c.video??0,d.video),u("input.toolUse",c.toolUse??0,d.toolUse),c.extensions&&d.extensions))for(let[g,y]of Object.entries(c.extensions))u(`input.ext.${g}`,y,d.extensions[g]);let l=t.output,f=e.output;if(f&&(u("output.regular",l.regular,f.regular),u("output.reasoning",l.reasoning??0,f.reasoning),u("output.audio",l.audio??0,f.audio),u("output.predictionAccepted",l.predictionAccepted??0,f.predictionAccepted),u("output.predictionRejected",l.predictionRejected??0,f.predictionRejected),l.extensions&&f.extensions))for(let[g,y]of Object.entries(l.extensions))u(`output.ext.${g}`,y,f.extensions[g]);let p=n?.tier;if(p&&e.tierMultipliers){let g=e.tierMultipliers[p];if(g!=null&&(a*=g,s))for(let y of Object.keys(i))i[y]*=g}let m=t.auxiliary,h=e.auxiliary;if(m&&h)for(let[g,y]of Object.entries(m)){let b=h[g];if(b==null||!y)continue;let v=y*b;a+=v,s&&(i[`auxiliary.${g}`]=v)}return s?{total:a,currency:o,breakdown:i}:{total:a,currency:o}}function ls(t,e){return`${t}::${e}`}function Om(t){let e=new Map,n=new Map,r=(o,s,i)=>{e.set(ls(o,s),{provider:o,model:s,pricing:i});let a=n.get(o);a||(a=new Set,n.set(o,a)),a.add(s)};if(t)for(let[o,s,i]of t)r(o,s,i);return{register:r,lookup(o,s){let i=e.get(ls(o,s));if(i)return i.pricing;let a=n.get(o);if(!a)return;let u;for(let c of a)if(s.startsWith(c)&&(!u||c.length>u.key.length)){let d=e.get(ls(o,c));d&&(u={key:c,pricing:d.pricing})}return u?.pricing},remove(o,s){let i=e.delete(ls(o,s));if(i){let a=n.get(o);a?.delete(s),a&&a.size===0&&n.delete(o)}return i},entries(){let o=e.values();return(function*(){for(let{provider:s,model:i,pricing:a}of o)yield[s,i,a]})()}}}function Cm(t,e="USD"){return(n,r)=>{let o=t.lookup(r.provider,r.model);return o?bl(n,o,{tier:r.tier,withBreakdown:r.withBreakdown}):da(e)}}function Am(...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):da()}}vt();function la(t,e={}){let n=e.breaker??pt(e);return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(o,s){if(!n.canExecute())throw new st;try{let i=await Promise.resolve(t.invoke(o,s));return n.recordSuccess(),i}catch(i){throw n.recordFailure(i),i}},async*stream(o,s){if(!n.canExecute())throw new st;try{for await(let i of t.stream(o,s))yield i;n.recordSuccess()}catch(i){throw n.recordFailure(i),i}}},breaker:n}}Te();ie();le();$e();var ps=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"},pa=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),vl=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function fa(t,e){let n=je(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),r=N(vl(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=A([r],([d])=>{let l=d;return!(e.caps.calls!=null&&l.calls>=e.caps.calls||e.caps.inputTokens!=null&&l.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&l.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&l.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(oe(o),e.onExhausted!=null){let d=e.onExhausted,l=!1,f=!0;o.subscribe(p=>{for(let m of p)if(m[0]===R){let h=m[1];if(l&&f&&h===!1){let g=Tl(r.cache??pa,e.caps);g&&d(g)}f=h,l=!0}})}let s=()=>{if(o.cache===!1){let d=r.cache??pa,l=Tl(d,e.caps);return new ps(l??"budget",e.caps[l??"calls"]??0,Lm(d,l??"calls"))}},i=(d,l)=>{let f=t.provider,p={timestamp:B(),wallClock:pe(),provider:f,model:l.model,tier:l.tier,usage:d,latencyMs:l.latencyMs,method:l.method,...l.error?{error:l.error}:{}};n.append(p);let m=r.cache??pa,h=e.pricingFn?m.usd+e.pricingFn(d,{model:l.model,provider:f,tier:l.tier}).total:m.usd;r.emit({calls:m.calls+1,inputTokens:m.inputTokens+Et(d),outputTokens:m.outputTokens+hn(d),usd:h})},a=()=>{n.clear(),r.emit(vl())},u=()=>({input:{regular:0},output:{regular:0}});return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),invoke(d,l){let f=s();if(f)return Promise.reject(f);let p=B(),m=t.invoke(d,l),h=y=>{let b=Math.max(0,(B()-p)/1e6);return i(y.usage??u(),{model:t.model??l?.model??y.model??"",tier:l?.tier??y.tier,latencyMs:b,method:"invoke"}),y};if(m!=null&&typeof m.then=="function")return m.then(h);if(m!=null&&typeof m=="object"&&"content"in m)return h(m);let g=!1;return A([re(m)],([y])=>y==null||g?y:(g=!0,h(y)),{name:"budgetGate/invokeTap"})},async*stream(d,l){let f=s();if(f)throw f;let p=B(),m;try{for await(let h of t.stream(d,l))h.type==="usage"&&(m=h.usage),yield h;i(m??u(),{model:t.model??l?.model??"",tier:l?.tier,latencyMs:Math.max(0,(B()-p)/1e6),method:"stream"})}catch(h){let g=h;throw i(m??u(),{model:t.model??l?.model??"",tier:l?.tier,latencyMs:Math.max(0,(B()-p)/1e6),method:"stream",error:{type:g?.name??"Error",message:g?.message??String(h)}}),h}}},budget:{totals:r,isOpen:o,log:n,reset:a}}}function Tl(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 Lm(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}$e();function Im(t,e){let n=e.mock??Nt({provider:t.provider,model:t.model}),r=typeof e.enabled=="boolean"?e.enabled:void 0,o=r===void 0?re(e.enabled):void 0,s;o&&(s=oe(o));let i=()=>r!==void 0?r:!!o?.cache;return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),invoke(c,d){return i()?n.invoke(c,d):t.invoke(c,d)},stream(c,d){return i()?n.stream(c,d):t.stream(c,d)}},dispose:()=>{s&&(s(),s=void 0)}}}function ma(t){if(t==null||typeof t!="object")return;let e=t,n=e.status,r=Pm(e.headers);if(n!==429&&n!==503&&!jm(e.message))return;let o={},s=r("retry-after"),i=Gm(s);i!=null&&(o.retryAfterMs=i);let a=r("anthropic-ratelimit-requests-reset");if(a){let p=wl(a);p!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,p))}let u=r("anthropic-ratelimit-tokens-reset");if(u){let p=wl(u);p!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,p))}let c=fs(r,"x-ratelimit-limit-requests");c!=null&&(o.rpmCap=c);let d=fs(r,"x-ratelimit-limit-tokens");d!=null&&(o.tpmCap=d);let l=fs(r,"x-ratelimit-remaining-requests"),f=fs(r,"x-ratelimit-remaining-tokens");if(l!=null&&c!=null&&c>0&&(o.usageHint??={},o.usageHint.rpm=1-l/c),f!=null&&d!=null&&d>0&&(o.usageHint??={},o.usageHint.tpm=1-f/d),o.retryAfterMs==null&&e.message){let p=$m(e.message);p!=null&&(o.retryAfterMs=p)}return e.headers&&(o.metadata={headers:Dm(e.headers)}),o.retryAfterMs==null&&o.rpmCap==null&&o.tpmCap==null&&o.usageHint==null?o.metadata?o:void 0:o}function Pm(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 Dm(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 fs(t,e){let n=t(e);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function Gm(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 wl(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var Fm=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function $m(t){let e=Fm.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 Bm=/rate\s*limit|too\s*many\s*requests|quota|429/i;function jm(t){return!!t&&Bm.test(t)}Te();ie();le();vt();$e();lt();function ha(t){let e=new Error(t);return e.name="AbortError",e}function xl(t={}){let e=Math.max(1,t.burstMultiplier??1),n=t.clampCooldownMs??6e4,r=t.rpm!=null?re(t.rpm):N(Number.POSITIVE_INFINITY),o=t.tpm!=null?re(t.tpm):N(Number.POSITIVE_INFINITY),s=N(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),i=N(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),a=N({},{name:"adaptiveRateLimiter/lastSignal"}),u=A([r,s],([C,K])=>Math.min(Number(C??1/0),Number(K??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),c=A([o,i],([C,K])=>Math.min(Number(C??1/0),Number(K??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),d=Hn(Number(r.cache??Number.POSITIVE_INFINITY),e),l=Hn(Number(o.cache??Number.POSITIVE_INFINITY),e),f=!1,p=!1,m=u.subscribe(C=>{for(let K of C)if(K[0]===R){let ne=Number(K[1]);Number.isFinite(ne)&&ne>0?(d=Hn(ne,e),f=!1):ne===1/0?(d=Hn(1/0,e),f=!1):ne<=0&&(f=!0)}}),h=c.subscribe(C=>{for(let K of C)if(K[0]===R){let ne=Number(K[1]);Number.isFinite(ne)&&ne>0?(l=Hn(ne,e),p=!1):ne===1/0?(l=Hn(1/0,e),p=!1):ne<=0&&(p=!0)}}),g=0,y=new Re,b=new Re,v;t.adaptation!=null&&(v=re(t.adaptation).subscribe(K=>{for(let ne of K)ne[0]===R&&T(ne[1])}));function T(C){if(a.emit(C),C.rpmCap!=null&&Number.isFinite(C.rpmCap)&&C.rpmCap>=0&&(s.emit(C.rpmCap),Number.isFinite(n)&&n>0&&y.start(n,()=>s.emit(Number.POSITIVE_INFINITY))),C.tpmCap!=null&&Number.isFinite(C.tpmCap)&&C.tpmCap>=0&&(i.emit(C.tpmCap),Number.isFinite(n)&&n>0&&b.start(n,()=>i.emit(Number.POSITIVE_INFINITY))),C.retryAfterMs!=null&&C.retryAfterMs>0){let K=B()+C.retryAfterMs*1e6;K>g&&(g=K)}}let w=N(0,{name:"adaptiveRateLimiter/pending"}),k=N(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),x=N(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),S=C=>{w.emit((w.cache??0)+C)},_=()=>{k.emit(d.available()),x.emit(l.available())};async function F(C={}){let K=C.requestCost??1,ne=C.tokenCost??0,P=C.signal;S(1);try{for(;;){if(P?.aborted)throw ha("AdaptiveRateLimiter.acquire aborted");let E=B();if(g>E){let ce=Math.ceil((g-E)/1e6);await ms(ce,P);continue}if(K>0&&f||ne>0&&p){await ms(250,P);continue}let I=d,G=l;if(!I.tryConsume(K)){await ms(kl(I,K),P);continue}if(!(ne>0?G.tryConsume(ne):!0)){I.putBack(K),await ms(kl(G,ne),P);continue}_();return}}finally{S(-1)}}function L(C){C>0?l.tryConsume(C):C<0&&l.putBack(-C),_()}function D(){m(),h(),v?.(),y.cancel(),b.cancel()}return{effectiveRpm:u,effectiveTpm:c,lastSignal:a,pending:w,rpmAvailable:k,tpmAvailable:x,acquire:F,recordUsage:L,recordSignal:T,dispose:D}}function Hn(t,e){if(!Number.isFinite(t)||t===1/0)return At(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let n=Math.max(1,t*e),r=t/60;return At(n,r)}function kl(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 ms(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(ha("AdaptiveRateLimiter.acquire aborted")):new Promise((n,r)=>{let o=new Re,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(ha("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",s,{once:!0}))})}$e();function ga(t,e={}){let n=e.limiter??xl({name:e.name??"rateLimiter",rpm:e.rpm,tpm:e.tpm,adaptation:e.adaptation,burstMultiplier:e.burstMultiplier}),r=(i,a)=>e.costFn?e.costFn(i,a):0,o=i=>{let a=ma(i);a&&n.recordSignal(a)};return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(i,a){let u=r(i,a);await n.acquire({requestCost:1,tokenCost:u,signal:a?.signal});try{let c=t.invoke(i,a),d=await Km(c),l=d.usage??yl(),p=Et(l)+hn(l)-u;return p>0&&n.recordUsage(p),d}catch(c){throw o(c),c}},async*stream(i,a){let u=r(i,a);await n.acquire({requestCost:1,tokenCost:u,signal:a?.signal});try{let c=0;for await(let l of t.stream(i,a))l.type==="usage"&&(c=Et(l.usage)+hn(l.usage)),yield l;let d=c-u;d>0&&n.recordUsage(d)}catch(c){throw o(c),c}}},limiter:n}}async function Km(t){return t!=null&&typeof t.then=="function"?await t:t&&typeof t=="object"&&"content"in t?t:await $n(re(t))}vt();var Gr=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 ya(t,e={}){if(t.length===0)throw new RangeError("cascadingLlmAdapter: tiers must be non-empty");let n=t.map(o=>({name:o.name,adapter:o.adapter,filter:o.filter,breaker:o.breaker?"canExecute"in o.breaker?o.breaker:pt(o.breaker):void 0})),r=e.streamRetryBeforeFirstChunk??!0;return{provider:"cascading",model:void 0,async invoke(o,s){let i=[],a=new Map;for(let c=0;c<n.length;c++){let d=n[c];if(d.filter&&!d.filter(o,s)){i.push({name:d.name,reason:"filter"});continue}if(d.breaker&&!d.breaker.canExecute()){i.push({name:d.name,reason:"breaker"});continue}try{let l=await Promise.resolve(d.adapter.invoke(o,s));return d.breaker?.recordSuccess(),{...l,metadata:{...l.metadata??{},tier:d.name}}}catch(l){a.set(d.name,l),d.breaker?.recordFailure(l);let f=n[c+1];f&&e.onFallback?.(d.name,f.name,l)}}let u={skipped:i,failed:a};throw e.onExhausted?.(u),new Gr(u)},async*stream(o,s){let i=[],a=new Map;for(let c=0;c<n.length;c++){let d=n[c];if(d.filter&&!d.filter(o,s)){i.push({name:d.name,reason:"filter"});continue}if(d.breaker&&!d.breaker.canExecute()){i.push({name:d.name,reason:"breaker"});continue}let l=!1;try{for await(let f of d.adapter.stream(o,s))l=!0,yield f;d.breaker?.recordSuccess();return}catch(f){if(a.set(d.name,f),d.breaker?.recordFailure(f),l||!r)throw f;let p=n[c+1];p&&e.onFallback?.(d.name,p.name,f)}}let u={skipped:i,failed:a};throw e.onExhausted?.(u),new Gr(u)}}}lt();function hs(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function Rl(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(hs()):new Promise((n,r)=>{let o=new Re,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(hs())},e.addEventListener("abort",s,{once:!0}))})}function ba(t,e={}){let n=e.attempts??3,r=e.baseDelayMs??500,o=e.maxDelayMs??1e4,s=e.strategy??"decorrelated",i=e.jitter??!0,a=e.shouldRetry??Vm,u=e.retryStreaming??!0,c=(d,l)=>{if(s==="decorrelated"){let h=Math.min(o,Math.max(r,l*3));return r+Math.random()*(h-r)}let f=s==="exp"?r*2**(d-1):r*d,p=Math.min(o,f);if(!i)return p;let m=p*(.5+Math.random());return Math.min(o,m)};return{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(d,l){if(l?.signal?.aborted)throw hs();let f,p=r;for(let m=1;m<=n;m++)try{return await Promise.resolve(t.invoke(d,l))}catch(h){if(f=h,m>=n||!a(h,m))throw h;let g=c(m,p);p=g,await Rl(g,l?.signal)}throw f},async*stream(d,l){if(l?.signal?.aborted)throw hs();if(!u){for await(let m of t.stream(d,l))yield m;return}let f,p=r;for(let m=1;m<=n;m++){let h=!1;try{for await(let g of t.stream(d,l))h=!0,yield g;return}catch(g){if(f=g,h||m>=n||!a(g,m))throw g;let y=c(m,p);p=y,await Rl(y,l?.signal)}}throw f}}}function Vm(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}lt();var Wn=class extends Error{constructor(n){super(`LLM call timed out after ${n}ms`);this.ms=n}name="LLMTimeoutError"};function va(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let n=o=>{let s=new AbortController,i=!1,a;o&&(o.aborted?s.abort(o.reason):(a=()=>s.abort(o.reason),o.addEventListener("abort",a,{once:!0})));let u=new Re;return u.start(e,()=>{i=!0,s.abort(new Wn(e))}),{signal:s.signal,cancel:()=>{u.cancel(),o&&a&&o.removeEventListener("abort",a)},timedOut:()=>i}},r=(o,s)=>{if(!s||o instanceof Wn)throw o;let i=o;if(i?.name==="AbortError"||i?.name==="DOMException"&&Number(i.code)===20||o?.message==="aborted"){let u=new Wn(e);throw u.cause=o,u}throw o};return{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(o,s){let{signal:i,cancel:a,timedOut:u}=n(s?.signal);try{return await Promise.resolve(t.invoke(o,{...s,signal:i}))}catch(c){return r(c,u())}finally{a()}},async*stream(o,s){let{signal:i,cancel:a,timedOut:u}=n(s?.signal);try{for await(let c of t.stream(o,{...s,signal:i}))yield c}catch(c){r(c,u())}finally{a()}}}}function qm(t,e={}){let n={adapter:t},r=t;if(e.rateLimit){let o=ga(r,e.rateLimit);r=o.adapter,n.rateLimiter=o.limiter}if(e.budget){let o=fa(r,e.budget);r=o.adapter,n.budget=o.budget}if(e.breaker){let o=la(r,e.breaker);r=o.adapter,n.breaker=o.breaker}if(e.timeoutMs!=null&&(r=va(r,e.timeoutMs)),e.retry&&(r=ba(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=ya([{name:e.name??"primary",adapter:r},{name:"fallback",adapter:e.fallback}],o)}return n.adapter=r,n}function Hm(){return Nt()}function Ce(t,e){return Ke("ai",t,e)}function Wm(t){return t!=null&&typeof t.then=="function"}function Um(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function zm(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var Jm=3e4;function Sl(t,e){if(t.status==="settled"){let r=t.cache;if(r!==void 0)return Promise.resolve(r)}let n=e?.timeoutMs??Jm;return new Promise((r,o)=>{let s=new Re,i=t.subscribe(a=>{for(let u of a){if(u[0]===R){s.cancel(),i(),r(u[1]);return}if(u[0]===O){s.cancel(),i(),o(u[1]);return}if(u[0]===M){s.cancel(),i(),o(new Error("firstDataFromNode: completed without producing a value"));return}}});s.start(n,()=>{i(),o(new Error(`firstDataFromNode: timed out after ${n}ms`))})})}async function vs(t){return Wm(t)?vs(await t):Um(t)?Sl(t):zm(t)?Sl(re(t)):t}function Ym(t,e){let n=re(t),r=e?.refreshTrigger!=null?re(e.refreshTrigger):null;return r==null?q([n],(o,s,i)=>{if(i.store.emitted===!0)return;let u=o[0],c=u!=null&&u.length>0?u.at(-1):i.prevData[0];if(c!==void 0)return i.store.emitted=!0,s.emit(c),{invalidate:()=>{i.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:Ce("frozen_context")}):q([n,r],(o,s,i)=>{let a=o[1];if(!(a!=null&&a.length>0))return;let c=o[0],d=c!=null&&c.length>0?c.at(-1):i.prevData[0];s.emit(d)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:Ce("frozen_context")})}function Qm(t,e,n){let r=re(e);return _e(r,s=>{if(!s||s.length===0)return N(null);let i=n?.tools;return t.invoke(s,{model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,tools:i,systemPrompt:n?.systemPrompt})})}function Xm(t,e,n,r){let o=r?.name??"llm",s=r?.format??"text",i=Rt(`${o}/stream`),a=A(e,d=>{if(d.some(p=>p==null))return[];let l=typeof n=="string"?n:n(...d);if(!l)return[];let f=[];return r?.systemPrompt&&f.push({role:"system",content:r.systemPrompt}),f.push({role:"user",content:l}),f}),u=_e(a,d=>{let l=d;if(!l||l.length===0)return N(null);let f=new AbortController;async function*p(){let m="",h=0;try{for await(let y of t.stream(l,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,signal:f.signal})){if(y.type!=="token")continue;let b=y.delta;m+=b,i.publish({source:o,token:b,accumulated:m,index:h++})}let g;if(s==="json")try{g=JSON.parse(Ts(m))}catch{g=null}else g=m;yield g}finally{f.abort()}}return re(p())}),c=oe(u);return{output:u,stream:i,dispose:()=>{c(),i.destroy()}}}function Zm(t,e,n){return A([t.latest],([r])=>r==null?null:e(r.accumulated),{name:n?.name??"extractor",describeKind:"derived",initial:null,meta:Ce("stream_extractor"),...n?.equals?{equals:n.equals}:{}})}var eh=(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 th(t,e){let n=e.maxPatternLength??128;return A([t.latest],([r],o)=>{if(r==null)return[];let s=r.accumulated;"flags"in o.store||(o.store.flags=[],o.store.scannedTo=0);let i=o.store.flags,a=o.store.scannedTo,u=Math.max(0,a-n),c=s.slice(u),d=!1;for(let{pattern:l,label:f}of e.patterns){let p=new RegExp(l.source,`${l.flags.replace("g","")}g`);for(let m of c.matchAll(p)){let h=u+m.index;h+m[0].length<=a||(i.push({label:f,pattern:l,match:m[0],position:h}),d=!0)}}return o.store.scannedTo=s.length,d?[...i]:i.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:Ce("keyword_flag_extractor"),equals:eh})}var nh=(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 rh(t,e){return A([t.latest],([n],r)=>{if(n==null)return[];let o=n.accumulated;"calls"in r.store||(r.store.calls=[],r.store.scanFrom=0);let s=r.store.calls,i=r.store.scanFrom,a=!1;for(;i<o.length;){let u=o.indexOf("{",i);if(u===-1){r.store.scanFrom=o.length;break}let c=0,d=-1,l=!1;for(let p=u;p<o.length;p++){let m=o[p];if(l)m==="\\"&&p+1<o.length?p++:m==='"'&&(l=!1);else if(m==='"')l=!0;else if(m==="{")c++;else if(m==="}"&&(c--,c===0)){d=p;break}}if(d===-1){r.store.scanFrom=u;break}let f=o.slice(u,d+1);try{let p=JSON.parse(f);typeof p.name=="string"&&p.arguments!=null&&typeof p.arguments=="object"&&(s.push({name:p.name,arguments:p.arguments,raw:f,startIndex:u}),a=!0)}catch{}i=d+1,r.store.scanFrom=i}return a?[...s]:s.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:Ce("tool_call_extractor"),equals:nh})}var oh=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens;function sh(t,e){let n=e?.charsPerToken??4;return A([t.latest],([r])=>{if(r==null)return{chunkCount:0,charCount:0,estimatedTokens:0};let o=r,s=o.accumulated.length;return{chunkCount:o.index+1,charCount:s,estimatedTokens:Math.ceil(s/n)}},{name:e?.name??"cost-meter",describeKind:"derived",initial:{chunkCount:0,charCount:0,estimatedTokens:0},meta:Ce("cost_meter_extractor"),equals:oh})}function ih(t,e,n,r){let o=n??(()=>"[REDACTED]");function s(i){let a=i;for(let u of e){let c=u.global?u:new RegExp(u.source,`${u.flags}g`);a=a.replace(c,d=>o(d,u))}return a}return A([t.latest],([i])=>{if(i==null)return{source:"",token:"",accumulated:"",index:-1};let a=i,u=s(a.accumulated),c=s(a.token);return{source:a.source,token:c,accumulated:u,index:a.index}},{name:r?.name??"redactor"})}function ah(t,e,n,r){let o=n*(r?.hardMultiplier??1.5),s=typeof e!="function",i=[t.latest];return s&&i.push(e),A(i,a=>{let u=a[0];if(u==null)return"allow";let c=s?a[1]??0:e(u.accumulated);return c>=o?"block":c>=n?"review":"allow"},{name:r?.name??"content-gate",initial:"allow"})}function uh(t,e,n,r,o,s){let i=N(0,{name:`${e}/cancel`}),a=0,u=[...r,i],c=s?.name??e,d=s?.format??"text",l=Rt(`${c}/stream`),f=A(u,v=>{let T=v.slice(0,-1);if(T.some(x=>x==null))return[];let w=typeof o=="string"?o:o(...T);if(!w)return[];let k=[];return s?.systemPrompt&&k.push({role:"system",content:s.systemPrompt}),k.push({role:"user",content:w}),k}),p=_e(f,v=>{let T=v;if(!T||T.length===0)return N(null);let w=new AbortController;async function*k(){let x="",S=0;try{for await(let F of n.stream(T,{model:s?.model,temperature:s?.temperature,maxTokens:s?.maxTokens,systemPrompt:s?.systemPrompt,signal:w.signal})){if(F.type!=="token")continue;let L=F.delta;x+=L,l.publish({source:c,token:L,accumulated:x,index:S++})}let _;if(d==="json")try{_=JSON.parse(Ts(x))}catch{_=null}else _=x;yield _}finally{w.abort()}}return re(k())}),m=oe(p),h=A([p],([v])=>{if(v!=null)return v},{name:`${e}/filter`});t.add(h,{name:`${e}/raw`});let g=Dr(t,`${e}/gate`,`${e}/raw`,s?.gate),y=g.reject.bind(g),b={...g,reject(v=1){y(v),i.emit(++a)}};return{output:g.node,stream:l,gate:b,dispose:()=>{m(),l.destroy()}}}function ch(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function Br(t,e,n,r){let o=r?.format??"text",s=r?.retries??0,i=r?.cache??!1,a=i?new Map:null,u=A(e,d=>{if(d.some(p=>p==null))return[];let l=typeof n=="string"?n:n(...d);if(!l)return[];let f=[];return r?.systemPrompt&&f.push({role:"system",content:r.systemPrompt}),f.push({role:"user",content:l}),f},{name:r?.name?`${r.name}::messages`:"prompt_node::messages",meta:Ce("prompt_node"),initial:[]});return _e(u,d=>{if(!d||d.length===0)return N(null);let l=i?JSON.stringify(d.map(p=>[p.role,p.content])):"";if(a?.has(l))return N(a.get(l));async function f(p){try{let m=await new Promise((y,b)=>{let v=t.invoke(d,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt});v&&typeof v.then=="function"?v.then(y,b):v&&typeof v.subscribe=="function"?y(v.cache):y(v)}),h=ch(m),g;return o==="json"?g=JSON.parse(Ts(h)):g=h,a?.set(l,g),g}catch(m){if(p>0)return f(p-1);throw m}}return f(s)})}function dh(t,e,n){let r=re(t),o=n?.condition!=null?re(n.condition):null,s=N(null,{name:n?.name?`${n.name}::null`:"handoff::null"});if(o==null)return _e(r,a=>{if(a==null)return s;let u=N(a);return e(u)});let i=A([r,o],([a,u])=>({v:a,open:u===!0}),{name:n?.name?`${n.name}::router`:"handoff::router",describeKind:"derived"});return _e(i,({v:a,open:u})=>{if(a==null)return s;if(!u)return N(a);let c=N(a);return e(c)})}var gs=class extends z{_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:Ce("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(oe(this.latest)),this.messageCount=A([this.messages],([r])=>r.length,{name:"messageCount",describeKind:"derived",meta:Ce("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(oe(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 _l(t,e){return new gs(t,e)}var ys=class extends z{definitions;schemas;constructor(e,n={}){super(e,n.graph),this.definitions=N(new Map,{name:"definitions",describeKind:"state",meta:Ce("tool_definitions")}),this.add(this.definitions,{name:"definitions"}),this.schemas=A([this.definitions],([r])=>[...(r??new Map).values()],{name:"schemas",describeKind:"derived",meta:Ce("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(oe(this.schemas))}register(e){let n=this.definitions.cache,r=new Map(n);r.set(e.name,e),this.definitions.emit(r)}unregister(e){let n=this.definitions.cache;if(!n.has(e))return;let r=new Map(n);r.delete(e),this.definitions.emit(r)}async execute(e,n){let o=this.definitions.cache.get(e);if(!o)throw new Error(`toolRegistry: unknown tool "${e}"`);let s=o.handler(n);return vs(s)}getDefinition(e){return this.definitions.cache?.get(e)}};function Ml(t,e){return new ys(t,e)}function lh(t,e,n){let r=re(t),o=e.map(i=>re(i)),s=[r,...o];return A(s,i=>{let a=i[0]??[],u=i.slice(1);return a.filter(c=>{for(let d of u)if(d!=null&&!d(c))return!1;return!0})},{name:n?.name??"tool-selector",describeKind:"derived",meta:Ce("tool_selector"),equals:(i,a)=>{let u=i,c=a;if(u.length!==c.length)return!1;for(let d=0;d<u.length;d++)if(u[d]!==c[d])return!1;return!0}})}function ph(t,e){let n=e?.separator??`
54
+ `),r=null;return e!==-1&&(r={index:e,length:4}),n!==-1&&(r===null||n<r.index)&&(r={index:n,length:2}),r}async function Il(t,e){let n;try{n=await t.text()}catch{n=""}let r=new Error(`${e} API ${t.status}: ${t.statusText}${n?` \u2014 ${n}`:""}`);return r.status=t.status,r.headers=t.headers,r}function th(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 ra(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 aa(e)}case"dry-run":{let e={model:t.model,...t.extras};return St(e)}case"fallback":{let e={provider:t.provider,model:t.model,...t.extras};return ia(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 ca(e)}default:{let e=t.provider;throw new Error(`createAdapter: unknown provider: ${String(e)}`)}}}ke();oe();Re();function Nt(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 hn(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 Gl(){return{input:{regular:0},output:{regular:0}}}function nh(t,e){let n=e?.logMax??1e3,r=Ve(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:n}),o=N(null,{name:"adapterStats/lastCall"}),s=N(0,{name:"adapterStats/totalCalls"}),i=N(0,{name:"adapterStats/totalInputTokens"}),a=N(0,{name:"adapterStats/totalOutputTokens"}),u=f=>{r.append(f),o.emit(f),s.emit((s.cache??0)+1),i.emit((i.cache??0)+Nt(f.usage)),a.emit((a.cache??0)+hn(f.usage))},c=()=>{r.clear(),o.emit(null),s.emit(0),i.emit(0),a.emit(0)};return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),invoke(f,p){let m=$(),h=pe(),g=t.invoke(f,p),y=v=>{let T=$();return u({timestamp:T,wallClock:h,provider:t.provider,model:t.model??p?.model??v.model??"",tier:p?.tier??v.tier,usage:v.usage??la(),latencyMs:Math.max(0,(T-m)/1e6),method:"invoke"}),v};if(g!=null&&typeof g.then=="function")return g.then(y);if(g!=null&&typeof g=="object"&&"content"in g)return y(g);let b=!1;return O([re(g)],([v])=>v==null||b?v:(b=!0,y(v)),{name:"adapterStats/invokeTap"})},async*stream(f,p){let m=$(),h=pe(),g;try{for await(let b of t.stream(f,p))b.type==="usage"&&(g=b.usage),yield b;let y=$();u({timestamp:y,wallClock:h,provider:t.provider,model:t.model??p?.model??"",tier:p?.tier,usage:g??la(),latencyMs:Math.max(0,(y-m)/1e6),method:"stream"})}catch(y){let b=$(),v=y;throw u({timestamp:b,wallClock:h,provider:t.provider,model:t.model??p?.model??"",tier:p?.tier,usage:g??la(),latencyMs:Math.max(0,(b-m)/1e6),method:"stream",error:{type:v?.name??"Error",message:v?.message??String(y)}}),y}}},stats:{lastCall:o,allCalls:r,totalCalls:s,totalInputTokens:i,totalOutputTokens:a,reset:c}}}function la(){return{input:{regular:0},output:{regular:0}}}function rh(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function pa(t="USD"){return{total:0,currency:t}}function Fl(t,e,n){let r=Nt(t),o=e.currency??"USD",s=n?.withBreakdown===!0,i=s?{}:null,a=0,u=(g,y,b)=>{if(!y||b==null)return;let v=rh(b,r),T=y*v/1e6;a+=T,s&&(i[g]=(i[g]??0)+T)},c=t.input,d=e.input;if(d&&(u("input.regular",c.regular,d.regular),u("input.cacheRead",c.cacheRead??0,d.cacheRead),u("input.cacheWrite5m",c.cacheWrite5m??0,d.cacheWrite5m),u("input.cacheWrite1h",c.cacheWrite1h??0,d.cacheWrite1h),u("input.cacheWriteOther",c.cacheWriteOther??0,d.cacheWriteOther),u("input.audio",c.audio??0,d.audio),u("input.image",c.image??0,d.image),u("input.video",c.video??0,d.video),u("input.toolUse",c.toolUse??0,d.toolUse),c.extensions&&d.extensions))for(let[g,y]of Object.entries(c.extensions))u(`input.ext.${g}`,y,d.extensions[g]);let l=t.output,f=e.output;if(f&&(u("output.regular",l.regular,f.regular),u("output.reasoning",l.reasoning??0,f.reasoning),u("output.audio",l.audio??0,f.audio),u("output.predictionAccepted",l.predictionAccepted??0,f.predictionAccepted),u("output.predictionRejected",l.predictionRejected??0,f.predictionRejected),l.extensions&&f.extensions))for(let[g,y]of Object.entries(l.extensions))u(`output.ext.${g}`,y,f.extensions[g]);let p=n?.tier;if(p&&e.tierMultipliers){let g=e.tierMultipliers[p];if(g!=null&&(a*=g,s))for(let y of Object.keys(i))i[y]*=g}let m=t.auxiliary,h=e.auxiliary;if(m&&h)for(let[g,y]of Object.entries(m)){let b=h[g];if(b==null||!y)continue;let v=y*b;a+=v,s&&(i[`auxiliary.${g}`]=v)}return s?{total:a,currency:o,breakdown:i}:{total:a,currency:o}}function ds(t,e){return`${t}::${e}`}function oh(t){let e=new Map,n=new Map,r=(o,s,i)=>{e.set(ds(o,s),{provider:o,model:s,pricing:i});let a=n.get(o);a||(a=new Set,n.set(o,a)),a.add(s)};if(t)for(let[o,s,i]of t)r(o,s,i);return{register:r,lookup(o,s){let i=e.get(ds(o,s));if(i)return i.pricing;let a=n.get(o);if(!a)return;let u;for(let c of a)if(s.startsWith(c)&&(!u||c.length>u.key.length)){let d=e.get(ds(o,c));d&&(u={key:c,pricing:d.pricing})}return u?.pricing},remove(o,s){let i=e.delete(ds(o,s));if(i){let a=n.get(o);a?.delete(s),a&&a.size===0&&n.delete(o)}return i},entries(){let o=e.values();return(function*(){for(let{provider:s,model:i,pricing:a}of o)yield[s,i,a]})()}}}function sh(t,e="USD"){return(n,r)=>{let o=t.lookup(r.provider,r.model);return o?Fl(n,o,{tier:r.tier,withBreakdown:r.withBreakdown}):pa(e)}}function ih(...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):pa()}}Tt();function fa(t,e={}){let n=e.breaker??ft(e);return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(o,s){if(!n.canExecute())throw new st;try{let i=await Promise.resolve(t.invoke(o,s));return n.recordSuccess(),i}catch(i){throw n.recordFailure(i),i}},async*stream(o,s){if(!n.canExecute())throw new st;try{for await(let i of t.stream(o,s))yield i;n.recordSuccess()}catch(i){throw n.recordFailure(i),i}}},breaker:n}}ke();ie();oe();Re();var ls=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"},ma=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),$l=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function ha(t,e){let n=Ve(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),r=N($l(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=O([r],([d])=>{let l=d;return!(e.caps.calls!=null&&l.calls>=e.caps.calls||e.caps.inputTokens!=null&&l.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&l.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&l.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(se(o),e.onExhausted!=null){let d=e.onExhausted,l=!1,f=!0;o.subscribe(p=>{for(let m of p)if(m[0]===S){let h=m[1];if(l&&f&&h===!1){let g=Bl(r.cache??ma,e.caps);g&&d(g)}f=h,l=!0}})}let s=()=>{if(o.cache===!1){let d=r.cache??ma,l=Bl(d,e.caps);return new ls(l??"budget",e.caps[l??"calls"]??0,ah(d,l??"calls"))}},i=(d,l)=>{let f=t.provider,p={timestamp:$(),wallClock:pe(),provider:f,model:l.model,tier:l.tier,usage:d,latencyMs:l.latencyMs,method:l.method,...l.error?{error:l.error}:{}};n.append(p);let m=r.cache??ma,h=e.pricingFn?m.usd+e.pricingFn(d,{model:l.model,provider:f,tier:l.tier}).total:m.usd;r.emit({calls:m.calls+1,inputTokens:m.inputTokens+Nt(d),outputTokens:m.outputTokens+hn(d),usd:h})},a=()=>{n.clear(),r.emit($l())},u=()=>({input:{regular:0},output:{regular:0}});return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),invoke(d,l){let f=s();if(f)return Promise.reject(f);let p=$(),m=t.invoke(d,l),h=y=>{let b=Math.max(0,($()-p)/1e6);return i(y.usage??u(),{model:t.model??l?.model??y.model??"",tier:l?.tier??y.tier,latencyMs:b,method:"invoke"}),y};if(m!=null&&typeof m.then=="function")return m.then(h);if(m!=null&&typeof m=="object"&&"content"in m)return h(m);let g=!1;return O([re(m)],([y])=>y==null||g?y:(g=!0,h(y)),{name:"budgetGate/invokeTap"})},async*stream(d,l){let f=s();if(f)throw f;let p=$(),m;try{for await(let h of t.stream(d,l))h.type==="usage"&&(m=h.usage),yield h;i(m??u(),{model:t.model??l?.model??"",tier:l?.tier,latencyMs:Math.max(0,($()-p)/1e6),method:"stream"})}catch(h){let g=h;throw i(m??u(),{model:t.model??l?.model??"",tier:l?.tier,latencyMs:Math.max(0,($()-p)/1e6),method:"stream",error:{type:g?.name??"Error",message:g?.message??String(h)}}),h}}},budget:{totals:r,isOpen:o,log:n,reset:a}}}function Bl(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 ah(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}Re();function uh(t,e){let n=e.mock??St({provider:t.provider,model:t.model}),r=typeof e.enabled=="boolean"?e.enabled:void 0,o=r===void 0?re(e.enabled):void 0,s;o&&(s=se(o));let i=()=>r!==void 0?r:!!o?.cache;return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),invoke(c,d){return i()?n.invoke(c,d):t.invoke(c,d)},stream(c,d){return i()?n.stream(c,d):t.stream(c,d)}},dispose:()=>{s&&(s(),s=void 0)}}}function ga(t){if(t==null||typeof t!="object")return;let e=t,n=e.status,r=ch(e.headers);if(n!==429&&n!==503&&!hh(e.message))return;let o={},s=r("retry-after"),i=lh(s);i!=null&&(o.retryAfterMs=i);let a=r("anthropic-ratelimit-requests-reset");if(a){let p=jl(a);p!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,p))}let u=r("anthropic-ratelimit-tokens-reset");if(u){let p=jl(u);p!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,p))}let c=ps(r,"x-ratelimit-limit-requests");c!=null&&(o.rpmCap=c);let d=ps(r,"x-ratelimit-limit-tokens");d!=null&&(o.tpmCap=d);let l=ps(r,"x-ratelimit-remaining-requests"),f=ps(r,"x-ratelimit-remaining-tokens");if(l!=null&&c!=null&&c>0&&(o.usageHint??={},o.usageHint.rpm=1-l/c),f!=null&&d!=null&&d>0&&(o.usageHint??={},o.usageHint.tpm=1-f/d),o.retryAfterMs==null&&e.message){let p=fh(e.message);p!=null&&(o.retryAfterMs=p)}return e.headers&&(o.metadata={headers:dh(e.headers)}),o.retryAfterMs==null&&o.rpmCap==null&&o.tpmCap==null&&o.usageHint==null?o.metadata?o:void 0:o}function ch(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 dh(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 ps(t,e){let n=t(e);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function lh(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 jl(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var ph=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function fh(t){let e=ph.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 mh=/rate\s*limit|too\s*many\s*requests|quota|429/i;function hh(t){return!!t&&mh.test(t)}ke();ie();oe();Tt();Re();pt();function ya(t){let e=new Error(t);return e.name="AbortError",e}function Kl(t={}){let e=Math.max(1,t.burstMultiplier??1),n=t.clampCooldownMs??6e4,r=t.rpm!=null?re(t.rpm):N(Number.POSITIVE_INFINITY),o=t.tpm!=null?re(t.tpm):N(Number.POSITIVE_INFINITY),s=N(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),i=N(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),a=N({},{name:"adaptiveRateLimiter/lastSignal"}),u=O([r,s],([C,V])=>Math.min(Number(C??1/0),Number(V??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),c=O([o,i],([C,V])=>Math.min(Number(C??1/0),Number(V??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),d=Yn(Number(r.cache??Number.POSITIVE_INFINITY),e),l=Yn(Number(o.cache??Number.POSITIVE_INFINITY),e),f=!1,p=!1,m=u.subscribe(C=>{for(let V of C)if(V[0]===S){let ne=Number(V[1]);Number.isFinite(ne)&&ne>0?(d=Yn(ne,e),f=!1):ne===1/0?(d=Yn(1/0,e),f=!1):ne<=0&&(f=!0)}}),h=c.subscribe(C=>{for(let V of C)if(V[0]===S){let ne=Number(V[1]);Number.isFinite(ne)&&ne>0?(l=Yn(ne,e),p=!1):ne===1/0?(l=Yn(1/0,e),p=!1):ne<=0&&(p=!0)}}),g=0,y=new _e,b=new _e,v;t.adaptation!=null&&(v=re(t.adaptation).subscribe(V=>{for(let ne of V)ne[0]===S&&T(ne[1])}));function T(C){if(a.emit(C),C.rpmCap!=null&&Number.isFinite(C.rpmCap)&&C.rpmCap>=0&&(s.emit(C.rpmCap),Number.isFinite(n)&&n>0&&y.start(n,()=>s.emit(Number.POSITIVE_INFINITY))),C.tpmCap!=null&&Number.isFinite(C.tpmCap)&&C.tpmCap>=0&&(i.emit(C.tpmCap),Number.isFinite(n)&&n>0&&b.start(n,()=>i.emit(Number.POSITIVE_INFINITY))),C.retryAfterMs!=null&&C.retryAfterMs>0){let V=$()+C.retryAfterMs*1e6;V>g&&(g=V)}}let w=N(0,{name:"adaptiveRateLimiter/pending"}),k=N(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),x=N(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),R=C=>{w.emit((w.cache??0)+C)},E=()=>{k.emit(d.available()),x.emit(l.available())};async function G(C={}){let V=C.requestCost??1,ne=C.tokenCost??0,F=C.signal;R(1);try{for(;;){if(F?.aborted)throw ya("AdaptiveRateLimiter.acquire aborted");let A=$();if(g>A){let ae=Math.ceil((g-A)/1e6);await fs(ae,F);continue}if(V>0&&f||ne>0&&p){await fs(250,F);continue}let D=d,I=l;if(!D.tryConsume(V)){await fs(Vl(D,V),F);continue}if(!(ne>0?I.tryConsume(ne):!0)){D.putBack(V),await fs(Vl(I,ne),F);continue}E();return}}finally{R(-1)}}function L(C){C>0?l.tryConsume(C):C<0&&l.putBack(-C),E()}function P(){m(),h(),v?.(),y.cancel(),b.cancel()}return{effectiveRpm:u,effectiveTpm:c,lastSignal:a,pending:w,rpmAvailable:k,tpmAvailable:x,acquire:G,recordUsage:L,recordSignal:T,dispose:P}}function Yn(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 Vl(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 fs(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(ya("AdaptiveRateLimiter.acquire aborted")):new Promise((n,r)=>{let o=new _e,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(ya("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",s,{once:!0}))})}Re();function ba(t,e={}){let n=e.limiter??Kl({name:e.name??"rateLimiter",rpm:e.rpm,tpm:e.tpm,adaptation:e.adaptation,burstMultiplier:e.burstMultiplier}),r=(i,a)=>e.costFn?e.costFn(i,a):0,o=i=>{let a=ga(i);a&&n.recordSignal(a)};return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(i,a){let u=r(i,a);await n.acquire({requestCost:1,tokenCost:u,signal:a?.signal});try{let c=t.invoke(i,a),d=await gh(c),l=d.usage??Gl(),p=Nt(l)+hn(l)-u;return p>0&&n.recordUsage(p),d}catch(c){throw o(c),c}},async*stream(i,a){let u=r(i,a);await n.acquire({requestCost:1,tokenCost:u,signal:a?.signal});try{let c=0;for await(let l of t.stream(i,a))l.type==="usage"&&(c=Nt(l.usage)+hn(l.usage)),yield l;let d=c-u;d>0&&n.recordUsage(d)}catch(c){throw o(c),c}}},limiter:n}}async function gh(t){return t!=null&&typeof t.then=="function"?await t:t&&typeof t=="object"&&"content"in t?t:await Kn(re(t))}Tt();var $r=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 va(t,e={}){if(t.length===0)throw new RangeError("cascadingLlmAdapter: tiers must be non-empty");let n=t.map(o=>({name:o.name,adapter:o.adapter,filter:o.filter,breaker:o.breaker?"canExecute"in o.breaker?o.breaker:ft(o.breaker):void 0})),r=e.streamRetryBeforeFirstChunk??!0;return{provider:"cascading",model:void 0,async invoke(o,s){let i=[],a=new Map;for(let c=0;c<n.length;c++){let d=n[c];if(d.filter&&!d.filter(o,s)){i.push({name:d.name,reason:"filter"});continue}if(d.breaker&&!d.breaker.canExecute()){i.push({name:d.name,reason:"breaker"});continue}try{let l=await Promise.resolve(d.adapter.invoke(o,s));return d.breaker?.recordSuccess(),{...l,metadata:{...l.metadata??{},tier:d.name}}}catch(l){a.set(d.name,l),d.breaker?.recordFailure(l);let f=n[c+1];f&&e.onFallback?.(d.name,f.name,l)}}let u={skipped:i,failed:a};throw e.onExhausted?.(u),new $r(u)},async*stream(o,s){let i=[],a=new Map;for(let c=0;c<n.length;c++){let d=n[c];if(d.filter&&!d.filter(o,s)){i.push({name:d.name,reason:"filter"});continue}if(d.breaker&&!d.breaker.canExecute()){i.push({name:d.name,reason:"breaker"});continue}let l=!1;try{for await(let f of d.adapter.stream(o,s))l=!0,yield f;d.breaker?.recordSuccess();return}catch(f){if(a.set(d.name,f),d.breaker?.recordFailure(f),l||!r)throw f;let p=n[c+1];p&&e.onFallback?.(d.name,p.name,f)}}let u={skipped:i,failed:a};throw e.onExhausted?.(u),new $r(u)}}}pt();function ms(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function Hl(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(ms()):new Promise((n,r)=>{let o=new _e,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(ms())},e.addEventListener("abort",s,{once:!0}))})}function Ta(t,e={}){let n=e.attempts??3,r=e.baseDelayMs??500,o=e.maxDelayMs??1e4,s=e.strategy??"decorrelated",i=e.jitter??!0,a=e.shouldRetry??yh,u=e.retryStreaming??!0,c=(d,l)=>{if(s==="decorrelated"){let h=Math.min(o,Math.max(r,l*3));return r+Math.random()*(h-r)}let f=s==="exp"?r*2**(d-1):r*d,p=Math.min(o,f);if(!i)return p;let m=p*(.5+Math.random());return Math.min(o,m)};return{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(d,l){if(l?.signal?.aborted)throw ms();let f,p=r;for(let m=1;m<=n;m++)try{return await Promise.resolve(t.invoke(d,l))}catch(h){if(f=h,m>=n||!a(h,m))throw h;let g=c(m,p);p=g,await Hl(g,l?.signal)}throw f},async*stream(d,l){if(l?.signal?.aborted)throw ms();if(!u){for await(let m of t.stream(d,l))yield m;return}let f,p=r;for(let m=1;m<=n;m++){let h=!1;try{for await(let g of t.stream(d,l))h=!0,yield g;return}catch(g){if(f=g,h||m>=n||!a(g,m))throw g;let y=c(m,p);p=y,await Hl(y,l?.signal)}}throw f}}}function yh(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}pt();var Qn=class extends Error{constructor(n){super(`LLM call timed out after ${n}ms`);this.ms=n}name="LLMTimeoutError"};function wa(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let n=o=>{let s=new AbortController,i=!1,a;o&&(o.aborted?s.abort(o.reason):(a=()=>s.abort(o.reason),o.addEventListener("abort",a,{once:!0})));let u=new _e;return u.start(e,()=>{i=!0,s.abort(new Qn(e))}),{signal:s.signal,cancel:()=>{u.cancel(),o&&a&&o.removeEventListener("abort",a)},timedOut:()=>i}},r=(o,s)=>{if(!s||o instanceof Qn)throw o;let i=o;if(i?.name==="AbortError"||i?.name==="DOMException"&&Number(i.code)===20||o?.message==="aborted"){let u=new Qn(e);throw u.cause=o,u}throw o};return{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(o,s){let{signal:i,cancel:a,timedOut:u}=n(s?.signal);try{return await Promise.resolve(t.invoke(o,{...s,signal:i}))}catch(c){return r(c,u())}finally{a()}},async*stream(o,s){let{signal:i,cancel:a,timedOut:u}=n(s?.signal);try{for await(let c of t.stream(o,{...s,signal:i}))yield c}catch(c){r(c,u())}finally{a()}}}}function bh(t,e={}){let n={adapter:t},r=t;if(e.rateLimit){let o=ba(r,e.rateLimit);r=o.adapter,n.rateLimiter=o.limiter}if(e.budget){let o=ha(r,e.budget);r=o.adapter,n.budget=o.budget}if(e.breaker){let o=fa(r,e.breaker);r=o.adapter,n.breaker=o.breaker}if(e.timeoutMs!=null&&(r=wa(r,e.timeoutMs)),e.retry&&(r=Ta(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=va([{name:e.name??"primary",adapter:r},{name:"fallback",adapter:e.fallback}],o)}return n.adapter=r,n}function vh(){return St()}oe();Re();function Th(t,e,n){let r=re(e);return be(r,s=>{if(!s||s.length===0)return N(null);let i=n?.tools;return t.invoke(s,{model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,tools:i,systemPrompt:n?.systemPrompt})})}xe();Re();ie();Re();pt();function ge(t,e){return Ke("ai",t,e)}function wh(t){return t!=null&&typeof t.then=="function"}function kh(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function xh(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var Rh=3e4;function Wl(t,e){if(t.status==="settled"){let r=t.cache;if(r!==void 0)return Promise.resolve(r)}let n=e?.timeoutMs??Rh;return new Promise((r,o)=>{let s=new _e,i=t.subscribe(a=>{for(let u of a){if(u[0]===S){s.cancel(),i(),r(u[1]);return}if(u[0]===M){s.cancel(),i(),o(u[1]);return}if(u[0]===_){s.cancel(),i(),o(new Error("firstDataFromNode: completed without producing a value"));return}}});s.start(n,()=>{i(),o(new Error(`firstDataFromNode: timed out after ${n}ms`))})})}async function gn(t){return wh(t)?gn(await t):kh(t)?Wl(t):xh(t)?Wl(re(t)):t}function yn(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function Sh(t,e){let n=re(t),r=e?.refreshTrigger!=null?re(e.refreshTrigger):null;return r==null?K([n],(o,s,i)=>{if(i.store.emitted===!0)return;let u=o[0],c=u!=null&&u.length>0?u.at(-1):i.prevData[0];if(c!==void 0)return i.store.emitted=!0,s.emit(c),{invalidate:()=>{i.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:ge("frozen_context")}):K([n,r],(o,s,i)=>{let a=o[1];if(!(a!=null&&a.length>0))return;let c=o[0],d=c!=null&&c.length>0?c.at(-1):i.prevData[0];s.emit(d)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:ge("frozen_context")})}oe();function Nh(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function Br(t,e,n,r){let o=r?.format??"text",s=r?.retries??0,i=r?.cache??!1,a=i?new Map:null,u=O(e,d=>{if(d.some(p=>p==null))return[];let l=typeof n=="string"?n:n(...d);if(!l)return[];let f=[];return r?.systemPrompt&&f.push({role:"system",content:r.systemPrompt}),f.push({role:"user",content:l}),f},{name:r?.name?`${r.name}::messages`:"prompt_node::messages",meta:ge("prompt_node"),initial:[]});return be(u,d=>{if(!d||d.length===0)return N(null);let l=i?JSON.stringify(d.map(p=>[p.role,p.content])):"";if(a?.has(l))return N(a.get(l));async function f(p){try{let m=await new Promise((y,b)=>{let v=t.invoke(d,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt});v&&typeof v.then=="function"?v.then(y,b):v&&typeof v.subscribe=="function"?y(v.cache):y(v)}),h=Nh(m),g;return o==="json"?g=JSON.parse(yn(h)):g=h,a?.set(l,g),g}catch(m){if(p>0)return f(p-1);throw m}}return f(s)})}oe();Re();var bs={};he(bs,{MessagingHubGraph:()=>ys,SubscriptionGraph:()=>jr,TopicBridgeGraph:()=>gs,TopicGraph:()=>nt,messagingHub:()=>_h,subscription:()=>ql,topic:()=>Et,topicBridge:()=>Mh});xe();var Eh=2147483647;function hs(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function bn(t,e){return Ke("messaging",t,e)}var nt=class extends q{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=Ve([],{name:"events",maxSize:n.retainedLimit}),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=O([this.events],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:bn("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(se(this.latest)),this.hasLatest=O([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:bn("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(se(this.hasLatest)),this.addDisposer(()=>{this.events.down([[_]])}),this.addDisposer(()=>this._log.disposeAllViews())}publish(e){this._log.append(e)}retained(){return this.events.cache}},jr=class extends q{source;cursor;available;topic;constructor(e,n,r={}){super(e,r.graph);let o=hs(r.cursor??0,"subscription cursor");this.topic=n;let s=n.events;this.source=O([s],([i])=>i,{name:"source",describeKind:"derived",meta:bn("subscription_source"),initial:s.cache}),this.add(this.source,{name:"source"}),this.cursor=N(o,{name:"cursor",describeKind:"state",meta:bn("subscription_cursor")}),this.add(this.cursor,{name:"cursor"}),this.available=O([this.source,this.cursor],([i,a])=>{let u=i,c=Math.max(0,Math.trunc(a??0));return u.slice(c)},{name:"available",describeKind:"derived",meta:bn("subscription_available"),initial:[]}),this.add(this.available,{name:"available"}),this.addDisposer(se(this.source)),this.addDisposer(se(this.available))}ack(e){let n=this.available.cache,r=e===void 0?n.length:hs(e,"subscription ack count"),o=Math.min(r,n.length);if(o<=0)return this.cursor.cache;let s=this.cursor.cache+o;return this.cursor.emit(s),s}pull(e,n={}){let r=this.available.cache,o=e===void 0?r.length:hs(e,"subscription pull limit"),s=r.slice(0,o);return n.ack&&s.length>0&&this.ack(s.length),s}},gs=class extends q{_sourceSub;_target;bridgedCount;constructor(e,n,r,o={}){super(e,o.graph),this._sourceSub=ql(`${e}-subscription`,n,{cursor:o.cursor}),this._target=r,this.mount("subscription",this._sourceSub),this.bridgedCount=N(0,{name:"bridgedCount",describeKind:"state",meta:bn("topic_bridge_count")}),this.add(this.bridgedCount,{name:"bridgedCount"});let s=Math.max(1,hs(o.maxPerPump??Eh,"topic bridge maxPerPump")),i=o.map??(u=>u),a=K([this._sourceSub.available],()=>{let u=this._sourceSub.pull(s,{ack:!0});if(u.length===0)return;let c=0;for(let d of u){let l=i(d);l!==void 0&&(this._target.publish(l),c+=1)}if(c>0){let d=this.bridgedCount.cache;this.bridgedCount.emit(d+c)}},{name:"pump",describeKind:"effect",meta:bn("topic_bridge_pump")});this.add(a,{name:"pump"}),this.addDisposer(se(a))}},ys=class extends q{_topics=new Map;_version=0;_defaultTopicOptions;constructor(e,n={}){super(e,n.graph),this._defaultTopicOptions={...n.defaultTopicOptions??{}}}get version(){return this._version}get size(){return this._topics.size}has(e){return this._topics.has(e)}topicNames(){return this._topics.keys()}topic(e,n){let r=this._topics.get(e);if(r===void 0){let o={...this._defaultTopicOptions,...n??{}};r=new nt(e,o),this._topics.set(e,r),this.mount(e,r),this._version+=1}return r}publish(e,n){this.topic(e).publish(n)}publishMany(e){te(()=>{for(let[n,r]of e)this.topic(n).publish(r)})}subscribe(e,n,r){let o=this.topic(n);return new jr(e,o,r)}removeTopic(e){if(!this._topics.has(e))return!1;try{this.remove(e)}finally{this._topics.delete(e),this._version+=1}return!0}};function Et(t,e){return new nt(t,e)}function _h(t,e){return new ys(t,e)}function ql(t,e,n){return new jr(t,e,n)}function Mh(t,e,n,r){return new gs(t,e,n,r)}var vs={};he(vs,{approval:()=>Ih,branch:()=>Lh,gate:()=>Vr,join:()=>Ph,loop:()=>Dh,onFailure:()=>$h,pipeline:()=>Ul,sensor:()=>Fh,subPipeline:()=>Gh,task:()=>Ah});Ne();ie();xe();oe();function _t(t,e){if(typeof e=="string")return{node:t.resolve(e),path:e};let n=Oh(t,e);if(!n)throw new Error("orchestration dep node must already be registered in the graph so explicit edges can be recorded; pass a string path or register the node first");return{node:e,path:n}}function Oh(t,e){let n=t.describe(),r=`::${je}::`;for(let o of Object.keys(n.nodes).sort())if(!o.includes(r))try{if(t.resolve(o)===e)return o}catch{}}function Bt(t,e,n,r){t.add(n,{name:e})}function jt(t,e){return Ke("orchestration",t,e)}function Ch(t){let e=r=>{let o=r.trim();return o.length===0?0:Number(o)},n;return typeof t=="string"?n=e(t):t===null?n=0:n=Number(t),Number.isFinite(n)?Math.max(0,Math.trunc(n)):1}function Ul(t,e){return new q(t,e)}function Ah(t,e,n,r){let s=(r?.deps??[]).map(d=>_t(t,d)),{deps:i,...a}=r??{},u=(d,l,f)=>{let p=d.map((m,h)=>m!=null&&m.length>0?m.at(-1):f.prevData[h]);l.emit(n(p,f))},c=K(s.map(d=>d.node),u,{...a,name:e,describeKind:"derived",meta:jt("task",r?.meta)});return Bt(t,e,c,s.flatMap(d=>d.path?[d.path]:[])),c}function Lh(t,e,n,r,o){let s=_t(t,n),i=O([s.node],([a])=>({branch:r(a)?"then":"else",value:a}),{...o,name:e,meta:jt("branch",o?.meta)});return Bt(t,e,i,s.path?[s.path]:[]),i}function Ih(t,e,n,r,o){let s=_t(t,n),i=_t(t,r),a=o?.isApproved??(c=>!!c),u=K([s.node,i.node],(c,d,l)=>{let f=c[0],p=c[1],m=p!=null&&p.length>0?p.at(-1):l.prevData[1];if(m===void 0||!a(m)){d.down([[B]]);return}if(f==null||f.length===0){p!=null&&p.length>0&&l.prevData[0]!==void 0?d.emit(l.prevData[0]):d.down([[B]]);return}for(let h of f)d.emit(h)},{...o,name:e,describeKind:"derived",meta:jt("approval",o?.meta)});return Bt(t,e,u,[s.path,i.path].filter(c=>typeof c=="string")),u}function Vr(t,e,n,r){let o=r?.maxPending??1/0;if(o<1&&o!==1/0)throw new RangeError("gate: maxPending must be >= 1");let s=r?.startOpen??!1,i=_t(t,n),a=N([],{name:"pending",equals:()=>!1}),u=N(s,{name:"isOpen"}),c=O([a],([w])=>w.length,{name:"count"}),d=[],l=!1,f=s,p=u.subscribe(w=>{for(let k of w)k[0]===S&&(f=k[1])});function m(){a.emit([...d])}function h(w){d.push(w),d.length>o&&d.shift(),m()}function g(w){let k=d.splice(0,w);return m(),k}function y(w){if(l)throw new Error(`gate: ${w}() called after gate was torn down`)}let b=K([i.node],(w,k,x)=>{let R=x.terminalDeps[0];if(R!==void 0){l=!0,d=[],m(),k.down(R===!0?[[_]]:[[M,R]]);return}let E=w[0];if(E==null||E.length===0){k.down([[B]]);return}for(let G of E)f?k.emit(G):(h(G),k.down([[B]]))},{name:e,describeKind:"derived",meta:jt("gate",r?.meta)}),v={node:b,pending:a,count:c,isOpen:u,approve(w=1){y("approve");let k=g(w);for(let x of k){if(l)break;b.emit(x)}},reject(w=1){y("reject"),g(w)},modify(w,k=1){y("modify");let x=[...d],R=g(k);for(let E=0;E<R.length&&!l;E++)b.emit(w(R[E],E,x))},open(){y("open"),te(()=>{u.emit(!0);let w=g(d.length);for(let k of w){if(l)break;b.emit(k)}})},close(){y("close"),u.emit(!1)}};t.addDisposer(c.subscribe(()=>{})),t.addDisposer(p),Bt(t,e,b,i.path?[i.path]:[]);let T=new q(`${e}_state`);return T.add(a,{name:"pending"}),T.add(u,{name:"isOpen"}),T.add(c,{name:"count"}),t.mount(`${e}_state`,T),v}function Ph(t,e,n,r){let o=n.map(i=>_t(t,i)),s=O(o.map(i=>i.node),i=>i,{...r,name:e,meta:jt("join",r?.meta)});return Bt(t,e,s,o.flatMap(i=>i.path?[i.path]:[])),s}function Dh(t,e,n,r,o){let s=_t(t,n),i=o?.iterations,a=typeof i=="number"||i===void 0?void 0:_t(t,i),u=typeof i=="number"?i:void 0,c=K(a?[s.node,a.node]:[s.node],(d,l,f)=>{let p=d[0],m=p!=null&&p.length>0?p.at(-1):f.prevData[0],h=a?d[1]:void 0,g=u??(a?h!=null&&h.length>0?h.at(-1):f.prevData[1]:1),y=Ch(g);for(let b=0;b<y;b+=1)m=r(m,b,l);l.emit(m)},{...o,name:e,describeKind:"derived",meta:jt("loop",o?.meta)});return Bt(t,e,c,[s.path,a?.path].filter(d=>typeof d=="string")),c}function Gh(t,e,n,r){let o=n instanceof q?n:Ul(e,r);return typeof n=="function"&&n(o),t.mount(e,o),o}function Fh(t,e,n,r){let o=K([],()=>{},{...r,name:e,initial:n,describeKind:"producer",meta:jt("sensor",r?.meta)});return Bt(t,e,o,[]),{node:o,push(s){o.emit(s)},error(s){o.down([[M,s]])},complete(){o.down([[_]])}}}function $h(t,e,n,r,o){let s=_t(t,n),i=!1,a=K([],(u,c)=>{let d=s.node.subscribe(l=>{for(let f of l){if(i)return;if(f[0]===M)try{c.emit(r(f[1],c))}catch(p){i=!0,c.down([[M,p]])}else c.down([f]),f[0]===_&&(i=!0)}});return()=>d()},{...o,name:e,describeKind:"derived",completeWhenDepsComplete:!1,errorWhenDepsError:!1,meta:jt("onFailure",o?.meta)});return Bt(t,e,a,s.path?[s.path]:[]),a}function Bh(t,e,n,r){let o=r?.name??"llm",s=r?.format??"text",i=Et(`${o}/stream`),a=O(e,d=>{if(d.some(p=>p==null))return[];let l=typeof n=="string"?n:n(...d);if(!l)return[];let f=[];return r?.systemPrompt&&f.push({role:"system",content:r.systemPrompt}),f.push({role:"user",content:l}),f}),u=be(a,d=>{let l=d;if(!l||l.length===0)return N(null);let f=new AbortController;async function*p(){let m="",h=0;try{for await(let y of t.stream(l,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,signal:f.signal})){if(y.type!=="token")continue;let b=y.delta;m+=b,i.publish({source:o,token:b,accumulated:m,index:h++})}let g;if(s==="json")try{g=JSON.parse(yn(m))}catch{g=null}else g=m;yield g}finally{f.abort()}}return re(p())}),c=se(u);return{output:u,stream:i,dispose:()=>{c(),i.destroy()}}}function jh(t,e,n,r,o,s){let i=N(0,{name:`${e}/cancel`}),a=0,u=[...r,i],c=s?.name??e,d=s?.format??"text",l=Et(`${c}/stream`),f=O(u,v=>{let T=v.slice(0,-1);if(T.some(x=>x==null))return[];let w=typeof o=="string"?o:o(...T);if(!w)return[];let k=[];return s?.systemPrompt&&k.push({role:"system",content:s.systemPrompt}),k.push({role:"user",content:w}),k}),p=be(f,v=>{let T=v;if(!T||T.length===0)return N(null);let w=new AbortController;async function*k(){let x="",R=0;try{for await(let G of n.stream(T,{model:s?.model,temperature:s?.temperature,maxTokens:s?.maxTokens,systemPrompt:s?.systemPrompt,signal:w.signal})){if(G.type!=="token")continue;let L=G.delta;x+=L,l.publish({source:c,token:L,accumulated:x,index:R++})}let E;if(d==="json")try{E=JSON.parse(yn(x))}catch{E=null}else E=x;yield E}finally{w.abort()}}return re(k())}),m=se(p),h=O([p],([v])=>{if(v!=null)return v},{name:`${e}/filter`});t.add(h,{name:`${e}/raw`});let g=Vr(t,`${e}/gate`,`${e}/raw`,s?.gate),y=g.reject.bind(g),b={...g,reject(v=1){y(v),i.emit(++a)}};return{output:g.node,stream:l,gate:b,dispose:()=>{m(),l.destroy()}}}oe();Re();function Vh(t,e){let n=e?.separator??`
54
55
 
55
- `,r=t.map(i=>typeof i=="string"?N(i):re(i)),o=A(r,i=>i.filter(a=>a!=null&&a!=="").join(n),{name:e?.name??"systemPrompt",describeKind:"derived",meta:Ce("system_prompt"),initial:""}),s=oe(o);return Object.assign(o,{dispose:s})}function Ol(t,e){return(n,r)=>{let o=[...r.keys()].slice(0,100),s=[{role:"system",content:t},{role:"user",content:JSON.stringify({input:n,existingKeys:o})}];return H(i=>{let a=!0,u=e.adapter.invoke(s,{model:e.model,temperature:e.temperature??0,maxTokens:e.maxTokens}),d=re(u).subscribe(l=>{if(!a)return;let f=!1;for(let p of l){if(f)break;if(p[0]===R){let m=p[1];try{let h=JSON.parse(m.content);i.emit(h),i.down([[M]])}catch{i.down([[O,new Error("llmExtractor: failed to parse LLM response as JSON")]])}f=!0}else p[0]===O?(i.down([[O,p[1]]]),f=!0):p[0]===M?(i.down([[M]]),f=!0):i.down([[p[0],p[1]]])}});return()=>{d(),a=!1}})}}function Cl(t,e){return n=>{let r=[...n.entries()].map(([s,i])=>({key:s,value:i})),o=[{role:"system",content:t},{role:"user",content:JSON.stringify({memories:r})}];return H(s=>{let i=!0,a=e.adapter.invoke(o,{model:e.model,temperature:e.temperature??0,maxTokens:e.maxTokens}),c=re(a).subscribe(d=>{if(!i)return;let l=!1;for(let f of d){if(l)break;if(f[0]===R){let p=f[1];try{let m=JSON.parse(p.content);s.emit(m),s.down([[M]])}catch{s.down([[O,new Error("llmConsolidator: failed to parse LLM response as JSON")]])}l=!0}else f[0]===O?(s.down([[O,f[1]]]),l=!0):f[0]===M?(s.down([[M]]),l=!0):s.down([[f[0],f[1]]])}});return()=>{c(),i=!1}})}}function fh(t){return{persistence:.5,structure:.5,personalValue:.5}}function mh(t={}){let e=t.scoreFn??fh,n=t.persistenceThreshold??.3,r=t.personalValueThreshold??.3,o=t.requireStructured??!1;return s=>{let i=e(s);return!(i.persistence<n||i.personalValue<r||o&&i.structure<=0)}}var hh=Math.LN2/(7*86400);function Fr(t){return t instanceof Map?t:new Map}function gh(t,e,n){let r=new z(t,n.graph),o=[],s;if(n.extractFn)s=n.extractFn;else if(n.adapter&&n.extractPrompt)s=Ol(n.extractPrompt,{adapter:n.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let i=(v,T)=>v==null?{upsert:[]}:s(v,T),a=e;if(n.admissionFilter){let v=re(e),T=n.admissionFilter;a=A([v],([w])=>{if(T(w))return w},{name:"admissionFilter",describeKind:"derived"})}let u;n.consolidateFn?u=n.consolidateFn:n.adapter&&n.consolidatePrompt&&(u=Cl(n.consolidatePrompt,{adapter:n.adapter}));let c=n.consolidateTrigger;if(!c&&u&&n.reflection?.enabled!==!1){let v=n.reflection?.interval??3e5;c=et(v,{period:v})}let d={score:n.score,cost:n.cost,budget:n.budget??2e3,context:n.context,consolidate:u,consolidateTrigger:c},l=Uo(a,i,d);r.add(l.store.entries,{name:"store"}),r.add(l.compact,{name:"compact"}),r.add(l.size,{name:"size"});let f=null;n.vectorDimensions&&n.vectorDimensions>0&&n.embedFn&&(f=Zi({dimension:n.vectorDimensions}),r.add(f.entries,{name:"vectorIndex"}));let p=null;n.enableKnowledgeGraph&&(p=ea(`${t}-kg`),r.mount("kg",p));let m=null;if(n.tiers){let v=n.tiers,T=v.decayRate??hh,w=v.maxActive??1e3,k=v.archiveThreshold??.1,x=v.permanentFilter??(()=>!1),S=Xi({name:"permanent"});r.add(S.entries,{name:"permanent"});let _=new Set,F=E=>_.has(E)?"permanent":Fr(l.store.entries.cache).has(E)?"active":"archived",L=(E,I)=>{_.add(E),S.upsert(E,I)},D=new Map,C=l.store.entries,K=n.context?re(n.context):N(null),ne=fe([C,K],([E,I])=>{let G=Fr(E),te=B(),U=[],ce=[];for(let[V,J]of G){if(D.has(V)||D.set(V,te),x(V,J)){ce.push({key:V,value:J});continue}let Y=n.score(J,I),Q=D.get(V)??te,W=Number(te-Q)/1e9;pn(Y,W,T)<k&&U.push(V)}for(let V of D.keys())G.has(V)||D.delete(V);for(let{key:V,value:J}of ce)_.has(V)||L(V,J);let j=G.size-_.size;if(j>w){let V=[...G.entries()].filter(([Y])=>!_.has(Y)).map(([Y,Q])=>({key:Y,score:n.score(Q,I)})).sort((Y,Q)=>Y.score-Q.score),J=j-w;for(let Y=0;Y<J&&Y<V.length;Y++){let Q=V[Y].key;U.includes(Q)||U.push(Q)}}U.length>0&&ee(()=>{for(let V of U)l.store.delete(V)})});o.push(ne.subscribe(()=>{}));let P=null;v.archiveTier&&(P=r.attachStorage([v.archiveTier],v.archiveStorageOptions??{})),m={permanent:S,activeEntries:C,archiveHandle:P,tierOf:F,markPermanent:L}}if(f||p){let v=n.embedFn,T=n.entityFn,w=l.store.entries,k=fe([w],([x])=>{let S=Fr(x);for(let[_,F]of S){if(f&&v){let L=v(F);L&&f.upsert(_,L,F)}if(p&&T){let L=T(_,F);if(L){for(let D of L.entities??[])p.upsertEntity(D.id,D.value);for(let D of L.relations??[])p.link(D.from,D.to,D.relation,D.weight)}}}});o.push(k.subscribe(()=>{}))}let h=null,g=null,y=null,b=null;if(f||p){let v=n.retrieval?.topK??20,T=n.retrieval?.graphDepth??1,w=n.budget??2e3,k=n.cost,x=n.score,S=n.contextOf,_=n.contextWeight??0,F=n.context?re(n.context):N(null),L=(P,E)=>{if(!P||!E)return 0;let I=Math.min(P.length,E.length),G=0;for(;G<I&&P[G]===E[G];)G++;return G},D=(P,E,I)=>{let G=new Map,te=[];if(f&&I.vector){te=f.search(I.vector,v);for(let Q of te){let W=P.get(Q.id);W&&G.set(Q.id,{value:W,sources:new Set(["vector"])})}}let U=[];if(p){let Q=[...I.entityIds??[],...G.keys()],W=new Set,ae=Q;for(let ye=0;ye<T;ye++){let Fe=[];for(let ze of ae){if(W.has(ze))continue;W.add(ze);let ht=p.related(ze);for(let Vt of ht){let rt=Vt.to;if(!W.has(rt)){Fe.push(rt);let qe=P.get(rt);if(qe){let X=G.get(rt);X?X.sources.add("graph"):G.set(rt,{value:qe,sources:new Set(["graph"])}),U.push(rt)}}}}ae=Fe}}for(let[Q,W]of P)G.has(Q)||G.set(Q,{value:W,sources:new Set(["store"])});let ce=I.context?.length??0,j=[];for(let[Q,{value:W,sources:ae}]of G){let ye=S?S(W):void 0,Fe=x(W,E);if(_>0&&ce>0){let ht=L(I.context,ye);ht>0&&(Fe=Fe*(1+_*ht/ce))}let ze=ye?{key:Q,value:W,score:Fe,sources:[...ae],context:ye}:{key:Q,value:W,score:Fe,sources:[...ae]};j.push(ze)}j.sort((Q,W)=>W.score-Q.score);let V=[],J=0;for(let Q of j){let W=k(Q.value);if(J+W>w&&V.length>0)break;V.push(Q),J+=W}return{packed:V,trace:{vectorCandidates:te,graphExpanded:U,ranked:j,packed:V}}},C=N([],{name:"retrieval",describeKind:"state",meta:Ce("retrieval_pipeline")});r.add(C,{name:"retrieval"}),h=C;let K=N(null,{name:"retrievalTrace",describeKind:"state",meta:Ce("retrieval_trace")});r.add(K,{name:"retrievalTrace"}),g=K,y=P=>{let E=Fr(l.store.entries.cache),{packed:I,trace:G}=D(E,F.cache,P);return ee(()=>{C.emit(I),K.emit(G)}),I},b=P=>{let E=re(P);return A([l.store.entries,F,E],([I,G,te])=>{if(te==null)return[];let U=Fr(I);return D(U,G,te).packed},{name:"retrievalReactive",describeKind:"derived",meta:Ce("retrieval_reactive"),initial:[]})}}return r.addDisposer(()=>{for(let v of o)v();o.length=0}),Object.assign(r,{distillBundle:l,compact:l.compact,size:l.size,vectors:f,kg:p,memoryTiers:m,retrieval:h,retrievalTrace:g,retrieve:y,retrieveReactive:b})}var bs=class extends z{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;turnCount;_terminalResult;_disposeRunWiring;_runVersion=0;_running=!1;_currentAbortController=null;constructor(e,n){if(super(e,n.graph),this.chat=_l(`${e}-chat`,{maxMessages:n.maxMessages}),this.mount("chat",this.chat),this.tools=Ml(`${e}-tools`),this.mount("tools",this.tools),n.tools)for(let P of n.tools)this.tools.register(P);this.status=N("idle",{name:"status",describeKind:"state",meta:Ce("agent_status")}),this.add(this.status,{name:"status"}),this.turn=N(0,{name:"turn",describeKind:"state",meta:Ce("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.turnCount=this.turn,this.aborted=N(!1,{name:"aborted",describeKind:"state",meta:Ce("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let r=0,o=this.turn.subscribe(P=>{for(let E of P)E[0]===R&&(r=E[1])}),s=!1,i=this.aborted.subscribe(P=>{for(let E of P)E[0]===R&&(s=E[1])}),a=n.adapter,u=n.systemPrompt,c=n.model,d=n.temperature,l=n.maxTokens,f=n.maxTurns??10,p=n.stopWhen,m=this.chat,h=this.tools,g=this.status,y=this.turn,b=this.aborted,v=q([g],(P,E,I)=>{if($r(P,I.prevData,0,"idle")!=="thinking"||s||r>=f){E.down([[$]]);return}let te=m.allMessages();if(te.length===0){E.down([[$]]);return}let U=h.schemas.cache??[];E.emit({messages:te,tools:U})},{name:"promptInput",describeKind:"derived",meta:Ce("agent_prompt_input")}),T=_e(v,P=>{let E=new AbortController;return this._currentAbortController=E,s&&E.abort(new Error("agentLoop: aborted")),re(Promise.resolve(a.invoke(P.messages,{tools:P.tools.length>0?P.tools:void 0,systemPrompt:u,model:c,temperature:d,maxTokens:l,signal:E.signal})),{signal:E.signal})},{equals:()=>!1}),w=N(null,{name:"lastResponse",describeKind:"state",meta:Ce("agent_last_response")});this.lastResponse=w;let k=q([w,g],(P,E,I)=>{let G=$r(P,I.prevData,0,null);if($r(P,I.prevData,1,"idle")!=="acting"){E.down([[$]]);return}let U=G?.toolCalls;if(U==null||U.length===0){E.down([[$]]);return}E.emit(U)},{name:"toolCalls",describeKind:"derived",meta:Ce("agent_tool_calls")}),x=n.interceptToolCalls?n.interceptToolCalls(k):k;this.toolCalls=x;let S=(P,E)=>{if(P===E)return!0;if(P.length!==E.length)return!1;for(let I=0;I<P.length;I++){let G=P[I],te=E[I];if(G?.id!==te?.id||G?.content!==te?.content)return!1}return!0},_=_e(x,P=>{if(P==null||P.length===0)throw new Error("agentLoop: toolResultsNode received an empty tool-call batch as DATA \u2014 toolCallsNode gating invariant broken (should emit RESOLVED for empty). Audit toolCallsNode.");let E=P.map(I=>yh(I,h));return A(E,I=>I.map((G,te)=>{let U=G;return U!=null&&typeof U=="object"&&"id"in U&&"content"in U?U:{id:P[te].id,content:JSON.stringify(G??null)}}),{name:"toolResults_batch",equals:S})});this.toolResults=_;let F=fe([T],([P])=>{if(s)return;let E=P,I=r+1,G=E.toolCalls!=null&&E.toolCalls.length>0,te=E.finishReason==="end_turn"&&(!E.toolCalls||E.toolCalls.length===0),U=p?.(E)===!0,ce=I>=f,j=U||te||!G||ce?"done":"acting";ee(()=>{w.emit(E),g.emit(j),y.emit(I),m.append("assistant",E.content,{toolCalls:E.toolCalls})})}),L=fe([_],([P])=>{if(s)return;let E=P;if(E.length===0)return;let I=r>=f?"done":"thinking";ee(()=>{g.emit(I);for(let G of E)m.appendToolResult(G.id,G.content)})}),D=fe([b],([P])=>{P===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),g.emit("done"))}),C=oe(F),K=oe(L),ne=oe(D);this._terminalResult=q([g,w],(P,E,I)=>{let G=$r(P,I.prevData,0,"idle"),te=$r(P,I.prevData,1,null);if(G==="done"){if(te!=null){E.emit({response:te,runVersion:this._runVersion});return}let U=new Error("agentLoop: aborted");U.name="AbortError",E.down([[O,U]]);return}if(G==="error"){E.down([[O,new Error("agentLoop: errored")]]);return}E.down([[$]])},{name:"terminalResult",describeKind:"derived",meta:Ce("agent_terminal_result")}),this.addDisposer(o),this.addDisposer(i),this.addDisposer(C),this.addDisposer(K),this.addDisposer(ne),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=++this._runVersion;ee(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle")}),e!=null&&this.chat.append("user",e),this.status.emit("thinking");let o;if(n!=null)if(n.aborted)this.aborted.emit(!0);else{let s=()=>this.aborted.emit(!0);n.addEventListener("abort",s,{once:!0}),o=()=>n.removeEventListener("abort",s)}try{return(await wo(this._terminalResult,{predicate:i=>i!=null&&typeof i=="object"&&i.runVersion===r})).response}finally{o?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function yh(t,e){let n=Ct(()=>re(Promise.resolve().then(()=>e.execute(t.name,t.arguments))),{count:1}),r=A([n],([o])=>({id:t.id,content:typeof o=="string"?o:JSON.stringify(o)}));return Sr(r,o=>({id:t.id,content:JSON.stringify({error:String(o)})}))}function $r(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 bh(t,e){return new bs(t,e)}function vh(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 Th(t,e){let n=t.describe({actor:e,detail:"full"}),r=[],o=[],s=[];for(let[i,a]of Object.entries(n.nodes)){if(a.type!=="state"||i.includes("::__meta__::")||a.status==="completed"||a.status==="errored")continue;let u=a.meta??{},c=u.access;if(c==="human"||c==="system")continue;let d=u.description??`Set the value of ${i}`,l=vh(u),f={type:"object",required:["value"],properties:{value:l},additionalProperties:!1},p=i.replace(/::/g,"__");r.push({type:"function",function:{name:p,description:d,parameters:f}}),o.push({name:i,description:d,inputSchema:f});let m=t,h=e,g=a.v;s.push({name:i,description:d,parameters:f,handler(y){return m.set(i,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}}function wh(t,e,n){let r=t.describe({actor:e,detail:"full"}),o=n?.groupByTags??!0,s=n?.separator??`
56
- `,i=[],a=n?.sinceVersion;for(let[u,c]of Object.entries(r.nodes)){let d=c.meta??{},l=d.description,f=d.format;if(!l&&!f)continue;if(a!=null&&c.v!=null){let y=a.get(u);if(y!=null&&y.id===c.v.id&&c.v.version<=y.version)continue}let p=l??u,m=c.value,h=d.unit,g;f==="currency"&&typeof m=="number"?g=`$${m.toFixed(2)}`:f==="percentage"&&typeof m=="number"?g=`${(m*100).toFixed(1)}%`:m==null?g="(no value)":g=String(m),h&&f!=="currency"&&f!=="percentage"&&(g=`${g} ${h}`),i.push({path:u,description:p,formatted:g})}if(i.length===0)return"";if(o){let u=new Map,c=[];for(let l of i){let p=r.nodes[l.path].meta?.tags;if(p&&p.length>0){let m=p[0],h=u.get(m);h||(h=[],u.set(m,h)),h.push(l)}else c.push(l)}if(u.size===0)return i.map(l=>`- ${l.description}: ${l.formatted}`).join(s);let d=[];for(let[l,f]of[...u.entries()].sort((p,m)=>p[0].localeCompare(m[0])))d.push(`[${l}]${s}${f.map(p=>`- ${p.description}: ${p.formatted}`).join(s)}`);return c.length>0&&d.push(c.map(l=>`- ${l.description}: ${l.formatted}`).join(s)),d.join(s+s)}return i.map(u=>`- ${u.description}: ${u.formatted}`).join(s)}var Nl=new Set(["state","derived","producer","operator","effect"]);function Al(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 i=s;if((typeof i.type!="string"||!Nl.has(i.type))&&e.push(`Node "${o}": invalid type "${String(i.type)}" (expected: ${[...Nl].join(", ")})`),Array.isArray(i.deps))for(let a of i.deps)typeof a=="string"&&!r.has(a)&&e.push(`Node "${o}": dep "${a}" 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 i=n.edges[s];if(i==null||typeof i!="object"){e.push(`Edge [${s}]: must be an object`);continue}let a=i;(typeof a.from!="string"||!r.has(a.from))&&e.push(`Edge [${s}]: 'from' "${String(a.from)}" does not reference an existing node`),(typeof a.to!="string"||!r.has(a.to))&&e.push(`Edge [${s}]: 'to' "${String(a.to)}" does not reference an existing node`);let u=`${a.from}->${a.to}`;o.has(u)&&e.push(`Edge [${s}]: duplicate edge ${u}`),o.add(u)}}return{valid:e.length===0,errors:e}}function Ts(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}var El=`You are a graph architect for GraphReFly, a reactive graph protocol.
56
+ `,r=t.map(i=>typeof i=="string"?N(i):re(i)),o=O(r,i=>i.filter(a=>a!=null&&a!=="").join(n),{name:e?.name??"systemPrompt",describeKind:"derived",meta:ge("system_prompt"),initial:""}),s=se(o);return Object.assign(o,{dispose:s})}oe();var Kh=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens;function Hh(t,e){let n=e?.charsPerToken??4;return O([t.latest],([r])=>{if(r==null)return{chunkCount:0,charCount:0,estimatedTokens:0};let o=r,s=o.accumulated.length;return{chunkCount:o.index+1,charCount:s,estimatedTokens:Math.ceil(s/n)}},{name:e?.name??"cost-meter",describeKind:"derived",initial:{chunkCount:0,charCount:0,estimatedTokens:0},meta:ge("cost_meter_extractor"),equals:Kh})}oe();var Wh=(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 qh(t,e){let n=e.maxPatternLength??128;return O([t.latest],([r],o)=>{if(r==null)return[];let s=r.accumulated;"flags"in o.store||(o.store.flags=[],o.store.scannedTo=0);let i=o.store.flags,a=o.store.scannedTo,u=Math.max(0,a-n),c=s.slice(u),d=!1;for(let{pattern:l,label:f}of e.patterns){let p=new RegExp(l.source,`${l.flags.replace("g","")}g`);for(let m of c.matchAll(p)){let h=u+m.index;h+m[0].length<=a||(i.push({label:f,pattern:l,match:m[0],position:h}),d=!0)}}return o.store.scannedTo=s.length,d?[...i]:i.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:ge("keyword_flag_extractor"),equals:Wh})}oe();function Uh(t,e,n){return O([t.latest],([r])=>r==null?null:e(r.accumulated),{name:n?.name??"extractor",describeKind:"derived",initial:null,meta:ge("stream_extractor"),...n?.equals?{equals:n.equals}:{}})}oe();var zh=(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 Jh(t,e){return O([t.latest],([n],r)=>{if(n==null)return[];let o=n.accumulated;"calls"in r.store||(r.store.calls=[],r.store.scanFrom=0);let s=r.store.calls,i=r.store.scanFrom,a=!1;for(;i<o.length;){let u=o.indexOf("{",i);if(u===-1){r.store.scanFrom=o.length;break}let c=0,d=-1,l=!1;for(let p=u;p<o.length;p++){let m=o[p];if(l)m==="\\"&&p+1<o.length?p++:m==='"'&&(l=!1);else if(m==='"')l=!0;else if(m==="{")c++;else if(m==="}"&&(c--,c===0)){d=p;break}}if(d===-1){r.store.scanFrom=u;break}let f=o.slice(u,d+1);try{let p=JSON.parse(f);typeof p.name=="string"&&p.arguments!=null&&typeof p.arguments=="object"&&(s.push({name:p.name,arguments:p.arguments,raw:f,startIndex:u}),a=!0)}catch{}i=d+1,r.store.scanFrom=i}return a?[...s]:s.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:ge("tool_call_extractor"),equals:zh})}oe();function Yh(t,e,n,r){let o=n*(r?.hardMultiplier??1.5),s=typeof e!="function",i=[t.latest];return s&&i.push(e),O(i,a=>{let u=a[0];if(u==null)return"allow";let c=s?a[1]??0:e(u.accumulated);return c>=o?"block":c>=n?"review":"allow"},{name:r?.name??"content-gate",initial:"allow"})}oe();function Qh(t,e,n,r){let o=n??(()=>"[REDACTED]");function s(i){let a=i;for(let u of e){let c=u.global?u:new RegExp(u.source,`${u.flags}g`);a=a.replace(c,d=>o(d,u))}return a}return O([t.latest],([i])=>{if(i==null)return{source:"",token:"",accumulated:"",index:-1};let a=i,u=s(a.accumulated),c=s(a.token);return{source:a.source,token:c,accumulated:u,index:a.index}},{name:r?.name??"redactor"})}Ne();ie();xe();oe();Tt();Re();oe();var Ts=class extends q{_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=O([this.messages],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:ge("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(se(this.latest)),this.messageCount=O([this.messages],([r])=>r.length,{name:"messageCount",describeKind:"derived",meta:ge("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(se(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 ka(t,e){return new Ts(t,e)}oe();var ws=class extends q{definitions;schemas;constructor(e,n={}){super(e,n.graph),this.definitions=N(new Map,{name:"definitions",describeKind:"state",meta:ge("tool_definitions")}),this.add(this.definitions,{name:"definitions"}),this.schemas=O([this.definitions],([r])=>[...(r??new Map).values()],{name:"schemas",describeKind:"derived",meta:ge("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(se(this.schemas))}register(e){let n=this.definitions.cache,r=new Map(n);r.set(e.name,e),this.definitions.emit(r)}unregister(e){let n=this.definitions.cache;if(!n.has(e))return;let r=new Map(n);r.delete(e),this.definitions.emit(r)}async execute(e,n){let o=this.definitions.cache.get(e);if(!o)throw new Error(`toolRegistry: unknown tool "${e}"`);let s=o.handler(n);return gn(s)}getDefinition(e){return this.definitions.cache?.get(e)}};function xa(t,e){return new ws(t,e)}var ks=class extends q{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;turnCount;_terminalResult;_disposeRunWiring;_runVersion=0;_running=!1;_currentAbortController=null;constructor(e,n){if(super(e,n.graph),this.chat=ka(`${e}-chat`,{maxMessages:n.maxMessages}),this.mount("chat",this.chat),this.tools=xa(`${e}-tools`),this.mount("tools",this.tools),n.tools)for(let F of n.tools)this.tools.register(F);this.status=N("idle",{name:"status",describeKind:"state",meta:ge("agent_status")}),this.add(this.status,{name:"status"}),this.turn=N(0,{name:"turn",describeKind:"state",meta:ge("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.turnCount=this.turn,this.aborted=N(!1,{name:"aborted",describeKind:"state",meta:ge("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let r=0,o=this.turn.subscribe(F=>{for(let A of F)A[0]===S&&(r=A[1])}),s=!1,i=this.aborted.subscribe(F=>{for(let A of F)A[0]===S&&(s=A[1])}),a=n.adapter,u=n.systemPrompt,c=n.model,d=n.temperature,l=n.maxTokens,f=n.maxTurns??10,p=n.stopWhen,m=this.chat,h=this.tools,g=this.status,y=this.turn,b=this.aborted,v=K([g],(F,A,D)=>{if(Kr(F,D.prevData,0,"idle")!=="thinking"||s||r>=f){A.down([[B]]);return}let Q=m.allMessages();if(Q.length===0){A.down([[B]]);return}let U=h.schemas.cache??[];A.emit({messages:Q,tools:U})},{name:"promptInput",describeKind:"derived",meta:ge("agent_prompt_input")}),T=be(v,F=>{let A=new AbortController;return this._currentAbortController=A,s&&A.abort(new Error("agentLoop: aborted")),re(Promise.resolve(a.invoke(F.messages,{tools:F.tools.length>0?F.tools:void 0,systemPrompt:u,model:c,temperature:d,maxTokens:l,signal:A.signal})),{signal:A.signal})},{equals:()=>!1}),w=N(null,{name:"lastResponse",describeKind:"state",meta:ge("agent_last_response")});this.lastResponse=w;let k=K([w,g],(F,A,D)=>{let I=Kr(F,D.prevData,0,null);if(Kr(F,D.prevData,1,"idle")!=="acting"){A.down([[B]]);return}let U=I?.toolCalls;if(U==null||U.length===0){A.down([[B]]);return}A.emit(U)},{name:"toolCalls",describeKind:"derived",meta:ge("agent_tool_calls")}),x=n.interceptToolCalls?n.interceptToolCalls(k):k;this.toolCalls=x;let R=(F,A)=>{if(F===A)return!0;if(F.length!==A.length)return!1;for(let D=0;D<F.length;D++){let I=F[D],Q=A[D];if(I?.id!==Q?.id||I?.content!==Q?.content)return!1}return!0},E=be(x,F=>{if(F==null||F.length===0)throw new Error("agentLoop: toolResultsNode received an empty tool-call batch as DATA \u2014 toolCallsNode gating invariant broken (should emit RESOLVED for empty). Audit toolCallsNode.");let A=F.map(D=>Xh(D,h));return O(A,D=>D.map((I,Q)=>{let U=I;return U!=null&&typeof U=="object"&&"id"in U&&"content"in U?U:{id:F[Q].id,content:JSON.stringify(I??null)}}),{name:"toolResults_batch",equals:R})});this.toolResults=E;let G=fe([T],([F])=>{if(s)return;let A=F,D=r+1,I=A.toolCalls!=null&&A.toolCalls.length>0,Q=A.finishReason==="end_turn"&&(!A.toolCalls||A.toolCalls.length===0),U=p?.(A)===!0,ae=D>=f,j=U||Q||!I||ae?"done":"acting";te(()=>{w.emit(A),g.emit(j),y.emit(D),m.append("assistant",A.content,{toolCalls:A.toolCalls})})}),L=fe([E],([F])=>{if(s)return;let A=F;if(A.length===0)return;let D=r>=f?"done":"thinking";te(()=>{g.emit(D);for(let I of A)m.appendToolResult(I.id,I.content)})}),P=fe([b],([F])=>{F===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),g.emit("done"))}),C=se(G),V=se(L),ne=se(P);this._terminalResult=K([g,w],(F,A,D)=>{let I=Kr(F,D.prevData,0,"idle"),Q=Kr(F,D.prevData,1,null);if(I==="done"){if(Q!=null){A.emit({response:Q,runVersion:this._runVersion});return}let U=new Error("agentLoop: aborted");U.name="AbortError",A.down([[M,U]]);return}if(I==="error"){A.down([[M,new Error("agentLoop: errored")]]);return}A.down([[B]])},{name:"terminalResult",describeKind:"derived",meta:ge("agent_terminal_result")}),this.addDisposer(o),this.addDisposer(i),this.addDisposer(C),this.addDisposer(V),this.addDisposer(ne),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=++this._runVersion;te(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle")}),e!=null&&this.chat.append("user",e),this.status.emit("thinking");let o;if(n!=null)if(n.aborted)this.aborted.emit(!0);else{let s=()=>this.aborted.emit(!0);n.addEventListener("abort",s,{once:!0}),o=()=>n.removeEventListener("abort",s)}try{return(await So(this._terminalResult,{predicate:i=>i!=null&&typeof i=="object"&&i.runVersion===r})).response}finally{o?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function Xh(t,e){let n=At(()=>re(Promise.resolve().then(()=>e.execute(t.name,t.arguments))),{count:1}),r=O([n],([o])=>({id:t.id,content:typeof o=="string"?o:JSON.stringify(o)}));return Mr(r,o=>({id:t.id,content:JSON.stringify({error:String(o)})}))}function Kr(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 Zh(t,e){return new ks(t,e)}oe();Re();function eg(t,e,n){let r=re(t),o=n?.condition!=null?re(n.condition):null,s=N(null,{name:n?.name?`${n.name}::null`:"handoff::null"});if(o==null)return be(r,a=>{if(a==null)return s;let u=N(a);return e(u)});let i=O([r,o],([a,u])=>({v:a,open:u===!0}),{name:n?.name?`${n.name}::router`:"handoff::router",describeKind:"derived"});return be(i,({v:a,open:u})=>{if(a==null)return s;if(!u)return N(a);let c=N(a);return e(c)})}oe();Re();function tg(t,e,n){let r=re(t),o=e.map(i=>re(i)),s=[r,...o];return O(s,i=>{let a=i[0]??[],u=i.slice(1);return a.filter(c=>{for(let d of u)if(d!=null&&!d(c))return!1;return!0})},{name:n?.name??"tool-selector",describeKind:"derived",meta:ge("tool_selector"),equals:(i,a)=>{let u=i,c=a;if(u.length!==c.length)return!1;for(let d=0;d<u.length;d++)if(u[d]!==c[d])return!1;return!0}})}function ng(t){return{persistence:.5,structure:.5,personalValue:.5}}function rg(t={}){let e=t.scoreFn??ng,n=t.persistenceThreshold??.3,r=t.personalValueThreshold??.3,o=t.requireStructured??!1;return s=>{let i=e(s);return!(i.persistence<n||i.personalValue<r||o&&i.structure<=0)}}Ne();ke();oe();Re();var Rs={};he(Rs,{collection:()=>sg,decay:()=>vn,knowledgeGraph:()=>Na,lightCollection:()=>Ra,vectorIndex:()=>Sa});ke();oe();function vn(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)}function zl(t){if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1")}function ht(t){return new Map(t)}function ze(t){return t.cache??new Map}function xs(t){return t.cache??[]}function og(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 a=t[i]??0,u=e[i]??0;r+=a*u,o+=a*a,s+=u*u}return o===0||s===0?0:r/Math.sqrt(o*s)}function Ra(t={}){let e=t.maxSize,n=t.policy??"fifo";zl(e);let r=N(new Map,{name:t.name,describeKind:"state"});function o(i){if(e!==void 0)for(;i.size>e;){let a;for(let u of i.values()){if(!a){a=u;continue}let c=n==="lru"?u.lastAccessNs:u.createdAtNs,d=n==="lru"?a.lastAccessNs:a.createdAtNs;c<d&&(a=u)}if(!a)break;i.delete(a.id)}}function s(i){r.emit(i)}return{entries:r,upsert(i,a){let u=$(),c=ze(r),d=c.get(i),l=ht(c);l.set(i,{id:i,value:a,createdAtNs:d?.createdAtNs??u,lastAccessNs:u}),o(l),s(l)},remove(i){let a=ht(ze(r));a.delete(i)&&s(a)},clear(){ze(r).size!==0&&s(new Map)},get(i){let a=ze(r),u=a.get(i);if(u){if(n==="lru"){let c=$(),d=ht(a);d.set(i,{...u,lastAccessNs:c}),s(d)}return u.value}},has(i){return ze(r).has(i)}}}function sg(t,e={}){let n=e.maxSize,r=e.policy??"lru",o=e.decayRate??0,s=e.minScore??0,i=e.score??(()=>1);zl(n);let a=new q(t),u=N(new Map,{name:"items",describeKind:"state"}),c=O([u],([h])=>{let g=h??new Map,y=$(),b=[...g.values()].map(v=>{let T=(y-v.lastAccessNs)/1e9;return{...v,score:vn(v.baseScore,T,o,s)}});return b.sort((v,T)=>T.score-v.score||T.lastAccessNs-v.lastAccessNs),b},{name:"ranked",describeKind:"derived"}),d=O([u],([h])=>(h??new Map).size,{name:"size",describeKind:"derived",initial:0});c.subscribe(()=>{}),d.subscribe(()=>{}),a.add(u,{name:"items"}),a.add(c,{name:"ranked"}),a.add(d,{name:"size"});function l(h,g){let y=(g-h.lastAccessNs)/1e9;return vn(h.baseScore,y,o,s)}function f(h){if(n!==void 0)for(;h.size>n;){let g=$(),y,b=Number.POSITIVE_INFINITY;for(let v of h.values()){let T=l(v,g);if(T<b){y=v,b=T;continue}if(T===b&&y){let w=r==="lru"?v.lastAccessNs:v.createdAtNs,k=r==="lru"?y.lastAccessNs:y.createdAtNs;w<k&&(y=v)}}if(!y)break;h.delete(y.id)}}function p(h){u.emit(h)}return Object.assign(a,{upsert(h,g,y){let b=$(),v=ze(u),T=v.get(h),w=y?.score??i(g),k=ht(v);k.set(h,{id:h,value:g,baseScore:w,createdAtNs:T?.createdAtNs??b,lastAccessNs:b}),f(k),p(k)},remove(h){let g=ht(ze(u));g.delete(h)&&p(g)},clear(){ze(u).size!==0&&p(new Map)},getItem(h){let g=ze(u),y=g.get(h);if(y){if(r==="lru"){let b=ht(g);b.set(h,{...y,lastAccessNs:$()}),p(b)}return y}}})}function Sa(t={}){let e=t.backend??"flat",n=t.dimension,r;if(e==="hnsw"&&(r=t.hnswFactory?.(),!r))throw new Error('vectorIndex backend "hnsw" requires an optional dependency adapter; install your HNSW package and provide `hnswFactory`.');let o=N(new Map,{describeKind:"state",name:"vector-index"});function s(a){if(n!==void 0&&a.length!==n)throw new RangeError(`vector dimension mismatch: expected ${n}, got ${a.length}`)}function i(a){o.emit(a)}return{backend:e,entries:o,upsert(a,u,c){s(u);let d=ht(ze(o));d.set(a,{id:a,vector:[...u],meta:c}),e==="hnsw"&&r.upsert(a,u,c),i(d)},remove(a){let u=ht(ze(o));u.delete(a)&&(e==="hnsw"&&r.remove(a),i(u))},clear(){ze(o).size!==0&&(e==="hnsw"&&r.clear(),i(new Map))},search(a,u=5){return s(a),u<=0?[]:e==="hnsw"?r.search(a,u):[...ze(o).values()].map(d=>({id:d.id,score:og(a,d.vector),meta:d.meta})).sort((d,l)=>l.score-d.score).slice(0,u)}}}function Na(t){let e=new q(t),n=N(new Map,{name:"entities",describeKind:"state"}),r=N([],{name:"edges",describeKind:"state"}),o=O([r],([u])=>{let c=u??[],d=new Map;for(let l of c){let f=d.get(l.from)??[];d.set(l.from,Object.freeze([...f,l]))}return d},{name:"adjacency",describeKind:"derived",initial:new Map});o.subscribe(()=>{}),e.add(n,{name:"entities"}),e.add(r,{name:"edges"}),e.add(o,{name:"adjacency"});function s(u){n.emit(u)}function i(u){r.emit(u)}return Object.assign(e,{upsertEntity(u,c){let d=ht(ze(n));d.set(u,c),s(d)},removeEntity(u){let c=ht(ze(n)),d=c.delete(u),l=xs(r),f=l.filter(p=>p.from!==u&&p.to!==u);!d&&f.length===l.length||(s(c),i(f))},link(u,c,d,l=1){let f=`${u}\0${c}\0${d}`,p=xs(r),m=new Set(p.map(g=>`${g.from}\0${g.to}\0${g.relation}`)),h=[...p];if(m.has(f))for(let g=0;g<h.length;g+=1){let y=h[g];if(y.from===u&&y.to===c&&y.relation===d){h[g]={...y,weight:l};break}}else h.push({from:u,to:c,relation:d,weight:l});i(h)},unlink(u,c,d){let l=xs(r),f=l.filter(p=>d===void 0?!(p.from===u&&p.to===c):!(p.from===u&&p.to===c&&p.relation===d));f.length!==l.length&&i(f)},related(u,c){return xs(r).filter(d=>(d.from===u||d.to===u)&&(c===void 0||d.relation===c))}})}ie();oe();Re();function Ea(t,e){return(n,r)=>{let o=[...r.keys()].slice(0,100),s=[{role:"system",content:t},{role:"user",content:JSON.stringify({input:n,existingKeys:o})}];return W(i=>{let a=!0,u=e.adapter.invoke(s,{model:e.model,temperature:e.temperature??0,maxTokens:e.maxTokens}),d=re(u).subscribe(l=>{if(!a)return;let f=!1;for(let p of l){if(f)break;if(p[0]===S){let m=p[1];try{let h=JSON.parse(m.content);i.emit(h),i.down([[_]])}catch{i.down([[M,new Error("llmExtractor: failed to parse LLM response as JSON")]])}f=!0}else p[0]===M?(i.down([[M,p[1]]]),f=!0):p[0]===_?(i.down([[_]]),f=!0):i.down([[p[0],p[1]]])}});return()=>{d(),a=!1}})}}function _a(t,e){return n=>{let r=[...n.entries()].map(([s,i])=>({key:s,value:i})),o=[{role:"system",content:t},{role:"user",content:JSON.stringify({memories:r})}];return W(s=>{let i=!0,a=e.adapter.invoke(o,{model:e.model,temperature:e.temperature??0,maxTokens:e.maxTokens}),c=re(a).subscribe(d=>{if(!i)return;let l=!1;for(let f of d){if(l)break;if(f[0]===S){let p=f[1];try{let m=JSON.parse(p.content);s.emit(m),s.down([[_]])}catch{s.down([[M,new Error("llmConsolidator: failed to parse LLM response as JSON")]])}l=!0}else f[0]===M?(s.down([[M,f[1]]]),l=!0):f[0]===_?(s.down([[_]]),l=!0):s.down([[f[0],f[1]]])}});return()=>{c(),i=!1}})}}var Ma=Math.LN2/604800;function Hr(t){return t instanceof Map?t:new Map}function ig(t,e,n){let r=new q(t,n.graph),o=[],s;if(n.extractFn)s=n.extractFn;else if(n.adapter&&n.extractPrompt)s=Ea(n.extractPrompt,{adapter:n.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let i=(v,T)=>v==null?{upsert:[]}:s(v,T),a=e;if(n.admissionFilter){let v=re(e),T=n.admissionFilter;a=O([v],([w])=>{if(T(w))return w},{name:"admissionFilter",describeKind:"derived"})}let u;n.consolidateFn?u=n.consolidateFn:n.adapter&&n.consolidatePrompt&&(u=_a(n.consolidatePrompt,{adapter:n.adapter}));let c=n.consolidateTrigger;if(!c&&u&&n.reflection?.enabled!==!1){let v=n.reflection?.interval??3e5;c=et(v,{period:v})}let d={score:n.score,cost:n.cost,budget:n.budget??2e3,context:n.context,consolidate:u,consolidateTrigger:c},l=Zo(a,i,d);r.add(l.store.entries,{name:"store"}),r.add(l.compact,{name:"compact"}),r.add(l.size,{name:"size"});let f=null;n.vectorDimensions&&n.vectorDimensions>0&&n.embedFn&&(f=Sa({dimension:n.vectorDimensions}),r.add(f.entries,{name:"vectorIndex"}));let p=null;n.enableKnowledgeGraph&&(p=Na(`${t}-kg`),r.mount("kg",p));let m=null;if(n.tiers){let v=n.tiers,T=v.decayRate??Ma,w=v.maxActive??1e3,k=v.archiveThreshold??.1,x=v.permanentFilter??(()=>!1),R=Ra({name:"permanent"});r.add(R.entries,{name:"permanent"});let E=new Set,G=A=>E.has(A)?"permanent":Hr(l.store.entries.cache).has(A)?"active":"archived",L=(A,D)=>{E.add(A),R.upsert(A,D)},P=new Map,C=l.store.entries,V=n.context?re(n.context):N(null),ne=fe([C,V],([A,D])=>{let I=Hr(A),Q=$(),U=[],ae=[];for(let[Y,J]of I){if(P.has(Y)||P.set(Y,Q),x(Y,J)){ae.push({key:Y,value:J});continue}let z=n.score(J,D),X=P.get(Y)??Q,H=Number(Q-X)/1e9;vn(z,H,T)<k&&U.push(Y)}for(let Y of P.keys())I.has(Y)||P.delete(Y);for(let{key:Y,value:J}of ae)E.has(Y)||L(Y,J);let j=I.size-E.size;if(j>w){let Y=[...I.entries()].filter(([z])=>!E.has(z)).map(([z,X])=>({key:z,score:n.score(X,D)})).sort((z,X)=>z.score-X.score),J=j-w;for(let z=0;z<J&&z<Y.length;z++){let X=Y[z].key;U.includes(X)||U.push(X)}}U.length>0&&te(()=>{for(let Y of U)l.store.delete(Y)})});o.push(ne.subscribe(()=>{}));let F=null;v.archiveTier&&(F=r.attachStorage([v.archiveTier],v.archiveStorageOptions??{})),m={permanent:R,activeEntries:C,archiveHandle:F,tierOf:G,markPermanent:L}}if(f||p){let v=n.embedFn,T=n.entityFn,w=l.store.entries,k=fe([w],([x])=>{let R=Hr(x);for(let[E,G]of R){if(f&&v){let L=v(G);L&&f.upsert(E,L,G)}if(p&&T){let L=T(E,G);if(L){for(let P of L.entities??[])p.upsertEntity(P.id,P.value);for(let P of L.relations??[])p.link(P.from,P.to,P.relation,P.weight)}}}});o.push(k.subscribe(()=>{}))}let h=null,g=null,y=null,b=null;if(f||p){let v=n.retrieval?.topK??20,T=n.retrieval?.graphDepth??1,w=n.budget??2e3,k=n.cost,x=n.score,R=n.contextOf,E=n.contextWeight??0,G=n.context?re(n.context):N(null),L=(F,A)=>{if(!F||!A)return 0;let D=Math.min(F.length,A.length),I=0;for(;I<D&&F[I]===A[I];)I++;return I},P=(F,A,D)=>{let I=new Map,Q=[];if(f&&D.vector){Q=f.search(D.vector,v);for(let X of Q){let H=F.get(X.id);H&&I.set(X.id,{value:H,sources:new Set(["vector"])})}}let U=[];if(p){let X=[...D.entityIds??[],...I.keys()],H=new Set,le=X;for(let ve=0;ve<T;ve++){let Oe=[];for(let Be of le){if(H.has(Be))continue;H.add(Be);let gt=p.related(Be);for(let Wt of gt){let rt=Wt.to;if(!H.has(rt)){Oe.push(rt);let We=F.get(rt);if(We){let Z=I.get(rt);Z?Z.sources.add("graph"):I.set(rt,{value:We,sources:new Set(["graph"])}),U.push(rt)}}}}le=Oe}}for(let[X,H]of F)I.has(X)||I.set(X,{value:H,sources:new Set(["store"])});let ae=D.context?.length??0,j=[];for(let[X,{value:H,sources:le}]of I){let ve=R?R(H):void 0,Oe=x(H,A);if(E>0&&ae>0){let gt=L(D.context,ve);gt>0&&(Oe=Oe*(1+E*gt/ae))}let Be=ve?{key:X,value:H,score:Oe,sources:[...le],context:ve}:{key:X,value:H,score:Oe,sources:[...le]};j.push(Be)}j.sort((X,H)=>H.score-X.score);let Y=[],J=0;for(let X of j){let H=k(X.value);if(J+H>w&&Y.length>0)break;Y.push(X),J+=H}return{packed:Y,trace:{vectorCandidates:Q,graphExpanded:U,ranked:j,packed:Y}}},C=N([],{name:"retrieval",describeKind:"state",meta:ge("retrieval_pipeline")});r.add(C,{name:"retrieval"}),h=C;let V=N(null,{name:"retrievalTrace",describeKind:"state",meta:ge("retrieval_trace")});r.add(V,{name:"retrievalTrace"}),g=V,y=F=>{let A=Hr(l.store.entries.cache),{packed:D,trace:I}=P(A,G.cache,F);return te(()=>{C.emit(D),V.emit(I)}),D},b=F=>{let A=re(F);return O([l.store.entries,G,A],([D,I,Q])=>{if(Q==null)return[];let U=Hr(D);return P(U,I,Q).packed},{name:"retrievalReactive",describeKind:"derived",meta:ge("retrieval_reactive"),initial:[]})}}return r.addDisposer(()=>{for(let v of o)v();o.length=0}),Object.assign(r,{distillBundle:l,compact:l.compact,size:l.size,vectors:f,kg:p,memoryTiers:m,retrieval:h,retrievalTrace:g,retrieve:y,retrieveReactive:b})}function ag(t,e,n){let r=t.describe({actor:e,detail:"full"}),o=n?.groupByTags??!0,s=n?.separator??`
57
+ `,i=[],a=n?.sinceVersion;for(let[u,c]of Object.entries(r.nodes)){let d=c.meta??{},l=d.description,f=d.format;if(!l&&!f)continue;if(a!=null&&c.v!=null){let y=a.get(u);if(y!=null&&y.id===c.v.id&&c.v.version<=y.version)continue}let p=l??u,m=c.value,h=d.unit,g;f==="currency"&&typeof m=="number"?g=`$${m.toFixed(2)}`:f==="percentage"&&typeof m=="number"?g=`${(m*100).toFixed(1)}%`:m==null?g="(no value)":g=String(m),h&&f!=="currency"&&f!=="percentage"&&(g=`${g} ${h}`),i.push({path:u,description:p,formatted:g})}if(i.length===0)return"";if(o){let u=new Map,c=[];for(let l of i){let p=r.nodes[l.path].meta?.tags;if(p&&p.length>0){let m=p[0],h=u.get(m);h||(h=[],u.set(m,h)),h.push(l)}else c.push(l)}if(u.size===0)return i.map(l=>`- ${l.description}: ${l.formatted}`).join(s);let d=[];for(let[l,f]of[...u.entries()].sort((p,m)=>p[0].localeCompare(m[0])))d.push(`[${l}]${s}${f.map(p=>`- ${p.description}: ${p.formatted}`).join(s)}`);return c.length>0&&d.push(c.map(l=>`- ${l.description}: ${l.formatted}`).join(s)),d.join(s+s)}return i.map(u=>`- ${u.description}: ${u.formatted}`).join(s)}var Jl=new Set(["state","derived","producer","operator","effect"]);function Oa(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 i=s;if((typeof i.type!="string"||!Jl.has(i.type))&&e.push(`Node "${o}": invalid type "${String(i.type)}" (expected: ${[...Jl].join(", ")})`),Array.isArray(i.deps))for(let a of i.deps)typeof a=="string"&&!r.has(a)&&e.push(`Node "${o}": dep "${a}" 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 i=n.edges[s];if(i==null||typeof i!="object"){e.push(`Edge [${s}]: must be an object`);continue}let a=i;(typeof a.from!="string"||!r.has(a.from))&&e.push(`Edge [${s}]: 'from' "${String(a.from)}" does not reference an existing node`),(typeof a.to!="string"||!r.has(a.to))&&e.push(`Edge [${s}]: 'to' "${String(a.to)}" does not reference an existing node`);let u=`${a.from}->${a.to}`;o.has(u)&&e.push(`Edge [${s}]: duplicate edge ${u}`),o.add(u)}}return{valid:e.length===0,errors:e}}var Yl=`You are a graph architect for GraphReFly, a reactive graph protocol.
57
58
 
58
59
  Given a natural-language description, produce a JSON graph definition with this structure:
59
60
 
@@ -88,11 +89,11 @@ Rules:
88
89
  - "producer" nodes have no deps but generate values asynchronously.
89
90
  - Edges wire output of one node as input to another. They must match deps.
90
91
  - meta.description is required for every node.
91
- - Return ONLY valid JSON, no markdown fences or commentary.`;async function kh(t,e,n){let o=[{role:"system",content:n?.systemPromptExtra?`${El}
92
+ - Return ONLY valid JSON, no markdown fences or commentary.`;async function ug(t,e,n){let o=[{role:"system",content:n?.systemPromptExtra?`${Yl}
92
93
 
93
- ${n.systemPromptExtra}`:El},{role:"user",content:t}],s=e.invoke(o,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens}),a=(await vs(s)).content.trim();a.startsWith("```")&&(a=Ts(a));let u;try{u=JSON.parse(a)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${a.slice(0,200)}`)}let c=Al(u);if(!c.valid)throw new Error(`graphFromSpec: invalid graph definition:
94
+ ${n.systemPromptExtra}`:Yl},{role:"user",content:t}],s=e.invoke(o,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens}),a=(await gn(s)).content.trim();a.startsWith("```")&&(a=yn(a));let u;try{u=JSON.parse(a)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${a.slice(0,200)}`)}let c=Oa(u);if(!c.valid)throw new Error(`graphFromSpec: invalid graph definition:
94
95
  ${c.errors.join(`
95
- `)}`);let d=u;return d.version===void 0&&(d.version=1),Array.isArray(d.subgraphs)||(d.subgraphs=[]),z.fromSnapshot(d,n?.build)}var xh=`You are a reactive graph optimizer for GraphReFly.
96
+ `)}`);let d=u;return d.version===void 0&&(d.version=1),Array.isArray(d.subgraphs)||(d.subgraphs=[]),q.fromSnapshot(d,n?.build)}function cg(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 dg(t,e){let n=t.describe({actor:e,detail:"full"}),r=[],o=[],s=[];for(let[i,a]of Object.entries(n.nodes)){if(a.type!=="state"||i.includes("::__meta__::")||a.status==="completed"||a.status==="errored")continue;let u=a.meta??{},c=u.access;if(c==="human"||c==="system")continue;let d=u.description??`Set the value of ${i}`,l=cg(u),f={type:"object",required:["value"],properties:{value:l},additionalProperties:!1},p=i.replace(/::/g,"__");r.push({type:"function",function:{name:p,description:d,parameters:f}}),o.push({name:i,description:d,inputSchema:f});let m=t,h=e,g=a.v;s.push({name:i,description:d,parameters:f,handler(y){return m.set(i,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}}var lg=`You are a reactive graph optimizer for GraphReFly.
96
97
 
97
98
  Given a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.
98
99
 
@@ -113,18 +114,18 @@ Return ONLY valid JSON with this structure:
113
114
  Rules:
114
115
  - Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).
115
116
  - Keep changes minimal \u2014 prefer the smallest set of operations that solves the problem.
116
- - Return ONLY valid JSON, no markdown fences or commentary.`;async function Rh(t,e,n,r){let{expand:o,...s}=t.describe({actor:r?.actor,detail:"standard"}),i=[{role:"system",content:xh},{role:"user",content:JSON.stringify({graph:s,problem:e})}],a=n.invoke(i,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens}),c=(await vs(a)).content.trim();c.startsWith("```")&&(c=c.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let d;try{d=JSON.parse(c)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${c.slice(0,200)}`)}let l=d;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}}var Rs={};he(Rs,{AuditTrailGraph:()=>ks,PolicyEnforcerGraph:()=>xs,auditTrail:()=>Nh,complianceSnapshot:()=>Eh,policyEnforcer:()=>wa,reactiveExplainPath:()=>ka});Te();Jt();ie();we();le();eo();function Il(t,e){return Ke("audit",t,e)}var Sh=new Set(["data","error","complete","teardown"]),ks=class extends z{entries;count;_log;_target;constructor(e,n){super(n.name??`${e.name}_audit`,n.graph),this._target=e,this._log=je([],{name:"entries",...n.maxSize!=null?{maxSize:n.maxSize}:{}}),this.entries=this._log.entries,this.add(this.entries,{name:"entries"}),this.count=A([this.entries],([u])=>u.length,{name:"count",describeKind:"derived",meta:Il("count")}),this.add(this.count,{name:"count"}),this.addDisposer(oe(this.count));let r=n.includeTypes!=null?new Set(n.includeTypes):Sh,o=n.filter,s=0,i=e.observe({timeline:!0,structured:!0}),a=i.onEvent(u=>{if(u.type==="derived")return;let c=u.type;if(!r.has(c))return;let d=u.path??"",l={seq:s++,timestamp_ns:u.timestamp_ns??B(),wall_clock_ns:pe(),path:d,type:c},p=(d?Ta(e,d):void 0)?.lastMutation;p!=null&&(l.actor=p.actor),c==="data"&&(l.value=u.data),c==="error"&&(l.error=u.data);let m=d?Mh(e,d):void 0;m!=null&&(l.annotation=m),!(o!=null&&!o(l))&&this._log.append(l)});this.addDisposer(()=>{a(),i.dispose()}),this.addDisposer(()=>this._log.disposeAllViews())}all(){return this.entries.cache??[]}byNode(e){return this.all().filter(n=>n.path===e)}byActor(e){return this.all().filter(n=>n.actor?.id===e)}byActorType(e){return this.all().filter(n=>n.actor?.type===e)}byTimeRange(e,n){return this.all().filter(r=>!(r.timestamp_ns<e||n!=null&&r.timestamp_ns>=n))}get target(){return this._target}};function Nh(t,e={}){return new ks(t,e)}var xs=class extends z{policies;violations;violationCount;_target;_mode;_currentGuard;constructor(e,n,r){super(r.name??`${e.name}_policy`,r.graph),this._target=e,this._mode=r.mode??"audit";let o=_h(n)?n:N(n,{name:"policies"});this.policies=o,this.add(this.policies,{name:"policies"}),this.violations=new nt("violations",{retainedLimit:r.violationsLimit??1e3}),this.mount("violations",this.violations),this.violationCount=A([this.violations.events],([c])=>c.length,{name:"violationCount",describeKind:"derived",meta:Il("policy_violation_count")}),this.add(this.violationCount,{name:"violationCount"}),this.addDisposer(oe(this.violationCount));let i=o.cache??[];this._currentGuard=ur(i);let a=o.subscribe(c=>{for(let d of c)d[0]===R&&(i=d[1]??[],this._currentGuard=ur(i))});this.addDisposer(a);let u=r.paths!=null?[...r.paths]:Ll(e);if(this._mode==="enforce"){let c=new Map,d=l=>{if(c.has(l))return;let f=Ta(e,l);if(!(f instanceof xe))return;let p=(m,h)=>{let g=this._currentGuard(m,h);return g||this._publishViolation(m,h,l,"blocked"),g};c.set(l,f._pushGuard(p))};for(let l of u)d(l);if(r.paths==null){let l=wt(e,(f,p,m)=>{if(f.kind==="added")if(f.nodeKind==="node")d(`${m}${f.name}`);else{let h=p._mounts.get(f.name);if(!(h instanceof z))return;let g=`${m}${f.name}::`,y=Ll(h);for(let b of y)d(b===""?`${m}${f.name}`:`${g}${b}`)}else if(f.kind==="removed")if(f.nodeKind==="node"){let h=`${m}${f.name}`,g=c.get(h);g!=null&&(g(),c.delete(h))}else{let h=`${m}${f.name}`,g=`${h}::`;for(let[y,b]of c)(y===h||y.startsWith(g))&&(b(),c.delete(y))}});this.addDisposer(l)}else{let l=e.topology.subscribe(f=>{for(let p of f){if(p[0]!==R)continue;let m=p[1];if(m.kind!=="removed"||m.nodeKind!=="node")continue;let h=c.get(m.name);h!=null&&(h(),c.delete(m.name))}});this.addDisposer(l)}this.addDisposer(()=>{for(let l of c.values())l();c.clear()})}else{let c=e.observe({timeline:!0,structured:!0}),d=c.onEvent(l=>{if(l.type!=="data"&&l.type!=="error")return;let f=l.path??"";if(!f||r.paths!=null&&!r.paths.includes(f))return;let p=l.actor??Ta(e,f)?.lastMutation?.actor;if(p==null)return;let m="write";this._currentGuard(p,m)||this._publishViolation(p,m,f,"observed")});this.addDisposer(()=>{d(),c.dispose()})}}_publishViolation(e,n,r,o){this.violations.publish({timestamp_ns:B(),wall_clock_ns:pe(),path:r,actor:e,action:n,mode:this._mode,result:o})}all(){return this.violations.retained()}get mode(){return this._mode}get target(){return this._target}};function wa(t,e,n={}){return new xs(t,e,n)}function ka(t,e,n,r){return t.explain(e,n,{reactive:!0,...r})}function Eh(t,e={}){let n={format_version:1,timestamp_ns:B(),wall_clock_ns:pe(),graph:t.snapshot()};if(e.actor!=null&&(n.actor=e.actor),e.audit!=null){let o=[...e.audit.all()];n.audit={count:o.length,entries:o}}if(e.policies!=null){let o=e.policies.policies.cache??[];n.policies={mode:e.policies.mode,rules:o,violations:[...e.policies.all()]}}let r=Oh(n);return{...n,fingerprint:r}}function _h(t){return typeof t=="object"&&t!==null&&"subscribe"in t}function Ta(t,e){try{return t.node(e)}catch{return}}function Mh(t,e){try{return t.annotation(e)}catch{return}}function Ll(t){let e=t.describe({detail:"minimal"});return Object.keys(e.nodes)}function Oh(t){return Mt(JSON.stringify(Ch(t)))}function Ch(t){let e=new Set,n=r=>{if(r===void 0)return{__undefined:!0};if(r===null)return null;let o=typeof r;if(o==="bigint")return{__bigint:r.toString()};if(o!=="object")return r;let s=r;if(e.has(s))return{__circular:!0};e.add(s);try{if(Array.isArray(s))return s.map(n);if(s instanceof Date)return{__date:s.toISOString()};if(s instanceof RegExp)return{__regexp:{source:s.source,flags:s.flags}};if(s instanceof Map)return{__map:[...s.entries()].map(([u,c])=>[n(u),n(c)])};if(s instanceof Set)return{__set:[...s].map(n)};if(ArrayBuffer.isView(s)){let a=s,u=new Array(a.length);for(let c=0;c<a.length;c++)u[c]=a[c]??0;return{__typed_array:{ctor:s.constructor.name,data:u}}}let i={};for(let a of Object.keys(s).sort())i[a]=n(s[a]);return i}finally{e.delete(s)}};return n(t)}var Ns={};he(Ns,{demoShell:()=>$h});Se();le();Te();we();le();function Ah(t){for(let e of t){let n=e.codePointAt(0);if(n>=19968&&n<=40959||n>=13312&&n<=19903||n>=12288&&n<=12351||n>=12352&&n<=12447||n>=12448&&n<=12543||n>=44032&&n<=55215||n>=65280&&n<=65519)return!0}return!1}var Pl=new Set(["\uFF0C","\uFF0E","\uFF01","\uFF1A","\uFF1B","\uFF1F","\u3001","\u3002","\u30FB","\uFF09","\u3015","\u3009","\u300B","\u300D","\u300F","\u3011"]),Lh=new Set([".",",","!","?",":",";",")","]","}","%",'"',"\u201D","\u2019","\xBB","\u203A","\u2026"]);function Ih(t){return t.replace(/[\t\n\r\f ]+/g," ").replace(/^ | $/g,"")}function Ph(t){let e=new Intl.Segmenter(void 0,{granularity:"word"}),n=[];for(let r of e.segment(t)){let o=r.segment,s=r.isWordLike??!1,i=[],a=[],u=[],c="",d=null;for(let l of o){let f;l===" "?f="space":l==="\u200B"?f="zero-width-break":l==="\xAD"?f="soft-hyphen":l===`
117
- `?f="hard-break":f="text",d!==null&&f===d?c+=l:(d!==null&&(i.push(c),a.push(d==="text"&&s),u.push(d)),c=l,d=f)}d!==null&&(i.push(c),a.push(d==="text"&&s),u.push(d)),n.push({texts:i,isWordLike:a,kinds:u})}return n}function _t(t,e,n,r,o){let s=Ih(t);if(s.length===0)return[];let i=Ph(s),a=new Intl.Segmenter(void 0,{granularity:"grapheme"}),u=[],c=[],d=[];for(let y of i)for(let b=0;b<y.texts.length;b++)u.push(y.texts[b]),c.push(y.kinds[b]),d.push(y.isWordLike[b]);let l=[],f=[],p=[];for(let y=0;y<u.length;y++){let b=u[y],v=c[y],T=d[y];if(v==="text"&&!T&&l.length>0&&f[f.length-1]==="text"&&b.length===1&&(Lh.has(b)||Pl.has(b))){l[l.length-1]+=b;continue}if(b==="-"&&l.length>0&&f[f.length-1]==="text"&&p[p.length-1]){l[l.length-1]+=b;continue}l.push(b),f.push(v),p.push(T)}let m=r.get(e);m||(m=new Map,r.set(e,m));function h(y){let b=m.get(y);if(b===void 0){o&&(o.misses+=1);let v=n.measureSegment(y,e).width;b=Number.isFinite(v)&&v>=0?v:0,m.set(y,b)}else o&&(o.hits+=1);return b}let g=[];for(let y=0;y<l.length;y++){let b=l[y],v=f[y];if(v!=="text"){g.push({text:b,width:v==="space"?h(" ")*b.length:0,kind:v,graphemeWidths:null});continue}if(Ah(b)){let k="";for(let x of a.segment(b)){let S=x.segment;if(k.length>0&&Pl.has(S)){k+=S;continue}if(k.length>0){let _=h(k);g.push({text:k,width:_,kind:"text",graphemeWidths:null})}k=S}if(k.length>0){let x=h(k);g.push({text:k,width:x,kind:"text",graphemeWidths:null})}continue}let T=h(b),w=null;if(p[y]&&b.length>1){let k=[];for(let x of a.segment(b))k.push(h(x.segment));k.length>1&&(w=k)}g.push({text:b,width:T,kind:"text",graphemeWidths:w})}return g}function gn(t,e,n,r,o){if(t.length===0)return{lines:[],lineCount:0};let s=[],i=0,a=!1,u=0,c=0,d=0,l=0,f=-1,p=0,m=o.get(r);m||(m=new Map,o.set(r,m));let h=m.get("-");h===void 0&&(h=n.measureSegment("-",r).width,m.set("-",h));function g(w=d,k=l,x=i){let S="";for(let _=u;_<w;_++){let F=t[_];if(!(F.kind==="soft-hyphen"||F.kind==="hard-break"))if(_===u&&c>0&&F.graphemeWidths){let D=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(F.text)].map(C=>C.segment);S+=D.slice(c).join("")}else S+=F.text}if(k>0&&w<t.length){let _=t[w],L=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(_.text)].map(C=>C.segment),D=u===w?c:0;S+=L.slice(D,k).join("")}w>0&&t[w-1]?.kind==="soft-hyphen"&&!(u===w&&c>0)&&(S+="-"),s.push({text:S,width:x,startSegment:u,startGrapheme:c,endSegment:w,endGrapheme:k}),i=0,a=!1,f=-1,p=0}function y(w){return w==="space"||w==="zero-width-break"||w==="soft-hyphen"}function b(w,k,x){a=!0,u=w,c=k,d=w+1,l=0,i=x}function v(w,k,x){a=!0,u=w,c=k,d=w,l=k+1,i=x}for(let w=0;w<t.length;w++){let k=t[w];if(k.kind==="hard-break"){a?g():s.push({text:"",width:0,startSegment:w,startGrapheme:0,endSegment:w,endGrapheme:0}),u=w+1,c=0;continue}let x=k.width;if(!a){x>e&&k.graphemeWidths?T(w,0,k.graphemeWidths):b(w,0,x),y(k.kind)&&(f=w+1,p=k.kind==="space"?i-x:i);continue}let S=i+x;if(S>e+.005){if(y(k.kind)){i+=x,d=w+1,l=0,g(w+1,0,k.kind==="space"?i-x:i);continue}if(f>=0){g(f,0,p),w--;continue}if(x>e&&k.graphemeWidths){g(),T(w,0,k.graphemeWidths);continue}g(),w--;continue}i=S,d=w+1,l=0,y(k.kind)&&(f=w+1,p=k.kind==="space"?i-x:i)}return a&&g(),{lines:s,lineCount:s.length};function T(w,k,x){for(let S=k;S<x.length;S++){let _=x[S];if(!a){v(w,S,_);continue}i+_>e+.005?(g(),v(w,S,_)):(i+=_,d=w,l=S+1)}a&&d===w&&l===x.length&&(d=w+1,l=0)}}function xa(t){return t==="space"||t==="zero-width-break"||t==="soft-hyphen"}var Ra=null;function Dh(){return Ra===null&&(Ra=new Intl.Segmenter(void 0,{granularity:"grapheme"})),Ra}function Dl(t,e,n){if(e===0&&n<0)return t.text;let r=[...Dh().segment(t.text)].map(s=>s.segment),o=n<0?r.length:n;return r.slice(e,o).join("")}function Bt(t,e,n,r,o,s){let i="";for(let a=e;a<r;a++){let u=t[a];u.kind==="soft-hyphen"||u.kind==="hard-break"||(a===e&&n>0?i+=Dl(u,n,-1):i+=u.text)}if(o>0&&r<t.length){let a=t[r];i+=Dl(a,e===r?n:0,o)}return s&&(i+="-"),i}function Gh(t){if(!t||!t.adapter||!t.font)return 0;let e=t.cache;if(e){let n=e.get(t.font);n||(n=new Map,e.set(t.font,n));let r=n.get("-");return r===void 0&&(r=t.adapter.measureSegment("-",t.font).width,n.set("-",r)),r}return t.adapter.measureSegment("-",t.font).width}function Sa(t,e,n,r){let o=e.segmentIndex,s=e.graphemeIndex;if(o>=t.length)return null;if(s===0){for(;o<t.length;){let w=t[o];if(w.kind==="hard-break")return{text:"",width:0,start:{segmentIndex:e.segmentIndex,graphemeIndex:0},end:{segmentIndex:o+1,graphemeIndex:0}};if(w.kind==="space"||w.kind==="zero-width-break"||w.kind==="soft-hyphen"){o+=1;continue}break}if(o>=t.length)return null}let i=Gh(r),a=o,u=o===e.segmentIndex?s:0,c=0,d=a,l=0,f=!1,p=-1,m=0,h=0,g=!1,y=(w,k,x,S)=>{p=w,m=k,h=x,g=S==="soft-hyphen"},b=(w,k,x)=>{for(let S=k;S<x.length;S++){let _=x[S];if(!f){c=_,d=w,l=S+1,f=!0;continue}if(c+_>n+.005)return!0;c+=_,d=w,l=S+1}return d===w&&l===x.length&&(d=w+1,l=0),!1};if(u>0&&a<t.length){let w=t[a];if(w.graphemeWidths){if(b(a,u,w.graphemeWidths))return{text:Bt(t,a,u,d,l,!1),width:c,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}};o=d}}for(;o<t.length;){let w=t[o];if(w.kind==="hard-break"){if(f){let S=d>0&&t[d-1]?.kind==="soft-hyphen";return{text:Bt(t,a,u,d,l,S),width:c+(S?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}}return{text:"",width:0,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:o+1,graphemeIndex:0}}}let k=w.width;if(!f){if(k>n&&w.graphemeWidths){if(b(o,0,w.graphemeWidths))return{text:Bt(t,a,u,d,l,!1),width:c,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}};o=d;continue}c=k,d=o+1,l=0,f=!0,xa(w.kind)&&y(o+1,0,w.kind==="space"?c-k:c,w.kind),o+=1;continue}let x=c+k;if(x>n+.005){if(xa(w.kind)){d=o+1,l=0;let _=w.kind==="soft-hyphen",F=w.kind==="space"?c:c+(_?i:0);return{text:Bt(t,a,u,d,l,_),width:F,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}}return p>=0?{text:Bt(t,a,u,p,m,g),width:h+(g?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:p,graphemeIndex:m}}:k>n&&w.graphemeWidths?{text:Bt(t,a,u,d,l,!1),width:c,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}:{text:Bt(t,a,u,d,l,!1),width:c,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}}c=x,d=o+1,l=0,xa(w.kind)&&y(o+1,0,w.kind==="space"?c-k:c,w.kind),o+=1}if(!f)return null;let v=d>0&&t[d-1]?.kind==="soft-hyphen";return{text:Bt(t,a,u,d,l,v),width:c+(v?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}}function Na(t,e,n=0){let r=[t];for(let o=0;o<e.length;o++){let s=e[o],i=[];for(let a=0;a<r.length;a++){let u=r[a];if(s.right<=u.left||s.left>=u.right){i.push(u);continue}s.left>u.left&&i.push({left:u.left,right:s.left}),s.right<u.right&&i.push({left:s.right,right:u.right})}r=i}return n>0?r.filter(o=>o.right-o.left>=n):r}function Ss(t,e,n){let r=[],o=new Intl.Segmenter(void 0,{granularity:"grapheme"});for(let s=0;s<t.lines.length;s++){let i=t.lines[s],a=s*n,u=0;for(let c=i.startSegment;c<e.length;c++){let d=e[c];if(d.kind==="soft-hyphen"||d.kind==="hard-break"){if(c>=i.endSegment&&i.endGrapheme===0)break;continue}let l=[...o.segment(d.text)].map(m=>m.segment);if(l.length===0)continue;let f=c===i.startSegment?i.startGrapheme:0,p;if(c<i.endSegment)p=l.length;else if(c===i.endSegment&&i.endGrapheme>0)p=i.endGrapheme;else break;for(let m=f;m<p;m++){let h=d.graphemeWidths?d.graphemeWidths[m]:d.width/l.length;r.push({x:u,y:a,width:h,height:n,line:s}),u+=h}}}return r}function Fh(t){let{adapter:e,name:n="reactive-layout"}=t,r=new z(n),o=new Map,s=N(t.text??"",{name:"text"}),i=N(t.font??"16px sans-serif",{name:"font"}),a=N(t.lineHeight??20,{name:"line-height"}),u=N(Math.max(0,t.maxWidth??800),{name:"max-width"});function c(m,h){if(m===null||h===null)return m===h;if(m.length!==h.length)return!1;for(let g=0;g<m.length;g++)if(m[g]!==h[g])return!1;return!0}let d=q([s,i],(m,h,g)=>{let y=m[0],b=y!=null&&y.length>0?y.at(-1):g.prevData[0],v=m[1],T=v!=null&&v.length>0?v.at(-1):g.prevData[1],w=B(),k={hits:0,misses:0},x=_t(b,T,e,o,k),S=B()-w,_=k.hits+k.misses,F=_===0?1:k.hits/_,L=d.meta;L&&(at(L["cache-hit-rate"],F),at(L["segment-count"],x.length),at(L["layout-time-ns"],S)),h.emit(x);let D=()=>{o.clear(),e.clearCache?.()};return{deactivate:D,invalidate:D}},{name:"segments",describeKind:"derived",meta:{"cache-hit-rate":0,"segment-count":0,"layout-time-ns":0},equals:(m,h)=>{let g=m,y=h;if(g==null||y==null)return g===y;if(g.length!==y.length)return!1;for(let b=0;b<g.length;b++){let v=g[b],T=y[b];if(v.text!==T.text||v.width!==T.width||v.kind!==T.kind||!c(v.graphemeWidths??null,T.graphemeWidths??null))return!1}return!0}}),l=A([d,u,i],([m,h,g])=>gn(m,h,e,g,o),{name:"line-breaks",equals:(m,h)=>{let g=m,y=h;if(g==null||y==null)return g===y;if(g.lineCount!==y.lineCount)return!1;for(let b=0;b<g.lines.length;b++){let v=g.lines[b],T=y.lines[b];if(v.text!==T.text||v.width!==T.width||v.startSegment!==T.startSegment||v.startGrapheme!==T.startGrapheme||v.endSegment!==T.endSegment||v.endGrapheme!==T.endGrapheme)return!1}return!0}}),f=A([l,a],([m,h])=>m.lineCount*h,{name:"height"}),p=A([l,d,a],([m,h,g])=>Ss(m,h,g),{name:"char-positions",equals:(m,h)=>{let g=m,y=h;if(g==null||y==null)return g===y;if(g.length!==y.length)return!1;for(let b=0;b<g.length;b++)if(g[b].x!==y[b].x||g[b].y!==y[b].y||g[b].width!==y[b].width)return!1;return!0}});return r.add(s,{name:"text"}),r.add(i,{name:"font"}),r.add(a,{name:"line-height"}),r.add(u,{name:"max-width"}),r.add(d,{name:"segments"}),r.add(l,{name:"line-breaks"}),r.add(f,{name:"height"}),r.add(p,{name:"char-positions"}),{graph:r,setText:m=>r.set("text",m),setFont:m=>r.set("font",m),setLineHeight:m=>r.set("line-height",m),setMaxWidth:m=>r.set("max-width",Math.max(0,m)),segments:d,lineBreaks:l,height:f,charPositions:p}}function jr(t){return Math.max(0,Math.min(1,t))}function $h(t){let e=jr(t?.mainRatio??.65),n=jr(t?.sideSplit??.5),r=Math.max(0,t?.viewportWidth??1280),o=t?.nodeRegistry??new Map,s=t?.adapter??null,i=t?.layoutFont??"14px monospace",a=t?.onHighlight,u=new z("demo-shell"),c=N(e,{name:"pane/main-ratio"}),d=N(n,{name:"pane/side-split"}),l=N(null,{name:"pane/fullscreen"}),f=N(r,{name:"viewport/width"});u.add(c,{name:"pane/main-ratio"}),u.add(d,{name:"pane/side-split"}),u.add(l,{name:"pane/fullscreen"}),u.add(f,{name:"viewport/width"});let p=A([c,f,l],([E,I,G])=>{let te=E,U=I,ce=G;return ce==="main"?U:ce==="graph"||ce==="code"?0:Math.round(U*te)},{name:"pane/main-width"}),m=A([p,f,l],([E,I,G])=>{let te=G,U=I;return te==="main"?0:te==="graph"||te==="code"?U:U-E},{name:"pane/side-width"}),h=A([d,l],([E,I])=>{let G=I;return G==="graph"?1:G==="code"||G==="main"?0:jr(E)},{name:"pane/graph-height-ratio"}),g=A([h,l],([E,I])=>{let G=I;return G==="code"?1:G==="graph"||G==="main"?0:1-E},{name:"pane/code-height-ratio"});u.add(p,{name:"pane/main-width"}),u.add(m,{name:"pane/side-width"}),u.add(h,{name:"pane/graph-height-ratio"}),u.add(g,{name:"pane/code-height-ratio"});let y=N(null,{name:"demo/graph-ref"}),b=N(0,{name:"demo/graph-tick"});u.add(y,{name:"demo/graph-ref"}),u.add(b,{name:"demo/graph-tick"});let v=A([y,b],([E,I])=>{let G=E;return G?G.describe({format:"mermaid"}):""},{name:"graph/mermaid"}),T=A([y,b],([E,I])=>{let G=E;if(!G)return null;let{expand:te,...U}=G.describe({detail:"standard"});return U},{name:"graph/describe"});u.add(v,{name:"graph/mermaid"}),u.add(T,{name:"graph/describe"});let w=N(null,{name:"hover/target"});u.add(w,{name:"hover/target"});let k=A([w],([E])=>{let I=E;if(!I)return null;let G=o.get(I.id);return G?G.codeLine:null},{name:"highlight/code-scroll"}),x=A([w],([E])=>{let I=E;if(!I)return null;let G=o.get(I.id);return G?G.visualSelector:null},{name:"highlight/visual"}),S=A([w],([E])=>{let I=E;return I?I.id:null},{name:"highlight/graph"});if(u.add(k,{name:"highlight/code-scroll"}),u.add(x,{name:"highlight/visual"}),u.add(S,{name:"highlight/graph"}),a?.codeScroll){let E=a.codeScroll,I=fe([k],([G])=>{E(G)});u.add(I,{name:"highlight/apply-code-scroll"})}if(a?.visual){let E=a.visual,I=fe([x],([G])=>{E(G)});u.add(I,{name:"highlight/apply-visual"})}if(a?.graph){let E=a.graph,I=fe([S],([G])=>{E(G)});u.add(I,{name:"highlight/apply-graph"})}let _=N(null,{name:"inspect/selected-node"});u.add(_,{name:"inspect/selected-node"});let F=Tt("standard"),L=A([_,y,b],([E,I,G])=>{let te=I,U=E;if(!te||!U)return null;try{let ce=te.resolve(U),j=gr(ce,F);return{path:U,...j,value:ce.cache}}catch{return null}},{name:"inspect/node-detail"}),D=A([y,b],([E,I])=>{let G=E;return G?G.trace():[]},{name:"inspect/trace-log"});u.add(L,{name:"inspect/node-detail"}),u.add(D,{name:"inspect/trace-log"});let C=N(!1,{name:"meta/debug"});u.add(C,{name:"meta/debug"});let K=A([C,b],([E,I])=>E?u.describe({format:"mermaid"}):"",{name:"meta/shell-mermaid"});u.add(K,{name:"meta/shell-mermaid"});let ne=N("",{name:"layout/code-text"});if(u.add(ne,{name:"layout/code-text"}),s){let E=new Map,I=A([T],([U])=>{let ce=U;if(!ce)return new Map;let j=new Map;for(let[V]of Object.entries(ce.nodes)){let J=_t(V,i,s,E),Y=gn(J,1/0,s,i,E),Q=Y.lines.reduce((ae,ye)=>Math.max(ae,ye.width),0),W=Y.lineCount*20;j.set(V,{width:Q,height:W})}return j},{name:"layout/graph-labels",equals:(U,ce)=>{if(U===ce)return!0;let j=U,V=ce;if(j.size!==V.size)return!1;for(let[J,Y]of j){let Q=V.get(J);if(!Q||Q.width!==Y.width||Q.height!==Y.height)return!1}return!0}}),G=A([ne,m],([U,ce])=>{let j=U;if(!j)return{lineCount:0,lines:[]};let V=_t(j,i,s,E),J=ce-40;return gn(V,Math.max(100,J),s,i,E)},{name:"layout/code-lines"}),te=A([I],([U])=>{let ce=U;if(ce.size===0)return 200;let j=0;for(let{width:V}of ce.values())V>j&&(j=V);return Math.max(200,Math.round(j+80))},{name:"layout/side-width-hint"});u.add(I,{name:"layout/graph-labels"}),u.add(G,{name:"layout/code-lines"}),u.add(te,{name:"layout/side-width-hint"})}let P=0;return{graph:u,setMainRatio(E){u.set("pane/main-ratio",jr(E))},setSideSplit(E){u.set("pane/side-split",jr(E))},setFullscreen(E){u.set("pane/fullscreen",E)},setViewportWidth(E){u.set("viewport/width",Math.max(0,E))},setHoverTarget(E){u.set("hover/target",E)},setDemoGraph(E){u.set("demo/graph-ref",E)},bumpGraphTick(){u.set("demo/graph-tick",++P)},selectNode(E){u.set("inspect/selected-node",E)},setMetaDebug(E){u.set("meta/debug",E)},setCodeText(E){u.set("layout/code-text",E)},batch(E){ee(E)},destroy(){u.destroy()}}}var Ms={};he(Ms,{contentModerationGraph:()=>qh,dataQualityGraph:()=>Hh,issueTrackerGraph:()=>Vh,observabilityGraph:()=>Kh});Se();le();var _s={};he(_s,{budgetGate:()=>Ea,effectivenessTracker:()=>jh,feedback:()=>jt,funnel:()=>Bh,scorer:()=>Kr});Se();ie();we();le();function Es(t,e){return Ke("reduction",t,e)}function Bh(t,e,n,r){if(e.length===0)throw new RangeError("funnel requires at least one source");if(n.length===0)throw new RangeError("funnel requires at least one stage");let o=new z(t,r),s=e.length===1?e[0]:ft(...e);o.add(s,{name:"merged"});let i="merged";for(let a=0;a<n.length;a++){let u=n[a],c=new z(u.name);u.build(c);try{c.resolve("input")}catch{throw new Error(`funnel stage "${u.name}" must define an "input" node`)}try{c.resolve("output")}catch{throw new Error(`funnel stage "${u.name}" must define an "output" node`)}o.mount(u.name,c);let d=o.resolve(i),l=`${u.name}::input`,f=o.resolve(l),p=`__bridge_${i}\u2192${u.name}_input`,m=fe([d],([h])=>{f.emit(h)},{name:p});o.add(m,{name:p}),o.addDisposer(oe(m)),i=`${u.name}::output`}return o}function jt(t,e,n,r){let o=r?.maxIterations??10,s=`__feedback_${e}`,i=N(0,{meta:Es("feedback_counter",{maxIterations:o,feedbackFrom:e,feedbackTo:n})});t.add(i,{name:s});let a=t.resolve(e),u=t.resolve(n),c=`__feedback_effect_${e}`,d=q([],(l,f)=>{let p=a.subscribe(m=>{for(let h of m){let g=h[0];if(g===R){let y=h[1];if(y==null)return;ee(()=>{Tr(i,o)&&u.emit(y)})}else if(g===M||g===O){let y=g===O&&h.length>1?[O,h[1]]:[g];i.down([y])}}});return()=>p()},{name:c,describeKind:"effect",meta:{...Es("feedback_effect",{feedbackFrom:e,feedbackTo:n}),_internal:!0}});return t.add(d,{name:c}),t.addDisposer(oe(d)),t}function Ea(t,e,n){if(e.length===0)throw new RangeError("budgetGate requires at least one constraint");let r=e.map(p=>p.node),o=[t,...r],s=[],i=!1,a=!1,u=Symbol("budget-gate"),c=new Array(e.length);function d(){return e.every((p,m)=>p.check(c[m]))}function l(p){for(;s.length>0&&d();){let m=s[0];s=s.slice(1),p.emit(m)}s.length===0&&a&&(a=!1,p.down([[$]]))}return q([],(p,m)=>{for(let g=0;g<e.length;g++)c[g]=e[g].node.cache;let h=[];for(let g=0;g<o.length;g++){let y=o[g];h.push(y.subscribe(b=>{for(let v of b)f(v,g,m)}))}return()=>{for(let g of h)g()}},{...n,describeKind:"derived",meta:Es("budget_gate",n?.meta)});function f(p,m,h){let g=p[0];if(m===0){if(g===R)return d()&&s.length===0?h.emit(p[1]):(s.push(p[1]),i||(i=!0,h.up([[Ae,u]]))),!0;if(g===Z)return h.down([[Z]]),!0;if(g===$)return s.length===0?h.down([[$]]):a=!0,!0;if(g===M||g===O){for(let y of s)h.emit(y);return s=[],a=!1,i&&(i=!1,h.up([[Pe,u]])),h.down([p]),!0}return!1}return g===R&&(c[m-1]=p[1]),g===R||g===$?(d()&&s.length>0?(l(h),s.length===0&&i&&(i=!1,h.up([[Pe,u]]))):!d()&&!i&&s.length>0&&(i=!0,h.up([[Ae,u]])),!0):g===Z?!0:g===O?(h.down([p]),!0):g===M}}function Kr(t,e,n){if(t.length===0)throw new RangeError("scorer requires at least one source");if(t.length!==e.length)throw new RangeError("scorer requires the same number of sources and weights");let r=[...t,...e],o=t.length,s=n?.scoreFns;return A(r,i=>{let a=i.slice(0,o),u=i.slice(o),c=[],d=0;for(let l=0;l<o;l++){let f=a[l]??0,p=u[l]??0,h=(s?.[l]?s[l](f):f)*p;c.push(h),d+=h}return{value:a,score:d,breakdown:c}},{...n?{equals:n.equals,resubscribable:n.resubscribable,resetOnTeardown:n.resetOnTeardown}:{},describeKind:"derived",meta:Es("scorer",n?.meta)})}function jh(t){let e=tt({name:t?.name??"effectiveness-entries"}),n=A([e.entries],([i])=>new Map(i),{name:`${t?.name??"effectiveness"}-snapshot`,equals:(i,a)=>{let u=i,c=a;if(u.size!==c.size)return!1;for(let[d,l]of u){let f=c.get(d);if(!f||l.attempts!==f.attempts||l.successes!==f.successes)return!1}return!0}});function r(i,a){let u=e.get(i),c=(u?.attempts??0)+1,d=(u?.successes??0)+(a?1:0);e.set(i,{key:i,attempts:c,successes:d,successRate:d/c})}function o(i){return e.get(i)}let s=oe(n);return{node:n,record:r,lookup:o,dispose:()=>s()}}function Ne(t,e){return Ke("domain_template",t,e)}function Kh(t,e){let n=new z(t,e);n.add(e.source,{name:"source"});let r=[{name:"errors",classify:T=>_a(T,"error")},{name:"traces",classify:T=>_a(T,"trace")},{name:"metrics",classify:T=>_a(T,"metric")}],o=e.branches??r,s=o.map(T=>({name:T.name,classify:T.classify})),i=Ir("stratify",e.source,s);n.mount("stratify",i);let a=o.map(T=>{try{let w=n.resolve(`stratify::branch/${T.name}`);return A([w],([k])=>k,{initial:null})}catch{return N(null)}}),u=e.correlate??(T=>T),c=A(a,T=>u(T),{meta:Ne("observability",{stage:"correlate"})});n.add(c,{name:"correlate"});let d=e.sloCheck??(()=>({pass:!0})),l=A([c],T=>T[0],{meta:Ne("observability",{stage:"slo_value"})}),f=A([l],T=>d(T[0]),{meta:Ne("observability",{stage:"slo_verified"})});n.add(l,{name:"slo_value"}),n.add(f,{name:"slo_verified"});let p=e.weights??o.map(()=>1),m=a.map(T=>A([T],w=>w[0]!=null?1:0)),h=p.map(T=>N(T));for(let T=0;T<m.length;T++)n.add(m[T],{name:`__signal_${T}`}),n.add(h[T],{name:`__weight_${T}`});let g=Kr(m,h);n.add(g,{name:"alerts"});let y=A([g,f],T=>({scored:T[0],slo:T[1]}),{meta:Ne("observability",{stage:"output"})});n.add(y,{name:"output"});let b=N(null,{meta:Ne("observability",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=A([f],T=>{let w=T[0];return w&&w.pass===!1?w:null},{meta:Ne("observability",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),jt(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??5}),n}function Vh(t,e){let n=new z(t,e);n.add(e.source,{name:"source"});let r=0,o=T=>({id:`issue-${++r}`,title:String(T),severity:1,source:"unknown",raw:T}),s=e.extract??o,i=A([e.source],T=>s(T[0]),{meta:Ne("issue_tracker",{stage:"extract"})});n.add(i,{name:"extract"});let a=e.verify??(()=>({valid:!0})),u=A([i],T=>{let w=T[0];return{issue:w,verification:a(w)}},{meta:Ne("issue_tracker",{stage:"verify"})});n.add(u,{name:"verify"});let c=N([],{meta:Ne("issue_tracker",{stage:"known_patterns"})});n.add(c,{name:"known_patterns"});let d=e.detectRegression??(()=>({regression:!1})),l=A([i,c],T=>{let w=T[0],k=T[1];return{issue:w,regression:d(w,k)}},{meta:Ne("issue_tracker",{stage:"regression"})});n.add(l,{name:"regression"});let f=A([i],T=>T[0]?.severity??0),p=A([l],T=>T[0]?.regression?2:0);n.add(f,{name:"__severity_signal"}),n.add(p,{name:"__regression_signal"});let m=N(1),h=N(1.5);n.add(m,{name:"__severity_weight"}),n.add(h,{name:"__regression_weight"});let g=Kr([f,p],[m,h]);n.add(g,{name:"priority"});let y=A([u,l,g],T=>({verified:T[0],regression:T[1],priority:T[2]}),{meta:Ne("issue_tracker",{stage:"output"})});n.add(y,{name:"output"});let b=N(null,{meta:Ne("issue_tracker",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=A([u],T=>{let w=T[0];if(w){let k=w.verification;if(k&&k.valid===!1)return w}return null},{meta:Ne("issue_tracker",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),jt(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??3}),n}function qh(t,e){let n=new z(t,e);n.add(e.source,{name:"source"});let r=v=>({label:"review",confidence:.5,original:v}),o=e.classify??r,s=A([e.source],v=>o(v[0]),{meta:Ne("content_moderation",{stage:"classify"})});n.add(s,{name:"classify"});let i=Ir("stratify",s,[{name:"safe",classify:v=>v.label==="safe"},{name:"review",classify:v=>v.label==="review"},{name:"block",classify:v=>v.label==="block"}]);n.mount("stratify",i);let a=je([],{name:"review_queue",maxSize:e.maxQueueSize});n.add(a.entries,{name:"review_queue"});let u;try{u=n.resolve("stratify::branch/review")}catch{u=N(null),n.add(u,{name:"__review_fallback"})}let c=fe([u],v=>{let T=v[0];T&&a.append(T)});n.add(c,{name:"__review_accumulator"}),n.addDisposer(oe(c));let d=N({},{meta:Ne("content_moderation",{stage:"policy",access:"both",description:"Moderation policy rules \u2014 updated via feedback"})});n.add(d,{name:"policy"});let l=e.weights??[.1,1,2],f=A([s],v=>v[0]?.confidence??0),p=A([s],v=>{let T=v[0];return T?T.label==="block"?l[2]:T.label==="review"?l[1]:l[0]:0});n.add(f,{name:"__confidence_signal"}),n.add(p,{name:"__severity_signal"});let m=N(1),h=N(1);n.add(m,{name:"__w_confidence"}),n.add(h,{name:"__w_severity"});let g=Kr([f,p],[m,h]);n.add(g,{name:"priority"});let y=A([s,g],v=>({classification:v[0],priority:v[1]}),{meta:Ne("content_moderation",{stage:"output"})});n.add(y,{name:"output"});let b=A([a.entries,d],v=>{let T=v[0];if(T&&T.length>0){let w=T[T.length-1];if(w&&w.falsePositive)return w}return null},{meta:Ne("content_moderation",{stage:"feedback_condition"})});return n.add(b,{name:"feedback_condition"}),jt(n,"feedback_condition","policy",{maxIterations:e.maxFeedbackIterations??5}),n}function Hh(t,e){let n=new z(t,e);n.add(e.source,{name:"source"});let r=e.validate??(g=>({valid:!0,errors:[],record:g})),o=A([e.source],g=>g[0]!=null?r(g[0]):void 0,{meta:Ne("data_quality",{stage:"validate"})});n.add(o,{name:"validate"});let s=e.detectAnomaly??(g=>({anomaly:!1,score:0,record:g})),i=A([e.source],g=>g[0]!=null?s(g[0]):void 0,{meta:Ne("data_quality",{stage:"anomaly"})});n.add(i,{name:"anomaly"});let a=N(null,{meta:Ne("data_quality",{stage:"baseline",description:"Rolling baseline for drift detection"})});n.add(a,{name:"baseline"});let u=fe([o],g=>{let y=g[0];y?.valid&&ee(()=>{a.emit(y.record)})});n.add(u,{name:"__baseline_updater"}),oe(u);let c=e.detectDrift??(()=>({drift:!1})),d=A([e.source,a],g=>c(g[0],g[1]),{meta:Ne("data_quality",{stage:"drift"})});n.add(d,{name:"drift"});let l=e.suggest??(()=>null),f=A([o,i],g=>l({validation:g[0],anomaly:g[1]}),{meta:Ne("data_quality",{stage:"remediate"})});n.add(f,{name:"remediate"});let p=A([o,i,d,f],g=>({validation:g[0],anomaly:g[1],drift:g[2],remediation:g[3]}),{meta:Ne("data_quality",{stage:"output"})});n.add(p,{name:"output"});let m=N([],{meta:Ne("data_quality",{stage:"validation_rules"})});n.add(m,{name:"validation_rules"});let h=A([i],g=>{let y=g[0];return y?.anomaly?y:null},{meta:Ne("data_quality",{stage:"feedback_condition"})});return n.add(h,{name:"feedback_condition"}),jt(n,"feedback_condition","validation_rules",{maxIterations:e.maxFeedbackIterations??3}),n}function _a(t,e){if(t==null||typeof t!="object")return!1;let n=t;return n.type===e||n.kind===e}var Os={};he(Os,{compileSpec:()=>Ca,decompileGraph:()=>Qh,extractFnFactory:()=>Fl,extractSourceFactory:()=>$l,generateCatalogPrompt:()=>Bl,isRichFnEntry:()=>Vr,isRichSourceEntry:()=>Oa,llmCompose:()=>Zh,llmRefine:()=>Vl,specDiff:()=>Xh,validateSpec:()=>Un,validateSpecAgainstCatalog:()=>qr});le();function Vr(t){return typeof t=="object"&&t!==null&&"factory"in t}function Oa(t){return typeof t=="object"&&t!==null&&"factory"in t}function Fl(t){return Vr(t)?t.factory:t}function $l(t){return Oa(t)?t.factory:t}function Bl(t){let e=[];if(t.fns){let n=new Map;for(let[r,o]of Object.entries(t.fns)){let s=Vr(o)?o.tags?.[0]??"Other":"Other";n.has(s)||n.set(s,[]),n.get(s).push(Wh(r,o))}for(let[r,o]of n)e.push(`${r}:
117
+ - Return ONLY valid JSON, no markdown fences or commentary.`;async function pg(t,e,n,r){let{expand:o,...s}=t.describe({actor:r?.actor,detail:"standard"}),i=[{role:"system",content:lg},{role:"user",content:JSON.stringify({graph:s,problem:e})}],a=n.invoke(i,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens}),c=(await gn(a)).content.trim();c.startsWith("```")&&(c=c.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let d;try{d=JSON.parse(c)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${c.slice(0,200)}`)}let l=d;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}}var _s={};he(_s,{AuditTrailGraph:()=>Ns,PolicyEnforcerGraph:()=>Es,auditTrail:()=>mg,complianceSnapshot:()=>hg,policyEnforcer:()=>Aa,reactiveExplainPath:()=>La});ke();Qt();ie();xe();oe();oo();function Xl(t,e){return Ke("audit",t,e)}var fg=new Set(["data","error","complete","teardown"]),Ns=class extends q{entries;count;_log;_target;constructor(e,n){super(n.name??`${e.name}_audit`,n.graph),this._target=e,this._log=Ve([],{name:"entries",...n.maxSize!=null?{maxSize:n.maxSize}:{}}),this.entries=this._log.entries,this.add(this.entries,{name:"entries"}),this.count=O([this.entries],([u])=>u.length,{name:"count",describeKind:"derived",meta:Xl("count")}),this.add(this.count,{name:"count"}),this.addDisposer(se(this.count));let r=n.includeTypes!=null?new Set(n.includeTypes):fg,o=n.filter,s=0,i=e.observe({timeline:!0,structured:!0}),a=i.onEvent(u=>{if(u.type==="derived")return;let c=u.type;if(!r.has(c))return;let d=u.path??"",l={seq:s++,timestamp_ns:u.timestamp_ns??$(),wall_clock_ns:pe(),path:d,type:c},p=(d?Ca(e,d):void 0)?.lastMutation;p!=null&&(l.actor=p.actor),c==="data"&&(l.value=u.data),c==="error"&&(l.error=u.data);let m=d?yg(e,d):void 0;m!=null&&(l.annotation=m),!(o!=null&&!o(l))&&this._log.append(l)});this.addDisposer(()=>{a(),i.dispose()}),this.addDisposer(()=>this._log.disposeAllViews())}all(){return this.entries.cache??[]}byNode(e){return this.all().filter(n=>n.path===e)}byActor(e){return this.all().filter(n=>n.actor?.id===e)}byActorType(e){return this.all().filter(n=>n.actor?.type===e)}byTimeRange(e,n){return this.all().filter(r=>!(r.timestamp_ns<e||n!=null&&r.timestamp_ns>=n))}get target(){return this._target}};function mg(t,e={}){return new Ns(t,e)}var Es=class extends q{policies;violations;violationCount;_target;_mode;_currentGuard;constructor(e,n,r){super(r.name??`${e.name}_policy`,r.graph),this._target=e,this._mode=r.mode??"audit";let o=gg(n)?n:N(n,{name:"policies"});this.policies=o,this.add(this.policies,{name:"policies"}),this.violations=new nt("violations",{retainedLimit:r.violationsLimit??1e3}),this.mount("violations",this.violations),this.violationCount=O([this.violations.events],([c])=>c.length,{name:"violationCount",describeKind:"derived",meta:Xl("policy_violation_count")}),this.add(this.violationCount,{name:"violationCount"}),this.addDisposer(se(this.violationCount));let i=o.cache??[];this._currentGuard=fr(i);let a=o.subscribe(c=>{for(let d of c)d[0]===S&&(i=d[1]??[],this._currentGuard=fr(i))});this.addDisposer(a);let u=r.paths!=null?[...r.paths]:Ql(e);if(this._mode==="enforce"){let c=new Map,d=l=>{if(c.has(l))return;let f=Ca(e,l);if(!(f instanceof Ee))return;let p=(m,h)=>{let g=this._currentGuard(m,h);return g||this._publishViolation(m,h,l,"blocked"),g};c.set(l,f._pushGuard(p))};for(let l of u)d(l);if(r.paths==null){let l=kt(e,(f,p,m)=>{if(f.kind==="added")if(f.nodeKind==="node")d(`${m}${f.name}`);else{let h=p._mounts.get(f.name);if(!(h instanceof q))return;let g=`${m}${f.name}::`,y=Ql(h);for(let b of y)d(b===""?`${m}${f.name}`:`${g}${b}`)}else if(f.kind==="removed")if(f.nodeKind==="node"){let h=`${m}${f.name}`,g=c.get(h);g!=null&&(g(),c.delete(h))}else{let h=`${m}${f.name}`,g=`${h}::`;for(let[y,b]of c)(y===h||y.startsWith(g))&&(b(),c.delete(y))}});this.addDisposer(l)}else{let l=e.topology.subscribe(f=>{for(let p of f){if(p[0]!==S)continue;let m=p[1];if(m.kind!=="removed"||m.nodeKind!=="node")continue;let h=c.get(m.name);h!=null&&(h(),c.delete(m.name))}});this.addDisposer(l)}this.addDisposer(()=>{for(let l of c.values())l();c.clear()})}else{let c=e.observe({timeline:!0,structured:!0}),d=c.onEvent(l=>{if(l.type!=="data"&&l.type!=="error")return;let f=l.path??"";if(!f||r.paths!=null&&!r.paths.includes(f))return;let p=l.actor??Ca(e,f)?.lastMutation?.actor;if(p==null)return;let m="write";this._currentGuard(p,m)||this._publishViolation(p,m,f,"observed")});this.addDisposer(()=>{d(),c.dispose()})}}_publishViolation(e,n,r,o){this.violations.publish({timestamp_ns:$(),wall_clock_ns:pe(),path:r,actor:e,action:n,mode:this._mode,result:o})}all(){return this.violations.retained()}get mode(){return this._mode}get target(){return this._target}};function Aa(t,e,n={}){return new Es(t,e,n)}function La(t,e,n,r){return t.explain(e,n,{reactive:!0,...r})}function hg(t,e={}){let n={format_version:1,timestamp_ns:$(),wall_clock_ns:pe(),graph:t.snapshot()};if(e.actor!=null&&(n.actor=e.actor),e.audit!=null){let o=[...e.audit.all()];n.audit={count:o.length,entries:o}}if(e.policies!=null){let o=e.policies.policies.cache??[];n.policies={mode:e.policies.mode,rules:o,violations:[...e.policies.all()]}}let r=bg(n);return{...n,fingerprint:r}}function gg(t){return typeof t=="object"&&t!==null&&"subscribe"in t}function Ca(t,e){try{return t.node(e)}catch{return}}function yg(t,e){try{return t.annotation(e)}catch{return}}function Ql(t){let e=t.describe({detail:"minimal"});return Object.keys(e.nodes)}function bg(t){return Ot(JSON.stringify(vg(t)))}function vg(t){let e=new Set,n=r=>{if(r===void 0)return{__undefined:!0};if(r===null)return null;let o=typeof r;if(o==="bigint")return{__bigint:r.toString()};if(o!=="object")return r;let s=r;if(e.has(s))return{__circular:!0};e.add(s);try{if(Array.isArray(s))return s.map(n);if(s instanceof Date)return{__date:s.toISOString()};if(s instanceof RegExp)return{__regexp:{source:s.source,flags:s.flags}};if(s instanceof Map)return{__map:[...s.entries()].map(([u,c])=>[n(u),n(c)])};if(s instanceof Set)return{__set:[...s].map(n)};if(ArrayBuffer.isView(s)){let a=s,u=new Array(a.length);for(let c=0;c<a.length;c++)u[c]=a[c]??0;return{__typed_array:{ctor:s.constructor.name,data:u}}}let i={};for(let a of Object.keys(s).sort())i[a]=n(s[a]);return i}finally{e.delete(s)}};return n(t)}var Os={};he(Os,{demoShell:()=>Eg});Ne();oe();ke();xe();oe();function Tg(t){for(let e of t){let n=e.codePointAt(0);if(n>=19968&&n<=40959||n>=13312&&n<=19903||n>=12288&&n<=12351||n>=12352&&n<=12447||n>=12448&&n<=12543||n>=44032&&n<=55215||n>=65280&&n<=65519)return!0}return!1}var Zl=new Set(["\uFF0C","\uFF0E","\uFF01","\uFF1A","\uFF1B","\uFF1F","\u3001","\u3002","\u30FB","\uFF09","\u3015","\u3009","\u300B","\u300D","\u300F","\u3011"]),wg=new Set([".",",","!","?",":",";",")","]","}","%",'"',"\u201D","\u2019","\xBB","\u203A","\u2026"]);function kg(t){return t.replace(/[\t\n\r\f ]+/g," ").replace(/^ | $/g,"")}function xg(t){let e=new Intl.Segmenter(void 0,{granularity:"word"}),n=[];for(let r of e.segment(t)){let o=r.segment,s=r.isWordLike??!1,i=[],a=[],u=[],c="",d=null;for(let l of o){let f;l===" "?f="space":l==="\u200B"?f="zero-width-break":l==="\xAD"?f="soft-hyphen":l===`
118
+ `?f="hard-break":f="text",d!==null&&f===d?c+=l:(d!==null&&(i.push(c),a.push(d==="text"&&s),u.push(d)),c=l,d=f)}d!==null&&(i.push(c),a.push(d==="text"&&s),u.push(d)),n.push({texts:i,isWordLike:a,kinds:u})}return n}function Mt(t,e,n,r,o){let s=kg(t);if(s.length===0)return[];let i=xg(s),a=new Intl.Segmenter(void 0,{granularity:"grapheme"}),u=[],c=[],d=[];for(let y of i)for(let b=0;b<y.texts.length;b++)u.push(y.texts[b]),c.push(y.kinds[b]),d.push(y.isWordLike[b]);let l=[],f=[],p=[];for(let y=0;y<u.length;y++){let b=u[y],v=c[y],T=d[y];if(v==="text"&&!T&&l.length>0&&f[f.length-1]==="text"&&b.length===1&&(wg.has(b)||Zl.has(b))){l[l.length-1]+=b;continue}if(b==="-"&&l.length>0&&f[f.length-1]==="text"&&p[p.length-1]){l[l.length-1]+=b;continue}l.push(b),f.push(v),p.push(T)}let m=r.get(e);m||(m=new Map,r.set(e,m));function h(y){let b=m.get(y);if(b===void 0){o&&(o.misses+=1);let v=n.measureSegment(y,e).width;b=Number.isFinite(v)&&v>=0?v:0,m.set(y,b)}else o&&(o.hits+=1);return b}let g=[];for(let y=0;y<l.length;y++){let b=l[y],v=f[y];if(v!=="text"){g.push({text:b,width:v==="space"?h(" ")*b.length:0,kind:v,graphemeWidths:null});continue}if(Tg(b)){let k="";for(let x of a.segment(b)){let R=x.segment;if(k.length>0&&Zl.has(R)){k+=R;continue}if(k.length>0){let E=h(k);g.push({text:k,width:E,kind:"text",graphemeWidths:null})}k=R}if(k.length>0){let x=h(k);g.push({text:k,width:x,kind:"text",graphemeWidths:null})}continue}let T=h(b),w=null;if(p[y]&&b.length>1){let k=[];for(let x of a.segment(b))k.push(h(x.segment));k.length>1&&(w=k)}g.push({text:b,width:T,kind:"text",graphemeWidths:w})}return g}function Tn(t,e,n,r,o){if(t.length===0)return{lines:[],lineCount:0};let s=[],i=0,a=!1,u=0,c=0,d=0,l=0,f=-1,p=0,m=o.get(r);m||(m=new Map,o.set(r,m));let h=m.get("-");h===void 0&&(h=n.measureSegment("-",r).width,m.set("-",h));function g(w=d,k=l,x=i){let R="";for(let E=u;E<w;E++){let G=t[E];if(!(G.kind==="soft-hyphen"||G.kind==="hard-break"))if(E===u&&c>0&&G.graphemeWidths){let P=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(G.text)].map(C=>C.segment);R+=P.slice(c).join("")}else R+=G.text}if(k>0&&w<t.length){let E=t[w],L=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(E.text)].map(C=>C.segment),P=u===w?c:0;R+=L.slice(P,k).join("")}w>0&&t[w-1]?.kind==="soft-hyphen"&&!(u===w&&c>0)&&(R+="-"),s.push({text:R,width:x,startSegment:u,startGrapheme:c,endSegment:w,endGrapheme:k}),i=0,a=!1,f=-1,p=0}function y(w){return w==="space"||w==="zero-width-break"||w==="soft-hyphen"}function b(w,k,x){a=!0,u=w,c=k,d=w+1,l=0,i=x}function v(w,k,x){a=!0,u=w,c=k,d=w,l=k+1,i=x}for(let w=0;w<t.length;w++){let k=t[w];if(k.kind==="hard-break"){a?g():s.push({text:"",width:0,startSegment:w,startGrapheme:0,endSegment:w,endGrapheme:0}),u=w+1,c=0;continue}let x=k.width;if(!a){x>e&&k.graphemeWidths?T(w,0,k.graphemeWidths):b(w,0,x),y(k.kind)&&(f=w+1,p=k.kind==="space"?i-x:i);continue}let R=i+x;if(R>e+.005){if(y(k.kind)){i+=x,d=w+1,l=0,g(w+1,0,k.kind==="space"?i-x:i);continue}if(f>=0){g(f,0,p),w--;continue}if(x>e&&k.graphemeWidths){g(),T(w,0,k.graphemeWidths);continue}g(),w--;continue}i=R,d=w+1,l=0,y(k.kind)&&(f=w+1,p=k.kind==="space"?i-x:i)}return a&&g(),{lines:s,lineCount:s.length};function T(w,k,x){for(let R=k;R<x.length;R++){let E=x[R];if(!a){v(w,R,E);continue}i+E>e+.005?(g(),v(w,R,E)):(i+=E,d=w,l=R+1)}a&&d===w&&l===x.length&&(d=w+1,l=0)}}function Ia(t){return t==="space"||t==="zero-width-break"||t==="soft-hyphen"}var Pa=null;function Rg(){return Pa===null&&(Pa=new Intl.Segmenter(void 0,{granularity:"grapheme"})),Pa}function ep(t,e,n){if(e===0&&n<0)return t.text;let r=[...Rg().segment(t.text)].map(s=>s.segment),o=n<0?r.length:n;return r.slice(e,o).join("")}function Vt(t,e,n,r,o,s){let i="";for(let a=e;a<r;a++){let u=t[a];u.kind==="soft-hyphen"||u.kind==="hard-break"||(a===e&&n>0?i+=ep(u,n,-1):i+=u.text)}if(o>0&&r<t.length){let a=t[r];i+=ep(a,e===r?n:0,o)}return s&&(i+="-"),i}function Sg(t){if(!t?.adapter||!t.font)return 0;let e=t.cache;if(e){let n=e.get(t.font);n||(n=new Map,e.set(t.font,n));let r=n.get("-");return r===void 0&&(r=t.adapter.measureSegment("-",t.font).width,n.set("-",r)),r}return t.adapter.measureSegment("-",t.font).width}function Da(t,e,n,r){let o=e.segmentIndex,s=e.graphemeIndex;if(o>=t.length)return null;if(s===0){for(;o<t.length;){let w=t[o];if(w.kind==="hard-break")return{text:"",width:0,start:{segmentIndex:e.segmentIndex,graphemeIndex:0},end:{segmentIndex:o+1,graphemeIndex:0}};if(w.kind==="space"||w.kind==="zero-width-break"||w.kind==="soft-hyphen"){o+=1;continue}break}if(o>=t.length)return null}let i=Sg(r),a=o,u=o===e.segmentIndex?s:0,c=0,d=a,l=0,f=!1,p=-1,m=0,h=0,g=!1,y=(w,k,x,R)=>{p=w,m=k,h=x,g=R==="soft-hyphen"},b=(w,k,x)=>{for(let R=k;R<x.length;R++){let E=x[R];if(!f){c=E,d=w,l=R+1,f=!0;continue}if(c+E>n+.005)return!0;c+=E,d=w,l=R+1}return d===w&&l===x.length&&(d=w+1,l=0),!1};if(u>0&&a<t.length){let w=t[a];if(w.graphemeWidths){if(b(a,u,w.graphemeWidths))return{text:Vt(t,a,u,d,l,!1),width:c,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}};o=d}}for(;o<t.length;){let w=t[o];if(w.kind==="hard-break"){if(f){let R=d>0&&t[d-1]?.kind==="soft-hyphen";return{text:Vt(t,a,u,d,l,R),width:c+(R?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}}return{text:"",width:0,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:o+1,graphemeIndex:0}}}let k=w.width;if(!f){if(k>n&&w.graphemeWidths){if(b(o,0,w.graphemeWidths))return{text:Vt(t,a,u,d,l,!1),width:c,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}};o=d;continue}c=k,d=o+1,l=0,f=!0,Ia(w.kind)&&y(o+1,0,w.kind==="space"?c-k:c,w.kind),o+=1;continue}let x=c+k;if(x>n+.005){if(Ia(w.kind)){d=o+1,l=0;let E=w.kind==="soft-hyphen",G=w.kind==="space"?c:c+(E?i:0);return{text:Vt(t,a,u,d,l,E),width:G,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}}return p>=0?{text:Vt(t,a,u,p,m,g),width:h+(g?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:p,graphemeIndex:m}}:k>n&&w.graphemeWidths?{text:Vt(t,a,u,d,l,!1),width:c,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}:{text:Vt(t,a,u,d,l,!1),width:c,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}}c=x,d=o+1,l=0,Ia(w.kind)&&y(o+1,0,w.kind==="space"?c-k:c,w.kind),o+=1}if(!f)return null;let v=d>0&&t[d-1]?.kind==="soft-hyphen";return{text:Vt(t,a,u,d,l,v),width:c+(v?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}}function Ga(t,e,n=0){let r=[t];for(let o=0;o<e.length;o++){let s=e[o],i=[];for(let a=0;a<r.length;a++){let u=r[a];if(s.right<=u.left||s.left>=u.right){i.push(u);continue}s.left>u.left&&i.push({left:u.left,right:s.left}),s.right<u.right&&i.push({left:s.right,right:u.right})}r=i}return n>0?r.filter(o=>o.right-o.left>=n):r}function Ms(t,e,n){let r=[],o=new Intl.Segmenter(void 0,{granularity:"grapheme"});for(let s=0;s<t.lines.length;s++){let i=t.lines[s],a=s*n,u=0;for(let c=i.startSegment;c<e.length;c++){let d=e[c];if(d.kind==="soft-hyphen"||d.kind==="hard-break"){if(c>=i.endSegment&&i.endGrapheme===0)break;continue}let l=[...o.segment(d.text)].map(m=>m.segment);if(l.length===0)continue;let f=c===i.startSegment?i.startGrapheme:0,p;if(c<i.endSegment)p=l.length;else if(c===i.endSegment&&i.endGrapheme>0)p=i.endGrapheme;else break;for(let m=f;m<p;m++){let h=d.graphemeWidths?d.graphemeWidths[m]:d.width/l.length;r.push({x:u,y:a,width:h,height:n,line:s}),u+=h}}}return r}function Ng(t){let{adapter:e,name:n="reactive-layout"}=t,r=new q(n),o=new Map,s=N(t.text??"",{name:"text"}),i=N(t.font??"16px sans-serif",{name:"font"}),a=N(t.lineHeight??20,{name:"line-height"}),u=N(Math.max(0,t.maxWidth??800),{name:"max-width"});function c(m,h){if(m===null||h===null)return m===h;if(m.length!==h.length)return!1;for(let g=0;g<m.length;g++)if(m[g]!==h[g])return!1;return!0}let d=K([s,i],(m,h,g)=>{let y=m[0],b=y!=null&&y.length>0?y.at(-1):g.prevData[0],v=m[1],T=v!=null&&v.length>0?v.at(-1):g.prevData[1],w=$(),k={hits:0,misses:0},x=Mt(b,T,e,o,k),R=$()-w,E=k.hits+k.misses,G=E===0?1:k.hits/E,L=d.meta;L&&(at(L["cache-hit-rate"],G),at(L["segment-count"],x.length),at(L["layout-time-ns"],R)),h.emit(x);let P=()=>{o.clear(),e.clearCache?.()};return{deactivate:P,invalidate:P}},{name:"segments",describeKind:"derived",meta:{"cache-hit-rate":0,"segment-count":0,"layout-time-ns":0},equals:(m,h)=>{let g=m,y=h;if(g==null||y==null)return g===y;if(g.length!==y.length)return!1;for(let b=0;b<g.length;b++){let v=g[b],T=y[b];if(v.text!==T.text||v.width!==T.width||v.kind!==T.kind||!c(v.graphemeWidths??null,T.graphemeWidths??null))return!1}return!0}}),l=O([d,u,i],([m,h,g])=>Tn(m,h,e,g,o),{name:"line-breaks",equals:(m,h)=>{let g=m,y=h;if(g==null||y==null)return g===y;if(g.lineCount!==y.lineCount)return!1;for(let b=0;b<g.lines.length;b++){let v=g.lines[b],T=y.lines[b];if(v.text!==T.text||v.width!==T.width||v.startSegment!==T.startSegment||v.startGrapheme!==T.startGrapheme||v.endSegment!==T.endSegment||v.endGrapheme!==T.endGrapheme)return!1}return!0}}),f=O([l,a],([m,h])=>m.lineCount*h,{name:"height"}),p=O([l,d,a],([m,h,g])=>Ms(m,h,g),{name:"char-positions",equals:(m,h)=>{let g=m,y=h;if(g==null||y==null)return g===y;if(g.length!==y.length)return!1;for(let b=0;b<g.length;b++)if(g[b].x!==y[b].x||g[b].y!==y[b].y||g[b].width!==y[b].width)return!1;return!0}});return r.add(s,{name:"text"}),r.add(i,{name:"font"}),r.add(a,{name:"line-height"}),r.add(u,{name:"max-width"}),r.add(d,{name:"segments"}),r.add(l,{name:"line-breaks"}),r.add(f,{name:"height"}),r.add(p,{name:"char-positions"}),{graph:r,setText:m=>r.set("text",m),setFont:m=>r.set("font",m),setLineHeight:m=>r.set("line-height",m),setMaxWidth:m=>r.set("max-width",Math.max(0,m)),segments:d,lineBreaks:l,height:f,charPositions:p}}function Wr(t){return Math.max(0,Math.min(1,t))}function Eg(t){let e=Wr(t?.mainRatio??.65),n=Wr(t?.sideSplit??.5),r=Math.max(0,t?.viewportWidth??1280),o=t?.nodeRegistry??new Map,s=t?.adapter??null,i=t?.layoutFont??"14px monospace",a=t?.onHighlight,u=new q("demo-shell"),c=N(e,{name:"pane/main-ratio"}),d=N(n,{name:"pane/side-split"}),l=N(null,{name:"pane/fullscreen"}),f=N(r,{name:"viewport/width"});u.add(c,{name:"pane/main-ratio"}),u.add(d,{name:"pane/side-split"}),u.add(l,{name:"pane/fullscreen"}),u.add(f,{name:"viewport/width"});let p=O([c,f,l],([A,D,I])=>{let Q=A,U=D,ae=I;return ae==="main"?U:ae==="graph"||ae==="code"?0:Math.round(U*Q)},{name:"pane/main-width"}),m=O([p,f,l],([A,D,I])=>{let Q=I,U=D;return Q==="main"?0:Q==="graph"||Q==="code"?U:U-A},{name:"pane/side-width"}),h=O([d,l],([A,D])=>{let I=D;return I==="graph"?1:I==="code"||I==="main"?0:Wr(A)},{name:"pane/graph-height-ratio"}),g=O([h,l],([A,D])=>{let I=D;return I==="code"?1:I==="graph"||I==="main"?0:1-A},{name:"pane/code-height-ratio"});u.add(p,{name:"pane/main-width"}),u.add(m,{name:"pane/side-width"}),u.add(h,{name:"pane/graph-height-ratio"}),u.add(g,{name:"pane/code-height-ratio"});let y=N(null,{name:"demo/graph-ref"}),b=N(0,{name:"demo/graph-tick"});u.add(y,{name:"demo/graph-ref"}),u.add(b,{name:"demo/graph-tick"});let v=O([y,b],([A,D])=>{let I=A;return I?I.describe({format:"mermaid"}):""},{name:"graph/mermaid"}),T=O([y,b],([A,D])=>{let I=A;if(!I)return null;let{expand:Q,...U}=I.describe({detail:"standard"});return U},{name:"graph/describe"});u.add(v,{name:"graph/mermaid"}),u.add(T,{name:"graph/describe"});let w=N(null,{name:"hover/target"});u.add(w,{name:"hover/target"});let k=O([w],([A])=>{let D=A;if(!D)return null;let I=o.get(D.id);return I?I.codeLine:null},{name:"highlight/code-scroll"}),x=O([w],([A])=>{let D=A;if(!D)return null;let I=o.get(D.id);return I?I.visualSelector:null},{name:"highlight/visual"}),R=O([w],([A])=>{let D=A;return D?D.id:null},{name:"highlight/graph"});if(u.add(k,{name:"highlight/code-scroll"}),u.add(x,{name:"highlight/visual"}),u.add(R,{name:"highlight/graph"}),a?.codeScroll){let A=a.codeScroll,D=fe([k],([I])=>{A(I)});u.add(D,{name:"highlight/apply-code-scroll"})}if(a?.visual){let A=a.visual,D=fe([x],([I])=>{A(I)});u.add(D,{name:"highlight/apply-visual"})}if(a?.graph){let A=a.graph,D=fe([R],([I])=>{A(I)});u.add(D,{name:"highlight/apply-graph"})}let E=N(null,{name:"inspect/selected-node"});u.add(E,{name:"inspect/selected-node"});let G=wt("standard"),L=O([E,y,b],([A,D,I])=>{let Q=D,U=A;if(!Q||!U)return null;try{let ae=Q.resolve(U),j=wr(ae,G);return{path:U,...j,value:ae.cache}}catch{return null}},{name:"inspect/node-detail"}),P=O([y,b],([A,D])=>{let I=A;return I?I.trace():[]},{name:"inspect/trace-log"});u.add(L,{name:"inspect/node-detail"}),u.add(P,{name:"inspect/trace-log"});let C=N(!1,{name:"meta/debug"});u.add(C,{name:"meta/debug"});let V=O([C,b],([A,D])=>A?u.describe({format:"mermaid"}):"",{name:"meta/shell-mermaid"});u.add(V,{name:"meta/shell-mermaid"});let ne=N("",{name:"layout/code-text"});if(u.add(ne,{name:"layout/code-text"}),s){let A=new Map,D=O([T],([U])=>{let ae=U;if(!ae)return new Map;let j=new Map;for(let[Y]of Object.entries(ae.nodes)){let J=Mt(Y,i,s,A),z=Tn(J,1/0,s,i,A),X=z.lines.reduce((le,ve)=>Math.max(le,ve.width),0),H=z.lineCount*20;j.set(Y,{width:X,height:H})}return j},{name:"layout/graph-labels",equals:(U,ae)=>{if(U===ae)return!0;let j=U,Y=ae;if(j.size!==Y.size)return!1;for(let[J,z]of j){let X=Y.get(J);if(!X||X.width!==z.width||X.height!==z.height)return!1}return!0}}),I=O([ne,m],([U,ae])=>{let j=U;if(!j)return{lineCount:0,lines:[]};let Y=Mt(j,i,s,A),J=ae-40;return Tn(Y,Math.max(100,J),s,i,A)},{name:"layout/code-lines"}),Q=O([D],([U])=>{let ae=U;if(ae.size===0)return 200;let j=0;for(let{width:Y}of ae.values())Y>j&&(j=Y);return Math.max(200,Math.round(j+80))},{name:"layout/side-width-hint"});u.add(D,{name:"layout/graph-labels"}),u.add(I,{name:"layout/code-lines"}),u.add(Q,{name:"layout/side-width-hint"})}let F=0;return{graph:u,setMainRatio(A){u.set("pane/main-ratio",Wr(A))},setSideSplit(A){u.set("pane/side-split",Wr(A))},setFullscreen(A){u.set("pane/fullscreen",A)},setViewportWidth(A){u.set("viewport/width",Math.max(0,A))},setHoverTarget(A){u.set("hover/target",A)},setDemoGraph(A){u.set("demo/graph-ref",A)},bumpGraphTick(){u.set("demo/graph-tick",++F)},selectNode(A){u.set("inspect/selected-node",A)},setMetaDebug(A){u.set("meta/debug",A)},setCodeText(A){u.set("layout/code-text",A)},batch(A){te(A)},destroy(){u.destroy()}}}var Ls={};he(Ls,{contentModerationGraph:()=>Ag,dataQualityGraph:()=>Lg,issueTrackerGraph:()=>Cg,observabilityGraph:()=>Og});Ne();oe();var As={};he(As,{budgetGate:()=>Fa,effectivenessTracker:()=>Mg,feedback:()=>Kt,funnel:()=>_g,scorer:()=>qr});Ne();ie();xe();oe();function Cs(t,e){return Ke("reduction",t,e)}function _g(t,e,n,r){if(e.length===0)throw new RangeError("funnel requires at least one source");if(n.length===0)throw new RangeError("funnel requires at least one stage");let o=new q(t,r),s=e.length===1?e[0]:mt(...e);o.add(s,{name:"merged"});let i="merged";for(let a=0;a<n.length;a++){let u=n[a],c=new q(u.name);u.build(c);try{c.resolve("input")}catch{throw new Error(`funnel stage "${u.name}" must define an "input" node`)}try{c.resolve("output")}catch{throw new Error(`funnel stage "${u.name}" must define an "output" node`)}o.mount(u.name,c);let d=o.resolve(i),l=`${u.name}::input`,f=o.resolve(l),p=`__bridge_${i}\u2192${u.name}_input`,m=fe([d],([h])=>{f.emit(h)},{name:p});o.add(m,{name:p}),o.addDisposer(se(m)),i=`${u.name}::output`}return o}function Kt(t,e,n,r){let o=r?.maxIterations??10,s=`__feedback_${e}`,i=N(0,{meta:Cs("feedback_counter",{maxIterations:o,feedbackFrom:e,feedbackTo:n})});t.add(i,{name:s});let a=t.resolve(e),u=t.resolve(n),c=`__feedback_effect_${e}`,d=K([],(l,f)=>{let p=a.subscribe(m=>{for(let h of m){let g=h[0];if(g===S){let y=h[1];if(y==null)return;te(()=>{Sr(i,o)&&u.emit(y)})}else if(g===_||g===M){let y=g===M&&h.length>1?[M,h[1]]:[g];i.down([y])}}});return()=>p()},{name:c,describeKind:"effect",meta:{...Cs("feedback_effect",{feedbackFrom:e,feedbackTo:n}),_internal:!0}});return t.add(d,{name:c}),t.addDisposer(se(d)),t}function Fa(t,e,n){if(e.length===0)throw new RangeError("budgetGate requires at least one constraint");let r=e.map(p=>p.node),o=[t,...r],s=[],i=!1,a=!1,u=Symbol("budget-gate"),c=new Array(e.length);function d(){return e.every((p,m)=>p.check(c[m]))}function l(p){for(;s.length>0&&d();){let m=s[0];s=s.slice(1),p.emit(m)}s.length===0&&a&&(a=!1,p.down([[B]]))}return K([],(p,m)=>{for(let g=0;g<e.length;g++)c[g]=e[g].node.cache;let h=[];for(let g=0;g<o.length;g++){let y=o[g];h.push(y.subscribe(b=>{for(let v of b)f(v,g,m)}))}return()=>{for(let g of h)g()}},{...n,describeKind:"derived",meta:Cs("budget_gate",n?.meta)});function f(p,m,h){let g=p[0];if(m===0){if(g===S)return d()&&s.length===0?h.emit(p[1]):(s.push(p[1]),i||(i=!0,h.up([[Ie,u]]))),!0;if(g===ee)return h.down([[ee]]),!0;if(g===B)return s.length===0?h.down([[B]]):a=!0,!0;if(g===_||g===M){for(let y of s)h.emit(y);return s=[],a=!1,i&&(i=!1,h.up([[Ge,u]])),h.down([p]),!0}return!1}return g===S&&(c[m-1]=p[1]),g===S||g===B?(d()&&s.length>0?(l(h),s.length===0&&i&&(i=!1,h.up([[Ge,u]]))):!d()&&!i&&s.length>0&&(i=!0,h.up([[Ie,u]])),!0):g===ee?!0:g===M?(h.down([p]),!0):g===_}}function qr(t,e,n){if(t.length===0)throw new RangeError("scorer requires at least one source");if(t.length!==e.length)throw new RangeError("scorer requires the same number of sources and weights");let r=[...t,...e],o=t.length,s=n?.scoreFns;return O(r,i=>{let a=i.slice(0,o),u=i.slice(o),c=[],d=0;for(let l=0;l<o;l++){let f=a[l]??0,p=u[l]??0,h=(s?.[l]?s[l](f):f)*p;c.push(h),d+=h}return{value:a,score:d,breakdown:c}},{...n?{equals:n.equals,resubscribable:n.resubscribable,resetOnTeardown:n.resetOnTeardown}:{},describeKind:"derived",meta:Cs("scorer",n?.meta)})}function Mg(t){let e=tt({name:t?.name??"effectiveness-entries"}),n=O([e.entries],([i])=>new Map(i),{name:`${t?.name??"effectiveness"}-snapshot`,equals:(i,a)=>{let u=i,c=a;if(u.size!==c.size)return!1;for(let[d,l]of u){let f=c.get(d);if(!f||l.attempts!==f.attempts||l.successes!==f.successes)return!1}return!0}});function r(i,a){let u=e.get(i),c=(u?.attempts??0)+1,d=(u?.successes??0)+(a?1:0);e.set(i,{key:i,attempts:c,successes:d,successRate:d/c})}function o(i){return e.get(i)}let s=se(n);return{node:n,record:r,lookup:o,dispose:()=>s()}}function Me(t,e){return Ke("domain_template",t,e)}function Og(t,e){let n=new q(t,e);n.add(e.source,{name:"source"});let r=[{name:"errors",classify:T=>$a(T,"error")},{name:"traces",classify:T=>$a(T,"trace")},{name:"metrics",classify:T=>$a(T,"metric")}],o=e.branches??r,s=o.map(T=>({name:T.name,classify:T.classify})),i=Fr("stratify",e.source,s);n.mount("stratify",i);let a=o.map(T=>{try{let w=n.resolve(`stratify::branch/${T.name}`);return O([w],([k])=>k,{initial:null})}catch{return N(null)}}),u=e.correlate??(T=>T),c=O(a,T=>u(T),{meta:Me("observability",{stage:"correlate"})});n.add(c,{name:"correlate"});let d=e.sloCheck??(()=>({pass:!0})),l=O([c],T=>T[0],{meta:Me("observability",{stage:"slo_value"})}),f=O([l],T=>d(T[0]),{meta:Me("observability",{stage:"slo_verified"})});n.add(l,{name:"slo_value"}),n.add(f,{name:"slo_verified"});let p=e.weights??o.map(()=>1),m=a.map(T=>O([T],w=>w[0]!=null?1:0)),h=p.map(T=>N(T));for(let T=0;T<m.length;T++)n.add(m[T],{name:`__signal_${T}`}),n.add(h[T],{name:`__weight_${T}`});let g=qr(m,h);n.add(g,{name:"alerts"});let y=O([g,f],T=>({scored:T[0],slo:T[1]}),{meta:Me("observability",{stage:"output"})});n.add(y,{name:"output"});let b=N(null,{meta:Me("observability",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=O([f],T=>{let w=T[0];return w&&w.pass===!1?w:null},{meta:Me("observability",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),Kt(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??5}),n}function Cg(t,e){let n=new q(t,e);n.add(e.source,{name:"source"});let r=0,o=T=>({id:`issue-${++r}`,title:String(T),severity:1,source:"unknown",raw:T}),s=e.extract??o,i=O([e.source],T=>s(T[0]),{meta:Me("issue_tracker",{stage:"extract"})});n.add(i,{name:"extract"});let a=e.verify??(()=>({valid:!0})),u=O([i],T=>{let w=T[0];return{issue:w,verification:a(w)}},{meta:Me("issue_tracker",{stage:"verify"})});n.add(u,{name:"verify"});let c=N([],{meta:Me("issue_tracker",{stage:"known_patterns"})});n.add(c,{name:"known_patterns"});let d=e.detectRegression??(()=>({regression:!1})),l=O([i,c],T=>{let w=T[0],k=T[1];return{issue:w,regression:d(w,k)}},{meta:Me("issue_tracker",{stage:"regression"})});n.add(l,{name:"regression"});let f=O([i],T=>T[0]?.severity??0),p=O([l],T=>T[0]?.regression?2:0);n.add(f,{name:"__severity_signal"}),n.add(p,{name:"__regression_signal"});let m=N(1),h=N(1.5);n.add(m,{name:"__severity_weight"}),n.add(h,{name:"__regression_weight"});let g=qr([f,p],[m,h]);n.add(g,{name:"priority"});let y=O([u,l,g],T=>({verified:T[0],regression:T[1],priority:T[2]}),{meta:Me("issue_tracker",{stage:"output"})});n.add(y,{name:"output"});let b=N(null,{meta:Me("issue_tracker",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=O([u],T=>{let w=T[0];if(w){let k=w.verification;if(k&&k.valid===!1)return w}return null},{meta:Me("issue_tracker",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),Kt(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??3}),n}function Ag(t,e){let n=new q(t,e);n.add(e.source,{name:"source"});let r=v=>({label:"review",confidence:.5,original:v}),o=e.classify??r,s=O([e.source],v=>o(v[0]),{meta:Me("content_moderation",{stage:"classify"})});n.add(s,{name:"classify"});let i=Fr("stratify",s,[{name:"safe",classify:v=>v.label==="safe"},{name:"review",classify:v=>v.label==="review"},{name:"block",classify:v=>v.label==="block"}]);n.mount("stratify",i);let a=Ve([],{name:"review_queue",maxSize:e.maxQueueSize});n.add(a.entries,{name:"review_queue"});let u;try{u=n.resolve("stratify::branch/review")}catch{u=N(null),n.add(u,{name:"__review_fallback"})}let c=fe([u],v=>{let T=v[0];T&&a.append(T)});n.add(c,{name:"__review_accumulator"}),n.addDisposer(se(c));let d=N({},{meta:Me("content_moderation",{stage:"policy",access:"both",description:"Moderation policy rules \u2014 updated via feedback"})});n.add(d,{name:"policy"});let l=e.weights??[.1,1,2],f=O([s],v=>v[0]?.confidence??0),p=O([s],v=>{let T=v[0];return T?T.label==="block"?l[2]:T.label==="review"?l[1]:l[0]:0});n.add(f,{name:"__confidence_signal"}),n.add(p,{name:"__severity_signal"});let m=N(1),h=N(1);n.add(m,{name:"__w_confidence"}),n.add(h,{name:"__w_severity"});let g=qr([f,p],[m,h]);n.add(g,{name:"priority"});let y=O([s,g],v=>({classification:v[0],priority:v[1]}),{meta:Me("content_moderation",{stage:"output"})});n.add(y,{name:"output"});let b=O([a.entries,d],v=>{let T=v[0];if(T&&T.length>0){let w=T[T.length-1];if(w&&w.falsePositive)return w}return null},{meta:Me("content_moderation",{stage:"feedback_condition"})});return n.add(b,{name:"feedback_condition"}),Kt(n,"feedback_condition","policy",{maxIterations:e.maxFeedbackIterations??5}),n}function Lg(t,e){let n=new q(t,e);n.add(e.source,{name:"source"});let r=e.validate??(g=>({valid:!0,errors:[],record:g})),o=O([e.source],g=>g[0]!=null?r(g[0]):void 0,{meta:Me("data_quality",{stage:"validate"})});n.add(o,{name:"validate"});let s=e.detectAnomaly??(g=>({anomaly:!1,score:0,record:g})),i=O([e.source],g=>g[0]!=null?s(g[0]):void 0,{meta:Me("data_quality",{stage:"anomaly"})});n.add(i,{name:"anomaly"});let a=N(null,{meta:Me("data_quality",{stage:"baseline",description:"Rolling baseline for drift detection"})});n.add(a,{name:"baseline"});let u=fe([o],g=>{let y=g[0];y?.valid&&te(()=>{a.emit(y.record)})});n.add(u,{name:"__baseline_updater"}),se(u);let c=e.detectDrift??(()=>({drift:!1})),d=O([e.source,a],g=>c(g[0],g[1]),{meta:Me("data_quality",{stage:"drift"})});n.add(d,{name:"drift"});let l=e.suggest??(()=>null),f=O([o,i],g=>l({validation:g[0],anomaly:g[1]}),{meta:Me("data_quality",{stage:"remediate"})});n.add(f,{name:"remediate"});let p=O([o,i,d,f],g=>({validation:g[0],anomaly:g[1],drift:g[2],remediation:g[3]}),{meta:Me("data_quality",{stage:"output"})});n.add(p,{name:"output"});let m=N([],{meta:Me("data_quality",{stage:"validation_rules"})});n.add(m,{name:"validation_rules"});let h=O([i],g=>{let y=g[0];return y?.anomaly?y:null},{meta:Me("data_quality",{stage:"feedback_condition"})});return n.add(h,{name:"feedback_condition"}),Kt(n,"feedback_condition","validation_rules",{maxIterations:e.maxFeedbackIterations??3}),n}function $a(t,e){if(t==null||typeof t!="object")return!1;let n=t;return n.type===e||n.kind===e}var Is={};he(Is,{compileSpec:()=>Va,decompileGraph:()=>$g,extractFnFactory:()=>np,extractSourceFactory:()=>rp,generateCatalogPrompt:()=>op,isRichFnEntry:()=>Ur,isRichSourceEntry:()=>ja,llmCompose:()=>jg,llmRefine:()=>ap,specDiff:()=>Bg,validateSpec:()=>Xn,validateSpecAgainstCatalog:()=>zr});oe();function Ur(t){return typeof t=="object"&&t!==null&&"factory"in t}function ja(t){return typeof t=="object"&&t!==null&&"factory"in t}function np(t){return Ur(t)?t.factory:t}function rp(t){return ja(t)?t.factory:t}function op(t){let e=[];if(t.fns){let n=new Map;for(let[r,o]of Object.entries(t.fns)){let s=Ur(o)?o.tags?.[0]??"Other":"Other";n.has(s)||n.set(s,[]),n.get(s).push(Ig(r,o))}for(let[r,o]of n)e.push(`${r}:
118
119
  ${o.join(`
119
- `)}`)}if(t.sources){let n=[];for(let[r,o]of Object.entries(t.sources))n.push(Uh(r,o));n.length>0&&e.push(`Sources:
120
+ `)}`)}if(t.sources){let n=[];for(let[r,o]of Object.entries(t.sources))n.push(Pg(r,o));n.length>0&&e.push(`Sources:
120
121
  ${n.join(`
121
122
  `)}`)}return e.join(`
122
123
 
123
- `)}function Wh(t,e){if(!Vr(e))return`- ${t}`;let n=`- ${t}: ${e.description}`;if(e.configSchema){let r=Object.entries(e.configSchema).map(([o,s])=>{let i=`${o}: ${s.type}`;return s.enum&&(i+=` (${s.enum.join("|")})`),s.required===!1&&(i+="?"),i});n+=`. Config: { ${r.join(", ")} }`}return n}function Uh(t,e){if(!Oa(e))return`- ${t}`;let n=`- ${t}: ${e.description}`;if(e.configSchema){let r=Object.entries(e.configSchema).map(([o,s])=>{let i=`${o}: ${s.type}`;return s.required===!1&&(i+="?"),i});n+=`. Config: { ${r.join(", ")} }`}return n}function qr(t,e){let n=[],r=new Set(Object.keys(e.fns??{})),o=new Set(Object.keys(e.sources??{}));for(let[s,i]of Object.entries(t.nodes)){if(i.type==="template")continue;let a=i;if(a.fn&&r.size>0&&!r.has(a.fn))if(o.has(a.fn))n.push(`Node "${s}": fn "${a.fn}" is a source, not a function. Use it as a producer source instead, or use a function from: ${[...r].join(", ")}`);else{let u=Ma(a.fn,r);n.push(`Node "${s}": fn "${a.fn}" not found in catalog`+(u?`. Did you mean "${u}"?`:""))}if(a.source&&o.size>0&&!o.has(a.source))if(r.has(a.source))n.push(`Node "${s}": source "${a.source}" is a function, not a source. Use it as fn instead, or use a source from: ${[...o].join(", ")}`);else{let u=Ma(a.source,o);n.push(`Node "${s}": source "${a.source}" not found in catalog`+(u?`. Did you mean "${u}"?`:""))}if(a.fn&&a.config&&e.fns?.[a.fn]){let u=e.fns[a.fn];if(Vr(u)&&u.configSchema){for(let[c,d]of Object.entries(u.configSchema))if(d.required!==!1&&!(c in a.config)&&n.push(`Node "${s}": config missing required field "${c}"`),c in a.config&&d.enum){let l=a.config[c];d.enum.includes(l)||n.push(`Node "${s}": config.${c} = ${JSON.stringify(l)}, expected one of: ${d.enum.join(", ")}`)}}}}if(t.templates){for(let[s,i]of Object.entries(t.templates))for(let[a,u]of Object.entries(i.nodes))if(u.fn&&r.size>0&&!r.has(u.fn)){let c=Ma(u.fn,r);n.push(`Template "${s}" node "${a}": fn "${u.fn}" not found in catalog`+(c?`. Did you mean "${c}"?`:""))}}return{valid:n.length===0,errors:n}}function Ma(t,e){let n=null,r=1/0,o=t.toLowerCase();for(let s of e){let i=zh(o,s.toLowerCase());i<r&&i<=Math.max(3,Math.floor(t.length/2))&&(r=i,n=s)}return n}function zh(t,e){let n=t.length,r=e.length,o=Array.from({length:n+1},(s,i)=>Array.from({length:r+1},(a,u)=>i===0?u:u===0?i:0));for(let s=1;s<=n;s++)for(let i=1;i<=r;i++)o[s][i]=t[s-1]===e[i-1]?o[s-1][i-1]:1+Math.min(o[s-1][i],o[s][i-1],o[s-1][i-1]);return o[n][r]}var Gl=new Set(["state","producer","derived","effect","operator","template"]),Jh=new Set(["state","producer","derived","effect","operator"]);function Un(t){let e=[];if(t==null||typeof t!="object")return{valid:!1,errors:["GraphSpec 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)),o=new Map,s=new Map;if(n.templates!=null&&typeof n.templates=="object"&&!Array.isArray(n.templates)){for(let[i,a]of Object.entries(n.templates))if(a!=null&&typeof a=="object"){let u=a;s.set(i,{params:Array.isArray(u.params)?u.params:[]})}}if(n.templates!=null)if(typeof n.templates!="object"||Array.isArray(n.templates))e.push("'templates' must be an object");else for(let[i,a]of Object.entries(n.templates)){if(a==null||typeof a!="object"){e.push(`Template "${i}": must be an object`);continue}let u=a;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:[]),d=new Set(Object.keys(u.nodes));for(let[l,f]of Object.entries(u.nodes)){if(f==null||typeof f!="object"){e.push(`Template "${i}" node "${l}": must be an object`);continue}let p=f;if((typeof p.type!="string"||!Jh.has(p.type))&&e.push(`Template "${i}" node "${l}": invalid type`),Array.isArray(p.deps))for(let m of p.deps)!d.has(m)&&!c.has(m)&&e.push(`Template "${i}" node "${l}": dep "${m}" 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,a]of Object.entries(n.nodes)){if(a==null||typeof a!="object"){e.push(`Node "${i}": must be an object`);continue}let u=a;if(typeof u.type!="string"||!Gl.has(u.type)){e.push(`Node "${i}": invalid type "${String(u.type)}" (expected: ${[...Gl].join(", ")})`);continue}if(o.set(i,u.type),u.type==="template")if(typeof u.template!="string"||!s.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=s.get(u.template),d=u.bind;for(let l of c.params)l in d||e.push(`Node "${i}": template param "${l}" is not bound (template "${u.template}")`);for(let[,l]of Object.entries(d))typeof l=="string"&&!r.has(l)&&e.push(`Node "${i}": bind target "${l}" 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`):r.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(n.feedback!=null)if(!Array.isArray(n.feedback))e.push("'feedback' must be an array");else for(let i=0;i<n.feedback.length;i++){let a=n.feedback[i];if(a==null||typeof a!="object"){e.push(`Feedback [${i}]: must be an object`);continue}let u=a;(typeof u.from!="string"||!r.has(u.from))&&e.push(`Feedback [${i}]: 'from' "${String(u.from)}" does not reference an existing node`),typeof u.from=="string"&&u.from===u.to&&e.push(`Feedback [${i}]: 'from' and 'to' must be different nodes`),typeof u.to!="string"||!r.has(u.to)?e.push(`Feedback [${i}]: 'to' "${String(u.to)}" does not reference an existing node`):typeof u.to=="string"&&o.get(u.to)!=="state"&&e.push(`Feedback [${i}]: 'to' node "${u.to}" must be a state node (got "${o.get(u.to)??"unknown"}")`)}return{valid:e.length===0,errors:e}}function Ca(t,e){let n=Un(t);if(!n.valid)throw new Error(`compileSpec: invalid GraphSpec:
124
+ `)}function Ig(t,e){if(!Ur(e))return`- ${t}`;let n=`- ${t}: ${e.description}`;if(e.configSchema){let r=Object.entries(e.configSchema).map(([o,s])=>{let i=`${o}: ${s.type}`;return s.enum&&(i+=` (${s.enum.join("|")})`),s.required===!1&&(i+="?"),i});n+=`. Config: { ${r.join(", ")} }`}return n}function Pg(t,e){if(!ja(e))return`- ${t}`;let n=`- ${t}: ${e.description}`;if(e.configSchema){let r=Object.entries(e.configSchema).map(([o,s])=>{let i=`${o}: ${s.type}`;return s.required===!1&&(i+="?"),i});n+=`. Config: { ${r.join(", ")} }`}return n}function zr(t,e){let n=[],r=new Set(Object.keys(e.fns??{})),o=new Set(Object.keys(e.sources??{}));for(let[s,i]of Object.entries(t.nodes)){if(i.type==="template")continue;let a=i;if(a.fn&&r.size>0&&!r.has(a.fn))if(o.has(a.fn))n.push(`Node "${s}": fn "${a.fn}" is a source, not a function. Use it as a producer source instead, or use a function from: ${[...r].join(", ")}`);else{let u=Ba(a.fn,r);n.push(`Node "${s}": fn "${a.fn}" not found in catalog`+(u?`. Did you mean "${u}"?`:""))}if(a.source&&o.size>0&&!o.has(a.source))if(r.has(a.source))n.push(`Node "${s}": source "${a.source}" is a function, not a source. Use it as fn instead, or use a source from: ${[...o].join(", ")}`);else{let u=Ba(a.source,o);n.push(`Node "${s}": source "${a.source}" not found in catalog`+(u?`. Did you mean "${u}"?`:""))}if(a.fn&&a.config&&e.fns?.[a.fn]){let u=e.fns[a.fn];if(Ur(u)&&u.configSchema){for(let[c,d]of Object.entries(u.configSchema))if(d.required!==!1&&!(c in a.config)&&n.push(`Node "${s}": config missing required field "${c}"`),c in a.config&&d.enum){let l=a.config[c];d.enum.includes(l)||n.push(`Node "${s}": config.${c} = ${JSON.stringify(l)}, expected one of: ${d.enum.join(", ")}`)}}}}if(t.templates){for(let[s,i]of Object.entries(t.templates))for(let[a,u]of Object.entries(i.nodes))if(u.fn&&r.size>0&&!r.has(u.fn)){let c=Ba(u.fn,r);n.push(`Template "${s}" node "${a}": fn "${u.fn}" not found in catalog`+(c?`. Did you mean "${c}"?`:""))}}return{valid:n.length===0,errors:n}}function Ba(t,e){let n=null,r=1/0,o=t.toLowerCase();for(let s of e){let i=Dg(o,s.toLowerCase());i<r&&i<=Math.max(3,Math.floor(t.length/2))&&(r=i,n=s)}return n}function Dg(t,e){let n=t.length,r=e.length,o=Array.from({length:n+1},(s,i)=>Array.from({length:r+1},(a,u)=>i===0?u:u===0?i:0));for(let s=1;s<=n;s++)for(let i=1;i<=r;i++)o[s][i]=t[s-1]===e[i-1]?o[s-1][i-1]:1+Math.min(o[s-1][i],o[s][i-1],o[s-1][i-1]);return o[n][r]}var tp=new Set(["state","producer","derived","effect","operator","template"]),Gg=new Set(["state","producer","derived","effect","operator"]);function Xn(t){let e=[];if(t==null||typeof t!="object")return{valid:!1,errors:["GraphSpec 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)),o=new Map,s=new Map;if(n.templates!=null&&typeof n.templates=="object"&&!Array.isArray(n.templates)){for(let[i,a]of Object.entries(n.templates))if(a!=null&&typeof a=="object"){let u=a;s.set(i,{params:Array.isArray(u.params)?u.params:[]})}}if(n.templates!=null)if(typeof n.templates!="object"||Array.isArray(n.templates))e.push("'templates' must be an object");else for(let[i,a]of Object.entries(n.templates)){if(a==null||typeof a!="object"){e.push(`Template "${i}": must be an object`);continue}let u=a;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:[]),d=new Set(Object.keys(u.nodes));for(let[l,f]of Object.entries(u.nodes)){if(f==null||typeof f!="object"){e.push(`Template "${i}" node "${l}": must be an object`);continue}let p=f;if((typeof p.type!="string"||!Gg.has(p.type))&&e.push(`Template "${i}" node "${l}": invalid type`),Array.isArray(p.deps))for(let m of p.deps)!d.has(m)&&!c.has(m)&&e.push(`Template "${i}" node "${l}": dep "${m}" 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,a]of Object.entries(n.nodes)){if(a==null||typeof a!="object"){e.push(`Node "${i}": must be an object`);continue}let u=a;if(typeof u.type!="string"||!tp.has(u.type)){e.push(`Node "${i}": invalid type "${String(u.type)}" (expected: ${[...tp].join(", ")})`);continue}if(o.set(i,u.type),u.type==="template")if(typeof u.template!="string"||!s.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=s.get(u.template),d=u.bind;for(let l of c.params)l in d||e.push(`Node "${i}": template param "${l}" is not bound (template "${u.template}")`);for(let[,l]of Object.entries(d))typeof l=="string"&&!r.has(l)&&e.push(`Node "${i}": bind target "${l}" 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`):r.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(n.feedback!=null)if(!Array.isArray(n.feedback))e.push("'feedback' must be an array");else for(let i=0;i<n.feedback.length;i++){let a=n.feedback[i];if(a==null||typeof a!="object"){e.push(`Feedback [${i}]: must be an object`);continue}let u=a;(typeof u.from!="string"||!r.has(u.from))&&e.push(`Feedback [${i}]: 'from' "${String(u.from)}" does not reference an existing node`),typeof u.from=="string"&&u.from===u.to&&e.push(`Feedback [${i}]: 'from' and 'to' must be different nodes`),typeof u.to!="string"||!r.has(u.to)?e.push(`Feedback [${i}]: 'to' "${String(u.to)}" does not reference an existing node`):typeof u.to=="string"&&o.get(u.to)!=="state"&&e.push(`Feedback [${i}]: 'to' node "${u.to}" must be a state node (got "${o.get(u.to)??"unknown"}")`)}return{valid:e.length===0,errors:e}}function Va(t,e){let n=Xn(t);if(!n.valid)throw new Error(`compileSpec: invalid GraphSpec:
124
125
  ${n.errors.join(`
125
- `)}`);let r=e?.catalog??{},o=new z(t.name),s=t.templates??{},i=qr(t,r);if(!i.valid)throw new Error(`compileSpec: catalog validation errors:
126
+ `)}`);let r=e?.catalog??{},o=new q(t.name),s=t.templates??{},i=zr(t,r);if(!i.valid)throw new Error(`compileSpec: catalog validation errors:
126
127
  ${i.errors.join(`
127
- `)}`);let a=p=>{let m=r.fns?.[p];return m?Fl(m):void 0},u=p=>{let m=r.sources?.[p];return m?$l(m):void 0},c=new Map,d=[];for(let[p,m]of Object.entries(t.nodes)){if(m.type==="template")continue;let h=m;if(h.type==="state"){let g=N(h.initial,{name:p,meta:h.meta?{...h.meta}:void 0});o.add(g,{name:p}),c.set(p,g)}else if(h.type==="producer"){let g=h.source?u(h.source):void 0,y=h.fn?a(h.fn):void 0;if(g){let b=g(h.config??{});o.add(b,{name:p}),c.set(p,b)}else if(y){let b=y([],h.config??{});o.add(b,{name:p}),c.set(p,b)}else{let b=H(()=>{},{name:p,meta:{...h.meta,_specFn:h.fn,_specSource:h.source}});o.add(b,{name:p}),c.set(p,b)}}else d.push([p,h])}let l=!0,f=new Map(d);for(;f.size>0&&l;){l=!1;for(let[p,m]of[...f.entries()]){let h=m.deps??[];if(!h.every(v=>c.has(v)))continue;let g=h.map(v=>c.get(v)),y=m.fn?a(m.fn):void 0,b;y?b=y(g,m.config??{}):m.type==="effect"?b=fe(g,()=>{}):b=A(g,v=>v[0]),o.add(b,{name:p}),c.set(p,b),f.delete(p),l=!0}}if(f.size>0){let p=[...f.keys()].sort().join(", ");throw new Error(`compileSpec: unresolvable deps for nodes: ${p}`)}for(let[p,m]of Object.entries(t.nodes)){if(m.type!=="template")continue;let h=m,g=s[h.template],y=new z(p),b=new Map,v=[];for(let[x,S]of Object.entries(g.nodes)){let _=(S.deps??[]).map(L=>L.startsWith("$")&&h.bind[L]?h.bind[L]:L),F={...S,deps:_};if(S.type==="state"){let L=N(S.initial,{name:x,meta:S.meta?{...S.meta}:void 0});y.add(L,{name:x}),b.set(x,L)}else if(S.type==="producer"){let L=S.source?u(S.source):void 0,D=S.fn?a(S.fn):void 0;if(L){let C=L(S.config??{});y.add(C,{name:x}),b.set(x,C)}else if(D){let C=D([],S.config??{});y.add(C,{name:x}),b.set(x,C)}else{let C=H(()=>{},{name:x,meta:{...S.meta,_specFn:S.fn,_specSource:S.source}});y.add(C,{name:x}),b.set(x,C)}}else v.push([x,F])}let T=!0,w=new Map(v);for(;w.size>0&&T;){T=!1;for(let[x,S]of[...w.entries()]){let _=S.deps??[];if(!_.every(K=>b.has(K)||c.has(K)))continue;let L=_.map(K=>b.get(K)??c.get(K)),D=S.fn?a(S.fn):void 0,C;D?C=D(L,S.config??{}):S.type==="effect"?C=fe(L,()=>{}):C=A(L,K=>K[0]),y.add(C,{name:x}),b.set(x,C),w.delete(x),T=!0}}if(w.size>0){let x=[...w.keys()].sort().join(", ");throw new Error(`compileSpec: template "${h.template}" has unresolvable deps: ${x}`)}o.mount(p,y);let k=`${p}::${g.output}`;c.set(p,o.resolve(k));try{let x=o.resolve(k);x.meta._templateName?.emit(h.template),x.meta._templateBind?.emit(h.bind)}catch{}}for(let p of t.feedback??[])jt(o,p.from,p.to,{maxIterations:p.maxIterations});return o}var Yh=new Set(["reduction","reduction_type","_specFn","_specSource","_templateName","_templateBind","feedbackFrom","feedbackTo","_internal"]);function Qh(t){let e=t.describe({detail:"standard"}),n={},r=[],o=`::${Be}::`,s=/^__feedback_(?!effect_)(.+)$/,i=new Set;for(let p of Object.keys(e.nodes)){if(p.includes(o))continue;let m=s.exec(p);if(m){i.add(m[1]);let h=e.nodes[p]?.meta;h?.feedbackFrom&&h?.feedbackTo&&r.push({from:h.feedbackFrom,to:h.feedbackTo,...h.maxIterations?{maxIterations:h.maxIterations}:{}})}}for(let[p,m]of Object.entries(e.nodes)){if(p.includes(o)||s.test(p)||m.meta?._internal||p.startsWith("__feedback_effect_")||p.startsWith("__bridge_")||p.includes("::"))continue;let h={type:m.type};if(m.deps.length>0&&(h.deps=m.deps.filter(g=>!g.includes("::"))),m.type==="state"&&m.value!==void 0&&(h.initial=m.value),m.meta&&Object.keys(m.meta).length>0){let g={};for(let[y,b]of Object.entries(m.meta))Yh.has(y)||(g[y]=b);Object.keys(g).length>0&&(h.meta=g)}n[p]=h}let a={},u={},c=new Set;for(let p of e.subgraphs){let m=`${p}::`;for(let[h,g]of Object.entries(e.nodes)){if(!h.startsWith(m)||h.includes(o))continue;let y=g.meta;if(y?._templateName&&y?._templateBind){let b=y._templateName,v=y._templateBind;if(!a[b]){let T={},w=new Set,k=`${p}::`;for(let[D,C]of Object.entries(e.nodes)){if(!D.startsWith(k)||D.includes(o))continue;let K=D.slice(k.length);K.includes("::")||(w.add(K),T[K]={type:C.type,...C.deps.length>0?{deps:C.deps.map(ne=>ne.startsWith(k)?ne.slice(k.length):ne)}:{}})}let x=[],S=new Map;for(let D of Object.values(T))for(let C of D.deps??[])if(!w.has(C)&&!S.has(C)){let K=`$${C}`;x.push(K),S.set(C,K)}for(let D of Object.values(T))D.deps&&(D.deps=D.deps.map(C=>S.get(C)??C));let _=new Set;for(let D of Object.values(T))for(let C of D.deps??[])w.has(C)&&_.add(C);let L=[...w].filter(D=>!_.has(D))[0]??[...w].pop();a[b]={params:x,nodes:T,output:L}}delete n[p],u[p]={type:"template",template:b,bind:v},c.add(p);break}}}let d=new Map;for(let p of e.subgraphs){if(c.has(p))continue;let m={},h=`${p}::`;for(let[y,b]of Object.entries(e.nodes)){if(y.includes(o)||!y.startsWith(h))continue;let v=y.slice(h.length);v.includes("::")||(m[v]={type:b.type,...b.deps.length>0?{deps:b.deps.map(T=>T.startsWith(h)?T.slice(h.length):T)}:{}})}let g=JSON.stringify(Object.fromEntries(Object.entries(m).sort(([y],[b])=>y.localeCompare(b)).map(([y,b])=>[y,{type:b.type,deps:b.deps??[]}])));d.has(g)||d.set(g,[]),d.get(g).push({name:p,nodes:m})}for(let[,p]of d){if(p.length<2)continue;let m=`${p[0].name}_template`,h=p[0].nodes,g=new Set(Object.keys(h)),y=[],b=new Map;for(let x of Object.values(h))for(let S of x.deps??[])if(!g.has(S)&&!b.has(S)){let _=`$${S}`;y.push(_),b.set(S,_)}let v=new Set;for(let x of Object.values(h))for(let S of x.deps??[])g.has(S)&&v.add(S);let w=[...g].filter(x=>!v.has(x))[0]??[...g].pop(),k={};for(let[x,S]of Object.entries(h))k[x]={...S,deps:S.deps?.map(_=>b.get(_)??_)};a[m]={params:y,nodes:k,output:w};for(let x of p){delete n[x.name];let S={},_=new Set(Object.keys(x.nodes));for(let F of Object.values(x.nodes))for(let L of F.deps??[])if(!_.has(L)){let D=b.get(L)??`$${L}`;S[D]=L}u[x.name]={type:"template",template:m,bind:S}}}let l={...n,...u},f={name:e.name,nodes:l};return Object.keys(a).length>0&&(f.templates=a),r.length>0&&(f.feedback=r),f}function Xh(t,e){let n=[];t.name!==e.name&&n.push({type:"changed",path:"name",detail:`"${t.name}" \u2192 "${e.name}"`});let r=new Set(Object.keys(t.nodes)),o=new Set(Object.keys(e.nodes));for(let b of o)if(!r.has(b)){let v=e.nodes[b];n.push({type:"added",path:`nodes.${b}`,detail:`type: ${v.type}`})}for(let b of r)o.has(b)||n.push({type:"removed",path:`nodes.${b}`});for(let b of r){if(!o.has(b))continue;let v=t.nodes[b],T=e.nodes[b];if(JSON.stringify(v)!==JSON.stringify(T)){let w=[];v.type!==T.type&&w.push(`type: ${v.type} \u2192 ${T.type}`),JSON.stringify(v.deps)!==JSON.stringify(T.deps)&&w.push("deps changed"),v.fn!==T.fn&&w.push(`fn: ${v.fn} \u2192 ${T.fn}`),JSON.stringify(v.config)!==JSON.stringify(T.config)&&w.push("config changed"),n.push({type:"changed",path:`nodes.${b}`,detail:w.join("; ")||"modified"})}}let s=t.templates??{},i=e.templates??{},a=new Set(Object.keys(s)),u=new Set(Object.keys(i));for(let b of u)a.has(b)||n.push({type:"added",path:`templates.${b}`});for(let b of a)u.has(b)||n.push({type:"removed",path:`templates.${b}`});for(let b of a)u.has(b)&&JSON.stringify(s[b])!==JSON.stringify(i[b])&&n.push({type:"changed",path:`templates.${b}`,detail:"template definition changed"});let c=t.feedback??[],d=e.feedback??[],l=new Set(c.map(b=>`${b.from}->${b.to}`)),f=new Set(d.map(b=>`${b.from}->${b.to}`));for(let b of d){let v=`${b.from}->${b.to}`;l.has(v)||n.push({type:"added",path:`feedback.${v}`,detail:`maxIterations: ${b.maxIterations??10}`})}for(let b of c){let v=`${b.from}->${b.to}`;f.has(v)||n.push({type:"removed",path:`feedback.${v}`})}for(let b of c){let v=`${b.from}->${b.to}`,T=d.find(w=>w.from===b.from&&w.to===b.to);T&&JSON.stringify(b)!==JSON.stringify(T)&&n.push({type:"changed",path:`feedback.${v}`,detail:`maxIterations: ${b.maxIterations??10} \u2192 ${T.maxIterations??10}`})}let p=n.filter(b=>b.type==="added").length,m=n.filter(b=>b.type==="removed").length,h=n.filter(b=>b.type==="changed").length,g=[];p&&g.push(`${p} added`),m&&g.push(`${m} removed`),h&&g.push(`${h} changed`);let y=g.length>0?g.join(", "):"no changes";return{entries:n,summary:y}}var jl=`You are a graph architect for GraphReFly, a reactive graph protocol.
128
+ `)}`);let a=p=>{let m=r.fns?.[p];return m?np(m):void 0},u=p=>{let m=r.sources?.[p];return m?rp(m):void 0},c=new Map,d=[];for(let[p,m]of Object.entries(t.nodes)){if(m.type==="template")continue;let h=m;if(h.type==="state"){let g=N(h.initial,{name:p,meta:h.meta?{...h.meta}:void 0});o.add(g,{name:p}),c.set(p,g)}else if(h.type==="producer"){let g=h.source?u(h.source):void 0,y=h.fn?a(h.fn):void 0;if(g){let b=g(h.config??{});o.add(b,{name:p}),c.set(p,b)}else if(y){let b=y([],h.config??{});o.add(b,{name:p}),c.set(p,b)}else{let b=W(()=>{},{name:p,meta:{...h.meta,_specFn:h.fn,_specSource:h.source}});o.add(b,{name:p}),c.set(p,b)}}else d.push([p,h])}let l=!0,f=new Map(d);for(;f.size>0&&l;){l=!1;for(let[p,m]of[...f.entries()]){let h=m.deps??[];if(!h.every(v=>c.has(v)))continue;let g=h.map(v=>c.get(v)),y=m.fn?a(m.fn):void 0,b;y?b=y(g,m.config??{}):m.type==="effect"?b=fe(g,()=>{}):b=O(g,v=>v[0]),o.add(b,{name:p}),c.set(p,b),f.delete(p),l=!0}}if(f.size>0){let p=[...f.keys()].sort().join(", ");throw new Error(`compileSpec: unresolvable deps for nodes: ${p}`)}for(let[p,m]of Object.entries(t.nodes)){if(m.type!=="template")continue;let h=m,g=s[h.template],y=new q(p),b=new Map,v=[];for(let[x,R]of Object.entries(g.nodes)){let E=(R.deps??[]).map(L=>L.startsWith("$")&&h.bind[L]?h.bind[L]:L),G={...R,deps:E};if(R.type==="state"){let L=N(R.initial,{name:x,meta:R.meta?{...R.meta}:void 0});y.add(L,{name:x}),b.set(x,L)}else if(R.type==="producer"){let L=R.source?u(R.source):void 0,P=R.fn?a(R.fn):void 0;if(L){let C=L(R.config??{});y.add(C,{name:x}),b.set(x,C)}else if(P){let C=P([],R.config??{});y.add(C,{name:x}),b.set(x,C)}else{let C=W(()=>{},{name:x,meta:{...R.meta,_specFn:R.fn,_specSource:R.source}});y.add(C,{name:x}),b.set(x,C)}}else v.push([x,G])}let T=!0,w=new Map(v);for(;w.size>0&&T;){T=!1;for(let[x,R]of[...w.entries()]){let E=R.deps??[];if(!E.every(V=>b.has(V)||c.has(V)))continue;let L=E.map(V=>b.get(V)??c.get(V)),P=R.fn?a(R.fn):void 0,C;P?C=P(L,R.config??{}):R.type==="effect"?C=fe(L,()=>{}):C=O(L,V=>V[0]),y.add(C,{name:x}),b.set(x,C),w.delete(x),T=!0}}if(w.size>0){let x=[...w.keys()].sort().join(", ");throw new Error(`compileSpec: template "${h.template}" has unresolvable deps: ${x}`)}o.mount(p,y);let k=`${p}::${g.output}`;c.set(p,o.resolve(k));try{let x=o.resolve(k);x.meta._templateName?.emit(h.template),x.meta._templateBind?.emit(h.bind)}catch{}}for(let p of t.feedback??[])Kt(o,p.from,p.to,{maxIterations:p.maxIterations});return o}var Fg=new Set(["reduction","reduction_type","_specFn","_specSource","_templateName","_templateBind","feedbackFrom","feedbackTo","_internal"]);function $g(t){let e=t.describe({detail:"standard"}),n={},r=[],o=`::${je}::`,s=/^__feedback_(?!effect_)(.+)$/,i=new Set;for(let p of Object.keys(e.nodes)){if(p.includes(o))continue;let m=s.exec(p);if(m){i.add(m[1]);let h=e.nodes[p]?.meta;h?.feedbackFrom&&h?.feedbackTo&&r.push({from:h.feedbackFrom,to:h.feedbackTo,...h.maxIterations?{maxIterations:h.maxIterations}:{}})}}for(let[p,m]of Object.entries(e.nodes)){if(p.includes(o)||s.test(p)||m.meta?._internal||p.startsWith("__feedback_effect_")||p.startsWith("__bridge_")||p.includes("::"))continue;let h={type:m.type};if(m.deps.length>0&&(h.deps=m.deps.filter(g=>!g.includes("::"))),m.type==="state"&&m.value!==void 0&&(h.initial=m.value),m.meta&&Object.keys(m.meta).length>0){let g={};for(let[y,b]of Object.entries(m.meta))Fg.has(y)||(g[y]=b);Object.keys(g).length>0&&(h.meta=g)}n[p]=h}let a={},u={},c=new Set;for(let p of e.subgraphs){let m=`${p}::`;for(let[h,g]of Object.entries(e.nodes)){if(!h.startsWith(m)||h.includes(o))continue;let y=g.meta;if(y?._templateName&&y?._templateBind){let b=y._templateName,v=y._templateBind;if(!a[b]){let T={},w=new Set,k=`${p}::`;for(let[P,C]of Object.entries(e.nodes)){if(!P.startsWith(k)||P.includes(o))continue;let V=P.slice(k.length);V.includes("::")||(w.add(V),T[V]={type:C.type,...C.deps.length>0?{deps:C.deps.map(ne=>ne.startsWith(k)?ne.slice(k.length):ne)}:{}})}let x=[],R=new Map;for(let P of Object.values(T))for(let C of P.deps??[])if(!w.has(C)&&!R.has(C)){let V=`$${C}`;x.push(V),R.set(C,V)}for(let P of Object.values(T))P.deps&&(P.deps=P.deps.map(C=>R.get(C)??C));let E=new Set;for(let P of Object.values(T))for(let C of P.deps??[])w.has(C)&&E.add(C);let L=[...w].filter(P=>!E.has(P))[0]??[...w].pop();a[b]={params:x,nodes:T,output:L}}delete n[p],u[p]={type:"template",template:b,bind:v},c.add(p);break}}}let d=new Map;for(let p of e.subgraphs){if(c.has(p))continue;let m={},h=`${p}::`;for(let[y,b]of Object.entries(e.nodes)){if(y.includes(o)||!y.startsWith(h))continue;let v=y.slice(h.length);v.includes("::")||(m[v]={type:b.type,...b.deps.length>0?{deps:b.deps.map(T=>T.startsWith(h)?T.slice(h.length):T)}:{}})}let g=JSON.stringify(Object.fromEntries(Object.entries(m).sort(([y],[b])=>y.localeCompare(b)).map(([y,b])=>[y,{type:b.type,deps:b.deps??[]}])));d.has(g)||d.set(g,[]),d.get(g).push({name:p,nodes:m})}for(let[,p]of d){if(p.length<2)continue;let m=`${p[0].name}_template`,h=p[0].nodes,g=new Set(Object.keys(h)),y=[],b=new Map;for(let x of Object.values(h))for(let R of x.deps??[])if(!g.has(R)&&!b.has(R)){let E=`$${R}`;y.push(E),b.set(R,E)}let v=new Set;for(let x of Object.values(h))for(let R of x.deps??[])g.has(R)&&v.add(R);let w=[...g].filter(x=>!v.has(x))[0]??[...g].pop(),k={};for(let[x,R]of Object.entries(h))k[x]={...R,deps:R.deps?.map(E=>b.get(E)??E)};a[m]={params:y,nodes:k,output:w};for(let x of p){delete n[x.name];let R={},E=new Set(Object.keys(x.nodes));for(let G of Object.values(x.nodes))for(let L of G.deps??[])if(!E.has(L)){let P=b.get(L)??`$${L}`;R[P]=L}u[x.name]={type:"template",template:m,bind:R}}}let l={...n,...u},f={name:e.name,nodes:l};return Object.keys(a).length>0&&(f.templates=a),r.length>0&&(f.feedback=r),f}function Bg(t,e){let n=[];t.name!==e.name&&n.push({type:"changed",path:"name",detail:`"${t.name}" \u2192 "${e.name}"`});let r=new Set(Object.keys(t.nodes)),o=new Set(Object.keys(e.nodes));for(let b of o)if(!r.has(b)){let v=e.nodes[b];n.push({type:"added",path:`nodes.${b}`,detail:`type: ${v.type}`})}for(let b of r)o.has(b)||n.push({type:"removed",path:`nodes.${b}`});for(let b of r){if(!o.has(b))continue;let v=t.nodes[b],T=e.nodes[b];if(JSON.stringify(v)!==JSON.stringify(T)){let w=[];v.type!==T.type&&w.push(`type: ${v.type} \u2192 ${T.type}`),JSON.stringify(v.deps)!==JSON.stringify(T.deps)&&w.push("deps changed"),v.fn!==T.fn&&w.push(`fn: ${v.fn} \u2192 ${T.fn}`),JSON.stringify(v.config)!==JSON.stringify(T.config)&&w.push("config changed"),n.push({type:"changed",path:`nodes.${b}`,detail:w.join("; ")||"modified"})}}let s=t.templates??{},i=e.templates??{},a=new Set(Object.keys(s)),u=new Set(Object.keys(i));for(let b of u)a.has(b)||n.push({type:"added",path:`templates.${b}`});for(let b of a)u.has(b)||n.push({type:"removed",path:`templates.${b}`});for(let b of a)u.has(b)&&JSON.stringify(s[b])!==JSON.stringify(i[b])&&n.push({type:"changed",path:`templates.${b}`,detail:"template definition changed"});let c=t.feedback??[],d=e.feedback??[],l=new Set(c.map(b=>`${b.from}->${b.to}`)),f=new Set(d.map(b=>`${b.from}->${b.to}`));for(let b of d){let v=`${b.from}->${b.to}`;l.has(v)||n.push({type:"added",path:`feedback.${v}`,detail:`maxIterations: ${b.maxIterations??10}`})}for(let b of c){let v=`${b.from}->${b.to}`;f.has(v)||n.push({type:"removed",path:`feedback.${v}`})}for(let b of c){let v=`${b.from}->${b.to}`,T=d.find(w=>w.from===b.from&&w.to===b.to);T&&JSON.stringify(b)!==JSON.stringify(T)&&n.push({type:"changed",path:`feedback.${v}`,detail:`maxIterations: ${b.maxIterations??10} \u2192 ${T.maxIterations??10}`})}let p=n.filter(b=>b.type==="added").length,m=n.filter(b=>b.type==="removed").length,h=n.filter(b=>b.type==="changed").length,g=[];p&&g.push(`${p} added`),m&&g.push(`${m} removed`),h&&g.push(`${h} changed`);let y=g.length>0?g.join(", "):"no changes";return{entries:n,summary:y}}var sp=`You are a graph architect for GraphReFly, a reactive graph protocol.
128
129
 
129
130
  Given a natural-language description, produce a JSON GraphSpec with this structure:
130
131
 
@@ -166,20 +167,20 @@ Rules:
166
167
  - Use "templates" when the same subgraph pattern repeats (e.g., per-source resilience).
167
168
  - Use "feedback" for bounded cycles where a derived value writes back to a state node.
168
169
  - meta.description is required for every node.
169
- - Return ONLY valid JSON, no markdown fences or commentary.`;function Kl(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}async function Zh(t,e,n){let r=jl,o=n?.catalogDescription??(n?.catalog?Bl(n.catalog):void 0);o&&(r+=`
170
+ - Return ONLY valid JSON, no markdown fences or commentary.`;function ip(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}async function jg(t,e,n){let r=sp,o=n?.catalogDescription??(n?.catalog?op(n.catalog):void 0);o&&(r+=`
170
171
 
171
172
  Available catalog (use ONLY these names):
172
173
  ${o}`),n?.systemPromptExtra&&(r+=`
173
174
 
174
- ${n.systemPromptExtra}`);let s=[{role:"system",content:r},{role:"user",content:t}],u=(await e.invoke(s,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens})).content.trim();u.startsWith("```")&&(u=Kl(u));let c;try{c=JSON.parse(u)}catch{throw new Error(`llmCompose: LLM response is not valid JSON: ${u.slice(0,200)}`)}let d=Un(c);if(!d.valid)throw new Error(`llmCompose: invalid GraphSpec:
175
+ ${n.systemPromptExtra}`);let s=[{role:"system",content:r},{role:"user",content:t}],u=(await e.invoke(s,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens})).content.trim();u.startsWith("```")&&(u=ip(u));let c;try{c=JSON.parse(u)}catch{throw new Error(`llmCompose: LLM response is not valid JSON: ${u.slice(0,200)}`)}let d=Xn(c);if(!d.valid)throw new Error(`llmCompose: invalid GraphSpec:
175
176
  ${d.errors.join(`
176
- `)}`);let l=c;if(n?.catalog){let f=n.maxAutoRefine??0;for(let p=0;p<=f;p++){let m=qr(l,n.catalog);if(m.valid)break;if(p===f)throw new Error(`llmCompose: catalog validation failed after ${f} refine attempts:
177
+ `)}`);let l=c;if(n?.catalog){let f=n.maxAutoRefine??0;for(let p=0;p<=f;p++){let m=zr(l,n.catalog);if(m.valid)break;if(p===f)throw new Error(`llmCompose: catalog validation failed after ${f} refine attempts:
177
178
  ${m.errors.join(`
178
- `)}`);l=await Vl(l,`Fix these catalog errors:
179
+ `)}`);l=await ap(l,`Fix these catalog errors:
179
180
  ${m.errors.join(`
180
181
  `)}
181
182
 
182
- Use ONLY functions and sources from the catalog.`,e,{...n,catalogDescription:o})}}return l}async function Vl(t,e,n,r){let o=jl;r?.catalogDescription&&(o+=`
183
+ Use ONLY functions and sources from the catalog.`,e,{...n,catalogDescription:o})}}return l}async function ap(t,e,n,r){let o=sp;r?.catalogDescription&&(o+=`
183
184
 
184
185
  Available catalog:
185
186
  ${r.catalogDescription}`),r?.systemPromptExtra&&(o+=`
@@ -189,9 +190,9 @@ ${JSON.stringify(t,null,2)}
189
190
 
190
191
  Modification request: ${e}
191
192
 
192
- Return the complete modified GraphSpec as JSON.`}],u=(await n.invoke(s,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens})).content.trim();u.startsWith("```")&&(u=Kl(u));let c;try{c=JSON.parse(u)}catch{throw new Error(`llmRefine: LLM response is not valid JSON: ${u.slice(0,200)}`)}let d=Un(c);if(!d.valid)throw new Error(`llmRefine: invalid GraphSpec:
193
+ Return the complete modified GraphSpec as JSON.`}],u=(await n.invoke(s,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens})).content.trim();u.startsWith("```")&&(u=ip(u));let c;try{c=JSON.parse(u)}catch{throw new Error(`llmRefine: LLM response is not valid JSON: ${u.slice(0,200)}`)}let d=Xn(c);if(!d.valid)throw new Error(`llmRefine: invalid GraphSpec:
193
194
  ${d.errors.join(`
194
- `)}`);return c}var As={};he(As,{GuardedExecutionGraph:()=>Cs,guardedExecution:()=>eg});var Cs=class extends z{enforcer;violations;_target;_defaultActor;constructor(e,n){super(n.name??`${e.name}_guarded`,n.graph),this._target=e,this._defaultActor=n.actor;let r={mode:n.mode??"enforce",name:"enforcer"};n.violationsLimit!=null&&(r.violationsLimit=n.violationsLimit),this.enforcer=wa(e,n.policies,r),this.violations=this.enforcer.violations,this.mount("enforcer",this.enforcer)}scopedDescribe(e){let n=e?.actor??this._defaultActor,r={...e,...n!=null?{actor:n}:{}};return this._target.describe(r)}get target(){return this._target}};function eg(t,e){return new Cs(t,e)}var Is={};he(Is,{DEFAULT_DECAY_RATE:()=>Ia,DEFAULT_QUEUE_CONFIGS:()=>Pa,DEFAULT_SEVERITY_WEIGHTS:()=>La,HarnessGraph:()=>Ls,QUEUE_NAMES:()=>Kt,affectedTaskFilter:()=>sg,beforeAfterCompare:()=>og,codeChangeBridge:()=>ig,createIntakeBridge:()=>tg,defaultErrorClassifier:()=>Aa,evalIntakeBridge:()=>ng,evalSource:()=>rg,harnessLoop:()=>pg,harnessProfile:()=>fg,harnessTrace:()=>hg,notifyEffect:()=>ag,priorityScore:()=>ug,strategyKey:()=>Hr,strategyModel:()=>Da});le();$e();function tg(t,e,n,r){return fe([t],([o])=>{if(o==null)return;let s=n(o);for(let i of s)e.publish(i)},{name:r?.name??"intake-bridge"})}function ng(t,e,n){let r=n?.defaultSeverity??"medium";return fe([t],([o])=>{if(o==null)return;let s=Array.isArray(o)?o:[o];for(let i of s)for(let a of i.tasks)if(!(a.valid&&a.judge_scores?.every(u=>u.pass))){if(!a.valid&&(!a.judge_scores||a.judge_scores.length===0)){e.publish({source:"eval",summary:`Task ${a.task_id} invalid (model: ${i.model})`,evidence:`Run ${i.run_id}: task produced invalid output`,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:r});continue}if(a.judge_scores)for(let u of a.judge_scores)u.pass||e.publish({source:"eval",summary:`${a.task_id}: ${u.claim} (model: ${i.model})`,evidence:u.reasoning,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:r})}},{name:n?.name??"eval-intake-bridge"})}function rg(t,e){return _e(t,()=>re(e()))}function og(t,e){return A([t,e],([n,r])=>{let o=n,s=r,i=new Map(o.tasks.map(f=>[f.task_id,f])),a=new Map(s.tasks.map(f=>[f.task_id,f])),u=new Set([...i.keys(),...a.keys()]),c=[],d=[],l=[];for(let f of u){let p=i.get(f),m=a.get(f),h=p?.valid??!1,g=m?.valid??!1,y=p?.judge_scores?p.judge_scores.filter(T=>T.pass).length:void 0,b=m?.judge_scores?m.judge_scores.filter(T=>T.pass).length:void 0,v=y!==void 0&&b!==void 0?b-y:void 0;c.push({taskId:f,before:h,after:g,scoreDiff:v}),h&&!g&&d.push(f),!h&&g&&l.push(f)}return{newFailures:d,resolved:l,taskDeltas:c,overallImproved:l.length>d.length}},{name:"eval-delta"})}function sg(t,e){let n=e==null?null:Array.isArray(e)?N(e):e,r=[t];return n&&r.push(n),A(r,o=>{let s=o[0],i=n?new Set(o[1]):null,a=new Set;for(let u of s)for(let c of u.affectsEvalTasks??[])(i==null||i.has(c))&&a.add(c);return[...a].sort()},{name:"affected-task-filter"})}function ig(t,e,n,r){let o=r?.defaultSeverity??"high";function s(a){let u=[];for(let c of a.lintErrors??[])u.push({source:"code-change",summary:`Lint: ${c.rule} in ${c.file}:${c.line}`,evidence:c.message,affectsAreas:[c.file],severity:o});for(let c of a.testFailures??[])u.push({source:"test",summary:`Test failure: ${c.testId}`,evidence:c.message,affectsAreas:[c.file],affectsEvalTasks:[c.testId],severity:o});return u}let i=n??s;return fe([t],([a])=>{if(a!=null)for(let u of i(a))e.publish(u)},{name:r?.name??"code-change-bridge"})}function ag(t,e,n){return fe([t.latest],([r])=>{r!=null&&e(r)},{name:n?.name??"notify-effect"})}we();le();Te();le();var Kt=["auto-fix","needs-decision","investigation","backlog"];function Hr(t,e){return`${t}\u2192${e}`}function Aa(t){let e=t.detail.toLowerCase();return e.includes("parse")||e.includes("json")||e.includes("config")||e.includes("validation")||e.includes("syntax")?"self-correctable":"structural"}var La={critical:100,high:70,medium:40,low:10},Ia=Math.LN2/(168*3600),Pa={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1,startOpen:!1}};function Da(){let t=tt({name:"strategy-entries"}),e=A([t.entries],([i])=>{let a=i;return new Map(a)},{name:"strategy-model",equals:(i,a)=>{let u=i,c=a;if(u.size!==c.size)return!1;for(let[d,l]of u){let f=c.get(d);if(!f||l.attempts!==f.attempts||l.successes!==f.successes)return!1}return!0}});function n(i,a,u){let c=Hr(i,a),d=t.get(c),l=(d?.attempts??0)+1,f=(d?.successes??0)+(u?1:0);t.set(c,{rootCause:i,intervention:a,attempts:l,successes:f,successRate:f/l})}function r(i,a){return t.get(Hr(i,a))}let o=e.subscribe(()=>{});function s(){o()}return{node:e,record:n,lookup:r,dispose:s}}function ug(t,e,n,r,o){let s={...La,...o?.severityWeights},i=o?.decayRate??Ia,a=o?.effectivenessThreshold??.7,u=o?.effectivenessBoost??15,c=[t,e,n];return r&&c.push(r),A(c,d=>{let l=d[0],f=d[1],p=d[2],m=r?d[3]:0,h=s[l.severity??"medium"],g=(B()-p)/1e9,y=pn(h,g,i,0),b=Hr(l.rootCause,l.intervention),v=f.get(b);return v&&v.successRate>=a&&(y+=u),y+=m*20,y},{name:"priority-score"})}var cg=`You are a triage classifier for a reactive collaboration harness.
195
+ `)}`);return c}var Ds={};he(Ds,{GuardedExecutionGraph:()=>Ps,guardedExecution:()=>Vg});var Ps=class extends q{enforcer;violations;_target;_defaultActor;constructor(e,n){super(n.name??`${e.name}_guarded`,n.graph),this._target=e,this._defaultActor=n.actor;let r={mode:n.mode??"enforce",name:"enforcer"};n.violationsLimit!=null&&(r.violationsLimit=n.violationsLimit),this.enforcer=Aa(e,n.policies,r),this.violations=this.enforcer.violations,this.mount("enforcer",this.enforcer)}scopedDescribe(e){let n=e?.actor??this._defaultActor,r={...e,...n!=null?{actor:n}:{}};return this._target.describe(r)}get target(){return this._target}};function Vg(t,e){return new Ps(t,e)}var $s={};he($s,{DEFAULT_DECAY_RATE:()=>Wa,DEFAULT_QUEUE_CONFIGS:()=>qa,DEFAULT_SEVERITY_WEIGHTS:()=>Ha,HarnessGraph:()=>Gs,QUEUE_NAMES:()=>Ht,affectedTaskFilter:()=>Ug,beforeAfterCompare:()=>qg,codeChangeBridge:()=>zg,createIntakeBridge:()=>Kg,defaultErrorClassifier:()=>Ka,defaultLlmExecutor:()=>up,defaultLlmVerifier:()=>cp,evalIntakeBridge:()=>Hg,evalSource:()=>Wg,evalVerifier:()=>Zg,harnessLoop:()=>oy,harnessProfile:()=>sy,harnessTrace:()=>my,notifyEffect:()=>Jg,priorityScore:()=>ey,refineExecutor:()=>py,strategyKey:()=>Jr,strategyModel:()=>Ua});oe();Re();function Kg(t,e,n,r){return fe([t],([o])=>{if(o==null)return;let s=n(o);for(let i of s)e.publish(i)},{name:r?.name??"intake-bridge"})}function Hg(t,e,n){let r=n?.defaultSeverity??"medium";return fe([t],([o])=>{if(o==null)return;let s=Array.isArray(o)?o:[o];for(let i of s)for(let a of i.tasks)if(!(a.valid&&a.judge_scores?.every(u=>u.pass))){if(!a.valid&&(!a.judge_scores||a.judge_scores.length===0)){e.publish({source:"eval",summary:`Task ${a.task_id} invalid (model: ${i.model})`,evidence:`Run ${i.run_id}: task produced invalid output`,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:r});continue}if(a.judge_scores)for(let u of a.judge_scores)u.pass||e.publish({source:"eval",summary:`${a.task_id}: ${u.claim} (model: ${i.model})`,evidence:u.reasoning,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:r})}},{name:n?.name??"eval-intake-bridge"})}function Wg(t,e){return be(t,()=>re(e()))}function qg(t,e){return O([t,e],([n,r])=>{let o=n,s=r,i=new Map(o.tasks.map(f=>[f.task_id,f])),a=new Map(s.tasks.map(f=>[f.task_id,f])),u=new Set([...i.keys(),...a.keys()]),c=[],d=[],l=[];for(let f of u){let p=i.get(f),m=a.get(f),h=p?.valid??!1,g=m?.valid??!1,y=p?.judge_scores?p.judge_scores.filter(T=>T.pass).length:void 0,b=m?.judge_scores?m.judge_scores.filter(T=>T.pass).length:void 0,v=y!==void 0&&b!==void 0?b-y:void 0;c.push({taskId:f,before:h,after:g,scoreDiff:v}),h&&!g&&d.push(f),!h&&g&&l.push(f)}return{newFailures:d,resolved:l,taskDeltas:c,overallImproved:l.length>d.length}},{name:"eval-delta"})}function Ug(t,e){let n=e==null?null:Array.isArray(e)?N(e):e,r=[t];return n&&r.push(n),O(r,o=>{let s=o[0],i=n?new Set(o[1]):null,a=new Set;for(let u of s)for(let c of u.affectsEvalTasks??[])(i==null||i.has(c))&&a.add(c);return[...a].sort()},{name:"affected-task-filter"})}function zg(t,e,n,r){let o=r?.defaultSeverity??"high";function s(a){let u=[];for(let c of a.lintErrors??[])u.push({source:"code-change",summary:`Lint: ${c.rule} in ${c.file}:${c.line}`,evidence:c.message,affectsAreas:[c.file],severity:o});for(let c of a.testFailures??[])u.push({source:"test",summary:`Test failure: ${c.testId}`,evidence:c.message,affectsAreas:[c.file],affectsEvalTasks:[c.testId],severity:o});return u}let i=n??s;return fe([t],([a])=>{if(a!=null)for(let u of i(a))e.publish(u)},{name:r?.name??"code-change-bridge"})}function Jg(t,e,n){return fe([t.latest],([r])=>{r!=null&&e(r)},{name:n?.name??"notify-effect"})}oe();function Yg(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let n of t)e+=n.score;return e/t.length}function Qg(t){let{passCount:e,total:n,meanScore:r,threshold:o,missingArtifact:s}=t,i=Number.isFinite(r)?r.toFixed(3):String(r),a=!s&&n>0&&r>=o,u=s?["EXECUTE stage did not emit an artifact; cannot verify reactively"]:a?[`${e}/${n} eval tasks passed; mean score ${i} \u2265 ${o}`]:n===0?["No eval tasks were selected for this item \u2014 cannot verify"]:[`${e}/${n} eval tasks passed; mean score ${i} < threshold ${o}`];return a?{verified:!0,findings:u}:{verified:!1,findings:u,errorClass:"structural"}}function Xg(t){return t.artifact}function Zg(t){let e=t.name??"eval-verifier",n=t.threshold??.5,r=t.toOutput??Qg,o=t.extractArtifact??Xg;return s=>{let i=ut(s,u=>u!=null&&u[0]!=null&&u[1]!=null),a=be(i,([u,c])=>{let d=o(u,c);if(d==null)return N(r({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:n,missingArtifact:!0}));let l=N([d],{name:`${e}/candidates`}),f=N(t.datasetFor(c),{name:`${e}/dataset`}),p=t.evaluator(l,f);return O([p],([m])=>{let h=m;if(h==null)return null;let g=Yg(h),y=h.filter(b=>b.score>=n).length;return r({scores:h,meanScore:g,passCount:y,total:h.length,threshold:n})},{name:`${e}/output`})},{name:e});return ut(a,u=>u!=null)}}xe();oe();ke();oe();var Ht=["auto-fix","needs-decision","investigation","backlog"];function Jr(t,e){return`${t}\u2192${e}`}function Ka(t){let e=t.detail.toLowerCase();return e.includes("parse")||e.includes("json")||e.includes("config")||e.includes("validation")||e.includes("syntax")?"self-correctable":"structural"}var Ha={critical:100,high:70,medium:40,low:10},Wa=Math.LN2/(168*3600),qa={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1,startOpen:!1}};function Ua(){let t=tt({name:"strategy-entries"}),e=O([t.entries],([i])=>{let a=i;return new Map(a)},{name:"strategy-model",equals:(i,a)=>{let u=i,c=a;if(u.size!==c.size)return!1;for(let[d,l]of u){let f=c.get(d);if(!f||l.attempts!==f.attempts||l.successes!==f.successes)return!1}return!0}});function n(i,a,u){let c=Jr(i,a),d=t.get(c),l=(d?.attempts??0)+1,f=(d?.successes??0)+(u?1:0);t.set(c,{rootCause:i,intervention:a,attempts:l,successes:f,successRate:f/l})}function r(i,a){return t.get(Jr(i,a))}let o=e.subscribe(()=>{});function s(){o()}return{node:e,record:n,lookup:r,dispose:s}}function ey(t,e,n,r,o){let s={...Ha,...o?.severityWeights},i=o?.decayRate??Wa,a=o?.effectivenessThreshold??.7,u=o?.effectivenessBoost??15,c=[t,e,n];return r&&c.push(r),O(c,d=>{let l=d[0],f=d[1],p=d[2],m=r?d[3]:0,h=s[l.severity??"medium"],g=($()-p)/1e9,y=vn(h,g,i,0),b=Jr(l.rootCause,l.intervention),v=f.get(b);return v&&v.successRate>=a&&(y+=u),y+=m*20,y},{name:"priority-score"})}var ty=`You are a triage classifier for a reactive collaboration harness.
195
196
 
196
197
  Given an intake item, classify it and output JSON:
197
198
  {
@@ -206,7 +207,7 @@ Strategy model (past effectiveness):
206
207
  {{strategy}}
207
208
 
208
209
  Intake item:
209
- {{item}}`,dg=`You are an implementation agent.
210
+ {{item}}`,ny=`You are an implementation agent.
210
211
 
211
212
  Given a triaged issue with root cause and intervention type, produce a fix.
212
213
 
@@ -217,7 +218,7 @@ Output JSON:
217
218
  {
218
219
  "outcome": "success" | "failure" | "partial",
219
220
  "detail": "<description of what was done or what failed>"
220
- }`,lg=`You are a QA reviewer.
221
+ }`,ry=`You are a QA reviewer.
221
222
 
222
223
  Given an execution result, verify whether the fix is correct.
223
224
 
@@ -232,11 +233,11 @@ Output JSON:
232
233
  "verified": true/false,
233
234
  "findings": ["<finding1>", ...],
234
235
  "errorClass": "self-correctable" | "structural" // only if verified=false
235
- }`,Ls=class extends z{intake;queues;gates;strategy;verifyResults;totalRetries;totalReingestions;constructor(e,n,r,o,s,i,a,u){super(e),this.intake=n,this.queues=r,this.gates=o,this.strategy=s,this.verifyResults=i,this.totalRetries=a,this.totalReingestions=u}};function pg(t,e){let n=e.adapter,r=e.maxRetries??2,o=e.retainedLimit??1e3,s=e.errorClassifier??Aa,i=new Map;for(let E of Kt)i.set(E,{...Pa[E],...e.queues?.[E]});let a=new nt("intake",{retainedLimit:o}),u=Da(),c=un(a.latest,u.node),d=Br(n,[c],e.triagePrompt??(E=>{let[I,G]=E;return I?cg.replace("{{strategy}}",JSON.stringify(Array.from(G.entries()))).replace("{{item}}",JSON.stringify(I)):""}),{name:"triage",format:"json",retries:1}),l=new Map;for(let E of Kt)l.set(E,new nt(`queue/${E}`,{retainedLimit:o}));let f=un(d,c),m=fe([f],([E])=>{if(E==null)return;let[I,G]=E;if(!I||!I.route)return;let U={...G?.[0],...I},ce=l.get(U.route);ce&&ce.publish(U)}).subscribe(()=>{}),h=new z("gates"),g=new Map;for(let E of Kt){let I=i.get(E),G=l.get(E);if(I.gated){h.add(G.latest,{name:`${E}/source`});let te=Dr(h,`${E}/gate`,`${E}/source`,{maxPending:I.maxPending,startOpen:I.startOpen});g.set(E,te)}}let y=new nt("retry-input",{retainedLimit:o}),b=[];for(let E of Kt)i.get(E).gated&&g.has(E)?b.push(g.get(E).node):b.push(l.get(E).latest);b.push(y.latest);let v=ft(...b),T=Br(n,[v],e.executePrompt??(E=>dg.replace("{{item}}",JSON.stringify(E))),{name:"execute",format:"json",retries:1}),w=un(T,v),k=new nt("verify-results",{retainedLimit:o}),x=Br(n,[w],e.verifyPrompt??(E=>{let[I,G]=E;return lg.replace("{{execution}}",JSON.stringify(I)).replace("{{item}}",JSON.stringify(G))}),{name:"verify",format:"json",retries:1}),S=un(x,w),_=e.maxReingestions??1,F=Math.min(e.maxTotalRetries??r*10,100),L=Math.min(e.maxTotalReingestions??_*10,100),D=N(0),C=N(0),ne=q([S],(E,I)=>{let G=E[0];if(G==null||G.length===0)return;let te=G[G.length-1];if(te==null)return;let[U,ce]=te,[j,V]=ce??[null,null];if(!U||!V)return;let J={item:V,outcome:j?.outcome??"failure",detail:j?.detail??"unknown"},Y={item:V,execution:J,verified:U.verified,findings:U.findings??[],errorClass:U.errorClass};if(Y.verified){u.record(V.rootCause,V.intervention,!0),k.publish(Y);return}let Q=Y.errorClass??s({item:V,outcome:"failure",detail:Y.findings.join("; ")}),W=V._retries??0;if(Q==="self-correctable"&&W<r&&Tr(D,F)){let ae=_i(V),ye={...V,_retries:W+1,summary:`[RETRY ${W+1}/${r}] ${ae} \u2014 Previous attempt failed: ${Y.findings.join("; ")}`,relatedTo:[ae]};y.publish(ye)}else{u.record(V.rootCause,V.intervention,!1),k.publish(Y);let ae=_i(V),ye=V._reingestions??0;ye<_&&Tr(C,L)&&a.publish({source:"eval",summary:`Verification failed for: ${ae}`,evidence:Y.findings.join(`
236
- `),affectsAreas:V.affectsAreas,affectsEvalTasks:V.affectsEvalTasks,severity:"high",relatedTo:[ae],_reingestions:ye+1})}}).subscribe(()=>{}),P=new Ls(t,a,l,g,u,k,D,C);P.addDisposer(m),P.addDisposer(ne),P.addDisposer(u.dispose),P.add(d,{name:"triage"}),P.add(T,{name:"execute"}),P.add(x,{name:"verify"}),P.add(u.node,{name:"strategy"}),P.mount("intake",a);for(let[E,I]of l)P.mount(`queue/${E}`,I);return P.mount("gates",h),P.mount("retry-input",y),P.mount("verify-results",k),P}function fg(t,e){let n=on(t,e),r={};for(let[o,s]of t.queues)r[o]=s.retained().length;return{...n,queueDepths:r,strategyEntries:t.strategy.node.cache?.size??0,totalRetries:t.totalRetries.cache??0,totalReingestions:t.totalReingestions.cache??0}}Te();function mg(t){let e={"intake::latest":"INTAKE",triage:"TRIAGE",execute:"EXECUTE","verify-results::latest":"VERIFY",strategy:"STRATEGY"};for(let n of Kt)e[`queue/${n}::latest`]="QUEUE";for(let[n]of t.gates)e[`gates::${n}/gate`]="GATE";return e}function hg(t,e){let n=e?.logger===null?null:e?.logger??console.log,r=e?.detail??"summary",o=B(),s=[],i=[],a=mg(t);function u(){return(B()-o)/1e9}function c(d,l,f){let p={elapsed:u(),stage:d,type:l};r!=="summary"&&(p.summary=gg(f)),r==="full"&&(p.data=f),i.push(p)}for(let[d,l]of Object.entries(a))try{let f=t.observe(d,{format:"stage-log",stageLabels:a,logger:n?p=>n(p):()=>{},includeTypes:["data","error","complete"]});f.onEvent(p=>{p.type==="data"?c(l,"data",p.data):p.type==="error"?c(l,"error",p.data):p.type==="complete"&&c(l,"complete",void 0)}),s.push(f)}catch(f){let p=f instanceof Error?f.message:String(f);c(l,"error",`observe-unavailable: ${d} \u2014 ${p}`),n&&n(`[${u().toFixed(3)}s] ${l.padEnd(9)} \u2717 observe-unavailable: ${p}`)}return{get events(){return i},dispose(){for(let d of s)d.dispose();s.length=0}}}function gg(t){if(t==null)return"null";if(typeof t=="string")return ql(t,80);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return ql(e,120)}catch{return String(t)}}function ql(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}var Gs={};he(Gs,{JobFlowGraph:()=>Ds,JobQueueGraph:()=>Ps,jobFlow:()=>bg,jobQueue:()=>Wl});we();var yg=2147483647;function Hl(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Ga(t,e){return Ke("job_queue",t,e)}var Ps=class extends z{_pending;_jobs;_seq=0;pending;jobs;depth;constructor(e,n={}){super(e,n.graph),this._pending=zo([],{name:"pending"}),this._jobs=tt({name:"jobs"}),this.pending=this._pending.items,this.jobs=this._jobs.entries,this.add(this.pending,{name:"pending"}),this.add(this.jobs,{name:"jobs"}),this.depth=A([this.pending],([r])=>r.length,{name:"depth",describeKind:"derived",meta:Ga("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(oe(this.depth))}enqueue(e,n={}){let r=n.id??`${this.name}-${++this._seq}`;if(this._jobs.get(r)!==void 0)throw new Error(`jobQueue("${this.name}"): duplicate job id "${r}"`);let o={id:r,payload:e,attempts:0,metadata:Object.freeze({...n.metadata??{}}),state:"queued"};return this._jobs.set(r,o),this._pending.append(r),r}claim(e=1){let n=Hl(e,"job queue claim limit");if(n===0)return[];let r=[];for(;r.length<n&&this.pending.cache.length!==0;){let s=this._pending.pop(0),i=this._jobs.get(s);if(!i||i.state!=="queued")continue;let a={...i,state:"inflight",attempts:i.attempts+1};this._jobs.set(s,a),r.push(a)}return r}ack(e){let n=this._jobs.get(e);return!n||n.state!=="inflight"?!1:(this._jobs.delete(e),!0)}nack(e,n={}){let r=this._jobs.get(e);return!r||r.state!=="inflight"?!1:n.requeue??!0?(this._jobs.set(e,{...r,state:"queued"}),this._pending.append(e),!0):(this._jobs.delete(e),!0)}},Ds=class extends z{_stageNames;_queues=new Map;_completed;completed;completedCount;constructor(e,n={}){super(e,n.graph);let r=(n.stages??["incoming","processing","done"]).map(i=>i.trim());if(r.length<2)throw new Error(`jobFlow("${e}"): requires at least 2 stages`);if(new Set(r).size!==r.length)throw new Error(`jobFlow("${e}"): stage names must be unique`);this._stageNames=Object.freeze([...r]);for(let i of this._stageNames){let a=Wl(`${e}-${i}`);this._queues.set(i,a),this.mount(i,a)}this._completed=je([],{name:"completed"}),this.completed=this._completed.entries,this.add(this.completed,{name:"completed"}),this.completedCount=A([this.completed],([i])=>i.length,{name:"completedCount",describeKind:"derived",meta:Ga("job_flow_completed_count"),initial:0}),this.add(this.completedCount,{name:"completedCount"}),this.addDisposer(oe(this.completedCount));let s=Math.max(1,Hl(n.maxPerPump??yg,"job flow maxPerPump"));for(let i=0;i<this._stageNames.length;i+=1){let a=this._stageNames[i],u=this.queue(a),c=i+1<this._stageNames.length?this.queue(this._stageNames[i+1]):null,d=q([u.pending],()=>{let l=0;for(;l<s;){let f=u.claim(1);if(f.length===0)break;let p=f[0];if(!p)break;c?c.enqueue(p.payload,{metadata:{...p.metadata,job_flow_from:a}}):this._completed.append(p),u.ack(p.id),l+=1}},{name:`pump_${a}`,describeKind:"effect",meta:Ga("job_flow_pump")});this.add(d,{name:`pump_${a}`}),this.addDisposer(oe(d))}}stages(){return this._stageNames}queue(e){let n=this._queues.get(e);if(!n)throw new Error(`jobFlow("${this.name}"): unknown stage "${e}"`);return n}enqueue(e,n={}){return this.queue(this._stageNames[0]).enqueue(e,n)}retainedCompleted(){return this.completed.cache}};function Wl(t,e){return new Ps(t,e)}function bg(t,e){return new Ds(t,e)}var $s={};he($s,{LensGraph:()=>Fs,graphLens:()=>xg,watchTopologyTree:()=>wt});Te();le();function Ul(t){return Ke("lens",t)}function vg(t){let e=Object.keys(t.nodes),n=new Map,r=new Map;for(let h of e){let g=t.nodes[h]?.deps??[];n.set(h,g);for(let y of g)r.has(y)||r.set(y,new Set),r.get(y).add(h)}let o=[],s=[];for(let h of e)(n.get(h)??[]).length===0&&o.push(h),r.has(h)||s.push(h);o.sort(),s.sort();let i=t.edges.length,a=0,u=1,c=2,d=new Map;for(let h of e)d.set(h,a);let l=!1,f=new Map,p=h=>{let g=d.get(h)??a;if(g===u)return l=!0,0;if(g===c)return f.get(h)??0;d.set(h,u);let y=0,b=r.get(h);if(b!=null)for(let v of b){let T=p(v);T+1>y&&(y=T+1)}return d.set(h,c),f.set(h,y),y},m=0;for(let h of o){let g=p(h);g>m&&(m=g)}for(let h of e)d.get(h)===a&&p(h);return{nodeCount:e.length,edgeCount:i,subgraphCount:t.subgraphs.length,sources:o,sinks:s,depth:m,hasCycles:l}}function Tg(t){let e=[];for(let[n,r]of Object.entries(t.nodes)){if(r.status!=="errored")continue;let o={path:n,status:"errored"},s=sn(t,n,"upstream",{});for(let i of s)if(i!==n&&t.nodes[i]?.status==="errored"){o.upstreamCause=i;break}e.push(o)}return e.sort((n,r)=>n.path<r.path?-1:n.path>r.path?1:0),{ok:e.length===0,problems:e}}function wg(t,e){return t.nodeCount===e.nodeCount&&t.edgeCount===e.edgeCount&&t.subgraphCount===e.subgraphCount&&t.depth===e.depth&&t.hasCycles===e.hasCycles&&zl(t.sources,e.sources)&&zl(t.sinks,e.sinks)}function kg(t,e){if(t.ok!==e.ok||t.problems.length!==e.problems.length)return!1;for(let n=0;n<t.problems.length;n++){let r=t.problems[n],o=e.problems[n];if(r.path!==o.path||r.status!==o.status||r.upstreamCause!==o.upstreamCause)return!1}return!0}function zl(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}var Fs=class extends z{stats;health;flow;_target;constructor(e,n={}){super(n.name??`${e.name}_lens`,n.graph),this._target=e;let r=0,o=0,s=N(0,{name:"stats_tick"}),i=N(0,{name:"health_tick"});this.add(s,{name:"stats_tick"}),this.add(i,{name:"health_tick"});let a={name:"flow"};n.maxFlowPaths!=null&&(a.maxSize=n.maxFlowPaths),this.flow=tt(a),this.add(this.flow.entries,{name:"flow"});let u=n.pathFilter,c=wt(e,(f,p,m)=>{if(r+=1,s.emit(r),o+=1,i.emit(o),f.kind==="removed")if(f.nodeKind==="node"){let h=`${m}${f.name}`;this.flow.delete(h)}else{let h=`${m}${f.name}::`,g=[];for(let y of f.audit.nodes){let b=y===""?`${m}${f.name}`:`${h}${y}`;g.push(b)}g.length>0&&this.flow.deleteMany(g)}});this.addDisposer(c);let d=e.observe({timeline:!0,structured:!0}),l=d.onEvent(f=>{let p=f.type;if((p==="error"||p==="complete"||p==="data"||p==="teardown")&&(o+=1,i.emit(o)),p==="data"){let m=f.path??"";if(!m||u!=null&&!u(m))return;let h=this.flow.get(m),g=h!=null?h.count+1:1;this.flow.set(m,{path:m,count:g,lastUpdate_ns:B()})}});this.addDisposer(()=>{l(),d.dispose()}),this.stats=A([s],()=>vg(e.describe({detail:"minimal"})),{name:"stats",describeKind:"derived",equals:wg,meta:Ul("stats")}),this.add(this.stats,{name:"stats"}),this.addDisposer(oe(this.stats)),this.health=A([i],()=>Tg(e.describe({detail:"standard"})),{name:"health",describeKind:"derived",equals:kg,meta:Ul("health")}),this.add(this.health,{name:"health"}),this.addDisposer(oe(this.health))}why(e,n,r){let o=ka(this._target,e,n,r);return this.addDisposer(o.dispose),o}get target(){return this._target}};function xg(t,e){return new Fs(t,e)}var Bs={};he(Bs,{CanvasMeasureAdapter:()=>ja,CliMeasureAdapter:()=>Fa,ImageSizeAdapter:()=>qa,NodeCanvasMeasureAdapter:()=>Ka,PrecomputedAdapter:()=>Ba,SvgBoundsAdapter:()=>Va,analyzeAndMeasure:()=>_t,carveTextLineSlots:()=>Na,circleIntervalForBand:()=>Zl,computeBlockFlow:()=>Ql,computeCharPositions:()=>Ss,computeFlowLines:()=>tp,computeLineBreaks:()=>gn,computeTotalHeight:()=>Xl,layoutNextLine:()=>Sa,measureBlock:()=>Jl,measureBlocks:()=>Yl,reactiveBlockLayout:()=>Ng,reactiveFlowLayout:()=>_g,reactiveLayout:()=>Fh,rectIntervalForBand:()=>ep});function Rg(t){return t>=768&&t<=879||t>=1155&&t<=1161||t>=1425&&t<=1469||t>=1552&&t<=1562||t>=1611&&t<=1631||t>=1648&&t===1648||t>=1750&&t<=1756||t>=1759&&t<=1764||t>=1767&&t<=1768||t>=1770&&t<=1773||t>=1840&&t<=1866||t>=1958&&t<=1968||t>=2304&&t<=2307||t>=2362&&t<=2383||t>=2385&&t<=2391||t>=2402&&t<=2403||t>=2433&&t<=2435||t>=2492&&t<=2509||t>=2561&&t<=2563||t>=2620&&t<=2641||t>=2672&&t<=2673||t>=2677&&t===2677||t>=3633&&t===3633||t>=3636&&t<=3642||t>=3655&&t<=3662||t>=3761&&t===3761||t>=3764&&t<=3772||t>=3784&&t<=3790||t>=7616&&t<=7679||t>=8400&&t<=8447||t>=65024&&t<=65039||t>=65056&&t<=65071||t===8205?0:t>=4352&&t<=4447||t>=8986&&t<=8987||t>=9001&&t<=9002||t>=9193&&t<=9203||t>=9208&&t<=9210||t>=9725&&t<=9726||t>=9748&&t<=9749||t>=9800&&t<=9811||t===9855||t===9875||t===9889||t>=9898&&t<=9899||t>=9917&&t<=9918||t>=9924&&t<=9925||t===9934||t===9940||t===9962||t>=9970&&t<=9971||t===9973||t===9978||t===9981||t===9986||t===9989||t>=9992&&t<=9997||t===9999||t>=10067&&t<=10069||t===10071||t>=10133&&t<=10135||t===10160||t===10175||t>=10548&&t<=10549||t>=11013&&t<=11015||t>=11035&&t<=11036||t===11088||t===11093||t>=11904&&t<=12350||t>=12352&&t<=12447||t>=12448&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12784&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=19968&&t<=40959||t>=43360&&t<=43388||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65131||t>=65281&&t<=65376||t>=65504&&t<=65510||t>=126980&&t===126980||t===127183||t>=127344&&t<=127345||t===127358||t===127359||t===127374||t>=127377&&t<=127386||t>=127456&&t<=127487||t>=127488&&t<=127490||t===127514||t===127535||t>=127538&&t<=127546||t>=127568&&t<=127569||t>=127744&&t<=129535||t>=129536&&t<=129791||t>=129792&&t<=130047||t>=131072&&t<=196605||t>=196608&&t<=262141?2:1}function Sg(t){let e=0;for(let n of t)e+=Rg(n.codePointAt(0));return e}var Fa=class{cellPx;constructor(e){this.cellPx=e?.cellPx??8}measureSegment(e,n){return{width:Sg(e)*this.cellPx}}},$a=class extends Error{name="KeyError"},Ba=class{metrics;fallback;constructor(e){this.metrics=e.metrics;let n=e.fallback??"per-char";if(n!=="per-char"&&n!=="error")throw new Error(`fallback must be 'per-char' or 'error', got ${JSON.stringify(e.fallback)}`);this.fallback=n}measureSegment(e,n){let r=this.metrics[n];if(r){let s=r[e];if(s!==void 0)return{width:s}}if(this.fallback==="error")throw new $a(`PrecomputedAdapter: no metrics for segment ${JSON.stringify(e)} in font ${JSON.stringify(n)}`);let o=0;if(r)for(let s of e){let i=r[s];i!==void 0&&(o+=i)}return{width:o}}},ja=class{ctx=null;currentFont="";emojiCorrection;constructor(e){this.emojiCorrection=e?.emojiCorrection??1}getContext(){if(!this.ctx){if(typeof OffscreenCanvas>"u")throw new Error("CanvasMeasureAdapter requires a browser environment with OffscreenCanvas support. Use CliMeasureAdapter or NodeCanvasMeasureAdapter for Node.js.");let n=new OffscreenCanvas(0,0).getContext("2d");if(!n)throw new Error("CanvasMeasureAdapter: failed to get 2d context");this.ctx=n}return this.ctx}measureSegment(e,n){let r=this.getContext();n!==this.currentFont&&(r.font=n,this.currentFont=n);let o=r.measureText(e).width;return this.emojiCorrection!==1&&new RegExp("\\p{Emoji_Presentation}","u").test(e)&&(o*=this.emojiCorrection),{width:o}}clearCache(){this.currentFont=""}},Ka=class{ctx=null;currentFont="";canvasModule;constructor(e){this.canvasModule=e}getContext(){if(!this.ctx){let n=this.canvasModule.createCanvas(0,0).getContext("2d");if(!n)throw new Error("NodeCanvasMeasureAdapter: failed to get 2d context");this.ctx=n}return this.ctx}measureSegment(e,n){let r=this.getContext();return n!==this.currentFont&&(r.font=n,this.currentFont=n),{width:r.measureText(e).width}}clearCache(){this.currentFont=""}},Va=class{measureSvg(e){let n=e.match(/viewBox\s*=\s*["']([^"']+)["']/);if(n){let s=n[1].trim().split(/[\s,]+/);if(s.length>=4){let i=Number.parseFloat(s[2]),a=Number.parseFloat(s[3]);if(Number.isFinite(i)&&Number.isFinite(a)&&i>0&&a>0)return{width:i,height:a};throw new Error("SvgBoundsAdapter: viewBox width/height are missing, non-finite, or not positive")}}let r=e.match(/<svg[^>]*\bwidth\s*=\s*["']?([\d.]+)/),o=e.match(/<svg[^>]*\bheight\s*=\s*["']?([\d.]+)/);if(r&&o){let s=Number.parseFloat(r[1]),i=Number.parseFloat(o[1]);if(Number.isFinite(s)&&Number.isFinite(i)&&s>0&&i>0)return{width:s,height:i};throw new Error("SvgBoundsAdapter: svg width/height attributes are non-finite or not positive")}throw new Error("SvgBoundsAdapter: cannot determine dimensions \u2014 SVG has no viewBox or width/height attributes")}},qa=class{sizes;constructor(e){this.sizes=new Map(Object.entries(e))}measureImage(e){let n=this.sizes.get(e);if(!n)throw new Error(`ImageSizeAdapter: no dimensions registered for ${JSON.stringify(e)}`);return{width:n.width,height:n.height}}};Te();we();le();function Jl(t,e,n,r,o,s,i){switch(t.type){case"text":{let a=t.font??o,u=t.lineHeight??s,c=_t(t.text,a,n.text,r),d=gn(c,e,n.text,a,r),l=Ss(d,c,u),f=d.lineCount*u,p=0;for(let m of d.lines)m.width>p&&(p=m.width);return{index:i,type:"text",width:Math.min(p,e),height:f,textSegments:c,textLineBreaks:d,textCharPositions:l}}case"image":{let a,u;if(t.naturalWidth!=null&&t.naturalHeight!=null)a=t.naturalWidth,u=t.naturalHeight;else if(n.image){let c=n.image.measureImage(t.src);a=c.width,u=c.height}else throw new Error(`Image block at index ${i} has no naturalWidth/naturalHeight and no ImageMeasurer adapter`);return a>e&&(u=u*e/a,a=e),{index:i,type:"image",width:a,height:u}}case"svg":{let a,u;if(t.viewBox)a=t.viewBox.width,u=t.viewBox.height;else if(n.svg){let c=n.svg.measureSvg(t.content);a=c.width,u=c.height}else throw new Error(`SVG block at index ${i} has no viewBox and no SvgMeasurer adapter`);return a>e&&(u=u*e/a,a=e),{index:i,type:"svg",width:a,height:u}}}}function Yl(t,e,n,r,o,s){return t.map((i,a)=>Jl(i,e,n,r,o,s,a))}function Ql(t,e){let n=[],r=0;for(let o=0;o<t.length;o++){let s=t[o];n.push({...s,x:0,y:r}),r+=s.height+(o<t.length-1?e:0)}return n}function Xl(t){if(t.length===0)return 0;let e=t[t.length-1];return e.y+e.height}function Ng(t){let{adapters:e,name:n="reactive-block-layout",defaultFont:r="16px sans-serif",defaultLineHeight:o=20}=t,s=new z(n),i=new Map,a=N(t.blocks??[],{name:"blocks"}),u=N(Math.max(0,t.maxWidth??800),{name:"max-width"}),c=N(t.gap??0,{name:"gap"}),d=q([a,u],(p,m,h)=>{let g=p[0]!=null&&p[0].length>0?p[0].at(-1):h.prevData[0],y=p[1]!=null&&p[1].length>0?p[1].at(-1):h.prevData[1],b=B(),v=Yl(g,y,e,i,r,o),T=B()-b,w=d.meta;w&&(at(w["block-count"],v.length),at(w["layout-time-ns"],T)),m.emit(v);let k=()=>{i.clear(),e.text.clearCache?.()};return{deactivate:k,invalidate:k}},{name:"measured-blocks",describeKind:"derived",meta:{"block-count":0,"layout-time-ns":0},equals:(p,m)=>{let h=p,g=m;if(h==null||g==null)return h===g;if(h.length!==g.length)return!1;for(let y=0;y<h.length;y++){let b=h[y],v=g[y];if(b.type!==v.type||b.width!==v.width||b.height!==v.height||b.index!==v.index)return!1}return!0}}),l=A([d,c],([p,m])=>Ql(p,m),{name:"block-flow",equals:(p,m)=>{let h=p,g=m;if(h==null||g==null)return h===g;if(h.length!==g.length)return!1;for(let y=0;y<h.length;y++){let b=h[y],v=g[y];if(b.x!==v.x||b.y!==v.y||b.width!==v.width||b.height!==v.height)return!1}return!0}}),f=A([l],([p])=>Xl(p),{name:"total-height"});return s.add(a,{name:"blocks"}),s.add(u,{name:"max-width"}),s.add(c,{name:"gap"}),s.add(d,{name:"measured-blocks"}),s.add(l,{name:"block-flow"}),s.add(f,{name:"total-height"}),{graph:s,setBlocks:p=>s.set("blocks",p),setMaxWidth:p=>s.set("max-width",Math.max(0,p)),setGap:p=>s.set("gap",p),measuredBlocks:d,blockFlow:l,totalHeight:f}}Te();we();le();function Zl(t,e,n){let r=t.hPad??0,o=t.vPad??0,s=e-o,i=n+o;if(s>=t.cy+t.r||i<=t.cy-t.r)return null;let a=t.cy>=s&&t.cy<=i?0:t.cy<s?s-t.cy:t.cy-i;if(a>=t.r)return null;let u=Math.sqrt(t.r*t.r-a*a);return{left:t.cx-u-r,right:t.cx+u+r}}function ep(t,e,n){let r=t.hPad??0,o=t.vPad??0;return n<=t.y-o||e>=t.y+t.h+o?null:{left:t.x-r,right:t.x+t.w+r}}function Eg(t,e,n){return t.kind==="circle"?Zl(t,e,n):ep(t,e,n)}function tp(t,e,n,r,o,s,i){let a=i?.paragraphSpacing??o,u=[],c={segmentIndex:0,graphemeIndex:0};if(t.length===0||n.count<=0||o<=0)return{lines:u,cursor:c};let d=e.paddingX??0,l=e.paddingY??0,f=Math.max(0,e.width-d*2),p=Math.max(0,e.height-l*2),m=n.gap*Math.max(0,n.count-1),h=Math.max(0,(f-m)/n.count);if(h<=0)return{lines:u,cursor:c};e:for(let g=0;g<n.count;g++){let y=d+g*(h+n.gap),b=y+h,v=l;for(;v+o<=l+p;){let T=v+o,w=[];for(let S=0;S<r.length;S++){let _=Eg(r[S],v,T);_!==null&&w.push(_)}let k=Na({left:y,right:b},w,s);if(k.length===0){v+=o;continue}let x=!1;for(let S=0;S<k.length;S++){let _=k[S],F=_.right-_.left,L=Sa(t,c,F);if(L===null)return{lines:u,cursor:c};if(L.text.length===0&&L.width===0){c=L.end,x=!0;break}u.push({x:_.left,y:v,width:L.width,slotWidth:F,text:L.text,columnIndex:g,flushToRight:_.right<b-.5}),c=L.end}if(x){v+=a;continue}if(v+=o,c.segmentIndex>=t.length)break e}if(c.segmentIndex>=t.length)break}return{lines:u,cursor:c}}function _g(t){let{adapter:e,name:n="reactive-flow-layout",minSlotWidth:r=20}=t,o=new z(n),s=new Map,i=N(t.text??"",{name:"text"}),a=N(t.font??"16px sans-serif",{name:"font"}),u=N(t.lineHeight??20,{name:"line-height"}),c=N(t.container??{width:800,height:600,paddingX:0,paddingY:0},{name:"container"}),d=N(t.columns??{count:1,gap:0},{name:"columns"}),l=N(t.obstacles??[],{name:"obstacles"}),f=N(t.paragraphSpacing??null,{name:"paragraph-spacing"}),p=q([i,a],(h,g,y)=>{let b=h[0],v=b!=null&&b.length>0?b.at(-1):y.prevData[0],T=h[1],w=T!=null&&T.length>0?T.at(-1):y.prevData[1],k=_t(v,w,e,s);g.emit(k);let x=()=>{s.clear(),e.clearCache?.()};return{deactivate:x,invalidate:x}},{name:"segments",describeKind:"derived"}),m=A([p,c,d,l,u,f],([h,g,y,b,v,T])=>{let w=h,k=B(),x=T??v,{lines:S,cursor:_}=tp(w,g,y,b,v,r,{paragraphSpacing:x}),F=B()-k,L=Math.max(0,w.length-_.segmentIndex),D=m.meta;return D&&(at(D["line-count"],S.length),at(D["layout-time-ns"],F),at(D["overflow-segments"],L)),S},{name:"flow-lines",meta:{"line-count":0,"layout-time-ns":0,"overflow-segments":0},equals:(h,g)=>{let y=h,b=g;if(y.length!==b.length)return!1;for(let v=0;v<y.length;v++){let T=y[v],w=b[v];if(T.x!==w.x||T.y!==w.y||T.width!==w.width||T.slotWidth!==w.slotWidth||T.text!==w.text||T.columnIndex!==w.columnIndex||T.flushToRight!==w.flushToRight)return!1}return!0}});return o.add(i,{name:"text"}),o.add(a,{name:"font"}),o.add(u,{name:"line-height"}),o.add(c,{name:"container"}),o.add(d,{name:"columns"}),o.add(l,{name:"obstacles"}),o.add(f,{name:"paragraph-spacing"}),o.add(p,{name:"segments"}),o.add(m,{name:"flow-lines"}),{graph:o,setText:h=>o.set("text",h),setFont:h=>o.set("font",h),setLineHeight:h=>o.set("line-height",h),setContainer:h=>o.set("container",h),setColumns:h=>o.set("columns",h),setObstacles:h=>o.set("obstacles",h),setParagraphSpacing:h=>o.set("paragraph-spacing",h),segments:p,flowLines:m}}var js={};he(js,{blindVariation:()=>Cg,errorCritique:()=>Ig,refineLoop:()=>Og});Se();Te();ie();we();le();function Mg(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.subscribe=="function"&&typeof e.down=="function"&&typeof e.emit=="function"}function np(t,e){if(t.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(t.length===1){let s=Ha(e);return{best:t[0],bestScore:s}}if(e.some(s=>typeof s.candidateIndex=="number")){let s=new Array(t.length);for(let u=0;u<t.length;u++)s[u]={sum:0,count:0};for(let u of e){let c=u.candidateIndex;typeof c=="number"&&c>=0&&c<t.length&&(s[c].sum+=u.score,s[c].count+=1)}let i=t[0],a=s[0].count>0?s[0].sum/s[0].count:Number.NEGATIVE_INFINITY;for(let u=1;u<t.length;u++){let c=s[u].count>0?s[u].sum/s[u].count:Number.NEGATIVE_INFINITY;c>a&&(a=c,i=t[u])}return{best:i,bestScore:a}}let r=t[0],o=e[0]?.score??Number.NEGATIVE_INFINITY;for(let s=1;s<t.length;s++){let i=e[s]?.score??Number.NEGATIVE_INFINITY;i>o&&(o=i,r=t[s])}return{best:r,bestScore:o}}function Ha(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let n of t)e+=n.score;return e/t.length}function Og(t,e,n,r){let o=r.name??"refine-loop",s=new z(o,r.graph),i=Mg(r.dataset)?r.dataset:N(r.dataset,{name:"dataset"});s.add(i,{name:"dataset"});let a=N(0,{name:"iteration"});s.add(a,{name:"iteration"});let u=N(n,{name:"strategy",equals:()=>!1});s.add(u,{name:"strategy"});let c=N(null,{name:"lastFeedback"});s.add(c,{name:"lastFeedback"});let d=N([],{name:"prevCandidates"});s.add(d,{name:"prevCandidates"});let l=N(!1,{name:"paused"});s.add(l,{name:"paused"});let f=N("running",{name:"status"});s.add(f,{name:"status"});let p=N([],{name:"history",equals:()=>!1});s.add(p,{name:"history"});let m=N(null,{name:"best"});s.add(m,{name:"best"});let h=N(Number.NEGATIVE_INFINITY,{name:"score"});s.add(h,{name:"score"});let g=N(0,{name:"budget-used"});s.add(g,{name:"budget-used"});let y=Rt("GENERATE"),b=Rt("EVALUATE"),v=Rt("ANALYZE"),T=Rt("DECIDE");s.mount("GENERATE",y),s.mount("EVALUATE",b),s.mount("ANALYZE",v),s.mount("DECIDE",T);let w=n,k=null,x=[];s.addDisposer(u.subscribe(J=>{for(let Y of J)Y[0]===R&&(w=Y[1])})),s.addDisposer(c.subscribe(J=>{for(let Y of J)Y[0]===R&&(k=Y[1])})),s.addDisposer(d.subscribe(J=>{for(let Y of J)Y[0]===R&&(x=Y[1])}));let S=_e(a,J=>{let Y=w,Q=J===0||k==null;return q([],(W,ae)=>{let ye=!1;try{let Fe=Q?Y.seed(t):Y.generate(k,x);if(Fe instanceof Promise)return Fe.then(ze=>{ye||ae.emit(ze)},ze=>{ye||ae.down([[O,ze]])}),()=>{ye=!0};ae.emit(Fe)}catch(Fe){ye=!0,ae.down([[O,Fe]])}},{describeKind:"producer"})},{name:"candidates"});s.add(S,{name:"candidates"});let _=fe([S],(J,Y,Q)=>{let W=Q.terminalDeps[0];W!==void 0&&W!==!0&&f.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});s.add(_,{name:"error-watcher"}),s.addDisposer(_.subscribe(()=>{}));let F=fe([S,a],([J,Y])=>{let Q=J,W=Y;ee(()=>{y.publish({iteration:W,candidates:Q,timestamp_ns:B()}),d.emit(Q)})},{name:"generate-bridge"});s.add(F,{name:"generate-bridge"}),s.addDisposer(F.subscribe(()=>{}));let L=e(S,i);s.add(L,{name:"scores"});let D=fe([L,S,a],([J,Y,Q])=>{b.publish({iteration:Q,candidates:Y,scores:J,timestamp_ns:B()})},{name:"evaluate-bridge"});s.add(D,{name:"evaluate-bridge"}),s.addDisposer(D.subscribe(()=>{}));let C=A([L,S],([J,Y])=>w.analyze(J,Y),{name:"feedback"});s.add(C,{name:"feedback"});let K=fe([C,S,a],([J,Y,Q])=>{v.publish({iteration:Q,candidates:Y,feedback:J,timestamp_ns:B()})},{name:"analyze-bridge"});s.add(K,{name:"analyze-bridge"}),s.addDisposer(K.subscribe(()=>{}));let ne=A([p],([J])=>{let Y=J;if(r.patience==null||Y.length<=r.patience)return!1;let Q=Y.slice(-(r.patience+1)),W=Q[0].bestScore;return Q.slice(1).every(ae=>ae.bestScore<=W)},{name:"patience-check"});s.add(ne,{name:"patience-check"});let P=A([h],([J])=>r.minScore!=null&&J>=r.minScore,{name:"min-score-check"});s.add(P,{name:"min-score-check"});let E=A([p],([J])=>{let Y=J;if(r.minDelta==null||Y.length<2)return!1;let Q=Y[Y.length-2].bestScore,W=Y[Y.length-1].bestScore;return Math.abs(W-Q)<r.minDelta},{name:"min-delta-check"});s.add(E,{name:"min-delta-check"});let I=A([g],([J])=>r.maxEvaluations!=null&&J>=r.maxEvaluations,{name:"max-evaluations-check"});s.add(I,{name:"max-evaluations-check"});let G=A([a],([J])=>r.maxIterations!=null&&J>=r.maxIterations,{name:"max-iterations-check"});s.add(G,{name:"max-iterations-check"});let te=A([g],([J])=>r.budget!=null&&J>=r.budget,{name:"budget-exhausted-check"});s.add(te,{name:"budget-exhausted-check"}),s.addDisposer(ne.subscribe(()=>{})),s.addDisposer(P.subscribe(()=>{})),s.addDisposer(E.subscribe(()=>{})),s.addDisposer(I.subscribe(()=>{})),s.addDisposer(G.subscribe(()=>{})),s.addDisposer(te.subscribe(()=>{}));let U=A([ne,P,E,I,G],([J,Y,Q,W,ae])=>J?{converged:!0,reason:"patience"}:Y?{converged:!0,reason:"min-score"}:Q?{converged:!0,reason:"min-delta"}:W?{converged:!0,reason:"max-evaluations"}:ae?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});s.add(U,{name:"converged"}),s.addDisposer(U.subscribe(()=>{}));let ce=-1,j=fe([C,L,S],([J,Y,Q])=>{let W=a.cache,ae=J,ye=Q,Fe=Y;if(W<=ce)return;ce=W;let{best:ze,bestScore:ht}=np(ye,Fe),Vt=p.cache,rt={n:W,candidates:ye,scores:Fe,feedback:ae,best:ze,bestScore:ht,timestamp_ns:B()},qe=[...Vt,rt],X=g.cache+ye.length,ue="continue",me,ke=r.budget!=null&&X>=r.budget,Ie=l.cache;if(ke)ue="budget",me="budget";else if(r.minScore!=null&&ae.score>=r.minScore)ue="converged",me="min-score";else if(r.maxIterations!=null&&W>=r.maxIterations)ue="converged",me="max-iterations";else if(r.maxEvaluations!=null&&X>=r.maxEvaluations)ue="converged",me="max-evaluations";else if(r.minDelta!=null&&qe.length>=2){let He=qe[qe.length-2].bestScore,be=qe[qe.length-1].bestScore;Math.abs(be-He)<r.minDelta&&(ue="converged",me="min-delta")}else if(r.patience!=null&&qe.length>r.patience){let He=qe.slice(-(r.patience+1)),be=He[0].bestScore;He.slice(1).every(ge=>ge.bestScore<=be)&&(ue="converged",me="patience")}ue==="continue"&&Ie&&(ue="paused"),ee(()=>{m.emit(ze),h.emit(ae.score),p.emit(qe),g.emit(X),c.emit(ae),T.publish({iteration:W,decision:ue,reason:me,timestamp_ns:B()}),ue==="continue"?a.emit(W+1):f.emit(ue==="converged"?"converged":ue==="budget"?"budget":"paused")})},{name:"decide-bridge"});return s.add(j,{name:"decide-bridge"}),s.addDisposer(j.subscribe(()=>{})),Object.assign(s,{best:m,score:h,status:f,history:p,strategy:u,iteration:a,generate:y,evaluate:b,analyze:v,decide:T,setStrategy(J){u.emit(J)},pause(){l.emit(!0)},resume(){f.cache==="paused"&&ee(()=>{l.emit(!1),f.emit("running"),a.emit(a.cache+1)})}})}function Cg(t){let e=t.width??4;return{name:t.name??"blindVariation",seed(r){return[r]},analyze(r,o){let s=Ha(r),i=null;for(let a of r)(!i||a.score<i.score)&&(i=a);return{summary:`blindVariation iteration: mean=${s.toFixed(3)}, n=${r.length}`,score:s,weakTasks:i?[i.taskId]:[]}},async generate(r,o){if(o.length===0)throw new Error("blindVariation.generate: empty candidate batch \u2014 cannot derive prior for teacher");let s=o[o.length-1],i=0,u={prior:s,reportCost:c=>{i+=c}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(u)));let c=[];for(let d=0;d<e;d++)c.push(await t.teacher(u));return c}finally{if(t.tokens!=null&&i>0){let c=t.tokens.cache??0;t.tokens.emit(c+i)}}}}}function Ag(t){return typeof t=="object"&&t!==null&&t.kind==="errorCritique"}function Lg(t,e){return t.length===0?`No task scored below the batch mean (${e.score.toFixed(3)}). Reinforce the current direction.`:`Failures below threshold:
236
+ }`;function up(t,e){let n=e??(r=>ny.replace("{{item}}",JSON.stringify(r)));return r=>Br(t,[r],n,{name:"execute",format:"json",retries:1})}function cp(t,e){let n=e??(r=>{let[o,s]=r;return ry.replace("{{execution}}",JSON.stringify(o)).replace("{{item}}",JSON.stringify(s))});return r=>Br(t,[r],n,{name:"verify",format:"json",retries:1})}var Gs=class extends q{intake;queues;gates;strategy;verifyResults;totalRetries;totalReingestions;constructor(e,n,r,o,s,i,a,u){super(e),this.intake=n,this.queues=r,this.gates=o,this.strategy=s,this.verifyResults=i,this.totalRetries=a,this.totalReingestions=u}};function oy(t,e){let n=e.adapter,r=e.maxRetries??2,o=e.retainedLimit??1e3,s=e.errorClassifier??Ka,i=new Map;for(let I of Ht)i.set(I,{...qa[I],...e.queues?.[I]});let a=new nt("intake",{retainedLimit:o}),u=Ua(),c=dn(a.latest,u.node),d=Br(n,[c],e.triagePrompt??(I=>{let[Q,U]=I;return Q?ty.replace("{{strategy}}",JSON.stringify(Array.from(U.entries()))).replace("{{item}}",JSON.stringify(Q)):""}),{name:"triage",format:"json",retries:1}),l=new Map;for(let I of Ht)l.set(I,new nt(`queue/${I}`,{retainedLimit:o}));let f=dn(d,c),m=fe([f],([I])=>{if(I==null)return;let[Q,U]=I;if(!Q?.route)return;let ae=U?.[0],j={...Q,...ae},Y=l.get(j.route);Y&&Y.publish(j)}).subscribe(()=>{}),h=new q("gates"),g=new Map;for(let I of Ht){let Q=i.get(I),U=l.get(I);if(Q.gated){h.add(U.latest,{name:`${I}/source`});let ae=Vr(h,`${I}/gate`,`${I}/source`,{maxPending:Q.maxPending,startOpen:Q.startOpen});g.set(I,ae)}}let y=new nt("retry-input",{retainedLimit:o}),b=[];for(let I of Ht)i.get(I).gated&&g.has(I)?b.push(g.get(I).node):b.push(l.get(I).latest);b.push(y.latest);let v=mt(...b),w=(e.executor??up(n,e.executePrompt))(v),k=dn(w,v),x=new nt("verify-results",{retainedLimit:o}),E=(e.verifier??cp(n,e.verifyPrompt))(k),G=dn(E,k),L=e.maxReingestions??1,P=Math.min(e.maxTotalRetries??r*10,100),C=Math.min(e.maxTotalReingestions??L*10,100),V=N(0),ne=N(0),A=K([G],(I,Q)=>{let U=I[0];if(U==null||U.length===0)return;let ae=U[U.length-1];if(ae==null)return;let[j,Y]=ae,[J,z]=Y??[null,null];if(!j||!z)return;let X={item:z,outcome:J?.outcome??"failure",detail:J?.detail??"unknown",artifact:J?.artifact},H={item:z,execution:X,verified:j.verified,findings:j.findings??[],errorClass:j.errorClass};if(H.verified){u.record(z.rootCause,z.intervention,!0),x.publish(H);return}let le=H.errorClass??s({item:z,outcome:"failure",detail:H.findings.join("; ")}),ve=z._retries??0;if(le==="self-correctable"&&ve<r&&Sr(V,P)){let Oe=Li(z),Be={...z,_retries:ve+1,summary:`[RETRY ${ve+1}/${r}] ${Oe} \u2014 Previous attempt failed: ${H.findings.join("; ")}`,relatedTo:[Oe]};y.publish(Be)}else{u.record(z.rootCause,z.intervention,!1),x.publish(H);let Oe=Li(z),Be=z._reingestions??0;Be<L&&Sr(ne,C)&&a.publish({source:"eval",summary:`Verification failed for: ${Oe}`,evidence:H.findings.join(`
237
+ `),affectsAreas:z.affectsAreas,affectsEvalTasks:z.affectsEvalTasks,severity:"high",relatedTo:[Oe],_reingestions:Be+1})}}).subscribe(()=>{}),D=new Gs(t,a,l,g,u,x,V,ne);D.addDisposer(m),D.addDisposer(A),D.addDisposer(u.dispose),D.add(d,{name:"triage"}),D.add(w,{name:"execute"}),D.add(E,{name:"verify"}),D.add(u.node,{name:"strategy"}),D.mount("intake",a);for(let[I,Q]of l)D.mount(`queue/${I}`,Q);return D.mount("gates",h),D.mount("retry-input",y),D.mount("verify-results",x),D}function sy(t,e){let n=an(t,e),r={};for(let[o,s]of t.queues)r[o]=s.retained().length;return{...n,queueDepths:r,strategyEntries:t.strategy.node.cache?.size??0,totalRetries:t.totalRetries.cache??0,totalReingestions:t.totalReingestions.cache??0}}oe();var Fs={};he(Fs,{blindVariation:()=>ay,errorCritique:()=>dy,refineLoop:()=>Ja});Ne();ke();ie();xe();oe();function iy(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.subscribe=="function"&&typeof e.down=="function"&&typeof e.emit=="function"}function dp(t,e){if(t.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(t.length===1){let s=za(e);return{best:t[0],bestScore:s}}if(e.some(s=>typeof s.candidateIndex=="number")){let s=new Array(t.length);for(let u=0;u<t.length;u++)s[u]={sum:0,count:0};for(let u of e){let c=u.candidateIndex;typeof c=="number"&&c>=0&&c<t.length&&(s[c].sum+=u.score,s[c].count+=1)}let i=t[0],a=s[0].count>0?s[0].sum/s[0].count:Number.NEGATIVE_INFINITY;for(let u=1;u<t.length;u++){let c=s[u].count>0?s[u].sum/s[u].count:Number.NEGATIVE_INFINITY;c>a&&(a=c,i=t[u])}return{best:i,bestScore:a}}let r=t[0],o=e[0]?.score??Number.NEGATIVE_INFINITY;for(let s=1;s<t.length;s++){let i=e[s]?.score??Number.NEGATIVE_INFINITY;i>o&&(o=i,r=t[s])}return{best:r,bestScore:o}}function za(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let n of t)e+=n.score;return e/t.length}function Ja(t,e,n,r){let o=r.name??"refine-loop",s=new q(o,r.graph),i=iy(r.dataset)?r.dataset:N(r.dataset,{name:"dataset"});s.add(i,{name:"dataset"});let a=N(0,{name:"iteration"});s.add(a,{name:"iteration"});let u=N(n,{name:"strategy",equals:()=>!1});s.add(u,{name:"strategy"});let c=N(null,{name:"lastFeedback"});s.add(c,{name:"lastFeedback"});let d=N([],{name:"prevCandidates"});s.add(d,{name:"prevCandidates"});let l=N(!1,{name:"paused"});s.add(l,{name:"paused"});let f=N("running",{name:"status"});s.add(f,{name:"status"});let p=N([],{name:"history",equals:()=>!1});s.add(p,{name:"history"});let m=N(null,{name:"best"});s.add(m,{name:"best"});let h=N(Number.NEGATIVE_INFINITY,{name:"score"});s.add(h,{name:"score"});let g=N(0,{name:"budget-used"});s.add(g,{name:"budget-used"});let y=Et("GENERATE"),b=Et("EVALUATE"),v=Et("ANALYZE"),T=Et("DECIDE");s.mount("GENERATE",y),s.mount("EVALUATE",b),s.mount("ANALYZE",v),s.mount("DECIDE",T);let w=n,k=null,x=[];s.addDisposer(u.subscribe(J=>{for(let z of J)z[0]===S&&(w=z[1])})),s.addDisposer(c.subscribe(J=>{for(let z of J)z[0]===S&&(k=z[1])})),s.addDisposer(d.subscribe(J=>{for(let z of J)z[0]===S&&(x=z[1])}));let R=be(a,J=>{let z=w,X=J===0||k==null;return K([],(H,le)=>{let ve=!1;try{let Oe=X?z.seed(t):z.generate(k,x);if(Oe instanceof Promise)return Oe.then(Be=>{ve||le.emit(Be)},Be=>{ve||le.down([[M,Be]])}),()=>{ve=!0};le.emit(Oe)}catch(Oe){ve=!0,le.down([[M,Oe]])}},{describeKind:"producer"})},{name:"candidates"});s.add(R,{name:"candidates"});let E=fe([R],(J,z,X)=>{let H=X.terminalDeps[0];H!==void 0&&H!==!0&&f.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});s.add(E,{name:"error-watcher"}),s.addDisposer(E.subscribe(()=>{}));let G=fe([R,a],([J,z])=>{let X=J,H=z;te(()=>{y.publish({iteration:H,candidates:X,timestamp_ns:$()}),d.emit(X)})},{name:"generate-bridge"});s.add(G,{name:"generate-bridge"}),s.addDisposer(G.subscribe(()=>{}));let L=e(R,i);s.add(L,{name:"scores"});let P=fe([L,R,a],([J,z,X])=>{b.publish({iteration:X,candidates:z,scores:J,timestamp_ns:$()})},{name:"evaluate-bridge"});s.add(P,{name:"evaluate-bridge"}),s.addDisposer(P.subscribe(()=>{}));let C=O([L,R],([J,z])=>w.analyze(J,z),{name:"feedback"});s.add(C,{name:"feedback"});let V=fe([C,R,a],([J,z,X])=>{v.publish({iteration:X,candidates:z,feedback:J,timestamp_ns:$()})},{name:"analyze-bridge"});s.add(V,{name:"analyze-bridge"}),s.addDisposer(V.subscribe(()=>{}));let ne=O([p],([J])=>{let z=J;if(r.patience==null||z.length<=r.patience)return!1;let X=z.slice(-(r.patience+1)),H=X[0].bestScore;return X.slice(1).every(le=>le.bestScore<=H)},{name:"patience-check"});s.add(ne,{name:"patience-check"});let F=O([h],([J])=>r.minScore!=null&&J>=r.minScore,{name:"min-score-check"});s.add(F,{name:"min-score-check"});let A=O([p],([J])=>{let z=J;if(r.minDelta==null||z.length<2)return!1;let X=z[z.length-2].bestScore,H=z[z.length-1].bestScore;return Math.abs(H-X)<r.minDelta},{name:"min-delta-check"});s.add(A,{name:"min-delta-check"});let D=O([g],([J])=>r.maxEvaluations!=null&&J>=r.maxEvaluations,{name:"max-evaluations-check"});s.add(D,{name:"max-evaluations-check"});let I=O([a],([J])=>r.maxIterations!=null&&J>=r.maxIterations,{name:"max-iterations-check"});s.add(I,{name:"max-iterations-check"});let Q=O([g],([J])=>r.budget!=null&&J>=r.budget,{name:"budget-exhausted-check"});s.add(Q,{name:"budget-exhausted-check"}),s.addDisposer(ne.subscribe(()=>{})),s.addDisposer(F.subscribe(()=>{})),s.addDisposer(A.subscribe(()=>{})),s.addDisposer(D.subscribe(()=>{})),s.addDisposer(I.subscribe(()=>{})),s.addDisposer(Q.subscribe(()=>{}));let U=O([ne,F,A,D,I],([J,z,X,H,le])=>J?{converged:!0,reason:"patience"}:z?{converged:!0,reason:"min-score"}:X?{converged:!0,reason:"min-delta"}:H?{converged:!0,reason:"max-evaluations"}:le?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});s.add(U,{name:"converged"}),s.addDisposer(U.subscribe(()=>{}));let ae=-1,j=fe([C,L,R],([J,z,X])=>{let H=a.cache,le=J,ve=X,Oe=z;if(H<=ae)return;ae=H;let{best:Be,bestScore:gt}=dp(ve,Oe),Wt=p.cache,rt={n:H,candidates:ve,scores:Oe,feedback:le,best:Be,bestScore:gt,timestamp_ns:$()},We=[...Wt,rt],Z=g.cache+ve.length,ue="continue",me,Se=r.budget!=null&&Z>=r.budget,De=l.cache;if(Se)ue="budget",me="budget";else if(r.minScore!=null&&le.score>=r.minScore)ue="converged",me="min-score";else if(r.maxIterations!=null&&H>=r.maxIterations)ue="converged",me="max-iterations";else if(r.maxEvaluations!=null&&Z>=r.maxEvaluations)ue="converged",me="max-evaluations";else if(r.minDelta!=null&&We.length>=2){let qe=We[We.length-2].bestScore,Te=We[We.length-1].bestScore;Math.abs(Te-qe)<r.minDelta&&(ue="converged",me="min-delta")}else if(r.patience!=null&&We.length>r.patience){let qe=We.slice(-(r.patience+1)),Te=qe[0].bestScore;qe.slice(1).every(ye=>ye.bestScore<=Te)&&(ue="converged",me="patience")}ue==="continue"&&De&&(ue="paused"),te(()=>{m.emit(Be),h.emit(le.score),p.emit(We),g.emit(Z),c.emit(le),T.publish({iteration:H,decision:ue,reason:me,timestamp_ns:$()}),ue==="continue"?a.emit(H+1):f.emit(ue==="converged"?"converged":ue==="budget"?"budget":"paused")})},{name:"decide-bridge"});return s.add(j,{name:"decide-bridge"}),s.addDisposer(j.subscribe(()=>{})),Object.assign(s,{best:m,score:h,status:f,history:p,strategy:u,iteration:a,generate:y,evaluate:b,analyze:v,decide:T,setStrategy(J){u.emit(J)},pause(){l.emit(!0)},resume(){f.cache==="paused"&&te(()=>{l.emit(!1),f.emit("running"),a.emit(a.cache+1)})}})}function ay(t){let e=t.width??4;return{name:t.name??"blindVariation",seed(r){return[r]},analyze(r,o){let s=za(r),i=null;for(let a of r)(!i||a.score<i.score)&&(i=a);return{summary:`blindVariation iteration: mean=${s.toFixed(3)}, n=${r.length}`,score:s,weakTasks:i?[i.taskId]:[]}},async generate(r,o){if(o.length===0)throw new Error("blindVariation.generate: empty candidate batch \u2014 cannot derive prior for teacher");let s=o[o.length-1],i=0,u={prior:s,reportCost:c=>{i+=c}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(u)));let c=[];for(let d=0;d<e;d++)c.push(await t.teacher(u));return c}finally{if(t.tokens!=null&&i>0){let c=t.tokens.cache??0;t.tokens.emit(c+i)}}}}}function uy(t){return typeof t=="object"&&t!==null&&t.kind==="errorCritique"}function cy(t,e){return t.length===0?`No task scored below the batch mean (${e.score.toFixed(3)}). Reinforce the current direction.`:`Failures below threshold:
237
238
  ${t.map(r=>{let o=r.error!=null?` | error: ${r.error}`:"";return`- ${r.taskId} (score=${r.score.toFixed(3)})${o}`}).join(`
238
- `)}`}function Ig(t){let e=t.width??4,n=t.name??"errorCritique",r=t.maxFailureSamples??5,o=t.formatCritique??Lg;return{name:n,seed(s){return[s]},analyze(s,i){let a=Ha(s),u=typeof t.failureThreshold=="function"?t.failureThreshold(s):t.failureThreshold,c=u===void 0&&!Number.isFinite(a),d=u??a,l=c?[...s].sort((v,T)=>v.score-T.score):s.filter(v=>v.score<d).slice().sort((v,T)=>v.score-T.score),f=l.slice(0,r),{best:p,bestScore:m}=np(i,s),h={summary:"",score:a,weakTasks:f.map(v=>v.taskId)},g=o(f,h),y={kind:"errorCritique",best:p,failures:f,critiqueText:g},b=l.length>f.length?` (top ${f.length} retained)`:"";return{summary:`errorCritique iteration: mean=${a.toFixed(3)}, failures=${l.length}${b}/${s.length}, bestScore=${m.toFixed(3)}`,critique:y,weakTasks:f.map(v=>v.taskId),score:a}},async generate(s,i){if(i.length===0)throw new Error("errorCritique.generate: empty candidate batch \u2014 cannot derive prior for teacher");let a=Ag(s.critique)?s.critique:void 0,u=a!==void 0?a.best:i[i.length-1],c=a?.critiqueText??s.summary,d=a?.failures??[],l=0,p={prior:u,critique:c,failures:d,reportCost:m=>{l+=m}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(p)));let m=[];for(let h=0;h<e;h++)m.push(await t.teacher(p));return m}finally{if(t.tokens!=null&&l>0){let m=t.tokens.cache??0;t.tokens.emit(m+l)}}}}}var Ks={};he(Ks,{NS_PER_MS:()=>De,NS_PER_SEC:()=>Qe,resilientPipeline:()=>Pg});Ln();vt();function Pg(t,e={}){let n=t;e.rateLimit!=null&&(n=Dn(n,e.rateLimit)),e.budget!=null&&e.budget.length>0&&(n=Ea(n,e.budget));let r;if(e.breaker!=null){let s=pt(e.breaker),i=e.breakerOnOpen??"skip",a=Pn(s,{onOpen:i})(n);n=a.node,r=a.breakerState}if(e.timeoutMs!=null){if(e.timeoutMs<=0)throw new RangeError("timeoutMs must be > 0");if(e.timeoutMs>9e6)throw new RangeError("timeoutMs must be <= 9_000_000 (\u22482.5h) to stay within safe ns arithmetic");n=Fn(n,e.timeoutMs*1e6)}e.retry!=null&&(n=In(n,e.retry)),e.fallback!==void 0&&(n=Gn(n,e.fallback));let o=Lt(n,{initialStatus:e.initialStatus??"pending"});return{node:o.node,status:o.status,error:o.error,breakerState:r}}var Qs={};he(Qs,{SNAPSHOT_WIRE_VERSION:()=>zr,SurfaceError:()=>ve,asSurfaceError:()=>Vs,createGraph:()=>zn,deleteSnapshot:()=>Ys,diffSnapshots:()=>zs,listSnapshots:()=>Js,restoreSnapshot:()=>Us,runReduction:()=>qs,saveSnapshot:()=>Ws});var ve=class extends Error{code;details;constructor(e,n,r){super(n),this.name="SurfaceError",this.code=e,r!==void 0&&(this.details=r)}toJSON(){let e={code:this.code,message:this.message};if(this.details!==void 0){let n=Dg(this.details);n!==void 0&&(e.details=n)}return e}};function Dg(t){try{return JSON.parse(JSON.stringify(t))}catch{return}}function Vs(t,e="internal-error"){if(t instanceof ve)return t;let n=t instanceof Error?t.message:String(t);return new ve(e,n)}function zn(t,e){let n=Un(t);if(!n.valid)throw new ve("invalid-spec",`GraphSpec validation failed:
239
+ `)}`}function dy(t){let e=t.width??4,n=t.name??"errorCritique",r=t.maxFailureSamples??5,o=t.formatCritique??cy;return{name:n,seed(s){return[s]},analyze(s,i){let a=za(s),u=typeof t.failureThreshold=="function"?t.failureThreshold(s):t.failureThreshold,c=u===void 0&&!Number.isFinite(a),d=u??a,l=c?[...s].sort((v,T)=>v.score-T.score):s.filter(v=>v.score<d).slice().sort((v,T)=>v.score-T.score),f=l.slice(0,r),{best:p,bestScore:m}=dp(i,s),h={summary:"",score:a,weakTasks:f.map(v=>v.taskId)},g=o(f,h),y={kind:"errorCritique",best:p,failures:f,critiqueText:g},b=l.length>f.length?` (top ${f.length} retained)`:"";return{summary:`errorCritique iteration: mean=${a.toFixed(3)}, failures=${l.length}${b}/${s.length}, bestScore=${m.toFixed(3)}`,critique:y,weakTasks:f.map(v=>v.taskId),score:a}},async generate(s,i){if(i.length===0)throw new Error("errorCritique.generate: empty candidate batch \u2014 cannot derive prior for teacher");let a=uy(s.critique)?s.critique:void 0,u=a!==void 0?a.best:i[i.length-1],c=a?.critiqueText??s.summary,d=a?.failures??[],l=0,p={prior:u,critique:c,failures:d,reportCost:m=>{l+=m}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(p)));let m=[];for(let h=0;h<e;h++)m.push(await t.teacher(p));return m}finally{if(t.tokens!=null&&l>0){let m=t.tokens.cache??0;t.tokens.emit(m+l)}}}}}function ly(t){let{best:e,score:n,status:r}=t,o=Number.isFinite(n)?n.toFixed(3):String(n);return r==="converged"?{outcome:"success",detail:`refineLoop converged at score ${o}`,artifact:e}:r==="budget"?{outcome:"partial",detail:`refineLoop hit budget at score ${o}`,artifact:e}:{outcome:"failure",detail:`refineLoop errored (status=${r})`,artifact:e}}function py(t){let e=t.name??"refine-executor",n=t.toOutput??ly;return r=>{let o=ut(r,i=>i!=null),s=be(o,i=>{let a=Ja(t.seedFrom(i),t.evaluator,t.strategy,{...t.refine,dataset:t.datasetFor(i),name:`${e}/inner`});return O([a.status,a.best,a.score],([u,c,d])=>{let l=u;return l!=="converged"&&l!=="budget"&&l!=="errored"?null:n({best:c,score:d,status:l})},{name:`${e}/output`})},{name:e});return ut(s,i=>i!=null)}}ke();function fy(t){let e={"intake::latest":"INTAKE",triage:"TRIAGE",execute:"EXECUTE","verify-results::latest":"VERIFY",strategy:"STRATEGY"};for(let n of Ht)e[`queue/${n}::latest`]="QUEUE";for(let[n]of t.gates)e[`gates::${n}/gate`]="GATE";return e}function my(t,e){let n=e?.logger===null?null:e?.logger??console.log,r=e?.detail??"summary",o=$(),s=[],i=[],a=fy(t);function u(){return($()-o)/1e9}function c(d,l,f){let p={elapsed:u(),stage:d,type:l};r!=="summary"&&(p.summary=hy(f)),r==="full"&&(p.data=f),i.push(p)}for(let[d,l]of Object.entries(a))try{let f=t.observe(d,{format:"stage-log",stageLabels:a,logger:n?p=>n(p):()=>{},includeTypes:["data","error","complete"]});f.onEvent(p=>{p.type==="data"?c(l,"data",p.data):p.type==="error"?c(l,"error",p.data):p.type==="complete"&&c(l,"complete",void 0)}),s.push(f)}catch(f){let p=f instanceof Error?f.message:String(f);c(l,"error",`observe-unavailable: ${d} \u2014 ${p}`),n&&n(`[${u().toFixed(3)}s] ${l.padEnd(9)} \u2717 observe-unavailable: ${p}`)}return{get events(){return i},dispose(){for(let d of s)d.dispose();s.length=0}}}function hy(t){if(t==null)return"null";if(typeof t=="string")return lp(t,80);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return lp(e,120)}catch{return String(t)}}function lp(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}var Vs={};he(Vs,{JobFlowGraph:()=>js,JobQueueGraph:()=>Bs,jobFlow:()=>yy,jobQueue:()=>fp});xe();var gy=2147483647;function pp(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Ya(t,e){return Ke("job_queue",t,e)}var Bs=class extends q{_pending;_jobs;_seq=0;pending;jobs;depth;constructor(e,n={}){super(e,n.graph),this._pending=es([],{name:"pending"}),this._jobs=tt({name:"jobs"}),this.pending=this._pending.items,this.jobs=this._jobs.entries,this.add(this.pending,{name:"pending"}),this.add(this.jobs,{name:"jobs"}),this.depth=O([this.pending],([r])=>r.length,{name:"depth",describeKind:"derived",meta:Ya("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(se(this.depth))}enqueue(e,n={}){let r=n.id??`${this.name}-${++this._seq}`;if(this._jobs.get(r)!==void 0)throw new Error(`jobQueue("${this.name}"): duplicate job id "${r}"`);let o={id:r,payload:e,attempts:0,metadata:Object.freeze({...n.metadata??{}}),state:"queued"};return this._jobs.set(r,o),this._pending.append(r),r}claim(e=1){let n=pp(e,"job queue claim limit");if(n===0)return[];let r=[];for(;r.length<n&&this.pending.cache.length!==0;){let s=this._pending.pop(0),i=this._jobs.get(s);if(!i||i.state!=="queued")continue;let a={...i,state:"inflight",attempts:i.attempts+1};this._jobs.set(s,a),r.push(a)}return r}ack(e){let n=this._jobs.get(e);return!n||n.state!=="inflight"?!1:(this._jobs.delete(e),!0)}nack(e,n={}){let r=this._jobs.get(e);return!r||r.state!=="inflight"?!1:n.requeue??!0?(this._jobs.set(e,{...r,state:"queued"}),this._pending.append(e),!0):(this._jobs.delete(e),!0)}},js=class extends q{_stageNames;_queues=new Map;_completed;completed;completedCount;constructor(e,n={}){super(e,n.graph);let r=(n.stages??["incoming","processing","done"]).map(i=>i.trim());if(r.length<2)throw new Error(`jobFlow("${e}"): requires at least 2 stages`);if(new Set(r).size!==r.length)throw new Error(`jobFlow("${e}"): stage names must be unique`);this._stageNames=Object.freeze([...r]);for(let i of this._stageNames){let a=fp(`${e}-${i}`);this._queues.set(i,a),this.mount(i,a)}this._completed=Ve([],{name:"completed"}),this.completed=this._completed.entries,this.add(this.completed,{name:"completed"}),this.completedCount=O([this.completed],([i])=>i.length,{name:"completedCount",describeKind:"derived",meta:Ya("job_flow_completed_count"),initial:0}),this.add(this.completedCount,{name:"completedCount"}),this.addDisposer(se(this.completedCount));let s=Math.max(1,pp(n.maxPerPump??gy,"job flow maxPerPump"));for(let i=0;i<this._stageNames.length;i+=1){let a=this._stageNames[i],u=this.queue(a),c=i+1<this._stageNames.length?this.queue(this._stageNames[i+1]):null,d=K([u.pending],()=>{let l=0;for(;l<s;){let f=u.claim(1);if(f.length===0)break;let p=f[0];if(!p)break;c?c.enqueue(p.payload,{metadata:{...p.metadata,job_flow_from:a}}):this._completed.append(p),u.ack(p.id),l+=1}},{name:`pump_${a}`,describeKind:"effect",meta:Ya("job_flow_pump")});this.add(d,{name:`pump_${a}`}),this.addDisposer(se(d))}}stages(){return this._stageNames}queue(e){let n=this._queues.get(e);if(!n)throw new Error(`jobFlow("${this.name}"): unknown stage "${e}"`);return n}enqueue(e,n={}){return this.queue(this._stageNames[0]).enqueue(e,n)}retainedCompleted(){return this.completed.cache}};function fp(t,e){return new Bs(t,e)}function yy(t,e){return new js(t,e)}var Hs={};he(Hs,{LensGraph:()=>Ks,graphLens:()=>ky,watchTopologyTree:()=>kt});ke();oe();function mp(t){return Ke("lens",t)}function by(t){let e=Object.keys(t.nodes),n=new Map,r=new Map;for(let h of e){let g=t.nodes[h]?.deps??[];n.set(h,g);for(let y of g)r.has(y)||r.set(y,new Set),r.get(y).add(h)}let o=[],s=[];for(let h of e)(n.get(h)??[]).length===0&&o.push(h),r.has(h)||s.push(h);o.sort(),s.sort();let i=t.edges.length,a=0,u=1,c=2,d=new Map;for(let h of e)d.set(h,a);let l=!1,f=new Map,p=h=>{let g=d.get(h)??a;if(g===u)return l=!0,0;if(g===c)return f.get(h)??0;d.set(h,u);let y=0,b=r.get(h);if(b!=null)for(let v of b){let T=p(v);T+1>y&&(y=T+1)}return d.set(h,c),f.set(h,y),y},m=0;for(let h of o){let g=p(h);g>m&&(m=g)}for(let h of e)d.get(h)===a&&p(h);return{nodeCount:e.length,edgeCount:i,subgraphCount:t.subgraphs.length,sources:o,sinks:s,depth:m,hasCycles:l}}function vy(t){let e=[];for(let[n,r]of Object.entries(t.nodes)){if(r.status!=="errored")continue;let o={path:n,status:"errored"},s=un(t,n,"upstream",{});for(let i of s)if(i!==n&&t.nodes[i]?.status==="errored"){o.upstreamCause=i;break}e.push(o)}return e.sort((n,r)=>n.path<r.path?-1:n.path>r.path?1:0),{ok:e.length===0,problems:e}}function Ty(t,e){return t.nodeCount===e.nodeCount&&t.edgeCount===e.edgeCount&&t.subgraphCount===e.subgraphCount&&t.depth===e.depth&&t.hasCycles===e.hasCycles&&hp(t.sources,e.sources)&&hp(t.sinks,e.sinks)}function wy(t,e){if(t.ok!==e.ok||t.problems.length!==e.problems.length)return!1;for(let n=0;n<t.problems.length;n++){let r=t.problems[n],o=e.problems[n];if(r.path!==o.path||r.status!==o.status||r.upstreamCause!==o.upstreamCause)return!1}return!0}function hp(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}var Ks=class extends q{stats;health;flow;_target;constructor(e,n={}){super(n.name??`${e.name}_lens`,n.graph),this._target=e;let r=0,o=0,s=N(0,{name:"stats_tick"}),i=N(0,{name:"health_tick"});this.add(s,{name:"stats_tick"}),this.add(i,{name:"health_tick"});let a={name:"flow"};n.maxFlowPaths!=null&&(a.maxSize=n.maxFlowPaths),this.flow=tt(a),this.add(this.flow.entries,{name:"flow"});let u=n.pathFilter,c=kt(e,(f,p,m)=>{if(r+=1,s.emit(r),o+=1,i.emit(o),f.kind==="removed")if(f.nodeKind==="node"){let h=`${m}${f.name}`;this.flow.delete(h)}else{let h=`${m}${f.name}::`,g=[];for(let y of f.audit.nodes){let b=y===""?`${m}${f.name}`:`${h}${y}`;g.push(b)}g.length>0&&this.flow.deleteMany(g)}});this.addDisposer(c);let d=e.observe({timeline:!0,structured:!0}),l=d.onEvent(f=>{let p=f.type;if((p==="error"||p==="complete"||p==="data"||p==="teardown")&&(o+=1,i.emit(o)),p==="data"){let m=f.path??"";if(!m||u!=null&&!u(m))return;let h=this.flow.get(m),g=h!=null?h.count+1:1;this.flow.set(m,{path:m,count:g,lastUpdate_ns:$()})}});this.addDisposer(()=>{l(),d.dispose()}),this.stats=O([s],()=>by(e.describe({detail:"minimal"})),{name:"stats",describeKind:"derived",equals:Ty,meta:mp("stats")}),this.add(this.stats,{name:"stats"}),this.addDisposer(se(this.stats)),this.health=O([i],()=>vy(e.describe({detail:"standard"})),{name:"health",describeKind:"derived",equals:wy,meta:mp("health")}),this.add(this.health,{name:"health"}),this.addDisposer(se(this.health))}why(e,n,r){let o=La(this._target,e,n,r);return this.addDisposer(o.dispose),o}get target(){return this._target}};function ky(t,e){return new Ks(t,e)}var Ws={};he(Ws,{CanvasMeasureAdapter:()=>eu,CliMeasureAdapter:()=>Qa,ImageSizeAdapter:()=>ru,NodeCanvasMeasureAdapter:()=>tu,PrecomputedAdapter:()=>Za,SvgBoundsAdapter:()=>nu,analyzeAndMeasure:()=>Mt,carveTextLineSlots:()=>Ga,circleIntervalForBand:()=>Tp,computeBlockFlow:()=>bp,computeCharPositions:()=>Ms,computeFlowLines:()=>kp,computeLineBreaks:()=>Tn,computeTotalHeight:()=>vp,layoutNextLine:()=>Da,measureBlock:()=>gp,measureBlocks:()=>yp,reactiveBlockLayout:()=>xy,reactiveFlowLayout:()=>Sy,reactiveLayout:()=>Ng,rectIntervalForBand:()=>wp});var Qa=class{cellPx;constructor(e){this.cellPx=e?.cellPx??8}measureSegment(e,n){return{width:Wn(e)*this.cellPx}}},Xa=class extends Error{name="KeyError"},Za=class{metrics;fallback;constructor(e){this.metrics=e.metrics;let n=e.fallback??"per-char";if(n!=="per-char"&&n!=="error")throw new Error(`fallback must be 'per-char' or 'error', got ${JSON.stringify(e.fallback)}`);this.fallback=n}measureSegment(e,n){let r=this.metrics[n];if(r){let s=r[e];if(s!==void 0)return{width:s}}if(this.fallback==="error")throw new Xa(`PrecomputedAdapter: no metrics for segment ${JSON.stringify(e)} in font ${JSON.stringify(n)}`);let o=0;if(r)for(let s of e){let i=r[s];i!==void 0&&(o+=i)}return{width:o}}},eu=class{ctx=null;currentFont="";emojiCorrection;constructor(e){this.emojiCorrection=e?.emojiCorrection??1}getContext(){if(!this.ctx){if(typeof OffscreenCanvas>"u")throw new Error("CanvasMeasureAdapter requires a browser environment with OffscreenCanvas support. Use CliMeasureAdapter or NodeCanvasMeasureAdapter for Node.js.");let n=new OffscreenCanvas(0,0).getContext("2d");if(!n)throw new Error("CanvasMeasureAdapter: failed to get 2d context");this.ctx=n}return this.ctx}measureSegment(e,n){let r=this.getContext();n!==this.currentFont&&(r.font=n,this.currentFont=n);let o=r.measureText(e).width;return this.emojiCorrection!==1&&new RegExp("\\p{Emoji_Presentation}","u").test(e)&&(o*=this.emojiCorrection),{width:o}}clearCache(){this.currentFont=""}},tu=class{ctx=null;currentFont="";canvasModule;constructor(e){this.canvasModule=e}getContext(){if(!this.ctx){let n=this.canvasModule.createCanvas(0,0).getContext("2d");if(!n)throw new Error("NodeCanvasMeasureAdapter: failed to get 2d context");this.ctx=n}return this.ctx}measureSegment(e,n){let r=this.getContext();return n!==this.currentFont&&(r.font=n,this.currentFont=n),{width:r.measureText(e).width}}clearCache(){this.currentFont=""}},nu=class{measureSvg(e){let n=e.match(/viewBox\s*=\s*["']([^"']+)["']/);if(n){let s=n[1].trim().split(/[\s,]+/);if(s.length>=4){let i=Number.parseFloat(s[2]),a=Number.parseFloat(s[3]);if(Number.isFinite(i)&&Number.isFinite(a)&&i>0&&a>0)return{width:i,height:a};throw new Error("SvgBoundsAdapter: viewBox width/height are missing, non-finite, or not positive")}}let r=e.match(/<svg[^>]*\bwidth\s*=\s*["']?([\d.]+)/),o=e.match(/<svg[^>]*\bheight\s*=\s*["']?([\d.]+)/);if(r&&o){let s=Number.parseFloat(r[1]),i=Number.parseFloat(o[1]);if(Number.isFinite(s)&&Number.isFinite(i)&&s>0&&i>0)return{width:s,height:i};throw new Error("SvgBoundsAdapter: svg width/height attributes are non-finite or not positive")}throw new Error("SvgBoundsAdapter: cannot determine dimensions \u2014 SVG has no viewBox or width/height attributes")}},ru=class{sizes;constructor(e){this.sizes=new Map(Object.entries(e))}measureImage(e){let n=this.sizes.get(e);if(!n)throw new Error(`ImageSizeAdapter: no dimensions registered for ${JSON.stringify(e)}`);return{width:n.width,height:n.height}}};ke();xe();oe();function gp(t,e,n,r,o,s,i){switch(t.type){case"text":{let a=t.font??o,u=t.lineHeight??s,c=Mt(t.text,a,n.text,r),d=Tn(c,e,n.text,a,r),l=Ms(d,c,u),f=d.lineCount*u,p=0;for(let m of d.lines)m.width>p&&(p=m.width);return{index:i,type:"text",width:Math.min(p,e),height:f,textSegments:c,textLineBreaks:d,textCharPositions:l}}case"image":{let a,u;if(t.naturalWidth!=null&&t.naturalHeight!=null)a=t.naturalWidth,u=t.naturalHeight;else if(n.image){let c=n.image.measureImage(t.src);a=c.width,u=c.height}else throw new Error(`Image block at index ${i} has no naturalWidth/naturalHeight and no ImageMeasurer adapter`);return a>e&&(u=u*e/a,a=e),{index:i,type:"image",width:a,height:u}}case"svg":{let a,u;if(t.viewBox)a=t.viewBox.width,u=t.viewBox.height;else if(n.svg){let c=n.svg.measureSvg(t.content);a=c.width,u=c.height}else throw new Error(`SVG block at index ${i} has no viewBox and no SvgMeasurer adapter`);return a>e&&(u=u*e/a,a=e),{index:i,type:"svg",width:a,height:u}}}}function yp(t,e,n,r,o,s){return t.map((i,a)=>gp(i,e,n,r,o,s,a))}function bp(t,e){let n=[],r=0;for(let o=0;o<t.length;o++){let s=t[o];n.push({...s,x:0,y:r}),r+=s.height+(o<t.length-1?e:0)}return n}function vp(t){if(t.length===0)return 0;let e=t[t.length-1];return e.y+e.height}function xy(t){let{adapters:e,name:n="reactive-block-layout",defaultFont:r="16px sans-serif",defaultLineHeight:o=20}=t,s=new q(n),i=new Map,a=N(t.blocks??[],{name:"blocks"}),u=N(Math.max(0,t.maxWidth??800),{name:"max-width"}),c=N(t.gap??0,{name:"gap"}),d=K([a,u],(p,m,h)=>{let g=p[0]!=null&&p[0].length>0?p[0].at(-1):h.prevData[0],y=p[1]!=null&&p[1].length>0?p[1].at(-1):h.prevData[1],b=$(),v=yp(g,y,e,i,r,o),T=$()-b,w=d.meta;w&&(at(w["block-count"],v.length),at(w["layout-time-ns"],T)),m.emit(v);let k=()=>{i.clear(),e.text.clearCache?.()};return{deactivate:k,invalidate:k}},{name:"measured-blocks",describeKind:"derived",meta:{"block-count":0,"layout-time-ns":0},equals:(p,m)=>{let h=p,g=m;if(h==null||g==null)return h===g;if(h.length!==g.length)return!1;for(let y=0;y<h.length;y++){let b=h[y],v=g[y];if(b.type!==v.type||b.width!==v.width||b.height!==v.height||b.index!==v.index)return!1}return!0}}),l=O([d,c],([p,m])=>bp(p,m),{name:"block-flow",equals:(p,m)=>{let h=p,g=m;if(h==null||g==null)return h===g;if(h.length!==g.length)return!1;for(let y=0;y<h.length;y++){let b=h[y],v=g[y];if(b.x!==v.x||b.y!==v.y||b.width!==v.width||b.height!==v.height)return!1}return!0}}),f=O([l],([p])=>vp(p),{name:"total-height"});return s.add(a,{name:"blocks"}),s.add(u,{name:"max-width"}),s.add(c,{name:"gap"}),s.add(d,{name:"measured-blocks"}),s.add(l,{name:"block-flow"}),s.add(f,{name:"total-height"}),{graph:s,setBlocks:p=>s.set("blocks",p),setMaxWidth:p=>s.set("max-width",Math.max(0,p)),setGap:p=>s.set("gap",p),measuredBlocks:d,blockFlow:l,totalHeight:f}}ke();xe();oe();function Tp(t,e,n){let r=t.hPad??0,o=t.vPad??0,s=e-o,i=n+o;if(s>=t.cy+t.r||i<=t.cy-t.r)return null;let a=t.cy>=s&&t.cy<=i?0:t.cy<s?s-t.cy:t.cy-i;if(a>=t.r)return null;let u=Math.sqrt(t.r*t.r-a*a);return{left:t.cx-u-r,right:t.cx+u+r}}function wp(t,e,n){let r=t.hPad??0,o=t.vPad??0;return n<=t.y-o||e>=t.y+t.h+o?null:{left:t.x-r,right:t.x+t.w+r}}function Ry(t,e,n){return t.kind==="circle"?Tp(t,e,n):wp(t,e,n)}function kp(t,e,n,r,o,s,i){let a=i?.paragraphSpacing??o,u=[],c={segmentIndex:0,graphemeIndex:0};if(t.length===0||n.count<=0||o<=0)return{lines:u,cursor:c};let d=e.paddingX??0,l=e.paddingY??0,f=Math.max(0,e.width-d*2),p=Math.max(0,e.height-l*2),m=n.gap*Math.max(0,n.count-1),h=Math.max(0,(f-m)/n.count);if(h<=0)return{lines:u,cursor:c};e:for(let g=0;g<n.count;g++){let y=d+g*(h+n.gap),b=y+h,v=l;for(;v+o<=l+p;){let T=v+o,w=[];for(let R=0;R<r.length;R++){let E=Ry(r[R],v,T);E!==null&&w.push(E)}let k=Ga({left:y,right:b},w,s);if(k.length===0){v+=o;continue}let x=!1;for(let R=0;R<k.length;R++){let E=k[R],G=E.right-E.left,L=Da(t,c,G);if(L===null)return{lines:u,cursor:c};if(L.text.length===0&&L.width===0){c=L.end,x=!0;break}u.push({x:E.left,y:v,width:L.width,slotWidth:G,text:L.text,columnIndex:g,flushToRight:E.right<b-.5}),c=L.end}if(x){v+=a;continue}if(v+=o,c.segmentIndex>=t.length)break e}if(c.segmentIndex>=t.length)break}return{lines:u,cursor:c}}function Sy(t){let{adapter:e,name:n="reactive-flow-layout",minSlotWidth:r=20}=t,o=new q(n),s=new Map,i=N(t.text??"",{name:"text"}),a=N(t.font??"16px sans-serif",{name:"font"}),u=N(t.lineHeight??20,{name:"line-height"}),c=N(t.container??{width:800,height:600,paddingX:0,paddingY:0},{name:"container"}),d=N(t.columns??{count:1,gap:0},{name:"columns"}),l=N(t.obstacles??[],{name:"obstacles"}),f=N(t.paragraphSpacing??null,{name:"paragraph-spacing"}),p=K([i,a],(h,g,y)=>{let b=h[0],v=b!=null&&b.length>0?b.at(-1):y.prevData[0],T=h[1],w=T!=null&&T.length>0?T.at(-1):y.prevData[1],k=Mt(v,w,e,s);g.emit(k);let x=()=>{s.clear(),e.clearCache?.()};return{deactivate:x,invalidate:x}},{name:"segments",describeKind:"derived"}),m=O([p,c,d,l,u,f],([h,g,y,b,v,T])=>{let w=h,k=$(),x=T??v,{lines:R,cursor:E}=kp(w,g,y,b,v,r,{paragraphSpacing:x}),G=$()-k,L=Math.max(0,w.length-E.segmentIndex),P=m.meta;return P&&(at(P["line-count"],R.length),at(P["layout-time-ns"],G),at(P["overflow-segments"],L)),R},{name:"flow-lines",meta:{"line-count":0,"layout-time-ns":0,"overflow-segments":0},equals:(h,g)=>{let y=h,b=g;if(y.length!==b.length)return!1;for(let v=0;v<y.length;v++){let T=y[v],w=b[v];if(T.x!==w.x||T.y!==w.y||T.width!==w.width||T.slotWidth!==w.slotWidth||T.text!==w.text||T.columnIndex!==w.columnIndex||T.flushToRight!==w.flushToRight)return!1}return!0}});return o.add(i,{name:"text"}),o.add(a,{name:"font"}),o.add(u,{name:"line-height"}),o.add(c,{name:"container"}),o.add(d,{name:"columns"}),o.add(l,{name:"obstacles"}),o.add(f,{name:"paragraph-spacing"}),o.add(p,{name:"segments"}),o.add(m,{name:"flow-lines"}),{graph:o,setText:h=>o.set("text",h),setFont:h=>o.set("font",h),setLineHeight:h=>o.set("line-height",h),setContainer:h=>o.set("container",h),setColumns:h=>o.set("columns",h),setObstacles:h=>o.set("obstacles",h),setParagraphSpacing:h=>o.set("paragraph-spacing",h),segments:p,flowLines:m}}var qs={};he(qs,{NS_PER_MS:()=>Fe,NS_PER_SEC:()=>Qe,resilientPipeline:()=>Ny});Gn();Tt();function Ny(t,e={}){let n=t;e.rateLimit!=null&&(n=Bn(n,e.rateLimit)),e.budget!=null&&e.budget.length>0&&(n=Fa(n,e.budget));let r;if(e.breaker!=null){let s=ft(e.breaker),i=e.breakerOnOpen??"skip",a=$n(s,{onOpen:i})(n);n=a.node,r=a.breakerState}if(e.timeoutMs!=null){if(e.timeoutMs<=0)throw new RangeError("timeoutMs must be > 0");if(e.timeoutMs>9e6)throw new RangeError("timeoutMs must be <= 9_000_000 (\u22482.5h) to stay within safe ns arithmetic");n=Vn(n,e.timeoutMs*1e6)}e.retry!=null&&(n=Fn(n,e.retry)),e.fallback!==void 0&&(n=jn(n,e.fallback));let o=It(n,{initialStatus:e.initialStatus??"pending"});return{node:o.node,status:o.status,error:o.error,breakerState:r}}var ti={};he(ti,{SNAPSHOT_WIRE_VERSION:()=>Xr,SurfaceError:()=>we,asSurfaceError:()=>Us,createGraph:()=>Zn,deleteSnapshot:()=>ei,diffSnapshots:()=>Xs,listSnapshots:()=>Zs,restoreSnapshot:()=>Qs,runReduction:()=>zs,saveSnapshot:()=>Ys});var we=class extends Error{code;details;constructor(e,n,r){super(n),this.name="SurfaceError",this.code=e,r!==void 0&&(this.details=r)}toJSON(){let e={code:this.code,message:this.message};if(this.details!==void 0){let n=Ey(this.details);n!==void 0&&(e.details=n)}return e}};function Ey(t){try{return JSON.parse(JSON.stringify(t))}catch{return}}function Us(t,e="internal-error"){if(t instanceof we)return t;let n=t instanceof Error?t.message:String(t);return new we(e,n)}function Zn(t,e){let n=Xn(t);if(!n.valid)throw new we("invalid-spec",`GraphSpec validation failed:
239
240
  ${n.errors.join(`
240
- `)}`,{errors:n.errors});let r=e?.catalog??{},o=qr(t,r);if(!o.valid)throw new ve("catalog-error",`Catalog validation failed:
241
+ `)}`,{errors:n.errors});let r=e?.catalog??{},o=zr(t,r);if(!o.valid)throw new we("catalog-error",`Catalog validation failed:
241
242
  ${o.errors.join(`
242
- `)}`,{errors:o.errors});try{return Ca(t,e)}catch(s){let i=s instanceof Error?s.message:String(s);throw new ve("catalog-error",i)}}ie();var Gg=3e4;async function qs(t,e,n){let r=n?.inputPath??"input",o=n?.outputPath??"output",s=n?.timeoutMs??Gg,i=zn(t,{catalog:n?.catalog}),a;try{a=i.resolve(o)}catch{throw i.destroy(),new ve("node-not-found",`reduce: output path "${o}" is not registered`,{path:o})}try{i.resolve(r)}catch{throw i.destroy(),new ve("node-not-found",`reduce: input path "${r}" is not registered`,{path:r})}try{return await new Promise((u,c)=>{let d=!1,l=!1,f,p,m=!1,h=g=>{l||(l=!0,f!==void 0&&clearTimeout(f),p!==void 0?(p(),p=void 0):m=!0,g())};p=a.subscribe(g=>{for(let y of g){if(l)return;if(d){if(y[0]===R){h(()=>u(y[1]));return}if(y[0]===$){let b=a.cache;h(()=>u(b));return}if(y[0]===O){let b=y[1],v=b instanceof Error?b.message:String(b),T=b instanceof Error?b:void 0;h(()=>c(new ve("internal-error",`reduce: output emitted ERROR: ${v}`,T!=null?{cause:T}:void 0)));return}if(y[0]===M){h(()=>c(new ve("internal-error","reduce: output COMPLETEd without a post-push DATA")));return}}}}),m&&(p?.(),p=void 0),d=!0;try{i.set(r,e)}catch(g){let y=g instanceof Error?g.message:String(g),b=g instanceof Error?g:void 0;h(()=>c(new ve("internal-error",`reduce: failed to set input on "${r}": ${y}`,b!=null?{path:r,cause:b}:{path:r})));return}!l&&Number.isFinite(s)&&s>0&&(f=setTimeout(()=>{h(()=>c(new ve("reduce-timeout",`reduce: no output emitted within ${s}ms`,{timeoutMs:s,outputPath:o})))},s),f.unref?.())})}finally{i.destroy()}}Te();var zr=it,Wr="snapshot:";function Ur(t){if(t.startsWith(Wr))throw new ve("snapshot-failed",`snapshot id must not start with "${Wr}" (reserved); got "${t}"`,{snapshotId:t})}function Hs(t){return`${Wr}${t}`}function Fg(t){return t.startsWith(Wr)?t.slice(Wr.length):void 0}function Wa(t,e){if(t==null||typeof t!="object")throw new ve("snapshot-not-found",`snapshot "${e}" not found in tier`,{snapshotId:e});let n=t;if("mode"in n){if(n.mode==="full"&&"snapshot"in n)return n.snapshot;throw n.mode==="diff"?new ve("restore-failed",`snapshot "${e}" is a diff record; restore the baseline and replay WAL instead`,{snapshotId:e,mode:"diff"}):new ve("restore-failed",`snapshot "${e}" has unknown mode "${String(n.mode)}"`,{snapshotId:e,mode:String(n.mode)})}if("nodes"in n&&"edges"in n&&"subgraphs"in n&&"name"in n)return n;throw new ve("restore-failed",`snapshot "${e}" payload is not a GraphCheckpointRecord or GraphPersistSnapshot`,{snapshotId:e})}async function Ws(t,e,n){Ur(e);let r;try{r=t.snapshot()}catch(s){let i=s instanceof Error?s.message:String(s);throw new ve("snapshot-failed",`snapshot "${e}" serialization failed: ${i}`,{snapshotId:e})}let o={mode:"full",seq:0,timestamp_ns:pe(),format_version:zr,snapshot:r};try{await n.save(Hs(e),o)}catch(s){let i=s instanceof Error?s.message:String(s);throw new ve("snapshot-failed",`snapshot "${e}" save failed: ${i}`,{snapshotId:e})}return{snapshotId:e,timestamp_ns:o.timestamp_ns}}async function Us(t,e,n){Ur(t);let r=Hs(t),o=await e.load(r);o==null&&(o=await e.load(t));let s=Wa(o,t);try{return z.fromSnapshot(s,n?.factories?{factories:n.factories}:void 0)}catch(i){let a=i instanceof Error?i.message:String(i);throw new ve("restore-failed",`snapshot "${t}" restore failed: ${a}`,{snapshotId:t})}}async function zs(t,e,n){Ur(t),Ur(e);let r=async u=>{let c=Hs(u),d=await n.load(c);return d==null&&(d=await n.load(u)),d},[o,s]=await Promise.all([r(t),r(e)]),i=Wa(o,t),a=Wa(s,e);return z.diff(i,a)}async function Js(t,e){if(typeof t.list!="function")throw new ve("tier-no-list","StorageTier does not implement list(); wrap the tier with an enumerator or use a different backend");let n=await t.list(),r=[],o=e?.includeUnprefixed===!0;for(let s of n){let i=Fg(s);i!==void 0?r.push(i):o&&r.push(s)}return r}async function Ys(t,e){if(Ur(t),typeof e.clear!="function")throw new ve("snapshot-failed",`StorageTier is append-only (no clear()); cannot delete "${t}"`,{snapshotId:t});try{await e.clear(Hs(t))}catch(n){let r=n instanceof Error?n.message:String(n);throw new ve("snapshot-failed",`snapshot "${t}" delete failed: ${r}`,{snapshotId:t})}}var $g="0.0.0";0&&(module.exports={COMPLETE,COMPLETE_MSG,COMPLETE_ONLY_BATCH,CircuitOpenError,DATA,DEFAULT_ACTOR,DIRTY,DIRTY_MSG,DIRTY_ONLY_BATCH,ENVELOPE_VERSION,ERROR,GRAPH_META_SEGMENT,Graph,GraphReFlyConfig,GuardDenied,INVALIDATE,INVALIDATE_MSG,INVALIDATE_ONLY_BATCH,JsonCodec,NS_PER_MS,NS_PER_SEC,NativeIndexBackend,NativeListBackend,NativeLogBackend,NativeMapBackend,NativePubSubBackend,NodeImpl,PAUSE,RESOLVED,RESOLVED_MSG,RESOLVED_ONLY_BATCH,RESUME,RateLimiterOverflowError,ResettableTimer,SIZEOF_OVERHEAD,SIZEOF_SYMBOL,SNAPSHOT_VERSION,SNAPSHOT_WIRE_VERSION,START,START_MSG,SurfaceError,TEARDOWN,TEARDOWN_MSG,TEARDOWN_ONLY_BATCH,TimeoutError,accessHintForGuard,accountability,advanceVersion,ai,asSurfaceError,audit,autoTrackNode,awaitSettled,batch,buffer,bufferCount,bufferTime,cached,cascadingCache,catchError,checkpointToRedis,checkpointToS3,circuitBreaker,combine,combineLatest,compat,concat,concatMap,configure,constant,core,cqrs,createDagCborCodec,createDagCborZstdCodec,createGraph,createTransport,createVersioning,createWatermarkController,csvRows,debounce,debounceTime,decodeEnvelope,decorrelatedJitter,defaultConfig,defaultHash,delay,deleteSnapshot,demoShell,derived,deserializeError,dictStorage,diffForWAL,diffSnapshots,distill,distinctUntilChanged,domainTemplates,downWithBatch,dynamicNode,effect,elementAt,empty,encodeEnvelope,escapeRegexChar,exhaustMap,explainPath,exponential,externalBundle,externalProducer,extra,fallback,fibonacci,filter,find,first,firstValueFrom,firstWhere,flatMap,forEach,fromAny,fromAsyncIter,fromCSV,fromClickHouseWatch,fromCron,fromDrizzle,fromEvent,fromHTTP,fromHTTPPoll,fromHTTPStream,fromIter,fromKafka,fromKysely,fromMCP,fromNATS,fromNDJSON,fromOTel,fromPrisma,fromPrometheus,fromPromise,fromPulsar,fromRabbitMQ,fromRaf,fromRedisStream,fromSSE,fromSqlite,fromSqliteCursor,fromStatsD,fromSyslog,fromTimer,fromWebSocket,fromWebSocketReconnect,fromWebhook,globToRegExp,graph,graphProfile,graphspec,guarded,harness,interval,isBatching,isV1,jobQueue,jotai,keepalive,last,layout,lens,linear,listSnapshots,lru,map,matchesAnyPattern,matchesCron,memory,memoryStorage,merge,mergeMap,mermaidLiveUrl,messaging,monotonicNs,nameToSignal,nanostores,ndjsonRows,nestjs,never,node,normalizeActor,of,orchestration,pairwise,parseCron,parsePrometheusText,parseStatsD,parseSyslog,patterns,pausable,pipe,policy,policyFromRules,producer,pubsub,race,rateLimiter,reachable,react,reactiveCounter,reactiveIndex,reactiveList,reactiveLog,reactiveMap,reactiveSink,reduce,reduction,refine,registerBuiltinCodecs,registerBuiltins,repeat,replay,replayWAL,rescue,resilientPipeline,resolveBackoffPreset,resolveDescribeFields,restoreSnapshot,retry,retrySource,runReduction,sample,saveSnapshot,scan,serializeError,share,shareReplay,signalToName,signals,singleFromAny,singleNodeFromAny,sizeof,skip,solid,sortJsonValue,stableJsonString,state,stratify,surface,svelte,switchMap,take,takeUntil,takeWhile,tap,throttle,throttleTime,throwError,timeout,toArray,toCSV,toClickHouse,toFile,toHTTP,toKafka,toLoki,toMongo,toNATS,toObservable,toPostgres,toPulsar,toRabbitMQ,toReadableStream,toRedisStream,toS3,toSSE,toSSEBytes,toSqlite,toTempo,toWebSocket,tokenBucket,validateGraphObservability,valve,verifiable,version,vue,wallClockNs,watchTopologyTree,window,windowCount,windowTime,withBreaker,withLatestFrom,withMaxAttempts,withStatus,workerBridge,workerSelf,zip,zustand});
243
+ `)}`,{errors:o.errors});try{return Va(t,e)}catch(s){let i=s instanceof Error?s.message:String(s);throw new we("catalog-error",i)}}ie();var _y=3e4;async function zs(t,e,n){let r=n?.inputPath??"input",o=n?.outputPath??"output",s=n?.timeoutMs??_y,i=Zn(t,{catalog:n?.catalog}),a;try{a=i.resolve(o)}catch{throw i.destroy(),new we("node-not-found",`reduce: output path "${o}" is not registered`,{path:o})}try{i.resolve(r)}catch{throw i.destroy(),new we("node-not-found",`reduce: input path "${r}" is not registered`,{path:r})}try{return await new Promise((u,c)=>{let d=!1,l=!1,f,p,m=!1,h=g=>{l||(l=!0,f!==void 0&&clearTimeout(f),p!==void 0?(p(),p=void 0):m=!0,g())};p=a.subscribe(g=>{for(let y of g){if(l)return;if(d){if(y[0]===S){h(()=>u(y[1]));return}if(y[0]===B){let b=a.cache;h(()=>u(b));return}if(y[0]===M){let b=y[1],v=b instanceof Error?b.message:String(b),T=b instanceof Error?b:void 0;h(()=>c(new we("internal-error",`reduce: output emitted ERROR: ${v}`,T!=null?{cause:T}:void 0)));return}if(y[0]===_){h(()=>c(new we("internal-error","reduce: output COMPLETEd without a post-push DATA")));return}}}}),m&&(p?.(),p=void 0),d=!0;try{i.set(r,e)}catch(g){let y=g instanceof Error?g.message:String(g),b=g instanceof Error?g:void 0;h(()=>c(new we("internal-error",`reduce: failed to set input on "${r}": ${y}`,b!=null?{path:r,cause:b}:{path:r})));return}!l&&Number.isFinite(s)&&s>0&&(f=setTimeout(()=>{h(()=>c(new we("reduce-timeout",`reduce: no output emitted within ${s}ms`,{timeoutMs:s,outputPath:o})))},s),f.unref?.())})}finally{i.destroy()}}ke();var Xr=it,Yr="snapshot:";function Qr(t){if(t.startsWith(Yr))throw new we("snapshot-failed",`snapshot id must not start with "${Yr}" (reserved); got "${t}"`,{snapshotId:t})}function Js(t){return`${Yr}${t}`}function My(t){return t.startsWith(Yr)?t.slice(Yr.length):void 0}function ou(t,e){if(t==null||typeof t!="object")throw new we("snapshot-not-found",`snapshot "${e}" not found in tier`,{snapshotId:e});let n=t;if("mode"in n){if(n.mode==="full"&&"snapshot"in n)return n.snapshot;throw n.mode==="diff"?new we("restore-failed",`snapshot "${e}" is a diff record; restore the baseline and replay WAL instead`,{snapshotId:e,mode:"diff"}):new we("restore-failed",`snapshot "${e}" has unknown mode "${String(n.mode)}"`,{snapshotId:e,mode:String(n.mode)})}if("nodes"in n&&"edges"in n&&"subgraphs"in n&&"name"in n)return n;throw new we("restore-failed",`snapshot "${e}" payload is not a GraphCheckpointRecord or GraphPersistSnapshot`,{snapshotId:e})}async function Ys(t,e,n){Qr(e);let r;try{r=t.snapshot()}catch(s){let i=s instanceof Error?s.message:String(s);throw new we("snapshot-failed",`snapshot "${e}" serialization failed: ${i}`,{snapshotId:e})}let o={mode:"full",seq:0,timestamp_ns:pe(),format_version:Xr,snapshot:r};try{await n.save(Js(e),o)}catch(s){let i=s instanceof Error?s.message:String(s);throw new we("snapshot-failed",`snapshot "${e}" save failed: ${i}`,{snapshotId:e})}return{snapshotId:e,timestamp_ns:o.timestamp_ns}}async function Qs(t,e,n){Qr(t);let r=Js(t),o=await e.load(r);o==null&&(o=await e.load(t));let s=ou(o,t);try{return q.fromSnapshot(s,n?.factories?{factories:n.factories}:void 0)}catch(i){let a=i instanceof Error?i.message:String(i);throw new we("restore-failed",`snapshot "${t}" restore failed: ${a}`,{snapshotId:t})}}async function Xs(t,e,n){Qr(t),Qr(e);let r=async u=>{let c=Js(u),d=await n.load(c);return d==null&&(d=await n.load(u)),d},[o,s]=await Promise.all([r(t),r(e)]),i=ou(o,t),a=ou(s,e);return q.diff(i,a)}async function Zs(t,e){if(typeof t.list!="function")throw new we("tier-no-list","StorageTier does not implement list(); wrap the tier with an enumerator or use a different backend");let n=await t.list(),r=[],o=e?.includeUnprefixed===!0;for(let s of n){let i=My(s);i!==void 0?r.push(i):o&&r.push(s)}return r}async function ei(t,e){if(Qr(t),typeof e.clear!="function")throw new we("snapshot-failed",`StorageTier is append-only (no clear()); cannot delete "${t}"`,{snapshotId:t});try{await e.clear(Js(t))}catch(n){let r=n instanceof Error?n.message:String(n);throw new we("snapshot-failed",`snapshot "${t}" delete failed: ${r}`,{snapshotId:t})}}var Oy="0.0.0";0&&(module.exports={COMPLETE,COMPLETE_MSG,COMPLETE_ONLY_BATCH,CircuitOpenError,DATA,DEFAULT_ACTOR,DIRTY,DIRTY_MSG,DIRTY_ONLY_BATCH,ENVELOPE_VERSION,ERROR,GRAPH_META_SEGMENT,Graph,GraphReFlyConfig,GuardDenied,INVALIDATE,INVALIDATE_MSG,INVALIDATE_ONLY_BATCH,JsonCodec,NS_PER_MS,NS_PER_SEC,NativeIndexBackend,NativeListBackend,NativeLogBackend,NativeMapBackend,NativePubSubBackend,NodeImpl,PAUSE,RESOLVED,RESOLVED_MSG,RESOLVED_ONLY_BATCH,RESUME,RateLimiterOverflowError,ResettableTimer,SIZEOF_OVERHEAD,SIZEOF_SYMBOL,SNAPSHOT_VERSION,SNAPSHOT_WIRE_VERSION,START,START_MSG,SurfaceError,TEARDOWN,TEARDOWN_MSG,TEARDOWN_ONLY_BATCH,TimeoutError,accessHintForGuard,accountability,advanceVersion,ai,asSurfaceError,audit,autoTrackNode,awaitSettled,batch,buffer,bufferCount,bufferTime,cached,cascadingCache,catchError,checkpointToRedis,checkpointToS3,circuitBreaker,combine,combineLatest,compat,concat,concatMap,configure,constant,core,cqrs,createDagCborCodec,createDagCborZstdCodec,createGraph,createTransport,createVersioning,createWatermarkController,csvRows,debounce,debounceTime,decodeEnvelope,decorrelatedJitter,defaultConfig,defaultHash,delay,deleteSnapshot,demoShell,derived,deserializeError,dictStorage,diffForWAL,diffSnapshots,distill,distinctUntilChanged,domainTemplates,downWithBatch,dynamicNode,effect,elementAt,empty,encodeEnvelope,escapeRegexChar,exhaustMap,explainPath,exponential,externalBundle,externalProducer,extra,fallback,fibonacci,filter,find,first,firstValueFrom,firstWhere,flatMap,forEach,fromAny,fromAsyncIter,fromCSV,fromClickHouseWatch,fromCron,fromDrizzle,fromEvent,fromHTTP,fromHTTPPoll,fromHTTPStream,fromIter,fromKafka,fromKysely,fromMCP,fromNATS,fromNDJSON,fromOTel,fromPrisma,fromPrometheus,fromPromise,fromPulsar,fromRabbitMQ,fromRaf,fromRedisStream,fromSSE,fromSqlite,fromSqliteCursor,fromStatsD,fromSyslog,fromTimer,fromWebSocket,fromWebSocketReconnect,fromWebhook,globToRegExp,graph,graphProfile,graphspec,guarded,harness,interval,isBatching,isV1,jobQueue,jotai,keepalive,last,layout,lens,linear,listSnapshots,lru,map,matchesAnyPattern,matchesCron,memory,memoryStorage,merge,mergeMap,mermaidLiveUrl,messaging,monotonicNs,nameToSignal,nanostores,ndjsonRows,nestjs,never,node,normalizeActor,of,orchestration,pairwise,parseCron,parsePrometheusText,parseStatsD,parseSyslog,patterns,pausable,pipe,policy,policyFromRules,producer,pubsub,race,rateLimiter,reachable,react,reactiveCounter,reactiveIndex,reactiveList,reactiveLog,reactiveMap,reactiveSink,reduce,reduction,refine,registerBuiltinCodecs,registerBuiltins,repeat,replay,replayWAL,rescue,resilientPipeline,resolveBackoffPreset,resolveDescribeFields,restoreSnapshot,retry,retrySource,runReduction,sample,saveSnapshot,scan,serializeError,share,shareReplay,signalToName,signals,singleFromAny,singleNodeFromAny,sizeof,skip,solid,sortJsonValue,stableJsonString,state,stratify,surface,svelte,switchMap,take,takeUntil,takeWhile,tap,throttle,throttleTime,throwError,timeout,toArray,toCSV,toClickHouse,toFile,toHTTP,toKafka,toLoki,toMongo,toNATS,toObservable,toPostgres,toPulsar,toRabbitMQ,toReadableStream,toRedisStream,toS3,toSSE,toSSEBytes,toSqlite,toTempo,toWebSocket,tokenBucket,validateGraphObservability,valve,verifiable,version,vue,wallClockNs,watchTopologyTree,window,windowCount,windowTime,withBreaker,withLatestFrom,withMaxAttempts,withStatus,workerBridge,workerSelf,zip,zustand});