@graphrefly/graphrefly 0.35.0 → 0.37.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 (193) hide show
  1. package/dist/{chunk-EUE7ELFQ.js → chunk-2C4NESZE.js} +1 -1
  2. package/dist/{chunk-PIIUJIF7.js → chunk-4EATTNAE.js} +1 -1
  3. package/dist/chunk-B4L5X2QO.js +7 -0
  4. package/dist/{chunk-YV2A2VWG.js → chunk-C5CBVOCB.js} +1 -1
  5. package/dist/{chunk-J6TGRQUP.js → chunk-CZIQ6JCE.js} +1 -1
  6. package/dist/chunk-FJ6IEMOS.js +1 -0
  7. package/dist/{chunk-T7GWBGOO.js → chunk-FMI4CWFL.js} +1 -1
  8. package/dist/{chunk-RRFOCAH6.js → chunk-G6Q3DUMJ.js} +1 -1
  9. package/dist/{chunk-CD4CB6S7.js → chunk-GDDPCDLG.js} +1 -1
  10. package/dist/{chunk-3OT7K33Q.js → chunk-GFOT6UBB.js} +1 -1
  11. package/dist/{chunk-53XJ2S6D.js → chunk-K2WYIVHM.js} +1 -1
  12. package/dist/{chunk-5XZRCS2M.js → chunk-K6ZFJ473.js} +1 -1
  13. package/dist/{chunk-E5YSBQSF.js → chunk-KTWBUJO5.js} +1 -1
  14. package/dist/{chunk-RLMYS3XZ.js → chunk-KUVDFOJH.js} +1 -1
  15. package/dist/{chunk-XMDNNSMK.js → chunk-LOQRPP4Y.js} +1 -1
  16. package/dist/{chunk-2Y3DKIZL.js → chunk-MC5LZG3U.js} +1 -1
  17. package/dist/{chunk-M5UC63ZI.js → chunk-NKKUUKPD.js} +1 -1
  18. package/dist/{chunk-GWOKTENT.js → chunk-QKBCTKH7.js} +1 -1
  19. package/dist/{chunk-YOUAVGHJ.js → chunk-QP5TH523.js} +1 -1
  20. package/dist/{chunk-T6RPUERH.js → chunk-QWVQIL3T.js} +1 -1
  21. package/dist/{chunk-6G5YD37E.js → chunk-T4U24DXX.js} +1 -1
  22. package/dist/{chunk-W2ZU226Q.js → chunk-TFK4P4CX.js} +1 -1
  23. package/dist/{chunk-PVUTRA5K.js → chunk-TLS7M7H4.js} +1 -1
  24. package/dist/{chunk-BGEY3PXH.js → chunk-U3COB5WU.js} +1 -1
  25. package/dist/{chunk-UAMWD4GG.js → chunk-UODQF4EY.js} +1 -1
  26. package/dist/{chunk-U347KVM4.js → chunk-WGST56ZH.js} +1 -1
  27. package/dist/{chunk-XINLP35X.js → chunk-WSLN4JFO.js} +1 -1
  28. package/dist/{chunk-ZGVA2SR5.js → chunk-XIJKEXWR.js} +1 -1
  29. package/dist/{chunk-JUJEPZOI.js → chunk-YVYSO5CW.js} +1 -1
  30. package/dist/compat/index.cjs +9 -9
  31. package/dist/compat/index.d.cts +6 -6
  32. package/dist/compat/index.d.ts +6 -6
  33. package/dist/compat/index.js +1 -1
  34. package/dist/compat/nestjs/index.cjs +11 -11
  35. package/dist/compat/nestjs/index.d.cts +4 -4
  36. package/dist/compat/nestjs/index.d.ts +4 -4
  37. package/dist/compat/nestjs/index.js +1 -1
  38. package/dist/compat/zustand/index.cjs +7 -7
  39. package/dist/compat/zustand/index.d.cts +2 -2
  40. package/dist/compat/zustand/index.d.ts +2 -2
  41. package/dist/compat/zustand/index.js +1 -1
  42. package/dist/extra/index.cjs +17 -17
  43. package/dist/extra/index.d.cts +3 -3
  44. package/dist/extra/index.d.ts +3 -3
  45. package/dist/extra/index.js +1 -1
  46. package/dist/extra/reactive.cjs +1 -1
  47. package/dist/extra/reactive.d.cts +1 -1
  48. package/dist/extra/reactive.d.ts +1 -1
  49. package/dist/extra/reactive.js +1 -1
  50. package/dist/graph/index.cjs +7 -7
  51. package/dist/graph/index.d.cts +3 -3
  52. package/dist/graph/index.d.ts +3 -3
  53. package/dist/graph/index.js +1 -1
  54. package/dist/{graph-kTltt95s.d.cts → graph-CaNXUc3c.d.cts} +26 -1
  55. package/dist/{graph-Cv-8x0ZI.d.ts → graph-YQXDndFy.d.ts} +26 -1
  56. package/dist/{index-KNAMYngu.d.ts → index-0qOD-421.d.ts} +2 -2
  57. package/dist/{index-CfOSES72.d.cts → index-4IwO4mH2.d.cts} +5 -5
  58. package/dist/{index-CAIhFfws.d.ts → index-9mbs_PIG.d.ts} +2 -2
  59. package/dist/{index-Bilohojo.d.ts → index-Ae6L8liv.d.ts} +2 -2
  60. package/dist/{index-BhkPzu-Z.d.cts → index-B1IcU--K.d.cts} +2 -2
  61. package/dist/{index-DzgS5uYi.d.ts → index-B46GWgk3.d.ts} +1 -1
  62. package/dist/{index-BpFwRAf9.d.cts → index-B9qJmmv3.d.cts} +1 -1
  63. package/dist/{index-CI_yjtua.d.ts → index-BCq12BqB.d.ts} +1 -1
  64. package/dist/{index-zK_mN1D-.d.cts → index-BECJ8M0T.d.cts} +2 -2
  65. package/dist/{index-DFe2Pk2u.d.ts → index-BOfHwQc1.d.ts} +1 -1
  66. package/dist/{index-hXKhbfh-.d.ts → index-BhLA9feT.d.ts} +12 -7
  67. package/dist/{index-Dp69u0ym.d.ts → index-BmLkcDlj.d.ts} +6 -6
  68. package/dist/{index-XxSeddWP.d.cts → index-BokynmA4.d.cts} +1 -1
  69. package/dist/{index-BEvsFlfH.d.ts → index-Bpzw8hx3.d.ts} +2 -2
  70. package/dist/{index-PluovH45.d.cts → index-BwtIbzSV.d.cts} +2 -2
  71. package/dist/{index-BZ1V5GzX.d.ts → index-C-pFD_FV.d.ts} +2 -2
  72. package/dist/{index-Cot94_82.d.ts → index-C0tga1_x.d.ts} +2 -2
  73. package/dist/{index-BlRVj-7Q.d.cts → index-C4N-dg5U.d.cts} +2 -2
  74. package/dist/{index-B4s70vYf.d.ts → index-CKcnuQ2c.d.ts} +2 -2
  75. package/dist/{index-D7r_vd0b.d.cts → index-CLPQyYY5.d.cts} +3 -3
  76. package/dist/{index-BuMzxRO2.d.ts → index-CRycrNfn.d.ts} +1 -1
  77. package/dist/{index-DeyzuqAi.d.cts → index-CU3z8Cel.d.cts} +2 -2
  78. package/dist/{index-DwNNufVa.d.ts → index-CUTHDZ7Q.d.ts} +3 -3
  79. package/dist/{index-CGKs5ixV.d.cts → index-C_qi0WlF.d.cts} +12 -7
  80. package/dist/{index-BBdwz2BW.d.ts → index-CajEOoAN.d.ts} +2 -2
  81. package/dist/{index-CzC0G0C3.d.cts → index-Ci358GSC.d.cts} +2 -2
  82. package/dist/{index-BkbawFkI.d.cts → index-CkN8CZlT.d.cts} +6 -6
  83. package/dist/{index-ZhKyR8co.d.cts → index-CrpjECS6.d.cts} +2 -2
  84. package/dist/{index-C40wA8zt.d.ts → index-CzIWlnPp.d.ts} +5 -5
  85. package/dist/{index-C9xF16gc.d.ts → index-D0ZxFXYl.d.ts} +2 -2
  86. package/dist/{index-BtY2QVDf.d.cts → index-D11pGlaI.d.cts} +2 -2
  87. package/dist/{index-DlccEIi3.d.ts → index-D1E1tqHT.d.ts} +1 -1
  88. package/dist/{index-Qq-G9B6g.d.cts → index-D6pwWiOc.d.cts} +2 -2
  89. package/dist/{index-BsZlbHM5.d.cts → index-D6tRNEKz.d.cts} +1 -1
  90. package/dist/{index-B3Dfl5sS.d.cts → index-DAKm44My.d.cts} +2 -2
  91. package/dist/{index-BWH17rK_.d.cts → index-DCAuN9u5.d.cts} +1 -1
  92. package/dist/{index-BF-ssbJB.d.ts → index-DPqR3wdW.d.ts} +2 -2
  93. package/dist/{index-GaW6Welt.d.cts → index-DTYIRT_v.d.cts} +2 -2
  94. package/dist/{index-DXSLMoma.d.ts → index-DXz9uwcs.d.ts} +1 -1
  95. package/dist/{index-DmtWMP0X.d.cts → index-D_DThl_J.d.cts} +1 -1
  96. package/dist/{index-BwYGLgmI.d.ts → index-D_d1erkR.d.ts} +2 -2
  97. package/dist/{index-D9qoEOj_.d.cts → index-DbWwMWiB.d.cts} +1 -1
  98. package/dist/{index-D6JRP-1_.d.cts → index-DcWbx58m.d.cts} +2 -2
  99. package/dist/{index-DzYTXMBz.d.ts → index-DfAo9WKr.d.ts} +1 -1
  100. package/dist/{index-DXZsXxtU.d.cts → index-DqtXA3yX.d.cts} +2 -2
  101. package/dist/{index-DBmBtqAN.d.ts → index-DuhOdNyg.d.ts} +2 -2
  102. package/dist/{index-DKp1CIbG.d.cts → index-e1m3ZHgc.d.cts} +1 -1
  103. package/dist/{index-DSD6xnbT.d.ts → index-fHKHdAso.d.ts} +2 -2
  104. package/dist/index.cjs +41 -41
  105. package/dist/index.d.cts +29 -29
  106. package/dist/index.d.ts +29 -29
  107. package/dist/index.js +1 -1
  108. package/dist/patterns/ai/index.cjs +19 -19
  109. package/dist/patterns/ai/index.d.cts +7 -7
  110. package/dist/patterns/ai/index.d.ts +7 -7
  111. package/dist/patterns/ai/index.js +1 -1
  112. package/dist/patterns/audit/index.cjs +7 -7
  113. package/dist/patterns/audit/index.d.cts +4 -4
  114. package/dist/patterns/audit/index.d.ts +4 -4
  115. package/dist/patterns/audit/index.js +1 -1
  116. package/dist/patterns/cqrs/index.cjs +7 -7
  117. package/dist/patterns/cqrs/index.d.cts +3 -3
  118. package/dist/patterns/cqrs/index.d.ts +3 -3
  119. package/dist/patterns/cqrs/index.js +1 -1
  120. package/dist/patterns/demo-shell/index.cjs +8 -8
  121. package/dist/patterns/demo-shell/index.d.cts +3 -3
  122. package/dist/patterns/demo-shell/index.d.ts +3 -3
  123. package/dist/patterns/demo-shell/index.js +1 -1
  124. package/dist/patterns/domain-templates/index.cjs +7 -7
  125. package/dist/patterns/domain-templates/index.d.cts +2 -2
  126. package/dist/patterns/domain-templates/index.d.ts +2 -2
  127. package/dist/patterns/domain-templates/index.js +1 -1
  128. package/dist/patterns/graphspec/index.cjs +17 -17
  129. package/dist/patterns/graphspec/index.d.cts +2 -2
  130. package/dist/patterns/graphspec/index.d.ts +2 -2
  131. package/dist/patterns/graphspec/index.js +1 -1
  132. package/dist/patterns/guarded-execution/index.cjs +7 -7
  133. package/dist/patterns/guarded-execution/index.d.cts +5 -5
  134. package/dist/patterns/guarded-execution/index.d.ts +5 -5
  135. package/dist/patterns/guarded-execution/index.js +1 -1
  136. package/dist/patterns/harness/index.cjs +10 -10
  137. package/dist/patterns/harness/index.d.cts +7 -7
  138. package/dist/patterns/harness/index.d.ts +7 -7
  139. package/dist/patterns/harness/index.js +1 -1
  140. package/dist/patterns/job-queue/index.cjs +7 -7
  141. package/dist/patterns/job-queue/index.d.cts +3 -3
  142. package/dist/patterns/job-queue/index.d.ts +3 -3
  143. package/dist/patterns/job-queue/index.js +1 -1
  144. package/dist/patterns/lens/index.cjs +7 -7
  145. package/dist/patterns/lens/index.d.cts +3 -3
  146. package/dist/patterns/lens/index.d.ts +3 -3
  147. package/dist/patterns/lens/index.js +1 -1
  148. package/dist/patterns/memory/index.cjs +7 -7
  149. package/dist/patterns/memory/index.d.cts +2 -2
  150. package/dist/patterns/memory/index.d.ts +2 -2
  151. package/dist/patterns/memory/index.js +1 -1
  152. package/dist/patterns/messaging/index.cjs +7 -7
  153. package/dist/patterns/messaging/index.d.cts +3 -3
  154. package/dist/patterns/messaging/index.d.ts +3 -3
  155. package/dist/patterns/messaging/index.js +1 -1
  156. package/dist/patterns/orchestration/index.cjs +7 -7
  157. package/dist/patterns/orchestration/index.d.cts +3 -3
  158. package/dist/patterns/orchestration/index.d.ts +3 -3
  159. package/dist/patterns/orchestration/index.js +1 -1
  160. package/dist/patterns/process/index.cjs +1 -1
  161. package/dist/patterns/process/index.d.cts +4 -4
  162. package/dist/patterns/process/index.d.ts +4 -4
  163. package/dist/patterns/process/index.js +1 -1
  164. package/dist/patterns/reactive-layout/index.cjs +8 -8
  165. package/dist/patterns/reactive-layout/index.d.cts +3 -3
  166. package/dist/patterns/reactive-layout/index.d.ts +3 -3
  167. package/dist/patterns/reactive-layout/index.js +1 -1
  168. package/dist/patterns/reduction/index.cjs +7 -7
  169. package/dist/patterns/reduction/index.d.cts +2 -2
  170. package/dist/patterns/reduction/index.d.ts +2 -2
  171. package/dist/patterns/reduction/index.js +1 -1
  172. package/dist/patterns/refine-loop/index.cjs +8 -8
  173. package/dist/patterns/refine-loop/index.d.cts +4 -4
  174. package/dist/patterns/refine-loop/index.d.ts +4 -4
  175. package/dist/patterns/refine-loop/index.js +1 -1
  176. package/dist/patterns/resilient-pipeline/index.d.cts +3 -3
  177. package/dist/patterns/resilient-pipeline/index.d.ts +3 -3
  178. package/dist/patterns/resilient-pipeline/index.js +1 -1
  179. package/dist/patterns/surface/index.cjs +10 -10
  180. package/dist/patterns/surface/index.d.cts +3 -3
  181. package/dist/patterns/surface/index.d.ts +3 -3
  182. package/dist/patterns/surface/index.js +1 -1
  183. package/dist/{pipeline-graph-B85HUrWg.d.cts → pipeline-graph-BrrYGjuZ.d.cts} +2 -2
  184. package/dist/{pipeline-graph-HOTU4UG0.d.ts → pipeline-graph-DX2Twdj-.d.ts} +2 -2
  185. package/dist/{reactive-layout-Btv0-efV.d.ts → reactive-layout-BDdngW56.d.ts} +1 -1
  186. package/dist/{reactive-layout-D9zqqaqK.d.cts → reactive-layout-DrGjuwyC.d.cts} +1 -1
  187. package/dist/{reactive-log-CgbNqksB.d.cts → reactive-log-ScpWyqny.d.cts} +11 -3
  188. package/dist/{reactive-log-ByBb8g6A.d.ts → reactive-log-jirQsxMY.d.ts} +11 -3
  189. package/dist/{topology-tree-CJsT24DP.d.ts → topology-tree-BI665P0L.d.ts} +1 -1
  190. package/dist/{topology-tree-C50l9ARE.d.cts → topology-tree-BkhmMg2a.d.cts} +1 -1
  191. package/package.json +1 -1
  192. package/dist/chunk-5KPIYVCC.js +0 -7
  193. package/dist/chunk-CUQFO6MT.js +0 -1
package/dist/index.cjs CHANGED
@@ -1,55 +1,55 @@
1
- "use strict";var Of=Object.create;var En=Object.defineProperty;var td=Object.getOwnPropertyDescriptor;var Cf=Object.getOwnPropertyNames;var Af=Object.prototype.hasOwnProperty;var nd=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),gr=t=>{throw TypeError(t)};var Lf=(t,e,n)=>e in t?En(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Xu=(t,e)=>En(t,"name",{value:e,configurable:!0});var tt=(t,e)=>()=>(t&&(e=t(t=0)),e);var ke=(t,e)=>{for(var n in e)En(t,n,{get:e[n],enumerable:!0})},If=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Cf(e))!Af.call(t,o)&&o!==n&&En(t,o,{get:()=>e[o],enumerable:!(r=td(e,o))||r.enumerable});return t};var Pf=t=>If(En({},"__esModule",{value:!0}),t);var rd=t=>[,,,Of(t?.[nd("metadata")]??null)],od=["class","method","getter","setter","accessor","field","value","get","set"],mr=t=>t!==void 0&&typeof t!="function"?gr("Function expected"):t,Df=(t,e,n,r,o)=>({kind:od[t],name:e,metadata:r,addInitializer:s=>n._?gr("Already initialized"):o.push(mr(s||null))}),Gf=(t,e)=>Lf(e,nd("metadata"),t[3]),sd=(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},id=(t,e,n,r,o,s)=>{var i,a,u,d,c,l=e&7,p=!!(e&8),f=!!(e&16),m=l>3?t.length+1:l?p?1:2:0,h=od[l+5],g=l>3&&(t[m-1]=[]),y=t[m]||(t[m]=[]),b=l&&(!f&&!p&&(o=o.prototype),l<5&&(l>3||!f)&&td(l<4?o:{get[n](){return Zu(this,s)},set[n](T){return ed(this,s,T)}},n));l?f&&l<4&&Xu(s,(l>2?"set ":l>1?"get ":"")+n):Xu(o,n);for(var v=r.length-1;v>=0;v--)d=Df(l,n,u={},t[3],y),l&&(d.static=p,d.private=f,c=d.access={has:f?T=>Ff(o,T):T=>n in T},l^3&&(c.get=f?T=>(l^1?Zu:$f)(T,o,l^4?s:b.get):T=>T[n]),l>2&&(c.set=f?(T,w)=>ed(T,o,w,l^4?s:b.set):(T,w)=>T[n]=w)),a=(0,r[v])(l?l<4?f?s:b[h]:l>4?void 0:{get:b.get,set:b.set}:o,d),u._=1,l^4||a===void 0?mr(a)&&(l>4?g.unshift(a):l?f?s=a:b[h]=a:o=a):typeof a!="object"||a===null?gr("Object expected"):(mr(i=a.get)&&(b.get=i),mr(i=a.set)&&(b.set=i),mr(i=a.init)&&g.unshift(i));return l||Gf(t,o),b&&En(o,n,b),f?l^4?s:b:o};var Ui=(t,e,n)=>e.has(t)||gr("Cannot "+n),Ff=(t,e)=>Object(e)!==e?gr('Cannot use the "in" operator on this value'):t.has(e),Zu=(t,e,n)=>(Ui(t,e,"read from private field"),n?n.call(t):e.get(t));var ed=(t,e,n,r)=>(Ui(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),$f=(t,e,n)=>(Ui(t,e,"access private method"),n);var dt,E,ne,V,Je,Be,qe,le,L,C,Et,Nn,Mo,_n,Oo,Co,Mn,hr,yr,br,On,ae=tt(()=>{"use strict";dt=Symbol.for("graphrefly/START"),E=Symbol.for("graphrefly/DATA"),ne=Symbol.for("graphrefly/DIRTY"),V=Symbol.for("graphrefly/RESOLVED"),Je=Symbol.for("graphrefly/INVALIDATE"),Be=Symbol.for("graphrefly/PAUSE"),qe=Symbol.for("graphrefly/RESUME"),le=Symbol.for("graphrefly/TEARDOWN"),L=Symbol.for("graphrefly/COMPLETE"),C=Symbol.for("graphrefly/ERROR"),Et=Object.freeze([ne]),Nn=Object.freeze([V]),Mo=Object.freeze([Je]),_n=Object.freeze([dt]),Oo=Object.freeze([L]),Co=Object.freeze([le]),Mn=Object.freeze([Et]),hr=Object.freeze([Nn]),yr=Object.freeze([Mo]),br=Object.freeze([Oo]),On=Object.freeze([Co])});function Ji(t){return{name:"dag-cbor",version:1,contentType:"application/dag-cbor",encode:e=>t.encode(e),decode:(e,n)=>t.decode(e)}}function Yi(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 vr(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++]=Cn,s[i++]=n.length,s.set(n,i),i+=n.length,s[i++]=r>>>8&255,s[i++]=r&255,s.set(e,i),s}function Tr(t,e){if(t.length<ad)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${ad})`);let n=0,r=t[n++];if(r!==Cn)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${Cn})`);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 wr(t){t.registerCodec(Ao)}function Qi(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,d]of Object.entries(a))n.nodes[u]=JSON.parse(JSON.stringify(d));for(let u of i.nodesChanged){let d=n.nodes[u.path];d!=null&&(d[u.field]=u.to)}r=s.seq}return n}var Ao,Cn,ad,Lo=tt(()=>{"use strict";Ao={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)}};Cn=1,ad=4});function Nt(t){if(t==null)return bt;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var bt,kr=tt(()=>{"use strict";bt={type:"system",id:""}});function tn(){return An>0||xr}function ud(){return An>0}function Sr(t){An>0?Rr.push(t):t()}function X(t){An+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(An-=1,An===0)if(e){if(!xr){let n=Rr.splice(0);for(let r of n)try{r()}catch{}Zt.length=0,en.length=0,Ln.length=0}}else jf()}}function jf(){let t=!xr;t&&(xr=!0);let e=[],n=0;try{for(;Zt.length>0||en.length>0||Ln.length>0||t&&Rr.length>0;){if(t&&Rr.length>0){let s=Rr.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,Ln.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let o=(Zt.length>0?Zt:en.length>0?en:Ln).splice(0);for(let s of o)try{s()}catch(i){e.push(i)}}}finally{t&&(xr=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function _t(t,e,n){if(e.length===0)return;if(e.length===1){let d=n(e[0][0]);if(d<3||!tn()){t(e);return}(d>=5?Ln:d===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 d=e.slice(0,o);t(d)}if(s>o){let d=e.slice(o,s);u?Zt.push(()=>t(d)):t(d)}if(i>s){let d=e.slice(s,i);u?en.push(()=>t(d)):t(d)}if(r>i){let d=e.slice(i,r);u?Ln.push(()=>t(d)):t(d)}}var An,xr,Zt,en,Ln,Rr,Me=tt(()=>{"use strict";An=0,xr=!1,Zt=[],en=[],Ln=[],Rr=[]});function H(){return Math.trunc(performance.now()*1e6)}function oe(){return Date.now()*1e6}var xe=tt(()=>{"use strict"});function Er(t){t.registerMessageType(dt,{tier:0,wireCrossing:!1}),t.registerMessageType(ne,{tier:1,wireCrossing:!1}),t.registerMessageType(Je,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(Be,{tier:2,wireCrossing:!1}),t.registerMessageType(qe,{tier:2,wireCrossing:!1}),t.registerMessageType(E,{tier:3,wireCrossing:!0}),t.registerMessageType(V,{tier:3,wireCrossing:!0}),t.registerMessageType(L,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(C,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(le,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var nn,Xi=tt(()=>{"use strict";ae();nn=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_rigorRecorder;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=n=>{let r=this._messageTypes.get(n);return r!=null?r.tier:1}}get onMessage(){return this._frozen=!0,this._onMessage}get onSubscribe(){return this._frozen=!0,this._onSubscribe}set onMessage(e){this._assertUnfrozen(),this._onMessage=e}set onSubscribe(e){this._assertUnfrozen(),this._onSubscribe=e}get defaultVersioning(){return this._defaultVersioning}set defaultVersioning(e){this._assertUnfrozen(),this._defaultVersioning=e}get defaultHashFn(){return this._defaultHashFn}set defaultHashFn(e){this._assertUnfrozen(),this._defaultHashFn=e}get inspectorEnabled(){return this._inspectorEnabled}set inspectorEnabled(e){this._inspectorEnabled=e}get globalInspector(){return this._globalInspector}set globalInspector(e){this._globalInspector=e}get rigorRecorder(){return this._rigorRecorder}set rigorRecorder(e){this._rigorRecorder=e}registerMessageType(e,n){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:n.tier,wireCrossing:n.wireCrossing??n.tier>=3,metaPassthrough:n.metaPassthrough??!0}),this}messageTier(e){let n=this._messageTypes.get(e);return n!=null?n.tier:1}isWireCrossing(e){let n=this._messageTypes.get(e);return n!=null?n.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let n=this._messageTypes.get(e);return n!=null?n.metaPassthrough:!0}isKnownMessageType(e){return this._messageTypes.has(e)}registerCodec(e){return this._assertUnfrozen(),this._codecs.set(e.name,e),this}lookupCodec(e){return this._codecs.get(e)}_isFrozen(){return this._frozen}_assertUnfrozen(){if(this._frozen)throw new Error("GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node.")}}});function dd(t){return Array.isArray(t)?[...t]:[t]}function Bf(t,e){return t.has(e)||t.has("*")}function Mt(t){let e=[];return t((o,s)=>{e.push({kind:"allow",actions:new Set(dd(o)),where:s?.where??(()=>!0)})},(o,s)=>{e.push({kind:"deny",actions:new Set(dd(o)),where:s?.where??(()=>!0)})}),(o,s)=>{let i=!1,a=!1;for(let u of e)Bf(u.actions,s)&&u.where(o)&&(u.kind==="deny"?i=!0:a=!0);return i?!1:a}}function Nr(t){return Mt((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[d,c]of i)if(u[d]!==c)return!1;return!0};r.effect==="deny"?n(r.action,{where:a}):e(r.action,{where:a})}})}function _r(t){let e=Vf.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 rt,Vf,$t=tt(()=>{"use strict";rt=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}};Vf=["human","llm","wallet","system"]});function Zi(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(Zi);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=Zi(t[n]);return e}return null}function Hf(t){let e=qf.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,d=1013904242,c=2773480762,l=1359893119,p=2600822924,f=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 _=0;_<16;_++)h[_]=i.getUint32(b+_*4,!1);for(let _=16;_<64;_++){let I=h[_-15],O=h[_-2],P=g(I,7)^g(I,18)^I>>>3,B=g(O,17)^g(O,19)^O>>>10;h[_]=h[_-16]+P+h[_-7]+B>>>0}let v=a,T=u,w=d,x=c,k=l,S=p,R=f,N=m;for(let _=0;_<64;_++){let I=g(k,6)^g(k,11)^g(k,25),O=k&S^~k&R,P=N+I+O+Kf[_]+h[_]>>>0,B=g(v,2)^g(v,13)^g(v,22),j=v&T^v&w^T&w,D=B+j>>>0;N=R,R=S,S=k,k=x+P>>>0,x=w,w=T,T=v,v=P+D>>>0}a=a+v>>>0,u=u+T>>>0,d=d+w>>>0,c=c+x>>>0,l=l+k>>>0,p=p+S>>>0,f=f+R>>>0,m=m+N>>>0}let y=b=>b.toString(16).padStart(8,"0");return y(a)+y(u)+y(d)+y(c)+y(l)+y(p)+y(f)+y(m)}function jt(t){let e=Zi(t??null),n=JSON.stringify(e);return Hf(n).slice(0,16)}function Wf(){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 In(t,e,n){let r=n?.id??Wf();if(t===0)return{id:r,version:0};let s=(n?.hash??jt)(e);return{id:r,version:0,cid:s,prev:null}}function Mr(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}function ea(t){return"cid"in t}var Kf,qf,Io=tt(()=>{"use strict";Kf=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]),qf=new TextEncoder});function pd(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function ta(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function Po(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function ra(t){if($e._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($e)}function z(t,e,n){let r=fd(t)?t:[],o=typeof t=="function"?t:typeof e=="function"?e:void 0,s={};return fd(t)?s=(na(e)?e:n)??{}:na(t)?s=t:s=(na(e)?e:n)??{},new Ae(r,o,s)}var cd,ld,zf,Uf,$e,Ae,fd,na,_e=tt(()=>{"use strict";Lo();kr();Me();xe();Xi();$t();ae();Io();cd=()=>{},ld=100;zf=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},Uf=(t,e,n,r)=>{let o=t;if(o._status==="completed"||o._status==="errored")return;let s=o._cached,i=s===void 0?[_n]:[_n,[E,s]];o._status==="dirty"&&i.push(Et),_t(e,i,o._config.tierOf)},$e=new nn({onMessage:zf,onSubscribe:Uf});Er($e);wr($e);Ae=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??$e,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??jt;let o=r.versioning??this._config.defaultVersioning;this._versioningLevel=o,this._versioning=o!=null?In(o,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(pd);let s={};for(let[a,u]of Object.entries(r.meta??{})){let d={initial:u,name:`${r.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};r.guard!=null&&(d.guard=r.guard),s[a]=new t([],void 0,d)}Object.freeze(s),this.meta=s,this._hasMeta=Object.keys(s).length>0;let i=this;this._actions={emit(a){i._emit([[E,a]])},down(a){i._emit(Po(a))},up(a){i._emitUp(Po(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,d=In(e,s,{id:a,hash:o});d.version=u,this._versioning=d,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=Nt(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=Nt(e?.actor),s=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(o,s))throw new rt({actor:o,action:s,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(o,s))throw new rt({actor:o,action:s,nodeName:this.name})}this._lastMutation={actor:o,timestamp_ns:oe()}}down(e,n){let r=Po(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[E,e]])}up(e,n){if(this._deps.length===0)return;let r=Po(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=Nt(n);if(!this._guard(u,"observe"))throw new rt({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)ta(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=cd,s.unsub=s.node.subscribe(i=>{if(s.unsub===null)return;let a=this._config.tierOf,u=!1;for(let d of i)a(d[0])>=3&&(u=!0),this._config.onMessage(this,d,{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{}ta(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=pd(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Mn),r.unsub=cd;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([[C,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([[C,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{}}ta(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===ne){this._depDirtied(r);return}if(o===Je){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(yr);return}if(o===Be||o===qe){this._emit([n]);return}if(o===le){this._emit(On);return}if(o===E)this._depSettledAsData(r,n[1]);else if(o===V)this._depSettledAsResolved(r);else if(o===L)this._depSettledAsTerminal(r,!0);else if(o===C)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(o===E||o===V)&&this._emit([n]),(o===L||o===C)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Mn))}_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(hr),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([[C,e.terminal]]);return}this._autoComplete&&this._deps.every(n=>n.terminal!==void 0)&&this._emit(br)}_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([[C,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([[C,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([[C,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>ld?(this._rerunDepth=0,this._emit([[C,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${ld} \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"?[Et,e[0]]:e;let r=!0,o=!1,s=!1,i=-1;for(let u of e){let d=n(u[0]);d<i&&(r=!1),d===3&&(o=!0),u[0]===ne&&(s=!0),i=d}let a=e;if(!r){let u=e.map((d,c)=>({m:d,i:c,tier:n(d[0])}));u.sort((d,c)=>d.tier-c.tier||d.i-c.i),a=u.map(d=>d.m)}if(o&&!s&&this._status!=="dirty"){let u=0;for(;u<a.length&&n(a[u][0])===0;)u++;return u===0?[Et,...a]:[...a.slice(0,u),Et,...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]===C&&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]===le||u[0]===Je);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],d=u[0];if(d!==Be&&d!==qe){o?.push(u);continue}if(u.length<2)throw new Error(`Node "${this.name}": [[${d===Be?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let c=!0;if(this._pausable!==!1){let l=u[1];if(d===Be)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(l),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(l))c=!1;else if(this._pauseLocks.delete(l),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let p=this._pauseBuffer;this._pauseBuffer=[],this._emit(p)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?o?.push(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]===le))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(On)}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 d of s)a(d[0])===3?this._pauseBuffer.push(d):u.push(d);u.length>0&&this._dispatchOrAccumulate(u)}else this._dispatchOrAccumulate(s);i!=null&&this._emit([[C,i]])}_updateState(e){let n=this._config.tierOf,r,o,s=-1,i=0;for(let c of e)n(c[0])===3&&i++;let a=i<=1,u=-1;if(this._versioning!=null&&i>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===E){u=c;break}}for(let c=0;c<e.length;c++){let l=e[c],p=l[0];if(p===E){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=c;break}if(f){r==null&&(r=e.slice(0,c)),r.push(Nn),this._status="resolved";continue}this._cached=l[1],this._versioning!=null&&(u<0||c===u)&&Mr(this._versioning,l[1],this._hashFn)}this._status="settled",r?.push(l)}else if(r?.push(l),p===ne)this._status="dirty";else if(p===V)this._status="resolved";else if(p===L){this._status="completed";{let f=this._config.rigorRecorder;if(f!=null)try{f.onTerminalTransition(this,"completed",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===C){this._status="errored";{let f=this._config.rigorRecorder;if(f!=null)try{f.onTerminalTransition(this,"errored",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===Je){if(this._cached!==void 0){let m=this._config.rigorRecorder;if(m!=null)try{m.onNonVacuousInvalidate(this,this._cached)}catch{}}this._cached=void 0,this._status="dirty";let f=this._cleanup;if(typeof f=="function"){this._cleanup=void 0;try{f()}catch{}}else if(f!=null&&typeof f=="object"){let m=f.invalidate;if(typeof m=="function")try{m()}catch{}}}else p===le&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let d=s>=0?r??e.slice(0,s):r??e;return o!=null?{finalMessages:d,equalsError:o}:{finalMessages:d}}_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(ud()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],Sr(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}_t(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);_t(this._deliverToSinks,n,this._config.tierOf)}},fd=t=>Array.isArray(t),na=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function M(t,e){return z([],{...e,initial:t})}function K(t,e){return z((r,o,s)=>t(o,s)??void 0,{describeKind:"producer",...e})}function A(t,e,n){return z(t,(o,s,i)=>{let a=o.map((u,d)=>u!=null&&u.length>0?u.at(-1):i.prevData[d]);s.emit(e(a,i))},{describeKind:"derived",...n})}function pe(t,e,n){return z(t,(o,s,i)=>{let a=o.map((u,d)=>u!=null&&u.length>0?u.at(-1):i.prevData[d]);return e(a,s,i)??void 0},{describeKind:"effect",...n})}function Or(t,e,n){let r=new Map;return t.forEach((o,s)=>{r.set(o,s)}),A(t,(o,s)=>e(a=>{let u=r.get(a);if(u==null)throw new Error(`dynamicNode: untracked dep "${a.name??"<unnamed>"}"`);return o[u]},s),n)}function rn(t,e){let n,r=new Map,o=(s,i,a)=>{let u=!1,d=c=>{let l=r.get(c);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 c.cache}u=!0;let p=n._addDep(c);return r.set(c,p),c.cache};try{let c=t(d,a);u||(i.emit(c),a.store.__autoTrackLastDiscoveryError!=null&&delete a.store.__autoTrackLastDiscoveryError)}catch(c){if(!u)throw c;a.store.__autoTrackLastDiscoveryError=c}};return n=new Ae([],o,{describeKind:"derived",...e}),n}function oa(t,...e){let n=t;for(let r of e)n=r(n);return n}var ee=tt(()=>{"use strict";_e()});function Lr(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,d;if(s==="*")u=e,d=n;else if(s.includes("-")){let[c,l]=s.split("-");u=Number.parseInt(c,10),d=Number.parseInt(l,10)}else u=Number.parseInt(s,10),d=u;if(Number.isNaN(u)||Number.isNaN(d))throw new Error(`Invalid cron field: ${t}`);if(u<e||d>n)throw new Error(`Cron field out of range: ${t} (${e}-${n})`);if(u>d)throw new Error(`Invalid cron range: ${u}-${d} in ${t}`);for(let c=u;c<=d;c+=a)r.add(c)}return r}function Vo(t){let e=t.trim().split(/\s+/);if(e.length!==5)throw new Error(`Invalid cron: expected 5 fields, got ${e.length}`);return{minutes:Lr(e[0],0,59),hours:Lr(e[1],0,23),daysOfMonth:Lr(e[2],1,31),months:Lr(e[3],1,12),daysOfWeek:Lr(e[4],0,6)}}function Ko(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 aa=tt(()=>{"use strict"});var Md={};ke(Md,{NS_PER_MS:()=>He,NS_PER_SEC:()=>at,constant:()=>qo,decorrelatedJitter:()=>Uo,exponential:()=>Wo,fibonacci:()=>zo,linear:()=>Ho,resolveBackoffPreset:()=>Bt,withMaxAttempts:()=>ua});function sn(t){return t<0?0:t}function rm(t,e){return e==="none"?t:e==="full"?Math.random()*t:t/2+Math.random()*(t/2)}function om(t,e){return t+Math.random()*(e-t)}function qo(t){let e=sn(t);return()=>e}function Ho(t,e){let n=sn(t),r=e===void 0?n:sn(e);return o=>n+r*Math.max(0,o)}function Wo(t){let e=sn(t?.baseNs??1e8),n=t?.factor!==void 0&&t.factor<1?1:t?.factor??2,r=sn(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 d=0;d<Math.max(0,s);d++){if(u>=a){u=a;break}u*=n}i=e*u,i>r&&(i=r)}return rm(i,o)}}function zo(t=100*1e6,e=30*1e9){let n=sn(t),r=sn(e);function o(s){if(s<=0)return 1;let i=1,a=2;for(let u=1;u<s;u++){let d=i+a;i=a,a=d}return a}return s=>{let i=o(s)*n;return i<=r?i:r}}function Uo(t=100*1e6,e=30*1e9){return(n,r,o)=>{let i=Math.min(e,(o??t)*3);return om(t,i)}}function ua(t,e){return(n,r,o)=>n>=e?null:t(n,r,o)}function Bt(t){if(t==="constant")return qo(1*1e9);if(t==="linear")return Ho(1*1e9);if(t==="exponential")return Wo();if(t==="fibonacci")return zo();if(t==="decorrelatedJitter")return Uo();throw new Error(`Unknown backoff preset: "${String(t)}". Use one of: constant, linear, exponential, fibonacci, decorrelatedJitter`)}var He,at,Vn=tt(()=>{"use strict";He=1e6,at=1e9});var Le,vt=tt(()=>{"use strict";Le=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 Cd={};ke(Cd,{CircuitOpenError:()=>pt,RateLimiterOverflowError:()=>an,TimeoutError:()=>un,circuitBreaker:()=>wt,fallback:()=>Hn,rateLimiter:()=>qn,retry:()=>Tt,timeout:()=>Wn,tokenBucket:()=>Vt,withBreaker:()=>Kn,withStatus:()=>Kt});function dn(t){return{describeKind:"derived",...t}}function sm(t){return t<0?0:t}function Jo(t){return t[1]}function Od(t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("backoff strategy must return a finite number");return t<0?0:t}function Tt(t,e){return typeof t=="function"?am(t,e):im(t,e)}function im(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"?Bt(r):r;return K(i=>{let a=0,u=!1,d=null,c,l=new Le;function p(){c?.(),c=void 0}function f(h){if(u)return;if(a>=o){p(),i.down([[C,h]]);return}let g=s===null?0:s(a,h,d);if(g==null){p(),i.down([[C,h]]);return}let y;try{y=Od(g)}catch{p(),i.down([[C,h]]);return}d=y,a+=1,p();let b=y>0?y/1e6:1;l.start(b,()=>{u||m()})}function m(){l.cancel(),p(),c=t.subscribe(h=>{if(!u)for(let g of h){let y=g[0];if(y===ne)i.down([[ne]]);else if(y===E)a=0,d=null,i.emit(g[1]);else if(y===V)i.down([[V]]);else if(y===L)p(),i.down([[L]]);else if(y===C){f(Jo(g));return}else i.down([g])}})}return m(),()=>{u=!0,l.cancel(),p()}},{...dn(),initial:t.cache})}function am(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"?Bt(r):r;return K(i=>{let a=0,u=!1,d=null,c,l=new Le;function p(){c?.(),c=void 0}function f(h){if(u)return;if(a>=o){p(),i.down([[C,h]]);return}let g=s===null?0:s(a,h,d);if(g==null){p(),i.down([[C,h]]);return}let y;try{y=Od(g)}catch{p(),i.down([[C,h]]);return}d=y,a+=1,p();let b=y>0?y/1e6:1;l.start(b,()=>{u||m()})}function m(){l.cancel(),p();let h;try{h=t()}catch(g){f(g);return}c=h.subscribe(g=>{if(!u)for(let y of g){let b=y[0];if(b===ne)i.down([[ne]]);else if(b===E)a=0,d=null,i.emit(y[1]);else if(b===V)i.down([[V]]);else if(b===L)p(),i.down([[L]]);else if(b===C){f(Jo(y));return}else i.down([y])}})}return m(),()=>{u=!0,l.cancel(),p()}},{...dn(),initial:e?.initial})}function wt(t){let e=Math.max(1,t?.failureThreshold??5),n=sm(t?.cooldownNs??30*1e9),r=t?.cooldown??null,o=Math.max(1,t?.halfOpenMax??1),s=t?.now??H,i="closed",a=0,u=0,d=0,c=n,l=0;function p(){if(!r)return n;let h=r(u);return h!==null?h:n}function f(){i="open",c=p(),d=s(),l=0}return{canExecute(){return i==="closed"?!0:i==="open"?s()-d>=c?(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++,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 Kn(t,e){let n=e?.onOpen??"skip";return r=>{let o=z([],(s,i)=>{function a(){o.meta.breakerState.down([[E,t.state]])}let u=r.subscribe(d=>{for(let c of d){let l=c[0];l===ne?i.down([[ne]]):l===E?t.canExecute()?(a(),i.emit(c[1])):(a(),n==="error"?i.down([[C,new pt]]):i.down([[V]])):l===V?i.down([[V]]):l===L?(t.recordSuccess(),a(),i.down([[L]])):l===C?(t.recordFailure(Jo(c)),a(),i.down([c])):i.down([c])}});return a(),u},{...dn(),meta:{breakerState:t.state},completeWhenDepsComplete:!1,initial:r.cache});return{node:o,breakerState:o.meta.breakerState}}}function Vt(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=H();function o(s){if(e>0){let i=s-r;n=Math.min(t,n+i/1e9*e)}r=s}return{available(){return o(H()),n},tryConsume(s=1){if(s<=0)return!0;let i=H();return o(i),n>=s?(n-=s,!0):!1},putBack(s=1){s<=0||(o(H()),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 K(a=>{let u=Vt(n,i),d=[],c=new Le,l=!1,p=1e9/i;function f(){for(;d.length>0;)if(u.tryConsume(1))a.emit(d.shift());else{c.start(Math.max(1,p/1e6),f);return}}let m=t.subscribe(h=>{for(let g of h){if(l)return;let y=g[0];if(y===ne)a.down([[ne]]);else if(y===E){if(o!==void 0&&d.length>=o){if(s!=="drop-newest")if(s==="drop-oldest")d.shift(),d.push(g[1]);else{l=!0,c.cancel(),d.length=0,a.down([[C,new an(o)]]);return}}else d.push(g[1]);f()}else if(y===V)a.down([[V]]);else if(y===L)l=!0,c.cancel(),d.length=0,a.down([[L]]);else if(y===C)l=!0,c.cancel(),d.length=0,a.down([g]);else if(y===le){l=!0,c.cancel(),d.length=0,a.down([g]);return}else a.down([g])}});return()=>{l=!0,c.cancel(),m()}},{...dn(),initial:t.cache})}function Kt(t,e){let n=e?.initialStatus??"pending",r=z([],(o,s)=>{let i=n;return r.meta.status.down([[E,n]]),r.meta.error.down([[E,null]]),t.subscribe(u=>{for(let d of u){let c=d[0];if(c===ne)s.down([[ne]]);else if(c===E)i==="errored"?X(()=>{r.meta.error.down([[E,null]]),r.meta.status.down([[E,"active"]])}):r.meta.status.down([[E,"active"]]),i="active",s.emit(d[1]);else if(c===V)s.down([[V]]);else if(c===L)r.meta.status.down([[E,"completed"]]),i="completed",s.down([[L]]);else if(c===C){let l=Jo(d);X(()=>{r.meta.error.down([[E,l]]),r.meta.status.down([[E,"errored"]])}),i="errored",s.down([d])}else s.down([d])}})},{...dn(),meta:{status:n,error:null},completeWhenDepsComplete:!1,resubscribable:!0,initial:t.cache});return{node:r,status:r.meta.status,error:r.meta.error}}function um(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function dm(t){return t!=null&&typeof t.then=="function"}function cm(t){return t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function"}function Hn(t,e){return K(n=>{let r,o;function s(){o?.(),o=void 0,um(e)||dm(e)||cm(e)?r=U(e).subscribe(a=>{n.down(a)}):(n.emit(e),n.down([[L]]))}return o=t.subscribe(i=>{for(let a of i){let u=a[0];if(u===ne)n.down([[ne]]);else if(u===E)n.emit(a[1]);else if(u===V)n.down([[V]]);else if(u===L)n.down([[L]]);else if(u===C){s();return}else if(u===le){r?.(),n.down([a]);return}else n.down([a])}}),()=>{o?.(),r?.()}},{...dn(),initial:t.cache})}function Wn(t,e){if(e<=0)throw new RangeError("timeoutNs must be > 0");return K(n=>{let r=!1,o=new Le;function s(){let a=e/1e6;o.start(a,()=>{r||(r=!0,i(),n.down([[C,new un(e)]]))})}let i=t.subscribe(a=>{for(let u of a){if(r)return;let d=u[0];if(d===ne)n.down([[ne]]);else if(d===E)s(),n.emit(u[1]);else if(d===V)n.down([[V]]);else if(d===L){o.cancel(),r=!0,n.down([[L]]);return}else if(d===C){o.cancel(),r=!0,n.down([u]);return}else if(d===le){o.cancel(),r=!0,n.down([u]);return}else n.down([u])}});return s(),()=>{r=!0,o.cancel(),i()}},{...dn(),initial:t.cache})}var pt,an,un,Ot=tt(()=>{"use strict";Me();xe();ae();_e();ee();Vn();he();vt();pt=class extends Error{name="CircuitOpenError";constructor(){super("Circuit breaker is open")}};an=class extends Error{name="RateLimiterOverflowError";constructor(e){super(`rateLimiter buffer overflow (maxBuffer=${e})`)}};un=class extends Error{name="TimeoutError";constructor(e){super(`Timed out after ${e/1e6}ms`)}}});function ut(t){return{describeKind:"producer",...t}}function ca(t){return/[\\^$+?.()|[\]{}]/.test(t)?`\\${t}`:t}function Ld(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+=ca(r)}return e+="$",new RegExp(e)}function Id(t,e){for(let n of e)if(n.test(t))return!0;return!1}function lm(t,e){let n=z([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[V]]);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 st(t,e){let{signal:n,period:r,...o}=e??{};return K(s=>{let i=!1,a=0,u,d,c=()=>{i=!0,u!==void 0&&clearTimeout(u),d!==void 0&&clearInterval(d),n?.removeEventListener("abort",p)},l=()=>{i||(r!=null?(s.emit(a++),d=setInterval(()=>{i||s.emit(a++)},r)):(i=!0,n?.removeEventListener("abort",p),s.emit(a++),s.down([[L]])))},p=()=>{i||(c(),s.down([[C,n.reason]]))};if(n?.aborted){p();return}return u=setTimeout(l,t),n?.addEventListener("abort",p,{once:!0}),c},ut(o))}function Pd(t){let{signal:e,...n}=t??{};return K(r=>{let o=!1,s,i,a=!1,u=!1,d=typeof requestAnimationFrame=="function"?requestAnimationFrame:void 0,c=typeof cancelAnimationFrame=="function"?cancelAnimationFrame:void 0,l=typeof document<"u"?document:void 0,p=()=>{s!==void 0&&c&&c(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([[C,e.reason]]))},h=b=>{o||(r.emit(b),g())},g=()=>{o||(d&&(!l||l.visibilityState!=="hidden")?s=d(h):i=setTimeout(()=>h(performance.now()),16))},y=()=>{o||(p(),g())};return e?.aborted?(m(),f):(e?.addEventListener("abort",m,{once:!0}),a=e!==void 0,l&&d&&(l.addEventListener("visibilitychange",y),u=!0),g(),f)},ut(n))}function Qo(t,e){let n=Vo(t),{tickMs:r,output:o,...s}=e??{},i=r??6e4,a=o==="date";return K(u=>{let d=-1,c=()=>{let p=new Date,f=p.getFullYear()*1e8+(p.getMonth()+1)*1e6+p.getDate()*1e4+p.getHours()*100+p.getMinutes();f!==d&&Ko(n,p)&&(d=f,u.emit(a?p:oe()))};c();let l=setInterval(c,i);return()=>clearInterval(l)},{...ut(s),name:s.name??`cron:${t}`})}function Dd(t,e,n){let{capture:r,passive:o,once:s,...i}=n??{};return K(a=>{let u=c=>{a.emit(c)},d={capture:r,passive:o,once:s};return t.addEventListener(e,u,d),()=>t.removeEventListener(e,u,d)},ut(i))}function Xo(t,e){return K(n=>{let r=!1;try{for(let o of t){if(r)return;n.emit(o)}r||n.down([[L]])}catch(o){r||n.down([[C,o]])}return()=>{r=!0}},ut(e))}function pm(t){return t!=null&&typeof t.then=="function"}function zn(t,e){let{signal:n,...r}=e??{};return K(o=>{let s=!1,i=()=>{s||(s=!0,o.down([[C,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([[L]]))},a=>{s||(s=!0,n?.removeEventListener("abort",i),o.down([[C,a]]))}),()=>{s=!0,n?.removeEventListener("abort",i)}},ut(r))}function Ir(t,e){let{signal:n,...r}=e??{};return K(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,d=t[Symbol.asyncIterator](),c=()=>{u||a.aborted||Promise.resolve(d.next()).then(l=>{if(!(u||a.aborted)){if(l.done){o.down([[L]]);return}o.emit(l.value),c()}},l=>{!u&&!a.aborted&&o.down([[C,l]])})};return c(),()=>{u=!0,n?.removeEventListener("abort",i),s.abort(),Promise.resolve(d.return?.()).catch(()=>{})}},ut(r))}function fm(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function U(t,e){if(fm(t))return t;if(pm(t))return zn(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return Ir(t,e);if(typeof n[Symbol.iterator]=="function")return Xo(t,e)}return la(t)}function la(...t){return Xo(t,void 0)}function Gd(t){return K(e=>{e.down([[L]])},ut(t))}function Fd(t){return K(()=>{},ut(t))}function $d(t,e){return K(n=>{n.down([[C,t]])},ut(e))}function jd(t,e){let{signal:n,...r}=e??{},o=ut(r),s=o.resubscribable===void 0?{...o,resubscribable:!0}:o;return K(i=>{let a,u=!1;try{let d=t();a=U(d,e).subscribe(l=>{if(!u)for(let p of l){let f=p[0];if(f!==dt)if(f===E)i.emit(p[1]);else if(f===L){u=!0,i.down([[L]]);break}else if(f===C){u=!0,i.down([[C,p[1]]]);break}else i.down([p])}})}catch(d){let c=d===void 0?new Error("defer: thunk threw undefined"):d;i.down([[C,c]])}return()=>{u=!0,a?.()}},s)}function qt(t,e,n){return z([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 Bd(t,e){return z([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([[L]]);return}(i==null||i.length===0)&&r.down([[V]])},{describeKind:"derived",completeWhenDepsComplete:!1,...e})}function Vd(t,e){return K(n=>t.subscribe(r=>{n.down(r)}),{...ut(e),initial:t.cache})}function Zo(t,e,n){if(e<1)throw new RangeError("replay expects bufferSize >= 1");let r=[],o=K(s=>t.subscribe(i=>{for(let a of i)a[0]===E&&(r.push(a[1]),r.length>e&&r.shift());s.down(i)}),{...ut(n),initial:t.cache});return lm(o,s=>{for(let i of r)s([[E,i]])})}function Kd(t,e){return Zo(t,1,e)}function Ye(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]===E){r=!0,e(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===C){r=!0,n(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===L){r=!0,n(new Error("completed without DATA")),s?(s(),s=void 0):o=!0;return}}}),o&&(s?.(),s=void 0)})}function Yo(t,e,n){return new Promise((r,o)=>{let s=!1,i=!1,a,u=n?.skipCurrent===!0;a=t.subscribe(d=>{for(let c of d){if(s)return;if(!(u&&c[0]===E)){if(c[0]===E){let l=c[1];if(e(l)){s=!0,r(l),a?(a(),a=void 0):i=!0;return}}if(c[0]===C){s=!0,o(c[1]),a?(a(),a=void 0):i=!0;return}if(c[0]===L){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 es(t,e){let n=e?.predicate??(s=>s!=null),r=e?.skipCurrent;if(e?.timeoutMs==null||e.timeoutMs<=0)return await Yo(t,n,{skipCurrent:r});if(da===void 0){let[s,i]=await Promise.all([Promise.resolve().then(()=>(Ot(),Cd)),Promise.resolve().then(()=>(Vn(),Md))]);da=s.timeout,Ad=i.NS_PER_MS}let o=da(t,e.timeoutMs*Ad);return await Yo(o,n,{skipCurrent:r})}function ts(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]===E&&u[1]===!0){n.abort(r),i();return}if(u[0]===C){n.abort(u[1]),i();return}if(u[0]===L){i();return}}}),s&&(o?.(),o=void 0),{signal:n.signal,dispose:()=>{o&&(o(),o=void 0)}}}function re(t){return t.subscribe(()=>{})}function pa(t){let e=M(0);return{node:e,increment(){let n=e.cache??0;return n>=t?!1:(e.down([[ne],[E,n+1]]),!0)},get(){return e.cache??0},atCap(){return(e.cache??0)>=t}}}var da,Ad,qd,he=tt(()=>{"use strict";xe();ae();_e();ee();aa();qd=Zo});var Kb={};ke(Kb,{COMPLETE:()=>L,COMPLETE_MSG:()=>Oo,COMPLETE_ONLY_BATCH:()=>br,CircuitOpenError:()=>pt,ContentAddressedMissError:()=>eo,DATA:()=>E,DEFAULT_ACTOR:()=>bt,DIRTY:()=>ne,DIRTY_MSG:()=>Et,DIRTY_ONLY_BATCH:()=>Mn,ENVELOPE_VERSION:()=>Cn,ERROR:()=>C,GRAPH_META_SEGMENT:()=>Qe,Graph:()=>Y,GraphReFlyConfig:()=>nn,GuardDenied:()=>rt,INVALIDATE:()=>Je,INVALIDATE_MSG:()=>Mo,INVALIDATE_ONLY_BATCH:()=>yr,JsonCodec:()=>Ao,NS_PER_MS:()=>He,NS_PER_SEC:()=>at,NativeIndexBackend:()=>ro,NativeListBackend:()=>oo,NativeLogBackend:()=>jr,NativeMapBackend:()=>Xr,NativePubSubBackend:()=>no,NodeImpl:()=>Ae,PAUSE:()=>Be,RESOLVED:()=>V,RESOLVED_MSG:()=>Nn,RESOLVED_ONLY_BATCH:()=>hr,RESUME:()=>qe,RateLimiterOverflowError:()=>an,ResettableTimer:()=>Le,SIZEOF_OVERHEAD:()=>je,SIZEOF_SYMBOL:()=>ds,SNAPSHOT_VERSION:()=>ft,SNAPSHOT_WIRE_VERSION:()=>No,START:()=>dt,START_MSG:()=>_n,SurfaceError:()=>Ne,TEARDOWN:()=>le,TEARDOWN_MSG:()=>Co,TEARDOWN_ONLY_BATCH:()=>On,TimeoutError:()=>un,accessHintForGuard:()=>_r,accountability:()=>yi,advanceVersion:()=>Mr,ai:()=>mi,appendLogStorage:()=>Ka,asSurfaceError:()=>Fi,audit:()=>zc,autoTrackNode:()=>rn,awaitSettled:()=>es,batch:()=>X,buffer:()=>Uc,bufferCount:()=>Jc,bufferTime:()=>Qc,cached:()=>Kd,canonicalJson:()=>to,cascadingCache:()=>sp,catchError:()=>al,checkpointToRedis:()=>Ql,checkpointToS3:()=>Yl,circuitBreaker:()=>wt,combine:()=>Aa,combineLatest:()=>ol,compat:()=>Oa,concat:()=>jc,concatMap:()=>Kc,configure:()=>ra,constant:()=>qo,contentAddressedStorage:()=>Ps,core:()=>va,cqrs:()=>Ts,createDagCborCodec:()=>Ji,createDagCborZstdCodec:()=>Yi,createGraph:()=>pr,createTransport:()=>Jt,createVersioning:()=>In,createWatermarkController:()=>Un,csvRows:()=>Al,debounce:()=>Ia,debounceTime:()=>sl,decodeEnvelope:()=>Tr,decorrelatedJitter:()=>Uo,defaultConfig:()=>$e,defaultHash:()=>jt,defer:()=>jd,delay:()=>Hc,deleteSnapshot:()=>Hi,demoShell:()=>vi,derived:()=>A,deserializeError:()=>yn,dictKv:()=>bp,dictSnapshot:()=>vp,diffForWAL:()=>fs,diffSnapshots:()=>Ki,distill:()=>Ls,distinctUntilChanged:()=>Gc,domainTemplates:()=>Ti,downWithBatch:()=>_t,dynamicNode:()=>Or,effect:()=>pe,elementAt:()=>Ic,empty:()=>Gd,encodeEnvelope:()=>vr,escapeRegexChar:()=>ca,exhaustMap:()=>Vc,explainPath:()=>Gr,exponential:()=>Wo,externalBundle:()=>Os,externalProducer:()=>mn,extra:()=>Wa,fallback:()=>Hn,fibonacci:()=>zo,filter:()=>Xe,find:()=>Lc,first:()=>Cs,firstValueFrom:()=>Ye,firstWhere:()=>Yo,flatMap:()=>qc,forEach:()=>qt,fromAny:()=>U,fromAsyncIter:()=>Ir,fromCSV:()=>Cl,fromClickHouseWatch:()=>Dl,fromCron:()=>Qo,fromDrizzle:()=>np,fromEvent:()=>Dd,fromHTTP:()=>$a,fromHTTPPoll:()=>yl,fromHTTPStream:()=>hl,fromIter:()=>Xo,fromKafka:()=>Nl,fromKysely:()=>rp,fromMCP:()=>Tl,fromNATS:()=>$l,fromNDJSON:()=>Pl,fromOTel:()=>wl,fromPrisma:()=>tp,fromPrometheus:()=>El,fromPromise:()=>zn,fromPulsar:()=>Gl,fromRabbitMQ:()=>Bl,fromRaf:()=>Pd,fromRedisStream:()=>Ml,fromSSE:()=>gl,fromSqlite:()=>Xl,fromSqliteCursor:()=>Zl,fromStatsD:()=>Rl,fromSyslog:()=>kl,fromTimer:()=>st,fromWebSocket:()=>Fa,fromWebSocketReconnect:()=>vl,fromWebhook:()=>ul,globToRegExp:()=>Ld,graph:()=>ka,graphProfile:()=>pn,graphspec:()=>fi,guarded:()=>ki,harness:()=>Ai,interval:()=>el,isBatching:()=>tn,isV1:()=>ea,jobQueue:()=>Oi,jotai:()=>Do,jsonCodec:()=>tr,jsonCodecFor:()=>gp,keepalive:()=>re,kvStorage:()=>js,last:()=>Ac,layout:()=>Di,lens:()=>Ii,linear:()=>Ho,listSnapshots:()=>qi,lru:()=>Va,makeHttpError:()=>ht,map:()=>zr,matchesAnyPattern:()=>Id,matchesCron:()=>Ko,memory:()=>ci,memoryAppendLog:()=>yp,memoryBackend:()=>io,memoryKv:()=>ao,memorySnapshot:()=>hp,merge:()=>xt,mergeMap:()=>La,mergeReactiveLogs:()=>bc,mermaidLiveUrl:()=>ps,messaging:()=>oi,monotonicNs:()=>H,nameToSignal:()=>gn,nanostores:()=>jo,ndjsonRows:()=>Ll,nestjs:()=>ks,never:()=>Fd,node:()=>z,nodeSignal:()=>ts,normalizeActor:()=>Nt,of:()=>la,onFirstData:()=>Jr,orchestration:()=>si,pairwise:()=>Fc,parseCron:()=>Vo,parsePrometheusText:()=>ja,parseSSEStream:()=>Dt,parseStatsD:()=>Sl,parseSyslog:()=>xl,patterns:()=>Qu,pausable:()=>nl,pipe:()=>oa,policy:()=>Mt,policyFromRules:()=>Nr,process:()=>Pi,producer:()=>K,pubsub:()=>cp,race:()=>Bc,rateLimiter:()=>qn,reachable:()=>fn,react:()=>xs,reactiveCounter:()=>pa,reactiveIndex:()=>fp,reactiveList:()=>Ds,reactiveLog:()=>Ve,reactiveMap:()=>Ze,reactiveSink:()=>We,reduce:()=>Mc,reduction:()=>pi,refine:()=>Si,registerBuiltinCodecs:()=>wr,registerBuiltins:()=>Er,repeat:()=>tl,replay:()=>Zo,replayWAL:()=>Qi,rescue:()=>Yr,resilientPipeline:()=>Gi,resolveBackoffPreset:()=>Bt,resolveDescribeFields:()=>Ct,restoreSnapshot:()=>Vi,retry:()=>Tt,runReduction:()=>$i,sample:()=>Wc,saveSnapshot:()=>Bi,scan:()=>_c,serializeError:()=>hn,share:()=>Vd,shareReplay:()=>qd,signalToName:()=>Ut,signals:()=>Ss,singleFromAny:()=>Gs,singleNodeFromAny:()=>mp,sizeof:()=>Fr,skip:()=>Ca,snapshotStorage:()=>$s,solid:()=>Es,sortJsonValue:()=>so,stableJsonString:()=>Fs,state:()=>M,stratify:()=>uo,surface:()=>Wi,svelte:()=>Ns,switchMap:()=>Te,take:()=>Ur,takeUntil:()=>Cc,takeWhile:()=>Oc,tap:()=>Pc,tapFirst:()=>Dc,throttle:()=>Pa,throttleTime:()=>il,throwError:()=>$d,timeout:()=>Wn,toArray:()=>Bd,toCSV:()=>Kl,toClickHouse:()=>ql,toFile:()=>Ba,toHTTP:()=>dl,toKafka:()=>_l,toLoki:()=>Ul,toMongo:()=>zl,toNATS:()=>jl,toObservable:()=>Bo,toPostgres:()=>Wl,toPulsar:()=>Fl,toRabbitMQ:()=>Vl,toReadableStream:()=>ml,toRedisStream:()=>Ol,toS3:()=>Hl,toSSE:()=>pl,toSSEBytes:()=>fl,toSqlite:()=>ep,toTempo:()=>Jl,toWebSocket:()=>bl,tokenBucket:()=>Vt,validateGraphObservability:()=>wa,valve:()=>rl,verifiable:()=>up,version:()=>Vb,vue:()=>_s,wallClockNs:()=>oe,watchTopologyTree:()=>At,window:()=>Zc,windowCount:()=>Yc,windowTime:()=>Xc,withBreaker:()=>Kn,withLatestFrom:()=>Pt,withMaxAttempts:()=>ua,withStatus:()=>Kt,workerBridge:()=>qa,workerSelf:()=>Ha,zip:()=>$c,zustand:()=>Ms});module.exports=Pf(Kb);var Oa={};ke(Oa,{jotai:()=>Do,nanostores:()=>jo,nestjs:()=>ks,react:()=>xs,signals:()=>Ss,solid:()=>Es,svelte:()=>Ns,vue:()=>_s,zustand:()=>Ms});var Do={};ke(Do,{atom:()=>Jf});ae();ee();function Jf(t,e,n){if(typeof t=="function"){let r=t;return typeof e=="function"?md(r,e,n):md(r,void 0,e)}return Yf(t,e)}function Cr(t){let e=t.cache,n;if(t.subscribe(o=>{for(let[s,i]of o)s===E&&(e=i),s===C&&(n=i)})(),n)throw n;return e}function Yf(t,e){let n=M(t,{...e,resubscribable:!0,resetOnTeardown:!0});return{get:()=>n.status==="sentinel"?Cr(n):n.cache,set:r=>n.emit(r),update:r=>{let o=n.status==="sentinel"?Cr(n):n.cache;n.emit(r(o))},subscribe:r=>{let o=!0;return n.subscribe(s=>{for(let[i,a]of s)if(i===E){if(o){o=!1;continue}r(a)}})},meta:n.meta,_node:n}}function md(t,e,n){let r=rn(s=>t(i=>{let a=i._node;return a.status==="sentinel"&&Cr(a),s(a)}),{...n,resubscribable:!0,resetOnTeardown:!0}),o={get:()=>r.status==="sentinel"?Cr(r):r.cache,subscribe:s=>{let i=!0;return r.subscribe(a=>{for(let[u,d]of a)if(u===E){if(i){i=!1;continue}s(d)}})},meta:r.meta,_node:r};if(e){let s=u=>u.get(),i=(u,d)=>u.set(d),a=o;return a.set=u=>e(s,i,u),a.update=u=>{let d=r.status==="sentinel"?Cr(r):r.cache;return e(s,i,u(d))},a}return o}var jo={};ke(jo,{action:()=>nm,atom:()=>Qf,computed:()=>Xf,getValue:()=>em,map:()=>Zf,onMount:()=>tm,onStart:()=>yd,onStop:()=>bd});Me();ae();ee();var Fo=new WeakMap,$o=new WeakMap;function Go(t,e){let n=e.get(t);if(n)for(let r of n)r()}function sa(t,e={}){let n=0;return{...e,get:()=>hd(t),subscribe:o=>{n===0&&Go(t,Fo),n++;let s=t.subscribe(i=>{for(let[a,u]of i)a===E&&o(u)});return()=>{s(),n--,n===0&&Go(t,$o)}},listen:o=>{n===0&&Go(t,Fo),n++;let s=!0,i=t.subscribe(a=>{for(let[u,d]of a)if(u===E){if(s){s=!1;continue}o(d)}});return()=>{i(),n--,n===0&&Go(t,$o)}},_node:t}}function gd(t){let e=t.cache,n;if(t.subscribe(o=>{for(let[s,i]of o)s===E&&(e=i),s===C&&(n=i)})(),n)throw n;return e}function hd(t){return t.status==="sentinel"?gd(t):t.cache}function Qf(t){let e=M(t,{resubscribable:!0,resetOnTeardown:!0});return sa(e,{set:n=>e.emit(n)})}function Xf(t,e){let n=Array.isArray(t)?t:[t],r=n.map(s=>s._node),o=Or(r,s=>{let i=n.map(a=>{let u=a._node;return u.status==="sentinel"&&gd(u),s(u)});return e(...i)},{resubscribable:!0,resetOnTeardown:!0,equals:Object.is});return sa(o)}function Zf(t){let e=M(t,{resubscribable:!0,resetOnTeardown:!0,equals:()=>!1});return sa(e,{set:n=>e.emit(n),setKey:(n,r)=>{let o=hd(e);e.emit({...o,[n]:r})}})}function em(t){return t.get()}function yd(t,e){let n=t._node,r=Fo.get(n);r||(r=new Set,Fo.set(n,r)),r.add(e)}function bd(t,e){let n=t._node,r=$o.get(n);r||(r=new Set,$o.set(n,r)),r.add(e)}function tm(t,e){yd(t,()=>{let n=e();typeof n=="function"&&bd(t,n)})}function nm(t,e,n){return(...r)=>{let o;return X(()=>{o=n(...r)}),o}}var ks={};ke(ks,{ACTOR_KEY:()=>rs,COMMAND_HANDLERS:()=>Fn,CQRS_EVENT_HANDLERS:()=>$n,CRON_HANDLERS:()=>Gn,CommandHandler:()=>Sd,EVENT_HANDLERS:()=>Pn,EventHandler:()=>Ed,GRAPHREFLY_REQUEST_GRAPH:()=>on,GRAPHREFLY_ROOT_GRAPH:()=>ct,GraphCron:()=>Rd,GraphInterval:()=>xd,GraphReflyEventExplorer:()=>cn,GraphReflyGuard:()=>Yd,GraphReflyGuardImpl:()=>Pr,GraphReflyModule:()=>ws,INTERVAL_HANDLERS:()=>Dn,InjectCqrsGraph:()=>Td,InjectGraph:()=>vd,InjectNode:()=>wd,ObserveGateway:()=>ns,OnGraphEvent:()=>kd,QUERY_HANDLERS:()=>jn,QueryHandler:()=>Nd,SAGA_HANDLERS:()=>Bn,SagaHandler:()=>_d,fromHeader:()=>Ud,fromJwtPayload:()=>ga,getActor:()=>Jd,getGraphToken:()=>ot,getNodeToken:()=>lt,observeSSE:()=>Wd,observeSubscription:()=>zd,toObservable:()=>Bo});var ia=require("rxjs");ae();function Bo(t,e){return e?.raw?new ia.Observable(n=>t.subscribe(o=>{if(!n.closed){n.next(o);for(let s of o){if(s[0]===C){n.error(s[1]);return}if(s[0]===L){n.complete();return}}}})):new ia.Observable(n=>t.subscribe(o=>{for(let s of o){if(n.closed)return;if(s[0]===E)n.next(s[1]);else if(s[0]===C){n.error(s[1]);return}else if(s[0]===L){n.complete();return}}}))}var Ar=require("@nestjs/common");var ct=Symbol.for("graphrefly:root-graph");var on=Symbol.for("graphrefly:request-graph");function ot(t){return Symbol.for(`graphrefly:graph:${t}`)}function lt(t){return Symbol.for(`graphrefly:node:${t}`)}var Pn=new Map,Dn=new Map,Gn=new Map,Fn=new Map,$n=new Map,jn=new Map,Bn=new Map;function vd(t){return t==="request"?(0,Ar.Inject)(on):(0,Ar.Inject)(t?ot(t):ct)}function Td(t){return(0,Ar.Inject)(ot(t))}function wd(t){return(0,Ar.Inject)(lt(t))}function kd(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 xd(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=Dn.get(o)??[];s.push({ms:t,methodKey:r}),Dn.set(o,s)})}}function Rd(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=Gn.get(o)??[];s.push({expr:t,methodKey:r}),Gn.set(o,s)})}}function Sd(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=Fn.get(s)??[];i.push({cqrsName:t,commandName:e,methodKey:o}),Fn.set(s,i)})}}function Ed(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=$n.get(s)??[];i.push({cqrsName:t,eventName:e,methodKey:o}),$n.set(s,i)})}}function Nd(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 _d(t,e,n){return(r,o)=>{let s=o.name;o.addInitializer(function(){let i=this.constructor,a=Bn.get(i)??[];a.push({cqrsName:t,eventNames:n,sagaName:e,methodKey:s}),Bn.set(i,a)})}}ae();he();var Hd=0,cn=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]===E&&o(u[1])});this.disposers.push(i)}wireIntervals(){for(let[e,n]of Dn){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)}.${Hd++}`,u=st(r.ms,{period:r.ms,name:a});this.graph.add(u),this.scheduleNodeNames.push(a);let c=this.observeNode(a).subscribe(l=>{for(let p of l)p[0]===E&&s(p[1])});this.disposers.push(c)}wireCrons(){for(let[e,n]of Gn){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)}.${Hd++}`,u=Qo(r.expr,{name:a});this.graph.add(u),this.scheduleNodeNames.push(a);let c=this.observeNode(a).subscribe(l=>{for(let p of l)p[0]===E&&s(p[1])});this.disposers.push(c)}wireCqrsCommands(){for(let[e,n]of Fn){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 $n){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,c=this.observeNodeOn(s,n.eventName).subscribe(l=>{for(let p of l)if(p[0]===E){let f=p[1];for(let m of f)m.seq>u&&(o(m),u=m.seq)}});this.disposers.push(c)}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 d of u)d[0]===E&&o(d[1])});this.disposers.push(a)}wireCqrsSagas(){for(let[e,n]of Bn){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(ot(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}}};ae();ae();var mm=0;function Un(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-${++mm}`),r=0,o=!1;return{onEnqueue(){return r+=1,!o&&r>=e.highWaterMark?(o=!0,t([[Be,n]]),!0):!1},onDequeue(){return r>0&&(r-=1),o&&r<=e.lowWaterMark?(o=!1,t([[qe,n]]),!0):!1},get pending(){return r},get paused(){return o},dispose(){o&&(o=!1,t([[qe,n]]))}}}function Wd(t,e,n){let{actor:r,serialize:o=gm,keepAliveMs:s,signal:i}=n??{},a=new TextEncoder,u,d=n?.highWaterMark!=null,c,l,p=[],f=!1;return new ReadableStream({start(m){let h,g=()=>{},y=()=>{if(!f){f=!0,h!==void 0&&clearInterval(h),i?.removeEventListener("abort",b),g(),c?.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});d&&(c=Un(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(f)return;let x=w[0];if(x===E){let k=a.encode(fa("data",o(w[1])));d?(p.push({frame:k,counted:!0}),c.onEnqueue(),l?.(),l=void 0):m.enqueue(k)}else if(x===C){let k=a.encode(fa("error",o(w[1])));d?(p.push({frame:k,counted:!1}),l?.(),l=void 0):m.enqueue(k),y();return}else if(x===L||x===le){if(x===L){let k=a.encode(fa("complete"));d?(p.push({frame:k,counted:!1}),l?.(),l=void 0):m.enqueue(k)}y();return}}}),s!==void 0&&s>0&&(h=setInterval(()=>{f||(d?(p.push({frame:a.encode(`: keepalive
1
+ "use strict";var Cf=Object.create;var En=Object.defineProperty;var td=Object.getOwnPropertyDescriptor;var Lf=Object.getOwnPropertyNames;var If=Object.prototype.hasOwnProperty;var nd=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),gr=t=>{throw TypeError(t)};var Pf=(t,e,n)=>e in t?En(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Xu=(t,e)=>En(t,"name",{value:e,configurable:!0});var tt=(t,e)=>()=>(t&&(e=t(t=0)),e);var ke=(t,e)=>{for(var n in e)En(t,n,{get:e[n],enumerable:!0})},Df=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Lf(e))!If.call(t,o)&&o!==n&&En(t,o,{get:()=>e[o],enumerable:!(r=td(e,o))||r.enumerable});return t};var Gf=t=>Df(En({},"__esModule",{value:!0}),t);var rd=t=>[,,,Cf(t?.[nd("metadata")]??null)],od=["class","method","getter","setter","accessor","field","value","get","set"],mr=t=>t!==void 0&&typeof t!="function"?gr("Function expected"):t,Ff=(t,e,n,r,o)=>({kind:od[t],name:e,metadata:r,addInitializer:s=>n._?gr("Already initialized"):o.push(mr(s||null))}),$f=(t,e)=>Pf(e,nd("metadata"),t[3]),sd=(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},id=(t,e,n,r,o,s)=>{var i,a,u,d,c,l=e&7,p=!!(e&8),f=!!(e&16),m=l>3?t.length+1:l?p?1:2:0,h=od[l+5],g=l>3&&(t[m-1]=[]),y=t[m]||(t[m]=[]),b=l&&(!f&&!p&&(o=o.prototype),l<5&&(l>3||!f)&&td(l<4?o:{get[n](){return Zu(this,s)},set[n](T){return ed(this,s,T)}},n));l?f&&l<4&&Xu(s,(l>2?"set ":l>1?"get ":"")+n):Xu(o,n);for(var v=r.length-1;v>=0;v--)d=Ff(l,n,u={},t[3],y),l&&(d.static=p,d.private=f,c=d.access={has:f?T=>jf(o,T):T=>n in T},l^3&&(c.get=f?T=>(l^1?Zu:Bf)(T,o,l^4?s:b.get):T=>T[n]),l>2&&(c.set=f?(T,w)=>ed(T,o,w,l^4?s:b.set):(T,w)=>T[n]=w)),a=(0,r[v])(l?l<4?f?s:b[h]:l>4?void 0:{get:b.get,set:b.set}:o,d),u._=1,l^4||a===void 0?mr(a)&&(l>4?g.unshift(a):l?f?s=a:b[h]=a:o=a):typeof a!="object"||a===null?gr("Object expected"):(mr(i=a.get)&&(b.get=i),mr(i=a.set)&&(b.set=i),mr(i=a.init)&&g.unshift(i));return l||$f(t,o),b&&En(o,n,b),f?l^4?s:b:o};var Ui=(t,e,n)=>e.has(t)||gr("Cannot "+n),jf=(t,e)=>Object(e)!==e?gr('Cannot use the "in" operator on this value'):t.has(e),Zu=(t,e,n)=>(Ui(t,e,"read from private field"),n?n.call(t):e.get(t));var ed=(t,e,n,r)=>(Ui(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),Bf=(t,e,n)=>(Ui(t,e,"access private method"),n);var dt,E,ne,V,Je,Be,qe,de,L,A,Et,Nn,Mo,_n,Oo,Ao,Mn,hr,yr,br,On,ae=tt(()=>{"use strict";dt=Symbol.for("graphrefly/START"),E=Symbol.for("graphrefly/DATA"),ne=Symbol.for("graphrefly/DIRTY"),V=Symbol.for("graphrefly/RESOLVED"),Je=Symbol.for("graphrefly/INVALIDATE"),Be=Symbol.for("graphrefly/PAUSE"),qe=Symbol.for("graphrefly/RESUME"),de=Symbol.for("graphrefly/TEARDOWN"),L=Symbol.for("graphrefly/COMPLETE"),A=Symbol.for("graphrefly/ERROR"),Et=Object.freeze([ne]),Nn=Object.freeze([V]),Mo=Object.freeze([Je]),_n=Object.freeze([dt]),Oo=Object.freeze([L]),Ao=Object.freeze([de]),Mn=Object.freeze([Et]),hr=Object.freeze([Nn]),yr=Object.freeze([Mo]),br=Object.freeze([Oo]),On=Object.freeze([Ao])});function Ji(t){return{name:"dag-cbor",version:1,contentType:"application/dag-cbor",encode:e=>t.encode(e),decode:(e,n)=>t.decode(e)}}function Yi(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 vr(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 Tr(t,e){if(t.length<ad)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${ad})`);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 wr(t){t.registerCodec(Co)}function Qi(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,d]of Object.entries(a))n.nodes[u]=JSON.parse(JSON.stringify(d));for(let u of i.nodesChanged){let d=n.nodes[u.path];d!=null&&(d[u.field]=u.to)}r=s.seq}return n}var Co,An,ad,Lo=tt(()=>{"use strict";Co={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,ad=4});function Nt(t){if(t==null)return bt;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var bt,kr=tt(()=>{"use strict";bt={type:"system",id:""}});function tn(){return Cn>0||xr}function ud(){return Cn>0}function Sr(t){Cn>0?Rr.push(t):t()}function X(t){Cn+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(Cn-=1,Cn===0)if(e){if(!xr){let n=Rr.splice(0);for(let r of n)try{r()}catch{}Zt.length=0,en.length=0,Ln.length=0}}else Vf()}}function Vf(){let t=!xr;t&&(xr=!0);let e=[],n=0;try{for(;Zt.length>0||en.length>0||Ln.length>0||t&&Rr.length>0;){if(t&&Rr.length>0){let s=Rr.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,Ln.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let o=(Zt.length>0?Zt:en.length>0?en:Ln).splice(0);for(let s of o)try{s()}catch(i){e.push(i)}}}finally{t&&(xr=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function _t(t,e,n){if(e.length===0)return;if(e.length===1){let d=n(e[0][0]);if(d<3||!tn()){t(e);return}(d>=5?Ln:d===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 d=e.slice(0,o);t(d)}if(s>o){let d=e.slice(o,s);u?Zt.push(()=>t(d)):t(d)}if(i>s){let d=e.slice(s,i);u?en.push(()=>t(d)):t(d)}if(r>i){let d=e.slice(i,r);u?Ln.push(()=>t(d)):t(d)}}var Cn,xr,Zt,en,Ln,Rr,Me=tt(()=>{"use strict";Cn=0,xr=!1,Zt=[],en=[],Ln=[],Rr=[]});function H(){return Math.trunc(performance.now()*1e6)}function oe(){return Date.now()*1e6}var xe=tt(()=>{"use strict"});function Er(t){t.registerMessageType(dt,{tier:0,wireCrossing:!1}),t.registerMessageType(ne,{tier:1,wireCrossing:!1}),t.registerMessageType(Je,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(Be,{tier:2,wireCrossing:!1}),t.registerMessageType(qe,{tier:2,wireCrossing:!1}),t.registerMessageType(E,{tier:3,wireCrossing:!0}),t.registerMessageType(V,{tier:3,wireCrossing:!0}),t.registerMessageType(L,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(A,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(de,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var nn,Xi=tt(()=>{"use strict";ae();nn=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_rigorRecorder;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=n=>{let r=this._messageTypes.get(n);return r!=null?r.tier:1}}get onMessage(){return this._frozen=!0,this._onMessage}get onSubscribe(){return this._frozen=!0,this._onSubscribe}set onMessage(e){this._assertUnfrozen(),this._onMessage=e}set onSubscribe(e){this._assertUnfrozen(),this._onSubscribe=e}get defaultVersioning(){return this._defaultVersioning}set defaultVersioning(e){this._assertUnfrozen(),this._defaultVersioning=e}get defaultHashFn(){return this._defaultHashFn}set defaultHashFn(e){this._assertUnfrozen(),this._defaultHashFn=e}get inspectorEnabled(){return this._inspectorEnabled}set inspectorEnabled(e){this._inspectorEnabled=e}get globalInspector(){return this._globalInspector}set globalInspector(e){this._globalInspector=e}get rigorRecorder(){return this._rigorRecorder}set rigorRecorder(e){this._rigorRecorder=e}registerMessageType(e,n){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:n.tier,wireCrossing:n.wireCrossing??n.tier>=3,metaPassthrough:n.metaPassthrough??!0}),this}messageTier(e){let n=this._messageTypes.get(e);return n!=null?n.tier:1}isWireCrossing(e){let n=this._messageTypes.get(e);return n!=null?n.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let n=this._messageTypes.get(e);return n!=null?n.metaPassthrough:!0}isKnownMessageType(e){return this._messageTypes.has(e)}registerCodec(e){return this._assertUnfrozen(),this._codecs.set(e.name,e),this}lookupCodec(e){return this._codecs.get(e)}_isFrozen(){return this._frozen}_assertUnfrozen(){if(this._frozen)throw new Error("GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node.")}}});function dd(t){return Array.isArray(t)?[...t]:[t]}function Kf(t,e){return t.has(e)||t.has("*")}function Mt(t){let e=[];return t((o,s)=>{e.push({kind:"allow",actions:new Set(dd(o)),where:s?.where??(()=>!0)})},(o,s)=>{e.push({kind:"deny",actions:new Set(dd(o)),where:s?.where??(()=>!0)})}),(o,s)=>{let i=!1,a=!1;for(let u of e)Kf(u.actions,s)&&u.where(o)&&(u.kind==="deny"?i=!0:a=!0);return i?!1:a}}function Nr(t){return Mt((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[d,c]of i)if(u[d]!==c)return!1;return!0};r.effect==="deny"?n(r.action,{where:a}):e(r.action,{where:a})}})}function _r(t){let e=qf.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 rt,qf,$t=tt(()=>{"use strict";rt=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}};qf=["human","llm","wallet","system"]});function Zi(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(Zi);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=Zi(t[n]);return e}return null}function zf(t){let e=Wf.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,d=1013904242,c=2773480762,l=1359893119,p=2600822924,f=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 _=0;_<16;_++)h[_]=i.getUint32(b+_*4,!1);for(let _=16;_<64;_++){let I=h[_-15],O=h[_-2],P=g(I,7)^g(I,18)^I>>>3,B=g(O,17)^g(O,19)^O>>>10;h[_]=h[_-16]+P+h[_-7]+B>>>0}let v=a,T=u,w=d,k=c,x=l,S=p,R=f,N=m;for(let _=0;_<64;_++){let I=g(x,6)^g(x,11)^g(x,25),O=x&S^~x&R,P=N+I+O+Hf[_]+h[_]>>>0,B=g(v,2)^g(v,13)^g(v,22),j=v&T^v&w^T&w,D=B+j>>>0;N=R,R=S,S=x,x=k+P>>>0,k=w,w=T,T=v,v=P+D>>>0}a=a+v>>>0,u=u+T>>>0,d=d+w>>>0,c=c+k>>>0,l=l+x>>>0,p=p+S>>>0,f=f+R>>>0,m=m+N>>>0}let y=b=>b.toString(16).padStart(8,"0");return y(a)+y(u)+y(d)+y(c)+y(l)+y(p)+y(f)+y(m)}function jt(t){let e=Zi(t??null),n=JSON.stringify(e);return zf(n).slice(0,16)}function Uf(){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 In(t,e,n){let r=n?.id??Uf();if(t===0)return{id:r,version:0};let s=(n?.hash??jt)(e);return{id:r,version:0,cid:s,prev:null}}function Mr(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}function ea(t){return"cid"in t}var Hf,Wf,Io=tt(()=>{"use strict";Hf=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]),Wf=new TextEncoder});function pd(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function ta(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function Po(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function ra(t){if($e._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($e)}function z(t,e,n){let r=fd(t)?t:[],o=typeof t=="function"?t:typeof e=="function"?e:void 0,s={};return fd(t)?s=(na(e)?e:n)??{}:na(t)?s=t:s=(na(e)?e:n)??{},new Ce(r,o,s)}var cd,ld,Jf,Yf,$e,Ce,fd,na,_e=tt(()=>{"use strict";Lo();kr();Me();xe();Xi();$t();ae();Io();cd=()=>{},ld=100;Jf=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},Yf=(t,e,n,r)=>{let o=t;if(o._status==="completed"||o._status==="errored")return;let s=o._cached,i=s===void 0?[_n]:[_n,[E,s]];o._status==="dirty"&&i.push(Et),_t(e,i,o._config.tierOf)},$e=new nn({onMessage:Jf,onSubscribe:Yf});Er($e);wr($e);Ce=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??$e,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??jt;let o=r.versioning??this._config.defaultVersioning;this._versioningLevel=o,this._versioning=o!=null?In(o,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(pd);let s={};for(let[a,u]of Object.entries(r.meta??{})){let d={initial:u,name:`${r.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};r.guard!=null&&(d.guard=r.guard),s[a]=new t([],void 0,d)}Object.freeze(s),this.meta=s,this._hasMeta=Object.keys(s).length>0;let i=this;this._actions={emit(a){i._emit([[E,a]])},down(a){i._emit(Po(a))},up(a){i._emitUp(Po(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,d=In(e,s,{id:a,hash:o});d.version=u,this._versioning=d,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=Nt(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=Nt(e?.actor),s=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(o,s))throw new rt({actor:o,action:s,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(o,s))throw new rt({actor:o,action:s,nodeName:this.name})}this._lastMutation={actor:o,timestamp_ns:oe()}}down(e,n){let r=Po(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[E,e]])}up(e,n){if(this._deps.length===0)return;let r=Po(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=Nt(n);if(!this._guard(u,"observe"))throw new rt({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)ta(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=cd,s.unsub=s.node.subscribe(i=>{if(s.unsub===null)return;let a=this._config.tierOf,u=!1;for(let d of i)a(d[0])>=3&&(u=!0),this._config.onMessage(this,d,{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{}ta(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=pd(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Mn),r.unsub=cd;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([[A,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([[A,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{}}ta(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===ne){this._depDirtied(r);return}if(o===Je){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(yr);return}if(o===Be||o===qe){this._emit([n]);return}if(o===de){this._emit(On);return}if(o===E)this._depSettledAsData(r,n[1]);else if(o===V)this._depSettledAsResolved(r);else if(o===L)this._depSettledAsTerminal(r,!0);else if(o===A)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(o===E||o===V)&&this._emit([n]),(o===L||o===A)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Mn))}_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(hr),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([[A,e.terminal]]);return}this._autoComplete&&this._deps.every(n=>n.terminal!==void 0)&&this._emit(br)}_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([[A,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([[A,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([[A,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>ld?(this._rerunDepth=0,this._emit([[A,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${ld} \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"?[Et,e[0]]:e;let r=!0,o=!1,s=!1,i=-1;for(let u of e){let d=n(u[0]);d<i&&(r=!1),d===3&&(o=!0),u[0]===ne&&(s=!0),i=d}let a=e;if(!r){let u=e.map((d,c)=>({m:d,i:c,tier:n(d[0])}));u.sort((d,c)=>d.tier-c.tier||d.i-c.i),a=u.map(d=>d.m)}if(o&&!s&&this._status!=="dirty"){let u=0;for(;u<a.length&&n(a[u][0])===0;)u++;return u===0?[Et,...a]:[...a.slice(0,u),Et,...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]===A&&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]===Je);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],d=u[0];if(d!==Be&&d!==qe){o?.push(u);continue}if(u.length<2)throw new Error(`Node "${this.name}": [[${d===Be?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let c=!0;if(this._pausable!==!1){let l=u[1];if(d===Be)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(l),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(l))c=!1;else if(this._pauseLocks.delete(l),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let p=this._pauseBuffer;this._pauseBuffer=[],this._emit(p)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?o?.push(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(On)}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 d of s)a(d[0])===3?this._pauseBuffer.push(d):u.push(d);u.length>0&&this._dispatchOrAccumulate(u)}else this._dispatchOrAccumulate(s);i!=null&&this._emit([[A,i]])}_updateState(e){let n=this._config.tierOf,r,o,s=-1,i=0;for(let c of e)n(c[0])===3&&i++;let a=i<=1,u=-1;if(this._versioning!=null&&i>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===E){u=c;break}}for(let c=0;c<e.length;c++){let l=e[c],p=l[0];if(p===E){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=c;break}if(f){r==null&&(r=e.slice(0,c)),r.push(Nn),this._status="resolved";continue}this._cached=l[1],this._versioning!=null&&(u<0||c===u)&&Mr(this._versioning,l[1],this._hashFn)}this._status="settled",r?.push(l)}else if(r?.push(l),p===ne)this._status="dirty";else if(p===V)this._status="resolved";else if(p===L){this._status="completed";{let f=this._config.rigorRecorder;if(f!=null)try{f.onTerminalTransition(this,"completed",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===A){this._status="errored";{let f=this._config.rigorRecorder;if(f!=null)try{f.onTerminalTransition(this,"errored",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===Je){if(this._cached!==void 0){let m=this._config.rigorRecorder;if(m!=null)try{m.onNonVacuousInvalidate(this,this._cached)}catch{}}this._cached=void 0,this._status="dirty";let f=this._cleanup;if(typeof f=="function"){this._cleanup=void 0;try{f()}catch{}}else if(f!=null&&typeof f=="object"){let m=f.invalidate;if(typeof m=="function")try{m()}catch{}}}else p===de&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let d=s>=0?r??e.slice(0,s):r??e;return o!=null?{finalMessages:d,equalsError:o}:{finalMessages:d}}_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(ud()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],Sr(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}_t(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);_t(this._deliverToSinks,n,this._config.tierOf)}},fd=t=>Array.isArray(t),na=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function M(t,e){return z([],{...e,initial:t})}function K(t,e){return z((r,o,s)=>t(o,s)??void 0,{describeKind:"producer",...e})}function C(t,e,n){return z(t,(o,s,i)=>{let a=o.map((u,d)=>u!=null&&u.length>0?u.at(-1):i.prevData[d]);s.emit(e(a,i))},{describeKind:"derived",...n})}function pe(t,e,n){return z(t,(o,s,i)=>{let a=o.map((u,d)=>u!=null&&u.length>0?u.at(-1):i.prevData[d]);return e(a,s,i)??void 0},{describeKind:"effect",...n})}function Or(t,e,n){let r=new Map;return t.forEach((o,s)=>{r.set(o,s)}),C(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 rn(t,e){let n,r=new Map,o=(s,i,a)=>{let u=!1,d=c=>{let l=r.get(c);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 c.cache}u=!0;let p=n._addDep(c);return r.set(c,p),c.cache};try{let c=t(d,a);u||(i.emit(c),a.store.__autoTrackLastDiscoveryError!=null&&delete a.store.__autoTrackLastDiscoveryError)}catch(c){if(!u)throw c;a.store.__autoTrackLastDiscoveryError=c}};return n=new Ce([],o,{describeKind:"derived",...e}),n}function oa(t,...e){let n=t;for(let r of e)n=r(n);return n}var ee=tt(()=>{"use strict";_e()});function Lr(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,d;if(s==="*")u=e,d=n;else if(s.includes("-")){let[c,l]=s.split("-");u=Number.parseInt(c,10),d=Number.parseInt(l,10)}else u=Number.parseInt(s,10),d=u;if(Number.isNaN(u)||Number.isNaN(d))throw new Error(`Invalid cron field: ${t}`);if(u<e||d>n)throw new Error(`Cron field out of range: ${t} (${e}-${n})`);if(u>d)throw new Error(`Invalid cron range: ${u}-${d} in ${t}`);for(let c=u;c<=d;c+=a)r.add(c)}return r}function Vo(t){let e=t.trim().split(/\s+/);if(e.length!==5)throw new Error(`Invalid cron: expected 5 fields, got ${e.length}`);return{minutes:Lr(e[0],0,59),hours:Lr(e[1],0,23),daysOfMonth:Lr(e[2],1,31),months:Lr(e[3],1,12),daysOfWeek:Lr(e[4],0,6)}}function Ko(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 aa=tt(()=>{"use strict"});var Md={};ke(Md,{NS_PER_MS:()=>He,NS_PER_SEC:()=>at,constant:()=>qo,decorrelatedJitter:()=>Uo,exponential:()=>Wo,fibonacci:()=>zo,linear:()=>Ho,resolveBackoffPreset:()=>Bt,withMaxAttempts:()=>ua});function sn(t){return t<0?0:t}function sm(t,e){return e==="none"?t:e==="full"?Math.random()*t:t/2+Math.random()*(t/2)}function im(t,e){return t+Math.random()*(e-t)}function qo(t){let e=sn(t);return()=>e}function Ho(t,e){let n=sn(t),r=e===void 0?n:sn(e);return o=>n+r*Math.max(0,o)}function Wo(t){let e=sn(t?.baseNs??1e8),n=t?.factor!==void 0&&t.factor<1?1:t?.factor??2,r=sn(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 d=0;d<Math.max(0,s);d++){if(u>=a){u=a;break}u*=n}i=e*u,i>r&&(i=r)}return sm(i,o)}}function zo(t=100*1e6,e=30*1e9){let n=sn(t),r=sn(e);function o(s){if(s<=0)return 1;let i=1,a=2;for(let u=1;u<s;u++){let d=i+a;i=a,a=d}return a}return s=>{let i=o(s)*n;return i<=r?i:r}}function Uo(t=100*1e6,e=30*1e9){return(n,r,o)=>{let i=Math.min(e,(o??t)*3);return im(t,i)}}function ua(t,e){return(n,r,o)=>n>=e?null:t(n,r,o)}function Bt(t){if(t==="constant")return qo(1*1e9);if(t==="linear")return Ho(1*1e9);if(t==="exponential")return Wo();if(t==="fibonacci")return zo();if(t==="decorrelatedJitter")return Uo();throw new Error(`Unknown backoff preset: "${String(t)}". Use one of: constant, linear, exponential, fibonacci, decorrelatedJitter`)}var He,at,Vn=tt(()=>{"use strict";He=1e6,at=1e9});var Le,vt=tt(()=>{"use strict";Le=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 Ad={};ke(Ad,{CircuitOpenError:()=>pt,RateLimiterOverflowError:()=>an,TimeoutError:()=>un,circuitBreaker:()=>wt,fallback:()=>Hn,rateLimiter:()=>qn,retry:()=>Tt,timeout:()=>Wn,tokenBucket:()=>Vt,withBreaker:()=>Kn,withStatus:()=>Kt});function dn(t){return{describeKind:"derived",...t}}function am(t){return t<0?0:t}function Jo(t){return t[1]}function Od(t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("backoff strategy must return a finite number");return t<0?0:t}function Tt(t,e){return typeof t=="function"?dm(t,e):um(t,e)}function um(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"?Bt(r):r;return K(i=>{let a=0,u=!1,d=null,c,l=new Le;function p(){c?.(),c=void 0}function f(h){if(u)return;if(a>=o){p(),i.down([[A,h]]);return}let g=s===null?0:s(a,h,d);if(g==null){p(),i.down([[A,h]]);return}let y;try{y=Od(g)}catch{p(),i.down([[A,h]]);return}d=y,a+=1,p();let b=y>0?y/1e6:1;l.start(b,()=>{u||m()})}function m(){l.cancel(),p(),c=t.subscribe(h=>{if(!u)for(let g of h){let y=g[0];if(y===ne)i.down([[ne]]);else if(y===E)a=0,d=null,i.emit(g[1]);else if(y===V)i.down([[V]]);else if(y===L)p(),i.down([[L]]);else if(y===A){f(Jo(g));return}else i.down([g])}})}return m(),()=>{u=!0,l.cancel(),p()}},{...dn(),initial:t.cache})}function dm(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"?Bt(r):r;return K(i=>{let a=0,u=!1,d=null,c,l=new Le;function p(){c?.(),c=void 0}function f(h){if(u)return;if(a>=o){p(),i.down([[A,h]]);return}let g=s===null?0:s(a,h,d);if(g==null){p(),i.down([[A,h]]);return}let y;try{y=Od(g)}catch{p(),i.down([[A,h]]);return}d=y,a+=1,p();let b=y>0?y/1e6:1;l.start(b,()=>{u||m()})}function m(){l.cancel(),p();let h;try{h=t()}catch(g){f(g);return}c=h.subscribe(g=>{if(!u)for(let y of g){let b=y[0];if(b===ne)i.down([[ne]]);else if(b===E)a=0,d=null,i.emit(y[1]);else if(b===V)i.down([[V]]);else if(b===L)p(),i.down([[L]]);else if(b===A){f(Jo(y));return}else i.down([y])}})}return m(),()=>{u=!0,l.cancel(),p()}},{...dn(),initial:e?.initial})}function wt(t){let e=Math.max(1,t?.failureThreshold??5),n=am(t?.cooldownNs??30*1e9),r=t?.cooldown??null,o=Math.max(1,t?.halfOpenMax??1),s=t?.now??H,i="closed",a=0,u=0,d=0,c=n,l=0;function p(){if(!r)return n;let h=r(u);return h!==null?h:n}function f(){i="open",c=p(),d=s(),l=0}return{canExecute(){return i==="closed"?!0:i==="open"?s()-d>=c?(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++,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 Kn(t,e){let n=e?.onOpen??"skip";return r=>{let o=z([],(s,i)=>{function a(){o.meta.breakerState.down([[E,t.state]])}let u=r.subscribe(d=>{for(let c of d){let l=c[0];l===ne?i.down([[ne]]):l===E?t.canExecute()?(a(),i.emit(c[1])):(a(),n==="error"?i.down([[A,new pt]]):i.down([[V]])):l===V?i.down([[V]]):l===L?(t.recordSuccess(),a(),i.down([[L]])):l===A?(t.recordFailure(Jo(c)),a(),i.down([c])):i.down([c])}});return a(),u},{...dn(),meta:{breakerState:t.state},completeWhenDepsComplete:!1,initial:r.cache});return{node:o,breakerState:o.meta.breakerState}}}function Vt(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=H();function o(s){if(e>0){let i=s-r;n=Math.min(t,n+i/1e9*e)}r=s}return{available(){return o(H()),n},tryConsume(s=1){if(s<=0)return!0;let i=H();return o(i),n>=s?(n-=s,!0):!1},putBack(s=1){s<=0||(o(H()),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 K(a=>{let u=Vt(n,i),d=[],c=new Le,l=!1,p=1e9/i;function f(){for(;d.length>0;)if(u.tryConsume(1))a.emit(d.shift());else{c.start(Math.max(1,p/1e6),f);return}}let m=t.subscribe(h=>{for(let g of h){if(l)return;let y=g[0];if(y===ne)a.down([[ne]]);else if(y===E){if(o!==void 0&&d.length>=o){if(s!=="drop-newest")if(s==="drop-oldest")d.shift(),d.push(g[1]);else{l=!0,c.cancel(),d.length=0,a.down([[A,new an(o)]]);return}}else d.push(g[1]);f()}else if(y===V)a.down([[V]]);else if(y===L)l=!0,c.cancel(),d.length=0,a.down([[L]]);else if(y===A)l=!0,c.cancel(),d.length=0,a.down([g]);else if(y===de){l=!0,c.cancel(),d.length=0,a.down([g]);return}else a.down([g])}});return()=>{l=!0,c.cancel(),m()}},{...dn(),initial:t.cache})}function Kt(t,e){let n=e?.initialStatus??"pending",r=z([],(o,s)=>{let i=n;return r.meta.status.down([[E,n]]),r.meta.error.down([[E,null]]),t.subscribe(u=>{for(let d of u){let c=d[0];if(c===ne)s.down([[ne]]);else if(c===E)i==="errored"?X(()=>{r.meta.error.down([[E,null]]),r.meta.status.down([[E,"active"]])}):r.meta.status.down([[E,"active"]]),i="active",s.emit(d[1]);else if(c===V)s.down([[V]]);else if(c===L)r.meta.status.down([[E,"completed"]]),i="completed",s.down([[L]]);else if(c===A){let l=Jo(d);X(()=>{r.meta.error.down([[E,l]]),r.meta.status.down([[E,"errored"]])}),i="errored",s.down([d])}else s.down([d])}})},{...dn(),meta:{status:n,error:null},completeWhenDepsComplete:!1,resubscribable:!0,initial:t.cache});return{node:r,status:r.meta.status,error:r.meta.error}}function cm(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function lm(t){return t!=null&&typeof t.then=="function"}function pm(t){return t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function"}function Hn(t,e){return K(n=>{let r,o;function s(){o?.(),o=void 0,cm(e)||lm(e)||pm(e)?r=U(e).subscribe(a=>{n.down(a)}):(n.emit(e),n.down([[L]]))}return o=t.subscribe(i=>{for(let a of i){let u=a[0];if(u===ne)n.down([[ne]]);else if(u===E)n.emit(a[1]);else if(u===V)n.down([[V]]);else if(u===L)n.down([[L]]);else if(u===A){s();return}else if(u===de){r?.(),n.down([a]);return}else n.down([a])}}),()=>{o?.(),r?.()}},{...dn(),initial:t.cache})}function Wn(t,e){if(e<=0)throw new RangeError("timeoutNs must be > 0");return K(n=>{let r=!1,o=new Le;function s(){let a=e/1e6;o.start(a,()=>{r||(r=!0,i(),n.down([[A,new un(e)]]))})}let i=t.subscribe(a=>{for(let u of a){if(r)return;let d=u[0];if(d===ne)n.down([[ne]]);else if(d===E)s(),n.emit(u[1]);else if(d===V)n.down([[V]]);else if(d===L){o.cancel(),r=!0,n.down([[L]]);return}else if(d===A){o.cancel(),r=!0,n.down([u]);return}else if(d===de){o.cancel(),r=!0,n.down([u]);return}else n.down([u])}});return s(),()=>{r=!0,o.cancel(),i()}},{...dn(),initial:t.cache})}var pt,an,un,Ot=tt(()=>{"use strict";Me();xe();ae();_e();ee();Vn();he();vt();pt=class extends Error{name="CircuitOpenError";constructor(){super("Circuit breaker is open")}};an=class extends Error{name="RateLimiterOverflowError";constructor(e){super(`rateLimiter buffer overflow (maxBuffer=${e})`)}};un=class extends Error{name="TimeoutError";constructor(e){super(`Timed out after ${e/1e6}ms`)}}});function ut(t){return{describeKind:"producer",...t}}function ca(t){return/[\\^$+?.()|[\]{}]/.test(t)?`\\${t}`:t}function Ld(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+=ca(r)}return e+="$",new RegExp(e)}function Id(t,e){for(let n of e)if(n.test(t))return!0;return!1}function fm(t,e){let n=z([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[V]]);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 st(t,e){let{signal:n,period:r,...o}=e??{};return K(s=>{let i=!1,a=0,u,d,c=()=>{i=!0,u!==void 0&&clearTimeout(u),d!==void 0&&clearInterval(d),n?.removeEventListener("abort",p)},l=()=>{i||(r!=null?(s.emit(a++),d=setInterval(()=>{i||s.emit(a++)},r)):(i=!0,n?.removeEventListener("abort",p),s.emit(a++),s.down([[L]])))},p=()=>{i||(c(),s.down([[A,n.reason]]))};if(n?.aborted){p();return}return u=setTimeout(l,t),n?.addEventListener("abort",p,{once:!0}),c},ut(o))}function Pd(t){let{signal:e,...n}=t??{};return K(r=>{let o=!1,s,i,a=!1,u=!1,d=typeof requestAnimationFrame=="function"?requestAnimationFrame:void 0,c=typeof cancelAnimationFrame=="function"?cancelAnimationFrame:void 0,l=typeof document<"u"?document:void 0,p=()=>{s!==void 0&&c&&c(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([[A,e.reason]]))},h=b=>{o||(r.emit(b),g())},g=()=>{o||(d&&(!l||l.visibilityState!=="hidden")?s=d(h):i=setTimeout(()=>h(performance.now()),16))},y=()=>{o||(p(),g())};return e?.aborted?(m(),f):(e?.addEventListener("abort",m,{once:!0}),a=e!==void 0,l&&d&&(l.addEventListener("visibilitychange",y),u=!0),g(),f)},ut(n))}function Qo(t,e){let n=Vo(t),{tickMs:r,output:o,...s}=e??{},i=r??6e4,a=o==="date";return K(u=>{let d=-1,c=()=>{let p=new Date,f=p.getFullYear()*1e8+(p.getMonth()+1)*1e6+p.getDate()*1e4+p.getHours()*100+p.getMinutes();f!==d&&Ko(n,p)&&(d=f,u.emit(a?p:oe()))};c();let l=setInterval(c,i);return()=>clearInterval(l)},{...ut(s),name:s.name??`cron:${t}`})}function Dd(t,e,n){let{capture:r,passive:o,once:s,...i}=n??{};return K(a=>{let u=c=>{a.emit(c)},d={capture:r,passive:o,once:s};return t.addEventListener(e,u,d),()=>t.removeEventListener(e,u,d)},ut(i))}function Xo(t,e){return K(n=>{let r=!1;try{for(let o of t){if(r)return;n.emit(o)}r||n.down([[L]])}catch(o){r||n.down([[A,o]])}return()=>{r=!0}},ut(e))}function mm(t){return t!=null&&typeof t.then=="function"}function zn(t,e){let{signal:n,...r}=e??{};return K(o=>{let s=!1,i=()=>{s||(s=!0,o.down([[A,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([[L]]))},a=>{s||(s=!0,n?.removeEventListener("abort",i),o.down([[A,a]]))}),()=>{s=!0,n?.removeEventListener("abort",i)}},ut(r))}function Ir(t,e){let{signal:n,...r}=e??{};return K(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,d=t[Symbol.asyncIterator](),c=()=>{u||a.aborted||Promise.resolve(d.next()).then(l=>{if(!(u||a.aborted)){if(l.done){o.down([[L]]);return}o.emit(l.value),c()}},l=>{!u&&!a.aborted&&o.down([[A,l]])})};return c(),()=>{u=!0,n?.removeEventListener("abort",i),s.abort(),Promise.resolve(d.return?.()).catch(()=>{})}},ut(r))}function gm(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function U(t,e){if(gm(t))return t;if(mm(t))return zn(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return Ir(t,e);if(typeof n[Symbol.iterator]=="function")return Xo(t,e)}return la(t)}function la(...t){return Xo(t,void 0)}function Gd(t){return K(e=>{e.down([[L]])},ut(t))}function Fd(t){return K(()=>{},ut(t))}function $d(t,e){return K(n=>{n.down([[A,t]])},ut(e))}function jd(t,e){let{signal:n,...r}=e??{},o=ut(r),s=o.resubscribable===void 0?{...o,resubscribable:!0}:o;return K(i=>{let a,u=!1;try{let d=t();a=U(d,e).subscribe(l=>{if(!u)for(let p of l){let f=p[0];if(f!==dt)if(f===E)i.emit(p[1]);else if(f===L){u=!0,i.down([[L]]);break}else if(f===A){u=!0,i.down([[A,p[1]]]);break}else i.down([p])}})}catch(d){let c=d===void 0?new Error("defer: thunk threw undefined"):d;i.down([[A,c]])}return()=>{u=!0,a?.()}},s)}function qt(t,e,n){return z([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 Bd(t,e){return z([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([[L]]);return}(i==null||i.length===0)&&r.down([[V]])},{describeKind:"derived",completeWhenDepsComplete:!1,...e})}function Vd(t,e){return K(n=>t.subscribe(r=>{n.down(r)}),{...ut(e),initial:t.cache})}function Zo(t,e,n){if(e<1)throw new RangeError("replay expects bufferSize >= 1");let r=[],o=K(s=>t.subscribe(i=>{for(let a of i)a[0]===E&&(r.push(a[1]),r.length>e&&r.shift());s.down(i)}),{...ut(n),initial:t.cache});return fm(o,s=>{for(let i of r)s([[E,i]])})}function Kd(t,e){return Zo(t,1,e)}function Ye(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]===E){r=!0,e(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===A){r=!0,n(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===L){r=!0,n(new Error("completed without DATA")),s?(s(),s=void 0):o=!0;return}}}),o&&(s?.(),s=void 0)})}function Yo(t,e,n){return new Promise((r,o)=>{let s=!1,i=!1,a,u=n?.skipCurrent===!0;a=t.subscribe(d=>{for(let c of d){if(s)return;if(!(u&&c[0]===E)){if(c[0]===E){let l=c[1];if(e(l)){s=!0,r(l),a?(a(),a=void 0):i=!0;return}}if(c[0]===A){s=!0,o(c[1]),a?(a(),a=void 0):i=!0;return}if(c[0]===L){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 es(t,e){let n=e?.predicate??(s=>s!=null),r=e?.skipCurrent;if(e?.timeoutMs==null||e.timeoutMs<=0)return await Yo(t,n,{skipCurrent:r});if(da===void 0){let[s,i]=await Promise.all([Promise.resolve().then(()=>(Ot(),Ad)),Promise.resolve().then(()=>(Vn(),Md))]);da=s.timeout,Cd=i.NS_PER_MS}let o=da(t,e.timeoutMs*Cd);return await Yo(o,n,{skipCurrent:r})}function ts(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]===E&&u[1]===!0){n.abort(r),i();return}if(u[0]===A){n.abort(u[1]),i();return}if(u[0]===L){i();return}}}),s&&(o?.(),o=void 0),{signal:n.signal,dispose:()=>{o&&(o(),o=void 0)}}}function re(t){return t.subscribe(()=>{})}function pa(t){let e=M(0);return{node:e,increment(){let n=e.cache??0;return n>=t?!1:(e.down([[ne],[E,n+1]]),!0)},get(){return e.cache??0},atCap(){return(e.cache??0)>=t}}}var da,Cd,qd,he=tt(()=>{"use strict";xe();ae();_e();ee();aa();qd=Zo});var Wb={};ke(Wb,{COMPLETE:()=>L,COMPLETE_MSG:()=>Oo,COMPLETE_ONLY_BATCH:()=>br,CircuitOpenError:()=>pt,ContentAddressedMissError:()=>eo,DATA:()=>E,DEFAULT_ACTOR:()=>bt,DIRTY:()=>ne,DIRTY_MSG:()=>Et,DIRTY_ONLY_BATCH:()=>Mn,ENVELOPE_VERSION:()=>An,ERROR:()=>A,GRAPH_META_SEGMENT:()=>Qe,Graph:()=>Y,GraphReFlyConfig:()=>nn,GuardDenied:()=>rt,INVALIDATE:()=>Je,INVALIDATE_MSG:()=>Mo,INVALIDATE_ONLY_BATCH:()=>yr,JsonCodec:()=>Co,NS_PER_MS:()=>He,NS_PER_SEC:()=>at,NativeIndexBackend:()=>ro,NativeListBackend:()=>oo,NativeLogBackend:()=>jr,NativeMapBackend:()=>Xr,NativePubSubBackend:()=>no,NodeImpl:()=>Ce,PAUSE:()=>Be,RESOLVED:()=>V,RESOLVED_MSG:()=>Nn,RESOLVED_ONLY_BATCH:()=>hr,RESUME:()=>qe,RateLimiterOverflowError:()=>an,ResettableTimer:()=>Le,SIZEOF_OVERHEAD:()=>je,SIZEOF_SYMBOL:()=>ds,SNAPSHOT_VERSION:()=>ft,SNAPSHOT_WIRE_VERSION:()=>No,START:()=>dt,START_MSG:()=>_n,SurfaceError:()=>Ne,TEARDOWN:()=>de,TEARDOWN_MSG:()=>Ao,TEARDOWN_ONLY_BATCH:()=>On,TimeoutError:()=>un,accessHintForGuard:()=>_r,accountability:()=>yi,advanceVersion:()=>Mr,ai:()=>mi,appendLogStorage:()=>Ka,asSurfaceError:()=>Fi,audit:()=>Jc,autoTrackNode:()=>rn,awaitSettled:()=>es,batch:()=>X,buffer:()=>Yc,bufferCount:()=>Qc,bufferTime:()=>Zc,cached:()=>Kd,canonicalJson:()=>to,cascadingCache:()=>ap,catchError:()=>dl,checkpointToRedis:()=>Zl,checkpointToS3:()=>Xl,circuitBreaker:()=>wt,combine:()=>Ca,combineLatest:()=>il,compat:()=>Oa,concat:()=>Vc,concatMap:()=>Hc,configure:()=>ra,constant:()=>qo,contentAddressedStorage:()=>Ps,core:()=>va,cqrs:()=>Ts,createDagCborCodec:()=>Ji,createDagCborZstdCodec:()=>Yi,createGraph:()=>pr,createTransport:()=>Jt,createVersioning:()=>In,createWatermarkController:()=>Un,csvRows:()=>Il,debounce:()=>Ia,debounceTime:()=>al,decodeEnvelope:()=>Tr,decorrelatedJitter:()=>Uo,defaultConfig:()=>$e,defaultHash:()=>jt,defer:()=>jd,delay:()=>zc,deleteSnapshot:()=>Hi,demoShell:()=>vi,derived:()=>C,deserializeError:()=>yn,dictKv:()=>Tp,dictSnapshot:()=>wp,diffForWAL:()=>fs,diffSnapshots:()=>Ki,distill:()=>Ls,distinctUntilChanged:()=>$c,domainTemplates:()=>Ti,downWithBatch:()=>_t,dynamicNode:()=>Or,effect:()=>pe,elementAt:()=>Dc,empty:()=>Gd,encodeEnvelope:()=>vr,escapeRegexChar:()=>ca,exhaustMap:()=>qc,explainPath:()=>Gr,exponential:()=>Wo,externalBundle:()=>Os,externalProducer:()=>mn,extra:()=>Wa,fallback:()=>Hn,fibonacci:()=>zo,filter:()=>Xe,find:()=>Pc,first:()=>As,firstValueFrom:()=>Ye,firstWhere:()=>Yo,flatMap:()=>Wc,forEach:()=>qt,fromAny:()=>U,fromAsyncIter:()=>Ir,fromCSV:()=>Ll,fromClickHouseWatch:()=>Fl,fromCron:()=>Qo,fromDrizzle:()=>op,fromEvent:()=>Dd,fromHTTP:()=>$a,fromHTTPPoll:()=>vl,fromHTTPStream:()=>bl,fromIter:()=>Xo,fromKafka:()=>Ml,fromKysely:()=>sp,fromMCP:()=>kl,fromNATS:()=>Bl,fromNDJSON:()=>Gl,fromOTel:()=>xl,fromPrisma:()=>rp,fromPrometheus:()=>_l,fromPromise:()=>zn,fromPulsar:()=>$l,fromRabbitMQ:()=>Kl,fromRaf:()=>Pd,fromRedisStream:()=>Al,fromSSE:()=>yl,fromSqlite:()=>ep,fromSqliteCursor:()=>tp,fromStatsD:()=>El,fromSyslog:()=>Rl,fromTimer:()=>st,fromWebSocket:()=>Fa,fromWebSocketReconnect:()=>wl,fromWebhook:()=>cl,globToRegExp:()=>Ld,graph:()=>ka,graphProfile:()=>pn,graphspec:()=>fi,guarded:()=>ki,harness:()=>Ci,interval:()=>nl,isBatching:()=>tn,isV1:()=>ea,jobQueue:()=>Oi,jotai:()=>Do,jsonCodec:()=>tr,jsonCodecFor:()=>yp,keepalive:()=>re,kvStorage:()=>js,last:()=>Ic,layout:()=>Di,lens:()=>Ii,linear:()=>Ho,listSnapshots:()=>qi,lru:()=>Va,makeHttpError:()=>ht,map:()=>zr,matchesAnyPattern:()=>Id,matchesCron:()=>Ko,memory:()=>ci,memoryAppendLog:()=>vp,memoryBackend:()=>io,memoryKv:()=>ao,memorySnapshot:()=>bp,merge:()=>xt,mergeMap:()=>La,mergeReactiveLogs:()=>vc,mermaidLiveUrl:()=>ps,messaging:()=>oi,monotonicNs:()=>H,nameToSignal:()=>gn,nanostores:()=>jo,ndjsonRows:()=>Pl,nestjs:()=>ks,never:()=>Fd,node:()=>z,nodeSignal:()=>ts,normalizeActor:()=>Nt,of:()=>la,onFirstData:()=>Jr,orchestration:()=>si,pairwise:()=>jc,parseCron:()=>Vo,parsePrometheusText:()=>ja,parseSSEStream:()=>Dt,parseStatsD:()=>Nl,parseSyslog:()=>Sl,patterns:()=>Qu,pausable:()=>ol,pipe:()=>oa,policy:()=>Mt,policyFromRules:()=>Nr,process:()=>Pi,producer:()=>K,pubsub:()=>pp,race:()=>Kc,rateLimiter:()=>qn,reachable:()=>fn,react:()=>xs,reactiveCounter:()=>pa,reactiveIndex:()=>gp,reactiveList:()=>Ds,reactiveLog:()=>Ve,reactiveMap:()=>Ze,reactiveSink:()=>We,reduce:()=>Ac,reduction:()=>pi,refine:()=>Si,registerBuiltinCodecs:()=>wr,registerBuiltins:()=>Er,repeat:()=>rl,replay:()=>Zo,replayWAL:()=>Qi,rescue:()=>Yr,resilientPipeline:()=>Gi,resolveBackoffPreset:()=>Bt,resolveDescribeFields:()=>At,restoreSnapshot:()=>Vi,retry:()=>Tt,runReduction:()=>$i,sample:()=>Uc,saveSnapshot:()=>Bi,scan:()=>Oc,serializeError:()=>hn,share:()=>Vd,shareReplay:()=>qd,signalToName:()=>Ut,signals:()=>Ss,singleFromAny:()=>Gs,singleNodeFromAny:()=>hp,sizeof:()=>Fr,skip:()=>Aa,snapshotStorage:()=>$s,solid:()=>Es,sortJsonValue:()=>so,stableJsonString:()=>Fs,state:()=>M,stratify:()=>uo,surface:()=>Wi,svelte:()=>Ns,switchMap:()=>Te,take:()=>Ur,takeUntil:()=>Lc,takeWhile:()=>Cc,tap:()=>Gc,tapFirst:()=>Fc,throttle:()=>Pa,throttleTime:()=>ul,throwError:()=>$d,timeout:()=>Wn,toArray:()=>Bd,toCSV:()=>Hl,toClickHouse:()=>Wl,toFile:()=>Ba,toHTTP:()=>ll,toKafka:()=>Ol,toLoki:()=>Yl,toMongo:()=>Jl,toNATS:()=>Vl,toObservable:()=>Bo,toPostgres:()=>Ul,toPulsar:()=>jl,toRabbitMQ:()=>ql,toReadableStream:()=>hl,toRedisStream:()=>Cl,toS3:()=>zl,toSSE:()=>ml,toSSEBytes:()=>gl,toSqlite:()=>np,toTempo:()=>Ql,toWebSocket:()=>Tl,tokenBucket:()=>Vt,validateGraphObservability:()=>wa,valve:()=>sl,verifiable:()=>cp,version:()=>Hb,vue:()=>_s,wallClockNs:()=>oe,watchTopologyTree:()=>Ct,window:()=>tl,windowCount:()=>Xc,windowTime:()=>el,withBreaker:()=>Kn,withLatestFrom:()=>Pt,withMaxAttempts:()=>ua,withStatus:()=>Kt,workerBridge:()=>qa,workerSelf:()=>Ha,zip:()=>Bc,zustand:()=>Ms});module.exports=Gf(Wb);var Oa={};ke(Oa,{jotai:()=>Do,nanostores:()=>jo,nestjs:()=>ks,react:()=>xs,signals:()=>Ss,solid:()=>Es,svelte:()=>Ns,vue:()=>_s,zustand:()=>Ms});var Do={};ke(Do,{atom:()=>Qf});ae();ee();function Qf(t,e,n){if(typeof t=="function"){let r=t;return typeof e=="function"?md(r,e,n):md(r,void 0,e)}return Xf(t,e)}function Ar(t){let e=t.cache,n;if(t.subscribe(o=>{for(let[s,i]of o)s===E&&(e=i),s===A&&(n=i)})(),n)throw n;return e}function Xf(t,e){let n=M(t,{...e,resubscribable:!0,resetOnTeardown:!0});return{get:()=>n.status==="sentinel"?Ar(n):n.cache,set:r=>n.emit(r),update:r=>{let o=n.status==="sentinel"?Ar(n):n.cache;n.emit(r(o))},subscribe:r=>{let o=!0;return n.subscribe(s=>{for(let[i,a]of s)if(i===E){if(o){o=!1;continue}r(a)}})},meta:n.meta,_node:n}}function md(t,e,n){let r=rn(s=>t(i=>{let a=i._node;return a.status==="sentinel"&&Ar(a),s(a)}),{...n,resubscribable:!0,resetOnTeardown:!0}),o={get:()=>r.status==="sentinel"?Ar(r):r.cache,subscribe:s=>{let i=!0;return r.subscribe(a=>{for(let[u,d]of a)if(u===E){if(i){i=!1;continue}s(d)}})},meta:r.meta,_node:r};if(e){let s=u=>u.get(),i=(u,d)=>u.set(d),a=o;return a.set=u=>e(s,i,u),a.update=u=>{let d=r.status==="sentinel"?Ar(r):r.cache;return e(s,i,u(d))},a}return o}var jo={};ke(jo,{action:()=>om,atom:()=>Zf,computed:()=>em,getValue:()=>nm,map:()=>tm,onMount:()=>rm,onStart:()=>yd,onStop:()=>bd});Me();ae();ee();var Fo=new WeakMap,$o=new WeakMap;function Go(t,e){let n=e.get(t);if(n)for(let r of n)r()}function sa(t,e={}){let n=0;return{...e,get:()=>hd(t),subscribe:o=>{n===0&&Go(t,Fo),n++;let s=t.subscribe(i=>{for(let[a,u]of i)a===E&&o(u)});return()=>{s(),n--,n===0&&Go(t,$o)}},listen:o=>{n===0&&Go(t,Fo),n++;let s=!0,i=t.subscribe(a=>{for(let[u,d]of a)if(u===E){if(s){s=!1;continue}o(d)}});return()=>{i(),n--,n===0&&Go(t,$o)}},_node:t}}function gd(t){let e=t.cache,n;if(t.subscribe(o=>{for(let[s,i]of o)s===E&&(e=i),s===A&&(n=i)})(),n)throw n;return e}function hd(t){return t.status==="sentinel"?gd(t):t.cache}function Zf(t){let e=M(t,{resubscribable:!0,resetOnTeardown:!0});return sa(e,{set:n=>e.emit(n)})}function em(t,e){let n=Array.isArray(t)?t:[t],r=n.map(s=>s._node),o=Or(r,s=>{let i=n.map(a=>{let u=a._node;return u.status==="sentinel"&&gd(u),s(u)});return e(...i)},{resubscribable:!0,resetOnTeardown:!0,equals:Object.is});return sa(o)}function tm(t){let e=M(t,{resubscribable:!0,resetOnTeardown:!0,equals:()=>!1});return sa(e,{set:n=>e.emit(n),setKey:(n,r)=>{let o=hd(e);e.emit({...o,[n]:r})}})}function nm(t){return t.get()}function yd(t,e){let n=t._node,r=Fo.get(n);r||(r=new Set,Fo.set(n,r)),r.add(e)}function bd(t,e){let n=t._node,r=$o.get(n);r||(r=new Set,$o.set(n,r)),r.add(e)}function rm(t,e){yd(t,()=>{let n=e();typeof n=="function"&&bd(t,n)})}function om(t,e,n){return(...r)=>{let o;return X(()=>{o=n(...r)}),o}}var ks={};ke(ks,{ACTOR_KEY:()=>rs,COMMAND_HANDLERS:()=>Fn,CQRS_EVENT_HANDLERS:()=>$n,CRON_HANDLERS:()=>Gn,CommandHandler:()=>Sd,EVENT_HANDLERS:()=>Pn,EventHandler:()=>Ed,GRAPHREFLY_REQUEST_GRAPH:()=>on,GRAPHREFLY_ROOT_GRAPH:()=>ct,GraphCron:()=>Rd,GraphInterval:()=>xd,GraphReflyEventExplorer:()=>cn,GraphReflyGuard:()=>Yd,GraphReflyGuardImpl:()=>Pr,GraphReflyModule:()=>ws,INTERVAL_HANDLERS:()=>Dn,InjectCqrsGraph:()=>Td,InjectGraph:()=>vd,InjectNode:()=>wd,ObserveGateway:()=>ns,OnGraphEvent:()=>kd,QUERY_HANDLERS:()=>jn,QueryHandler:()=>Nd,SAGA_HANDLERS:()=>Bn,SagaHandler:()=>_d,fromHeader:()=>Ud,fromJwtPayload:()=>ga,getActor:()=>Jd,getGraphToken:()=>ot,getNodeToken:()=>lt,observeSSE:()=>Wd,observeSubscription:()=>zd,toObservable:()=>Bo});var ia=require("rxjs");ae();function Bo(t,e){return e?.raw?new ia.Observable(n=>t.subscribe(o=>{if(!n.closed){n.next(o);for(let s of o){if(s[0]===A){n.error(s[1]);return}if(s[0]===L){n.complete();return}}}})):new ia.Observable(n=>t.subscribe(o=>{for(let s of o){if(n.closed)return;if(s[0]===E)n.next(s[1]);else if(s[0]===A){n.error(s[1]);return}else if(s[0]===L){n.complete();return}}}))}var Cr=require("@nestjs/common");var ct=Symbol.for("graphrefly:root-graph");var on=Symbol.for("graphrefly:request-graph");function ot(t){return Symbol.for(`graphrefly:graph:${t}`)}function lt(t){return Symbol.for(`graphrefly:node:${t}`)}var Pn=new Map,Dn=new Map,Gn=new Map,Fn=new Map,$n=new Map,jn=new Map,Bn=new Map;function vd(t){return t==="request"?(0,Cr.Inject)(on):(0,Cr.Inject)(t?ot(t):ct)}function Td(t){return(0,Cr.Inject)(ot(t))}function wd(t){return(0,Cr.Inject)(lt(t))}function kd(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 xd(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=Dn.get(o)??[];s.push({ms:t,methodKey:r}),Dn.set(o,s)})}}function Rd(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=Gn.get(o)??[];s.push({expr:t,methodKey:r}),Gn.set(o,s)})}}function Sd(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=Fn.get(s)??[];i.push({cqrsName:t,commandName:e,methodKey:o}),Fn.set(s,i)})}}function Ed(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=$n.get(s)??[];i.push({cqrsName:t,eventName:e,methodKey:o}),$n.set(s,i)})}}function Nd(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 _d(t,e,n){return(r,o)=>{let s=o.name;o.addInitializer(function(){let i=this.constructor,a=Bn.get(i)??[];a.push({cqrsName:t,eventNames:n,sagaName:e,methodKey:s}),Bn.set(i,a)})}}ae();he();var Hd=0,cn=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]===E&&o(u[1])});this.disposers.push(i)}wireIntervals(){for(let[e,n]of Dn){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)}.${Hd++}`,u=st(r.ms,{period:r.ms,name:a});this.graph.add(u),this.scheduleNodeNames.push(a);let c=this.observeNode(a).subscribe(l=>{for(let p of l)p[0]===E&&s(p[1])});this.disposers.push(c)}wireCrons(){for(let[e,n]of Gn){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)}.${Hd++}`,u=Qo(r.expr,{name:a});this.graph.add(u),this.scheduleNodeNames.push(a);let c=this.observeNode(a).subscribe(l=>{for(let p of l)p[0]===E&&s(p[1])});this.disposers.push(c)}wireCqrsCommands(){for(let[e,n]of Fn){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 $n){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,c=this.observeNodeOn(s,n.eventName).subscribe(l=>{for(let p of l)if(p[0]===E){let f=p[1];for(let m of f)m.seq>u&&(o(m),u=m.seq)}});this.disposers.push(c)}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 d of u)d[0]===E&&o(d[1])});this.disposers.push(a)}wireCqrsSagas(){for(let[e,n]of Bn){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(ot(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}}};ae();ae();var hm=0;function Un(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-${++hm}`),r=0,o=!1;return{onEnqueue(){return r+=1,!o&&r>=e.highWaterMark?(o=!0,t([[Be,n]]),!0):!1},onDequeue(){return r>0&&(r-=1),o&&r<=e.lowWaterMark?(o=!1,t([[qe,n]]),!0):!1},get pending(){return r},get paused(){return o},dispose(){o&&(o=!1,t([[qe,n]]))}}}function Wd(t,e,n){let{actor:r,serialize:o=ym,keepAliveMs:s,signal:i}=n??{},a=new TextEncoder,u,d=n?.highWaterMark!=null,c,l,p=[],f=!1;return new ReadableStream({start(m){let h,g=()=>{},y=()=>{if(!f){f=!0,h!==void 0&&clearInterval(h),i?.removeEventListener("abort",b),g(),c?.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});d&&(c=Un(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(f)return;let k=w[0];if(k===E){let x=a.encode(fa("data",o(w[1])));d?(p.push({frame:x,counted:!0}),c.onEnqueue(),l?.(),l=void 0):m.enqueue(x)}else if(k===A){let x=a.encode(fa("error",o(w[1])));d?(p.push({frame:x,counted:!1}),l?.(),l=void 0):m.enqueue(x),y();return}else if(k===L||k===de){if(k===L){let x=a.encode(fa("complete"));d?(p.push({frame:x,counted:!1}),l?.(),l=void 0):m.enqueue(x)}y();return}}}),s!==void 0&&s>0&&(h=setInterval(()=>{f||(d?(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(d&&!f){if(p.length>0){let h=p.shift();m.enqueue(h.frame),h.counted&&c.onDequeue();return}return new Promise(h=>{l=h})}},cancel(){try{u?.()}catch{}}})}function zd(t,e,n){let{actor:r,filter:o}=n??{},s=[],i=[],a=!1,u=t.observe(e,{actor:r}),d=n?.highWaterMark!=null?Un(m=>u.up(m),{highWaterMark:n.highWaterMark,lowWaterMark:n.lowWaterMark??Math.floor(n.highWaterMark/2)}):void 0,c=()=>{a||(a=!0,d?.dispose(),p())},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||d?.onEnqueue()},p=u.subscribe(m=>{for(let h of m){let g=h[0];if(g===E){let y=h[1];if(o&&!o(y))continue;l({done:!1,value:y})}else if(g===C){let y=h[1]instanceof Error?h[1]:new Error(String(h[1]));l({done:!0,error:y}),c();return}else if(g===L||g===le){l({done:!0}),c();return}}});return{next(){if(s.length>0){let m=s.shift();return m.done||d?.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(){c();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 c(),Promise.reject(m)},[Symbol.asyncIterator](){return this}}}var ns=class{constructor(e,n){this.graph=e;this.extractActor=n?.extractActor??(()=>{}),this.parse=n?.parse??hm,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??ym.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(c){let l=c instanceof Error?c.message:String(c);r({type:"err",message:l});return}let a=this.highWaterMark!=null?Un(c=>i.up(c),{highWaterMark:this.highWaterMark,lowWaterMark:this.lowWaterMark??Math.floor(this.highWaterMark/2)}):void 0,u=()=>{a?.dispose(),d(),o.delete(n)},d=i.subscribe(c=>{for(let l of c){let p=l[0];if(p===E)a?.onEnqueue(),ma(r,{type:"data",path:n,value:l[1]});else if(p===C){let f=l[1]instanceof Error?l[1].message:String(l[1]);ma(r,{type:"error",path:n,error:f}),u();return}else if(p===L||p===le){ma(r,{type:"complete",path:n}),u();return}}});o.set(n,{unsub:d,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 gm(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)}catch{return String(t)}}function fa(t,e){let n=`event: ${t}
5
+ `)))},s)),i?.aborted?b():i?.addEventListener("abort",b,{once:!0})},pull(m){if(d&&!f){if(p.length>0){let h=p.shift();m.enqueue(h.frame),h.counted&&c.onDequeue();return}return new Promise(h=>{l=h})}},cancel(){try{u?.()}catch{}}})}function zd(t,e,n){let{actor:r,filter:o}=n??{},s=[],i=[],a=!1,u=t.observe(e,{actor:r}),d=n?.highWaterMark!=null?Un(m=>u.up(m),{highWaterMark:n.highWaterMark,lowWaterMark:n.lowWaterMark??Math.floor(n.highWaterMark/2)}):void 0,c=()=>{a||(a=!0,d?.dispose(),p())},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||d?.onEnqueue()},p=u.subscribe(m=>{for(let h of m){let g=h[0];if(g===E){let y=h[1];if(o&&!o(y))continue;l({done:!1,value:y})}else if(g===A){let y=h[1]instanceof Error?h[1]:new Error(String(h[1]));l({done:!0,error:y}),c();return}else if(g===L||g===de){l({done:!0}),c();return}}});return{next(){if(s.length>0){let m=s.shift();return m.done||d?.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(){c();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 c(),Promise.reject(m)},[Symbol.asyncIterator](){return this}}}var ns=class{constructor(e,n){this.graph=e;this.extractActor=n?.extractActor??(()=>{}),this.parse=n?.parse??bm,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??vm.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(c){let l=c instanceof Error?c.message:String(c);r({type:"err",message:l});return}let a=this.highWaterMark!=null?Un(c=>i.up(c),{highWaterMark:this.highWaterMark,lowWaterMark:this.lowWaterMark??Math.floor(this.highWaterMark/2)}):void 0,u=()=>{a?.dispose(),d(),o.delete(n)},d=i.subscribe(c=>{for(let l of c){let p=l[0];if(p===E)a?.onEnqueue(),ma(r,{type:"data",path:n,value:l[1]});else if(p===A){let f=l[1]instanceof Error?l[1].message:String(l[1]);ma(r,{type:"error",path:n,error:f}),u();return}else if(p===L||p===de){ma(r,{type:"complete",path:n}),u();return}}});o.set(n,{unsub:d,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 ym(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)}catch{return String(t)}}function fa(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 hm(t){return JSON.parse(t)}function ym(t,e){try{t.send(JSON.stringify(e))}catch{}}function ma(t,e){try{t(e)}catch{}}kr();var rs="graphReflyActor";function ga(t){return e=>{let r=e.switchToHttp().getRequest()?.user;if(r!=null)return t?t(r):r}}function Ud(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 Jd(t){let e=t?.[rs];return e!=null?Nt(e):bt}var Pr=class{constructor(e){this.extractor=e}canActivate(e){let n=Nt(this.extractor(e)),r=e.switchToHttp().getRequest();return r!=null&&(r[rs]=n),!0}};function Yd(t){return new Pr(t??ga())}var Wr=require("@nestjs/common"),xc=require("@nestjs/core");kr();Me();xe();$t();ae();$t();_e();function Ct(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 bm(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function vm(t){let e={};for(let[n,r]of Object.entries(t.meta))try{e[n]=r.cache}catch{}return e}function Dr(t,e){let n=e==null,r=!n&&e!=null?[...e].filter(d=>d.startsWith("meta.")).map(d=>d.slice(5)):null,o=n||e.has("meta")||r!=null&&r.length>0,s="state",i=[];t instanceof Ae&&(s=bm(t),i=t._deps.map(d=>d.node.name??""));let a={type:s,deps:i};(n||e.has("status"))&&(a.status=t.status);let u=t instanceof Ae?t._guard:void 0;if(o){let d={...vm(t)};if(u!=null&&d.access===void 0&&(d.access=_r(u)),r!=null&&r.length>0&&!e.has("meta")){let c={};for(let l of r)l in d&&(c[l]=d[l]);a.meta=c}else a.meta=d}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 d={id:t.v.id,version:t.v.version};"cid"in t.v&&(d.cid=t.v.cid,d.prev=t.v.prev),a.v=d}return(n||e.has("guard"))&&u!=null&&(a.guard=_r(u)),(n||e.has("lastMutation"))&&t.lastMutation!=null&&(a.lastMutation=t.lastMutation),a}_e();ee();he();vt();var ln=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}};Lo();function ha(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 Jn(t){let e=0;for(let n of t)e+=ha(n.codePointAt(0));return e}function Qd(t,e){if(e<=0)return"";let n=0,r="";for(let o of t){let s=ha(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-=ha(i.codePointAt(0))}return`${r}\u2026`}r+=o,n+=s}return r}var Tm={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"},wm={horizontal:"-",vertical:"|",cornerTL:"+",cornerTR:"+",cornerBL:"+",cornerBR:"+",tDown:"+",tUp:"+",tRight:"+",tLeft:"+",cross:"+",arrowRight:">",arrowDown:"v",arrowLeft:"<",arrowUp:"^",boxTL:"+",boxTR:"+",boxBL:"+",boxBR:"+",boxH:"-",boxV:"|"};function tc(t,e){let n=e.charset==="ascii"?wm:Tm,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)xm(s,i,n,a);for(let a of t.boxes)km(s,i,n,a,e.labelOf(a.id));return s.map(a=>Nm(a.join(""))).join(`
10
- `)}function km(t,e,n,r,o){let{x:s,y:i,w:a,h:u}=r;if(a<2||u<2){u>0&&Xd(t,e,s,i,a,o);return}Ht(t,e,s,i,n.boxTL);for(let c=s+1;c<s+a-1;c+=1)Ht(t,e,c,i,n.boxH);Ht(t,e,s+a-1,i,n.boxTR);for(let c=i+1;c<i+u-1;c+=1){Ht(t,e,s,c,n.boxV);for(let l=s+1;l<s+a-1;l+=1)nc(t,e,l,c," ","empty");Ht(t,e,s+a-1,c,n.boxV)}Ht(t,e,s,i+u-1,n.boxBL);for(let c=s+1;c<s+a-1;c+=1)Ht(t,e,c,i+u-1,n.boxH);Ht(t,e,s+a-1,i+u-1,n.boxBR);let d=i+Math.floor(u/2);Xd(t,e,s+1,d,a-2,o)}function Ht(t,e,n,r,o){nc(t,e,n,r,o,o===" "?"empty":o==="\u2500"||o==="-"?"boxH":o==="\u2502"||o==="|"?"boxV":"boxCorner")}function nc(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 Xd(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=n,a=o;for(let u of s){let d=Jn(u);if(d!==0){if(a<d)break;i>=0&&i<t[r].length&&(t[r][i]=u,e[r][i]="label",d===2&&i+1<t[r].length&&(t[r][i+1]="",e[r][i+1]="label")),i+=d,a-=d}}for(;a>0;)i>=0&&i<t[r].length&&(t[r][i]=" ",e[r][i]="empty"),i+=1,a-=1}function xm(t,e,n,r){let o=r.points;if(o.length<2)return;for(let u=0;u+1<o.length;u+=1)Rm(t,e,n,o[u],o[u+1]);for(let u=1;u+1<o.length;u+=1){let d=o[u-1],c=o[u],l=o[u+1],p=Sm(d,c,l,n);p&&ec(t,e,c.x,c.y,p,"edgeCorner")}let s=o[o.length-1],i=o[o.length-2],a=Em(i,s,n);a&&ec(t,e,s.x,s.y,a,"arrow")}function Rm(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)Zd(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)Zd(t,e,s,u,n,"v")}}}function Zd(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 ec(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 Sm(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,d=n.y>e.y;return u&&d?r.cornerTR:u&&!d?r.cornerBR:!u&&d?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 Em(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 Nm(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}function sc(t){let e=_m(t);Mm(e),Om(e),Cm(e),Am(e,t);let n=Pm(e,t),{width:r,height:o}=Gm(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 _m(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 Mm(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 Om(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 d=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:d.id,toId:p,hopIndex:l-1,chainLen:u};d.out.push(m),f.in.push(m),r.push(m),d=f}let c={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:d.id,toId:a.id,hopIndex:u-1,chainLen:u};d.out.push(c),a.in.push(c),r.push(c)}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 Cm(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)rc(t,t.layers[r],"in"),os(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)rc(t,t.layers[r],"out"),os(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=oc(t,s[i],s[i+1],"in");[s[i],s[i+1]]=[s[i+1],s[i]],os(s),oc(t,s[i],s[i+1],"in")<a?r=!0:([s[i],s[i+1]]=[s[i+1],s[i]],os(s))}}if(!r)break}}function rc(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 d=t.nodes.get(n==="in"?u.fromId:u.toId);d&&(i+=d.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 os(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function oc(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 d=t.nodes.get(r==="in"?a.fromId:a.toId)?.order??0,c=t.nodes.get(r==="in"?u.fromId:u.toId)?.order??0;(e.order<n.order&&d>c||e.order>n.order&&d<c)&&(i+=1)}return i}function Am(t,e){e.direction==="LR"?Lm(t,e):Im(t,e)}function Lm(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}ic(t,e,"y")}function Im(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}ic(t,e,"x")}function ic(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 c of a){let l=s===0?c.in:c.out;if(l.length===0)continue;let p=[];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;p.push(g+Math.floor(r(h)/2))}if(p.length===0)continue;p.sort((m,h)=>m-h);let f=p[Math.floor(p.length/2)];u.set(c.id,f-Math.floor(r(c)/2))}let d=0;for(let c of a){let l=u.get(c.id),p=n==="y"?c.y:c.x,m=Math.max(l??p,d);n==="y"?c.y=m:c.x=m,d=m+r(c)+o}}}}function Pm(t,e){let n=new Map;for(let d of t.hops){let c=n.get(d.chainId);c?c.push(d):n.set(d.chainId,[d])}for(let d of n.values())d.sort((c,l)=>c.hopIndex-l.hopIndex);let r=e.direction==="LR",o=d=>r?d.x:d.y,s=d=>r?d.w:d.h,i=d=>r?d.y+Math.floor(d.h/2):d.x+Math.floor(d.w/2),a=new Map;for(let d=0;d+1<t.layers.length;d+=1){let c=t.layers[d],l=t.layers[d+1],p=0;for(let S of c)p=Math.max(p,o(S)+s(S));let f=Number.POSITIVE_INFINITY;for(let S of l)f=Math.min(f,o(S));let m=Number.isFinite(f)?f-1:p,h=Math.max(1,m-p+1),g=[];for(let S of c)for(let R of S.out)g.push(R);g.sort((S,R)=>{let N=i(t.nodes.get(S.fromId)),_=i(t.nodes.get(R.fromId));if(N!==_)return N-_;let I=i(t.nodes.get(S.toId)),O=i(t.nodes.get(R.toId));return I-O});let y=[],b=new Map;for(let S of g){let R=i(t.nodes.get(S.fromId)),N=i(t.nodes.get(S.toId)),_=Math.min(R,N),I=Math.max(R,N),O=-1;for(let P=0;P<y.length;P+=1){let B=y[P],j=!0;for(let D of B)if(D.lo<=I&&_<=D.hi){j=!1;break}if(j){B.push({lo:_,hi:I}),O=P;break}}O<0&&(y.push([{lo:_,hi:I}]),O=y.length-1),b.set(S,O)}let v=y.length,T=h>=Math.max(3,v+2),w=T?p+1:p,x=T?m-1:m,k=Math.max(1,x-w+1);for(let S of g){let R=b.get(S),N;if(v<=1)N=w+Math.floor(k/2);else{let _=(k-1)/(v-1);N=w+Math.floor(R*_)}a.set(S,Math.max(p,Math.min(m,N)))}}let u=[];for(let[,d]of n){let c=[];for(let p=0;p<d.length;p+=1){let f=d[p],m=t.nodes.get(f.fromId),h=t.nodes.get(f.toId),g=a.get(f),y=m.isVirtual?o(m):o(m)+s(m),b=h.isVirtual?o(h):o(h)-1,v=i(m),T=i(h);p===0&&ss(c,r,y,v),v!==T&&(ss(c,r,g,v),ss(c,r,g,T)),ss(c,r,b,T)}let l=d[0];u.push({from:l.chainFrom,to:l.chainTo,points:Dm(c)})}return u}function ss(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function Dm(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 Gm(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 Fm=24,$m=4,jm=1,Bm=3;function ac(t,e){let n=Vm(e.direction),r=Math.max(3,e.maxLabelWidth??Fm),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,d=new Map;for(let f of s){let m=Qd(f,r);u.set(f,m),d.set(f,Jn(m)+4)}let c=sc({nodes:s,edges:a,widthCells:f=>d.get(f)??3,heightCells:()=>Bm,layerGap:$m,nodeGap:jm,direction:n}),l=tc(c,{charset:o,labelOf:f=>u.get(f)??f}),p=e.logger;return p&&p(l),l}function Vm(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 Gr(t,e,n,r={}){let o=e in t.nodes,s=n in t.nodes;if(!o)return is(e,n,"no-such-from");if(!s)return is(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 d=Km(t,e,r);if(d!=null)return d}let u=as(e,t.nodes[e],0,r);return us(e,n,[u])}if(i===0)return is(e,n,"no-path");let a=uc(t,e,n,i);return a.found?us(e,n,dc(t,a.pathOrder,r)):is(e,n,a.truncated?"max-depth-exceeded":"no-path")}function uc(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 p=t.nodes[l.path];if(p==null)continue;let f=p.deps??[],m=new Map;for(let h=0;h<f.length;h++){let g=f[h];if(!g)continue;let y=m.get(g);y==null&&(y=[],m.set(g,y)),y.push(h)}for(let[h,g]of m)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 d=[{path:e}],c=e;for(;c!==n;){let l=o.get(c);if(l==null)return{found:!1,pathOrder:[],truncated:!1};d[d.length-1].depIndices=l.depIndices,d.push({path:l.from}),c=l.from}return{found:!0,pathOrder:d,truncated:!1}}function Km(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=as(e,r,0,n);a.dep_index=s[0];let u=as(e,r,1,n);return us(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 d=uc(t,u,e,n.maxDepth);d.found&&(i==null||d.pathOrder.length<i.pathOrder.length)&&(i=d,i={found:!0,pathOrder:[{path:e,depIndices:[a]},...d.pathOrder],truncated:!1})}return i==null?null:us(e,e,dc(t,i.pathOrder,n))}function dc(t,e,n){return e.map((r,o)=>{let s=t.nodes[r.path],i=as(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 as(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 us(t,e,n){return cc(t,e,!0,"ok",n)}function is(t,e,n){return cc(t,e,!1,n,[])}function cc(t,e,n,r,o){let s=qm(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 qm(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: ${Hm(i.value)}`),i.annotation!=null&&s.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let d=i.lastMutation.actor;s.push(` actor: ${d.type}${d.id?`:${d.id}`:""}`)}}return s.join(`
11
- `)}function Hm(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)}}_e();var je={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},ds=Symbol.for("sizeof");function Fr(t){let e=new WeakSet,n=new WeakSet,r=[t],o=0;for(;r.length>0;){let s=r.pop();o+=Wm(s,e,n,r)}return o}function Wm(t,e,n,r){if(t==null)return 0;switch(typeof t){case"number":return je.number;case"boolean":return je.boolean;case"string":return je.string+t.length*2;case"bigint":return je.bigint+zm(t);case"symbol":return je.symbol;case"function":return e.has(t)?0:(e.add(t),je.function);case"undefined":return 0}let s=t;if(e.has(s))return 0;e.add(s);let i=s[ds];if(typeof i=="function")try{let d=i.call(s);if(typeof d=="number"&&Number.isFinite(d))return d}catch{}if(s instanceof Date)return je.date;if(s instanceof RegExp)return je.regexp+s.source.length*2;if(s instanceof Error){let d=s.message?s.message.length*2:0,c=s.stack?s.stack.length*2:0;return je.error+d+c}if(typeof URL<"u"&&s instanceof URL)return je.url+s.href.length*2;if(typeof Promise<"u"&&s instanceof Promise)return je.promise;if(s instanceof WeakMap)return je.weakmap;if(s instanceof WeakSet)return je.weakset;if(s instanceof Map){let d=je.map;for(let[c,l]of s)d+=je.mapEntry,r.push(c),r.push(l);return d}if(s instanceof Set){let d=je.set;for(let c of s)d+=je.setEntry,r.push(c);return d}if(Array.isArray(s)){let d=je.array+s.length*8;for(let c of s)r.push(c);return d}if(s instanceof ArrayBuffer)return n.has(s)?0:(n.add(s),s.byteLength);if(ArrayBuffer.isView(s)){let d=s;return n.has(d.buffer)?48:(n.add(d.buffer),d.buffer.byteLength+48)}let a=je.object,u=Object.keys(s);for(let d of u){a+=je.string+d.length*2;try{r.push(s[d])}catch{}}return a}function zm(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 pn(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),h=m instanceof Ae?m:null,g=h?Fr(h.cache):0,y=h?h._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:g,subscriberCount:y,depCount:b,isOrphanEffect:v,orphanKind:T})}let u=a.reduce((p,f)=>p+f.valueSizeBytes,0),d=(p,f)=>[...a].sort(f??((m,h)=>h[p]-m[p])).slice(0,n),c=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:d("valueSizeBytes"),bySubscriberCount:d("subscriberCount"),byDepCount:d("depCount")},orphans:c,orphanEffects:l}}var De="::",Qe="__meta__",ft=1;function lc(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 Um(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 pc(t){if(t.version!==ft)throw new Error(`unsupported snapshot version ${String(t.version)} (expected ${ft})`);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 Jm(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 h of p)if(r(f,h)){m=!0;break}if(!m)return!1}return!0}if(ArrayBuffer.isView(o)){let p=o,f=s;if(p.length!==f.length)return!1;for(let m=0;m<p.length;m++)if(p[m]!==f[m])return!1;return!0}let d=Object.keys(o),c=Object.keys(s);if(d.length!==c.length)return!1;let l=new Set(c);for(let p of d)if(!l.has(p)||!r(o[p],s[p]))return!1;return!0};return r(t,e)}function ba(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(ba);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=ba(e[o]);return r}function Ym(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Qm(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Xm(t){return t==="TD"?"down":t==="BT"?"up":t==="RL"?"left":"right"}function mc(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 gc(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 Zm(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(ba(i),null,e.indent??2);return e.logger?.(a),a}function eg(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}): ${ls(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 hc(t,e){let n=gc(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}["${Ym(i)}"]`)}for(let[i,a]of mc(t)){let u=o.get(i),d=o.get(a);!u||!d||s.push(` ${u} --> ${d}`)}return s.join(`
14
- `)}function tg(t,e){let n=hc(t,e);return ps(n)}function ps(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 d=0;d<i.length;d++)a+=String.fromCharCode(i[d]);return`https://mermaid.live/edit#base64:${globalThis.btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`}function ng(t,e){let n=gc(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: ${Xm(n)}`];for(let i of r){let a=o.get(i);s.push(`${a}: "${Qm(i)}"`)}for(let[i,a]of mc(t)){let u=o.get(i),d=o.get(a);!u||!d||s.push(`${u} -> ${d}`)}return s.join(`
15
- `)}function rg(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function cs(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+=rg(r)}return e+="$",new RegExp(e)}var og={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"},sg={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function ls(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 ig(t){return t==="none"?sg:t==="ansi"||t==null?og:{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 fc(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 ag(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 ya(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(De))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${De}' (path separator)`);if(t===Qe)throw new Error(`Graph "${e}": ${n} name "${Qe}" is reserved for meta companion paths`);ag(t,e,n)}function ug(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(De);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function dg(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 yc(t){for(let e of t._mounts.values())yc(e);for(let e of t._nodes.values())try{e.down([[le]],{internal:!0})}catch{}}var Y=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(De))throw new Error(`Graph name must not contain '${De}' (got "${e}")`);if(e===Qe)throw new Error(`Graph name "${Qe}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??$e,this._traceRing=new ln(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=K(e=>{let n=r=>{e.emit(r)};return this._topologyEmitters.add(n),()=>{this._topologyEmitters.delete(n)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let n of this._topologyEmitters)n(e)}nameOf(e){return this._nodeToName.get(e)}add(e,n){let r=e.name,o=n?.name??r;if(o==null||o==="")throw new Error(`Graph "${this.name}": graph.add requires a non-empty name \u2014 pass via opts.name or set it on the node (e.g. state(0, { name: "x" }))`);let s=o,i=n?.annotation;if(ya(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:H()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof Ae&&n._applyVersioning(e)}remove(e){ya(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(`${De}${Qe}${De}`)||s.nodes.push(a);return s.nodes.sort(),s.mounts.push(e),s.mounts.push(...n._collectSubgraphs(`${e}${De}`)),this._mounts.delete(e),n._parent=void 0,yc(n),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:s}),s}let r=this._nodes.get(e);if(!r)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(r),r.down([[le]],{internal:!0});let o={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:o}),o}removeAll(e){let n=typeof e=="function"?e:(()=>{let s=cs(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(De))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([[E,n]],{actor:r?.actor,internal:o,delivery:"write"})}setAll(e,n){let r=Symbol.iterator in e?e:Object.entries(e);X(()=>{for(let[o,s]of r)this.set(o,s,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[Je]],{actor:n?.actor,internal:r,delivery:"write"})}error(e,n,r){let o=r?.internal===!0;this.node(e).down([[C,n]],{actor:r?.actor,internal:o,delivery:"write"})}complete(e,n){let r=n?.internal===!0;this.node(e).down([[L]],{actor:n?.actor,internal:r,delivery:"write"})}edges(e){let n=e?.recursive===!0,r=new Map;if(!n){for(let[u,d]of this._nodes)r.set(d,u);let a=[];for(let[u,d]of this._nodes)if(d instanceof Ae)for(let c of d._deps){let l=r.get(c.node);l!=null&&a.push([l,u])}return a.sort((u,d)=>u[0]<d[0]?-1:u[0]>d[0]?1:u[1]<d[1]?-1:u[1]>d[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 Ae)for(let d of u._deps){let c=s.get(d.node);c!=null&&i.push([c,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(n===void 0){let o=new t(e);return this.mount(e,o)}if(typeof n=="function"){let o=new t(e);return n(o),this.mount(e,o)}let r=n;if(ya(e,this.name,"mount"),this._nodes.has(e))throw new Error(`Graph "${this.name}": cannot mount at "${e}" \u2014 node with that name exists`);if(this._mounts.has(e))throw new Error(`Graph "${this.name}": mount "${e}" already exists`);if(r===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(r._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${r._parent.name}"`);for(let o=this;o!=null;o=o._parent)if(o===r)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,r),r._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),r}resolve(e){let n=ug(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]===Qe)return this._resolveMetaChainFromNode(s,o,n.join(De));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(De)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(o.join(De))}_resolveMetaChainFromNode(e,n,r){let o=e,s=0,i=[...n];for(;s<i.length;){if(i[s]!==Qe)throw new Error(`Graph "${this.name}": expected ${Qe} segment in meta path "${r}"`);if(s+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${Qe} 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=dg(e,this.config);for(let u of[...this._nodes.keys()].sort()){let d=this._nodes.get(u);if(!r.has(d)){r.add(d);try{d.down(e,i)}catch(c){if(c instanceof rt)throw c;o.push(c)}a.length!==0&&this._signalMetaSubtree(d,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 rt)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=Ct(e?.detail,e?.fields),s=e?.format==="spec",i=s?Ct("minimal"):o,a=[];this._collectObserveTargets("",a);let u=new Map;for(let[x,k]of a)u.set(k,x);let d=[];{let x=a.map(([,R])=>R),k=new Set(u.values()),S=0;for(;x.length>0;){let R=x.shift();if(R instanceof Ae)for(let N of R._deps){let _=N.node;if(u.has(_))continue;let I=_.name??"",O=I;if(!O||k.has(O))if(I){let P=2;for(;k.has(`${I}#${P}`);)P++;O=`${I}#${P}`}else for(O=`__internal__/${S++}`;k.has(O);)O=`__internal__/${S++}`;u.set(_,O),k.add(O),d.push([O,_]),x.push(_)}}}let c=[...a,...d],l={};for(let[x,k]of c){if(n!=null&&!k.allowsObserve(n))continue;let S=Dr(k,i),R=k instanceof Ae?k._deps.map(O=>u.get(O.node)??O.node.name??""):[],{name:N,..._}=S,I={..._,deps:R};if(!s){let O=this._annotations.get(x);O!=null&&(I.annotation=O)}if(r!=null)if(typeof r=="function"){let O=r;if(!(O.length>=2?O(x,I):O(I)))continue}else{let O=!0;for(let[P,B]of Object.entries(r)){let j=P==="deps_includes"?"depsIncludes":P==="meta_has"?"metaHas":P;if(j==="depsIncludes"){if(!I.deps.includes(String(B))){O=!1;break}continue}if(j==="metaHas"){if(!Object.hasOwn(I.meta??{},String(B))){O=!1;break}continue}if(I[j]!==B){O=!1;break}}if(!O)continue}l[x]=I}let p=new Set(Object.keys(l)),f=[];for(let[x,k]of c)if(k instanceof Ae)for(let S of k._deps){let R=u.get(S.node);R!=null&&f.push([R,x])}f.sort((x,k)=>x[0]<k[0]?-1:x[0]>k[0]?1:x[1]<k[1]?-1:x[1]>k[1]?1:0);let m=f.map(([x,k])=>({from:x,to:k}));(n!=null||r!=null)&&(m=m.filter(x=>p.has(x.from)&&p.has(x.to)));let h=this._collectSubgraphs(""),g=n!=null||r!=null?h.filter(x=>{let k=`${x}${De}`;return[...p].some(S=>S===x||S.startsWith(k))}):h,y=this,b=e,v={name:this.name,nodes:l,edges:m,subgraphs:g,expand(x){let k={...b,format:void 0};return Array.isArray(x)?(k.fields=x,k.detail=void 0):(k.detail=x,k.fields=void 0),y.describe(k)}},T=e??{},w=T.format;return w==="json"?Zm(v,T):w==="pretty"?eg(v,T):w==="mermaid"?hc(v,T):w==="mermaid-url"?tg(v,T):w==="d2"?ng(v,T):w==="ascii"?ac(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}${De}`))}return n}resourceProfile(e){return pn(this,e)}reachable(e,n,r={}){return r.withDetail===!0?fn(this.describe(),e,n,{...r,withDetail:!0}):fn(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 Gr(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=M(o,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,u=!1,d=()=>{a||u||(a=!0,Sr(()=>{a=!1,!u&&(o+=1,s.emit(o))}))},c=i.onEvent(g=>{let y=g.type;y!=="data"&&y!=="error"&&y!=="complete"&&y!=="teardown"||d()}),l=[],p=new WeakSet,f=g=>{if(p.has(g)||u)return;p.add(g);let y=g.topology.subscribe(b=>{for(let v of b){if(v[0]!==E)continue;let T=v[1];if(d(),T.kind==="added"&&T.nodeKind==="mount"){let w=g._mounts.get(T.name);w!=null&&f(w)}}});l.push(y);for(let b of g._mounts.keys()){let v=g._mounts.get(b);v!=null&&f(v)}};f(this);let m;try{m=A([s],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(g,y)=>g===y})}catch(g){c();for(let y of l)y();throw i.dispose(),g}let h=re(m);return{node:m,dispose(){u=!0,c();for(let g of l)g();l.length=0,i.dispose(),h()}}}_explainReactive(e,n,r){let o=0,s=M(o,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,u=!1,d=i.onEvent(f=>{let m=f.type;m!=="data"&&m!=="error"&&m!=="complete"&&m!=="teardown"||a||u||(a=!0,Sr(()=>{a=!1,!u&&(o+=1,s.emit(o))}))}),c={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},l;try{l=A([s],()=>this._explainStatic(e,n,c),{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&&cg(f.steps,m.steps)})}catch(f){throw d(),i.dispose(),f}let p=re(l);return{node:l,dispose(){u=!0,d(),i.dispose(),p()}}}_pathsMatching(e){let n=cs(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}${De}${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}${De}${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}${De}${Qe}${De}${o}`;r.push([i,s]),this._appendMetaObserveTargets(i,s,r)}}observe(e,n){let r=typeof e=="string",s=fc(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 c=e,l=this.resolve(c);if(a!=null&&!l.allowsObserve(a))throw new rt({actor:a,action:"observe",nodeName:c});return i?this._buildStructuredObserver([[c,l]],s,"one"):{subscribe(p){return l.subscribe(p)},up(p){try{l.up?.(p)}catch(f){if(f instanceof rt)return;throw f}}}}let u=[];this._collectObserveTargets("",u),u.sort((c,l)=>c[0]<l[0]?-1:c[0]>l[0]?1:0);let d=a==null?u:u.filter(([,c])=>c.allowsObserve(a));return i?this._buildStructuredObserver(d,s,"all"):{subscribe:c=>{let l=d.map(([p,f])=>f.subscribe(m=>{c(p,m)}));return()=>{for(let p of l)p()}},up:(c,l)=>{try{this.resolve(c).up?.(l)}catch(p){if(p instanceof rt)return;throw p}}}}_buildStructuredObserver(e,n,r){let o=r==="one"?e[0]?.[0]:void 0,s=i=>{if(r==="one"&&o!=null){let c=this.resolve(o);return this._buildStructuredObserver([[o,c]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((c,l)=>c[0]<l[0]?-1:c[0]>l[0]?1:0);let u=i.actor,d=u==null?a:a.filter(([,c])=>c.allowsObserve(u));return this._buildStructuredObserver(d,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,d=(s||i)&&u,c=n.maxEvents,l=c!=null&&c>0?new ln(c):null,p=[],f=new Set,m={},h=new Set,g=0,y=0,b=0,v=0,T=0,w=0,x=!1,k=!1,S=0,R=new Map,N=new Map,_=new Map,I=$=>{l?l.push($):p.push($);for(let te of f)te($)},O=()=>o?{timestamp_ns:H(),in_batch:tn(),batch_id:S}:{},P=($,te)=>{if(!(!d||!($ instanceof Ae)))return $._setInspectorHook(Re=>{if(Re.kind==="dep_message")R.set($,Re.depIndex);else if(Re.kind==="run"){let Oe=Re.batchData.map((ye,Ge)=>ye!=null&&ye.length>0?ye.at(-1):Re.prevData[Ge]);N.set($,Oe);let Ce=Re.batchData.map(ye=>ye!=null?[...ye]:void 0);_.set($,Ce),i&&I({type:"derived",path:te,dep_values:Oe,dep_batches:Ce,...O()})}})},B=$=>{let te=R.get($),Re=N.get($);if(!s||Re==null)return{};let Ce=(te!=null&&te>=0&&$ instanceof Ae?$._deps[te]:void 0)?.node,ye=Ce?.v,Ge=_.get($);return{trigger_dep_index:te,trigger_dep_name:Ce?.name,...ye!=null?{trigger_version:{id:ye.id,version:ye.version}}:{},dep_values:[...Re],...Ge!=null?{dep_batches:Ge}:{}}},j=[],D=[];for(let[$,te]of e){let Re=P(te,$);Re&&j.push(Re),D.push(te.subscribe(Oe=>{S++;for(let Ce of Oe){let ye=Ce[0],Ge=O();if(ye===E){m[$]=Ce[1];let ie=te instanceof Ae?te.lastMutation?.actor??bt:bt;I({type:"data",path:$,data:Ce[1],actor:ie,...Ge,...B(te)})}else if(a)ye===ne?g++:ye===V?y++:ye===Je?b++:ye===Be?v++:ye===qe?T++:ye===le?w++:ye===L&&!h.has($)?x=!0:ye===C&&(k=!0,h.add($));else if(ye===ne)g++,I({type:"dirty",path:$,...Ge});else if(ye===V)y++,I({type:"resolved",path:$,...Ge,...B(te)});else if(ye===Je)b++,I({type:"invalidate",path:$,...Ge});else if(ye===Be)v++,I({type:"pause",path:$,lockId:Ce[1],...Ge});else if(ye===qe)T++,I({type:"resume",path:$,lockId:Ce[1],...Ge});else if(ye===L)h.has($)||(x=!0),I({type:"complete",path:$,...Ge});else if(ye===C){k=!0,h.add($);let ie=te instanceof Ae?te.lastMutation?.actor??bt:bt;I({type:"error",path:$,data:Ce[1],actor:ie,...Ge})}else ye===le&&(w++,I({type:"teardown",path:$,...Ge}))}}))}let Z=!1,F=()=>{if(!Z){Z=!0;for(let $ of D)$();for(let $ of j)$();for(let $ of G)$({value:void 0,done:!0});G.length=0}},Q=[],G=[];f.add($=>{let te=G.shift();te?te({value:$,done:!1}):Q.push($)});let q={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():[...p]},get anyCompletedCleanly(){return x},get anyErrored(){return k},get completedWithoutErrors(){return x&&!k},onEvent($){return f.add($),()=>f.delete($)},dispose:F,expand($){F();let te={...n};return typeof $=="string"?te.detail=$:Object.assign(te,$),r(fc(te))},[Symbol.asyncIterator](){return{next(){return Q.length>0?Promise.resolve({value:Q.shift(),done:!1}):Z?Promise.resolve({value:void 0,done:!0}):new Promise($=>G.push($))},return(){return F(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(q,n),q}_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=ig(n.theme),d=r==="stage-log"?H():0,c=m=>m==null?"":n.stageLabels?.[m]??m,l=(m,h)=>m.length>h?`${m.slice(0,h-1)}\u2026`:m,p=m=>m.type==="data"||m.type==="error"?l(ls(m.data),120):"",f=m=>{if(r==="stage-log"){let k=(H()-d)/1e9,S=c(m.path).padEnd(9);if(m.type==="data"){let R=p(m);return`[${k.toFixed(3)}s] ${S} \u2190${R?` ${R}`:""}`}if(m.type==="error"){let R=p(m);return`[${k.toFixed(3)}s] ${S} \u2717${R?` ${R}`:""}`}return m.type==="complete"?`[${k.toFixed(3)}s] ${S} \u25A0 complete`:`[${k.toFixed(3)}s] ${S} ${m.type}`}if(r==="json")try{return JSON.stringify(m)}catch{return JSON.stringify({type:m.type,path:m.path,data:"[unserializable]"})}let h=u[m.type]??"",g=m.path?`${u.path}${m.path}${u.reset} `:"",y=m.type==="data"||m.type==="error",b=m.type==="pause"||m.type==="resume",v=y?` ${ls(m.data)}`:b?` ${ls(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}`:"",x=m.in_batch?" [batch]":"";return`${g}${h}${m.type.toUpperCase()}${u.reset}${v}${w}${x}`};e.onEvent(m=>{a(m.type)&&o(f(m),m)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){lc(this._disposers,this.name),this.signal([[le]],{internal:!0}),lc(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:d,...c}=r.nodes[a];o[a]=c}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 vr(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??$e,{codec:o,codecVersion:s,payload:i}=Tr(e,r);return o.decode(i,s)}restore(e,n){if(pc(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=>cs(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){pc(e);let r=typeof n=="function"?n:n?.build,o=typeof n=="function"?void 0:n?.factories,s=new t(e.name);if(r)return r(s),s.restore(e),s;for(let f of[...e.subgraphs].sort((m,h)=>{let g=m.split(De).length,y=h.split(De).length;return g!==y?g-y:m<h?-1:m>h?1:0})){let m=f.split(De),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(([f,m])=>({re:cs(f),factory:m})):[],a=f=>{for(let m of i)if(m.re.test(f))return m.factory},u=f=>{let m=f.split(De),h=m.pop();if(h==null||h.length===0)throw new Error(`invalid snapshot path "${f}"`);let g=s;for(let y of m){let b=g._mounts.get(y);if(!b)throw new Error(`unknown mount "${y}" in path "${f}"`);g=b}return[g,h]},d=Object.entries(e.nodes).filter(([f])=>!f.includes(`${De}${Qe}${De}`)).sort((f,m)=>f[0]<m[0]?-1:f[0]>m[0]?1:0),c=new Map(d),l=new Map,p=!0;for(;c.size>0&&p;){p=!1;for(let[f,m]of[...c.entries()]){let h=m?.deps??[];if(!h.every(w=>l.has(w)))continue;let[g,y]=u(f),b={...m?.meta??{}},v=a(f),T;if(m?.type==="state")T=M(m.value,{meta:b});else{if(v==null)continue;T=v(y,{path:f,type:m.type,value:m.value,meta:b,deps:h,resolvedDeps:h.map(w=>l.get(w))})}g.add(T,{name:y}),l.set(f,T),c.delete(f),p=!0}}if(c.size>0){let f=[...c.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${f}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return s.restore(e),s}toJSON(){return this.snapshot()}attachSnapshotStorage(e,n={}){let r=e.map(d=>({tier:d,debounceMs:Math.max(0,d.debounceMs??0),compactEvery:Math.max(1,d.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=(d,c)=>{if(d.disposed)return;let l=Um(c.nodes);if(d.lastSnapshot!=null&&l!==""&&l===d.lastFingerprint)return;let p=d.seq+1,f=oe(),g=d.lastSnapshot==null||p%d.compactEvery===0?{name:this.name,mode:"full",snapshot:c,seq:p,timestamp_ns:f,format_version:ft}:{name:this.name,mode:"diff",diff:fs(d.lastSnapshot,c),seq:p,timestamp_ns:f,format_version:ft};if(d.tier.filter&&!d.tier.filter(g))return;let y;try{y=d.tier.save(g)}catch(b){n.onError?.(b,d.tier);return}if(y&&typeof y.then=="function"){let T=(d.savePending??Promise.resolve()).then(()=>y,()=>y).then(()=>{d.disposed||(d.seq=p,d.lastSnapshot=c,d.lastFingerprint=l)},w=>{n.onError?.(w,d.tier)});d.savePending=T.finally(()=>{d.savePending===T&&(d.savePending=void 0)})}else d.seq=p,d.lastSnapshot=c,d.lastFingerprint=l},s=(d,c)=>{try{o(d,c)}catch(l){n.onError?.(l,d.tier)}},i=(d,c)=>{if(!c.some(m=>{let h=this.config.messageTier(m[0]);return h>=3&&h<5}))return;if(n.filter){let m=this.tryResolve(d);if(m==null)return;let h=Dr(m,Ct("standard"));if(!n.filter(d,h))return}let p,f=()=>(p==null&&(p=this.snapshot()),p);for(let m of r)m.disposed||(m.debounceMs===0?s(m,f()):(m.timer==null&&(m.timer=new Le),m.timer.start(m.debounceMs,()=>{m.disposed||s(m,this.snapshot())})))},a;if(n.paths!=null){let c=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(l=>{let p=this.tryResolve(l);return p==null?()=>{}:p.subscribe(f=>i(l,f))});a=()=>{for(let l of c)l()}}else a=this.observe().subscribe((d,c)=>i(d,c));let u=()=>{a();for(let d of r)d.disposed=!0,d.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?.()}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===ft&&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?.()}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===ft&&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:H(),...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,x=T.v;w!=null&&x!=null&&w.id===x.id&&w.version!==x.version&&u.push({path:b,id:w.id,from:w.version,to:x.version});let k=w!=null&&x!=null&&w.id===x.id&&w.version===x.version;for(let S of["type","status","sentinel"]){let R=v[S],N=T[S];R!==N&&a.push({path:b,field:S,from:R,to:N})}if(!k)for(let S of["value","meta"]){let R=v[S],N=T[S];Jm(R,N)||a.push({path:b,field:S,from:R,to:N})}}let d=b=>`${b.from} ${b.to}`,c=new Set(e.edges.map(d)),l=new Set(n.edges.map(d)),p=n.edges.filter(b=>!c.has(d(b))),f=e.edges.filter(b=>!l.has(d(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:p,edgesRemoved:f,subgraphsAdded:g,subgraphsRemoved:y}}};function fs(t,e){let n=Y.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 fn(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,d=new Map,c=new Set;for(let[v,T]of Object.entries(t.nodes)){if(!v)continue;c.add(v);let w=T.deps??[];i.set(v,w);for(let x of w)x&&(c.add(x),a.has(x)||a.set(x,new Set),a.get(x).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||(c.add(T),c.add(w),d.has(T)||d.set(T,new Set),d.get(T).add(w),u.has(w)||u.set(w,new Set),u.get(w).add(T))}if(!c.has(e))return r.withDetail?o:[];let l=r.both===!0,p=v=>{if(l){let k=i.get(v)??[],S=u.get(v),R=a.get(v),N=d.get(v),_=[...k];return S&&_.push(...S),R&&_.push(...R),N&&_.push(...N),_}if(n==="upstream"){let k=i.get(v)??[],S=u.get(v);return S?[...k,...S]:k}let T=a.get(v),w=d.get(v),x=T?[...T]:[];return w&&x.push(...w),x},f=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){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),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 cg(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 Ts={};ke(Ts,{CqrsGraph:()=>vs,cqrs:()=>Ra,cqrsEventKeyOf:()=>hg,dispatchKeyOf:()=>yg,sagaInvocationKeyOf:()=>bg});Me();xe();$t();var va={};ke(va,{COMPLETE:()=>L,COMPLETE_MSG:()=>Oo,COMPLETE_ONLY_BATCH:()=>br,DATA:()=>E,DEFAULT_ACTOR:()=>bt,DIRTY:()=>ne,DIRTY_MSG:()=>Et,DIRTY_ONLY_BATCH:()=>Mn,ERROR:()=>C,GraphReFlyConfig:()=>nn,GuardDenied:()=>rt,INVALIDATE:()=>Je,INVALIDATE_MSG:()=>Mo,INVALIDATE_ONLY_BATCH:()=>yr,NodeImpl:()=>Ae,PAUSE:()=>Be,RESOLVED:()=>V,RESOLVED_MSG:()=>Nn,RESOLVED_ONLY_BATCH:()=>hr,RESUME:()=>qe,START:()=>dt,START_MSG:()=>_n,TEARDOWN:()=>le,TEARDOWN_MSG:()=>Co,TEARDOWN_ONLY_BATCH:()=>On,accessHintForGuard:()=>_r,advanceVersion:()=>Mr,autoTrackNode:()=>rn,batch:()=>X,configure:()=>ra,createVersioning:()=>In,defaultConfig:()=>$e,defaultHash:()=>jt,derived:()=>A,downWithBatch:()=>_t,dynamicNode:()=>Or,effect:()=>pe,isBatching:()=>tn,isV1:()=>ea,monotonicNs:()=>H,node:()=>z,normalizeActor:()=>Nt,pipe:()=>oa,policy:()=>Mt,policyFromRules:()=>Nr,producer:()=>K,registerBuiltins:()=>Er,resolveDescribeFields:()=>Ct,state:()=>M,wallClockNs:()=>oe});kr();Me();xe();Xi();$t();ae();_e();ee();Io();Me();ae();_e();ee();he();var jr=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}snapshot(){return this.toArray()}restore(e){if(this._maxSize===void 0){this._buf.length=0;for(let n=0;n<e.length;n++)this._buf.push(e[n]);this._size=this._buf.length}else{let n=this._maxSize;for(let s=0;s<n;s++)this._buf[s]=void 0;this._head=0;let r=Math.min(e.length,n),o=e.length-r;for(let s=0;s<r;s++)this._buf[s]=e[o+s];this._size=r}this._version+=1}_rawAppend(e){if(this._maxSize===void 0){this._buf.push(e),this._size=this._buf.length;return}this._size<this._maxSize?(this._buf[(this._head+this._size)%this._maxSize]=e,this._size+=1):(this._buf[this._head]=e,this._head=(this._head+1)%this._maxSize)}};function $r(t){return t.subscribe(()=>{})}var lg=64;function Ve(t,e={}){let{name:n,maxSize:r,versioning:o,guard:s,backend:i}=e,a=i??new jr(t,r),u=M(a.toArray(),{name:n,describeKind:"state",equals:(k,S)=>k===S,...o!=null?{versioning:o}:{},...s!=null?{guard:s}:{}});function d(){let k=a.toArray();X(()=>{u.down([[ne]],{internal:!0}),u.down([[E,k]],{internal:!0})})}let c=new Map,l=new Map,p=new Map;function f(k,S){return`${k}:${S===void 0?"END":S}`}function m(k){if(k.size<lg)return;let S=k.keys().next();if(S.done)return;let R=k.get(S.value);R!==void 0&&R.dispose(),k.delete(S.value)}function h(k){let S=a.version;try{return k()}finally{a.version!==S&&d()}}function g(k){if(!Number.isInteger(k)||k<0)throw new RangeError(`tail: n must be a non-negative integer (got ${k})`);let S=c.get(k);if(S!==void 0)return c.delete(k),c.set(k,S),S.node;m(c);let R=A([u],([_])=>{let I=_;return k===0||I.length===0?[]:I.slice(Math.max(0,I.length-k))},{initial:a.tail(k),describeKind:"derived"}),N=$r(R);return c.set(k,{node:R,dispose:N}),R}function y(k,S){if(!Number.isInteger(k)||k<0)throw new RangeError(`slice: start must be a non-negative integer (got ${k})`);if(S!==void 0&&(!Number.isInteger(S)||S<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${S})`);let R=f(k,S),N=l.get(R);if(N!==void 0)return l.delete(R),l.set(R,N),N.node;m(l);let _=A([u],([O])=>{let P=O;return S===void 0?P.slice(k):P.slice(k,S)},{initial:a.slice(k,S),describeKind:"derived"}),I=$r(_);return l.set(R,{node:_,dispose:I}),_}function b(k){let S=p.get(k);if(S!==void 0)return S.node;let R=A([u,k],([_,I])=>{let O=_,P=Math.max(0,Math.trunc(I??0));return O.slice(P)},{initial:[],describeKind:"derived"}),N=$r(R);return p.set(k,{node:R,dispose:N}),R}let v,T;function w(){v===void 0&&(v=z([u],(k,S,R)=>{let N=k[0],I=N!=null&&N.length>0?N.at(-1):R.prevData[0];if(I==null||I.length===0){S.down([[V]]);return}S.emit(I[I.length-1])},{name:n!=null?`${n}::lastValue`:"lastValue",describeKind:"derived",initial:a.size===0?void 0:a.at(a.size-1)}),T=A([u],([k])=>k.length>0,{name:n!=null?`${n}::hasLatest`:"hasLatest",describeKind:"derived",initial:a.size>0}),$r(v),$r(T))}let x={entries:u,get size(){return a.size},at(k){return a.at(k)},append(k){h(()=>a.append(k))},appendMany(k){k.length!==0&&h(()=>a.appendMany(k))},clear(){h(()=>a.clear())},trimHead(k){h(()=>a.trimHead(k))},withLatest(){return w(),u},get lastValue(){return w(),v},get hasLatest(){return w(),T},view(k){switch(k.kind){case"tail":return g(k.n);case"slice":return y(k.start,k.stop);case"fromCursor":return b(k.cursor)}},attach(k){let S=k.subscribe(R=>{for(let N of R)N[0]===E&&x.append(N[1])});return()=>S()},attachStorage(k){if(k.length===0)return()=>{};let S=new Map;for(let N of k)S.set(N,a.size);(async()=>{for(let N of k)if(typeof N.loadEntries=="function")try{let _=await Promise.resolve(N.loadEntries());_.entries.length>0&&a.size===0&&(a.restore(_.entries),S.set(N,_.entries.length),d());break}catch{}})();let R=u.subscribe(N=>{for(let _ of N){if(_[0]!==E)continue;let I=_[1];for(let O of k){let P=S.get(O)??0;if(I.length<P){try{let j=O.appendEntries(I);j instanceof Promise&&j.catch(()=>{})}catch{}S.set(O,I.length);continue}if(I.length===P)continue;let B=I.slice(P);S.set(O,I.length);try{let j=O.appendEntries(B);j instanceof Promise&&j.catch(()=>{})}catch{}}}});return()=>R()},disposeAllViews(){for(let k of c.values())k.dispose();c.clear();for(let k of l.values())k.dispose();l.clear();for(let k of p.values())k.dispose();p.clear()},dispose(){for(let k of c.values())k.dispose();c.clear();for(let k of l.values())k.dispose();l.clear();for(let k of p.values())k.dispose();p.clear()}};return x}var Ta=new WeakMap;function bc(t){let e=Ta.get(t);if(e)return e;let n=t.map(c=>c.cache??[]),r=n.flat(),o=M(r,{name:"mergeReactiveLogs",describeKind:"state",equals:(c,l)=>c===l}),s=t.map((c,l)=>[...n[l]??[]]),i=[];for(let c=0;c<t.length;c++){let l=c,p=t[l].subscribe(f=>{for(let m of f)m[0]===E?(s[l]=[...m[1]],o.emit(s.flat())):m[0]===L?s[l]=[]:m[0]===C&&o.down([[C,m[1]]])});i.push(p)}let a=re(o),u=!1,d={node:o,dispose(){if(!u){u=!0;for(let c of i)c();i.length=0,a(),Ta.delete(t)}}};return Ta.set(t,d),d}var ka={};ke(ka,{ENVELOPE_VERSION:()=>Cn,GRAPH_META_SEGMENT:()=>Qe,Graph:()=>Y,JsonCodec:()=>Ao,SIZEOF_OVERHEAD:()=>je,SIZEOF_SYMBOL:()=>ds,SNAPSHOT_VERSION:()=>ft,createDagCborCodec:()=>Ji,createDagCborZstdCodec:()=>Yi,decodeEnvelope:()=>Tr,diffForWAL:()=>fs,encodeEnvelope:()=>vr,explainPath:()=>Gr,graphProfile:()=>pn,mermaidLiveUrl:()=>ps,reachable:()=>fn,registerBuiltinCodecs:()=>wr,replayWAL:()=>Qi,sizeof:()=>Fr,validateGraphObservability:()=>wa,watchTopologyTree:()=>At});Lo();ae();function At(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 d of u){if(d[0]!==E)continue;let c=d[1];if(e(c,o,s),c.kind==="added"&&c.nodeKind==="mount"){let l=o._mounts.get(c.name);if(l instanceof Y){let p=`${s}${c.name}::`;r(l,p)}}else if(c.kind==="removed"&&c.nodeKind==="mount"){let l=`${s}${c.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,d]of o._mounts)if(d instanceof Y){let c=`${s}${u}::`;r(d,c)}};return r(t,""),()=>{for(let o of n.values())o.off();n.clear()}}function wa(t,e={}){let n=[],r=e.requireFound??!0;if(e.skipDescribe!==!0)try{let d=t.describe(),c=new Set(Object.keys(d.nodes)),l=[];for(let[p,f]of Object.entries(d.nodes))for(let m of f.deps)m!==""&&!c.has(m)&&l.push(`${p} \u2192 ${m}`);for(let p of d.edges)c.has(p.from)||l.push(`edge.from: ${p.from}`),c.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:c.size,edgeCount:d.edges.length})}catch(d){n.push({kind:"describe",ok:!1,reason:`describe() threw: ${d instanceof Error?d.message:String(d)}`})}for(let d of e.formats??[])try{let c=t.describe({format:d});typeof c!="string"||c.length===0?n.push({kind:"describe-format",ok:!1,format:d,reason:`describe({ format: "${d}" }) returned empty or non-string output`}):n.push({kind:"describe-format",ok:!0,format:d,length:c.length})}catch(c){n.push({kind:"describe-format",ok:!1,format:d,reason:c instanceof Error?c.message:String(c)})}for(let d of e.paths??[])try{t.resolve(d),n.push({kind:"observe",ok:!0,path:d})}catch(c){n.push({kind:"observe",ok:!1,path:d,reason:c instanceof Error?c.message:String(c)})}for(let[d,c]of e.pairs??[])try{let l=t.explain(d,c);r&&l.found===!1?n.push({kind:"explain",ok:!1,from:d,to:c,reason:`explain(${d} \u2192 ${c}) found no path${l.reason?`: ${l.reason}`:""}`}):n.push({kind:"explain",ok:!0,from:d,to:c,found:l.found,steps:l.steps.length})}catch(l){n.push({kind:"explain",ok:!1,from:d,to:c,reason:l instanceof Error?l.message:String(l)})}let o=n.filter(d=>!d.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 d=[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),c=d.length>0?d.join(", "):"describe-only";return s?`validateGraphObservability: OK (${c})`:`validateGraphObservability: ${o.length} failure(s) across ${c}`}}}var Wt=class extends Error{constructor(e,n){super(e,n),this.name=this.constructor.name}},ms=class extends Wt{constructor(n,r){super(`Duplicate ${n} registration: "${r}"`);this.kind=n;this.registrationName=r}},gs=class extends Wt{constructor(n,r,o){super(`Command "${n}" emitted undeclared event "${r}". Declared emits: [${o.join(", ")}]`);this.commandName=n;this.eventName=r;this.declaredEmits=o}},hs=class extends Wt{constructor(n,r,o){super(`Optimistic concurrency conflict on aggregate "${n}": expected version ${r}, got ${o}`);this.aggregateId=n;this.expected=r;this.actual=o}},ys=class extends Wt{constructor(n){super(`Unknown command: "${n}". Register with command() first.`);this.commandName=n}},Br=class extends Wt{constructor(n,r){super(`Command handler "${n}" threw: ${r instanceof Error?r.message:String(r)}`,{cause:r});this.commandName=n}};var Vr=class extends Wt{constructor(n,r){super(`Projection "${n}" rebuild failed: ${r instanceof Error?r.message:String(r)}`,{cause:r});this.projectionName=n}};Me();xe();$t();ae();ee();var pg=Mt((t,e)=>{t("observe"),t("signal"),e("write")});function kt(t){let e=Ve([],{name:t.name,maxSize:t.retainedLimit??1024,guard:t.guard??pg,...t.versioning!=null?{versioning:t.versioning}:{}});return e.withLatest(),t.graph&&t.graph.add(e.entries,{name:t.name}),e}function vc(t){if(t===null||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.keys(t))vc(t[e]);return Object.freeze(t)}function fg(t){let n=(t.cache??0)+1;return t.down([[ne],[E,n]]),n}function Yn(t,e){let n=e.freeze??!0;return function(...o){let s=n?o.map(vc):o,i=oe(),a,u,d=!1,c;try{X(()=>{e.seq&&(c=fg(e.seq));try{if(a=t(...s),e.onSuccess){let l=e.onSuccess(s,a,{t_ns:i,seq:c});if(l!==void 0){let p=e.handlerVersion!=null?{...l,handlerVersion:e.handlerVersion}:l;e.audit.append(p)}}}catch(l){throw u=l,d=!0,l}})}catch(l){if(d&&e.onFailure){let p=u instanceof Error?u.name:typeof u,f=e.onFailure(s,u,{t_ns:i,seq:c,errorType:p});if(f!==void 0){let m=e.handlerVersion!=null?{...f,handlerVersion:e.handlerVersion}:f;e.audit.append(m)}}throw d?u:l}return a}}function bs(t,e,n=0){let r=M(n,{name:e,describeKind:"state"});return t.add(r,{name:e}),r}function Tc(t,e,n,r=0){let o={},s=new Y(e);for(let i of n){let a=M(r,{name:i,describeKind:"state"});s.add(a,{name:i}),o[i]=a}return t.mount(e,s),o}Me();ae();_e();he();function mt(t,e){t!=null&&_t(n=>t.down(n),[[E,e]],$e.tierOf)}function Kr(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[ne],[E,n+1]]),!0)}function ze(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}function qr(t){return t.relatedTo?.[0]??t.summary}var mg=Mt((t,e)=>{t("write"),t("signal"),e("observe")}),gg=Mt((t,e)=>{t("observe"),t("signal"),e("write")}),wc=Mt((t,e)=>{t("observe"),t("signal"),e("write")});function Hr(t,e){return ze("cqrs",t,e)}function xa(t){if(t===null||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.keys(t))xa(t[e]);return Object.freeze(t)}var hg=t=>`${t.type}::${t.aggregateId??"__default__"}`,yg=t=>t.commandName,bg=t=>t.eventType,vs=class extends Y{_eventLogs=new Map;_eventLogsByAggregate=new Map;_aggregateVersions=new Map;_aggregateLru=new Map;_commandRegs=new Map;_projections=new Set;_sagas=new Set;_keepaliveDisposers=[];_seq=0;_retainedLimit;_freezeCommandPayload;_freezeEventPayload;_maxAggregates;_dispatchSeqCursor;dispatches;audit;aggregateEvictions;constructor(e,n={}){super(e,n.graph),this._retainedLimit=n.retainedLimit??1024,this._freezeCommandPayload=n.freezeCommandPayload??!0,this._freezeEventPayload=n.freezeEventPayload??!0,this._maxAggregates=n.maxAggregates??1e4,this.dispatches=kt({name:"dispatches",retainedLimit:this._retainedLimit,graph:this}),this.audit=this.dispatches,this.aggregateEvictions=kt({name:"aggregateEvictions",retainedLimit:this._retainedLimit,graph:this}),this._dispatchSeqCursor=bs(this,"dispatch_seq",0)}aggregateVersion(e,n){return this._aggregateVersions.get(`${e}::${n}`)??0}_touchAggregate(e){this._aggregateLru.delete(e),this._aggregateLru.set(e,!0)}_enforceAggregateLru(){for(;this._aggregateLru.size>this._maxAggregates;){let e=this._aggregateLru.keys().next();if(e.done)break;let n=e.value;this._aggregateLru.delete(n);let r=n.indexOf("::");if(r<0)continue;let o=n.slice(0,r),s=n.slice(r+2),i=this._aggregateVersions.get(n)??0;this._aggregateVersions.delete(n);let a=this._eventLogsByAggregate.get(o);a&&(a.delete(s),a.size===0&&this._eventLogsByAggregate.delete(o)),this.aggregateEvictions.append({aggregateId:s,type:o,lastVersion:i,t_ns:oe()})}}destroy(){for(let e of this._keepaliveDisposers)e();this._keepaliveDisposers.length=0,super.destroy()}_attachedEventTiers=[];_attachedTierDisposers=new Map;attachEventStorage(e){this._attachedEventTiers.push(e);for(let[n,r]of this._eventLogs){let o=r.log.attachStorage(e),s=this._attachedTierDisposers.get(n);s||(s=[],this._attachedTierDisposers.set(n,s)),s.push(o)}for(let[n,r]of this._eventLogsByAggregate)for(let[o,s]of r){let i=`${n}::${o}`,a=s.log.attachStorage(e),u=this._attachedTierDisposers.get(i);u||(u=[],this._attachedTierDisposers.set(i,u)),u.push(a)}return()=>{let n=this._attachedEventTiers.indexOf(e);n>=0&&this._attachedEventTiers.splice(n,1)}}_autoWireStreamStorage(e,n){if(this._attachedEventTiers.length===0)return;let r=this._attachedTierDisposers.get(e);r||(r=[],this._attachedTierDisposers.set(e,r));for(let o of this._attachedEventTiers)r.push(n.attachStorage(o))}_bumpDispatchSeq(){let n=(this._dispatchSeqCursor.cache??0)+1;return this._dispatchSeqCursor.emit(n),n}event(e,n){if(n!==void 0)return this._ensureAggregateStream(e,n).node;let r=this._eventLogs.get(e);if(r)return r.node;let o=Ve([],{name:e,versioning:0,maxSize:this._retainedLimit});o.withLatest();let s=o.entries,i=A([s],([a])=>a,{name:e,describeKind:"state",meta:Hr("event",{event_name:e}),guard:wc,initial:s.cache});return this.add(i,{name:e}),this._keepaliveDisposers.push(re(i)),this._eventLogs.set(e,{log:o,node:i}),this._autoWireStreamStorage(e,o),i}_ensureAggregateStream(e,n){this._eventLogs.has(e)||this.event(e);let r=this._eventLogsByAggregate.get(e);r||(r=new Map,this._eventLogsByAggregate.set(e,r));let o=`${e}::${n}`;this._touchAggregate(o);let s=r.get(n);if(s)return s;let i=`${e}_${n.replace(/[^a-zA-Z0-9_-]/g,"_")}`,a=Ve([],{name:i,versioning:0,maxSize:this._retainedLimit});a.withLatest();let u=a.entries,d=A([u],([f])=>f,{name:i,describeKind:"state",meta:Hr("event_aggregate",{event_name:e,aggregate_id:n}),guard:wc,initial:u.cache}),c=i,l=0;for(;this.nameOf(this.resolveOptional(c)??d)===c&&(l+=1,c=`${i}_${l}`,this.resolveOptional(c)!==void 0););try{this.add(d,{name:c})}catch{}this._keepaliveDisposers.push(re(d));let p={log:a,node:d};return r.set(n,p),this._autoWireStreamStorage(`${e}::${n}`,a),this._enforceAggregateLru(),p}resolveOptional(e){try{return this.resolve(e)}catch{return}}_appendEvent(e,n,r){let o=this._eventLogs.get(e);if(o||(this.event(e),o=this._eventLogs.get(e)),o.node.status==="completed"||o.node.status==="errored")throw new Error(`Cannot dispatch to terminated event stream "${e}" (status: ${o.node.status}).`);let s,i;if(r?.aggregateId!==void 0){let c=`${e}::${r.aggregateId}`;s=(this._aggregateVersions.get(c)??0)+1,this._aggregateVersions.set(c,s),i=this._ensureAggregateStream(e,r.aggregateId)}let a=o.log.entries.v,u=this._freezeEventPayload?xa(n):n,d={type:e,payload:u,timestampNs:oe(),seq:++this._seq,...r?.aggregateId!==void 0?{aggregateId:r.aggregateId}:{},...s!==void 0?{aggregateVersion:s}:{},...r?.correlationId!==void 0?{correlationId:r.correlationId}:{},...r?.causationId!==void 0?{causationId:r.causationId}:{},...r?.metadata!==void 0?{metadata:Object.freeze({...r.metadata})}:{},...r?.handlerVersion!==void 0?{handlerVersion:r.handlerVersion}:{},...a!=null?{v0:{id:a.id,version:a.version}}:{}};return o.log.append(d),i&&i.log.append(d),d}command(e,n){if(this._commandRegs.has(e))throw new ms("command",e);let r=typeof n=="function"?{handler:n}:n,o=M(void 0,{name:e,describeKind:"state",meta:{...Hr("command",{command_name:e}),error:null},guard:mg});if(this.add(o,{name:e}),this._commandRegs.set(e,{handler:r.handler,...r.emits!==void 0?{emits:r.emits}:{},...r.handlerVersion!==void 0?{handlerVersion:r.handlerVersion}:{}}),r.emits)for(let s of r.emits)this._eventLogs.has(s)||this.event(s);return o}dispatch(e,n,r){let o=this._commandRegs.get(e);if(!o)throw new ys(e);if(r?.aggregateId!==void 0&&r.expectedAggregateVersion!==void 0&&o.emits!==void 0){let p=0;for(let f of o.emits){let m=this._aggregateVersions.get(`${f}::${r.aggregateId}`);m!==void 0&&m>p&&(p=m)}if(p!==r.expectedAggregateVersion)throw new hs(r.aggregateId,r.expectedAggregateVersion,p)}let s=this.resolve(e),i=this._freezeCommandPayload?xa(n):n,a=[],u=oe(),d=0,c,l=!1;try{X(()=>{d=this._bumpDispatchSeq(),s.emit(i,{internal:!0});try{o.handler(i,{emit:(p,f)=>{if(o.emits!==void 0&&!o.emits.includes(p))throw new gs(e,p,o.emits);a.push(p),this._appendEvent(p,f,{...r?.aggregateId!==void 0?{aggregateId:r.aggregateId}:{},...r?.correlationId!==void 0?{correlationId:r.correlationId}:{},...r?.causationId!==void 0?{causationId:r.causationId}:{},...r?.metadata!==void 0?{metadata:Object.freeze({...r.metadata})}:{},...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}})}}),s.meta.error.emit(null,{internal:!0}),this.dispatches.append({commandName:e,payload:i,status:"success",emittedEvents:[...a],t_ns:u,seq:d,...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}})}catch(p){throw c=p,l=!0,p}})}catch(p){if(l){s.meta.error.emit(c,{internal:!0});let f=c instanceof Error?c.name:typeof c,m=c instanceof Br?c:new Br(e,c);this.dispatches.append({commandName:e,payload:i,status:"failed",error:m,errorType:f,emittedEvents:[...a],t_ns:u,seq:d,...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}})}throw l?c:p}}projection(e){let{name:n,events:r,reducer:o,initial:s}=e,i=e.mode??"scan",a=e.freezeInputs??!0,u=e.snapshot,d=r.map(N=>(this._eventLogs.has(N)||this.event(N),this._eventLogs.get(N).node));function c(N){N.sort((_,I)=>_.timestampNs-I.timestampNs||_.seq-I.seq||(_.aggregateId??"").localeCompare(I.aggregateId??""))}function l(N){let _=[];for(let I of N)_.push(...I);return c(_),_}let p=d.map(N=>N.cache??[]),f=l(p),m=a?Object.freeze(f):f,h=0,g=s;i==="scan"&&f.length>0&&(g=o(s,m),h=f.length);let y=i==="replay"?o(s,m):g,b=u?.saveDebounceMs??1e3,v=u?.saveEvery??1e3,T,w=0;function x(N){if(u?.save){if(w+=1,w>=v){w=0,T!==void 0&&(clearTimeout(T),T=void 0);let _=u.save(N);_ instanceof Promise&&_.catch(()=>{});return}T!==void 0&&clearTimeout(T),T=setTimeout(()=>{T=void 0,w=0;let _=u.save(N);_ instanceof Promise&&_.catch(()=>{})},b)}}let k=A(d,N=>{let _=l(N),I;if(i==="replay"){let O=a?Object.freeze(_):_;I=o(s,O)}else{let O=_.slice(h);h=_.length;let P=a?Object.freeze(O):O;I=o(g,P),g=I}return x(I),I},{name:n,describeKind:"derived",meta:Hr("projection",{projection_name:n,source_events:r}),guard:gg,initial:y});return this.add(k,{name:n}),this._keepaliveDisposers.push(re(k)),this._keepaliveDisposers.push(()=>{T!==void 0&&(clearTimeout(T),T=void 0)}),this._projections.add(n),{node:k,rebuild:async N=>{try{let _=N?.pageSize??1e3,I=N?.fromTier??this._attachedEventTiers[0]?.[0],O=l(d.map(B=>B.cache??[])).length,P=s;if(u?.load){let B=await u.load();B!==void 0&&(P=B)}if(!I||!I.loadEntries){let B=l(d.map(D=>D.cache??[])),j=a?Object.freeze(B):B;P=o(P,j)}else{let B=new Set(r),j,D=!1;for(;!D;){let Z=await I.loadEntries({cursor:j,pageSize:_}),F=[...Z.entries].filter(G=>B.has(G.type));c(F);let Q=a?Object.freeze(F):F;P=o(P,Q),j=Z.cursor,D=!j||Z.entries.length===0}}if(i==="scan"){let B=l(d.map(D=>D.cache??[])),j=B.slice(O);if(j.length>0){let D=a?Object.freeze(j):j;P=o(P,D)}g=P,h=B.length}return k.emit(P,{internal:!0}),P}catch(_){throw new Vr(n,_)}},reset:async()=>{try{let N=s;if(u?.load){let P=await u.load();P!==void 0&&(N=P)}let _=l(d.map(P=>P.cache??[])),I=a?Object.freeze(_):_,O=o(N,I);return i==="scan"&&(g=O,h=_.length),k.emit(O,{internal:!0}),O}catch(N){throw new Vr(n,N)}}}}saga(e,n,r,o={}){let s=n.map(f=>(this._eventLogs.has(f)||this.event(f),this._eventLogs.get(f).node)),i=Tc(this,`${e}_cursor`,n,0),a=kt({name:`${e}_invocations`,retainedLimit:this._retainedLimit,graph:this}),u=o.aggregateId,d=o.errorPolicy??"advance",c=new Map;for(let f of n){let m=i[f];c.set(f,m.cache??0);let h=m.subscribe(g=>{for(let y of g)y[0]===E&&c.set(f,y[1])});this._keepaliveDisposers.push(h)}let l={},p=z(s,(f,m)=>{let h=l.n.meta.error;for(let g=0;g<f.length;g++){let y=f[g];if(y==null||y.length===0)continue;let b=y.at(-1);if(!b)continue;let v=n[g],T=i[v],w=c.get(v)??0;if(b.length>w){let x=b.slice(w),k=w;for(let S of x){let R=S;if(u!==void 0&&R.aggregateId!==u){k+=1;continue}try{r(R),h.emit(null,{internal:!0}),a.append({eventType:v,status:"success",aggregateId:R.aggregateId,event:R,t_ns:oe(),...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}}),k+=1}catch(N){if(h.emit(N,{internal:!0}),a.append({eventType:v,status:"failed",error:N,errorType:N instanceof Error?N.name:typeof N,aggregateId:R.aggregateId,event:R,t_ns:oe(),...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}}),d==="hold")break;k+=1}}T.emit(k)}}},{name:e,describeKind:"effect",meta:{...Hr("saga",{saga_name:e,source_events:n}),error:null}});return l.n=p,this.add(p,{name:e}),this._keepaliveDisposers.push(re(p)),this._sagas.add(e),{node:p,invocations:a,audit:a,cursors:i}}};function Ra(t,e){return new vs(t,e)}var Ea=class{constructor(e){this.graph=e}onModuleDestroy(){this.graph.destroy()}},Na=class{graph=new Y("request");onModuleDestroy(){this.graph.destroy()}},kc,Sa;kc=[(0,Wr.Module)({})];var zt=class zt{static forRoot(e){let n=e??{},r=n.name??"root",o=[{provide:ct,useFactory:()=>{let s=new Y(r);return n.build&&n.build(s),n.snapshot&&s.restore(n.snapshot),s}},{provide:Symbol.for("graphrefly:root-lifecycle"),useFactory:s=>new Ea(s),inject:[ct]},{provide:cn,useFactory:(s,i)=>new cn(s,i),inject:[ct,xc.ModuleRef]}];if(n.nodes)for(let s of n.nodes)o.push({provide:lt(s),useFactory:i=>i.resolve(s),inject:[ct]});return n.requestScope&&o.push({provide:Symbol.for("graphrefly:request-lifecycle"),useFactory:()=>new Na,scope:Wr.Scope.REQUEST},{provide:on,useFactory:s=>s.graph,inject:[Symbol.for("graphrefly:request-lifecycle")],scope:Wr.Scope.REQUEST}),{module:zt,global:!0,providers:o,exports:[ct,...(n.nodes??[]).map(lt),...n.requestScope?[on]:[]]}}static forFeature(e){let n=[{provide:ot(e.name),useFactory:r=>{let o=new Y(e.name);return e.build&&e.build(o),e.snapshot&&o.restore(e.snapshot),r.mount(e.name,o),o},inject:[ct]}];if(e.nodes)for(let r of e.nodes)n.push({provide:lt(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[ot(e.name)]});return{module:zt,providers:n,exports:[ot(e.name),...(e.nodes??[]).map(r=>lt(`${e.name}::${r}`))]}}static forCqrs(e){let n=[{provide:ot(e.name),useFactory:r=>{let o=Ra(e.name,e.cqrs);return e.eventStorage&&o.attachEventStorage(e.eventStorage),e.build&&e.build(o),r.mount(e.name,o),o},inject:[ct]}];if(e.nodes)for(let r of e.nodes)n.push({provide:lt(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[ot(e.name)]});return{module:zt,providers:n,exports:[ot(e.name),...(e.nodes??[]).map(r=>lt(`${e.name}::${r}`))]}}};Sa=rd(null),zt=id(Sa,0,"GraphReflyModule",kc,zt),sd(Sa,1,zt);var ws=zt;var xs={};ke(xs,{useStore:()=>vg,useSubscribe:()=>Rc,useSubscribeRecord:()=>Tg});var Lt=require("react");ae();function Rc(t){return(0,Lt.useSyncExternalStore)(e=>{let n=!1,r=t.subscribe(()=>{n||e()});return()=>{n=!0,r()}},()=>t.cache,()=>t.cache)}function vg(t){let e=Rc(t),n=(0,Lt.useCallback)(r=>{t.down([[ne],[E,r]])},[t]);return[e,n]}function Tg(t,e){let n=(0,Lt.useRef)(e);n.current=e;let r=(0,Lt.useMemo)(()=>{let o=()=>{let i={},a=t.cache??[];for(let u of a){let d=n.current(u),c={};for(let l of Object.keys(d))c[l]=d[l].cache;i[u]=c}return i},s=o();return{subscribe:i=>{let a=!1,u=[],d=()=>{for(let p of u)p();u=[]},c=p=>{d();for(let f of p){let m=n.current(f);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(p=>{let f=p.some(m=>m[0]===E||m[0]===V);!a&&f&&c(t.cache??[])});return c(t.cache??[]),()=>{a=!0,l(),d()}},getSnapshot:()=>s}},[t]);return(0,Lt.useSyncExternalStore)(r.subscribe,r.getSnapshot,r.getSnapshot)}var Ss={};ke(Ss,{Signal:()=>wg});Me();ae();ee();var Qn=[];function Rs(t){let e=t.cache;return t.subscribe(r=>{for(let[o,s]of r)o===E&&(e=s)})(),e}var _a=class{_node;_equals;constructor(e,n){this._equals=n?.equals??Object.is,this._node=M(e,{...n,resubscribable:!0,resetOnTeardown:!0})}get(){let e=Qn[Qn.length-1];return e?(this._node.status==="sentinel"&&Rs(this._node),e(this._node)):this._node.status==="sentinel"?Rs(this._node):this._node.cache}set(e){this._equals(this.get(),e)||X(()=>{this._node.down([[ne],[E,e]])})}},Ma=class{_node;constructor(e,n){this._node=rn(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"&&Rs(this._node),e(this._node)):this._node.status==="sentinel"?Rs(this._node):this._node.cache}},wg={State:_a,Computed:Ma,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===E){if(r){r=!1;continue}n.data?.(i)}s===C&&n.error?.(i),s===L&&n.complete?.()}})}};var Es={};ke(Es,{useStore:()=>kg,useSubscribe:()=>Sc,useSubscribeRecord:()=>xg});var It=require("solid-js");ae();function Sc(t){let[e,n]=(0,It.createSignal)(t.cache,{equals:!1}),r=t.subscribe(()=>{n(()=>t.cache)});return(0,It.getOwner)()?(0,It.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 kg(t){return[Sc(t),r=>{t.down([[ne],[E,r]])}]}function xg(t,e){let[n,r]=(0,It.createSignal)({},{equals:!1}),o=[],s=()=>{for(let d of o)d();o=[]},i=()=>{let d={};for(let c of t.cache??[]){let l=e(c),p={};for(let f of Object.keys(l))p[f]=l[f].cache;d[c]=p}return d},a=d=>{s();for(let c of d){let l=e(c);for(let p of Object.keys(l)){let f=l[p].subscribe(()=>{r(()=>i())});o.push(f)}}r(()=>i())},u=t.subscribe(d=>{d.some(c=>c[0]===E||c[0]===V)&&a(t.cache??[])});return a(t.cache??[]),(0,It.getOwner)()?(0,It.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 Ns={};ke(Ns,{useStore:()=>Sg,useSubscribe:()=>Rg,useSubscribeRecord:()=>Eg});ae();function Rg(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n}}}function Sg(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n},set(e){t.down([[ne],[E,e]])},update(e){let n=e(t.cache);t.down([[ne],[E,n]])}}}function Eg(t,e){return{subscribe(n){let r=[],o=()=>{for(let u of r)u();r=[]},s=()=>{let u={};for(let d of t.cache??[]){let c=e(d),l={};for(let p of Object.keys(c))l[p]=c[p].cache;u[d]=l}return u},i=u=>{o();for(let d of u){let c=e(d);for(let l of Object.keys(c)){let p=c[l].subscribe(()=>{n(s())});r.push(p)}}n(s())},a=t.subscribe(u=>{u.some(d=>d[0]===E||d[0]===V)&&i(t.cache??[])});return i(t.cache??[]),()=>{a(),o()}}}}var _s={};ke(_s,{useStore:()=>_g,useSubscribe:()=>Ng,useSubscribeRecord:()=>Mg});var Ke=require("vue");ae();function Ng(t){let e=(0,Ke.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,Ke.getCurrentScope)()?(0,Ke.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Ke.readonly)(e)}function _g(t){let e=(0,Ke.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,Ke.getCurrentScope)()?(0,Ke.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useStore called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Ke.computed)({get:()=>e.value,set:r=>{t.down([[ne],[E,r]])}})}function Mg(t,e){let n=(0,Ke.shallowRef)({}),r=new Map;function o(){let a={};for(let[u,d]of r)a[u]={...d.values};n.value=a}function s(a){for(let d of r.values())for(let c of d.subs)c();r.clear();for(let d of a){let c=e(d),l=Object.keys(c),p={},f=[];for(let m of l){let h=c[m];p[m]=h.cache;let g=h.subscribe(()=>{p[m]=h.cache,o()});f.push(g)}r.set(d,{subs:f,values:p})}let u={};for(let[d,c]of r)u[d]={...c.values};n.value=u}return(0,Ke.watch)(()=>[...(typeof t=="function"?t():(0,Ke.isRef)(t)?t.value:t)??[]],a=>s(a??[]),{immediate:!0}),(0,Ke.getCurrentScope)()?(0,Ke.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,Ke.readonly)(n)}var Ms={};ke(Ms,{create:()=>Cg});ae();ee();var Og=()=>!1;function Cg(t){let e=new Y("zustand"),n=M(void 0,{name:"state",equals:Og});e.add(n,{name:"state"});let r=()=>n.cache,o=(a,u)=>{let d=n.cache,c=typeof a=="function"?a(d):a;n.emit(u?c:{...d,...c})},s={getState:r,setState:o,getInitialState:()=>i,subscribe:a=>{let u=!0,d=n.cache;return n.subscribe(c=>{for(let[l,p]of c)if(l===E){if(u){u=!1;continue}a(p,d),d=p}})},destroy:e.destroy.bind(e)},i=t(o,r,s);return n.emit(i),Object.assign(e,s)}var Wa={};ke(Wa,{CircuitOpenError:()=>pt,ContentAddressedMissError:()=>eo,NS_PER_MS:()=>He,NS_PER_SEC:()=>at,NativeIndexBackend:()=>ro,NativeListBackend:()=>oo,NativeLogBackend:()=>jr,NativeMapBackend:()=>Xr,NativePubSubBackend:()=>no,RateLimiterOverflowError:()=>an,ResettableTimer:()=>Le,TimeoutError:()=>un,appendLogStorage:()=>Ka,audit:()=>zc,awaitSettled:()=>es,buffer:()=>Uc,bufferCount:()=>Jc,bufferTime:()=>Qc,cached:()=>Kd,canonicalJson:()=>to,cascadingCache:()=>sp,catchError:()=>al,checkpointToRedis:()=>Ql,checkpointToS3:()=>Yl,circuitBreaker:()=>wt,combine:()=>Aa,combineLatest:()=>ol,concat:()=>jc,concatMap:()=>Kc,constant:()=>qo,contentAddressedStorage:()=>Ps,createTransport:()=>Jt,createWatermarkController:()=>Un,csvRows:()=>Al,debounce:()=>Ia,debounceTime:()=>sl,decorrelatedJitter:()=>Uo,defer:()=>jd,delay:()=>Hc,deserializeError:()=>yn,dictKv:()=>bp,dictSnapshot:()=>vp,distill:()=>Ls,distinctUntilChanged:()=>Gc,elementAt:()=>Ic,empty:()=>Gd,escapeRegexChar:()=>ca,exhaustMap:()=>Vc,exponential:()=>Wo,externalBundle:()=>Os,externalProducer:()=>mn,fallback:()=>Hn,fibonacci:()=>zo,filter:()=>Xe,find:()=>Lc,first:()=>Cs,firstValueFrom:()=>Ye,firstWhere:()=>Yo,flatMap:()=>qc,forEach:()=>qt,fromAny:()=>U,fromAsyncIter:()=>Ir,fromCSV:()=>Cl,fromClickHouseWatch:()=>Dl,fromCron:()=>Qo,fromDrizzle:()=>np,fromEvent:()=>Dd,fromHTTP:()=>$a,fromHTTPPoll:()=>yl,fromHTTPStream:()=>hl,fromIter:()=>Xo,fromKafka:()=>Nl,fromKysely:()=>rp,fromMCP:()=>Tl,fromNATS:()=>$l,fromNDJSON:()=>Pl,fromOTel:()=>wl,fromPrisma:()=>tp,fromPrometheus:()=>El,fromPromise:()=>zn,fromPulsar:()=>Gl,fromRabbitMQ:()=>Bl,fromRaf:()=>Pd,fromRedisStream:()=>Ml,fromSSE:()=>gl,fromSqlite:()=>Xl,fromSqliteCursor:()=>Zl,fromStatsD:()=>Rl,fromSyslog:()=>kl,fromTimer:()=>st,fromWebSocket:()=>Fa,fromWebSocketReconnect:()=>vl,fromWebhook:()=>ul,globToRegExp:()=>Ld,interval:()=>el,jsonCodec:()=>tr,jsonCodecFor:()=>gp,keepalive:()=>re,kvStorage:()=>js,last:()=>Ac,linear:()=>Ho,lru:()=>Va,makeHttpError:()=>ht,map:()=>zr,matchesAnyPattern:()=>Id,matchesCron:()=>Ko,memoryAppendLog:()=>yp,memoryBackend:()=>io,memoryKv:()=>ao,memorySnapshot:()=>hp,merge:()=>xt,mergeMap:()=>La,mergeReactiveLogs:()=>bc,nameToSignal:()=>gn,ndjsonRows:()=>Ll,never:()=>Fd,nodeSignal:()=>ts,of:()=>la,onFirstData:()=>Jr,pairwise:()=>Fc,parseCron:()=>Vo,parsePrometheusText:()=>ja,parseSSEStream:()=>Dt,parseStatsD:()=>Sl,parseSyslog:()=>xl,pausable:()=>nl,pubsub:()=>cp,race:()=>Bc,rateLimiter:()=>qn,reactiveCounter:()=>pa,reactiveIndex:()=>fp,reactiveList:()=>Ds,reactiveLog:()=>Ve,reactiveMap:()=>Ze,reactiveSink:()=>We,reduce:()=>Mc,repeat:()=>tl,replay:()=>Zo,rescue:()=>Yr,resolveBackoffPreset:()=>Bt,retry:()=>Tt,sample:()=>Wc,scan:()=>_c,serializeError:()=>hn,share:()=>Vd,shareReplay:()=>qd,signalToName:()=>Ut,singleFromAny:()=>Gs,singleNodeFromAny:()=>mp,skip:()=>Ca,snapshotStorage:()=>$s,sortJsonValue:()=>so,stableJsonString:()=>Fs,stratify:()=>uo,switchMap:()=>Te,take:()=>Ur,takeUntil:()=>Cc,takeWhile:()=>Oc,tap:()=>Pc,tapFirst:()=>Dc,throttle:()=>Pa,throttleTime:()=>il,throwError:()=>$d,timeout:()=>Wn,toArray:()=>Bd,toCSV:()=>Kl,toClickHouse:()=>ql,toFile:()=>Ba,toHTTP:()=>dl,toKafka:()=>_l,toLoki:()=>Ul,toMongo:()=>zl,toNATS:()=>jl,toObservable:()=>Bo,toPostgres:()=>Wl,toPulsar:()=>Fl,toRabbitMQ:()=>Vl,toReadableStream:()=>ml,toRedisStream:()=>Ol,toS3:()=>Hl,toSSE:()=>pl,toSSEBytes:()=>fl,toSqlite:()=>ep,toTempo:()=>Jl,toWebSocket:()=>bl,tokenBucket:()=>Vt,valve:()=>rl,verifiable:()=>up,window:()=>Zc,windowCount:()=>Yc,windowTime:()=>Xc,withBreaker:()=>Kn,withLatestFrom:()=>Pt,withMaxAttempts:()=>ua,withStatus:()=>Kt,workerBridge:()=>qa,workerSelf:()=>Ha,zip:()=>$c});Me();xe();ae();_e();ee();Me();ae();ee();function Ec(t){return{describeKind:"producer",...t}}function mn(t,e){return K(n=>{let r=!0,o={emit(i){r&&n.emit(i)},error(i){r&&(r=!1,n.down([[C,i]]))},complete(){r&&(r=!1,n.down([[L]]))}},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{}}},Ec(e))}function Os(t,e,n){let r=!0,o,s=0,i=0,a={},u=[],d=()=>{let f=o;o=void 0;try{f?.()}catch{}};for(let f of e){let m=n?.name?`${n.name}::${f}`:f,h=n?.channelOpts?.[f],g=K(y=>(s++,()=>{i++,s>0&&i>=s&&i>=e.length&&d()}),Ec({...h,name:m}));a[f]=g,u.push(g)}let c={};for(let f of e)c[f]=m=>{r&&a[f].down([[E,m]])};c.error=f=>{r&&(r=!1,X(()=>{for(let m of u)m.down([[C,f]])}),d())},c.complete=()=>{r&&(r=!1,X(()=>{for(let f of u)f.down([[L]])}),d())};let l=t(c);return o=typeof l=="function"?l:void 0,Object.assign(a,{dispose:()=>{r&&(r=!1,X(()=>{for(let f of u)try{f.down([[L]])}catch{}}),d())}})}xe();ae();_e();ee();he();function ue(t){return{describeKind:"derived",...t}}function Nc(t){return{describeKind:"derived",partial:!0,...t}}function zr(t,e,n){return z([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[V]]);return}for(let i of s)o.emit(e(i))},ue(n))}function Xe(t,e,n){return z([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[V]]);return}let i=!1;for(let a of s)e(a)&&(o.emit(a),i=!0);i||o.down([[V]])},ue(n))}function _c(t,e,n,r){return z([t],(o,s,i)=>{"acc"in i.store||(i.store.acc=n);let a=o[0];if(a==null||a.length===0){s.down([[V]]);return}for(let u of a)i.store.acc=e(i.store.acc,u),s.emit(i.store.acc)},{...ue(r),initial:n,resetOnTeardown:!0})}function Mc(t,e,n,r){return z([t],(o,s,i)=>{if("acc"in i.store||(i.store.acc=n),i.terminalDeps[0]===!0){s.emit(i.store.acc),s.down([[L]]);return}let a=o[0];if(a==null||a.length===0){s.down([[V]]);return}for(let u of a)i.store.acc=e(i.store.acc,u)},{...ue(r),completeWhenDepsComplete:!1})}function Ur(t,e,n){return e<=0?z([t],(r,o,s)=>{s.store.completed||(s.store.completed=!0,o.down([[L]]))},{...ue(n),completeWhenDepsComplete:!1}):z([t],(r,o,s)=>{if("taken"in s.store||(s.store.taken=0),s.store.done){o.down([[V]]);return}if(s.terminalDeps[0]===!0){s.store.done=!0,o.down([[L]]);return}let i=r[0];if(i==null||i.length===0){o.down([[V]]);return}for(let a of i)if(s.store.taken++,o.emit(a),s.store.taken>=e){s.store.done=!0,o.down([[L]]);return}},{...ue(n),completeWhenDepsComplete:!1})}function Ca(t,e,n){return z([t],(r,o,s)=>{"skipped"in s.store||(s.store.skipped=0);let i=r[0];if(i==null||i.length===0){o.down([[V]]);return}let a=!1;for(let u of i)s.store.skipped++,s.store.skipped<=e||(o.emit(u),a=!0);a||o.down([[V]])},ue(n))}function Oc(t,e,n){return z([t],(r,o,s)=>{if(s.store.done){o.down([[V]]);return}let i=r[0];if(i==null||i.length===0){o.down([[V]]);return}for(let a of i){if(!e(a)){s.store.done=!0,o.down([[L]]);return}o.emit(a)}},{...ue(n),completeWhenDepsComplete:!1})}function Cc(t,e,n){let r=n?.predicate??(i=>i[0]===E),{predicate:o,...s}=n??{};return K(i=>{let a=!1,u=t.subscribe(c=>{if(!a)for(let l of c){if(a)return;l[0]===E?i.emit(l[1]):(l[0]===L||l[0]===C)&&(a=!0,i.down([l]))}}),d=e.subscribe(c=>{if(!a)for(let l of c){if(a)return;if(r(l)){a=!0,i.down([[L]]);return}}});return()=>{u(),d()}},ue(s))}function Cs(t,e){return Ur(t,1,e)}function Ac(t,e){let{defaultValue:n,...r}=e??{},o=e!=null&&Object.hasOwn(e,"defaultValue");return z([t],(s,i,a)=>{if(a.terminalDeps[0]===!0){a.store.has?i.emit(a.store.latest):o&&i.emit(n),i.down([[L]]);return}let u=s[0];if(u==null||u.length===0){i.down([[V]]);return}a.store.latest=u.at(-1),a.store.has=!0},{...ue(r),completeWhenDepsComplete:!1})}function Lc(t,e,n){return Ur(Xe(t,e,n),1,n)}function Ic(t,e,n){return Ur(Ca(t,e,n),1,n)}function Pc(t,e,n){if(typeof e=="function")return z([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[V]]);return}for(let a of i)e(a),s.emit(a)},ue(n));let r=e;return z([t],(o,s,i)=>{if(i.terminalDeps[0]!==void 0){i.terminalDeps[0]===!0?(r.complete?.(),s.down([[L]])):(r.error?.(i.terminalDeps[0]),s.down([[C,i.terminalDeps[0]]]));return}let a=o[0];if(a==null||a.length===0){s.down([[V]]);return}for(let u of a)r.data?.(u),s.emit(u)},{...ue(n),completeWhenDepsComplete:!1})}function Jr(t,e,n){let r=n?.where??(s=>s!=null),o=!1;return z([t],(s,i)=>{let a=s[0];if(a==null||a.length===0){i.down([[V]]);return}for(let u of a)!o&&r(u)&&(o=!0,e(u)),i.emit(u)},ue(n))}var Dc=Jr;function Gc(t,e=Object.is,n){return z([t],(r,o,s)=>{let i=r[0];if(i==null||i.length===0){o.down([[V]]);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([[V]])},ue(n))}function Fc(t,e){return z([t],(n,r,o)=>{let s=n[0];if(s==null||s.length===0){r.down([[V]]);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([[V]])},ue(e))}function Aa(...t){let e=[...t];return A(e,n=>n,{...ue(),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 Pt(t,e,n){return z([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([[V]]);return}for(let d of i)o.emit([d,u])}else o.down([[V]])},Nc(n))}function xt(...t){return t.length===0?K(e=>{e.down([[L]])},ue()):K(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]===E?e.emit(u[1]):u[0]===L?(r+=1,r>=n&&e.down([[L]])):u[0]===C&&e.down([u])});o.push(i)}return()=>{for(let s of o)s()}},ue())}function $c(...t){let e=t.length;return e===0?K(n=>{n.emit([]),n.down([[L]])},ue()):K(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,d=t[a].subscribe(c=>{for(let l of c)l[0]===E?(r[u].push(l[1]),s()):l[0]===L?(o-=1,(o===0||r[u].length===0)&&n.down([[L]])):l[0]===C&&n.down([l])});i.push(d)}return()=>{for(let a of i)a()}},ue())}function jc(t,e,n){return K(r=>{let o=0,s=[],i,a;return a=e.subscribe(u=>{for(let d of u)o===0?d[0]===E?s.push(d[1]):d[0]===C&&r.down([d]):d[0]===E?r.emit(d[1]):(d[0]===L||d[0]===C)&&r.down([d])}),i=t.subscribe(u=>{for(let d of u)if(o===0)if(d[0]===E)r.emit(d[1]);else if(d[0]===L){o=1;for(let c of s)r.emit(c);s.length=0}else d[0]===C&&r.down([d])}),()=>{i?.(),a?.()}},ue(n))}function Bc(...t){return t.length===0?K(e=>{e.down([[L]])},ue()):t.length===1?z([t[0]],(e,n)=>{let r=e[0];if(r==null||r.length===0){n.down([[V]]);return}for(let o of r)n.emit(o)},ue()):K(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]===E?(n===null&&(n=s),e.emit(u[1])):(u[0]===L||u[0]===C)&&(n===null||s===n)&&e.down([u])}});r.push(i)}return()=>{for(let o of r)o()}},ue())}function As(t,e,n){let r,o=!1,s=()=>{o||(o=!0,n())};return r=t.subscribe(i=>{let a=!1,u=!1;for(let d of i)d[0]!==dt&&(d[0]===E?e.emit(d[1]):d[0]===L?a=!0:d[0]===C?(u=!0,e.down([d])):(d[0]===ne||d[0]===V)&&e.down([d]));u?(r?.(),r=void 0,s()):a&&s()}),()=>{r?.(),r=void 0}}function Te(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return z([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([[L]]);return}let d=i[0];if(!(d==null||d.length===0))return s(),r=As(U(e(d[d.length-1])),a,()=>{s(),o&&a.down([[L]])}),{deactivate:()=>{s(),o=!1}}},{...ue(n),completeWhenDepsComplete:!1})}function Vc(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return z([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([[L]]);return}let d=i[0];if(!(d==null||d.length===0))return r===void 0?r=As(U(e(d[0])),a,()=>{s(),o&&a.down([[L]])}):a.down([[V]]),{deactivate:()=>{s(),o=!1}}},{...ue(n),completeWhenDepsComplete:!1})}function Kc(t,e,n){let{maxBuffer:r,...o}=n??{},s=[],i,a=!1,u;function d(){i?.(),i=void 0}function c(){if(!u||i!==void 0)return;if(s.length===0){a&&u.down([[L]]);return}let p=s.shift();i=As(U(e(p)),u,()=>{d(),c()})}function l(p){r&&r>0&&s.length>=r&&s.shift(),s.push(p),c()}return z([t],(p,f,m)=>{if(u=f,m.terminalDeps[0]!=null&&m.terminalDeps[0]!==!0){d(),s.length=0;return}if(m.terminalDeps[0]===!0){a=!0,c();return}let h=p[0];if(!(h==null||h.length===0)){for(let g of h)l(g);return{deactivate:()=>{d(),s.length=0,a=!1}}}},{...ue(o),completeWhenDepsComplete:!1})}function La(t,e,n){let{concurrent:r,...o}=n??{},s=r!=null&&r>0?r:Number.POSITIVE_INFINITY,i=0,a=!1,u=new Set,d=[],c;function l(){a&&i===0&&d.length===0&&c&&c.down([[L]])}function p(g){if(!c)return;i++;let y;y=As(U(e(g)),c,()=>{y&&u.delete(y),i--,f(),l()}),u.add(y)}function f(){for(;d.length>0&&i<s;)p(d.shift())}function m(g){i<s?p(g):d.push(g)}function h(){for(let g of u)g();u.clear(),i=0,d.length=0}return z([t],(g,y,b)=>{if(c=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}}}},{...ue(o),completeWhenDepsComplete:!1})}var qc=La;function Hc(t,e,n){return K(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]===E){let d=setTimeout(()=>{o.delete(d),r.emit(u[1])},e);o.add(d)}else if(u[0]===L){let d=setTimeout(()=>{o.delete(d),r.down([[L]])},e);o.add(d)}else u[0]===C&&(s(),r.down([u]))});return()=>{i(),s()}},ue(n))}function Ia(t,e,n){return K(r=>{let o,s;function i(){o!==void 0&&(clearTimeout(o),o=void 0)}let a=t.subscribe(u=>{for(let d of u)d[0]===E?(i(),s=d[1],o=setTimeout(()=>{o=void 0,r.emit(s)},e)):d[0]===L?(o!==void 0&&(i(),r.emit(s)),r.down([[L]])):d[0]===C&&(i(),r.down([d]))});return()=>{a(),i()}},ue(n))}function Pa(t,e,n){let{leading:r,trailing:o,...s}=n??{},i=r!==!1,a=o===!0,u=e*1e6;return K(d=>{let c,l=-1/0,p,f=!1;function m(){c!==void 0&&(clearTimeout(c),c=void 0)}let h=t.subscribe(g=>{for(let y of g)if(y[0]===E){let b=y[1],v=H();if(i&&v-l>=u)l=v,d.emit(b),m(),a&&(c=setTimeout(()=>{c=void 0,f&&(l=H(),d.emit(p),f=!1)},e));else if(a&&(p=b,f=!0,c===void 0)){let T=(v-l)/1e6;c=setTimeout(()=>{c=void 0,f&&(l=H(),d.emit(p),f=!1)},Math.max(0,e-T))}}else(y[0]===L||y[0]===C)&&(m(),d.down([y]))});return()=>{h(),m()}},ue(s))}function Wc(t,e,n){return K(r=>{let o,s=!1,i=!1,a=t.subscribe(d=>{if(!s)for(let c of d){if(s)return;c[0]===E?o={v:c[1]}:c[0]===C?(s=!0,r.down([c])):c[0]===L&&(i=!0,o=void 0)}}),u=e.subscribe(d=>{if(!s)for(let c of d){if(s)return;c[0]===E?o!==void 0&&!i&&r.emit(o.v):c[0]===C?(s=!0,r.down([c])):c[0]===L&&(s=!0,r.down([[L]]))}});return()=>{a(),u()}},ue(n))}function zc(t,e,n){return K(r=>{let o,s,i=!1;function a(){o!==void 0&&(clearTimeout(o),o=void 0)}let u=t.subscribe(d=>{for(let c of d)c[0]===E?(s=c[1],i=!0,a(),o=setTimeout(()=>{o=void 0,i&&(i=!1,r.emit(s))},e)):(c[0]===L||c[0]===C)&&(a(),r.down([c]))});return()=>{u(),a()}},ue(n))}function Uc(t,e,n){return K(r=>{let o=[],s=t.subscribe(a=>{for(let u of a)u[0]===E?o.push(u[1]):u[0]===L?(o.length>0&&r.emit([...o]),o.length=0,r.down([[L]])):u[0]===C&&r.down([u])}),i=e.subscribe(a=>{for(let u of a)u[0]===E?o.length>0&&(r.emit([...o]),o.length=0):u[0]===L?r.down([[L]]):u[0]===C&&r.down([u])});return()=>{s(),i(),o.length=0}},ue(n))}function Jc(t,e,n){if(e<=0)throw new RangeError("bufferCount expects count > 0");return K(r=>{let o=[],s=t.subscribe(i=>{for(let a of i)a[0]===E?(o.push(a[1]),o.length>=e&&r.emit(o.splice(0,o.length))):a[0]===L?(o.length>0&&r.emit([...o]),o.length=0,r.down([[L]])):a[0]===C&&r.down([a])});return()=>{s(),o.length=0}},ue(n))}function Yc(t,e,n){if(e<=0)throw new RangeError("windowCount expects count > 0");return K(r=>{let o,s=0;function i(){let u=K(d=>(o=d.down.bind(d),()=>{o=void 0}),ue());s=0,r.emit(u)}let a=t.subscribe(u=>{for(let d of u)d[0]===E?(o||i(),o?.([[E,d[1]]]),s+=1,s>=e&&(o?.([[L]]),o=void 0)):d[0]===L?(o?.([[L]]),o=void 0,r.down([[L]])):d[0]===C&&(o?.([d]),o=void 0,r.down([d]))});return()=>{a(),o?.([[L]]),o=void 0}},ue(n))}function Qc(t,e,n){return K(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]===E?o.push(u[1]):u[0]===L?(clearInterval(s),o.length>0&&r.emit([...o]),o.length=0,r.down([[L]])):u[0]===C&&(clearInterval(s),r.down([u]))});return()=>{i(),clearInterval(s),o.length=0}},ue(n))}function Xc(t,e,n){return K(r=>{let o;function s(){o?.([[L]]),o=void 0}function i(){let d=K(c=>(o=c.down.bind(c),()=>{o=void 0}),ue());r.emit(d)}i();let a=setInterval(()=>{s(),i()},e),u=t.subscribe(d=>{for(let c of d)c[0]===E?o?.([[E,c[1]]]):c[0]===L?(clearInterval(a),s(),r.down([[L]])):c[0]===C&&(clearInterval(a),o?.([c]),s(),r.down([c]))});return()=>{u(),clearInterval(a),s()}},ue(n))}function Zc(t,e,n){return K(r=>{let o;function s(){o?.([[L]]),o=void 0}function i(){let d=K(c=>(o=c.down.bind(c),()=>{o=void 0}),ue());r.emit(d)}let a=t.subscribe(d=>{for(let c of d)c[0]===E?(o||i(),o?.([[E,c[1]]])):c[0]===L?(s(),r.down([[L]])):c[0]===C&&(o?.([c]),o=void 0,r.down([c]))}),u=e.subscribe(d=>{for(let c of d)c[0]===E&&(s(),i())});return()=>{a(),u(),s()}},ue(n))}function el(t,e){return K((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)},ue(e))}function tl(t,e,n){if(e<=0)throw new RangeError("repeat expects count > 0");return K(r=>{let o=e,s,i=()=>{s?.(),s=t.subscribe(a=>{let u=!1,d=[];for(let c of a)c[0]===L?u=!0:d.push(c);d.length>0&&r.down(d),u&&(s?.(),s=void 0,o-=1,o>0?i():r.down([[L]]))})};return i(),()=>{s?.()}},ue(n))}function nl(t,e){return z([t],(n,r)=>{let o=n[0];if(o==null||o.length===0){r.down([[V]]);return}for(let s of o)r.emit(s)},ue(e))}function Yr(t,e,n){return K(r=>{let o=t.subscribe(s=>{for(let i of s)if(i[0]===E)r.emit(i[1]);else if(i[0]===C)try{r.emit(e(i[1]))}catch(a){r.down([[C,a]])}else i[0]===L&&r.down([[L]])});return()=>{o()}},ue(n))}function rl(t,e,n){return z([t,e],(r,o,s)=>{let i=r[1];if(!(i!=null&&i.length>0?i.at(-1):s.prevData[1])){o.down([[V]]);return}let u=r[0];if(u!=null&&u.length>0){for(let d of u)o.emit(d);return}if(i!=null&&i.length>0&&s.prevData[0]!==void 0){o.emit(s.prevData[0]);return}o.down([[V]])},Nc(n))}var ol=Aa,sl=Ia,il=Pa,al=Yr;ae();_e();ee();Vn();var Da=class{ring;arr;constructor(e){e===Number.POSITIVE_INFINITY||e<=0?(this.arr=[],this.ring=null):(this.ring=new ln(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 Qr(t){return t instanceof Error?t:new Error(String(t))}function Ag(t){return t===void 0?null:typeof t=="string"?Bt(t):t}function We(t,e){let{name:n,onTransportError:r,retry:o,backpressure:s,batchSize:i=Number.POSITIVE_INFINITY,flushIntervalMs:a=0,serialize:u,stopOn:d,onUpstreamMessage:c,onDispose:l,send:p,sendBatch:f,ctx:m}=e;if(!p&&!f)throw new Error("reactiveSink: `send` or `sendBatch` must be provided");let h=m,g=Math.max(1,o?.maxAttempts??1),y=Ag(o?.backoff??(g>1?"exponential":void 0)),b=o?.shouldRetry??(()=>!0),v=f!==void 0||i<Number.POSITIVE_INFINITY||a>0,T=W=>n?`${n}::${W}`:void 0,w=M(void 0,{equals:()=>!1,name:T("sent")}),x=M(null,{name:T("failed")}),k=M(0,{name:T("inFlight")}),S=M(null,{name:T("errors")}),R=v?M(0,{name:T("buffered")}):void 0,N=s?M(!1,{name:T("paused")}):void 0,_=0,I=W=>{_+=W,k.down([[E,_]])},O=W=>{try{r?.(W)}catch{}try{S.down([[E,W]])}catch{}},P=new Set,B=W=>{P.add(W);let de=()=>P.delete(W);W.then(de,de)},j=(W,de,Se)=>{let Ee=y?y(de-1,Se,null):0,ce=Ee==null?0:typeof Ee=="number"&&Ee>0?Ee:0,Pe=Math.max(1,Math.ceil(ce/1e6));return new Promise(me=>{setTimeout(()=>me(W()),Pe)})},D=W=>W!=null&&typeof W=="object"&&typeof W.then=="function",Z=W=>{let de;try{de=u?u(W):W}catch(me){let ge=Qr(me);return O({stage:"serialize",error:ge,value:W}),x.down([[E,{value:W,error:ge,attempts:0}]]),Promise.resolve()}let Se=0,Ee=me=>{I(-1);let ge=Qr(me);if(O({stage:"send",error:ge,value:W,attempt:Se}),!(Se<g&&b(ge,Se))){x.down([[E,{value:W,error:ge,attempts:Se}]]);return}return j(Pe,Se,ge)},ce=()=>{I(-1),w.down([[E,W]])};function Pe(){Se+=1,I(1);let me;try{me=p(de,h)}catch(ge){return Ee(ge)??Promise.resolve()}return D(me)?me.then(ce,ge=>Ee(ge)):(ce(),Promise.resolve())}return Pe()},F=s?.maxBuffer??Number.POSITIVE_INFINITY,Q=new Da(F),G,q=!1,$=()=>{R?.down([[E,Q.length]])},te=W=>{N&&N.down([[E,W]])},Re=s?.strategy??"drop-oldest",Oe=(W,de)=>{let Se={value:W,payload:de};if(Q.length<F)return Q.push(Se),$(),!0;if(Re==="drop-oldest"){let ce=Q.shift();return Q.push(Se),$(),te(!0),x.down([[E,{value:ce.value,error:new Error("backpressure: buffer overflow \u2014 dropped oldest"),attempts:0}]]),!0}if(Re==="drop-newest")return te(!0),x.down([[E,{value:W,error:new Error("backpressure: buffer overflow \u2014 dropped newest"),attempts:0}]]),!1;let Ee=new Error("backpressure: buffer overflow");return O({stage:"send",error:Ee,value:W}),x.down([[E,{value:W,error:Ee,attempts:0}]]),te(!0),!1},Ce=W=>{let de=0,Se=W.map(me=>me.payload),Ee=me=>{I(-1);let ge=Qr(me);if(O({stage:"send",error:ge,value:W.map(Sn=>Sn.value),attempt:de}),!(de<g&&b(ge,de))){for(let{value:Sn}of W)x.down([[E,{value:Sn,error:ge,attempts:de}]]);return}return j(Pe,de,ge)},ce=()=>{I(-1);for(let{value:me}of W)w.down([[E,me]])};function Pe(){de+=1,I(1);let me;try{me=f(Se,h)}catch(ge){return Ee(ge)??Promise.resolve()}return D(me)?me.then(ce,ge=>Ee(ge)):(ce(),Promise.resolve())}return Pe()},ye=async W=>{for(let de of W)await Ge(de.value,de.payload)},Ge=(W,de)=>{let Se=0,Ee=me=>{I(-1);let ge=Qr(me);if(O({stage:"send",error:ge,value:W,attempt:Se}),!(Se<g&&b(ge,Se))){x.down([[E,{value:W,error:ge,attempts:Se}]]);return}return j(Pe,Se,ge)},ce=()=>{I(-1),w.down([[E,W]])};function Pe(){Se+=1,I(1);let me;try{me=p(de,h)}catch(ge){return Ee(ge)??Promise.resolve()}return D(me)?me.then(ce,ge=>Ee(ge)):(ce(),Promise.resolve())}return Pe()},ie=()=>{if(q||Q.length===0)return Promise.resolve();let W=Q.drain();if($(),te(!1),f!==void 0){let Se=Ce(W);return B(Se),Se}let de=ye(W);return B(de),de},we=()=>{G!==void 0||q||a<=0||(G=setTimeout(()=>{G=void 0,ie()},a))},Fe=t.subscribe(W=>{for(let de of W){let Se=de[0];if(Se!==E)try{c?.(de)}catch{}if(Se===E){let Ee=de[1];if(v){let ce;if(u)try{ce=u(Ee)}catch(me){let ge=Qr(me);O({stage:"serialize",error:ge,value:Ee}),x.down([[E,{value:Ee,error:ge,attempts:0}]]);continue}else ce=Ee;if(!Oe(Ee,ce))continue;Q.length>=i?ie():we()}else{let ce=Z(Ee);B(ce)}}else $e.messageTier(Se)>=3&&v&&(G!==void 0&&(clearTimeout(G),G=void 0),ie())}}),be;if(d){let W=!1;be=d.subscribe(de=>{if(!W){W=!0;return}de.length>0&&!J&&se()})}let J=!1,se=()=>{if(J)return;J=!0,G!==void 0&&(clearTimeout(G),G=void 0),v&&ie(),q=!0,be?.(),Fe();let W=de=>{try{de.down([[le]])}catch{}};W(S),W(x),W(w),W(k),R&&W(R),N&&W(N);try{l?.()}catch{}},ve={dispose:se,sent:w,failed:x,inFlight:k,errors:S};return v&&(ve.buffered=R,ve.flush=async()=>{q||(await ie(),await Promise.all(P))}),N&&(ve.paused=N),ve}Ot();he();function gt(t){return{describeKind:"producer",...t}}function Fa(t,e){let{parse:n,closeOnTeardown:r=!1,...o}=e??{};return K(s=>{let i=!0,a,u=()=>{let y=a;a=void 0,y?.()},d=y=>{i&&(i=!1,s.down([y]),u())},c=(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){d([C,v])}},l=y=>{d([C,y])},p=()=>{d([L])};if(typeof t=="function"){try{if(a=t(c,l,p),typeof a!="function")throw new Error("fromWebSocket register contract violation: register must return cleanup callable")}catch(y){d([C,y])}return()=>{i=!1,u()}}let f=t,m=y=>c(y,y),h=y=>l(y),g=()=>p();return f.addEventListener("message",m),f.addEventListener("error",h),f.addEventListener("close",g),a=()=>{f.removeEventListener("message",m),f.removeEventListener("error",h),f.removeEventListener("close",g),r&&f.close()},()=>{i=!1,u()}},gt(o))}function ul(t,e){return mn(t,e)}function $a(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:d=!1,...c}=e??{},l=M(0,{name:`${c.name??"http"}/fetchCount`}),p=M(0,{name:`${c.name??"http"}/lastUpdated`}),f=M(!1,{name:`${c.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([[C,a.reason??new Error("Aborted")]]),()=>{};a?.addEventListener("abort",()=>T.abort(a.reason),{once:!0});let x=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 k=>{if(clearTimeout(x),!w)return;if(!k.ok)throw new Error(`HTTP ${k.status}: ${k.statusText}`);let S=await s(k);w&&(X(()=>{m+=1,l.down([[E,m]]),p.down([[E,oe()]]),f.down([[E,!0]]),v.emit(S)}),u&&v.down([[L]]))}).catch(k=>{clearTimeout(x),w&&(k&&k.name==="AbortError"||v.down([[C,k]]))}),()=>{w=!1,T.abort()}},y=K(v=>g({emit:T=>v.emit(T),down:T=>v.down(T)}),{...gt(c),resubscribable:d});return{...Kt(y),fetchCount:l,lastUpdated:p,fetched:f}}function dl(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:d,retry:c,onTransportError:l}=n??{},p=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||d!==void 0?We(t,{onTransportError:l,retry:c,batchSize:u,flushIntervalMs:d,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 p(h)}}):We(t,{onTransportError:l,retry:c,serialize:s,send:async m=>{await p(m)}})}function cl(t){return Symbol.keyFor(t)??t.description??"message"}function Xn(t,e){return typeof t=="string"?t:e(t)}function ll(t,e){let n=`event: ${t}
9
+ `,n}function bm(t){return JSON.parse(t)}function vm(t,e){try{t.send(JSON.stringify(e))}catch{}}function ma(t,e){try{t(e)}catch{}}kr();var rs="graphReflyActor";function ga(t){return e=>{let r=e.switchToHttp().getRequest()?.user;if(r!=null)return t?t(r):r}}function Ud(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 Jd(t){let e=t?.[rs];return e!=null?Nt(e):bt}var Pr=class{constructor(e){this.extractor=e}canActivate(e){let n=Nt(this.extractor(e)),r=e.switchToHttp().getRequest();return r!=null&&(r[rs]=n),!0}};function Yd(t){return new Pr(t??ga())}var Wr=require("@nestjs/common"),Sc=require("@nestjs/core");kr();Me();xe();$t();ae();$t();_e();function At(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 Tm(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function wm(t){let e={};for(let[n,r]of Object.entries(t.meta))try{e[n]=r.cache}catch{}return e}function Dr(t,e){let n=e==null,r=!n&&e!=null?[...e].filter(d=>d.startsWith("meta.")).map(d=>d.slice(5)):null,o=n||e.has("meta")||r!=null&&r.length>0,s="state",i=[];t instanceof Ce&&(s=Tm(t),i=t._deps.map(d=>d.node.name??""));let a={type:s,deps:i};(n||e.has("status"))&&(a.status=t.status);let u=t instanceof Ce?t._guard:void 0;if(o){let d={...wm(t)};if(u!=null&&d.access===void 0&&(d.access=_r(u)),r!=null&&r.length>0&&!e.has("meta")){let c={};for(let l of r)l in d&&(c[l]=d[l]);a.meta=c}else a.meta=d}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 d={id:t.v.id,version:t.v.version};"cid"in t.v&&(d.cid=t.v.cid,d.prev=t.v.prev),a.v=d}return(n||e.has("guard"))&&u!=null&&(a.guard=_r(u)),(n||e.has("lastMutation"))&&t.lastMutation!=null&&(a.lastMutation=t.lastMutation),a}_e();ee();he();vt();var ln=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}};Lo();function ha(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 Jn(t){let e=0;for(let n of t)e+=ha(n.codePointAt(0));return e}function Qd(t,e){if(e<=0)return"";let n=0,r="";for(let o of t){let s=ha(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-=ha(i.codePointAt(0))}return`${r}\u2026`}r+=o,n+=s}return r}var km={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"},xm={horizontal:"-",vertical:"|",cornerTL:"+",cornerTR:"+",cornerBL:"+",cornerBR:"+",tDown:"+",tUp:"+",tRight:"+",tLeft:"+",cross:"+",arrowRight:">",arrowDown:"v",arrowLeft:"<",arrowUp:"^",boxTL:"+",boxTR:"+",boxBL:"+",boxBR:"+",boxH:"-",boxV:"|"};function tc(t,e){let n=e.charset==="ascii"?xm:km,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)Sm(s,i,n,a);for(let a of t.boxes)Rm(s,i,n,a,e.labelOf(a.id));return s.map(a=>Mm(a.join(""))).join(`
10
+ `)}function Rm(t,e,n,r,o){let{x:s,y:i,w:a,h:u}=r;if(a<2||u<2){u>0&&Xd(t,e,s,i,a,o);return}Ht(t,e,s,i,n.boxTL);for(let c=s+1;c<s+a-1;c+=1)Ht(t,e,c,i,n.boxH);Ht(t,e,s+a-1,i,n.boxTR);for(let c=i+1;c<i+u-1;c+=1){Ht(t,e,s,c,n.boxV);for(let l=s+1;l<s+a-1;l+=1)nc(t,e,l,c," ","empty");Ht(t,e,s+a-1,c,n.boxV)}Ht(t,e,s,i+u-1,n.boxBL);for(let c=s+1;c<s+a-1;c+=1)Ht(t,e,c,i+u-1,n.boxH);Ht(t,e,s+a-1,i+u-1,n.boxBR);let d=i+Math.floor(u/2);Xd(t,e,s+1,d,a-2,o)}function Ht(t,e,n,r,o){nc(t,e,n,r,o,o===" "?"empty":o==="\u2500"||o==="-"?"boxH":o==="\u2502"||o==="|"?"boxV":"boxCorner")}function nc(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 Xd(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=n,a=o;for(let u of s){let d=Jn(u);if(d!==0){if(a<d)break;i>=0&&i<t[r].length&&(t[r][i]=u,e[r][i]="label",d===2&&i+1<t[r].length&&(t[r][i+1]="",e[r][i+1]="label")),i+=d,a-=d}}for(;a>0;)i>=0&&i<t[r].length&&(t[r][i]=" ",e[r][i]="empty"),i+=1,a-=1}function Sm(t,e,n,r){let o=r.points;if(o.length<2)return;for(let u=0;u+1<o.length;u+=1)Em(t,e,n,o[u],o[u+1]);for(let u=1;u+1<o.length;u+=1){let d=o[u-1],c=o[u],l=o[u+1],p=Nm(d,c,l,n);p&&ec(t,e,c.x,c.y,p,"edgeCorner")}let s=o[o.length-1],i=o[o.length-2],a=_m(i,s,n);a&&ec(t,e,s.x,s.y,a,"arrow")}function Em(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)Zd(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)Zd(t,e,s,u,n,"v")}}}function Zd(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 ec(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 Nm(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,d=n.y>e.y;return u&&d?r.cornerTR:u&&!d?r.cornerBR:!u&&d?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 _m(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 Mm(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}function sc(t){let e=Om(t);Am(e),Cm(e),Lm(e),Im(e,t);let n=Gm(e,t),{width:r,height:o}=$m(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 Om(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 Am(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 Cm(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 d=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:d.id,toId:p,hopIndex:l-1,chainLen:u};d.out.push(m),f.in.push(m),r.push(m),d=f}let c={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:d.id,toId:a.id,hopIndex:u-1,chainLen:u};d.out.push(c),a.in.push(c),r.push(c)}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 Lm(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)rc(t,t.layers[r],"in"),os(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)rc(t,t.layers[r],"out"),os(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=oc(t,s[i],s[i+1],"in");[s[i],s[i+1]]=[s[i+1],s[i]],os(s),oc(t,s[i],s[i+1],"in")<a?r=!0:([s[i],s[i+1]]=[s[i+1],s[i]],os(s))}}if(!r)break}}function rc(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 d=t.nodes.get(n==="in"?u.fromId:u.toId);d&&(i+=d.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 os(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function oc(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 d=t.nodes.get(r==="in"?a.fromId:a.toId)?.order??0,c=t.nodes.get(r==="in"?u.fromId:u.toId)?.order??0;(e.order<n.order&&d>c||e.order>n.order&&d<c)&&(i+=1)}return i}function Im(t,e){e.direction==="LR"?Pm(t,e):Dm(t,e)}function Pm(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}ic(t,e,"y")}function Dm(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}ic(t,e,"x")}function ic(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 c of a){let l=s===0?c.in:c.out;if(l.length===0)continue;let p=[];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;p.push(g+Math.floor(r(h)/2))}if(p.length===0)continue;p.sort((m,h)=>m-h);let f=p[Math.floor(p.length/2)];u.set(c.id,f-Math.floor(r(c)/2))}let d=0;for(let c of a){let l=u.get(c.id),p=n==="y"?c.y:c.x,m=Math.max(l??p,d);n==="y"?c.y=m:c.x=m,d=m+r(c)+o}}}}function Gm(t,e){let n=new Map;for(let d of t.hops){let c=n.get(d.chainId);c?c.push(d):n.set(d.chainId,[d])}for(let d of n.values())d.sort((c,l)=>c.hopIndex-l.hopIndex);let r=e.direction==="LR",o=d=>r?d.x:d.y,s=d=>r?d.w:d.h,i=d=>r?d.y+Math.floor(d.h/2):d.x+Math.floor(d.w/2),a=new Map;for(let d=0;d+1<t.layers.length;d+=1){let c=t.layers[d],l=t.layers[d+1],p=0;for(let S of c)p=Math.max(p,o(S)+s(S));let f=Number.POSITIVE_INFINITY;for(let S of l)f=Math.min(f,o(S));let m=Number.isFinite(f)?f-1:p,h=Math.max(1,m-p+1),g=[];for(let S of c)for(let R of S.out)g.push(R);g.sort((S,R)=>{let N=i(t.nodes.get(S.fromId)),_=i(t.nodes.get(R.fromId));if(N!==_)return N-_;let I=i(t.nodes.get(S.toId)),O=i(t.nodes.get(R.toId));return I-O});let y=[],b=new Map;for(let S of g){let R=i(t.nodes.get(S.fromId)),N=i(t.nodes.get(S.toId)),_=Math.min(R,N),I=Math.max(R,N),O=-1;for(let P=0;P<y.length;P+=1){let B=y[P],j=!0;for(let D of B)if(D.lo<=I&&_<=D.hi){j=!1;break}if(j){B.push({lo:_,hi:I}),O=P;break}}O<0&&(y.push([{lo:_,hi:I}]),O=y.length-1),b.set(S,O)}let v=y.length,T=h>=Math.max(3,v+2),w=T?p+1:p,k=T?m-1:m,x=Math.max(1,k-w+1);for(let S of g){let R=b.get(S),N;if(v<=1)N=w+Math.floor(x/2);else{let _=(x-1)/(v-1);N=w+Math.floor(R*_)}a.set(S,Math.max(p,Math.min(m,N)))}}let u=[];for(let[,d]of n){let c=[];for(let p=0;p<d.length;p+=1){let f=d[p],m=t.nodes.get(f.fromId),h=t.nodes.get(f.toId),g=a.get(f),y=m.isVirtual?o(m):o(m)+s(m),b=h.isVirtual?o(h):o(h)-1,v=i(m),T=i(h);p===0&&ss(c,r,y,v),v!==T&&(ss(c,r,g,v),ss(c,r,g,T)),ss(c,r,b,T)}let l=d[0];u.push({from:l.chainFrom,to:l.chainTo,points:Fm(c)})}return u}function ss(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function Fm(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 $m(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 jm=24,Bm=4,Vm=1,Km=3;function ac(t,e){let n=qm(e.direction),r=Math.max(3,e.maxLabelWidth??jm),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,d=new Map;for(let f of s){let m=Qd(f,r);u.set(f,m),d.set(f,Jn(m)+4)}let c=sc({nodes:s,edges:a,widthCells:f=>d.get(f)??3,heightCells:()=>Km,layerGap:Bm,nodeGap:Vm,direction:n}),l=tc(c,{charset:o,labelOf:f=>u.get(f)??f}),p=e.logger;return p&&p(l),l}function qm(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 Gr(t,e,n,r={}){let o=e in t.nodes,s=n in t.nodes;if(!o)return is(e,n,"no-such-from");if(!s)return is(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 d=Hm(t,e,r);if(d!=null)return d}let u=as(e,t.nodes[e],0,r);return us(e,n,[u])}if(i===0)return is(e,n,"no-path");let a=uc(t,e,n,i);return a.found?us(e,n,dc(t,a.pathOrder,r)):is(e,n,a.truncated?"max-depth-exceeded":"no-path")}function uc(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 p=t.nodes[l.path];if(p==null)continue;let f=p.deps??[],m=new Map;for(let h=0;h<f.length;h++){let g=f[h];if(!g)continue;let y=m.get(g);y==null&&(y=[],m.set(g,y)),y.push(h)}for(let[h,g]of m)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 d=[{path:e}],c=e;for(;c!==n;){let l=o.get(c);if(l==null)return{found:!1,pathOrder:[],truncated:!1};d[d.length-1].depIndices=l.depIndices,d.push({path:l.from}),c=l.from}return{found:!0,pathOrder:d,truncated:!1}}function Hm(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=as(e,r,0,n);a.dep_index=s[0];let u=as(e,r,1,n);return us(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 d=uc(t,u,e,n.maxDepth);d.found&&(i==null||d.pathOrder.length<i.pathOrder.length)&&(i=d,i={found:!0,pathOrder:[{path:e,depIndices:[a]},...d.pathOrder],truncated:!1})}return i==null?null:us(e,e,dc(t,i.pathOrder,n))}function dc(t,e,n){return e.map((r,o)=>{let s=t.nodes[r.path],i=as(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 as(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 us(t,e,n){return cc(t,e,!0,"ok",n)}function is(t,e,n){return cc(t,e,!1,n,[])}function cc(t,e,n,r,o){let s=Wm(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 Wm(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: ${zm(i.value)}`),i.annotation!=null&&s.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let d=i.lastMutation.actor;s.push(` actor: ${d.type}${d.id?`:${d.id}`:""}`)}}return s.join(`
11
+ `)}function zm(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)}}_e();var je={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},ds=Symbol.for("sizeof");function Fr(t){let e=new WeakSet,n=new WeakSet,r=[t],o=0;for(;r.length>0;){let s=r.pop();o+=Um(s,e,n,r)}return o}function Um(t,e,n,r){if(t==null)return 0;switch(typeof t){case"number":return je.number;case"boolean":return je.boolean;case"string":return je.string+t.length*2;case"bigint":return je.bigint+Jm(t);case"symbol":return je.symbol;case"function":return e.has(t)?0:(e.add(t),je.function);case"undefined":return 0}let s=t;if(e.has(s))return 0;e.add(s);let i=s[ds];if(typeof i=="function")try{let d=i.call(s);if(typeof d=="number"&&Number.isFinite(d))return d}catch{}if(s instanceof Date)return je.date;if(s instanceof RegExp)return je.regexp+s.source.length*2;if(s instanceof Error){let d=s.message?s.message.length*2:0,c=s.stack?s.stack.length*2:0;return je.error+d+c}if(typeof URL<"u"&&s instanceof URL)return je.url+s.href.length*2;if(typeof Promise<"u"&&s instanceof Promise)return je.promise;if(s instanceof WeakMap)return je.weakmap;if(s instanceof WeakSet)return je.weakset;if(s instanceof Map){let d=je.map;for(let[c,l]of s)d+=je.mapEntry,r.push(c),r.push(l);return d}if(s instanceof Set){let d=je.set;for(let c of s)d+=je.setEntry,r.push(c);return d}if(Array.isArray(s)){let d=je.array+s.length*8;for(let c of s)r.push(c);return d}if(s instanceof ArrayBuffer)return n.has(s)?0:(n.add(s),s.byteLength);if(ArrayBuffer.isView(s)){let d=s;return n.has(d.buffer)?48:(n.add(d.buffer),d.buffer.byteLength+48)}let a=je.object,u=Object.keys(s);for(let d of u){a+=je.string+d.length*2;try{r.push(s[d])}catch{}}return a}function Jm(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 pn(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),h=m instanceof Ce?m:null,g=h?Fr(h.cache):0,y=h?h._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:g,subscriberCount:y,depCount:b,isOrphanEffect:v,orphanKind:T})}let u=a.reduce((p,f)=>p+f.valueSizeBytes,0),d=(p,f)=>[...a].sort(f??((m,h)=>h[p]-m[p])).slice(0,n),c=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:d("valueSizeBytes"),bySubscriberCount:d("subscriberCount"),byDepCount:d("depCount")},orphans:c,orphanEffects:l}}var De="::",Qe="__meta__",ft=1;function lc(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 mc(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"&&typeof t.down=="function"}function Ym(t){if(t!=null)return mc(t)?t.cache:t}function Qm(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 pc(t){if(t.version!==ft)throw new Error(`unsupported snapshot version ${String(t.version)} (expected ${ft})`);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 Xm(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 h of p)if(r(f,h)){m=!0;break}if(!m)return!1}return!0}if(ArrayBuffer.isView(o)){let p=o,f=s;if(p.length!==f.length)return!1;for(let m=0;m<p.length;m++)if(p[m]!==f[m])return!1;return!0}let d=Object.keys(o),c=Object.keys(s);if(d.length!==c.length)return!1;let l=new Set(c);for(let p of d)if(!l.has(p)||!r(o[p],s[p]))return!1;return!0};return r(t,e)}function ba(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(ba);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=ba(e[o]);return r}function Zm(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function eg(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function tg(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 hc(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 ng(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(ba(i),null,e.indent??2);return e.logger?.(a),a}function rg(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}): ${ls(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 yc(t,e){let n=hc(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}["${Zm(i)}"]`)}for(let[i,a]of gc(t)){let u=o.get(i),d=o.get(a);!u||!d||s.push(` ${u} --> ${d}`)}return s.join(`
14
+ `)}function og(t,e){let n=yc(t,e);return ps(n)}function ps(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 d=0;d<i.length;d++)a+=String.fromCharCode(i[d]);return`https://mermaid.live/edit#base64:${globalThis.btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`}function sg(t,e){let n=hc(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: ${tg(n)}`];for(let i of r){let a=o.get(i);s.push(`${a}: "${eg(i)}"`)}for(let[i,a]of gc(t)){let u=o.get(i),d=o.get(a);!u||!d||s.push(`${u} -> ${d}`)}return s.join(`
15
+ `)}function ig(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function cs(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+=ig(r)}return e+="$",new RegExp(e)}var ag={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"},ug={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function ls(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 dg(t){return t==="none"?ug:t==="ansi"||t==null?ag:{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 fc(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 cg(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 ya(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(De))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${De}' (path separator)`);if(t===Qe)throw new Error(`Graph "${e}": ${n} name "${Qe}" is reserved for meta companion paths`);cg(t,e,n)}function lg(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(De);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function pg(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([[de]],{internal:!0})}catch{}}var Y=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(De))throw new Error(`Graph name must not contain '${De}' (got "${e}")`);if(e===Qe)throw new Error(`Graph name "${Qe}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??$e,this._traceRing=new ln(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=K(e=>{let n=r=>{e.emit(r)};return this._topologyEmitters.add(n),()=>{this._topologyEmitters.delete(n)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let n of this._topologyEmitters)n(e)}nameOf(e){return this._nodeToName.get(e)}add(e,n){let r=e.name,o=n?.name??r;if(o==null||o==="")throw new Error(`Graph "${this.name}": graph.add requires a non-empty name \u2014 pass via opts.name or set it on the node (e.g. state(0, { name: "x" }))`);let s=o,i=n?.annotation;if(ya(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:H()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof Ce&&n._applyVersioning(e)}remove(e){ya(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(`${De}${Qe}${De}`)||s.nodes.push(a);return s.nodes.sort(),s.mounts.push(e),s.mounts.push(...n._collectSubgraphs(`${e}${De}`)),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([[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=cs(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(De))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([[E,n]],{actor:r?.actor,internal:o,delivery:"write"})}setAll(e,n){let r=Symbol.iterator in e?e:Object.entries(e);X(()=>{for(let[o,s]of r)this.set(o,s,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[Je]],{actor:n?.actor,internal:r,delivery:"write"})}error(e,n,r){let o=r?.internal===!0;this.node(e).down([[A,n]],{actor:r?.actor,internal:o,delivery:"write"})}complete(e,n){let r=n?.internal===!0;this.node(e).down([[L]],{actor:n?.actor,internal:r,delivery:"write"})}edges(e){let n=e?.recursive===!0,r=new Map;if(!n){for(let[u,d]of this._nodes)r.set(d,u);let a=[];for(let[u,d]of this._nodes)if(d instanceof Ce)for(let c of d._deps){let l=r.get(c.node);l!=null&&a.push([l,u])}return a.sort((u,d)=>u[0]<d[0]?-1:u[0]>d[0]?1:u[1]<d[1]?-1:u[1]>d[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 Ce)for(let d of u._deps){let c=s.get(d.node);c!=null&&i.push([c,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(n===void 0){let o=new t(e);return this.mount(e,o)}if(typeof n=="function"){let o=new t(e);return n(o),this.mount(e,o)}let r=n;if(ya(e,this.name,"mount"),this._nodes.has(e))throw new Error(`Graph "${this.name}": cannot mount at "${e}" \u2014 node with that name exists`);if(this._mounts.has(e))throw new Error(`Graph "${this.name}": mount "${e}" already exists`);if(r===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(r._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${r._parent.name}"`);for(let o=this;o!=null;o=o._parent)if(o===r)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,r),r._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),r}resolve(e){let n=lg(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]===Qe)return this._resolveMetaChainFromNode(s,o,n.join(De));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(De)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(o.join(De))}_resolveMetaChainFromNode(e,n,r){let o=e,s=0,i=[...n];for(;s<i.length;){if(i[s]!==Qe)throw new Error(`Graph "${this.name}": expected ${Qe} segment in meta path "${r}"`);if(s+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${Qe} 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=pg(e,this.config);for(let u of[...this._nodes.keys()].sort()){let d=this._nodes.get(u);if(!r.has(d)){r.add(d);try{d.down(e,i)}catch(c){if(c instanceof rt)throw c;o.push(c)}a.length!==0&&this._signalMetaSubtree(d,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 rt)throw u;s.push(u)}this._signalMetaSubtree(a,n,r,o,s)}}}describe(e){if(e?.reactive===!0)return this._describeReactive(e);let n=Ym(e?.actor),r=e?.filter,o=At(e?.detail,e?.fields),s=e?.format==="spec",i=s?At("minimal"):o,a=[];this._collectObserveTargets("",a);let u=new Map;for(let[k,x]of a)u.set(x,k);let d=[];{let k=a.map(([,R])=>R),x=new Set(u.values()),S=0;for(;k.length>0;){let R=k.shift();if(R instanceof Ce)for(let N of R._deps){let _=N.node;if(u.has(_))continue;let I=_.name??"",O=I;if(!O||x.has(O))if(I){let P=2;for(;x.has(`${I}#${P}`);)P++;O=`${I}#${P}`}else for(O=`__internal__/${S++}`;x.has(O);)O=`__internal__/${S++}`;u.set(_,O),x.add(O),d.push([O,_]),k.push(_)}}}let c=[...a,...d],l={};for(let[k,x]of c){if(n!=null&&!x.allowsObserve(n))continue;let S=Dr(x,i),R=x instanceof Ce?x._deps.map(O=>u.get(O.node)??O.node.name??""):[],{name:N,..._}=S,I={..._,deps:R};if(!s){let O=this._annotations.get(k);O!=null&&(I.annotation=O)}if(r!=null)if(typeof r=="function"){let O=r;if(!(O.length>=2?O(k,I):O(I)))continue}else{let O=!0;for(let[P,B]of Object.entries(r)){let j=P==="deps_includes"?"depsIncludes":P==="meta_has"?"metaHas":P;if(j==="depsIncludes"){if(!I.deps.includes(String(B))){O=!1;break}continue}if(j==="metaHas"){if(!Object.hasOwn(I.meta??{},String(B))){O=!1;break}continue}if(I[j]!==B){O=!1;break}}if(!O)continue}l[k]=I}let p=new Set(Object.keys(l)),f=[];for(let[k,x]of c)if(x instanceof Ce)for(let S of x._deps){let R=u.get(S.node);R!=null&&f.push([R,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 h=this._collectSubgraphs(""),g=n!=null||r!=null?h.filter(k=>{let x=`${k}${De}`;return[...p].some(S=>S===k||S.startsWith(x))}):h,y=this,b=e,v={name:this.name,nodes:l,edges:m,subgraphs:g,expand(k){let x={...b,format:void 0};return Array.isArray(k)?(x.fields=k,x.detail=void 0):(x.detail=k,x.fields=void 0),y.describe(x)}},T=e??{},w=T.format;return w==="json"?ng(v,T):w==="pretty"?rg(v,T):w==="mermaid"?yc(v,T):w==="mermaid-url"?og(v,T):w==="d2"?sg(v,T):w==="ascii"?ac(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}${De}`))}return n}resourceProfile(e){return pn(this,e)}reachable(e,n,r={}){return r.withDetail===!0?fn(this.describe(),e,n,{...r,withDetail:!0}):fn(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 Gr(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=M(o,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,u=!1,d=()=>{a||u||(a=!0,Sr(()=>{a=!1,!u&&(o+=1,s.emit(o))}))},c=i.onEvent(b=>{let v=b.type;v!=="data"&&v!=="error"&&v!=="complete"&&v!=="teardown"||d()}),l=[],p=new WeakSet,f=b=>{if(p.has(b)||u)return;p.add(b);let v=b.topology.subscribe(T=>{for(let w of T){if(w[0]!==E)continue;let k=w[1];if(d(),k.kind==="added"&&k.nodeKind==="mount"){let x=b._mounts.get(k.name);x!=null&&f(x)}}});l.push(v);for(let T of b._mounts.keys()){let w=b._mounts.get(T);w!=null&&f(w)}};f(this);let m,h=e.actor;mc(h)&&(m=h.subscribe(b=>{let v=!1,T=!1;for(let w of b){let k=w[0];k===E?v=!0:(k===L||k===A||k===de)&&(T=!0)}v&&d(),T&&(m?.(),m=void 0,d())}));let g;try{g=C([s],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(b,v)=>b===v})}catch(b){c(),m?.();for(let v of l)v();throw i.dispose(),b}let y=re(g);return{node:g,dispose(){u=!0,c(),m?.();for(let b of l)b();l.length=0,i.dispose(),y()}}}_explainReactive(e,n,r){let o=0,s=M(o,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,u=!1,d=i.onEvent(f=>{let m=f.type;m!=="data"&&m!=="error"&&m!=="complete"&&m!=="teardown"||a||u||(a=!0,Sr(()=>{a=!1,!u&&(o+=1,s.emit(o))}))}),c={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},l;try{l=C([s],()=>this._explainStatic(e,n,c),{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&&fg(f.steps,m.steps)})}catch(f){throw d(),i.dispose(),f}let p=re(l);return{node:l,dispose(){u=!0,d(),i.dispose(),p()}}}_pathsMatching(e){let n=cs(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}${De}${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}${De}${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}${De}${Qe}${De}${o}`;r.push([i,s]),this._appendMetaObserveTargets(i,s,r)}}observe(e,n){let r=typeof e=="string",s=fc(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 c=e,l=this.resolve(c);if(a!=null&&!l.allowsObserve(a))throw new rt({actor:a,action:"observe",nodeName:c});return i?this._buildStructuredObserver([[c,l]],s,"one"):{subscribe(p){return l.subscribe(p)},up(p){try{l.up?.(p)}catch(f){if(f instanceof rt)return;throw f}}}}let u=[];this._collectObserveTargets("",u),u.sort((c,l)=>c[0]<l[0]?-1:c[0]>l[0]?1:0);let d=a==null?u:u.filter(([,c])=>c.allowsObserve(a));return i?this._buildStructuredObserver(d,s,"all"):{subscribe:c=>{let l=d.map(([p,f])=>f.subscribe(m=>{c(p,m)}));return()=>{for(let p of l)p()}},up:(c,l)=>{try{this.resolve(c).up?.(l)}catch(p){if(p instanceof rt)return;throw p}}}}_buildStructuredObserver(e,n,r){let o=r==="one"?e[0]?.[0]:void 0,s=i=>{if(r==="one"&&o!=null){let c=this.resolve(o);return this._buildStructuredObserver([[o,c]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((c,l)=>c[0]<l[0]?-1:c[0]>l[0]?1:0);let u=i.actor,d=u==null?a:a.filter(([,c])=>c.allowsObserve(u));return this._buildStructuredObserver(d,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,d=(s||i)&&u,c=n.maxEvents,l=c!=null&&c>0?new ln(c):null,p=[],f=new Set,m={},h=new Set,g=0,y=0,b=0,v=0,T=0,w=0,k=!1,x=!1,S=0,R=new Map,N=new Map,_=new Map,I=$=>{l?l.push($):p.push($);for(let te of f)te($)},O=()=>o?{timestamp_ns:H(),in_batch:tn(),batch_id:S}:{},P=($,te)=>{if(!(!d||!($ instanceof Ce)))return $._setInspectorHook(Re=>{if(Re.kind==="dep_message")R.set($,Re.depIndex);else if(Re.kind==="run"){let Oe=Re.batchData.map((ye,Ge)=>ye!=null&&ye.length>0?ye.at(-1):Re.prevData[Ge]);N.set($,Oe);let Ae=Re.batchData.map(ye=>ye!=null?[...ye]:void 0);_.set($,Ae),i&&I({type:"derived",path:te,dep_values:Oe,dep_batches:Ae,...O()})}})},B=$=>{let te=R.get($),Re=N.get($);if(!s||Re==null)return{};let Ae=(te!=null&&te>=0&&$ instanceof Ce?$._deps[te]:void 0)?.node,ye=Ae?.v,Ge=_.get($);return{trigger_dep_index:te,trigger_dep_name:Ae?.name,...ye!=null?{trigger_version:{id:ye.id,version:ye.version}}:{},dep_values:[...Re],...Ge!=null?{dep_batches:Ge}:{}}},j=[],D=[];for(let[$,te]of e){let Re=P(te,$);Re&&j.push(Re),D.push(te.subscribe(Oe=>{S++;for(let Ae of Oe){let ye=Ae[0],Ge=O();if(ye===E){m[$]=Ae[1];let ie=te instanceof Ce?te.lastMutation?.actor??bt:bt;I({type:"data",path:$,data:Ae[1],actor:ie,...Ge,...B(te)})}else if(a)ye===ne?g++:ye===V?y++:ye===Je?b++:ye===Be?v++:ye===qe?T++:ye===de?w++:ye===L&&!h.has($)?k=!0:ye===A&&(x=!0,h.add($));else if(ye===ne)g++,I({type:"dirty",path:$,...Ge});else if(ye===V)y++,I({type:"resolved",path:$,...Ge,...B(te)});else if(ye===Je)b++,I({type:"invalidate",path:$,...Ge});else if(ye===Be)v++,I({type:"pause",path:$,lockId:Ae[1],...Ge});else if(ye===qe)T++,I({type:"resume",path:$,lockId:Ae[1],...Ge});else if(ye===L)h.has($)||(k=!0),I({type:"complete",path:$,...Ge});else if(ye===A){x=!0,h.add($);let ie=te instanceof Ce?te.lastMutation?.actor??bt:bt;I({type:"error",path:$,data:Ae[1],actor:ie,...Ge})}else ye===de&&(w++,I({type:"teardown",path:$,...Ge}))}}))}let Z=!1,F=()=>{if(!Z){Z=!0;for(let $ of D)$();for(let $ of j)$();for(let $ of G)$({value:void 0,done:!0});G.length=0}},Q=[],G=[];f.add($=>{let te=G.shift();te?te({value:$,done:!1}):Q.push($)});let q={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():[...p]},get anyCompletedCleanly(){return k},get anyErrored(){return x},get completedWithoutErrors(){return k&&!x},onEvent($){return f.add($),()=>f.delete($)},dispose:F,expand($){F();let te={...n};return typeof $=="string"?te.detail=$:Object.assign(te,$),r(fc(te))},[Symbol.asyncIterator](){return{next(){return Q.length>0?Promise.resolve({value:Q.shift(),done:!1}):Z?Promise.resolve({value:void 0,done:!0}):new Promise($=>G.push($))},return(){return F(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(q,n),q}_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=dg(n.theme),d=r==="stage-log"?H():0,c=m=>m==null?"":n.stageLabels?.[m]??m,l=(m,h)=>m.length>h?`${m.slice(0,h-1)}\u2026`:m,p=m=>m.type==="data"||m.type==="error"?l(ls(m.data),120):"",f=m=>{if(r==="stage-log"){let x=(H()-d)/1e9,S=c(m.path).padEnd(9);if(m.type==="data"){let R=p(m);return`[${x.toFixed(3)}s] ${S} \u2190${R?` ${R}`:""}`}if(m.type==="error"){let R=p(m);return`[${x.toFixed(3)}s] ${S} \u2717${R?` ${R}`:""}`}return m.type==="complete"?`[${x.toFixed(3)}s] ${S} \u25A0 complete`:`[${x.toFixed(3)}s] ${S} ${m.type}`}if(r==="json")try{return JSON.stringify(m)}catch{return JSON.stringify({type:m.type,path:m.path,data:"[unserializable]"})}let h=u[m.type]??"",g=m.path?`${u.path}${m.path}${u.reset} `:"",y=m.type==="data"||m.type==="error",b=m.type==="pause"||m.type==="resume",v=y?` ${ls(m.data)}`:b?` ${ls(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(f(m),m)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){lc(this._disposers,this.name),this.signal([[de]],{internal:!0}),lc(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:d,...c}=r.nodes[a];o[a]=c}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 vr(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??$e,{codec:o,codecVersion:s,payload:i}=Tr(e,r);return o.decode(i,s)}restore(e,n){if(pc(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=>cs(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){pc(e);let r=typeof n=="function"?n:n?.build,o=typeof n=="function"?void 0:n?.factories,s=new t(e.name);if(r)return r(s),s.restore(e),s;for(let f of[...e.subgraphs].sort((m,h)=>{let g=m.split(De).length,y=h.split(De).length;return g!==y?g-y:m<h?-1:m>h?1:0})){let m=f.split(De),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(([f,m])=>({re:cs(f),factory:m})):[],a=f=>{for(let m of i)if(m.re.test(f))return m.factory},u=f=>{let m=f.split(De),h=m.pop();if(h==null||h.length===0)throw new Error(`invalid snapshot path "${f}"`);let g=s;for(let y of m){let b=g._mounts.get(y);if(!b)throw new Error(`unknown mount "${y}" in path "${f}"`);g=b}return[g,h]},d=Object.entries(e.nodes).filter(([f])=>!f.includes(`${De}${Qe}${De}`)).sort((f,m)=>f[0]<m[0]?-1:f[0]>m[0]?1:0),c=new Map(d),l=new Map,p=!0;for(;c.size>0&&p;){p=!1;for(let[f,m]of[...c.entries()]){let h=m?.deps??[];if(!h.every(w=>l.has(w)))continue;let[g,y]=u(f),b={...m?.meta??{}},v=a(f),T;if(m?.type==="state")T=M(m.value,{meta:b});else{if(v==null)continue;T=v(y,{path:f,type:m.type,value:m.value,meta:b,deps:h,resolvedDeps:h.map(w=>l.get(w))})}g.add(T,{name:y}),l.set(f,T),c.delete(f),p=!0}}if(c.size>0){let f=[...c.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${f}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return s.restore(e),s}toJSON(){return this.snapshot()}attachSnapshotStorage(e,n={}){let r=e.map(d=>({tier:d,debounceMs:Math.max(0,d.debounceMs??0),compactEvery:Math.max(1,d.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=(d,c)=>{if(d.disposed)return;let l=Qm(c.nodes);if(d.lastSnapshot!=null&&l!==""&&l===d.lastFingerprint)return;let p=d.seq+1,f=oe(),g=d.lastSnapshot==null||p%d.compactEvery===0?{name:this.name,mode:"full",snapshot:c,seq:p,timestamp_ns:f,format_version:ft}:{name:this.name,mode:"diff",diff:fs(d.lastSnapshot,c),seq:p,timestamp_ns:f,format_version:ft};if(d.tier.filter&&!d.tier.filter(g))return;let y;try{y=d.tier.save(g)}catch(b){n.onError?.(b,d.tier);return}if(y&&typeof y.then=="function"){let T=(d.savePending??Promise.resolve()).then(()=>y,()=>y).then(()=>{d.disposed||(d.seq=p,d.lastSnapshot=c,d.lastFingerprint=l)},w=>{n.onError?.(w,d.tier)});d.savePending=T.finally(()=>{d.savePending===T&&(d.savePending=void 0)})}else d.seq=p,d.lastSnapshot=c,d.lastFingerprint=l},s=(d,c)=>{try{o(d,c)}catch(l){n.onError?.(l,d.tier)}},i=(d,c)=>{if(!c.some(m=>{let h=this.config.messageTier(m[0]);return h>=3&&h<5}))return;if(n.filter){let m=this.tryResolve(d);if(m==null)return;let h=Dr(m,At("standard"));if(!n.filter(d,h))return}let p,f=()=>(p==null&&(p=this.snapshot()),p);for(let m of r)m.disposed||(m.debounceMs===0?s(m,f()):(m.timer==null&&(m.timer=new Le),m.timer.start(m.debounceMs,()=>{m.disposed||s(m,this.snapshot())})))},a;if(n.paths!=null){let c=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(l=>{let p=this.tryResolve(l);return p==null?()=>{}:p.subscribe(f=>i(l,f))});a=()=>{for(let l of c)l()}}else a=this.observe().subscribe((d,c)=>i(d,c));let u=()=>{a();for(let d of r)d.disposed=!0,d.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?.()}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===ft&&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?.()}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===ft&&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:H(),...r?.actor!=null?{actor:r.actor}:{}};this._traceRing.push(o)}return}return e!=null?this.config.inspectorEnabled?this._annotations.get(e):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(e){return this._annotations.get(e)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(e){let n=this._traceRing.toArray().filter(o=>!e(o)),r=this._traceRing.size-n.length;this._traceRing.clear();for(let o of n)this._traceRing.push(o);return r}static diff(e,n){let r=new Set(Object.keys(e.nodes)),o=new Set(Object.keys(n.nodes)),s=[...o].filter(b=>!r.has(b)).sort(),i=[...r].filter(b=>!o.has(b)).sort(),a=[],u=[];for(let b of r){if(!o.has(b))continue;let v=e.nodes[b],T=n.nodes[b],w=v.v,k=T.v;w!=null&&k!=null&&w.id===k.id&&w.version!==k.version&&u.push({path:b,id:w.id,from:w.version,to:k.version});let x=w!=null&&k!=null&&w.id===k.id&&w.version===k.version;for(let S of["type","status","sentinel"]){let R=v[S],N=T[S];R!==N&&a.push({path:b,field:S,from:R,to:N})}if(!x)for(let S of["value","meta"]){let R=v[S],N=T[S];Xm(R,N)||a.push({path:b,field:S,from:R,to:N})}}let d=b=>`${b.from} ${b.to}`,c=new Set(e.edges.map(d)),l=new Set(n.edges.map(d)),p=n.edges.filter(b=>!c.has(d(b))),f=e.edges.filter(b=>!l.has(d(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:p,edgesRemoved:f,subgraphsAdded:g,subgraphsRemoved:y}}};function fs(t,e){let n=Y.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 fn(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,d=new Map,c=new Set;for(let[v,T]of Object.entries(t.nodes)){if(!v)continue;c.add(v);let w=T.deps??[];i.set(v,w);for(let k of w)k&&(c.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||(c.add(T),c.add(w),d.has(T)||d.set(T,new Set),d.get(T).add(w),u.has(w)||u.set(w,new Set),u.get(w).add(T))}if(!c.has(e))return r.withDetail?o:[];let l=r.both===!0,p=v=>{if(l){let x=i.get(v)??[],S=u.get(v),R=a.get(v),N=d.get(v),_=[...x];return S&&_.push(...S),R&&_.push(...R),N&&_.push(...N),_}if(n==="upstream"){let x=i.get(v)??[],S=u.get(v);return S?[...x,...S]:x}let T=a.get(v),w=d.get(v),k=T?[...T]:[];return w&&k.push(...w),k},f=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){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),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 fg(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 Ts={};ke(Ts,{CqrsGraph:()=>vs,cqrs:()=>Ra,cqrsEventKeyOf:()=>vg,dispatchKeyOf:()=>Tg,sagaInvocationKeyOf:()=>wg});Me();xe();$t();var va={};ke(va,{COMPLETE:()=>L,COMPLETE_MSG:()=>Oo,COMPLETE_ONLY_BATCH:()=>br,DATA:()=>E,DEFAULT_ACTOR:()=>bt,DIRTY:()=>ne,DIRTY_MSG:()=>Et,DIRTY_ONLY_BATCH:()=>Mn,ERROR:()=>A,GraphReFlyConfig:()=>nn,GuardDenied:()=>rt,INVALIDATE:()=>Je,INVALIDATE_MSG:()=>Mo,INVALIDATE_ONLY_BATCH:()=>yr,NodeImpl:()=>Ce,PAUSE:()=>Be,RESOLVED:()=>V,RESOLVED_MSG:()=>Nn,RESOLVED_ONLY_BATCH:()=>hr,RESUME:()=>qe,START:()=>dt,START_MSG:()=>_n,TEARDOWN:()=>de,TEARDOWN_MSG:()=>Ao,TEARDOWN_ONLY_BATCH:()=>On,accessHintForGuard:()=>_r,advanceVersion:()=>Mr,autoTrackNode:()=>rn,batch:()=>X,configure:()=>ra,createVersioning:()=>In,defaultConfig:()=>$e,defaultHash:()=>jt,derived:()=>C,downWithBatch:()=>_t,dynamicNode:()=>Or,effect:()=>pe,isBatching:()=>tn,isV1:()=>ea,monotonicNs:()=>H,node:()=>z,normalizeActor:()=>Nt,pipe:()=>oa,policy:()=>Mt,policyFromRules:()=>Nr,producer:()=>K,registerBuiltins:()=>Er,resolveDescribeFields:()=>At,state:()=>M,wallClockNs:()=>oe});kr();Me();xe();Xi();$t();ae();_e();ee();Io();Me();ae();_e();ee();he();var jr=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}snapshot(){return this.toArray()}restore(e){if(this._maxSize===void 0){this._buf.length=0;for(let n=0;n<e.length;n++)this._buf.push(e[n]);this._size=this._buf.length}else{let n=this._maxSize;for(let s=0;s<n;s++)this._buf[s]=void 0;this._head=0;let r=Math.min(e.length,n),o=e.length-r;for(let s=0;s<r;s++)this._buf[s]=e[o+s];this._size=r}this._version+=1}_rawAppend(e){if(this._maxSize===void 0){this._buf.push(e),this._size=this._buf.length;return}this._size<this._maxSize?(this._buf[(this._head+this._size)%this._maxSize]=e,this._size+=1):(this._buf[this._head]=e,this._head=(this._head+1)%this._maxSize)}};function $r(t){return t.subscribe(()=>{})}var mg=64;function Ve(t,e={}){let{name:n,maxSize:r,versioning:o,guard:s,backend:i}=e,a=i??new jr(t,r),u=M(a.toArray(),{name:n,describeKind:"state",equals:(x,S)=>x===S,...o!=null?{versioning:o}:{},...s!=null?{guard:s}:{}});function d(){let x=a.toArray();X(()=>{u.down([[ne]],{internal:!0}),u.down([[E,x]],{internal:!0})})}let c=new Map,l=new Map,p=new Map;function f(x,S){return`${x}:${S===void 0?"END":S}`}function m(x){if(x.size<mg)return;let S=x.keys().next();if(S.done)return;let R=x.get(S.value);R!==void 0&&R.dispose(),x.delete(S.value)}function h(x){let S=a.version;try{return x()}finally{a.version!==S&&d()}}function g(x){if(!Number.isInteger(x)||x<0)throw new RangeError(`tail: n must be a non-negative integer (got ${x})`);let S=c.get(x);if(S!==void 0)return c.delete(x),c.set(x,S),S.node;m(c);let R=C([u],([_])=>{let I=_;return x===0||I.length===0?[]:I.slice(Math.max(0,I.length-x))},{initial:a.tail(x),describeKind:"derived"}),N=$r(R);return c.set(x,{node:R,dispose:N}),R}function y(x,S){if(!Number.isInteger(x)||x<0)throw new RangeError(`slice: start must be a non-negative integer (got ${x})`);if(S!==void 0&&(!Number.isInteger(S)||S<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${S})`);let R=f(x,S),N=l.get(R);if(N!==void 0)return l.delete(R),l.set(R,N),N.node;m(l);let _=C([u],([O])=>{let P=O;return S===void 0?P.slice(x):P.slice(x,S)},{initial:a.slice(x,S),describeKind:"derived"}),I=$r(_);return l.set(R,{node:_,dispose:I}),_}function b(x){let S=p.get(x);if(S!==void 0)return S.node;let R=C([u,x],([_,I])=>{let O=_,P=Math.max(0,Math.trunc(I??0));return O.slice(P)},{initial:[],describeKind:"derived"}),N=$r(R);return p.set(x,{node:R,dispose:N}),R}let v,T;function w(){v===void 0&&(v=z([u],(x,S,R)=>{let N=x[0],I=N!=null&&N.length>0?N.at(-1):R.prevData[0];if(I==null||I.length===0){S.down([[V]]);return}S.emit(I[I.length-1])},{name:n!=null?`${n}::lastValue`:"lastValue",describeKind:"derived",initial:a.size===0?void 0:a.at(a.size-1)}),T=C([u],([x])=>x.length>0,{name:n!=null?`${n}::hasLatest`:"hasLatest",describeKind:"derived",initial:a.size>0}),$r(v),$r(T))}let k={entries:u,get size(){return a.size},at(x){return a.at(x)},append(x){h(()=>a.append(x))},appendMany(x){x.length!==0&&h(()=>a.appendMany(x))},clear(){h(()=>a.clear())},trimHead(x){h(()=>a.trimHead(x))},withLatest(){return w(),u},get lastValue(){return w(),v},get hasLatest(){return w(),T},view(x){switch(x.kind){case"tail":return g(x.n);case"slice":return y(x.start,x.stop);case"fromCursor":return b(x.cursor)}},attach(x){let S=x.subscribe(R=>{for(let N of R)N[0]===E&&k.append(N[1])});return()=>S()},attachStorage(x){if(x.length===0)return()=>{};let S=new Map;for(let N of x)S.set(N,a.size);(async()=>{for(let N of x)if(typeof N.loadEntries=="function")try{let _=await Promise.resolve(N.loadEntries());_.entries.length>0&&a.size===0&&(a.restore(_.entries),S.set(N,_.entries.length),d());break}catch{}})();let R=u.subscribe(N=>{for(let _ of N){if(_[0]!==E)continue;let I=_[1];for(let O of x){let P=S.get(O)??0;if(I.length<P){try{let j=O.appendEntries(I);j instanceof Promise&&j.catch(()=>{})}catch{}S.set(O,I.length);continue}if(I.length===P)continue;let B=I.slice(P);S.set(O,I.length);try{let j=O.appendEntries(B);j instanceof Promise&&j.catch(()=>{})}catch{}}}});return()=>R()},disposeAllViews(){for(let x of c.values())x.dispose();c.clear();for(let x of l.values())x.dispose();l.clear();for(let x of p.values())x.dispose();p.clear()},dispose(){for(let x of c.values())x.dispose();c.clear();for(let x of l.values())x.dispose();l.clear();for(let x of p.values())x.dispose();p.clear()}};return k}var Ta=new WeakMap;function vc(t){let e=Ta.get(t);if(e)return e;let n=t.map(c=>c.cache??[]),r=n.flat(),o=M(r,{name:"mergeReactiveLogs",describeKind:"state",equals:(c,l)=>c===l}),s=t.map((c,l)=>[...n[l]??[]]),i=[];for(let c=0;c<t.length;c++){let l=c,p=t[l].subscribe(f=>{for(let m of f)if(m[0]===E)s[l]=[...m[1]],o.emit(s.flat());else if(m[0]===L){s[l]=[];let h=i[l];h!==void 0&&(i[l]=void 0,h())}else m[0]===A&&o.down([[A,m[1]]])});i.push(p)}let a=re(o),u=!1,d={node:o,dispose(){if(!u){u=!0;for(let c of i)c?.();i.length=0,a(),Ta.delete(t)}}};return Ta.set(t,d),d}var ka={};ke(ka,{ENVELOPE_VERSION:()=>An,GRAPH_META_SEGMENT:()=>Qe,Graph:()=>Y,JsonCodec:()=>Co,SIZEOF_OVERHEAD:()=>je,SIZEOF_SYMBOL:()=>ds,SNAPSHOT_VERSION:()=>ft,createDagCborCodec:()=>Ji,createDagCborZstdCodec:()=>Yi,decodeEnvelope:()=>Tr,diffForWAL:()=>fs,encodeEnvelope:()=>vr,explainPath:()=>Gr,graphProfile:()=>pn,mermaidLiveUrl:()=>ps,reachable:()=>fn,registerBuiltinCodecs:()=>wr,replayWAL:()=>Qi,sizeof:()=>Fr,validateGraphObservability:()=>wa,watchTopologyTree:()=>Ct});Lo();ae();function Ct(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 d of u){if(d[0]!==E)continue;let c=d[1];if(e(c,o,s),c.kind==="added"&&c.nodeKind==="mount"){let l=o._mounts.get(c.name);if(l instanceof Y){let p=`${s}${c.name}::`;r(l,p)}}else if(c.kind==="removed"&&c.nodeKind==="mount"){let l=`${s}${c.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,d]of o._mounts)if(d instanceof Y){let c=`${s}${u}::`;r(d,c)}};return r(t,""),()=>{for(let o of n.values())o.off();n.clear()}}function wa(t,e={}){let n=[],r=e.requireFound??!0;if(e.skipDescribe!==!0)try{let d=t.describe(),c=new Set(Object.keys(d.nodes)),l=[];for(let[p,f]of Object.entries(d.nodes))for(let m of f.deps)m!==""&&!c.has(m)&&l.push(`${p} \u2192 ${m}`);for(let p of d.edges)c.has(p.from)||l.push(`edge.from: ${p.from}`),c.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:c.size,edgeCount:d.edges.length})}catch(d){n.push({kind:"describe",ok:!1,reason:`describe() threw: ${d instanceof Error?d.message:String(d)}`})}for(let d of e.formats??[])try{let c=t.describe({format:d});typeof c!="string"||c.length===0?n.push({kind:"describe-format",ok:!1,format:d,reason:`describe({ format: "${d}" }) returned empty or non-string output`}):n.push({kind:"describe-format",ok:!0,format:d,length:c.length})}catch(c){n.push({kind:"describe-format",ok:!1,format:d,reason:c instanceof Error?c.message:String(c)})}for(let d of e.paths??[])try{t.resolve(d),n.push({kind:"observe",ok:!0,path:d})}catch(c){n.push({kind:"observe",ok:!1,path:d,reason:c instanceof Error?c.message:String(c)})}for(let[d,c]of e.pairs??[])try{let l=t.explain(d,c);r&&l.found===!1?n.push({kind:"explain",ok:!1,from:d,to:c,reason:`explain(${d} \u2192 ${c}) found no path${l.reason?`: ${l.reason}`:""}`}):n.push({kind:"explain",ok:!0,from:d,to:c,found:l.found,steps:l.steps.length})}catch(l){n.push({kind:"explain",ok:!1,from:d,to:c,reason:l instanceof Error?l.message:String(l)})}let o=n.filter(d=>!d.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 d=[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),c=d.length>0?d.join(", "):"describe-only";return s?`validateGraphObservability: OK (${c})`:`validateGraphObservability: ${o.length} failure(s) across ${c}`}}}var Wt=class extends Error{constructor(e,n){super(e,n),this.name=this.constructor.name}},ms=class extends Wt{constructor(n,r){super(`Duplicate ${n} registration: "${r}"`);this.kind=n;this.registrationName=r}},gs=class extends Wt{constructor(n,r,o){super(`Command "${n}" emitted undeclared event "${r}". Declared emits: [${o.join(", ")}]`);this.commandName=n;this.eventName=r;this.declaredEmits=o}},hs=class extends Wt{constructor(n,r,o){super(`Optimistic concurrency conflict on aggregate "${n}": expected version ${r}, got ${o}`);this.aggregateId=n;this.expected=r;this.actual=o}},ys=class extends Wt{constructor(n){super(`Unknown command: "${n}". Register with command() first.`);this.commandName=n}},Br=class extends Wt{constructor(n,r){super(`Command handler "${n}" threw: ${r instanceof Error?r.message:String(r)}`,{cause:r});this.commandName=n}};var Vr=class extends Wt{constructor(n,r){super(`Projection "${n}" rebuild failed: ${r instanceof Error?r.message:String(r)}`,{cause:r});this.projectionName=n}};Me();xe();$t();ae();ee();var gg=Mt((t,e)=>{t("observe"),t("signal"),e("write")});function kt(t){let e=Ve([],{name:t.name,maxSize:t.retainedLimit??1024,guard:t.guard??gg,...t.versioning!=null?{versioning:t.versioning}:{}});return e.withLatest(),t.graph&&t.graph.add(e.entries,{name:t.name}),e}function wc(t){if(t===null||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.keys(t))wc(t[e]);return Object.freeze(t)}function hg(t){let e=t.cache,r=(typeof e=="number"&&Number.isFinite(e)?e:0)+1;return t.down([[ne],[E,r]]),r}function Tc(t,e,n,r,o,s){let i=e(n,r,o);if(i===void 0)return;let a=s!=null?{...i,handlerVersion:s}:i;t.append(a)}function Yn(t,e){let n=e.freeze??!0;return function(...o){let s=n?o.map(wc):o,i=oe(),a,u,d=!1,c;try{X(()=>{e.seq&&(c=hg(e.seq));try{a=t(...s),e.onSuccess&&Tc(e.audit,e.onSuccess,s,a,{t_ns:i,seq:c},e.handlerVersion)}catch(l){throw u=l,d=!0,l}})}catch(l){if(d&&e.onFailure){let p=u instanceof Error?u.name:typeof u;Tc(e.audit,e.onFailure,s,u,{t_ns:i,seq:c,errorType:p},e.handlerVersion)}throw d?u:l}return a}}function bs(t,e,n=0){let r=M(n,{name:e,describeKind:"state"});return t.add(r,{name:e}),r}function kc(t,e,n,r=0){let o={},s=new Y(e);for(let i of n){let a=M(r,{name:i,describeKind:"state"});s.add(a,{name:i}),o[i]=a}return t.mount(e,s),o}Me();ae();_e();he();function mt(t,e){t!=null&&_t(n=>t.down(n),[[E,e]],$e.tierOf)}function Kr(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[ne],[E,n+1]]),!0)}function ze(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}function qr(t){return t.relatedTo?.[0]??t.summary}var yg=Mt((t,e)=>{t("write"),t("signal"),e("observe")}),bg=Mt((t,e)=>{t("observe"),t("signal"),e("write")}),xc=Mt((t,e)=>{t("observe"),t("signal"),e("write")});function Hr(t,e){return ze("cqrs",t,e)}function xa(t){if(t===null||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.keys(t))xa(t[e]);return Object.freeze(t)}var vg=t=>`${t.type}::${t.aggregateId??"__default__"}`,Tg=t=>t.commandName,wg=t=>t.eventType,vs=class extends Y{_eventLogs=new Map;_eventLogsByAggregate=new Map;_aggregateVersions=new Map;_aggregateLru=new Map;_commandRegs=new Map;_projections=new Set;_sagas=new Set;_keepaliveDisposers=[];_seq=0;_retainedLimit;_freezeCommandPayload;_freezeEventPayload;_maxAggregates;_dispatchSeqCursor;dispatches;audit;aggregateEvictions;constructor(e,n={}){super(e,n.graph),this._retainedLimit=n.retainedLimit??1024,this._freezeCommandPayload=n.freezeCommandPayload??!0,this._freezeEventPayload=n.freezeEventPayload??!0,this._maxAggregates=n.maxAggregates??1e4,this.dispatches=kt({name:"dispatches",retainedLimit:this._retainedLimit,graph:this}),this.audit=this.dispatches,this.aggregateEvictions=kt({name:"aggregateEvictions",retainedLimit:this._retainedLimit,graph:this}),this._dispatchSeqCursor=bs(this,"dispatch_seq",0)}aggregateVersion(e,n){return this._aggregateVersions.get(`${e}::${n}`)??0}_touchAggregate(e){this._aggregateLru.delete(e),this._aggregateLru.set(e,!0)}_enforceAggregateLru(){for(;this._aggregateLru.size>this._maxAggregates;){let e=this._aggregateLru.keys().next();if(e.done)break;let n=e.value;this._aggregateLru.delete(n);let r=n.indexOf("::");if(r<0)continue;let o=n.slice(0,r),s=n.slice(r+2),i=this._aggregateVersions.get(n)??0;this._aggregateVersions.delete(n);let a=this._eventLogsByAggregate.get(o);a&&(a.delete(s),a.size===0&&this._eventLogsByAggregate.delete(o)),this.aggregateEvictions.append({aggregateId:s,type:o,lastVersion:i,t_ns:oe()})}}destroy(){for(let e of this._keepaliveDisposers)e();this._keepaliveDisposers.length=0,super.destroy()}_attachedEventTiers=[];_attachedTierDisposers=new Map;attachEventStorage(e){this._attachedEventTiers.push(e);for(let[n,r]of this._eventLogs){let o=r.log.attachStorage(e),s=this._attachedTierDisposers.get(n);s||(s=[],this._attachedTierDisposers.set(n,s)),s.push(o)}for(let[n,r]of this._eventLogsByAggregate)for(let[o,s]of r){let i=`${n}::${o}`,a=s.log.attachStorage(e),u=this._attachedTierDisposers.get(i);u||(u=[],this._attachedTierDisposers.set(i,u)),u.push(a)}return()=>{let n=this._attachedEventTiers.indexOf(e);n>=0&&this._attachedEventTiers.splice(n,1)}}_autoWireStreamStorage(e,n){if(this._attachedEventTiers.length===0)return;let r=this._attachedTierDisposers.get(e);r||(r=[],this._attachedTierDisposers.set(e,r));for(let o of this._attachedEventTiers)r.push(n.attachStorage(o))}_bumpDispatchSeq(){let n=(this._dispatchSeqCursor.cache??0)+1;return this._dispatchSeqCursor.emit(n),n}event(e,n){if(n!==void 0)return this._ensureAggregateStream(e,n).node;let r=this._eventLogs.get(e);if(r)return r.node;let o=Ve([],{name:e,versioning:0,maxSize:this._retainedLimit});o.withLatest();let s=o.entries,i=C([s],([a])=>a,{name:e,describeKind:"state",meta:Hr("event",{event_name:e}),guard:xc,initial:s.cache});return this.add(i,{name:e}),this._keepaliveDisposers.push(re(i)),this._eventLogs.set(e,{log:o,node:i}),this._autoWireStreamStorage(e,o),i}_ensureAggregateStream(e,n){this._eventLogs.has(e)||this.event(e);let r=this._eventLogsByAggregate.get(e);r||(r=new Map,this._eventLogsByAggregate.set(e,r));let o=`${e}::${n}`;this._touchAggregate(o);let s=r.get(n);if(s)return s;let i=`${e}_${n.replace(/[^a-zA-Z0-9_-]/g,"_")}`,a=Ve([],{name:i,versioning:0,maxSize:this._retainedLimit});a.withLatest();let u=a.entries,d=C([u],([f])=>f,{name:i,describeKind:"state",meta:Hr("event_aggregate",{event_name:e,aggregate_id:n}),guard:xc,initial:u.cache}),c=i,l=0;for(;this.nameOf(this.resolveOptional(c)??d)===c&&(l+=1,c=`${i}_${l}`,this.resolveOptional(c)!==void 0););try{this.add(d,{name:c})}catch{}this._keepaliveDisposers.push(re(d));let p={log:a,node:d};return r.set(n,p),this._autoWireStreamStorage(`${e}::${n}`,a),this._enforceAggregateLru(),p}resolveOptional(e){try{return this.resolve(e)}catch{return}}_appendEvent(e,n,r){let o=this._eventLogs.get(e);if(o||(this.event(e),o=this._eventLogs.get(e)),o.node.status==="completed"||o.node.status==="errored")throw new Error(`Cannot dispatch to terminated event stream "${e}" (status: ${o.node.status}).`);let s,i;if(r?.aggregateId!==void 0){let c=`${e}::${r.aggregateId}`;s=(this._aggregateVersions.get(c)??0)+1,this._aggregateVersions.set(c,s),i=this._ensureAggregateStream(e,r.aggregateId)}let a=o.log.entries.v,u=this._freezeEventPayload?xa(n):n,d={type:e,payload:u,timestampNs:oe(),seq:++this._seq,...r?.aggregateId!==void 0?{aggregateId:r.aggregateId}:{},...s!==void 0?{aggregateVersion:s}:{},...r?.correlationId!==void 0?{correlationId:r.correlationId}:{},...r?.causationId!==void 0?{causationId:r.causationId}:{},...r?.metadata!==void 0?{metadata:Object.freeze({...r.metadata})}:{},...r?.handlerVersion!==void 0?{handlerVersion:r.handlerVersion}:{},...a!=null?{v0:{id:a.id,version:a.version}}:{}};return o.log.append(d),i&&i.log.append(d),d}command(e,n){if(this._commandRegs.has(e))throw new ms("command",e);let r=typeof n=="function"?{handler:n}:n,o=M(void 0,{name:e,describeKind:"state",meta:{...Hr("command",{command_name:e}),error:null},guard:yg});if(this.add(o,{name:e}),this._commandRegs.set(e,{handler:r.handler,...r.emits!==void 0?{emits:r.emits}:{},...r.handlerVersion!==void 0?{handlerVersion:r.handlerVersion}:{}}),r.emits)for(let s of r.emits)this._eventLogs.has(s)||this.event(s);return o}dispatch(e,n,r){let o=this._commandRegs.get(e);if(!o)throw new ys(e);if(r?.aggregateId!==void 0&&r.expectedAggregateVersion!==void 0&&o.emits!==void 0){let p=0;for(let f of o.emits){let m=this._aggregateVersions.get(`${f}::${r.aggregateId}`);m!==void 0&&m>p&&(p=m)}if(p!==r.expectedAggregateVersion)throw new hs(r.aggregateId,r.expectedAggregateVersion,p)}let s=this.resolve(e),i=this._freezeCommandPayload?xa(n):n,a=[],u=oe(),d=0,c,l=!1;try{X(()=>{d=this._bumpDispatchSeq(),s.emit(i,{internal:!0});try{o.handler(i,{emit:(p,f)=>{if(o.emits!==void 0&&!o.emits.includes(p))throw new gs(e,p,o.emits);a.push(p),this._appendEvent(p,f,{...r?.aggregateId!==void 0?{aggregateId:r.aggregateId}:{},...r?.correlationId!==void 0?{correlationId:r.correlationId}:{},...r?.causationId!==void 0?{causationId:r.causationId}:{},...r?.metadata!==void 0?{metadata:Object.freeze({...r.metadata})}:{},...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}})}}),s.meta.error.emit(null,{internal:!0}),this.dispatches.append({commandName:e,payload:i,status:"success",emittedEvents:[...a],t_ns:u,seq:d,...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}})}catch(p){throw c=p,l=!0,p}})}catch(p){if(l){s.meta.error.emit(c,{internal:!0});let f=c instanceof Error?c.name:typeof c,m=c instanceof Br?c:new Br(e,c);this.dispatches.append({commandName:e,payload:i,status:"failed",error:m,errorType:f,emittedEvents:[...a],t_ns:u,seq:d,...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}})}throw l?c:p}}projection(e){let{name:n,events:r,reducer:o,initial:s}=e,i=e.mode??"scan",a=e.freezeInputs??!0,u=e.snapshot,d=r.map(N=>(this._eventLogs.has(N)||this.event(N),this._eventLogs.get(N).node));function c(N){N.sort((_,I)=>_.timestampNs-I.timestampNs||_.seq-I.seq||(_.aggregateId??"").localeCompare(I.aggregateId??""))}function l(N){let _=[];for(let I of N)_.push(...I);return c(_),_}let p=d.map(N=>N.cache??[]),f=l(p),m=a?Object.freeze(f):f,h=0,g=s;i==="scan"&&f.length>0&&(g=o(s,m),h=f.length);let y=i==="replay"?o(s,m):g,b=u?.saveDebounceMs??1e3,v=u?.saveEvery??1e3,T,w=0;function k(N){if(u?.save){if(w+=1,w>=v){w=0,T!==void 0&&(clearTimeout(T),T=void 0);let _=u.save(N);_ instanceof Promise&&_.catch(()=>{});return}T!==void 0&&clearTimeout(T),T=setTimeout(()=>{T=void 0,w=0;let _=u.save(N);_ instanceof Promise&&_.catch(()=>{})},b)}}let x=C(d,N=>{let _=l(N),I;if(i==="replay"){let O=a?Object.freeze(_):_;I=o(s,O)}else{let O=_.slice(h);h=_.length;let P=a?Object.freeze(O):O;I=o(g,P),g=I}return k(I),I},{name:n,describeKind:"derived",meta:Hr("projection",{projection_name:n,source_events:r}),guard:bg,initial:y});return this.add(x,{name:n}),this._keepaliveDisposers.push(re(x)),this._keepaliveDisposers.push(()=>{T!==void 0&&(clearTimeout(T),T=void 0)}),this._projections.add(n),{node:x,rebuild:async N=>{try{let _=N?.pageSize??1e3,I=N?.fromTier??this._attachedEventTiers[0]?.[0],O=l(d.map(B=>B.cache??[])).length,P=s;if(u?.load){let B=await u.load();B!==void 0&&(P=B)}if(!I||!I.loadEntries){let B=l(d.map(D=>D.cache??[])),j=a?Object.freeze(B):B;P=o(P,j)}else{let B=new Set(r),j,D=!1;for(;!D;){let Z=await I.loadEntries({cursor:j,pageSize:_}),F=[...Z.entries].filter(G=>B.has(G.type));c(F);let Q=a?Object.freeze(F):F;P=o(P,Q),j=Z.cursor,D=!j||Z.entries.length===0}}if(i==="scan"){let B=l(d.map(D=>D.cache??[])),j=B.slice(O);if(j.length>0){let D=a?Object.freeze(j):j;P=o(P,D)}g=P,h=B.length}return x.emit(P,{internal:!0}),P}catch(_){throw new Vr(n,_)}},reset:async()=>{try{let N=s;if(u?.load){let P=await u.load();P!==void 0&&(N=P)}let _=l(d.map(P=>P.cache??[])),I=a?Object.freeze(_):_,O=o(N,I);return i==="scan"&&(g=O,h=_.length),x.emit(O,{internal:!0}),O}catch(N){throw new Vr(n,N)}}}}saga(e,n,r,o={}){let s=n.map(f=>(this._eventLogs.has(f)||this.event(f),this._eventLogs.get(f).node)),i=kc(this,`${e}_cursor`,n,0),a=kt({name:`${e}_invocations`,retainedLimit:this._retainedLimit,graph:this}),u=o.aggregateId,d=o.errorPolicy??"advance",c=new Map;for(let f of n){let m=i[f];c.set(f,m.cache??0);let h=m.subscribe(g=>{for(let y of g)y[0]===E&&c.set(f,y[1])});this._keepaliveDisposers.push(h)}let l={},p=z(s,(f,m)=>{let h=l.n.meta.error;for(let g=0;g<f.length;g++){let y=f[g];if(y==null||y.length===0)continue;let b=y.at(-1);if(!b)continue;let v=n[g],T=i[v],w=c.get(v)??0;if(b.length>w){let k=b.slice(w),x=w;for(let S of k){let R=S;if(u!==void 0&&R.aggregateId!==u){x+=1;continue}try{r(R),h.emit(null,{internal:!0}),a.append({eventType:v,status:"success",aggregateId:R.aggregateId,event:R,t_ns:oe(),...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}}),x+=1}catch(N){if(h.emit(N,{internal:!0}),a.append({eventType:v,status:"failed",error:N,errorType:N instanceof Error?N.name:typeof N,aggregateId:R.aggregateId,event:R,t_ns:oe(),...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}}),d==="hold")break;x+=1}}T.emit(x)}}},{name:e,describeKind:"effect",meta:{...Hr("saga",{saga_name:e,source_events:n}),error:null}});return l.n=p,this.add(p,{name:e}),this._keepaliveDisposers.push(re(p)),this._sagas.add(e),{node:p,invocations:a,audit:a,cursors:i}}};function Ra(t,e){return new vs(t,e)}var Ea=class{constructor(e){this.graph=e}onModuleDestroy(){this.graph.destroy()}},Na=class{graph=new Y("request");onModuleDestroy(){this.graph.destroy()}},Rc,Sa;Rc=[(0,Wr.Module)({})];var zt=class zt{static forRoot(e){let n=e??{},r=n.name??"root",o=[{provide:ct,useFactory:()=>{let s=new Y(r);return n.build&&n.build(s),n.snapshot&&s.restore(n.snapshot),s}},{provide:Symbol.for("graphrefly:root-lifecycle"),useFactory:s=>new Ea(s),inject:[ct]},{provide:cn,useFactory:(s,i)=>new cn(s,i),inject:[ct,Sc.ModuleRef]}];if(n.nodes)for(let s of n.nodes)o.push({provide:lt(s),useFactory:i=>i.resolve(s),inject:[ct]});return n.requestScope&&o.push({provide:Symbol.for("graphrefly:request-lifecycle"),useFactory:()=>new Na,scope:Wr.Scope.REQUEST},{provide:on,useFactory:s=>s.graph,inject:[Symbol.for("graphrefly:request-lifecycle")],scope:Wr.Scope.REQUEST}),{module:zt,global:!0,providers:o,exports:[ct,...(n.nodes??[]).map(lt),...n.requestScope?[on]:[]]}}static forFeature(e){let n=[{provide:ot(e.name),useFactory:r=>{let o=new Y(e.name);return e.build&&e.build(o),e.snapshot&&o.restore(e.snapshot),r.mount(e.name,o),o},inject:[ct]}];if(e.nodes)for(let r of e.nodes)n.push({provide:lt(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[ot(e.name)]});return{module:zt,providers:n,exports:[ot(e.name),...(e.nodes??[]).map(r=>lt(`${e.name}::${r}`))]}}static forCqrs(e){let n=[{provide:ot(e.name),useFactory:r=>{let o=Ra(e.name,e.cqrs);return e.eventStorage&&o.attachEventStorage(e.eventStorage),e.build&&e.build(o),r.mount(e.name,o),o},inject:[ct]}];if(e.nodes)for(let r of e.nodes)n.push({provide:lt(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[ot(e.name)]});return{module:zt,providers:n,exports:[ot(e.name),...(e.nodes??[]).map(r=>lt(`${e.name}::${r}`))]}}};Sa=rd(null),zt=id(Sa,0,"GraphReflyModule",Rc,zt),sd(Sa,1,zt);var ws=zt;var xs={};ke(xs,{useStore:()=>kg,useSubscribe:()=>Ec,useSubscribeRecord:()=>xg});var Lt=require("react");ae();function Ec(t){return(0,Lt.useSyncExternalStore)(e=>{let n=!1,r=t.subscribe(()=>{n||e()});return()=>{n=!0,r()}},()=>t.cache,()=>t.cache)}function kg(t){let e=Ec(t),n=(0,Lt.useCallback)(r=>{t.down([[ne],[E,r]])},[t]);return[e,n]}function xg(t,e){let n=(0,Lt.useRef)(e);n.current=e;let r=(0,Lt.useMemo)(()=>{let o=()=>{let i={},a=t.cache??[];for(let u of a){let d=n.current(u),c={};for(let l of Object.keys(d))c[l]=d[l].cache;i[u]=c}return i},s=o();return{subscribe:i=>{let a=!1,u=[],d=()=>{for(let p of u)p();u=[]},c=p=>{d();for(let f of p){let m=n.current(f);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(p=>{let f=p.some(m=>m[0]===E||m[0]===V);!a&&f&&c(t.cache??[])});return c(t.cache??[]),()=>{a=!0,l(),d()}},getSnapshot:()=>s}},[t]);return(0,Lt.useSyncExternalStore)(r.subscribe,r.getSnapshot,r.getSnapshot)}var Ss={};ke(Ss,{Signal:()=>Rg});Me();ae();ee();var Qn=[];function Rs(t){let e=t.cache;return t.subscribe(r=>{for(let[o,s]of r)o===E&&(e=s)})(),e}var _a=class{_node;_equals;constructor(e,n){this._equals=n?.equals??Object.is,this._node=M(e,{...n,resubscribable:!0,resetOnTeardown:!0})}get(){let e=Qn[Qn.length-1];return e?(this._node.status==="sentinel"&&Rs(this._node),e(this._node)):this._node.status==="sentinel"?Rs(this._node):this._node.cache}set(e){this._equals(this.get(),e)||X(()=>{this._node.down([[ne],[E,e]])})}},Ma=class{_node;constructor(e,n){this._node=rn(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"&&Rs(this._node),e(this._node)):this._node.status==="sentinel"?Rs(this._node):this._node.cache}},Rg={State:_a,Computed:Ma,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===E){if(r){r=!1;continue}n.data?.(i)}s===A&&n.error?.(i),s===L&&n.complete?.()}})}};var Es={};ke(Es,{useStore:()=>Sg,useSubscribe:()=>Nc,useSubscribeRecord:()=>Eg});var It=require("solid-js");ae();function Nc(t){let[e,n]=(0,It.createSignal)(t.cache,{equals:!1}),r=t.subscribe(()=>{n(()=>t.cache)});return(0,It.getOwner)()?(0,It.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 Sg(t){return[Nc(t),r=>{t.down([[ne],[E,r]])}]}function Eg(t,e){let[n,r]=(0,It.createSignal)({},{equals:!1}),o=[],s=()=>{for(let d of o)d();o=[]},i=()=>{let d={};for(let c of t.cache??[]){let l=e(c),p={};for(let f of Object.keys(l))p[f]=l[f].cache;d[c]=p}return d},a=d=>{s();for(let c of d){let l=e(c);for(let p of Object.keys(l)){let f=l[p].subscribe(()=>{r(()=>i())});o.push(f)}}r(()=>i())},u=t.subscribe(d=>{d.some(c=>c[0]===E||c[0]===V)&&a(t.cache??[])});return a(t.cache??[]),(0,It.getOwner)()?(0,It.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 Ns={};ke(Ns,{useStore:()=>_g,useSubscribe:()=>Ng,useSubscribeRecord:()=>Mg});ae();function Ng(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n}}}function _g(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n},set(e){t.down([[ne],[E,e]])},update(e){let n=e(t.cache);t.down([[ne],[E,n]])}}}function Mg(t,e){return{subscribe(n){let r=[],o=()=>{for(let u of r)u();r=[]},s=()=>{let u={};for(let d of t.cache??[]){let c=e(d),l={};for(let p of Object.keys(c))l[p]=c[p].cache;u[d]=l}return u},i=u=>{o();for(let d of u){let c=e(d);for(let l of Object.keys(c)){let p=c[l].subscribe(()=>{n(s())});r.push(p)}}n(s())},a=t.subscribe(u=>{u.some(d=>d[0]===E||d[0]===V)&&i(t.cache??[])});return i(t.cache??[]),()=>{a(),o()}}}}var _s={};ke(_s,{useStore:()=>Ag,useSubscribe:()=>Og,useSubscribeRecord:()=>Cg});var Ke=require("vue");ae();function Og(t){let e=(0,Ke.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,Ke.getCurrentScope)()?(0,Ke.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Ke.readonly)(e)}function Ag(t){let e=(0,Ke.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,Ke.getCurrentScope)()?(0,Ke.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useStore called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Ke.computed)({get:()=>e.value,set:r=>{t.down([[ne],[E,r]])}})}function Cg(t,e){let n=(0,Ke.shallowRef)({}),r=new Map;function o(){let a={};for(let[u,d]of r)a[u]={...d.values};n.value=a}function s(a){for(let d of r.values())for(let c of d.subs)c();r.clear();for(let d of a){let c=e(d),l=Object.keys(c),p={},f=[];for(let m of l){let h=c[m];p[m]=h.cache;let g=h.subscribe(()=>{p[m]=h.cache,o()});f.push(g)}r.set(d,{subs:f,values:p})}let u={};for(let[d,c]of r)u[d]={...c.values};n.value=u}return(0,Ke.watch)(()=>[...(typeof t=="function"?t():(0,Ke.isRef)(t)?t.value:t)??[]],a=>s(a??[]),{immediate:!0}),(0,Ke.getCurrentScope)()?(0,Ke.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,Ke.readonly)(n)}var Ms={};ke(Ms,{create:()=>Ig});ae();ee();var Lg=()=>!1;function Ig(t){let e=new Y("zustand"),n=M(void 0,{name:"state",equals:Lg});e.add(n,{name:"state"});let r=()=>n.cache,o=(a,u)=>{let d=n.cache,c=typeof a=="function"?a(d):a;n.emit(u?c:{...d,...c})},s={getState:r,setState:o,getInitialState:()=>i,subscribe:a=>{let u=!0,d=n.cache;return n.subscribe(c=>{for(let[l,p]of c)if(l===E){if(u){u=!1;continue}a(p,d),d=p}})},destroy:e.destroy.bind(e)},i=t(o,r,s);return n.emit(i),Object.assign(e,s)}var Wa={};ke(Wa,{CircuitOpenError:()=>pt,ContentAddressedMissError:()=>eo,NS_PER_MS:()=>He,NS_PER_SEC:()=>at,NativeIndexBackend:()=>ro,NativeListBackend:()=>oo,NativeLogBackend:()=>jr,NativeMapBackend:()=>Xr,NativePubSubBackend:()=>no,RateLimiterOverflowError:()=>an,ResettableTimer:()=>Le,TimeoutError:()=>un,appendLogStorage:()=>Ka,audit:()=>Jc,awaitSettled:()=>es,buffer:()=>Yc,bufferCount:()=>Qc,bufferTime:()=>Zc,cached:()=>Kd,canonicalJson:()=>to,cascadingCache:()=>ap,catchError:()=>dl,checkpointToRedis:()=>Zl,checkpointToS3:()=>Xl,circuitBreaker:()=>wt,combine:()=>Ca,combineLatest:()=>il,concat:()=>Vc,concatMap:()=>Hc,constant:()=>qo,contentAddressedStorage:()=>Ps,createTransport:()=>Jt,createWatermarkController:()=>Un,csvRows:()=>Il,debounce:()=>Ia,debounceTime:()=>al,decorrelatedJitter:()=>Uo,defer:()=>jd,delay:()=>zc,deserializeError:()=>yn,dictKv:()=>Tp,dictSnapshot:()=>wp,distill:()=>Ls,distinctUntilChanged:()=>$c,elementAt:()=>Dc,empty:()=>Gd,escapeRegexChar:()=>ca,exhaustMap:()=>qc,exponential:()=>Wo,externalBundle:()=>Os,externalProducer:()=>mn,fallback:()=>Hn,fibonacci:()=>zo,filter:()=>Xe,find:()=>Pc,first:()=>As,firstValueFrom:()=>Ye,firstWhere:()=>Yo,flatMap:()=>Wc,forEach:()=>qt,fromAny:()=>U,fromAsyncIter:()=>Ir,fromCSV:()=>Ll,fromClickHouseWatch:()=>Fl,fromCron:()=>Qo,fromDrizzle:()=>op,fromEvent:()=>Dd,fromHTTP:()=>$a,fromHTTPPoll:()=>vl,fromHTTPStream:()=>bl,fromIter:()=>Xo,fromKafka:()=>Ml,fromKysely:()=>sp,fromMCP:()=>kl,fromNATS:()=>Bl,fromNDJSON:()=>Gl,fromOTel:()=>xl,fromPrisma:()=>rp,fromPrometheus:()=>_l,fromPromise:()=>zn,fromPulsar:()=>$l,fromRabbitMQ:()=>Kl,fromRaf:()=>Pd,fromRedisStream:()=>Al,fromSSE:()=>yl,fromSqlite:()=>ep,fromSqliteCursor:()=>tp,fromStatsD:()=>El,fromSyslog:()=>Rl,fromTimer:()=>st,fromWebSocket:()=>Fa,fromWebSocketReconnect:()=>wl,fromWebhook:()=>cl,globToRegExp:()=>Ld,interval:()=>nl,jsonCodec:()=>tr,jsonCodecFor:()=>yp,keepalive:()=>re,kvStorage:()=>js,last:()=>Ic,linear:()=>Ho,lru:()=>Va,makeHttpError:()=>ht,map:()=>zr,matchesAnyPattern:()=>Id,matchesCron:()=>Ko,memoryAppendLog:()=>vp,memoryBackend:()=>io,memoryKv:()=>ao,memorySnapshot:()=>bp,merge:()=>xt,mergeMap:()=>La,mergeReactiveLogs:()=>vc,nameToSignal:()=>gn,ndjsonRows:()=>Pl,never:()=>Fd,nodeSignal:()=>ts,of:()=>la,onFirstData:()=>Jr,pairwise:()=>jc,parseCron:()=>Vo,parsePrometheusText:()=>ja,parseSSEStream:()=>Dt,parseStatsD:()=>Nl,parseSyslog:()=>Sl,pausable:()=>ol,pubsub:()=>pp,race:()=>Kc,rateLimiter:()=>qn,reactiveCounter:()=>pa,reactiveIndex:()=>gp,reactiveList:()=>Ds,reactiveLog:()=>Ve,reactiveMap:()=>Ze,reactiveSink:()=>We,reduce:()=>Ac,repeat:()=>rl,replay:()=>Zo,rescue:()=>Yr,resolveBackoffPreset:()=>Bt,retry:()=>Tt,sample:()=>Uc,scan:()=>Oc,serializeError:()=>hn,share:()=>Vd,shareReplay:()=>qd,signalToName:()=>Ut,singleFromAny:()=>Gs,singleNodeFromAny:()=>hp,skip:()=>Aa,snapshotStorage:()=>$s,sortJsonValue:()=>so,stableJsonString:()=>Fs,stratify:()=>uo,switchMap:()=>Te,take:()=>Ur,takeUntil:()=>Lc,takeWhile:()=>Cc,tap:()=>Gc,tapFirst:()=>Fc,throttle:()=>Pa,throttleTime:()=>ul,throwError:()=>$d,timeout:()=>Wn,toArray:()=>Bd,toCSV:()=>Hl,toClickHouse:()=>Wl,toFile:()=>Ba,toHTTP:()=>ll,toKafka:()=>Ol,toLoki:()=>Yl,toMongo:()=>Jl,toNATS:()=>Vl,toObservable:()=>Bo,toPostgres:()=>Ul,toPulsar:()=>jl,toRabbitMQ:()=>ql,toReadableStream:()=>hl,toRedisStream:()=>Cl,toS3:()=>zl,toSSE:()=>ml,toSSEBytes:()=>gl,toSqlite:()=>np,toTempo:()=>Ql,toWebSocket:()=>Tl,tokenBucket:()=>Vt,valve:()=>sl,verifiable:()=>cp,window:()=>tl,windowCount:()=>Xc,windowTime:()=>el,withBreaker:()=>Kn,withLatestFrom:()=>Pt,withMaxAttempts:()=>ua,withStatus:()=>Kt,workerBridge:()=>qa,workerSelf:()=>Ha,zip:()=>Bc});Me();xe();ae();_e();ee();Me();ae();ee();function _c(t){return{describeKind:"producer",...t}}function mn(t,e){return K(n=>{let r=!0,o={emit(i){r&&n.emit(i)},error(i){r&&(r=!1,n.down([[A,i]]))},complete(){r&&(r=!1,n.down([[L]]))}},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{}}},_c(e))}function Os(t,e,n){let r=!0,o,s=0,i=0,a={},u=[],d=()=>{let f=o;o=void 0;try{f?.()}catch{}};for(let f of e){let m=n?.name?`${n.name}::${f}`:f,h=n?.channelOpts?.[f],g=K(y=>(s++,()=>{i++,s>0&&i>=s&&i>=e.length&&d()}),_c({...h,name:m}));a[f]=g,u.push(g)}let c={};for(let f of e)c[f]=m=>{r&&a[f].down([[E,m]])};c.error=f=>{r&&(r=!1,X(()=>{for(let m of u)m.down([[A,f]])}),d())},c.complete=()=>{r&&(r=!1,X(()=>{for(let f of u)f.down([[L]])}),d())};let l=t(c);return o=typeof l=="function"?l:void 0,Object.assign(a,{dispose:()=>{r&&(r=!1,X(()=>{for(let f of u)try{f.down([[L]])}catch{}}),d())}})}xe();ae();_e();ee();he();function ue(t){return{describeKind:"derived",...t}}function Mc(t){return{describeKind:"derived",partial:!0,...t}}function zr(t,e,n){return z([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[V]]);return}for(let i of s)o.emit(e(i))},ue(n))}function Xe(t,e,n){return z([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[V]]);return}let i=!1;for(let a of s)e(a)&&(o.emit(a),i=!0);i||o.down([[V]])},ue(n))}function Oc(t,e,n,r){return z([t],(o,s,i)=>{"acc"in i.store||(i.store.acc=n);let a=o[0];if(a==null||a.length===0){s.down([[V]]);return}for(let u of a)i.store.acc=e(i.store.acc,u),s.emit(i.store.acc)},{...ue(r),initial:n,resetOnTeardown:!0})}function Ac(t,e,n,r){return z([t],(o,s,i)=>{if("acc"in i.store||(i.store.acc=n),i.terminalDeps[0]===!0){s.emit(i.store.acc),s.down([[L]]);return}let a=o[0];if(a==null||a.length===0){s.down([[V]]);return}for(let u of a)i.store.acc=e(i.store.acc,u)},{...ue(r),completeWhenDepsComplete:!1})}function Ur(t,e,n){return e<=0?z([t],(r,o,s)=>{s.store.completed||(s.store.completed=!0,o.down([[L]]))},{...ue(n),completeWhenDepsComplete:!1}):z([t],(r,o,s)=>{if("taken"in s.store||(s.store.taken=0),s.store.done){o.down([[V]]);return}if(s.terminalDeps[0]===!0){s.store.done=!0,o.down([[L]]);return}let i=r[0];if(i==null||i.length===0){o.down([[V]]);return}for(let a of i)if(s.store.taken++,o.emit(a),s.store.taken>=e){s.store.done=!0,o.down([[L]]);return}},{...ue(n),completeWhenDepsComplete:!1})}function Aa(t,e,n){return z([t],(r,o,s)=>{"skipped"in s.store||(s.store.skipped=0);let i=r[0];if(i==null||i.length===0){o.down([[V]]);return}let a=!1;for(let u of i)s.store.skipped++,s.store.skipped<=e||(o.emit(u),a=!0);a||o.down([[V]])},ue(n))}function Cc(t,e,n){return z([t],(r,o,s)=>{if(s.store.done){o.down([[V]]);return}let i=r[0];if(i==null||i.length===0){o.down([[V]]);return}for(let a of i){if(!e(a)){s.store.done=!0,o.down([[L]]);return}o.emit(a)}},{...ue(n),completeWhenDepsComplete:!1})}function Lc(t,e,n){let r=n?.predicate??(i=>i[0]===E),{predicate:o,...s}=n??{};return K(i=>{let a=!1,u=t.subscribe(c=>{if(!a)for(let l of c){if(a)return;l[0]===E?i.emit(l[1]):(l[0]===L||l[0]===A)&&(a=!0,i.down([l]))}}),d=e.subscribe(c=>{if(!a)for(let l of c){if(a)return;if(r(l)){a=!0,i.down([[L]]);return}}});return()=>{u(),d()}},ue(s))}function As(t,e){return Ur(t,1,e)}function Ic(t,e){let{defaultValue:n,...r}=e??{},o=e!=null&&Object.hasOwn(e,"defaultValue");return z([t],(s,i,a)=>{if(a.terminalDeps[0]===!0){a.store.has?i.emit(a.store.latest):o&&i.emit(n),i.down([[L]]);return}let u=s[0];if(u==null||u.length===0){i.down([[V]]);return}a.store.latest=u.at(-1),a.store.has=!0},{...ue(r),completeWhenDepsComplete:!1})}function Pc(t,e,n){return Ur(Xe(t,e,n),1,n)}function Dc(t,e,n){return Ur(Aa(t,e,n),1,n)}function Gc(t,e,n){if(typeof e=="function")return z([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[V]]);return}for(let a of i)e(a),s.emit(a)},ue(n));let r=e;return z([t],(o,s,i)=>{if(i.terminalDeps[0]!==void 0){i.terminalDeps[0]===!0?(r.complete?.(),s.down([[L]])):(r.error?.(i.terminalDeps[0]),s.down([[A,i.terminalDeps[0]]]));return}let a=o[0];if(a==null||a.length===0){s.down([[V]]);return}for(let u of a)r.data?.(u),s.emit(u)},{...ue(n),completeWhenDepsComplete:!1})}function Jr(t,e,n){let r=n?.where??(s=>s!=null),o=!1;return z([t],(s,i)=>{let a=s[0];if(a==null||a.length===0){i.down([[V]]);return}for(let u of a)!o&&r(u)&&(o=!0,e(u)),i.emit(u)},ue(n))}var Fc=Jr;function $c(t,e=Object.is,n){return z([t],(r,o,s)=>{let i=r[0];if(i==null||i.length===0){o.down([[V]]);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([[V]])},ue(n))}function jc(t,e){return z([t],(n,r,o)=>{let s=n[0];if(s==null||s.length===0){r.down([[V]]);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([[V]])},ue(e))}function Ca(...t){let e=[...t];return C(e,n=>n,{...ue(),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 Pt(t,e,n){return z([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([[V]]);return}for(let d of i)o.emit([d,u])}else o.down([[V]])},Mc(n))}function xt(...t){return t.length===0?K(e=>{e.down([[L]])},ue()):K(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]===E?e.emit(u[1]):u[0]===L?(r+=1,r>=n&&e.down([[L]])):u[0]===A&&e.down([u])});o.push(i)}return()=>{for(let s of o)s()}},ue())}function Bc(...t){let e=t.length;return e===0?K(n=>{n.emit([]),n.down([[L]])},ue()):K(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,d=t[a].subscribe(c=>{for(let l of c)l[0]===E?(r[u].push(l[1]),s()):l[0]===L?(o-=1,(o===0||r[u].length===0)&&n.down([[L]])):l[0]===A&&n.down([l])});i.push(d)}return()=>{for(let a of i)a()}},ue())}function Vc(t,e,n){return K(r=>{let o=0,s=[],i,a;return a=e.subscribe(u=>{for(let d of u)o===0?d[0]===E?s.push(d[1]):d[0]===A&&r.down([d]):d[0]===E?r.emit(d[1]):(d[0]===L||d[0]===A)&&r.down([d])}),i=t.subscribe(u=>{for(let d of u)if(o===0)if(d[0]===E)r.emit(d[1]);else if(d[0]===L){o=1;for(let c of s)r.emit(c);s.length=0}else d[0]===A&&r.down([d])}),()=>{i?.(),a?.()}},ue(n))}function Kc(...t){return t.length===0?K(e=>{e.down([[L]])},ue()):t.length===1?z([t[0]],(e,n)=>{let r=e[0];if(r==null||r.length===0){n.down([[V]]);return}for(let o of r)n.emit(o)},ue()):K(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]===E?(n===null&&(n=s),e.emit(u[1])):(u[0]===L||u[0]===A)&&(n===null||s===n)&&e.down([u])}});r.push(i)}return()=>{for(let o of r)o()}},ue())}function Cs(t,e,n){let r,o=!1,s=()=>{o||(o=!0,n())};return r=t.subscribe(i=>{let a=!1,u=!1;for(let d of i)d[0]!==dt&&(d[0]===E?e.emit(d[1]):d[0]===L?a=!0:d[0]===A?(u=!0,e.down([d])):(d[0]===ne||d[0]===V)&&e.down([d]));u?(r?.(),r=void 0,s()):a&&s()}),()=>{r?.(),r=void 0}}function Te(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return z([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([[L]]);return}let d=i[0];if(!(d==null||d.length===0))return s(),r=Cs(U(e(d[d.length-1])),a,()=>{s(),o&&a.down([[L]])}),{deactivate:()=>{s(),o=!1}}},{...ue(n),completeWhenDepsComplete:!1})}function qc(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return z([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([[L]]);return}let d=i[0];if(!(d==null||d.length===0))return r===void 0?r=Cs(U(e(d[0])),a,()=>{s(),o&&a.down([[L]])}):a.down([[V]]),{deactivate:()=>{s(),o=!1}}},{...ue(n),completeWhenDepsComplete:!1})}function Hc(t,e,n){let{maxBuffer:r,...o}=n??{},s=[],i,a=!1,u;function d(){i?.(),i=void 0}function c(){if(!u||i!==void 0)return;if(s.length===0){a&&u.down([[L]]);return}let p=s.shift();i=Cs(U(e(p)),u,()=>{d(),c()})}function l(p){r&&r>0&&s.length>=r&&s.shift(),s.push(p),c()}return z([t],(p,f,m)=>{if(u=f,m.terminalDeps[0]!=null&&m.terminalDeps[0]!==!0){d(),s.length=0;return}if(m.terminalDeps[0]===!0){a=!0,c();return}let h=p[0];if(!(h==null||h.length===0)){for(let g of h)l(g);return{deactivate:()=>{d(),s.length=0,a=!1}}}},{...ue(o),completeWhenDepsComplete:!1})}function La(t,e,n){let{concurrent:r,...o}=n??{},s=r!=null&&r>0?r:Number.POSITIVE_INFINITY,i=0,a=!1,u=new Set,d=[],c;function l(){a&&i===0&&d.length===0&&c&&c.down([[L]])}function p(g){if(!c)return;i++;let y;y=Cs(U(e(g)),c,()=>{y&&u.delete(y),i--,f(),l()}),u.add(y)}function f(){for(;d.length>0&&i<s;)p(d.shift())}function m(g){i<s?p(g):d.push(g)}function h(){for(let g of u)g();u.clear(),i=0,d.length=0}return z([t],(g,y,b)=>{if(c=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}}}},{...ue(o),completeWhenDepsComplete:!1})}var Wc=La;function zc(t,e,n){return K(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]===E){let d=setTimeout(()=>{o.delete(d),r.emit(u[1])},e);o.add(d)}else if(u[0]===L){let d=setTimeout(()=>{o.delete(d),r.down([[L]])},e);o.add(d)}else u[0]===A&&(s(),r.down([u]))});return()=>{i(),s()}},ue(n))}function Ia(t,e,n){return K(r=>{let o,s;function i(){o!==void 0&&(clearTimeout(o),o=void 0)}let a=t.subscribe(u=>{for(let d of u)d[0]===E?(i(),s=d[1],o=setTimeout(()=>{o=void 0,r.emit(s)},e)):d[0]===L?(o!==void 0&&(i(),r.emit(s)),r.down([[L]])):d[0]===A&&(i(),r.down([d]))});return()=>{a(),i()}},ue(n))}function Pa(t,e,n){let{leading:r,trailing:o,...s}=n??{},i=r!==!1,a=o===!0,u=e*1e6;return K(d=>{let c,l=-1/0,p,f=!1;function m(){c!==void 0&&(clearTimeout(c),c=void 0)}let h=t.subscribe(g=>{for(let y of g)if(y[0]===E){let b=y[1],v=H();if(i&&v-l>=u)l=v,d.emit(b),m(),a&&(c=setTimeout(()=>{c=void 0,f&&(l=H(),d.emit(p),f=!1)},e));else if(a&&(p=b,f=!0,c===void 0)){let T=(v-l)/1e6;c=setTimeout(()=>{c=void 0,f&&(l=H(),d.emit(p),f=!1)},Math.max(0,e-T))}}else(y[0]===L||y[0]===A)&&(m(),d.down([y]))});return()=>{h(),m()}},ue(s))}function Uc(t,e,n){return K(r=>{let o,s=!1,i=!1,a=t.subscribe(d=>{if(!s)for(let c of d){if(s)return;c[0]===E?o={v:c[1]}:c[0]===A?(s=!0,r.down([c])):c[0]===L&&(i=!0,o=void 0)}}),u=e.subscribe(d=>{if(!s)for(let c of d){if(s)return;c[0]===E?o!==void 0&&!i&&r.emit(o.v):c[0]===A?(s=!0,r.down([c])):c[0]===L&&(s=!0,r.down([[L]]))}});return()=>{a(),u()}},ue(n))}function Jc(t,e,n){return K(r=>{let o,s,i=!1;function a(){o!==void 0&&(clearTimeout(o),o=void 0)}let u=t.subscribe(d=>{for(let c of d)c[0]===E?(s=c[1],i=!0,a(),o=setTimeout(()=>{o=void 0,i&&(i=!1,r.emit(s))},e)):(c[0]===L||c[0]===A)&&(a(),r.down([c]))});return()=>{u(),a()}},ue(n))}function Yc(t,e,n){return K(r=>{let o=[],s=t.subscribe(a=>{for(let u of a)u[0]===E?o.push(u[1]):u[0]===L?(o.length>0&&r.emit([...o]),o.length=0,r.down([[L]])):u[0]===A&&r.down([u])}),i=e.subscribe(a=>{for(let u of a)u[0]===E?o.length>0&&(r.emit([...o]),o.length=0):u[0]===L?r.down([[L]]):u[0]===A&&r.down([u])});return()=>{s(),i(),o.length=0}},ue(n))}function Qc(t,e,n){if(e<=0)throw new RangeError("bufferCount expects count > 0");return K(r=>{let o=[],s=t.subscribe(i=>{for(let a of i)a[0]===E?(o.push(a[1]),o.length>=e&&r.emit(o.splice(0,o.length))):a[0]===L?(o.length>0&&r.emit([...o]),o.length=0,r.down([[L]])):a[0]===A&&r.down([a])});return()=>{s(),o.length=0}},ue(n))}function Xc(t,e,n){if(e<=0)throw new RangeError("windowCount expects count > 0");return K(r=>{let o,s=0;function i(){let u=K(d=>(o=d.down.bind(d),()=>{o=void 0}),ue());s=0,r.emit(u)}let a=t.subscribe(u=>{for(let d of u)d[0]===E?(o||i(),o?.([[E,d[1]]]),s+=1,s>=e&&(o?.([[L]]),o=void 0)):d[0]===L?(o?.([[L]]),o=void 0,r.down([[L]])):d[0]===A&&(o?.([d]),o=void 0,r.down([d]))});return()=>{a(),o?.([[L]]),o=void 0}},ue(n))}function Zc(t,e,n){return K(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]===E?o.push(u[1]):u[0]===L?(clearInterval(s),o.length>0&&r.emit([...o]),o.length=0,r.down([[L]])):u[0]===A&&(clearInterval(s),r.down([u]))});return()=>{i(),clearInterval(s),o.length=0}},ue(n))}function el(t,e,n){return K(r=>{let o;function s(){o?.([[L]]),o=void 0}function i(){let d=K(c=>(o=c.down.bind(c),()=>{o=void 0}),ue());r.emit(d)}i();let a=setInterval(()=>{s(),i()},e),u=t.subscribe(d=>{for(let c of d)c[0]===E?o?.([[E,c[1]]]):c[0]===L?(clearInterval(a),s(),r.down([[L]])):c[0]===A&&(clearInterval(a),o?.([c]),s(),r.down([c]))});return()=>{u(),clearInterval(a),s()}},ue(n))}function tl(t,e,n){return K(r=>{let o;function s(){o?.([[L]]),o=void 0}function i(){let d=K(c=>(o=c.down.bind(c),()=>{o=void 0}),ue());r.emit(d)}let a=t.subscribe(d=>{for(let c of d)c[0]===E?(o||i(),o?.([[E,c[1]]])):c[0]===L?(s(),r.down([[L]])):c[0]===A&&(o?.([c]),o=void 0,r.down([c]))}),u=e.subscribe(d=>{for(let c of d)c[0]===E&&(s(),i())});return()=>{a(),u(),s()}},ue(n))}function nl(t,e){return K((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)},ue(e))}function rl(t,e,n){if(e<=0)throw new RangeError("repeat expects count > 0");return K(r=>{let o=e,s,i=()=>{s?.(),s=t.subscribe(a=>{let u=!1,d=[];for(let c of a)c[0]===L?u=!0:d.push(c);d.length>0&&r.down(d),u&&(s?.(),s=void 0,o-=1,o>0?i():r.down([[L]]))})};return i(),()=>{s?.()}},ue(n))}function ol(t,e){return z([t],(n,r)=>{let o=n[0];if(o==null||o.length===0){r.down([[V]]);return}for(let s of o)r.emit(s)},ue(e))}function Yr(t,e,n){return K(r=>{let o=t.subscribe(s=>{for(let i of s)if(i[0]===E)r.emit(i[1]);else if(i[0]===A)try{r.emit(e(i[1]))}catch(a){r.down([[A,a]])}else i[0]===L&&r.down([[L]])});return()=>{o()}},ue(n))}function sl(t,e,n){return z([t,e],(r,o,s)=>{let i=r[1];if(!(i!=null&&i.length>0?i.at(-1):s.prevData[1])){o.down([[V]]);return}let u=r[0];if(u!=null&&u.length>0){for(let d of u)o.emit(d);return}if(i!=null&&i.length>0&&s.prevData[0]!==void 0){o.emit(s.prevData[0]);return}o.down([[V]])},Mc(n))}var il=Ca,al=Ia,ul=Pa,dl=Yr;ae();_e();ee();Vn();var Da=class{ring;arr;constructor(e){e===Number.POSITIVE_INFINITY||e<=0?(this.arr=[],this.ring=null):(this.ring=new ln(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 Qr(t){return t instanceof Error?t:new Error(String(t))}function Pg(t){return t===void 0?null:typeof t=="string"?Bt(t):t}function We(t,e){let{name:n,onTransportError:r,retry:o,backpressure:s,batchSize:i=Number.POSITIVE_INFINITY,flushIntervalMs:a=0,serialize:u,stopOn:d,onUpstreamMessage:c,onDispose:l,send:p,sendBatch:f,ctx:m}=e;if(!p&&!f)throw new Error("reactiveSink: `send` or `sendBatch` must be provided");let h=m,g=Math.max(1,o?.maxAttempts??1),y=Pg(o?.backoff??(g>1?"exponential":void 0)),b=o?.shouldRetry??(()=>!0),v=f!==void 0||i<Number.POSITIVE_INFINITY||a>0,T=W=>n?`${n}::${W}`:void 0,w=M(void 0,{equals:()=>!1,name:T("sent")}),k=M(null,{name:T("failed")}),x=M(0,{name:T("inFlight")}),S=M(null,{name:T("errors")}),R=v?M(0,{name:T("buffered")}):void 0,N=s?M(!1,{name:T("paused")}):void 0,_=0,I=W=>{_+=W,x.down([[E,_]])},O=W=>{try{r?.(W)}catch{}try{S.down([[E,W]])}catch{}},P=new Set,B=W=>{P.add(W);let ce=()=>P.delete(W);W.then(ce,ce)},j=(W,ce,Se)=>{let Ee=y?y(ce-1,Se,null):0,le=Ee==null?0:typeof Ee=="number"&&Ee>0?Ee:0,Pe=Math.max(1,Math.ceil(le/1e6));return new Promise(me=>{setTimeout(()=>me(W()),Pe)})},D=W=>W!=null&&typeof W=="object"&&typeof W.then=="function",Z=W=>{let ce;try{ce=u?u(W):W}catch(me){let ge=Qr(me);return O({stage:"serialize",error:ge,value:W}),k.down([[E,{value:W,error:ge,attempts:0}]]),Promise.resolve()}let Se=0,Ee=me=>{I(-1);let ge=Qr(me);if(O({stage:"send",error:ge,value:W,attempt:Se}),!(Se<g&&b(ge,Se))){k.down([[E,{value:W,error:ge,attempts:Se}]]);return}return j(Pe,Se,ge)},le=()=>{I(-1),w.down([[E,W]])};function Pe(){Se+=1,I(1);let me;try{me=p(ce,h)}catch(ge){return Ee(ge)??Promise.resolve()}return D(me)?me.then(le,ge=>Ee(ge)):(le(),Promise.resolve())}return Pe()},F=s?.maxBuffer??Number.POSITIVE_INFINITY,Q=new Da(F),G,q=!1,$=()=>{R?.down([[E,Q.length]])},te=W=>{N&&N.down([[E,W]])},Re=s?.strategy??"drop-oldest",Oe=(W,ce)=>{let Se={value:W,payload:ce};if(Q.length<F)return Q.push(Se),$(),!0;if(Re==="drop-oldest"){let le=Q.shift();return Q.push(Se),$(),te(!0),k.down([[E,{value:le.value,error:new Error("backpressure: buffer overflow \u2014 dropped oldest"),attempts:0}]]),!0}if(Re==="drop-newest")return te(!0),k.down([[E,{value:W,error:new Error("backpressure: buffer overflow \u2014 dropped newest"),attempts:0}]]),!1;let Ee=new Error("backpressure: buffer overflow");return O({stage:"send",error:Ee,value:W}),k.down([[E,{value:W,error:Ee,attempts:0}]]),te(!0),!1},Ae=W=>{let ce=0,Se=W.map(me=>me.payload),Ee=me=>{I(-1);let ge=Qr(me);if(O({stage:"send",error:ge,value:W.map(Sn=>Sn.value),attempt:ce}),!(ce<g&&b(ge,ce))){for(let{value:Sn}of W)k.down([[E,{value:Sn,error:ge,attempts:ce}]]);return}return j(Pe,ce,ge)},le=()=>{I(-1);for(let{value:me}of W)w.down([[E,me]])};function Pe(){ce+=1,I(1);let me;try{me=f(Se,h)}catch(ge){return Ee(ge)??Promise.resolve()}return D(me)?me.then(le,ge=>Ee(ge)):(le(),Promise.resolve())}return Pe()},ye=async W=>{for(let ce of W)await Ge(ce.value,ce.payload)},Ge=(W,ce)=>{let Se=0,Ee=me=>{I(-1);let ge=Qr(me);if(O({stage:"send",error:ge,value:W,attempt:Se}),!(Se<g&&b(ge,Se))){k.down([[E,{value:W,error:ge,attempts:Se}]]);return}return j(Pe,Se,ge)},le=()=>{I(-1),w.down([[E,W]])};function Pe(){Se+=1,I(1);let me;try{me=p(ce,h)}catch(ge){return Ee(ge)??Promise.resolve()}return D(me)?me.then(le,ge=>Ee(ge)):(le(),Promise.resolve())}return Pe()},ie=()=>{if(q||Q.length===0)return Promise.resolve();let W=Q.drain();if($(),te(!1),f!==void 0){let Se=Ae(W);return B(Se),Se}let ce=ye(W);return B(ce),ce},we=()=>{G!==void 0||q||a<=0||(G=setTimeout(()=>{G=void 0,ie()},a))},Fe=t.subscribe(W=>{for(let ce of W){let Se=ce[0];if(Se!==E)try{c?.(ce)}catch{}if(Se===E){let Ee=ce[1];if(v){let le;if(u)try{le=u(Ee)}catch(me){let ge=Qr(me);O({stage:"serialize",error:ge,value:Ee}),k.down([[E,{value:Ee,error:ge,attempts:0}]]);continue}else le=Ee;if(!Oe(Ee,le))continue;Q.length>=i?ie():we()}else{let le=Z(Ee);B(le)}}else $e.messageTier(Se)>=3&&v&&(G!==void 0&&(clearTimeout(G),G=void 0),ie())}}),be;if(d){let W=!1;be=d.subscribe(ce=>{if(!W){W=!0;return}ce.length>0&&!J&&se()})}let J=!1,se=()=>{if(J)return;J=!0,G!==void 0&&(clearTimeout(G),G=void 0),v&&ie(),q=!0,be?.(),Fe();let W=ce=>{try{ce.down([[de]])}catch{}};W(S),W(k),W(w),W(x),R&&W(R),N&&W(N);try{l?.()}catch{}},ve={dispose:se,sent:w,failed:k,inFlight:x,errors:S};return v&&(ve.buffered=R,ve.flush=async()=>{q||(await ie(),await Promise.all(P))}),N&&(ve.paused=N),ve}Ot();he();function gt(t){return{describeKind:"producer",...t}}function Fa(t,e){let{parse:n,closeOnTeardown:r=!1,...o}=e??{};return K(s=>{let i=!0,a,u=()=>{let y=a;a=void 0,y?.()},d=y=>{i&&(i=!1,s.down([y]),u())},c=(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){d([A,v])}},l=y=>{d([A,y])},p=()=>{d([L])};if(typeof t=="function"){try{if(a=t(c,l,p),typeof a!="function")throw new Error("fromWebSocket register contract violation: register must return cleanup callable")}catch(y){d([A,y])}return()=>{i=!1,u()}}let f=t,m=y=>c(y,y),h=y=>l(y),g=()=>p();return f.addEventListener("message",m),f.addEventListener("error",h),f.addEventListener("close",g),a=()=>{f.removeEventListener("message",m),f.removeEventListener("error",h),f.removeEventListener("close",g),r&&f.close()},()=>{i=!1,u()}},gt(o))}function cl(t,e){return mn(t,e)}function $a(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:d=!1,...c}=e??{},l=M(0,{name:`${c.name??"http"}/fetchCount`}),p=M(0,{name:`${c.name??"http"}/lastUpdated`}),f=M(!1,{name:`${c.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([[A,a.reason??new Error("Aborted")]]),()=>{};a?.addEventListener("abort",()=>T.abort(a.reason),{once:!0});let k=setTimeout(()=>T.abort(new Error("Request timeout")),Math.ceil(i/1e6));return fetch(t,{method:n,headers:r,body:h,signal:T.signal}).then(async x=>{if(clearTimeout(k),!w)return;if(!x.ok)throw new Error(`HTTP ${x.status}: ${x.statusText}`);let S=await s(x);w&&(X(()=>{m+=1,l.down([[E,m]]),p.down([[E,oe()]]),f.down([[E,!0]]),v.emit(S)}),u&&v.down([[L]]))}).catch(x=>{clearTimeout(k),w&&(x&&x.name==="AbortError"||v.down([[A,x]]))}),()=>{w=!1,T.abort()}},y=K(v=>g({emit:T=>v.emit(T),down:T=>v.down(T)}),{...gt(c),resubscribable:d});return{...Kt(y),fetchCount:l,lastUpdated:p,fetched:f}}function ll(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:d,retry:c,onTransportError:l}=n??{},p=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||d!==void 0?We(t,{onTransportError:l,retry:c,batchSize:u,flushIntervalMs:d,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 p(h)}}):We(t,{onTransportError:l,retry:c,serialize:s,send:async m=>{await p(m)}})}function pl(t){return Symbol.keyFor(t)??t.description??"message"}function Xn(t,e){return typeof t=="string"?t:e(t)}function fl(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 pl(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:d,eventNameResolver:c=cl}=e??{},l=new TextEncoder,p;return new ReadableStream({start(f){let m=!1,h,g=()=>{},y=()=>{m||(m=!0,h!==void 0&&clearInterval(h),d?.removeEventListener("abort",v),g(),f.close())};p=y;let b=(T,w)=>{m||f.enqueue(l.encode(ll(T,w)))},v=()=>{m||y()};g=t.subscribe(T=>{for(let w of T){let x=w[0];if(!($e.isLocalOnly(x)&&!(x===ne&&a))){if(x===E){b(r,Xn(w[1],n));continue}if(x===C){b(o,Xn(w[1],n)),y();return}if(x===L){b(s),y();return}!i&&x===V||b(c(x),w.length>1?Xn(w[1],n):void 0)}}}),u!==void 0&&u>0&&(h=setInterval(()=>{m||f.enqueue(l.encode(`: keepalive
19
+ `}function ml(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:d,eventNameResolver:c=pl}=e??{},l=new TextEncoder,p;return new ReadableStream({start(f){let m=!1,h,g=()=>{},y=()=>{m||(m=!0,h!==void 0&&clearInterval(h),d?.removeEventListener("abort",v),g(),f.close())};p=y;let b=(T,w)=>{m||f.enqueue(l.encode(fl(T,w)))},v=()=>{m||y()};g=t.subscribe(T=>{for(let w of T){let k=w[0];if(!($e.isLocalOnly(k)&&!(k===ne&&a))){if(k===E){b(r,Xn(w[1],n));continue}if(k===A){b(o,Xn(w[1],n)),y();return}if(k===L){b(s),y();return}!i&&k===V||b(c(k),w.length>1?Xn(w[1],n):void 0)}}}),u!==void 0&&u>0&&(h=setInterval(()=>{m||f.enqueue(l.encode(`: keepalive
20
20
 
21
- `))},u)),d?.aborted?v():d?.addEventListener("abort",v,{once:!0})},cancel(){p?.()}})}function fl(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:d,eventNameResolver:c=cl}=e??{},l=new TextEncoder;return K(p=>{let f=!0,m,h=(b,v)=>{f&&p.emit(l.encode(ll(b,v)))},g=()=>{f&&(f=!1,p.down([[L]]))},y=t.subscribe(b=>{if(f)for(let v of b){let T=v[0];if(!($e.isLocalOnly(T)&&!(T===ne&&a))){if(T===E){h(r,Xn(v[1],n));continue}if(T===C){h(o,Xn(v[1],n)),f=!1,p.down([[L]]);return}if(T===L){h(s),f=!1,p.down([[L]]);return}!i&&T===V||h(c(T),v.length>1?Xn(v[1],n):void 0)}}});return u!==void 0&&u>0&&(m=setInterval(()=>{f&&p.emit(l.encode(`: keepalive
21
+ `))},u)),d?.aborted?v():d?.addEventListener("abort",v,{once:!0})},cancel(){p?.()}})}function gl(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:d,eventNameResolver:c=pl}=e??{},l=new TextEncoder;return K(p=>{let f=!0,m,h=(b,v)=>{f&&p.emit(l.encode(fl(b,v)))},g=()=>{f&&(f=!1,p.down([[L]]))},y=t.subscribe(b=>{if(f)for(let v of b){let T=v[0];if(!($e.isLocalOnly(T)&&!(T===ne&&a))){if(T===E){h(r,Xn(v[1],n));continue}if(T===A){h(o,Xn(v[1],n)),f=!1,p.down([[L]]);return}if(T===L){h(s),f=!1,p.down([[L]]);return}!i&&T===V||h(c(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
22
 
23
- `))},u)),d?.aborted?g():d?.addEventListener("abort",g,{once:!0}),()=>{f=!1,m!==void 0&&clearInterval(m),d?.removeEventListener("abort",g),y()}})}function ml(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===E)try{r.enqueue(s[1])}catch{n=!0,e?.()}else if(i===C){n=!0;try{r.error(s[1])}catch{}return}else if(i===L){n=!0;try{r.close()}catch{}return}}})},cancel(){n=!0,e?.()}})}async function*Dt(t,e){let n=e?.parse??(w=>w),r=e?.signal,o=new TextDecoder,s="",i="message",a=[],u,d,c=[],l=()=>{if(a.length===0&&i==="message"&&u===void 0){a=[];return}let w=a.join(`
24
- `);c.push({event:i,data:n(w),id:u,retry:d}),i="message",a=[],u=void 0,d=void 0},p=w=>{if(w===""){l();return}if(w.startsWith(":"))return;let x=w.indexOf(":"),k=x<0?w:w.slice(0,x),S=x<0?"":w.slice(x+1);switch(S.startsWith(" ")&&(S=S.slice(1)),k){case"event":i=S;break;case"data":a.push(S);break;case"id":S.includes("\0")||(u=S);break;case"retry":{let R=Number(S);Number.isFinite(R)&&(d=R);break}}},f=(w,x)=>{s+=o.decode(w,{stream:!x});let k=s.split(/\r?\n/);s=k.pop()??"";for(let S of k)p(S)},m=t,h=t instanceof ReadableStream?t:m&&typeof m=="object"&&m.body instanceof ReadableStream?m.body:null,g,y,b=!1,v=()=>{b||(b=!0,g&&g.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(h){for(g=h.getReader();!r?.aborted;){let{value:w,done:x}=await g.read();if(x)break;for(f(w,!1);c.length>0;)yield c.shift()}f(new Uint8Array,!0)}else{for(y=t[Symbol.asyncIterator]();!r?.aborted;){let x=await y.next();if(x.done)break;for(f(x.value,!1);c.length>0;)yield c.shift()}f(new Uint8Array,!0)}if(s.trim()){for(let w of s.split(/\r?\n/))p(w);l()}for(;c.length>0;)yield c.shift()}finally{r&&r.removeEventListener("abort",T),v()}}function gl(t,e){let{parse:n,...r}=e??{};return K(o=>{let s=!0,i=new AbortController;return(async()=>{try{for await(let u of Dt(t,{parse:n,signal:i.signal})){if(!s)return;o.emit(u)}s&&o.down([[L]])}catch(u){s&&o.down([[C,u]])}})(),()=>{s=!1,i.abort()}},gt(r))}function hl(t,e){let{method:n="GET",headers:r,body:o,signal:s,...i}=e??{};return K(a=>{let u=!0,d=new AbortController;if(s?.aborted)return a.down([[C,s.reason??new Error("Aborted")]]),()=>{};s?.addEventListener("abort",()=>d.abort(s.reason),{once:!0});let c=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:c,signal:d.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:h}=await f.read();if(h)break;m&&a.emit(m)}u&&a.down([[L]])}catch(p){if(!u||p&&p.name==="AbortError")return;a.down([[C,p]])}})(),()=>{u=!1,d.abort()}},gt(i))}function yl(t,e){let{intervalMs:n=5e3,...r}=e??{};return Te(st(n,{period:n}),()=>$a(t,{...r,completeAfterFetch:!0}).node)}function bl(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:d,backpressure:c,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,g=We(t,{onTransportError:u,serialize:y=>{let b=r(y);if(b===void 0)throw new Error("serialize returned undefined");return b},retry:d,backpressure:c,stopOn:l,onDispose:()=>{if(m){try{e.removeEventListener("close",m)}catch{}m=null}},send:y=>{e.send(y)},onUpstreamMessage:y=>{(y[0]===L&&o||y[0]===C&&s)&&f(y)}});return m=()=>{p=!0,g.dispose()},e.addEventListener("close",m),g}function vl(t,e){let{parse:n,maxRetries:r,backoff:o="exponential",closeOnTeardown:s=!0,...i}=e??{};return Tt(()=>Fa(t(),{parse:n,closeOnTeardown:s,...i}),{count:r,backoff:o})}function Tl(t,e){let{method:n="notifications/message",onDisconnect:r,...o}=e??{};return mn(({emit:s,error:i})=>(t.setNotificationHandler(n,a=>s(a)),r?.(a=>i(a??new Error("MCP client disconnected"))),()=>t.setNotificationHandler(n,()=>{})),o)}function wl(t,e){return Os(({traces:r,metrics:o,logs:s,error:i})=>t({onTraces:a=>{X(()=>{for(let u of a)r(u)})},onMetrics:a=>{X(()=>{for(let u of a)o(u)})},onLogs:a=>{X(()=>{for(let u of a)s(u)})},onError:i})??void 0,["traces","metrics","logs"],e?.name?{name:e.name}:void 0)}function kl(t,e){return mn(t,e)}function xl(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=oe();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:oe()}}function Rl(t,e){return mn(t,e)}var Lg={c:"counter",g:"gauge",ms:"timer",h:"histogram",s:"set",d:"distribution"};function Sl(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=Lg[o]??"counter",i=s==="set"?0:Number(r),a,u={};for(let d=2;d<e.length;d++){let c=e[d].trim();if(c.startsWith("@"))a=Number(c.slice(1));else if(c.startsWith("#"))for(let l of c.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:oe()}}function El(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 Te(st(0,{period:a,signal:s}),()=>K(d=>{let c=!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),!c)return;if(!m.ok)throw new Error(`Prometheus scrape ${m.status}: ${m.statusText}`);let h=await m.text();if(!c)return;let g=ja(h);for(let y of g)d.emit(y);u=0,d.down([[L]])}catch(m){if(clearTimeout(p),!c||m instanceof Error&&m.name==="AbortError")return;u+=1,u>=i&&d.down([[C,m]])}})(),()=>{c=!1,clearTimeout(p),l.abort()}}))}function ja(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,d,c=s.indexOf("{");if(c>=0){i=s.slice(0,c);let p=s.indexOf("}",c);if(p<0)continue;let f=s.slice(c+1,p);a=Ig(f);let m=s.slice(p+1).trim().split(/\s+/);u=m[0]??"",d=m[1]}else{let p=s.split(/\s+/);i=p[0]??"",u=p[1]??"",d=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:d?Number(d):void 0,type:n.get(l)??n.get(i),help:r.get(l)??r.get(i),timestampNs:oe()})}return e}function Ig(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 Nl(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 K(i=>{let a=!0;return(async()=>{try{await t.subscribe({topic:e,fromBeginning:r}),await t.run({eachMessage:async({topic:d,partition:c,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:d,partition:c,key:l.key?.toString()??null,value:o(l.value),headers:p,offset:l.offset,timestamp:l.timestamp,timestampNs:oe()})}})}catch(d){a&&i.down([[C,d]])}})(),()=>{a=!1}},gt(s))}function _l(t,e,n,r){let{serialize:o=a=>JSON.stringify(a),keyExtractor:s,onTransportError:i}=r??{};return We(t,{onTransportError:i,send:async a=>{let u=s?.(a)??null,d=o(a);await e.send({topic:n,messages:[{key:u,value:Buffer.from(d)}]})}})}function Ml(t,e,n){let{blockMs:r=5e3,startId:o="$",parse:s=a=>{for(let d=0;d<a.length;d+=2)if(a[d]==="data")try{return JSON.parse(a[d+1])}catch{return a[d+1]}let u={};for(let d=0;d<a.length;d+=2)u[a[d]]=a[d+1];return u},...i}=n??{};return K(a=>{let u=!0,d=o;return(async()=>{for(;u;)try{let l=await t.xread("BLOCK",r,"STREAMS",e,d);if(!u)return;if(l)for(let[p,f]of l)for(let[m,h]of f)d=m,a.emit({id:m,key:e,data:s(h),timestampNs:oe()})}catch(l){if(!u)return;a.down([[C,l]]);return}})(),()=>{u=!1}},gt(i))}function Ol(t,e,n,r){let{serialize:o=a=>["data",JSON.stringify(a)],maxLen:s,onTransportError:i}=r??{};return We(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 Cl(t,e){let{delimiter:n=",",hasHeader:r=!0,columns:o,parseLine:s,...i}=e??{},a=s??(u=>Il(u,n));return K(u=>{let d=!1;return(async()=>{try{let l=o,p="";for await(let f of t){if(d)return;p+=f;let m=p.split(/\r?\n/);p=m.pop()??"";for(let h of m){if(d)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(!d&&p.trim()){let f=a(p);if(l){let m={};for(let h=0;h<l.length;h++)m[l[h]]=f[h]??"";u.emit(m)}}d||u.down([[L]])}catch(l){d||u.down([[C,l]])}})(),()=>{d=!0}},gt(i))}function Al(t,e){let{delimiter:n=",",hasHeader:r=!0,columns:o,parseLine:s,...i}=e??{},a=s??(u=>Il(u,n));return z([t],(u,d,c)=>{let l=u[0];if(l==null||l.length===0)return;let p=c.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 h of m){if(!h.trim())continue;let g=a(h);if(!p.headers&&r){p.headers=g;continue}p.headers||(p.headers=g.map((b,v)=>`col${v}`));let y={};for(let b=0;b<p.headers.length;b++)y[p.headers[b]]=g[b]??"";d.emit(y)}}},{describeKind:"derived",...i})}function Ll(t,e){return z([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 d of u)if(d.trim())try{r.emit(JSON.parse(d))}catch(c){r.down([[C,c]]);return}}},{describeKind:"derived",...e??{}})}function Il(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 Pl(t,e){return K(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 d=u.trim();d&&n.emit(JSON.parse(d))}}!r&&s.trim()&&n.emit(JSON.parse(s.trim())),r||n.down([[L]])}catch(s){r||n.down([[C,s]])}})(),()=>{r=!0}},gt(e))}function Dl(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 Te(st(0,{period:a,signal:s}),()=>K(d=>{let c=!0;return(async()=>{try{let p=await t.query({query:e,format:o});if(!c)return;let f=await p.json();if(!c)return;for(let m of f)d.emit(m);u=0,d.down([[L]])}catch(p){if(!c)return;u+=1,u>=i&&d.down([[C,p]])}})(),()=>{c=!1}}))}function Gl(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 K(a=>{let u=!0;return(async()=>{for(;u;)try{let c=await t.receive();if(!u)return;let l={topic:c.getTopicName(),messageId:c.getMessageId().toString(),key:c.getPartitionKey(),value:r(c.getData()),properties:c.getProperties(),publishTime:c.getPublishTimestamp(),eventTime:c.getEventTimestamp(),timestampNs:oe()};if(n)a.emit(l),t.acknowledge(c).catch(i);else{let p=!1,f={value:l,ack(){p||(p=!0,t.acknowledge(c).catch(i))},nack(m){if(p)return;p=!0;let h=t;try{let g=h.negativeAcknowledge?.(c);g&&typeof g.then=="function"&&g.catch(i)}catch(g){i(g)}}};a.emit(f)}}catch(c){u&&a.down([[C,c]]);return}})(),()=>{u=!1}},gt(s))}function Fl(t,e,n){let{serialize:r=a=>Buffer.from(JSON.stringify(a)),keyExtractor:o,propertiesExtractor:s,onTransportError:i}=n??{};return We(t,{onTransportError:i,send:async a=>{await e.send({data:r(a),partitionKey:o?.(a),properties:s?.(a)})}})}function $l(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 K(a=>{let u=!0,d=t.subscribe(e,o?{queue:o}:void 0);return(async()=>{try{for await(let l of d){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:oe()})}u&&a.down([[L]])}catch(l){u&&a.down([[C,l]])}})(),()=>{u=!1}},gt(i))}function jl(t,e,n,r){let o=new TextEncoder,{serialize:s=a=>o.encode(JSON.stringify(a)),onTransportError:i}=r??{};return We(t,{onTransportError:i,send:a=>{e.publish(n,s(a))}})}function Bl(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 K(u=>{let d=!0,c;return(async()=>{try{c=(await t.consume(e,f=>{if(!d)return;if(f===null){d&&u.down([[C,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:oe()};if(r){u.emit(m);try{t.ack(f)}catch(h){a(h)}}else{let h=!1,g=t,y={value:m,ack(){if(!h){h=!0;try{t.ack(f)}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(f,!1,v)}catch(T){a(T)}}};u.emit(y)}},{noAck:!1})).consumerTag}catch(p){d&&u.down([[C,p]])}})(),()=>{d=!1,c!==void 0&&t.cancel(c)}},gt(i))}function Vl(t,e,n,r){let{serialize:o=a=>Buffer.from(JSON.stringify(a)),routingKeyExtractor:s=()=>"",onTransportError:i}=r??{};return We(t,{onTransportError:i,send:a=>{let u=s(a),d=o(a);e.publish(n,u,d)}})}function Ba(t,e,n){let{serialize:r=l=>`${JSON.stringify(l)}
23
+ `))},u)),d?.aborted?g():d?.addEventListener("abort",g,{once:!0}),()=>{f=!1,m!==void 0&&clearInterval(m),d?.removeEventListener("abort",g),y()}})}function hl(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===E)try{r.enqueue(s[1])}catch{n=!0,e?.()}else if(i===A){n=!0;try{r.error(s[1])}catch{}return}else if(i===L){n=!0;try{r.close()}catch{}return}}})},cancel(){n=!0,e?.()}})}async function*Dt(t,e){let n=e?.parse??(w=>w),r=e?.signal,o=new TextDecoder,s="",i="message",a=[],u,d,c=[],l=()=>{if(a.length===0&&i==="message"&&u===void 0){a=[];return}let w=a.join(`
24
+ `);c.push({event:i,data:n(w),id:u,retry:d}),i="message",a=[],u=void 0,d=void 0},p=w=>{if(w===""){l();return}if(w.startsWith(":"))return;let k=w.indexOf(":"),x=k<0?w:w.slice(0,k),S=k<0?"":w.slice(k+1);switch(S.startsWith(" ")&&(S=S.slice(1)),x){case"event":i=S;break;case"data":a.push(S);break;case"id":S.includes("\0")||(u=S);break;case"retry":{let R=Number(S);Number.isFinite(R)&&(d=R);break}}},f=(w,k)=>{s+=o.decode(w,{stream:!k});let x=s.split(/\r?\n/);s=x.pop()??"";for(let S of x)p(S)},m=t,h=t instanceof ReadableStream?t:m&&typeof m=="object"&&m.body instanceof ReadableStream?m.body:null,g,y,b=!1,v=()=>{b||(b=!0,g&&g.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(h){for(g=h.getReader();!r?.aborted;){let{value:w,done:k}=await g.read();if(k)break;for(f(w,!1);c.length>0;)yield c.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);c.length>0;)yield c.shift()}f(new Uint8Array,!0)}if(s.trim()){for(let w of s.split(/\r?\n/))p(w);l()}for(;c.length>0;)yield c.shift()}finally{r&&r.removeEventListener("abort",T),v()}}function yl(t,e){let{parse:n,...r}=e??{};return K(o=>{let s=!0,i=new AbortController;return(async()=>{try{for await(let u of Dt(t,{parse:n,signal:i.signal})){if(!s)return;o.emit(u)}s&&o.down([[L]])}catch(u){s&&o.down([[A,u]])}})(),()=>{s=!1,i.abort()}},gt(r))}function bl(t,e){let{method:n="GET",headers:r,body:o,signal:s,...i}=e??{};return K(a=>{let u=!0,d=new AbortController;if(s?.aborted)return a.down([[A,s.reason??new Error("Aborted")]]),()=>{};s?.addEventListener("abort",()=>d.abort(s.reason),{once:!0});let c=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:c,signal:d.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:h}=await f.read();if(h)break;m&&a.emit(m)}u&&a.down([[L]])}catch(p){if(!u||p&&p.name==="AbortError")return;a.down([[A,p]])}})(),()=>{u=!1,d.abort()}},gt(i))}function vl(t,e){let{intervalMs:n=5e3,...r}=e??{};return Te(st(n,{period:n}),()=>$a(t,{...r,completeAfterFetch:!0}).node)}function Tl(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:d,backpressure:c,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,g=We(t,{onTransportError:u,serialize:y=>{let b=r(y);if(b===void 0)throw new Error("serialize returned undefined");return b},retry:d,backpressure:c,stopOn:l,onDispose:()=>{if(m){try{e.removeEventListener("close",m)}catch{}m=null}},send:y=>{e.send(y)},onUpstreamMessage:y=>{(y[0]===L&&o||y[0]===A&&s)&&f(y)}});return m=()=>{p=!0,g.dispose()},e.addEventListener("close",m),g}function wl(t,e){let{parse:n,maxRetries:r,backoff:o="exponential",closeOnTeardown:s=!0,...i}=e??{};return Tt(()=>Fa(t(),{parse:n,closeOnTeardown:s,...i}),{count:r,backoff:o})}function kl(t,e){let{method:n="notifications/message",onDisconnect:r,...o}=e??{};return mn(({emit:s,error:i})=>(t.setNotificationHandler(n,a=>s(a)),r?.(a=>i(a??new Error("MCP client disconnected"))),()=>t.setNotificationHandler(n,()=>{})),o)}function xl(t,e){return Os(({traces:r,metrics:o,logs:s,error:i})=>t({onTraces:a=>{X(()=>{for(let u of a)r(u)})},onMetrics:a=>{X(()=>{for(let u of a)o(u)})},onLogs:a=>{X(()=>{for(let u of a)s(u)})},onError:i})??void 0,["traces","metrics","logs"],e?.name?{name:e.name}:void 0)}function Rl(t,e){return mn(t,e)}function Sl(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=oe();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:oe()}}function El(t,e){return mn(t,e)}var Dg={c:"counter",g:"gauge",ms:"timer",h:"histogram",s:"set",d:"distribution"};function Nl(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=Dg[o]??"counter",i=s==="set"?0:Number(r),a,u={};for(let d=2;d<e.length;d++){let c=e[d].trim();if(c.startsWith("@"))a=Number(c.slice(1));else if(c.startsWith("#"))for(let l of c.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:oe()}}function _l(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 Te(st(0,{period:a,signal:s}),()=>K(d=>{let c=!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),!c)return;if(!m.ok)throw new Error(`Prometheus scrape ${m.status}: ${m.statusText}`);let h=await m.text();if(!c)return;let g=ja(h);for(let y of g)d.emit(y);u=0,d.down([[L]])}catch(m){if(clearTimeout(p),!c||m instanceof Error&&m.name==="AbortError")return;u+=1,u>=i&&d.down([[A,m]])}})(),()=>{c=!1,clearTimeout(p),l.abort()}}))}function ja(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,d,c=s.indexOf("{");if(c>=0){i=s.slice(0,c);let p=s.indexOf("}",c);if(p<0)continue;let f=s.slice(c+1,p);a=Gg(f);let m=s.slice(p+1).trim().split(/\s+/);u=m[0]??"",d=m[1]}else{let p=s.split(/\s+/);i=p[0]??"",u=p[1]??"",d=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:d?Number(d):void 0,type:n.get(l)??n.get(i),help:r.get(l)??r.get(i),timestampNs:oe()})}return e}function Gg(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 Ml(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 K(i=>{let a=!0;return(async()=>{try{await t.subscribe({topic:e,fromBeginning:r}),await t.run({eachMessage:async({topic:d,partition:c,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:d,partition:c,key:l.key?.toString()??null,value:o(l.value),headers:p,offset:l.offset,timestamp:l.timestamp,timestampNs:oe()})}})}catch(d){a&&i.down([[A,d]])}})(),()=>{a=!1}},gt(s))}function Ol(t,e,n,r){let{serialize:o=a=>JSON.stringify(a),keyExtractor:s,onTransportError:i}=r??{};return We(t,{onTransportError:i,send:async a=>{let u=s?.(a)??null,d=o(a);await e.send({topic:n,messages:[{key:u,value:Buffer.from(d)}]})}})}function Al(t,e,n){let{blockMs:r=5e3,startId:o="$",parse:s=a=>{for(let d=0;d<a.length;d+=2)if(a[d]==="data")try{return JSON.parse(a[d+1])}catch{return a[d+1]}let u={};for(let d=0;d<a.length;d+=2)u[a[d]]=a[d+1];return u},...i}=n??{};return K(a=>{let u=!0,d=o;return(async()=>{for(;u;)try{let l=await t.xread("BLOCK",r,"STREAMS",e,d);if(!u)return;if(l)for(let[p,f]of l)for(let[m,h]of f)d=m,a.emit({id:m,key:e,data:s(h),timestampNs:oe()})}catch(l){if(!u)return;a.down([[A,l]]);return}})(),()=>{u=!1}},gt(i))}function Cl(t,e,n,r){let{serialize:o=a=>["data",JSON.stringify(a)],maxLen:s,onTransportError:i}=r??{};return We(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 Ll(t,e){let{delimiter:n=",",hasHeader:r=!0,columns:o,parseLine:s,...i}=e??{},a=s??(u=>Dl(u,n));return K(u=>{let d=!1;return(async()=>{try{let l=o,p="";for await(let f of t){if(d)return;p+=f;let m=p.split(/\r?\n/);p=m.pop()??"";for(let h of m){if(d)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(!d&&p.trim()){let f=a(p);if(l){let m={};for(let h=0;h<l.length;h++)m[l[h]]=f[h]??"";u.emit(m)}}d||u.down([[L]])}catch(l){d||u.down([[A,l]])}})(),()=>{d=!0}},gt(i))}function Il(t,e){let{delimiter:n=",",hasHeader:r=!0,columns:o,parseLine:s,...i}=e??{},a=s??(u=>Dl(u,n));return z([t],(u,d,c)=>{let l=u[0];if(l==null||l.length===0)return;let p=c.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 h of m){if(!h.trim())continue;let g=a(h);if(!p.headers&&r){p.headers=g;continue}p.headers||(p.headers=g.map((b,v)=>`col${v}`));let y={};for(let b=0;b<p.headers.length;b++)y[p.headers[b]]=g[b]??"";d.emit(y)}}},{describeKind:"derived",...i})}function Pl(t,e){return z([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 d of u)if(d.trim())try{r.emit(JSON.parse(d))}catch(c){r.down([[A,c]]);return}}},{describeKind:"derived",...e??{}})}function Dl(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 Gl(t,e){return K(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 d=u.trim();d&&n.emit(JSON.parse(d))}}!r&&s.trim()&&n.emit(JSON.parse(s.trim())),r||n.down([[L]])}catch(s){r||n.down([[A,s]])}})(),()=>{r=!0}},gt(e))}function Fl(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 Te(st(0,{period:a,signal:s}),()=>K(d=>{let c=!0;return(async()=>{try{let p=await t.query({query:e,format:o});if(!c)return;let f=await p.json();if(!c)return;for(let m of f)d.emit(m);u=0,d.down([[L]])}catch(p){if(!c)return;u+=1,u>=i&&d.down([[A,p]])}})(),()=>{c=!1}}))}function $l(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 K(a=>{let u=!0;return(async()=>{for(;u;)try{let c=await t.receive();if(!u)return;let l={topic:c.getTopicName(),messageId:c.getMessageId().toString(),key:c.getPartitionKey(),value:r(c.getData()),properties:c.getProperties(),publishTime:c.getPublishTimestamp(),eventTime:c.getEventTimestamp(),timestampNs:oe()};if(n)a.emit(l),t.acknowledge(c).catch(i);else{let p=!1,f={value:l,ack(){p||(p=!0,t.acknowledge(c).catch(i))},nack(m){if(p)return;p=!0;let h=t;try{let g=h.negativeAcknowledge?.(c);g&&typeof g.then=="function"&&g.catch(i)}catch(g){i(g)}}};a.emit(f)}}catch(c){u&&a.down([[A,c]]);return}})(),()=>{u=!1}},gt(s))}function jl(t,e,n){let{serialize:r=a=>Buffer.from(JSON.stringify(a)),keyExtractor:o,propertiesExtractor:s,onTransportError:i}=n??{};return We(t,{onTransportError:i,send:async a=>{await e.send({data:r(a),partitionKey:o?.(a),properties:s?.(a)})}})}function Bl(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 K(a=>{let u=!0,d=t.subscribe(e,o?{queue:o}:void 0);return(async()=>{try{for await(let l of d){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:oe()})}u&&a.down([[L]])}catch(l){u&&a.down([[A,l]])}})(),()=>{u=!1}},gt(i))}function Vl(t,e,n,r){let o=new TextEncoder,{serialize:s=a=>o.encode(JSON.stringify(a)),onTransportError:i}=r??{};return We(t,{onTransportError:i,send:a=>{e.publish(n,s(a))}})}function Kl(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 K(u=>{let d=!0,c;return(async()=>{try{c=(await t.consume(e,f=>{if(!d)return;if(f===null){d&&u.down([[A,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:oe()};if(r){u.emit(m);try{t.ack(f)}catch(h){a(h)}}else{let h=!1,g=t,y={value:m,ack(){if(!h){h=!0;try{t.ack(f)}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(f,!1,v)}catch(T){a(T)}}};u.emit(y)}},{noAck:!1})).consumerTag}catch(p){d&&u.down([[A,p]])}})(),()=>{d=!1,c!==void 0&&t.cancel(c)}},gt(i))}function ql(t,e,n,r){let{serialize:o=a=>Buffer.from(JSON.stringify(a)),routingKeyExtractor:s=()=>"",onTransportError:i}=r??{};return We(t,{onTransportError:i,send:a=>{let u=s(a),d=o(a);e.publish(n,u,d)}})}function Ba(t,e,n){let{serialize:r=l=>`${JSON.stringify(l)}
26
26
  `,flushIntervalMs:o=0,batchSize:s=Number.POSITIVE_INFINITY,onTransportError:i,mode:a}=n??{},d=o>0||s<Number.POSITIVE_INFINITY?We(t,{onTransportError:i,batchSize:s,flushIntervalMs:o,serialize:r,sendBatch:l=>{e.write(l.join(""))}}):We(t,{onTransportError:i,serialize:r,send:l=>{e.write(l)}}),c=d.dispose;return d.dispose=()=>{c();try{e.end()}catch{}},d}function Ga(t,e){return t.includes(e)||t.includes('"')||t.includes(`
27
- `)?`"${t.replace(/"/g,'""')}"`:t}function Kl(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:d,...c}=n,l=!1;return Ba(t,e,{serialize:f=>{if(!l&&s){l=!0;let m=r.map(g=>Ga(g,o)).join(o),h=r.map(g=>Ga(i(f,g),o)).join(o);return`${m}
27
+ `)?`"${t.replace(/"/g,'""')}"`:t}function Hl(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:d,...c}=n,l=!1;return Ba(t,e,{serialize:f=>{if(!l&&s){l=!0;let m=r.map(g=>Ga(g,o)).join(o),h=r.map(g=>Ga(i(f,g),o)).join(o);return`${m}
28
28
  ${h}
29
29
  `}return`${r.map(m=>Ga(i(f,m),o)).join(o)}
30
- `},flushIntervalMs:a,batchSize:u,onTransportError:d,...c})}function ql(t,e,n,r){let{batchSize:o=1e3,flushIntervalMs:s=5e3,format:i="JSONEachRow",transform:a=d=>d,onTransportError:u}=r??{};return We(t,{onTransportError:u,batchSize:o,flushIntervalMs:s,serialize:a,sendBatch:async d=>{await e.insert({table:n,values:d,format:i})}})}function Hl(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:d}=r??{},c=o==="ndjson"?"application/x-ndjson":"application/json",l=0;return We(t,{onTransportError:d,batchSize:i,flushIntervalMs:a,serialize:u,sendBatch:async p=>{l+=1;let f=o==="ndjson"?`${p.map(h=>JSON.stringify(h)).join(`
30
+ `},flushIntervalMs:a,batchSize:u,onTransportError:d,...c})}function Wl(t,e,n,r){let{batchSize:o=1e3,flushIntervalMs:s=5e3,format:i="JSONEachRow",transform:a=d=>d,onTransportError:u}=r??{};return We(t,{onTransportError:u,batchSize:o,flushIntervalMs:s,serialize:a,sendBatch:async d=>{await e.insert({table:n,values:d,format:i})}})}function zl(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:d}=r??{},c=o==="ndjson"?"application/x-ndjson":"application/json",l=0;return We(t,{onTransportError:d,batchSize:i,flushIntervalMs:a,serialize:u,sendBatch:async p=>{l+=1;let f=o==="ndjson"?`${p.map(h=>JSON.stringify(h)).join(`
31
31
  `)}
32
- `:JSON.stringify(p),m=s(l,oe());await e.putObject({Bucket:n,Key:m,Body:f,ContentType:c})}})}function Wl(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 We(t,{onTransportError:s,serialize:i=>o(i,n),send:async i=>{let a=i;await e.query(a.sql,a.params)}})}function zl(t,e,n){let{toDocument:r=s=>s,onTransportError:o}=n??{};return We(t,{onTransportError:o,serialize:r,send:async s=>{await e.insertOne(s)}})}function Ul(t,e,n){let{labels:r={},toLine:o=a=>JSON.stringify(a),toLabels:s,onTransportError:i}=n??{};return We(t,{onTransportError:i,serialize:a=>({line:o(a),labels:s?{...r,...s(a)}:r}),send:async a=>{let{line:u,labels:d}=a,c=`${oe()}`;await e.push({streams:[{stream:d,values:[[c,u]]}]})}})}function Jl(t,e,n){let{toResourceSpans:r=s=>[s],onTransportError:o}=n??{};return We(t,{onTransportError:o,serialize:r,send:async s=>{await e.push({resourceSpans:s})}})}function Yl(t,e,n,r){let{prefix:o="checkpoints/",debounceMs:s=500,compactEvery:i=10,onError:a}=r??{},u={name:`s3:${n}`,debounceMs:s,compactEvery:i,save(d){let c=Math.floor(oe()/1e6),l=`${o}${t.name}/checkpoint-${c}.json`,p;try{p=JSON.stringify(d)}catch(f){a?.(f);return}e.putObject({Bucket:n,Key:l,Body:p,ContentType:"application/json"}).catch(f=>a?.(f))}};return t.attachSnapshotStorage([u],{onError:d=>a?.(d)})}function Ql(t,e,n){let{prefix:r="graphrefly:checkpoint:",debounceMs:o=500,compactEvery:s=10,onError:i}=n??{},a=`${r}${t.name}`,u={name:`redis:${a}`,debounceMs:o,compactEvery:s,save(d){let c;try{c=JSON.stringify(d)}catch(l){i?.(l);return}e.set(a,c).catch(l=>i?.(l))},async load(){let d=await e.get(a);if(d!=null)try{return JSON.parse(d)}catch{return}}};return t.attachSnapshotStorage([u],{onError:d=>i?.(d)})}function Xl(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return K(i=>{try{let u=t.query(e,o).map(r);i.emit(u),i.down([[L]])}catch(a){i.down([[C,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...s})}function Zl(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return K(i=>{try{let a=t.iterate(e,o);X(()=>{for(let u of a)i.emit(r(u));i.down([[L]])})}catch(a){i.down([[C,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...s})}function ep(t,e,n,r){if(n.includes("\0")||n.length===0)throw new Error(`toSqlite: invalid table name: ${JSON.stringify(n)}`);let{toSQL:o=(O,P)=>({sql:`INSERT INTO "${P.replace(/"/g,'""')}" (data) VALUES (?)`,params:[JSON.stringify(O)]}),onTransportError:s,batchInsert:i=!1,maxBatchSize:a=1e3,flushIntervalMs:u=0}=r??{},d=O=>o(O,n);if(!i)return We(t,{onTransportError:s,serialize:d,send:O=>{let P=O;e.query(P.sql,P.params)}});let c=M(null),l=M(void 0,{equals:()=>!1}),p=M(null),f=M(0),m=M(0),h=O=>{try{s?.(O)}catch{}try{c.down([[E,O]])}catch{}},g=[],y=!1,b,v=!1,T=()=>m.down([[E,g.length]]),w=O=>{v||l.down([[E,O]])},x=O=>{v||p.down([[E,O]])},k=O=>{v||f.down([[E,O]])},S=O=>{v||h(O)},R=()=>{if(g.length===0||y)return;y=!0,k(1);try{e.query("BEGIN",[])}catch(j){y=!1,k(0),S({stage:"send",error:j instanceof Error?j:new Error(String(j)),value:void 0});return}let O=g;g=[],T();let P,B=0;for(let j of O)try{e.query(j.query.sql,j.query.params),B+=1}catch(D){P=D instanceof Error?D:new Error(String(D));break}if(P){try{e.query("ROLLBACK",[])}catch{}S({stage:"send",error:P,value:void 0});for(let j of O)x({value:j.value,error:P,attempts:1})}else try{e.query("COMMIT",[]);for(let j of O)w(j.value)}catch(j){let D=j instanceof Error?j:new Error(String(j));S({stage:"send",error:D,value:void 0});for(let Z=0;Z<B;Z++)x({value:O[Z].value,error:D,attempts:1})}y=!1,k(0)},N=()=>{u>0&&b===void 0&&!v&&(b=setTimeout(()=>{b=void 0,R()},u))},_=t.subscribe(O=>{for(let P of O){let B=P[0];if(B===E){let j=P[1],D;try{D=d(j)}catch(Z){let F=Z instanceof Error?Z:new Error(String(Z));h({stage:"serialize",error:F,value:j}),p.down([[E,{value:j,error:F,attempts:0}]]);continue}g.push({value:j,query:D}),T(),g.length>=a?R():N()}else $e.messageTier(B)>=3&&R()}});return{dispose:()=>{if(!v){b!==void 0&&(clearTimeout(b),b=void 0),R(),v=!0,_();for(let O of[c,l,p,f,m])try{O.down([[le]])}catch{}}},sent:l,failed:p,inFlight:f,errors:c,buffered:m,flush:async()=>{v||R()}}}function tp(t,e){let{args:n,mapRow:r=s=>s,...o}=e??{};return K(s=>{let i=!0;return t.findMany(n).then(a=>{i&&(s.emit(a.map(r)),s.down([[L]]))}).catch(a=>{if(i)try{s.down([[C,a instanceof Error?a:new Error(String(a))]])}catch{}}),()=>{i=!1}},{...o,describeKind:"producer",completeWhenDepsComplete:!1})}function np(t,e){let{mapRow:n=o=>o,...r}=e??{};return K(o=>{let s=!0;return t.execute().then(i=>{s&&(o.emit(i.map(n)),o.down([[L]]))}).catch(i=>{if(s)try{o.down([[C,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{s=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}function rp(t,e){let{mapRow:n=o=>o,...r}=e??{};return K(o=>{let s=!0;return t.execute().then(i=>{s&&(o.emit(i.map(n)),o.down([[L]]))}).catch(i=>{if(s)try{o.down([[C,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{s=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}Vn();ae();ee();function Va(){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 op(t){return t!=null&&typeof t.then=="function"}function Zn(t){op(t)&&t.catch(()=>{})}function sp(t,e){let n=new Map,r=e?.maxSize??0,o=r>0?e?.eviction??Va():null,s=e?.writeThrough??!1;function i(d,c,l){for(let p=0;p<l;p++)try{Zn(t[p].save(d,c))}catch{}}function a(d,c,l=0){for(let p=l;p<t.length;p++){let f;try{f=t[p].load(d)}catch{continue}if(op(f)){let m=p;f.then(h=>{h!==void 0?(c.down([[E,h]]),i(d,h,m)):a(d,c,m+1)},()=>{a(d,c,m+1)});return}if(f!==void 0){c.down([[E,f]]),i(d,f,p);return}}}function u(){if(!(!o||r<=0))for(;o.size()>=r;){let d=o.evict(1);if(d.length===0)break;for(let c of d){let l=n.get(c);if(l){let p=l.cache;if(l.status!=="sentinel"&&t.length>0){let f=t.length-1;try{Zn(t[f].save(c,p))}catch{}for(let m=0;m<f;m++)try{let h=t[m].delete;h&&Zn(h.call(t[m],c))}catch{}}l.down([[le]])}n.delete(c)}}}return{load(d){let c=n.get(d);if(c)return o?.touch(d),c;o&&r>0&&o.size()>=r&&u();let l=M(void 0);return n.set(d,l),o?.insert(d),a(d,l),l},save(d,c){if(s)for(let p of t)try{Zn(p.save(d,c))}catch{}else if(t[0])try{Zn(t[0].save(d,c))}catch{}let l=n.get(d);if(l)l.down([[E,c]]),o?.touch(d);else{o&&r>0&&o.size()>=r&&u();let p=M(c);n.set(d,p),o?.insert(d)}},invalidate(d){let c=n.get(d);c&&a(d,c)},delete(d){o?.delete(d);let c=n.get(d);c&&c.down([[le]]),n.delete(d);for(let l of t)try{let p=l.delete;p&&Zn(p.call(l,d))}catch{}},has(d){return n.has(d)},get size(){return n.size}}}Me();ae();ee();Me();xe();ae();ee();var Xr=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=H(),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=H(),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 H()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??H())>=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 Ze(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 Xr({maxSize:n,defaultTtl:r}),u=M(a.toMap(),{name:e,describeKind:"state",equals:(p,f)=>p===f,...o!=null?{versioning:o}:{}});function d(){let p=a.toMap();X(()=>{u.down([[ne]]),u.down([[E,p]])})}function c(){if(!i)return;let p=a.toMap(),f=i.archiveThreshold,m=i.maxSize,h=[];for(let[y,b]of p)h.push({key:y,value:b,score:i.score(y,b)});h.sort((y,b)=>y.score-b.score);let g=new Set;if(f!==void 0)for(let y of h)if(y.score<f)g.add(y.key);else break;if(m!==void 0&&h.length-g.size>m)for(let y of h){if(h.length-g.size<=m)break;g.has(y.key)||g.add(y.key)}if(g.size!==0)for(let y of h)g.has(y.key)&&(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"&&c(),d())}}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(){}}}he();function Pg(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function up(t,e,n){let r=U(t),o=r.v!=null,s=M(n?.initialVerified??null,{...o?{meta:{sourceVersion:null}}:{}}),i=n?.trigger!==void 0&&n.trigger!==null,a=null;if(i&&n?.autoVerify?a=xt(U(n.trigger),r):i?a=U(n.trigger):n?.autoVerify&&(a=r),a!==null){let u;if(a===r)u=Te(r,d=>e(d));else{let d=r.cache;r.subscribe(c=>{for(let l of c)l[0]===E&&(d=l[1])}),u=Te(a,()=>e(d))}qt(u,d=>{X(()=>{if(s.down([[E,d]]),o){let c=r.v;c!=null&&s.meta.sourceVersion.down([[E,{id:c.id,version:c.version}]])}})})}return{node:r,verified:s,trigger:a}}function ip(t){t.subscribe(()=>{})}function Zr(t){return t instanceof Map?t:new Map}function ap(t,e){if(!Array.isArray(e.upsert))throw new TypeError("distill extraction requires upsert: Array<{ key, value }>");X(()=>{for(let{key:n,value:r}of e.upsert)t.set(n,r);for(let n of e.remove??[])t.delete(n)})}function Ls(t,e,n){let r=U(t),o=Ze(n.mapOptions??{}),s=n.budget??2e3,a=n.context!==void 0&&n.context!==null?U(n.context):M(null),u=Zr(o.entries.cache);o.entries.subscribe(f=>{for(let m of f)m[0]===E&&(u=Zr(m[1]))});let d=Te(r,f=>e(f,u));if(qt(d,f=>{ap(o,f)}),n.evict){let f=new Map,m=A([o.entries],([h])=>{let g=[],y=Zr(h);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(Pg(T)){if(!f.has(b)){let w=qt(T,x=>{x===!0&&o.has(b)&&o.delete(b)});f.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});qt(m,h=>{for(let g of h)o.delete(g)})}let c=n.consolidateTrigger!==void 0&&n.consolidateTrigger!==null;if(n.consolidate&&c){let f=U(n.consolidateTrigger),m=Te(f,()=>n.consolidate(u));qt(m,h=>{ap(o,h)})}let l=A([o.entries,a],([f,m])=>{let h=[...Zr(f).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}),p=A([o.entries],([f])=>Zr(f).size);return ip(l),ip(p),{store:o,compact:l,size:p}}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+=dp[r[s]];return o}var dp=new Array(256);for(let t=0;t<256;t++)dp[t]=t.toString(16).padStart(2,"0");var eo=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 to(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 Ps(t){let{storage:e,keyContext:n,keyPrefix:r,mode:o="read-write"}=t,s=n??(a=>a);async function i(a){let u=to(s(a)),d=await Is(u);return r?`${r}:${d}`:d}return{keyFor:i,async lookup(a){if(o==="write")return;let u=await i(a),d=await e.load(u);if(d===void 0){if(o==="read-strict")throw new eo(u,a);return}return d},async store(a,u){if(o==="read")return;let d=await i(a);await e.save(d,u)},async forget(a){if(o==="read"||o==="write"||!e.delete)return;let u=await i(a);await e.delete(u)}}}aa();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}Me();ae();_e();var no=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 cp(t={}){let{backend:e}=t,n=e??new no,r=new Map;function o(s){let i=r.get(s);return i===void 0&&(i=z({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){X(()=>{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([[le]]),!0)},has(s){return n.hasTopic(s)},get size(){return n.topicCount},topicNames(){return n.topicNames()}}}Me();ae();ee();function lp(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 Dg(t,e){let n=lp(t[0],e[0]);return n!==0?n:lp(t[1],e[1])}function pp(t){return[t.secondary,t.primary]}function er(t,e){let n=pp(e),r=0,o=t.length;for(;r<o;){let s=r+o>>1;Dg(n,pp(t[s]))>0?r=s+1:o=s}return r}var ro=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 Gg(t){return t.subscribe(()=>{})}function fp(t={}){let{name:e,versioning:n,equals:r,backend:o}=t,s=o??new ro;function i(f){return f?.equals!==void 0||r===void 0?f:{...f,equals:r}}let a=M([],{name:e,describeKind:"state",equals:(f,m)=>f===m,...n!=null?{versioning:n}:{}}),u=A([a],([f])=>{let m=f,h=new Map;for(let g of m)h.set(g.primary,g.value);return h},{initial:s.toPrimaryMap(),describeKind:"derived"}),d=Gg(u),c=!1;function l(){let f=s.toArray();X(()=>{a.down([[ne]]),a.down([[E,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,h,g){return p(()=>s.upsert(f,m,h,i(g)))},upsertMany(f,m){let h=[...f];h.length!==0&&p(()=>s.upsertMany(h,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(){c||(c=!0,d())}}}Me();ae();ee();var oo=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 Ds(t,e={}){let{name:n,versioning:r,backend:o}=e,s=o??new oo(t),i=M(s.toArray(),{name:n,describeKind:"state",equals:(d,c)=>d===c,...r!=null?{versioning:r}:{}});function a(){let d=s.toArray();X(()=>{i.down([[ne]]),i.down([[E,d]])})}function u(d){let c=s.version;try{return d()}finally{s.version!==c&&a()}}return{items:i,get size(){return s.size},at(d){return s.at(d)},append(d){u(()=>s.append(d))},appendMany(d){u(()=>s.appendMany(d))},insert(d,c){u(()=>s.insert(d,c))},insertMany(d,c){u(()=>s.insertMany(d,c))},pop(d=-1){return u(()=>s.pop(d))},clear(){u(()=>s.clear())},dispose(){}}}Ot();ae();he();function Gs(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=Ye(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 d,c=()=>{r.get(s)===d&&r.delete(s)};return d=u.then(l=>(c(),l),l=>{throw c(),l}),r.set(s,d),d}}function mp(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(d=>{for(let c of d)if(c[0]===C||c[0]===L){r.get(s)===a&&r.delete(s),u();return}});return a}}he();function so(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(so);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=so(e[o]);return r}function Fs(t){return JSON.stringify(so(t),void 0,0)}var Fg=new TextEncoder,$g=new TextDecoder("utf-8",{fatal:!0}),tr={name:"json",version:1,encode(t){return Fg.encode(Fs(t))},decode(t){return JSON.parse($g.decode(t))}};function gp(){return tr}function io(){let t=new Map;return{name:"memory",read(e){let n=t.get(e);return n===void 0?void 0:new Uint8Array(n)},write(e,n){t.set(e,new Uint8Array(n))},delete(e){t.delete(e)},list(e){let n=[...t.keys()];return e?n.filter(r=>r.startsWith(e)).sort():n.sort()}}}function $s(t,e={}){let n=e.codec??tr,r=e.name??t.name??"snapshot",o=e.keyOf??(l=>l.name??e.name??t.name??"snapshot"),s,i=0,a=e.compactEvery,u,d={name:r,debounceMs:e.debounceMs,compactEvery:a,filter:e.filter,keyOf:o,save(l){if(!(e.filter&&!e.filter(l))&&(s={snapshot:l},i+=1,a!==void 0&&i%a===0||!e.debounceMs))return c()},load(){let l=u??r,p=t.read(l);if(p!==void 0)return p instanceof Uint8Array?p.length===0?void 0:n.decode(p):Promise.resolve(p).then(f=>f===void 0||f.length===0?void 0:n.decode(f))},async flush(){await c()},async rollback(){s=void 0}};function c(){let l=s;if(!l)return;s=void 0;let p=o(l.snapshot),f=n.encode(l.snapshot),m=t.write(p,f);if(m instanceof Promise)return m.then(()=>{u=p});u=p}return d}function Ka(t,e={}){let n=e.codec??tr,r=e.name??t.name??"append-log",o=e.keyOf??(p=>r),s=e.compactEvery,i=new Map,a=0,u,d={name:r,debounceMs:e.debounceMs,compactEvery:s,keyOf:o,appendEntries(p){if(p.length!==0){for(let f of p){let m=o(f),h=i.get(m);h||(h=[],i.set(m,h)),h.push(f)}if(a+=p.length,s!==void 0&&a%s===0||!e.debounceMs)return c()}},async loadEntries(p){let f=p?.keyFilter,m=t.list===void 0?f!==void 0?[f]:[r]:await Promise.resolve(t.list(f)),h=[];for(let g of m){let y=await Promise.resolve(t.read(g));if(y===void 0||y.length===0)continue;let b=n.decode(y);Array.isArray(b)&&h.push(...b)}return{entries:h,cursor:void 0}},async flush(){await c()},async rollback(){i=new Map}};function c(){if(i.size===0)return;let p=i;i=new Map;let f=(u??Promise.resolve()).then(()=>{let m=l(p);return m instanceof Promise?m:Promise.resolve()},()=>{let m=l(p);return m instanceof Promise?m:Promise.resolve()});return u=f.finally(()=>{u===f&&(u=void 0)}),u}function l(p){let f=[];for(let[m,h]of p){let g=t.read(m),y=b=>{let T=[...b===void 0||b.length===0?[]:n.decode(b)??[],...h],w=n.encode(T);return t.write(m,w)};if(g instanceof Promise)f.push(g.then(async b=>{let v=y(b);v instanceof Promise&&await v}));else{let b=y(g);b instanceof Promise&&f.push(b)}}if(f.length>0)return Promise.all(f).then(()=>{})}return d}function js(t,e={}){let n=e.codec??tr,r=e.name??t.name??"kv",o=e.compactEvery,s=new Map,i=0,a={name:r,debounceMs:e.debounceMs,compactEvery:o,filter:e.filter,save(d,c){if(!(e.filter&&!e.filter(d,c))&&(s.set(d,c),i+=1,o!==void 0&&i%o===0||!e.debounceMs))return u()},load(d){let c=t.read(d);if(c!==void 0)return c instanceof Uint8Array?c.length===0?void 0:n.decode(c):Promise.resolve(c).then(l=>l===void 0||l.length===0?void 0:n.decode(l))},delete(d){if(s.delete(d),!!t.delete)return t.delete(d)},list(d){return t.list?t.list(d):[]},async flush(){await u()},async rollback(){s=new Map}};function u(){if(s.size===0)return;let d=s;s=new Map;let c=[];for(let[l,p]of d){let f=n.encode(p),m=t.write(l,f);m instanceof Promise&&c.push(m)}if(c.length>0)return Promise.all(c).then(()=>{})}return a}function hp(t){return $s(io(),t)}function yp(t){return Ka(io(),t)}function ao(t){return js(io(),t)}function bp(t,e){let n={name:e?.name??"dict-kv",read(r){return t[r]},write(r,o){t[r]=new Uint8Array(o)},delete(r){delete t[r]},list(r){let o=Object.keys(t).sort();return r?o.filter(s=>s.startsWith(r)):o}};return js(n,e)}function vp(t,e){return $s({name:"dict",read(r){return t[r]},write(r,o){t[r]=new Uint8Array(o)},delete(r){delete t[r]},list(r){let o=Object.keys(t).sort();return r?o.filter(s=>s.startsWith(r)):o}},e)}ae();_e();ee();function uo(t,e,n,r){let o=new Y(t,r);o.add(e,{name:"source"});let s=M(n,{meta:{kind:"stratify_rules"}});o.add(s,{name:"rules"});for(let i of n)jg(o,e,s,i);return o}function jg(t,e,n,r){let o=`branch/${r.name}`,s=Symbol("noValue"),i=!1,a=!1,u=!1,d=s,c=!1,l=n.cache??[];function p(h){if(u){u=!1;let g=d;if(d=s,g!==s){let y=l.find(v=>v.name===r.name),b=!1;try{b=y?.classify(g)??!1}catch{b=!1}b?(c=!1,h.emit(g)):c&&(c=!1,h.down([[ne],[V]]))}else c?(c=!1,h.down([[ne],[V]])):h.down([[V]])}}let f=z([],(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===ne?(g===0?(i=!0,c=!0):a=!0,!0):b===E||b===V?(g===0?(i=!1,u=!0,d=b===E?h[1]:s):(b===E&&(l=h[1]),a=!1),i||a||p(y),!0):b===L||b===C||b===le?(i=!1,a=!1,u=!1,d=s,c=!1,g===0&&y.down([h]),!0):g===1}if(t.add(f,{name:o}),r.ops){let h=r.ops(f),g=`branch/${r.name}/out`;t.add(h,{name:g})}}vt();Me();ae();_e();ee();he();ae();var Bg=new Map([[Je,"INVALIDATE"],[Be,"PAUSE"],[qe,"RESUME"],[le,"TEARDOWN"],[L,"COMPLETE"],[C,"ERROR"]]),Vg=new Map([["INVALIDATE",Je],["PAUSE",Be],["RESUME",qe],["TEARDOWN",le],["COMPLETE",L],["ERROR",C]]);function Ut(t){let e=Bg.get(t);return e||(Symbol.keyFor(t)??"UNKNOWN")}function gn(t){let e=Vg.get(t);if(e)return e;if(t&&t!=="UNKNOWN")return Symbol.for(t)}function hn(t){return t instanceof Error?{message:t.message,name:t.name,stack:t.stack}:{message:String(t),name:"Error"}}function yn(t){let e=new Error(t.message);return e.name=t.name,t.stack&&(e.stack=t.stack),e}function Jt(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 Jt(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 Kg(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function qa(t,e){let n=Kg(t)?t:Jt(t),r=e.name??"workerBridge",o=Object.entries(e.expose??{}),s=e.import??[],i=e.transfer??{},a=M("connecting",{name:`${r}::meta::status`}),u=M(null,{name:`${r}::meta::error`}),d=new Map,c=new Map;for(let b of s){let v=M(void 0,{name:`${r}::${b}`});d.set(b,v)}let l;if(o.length>0){let b=o.map(([,w])=>w),v=z(b,(w,x)=>{let k={};for(let S=0;S<o.length;S++){let[R]=o[S],N=w[S];N!=null&&N.length>0&&(k[R]=N.at(-1))}Object.keys(k).length!==0&&x.emit(k)},{name:`${r}::aggregated`,partial:!0});l=pe([v],w=>{let x=w[0];if(x==null||Object.keys(x).length===0)return;let k=[];for(let N of Object.keys(x)){let _=i[N];_&&k.push(..._(x[N]))}let S;for(let[N,_]of o)N in x&&_.v!=null&&(S==null&&(S={}),S[N]=_.v.version);let R={t:"b",u:x,...S?{v:S}:{}};try{n.post(R,k.length>0?k:void 0)}catch(N){u.down([[E,N instanceof Error?N:new Error(String(N))]])}}).subscribe(()=>{})}let p=!1,f=n.listen(b=>{if(p)return;let v=b;switch(v.t){case"r":{X(()=>{for(let[w,x]of Object.entries(v.stores)){let k=d.get(w);k&&k.down([[E,x]])}}),a.down([[E,"connected"]]);let T={};for(let[w,x]of o)T[w]=x.cache;n.post({t:"i",stores:T});break}case"v":{let T=d.get(v.s);T&&T.down([[E,v.d]]);break}case"b":{X(()=>{for(let[T,w]of Object.entries(v.u)){let x=v.v?.[T];if(x!=null){let S=c.get(T);if(S!=null&&x<=S)continue;c.set(T,x)}let k=d.get(T);k&&k.down([[E,w]])}});break}case"e":{let T=d.get(v.s);T&&T.down([[C,yn(v.err)]]);break}case"s":{let T=gn(v.sig);if(!T)break;let w=v.s==="*"?[...d.values()]:d.has(v.s)?[d.get(v.s)]:[];for(let x of w)x.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 x of w){let k=x[0];k!==E&&($e.isLocalOnly(k)||(k===C?n.post({t:"e",s:b,err:hn(x[1])}):n.post({t:"s",s:b,sig:Ut(k),d:x.length>1?x[1]:void 0})))}}));m.push(T)}let h;if(e.timeoutMs!=null&&e.timeoutMs>0){let b=st(e.timeoutMs),v=Xe(a,w=>w==="connected");h=Cs(xt(zr(b,()=>"timeout"),zr(v,()=>"ready"))).subscribe(w=>{for(let x of w)x[0]===E&&x[1]==="timeout"&&(u.down([[E,new Error("Worker bridge handshake timeout")]]),g())})}function g(){if(!p){p=!0,h?.(),n.post({t:"s",s:"*",sig:Ut(le)}),l&&l();for(let b of m)b();m.length=0,f(),a.down([[E,"closed"]]),c.clear(),d.clear()}}let y={meta:{status:a,error:u},destroy:g};for(let[b,v]of d)y[b]=v;return y}Me();ae();_e();ee();function qg(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function Ha(t,e){let n=qg(t)?t:Jt(t),r=e.import??[],o=e.transfer??{},s=new Map,i=new Map,a={};for(let g of r){let y=M(void 0,{name:`worker::${g}`});s.set(g,y),a[g]=y}let u=e.expose(a),d=Object.entries(u),c,l=!1;if(d.length>0){let g=d.map(([,v])=>v),y=z(g,(v,T)=>{let w={};for(let x=0;x<d.length;x++){let[k]=d[x],S=v[x];S!=null&&S.length>0&&(w[k]=S.at(-1))}Object.keys(w).length!==0&&T.emit(w)},{name:"workerSelf::aggregated",partial:!0});c=pe([y],v=>{if(l)return;let T=v[0];if(T==null||Object.keys(T).length===0)return;let w=[];for(let S of Object.keys(T)){let R=o[S];R&&w.push(...R(T[S]))}let x;for(let[S,R]of d)S in T&&R.v!=null&&(x==null&&(x={}),x[S]=R.v.version);let k={t:"b",u:T,...x?{v:x}:{}};try{n.post(k,w.length>0?w:void 0)}catch{}}).subscribe(()=>{})}let p=[];for(let[g,y]of d){let b=y.subscribe((v=>{if(!l)for(let T of v){let w=T[0];w!==E&&($e.isLocalOnly(w)||(w===C?n.post({t:"e",s:g,err:hn(T[1])}):n.post({t:"s",s:g,sig:Ut(w),d:T.length>1?T[1]:void 0})))}}));p.push(b)}let f=n.listen(g=>{if(l)return;let y=g;switch(y.t){case"i":{X(()=>{for(let[b,v]of Object.entries(y.stores)){let T=s.get(b);T&&T.down([[E,v]])}});break}case"v":{let b=s.get(y.s);b&&b.down([[E,y.d]]);break}case"b":{X(()=>{for(let[b,v]of Object.entries(y.u)){let T=y.v?.[b];if(T!=null){let x=i.get(b);if(x!=null&&T<=x)continue;i.set(b,T)}let w=s.get(b);w&&w.down([[E,v]])}});break}case"e":{let b=s.get(y.s);b&&b.down([[C,yn(y.err)]]);break}case"s":{let b=gn(y.sig);if(!b)break;if(b===le&&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 d)m[g]=y.cache;n.post({t:"r",stores:m});function h(){if(!l){l=!0,c&&c();for(let g of p)g();p.length=0,f(),n.terminate?.(),i.clear(),s.clear()}}return{destroy:h}}var Qu={};ke(Qu,{SNAPSHOT_WIRE_VERSION:()=>No,SurfaceError:()=>Ne,accountability:()=>yi,ai:()=>mi,asSurfaceError:()=>Fi,cqrs:()=>Ts,createGraph:()=>pr,deleteSnapshot:()=>Hi,demoShell:()=>vi,diffSnapshots:()=>Ki,domainTemplates:()=>Ti,graphspec:()=>fi,guarded:()=>ki,harness:()=>Ai,jobQueue:()=>Oi,layout:()=>Di,lens:()=>Ii,listSnapshots:()=>qi,memory:()=>ci,messaging:()=>oi,orchestration:()=>si,process:()=>Pi,reduction:()=>pi,refine:()=>Si,resilientPipeline:()=>Gi,restoreSnapshot:()=>Vi,runReduction:()=>$i,saveSnapshot:()=>Bi,surface:()=>Wi});var mi={};ke(mi,{AgentLoopGraph:()=>ui,AllTiersExhaustedError:()=>po,BudgetExhaustedError:()=>Js,ChatStreamGraph:()=>ii,CircuitOpenError:()=>pt,DEFAULT_DECAY_RATE:()=>Tu,FallbackMissError:()=>Xg,LLMTimeoutError:()=>rr,ReplayCacheMissError:()=>Tn,ToolRegistryGraph:()=>ai,admissionFilter3D:()=>ry,admissionScored:()=>qp,agentLoop:()=>ey,agentMemory:()=>ay,anthropicAdapter:()=>za,canonicalJson:()=>Ja,cascadingLlmAdapter:()=>uu,chatStream:()=>pu,composePricing:()=>yh,computePrice:()=>tu,contentGate:()=>Yh,costMeterExtractor:()=>qh,createAdapter:()=>ph,createCapabilitiesRegistry:()=>Hg,createPricingRegistry:()=>gh,dryRunAdapter:()=>bn,fallbackAdapter:()=>Ya,fromLLM:()=>Ch,frozenContext:()=>Ph,gatedStream:()=>Bh,gaugesAsContext:()=>uy,googleAdapter:()=>Qa,graphFromSpec:()=>tf,graphFromSpecReactive:()=>vy,handoff:()=>ty,keywordFlagExtractor:()=>Wh,knobsAsTools:()=>wy,llmConsolidator:()=>hu,llmExtractor:()=>gu,memoryRetrieval:()=>Ru,memoryWithKG:()=>ku,memoryWithTiers:()=>xu,memoryWithVectors:()=>wu,observableAdapter:()=>fh,openAICompatAdapter:()=>Za,parseRateLimitFromError:()=>su,pricingFor:()=>bh,promptNode:()=>wn,redactor:()=>Qh,registryPricing:()=>hh,resilientAdapter:()=>Oh,streamExtractor:()=>zh,streamingPromptNode:()=>jh,suggestStrategy:()=>nf,suggestStrategyReactive:()=>xy,systemPromptBuilder:()=>Vh,tier:()=>_h,toolCallExtractor:()=>Jh,toolExecution:()=>fu,toolRegistry:()=>mu,toolSelector:()=>ny,validateGraphDef:()=>Ry,withBreaker:()=>nu,withBudgetGate:()=>ou,withDryRun:()=>Th,withRateLimiter:()=>au,withReplayCache:()=>lo,withRetry:()=>du,withTimeout:()=>cu,zeroPrice:()=>Us});ee();function co(t,e){return`${t}::${e}`}function Hg(t){let e=Ze({name:"capabilitiesRegistry"}),n=d=>{e.set(co(d.provider,d.id),d)};if(t)for(let d of t)n(d);let r=(d,c)=>{let l=e.get(co(d,c));if(l)return l;let p=e.entries.cache;if(!p)return;let f;for(let[,m]of p){if(m.provider!==d)continue;let h=m.id;c.startsWith(h)&&(!f||h.length>f.id.length)&&(f=m)}return f},o=128,s=new Map,i=new Map,a=(d,c,l,p)=>{for(d.has(c)&&d.delete(c),d.set(c,l);d.size>p;){let f=d.keys().next().value;if(f===void 0)break;d.delete(f)}},u=A([e.entries],([d])=>Array.from(d.values()),{name:"capabilitiesRegistry/entries",initial:[]});return{register:n,lookup:r,remove(d,c){let l=e.has(co(d,c));return l&&e.delete(co(d,c)),l},entries(){let d=e.entries.cache;return(function*(){if(d)for(let c of d.values())yield c})()},lookupNode(d,c){let l=co(d,c),p=s.get(l);if(p)return s.delete(l),s.set(l,p),p;let f=A([e.entries],()=>r(d,c),{name:`capabilitiesRegistry/lookup/${d}::${c}`,initial:void 0});return a(s,l,f,o),f},entriesNode:u,byProvider(d){let c=i.get(d);if(c)return i.delete(d),i.set(d,c),c;let l=A([u],([p])=>p.filter(f=>f.provider===d),{name:`capabilitiesRegistry/byProvider/${d}`,initial:[]});return a(i,d,l,o),l}}}xe();function za(t={}){return t.sdk?Yg(t):Jg(t)}function Bs(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}=Wg(t,e?.systemPrompt),a={model:o,messages:i.map(zg),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(Ug)),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 Wg(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,oe());await e.putObject({Bucket:n,Key:m,Body:f,ContentType:c})}})}function Ul(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 We(t,{onTransportError:s,serialize:i=>o(i,n),send:async i=>{let a=i;await e.query(a.sql,a.params)}})}function Jl(t,e,n){let{toDocument:r=s=>s,onTransportError:o}=n??{};return We(t,{onTransportError:o,serialize:r,send:async s=>{await e.insertOne(s)}})}function Yl(t,e,n){let{labels:r={},toLine:o=a=>JSON.stringify(a),toLabels:s,onTransportError:i}=n??{};return We(t,{onTransportError:i,serialize:a=>({line:o(a),labels:s?{...r,...s(a)}:r}),send:async a=>{let{line:u,labels:d}=a,c=`${oe()}`;await e.push({streams:[{stream:d,values:[[c,u]]}]})}})}function Ql(t,e,n){let{toResourceSpans:r=s=>[s],onTransportError:o}=n??{};return We(t,{onTransportError:o,serialize:r,send:async s=>{await e.push({resourceSpans:s})}})}function Xl(t,e,n,r){let{prefix:o="checkpoints/",debounceMs:s=500,compactEvery:i=10,onError:a}=r??{},u={name:`s3:${n}`,debounceMs:s,compactEvery:i,save(d){let c=Math.floor(oe()/1e6),l=`${o}${t.name}/checkpoint-${c}.json`,p;try{p=JSON.stringify(d)}catch(f){a?.(f);return}e.putObject({Bucket:n,Key:l,Body:p,ContentType:"application/json"}).catch(f=>a?.(f))}};return t.attachSnapshotStorage([u],{onError:d=>a?.(d)})}function Zl(t,e,n){let{prefix:r="graphrefly:checkpoint:",debounceMs:o=500,compactEvery:s=10,onError:i}=n??{},a=`${r}${t.name}`,u={name:`redis:${a}`,debounceMs:o,compactEvery:s,save(d){let c;try{c=JSON.stringify(d)}catch(l){i?.(l);return}e.set(a,c).catch(l=>i?.(l))},async load(){let d=await e.get(a);if(d!=null)try{return JSON.parse(d)}catch{return}}};return t.attachSnapshotStorage([u],{onError:d=>i?.(d)})}function ep(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return K(i=>{try{let u=t.query(e,o).map(r);i.emit(u),i.down([[L]])}catch(a){i.down([[A,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...s})}function tp(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return K(i=>{try{let a=t.iterate(e,o);X(()=>{for(let u of a)i.emit(r(u));i.down([[L]])})}catch(a){i.down([[A,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...s})}function np(t,e,n,r){if(n.includes("\0")||n.length===0)throw new Error(`toSqlite: invalid table name: ${JSON.stringify(n)}`);let{toSQL:o=(O,P)=>({sql:`INSERT INTO "${P.replace(/"/g,'""')}" (data) VALUES (?)`,params:[JSON.stringify(O)]}),onTransportError:s,batchInsert:i=!1,maxBatchSize:a=1e3,flushIntervalMs:u=0}=r??{},d=O=>o(O,n);if(!i)return We(t,{onTransportError:s,serialize:d,send:O=>{let P=O;e.query(P.sql,P.params)}});let c=M(null),l=M(void 0,{equals:()=>!1}),p=M(null),f=M(0),m=M(0),h=O=>{try{s?.(O)}catch{}try{c.down([[E,O]])}catch{}},g=[],y=!1,b,v=!1,T=()=>m.down([[E,g.length]]),w=O=>{v||l.down([[E,O]])},k=O=>{v||p.down([[E,O]])},x=O=>{v||f.down([[E,O]])},S=O=>{v||h(O)},R=()=>{if(g.length===0||y)return;y=!0,x(1);try{e.query("BEGIN",[])}catch(j){y=!1,x(0),S({stage:"send",error:j instanceof Error?j:new Error(String(j)),value:void 0});return}let O=g;g=[],T();let P,B=0;for(let j of O)try{e.query(j.query.sql,j.query.params),B+=1}catch(D){P=D instanceof Error?D:new Error(String(D));break}if(P){try{e.query("ROLLBACK",[])}catch{}S({stage:"send",error:P,value:void 0});for(let j of O)k({value:j.value,error:P,attempts:1})}else try{e.query("COMMIT",[]);for(let j of O)w(j.value)}catch(j){let D=j instanceof Error?j:new Error(String(j));S({stage:"send",error:D,value:void 0});for(let Z=0;Z<B;Z++)k({value:O[Z].value,error:D,attempts:1})}y=!1,x(0)},N=()=>{u>0&&b===void 0&&!v&&(b=setTimeout(()=>{b=void 0,R()},u))},_=t.subscribe(O=>{for(let P of O){let B=P[0];if(B===E){let j=P[1],D;try{D=d(j)}catch(Z){let F=Z instanceof Error?Z:new Error(String(Z));h({stage:"serialize",error:F,value:j}),p.down([[E,{value:j,error:F,attempts:0}]]);continue}g.push({value:j,query:D}),T(),g.length>=a?R():N()}else $e.messageTier(B)>=3&&R()}});return{dispose:()=>{if(!v){b!==void 0&&(clearTimeout(b),b=void 0),R(),v=!0,_();for(let O of[c,l,p,f,m])try{O.down([[de]])}catch{}}},sent:l,failed:p,inFlight:f,errors:c,buffered:m,flush:async()=>{v||R()}}}function rp(t,e){let{args:n,mapRow:r=s=>s,...o}=e??{};return K(s=>{let i=!0;return t.findMany(n).then(a=>{i&&(s.emit(a.map(r)),s.down([[L]]))}).catch(a=>{if(i)try{s.down([[A,a instanceof Error?a:new Error(String(a))]])}catch{}}),()=>{i=!1}},{...o,describeKind:"producer",completeWhenDepsComplete:!1})}function op(t,e){let{mapRow:n=o=>o,...r}=e??{};return K(o=>{let s=!0;return t.execute().then(i=>{s&&(o.emit(i.map(n)),o.down([[L]]))}).catch(i=>{if(s)try{o.down([[A,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{s=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}function sp(t,e){let{mapRow:n=o=>o,...r}=e??{};return K(o=>{let s=!0;return t.execute().then(i=>{s&&(o.emit(i.map(n)),o.down([[L]]))}).catch(i=>{if(s)try{o.down([[A,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{s=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}Vn();ae();ee();function Va(){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 ip(t){return t!=null&&typeof t.then=="function"}function Zn(t){ip(t)&&t.catch(()=>{})}function ap(t,e){let n=new Map,r=e?.maxSize??0,o=r>0?e?.eviction??Va():null,s=e?.writeThrough??!1;function i(d,c,l){for(let p=0;p<l;p++)try{Zn(t[p].save(d,c))}catch{}}function a(d,c,l=0){for(let p=l;p<t.length;p++){let f;try{f=t[p].load(d)}catch{continue}if(ip(f)){let m=p;f.then(h=>{h!==void 0?(c.down([[E,h]]),i(d,h,m)):a(d,c,m+1)},()=>{a(d,c,m+1)});return}if(f!==void 0){c.down([[E,f]]),i(d,f,p);return}}}function u(){if(!(!o||r<=0))for(;o.size()>=r;){let d=o.evict(1);if(d.length===0)break;for(let c of d){let l=n.get(c);if(l){let p=l.cache;if(l.status!=="sentinel"&&t.length>0){let f=t.length-1;try{Zn(t[f].save(c,p))}catch{}for(let m=0;m<f;m++)try{let h=t[m].delete;h&&Zn(h.call(t[m],c))}catch{}}l.down([[de]])}n.delete(c)}}}return{load(d){let c=n.get(d);if(c)return o?.touch(d),c;o&&r>0&&o.size()>=r&&u();let l=M(void 0);return n.set(d,l),o?.insert(d),a(d,l),l},save(d,c){if(s)for(let p of t)try{Zn(p.save(d,c))}catch{}else if(t[0])try{Zn(t[0].save(d,c))}catch{}let l=n.get(d);if(l)l.down([[E,c]]),o?.touch(d);else{o&&r>0&&o.size()>=r&&u();let p=M(c);n.set(d,p),o?.insert(d)}},invalidate(d){let c=n.get(d);c&&a(d,c)},delete(d){o?.delete(d);let c=n.get(d);c&&c.down([[de]]),n.delete(d);for(let l of t)try{let p=l.delete;p&&Zn(p.call(l,d))}catch{}},has(d){return n.has(d)},get size(){return n.size}}}Me();ae();ee();Me();xe();ae();ee();var Xr=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=H(),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=H(),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 H()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??H())>=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 Ze(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 Xr({maxSize:n,defaultTtl:r}),u=M(a.toMap(),{name:e,describeKind:"state",equals:(p,f)=>p===f,...o!=null?{versioning:o}:{}});function d(){let p=a.toMap();X(()=>{u.down([[ne]]),u.down([[E,p]])})}function c(){if(!i)return;let p=a.toMap(),f=i.archiveThreshold,m=i.maxSize,h=[];for(let[y,b]of p)h.push({key:y,value:b,score:i.score(y,b)});h.sort((y,b)=>y.score-b.score);let g=new Set;if(f!==void 0)for(let y of h)if(y.score<f)g.add(y.key);else break;if(m!==void 0&&h.length-g.size>m)for(let y of h){if(h.length-g.size<=m)break;g.has(y.key)||g.add(y.key)}if(g.size!==0)for(let y of h)g.has(y.key)&&(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"&&c(),d())}}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(){}}}he();function Fg(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function cp(t,e,n){let r=U(t),o=r.v!=null,s=M(n?.initialVerified??null,{...o?{meta:{sourceVersion:null}}:{}}),i=n?.trigger!==void 0&&n.trigger!==null,a=null;if(i&&n?.autoVerify?a=xt(U(n.trigger),r):i?a=U(n.trigger):n?.autoVerify&&(a=r),a!==null){let u;if(a===r)u=Te(r,d=>e(d));else{let d=r.cache;r.subscribe(c=>{for(let l of c)l[0]===E&&(d=l[1])}),u=Te(a,()=>e(d))}qt(u,d=>{X(()=>{if(s.down([[E,d]]),o){let c=r.v;c!=null&&s.meta.sourceVersion.down([[E,{id:c.id,version:c.version}]])}})})}return{node:r,verified:s,trigger:a}}function up(t){t.subscribe(()=>{})}function Zr(t){return t instanceof Map?t:new Map}function dp(t,e){if(!Array.isArray(e.upsert))throw new TypeError("distill extraction requires upsert: Array<{ key, value }>");X(()=>{for(let{key:n,value:r}of e.upsert)t.set(n,r);for(let n of e.remove??[])t.delete(n)})}function Ls(t,e,n){let r=U(t),o=Ze(n.mapOptions??{}),s=n.budget??2e3,a=n.context!==void 0&&n.context!==null?U(n.context):M(null),u=Zr(o.entries.cache);o.entries.subscribe(f=>{for(let m of f)m[0]===E&&(u=Zr(m[1]))});let d=Te(r,f=>e(f,u));if(qt(d,f=>{dp(o,f)}),n.evict){let f=new Map,m=C([o.entries],([h])=>{let g=[],y=Zr(h);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(Fg(T)){if(!f.has(b)){let w=qt(T,k=>{k===!0&&o.has(b)&&o.delete(b)});f.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});qt(m,h=>{for(let g of h)o.delete(g)})}let c=n.consolidateTrigger!==void 0&&n.consolidateTrigger!==null;if(n.consolidate&&c){let f=U(n.consolidateTrigger),m=Te(f,()=>n.consolidate(u));qt(m,h=>{dp(o,h)})}let l=C([o.entries,a],([f,m])=>{let h=[...Zr(f).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}),p=C([o.entries],([f])=>Zr(f).size);return up(l),up(p),{store:o,compact:l,size:p}}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+=lp[r[s]];return o}var lp=new Array(256);for(let t=0;t<256;t++)lp[t]=t.toString(16).padStart(2,"0");var eo=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 to(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 Ps(t){let{storage:e,keyContext:n,keyPrefix:r,mode:o="read-write"}=t,s=n??(a=>a);async function i(a){let u=to(s(a)),d=await Is(u);return r?`${r}:${d}`:d}return{keyFor:i,async lookup(a){if(o==="write")return;let u=await i(a),d=await e.load(u);if(d===void 0){if(o==="read-strict")throw new eo(u,a);return}return d},async store(a,u){if(o==="read")return;let d=await i(a);await e.save(d,u)},async forget(a){if(o==="read"||o==="write"||!e.delete)return;let u=await i(a);await e.delete(u)}}}aa();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}Me();ae();_e();var no=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 pp(t={}){let{backend:e}=t,n=e??new no,r=new Map;function o(s){let i=r.get(s);return i===void 0&&(i=z({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){X(()=>{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()}}}Me();ae();ee();function fp(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 $g(t,e){let n=fp(t[0],e[0]);return n!==0?n:fp(t[1],e[1])}function mp(t){return[t.secondary,t.primary]}function er(t,e){let n=mp(e),r=0,o=t.length;for(;r<o;){let s=r+o>>1;$g(n,mp(t[s]))>0?r=s+1:o=s}return r}var ro=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 jg(t){return t.subscribe(()=>{})}function gp(t={}){let{name:e,versioning:n,equals:r,backend:o}=t,s=o??new ro;function i(f){return f?.equals!==void 0||r===void 0?f:{...f,equals:r}}let a=M([],{name:e,describeKind:"state",equals:(f,m)=>f===m,...n!=null?{versioning:n}:{}}),u=C([a],([f])=>{let m=f,h=new Map;for(let g of m)h.set(g.primary,g.value);return h},{initial:s.toPrimaryMap(),describeKind:"derived"}),d=jg(u),c=!1;function l(){let f=s.toArray();X(()=>{a.down([[ne]]),a.down([[E,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,h,g){return p(()=>s.upsert(f,m,h,i(g)))},upsertMany(f,m){let h=[...f];h.length!==0&&p(()=>s.upsertMany(h,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(){c||(c=!0,d())}}}Me();ae();ee();var oo=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 Ds(t,e={}){let{name:n,versioning:r,backend:o}=e,s=o??new oo(t),i=M(s.toArray(),{name:n,describeKind:"state",equals:(d,c)=>d===c,...r!=null?{versioning:r}:{}});function a(){let d=s.toArray();X(()=>{i.down([[ne]]),i.down([[E,d]])})}function u(d){let c=s.version;try{return d()}finally{s.version!==c&&a()}}return{items:i,get size(){return s.size},at(d){return s.at(d)},append(d){u(()=>s.append(d))},appendMany(d){u(()=>s.appendMany(d))},insert(d,c){u(()=>s.insert(d,c))},insertMany(d,c){u(()=>s.insertMany(d,c))},pop(d=-1){return u(()=>s.pop(d))},clear(){u(()=>s.clear())},dispose(){}}}Ot();ae();he();function Gs(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=Ye(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 d,c=()=>{r.get(s)===d&&r.delete(s)};return d=u.then(l=>(c(),l),l=>{throw c(),l}),r.set(s,d),d}}function hp(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(d=>{for(let c of d)if(c[0]===A||c[0]===L){r.get(s)===a&&r.delete(s),u();return}});return a}}he();function so(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(so);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=so(e[o]);return r}function Fs(t){return JSON.stringify(so(t),void 0,0)}var Bg=new TextEncoder,Vg=new TextDecoder("utf-8",{fatal:!0}),tr={name:"json",version:1,encode(t){return Bg.encode(Fs(t))},decode(t){return JSON.parse(Vg.decode(t))}};function yp(){return tr}function io(){let t=new Map;return{name:"memory",read(e){let n=t.get(e);return n===void 0?void 0:new Uint8Array(n)},write(e,n){t.set(e,new Uint8Array(n))},delete(e){t.delete(e)},list(e){let n=[...t.keys()];return e?n.filter(r=>r.startsWith(e)).sort():n.sort()}}}function $s(t,e={}){let n=e.codec??tr,r=e.name??t.name??"snapshot",o=e.keyOf??(l=>l.name??e.name??t.name??"snapshot"),s,i=0,a=e.compactEvery,u,d={name:r,debounceMs:e.debounceMs,compactEvery:a,filter:e.filter,keyOf:o,save(l){if(!(e.filter&&!e.filter(l))&&(s={snapshot:l},i+=1,a!==void 0&&i%a===0||!e.debounceMs))return c()},load(){let l=u??r,p=t.read(l);if(p!==void 0)return p instanceof Uint8Array?p.length===0?void 0:n.decode(p):Promise.resolve(p).then(f=>f===void 0||f.length===0?void 0:n.decode(f))},async flush(){await c()},async rollback(){s=void 0}};function c(){let l=s;if(!l)return;s=void 0;let p=o(l.snapshot),f=n.encode(l.snapshot),m=t.write(p,f);if(m instanceof Promise)return m.then(()=>{u=p});u=p}return d}function Ka(t,e={}){let n=e.codec??tr,r=e.name??t.name??"append-log",o=e.keyOf??(p=>r),s=e.compactEvery,i=new Map,a=0,u,d={name:r,debounceMs:e.debounceMs,compactEvery:s,keyOf:o,appendEntries(p){if(p.length!==0){for(let f of p){let m=o(f),h=i.get(m);h||(h=[],i.set(m,h)),h.push(f)}if(a+=p.length,s!==void 0&&a%s===0||!e.debounceMs)return c()}},async loadEntries(p){let f=p?.keyFilter,m=t.list===void 0?f!==void 0?[f]:[r]:await Promise.resolve(t.list(f)),h=[];for(let g of m){let y=await Promise.resolve(t.read(g));if(y===void 0||y.length===0)continue;let b=n.decode(y);Array.isArray(b)&&h.push(...b)}return{entries:h,cursor:void 0}},async flush(){await c()},async rollback(){i=new Map}};function c(){if(i.size===0)return;let p=i;i=new Map;let f=(u??Promise.resolve()).then(()=>{let m=l(p);return m instanceof Promise?m:Promise.resolve()},()=>{let m=l(p);return m instanceof Promise?m:Promise.resolve()});return u=f.finally(()=>{u===f&&(u=void 0)}),u}function l(p){let f=[];for(let[m,h]of p){let g=t.read(m),y=b=>{let T=[...b===void 0||b.length===0?[]:n.decode(b)??[],...h],w=n.encode(T);return t.write(m,w)};if(g instanceof Promise)f.push(g.then(async b=>{let v=y(b);v instanceof Promise&&await v}));else{let b=y(g);b instanceof Promise&&f.push(b)}}if(f.length>0)return Promise.all(f).then(()=>{})}return d}function js(t,e={}){let n=e.codec??tr,r=e.name??t.name??"kv",o=e.compactEvery,s=new Map,i=0,a={name:r,debounceMs:e.debounceMs,compactEvery:o,filter:e.filter,save(d,c){if(!(e.filter&&!e.filter(d,c))&&(s.set(d,c),i+=1,o!==void 0&&i%o===0||!e.debounceMs))return u()},load(d){let c=t.read(d);if(c!==void 0)return c instanceof Uint8Array?c.length===0?void 0:n.decode(c):Promise.resolve(c).then(l=>l===void 0||l.length===0?void 0:n.decode(l))},delete(d){if(s.delete(d),!!t.delete)return t.delete(d)},list(d){return t.list?t.list(d):[]},async flush(){await u()},async rollback(){s=new Map}};function u(){if(s.size===0)return;let d=s;s=new Map;let c=[];for(let[l,p]of d){let f=n.encode(p),m=t.write(l,f);m instanceof Promise&&c.push(m)}if(c.length>0)return Promise.all(c).then(()=>{})}return a}function bp(t){return $s(io(),t)}function vp(t){return Ka(io(),t)}function ao(t){return js(io(),t)}function Tp(t,e){let n={name:e?.name??"dict-kv",read(r){return t[r]},write(r,o){t[r]=new Uint8Array(o)},delete(r){delete t[r]},list(r){let o=Object.keys(t).sort();return r?o.filter(s=>s.startsWith(r)):o}};return js(n,e)}function wp(t,e){return $s({name:"dict",read(r){return t[r]},write(r,o){t[r]=new Uint8Array(o)},delete(r){delete t[r]},list(r){let o=Object.keys(t).sort();return r?o.filter(s=>s.startsWith(r)):o}},e)}ae();_e();ee();function uo(t,e,n,r){let o=new Y(t,r);o.add(e,{name:"source"});let s=M(n,{meta:{kind:"stratify_rules"}});o.add(s,{name:"rules"});for(let i of n)Kg(o,e,s,i);return o}function Kg(t,e,n,r){let o=`branch/${r.name}`,s=Symbol("noValue"),i=!1,a=!1,u=!1,d=s,c=!1,l=n.cache??[];function p(h){if(u){u=!1;let g=d;if(d=s,g!==s){let y=l.find(v=>v.name===r.name),b=!1;try{b=y?.classify(g)??!1}catch{b=!1}b?(c=!1,h.emit(g)):c&&(c=!1,h.down([[ne],[V]]))}else c?(c=!1,h.down([[ne],[V]])):h.down([[V]])}}let f=z([],(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===ne?(g===0?(i=!0,c=!0):a=!0,!0):b===E||b===V?(g===0?(i=!1,u=!0,d=b===E?h[1]:s):(b===E&&(l=h[1]),a=!1),i||a||p(y),!0):b===L||b===A||b===de?(i=!1,a=!1,u=!1,d=s,c=!1,g===0&&y.down([h]),!0):g===1}if(t.add(f,{name:o}),r.ops){let h=r.ops(f),g=`branch/${r.name}/out`;t.add(h,{name:g})}}vt();Me();ae();_e();ee();he();ae();var qg=new Map([[Je,"INVALIDATE"],[Be,"PAUSE"],[qe,"RESUME"],[de,"TEARDOWN"],[L,"COMPLETE"],[A,"ERROR"]]),Hg=new Map([["INVALIDATE",Je],["PAUSE",Be],["RESUME",qe],["TEARDOWN",de],["COMPLETE",L],["ERROR",A]]);function Ut(t){let e=qg.get(t);return e||(Symbol.keyFor(t)??"UNKNOWN")}function gn(t){let e=Hg.get(t);if(e)return e;if(t&&t!=="UNKNOWN")return Symbol.for(t)}function hn(t){return t instanceof Error?{message:t.message,name:t.name,stack:t.stack}:{message:String(t),name:"Error"}}function yn(t){let e=new Error(t.message);return e.name=t.name,t.stack&&(e.stack=t.stack),e}function Jt(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 Jt(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 Wg(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function qa(t,e){let n=Wg(t)?t:Jt(t),r=e.name??"workerBridge",o=Object.entries(e.expose??{}),s=e.import??[],i=e.transfer??{},a=M("connecting",{name:`${r}::meta::status`}),u=M(null,{name:`${r}::meta::error`}),d=new Map,c=new Map;for(let b of s){let v=M(void 0,{name:`${r}::${b}`});d.set(b,v)}let l;if(o.length>0){let b=o.map(([,w])=>w),v=z(b,(w,k)=>{let x={};for(let S=0;S<o.length;S++){let[R]=o[S],N=w[S];N!=null&&N.length>0&&(x[R]=N.at(-1))}Object.keys(x).length!==0&&k.emit(x)},{name:`${r}::aggregated`,partial:!0});l=pe([v],w=>{let k=w[0];if(k==null||Object.keys(k).length===0)return;let x=[];for(let N of Object.keys(k)){let _=i[N];_&&x.push(..._(k[N]))}let S;for(let[N,_]of o)N in k&&_.v!=null&&(S==null&&(S={}),S[N]=_.v.version);let R={t:"b",u:k,...S?{v:S}:{}};try{n.post(R,x.length>0?x:void 0)}catch(N){u.down([[E,N instanceof Error?N:new Error(String(N))]])}}).subscribe(()=>{})}let p=!1,f=n.listen(b=>{if(p)return;let v=b;switch(v.t){case"r":{X(()=>{for(let[w,k]of Object.entries(v.stores)){let x=d.get(w);x&&x.down([[E,k]])}}),a.down([[E,"connected"]]);let T={};for(let[w,k]of o)T[w]=k.cache;n.post({t:"i",stores:T});break}case"v":{let T=d.get(v.s);T&&T.down([[E,v.d]]);break}case"b":{X(()=>{for(let[T,w]of Object.entries(v.u)){let k=v.v?.[T];if(k!=null){let S=c.get(T);if(S!=null&&k<=S)continue;c.set(T,k)}let x=d.get(T);x&&x.down([[E,w]])}});break}case"e":{let T=d.get(v.s);T&&T.down([[A,yn(v.err)]]);break}case"s":{let T=gn(v.sig);if(!T)break;let w=v.s==="*"?[...d.values()]:d.has(v.s)?[d.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!==E&&($e.isLocalOnly(x)||(x===A?n.post({t:"e",s:b,err:hn(k[1])}):n.post({t:"s",s:b,sig:Ut(x),d:k.length>1?k[1]:void 0})))}}));m.push(T)}let h;if(e.timeoutMs!=null&&e.timeoutMs>0){let b=st(e.timeoutMs),v=Xe(a,w=>w==="connected");h=As(xt(zr(b,()=>"timeout"),zr(v,()=>"ready"))).subscribe(w=>{for(let k of w)k[0]===E&&k[1]==="timeout"&&(u.down([[E,new Error("Worker bridge handshake timeout")]]),g())})}function g(){if(!p){p=!0,h?.(),n.post({t:"s",s:"*",sig:Ut(de)}),l&&l();for(let b of m)b();m.length=0,f(),a.down([[E,"closed"]]),c.clear(),d.clear()}}let y={meta:{status:a,error:u},destroy:g};for(let[b,v]of d)y[b]=v;return y}Me();ae();_e();ee();function zg(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function Ha(t,e){let n=zg(t)?t:Jt(t),r=e.import??[],o=e.transfer??{},s=new Map,i=new Map,a={};for(let g of r){let y=M(void 0,{name:`worker::${g}`});s.set(g,y),a[g]=y}let u=e.expose(a),d=Object.entries(u),c,l=!1;if(d.length>0){let g=d.map(([,v])=>v),y=z(g,(v,T)=>{let w={};for(let k=0;k<d.length;k++){let[x]=d[k],S=v[k];S!=null&&S.length>0&&(w[x]=S.at(-1))}Object.keys(w).length!==0&&T.emit(w)},{name:"workerSelf::aggregated",partial:!0});c=pe([y],v=>{if(l)return;let T=v[0];if(T==null||Object.keys(T).length===0)return;let w=[];for(let S of Object.keys(T)){let R=o[S];R&&w.push(...R(T[S]))}let k;for(let[S,R]of d)S in T&&R.v!=null&&(k==null&&(k={}),k[S]=R.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[g,y]of d){let b=y.subscribe((v=>{if(!l)for(let T of v){let w=T[0];w!==E&&($e.isLocalOnly(w)||(w===A?n.post({t:"e",s:g,err:hn(T[1])}):n.post({t:"s",s:g,sig:Ut(w),d:T.length>1?T[1]:void 0})))}}));p.push(b)}let f=n.listen(g=>{if(l)return;let y=g;switch(y.t){case"i":{X(()=>{for(let[b,v]of Object.entries(y.stores)){let T=s.get(b);T&&T.down([[E,v]])}});break}case"v":{let b=s.get(y.s);b&&b.down([[E,y.d]]);break}case"b":{X(()=>{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([[E,v]])}});break}case"e":{let b=s.get(y.s);b&&b.down([[A,yn(y.err)]]);break}case"s":{let b=gn(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 d)m[g]=y.cache;n.post({t:"r",stores:m});function h(){if(!l){l=!0,c&&c();for(let g of p)g();p.length=0,f(),n.terminate?.(),i.clear(),s.clear()}}return{destroy:h}}var Qu={};ke(Qu,{SNAPSHOT_WIRE_VERSION:()=>No,SurfaceError:()=>Ne,accountability:()=>yi,ai:()=>mi,asSurfaceError:()=>Fi,cqrs:()=>Ts,createGraph:()=>pr,deleteSnapshot:()=>Hi,demoShell:()=>vi,diffSnapshots:()=>Ki,domainTemplates:()=>Ti,graphspec:()=>fi,guarded:()=>ki,harness:()=>Ci,jobQueue:()=>Oi,layout:()=>Di,lens:()=>Ii,listSnapshots:()=>qi,memory:()=>ci,messaging:()=>oi,orchestration:()=>si,process:()=>Pi,reduction:()=>pi,refine:()=>Si,resilientPipeline:()=>Gi,restoreSnapshot:()=>Vi,runReduction:()=>$i,saveSnapshot:()=>Bi,surface:()=>Wi});var mi={};ke(mi,{AgentLoopGraph:()=>ui,AllTiersExhaustedError:()=>po,BudgetExhaustedError:()=>Js,ChatStreamGraph:()=>ii,CircuitOpenError:()=>pt,DEFAULT_DECAY_RATE:()=>Tu,FallbackMissError:()=>th,LLMTimeoutError:()=>rr,ReplayCacheMissError:()=>Tn,ToolRegistryGraph:()=>ai,admissionFilter3D:()=>iy,admissionScored:()=>Wp,agentLoop:()=>ry,agentMemory:()=>cy,anthropicAdapter:()=>za,canonicalJson:()=>Ja,cascadingLlmAdapter:()=>uu,chatStream:()=>pu,composePricing:()=>Th,computePrice:()=>tu,contentGate:()=>Zh,costMeterExtractor:()=>zh,createAdapter:()=>gh,createCapabilitiesRegistry:()=>Ug,createPricingRegistry:()=>bh,dryRunAdapter:()=>bn,fallbackAdapter:()=>Ya,fromLLM:()=>Ih,frozenContext:()=>Fh,gatedStream:()=>qh,gaugesAsContext:()=>ly,googleAdapter:()=>Qa,graphFromSpec:()=>rf,graphFromSpecReactive:()=>ky,handoff:()=>oy,keywordFlagExtractor:()=>Jh,knobsAsTools:()=>Ry,llmConsolidator:()=>hu,llmExtractor:()=>gu,memoryRetrieval:()=>Ru,memoryWithKG:()=>ku,memoryWithTiers:()=>xu,memoryWithVectors:()=>wu,observableAdapter:()=>hh,openAICompatAdapter:()=>Za,parseRateLimitFromError:()=>su,pricingFor:()=>wh,promptNode:()=>wn,redactor:()=>ey,registryPricing:()=>vh,resilientAdapter:()=>Lh,streamExtractor:()=>Yh,streamingPromptNode:()=>Kh,suggestStrategy:()=>of,suggestStrategyReactive:()=>Ey,systemPromptBuilder:()=>Hh,tier:()=>Ah,toolCallExtractor:()=>Xh,toolExecution:()=>fu,toolRegistry:()=>mu,toolSelector:()=>sy,validateGraphDef:()=>Ny,withBreaker:()=>nu,withBudgetGate:()=>ou,withDryRun:()=>xh,withRateLimiter:()=>au,withReplayCache:()=>lo,withRetry:()=>du,withTimeout:()=>cu,zeroPrice:()=>Us});ee();function co(t,e){return`${t}::${e}`}function Ug(t){let e=Ze({name:"capabilitiesRegistry"}),n=d=>{e.set(co(d.provider,d.id),d)};if(t)for(let d of t)n(d);let r=(d,c)=>{let l=e.get(co(d,c));if(l)return l;let p=e.entries.cache;if(!p)return;let f;for(let[,m]of p){if(m.provider!==d)continue;let h=m.id;c.startsWith(h)&&(!f||h.length>f.id.length)&&(f=m)}return f},o=128,s=new Map,i=new Map,a=(d,c,l,p)=>{for(d.has(c)&&d.delete(c),d.set(c,l);d.size>p;){let f=d.keys().next().value;if(f===void 0)break;d.delete(f)}},u=C([e.entries],([d])=>Array.from(d.values()),{name:"capabilitiesRegistry/entries",initial:[]});return{register:n,lookup:r,remove(d,c){let l=e.has(co(d,c));return l&&e.delete(co(d,c)),l},entries(){let d=e.entries.cache;return(function*(){if(d)for(let c of d.values())yield c})()},lookupNode(d,c){let l=co(d,c),p=s.get(l);if(p)return s.delete(l),s.set(l,p),p;let f=C([e.entries],()=>r(d,c),{name:`capabilitiesRegistry/lookup/${d}::${c}`,initial:void 0});return a(s,l,f,o),f},entriesNode:u,byProvider(d){let c=i.get(d);if(c)return i.delete(d),i.set(d,c),c;let l=C([u],([p])=>p.filter(f=>f.provider===d),{name:`capabilitiesRegistry/byProvider/${d}`,initial:[]});return a(i,d,l,o),l}}}xe();function za(t={}){return t.sdk?Zg(t):Xg(t)}function Bs(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}=Jg(t,e?.systemPrompt),a={model:o,messages:i.map(Yg),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(Qg)),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 Jg(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 zg(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 Ug(t){return{name:t.name,description:t.description,input_schema:t.parameters}}function Vs(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 Ua(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 Tp(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:Ua(t.usage),finishReason:t.stop_reason,latencyMs:e,model:t.model,provider:"anthropic"}}function Jg(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=Bs(i,a,t.model,!1),d=H(),c=await o(`${n}/v1/messages`,{method:"POST",headers:s(),body:JSON.stringify(u),signal:a?.signal});if(!c.ok)throw await ht(c,"Anthropic");let l=await c.json(),p=Math.max(0,(H()-d)/1e6);return Tp(l,p)},async*stream(i,a){let u=Bs(i,a,t.model,!0),d=await o(`${n}/v1/messages`,{method:"POST",headers:{...s(),accept:"text/event-stream"},body:JSON.stringify(u),signal:a?.signal});if(!d.ok)throw await ht(d,"Anthropic");if(!d.body)throw new Error("anthropicAdapter: streaming response has no body");let c,l,p=new Map;for await(let f of Dt(d.body,{signal:a?.signal})){let m=f.data;if(!m)continue;let h;try{h=JSON.parse(m)}catch{continue}switch(h.type){case"message_start":{c=Vs(c,h.message.usage);break}case"content_block_start":{let g=h,y=g.content_block;y.type==="tool_use"&&(p.set(g.index,{id:String(y.id??""),name:String(y.name??""),argBuf:""}),yield{type:"tool-call-delta",delta:{id:String(y.id??""),name:String(y.name??"")}});break}case"content_block_delta":{let g=h,y=g.delta;if(y.type==="text_delta"&&typeof y.text=="string")yield{type:"token",delta:y.text};else if(y.type==="input_json_delta"&&typeof y.partial_json=="string"){let b=p.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&&(c=Vs(c,g.delta.usage));break}case"message_stop":break}}c&&(yield{type:"usage",usage:Ua(c)}),yield{type:"finish",reason:l??"stop"}}}}function Yg(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=Bs(n,r,t.model,!1),s=H(),i=await e.messages.create(o,{signal:r?.signal}),a=Math.max(0,(H()-s)/1e6);return Tp(i,a)},async*stream(n,r){if(!e.messages.stream)throw new Error("sdkBackedAnthropic: SDK instance does not expose .messages.stream");let o=Bs(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=Vs(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=Vs(s,u.delta.usage));break}}s&&(yield{type:"usage",usage:Ua(s)}),yield{type:"finish",reason:i??"stop"}}}}vt();function Ks(){let t=new Error("aborted");return t.name="AbortError",t}function wp(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Ks()):new Promise((n,r)=>{let o=new Le,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(Ks())},e.addEventListener("abort",s,{once:!0}))})}function bn(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(d=>d.role==="user");return u?`echo: ${u.content}`:"dry-run: no user message"}),i=t.usage??((a,u)=>{let d=a.reduce((c,l)=>c+l.content.length,0);return{input:{regular:Math.ceil(d/4)},output:{regular:Math.ceil(u.length/4)}}});return{provider:e,model:n,async invoke(a,u){if(await wp(r,u?.signal),u?.signal?.aborted)throw Ks();let d=s(a,u),c=i(a,d);return{content:d,usage:c,finishReason:"stop",model:u?.model??n,provider:e,tier:u?.tier,metadata:{dryRun:!0}}},async*stream(a,u){let d=s(a,u),c=i(a,d),l=Math.ceil(d.length/o)||1,p=r>0?r/l:0;for(let f=0;f<d.length;f+=o){if(u?.signal?.aborted)throw Ks();await wp(p,u?.signal),yield{type:"token",delta:d.slice(f,f+o)}}yield{type:"usage",usage:c},yield{type:"finish",reason:"stop"}}}}xe();xe();he();vt();function kp(t){let{storage:e,mode:n="read-write",keyFn:r,keyPrefix:o="llm-replay"}=t,i=Ps({storage:e,keyPrefix:o,mode:n==="read-strict"?"read":n,keyContext:({messages:u,opts:d})=>{let{signal:c,keyContext:l,...p}=d??{};return{messages:u,opts:p}}});async function a(u,d){if(r){if(r.length<=1){let l={messages:u,opts:d,context:d?.keyContext},p=await r(l);return`${o}:${p}`}let c=await r(u,d);return`${o}:${c}`}return i.keyFor({messages:u,opts:d})}return{keyFor:a,async lookup(u,d){if(n!=="write"){if(r){let c=await a(u,d),l=await e.load(c);return l===void 0?void 0:l}return i.lookup({messages:u,opts:d})}},async store(u,d,c){if(n!=="read"){if(r){let l=await a(u,d);await e.save(l,c);return}await i.store({messages:u,opts:d},c)}},async forget(u,d){if(!(n==="read"||n==="write")&&e.delete){if(r){let c=await a(u,d);await e.delete(c);return}await i.forget({messages:u,opts:d})}}}}xe();ae();ee();he();function et(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 qs(t,e){let{onResp:n,onError:r,name:o}=e;if(t!=null&&typeof t.then=="function"){let d=t;return r?d.then(n).catch(c=>{throw r(c),c}):d.then(n)}if(t!=null&&typeof t=="object"&&"content"in t)return n(t);let s=U(t);if(r){let d=!1;s.subscribe(c=>{for(let l of c){if(d)return;l[0]===C&&(d=!0,r(l[1]))}})}let i,a=!1,u=Jr(s,d=>{i=n(d),a=!0});return A([u],([d])=>d==null?null:a?i:n(d),{name:o??"adapt/invokeTap"})}function vn(t){let e=t.endNs??H();return{timestamp:e,wallClock:t.startWallClockNs??oe(),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 Rt(){return{input:{regular:0},output:{regular:0}}}var xp=Symbol.for("graphrefly.adapter.middlewareLayers");function Ue(t,e,n){let o=[...n?Qg(n):[],e];return Object.defineProperty(t,xp,{value:Object.freeze(o),enumerable:!1,writable:!1,configurable:!1}),t}function Qg(t){let e=t[xp];return Array.isArray(e)?e:[]}var Tn=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 lo(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=kp({storage:e.storage,mode:n==="write-only"?"write":n,keyFn:e.keyFn,keyPrefix:i}),d=p=>p<=0?Promise.resolve():new Promise(f=>{new Le().start(p,()=>f())}),c=Gs(async({messages:p,invokeOpts:f})=>await Ye(U(t.invoke(p,f))),{keyFn:({_precomputedKey:p})=>p}),l=et(t,{async invoke(p,f){let m=await u.keyFor(p,f),h=await u.lookup(p,f);if(h?.response){let y=h.response;return{...y,metadata:{...y.metadata??{},replayCache:"hit"}}}if(n==="read-strict")throw new Tn(m,"invoke");let g=await c({messages:p,invokeOpts:f,_precomputedKey:m});return a||await u.store(p,f,{response:g,storedAtNs:oe()}),g},async*stream(p,f){if(!r){for await(let x of t.stream(p,f))yield x;return}let m=await u.keyFor(p,f),h=await u.lookup(p,f);if(h){let x=h.response;if(h.streamChunks&&h.streamCadenceMs)for(let k=0;k<h.streamChunks.length;k++){let S=h.streamCadenceMs[k]??0,R=s>0?S/s:0;R>0&&await d(R),yield{type:"token",delta:h.streamChunks[k]?.delta??""}}else x.content&&(yield{type:"token",delta:x.content});x.usage&&(yield{type:"usage",usage:x.usage}),yield{type:"finish",reason:x.finishReason??"stop"};return}if(n==="read-strict")throw new Tn(m,"stream");let g="",y,b,v=[],T=[],w;for await(let x of t.stream(p,f)){if(x.type==="token"&&(g+=x.delta,o)){let k=H(),S=w===void 0?0:(k-w)/1e6;T.push(S),w=k,v.push({delta:x.delta})}x.type==="usage"&&(y=x.usage),x.type==="finish"&&(b=x.reason),yield x}if((g||y)&&!a){let k={response:{content:g,usage:y??{input:{regular:0},output:{regular:0}},finishReason:b,model:t.model??f?.model??"",provider:t.provider},storedAtNs:oe(),...o?{streamChunks:v,streamCadenceMs:T}:{}};await u.store(p,f,k)}}});return Ue(l,"withReplayCache",t),l}var Ja=to;var Xg=Tn;function Rp(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 Sp(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 Zg(t,e){if("key"in t)return t.key;let n=Ja({messages:t.messages,opts:t.invokeOpts??{}}),r=await Is(n);return`${e}:${r}`}function eh(t){let e={response:t.response,storedAtNs:oe()};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 th(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=ao(),o=t.fixtures,s=(async()=>{for(let i of o){let a=await Zg(i,e);await r.save(a,eh(i))}})();return s.catch(()=>{}),{tier:r,seedReady:s}}return t.fixturesStorage?{tier:t.fixturesStorage,seedReady:Promise.resolve()}:{tier:void 0,seedReady:Promise.resolve()}}function Ya(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"?bn({provider:e,model:n,respond:()=>"[unreachable: read-strict mode throws on miss]"}):{provider:e,model:n,async invoke(c,l){let p=t.respond?t.respond(c,l):Rp(e,n);return Sp(p,e,n)},async*stream(c,l){let p=t.respond?t.respond(c,l):Rp(e,n),f=Sp(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 c=th(t,o);i=c.tier??ao(),a=c.seedReady}let u=t.record?"read-write":r==="throw"?"read-strict":"read",d=lo(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:d.capabilities?.bind(d),async invoke(c,l){return await a,d.invoke(c,l)},async*stream(c,l){await a;for await(let p of d.stream(c,l))yield p}}}xe();function Qa(t={}){return t.sdk?sh(t):oh(t)}function Hs(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(`
34
+ `):void 0,chat:r}}function Yg(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 Qg(t){return{name:t.name,description:t.description,input_schema:t.parameters}}function Vs(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 Ua(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 kp(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:Ua(t.usage),finishReason:t.stop_reason,latencyMs:e,model:t.model,provider:"anthropic"}}function Xg(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=Bs(i,a,t.model,!1),d=H(),c=await o(`${n}/v1/messages`,{method:"POST",headers:s(),body:JSON.stringify(u),signal:a?.signal});if(!c.ok)throw await ht(c,"Anthropic");let l=await c.json(),p=Math.max(0,(H()-d)/1e6);return kp(l,p)},async*stream(i,a){let u=Bs(i,a,t.model,!0),d=await o(`${n}/v1/messages`,{method:"POST",headers:{...s(),accept:"text/event-stream"},body:JSON.stringify(u),signal:a?.signal});if(!d.ok)throw await ht(d,"Anthropic");if(!d.body)throw new Error("anthropicAdapter: streaming response has no body");let c,l,p=new Map;for await(let f of Dt(d.body,{signal:a?.signal})){let m=f.data;if(!m)continue;let h;try{h=JSON.parse(m)}catch{continue}switch(h.type){case"message_start":{c=Vs(c,h.message.usage);break}case"content_block_start":{let g=h,y=g.content_block;y.type==="tool_use"&&(p.set(g.index,{id:String(y.id??""),name:String(y.name??""),argBuf:""}),yield{type:"tool-call-delta",delta:{id:String(y.id??""),name:String(y.name??"")}});break}case"content_block_delta":{let g=h,y=g.delta;if(y.type==="text_delta"&&typeof y.text=="string")yield{type:"token",delta:y.text};else if(y.type==="input_json_delta"&&typeof y.partial_json=="string"){let b=p.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&&(c=Vs(c,g.delta.usage));break}case"message_stop":break}}c&&(yield{type:"usage",usage:Ua(c)}),yield{type:"finish",reason:l??"stop"}}}}function Zg(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=Bs(n,r,t.model,!1),s=H(),i=await e.messages.create(o,{signal:r?.signal}),a=Math.max(0,(H()-s)/1e6);return kp(i,a)},async*stream(n,r){if(!e.messages.stream)throw new Error("sdkBackedAnthropic: SDK instance does not expose .messages.stream");let o=Bs(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=Vs(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=Vs(s,u.delta.usage));break}}s&&(yield{type:"usage",usage:Ua(s)}),yield{type:"finish",reason:i??"stop"}}}}vt();function Ks(){let t=new Error("aborted");return t.name="AbortError",t}function xp(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Ks()):new Promise((n,r)=>{let o=new Le,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(Ks())},e.addEventListener("abort",s,{once:!0}))})}function bn(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(d=>d.role==="user");return u?`echo: ${u.content}`:"dry-run: no user message"}),i=t.usage??((a,u)=>{let d=a.reduce((c,l)=>c+l.content.length,0);return{input:{regular:Math.ceil(d/4)},output:{regular:Math.ceil(u.length/4)}}});return{provider:e,model:n,async invoke(a,u){if(await xp(r,u?.signal),u?.signal?.aborted)throw Ks();let d=s(a,u),c=i(a,d);return{content:d,usage:c,finishReason:"stop",model:u?.model??n,provider:e,tier:u?.tier,metadata:{dryRun:!0}}},async*stream(a,u){let d=s(a,u),c=i(a,d),l=Math.ceil(d.length/o)||1,p=r>0?r/l:0;for(let f=0;f<d.length;f+=o){if(u?.signal?.aborted)throw Ks();await xp(p,u?.signal),yield{type:"token",delta:d.slice(f,f+o)}}yield{type:"usage",usage:c},yield{type:"finish",reason:"stop"}}}}xe();xe();he();vt();function Rp(t){let{storage:e,mode:n="read-write",keyFn:r,keyPrefix:o="llm-replay"}=t,i=Ps({storage:e,keyPrefix:o,mode:n==="read-strict"?"read":n,keyContext:({messages:u,opts:d})=>{let{signal:c,keyContext:l,...p}=d??{};return{messages:u,opts:p}}});async function a(u,d){if(r){if(r.length<=1){let l={messages:u,opts:d,context:d?.keyContext},p=await r(l);return`${o}:${p}`}let c=await r(u,d);return`${o}:${c}`}return i.keyFor({messages:u,opts:d})}return{keyFor:a,async lookup(u,d){if(n!=="write"){if(r){let c=await a(u,d),l=await e.load(c);return l===void 0?void 0:l}return i.lookup({messages:u,opts:d})}},async store(u,d,c){if(n!=="read"){if(r){let l=await a(u,d);await e.save(l,c);return}await i.store({messages:u,opts:d},c)}},async forget(u,d){if(!(n==="read"||n==="write")&&e.delete){if(r){let c=await a(u,d);await e.delete(c);return}await i.forget({messages:u,opts:d})}}}}xe();ae();ee();he();function et(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 qs(t,e){let{onResp:n,onError:r,name:o}=e;if(t!=null&&typeof t.then=="function"){let d=t;return r?d.then(n).catch(c=>{throw r(c),c}):d.then(n)}if(t!=null&&typeof t=="object"&&"content"in t)return n(t);let s=U(t);if(r){let d=!1;s.subscribe(c=>{for(let l of c){if(d)return;l[0]===A&&(d=!0,r(l[1]))}})}let i,a=!1,u=Jr(s,d=>{i=n(d),a=!0});return C([u],([d])=>d==null?null:a?i:n(d),{name:o??"adapt/invokeTap"})}function vn(t){let e=t.endNs??H();return{timestamp:e,wallClock:t.startWallClockNs??oe(),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 Rt(){return{input:{regular:0},output:{regular:0}}}var Sp=Symbol.for("graphrefly.adapter.middlewareLayers");function Ue(t,e,n){let o=[...n?eh(n):[],e];return Object.defineProperty(t,Sp,{value:Object.freeze(o),enumerable:!1,writable:!1,configurable:!1}),t}function eh(t){let e=t[Sp];return Array.isArray(e)?e:[]}var Tn=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 lo(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=Rp({storage:e.storage,mode:n==="write-only"?"write":n,keyFn:e.keyFn,keyPrefix:i}),d=p=>p<=0?Promise.resolve():new Promise(f=>{new Le().start(p,()=>f())}),c=Gs(async({messages:p,invokeOpts:f})=>await Ye(U(t.invoke(p,f))),{keyFn:({_precomputedKey:p})=>p}),l=et(t,{async invoke(p,f){let m=await u.keyFor(p,f),h=await u.lookup(p,f);if(h?.response){let y=h.response;return{...y,metadata:{...y.metadata??{},replayCache:"hit"}}}if(n==="read-strict")throw new Tn(m,"invoke");let g=await c({messages:p,invokeOpts:f,_precomputedKey:m});return a||await u.store(p,f,{response:g,storedAtNs:oe()}),g},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),h=await u.lookup(p,f);if(h){let k=h.response;if(h.streamChunks&&h.streamCadenceMs)for(let x=0;x<h.streamChunks.length;x++){let S=h.streamCadenceMs[x]??0,R=s>0?S/s:0;R>0&&await d(R),yield{type:"token",delta:h.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 Tn(m,"stream");let g="",y,b,v=[],T=[],w;for await(let k of t.stream(p,f)){if(k.type==="token"&&(g+=k.delta,o)){let x=H(),S=w===void 0?0:(x-w)/1e6;T.push(S),w=x,v.push({delta:k.delta})}k.type==="usage"&&(y=k.usage),k.type==="finish"&&(b=k.reason),yield k}if((g||y)&&!a){let x={response:{content:g,usage:y??{input:{regular:0},output:{regular:0}},finishReason:b,model:t.model??f?.model??"",provider:t.provider},storedAtNs:oe(),...o?{streamChunks:v,streamCadenceMs:T}:{}};await u.store(p,f,x)}}});return Ue(l,"withReplayCache",t),l}var Ja=to;var th=Tn;function Ep(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 Np(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=Ja({messages:t.messages,opts:t.invokeOpts??{}}),r=await Is(n);return`${e}:${r}`}function rh(t){let e={response:t.response,storedAtNs:oe()};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=ao(),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 Ya(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"?bn({provider:e,model:n,respond:()=>"[unreachable: read-strict mode throws on miss]"}):{provider:e,model:n,async invoke(c,l){let p=t.respond?t.respond(c,l):Ep(e,n);return Np(p,e,n)},async*stream(c,l){let p=t.respond?t.respond(c,l):Ep(e,n),f=Np(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 c=oh(t,o);i=c.tier??ao(),a=c.seedReady}let u=t.record?"read-write":r==="throw"?"read-strict":"read",d=lo(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:d.capabilities?.bind(d),async invoke(c,l){return await a,d.invoke(c,l)},async*stream(c,l){await a;for await(let p of d.stream(c,l))yield p}}}xe();function Qa(t={}){return t.sdk?uh(t):ah(t)}function Hs(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(`
35
35
 
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(nh)}]),e?.providerExtras&&Object.assign(o,e.providerExtras),o}function nh(t){return{name:t.name,description:t.description,parameters:t.parameters}}function Ep(t,e,n){let r={},o=t.generationConfig;o&&(typeof o.maxOutputTokens=="number"&&(r.maxOutputTokens=o.maxOutputTokens),typeof o.temperature=="number"&&(r.temperature=o.temperature),o.thinkingConfig&&(r.thinkingConfig=o.thinkingConfig)),t.systemInstruction&&(r.systemInstruction=t.systemInstruction),t.tools&&(r.tools=t.tools);for(let[s,i]of Object.entries(t))s==="contents"||s==="generationConfig"||s==="systemInstruction"||s==="tools"||s==="abortSignal"||s==="model"||(r[s]=i);return n&&(r.abortSignal=n),{model:e,contents:t.contents,config:Object.keys(r).length>0?r:void 0}}function Xa(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 Np(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:Xa(t.usageMetadata),finishReason:n?.finishReason,latencyMs:e,model:t.modelVersion,provider:"google"}}function rh(t){if(t.apiKey)return t.apiKey;let e=globalThis.process?.env;return e?.GOOGLE_API_KEY??e?.GEMINI_API_KEY}function oh(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=rh(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=Hs(s,i),d=H(),c=`${e}/models/${encodeURIComponent(a)}:generateContent?${o()}`,l=await n(c,{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,(H()-d)/1e6);return Np(p,f)},async*stream(s,i){let a=r(i),u=Hs(s,i),d=`${e}/models/${encodeURIComponent(a)}:streamGenerateContent?alt=sse&${o()}`,c=await n(d,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",...t.headers??{}},body:JSON.stringify(u),signal:i?.signal});if(!c.ok)throw await ht(c,"Google");if(!c.body)throw new Error("googleAdapter: streaming response has no body");let l,p;for await(let f of Dt(c.body,{signal:i?.signal})){if(!f.data)continue;let m;try{m=JSON.parse(f.data)}catch{continue}let h=m.candidates?.[0];for(let g of h?.content?.parts??[])typeof g.text=="string"&&(g.thought?yield{type:"thinking",delta:g.text}:yield{type:"token",delta:g.text}),g.functionCall&&(yield{type:"tool-call-delta",delta:{name:g.functionCall.name,argumentsDelta:JSON.stringify(g.functionCall.args??{})}});h?.finishReason&&(p=h.finishReason),m.usageMetadata&&(l=m.usageMetadata)}l&&(yield{type:"usage",usage:Xa(l)}),yield{type:"finish",reason:p??"stop"}}}}function sh(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=Hs(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=Ep(o,s,r?.signal),a=H(),u=await e.models.generateContent(i),d=Math.max(0,(H()-a)/1e6);return Np(u,d)},async*stream(n,r){if(!e.models.generateContentStream)throw new Error("sdkBackedGoogle: SDK instance does not expose generateContentStream");let o=Hs(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=Ep(o,s,r?.signal),a,u,d=await e.models.generateContentStream(i);for await(let c of d){let l=c.candidates?.[0];for(let p of l?.content?.parts??[])typeof p.text=="string"&&(p.thought?yield{type:"thinking",delta:p.text}:yield{type:"token",delta:p.text}),p.functionCall&&(yield{type:"tool-call-delta",delta:{name:p.functionCall.name,argumentsDelta:JSON.stringify(p.functionCall.args??{})}});l?.finishReason&&(u=l.finishReason),c.usageMetadata&&(a=c.usageMetadata)}a&&(yield{type:"usage",usage:Xa(a)}),yield{type:"finish",reason:u??"stop"}}}}xe();var ih={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 Za(t={}){return t.sdk?lh(t):ch(t)}function Ws(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(ah);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(uh)),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 ah(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 uh(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}}function eu(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 _p(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:dh(a.function.arguments)}));return{content:s,toolCalls:i.length>0?i:void 0,usage:eu(t.usage),finishReason:r?.finish_reason,latencyMs:e,model:t.model,provider:n}}function dh(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!=null?e:{_raw:t}}catch{return{_raw:t}}}function Mp(t){let e=t.preset??"openai",n=ih[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 ch(t){let{provider:e,baseURL:n,apiKey:r}=Mp(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 d=Ws(a,u,t.model,!1,t.bodyExtras),c=H(),l=await o(`${n}/chat/completions`,{method:"POST",headers:i(),body:JSON.stringify(d),signal:u?.signal});if(!l.ok)throw await ht(l,e);let p=await l.json(),f=Math.max(0,(H()-c)/1e6);return _p(p,f,e)},async*stream(a,u){let d=Ws(a,u,t.model,!0,t.bodyExtras),c=await o(`${n}/chat/completions`,{method:"POST",headers:{...i(),accept:"text/event-stream"},body:JSON.stringify(d),signal:u?.signal});if(!c.ok)throw await ht(c,e);if(!c.body)throw new Error(`openAICompatAdapter[${e}]: streaming response has no body`);let l,p;for await(let f of Dt(c.body,{signal:u?.signal})){if(!f.data||f.data==="[DONE]")continue;let m;try{m=JSON.parse(f.data)}catch{continue}let h=m.choices;if(h){let g=h[0];if(g?.delta?.content&&(yield{type:"token",delta:g.delta.content}),g?.delta?.reasoning_content&&(yield{type:"thinking",delta:g.delta.reasoning_content}),g?.delta?.tool_calls)for(let y of g.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:y.id,name:y.function?.name,argumentsDelta:y.function?.arguments}};g?.finish_reason&&(p=g.finish_reason)}m.usage&&(l=m.usage,yield{type:"usage",usage:eu(l)})}yield{type:"finish",reason:p??"stop"}}}}function lh(t){let e=t.sdk;if(!e)throw new Error("sdkBackedOpenAI: sdk instance required");let{provider:n}=Mp(t);return{provider:n,model:t.model,async invoke(r,o){let s=Ws(r,o,t.model,!1,t.bodyExtras),i=H(),a=await e.chat.completions.create(s,{signal:o?.signal}),u=Math.max(0,(H()-i)/1e6);return _p(a,u,n)},async*stream(r,o){let s=Ws(r,o,t.model,!0,t.bodyExtras),i=await e.chat.completions.create(s,{signal:o?.signal}),a,u;for await(let d of i){let c=d.choices;if(c){let p=c[0];if(p?.delta?.content&&(yield{type:"token",delta:p.delta.content}),p?.delta?.reasoning_content&&(yield{type:"thinking",delta:p.delta.reasoning_content}),p?.delta?.tool_calls)for(let f of p.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:f.id,name:f.function?.name,argumentsDelta:f.function?.arguments}};p?.finish_reason&&(u=p.finish_reason)}let l=d.usage;l&&(a=l,yield{type:"usage",usage:eu(l)})}yield{type:"finish",reason:u??"stop"}}}}function ph(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 za(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 Qa(e)}case"dry-run":{let e={model:t.model,...t.extras};return bn(e)}case"fallback":{let e={provider:t.provider,model:t.model,...t.extras};return Ya(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 Za(e)}default:{let e=t.provider;throw new Error(`createAdapter: unknown provider: ${String(e)}`)}}}xe();ee();he();function yt(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 Gt(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 Op(){return{input:{regular:0},output:{regular:0}}}function fh(t,e){let n=e?.logMax??1e3,r=Ve(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:n}),o=M(null,{name:"adapterStats/lastCall"}),s=A([r.entries],([h])=>h.length,{name:"adapterStats/totalCalls",initial:0}),i=A([r.entries],([h])=>h.reduce((g,y)=>g+yt(y.usage),0),{name:"adapterStats/totalInputTokens",initial:0}),a=A([r.entries],([h])=>h.reduce((g,y)=>g+Gt(y.usage),0),{name:"adapterStats/totalOutputTokens",initial:0}),u=[re(s),re(i),re(a)],d=h=>{r.append(h),o.emit(h)},c=()=>{r.clear(),o.emit(null)},l=et(t,{invoke(h,g){let y=H(),b=oe(),v=t.model??g?.model??"",T=x=>(d(vn({provider:t.provider,model:t.model??g?.model??x.model??"",tier:g?.tier??x.tier,usage:x.usage??Rt(),startNs:y,startWallClockNs:b,method:"invoke"})),x),w=x=>{let k=x;d(vn({provider:t.provider,model:v,tier:g?.tier,usage:Rt(),startNs:y,startWallClockNs:b,method:"invoke",error:{type:k?.name??"Error",message:k?.message??String(x)}}))};return qs(t.invoke(h,g),{onResp:T,onError:w,name:"adapterStats/invokeTap"})},async*stream(h,g){let y=H(),b=oe(),v=t.model??g?.model??"",T;try{for await(let w of t.stream(h,g))w.type==="usage"&&(T=w.usage),yield w;d(vn({provider:t.provider,model:v,tier:g?.tier,usage:T??Rt(),startNs:y,startWallClockNs:b,method:"stream"}))}catch(w){let x=w;throw d(vn({provider:t.provider,model:v,tier:g?.tier,usage:T??Rt(),startNs:y,startWallClockNs:b,method:"stream",error:{type:x?.name??"Error",message:x?.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:c,dispose:()=>{if(!p){p=!0;for(let h of u)h();u.length=0}}}}}function mh(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function Us(t="USD"){return{total:0,currency:t}}function tu(t,e,n){let r=yt(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=mh(b,r),T=y*v/1e6;a+=T,s&&(i[g]=(i[g]??0)+T)},d=t.input,c=e.input;if(c&&(u("input.regular",d.regular,c.regular),u("input.cacheRead",d.cacheRead??0,c.cacheRead),u("input.cacheWrite5m",d.cacheWrite5m??0,c.cacheWrite5m),u("input.cacheWrite1h",d.cacheWrite1h??0,c.cacheWrite1h),u("input.cacheWriteOther",d.cacheWriteOther??0,c.cacheWriteOther),u("input.audio",d.audio??0,c.audio),u("input.image",d.image??0,c.image),u("input.video",d.video??0,c.video),u("input.toolUse",d.toolUse??0,c.toolUse),d.extensions&&c.extensions))for(let[g,y]of Object.entries(d.extensions))u(`input.ext.${g}`,y,c.extensions[g]);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[g,y]of Object.entries(l.extensions))u(`output.ext.${g}`,y,p.extensions[g]);let f=n?.tier;if(f&&e.tierMultipliers){let g=e.tierMultipliers[f];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 zs(t,e){return`${t}::${e}`}function gh(t){let e=new Map,n=new Map,r=(o,s,i)=>{e.set(zs(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(zs(o,s));if(i)return i.pricing;let a=n.get(o);if(!a)return;let u;for(let d of a)if(s.startsWith(d)&&(!u||d.length>u.key.length)){let c=e.get(zs(o,d));c&&(u={key:d,pricing:c.pricing})}return u?.pricing},remove(o,s){let i=e.delete(zs(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 hh(t,e="USD"){return(n,r)=>{let o=t.lookup(r.provider,r.model);return o?tu(n,o,{tier:r.tier,withBreakdown:r.withBreakdown}):Us(e)}}function yh(...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):Us()}}function bh(t,e,n){return t?.pricing?tu(e,t.pricing,n):Us()}Ot();he();function nu(t,e={}){let n=e.breaker??wt(e),r=et(t,{async invoke(o,s){if(!n.canExecute())throw new pt;try{let i=await Ye(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 pt;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}}xe();ae();ee();he();var Js=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"},ru=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),Cp=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function ou(t,e){let n=Ve(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),r=M(Cp(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=A([r],([d])=>{let c=d;return!(e.caps.calls!=null&&c.calls>=e.caps.calls||e.caps.inputTokens!=null&&c.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&c.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&c.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(re(o),e.onExhausted!=null){let d=e.onExhausted,c=!1,l=!0;o.subscribe(p=>{for(let f of p)if(f[0]===E){let m=f[1];if(c&&l&&m===!1){let h=Ap(r.cache??ru,e.caps);h&&d(h)}l=m,c=!0}})}let s=()=>{if(o.cache===!1){let d=r.cache??ru,c=Ap(d,e.caps);return new Js(c??"budget",e.caps[c??"calls"]??0,vh(d,c??"calls"))}},i=(d,c)=>{let l=t.provider,p=vn({provider:l,model:c.model,tier:c.tier,usage:d,startNs:c.startNs,method:c.method,...c.error?{error:c.error}:{}});n.append(p);let f=r.cache??ru,m=e.pricingFn?f.usd+e.pricingFn(d,{model:c.model,provider:l,tier:c.tier}).total:f.usd;r.emit({calls:f.calls+1,inputTokens:f.inputTokens+yt(d),outputTokens:f.outputTokens+Gt(d),usd:m})},a=()=>{n.clear(),r.emit(Cp())},u=et(t,{invoke(d,c){let l=s();if(l)return Promise.reject(l);let p=H(),f=t.model??c?.model??"",m=g=>(i(g.usage??Rt(),{model:t.model??c?.model??g.model??"",tier:c?.tier??g.tier,startNs:p,method:"invoke"}),g),h=g=>{let y=g;i(Rt(),{model:f,tier:c?.tier,startNs:p,method:"invoke",error:{type:y?.name??"Error",message:y?.message??String(g)}})};return qs(t.invoke(d,c),{onResp:m,onError:h,name:"budgetGate/invokeTap"})},async*stream(d,c){let l=s();if(l)throw l;let p=H(),f;try{for await(let m of t.stream(d,c))m.type==="usage"&&(f=m.usage),yield m;i(f??Rt(),{model:t.model??c?.model??"",tier:c?.tier,startNs:p,method:"stream"})}catch(m){let h=m;throw i(f??Rt(),{model:t.model??c?.model??"",tier:c?.tier,startNs:p,method:"stream",error:{type:h?.name??"Error",message:h?.message??String(m)}}),m}}});return Ue(u,"withBudgetGate",t),{adapter:u,budget:{totals:r,isOpen:o,log:n,reset:a}}}function Ap(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 vh(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}he();function Th(t,e){let n=e.mock??bn({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=re(o));let i=()=>r!==void 0?r:!!o?.cache,a=et(t,{invoke(d,c){return i()?n.invoke(d,c):t.invoke(d,c)},stream(d,c){return i()?n.stream(d,c):t.stream(d,c)}});return Ue(a,"withDryRun",t),{adapter:a,dispose:()=>{s&&(s(),s=void 0)}}}function su(t){if(t==null||typeof t!="object")return;let e=t,n=e.status,r=wh(e.headers);if(n!==429&&n!==503&&!Nh(e.message))return;let o={},s=r("retry-after"),i=xh(s);i!=null&&(o.retryAfterMs=i);let a=r("anthropic-ratelimit-requests-reset");if(a){let f=Lp(a);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let u=r("anthropic-ratelimit-tokens-reset");if(u){let f=Lp(u);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let d=Ys(r,"x-ratelimit-limit-requests");d!=null&&(o.rpmCap=d);let c=Ys(r,"x-ratelimit-limit-tokens");c!=null&&(o.tpmCap=c);let l=Ys(r,"x-ratelimit-remaining-requests"),p=Ys(r,"x-ratelimit-remaining-tokens");if(l!=null&&d!=null&&d>0&&(o.usageHint??={},o.usageHint.rpm=1-l/d),p!=null&&c!=null&&c>0&&(o.usageHint??={},o.usageHint.tpm=1-p/c),o.retryAfterMs==null&&e.message){let f=Sh(e.message);f!=null&&(o.retryAfterMs=f)}return e.headers&&(o.metadata={headers:kh(e.headers)}),o.retryAfterMs==null&&o.rpmCap==null&&o.tpmCap==null&&o.usageHint==null?o.metadata?o:void 0:o}function wh(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 kh(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 Ys(t,e){let n=t(e);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function xh(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 Lp(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var Rh=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function Sh(t){let e=Rh.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 Eh=/rate\s*limit|too\s*many\s*requests|quota|429/i;function Nh(t){return!!t&&Eh.test(t)}xe();ae();ee();Ot();he();vt();function iu(t){let e=new Error(t);return e.name="AbortError",e}function Pp(t={}){let e=Math.max(1,t.burstMultiplier??1),n=t.clampCooldownMs??6e4,r=t.rpm!=null?U(t.rpm):M(Number.POSITIVE_INFINITY),o=t.tpm!=null?U(t.tpm):M(Number.POSITIVE_INFINITY),s=M(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),i=M(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),a=M({},{name:"adaptiveRateLimiter/lastSignal"}),u=A([r,s],([O,P])=>Math.min(Number(O??1/0),Number(P??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),d=A([o,i],([O,P])=>Math.min(Number(O??1/0),Number(P??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),c=nr(Number(r.cache??Number.POSITIVE_INFINITY),e),l=nr(Number(o.cache??Number.POSITIVE_INFINITY),e),p=!1,f=!1,m=u.subscribe(O=>{for(let P of O)if(P[0]===E){let B=Number(P[1]);Number.isFinite(B)&&B>0?(c=nr(B,e),p=!1):B===1/0?(c=nr(1/0,e),p=!1):B<=0&&(p=!0)}}),h=d.subscribe(O=>{for(let P of O)if(P[0]===E){let B=Number(P[1]);Number.isFinite(B)&&B>0?(l=nr(B,e),f=!1):B===1/0?(l=nr(1/0,e),f=!1):B<=0&&(f=!0)}}),g=0,y=new Le,b=new Le,v;t.adaptation!=null&&(v=U(t.adaptation).subscribe(P=>{for(let B of P)B[0]===E&&T(B[1])}));function T(O){if(a.emit(O),O.rpmCap!=null&&Number.isFinite(O.rpmCap)&&O.rpmCap>=0&&(s.emit(O.rpmCap),Number.isFinite(n)&&n>0&&y.start(n,()=>s.emit(Number.POSITIVE_INFINITY))),O.tpmCap!=null&&Number.isFinite(O.tpmCap)&&O.tpmCap>=0&&(i.emit(O.tpmCap),Number.isFinite(n)&&n>0&&b.start(n,()=>i.emit(Number.POSITIVE_INFINITY))),O.retryAfterMs!=null&&O.retryAfterMs>0){let P=H()+O.retryAfterMs*1e6;P>g&&(g=P)}}let w=M(0,{name:"adaptiveRateLimiter/pending"}),x=M(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),k=M(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),S=O=>{w.emit((w.cache??0)+O)},R=()=>{x.emit(c.available()),k.emit(l.available())};async function N(O={}){let P=O.requestCost??1,B=O.tokenCost??0,j=O.signal;S(1);try{for(;;){if(j?.aborted)throw iu("AdaptiveRateLimiter.acquire aborted");let D=H();if(g>D){let q=Math.ceil((g-D)/1e6);await Qs(q,j);continue}if(P>0&&p||B>0&&f){await Qs(250,j);continue}let Z=c,F=l;if(!Z.tryConsume(P)){await Qs(Ip(Z,P),j);continue}if(!(B>0?F.tryConsume(B):!0)){Z.putBack(P),await Qs(Ip(F,B),j);continue}R();return}}finally{S(-1)}}function _(O){O>0?l.tryConsume(O):O<0&&l.putBack(-O),R()}function I(){m(),h(),v?.(),y.cancel(),b.cancel()}return{effectiveRpm:u,effectiveTpm:d,lastSignal:a,pending:w,rpmAvailable:x,tpmAvailable:k,acquire:N,recordUsage:_,recordSignal:T,dispose:I}}function nr(t,e){if(!Number.isFinite(t)||t===1/0)return Vt(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let n=Math.max(1,t*e),r=t/60;return Vt(n,r)}function Ip(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 Qs(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(iu("AdaptiveRateLimiter.acquire aborted")):new Promise((n,r)=>{let o=new Le,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(iu("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",s,{once:!0}))})}he();function au(t,e={}){let n=e.limiter??Pp({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=su(i);a&&n.recordSignal(a)},s=et(t,{async invoke(i,a){let u=r(i,a);await n.acquire({requestCost:1,tokenCost:u,signal:a?.signal});try{let d=await Ye(U(t.invoke(i,a))),c=d.usage??Op(),p=yt(c)+Gt(c)-u;return p>0&&n.recordUsage(p),d}catch(d){throw o(d),d}},async*stream(i,a){let u=r(i,a);await n.acquire({requestCost:1,tokenCost:u,signal:a?.signal});try{let d=0;for await(let l of t.stream(i,a))l.type==="usage"&&(d=yt(l.usage)+Gt(l.usage)),yield l;let c=d-u;c>0&&n.recordUsage(c)}catch(d){throw o(d),d}}});return Ue(s,"withRateLimiter",t),{adapter:s,limiter:n}}Ot();he();var po=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 uu(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:wt(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 c=0;c<n.length;c++){let l=n[c];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 Ye(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[c+1];f&&e.onFallback?.(l.name,f.name,p)}}let d={skipped:a,failed:u};throw e.onExhausted?.(d),new po(d)},async*stream(s,i){let a=[],u=new Map;for(let c=0;c<n.length;c++){let l=n[c];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[c+1];m&&e.onFallback?.(l.name,m.name,f)}}let d={skipped:a,failed:u};throw e.onExhausted?.(d),new po(d)}};return Ue(o,`cascade[${n.map(s=>s.name).join(",")}]`),o}function _h(t,e,n){let r={name:t,adapter:e};return n?.breaker&&(r.breaker=n.breaker),n?.filter&&(r.filter=n.filter),r}he();vt();function Xs(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function Dp(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Xs()):new Promise((n,r)=>{let o=new Le,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(Xs())},e.addEventListener("abort",s,{once:!0}))})}function du(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??Mh,u=e.retryStreaming??!0,d=(l,p)=>{if(s==="decorrelated"){let g=Math.min(o,Math.max(r,p*3));return r+Math.random()*(g-r)}let f=s==="exp"?r*2**(l-1):r*l,m=Math.min(o,f);if(!i)return m;let h=m*(.5+Math.random());return Math.min(o,h)},c=et(t,{async invoke(l,p){if(p?.signal?.aborted)throw Xs();let f,m=r;for(let h=1;h<=n;h++)try{return await Ye(U(t.invoke(l,p)))}catch(g){if(f=g,h>=n||!a(g,h))throw g;let y=d(h,m);m=y,await Dp(y,p?.signal)}throw f},async*stream(l,p){if(p?.signal?.aborted)throw Xs();if(!u){for await(let h of t.stream(l,p))yield h;return}let f,m=r;for(let h=1;h<=n;h++){let g=!1;try{for await(let y of t.stream(l,p))g=!0,yield y;return}catch(y){if(f=y,g||h>=n||!a(y,h))throw y;let b=d(h,m);m=b,await Dp(b,p?.signal)}}throw f}});return Ue(c,"withRetry",t),c}function Mh(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}he();vt();var rr=class extends Error{constructor(n){super(`LLM call timed out after ${n}ms`);this.ms=n}name="LLMTimeoutError"};function cu(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let n=s=>{let i=new AbortController,a=!1,u,d=new Le;return s&&(s.aborted?i.abort(s.reason):(u=()=>{d.cancel(),i.abort(s.reason)},s.addEventListener("abort",u,{once:!0}))),d.start(e,()=>{a=!0,i.abort(new rr(e))}),{signal:i.signal,cancel:()=>{d.cancel(),s&&u&&s.removeEventListener("abort",u)},timedOut:()=>a}},r=(s,i)=>{if(!i||s instanceof rr)throw s;let a=s;if(a?.name==="AbortError"||a?.name==="DOMException"&&Number(a.code)===20||s?.message==="aborted"){let d=new rr(e);throw d.cause=s,d}throw s},o=et(t,{async invoke(s,i){let{signal:a,cancel:u,timedOut:d}=n(i?.signal);try{return await Ye(U(t.invoke(s,{...i,signal:a})))}catch(c){return r(c,d())}finally{u()}},async*stream(s,i){let{signal:a,cancel:u,timedOut:d}=n(i?.signal);try{for await(let c of t.stream(s,{...i,signal:a}))yield c}catch(c){r(c,d())}finally{u()}}});return Ue(o,"withTimeout",t),o}function Oh(t,e={}){let n={adapter:t},r=t;if(e.rateLimit){let o=au(r,e.rateLimit);r=o.adapter,n.rateLimiter=o.limiter}if(e.budget){let o=ou(r,e.budget);r=o.adapter,n.budget=o.budget}if(e.breaker){let o=nu(r,e.breaker);r=o.adapter,n.breaker=o.breaker}if(e.timeoutMs!=null&&(r=cu(r,e.timeoutMs)),e.retry&&(r=du(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=uu([{name:e.name??"primary",adapter:r},{name:"fallback",adapter:e.fallback}],o)}return e.cache&&(r=lo(r,e.cache)),n.adapter=r,n}ee();he();function Ch(t,e,n){let r=U(e);return Te(r,s=>{if(!s||s.length===0)return M(null);let i=n?.tools;return t.invoke(s,{model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,tools:i,systemPrompt:n?.systemPrompt})})}_e();he();ae();he();vt();function fe(t,e){return ze("ai",t,e)}function Ah(t){return t!=null&&typeof t.then=="function"}function lu(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function Lh(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var Ih=3e4;function Gp(t,e){if(t.status==="settled"){let r=t.cache;if(r!==void 0)return Promise.resolve(r)}let n=e?.timeoutMs??Ih;return new Promise((r,o)=>{let s=new Le,i=t.subscribe(a=>{for(let u of a){if(u[0]===E){s.cancel(),i(),r(u[1]);return}if(u[0]===C){s.cancel(),i(),o(u[1]);return}if(u[0]===L){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 fo(t){return Ah(t)?fo(await t):lu(t)?Gp(t):Lh(t)?Gp(U(t)):t}function or(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function Ph(t,e){let n=U(t),r=e?.refreshTrigger!=null?U(e.refreshTrigger):null;return r==null?z([n],(o,s,i)=>{if(i.store.emitted===!0)return;let u=o[0],d=u!=null&&u.length>0?u.at(-1):i.prevData[0];if(d!==void 0)return i.store.emitted=!0,s.emit(d),{invalidate:()=>{i.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:fe("frozen_context")}):z([n,r],(o,s,i)=>{let a=o[1];if(!(a!=null&&a.length>0))return;let d=o[0],c=d!=null&&d.length>0?d.at(-1):i.prevData[0];s.emit(c)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:fe("frozen_context")})}ae();ee();he();function Fp(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function Dh(t,e=200){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function wn(t,e,n,r){let o=r?.format??"text",s=r?.name??"prompt_node",i=A(e,u=>{if(u.some(c=>c==null))return[];let d=typeof n=="string"?n:n(...u);return d?[{role:"user",content:d}]:[]},{name:`${s}::messages`,meta:fe("prompt_node")});return Te(i,u=>!u||u.length===0?M(null):K(d=>{let c=!1,l=!1,p,f={model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt};if(r?.abort){let y=ts(r.abort);f.signal=y.signal,p=y.dispose}let m;try{m=t.invoke(u,f)}catch(y){return c=!0,d.down([[C,y]]),()=>{p?.()}}let g=U(m).subscribe(y=>{if(!(l||c))for(let b of y){if(c)return;if(b[0]===E){let v=b[1];try{let T=Fp(v),w=o==="json"?JSON.parse(or(T)):T;d.emit(w)}catch(T){let w=Fp(v),x=new Error(`promptNode: failed to parse LLM response as JSON: ${T.message}
37
- Raw content (first 200 chars): ${Dh(w)}`);c=!0,d.down([[C,x]]);return}}else if(b[0]===C){c=!0,d.down([[C,b[1]]]);return}else if(b[0]===L){c=!0,d.down([[L]]);return}else d.down([b])}});return()=>{l=!0,g(),p?.()}},{name:`${s}::call`,meta:fe("prompt_node::call")}),{name:`${s}::output`,meta:r?.meta?{...fe("prompt_node::output"),...r.meta}:fe("prompt_node::output")})}Me();xe();ee();he();var oi={};ke(oi,{MessagingHubGraph:()=>ti,SubscriptionGraph:()=>mo,TopicBridgeGraph:()=>Zs,TopicGraph:()=>kn,TopicRegistry:()=>ei,messagingHub:()=>go,subscription:()=>$p,topic:()=>ni,topicBridge:()=>ri});_e();var Gh=256;function sr(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Yt(t,e){return ze("messaging",t,e)}var Fh=1024,kn=class extends Y{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=Ve([],{name:"events",maxSize:n.retainedLimit??Fh}),this._log.withLatest(),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=A([this.events],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:Yt("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(re(this.latest)),this.hasLatest=A([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:Yt("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(re(this.hasLatest)),this.addDisposer(()=>{this.events.down([[L]])}),this.addDisposer(()=>this._log.disposeAllViews())}publish(e){if(e===void 0)throw new TypeError(`TopicGraph "${this.name}": publish(undefined) is not allowed (spec \xA75.12 SENTINEL).`);this._log.append(e)}attachEventStorage(e){return this._log.attachStorage(e)}retained(){return this.events.cache}get _logBundle(){return this._log}},mo=class extends Y{cursor;available;topic;_disposed=!1;constructor(e,n,r={}){super(e,r.graph),this.topic=n;let o;if(r.from!==void 0?r.from==="retained"?o=0:r.from==="now"?o=n.events.cache.length:o=sr(r.from,"subscription from"):o=sr(r.cursor??0,"subscription cursor"),this.cursor=M(o,{name:"cursor",describeKind:"state",meta:Yt("subscription_cursor")}),this.add(this.cursor,{name:"cursor"}),this.available=n._logBundle.view({kind:"fromCursor",cursor:this.cursor}),this.add(this.available,{name:"available"}),this.addDisposer(re(this.available)),r.advanceOn!==void 0){let s=r.advanceOn,i=!1,a=z([s],()=>{if(!i){i=!0;return}if(this._disposed)return;let u=this.available.cache;if(u.length===0)return;let d=this.cursor.cache+u.length;this.cursor.emit(d)},{name:"advancePump",describeKind:"effect",meta:Yt("subscription_advance_pump")});this.add(a,{name:"advancePump"}),this.addDisposer(re(a))}}ack(e){if(this._disposed)return this.cursor.cache;let n=this.available.cache,r=e===void 0?n.length:sr(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){if(this._disposed)return[];let n=this.available.cache,r=e===void 0?n.length:sr(e,"subscription pull limit");return n.slice(0,r)}pullAndAck(e){if(this._disposed)return{items:[],cursor:this.cursor.cache};let n=this.available.cache,r=e===void 0?n.length:sr(e,"subscription pullAndAck limit"),o=n.slice(0,r);if(o.length===0)return{items:o,cursor:this.cursor.cache};let s=this.cursor.cache+o.length;return this.cursor.emit(s),{items:o,cursor:s}}dispose(){this._disposed||(this._disposed=!0,this.cursor.down([[L]]),this.destroy())}},Zs=class extends Y{_sourceSub;bridgedCount;output;constructor(e,n,r,o={}){super(e,o.graph),this._sourceSub=$p(`${e}-subscription`,n,{cursor:o.cursor}),this.mount("subscription",this._sourceSub);let s=Math.max(1,sr(o.maxPerPump??Gh,"topic bridge maxPerPump")),i=o.map??(p=>p);this.output=A([this._sourceSub.available],([p])=>{let f=p,m=[],h=Math.min(f.length,s);for(let g=0;g<h;g++){let y=i(f[g]);y!==void 0&&m.push(y)}return m},{name:"output",describeKind:"derived",meta:Yt("topic_bridge_output",{targetRef:r.name}),initial:[]}),this.add(this.output,{name:"output"}),this.addDisposer(re(this.output)),this.bridgedCount=M(0,{name:"bridgedCount",describeKind:"state",meta:Yt("topic_bridge_count")}),this.add(this.bridgedCount,{name:"bridgedCount"}),this.addDisposer(re(this.bridgedCount));let a=this.output,u=this._sourceSub,d=this.bridgedCount,c=z([a],()=>{let p=a.cache;if(p.length===0)return;let f=u.available.cache.length,m=Math.min(f,s);if(m>0){u.ack(m);let h=d.cache??0;d.emit(h+p.length)}},{name:"ackPump",describeKind:"effect",meta:Yt("topic_bridge_ack_pump")});this.add(c,{name:"ackPump"}),this.addDisposer(re(c));let l=$h(this.output,r);this.addDisposer(l)}};function $h(t,e){return t.subscribe(n=>{for(let r of n){if(r[0]!==E)continue;let o=r[1];o.length!==0&&X(()=>{for(let s of o)e.publish(s)})}})}var ei=class{_map=new Map;version;constructor(e){this.version=e}get size(){return this._map.size}has(e){return this._map.has(e)}get(e){return this._map.get(e)}set(e,n){this._map.set(e,n)}delete(e){return this._map.delete(e)}keys(){return this._map.keys()}},ti=class extends Y{_registry;version;_defaultTopicOptions;constructor(e,n={}){super(e,n.graph);let r=M(0,{name:"version",describeKind:"state",meta:Yt("hub_version")});this.add(r,{name:"version"}),this.version=r,this._registry=new ei(r),this._defaultTopicOptions={...n.defaultTopicOptions??{}}}get size(){return this._registry.size}has(e){return this._registry.has(e)}topicNames(){return this._registry.keys()}topic(e,n){let r=this._registry.get(e);if(r===void 0){let o={...this._defaultTopicOptions,...n??{}};r=new kn(e,o),this._registry.set(e,r),this.mount(e,r);let s=this.version.cache??0;this.version.emit(s+1)}return r}publish(e,n){this.topic(e).publish(n)}publishMany(e){X(()=>{for(let[n,r]of e)this.topic(n).publish(r)})}subscribe(e,n,r){let o=this.topic(n);return new mo(e,o,r)}removeTopic(e){if(!this._registry.has(e))return!1;try{this.remove(e)}finally{this._registry.delete(e);let n=this.version.cache??0;this.version.emit(n+1)}return!0}};function ni(t,e){return new kn(t,e)}function go(t,e){return new ti(t,e)}function $p(t,e,n){return new mo(t,e,n)}function ri(t,e,n,r){return new Zs(t,e,n,r)}var si={};ke(si,{PipelineGraph:()=>yo,decisionKeyOf:()=>jp,pipelineGraph:()=>ir});Me();xe();ae();_e();ee();function ho(t,e){return ze("orchestration",t,e)}var jp=t=>t.action,yo=class extends Y{constructor(e,n){super(e,n)}task(e,n,r={}){let o=(r.deps??[]).map(i=>this._resolveStep(i)),s=A(o,n,{name:e,describeKind:"derived",meta:ho("task",r.meta)});return this.add(s,{name:e}),s}classify(e,n,r,o={}){let s=this._resolveStep(n),i=A([s],([a])=>{try{return{tag:r(a),value:a}}catch(u){return{tag:"error",value:a,error:u}}},{name:e,describeKind:"derived",meta:ho("classify",o.meta)});return this.add(i,{name:e}),i}combine(e,n,r={}){let o=Object.keys(n),s=o.map(a=>this._resolveStep(n[a])),i=A(s,a=>{let u={};for(let d=0;d<o.length;d++)u[o[d]]=a[d];return u},{name:e,describeKind:"derived",meta:ho("combine",r.meta)});return this.add(i,{name:e}),i}gate(e,n,r={}){let o=r.maxPending??1e3;if(o<1&&o!==Number.POSITIVE_INFINITY)throw new RangeError("gate: maxPending must be >= 1");let s=r.startOpen??!1;typeof n!="string"&&this.nameOf(n)===void 0&&this.add(n,{name:`${e}/source`});let i=this._resolveStep(n),a=new Y(`${e}_state`),u=M([],{name:"pending",equals:()=>!1}),d=M(s,{name:"isOpen"}),c=A([u],([F])=>F.length,{name:"count"}),l=M(0,{name:"droppedCount"}),p=kt({name:"decisions",retainedLimit:1024,graph:a});a.add(u,{name:"pending"}),a.add(d,{name:"isOpen"}),a.add(c,{name:"count"}),a.add(l,{name:"droppedCount"}),this.mount(`${e}_state`,a);let f=[],m=!1,h=!1,g=s,y=d.subscribe(F=>{for(let Q of F)Q[0]===E&&(g=Q[1])});this.addDisposer(y);function b(){u.emit([...f])}function v(F,Q,G){p.append({action:F,t_ns:oe(),...Q!==void 0?{items:Q,count:Q.length}:{},...G!==void 0?{unflushed:G}:{},...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}function T(F){if(f.push(F),f.length>o){let Q=f.shift();l.emit(l.cache+1),v("drop",[Q])}b()}function w(F){let Q=f.splice(0,F);return b(),Q}let x=z([i],(F,Q,G)=>{let q=G.terminalDeps[0];if(q!==void 0){m=!0;let te=f.length;f=[],b(),v("teardown",void 0,te),Q.down(q===!0?[[L]]:[[C,q]]);return}let $=F[0];if($==null||$.length===0){Q.down([[V]]);return}for(let te of $)g?Q.emit(te):(T(te),Q.down([[V]]))},{name:e,describeKind:"derived",meta:ho("gate",r.meta)});if(this.add(x,{name:e}),r.approver!=null){r.approver.cache&&(d.emit(!0),g=!0,r.onceOnly&&(h=!0));let Q=r.approver.subscribe(G=>{for(let q of G){if(q[0]!==E)continue;let $=!!q[1];if($&&!g){if(r.onceOnly){if(h)continue;h=!0}X(()=>{d.emit(!0);let te=w(f.length);v("open",te);for(let Re of te){if(m)break;x.emit(Re)}})}else if(!$&&g){if(r.onceOnly&&h)continue;X(()=>{d.emit(!1),v("close")})}}});this.addDisposer(Q)}let k=F=>{if(m)throw new Error(`gate: ${F}() called after gate was torn down`)},S=(F=1)=>{k("approve");let Q=w(F);for(let G of Q){if(m)break;x.emit(G)}},R=(F=1)=>{k("reject"),w(F)},N=(F,Q=1)=>{k("modify");let G=[...f],q=w(Q);for(let $=0;$<q.length&&!m;$++)x.emit(F(q[$],$,G))},_=()=>{k("open"),d.emit(!0);let F=w(f.length);for(let Q of F){if(m)break;x.emit(Q)}},I=()=>{k("close"),!(r.onceOnly&&h)&&d.emit(!1)},O=Yn(S,{audit:p,freeze:!1,onSuccess:(F,Q,G)=>({action:"approve",count:F[0]??1,t_ns:G.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,Q,G)=>({action:"drop",t_ns:G.t_ns,errorType:G.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),P=Yn(R,{audit:p,freeze:!1,onSuccess:(F,Q,G)=>({action:"reject",count:F[0]??1,t_ns:G.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,Q,G)=>({action:"drop",t_ns:G.t_ns,errorType:G.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),B=Yn(N,{audit:p,freeze:!1,onSuccess:(F,Q,G)=>({action:"modify",count:F[1]??1,t_ns:G.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,Q,G)=>({action:"drop",t_ns:G.t_ns,errorType:G.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),j=Yn(_,{audit:p,freeze:!1,onSuccess:(F,Q,G)=>({action:"open",t_ns:G.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,Q,G)=>({action:"drop",t_ns:G.t_ns,errorType:G.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),D=Yn(I,{audit:p,freeze:!1,onSuccess:(F,Q,G)=>({action:"close",t_ns:G.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,Q,G)=>({action:"drop",t_ns:G.t_ns,errorType:G.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})});return this.addDisposer(c.subscribe(()=>{})),{node:x,pending:u,count:c,isOpen:d,droppedCount:l,decisions:p,audit:p,approve:O,reject:P,modify:B,open:j,close:D}}approval(e,n,r,o={}){return this.gate(e,n,{...o,approver:r,maxPending:1})}catch(e,n,r,o={}){let s=this._resolveStep(n),i=o.on??"error",a=z([s],(u,d,c)=>{let l=c.terminalDeps[0];if(l!==void 0){let f=l===!0?{kind:"complete"}:{kind:"error",error:l};if(i==="terminal"||i===f.kind){d.emit(r(f,d));return}d.down(f.kind==="complete"?[[L]]:[[C,f.error]]);return}let p=u[0];if(p==null||p.length===0){d.down([[V]]);return}for(let f of p)d.emit(f)},{name:e,describeKind:"derived",completeWhenDepsComplete:o.completeWhenDepsComplete??!(i==="complete"||i==="terminal"),errorWhenDepsError:!(i==="error"||i==="terminal"),meta:ho("catch",o.meta)});return this.add(a,{name:e}),a}_resolveStep(e){if(typeof e=="string")return this.resolve(e);if(this.nameOf(e)===void 0)throw new Error(`PipelineGraph "${this.name}": Node dep is not registered. Pass a string path or call graph.add(node) first.`);return e}};function ir(t,e){return new yo(t,e)}async function Bp(t,e,n,r){let o="",s=0;for await(let i of t.stream(e,n))r.publish({...i,seq:s++,ts:oe()}),i.type==="token"&&(o+=i.delta);return o}function Vp(t,e){if(e==="json")try{return JSON.parse(or(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 Kp(t,e){return A([t.latest],([n],r)=>{let o=r.store;if(n==null)return o.acc??"";let s=n;return s.seq===0&&(o.acc=""),s.type==="token"&&(o.acc=(o.acc??"")+s.delta),o.acc??""},{name:e,meta:fe("accumulated_text"),initial:""})}function jh(t,e,n,r){let o=r?.name??"llm",s=r?.format??"text",i=ni(`${o}/stream`,{...r?.retainedLimit!=null?{retainedLimit:r.retainedLimit}:{}}),a=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:fe("prompt_node::messages"),initial:[]}),u=Te(a,l=>{let p=l;if(!p||p.length===0)return M(null);let f=new AbortController;async function*m(){try{let h=await Bp(t,p,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,signal:f.signal},i);yield Vp(h,s)}finally{f.abort()}}return U(m())}),d=Kp(i,`${o}::accumulatedText`),c=re(u);return{output:u,deltaTopic:i,accumulatedText:d,dispose:()=>{c(),i.destroy()}}}function Bh(t,e,n,r,o,s){let i=M(0,{name:`${e}/cancel`}),a=0,u=[...r,i],d=s?.name??e,c=s?.format??"text",l=ni(`${d}/stream`,{...s?.retainedLimit!=null?{retainedLimit:s.retainedLimit}:{}}),p=A(u,k=>{let S=k.slice(0,-1);if(S.some(N=>N==null))return[];let R=typeof o=="string"?o:o(...S);return R?[{role:"user",content:R}]:[]},{name:`${d}::messages`,meta:fe("prompt_node::messages"),initial:[]}),f=Te(p,k=>{let S=k;if(!S||S.length===0)return M(null);let R=new AbortController;async function*N(){try{let _=await Bp(n,S,{model:s?.model,temperature:s?.temperature,maxTokens:s?.maxTokens,systemPrompt:s?.systemPrompt,signal:R.signal},l);yield Vp(_,c)}finally{R.abort()}}return U(N())}),m=Kp(l,`${d}::accumulatedText`),h=Xe(f,k=>k!=null);t.add(h,{name:`${e}/raw`});let g=ir(`${e}/gate-graph`);t.mount(`${e}/gate-graph`,g),g.add(h,{name:`${e}/raw`});let y=g.gate(`${e}/gate`,`${e}/raw`,s?.gate),b=re(f),v=re(y.node),T=re(m);t.addDisposer(b),t.addDisposer(v),t.addDisposer(T);let w=y.reject.bind(y),x={...y,reject(k=1){X(()=>{w(k),i.emit(++a)})}};return{output:y.node,deltaTopic:l,accumulatedText:m,gate:x,dispose:()=>{b(),v(),T(),l.destroy()}}}ee();he();function Vh(t,e){let n=e?.separator??`
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 _p(t,e,n){let r={},o=t.generationConfig;o&&(typeof o.maxOutputTokens=="number"&&(r.maxOutputTokens=o.maxOutputTokens),typeof o.temperature=="number"&&(r.temperature=o.temperature),o.thinkingConfig&&(r.thinkingConfig=o.thinkingConfig)),t.systemInstruction&&(r.systemInstruction=t.systemInstruction),t.tools&&(r.tools=t.tools);for(let[s,i]of Object.entries(t))s==="contents"||s==="generationConfig"||s==="systemInstruction"||s==="tools"||s==="abortSignal"||s==="model"||(r[s]=i);return n&&(r.abortSignal=n),{model:e,contents:t.contents,config:Object.keys(r).length>0?r:void 0}}function Xa(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 Mp(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:Xa(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=Hs(s,i),d=H(),c=`${e}/models/${encodeURIComponent(a)}:generateContent?${o()}`,l=await n(c,{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,(H()-d)/1e6);return Mp(p,f)},async*stream(s,i){let a=r(i),u=Hs(s,i),d=`${e}/models/${encodeURIComponent(a)}:streamGenerateContent?alt=sse&${o()}`,c=await n(d,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",...t.headers??{}},body:JSON.stringify(u),signal:i?.signal});if(!c.ok)throw await ht(c,"Google");if(!c.body)throw new Error("googleAdapter: streaming response has no body");let l,p;for await(let f of Dt(c.body,{signal:i?.signal})){if(!f.data)continue;let m;try{m=JSON.parse(f.data)}catch{continue}let h=m.candidates?.[0];for(let g of h?.content?.parts??[])typeof g.text=="string"&&(g.thought?yield{type:"thinking",delta:g.text}:yield{type:"token",delta:g.text}),g.functionCall&&(yield{type:"tool-call-delta",delta:{name:g.functionCall.name,argumentsDelta:JSON.stringify(g.functionCall.args??{})}});h?.finishReason&&(p=h.finishReason),m.usageMetadata&&(l=m.usageMetadata)}l&&(yield{type:"usage",usage:Xa(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=Hs(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=_p(o,s,r?.signal),a=H(),u=await e.models.generateContent(i),d=Math.max(0,(H()-a)/1e6);return Mp(u,d)},async*stream(n,r){if(!e.models.generateContentStream)throw new Error("sdkBackedGoogle: SDK instance does not expose generateContentStream");let o=Hs(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=_p(o,s,r?.signal),a,u,d=await e.models.generateContentStream(i);for await(let c of d){let l=c.candidates?.[0];for(let p of l?.content?.parts??[])typeof p.text=="string"&&(p.thought?yield{type:"thinking",delta:p.text}:yield{type:"token",delta:p.text}),p.functionCall&&(yield{type:"tool-call-delta",delta:{name:p.functionCall.name,argumentsDelta:JSON.stringify(p.functionCall.args??{})}});l?.finishReason&&(u=l.finishReason),c.usageMetadata&&(a=c.usageMetadata)}a&&(yield{type:"usage",usage:Xa(a)}),yield{type:"finish",reason:u??"stop"}}}}xe();var dh={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 Za(t={}){return t.sdk?mh(t):fh(t)}function Ws(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(ch);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 ch(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 eu(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 Op(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:eu(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 Ap(t){let e=t.preset??"openai",n=dh[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}=Ap(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 d=Ws(a,u,t.model,!1,t.bodyExtras),c=H(),l=await o(`${n}/chat/completions`,{method:"POST",headers:i(),body:JSON.stringify(d),signal:u?.signal});if(!l.ok)throw await ht(l,e);let p=await l.json(),f=Math.max(0,(H()-c)/1e6);return Op(p,f,e)},async*stream(a,u){let d=Ws(a,u,t.model,!0,t.bodyExtras),c=await o(`${n}/chat/completions`,{method:"POST",headers:{...i(),accept:"text/event-stream"},body:JSON.stringify(d),signal:u?.signal});if(!c.ok)throw await ht(c,e);if(!c.body)throw new Error(`openAICompatAdapter[${e}]: streaming response has no body`);let l,p;for await(let f of Dt(c.body,{signal:u?.signal})){if(!f.data||f.data==="[DONE]")continue;let m;try{m=JSON.parse(f.data)}catch{continue}let h=m.choices;if(h){let g=h[0];if(g?.delta?.content&&(yield{type:"token",delta:g.delta.content}),g?.delta?.reasoning_content&&(yield{type:"thinking",delta:g.delta.reasoning_content}),g?.delta?.tool_calls)for(let y of g.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:y.id,name:y.function?.name,argumentsDelta:y.function?.arguments}};g?.finish_reason&&(p=g.finish_reason)}m.usage&&(l=m.usage,yield{type:"usage",usage:eu(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}=Ap(t);return{provider:n,model:t.model,async invoke(r,o){let s=Ws(r,o,t.model,!1,t.bodyExtras),i=H(),a=await e.chat.completions.create(s,{signal:o?.signal}),u=Math.max(0,(H()-i)/1e6);return Op(a,u,n)},async*stream(r,o){let s=Ws(r,o,t.model,!0,t.bodyExtras),i=await e.chat.completions.create(s,{signal:o?.signal}),a,u;for await(let d of i){let c=d.choices;if(c){let p=c[0];if(p?.delta?.content&&(yield{type:"token",delta:p.delta.content}),p?.delta?.reasoning_content&&(yield{type:"thinking",delta:p.delta.reasoning_content}),p?.delta?.tool_calls)for(let f of p.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:f.id,name:f.function?.name,argumentsDelta:f.function?.arguments}};p?.finish_reason&&(u=p.finish_reason)}let l=d.usage;l&&(a=l,yield{type:"usage",usage:eu(l)})}yield{type:"finish",reason:u??"stop"}}}}function gh(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 za(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 Qa(e)}case"dry-run":{let e={model:t.model,...t.extras};return bn(e)}case"fallback":{let e={provider:t.provider,model:t.model,...t.extras};return Ya(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 Za(e)}default:{let e=t.provider;throw new Error(`createAdapter: unknown provider: ${String(e)}`)}}}xe();ee();he();function yt(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 Gt(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 Cp(){return{input:{regular:0},output:{regular:0}}}function hh(t,e){let n=e?.logMax??1e3,r=Ve(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:n}),o=M(null,{name:"adapterStats/lastCall"}),s=C([r.entries],([h])=>h.length,{name:"adapterStats/totalCalls",initial:0}),i=C([r.entries],([h])=>h.reduce((g,y)=>g+yt(y.usage),0),{name:"adapterStats/totalInputTokens",initial:0}),a=C([r.entries],([h])=>h.reduce((g,y)=>g+Gt(y.usage),0),{name:"adapterStats/totalOutputTokens",initial:0}),u=[re(s),re(i),re(a)],d=h=>{r.append(h),o.emit(h)},c=()=>{r.clear(),o.emit(null)},l=et(t,{invoke(h,g){let y=H(),b=oe(),v=t.model??g?.model??"",T=k=>(d(vn({provider:t.provider,model:t.model??g?.model??k.model??"",tier:g?.tier??k.tier,usage:k.usage??Rt(),startNs:y,startWallClockNs:b,method:"invoke"})),k),w=k=>{let x=k;d(vn({provider:t.provider,model:v,tier:g?.tier,usage:Rt(),startNs:y,startWallClockNs:b,method:"invoke",error:{type:x?.name??"Error",message:x?.message??String(k)}}))};return qs(t.invoke(h,g),{onResp:T,onError:w,name:"adapterStats/invokeTap"})},async*stream(h,g){let y=H(),b=oe(),v=t.model??g?.model??"",T;try{for await(let w of t.stream(h,g))w.type==="usage"&&(T=w.usage),yield w;d(vn({provider:t.provider,model:v,tier:g?.tier,usage:T??Rt(),startNs:y,startWallClockNs:b,method:"stream"}))}catch(w){let k=w;throw d(vn({provider:t.provider,model:v,tier:g?.tier,usage:T??Rt(),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:c,dispose:()=>{if(!p){p=!0;for(let h of u)h();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 Us(t="USD"){return{total:0,currency:t}}function tu(t,e,n){let r=yt(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=yh(b,r),T=y*v/1e6;a+=T,s&&(i[g]=(i[g]??0)+T)},d=t.input,c=e.input;if(c&&(u("input.regular",d.regular,c.regular),u("input.cacheRead",d.cacheRead??0,c.cacheRead),u("input.cacheWrite5m",d.cacheWrite5m??0,c.cacheWrite5m),u("input.cacheWrite1h",d.cacheWrite1h??0,c.cacheWrite1h),u("input.cacheWriteOther",d.cacheWriteOther??0,c.cacheWriteOther),u("input.audio",d.audio??0,c.audio),u("input.image",d.image??0,c.image),u("input.video",d.video??0,c.video),u("input.toolUse",d.toolUse??0,c.toolUse),d.extensions&&c.extensions))for(let[g,y]of Object.entries(d.extensions))u(`input.ext.${g}`,y,c.extensions[g]);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[g,y]of Object.entries(l.extensions))u(`output.ext.${g}`,y,p.extensions[g]);let f=n?.tier;if(f&&e.tierMultipliers){let g=e.tierMultipliers[f];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 zs(t,e){return`${t}::${e}`}function bh(t){let e=new Map,n=new Map,r=(o,s,i)=>{e.set(zs(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(zs(o,s));if(i)return i.pricing;let a=n.get(o);if(!a)return;let u;for(let d of a)if(s.startsWith(d)&&(!u||d.length>u.key.length)){let c=e.get(zs(o,d));c&&(u={key:d,pricing:c.pricing})}return u?.pricing},remove(o,s){let i=e.delete(zs(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?tu(n,o,{tier:r.tier,withBreakdown:r.withBreakdown}):Us(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):Us()}}function wh(t,e,n){return t?.pricing?tu(e,t.pricing,n):Us()}Ot();he();function nu(t,e={}){let n=e.breaker??wt(e),r=et(t,{async invoke(o,s){if(!n.canExecute())throw new pt;try{let i=await Ye(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 pt;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}}xe();ae();ee();he();var Js=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"},ru=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),Lp=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function ou(t,e){let n=Ve(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),r=M(Lp(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=C([r],([d])=>{let c=d;return!(e.caps.calls!=null&&c.calls>=e.caps.calls||e.caps.inputTokens!=null&&c.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&c.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&c.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(re(o),e.onExhausted!=null){let d=e.onExhausted,c=!1,l=!0;o.subscribe(p=>{for(let f of p)if(f[0]===E){let m=f[1];if(c&&l&&m===!1){let h=Ip(r.cache??ru,e.caps);h&&d(h)}l=m,c=!0}})}let s=()=>{if(o.cache===!1){let d=r.cache??ru,c=Ip(d,e.caps);return new Js(c??"budget",e.caps[c??"calls"]??0,kh(d,c??"calls"))}},i=(d,c)=>{let l=t.provider,p=vn({provider:l,model:c.model,tier:c.tier,usage:d,startNs:c.startNs,method:c.method,...c.error?{error:c.error}:{}});n.append(p);let f=r.cache??ru,m=e.pricingFn?f.usd+e.pricingFn(d,{model:c.model,provider:l,tier:c.tier}).total:f.usd;r.emit({calls:f.calls+1,inputTokens:f.inputTokens+yt(d),outputTokens:f.outputTokens+Gt(d),usd:m})},a=()=>{n.clear(),r.emit(Lp())},u=et(t,{invoke(d,c){let l=s();if(l)return Promise.reject(l);let p=H(),f=t.model??c?.model??"",m=g=>(i(g.usage??Rt(),{model:t.model??c?.model??g.model??"",tier:c?.tier??g.tier,startNs:p,method:"invoke"}),g),h=g=>{let y=g;i(Rt(),{model:f,tier:c?.tier,startNs:p,method:"invoke",error:{type:y?.name??"Error",message:y?.message??String(g)}})};return qs(t.invoke(d,c),{onResp:m,onError:h,name:"budgetGate/invokeTap"})},async*stream(d,c){let l=s();if(l)throw l;let p=H(),f;try{for await(let m of t.stream(d,c))m.type==="usage"&&(f=m.usage),yield m;i(f??Rt(),{model:t.model??c?.model??"",tier:c?.tier,startNs:p,method:"stream"})}catch(m){let h=m;throw i(f??Rt(),{model:t.model??c?.model??"",tier:c?.tier,startNs:p,method:"stream",error:{type:h?.name??"Error",message:h?.message??String(m)}}),m}}});return Ue(u,"withBudgetGate",t),{adapter:u,budget:{totals:r,isOpen:o,log:n,reset:a}}}function Ip(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}}he();function xh(t,e){let n=e.mock??bn({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=re(o));let i=()=>r!==void 0?r:!!o?.cache,a=et(t,{invoke(d,c){return i()?n.invoke(d,c):t.invoke(d,c)},stream(d,c){return i()?n.stream(d,c):t.stream(d,c)}});return Ue(a,"withDryRun",t),{adapter:a,dispose:()=>{s&&(s(),s=void 0)}}}function su(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=Eh(s);i!=null&&(o.retryAfterMs=i);let a=r("anthropic-ratelimit-requests-reset");if(a){let f=Pp(a);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let u=r("anthropic-ratelimit-tokens-reset");if(u){let f=Pp(u);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let d=Ys(r,"x-ratelimit-limit-requests");d!=null&&(o.rpmCap=d);let c=Ys(r,"x-ratelimit-limit-tokens");c!=null&&(o.tpmCap=c);let l=Ys(r,"x-ratelimit-remaining-requests"),p=Ys(r,"x-ratelimit-remaining-tokens");if(l!=null&&d!=null&&d>0&&(o.usageHint??={},o.usageHint.rpm=1-l/d),p!=null&&c!=null&&c>0&&(o.usageHint??={},o.usageHint.tpm=1-p/c),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 Ys(t,e){let n=t(e);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function Eh(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 Pp(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var Nh=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function _h(t){let e=Nh.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)}xe();ae();ee();Ot();he();vt();function iu(t){let e=new Error(t);return e.name="AbortError",e}function Gp(t={}){let e=Math.max(1,t.burstMultiplier??1),n=t.clampCooldownMs??6e4,r=t.rpm!=null?U(t.rpm):M(Number.POSITIVE_INFINITY),o=t.tpm!=null?U(t.tpm):M(Number.POSITIVE_INFINITY),s=M(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),i=M(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),a=M({},{name:"adaptiveRateLimiter/lastSignal"}),u=C([r,s],([O,P])=>Math.min(Number(O??1/0),Number(P??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),d=C([o,i],([O,P])=>Math.min(Number(O??1/0),Number(P??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),c=nr(Number(r.cache??Number.POSITIVE_INFINITY),e),l=nr(Number(o.cache??Number.POSITIVE_INFINITY),e),p=!1,f=!1,m=u.subscribe(O=>{for(let P of O)if(P[0]===E){let B=Number(P[1]);Number.isFinite(B)&&B>0?(c=nr(B,e),p=!1):B===1/0?(c=nr(1/0,e),p=!1):B<=0&&(p=!0)}}),h=d.subscribe(O=>{for(let P of O)if(P[0]===E){let B=Number(P[1]);Number.isFinite(B)&&B>0?(l=nr(B,e),f=!1):B===1/0?(l=nr(1/0,e),f=!1):B<=0&&(f=!0)}}),g=0,y=new Le,b=new Le,v;t.adaptation!=null&&(v=U(t.adaptation).subscribe(P=>{for(let B of P)B[0]===E&&T(B[1])}));function T(O){if(a.emit(O),O.rpmCap!=null&&Number.isFinite(O.rpmCap)&&O.rpmCap>=0&&(s.emit(O.rpmCap),Number.isFinite(n)&&n>0&&y.start(n,()=>s.emit(Number.POSITIVE_INFINITY))),O.tpmCap!=null&&Number.isFinite(O.tpmCap)&&O.tpmCap>=0&&(i.emit(O.tpmCap),Number.isFinite(n)&&n>0&&b.start(n,()=>i.emit(Number.POSITIVE_INFINITY))),O.retryAfterMs!=null&&O.retryAfterMs>0){let P=H()+O.retryAfterMs*1e6;P>g&&(g=P)}}let w=M(0,{name:"adaptiveRateLimiter/pending"}),k=M(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),x=M(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),S=O=>{w.emit((w.cache??0)+O)},R=()=>{k.emit(c.available()),x.emit(l.available())};async function N(O={}){let P=O.requestCost??1,B=O.tokenCost??0,j=O.signal;S(1);try{for(;;){if(j?.aborted)throw iu("AdaptiveRateLimiter.acquire aborted");let D=H();if(g>D){let q=Math.ceil((g-D)/1e6);await Qs(q,j);continue}if(P>0&&p||B>0&&f){await Qs(250,j);continue}let Z=c,F=l;if(!Z.tryConsume(P)){await Qs(Dp(Z,P),j);continue}if(!(B>0?F.tryConsume(B):!0)){Z.putBack(P),await Qs(Dp(F,B),j);continue}R();return}}finally{S(-1)}}function _(O){O>0?l.tryConsume(O):O<0&&l.putBack(-O),R()}function I(){m(),h(),v?.(),y.cancel(),b.cancel()}return{effectiveRpm:u,effectiveTpm:d,lastSignal:a,pending:w,rpmAvailable:k,tpmAvailable:x,acquire:N,recordUsage:_,recordSignal:T,dispose:I}}function nr(t,e){if(!Number.isFinite(t)||t===1/0)return Vt(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let n=Math.max(1,t*e),r=t/60;return Vt(n,r)}function Dp(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 Qs(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(iu("AdaptiveRateLimiter.acquire aborted")):new Promise((n,r)=>{let o=new Le,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(iu("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",s,{once:!0}))})}he();function au(t,e={}){let n=e.limiter??Gp({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=su(i);a&&n.recordSignal(a)},s=et(t,{async invoke(i,a){let u=r(i,a);await n.acquire({requestCost:1,tokenCost:u,signal:a?.signal});try{let d=await Ye(U(t.invoke(i,a))),c=d.usage??Cp(),p=yt(c)+Gt(c)-u;return p>0&&n.recordUsage(p),d}catch(d){throw o(d),d}},async*stream(i,a){let u=r(i,a);await n.acquire({requestCost:1,tokenCost:u,signal:a?.signal});try{let d=0;for await(let l of t.stream(i,a))l.type==="usage"&&(d=yt(l.usage)+Gt(l.usage)),yield l;let c=d-u;c>0&&n.recordUsage(c)}catch(d){throw o(d),d}}});return Ue(s,"withRateLimiter",t),{adapter:s,limiter:n}}Ot();he();var po=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 uu(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:wt(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 c=0;c<n.length;c++){let l=n[c];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 Ye(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[c+1];f&&e.onFallback?.(l.name,f.name,p)}}let d={skipped:a,failed:u};throw e.onExhausted?.(d),new po(d)},async*stream(s,i){let a=[],u=new Map;for(let c=0;c<n.length;c++){let l=n[c];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[c+1];m&&e.onFallback?.(l.name,m.name,f)}}let d={skipped:a,failed:u};throw e.onExhausted?.(d),new po(d)}};return Ue(o,`cascade[${n.map(s=>s.name).join(",")}]`),o}function Ah(t,e,n){let r={name:t,adapter:e};return n?.breaker&&(r.breaker=n.breaker),n?.filter&&(r.filter=n.filter),r}he();vt();function Xs(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function Fp(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Xs()):new Promise((n,r)=>{let o=new Le,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(Xs())},e.addEventListener("abort",s,{once:!0}))})}function du(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??Ch,u=e.retryStreaming??!0,d=(l,p)=>{if(s==="decorrelated"){let g=Math.min(o,Math.max(r,p*3));return r+Math.random()*(g-r)}let f=s==="exp"?r*2**(l-1):r*l,m=Math.min(o,f);if(!i)return m;let h=m*(.5+Math.random());return Math.min(o,h)},c=et(t,{async invoke(l,p){if(p?.signal?.aborted)throw Xs();let f,m=r;for(let h=1;h<=n;h++)try{return await Ye(U(t.invoke(l,p)))}catch(g){if(f=g,h>=n||!a(g,h))throw g;let y=d(h,m);m=y,await Fp(y,p?.signal)}throw f},async*stream(l,p){if(p?.signal?.aborted)throw Xs();if(!u){for await(let h of t.stream(l,p))yield h;return}let f,m=r;for(let h=1;h<=n;h++){let g=!1;try{for await(let y of t.stream(l,p))g=!0,yield y;return}catch(y){if(f=y,g||h>=n||!a(y,h))throw y;let b=d(h,m);m=b,await Fp(b,p?.signal)}}throw f}});return Ue(c,"withRetry",t),c}function Ch(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}he();vt();var rr=class extends Error{constructor(n){super(`LLM call timed out after ${n}ms`);this.ms=n}name="LLMTimeoutError"};function cu(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let n=s=>{let i=new AbortController,a=!1,u,d=new Le;return s&&(s.aborted?i.abort(s.reason):(u=()=>{d.cancel(),i.abort(s.reason)},s.addEventListener("abort",u,{once:!0}))),d.start(e,()=>{a=!0,i.abort(new rr(e))}),{signal:i.signal,cancel:()=>{d.cancel(),s&&u&&s.removeEventListener("abort",u)},timedOut:()=>a}},r=(s,i)=>{if(!i||s instanceof rr)throw s;let a=s;if(a?.name==="AbortError"||a?.name==="DOMException"&&Number(a.code)===20||s?.message==="aborted"){let d=new rr(e);throw d.cause=s,d}throw s},o=et(t,{async invoke(s,i){let{signal:a,cancel:u,timedOut:d}=n(i?.signal);try{return await Ye(U(t.invoke(s,{...i,signal:a})))}catch(c){return r(c,d())}finally{u()}},async*stream(s,i){let{signal:a,cancel:u,timedOut:d}=n(i?.signal);try{for await(let c of t.stream(s,{...i,signal:a}))yield c}catch(c){r(c,d())}finally{u()}}});return Ue(o,"withTimeout",t),o}function Lh(t,e={}){let n={adapter:t},r=t;if(e.rateLimit){let o=au(r,e.rateLimit);r=o.adapter,n.rateLimiter=o.limiter}if(e.budget){let o=ou(r,e.budget);r=o.adapter,n.budget=o.budget}if(e.breaker){let o=nu(r,e.breaker);r=o.adapter,n.breaker=o.breaker}if(e.timeoutMs!=null&&(r=cu(r,e.timeoutMs)),e.retry&&(r=du(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=uu([{name:e.name??"primary",adapter:r},{name:"fallback",adapter:e.fallback}],o)}return e.cache&&(r=lo(r,e.cache)),n.adapter=r,n}ee();he();function Ih(t,e,n){let r=U(e);return Te(r,s=>{if(!s||s.length===0)return M(null);let i=n?.tools;return t.invoke(s,{model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,tools:i,systemPrompt:n?.systemPrompt})})}_e();he();ae();he();vt();function fe(t,e){return ze("ai",t,e)}function Ph(t){return t!=null&&typeof t.then=="function"}function lu(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function Dh(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var Gh=3e4;function $p(t,e){if(t.status==="settled"){let r=t.cache;if(r!==void 0)return Promise.resolve(r)}let n=e?.timeoutMs??Gh;return new Promise((r,o)=>{let s=new Le,i=t.subscribe(a=>{for(let u of a){if(u[0]===E){s.cancel(),i(),r(u[1]);return}if(u[0]===A){s.cancel(),i(),o(u[1]);return}if(u[0]===L){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 fo(t){return Ph(t)?fo(await t):lu(t)?$p(t):Dh(t)?$p(U(t)):t}function or(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function Fh(t,e){let n=U(t),r=e?.refreshTrigger!=null?U(e.refreshTrigger):null;return r==null?z([n],(o,s,i)=>{if(i.store.emitted===!0)return;let u=o[0],d=u!=null&&u.length>0?u.at(-1):i.prevData[0];if(d!==void 0)return i.store.emitted=!0,s.emit(d),{invalidate:()=>{i.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:fe("frozen_context")}):z([n,r],(o,s,i)=>{let a=o[1];if(!(a!=null&&a.length>0))return;let d=o[0],c=d!=null&&d.length>0?d.at(-1):i.prevData[0];s.emit(c)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:fe("frozen_context")})}ae();ee();he();function jp(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function $h(t,e=200){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function wn(t,e,n,r){let o=r?.format??"text",s=r?.name??"prompt_node",i=C(e,u=>{if(u.some(c=>c==null))return[];let d=typeof n=="string"?n:n(...u);return d?[{role:"user",content:d}]:[]},{name:`${s}::messages`,meta:fe("prompt_node")});return Te(i,u=>!u||u.length===0?M(null):K(d=>{let c=!1,l=!1,p,f={model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt};if(r?.abort){let y=ts(r.abort);f.signal=y.signal,p=y.dispose}let m;try{m=t.invoke(u,f)}catch(y){return c=!0,d.down([[A,y]]),()=>{p?.()}}let g=U(m).subscribe(y=>{if(!(l||c))for(let b of y){if(c)return;if(b[0]===E){let v=b[1];try{let T=jp(v),w=o==="json"?JSON.parse(or(T)):T;d.emit(w)}catch(T){let w=jp(v),k=new Error(`promptNode: failed to parse LLM response as JSON: ${T.message}
37
+ Raw content (first 200 chars): ${$h(w)}`);c=!0,d.down([[A,k]]);return}}else if(b[0]===A){c=!0,d.down([[A,b[1]]]);return}else if(b[0]===L){c=!0,d.down([[L]]);return}else d.down([b])}});return()=>{l=!0,g(),p?.()}},{name:`${s}::call`,meta:fe("prompt_node::call")}),{name:`${s}::output`,meta:r?.meta?{...fe("prompt_node::output"),...r.meta}:fe("prompt_node::output")})}Me();xe();ee();he();var oi={};ke(oi,{MessagingHubGraph:()=>ti,SubscriptionGraph:()=>mo,TopicBridgeGraph:()=>Zs,TopicGraph:()=>kn,TopicRegistry:()=>ei,messagingHub:()=>go,subscription:()=>Bp,topic:()=>ni,topicBridge:()=>ri});_e();var jh=256;function sr(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Yt(t,e){return ze("messaging",t,e)}var Bh=1024,kn=class extends Y{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=Ve([],{name:"events",maxSize:n.retainedLimit??Bh}),this._log.withLatest(),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=C([this.events],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:Yt("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(re(this.latest)),this.hasLatest=C([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:Yt("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(re(this.hasLatest)),this.addDisposer(()=>{this.events.down([[L]])}),this.addDisposer(()=>this._log.disposeAllViews())}publish(e){if(e===void 0)throw new TypeError(`TopicGraph "${this.name}": publish(undefined) is not allowed (spec \xA75.12 SENTINEL).`);this._log.append(e)}attachEventStorage(e){return this._log.attachStorage(e)}retained(){return this.events.cache}get _logBundle(){return this._log}},mo=class extends Y{cursor;available;topic;_disposed=!1;constructor(e,n,r={}){super(e,r.graph),this.topic=n;let o;if(r.from!==void 0?r.from==="retained"?o=0:r.from==="now"?o=n.events.cache.length:o=sr(r.from,"subscription from"):o=sr(r.cursor??0,"subscription cursor"),this.cursor=M(o,{name:"cursor",describeKind:"state",meta:Yt("subscription_cursor")}),this.add(this.cursor,{name:"cursor"}),this.available=n._logBundle.view({kind:"fromCursor",cursor:this.cursor}),this.add(this.available,{name:"available"}),this.addDisposer(re(this.available)),r.advanceOn!==void 0){let s=r.advanceOn,i=!1,a=z([s],()=>{if(!i){i=!0;return}if(this._disposed)return;let u=this.available.cache;if(u.length===0)return;let d=this.cursor.cache+u.length;this.cursor.emit(d)},{name:"advancePump",describeKind:"effect",meta:Yt("subscription_advance_pump")});this.add(a,{name:"advancePump"}),this.addDisposer(re(a))}}ack(e){if(this._disposed)return this.cursor.cache;let n=this.available.cache,r=e===void 0?n.length:sr(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){if(this._disposed)return[];let n=this.available.cache,r=e===void 0?n.length:sr(e,"subscription pull limit");return n.slice(0,r)}pullAndAck(e){if(this._disposed)return{items:[],cursor:this.cursor.cache};let n=this.available.cache,r=e===void 0?n.length:sr(e,"subscription pullAndAck limit"),o=n.slice(0,r);if(o.length===0)return{items:o,cursor:this.cursor.cache};let s=this.cursor.cache+o.length;return this.cursor.emit(s),{items:o,cursor:s}}dispose(){this._disposed||(this._disposed=!0,this.cursor.down([[L]]),this.destroy())}},Zs=class extends Y{_sourceSub;bridgedCount;output;constructor(e,n,r,o={}){super(e,o.graph),this._sourceSub=Bp(`${e}-subscription`,n,{cursor:o.cursor}),this.mount("subscription",this._sourceSub);let s=Math.max(1,sr(o.maxPerPump??jh,"topic bridge maxPerPump")),i=o.map??(p=>p);this.output=C([this._sourceSub.available],([p])=>{let f=p,m=[],h=Math.min(f.length,s);for(let g=0;g<h;g++){let y=i(f[g]);y!==void 0&&m.push(y)}return m},{name:"output",describeKind:"derived",meta:Yt("topic_bridge_output",{targetRef:r.name}),initial:[]}),this.add(this.output,{name:"output"}),this.addDisposer(re(this.output)),this.bridgedCount=M(0,{name:"bridgedCount",describeKind:"state",meta:Yt("topic_bridge_count")}),this.add(this.bridgedCount,{name:"bridgedCount"}),this.addDisposer(re(this.bridgedCount));let a=this.output,u=this._sourceSub,d=this.bridgedCount,c=z([a],()=>{let p=a.cache;if(p.length===0)return;let f=u.available.cache.length,m=Math.min(f,s);if(m>0){u.ack(m);let h=d.cache??0;d.emit(h+p.length)}},{name:"ackPump",describeKind:"effect",meta:Yt("topic_bridge_ack_pump")});this.add(c,{name:"ackPump"}),this.addDisposer(re(c));let l=Vh(this.output,r);this.addDisposer(l)}};function Vh(t,e){return t.subscribe(n=>{for(let r of n){if(r[0]!==E)continue;let o=r[1];o.length!==0&&X(()=>{for(let s of o)e.publish(s)})}})}var ei=class{_map=new Map;version;constructor(e){this.version=e}get size(){return this._map.size}has(e){return this._map.has(e)}get(e){return this._map.get(e)}set(e,n){this._map.set(e,n)}delete(e){return this._map.delete(e)}keys(){return this._map.keys()}},ti=class extends Y{_registry;version;_defaultTopicOptions;constructor(e,n={}){super(e,n.graph);let r=M(0,{name:"version",describeKind:"state",meta:Yt("hub_version")});this.add(r,{name:"version"}),this.version=r,this._registry=new ei(r),this._defaultTopicOptions={...n.defaultTopicOptions??{}}}get size(){return this._registry.size}has(e){return this._registry.has(e)}topicNames(){return this._registry.keys()}topic(e,n){let r=this._registry.get(e);if(r===void 0){let o={...this._defaultTopicOptions,...n??{}};r=new kn(e,o),this._registry.set(e,r),this.mount(e,r);let s=this.version.cache??0;this.version.emit(s+1)}return r}publish(e,n){this.topic(e).publish(n)}publishMany(e){X(()=>{for(let[n,r]of e)this.topic(n).publish(r)})}subscribe(e,n,r){let o=this.topic(n);return new mo(e,o,r)}removeTopic(e){if(!this._registry.has(e))return!1;try{this.remove(e)}finally{this._registry.delete(e);let n=this.version.cache??0;this.version.emit(n+1)}return!0}};function ni(t,e){return new kn(t,e)}function go(t,e){return new ti(t,e)}function Bp(t,e,n){return new mo(t,e,n)}function ri(t,e,n,r){return new Zs(t,e,n,r)}var si={};ke(si,{PipelineGraph:()=>yo,decisionKeyOf:()=>Vp,pipelineGraph:()=>ir});Me();xe();ae();_e();ee();function ho(t,e){return ze("orchestration",t,e)}var Vp=t=>t.action,yo=class extends Y{constructor(e,n){super(e,n)}task(e,n,r={}){let o=(r.deps??[]).map(i=>this._resolveStep(i)),s=C(o,n,{name:e,describeKind:"derived",meta:ho("task",r.meta)});return this.add(s,{name:e}),s}classify(e,n,r,o={}){let s=this._resolveStep(n),i=C([s],([a])=>{try{return{tag:r(a),value:a}}catch(u){return{tag:"error",value:a,error:u}}},{name:e,describeKind:"derived",meta:ho("classify",o.meta)});return this.add(i,{name:e}),i}combine(e,n,r={}){let o=Object.keys(n),s=o.map(a=>this._resolveStep(n[a])),i=C(s,a=>{let u={};for(let d=0;d<o.length;d++)u[o[d]]=a[d];return u},{name:e,describeKind:"derived",meta:ho("combine",r.meta)});return this.add(i,{name:e}),i}gate(e,n,r={}){let o=r.maxPending??1e3;if(o<1&&o!==Number.POSITIVE_INFINITY)throw new RangeError("gate: maxPending must be >= 1");let s=r.startOpen??!1;typeof n!="string"&&this.nameOf(n)===void 0&&this.add(n,{name:`${e}/source`});let i=this._resolveStep(n),a=new Y(`${e}_state`),u=M([],{name:"pending",equals:()=>!1}),d=M(s,{name:"isOpen"}),c=C([u],([F])=>F.length,{name:"count"}),l=M(0,{name:"droppedCount"}),p=kt({name:"decisions",retainedLimit:1024,graph:a});a.add(u,{name:"pending"}),a.add(d,{name:"isOpen"}),a.add(c,{name:"count"}),a.add(l,{name:"droppedCount"}),this.mount(`${e}_state`,a);let f=[],m=!1,h=!1,g=s,y=d.subscribe(F=>{for(let Q of F)Q[0]===E&&(g=Q[1])});this.addDisposer(y);function b(){u.emit([...f])}function v(F,Q,G){p.append({action:F,t_ns:oe(),...Q!==void 0?{items:Q,count:Q.length}:{},...G!==void 0?{unflushed:G}:{},...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}function T(F){if(f.push(F),f.length>o){let Q=f.shift();l.emit(l.cache+1),v("drop",[Q])}b()}function w(F){let Q=f.splice(0,F);return b(),Q}let k=z([i],(F,Q,G)=>{let q=G.terminalDeps[0];if(q!==void 0){m=!0;let te=f.length;f=[],b(),v("teardown",void 0,te),Q.down(q===!0?[[L]]:[[A,q]]);return}let $=F[0];if($==null||$.length===0){Q.down([[V]]);return}for(let te of $)g?Q.emit(te):(T(te),Q.down([[V]]))},{name:e,describeKind:"derived",meta:ho("gate",r.meta)});if(this.add(k,{name:e}),r.approver!=null){r.approver.cache&&(d.emit(!0),g=!0,r.onceOnly&&(h=!0));let Q=r.approver.subscribe(G=>{for(let q of G){if(q[0]!==E)continue;let $=!!q[1];if($&&!g){if(r.onceOnly){if(h)continue;h=!0}X(()=>{d.emit(!0);let te=w(f.length);v("open",te);for(let Re of te){if(m)break;k.emit(Re)}})}else if(!$&&g){if(r.onceOnly&&h)continue;X(()=>{d.emit(!1),v("close")})}}});this.addDisposer(Q)}let x=F=>{if(m)throw new Error(`gate: ${F}() called after gate was torn down`)},S=(F=1)=>{x("approve");let Q=w(F);for(let G of Q){if(m)break;k.emit(G)}},R=(F=1)=>{x("reject"),w(F)},N=(F,Q=1)=>{x("modify");let G=[...f],q=w(Q);for(let $=0;$<q.length&&!m;$++)k.emit(F(q[$],$,G))},_=()=>{x("open"),d.emit(!0);let F=w(f.length);for(let Q of F){if(m)break;k.emit(Q)}},I=()=>{x("close"),!(r.onceOnly&&h)&&d.emit(!1)},O=Yn(S,{audit:p,freeze:!1,onSuccess:(F,Q,G)=>({action:"approve",count:F[0]??1,t_ns:G.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,Q,G)=>({action:"drop",t_ns:G.t_ns,errorType:G.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),P=Yn(R,{audit:p,freeze:!1,onSuccess:(F,Q,G)=>({action:"reject",count:F[0]??1,t_ns:G.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,Q,G)=>({action:"drop",t_ns:G.t_ns,errorType:G.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),B=Yn(N,{audit:p,freeze:!1,onSuccess:(F,Q,G)=>({action:"modify",count:F[1]??1,t_ns:G.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,Q,G)=>({action:"drop",t_ns:G.t_ns,errorType:G.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),j=Yn(_,{audit:p,freeze:!1,onSuccess:(F,Q,G)=>({action:"open",t_ns:G.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,Q,G)=>({action:"drop",t_ns:G.t_ns,errorType:G.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),D=Yn(I,{audit:p,freeze:!1,onSuccess:(F,Q,G)=>({action:"close",t_ns:G.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,Q,G)=>({action:"drop",t_ns:G.t_ns,errorType:G.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})});return this.addDisposer(c.subscribe(()=>{})),{node:k,pending:u,count:c,isOpen:d,droppedCount:l,decisions:p,audit:p,approve:O,reject:P,modify:B,open:j,close:D}}approval(e,n,r,o={}){return this.gate(e,n,{...o,approver:r,maxPending:1})}catch(e,n,r,o={}){let s=this._resolveStep(n),i=o.on??"error",a=z([s],(u,d,c)=>{let l=c.terminalDeps[0];if(l!==void 0){let f=l===!0?{kind:"complete"}:{kind:"error",error:l};if(i==="terminal"||i===f.kind){d.emit(r(f,d));return}d.down(f.kind==="complete"?[[L]]:[[A,f.error]]);return}let p=u[0];if(p==null||p.length===0){d.down([[V]]);return}for(let f of p)d.emit(f)},{name:e,describeKind:"derived",completeWhenDepsComplete:o.completeWhenDepsComplete??!(i==="complete"||i==="terminal"),errorWhenDepsError:!(i==="error"||i==="terminal"),meta:ho("catch",o.meta)});return this.add(a,{name:e}),a}_resolveStep(e){if(typeof e=="string")return this.resolve(e);if(this.nameOf(e)===void 0)throw new Error(`PipelineGraph "${this.name}": Node dep is not registered. Pass a string path or call graph.add(node) first.`);return e}};function ir(t,e){return new yo(t,e)}async function Kp(t,e,n,r){let o="",s=0;for await(let i of t.stream(e,n))r.publish({...i,seq:s++,ts:oe()}),i.type==="token"&&(o+=i.delta);return o}function qp(t,e){if(e==="json")try{return JSON.parse(or(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 Hp(t,e){return C([t.latest],([n],r)=>{let o=r.store;if(n==null)return o.acc??"";let s=n;return s.seq===0&&(o.acc=""),s.type==="token"&&(o.acc=(o.acc??"")+s.delta),o.acc??""},{name:e,meta:fe("accumulated_text"),initial:""})}function Kh(t,e,n,r){let o=r?.name??"llm",s=r?.format??"text",i=ni(`${o}/stream`,{...r?.retainedLimit!=null?{retainedLimit:r.retainedLimit}:{}}),a=C(e,l=>{if(l.some(f=>f==null))return[];let p=typeof n=="string"?n:n(...l);return p?[{role:"user",content:p}]:[]},{name:`${o}::messages`,meta:fe("prompt_node::messages"),initial:[]}),u=Te(a,l=>{let p=l;if(!p||p.length===0)return M(null);let f=new AbortController;async function*m(){try{let h=await Kp(t,p,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,signal:f.signal},i);yield qp(h,s)}finally{f.abort()}}return U(m())}),d=Hp(i,`${o}::accumulatedText`),c=re(u);return{output:u,deltaTopic:i,accumulatedText:d,dispose:()=>{c(),i.destroy()}}}function qh(t,e,n,r,o,s){let i=M(0,{name:`${e}/cancel`}),a=0,u=[...r,i],d=s?.name??e,c=s?.format??"text",l=ni(`${d}/stream`,{...s?.retainedLimit!=null?{retainedLimit:s.retainedLimit}:{}}),p=C(u,x=>{let S=x.slice(0,-1);if(S.some(N=>N==null))return[];let R=typeof o=="string"?o:o(...S);return R?[{role:"user",content:R}]:[]},{name:`${d}::messages`,meta:fe("prompt_node::messages"),initial:[]}),f=Te(p,x=>{let S=x;if(!S||S.length===0)return M(null);let R=new AbortController;async function*N(){try{let _=await Kp(n,S,{model:s?.model,temperature:s?.temperature,maxTokens:s?.maxTokens,systemPrompt:s?.systemPrompt,signal:R.signal},l);yield qp(_,c)}finally{R.abort()}}return U(N())}),m=Hp(l,`${d}::accumulatedText`),h=Xe(f,x=>x!=null);t.add(h,{name:`${e}/raw`});let g=ir(`${e}/gate-graph`);t.mount(`${e}/gate-graph`,g),g.add(h,{name:`${e}/raw`});let y=g.gate(`${e}/gate`,`${e}/raw`,s?.gate),b=re(f),v=re(y.node),T=re(m);t.addDisposer(b),t.addDisposer(v),t.addDisposer(T);let w=y.reject.bind(y),k={...y,reject(x=1){X(()=>{w(x),i.emit(++a)})}};return{output:y.node,deltaTopic:l,accumulatedText:m,gate:k,dispose:()=>{b(),v(),T(),l.destroy()}}}ee();he();function Hh(t,e){let n=e?.separator??`
38
38
 
39
- `,r=t.map(i=>typeof i=="string"?M(i):U(i)),o=A(r,i=>i.filter(a=>a!=null&&a!=="").join(n),{name:e?.name??"systemPrompt",describeKind:"derived",meta:fe("system_prompt"),initial:""}),s=re(o);return Object.assign(o,{dispose:s})}ee();var Kh=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens&&t.estimated===e.estimated;function qh(t,e){let n=e?.charsPerToken??4,r={chunkCount:0,charCount:0,estimatedTokens:0,estimated:!0};return A([t.latest],([o],s)=>{if(o==null)return r;let 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=yt(i.usage)+Gt(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:fe("cost_meter_extractor"),equals:Kh})}ee();var Hh=(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 Wh(t,e){let n=e.maxPatternLength??128;for(let o of e.patterns)if(o.pattern.source.length>n)throw new Error(`keywordFlagExtractor: pattern "${o.label}" literal exceeds maxPatternLength (${o.pattern.source.length} > ${n}); raise the option or shorten the pattern.`);let r=e.patterns.map(o=>({label:o.label,pattern:o.pattern,compiled:new RegExp(o.pattern.source,`${o.pattern.flags.replace("g","")}g`)}));return A([t],([o],s)=>{if(o==null)return[];let i=o;"flags"in s.store||(s.store.flags=[],s.store.scannedTo=0);let a=s.store.flags,u=s.store.scannedTo,d=Math.max(0,u-n),c=i.slice(d),l=!1;for(let{pattern:p,label:f,compiled:m}of r){m.lastIndex=0;for(let h of c.matchAll(m)){let g=d+(h.index??0);g+h[0].length<=u||(a.push({label:f,pattern:p,match:h[0],position:g}),l=!0)}}return s.store.scannedTo=i.length,l?[...a]:a.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:fe("keyword_flag_extractor"),equals:Hh})}ee();function zh(t,e,n){return A([t],([r])=>r==null?null:e(r),{name:n?.name??"extractor",describeKind:"derived",initial:null,meta:fe("stream_extractor"),...n?.equals?{equals:n.equals}:{}})}ee();var Uh=(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 A([t],([n],r)=>{if(n==null)return[];let o=n;"calls"in r.store||(r.store.calls=[],r.store.scanFrom=0);let s=r.store.calls,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 d=0,c=-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==="{")d++;else if(m==="}"&&(d--,d===0)){c=f;break}}if(c===-1){r.store.scanFrom=u;break}let p=o.slice(u,c+1);try{let f=JSON.parse(p);typeof f.name=="string"&&f.arguments!=null&&typeof f.arguments=="object"&&(s.push({name:f.name,arguments:f.arguments,raw:p,startIndex:u}),a=!0)}catch{}i=c+1,r.store.scanFrom=i}return a?[...s]:s.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:fe("tool_call_extractor"),equals:Uh})}ee();function Yh(t,e,n,r){let o=n*(r?.hardMultiplier??1.5),s=typeof e!="function",i=[t];return s&&i.push(e),A(i,a=>{let u=a[0]??"";if(u.length===0)return"allow";let d=s?a[1]??0:e(u);return d>=o?"block":d>=n?"review":"allow"},{name:r?.name??"content-gate",initial:"allow"})}ee();function Qh(t,e,n,r){let o=n??(()=>"[REDACTED]");function s(i){let a=i;for(let u of e){let d=u.global?u:new RegExp(u.source,`${u.flags}g`);a=a.replace(d,c=>o(c,u))}return a}return A([t],([i])=>s(i??""),{name:r?.name??"redactor",initial:""})}Me();ae();_e();ee();he();ee();var ii=class extends Y{_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=A([this.messages],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:fe("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(re(this.latest)),this.messageCount=A([this.messages],([r])=>r.length,{name:"messageCount",describeKind:"derived",meta:fe("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(re(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 pu(t,e){return new ii(t,e)}ee();Ot();function fu(t){let{toolCalls:e,tools:n}=t,r=t.retryCount??1,o=t.onError??"rescue",s=(i,a)=>{if(i===a)return!0;if(i.length!==a.length)return!1;for(let u=0;u<i.length;u++){let d=i[u],c=a[u];if(d?.id!==c?.id||d?.content!==c?.content)return!1}return!0};return Te(e,i=>{if(i==null||i.length===0)throw new Error("toolExecution: received an empty tool-call batch as DATA \u2014 callers must upstream-filter empty batches (emit RESOLVED) so switchMap is only dispatched for non-empty batches.");let a=i.map(u=>Xh(u,n,r,o));return A(a,u=>u,{name:"toolExecution::batch",equals:s})})}function Xh(t,e,n,r){let o=Tt(()=>e.executeReactive(t.name,t.arguments),{count:n}),s=A([o],([i])=>({id:t.id,content:typeof i=="string"?i:JSON.stringify(i)}));return r==="propagate"?s:Yr(s,i=>({id:t.id,content:JSON.stringify({error:String(i)})}))}ae();ee();he();var ai=class extends Y{definitions;schemas;_bundle;constructor(e,n={}){super(e,n.graph),this._bundle=Ze({name:"definitions"}),this.definitions=this._bundle.entries,this.add(this.definitions,{name:"definitions"}),this.schemas=A([this.definitions],([r])=>[...(r??new Map).values()],{name:"schemas",describeKind:"derived",meta:fe("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(re(this.schemas))}register(e){this._bundle.set(e.name,e)}unregister(e){this._bundle.delete(e)}executeReactive(e,n){let r=this._bundle.get(e);if(!r)throw new Error(`toolRegistry: unknown tool "${e}"`);return K(o=>{let s=new AbortController,i;try{let u=r.handler(n,{signal:s.signal});i=Zh(u,s.signal)}catch(u){return o.down([[C,u]]),()=>{s.abort()}}let a=i.subscribe(u=>{o.down(u)});return()=>{s.abort(),a()}},{name:`executeReactive::${e}`,meta:fe("tool_execute_reactive")})}getDefinition(e){return this._bundle.entries.cache?.get(e)}};function mu(t,e){return new ai(t,e)}function Zh(t,e){return lu(t)?t:t!=null&&typeof t.then=="function"?zn(t,{signal:e}):t!=null&&typeof t=="object"&&Symbol.asyncIterator in t?Ir(t,{signal:e}):zn(Promise.resolve(t),{signal:e})}var ui=class extends Y{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;_terminalResult;_disposeRunWiring;_running=!1;_currentAbortController=null;constructor(e,n){if(super(e,n.graph),this.chat=pu(`${e}-chat`,{maxMessages:n.maxMessages}),this.mount("chat",this.chat),this.tools=mu(`${e}-tools`),this.mount("tools",this.tools),n.tools)for(let G of n.tools)this.tools.register(G);this.status=M("idle",{name:"status",describeKind:"state",meta:fe("agent_status")}),this.add(this.status,{name:"status"}),this.turn=M(0,{name:"turn",describeKind:"state",meta:fe("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.aborted=M(!1,{name:"aborted",describeKind:"state",meta:fe("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let r=0,o=this.turn.subscribe(G=>{for(let q of G)q[0]===E&&(r=q[1])}),s=!1,i=this.aborted.subscribe(G=>{for(let q of G)q[0]===E&&(s=q[1])}),a=this.chat.messages.cache??[],u=this.chat.messages.subscribe(G=>{for(let q of G)q[0]===E&&(a=q[1])}),d=this.tools.schemas.cache??[],c=this.tools.schemas.subscribe(G=>{for(let q of G)q[0]===E&&(d=q[1])}),l=n.adapter,p=n.systemPrompt,f=n.model,m=n.temperature,h=n.maxTokens,g=n.maxTurns??10,y=n.stopWhen,b=this.chat,v=this.tools,T=this.status,w=this.turn,x=this.aborted,k=z([T],(G,q,$)=>{if(bo(G,$.prevData,0,"idle")!=="thinking"||s||r>=g){q.down([[V]]);return}if(a.length===0){q.down([[V]]);return}q.emit({messages:a,tools:d})},{name:"promptInput",describeKind:"derived",meta:fe("agent_prompt_input",{closureReads:["aborted","turn","chat.messages","tools.schemas"]})}),S=Te(k,G=>{let q=new AbortController;return this._currentAbortController=q,s&&q.abort(new Error("agentLoop: aborted")),U(l.invoke(G.messages,{tools:G.tools.length>0?G.tools:void 0,systemPrompt:p,model:f,temperature:m,maxTokens:h,signal:q.signal}),{signal:q.signal})},{equals:()=>!1}),R=M(null,{name:"lastResponse",describeKind:"state",meta:fe("agent_last_response")});this.lastResponse=R;let N=z([R,T],(G,q,$)=>{let te=bo(G,$.prevData,0,null);if(bo(G,$.prevData,1,"idle")!=="acting"){q.down([[V]]);return}let Oe=te?.toolCalls;if(Oe==null||Oe.length===0){q.down([[V]]);return}q.emit(Oe)},{name:"toolCallsRaw",describeKind:"derived",meta:fe("agent_tool_calls_raw")}),_=n.interceptToolCalls?n.interceptToolCalls(N):N;this.toolCalls=_;let I=fu({toolCalls:_,tools:v,retryCount:1});this.toolResults=I;let O=pe([S],([G])=>{if(s)return;let q=G,$=r+1,te=q.toolCalls!=null&&q.toolCalls.length>0,Re=q.finishReason==="end_turn"&&(!q.toolCalls||q.toolCalls.length===0),Oe=y?.(q)===!0,Ce=$>=g,ye=Oe||Re||!te||Ce?"done":"acting";X(()=>{R.emit(q),T.emit(ye),w.emit($),b.append("assistant",q.content,{toolCalls:q.toolCalls})})}),P=pe([I],([G])=>{if(s)return;let q=G;if(q.length===0)return;let $=r>=g?"done":"thinking";X(()=>{T.emit($);for(let te of q)b.appendToolResult(te.id,te.content)})}),B=T.cache??"idle",j=T.subscribe(G=>{for(let q of G)q[0]===E&&(B=q[1])}),D=pe([x],([G])=>{G===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),B!=="done"&&T.emit("done"))}),Z=re(O),F=re(P),Q=re(D);this._terminalResult=z([T,R],(G,q,$)=>{let te=bo(G,$.prevData,0,"idle"),Re=bo(G,$.prevData,1,null);if(te==="done"){if(Re!=null){q.emit(Re);return}let Oe=new Error("agentLoop: aborted");Oe.name="AbortError",q.down([[C,Oe]]);return}if(te==="error"){q.down([[C,new Error("agentLoop: errored")]]);return}q.down([[V]])},{name:"terminalResult",describeKind:"derived",meta:fe("agent_terminal_result")}),this.add(k,{name:"promptInput"}),this.add(S,{name:"llmResponse"}),this.add(this.lastResponse,{name:"lastResponse"}),this.toolCalls===N?this.add(this.toolCalls,{name:"toolCalls"}):(this.add(N,{name:"toolCallsRaw"}),this.add(this.toolCalls,{name:"toolCalls"})),this.add(I,{name:"toolResults"}),this.add(this._terminalResult,{name:"terminalResult"}),this.addDisposer(o),this.addDisposer(i),this.addDisposer(j),this.addDisposer(u),this.addDisposer(c),this.addDisposer(Z),this.addDisposer(F),this.addDisposer(Q),this._disposeRunWiring=()=>{}}async run(e,n){if(this._running)throw new RangeError(`agentLoop "${this.name}": run() called while a previous run() is still pending \u2014 await the previous run before starting another, or call abort() first`);this._running=!0;let r;try{X(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle"),this.lastResponse.emit(null)}),e!=null&&this.chat.append("user",e);let o=es(this._terminalResult,{skipCurrent:!0});if(n!=null)if(n.aborted)this.aborted.emit(!0);else{let s=()=>this.aborted.emit(!0);n.addEventListener("abort",s,{once:!0}),r=()=>n.removeEventListener("abort",s)}return n?.aborted!==!0&&this.status.emit("thinking"),await o}finally{r?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function bo(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 ey(t,e){return new ui(t,e)}ee();he();function ty(t,e,n){let r=U(t),o=n?.condition!=null?U(n.condition):null,s=M(null,{name:n?.name?`${n.name}::null`:"handoff::null"});if(o==null)return Te(r,a=>{if(a==null)return s;let u=M(a);return e(u)});let i=A([r,o],([a,u])=>({v:a,open:u===!0}),{name:n?.name?`${n.name}::router`:"handoff::router",describeKind:"derived"});return Te(i,({v:a,open:u})=>{if(a==null)return s;if(!u)return M(a);let d=M(a);return e(d)})}ee();he();function ny(t,e,n){let r=U(t),o=e.map(i=>U(i)),s=[r,...o];return A(s,i=>{let a=i[0]??[],u=i.slice(1);return a.filter(d=>{for(let c of u)if(c!=null&&!c(d))return!1;return!0})},{name:n?.name??"tool-selector",describeKind:"derived",meta:fe("tool_selector"),equals:(i,a)=>{let u=i,d=a;if(u.length!==d.length)return!1;for(let c=0;c<u.length;c++)if(u[c]!==d[c])return!1;return!0}})}function qp(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 ry(t){let e={persistence:t.persistenceThreshold??.3,personalValue:t.personalValueThreshold??.3},n=qp({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}ee();he();ee();function Hp(t,e,n,r){let o=n.name??r;return s=>{let i=M(s);return wn(n.adapter,[i],a=>e(a),{name:o,format:"json",systemPrompt:t,model:n.model,temperature:n.temperature??0,maxTokens:n.maxTokens})}}function gu(t,e){let n=e.maxExistingKeys??100,r=Hp(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 hu(t,e){let n=Hp(t,r=>JSON.stringify({memories:r}),e,"llmConsolidator");return r=>{let o=[...r.entries()].map(([s,i])=>({key:s,value:i}));return n(o)}}Me();xe();ee();he();var ci={};ke(ci,{collection:()=>sy,decay:()=>xn,knowledgeGraph:()=>vu,lightCollection:()=>yu,vectorIndex:()=>bu});xe();ee();function xn(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 Wp(t){if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1")}function St(t){return new Map(t)}function nt(t){return t.cache??new Map}function di(t){return t.cache??[]}function oy(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 yu(t={}){let e=t.maxSize,n=t.policy??"fifo";Wp(e);let r=M(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 d=n==="lru"?u.lastAccessNs:u.createdAtNs,c=n==="lru"?a.lastAccessNs:a.createdAtNs;d<c&&(a=u)}if(!a)break;i.delete(a.id)}}function s(i){r.emit(i)}return{entries:r,upsert(i,a){let u=H(),d=nt(r),c=d.get(i),l=St(d);l.set(i,{id:i,value:a,createdAtNs:c?.createdAtNs??u,lastAccessNs:u}),o(l),s(l)},remove(i){let a=St(nt(r));a.delete(i)&&s(a)},clear(){nt(r).size!==0&&s(new Map)},get(i){let a=nt(r),u=a.get(i);if(u){if(n==="lru"){let d=H(),c=St(a);c.set(i,{...u,lastAccessNs:d}),s(c)}return u.value}},has(i){return nt(r).has(i)}}}function sy(t,e={}){let n=e.maxSize,r=e.policy??"lru",o=e.decayRate??0,s=e.minScore??0,i=e.score??(()=>1);Wp(n);let a=new Y(t),u=M(new Map,{name:"items",describeKind:"state"}),d=A([u],([h])=>{let g=h??new Map,y=H(),b=[...g.values()].map(v=>{let T=(y-v.lastAccessNs)/1e9;return{...v,score:xn(v.baseScore,T,o,s)}});return b.sort((v,T)=>T.score-v.score||T.lastAccessNs-v.lastAccessNs),b},{name:"ranked",describeKind:"derived"}),c=A([u],([h])=>(h??new Map).size,{name:"size",describeKind:"derived",initial:0});d.subscribe(()=>{}),c.subscribe(()=>{}),a.add(u,{name:"items"}),a.add(d,{name:"ranked"}),a.add(c,{name:"size"});function l(h,g){let y=(g-h.lastAccessNs)/1e9;return xn(h.baseScore,y,o,s)}function p(h){if(n!==void 0)for(;h.size>n;){let g=H(),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,x=r==="lru"?y.lastAccessNs:y.createdAtNs;w<x&&(y=v)}}if(!y)break;h.delete(y.id)}}function f(h){u.emit(h)}return Object.assign(a,{upsert(h,g,y){let b=H(),v=nt(u),T=v.get(h),w=y?.score??i(g),x=St(v);x.set(h,{id:h,value:g,baseScore:w,createdAtNs:T?.createdAtNs??b,lastAccessNs:b}),p(x),f(x)},remove(h){let g=St(nt(u));g.delete(h)&&f(g)},clear(){nt(u).size!==0&&f(new Map)},getItem(h){let g=nt(u),y=g.get(h);if(y){if(r==="lru"){let b=St(g);b.set(h,{...y,lastAccessNs:H()}),f(b)}return y}}})}function bu(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=M(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,d){s(u);let c=St(nt(o));c.set(a,{id:a,vector:[...u],meta:d}),e==="hnsw"&&r.upsert(a,u,d),i(c)},remove(a){let u=St(nt(o));u.delete(a)&&(e==="hnsw"&&r.remove(a),i(u))},clear(){nt(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):[...nt(o).values()].map(c=>({id:c.id,score:oy(a,c.vector),meta:c.meta})).sort((c,l)=>l.score-c.score).slice(0,u)}}}function vu(t){let e=new Y(t),n=M(new Map,{name:"entities",describeKind:"state"}),r=M([],{name:"edges",describeKind:"state"}),o=A([r],([u])=>{let d=u??[],c=new Map;for(let l of d){let p=c.get(l.from)??[];c.set(l.from,Object.freeze([...p,l]))}return c},{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,d){let c=St(nt(n));c.set(u,d),s(c)},removeEntity(u){let d=St(nt(n)),c=d.delete(u),l=di(r),p=l.filter(f=>f.from!==u&&f.to!==u);!c&&p.length===l.length||(s(d),i(p))},link(u,d,c,l=1){let p=`${u}\0${d}\0${c}`,f=di(r),m=new Set(f.map(g=>`${g.from}\0${g.to}\0${g.relation}`)),h=[...f];if(m.has(p))for(let g=0;g<h.length;g+=1){let y=h[g];if(y.from===u&&y.to===d&&y.relation===c){h[g]={...y,weight:l};break}}else h.push({from:u,to:d,relation:c,weight:l});i(h)},unlink(u,d,c){let l=di(r),p=l.filter(f=>c===void 0?!(f.from===u&&f.to===d):!(f.from===u&&f.to===d&&f.relation===c));p.length!==l.length&&i(p)},related(u,d){return di(r).filter(c=>(c.from===u||c.to===u)&&(d===void 0||c.relation===d))}})}var Tu=Math.LN2/604800;function ar(t){return t instanceof Map?t:new Map}function wu(t,e,n){let r=bu({dimension:n.dimension});t.add(r.entries,{name:"vectorIndex"});let s=pe([e.store.entries],([i])=>{let a=ar(i);for(let[u,d]of a){let c=n.embedFn(d);c&&r.upsert(u,c,d)}}).subscribe(()=>{});return t.addDisposer(s),{vectors:r,dispose:()=>s()}}function ku(t,e,n,r){let o=r.mountPath??n,s=vu(`${n}-kg`);if(t.mount(o,s),!r.entityFn)return{kg:s,dispose:()=>{}};let i=r.entityFn,u=pe([e.store.entries],([d])=>{let c=ar(d);for(let[l,p]of c){let f=i(l,p);if(f){for(let m of f.entities??[])s.upsertEntity(m.id,m.value);for(let m of f.relations??[])s.link(m.from,m.to,m.relation,m.weight)}}}).subscribe(()=>{});return t.addDisposer(u),{kg:s,dispose:()=>u()}}function xu(t,e,n){let r=n.decayRate??Tu,o=n.maxActive??1e3,s=n.archiveThreshold??.1,i=n.permanentFilter??(()=>!1),a=yu({name:"permanent"});t.add(a.entries,{name:"permanent"});let u=new Set,d=b=>u.has(b)?"permanent":ar(e.store.entries.cache).has(b)?"active":"archived",c=(b,v)=>{u.add(b),a.upsert(b,v)},l=new Map,p=e.store.entries,f=n.context?U(n.context):M(null),h=pe([p,f],([b,v])=>{let T=ar(b),w=H(),x=[],k=[];for(let[R,N]of T){if(l.has(R)||l.set(R,w),i(R,N)){k.push({key:R,value:N});continue}let _=n.score(N,v),I=l.get(R)??w,O=Number(w-I)/1e9;xn(_,O,r)<s&&x.push(R)}for(let R of l.keys())T.has(R)||l.delete(R);for(let{key:R,value:N}of k)u.has(R)||c(R,N);let S=T.size-u.size;if(S>o){let R=[...T.entries()].filter(([_])=>!u.has(_)).map(([_,I])=>({key:_,score:n.score(I,v)})).sort((_,I)=>_.score-I.score),N=S-o;for(let _=0;_<N&&_<R.length;_++){let I=R[_].key;x.includes(I)||x.push(I)}}x.length>0&&X(()=>{for(let R of x)e.store.delete(R)})}).subscribe(()=>{}),g=null;n.archiveTier&&(g=t.attachSnapshotStorage([n.archiveTier],n.archiveStorageOptions??{}));let y=()=>{h(),g?.dispose()};return t.addDisposer(y),{tiers:{permanent:a,activeEntries:p,archiveHandle:g,tierOf:d,markPermanent:c},dispose:y}}function iy(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 Ru(t,e,n,r,o){let s=o.topK??20,i=o.graphDepth??1,a=o.budget??2e3,u=o.contextWeight??0,d=o.context?U(o.context):M(null),c=(g,y,b)=>{let v=new Map,T=[];if(n&&b.vector){T=n.search(b.vector,s);for(let N of T){let _=g.get(N.id);_&&v.set(N.id,{value:_,sources:new Set(["vector"])})}}let w=[];if(r){let N=[...b.entityIds??[],...v.keys()],_=new Set,I=N;for(let O=0;O<i;O++){let P=[];for(let B of I)if(!_.has(B)){_.add(B);for(let j of r.related(B)){let D=j.to;if(!_.has(D)){P.push(D);let Z=g.get(D);if(Z){let F=v.get(D);F?F.sources.add("graph"):v.set(D,{value:Z,sources:new Set(["graph"])}),w.push(D)}}}}I=P}}for(let[N,_]of g)v.has(N)||v.set(N,{value:_,sources:new Set(["store"])});let x=b.context?.length??0,k=[];for(let[N,{value:_,sources:I}]of v){let O=o.contextOf?o.contextOf(_):void 0,P=o.score(_,y);if(u>0&&x>0){let j=iy(b.context,O);j>0&&(P=P*(1+u*j/x))}let B=O?{key:N,value:_,score:P,sources:[...I],context:O}:{key:N,value:_,score:P,sources:[...I]};k.push(B)}k.sort((N,_)=>_.score-N.score);let S=[],R=0;for(let N of k){let _=o.cost(N.value);if(R+_>a&&S.length>0)break;S.push(N),R+=_}return{packed:S,trace:{vectorCandidates:T,graphExpanded:w,ranked:k,packed:S}}},l=(g,y)=>{if(g===y)return!0;if(g.length!==y.length)return!1;for(let b=0;b<g.length;b++)if(g[b]!==y[b])return!1;return!0},p=M([],{name:"retrieval",describeKind:"state",meta:fe("retrieval_pipeline"),equals:l});t.add(p,{name:"retrieval"});let f=M(null,{name:"retrievalTrace",describeKind:"state",meta:fe("retrieval_trace")});return t.add(f,{name:"retrievalTrace"}),{retrieval:p,retrievalTrace:f,retrieve:g=>{let y=ar(e.store.entries.cache),{packed:b,trace:v}=c(y,d.cache,g);return X(()=>{p.emit(b),f.emit(v)}),b},retrieveReactive:g=>{let y=U(g),b=A([e.store.entries,d,y],([w,x,k])=>{if(k==null)return{packed:[],trace:null};let S=ar(w),{packed:R,trace:N}=c(S,x,k);return{packed:R,trace:N}},{name:"retrievalReactive::result",describeKind:"derived",meta:fe("retrieval_reactive_result"),initial:{packed:[],trace:null}}),T=pe([b],([w])=>{let x=w;X(()=>{p.emit(x.packed),x.trace&&f.emit(x.trace)})}).subscribe(()=>{});return t.addDisposer(T),A([b],([w])=>w.packed,{name:"retrievalReactive",describeKind:"derived",meta:fe("retrieval_reactive"),initial:[],equals:l})}}}function ay(t,e,n){let r=new Y(t,n.graph),o;if(n.extractFn)o=n.extractFn;else if(n.adapter&&n.extractPrompt)o=gu(n.extractPrompt,{adapter:n.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let s=(b,v)=>b==null?{upsert:[]}:o(b,v),i=e;if(n.admissionFilter){let b=U(e),v=n.admissionFilter;i=A([b],([T])=>{if(v(T))return T},{name:"admissionFilter",describeKind:"derived"})}let a;n.consolidateFn?a=n.consolidateFn:n.adapter&&n.consolidatePrompt&&(a=hu(n.consolidatePrompt,{adapter:n.adapter}));let u=n.consolidateTrigger;if(!u&&a&&n.reflection?.enabled!==!1){let b=n.reflection?.interval??3e5;u=st(b,{period:b})}let d={score:n.score,cost:n.cost,budget:n.budget??2e3,context:n.context,consolidate:a,consolidateTrigger:u},c=Ls(i,s,d);r.add(c.store.entries,{name:"store"}),r.add(c.compact,{name:"compact"}),r.add(c.size,{name:"size"});let l=null;n.vectorDimensions&&n.vectorDimensions>0&&n.embedFn&&(l=wu(r,c,{dimension:n.vectorDimensions,embedFn:n.embedFn}).vectors);let p=null;n.enableKnowledgeGraph&&(p=ku(r,c,t,{mountPath:"kg",entityFn:n.entityFn}).kg);let f=null;n.tiers&&(f=xu(r,c,{...n.tiers,score:n.score,context:n.context}).tiers);let m=null,h=null,g=null,y=null;if(l||p){let b=Ru(r,c,l,p,{score:n.score,cost:n.cost,budget:n.budget,topK:n.retrieval?.topK,graphDepth:n.retrieval?.graphDepth,contextOf:n.contextOf,contextWeight:n.contextWeight,context:n.context});m=b.retrieval,h=b.retrievalTrace,g=b.retrieve,y=b.retrieveReactive}return Object.assign(r,{distillBundle:c,compact:c.compact,size:c.size,vectors:l,kg:p,memoryTiers:f,retrieval:m,retrievalTrace:h,retrieve:g,retrieveReactive:y})}function uy(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,d]of Object.entries(r.nodes)){let c=d.meta??{},l=c.description,p=c.format;if(!l&&!p)continue;if(a!=null&&d.v!=null){let y=a.get(u);if(y!=null&&y.id===d.v.id&&d.v.version<=y.version)continue}let f=l??u,m=d.value,h=c.unit,g;p==="currency"&&typeof m=="number"?g=`$${m.toFixed(2)}`:p==="percentage"&&typeof m=="number"?g=`${(m*100).toFixed(1)}%`:m==null?g="(no value)":g=String(m),h&&p!=="currency"&&p!=="percentage"&&(g=`${g} ${h}`),i.push({path:u,description:f,formatted:g})}if(i.length===0)return"";if(o){let u=new Map,d=[];for(let l of i){let f=r.nodes[l.path].meta?.tags;if(f&&f.length>0){let m=f[0],h=u.get(m);h||(h=[],u.set(m,h)),h.push(l)}else d.push(l)}if(u.size===0)return i.map(l=>`- ${l.description}: ${l.formatted}`).join(s);let c=[];for(let[l,p]of[...u.entries()].sort((f,m)=>f[0].localeCompare(m[0])))c.push(`[${l}]${s}${p.map(f=>`- ${f.description}: ${f.formatted}`).join(s)}`);return d.length>0&&c.push(d.map(l=>`- ${l.description}: ${l.formatted}`).join(s)),c.join(s+s)}return i.map(u=>`- ${u.description}: ${u.formatted}`).join(s)}ae();ee();he();var fi={};ke(fi,{compileSpec:()=>ko,decompileGraph:()=>hy,extractFnFactory:()=>Up,extractSourceFactory:()=>Jp,generateCatalogPrompt:()=>Yp,isRichFnEntry:()=>To,isRichSourceEntry:()=>Nu,llmCompose:()=>by,llmRefine:()=>Zp,specDiff:()=>yy,validateSpec:()=>ur,validateSpecAgainstCatalog:()=>wo});ee();var pi={};ke(pi,{budgetGate:()=>Su,effectivenessTracker:()=>cy,feedback:()=>Qt,funnel:()=>dy,scorer:()=>vo});Me();ae();_e();ee();function li(t,e){return ze("reduction",t,e)}function dy(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 Y(t,r),s=e.length===1?e[0]:xt(...e);o.add(s,{name:"merged"});let i="merged";for(let a=0;a<n.length;a++){let u=n[a],d=new Y(u.name);u.build(d);try{d.resolve("input")}catch{throw new Error(`funnel stage "${u.name}" must define an "input" node`)}try{d.resolve("output")}catch{throw new Error(`funnel stage "${u.name}" must define an "output" node`)}o.mount(u.name,d);let c=o.resolve(i),l=`${u.name}::input`,p=o.resolve(l),f=`__bridge_${i}\u2192${u.name}_input`,m=pe([c],([h])=>{p.emit(h)},{name:f});o.add(m,{name:f}),o.addDisposer(re(m)),i=`${u.name}::output`}return o}function Qt(t,e,n,r){let o=r?.maxIterations??10,s=`__feedback_${e}`,i=M(0,{meta:li("feedback_counter",{maxIterations:o,feedbackFrom:e,feedbackTo:n})});t.add(i,{name:s});let a=t.resolve(e),u=t.resolve(n),d=`__feedback_effect_${e}`,c=z([],(l,p)=>{let f=a.subscribe(m=>{for(let h of m){let g=h[0];if(g===E){let y=h[1];if(y==null)return;X(()=>{Kr(i,o)&&u.emit(y)})}else if(g===L||g===C){let y=g===C&&h.length>1?[C,h[1]]:[g];i.down([y])}}});return()=>f()},{name:d,describeKind:"effect",meta:{...li("feedback_effect",{feedbackFrom:e,feedbackTo:n}),_internal:!0}});return t.add(c,{name:d}),t.addDisposer(re(c)),t}function Su(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"),d=new Array(e.length);function c(){return e.every((f,m)=>f.check(d[m]))}function l(f){for(;s.length>0&&c();){let m=s[0];s=s.slice(1),f.emit(m)}s.length===0&&a&&(a=!1,f.down([[V]]))}return z([],(f,m)=>{for(let g=0;g<e.length;g++)d[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)p(v,g,m)}))}return()=>{for(let g of h)g()}},{...n,describeKind:"derived",meta:li("budget_gate",n?.meta)});function p(f,m,h){let g=f[0];if(m===0){if(g===E)return c()&&s.length===0?h.emit(f[1]):(s.push(f[1]),i||(i=!0,h.up([[Be,u]]))),!0;if(g===ne)return h.down([[ne]]),!0;if(g===V)return s.length===0?h.down([[V]]):a=!0,!0;if(g===L||g===C){for(let y of s)h.emit(y);return s=[],a=!1,i&&(i=!1,h.up([[qe,u]])),h.down([f]),!0}return!1}return g===E&&(d[m-1]=f[1]),g===E||g===V?(c()&&s.length>0?(l(h),s.length===0&&i&&(i=!1,h.up([[qe,u]]))):!c()&&!i&&s.length>0&&(i=!0,h.up([[Be,u]])),!0):g===ne?!0:g===C?(h.down([f]),!0):g===L}}function vo(t,e,n){if(t.length===0)throw new RangeError("scorer requires at least one source");if(t.length!==e.length)throw new RangeError("scorer requires the same number of sources and weights");let r=[...t,...e],o=t.length,s=n?.scoreFns;return A(r,i=>{let a=i.slice(0,o),u=i.slice(o),d=[],c=0;for(let l=0;l<o;l++){let p=a[l]??0,f=u[l]??0,h=(s?.[l]?s[l](p):p)*f;d.push(h),c+=h}return{value:a,score:c,breakdown:d}},{...n?{equals:n.equals,resubscribable:n.resubscribable,resetOnTeardown:n.resetOnTeardown}:{},describeKind:"derived",meta:li("scorer",n?.meta)})}function cy(t){let e=Ze({name:t?.name??"effectiveness-entries"}),n=A([e.entries],([i])=>new Map(i),{name:`${t?.name??"effectiveness"}-snapshot`,equals:(i,a)=>{let u=i,d=a;if(u.size!==d.size)return!1;for(let[c,l]of u){let p=d.get(c);if(!p||l.attempts!==p.attempts||l.successes!==p.successes)return!1}return!0}});function r(i,a){let u=e.get(i),d=(u?.attempts??0)+1,c=(u?.successes??0)+(a?1:0);e.set(i,{key:i,attempts:d,successes:c,successRate:c/d})}function o(i){return e.get(i)}let s=re(n);return{node:n,record:r,lookup:o,dispose:()=>s()}}function To(t){return typeof t=="object"&&t!==null&&"factory"in t}function Nu(t){return typeof t=="object"&&t!==null&&"factory"in t}function Up(t){return To(t)?t.factory:t}function Jp(t){return Nu(t)?t.factory:t}function Yp(t){let e=[];if(t.fns){let n=new Map;for(let[r,o]of Object.entries(t.fns)){let s=To(o)?o.tags?.[0]??"Other":"Other";n.has(s)||n.set(s,[]),n.get(s).push(ly(r,o))}for(let[r,o]of n)e.push(`${r}:
39
+ `,r=t.map(i=>typeof i=="string"?M(i):U(i)),o=C(r,i=>i.filter(a=>a!=null&&a!=="").join(n),{name:e?.name??"systemPrompt",describeKind:"derived",meta:fe("system_prompt"),initial:""}),s=re(o);return Object.assign(o,{dispose:s})}ee();var Wh=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens&&t.estimated===e.estimated;function zh(t,e){let n=e?.charsPerToken??4,r={chunkCount:0,charCount:0,estimatedTokens:0,estimated:!0};return C([t.latest],([o],s)=>{if(o==null)return r;let 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=yt(i.usage)+Gt(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:fe("cost_meter_extractor"),equals:Wh})}ee();var Uh=(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 Jh(t,e){let n=e.maxPatternLength??128;for(let o of e.patterns)if(o.pattern.source.length>n)throw new Error(`keywordFlagExtractor: pattern "${o.label}" literal exceeds maxPatternLength (${o.pattern.source.length} > ${n}); raise the option or shorten the pattern.`);let r=e.patterns.map(o=>({label:o.label,pattern:o.pattern,compiled:new RegExp(o.pattern.source,`${o.pattern.flags.replace("g","")}g`)}));return C([t],([o],s)=>{if(o==null)return[];let i=o;"flags"in s.store||(s.store.flags=[],s.store.scannedTo=0);let a=s.store.flags,u=s.store.scannedTo,d=Math.max(0,u-n),c=i.slice(d),l=!1;for(let{pattern:p,label:f,compiled:m}of r){m.lastIndex=0;for(let h of c.matchAll(m)){let g=d+(h.index??0);g+h[0].length<=u||(a.push({label:f,pattern:p,match:h[0],position:g}),l=!0)}}return s.store.scannedTo=i.length,l?[...a]:a.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:fe("keyword_flag_extractor"),equals:Uh})}ee();function Yh(t,e,n){return C([t],([r])=>r==null?null:e(r),{name:n?.name??"extractor",describeKind:"derived",initial:null,meta:fe("stream_extractor"),...n?.equals?{equals:n.equals}:{}})}ee();var Qh=(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 Xh(t,e){return C([t],([n],r)=>{if(n==null)return[];let o=n;"calls"in r.store||(r.store.calls=[],r.store.scanFrom=0);let s=r.store.calls,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 d=0,c=-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==="{")d++;else if(m==="}"&&(d--,d===0)){c=f;break}}if(c===-1){r.store.scanFrom=u;break}let p=o.slice(u,c+1);try{let f=JSON.parse(p);typeof f.name=="string"&&f.arguments!=null&&typeof f.arguments=="object"&&(s.push({name:f.name,arguments:f.arguments,raw:p,startIndex:u}),a=!0)}catch{}i=c+1,r.store.scanFrom=i}return a?[...s]:s.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:fe("tool_call_extractor"),equals:Qh})}ee();function Zh(t,e,n,r){let o=n*(r?.hardMultiplier??1.5),s=typeof e!="function",i=[t];return s&&i.push(e),C(i,a=>{let u=a[0]??"";if(u.length===0)return"allow";let d=s?a[1]??0:e(u);return d>=o?"block":d>=n?"review":"allow"},{name:r?.name??"content-gate",initial:"allow"})}ee();function ey(t,e,n,r){let o=n??(()=>"[REDACTED]");function s(i){let a=i;for(let u of e){let d=u.global?u:new RegExp(u.source,`${u.flags}g`);a=a.replace(d,c=>o(c,u))}return a}return C([t],([i])=>s(i??""),{name:r?.name??"redactor",initial:""})}Me();ae();_e();ee();he();ee();var ii=class extends Y{_log;messages;latest;messageCount;constructor(e,n={}){super(e,n.graph),this._log=Ve([],{name:"messages",maxSize:n.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=C([this.messages],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:fe("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(re(this.latest)),this.messageCount=C([this.messages],([r])=>r.length,{name:"messageCount",describeKind:"derived",meta:fe("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(re(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 pu(t,e){return new ii(t,e)}ee();Ot();function fu(t){let{toolCalls:e,tools:n}=t,r=t.retryCount??1,o=t.onError??"rescue",s=(i,a)=>{if(i===a)return!0;if(i.length!==a.length)return!1;for(let u=0;u<i.length;u++){let d=i[u],c=a[u];if(d?.id!==c?.id||d?.content!==c?.content)return!1}return!0};return Te(e,i=>{if(i==null||i.length===0)throw new Error("toolExecution: received an empty tool-call batch as DATA \u2014 callers must upstream-filter empty batches (emit RESOLVED) so switchMap is only dispatched for non-empty batches.");let a=i.map(u=>ty(u,n,r,o));return C(a,u=>u,{name:"toolExecution::batch",equals:s})})}function ty(t,e,n,r){let o=Tt(()=>e.executeReactive(t.name,t.arguments),{count:n}),s=C([o],([i])=>({id:t.id,content:typeof i=="string"?i:JSON.stringify(i)}));return r==="propagate"?s:Yr(s,i=>({id:t.id,content:JSON.stringify({error:String(i)})}))}ae();ee();he();var ai=class extends Y{definitions;schemas;_bundle;constructor(e,n={}){super(e,n.graph),this._bundle=Ze({name:"definitions"}),this.definitions=this._bundle.entries,this.add(this.definitions,{name:"definitions"}),this.schemas=C([this.definitions],([r])=>[...(r??new Map).values()],{name:"schemas",describeKind:"derived",meta:fe("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(re(this.schemas))}register(e){this._bundle.set(e.name,e)}unregister(e){this._bundle.delete(e)}executeReactive(e,n){let r=this._bundle.get(e);if(!r)throw new Error(`toolRegistry: unknown tool "${e}"`);return K(o=>{let s=new AbortController,i;try{let u=r.handler(n,{signal:s.signal});i=ny(u,s.signal)}catch(u){return o.down([[A,u]]),()=>{s.abort()}}let a=i.subscribe(u=>{o.down(u)});return()=>{s.abort(),a()}},{name:`executeReactive::${e}`,meta:fe("tool_execute_reactive")})}getDefinition(e){return this._bundle.entries.cache?.get(e)}};function mu(t,e){return new ai(t,e)}function ny(t,e){return lu(t)?t:t!=null&&typeof t.then=="function"?zn(t,{signal:e}):t!=null&&typeof t=="object"&&Symbol.asyncIterator in t?Ir(t,{signal:e}):zn(Promise.resolve(t),{signal:e})}var ui=class extends Y{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;_terminalResult;_disposeRunWiring;_running=!1;_currentAbortController=null;constructor(e,n){if(super(e,n.graph),this.chat=pu(`${e}-chat`,{maxMessages:n.maxMessages}),this.mount("chat",this.chat),this.tools=mu(`${e}-tools`),this.mount("tools",this.tools),n.tools)for(let G of n.tools)this.tools.register(G);this.status=M("idle",{name:"status",describeKind:"state",meta:fe("agent_status")}),this.add(this.status,{name:"status"}),this.turn=M(0,{name:"turn",describeKind:"state",meta:fe("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.aborted=M(!1,{name:"aborted",describeKind:"state",meta:fe("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let r=0,o=this.turn.subscribe(G=>{for(let q of G)q[0]===E&&(r=q[1])}),s=!1,i=this.aborted.subscribe(G=>{for(let q of G)q[0]===E&&(s=q[1])}),a=this.chat.messages.cache??[],u=this.chat.messages.subscribe(G=>{for(let q of G)q[0]===E&&(a=q[1])}),d=this.tools.schemas.cache??[],c=this.tools.schemas.subscribe(G=>{for(let q of G)q[0]===E&&(d=q[1])}),l=n.adapter,p=n.systemPrompt,f=n.model,m=n.temperature,h=n.maxTokens,g=n.maxTurns??10,y=n.stopWhen,b=this.chat,v=this.tools,T=this.status,w=this.turn,k=this.aborted,x=z([T],(G,q,$)=>{if(bo(G,$.prevData,0,"idle")!=="thinking"||s||r>=g){q.down([[V]]);return}if(a.length===0){q.down([[V]]);return}q.emit({messages:a,tools:d})},{name:"promptInput",describeKind:"derived",meta:fe("agent_prompt_input",{closureReads:["aborted","turn","chat.messages","tools.schemas"]})}),S=Te(x,G=>{let q=new AbortController;return this._currentAbortController=q,s&&q.abort(new Error("agentLoop: aborted")),U(l.invoke(G.messages,{tools:G.tools.length>0?G.tools:void 0,systemPrompt:p,model:f,temperature:m,maxTokens:h,signal:q.signal}),{signal:q.signal})},{equals:()=>!1}),R=M(null,{name:"lastResponse",describeKind:"state",meta:fe("agent_last_response")});this.lastResponse=R;let N=z([R,T],(G,q,$)=>{let te=bo(G,$.prevData,0,null);if(bo(G,$.prevData,1,"idle")!=="acting"){q.down([[V]]);return}let Oe=te?.toolCalls;if(Oe==null||Oe.length===0){q.down([[V]]);return}q.emit(Oe)},{name:"toolCallsRaw",describeKind:"derived",meta:fe("agent_tool_calls_raw")}),_=n.interceptToolCalls?n.interceptToolCalls(N):N;this.toolCalls=_;let I=fu({toolCalls:_,tools:v,retryCount:1});this.toolResults=I;let O=pe([S],([G])=>{if(s)return;let q=G,$=r+1,te=q.toolCalls!=null&&q.toolCalls.length>0,Re=q.finishReason==="end_turn"&&(!q.toolCalls||q.toolCalls.length===0),Oe=y?.(q)===!0,Ae=$>=g,ye=Oe||Re||!te||Ae?"done":"acting";X(()=>{R.emit(q),T.emit(ye),w.emit($),b.append("assistant",q.content,{toolCalls:q.toolCalls})})}),P=pe([I],([G])=>{if(s)return;let q=G;if(q.length===0)return;let $=r>=g?"done":"thinking";X(()=>{T.emit($);for(let te of q)b.appendToolResult(te.id,te.content)})}),B=T.cache??"idle",j=T.subscribe(G=>{for(let q of G)q[0]===E&&(B=q[1])}),D=pe([k],([G])=>{G===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),B!=="done"&&T.emit("done"))}),Z=re(O),F=re(P),Q=re(D);this._terminalResult=z([T,R],(G,q,$)=>{let te=bo(G,$.prevData,0,"idle"),Re=bo(G,$.prevData,1,null);if(te==="done"){if(Re!=null){q.emit(Re);return}let Oe=new Error("agentLoop: aborted");Oe.name="AbortError",q.down([[A,Oe]]);return}if(te==="error"){q.down([[A,new Error("agentLoop: errored")]]);return}q.down([[V]])},{name:"terminalResult",describeKind:"derived",meta:fe("agent_terminal_result")}),this.add(x,{name:"promptInput"}),this.add(S,{name:"llmResponse"}),this.add(this.lastResponse,{name:"lastResponse"}),this.toolCalls===N?this.add(this.toolCalls,{name:"toolCalls"}):(this.add(N,{name:"toolCallsRaw"}),this.add(this.toolCalls,{name:"toolCalls"})),this.add(I,{name:"toolResults"}),this.add(this._terminalResult,{name:"terminalResult"}),this.addDisposer(o),this.addDisposer(i),this.addDisposer(j),this.addDisposer(u),this.addDisposer(c),this.addDisposer(Z),this.addDisposer(F),this.addDisposer(Q),this._disposeRunWiring=()=>{}}async run(e,n){if(this._running)throw new RangeError(`agentLoop "${this.name}": run() called while a previous run() is still pending \u2014 await the previous run before starting another, or call abort() first`);this._running=!0;let r;try{X(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle"),this.lastResponse.emit(null)}),e!=null&&this.chat.append("user",e);let o=es(this._terminalResult,{skipCurrent:!0});if(n!=null)if(n.aborted)this.aborted.emit(!0);else{let s=()=>this.aborted.emit(!0);n.addEventListener("abort",s,{once:!0}),r=()=>n.removeEventListener("abort",s)}return n?.aborted!==!0&&this.status.emit("thinking"),await o}finally{r?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function bo(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 ry(t,e){return new ui(t,e)}ee();he();function oy(t,e,n){let r=U(t),o=n?.condition!=null?U(n.condition):null,s=M(null,{name:n?.name?`${n.name}::null`:"handoff::null"});if(o==null)return Te(r,a=>{if(a==null)return s;let u=M(a);return e(u)});let i=C([r,o],([a,u])=>({v:a,open:u===!0}),{name:n?.name?`${n.name}::router`:"handoff::router",describeKind:"derived"});return Te(i,({v:a,open:u})=>{if(a==null)return s;if(!u)return M(a);let d=M(a);return e(d)})}ee();he();function sy(t,e,n){let r=U(t),o=e.map(i=>U(i)),s=[r,...o];return C(s,i=>{let a=i[0]??[],u=i.slice(1);return a.filter(d=>{for(let c of u)if(c!=null&&!c(d))return!1;return!0})},{name:n?.name??"tool-selector",describeKind:"derived",meta:fe("tool_selector"),equals:(i,a)=>{let u=i,d=a;if(u.length!==d.length)return!1;for(let c=0;c<u.length;c++)if(u[c]!==d[c])return!1;return!0}})}function Wp(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 iy(t){let e={persistence:t.persistenceThreshold??.3,personalValue:t.personalValueThreshold??.3},n=Wp({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}ee();he();ee();function zp(t,e,n,r){let o=n.name??r;return s=>{let i=M(s);return wn(n.adapter,[i],a=>e(a),{name:o,format:"json",systemPrompt:t,model:n.model,temperature:n.temperature??0,maxTokens:n.maxTokens})}}function gu(t,e){let n=e.maxExistingKeys??100,r=zp(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 hu(t,e){let n=zp(t,r=>JSON.stringify({memories:r}),e,"llmConsolidator");return r=>{let o=[...r.entries()].map(([s,i])=>({key:s,value:i}));return n(o)}}Me();xe();ee();he();var ci={};ke(ci,{collection:()=>uy,decay:()=>xn,knowledgeGraph:()=>vu,lightCollection:()=>yu,vectorIndex:()=>bu});xe();ee();function xn(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 Up(t){if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1")}function St(t){return new Map(t)}function nt(t){return t.cache??new Map}function di(t){return t.cache??[]}function ay(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 yu(t={}){let e=t.maxSize,n=t.policy??"fifo";Up(e);let r=M(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 d=n==="lru"?u.lastAccessNs:u.createdAtNs,c=n==="lru"?a.lastAccessNs:a.createdAtNs;d<c&&(a=u)}if(!a)break;i.delete(a.id)}}function s(i){r.emit(i)}return{entries:r,upsert(i,a){let u=H(),d=nt(r),c=d.get(i),l=St(d);l.set(i,{id:i,value:a,createdAtNs:c?.createdAtNs??u,lastAccessNs:u}),o(l),s(l)},remove(i){let a=St(nt(r));a.delete(i)&&s(a)},clear(){nt(r).size!==0&&s(new Map)},get(i){let a=nt(r),u=a.get(i);if(u){if(n==="lru"){let d=H(),c=St(a);c.set(i,{...u,lastAccessNs:d}),s(c)}return u.value}},has(i){return nt(r).has(i)}}}function uy(t,e={}){let n=e.maxSize,r=e.policy??"lru",o=e.decayRate??0,s=e.minScore??0,i=e.score??(()=>1);Up(n);let a=new Y(t),u=M(new Map,{name:"items",describeKind:"state"}),d=C([u],([h])=>{let g=h??new Map,y=H(),b=[...g.values()].map(v=>{let T=(y-v.lastAccessNs)/1e9;return{...v,score:xn(v.baseScore,T,o,s)}});return b.sort((v,T)=>T.score-v.score||T.lastAccessNs-v.lastAccessNs),b},{name:"ranked",describeKind:"derived"}),c=C([u],([h])=>(h??new Map).size,{name:"size",describeKind:"derived",initial:0});d.subscribe(()=>{}),c.subscribe(()=>{}),a.add(u,{name:"items"}),a.add(d,{name:"ranked"}),a.add(c,{name:"size"});function l(h,g){let y=(g-h.lastAccessNs)/1e9;return xn(h.baseScore,y,o,s)}function p(h){if(n!==void 0)for(;h.size>n;){let g=H(),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 f(h){u.emit(h)}return Object.assign(a,{upsert(h,g,y){let b=H(),v=nt(u),T=v.get(h),w=y?.score??i(g),k=St(v);k.set(h,{id:h,value:g,baseScore:w,createdAtNs:T?.createdAtNs??b,lastAccessNs:b}),p(k),f(k)},remove(h){let g=St(nt(u));g.delete(h)&&f(g)},clear(){nt(u).size!==0&&f(new Map)},getItem(h){let g=nt(u),y=g.get(h);if(y){if(r==="lru"){let b=St(g);b.set(h,{...y,lastAccessNs:H()}),f(b)}return y}}})}function bu(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=M(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,d){s(u);let c=St(nt(o));c.set(a,{id:a,vector:[...u],meta:d}),e==="hnsw"&&r.upsert(a,u,d),i(c)},remove(a){let u=St(nt(o));u.delete(a)&&(e==="hnsw"&&r.remove(a),i(u))},clear(){nt(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):[...nt(o).values()].map(c=>({id:c.id,score:ay(a,c.vector),meta:c.meta})).sort((c,l)=>l.score-c.score).slice(0,u)}}}function vu(t){let e=new Y(t),n=M(new Map,{name:"entities",describeKind:"state"}),r=M([],{name:"edges",describeKind:"state"}),o=C([r],([u])=>{let d=u??[],c=new Map;for(let l of d){let p=c.get(l.from)??[];c.set(l.from,Object.freeze([...p,l]))}return c},{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,d){let c=St(nt(n));c.set(u,d),s(c)},removeEntity(u){let d=St(nt(n)),c=d.delete(u),l=di(r),p=l.filter(f=>f.from!==u&&f.to!==u);!c&&p.length===l.length||(s(d),i(p))},link(u,d,c,l=1){let p=`${u}\0${d}\0${c}`,f=di(r),m=new Set(f.map(g=>`${g.from}\0${g.to}\0${g.relation}`)),h=[...f];if(m.has(p))for(let g=0;g<h.length;g+=1){let y=h[g];if(y.from===u&&y.to===d&&y.relation===c){h[g]={...y,weight:l};break}}else h.push({from:u,to:d,relation:c,weight:l});i(h)},unlink(u,d,c){let l=di(r),p=l.filter(f=>c===void 0?!(f.from===u&&f.to===d):!(f.from===u&&f.to===d&&f.relation===c));p.length!==l.length&&i(p)},related(u,d){return di(r).filter(c=>(c.from===u||c.to===u)&&(d===void 0||c.relation===d))}})}var Tu=Math.LN2/604800;function ar(t){return t instanceof Map?t:new Map}function wu(t,e,n){let r=bu({dimension:n.dimension});t.add(r.entries,{name:"vectorIndex"});let s=pe([e.store.entries],([i])=>{let a=ar(i);for(let[u,d]of a){let c=n.embedFn(d);c&&r.upsert(u,c,d)}}).subscribe(()=>{});return t.addDisposer(s),{vectors:r,dispose:()=>s()}}function ku(t,e,n,r){let o=r.mountPath??n,s=vu(`${n}-kg`);if(t.mount(o,s),!r.entityFn)return{kg:s,dispose:()=>{}};let i=r.entityFn,u=pe([e.store.entries],([d])=>{let c=ar(d);for(let[l,p]of c){let f=i(l,p);if(f){for(let m of f.entities??[])s.upsertEntity(m.id,m.value);for(let m of f.relations??[])s.link(m.from,m.to,m.relation,m.weight)}}}).subscribe(()=>{});return t.addDisposer(u),{kg:s,dispose:()=>u()}}function xu(t,e,n){let r=n.decayRate??Tu,o=n.maxActive??1e3,s=n.archiveThreshold??.1,i=n.permanentFilter??(()=>!1),a=yu({name:"permanent"});t.add(a.entries,{name:"permanent"});let u=new Set,d=b=>u.has(b)?"permanent":ar(e.store.entries.cache).has(b)?"active":"archived",c=(b,v)=>{u.add(b),a.upsert(b,v)},l=new Map,p=e.store.entries,f=n.context?U(n.context):M(null),h=pe([p,f],([b,v])=>{let T=ar(b),w=H(),k=[],x=[];for(let[R,N]of T){if(l.has(R)||l.set(R,w),i(R,N)){x.push({key:R,value:N});continue}let _=n.score(N,v),I=l.get(R)??w,O=Number(w-I)/1e9;xn(_,O,r)<s&&k.push(R)}for(let R of l.keys())T.has(R)||l.delete(R);for(let{key:R,value:N}of x)u.has(R)||c(R,N);let S=T.size-u.size;if(S>o){let R=[...T.entries()].filter(([_])=>!u.has(_)).map(([_,I])=>({key:_,score:n.score(I,v)})).sort((_,I)=>_.score-I.score),N=S-o;for(let _=0;_<N&&_<R.length;_++){let I=R[_].key;k.includes(I)||k.push(I)}}k.length>0&&X(()=>{for(let R of k)e.store.delete(R)})}).subscribe(()=>{}),g=null;n.archiveTier&&(g=t.attachSnapshotStorage([n.archiveTier],n.archiveStorageOptions??{}));let y=()=>{h(),g?.dispose()};return t.addDisposer(y),{tiers:{permanent:a,activeEntries:p,archiveHandle:g,tierOf:d,markPermanent:c},dispose:y}}function dy(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 Ru(t,e,n,r,o){let s=o.topK??20,i=o.graphDepth??1,a=o.budget??2e3,u=o.contextWeight??0,d=o.context?U(o.context):M(null),c=(g,y,b)=>{let v=new Map,T=[];if(n&&b.vector){T=n.search(b.vector,s);for(let N of T){let _=g.get(N.id);_&&v.set(N.id,{value:_,sources:new Set(["vector"])})}}let w=[];if(r){let N=[...b.entityIds??[],...v.keys()],_=new Set,I=N;for(let O=0;O<i;O++){let P=[];for(let B of I)if(!_.has(B)){_.add(B);for(let j of r.related(B)){let D=j.to;if(!_.has(D)){P.push(D);let Z=g.get(D);if(Z){let F=v.get(D);F?F.sources.add("graph"):v.set(D,{value:Z,sources:new Set(["graph"])}),w.push(D)}}}}I=P}}for(let[N,_]of g)v.has(N)||v.set(N,{value:_,sources:new Set(["store"])});let k=b.context?.length??0,x=[];for(let[N,{value:_,sources:I}]of v){let O=o.contextOf?o.contextOf(_):void 0,P=o.score(_,y);if(u>0&&k>0){let j=dy(b.context,O);j>0&&(P=P*(1+u*j/k))}let B=O?{key:N,value:_,score:P,sources:[...I],context:O}:{key:N,value:_,score:P,sources:[...I]};x.push(B)}x.sort((N,_)=>_.score-N.score);let S=[],R=0;for(let N of x){let _=o.cost(N.value);if(R+_>a&&S.length>0)break;S.push(N),R+=_}return{packed:S,trace:{vectorCandidates:T,graphExpanded:w,ranked:x,packed:S}}},l=(g,y)=>{if(g===y)return!0;if(g.length!==y.length)return!1;for(let b=0;b<g.length;b++)if(g[b]!==y[b])return!1;return!0},p=M([],{name:"retrieval",describeKind:"state",meta:fe("retrieval_pipeline"),equals:l});t.add(p,{name:"retrieval"});let f=M(null,{name:"retrievalTrace",describeKind:"state",meta:fe("retrieval_trace")});return t.add(f,{name:"retrievalTrace"}),{retrieval:p,retrievalTrace:f,retrieve:g=>{let y=ar(e.store.entries.cache),{packed:b,trace:v}=c(y,d.cache,g);return X(()=>{p.emit(b),f.emit(v)}),b},retrieveReactive:g=>{let y=U(g),b=C([e.store.entries,d,y],([w,k,x])=>{if(x==null)return{packed:[],trace:null};let S=ar(w),{packed:R,trace:N}=c(S,k,x);return{packed:R,trace:N}},{name:"retrievalReactive::result",describeKind:"derived",meta:fe("retrieval_reactive_result"),initial:{packed:[],trace:null}}),T=pe([b],([w])=>{let k=w;X(()=>{p.emit(k.packed),k.trace&&f.emit(k.trace)})}).subscribe(()=>{});return t.addDisposer(T),C([b],([w])=>w.packed,{name:"retrievalReactive",describeKind:"derived",meta:fe("retrieval_reactive"),initial:[],equals:l})}}}function cy(t,e,n){let r=new Y(t,n.graph),o;if(n.extractFn)o=n.extractFn;else if(n.adapter&&n.extractPrompt)o=gu(n.extractPrompt,{adapter:n.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let s=(b,v)=>b==null?{upsert:[]}:o(b,v),i=e;if(n.admissionFilter){let b=U(e),v=n.admissionFilter;i=C([b],([T])=>{if(v(T))return T},{name:"admissionFilter",describeKind:"derived"})}let a;n.consolidateFn?a=n.consolidateFn:n.adapter&&n.consolidatePrompt&&(a=hu(n.consolidatePrompt,{adapter:n.adapter}));let u=n.consolidateTrigger;if(!u&&a&&n.reflection?.enabled!==!1){let b=n.reflection?.interval??3e5;u=st(b,{period:b})}let d={score:n.score,cost:n.cost,budget:n.budget??2e3,context:n.context,consolidate:a,consolidateTrigger:u},c=Ls(i,s,d);r.add(c.store.entries,{name:"store"}),r.add(c.compact,{name:"compact"}),r.add(c.size,{name:"size"});let l=null;n.vectorDimensions&&n.vectorDimensions>0&&n.embedFn&&(l=wu(r,c,{dimension:n.vectorDimensions,embedFn:n.embedFn}).vectors);let p=null;n.enableKnowledgeGraph&&(p=ku(r,c,t,{mountPath:"kg",entityFn:n.entityFn}).kg);let f=null;n.tiers&&(f=xu(r,c,{...n.tiers,score:n.score,context:n.context}).tiers);let m=null,h=null,g=null,y=null;if(l||p){let b=Ru(r,c,l,p,{score:n.score,cost:n.cost,budget:n.budget,topK:n.retrieval?.topK,graphDepth:n.retrieval?.graphDepth,contextOf:n.contextOf,contextWeight:n.contextWeight,context:n.context});m=b.retrieval,h=b.retrievalTrace,g=b.retrieve,y=b.retrieveReactive}return Object.assign(r,{distillBundle:c,compact:c.compact,size:c.size,vectors:l,kg:p,memoryTiers:f,retrieval:m,retrievalTrace:h,retrieve:g,retrieveReactive:y})}function ly(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,d]of Object.entries(r.nodes)){let c=d.meta??{},l=c.description,p=c.format;if(!l&&!p)continue;if(a!=null&&d.v!=null){let y=a.get(u);if(y!=null&&y.id===d.v.id&&d.v.version<=y.version)continue}let f=l??u,m=d.value,h=c.unit,g;p==="currency"&&typeof m=="number"?g=`$${m.toFixed(2)}`:p==="percentage"&&typeof m=="number"?g=`${(m*100).toFixed(1)}%`:m==null?g="(no value)":g=String(m),h&&p!=="currency"&&p!=="percentage"&&(g=`${g} ${h}`),i.push({path:u,description:f,formatted:g})}if(i.length===0)return"";if(o){let u=new Map,d=[];for(let l of i){let f=r.nodes[l.path].meta?.tags;if(f&&f.length>0){let m=f[0],h=u.get(m);h||(h=[],u.set(m,h)),h.push(l)}else d.push(l)}if(u.size===0)return i.map(l=>`- ${l.description}: ${l.formatted}`).join(s);let c=[];for(let[l,p]of[...u.entries()].sort((f,m)=>f[0].localeCompare(m[0])))c.push(`[${l}]${s}${p.map(f=>`- ${f.description}: ${f.formatted}`).join(s)}`);return d.length>0&&c.push(d.map(l=>`- ${l.description}: ${l.formatted}`).join(s)),c.join(s+s)}return i.map(u=>`- ${u.description}: ${u.formatted}`).join(s)}ae();ee();he();var fi={};ke(fi,{compileSpec:()=>ko,decompileGraph:()=>vy,extractFnFactory:()=>Yp,extractSourceFactory:()=>Qp,generateCatalogPrompt:()=>Xp,isRichFnEntry:()=>To,isRichSourceEntry:()=>Nu,llmCompose:()=>wy,llmRefine:()=>tf,specDiff:()=>Ty,validateSpec:()=>ur,validateSpecAgainstCatalog:()=>wo});ee();var pi={};ke(pi,{budgetGate:()=>Su,effectivenessTracker:()=>fy,feedback:()=>Qt,funnel:()=>py,scorer:()=>vo});Me();ae();_e();ee();function li(t,e){return ze("reduction",t,e)}function py(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 Y(t,r),s=e.length===1?e[0]:xt(...e);o.add(s,{name:"merged"});let i="merged";for(let a=0;a<n.length;a++){let u=n[a],d=new Y(u.name);u.build(d);try{d.resolve("input")}catch{throw new Error(`funnel stage "${u.name}" must define an "input" node`)}try{d.resolve("output")}catch{throw new Error(`funnel stage "${u.name}" must define an "output" node`)}o.mount(u.name,d);let c=o.resolve(i),l=`${u.name}::input`,p=o.resolve(l),f=`__bridge_${i}\u2192${u.name}_input`,m=pe([c],([h])=>{p.emit(h)},{name:f});o.add(m,{name:f}),o.addDisposer(re(m)),i=`${u.name}::output`}return o}function Qt(t,e,n,r){let o=r?.maxIterations??10,s=`__feedback_${e}`,i=M(0,{meta:li("feedback_counter",{maxIterations:o,feedbackFrom:e,feedbackTo:n})});t.add(i,{name:s});let a=t.resolve(e),u=t.resolve(n),d=`__feedback_effect_${e}`,c=z([],(l,p)=>{let f=a.subscribe(m=>{for(let h of m){let g=h[0];if(g===E){let y=h[1];if(y==null)return;X(()=>{Kr(i,o)&&u.emit(y)})}else if(g===L||g===A){let y=g===A&&h.length>1?[A,h[1]]:[g];i.down([y])}}});return()=>f()},{name:d,describeKind:"effect",meta:{...li("feedback_effect",{feedbackFrom:e,feedbackTo:n}),_internal:!0}});return t.add(c,{name:d}),t.addDisposer(re(c)),t}function Su(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"),d=new Array(e.length);function c(){return e.every((f,m)=>f.check(d[m]))}function l(f){for(;s.length>0&&c();){let m=s[0];s=s.slice(1),f.emit(m)}s.length===0&&a&&(a=!1,f.down([[V]]))}return z([],(f,m)=>{for(let g=0;g<e.length;g++)d[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)p(v,g,m)}))}return()=>{for(let g of h)g()}},{...n,describeKind:"derived",meta:li("budget_gate",n?.meta)});function p(f,m,h){let g=f[0];if(m===0){if(g===E)return c()&&s.length===0?h.emit(f[1]):(s.push(f[1]),i||(i=!0,h.up([[Be,u]]))),!0;if(g===ne)return h.down([[ne]]),!0;if(g===V)return s.length===0?h.down([[V]]):a=!0,!0;if(g===L||g===A){for(let y of s)h.emit(y);return s=[],a=!1,i&&(i=!1,h.up([[qe,u]])),h.down([f]),!0}return!1}return g===E&&(d[m-1]=f[1]),g===E||g===V?(c()&&s.length>0?(l(h),s.length===0&&i&&(i=!1,h.up([[qe,u]]))):!c()&&!i&&s.length>0&&(i=!0,h.up([[Be,u]])),!0):g===ne?!0:g===A?(h.down([f]),!0):g===L}}function vo(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 C(r,i=>{let a=i.slice(0,o),u=i.slice(o),d=[],c=0;for(let l=0;l<o;l++){let p=a[l]??0,f=u[l]??0,h=(s?.[l]?s[l](p):p)*f;d.push(h),c+=h}return{value:a,score:c,breakdown:d}},{...n?{equals:n.equals,resubscribable:n.resubscribable,resetOnTeardown:n.resetOnTeardown}:{},describeKind:"derived",meta:li("scorer",n?.meta)})}function fy(t){let e=Ze({name:t?.name??"effectiveness-entries"}),n=C([e.entries],([i])=>new Map(i),{name:`${t?.name??"effectiveness"}-snapshot`,equals:(i,a)=>{let u=i,d=a;if(u.size!==d.size)return!1;for(let[c,l]of u){let p=d.get(c);if(!p||l.attempts!==p.attempts||l.successes!==p.successes)return!1}return!0}});function r(i,a){let u=e.get(i),d=(u?.attempts??0)+1,c=(u?.successes??0)+(a?1:0);e.set(i,{key:i,attempts:d,successes:c,successRate:c/d})}function o(i){return e.get(i)}let s=re(n);return{node:n,record:r,lookup:o,dispose:()=>s()}}function To(t){return typeof t=="object"&&t!==null&&"factory"in t}function Nu(t){return typeof t=="object"&&t!==null&&"factory"in t}function Yp(t){return To(t)?t.factory:t}function Qp(t){return Nu(t)?t.factory:t}function Xp(t){let e=[];if(t.fns){let n=new Map;for(let[r,o]of Object.entries(t.fns)){let s=To(o)?o.tags?.[0]??"Other":"Other";n.has(s)||n.set(s,[]),n.get(s).push(my(r,o))}for(let[r,o]of n)e.push(`${r}:
41
41
  ${o.join(`
42
- `)}`)}if(t.sources){let n=[];for(let[r,o]of Object.entries(t.sources))n.push(py(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(gy(r,o));n.length>0&&e.push(`Sources:
43
43
  ${n.join(`
44
44
  `)}`)}return e.join(`
45
45
 
46
- `)}function ly(t,e){if(!To(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 py(t,e){if(!Nu(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 wo(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=Eu(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=Eu(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(To(u)&&u.configSchema){for(let[d,c]of Object.entries(u.configSchema))if(c.required!==!1&&!(d in a.config)&&n.push(`Node "${s}": config missing required field "${d}"`),d in a.config&&c.enum){let l=a.config[d];c.enum.includes(l)||n.push(`Node "${s}": config.${d} = ${JSON.stringify(l)}, expected one of: ${c.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 d=Eu(u.fn,r);n.push(`Template "${s}" node "${a}": fn "${u.fn}" not found in catalog`+(d?`. Did you mean "${d}"?`:""))}}return{valid:n.length===0,errors:n,warnings:[]}}function Eu(t,e){let n=null,r=1/0,o=t.toLowerCase();for(let s of e){let i=fy(o,s.toLowerCase());i<r&&i<=Math.max(3,Math.floor(t.length/2))&&(r=i,n=s)}return n}function fy(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 zp=new Set(["state","producer","derived","effect","operator","template"]),my=new Set(["state","producer","derived","effect","operator"]);function ur(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 d=u;i.set(a,{params:Array.isArray(d.params)?d.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 d=u;if(Array.isArray(d.params)||e.push(`Template "${a}": missing 'params' array`),d.nodes==null||typeof d.nodes!="object"||Array.isArray(d.nodes))e.push(`Template "${a}": missing or invalid 'nodes' object`);else{let c=new Set(Array.isArray(d.params)?d.params:[]),l=new Set(Object.keys(d.nodes));for(let[p,f]of Object.entries(d.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"||!my.has(m.type))&&e.push(`Template "${a}" node "${p}": invalid type`),Array.isArray(m.deps))for(let h of m.deps)!l.has(h)&&!c.has(h)&&e.push(`Template "${a}" node "${p}": dep "${h}" is not an inner node or param`)}typeof d.output!="string"?e.push(`Template "${a}": missing 'output' string`):d.nodes[d.output]||e.push(`Template "${a}": output "${d.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 d=u;if(typeof d.type!="string"||!zp.has(d.type)){e.push(`Node "${a}": invalid type "${String(d.type)}" (expected: ${[...zp].join(", ")})`);continue}if(s.set(a,d.type),d.type==="template")if(typeof d.template!="string"||!i.has(d.template))e.push(`Node "${a}": template "${String(d.template)}" not found in templates`);else if(d.bind==null||typeof d.bind!="object"||Array.isArray(d.bind))e.push(`Node "${a}": template ref requires 'bind' object`);else{let c=i.get(d.template),l=d.bind;for(let p of c.params)p in l||e.push(`Node "${a}": template param "${p}" is not bound (template "${d.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(d.deps))for(let c of d.deps)c===a?e.push(`Node "${a}": self-referencing dep`):o.has(c)||e.push(`Node "${a}": dep "${c}" does not reference an existing node`);(d.type==="derived"||d.type==="effect"||d.type==="operator")&&!Array.isArray(d.deps)&&e.push(`Node "${a}": ${d.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 d=u;typeof d.from!="string"||!o.has(d.from)?e.push(`Feedback [${a}]: 'from' "${String(d.from)}" does not reference an existing node`):s.get(d.from)==="effect"&&n.push(`Feedback [${a}]: 'from' "${d.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 d.from=="string"&&d.from===d.to&&e.push(`Feedback [${a}]: 'from' and 'to' must be different nodes`),typeof d.to!="string"||!o.has(d.to)?e.push(`Feedback [${a}]: 'to' "${String(d.to)}" does not reference an existing node`):typeof d.to=="string"&&s.get(d.to)!=="state"&&e.push(`Feedback [${a}]: 'to' node "${d.to}" must be a state node (got "${s.get(d.to)??"unknown"}")`)}return{valid:e.length===0,errors:e,warnings:n}}function ko(t,e){let n=ur(t);if(!n.valid)throw new Error(`compileSpec: invalid GraphSpec:
46
+ `)}function my(t,e){if(!To(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 gy(t,e){if(!Nu(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 wo(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=Eu(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=Eu(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(To(u)&&u.configSchema){for(let[d,c]of Object.entries(u.configSchema))if(c.required!==!1&&!(d in a.config)&&n.push(`Node "${s}": config missing required field "${d}"`),d in a.config&&c.enum){let l=a.config[d];c.enum.includes(l)||n.push(`Node "${s}": config.${d} = ${JSON.stringify(l)}, expected one of: ${c.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 d=Eu(u.fn,r);n.push(`Template "${s}" node "${a}": fn "${u.fn}" not found in catalog`+(d?`. Did you mean "${d}"?`:""))}}return{valid:n.length===0,errors:n,warnings:[]}}function Eu(t,e){let n=null,r=1/0,o=t.toLowerCase();for(let s of e){let i=hy(o,s.toLowerCase());i<r&&i<=Math.max(3,Math.floor(t.length/2))&&(r=i,n=s)}return n}function hy(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 Jp=new Set(["state","producer","derived","effect","operator","template"]),yy=new Set(["state","producer","derived","effect","operator"]);function ur(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 d=u;i.set(a,{params:Array.isArray(d.params)?d.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 d=u;if(Array.isArray(d.params)||e.push(`Template "${a}": missing 'params' array`),d.nodes==null||typeof d.nodes!="object"||Array.isArray(d.nodes))e.push(`Template "${a}": missing or invalid 'nodes' object`);else{let c=new Set(Array.isArray(d.params)?d.params:[]),l=new Set(Object.keys(d.nodes));for(let[p,f]of Object.entries(d.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"||!yy.has(m.type))&&e.push(`Template "${a}" node "${p}": invalid type`),Array.isArray(m.deps))for(let h of m.deps)!l.has(h)&&!c.has(h)&&e.push(`Template "${a}" node "${p}": dep "${h}" is not an inner node or param`)}typeof d.output!="string"?e.push(`Template "${a}": missing 'output' string`):d.nodes[d.output]||e.push(`Template "${a}": output "${d.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 d=u;if(typeof d.type!="string"||!Jp.has(d.type)){e.push(`Node "${a}": invalid type "${String(d.type)}" (expected: ${[...Jp].join(", ")})`);continue}if(s.set(a,d.type),d.type==="template")if(typeof d.template!="string"||!i.has(d.template))e.push(`Node "${a}": template "${String(d.template)}" not found in templates`);else if(d.bind==null||typeof d.bind!="object"||Array.isArray(d.bind))e.push(`Node "${a}": template ref requires 'bind' object`);else{let c=i.get(d.template),l=d.bind;for(let p of c.params)p in l||e.push(`Node "${a}": template param "${p}" is not bound (template "${d.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(d.deps))for(let c of d.deps)c===a?e.push(`Node "${a}": self-referencing dep`):o.has(c)||e.push(`Node "${a}": dep "${c}" does not reference an existing node`);(d.type==="derived"||d.type==="effect"||d.type==="operator")&&!Array.isArray(d.deps)&&e.push(`Node "${a}": ${d.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 d=u;typeof d.from!="string"||!o.has(d.from)?e.push(`Feedback [${a}]: 'from' "${String(d.from)}" does not reference an existing node`):s.get(d.from)==="effect"&&n.push(`Feedback [${a}]: 'from' "${d.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 d.from=="string"&&d.from===d.to&&e.push(`Feedback [${a}]: 'from' and 'to' must be different nodes`),typeof d.to!="string"||!o.has(d.to)?e.push(`Feedback [${a}]: 'to' "${String(d.to)}" does not reference an existing node`):typeof d.to=="string"&&s.get(d.to)!=="state"&&e.push(`Feedback [${a}]: 'to' node "${d.to}" must be a state node (got "${s.get(d.to)??"unknown"}")`)}return{valid:e.length===0,errors:e,warnings:n}}function ko(t,e){let n=ur(t);if(!n.valid)throw new Error(`compileSpec: invalid GraphSpec:
47
47
  ${n.errors.join(`
48
48
  `)}`);let r=e?.catalog??{},o=e?.onMissing??"placeholder",s=new Y(t.name),i=t.templates??{},a=wo(t,r);if(!a.valid)throw new Error(`compileSpec: catalog validation errors:
49
49
  ${a.errors.join(`
50
- `)}`);let u=[],d=(g,y,b)=>{if(b){u.push({path:g,kind:"source",name:b});return}y&&u.push({path:g,kind:"fn",name:y})},c=g=>{let y=r.fns?.[g];return y?Up(y):void 0},l=g=>{let y=r.sources?.[g];return y?Jp(y):void 0},p=new Map,f=[];for(let[g,y]of Object.entries(t.nodes)){if(y.type==="template")continue;let b=y;if(b.type==="state"){let v=M(b.initial,{name:g,meta:b.meta?{...b.meta}:void 0});s.add(v,{name:g}),p.set(g,v)}else if(b.type==="producer"){let v=b.source?l(b.source):void 0,T=b.fn?c(b.fn):void 0;if(v){let w=v(b.config??{});s.add(w,{name:g}),p.set(g,w)}else if(T){let w=T([],b.config??{});s.add(w,{name:g}),p.set(g,w)}else{d(g,b.fn,b.source);let w=K(()=>{},{name:g,meta:{...b.meta,_specFn:b.fn,_specSource:b.source}});s.add(w,{name:g}),p.set(g,w)}}else f.push([g,b])}let m=!0,h=new Map(f);for(;h.size>0&&m;){m=!1;for(let[g,y]of[...h.entries()]){let b=y.deps??[];if(!b.every(x=>p.has(x)))continue;let v=b.map(x=>p.get(x)),T=y.fn?c(y.fn):void 0,w;T?w=T(v,y.config??{}):y.type==="effect"?(y.fn&&d(g,y.fn,void 0),w=pe(v,()=>{})):(y.fn&&d(g,y.fn,void 0),w=A(v,x=>x[0])),s.add(w,{name:g}),p.set(g,w),h.delete(g),m=!0}}if(h.size>0){let g=[...h.keys()].sort().join(", ");throw new Error(`compileSpec: unresolvable deps for nodes: ${g}`)}for(let[g,y]of Object.entries(t.nodes)){if(y.type!=="template")continue;let b=y,v=i[b.template],T=new Y(g),w=new Map,x=[];for(let[N,_]of Object.entries(v.nodes)){let I=(_.deps??[]).map(P=>P.startsWith("$")&&b.bind[P]?b.bind[P]:P),O={..._,deps:I};if(_.type==="state"){let P=M(_.initial,{name:N,meta:_.meta?{..._.meta}:void 0});T.add(P,{name:N}),w.set(N,P)}else if(_.type==="producer"){let P=_.source?l(_.source):void 0,B=_.fn?c(_.fn):void 0;if(P){let j=P(_.config??{});T.add(j,{name:N}),w.set(N,j)}else if(B){let j=B([],_.config??{});T.add(j,{name:N}),w.set(N,j)}else{d(`${g}.${N}`,_.fn,_.source);let j=K(()=>{},{name:N,meta:{..._.meta,_specFn:_.fn,_specSource:_.source}});T.add(j,{name:N}),w.set(N,j)}}else x.push([N,O])}let k=!0,S=new Map(x);for(;S.size>0&&k;){k=!1;for(let[N,_]of[...S.entries()]){let I=_.deps??[];if(!I.every(D=>w.has(D)||p.has(D)))continue;let P=I.map(D=>w.get(D)??p.get(D)),B=_.fn?c(_.fn):void 0,j;B?j=B(P,_.config??{}):_.type==="effect"?(_.fn&&d(`${g}.${N}`,_.fn,void 0),j=pe(P,()=>{})):(_.fn&&d(`${g}.${N}`,_.fn,void 0),j=A(P,D=>D[0])),T.add(j,{name:N}),w.set(N,j),S.delete(N),k=!0}}if(S.size>0){let N=[...S.keys()].sort().join(", ");throw new Error(`compileSpec: template "${b.template}" has unresolvable deps: ${N}`)}s.mount(g,T);let R=`${g}::${v.output}`;p.set(g,s.resolve(R));try{let N=s.resolve(R);N.meta._templateName?.emit(b.template),N.meta._templateBind?.emit(b.bind)}catch{}}for(let g of t.feedback??[])Qt(s,g.from,g.to,{maxIterations:g.maxIterations});if(u.length>0){if(o==="error"){let g=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":
50
+ `)}`);let u=[],d=(g,y,b)=>{if(b){u.push({path:g,kind:"source",name:b});return}y&&u.push({path:g,kind:"fn",name:y})},c=g=>{let y=r.fns?.[g];return y?Yp(y):void 0},l=g=>{let y=r.sources?.[g];return y?Qp(y):void 0},p=new Map,f=[];for(let[g,y]of Object.entries(t.nodes)){if(y.type==="template")continue;let b=y;if(b.type==="state"){let v=M(b.initial,{name:g,meta:b.meta?{...b.meta}:void 0});s.add(v,{name:g}),p.set(g,v)}else if(b.type==="producer"){let v=b.source?l(b.source):void 0,T=b.fn?c(b.fn):void 0;if(v){let w=v(b.config??{});s.add(w,{name:g}),p.set(g,w)}else if(T){let w=T([],b.config??{});s.add(w,{name:g}),p.set(g,w)}else{d(g,b.fn,b.source);let w=K(()=>{},{name:g,meta:{...b.meta,_specFn:b.fn,_specSource:b.source}});s.add(w,{name:g}),p.set(g,w)}}else f.push([g,b])}let m=!0,h=new Map(f);for(;h.size>0&&m;){m=!1;for(let[g,y]of[...h.entries()]){let b=y.deps??[];if(!b.every(k=>p.has(k)))continue;let v=b.map(k=>p.get(k)),T=y.fn?c(y.fn):void 0,w;T?w=T(v,y.config??{}):y.type==="effect"?(y.fn&&d(g,y.fn,void 0),w=pe(v,()=>{})):(y.fn&&d(g,y.fn,void 0),w=C(v,k=>k[0])),s.add(w,{name:g}),p.set(g,w),h.delete(g),m=!0}}if(h.size>0){let g=[...h.keys()].sort().join(", ");throw new Error(`compileSpec: unresolvable deps for nodes: ${g}`)}for(let[g,y]of Object.entries(t.nodes)){if(y.type!=="template")continue;let b=y,v=i[b.template],T=new Y(g),w=new Map,k=[];for(let[N,_]of Object.entries(v.nodes)){let I=(_.deps??[]).map(P=>P.startsWith("$")&&b.bind[P]?b.bind[P]:P),O={..._,deps:I};if(_.type==="state"){let P=M(_.initial,{name:N,meta:_.meta?{..._.meta}:void 0});T.add(P,{name:N}),w.set(N,P)}else if(_.type==="producer"){let P=_.source?l(_.source):void 0,B=_.fn?c(_.fn):void 0;if(P){let j=P(_.config??{});T.add(j,{name:N}),w.set(N,j)}else if(B){let j=B([],_.config??{});T.add(j,{name:N}),w.set(N,j)}else{d(`${g}.${N}`,_.fn,_.source);let j=K(()=>{},{name:N,meta:{..._.meta,_specFn:_.fn,_specSource:_.source}});T.add(j,{name:N}),w.set(N,j)}}else k.push([N,O])}let x=!0,S=new Map(k);for(;S.size>0&&x;){x=!1;for(let[N,_]of[...S.entries()]){let I=_.deps??[];if(!I.every(D=>w.has(D)||p.has(D)))continue;let P=I.map(D=>w.get(D)??p.get(D)),B=_.fn?c(_.fn):void 0,j;B?j=B(P,_.config??{}):_.type==="effect"?(_.fn&&d(`${g}.${N}`,_.fn,void 0),j=pe(P,()=>{})):(_.fn&&d(`${g}.${N}`,_.fn,void 0),j=C(P,D=>D[0])),T.add(j,{name:N}),w.set(N,j),S.delete(N),x=!0}}if(S.size>0){let N=[...S.keys()].sort().join(", ");throw new Error(`compileSpec: template "${b.template}" has unresolvable deps: ${N}`)}s.mount(g,T);let R=`${g}::${v.output}`;p.set(g,s.resolve(R));try{let N=s.resolve(R);N.meta._templateName?.emit(b.template),N.meta._templateBind?.emit(b.bind)}catch{}}for(let g of t.feedback??[])Qt(s,g.from,g.to,{maxIterations:g.maxIterations});if(u.length>0){if(o==="error"){let g=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
51
  ${g.join(`
52
- `)}`)}if(o==="warn"){let g=e?.onWarn??(y=>console.warn(y));for(let y of u)g(`compileSpec: ${y.path} references missing ${y.kind} "${y.name}" \u2014 substituted placeholder`)}}return s}var gy=new Set(["reduction","reduction_type","_specFn","_specSource","_templateName","_templateBind","feedbackFrom","feedbackTo","_internal"]);function hy(t){let e=t.describe({detail:"standard"}),n={},r=[],o=`::${Qe}::`,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 h=e.nodes[f]?.meta;h?.feedbackFrom&&h?.feedbackTo&&r.push({from:h.feedbackFrom,to:h.feedbackTo,...h.maxIterations?{maxIterations:h.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 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))gy.has(y)||(g[y]=b);Object.keys(g).length>0&&(h.meta=g)}n[f]=h}let a={},u={},d=new Set;for(let f of e.subgraphs){let m=`${f}::`;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,x=`${f}::`;for(let[I,O]of Object.entries(e.nodes)){if(!I.startsWith(x)||I.includes(o))continue;let P=I.slice(x.length);P.includes("::")||(w.add(P),T[P]={type:O.type,...O.deps.length>0?{deps:O.deps.map(B=>B.startsWith(x)?B.slice(x.length):B)}:{}})}let k=[],S=new Map;for(let I of Object.values(T))for(let O of I.deps??[])if(!w.has(O)&&!S.has(O)){let P=`$${O}`;k.push(P),S.set(O,P)}for(let I of Object.values(T))I.deps&&(I.deps=I.deps.map(O=>S.get(O)??O));let R=new Set;for(let I of Object.values(T))for(let O of I.deps??[])w.has(O)&&R.add(O);let _=[...w].filter(I=>!R.has(I))[0]??[...w].pop();a[b]={params:k,nodes:T,output:_}}delete n[f],u[f]={type:"template",template:b,bind:v},d.add(f);break}}}let c=new Map;for(let f of e.subgraphs){if(d.has(f))continue;let m={},h=`${f}::`;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??[]}])));c.has(g)||c.set(g,[]),c.get(g).push({name:f,nodes:m})}for(let[,f]of c){if(f.length<2)continue;let m=`${f[0].name}_template`,h=f[0].nodes,g=new Set(Object.keys(h)),y=[],b=new Map;for(let k of Object.values(h))for(let S of k.deps??[])if(!g.has(S)&&!b.has(S)){let R=`$${S}`;y.push(R),b.set(S,R)}let v=new Set;for(let k of Object.values(h))for(let S of k.deps??[])g.has(S)&&v.add(S);let w=[...g].filter(k=>!v.has(k))[0]??[...g].pop(),x={};for(let[k,S]of Object.entries(h))x[k]={...S,deps:S.deps?.map(R=>b.get(R)??R)};a[m]={params:y,nodes:x,output:w};for(let k of f){delete n[k.name];let S={},R=new Set(Object.keys(k.nodes));for(let N of Object.values(k.nodes))for(let _ of N.deps??[])if(!R.has(_)){let I=b.get(_)??`$${_}`;S[I]=_}u[k.name]={type:"template",template:m,bind:S}}}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 yy(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 d=t.feedback??[],c=e.feedback??[],l=new Set(d.map(b=>`${b.from}->${b.to}`)),p=new Set(c.map(b=>`${b.from}->${b.to}`));for(let b of c){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 d){let v=`${b.from}->${b.to}`;p.has(v)||n.push({type:"removed",path:`feedback.${v}`})}for(let b of d){let v=`${b.from}->${b.to}`,T=c.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,h=n.filter(b=>b.type==="changed").length,g=[];f&&g.push(`${f} 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 Qp=`You are a graph architect for GraphReFly, a reactive graph protocol.
52
+ `)}`)}if(o==="warn"){let g=e?.onWarn??(y=>console.warn(y));for(let y of u)g(`compileSpec: ${y.path} references missing ${y.kind} "${y.name}" \u2014 substituted placeholder`)}}return s}var by=new Set(["reduction","reduction_type","_specFn","_specSource","_templateName","_templateBind","feedbackFrom","feedbackTo","_internal"]);function vy(t){let e=t.describe({detail:"standard"}),n={},r=[],o=`::${Qe}::`,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 h=e.nodes[f]?.meta;h?.feedbackFrom&&h?.feedbackTo&&r.push({from:h.feedbackFrom,to:h.feedbackTo,...h.maxIterations?{maxIterations:h.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 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))by.has(y)||(g[y]=b);Object.keys(g).length>0&&(h.meta=g)}n[f]=h}let a={},u={},d=new Set;for(let f of e.subgraphs){let m=`${f}::`;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=`${f}::`;for(let[I,O]of Object.entries(e.nodes)){if(!I.startsWith(k)||I.includes(o))continue;let P=I.slice(k.length);P.includes("::")||(w.add(P),T[P]={type:O.type,...O.deps.length>0?{deps:O.deps.map(B=>B.startsWith(k)?B.slice(k.length):B)}:{}})}let x=[],S=new Map;for(let I of Object.values(T))for(let O of I.deps??[])if(!w.has(O)&&!S.has(O)){let P=`$${O}`;x.push(P),S.set(O,P)}for(let I of Object.values(T))I.deps&&(I.deps=I.deps.map(O=>S.get(O)??O));let R=new Set;for(let I of Object.values(T))for(let O of I.deps??[])w.has(O)&&R.add(O);let _=[...w].filter(I=>!R.has(I))[0]??[...w].pop();a[b]={params:x,nodes:T,output:_}}delete n[f],u[f]={type:"template",template:b,bind:v},d.add(f);break}}}let c=new Map;for(let f of e.subgraphs){if(d.has(f))continue;let m={},h=`${f}::`;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??[]}])));c.has(g)||c.set(g,[]),c.get(g).push({name:f,nodes:m})}for(let[,f]of c){if(f.length<2)continue;let m=`${f[0].name}_template`,h=f[0].nodes,g=new Set(Object.keys(h)),y=[],b=new Map;for(let x of Object.values(h))for(let S of x.deps??[])if(!g.has(S)&&!b.has(S)){let R=`$${S}`;y.push(R),b.set(S,R)}let v=new Set;for(let x of Object.values(h))for(let S of x.deps??[])g.has(S)&&v.add(S);let w=[...g].filter(x=>!v.has(x))[0]??[...g].pop(),k={};for(let[x,S]of Object.entries(h))k[x]={...S,deps:S.deps?.map(R=>b.get(R)??R)};a[m]={params:y,nodes:k,output:w};for(let x of f){delete n[x.name];let S={},R=new Set(Object.keys(x.nodes));for(let N of Object.values(x.nodes))for(let _ of N.deps??[])if(!R.has(_)){let I=b.get(_)??`$${_}`;S[I]=_}u[x.name]={type:"template",template:m,bind:S}}}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 Ty(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 d=t.feedback??[],c=e.feedback??[],l=new Set(d.map(b=>`${b.from}->${b.to}`)),p=new Set(c.map(b=>`${b.from}->${b.to}`));for(let b of c){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 d){let v=`${b.from}->${b.to}`;p.has(v)||n.push({type:"removed",path:`feedback.${v}`})}for(let b of d){let v=`${b.from}->${b.to}`,T=c.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,h=n.filter(b=>b.type==="changed").length,g=[];f&&g.push(`${f} 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 Zp=`You are a graph architect for GraphReFly, a reactive graph protocol.
53
53
 
54
54
  Given a natural-language description, produce a JSON GraphSpec with this structure:
55
55
 
@@ -91,20 +91,20 @@ Rules:
91
91
  - Use "templates" when the same subgraph pattern repeats (e.g., per-source resilience).
92
92
  - Use "feedback" for bounded cycles where a derived value writes back to a state node.
93
93
  - meta.description is required for every node.
94
- - Return ONLY valid JSON, no markdown fences or commentary.`;function Xp(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}async function by(t,e,n){let r=Qp,o=n?.catalogDescription??(n?.catalog?Yp(n.catalog):void 0);o&&(r+=`
94
+ - Return ONLY valid JSON, no markdown fences or commentary.`;function ef(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}async function wy(t,e,n){let r=Zp,o=n?.catalogDescription??(n?.catalog?Xp(n.catalog):void 0);o&&(r+=`
95
95
 
96
96
  Available catalog (use ONLY these names):
97
97
  ${o}`),n?.systemPromptExtra&&(r+=`
98
98
 
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=Xp(u));let d;try{d=JSON.parse(u)}catch{throw new Error(`llmCompose: LLM response is not valid JSON: ${u.slice(0,200)}`)}let c=ur(d);if(!c.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=ef(u));let d;try{d=JSON.parse(u)}catch{throw new Error(`llmCompose: LLM response is not valid JSON: ${u.slice(0,200)}`)}let c=ur(d);if(!c.valid)throw new Error(`llmCompose: invalid GraphSpec:
100
100
  ${c.errors.join(`
101
101
  `)}`);let l=d;if(n?.catalog){let p=n.maxAutoRefine??0;for(let f=0;f<=p;f++){let m=wo(l,n.catalog);if(m.valid)break;if(f===p)throw new Error(`llmCompose: catalog validation failed after ${p} refine attempts:
102
102
  ${m.errors.join(`
103
- `)}`);l=await Zp(l,`Fix these catalog errors:
103
+ `)}`);l=await tf(l,`Fix these catalog errors:
104
104
  ${m.errors.join(`
105
105
  `)}
106
106
 
107
- Use ONLY functions and sources from the catalog.`,e,{...n,catalogDescription:o})}}return l}async function Zp(t,e,n,r){let o=Qp;r?.catalogDescription&&(o+=`
107
+ Use ONLY functions and sources from the catalog.`,e,{...n,catalogDescription:o})}}return l}async function tf(t,e,n,r){let o=Zp;r?.catalogDescription&&(o+=`
108
108
 
109
109
  Available catalog:
110
110
  ${r.catalogDescription}`),r?.systemPromptExtra&&(o+=`
@@ -114,9 +114,9 @@ ${JSON.stringify(t,null,2)}
114
114
 
115
115
  Modification request: ${e}
116
116
 
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=Xp(u));let d;try{d=JSON.parse(u)}catch{throw new Error(`llmRefine: LLM response is not valid JSON: ${u.slice(0,200)}`)}let c=ur(d);if(!c.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=ef(u));let d;try{d=JSON.parse(u)}catch{throw new Error(`llmRefine: LLM response is not valid JSON: ${u.slice(0,200)}`)}let c=ur(d);if(!c.valid)throw new Error(`llmRefine: invalid GraphSpec:
118
118
  ${c.errors.join(`
119
- `)}`);return d}var ef=`You are a graph architect for GraphReFly, a reactive graph protocol.
119
+ `)}`);return d}var nf=`You are a graph architect for GraphReFly, a reactive graph protocol.
120
120
 
121
121
  Given a natural-language description, produce a JSON graph specification with this structure:
122
122
 
@@ -149,9 +149,9 @@ Rules:
149
149
  - "operator" nodes are parameterized transformations with deps.
150
150
  - Use "deps" inside each node to declare dependencies \u2014 no separate "edges" array.
151
151
  - meta.description is required for every node.
152
- - Return ONLY valid JSON, no markdown fences or commentary.`;async function tf(t,e,n){let o=[{role:"system",content:n?.systemPromptExtra?`${ef}
152
+ - Return ONLY valid JSON, no markdown fences or commentary.`;async function rf(t,e,n){let o=[{role:"system",content:n?.systemPromptExtra?`${nf}
153
153
 
154
- ${n.systemPromptExtra}`:ef},{role:"user",content:t}],s=e.invoke(o,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens,signal:n?.signal}),a=(await fo(s)).content.trim();a.startsWith("```")&&(a=or(a));let u;try{u=JSON.parse(a)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${a.slice(0,200)}`)}return ko(u,{catalog:n?.catalog})}function vy(t,e,n){let r=U(t);return Te(r,o=>!o||typeof o!="string"||o.trim().length===0?M(null):K(s=>{let i=new AbortController,a=!1;return tf(o,e,{...n,signal:i.signal}).then(u=>{if(a){u.destroy();return}s.emit(u),s.down([[L]])}).catch(u=>{a||s.down([[C,u]])}),()=>{a=!0,i.abort()}},{name:"graphFromSpec::call"}))}function Ty(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 wy(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??{},d=u.access;if(d==="human"||d==="system")continue;let c=u.description??`Set the value of ${i}`,l=Ty(u),p={type:"object",required:["value"],properties:{value:l},additionalProperties:!1},f=i.replace(/::/g,"__");r.push({type:"function",function:{name:f,description:c,parameters:p}}),o.push({name:i,description:c,inputSchema:p});let m=t,h=e,g=a.v;s.push({name:i,description:c,parameters:p,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}}ae();ee();he();var ky=`You are a reactive graph optimizer for GraphReFly.
154
+ ${n.systemPromptExtra}`:nf},{role:"user",content:t}],s=e.invoke(o,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens,signal:n?.signal}),a=(await fo(s)).content.trim();a.startsWith("```")&&(a=or(a));let u;try{u=JSON.parse(a)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${a.slice(0,200)}`)}return ko(u,{catalog:n?.catalog})}function ky(t,e,n){let r=U(t);return Te(r,o=>!o||typeof o!="string"||o.trim().length===0?M(null):K(s=>{let i=new AbortController,a=!1;return rf(o,e,{...n,signal:i.signal}).then(u=>{if(a){u.destroy();return}s.emit(u),s.down([[L]])}).catch(u=>{a||s.down([[A,u]])}),()=>{a=!0,i.abort()}},{name:"graphFromSpec::call"}))}function xy(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 Ry(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??{},d=u.access;if(d==="human"||d==="system")continue;let c=u.description??`Set the value of ${i}`,l=xy(u),p={type:"object",required:["value"],properties:{value:l},additionalProperties:!1},f=i.replace(/::/g,"__");r.push({type:"function",function:{name:f,description:c,parameters:p}}),o.push({name:i,description:c,inputSchema:p});let m=t,h=e,g=a.v;s.push({name:i,description:c,parameters:p,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}}ae();ee();he();var Sy=`You are a reactive graph optimizer for GraphReFly.
155
155
 
156
156
  Given a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.
157
157
 
@@ -172,8 +172,8 @@ Return ONLY valid JSON with this structure:
172
172
  Rules:
173
173
  - Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).
174
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 nf(t,e,n,r){let{expand:o,...s}=t.describe({actor:r?.actor,detail:"standard"}),i=[{role:"system",content:ky},{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}),d=(await fo(a)).content.trim();d.startsWith("```")&&(d=d.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let c;try{c=JSON.parse(d)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${d.slice(0,200)}`)}let l=c;if(typeof l.summary!="string")throw new Error("suggestStrategy: missing 'summary' in response");if(typeof l.reasoning!="string")throw new Error("suggestStrategy: missing 'reasoning' in response");if(!Array.isArray(l.operations))throw new Error("suggestStrategy: missing 'operations' array in response");return{summary:l.summary,reasoning:l.reasoning,operations:l.operations}}function xy(t,e,n,r){let o=U(e),s=Pt(o,t);return Te(s,i=>{if(i==null)return M(null);let[a,u]=i;return!u||!a||typeof a!="string"||a.trim().length===0?M(null):u.destroyed?M(null):K(d=>{let c=new AbortController,l=!1;return nf(u,a,n,{...r,signal:c.signal}).then(p=>{l||(d.emit(p),d.down([[L]]))}).catch(p=>{l||d.down([[C,p]])}),()=>{l=!0,c.abort()}},{name:"suggestStrategy::call"})})}var rf=new Set(["state","derived","producer","operator","effect"]);function Ry(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"||!rf.has(i.type))&&e.push(`Node "${o}": invalid type "${String(i.type)}" (expected: ${[...rf].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 yi={};ke(yi,{AuditTrailGraph:()=>gi,PolicyEnforcerGraph:()=>hi,auditTrail:()=>Ey,complianceSnapshot:()=>Ny,policyEnforcer:()=>Mu,reactiveExplainPath:()=>Ou});xe();$t();ae();_e();ee();Io();function sf(t,e){return ze("audit",t,e)}var Sy=new Set(["data","error","complete","teardown"]),gi=class extends Y{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=A([this.entries],([u])=>u.length,{name:"count",describeKind:"derived",meta:sf("count")}),this.add(this.count,{name:"count"}),this.addDisposer(re(this.count));let r=n.includeTypes!=null?new Set(n.includeTypes):Sy,o=n.filter,s=0,i=e.observe({timeline:!0,structured:!0}),a=i.onEvent(u=>{if(u.type==="derived")return;let d=u.type;if(!r.has(d))return;let c=u.path??"",l={seq:s++,timestamp_ns:u.timestamp_ns??H(),wall_clock_ns:oe(),path:c,type:d},f=(c?_u(e,c):void 0)?.lastMutation;f!=null&&(l.actor=f.actor),d==="data"&&(l.value=u.data),d==="error"&&(l.error=u.data);let m=c?My(e,c):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 Ey(t,e={}){return new gi(t,e)}var hi=class extends Y{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=_y(n)?n:M(n,{name:"policies"});this.policies=o,this.add(this.policies,{name:"policies"}),this.violations=new kn("violations",{retainedLimit:r.violationsLimit??1e3}),this.mount("violations",this.violations),this.violationCount=A([this.violations.events],([d])=>d.length,{name:"violationCount",describeKind:"derived",meta:sf("policy_violation_count")}),this.add(this.violationCount,{name:"violationCount"}),this.addDisposer(re(this.violationCount));let i=o.cache??[];this._currentGuard=Nr(i);let a=o.subscribe(d=>{for(let c of d)c[0]===E&&(i=c[1]??[],this._currentGuard=Nr(i))});this.addDisposer(a);let u=r.paths!=null?[...r.paths]:of(e);if(this._mode==="enforce"){let d=new Map,c=l=>{if(d.has(l))return;let p=_u(e,l);if(!(p instanceof Ae))return;let f=(m,h)=>{let g=this._currentGuard(m,h);return g||this._publishViolation(m,h,l,"blocked"),g};d.set(l,p._pushGuard(f))};for(let l of u)c(l);if(r.paths==null){let l=At(e,(p,f,m)=>{if(p.kind==="added")if(p.nodeKind==="node")c(`${m}${p.name}`);else{let h=f._mounts.get(p.name);if(!(h instanceof Y))return;let g=`${m}${p.name}::`,y=of(h);for(let b of y)c(b===""?`${m}${p.name}`:`${g}${b}`)}else if(p.kind==="removed")if(p.nodeKind==="node"){let h=`${m}${p.name}`,g=d.get(h);g!=null&&(g(),d.delete(h))}else{let h=`${m}${p.name}`,g=`${h}::`;for(let[y,b]of d)(y===h||y.startsWith(g))&&(b(),d.delete(y))}});this.addDisposer(l)}else{let l=e.topology.subscribe(p=>{for(let f of p){if(f[0]!==E)continue;let m=f[1];if(m.kind!=="removed"||m.nodeKind!=="node")continue;let h=d.get(m.name);h!=null&&(h(),d.delete(m.name))}});this.addDisposer(l)}this.addDisposer(()=>{for(let l of d.values())l();d.clear()})}else{let d=e.observe({timeline:!0,structured:!0}),c=d.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??_u(e,p)?.lastMutation?.actor;if(f==null)return;let m="write";this._currentGuard(f,m)||this._publishViolation(f,m,p,"observed")});this.addDisposer(()=>{c(),d.dispose()})}}_publishViolation(e,n,r,o){this.violations.publish({timestamp_ns:H(),wall_clock_ns:oe(),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 Mu(t,e,n={}){return new hi(t,e,n)}function Ou(t,e,n,r){return t.explain(e,n,{reactive:!0,...r})}function Ny(t,e={}){let n={format_version:1,timestamp_ns:H(),wall_clock_ns:oe(),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=Oy(n);return{...n,fingerprint:r}}function _y(t){return typeof t=="object"&&t!==null&&"subscribe"in t}function _u(t,e){try{return t.node(e)}catch{return}}function My(t,e){try{return t.annotation(e)}catch{return}}function of(t){let e=t.describe({detail:"minimal"});return Object.keys(e.nodes)}function Oy(t){return jt(JSON.stringify(Cy(t)))}function Cy(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,d])=>[n(u),n(d)])};if(s instanceof Set)return{__set:[...s].map(n)};if(ArrayBuffer.isView(s)){let a=s,u=new Array(a.length);for(let d=0;d<a.length;d++)u[d]=a[d]??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 vi={};ke(vi,{demoShell:()=>$y});Me();ee();xe();_e();ee();function Ay(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 af=new Set(["\uFF0C","\uFF0E","\uFF01","\uFF1A","\uFF1B","\uFF1F","\u3001","\u3002","\u30FB","\uFF09","\u3015","\u3009","\u300B","\u300D","\u300F","\u3011"]),Ly=new Set([".",",","!","?",":",";",")","]","}","%",'"',"\u201D","\u2019","\xBB","\u203A","\u2026"]);function Iy(t){return t.replace(/[\t\n\r\f ]+/g," ").replace(/^ | $/g,"")}function Py(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=[],d="",c=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",c!==null&&p===c?d+=l:(c!==null&&(i.push(d),a.push(c==="text"&&s),u.push(c)),d=l,c=p)}c!==null&&(i.push(d),a.push(c==="text"&&s),u.push(c)),n.push({texts:i,isWordLike:a,kinds:u})}return n}function Ft(t,e,n,r,o){let s=Iy(t);if(s.length===0)return[];let i=Py(s),a=new Intl.Segmenter(void 0,{granularity:"grapheme"}),u=[],d=[],c=[];for(let y of i)for(let b=0;b<y.texts.length;b++)u.push(y.texts[b]),d.push(y.kinds[b]),c.push(y.isWordLike[b]);let l=[],p=[],f=[];for(let y=0;y<u.length;y++){let b=u[y],v=d[y],T=c[y];if(v==="text"&&!T&&l.length>0&&p[p.length-1]==="text"&&b.length===1&&(Ly.has(b)||af.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 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=p[y];if(v!=="text"){g.push({text:b,width:v==="space"?h(" ")*b.length:0,kind:v,graphemeWidths:null});continue}if(Ay(b)){let x="";for(let k of a.segment(b)){let S=k.segment;if(x.length>0&&af.has(S)){x+=S;continue}if(x.length>0){let R=h(x);g.push({text:x,width:R,kind:"text",graphemeWidths:null})}x=S}if(x.length>0){let k=h(x);g.push({text:x,width:k,kind:"text",graphemeWidths:null})}continue}let T=h(b),w=null;if(f[y]&&b.length>1){let x=[];for(let k of a.segment(b))x.push(h(k.segment));x.length>1&&(w=x)}g.push({text:b,width:T,kind:"text",graphemeWidths:w})}return g}function Rn(t,e,n,r,o){if(t.length===0)return{lines:[],lineCount:0};let s=[],i=0,a=!1,u=0,d=0,c=0,l=0,p=-1,f=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=c,x=l,k=i){let S="";for(let R=u;R<w;R++){let N=t[R];if(!(N.kind==="soft-hyphen"||N.kind==="hard-break"))if(R===u&&d>0&&N.graphemeWidths){let I=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(N.text)].map(O=>O.segment);S+=I.slice(d).join("")}else S+=N.text}if(x>0&&w<t.length){let R=t[w],_=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(R.text)].map(O=>O.segment),I=u===w?d:0;S+=_.slice(I,x).join("")}w>0&&t[w-1]?.kind==="soft-hyphen"&&!(u===w&&d>0)&&(S+="-"),s.push({text:S,width:k,startSegment:u,startGrapheme:d,endSegment:w,endGrapheme:x}),i=0,a=!1,p=-1,f=0}function y(w){return w==="space"||w==="zero-width-break"||w==="soft-hyphen"}function b(w,x,k){a=!0,u=w,d=x,c=w+1,l=0,i=k}function v(w,x,k){a=!0,u=w,d=x,c=w,l=x+1,i=k}for(let w=0;w<t.length;w++){let x=t[w];if(x.kind==="hard-break"){a?g():s.push({text:"",width:0,startSegment:w,startGrapheme:0,endSegment:w,endGrapheme:0}),u=w+1,d=0;continue}let k=x.width;if(!a){k>e&&x.graphemeWidths?T(w,0,x.graphemeWidths):b(w,0,k),y(x.kind)&&(p=w+1,f=x.kind==="space"?i-k:i);continue}let S=i+k;if(S>e+.005){if(y(x.kind)){i+=k,c=w+1,l=0,g(w+1,0,x.kind==="space"?i-k:i);continue}if(p>=0){g(p,0,f),w--;continue}if(k>e&&x.graphemeWidths){g(),T(w,0,x.graphemeWidths);continue}g(),w--;continue}i=S,c=w+1,l=0,y(x.kind)&&(p=w+1,f=x.kind==="space"?i-k:i)}return a&&g(),{lines:s,lineCount:s.length};function T(w,x,k){for(let S=x;S<k.length;S++){let R=k[S];if(!a){v(w,S,R);continue}i+R>e+.005?(g(),v(w,S,R)):(i+=R,c=w,l=S+1)}a&&c===w&&l===k.length&&(c=w+1,l=0)}}function Cu(t){return t==="space"||t==="zero-width-break"||t==="soft-hyphen"}var Au=null;function Dy(){return Au===null&&(Au=new Intl.Segmenter(void 0,{granularity:"grapheme"})),Au}function uf(t,e,n){if(e===0&&n<0)return t.text;let r=[...Dy().segment(t.text)].map(s=>s.segment),o=n<0?r.length:n;return r.slice(e,o).join("")}function Xt(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+=uf(u,n,-1):i+=u.text)}if(o>0&&r<t.length){let a=t[r];i+=uf(a,e===r?n:0,o)}return s&&(i+="-"),i}function Gy(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 Lu(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=Gy(r),a=o,u=o===e.segmentIndex?s:0,d=0,c=a,l=0,p=!1,f=-1,m=0,h=0,g=!1,y=(w,x,k,S)=>{f=w,m=x,h=k,g=S==="soft-hyphen"},b=(w,x,k)=>{for(let S=x;S<k.length;S++){let R=k[S];if(!p){d=R,c=w,l=S+1,p=!0;continue}if(d+R>n+.005)return!0;d+=R,c=w,l=S+1}return c===w&&l===k.length&&(c=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:Xt(t,a,u,c,l,!1),width:d,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}};o=c}}for(;o<t.length;){let w=t[o];if(w.kind==="hard-break"){if(p){let S=c>0&&t[c-1]?.kind==="soft-hyphen";return{text:Xt(t,a,u,c,l,S),width:d+(S?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}}}return{text:"",width:0,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:o+1,graphemeIndex:0}}}let x=w.width;if(!p){if(x>n&&w.graphemeWidths){if(b(o,0,w.graphemeWidths))return{text:Xt(t,a,u,c,l,!1),width:d,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}};o=c;continue}d=x,c=o+1,l=0,p=!0,Cu(w.kind)&&y(o+1,0,w.kind==="space"?d-x:d,w.kind),o+=1;continue}let k=d+x;if(k>n+.005){if(Cu(w.kind)){c=o+1,l=0;let R=w.kind==="soft-hyphen",N=w.kind==="space"?d:d+(R?i:0);return{text:Xt(t,a,u,c,l,R),width:N,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}}}return f>=0?{text:Xt(t,a,u,f,m,g),width:h+(g?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:f,graphemeIndex:m}}:x>n&&w.graphemeWidths?{text:Xt(t,a,u,c,l,!1),width:d,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}}:{text:Xt(t,a,u,c,l,!1),width:d,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}}}d=k,c=o+1,l=0,Cu(w.kind)&&y(o+1,0,w.kind==="space"?d-x:d,w.kind),o+=1}if(!p)return null;let v=c>0&&t[c-1]?.kind==="soft-hyphen";return{text:Xt(t,a,u,c,l,v),width:d+(v?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}}}function Iu(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 bi(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 d=i.startSegment;d<e.length;d++){let c=e[d];if(c.kind==="soft-hyphen"||c.kind==="hard-break"){if(d>=i.endSegment&&i.endGrapheme===0)break;continue}let l=[...o.segment(c.text)].map(m=>m.segment);if(l.length===0)continue;let p=d===i.startSegment?i.startGrapheme:0,f;if(d<i.endSegment)f=l.length;else if(d===i.endSegment&&i.endGrapheme>0)f=i.endGrapheme;else break;for(let m=p;m<f;m++){let h=c.graphemeWidths?c.graphemeWidths[m]:c.width/l.length;r.push({x:u,y:a,width:h,height:n,line:s}),u+=h}}}return r}function Fy(t){let{adapter:e,name:n="reactive-layout"}=t,r=new Y(n),o=new Map,s=M(t.text??"",{name:"text"}),i=M(t.font??"16px sans-serif",{name:"font"}),a=M(t.lineHeight??20,{name:"line-height"}),u=M(Math.max(0,t.maxWidth??800),{name:"max-width"});function d(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 c=z([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=H(),x={hits:0,misses:0},k=Ft(b,T,e,o,x),S=H()-w,R=x.hits+x.misses,N=R===0?1:x.hits/R,_=c.meta;_&&(mt(_["cache-hit-rate"],N),mt(_["segment-count"],k.length),mt(_["layout-time-ns"],S)),h.emit(k);let I=()=>{o.clear(),e.clearCache?.()};return{deactivate:I,invalidate:I}},{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||!d(v.graphemeWidths??null,T.graphemeWidths??null))return!1}return!0}}),l=A([c,u,i],([m,h,g])=>Rn(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}}),p=A([l,a],([m,h])=>m.lineCount*h,{name:"height"}),f=A([l,c,a],([m,h,g])=>bi(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(c,{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:c,lineBreaks:l,height:p,charPositions:f}}function xo(t){return Math.max(0,Math.min(1,t))}function $y(t){let e=xo(t?.mainRatio??.65),n=xo(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 Y("demo-shell"),d=M(e,{name:"pane/main-ratio"}),c=M(n,{name:"pane/side-split"}),l=M(null,{name:"pane/fullscreen"}),p=M(r,{name:"viewport/width"});u.add(d,{name:"pane/main-ratio"}),u.add(c,{name:"pane/side-split"}),u.add(l,{name:"pane/fullscreen"}),u.add(p,{name:"viewport/width"});let f=A([d,p,l],([D,Z,F])=>{let Q=D,G=Z,q=F;return q==="main"?G:q==="graph"||q==="code"?0:Math.round(G*Q)},{name:"pane/main-width"}),m=A([f,p,l],([D,Z,F])=>{let Q=F,G=Z;return Q==="main"?0:Q==="graph"||Q==="code"?G:G-D},{name:"pane/side-width"}),h=A([c,l],([D,Z])=>{let F=Z;return F==="graph"?1:F==="code"||F==="main"?0:xo(D)},{name:"pane/graph-height-ratio"}),g=A([h,l],([D,Z])=>{let F=Z;return F==="code"?1:F==="graph"||F==="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(h,{name:"pane/graph-height-ratio"}),u.add(g,{name:"pane/code-height-ratio"});let y=M(null,{name:"demo/graph-ref"}),b=M(0,{name:"demo/graph-tick"});u.add(y,{name:"demo/graph-ref"}),u.add(b,{name:"demo/graph-tick"});let v=A([y,b],([D,Z])=>{let F=D;return F?F.describe({format:"mermaid"}):""},{name:"graph/mermaid"}),T=A([y,b],([D,Z])=>{let F=D;if(!F)return null;let{expand:Q,...G}=F.describe({detail:"standard"});return G},{name:"graph/describe"});u.add(v,{name:"graph/mermaid"}),u.add(T,{name:"graph/describe"});let w=M(null,{name:"hover/target"});u.add(w,{name:"hover/target"});let x=A([w],([D])=>{let Z=D;if(!Z)return null;let F=o.get(Z.id);return F?F.codeLine:null},{name:"highlight/code-scroll"}),k=A([w],([D])=>{let Z=D;if(!Z)return null;let F=o.get(Z.id);return F?F.visualSelector:null},{name:"highlight/visual"}),S=A([w],([D])=>{let Z=D;return Z?Z.id:null},{name:"highlight/graph"});if(u.add(x,{name:"highlight/code-scroll"}),u.add(k,{name:"highlight/visual"}),u.add(S,{name:"highlight/graph"}),a?.codeScroll){let D=a.codeScroll,Z=pe([x],([F])=>{D(F)});u.add(Z,{name:"highlight/apply-code-scroll"})}if(a?.visual){let D=a.visual,Z=pe([k],([F])=>{D(F)});u.add(Z,{name:"highlight/apply-visual"})}if(a?.graph){let D=a.graph,Z=pe([S],([F])=>{D(F)});u.add(Z,{name:"highlight/apply-graph"})}let R=M(null,{name:"inspect/selected-node"});u.add(R,{name:"inspect/selected-node"});let N=Ct("standard"),_=A([R,y,b],([D,Z,F])=>{let Q=Z,G=D;if(!Q||!G)return null;try{let q=Q.resolve(G),$=Dr(q,N);return{path:G,...$,value:q.cache}}catch{return null}},{name:"inspect/node-detail"}),I=A([y,b],([D,Z])=>{let F=D;return F?F.trace():[]},{name:"inspect/trace-log"});u.add(_,{name:"inspect/node-detail"}),u.add(I,{name:"inspect/trace-log"});let O=M(!1,{name:"meta/debug"});u.add(O,{name:"meta/debug"});let P=A([O,b],([D,Z])=>D?u.describe({format:"mermaid"}):"",{name:"meta/shell-mermaid"});u.add(P,{name:"meta/shell-mermaid"});let B=M("",{name:"layout/code-text"});if(u.add(B,{name:"layout/code-text"}),s){let D=new Map,Z=A([T],([G])=>{let q=G;if(!q)return new Map;let $=new Map;for(let[te]of Object.entries(q.nodes)){let Re=Ft(te,i,s,D),Oe=Rn(Re,1/0,s,i,D),Ce=Oe.lines.reduce((Ge,ie)=>Math.max(Ge,ie.width),0),ye=Oe.lineCount*20;$.set(te,{width:Ce,height:ye})}return $},{name:"layout/graph-labels",equals:(G,q)=>{if(G===q)return!0;let $=G,te=q;if($.size!==te.size)return!1;for(let[Re,Oe]of $){let Ce=te.get(Re);if(!Ce||Ce.width!==Oe.width||Ce.height!==Oe.height)return!1}return!0}}),F=A([B,m],([G,q])=>{let $=G;if(!$)return{lineCount:0,lines:[]};let te=Ft($,i,s,D),Re=q-40;return Rn(te,Math.max(100,Re),s,i,D)},{name:"layout/code-lines"}),Q=A([Z],([G])=>{let q=G;if(q.size===0)return 200;let $=0;for(let{width:te}of q.values())te>$&&($=te);return Math.max(200,Math.round($+80))},{name:"layout/side-width-hint"});u.add(Z,{name:"layout/graph-labels"}),u.add(F,{name:"layout/code-lines"}),u.add(Q,{name:"layout/side-width-hint"})}let j=0;return{graph:u,setMainRatio(D){u.set("pane/main-ratio",xo(D))},setSideSplit(D){u.set("pane/side-split",xo(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",++j)},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){X(D)},destroy(){u.destroy()}}}var Ti={};ke(Ti,{contentModerationGraph:()=>Vy,dataQualityGraph:()=>Ky,issueTrackerGraph:()=>By,observabilityGraph:()=>jy});Me();ee();function Ie(t,e){return ze("domain_template",t,e)}function jy(t,e){let n=new Y(t,e);n.add(e.source,{name:"source"});let r=[{name:"errors",classify:T=>Pu(T,"error")},{name:"traces",classify:T=>Pu(T,"trace")},{name:"metrics",classify:T=>Pu(T,"metric")}],o=e.branches??r,s=o.map(T=>({name:T.name,classify:T.classify})),i=uo("stratify",e.source,s);n.mount("stratify",i);let a=o.map(T=>{try{let w=n.resolve(`stratify::branch/${T.name}`);return A([w],([x])=>x,{initial:null})}catch{return M(null)}}),u=e.correlate??(T=>T),d=A(a,T=>u(T),{meta:Ie("observability",{stage:"correlate"})});n.add(d,{name:"correlate"});let c=e.sloCheck??(()=>({pass:!0})),l=A([d],T=>T[0],{meta:Ie("observability",{stage:"slo_value"})}),p=A([l],T=>c(T[0]),{meta:Ie("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=>A([T],w=>w[0]!=null?1:0)),h=f.map(T=>M(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=vo(m,h);n.add(g,{name:"alerts"});let y=A([g,p],T=>({scored:T[0],slo:T[1]}),{meta:Ie("observability",{stage:"output"})});n.add(y,{name:"output"});let b=M(null,{meta:Ie("observability",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=A([p],T=>{let w=T[0];return w&&w.pass===!1?w:null},{meta:Ie("observability",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),Qt(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??5}),n}function By(t,e){let n=new Y(t,e);n.add(e.source,{name:"source"});let r=0,o=T=>({id:`issue-${++r}`,title:String(T),severity:1,source:"unknown",raw:T}),s=e.extract??o,i=A([e.source],T=>s(T[0]),{meta:Ie("issue_tracker",{stage:"extract"})});n.add(i,{name:"extract"});let a=e.verify??(()=>({valid:!0})),u=A([i],T=>{let w=T[0];return{issue:w,verification:a(w)}},{meta:Ie("issue_tracker",{stage:"verify"})});n.add(u,{name:"verify"});let d=M([],{meta:Ie("issue_tracker",{stage:"known_patterns"})});n.add(d,{name:"known_patterns"});let c=e.detectRegression??(()=>({regression:!1})),l=A([i,d],T=>{let w=T[0],x=T[1];return{issue:w,regression:c(w,x)}},{meta:Ie("issue_tracker",{stage:"regression"})});n.add(l,{name:"regression"});let p=A([i],T=>T[0]?.severity??0),f=A([l],T=>T[0]?.regression?2:0);n.add(p,{name:"__severity_signal"}),n.add(f,{name:"__regression_signal"});let m=M(1),h=M(1.5);n.add(m,{name:"__severity_weight"}),n.add(h,{name:"__regression_weight"});let g=vo([p,f],[m,h]);n.add(g,{name:"priority"});let y=A([u,l,g],T=>({verified:T[0],regression:T[1],priority:T[2]}),{meta:Ie("issue_tracker",{stage:"output"})});n.add(y,{name:"output"});let b=M(null,{meta:Ie("issue_tracker",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=A([u],T=>{let w=T[0];if(w){let x=w.verification;if(x&&x.valid===!1)return w}return null},{meta:Ie("issue_tracker",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),Qt(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??3}),n}function Vy(t,e){let n=new Y(t,e);n.add(e.source,{name:"source"});let r=v=>({label:"review",confidence:.5,original:v}),o=e.classify??r,s=A([e.source],v=>o(v[0]),{meta:Ie("content_moderation",{stage:"classify"})});n.add(s,{name:"classify"});let i=uo("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=M(null),n.add(u,{name:"__review_fallback"})}let d=pe([u],v=>{let T=v[0];T&&a.append(T)});n.add(d,{name:"__review_accumulator"}),n.addDisposer(re(d));let c=M({},{meta:Ie("content_moderation",{stage:"policy",access:"both",description:"Moderation policy rules \u2014 updated via feedback"})});n.add(c,{name:"policy"});let l=e.weights??[.1,1,2],p=A([s],v=>v[0]?.confidence??0),f=A([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=M(1),h=M(1);n.add(m,{name:"__w_confidence"}),n.add(h,{name:"__w_severity"});let g=vo([p,f],[m,h]);n.add(g,{name:"priority"});let y=A([s,g],v=>({classification:v[0],priority:v[1]}),{meta:Ie("content_moderation",{stage:"output"})});n.add(y,{name:"output"});let b=A([a.entries,c],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:Ie("content_moderation",{stage:"feedback_condition"})});return n.add(b,{name:"feedback_condition"}),Qt(n,"feedback_condition","policy",{maxIterations:e.maxFeedbackIterations??5}),n}function Ky(t,e){let n=new Y(t,e);n.add(e.source,{name:"source"});let r=e.validate??(g=>({valid:!0,errors:[],record:g})),o=A([e.source],g=>g[0]!=null?r(g[0]):void 0,{meta:Ie("data_quality",{stage:"validate"})});n.add(o,{name:"validate"});let s=e.detectAnomaly??(g=>({anomaly:!1,score:0,record:g})),i=A([e.source],g=>g[0]!=null?s(g[0]):void 0,{meta:Ie("data_quality",{stage:"anomaly"})});n.add(i,{name:"anomaly"});let a=M(null,{meta:Ie("data_quality",{stage:"baseline",description:"Rolling baseline for drift detection"})});n.add(a,{name:"baseline"});let u=pe([o],g=>{let y=g[0];y?.valid&&X(()=>{a.emit(y.record)})});n.add(u,{name:"__baseline_updater"}),re(u);let d=e.detectDrift??(()=>({drift:!1})),c=A([e.source,a],g=>d(g[0],g[1]),{meta:Ie("data_quality",{stage:"drift"})});n.add(c,{name:"drift"});let l=e.suggest??(()=>null),p=A([o,i],g=>l({validation:g[0],anomaly:g[1]}),{meta:Ie("data_quality",{stage:"remediate"})});n.add(p,{name:"remediate"});let f=A([o,i,c,p],g=>({validation:g[0],anomaly:g[1],drift:g[2],remediation:g[3]}),{meta:Ie("data_quality",{stage:"output"})});n.add(f,{name:"output"});let m=M([],{meta:Ie("data_quality",{stage:"validation_rules"})});n.add(m,{name:"validation_rules"});let h=A([i],g=>{let y=g[0];return y?.anomaly?y:null},{meta:Ie("data_quality",{stage:"feedback_condition"})});return n.add(h,{name:"feedback_condition"}),Qt(n,"feedback_condition","validation_rules",{maxIterations:e.maxFeedbackIterations??3}),n}function Pu(t,e){if(t==null||typeof t!="object")return!1;let n=t;return n.type===e||n.kind===e}var ki={};ke(ki,{GuardedExecutionGraph:()=>wi,guardedExecution:()=>qy});var wi=class extends Y{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=Mu(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 qy(t,e){return new wi(t,e)}var Ai={};ke(Ai,{DEFAULT_DECAY_RATE:()=>cr,DEFAULT_EXECUTE_PROMPT:()=>Gu,DEFAULT_QUEUE_CONFIGS:()=>xi,DEFAULT_SEVERITY_WEIGHTS:()=>dr,DEFAULT_TRIAGE_PROMPT:()=>Du,DEFAULT_VERIFY_PROMPT:()=>Fu,HarnessGraph:()=>Ci,QUEUE_NAMES:()=>it,actuatorExecutor:()=>Jy,affectedTaskFilter:()=>tb,autoSolidify:()=>Yy,beforeAfterCompare:()=>eb,codeChangeBridge:()=>nb,createIntakeBridge:()=>Qy,defaultErrorClassifier:()=>Ri,defaultLlmExecutor:()=>hf,defaultLlmVerifier:()=>yf,evalIntakeBridge:()=>Xy,evalSource:()=>Zy,evalVerifier:()=>cf,harnessEvalPair:()=>mb,harnessLoop:()=>wb,harnessProfile:()=>xb,harnessTrace:()=>Sb,notifyEffect:()=>rb,priorityScore:()=>vb,refineExecutor:()=>Bu,resolvePromptFn:()=>Ro,strategyKey:()=>lr,strategyModel:()=>Vu});ae();ee();he();function Hy(t,e){return{outcome:"success",detail:`actuator applied ${e.intervention} for ${Uy(e.summary)}`,artifact:t}}function Wy(t,e){let n=t instanceof Error?t.message:String(t);return{outcome:"failure",detail:`actuator threw on ${e.intervention}: ${n}`}}function zy(t){return`actuator skipped ${t.intervention} (shouldApply returned false)`}function Uy(t,e=80){return t.length<=e?t:`${t.slice(0,e-1)}\u2026`}function Jy(t){let e=t.name??"actuator-executor",n=t.toOutput??Hy,r=t.onError??Wy,o=t.skipDetail??zy;return s=>{let i=Xe(s,u=>u!=null,{name:`${e}/gate-in`}),a=Te(i,u=>t.shouldApply&&!t.shouldApply(u)?K(d=>(d.down([[E,{outcome:"failure",detail:o(u)}],[L]]),()=>{}),{name:`${e}/skip`}):K(d=>{let c=new AbortController,l=!1,p=null,f=h=>{l||(l=!0,d.down([[E,h],[L]]),p?.(),p=null)},m;try{let h=t.apply(u,{signal:c.signal});m=U(h,{signal:c.signal})}catch(h){return f(r(h,u)),()=>{c.abort()}}return p=m.subscribe(h=>{for(let g of h){if(l)return;if(g[0]===E){f(n(g[1],u));return}if(g[0]===C){f(r(g[1],u));return}if(g[0]===L){f(r(new Error("actuator inner completed without emitting DATA"),u));return}}}),l&&p&&(p(),p=null),()=>{c.abort(),p?.(),p=null}},{name:`${e}/inner`}),{name:e});return Xe(a,u=>u!=null,{name:`${e}/gate-out`})}}ae();ee();function Yy(t){let e=t.name??"auto-solidify",n=t.extract??(o=>o.execution.artifact??null),r=t.predicate??(()=>!0);return K(o=>{let s=null,i=!1,a=()=>{i||(i=!0,s?.(),s=null)},u=d=>{i||(o.down([[C,d]]),a())};return s=t.verifyResults.subscribe(d=>{if(!i)for(let c of d){if(i)return;if(c[0]!==E){if(c[0]===L){o.down([[L]]),a();return}continue}let l=c[1];if(l==null||!l.verified)continue;let p;try{p=r(l)}catch(m){u(m);return}if(!p)continue;let f;try{f=n(l)}catch(m){u(m);return}if(f!=null){try{t.write(f,l)}catch(m){u(m);return}o.down([[E,f]])}}}),i&&s&&(s(),s=null),()=>{a()}},{name:e})}ee();he();function Qy(t,e,n,r){return pe([t],([o])=>{if(o==null)return;let s=n(o);for(let i of s)e.publish(i)},{name:r?.name??"intake-bridge"})}function Xy(t,e,n){let r=n?.defaultSeverity??"medium";return pe([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 Zy(t,e){return Te(t,()=>U(e()))}function eb(t,e){return A([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()]),d=[],c=[],l=[];for(let p of u){let f=i.get(p),m=a.get(p),h=f?.valid??!1,g=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;d.push({taskId:p,before:h,after:g,scoreDiff:v}),h&&!g&&c.push(p),!h&&g&&l.push(p)}return{newFailures:c,resolved:l,taskDeltas:d,overallImproved:l.length>c.length}},{name:"eval-delta"})}function tb(t,e){let n=e==null?null:Array.isArray(e)?M(e):e,r=[t];return n&&r.push(n),A(r,o=>{let s=o[0],i=n?new Set(o[1]):null,a=new Set;for(let u of s)for(let d of u.affectsEvalTasks??[])(i==null||i.has(d))&&a.add(d);return[...a].sort()},{name:"affected-task-filter"})}function nb(t,e,n,r){let o=r?.defaultSeverity??"high";function s(a){let u=[];for(let d of a.lintErrors??[])u.push({source:"code-change",summary:`Lint: ${d.rule} in ${d.file}:${d.line}`,evidence:d.message,affectsAreas:[d.file],severity:o});for(let d of a.testFailures??[])u.push({source:"test",summary:`Test failure: ${d.testId}`,evidence:d.message,affectsAreas:[d.file],affectsEvalTasks:[d.testId],severity:o});return u}let i=n??s;return pe([t],([a])=>{if(a!=null)for(let u of i(a))e.publish(u)},{name:r?.name??"code-change-bridge"})}function rb(t,e,n){return pe([t.latest],([r])=>{r!=null&&e(r)},{name:n?.name??"notify-effect"})}var it=["auto-fix","needs-decision","investigation","backlog"],xi={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1}},dr={critical:100,high:70,medium:40,low:10},cr=Math.LN2/(168*3600);function lr(t,e){return`${t}\u2192${e}`}var ob=/\b(parse|json|config|validation|syntax)\b/i,Ri=t=>ob.test(t.detail)?"self-correctable":"structural",Du=`You are a triage classifier for a reactive collaboration harness.
175
+ - Return ONLY valid JSON, no markdown fences or commentary.`;async function of(t,e,n,r){let{expand:o,...s}=t.describe({actor:r?.actor,detail:"standard"}),i=[{role:"system",content:Sy},{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}),d=(await fo(a)).content.trim();d.startsWith("```")&&(d=d.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let c;try{c=JSON.parse(d)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${d.slice(0,200)}`)}let l=c;if(typeof l.summary!="string")throw new Error("suggestStrategy: missing 'summary' in response");if(typeof l.reasoning!="string")throw new Error("suggestStrategy: missing 'reasoning' in response");if(!Array.isArray(l.operations))throw new Error("suggestStrategy: missing 'operations' array in response");return{summary:l.summary,reasoning:l.reasoning,operations:l.operations}}function Ey(t,e,n,r){let o=U(e),s=Pt(o,t);return Te(s,i=>{if(i==null)return M(null);let[a,u]=i;return!u||!a||typeof a!="string"||a.trim().length===0?M(null):u.destroyed?M(null):K(d=>{let c=new AbortController,l=!1;return of(u,a,n,{...r,signal:c.signal}).then(p=>{l||(d.emit(p),d.down([[L]]))}).catch(p=>{l||d.down([[A,p]])}),()=>{l=!0,c.abort()}},{name:"suggestStrategy::call"})})}var sf=new Set(["state","derived","producer","operator","effect"]);function Ny(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"||!sf.has(i.type))&&e.push(`Node "${o}": invalid type "${String(i.type)}" (expected: ${[...sf].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 yi={};ke(yi,{AuditTrailGraph:()=>gi,PolicyEnforcerGraph:()=>hi,auditTrail:()=>My,complianceSnapshot:()=>Oy,policyEnforcer:()=>Mu,reactiveExplainPath:()=>Ou});xe();$t();ae();_e();ee();Io();function uf(t,e){return ze("audit",t,e)}var _y=new Set(["data","error","complete","teardown"]),gi=class extends Y{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=C([this.entries],([u])=>u.length,{name:"count",describeKind:"derived",meta:uf("count")}),this.add(this.count,{name:"count"}),this.addDisposer(re(this.count));let r=n.includeTypes!=null?new Set(n.includeTypes):_y,o=n.filter,s=0,i=e.observe({timeline:!0,structured:!0}),a=i.onEvent(u=>{if(u.type==="derived")return;let d=u.type;if(!r.has(d))return;let c=u.path??"",l={seq:s++,timestamp_ns:u.timestamp_ns??H(),wall_clock_ns:oe(),path:c,type:d},f=(c?_u(e,c):void 0)?.lastMutation;f!=null&&(l.actor=f.actor),d==="data"&&(l.value=u.data),d==="error"&&(l.error=u.data);let m=c?Cy(e,c):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 My(t,e={}){return new gi(t,e)}var hi=class extends Y{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=Ay(n)?n:M(n,{name:"policies"});this.policies=o,this.add(this.policies,{name:"policies"}),this.violations=new kn("violations",{retainedLimit:r.violationsLimit??1e3}),this.mount("violations",this.violations),this.violationCount=C([this.violations.events],([d])=>d.length,{name:"violationCount",describeKind:"derived",meta:uf("policy_violation_count")}),this.add(this.violationCount,{name:"violationCount"}),this.addDisposer(re(this.violationCount));let i=o.cache??[];this._currentGuard=Nr(i);let a=o.subscribe(d=>{for(let c of d)c[0]===E&&(i=c[1]??[],this._currentGuard=Nr(i))});this.addDisposer(a);let u=r.paths!=null?[...r.paths]:af(e);if(this._mode==="enforce"){let d=new Map,c=l=>{if(d.has(l))return;let p=_u(e,l);if(!(p instanceof Ce))return;let f=(m,h)=>{let g=this._currentGuard(m,h);return g||this._publishViolation(m,h,l,"blocked"),g};d.set(l,p._pushGuard(f))};for(let l of u)c(l);if(r.paths==null){let l=Ct(e,(p,f,m)=>{if(p.kind==="added")if(p.nodeKind==="node")c(`${m}${p.name}`);else{let h=f._mounts.get(p.name);if(!(h instanceof Y))return;let g=`${m}${p.name}::`,y=af(h);for(let b of y)c(b===""?`${m}${p.name}`:`${g}${b}`)}else if(p.kind==="removed")if(p.nodeKind==="node"){let h=`${m}${p.name}`,g=d.get(h);g!=null&&(g(),d.delete(h))}else{let h=`${m}${p.name}`,g=`${h}::`;for(let[y,b]of d)(y===h||y.startsWith(g))&&(b(),d.delete(y))}});this.addDisposer(l)}else{let l=e.topology.subscribe(p=>{for(let f of p){if(f[0]!==E)continue;let m=f[1];if(m.kind!=="removed"||m.nodeKind!=="node")continue;let h=d.get(m.name);h!=null&&(h(),d.delete(m.name))}});this.addDisposer(l)}this.addDisposer(()=>{for(let l of d.values())l();d.clear()})}else{let d=e.observe({timeline:!0,structured:!0}),c=d.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??_u(e,p)?.lastMutation?.actor;if(f==null)return;let m="write";this._currentGuard(f,m)||this._publishViolation(f,m,p,"observed")});this.addDisposer(()=>{c(),d.dispose()})}}_publishViolation(e,n,r,o){this.violations.publish({timestamp_ns:H(),wall_clock_ns:oe(),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 Mu(t,e,n={}){return new hi(t,e,n)}function Ou(t,e,n,r){return t.explain(e,n,{reactive:!0,...r})}function Oy(t,e={}){let n={format_version:1,timestamp_ns:H(),wall_clock_ns:oe(),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=Ly(n);return{...n,fingerprint:r}}function Ay(t){return typeof t=="object"&&t!==null&&"subscribe"in t}function _u(t,e){try{return t.node(e)}catch{return}}function Cy(t,e){try{return t.annotation(e)}catch{return}}function af(t){let e=t.describe({detail:"minimal"});return Object.keys(e.nodes)}function Ly(t){return jt(JSON.stringify(Iy(t)))}function Iy(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,d])=>[n(u),n(d)])};if(s instanceof Set)return{__set:[...s].map(n)};if(ArrayBuffer.isView(s)){let a=s,u=new Array(a.length);for(let d=0;d<a.length;d++)u[d]=a[d]??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 vi={};ke(vi,{demoShell:()=>Vy});Me();ee();xe();_e();ee();function Py(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 df=new Set(["\uFF0C","\uFF0E","\uFF01","\uFF1A","\uFF1B","\uFF1F","\u3001","\u3002","\u30FB","\uFF09","\u3015","\u3009","\u300B","\u300D","\u300F","\u3011"]),Dy=new Set([".",",","!","?",":",";",")","]","}","%",'"',"\u201D","\u2019","\xBB","\u203A","\u2026"]);function Gy(t){return t.replace(/[\t\n\r\f ]+/g," ").replace(/^ | $/g,"")}function Fy(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=[],d="",c=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",c!==null&&p===c?d+=l:(c!==null&&(i.push(d),a.push(c==="text"&&s),u.push(c)),d=l,c=p)}c!==null&&(i.push(d),a.push(c==="text"&&s),u.push(c)),n.push({texts:i,isWordLike:a,kinds:u})}return n}function Ft(t,e,n,r,o){let s=Gy(t);if(s.length===0)return[];let i=Fy(s),a=new Intl.Segmenter(void 0,{granularity:"grapheme"}),u=[],d=[],c=[];for(let y of i)for(let b=0;b<y.texts.length;b++)u.push(y.texts[b]),d.push(y.kinds[b]),c.push(y.isWordLike[b]);let l=[],p=[],f=[];for(let y=0;y<u.length;y++){let b=u[y],v=d[y],T=c[y];if(v==="text"&&!T&&l.length>0&&p[p.length-1]==="text"&&b.length===1&&(Dy.has(b)||df.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 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=p[y];if(v!=="text"){g.push({text:b,width:v==="space"?h(" ")*b.length:0,kind:v,graphemeWidths:null});continue}if(Py(b)){let k="";for(let x of a.segment(b)){let S=x.segment;if(k.length>0&&df.has(S)){k+=S;continue}if(k.length>0){let R=h(k);g.push({text:k,width:R,kind:"text",graphemeWidths:null})}k=S}if(k.length>0){let x=h(k);g.push({text:k,width:x,kind:"text",graphemeWidths:null})}continue}let T=h(b),w=null;if(f[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 Rn(t,e,n,r,o){if(t.length===0)return{lines:[],lineCount:0};let s=[],i=0,a=!1,u=0,d=0,c=0,l=0,p=-1,f=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=c,k=l,x=i){let S="";for(let R=u;R<w;R++){let N=t[R];if(!(N.kind==="soft-hyphen"||N.kind==="hard-break"))if(R===u&&d>0&&N.graphemeWidths){let I=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(N.text)].map(O=>O.segment);S+=I.slice(d).join("")}else S+=N.text}if(k>0&&w<t.length){let R=t[w],_=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(R.text)].map(O=>O.segment),I=u===w?d:0;S+=_.slice(I,k).join("")}w>0&&t[w-1]?.kind==="soft-hyphen"&&!(u===w&&d>0)&&(S+="-"),s.push({text:S,width:x,startSegment:u,startGrapheme:d,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,d=k,c=w+1,l=0,i=x}function v(w,k,x){a=!0,u=w,d=k,c=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,d=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 S=i+x;if(S>e+.005){if(y(k.kind)){i+=x,c=w+1,l=0,g(w+1,0,k.kind==="space"?i-x:i);continue}if(p>=0){g(p,0,f),w--;continue}if(x>e&&k.graphemeWidths){g(),T(w,0,k.graphemeWidths);continue}g(),w--;continue}i=S,c=w+1,l=0,y(k.kind)&&(p=w+1,f=k.kind==="space"?i-x:i)}return a&&g(),{lines:s,lineCount:s.length};function T(w,k,x){for(let S=k;S<x.length;S++){let R=x[S];if(!a){v(w,S,R);continue}i+R>e+.005?(g(),v(w,S,R)):(i+=R,c=w,l=S+1)}a&&c===w&&l===x.length&&(c=w+1,l=0)}}function Au(t){return t==="space"||t==="zero-width-break"||t==="soft-hyphen"}var Cu=null;function $y(){return Cu===null&&(Cu=new Intl.Segmenter(void 0,{granularity:"grapheme"})),Cu}function cf(t,e,n){if(e===0&&n<0)return t.text;let r=[...$y().segment(t.text)].map(s=>s.segment),o=n<0?r.length:n;return r.slice(e,o).join("")}function Xt(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+=cf(u,n,-1):i+=u.text)}if(o>0&&r<t.length){let a=t[r];i+=cf(a,e===r?n:0,o)}return s&&(i+="-"),i}function jy(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 Lu(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=jy(r),a=o,u=o===e.segmentIndex?s:0,d=0,c=a,l=0,p=!1,f=-1,m=0,h=0,g=!1,y=(w,k,x,S)=>{f=w,m=k,h=x,g=S==="soft-hyphen"},b=(w,k,x)=>{for(let S=k;S<x.length;S++){let R=x[S];if(!p){d=R,c=w,l=S+1,p=!0;continue}if(d+R>n+.005)return!0;d+=R,c=w,l=S+1}return c===w&&l===x.length&&(c=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:Xt(t,a,u,c,l,!1),width:d,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}};o=c}}for(;o<t.length;){let w=t[o];if(w.kind==="hard-break"){if(p){let S=c>0&&t[c-1]?.kind==="soft-hyphen";return{text:Xt(t,a,u,c,l,S),width:d+(S?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,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:Xt(t,a,u,c,l,!1),width:d,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}};o=c;continue}d=k,c=o+1,l=0,p=!0,Au(w.kind)&&y(o+1,0,w.kind==="space"?d-k:d,w.kind),o+=1;continue}let x=d+k;if(x>n+.005){if(Au(w.kind)){c=o+1,l=0;let R=w.kind==="soft-hyphen",N=w.kind==="space"?d:d+(R?i:0);return{text:Xt(t,a,u,c,l,R),width:N,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}}}return f>=0?{text:Xt(t,a,u,f,m,g),width:h+(g?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:f,graphemeIndex:m}}:k>n&&w.graphemeWidths?{text:Xt(t,a,u,c,l,!1),width:d,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}}:{text:Xt(t,a,u,c,l,!1),width:d,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}}}d=x,c=o+1,l=0,Au(w.kind)&&y(o+1,0,w.kind==="space"?d-k:d,w.kind),o+=1}if(!p)return null;let v=c>0&&t[c-1]?.kind==="soft-hyphen";return{text:Xt(t,a,u,c,l,v),width:d+(v?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}}}function Iu(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 bi(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 d=i.startSegment;d<e.length;d++){let c=e[d];if(c.kind==="soft-hyphen"||c.kind==="hard-break"){if(d>=i.endSegment&&i.endGrapheme===0)break;continue}let l=[...o.segment(c.text)].map(m=>m.segment);if(l.length===0)continue;let p=d===i.startSegment?i.startGrapheme:0,f;if(d<i.endSegment)f=l.length;else if(d===i.endSegment&&i.endGrapheme>0)f=i.endGrapheme;else break;for(let m=p;m<f;m++){let h=c.graphemeWidths?c.graphemeWidths[m]:c.width/l.length;r.push({x:u,y:a,width:h,height:n,line:s}),u+=h}}}return r}function By(t){let{adapter:e,name:n="reactive-layout"}=t,r=new Y(n),o=new Map,s=M(t.text??"",{name:"text"}),i=M(t.font??"16px sans-serif",{name:"font"}),a=M(t.lineHeight??20,{name:"line-height"}),u=M(Math.max(0,t.maxWidth??800),{name:"max-width"});function d(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 c=z([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=H(),k={hits:0,misses:0},x=Ft(b,T,e,o,k),S=H()-w,R=k.hits+k.misses,N=R===0?1:k.hits/R,_=c.meta;_&&(mt(_["cache-hit-rate"],N),mt(_["segment-count"],x.length),mt(_["layout-time-ns"],S)),h.emit(x);let I=()=>{o.clear(),e.clearCache?.()};return{deactivate:I,invalidate:I}},{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||!d(v.graphemeWidths??null,T.graphemeWidths??null))return!1}return!0}}),l=C([c,u,i],([m,h,g])=>Rn(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}}),p=C([l,a],([m,h])=>m.lineCount*h,{name:"height"}),f=C([l,c,a],([m,h,g])=>bi(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(c,{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:c,lineBreaks:l,height:p,charPositions:f}}function xo(t){return Math.max(0,Math.min(1,t))}function Vy(t){let e=xo(t?.mainRatio??.65),n=xo(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 Y("demo-shell"),d=M(e,{name:"pane/main-ratio"}),c=M(n,{name:"pane/side-split"}),l=M(null,{name:"pane/fullscreen"}),p=M(r,{name:"viewport/width"});u.add(d,{name:"pane/main-ratio"}),u.add(c,{name:"pane/side-split"}),u.add(l,{name:"pane/fullscreen"}),u.add(p,{name:"viewport/width"});let f=C([d,p,l],([D,Z,F])=>{let Q=D,G=Z,q=F;return q==="main"?G:q==="graph"||q==="code"?0:Math.round(G*Q)},{name:"pane/main-width"}),m=C([f,p,l],([D,Z,F])=>{let Q=F,G=Z;return Q==="main"?0:Q==="graph"||Q==="code"?G:G-D},{name:"pane/side-width"}),h=C([c,l],([D,Z])=>{let F=Z;return F==="graph"?1:F==="code"||F==="main"?0:xo(D)},{name:"pane/graph-height-ratio"}),g=C([h,l],([D,Z])=>{let F=Z;return F==="code"?1:F==="graph"||F==="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(h,{name:"pane/graph-height-ratio"}),u.add(g,{name:"pane/code-height-ratio"});let y=M(null,{name:"demo/graph-ref"}),b=M(0,{name:"demo/graph-tick"});u.add(y,{name:"demo/graph-ref"}),u.add(b,{name:"demo/graph-tick"});let v=C([y,b],([D,Z])=>{let F=D;return F?F.describe({format:"mermaid"}):""},{name:"graph/mermaid"}),T=C([y,b],([D,Z])=>{let F=D;if(!F)return null;let{expand:Q,...G}=F.describe({detail:"standard"});return G},{name:"graph/describe"});u.add(v,{name:"graph/mermaid"}),u.add(T,{name:"graph/describe"});let w=M(null,{name:"hover/target"});u.add(w,{name:"hover/target"});let k=C([w],([D])=>{let Z=D;if(!Z)return null;let F=o.get(Z.id);return F?F.codeLine:null},{name:"highlight/code-scroll"}),x=C([w],([D])=>{let Z=D;if(!Z)return null;let F=o.get(Z.id);return F?F.visualSelector:null},{name:"highlight/visual"}),S=C([w],([D])=>{let Z=D;return Z?Z.id:null},{name:"highlight/graph"});if(u.add(k,{name:"highlight/code-scroll"}),u.add(x,{name:"highlight/visual"}),u.add(S,{name:"highlight/graph"}),a?.codeScroll){let D=a.codeScroll,Z=pe([k],([F])=>{D(F)});u.add(Z,{name:"highlight/apply-code-scroll"})}if(a?.visual){let D=a.visual,Z=pe([x],([F])=>{D(F)});u.add(Z,{name:"highlight/apply-visual"})}if(a?.graph){let D=a.graph,Z=pe([S],([F])=>{D(F)});u.add(Z,{name:"highlight/apply-graph"})}let R=M(null,{name:"inspect/selected-node"});u.add(R,{name:"inspect/selected-node"});let N=At("standard"),_=C([R,y,b],([D,Z,F])=>{let Q=Z,G=D;if(!Q||!G)return null;try{let q=Q.resolve(G),$=Dr(q,N);return{path:G,...$,value:q.cache}}catch{return null}},{name:"inspect/node-detail"}),I=C([y,b],([D,Z])=>{let F=D;return F?F.trace():[]},{name:"inspect/trace-log"});u.add(_,{name:"inspect/node-detail"}),u.add(I,{name:"inspect/trace-log"});let O=M(!1,{name:"meta/debug"});u.add(O,{name:"meta/debug"});let P=C([O,b],([D,Z])=>D?u.describe({format:"mermaid"}):"",{name:"meta/shell-mermaid"});u.add(P,{name:"meta/shell-mermaid"});let B=M("",{name:"layout/code-text"});if(u.add(B,{name:"layout/code-text"}),s){let D=new Map,Z=C([T],([G])=>{let q=G;if(!q)return new Map;let $=new Map;for(let[te]of Object.entries(q.nodes)){let Re=Ft(te,i,s,D),Oe=Rn(Re,1/0,s,i,D),Ae=Oe.lines.reduce((Ge,ie)=>Math.max(Ge,ie.width),0),ye=Oe.lineCount*20;$.set(te,{width:Ae,height:ye})}return $},{name:"layout/graph-labels",equals:(G,q)=>{if(G===q)return!0;let $=G,te=q;if($.size!==te.size)return!1;for(let[Re,Oe]of $){let Ae=te.get(Re);if(!Ae||Ae.width!==Oe.width||Ae.height!==Oe.height)return!1}return!0}}),F=C([B,m],([G,q])=>{let $=G;if(!$)return{lineCount:0,lines:[]};let te=Ft($,i,s,D),Re=q-40;return Rn(te,Math.max(100,Re),s,i,D)},{name:"layout/code-lines"}),Q=C([Z],([G])=>{let q=G;if(q.size===0)return 200;let $=0;for(let{width:te}of q.values())te>$&&($=te);return Math.max(200,Math.round($+80))},{name:"layout/side-width-hint"});u.add(Z,{name:"layout/graph-labels"}),u.add(F,{name:"layout/code-lines"}),u.add(Q,{name:"layout/side-width-hint"})}let j=0;return{graph:u,setMainRatio(D){u.set("pane/main-ratio",xo(D))},setSideSplit(D){u.set("pane/side-split",xo(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",++j)},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){X(D)},destroy(){u.destroy()}}}var Ti={};ke(Ti,{contentModerationGraph:()=>Hy,dataQualityGraph:()=>Wy,issueTrackerGraph:()=>qy,observabilityGraph:()=>Ky});Me();ee();function Ie(t,e){return ze("domain_template",t,e)}function Ky(t,e){let n=new Y(t,e);n.add(e.source,{name:"source"});let r=[{name:"errors",classify:T=>Pu(T,"error")},{name:"traces",classify:T=>Pu(T,"trace")},{name:"metrics",classify:T=>Pu(T,"metric")}],o=e.branches??r,s=o.map(T=>({name:T.name,classify:T.classify})),i=uo("stratify",e.source,s);n.mount("stratify",i);let a=o.map(T=>{try{let w=n.resolve(`stratify::branch/${T.name}`);return C([w],([k])=>k,{initial:null})}catch{return M(null)}}),u=e.correlate??(T=>T),d=C(a,T=>u(T),{meta:Ie("observability",{stage:"correlate"})});n.add(d,{name:"correlate"});let c=e.sloCheck??(()=>({pass:!0})),l=C([d],T=>T[0],{meta:Ie("observability",{stage:"slo_value"})}),p=C([l],T=>c(T[0]),{meta:Ie("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=>C([T],w=>w[0]!=null?1:0)),h=f.map(T=>M(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=vo(m,h);n.add(g,{name:"alerts"});let y=C([g,p],T=>({scored:T[0],slo:T[1]}),{meta:Ie("observability",{stage:"output"})});n.add(y,{name:"output"});let b=M(null,{meta:Ie("observability",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=C([p],T=>{let w=T[0];return w&&w.pass===!1?w:null},{meta:Ie("observability",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),Qt(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??5}),n}function qy(t,e){let n=new Y(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=C([e.source],T=>s(T[0]),{meta:Ie("issue_tracker",{stage:"extract"})});n.add(i,{name:"extract"});let a=e.verify??(()=>({valid:!0})),u=C([i],T=>{let w=T[0];return{issue:w,verification:a(w)}},{meta:Ie("issue_tracker",{stage:"verify"})});n.add(u,{name:"verify"});let d=M([],{meta:Ie("issue_tracker",{stage:"known_patterns"})});n.add(d,{name:"known_patterns"});let c=e.detectRegression??(()=>({regression:!1})),l=C([i,d],T=>{let w=T[0],k=T[1];return{issue:w,regression:c(w,k)}},{meta:Ie("issue_tracker",{stage:"regression"})});n.add(l,{name:"regression"});let p=C([i],T=>T[0]?.severity??0),f=C([l],T=>T[0]?.regression?2:0);n.add(p,{name:"__severity_signal"}),n.add(f,{name:"__regression_signal"});let m=M(1),h=M(1.5);n.add(m,{name:"__severity_weight"}),n.add(h,{name:"__regression_weight"});let g=vo([p,f],[m,h]);n.add(g,{name:"priority"});let y=C([u,l,g],T=>({verified:T[0],regression:T[1],priority:T[2]}),{meta:Ie("issue_tracker",{stage:"output"})});n.add(y,{name:"output"});let b=M(null,{meta:Ie("issue_tracker",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=C([u],T=>{let w=T[0];if(w){let k=w.verification;if(k&&k.valid===!1)return w}return null},{meta:Ie("issue_tracker",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),Qt(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??3}),n}function Hy(t,e){let n=new Y(t,e);n.add(e.source,{name:"source"});let r=v=>({label:"review",confidence:.5,original:v}),o=e.classify??r,s=C([e.source],v=>o(v[0]),{meta:Ie("content_moderation",{stage:"classify"})});n.add(s,{name:"classify"});let i=uo("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=M(null),n.add(u,{name:"__review_fallback"})}let d=pe([u],v=>{let T=v[0];T&&a.append(T)});n.add(d,{name:"__review_accumulator"}),n.addDisposer(re(d));let c=M({},{meta:Ie("content_moderation",{stage:"policy",access:"both",description:"Moderation policy rules \u2014 updated via feedback"})});n.add(c,{name:"policy"});let l=e.weights??[.1,1,2],p=C([s],v=>v[0]?.confidence??0),f=C([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=M(1),h=M(1);n.add(m,{name:"__w_confidence"}),n.add(h,{name:"__w_severity"});let g=vo([p,f],[m,h]);n.add(g,{name:"priority"});let y=C([s,g],v=>({classification:v[0],priority:v[1]}),{meta:Ie("content_moderation",{stage:"output"})});n.add(y,{name:"output"});let b=C([a.entries,c],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:Ie("content_moderation",{stage:"feedback_condition"})});return n.add(b,{name:"feedback_condition"}),Qt(n,"feedback_condition","policy",{maxIterations:e.maxFeedbackIterations??5}),n}function Wy(t,e){let n=new Y(t,e);n.add(e.source,{name:"source"});let r=e.validate??(g=>({valid:!0,errors:[],record:g})),o=C([e.source],g=>g[0]!=null?r(g[0]):void 0,{meta:Ie("data_quality",{stage:"validate"})});n.add(o,{name:"validate"});let s=e.detectAnomaly??(g=>({anomaly:!1,score:0,record:g})),i=C([e.source],g=>g[0]!=null?s(g[0]):void 0,{meta:Ie("data_quality",{stage:"anomaly"})});n.add(i,{name:"anomaly"});let a=M(null,{meta:Ie("data_quality",{stage:"baseline",description:"Rolling baseline for drift detection"})});n.add(a,{name:"baseline"});let u=pe([o],g=>{let y=g[0];y?.valid&&X(()=>{a.emit(y.record)})});n.add(u,{name:"__baseline_updater"}),re(u);let d=e.detectDrift??(()=>({drift:!1})),c=C([e.source,a],g=>d(g[0],g[1]),{meta:Ie("data_quality",{stage:"drift"})});n.add(c,{name:"drift"});let l=e.suggest??(()=>null),p=C([o,i],g=>l({validation:g[0],anomaly:g[1]}),{meta:Ie("data_quality",{stage:"remediate"})});n.add(p,{name:"remediate"});let f=C([o,i,c,p],g=>({validation:g[0],anomaly:g[1],drift:g[2],remediation:g[3]}),{meta:Ie("data_quality",{stage:"output"})});n.add(f,{name:"output"});let m=M([],{meta:Ie("data_quality",{stage:"validation_rules"})});n.add(m,{name:"validation_rules"});let h=C([i],g=>{let y=g[0];return y?.anomaly?y:null},{meta:Ie("data_quality",{stage:"feedback_condition"})});return n.add(h,{name:"feedback_condition"}),Qt(n,"feedback_condition","validation_rules",{maxIterations:e.maxFeedbackIterations??3}),n}function Pu(t,e){if(t==null||typeof t!="object")return!1;let n=t;return n.type===e||n.kind===e}var ki={};ke(ki,{GuardedExecutionGraph:()=>wi,guardedExecution:()=>zy});var wi=class extends Y{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=Mu(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 zy(t,e){return new wi(t,e)}var Ci={};ke(Ci,{DEFAULT_DECAY_RATE:()=>cr,DEFAULT_EXECUTE_PROMPT:()=>Gu,DEFAULT_QUEUE_CONFIGS:()=>xi,DEFAULT_SEVERITY_WEIGHTS:()=>dr,DEFAULT_TRIAGE_PROMPT:()=>Du,DEFAULT_VERIFY_PROMPT:()=>Fu,HarnessGraph:()=>Ai,QUEUE_NAMES:()=>it,actuatorExecutor:()=>Xy,affectedTaskFilter:()=>ob,autoSolidify:()=>Zy,beforeAfterCompare:()=>rb,codeChangeBridge:()=>sb,createIntakeBridge:()=>eb,defaultErrorClassifier:()=>Ri,defaultLlmExecutor:()=>bf,defaultLlmVerifier:()=>vf,evalIntakeBridge:()=>tb,evalSource:()=>nb,evalVerifier:()=>pf,harnessEvalPair:()=>yb,harnessLoop:()=>Rb,harnessProfile:()=>Eb,harnessTrace:()=>_b,notifyEffect:()=>ib,priorityScore:()=>kb,refineExecutor:()=>Bu,resolvePromptFn:()=>Ro,strategyKey:()=>lr,strategyModel:()=>Vu});ae();ee();he();function Uy(t,e){return{outcome:"success",detail:`actuator applied ${e.intervention} for ${Qy(e.summary)}`,artifact:t}}function Jy(t,e){let n=t instanceof Error?t.message:String(t);return{outcome:"failure",detail:`actuator threw on ${e.intervention}: ${n}`}}function Yy(t){return`actuator skipped ${t.intervention} (shouldApply returned false)`}function Qy(t,e=80){return t.length<=e?t:`${t.slice(0,e-1)}\u2026`}function Xy(t){let e=t.name??"actuator-executor",n=t.toOutput??Uy,r=t.onError??Jy,o=t.skipDetail??Yy;return s=>{let i=Xe(s,u=>u!=null,{name:`${e}/gate-in`}),a=Te(i,u=>t.shouldApply&&!t.shouldApply(u)?K(d=>(d.down([[E,{outcome:"failure",detail:o(u)}],[L]]),()=>{}),{name:`${e}/skip`}):K(d=>{let c=new AbortController,l=!1,p=null,f=h=>{l||(l=!0,d.down([[E,h],[L]]),p?.(),p=null)},m;try{let h=t.apply(u,{signal:c.signal});m=U(h,{signal:c.signal})}catch(h){return f(r(h,u)),()=>{c.abort()}}return p=m.subscribe(h=>{for(let g of h){if(l)return;if(g[0]===E){f(n(g[1],u));return}if(g[0]===A){f(r(g[1],u));return}if(g[0]===L){f(r(new Error("actuator inner completed without emitting DATA"),u));return}}}),l&&p&&(p(),p=null),()=>{c.abort(),p?.(),p=null}},{name:`${e}/inner`}),{name:e});return Xe(a,u=>u!=null,{name:`${e}/gate-out`})}}ae();ee();function Zy(t){let e=t.name??"auto-solidify",n=t.extract??(o=>o.execution.artifact??null),r=t.predicate??(()=>!0);return K(o=>{let s=null,i=!1,a=()=>{i||(i=!0,s?.(),s=null)},u=d=>{i||(o.down([[A,d]]),a())};return s=t.verifyResults.subscribe(d=>{if(!i)for(let c of d){if(i)return;if(c[0]!==E){if(c[0]===L){o.down([[L]]),a();return}continue}let l=c[1];if(l==null||!l.verified)continue;let p;try{p=r(l)}catch(m){u(m);return}if(!p)continue;let f;try{f=n(l)}catch(m){u(m);return}if(f!=null){try{t.write(f,l)}catch(m){u(m);return}o.down([[E,f]])}}}),i&&s&&(s(),s=null),()=>{a()}},{name:e})}ee();he();function eb(t,e,n,r){return pe([t],([o])=>{if(o==null)return;let s=n(o);for(let i of s)e.publish(i)},{name:r?.name??"intake-bridge"})}function tb(t,e,n){let r=n?.defaultSeverity??"medium";return pe([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 nb(t,e){return Te(t,()=>U(e()))}function rb(t,e){return C([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()]),d=[],c=[],l=[];for(let p of u){let f=i.get(p),m=a.get(p),h=f?.valid??!1,g=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;d.push({taskId:p,before:h,after:g,scoreDiff:v}),h&&!g&&c.push(p),!h&&g&&l.push(p)}return{newFailures:c,resolved:l,taskDeltas:d,overallImproved:l.length>c.length}},{name:"eval-delta"})}function ob(t,e){let n=e==null?null:Array.isArray(e)?M(e):e,r=[t];return n&&r.push(n),C(r,o=>{let s=o[0],i=n?new Set(o[1]):null,a=new Set;for(let u of s)for(let d of u.affectsEvalTasks??[])(i==null||i.has(d))&&a.add(d);return[...a].sort()},{name:"affected-task-filter"})}function sb(t,e,n,r){let o=r?.defaultSeverity??"high";function s(a){let u=[];for(let d of a.lintErrors??[])u.push({source:"code-change",summary:`Lint: ${d.rule} in ${d.file}:${d.line}`,evidence:d.message,affectsAreas:[d.file],severity:o});for(let d of a.testFailures??[])u.push({source:"test",summary:`Test failure: ${d.testId}`,evidence:d.message,affectsAreas:[d.file],affectsEvalTasks:[d.testId],severity:o});return u}let i=n??s;return pe([t],([a])=>{if(a!=null)for(let u of i(a))e.publish(u)},{name:r?.name??"code-change-bridge"})}function ib(t,e,n){return pe([t.latest],([r])=>{r!=null&&e(r)},{name:n?.name??"notify-effect"})}var it=["auto-fix","needs-decision","investigation","backlog"],xi={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1}},dr={critical:100,high:70,medium:40,low:10},cr=Math.LN2/(168*3600);function lr(t,e){return`${t}\u2192${e}`}var ab=/\b(parse|json|config|validation|syntax)\b/i,Ri=t=>ab.test(t.detail)?"self-correctable":"structural",Du=`You are a triage classifier for a reactive collaboration harness.
177
177
 
178
178
  Given an intake item, classify it and output JSON:
179
179
  {
@@ -214,11 +214,11 @@ Output JSON:
214
214
  "verified": true/false,
215
215
  "findings": ["<finding1>", ...],
216
216
  "errorClass": "self-correctable" | "structural" // only if verified=false
217
- }`;function Ro(t,e,n){if(typeof t=="function")return t;let r=t??e;return o=>n(r,o)}ee();ee();var Si={};ke(Si,{blindVariation:()=>ib,errorCritique:()=>db,refineLoop:()=>ju});Me();xe();ae();_e();ee();function sb(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 df(t,e){if(t.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(t.length===1){let s=$u(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 d=u.candidateIndex;typeof d=="number"&&d>=0&&d<t.length&&(s[d].sum+=u.score,s[d].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 d=s[u].count>0?s[u].sum/s[u].count:Number.NEGATIVE_INFINITY;d>a&&(a=d,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 $u(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 ju(t,e,n,r){let o=r.name??"refine-loop",s=new Y(o,r.graph),i=sb(r.dataset)?r.dataset:M(r.dataset,{name:"dataset"});s.add(i,{name:"dataset"});let a=M(0,{name:"iteration"});s.add(a,{name:"iteration"});let u=M(n,{name:"strategy",equals:()=>!1});s.add(u,{name:"strategy"});let d=M(null,{name:"lastFeedback"});s.add(d,{name:"lastFeedback"});let c=M([],{name:"prevCandidates"});s.add(c,{name:"prevCandidates"});let l=M(!1,{name:"paused"});s.add(l,{name:"paused"});let p=M("running",{name:"status"});s.add(p,{name:"status"});let f=M([],{name:"history",equals:()=>!1});s.add(f,{name:"history"});let m=M(null,{name:"best"});s.add(m,{name:"best"});let h=M(Number.NEGATIVE_INFINITY,{name:"score"});s.add(h,{name:"score"});let g=M(0,{name:"budget-used"});s.add(g,{name:"budget-used"});let y=go("stages");s.mount("stages",y);let b=y.topic("generate"),v=y.topic("evaluate"),T=y.topic("analyze"),w=y.topic("decide"),x=n,k=null,S=[];s.addDisposer(u.subscribe(ie=>{for(let we of ie)we[0]===E&&(x=we[1])})),s.addDisposer(d.subscribe(ie=>{for(let we of ie)we[0]===E&&(k=we[1])})),s.addDisposer(c.subscribe(ie=>{for(let we of ie)we[0]===E&&(S=we[1])}));let R=Te(a,ie=>{let we=x,Fe=ie===0||k==null;return z([],(be,J)=>{let se=!1;try{let ve=Fe?we.seed(t):we.generate(k,S);if(ve instanceof Promise)return ve.then(W=>{se||J.emit(W)},W=>{se||J.down([[C,W]])}),()=>{se=!0};J.emit(ve)}catch(ve){se=!0,J.down([[C,ve]])}},{describeKind:"producer"})},{name:"candidates"});s.add(R,{name:"candidates"});let N=pe([R],(ie,we,Fe)=>{let be=Fe.terminalDeps[0];be!==void 0&&be!==!0&&p.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});s.add(N,{name:"error-watcher"}),s.addDisposer(N.subscribe(()=>{}));let _=A([R,a],([ie,we])=>({iteration:we,candidates:ie,timestamp_ns:H()}),{name:"generate-event"});s.add(_,{name:"generate-event"}),s.addDisposer(_.subscribe(()=>{}));let I=pe([_],([ie])=>{b.publish(ie)},{name:"generate-publish"});s.add(I,{name:"generate-publish"}),s.addDisposer(I.subscribe(()=>{}));let O=pe([R],([ie])=>{c.emit(ie)},{name:"generate-mirror"});s.add(O,{name:"generate-mirror"}),s.addDisposer(O.subscribe(()=>{}));let P=e(R,i);s.add(P,{name:"scores"});let B=A([P,R,a],([ie,we,Fe])=>({iteration:Fe,candidates:we,scores:ie,timestamp_ns:H()}),{name:"evaluate-event"});s.add(B,{name:"evaluate-event"}),s.addDisposer(B.subscribe(()=>{}));let j=pe([B],([ie])=>{v.publish(ie)},{name:"evaluate-publish"});s.add(j,{name:"evaluate-publish"}),s.addDisposer(j.subscribe(()=>{}));let D=A([P,R],([ie,we])=>x.analyze(ie,we),{name:"feedback"});s.add(D,{name:"feedback"});let Z=A([D,R,a],([ie,we,Fe])=>({iteration:Fe,candidates:we,feedback:ie,timestamp_ns:H()}),{name:"analyze-event"});s.add(Z,{name:"analyze-event"}),s.addDisposer(Z.subscribe(()=>{}));let F=pe([Z],([ie])=>{T.publish(ie)},{name:"analyze-publish"});s.add(F,{name:"analyze-publish"}),s.addDisposer(F.subscribe(()=>{}));let Q=A([f],([ie])=>{let we=ie;if(r.patience==null||we.length<=r.patience)return!1;let Fe=we.slice(-(r.patience+1)),be=Fe[0].bestScore;return Fe.slice(1).every(J=>J.bestScore<=be)},{name:"patience-check"});s.add(Q,{name:"patience-check"});let G=A([h],([ie])=>r.minScore!=null&&ie>=r.minScore,{name:"min-score-check"});s.add(G,{name:"min-score-check"});let q=A([f],([ie])=>{let we=ie;if(r.minDelta==null||we.length<2)return!1;let Fe=we[we.length-2].bestScore,be=we[we.length-1].bestScore;return Math.abs(be-Fe)<r.minDelta},{name:"min-delta-check"});s.add(q,{name:"min-delta-check"});let $=A([g],([ie])=>r.maxEvaluations!=null&&ie>=r.maxEvaluations,{name:"max-evaluations-check"});s.add($,{name:"max-evaluations-check"});let te=A([a],([ie])=>r.maxIterations!=null&&ie>=r.maxIterations,{name:"max-iterations-check"});s.add(te,{name:"max-iterations-check"});let Re=A([g],([ie])=>r.budget!=null&&ie>=r.budget,{name:"budget-exhausted-check"});s.add(Re,{name:"budget-exhausted-check"}),s.addDisposer(Q.subscribe(()=>{})),s.addDisposer(G.subscribe(()=>{})),s.addDisposer(q.subscribe(()=>{})),s.addDisposer($.subscribe(()=>{})),s.addDisposer(te.subscribe(()=>{})),s.addDisposer(Re.subscribe(()=>{}));let Oe=A([Q,G,q,$,te],([ie,we,Fe,be,J])=>ie?{converged:!0,reason:"patience"}:we?{converged:!0,reason:"min-score"}:Fe?{converged:!0,reason:"min-delta"}:be?{converged:!0,reason:"max-evaluations"}:J?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});s.add(Oe,{name:"converged"}),s.addDisposer(Oe.subscribe(()=>{}));let Ce=-1,ye=pe([D,P,R],([ie,we,Fe])=>{let be=a.cache,J=ie,se=Fe,ve=we;if(be<=Ce)return;Ce=be;let{best:W,bestScore:de}=df(se,ve),Se=f.cache,Ee={n:be,candidates:se,scores:ve,feedback:J,best:W,bestScore:de,timestamp_ns:H()},ce=[...Se,Ee],Pe=g.cache+se.length,me="continue",ge,fr=r.budget!=null&&Pe>=r.budget,Sn=l.cache;if(fr)me="budget",ge="budget";else if(r.minScore!=null&&J.score>=r.minScore)me="converged",ge="min-score";else if(r.maxIterations!=null&&be>=r.maxIterations)me="converged",ge="max-iterations";else if(r.maxEvaluations!=null&&Pe>=r.maxEvaluations)me="converged",ge="max-evaluations";else if(r.minDelta!=null&&ce.length>=2){let _o=ce[ce.length-2].bestScore,zi=ce[ce.length-1].bestScore;Math.abs(zi-_o)<r.minDelta&&(me="converged",ge="min-delta")}else if(r.patience!=null&&ce.length>r.patience){let _o=ce.slice(-(r.patience+1)),zi=_o[0].bestScore;_o.slice(1).every(Mf=>Mf.bestScore<=zi)&&(me="converged",ge="patience")}me==="continue"&&Sn&&(me="paused"),X(()=>{m.emit(W),h.emit(J.score),f.emit(ce),g.emit(Pe),d.emit(J),w.publish({iteration:be,decision:me,reason:ge,timestamp_ns:H()}),me==="continue"?a.emit(be+1):p.emit(me==="converged"?"converged":me==="budget"?"budget":"paused")})},{name:"decide-bridge"});return s.add(ye,{name:"decide-bridge"}),s.addDisposer(ye.subscribe(()=>{})),Object.assign(s,{best:m,score:h,status:p,history:f,strategy:u,iteration:a,generate:b,evaluate:v,analyze:T,decide:w,setStrategy(ie){u.emit(ie)},pause(){l.emit(!0)},resume(){p.cache==="paused"&&X(()=>{l.emit(!1),p.emit("running"),a.emit(a.cache+1)})}})}function ib(t){let e=t.width??4;return{name:t.name??"blindVariation",seed(r){return[r]},analyze(r,o){let s=$u(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:d=>{i+=d}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(u)));let d=[];for(let c=0;c<e;c++)d.push(await t.teacher(u));return d}finally{if(t.tokens!=null&&i>0){let d=t.tokens.cache??0;t.tokens.emit(d+i)}}}}}function ab(t){return typeof t=="object"&&t!==null&&t.kind==="errorCritique"}function ub(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 Ro(t,e,n){if(typeof t=="function")return t;let r=t??e;return o=>n(r,o)}ee();ee();var Si={};ke(Si,{blindVariation:()=>db,errorCritique:()=>pb,refineLoop:()=>ju});Me();xe();ae();_e();ee();function ub(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 lf(t,e){if(t.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(t.length===1){let s=$u(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 d=u.candidateIndex;typeof d=="number"&&d>=0&&d<t.length&&(s[d].sum+=u.score,s[d].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 d=s[u].count>0?s[u].sum/s[u].count:Number.NEGATIVE_INFINITY;d>a&&(a=d,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 $u(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 ju(t,e,n,r){let o=r.name??"refine-loop",s=new Y(o,r.graph),i=ub(r.dataset)?r.dataset:M(r.dataset,{name:"dataset"});s.add(i,{name:"dataset"});let a=M(0,{name:"iteration"});s.add(a,{name:"iteration"});let u=M(n,{name:"strategy",equals:()=>!1});s.add(u,{name:"strategy"});let d=M(null,{name:"lastFeedback"});s.add(d,{name:"lastFeedback"});let c=M([],{name:"prevCandidates"});s.add(c,{name:"prevCandidates"});let l=M(!1,{name:"paused"});s.add(l,{name:"paused"});let p=M("running",{name:"status"});s.add(p,{name:"status"});let f=M([],{name:"history",equals:()=>!1});s.add(f,{name:"history"});let m=M(null,{name:"best"});s.add(m,{name:"best"});let h=M(Number.NEGATIVE_INFINITY,{name:"score"});s.add(h,{name:"score"});let g=M(0,{name:"budget-used"});s.add(g,{name:"budget-used"});let y=go("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,S=[];s.addDisposer(u.subscribe(ie=>{for(let we of ie)we[0]===E&&(k=we[1])})),s.addDisposer(d.subscribe(ie=>{for(let we of ie)we[0]===E&&(x=we[1])})),s.addDisposer(c.subscribe(ie=>{for(let we of ie)we[0]===E&&(S=we[1])}));let R=Te(a,ie=>{let we=k,Fe=ie===0||x==null;return z([],(be,J)=>{let se=!1;try{let ve=Fe?we.seed(t):we.generate(x,S);if(ve instanceof Promise)return ve.then(W=>{se||J.emit(W)},W=>{se||J.down([[A,W]])}),()=>{se=!0};J.emit(ve)}catch(ve){se=!0,J.down([[A,ve]])}},{describeKind:"producer"})},{name:"candidates"});s.add(R,{name:"candidates"});let N=pe([R],(ie,we,Fe)=>{let be=Fe.terminalDeps[0];be!==void 0&&be!==!0&&p.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});s.add(N,{name:"error-watcher"}),s.addDisposer(N.subscribe(()=>{}));let _=C([R,a],([ie,we])=>({iteration:we,candidates:ie,timestamp_ns:H()}),{name:"generate-event"});s.add(_,{name:"generate-event"}),s.addDisposer(_.subscribe(()=>{}));let I=pe([_],([ie])=>{b.publish(ie)},{name:"generate-publish"});s.add(I,{name:"generate-publish"}),s.addDisposer(I.subscribe(()=>{}));let O=pe([R],([ie])=>{c.emit(ie)},{name:"generate-mirror"});s.add(O,{name:"generate-mirror"}),s.addDisposer(O.subscribe(()=>{}));let P=e(R,i);s.add(P,{name:"scores"});let B=C([P,R,a],([ie,we,Fe])=>({iteration:Fe,candidates:we,scores:ie,timestamp_ns:H()}),{name:"evaluate-event"});s.add(B,{name:"evaluate-event"}),s.addDisposer(B.subscribe(()=>{}));let j=pe([B],([ie])=>{v.publish(ie)},{name:"evaluate-publish"});s.add(j,{name:"evaluate-publish"}),s.addDisposer(j.subscribe(()=>{}));let D=C([P,R],([ie,we])=>k.analyze(ie,we),{name:"feedback"});s.add(D,{name:"feedback"});let Z=C([D,R,a],([ie,we,Fe])=>({iteration:Fe,candidates:we,feedback:ie,timestamp_ns:H()}),{name:"analyze-event"});s.add(Z,{name:"analyze-event"}),s.addDisposer(Z.subscribe(()=>{}));let F=pe([Z],([ie])=>{T.publish(ie)},{name:"analyze-publish"});s.add(F,{name:"analyze-publish"}),s.addDisposer(F.subscribe(()=>{}));let Q=C([f],([ie])=>{let we=ie;if(r.patience==null||we.length<=r.patience)return!1;let Fe=we.slice(-(r.patience+1)),be=Fe[0].bestScore;return Fe.slice(1).every(J=>J.bestScore<=be)},{name:"patience-check"});s.add(Q,{name:"patience-check"});let G=C([h],([ie])=>r.minScore!=null&&ie>=r.minScore,{name:"min-score-check"});s.add(G,{name:"min-score-check"});let q=C([f],([ie])=>{let we=ie;if(r.minDelta==null||we.length<2)return!1;let Fe=we[we.length-2].bestScore,be=we[we.length-1].bestScore;return Math.abs(be-Fe)<r.minDelta},{name:"min-delta-check"});s.add(q,{name:"min-delta-check"});let $=C([g],([ie])=>r.maxEvaluations!=null&&ie>=r.maxEvaluations,{name:"max-evaluations-check"});s.add($,{name:"max-evaluations-check"});let te=C([a],([ie])=>r.maxIterations!=null&&ie>=r.maxIterations,{name:"max-iterations-check"});s.add(te,{name:"max-iterations-check"});let Re=C([g],([ie])=>r.budget!=null&&ie>=r.budget,{name:"budget-exhausted-check"});s.add(Re,{name:"budget-exhausted-check"}),s.addDisposer(Q.subscribe(()=>{})),s.addDisposer(G.subscribe(()=>{})),s.addDisposer(q.subscribe(()=>{})),s.addDisposer($.subscribe(()=>{})),s.addDisposer(te.subscribe(()=>{})),s.addDisposer(Re.subscribe(()=>{}));let Oe=C([Q,G,q,$,te],([ie,we,Fe,be,J])=>ie?{converged:!0,reason:"patience"}:we?{converged:!0,reason:"min-score"}:Fe?{converged:!0,reason:"min-delta"}:be?{converged:!0,reason:"max-evaluations"}:J?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});s.add(Oe,{name:"converged"}),s.addDisposer(Oe.subscribe(()=>{}));let Ae=-1,ye=pe([D,P,R],([ie,we,Fe])=>{let be=a.cache,J=ie,se=Fe,ve=we;if(be<=Ae)return;Ae=be;let{best:W,bestScore:ce}=lf(se,ve),Se=f.cache,Ee={n:be,candidates:se,scores:ve,feedback:J,best:W,bestScore:ce,timestamp_ns:H()},le=[...Se,Ee],Pe=g.cache+se.length,me="continue",ge,fr=r.budget!=null&&Pe>=r.budget,Sn=l.cache;if(fr)me="budget",ge="budget";else if(r.minScore!=null&&J.score>=r.minScore)me="converged",ge="min-score";else if(r.maxIterations!=null&&be>=r.maxIterations)me="converged",ge="max-iterations";else if(r.maxEvaluations!=null&&Pe>=r.maxEvaluations)me="converged",ge="max-evaluations";else if(r.minDelta!=null&&le.length>=2){let _o=le[le.length-2].bestScore,zi=le[le.length-1].bestScore;Math.abs(zi-_o)<r.minDelta&&(me="converged",ge="min-delta")}else if(r.patience!=null&&le.length>r.patience){let _o=le.slice(-(r.patience+1)),zi=_o[0].bestScore;_o.slice(1).every(Af=>Af.bestScore<=zi)&&(me="converged",ge="patience")}me==="continue"&&Sn&&(me="paused"),X(()=>{m.emit(W),h.emit(J.score),f.emit(le),g.emit(Pe),d.emit(J),w.publish({iteration:be,decision:me,reason:ge,timestamp_ns:H()}),me==="continue"?a.emit(be+1):p.emit(me==="converged"?"converged":me==="budget"?"budget":"paused")})},{name:"decide-bridge"});return s.add(ye,{name:"decide-bridge"}),s.addDisposer(ye.subscribe(()=>{})),Object.assign(s,{best:m,score:h,status:p,history:f,strategy:u,iteration:a,generate:b,evaluate:v,analyze:T,decide:w,setStrategy(ie){u.emit(ie)},pause(){l.emit(!0)},resume(){p.cache==="paused"&&X(()=>{l.emit(!1),p.emit("running"),a.emit(a.cache+1)})}})}function db(t){let e=t.width??4;return{name:t.name??"blindVariation",seed(r){return[r]},analyze(r,o){let s=$u(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:d=>{i+=d}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(u)));let d=[];for(let c=0;c<e;c++)d.push(await t.teacher(u));return d}finally{if(t.tokens!=null&&i>0){let d=t.tokens.cache??0;t.tokens.emit(d+i)}}}}}function cb(t){return typeof t=="object"&&t!==null&&t.kind==="errorCritique"}function lb(t,e){return t.length===0?`No task scored below the batch mean (${e.score.toFixed(3)}). Reinforce the current direction.`:`Failures below threshold:
218
218
  ${t.map(r=>{let o=r.error!=null?` | error: ${r.error}`:"";return`- ${r.taskId} (score=${r.score.toFixed(3)})${o}`}).join(`
219
- `)}`}function db(t){let e=t.width??4,n=t.name??"errorCritique",r=t.maxFailureSamples??5,o=t.formatCritique??ub;return{name:n,seed(s){return[s]},analyze(s,i){let a=$u(s),u=typeof t.failureThreshold=="function"?t.failureThreshold(s):t.failureThreshold,d=u===void 0&&!Number.isFinite(a),c=u??a,l=d?[...s].sort((v,T)=>v.score-T.score):s.filter(v=>v.score<c).slice().sort((v,T)=>v.score-T.score),p=l.slice(0,r),{best:f,bestScore:m}=df(i,s),h={summary:"",score:a,weakTasks:p.map(v=>v.taskId)},g=o(p,h),y={kind:"errorCritique",best:f,failures:p,critiqueText:g},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=ab(s.critique)?s.critique:void 0,u=a!==void 0?a.best:i[i.length-1],d=a?.critiqueText??s.summary,c=a?.failures??[],l=0,f={prior:u,critique:d,failures:c,reportCost:m=>{l+=m}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(f)));let m=[];for(let h=0;h<e;h++)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 cb(t){let{best:e,score:n,status:r}=t,o=Number.isFinite(n)?n.toFixed(3):String(n),s=e??void 0;return r==="converged"?{outcome:"success",detail:`refineLoop converged at score ${o}`,artifact:s}:r==="budget"?{outcome:"partial",detail:`refineLoop hit budget at score ${o}`,artifact:s}:{outcome:"failure",detail:`refineLoop errored (status=${r})`,artifact:s}}function Bu(t){let e=t.name??"refine-executor",n=t.toOutput??cb;return r=>{let o=Xe(r,i=>i!=null,{name:`${e}/gate-in`}),s=Te(o,i=>{let a=ju(t.seedFrom(i),t.evaluator,t.strategy,{...t.refine,dataset:t.datasetFor(i),name:`${e}/inner`});return A([a.status,a.best,a.score],([u,d,c])=>{let l=u;return l!=="converged"&&l!=="budget"&&l!=="errored"?null:n({best:d,score:c,status:l})},{name:`${e}/output`})},{name:e});return Xe(s,i=>i!=null,{name:`${e}/gate-out`})}}function lb(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 pb(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 fb(t){return t.artifact??null}function cf(t){let e=t.name??"eval-verifier",n=t.threshold??.5,r=t.toOutput??pb,o=t.extractArtifact??fb;return s=>{let i=Xe(s,u=>u!=null&&u[0]!=null&&u[1]!=null,{name:`${e}/gate-in`}),a=Te(i,u=>{let[d,c]=u,l=o(d,c);if(l==null)return M(r({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:n,missingArtifact:!0}));let p=M([l],{name:`${e}/candidates`}),f=M(t.datasetFor(c),{name:`${e}/dataset`}),m=t.evaluator(p,f);return A([m],([h])=>{let g=h;if(g==null)return null;let y=lb(g),b=g.filter(v=>v.score>=n).length;return r({scores:g,meanScore:y,passCount:b,total:g.length,threshold:n})},{name:`${e}/output`})},{name:e});return Xe(a,u=>u!=null,{name:`${e}/gate-out`})}}function mb(t){let e=t.name??"harness-pair",n=Bu({name:`${e}-exec`,seedFrom:t.seedFrom,evaluator:t.evaluator,strategy:t.strategy,datasetFor:t.datasetFor,refine:t.refine}),r=cf({name:`${e}-verify`,evaluator:t.evaluator,datasetFor:t.datasetFor,threshold:t.threshold});return{executor:n,verifier:r}}xe();_e();ee();var Oi={};ke(Oi,{JobFlowGraph:()=>_i,JobQueueGraph:()=>Ni,jobEventKeyOf:()=>yb,jobFlow:()=>bb,jobQueue:()=>Mi});xe();_e();he();var gb=256,hb=1024;function lf(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Ei(t,e){return ze("job_queue",t,e)}var yb=t=>t.action,Ni=class extends Y{_pending;_jobs;_seqCursor;pending;jobs;depth;events;audit;constructor(e,n={}){super(e,n.graph),this._pending=Ds([],{name:"pending"}),this._jobs=Ze({name:"jobs"}),this.pending=this._pending.items,this.jobs=this._jobs.entries,this.add(this.pending,{name:"pending"}),this.add(this.jobs,{name:"jobs"}),this.depth=A([this.pending],([r])=>r.length,{name:"depth",describeKind:"derived",meta:Ei("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(re(this.depth)),this.events=kt({name:"events",retainedLimit:1024,graph:this}),this.audit=this.events,this._seqCursor=bs(this,"seq",0)}_bumpSeq(){let n=(this._seqCursor.cache??0)+1;return this._seqCursor.emit(n),n}attachEventStorage(e){return this.events.attachStorage(e)}enqueue(e,n={}){let r=this._bumpSeq(),o=n.id??`${this.name}-${r}`;if(this._jobs.get(o)!==void 0)throw new Error(`jobQueue("${this.name}"): duplicate job id "${o}"`);let s={id:o,payload:e,attempts:0,metadata:Object.freeze({...n.metadata??{}}),state:"queued"};return this._jobs.set(o,s),this._pending.append(o),this.events.append({action:"enqueue",id:o,payload:e,t_ns:oe(),seq:r}),o}claim(e=1){let n=lf(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),this.events.append({action:"claim",id:s,attempts:a.attempts,t_ns:oe(),seq:this._bumpSeq()})}return r}ack(e){let n=this._jobs.get(e);return!n||n.state!=="inflight"?!1:(this._jobs.delete(e),this.events.append({action:"ack",id:e,attempts:n.attempts,t_ns:oe(),seq:this._bumpSeq()}),!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),this.events.append({action:"nack",id:e,attempts:r.attempts,t_ns:oe(),seq:this._bumpSeq()}),!0):(this._jobs.delete(e),this.events.append({action:"nack",id:e,attempts:r.attempts,t_ns:oe(),seq:this._bumpSeq()}),!0)}removeById(e){let n=this._jobs.get(e);if(!n)return!1;if(n.state==="queued"){let o=this.pending.cache.indexOf(e);o>=0&&this._pending.pop(o)}return this._jobs.delete(e),this.events.append({action:"remove",id:e,attempts:n.attempts,t_ns:oe(),seq:this._bumpSeq()}),!0}consumeFrom(e,n){return e.subscribe(r=>{for(let o of r){if(o[0]!==E)continue;let s=o[1];this.enqueue(s,n?{metadata:n.metadata}:void 0)}})}},_i=class extends Y{_stageNames;_stageWorkFns;_queues=new Map;_completed;completed;completedCount;constructor(e,n={}){super(e,n.graph);let r=n.stages??["incoming","processing","done"],o=[],s=new Map;for(let u of r){let d=typeof u=="string"?u.trim():u.name.trim();typeof u!="string"&&u.work&&s.set(d,u.work),o.push(d)}if(o.length<2)throw new Error(`jobFlow("${e}"): requires at least 2 stages`);if(new Set(o).size!==o.length)throw new Error(`jobFlow("${e}"): stage names must be unique`);this._stageNames=Object.freeze([...o]),this._stageWorkFns=s;for(let u of this._stageNames){let d=Mi(`${e}-${u}`);this._queues.set(u,d),this.mount(u,d)}this._completed=Ve([],{name:"completed",maxSize:hb}),this.completed=this._completed.entries,this.add(this.completed,{name:"completed"}),this.completedCount=A([this.completed],([u])=>u.length,{name:"completedCount",describeKind:"derived",meta:Ei("job_flow_completed_count"),initial:0}),this.add(this.completedCount,{name:"completedCount"}),this.addDisposer(re(this.completedCount));let a=Math.max(1,lf(n.maxPerPump??gb,"job flow maxPerPump"));for(let u=0;u<this._stageNames.length;u+=1){let d=this._stageNames[u],c=this.queue(d),l=u+1<this._stageNames.length?this.queue(this._stageNames[u+1]):null,p=this._stageWorkFns.get(d),f=l===null;if(p){let m=z([c.pending],()=>{let h=0;for(;h<a;){let g=c.claim(1);if(g.length===0)break;let y=g[0];if(!y)break;let v=[...y.metadata.job_flow_path??[],d],T;try{T=p(y)}catch{c.nack(y.id,{requeue:!1}),h+=1;continue}let w=U(T),x=!1,k;k=w.subscribe(S=>{if(!x){for(let R of S)if(R[0]===E){x=!0,k?k():Promise.resolve().then(()=>k?.());let N=R[1],_={...y.metadata,job_flow_path:v};if(f){let I={...y,payload:N,metadata:Object.freeze(_)};X(()=>{c.ack(y.id),this._completed.append(I)})}else X(()=>{c.ack(y.id),l.enqueue(N,{metadata:_})});return}else if(R[0]===C){x=!0,k?k():Promise.resolve().then(()=>k?.()),c.nack(y.id,{requeue:!1});return}}}),h+=1}},{name:`pump_${d}`,describeKind:"effect",meta:Ei("job_flow_pump",{stage:d,has_work:!0})});this.add(m,{name:`pump_${d}`}),this.addDisposer(re(m))}else{let m=z([c.pending],()=>{let h=0;for(;h<a;){let g=c.claim(1);if(g.length===0)break;let y=g[0];if(!y)break;let v=[...y.metadata.job_flow_path??[],d],T={...y.metadata,job_flow_path:v};if(f){let w={...y,metadata:Object.freeze(T)};X(()=>{c.ack(y.id),this._completed.append(w)})}else X(()=>{c.ack(y.id),l.enqueue(y.payload,{metadata:T})});h+=1}},{name:`pump_${d}`,describeKind:"effect",meta:Ei("job_flow_pump",{stage:d,has_work:!1})});this.add(m,{name:`pump_${d}`}),this.addDisposer(re(m))}}}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 Mi(t,e){return new Ni(t,e)}function bb(t,e){return new _i(t,e)}xe();ee();function Vu(){let t=Ze({name:"strategy-entries"}),e=A([t.entries],([i])=>{let a=i;return new Map(a)},{name:"strategy-model",equals:(i,a)=>{let u=i,d=a;if(u.size!==d.size)return!1;for(let[c,l]of u){let p=d.get(c);if(!p||l.attempts!==p.attempts||l.successes!==p.successes)return!1}return!0}});function n(i,a,u){let d=lr(i,a),c=t.get(d),l=(c?.attempts??0)+1,p=(c?.successes??0)+(u?1:0);t.set(d,{rootCause:i,intervention:a,attempts:l,successes:p,successRate:p/l})}function r(i,a){return t.get(lr(i,a))}let o=e.subscribe(()=>{});function s(){o()}return{node:e,record:n,lookup:r,dispose:s}}function vb(t,e,n,r,o){let s={...dr,...o?.severityWeights},i=o?.decayRate??cr,a=o?.effectivenessThreshold??.7,u=o?.effectivenessBoost??15,d=[t,e,n];return r&&d.push(r),A(d,c=>{let l=c[0],p=c[1],f=c[2],m=r?c[3]:0,h=s[l.severity??"medium"],g=(H()-f)/1e9,y=xn(h,g,i,0),b=lr(l.rootCause,l.intervention),v=p.get(b);return v&&v.successRate>=a&&(y+=u),y+=m*20,y},{name:"priority-score"})}var pf="intake",Tb="triage-output",ff="retry",mf="verify-results",gf="__unrouted";function hf(t,e){let n=Ro(e,Gu,(r,o)=>r.replace("{{item}}",JSON.stringify(o)));return r=>wn(t,[r],n,{name:"execute",format:"json"})}function yf(t,e){let n=Ro(e,Fu,(r,o)=>{let[s,i]=o;return r.replace("{{execution}}",JSON.stringify(s)).replace("{{item}}",JSON.stringify(i))});return r=>wn(t,[r],o=>o==null?"":n(o),{name:"verify",format:"json"})}var Ci=class extends Y{queues;jobs;gates;queueTopics;strategy;totalRetries;totalReingestions;priorityScores;constructor(e,n,r,o,s,i,a,u,d){super(e),this.queues=n,this.queueTopics=r,this.jobs=o,this.gates=s,this.strategy=i,this.totalRetries=a,this.totalReingestions=u,this.priorityScores=d}get intake(){return this.queues.topic(pf)}get verifyResults(){return this.queues.topic(mf)}get retry(){return this.queues.topic(ff)}get unrouted(){return this.queues.topic(gf)}stageNodes(){let e=this.queues,n=i=>e.has(i)?`queues::${i}::latest`:null,r=i=>i==null?[]:[i],o=it.flatMap(i=>r(n(i))),s=[];for(let[i]of this.gates)s.push(`gates::${i}/gate`);return[{label:"INTAKE",paths:r(n("intake"))},{label:"TRIAGE",paths:["triage"]},{label:"QUEUE",paths:o},{label:"GATE",paths:s},{label:"EXECUTE",paths:["execute"]},{label:"VERIFY",paths:r(n("verify-results"))},{label:"REFLECT",paths:["reflect"]},{label:"STRATEGY",paths:["strategy"]}]}};function wb(t,e){let n=e.adapter,r=e.maxRetries??2,o=e.retainedLimit??1e3,s=e.errorClassifier??Ri,i=new Map;for(let J of it)i.set(J,{...xi[J],...e.queues?.[J]});let a=go(`${t}/queues`,{defaultTopicOptions:{retainedLimit:o}}),u=a.topic(pf),d=a.topic(Tb),c=a.topic(ff),l=a.topic(mf),p=new Map;for(let J of it)p.set(J,a.topic(J));let f=a.topic(gf),m=Vu(),h=Pt(u.latest,m.node),g=Ro(e.triagePrompt,Du,(J,se)=>{let[ve,W]=se;return J.replace("{{strategy}}",JSON.stringify(Array.from(W.entries()))).replace("{{item}}",JSON.stringify(ve))}),y=wn(n,[h],J=>{let se=J;return!se||!se[0]?"":g(se)},{name:"triage",format:"json"}),b=Pt(y,h),T=pe([b],([J])=>{if(J==null)return;let[se,ve]=J;if(!se?.route)return;let W=ve?.[0],de={...se,...W};d.publish(de)}).subscribe(()=>{}),w=new Set(it);for(let J of it)ri(`bridge/${J}`,d,p.get(J),{map:se=>se.route===J?se:void 0});ri("bridge/__unrouted",d,f,{map:J=>w.has(J.route)?void 0:J});let x=new Map,k=new Map;for(let J of it)x.set(J,Mi(`jobs/${J}`));let S=[];for(let J of it){let se=p.get(J),ve=x.get(J),W=new WeakSet,de=pe([se.events],([Se])=>{let Ee=Se??[];for(let ce of Ee){if(W.has(ce))continue;W.add(ce);let Pe=ve.enqueue(ce);k.set(qr(ce),{route:J,id:Pe})}},{name:`jobs/${J}-mirror`});S.push(de.subscribe(()=>{}))}function R(J){let se=qr(J),ve=k.get(se);ve&&(x.get(ve.route)?.removeById(ve.id),k.delete(se))}let N=ir("gates"),_=new Map;for(let J of it){let se=i.get(J);if(!se.gated)continue;let ve=p.get(J),W=N.gate(`${J}/gate`,ve.latest,{maxPending:se.maxPending,startOpen:se.startOpen});_.set(J,W)}let I=[];for(let J of it)i.get(J).gated&&_.has(J)?I.push(_.get(J).node):I.push(p.get(J).latest);I.push(c.latest);let O=xt(...I),B=(e.executor??hf(n,e.executePrompt))(O),j=Pt(B,O),Z=(e.verifier??yf(n,e.verifyPrompt))(j),F=Pt(Z,j),Q=e.maxReingestions??1,G=Math.min(e.maxTotalRetries??r*10,100),q=Math.min(e.maxTotalReingestions??Q*10,100),$=M(0),te=M(0);function Re(J,se,ve){let W={item:ve,outcome:se?.outcome??"failure",detail:se?.detail??"unknown",artifact:se?.artifact};return{item:ve,execution:W,verified:J.verified,findings:J.findings??[],errorClass:J.errorClass}}function Oe(J,se){m.record(se.rootCause,se.intervention,!0),l.publish(J),R(se)}function Ce(J,se){let ve=qr(se),W=se.$retries??0,de={...se,$retries:W+1,summary:`[RETRY ${W+1}/${r}] ${ve} \u2014 Previous attempt failed: ${J.findings.join("; ")}`,relatedTo:[ve]};c.publish(de)}function ye(J,se){m.record(se.rootCause,se.intervention,!1),l.publish(J),R(se);let ve=qr(se),W=se.$reingestions??0;W<Q&&Kr(te,q)&&u.publish({source:se.source,summary:`Verification failed for: ${ve}`,evidence:J.findings.join(`
220
- `),affectsAreas:se.affectsAreas,affectsEvalTasks:se.affectsEvalTasks,severity:se.severity??"high",relatedTo:[ve],$reingestions:W+1})}let Ge=z([F],(J,se)=>{let ve=J[0];if(ve==null||ve.length===0)return;let W=ve[ve.length-1];if(W==null)return;let[de,Se]=W,[Ee,ce]=Se??[null,null];if(!de||!ce)return;if(Ee==null){ye({item:ce,execution:{item:ce,outcome:"failure",detail:"executor returned null"},verified:!1,findings:["executor returned null"],errorClass:"structural"},ce);return}let Pe=Re(de,Ee,ce);if(Pe.verified){Oe(Pe,ce);return}let me=Pe.errorClass??s({item:ce,outcome:Ee.outcome,detail:Pe.findings.join("; ")}),ge=ce.$retries??0;me==="self-correctable"&&ge<r&&Kr($,G)?Ce(Pe,ce):ye(Pe,ce)}),ie=Ge.subscribe(()=>{}),we=A([Ge],()=>null,{name:"reflect",equals:()=>!1}),Fe;e.priority&&(Fe=kb(p,m,e));let be=new Ci(t,a,p,x,_,m,$,te,Fe);be.addDisposer(T),be.addDisposer(ie),be.addDisposer(m.dispose);for(let J of S)be.addDisposer(J);if(be.add(y,{name:"triage"}),be.add(O,{name:"execute-input"}),be.add(B,{name:"execute"}),be.add(j,{name:"execute-context"}),be.add(Z,{name:"verify"}),be.add(F,{name:"verify-context"}),be.add(Ge,{name:"verify-dispatch"}),be.add(we,{name:"reflect"}),be.add(m.node,{name:"strategy"}),be.addDisposer(we.subscribe(()=>{})),Fe)for(let[J,se]of Fe)be.add(se,{name:`priority/${J}`}),be.addDisposer(se.subscribe(()=>{}));be.mount("queues",a),be.mount("gates",N);for(let[J,se]of x)be.mount(`jobs/${J}`,se);return be}function kb(t,e,n){if(!n.lastInteractionNs)throw new Error("harnessLoop: `opts.priority` requires `opts.lastInteractionNs` \u2014 pass a Node<number> (e.g. `fromTimer(60_000)` or a `state(monotonicNs())` you bump on human interaction). Priority scores only decay when this node settles; an internal default would freeze age at construction time.");let r=n.lastInteractionNs,o=n.priority??{},s={...dr,...o.severityWeights},i=o.decayRate??cr,a=o.effectivenessThreshold??.7,u=o.effectivenessBoost??15,d=new Map;for(let[c,l]of t){let p=A([l.latest,e.node,r],f=>{let m=f[0];if(m==null)return 0;let h=s[m.severity??"medium"]??40,g=(H()-f[2])/1e9,y=h*Math.exp(-i*Math.max(0,g)),b=`${m.rootCause}\u2192${m.intervention}`,T=f[1]?.get(b);return T&&T.successRate>=a&&(y+=u),y},{name:`priority/${c}`});d.set(c,p)}return d}function xb(t,e){let n=pn(t,e),r={};for(let o of it){let s=t.queues.has(o)?t.queues.topic(o):null;r[o]=s?.retained().length??0}return{...n,queueDepths:r,strategyEntries:t.strategy.node.cache?.size??0,totalRetries:t.totalRetries.cache??0,totalReingestions:t.totalReingestions.cache??0}}xe();function Rb(t){let e={};for(let{label:n,paths:r}of t.stageNodes())for(let o of r)e[o]=n;return e}function Sb(t,e){let n=e?.logger===null?null:e?.logger??console.log,r=e?.detail??"summary",o=H(),s=[],i=[],a=Rb(t);function u(){return(H()-o)/1e9}function d(c,l,p){let f={elapsed:u(),stage:c,type:l};r!=="summary"&&(f.summary=Eb(p)),r==="full"&&(f.data=p),i.push(f)}for(let[c,l]of Object.entries(a))try{let p=t.observe(c,{format:"stage-log",stageLabels:a,logger:n?f=>n(f):()=>{},includeTypes:["data","error","complete"]});p.onEvent(f=>{f.type==="data"?d(l,"data",f.data):f.type==="error"?d(l,"error",f.data):f.type==="complete"&&d(l,"complete",void 0)}),s.push(p)}catch(p){let f=p instanceof Error?p.message:String(p);d(l,"error",`observe-unavailable: ${c} \u2014 ${f}`),n&&n(`[${u().toFixed(3)}s] ${l.padEnd(9)} \u2717 observe-unavailable: ${f}`)}return{get events(){return i},dispose(){for(let c of s)c.dispose();s.length=0}}}function Eb(t){if(t==null)return"null";if(typeof t=="string")return bf(t,80);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return bf(e,120)}catch{return String(t)}}function bf(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}var Ii={};ke(Ii,{LensGraph:()=>Li,graphLens:()=>Cb,watchTopologyTree:()=>At});xe();ee();function vf(t){return ze("lens",t)}function Nb(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,d=2,c=new Map;for(let h of e)c.set(h,a);let l=!1,p=new Map,f=h=>{let g=c.get(h)??a;if(g===u)return l=!0,0;if(g===d)return p.get(h)??0;c.set(h,u);let y=0,b=r.get(h);if(b!=null)for(let v of b){let T=f(v);T+1>y&&(y=T+1)}return c.set(h,d),p.set(h,y),y},m=0;for(let h of o){let g=f(h);g>m&&(m=g)}for(let h of e)c.get(h)===a&&f(h);return{nodeCount:e.length,edgeCount:i,subgraphCount:t.subgraphs.length,sources:o,sinks:s,depth:m,hasCycles:l}}function _b(t){let e=[];for(let[n,r]of Object.entries(t.nodes)){if(r.status!=="errored")continue;let o={path:n,status:"errored"},s=fn(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 Mb(t,e){return t.nodeCount===e.nodeCount&&t.edgeCount===e.edgeCount&&t.subgraphCount===e.subgraphCount&&t.depth===e.depth&&t.hasCycles===e.hasCycles&&Tf(t.sources,e.sources)&&Tf(t.sinks,e.sinks)}function Ob(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 Tf(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 Y{stats;health;flow;_target;constructor(e,n={}){super(n.name??`${e.name}_lens`,n.graph),this._target=e;let r=0,o=0,s=M(0,{name:"stats_tick"}),i=M(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=Ze(a),this.add(this.flow.entries,{name:"flow"});let u=n.pathFilter,d=At(e,(p,f,m)=>{if(r+=1,s.emit(r),o+=1,i.emit(o),p.kind==="removed")if(p.nodeKind==="node"){let h=`${m}${p.name}`;this.flow.delete(h)}else{let h=`${m}${p.name}::`,g=[];for(let y of p.audit.nodes){let b=y===""?`${m}${p.name}`:`${h}${y}`;g.push(b)}g.length>0&&this.flow.deleteMany(g)}});this.addDisposer(d);let c=e.observe({timeline:!0,structured:!0}),l=c.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 h=this.flow.get(m),g=h!=null?h.count+1:1;this.flow.set(m,{path:m,count:g,lastUpdate_ns:H()})}});this.addDisposer(()=>{l(),c.dispose()}),this.stats=A([s],()=>Nb(e.describe({detail:"minimal"})),{name:"stats",describeKind:"derived",equals:Mb,meta:vf("stats")}),this.add(this.stats,{name:"stats"}),this.addDisposer(re(this.stats)),this.health=A([i],()=>_b(e.describe({detail:"standard"})),{name:"health",describeKind:"derived",equals:Ob,meta:vf("health")}),this.add(this.health,{name:"health"}),this.addDisposer(re(this.health))}why(e,n,r){let o=Ou(this._target,e,n,r);return this.addDisposer(o.dispose),o}get target(){return this._target}};function Cb(t,e){return new Li(t,e)}var Pi={};ke(Pi,{processInstanceKeyOf:()=>Ab,processManager:()=>Ib});xe();ae();he();var Ab=t=>t.correlationId;function wf(t){if(t==null)return Promise.resolve(void 0);let e=U(t);return new Promise((n,r)=>{let o=!1,s,i=()=>{s&&s()};s=e.subscribe(a=>{if(!o)for(let u of a){if(u[0]===E){o=!0,Promise.resolve().then(i),n(u[1]);return}if(u[0]===C){o=!0,Promise.resolve().then(i),r(u[1]);return}if(u[0]===L){o=!0,Promise.resolve().then(i),n(void 0);return}}})})}async function Lb(t,e,n,r,o){let s;for(let i=0;i<=r;i++){if(i>0){let a=o[Math.min(i-1,o.length-1)]??0;a>0&&await new Promise(u=>setTimeout(u,a))}try{return await wf(t(e,n))}catch(a){s=a}}return{kind:"fail",error:s}}function Ib(t,e,n){let r=n.retryMax??0,o=n.backoffMs??[0],s=1024,i=new Map,a=new Set,u=new Map,d=kt({name:`${e}_process_instances`,retainedLimit:s,graph:t}),c=0;function l(){return++c}function p(R,N,_){f(R,N,_,void 0)}function f(R,N,_,I){let O=oe(),P={correlationId:R,state:N,status:_,startedAt:u.get(R)??O,updatedAt:O,t_ns:O,seq:l(),...n.handlerVersion!==void 0?{handlerVersion:n.handlerVersion}:{},...I!==void 0?{reason:I}:{}};d.append(P)}let m=`_process_${e}_started`;t.event(m),n.persistence?.eventStorage&&t.attachEventStorage(n.persistence.eventStorage);async function h(R,N,_,I){if(a.delete(R),i.delete(R),u.delete(R),n.compensate)try{await wf(n.compensate(N,_)),f(R,N,"compensated",I)}catch{p(R,N,"failed")}else p(R,N,"failed")}async function g(R,N){if(a.has(R)){if(N.kind==="fail"){let _=i.get(R)??n.initial;await h(R,_,N.error);return}if(N.kind==="continue"){if(i.set(R,N.state),N.emit)for(let _ of N.emit)try{t._appendEvent(_.type,_.payload,{correlationId:R,aggregateId:R})}catch{}if(p(R,N.state,"running"),n.isTerminal?.(N.state)){a.delete(R),i.delete(R),u.delete(R),p(R,N.state,"terminated");return}if(N.schedule){let{afterMs:_,eventType:I}=N.schedule,O,P=st(_),B=j=>{for(let D of j)if(D[0]===E){if(O?O():queueMicrotask(()=>O?.()),!a.has(R))return;let Z=i.get(R);if(Z===void 0)return;let F=n.steps[I];if(!F)return;let Q={type:I,payload:null,timestampNs:oe(),seq:Number.NaN,correlationId:R,aggregateId:R};b(R,F,Z,Q)}};O=P.subscribe(B)}return}if(N.kind==="terminate"){if(i.set(R,N.state),N.emit)for(let _ of N.emit)try{t._appendEvent(_.type,_.payload,{correlationId:R,aggregateId:R})}catch{}a.delete(R),i.delete(R),u.delete(R),p(R,N.state,"terminated")}}}let y=new Map;function b(R,N,_,I){let P=(y.get(R)??Promise.resolve()).then(async()=>{let B=i.get(R);if(B===void 0||!a.has(R))return;let j;try{j=await Lb(N,B,I,r,o)}catch(D){await h(R,i.get(R)??n.initial,D);return}await g(R,j)});y.set(R,P),P.finally(()=>{y.get(R)===P&&y.delete(R)})}let v=!1,T=[];for(let R of n.watching){let N=t.event(R),_=0;_=(N.cache??[]).length;let O=N.subscribe(P=>{for(let B of P){if(B[0]!==E)continue;let j=B[1];if(j.length<=_)continue;let D=j.slice(_);_=j.length;for(let Z of D){let F=Z.correlationId;if(F===void 0||!a.has(F))continue;let Q=n.steps[R];if(!Q)continue;let G=i.get(F);G!==void 0&&b(F,Q,G,Z)}}});T.push(O)}function w(R,N){if(v||a.has(R))return;let _=oe();u.set(R,_),i.set(R,n.initial),a.add(R);try{t._appendEvent(m,N??null,{correlationId:R,aggregateId:R})}catch{}p(R,n.initial,"running")}function x(R,N){if(v||!a.has(R))return;let _=i.get(R)??n.initial;h(R,_,new Error(`cancelled: ${N??"no reason given"}`),N)}function k(R){return i.get(R)}function S(){if(!v){v=!0;for(let R of T)try{R()}catch{}T.length=0}}return{instances:d,audit:d,start:w,cancel:x,getState:k,dispose:S}}var Di={};ke(Di,{CanvasMeasureAdapter:()=>Wu,CliMeasureAdapter:()=>Ku,ImageSizeAdapter:()=>Ju,NodeCanvasMeasureAdapter:()=>zu,PrecomputedAdapter:()=>Hu,SvgBoundsAdapter:()=>Uu,analyzeAndMeasure:()=>Ft,carveTextLineSlots:()=>Iu,circleIntervalForBand:()=>Ef,computeBlockFlow:()=>Rf,computeCharPositions:()=>bi,computeFlowLines:()=>_f,computeLineBreaks:()=>Rn,computeTotalHeight:()=>Sf,layoutNextLine:()=>Lu,measureBlock:()=>kf,measureBlocks:()=>xf,reactiveBlockLayout:()=>Pb,reactiveFlowLayout:()=>Gb,reactiveLayout:()=>Fy,rectIntervalForBand:()=>Nf});var Ku=class{cellPx;constructor(e){this.cellPx=e?.cellPx??8}measureSegment(e,n){return{width:Jn(e)*this.cellPx}}},qu=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 qu(`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}}},Wu=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=""}},zu=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=""}},Uu=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")}},Ju=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}}};xe();_e();ee();function kf(t,e,n,r,o,s,i){switch(t.type){case"text":{let a=t.font??o,u=t.lineHeight??s,d=Ft(t.text,a,n.text,r),c=Rn(d,e,n.text,a,r),l=bi(c,d,u),p=c.lineCount*u,f=0;for(let m of c.lines)m.width>f&&(f=m.width);return{index:i,type:"text",width:Math.min(f,e),height:p,textSegments:d,textLineBreaks:c,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 d=n.image.measureImage(t.src);a=d.width,u=d.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 d=n.svg.measureSvg(t.content);a=d.width,u=d.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 xf(t,e,n,r,o,s){return t.map((i,a)=>kf(i,e,n,r,o,s,a))}function Rf(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 Sf(t){if(t.length===0)return 0;let e=t[t.length-1];return e.y+e.height}function Pb(t){let{adapters:e,name:n="reactive-block-layout",defaultFont:r="16px sans-serif",defaultLineHeight:o=20}=t,s=new Y(n),i=new Map,a=M(t.blocks??[],{name:"blocks"}),u=M(Math.max(0,t.maxWidth??800),{name:"max-width"}),d=M(t.gap??0,{name:"gap"}),c=z([a,u],(f,m,h)=>{let g=f[0]!=null&&f[0].length>0?f[0].at(-1):h.prevData[0],y=f[1]!=null&&f[1].length>0?f[1].at(-1):h.prevData[1],b=H(),v=xf(g,y,e,i,r,o),T=H()-b,w=c.meta;w&&(mt(w["block-count"],v.length),mt(w["layout-time-ns"],T)),m.emit(v);let x=()=>{i.clear(),e.text.clearCache?.()};return{deactivate:x,invalidate:x}},{name:"measured-blocks",describeKind:"derived",meta:{"block-count":0,"layout-time-ns":0},equals:(f,m)=>{let h=f,g=m;if(h==null||g==null)return h===g;if(h.length!==g.length)return!1;for(let y=0;y<h.length;y++){let b=h[y],v=g[y];if(b.type!==v.type||b.width!==v.width||b.height!==v.height||b.index!==v.index)return!1}return!0}}),l=A([c,d],([f,m])=>Rf(f,m),{name:"block-flow",equals:(f,m)=>{let h=f,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}}),p=A([l],([f])=>Sf(f),{name:"total-height"});return s.add(a,{name:"blocks"}),s.add(u,{name:"max-width"}),s.add(d,{name:"gap"}),s.add(c,{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:c,blockFlow:l,totalHeight:p}}xe();_e();ee();function Ef(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 Nf(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 Db(t,e,n){return t.kind==="circle"?Ef(t,e,n):Nf(t,e,n)}function _f(t,e,n,r,o,s,i){let a=i?.paragraphSpacing??o,u=[],d={segmentIndex:0,graphemeIndex:0};if(t.length===0||n.count<=0||o<=0)return{lines:u,cursor:d};let c=e.paddingX??0,l=e.paddingY??0,p=Math.max(0,e.width-c*2),f=Math.max(0,e.height-l*2),m=n.gap*Math.max(0,n.count-1),h=Math.max(0,(p-m)/n.count);if(h<=0)return{lines:u,cursor:d};e:for(let g=0;g<n.count;g++){let y=c+g*(h+n.gap),b=y+h,v=l;for(;v+o<=l+f;){let T=v+o,w=[];for(let S=0;S<r.length;S++){let R=Db(r[S],v,T);R!==null&&w.push(R)}let x=Iu({left:y,right:b},w,s);if(x.length===0){v+=o;continue}let k=!1;for(let S=0;S<x.length;S++){let R=x[S],N=R.right-R.left,_=Lu(t,d,N);if(_===null)return{lines:u,cursor:d};if(_.text.length===0&&_.width===0){d=_.end,k=!0;break}u.push({x:R.left,y:v,width:_.width,slotWidth:N,text:_.text,columnIndex:g,flushToRight:R.right<b-.5}),d=_.end}if(k){v+=a;continue}if(v+=o,d.segmentIndex>=t.length)break e}if(d.segmentIndex>=t.length)break}return{lines:u,cursor:d}}function Gb(t){let{adapter:e,name:n="reactive-flow-layout",minSlotWidth:r=20}=t,o=new Y(n),s=new Map,i=M(t.text??"",{name:"text"}),a=M(t.font??"16px sans-serif",{name:"font"}),u=M(t.lineHeight??20,{name:"line-height"}),d=M(t.container??{width:800,height:600,paddingX:0,paddingY:0},{name:"container"}),c=M(t.columns??{count:1,gap:0},{name:"columns"}),l=M(t.obstacles??[],{name:"obstacles"}),p=M(t.paragraphSpacing??null,{name:"paragraph-spacing"}),f=z([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],x=Ft(v,w,e,s);g.emit(x);let k=()=>{s.clear(),e.clearCache?.()};return{deactivate:k,invalidate:k}},{name:"segments",describeKind:"derived"}),m=A([f,d,c,l,u,p],([h,g,y,b,v,T])=>{let w=h,x=H(),k=T??v,{lines:S,cursor:R}=_f(w,g,y,b,v,r,{paragraphSpacing:k}),N=H()-x,_=Math.max(0,w.length-R.segmentIndex),I=m.meta;return I&&(mt(I["line-count"],S.length),mt(I["layout-time-ns"],N),mt(I["overflow-segments"],_)),S},{name:"flow-lines",meta:{"line-count":0,"layout-time-ns":0,"overflow-segments":0},equals:(h,g)=>{let y=h,b=g;if(y.length!==b.length)return!1;for(let v=0;v<y.length;v++){let T=y[v],w=b[v];if(T.x!==w.x||T.y!==w.y||T.width!==w.width||T.slotWidth!==w.slotWidth||T.text!==w.text||T.columnIndex!==w.columnIndex||T.flushToRight!==w.flushToRight)return!1}return!0}});return o.add(i,{name:"text"}),o.add(a,{name:"font"}),o.add(u,{name:"line-height"}),o.add(d,{name:"container"}),o.add(c,{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: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:f,flowLines:m}}var Gi={};ke(Gi,{NS_PER_MS:()=>He,NS_PER_SEC:()=>at,resilientPipeline:()=>Fb});Vn();Ot();function Fb(t,e={}){let n=t;e.rateLimit!=null&&(n=qn(n,e.rateLimit)),e.budget!=null&&e.budget.length>0&&(n=Su(n,e.budget));let r;if(e.breaker!=null){let s=wt(e.breaker),i=e.breakerOnOpen??"skip",a=Kn(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=Wn(n,e.timeoutMs*1e6)}e.retry!=null&&(n=Tt(n,e.retry)),e.fallback!==void 0&&(n=Hn(n,e.fallback));let o=Kt(n,{initialStatus:e.initialStatus??"pending"});return{node:o.node,status:o.status,error:o.error,breakerState:r}}var Wi={};ke(Wi,{SNAPSHOT_WIRE_VERSION:()=>No,SurfaceError:()=>Ne,asSurfaceError:()=>Fi,createGraph:()=>pr,deleteSnapshot:()=>Hi,diffSnapshots:()=>Ki,listSnapshots:()=>qi,restoreSnapshot:()=>Vi,runReduction:()=>$i,saveSnapshot:()=>Bi});var Ne=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=$b(this.details);n!==void 0&&(e.details=n)}return e}};function $b(t){try{return JSON.parse(JSON.stringify(t))}catch{return}}function Fi(t,e="internal-error"){if(t instanceof Ne)return t;let n=t instanceof Error?t.message:String(t);return new Ne(e,n)}function pr(t,e){let n=ur(t);if(!n.valid)throw new Ne("invalid-spec",`GraphSpec validation failed:
219
+ `)}`}function pb(t){let e=t.width??4,n=t.name??"errorCritique",r=t.maxFailureSamples??5,o=t.formatCritique??lb;return{name:n,seed(s){return[s]},analyze(s,i){let a=$u(s),u=typeof t.failureThreshold=="function"?t.failureThreshold(s):t.failureThreshold,d=u===void 0&&!Number.isFinite(a),c=u??a,l=d?[...s].sort((v,T)=>v.score-T.score):s.filter(v=>v.score<c).slice().sort((v,T)=>v.score-T.score),p=l.slice(0,r),{best:f,bestScore:m}=lf(i,s),h={summary:"",score:a,weakTasks:p.map(v=>v.taskId)},g=o(p,h),y={kind:"errorCritique",best:f,failures:p,critiqueText:g},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=cb(s.critique)?s.critique:void 0,u=a!==void 0?a.best:i[i.length-1],d=a?.critiqueText??s.summary,c=a?.failures??[],l=0,f={prior:u,critique:d,failures:c,reportCost:m=>{l+=m}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(f)));let m=[];for(let h=0;h<e;h++)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 fb(t){let{best:e,score:n,status:r}=t,o=Number.isFinite(n)?n.toFixed(3):String(n),s=e??void 0;return r==="converged"?{outcome:"success",detail:`refineLoop converged at score ${o}`,artifact:s}:r==="budget"?{outcome:"partial",detail:`refineLoop hit budget at score ${o}`,artifact:s}:{outcome:"failure",detail:`refineLoop errored (status=${r})`,artifact:s}}function Bu(t){let e=t.name??"refine-executor",n=t.toOutput??fb;return r=>{let o=Xe(r,i=>i!=null,{name:`${e}/gate-in`}),s=Te(o,i=>{let a=ju(t.seedFrom(i),t.evaluator,t.strategy,{...t.refine,dataset:t.datasetFor(i),name:`${e}/inner`});return C([a.status,a.best,a.score],([u,d,c])=>{let l=u;return l!=="converged"&&l!=="budget"&&l!=="errored"?null:n({best:d,score:c,status:l})},{name:`${e}/output`})},{name:e});return Xe(s,i=>i!=null,{name:`${e}/gate-out`})}}function mb(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 gb(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 hb(t){return t.artifact??null}function pf(t){let e=t.name??"eval-verifier",n=t.threshold??.5,r=t.toOutput??gb,o=t.extractArtifact??hb;return s=>{let i=Xe(s,u=>u!=null&&u[0]!=null&&u[1]!=null,{name:`${e}/gate-in`}),a=Te(i,u=>{let[d,c]=u,l=o(d,c);if(l==null)return M(r({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:n,missingArtifact:!0}));let p=M([l],{name:`${e}/candidates`}),f=M(t.datasetFor(c),{name:`${e}/dataset`}),m=t.evaluator(p,f);return C([m],([h])=>{let g=h;if(g==null)return null;let y=mb(g),b=g.filter(v=>v.score>=n).length;return r({scores:g,meanScore:y,passCount:b,total:g.length,threshold:n})},{name:`${e}/output`})},{name:e});return Xe(a,u=>u!=null,{name:`${e}/gate-out`})}}function yb(t){let e=t.name??"harness-pair",n=Bu({name:`${e}-exec`,seedFrom:t.seedFrom,evaluator:t.evaluator,strategy:t.strategy,datasetFor:t.datasetFor,refine:t.refine}),r=pf({name:`${e}-verify`,evaluator:t.evaluator,datasetFor:t.datasetFor,threshold:t.threshold});return{executor:n,verifier:r}}xe();_e();ee();var Oi={};ke(Oi,{JobFlowGraph:()=>_i,JobQueueGraph:()=>Ni,jobEventKeyOf:()=>Tb,jobFlow:()=>wb,jobQueue:()=>Mi});xe();_e();he();var bb=256,vb=1024;function ff(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Ei(t,e){return ze("job_queue",t,e)}var Tb=t=>t.action,Ni=class extends Y{_pending;_jobs;_seqCursor;pending;jobs;depth;events;audit;constructor(e,n={}){super(e,n.graph),this._pending=Ds([],{name:"pending"}),this._jobs=Ze({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=C([this.pending],([r])=>r.length,{name:"depth",describeKind:"derived",meta:Ei("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(re(this.depth)),this.events=kt({name:"events",retainedLimit:1024,graph:this}),this.audit=this.events,this._seqCursor=bs(this,"seq",0)}_bumpSeq(){let n=(this._seqCursor.cache??0)+1;return this._seqCursor.emit(n),n}attachEventStorage(e){return this.events.attachStorage(e)}enqueue(e,n={}){let r=this._bumpSeq(),o=n.id??`${this.name}-${r}`;if(this._jobs.get(o)!==void 0)throw new Error(`jobQueue("${this.name}"): duplicate job id "${o}"`);let s={id:o,payload:e,attempts:0,metadata:Object.freeze({...n.metadata??{}}),state:"queued"};return this._jobs.set(o,s),this._pending.append(o),this.events.append({action:"enqueue",id:o,payload:e,t_ns:oe(),seq:r}),o}claim(e=1){let n=ff(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),this.events.append({action:"claim",id:s,attempts:a.attempts,t_ns:oe(),seq:this._bumpSeq()})}return r}ack(e){let n=this._jobs.get(e);return!n||n.state!=="inflight"?!1:(this._jobs.delete(e),this.events.append({action:"ack",id:e,attempts:n.attempts,t_ns:oe(),seq:this._bumpSeq()}),!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),this.events.append({action:"nack",id:e,attempts:r.attempts,t_ns:oe(),seq:this._bumpSeq()}),!0):(this._jobs.delete(e),this.events.append({action:"nack",id:e,attempts:r.attempts,t_ns:oe(),seq:this._bumpSeq()}),!0)}removeById(e){let n=this._jobs.get(e);if(!n)return!1;if(n.state==="queued"){let o=this.pending.cache.indexOf(e);o>=0&&this._pending.pop(o)}return this._jobs.delete(e),this.events.append({action:"remove",id:e,attempts:n.attempts,t_ns:oe(),seq:this._bumpSeq()}),!0}consumeFrom(e,n){return e.subscribe(r=>{for(let o of r){if(o[0]!==E)continue;let s=o[1];this.enqueue(s,n?{metadata:n.metadata}:void 0)}})}},_i=class extends Y{_stageNames;_stageWorkFns;_queues=new Map;_completed;completed;completedCount;constructor(e,n={}){super(e,n.graph);let r=n.stages??["incoming","processing","done"],o=[],s=new Map;for(let u of r){let d=typeof u=="string"?u.trim():u.name.trim();typeof u!="string"&&u.work&&s.set(d,u.work),o.push(d)}if(o.length<2)throw new Error(`jobFlow("${e}"): requires at least 2 stages`);if(new Set(o).size!==o.length)throw new Error(`jobFlow("${e}"): stage names must be unique`);this._stageNames=Object.freeze([...o]),this._stageWorkFns=s;for(let u of this._stageNames){let d=Mi(`${e}-${u}`);this._queues.set(u,d),this.mount(u,d)}this._completed=Ve([],{name:"completed",maxSize:vb}),this.completed=this._completed.entries,this.add(this.completed,{name:"completed"}),this.completedCount=C([this.completed],([u])=>u.length,{name:"completedCount",describeKind:"derived",meta:Ei("job_flow_completed_count"),initial:0}),this.add(this.completedCount,{name:"completedCount"}),this.addDisposer(re(this.completedCount));let a=Math.max(1,ff(n.maxPerPump??bb,"job flow maxPerPump"));for(let u=0;u<this._stageNames.length;u+=1){let d=this._stageNames[u],c=this.queue(d),l=u+1<this._stageNames.length?this.queue(this._stageNames[u+1]):null,p=this._stageWorkFns.get(d),f=l===null;if(p){let m=z([c.pending],()=>{let h=0;for(;h<a;){let g=c.claim(1);if(g.length===0)break;let y=g[0];if(!y)break;let v=[...y.metadata.job_flow_path??[],d],T;try{T=p(y)}catch{c.nack(y.id,{requeue:!1}),h+=1;continue}let w=U(T),k=!1,x;x=w.subscribe(S=>{if(!k){for(let R of S)if(R[0]===E){k=!0,x?x():Promise.resolve().then(()=>x?.());let N=R[1],_={...y.metadata,job_flow_path:v};if(f){let I={...y,payload:N,metadata:Object.freeze(_)};X(()=>{c.ack(y.id),this._completed.append(I)})}else X(()=>{c.ack(y.id),l.enqueue(N,{metadata:_})});return}else if(R[0]===A){k=!0,x?x():Promise.resolve().then(()=>x?.()),c.nack(y.id,{requeue:!1});return}}}),h+=1}},{name:`pump_${d}`,describeKind:"effect",meta:Ei("job_flow_pump",{stage:d,has_work:!0})});this.add(m,{name:`pump_${d}`}),this.addDisposer(re(m))}else{let m=z([c.pending],()=>{let h=0;for(;h<a;){let g=c.claim(1);if(g.length===0)break;let y=g[0];if(!y)break;let v=[...y.metadata.job_flow_path??[],d],T={...y.metadata,job_flow_path:v};if(f){let w={...y,metadata:Object.freeze(T)};X(()=>{c.ack(y.id),this._completed.append(w)})}else X(()=>{c.ack(y.id),l.enqueue(y.payload,{metadata:T})});h+=1}},{name:`pump_${d}`,describeKind:"effect",meta:Ei("job_flow_pump",{stage:d,has_work:!1})});this.add(m,{name:`pump_${d}`}),this.addDisposer(re(m))}}}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 Mi(t,e){return new Ni(t,e)}function wb(t,e){return new _i(t,e)}xe();ee();function Vu(){let t=Ze({name:"strategy-entries"}),e=C([t.entries],([i])=>{let a=i;return new Map(a)},{name:"strategy-model",equals:(i,a)=>{let u=i,d=a;if(u.size!==d.size)return!1;for(let[c,l]of u){let p=d.get(c);if(!p||l.attempts!==p.attempts||l.successes!==p.successes)return!1}return!0}});function n(i,a,u){let d=lr(i,a),c=t.get(d),l=(c?.attempts??0)+1,p=(c?.successes??0)+(u?1:0);t.set(d,{rootCause:i,intervention:a,attempts:l,successes:p,successRate:p/l})}function r(i,a){return t.get(lr(i,a))}let o=e.subscribe(()=>{});function s(){o()}return{node:e,record:n,lookup:r,dispose:s}}function kb(t,e,n,r,o){let s={...dr,...o?.severityWeights},i=o?.decayRate??cr,a=o?.effectivenessThreshold??.7,u=o?.effectivenessBoost??15,d=[t,e,n];return r&&d.push(r),C(d,c=>{let l=c[0],p=c[1],f=c[2],m=r?c[3]:0,h=s[l.severity??"medium"],g=(H()-f)/1e9,y=xn(h,g,i,0),b=lr(l.rootCause,l.intervention),v=p.get(b);return v&&v.successRate>=a&&(y+=u),y+=m*20,y},{name:"priority-score"})}var mf="intake",xb="triage-output",gf="retry",hf="verify-results",yf="__unrouted";function bf(t,e){let n=Ro(e,Gu,(r,o)=>r.replace("{{item}}",JSON.stringify(o)));return r=>wn(t,[r],n,{name:"execute",format:"json"})}function vf(t,e){let n=Ro(e,Fu,(r,o)=>{let[s,i]=o;return r.replace("{{execution}}",JSON.stringify(s)).replace("{{item}}",JSON.stringify(i))});return r=>wn(t,[r],o=>o==null?"":n(o),{name:"verify",format:"json"})}var Ai=class extends Y{queues;jobs;gates;queueTopics;strategy;totalRetries;totalReingestions;priorityScores;constructor(e,n,r,o,s,i,a,u,d){super(e),this.queues=n,this.queueTopics=r,this.jobs=o,this.gates=s,this.strategy=i,this.totalRetries=a,this.totalReingestions=u,this.priorityScores=d}get intake(){return this.queues.topic(mf)}get verifyResults(){return this.queues.topic(hf)}get retry(){return this.queues.topic(gf)}get unrouted(){return this.queues.topic(yf)}stageNodes(){let e=this.queues,n=i=>e.has(i)?`queues::${i}::latest`:null,r=i=>i==null?[]:[i],o=it.flatMap(i=>r(n(i))),s=[];for(let[i]of this.gates)s.push(`gates::${i}/gate`);return[{label:"INTAKE",paths:r(n("intake"))},{label:"TRIAGE",paths:["triage"]},{label:"QUEUE",paths:o},{label:"GATE",paths:s},{label:"EXECUTE",paths:["execute"]},{label:"VERIFY",paths:r(n("verify-results"))},{label:"REFLECT",paths:["reflect"]},{label:"STRATEGY",paths:["strategy"]}]}};function Rb(t,e){let n=e.adapter,r=e.maxRetries??2,o=e.retainedLimit??1e3,s=e.errorClassifier??Ri,i=new Map;for(let J of it)i.set(J,{...xi[J],...e.queues?.[J]});let a=go(`${t}/queues`,{defaultTopicOptions:{retainedLimit:o}}),u=a.topic(mf),d=a.topic(xb),c=a.topic(gf),l=a.topic(hf),p=new Map;for(let J of it)p.set(J,a.topic(J));let f=a.topic(yf),m=Vu(),h=Pt(u.latest,m.node),g=Ro(e.triagePrompt,Du,(J,se)=>{let[ve,W]=se;return J.replace("{{strategy}}",JSON.stringify(Array.from(W.entries()))).replace("{{item}}",JSON.stringify(ve))}),y=wn(n,[h],J=>{let se=J;return!se||!se[0]?"":g(se)},{name:"triage",format:"json"}),b=Pt(y,h),T=pe([b],([J])=>{if(J==null)return;let[se,ve]=J;if(!se?.route)return;let W=ve?.[0],ce={...se,...W};d.publish(ce)}).subscribe(()=>{}),w=new Set(it);for(let J of it)ri(`bridge/${J}`,d,p.get(J),{map:se=>se.route===J?se:void 0});ri("bridge/__unrouted",d,f,{map:J=>w.has(J.route)?void 0:J});let k=new Map,x=new Map;for(let J of it)k.set(J,Mi(`jobs/${J}`));let S=[];for(let J of it){let se=p.get(J),ve=k.get(J),W=new WeakSet,ce=pe([se.events],([Se])=>{let Ee=Se??[];for(let le of Ee){if(W.has(le))continue;W.add(le);let Pe=ve.enqueue(le);x.set(qr(le),{route:J,id:Pe})}},{name:`jobs/${J}-mirror`});S.push(ce.subscribe(()=>{}))}function R(J){let se=qr(J),ve=x.get(se);ve&&(k.get(ve.route)?.removeById(ve.id),x.delete(se))}let N=ir("gates"),_=new Map;for(let J of it){let se=i.get(J);if(!se.gated)continue;let ve=p.get(J),W=N.gate(`${J}/gate`,ve.latest,{maxPending:se.maxPending,startOpen:se.startOpen});_.set(J,W)}let I=[];for(let J of it)i.get(J).gated&&_.has(J)?I.push(_.get(J).node):I.push(p.get(J).latest);I.push(c.latest);let O=xt(...I),B=(e.executor??bf(n,e.executePrompt))(O),j=Pt(B,O),Z=(e.verifier??vf(n,e.verifyPrompt))(j),F=Pt(Z,j),Q=e.maxReingestions??1,G=Math.min(e.maxTotalRetries??r*10,100),q=Math.min(e.maxTotalReingestions??Q*10,100),$=M(0),te=M(0);function Re(J,se,ve){let W={item:ve,outcome:se?.outcome??"failure",detail:se?.detail??"unknown",artifact:se?.artifact};return{item:ve,execution:W,verified:J.verified,findings:J.findings??[],errorClass:J.errorClass}}function Oe(J,se){m.record(se.rootCause,se.intervention,!0),l.publish(J),R(se)}function Ae(J,se){let ve=qr(se),W=se.$retries??0,ce={...se,$retries:W+1,summary:`[RETRY ${W+1}/${r}] ${ve} \u2014 Previous attempt failed: ${J.findings.join("; ")}`,relatedTo:[ve]};c.publish(ce)}function ye(J,se){m.record(se.rootCause,se.intervention,!1),l.publish(J),R(se);let ve=qr(se),W=se.$reingestions??0;W<Q&&Kr(te,q)&&u.publish({source:se.source,summary:`Verification failed for: ${ve}`,evidence:J.findings.join(`
220
+ `),affectsAreas:se.affectsAreas,affectsEvalTasks:se.affectsEvalTasks,severity:se.severity??"high",relatedTo:[ve],$reingestions:W+1})}let Ge=z([F],(J,se)=>{let ve=J[0];if(ve==null||ve.length===0)return;let W=ve[ve.length-1];if(W==null)return;let[ce,Se]=W,[Ee,le]=Se??[null,null];if(!ce||!le)return;if(Ee==null){ye({item:le,execution:{item:le,outcome:"failure",detail:"executor returned null"},verified:!1,findings:["executor returned null"],errorClass:"structural"},le);return}let Pe=Re(ce,Ee,le);if(Pe.verified){Oe(Pe,le);return}let me=Pe.errorClass??s({item:le,outcome:Ee.outcome,detail:Pe.findings.join("; ")}),ge=le.$retries??0;me==="self-correctable"&&ge<r&&Kr($,G)?Ae(Pe,le):ye(Pe,le)}),ie=Ge.subscribe(()=>{}),we=C([Ge],()=>null,{name:"reflect",equals:()=>!1}),Fe;e.priority&&(Fe=Sb(p,m,e));let be=new Ai(t,a,p,k,_,m,$,te,Fe);be.addDisposer(T),be.addDisposer(ie),be.addDisposer(m.dispose);for(let J of S)be.addDisposer(J);if(be.add(y,{name:"triage"}),be.add(O,{name:"execute-input"}),be.add(B,{name:"execute"}),be.add(j,{name:"execute-context"}),be.add(Z,{name:"verify"}),be.add(F,{name:"verify-context"}),be.add(Ge,{name:"verify-dispatch"}),be.add(we,{name:"reflect"}),be.add(m.node,{name:"strategy"}),be.addDisposer(we.subscribe(()=>{})),Fe)for(let[J,se]of Fe)be.add(se,{name:`priority/${J}`}),be.addDisposer(se.subscribe(()=>{}));be.mount("queues",a),be.mount("gates",N);for(let[J,se]of k)be.mount(`jobs/${J}`,se);return be}function Sb(t,e,n){if(!n.lastInteractionNs)throw new Error("harnessLoop: `opts.priority` requires `opts.lastInteractionNs` \u2014 pass a Node<number> (e.g. `fromTimer(60_000)` or a `state(monotonicNs())` you bump on human interaction). Priority scores only decay when this node settles; an internal default would freeze age at construction time.");let r=n.lastInteractionNs,o=n.priority??{},s={...dr,...o.severityWeights},i=o.decayRate??cr,a=o.effectivenessThreshold??.7,u=o.effectivenessBoost??15,d=new Map;for(let[c,l]of t){let p=C([l.latest,e.node,r],f=>{let m=f[0];if(m==null)return 0;let h=s[m.severity??"medium"]??40,g=(H()-f[2])/1e9,y=h*Math.exp(-i*Math.max(0,g)),b=`${m.rootCause}\u2192${m.intervention}`,T=f[1]?.get(b);return T&&T.successRate>=a&&(y+=u),y},{name:`priority/${c}`});d.set(c,p)}return d}function Eb(t,e){let n=pn(t,e),r={};for(let o of it){let s=t.queues.has(o)?t.queues.topic(o):null;r[o]=s?.retained().length??0}return{...n,queueDepths:r,strategyEntries:t.strategy.node.cache?.size??0,totalRetries:t.totalRetries.cache??0,totalReingestions:t.totalReingestions.cache??0}}xe();function Nb(t){let e={};for(let{label:n,paths:r}of t.stageNodes())for(let o of r)e[o]=n;return e}function _b(t,e){let n=e?.logger===null?null:e?.logger??console.log,r=e?.detail??"summary",o=H(),s=[],i=[],a=Nb(t);function u(){return(H()-o)/1e9}function d(c,l,p){let f={elapsed:u(),stage:c,type:l};r!=="summary"&&(f.summary=Mb(p)),r==="full"&&(f.data=p),i.push(f)}for(let[c,l]of Object.entries(a))try{let p=t.observe(c,{format:"stage-log",stageLabels:a,logger:n?f=>n(f):()=>{},includeTypes:["data","error","complete"]});p.onEvent(f=>{f.type==="data"?d(l,"data",f.data):f.type==="error"?d(l,"error",f.data):f.type==="complete"&&d(l,"complete",void 0)}),s.push(p)}catch(p){let f=p instanceof Error?p.message:String(p);d(l,"error",`observe-unavailable: ${c} \u2014 ${f}`),n&&n(`[${u().toFixed(3)}s] ${l.padEnd(9)} \u2717 observe-unavailable: ${f}`)}return{get events(){return i},dispose(){for(let c of s)c.dispose();s.length=0}}}function Mb(t){if(t==null)return"null";if(typeof t=="string")return Tf(t,80);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return Tf(e,120)}catch{return String(t)}}function Tf(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}var Ii={};ke(Ii,{LensGraph:()=>Li,graphLens:()=>Ib,watchTopologyTree:()=>Ct});xe();ee();function wf(t){return ze("lens",t)}function Ob(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,d=2,c=new Map;for(let h of e)c.set(h,a);let l=!1,p=new Map,f=h=>{let g=c.get(h)??a;if(g===u)return l=!0,0;if(g===d)return p.get(h)??0;c.set(h,u);let y=0,b=r.get(h);if(b!=null)for(let v of b){let T=f(v);T+1>y&&(y=T+1)}return c.set(h,d),p.set(h,y),y},m=0;for(let h of o){let g=f(h);g>m&&(m=g)}for(let h of e)c.get(h)===a&&f(h);return{nodeCount:e.length,edgeCount:i,subgraphCount:t.subgraphs.length,sources:o,sinks:s,depth:m,hasCycles:l}}function Ab(t){let e=[];for(let[n,r]of Object.entries(t.nodes)){if(r.status!=="errored")continue;let o={path:n,status:"errored"},s=fn(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 Cb(t,e){return t.nodeCount===e.nodeCount&&t.edgeCount===e.edgeCount&&t.subgraphCount===e.subgraphCount&&t.depth===e.depth&&t.hasCycles===e.hasCycles&&kf(t.sources,e.sources)&&kf(t.sinks,e.sinks)}function Lb(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 kf(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 Y{stats;health;flow;_target;constructor(e,n={}){super(n.name??`${e.name}_lens`,n.graph),this._target=e;let r=0,o=0,s=M(0,{name:"stats_tick"}),i=M(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=Ze(a),this.add(this.flow.entries,{name:"flow"});let u=n.pathFilter,d=Ct(e,(p,f,m)=>{if(r+=1,s.emit(r),o+=1,i.emit(o),p.kind==="removed")if(p.nodeKind==="node"){let h=`${m}${p.name}`;this.flow.delete(h)}else{let h=`${m}${p.name}::`,g=[];for(let y of p.audit.nodes){let b=y===""?`${m}${p.name}`:`${h}${y}`;g.push(b)}g.length>0&&this.flow.deleteMany(g)}});this.addDisposer(d);let c=e.observe({timeline:!0,structured:!0}),l=c.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 h=this.flow.get(m),g=h!=null?h.count+1:1;this.flow.set(m,{path:m,count:g,lastUpdate_ns:H()})}});this.addDisposer(()=>{l(),c.dispose()}),this.stats=C([s],()=>Ob(e.describe({detail:"minimal"})),{name:"stats",describeKind:"derived",equals:Cb,meta:wf("stats")}),this.add(this.stats,{name:"stats"}),this.addDisposer(re(this.stats)),this.health=C([i],()=>Ab(e.describe({detail:"standard"})),{name:"health",describeKind:"derived",equals:Lb,meta:wf("health")}),this.add(this.health,{name:"health"}),this.addDisposer(re(this.health))}why(e,n,r){let o=Ou(this._target,e,n,r);return this.addDisposer(o.dispose),o}get target(){return this._target}};function Ib(t,e){return new Li(t,e)}var Pi={};ke(Pi,{processInstanceKeyOf:()=>Pb,processManager:()=>Gb});xe();ae();he();var Pb=t=>t.correlationId;function xf(t){if(t==null)return Promise.resolve(void 0);let e=U(t);return new Promise((n,r)=>{let o=!1,s,i=()=>{s&&s()};s=e.subscribe(a=>{if(!o)for(let u of a){if(u[0]===E){o=!0,Promise.resolve().then(i),n(u[1]);return}if(u[0]===A){o=!0,Promise.resolve().then(i),r(u[1]);return}if(u[0]===L){o=!0,Promise.resolve().then(i),n(void 0);return}}})})}async function Db(t,e,n,r,o){let s;for(let i=0;i<=r;i++){if(i>0){let a=o[Math.min(i-1,o.length-1)]??0;a>0&&await new Promise(u=>setTimeout(u,a))}try{return await xf(t(e,n))}catch(a){s=a}}return{kind:"fail",error:s}}function Gb(t,e,n){let r=n.retryMax??0,o=n.backoffMs??[0],s=1024,i=new Map,a=new Set,u=new Map,d=kt({name:`${e}_process_instances`,retainedLimit:s,graph:t}),c=0;function l(){return++c}function p(R,N,_){f(R,N,_,void 0)}function f(R,N,_,I){let O=oe(),P={correlationId:R,state:N,status:_,startedAt:u.get(R)??O,updatedAt:O,t_ns:O,seq:l(),...n.handlerVersion!==void 0?{handlerVersion:n.handlerVersion}:{},...I!==void 0?{reason:I}:{}};d.append(P)}let m=`_process_${e}_started`;t.event(m),n.persistence?.eventStorage&&t.attachEventStorage(n.persistence.eventStorage);async function h(R,N,_,I){if(a.delete(R),i.delete(R),u.delete(R),n.compensate)try{await xf(n.compensate(N,_)),f(R,N,"compensated",I)}catch{p(R,N,"failed")}else p(R,N,"failed")}async function g(R,N){if(a.has(R)){if(N.kind==="fail"){let _=i.get(R)??n.initial;await h(R,_,N.error);return}if(N.kind==="continue"){if(i.set(R,N.state),N.emit)for(let _ of N.emit)try{t._appendEvent(_.type,_.payload,{correlationId:R,aggregateId:R})}catch{}if(p(R,N.state,"running"),n.isTerminal?.(N.state)){a.delete(R),i.delete(R),u.delete(R),p(R,N.state,"terminated");return}if(N.schedule){let{afterMs:_,eventType:I}=N.schedule,O,P=st(_),B=j=>{for(let D of j)if(D[0]===E){if(O?O():queueMicrotask(()=>O?.()),!a.has(R))return;let Z=i.get(R);if(Z===void 0)return;let F=n.steps[I];if(!F)return;let Q={type:I,payload:null,timestampNs:oe(),seq:Number.NaN,correlationId:R,aggregateId:R};b(R,F,Z,Q)}};O=P.subscribe(B)}return}if(N.kind==="terminate"){if(i.set(R,N.state),N.emit)for(let _ of N.emit)try{t._appendEvent(_.type,_.payload,{correlationId:R,aggregateId:R})}catch{}a.delete(R),i.delete(R),u.delete(R),p(R,N.state,"terminated")}}}let y=new Map;function b(R,N,_,I){let P=(y.get(R)??Promise.resolve()).then(async()=>{let B=i.get(R);if(B===void 0||!a.has(R))return;let j;try{j=await Db(N,B,I,r,o)}catch(D){await h(R,i.get(R)??n.initial,D);return}await g(R,j)});y.set(R,P),P.finally(()=>{y.get(R)===P&&y.delete(R)})}let v=!1,T=[];for(let R of n.watching){let N=t.event(R),_=0;_=(N.cache??[]).length;let O=N.subscribe(P=>{for(let B of P){if(B[0]!==E)continue;let j=B[1];if(j.length<=_)continue;let D=j.slice(_);_=j.length;for(let Z of D){let F=Z.correlationId;if(F===void 0||!a.has(F))continue;let Q=n.steps[R];if(!Q)continue;let G=i.get(F);G!==void 0&&b(F,Q,G,Z)}}});T.push(O)}function w(R,N){if(v||a.has(R))return;let _=oe();u.set(R,_),i.set(R,n.initial),a.add(R);try{t._appendEvent(m,N??null,{correlationId:R,aggregateId:R})}catch{}p(R,n.initial,"running")}function k(R,N){if(v||!a.has(R))return;let _=i.get(R)??n.initial;h(R,_,new Error(`cancelled: ${N??"no reason given"}`),N)}function x(R){return i.get(R)}function S(){if(!v){v=!0;for(let R of T)try{R()}catch{}T.length=0}}return{instances:d,audit:d,start:w,cancel:k,getState:x,dispose:S}}var Di={};ke(Di,{CanvasMeasureAdapter:()=>Wu,CliMeasureAdapter:()=>Ku,ImageSizeAdapter:()=>Ju,NodeCanvasMeasureAdapter:()=>zu,PrecomputedAdapter:()=>Hu,SvgBoundsAdapter:()=>Uu,analyzeAndMeasure:()=>Ft,carveTextLineSlots:()=>Iu,circleIntervalForBand:()=>_f,computeBlockFlow:()=>Ef,computeCharPositions:()=>bi,computeFlowLines:()=>Of,computeLineBreaks:()=>Rn,computeTotalHeight:()=>Nf,layoutNextLine:()=>Lu,measureBlock:()=>Rf,measureBlocks:()=>Sf,reactiveBlockLayout:()=>Fb,reactiveFlowLayout:()=>jb,reactiveLayout:()=>By,rectIntervalForBand:()=>Mf});var Ku=class{cellPx;constructor(e){this.cellPx=e?.cellPx??8}measureSegment(e,n){return{width:Jn(e)*this.cellPx}}},qu=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 qu(`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}}},Wu=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=""}},zu=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=""}},Uu=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")}},Ju=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}}};xe();_e();ee();function Rf(t,e,n,r,o,s,i){switch(t.type){case"text":{let a=t.font??o,u=t.lineHeight??s,d=Ft(t.text,a,n.text,r),c=Rn(d,e,n.text,a,r),l=bi(c,d,u),p=c.lineCount*u,f=0;for(let m of c.lines)m.width>f&&(f=m.width);return{index:i,type:"text",width:Math.min(f,e),height:p,textSegments:d,textLineBreaks:c,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 d=n.image.measureImage(t.src);a=d.width,u=d.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 d=n.svg.measureSvg(t.content);a=d.width,u=d.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 Sf(t,e,n,r,o,s){return t.map((i,a)=>Rf(i,e,n,r,o,s,a))}function Ef(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 Nf(t){if(t.length===0)return 0;let e=t[t.length-1];return e.y+e.height}function Fb(t){let{adapters:e,name:n="reactive-block-layout",defaultFont:r="16px sans-serif",defaultLineHeight:o=20}=t,s=new Y(n),i=new Map,a=M(t.blocks??[],{name:"blocks"}),u=M(Math.max(0,t.maxWidth??800),{name:"max-width"}),d=M(t.gap??0,{name:"gap"}),c=z([a,u],(f,m,h)=>{let g=f[0]!=null&&f[0].length>0?f[0].at(-1):h.prevData[0],y=f[1]!=null&&f[1].length>0?f[1].at(-1):h.prevData[1],b=H(),v=Sf(g,y,e,i,r,o),T=H()-b,w=c.meta;w&&(mt(w["block-count"],v.length),mt(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 h=f,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=C([c,d],([f,m])=>Ef(f,m),{name:"block-flow",equals:(f,m)=>{let h=f,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}}),p=C([l],([f])=>Nf(f),{name:"total-height"});return s.add(a,{name:"blocks"}),s.add(u,{name:"max-width"}),s.add(d,{name:"gap"}),s.add(c,{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:c,blockFlow:l,totalHeight:p}}xe();_e();ee();function _f(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 Mf(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 $b(t,e,n){return t.kind==="circle"?_f(t,e,n):Mf(t,e,n)}function Of(t,e,n,r,o,s,i){let a=i?.paragraphSpacing??o,u=[],d={segmentIndex:0,graphemeIndex:0};if(t.length===0||n.count<=0||o<=0)return{lines:u,cursor:d};let c=e.paddingX??0,l=e.paddingY??0,p=Math.max(0,e.width-c*2),f=Math.max(0,e.height-l*2),m=n.gap*Math.max(0,n.count-1),h=Math.max(0,(p-m)/n.count);if(h<=0)return{lines:u,cursor:d};e:for(let g=0;g<n.count;g++){let y=c+g*(h+n.gap),b=y+h,v=l;for(;v+o<=l+f;){let T=v+o,w=[];for(let S=0;S<r.length;S++){let R=$b(r[S],v,T);R!==null&&w.push(R)}let k=Iu({left:y,right:b},w,s);if(k.length===0){v+=o;continue}let x=!1;for(let S=0;S<k.length;S++){let R=k[S],N=R.right-R.left,_=Lu(t,d,N);if(_===null)return{lines:u,cursor:d};if(_.text.length===0&&_.width===0){d=_.end,x=!0;break}u.push({x:R.left,y:v,width:_.width,slotWidth:N,text:_.text,columnIndex:g,flushToRight:R.right<b-.5}),d=_.end}if(x){v+=a;continue}if(v+=o,d.segmentIndex>=t.length)break e}if(d.segmentIndex>=t.length)break}return{lines:u,cursor:d}}function jb(t){let{adapter:e,name:n="reactive-flow-layout",minSlotWidth:r=20}=t,o=new Y(n),s=new Map,i=M(t.text??"",{name:"text"}),a=M(t.font??"16px sans-serif",{name:"font"}),u=M(t.lineHeight??20,{name:"line-height"}),d=M(t.container??{width:800,height:600,paddingX:0,paddingY:0},{name:"container"}),c=M(t.columns??{count:1,gap:0},{name:"columns"}),l=M(t.obstacles??[],{name:"obstacles"}),p=M(t.paragraphSpacing??null,{name:"paragraph-spacing"}),f=z([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=Ft(v,w,e,s);g.emit(k);let x=()=>{s.clear(),e.clearCache?.()};return{deactivate:x,invalidate:x}},{name:"segments",describeKind:"derived"}),m=C([f,d,c,l,u,p],([h,g,y,b,v,T])=>{let w=h,k=H(),x=T??v,{lines:S,cursor:R}=Of(w,g,y,b,v,r,{paragraphSpacing:x}),N=H()-k,_=Math.max(0,w.length-R.segmentIndex),I=m.meta;return I&&(mt(I["line-count"],S.length),mt(I["layout-time-ns"],N),mt(I["overflow-segments"],_)),S},{name:"flow-lines",meta:{"line-count":0,"layout-time-ns":0,"overflow-segments":0},equals:(h,g)=>{let y=h,b=g;if(y.length!==b.length)return!1;for(let v=0;v<y.length;v++){let T=y[v],w=b[v];if(T.x!==w.x||T.y!==w.y||T.width!==w.width||T.slotWidth!==w.slotWidth||T.text!==w.text||T.columnIndex!==w.columnIndex||T.flushToRight!==w.flushToRight)return!1}return!0}});return o.add(i,{name:"text"}),o.add(a,{name:"font"}),o.add(u,{name:"line-height"}),o.add(d,{name:"container"}),o.add(c,{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: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:f,flowLines:m}}var Gi={};ke(Gi,{NS_PER_MS:()=>He,NS_PER_SEC:()=>at,resilientPipeline:()=>Bb});Vn();Ot();function Bb(t,e={}){let n=t;e.rateLimit!=null&&(n=qn(n,e.rateLimit)),e.budget!=null&&e.budget.length>0&&(n=Su(n,e.budget));let r;if(e.breaker!=null){let s=wt(e.breaker),i=e.breakerOnOpen??"skip",a=Kn(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=Wn(n,e.timeoutMs*1e6)}e.retry!=null&&(n=Tt(n,e.retry)),e.fallback!==void 0&&(n=Hn(n,e.fallback));let o=Kt(n,{initialStatus:e.initialStatus??"pending"});return{node:o.node,status:o.status,error:o.error,breakerState:r}}var Wi={};ke(Wi,{SNAPSHOT_WIRE_VERSION:()=>No,SurfaceError:()=>Ne,asSurfaceError:()=>Fi,createGraph:()=>pr,deleteSnapshot:()=>Hi,diffSnapshots:()=>Ki,listSnapshots:()=>qi,restoreSnapshot:()=>Vi,runReduction:()=>$i,saveSnapshot:()=>Bi});var Ne=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=Vb(this.details);n!==void 0&&(e.details=n)}return e}};function Vb(t){try{return JSON.parse(JSON.stringify(t))}catch{return}}function Fi(t,e="internal-error"){if(t instanceof Ne)return t;let n=t instanceof Error?t.message:String(t);return new Ne(e,n)}function pr(t,e){let n=ur(t);if(!n.valid)throw new Ne("invalid-spec",`GraphSpec validation failed:
221
221
  ${n.errors.join(`
222
222
  `)}`,{errors:n.errors});let r=e?.catalog??{},o=wo(t,r);if(!o.valid)throw new Ne("catalog-error",`Catalog validation failed:
223
223
  ${o.errors.join(`
224
- `)}`,{errors:o.errors});try{return ko(t,e)}catch(s){let i=s instanceof Error?s.message:String(s);throw new Ne("catalog-error",i)}}ae();var jb=3e4;async function $i(t,e,n){let r=n?.inputPath??"input",o=n?.outputPath??"output",s=n?.timeoutMs??jb,i=pr(t,{catalog:n?.catalog}),a;try{a=i.resolve(o)}catch{throw i.destroy(),new Ne("node-not-found",`reduce: output path "${o}" is not registered`,{path:o})}try{i.resolve(r)}catch{throw i.destroy(),new Ne("node-not-found",`reduce: input path "${r}" is not registered`,{path:r})}try{return await new Promise((u,d)=>{let c=!1,l=!1,p,f,m=!1,h=g=>{l||(l=!0,p!==void 0&&clearTimeout(p),f!==void 0?(f(),f=void 0):m=!0,g())};f=a.subscribe(g=>{for(let y of g){if(l)return;if(c){if(y[0]===E){h(()=>u(y[1]));return}if(y[0]===V){let b=a.cache;h(()=>u(b));return}if(y[0]===C){let b=y[1],v=b instanceof Error?b.message:String(b),T=b instanceof Error?b:void 0;h(()=>d(new Ne("internal-error",`reduce: output emitted ERROR: ${v}`,T!=null?{cause:T}:void 0)));return}if(y[0]===L){h(()=>d(new Ne("internal-error","reduce: output COMPLETEd without a post-push DATA")));return}}}}),m&&(f?.(),f=void 0),c=!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(()=>d(new Ne("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(()=>{h(()=>d(new Ne("reduce-timeout",`reduce: no output emitted within ${s}ms`,{timeoutMs:s,outputPath:o})))},s),p.unref?.())})}finally{i.destroy()}}xe();var No=ft,So="snapshot:";function Eo(t){if(t.startsWith(So))throw new Ne("snapshot-failed",`snapshot id must not start with "${So}" (reserved); got "${t}"`,{snapshotId:t})}function ji(t){return`${So}${t}`}function Bb(t){return t.startsWith(So)?t.slice(So.length):void 0}function Yu(t,e){if(t==null||typeof t!="object")throw new Ne("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 Ne("restore-failed",`snapshot "${e}" is a diff record; restore the baseline and replay WAL instead`,{snapshotId:e,mode:"diff"}):new Ne("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 Ne("restore-failed",`snapshot "${e}" payload is not a GraphCheckpointRecord or GraphPersistSnapshot`,{snapshotId:e})}async function Bi(t,e,n){Eo(e);let r;try{r=t.snapshot()}catch(s){let i=s instanceof Error?s.message:String(s);throw new Ne("snapshot-failed",`snapshot "${e}" serialization failed: ${i}`,{snapshotId:e})}let o={name:t.name,mode:"full",seq:0,timestamp_ns:oe(),format_version:No,snapshot:r};try{await n.save(ji(e),o)}catch(s){let i=s instanceof Error?s.message:String(s);throw new Ne("snapshot-failed",`snapshot "${e}" save failed: ${i}`,{snapshotId:e})}return{snapshotId:e,timestamp_ns:o.timestamp_ns}}async function Vi(t,e,n){Eo(t);let r=ji(t),o=await e.load(r);o===void 0&&(o=await e.load(t));let s=Yu(o,t);try{return Y.fromSnapshot(s,n?.factories?{factories:n.factories}:void 0)}catch(i){let a=i instanceof Error?i.message:String(i);throw new Ne("restore-failed",`snapshot "${t}" restore failed: ${a}`,{snapshotId:t})}}async function Ki(t,e,n){Eo(t),Eo(e);let r=async u=>{let d=ji(u),c=await n.load(d);return c===void 0&&(c=await n.load(u)),c},[o,s]=await Promise.all([r(t),r(e)]),i=Yu(o,t),a=Yu(s,e);return Y.diff(i,a)}async function qi(t,e){if(typeof t.list!="function")throw new Ne("tier-no-list","KvStorageTier 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=Bb(s);i!==void 0?r.push(i):o&&r.push(s)}return r}async function Hi(t,e){if(Eo(t),typeof e.delete!="function")throw new Ne("snapshot-failed",`KvStorageTier is append-only (no delete()); cannot delete "${t}"`,{snapshotId:t});try{await e.delete(ji(t))}catch(n){let r=n instanceof Error?n.message:String(n);throw new Ne("snapshot-failed",`snapshot "${t}" delete failed: ${r}`,{snapshotId:t})}}var Vb="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,appendLogStorage,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,defer,delay,deleteSnapshot,demoShell,derived,deserializeError,dictKv,dictSnapshot,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,jsonCodec,jsonCodecFor,keepalive,kvStorage,last,layout,lens,linear,listSnapshots,lru,makeHttpError,map,matchesAnyPattern,matchesCron,memory,memoryAppendLog,memoryBackend,memoryKv,memorySnapshot,merge,mergeMap,mergeReactiveLogs,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,process,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,runReduction,sample,saveSnapshot,scan,serializeError,share,shareReplay,signalToName,signals,singleFromAny,singleNodeFromAny,sizeof,skip,snapshotStorage,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});
224
+ `)}`,{errors:o.errors});try{return ko(t,e)}catch(s){let i=s instanceof Error?s.message:String(s);throw new Ne("catalog-error",i)}}ae();var Kb=3e4;async function $i(t,e,n){let r=n?.inputPath??"input",o=n?.outputPath??"output",s=n?.timeoutMs??Kb,i=pr(t,{catalog:n?.catalog}),a;try{a=i.resolve(o)}catch{throw i.destroy(),new Ne("node-not-found",`reduce: output path "${o}" is not registered`,{path:o})}try{i.resolve(r)}catch{throw i.destroy(),new Ne("node-not-found",`reduce: input path "${r}" is not registered`,{path:r})}try{return await new Promise((u,d)=>{let c=!1,l=!1,p,f,m=!1,h=g=>{l||(l=!0,p!==void 0&&clearTimeout(p),f!==void 0?(f(),f=void 0):m=!0,g())};f=a.subscribe(g=>{for(let y of g){if(l)return;if(c){if(y[0]===E){h(()=>u(y[1]));return}if(y[0]===V){let b=a.cache;h(()=>u(b));return}if(y[0]===A){let b=y[1],v=b instanceof Error?b.message:String(b),T=b instanceof Error?b:void 0;h(()=>d(new Ne("internal-error",`reduce: output emitted ERROR: ${v}`,T!=null?{cause:T}:void 0)));return}if(y[0]===L){h(()=>d(new Ne("internal-error","reduce: output COMPLETEd without a post-push DATA")));return}}}}),m&&(f?.(),f=void 0),c=!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(()=>d(new Ne("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(()=>{h(()=>d(new Ne("reduce-timeout",`reduce: no output emitted within ${s}ms`,{timeoutMs:s,outputPath:o})))},s),p.unref?.())})}finally{i.destroy()}}xe();var No=ft,So="snapshot:";function Eo(t){if(t.startsWith(So))throw new Ne("snapshot-failed",`snapshot id must not start with "${So}" (reserved); got "${t}"`,{snapshotId:t})}function ji(t){return`${So}${t}`}function qb(t){return t.startsWith(So)?t.slice(So.length):void 0}function Yu(t,e){if(t==null||typeof t!="object")throw new Ne("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 Ne("restore-failed",`snapshot "${e}" is a diff record; restore the baseline and replay WAL instead`,{snapshotId:e,mode:"diff"}):new Ne("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 Ne("restore-failed",`snapshot "${e}" payload is not a GraphCheckpointRecord or GraphPersistSnapshot`,{snapshotId:e})}async function Bi(t,e,n){Eo(e);let r;try{r=t.snapshot()}catch(s){let i=s instanceof Error?s.message:String(s);throw new Ne("snapshot-failed",`snapshot "${e}" serialization failed: ${i}`,{snapshotId:e})}let o={name:t.name,mode:"full",seq:0,timestamp_ns:oe(),format_version:No,snapshot:r};try{await n.save(ji(e),o)}catch(s){let i=s instanceof Error?s.message:String(s);throw new Ne("snapshot-failed",`snapshot "${e}" save failed: ${i}`,{snapshotId:e})}return{snapshotId:e,timestamp_ns:o.timestamp_ns}}async function Vi(t,e,n){Eo(t);let r=ji(t),o=await e.load(r);o===void 0&&(o=await e.load(t));let s=Yu(o,t);try{return Y.fromSnapshot(s,n?.factories?{factories:n.factories}:void 0)}catch(i){let a=i instanceof Error?i.message:String(i);throw new Ne("restore-failed",`snapshot "${t}" restore failed: ${a}`,{snapshotId:t})}}async function Ki(t,e,n){Eo(t),Eo(e);let r=async u=>{let d=ji(u),c=await n.load(d);return c===void 0&&(c=await n.load(u)),c},[o,s]=await Promise.all([r(t),r(e)]),i=Yu(o,t),a=Yu(s,e);return Y.diff(i,a)}async function qi(t,e){if(typeof t.list!="function")throw new Ne("tier-no-list","KvStorageTier 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=qb(s);i!==void 0?r.push(i):o&&r.push(s)}return r}async function Hi(t,e){if(Eo(t),typeof e.delete!="function")throw new Ne("snapshot-failed",`KvStorageTier is append-only (no delete()); cannot delete "${t}"`,{snapshotId:t});try{await e.delete(ji(t))}catch(n){let r=n instanceof Error?n.message:String(n);throw new Ne("snapshot-failed",`snapshot "${t}" delete failed: ${r}`,{snapshotId:t})}}var Hb="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,appendLogStorage,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,defer,delay,deleteSnapshot,demoShell,derived,deserializeError,dictKv,dictSnapshot,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,jsonCodec,jsonCodecFor,keepalive,kvStorage,last,layout,lens,linear,listSnapshots,lru,makeHttpError,map,matchesAnyPattern,matchesCron,memory,memoryAppendLog,memoryBackend,memoryKv,memorySnapshot,merge,mergeMap,mergeReactiveLogs,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,process,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,runReduction,sample,saveSnapshot,scan,serializeError,share,shareReplay,signalToName,signals,singleFromAny,singleNodeFromAny,sizeof,skip,snapshotStorage,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});