@graphrefly/graphrefly 0.30.0 → 0.32.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 (253) hide show
  1. package/dist/{cascading-dNCtjW8j.d.cts → cascading-BfQmSmjU.d.cts} +21 -2
  2. package/dist/{cascading-BszPheHD.d.ts → cascading-D3sapjue.d.ts} +21 -2
  3. package/dist/chunk-2JNT5NDF.js +61 -0
  4. package/dist/{chunk-DDPYNMGG.js → chunk-2RH4QNDQ.js} +1 -1
  5. package/dist/chunk-4JBKKUCJ.js +7 -0
  6. package/dist/{chunk-SLMYTGTU.js → chunk-4UUDNFYG.js} +1 -1
  7. package/dist/chunk-4VXL3UZK.js +1 -0
  8. package/dist/{chunk-SHYH5SXV.js → chunk-4YGJ7KZ6.js} +1 -1
  9. package/dist/{chunk-GJR3P6JG.js → chunk-5PBXUVHI.js} +1 -1
  10. package/dist/{chunk-W4TSQ6RJ.js → chunk-7AJKUA36.js} +1 -1
  11. package/dist/{chunk-XQAXYVXX.js → chunk-7EMUF2RY.js} +1 -1
  12. package/dist/chunk-7JZ3YORY.js +80 -0
  13. package/dist/chunk-7QMVU3IX.js +1 -0
  14. package/dist/{chunk-WANIEEKV.js → chunk-7QS77X6G.js} +1 -1
  15. package/dist/{chunk-BA5URFYW.js → chunk-A4JT4SAD.js} +1 -1
  16. package/dist/{chunk-Y36UZ5VS.js → chunk-BU4SUZSA.js} +1 -1
  17. package/dist/{chunk-P7JXGKDO.js → chunk-CNXUW2CU.js} +1 -1
  18. package/dist/{chunk-Y32RJO24.js → chunk-CZVYLXFK.js} +1 -1
  19. package/dist/{chunk-567NWZ3T.js → chunk-DWIAG62L.js} +1 -1
  20. package/dist/chunk-EIFHFDFD.js +1 -0
  21. package/dist/chunk-FTA5TB2A.js +1 -0
  22. package/dist/{chunk-T5SHIKJD.js → chunk-JAHAJU4G.js} +1 -1
  23. package/dist/{chunk-AV3PIDFQ.js → chunk-JYMNVEH6.js} +1 -1
  24. package/dist/{chunk-5Z4HDCO6.js → chunk-K54OKWNY.js} +1 -1
  25. package/dist/chunk-KD3IYBTD.js +3 -0
  26. package/dist/{chunk-3NEPQO2E.js → chunk-LG73TUF4.js} +2 -2
  27. package/dist/chunk-LJGPOJHS.js +1 -0
  28. package/dist/chunk-LWGLBCMU.js +1 -0
  29. package/dist/{chunk-BKPLTBL5.js → chunk-M2VFLRPJ.js} +1 -1
  30. package/dist/{chunk-GNCBXARM.js → chunk-MFNOZ5E6.js} +1 -1
  31. package/dist/{chunk-TWMEGG45.js → chunk-N2KKISCE.js} +1 -1
  32. package/dist/chunk-PNTBXOQ6.js +5 -0
  33. package/dist/{chunk-73Z3W2RN.js → chunk-PWKLZ2XU.js} +1 -1
  34. package/dist/{chunk-7TDOES3L.js → chunk-Q2SY7M7K.js} +1 -1
  35. package/dist/{chunk-OL33ZI6R.js → chunk-RWGJQQLT.js} +1 -1
  36. package/dist/chunk-SGS4OJGS.js +1 -0
  37. package/dist/{chunk-4OFIQ66T.js → chunk-TOCCHQI6.js} +1 -1
  38. package/dist/chunk-UMH3HSP7.js +1 -0
  39. package/dist/{chunk-XHVB6G6M.js → chunk-UXEB35L4.js} +1 -1
  40. package/dist/{chunk-33FA6V4B.js → chunk-VXJX3ZZP.js} +1 -1
  41. package/dist/{chunk-BZP5T4X6.js → chunk-W6FQIFVE.js} +1 -1
  42. package/dist/{chunk-RD52SNH2.js → chunk-WE32AFFA.js} +1 -1
  43. package/dist/{chunk-KA6MMXIY.js → chunk-WF3V5X2L.js} +1 -1
  44. package/dist/chunk-WQ7I7JVU.js +1 -0
  45. package/dist/{chunk-4JJCCD5S.js → chunk-X4OOM6QU.js} +1 -1
  46. package/dist/{chunk-AUY2YKCO.js → chunk-XRSHMHEG.js} +1 -1
  47. package/dist/chunk-Y26UN6J5.js +18 -0
  48. package/dist/{chunk-VWPRPPKR.js → chunk-ZWETYYQG.js} +1 -1
  49. package/dist/compat/index.cjs +2 -2
  50. package/dist/compat/index.d.cts +5 -5
  51. package/dist/compat/index.d.ts +5 -5
  52. package/dist/compat/index.js +1 -1
  53. package/dist/compat/jotai/index.cjs +1 -1
  54. package/dist/compat/jotai/index.js +1 -1
  55. package/dist/compat/nanostores/index.cjs +1 -1
  56. package/dist/compat/nanostores/index.js +1 -1
  57. package/dist/compat/nestjs/index.cjs +5 -5
  58. package/dist/compat/nestjs/index.d.cts +3 -3
  59. package/dist/compat/nestjs/index.d.ts +3 -3
  60. package/dist/compat/nestjs/index.js +1 -1
  61. package/dist/compat/zustand/index.cjs +2 -2
  62. package/dist/compat/zustand/index.d.cts +2 -2
  63. package/dist/compat/zustand/index.d.ts +2 -2
  64. package/dist/compat/zustand/index.js +1 -1
  65. package/dist/{composite-DGspwCqk.d.ts → composite-BY9hMxN7.d.ts} +1 -1
  66. package/dist/{composite-nrRumJ7l.d.cts → composite-CH0S8DFn.d.cts} +1 -1
  67. package/dist/content-addressed-storage-BUiREIuj.d.ts +124 -0
  68. package/dist/content-addressed-storage-DqIWCmZG.d.cts +124 -0
  69. package/dist/core/index.cjs +1 -1
  70. package/dist/core/index.js +1 -1
  71. package/dist/extra/browser.cjs +1 -1
  72. package/dist/extra/browser.js +1 -1
  73. package/dist/extra/index.cjs +18 -18
  74. package/dist/extra/index.d.cts +7 -6
  75. package/dist/extra/index.d.ts +7 -6
  76. package/dist/extra/index.js +1 -1
  77. package/dist/extra/node.cjs +2 -2
  78. package/dist/extra/node.js +1 -1
  79. package/dist/extra/operators.cjs +1 -1
  80. package/dist/extra/operators.d.cts +41 -1
  81. package/dist/extra/operators.d.ts +41 -1
  82. package/dist/extra/operators.js +1 -1
  83. package/dist/extra/reactive.cjs +1 -1
  84. package/dist/extra/reactive.d.cts +1 -1
  85. package/dist/extra/reactive.d.ts +1 -1
  86. package/dist/extra/reactive.js +1 -1
  87. package/dist/extra/sources.cjs +1 -1
  88. package/dist/extra/sources.d.cts +62 -2
  89. package/dist/extra/sources.d.ts +62 -2
  90. package/dist/extra/sources.js +1 -1
  91. package/dist/extra/storage-browser.cjs +1 -1
  92. package/dist/extra/storage-browser.js +1 -1
  93. package/dist/{fallback-BaTS7vVY.d.cts → fallback-Cb3GH1O7.d.cts} +6 -14
  94. package/dist/{fallback-eOm3LNxP.d.ts → fallback-DRjJ_ZM8.d.ts} +6 -14
  95. package/dist/graph/index.cjs +4 -4
  96. package/dist/graph/index.d.cts +3 -3
  97. package/dist/graph/index.d.ts +3 -3
  98. package/dist/graph/index.js +1 -1
  99. package/dist/{graph-CWeI0aHd.d.ts → graph-BOhEGJ6E.d.ts} +10 -0
  100. package/dist/{graph-C4Uxwv0T.d.cts → graph-CdJeX7O7.d.cts} +10 -0
  101. package/dist/{index-B-z8WaSd.d.cts → index-BDLy6CQ9.d.cts} +1 -1
  102. package/dist/{index-iBp74eGU.d.cts → index-BJDXj9Wf.d.cts} +2 -2
  103. package/dist/{index-BBINVimG.d.ts → index-BUZPTPSQ.d.ts} +2 -2
  104. package/dist/{index-DnrZghBB.d.ts → index-BbcSZCAG.d.ts} +1 -1
  105. package/dist/{index-lKuLYmHO.d.cts → index-BiGeETJs.d.cts} +1 -1
  106. package/dist/{index-BHu_Wba0.d.cts → index-BmZb8fNF.d.cts} +3 -3
  107. package/dist/{index-Docdiu9a.d.ts → index-Bnmttu35.d.ts} +1 -1
  108. package/dist/{index-D6ajK8Mh.d.cts → index-BuN2wGJs.d.cts} +517 -134
  109. package/dist/{index-Cy7eFeIX.d.cts → index-BwdPDWI4.d.cts} +1 -1
  110. package/dist/{index-DylQCKEL.d.cts → index-BzxU4yhV.d.cts} +11 -2
  111. package/dist/{index-D9Y_u6BG.d.cts → index-C-Gsh-0a.d.cts} +2 -2
  112. package/dist/{index-ybtSyjWB.d.cts → index-C22aTC1X.d.cts} +5 -5
  113. package/dist/{index-yIdWFo2b.d.cts → index-C4QTaDli.d.cts} +2 -2
  114. package/dist/{index-BJHQUCZx.d.ts → index-C7RqYbOZ.d.ts} +82 -7
  115. package/dist/{index-C5Ghnp5B.d.ts → index-C9qCLIN4.d.ts} +2 -2
  116. package/dist/{index-DVNLe3pS.d.cts → index-CCdg0JLX.d.cts} +1 -1
  117. package/dist/{index-B5iVOD7w.d.ts → index-CEoU-r-g.d.ts} +2 -2
  118. package/dist/{index-CfFYyLR8.d.ts → index-CHfBm51k.d.ts} +11 -2
  119. package/dist/{index-Dljd76bC.d.ts → index-CNyiYQWF.d.ts} +5 -5
  120. package/dist/{index-C6NBfXj-.d.ts → index-CVevMZ0n.d.ts} +2 -2
  121. package/dist/{index-DGb1awva.d.ts → index-CZUzi6Dy.d.ts} +2 -2
  122. package/dist/{index-FrYrV-Vf.d.ts → index-Ckl03Q0s.d.ts} +1 -1
  123. package/dist/{index-Bvi5uJxX.d.ts → index-CmSjld-4.d.ts} +1 -1
  124. package/dist/{index-9iguV3bF.d.cts → index-CnjUhRbs.d.cts} +2 -2
  125. package/dist/{index-C98oJsEs.d.cts → index-D3HcdZ4d.d.cts} +1 -1
  126. package/dist/{index-IZ3l_vQ9.d.ts → index-DD1czHj3.d.ts} +1 -1
  127. package/dist/{index-BS220yqj.d.cts → index-DNhTQReY.d.cts} +82 -7
  128. package/dist/{index-UZO988ox.d.cts → index-DSawGt8n.d.cts} +2 -2
  129. package/dist/{index-CcpEvuPl.d.cts → index-DUkuH3jP.d.cts} +1 -1
  130. package/dist/{index-CRAkoq-y.d.cts → index-DY2QbdoP.d.cts} +1 -1
  131. package/dist/{index-CvS9IuTG.d.ts → index-Dbmj0iYR.d.ts} +1 -1
  132. package/dist/{index-ClgKmOHe.d.ts → index-DhlAMlm9.d.ts} +517 -134
  133. package/dist/{index-ClB7TCfL.d.cts → index-DlGaEBW5.d.cts} +2 -2
  134. package/dist/{index-CotRMjtJ.d.ts → index-Dp_pS7Bw.d.ts} +1 -1
  135. package/dist/{index-Cc8VQIgL.d.ts → index-Dxk-pUQI.d.ts} +2 -2
  136. package/dist/{index-DBQUKh59.d.cts → index-EGjF6iSY.d.cts} +3 -3
  137. package/dist/{index-D9HrBx2J.d.ts → index-LGzAYqdR.d.ts} +1 -1
  138. package/dist/{index-DR3gf_DG.d.cts → index-LzCJ0kMT.d.cts} +2 -2
  139. package/dist/{index-RQg6lTrN.d.ts → index-MV2yGIAq.d.ts} +2 -2
  140. package/dist/{index-Bs3-LC83.d.cts → index-_BXz9K7b.d.cts} +1 -1
  141. package/dist/{index-SSGqF8mI.d.cts → index-aBqZUx3B.d.cts} +1 -1
  142. package/dist/{index-CFW32Dy1.d.ts → index-eYHRkoK-.d.ts} +1 -1
  143. package/dist/{index-B2HBxvMb.d.ts → index-gXTVbSax.d.ts} +3 -3
  144. package/dist/{index-B8Aj_z8S.d.cts → index-j33Lfb1G.d.cts} +23 -2
  145. package/dist/{index-BEpRsvhg.d.ts → index-lpGUhTBn.d.ts} +3 -3
  146. package/dist/{index-BXbQUn4n.d.ts → index-zMQIQuDu.d.ts} +23 -2
  147. package/dist/index.cjs +106 -125
  148. package/dist/index.d.cts +34 -33
  149. package/dist/index.d.ts +34 -33
  150. package/dist/index.js +1 -1
  151. package/dist/patterns/ai/browser.cjs +5 -22
  152. package/dist/patterns/ai/browser.d.cts +3 -3
  153. package/dist/patterns/ai/browser.d.ts +3 -3
  154. package/dist/patterns/ai/browser.js +1 -1
  155. package/dist/patterns/ai/index.cjs +30 -44
  156. package/dist/patterns/ai/index.d.cts +13 -11
  157. package/dist/patterns/ai/index.d.ts +13 -11
  158. package/dist/patterns/ai/index.js +1 -1
  159. package/dist/patterns/ai/node.cjs +2 -2
  160. package/dist/patterns/ai/node.d.cts +5 -4
  161. package/dist/patterns/ai/node.d.ts +5 -4
  162. package/dist/patterns/ai/node.js +1 -1
  163. package/dist/patterns/audit/index.cjs +3 -3
  164. package/dist/patterns/audit/index.d.cts +3 -3
  165. package/dist/patterns/audit/index.d.ts +3 -3
  166. package/dist/patterns/audit/index.js +1 -1
  167. package/dist/patterns/cqrs/index.cjs +6 -6
  168. package/dist/patterns/cqrs/index.d.cts +2 -2
  169. package/dist/patterns/cqrs/index.d.ts +2 -2
  170. package/dist/patterns/cqrs/index.js +1 -1
  171. package/dist/patterns/demo-shell/index.cjs +2 -2
  172. package/dist/patterns/demo-shell/index.d.cts +3 -3
  173. package/dist/patterns/demo-shell/index.d.ts +3 -3
  174. package/dist/patterns/demo-shell/index.js +1 -1
  175. package/dist/patterns/domain-templates/index.cjs +6 -6
  176. package/dist/patterns/domain-templates/index.d.cts +2 -2
  177. package/dist/patterns/domain-templates/index.d.ts +2 -2
  178. package/dist/patterns/domain-templates/index.js +1 -1
  179. package/dist/patterns/graphspec/index.cjs +27 -25
  180. package/dist/patterns/graphspec/index.d.cts +3 -3
  181. package/dist/patterns/graphspec/index.d.ts +3 -3
  182. package/dist/patterns/graphspec/index.js +1 -1
  183. package/dist/patterns/guarded-execution/index.cjs +7 -7
  184. package/dist/patterns/guarded-execution/index.d.cts +4 -4
  185. package/dist/patterns/guarded-execution/index.d.ts +4 -4
  186. package/dist/patterns/guarded-execution/index.js +1 -1
  187. package/dist/patterns/harness/index.cjs +12 -11
  188. package/dist/patterns/harness/index.d.cts +6 -6
  189. package/dist/patterns/harness/index.d.ts +6 -6
  190. package/dist/patterns/harness/index.js +1 -1
  191. package/dist/patterns/job-queue/index.cjs +5 -5
  192. package/dist/patterns/job-queue/index.d.cts +2 -2
  193. package/dist/patterns/job-queue/index.d.ts +2 -2
  194. package/dist/patterns/job-queue/index.js +1 -1
  195. package/dist/patterns/lens/index.cjs +5 -5
  196. package/dist/patterns/lens/index.d.cts +4 -4
  197. package/dist/patterns/lens/index.d.ts +4 -4
  198. package/dist/patterns/lens/index.js +1 -1
  199. package/dist/patterns/memory/index.cjs +4 -4
  200. package/dist/patterns/memory/index.d.cts +2 -2
  201. package/dist/patterns/memory/index.d.ts +2 -2
  202. package/dist/patterns/memory/index.js +1 -1
  203. package/dist/patterns/messaging/index.cjs +5 -5
  204. package/dist/patterns/messaging/index.d.cts +2 -2
  205. package/dist/patterns/messaging/index.d.ts +2 -2
  206. package/dist/patterns/messaging/index.js +1 -1
  207. package/dist/patterns/orchestration/index.cjs +7 -7
  208. package/dist/patterns/orchestration/index.d.cts +2 -2
  209. package/dist/patterns/orchestration/index.d.ts +2 -2
  210. package/dist/patterns/orchestration/index.js +1 -1
  211. package/dist/patterns/reactive-layout/index.cjs +2 -2
  212. package/dist/patterns/reactive-layout/index.d.cts +3 -3
  213. package/dist/patterns/reactive-layout/index.d.ts +3 -3
  214. package/dist/patterns/reactive-layout/index.js +1 -1
  215. package/dist/patterns/reduction/index.cjs +5 -5
  216. package/dist/patterns/reduction/index.d.cts +2 -2
  217. package/dist/patterns/reduction/index.d.ts +2 -2
  218. package/dist/patterns/reduction/index.js +1 -1
  219. package/dist/patterns/refine-loop/index.cjs +8 -8
  220. package/dist/patterns/refine-loop/index.d.cts +3 -3
  221. package/dist/patterns/refine-loop/index.d.ts +3 -3
  222. package/dist/patterns/refine-loop/index.js +1 -1
  223. package/dist/patterns/resilient-pipeline/index.cjs +1 -1
  224. package/dist/patterns/resilient-pipeline/index.d.cts +3 -3
  225. package/dist/patterns/resilient-pipeline/index.d.ts +3 -3
  226. package/dist/patterns/resilient-pipeline/index.js +1 -1
  227. package/dist/patterns/surface/index.cjs +15 -13
  228. package/dist/patterns/surface/index.d.cts +4 -4
  229. package/dist/patterns/surface/index.d.ts +4 -4
  230. package/dist/patterns/surface/index.js +1 -1
  231. package/dist/{reactive-layout-BAr6-_o5.d.ts → reactive-layout-Bq0rA2Wb.d.ts} +1 -1
  232. package/dist/{reactive-layout-5oEn8lHM.d.cts → reactive-layout-Dhhe54Oj.d.cts} +1 -1
  233. package/dist/{reactive-map-BvDrRuwt.d.ts → reactive-map-CtRaCddO.d.ts} +59 -1
  234. package/dist/{reactive-map-CmlPPKHN.d.cts → reactive-map-IJIfZxoh.d.cts} +59 -1
  235. package/dist/{resilience-XRUF267O.js → resilience-IVNDYORD.js} +1 -1
  236. package/dist/{topology-tree-CVREibAc.d.cts → topology-tree-CpSjvIXp.d.cts} +1 -1
  237. package/dist/{topology-tree-CkjojcB6.d.ts → topology-tree-DAbCV2Yw.d.ts} +1 -1
  238. package/dist/{types-O3GzJY2U.d.cts → types-BgMqbc7N.d.cts} +41 -14
  239. package/dist/{types-u64Ose53.d.ts → types-CdfO2QTt.d.ts} +41 -14
  240. package/package.json +1 -1
  241. package/dist/chunk-2GQREQ6C.js +0 -1
  242. package/dist/chunk-4C2OR2GH.js +0 -18
  243. package/dist/chunk-5JDE5JHE.js +0 -1
  244. package/dist/chunk-7JDLFI6N.js +0 -1
  245. package/dist/chunk-AMBYCIOH.js +0 -3
  246. package/dist/chunk-GLSM33ZM.js +0 -78
  247. package/dist/chunk-ISCENNXS.js +0 -1
  248. package/dist/chunk-IUK4EFCE.js +0 -1
  249. package/dist/chunk-KASHOCF5.js +0 -1
  250. package/dist/chunk-LI3E75VE.js +0 -64
  251. package/dist/chunk-MGKAO4EK.js +0 -7
  252. package/dist/chunk-NSG4C6BF.js +0 -23
  253. package/dist/chunk-VIEUJSTT.js +0 -1
package/dist/index.cjs CHANGED
@@ -1,131 +1,55 @@
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
1
+ "use strict";var Bp=Object.create;var En=Object.defineProperty;var Su=Object.getOwnPropertyDescriptor;var jp=Object.getOwnPropertyNames;var Vp=Object.prototype.hasOwnProperty;var Nu=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),cr=t=>{throw TypeError(t)};var Kp=(t,e,n)=>e in t?En(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var ku=(t,e)=>En(t,"name",{value:e,configurable:!0});var Ze=(t,e)=>()=>(t&&(e=t(t=0)),e);var we=(t,e)=>{for(var n in e)En(t,n,{get:e[n],enumerable:!0})},Hp=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of jp(e))!Vp.call(t,o)&&o!==n&&En(t,o,{get:()=>e[o],enumerable:!(r=Su(e,o))||r.enumerable});return t};var Wp=t=>Hp(En({},"__esModule",{value:!0}),t);var Eu=t=>[,,,Bp(t?.[Nu("metadata")]??null)],_u=["class","method","getter","setter","accessor","field","value","get","set"],ur=t=>t!==void 0&&typeof t!="function"?cr("Function expected"):t,qp=(t,e,n,r,o)=>({kind:_u[t],name:e,metadata:r,addInitializer:s=>n._?cr("Already initialized"):o.push(ur(s||null))}),Up=(t,e)=>Kp(e,Nu("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},Ou=(t,e,n,r,o,s)=>{var i,a,u,c,d,l=e&7,p=!!(e&8),f=!!(e&16),m=l>3?t.length+1:l?p?1:2:0,g=_u[l+5],h=l>3&&(t[m-1]=[]),y=t[m]||(t[m]=[]),b=l&&(!f&&!p&&(o=o.prototype),l<5&&(l>3||!f)&&Su(l<4?o:{get[n](){return xu(this,s)},set[n](T){return Ru(this,s,T)}},n));l?f&&l<4&&ku(s,(l>2?"set ":l>1?"get ":"")+n):ku(o,n);for(var v=r.length-1;v>=0;v--)c=qp(l,n,u={},t[3],y),l&&(c.static=p,c.private=f,d=c.access={has:f?T=>zp(o,T):T=>n in T},l^3&&(d.get=f?T=>(l^1?xu:Jp)(T,o,l^4?s:b.get):T=>T[n]),l>2&&(d.set=f?(T,w)=>Ru(T,o,w,l^4?s:b.set):(T,w)=>T[n]=w)),a=(0,r[v])(l?l<4?f?s:b[g]:l>4?void 0:{get:b.get,set:b.set}:o,c),u._=1,l^4||a===void 0?ur(a)&&(l>4?h.unshift(a):l?f?s=a:b[g]=a:o=a):typeof a!="object"||a===null?cr("Object expected"):(ur(i=a.get)&&(b.get=i),ur(i=a.set)&&(b.set=i),ur(i=a.init)&&h.unshift(i));return l||Up(t,o),b&&En(o,n,b),f?l^4?s:b:o};var Si=(t,e,n)=>e.has(t)||cr("Cannot "+n),zp=(t,e)=>Object(e)!==e?cr('Cannot use the "in" operator on this value'):t.has(e),xu=(t,e,n)=>(Si(t,e,"read from private field"),n?n.call(t):e.get(t));var Ru=(t,e,n,r)=>(Si(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),Jp=(t,e,n)=>(Si(t,e,"access private method"),n);var yt,S,te,B,ze,Fe,je,pe,C,M,Rt,_n,vo,Mn,To,wo,On,dr,lr,pr,Cn,ie=Ze(()=>{"use strict";yt=Symbol.for("graphrefly/START"),S=Symbol.for("graphrefly/DATA"),te=Symbol.for("graphrefly/DIRTY"),B=Symbol.for("graphrefly/RESOLVED"),ze=Symbol.for("graphrefly/INVALIDATE"),Fe=Symbol.for("graphrefly/PAUSE"),je=Symbol.for("graphrefly/RESUME"),pe=Symbol.for("graphrefly/TEARDOWN"),C=Symbol.for("graphrefly/COMPLETE"),M=Symbol.for("graphrefly/ERROR"),Rt=Object.freeze([te]),_n=Object.freeze([B]),vo=Object.freeze([ze]),Mn=Object.freeze([yt]),To=Object.freeze([C]),wo=Object.freeze([pe]),On=Object.freeze([Rt]),dr=Object.freeze([_n]),lr=Object.freeze([vo]),pr=Object.freeze([To]),Cn=Object.freeze([wo])});function Ni(t){return{name:"dag-cbor",version:1,contentType:"application/dag-cbor",encode:e=>t.encode(e),decode:(e,n)=>t.decode(e)}}function Ei(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 fr(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++]=An,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 mr(t,e){if(t.length<Cu)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${Cu})`);let n=0,r=t[n++];if(r!==An)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${An})`);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 hr(t){t.registerCodec(ko)}function _i(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 ko,An,Cu,xo=Ze(()=>{"use strict";ko={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)}};An=1,Cu=4});function St(t){if(t==null)return bt;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var bt,gr=Ze(()=>{"use strict";bt={type:"system",id:""}});function tn(){return Ln>0||yr}function Au(){return Ln>0}function vr(t){Ln>0?br.push(t):t()}function Q(t){Ln+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(Ln-=1,Ln===0)if(e){if(!yr){let n=br.splice(0);for(let r of n)try{r()}catch{}Zt.length=0,en.length=0,In.length=0}}else Yp()}}function Yp(){let t=!yr;t&&(yr=!0);let e=[],n=0;try{for(;Zt.length>0||en.length>0||In.length>0||t&&br.length>0;){if(t&&br.length>0){let s=br.splice(0);for(let i of s)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw Zt.length=0,en.length=0,In.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let o=(Zt.length>0?Zt:en.length>0?en:In).splice(0);for(let s of o)try{s()}catch(i){e.push(i)}}}finally{t&&(yr=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function Nt(t,e,n){if(e.length===0)return;if(e.length===1){let c=n(e[0][0]);if(c<3||!tn()){t(e);return}(c>=5?In:c===4?en:Zt).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=tn();if(o>0){let c=e.slice(0,o);t(c)}if(s>o){let c=e.slice(o,s);u?Zt.push(()=>t(c)):t(c)}if(i>s){let c=e.slice(s,i);u?en.push(()=>t(c)):t(c)}if(r>i){let c=e.slice(i,r);u?In.push(()=>t(c)):t(c)}}var Ln,yr,Zt,en,In,br,Ne=Ze(()=>{"use strict";Ln=0,yr=!1,Zt=[],en=[],In=[],br=[]});function j(){return Math.trunc(performance.now()*1e6)}function fe(){return Date.now()*1e6}var ke=Ze(()=>{"use strict"});function Tr(t){t.registerMessageType(yt,{tier:0,wireCrossing:!1}),t.registerMessageType(te,{tier:1,wireCrossing:!1}),t.registerMessageType(ze,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(Fe,{tier:2,wireCrossing:!1}),t.registerMessageType(je,{tier:2,wireCrossing:!1}),t.registerMessageType(S,{tier:3,wireCrossing:!0}),t.registerMessageType(B,{tier:3,wireCrossing:!0}),t.registerMessageType(C,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(M,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(pe,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var nn,Mi=Ze(()=>{"use strict";ie();nn=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 Lu(t){return Array.isArray(t)?[...t]:[t]}function Qp(t,e){return t.has(e)||t.has("*")}function rn(t){let e=[];return t((o,s)=>{e.push({kind:"allow",actions:new Set(Lu(o)),where:s?.where??(()=>!0)})},(o,s)=>{e.push({kind:"deny",actions:new Set(Lu(o)),where:s?.where??(()=>!0)})}),(o,s)=>{let i=!1,a=!1;for(let u of e)Qp(u.actions,s)&&u.where(o)&&(u.kind==="deny"?i=!0:a=!0);return i?!1:a}}function wr(t){return rn((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 kr(t){let e=Xp.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 tt,Xp,on=Ze(()=>{"use strict";tt=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}};Xp=["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 tf(t){let e=ef.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,p=2600822924,f=528734635,m=1541459225,g=new Uint32Array(64),h=(b,v)=>b>>>v|b<<32-v;for(let b=0;b<o;b+=64){for(let O=0;O<16;O++)g[O]=i.getUint32(b+O*4,!1);for(let O=16;O<64;O++){let G=g[O-15],A=g[O-2],F=h(G,7)^h(G,18)^G>>>3,q=h(A,17)^h(A,19)^A>>>10;g[O]=g[O-16]+F+g[O-7]+q>>>0}let v=a,T=u,w=c,k=d,x=l,R=p,E=f,I=m;for(let O=0;O<64;O++){let G=h(x,6)^h(x,11)^h(x,25),A=x&R^~x&E,F=I+G+A+Zp[O]+g[O]>>>0,q=h(v,2)^h(v,13)^h(v,22),Y=v&T^v&w^T&w,D=q+Y>>>0;I=E,E=R,R=x,x=k+F>>>0,k=w,w=T,T=v,v=F+D>>>0}a=a+v>>>0,u=u+T>>>0,c=c+w>>>0,d=d+k>>>0,l=l+x>>>0,p=p+R>>>0,f=f+E>>>0,m=m+I>>>0}let y=b=>b.toString(16).padStart(8,"0");return y(a)+y(u)+y(c)+y(d)+y(l)+y(p)+y(f)+y(m)}function Ft(t){let e=Oi(t??null),n=JSON.stringify(e);return tf(n).slice(0,16)}function nf(){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 Dn(t,e,n){let r=n?.id??nf();if(t===0)return{id:r,version:0};let s=(n?.hash??Ft)(e);return{id:r,version:0,cid:s,prev:null}}function xr(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 Zp,ef,Ro=Ze(()=>{"use strict";Zp=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]),ef=new TextEncoder});function Pu(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function Ai(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 Ii(t){if(De._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(De)}function H(t,e,n){let r=Gu(t)?t:[],o=typeof t=="function"?t:typeof e=="function"?e:void 0,s={};return Gu(t)?s=(Li(e)?e:n)??{}:Li(t)?s=t:s=(Li(e)?e:n)??{},new Oe(r,o,s)}var Iu,Du,rf,of,De,Oe,Gu,Li,Ee=Ze(()=>{"use strict";xo();gr();Ne();ke();Mi();on();ie();Ro();Iu=()=>{},Du=100;rf=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},of=(t,e,n,r)=>{let o=t;if(o._status==="completed"||o._status==="errored")return;let s=o._cached,i=s===void 0?[Mn]:[Mn,[S,s]];o._status==="dirty"&&i.push(Rt),Nt(e,i,o._config.tierOf)},De=new nn({onMessage:rf,onSubscribe:of});Tr(De);hr(De);Oe=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??De,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??Ft;let o=r.versioning??this._config.defaultVersioning;this._versioningLevel=o,this._versioning=o!=null?Dn(o,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(Pu);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=Dn(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=St(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=St(e?.actor),s=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(o,s))throw new tt({actor:o,action:s,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(o,s))throw new tt({actor:o,action:s,nodeName:this.name})}this._lastMutation={actor:o,timestamp_ns:fe()}}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=St(n);if(!this._guard(u,"observe"))throw new tt({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)Ai(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=Iu,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{}Ai(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=Pu(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(On),r.unsub=Iu;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{}}Ai(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!==yt){if(o===te){this._depDirtied(r);return}if(o===ze){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(lr);return}if(o===Fe||o===je){this._emit([n]);return}if(o===pe){this._emit(Cn);return}if(o===S)this._depSettledAsData(r,n[1]);else if(o===B)this._depSettledAsResolved(r);else if(o===C)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===C||o===M)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(On))}_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(dr),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(pr)}_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>Du?(this._rerunDepth=0,this._emit([[M,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${Du} \u2014 likely a reactive cycle`)]])):this._maybeRunFnOnSettlement()):this._rerunDepth=0,this._clearWaveFlags()}}_clearWaveFlags(){this._waveHasNewData=!1,this._hasNewTerminal=!1;for(let e of this._deps)e.involvedThisWave=!1,e.dataBatch.length=0}_wrapFnError(e,n){let r=n instanceof Error?n.message:String(n);return new Error(`Node "${this.name}": ${e}: ${r}`,{cause:n})}_frameBatch(e){let n=this._config.tierOf;if(e.length===1)return n(e[0][0])===3&&this._status!=="dirty"?[Rt,e[0]]:e;let r=!0,o=!1,s=!1,i=-1;for(let u of e){let c=n(u[0]);c<i&&(r=!1),c===3&&(o=!0),u[0]===te&&(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?[Rt,...a]:[...a.slice(0,u),Rt,...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]===pe||u[0]===ze);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!==Fe&&c!==je){o?.push(u);continue}if(u.length<2)throw new Error(`Node "${this.name}": [[${c===Fe?"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===Fe)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 p=this._pauseBuffer;this._pauseBuffer=[],this._emit(p)}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]===pe))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(Cn)}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],p=l[0];if(p===S){if(l.length>=2){let f=!1;if(a&&this._cached!==void 0)try{f=this._equals(this._cached,l[1])}catch(m){o=this._wrapFnError("equals threw",m),s=d;break}if(f){r==null&&(r=e.slice(0,d)),r.push(_n),this._status="resolved";continue}this._cached=l[1],this._versioning!=null&&(u<0||d===u)&&xr(this._versioning,l[1],this._hashFn)}this._status="settled",r?.push(l)}else if(r?.push(l),p===te)this._status="dirty";else if(p===B)this._status="resolved";else if(p===C)this._status="completed";else if(p===M)this._status="errored";else if(p===ze){this._cached=void 0,this._status="dirty";let f=this._cleanup;if(typeof f=="function"){this._cleanup=void 0;try{f()}catch{}}else if(f!=null&&typeof f=="object"){let m=f.invalidate;if(typeof m=="function")try{m()}catch{}}}else p===pe&&(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(Au()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],vr(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}Nt(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);Nt(this._deliverToSinks,n,this._config.tierOf)}},Gu=t=>Array.isArray(t),Li=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function N(t,e){return H([],{...e,initial:t})}function W(t,e){return H((r,o,s)=>t(o,s)??void 0,{describeKind:"producer",...e})}function _(t,e,n){return H(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 ce(t,e,n){return H(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 Rr(t,e,n){let r=new Map;return t.forEach((o,s)=>{r.set(o,s)}),_(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 sn(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 f=s[l];return f!=null&&f.length>0?f.at(-1):a.prevData[l]}return d.cache}u=!0;let p=n._addDep(d);return r.set(d,p),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 Oe([],o,{describeKind:"derived",...e}),n}function Di(t,...e){let n=t;for(let r of e)n=r(n);return n}var ne=Ze(()=>{"use strict";Ee()});function Er(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 Ao(t){let e=t.trim().split(/\s+/);if(e.length!==5)throw new Error(`Invalid cron: expected 5 fields, got ${e.length}`);return{minutes:Er(e[0],0,59),hours:Er(e[1],0,23),daysOfMonth:Er(e[2],1,31),months:Er(e[3],1,12),daysOfWeek:Er(e[4],0,6)}}function Lo(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 Fi=Ze(()=>{"use strict"});var Zu={};we(Zu,{NS_PER_MS:()=>Ve,NS_PER_SEC:()=>ot,constant:()=>Io,decorrelatedJitter:()=>Fo,exponential:()=>Po,fibonacci:()=>Go,linear:()=>Do,resolveBackoffPreset:()=>$t,withMaxAttempts:()=>$i});function un(t){return t<0?0:t}function mf(t,e){return e==="none"?t:e==="full"?Math.random()*t:t/2+Math.random()*(t/2)}function hf(t,e){return t+Math.random()*(e-t)}function Io(t){let e=un(t);return()=>e}function Do(t,e){let n=un(t),r=e===void 0?n:un(e);return o=>n+r*Math.max(0,o)}function Po(t){let e=un(t?.baseNs??1e8),n=t?.factor!==void 0&&t.factor<1?1:t?.factor??2,r=un(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 mf(i,o)}}function Go(t=100*1e6,e=30*1e9){let n=un(t),r=un(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 Fo(t=100*1e6,e=30*1e9){return(n,r,o)=>{let i=Math.min(e,(o??t)*3);return hf(t,i)}}function $i(t,e){return(n,r,o)=>n>=e?null:t(n,r,o)}function $t(t){if(t==="constant")return Io(1*1e9);if(t==="linear")return Do(1*1e9);if(t==="exponential")return Po();if(t==="fibonacci")return Go();if(t==="decorrelatedJitter")return Fo();throw new Error(`Unknown backoff preset: "${String(t)}". Use one of: constant, linear, exponential, fibonacci, decorrelatedJitter`)}var Ve,ot,Kn=Ze(()=>{"use strict";Ve=1e6,ot=1e9});var Ce,vt=Ze(()=>{"use strict";Ce=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 tc={};we(tc,{CircuitOpenError:()=>dt,RateLimiterOverflowError:()=>cn,TimeoutError:()=>dn,circuitBreaker:()=>Tt,fallback:()=>Un,rateLimiter:()=>qn,retry:()=>Hn,retrySource:()=>Bt,timeout:()=>zn,tokenBucket:()=>jt,withBreaker:()=>Wn,withStatus:()=>Vt});function ln(t){return{describeKind:"derived",...t}}function gf(t){return t<0?0:t}function $o(t){return t[1]}function ec(t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("backoff strategy must return a finite number");return t<0?0:t}function Hn(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"?$t(r):r;return W(i=>{let a=0,u=!1,c=null,d,l=new Ce;function p(){d?.(),d=void 0}function f(g){if(u)return;if(a>=o){p(),i.down([[M,g]]);return}let h=s===null?0:s(a,g,c);if(h==null){p(),i.down([[M,g]]);return}let y;try{y=ec(h)}catch{p(),i.down([[M,g]]);return}c=y,a+=1,p();let b=y>0?y/1e6:1;l.start(b,()=>{u||m()})}function m(){l.cancel(),p(),d=t.subscribe(g=>{if(!u)for(let h of g){let y=h[0];if(y===te)i.down([[te]]);else if(y===S)a=0,c=null,i.emit(h[1]);else if(y===B)i.down([[B]]);else if(y===C)p(),i.down([[C]]);else if(y===M){f($o(h));return}else i.down([h])}})}return m(),()=>{u=!0,l.cancel(),p()}},{...ln(),initial:t.cache})}function Bt(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"?$t(r):r;return W(i=>{let a=0,u=!1,c=null,d,l=new Ce;function p(){d?.(),d=void 0}function f(g){if(u)return;if(a>=o){p(),i.down([[M,g]]);return}let h=s===null?0:s(a,g,c);if(h==null){p(),i.down([[M,g]]);return}let y;try{y=ec(h)}catch{p(),i.down([[M,g]]);return}c=y,a+=1,p();let b=y>0?y/1e6:1;l.start(b,()=>{u||m()})}function m(){l.cancel(),p();let g;try{g=t()}catch(h){f(h);return}d=g.subscribe(h=>{if(!u)for(let y of h){let b=y[0];if(b===te)i.down([[te]]);else if(b===S)a=0,c=null,i.emit(y[1]);else if(b===B)i.down([[B]]);else if(b===C)p(),i.down([[C]]);else if(b===M){f($o(y));return}else i.down([y])}})}return m(),()=>{u=!0,l.cancel(),p()}},{...ln(),initial:e?.initial})}function Tt(t){let e=Math.max(1,t?.failureThreshold??5),n=gf(t?.cooldownNs??30*1e9),r=t?.cooldown??null,o=Math.max(1,t?.halfOpenMax??1),s=t?.now??j,i="closed",a=0,u=0,c=0,d=n,l=0;function p(){if(!r)return n;let g=r(u);return g!==null?g:n}function f(){i="open",d=p(),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(g){if(i==="half-open"){u++,f();return}i==="closed"&&(a++,a>=e&&f())},get state(){return i},get failureCount(){return a},reset(){i="closed",a=0,u=0,l=0}}}function Wn(t,e){let n=e?.onOpen??"skip";return r=>{let o=H([],(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===te?i.down([[te]]):l===S?t.canExecute()?(a(),i.emit(d[1])):(a(),n==="error"?i.down([[M,new dt]]):i.down([[B]])):l===B?i.down([[B]]):l===C?(t.recordSuccess(),a(),i.down([[C]])):l===M?(t.recordFailure($o(d)),a(),i.down([d])):i.down([d])}});return a(),u},{...ln(),meta:{breakerState:t.state},completeWhenDepsComplete:!1,initial:r.cache});return{node:o,breakerState:o.meta.breakerState}}}function jt(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=j();function o(s){if(e>0){let i=s-r;n=Math.min(t,n+i/1e9*e)}r=s}return{available(){return o(j()),n},tryConsume(s=1){if(s<=0)return!0;let i=j();return o(i),n>=s?(n-=s,!0):!1},putBack(s=1){s<=0||(o(j()),n=Math.min(t,n+s))}}}function qn(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=jt(n,i),c=[],d=new Ce,l=!1,p=1e9/i;function f(){for(;c.length>0;)if(u.tryConsume(1))a.emit(c.shift());else{d.start(Math.max(1,p/1e6),f);return}}let m=t.subscribe(g=>{for(let h of g){if(l)return;let y=h[0];if(y===te)a.down([[te]]);else if(y===S){if(o!==void 0&&c.length>=o){if(s!=="drop-newest")if(s==="drop-oldest")c.shift(),c.push(h[1]);else{l=!0,d.cancel(),c.length=0,a.down([[M,new cn(o)]]);return}}else c.push(h[1]);f()}else if(y===B)a.down([[B]]);else if(y===C)l=!0,d.cancel(),c.length=0,a.down([[C]]);else if(y===M)l=!0,d.cancel(),c.length=0,a.down([h]);else if(y===pe){l=!0,d.cancel(),c.length=0,a.down([h]);return}else a.down([h])}});return()=>{l=!0,d.cancel(),m()}},{...ln(),initial:t.cache})}function Vt(t,e){let n=e?.initialStatus??"pending",r=H([],(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===te)s.down([[te]]);else if(d===S)i==="errored"?Q(()=>{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===C)r.meta.status.down([[S,"completed"]]),i="completed",s.down([[C]]);else if(d===M){let l=$o(c);Q(()=>{r.meta.error.down([[S,l]]),r.meta.status.down([[S,"errored"]])}),i="errored",s.down([c])}else s.down([c])}})},{...ln(),meta:{status:n,error:null},completeWhenDepsComplete:!1,resubscribable:!0,initial:t.cache});return{node:r,status:r.meta.status,error:r.meta.error}}function yf(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function bf(t){return t!=null&&typeof t.then=="function"}function vf(t){return t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function"}function Un(t,e){return W(n=>{let r,o;function s(){o?.(),o=void 0,yf(e)||bf(e)||vf(e)?r=U(e).subscribe(a=>{n.down(a)}):(n.emit(e),n.down([[C]]))}return o=t.subscribe(i=>{for(let a of i){let u=a[0];if(u===te)n.down([[te]]);else if(u===S)n.emit(a[1]);else if(u===B)n.down([[B]]);else if(u===C)n.down([[C]]);else if(u===M){s();return}else if(u===pe){r?.(),n.down([a]);return}else n.down([a])}}),()=>{o?.(),r?.()}},{...ln(),initial:t.cache})}function zn(t,e){if(e<=0)throw new RangeError("timeoutNs must be > 0");return W(n=>{let r=!1,o=new Ce;function s(){let a=e/1e6;o.start(a,()=>{r||(r=!0,i(),n.down([[M,new dn(e)]]))})}let i=t.subscribe(a=>{for(let u of a){if(r)return;let c=u[0];if(c===te)n.down([[te]]);else if(c===S)s(),n.emit(u[1]);else if(c===B)n.down([[B]]);else if(c===C){o.cancel(),r=!0,n.down([[C]]);return}else if(c===M){o.cancel(),r=!0,n.down([u]);return}else if(c===pe){o.cancel(),r=!0,n.down([u]);return}else n.down([u])}});return s(),()=>{r=!0,o.cancel(),i()}},{...ln(),initial:t.cache})}var dt,cn,dn,Et=Ze(()=>{"use strict";Ne();ke();ie();Ee();ne();Kn();be();vt();dt=class extends Error{name="CircuitOpenError";constructor(){super("Circuit breaker is open")}};cn=class extends Error{name="RateLimiterOverflowError";constructor(e){super(`rateLimiter buffer overflow (maxBuffer=${e})`)}};dn=class extends Error{name="TimeoutError";constructor(e){super(`Timed out after ${e/1e6}ms`)}}});function it(t){return{describeKind:"producer",...t}}function ji(t){return/[\\^$+?.()|[\]{}]/.test(t)?`\\${t}`:t}function rc(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+=ji(r)}return e+="$",new RegExp(e)}function oc(t,e){for(let n of e)if(n.test(t))return!0;return!1}function Tf(t,e){let n=H([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 at(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",p)},l=()=>{i||(r!=null?(s.emit(a++),c=setInterval(()=>{i||s.emit(a++)},r)):(i=!0,n?.removeEventListener("abort",p),s.emit(a++),s.down([[C]])))},p=()=>{i||(d(),s.down([[M,n.reason]]))};if(n?.aborted){p();return}return u=setTimeout(l,t),n?.addEventListener("abort",p,{once:!0}),d},it(o))}function sc(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,p=()=>{s!==void 0&&d&&d(s),i!==void 0&&clearTimeout(i),s=void 0,i=void 0},f=()=>{o=!0,p(),a&&(e?.removeEventListener("abort",m),a=!1),u&&l&&(l.removeEventListener("visibilitychange",y),u=!1)},m=()=>{o||(f(),r.down([[M,e.reason]]))},g=b=>{o||(r.emit(b),h())},h=()=>{o||(c&&(!l||l.visibilityState!=="hidden")?s=c(g):i=setTimeout(()=>g(performance.now()),16))},y=()=>{o||(p(),h())};return e?.aborted?(m(),f):(e?.addEventListener("abort",m,{once:!0}),a=e!==void 0,l&&c&&(l.addEventListener("visibilitychange",y),u=!0),h(),f)},it(n))}function jo(t,e){let n=Ao(t),{tickMs:r,output:o,...s}=e??{},i=r??6e4,a=o==="date";return W(u=>{let c=-1,d=()=>{let p=new Date,f=p.getFullYear()*1e8+(p.getMonth()+1)*1e6+p.getDate()*1e4+p.getHours()*100+p.getMinutes();f!==c&&Lo(n,p)&&(c=f,u.emit(a?p:fe()))};d();let l=setInterval(d,i);return()=>clearInterval(l)},{...it(s),name:s.name??`cron:${t}`})}function ic(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)},it(i))}function Vo(t,e){return W(n=>{let r=!1;try{for(let o of t){if(r)return;n.emit(o)}r||n.down([[C]])}catch(o){r||n.down([[M,o]])}return()=>{r=!0}},it(e))}function wf(t){return t!=null&&typeof t.then=="function"}function Vi(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([[C]]))},a=>{s||(s=!0,n?.removeEventListener("abort",i),o.down([[M,a]]))}),()=>{s=!0,n?.removeEventListener("abort",i)}},it(r))}function Ki(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([[C]]);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(()=>{})}},it(r))}function kf(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function U(t,e){if(kf(t))return t;if(wf(t))return Vi(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return Ki(t,e);if(typeof n[Symbol.iterator]=="function")return Vo(t,e)}return Hi(t)}function Hi(...t){return Vo(t,void 0)}function ac(t){return W(e=>{e.down([[C]])},it(t))}function uc(t){return W(()=>{},it(t))}function cc(t,e){return W(n=>{n.down([[M,t]])},it(e))}function Kt(t,e,n){return H([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 dc(t,e){return H([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([[C]]);return}(i==null||i.length===0)&&r.down([[B]])},{describeKind:"derived",completeWhenDepsComplete:!1,...e})}function lc(t,e){return W(n=>t.subscribe(r=>{n.down(r)}),{...it(e),initial:t.cache})}function Ko(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)}),{...it(n),initial:t.cache});return Tf(o,s=>{for(let i of r)s([[S,i]])})}function pc(t,e){return Ko(t,1,e)}function Je(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]===C){r=!0,n(new Error("completed without DATA")),s?(s(),s=void 0):o=!0;return}}}),o&&(s?.(),s=void 0)})}function Bo(t,e,n){return new Promise((r,o)=>{let s=!1,i=!1,a,u=n?.skipCurrent===!0;a=t.subscribe(c=>{for(let d of c){if(s)return;if(!(u&&d[0]===S)){if(d[0]===S){let l=d[1];if(e(l)){s=!0,r(l),a?(a(),a=void 0):i=!0;return}}if(d[0]===M){s=!0,o(d[1]),a?(a(),a=void 0):i=!0;return}if(d[0]===C){s=!0,o(new Error("completed without matching value")),a?(a(),a=void 0):i=!0;return}}}}),u=!1,i&&(a?.(),a=void 0)})}async function Ho(t,e){let n=e?.predicate??(s=>s!=null),r=e?.skipCurrent;if(e?.timeoutMs==null||e.timeoutMs<=0)return await Bo(t,n,{skipCurrent:r});if(Bi===void 0){let[s,i]=await Promise.all([Promise.resolve().then(()=>(Et(),tc)),Promise.resolve().then(()=>(Kn(),Zu))]);Bi=s.timeout,nc=i.NS_PER_MS}let o=Bi(t,e.timeoutMs*nc);return await Bo(o,n,{skipCurrent:r})}function Wo(t,e){let n=new AbortController,r=e?.reason??new Error("cancelled via nodeSignal"),o,s=!1,i=()=>{o?(o(),o=void 0):s=!0};return o=t.subscribe(a=>{if(!n.signal.aborted)for(let u of a){if(u[0]===S&&u[1]===!0){n.abort(r),i();return}if(u[0]===M){n.abort(u[1]),i();return}if(u[0]===C){i();return}}}),s&&(o?.(),o=void 0),{signal:n.signal,dispose:()=>{o&&(o(),o=void 0)}}}function oe(t){return t.subscribe(()=>{})}function Wi(t){let e=N(0);return{node:e,increment(){let n=e.cache??0;return n>=t?!1:(e.down([[te],[S,n+1]]),!0)},get(){return e.cache??0},atCap(){return(e.cache??0)>=t}}}var Bi,nc,fc,be=Ze(()=>{"use strict";ke();ie();Ee();ne();Fi();fc=Ko});var Jy={};we(Jy,{COMPLETE:()=>C,COMPLETE_MSG:()=>To,COMPLETE_ONLY_BATCH:()=>pr,CircuitOpenError:()=>dt,ContentAddressedMissError:()=>Vr,DATA:()=>S,DEFAULT_ACTOR:()=>bt,DIRTY:()=>te,DIRTY_MSG:()=>Rt,DIRTY_ONLY_BATCH:()=>On,ENVELOPE_VERSION:()=>An,ERROR:()=>M,GRAPH_META_SEGMENT:()=>He,Graph:()=>z,GraphReFlyConfig:()=>nn,GuardDenied:()=>tt,INVALIDATE:()=>ze,INVALIDATE_MSG:()=>vo,INVALIDATE_ONLY_BATCH:()=>lr,JsonCodec:()=>ko,NS_PER_MS:()=>Ve,NS_PER_SEC:()=>ot,NativeIndexBackend:()=>Wr,NativeListBackend:()=>qr,NativeLogBackend:()=>Ar,NativeMapBackend:()=>Br,NativePubSubBackend:()=>Hr,NodeImpl:()=>Oe,PAUSE:()=>Fe,RESOLVED:()=>B,RESOLVED_MSG:()=>_n,RESOLVED_ONLY_BATCH:()=>dr,RESUME:()=>je,RateLimiterOverflowError:()=>cn,ResettableTimer:()=>Ce,SIZEOF_OVERHEAD:()=>Pe,SIZEOF_SYMBOL:()=>Zo,SNAPSHOT_VERSION:()=>lt,SNAPSHOT_WIRE_VERSION:()=>go,START:()=>yt,START_MSG:()=>Mn,SurfaceError:()=>Re,TEARDOWN:()=>pe,TEARDOWN_MSG:()=>wo,TEARDOWN_ONLY_BATCH:()=>Cn,TimeoutError:()=>dn,accessHintForGuard:()=>kr,accountability:()=>Zs,advanceVersion:()=>xr,ai:()=>Ys,asSurfaceError:()=>hi,audit:()=>fd,autoTrackNode:()=>sn,awaitSettled:()=>Ho,batch:()=>Q,buffer:()=>md,bufferCount:()=>hd,bufferTime:()=>yd,cached:()=>pc,canonicalJson:()=>Kr,cascadingCache:()=>Sl,catchError:()=>Ed,checkpointToRedis:()=>yl,checkpointToS3:()=>gl,circuitBreaker:()=>Tt,combine:()=>la,combineLatest:()=>Rd,compat:()=>ca,concat:()=>id,concatMap:()=>cd,configure:()=>Ii,constant:()=>Io,contentAddressedStorage:()=>ws,core:()=>Xi,cqrs:()=>is,createDagCborCodec:()=>Ni,createDagCborZstdCodec:()=>Ei,createGraph:()=>ir,createTransport:()=>Ut,createVersioning:()=>Dn,createWatermarkController:()=>Jn,csvRows:()=>Xd,debounce:()=>fa,debounceTime:()=>Sd,decodeEnvelope:()=>mr,decorrelatedJitter:()=>Fo,defaultConfig:()=>De,defaultHash:()=>Ft,delay:()=>ld,deleteSnapshot:()=>ki,demoShell:()=>ti,derived:()=>_,deserializeError:()=>vn,dictStorage:()=>Pl,diffForWAL:()=>rs,diffSnapshots:()=>Ti,distill:()=>vs,distinctUntilChanged:()=>rd,domainTemplates:()=>ni,downWithBatch:()=>Nt,dynamicNode:()=>Rr,effect:()=>ce,elementAt:()=>ed,empty:()=>ac,encodeEnvelope:()=>fr,escapeRegexChar:()=>ji,exhaustMap:()=>ud,explainPath:()=>Or,exponential:()=>Po,externalBundle:()=>gs,externalProducer:()=>gn,extra:()=>Ra,fallback:()=>Un,fibonacci:()=>Go,filter:()=>ft,find:()=>Zc,first:()=>ys,firstValueFrom:()=>Je,firstWhere:()=>Bo,flatMap:()=>dd,forEach:()=>Kt,fromAny:()=>U,fromAsyncIter:()=>Ki,fromCSV:()=>Qd,fromClickHouseWatch:()=>nl,fromCron:()=>jo,fromDrizzle:()=>kl,fromEvent:()=>ic,fromHTTP:()=>ba,fromHTTPPoll:()=>Gd,fromHTTPStream:()=>Pd,fromIter:()=>Vo,fromKafka:()=>Ud,fromKysely:()=>xl,fromMCP:()=>Bd,fromNATS:()=>sl,fromNDJSON:()=>tl,fromOTel:()=>jd,fromPrisma:()=>wl,fromPrometheus:()=>qd,fromPromise:()=>Vi,fromPulsar:()=>rl,fromRabbitMQ:()=>al,fromRaf:()=>sc,fromRedisStream:()=>Jd,fromSSE:()=>Dd,fromSqlite:()=>bl,fromSqliteCursor:()=>vl,fromStatsD:()=>Hd,fromSyslog:()=>Vd,fromTimer:()=>at,fromWebSocket:()=>ya,fromWebSocketReconnect:()=>$d,fromWebhook:()=>_d,globToRegExp:()=>rc,graph:()=>ea,graphProfile:()=>mn,graphspec:()=>Js,guarded:()=>oi,harness:()=>ai,interval:()=>Td,isBatching:()=>tn,isV1:()=>Ci,jobQueue:()=>di,jotai:()=>No,keepalive:()=>oe,last:()=>Xc,layout:()=>fi,lens:()=>pi,linear:()=>Do,listSnapshots:()=>wi,lru:()=>wa,makeHttpError:()=>ht,map:()=>Dr,matchesAnyPattern:()=>oc,matchesCron:()=>Lo,memory:()=>qs,memoryStorage:()=>zr,merge:()=>wt,mergeMap:()=>pa,mermaidLiveUrl:()=>ns,messaging:()=>Bs,monotonicNs:()=>j,nameToSignal:()=>yn,nanostores:()=>Oo,ndjsonRows:()=>Zd,nestjs:()=>us,never:()=>uc,node:()=>H,nodeSignal:()=>Wo,normalizeActor:()=>St,of:()=>Hi,onFirstData:()=>Gr,orchestration:()=>js,pairwise:()=>od,parseCron:()=>Ao,parsePrometheusText:()=>va,parseSSEStream:()=>Lt,parseStatsD:()=>Wd,parseSyslog:()=>Kd,patterns:()=>wu,pausable:()=>kd,pipe:()=>Di,policy:()=>rn,policyFromRules:()=>wr,producer:()=>W,pubsub:()=>Ol,race:()=>ad,rateLimiter:()=>qn,reachable:()=>hn,react:()=>cs,reactiveCounter:()=>Wi,reactiveIndex:()=>Ll,reactiveList:()=>ks,reactiveLog:()=>We,reactiveMap:()=>Ye,reactiveSink:()=>Ke,reduce:()=>Jc,reduction:()=>zs,refine:()=>ii,registerBuiltinCodecs:()=>hr,registerBuiltins:()=>Tr,repeat:()=>wd,replay:()=>Ko,replayWAL:()=>_i,rescue:()=>Fr,resilientPipeline:()=>mi,resolveBackoffPreset:()=>$t,resolveDescribeFields:()=>_t,restoreSnapshot:()=>vi,retry:()=>Hn,retrySource:()=>Bt,runReduction:()=>gi,sample:()=>pd,saveSnapshot:()=>bi,scan:()=>zc,serializeError:()=>bn,share:()=>lc,shareReplay:()=>fc,signalToName:()=>qt,signals:()=>ls,singleFromAny:()=>xs,singleNodeFromAny:()=>Il,sizeof:()=>Cr,skip:()=>da,solid:()=>ps,sortJsonValue:()=>Ur,stableJsonString:()=>Dl,state:()=>N,stratify:()=>Jr,surface:()=>xi,svelte:()=>fs,switchMap:()=>ve,take:()=>Pr,takeUntil:()=>Qc,takeWhile:()=>Yc,tap:()=>td,tapFirst:()=>nd,throttle:()=>ma,throttleTime:()=>Nd,throwError:()=>cc,timeout:()=>zn,toArray:()=>dc,toCSV:()=>cl,toClickHouse:()=>dl,toFile:()=>Ta,toHTTP:()=>Md,toKafka:()=>zd,toLoki:()=>ml,toMongo:()=>fl,toNATS:()=>il,toObservable:()=>Co,toPostgres:()=>pl,toPulsar:()=>ol,toRabbitMQ:()=>ul,toReadableStream:()=>Id,toRedisStream:()=>Yd,toS3:()=>ll,toSSE:()=>Ad,toSSEBytes:()=>Ld,toSqlite:()=>Tl,toTempo:()=>hl,toWebSocket:()=>Fd,tokenBucket:()=>jt,validateGraphObservability:()=>Zi,valve:()=>xd,verifiable:()=>_l,version:()=>zy,vue:()=>ms,wallClockNs:()=>fe,watchTopologyTree:()=>Mt,window:()=>vd,windowCount:()=>gd,windowTime:()=>bd,withBreaker:()=>Wn,withLatestFrom:()=>At,withMaxAttempts:()=>$i,withStatus:()=>Vt,workerBridge:()=>ka,workerSelf:()=>xa,zip:()=>sd,zustand:()=>hs});module.exports=Wp(Jy);var ca={};we(ca,{jotai:()=>No,nanostores:()=>Oo,nestjs:()=>us,react:()=>cs,signals:()=>ls,solid:()=>ps,svelte:()=>fs,vue:()=>ms,zustand:()=>hs});var No={};we(No,{atom:()=>sf});ie();ne();function sf(t,e,n){if(typeof t=="function"){let r=t;return typeof e=="function"?Fu(r,e,n):Fu(r,void 0,e)}return af(t,e)}function Sr(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 af(t,e){let n=N(t,{...e,resubscribable:!0,resetOnTeardown:!0});return{get:()=>n.status==="sentinel"?Sr(n):n.cache,set:r=>n.emit(r),update:r=>{let o=n.status==="sentinel"?Sr(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 Fu(t,e,n){let r=sn(s=>t(i=>{let a=i._node;return a.status==="sentinel"&&Sr(a),s(a)}),{...n,resubscribable:!0,resetOnTeardown:!0}),o={get:()=>r.status==="sentinel"?Sr(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"?Sr(r):r.cache;return e(s,i,u(c))},a}return o}var Oo={};we(Oo,{action:()=>ff,atom:()=>uf,computed:()=>cf,getValue:()=>lf,map:()=>df,onMount:()=>pf,onStart:()=>ju,onStop:()=>Vu});Ne();ie();ne();var _o=new WeakMap,Mo=new WeakMap;function Eo(t,e){let n=e.get(t);if(n)for(let r of n)r()}function Pi(t,e={}){let n=0;return{...e,get:()=>Bu(t),subscribe:o=>{n===0&&Eo(t,_o),n++;let s=t.subscribe(i=>{for(let[a,u]of i)a===S&&o(u)});return()=>{s(),n--,n===0&&Eo(t,Mo)}},listen:o=>{n===0&&Eo(t,_o),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&&Eo(t,Mo)}},_node:t}}function $u(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 Bu(t){return t.status==="sentinel"?$u(t):t.cache}function uf(t){let e=N(t,{resubscribable:!0,resetOnTeardown:!0});return Pi(e,{set:n=>e.emit(n)})}function cf(t,e){let n=Array.isArray(t)?t:[t],r=n.map(s=>s._node),o=Rr(r,s=>{let i=n.map(a=>{let u=a._node;return u.status==="sentinel"&&$u(u),s(u)});return e(...i)},{resubscribable:!0,resetOnTeardown:!0,equals:Object.is});return Pi(o)}function df(t){let e=N(t,{resubscribable:!0,resetOnTeardown:!0,equals:()=>!1});return Pi(e,{set:n=>e.emit(n),setKey:(n,r)=>{let o=Bu(e);e.emit({...o,[n]:r})}})}function lf(t){return t.get()}function ju(t,e){let n=t._node,r=_o.get(n);r||(r=new Set,_o.set(n,r)),r.add(e)}function Vu(t,e){let n=t._node,r=Mo.get(n);r||(r=new Set,Mo.set(n,r)),r.add(e)}function pf(t,e){ju(t,()=>{let n=e();typeof n=="function"&&Vu(t,n)})}function ff(t,e,n){return(...r)=>{let o;return Q(()=>{o=n(...r)}),o}}var us={};we(us,{ACTOR_KEY:()=>Uo,COMMAND_HANDLERS:()=>$n,CQRS_EVENT_HANDLERS:()=>Bn,CRON_HANDLERS:()=>Fn,CommandHandler:()=>Ju,EVENT_HANDLERS:()=>Pn,EventHandler:()=>Yu,GRAPHREFLY_REQUEST_GRAPH:()=>an,GRAPHREFLY_ROOT_GRAPH:()=>st,GraphCron:()=>zu,GraphInterval:()=>Uu,GraphReflyEventExplorer:()=>pn,GraphReflyGuard:()=>vc,GraphReflyGuardImpl:()=>_r,GraphReflyModule:()=>as,INTERVAL_HANDLERS:()=>Gn,InjectCqrsGraph:()=>Hu,InjectGraph:()=>Ku,InjectNode:()=>Wu,ObserveGateway:()=>qo,OnGraphEvent:()=>qu,QUERY_HANDLERS:()=>jn,QueryHandler:()=>Qu,SAGA_HANDLERS:()=>Vn,SagaHandler:()=>Xu,fromHeader:()=>yc,fromJwtPayload:()=>zi,getActor:()=>bc,getGraphToken:()=>nt,getNodeToken:()=>ct,observeSSE:()=>hc,observeSubscription:()=>gc,toObservable:()=>Co});var Gi=require("rxjs");ie();function Co(t,e){return e?.raw?new Gi.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]===C){n.complete();return}}}})):new Gi.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]===C){n.complete();return}}}))}var Nr=require("@nestjs/common");var st=Symbol.for("graphrefly:root-graph");var an=Symbol.for("graphrefly:request-graph");function nt(t){return Symbol.for(`graphrefly:graph:${t}`)}function ct(t){return Symbol.for(`graphrefly:node:${t}`)}var Pn=new Map,Gn=new Map,Fn=new Map,$n=new Map,Bn=new Map,jn=new Map,Vn=new Map;function Ku(t){return t==="request"?(0,Nr.Inject)(an):(0,Nr.Inject)(t?nt(t):st)}function Hu(t){return(0,Nr.Inject)(nt(t))}function Wu(t){return(0,Nr.Inject)(ct(t))}function qu(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=Pn.get(o)??[];s.push({nodeName:t,methodKey:r}),Pn.set(o,s)})}}function Uu(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=Gn.get(o)??[];s.push({ms:t,methodKey:r}),Gn.set(o,s)})}}function zu(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=Fn.get(o)??[];s.push({expr:t,methodKey:r}),Fn.set(o,s)})}}function Ju(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=$n.get(s)??[];i.push({cqrsName:t,commandName:e,methodKey:o}),$n.set(s,i)})}}function Yu(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=Bn.get(s)??[];i.push({cqrsName:t,eventName:e,methodKey:o}),Bn.set(s,i)})}}function Qu(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=jn.get(s)??[];i.push({cqrsName:t,projectionName:e,methodKey:o}),jn.set(s,i)})}}function Xu(t,e,n){return(r,o)=>{let s=o.name;o.addInitializer(function(){let i=this.constructor,a=Vn.get(i)??[];a.push({cqrsName:t,eventNames:n,sagaName:e,methodKey:s}),Vn.set(i,a)})}}ie();be();var mc=0,pn=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 Pn){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 Gn){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)}.${mc++}`,u=at(r.ms,{period:r.ms,name:a});this.graph.add(u),this.scheduleNodeNames.push(a);let d=this.observeNode(a).subscribe(l=>{for(let p of l)p[0]===S&&s(p[1])});this.disposers.push(d)}wireCrons(){for(let[e,n]of Fn){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)}.${mc++}`,u=jo(r.expr,{name:a});this.graph.add(u),this.scheduleNodeNames.push(a);let d=this.observeNode(a).subscribe(l=>{for(let p of l)p[0]===S&&s(p[1])});this.disposers.push(d)}wireCqrsCommands(){for(let[e,n]of $n){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 Bn){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 p of l)if(p[0]===S){let f=p[1];for(let m of f)m.seq>u&&(o(m),u=m.seq)}});this.disposers.push(d)}wireCqrsQueries(){for(let[e,n]of jn){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 Vn){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(nt(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 xf=0;function Jn(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-${++xf}`),r=0,o=!1;return{onEnqueue(){return r+=1,!o&&r>=e.highWaterMark?(o=!0,t([[Fe,n]]),!0):!1},onDequeue(){return r>0&&(r-=1),o&&r<=e.lowWaterMark?(o=!1,t([[je,n]]),!0):!1},get pending(){return r},get paused(){return o},dispose(){o&&(o=!1,t([[je,n]]))}}}function hc(t,e,n){let{actor:r,serialize:o=Rf,keepAliveMs:s,signal:i}=n??{},a=new TextEncoder,u,c=n?.highWaterMark!=null,d,l,p=[],f=!1;return new ReadableStream({start(m){let g,h=()=>{},y=()=>{if(!f){f=!0,g!==void 0&&clearInterval(g),i?.removeEventListener("abort",b),h(),d?.dispose(),l?.(),l=void 0;for(let T of p)m.enqueue(T.frame);p.length=0,m.close()}};u=y;let b=()=>y(),v=t.observe(e,{actor:r});c&&(d=Jn(T=>v.up(T),{highWaterMark:n.highWaterMark,lowWaterMark:n.lowWaterMark??Math.floor(n.highWaterMark/2)})),h=v.subscribe(T=>{for(let w of T){if(f)return;let k=w[0];if(k===S){let x=a.encode(qi("data",o(w[1])));c?(p.push({frame:x,counted:!0}),d.onEnqueue(),l?.(),l=void 0):m.enqueue(x)}else if(k===M){let x=a.encode(qi("error",o(w[1])));c?(p.push({frame:x,counted:!1}),l?.(),l=void 0):m.enqueue(x),y();return}else if(k===C||k===pe){if(k===C){let x=a.encode(qi("complete"));c?(p.push({frame:x,counted:!1}),l?.(),l=void 0):m.enqueue(x)}y();return}}}),s!==void 0&&s>0&&(g=setInterval(()=>{f||(c?(p.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 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}
5
+ `)))},s)),i?.aborted?b():i?.addEventListener("abort",b,{once:!0})},pull(m){if(c&&!f){if(p.length>0){let g=p.shift();m.enqueue(g.frame),g.counted&&d.onDequeue();return}return new Promise(g=>{l=g})}},cancel(){try{u?.()}catch{}}})}function gc(t,e,n){let{actor:r,filter:o}=n??{},s=[],i=[],a=!1,u=t.observe(e,{actor:r}),c=n?.highWaterMark!=null?Jn(m=>u.up(m),{highWaterMark:n.highWaterMark,lowWaterMark:n.lowWaterMark??Math.floor(n.highWaterMark/2)}):void 0,d=()=>{a||(a=!0,c?.dispose(),p())},l=m=>{if(!a)if(i.length>0){let g=i.shift();m.done&&m.error?g.reject(m.error):m.done?g.resolve({done:!0,value:void 0}):g.resolve({done:!1,value:m.value})}else s.push(m),m.done||c?.onEnqueue()},p=u.subscribe(m=>{for(let g of m){let h=g[0];if(h===S){let y=g[1];if(o&&!o(y))continue;l({done:!1,value:y})}else if(h===M){let y=g[1]instanceof Error?g[1]:new Error(String(g[1]));l({done:!0,error:y}),d();return}else if(h===C||h===pe){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,g)=>{i.push({resolve:m,reject:g})})},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 qo=class{constructor(e,n){this.graph=e;this.extractActor=n?.extractActor??(()=>{}),this.parse=n?.parse??Sf,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??Nf.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?Jn(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 p=l[0];if(p===S)a?.onEnqueue(),Ui(r,{type:"data",path:n,value:l[1]});else if(p===M){let f=l[1]instanceof Error?l[1].message:String(l[1]);Ui(r,{type:"error",path:n,error:f}),u();return}else if(p===C||p===pe){Ui(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 Rf(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)}catch{return String(t)}}function qi(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 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}
9
+ `,n}function Sf(t){return JSON.parse(t)}function Nf(t,e){try{t.send(JSON.stringify(e))}catch{}}function Ui(t,e){try{t(e)}catch{}}gr();var Uo="graphReflyActor";function zi(t){return e=>{let r=e.switchToHttp().getRequest()?.user;if(r!=null)return t?t(r):r}}function yc(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 bc(t){let e=t?.[Uo];return e!=null?St(e):bt}var _r=class{constructor(e){this.extractor=e}canActivate(e){let n=St(this.extractor(e)),r=e.switchToHttp().getRequest();return r!=null&&(r[Uo]=n),!0}};function vc(t){return new _r(t??zi())}var Ir=require("@nestjs/common"),Kc=require("@nestjs/core");gr();Ne();ke();on();ie();on();Ee();function _t(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 Ef(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function _f(t){let e={};for(let[n,r]of Object.entries(t.meta))try{e[n]=r.cache}catch{}return e}function Mr(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 Oe&&(s=Ef(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 Oe?t._guard:void 0;if(o){let c={..._f(t)};if(u!=null&&c.access===void 0&&(c.access=kr(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=kr(u)),(n||e.has("lastMutation"))&&t.lastMutation!=null&&(a.lastMutation=t.lastMutation),a}Ee();ne();be();vt();var fn=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}};xo();function Ji(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 Yn(t){let e=0;for(let n of t)e+=Ji(n.codePointAt(0));return e}function Tc(t,e){if(e<=0)return"";let n=0,r="";for(let o of t){let s=Ji(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-=Ji(i.codePointAt(0))}return`${r}\u2026`}r+=o,n+=s}return r}var Mf={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"},Of={horizontal:"-",vertical:"|",cornerTL:"+",cornerTR:"+",cornerBL:"+",cornerBR:"+",tDown:"+",tUp:"+",tRight:"+",tLeft:"+",cross:"+",arrowRight:">",arrowDown:"v",arrowLeft:"<",arrowUp:"^",boxTL:"+",boxTR:"+",boxBL:"+",boxBR:"+",boxH:"-",boxV:"|"};function Rc(t,e){let n=e.charset==="ascii"?Of:Mf,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)Af(s,i,n,a);for(let a of t.boxes)Cf(s,i,n,a,e.labelOf(a.id));return s.map(a=>Pf(a.join(""))).join(`
10
+ `)}function Cf(t,e,n,r,o){let{x:s,y:i,w:a,h:u}=r;if(a<2||u<2){u>0&&wc(t,e,s,i,a,o);return}Ht(t,e,s,i,n.boxTL);for(let d=s+1;d<s+a-1;d+=1)Ht(t,e,d,i,n.boxH);Ht(t,e,s+a-1,i,n.boxTR);for(let d=i+1;d<i+u-1;d+=1){Ht(t,e,s,d,n.boxV);for(let l=s+1;l<s+a-1;l+=1)Sc(t,e,l,d," ","empty");Ht(t,e,s+a-1,d,n.boxV)}Ht(t,e,s,i+u-1,n.boxBL);for(let d=s+1;d<s+a-1;d+=1)Ht(t,e,d,i+u-1,n.boxH);Ht(t,e,s+a-1,i+u-1,n.boxBR);let c=i+Math.floor(u/2);wc(t,e,s+1,c,a-2,o)}function Ht(t,e,n,r,o){Sc(t,e,n,r,o,o===" "?"empty":o==="\u2500"||o==="-"?"boxH":o==="\u2502"||o==="|"?"boxV":"boxCorner")}function Sc(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 wc(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=Yn(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 Af(t,e,n,r){let o=r.points;if(o.length<2)return;for(let u=0;u+1<o.length;u+=1)Lf(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],p=If(c,d,l,n);p&&xc(t,e,d.x,d.y,p,"edgeCorner")}let s=o[o.length-1],i=o[o.length-2],a=Df(i,s,n);a&&xc(t,e,s.x,s.y,a,"arrow")}function Lf(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)kc(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)kc(t,e,s,u,n,"v")}}}function kc(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 xc(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 If(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 Df(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 Pf(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}function _c(t){let e=Gf(t);Ff(e),$f(e),Bf(e),jf(e,t);let n=Hf(e,t),{width:r,height:o}=qf(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 Gf(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 Ff(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 $f(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 p=`__virt_${o++}__`,f={id:p,isVirtual:!0,layer:i.layer+l,order:0,x:0,y:0,w:0,h:1,in:[],out:[]};t.nodes.set(p,f),n[f.layer].push(f);let m={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:c.id,toId:p,hopIndex:l-1,chainLen:u};c.out.push(m),f.in.push(m),r.push(m),c=f}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 Bf(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)Nc(t,t.layers[r],"in"),zo(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)Nc(t,t.layers[r],"out"),zo(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=Ec(t,s[i],s[i+1],"in");[s[i],s[i+1]]=[s[i+1],s[i]],zo(s),Ec(t,s[i],s[i+1],"in")<a?r=!0:([s[i],s[i+1]]=[s[i+1],s[i]],zo(s))}}if(!r)break}}function Nc(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 zo(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function Ec(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 jf(t,e){e.direction==="LR"?Vf(t,e):Kf(t,e)}function Vf(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 Kf(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 p=[];for(let m of l){let g=t.nodes.get(s===0?m.fromId:m.toId);if(!g)continue;let h=n==="y"?g.y:g.x;p.push(h+Math.floor(r(g)/2))}if(p.length===0)continue;p.sort((m,g)=>m-g);let f=p[Math.floor(p.length/2)];u.set(d.id,f-Math.floor(r(d)/2))}let c=0;for(let d of a){let l=u.get(d.id),p=n==="y"?d.y:d.x,m=Math.max(l??p,c);n==="y"?d.y=m:d.x=m,c=m+r(d)+o}}}}function Hf(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],p=0;for(let R of d)p=Math.max(p,o(R)+s(R));let f=Number.POSITIVE_INFINITY;for(let R of l)f=Math.min(f,o(R));let m=Number.isFinite(f)?f-1:p,g=Math.max(1,m-p+1),h=[];for(let R of d)for(let E of R.out)h.push(E);h.sort((R,E)=>{let I=i(t.nodes.get(R.fromId)),O=i(t.nodes.get(E.fromId));if(I!==O)return I-O;let G=i(t.nodes.get(R.toId)),A=i(t.nodes.get(E.toId));return G-A});let y=[],b=new Map;for(let R of h){let E=i(t.nodes.get(R.fromId)),I=i(t.nodes.get(R.toId)),O=Math.min(E,I),G=Math.max(E,I),A=-1;for(let F=0;F<y.length;F+=1){let q=y[F],Y=!0;for(let D of q)if(D.lo<=G&&O<=D.hi){Y=!1;break}if(Y){q.push({lo:O,hi:G}),A=F;break}}A<0&&(y.push([{lo:O,hi:G}]),A=y.length-1),b.set(R,A)}let v=y.length,T=g>=Math.max(3,v+2),w=T?p+1:p,k=T?m-1:m,x=Math.max(1,k-w+1);for(let R of h){let E=b.get(R),I;if(v<=1)I=w+Math.floor(x/2);else{let O=(x-1)/(v-1);I=w+Math.floor(E*O)}a.set(R,Math.max(p,Math.min(m,I)))}}let u=[];for(let[,c]of n){let d=[];for(let p=0;p<c.length;p+=1){let f=c[p],m=t.nodes.get(f.fromId),g=t.nodes.get(f.toId),h=a.get(f),y=m.isVirtual?o(m):o(m)+s(m),b=g.isVirtual?o(g):o(g)-1,v=i(m),T=i(g);p===0&&Jo(d,r,y,v),v!==T&&(Jo(d,r,h,v),Jo(d,r,h,T)),Jo(d,r,b,T)}let l=c[0];u.push({from:l.chainFrom,to:l.chainTo,points:Wf(d)})}return u}function Jo(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function Wf(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 qf(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 Uf=24,zf=4,Jf=1,Yf=3;function Oc(t,e){let n=Qf(e.direction),r=Math.max(3,e.maxLabelWidth??Uf),o=e.asciiCharset??"unicode",s=Object.keys(t.nodes).sort(),i=new Set(s),a=t.edges.filter(f=>i.has(f.from)&&i.has(f.to)),u=new Map,c=new Map;for(let f of s){let m=Tc(f,r);u.set(f,m),c.set(f,Yn(m)+4)}let d=_c({nodes:s,edges:a,widthCells:f=>c.get(f)??3,heightCells:()=>Yf,layerGap:zf,nodeGap:Jf,direction:n}),l=Rc(d,{charset:o,labelOf:f=>u.get(f)??f}),p=e.logger;return p&&p(l),l}function Qf(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 Or(t,e,n,r={}){let o=e in t.nodes,s=n in t.nodes;if(!o)return Yo(e,n,"no-such-from");if(!s)return Yo(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=Xf(t,e,r);if(c!=null)return c}let u=Qo(e,t.nodes[e],0,r);return Xo(e,n,[u])}if(i===0)return Yo(e,n,"no-path");let a=Cc(t,e,n,i);return a.found?Xo(e,n,Ac(t,a.pathOrder,r)):Yo(e,n,a.truncated?"max-depth-exceeded":"no-path")}function Cc(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 g=t.nodes[l.path];g?.deps&&g.deps.length>0&&(u=!0);continue}let p=t.nodes[l.path];if(p==null)continue;let f=p.deps??[],m=new Map;for(let g=0;g<f.length;g++){let h=f[g];if(!h)continue;let y=m.get(h);y==null&&(y=[],m.set(h,y)),y.push(g)}for(let[g,h]of m)i.has(g)||(i.add(g),o.set(g,{from:l.path,depIndices:h}),s.push({path:g,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 Xf(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=Qo(e,r,0,n);a.dep_index=s[0];let u=Qo(e,r,1,n);return Xo(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=Cc(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:Xo(e,e,Ac(t,i.pathOrder,n))}function Ac(t,e,n){return e.map((r,o)=>{let s=t.nodes[r.path],i=Qo(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 Qo(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 Xo(t,e,n){return Lc(t,e,!0,"ok",n)}function Yo(t,e,n){return Lc(t,e,!1,n,[])}function Lc(t,e,n,r,o){let s=Zf(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 Zf(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: ${em(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 em(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)}}Ee();var Pe={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},Zo=Symbol.for("sizeof");function Cr(t){let e=new WeakSet,n=new WeakSet,r=[t],o=0;for(;r.length>0;){let s=r.pop();o+=tm(s,e,n,r)}return o}function tm(t,e,n,r){if(t==null)return 0;switch(typeof t){case"number":return Pe.number;case"boolean":return Pe.boolean;case"string":return Pe.string+t.length*2;case"bigint":return Pe.bigint+nm(t);case"symbol":return Pe.symbol;case"function":return e.has(t)?0:(e.add(t),Pe.function);case"undefined":return 0}let s=t;if(e.has(s))return 0;e.add(s);let i=s[Zo];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 Pe.date;if(s instanceof RegExp)return Pe.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 Pe.error+c+d}if(typeof URL<"u"&&s instanceof URL)return Pe.url+s.href.length*2;if(typeof Promise<"u"&&s instanceof Promise)return Pe.promise;if(s instanceof WeakMap)return Pe.weakmap;if(s instanceof WeakSet)return Pe.weakset;if(s instanceof Map){let c=Pe.map;for(let[d,l]of s)c+=Pe.mapEntry,r.push(d),r.push(l);return c}if(s instanceof Set){let c=Pe.set;for(let d of s)c+=Pe.setEntry,r.push(d);return c}if(Array.isArray(s)){let c=Pe.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=Pe.object,u=Object.keys(s);for(let c of u){a+=Pe.string+c.length*2;try{r.push(s[c])}catch{}}return a}function nm(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 mn(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[p,f]of o)i.set(p,f);let a=[];for(let[p,f]of Object.entries(r.nodes)){let m=i.get(p),g=m instanceof Oe?m:null,h=g?Cr(g.cache):0,y=g?g._sinkCount:0,b=f.deps?.length??0,v=f.type==="effect"&&y===0,T=y===0?f.type==="effect"?"orphan-effect":f.type==="derived"?"idle-derived":f.type==="producer"?"idle-producer":null:null;a.push({path:p,type:f.type,status:f.status??"unknown",valueSizeBytes:h,subscriberCount:y,depCount:b,isOrphanEffect:v,orphanKind:T})}let u=a.reduce((p,f)=>p+f.valueSizeBytes,0),c=(p,f)=>[...a].sort(f??((m,g)=>g[p]-m[p])).slice(0,n),d=a.filter(p=>p.orphanKind!=null),l=a.filter(p=>p.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 Ie="::",He="__meta__",lt=1;function Ic(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 rm(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 Dc(t){if(t.version!==lt)throw new Error(`unsupported snapshot version ${String(t.version)} (expected ${lt})`);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 om(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 p=s;if(o.length!==p.length)return!1;for(let f=0;f<o.length;f++)if(!r(o[f],p[f]))return!1;return!0}if(o instanceof Map){let p=s;if(o.size!==p.size)return!1;for(let[f,m]of o)if(!p.has(f)||!r(m,p.get(f)))return!1;return!0}if(o instanceof Set){let p=s;if(o.size!==p.size)return!1;for(let f of o){let m=!1;for(let g of p)if(r(f,g)){m=!0;break}if(!m)return!1}return!0}if(ArrayBuffer.isView(o)){let p=o,f=s;if(p.length!==f.length)return!1;for(let m=0;m<p.length;m++)if(p[m]!==f[m])return!1;return!0}let c=Object.keys(o),d=Object.keys(s);if(c.length!==d.length)return!1;let l=new Set(d);for(let p of c)if(!l.has(p)||!r(o[p],s[p]))return!1;return!0};return r(t,e)}function Qi(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(Qi);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=Qi(e[o]);return r}function sm(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function im(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function am(t){return t==="TD"?"down":t==="BT"?"up":t==="RL"?"left":"right"}function Gc(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 Fc(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 um(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(Qi(i),null,e.indent??2);return e.logger?.(a),a}function cm(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}): ${ts(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 $c(t,e){let n=Fc(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}["${sm(i)}"]`)}for(let[i,a]of Gc(t)){let u=o.get(i),c=o.get(a);!u||!c||s.push(` ${u} --> ${c}`)}return s.join(`
14
+ `)}function dm(t,e){let n=$c(t,e);return ns(n)}function ns(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 lm(t,e){let n=Fc(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: ${am(n)}`];for(let i of r){let a=o.get(i);s.push(`${a}: "${im(i)}"`)}for(let[i,a]of Gc(t)){let u=o.get(i),c=o.get(a);!u||!c||s.push(`${u} -> ${c}`)}return s.join(`
15
+ `)}function pm(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function es(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+=pm(r)}return e+="$",new RegExp(e)}var fm={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"},mm={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function ts(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 hm(t){return t==="none"?mm:t==="ansi"||t==null?fm:{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 Pc(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 gm(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 Yi(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(Ie))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${Ie}' (path separator)`);if(t===He)throw new Error(`Graph "${e}": ${n} name "${He}" is reserved for meta companion paths`);gm(t,e,n)}function ym(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(Ie);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function bm(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 Bc(t){for(let e of t._mounts.values())Bc(e);for(let e of t._nodes.values())try{e.down([[pe]],{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;_destroyed=!1;_topology;_topologyEmitters=new Set;constructor(e,n){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(Ie))throw new Error(`Graph name must not contain '${Ie}' (got "${e}")`);if(e===He)throw new Error(`Graph name "${He}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??De,this._traceRing=new fn(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(Yi(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:j()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof Oe&&n._applyVersioning(e)}remove(e){Yi(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(`${Ie}${He}${Ie}`)||s.nodes.push(a);return s.nodes.sort(),s.mounts.push(e),s.mounts.push(...n._collectSubgraphs(`${e}${Ie}`)),this._mounts.delete(e),n._parent=void 0,Bc(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([[pe]],{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=es(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(Ie))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);Q(()=>{for(let[o,s]of r)this.set(o,s,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[ze]],{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([[C]],{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 Oe)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 Oe)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(Yi(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=ym(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]===He)return this._resolveMetaChainFromNode(s,o,n.join(Ie));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(Ie)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(o.join(Ie))}_resolveMetaChainFromNode(e,n,r){let o=e,s=0,i=[...n];for(;s<i.length;){if(i[s]!==He)throw new Error(`Graph "${this.name}": expected ${He} segment in meta path "${r}"`);if(s+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${He} 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=bm(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 tt)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 tt)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=_t(e?.detail,e?.fields),s=e?.format==="spec",i=s?_t("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 Oe)for(let I of E._deps){let O=I.node;if(u.has(O))continue;let G=O.name??"",A=G;if(!A||x.has(A))if(G){let F=2;for(;x.has(`${G}#${F}`);)F++;A=`${G}#${F}`}else for(A=`__internal__/${R++}`;x.has(A);)A=`__internal__/${R++}`;u.set(O,A),x.add(A),c.push([A,O]),k.push(O)}}}let d=[...a,...c],l={};for(let[k,x]of d){if(n!=null&&!x.allowsObserve(n))continue;let R=Mr(x,i),E=x instanceof Oe?x._deps.map(A=>u.get(A.node)??A.node.name??""):[],{name:I,...O}=R,G={...O,deps:E};if(!s){let A=this._annotations.get(k);A!=null&&(G.annotation=A)}if(r!=null)if(typeof r=="function"){let A=r;if(!(A.length>=2?A(k,G):A(G)))continue}else{let A=!0;for(let[F,q]of Object.entries(r)){let Y=F==="deps_includes"?"depsIncludes":F==="meta_has"?"metaHas":F;if(Y==="depsIncludes"){if(!G.deps.includes(String(q))){A=!1;break}continue}if(Y==="metaHas"){if(!Object.hasOwn(G.meta??{},String(q))){A=!1;break}continue}if(G[Y]!==q){A=!1;break}}if(!A)continue}l[k]=G}let p=new Set(Object.keys(l)),f=[];for(let[k,x]of d)if(x instanceof Oe)for(let R of x._deps){let E=u.get(R.node);E!=null&&f.push([E,k])}f.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=f.map(([k,x])=>({from:k,to:x}));(n!=null||r!=null)&&(m=m.filter(k=>p.has(k.from)&&p.has(k.to)));let g=this._collectSubgraphs(""),h=n!=null||r!=null?g.filter(k=>{let x=`${k}${Ie}`;return[...p].some(R=>R===k||R.startsWith(x))}):g,y=this,b=e,v={name:this.name,nodes:l,edges:m,subgraphs:h,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"?um(v,T):w==="pretty"?cm(v,T):w==="mermaid"?$c(v,T):w==="mermaid-url"?dm(v,T):w==="d2"?lm(v,T):w==="ascii"?Oc(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}${Ie}`))}return n}resourceProfile(e){return mn(this,e)}reachable(e,n,r={}){return r.withDetail===!0?hn(this.describe(),e,n,{...r,withDetail:!0}):hn(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 Or(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,vr(()=>{a=!1,!u&&(o+=1,s.emit(o))}))},d=i.onEvent(h=>{let y=h.type;y!=="data"&&y!=="error"&&y!=="complete"&&y!=="teardown"||c()}),l=[],p=new WeakSet,f=h=>{if(p.has(h)||u)return;p.add(h);let y=h.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=h._mounts.get(T.name);w!=null&&f(w)}}});l.push(y);for(let b of h._mounts.keys()){let v=h._mounts.get(b);v!=null&&f(v)}};f(this);let m;try{m=_([s],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(h,y)=>h===y})}catch(h){d();for(let y of l)y();throw i.dispose(),h}let g=oe(m);return{node:m,dispose(){u=!0,d();for(let h of l)h();l.length=0,i.dispose(),g()}}}_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(f=>{let m=f.type;m!=="data"&&m!=="error"&&m!=="complete"&&m!=="teardown"||a||u||(a=!0,vr(()=>{a=!1,!u&&(o+=1,s.emit(o))}))}),d={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},l;try{l=_([s],()=>this._explainStatic(e,n,d),{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:e,to:n},equals:(f,m)=>f.found===m.found&&f.reason===m.reason&&f.steps.length===m.steps.length&&vm(f.steps,m.steps)})}catch(f){throw c(),i.dispose(),f}let p=oe(l);return{node:l,dispose(){u=!0,c(),i.dispose(),p()}}}_pathsMatching(e){let n=es(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}${Ie}${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}${Ie}${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}${Ie}${He}${Ie}${o}`;r.push([i,s]),this._appendMetaObserveTargets(i,s,r)}}observe(e,n){let r=typeof e=="string",s=Pc(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 tt({actor:a,action:"observe",nodeName:d});return i?this._buildStructuredObserver([[d,l]],s,"one"):{subscribe(p){return l.subscribe(p)},up(p){try{l.up?.(p)}catch(f){if(f instanceof tt)return;throw f}}}}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(([p,f])=>f.subscribe(m=>{d(p,m)}));return()=>{for(let p of l)p()}},up:(d,l)=>{try{this.resolve(d).up?.(l)}catch(p){if(p instanceof tt)return;throw p}}}}_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 fn(d):null,p=[],f=new Set,m={},g=new Set,h=0,y=0,b=0,v=0,T=0,w=0,k=!1,x=!1,R=0,E=new Map,I=new Map,O=new Map,G=$=>{l?l.push($):p.push($);for(let J of f)J($)},A=()=>o?{timestamp_ns:j(),in_batch:tn(),batch_id:R}:{},F=($,J)=>{if(!(!c||!($ instanceof Oe)))return $._setInspectorHook(le=>{if(le.kind==="dep_message")E.set($,le.depIndex);else if(le.kind==="run"){let se=le.batchData.map((re,me)=>re!=null&&re.length>0?re.at(-1):le.prevData[me]);I.set($,se);let Te=le.batchData.map(re=>re!=null?[...re]:void 0);O.set($,Te),i&&G({type:"derived",path:J,dep_values:se,dep_batches:Te,...A()})}})},q=$=>{let J=E.get($),le=I.get($);if(!s||le==null)return{};let Te=(J!=null&&J>=0&&$ instanceof Oe?$._deps[J]:void 0)?.node,re=Te?.v,me=O.get($);return{trigger_dep_index:J,trigger_dep_name:Te?.name,...re!=null?{trigger_version:{id:re.id,version:re.version}}:{},dep_values:[...le],...me!=null?{dep_batches:me}:{}}},Y=[],D=[];for(let[$,J]of e){let le=F(J,$);le&&Y.push(le),D.push(J.subscribe(se=>{R++;for(let Te of se){let re=Te[0],me=A();if(re===S){m[$]=Te[1];let ee=J instanceof Oe?J.lastMutation?.actor??bt:bt;G({type:"data",path:$,data:Te[1],actor:ee,...me,...q(J)})}else if(a)re===te?h++:re===B?y++:re===ze?b++:re===Fe?v++:re===je?T++:re===pe?w++:re===C&&!g.has($)?k=!0:re===M&&(x=!0,g.add($));else if(re===te)h++,G({type:"dirty",path:$,...me});else if(re===B)y++,G({type:"resolved",path:$,...me,...q(J)});else if(re===ze)b++,G({type:"invalidate",path:$,...me});else if(re===Fe)v++,G({type:"pause",path:$,lockId:Te[1],...me});else if(re===je)T++,G({type:"resume",path:$,lockId:Te[1],...me});else if(re===C)g.has($)||(k=!0),G({type:"complete",path:$,...me});else if(re===M){x=!0,g.add($);let ee=J instanceof Oe?J.lastMutation?.actor??bt:bt;G({type:"error",path:$,data:Te[1],actor:ee,...me})}else re===pe&&(w++,G({type:"teardown",path:$,...me}))}}))}let P=!1,L=()=>{if(!P){P=!0;for(let $ of D)$();for(let $ of Y)$();for(let $ of K)$({value:void 0,done:!0});K.length=0}},V=[],K=[];f.add($=>{let J=K.shift();J?J({value:$,done:!1}):V.push($)});let Z={get values(){return m},get dirtyCount(){return h},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():[...p]},get anyCompletedCleanly(){return k},get anyErrored(){return x},get completedWithoutErrors(){return k&&!x},onEvent($){return f.add($),()=>f.delete($)},dispose:L,expand($){L();let J={...n};return typeof $=="string"?J.detail=$:Object.assign(J,$),r(Pc(J))},[Symbol.asyncIterator](){return{next(){return V.length>0?Promise.resolve({value:V.shift(),done:!1}):P?Promise.resolve({value:void 0,done:!0}):new Promise($=>K.push($))},return(){return L(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(Z,n),Z}_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=hm(n.theme),c=r==="stage-log"?j():0,d=m=>m==null?"":n.stageLabels?.[m]??m,l=(m,g)=>m.length>g?`${m.slice(0,g-1)}\u2026`:m,p=m=>m.type==="data"||m.type==="error"?l(ts(m.data),120):"",f=m=>{if(r==="stage-log"){let x=(j()-c)/1e9,R=d(m.path).padEnd(9);if(m.type==="data"){let E=p(m);return`[${x.toFixed(3)}s] ${R} \u2190${E?` ${E}`:""}`}if(m.type==="error"){let E=p(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 g=u[m.type]??"",h=m.path?`${u.path}${m.path}${u.reset} `:"",y=m.type==="data"||m.type==="error",b=m.type==="pause"||m.type==="resume",v=y?` ${ts(m.data)}`:b?` ${ts(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`${h}${g}${m.type.toUpperCase()}${u.reset}${v}${w}${k}`};e.onEvent(m=>{a(m.type)&&o(f(m),m)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){Ic(this._disposers,this.name),this.signal([[pe]],{internal:!0}),Ic(this._storageDisposers,this.name);for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}get destroyed(){return this._destroyed}_destroyClearOnly(){for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}snapshot(e){let{expand:n,...r}=this.describe({detail:"full"}),o={};for(let 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 fr(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??De,{codec:o,codecVersion:s,payload:i}=mr(e,r);return o.decode(i,s)}restore(e,n){if(Dc(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=>es(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){Dc(e);let r=typeof n=="function"?n:n?.build,o=typeof n=="function"?void 0:n?.factories,s=new t(e.name);if(r)return r(s),s.restore(e),s;for(let f of[...e.subgraphs].sort((m,g)=>{let h=m.split(Ie).length,y=g.split(Ie).length;return h!==y?h-y:m<g?-1:m>g?1:0})){let m=f.split(Ie),g=s;for(let h of m)g._mounts.has(h)||g.mount(h,new t(h)),g=g._mounts.get(h)}let i=o?Object.entries(o).map(([f,m])=>({re:es(f),factory:m})):[],a=f=>{for(let m of i)if(m.re.test(f))return m.factory},u=f=>{let m=f.split(Ie),g=m.pop();if(g==null||g.length===0)throw new Error(`invalid snapshot path "${f}"`);let h=s;for(let y of m){let b=h._mounts.get(y);if(!b)throw new Error(`unknown mount "${y}" in path "${f}"`);h=b}return[h,g]},c=Object.entries(e.nodes).filter(([f])=>!f.includes(`${Ie}${He}${Ie}`)).sort((f,m)=>f[0]<m[0]?-1:f[0]>m[0]?1:0),d=new Map(c),l=new Map,p=!0;for(;d.size>0&&p;){p=!1;for(let[f,m]of[...d.entries()]){let g=m?.deps??[];if(!g.every(w=>l.has(w)))continue;let[h,y]=u(f),b={...m?.meta??{}},v=a(f),T;if(m?.type==="state")T=N(m.value,{meta:b});else{if(v==null)continue;T=v(y,{path:f,type:m.type,value:m.value,meta:b,deps:g,resolvedDeps:g.map(w=>l.get(w))})}h.add(T,{name:y}),l.set(f,T),d.delete(f),p=!0}}if(d.size>0){let f=[...d.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${f}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return s.restore(e),s}toJSON(){return this.snapshot()}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=rm(d.nodes);if(c.lastSnapshot!=null&&l!==""&&l===c.lastFingerprint)return;let p=c.seq+1,f=fe(),h=c.lastSnapshot==null||p%c.compactEvery===0?{mode:"full",snapshot:d,seq:p,timestamp_ns:f,format_version:lt}:{mode:"diff",diff:rs(c.lastSnapshot,d),seq:p,timestamp_ns:f,format_version:lt};if(c.tier.filter&&!c.tier.filter(this.name,h))return;let y;try{y=c.tier.save(this.name,h)}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=p,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=p,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 g=this.config.messageTier(m[0]);return g>=3&&g<5}))return;if(n.filter){let m=this.tryResolve(c);if(m==null)return;let g=Mr(m,_t("standard"));if(!n.filter(c,g))return}let p,f=()=>(p==null&&(p=this.snapshot()),p);for(let m of r)m.disposed||(m.debounceMs===0?s(m,f()):(m.timer==null&&(m.timer=new Ce),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 p=this.tryResolve(l);return p==null?()=>{}:p.subscribe(f=>i(l,f))});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===lt&&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===lt&&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:j(),...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],I=T[R];E!==I&&a.push({path:b,field:R,from:E,to:I})}if(!x)for(let R of["value","meta"]){let E=v[R],I=T[R];om(E,I)||a.push({path:b,field:R,from:E,to:I})}}let c=b=>`${b.from} ${b.to}`,d=new Set(e.edges.map(c)),l=new Set(n.edges.map(c)),p=n.edges.filter(b=>!d.has(c(b))),f=e.edges.filter(b=>!l.has(c(b))),m=new Set(e.subgraphs),g=new Set(n.subgraphs),h=[...g].filter(b=>!m.has(b)).sort(),y=[...m].filter(b=>!g.has(b)).sort();return{nodesAdded:s,nodesRemoved:i,nodesChanged:a,versionChanges:u,edgesAdded:p,edgesRemoved:f,subgraphsAdded:h,subgraphsRemoved:y}}};function rs(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 hn(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,p=v=>{if(l){let x=i.get(v)??[],R=u.get(v),E=a.get(v),I=c.get(v),O=[...x];return R&&O.push(...R),E&&O.push(...E),I&&O.push(...I),O}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},f=new Set([e]),m=new Map,g=[{path:e,depth:0}],h=0,y=!1;for(;h<g.length;){let v=g[h++];if(s!=null&&v.depth>=s){p(v.path).length>0&&(y=!0);continue}for(let T of p(v.path))!T||f.has(T)||(f.add(T),m.set(T,v.depth+1),g.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 vm(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 is={};we(is,{CqrsGraph:()=>ss,MemoryEventStore:()=>na,cqrs:()=>ra});Ne();ke();on();var Xi={};we(Xi,{COMPLETE:()=>C,COMPLETE_MSG:()=>To,COMPLETE_ONLY_BATCH:()=>pr,DATA:()=>S,DEFAULT_ACTOR:()=>bt,DIRTY:()=>te,DIRTY_MSG:()=>Rt,DIRTY_ONLY_BATCH:()=>On,ERROR:()=>M,GraphReFlyConfig:()=>nn,GuardDenied:()=>tt,INVALIDATE:()=>ze,INVALIDATE_MSG:()=>vo,INVALIDATE_ONLY_BATCH:()=>lr,NodeImpl:()=>Oe,PAUSE:()=>Fe,RESOLVED:()=>B,RESOLVED_MSG:()=>_n,RESOLVED_ONLY_BATCH:()=>dr,RESUME:()=>je,START:()=>yt,START_MSG:()=>Mn,TEARDOWN:()=>pe,TEARDOWN_MSG:()=>wo,TEARDOWN_ONLY_BATCH:()=>Cn,accessHintForGuard:()=>kr,advanceVersion:()=>xr,autoTrackNode:()=>sn,batch:()=>Q,configure:()=>Ii,createVersioning:()=>Dn,defaultConfig:()=>De,defaultHash:()=>Ft,derived:()=>_,downWithBatch:()=>Nt,dynamicNode:()=>Rr,effect:()=>ce,isBatching:()=>tn,isV1:()=>Ci,monotonicNs:()=>j,node:()=>H,normalizeActor:()=>St,pipe:()=>Di,policy:()=>rn,policyFromRules:()=>wr,producer:()=>W,registerBuiltins:()=>Tr,resolveDescribeFields:()=>_t,state:()=>N,wallClockNs:()=>fe});gr();Ne();ke();Mi();on();ie();Ee();ne();Ro();Ne();ie();ne();var Ar=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 jc(t){return t.subscribe(()=>{})}var Tm=64;function We(t,e={}){let{name:n,maxSize:r,versioning:o,backend:s}=e,i=s??new Ar(t,r),a=N(i.toArray(),{name:n,describeKind:"state",equals:(m,g)=>m===g,...o!=null?{versioning:o}:{}});function u(){let m=i.toArray();Q(()=>{a.down([[te]]),a.down([[S,m]])})}let c=new Map,d=new Map;function l(m,g){return`${m}:${g===void 0?"END":g}`}function p(m){if(m.size<Tm)return;let g=m.keys().next();if(g.done)return;let h=m.get(g.value);h!==void 0&&h.dispose(),m.delete(g.value)}function f(m){let g=i.version;try{return m()}finally{i.version!==g&&u()}}return{entries:a,get size(){return i.size},at(m){return i.at(m)},append(m){f(()=>i.append(m))},appendMany(m){m.length!==0&&f(()=>i.appendMany(m))},clear(){f(()=>i.clear())},trimHead(m){f(()=>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 g=c.get(m);if(g!==void 0)return c.delete(m),c.set(m,g),g.node;p(c);let h=_([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=jc(h);return c.set(m,{node:h,dispose:y}),h},slice(m,g){if(!Number.isInteger(m)||m<0)throw new RangeError(`slice: start must be a non-negative integer (got ${m})`);if(g!==void 0&&(!Number.isInteger(g)||g<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${g})`);let h=l(m,g),y=d.get(h);if(y!==void 0)return d.delete(h),d.set(h,y),y.node;p(d);let b=_([a],([T])=>{let w=T;return g===void 0?w.slice(m):w.slice(m,g)},{initial:i.slice(m,g),describeKind:"derived"}),v=jc(b);return d.set(h,{node:b,dispose:v}),b},disposeTail(m){let g=c.get(m);return g===void 0?!1:(g.dispose(),c.delete(m),!0)},disposeSlice(m,g){let h=l(m,g),y=d.get(h);return y===void 0?!1:(y.dispose(),d.delete(h),!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 ea={};we(ea,{ENVELOPE_VERSION:()=>An,GRAPH_META_SEGMENT:()=>He,Graph:()=>z,JsonCodec:()=>ko,SIZEOF_OVERHEAD:()=>Pe,SIZEOF_SYMBOL:()=>Zo,SNAPSHOT_VERSION:()=>lt,createDagCborCodec:()=>Ni,createDagCborZstdCodec:()=>Ei,decodeEnvelope:()=>mr,diffForWAL:()=>rs,encodeEnvelope:()=>fr,explainPath:()=>Or,graphProfile:()=>mn,mermaidLiveUrl:()=>ns,reachable:()=>hn,registerBuiltinCodecs:()=>hr,replayWAL:()=>_i,sizeof:()=>Cr,validateGraphObservability:()=>Zi,watchTopologyTree:()=>Mt});xo();ie();function Mt(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 z){let p=`${s}${d.name}::`;r(l,p)}}else if(d.kind==="removed"&&d.nodeKind==="mount"){let l=`${s}${d.name}::`;for(let[p,f]of Array.from(n.entries()))p!==t&&f.prefix.startsWith(l)&&(f.off(),n.delete(p))}}});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 Zi(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[p,f]of Object.entries(c.nodes))for(let m of f.deps)m!==""&&!d.has(m)&&l.push(`${p} \u2192 ${m}`);for(let p of c.edges)d.has(p.from)||l.push(`edge.from: ${p.from}`),d.has(p.to)||l.push(`edge.to: ${p.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();Ee();be();function pt(t,e){t!=null&&Nt(n=>t.down(n),[[S,e]],De.tierOf)}function Lr(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[te],[S,n+1]]),!0)}function qe(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}function ta(t){return t.relatedTo?.[0]??t.summary}var wm=rn((t,e)=>{t("write"),t("signal"),e("observe")}),km=rn((t,e)=>{t("observe"),t("signal"),e("write")}),xm=rn((t,e)=>{t("observe"),t("signal"),e("write")});function os(t,e){return qe("cqrs",t,e)}var na=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()}},ss=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=We([],{name:e,versioning:0}),o=r.entries,s=_([o],([i])=>i,{name:e,describeKind:"state",meta:os("event",{event_name:e}),guard:xm,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:fe(),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:{...os("command",{command_name:e}),error:null},guard:wm});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);Q(()=>{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=_(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:os("projection",{projection_name:e,source_events:n}),guard:km,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=H(o,(u,c)=>{let d=i.n.meta.error;for(let l=0;l<u.length;l++){let p=u[l];if(p==null||p.length===0)continue;let f=p.at(-1);if(!f)continue;let m=n[l],g=s.get(m)??0;if(f.length>g){let h=f.slice(g);for(let y of h)try{r(y),d.emit(null,{internal:!0})}catch(b){d.emit(b,{internal:!0})}s.set(m,f.length)}}},{name:e,describeKind:"effect",meta:{...os("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 ra(t,e){return new ss(t,e)}var sa=class{constructor(e){this.graph=e}onModuleDestroy(){this.graph.destroy()}},ia=class{graph=new z("request");onModuleDestroy(){this.graph.destroy()}},Vc,oa;Vc=[(0,Ir.Module)({})];var Wt=class Wt{static forRoot(e){let n=e??{},r=n.name??"root",o=[{provide:st,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 sa(s),inject:[st]},{provide:pn,useFactory:(s,i)=>new pn(s,i),inject:[st,Kc.ModuleRef]}];if(n.nodes)for(let s of n.nodes)o.push({provide:ct(s),useFactory:i=>i.resolve(s),inject:[st]});return n.requestScope&&o.push({provide:Symbol.for("graphrefly:request-lifecycle"),useFactory:()=>new ia,scope:Ir.Scope.REQUEST},{provide:an,useFactory:s=>s.graph,inject:[Symbol.for("graphrefly:request-lifecycle")],scope:Ir.Scope.REQUEST}),{module:Wt,global:!0,providers:o,exports:[st,...(n.nodes??[]).map(ct),...n.requestScope?[an]:[]]}}static forFeature(e){let n=[{provide:nt(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:[st]}];if(e.nodes)for(let r of e.nodes)n.push({provide:ct(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[nt(e.name)]});return{module:Wt,providers:n,exports:[nt(e.name),...(e.nodes??[]).map(r=>ct(`${e.name}::${r}`))]}}static forCqrs(e){let n=[{provide:nt(e.name),useFactory:r=>{let o=ra(e.name,e.cqrs);return e.eventStore&&o.useEventStore(e.eventStore),e.build&&e.build(o),r.mount(e.name,o),o},inject:[st]}];if(e.nodes)for(let r of e.nodes)n.push({provide:ct(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[nt(e.name)]});return{module:Wt,providers:n,exports:[nt(e.name),...(e.nodes??[]).map(r=>ct(`${e.name}::${r}`))]}}};oa=Eu(null),Wt=Ou(oa,0,"GraphReflyModule",Vc,Wt),Mu(oa,1,Wt);var as=Wt;var cs={};we(cs,{useStore:()=>Rm,useSubscribe:()=>Hc,useSubscribeRecord:()=>Sm});var Ot=require("react");ie();function Hc(t){return(0,Ot.useSyncExternalStore)(e=>{let n=!1,r=t.subscribe(()=>{n||e()});return()=>{n=!0,r()}},()=>t.cache,()=>t.cache)}function Rm(t){let e=Hc(t),n=(0,Ot.useCallback)(r=>{t.down([[te],[S,r]])},[t]);return[e,n]}function Sm(t,e){let n=(0,Ot.useRef)(e);n.current=e;let r=(0,Ot.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 p of u)p();u=[]},d=p=>{c();for(let f of p){let m=n.current(f);for(let g of Object.keys(m)){let h=m[g].subscribe(()=>{s=o(),a||i()});u.push(h)}}s=o(),a||i()},l=t.subscribe(p=>{let f=p.some(m=>m[0]===S||m[0]===B);!a&&f&&d(t.cache??[])});return d(t.cache??[]),()=>{a=!0,l(),c()}},getSnapshot:()=>s}},[t]);return(0,Ot.useSyncExternalStore)(r.subscribe,r.getSnapshot,r.getSnapshot)}var ls={};we(ls,{Signal:()=>Nm});Ne();ie();ne();var Qn=[];function ds(t){let e=t.cache;return t.subscribe(r=>{for(let[o,s]of r)o===S&&(e=s)})(),e}var aa=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"&&ds(this._node),e(this._node)):this._node.status==="sentinel"?ds(this._node):this._node.cache}set(e){this._equals(this.get(),e)||Q(()=>{this._node.down([[te],[S,e]])})}},ua=class{_node;constructor(e,n){this._node=sn(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"&&ds(this._node),e(this._node)):this._node.status==="sentinel"?ds(this._node):this._node.cache}},Nm={State:aa,Computed:ua,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===C&&n.complete?.()}})}};var ps={};we(ps,{useStore:()=>Em,useSubscribe:()=>Wc,useSubscribeRecord:()=>_m});var Ct=require("solid-js");ie();function Wc(t){let[e,n]=(0,Ct.createSignal)(t.cache,{equals:!1}),r=t.subscribe(()=>{n(()=>t.cache)});return(0,Ct.getOwner)()?(0,Ct.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 Em(t){return[Wc(t),r=>{t.down([[te],[S,r]])}]}function _m(t,e){let[n,r]=(0,Ct.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),p={};for(let f of Object.keys(l))p[f]=l[f].cache;c[d]=p}return c},a=c=>{s();for(let d of c){let l=e(d);for(let p of Object.keys(l)){let f=l[p].subscribe(()=>{r(()=>i())});o.push(f)}}r(()=>i())},u=t.subscribe(c=>{c.some(d=>d[0]===S||d[0]===B)&&a(t.cache??[])});return a(t.cache??[]),(0,Ct.getOwner)()?(0,Ct.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 fs={};we(fs,{useStore:()=>Om,useSubscribe:()=>Mm,useSubscribeRecord:()=>Cm});ie();function Mm(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n}}}function Om(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n},set(e){t.down([[te],[S,e]])},update(e){let n=e(t.cache);t.down([[te],[S,n]])}}}function Cm(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 p of Object.keys(d))l[p]=d[p].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 p=d[l].subscribe(()=>{n(s())});r.push(p)}}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 ms={};we(ms,{useStore:()=>Lm,useSubscribe:()=>Am,useSubscribeRecord:()=>Im});var $e=require("vue");ie();function Am(t){let e=(0,$e.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,$e.getCurrentScope)()?(0,$e.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,$e.readonly)(e)}function Lm(t){let e=(0,$e.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,$e.getCurrentScope)()?(0,$e.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useStore called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,$e.computed)({get:()=>e.value,set:r=>{t.down([[te],[S,r]])}})}function Im(t,e){let n=(0,$e.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),p={},f=[];for(let m of l){let g=d[m];p[m]=g.cache;let h=g.subscribe(()=>{p[m]=g.cache,o()});f.push(h)}r.set(c,{subs:f,values:p})}let u={};for(let[c,d]of r)u[c]={...d.values};n.value=u}return(0,$e.watch)(()=>[...(typeof t=="function"?t():(0,$e.isRef)(t)?t.value:t)??[]],a=>s(a??[]),{immediate:!0}),(0,$e.getCurrentScope)()?(0,$e.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,$e.readonly)(n)}var hs={};we(hs,{create:()=>Pm});ie();ne();var Dm=()=>!1;function Pm(t){let e=new z("zustand"),n=N(void 0,{name:"state",equals:Dm});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,p]of d)if(l===S){if(u){u=!1;continue}a(p,c),c=p}})},destroy:e.destroy.bind(e)},i=t(o,r,s);return n.emit(i),Object.assign(e,s)}var Ra={};we(Ra,{CircuitOpenError:()=>dt,ContentAddressedMissError:()=>Vr,NS_PER_MS:()=>Ve,NS_PER_SEC:()=>ot,NativeIndexBackend:()=>Wr,NativeListBackend:()=>qr,NativeLogBackend:()=>Ar,NativeMapBackend:()=>Br,NativePubSubBackend:()=>Hr,RateLimiterOverflowError:()=>cn,ResettableTimer:()=>Ce,TimeoutError:()=>dn,audit:()=>fd,awaitSettled:()=>Ho,buffer:()=>md,bufferCount:()=>hd,bufferTime:()=>yd,cached:()=>pc,canonicalJson:()=>Kr,cascadingCache:()=>Sl,catchError:()=>Ed,checkpointToRedis:()=>yl,checkpointToS3:()=>gl,circuitBreaker:()=>Tt,combine:()=>la,combineLatest:()=>Rd,concat:()=>id,concatMap:()=>cd,constant:()=>Io,contentAddressedStorage:()=>ws,createTransport:()=>Ut,createWatermarkController:()=>Jn,csvRows:()=>Xd,debounce:()=>fa,debounceTime:()=>Sd,decorrelatedJitter:()=>Fo,delay:()=>ld,deserializeError:()=>vn,dictStorage:()=>Pl,distill:()=>vs,distinctUntilChanged:()=>rd,elementAt:()=>ed,empty:()=>ac,escapeRegexChar:()=>ji,exhaustMap:()=>ud,exponential:()=>Po,externalBundle:()=>gs,externalProducer:()=>gn,fallback:()=>Un,fibonacci:()=>Go,filter:()=>ft,find:()=>Zc,first:()=>ys,firstValueFrom:()=>Je,firstWhere:()=>Bo,flatMap:()=>dd,forEach:()=>Kt,fromAny:()=>U,fromAsyncIter:()=>Ki,fromCSV:()=>Qd,fromClickHouseWatch:()=>nl,fromCron:()=>jo,fromDrizzle:()=>kl,fromEvent:()=>ic,fromHTTP:()=>ba,fromHTTPPoll:()=>Gd,fromHTTPStream:()=>Pd,fromIter:()=>Vo,fromKafka:()=>Ud,fromKysely:()=>xl,fromMCP:()=>Bd,fromNATS:()=>sl,fromNDJSON:()=>tl,fromOTel:()=>jd,fromPrisma:()=>wl,fromPrometheus:()=>qd,fromPromise:()=>Vi,fromPulsar:()=>rl,fromRabbitMQ:()=>al,fromRaf:()=>sc,fromRedisStream:()=>Jd,fromSSE:()=>Dd,fromSqlite:()=>bl,fromSqliteCursor:()=>vl,fromStatsD:()=>Hd,fromSyslog:()=>Vd,fromTimer:()=>at,fromWebSocket:()=>ya,fromWebSocketReconnect:()=>$d,fromWebhook:()=>_d,globToRegExp:()=>rc,interval:()=>Td,keepalive:()=>oe,last:()=>Xc,linear:()=>Do,lru:()=>wa,makeHttpError:()=>ht,map:()=>Dr,matchesAnyPattern:()=>oc,matchesCron:()=>Lo,memoryStorage:()=>zr,merge:()=>wt,mergeMap:()=>pa,nameToSignal:()=>yn,ndjsonRows:()=>Zd,never:()=>uc,nodeSignal:()=>Wo,of:()=>Hi,onFirstData:()=>Gr,pairwise:()=>od,parseCron:()=>Ao,parsePrometheusText:()=>va,parseSSEStream:()=>Lt,parseStatsD:()=>Wd,parseSyslog:()=>Kd,pausable:()=>kd,pubsub:()=>Ol,race:()=>ad,rateLimiter:()=>qn,reactiveCounter:()=>Wi,reactiveIndex:()=>Ll,reactiveList:()=>ks,reactiveLog:()=>We,reactiveMap:()=>Ye,reactiveSink:()=>Ke,reduce:()=>Jc,repeat:()=>wd,replay:()=>Ko,rescue:()=>Fr,resolveBackoffPreset:()=>$t,retry:()=>Hn,retrySource:()=>Bt,sample:()=>pd,scan:()=>zc,serializeError:()=>bn,share:()=>lc,shareReplay:()=>fc,signalToName:()=>qt,singleFromAny:()=>xs,singleNodeFromAny:()=>Il,skip:()=>da,sortJsonValue:()=>Ur,stableJsonString:()=>Dl,stratify:()=>Jr,switchMap:()=>ve,take:()=>Pr,takeUntil:()=>Qc,takeWhile:()=>Yc,tap:()=>td,tapFirst:()=>nd,throttle:()=>ma,throttleTime:()=>Nd,throwError:()=>cc,timeout:()=>zn,toArray:()=>dc,toCSV:()=>cl,toClickHouse:()=>dl,toFile:()=>Ta,toHTTP:()=>Md,toKafka:()=>zd,toLoki:()=>ml,toMongo:()=>fl,toNATS:()=>il,toObservable:()=>Co,toPostgres:()=>pl,toPulsar:()=>ol,toRabbitMQ:()=>ul,toReadableStream:()=>Id,toRedisStream:()=>Yd,toS3:()=>ll,toSSE:()=>Ad,toSSEBytes:()=>Ld,toSqlite:()=>Tl,toTempo:()=>hl,toWebSocket:()=>Fd,tokenBucket:()=>jt,valve:()=>xd,verifiable:()=>_l,window:()=>vd,windowCount:()=>gd,windowTime:()=>bd,withBreaker:()=>Wn,withLatestFrom:()=>At,withMaxAttempts:()=>$i,withStatus:()=>Vt,workerBridge:()=>ka,workerSelf:()=>xa,zip:()=>sd});Ne();ke();ie();Ee();ne();Ne();ie();ne();function qc(t){return{describeKind:"producer",...t}}function gn(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([[C]]))}},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{}}},qc(e))}function gs(t,e,n){let r=!0,o,s=0,i=0,a={},u=[],c=()=>{let f=o;o=void 0;try{f?.()}catch{}};for(let f of e){let m=n?.name?`${n.name}::${f}`:f,g=n?.channelOpts?.[f],h=W(y=>(s++,()=>{i++,s>0&&i>=s&&i>=e.length&&c()}),qc({...g,name:m}));a[f]=h,u.push(h)}let d={};for(let f of e)d[f]=m=>{r&&a[f].down([[S,m]])};d.error=f=>{r&&(r=!1,Q(()=>{for(let m of u)m.down([[M,f]])}),c())},d.complete=()=>{r&&(r=!1,Q(()=>{for(let f of u)f.down([[C]])}),c())};let l=t(d);return o=typeof l=="function"?l:void 0,Object.assign(a,{dispose:()=>{r&&(r=!1,Q(()=>{for(let f of u)try{f.down([[C]])}catch{}}),c())}})}ke();ie();Ee();ne();be();function de(t){return{describeKind:"derived",...t}}function Uc(t){return{describeKind:"derived",partial:!0,...t}}function Dr(t,e,n){return H([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))},de(n))}function ft(t,e,n){return H([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]])},de(n))}function zc(t,e,n,r){return H([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)},{...de(r),initial:n,resetOnTeardown:!0})}function Jc(t,e,n,r){return H([t],(o,s,i)=>{if("acc"in i.store||(i.store.acc=n),i.terminalDeps[0]===!0){s.emit(i.store.acc),s.down([[C]]);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)},{...de(r),completeWhenDepsComplete:!1})}function Pr(t,e,n){return e<=0?H([t],(r,o,s)=>{s.store.completed||(s.store.completed=!0,o.down([[C]]))},{...de(n),completeWhenDepsComplete:!1}):H([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([[C]]);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([[C]]);return}},{...de(n),completeWhenDepsComplete:!1})}function da(t,e,n){return H([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]])},de(n))}function Yc(t,e,n){return H([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([[C]]);return}o.emit(a)}},{...de(n),completeWhenDepsComplete:!1})}function Qc(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]===C||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([[C]]);return}}});return()=>{u(),c()}},de(s))}function ys(t,e){return Pr(t,1,e)}function Xc(t,e){let{defaultValue:n,...r}=e??{},o=e!=null&&Object.hasOwn(e,"defaultValue");return H([t],(s,i,a)=>{if(a.terminalDeps[0]===!0){a.store.has?i.emit(a.store.latest):o&&i.emit(n),i.down([[C]]);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},{...de(r),completeWhenDepsComplete:!1})}function Zc(t,e,n){return Pr(ft(t,e,n),1,n)}function ed(t,e,n){return Pr(da(t,e,n),1,n)}function td(t,e,n){if(typeof e=="function")return H([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)},de(n));let r=e;return H([t],(o,s,i)=>{if(i.terminalDeps[0]!==void 0){i.terminalDeps[0]===!0?(r.complete?.(),s.down([[C]])):(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)},{...de(n),completeWhenDepsComplete:!1})}function Gr(t,e,n){let r=n?.where??(s=>s!=null),o=!1;return H([t],(s,i)=>{let a=s[0];if(a==null||a.length===0){i.down([[B]]);return}for(let u of a)!o&&r(u)&&(o=!0,e(u)),i.emit(u)},de(n))}var nd=Gr;function rd(t,e=Object.is,n){return H([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]])},de(n))}function od(t,e){return H([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]])},de(e))}function la(...t){let e=[...t];return _(e,n=>n,{...de(),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 At(t,e,n){return H([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]])},Uc(n))}function wt(...t){return t.length===0?W(e=>{e.down([[C]])},de()):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]===C?(r+=1,r>=n&&e.down([[C]])):u[0]===M&&e.down([u])});o.push(i)}return()=>{for(let s of o)s()}},de())}function sd(...t){let e=t.length;return e===0?W(n=>{n.emit([]),n.down([[C]])},de()):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]===C?(o-=1,(o===0||r[u].length===0)&&n.down([[C]])):l[0]===M&&n.down([l])});i.push(c)}return()=>{for(let a of i)a()}},de())}function id(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||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]===C){o=1;for(let d of s)r.emit(d);s.length=0}else c[0]===M&&r.down([c])}),()=>{i?.(),a?.()}},de(n))}function ad(...t){return t.length===0?W(e=>{e.down([[C]])},de()):t.length===1?H([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)},de()):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]===C||u[0]===M)&&(n===null||s===n)&&e.down([u])}});r.push(i)}return()=>{for(let o of r)o()}},de())}function bs(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]!==yt&&(c[0]===S?e.emit(c[1]):c[0]===C?a=!0:c[0]===M?(u=!0,e.down([c])):(c[0]===te||c[0]===B)&&e.down([c]));u?(r?.(),r=void 0,s()):a&&s()}),()=>{r?.(),r=void 0}}function ve(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return H([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([[C]]);return}let c=i[0];if(!(c==null||c.length===0))return s(),r=bs(U(e(c[c.length-1])),a,()=>{s(),o&&a.down([[C]])}),{deactivate:()=>{s(),o=!1}}},{...de(n),completeWhenDepsComplete:!1})}function ud(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return H([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([[C]]);return}let c=i[0];if(!(c==null||c.length===0))return r===void 0?r=bs(U(e(c[0])),a,()=>{s(),o&&a.down([[C]])}):a.down([[B]]),{deactivate:()=>{s(),o=!1}}},{...de(n),completeWhenDepsComplete:!1})}function cd(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([[C]]);return}let p=s.shift();i=bs(U(e(p)),u,()=>{c(),d()})}function l(p){r&&r>0&&s.length>=r&&s.shift(),s.push(p),d()}return H([t],(p,f,m)=>{if(u=f,m.terminalDeps[0]!=null&&m.terminalDeps[0]!==!0){c(),s.length=0;return}if(m.terminalDeps[0]===!0){a=!0,d();return}let g=p[0];if(!(g==null||g.length===0)){for(let h of g)l(h);return{deactivate:()=>{c(),s.length=0,a=!1}}}},{...de(o),completeWhenDepsComplete:!1})}function pa(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([[C]])}function p(h){if(!d)return;i++;let y;y=bs(U(e(h)),d,()=>{y&&u.delete(y),i--,f(),l()}),u.add(y)}function f(){for(;c.length>0&&i<s;)p(c.shift())}function m(h){i<s?p(h):c.push(h)}function g(){for(let h of u)h();u.clear(),i=0,c.length=0}return H([t],(h,y,b)=>{if(d=y,b.terminalDeps[0]!=null&&b.terminalDeps[0]!==!0){g();return}if(b.terminalDeps[0]===!0){a=!0,l();return}let v=h[0];if(!(v==null||v.length===0)){for(let T of v)m(T);return{deactivate:()=>{g(),a=!1}}}},{...de(o),completeWhenDepsComplete:!1})}var dd=pa;function ld(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]===C){let c=setTimeout(()=>{o.delete(c),r.down([[C]])},e);o.add(c)}else u[0]===M&&(s(),r.down([u]))});return()=>{i(),s()}},de(n))}function fa(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]===C?(o!==void 0&&(i(),r.emit(s)),r.down([[C]])):c[0]===M&&(i(),r.down([c]))});return()=>{a(),i()}},de(n))}function ma(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,p,f=!1;function m(){d!==void 0&&(clearTimeout(d),d=void 0)}let g=t.subscribe(h=>{for(let y of h)if(y[0]===S){let b=y[1],v=j();if(i&&v-l>=u)l=v,c.emit(b),m(),a&&(d=setTimeout(()=>{d=void 0,f&&(l=j(),c.emit(p),f=!1)},e));else if(a&&(p=b,f=!0,d===void 0)){let T=(v-l)/1e6;d=setTimeout(()=>{d=void 0,f&&(l=j(),c.emit(p),f=!1)},Math.max(0,e-T))}}else(y[0]===C||y[0]===M)&&(m(),c.down([y]))});return()=>{g(),m()}},de(s))}function pd(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]===C&&(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]===C&&(s=!0,r.down([[C]]))}});return()=>{a(),u()}},de(n))}function fd(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]===C||d[0]===M)&&(a(),r.down([d]))});return()=>{u(),a()}},de(n))}function md(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]===C?(o.length>0&&r.emit([...o]),o.length=0,r.down([[C]])):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]===C?r.down([[C]]):u[0]===M&&r.down([u])});return()=>{s(),i(),o.length=0}},de(n))}function hd(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]===C?(o.length>0&&r.emit([...o]),o.length=0,r.down([[C]])):a[0]===M&&r.down([a])});return()=>{s(),o.length=0}},de(n))}function gd(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}),de());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?.([[C]]),o=void 0)):c[0]===C?(o?.([[C]]),o=void 0,r.down([[C]])):c[0]===M&&(o?.([c]),o=void 0,r.down([c]))});return()=>{a(),o?.([[C]]),o=void 0}},de(n))}function yd(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]===C?(clearInterval(s),o.length>0&&r.emit([...o]),o.length=0,r.down([[C]])):u[0]===M&&(clearInterval(s),r.down([u]))});return()=>{i(),clearInterval(s),o.length=0}},de(n))}function bd(t,e,n){return W(r=>{let o;function s(){o?.([[C]]),o=void 0}function i(){let c=W(d=>(o=d.down.bind(d),()=>{o=void 0}),de());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]===C?(clearInterval(a),s(),r.down([[C]])):d[0]===M&&(clearInterval(a),o?.([d]),s(),r.down([d]))});return()=>{u(),clearInterval(a),s()}},de(n))}function vd(t,e,n){return W(r=>{let o;function s(){o?.([[C]]),o=void 0}function i(){let c=W(d=>(o=d.down.bind(d),()=>{o=void 0}),de());r.emit(c)}let a=t.subscribe(c=>{for(let d of c)d[0]===S?(o||i(),o?.([[S,d[1]]])):d[0]===C?(s(),r.down([[C]])):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()}},de(n))}function Td(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)},de(e))}function wd(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]===C?u=!0:c.push(d);c.length>0&&r.down(c),u&&(s?.(),s=void 0,o-=1,o>0?i():r.down([[C]]))})};return i(),()=>{s?.()}},de(n))}function kd(t,e){return H([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)},de(e))}function Fr(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]===C&&r.down([[C]])});return()=>{o()}},de(n))}function xd(t,e,n){return H([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]])},Uc(n))}var Rd=la,Sd=fa,Nd=ma,Ed=Fr;ie();Ee();ne();Kn();var ha=class{ring;arr;constructor(e){e===Number.POSITIVE_INFINITY||e<=0?(this.arr=[],this.ring=null):(this.ring=new fn(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 $r(t){return t instanceof Error?t:new Error(String(t))}function Gm(t){return t===void 0?null:typeof t=="string"?$t(t):t}function Ke(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:p,sendBatch:f,ctx:m}=e;if(!p&&!f)throw new Error("reactiveSink: `send` or `sendBatch` must be provided");let g=m,h=Math.max(1,o?.maxAttempts??1),y=Gm(o?.backoff??(h>1?"exponential":void 0)),b=o?.shouldRetry??(()=>!0),v=f!==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")}),R=N(null,{name:T("errors")}),E=v?N(0,{name:T("buffered")}):void 0,I=s?N(!1,{name:T("paused")}):void 0,O=0,G=X=>{O+=X,x.down([[S,O]])},A=X=>{try{r?.(X)}catch{}try{R.down([[S,X]])}catch{}},F=new Set,q=X=>{F.add(X);let ye=()=>F.delete(X);X.then(ye,ye)},Y=(X,ye,Se)=>{let Me=y?y(ye-1,Se,null):0,_e=Me==null?0:typeof Me=="number"&&Me>0?Me:0,Xe=Math.max(1,Math.ceil(_e/1e6));return new Promise(he=>{setTimeout(()=>he(X()),Xe)})},D=X=>X!=null&&typeof X=="object"&&typeof X.then=="function",P=X=>{let ye;try{ye=u?u(X):X}catch(he){let ge=$r(he);return A({stage:"serialize",error:ge,value:X}),k.down([[S,{value:X,error:ge,attempts:0}]]),Promise.resolve()}let Se=0,Me=he=>{G(-1);let ge=$r(he);if(A({stage:"send",error:ge,value:X,attempt:Se}),!(Se<h&&b(ge,Se))){k.down([[S,{value:X,error:ge,attempts:Se}]]);return}return Y(Xe,Se,ge)},_e=()=>{G(-1),w.down([[S,X]])};function Xe(){Se+=1,G(1);let he;try{he=p(ye,g)}catch(ge){return Me(ge)??Promise.resolve()}return D(he)?he.then(_e,ge=>Me(ge)):(_e(),Promise.resolve())}return Xe()},L=s?.maxBuffer??Number.POSITIVE_INFINITY,V=new ha(L),K,Z=!1,$=()=>{E?.down([[S,V.length]])},J=X=>{I&&I.down([[S,X]])},le=s?.strategy??"drop-oldest",se=(X,ye)=>{let Se={value:X,payload:ye};if(V.length<L)return V.push(Se),$(),!0;if(le==="drop-oldest"){let _e=V.shift();return V.push(Se),$(),J(!0),k.down([[S,{value:_e.value,error:new Error("backpressure: buffer overflow \u2014 dropped oldest"),attempts:0}]]),!0}if(le==="drop-newest")return J(!0),k.down([[S,{value:X,error:new Error("backpressure: buffer overflow \u2014 dropped newest"),attempts:0}]]),!1;let Me=new Error("backpressure: buffer overflow");return A({stage:"send",error:Me,value:X}),k.down([[S,{value:X,error:Me,attempts:0}]]),J(!0),!1},Te=X=>{let ye=0,Se=X.map(he=>he.payload),Me=he=>{G(-1);let ge=$r(he);if(A({stage:"send",error:ge,value:X.map(ar=>ar.value),attempt:ye}),!(ye<h&&b(ge,ye))){for(let{value:ar}of X)k.down([[S,{value:ar,error:ge,attempts:ye}]]);return}return Y(Xe,ye,ge)},_e=()=>{G(-1);for(let{value:he}of X)w.down([[S,he]])};function Xe(){ye+=1,G(1);let he;try{he=f(Se,g)}catch(ge){return Me(ge)??Promise.resolve()}return D(he)?he.then(_e,ge=>Me(ge)):(_e(),Promise.resolve())}return Xe()},re=async X=>{for(let ye of X)await me(ye.value,ye.payload)},me=(X,ye)=>{let Se=0,Me=he=>{G(-1);let ge=$r(he);if(A({stage:"send",error:ge,value:X,attempt:Se}),!(Se<h&&b(ge,Se))){k.down([[S,{value:X,error:ge,attempts:Se}]]);return}return Y(Xe,Se,ge)},_e=()=>{G(-1),w.down([[S,X]])};function Xe(){Se+=1,G(1);let he;try{he=p(ye,g)}catch(ge){return Me(ge)??Promise.resolve()}return D(he)?he.then(_e,ge=>Me(ge)):(_e(),Promise.resolve())}return Xe()},ee=()=>{if(Z||V.length===0)return Promise.resolve();let X=V.drain();if($(),J(!1),f!==void 0){let Se=Te(X);return q(Se),Se}let ye=re(X);return q(ye),ye},ae=()=>{K!==void 0||Z||a<=0||(K=setTimeout(()=>{K=void 0,ee()},a))},xe=t.subscribe(X=>{for(let ye of X){let Se=ye[0];if(Se!==S)try{d?.(ye)}catch{}if(Se===S){let Me=ye[1];if(v){let _e;if(u)try{_e=u(Me)}catch(he){let ge=$r(he);A({stage:"serialize",error:ge,value:Me}),k.down([[S,{value:Me,error:ge,attempts:0}]]);continue}else _e=Me;if(!se(Me,_e))continue;V.length>=i?ee():ae()}else{let _e=P(Me);q(_e)}}else De.messageTier(Se)>=3&&v&&(K!==void 0&&(clearTimeout(K),K=void 0),ee())}}),Ae;if(c){let X=!1;Ae=c.subscribe(ye=>{if(!X){X=!0;return}ye.length>0&&!Ge&&rt()})}let Ge=!1,rt=()=>{if(Ge)return;Ge=!0,K!==void 0&&(clearTimeout(K),K=void 0),v&&ee(),Z=!0,Ae?.(),xe();let X=ye=>{try{ye.down([[pe]])}catch{}};X(R),X(k),X(w),X(x),E&&X(E),I&&X(I);try{l?.()}catch{}},Be={dispose:rt,sent:w,failed:k,inFlight:x,errors:R};return v&&(Be.buffered=E,Be.flush=async()=>{Z||(await ee(),await Promise.all(F))}),I&&(Be.paused=I),Be}Et();be();function mt(t){return{describeKind:"producer",...t}}function ya(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])},p=()=>{c([C])};if(typeof t=="function"){try{if(a=t(d,l,p),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 f=t,m=y=>d(y,y),g=y=>l(y),h=()=>p();return f.addEventListener("message",m),f.addEventListener("error",g),f.addEventListener("close",h),a=()=>{f.removeEventListener("message",m),f.removeEventListener("error",g),f.removeEventListener("close",h),r&&f.close()},()=>{i=!1,u()}},mt(o))}function _d(t,e){return gn(t,e)}function ba(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`}),p=N(0,{name:`${d.name??"http"}/lastUpdated`}),f=N(!1,{name:`${d.name??"http"}/fetched`}),m=0,g=o!==void 0?typeof o=="string"?o:JSON.stringify(o):void 0,h=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:g,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&&(Q(()=>{m+=1,l.down([[S,m]]),p.down([[S,fe()]]),f.down([[S,!0]]),v.emit(R)}),u&&v.down([[C]]))}).catch(x=>{clearTimeout(k),w&&(x&&x.name==="AbortError"||v.down([[M,x]]))}),()=>{w=!1,T.abort()}},y=W(v=>h({emit:T=>v.emit(T),down:T=>v.down(T)}),{...mt(d),resubscribable:c});return{...Vt(y),fetchCount:l,lastUpdated:p,fetched:f}}function Md(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??{},p=async m=>{let g=i!==void 0?new AbortController:void 0,h;g&&i!==void 0&&(h=setTimeout(()=>g.abort(new Error("Request timeout")),Math.ceil(i/1e6)));try{let y=await fetch(e,{method:r,headers:o,body:m,signal:g?.signal}),b=async()=>{try{await y.arrayBuffer?.()}catch{}};if(!y.ok)throw await b(),new Error(`HTTP ${y.status}: ${y.statusText}`);await b()}finally{h!==void 0&&clearTimeout(h)}};return u!==void 0||c!==void 0?Ke(t,{onTransportError:l,retry:d,batchSize:u,flushIntervalMs:c,sendBatch:async m=>{let g;a==="ndjson"?g=m.map(h=>{let y=s(h);return typeof y=="string"?y:new TextDecoder().decode(y)}).join(`
16
+ `):g=JSON.stringify(m),await p(g)}}):Ke(t,{onTransportError:l,retry:d,serialize:s,send:async m=>{await p(m)}})}function Od(t){return Symbol.keyFor(t)??t.description??"message"}function Xn(t,e){return typeof t=="string"?t:e(t)}function Cd(t,e){let n=`event: ${t}
17
17
  `;if(e!==void 0){let r=e.split(/\r?\n/);for(let o of r)n+=`data: ${o}
18
18
  `}return`${n}
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
20
-
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
22
-
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}
28
- ${h}
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(`
19
+ `}function Ad(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=Od}=e??{},l=new TextEncoder,p;return new ReadableStream({start(f){let m=!1,g,h=()=>{},y=()=>{m||(m=!0,g!==void 0&&clearInterval(g),c?.removeEventListener("abort",v),h(),f.close())};p=y;let b=(T,w)=>{m||f.enqueue(l.encode(Cd(T,w)))},v=()=>{m||y()};h=t.subscribe(T=>{for(let w of T){let k=w[0];if(!(De.isLocalOnly(k)&&!(k===te&&a))){if(k===S){b(r,Xn(w[1],n));continue}if(k===M){b(o,Xn(w[1],n)),y();return}if(k===C){b(s),y();return}!i&&k===B||b(d(k),w.length>1?Xn(w[1],n):void 0)}}}),u!==void 0&&u>0&&(g=setInterval(()=>{m||f.enqueue(l.encode(`: keepalive
20
+
21
+ `))},u)),c?.aborted?v():c?.addEventListener("abort",v,{once:!0})},cancel(){p?.()}})}function Ld(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=Od}=e??{},l=new TextEncoder;return W(p=>{let f=!0,m,g=(b,v)=>{f&&p.emit(l.encode(Cd(b,v)))},h=()=>{f&&(f=!1,p.down([[C]]))},y=t.subscribe(b=>{if(f)for(let v of b){let T=v[0];if(!(De.isLocalOnly(T)&&!(T===te&&a))){if(T===S){g(r,Xn(v[1],n));continue}if(T===M){g(o,Xn(v[1],n)),f=!1,p.down([[C]]);return}if(T===C){g(s),f=!1,p.down([[C]]);return}!i&&T===B||g(d(T),v.length>1?Xn(v[1],n):void 0)}}});return u!==void 0&&u>0&&(m=setInterval(()=>{f&&p.emit(l.encode(`: keepalive
22
+
23
+ `))},u)),c?.aborted?h():c?.addEventListener("abort",h,{once:!0}),()=>{f=!1,m!==void 0&&clearInterval(m),c?.removeEventListener("abort",h),y()}})}function Id(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===C){n=!0;try{r.close()}catch{}return}}})},cancel(){n=!0,e?.()}})}async function*Lt(t,e){let n=e?.parse??(w=>w),r=e?.signal,o=new TextDecoder,s="",i="message",a=[],u,c,d=[],l=()=>{if(a.length===0&&i==="message"&&u===void 0){a=[];return}let w=a.join(`
24
+ `);d.push({event:i,data:n(w),id:u,retry:c}),i="message",a=[],u=void 0,c=void 0},p=w=>{if(w===""){l();return}if(w.startsWith(":"))return;let k=w.indexOf(":"),x=k<0?w:w.slice(0,k),R=k<0?"":w.slice(k+1);switch(R.startsWith(" ")&&(R=R.slice(1)),x){case"event":i=R;break;case"data":a.push(R);break;case"id":R.includes("\0")||(u=R);break;case"retry":{let E=Number(R);Number.isFinite(E)&&(c=E);break}}},f=(w,k)=>{s+=o.decode(w,{stream:!k});let x=s.split(/\r?\n/);s=x.pop()??"";for(let R of x)p(R)},m=t,g=t instanceof ReadableStream?t:m&&typeof m=="object"&&m.body instanceof ReadableStream?m.body:null,h,y,b=!1,v=()=>{b||(b=!0,h&&h.cancel().catch(()=>{}),y&&typeof y.return=="function"&&Promise.resolve(y.return()).catch(()=>{}))},T=()=>{v()};if(r){if(r.aborted)return;r.addEventListener("abort",T,{once:!0})}try{if(g){for(h=g.getReader();!r?.aborted;){let{value:w,done:k}=await h.read();if(k)break;for(f(w,!1);d.length>0;)yield d.shift()}f(new Uint8Array,!0)}else{for(y=t[Symbol.asyncIterator]();!r?.aborted;){let k=await y.next();if(k.done)break;for(f(k.value,!1);d.length>0;)yield d.shift()}f(new Uint8Array,!0)}if(s.trim()){for(let w of s.split(/\r?\n/))p(w);l()}for(;d.length>0;)yield d.shift()}finally{r&&r.removeEventListener("abort",T),v()}}function Dd(t,e){let{parse:n,...r}=e??{};return W(o=>{let s=!0,i=new AbortController;return(async()=>{try{for await(let u of Lt(t,{parse:n,signal:i.signal})){if(!s)return;o.emit(u)}s&&o.down([[C]])}catch(u){s&&o.down([[M,u]])}})(),()=>{s=!1,i.abort()}},mt(r))}function Pd(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 p=await fetch(t,{method:n,headers:r,body:d,signal:c.signal});if(!u)return;if(!p.ok)throw new Error(`HTTP ${p.status}: ${p.statusText}`);if(!p.body)throw new Error("HTTP response has no body");let f=p.body.getReader();for(;u;){let{value:m,done:g}=await f.read();if(g)break;m&&a.emit(m)}u&&a.down([[C]])}catch(p){if(!u||p&&p.name==="AbortError")return;a.down([[M,p]])}})(),()=>{u=!1,c.abort()}},mt(i))}function Gd(t,e){let{intervalMs:n=5e3,...r}=e??{};return ve(at(n,{period:n}),()=>ba(t,{...r,completeAfterFetch:!0}).node)}function Fd(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??{},p=!1,f=y=>{if(!p){p=!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,h=Ke(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]===C&&o||y[0]===M&&s)&&f(y)}});return m=()=>{p=!0,h.dispose()},e.addEventListener("close",m),h}function $d(t,e){let{parse:n,maxRetries:r,backoff:o="exponential",closeOnTeardown:s=!0,...i}=e??{};return Bt(()=>ya(t(),{parse:n,closeOnTeardown:s,...i}),{count:r,backoff:o})}function Bd(t,e){let{method:n="notifications/message",onDisconnect:r,...o}=e??{};return gn(({emit:s,error:i})=>(t.setNotificationHandler(n,a=>s(a)),r?.(a=>i(a??new Error("MCP client disconnected"))),()=>t.setNotificationHandler(n,()=>{})),o)}function jd(t,e){return gs(({traces:r,metrics:o,logs:s,error:i})=>t({onTraces:a=>{Q(()=>{for(let u of a)r(u)})},onMetrics:a=>{Q(()=>{for(let u of a)o(u)})},onLogs:a=>{Q(()=>{for(let u of a)s(u)})},onError:i})??void 0,["traces","metrics","logs"],e?.name?{name:e.name}:void 0)}function Vd(t,e){return gn(t,e)}function Kd(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=fe();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:fe()}}function Hd(t,e){return gn(t,e)}var Fm={c:"counter",g:"gauge",ms:"timer",h:"histogram",s:"set",d:"distribution"};function Wd(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=Fm[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[p,f]=l.split(":");p&&(u[p]=f??"")}}return{name:n.trim(),value:i,type:s,sampleRate:a,tags:u,timestampNs:fe()}}function qd(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 ve(at(0,{period:a,signal:s}),()=>W(c=>{let d=!0,l=new AbortController,p=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(p),!d)return;if(!m.ok)throw new Error(`Prometheus scrape ${m.status}: ${m.statusText}`);let g=await m.text();if(!d)return;let h=va(g);for(let y of h)c.emit(y);u=0,c.down([[C]])}catch(m){if(clearTimeout(p),!d||m instanceof Error&&m.name==="AbortError")return;u+=1,u>=i&&c.down([[M,m]])}})(),()=>{d=!1,clearTimeout(p),l.abort()}}))}function va(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 p=s.slice(7),f=p.indexOf(" ");f>0&&n.set(p.slice(0,f),p.slice(f+1).trim());continue}if(s.startsWith("# HELP ")){let p=s.slice(7),f=p.indexOf(" ");f>0&&r.set(p.slice(0,f),p.slice(f+1).trim());continue}if(s.startsWith("#"))continue;let i,a={},u,c,d=s.indexOf("{");if(d>=0){i=s.slice(0,d);let p=s.indexOf("}",d);if(p<0)continue;let f=s.slice(d+1,p);a=$m(f);let m=s.slice(p+1).trim().split(/\s+/);u=m[0]??"",c=m[1]}else{let p=s.split(/\s+/);i=p[0]??"",u=p[1]??"",c=p[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:fe()})}return e}function $m(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 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 p={};if(l.headers)for(let[f,m]of Object.entries(l.headers))m!==void 0&&(p[f]=typeof m=="string"?m:m.toString());i.emit({topic:c,partition:d,key:l.key?.toString()??null,value:o(l.value),headers:p,offset:l.offset,timestamp:l.timestamp,timestampNs:fe()})}})}catch(c){a&&i.down([[M,c]])}})(),()=>{a=!1}},mt(s))}function zd(t,e,n,r){let{serialize:o=a=>JSON.stringify(a),keyExtractor:s,onTransportError:i}=r??{};return Ke(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 Jd(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[p,f]of l)for(let[m,g]of f)c=m,a.emit({id:m,key:e,data:s(g),timestampNs:fe()})}catch(l){if(!u)return;a.down([[M,l]]);return}})(),()=>{u=!1}},mt(i))}function Yd(t,e,n,r){let{serialize:o=a=>["data",JSON.stringify(a)],maxLen:s,onTransportError:i}=r??{};return Ke(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 Qd(t,e){let{delimiter:n=",",hasHeader:r=!0,columns:o,parseLine:s,...i}=e??{},a=s??(u=>el(u,n));return W(u=>{let c=!1;return(async()=>{try{let l=o,p="";for await(let f of t){if(c)return;p+=f;let m=p.split(/\r?\n/);p=m.pop()??"";for(let g of m){if(c)return;if(!g.trim())continue;let h=a(g);if(!l&&r){l=h;continue}l||(l=h.map((b,v)=>`col${v}`));let y={};for(let b=0;b<l.length;b++)y[l[b]]=h[b]??"";u.emit(y)}}if(!c&&p.trim()){let f=a(p);if(l){let m={};for(let g=0;g<l.length;g++)m[l[g]]=f[g]??"";u.emit(m)}}c||u.down([[C]])}catch(l){c||u.down([[M,l]])}})(),()=>{c=!0}},mt(i))}function Xd(t,e){let{delimiter:n=",",hasHeader:r=!0,columns:o,parseLine:s,...i}=e??{},a=s??(u=>el(u,n));return H([t],(u,c,d)=>{let l=u[0];if(l==null||l.length===0)return;let p=d.store;typeof p.buffer!="string"&&(p.buffer=""),p.headers===void 0&&o&&(p.headers=o.slice());for(let f of l){p.buffer=p.buffer+f;let m=p.buffer.split(/\r?\n/);p.buffer=m.pop()??"";for(let g of m){if(!g.trim())continue;let h=a(g);if(!p.headers&&r){p.headers=h;continue}p.headers||(p.headers=h.map((b,v)=>`col${v}`));let y={};for(let b=0;b<p.headers.length;b++)y[p.headers[b]]=h[b]??"";c.emit(y)}}},{describeKind:"derived",...i})}function Zd(t,e){return H([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 el(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 tl(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([[C]])}catch(s){r||n.down([[M,s]])}})(),()=>{r=!0}},mt(e))}function nl(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 ve(at(0,{period:a,signal:s}),()=>W(c=>{let d=!0;return(async()=>{try{let p=await t.query({query:e,format:o});if(!d)return;let f=await p.json();if(!d)return;for(let m of f)c.emit(m);u=0,c.down([[C]])}catch(p){if(!d)return;u+=1,u>=i&&c.down([[M,p]])}})(),()=>{d=!1}}))}function rl(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:fe()};if(n)a.emit(l),t.acknowledge(d).catch(i);else{let p=!1,f={value:l,ack(){p||(p=!0,t.acknowledge(d).catch(i))},nack(m){if(p)return;p=!0;let g=t;try{let h=g.negativeAcknowledge?.(d);h&&typeof h.then=="function"&&h.catch(i)}catch(h){i(h)}}};a.emit(f)}}catch(d){u&&a.down([[M,d]]);return}})(),()=>{u=!1}},mt(s))}function ol(t,e,n){let{serialize:r=a=>Buffer.from(JSON.stringify(a)),keyExtractor:o,propertiesExtractor:s,onTransportError:i}=n??{};return Ke(t,{onTransportError:i,send:async a=>{await e.send({data:r(a),partitionKey:o?.(a),properties:s?.(a)})}})}function sl(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 p={};if(l.headers)for(let f of l.headers.keys())p[f]=l.headers.get(f);a.emit({subject:l.subject,data:s(l.data),headers:p,reply:l.reply,sid:l.sid,timestampNs:fe()})}u&&a.down([[C]])}catch(l){u&&a.down([[M,l]])}})(),()=>{u=!1}},mt(i))}function il(t,e,n,r){let o=new TextEncoder,{serialize:s=a=>o.encode(JSON.stringify(a)),onTransportError:i}=r??{};return Ke(t,{onTransportError:i,send:a=>{e.publish(n,s(a))}})}function al(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,f=>{if(!c)return;if(f===null){c&&u.down([[M,new Error("Consumer cancelled by broker")]]);return}let m={queue:e,routingKey:f.fields.routingKey,exchange:f.fields.exchange,content:o(f.content),properties:f.properties,deliveryTag:f.fields.deliveryTag,redelivered:f.fields.redelivered,timestampNs:fe()};if(r){u.emit(m);try{t.ack(f)}catch(g){a(g)}}else{let g=!1,h=t,y={value:m,ack(){if(!g){g=!0;try{t.ack(f)}catch(b){a(b)}}},nack(b){if(g)return;g=!0;let v=b?.requeue;if(!h.nack){a(new Error("RabbitMQ channel does not expose `nack`; cannot negative-ack"));return}try{h.nack(f,!1,v)}catch(T){a(T)}}};u.emit(y)}},{noAck:!1})).consumerTag}catch(p){c&&u.down([[M,p]])}})(),()=>{c=!1,d!==void 0&&t.cancel(d)}},mt(i))}function ul(t,e,n,r){let{serialize:o=a=>Buffer.from(JSON.stringify(a)),routingKeyExtractor:s=()=>"",onTransportError:i}=r??{};return Ke(t,{onTransportError:i,send:a=>{let u=s(a),c=o(a);e.publish(n,u,c)}})}function Ta(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?Ke(t,{onTransportError:i,batchSize:s,flushIntervalMs:o,serialize:r,sendBatch:l=>{e.write(l.join(""))}}):Ke(t,{onTransportError:i,serialize:r,send:l=>{e.write(l)}}),d=c.dispose;return c.dispose=()=>{d();try{e.end()}catch{}},c}function ga(t,e){return t.includes(e)||t.includes('"')||t.includes(`
27
+ `)?`"${t.replace(/"/g,'""')}"`:t}function cl(t,e,n){let{columns:r,delimiter:o=",",writeHeader:s=!0,cellExtractor:i=(f,m)=>String(f[m]??""),flushIntervalMs:a=0,batchSize:u=Number.POSITIVE_INFINITY,onTransportError:c,...d}=n,l=!1;return Ta(t,e,{serialize:f=>{if(!l&&s){l=!0;let m=r.map(h=>ga(h,o)).join(o),g=r.map(h=>ga(i(f,h),o)).join(o);return`${m}
28
+ ${g}
29
+ `}return`${r.map(m=>ga(i(f,m),o)).join(o)}
30
+ `},flushIntervalMs:a,batchSize:u,onTransportError:c,...d})}function dl(t,e,n,r){let{batchSize:o=1e3,flushIntervalMs:s=5e3,format:i="JSONEachRow",transform:a=c=>c,onTransportError:u}=r??{};return Ke(t,{onTransportError:u,batchSize:o,flushIntervalMs:s,serialize:a,sendBatch:async c=>{await e.insert({table:n,values:c,format:i})}})}function ll(t,e,n,r){let{format:o="ndjson",keyGenerator:s=(p,f)=>{let m=Math.floor(f/1e6);return`data/${new Date(m).toISOString().replace(/[:.]/g,"-")}-${p}.${o==="ndjson"?"ndjson":"json"}`},batchSize:i=1e3,flushIntervalMs:a=1e4,transform:u=p=>p,onTransportError:c}=r??{},d=o==="ndjson"?"application/x-ndjson":"application/json",l=0;return Ke(t,{onTransportError:c,batchSize:i,flushIntervalMs:a,serialize:u,sendBatch:async p=>{l+=1;let f=o==="ndjson"?`${p.map(g=>JSON.stringify(g)).join(`
31
31
  `)}
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
+ `:JSON.stringify(p),m=s(l,fe());await e.putObject({Bucket:n,Key:m,Body:f,ContentType:d})}})}function pl(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 Ke(t,{onTransportError:s,serialize:i=>o(i,n),send:async i=>{let a=i;await e.query(a.sql,a.params)}})}function fl(t,e,n){let{toDocument:r=s=>s,onTransportError:o}=n??{};return Ke(t,{onTransportError:o,serialize:r,send:async s=>{await e.insertOne(s)}})}function ml(t,e,n){let{labels:r={},toLine:o=a=>JSON.stringify(a),toLabels:s,onTransportError:i}=n??{};return Ke(t,{onTransportError:i,serialize:a=>({line:o(a),labels:s?{...r,...s(a)}:r}),send:async a=>{let{line:u,labels:c}=a,d=`${fe()}`;await e.push({streams:[{stream:c,values:[[d,u]]}]})}})}function hl(t,e,n){let{toResourceSpans:r=s=>[s],onTransportError:o}=n??{};return Ke(t,{onTransportError:o,serialize:r,send:async s=>{await e.push({resourceSpans:s})}})}function gl(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(fe()/1e6),p=`${o}${t.name}/checkpoint-${l}.json`,f;try{f=JSON.stringify(d)}catch(m){a?.(m);return}e.putObject({Bucket:n,Key:p,Body:f,ContentType:"application/json"}).catch(m=>a?.(m))},load(){return null}};return t.attachStorage([u],{onError:c=>a?.(c)})}function yl(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(p){i?.(p);return}e.set(a,l).catch(p=>i?.(p))},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 bl(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([[C]])}catch(a){i.down([[M,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...s})}function vl(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return W(i=>{try{let a=t.iterate(e,o);Q(()=>{for(let u of a)i.emit(r(u));i.down([[C]])})}catch(a){i.down([[M,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...s})}function Tl(t,e,n,r){if(n.includes("\0")||n.length===0)throw new Error(`toSqlite: invalid table name: ${JSON.stringify(n)}`);let{toSQL:o=(A,F)=>({sql:`INSERT INTO "${F.replace(/"/g,'""')}" (data) VALUES (?)`,params:[JSON.stringify(A)]}),onTransportError:s,batchInsert:i=!1,maxBatchSize:a=1e3,flushIntervalMs:u=0}=r??{},c=A=>o(A,n);if(!i)return Ke(t,{onTransportError:s,serialize:c,send:A=>{let F=A;e.query(F.sql,F.params)}});let d=N(null),l=N(void 0,{equals:()=>!1}),p=N(null),f=N(0),m=N(0),g=A=>{try{s?.(A)}catch{}try{d.down([[S,A]])}catch{}},h=[],y=!1,b,v=!1,T=()=>m.down([[S,h.length]]),w=A=>{v||l.down([[S,A]])},k=A=>{v||p.down([[S,A]])},x=A=>{v||f.down([[S,A]])},R=A=>{v||g(A)},E=()=>{if(h.length===0||y)return;y=!0,x(1);try{e.query("BEGIN",[])}catch(Y){y=!1,x(0),R({stage:"send",error:Y instanceof Error?Y:new Error(String(Y)),value:void 0});return}let A=h;h=[],T();let F,q=0;for(let Y of A)try{e.query(Y.query.sql,Y.query.params),q+=1}catch(D){F=D instanceof Error?D:new Error(String(D));break}if(F){try{e.query("ROLLBACK",[])}catch{}R({stage:"send",error:F,value:void 0});for(let Y of A)k({value:Y.value,error:F,attempts:1})}else try{e.query("COMMIT",[]);for(let Y of A)w(Y.value)}catch(Y){let D=Y instanceof Error?Y:new Error(String(Y));R({stage:"send",error:D,value:void 0});for(let P=0;P<q;P++)k({value:A[P].value,error:D,attempts:1})}y=!1,x(0)},I=()=>{u>0&&b===void 0&&!v&&(b=setTimeout(()=>{b=void 0,E()},u))},O=t.subscribe(A=>{for(let F of A){let q=F[0];if(q===S){let Y=F[1],D;try{D=c(Y)}catch(P){let L=P instanceof Error?P:new Error(String(P));g({stage:"serialize",error:L,value:Y}),p.down([[S,{value:Y,error:L,attempts:0}]]);continue}h.push({value:Y,query:D}),T(),h.length>=a?E():I()}else De.messageTier(q)>=3&&E()}});return{dispose:()=>{if(!v){b!==void 0&&(clearTimeout(b),b=void 0),E(),v=!0,O();for(let A of[d,l,p,f,m])try{A.down([[pe]])}catch{}}},sent:l,failed:p,inFlight:f,errors:d,buffered:m,flush:async()=>{v||E()}}}function wl(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([[C]]))}).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 kl(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([[C]]))}).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 xl(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([[C]]))}).catch(i=>{if(s)try{o.down([[M,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{s=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}Kn();ie();ne();function wa(){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 Rl(t){return t!=null&&typeof t.then=="function"}function Zn(t){Rl(t)&&t.catch(()=>{})}function Sl(t,e){let n=new Map,r=e?.maxSize??0,o=r>0?e?.eviction??wa():null,s=e?.writeThrough??!1;function i(c,d,l){for(let p=0;p<l;p++)try{Zn(t[p].save(c,d))}catch{}}function a(c,d,l=0){for(let p=l;p<t.length;p++){let f;try{f=t[p].load(c)}catch{continue}if(Rl(f)){let m=p;f.then(g=>{g!=null?(d.down([[S,g]]),i(c,g,m)):a(c,d,m+1)},()=>{a(c,d,m+1)});return}if(f!=null){d.down([[S,f]]),i(c,f,p);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 p=l.cache;if(l.status!=="sentinel"&&t.length>0){let f=t.length-1;try{Zn(t[f].save(d,p))}catch{}for(let m=0;m<f;m++)try{let g=t[m].clear;g&&Zn(g.call(t[m],d))}catch{}}l.down([[pe]])}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 p of t)try{Zn(p.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 p=N(d);n.set(c,p),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([[pe]]),n.delete(c);for(let l of t)try{let p=l.clear;p&&Zn(p.call(l,c))}catch{}},has(c){return n.has(c)},get size(){return n.size}}}Ne();ie();ne();Ne();ke();ie();ne();var Br=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=j(),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=j(),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 j()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??j())>=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 Ye(t={}){let{name:e,maxSize:n,defaultTtl:r,versioning:o,backend:s,retention:i}=t;if(i&&n!==void 0)throw new RangeError("reactiveMap: `maxSize` (LRU) and `retention` (score-based) are mutually exclusive. Pick one eviction policy.");if(i&&i.archiveThreshold===void 0&&i.maxSize===void 0)throw new RangeError("reactiveMap: `retention` requires at least one of `archiveThreshold` or `maxSize` to trigger archival.");let a=s??new Br({maxSize:n,defaultTtl:r}),u=N(a.toMap(),{name:e,describeKind:"state",equals:(p,f)=>p===f,...o!=null?{versioning:o}:{}});function c(){let p=a.toMap();Q(()=>{u.down([[te]]),u.down([[S,p]])})}function d(){if(!i)return;let p=a.toMap(),f=i.archiveThreshold,m=i.maxSize,g=[];for(let[y,b]of p)g.push({key:y,value:b,score:i.score(y,b)});g.sort((y,b)=>y.score-b.score);let h=new Set;if(f!==void 0)for(let y of g)if(y.score<f)h.add(y.key);else break;if(m!==void 0&&g.length-h.size>m)for(let y of g){if(g.length-h.size<=m)break;h.has(y.key)||h.add(y.key)}if(h.size!==0)for(let y of g)h.has(y.key)&&(i.onArchive?.(y.key,y.value,y.score),a.delete(y.key))}function l(p,f="mutation"){let m=a.version;try{return p()}finally{a.version!==m&&(f==="mutation"&&d(),c())}}return{entries:u,has(p){return l(()=>a.has(p),"read")},get(p){return l(()=>a.get(p),"read")},set(p,f,m){l(()=>a.set(p,f,m?.ttl))},setMany(p,f){l(()=>a.setMany(p,f?.ttl))},delete(p){l(()=>a.delete(p))},deleteMany(p){l(()=>a.deleteMany(p))},clear(){l(()=>a.clear())},pruneExpired(){l(()=>a.pruneExpired())},get size(){return a.size},dispose(){}}}be();function Bm(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function _l(t,e,n){let r=U(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=wt(U(n.trigger),r):i?a=U(n.trigger):n?.autoVerify&&(a=r),a!==null){let u;if(a===r)u=ve(r,c=>e(c));else{let c=r.cache;r.subscribe(d=>{for(let l of d)l[0]===S&&(c=l[1])}),u=ve(a,()=>e(c))}Kt(u,c=>{Q(()=>{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 Nl(t){t.subscribe(()=>{})}function jr(t){return t instanceof Map?t:new Map}function El(t,e){if(!Array.isArray(e.upsert))throw new TypeError("distill extraction requires upsert: Array<{ key, value }>");Q(()=>{for(let{key:n,value:r}of e.upsert)t.set(n,r);for(let n of e.remove??[])t.delete(n)})}function vs(t,e,n){let r=U(t),o=Ye(n.mapOptions??{}),s=n.budget??2e3,a=n.context!==void 0&&n.context!==null?U(n.context):N(null),u=jr(o.entries.cache);o.entries.subscribe(f=>{for(let m of f)m[0]===S&&(u=jr(m[1]))});let c=ve(r,f=>e(f,u));if(Kt(c,f=>{El(o,f)}),n.evict){let f=new Map,m=_([o.entries],([g])=>{let h=[],y=jr(g);for(let b of f.keys())y.has(b)||(f.get(b)(),f.delete(b));for(let[b,v]of y){let T=n.evict(b,v);if(Bm(T)){if(!f.has(b)){let w=Kt(T,k=>{k===!0&&o.has(b)&&o.delete(b)});f.set(b,w)}continue}if(typeof T=="boolean"){T&&h.push(b);continue}throw new TypeError("distill evict() must return boolean or Node<boolean>")}return h});Kt(m,g=>{for(let h of g)o.delete(h)})}let d=n.consolidateTrigger!==void 0&&n.consolidateTrigger!==null;if(n.consolidate&&d){let f=U(n.consolidateTrigger),m=ve(f,()=>n.consolidate(u));Kt(m,g=>{El(o,g)})}let l=_([o.entries,a],([f,m])=>{let g=[...jr(f).entries()].map(([b,v])=>({key:b,value:v,score:n.score(v,m),cost:n.cost(v)}));g.sort((b,v)=>v.score-b.score);let h=[],y=s;for(let b of g)b.cost<=y&&(h.push({key:b.key,value:b.value,score:b.score}),y-=b.cost);return h}),p=_([o.entries],([f])=>jr(f).size);return Nl(l),Nl(p),{store:o,compact:l,size:p}}async function Ts(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+=Ml[r[s]];return o}var Ml=new Array(256);for(let t=0;t<256;t++)Ml[t]=t.toString(16).padStart(2,"0");var Vr=class extends Error{constructor(n,r){super(`content-addressed lookup miss in read-strict mode: ${n}`);this.key=n;this.context=r;this.name="ContentAddressedMissError"}};function Kr(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))}function ws(t){let{storage:e,keyContext:n,keyPrefix:r,mode:o="read-write"}=t,s=n??(a=>a);async function i(a){let u=Kr(s(a)),c=await Ts(u);return r?`${r}:${c}`:c}return{keyFor:i,async lookup(a){if(o==="write")return;let u=await i(a),c=await e.load(u);if(c==null){if(o==="read-strict")throw new Vr(u,a);return}return c},async store(a,u){if(o==="read")return;let c=await i(a);await e.save(c,u)},async forget(a){if(o==="read"||o==="write"||!e.clear)return;let u=await i(a);await e.clear(u)}}}Fi();async function ht(t,e){let n;try{n=await t.text()}catch{n=""}let r=e??"HTTP",o=new Error(`${r} API ${t.status}: ${t.statusText}${n?` \u2014 ${n}`:""}`);return o.status=t.status,o.headers=t.headers,o}Ne();ie();Ee();var Hr=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 Ol(t={}){let{backend:e}=t,n=e??new Hr,r=new Map;function o(s){let i=r.get(s);return i===void 0&&(i=H({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){Q(()=>{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([[pe]]),!0)},has(s){return n.hasTopic(s)},get size(){return n.topicCount},topicNames(){return n.topicNames()}}}Ne();ie();ne();function Cl(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 jm(t,e){let n=Cl(t[0],e[0]);return n!==0?n:Cl(t[1],e[1])}function Al(t){return[t.secondary,t.primary]}function er(t,e){let n=Al(e),r=0,o=t.length;for(;r<o;){let s=r+o>>1;jm(n,Al(t[s]))>0?r=s+1:o=s}return r}var Wr=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=er(this._buf,s);this._buf.splice(u,1)}let a=er(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=er(this._buf,s);this._buf.splice(u,1)}let a=er(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=er(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=er(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 Vm(t){return t.subscribe(()=>{})}function Ll(t={}){let{name:e,versioning:n,equals:r,backend:o}=t,s=o??new Wr;function i(f){return f?.equals!==void 0||r===void 0?f:{...f,equals:r}}let a=N([],{name:e,describeKind:"state",equals:(f,m)=>f===m,...n!=null?{versioning:n}:{}}),u=_([a],([f])=>{let m=f,g=new Map;for(let h of m)g.set(h.primary,h.value);return g},{initial:s.toPrimaryMap(),describeKind:"derived"}),c=Vm(u),d=!1;function l(){let f=s.toArray();Q(()=>{a.down([[te]]),a.down([[S,f]])})}function p(f){let m=s.version;try{return f()}finally{s.version!==m&&l()}}return{ordered:a,byPrimary:u,has(f){return s.has(f)},get(f){return s.get(f)},get size(){return s.size},upsert(f,m,g,h){return p(()=>s.upsert(f,m,g,i(h)))},upsertMany(f,m){let g=[...f];g.length!==0&&p(()=>s.upsertMany(g,i(m)))},delete(f){p(()=>s.delete(f))},deleteMany(f){let m=[...f];m.length!==0&&p(()=>s.deleteMany(m))},clear(){p(()=>s.clear())},dispose(){d||(d=!0,c())}}}Ne();ie();ne();var qr=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 ks(t,e={}){let{name:n,versioning:r,backend:o}=e,s=o??new qr(t),i=N(s.toArray(),{name:n,describeKind:"state",equals:(c,d)=>c===d,...r!=null?{versioning:r}:{}});function a(){let c=s.toArray();Q(()=>{i.down([[te]]),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(){}}}Et();ie();be();function xs(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=Je(a):a!=null&&typeof a=="object"&&Symbol.asyncIterator in a?u=(async()=>{let l=a[Symbol.asyncIterator]();try{let{value:p,done:f}=await l.next();if(f)throw new Error("singleFromAny: factory returned empty async iterable");return p}finally{await l.return?.()}})():a!=null&&typeof a=="object"&&Symbol.iterator in a?u=(async()=>{let l=a[Symbol.iterator]();try{let{value:p,done:f}=l.next();if(f)throw new Error("singleFromAny: factory returned empty iterable");return p}finally{l.return?.()}})():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 Il(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=U(t(o));r.set(s,a);let u=a.subscribe(c=>{for(let d of c)if(d[0]===M||d[0]===C){r.get(s)===a&&r.delete(s),u();return}});return a}}be();function Ur(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(Ur);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=Ur(e[o]);return r}function Dl(t){return JSON.stringify(Ur(t),void 0,0)}function zr(){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 Pl(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();Ee();ne();function Jr(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)Km(o,e,s,i);return o}function Km(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 p(g){if(u){u=!1;let h=c;if(c=s,h!==s){let y=l.find(v=>v.name===r.name),b=!1;try{b=y?.classify(h)??!1}catch{b=!1}b?(d=!1,g.emit(h)):d&&(d=!1,g.down([[te],[B]]))}else d?(d=!1,g.down([[te],[B]])):g.down([[B]])}}let f=H([],(g,h)=>{let y=e.subscribe(v=>{for(let T of v)m(T,0,h)}),b=n.subscribe(v=>{for(let T of v)m(T,1,h)});return()=>{y(),b()}},{describeKind:"derived",meta:{kind:"stratify_branch",branch:r.name},completeWhenDepsComplete:!1});function m(g,h,y){let b=g[0];return b===te?(h===0?(i=!0,d=!0):a=!0,!0):b===S||b===B?(h===0?(i=!1,u=!0,c=b===S?g[1]:s):(b===S&&(l=g[1]),a=!1),i||a||p(y),!0):b===C||b===M||b===pe?(i=!1,a=!1,u=!1,c=s,d=!1,h===0&&y.down([g]),!0):h===1}if(t.add(f,{name:o}),r.ops){let g=r.ops(f),h=`branch/${r.name}/out`;t.add(g,{name:h})}}vt();Ne();ie();Ee();ne();be();ie();var Hm=new Map([[ze,"INVALIDATE"],[Fe,"PAUSE"],[je,"RESUME"],[pe,"TEARDOWN"],[C,"COMPLETE"],[M,"ERROR"]]),Wm=new Map([["INVALIDATE",ze],["PAUSE",Fe],["RESUME",je],["TEARDOWN",pe],["COMPLETE",C],["ERROR",M]]);function qt(t){let e=Hm.get(t);return e||(Symbol.keyFor(t)??"UNKNOWN")}function yn(t){let e=Wm.get(t);if(e)return e;if(t&&t!=="UNKNOWN")return Symbol.for(t)}function bn(t){return t instanceof Error?{message:t.message,name:t.name,stack:t.stack}:{message:String(t),name:"Error"}}function vn(t){let e=new Error(t.message);return e.name=t.name,t.stack&&(e.stack=t.stack),e}function Ut(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 Ut(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 qm(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function ka(t,e){let n=qm(t)?t:Ut(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=H(b,(w,k)=>{let x={};for(let R=0;R<o.length;R++){let[E]=o[R],I=w[R];I!=null&&I.length>0&&(x[E]=I.at(-1))}Object.keys(x).length!==0&&k.emit(x)},{name:`${r}::aggregated`,partial:!0});l=ce([v],w=>{let k=w[0];if(k==null||Object.keys(k).length===0)return;let x=[];for(let I of Object.keys(k)){let O=i[I];O&&x.push(...O(k[I]))}let R;for(let[I,O]of o)I in k&&O.v!=null&&(R==null&&(R={}),R[I]=O.v.version);let E={t:"b",u:k,...R?{v:R}:{}};try{n.post(E,x.length>0?x:void 0)}catch(I){u.down([[S,I instanceof Error?I:new Error(String(I))]])}}).subscribe(()=>{})}let p=!1,f=n.listen(b=>{if(p)return;let v=b;switch(v.t){case"r":{Q(()=>{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":{Q(()=>{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,vn(v.err)]]);break}case"s":{let T=yn(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(!p)for(let k of w){let x=k[0];x!==S&&(De.isLocalOnly(x)||(x===M?n.post({t:"e",s:b,err:bn(k[1])}):n.post({t:"s",s:b,sig:qt(x),d:k.length>1?k[1]:void 0})))}}));m.push(T)}let g;if(e.timeoutMs!=null&&e.timeoutMs>0){let b=at(e.timeoutMs),v=ft(a,w=>w==="connected");g=ys(wt(Dr(b,()=>"timeout"),Dr(v,()=>"ready"))).subscribe(w=>{for(let k of w)k[0]===S&&k[1]==="timeout"&&(u.down([[S,new Error("Worker bridge handshake timeout")]]),h())})}function h(){if(!p){p=!0,g?.(),n.post({t:"s",s:"*",sig:qt(pe)}),l&&l();for(let b of m)b();m.length=0,f(),a.down([[S,"closed"]]),d.clear(),c.clear()}}let y={meta:{status:a,error:u},destroy:h};for(let[b,v]of c)y[b]=v;return y}Ne();ie();Ee();ne();function Um(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function xa(t,e){let n=Um(t)?t:Ut(t),r=e.import??[],o=e.transfer??{},s=new Map,i=new Map,a={};for(let h of r){let y=N(void 0,{name:`worker::${h}`});s.set(h,y),a[h]=y}let u=e.expose(a),c=Object.entries(u),d,l=!1;if(c.length>0){let h=c.map(([,v])=>v),y=H(h,(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=ce([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 p=[];for(let[h,y]of c){let b=y.subscribe((v=>{if(!l)for(let T of v){let w=T[0];w!==S&&(De.isLocalOnly(w)||(w===M?n.post({t:"e",s:h,err:bn(T[1])}):n.post({t:"s",s:h,sig:qt(w),d:T.length>1?T[1]:void 0})))}}));p.push(b)}let f=n.listen(h=>{if(l)return;let y=h;switch(y.t){case"i":{Q(()=>{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":{Q(()=>{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,vn(y.err)]]);break}case"s":{let b=yn(y.sig);if(!b)break;if(b===pe&&y.s==="*"){g();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[h,y]of c)m[h]=y.cache;n.post({t:"r",stores:m});function g(){if(!l){l=!0,d&&d();for(let h of p)h();p.length=0,f(),n.terminate?.(),i.clear(),s.clear()}}return{destroy:g}}var wu={};we(wu,{SNAPSHOT_WIRE_VERSION:()=>go,SurfaceError:()=>Re,accountability:()=>Zs,ai:()=>Ys,asSurfaceError:()=>hi,cqrs:()=>is,createGraph:()=>ir,deleteSnapshot:()=>ki,demoShell:()=>ti,diffSnapshots:()=>Ti,domainTemplates:()=>ni,graphspec:()=>Js,guarded:()=>oi,harness:()=>ai,jobQueue:()=>di,layout:()=>fi,lens:()=>pi,listSnapshots:()=>wi,memory:()=>qs,messaging:()=>Bs,orchestration:()=>js,reduction:()=>zs,refine:()=>ii,resilientPipeline:()=>mi,restoreSnapshot:()=>vi,runReduction:()=>gi,saveSnapshot:()=>bi,surface:()=>xi});var Ys={};we(Ys,{AgentLoopGraph:()=>Hs,AllTiersExhaustedError:()=>Xr,BudgetExhaustedError:()=>As,ChatStreamGraph:()=>Vs,CircuitOpenError:()=>dt,DEFAULT_DECAY_RATE:()=>so,FallbackMissError:()=>th,LLMTimeoutError:()=>nr,ReplayCacheMissError:()=>kn,ToolRegistryGraph:()=>Ks,admissionFilter3D:()=>hg,admissionScored:()=>ip,agentLoop:()=>pg,agentMemory:()=>bg,anthropicAdapter:()=>Sa,canonicalJson:()=>Ea,cascadingLlmAdapter:()=>Ba,chatStream:()=>Ha,composePricing:()=>Th,computePrice:()=>La,contentGate:()=>cg,costMeterExtractor:()=>rg,createAdapter:()=>hh,createCapabilitiesRegistry:()=>zm,createPricingRegistry:()=>bh,dryRunAdapter:()=>Tn,fallbackAdapter:()=>_a,fromLLM:()=>Ih,frozenContext:()=>$h,gatedStream:()=>eg,gaugesAsContext:()=>Rg,googleAdapter:()=>Ma,graphFromSpec:()=>yp,graphFromSpecReactive:()=>Dg,handoff:()=>fg,keywordFlagExtractor:()=>sg,knobsAsTools:()=>Gg,llmConsolidator:()=>Ua,llmExtractor:()=>qa,memoryRetrieval:()=>xg,memoryWithKG:()=>Tg,memoryWithTiers:()=>wg,memoryWithVectors:()=>vg,observableAdapter:()=>gh,openAICompatAdapter:()=>Ca,parseRateLimitFromError:()=>Ga,pricingFor:()=>wh,promptNode:()=>Rn,redactor:()=>dg,registryPricing:()=>vh,resilientAdapter:()=>Lh,streamExtractor:()=>ig,streamingPromptNode:()=>Zh,suggestStrategy:()=>bp,suggestStrategyReactive:()=>$g,systemPromptBuilder:()=>tg,tier:()=>Ch,toolCallExtractor:()=>ug,toolRegistry:()=>Wa,toolSelector:()=>mg,validateGraphDef:()=>Bg,withBreaker:()=>Ia,withBudgetGate:()=>Pa,withDryRun:()=>xh,withRateLimiter:()=>$a,withReplayCache:()=>Qr,withRetry:()=>ja,withTimeout:()=>Va,zeroPrice:()=>Cs});ne();function Yr(t,e){return`${t}::${e}`}function zm(t){let e=Ye({name:"capabilitiesRegistry"}),n=c=>{e.set(Yr(c.provider,c.id),c)};if(t)for(let c of t)n(c);let r=(c,d)=>{let l=e.get(Yr(c,d));if(l)return l;let p=e.entries.cache;if(!p)return;let f;for(let[,m]of p){if(m.provider!==c)continue;let g=m.id;d.startsWith(g)&&(!f||g.length>f.id.length)&&(f=m)}return f},o=128,s=new Map,i=new Map,a=(c,d,l,p)=>{for(c.has(d)&&c.delete(d),c.set(d,l);c.size>p;){let f=c.keys().next().value;if(f===void 0)break;c.delete(f)}},u=_([e.entries],([c])=>Array.from(c.values()),{name:"capabilitiesRegistry/entries",initial:[]});return{register:n,lookup:r,remove(c,d){let l=e.has(Yr(c,d));return l&&e.delete(Yr(c,d)),l},entries(){let c=e.entries.cache;return(function*(){if(c)for(let d of c.values())yield d})()},lookupNode(c,d){let l=Yr(c,d),p=s.get(l);if(p)return s.delete(l),s.set(l,p),p;let f=_([e.entries],()=>r(c,d),{name:`capabilitiesRegistry/lookup/${c}::${d}`,initial:void 0});return a(s,l,f,o),f},entriesNode:u,byProvider(c){let d=i.get(c);if(d)return i.delete(c),i.set(c,d),d;let l=_([u],([p])=>p.filter(f=>f.provider===c),{name:`capabilitiesRegistry/byProvider/${c}`,initial:[]});return a(i,c,l,o),l}}}ke();function Sa(t={}){return t.sdk?Zm(t):Xm(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}=Jm(t,e?.systemPrompt),a={model:o,messages:i.map(Ym),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(Qm)),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 Jm(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(`
33
33
 
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(`
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(`
36
- `)),e}function wl(t){let e=t.indexOf(`\r
37
- \r
38
- `),n=t.indexOf(`
34
+ `):void 0,chat:r}}function Ym(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 Qm(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 Gl(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 Xm(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=j(),d=await o(`${n}/v1/messages`,{method:"POST",headers:s(),body:JSON.stringify(u),signal:a?.signal});if(!d.ok)throw await ht(d,"Anthropic");let l=await d.json(),p=Math.max(0,(j()-c)/1e6);return Gl(l,p)},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 ht(c,"Anthropic");if(!c.body)throw new Error("anthropicAdapter: streaming response has no body");let d,l,p=new Map;for await(let f of Lt(c.body,{signal:a?.signal})){let m=f.data;if(!m)continue;let g;try{g=JSON.parse(m)}catch{continue}switch(g.type){case"message_start":{d=Ss(d,g.message.usage);break}case"content_block_start":{let h=g,y=h.content_block;y.type==="tool_use"&&(p.set(h.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 h=g,y=h.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=p.get(h.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 h=g;h.delta.stop_reason&&(l=h.delta.stop_reason),h.delta.usage&&(d=Ss(d,h.delta.usage));break}case"message_stop":break}}d&&(yield{type:"usage",usage:Na(d)}),yield{type:"finish",reason:l??"stop"}}}}function Zm(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=j(),i=await e.messages.create(o,{signal:r?.signal}),a=Math.max(0,(j()-s)/1e6);return Gl(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=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"}}}}vt();function Ns(){let t=new Error("aborted");return t.name="AbortError",t}function Fl(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Ns()):new Promise((n,r)=>{let o=new Ce,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(Ns())},e.addEventListener("abort",s,{once:!0}))})}function Tn(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 Fl(r,u?.signal),u?.signal?.aborted)throw Ns();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,p=r>0?r/l:0;for(let f=0;f<c.length;f+=o){if(u?.signal?.aborted)throw Ns();await Fl(p,u?.signal),yield{type:"token",delta:c.slice(f,f+o)}}yield{type:"usage",usage:d},yield{type:"finish",reason:"stop"}}}}ke();ke();be();vt();function $l(t){let{storage:e,mode:n="read-write",keyFn:r,keyPrefix:o="llm-replay"}=t,i=ws({storage:e,keyPrefix:o,mode:n==="read-strict"?"read":n,keyContext:({messages:u,opts:c})=>{let{signal:d,keyContext:l,...p}=c??{};return{messages:u,opts:p}}});async function a(u,c){if(r){if(r.length<=1){let l={messages:u,opts:c,context:c?.keyContext},p=await r(l);return`${o}:${p}`}let d=await r(u,c);return`${o}:${d}`}return i.keyFor({messages:u,opts:c})}return{keyFor:a,async lookup(u,c){if(n!=="write"){if(r){let d=await a(u,c),l=await e.load(d);return l??void 0}return i.lookup({messages:u,opts:c})}},async store(u,c,d){if(n!=="read"){if(r){let l=await a(u,c);await e.save(l,d);return}await i.store({messages:u,opts:c},d)}},async forget(u,c){if(!(n==="read"||n==="write")&&e.clear){if(r){let d=await a(u,c);await e.clear(d);return}await i.forget({messages:u,opts:c})}}}}ke();ie();ne();be();function Qe(t,e,n){return{provider:n?.provider??t.provider,model:n?.model??t.model,capabilities:n?.capabilities??t.capabilities?.bind(t),invoke:e.invoke,stream:e.stream}}function Es(t,e){let{onResp:n,onError:r,name:o}=e;if(t!=null&&typeof t.then=="function"){let c=t;return r?c.then(n).catch(d=>{throw r(d),d}):c.then(n)}if(t!=null&&typeof t=="object"&&"content"in t)return n(t);let s=U(t);if(r){let c=!1;s.subscribe(d=>{for(let l of d){if(c)return;l[0]===M&&(c=!0,r(l[1]))}})}let i,a=!1,u=Gr(s,c=>{i=n(c),a=!0});return _([u],([c])=>c==null?null:a?i:n(c),{name:o??"adapt/invokeTap"})}function wn(t){let e=t.endNs??j();return{timestamp:e,wallClock:t.startWallClockNs??fe(),provider:t.provider,model:t.model,tier:t.tier,usage:t.usage,latencyMs:Math.max(0,(e-t.startNs)/1e6),method:t.method,...t.error?{error:t.error}:{}}}function kt(){return{input:{regular:0},output:{regular:0}}}var Bl=Symbol.for("graphrefly.adapter.middlewareLayers");function Ue(t,e,n){let o=[...n?eh(n):[],e];return Object.defineProperty(t,Bl,{value:Object.freeze(o),enumerable:!1,writable:!1,configurable:!1}),t}function eh(t){let e=t[Bl];return Array.isArray(e)?e:[]}var kn=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 Qr(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=n==="read"||n==="read-strict",u=$l({storage:e.storage,mode:n==="write-only"?"write":n,keyFn:e.keyFn,keyPrefix:i}),c=p=>p<=0?Promise.resolve():new Promise(f=>{new Ce().start(p,()=>f())}),d=xs(async({messages:p,invokeOpts:f})=>await Je(U(t.invoke(p,f))),{keyFn:({_precomputedKey:p})=>p}),l=Qe(t,{async invoke(p,f){let m=await u.keyFor(p,f),g=await u.lookup(p,f);if(g?.response){let y=g.response;return{...y,metadata:{...y.metadata??{},replayCache:"hit"}}}if(n==="read-strict")throw new kn(m,"invoke");let h=await d({messages:p,invokeOpts:f,_precomputedKey:m});return a||await u.store(p,f,{response:h,storedAtNs:fe()}),h},async*stream(p,f){if(!r){for await(let k of t.stream(p,f))yield k;return}let m=await u.keyFor(p,f),g=await u.lookup(p,f);if(g){let k=g.response;if(g.streamChunks&&g.streamCadenceMs)for(let x=0;x<g.streamChunks.length;x++){let R=g.streamCadenceMs[x]??0,E=s>0?R/s:0;E>0&&await c(E),yield{type:"token",delta:g.streamChunks[x]?.delta??""}}else k.content&&(yield{type:"token",delta:k.content});k.usage&&(yield{type:"usage",usage:k.usage}),yield{type:"finish",reason:k.finishReason??"stop"};return}if(n==="read-strict")throw new kn(m,"stream");let h="",y,b,v=[],T=[],w;for await(let k of t.stream(p,f)){if(k.type==="token"&&(h+=k.delta,o)){let x=j(),R=w===void 0?0:(x-w)/1e6;T.push(R),w=x,v.push({delta:k.delta})}k.type==="usage"&&(y=k.usage),k.type==="finish"&&(b=k.reason),yield k}if((h||y)&&!a){let x={response:{content:h,usage:y??{input:{regular:0},output:{regular:0}},finishReason:b,model:t.model??f?.model??"",provider:t.provider},storedAtNs:fe(),...o?{streamChunks:v,streamCadenceMs:T}:{}};await u.store(p,f,x)}}});return Ue(l,"withReplayCache",t),l}var Ea=Kr;var th=kn;function jl(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 Vl(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 nh(t,e){if("key"in t)return t.key;let n=Ea({messages:t.messages,opts:t.invokeOpts??{}}),r=await Ts(n);return`${e}:${r}`}function rh(t){let e={response:t.response,storedAtNs:fe()};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 oh(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=zr(),o=t.fixtures,s=(async()=>{for(let i of o){let a=await nh(i,e);await r.save(a,rh(i))}})();return s.catch(()=>{}),{tier:r,seedReady:s}}return t.fixturesStorage?{tier:t.fixturesStorage,seedReady:Promise.resolve()}:{tier:void 0,seedReady:Promise.resolve()}}function _a(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"?Tn({provider:e,model:n,respond:()=>"[unreachable: read-strict mode throws on miss]"}):{provider:e,model:n,async invoke(d,l){let p=t.respond?t.respond(d,l):jl(e,n);return Vl(p,e,n)},async*stream(d,l){let p=t.respond?t.respond(d,l):jl(e,n),f=Vl(p,e,n);yield{type:"token",delta:f.content},f.usage&&(yield{type:"usage",usage:f.usage}),yield{type:"finish",reason:f.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=oh(t,o);i=d.tier??zr(),a=d.seedReady}let u=t.record?"read-write":r==="throw"?"read-strict":"read",c=Qr(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 p of c.stream(d,l))yield p}}}ke();function Ma(t={}){return t.sdk?uh(t):ah(t)}function _s(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(`
39
35
 
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(`
36
+ `)}]});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(sh)}]),e?.providerExtras&&Object.assign(o,e.providerExtras),o}function sh(t){return{name:t.name,description:t.description,parameters:t.parameters}}function Oa(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 Kl(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:Oa(t.usageMetadata),finishReason:n?.finishReason,latencyMs:e,model:t.modelVersion,provider:"google"}}function ih(t){if(t.apiKey)return t.apiKey;let e=globalThis.process?.env;return e?.GOOGLE_API_KEY??e?.GEMINI_API_KEY}function ah(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=ih(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=_s(s,i),c=j(),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 ht(l,"Google");let p=await l.json(),f=Math.max(0,(j()-c)/1e6);return Kl(p,f)},async*stream(s,i){let a=r(i),u=_s(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 ht(d,"Google");if(!d.body)throw new Error("googleAdapter: streaming response has no body");let l,p;for await(let f of Lt(d.body,{signal:i?.signal})){if(!f.data)continue;let m;try{m=JSON.parse(f.data)}catch{continue}let g=m.candidates?.[0];for(let h of g?.content?.parts??[])typeof h.text=="string"&&(h.thought?yield{type:"thinking",delta:h.text}:yield{type:"token",delta:h.text}),h.functionCall&&(yield{type:"tool-call-delta",delta:{name:h.functionCall.name,argumentsDelta:JSON.stringify(h.functionCall.args??{})}});g?.finishReason&&(p=g.finishReason),m.usageMetadata&&(l=m.usageMetadata)}l&&(yield{type:"usage",usage:Oa(l)}),yield{type:"finish",reason:p??"stop"}}}}function uh(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=_s(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=j(),a=await e.models.generateContent({...o,model:s},{signal:r?.signal}),u=Math.max(0,(j()-i)/1e6);return Kl(a,u)},async*stream(n,r){if(!e.models.generateContentStream)throw new Error("sdkBackedGoogle: SDK instance does not expose generateContentStream");let o=_s(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:Oa(i)}),yield{type:"finish",reason:a??"stop"}}}}ke();var ch={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?mh(t):fh(t)}function Ms(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(dh);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(lh)),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 dh(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 lh(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}}function Aa(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:ph(a.function.arguments)}));return{content:s,toolCalls:i.length>0?i:void 0,usage:Aa(t.usage),finishReason:r?.finish_reason,latencyMs:e,model:t.model,provider:n}}function ph(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!=null?e:{_raw:t}}catch{return{_raw:t}}}function Wl(t){let e=t.preset??"openai",n=ch[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 fh(t){let{provider:e,baseURL:n,apiKey:r}=Wl(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=Ms(a,u,t.model,!1,t.bodyExtras),d=j(),l=await o(`${n}/chat/completions`,{method:"POST",headers:i(),body:JSON.stringify(c),signal:u?.signal});if(!l.ok)throw await ht(l,e);let p=await l.json(),f=Math.max(0,(j()-d)/1e6);return Hl(p,f,e)},async*stream(a,u){let c=Ms(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 ht(d,e);if(!d.body)throw new Error(`openAICompatAdapter[${e}]: streaming response has no body`);let l,p;for await(let f of Lt(d.body,{signal:u?.signal})){if(!f.data||f.data==="[DONE]")continue;let m;try{m=JSON.parse(f.data)}catch{continue}let g=m.choices;if(g){let h=g[0];if(h?.delta?.content&&(yield{type:"token",delta:h.delta.content}),h?.delta?.reasoning_content&&(yield{type:"thinking",delta:h.delta.reasoning_content}),h?.delta?.tool_calls)for(let y of h.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:y.id,name:y.function?.name,argumentsDelta:y.function?.arguments}};h?.finish_reason&&(p=h.finish_reason)}m.usage&&(l=m.usage,yield{type:"usage",usage:Aa(l)})}yield{type:"finish",reason:p??"stop"}}}}function mh(t){let e=t.sdk;if(!e)throw new Error("sdkBackedOpenAI: sdk instance required");let{provider:n}=Wl(t);return{provider:n,model:t.model,async invoke(r,o){let s=Ms(r,o,t.model,!1,t.bodyExtras),i=j(),a=await e.chat.completions.create(s,{signal:o?.signal}),u=Math.max(0,(j()-i)/1e6);return Hl(a,u,n)},async*stream(r,o){let s=Ms(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 p=d[0];if(p?.delta?.content&&(yield{type:"token",delta:p.delta.content}),p?.delta?.reasoning_content&&(yield{type:"thinking",delta:p.delta.reasoning_content}),p?.delta?.tool_calls)for(let f of p.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:f.id,name:f.function?.name,argumentsDelta:f.function?.arguments}};p?.finish_reason&&(u=p.finish_reason)}let l=c.usage;l&&(a=l,yield{type:"usage",usage:Aa(l)})}yield{type:"finish",reason:u??"stop"}}}}function hh(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 Sa(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 Ma(e)}case"dry-run":{let e={model:t.model,...t.extras};return Tn(e)}case"fallback":{let e={provider:t.provider,model:t.model,...t.extras};return _a(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();ne();be();function gt(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 It(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 ql(){return{input:{regular:0},output:{regular:0}}}function gh(t,e){let n=e?.logMax??1e3,r=We(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:n}),o=N(null,{name:"adapterStats/lastCall"}),s=_([r.entries],([g])=>g.length,{name:"adapterStats/totalCalls",initial:0}),i=_([r.entries],([g])=>g.reduce((h,y)=>h+gt(y.usage),0),{name:"adapterStats/totalInputTokens",initial:0}),a=_([r.entries],([g])=>g.reduce((h,y)=>h+It(y.usage),0),{name:"adapterStats/totalOutputTokens",initial:0}),u=[oe(s),oe(i),oe(a)],c=g=>{r.append(g),o.emit(g)},d=()=>{r.clear(),o.emit(null)},l=Qe(t,{invoke(g,h){let y=j(),b=fe(),v=t.model??h?.model??"",T=k=>(c(wn({provider:t.provider,model:t.model??h?.model??k.model??"",tier:h?.tier??k.tier,usage:k.usage??kt(),startNs:y,startWallClockNs:b,method:"invoke"})),k),w=k=>{let x=k;c(wn({provider:t.provider,model:v,tier:h?.tier,usage:kt(),startNs:y,startWallClockNs:b,method:"invoke",error:{type:x?.name??"Error",message:x?.message??String(k)}}))};return Es(t.invoke(g,h),{onResp:T,onError:w,name:"adapterStats/invokeTap"})},async*stream(g,h){let y=j(),b=fe(),v=t.model??h?.model??"",T;try{for await(let w of t.stream(g,h))w.type==="usage"&&(T=w.usage),yield w;c(wn({provider:t.provider,model:v,tier:h?.tier,usage:T??kt(),startNs:y,startWallClockNs:b,method:"stream"}))}catch(w){let k=w;throw c(wn({provider:t.provider,model:v,tier:h?.tier,usage:T??kt(),startNs:y,startWallClockNs:b,method:"stream",error:{type:k?.name??"Error",message:k?.message??String(w)}})),w}}});Ue(l,"observableAdapter",t);let p=!1;return{adapter:l,stats:{lastCall:o,allCalls:r,totalCalls:s,totalInputTokens:i,totalOutputTokens:a,reset:d,dispose:()=>{if(!p){p=!0;for(let g of u)g();u.length=0}}}}}function yh(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function Cs(t="USD"){return{total:0,currency:t}}function La(t,e,n){let r=gt(t),o=e.currency??"USD",s=n?.withBreakdown===!0,i=s?{}:null,a=0,u=(h,y,b)=>{if(!y||b==null)return;let v=yh(b,r),T=y*v/1e6;a+=T,s&&(i[h]=(i[h]??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[h,y]of Object.entries(c.extensions))u(`input.ext.${h}`,y,d.extensions[h]);let l=t.output,p=e.output;if(p&&(u("output.regular",l.regular,p.regular),u("output.reasoning",l.reasoning??0,p.reasoning),u("output.audio",l.audio??0,p.audio),u("output.predictionAccepted",l.predictionAccepted??0,p.predictionAccepted),u("output.predictionRejected",l.predictionRejected??0,p.predictionRejected),l.extensions&&p.extensions))for(let[h,y]of Object.entries(l.extensions))u(`output.ext.${h}`,y,p.extensions[h]);let f=n?.tier;if(f&&e.tierMultipliers){let h=e.tierMultipliers[f];if(h!=null&&(a*=h,s))for(let y of Object.keys(i))i[y]*=h}let m=t.auxiliary,g=e.auxiliary;if(m&&g)for(let[h,y]of Object.entries(m)){let b=g[h];if(b==null||!y)continue;let v=y*b;a+=v,s&&(i[`auxiliary.${h}`]=v)}return s?{total:a,currency:o,breakdown:i}:{total:a,currency:o}}function Os(t,e){return`${t}::${e}`}function bh(t){let e=new Map,n=new Map,r=(o,s,i)=>{e.set(Os(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(Os(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(Os(o,c));d&&(u={key:c,pricing:d.pricing})}return u?.pricing},remove(o,s){let i=e.delete(Os(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 vh(t,e="USD"){return(n,r)=>{let o=t.lookup(r.provider,r.model);return o?La(n,o,{tier:r.tier,withBreakdown:r.withBreakdown}):Cs(e)}}function Th(...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):Cs()}}function wh(t,e,n){return t?.pricing?La(e,t.pricing,n):Cs()}Et();be();function Ia(t,e={}){let n=e.breaker??Tt(e),r=Qe(t,{async invoke(o,s){if(!n.canExecute())throw new dt;try{let i=await Je(U(t.invoke(o,s)));return n.recordSuccess(),i}catch(i){throw n.recordFailure(i),i}},async*stream(o,s){if(!n.canExecute())throw new dt;try{for await(let i of t.stream(o,s))yield i;n.recordSuccess()}catch(i){throw n.recordFailure(i),i}}});return Ue(r,"withBreaker",t),{adapter:r,breaker:n}}ke();ie();ne();be();var As=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"},Da=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),Ul=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function Pa(t,e){let n=We(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),r=N(Ul(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=_([r],([c])=>{let d=c;return!(e.caps.calls!=null&&d.calls>=e.caps.calls||e.caps.inputTokens!=null&&d.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&d.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&d.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(oe(o),e.onExhausted!=null){let c=e.onExhausted,d=!1,l=!0;o.subscribe(p=>{for(let f of p)if(f[0]===S){let m=f[1];if(d&&l&&m===!1){let g=zl(r.cache??Da,e.caps);g&&c(g)}l=m,d=!0}})}let s=()=>{if(o.cache===!1){let c=r.cache??Da,d=zl(c,e.caps);return new As(d??"budget",e.caps[d??"calls"]??0,kh(c,d??"calls"))}},i=(c,d)=>{let l=t.provider,p=wn({provider:l,model:d.model,tier:d.tier,usage:c,startNs:d.startNs,method:d.method,...d.error?{error:d.error}:{}});n.append(p);let f=r.cache??Da,m=e.pricingFn?f.usd+e.pricingFn(c,{model:d.model,provider:l,tier:d.tier}).total:f.usd;r.emit({calls:f.calls+1,inputTokens:f.inputTokens+gt(c),outputTokens:f.outputTokens+It(c),usd:m})},a=()=>{n.clear(),r.emit(Ul())},u=Qe(t,{invoke(c,d){let l=s();if(l)return Promise.reject(l);let p=j(),f=t.model??d?.model??"",m=h=>(i(h.usage??kt(),{model:t.model??d?.model??h.model??"",tier:d?.tier??h.tier,startNs:p,method:"invoke"}),h),g=h=>{let y=h;i(kt(),{model:f,tier:d?.tier,startNs:p,method:"invoke",error:{type:y?.name??"Error",message:y?.message??String(h)}})};return Es(t.invoke(c,d),{onResp:m,onError:g,name:"budgetGate/invokeTap"})},async*stream(c,d){let l=s();if(l)throw l;let p=j(),f;try{for await(let m of t.stream(c,d))m.type==="usage"&&(f=m.usage),yield m;i(f??kt(),{model:t.model??d?.model??"",tier:d?.tier,startNs:p,method:"stream"})}catch(m){let g=m;throw i(f??kt(),{model:t.model??d?.model??"",tier:d?.tier,startNs:p,method:"stream",error:{type:g?.name??"Error",message:g?.message??String(m)}}),m}}});return Ue(u,"withBudgetGate",t),{adapter:u,budget:{totals:r,isOpen:o,log:n,reset:a}}}function zl(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 kh(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}be();function xh(t,e){let n=e.mock??Tn({provider:t.provider,model:t.model}),r=typeof e.enabled=="boolean"?e.enabled:void 0,o=r===void 0?U(e.enabled):void 0,s;o&&(s=oe(o));let i=()=>r!==void 0?r:!!o?.cache,a=Qe(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)}});return Ue(a,"withDryRun",t),{adapter:a,dispose:()=>{s&&(s(),s=void 0)}}}function Ga(t){if(t==null||typeof t!="object")return;let e=t,n=e.status,r=Rh(e.headers);if(n!==429&&n!==503&&!Oh(e.message))return;let o={},s=r("retry-after"),i=Nh(s);i!=null&&(o.retryAfterMs=i);let a=r("anthropic-ratelimit-requests-reset");if(a){let f=Jl(a);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let u=r("anthropic-ratelimit-tokens-reset");if(u){let f=Jl(u);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let c=Ls(r,"x-ratelimit-limit-requests");c!=null&&(o.rpmCap=c);let d=Ls(r,"x-ratelimit-limit-tokens");d!=null&&(o.tpmCap=d);let l=Ls(r,"x-ratelimit-remaining-requests"),p=Ls(r,"x-ratelimit-remaining-tokens");if(l!=null&&c!=null&&c>0&&(o.usageHint??={},o.usageHint.rpm=1-l/c),p!=null&&d!=null&&d>0&&(o.usageHint??={},o.usageHint.tpm=1-p/d),o.retryAfterMs==null&&e.message){let f=_h(e.message);f!=null&&(o.retryAfterMs=f)}return e.headers&&(o.metadata={headers:Sh(e.headers)}),o.retryAfterMs==null&&o.rpmCap==null&&o.tpmCap==null&&o.usageHint==null?o.metadata?o:void 0:o}function Rh(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 Sh(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 Ls(t,e){let n=t(e);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function Nh(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 Eh=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function _h(t){let e=Eh.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 Oh(t){return!!t&&Mh.test(t)}ke();ie();ne();Et();be();vt();function Fa(t){let e=new Error(t);return e.name="AbortError",e}function Ql(t={}){let e=Math.max(1,t.burstMultiplier??1),n=t.clampCooldownMs??6e4,r=t.rpm!=null?U(t.rpm):N(Number.POSITIVE_INFINITY),o=t.tpm!=null?U(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=_([r,s],([A,F])=>Math.min(Number(A??1/0),Number(F??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),c=_([o,i],([A,F])=>Math.min(Number(A??1/0),Number(F??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),d=tr(Number(r.cache??Number.POSITIVE_INFINITY),e),l=tr(Number(o.cache??Number.POSITIVE_INFINITY),e),p=!1,f=!1,m=u.subscribe(A=>{for(let F of A)if(F[0]===S){let q=Number(F[1]);Number.isFinite(q)&&q>0?(d=tr(q,e),p=!1):q===1/0?(d=tr(1/0,e),p=!1):q<=0&&(p=!0)}}),g=c.subscribe(A=>{for(let F of A)if(F[0]===S){let q=Number(F[1]);Number.isFinite(q)&&q>0?(l=tr(q,e),f=!1):q===1/0?(l=tr(1/0,e),f=!1):q<=0&&(f=!0)}}),h=0,y=new Ce,b=new Ce,v;t.adaptation!=null&&(v=U(t.adaptation).subscribe(F=>{for(let q of F)q[0]===S&&T(q[1])}));function T(A){if(a.emit(A),A.rpmCap!=null&&Number.isFinite(A.rpmCap)&&A.rpmCap>=0&&(s.emit(A.rpmCap),Number.isFinite(n)&&n>0&&y.start(n,()=>s.emit(Number.POSITIVE_INFINITY))),A.tpmCap!=null&&Number.isFinite(A.tpmCap)&&A.tpmCap>=0&&(i.emit(A.tpmCap),Number.isFinite(n)&&n>0&&b.start(n,()=>i.emit(Number.POSITIVE_INFINITY))),A.retryAfterMs!=null&&A.retryAfterMs>0){let F=j()+A.retryAfterMs*1e6;F>h&&(h=F)}}let w=N(0,{name:"adaptiveRateLimiter/pending"}),k=N(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),x=N(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),R=A=>{w.emit((w.cache??0)+A)},E=()=>{k.emit(d.available()),x.emit(l.available())};async function I(A={}){let F=A.requestCost??1,q=A.tokenCost??0,Y=A.signal;R(1);try{for(;;){if(Y?.aborted)throw Fa("AdaptiveRateLimiter.acquire aborted");let D=j();if(h>D){let Z=Math.ceil((h-D)/1e6);await Is(Z,Y);continue}if(F>0&&p||q>0&&f){await Is(250,Y);continue}let P=d,L=l;if(!P.tryConsume(F)){await Is(Yl(P,F),Y);continue}if(!(q>0?L.tryConsume(q):!0)){P.putBack(F),await Is(Yl(L,q),Y);continue}E();return}}finally{R(-1)}}function O(A){A>0?l.tryConsume(A):A<0&&l.putBack(-A),E()}function G(){m(),g(),v?.(),y.cancel(),b.cancel()}return{effectiveRpm:u,effectiveTpm:c,lastSignal:a,pending:w,rpmAvailable:k,tpmAvailable:x,acquire:I,recordUsage:O,recordSignal:T,dispose:G}}function tr(t,e){if(!Number.isFinite(t)||t===1/0)return jt(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let n=Math.max(1,t*e),r=t/60;return jt(n,r)}function Yl(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 Is(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Fa("AdaptiveRateLimiter.acquire aborted")):new Promise((n,r)=>{let o=new Ce,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(Fa("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",s,{once:!0}))})}be();function $a(t,e={}){let n=e.limiter??Ql({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)},s=Qe(t,{async invoke(i,a){let u=r(i,a);await n.acquire({requestCost:1,tokenCost:u,signal:a?.signal});try{let c=await Je(U(t.invoke(i,a))),d=c.usage??ql(),p=gt(d)+It(d)-u;return p>0&&n.recordUsage(p),c}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=gt(l.usage)+It(l.usage)),yield l;let d=c-u;d>0&&n.recordUsage(d)}catch(c){throw o(c),c}}});return Ue(s,"withRateLimiter",t),{adapter:s,limiter:n}}Et();be();var Xr=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 Ba(t,e={}){if(t.length===0)throw new RangeError("cascadingLlmAdapter: tiers must be non-empty");let n=t.map(s=>({name:s.name,adapter:s.adapter,filter:s.filter,breaker:s.breaker?"canExecute"in s.breaker?s.breaker:Tt(s.breaker):void 0})),r=e.streamRetryBeforeFirstChunk??!0,o={provider:"cascading",model:void 0,async invoke(s,i){let a=[],u=new Map;for(let d=0;d<n.length;d++){let l=n[d];if(l.filter&&!l.filter(s,i)){a.push({name:l.name,reason:"filter"});continue}if(l.breaker&&!l.breaker.canExecute()){a.push({name:l.name,reason:"breaker"});continue}try{let p=await Je(U(l.adapter.invoke(s,i)));return l.breaker?.recordSuccess(),{...p,metadata:{...p.metadata??{},tier:l.name}}}catch(p){u.set(l.name,p),l.breaker?.recordFailure(p);let f=n[d+1];f&&e.onFallback?.(l.name,f.name,p)}}let c={skipped:a,failed:u};throw e.onExhausted?.(c),new Xr(c)},async*stream(s,i){let a=[],u=new Map;for(let d=0;d<n.length;d++){let l=n[d];if(l.filter&&!l.filter(s,i)){a.push({name:l.name,reason:"filter"});continue}if(l.breaker&&!l.breaker.canExecute()){a.push({name:l.name,reason:"breaker"});continue}let p=!1;try{for await(let f of l.adapter.stream(s,i))p=!0,yield f;l.breaker?.recordSuccess();return}catch(f){if(u.set(l.name,f),l.breaker?.recordFailure(f),p||!r)throw f;let m=n[d+1];m&&e.onFallback?.(l.name,m.name,f)}}let c={skipped:a,failed:u};throw e.onExhausted?.(c),new Xr(c)}};return Ue(o,`cascade[${n.map(s=>s.name).join(",")}]`),o}function Ch(t,e,n){let r={name:t,adapter:e};return n?.breaker&&(r.breaker=n.breaker),n?.filter&&(r.filter=n.filter),r}be();vt();function Ds(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function Xl(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Ds()):new Promise((n,r)=>{let o=new Ce,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(Ds())},e.addEventListener("abort",s,{once:!0}))})}function ja(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??Ah,u=e.retryStreaming??!0,c=(l,p)=>{if(s==="decorrelated"){let h=Math.min(o,Math.max(r,p*3));return r+Math.random()*(h-r)}let f=s==="exp"?r*2**(l-1):r*l,m=Math.min(o,f);if(!i)return m;let g=m*(.5+Math.random());return Math.min(o,g)},d=Qe(t,{async invoke(l,p){if(p?.signal?.aborted)throw Ds();let f,m=r;for(let g=1;g<=n;g++)try{return await Je(U(t.invoke(l,p)))}catch(h){if(f=h,g>=n||!a(h,g))throw h;let y=c(g,m);m=y,await Xl(y,p?.signal)}throw f},async*stream(l,p){if(p?.signal?.aborted)throw Ds();if(!u){for await(let g of t.stream(l,p))yield g;return}let f,m=r;for(let g=1;g<=n;g++){let h=!1;try{for await(let y of t.stream(l,p))h=!0,yield y;return}catch(y){if(f=y,h||g>=n||!a(y,g))throw y;let b=c(g,m);m=b,await Xl(b,p?.signal)}}throw f}});return Ue(d,"withRetry",t),d}function Ah(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}be();vt();var nr=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=s=>{let i=new AbortController,a=!1,u,c=new Ce;return s&&(s.aborted?i.abort(s.reason):(u=()=>{c.cancel(),i.abort(s.reason)},s.addEventListener("abort",u,{once:!0}))),c.start(e,()=>{a=!0,i.abort(new nr(e))}),{signal:i.signal,cancel:()=>{c.cancel(),s&&u&&s.removeEventListener("abort",u)},timedOut:()=>a}},r=(s,i)=>{if(!i||s instanceof nr)throw s;let a=s;if(a?.name==="AbortError"||a?.name==="DOMException"&&Number(a.code)===20||s?.message==="aborted"){let c=new nr(e);throw c.cause=s,c}throw s},o=Qe(t,{async invoke(s,i){let{signal:a,cancel:u,timedOut:c}=n(i?.signal);try{return await Je(U(t.invoke(s,{...i,signal:a})))}catch(d){return r(d,c())}finally{u()}},async*stream(s,i){let{signal:a,cancel:u,timedOut:c}=n(i?.signal);try{for await(let d of t.stream(s,{...i,signal:a}))yield d}catch(d){r(d,c())}finally{u()}}});return Ue(o,"withTimeout",t),o}function Lh(t,e={}){let n={adapter:t},r=t;if(e.rateLimit){let o=$a(r,e.rateLimit);r=o.adapter,n.rateLimiter=o.limiter}if(e.budget){let o=Pa(r,e.budget);r=o.adapter,n.budget=o.budget}if(e.breaker){let o=Ia(r,e.breaker);r=o.adapter,n.breaker=o.breaker}if(e.timeoutMs!=null&&(r=Va(r,e.timeoutMs)),e.retry&&(r=ja(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=Ba([{name:e.name??"primary",adapter:r},{name:"fallback",adapter:e.fallback}],o)}return e.cache&&(r=Qr(r,e.cache)),n.adapter=r,n}ne();be();function Ih(t,e,n){let r=U(e);return ve(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})})}Ee();be();ie();be();vt();function ue(t,e){return qe("ai",t,e)}function Dh(t){return t!=null&&typeof t.then=="function"}function Ph(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function Gh(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var Fh=3e4;function Zl(t,e){if(t.status==="settled"){let r=t.cache;if(r!==void 0)return Promise.resolve(r)}let n=e?.timeoutMs??Fh;return new Promise((r,o)=>{let s=new Ce,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]===C){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 xn(t){return Dh(t)?xn(await t):Ph(t)?Zl(t):Gh(t)?Zl(U(t)):t}function rr(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function $h(t,e){let n=U(t),r=e?.refreshTrigger!=null?U(e.refreshTrigger):null;return r==null?H([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:ue("frozen_context")}):H([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:ue("frozen_context")})}ie();ne();be();function ep(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function Bh(t,e=200){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Rn(t,e,n,r){let o=r?.format??"text",s=r?.name??"prompt_node",i=_(e,u=>{if(u.some(d=>d==null))return[];let c=typeof n=="string"?n:n(...u);return c?[{role:"user",content:c}]:[]},{name:`${s}::messages`,meta:ue("prompt_node")});return ve(i,u=>!u||u.length===0?N(null):W(c=>{let d=!1,l=!1,p,f={model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt};if(r?.abort){let y=Wo(r.abort);f.signal=y.signal,p=y.dispose}let m;try{m=t.invoke(u,f)}catch(y){return d=!0,c.down([[M,y]]),()=>{p?.()}}let h=U(m).subscribe(y=>{if(!(l||d))for(let b of y){if(d)return;if(b[0]===S){let v=b[1];try{let T=ep(v),w=o==="json"?JSON.parse(rr(T)):T;c.emit(w)}catch(T){let w=ep(v),k=new Error(`promptNode: failed to parse LLM response as JSON: ${T.message}
37
+ Raw content (first 200 chars): ${Bh(w)}`);d=!0,c.down([[M,k]]);return}}else if(b[0]===M){d=!0,c.down([[M,b[1]]]);return}else if(b[0]===C){d=!0,c.down([[C]]);return}else c.down([b])}});return()=>{l=!0,h(),p?.()}},{name:`${s}::call`,meta:ue("prompt_node::call")}),{name:`${s}::output`,meta:r?.meta?{...ue("prompt_node::output"),...r.meta}:ue("prompt_node::output")})}Ne();ke();ne();be();var Bs={};we(Bs,{MessagingHubGraph:()=>Fs,SubscriptionGraph:()=>Zr,TopicBridgeGraph:()=>Gs,TopicGraph:()=>ut,messagingHub:()=>Ka,subscription:()=>tp,topic:()=>$s,topicBridge:()=>Vh});Ee();var jh=2147483647;function Ps(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Sn(t,e){return qe("messaging",t,e)}var ut=class extends z{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=We([],{name:"events",maxSize:n.retainedLimit}),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=_([this.events],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:Sn("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(oe(this.latest)),this.hasLatest=_([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:Sn("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(oe(this.hasLatest)),this.addDisposer(()=>{this.events.down([[C]])}),this.addDisposer(()=>this._log.disposeAllViews())}publish(e){this._log.append(e)}retained(){return this.events.cache}},Zr=class extends z{source;cursor;available;topic;constructor(e,n,r={}){super(e,r.graph);let o=Ps(r.cursor??0,"subscription cursor");this.topic=n;let s=n.events;this.source=_([s],([i])=>i,{name:"source",describeKind:"derived",meta:Sn("subscription_source"),initial:s.cache}),this.add(this.source,{name:"source"}),this.cursor=N(o,{name:"cursor",describeKind:"state",meta:Sn("subscription_cursor")}),this.add(this.cursor,{name:"cursor"}),this.available=_([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:Sn("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:Ps(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:Ps(e,"subscription pull limit"),s=r.slice(0,o);return n.ack&&s.length>0&&this.ack(s.length),s}},Gs=class extends z{_sourceSub;_target;bridgedCount;constructor(e,n,r,o={}){super(e,o.graph),this._sourceSub=tp(`${e}-subscription`,n,{cursor:o.cursor}),this._target=r,this.mount("subscription",this._sourceSub),this.bridgedCount=N(0,{name:"bridgedCount",describeKind:"state",meta:Sn("topic_bridge_count")}),this.add(this.bridgedCount,{name:"bridgedCount"});let s=Math.max(1,Ps(o.maxPerPump??jh,"topic bridge maxPerPump")),i=o.map??(u=>u),a=H([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:Sn("topic_bridge_pump")});this.add(a,{name:"pump"}),this.addDisposer(oe(a))}},Fs=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 ut(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){Q(()=>{for(let[n,r]of e)this.topic(n).publish(r)})}subscribe(e,n,r){let o=this.topic(n);return new Zr(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 $s(t,e){return new ut(t,e)}function Ka(t,e){return new Fs(t,e)}function tp(t,e,n){return new Zr(t,e,n)}function Vh(t,e,n,r){return new Gs(t,e,n,r)}var js={};we(js,{approval:()=>Uh,branch:()=>qh,gate:()=>eo,join:()=>zh,loop:()=>Jh,onFailure:()=>Xh,pipeline:()=>np,sensor:()=>Qh,subPipeline:()=>Yh,task:()=>Wh});Ne();ie();Ee();ne();function Dt(t,e){if(typeof e=="string")return{node:t.resolve(e),path:e};let n=Kh(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 Kh(t,e){let n=t.describe(),r=`::${He}::`;for(let o of Object.keys(n.nodes).sort())if(!o.includes(r))try{if(t.resolve(o)===e)return o}catch{}}function zt(t,e,n,r){t.add(n,{name:e})}function Jt(t,e){return qe("orchestration",t,e)}function Hh(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 np(t,e){return new z(t,e)}function Wh(t,e,n,r){let s=(r?.deps??[]).map(d=>Dt(t,d)),{deps:i,...a}=r??{},u=(d,l,p)=>{let f=d.map((m,g)=>m!=null&&m.length>0?m.at(-1):p.prevData[g]);l.emit(n(f,p))},c=H(s.map(d=>d.node),u,{...a,name:e,describeKind:"derived",meta:Jt("task",r?.meta)});return zt(t,e,c,s.flatMap(d=>d.path?[d.path]:[])),c}function qh(t,e,n,r,o){let s=Dt(t,n),i=_([s.node],([a])=>({branch:r(a)?"then":"else",value:a}),{...o,name:e,meta:Jt("branch",o?.meta)});return zt(t,e,i,s.path?[s.path]:[]),i}function Uh(t,e,n,r,o){let s=Dt(t,n),i=Dt(t,r),a=o?.isApproved??(c=>!!c),u=H([s.node,i.node],(c,d,l)=>{let p=c[0],f=c[1],m=f!=null&&f.length>0?f.at(-1):l.prevData[1];if(m===void 0||!a(m)){d.down([[B]]);return}if(p==null||p.length===0){f!=null&&f.length>0&&l.prevData[0]!==void 0?d.emit(l.prevData[0]):d.down([[B]]);return}for(let g of p)d.emit(g)},{...o,name:e,describeKind:"derived",meta:Jt("approval",o?.meta)});return zt(t,e,u,[s.path,i.path].filter(c=>typeof c=="string")),u}function eo(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=Dt(t,n),a=N([],{name:"pending",equals:()=>!1}),u=N(s,{name:"isOpen"}),c=_([a],([w])=>w.length,{name:"count"}),d=[],l=!1,p=s,f=u.subscribe(w=>{for(let k of w)k[0]===S&&(p=k[1])});function m(){a.emit([...d])}function g(w){d.push(w),d.length>o&&d.shift(),m()}function h(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=H([i.node],(w,k,x)=>{let R=x.terminalDeps[0];if(R!==void 0){l=!0,d=[],m(),k.down(R===!0?[[C]]:[[M,R]]);return}let E=w[0];if(E==null||E.length===0){k.down([[B]]);return}for(let I of E)p?k.emit(I):(g(I),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=h(w);for(let x of k){if(l)break;b.emit(x)}},reject(w=1){y("reject"),h(w)},modify(w,k=1){y("modify");let x=[...d],R=h(k);for(let E=0;E<R.length&&!l;E++)b.emit(w(R[E],E,x))},open(){y("open"),Q(()=>{u.emit(!0);let w=h(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(f),zt(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 zh(t,e,n,r){let o=n.map(i=>Dt(t,i)),s=_(o.map(i=>i.node),i=>i,{...r,name:e,meta:Jt("join",r?.meta)});return zt(t,e,s,o.flatMap(i=>i.path?[i.path]:[])),s}function Jh(t,e,n,r,o){let s=Dt(t,n),i=o?.iterations,a=typeof i=="number"||i===void 0?void 0:Dt(t,i),u=typeof i=="number"?i:void 0,c=H(a?[s.node,a.node]:[s.node],(d,l,p)=>{let f=d[0],m=f!=null&&f.length>0?f.at(-1):p.prevData[0],g=a?d[1]:void 0,h=u??(a?g!=null&&g.length>0?g.at(-1):p.prevData[1]:1),y=Hh(h);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 zt(t,e,c,[s.path,a?.path].filter(d=>typeof d=="string")),c}function Yh(t,e,n,r){let o=n instanceof z?n:np(e,r);return typeof n=="function"&&n(o),t.mount(e,o),o}function Qh(t,e,n,r){let o=H([],()=>{},{...r,name:e,initial:n,describeKind:"producer",meta:Jt("sensor",r?.meta)});return zt(t,e,o,[]),{node:o,push(s){o.emit(s)},error(s){o.down([[M,s]])},complete(){o.down([[C]])}}}function Xh(t,e,n,r,o){let s=Dt(t,n),i=!1,a=H([],(u,c)=>{let d=s.node.subscribe(l=>{for(let p of l){if(i)return;if(p[0]===M)try{c.emit(r(p[1],c))}catch(f){i=!0,c.down([[M,f]])}else c.down([p]),p[0]===C&&(i=!0)}});return()=>d()},{...o,name:e,describeKind:"derived",completeWhenDepsComplete:!1,errorWhenDepsError:!1,meta:Jt("onFailure",o?.meta)});return zt(t,e,a,s.path?[s.path]:[]),a}async function rp(t,e,n,r){let o="",s=0;for await(let i of t.stream(e,n))r.publish({...i,seq:s++,ts:fe()}),i.type==="token"&&(o+=i.delta);return o}function op(t,e){if(e==="json")try{return JSON.parse(rr(t))}catch(n){let r=t.slice(0,160);throw new Error(`streamingPromptNode: format:"json" \u2014 failed to parse accumulated text as JSON: ${n.message}; content preview: ${r}`)}return t}function sp(t,e){return _([t.latest],([n],r)=>{let o=r.store;if(n==null)return o.acc??"";let s=n;return s.seq===0&&(o.acc=""),s.type==="token"&&(o.acc=(o.acc??"")+s.delta),o.acc??""},{name:e,meta:ue("accumulated_text"),initial:""})}function Zh(t,e,n,r){let o=r?.name??"llm",s=r?.format??"text",i=$s(`${o}/stream`,{...r?.retainedLimit!=null?{retainedLimit:r.retainedLimit}:{}}),a=_(e,l=>{if(l.some(f=>f==null))return[];let p=typeof n=="string"?n:n(...l);return p?[{role:"user",content:p}]:[]},{name:`${o}::messages`,meta:ue("prompt_node::messages"),initial:[]}),u=ve(a,l=>{let p=l;if(!p||p.length===0)return N(null);let f=new AbortController;async function*m(){try{let g=await rp(t,p,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,signal:f.signal},i);yield op(g,s)}finally{f.abort()}}return U(m())}),c=sp(i,`${o}::accumulatedText`),d=oe(u);return{output:u,deltaTopic:i,accumulatedText:c,dispose:()=>{d(),i.destroy()}}}function eg(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=$s(`${c}/stream`,{...s?.retainedLimit!=null?{retainedLimit:s.retainedLimit}:{}}),p=_(u,T=>{let w=T.slice(0,-1);if(w.some(x=>x==null))return[];let k=typeof o=="string"?o:o(...w);return k?[{role:"user",content:k}]:[]},{name:`${c}::messages`,meta:ue("prompt_node::messages"),initial:[]}),f=ve(p,T=>{let w=T;if(!w||w.length===0)return N(null);let k=new AbortController;async function*x(){try{let R=await rp(n,w,{model:s?.model,temperature:s?.temperature,maxTokens:s?.maxTokens,systemPrompt:s?.systemPrompt,signal:k.signal},l);yield op(R,d)}finally{k.abort()}}return U(x())}),m=sp(l,`${c}::accumulatedText`),g=_([f],([T])=>{if(T!=null)return T},{name:`${e}/filter`});t.add(g,{name:`${e}/raw`});let h=eo(t,`${e}/gate`,`${e}/raw`,s?.gate),y=oe(f),b=h.reject.bind(h),v={...h,reject(T=1){Q(()=>{b(T),i.emit(++a)})}};return{output:h.node,deltaTopic:l,accumulatedText:m,gate:v,dispose:()=>{y(),l.destroy()}}}ne();be();function tg(t,e){let n=e?.separator??`
41
38
 
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(`
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(`
44
- `)),e}function Ml(t){let e=t.indexOf(`\r
45
- \r
46
- `),n=t.indexOf(`
47
-
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(`
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(`
50
- `)),e}function Ll(t){let e=t.indexOf(`\r
51
- \r
52
- `),n=t.indexOf(`
53
-
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??`
55
-
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.
58
-
59
- Given a natural-language description, produce a JSON graph definition with this structure:
60
-
61
- {
62
- "name": "<graph_name>",
63
- "nodes": {
64
- "<node_name>": {
65
- "type": "state" | "derived" | "producer" | "operator" | "effect",
66
- "value": <initial_value_or_null>,
67
- "deps": ["<dep_node_name>", ...],
68
- "meta": {
69
- "description": "<human-readable purpose>",
70
- "type": "string" | "number" | "boolean" | "integer" | "enum",
71
- "range": [min, max],
72
- "values": ["a", "b"],
73
- "format": "currency" | "percentage" | "status",
74
- "access": "human" | "llm" | "both" | "system",
75
- "unit": "<unit>",
76
- "tags": ["<tag>"]
77
- }
78
- }
79
- },
80
- "edges": [
81
- { "from": "<source_node>", "to": "<target_node>" }
82
- ]
83
- }
84
-
85
- Rules:
86
- - "state" nodes have no deps and hold user/LLM-writable values (knobs).
87
- - "derived" nodes have deps and compute from them.
88
- - "effect" nodes have deps but produce side effects (no return value).
89
- - "producer" nodes have no deps but generate values asynchronously.
90
- - Edges wire output of one node as input to another. They must match deps.
91
- - meta.description is required for every node.
92
- - Return ONLY valid JSON, no markdown fences or commentary.`;async function ug(t,e,n){let o=[{role:"system",content:n?.systemPromptExtra?`${Yl}
93
-
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:
95
- ${c.errors.join(`
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.
97
-
98
- Given a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.
99
-
100
- Return ONLY valid JSON with this structure:
101
- {
102
- "summary": "<one-line summary of the strategy>",
103
- "reasoning": "<explanation of why these changes help>",
104
- "operations": [
105
- { "type": "add_node", "name": "<name>", "nodeType": "state|derived|effect|producer|operator", "meta": {...}, "initial": <value> },
106
- { "type": "remove_node", "name": "<name>" },
107
- { "type": "connect", "from": "<source>", "to": "<target>" },
108
- { "type": "disconnect", "from": "<source>", "to": "<target>" },
109
- { "type": "set_value", "name": "<name>", "value": <new_value> },
110
- { "type": "update_meta", "name": "<name>", "key": "<meta_key>", "value": <new_value> }
111
- ]
112
- }
113
-
114
- Rules:
115
- - Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).
116
- - Keep changes minimal \u2014 prefer the smallest set of operations that solves the problem.
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}:
39
+ `,r=t.map(i=>typeof i=="string"?N(i):U(i)),o=_(r,i=>i.filter(a=>a!=null&&a!=="").join(n),{name:e?.name??"systemPrompt",describeKind:"derived",meta:ue("system_prompt"),initial:""}),s=oe(o);return Object.assign(o,{dispose:s})}ne();var ng=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens&&t.estimated===e.estimated;function rg(t,e){let n=e?.charsPerToken??4,r={chunkCount:0,charCount:0,estimatedTokens:0,estimated:!0};return _([t.latest],([o],s)=>{if(o==null)return r;let i=o;"chunkCount"in s.store||(s.store.chunkCount=0,s.store.charCount=0,s.store.usageTokens=0,s.store.sawUsage=!1);let a=s.store;i.type==="token"?(a.chunkCount+=1,a.charCount+=i.delta.length):i.type==="usage"&&(a.sawUsage=!0,a.usageTokens=gt(i.usage)+It(i.usage));let u=a.sawUsage?a.usageTokens:Math.ceil(a.charCount/n);return{chunkCount:a.chunkCount,charCount:a.charCount,estimatedTokens:u,estimated:!a.sawUsage}},{name:e?.name??"cost-meter",describeKind:"derived",initial:r,meta:ue("cost_meter_extractor"),equals:ng})}ne();var og=(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 sg(t,e){let n=e.maxPatternLength??128;for(let o of e.patterns)if(o.pattern.source.length>n)throw new Error(`keywordFlagExtractor: pattern "${o.label}" literal exceeds maxPatternLength (${o.pattern.source.length} > ${n}); raise the option or shorten the pattern.`);let r=e.patterns.map(o=>({label:o.label,pattern:o.pattern,compiled:new RegExp(o.pattern.source,`${o.pattern.flags.replace("g","")}g`)}));return _([t],([o],s)=>{if(o==null)return[];let i=o;"flags"in s.store||(s.store.flags=[],s.store.scannedTo=0);let a=s.store.flags,u=s.store.scannedTo,c=Math.max(0,u-n),d=i.slice(c),l=!1;for(let{pattern:p,label:f,compiled:m}of r){m.lastIndex=0;for(let g of d.matchAll(m)){let h=c+(g.index??0);h+g[0].length<=u||(a.push({label:f,pattern:p,match:g[0],position:h}),l=!0)}}return s.store.scannedTo=i.length,l?[...a]:a.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:ue("keyword_flag_extractor"),equals:og})}ne();function ig(t,e,n){return _([t],([r])=>r==null?null:e(r),{name:n?.name??"extractor",describeKind:"derived",initial:null,meta:ue("stream_extractor"),...n?.equals?{equals:n.equals}:{}})}ne();var ag=(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 ug(t,e){return _([t],([n],r)=>{if(n==null)return[];let o=n;"calls"in r.store||(r.store.calls=[],r.store.scanFrom=0);let s=r.store.calls,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 f=u;f<o.length;f++){let m=o[f];if(l)m==="\\"&&f+1<o.length?f++:m==='"'&&(l=!1);else if(m==='"')l=!0;else if(m==="{")c++;else if(m==="}"&&(c--,c===0)){d=f;break}}if(d===-1){r.store.scanFrom=u;break}let p=o.slice(u,d+1);try{let f=JSON.parse(p);typeof f.name=="string"&&f.arguments!=null&&typeof f.arguments=="object"&&(s.push({name:f.name,arguments:f.arguments,raw:p,startIndex: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:ue("tool_call_extractor"),equals:ag})}ne();function cg(t,e,n,r){let o=n*(r?.hardMultiplier??1.5),s=typeof e!="function",i=[t];return s&&i.push(e),_(i,a=>{let u=a[0]??"";if(u.length===0)return"allow";let c=s?a[1]??0:e(u);return c>=o?"block":c>=n?"review":"allow"},{name:r?.name??"content-gate",initial:"allow"})}ne();function dg(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 _([t],([i])=>s(i??""),{name:r?.name??"redactor",initial:""})}Ne();ie();Ee();ne();Et();be();ne();var Vs=class extends z{_log;messages;latest;messageCount;constructor(e,n={}){super(e,n.graph),this._log=We([],{name:"messages",maxSize:n.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=_([this.messages],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:ue("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(oe(this.latest)),this.messageCount=_([this.messages],([r])=>r.length,{name:"messageCount",describeKind:"derived",meta:ue("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 Ha(t,e){return new Vs(t,e)}ne();be();var Ks=class extends z{definitions;schemas;_bundle;constructor(e,n={}){super(e,n.graph),this._bundle=Ye({name:"definitions"}),this.definitions=this._bundle.entries,this.add(this.definitions,{name:"definitions"}),this.schemas=_([this.definitions],([r])=>[...(r??new Map).values()],{name:"schemas",describeKind:"derived",meta:ue("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(oe(this.schemas))}register(e){this._bundle.set(e.name,e)}unregister(e){this._bundle.delete(e)}async execute(e,n){let r=this._bundle.get(e);if(!r)throw new Error(`toolRegistry: unknown tool "${e}"`);let o=r.handler(n);return xn(o)}executeReactive(e,n){let r=this._bundle.get(e);if(!r)throw new Error(`toolRegistry: unknown tool "${e}"`);return U(r.handler(n))}getDefinition(e){return this._bundle.entries.cache?.get(e)}};function Wa(t,e){return new Ks(t,e)}var Hs=class extends z{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;_terminalResult;_disposeRunWiring;_runVersion=0;_running=!1;_currentAbortController=null;constructor(e,n){if(super(e,n.graph),this.chat=Ha(`${e}-chat`,{maxMessages:n.maxMessages}),this.mount("chat",this.chat),this.tools=Wa(`${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:ue("agent_status")}),this.add(this.status,{name:"status"}),this.turn=N(0,{name:"turn",describeKind:"state",meta:ue("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.aborted=N(!1,{name:"aborted",describeKind:"state",meta:ue("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let r=0,o=this.turn.subscribe(P=>{for(let L of P)L[0]===S&&(r=L[1])}),s=!1,i=this.aborted.subscribe(P=>{for(let L of P)L[0]===S&&(s=L[1])}),a=n.adapter,u=n.systemPrompt,c=n.model,d=n.temperature,l=n.maxTokens,p=n.maxTurns??10,f=n.stopWhen,m=this.chat,g=this.tools,h=this.status,y=this.turn,b=this.aborted,v=H([h],(P,L,V)=>{if(to(P,V.prevData,0,"idle")!=="thinking"||s||r>=p){L.down([[B]]);return}let Z=m.allMessages();if(Z.length===0){L.down([[B]]);return}let $=g.schemas.cache??[];L.emit({messages:Z,tools:$})},{name:"promptInput",describeKind:"derived",meta:ue("agent_prompt_input")}),T=ve(v,P=>{let L=new AbortController;return this._currentAbortController=L,s&&L.abort(new Error("agentLoop: aborted")),U(a.invoke(P.messages,{tools:P.tools.length>0?P.tools:void 0,systemPrompt:u,model:c,temperature:d,maxTokens:l,signal:L.signal}),{signal:L.signal})},{equals:()=>!1}),w=N(null,{name:"lastResponse",describeKind:"state",meta:ue("agent_last_response")});this.lastResponse=w;let k=H([w,h],(P,L,V)=>{let K=to(P,V.prevData,0,null);if(to(P,V.prevData,1,"idle")!=="acting"){L.down([[B]]);return}let $=K?.toolCalls;if($==null||$.length===0){L.down([[B]]);return}L.emit($)},{name:"toolCallsRaw",describeKind:"derived",meta:ue("agent_tool_calls_raw")}),x=n.interceptToolCalls?n.interceptToolCalls(k):k;this.toolCalls=x;let R=(P,L)=>{if(P===L)return!0;if(P.length!==L.length)return!1;for(let V=0;V<P.length;V++){let K=P[V],Z=L[V];if(K?.id!==Z?.id||K?.content!==Z?.content)return!1}return!0},E=ve(x,P=>{if(P==null||P.length===0)throw new Error("agentLoop: toolResultsNode received an empty tool-call batch as DATA \u2014 toolCallsRaw gating invariant broken (should emit RESOLVED for empty). Audit toolCallsRaw.");let L=P.map(V=>lg(V,g));return _(L,V=>V.map((K,Z)=>{let $=K;return $!=null&&typeof $=="object"&&"id"in $&&"content"in $?$:{id:P[Z].id,content:JSON.stringify(K??null)}}),{name:"toolResults_batch",equals:R})});this.toolResults=E;let I=ce([T],([P])=>{if(s)return;let L=P,V=r+1,K=L.toolCalls!=null&&L.toolCalls.length>0,Z=L.finishReason==="end_turn"&&(!L.toolCalls||L.toolCalls.length===0),$=f?.(L)===!0,J=V>=p,le=$||Z||!K||J?"done":"acting";Q(()=>{w.emit(L),h.emit(le),y.emit(V),m.append("assistant",L.content,{toolCalls:L.toolCalls})})}),O=ce([E],([P])=>{if(s)return;let L=P;if(L.length===0)return;let V=r>=p?"done":"thinking";Q(()=>{h.emit(V);for(let K of L)m.appendToolResult(K.id,K.content)})}),G=h.cache??"idle",A=h.subscribe(P=>{for(let L of P)L[0]===S&&(G=L[1])}),F=ce([b],([P])=>{P===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),G!=="done"&&h.emit("done"))}),q=oe(I),Y=oe(O),D=oe(F);this._terminalResult=H([h,w],(P,L,V)=>{let K=to(P,V.prevData,0,"idle"),Z=to(P,V.prevData,1,null);if(K==="done"){if(Z!=null){L.emit({response:Z,runVersion:this._runVersion});return}let $=new Error("agentLoop: aborted");$.name="AbortError",L.down([[M,$]]);return}if(K==="error"){L.down([[M,new Error("agentLoop: errored")]]);return}L.down([[B]])},{name:"terminalResult",describeKind:"derived",meta:ue("agent_terminal_result")}),this.add(v,{name:"promptInput"}),this.add(T,{name:"llmResponse"}),this.add(this.lastResponse,{name:"lastResponse"}),this.toolCalls===k?this.add(this.toolCalls,{name:"toolCalls"}):(this.add(k,{name:"toolCallsRaw"}),this.add(this.toolCalls,{name:"toolCalls"})),this.add(E,{name:"toolResults"}),this.add(this._terminalResult,{name:"terminalResult"}),this.addDisposer(o),this.addDisposer(i),this.addDisposer(A),this.addDisposer(q),this.addDisposer(Y),this.addDisposer(D),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;Q(()=>{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 Ho(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 lg(t,e){let n=Bt(()=>U(Promise.resolve().then(()=>e.execute(t.name,t.arguments))),{count:1}),r=_([n],([o])=>({id:t.id,content:typeof o=="string"?o:JSON.stringify(o)}));return Fr(r,o=>({id:t.id,content:JSON.stringify({error:String(o)})}))}function to(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 pg(t,e){return new Hs(t,e)}ne();be();function fg(t,e,n){let r=U(t),o=n?.condition!=null?U(n.condition):null,s=N(null,{name:n?.name?`${n.name}::null`:"handoff::null"});if(o==null)return ve(r,a=>{if(a==null)return s;let u=N(a);return e(u)});let i=_([r,o],([a,u])=>({v:a,open:u===!0}),{name:n?.name?`${n.name}::router`:"handoff::router",describeKind:"derived"});return ve(i,({v:a,open:u})=>{if(a==null)return s;if(!u)return N(a);let c=N(a);return e(c)})}ne();be();function mg(t,e,n){let r=U(t),o=e.map(i=>U(i)),s=[r,...o];return _(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:ue("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 ip(t){let e=t.thresholds??{};return n=>{let r=t.scoreFn(n);for(let o of Object.keys(e)){let s=e[o];if(s===void 0)continue;let i=r[o];if((Number.isFinite(i)?i:Number.NEGATIVE_INFINITY)<s)return!1}return!0}}function hg(t){let e={persistence:t.persistenceThreshold??.3,personalValue:t.personalValueThreshold??.3},n=ip({scoreFn:t.scoreFn,thresholds:e});return t.requireStructured?r=>{if(!n(r))return!1;let o=t.scoreFn(r).structure;return Number.isFinite(o)&&o>0}:n}Ne();ke();ne();be();var qs={};we(qs,{collection:()=>yg,decay:()=>Pt,knowledgeGraph:()=>oo,lightCollection:()=>no,vectorIndex:()=>ro});ke();ne();function Pt(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 ap(t){if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1")}function xt(t){return new Map(t)}function et(t){return t.cache??new Map}function Ws(t){return t.cache??[]}function gg(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 no(t={}){let e=t.maxSize,n=t.policy??"fifo";ap(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=j(),c=et(r),d=c.get(i),l=xt(c);l.set(i,{id:i,value:a,createdAtNs:d?.createdAtNs??u,lastAccessNs:u}),o(l),s(l)},remove(i){let a=xt(et(r));a.delete(i)&&s(a)},clear(){et(r).size!==0&&s(new Map)},get(i){let a=et(r),u=a.get(i);if(u){if(n==="lru"){let c=j(),d=xt(a);d.set(i,{...u,lastAccessNs:c}),s(d)}return u.value}},has(i){return et(r).has(i)}}}function yg(t,e={}){let n=e.maxSize,r=e.policy??"lru",o=e.decayRate??0,s=e.minScore??0,i=e.score??(()=>1);ap(n);let a=new z(t),u=N(new Map,{name:"items",describeKind:"state"}),c=_([u],([g])=>{let h=g??new Map,y=j(),b=[...h.values()].map(v=>{let T=(y-v.lastAccessNs)/1e9;return{...v,score:Pt(v.baseScore,T,o,s)}});return b.sort((v,T)=>T.score-v.score||T.lastAccessNs-v.lastAccessNs),b},{name:"ranked",describeKind:"derived"}),d=_([u],([g])=>(g??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(g,h){let y=(h-g.lastAccessNs)/1e9;return Pt(g.baseScore,y,o,s)}function p(g){if(n!==void 0)for(;g.size>n;){let h=j(),y,b=Number.POSITIVE_INFINITY;for(let v of g.values()){let T=l(v,h);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;g.delete(y.id)}}function f(g){u.emit(g)}return Object.assign(a,{upsert(g,h,y){let b=j(),v=et(u),T=v.get(g),w=y?.score??i(h),k=xt(v);k.set(g,{id:g,value:h,baseScore:w,createdAtNs:T?.createdAtNs??b,lastAccessNs:b}),p(k),f(k)},remove(g){let h=xt(et(u));h.delete(g)&&f(h)},clear(){et(u).size!==0&&f(new Map)},getItem(g){let h=et(u),y=h.get(g);if(y){if(r==="lru"){let b=xt(h);b.set(g,{...y,lastAccessNs:j()}),f(b)}return y}}})}function ro(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=xt(et(o));d.set(a,{id:a,vector:[...u],meta:c}),e==="hnsw"&&r.upsert(a,u,c),i(d)},remove(a){let u=xt(et(o));u.delete(a)&&(e==="hnsw"&&r.remove(a),i(u))},clear(){et(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):[...et(o).values()].map(d=>({id:d.id,score:gg(a,d.vector),meta:d.meta})).sort((d,l)=>l.score-d.score).slice(0,u)}}}function oo(t){let e=new z(t),n=N(new Map,{name:"entities",describeKind:"state"}),r=N([],{name:"edges",describeKind:"state"}),o=_([r],([u])=>{let c=u??[],d=new Map;for(let l of c){let p=d.get(l.from)??[];d.set(l.from,Object.freeze([...p,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=xt(et(n));d.set(u,c),s(d)},removeEntity(u){let c=xt(et(n)),d=c.delete(u),l=Ws(r),p=l.filter(f=>f.from!==u&&f.to!==u);!d&&p.length===l.length||(s(c),i(p))},link(u,c,d,l=1){let p=`${u}\0${c}\0${d}`,f=Ws(r),m=new Set(f.map(h=>`${h.from}\0${h.to}\0${h.relation}`)),g=[...f];if(m.has(p))for(let h=0;h<g.length;h+=1){let y=g[h];if(y.from===u&&y.to===c&&y.relation===d){g[h]={...y,weight:l};break}}else g.push({from:u,to:c,relation:d,weight:l});i(g)},unlink(u,c,d){let l=Ws(r),p=l.filter(f=>d===void 0?!(f.from===u&&f.to===c):!(f.from===u&&f.to===c&&f.relation===d));p.length!==l.length&&i(p)},related(u,c){return Ws(r).filter(d=>(d.from===u||d.to===u)&&(c===void 0||d.relation===c))}})}ne();function up(t,e,n,r){let o=n.name??r;return s=>{let i=N(s);return Rn(n.adapter,[i],a=>e(a),{name:o,format:"json",systemPrompt:t,model:n.model,temperature:n.temperature??0,maxTokens:n.maxTokens})}}function qa(t,e){let n=e.maxExistingKeys??100,r=up(t,o=>JSON.stringify({input:o.raw,existingKeys:o.existingKeys}),e,"llmExtractor");return(o,s)=>{let i=n===Number.POSITIVE_INFINITY?[...s.keys()]:[...s.keys()].slice(0,n);return r({raw:o,existingKeys:i})}}function Ua(t,e){let n=up(t,r=>JSON.stringify({memories:r}),e,"llmConsolidator");return r=>{let o=[...r.entries()].map(([s,i])=>({key:s,value:i}));return n(o)}}var so=Math.LN2/604800;function io(t){return t instanceof Map?t:new Map}function bg(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=qa(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=U(e),T=n.admissionFilter;a=_([v],([w])=>{if(T(w))return w},{name:"admissionFilter",describeKind:"derived"})}let u;n.consolidateFn?u=n.consolidateFn:n.adapter&&n.consolidatePrompt&&(u=Ua(n.consolidatePrompt,{adapter:n.adapter}));let c=n.consolidateTrigger;if(!c&&u&&n.reflection?.enabled!==!1){let v=n.reflection?.interval??3e5;c=at(v,{period:v})}let d={score:n.score,cost:n.cost,budget:n.budget??2e3,context:n.context,consolidate:u,consolidateTrigger:c},l=vs(a,i,d);r.add(l.store.entries,{name:"store"}),r.add(l.compact,{name:"compact"}),r.add(l.size,{name:"size"});let p=null;n.vectorDimensions&&n.vectorDimensions>0&&n.embedFn&&(p=ro({dimension:n.vectorDimensions}),r.add(p.entries,{name:"vectorIndex"}));let f=null;n.enableKnowledgeGraph&&(f=oo(`${t}-kg`),r.mount("kg",f));let m=null;if(n.tiers){let v=n.tiers,T=v.decayRate??so,w=v.maxActive??1e3,k=v.archiveThreshold??.1,x=v.permanentFilter??(()=>!1),R=no({name:"permanent"});r.add(R.entries,{name:"permanent"});let E=new Set,I=D=>E.has(D)?"permanent":io(l.store.entries.cache).has(D)?"active":"archived",O=(D,P)=>{E.add(D),R.upsert(D,P)},G=new Map,A=l.store.entries,F=n.context?U(n.context):N(null),q=ce([A,F],([D,P])=>{let L=io(D),V=j(),K=[],Z=[];for(let[J,le]of L){if(G.has(J)||G.set(J,V),x(J,le)){Z.push({key:J,value:le});continue}let se=n.score(le,P),Te=G.get(J)??V,re=Number(V-Te)/1e9;Pt(se,re,T)<k&&K.push(J)}for(let J of G.keys())L.has(J)||G.delete(J);for(let{key:J,value:le}of Z)E.has(J)||O(J,le);let $=L.size-E.size;if($>w){let J=[...L.entries()].filter(([se])=>!E.has(se)).map(([se,Te])=>({key:se,score:n.score(Te,P)})).sort((se,Te)=>se.score-Te.score),le=$-w;for(let se=0;se<le&&se<J.length;se++){let Te=J[se].key;K.includes(Te)||K.push(Te)}}K.length>0&&Q(()=>{for(let J of K)l.store.delete(J)})});o.push(q.subscribe(()=>{}));let Y=null;v.archiveTier&&(Y=r.attachStorage([v.archiveTier],v.archiveStorageOptions??{})),m={permanent:R,activeEntries:A,archiveHandle:Y,tierOf:I,markPermanent:O}}if(p||f){let v=n.embedFn,T=n.entityFn,w=l.store.entries,k=ce([w],([x])=>{let R=io(x);for(let[E,I]of R){if(p&&v){let O=v(I);O&&p.upsert(E,O,I)}if(f&&T){let O=T(E,I);if(O){for(let G of O.entities??[])f.upsertEntity(G.id,G.value);for(let G of O.relations??[])f.link(G.from,G.to,G.relation,G.weight)}}}});o.push(k.subscribe(()=>{}))}let g=null,h=null,y=null,b=null;if(p||f){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,I=n.context?U(n.context):N(null),O=(D,P)=>{if(!D||!P)return 0;let L=Math.min(D.length,P.length),V=0;for(;V<L&&D[V]===P[V];)V++;return V},G=(D,P,L)=>{let V=new Map,K=[];if(p&&L.vector){K=p.search(L.vector,v);for(let re of K){let me=D.get(re.id);me&&V.set(re.id,{value:me,sources:new Set(["vector"])})}}let Z=[];if(f){let re=[...L.entityIds??[],...V.keys()],me=new Set,ee=re;for(let ae=0;ae<T;ae++){let xe=[];for(let Ae of ee){if(me.has(Ae))continue;me.add(Ae);let Ge=f.related(Ae);for(let rt of Ge){let Be=rt.to;if(!me.has(Be)){xe.push(Be);let X=D.get(Be);if(X){let ye=V.get(Be);ye?ye.sources.add("graph"):V.set(Be,{value:X,sources:new Set(["graph"])}),Z.push(Be)}}}}ee=xe}}for(let[re,me]of D)V.has(re)||V.set(re,{value:me,sources:new Set(["store"])});let $=L.context?.length??0,J=[];for(let[re,{value:me,sources:ee}]of V){let ae=R?R(me):void 0,xe=x(me,P);if(E>0&&$>0){let Ge=O(L.context,ae);Ge>0&&(xe=xe*(1+E*Ge/$))}let Ae=ae?{key:re,value:me,score:xe,sources:[...ee],context:ae}:{key:re,value:me,score:xe,sources:[...ee]};J.push(Ae)}J.sort((re,me)=>me.score-re.score);let le=[],se=0;for(let re of J){let me=k(re.value);if(se+me>w&&le.length>0)break;le.push(re),se+=me}return{packed:le,trace:{vectorCandidates:K,graphExpanded:Z,ranked:J,packed:le}}},A=(D,P)=>{if(D===P)return!0;if(D.length!==P.length)return!1;for(let L=0;L<D.length;L++)if(D[L]!==P[L])return!1;return!0},F=N([],{name:"retrieval",describeKind:"state",meta:ue("retrieval_pipeline"),equals:A});r.add(F,{name:"retrieval"}),g=F;let q=N(null,{name:"retrievalTrace",describeKind:"state",meta:ue("retrieval_trace")});r.add(q,{name:"retrievalTrace"}),h=q,y=D=>{let P=io(l.store.entries.cache),{packed:L,trace:V}=G(P,I.cache,D);return Q(()=>{F.emit(L),q.emit(V)}),L},b=D=>{let P=U(D),L=_([l.store.entries,I,P],([K,Z,$])=>{if($==null)return{packed:[],trace:null};let J=io(K),{packed:le,trace:se}=G(J,Z,$);return{packed:le,trace:se}},{name:"retrievalReactive::result",describeKind:"derived",meta:ue("retrieval_reactive_result"),initial:{packed:[],trace:null}}),V=ce([L],([K])=>{let Z=K;Q(()=>{F.emit(Z.packed),Z.trace&&q.emit(Z.trace)})});return o.push(V.subscribe(()=>{})),_([L],([K])=>K.packed,{name:"retrievalReactive",describeKind:"derived",meta:ue("retrieval_reactive"),initial:[],equals:A})}}return r.addDisposer(()=>{for(let v of o)v();o.length=0}),Object.assign(r,{distillBundle:l,compact:l.compact,size:l.size,vectors:p,kg:f,memoryTiers:m,retrieval:g,retrievalTrace:h,retrieve:y,retrieveReactive:b})}Ne();ke();ne();be();function or(t){return t instanceof Map?t:new Map}function vg(t,e,n){let r=ro({dimension:n.dimension});t.add(r.entries,{name:"vectorIndex"});let s=ce([e.store.entries],([i])=>{let a=or(i);for(let[u,c]of a){let d=n.embedFn(c);d&&r.upsert(u,d,c)}}).subscribe(()=>{});return t.addDisposer(s),{vectors:r,dispose:()=>s()}}function Tg(t,e,n,r){let o=oo(`${n}-kg`);t.mount(n,o);let i=ce([e.store.entries],([a])=>{let u=or(a);for(let[c,d]of u){let l=r.entityFn(c,d);if(l){for(let p of l.entities??[])o.upsertEntity(p.id,p.value);for(let p of l.relations??[])o.link(p.from,p.to,p.relation,p.weight)}}}).subscribe(()=>{});return t.addDisposer(i),{kg:o,dispose:()=>i()}}function wg(t,e,n){let r=n.decayRate??so,o=n.maxActive??1e3,s=n.archiveThreshold??.1,i=n.permanentFilter??(()=>!1),a=no({name:"permanent"});t.add(a.entries,{name:"permanent"});let u=new Set,c=b=>u.has(b)?"permanent":or(e.store.entries.cache).has(b)?"active":"archived",d=(b,v)=>{u.add(b),a.upsert(b,v)},l=new Map,p=e.store.entries,f=n.context?U(n.context):N(null),g=ce([p,f],([b,v])=>{let T=or(b),w=j(),k=[],x=[];for(let[E,I]of T){if(l.has(E)||l.set(E,w),i(E,I)){x.push({key:E,value:I});continue}let O=n.score(I,v),G=l.get(E)??w,A=Number(w-G)/1e9;Pt(O,A,r)<s&&k.push(E)}for(let E of l.keys())T.has(E)||l.delete(E);for(let{key:E,value:I}of x)u.has(E)||d(E,I);let R=T.size-u.size;if(R>o){let E=[...T.entries()].filter(([O])=>!u.has(O)).map(([O,G])=>({key:O,score:n.score(G,v)})).sort((O,G)=>O.score-G.score),I=R-o;for(let O=0;O<I&&O<E.length;O++){let G=E[O].key;k.includes(G)||k.push(G)}}k.length>0&&Q(()=>{for(let E of k)e.store.delete(E)})}).subscribe(()=>{}),h=null;n.archiveTier&&(h=t.attachStorage([n.archiveTier],n.archiveStorageOptions??{}));let y=()=>{g(),h?.dispose()};return t.addDisposer(y),{tiers:{permanent:a,activeEntries:p,archiveHandle:h,tierOf:c,markPermanent:d},dispose:y}}function kg(t,e){if(!t||!e)return 0;let n=Math.min(t.length,e.length),r=0;for(;r<n&&t[r]===e[r];)r++;return r}function xg(t,e,n,r,o){let s=o.topK??20,i=o.graphDepth??1,a=o.budget??2e3,u=o.contextWeight??0,c=o.context?U(o.context):N(null),d=(h,y,b)=>{let v=new Map,T=[];if(n&&b.vector){T=n.search(b.vector,s);for(let I of T){let O=h.get(I.id);O&&v.set(I.id,{value:O,sources:new Set(["vector"])})}}let w=[];if(r){let I=[...b.entityIds??[],...v.keys()],O=new Set,G=I;for(let A=0;A<i;A++){let F=[];for(let q of G)if(!O.has(q)){O.add(q);for(let Y of r.related(q)){let D=Y.to;if(!O.has(D)){F.push(D);let P=h.get(D);if(P){let L=v.get(D);L?L.sources.add("graph"):v.set(D,{value:P,sources:new Set(["graph"])}),w.push(D)}}}}G=F}}for(let[I,O]of h)v.has(I)||v.set(I,{value:O,sources:new Set(["store"])});let k=b.context?.length??0,x=[];for(let[I,{value:O,sources:G}]of v){let A=o.contextOf?o.contextOf(O):void 0,F=o.score(O,y);if(u>0&&k>0){let Y=kg(b.context,A);Y>0&&(F=F*(1+u*Y/k))}let q=A?{key:I,value:O,score:F,sources:[...G],context:A}:{key:I,value:O,score:F,sources:[...G]};x.push(q)}x.sort((I,O)=>O.score-I.score);let R=[],E=0;for(let I of x){let O=o.cost(I.value);if(E+O>a&&R.length>0)break;R.push(I),E+=O}return{packed:R,trace:{vectorCandidates:T,graphExpanded:w,ranked:x,packed:R}}},l=(h,y)=>{if(h===y)return!0;if(h.length!==y.length)return!1;for(let b=0;b<h.length;b++)if(h[b]!==y[b])return!1;return!0},p=N([],{name:"retrieval",describeKind:"state",meta:ue("retrieval_pipeline"),equals:l});t.add(p,{name:"retrieval"});let f=N(null,{name:"retrievalTrace",describeKind:"state",meta:ue("retrieval_trace")});return t.add(f,{name:"retrievalTrace"}),{retrieval:p,retrievalTrace:f,retrieve:h=>{let y=or(e.store.entries.cache),{packed:b,trace:v}=d(y,c.cache,h);return Q(()=>{p.emit(b),f.emit(v)}),b},retrieveReactive:h=>{let y=U(h),b=_([e.store.entries,c,y],([w,k,x])=>{if(x==null)return{packed:[],trace:null};let R=or(w),{packed:E,trace:I}=d(R,k,x);return{packed:E,trace:I}},{name:"retrievalReactive::result",describeKind:"derived",meta:ue("retrieval_reactive_result"),initial:{packed:[],trace:null}}),T=ce([b],([w])=>{let k=w;Q(()=>{p.emit(k.packed),k.trace&&f.emit(k.trace)})}).subscribe(()=>{});return t.addDisposer(T),_([b],([w])=>w.packed,{name:"retrievalReactive",describeKind:"derived",meta:ue("retrieval_reactive"),initial:[],equals:l})}}}function Rg(t,e,n){let r=t.describe({actor:e,detail:"full"}),o=n?.groupByTags??!0,s=n?.separator??`
40
+ `,i=[],a=n?.sinceVersion;for(let[u,c]of Object.entries(r.nodes)){let d=c.meta??{},l=d.description,p=d.format;if(!l&&!p)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 f=l??u,m=c.value,g=d.unit,h;p==="currency"&&typeof m=="number"?h=`$${m.toFixed(2)}`:p==="percentage"&&typeof m=="number"?h=`${(m*100).toFixed(1)}%`:m==null?h="(no value)":h=String(m),g&&p!=="currency"&&p!=="percentage"&&(h=`${h} ${g}`),i.push({path:u,description:f,formatted:h})}if(i.length===0)return"";if(o){let u=new Map,c=[];for(let l of i){let f=r.nodes[l.path].meta?.tags;if(f&&f.length>0){let m=f[0],g=u.get(m);g||(g=[],u.set(m,g)),g.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,p]of[...u.entries()].sort((f,m)=>f[0].localeCompare(m[0])))d.push(`[${l}]${s}${p.map(f=>`- ${f.description}: ${f.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)}ie();ne();be();var Js={};we(Js,{compileSpec:()=>lo,decompileGraph:()=>Ag,extractFnFactory:()=>dp,extractSourceFactory:()=>lp,generateCatalogPrompt:()=>pp,isRichFnEntry:()=>uo,isRichSourceEntry:()=>Ya,llmCompose:()=>Ig,llmRefine:()=>hp,specDiff:()=>Lg,validateSpec:()=>sr,validateSpecAgainstCatalog:()=>co});ne();var zs={};we(zs,{budgetGate:()=>za,effectivenessTracker:()=>Ng,feedback:()=>Yt,funnel:()=>Sg,scorer:()=>ao});Ne();ie();Ee();ne();function Us(t,e){return qe("reduction",t,e)}function Sg(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]:wt(...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`,p=o.resolve(l),f=`__bridge_${i}\u2192${u.name}_input`,m=ce([d],([g])=>{p.emit(g)},{name:f});o.add(m,{name:f}),o.addDisposer(oe(m)),i=`${u.name}::output`}return o}function Yt(t,e,n,r){let o=r?.maxIterations??10,s=`__feedback_${e}`,i=N(0,{meta:Us("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=H([],(l,p)=>{let f=a.subscribe(m=>{for(let g of m){let h=g[0];if(h===S){let y=g[1];if(y==null)return;Q(()=>{Lr(i,o)&&u.emit(y)})}else if(h===C||h===M){let y=h===M&&g.length>1?[M,g[1]]:[h];i.down([y])}}});return()=>f()},{name:c,describeKind:"effect",meta:{...Us("feedback_effect",{feedbackFrom:e,feedbackTo:n}),_internal:!0}});return t.add(d,{name:c}),t.addDisposer(oe(d)),t}function za(t,e,n){if(e.length===0)throw new RangeError("budgetGate requires at least one constraint");let r=e.map(f=>f.node),o=[t,...r],s=[],i=!1,a=!1,u=Symbol("budget-gate"),c=new Array(e.length);function d(){return e.every((f,m)=>f.check(c[m]))}function l(f){for(;s.length>0&&d();){let m=s[0];s=s.slice(1),f.emit(m)}s.length===0&&a&&(a=!1,f.down([[B]]))}return H([],(f,m)=>{for(let h=0;h<e.length;h++)c[h]=e[h].node.cache;let g=[];for(let h=0;h<o.length;h++){let y=o[h];g.push(y.subscribe(b=>{for(let v of b)p(v,h,m)}))}return()=>{for(let h of g)h()}},{...n,describeKind:"derived",meta:Us("budget_gate",n?.meta)});function p(f,m,g){let h=f[0];if(m===0){if(h===S)return d()&&s.length===0?g.emit(f[1]):(s.push(f[1]),i||(i=!0,g.up([[Fe,u]]))),!0;if(h===te)return g.down([[te]]),!0;if(h===B)return s.length===0?g.down([[B]]):a=!0,!0;if(h===C||h===M){for(let y of s)g.emit(y);return s=[],a=!1,i&&(i=!1,g.up([[je,u]])),g.down([f]),!0}return!1}return h===S&&(c[m-1]=f[1]),h===S||h===B?(d()&&s.length>0?(l(g),s.length===0&&i&&(i=!1,g.up([[je,u]]))):!d()&&!i&&s.length>0&&(i=!0,g.up([[Fe,u]])),!0):h===te?!0:h===M?(g.down([f]),!0):h===C}}function ao(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 _(r,i=>{let a=i.slice(0,o),u=i.slice(o),c=[],d=0;for(let l=0;l<o;l++){let p=a[l]??0,f=u[l]??0,g=(s?.[l]?s[l](p):p)*f;c.push(g),d+=g}return{value:a,score:d,breakdown:c}},{...n?{equals:n.equals,resubscribable:n.resubscribable,resetOnTeardown:n.resetOnTeardown}:{},describeKind:"derived",meta:Us("scorer",n?.meta)})}function Ng(t){let e=Ye({name:t?.name??"effectiveness-entries"}),n=_([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 p=c.get(d);if(!p||l.attempts!==p.attempts||l.successes!==p.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 uo(t){return typeof t=="object"&&t!==null&&"factory"in t}function Ya(t){return typeof t=="object"&&t!==null&&"factory"in t}function dp(t){return uo(t)?t.factory:t}function lp(t){return Ya(t)?t.factory:t}function pp(t){let e=[];if(t.fns){let n=new Map;for(let[r,o]of Object.entries(t.fns)){let s=uo(o)?o.tags?.[0]??"Other":"Other";n.has(s)||n.set(s,[]),n.get(s).push(Eg(r,o))}for(let[r,o]of n)e.push(`${r}:
119
41
  ${o.join(`
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:
42
+ `)}`)}if(t.sources){let n=[];for(let[r,o]of Object.entries(t.sources))n.push(_g(r,o));n.length>0&&e.push(`Sources:
121
43
  ${n.join(`
122
44
  `)}`)}return e.join(`
123
45
 
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:
46
+ `)}function Eg(t,e){if(!uo(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 _g(t,e){if(!Ya(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 co(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=Ja(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=Ja(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(uo(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=Ja(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,warnings:[]}}function Ja(t,e){let n=null,r=1/0,o=t.toLowerCase();for(let s of e){let i=Mg(o,s.toLowerCase());i<r&&i<=Math.max(3,Math.floor(t.length/2))&&(r=i,n=s)}return n}function Mg(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 cp=new Set(["state","producer","derived","effect","operator","template"]),Og=new Set(["state","producer","derived","effect","operator"]);function sr(t){let e=[],n=[];if(t==null||typeof t!="object")return{valid:!1,errors:["GraphSpec must be a non-null object"],warnings:n};let r=t;if((typeof r.name!="string"||r.name.length===0)&&e.push("Missing or empty 'name' field"),r.nodes==null||typeof r.nodes!="object"||Array.isArray(r.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e,warnings:n};let o=new Set(Object.keys(r.nodes)),s=new Map,i=new Map;if(r.templates!=null&&typeof r.templates=="object"&&!Array.isArray(r.templates)){for(let[a,u]of Object.entries(r.templates))if(u!=null&&typeof u=="object"){let c=u;i.set(a,{params:Array.isArray(c.params)?c.params:[]})}}if(r.templates!=null)if(typeof r.templates!="object"||Array.isArray(r.templates))e.push("'templates' must be an object");else for(let[a,u]of Object.entries(r.templates)){if(u==null||typeof u!="object"){e.push(`Template "${a}": must be an object`);continue}let c=u;if(Array.isArray(c.params)||e.push(`Template "${a}": missing 'params' array`),c.nodes==null||typeof c.nodes!="object"||Array.isArray(c.nodes))e.push(`Template "${a}": missing or invalid 'nodes' object`);else{let d=new Set(Array.isArray(c.params)?c.params:[]),l=new Set(Object.keys(c.nodes));for(let[p,f]of Object.entries(c.nodes)){if(f==null||typeof f!="object"){e.push(`Template "${a}" node "${p}": must be an object`);continue}let m=f;if((typeof m.type!="string"||!Og.has(m.type))&&e.push(`Template "${a}" node "${p}": invalid type`),Array.isArray(m.deps))for(let g of m.deps)!l.has(g)&&!d.has(g)&&e.push(`Template "${a}" node "${p}": dep "${g}" is not an inner node or param`)}typeof c.output!="string"?e.push(`Template "${a}": missing 'output' string`):c.nodes[c.output]||e.push(`Template "${a}": output "${c.output}" is not a declared node`)}}for(let[a,u]of Object.entries(r.nodes)){if(u==null||typeof u!="object"){e.push(`Node "${a}": must be an object`);continue}let c=u;if(typeof c.type!="string"||!cp.has(c.type)){e.push(`Node "${a}": invalid type "${String(c.type)}" (expected: ${[...cp].join(", ")})`);continue}if(s.set(a,c.type),c.type==="template")if(typeof c.template!="string"||!i.has(c.template))e.push(`Node "${a}": template "${String(c.template)}" not found in templates`);else if(c.bind==null||typeof c.bind!="object"||Array.isArray(c.bind))e.push(`Node "${a}": template ref requires 'bind' object`);else{let d=i.get(c.template),l=c.bind;for(let p of d.params)p in l||e.push(`Node "${a}": template param "${p}" is not bound (template "${c.template}")`);for(let[,p]of Object.entries(l))typeof p=="string"&&!o.has(p)&&e.push(`Node "${a}": bind target "${p}" does not reference an existing node`)}else{if(Array.isArray(c.deps))for(let d of c.deps)d===a?e.push(`Node "${a}": self-referencing dep`):o.has(d)||e.push(`Node "${a}": dep "${d}" does not reference an existing node`);(c.type==="derived"||c.type==="effect"||c.type==="operator")&&!Array.isArray(c.deps)&&e.push(`Node "${a}": ${c.type} node should have a 'deps' array`)}}if(r.feedback!=null)if(!Array.isArray(r.feedback))e.push("'feedback' must be an array");else for(let a=0;a<r.feedback.length;a++){let u=r.feedback[a];if(u==null||typeof u!="object"){e.push(`Feedback [${a}]: must be an object`);continue}let c=u;typeof c.from!="string"||!o.has(c.from)?e.push(`Feedback [${a}]: 'from' "${String(c.from)}" does not reference an existing node`):s.get(c.from)==="effect"&&n.push(`Feedback [${a}]: 'from' "${c.from}" is an effect node \u2014 effects emit no DATA, so the feedback edge will never fire. Did you mean a derived/state node upstream?`),typeof c.from=="string"&&c.from===c.to&&e.push(`Feedback [${a}]: 'from' and 'to' must be different nodes`),typeof c.to!="string"||!o.has(c.to)?e.push(`Feedback [${a}]: 'to' "${String(c.to)}" does not reference an existing node`):typeof c.to=="string"&&s.get(c.to)!=="state"&&e.push(`Feedback [${a}]: 'to' node "${c.to}" must be a state node (got "${s.get(c.to)??"unknown"}")`)}return{valid:e.length===0,errors:e,warnings:n}}function lo(t,e){let n=sr(t);if(!n.valid)throw new Error(`compileSpec: invalid GraphSpec:
125
47
  ${n.errors.join(`
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:
127
- ${i.errors.join(`
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.
48
+ `)}`);let r=e?.catalog??{},o=e?.onMissing??"placeholder",s=new z(t.name),i=t.templates??{},a=co(t,r);if(!a.valid)throw new Error(`compileSpec: catalog validation errors:
49
+ ${a.errors.join(`
50
+ `)}`);let u=[],c=(h,y,b)=>{if(b){u.push({path:h,kind:"source",name:b});return}y&&u.push({path:h,kind:"fn",name:y})},d=h=>{let y=r.fns?.[h];return y?dp(y):void 0},l=h=>{let y=r.sources?.[h];return y?lp(y):void 0},p=new Map,f=[];for(let[h,y]of Object.entries(t.nodes)){if(y.type==="template")continue;let b=y;if(b.type==="state"){let v=N(b.initial,{name:h,meta:b.meta?{...b.meta}:void 0});s.add(v,{name:h}),p.set(h,v)}else if(b.type==="producer"){let v=b.source?l(b.source):void 0,T=b.fn?d(b.fn):void 0;if(v){let w=v(b.config??{});s.add(w,{name:h}),p.set(h,w)}else if(T){let w=T([],b.config??{});s.add(w,{name:h}),p.set(h,w)}else{c(h,b.fn,b.source);let w=W(()=>{},{name:h,meta:{...b.meta,_specFn:b.fn,_specSource:b.source}});s.add(w,{name:h}),p.set(h,w)}}else f.push([h,b])}let m=!0,g=new Map(f);for(;g.size>0&&m;){m=!1;for(let[h,y]of[...g.entries()]){let b=y.deps??[];if(!b.every(k=>p.has(k)))continue;let v=b.map(k=>p.get(k)),T=y.fn?d(y.fn):void 0,w;T?w=T(v,y.config??{}):y.type==="effect"?(y.fn&&c(h,y.fn,void 0),w=ce(v,()=>{})):(y.fn&&c(h,y.fn,void 0),w=_(v,k=>k[0])),s.add(w,{name:h}),p.set(h,w),g.delete(h),m=!0}}if(g.size>0){let h=[...g.keys()].sort().join(", ");throw new Error(`compileSpec: unresolvable deps for nodes: ${h}`)}for(let[h,y]of Object.entries(t.nodes)){if(y.type!=="template")continue;let b=y,v=i[b.template],T=new z(h),w=new Map,k=[];for(let[I,O]of Object.entries(v.nodes)){let G=(O.deps??[]).map(F=>F.startsWith("$")&&b.bind[F]?b.bind[F]:F),A={...O,deps:G};if(O.type==="state"){let F=N(O.initial,{name:I,meta:O.meta?{...O.meta}:void 0});T.add(F,{name:I}),w.set(I,F)}else if(O.type==="producer"){let F=O.source?l(O.source):void 0,q=O.fn?d(O.fn):void 0;if(F){let Y=F(O.config??{});T.add(Y,{name:I}),w.set(I,Y)}else if(q){let Y=q([],O.config??{});T.add(Y,{name:I}),w.set(I,Y)}else{c(`${h}.${I}`,O.fn,O.source);let Y=W(()=>{},{name:I,meta:{...O.meta,_specFn:O.fn,_specSource:O.source}});T.add(Y,{name:I}),w.set(I,Y)}}else k.push([I,A])}let x=!0,R=new Map(k);for(;R.size>0&&x;){x=!1;for(let[I,O]of[...R.entries()]){let G=O.deps??[];if(!G.every(D=>w.has(D)||p.has(D)))continue;let F=G.map(D=>w.get(D)??p.get(D)),q=O.fn?d(O.fn):void 0,Y;q?Y=q(F,O.config??{}):O.type==="effect"?(O.fn&&c(`${h}.${I}`,O.fn,void 0),Y=ce(F,()=>{})):(O.fn&&c(`${h}.${I}`,O.fn,void 0),Y=_(F,D=>D[0])),T.add(Y,{name:I}),w.set(I,Y),R.delete(I),x=!0}}if(R.size>0){let I=[...R.keys()].sort().join(", ");throw new Error(`compileSpec: template "${b.template}" has unresolvable deps: ${I}`)}s.mount(h,T);let E=`${h}::${v.output}`;p.set(h,s.resolve(E));try{let I=s.resolve(E);I.meta._templateName?.emit(b.template),I.meta._templateBind?.emit(b.bind)}catch{}}for(let h of t.feedback??[])Yt(s,h.from,h.to,{maxIterations:h.maxIterations});if(u.length>0){if(o==="error"){let h=u.map(y=>` - ${y.path}: missing ${y.kind} "${y.name}"`);throw new Error(`compileSpec: ${u.length} catalog entr${u.length===1?"y":"ies"} missing \u2014 pass them via opts.catalog or set opts.onMissing to "warn"/"placeholder":
51
+ ${h.join(`
52
+ `)}`)}if(o==="warn"){let h=e?.onWarn??(y=>console.warn(y));for(let y of u)h(`compileSpec: ${y.path} references missing ${y.kind} "${y.name}" \u2014 substituted placeholder`)}}return s}var Cg=new Set(["reduction","reduction_type","_specFn","_specSource","_templateName","_templateBind","feedbackFrom","feedbackTo","_internal"]);function Ag(t){let e=t.describe({detail:"standard"}),n={},r=[],o=`::${He}::`,s=/^__feedback_(?!effect_)(.+)$/,i=new Set;for(let f of Object.keys(e.nodes)){if(f.includes(o))continue;let m=s.exec(f);if(m){i.add(m[1]);let g=e.nodes[f]?.meta;g?.feedbackFrom&&g?.feedbackTo&&r.push({from:g.feedbackFrom,to:g.feedbackTo,...g.maxIterations?{maxIterations:g.maxIterations}:{}})}}for(let[f,m]of Object.entries(e.nodes)){if(f.includes(o)||s.test(f)||m.meta?._internal||f.startsWith("__feedback_effect_")||f.startsWith("__bridge_")||f.includes("::"))continue;let g={type:m.type};if(m.deps.length>0&&(g.deps=m.deps.filter(h=>!h.includes("::"))),m.type==="state"&&m.value!==void 0&&(g.initial=m.value),m.meta&&Object.keys(m.meta).length>0){let h={};for(let[y,b]of Object.entries(m.meta))Cg.has(y)||(h[y]=b);Object.keys(h).length>0&&(g.meta=h)}n[f]=g}let a={},u={},c=new Set;for(let f of e.subgraphs){let m=`${f}::`;for(let[g,h]of Object.entries(e.nodes)){if(!g.startsWith(m)||g.includes(o))continue;let y=h.meta;if(y?._templateName&&y?._templateBind){let b=y._templateName,v=y._templateBind;if(!a[b]){let T={},w=new Set,k=`${f}::`;for(let[G,A]of Object.entries(e.nodes)){if(!G.startsWith(k)||G.includes(o))continue;let F=G.slice(k.length);F.includes("::")||(w.add(F),T[F]={type:A.type,...A.deps.length>0?{deps:A.deps.map(q=>q.startsWith(k)?q.slice(k.length):q)}:{}})}let x=[],R=new Map;for(let G of Object.values(T))for(let A of G.deps??[])if(!w.has(A)&&!R.has(A)){let F=`$${A}`;x.push(F),R.set(A,F)}for(let G of Object.values(T))G.deps&&(G.deps=G.deps.map(A=>R.get(A)??A));let E=new Set;for(let G of Object.values(T))for(let A of G.deps??[])w.has(A)&&E.add(A);let O=[...w].filter(G=>!E.has(G))[0]??[...w].pop();a[b]={params:x,nodes:T,output:O}}delete n[f],u[f]={type:"template",template:b,bind:v},c.add(f);break}}}let d=new Map;for(let f of e.subgraphs){if(c.has(f))continue;let m={},g=`${f}::`;for(let[y,b]of Object.entries(e.nodes)){if(y.includes(o)||!y.startsWith(g))continue;let v=y.slice(g.length);v.includes("::")||(m[v]={type:b.type,...b.deps.length>0?{deps:b.deps.map(T=>T.startsWith(g)?T.slice(g.length):T)}:{}})}let h=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(h)||d.set(h,[]),d.get(h).push({name:f,nodes:m})}for(let[,f]of d){if(f.length<2)continue;let m=`${f[0].name}_template`,g=f[0].nodes,h=new Set(Object.keys(g)),y=[],b=new Map;for(let x of Object.values(g))for(let R of x.deps??[])if(!h.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(g))for(let R of x.deps??[])h.has(R)&&v.add(R);let w=[...h].filter(x=>!v.has(x))[0]??[...h].pop(),k={};for(let[x,R]of Object.entries(g))k[x]={...R,deps:R.deps?.map(E=>b.get(E)??E)};a[m]={params:y,nodes:k,output:w};for(let x of f){delete n[x.name];let R={},E=new Set(Object.keys(x.nodes));for(let I of Object.values(x.nodes))for(let O of I.deps??[])if(!E.has(O)){let G=b.get(O)??`$${O}`;R[G]=O}u[x.name]={type:"template",template:m,bind:R}}}let l={...n,...u},p={name:e.name,nodes:l};return Object.keys(a).length>0&&(p.templates=a),r.length>0&&(p.feedback=r),p}function Lg(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}`)),p=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}`;p.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 f=n.filter(b=>b.type==="added").length,m=n.filter(b=>b.type==="removed").length,g=n.filter(b=>b.type==="changed").length,h=[];f&&h.push(`${f} added`),m&&h.push(`${m} removed`),g&&h.push(`${g} changed`);let y=h.length>0?h.join(", "):"no changes";return{entries:n,summary:y}}var fp=`You are a graph architect for GraphReFly, a reactive graph protocol.
129
53
 
130
54
  Given a natural-language description, produce a JSON GraphSpec with this structure:
131
55
 
@@ -167,20 +91,20 @@ Rules:
167
91
  - Use "templates" when the same subgraph pattern repeats (e.g., per-source resilience).
168
92
  - Use "feedback" for bounded cycles where a derived value writes back to a state node.
169
93
  - meta.description is required for every node.
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+=`
94
+ - Return ONLY valid JSON, no markdown fences or commentary.`;function mp(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}async function Ig(t,e,n){let r=fp,o=n?.catalogDescription??(n?.catalog?pp(n.catalog):void 0);o&&(r+=`
171
95
 
172
96
  Available catalog (use ONLY these names):
173
97
  ${o}`),n?.systemPromptExtra&&(r+=`
174
98
 
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:
99
+ ${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=mp(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=sr(c);if(!d.valid)throw new Error(`llmCompose: invalid GraphSpec:
176
100
  ${d.errors.join(`
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:
101
+ `)}`);let l=c;if(n?.catalog){let p=n.maxAutoRefine??0;for(let f=0;f<=p;f++){let m=co(l,n.catalog);if(m.valid)break;if(f===p)throw new Error(`llmCompose: catalog validation failed after ${p} refine attempts:
178
102
  ${m.errors.join(`
179
- `)}`);l=await ap(l,`Fix these catalog errors:
103
+ `)}`);l=await hp(l,`Fix these catalog errors:
180
104
  ${m.errors.join(`
181
105
  `)}
182
106
 
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+=`
107
+ Use ONLY functions and sources from the catalog.`,e,{...n,catalogDescription:o})}}return l}async function hp(t,e,n,r){let o=fp;r?.catalogDescription&&(o+=`
184
108
 
185
109
  Available catalog:
186
110
  ${r.catalogDescription}`),r?.systemPromptExtra&&(o+=`
@@ -190,9 +114,66 @@ ${JSON.stringify(t,null,2)}
190
114
 
191
115
  Modification request: ${e}
192
116
 
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:
117
+ 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=mp(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=sr(c);if(!d.valid)throw new Error(`llmRefine: invalid GraphSpec:
194
118
  ${d.errors.join(`
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.
119
+ `)}`);return c}var gp=`You are a graph architect for GraphReFly, a reactive graph protocol.
120
+
121
+ Given a natural-language description, produce a JSON graph specification with this structure:
122
+
123
+ {
124
+ "name": "<graph_name>",
125
+ "nodes": {
126
+ "<node_name>": {
127
+ "type": "state" | "derived" | "producer" | "effect" | "operator",
128
+ "initial": <initial_value_for_state_nodes>,
129
+ "deps": ["<dep_node_name>", ...],
130
+ "meta": {
131
+ "description": "<human-readable purpose>",
132
+ "type": "string" | "number" | "boolean" | "integer" | "enum",
133
+ "range": [min, max],
134
+ "values": ["a", "b"],
135
+ "format": "currency" | "percentage" | "status",
136
+ "access": "human" | "llm" | "both" | "system",
137
+ "unit": "<unit>",
138
+ "tags": ["<tag>"]
139
+ }
140
+ }
141
+ }
142
+ }
143
+
144
+ Rules:
145
+ - "state" nodes have no deps and hold user/LLM-writable values (knobs). Use "initial" for the starting value.
146
+ - "derived" nodes have deps and compute from them (pure, no side effects).
147
+ - "effect" nodes have deps but produce side effects (no return value).
148
+ - "producer" nodes have no deps but generate values asynchronously.
149
+ - "operator" nodes are parameterized transformations with deps.
150
+ - Use "deps" inside each node to declare dependencies \u2014 no separate "edges" array.
151
+ - meta.description is required for every node.
152
+ - Return ONLY valid JSON, no markdown fences or commentary.`;async function yp(t,e,n){let o=[{role:"system",content:n?.systemPromptExtra?`${gp}
153
+
154
+ ${n.systemPromptExtra}`:gp},{role:"user",content:t}],s=e.invoke(o,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens,signal:n?.signal}),a=(await xn(s)).content.trim();a.startsWith("```")&&(a=rr(a));let u;try{u=JSON.parse(a)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${a.slice(0,200)}`)}return lo(u,{catalog:n?.catalog})}function Dg(t,e,n){let r=U(t);return ve(r,o=>!o||typeof o!="string"||o.trim().length===0?N(null):W(s=>{let i=new AbortController,a=!1;return yp(o,e,{...n,signal:i.signal}).then(u=>{if(a){u.destroy();return}s.emit(u),s.down([[C]])}).catch(u=>{a||s.down([[M,u]])}),()=>{a=!0,i.abort()}},{name:"graphFromSpec::call"}))}function Pg(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 Gg(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=Pg(u),p={type:"object",required:["value"],properties:{value:l},additionalProperties:!1},f=i.replace(/::/g,"__");r.push({type:"function",function:{name:f,description:d,parameters:p}}),o.push({name:i,description:d,inputSchema:p});let m=t,g=e,h=a.v;s.push({name:i,description:d,parameters:p,handler(y){return m.set(i,y.value,g?{actor:g}:void 0),y.value},...h!=null?{version:{id:h.id,version:h.version}}:{}})}return{openai:r,mcp:o,definitions:s}}ie();ne();be();var Fg=`You are a reactive graph optimizer for GraphReFly.
155
+
156
+ Given a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.
157
+
158
+ Return ONLY valid JSON with this structure:
159
+ {
160
+ "summary": "<one-line summary of the strategy>",
161
+ "reasoning": "<explanation of why these changes help>",
162
+ "operations": [
163
+ { "type": "add_node", "name": "<name>", "nodeType": "state|derived|effect|producer|operator", "meta": {...}, "initial": <value> },
164
+ { "type": "remove_node", "name": "<name>" },
165
+ { "type": "connect", "from": "<source>", "to": "<target>" },
166
+ { "type": "disconnect", "from": "<source>", "to": "<target>" },
167
+ { "type": "set_value", "name": "<name>", "value": <new_value> },
168
+ { "type": "update_meta", "name": "<name>", "key": "<meta_key>", "value": <new_value> }
169
+ ]
170
+ }
171
+
172
+ Rules:
173
+ - Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).
174
+ - Keep changes minimal \u2014 prefer the smallest set of operations that solves the problem.
175
+ - Return ONLY valid JSON, no markdown fences or commentary.`;async function bp(t,e,n,r){let{expand:o,...s}=t.describe({actor:r?.actor,detail:"standard"}),i=[{role:"system",content:Fg},{role:"user",content:JSON.stringify({graph:s,problem:e})}],a=n.invoke(i,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens,signal:r?.signal}),c=(await xn(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}}function $g(t,e,n,r){let o=U(e),s=At(o,t);return ve(s,i=>{if(i==null)return N(null);let[a,u]=i;return!u||!a||typeof a!="string"||a.trim().length===0?N(null):u.destroyed?N(null):W(c=>{let d=new AbortController,l=!1;return bp(u,a,n,{...r,signal:d.signal}).then(p=>{l||(c.emit(p),c.down([[C]]))}).catch(p=>{l||c.down([[M,p]])}),()=>{l=!0,d.abort()}},{name:"suggestStrategy::call"})})}var vp=new Set(["state","derived","producer","operator","effect"]);function Bg(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"||!vp.has(i.type))&&e.push(`Node "${o}": invalid type "${String(i.type)}" (expected: ${[...vp].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 Zs={};we(Zs,{AuditTrailGraph:()=>Qs,PolicyEnforcerGraph:()=>Xs,auditTrail:()=>Vg,complianceSnapshot:()=>Kg,policyEnforcer:()=>Xa,reactiveExplainPath:()=>Za});ke();on();ie();Ee();ne();Ro();function wp(t,e){return qe("audit",t,e)}var jg=new Set(["data","error","complete","teardown"]),Qs=class extends z{entries;count;_log;_target;constructor(e,n){super(n.name??`${e.name}_audit`,n.graph),this._target=e,this._log=We([],{name:"entries",...n.maxSize!=null?{maxSize:n.maxSize}:{}}),this.entries=this._log.entries,this.add(this.entries,{name:"entries"}),this.count=_([this.entries],([u])=>u.length,{name:"count",describeKind:"derived",meta:wp("count")}),this.add(this.count,{name:"count"}),this.addDisposer(oe(this.count));let r=n.includeTypes!=null?new Set(n.includeTypes):jg,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??j(),wall_clock_ns:fe(),path:d,type:c},f=(d?Qa(e,d):void 0)?.lastMutation;f!=null&&(l.actor=f.actor),c==="data"&&(l.value=u.data),c==="error"&&(l.error=u.data);let m=d?Wg(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 Vg(t,e={}){return new Qs(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=Hg(n)?n:N(n,{name:"policies"});this.policies=o,this.add(this.policies,{name:"policies"}),this.violations=new ut("violations",{retainedLimit:r.violationsLimit??1e3}),this.mount("violations",this.violations),this.violationCount=_([this.violations.events],([c])=>c.length,{name:"violationCount",describeKind:"derived",meta:wp("policy_violation_count")}),this.add(this.violationCount,{name:"violationCount"}),this.addDisposer(oe(this.violationCount));let i=o.cache??[];this._currentGuard=wr(i);let a=o.subscribe(c=>{for(let d of c)d[0]===S&&(i=d[1]??[],this._currentGuard=wr(i))});this.addDisposer(a);let u=r.paths!=null?[...r.paths]:Tp(e);if(this._mode==="enforce"){let c=new Map,d=l=>{if(c.has(l))return;let p=Qa(e,l);if(!(p instanceof Oe))return;let f=(m,g)=>{let h=this._currentGuard(m,g);return h||this._publishViolation(m,g,l,"blocked"),h};c.set(l,p._pushGuard(f))};for(let l of u)d(l);if(r.paths==null){let l=Mt(e,(p,f,m)=>{if(p.kind==="added")if(p.nodeKind==="node")d(`${m}${p.name}`);else{let g=f._mounts.get(p.name);if(!(g instanceof z))return;let h=`${m}${p.name}::`,y=Tp(g);for(let b of y)d(b===""?`${m}${p.name}`:`${h}${b}`)}else if(p.kind==="removed")if(p.nodeKind==="node"){let g=`${m}${p.name}`,h=c.get(g);h!=null&&(h(),c.delete(g))}else{let g=`${m}${p.name}`,h=`${g}::`;for(let[y,b]of c)(y===g||y.startsWith(h))&&(b(),c.delete(y))}});this.addDisposer(l)}else{let l=e.topology.subscribe(p=>{for(let f of p){if(f[0]!==S)continue;let m=f[1];if(m.kind!=="removed"||m.nodeKind!=="node")continue;let g=c.get(m.name);g!=null&&(g(),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 p=l.path??"";if(!p||r.paths!=null&&!r.paths.includes(p))return;let f=l.actor??Qa(e,p)?.lastMutation?.actor;if(f==null)return;let m="write";this._currentGuard(f,m)||this._publishViolation(f,m,p,"observed")});this.addDisposer(()=>{d(),c.dispose()})}}_publishViolation(e,n,r,o){this.violations.publish({timestamp_ns:j(),wall_clock_ns:fe(),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 Xa(t,e,n={}){return new Xs(t,e,n)}function Za(t,e,n,r){return t.explain(e,n,{reactive:!0,...r})}function Kg(t,e={}){let n={format_version:1,timestamp_ns:j(),wall_clock_ns:fe(),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=qg(n);return{...n,fingerprint:r}}function Hg(t){return typeof t=="object"&&t!==null&&"subscribe"in t}function Qa(t,e){try{return t.node(e)}catch{return}}function Wg(t,e){try{return t.annotation(e)}catch{return}}function Tp(t){let e=t.describe({detail:"minimal"});return Object.keys(e.nodes)}function qg(t){return Ft(JSON.stringify(Ug(t)))}function Ug(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 ti={};we(ti,{demoShell:()=>ty});Ne();ne();ke();Ee();ne();function zg(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 kp=new Set(["\uFF0C","\uFF0E","\uFF01","\uFF1A","\uFF1B","\uFF1F","\u3001","\u3002","\u30FB","\uFF09","\u3015","\u3009","\u300B","\u300D","\u300F","\u3011"]),Jg=new Set([".",",","!","?",":",";",")","]","}","%",'"',"\u201D","\u2019","\xBB","\u203A","\u2026"]);function Yg(t){return t.replace(/[\t\n\r\f ]+/g," ").replace(/^ | $/g,"")}function Qg(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 p;l===" "?p="space":l==="\u200B"?p="zero-width-break":l==="\xAD"?p="soft-hyphen":l===`
176
+ `?p="hard-break":p="text",d!==null&&p===d?c+=l:(d!==null&&(i.push(c),a.push(d==="text"&&s),u.push(d)),c=l,d=p)}d!==null&&(i.push(c),a.push(d==="text"&&s),u.push(d)),n.push({texts:i,isWordLike:a,kinds:u})}return n}function Gt(t,e,n,r,o){let s=Yg(t);if(s.length===0)return[];let i=Qg(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=[],p=[],f=[];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&&p[p.length-1]==="text"&&b.length===1&&(Jg.has(b)||kp.has(b))){l[l.length-1]+=b;continue}if(b==="-"&&l.length>0&&p[p.length-1]==="text"&&f[f.length-1]){l[l.length-1]+=b;continue}l.push(b),p.push(v),f.push(T)}let m=r.get(e);m||(m=new Map,r.set(e,m));function g(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 h=[];for(let y=0;y<l.length;y++){let b=l[y],v=p[y];if(v!=="text"){h.push({text:b,width:v==="space"?g(" ")*b.length:0,kind:v,graphemeWidths:null});continue}if(zg(b)){let k="";for(let x of a.segment(b)){let R=x.segment;if(k.length>0&&kp.has(R)){k+=R;continue}if(k.length>0){let E=g(k);h.push({text:k,width:E,kind:"text",graphemeWidths:null})}k=R}if(k.length>0){let x=g(k);h.push({text:k,width:x,kind:"text",graphemeWidths:null})}continue}let T=g(b),w=null;if(f[y]&&b.length>1){let k=[];for(let x of a.segment(b))k.push(g(x.segment));k.length>1&&(w=k)}h.push({text:b,width:T,kind:"text",graphemeWidths:w})}return h}function Nn(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,p=-1,f=0,m=o.get(r);m||(m=new Map,o.set(r,m));let g=m.get("-");g===void 0&&(g=n.measureSegment("-",r).width,m.set("-",g));function h(w=d,k=l,x=i){let R="";for(let E=u;E<w;E++){let I=t[E];if(!(I.kind==="soft-hyphen"||I.kind==="hard-break"))if(E===u&&c>0&&I.graphemeWidths){let G=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(I.text)].map(A=>A.segment);R+=G.slice(c).join("")}else R+=I.text}if(k>0&&w<t.length){let E=t[w],O=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(E.text)].map(A=>A.segment),G=u===w?c:0;R+=O.slice(G,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,p=-1,f=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?h():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)&&(p=w+1,f=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,h(w+1,0,k.kind==="space"?i-x:i);continue}if(p>=0){h(p,0,f),w--;continue}if(x>e&&k.graphemeWidths){h(),T(w,0,k.graphemeWidths);continue}h(),w--;continue}i=R,d=w+1,l=0,y(k.kind)&&(p=w+1,f=k.kind==="space"?i-x:i)}return a&&h(),{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?(h(),v(w,R,E)):(i+=E,d=w,l=R+1)}a&&d===w&&l===x.length&&(d=w+1,l=0)}}function eu(t){return t==="space"||t==="zero-width-break"||t==="soft-hyphen"}var tu=null;function Xg(){return tu===null&&(tu=new Intl.Segmenter(void 0,{granularity:"grapheme"})),tu}function xp(t,e,n){if(e===0&&n<0)return t.text;let r=[...Xg().segment(t.text)].map(s=>s.segment),o=n<0?r.length:n;return r.slice(e,o).join("")}function Qt(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+=xp(u,n,-1):i+=u.text)}if(o>0&&r<t.length){let a=t[r];i+=xp(a,e===r?n:0,o)}return s&&(i+="-"),i}function Zg(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 nu(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=Zg(r),a=o,u=o===e.segmentIndex?s:0,c=0,d=a,l=0,p=!1,f=-1,m=0,g=0,h=!1,y=(w,k,x,R)=>{f=w,m=k,g=x,h=R==="soft-hyphen"},b=(w,k,x)=>{for(let R=k;R<x.length;R++){let E=x[R];if(!p){c=E,d=w,l=R+1,p=!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:Qt(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(p){let R=d>0&&t[d-1]?.kind==="soft-hyphen";return{text:Qt(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(!p){if(k>n&&w.graphemeWidths){if(b(o,0,w.graphemeWidths))return{text:Qt(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,p=!0,eu(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(eu(w.kind)){d=o+1,l=0;let E=w.kind==="soft-hyphen",I=w.kind==="space"?c:c+(E?i:0);return{text:Qt(t,a,u,d,l,E),width:I,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}}return f>=0?{text:Qt(t,a,u,f,m,h),width:g+(h?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:f,graphemeIndex:m}}:k>n&&w.graphemeWidths?{text:Qt(t,a,u,d,l,!1),width:c,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}:{text:Qt(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,eu(w.kind)&&y(o+1,0,w.kind==="space"?c-k:c,w.kind),o+=1}if(!p)return null;let v=d>0&&t[d-1]?.kind==="soft-hyphen";return{text:Qt(t,a,u,d,l,v),width:c+(v?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}}function ru(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 ei(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 p=c===i.startSegment?i.startGrapheme:0,f;if(c<i.endSegment)f=l.length;else if(c===i.endSegment&&i.endGrapheme>0)f=i.endGrapheme;else break;for(let m=p;m<f;m++){let g=d.graphemeWidths?d.graphemeWidths[m]:d.width/l.length;r.push({x:u,y:a,width:g,height:n,line:s}),u+=g}}}return r}function ey(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,g){if(m===null||g===null)return m===g;if(m.length!==g.length)return!1;for(let h=0;h<m.length;h++)if(m[h]!==g[h])return!1;return!0}let d=H([s,i],(m,g,h)=>{let y=m[0],b=y!=null&&y.length>0?y.at(-1):h.prevData[0],v=m[1],T=v!=null&&v.length>0?v.at(-1):h.prevData[1],w=j(),k={hits:0,misses:0},x=Gt(b,T,e,o,k),R=j()-w,E=k.hits+k.misses,I=E===0?1:k.hits/E,O=d.meta;O&&(pt(O["cache-hit-rate"],I),pt(O["segment-count"],x.length),pt(O["layout-time-ns"],R)),g.emit(x);let G=()=>{o.clear(),e.clearCache?.()};return{deactivate:G,invalidate:G}},{name:"segments",describeKind:"derived",meta:{"cache-hit-rate":0,"segment-count":0,"layout-time-ns":0},equals:(m,g)=>{let h=m,y=g;if(h==null||y==null)return h===y;if(h.length!==y.length)return!1;for(let b=0;b<h.length;b++){let v=h[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=_([d,u,i],([m,g,h])=>Nn(m,g,e,h,o),{name:"line-breaks",equals:(m,g)=>{let h=m,y=g;if(h==null||y==null)return h===y;if(h.lineCount!==y.lineCount)return!1;for(let b=0;b<h.lines.length;b++){let v=h.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}}),p=_([l,a],([m,g])=>m.lineCount*g,{name:"height"}),f=_([l,d,a],([m,g,h])=>ei(m,g,h),{name:"char-positions",equals:(m,g)=>{let h=m,y=g;if(h==null||y==null)return h===y;if(h.length!==y.length)return!1;for(let b=0;b<h.length;b++)if(h[b].x!==y[b].x||h[b].y!==y[b].y||h[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(p,{name:"height"}),r.add(f,{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:p,charPositions:f}}function po(t){return Math.max(0,Math.min(1,t))}function ty(t){let e=po(t?.mainRatio??.65),n=po(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"}),p=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(p,{name:"viewport/width"});let f=_([c,p,l],([D,P,L])=>{let V=D,K=P,Z=L;return Z==="main"?K:Z==="graph"||Z==="code"?0:Math.round(K*V)},{name:"pane/main-width"}),m=_([f,p,l],([D,P,L])=>{let V=L,K=P;return V==="main"?0:V==="graph"||V==="code"?K:K-D},{name:"pane/side-width"}),g=_([d,l],([D,P])=>{let L=P;return L==="graph"?1:L==="code"||L==="main"?0:po(D)},{name:"pane/graph-height-ratio"}),h=_([g,l],([D,P])=>{let L=P;return L==="code"?1:L==="graph"||L==="main"?0:1-D},{name:"pane/code-height-ratio"});u.add(f,{name:"pane/main-width"}),u.add(m,{name:"pane/side-width"}),u.add(g,{name:"pane/graph-height-ratio"}),u.add(h,{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=_([y,b],([D,P])=>{let L=D;return L?L.describe({format:"mermaid"}):""},{name:"graph/mermaid"}),T=_([y,b],([D,P])=>{let L=D;if(!L)return null;let{expand:V,...K}=L.describe({detail:"standard"});return K},{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=_([w],([D])=>{let P=D;if(!P)return null;let L=o.get(P.id);return L?L.codeLine:null},{name:"highlight/code-scroll"}),x=_([w],([D])=>{let P=D;if(!P)return null;let L=o.get(P.id);return L?L.visualSelector:null},{name:"highlight/visual"}),R=_([w],([D])=>{let P=D;return P?P.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 D=a.codeScroll,P=ce([k],([L])=>{D(L)});u.add(P,{name:"highlight/apply-code-scroll"})}if(a?.visual){let D=a.visual,P=ce([x],([L])=>{D(L)});u.add(P,{name:"highlight/apply-visual"})}if(a?.graph){let D=a.graph,P=ce([R],([L])=>{D(L)});u.add(P,{name:"highlight/apply-graph"})}let E=N(null,{name:"inspect/selected-node"});u.add(E,{name:"inspect/selected-node"});let I=_t("standard"),O=_([E,y,b],([D,P,L])=>{let V=P,K=D;if(!V||!K)return null;try{let Z=V.resolve(K),$=Mr(Z,I);return{path:K,...$,value:Z.cache}}catch{return null}},{name:"inspect/node-detail"}),G=_([y,b],([D,P])=>{let L=D;return L?L.trace():[]},{name:"inspect/trace-log"});u.add(O,{name:"inspect/node-detail"}),u.add(G,{name:"inspect/trace-log"});let A=N(!1,{name:"meta/debug"});u.add(A,{name:"meta/debug"});let F=_([A,b],([D,P])=>D?u.describe({format:"mermaid"}):"",{name:"meta/shell-mermaid"});u.add(F,{name:"meta/shell-mermaid"});let q=N("",{name:"layout/code-text"});if(u.add(q,{name:"layout/code-text"}),s){let D=new Map,P=_([T],([K])=>{let Z=K;if(!Z)return new Map;let $=new Map;for(let[J]of Object.entries(Z.nodes)){let le=Gt(J,i,s,D),se=Nn(le,1/0,s,i,D),Te=se.lines.reduce((me,ee)=>Math.max(me,ee.width),0),re=se.lineCount*20;$.set(J,{width:Te,height:re})}return $},{name:"layout/graph-labels",equals:(K,Z)=>{if(K===Z)return!0;let $=K,J=Z;if($.size!==J.size)return!1;for(let[le,se]of $){let Te=J.get(le);if(!Te||Te.width!==se.width||Te.height!==se.height)return!1}return!0}}),L=_([q,m],([K,Z])=>{let $=K;if(!$)return{lineCount:0,lines:[]};let J=Gt($,i,s,D),le=Z-40;return Nn(J,Math.max(100,le),s,i,D)},{name:"layout/code-lines"}),V=_([P],([K])=>{let Z=K;if(Z.size===0)return 200;let $=0;for(let{width:J}of Z.values())J>$&&($=J);return Math.max(200,Math.round($+80))},{name:"layout/side-width-hint"});u.add(P,{name:"layout/graph-labels"}),u.add(L,{name:"layout/code-lines"}),u.add(V,{name:"layout/side-width-hint"})}let Y=0;return{graph:u,setMainRatio(D){u.set("pane/main-ratio",po(D))},setSideSplit(D){u.set("pane/side-split",po(D))},setFullscreen(D){u.set("pane/fullscreen",D)},setViewportWidth(D){u.set("viewport/width",Math.max(0,D))},setHoverTarget(D){u.set("hover/target",D)},setDemoGraph(D){u.set("demo/graph-ref",D)},bumpGraphTick(){u.set("demo/graph-tick",++Y)},selectNode(D){u.set("inspect/selected-node",D)},setMetaDebug(D){u.set("meta/debug",D)},setCodeText(D){u.set("layout/code-text",D)},batch(D){Q(D)},destroy(){u.destroy()}}}var ni={};we(ni,{contentModerationGraph:()=>oy,dataQualityGraph:()=>sy,issueTrackerGraph:()=>ry,observabilityGraph:()=>ny});Ne();ne();function Le(t,e){return qe("domain_template",t,e)}function ny(t,e){let n=new z(t,e);n.add(e.source,{name:"source"});let r=[{name:"errors",classify:T=>ou(T,"error")},{name:"traces",classify:T=>ou(T,"trace")},{name:"metrics",classify:T=>ou(T,"metric")}],o=e.branches??r,s=o.map(T=>({name:T.name,classify:T.classify})),i=Jr("stratify",e.source,s);n.mount("stratify",i);let a=o.map(T=>{try{let w=n.resolve(`stratify::branch/${T.name}`);return _([w],([k])=>k,{initial:null})}catch{return N(null)}}),u=e.correlate??(T=>T),c=_(a,T=>u(T),{meta:Le("observability",{stage:"correlate"})});n.add(c,{name:"correlate"});let d=e.sloCheck??(()=>({pass:!0})),l=_([c],T=>T[0],{meta:Le("observability",{stage:"slo_value"})}),p=_([l],T=>d(T[0]),{meta:Le("observability",{stage:"slo_verified"})});n.add(l,{name:"slo_value"}),n.add(p,{name:"slo_verified"});let f=e.weights??o.map(()=>1),m=a.map(T=>_([T],w=>w[0]!=null?1:0)),g=f.map(T=>N(T));for(let T=0;T<m.length;T++)n.add(m[T],{name:`__signal_${T}`}),n.add(g[T],{name:`__weight_${T}`});let h=ao(m,g);n.add(h,{name:"alerts"});let y=_([h,p],T=>({scored:T[0],slo:T[1]}),{meta:Le("observability",{stage:"output"})});n.add(y,{name:"output"});let b=N(null,{meta:Le("observability",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=_([p],T=>{let w=T[0];return w&&w.pass===!1?w:null},{meta:Le("observability",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),Yt(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??5}),n}function ry(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=_([e.source],T=>s(T[0]),{meta:Le("issue_tracker",{stage:"extract"})});n.add(i,{name:"extract"});let a=e.verify??(()=>({valid:!0})),u=_([i],T=>{let w=T[0];return{issue:w,verification:a(w)}},{meta:Le("issue_tracker",{stage:"verify"})});n.add(u,{name:"verify"});let c=N([],{meta:Le("issue_tracker",{stage:"known_patterns"})});n.add(c,{name:"known_patterns"});let d=e.detectRegression??(()=>({regression:!1})),l=_([i,c],T=>{let w=T[0],k=T[1];return{issue:w,regression:d(w,k)}},{meta:Le("issue_tracker",{stage:"regression"})});n.add(l,{name:"regression"});let p=_([i],T=>T[0]?.severity??0),f=_([l],T=>T[0]?.regression?2:0);n.add(p,{name:"__severity_signal"}),n.add(f,{name:"__regression_signal"});let m=N(1),g=N(1.5);n.add(m,{name:"__severity_weight"}),n.add(g,{name:"__regression_weight"});let h=ao([p,f],[m,g]);n.add(h,{name:"priority"});let y=_([u,l,h],T=>({verified:T[0],regression:T[1],priority:T[2]}),{meta:Le("issue_tracker",{stage:"output"})});n.add(y,{name:"output"});let b=N(null,{meta:Le("issue_tracker",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=_([u],T=>{let w=T[0];if(w){let k=w.verification;if(k&&k.valid===!1)return w}return null},{meta:Le("issue_tracker",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),Yt(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??3}),n}function oy(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=_([e.source],v=>o(v[0]),{meta:Le("content_moderation",{stage:"classify"})});n.add(s,{name:"classify"});let i=Jr("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=We([],{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=ce([u],v=>{let T=v[0];T&&a.append(T)});n.add(c,{name:"__review_accumulator"}),n.addDisposer(oe(c));let d=N({},{meta:Le("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],p=_([s],v=>v[0]?.confidence??0),f=_([s],v=>{let T=v[0];return T?T.label==="block"?l[2]:T.label==="review"?l[1]:l[0]:0});n.add(p,{name:"__confidence_signal"}),n.add(f,{name:"__severity_signal"});let m=N(1),g=N(1);n.add(m,{name:"__w_confidence"}),n.add(g,{name:"__w_severity"});let h=ao([p,f],[m,g]);n.add(h,{name:"priority"});let y=_([s,h],v=>({classification:v[0],priority:v[1]}),{meta:Le("content_moderation",{stage:"output"})});n.add(y,{name:"output"});let b=_([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:Le("content_moderation",{stage:"feedback_condition"})});return n.add(b,{name:"feedback_condition"}),Yt(n,"feedback_condition","policy",{maxIterations:e.maxFeedbackIterations??5}),n}function sy(t,e){let n=new z(t,e);n.add(e.source,{name:"source"});let r=e.validate??(h=>({valid:!0,errors:[],record:h})),o=_([e.source],h=>h[0]!=null?r(h[0]):void 0,{meta:Le("data_quality",{stage:"validate"})});n.add(o,{name:"validate"});let s=e.detectAnomaly??(h=>({anomaly:!1,score:0,record:h})),i=_([e.source],h=>h[0]!=null?s(h[0]):void 0,{meta:Le("data_quality",{stage:"anomaly"})});n.add(i,{name:"anomaly"});let a=N(null,{meta:Le("data_quality",{stage:"baseline",description:"Rolling baseline for drift detection"})});n.add(a,{name:"baseline"});let u=ce([o],h=>{let y=h[0];y?.valid&&Q(()=>{a.emit(y.record)})});n.add(u,{name:"__baseline_updater"}),oe(u);let c=e.detectDrift??(()=>({drift:!1})),d=_([e.source,a],h=>c(h[0],h[1]),{meta:Le("data_quality",{stage:"drift"})});n.add(d,{name:"drift"});let l=e.suggest??(()=>null),p=_([o,i],h=>l({validation:h[0],anomaly:h[1]}),{meta:Le("data_quality",{stage:"remediate"})});n.add(p,{name:"remediate"});let f=_([o,i,d,p],h=>({validation:h[0],anomaly:h[1],drift:h[2],remediation:h[3]}),{meta:Le("data_quality",{stage:"output"})});n.add(f,{name:"output"});let m=N([],{meta:Le("data_quality",{stage:"validation_rules"})});n.add(m,{name:"validation_rules"});let g=_([i],h=>{let y=h[0];return y?.anomaly?y:null},{meta:Le("data_quality",{stage:"feedback_condition"})});return n.add(g,{name:"feedback_condition"}),Yt(n,"feedback_condition","validation_rules",{maxIterations:e.maxFeedbackIterations??3}),n}function ou(t,e){if(t==null||typeof t!="object")return!1;let n=t;return n.type===e||n.kind===e}var oi={};we(oi,{GuardedExecutionGraph:()=>ri,guardedExecution:()=>iy});var ri=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=Xa(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 iy(t,e){return new ri(t,e)}var ai={};we(ai,{DEFAULT_DECAY_RATE:()=>au,DEFAULT_QUEUE_CONFIGS:()=>uu,DEFAULT_SEVERITY_WEIGHTS:()=>iu,HarnessGraph:()=>si,QUEUE_NAMES:()=>Xt,affectedTaskFilter:()=>ly,beforeAfterCompare:()=>dy,codeChangeBridge:()=>py,createIntakeBridge:()=>ay,defaultErrorClassifier:()=>su,defaultLlmExecutor:()=>Rp,defaultLlmVerifier:()=>Sp,evalIntakeBridge:()=>uy,evalSource:()=>cy,evalVerifier:()=>yy,harnessLoop:()=>ky,harnessProfile:()=>xy,harnessTrace:()=>Ay,notifyEffect:()=>fy,priorityScore:()=>by,refineExecutor:()=>Oy,strategyKey:()=>fo,strategyModel:()=>cu});ne();be();function ay(t,e,n,r){return ce([t],([o])=>{if(o==null)return;let s=n(o);for(let i of s)e.publish(i)},{name:r?.name??"intake-bridge"})}function uy(t,e,n){let r=n?.defaultSeverity??"medium";return ce([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 cy(t,e){return ve(t,()=>U(e()))}function dy(t,e){return _([t,e],([n,r])=>{let o=n,s=r,i=new Map(o.tasks.map(p=>[p.task_id,p])),a=new Map(s.tasks.map(p=>[p.task_id,p])),u=new Set([...i.keys(),...a.keys()]),c=[],d=[],l=[];for(let p of u){let f=i.get(p),m=a.get(p),g=f?.valid??!1,h=m?.valid??!1,y=f?.judge_scores?f.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:p,before:g,after:h,scoreDiff:v}),g&&!h&&d.push(p),!g&&h&&l.push(p)}return{newFailures:d,resolved:l,taskDeltas:c,overallImproved:l.length>d.length}},{name:"eval-delta"})}function ly(t,e){let n=e==null?null:Array.isArray(e)?N(e):e,r=[t];return n&&r.push(n),_(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 py(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 ce([t],([a])=>{if(a!=null)for(let u of i(a))e.publish(u)},{name:r?.name??"code-change-bridge"})}function fy(t,e,n){return ce([t.latest],([r])=>{r!=null&&e(r)},{name:n?.name??"notify-effect"})}ne();function my(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 hy(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 gy(t){return t.artifact}function yy(t){let e=t.name??"eval-verifier",n=t.threshold??.5,r=t.toOutput??hy,o=t.extractArtifact??gy;return s=>{let i=ft(s,u=>u!=null&&u[0]!=null&&u[1]!=null),a=ve(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`}),p=N(t.datasetFor(c),{name:`${e}/dataset`}),f=t.evaluator(l,p);return _([f],([m])=>{let g=m;if(g==null)return null;let h=my(g),y=g.filter(b=>b.score>=n).length;return r({scores:g,meanScore:h,passCount:y,total:g.length,threshold:n})},{name:`${e}/output`})},{name:e});return ft(a,u=>u!=null)}}Ee();ne();ke();ne();var Xt=["auto-fix","needs-decision","investigation","backlog"];function fo(t,e){return`${t}\u2192${e}`}function su(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 iu={critical:100,high:70,medium:40,low:10},au=Math.LN2/(168*3600),uu={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1,startOpen:!1}};function cu(){let t=Ye({name:"strategy-entries"}),e=_([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 p=c.get(d);if(!p||l.attempts!==p.attempts||l.successes!==p.successes)return!1}return!0}});function n(i,a,u){let c=fo(i,a),d=t.get(c),l=(d?.attempts??0)+1,p=(d?.successes??0)+(u?1:0);t.set(c,{rootCause:i,intervention:a,attempts:l,successes:p,successRate:p/l})}function r(i,a){return t.get(fo(i,a))}let o=e.subscribe(()=>{});function s(){o()}return{node:e,record:n,lookup:r,dispose:s}}function by(t,e,n,r,o){let s={...iu,...o?.severityWeights},i=o?.decayRate??au,a=o?.effectivenessThreshold??.7,u=o?.effectivenessBoost??15,c=[t,e,n];return r&&c.push(r),_(c,d=>{let l=d[0],p=d[1],f=d[2],m=r?d[3]:0,g=s[l.severity??"medium"],h=(j()-f)/1e9,y=Pt(g,h,i,0),b=fo(l.rootCause,l.intervention),v=p.get(b);return v&&v.successRate>=a&&(y+=u),y+=m*20,y},{name:"priority-score"})}var vy=`You are a triage classifier for a reactive collaboration harness.
196
177
 
197
178
  Given an intake item, classify it and output JSON:
198
179
  {
@@ -207,7 +188,7 @@ Strategy model (past effectiveness):
207
188
  {{strategy}}
208
189
 
209
190
  Intake item:
210
- {{item}}`,ny=`You are an implementation agent.
191
+ {{item}}`,Ty=`You are an implementation agent.
211
192
 
212
193
  Given a triaged issue with root cause and intervention type, produce a fix.
213
194
 
@@ -218,7 +199,7 @@ Output JSON:
218
199
  {
219
200
  "outcome": "success" | "failure" | "partial",
220
201
  "detail": "<description of what was done or what failed>"
221
- }`,ry=`You are a QA reviewer.
202
+ }`,wy=`You are a QA reviewer.
222
203
 
223
204
  Given an execution result, verify whether the fix is correct.
224
205
 
@@ -233,11 +214,11 @@ Output JSON:
233
214
  "verified": true/false,
234
215
  "findings": ["<finding1>", ...],
235
216
  "errorClass": "self-correctable" | "structural" // only if verified=false
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:
217
+ }`;function Rp(t,e){let n=e??(r=>Ty.replace("{{item}}",JSON.stringify(r)));return r=>Rn(t,[r],n,{name:"execute",format:"json"})}function Sp(t,e){let n=e??(r=>{let[o,s]=r;return wy.replace("{{execution}}",JSON.stringify(o)).replace("{{item}}",JSON.stringify(s))});return r=>Rn(t,[r],n,{name:"verify",format:"json"})}var si=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 ky(t,e){let n=e.adapter,r=e.maxRetries??2,o=e.retainedLimit??1e3,s=e.errorClassifier??su,i=new Map;for(let L of Xt)i.set(L,{...uu[L],...e.queues?.[L]});let a=new ut("intake",{retainedLimit:o}),u=cu(),c=At(a.latest,u.node),d=Rn(n,[c],e.triagePrompt??(L=>{let[V,K]=L;return V?vy.replace("{{strategy}}",JSON.stringify(Array.from(K.entries()))).replace("{{item}}",JSON.stringify(V)):""}),{name:"triage",format:"json"}),l=new Map;for(let L of Xt)l.set(L,new ut(`queue/${L}`,{retainedLimit:o}));let p=At(d,c),m=ce([p],([L])=>{if(L==null)return;let[V,K]=L;if(!V?.route)return;let Z=K?.[0],$={...V,...Z},J=l.get($.route);J&&J.publish($)}).subscribe(()=>{}),g=new z("gates"),h=new Map;for(let L of Xt){let V=i.get(L),K=l.get(L);if(V.gated){g.add(K.latest,{name:`${L}/source`});let Z=eo(g,`${L}/gate`,`${L}/source`,{maxPending:V.maxPending,startOpen:V.startOpen});h.set(L,Z)}}let y=new ut("retry-input",{retainedLimit:o}),b=[];for(let L of Xt)i.get(L).gated&&h.has(L)?b.push(h.get(L).node):b.push(l.get(L).latest);b.push(y.latest);let v=wt(...b),w=(e.executor??Rp(n,e.executePrompt))(v),k=At(w,v),x=new ut("verify-results",{retainedLimit:o}),E=(e.verifier??Sp(n,e.verifyPrompt))(k),I=At(E,k),O=e.maxReingestions??1,G=Math.min(e.maxTotalRetries??r*10,100),A=Math.min(e.maxTotalReingestions??O*10,100),F=N(0),q=N(0),D=H([I],(L,V)=>{let K=L[0];if(K==null||K.length===0)return;let Z=K[K.length-1];if(Z==null)return;let[$,J]=Z,[le,se]=J??[null,null];if(!$||!se)return;let Te={item:se,outcome:le?.outcome??"failure",detail:le?.detail??"unknown",artifact:le?.artifact},re={item:se,execution:Te,verified:$.verified,findings:$.findings??[],errorClass:$.errorClass};if(re.verified){u.record(se.rootCause,se.intervention,!0),x.publish(re);return}let me=re.errorClass??s({item:se,outcome:"failure",detail:re.findings.join("; ")}),ee=se._retries??0;if(me==="self-correctable"&&ee<r&&Lr(F,G)){let ae=ta(se),xe={...se,_retries:ee+1,summary:`[RETRY ${ee+1}/${r}] ${ae} \u2014 Previous attempt failed: ${re.findings.join("; ")}`,relatedTo:[ae]};y.publish(xe)}else{u.record(se.rootCause,se.intervention,!1),x.publish(re);let ae=ta(se),xe=se._reingestions??0;xe<O&&Lr(q,A)&&a.publish({source:"eval",summary:`Verification failed for: ${ae}`,evidence:re.findings.join(`
218
+ `),affectsAreas:se.affectsAreas,affectsEvalTasks:se.affectsEvalTasks,severity:"high",relatedTo:[ae],_reingestions:xe+1})}}).subscribe(()=>{}),P=new si(t,a,l,h,u,x,F,q);P.addDisposer(m),P.addDisposer(D),P.addDisposer(u.dispose),P.add(d,{name:"triage"}),P.add(w,{name:"execute"}),P.add(E,{name:"verify"}),P.add(u.node,{name:"strategy"}),P.mount("intake",a);for(let[L,V]of l)P.mount(`queue/${L}`,V);return P.mount("gates",g),P.mount("retry-input",y),P.mount("verify-results",x),P}function xy(t,e){let n=mn(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}}ne();var ii={};we(ii,{blindVariation:()=>Sy,errorCritique:()=>_y,refineLoop:()=>lu});Ne();ke();ie();Ee();ne();function Ry(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=du(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 du(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 lu(t,e,n,r){let o=r.name??"refine-loop",s=new z(o,r.graph),i=Ry(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 p=N("running",{name:"status"});s.add(p,{name:"status"});let f=N([],{name:"history",equals:()=>!1});s.add(f,{name:"history"});let m=N(null,{name:"best"});s.add(m,{name:"best"});let g=N(Number.NEGATIVE_INFINITY,{name:"score"});s.add(g,{name:"score"});let h=N(0,{name:"budget-used"});s.add(h,{name:"budget-used"});let y=Ka("stages");s.mount("stages",y);let b=y.topic("generate"),v=y.topic("evaluate"),T=y.topic("analyze"),w=y.topic("decide"),k=n,x=null,R=[];s.addDisposer(u.subscribe(ee=>{for(let ae of ee)ae[0]===S&&(k=ae[1])})),s.addDisposer(c.subscribe(ee=>{for(let ae of ee)ae[0]===S&&(x=ae[1])})),s.addDisposer(d.subscribe(ee=>{for(let ae of ee)ae[0]===S&&(R=ae[1])}));let E=ve(a,ee=>{let ae=k,xe=ee===0||x==null;return H([],(Ae,Ge)=>{let rt=!1;try{let Be=xe?ae.seed(t):ae.generate(x,R);if(Be instanceof Promise)return Be.then(X=>{rt||Ge.emit(X)},X=>{rt||Ge.down([[M,X]])}),()=>{rt=!0};Ge.emit(Be)}catch(Be){rt=!0,Ge.down([[M,Be]])}},{describeKind:"producer"})},{name:"candidates"});s.add(E,{name:"candidates"});let I=ce([E],(ee,ae,xe)=>{let Ae=xe.terminalDeps[0];Ae!==void 0&&Ae!==!0&&p.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});s.add(I,{name:"error-watcher"}),s.addDisposer(I.subscribe(()=>{}));let O=_([E,a],([ee,ae])=>({iteration:ae,candidates:ee,timestamp_ns:j()}),{name:"generate-event"});s.add(O,{name:"generate-event"}),s.addDisposer(O.subscribe(()=>{}));let G=ce([O],([ee])=>{b.publish(ee)},{name:"generate-publish"});s.add(G,{name:"generate-publish"}),s.addDisposer(G.subscribe(()=>{}));let A=ce([E],([ee])=>{d.emit(ee)},{name:"generate-mirror"});s.add(A,{name:"generate-mirror"}),s.addDisposer(A.subscribe(()=>{}));let F=e(E,i);s.add(F,{name:"scores"});let q=_([F,E,a],([ee,ae,xe])=>({iteration:xe,candidates:ae,scores:ee,timestamp_ns:j()}),{name:"evaluate-event"});s.add(q,{name:"evaluate-event"}),s.addDisposer(q.subscribe(()=>{}));let Y=ce([q],([ee])=>{v.publish(ee)},{name:"evaluate-publish"});s.add(Y,{name:"evaluate-publish"}),s.addDisposer(Y.subscribe(()=>{}));let D=_([F,E],([ee,ae])=>k.analyze(ee,ae),{name:"feedback"});s.add(D,{name:"feedback"});let P=_([D,E,a],([ee,ae,xe])=>({iteration:xe,candidates:ae,feedback:ee,timestamp_ns:j()}),{name:"analyze-event"});s.add(P,{name:"analyze-event"}),s.addDisposer(P.subscribe(()=>{}));let L=ce([P],([ee])=>{T.publish(ee)},{name:"analyze-publish"});s.add(L,{name:"analyze-publish"}),s.addDisposer(L.subscribe(()=>{}));let V=_([f],([ee])=>{let ae=ee;if(r.patience==null||ae.length<=r.patience)return!1;let xe=ae.slice(-(r.patience+1)),Ae=xe[0].bestScore;return xe.slice(1).every(Ge=>Ge.bestScore<=Ae)},{name:"patience-check"});s.add(V,{name:"patience-check"});let K=_([g],([ee])=>r.minScore!=null&&ee>=r.minScore,{name:"min-score-check"});s.add(K,{name:"min-score-check"});let Z=_([f],([ee])=>{let ae=ee;if(r.minDelta==null||ae.length<2)return!1;let xe=ae[ae.length-2].bestScore,Ae=ae[ae.length-1].bestScore;return Math.abs(Ae-xe)<r.minDelta},{name:"min-delta-check"});s.add(Z,{name:"min-delta-check"});let $=_([h],([ee])=>r.maxEvaluations!=null&&ee>=r.maxEvaluations,{name:"max-evaluations-check"});s.add($,{name:"max-evaluations-check"});let J=_([a],([ee])=>r.maxIterations!=null&&ee>=r.maxIterations,{name:"max-iterations-check"});s.add(J,{name:"max-iterations-check"});let le=_([h],([ee])=>r.budget!=null&&ee>=r.budget,{name:"budget-exhausted-check"});s.add(le,{name:"budget-exhausted-check"}),s.addDisposer(V.subscribe(()=>{})),s.addDisposer(K.subscribe(()=>{})),s.addDisposer(Z.subscribe(()=>{})),s.addDisposer($.subscribe(()=>{})),s.addDisposer(J.subscribe(()=>{})),s.addDisposer(le.subscribe(()=>{}));let se=_([V,K,Z,$,J],([ee,ae,xe,Ae,Ge])=>ee?{converged:!0,reason:"patience"}:ae?{converged:!0,reason:"min-score"}:xe?{converged:!0,reason:"min-delta"}:Ae?{converged:!0,reason:"max-evaluations"}:Ge?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});s.add(se,{name:"converged"}),s.addDisposer(se.subscribe(()=>{}));let Te=-1,re=ce([D,F,E],([ee,ae,xe])=>{let Ae=a.cache,Ge=ee,rt=xe,Be=ae;if(Ae<=Te)return;Te=Ae;let{best:X,bestScore:ye}=Np(rt,Be),Se=f.cache,Me={n:Ae,candidates:rt,scores:Be,feedback:Ge,best:X,bestScore:ye,timestamp_ns:j()},_e=[...Se,Me],Xe=h.cache+rt.length,he="continue",ge,yo=r.budget!=null&&Xe>=r.budget,ar=l.cache;if(yo)he="budget",ge="budget";else if(r.minScore!=null&&Ge.score>=r.minScore)he="converged",ge="min-score";else if(r.maxIterations!=null&&Ae>=r.maxIterations)he="converged",ge="max-iterations";else if(r.maxEvaluations!=null&&Xe>=r.maxEvaluations)he="converged",ge="max-evaluations";else if(r.minDelta!=null&&_e.length>=2){let bo=_e[_e.length-2].bestScore,Ri=_e[_e.length-1].bestScore;Math.abs(Ri-bo)<r.minDelta&&(he="converged",ge="min-delta")}else if(r.patience!=null&&_e.length>r.patience){let bo=_e.slice(-(r.patience+1)),Ri=bo[0].bestScore;bo.slice(1).every($p=>$p.bestScore<=Ri)&&(he="converged",ge="patience")}he==="continue"&&ar&&(he="paused"),Q(()=>{m.emit(X),g.emit(Ge.score),f.emit(_e),h.emit(Xe),c.emit(Ge),w.publish({iteration:Ae,decision:he,reason:ge,timestamp_ns:j()}),he==="continue"?a.emit(Ae+1):p.emit(he==="converged"?"converged":he==="budget"?"budget":"paused")})},{name:"decide-bridge"});return s.add(re,{name:"decide-bridge"}),s.addDisposer(re.subscribe(()=>{})),Object.assign(s,{best:m,score:g,status:p,history:f,strategy:u,iteration:a,generate:b,evaluate:v,analyze:T,decide:w,setStrategy(ee){u.emit(ee)},pause(){l.emit(!0)},resume(){p.cache==="paused"&&Q(()=>{l.emit(!1),p.emit("running"),a.emit(a.cache+1)})}})}function Sy(t){let e=t.width??4;return{name:t.name??"blindVariation",seed(r){return[r]},analyze(r,o){let s=du(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 Ny(t){return typeof t=="object"&&t!==null&&t.kind==="errorCritique"}function Ey(t,e){return t.length===0?`No task scored below the batch mean (${e.score.toFixed(3)}). Reinforce the current direction.`:`Failures below threshold:
238
219
  ${t.map(r=>{let o=r.error!=null?` | error: ${r.error}`:"";return`- ${r.taskId} (score=${r.score.toFixed(3)})${o}`}).join(`
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:
220
+ `)}`}function _y(t){let e=t.width??4,n=t.name??"errorCritique",r=t.maxFailureSamples??5,o=t.formatCritique??Ey;return{name:n,seed(s){return[s]},analyze(s,i){let a=du(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),p=l.slice(0,r),{best:f,bestScore:m}=Np(i,s),g={summary:"",score:a,weakTasks:p.map(v=>v.taskId)},h=o(p,g),y={kind:"errorCritique",best:f,failures:p,critiqueText:h},b=l.length>p.length?` (top ${p.length} retained)`:"";return{summary:`errorCritique iteration: mean=${a.toFixed(3)}, failures=${l.length}${b}/${s.length}, bestScore=${m.toFixed(3)}`,critique:y,weakTasks:p.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=Ny(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,f={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(f)));let m=[];for(let g=0;g<e;g++)m.push(await t.teacher(f));return m}finally{if(t.tokens!=null&&l>0){let m=t.tokens.cache??0;t.tokens.emit(m+l)}}}}}function My(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 Oy(t){let e=t.name??"refine-executor",n=t.toOutput??My;return r=>{let o=ft(r,i=>i!=null),s=ve(o,i=>{let a=lu(t.seedFrom(i),t.evaluator,t.strategy,{...t.refine,dataset:t.datasetFor(i),name:`${e}/inner`});return _([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 ft(s,i=>i!=null)}}ke();function Cy(t){let e={"intake::latest":"INTAKE",triage:"TRIAGE",execute:"EXECUTE","verify-results::latest":"VERIFY",strategy:"STRATEGY"};for(let n of Xt)e[`queue/${n}::latest`]="QUEUE";for(let[n]of t.gates)e[`gates::${n}/gate`]="GATE";return e}function Ay(t,e){let n=e?.logger===null?null:e?.logger??console.log,r=e?.detail??"summary",o=j(),s=[],i=[],a=Cy(t);function u(){return(j()-o)/1e9}function c(d,l,p){let f={elapsed:u(),stage:d,type:l};r!=="summary"&&(f.summary=Ly(p)),r==="full"&&(f.data=p),i.push(f)}for(let[d,l]of Object.entries(a))try{let p=t.observe(d,{format:"stage-log",stageLabels:a,logger:n?f=>n(f):()=>{},includeTypes:["data","error","complete"]});p.onEvent(f=>{f.type==="data"?c(l,"data",f.data):f.type==="error"?c(l,"error",f.data):f.type==="complete"&&c(l,"complete",void 0)}),s.push(p)}catch(p){let f=p instanceof Error?p.message:String(p);c(l,"error",`observe-unavailable: ${d} \u2014 ${f}`),n&&n(`[${u().toFixed(3)}s] ${l.padEnd(9)} \u2717 observe-unavailable: ${f}`)}return{get events(){return i},dispose(){for(let d of s)d.dispose();s.length=0}}}function Ly(t){if(t==null)return"null";if(typeof t=="string")return Ep(t,80);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return Ep(e,120)}catch{return String(t)}}function Ep(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}var di={};we(di,{JobFlowGraph:()=>ci,JobQueueGraph:()=>ui,jobFlow:()=>Dy,jobQueue:()=>Mp});Ee();var Iy=2147483647;function _p(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function pu(t,e){return qe("job_queue",t,e)}var ui=class extends z{_pending;_jobs;_seq=0;pending;jobs;depth;constructor(e,n={}){super(e,n.graph),this._pending=ks([],{name:"pending"}),this._jobs=Ye({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=_([this.pending],([r])=>r.length,{name:"depth",describeKind:"derived",meta:pu("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=_p(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)}},ci=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=Mp(`${e}-${i}`);this._queues.set(i,a),this.mount(i,a)}this._completed=We([],{name:"completed"}),this.completed=this._completed.entries,this.add(this.completed,{name:"completed"}),this.completedCount=_([this.completed],([i])=>i.length,{name:"completedCount",describeKind:"derived",meta:pu("job_flow_completed_count"),initial:0}),this.add(this.completedCount,{name:"completedCount"}),this.addDisposer(oe(this.completedCount));let s=Math.max(1,_p(n.maxPerPump??Iy,"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=H([u.pending],()=>{let l=0;for(;l<s;){let p=u.claim(1);if(p.length===0)break;let f=p[0];if(!f)break;c?c.enqueue(f.payload,{metadata:{...f.metadata,job_flow_from:a}}):this._completed.append(f),u.ack(f.id),l+=1}},{name:`pump_${a}`,describeKind:"effect",meta:pu("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 Mp(t,e){return new ui(t,e)}function Dy(t,e){return new ci(t,e)}var pi={};we(pi,{LensGraph:()=>li,graphLens:()=>By,watchTopologyTree:()=>Mt});ke();ne();function Op(t){return qe("lens",t)}function Py(t){let e=Object.keys(t.nodes),n=new Map,r=new Map;for(let g of e){let h=t.nodes[g]?.deps??[];n.set(g,h);for(let y of h)r.has(y)||r.set(y,new Set),r.get(y).add(g)}let o=[],s=[];for(let g of e)(n.get(g)??[]).length===0&&o.push(g),r.has(g)||s.push(g);o.sort(),s.sort();let i=t.edges.length,a=0,u=1,c=2,d=new Map;for(let g of e)d.set(g,a);let l=!1,p=new Map,f=g=>{let h=d.get(g)??a;if(h===u)return l=!0,0;if(h===c)return p.get(g)??0;d.set(g,u);let y=0,b=r.get(g);if(b!=null)for(let v of b){let T=f(v);T+1>y&&(y=T+1)}return d.set(g,c),p.set(g,y),y},m=0;for(let g of o){let h=f(g);h>m&&(m=h)}for(let g of e)d.get(g)===a&&f(g);return{nodeCount:e.length,edgeCount:i,subgraphCount:t.subgraphs.length,sources:o,sinks:s,depth:m,hasCycles:l}}function Gy(t){let e=[];for(let[n,r]of Object.entries(t.nodes)){if(r.status!=="errored")continue;let o={path:n,status:"errored"},s=hn(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 Fy(t,e){return t.nodeCount===e.nodeCount&&t.edgeCount===e.edgeCount&&t.subgraphCount===e.subgraphCount&&t.depth===e.depth&&t.hasCycles===e.hasCycles&&Cp(t.sources,e.sources)&&Cp(t.sinks,e.sinks)}function $y(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 Cp(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 li=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=Ye(a),this.add(this.flow.entries,{name:"flow"});let u=n.pathFilter,c=Mt(e,(p,f,m)=>{if(r+=1,s.emit(r),o+=1,i.emit(o),p.kind==="removed")if(p.nodeKind==="node"){let g=`${m}${p.name}`;this.flow.delete(g)}else{let g=`${m}${p.name}::`,h=[];for(let y of p.audit.nodes){let b=y===""?`${m}${p.name}`:`${g}${y}`;h.push(b)}h.length>0&&this.flow.deleteMany(h)}});this.addDisposer(c);let d=e.observe({timeline:!0,structured:!0}),l=d.onEvent(p=>{let f=p.type;if((f==="error"||f==="complete"||f==="data"||f==="teardown")&&(o+=1,i.emit(o)),f==="data"){let m=p.path??"";if(!m||u!=null&&!u(m))return;let g=this.flow.get(m),h=g!=null?g.count+1:1;this.flow.set(m,{path:m,count:h,lastUpdate_ns:j()})}});this.addDisposer(()=>{l(),d.dispose()}),this.stats=_([s],()=>Py(e.describe({detail:"minimal"})),{name:"stats",describeKind:"derived",equals:Fy,meta:Op("stats")}),this.add(this.stats,{name:"stats"}),this.addDisposer(oe(this.stats)),this.health=_([i],()=>Gy(e.describe({detail:"standard"})),{name:"health",describeKind:"derived",equals:$y,meta:Op("health")}),this.add(this.health,{name:"health"}),this.addDisposer(oe(this.health))}why(e,n,r){let o=Za(this._target,e,n,r);return this.addDisposer(o.dispose),o}get target(){return this._target}};function By(t,e){return new li(t,e)}var fi={};we(fi,{CanvasMeasureAdapter:()=>gu,CliMeasureAdapter:()=>fu,ImageSizeAdapter:()=>vu,NodeCanvasMeasureAdapter:()=>yu,PrecomputedAdapter:()=>hu,SvgBoundsAdapter:()=>bu,analyzeAndMeasure:()=>Gt,carveTextLineSlots:()=>ru,circleIntervalForBand:()=>Pp,computeBlockFlow:()=>Ip,computeCharPositions:()=>ei,computeFlowLines:()=>Fp,computeLineBreaks:()=>Nn,computeTotalHeight:()=>Dp,layoutNextLine:()=>nu,measureBlock:()=>Ap,measureBlocks:()=>Lp,reactiveBlockLayout:()=>jy,reactiveFlowLayout:()=>Ky,reactiveLayout:()=>ey,rectIntervalForBand:()=>Gp});var fu=class{cellPx;constructor(e){this.cellPx=e?.cellPx??8}measureSegment(e,n){return{width:Yn(e)*this.cellPx}}},mu=class extends Error{name="KeyError"},hu=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 mu(`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}}},gu=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=""}},yu=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=""}},bu=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")}},vu=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();Ee();ne();function Ap(t,e,n,r,o,s,i){switch(t.type){case"text":{let a=t.font??o,u=t.lineHeight??s,c=Gt(t.text,a,n.text,r),d=Nn(c,e,n.text,a,r),l=ei(d,c,u),p=d.lineCount*u,f=0;for(let m of d.lines)m.width>f&&(f=m.width);return{index:i,type:"text",width:Math.min(f,e),height:p,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 Lp(t,e,n,r,o,s){return t.map((i,a)=>Ap(i,e,n,r,o,s,a))}function Ip(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 Dp(t){if(t.length===0)return 0;let e=t[t.length-1];return e.y+e.height}function jy(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=H([a,u],(f,m,g)=>{let h=f[0]!=null&&f[0].length>0?f[0].at(-1):g.prevData[0],y=f[1]!=null&&f[1].length>0?f[1].at(-1):g.prevData[1],b=j(),v=Lp(h,y,e,i,r,o),T=j()-b,w=d.meta;w&&(pt(w["block-count"],v.length),pt(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:(f,m)=>{let g=f,h=m;if(g==null||h==null)return g===h;if(g.length!==h.length)return!1;for(let y=0;y<g.length;y++){let b=g[y],v=h[y];if(b.type!==v.type||b.width!==v.width||b.height!==v.height||b.index!==v.index)return!1}return!0}}),l=_([d,c],([f,m])=>Ip(f,m),{name:"block-flow",equals:(f,m)=>{let g=f,h=m;if(g==null||h==null)return g===h;if(g.length!==h.length)return!1;for(let y=0;y<g.length;y++){let b=g[y],v=h[y];if(b.x!==v.x||b.y!==v.y||b.width!==v.width||b.height!==v.height)return!1}return!0}}),p=_([l],([f])=>Dp(f),{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(p,{name:"total-height"}),{graph:s,setBlocks:f=>s.set("blocks",f),setMaxWidth:f=>s.set("max-width",Math.max(0,f)),setGap:f=>s.set("gap",f),measuredBlocks:d,blockFlow:l,totalHeight:p}}ke();Ee();ne();function Pp(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 Gp(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 Vy(t,e,n){return t.kind==="circle"?Pp(t,e,n):Gp(t,e,n)}function Fp(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,p=Math.max(0,e.width-d*2),f=Math.max(0,e.height-l*2),m=n.gap*Math.max(0,n.count-1),g=Math.max(0,(p-m)/n.count);if(g<=0)return{lines:u,cursor:c};e:for(let h=0;h<n.count;h++){let y=d+h*(g+n.gap),b=y+g,v=l;for(;v+o<=l+f;){let T=v+o,w=[];for(let R=0;R<r.length;R++){let E=Vy(r[R],v,T);E!==null&&w.push(E)}let k=ru({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],I=E.right-E.left,O=nu(t,c,I);if(O===null)return{lines:u,cursor:c};if(O.text.length===0&&O.width===0){c=O.end,x=!0;break}u.push({x:E.left,y:v,width:O.width,slotWidth:I,text:O.text,columnIndex:h,flushToRight:E.right<b-.5}),c=O.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 Ky(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"}),p=N(t.paragraphSpacing??null,{name:"paragraph-spacing"}),f=H([i,a],(g,h,y)=>{let b=g[0],v=b!=null&&b.length>0?b.at(-1):y.prevData[0],T=g[1],w=T!=null&&T.length>0?T.at(-1):y.prevData[1],k=Gt(v,w,e,s);h.emit(k);let x=()=>{s.clear(),e.clearCache?.()};return{deactivate:x,invalidate:x}},{name:"segments",describeKind:"derived"}),m=_([f,c,d,l,u,p],([g,h,y,b,v,T])=>{let w=g,k=j(),x=T??v,{lines:R,cursor:E}=Fp(w,h,y,b,v,r,{paragraphSpacing:x}),I=j()-k,O=Math.max(0,w.length-E.segmentIndex),G=m.meta;return G&&(pt(G["line-count"],R.length),pt(G["layout-time-ns"],I),pt(G["overflow-segments"],O)),R},{name:"flow-lines",meta:{"line-count":0,"layout-time-ns":0,"overflow-segments":0},equals:(g,h)=>{let y=g,b=h;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(p,{name:"paragraph-spacing"}),o.add(f,{name:"segments"}),o.add(m,{name:"flow-lines"}),{graph:o,setText:g=>o.set("text",g),setFont:g=>o.set("font",g),setLineHeight:g=>o.set("line-height",g),setContainer:g=>o.set("container",g),setColumns:g=>o.set("columns",g),setObstacles:g=>o.set("obstacles",g),setParagraphSpacing:g=>o.set("paragraph-spacing",g),segments:f,flowLines:m}}var mi={};we(mi,{NS_PER_MS:()=>Ve,NS_PER_SEC:()=>ot,resilientPipeline:()=>Hy});Kn();Et();function Hy(t,e={}){let n=t;e.rateLimit!=null&&(n=qn(n,e.rateLimit)),e.budget!=null&&e.budget.length>0&&(n=za(n,e.budget));let r;if(e.breaker!=null){let s=Tt(e.breaker),i=e.breakerOnOpen??"skip",a=Wn(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=zn(n,e.timeoutMs*1e6)}e.retry!=null&&(n=Hn(n,e.retry)),e.fallback!==void 0&&(n=Un(n,e.fallback));let o=Vt(n,{initialStatus:e.initialStatus??"pending"});return{node:o.node,status:o.status,error:o.error,breakerState:r}}var xi={};we(xi,{SNAPSHOT_WIRE_VERSION:()=>go,SurfaceError:()=>Re,asSurfaceError:()=>hi,createGraph:()=>ir,deleteSnapshot:()=>ki,diffSnapshots:()=>Ti,listSnapshots:()=>wi,restoreSnapshot:()=>vi,runReduction:()=>gi,saveSnapshot:()=>bi});var Re=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=Wy(this.details);n!==void 0&&(e.details=n)}return e}};function Wy(t){try{return JSON.parse(JSON.stringify(t))}catch{return}}function hi(t,e="internal-error"){if(t instanceof Re)return t;let n=t instanceof Error?t.message:String(t);return new Re(e,n)}function ir(t,e){let n=sr(t);if(!n.valid)throw new Re("invalid-spec",`GraphSpec validation failed:
240
221
  ${n.errors.join(`
241
- `)}`,{errors:n.errors});let r=e?.catalog??{},o=zr(t,r);if(!o.valid)throw new we("catalog-error",`Catalog validation failed:
222
+ `)}`,{errors:n.errors});let r=e?.catalog??{},o=co(t,r);if(!o.valid)throw new Re("catalog-error",`Catalog validation failed:
242
223
  ${o.errors.join(`
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});
224
+ `)}`,{errors:o.errors});try{return lo(t,e)}catch(s){let i=s instanceof Error?s.message:String(s);throw new Re("catalog-error",i)}}ie();var qy=3e4;async function gi(t,e,n){let r=n?.inputPath??"input",o=n?.outputPath??"output",s=n?.timeoutMs??qy,i=ir(t,{catalog:n?.catalog}),a;try{a=i.resolve(o)}catch{throw i.destroy(),new Re("node-not-found",`reduce: output path "${o}" is not registered`,{path:o})}try{i.resolve(r)}catch{throw i.destroy(),new Re("node-not-found",`reduce: input path "${r}" is not registered`,{path:r})}try{return await new Promise((u,c)=>{let d=!1,l=!1,p,f,m=!1,g=h=>{l||(l=!0,p!==void 0&&clearTimeout(p),f!==void 0?(f(),f=void 0):m=!0,h())};f=a.subscribe(h=>{for(let y of h){if(l)return;if(d){if(y[0]===S){g(()=>u(y[1]));return}if(y[0]===B){let b=a.cache;g(()=>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;g(()=>c(new Re("internal-error",`reduce: output emitted ERROR: ${v}`,T!=null?{cause:T}:void 0)));return}if(y[0]===C){g(()=>c(new Re("internal-error","reduce: output COMPLETEd without a post-push DATA")));return}}}}),m&&(f?.(),f=void 0),d=!0;try{i.set(r,e)}catch(h){let y=h instanceof Error?h.message:String(h),b=h instanceof Error?h:void 0;g(()=>c(new Re("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&&(p=setTimeout(()=>{g(()=>c(new Re("reduce-timeout",`reduce: no output emitted within ${s}ms`,{timeoutMs:s,outputPath:o})))},s),p.unref?.())})}finally{i.destroy()}}ke();var go=lt,mo="snapshot:";function ho(t){if(t.startsWith(mo))throw new Re("snapshot-failed",`snapshot id must not start with "${mo}" (reserved); got "${t}"`,{snapshotId:t})}function yi(t){return`${mo}${t}`}function Uy(t){return t.startsWith(mo)?t.slice(mo.length):void 0}function Tu(t,e){if(t==null||typeof t!="object")throw new Re("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 Re("restore-failed",`snapshot "${e}" is a diff record; restore the baseline and replay WAL instead`,{snapshotId:e,mode:"diff"}):new Re("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 Re("restore-failed",`snapshot "${e}" payload is not a GraphCheckpointRecord or GraphPersistSnapshot`,{snapshotId:e})}async function bi(t,e,n){ho(e);let r;try{r=t.snapshot()}catch(s){let i=s instanceof Error?s.message:String(s);throw new Re("snapshot-failed",`snapshot "${e}" serialization failed: ${i}`,{snapshotId:e})}let o={mode:"full",seq:0,timestamp_ns:fe(),format_version:go,snapshot:r};try{await n.save(yi(e),o)}catch(s){let i=s instanceof Error?s.message:String(s);throw new Re("snapshot-failed",`snapshot "${e}" save failed: ${i}`,{snapshotId:e})}return{snapshotId:e,timestamp_ns:o.timestamp_ns}}async function vi(t,e,n){ho(t);let r=yi(t),o=await e.load(r);o==null&&(o=await e.load(t));let s=Tu(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 Re("restore-failed",`snapshot "${t}" restore failed: ${a}`,{snapshotId:t})}}async function Ti(t,e,n){ho(t),ho(e);let r=async u=>{let c=yi(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=Tu(o,t),a=Tu(s,e);return z.diff(i,a)}async function wi(t,e){if(typeof t.list!="function")throw new Re("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=Uy(s);i!==void 0?r.push(i):o&&r.push(s)}return r}async function ki(t,e){if(ho(t),typeof e.clear!="function")throw new Re("snapshot-failed",`StorageTier is append-only (no clear()); cannot delete "${t}"`,{snapshotId:t});try{await e.clear(yi(t))}catch(n){let r=n instanceof Error?n.message:String(n);throw new Re("snapshot-failed",`snapshot "${t}" delete failed: ${r}`,{snapshotId:t})}}var zy="0.0.0";0&&(module.exports={COMPLETE,COMPLETE_MSG,COMPLETE_ONLY_BATCH,CircuitOpenError,ContentAddressedMissError,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,canonicalJson,cascadingCache,catchError,checkpointToRedis,checkpointToS3,circuitBreaker,combine,combineLatest,compat,concat,concatMap,configure,constant,contentAddressedStorage,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,makeHttpError,map,matchesAnyPattern,matchesCron,memory,memoryStorage,merge,mergeMap,mermaidLiveUrl,messaging,monotonicNs,nameToSignal,nanostores,ndjsonRows,nestjs,never,node,nodeSignal,normalizeActor,of,onFirstData,orchestration,pairwise,parseCron,parsePrometheusText,parseSSEStream,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,tapFirst,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});