@graphrefly/graphrefly 0.30.0 → 0.31.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 (178) hide show
  1. package/dist/{cascading-dNCtjW8j.d.cts → cascading-BfQmSmjU.d.cts} +21 -2
  2. package/dist/{cascading-BszPheHD.d.ts → cascading-D3sapjue.d.ts} +21 -2
  3. package/dist/{chunk-T5SHIKJD.js → chunk-3JRKP4BH.js} +1 -1
  4. package/dist/{chunk-GJR3P6JG.js → chunk-3Q2WXM6X.js} +1 -1
  5. package/dist/chunk-4KAUNEKV.js +3 -0
  6. package/dist/{chunk-SLMYTGTU.js → chunk-4UUDNFYG.js} +1 -1
  7. package/dist/chunk-4VXL3UZK.js +1 -0
  8. package/dist/{chunk-AV3PIDFQ.js → chunk-4ZPO2EL5.js} +1 -1
  9. package/dist/{chunk-VWPRPPKR.js → chunk-5LJAQTSS.js} +1 -1
  10. package/dist/{chunk-W4TSQ6RJ.js → chunk-7AJKUA36.js} +1 -1
  11. package/dist/{chunk-RD52SNH2.js → chunk-7EJTWGKW.js} +1 -1
  12. package/dist/{chunk-GNCBXARM.js → chunk-7EQPXQ7H.js} +1 -1
  13. package/dist/chunk-7QMVU3IX.js +1 -0
  14. package/dist/{chunk-BA5URFYW.js → chunk-A4JT4SAD.js} +1 -1
  15. package/dist/chunk-ASDKRNOJ.js +60 -0
  16. package/dist/{chunk-Y32RJO24.js → chunk-CZVYLXFK.js} +1 -1
  17. package/dist/{chunk-567NWZ3T.js → chunk-DWIAG62L.js} +1 -1
  18. package/dist/{chunk-33FA6V4B.js → chunk-EBQ6FXKW.js} +1 -1
  19. package/dist/chunk-FTA5TB2A.js +1 -0
  20. package/dist/{chunk-P7JXGKDO.js → chunk-GF5T7PGC.js} +1 -1
  21. package/dist/{chunk-WANIEEKV.js → chunk-I4U3TPK2.js} +1 -1
  22. package/dist/{chunk-KA6MMXIY.js → chunk-JMGGCSIC.js} +1 -1
  23. package/dist/chunk-JXRZXP3N.js +1 -0
  24. package/dist/{chunk-5Z4HDCO6.js → chunk-K54OKWNY.js} +1 -1
  25. package/dist/{chunk-DDPYNMGG.js → chunk-KN4Q5MQO.js} +1 -1
  26. package/dist/chunk-LWGLBCMU.js +1 -0
  27. package/dist/{chunk-TWMEGG45.js → chunk-N2KKISCE.js} +1 -1
  28. package/dist/{chunk-4OFIQ66T.js → chunk-OKQUPJRY.js} +1 -1
  29. package/dist/chunk-PNTBXOQ6.js +5 -0
  30. package/dist/chunk-PSQNYY72.js +7 -0
  31. package/dist/{chunk-XHVB6G6M.js → chunk-PZP4MEXK.js} +1 -1
  32. package/dist/{chunk-7TDOES3L.js → chunk-Q2SY7M7K.js} +1 -1
  33. package/dist/{chunk-OL33ZI6R.js → chunk-RWGJQQLT.js} +1 -1
  34. package/dist/chunk-SGS4OJGS.js +1 -0
  35. package/dist/chunk-UMH3HSP7.js +1 -0
  36. package/dist/{chunk-BZP5T4X6.js → chunk-W6FQIFVE.js} +1 -1
  37. package/dist/{chunk-SHYH5SXV.js → chunk-WLPVGXQ6.js} +1 -1
  38. package/dist/chunk-WQ7I7JVU.js +1 -0
  39. package/dist/{chunk-XQAXYVXX.js → chunk-WYJTXYWX.js} +1 -1
  40. package/dist/{chunk-3NEPQO2E.js → chunk-X2VHDT26.js} +1 -1
  41. package/dist/{chunk-GLSM33ZM.js → chunk-XEFAMCEA.js} +1 -1
  42. package/dist/{chunk-AUY2YKCO.js → chunk-XRSHMHEG.js} +1 -1
  43. package/dist/chunk-Y26UN6J5.js +18 -0
  44. package/dist/{chunk-BKPLTBL5.js → chunk-YQJPYEAL.js} +1 -1
  45. package/dist/{chunk-73Z3W2RN.js → chunk-YZ6VYLFD.js} +1 -1
  46. package/dist/{chunk-4JJCCD5S.js → chunk-YZKGGMPT.js} +1 -1
  47. package/dist/chunk-Z3UWIJ3A.js +1 -0
  48. package/dist/{chunk-Y36UZ5VS.js → chunk-ZM7C2FUM.js} +1 -1
  49. package/dist/compat/index.cjs +1 -1
  50. package/dist/compat/index.js +1 -1
  51. package/dist/compat/jotai/index.cjs +1 -1
  52. package/dist/compat/jotai/index.js +1 -1
  53. package/dist/compat/nanostores/index.cjs +1 -1
  54. package/dist/compat/nanostores/index.js +1 -1
  55. package/dist/compat/nestjs/index.cjs +5 -5
  56. package/dist/compat/nestjs/index.js +1 -1
  57. package/dist/compat/zustand/index.cjs +1 -1
  58. package/dist/compat/zustand/index.js +1 -1
  59. package/dist/{composite-DGspwCqk.d.ts → composite-BY9hMxN7.d.ts} +1 -1
  60. package/dist/{composite-nrRumJ7l.d.cts → composite-CH0S8DFn.d.cts} +1 -1
  61. package/dist/content-addressed-storage-BUiREIuj.d.ts +124 -0
  62. package/dist/content-addressed-storage-DqIWCmZG.d.cts +124 -0
  63. package/dist/core/index.cjs +1 -1
  64. package/dist/core/index.js +1 -1
  65. package/dist/extra/browser.cjs +1 -1
  66. package/dist/extra/browser.js +1 -1
  67. package/dist/extra/index.cjs +18 -18
  68. package/dist/extra/index.d.cts +6 -5
  69. package/dist/extra/index.d.ts +6 -5
  70. package/dist/extra/index.js +1 -1
  71. package/dist/extra/node.cjs +2 -2
  72. package/dist/extra/node.js +1 -1
  73. package/dist/extra/operators.cjs +1 -1
  74. package/dist/extra/operators.d.cts +41 -1
  75. package/dist/extra/operators.d.ts +41 -1
  76. package/dist/extra/operators.js +1 -1
  77. package/dist/extra/reactive.cjs +1 -1
  78. package/dist/extra/reactive.d.cts +1 -1
  79. package/dist/extra/reactive.d.ts +1 -1
  80. package/dist/extra/reactive.js +1 -1
  81. package/dist/extra/sources.cjs +1 -1
  82. package/dist/extra/sources.d.cts +62 -2
  83. package/dist/extra/sources.d.ts +62 -2
  84. package/dist/extra/sources.js +1 -1
  85. package/dist/extra/storage-browser.cjs +1 -1
  86. package/dist/extra/storage-browser.js +1 -1
  87. package/dist/{fallback-BaTS7vVY.d.cts → fallback-Cb3GH1O7.d.cts} +6 -14
  88. package/dist/{fallback-eOm3LNxP.d.ts → fallback-DRjJ_ZM8.d.ts} +6 -14
  89. package/dist/graph/index.cjs +4 -4
  90. package/dist/graph/index.js +1 -1
  91. package/dist/{index-ClB7TCfL.d.cts → index-BMe3pCom.d.cts} +1 -1
  92. package/dist/{index-Dljd76bC.d.ts → index-BXzl1NDD.d.ts} +1 -1
  93. package/dist/{index-ClgKmOHe.d.ts → index-Bd6oFZqO.d.ts} +223 -115
  94. package/dist/{index-BJHQUCZx.d.ts → index-CJymKyzT.d.ts} +81 -6
  95. package/dist/{index-D6ajK8Mh.d.cts → index-CZChc85Q.d.cts} +223 -115
  96. package/dist/{index-BXbQUn4n.d.ts → index-CcS0t-l2.d.ts} +1 -1
  97. package/dist/{index-B2HBxvMb.d.ts → index-CwhcFzTA.d.ts} +1 -1
  98. package/dist/{index-B8Aj_z8S.d.cts → index-D-kHVedZ.d.cts} +1 -1
  99. package/dist/{index-ybtSyjWB.d.cts → index-DD7RhHNJ.d.cts} +1 -1
  100. package/dist/{index-BHu_Wba0.d.cts → index-Dm3_D5Ta.d.cts} +1 -1
  101. package/dist/{index-Cc8VQIgL.d.ts → index-DxMS0cHM.d.ts} +1 -1
  102. package/dist/{index-BS220yqj.d.cts → index-gJQqJTKx.d.cts} +81 -6
  103. package/dist/index.cjs +99 -121
  104. package/dist/index.d.cts +14 -13
  105. package/dist/index.d.ts +14 -13
  106. package/dist/index.js +1 -1
  107. package/dist/patterns/ai/browser.cjs +5 -22
  108. package/dist/patterns/ai/browser.d.cts +3 -3
  109. package/dist/patterns/ai/browser.d.ts +3 -3
  110. package/dist/patterns/ai/browser.js +1 -1
  111. package/dist/patterns/ai/index.cjs +27 -44
  112. package/dist/patterns/ai/index.d.cts +9 -7
  113. package/dist/patterns/ai/index.d.ts +9 -7
  114. package/dist/patterns/ai/index.js +1 -1
  115. package/dist/patterns/ai/node.cjs +2 -2
  116. package/dist/patterns/ai/node.d.cts +5 -4
  117. package/dist/patterns/ai/node.d.ts +5 -4
  118. package/dist/patterns/ai/node.js +1 -1
  119. package/dist/patterns/audit/index.cjs +3 -3
  120. package/dist/patterns/audit/index.js +1 -1
  121. package/dist/patterns/cqrs/index.cjs +6 -6
  122. package/dist/patterns/cqrs/index.js +1 -1
  123. package/dist/patterns/demo-shell/index.cjs +1 -1
  124. package/dist/patterns/demo-shell/index.js +1 -1
  125. package/dist/patterns/domain-templates/index.cjs +4 -4
  126. package/dist/patterns/domain-templates/index.js +1 -1
  127. package/dist/patterns/graphspec/index.cjs +6 -6
  128. package/dist/patterns/graphspec/index.d.cts +2 -2
  129. package/dist/patterns/graphspec/index.d.ts +2 -2
  130. package/dist/patterns/graphspec/index.js +1 -1
  131. package/dist/patterns/guarded-execution/index.cjs +7 -7
  132. package/dist/patterns/guarded-execution/index.js +1 -1
  133. package/dist/patterns/harness/index.cjs +11 -11
  134. package/dist/patterns/harness/index.d.cts +2 -2
  135. package/dist/patterns/harness/index.d.ts +2 -2
  136. package/dist/patterns/harness/index.js +1 -1
  137. package/dist/patterns/job-queue/index.cjs +5 -5
  138. package/dist/patterns/job-queue/index.js +1 -1
  139. package/dist/patterns/lens/index.cjs +5 -5
  140. package/dist/patterns/lens/index.d.cts +2 -2
  141. package/dist/patterns/lens/index.d.ts +2 -2
  142. package/dist/patterns/lens/index.js +1 -1
  143. package/dist/patterns/memory/index.cjs +4 -4
  144. package/dist/patterns/memory/index.js +1 -1
  145. package/dist/patterns/messaging/index.cjs +5 -5
  146. package/dist/patterns/messaging/index.js +1 -1
  147. package/dist/patterns/orchestration/index.cjs +1 -1
  148. package/dist/patterns/orchestration/index.js +1 -1
  149. package/dist/patterns/reactive-layout/index.cjs +1 -1
  150. package/dist/patterns/reactive-layout/index.js +1 -1
  151. package/dist/patterns/reduction/index.cjs +5 -5
  152. package/dist/patterns/reduction/index.js +1 -1
  153. package/dist/patterns/refine-loop/index.cjs +8 -8
  154. package/dist/patterns/refine-loop/index.js +1 -1
  155. package/dist/patterns/resilient-pipeline/index.cjs +1 -1
  156. package/dist/patterns/resilient-pipeline/index.js +1 -1
  157. package/dist/patterns/surface/index.cjs +7 -7
  158. package/dist/patterns/surface/index.d.cts +3 -3
  159. package/dist/patterns/surface/index.d.ts +3 -3
  160. package/dist/patterns/surface/index.js +1 -1
  161. package/dist/{reactive-map-BvDrRuwt.d.ts → reactive-map-CtRaCddO.d.ts} +59 -1
  162. package/dist/{reactive-map-CmlPPKHN.d.cts → reactive-map-IJIfZxoh.d.cts} +59 -1
  163. package/dist/{resilience-XRUF267O.js → resilience-IVNDYORD.js} +1 -1
  164. package/dist/{types-O3GzJY2U.d.cts → types-BgMqbc7N.d.cts} +41 -14
  165. package/dist/{types-u64Ose53.d.ts → types-CdfO2QTt.d.ts} +41 -14
  166. package/package.json +1 -1
  167. package/dist/chunk-2GQREQ6C.js +0 -1
  168. package/dist/chunk-4C2OR2GH.js +0 -18
  169. package/dist/chunk-5JDE5JHE.js +0 -1
  170. package/dist/chunk-7JDLFI6N.js +0 -1
  171. package/dist/chunk-AMBYCIOH.js +0 -3
  172. package/dist/chunk-ISCENNXS.js +0 -1
  173. package/dist/chunk-IUK4EFCE.js +0 -1
  174. package/dist/chunk-KASHOCF5.js +0 -1
  175. package/dist/chunk-LI3E75VE.js +0 -64
  176. package/dist/chunk-MGKAO4EK.js +0 -7
  177. package/dist/chunk-NSG4C6BF.js +0 -23
  178. package/dist/chunk-VIEUJSTT.js +0 -1
package/dist/index.cjs CHANGED
@@ -1,131 +1,52 @@
1
- "use strict";var xp=Object.create;var wn=Object.defineProperty;var du=Object.getOwnPropertyDescriptor;var Rp=Object.getOwnPropertyNames;var Sp=Object.prototype.hasOwnProperty;var lu=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),tr=t=>{throw TypeError(t)};var Np=(t,e,n)=>e in t?wn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var au=(t,e)=>wn(t,"name",{value:e,configurable:!0});var Ue=(t,e)=>()=>(t&&(e=t(t=0)),e);var he=(t,e)=>{for(var n in e)wn(t,n,{get:e[n],enumerable:!0})},Ep=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Rp(e))!Sp.call(t,o)&&o!==n&&wn(t,o,{get:()=>e[o],enumerable:!(r=du(e,o))||r.enumerable});return t};var _p=t=>Ep(wn({},"__esModule",{value:!0}),t);var pu=t=>[,,,xp(t?.[lu("metadata")]??null)],fu=["class","method","getter","setter","accessor","field","value","get","set"],er=t=>t!==void 0&&typeof t!="function"?tr("Function expected"):t,Mp=(t,e,n,r,o)=>({kind:fu[t],name:e,metadata:r,addInitializer:s=>n._?tr("Already initialized"):o.push(er(s||null))}),Op=(t,e)=>Np(e,lu("metadata"),t[3]),mu=(t,e,n,r)=>{for(var o=0,s=t[e>>1],i=s&&s.length;o<i;o++)e&1?s[o].call(n):r=s[o].call(n,r);return r},hu=(t,e,n,r,o,s)=>{var i,a,u,c,d,l=e&7,f=!!(e&8),p=!!(e&16),m=l>3?t.length+1:l?f?1:2:0,h=fu[l+5],g=l>3&&(t[m-1]=[]),y=t[m]||(t[m]=[]),b=l&&(!p&&!f&&(o=o.prototype),l<5&&(l>3||!p)&&du(l<4?o:{get[n](){return uu(this,s)},set[n](T){return cu(this,s,T)}},n));l?p&&l<4&&au(s,(l>2?"set ":l>1?"get ":"")+n):au(o,n);for(var v=r.length-1;v>=0;v--)c=Mp(l,n,u={},t[3],y),l&&(c.static=f,c.private=p,d=c.access={has:p?T=>Cp(o,T):T=>n in T},l^3&&(d.get=p?T=>(l^1?uu:Ap)(T,o,l^4?s:b.get):T=>T[n]),l>2&&(d.set=p?(T,w)=>cu(T,o,w,l^4?s:b.set):(T,w)=>T[n]=w)),a=(0,r[v])(l?l<4?p?s:b[h]:l>4?void 0:{get:b.get,set:b.set}:o,c),u._=1,l^4||a===void 0?er(a)&&(l>4?g.unshift(a):l?p?s=a:b[h]=a:o=a):typeof a!="object"||a===null?tr("Object expected"):(er(i=a.get)&&(b.get=i),er(i=a.set)&&(b.set=i),er(i=a.init)&&g.unshift(i));return l||Op(t,o),b&&wn(o,n,b),p?l^4?s:b:o};var ri=(t,e,n)=>e.has(t)||tr("Cannot "+n),Cp=(t,e)=>Object(e)!==e?tr('Cannot use the "in" operator on this value'):t.has(e),uu=(t,e,n)=>(ri(t,e,"read from private field"),n?n.call(t):e.get(t));var cu=(t,e,n,r)=>(ri(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),Ap=(t,e,n)=>(ri(t,e,"access private method"),n);var dt,S,ee,B,He,Ie,Ge,de,_,M,yt,kn,Zr,xn,eo,to,Rn,nr,rr,or,Sn,ie=Ue(()=>{"use strict";dt=Symbol.for("graphrefly/START"),S=Symbol.for("graphrefly/DATA"),ee=Symbol.for("graphrefly/DIRTY"),B=Symbol.for("graphrefly/RESOLVED"),He=Symbol.for("graphrefly/INVALIDATE"),Ie=Symbol.for("graphrefly/PAUSE"),Ge=Symbol.for("graphrefly/RESUME"),de=Symbol.for("graphrefly/TEARDOWN"),_=Symbol.for("graphrefly/COMPLETE"),M=Symbol.for("graphrefly/ERROR"),yt=Object.freeze([ee]),kn=Object.freeze([B]),Zr=Object.freeze([He]),xn=Object.freeze([dt]),eo=Object.freeze([_]),to=Object.freeze([de]),Rn=Object.freeze([yt]),nr=Object.freeze([kn]),rr=Object.freeze([Zr]),or=Object.freeze([eo]),Sn=Object.freeze([to])});function oi(t){return{name:"dag-cbor",version:1,contentType:"application/dag-cbor",encode:e=>t.encode(e),decode:(e,n)=>t.decode(e)}}function si(t,e){return{name:"dag-cbor-zstd",version:1,contentType:"application/dag-cbor+zstd",encode:n=>e.compressSync(t.encode(n)),decode:(n,r)=>t.decode(e.decompressSync(n))}}function sr(t,e){let n=new TextEncoder().encode(t.name);if(n.length===0||n.length>255)throw new Error(`encodeEnvelope: codec name "${t.name}" encodes to ${n.length} bytes (must be 1\u2013255)`);let r=t.version;if(!Number.isInteger(r)||r<0||r>65535)throw new Error(`encodeEnvelope: codec.version ${r} out of u16 range (expected integer 0\u201365535)`);let o=2+n.length+2+e.length;if(o>4294967295)throw new Error(`encodeEnvelope: total envelope size ${o} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let s=new Uint8Array(o),i=0;return s[i++]=Nn,s[i++]=n.length,s.set(n,i),i+=n.length,s[i++]=r>>>8&255,s[i++]=r&255,s.set(e,i),s}function ir(t,e){if(t.length<gu)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${gu})`);let n=0,r=t[n++];if(r!==Nn)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${Nn})`);let o=t[n++];if(o===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(n+o+2>t.length)throw new Error(`decodeEnvelope: envelope truncated (need ${n+o+2} bytes, have ${t.length})`);let s=new TextDecoder().decode(t.subarray(n,n+o));n+=o;let i=(t[n]<<8|t[n+1])>>>0;n+=2;let a=t.subarray(n),u=e.lookupCodec(s);if(u==null)throw new Error(`decodeEnvelope: codec "${s}" not registered (envelope codec_v=${i})`);return{codec:u,codecVersion:i,payload:a}}function ar(t){t.registerCodec(no)}function ii(t){if(t.length===0)throw new Error("WAL is empty \u2014 need at least one full snapshot");let e=t[0];if(e.mode!=="full")throw new Error("WAL must start with a full record carrying a baseline snapshot");let n=JSON.parse(JSON.stringify(e.snapshot)),r=e.seq;for(let o=1;o<t.length;o++){let s=t[o];if(s.seq<=r)throw new Error(`WAL chain broken at index ${o}: seq=${s.seq} must exceed prev seq=${r}`);if(s.mode==="full"){n=JSON.parse(JSON.stringify(s.snapshot)),r=s.seq;continue}let i=s.diff;for(let u of i.nodesRemoved)delete n.nodes[u];let a=i.nodesAddedFull;if(a!=null)for(let[u,c]of Object.entries(a))n.nodes[u]=JSON.parse(JSON.stringify(c));for(let u of i.nodesChanged){let c=n.nodes[u.path];c!=null&&(c[u.field]=u.to)}r=s.seq}return n}var no,Nn,gu,ro=Ue(()=>{"use strict";no={name:"json",version:1,contentType:"application/json",encode(t){let e=JSON.stringify(t);return new TextEncoder().encode(e)},decode(t,e){let n=new TextDecoder().decode(t);return JSON.parse(n)}};Nn=1,gu=4});function bt(t){if(t==null)return lt;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var lt,ur=Ue(()=>{"use strict";lt={type:"system",id:""}});function zt(){return En>0||cr}function yu(){return En>0}function lr(t){En>0?dr.push(t):t()}function te(t){En+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(En-=1,En===0)if(e){if(!cr){let n=dr.splice(0);for(let r of n)try{r()}catch{}qt.length=0,Ut.length=0,_n.length=0}}else Lp()}}function Lp(){let t=!cr;t&&(cr=!0);let e=[],n=0;try{for(;qt.length>0||Ut.length>0||_n.length>0||t&&dr.length>0;){if(t&&dr.length>0){let s=dr.splice(0);for(let i of s)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw qt.length=0,Ut.length=0,_n.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let o=(qt.length>0?qt:Ut.length>0?Ut:_n).splice(0);for(let s of o)try{s()}catch(i){e.push(i)}}}finally{t&&(cr=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function vt(t,e,n){if(e.length===0)return;if(e.length===1){let c=n(e[0][0]);if(c<3||!zt()){t(e);return}(c>=5?_n:c===4?Ut:qt).push(()=>t(e));return}let r=e.length,o=r,s=r,i=r,a=0;for(;a<r&&n(e[a][0])<3;)a++;for(o=a;a<r&&n(e[a][0])===3;)a++;for(s=a;a<r&&n(e[a][0])===4;)a++;i=a;let u=zt();if(o>0){let c=e.slice(0,o);t(c)}if(s>o){let c=e.slice(o,s);u?qt.push(()=>t(c)):t(c)}if(i>s){let c=e.slice(s,i);u?Ut.push(()=>t(c)):t(c)}if(r>i){let c=e.slice(i,r);u?_n.push(()=>t(c)):t(c)}}var En,cr,qt,Ut,_n,dr,Ne=Ue(()=>{"use strict";En=0,cr=!1,qt=[],Ut=[],_n=[],dr=[]});function $(){return Math.trunc(performance.now()*1e6)}function pe(){return Date.now()*1e6}var ke=Ue(()=>{"use strict"});function pr(t){t.registerMessageType(dt,{tier:0,wireCrossing:!1}),t.registerMessageType(ee,{tier:1,wireCrossing:!1}),t.registerMessageType(He,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(Ie,{tier:2,wireCrossing:!1}),t.registerMessageType(Ge,{tier:2,wireCrossing:!1}),t.registerMessageType(S,{tier:3,wireCrossing:!0}),t.registerMessageType(B,{tier:3,wireCrossing:!0}),t.registerMessageType(_,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(M,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(de,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var Jt,ai=Ue(()=>{"use strict";ie();Jt=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=n=>{let r=this._messageTypes.get(n);return r!=null?r.tier:1}}get onMessage(){return this._frozen=!0,this._onMessage}get onSubscribe(){return this._frozen=!0,this._onSubscribe}set onMessage(e){this._assertUnfrozen(),this._onMessage=e}set onSubscribe(e){this._assertUnfrozen(),this._onSubscribe=e}get defaultVersioning(){return this._defaultVersioning}set defaultVersioning(e){this._assertUnfrozen(),this._defaultVersioning=e}get defaultHashFn(){return this._defaultHashFn}set defaultHashFn(e){this._assertUnfrozen(),this._defaultHashFn=e}get inspectorEnabled(){return this._inspectorEnabled}set inspectorEnabled(e){this._inspectorEnabled=e}get globalInspector(){return this._globalInspector}set globalInspector(e){this._globalInspector=e}registerMessageType(e,n){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:n.tier,wireCrossing:n.wireCrossing??n.tier>=3,metaPassthrough:n.metaPassthrough??!0}),this}messageTier(e){let n=this._messageTypes.get(e);return n!=null?n.tier:1}isWireCrossing(e){let n=this._messageTypes.get(e);return n!=null?n.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let n=this._messageTypes.get(e);return n!=null?n.metaPassthrough:!0}isKnownMessageType(e){return this._messageTypes.has(e)}registerCodec(e){return this._assertUnfrozen(),this._codecs.set(e.name,e),this}lookupCodec(e){return this._codecs.get(e)}_isFrozen(){return this._frozen}_assertUnfrozen(){if(this._frozen)throw new Error("GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node.")}}});function bu(t){return Array.isArray(t)?[...t]:[t]}function Ip(t,e){return t.has(e)||t.has("*")}function Yt(t){let e=[];return t((o,s)=>{e.push({kind:"allow",actions:new Set(bu(o)),where:s?.where??(()=>!0)})},(o,s)=>{e.push({kind:"deny",actions:new Set(bu(o)),where:s?.where??(()=>!0)})}),(o,s)=>{let i=!1,a=!1;for(let u of e)Ip(u.actions,s)&&u.where(o)&&(u.kind==="deny"?i=!0:a=!0);return i?!1:a}}function fr(t){return Yt((e,n)=>{for(let r of t){let o=r.actorType==null?null:new Set(Array.isArray(r.actorType)?r.actorType:[r.actorType]),s=r.actorId==null?null:new Set(Array.isArray(r.actorId)?r.actorId:[r.actorId]),i=Object.entries(r.claims??{}),a=u=>{if(o!==null&&!o.has(String(u.type))||s!==null&&!s.has(String(u.id??"")))return!1;for(let[c,d]of i)if(u[c]!==d)return!1;return!0};r.effect==="deny"?n(r.action,{where:a}):e(r.action,{where:a})}})}function mr(t){let e=Pp.filter(n=>t({type:n,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(n=>n==="human"||n==="llm"||n==="system")?"both":e.length===1?e[0]:e.join("+")}var Je,Pp,Qt=Ue(()=>{"use strict";Je=class extends Error{actor;action;nodeName;constructor(e,n){super(n??`GuardDenied: action "${String(e.action)}" denied for actor type "${String(e.actor.type)}"`),this.name="GuardDenied",this.actor=e.actor,this.action=e.action,this.nodeName=e.nodeName}get node(){return this.nodeName}};Pp=["human","llm","wallet","system"]});function ui(t){if(t===void 0)return null;if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`Cannot hash non-finite number: ${t}`);if(Number.isInteger(t)&&!Number.isSafeInteger(t))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${t}. Cross-language cid parity is not guaranteed for unsafe integers.`);return t}if(typeof t=="string"||typeof t=="boolean"||t===null)return t;if(Array.isArray(t))return t.map(ui);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=ui(t[n]);return e}return null}function Fp(t){let e=Gp.encode(t),n=e.length,r=n*8,o=n+9+63&-64,s=new Uint8Array(o);s.set(e),s[n]=128;let i=new DataView(s.buffer);i.setUint32(o-4,r>>>0,!1),i.setUint32(o-8,Math.floor(r/4294967296)>>>0,!1);let a=1779033703,u=3144134277,c=1013904242,d=2773480762,l=1359893119,f=2600822924,p=528734635,m=1541459225,h=new Uint32Array(64),g=(b,v)=>b>>>v|b<<32-v;for(let b=0;b<o;b+=64){for(let L=0;L<16;L++)h[L]=i.getUint32(b+L*4,!1);for(let L=16;L<64;L++){let P=h[L-15],C=h[L-2],V=g(P,7)^g(P,18)^P>>>3,ne=g(C,17)^g(C,19)^C>>>10;h[L]=h[L-16]+V+h[L-7]+ne>>>0}let v=a,T=u,w=c,k=d,x=l,R=f,E=p,G=m;for(let L=0;L<64;L++){let P=g(x,6)^g(x,11)^g(x,25),C=x&R^~x&E,V=G+P+C+Dp[L]+h[L]>>>0,ne=g(v,2)^g(v,13)^g(v,22),F=v&T^v&w^T&w,A=ne+F>>>0;G=E,E=R,R=x,x=k+V>>>0,k=w,w=T,T=v,v=V+A>>>0}a=a+v>>>0,u=u+T>>>0,c=c+w>>>0,d=d+k>>>0,l=l+x>>>0,f=f+R>>>0,p=p+E>>>0,m=m+G>>>0}let y=b=>b.toString(16).padStart(8,"0");return y(a)+y(u)+y(c)+y(d)+y(l)+y(f)+y(p)+y(m)}function Ot(t){let e=ui(t??null),n=JSON.stringify(e);return Fp(n).slice(0,16)}function $p(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),n=e()+e()+e()+e();return`${n.slice(0,8)}-${n.slice(8,12)}-4${n.slice(13,16)}-${(parseInt(n.slice(16,17),16)&3|8).toString(16)}${n.slice(17,20)}-${n.slice(20,32)}`}function Mn(t,e,n){let r=n?.id??$p();if(t===0)return{id:r,version:0};let s=(n?.hash??Ot)(e);return{id:r,version:0,cid:s,prev:null}}function hr(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}function ci(t){return"cid"in t}var Dp,Gp,oo=Ue(()=>{"use strict";Dp=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Gp=new TextEncoder});function wu(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function di(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function so(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function pi(t){if(Ae._isFrozen())throw new Error("configure() called after a node was created \u2014 the default GraphReFlyConfig is frozen. Call configure(...) at application startup, before any node factories run.");t(Ae)}function K(t,e,n){let r=ku(t)?t:[],o=typeof t=="function"?t:typeof e=="function"?e:void 0,s={};return ku(t)?s=(li(e)?e:n)??{}:li(t)?s=t:s=(li(e)?e:n)??{},new Ee(r,o,s)}var vu,Tu,Bp,jp,Ae,Ee,ku,li,xe=Ue(()=>{"use strict";ro();ur();Ne();ke();ai();Qt();ie();oo();vu=()=>{},Tu=100;Bp=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},jp=(t,e,n,r)=>{let o=t;if(o._status==="completed"||o._status==="errored")return;let s=o._cached,i=s===void 0?[xn]:[xn,[S,s]];o._status==="dirty"&&i.push(yt),vt(e,i,o._config.tierOf)},Ae=new Jt({onMessage:Bp,onSubscribe:jp});pr(Ae);ar(Ae);Ee=class t{_optsName;_describeKind;meta;_hasMeta;_config;_deps;_sinks=null;_sinkCount=0;_cached;_status;_cleanup;_store={};_waveHasNewData=!1;_hasNewTerminal=!1;_hasCalledFnOnce=!1;_paused=!1;_pendingWave=!1;_isExecutingFn=!1;_pendingRerun=!1;_rerunDepth=0;_dirtyDepCount=0;_batchPendingMessages=null;_pauseLocks=null;_pauseBuffer=null;_fn;_equals;_resubscribable;_resetOnTeardown;_autoComplete;_autoError;_pausable;_partial;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,n,r){this._config=r.config??Ae,this._config.onMessage,this._optsName=r.name,this._describeKind=r.describeKind,this._equals=r.equals??Object.is,this._resubscribable=r.resubscribable??!1,this._resetOnTeardown=r.resetOnTeardown??!1,this._autoComplete=r.completeWhenDepsComplete??!0,this._autoError=r.errorWhenDepsError??!0,this._pausable=r.pausable??!0,this._guard=r.guard,this._fn=n,this._partial=r.partial??!1,this._cached=r.initial!==void 0?r.initial:void 0,this._status=e.length===0&&n==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=r.versioningHash??this._config.defaultHashFn??Ot;let o=r.versioning??this._config.defaultVersioning;this._versioningLevel=o,this._versioning=o!=null?Mn(o,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(wu);let s={};for(let[a,u]of Object.entries(r.meta??{})){let c={initial:u,name:`${r.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};r.guard!=null&&(c.guard=r.guard),s[a]=new t([],void 0,c)}Object.freeze(s),this.meta=s,this._hasMeta=Object.keys(s).length>0;let i=this;this._actions={emit(a){i._emit([[S,a]])},down(a){i._emit(so(a))},up(a){i._emitUp(so(a))}},this.down=this.down.bind(this),this.up=this.up.bind(this)}get _isTerminal(){return this._status==="completed"||this._status==="errored"}get name(){return this._optsName}get status(){return this._status}get cache(){return this._cached===void 0?void 0:this._cached}get lastMutation(){return this._lastMutation}get v(){return this._versioning}hasGuard(){return this._guard!=null}_applyVersioning(e,n){if(this._isExecutingFn)throw new Error(`Node "${this.name}": _applyVersioning cannot run mid-fn \u2014 call it outside of \`_execFn\` (typically at graph setup time before the first subscribe).`);let r=this._versioningLevel;if(r!=null&&e<=r)return;let o=n?.hash??this._hashFn;o!==this._hashFn&&(this._hashFn=o);let s=this._cached===void 0?void 0:this._cached,i=this._versioning,a=i?.id??n?.id,u=i?.version??0,c=Mn(e,s,{id:a,hash:o});c.version=u,this._versioning=c,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let n=bt(e);if(this._guard!=null&&!this._guard(n,"observe"))return!1;if(this._extraGuards!=null){for(let r of this._extraGuards)if(!r(n,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let n=this._guard!=null||this._extraGuards!=null,r=e?.actor!=null;if(!n&&!r)return;let o=bt(e?.actor),s=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(o,s))throw new Je({actor:o,action:s,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(o,s))throw new Je({actor:o,action:s,nodeName:this.name})}this._lastMutation={actor:o,timestamp_ns:pe()}}down(e,n){let r=so(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[S,e]])}up(e,n){if(this._deps.length===0)return;let r=so(e);if(r.length===0)return;this._checkGuard(n);let o=n??{internal:!0};this._validateUpTiers(r);for(let s of this._deps)s.node.up?.(r,o)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let n of this._deps)n.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let n=this._config.tierOf;for(let r of e){let o=n(r[0]);if(o===3||o===4)throw new Error(`Node "${this.name}": tier-${o} messages cannot flow up \u2014 DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \`down(...)\` for value delivery; \`up(...)\` is for control signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).`)}}subscribe(e,n){if(n!=null&&this._guard!=null){let u=bt(n);if(!this._guard(u,"observe"))throw new Je({actor:u,action:"observe",nodeName:this.name})}let o=this._isTerminal&&this._resubscribable;if(o){this._cached=void 0,this._status="sentinel",this._store={},this._hasCalledFnOnce=!1,this._waveHasNewData=!1,this._hasNewTerminal=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._isExecutingFn=!1,this._rerunDepth=0,this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null;for(let u of this._deps)di(u);if(this._partial===!1){for(let u of this._deps)if(u.prevData!==void 0||u.dataBatch.length!==0||u.terminal!==void 0||u.dirty)throw new Error(`resubscribable-reset invariant: DepRecord not fully reset for node ${this._optsName??"(anonymous)"}`)}}this._sinkCount+=1;let s;try{s=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:o},this._actions)}catch(u){throw this._sinkCount-=1,u}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let i=this._isTerminal;if(this._sinkCount===1&&!i)try{this._activate()}catch(u){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof s=="function")try{s()}catch{}throw u}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let a=!1;return()=>{a||(a=!0,this._sinkCount-=1,this._removeSink(e),typeof s=="function"&&s(),this._sinks==null&&this._deactivate())}}_removeSink(e){if(this._sinks===e)this._sinks=null;else if(this._sinks!=null&&typeof this._sinks!="function")if(this._sinks.delete(e),this._sinks.size===1){let[n]=this._sinks;this._sinks=n}else this._sinks.size===0&&(this._sinks=null)}_activate(){if(this._deps.length===0){this._fn&&this._execFn();return}this._dirtyDepCount=0;let e=this._deps.length,n=0;try{for(let r=0;r<e;r++){let o=r,s=this._deps[r];s.unsub=vu,s.unsub=s.node.subscribe(i=>{if(s.unsub===null)return;let a=this._config.tierOf,u=!1;for(let c of i)a(c[0])>=3&&(u=!0),this._config.onMessage(this,c,{direction:"down-in",depIndex:o},this._actions);u&&this._maybeRunFnOnSettlement()}),n++}}catch(r){this._deps[n].unsub=null;for(let o=0;o<n;o++){let s=this._deps[o];if(s.unsub!=null){let i=s.unsub;s.unsub=null;try{i()}catch{}di(s)}}throw this._dirtyDepCount=0,r}}_addDep(e){for(let o=0;o<this._deps.length;o++)if(this._deps[o].node===e)return o;let n=this._deps.length,r=wu(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Rn),r.unsub=vu;try{r.unsub=e.subscribe(o=>{if(r.unsub===null)return;let s=this._config.tierOf,i=!1;for(let a of o)s(a[0])>=3&&(i=!0),this._config.onMessage(this,a,{direction:"down-in",depIndex:n},this._actions);i&&this._maybeRunFnOnSettlement()})}catch(o){throw r.unsub=null,this._deps.pop(),this._dirtyDepCount--,o}return n}_deactivate(e=!1){let n=this._cleanup;if(this._cleanup=void 0,typeof n=="function")try{n()}catch(r){this._emit([[M,this._wrapFnError("cleanup threw",r)]])}else if(n!=null&&typeof n=="object"){let r=n.deactivate;if(typeof r=="function")try{r()}catch(o){this._emit([[M,this._wrapFnError("cleanup.deactivate threw",o)]])}}for(let r of this._deps){if(r.unsub!=null){let o=r.unsub;r.unsub=null;try{o()}catch{}}di(r)}this._waveHasNewData=!1,this._hasNewTerminal=!1,this._hasCalledFnOnce=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._rerunDepth=0,this._store={},this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null,this._fn!=null&&(this._cached=void 0),e||(this._fn!=null||this._deps.length>0)&&(!this._isTerminal||this._resubscribable)&&(this._status="sentinel")}_onDepMessage(e,n){let r=this._deps[e],o=n[0];if(this._inspectorHooks!=null){let s={kind:"dep_message",depIndex:e,message:n};for(let i of this._inspectorHooks)i(s)}if(o!==dt){if(o===ee){this._depDirtied(r);return}if(o===He){this._depInvalidated(r),this._emit(rr);return}if(o===Ie||o===Ge){this._emit([n]);return}if(o===de){this._emit(Sn);return}if(o===S)this._depSettledAsData(r,n[1]);else if(o===B)this._depSettledAsResolved(r);else if(o===_)this._depSettledAsTerminal(r,!0);else if(o===M)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(o===S||o===B)&&this._emit([n]),(o===_||o===M)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Rn))}_depSettledAsData(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(n),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=n,e.involvedThisWave=!0,this._hasNewTerminal=!0}_depInvalidated(e){e.prevData=void 0,e.terminal=void 0,e.dataBatch.length=0,e.dirty?e.involvedThisWave=!1:(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++)}_maybeRunFnOnSettlement(){if(!(this._isTerminal&&!this._resubscribable)&&!(this._dirtyDepCount>0)){if(!this._partial&&!this._hasCalledFnOnce)for(let e=0;e<this._deps.length;e++){let n=this._deps[e];if(n.dataBatch.length===0&&n.prevData===void 0&&n.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(nr),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(n=>n.terminal!==void 0&&n.terminal!==!0);if(e!=null){this._autoError&&this._emit([[M,e.terminal]]);return}this._autoComplete&&this._deps.every(n=>n.terminal!==void 0)&&this._emit(or)}_execFn(){if(!this._fn||this._isTerminal&&!this._resubscribable)return;if(this._isExecutingFn){this._pendingRerun=!0;return}let e=this._cleanup;if(typeof e=="function"){this._cleanup=void 0;try{e()}catch(i){this._emit([[M,this._wrapFnError("cleanup threw",i)]]);return}}else if(e!=null&&typeof e=="object"){let i=e.beforeRun;if(typeof i=="function"){e.beforeRun=void 0;try{i()}catch(a){this._emit([[M,this._wrapFnError("cleanup.beforeRun threw",a)]]);return}}}let n=this._deps.map(i=>i.involvedThisWave?i.dataBatch.length>0?[...i.dataBatch]:[]:void 0),r=this._deps.map(i=>i.prevData);for(let i=0;i<this._deps.length;i++){let a=n[i];a!=null&&a.length>0&&(this._deps[i].prevData=a[a.length-1])}let o=this._deps.map(i=>i.terminal),s={prevData:r,terminalDeps:o,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let i={kind:"run",batchData:n,prevData:r};for(let a of this._inspectorHooks)a(i)}this._isExecutingFn=!0;try{let i=this._fn(n,this._actions,s);if(typeof i=="function")this._cleanup=i;else if(i!=null&&typeof i=="object"){let a=i;(typeof a.beforeRun=="function"||typeof a.deactivate=="function"||typeof a.invalidate=="function")&&(this._cleanup=i)}}catch(i){this._emit([[M,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>Tu?(this._rerunDepth=0,this._emit([[M,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${Tu} \u2014 likely a reactive cycle`)]])):this._maybeRunFnOnSettlement()):this._rerunDepth=0,this._clearWaveFlags()}}_clearWaveFlags(){this._waveHasNewData=!1,this._hasNewTerminal=!1;for(let e of this._deps)e.involvedThisWave=!1,e.dataBatch.length=0}_wrapFnError(e,n){let r=n instanceof Error?n.message:String(n);return new Error(`Node "${this.name}": ${e}: ${r}`,{cause:n})}_frameBatch(e){let n=this._config.tierOf;if(e.length===1)return n(e[0][0])===3&&this._status!=="dirty"?[yt,e[0]]:e;let r=!0,o=!1,s=!1,i=-1;for(let u of e){let c=n(u[0]);c<i&&(r=!1),c===3&&(o=!0),u[0]===ee&&(s=!0),i=c}let a=e;if(!r){let u=e.map((c,d)=>({m:c,i:d,tier:n(c[0])}));u.sort((c,d)=>c.tier-d.tier||c.i-d.i),a=u.map(c=>c.m)}if(o&&!s&&this._status!=="dirty"){let u=0;for(;u<a.length&&n(a[u][0])===0;)u++;return u===0?[yt,...a]:[...a.slice(0,u),yt,...a.slice(u)]}return a}_emit(e){if(e.length===0)return;for(let a=0;a<e.length;a++){let u=e[a];if(u[0]===M&&u[1]===void 0)throw new TypeError('[ERROR, payload] requires a non-undefined payload (spec \xA71.2). Pass an Error object or domain tag instead \u2014 e.g. node.down([[ERROR, new Error("reason")]])')}let n=e;if(this._isTerminal&&!this._resubscribable){let a=e.filter(u=>u[0]===de||u[0]===He);if(a.length===0)return;n=a}n=this._frameBatch(n);let o=null;for(let a=0;a<n.length;a++){let u=n[a],c=u[0];if(c!==Ie&&c!==Ge){o?.push(u);continue}if(u.length<2)throw new Error(`Node "${this.name}": [[${c===Ie?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let d=!0;if(this._pausable!==!1){let l=u[1];if(c===Ie)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(l),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(l))d=!1;else if(this._pauseLocks.delete(l),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let f=this._pauseBuffer;this._pauseBuffer=[],this._emit(f)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}d?o?.push(u):o==null&&(o=n.slice(0,a))}if(o!=null){if(o.length===0)return;n=o}if(this._hasMeta&&n.some(a=>a[0]===de))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(Sn)}catch{}let{finalMessages:s,equalsError:i}=this._updateState(n);if(s.length>0&&this._config.inspectorEnabled){let a=this._config.globalInspector;if(a!=null)try{a({kind:"emit",node:this,messages:s})}catch{}}if(s.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let a=this._config.tierOf,u=[];for(let c of s)a(c[0])===3?this._pauseBuffer.push(c):u.push(c);u.length>0&&this._dispatchOrAccumulate(u)}else this._dispatchOrAccumulate(s);i!=null&&this._emit([[M,i]])}_updateState(e){let n=this._config.tierOf,r,o,s=-1,i=0;for(let d of e)n(d[0])===3&&i++;let a=i<=1,u=-1;if(this._versioning!=null&&i>1){for(let d=e.length-1;d>=0;d--)if(e[d][0]===S){u=d;break}}for(let d=0;d<e.length;d++){let l=e[d],f=l[0];if(f===S){if(l.length>=2){let p=!1;if(a&&this._cached!==void 0)try{p=this._equals(this._cached,l[1])}catch(m){o=this._wrapFnError("equals threw",m),s=d;break}if(p){r==null&&(r=e.slice(0,d)),r.push(kn),this._status="resolved";continue}this._cached=l[1],this._versioning!=null&&(u<0||d===u)&&hr(this._versioning,l[1],this._hashFn)}this._status="settled",r?.push(l)}else if(r?.push(l),f===ee)this._status="dirty";else if(f===B)this._status="resolved";else if(f===_)this._status="completed";else if(f===M)this._status="errored";else if(f===He){this._cached=void 0,this._status="dirty";let p=this._cleanup;if(typeof p=="function"){this._cleanup=void 0;try{p()}catch{}}else if(p!=null&&typeof p=="object"){let m=p.invalidate;if(typeof m=="function")try{m()}catch{}}}else f===de&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let c=s>=0?r??e.slice(0,s):r??e;return o!=null?{finalMessages:c,equalsError:o}:{finalMessages:c}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let n=[...this._sinks];for(let r of n)r(e)};_dispatchOrAccumulate(e){if(yu()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],lr(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}vt(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let n=this._frameBatch(e);vt(this._deliverToSinks,n,this._config.tierOf)}},ku=t=>Array.isArray(t),li=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function N(t,e){return K([],{...e,initial:t})}function W(t,e){return K((r,o,s)=>t(o,s)??void 0,{describeKind:"producer",...e})}function O(t,e,n){return K(t,(o,s,i)=>{let a=o.map((u,c)=>u!=null&&u.length>0?u.at(-1):i.prevData[c]);s.emit(e(a,i))},{describeKind:"derived",...n})}function fe(t,e,n){return K(t,(o,s,i)=>{let a=o.map((u,c)=>u!=null&&u.length>0?u.at(-1):i.prevData[c]);return e(a,s,i)??void 0},{describeKind:"effect",...n})}function gr(t,e,n){let r=new Map;return t.forEach((o,s)=>{r.set(o,s)}),O(t,(o,s)=>e(a=>{let u=r.get(a);if(u==null)throw new Error(`dynamicNode: untracked dep "${a.name??"<unnamed>"}"`);return o[u]},s),n)}function Xt(t,e){let n,r=new Map,o=(s,i,a)=>{let u=!1,c=d=>{let l=r.get(d);if(l!==void 0){if(l<s.length){let p=s[l];return p!=null&&p.length>0?p.at(-1):a.prevData[l]}return d.cache}u=!0;let f=n._addDep(d);return r.set(d,f),d.cache};try{let d=t(c,a);u||(i.emit(d),a.store.__autoTrackLastDiscoveryError!=null&&delete a.store.__autoTrackLastDiscoveryError)}catch(d){if(!u)throw d;a.store.__autoTrackLastDiscoveryError=d}};return n=new Ee([],o,{describeKind:"derived",...e}),n}function fi(t,...e){let n=t;for(let r of e)n=r(n);return n}var oe=Ue(()=>{"use strict";xe()});function vr(t,e,n){let r=new Set;for(let o of t.split(",")){let[s,i]=o.split("/"),a=i?Number.parseInt(i,10):1;if(Number.isNaN(a)||a<1)throw new Error(`Invalid cron step: ${o}`);let u,c;if(s==="*")u=e,c=n;else if(s.includes("-")){let[d,l]=s.split("-");u=Number.parseInt(d,10),c=Number.parseInt(l,10)}else u=Number.parseInt(s,10),c=u;if(Number.isNaN(u)||Number.isNaN(c))throw new Error(`Invalid cron field: ${t}`);if(u<e||c>n)throw new Error(`Cron field out of range: ${t} (${e}-${n})`);if(u>c)throw new Error(`Invalid cron range: ${u}-${c} in ${t}`);for(let d=u;d<=c;d+=a)r.add(d)}return r}function fo(t){let e=t.trim().split(/\s+/);if(e.length!==5)throw new Error(`Invalid cron: expected 5 fields, got ${e.length}`);return{minutes:vr(e[0],0,59),hours:vr(e[1],0,23),daysOfMonth:vr(e[2],1,31),months:vr(e[3],1,12),daysOfWeek:vr(e[4],0,6)}}function mo(t,e){return t.minutes.has(e.getMinutes())&&t.hours.has(e.getHours())&&t.daysOfMonth.has(e.getDate())&&t.months.has(e.getMonth()+1)&&t.daysOfWeek.has(e.getDay())}var gi=Ue(()=>{"use strict"});var Fu={};he(Fu,{NS_PER_MS:()=>Fe,NS_PER_SEC:()=>Qe,constant:()=>ho,decorrelatedJitter:()=>vo,exponential:()=>yo,fibonacci:()=>bo,linear:()=>go,resolveBackoffPreset:()=>Ct,withMaxAttempts:()=>yi});function en(t){return t<0?0:t}function Yp(t,e){return e==="none"?t:e==="full"?Math.random()*t:t/2+Math.random()*(t/2)}function Qp(t,e){return t+Math.random()*(e-t)}function ho(t){let e=en(t);return()=>e}function go(t,e){let n=en(t),r=e===void 0?n:en(e);return o=>n+r*Math.max(0,o)}function yo(t){let e=en(t?.baseNs??1e8),n=t?.factor!==void 0&&t.factor<1?1:t?.factor??2,r=en(t?.maxDelayNs??30*1e9),o=t?.jitter??"none";return s=>{let i;if(e===0)i=0;else if(n===1)i=e;else{let a=r/e,u=1;for(let c=0;c<Math.max(0,s);c++){if(u>=a){u=a;break}u*=n}i=e*u,i>r&&(i=r)}return Yp(i,o)}}function bo(t=100*1e6,e=30*1e9){let n=en(t),r=en(e);function o(s){if(s<=0)return 1;let i=1,a=2;for(let u=1;u<s;u++){let c=i+a;i=a,a=c}return a}return s=>{let i=o(s)*n;return i<=r?i:r}}function vo(t=100*1e6,e=30*1e9){return(n,r,o)=>{let i=Math.min(e,(o??t)*3);return Qp(t,i)}}function yi(t,e){return(n,r,o)=>n>=e?null:t(n,r,o)}function Ct(t){if(t==="constant")return ho(1*1e9);if(t==="linear")return go(1*1e9);if(t==="exponential")return yo();if(t==="fibonacci")return bo();if(t==="decorrelatedJitter")return vo();throw new Error(`Unknown backoff preset: "${String(t)}". Use one of: constant, linear, exponential, fibonacci, decorrelatedJitter`)}var Fe,Qe,Gn=Ue(()=>{"use strict";Fe=1e6,Qe=1e9});var _e,pt=Ue(()=>{"use strict";_e=class{_timer;_gen=0;start(e,n){this.cancel(),this._gen+=1;let r=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,r===this._gen&&n()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var Bu={};he(Bu,{CircuitOpenError:()=>st,RateLimiterOverflowError:()=>tn,TimeoutError:()=>nn,circuitBreaker:()=>ft,fallback:()=>jn,rateLimiter:()=>Bn,retry:()=>Fn,retrySource:()=>At,timeout:()=>Vn,tokenBucket:()=>Lt,withBreaker:()=>$n,withStatus:()=>It});function rn(t){return{describeKind:"derived",...t}}function Xp(t){return t<0?0:t}function To(t){return t[1]}function $u(t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("backoff strategy must return a finite number");return t<0?0:t}function Fn(t,e){let n=e?.count,r=e?.backoff,o=n!==void 0?n:r===void 0?0:2147483647;if(o<0)throw new RangeError("retry count must be >= 0");let s=r===void 0?null:typeof r=="string"?Ct(r):r;return W(i=>{let a=0,u=!1,c=null,d,l=new _e;function f(){d?.(),d=void 0}function p(h){if(u)return;if(a>=o){f(),i.down([[M,h]]);return}let g=s===null?0:s(a,h,c);if(g==null){f(),i.down([[M,h]]);return}let y;try{y=$u(g)}catch{f(),i.down([[M,h]]);return}c=y,a+=1,f();let b=y>0?y/1e6:1;l.start(b,()=>{u||m()})}function m(){l.cancel(),f(),d=t.subscribe(h=>{if(!u)for(let g of h){let y=g[0];if(y===ee)i.down([[ee]]);else if(y===S)a=0,c=null,i.emit(g[1]);else if(y===B)i.down([[B]]);else if(y===_)f(),i.down([[_]]);else if(y===M){p(To(g));return}else i.down([g])}})}return m(),()=>{u=!0,l.cancel(),f()}},{...rn(),initial:t.cache})}function At(t,e){let n=e?.count,r=e?.backoff,o=n!==void 0?n:r===void 0?0:2147483647;if(o<0)throw new RangeError("retry count must be >= 0");let s=r===void 0?null:typeof r=="string"?Ct(r):r;return W(i=>{let a=0,u=!1,c=null,d,l=new _e;function f(){d?.(),d=void 0}function p(h){if(u)return;if(a>=o){f(),i.down([[M,h]]);return}let g=s===null?0:s(a,h,c);if(g==null){f(),i.down([[M,h]]);return}let y;try{y=$u(g)}catch{f(),i.down([[M,h]]);return}c=y,a+=1,f();let b=y>0?y/1e6:1;l.start(b,()=>{u||m()})}function m(){l.cancel(),f();let h;try{h=t()}catch(g){p(g);return}d=h.subscribe(g=>{if(!u)for(let y of g){let b=y[0];if(b===ee)i.down([[ee]]);else if(b===S)a=0,c=null,i.emit(y[1]);else if(b===B)i.down([[B]]);else if(b===_)f(),i.down([[_]]);else if(b===M){p(To(y));return}else i.down([y])}})}return m(),()=>{u=!0,l.cancel(),f()}},{...rn(),initial:e?.initial})}function ft(t){let e=Math.max(1,t?.failureThreshold??5),n=Xp(t?.cooldownNs??30*1e9),r=t?.cooldown??null,o=Math.max(1,t?.halfOpenMax??1),s=t?.now??$,i="closed",a=0,u=0,c=0,d=n,l=0;function f(){if(!r)return n;let h=r(u);return h!==null?h:n}function p(){i="open",d=f(),c=s(),l=0}return{canExecute(){return i==="closed"?!0:i==="open"?s()-c>=d?(i="half-open",l=1,!0):!1:l<o?(l++,!0):!1},recordSuccess(){i==="half-open"?(i="closed",a=0,u=0):i==="closed"&&(a=0)},recordFailure(h){if(i==="half-open"){u++,p();return}i==="closed"&&(a++,a>=e&&p())},get state(){return i},get failureCount(){return a},reset(){i="closed",a=0,u=0,l=0}}}function $n(t,e){let n=e?.onOpen??"skip";return r=>{let o=K([],(s,i)=>{function a(){o.meta.breakerState.down([[S,t.state]])}let u=r.subscribe(c=>{for(let d of c){let l=d[0];l===ee?i.down([[ee]]):l===S?t.canExecute()?(a(),i.emit(d[1])):(a(),n==="error"?i.down([[M,new st]]):i.down([[B]])):l===B?i.down([[B]]):l===_?(t.recordSuccess(),a(),i.down([[_]])):l===M?(t.recordFailure(To(d)),a(),i.down([d])):i.down([d])}});return a(),u},{...rn(),meta:{breakerState:t.state},completeWhenDepsComplete:!1,initial:r.cache});return{node:o,breakerState:o.meta.breakerState}}}function Lt(t,e){if(t<=0)throw new RangeError("capacity must be > 0");if(e<0)throw new RangeError("refillPerSecond must be >= 0");let n=t,r=$();function o(s){if(e>0){let i=s-r;n=Math.min(t,n+i/1e9*e)}r=s}return{available(){return o($()),n},tryConsume(s=1){if(s<=0)return!0;let i=$();return o(i),n>=s?(n-=s,!0):!1},putBack(s=1){s<=0||(o($()),n=Math.min(t,n+s))}}}function Bn(t,e){let{maxEvents:n,windowNs:r}=e;if(n<=0)throw new RangeError("maxEvents must be > 0");if(r<=0)throw new RangeError("windowNs must be > 0");let o=e.maxBuffer;if(o!==void 0&&o<1)throw new RangeError("maxBuffer must be >= 1");let s=e.onOverflow??"drop-newest",i=n*1e9/r;return W(a=>{let u=Lt(n,i),c=[],d=new _e,l=!1,f=1e9/i;function p(){for(;c.length>0;)if(u.tryConsume(1))a.emit(c.shift());else{d.start(Math.max(1,f/1e6),p);return}}let m=t.subscribe(h=>{for(let g of h){if(l)return;let y=g[0];if(y===ee)a.down([[ee]]);else if(y===S){if(o!==void 0&&c.length>=o){if(s!=="drop-newest")if(s==="drop-oldest")c.shift(),c.push(g[1]);else{l=!0,d.cancel(),c.length=0,a.down([[M,new tn(o)]]);return}}else c.push(g[1]);p()}else if(y===B)a.down([[B]]);else if(y===_)l=!0,d.cancel(),c.length=0,a.down([[_]]);else if(y===M)l=!0,d.cancel(),c.length=0,a.down([g]);else if(y===de){l=!0,d.cancel(),c.length=0,a.down([g]);return}else a.down([g])}});return()=>{l=!0,d.cancel(),m()}},{...rn(),initial:t.cache})}function It(t,e){let n=e?.initialStatus??"pending",r=K([],(o,s)=>{let i=n;return r.meta.status.down([[S,n]]),r.meta.error.down([[S,null]]),t.subscribe(u=>{for(let c of u){let d=c[0];if(d===ee)s.down([[ee]]);else if(d===S)i==="errored"?te(()=>{r.meta.error.down([[S,null]]),r.meta.status.down([[S,"active"]])}):r.meta.status.down([[S,"active"]]),i="active",s.emit(c[1]);else if(d===B)s.down([[B]]);else if(d===_)r.meta.status.down([[S,"completed"]]),i="completed",s.down([[_]]);else if(d===M){let l=To(c);te(()=>{r.meta.error.down([[S,l]]),r.meta.status.down([[S,"errored"]])}),i="errored",s.down([c])}else s.down([c])}})},{...rn(),meta:{status:n,error:null},completeWhenDepsComplete:!1,resubscribable:!0,initial:t.cache});return{node:r,status:r.meta.status,error:r.meta.error}}function Zp(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function ef(t){return t!=null&&typeof t.then=="function"}function tf(t){return t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function"}function jn(t,e){return W(n=>{let r,o;function s(){o?.(),o=void 0,Zp(e)||ef(e)||tf(e)?r=re(e).subscribe(a=>{n.down(a)}):(n.emit(e),n.down([[_]]))}return o=t.subscribe(i=>{for(let a of i){let u=a[0];if(u===ee)n.down([[ee]]);else if(u===S)n.emit(a[1]);else if(u===B)n.down([[B]]);else if(u===_)n.down([[_]]);else if(u===M){s();return}else if(u===de){r?.(),n.down([a]);return}else n.down([a])}}),()=>{o?.(),r?.()}},{...rn(),initial:t.cache})}function Vn(t,e){if(e<=0)throw new RangeError("timeoutNs must be > 0");return W(n=>{let r=!1,o=new _e;function s(){let a=e/1e6;o.start(a,()=>{r||(r=!0,i(),n.down([[M,new nn(e)]]))})}let i=t.subscribe(a=>{for(let u of a){if(r)return;let c=u[0];if(c===ee)n.down([[ee]]);else if(c===S)s(),n.emit(u[1]);else if(c===B)n.down([[B]]);else if(c===_){o.cancel(),r=!0,n.down([[_]]);return}else if(c===M){o.cancel(),r=!0,n.down([u]);return}else if(c===de){o.cancel(),r=!0,n.down([u]);return}else n.down([u])}});return s(),()=>{r=!0,o.cancel(),i()}},{...rn(),initial:t.cache})}var st,tn,nn,Tt=Ue(()=>{"use strict";Ne();ke();ie();xe();oe();Gn();Re();pt();st=class extends Error{name="CircuitOpenError";constructor(){super("Circuit breaker is open")}};tn=class extends Error{name="RateLimiterOverflowError";constructor(e){super(`rateLimiter buffer overflow (maxBuffer=${e})`)}};nn=class extends Error{name="TimeoutError";constructor(e){super(`Timed out after ${e/1e6}ms`)}}});function Ze(t){return{describeKind:"producer",...t}}function vi(t){return/[\\^$+?.()|[\]{}]/.test(t)?`\\${t}`:t}function Vu(t){let e="^";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="*"){t[n+1]==="*"?(e+=".*",n+=1):e+="[^/]*";continue}e+=vi(r)}return e+="$",new RegExp(e)}function Ku(t,e){for(let n of e)if(n.test(t))return!0;return!1}function nf(t,e){let n=K([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[B]]);return}for(let a of i)s.emit(a)},{describeKind:"derived",initial:t.cache}),r=n.subscribe.bind(n);return n.subscribe=(o,s)=>(e(o),r(o,s)),n}function et(t,e){let{signal:n,period:r,...o}=e??{};return W(s=>{let i=!1,a=0,u,c,d=()=>{i=!0,u!==void 0&&clearTimeout(u),c!==void 0&&clearInterval(c),n?.removeEventListener("abort",f)},l=()=>{i||(r!=null?(s.emit(a++),c=setInterval(()=>{i||s.emit(a++)},r)):(i=!0,n?.removeEventListener("abort",f),s.emit(a++),s.down([[_]])))},f=()=>{i||(d(),s.down([[M,n.reason]]))};if(n?.aborted){f();return}return u=setTimeout(l,t),n?.addEventListener("abort",f,{once:!0}),d},Ze(o))}function Hu(t){let{signal:e,...n}=t??{};return W(r=>{let o=!1,s,i,a=!1,u=!1,c=typeof requestAnimationFrame=="function"?requestAnimationFrame:void 0,d=typeof cancelAnimationFrame=="function"?cancelAnimationFrame:void 0,l=typeof document<"u"?document:void 0,f=()=>{s!==void 0&&d&&d(s),i!==void 0&&clearTimeout(i),s=void 0,i=void 0},p=()=>{o=!0,f(),a&&(e?.removeEventListener("abort",m),a=!1),u&&l&&(l.removeEventListener("visibilitychange",y),u=!1)},m=()=>{o||(p(),r.down([[M,e.reason]]))},h=b=>{o||(r.emit(b),g())},g=()=>{o||(c&&(!l||l.visibilityState!=="hidden")?s=c(h):i=setTimeout(()=>h(performance.now()),16))},y=()=>{o||(f(),g())};return e?.aborted?(m(),p):(e?.addEventListener("abort",m,{once:!0}),a=e!==void 0,l&&c&&(l.addEventListener("visibilitychange",y),u=!0),g(),p)},Ze(n))}function ko(t,e){let n=fo(t),{tickMs:r,output:o,...s}=e??{},i=r??6e4,a=o==="date";return W(u=>{let c=-1,d=()=>{let f=new Date,p=f.getFullYear()*1e8+(f.getMonth()+1)*1e6+f.getDate()*1e4+f.getHours()*100+f.getMinutes();p!==c&&mo(n,f)&&(c=p,u.emit(a?f:pe()))};d();let l=setInterval(d,i);return()=>clearInterval(l)},{...Ze(s),name:s.name??`cron:${t}`})}function Wu(t,e,n){let{capture:r,passive:o,once:s,...i}=n??{};return W(a=>{let u=d=>{a.emit(d)},c={capture:r,passive:o,once:s};return t.addEventListener(e,u,c),()=>t.removeEventListener(e,u,c)},Ze(i))}function xo(t,e){return W(n=>{let r=!1;try{for(let o of t){if(r)return;n.emit(o)}r||n.down([[_]])}catch(o){r||n.down([[M,o]])}return()=>{r=!0}},Ze(e))}function rf(t){return t!=null&&typeof t.then=="function"}function Ti(t,e){let{signal:n,...r}=e??{};return W(o=>{let s=!1,i=()=>{s||(s=!0,o.down([[M,n.reason]]))};if(n?.aborted){i();return}return n?.addEventListener("abort",i,{once:!0}),Promise.resolve(t).then(a=>{s||(s=!0,n?.removeEventListener("abort",i),o.emit(a),o.down([[_]]))},a=>{s||(s=!0,n?.removeEventListener("abort",i),o.down([[M,a]]))}),()=>{s=!0,n?.removeEventListener("abort",i)}},Ze(r))}function wi(t,e){let{signal:n,...r}=e??{};return W(o=>{let s=new AbortController,i=()=>s.abort(n?.reason);n?.aborted?s.abort(n.reason):n?.addEventListener("abort",i,{once:!0});let a=n??s.signal,u=!1,c=t[Symbol.asyncIterator](),d=()=>{u||a.aborted||Promise.resolve(c.next()).then(l=>{if(!(u||a.aborted)){if(l.done){o.down([[_]]);return}o.emit(l.value),d()}},l=>{!u&&!a.aborted&&o.down([[M,l]])})};return d(),()=>{u=!0,n?.removeEventListener("abort",i),s.abort(),Promise.resolve(c.return?.()).catch(()=>{})}},Ze(r))}function of(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function re(t,e){if(of(t))return t;if(rf(t))return Ti(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return wi(t,e);if(typeof n[Symbol.iterator]=="function")return xo(t,e)}return ki(t)}function ki(...t){return xo(t,void 0)}function qu(t){return W(e=>{e.down([[_]])},Ze(t))}function Uu(t){return W(()=>{},Ze(t))}function zu(t,e){return W(n=>{n.down([[M,t]])},Ze(e))}function Pt(t,e,n){return K([t],(o,s)=>{let i=o[0];if(i!=null&&i.length>0)for(let a of i)e(a)},{describeKind:"effect",...n}).subscribe(()=>{})}function Ju(t,e){return K([t],(n,r,o)=>{o.store.buf||(o.store.buf=[]);let s=o.store.buf,i=n[0];if(i!=null&&i.length>0)for(let a of i)s.push(a);if(o.terminalDeps[0]===!0){r.emit([...s]),r.down([[_]]);return}(i==null||i.length===0)&&r.down([[B]])},{describeKind:"derived",completeWhenDepsComplete:!1,...e})}function Yu(t,e){return W(n=>t.subscribe(r=>{n.down(r)}),{...Ze(e),initial:t.cache})}function Ro(t,e,n){if(e<1)throw new RangeError("replay expects bufferSize >= 1");let r=[],o=W(s=>t.subscribe(i=>{for(let a of i)a[0]===S&&(r.push(a[1]),r.length>e&&r.shift());s.down(i)}),{...Ze(n),initial:t.cache});return nf(o,s=>{for(let i of r)s([[S,i]])})}function Qu(t,e){return Ro(t,1,e)}function Kn(t){return new Promise((e,n)=>{let r=!1,o=!1,s;s=t.subscribe(i=>{for(let a of i){if(r)return;if(a[0]===S){r=!0,e(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===M){r=!0,n(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===_){r=!0,n(new Error("completed without DATA")),s?(s(),s=void 0):o=!0;return}}}),o&&(s?.(),s=void 0)})}function wo(t,e){return new Promise((n,r)=>{let o=!1,s=!1,i;i=t.subscribe(a=>{for(let u of a){if(o)return;if(u[0]===S){let c=u[1];if(e(c)){o=!0,n(c),i?(i(),i=void 0):s=!0;return}}if(u[0]===M){o=!0,r(u[1]),i?(i(),i=void 0):s=!0;return}if(u[0]===_){o=!0,r(new Error("completed without matching value")),i?(i(),i=void 0):s=!0;return}}}),s&&(i?.(),i=void 0)})}async function So(t,e){let n=e?.predicate??(o=>o!=null);if(e?.timeoutMs==null||e.timeoutMs<=0)return await wo(t,n);if(bi===void 0){let[o,s]=await Promise.all([Promise.resolve().then(()=>(Tt(),Bu)),Promise.resolve().then(()=>(Gn(),Fu))]);bi=o.timeout,ju=s.NS_PER_MS}let r=bi(t,e.timeoutMs*ju);return await wo(r,n)}function se(t){return t.subscribe(()=>{})}function xi(t){let e=N(0);return{node:e,increment(){let n=e.cache??0;return n>=t?!1:(e.down([[ee],[S,n+1]]),!0)},get(){return e.cache??0},atCap(){return(e.cache??0)>=t}}}var bi,ju,Xu,Re=Ue(()=>{"use strict";ke();ie();xe();oe();gi();Xu=Ro});var Cy={};he(Cy,{COMPLETE:()=>_,COMPLETE_MSG:()=>eo,COMPLETE_ONLY_BATCH:()=>or,CircuitOpenError:()=>st,DATA:()=>S,DEFAULT_ACTOR:()=>lt,DIRTY:()=>ee,DIRTY_MSG:()=>yt,DIRTY_ONLY_BATCH:()=>Rn,ENVELOPE_VERSION:()=>Nn,ERROR:()=>M,GRAPH_META_SEGMENT:()=>je,Graph:()=>q,GraphReFlyConfig:()=>Jt,GuardDenied:()=>Je,INVALIDATE:()=>He,INVALIDATE_MSG:()=>Zr,INVALIDATE_ONLY_BATCH:()=>rr,JsonCodec:()=>no,NS_PER_MS:()=>Fe,NS_PER_SEC:()=>Qe,NativeIndexBackend:()=>Ir,NativeListBackend:()=>Pr,NativeLogBackend:()=>Rr,NativeMapBackend:()=>Cr,NativePubSubBackend:()=>Lr,NodeImpl:()=>Ee,PAUSE:()=>Ie,RESOLVED:()=>B,RESOLVED_MSG:()=>kn,RESOLVED_ONLY_BATCH:()=>nr,RESUME:()=>Ge,RateLimiterOverflowError:()=>tn,ResettableTimer:()=>_e,SIZEOF_OVERHEAD:()=>Le,SIZEOF_SYMBOL:()=>Lo,SNAPSHOT_VERSION:()=>it,SNAPSHOT_WIRE_VERSION:()=>Xr,START:()=>dt,START_MSG:()=>xn,SurfaceError:()=>we,TEARDOWN:()=>de,TEARDOWN_MSG:()=>to,TEARDOWN_ONLY_BATCH:()=>Sn,TimeoutError:()=>nn,accessHintForGuard:()=>mr,accountability:()=>_s,advanceVersion:()=>hr,ai:()=>Ss,asSurfaceError:()=>Us,audit:()=>Qc,autoTrackNode:()=>Xt,awaitSettled:()=>So,batch:()=>te,buffer:()=>Xc,bufferCount:()=>Zc,bufferTime:()=>td,cached:()=>Qu,cascadingCache:()=>cl,catchError:()=>ld,checkpointToRedis:()=>tl,checkpointToS3:()=>el,circuitBreaker:()=>ft,combine:()=>Ki,combineLatest:()=>ud,compat:()=>ji,concat:()=>Hc,concatMap:()=>Uc,configure:()=>pi,constant:()=>ho,core:()=>Oi,cqrs:()=>Bo,createDagCborCodec:()=>oi,createDagCborZstdCodec:()=>si,createGraph:()=>Zn,createTransport:()=>$t,createVersioning:()=>Mn,createWatermarkController:()=>Hn,csvRows:()=>Dd,debounce:()=>Wi,debounceTime:()=>cd,decodeEnvelope:()=>ir,decorrelatedJitter:()=>vo,defaultConfig:()=>Ae,defaultHash:()=>Ot,delay:()=>Jc,deleteSnapshot:()=>ei,demoShell:()=>Os,derived:()=>O,deserializeError:()=>fn,dictStorage:()=>vl,diffForWAL:()=>Go,diffSnapshots:()=>Xs,distill:()=>Zo,distinctUntilChanged:()=>jc,domainTemplates:()=>Ls,downWithBatch:()=>vt,dynamicNode:()=>gr,effect:()=>fe,elementAt:()=>$c,empty:()=>qu,encodeEnvelope:()=>sr,escapeRegexChar:()=>vi,exhaustMap:()=>qc,explainPath:()=>kr,exponential:()=>yo,externalBundle:()=>Yo,externalProducer:()=>cn,extra:()=>na,fallback:()=>jn,fibonacci:()=>bo,filter:()=>ut,find:()=>Fc,first:()=>Qo,firstValueFrom:()=>Kn,firstWhere:()=>wo,flatMap:()=>zc,forEach:()=>Pt,fromAny:()=>re,fromAsyncIter:()=>wi,fromCSV:()=>Pd,fromClickHouseWatch:()=>Bd,fromCron:()=>ko,fromDrizzle:()=>il,fromEvent:()=>Wu,fromHTTP:()=>Yi,fromHTTPPoll:()=>wd,fromHTTPStream:()=>Td,fromIter:()=>xo,fromKafka:()=>Cd,fromKysely:()=>al,fromMCP:()=>Rd,fromNATS:()=>Kd,fromNDJSON:()=>$d,fromOTel:()=>Sd,fromPrisma:()=>sl,fromPrometheus:()=>Od,fromPromise:()=>Ti,fromPulsar:()=>jd,fromRabbitMQ:()=>Wd,fromRaf:()=>Hu,fromRedisStream:()=>Ld,fromSSE:()=>vd,fromSqlite:()=>nl,fromSqliteCursor:()=>rl,fromStatsD:()=>_d,fromSyslog:()=>Nd,fromTimer:()=>et,fromWebSocket:()=>Ji,fromWebSocketReconnect:()=>xd,fromWebhook:()=>pd,globToRegExp:()=>Vu,graph:()=>Ai,graphProfile:()=>an,graphspec:()=>Is,guarded:()=>Ds,harness:()=>$s,interval:()=>od,isBatching:()=>zt,isV1:()=>ci,jobQueue:()=>Vs,jotai:()=>io,keepalive:()=>se,last:()=>Gc,layout:()=>Ws,lens:()=>Hs,linear:()=>go,listSnapshots:()=>Zs,lru:()=>Zi,map:()=>Er,matchesAnyPattern:()=>Ku,matchesCron:()=>mo,memory:()=>Rs,memoryStorage:()=>Gr,merge:()=>mt,mergeMap:()=>Hi,mermaidLiveUrl:()=>Do,messaging:()=>bs,monotonicNs:()=>$,nameToSignal:()=>ln,nanostores:()=>lo,ndjsonRows:()=>Gd,nestjs:()=>Vo,never:()=>Uu,node:()=>K,normalizeActor:()=>bt,of:()=>ki,orchestration:()=>vs,pairwise:()=>Vc,parseCron:()=>fo,parsePrometheusText:()=>Qi,parseStatsD:()=>Md,parseSyslog:()=>Ed,patterns:()=>su,pausable:()=>id,pipe:()=>fi,policy:()=>Yt,policyFromRules:()=>fr,producer:()=>W,pubsub:()=>fl,race:()=>Wc,rateLimiter:()=>Bn,reachable:()=>un,react:()=>Ko,reactiveCounter:()=>xi,reactiveIndex:()=>gl,reactiveList:()=>es,reactiveLog:()=>Ve,reactiveMap:()=>tt,reactiveSink:()=>$e,reduce:()=>Ic,reduction:()=>As,refine:()=>Fs,registerBuiltinCodecs:()=>ar,registerBuiltins:()=>pr,repeat:()=>sd,replay:()=>Ro,replayWAL:()=>ii,rescue:()=>Mr,resilientPipeline:()=>qs,resolveBackoffPreset:()=>Ct,resolveDescribeFields:()=>wt,restoreSnapshot:()=>Qs,retry:()=>Fn,retrySource:()=>At,runReduction:()=>zs,sample:()=>Yc,saveSnapshot:()=>Ys,scan:()=>Lc,serializeError:()=>pn,share:()=>Yu,shareReplay:()=>Xu,signalToName:()=>Ft,signals:()=>Wo,singleFromAny:()=>ts,singleNodeFromAny:()=>yl,sizeof:()=>xr,skip:()=>Vi,solid:()=>qo,sortJsonValue:()=>Dr,stableJsonString:()=>bl,state:()=>N,stratify:()=>Fr,surface:()=>ti,svelte:()=>Uo,switchMap:()=>be,take:()=>_r,takeUntil:()=>Dc,takeWhile:()=>Pc,tap:()=>Bc,throttle:()=>qi,throttleTime:()=>dd,throwError:()=>zu,timeout:()=>Vn,toArray:()=>Ju,toCSV:()=>Ud,toClickHouse:()=>zd,toFile:()=>Xi,toHTTP:()=>fd,toKafka:()=>Ad,toLoki:()=>Xd,toMongo:()=>Qd,toNATS:()=>Hd,toObservable:()=>po,toPostgres:()=>Yd,toPulsar:()=>Vd,toRabbitMQ:()=>qd,toReadableStream:()=>bd,toRedisStream:()=>Id,toS3:()=>Jd,toSSE:()=>gd,toSSEBytes:()=>yd,toSqlite:()=>ol,toTempo:()=>Zd,toWebSocket:()=>kd,tokenBucket:()=>Lt,validateGraphObservability:()=>Ci,valve:()=>ad,verifiable:()=>pl,version:()=>Oy,vue:()=>zo,wallClockNs:()=>pe,watchTopologyTree:()=>kt,window:()=>rd,windowCount:()=>ed,windowTime:()=>nd,withBreaker:()=>$n,withLatestFrom:()=>dn,withMaxAttempts:()=>yi,withStatus:()=>It,workerBridge:()=>ea,workerSelf:()=>ta,zip:()=>Kc,zustand:()=>Jo});module.exports=_p(Cy);var ji={};he(ji,{jotai:()=>io,nanostores:()=>lo,nestjs:()=>Vo,react:()=>Ko,signals:()=>Wo,solid:()=>qo,svelte:()=>Uo,vue:()=>zo,zustand:()=>Jo});var io={};he(io,{atom:()=>Vp});ie();oe();function Vp(t,e,n){if(typeof t=="function"){let r=t;return typeof e=="function"?xu(r,e,n):xu(r,void 0,e)}return Kp(t,e)}function yr(t){let e=t.cache,n;if(t.subscribe(o=>{for(let[s,i]of o)s===S&&(e=i),s===M&&(n=i)})(),n)throw n;return e}function Kp(t,e){let n=N(t,{...e,resubscribable:!0,resetOnTeardown:!0});return{get:()=>n.status==="sentinel"?yr(n):n.cache,set:r=>n.emit(r),update:r=>{let o=n.status==="sentinel"?yr(n):n.cache;n.emit(r(o))},subscribe:r=>{let o=!0;return n.subscribe(s=>{for(let[i,a]of s)if(i===S){if(o){o=!1;continue}r(a)}})},meta:n.meta,_node:n}}function xu(t,e,n){let r=Xt(s=>t(i=>{let a=i._node;return a.status==="sentinel"&&yr(a),s(a)}),{...n,resubscribable:!0,resetOnTeardown:!0}),o={get:()=>r.status==="sentinel"?yr(r):r.cache,subscribe:s=>{let i=!0;return r.subscribe(a=>{for(let[u,c]of a)if(u===S){if(i){i=!1;continue}s(c)}})},meta:r.meta,_node:r};if(e){let s=u=>u.get(),i=(u,c)=>u.set(c),a=o;return a.set=u=>e(s,i,u),a.update=u=>{let c=r.status==="sentinel"?yr(r):r.cache;return e(s,i,u(c))},a}return o}var lo={};he(lo,{action:()=>Jp,atom:()=>Hp,computed:()=>Wp,getValue:()=>Up,map:()=>qp,onMount:()=>zp,onStart:()=>Nu,onStop:()=>Eu});Ne();ie();oe();var uo=new WeakMap,co=new WeakMap;function ao(t,e){let n=e.get(t);if(n)for(let r of n)r()}function mi(t,e={}){let n=0;return{...e,get:()=>Su(t),subscribe:o=>{n===0&&ao(t,uo),n++;let s=t.subscribe(i=>{for(let[a,u]of i)a===S&&o(u)});return()=>{s(),n--,n===0&&ao(t,co)}},listen:o=>{n===0&&ao(t,uo),n++;let s=!0,i=t.subscribe(a=>{for(let[u,c]of a)if(u===S){if(s){s=!1;continue}o(c)}});return()=>{i(),n--,n===0&&ao(t,co)}},_node:t}}function Ru(t){let e=t.cache,n;if(t.subscribe(o=>{for(let[s,i]of o)s===S&&(e=i),s===M&&(n=i)})(),n)throw n;return e}function Su(t){return t.status==="sentinel"?Ru(t):t.cache}function Hp(t){let e=N(t,{resubscribable:!0,resetOnTeardown:!0});return mi(e,{set:n=>e.emit(n)})}function Wp(t,e){let n=Array.isArray(t)?t:[t],r=n.map(s=>s._node),o=gr(r,s=>{let i=n.map(a=>{let u=a._node;return u.status==="sentinel"&&Ru(u),s(u)});return e(...i)},{resubscribable:!0,resetOnTeardown:!0,equals:Object.is});return mi(o)}function qp(t){let e=N(t,{resubscribable:!0,resetOnTeardown:!0,equals:()=>!1});return mi(e,{set:n=>e.emit(n),setKey:(n,r)=>{let o=Su(e);e.emit({...o,[n]:r})}})}function Up(t){return t.get()}function Nu(t,e){let n=t._node,r=uo.get(n);r||(r=new Set,uo.set(n,r)),r.add(e)}function Eu(t,e){let n=t._node,r=co.get(n);r||(r=new Set,co.set(n,r)),r.add(e)}function zp(t,e){Nu(t,()=>{let n=e();typeof n=="function"&&Eu(t,n)})}function Jp(t,e,n){return(...r)=>{let o;return te(()=>{o=n(...r)}),o}}var Vo={};he(Vo,{ACTOR_KEY:()=>Eo,COMMAND_HANDLERS:()=>Ln,CQRS_EVENT_HANDLERS:()=>In,CRON_HANDLERS:()=>An,CommandHandler:()=>Iu,EVENT_HANDLERS:()=>On,EventHandler:()=>Pu,GRAPHREFLY_REQUEST_GRAPH:()=>Zt,GRAPHREFLY_ROOT_GRAPH:()=>Xe,GraphCron:()=>Lu,GraphInterval:()=>Au,GraphReflyEventExplorer:()=>on,GraphReflyGuard:()=>oc,GraphReflyGuardImpl:()=>Tr,GraphReflyModule:()=>jo,INTERVAL_HANDLERS:()=>Cn,InjectCqrsGraph:()=>Mu,InjectGraph:()=>_u,InjectNode:()=>Ou,ObserveGateway:()=>No,OnGraphEvent:()=>Cu,QUERY_HANDLERS:()=>Pn,QueryHandler:()=>Du,SAGA_HANDLERS:()=>Dn,SagaHandler:()=>Gu,fromHeader:()=>nc,fromJwtPayload:()=>Ni,getActor:()=>rc,getGraphToken:()=>Ye,getNodeToken:()=>ot,observeSSE:()=>ec,observeSubscription:()=>tc,toObservable:()=>po});var hi=require("rxjs");ie();function po(t,e){return e?.raw?new hi.Observable(n=>t.subscribe(o=>{if(!n.closed){n.next(o);for(let s of o){if(s[0]===M){n.error(s[1]);return}if(s[0]===_){n.complete();return}}}})):new hi.Observable(n=>t.subscribe(o=>{for(let s of o){if(n.closed)return;if(s[0]===S)n.next(s[1]);else if(s[0]===M){n.error(s[1]);return}else if(s[0]===_){n.complete();return}}}))}var br=require("@nestjs/common");var Xe=Symbol.for("graphrefly:root-graph");var Zt=Symbol.for("graphrefly:request-graph");function Ye(t){return Symbol.for(`graphrefly:graph:${t}`)}function ot(t){return Symbol.for(`graphrefly:node:${t}`)}var On=new Map,Cn=new Map,An=new Map,Ln=new Map,In=new Map,Pn=new Map,Dn=new Map;function _u(t){return t==="request"?(0,br.Inject)(Zt):(0,br.Inject)(t?Ye(t):Xe)}function Mu(t){return(0,br.Inject)(Ye(t))}function Ou(t){return(0,br.Inject)(ot(t))}function Cu(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=On.get(o)??[];s.push({nodeName:t,methodKey:r}),On.set(o,s)})}}function Au(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=Cn.get(o)??[];s.push({ms:t,methodKey:r}),Cn.set(o,s)})}}function Lu(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=An.get(o)??[];s.push({expr:t,methodKey:r}),An.set(o,s)})}}function Iu(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=Ln.get(s)??[];i.push({cqrsName:t,commandName:e,methodKey:o}),Ln.set(s,i)})}}function Pu(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=In.get(s)??[];i.push({cqrsName:t,eventName:e,methodKey:o}),In.set(s,i)})}}function Du(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=Pn.get(s)??[];i.push({cqrsName:t,projectionName:e,methodKey:o}),Pn.set(s,i)})}}function Gu(t,e,n){return(r,o)=>{let s=o.name;o.addInitializer(function(){let i=this.constructor,a=Dn.get(i)??[];a.push({cqrsName:t,eventNames:n,sagaName:e,methodKey:s}),Dn.set(i,a)})}}ie();Re();var Zu=0,on=class{constructor(e,n){this.graph=e;this.moduleRef=n}disposers=[];scheduleNodeNames=[];onModuleInit(){this.wireEvents(),this.wireIntervals(),this.wireCrons(),this.wireCqrsCommands(),this.wireCqrsEvents(),this.wireCqrsQueries(),this.wireCqrsSagas()}onModuleDestroy(){for(let e of this.disposers)e();this.disposers.length=0;for(let e of this.scheduleNodeNames)try{this.graph.remove(e)}catch{}this.scheduleNodeNames.length=0}wireEvents(){for(let[e,n]of On){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireEventHandler(r,o)}}wireEventHandler(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),i=this.observeNode(n.nodeName).subscribe(a=>{for(let u of a)u[0]===S&&o(u[1])});this.disposers.push(i)}wireIntervals(){for(let[e,n]of Cn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireIntervalHandler(r,e,o)}}wireIntervalHandler(e,n,r){let o=e[r.methodKey];if(typeof o!="function")return;let s=o.bind(e),a=`__schedule__.${n.name??"anonymous"}.${String(r.methodKey)}.${Zu++}`,u=et(r.ms,{period:r.ms,name:a});this.graph.add(u),this.scheduleNodeNames.push(a);let d=this.observeNode(a).subscribe(l=>{for(let f of l)f[0]===S&&s(f[1])});this.disposers.push(d)}wireCrons(){for(let[e,n]of An){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCronHandler(r,e,o)}}wireCronHandler(e,n,r){let o=e[r.methodKey];if(typeof o!="function")return;let s=o.bind(e),a=`__schedule__.${n.name??"anonymous"}.${String(r.methodKey)}.${Zu++}`,u=ko(r.expr,{name:a});this.graph.add(u),this.scheduleNodeNames.push(a);let d=this.observeNode(a).subscribe(l=>{for(let f of l)f[0]===S&&s(f[1])});this.disposers.push(d)}wireCqrsCommands(){for(let[e,n]of Ln){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsCommand(r,o)}}wireCqrsCommand(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);s&&s.command(n.commandName,o)}wireCqrsEvents(){for(let[e,n]of In){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsEventHandler(r,o)}}wireCqrsEventHandler(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);if(!s)return;s.event(n.eventName);let a=s.resolve(n.eventName).cache,u=a&&a.length>0?a[a.length-1].seq:0,d=this.observeNodeOn(s,n.eventName).subscribe(l=>{for(let f of l)if(f[0]===S){let p=f[1];for(let m of p)m.seq>u&&(o(m),u=m.seq)}});this.disposers.push(d)}wireCqrsQueries(){for(let[e,n]of Pn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsQuery(r,o)}}wireCqrsQuery(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);if(!s)return;let a=this.observeNodeOn(s,n.projectionName).subscribe(u=>{for(let c of u)c[0]===S&&o(c[1])});this.disposers.push(a)}wireCqrsSagas(){for(let[e,n]of Dn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsSaga(r,o)}}wireCqrsSaga(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);s&&s.saga(n.sagaName,n.eventNames,o)}observeNode(e){return this.graph.observe(e)}observeNodeOn(e,n){return e.observe(n)}resolveCqrsGraph(e){try{return this.moduleRef.get(Ye(e),{strict:!1})}catch{return console.warn(`[GraphReFly] CqrsGraph "${e}" not found in DI \u2014 did you import GraphReflyModule.forCqrs({ name: "${e}" })?`),null}}resolveInstance(e){try{return this.moduleRef.get(e,{strict:!1})}catch{return null}}};ie();ie();var sf=0;function Hn(t,e){if(e.highWaterMark<1)throw new RangeError("highWaterMark must be >= 1");if(e.lowWaterMark<0)throw new RangeError("lowWaterMark must be >= 0");if(e.lowWaterMark>=e.highWaterMark)throw new RangeError("lowWaterMark must be < highWaterMark");let n=Symbol(`bp-${++sf}`),r=0,o=!1;return{onEnqueue(){return r+=1,!o&&r>=e.highWaterMark?(o=!0,t([[Ie,n]]),!0):!1},onDequeue(){return r>0&&(r-=1),o&&r<=e.lowWaterMark?(o=!1,t([[Ge,n]]),!0):!1},get pending(){return r},get paused(){return o},dispose(){o&&(o=!1,t([[Ge,n]]))}}}function ec(t,e,n){let{actor:r,serialize:o=af,keepAliveMs:s,signal:i}=n??{},a=new TextEncoder,u,c=n?.highWaterMark!=null,d,l,f=[],p=!1;return new ReadableStream({start(m){let h,g=()=>{},y=()=>{if(!p){p=!0,h!==void 0&&clearInterval(h),i?.removeEventListener("abort",b),g(),d?.dispose(),l?.(),l=void 0;for(let T of f)m.enqueue(T.frame);f.length=0,m.close()}};u=y;let b=()=>y(),v=t.observe(e,{actor:r});c&&(d=Hn(T=>v.up(T),{highWaterMark:n.highWaterMark,lowWaterMark:n.lowWaterMark??Math.floor(n.highWaterMark/2)})),g=v.subscribe(T=>{for(let w of T){if(p)return;let k=w[0];if(k===S){let x=a.encode(Ri("data",o(w[1])));c?(f.push({frame:x,counted:!0}),d.onEnqueue(),l?.(),l=void 0):m.enqueue(x)}else if(k===M){let x=a.encode(Ri("error",o(w[1])));c?(f.push({frame:x,counted:!1}),l?.(),l=void 0):m.enqueue(x),y();return}else if(k===_||k===de){if(k===_){let x=a.encode(Ri("complete"));c?(f.push({frame:x,counted:!1}),l?.(),l=void 0):m.enqueue(x)}y();return}}}),s!==void 0&&s>0&&(h=setInterval(()=>{p||(c?(f.push({frame:a.encode(`: keepalive
1
+ "use strict";var Ip=Object.create;var Nn=Object.defineProperty;var xu=Object.getOwnPropertyDescriptor;var Pp=Object.getOwnPropertyNames;var Dp=Object.prototype.hasOwnProperty;var Ru=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),ar=t=>{throw TypeError(t)};var Gp=(t,e,n)=>e in t?Nn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Tu=(t,e)=>Nn(t,"name",{value:e,configurable:!0});var et=(t,e)=>()=>(t&&(e=t(t=0)),e);var ye=(t,e)=>{for(var n in e)Nn(t,n,{get:e[n],enumerable:!0})},Fp=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Pp(e))!Dp.call(t,o)&&o!==n&&Nn(t,o,{get:()=>e[o],enumerable:!(r=xu(e,o))||r.enumerable});return t};var $p=t=>Fp(Nn({},"__esModule",{value:!0}),t);var Su=t=>[,,,Ip(t?.[Ru("metadata")]??null)],Nu=["class","method","getter","setter","accessor","field","value","get","set"],ir=t=>t!==void 0&&typeof t!="function"?ar("Function expected"):t,Bp=(t,e,n,r,o)=>({kind:Nu[t],name:e,metadata:r,addInitializer:s=>n._?ar("Already initialized"):o.push(ir(s||null))}),jp=(t,e)=>Gp(e,Ru("metadata"),t[3]),Eu=(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},_u=(t,e,n,r,o,s)=>{var i,a,u,c,d,l=e&7,f=!!(e&8),p=!!(e&16),m=l>3?t.length+1:l?f?1:2:0,h=Nu[l+5],g=l>3&&(t[m-1]=[]),y=t[m]||(t[m]=[]),b=l&&(!p&&!f&&(o=o.prototype),l<5&&(l>3||!p)&&xu(l<4?o:{get[n](){return wu(this,s)},set[n](T){return ku(this,s,T)}},n));l?p&&l<4&&Tu(s,(l>2?"set ":l>1?"get ":"")+n):Tu(o,n);for(var v=r.length-1;v>=0;v--)c=Bp(l,n,u={},t[3],y),l&&(c.static=f,c.private=p,d=c.access={has:p?T=>Vp(o,T):T=>n in T},l^3&&(d.get=p?T=>(l^1?wu:Kp)(T,o,l^4?s:b.get):T=>T[n]),l>2&&(d.set=p?(T,w)=>ku(T,o,w,l^4?s:b.set):(T,w)=>T[n]=w)),a=(0,r[v])(l?l<4?p?s:b[h]:l>4?void 0:{get:b.get,set:b.set}:o,c),u._=1,l^4||a===void 0?ir(a)&&(l>4?g.unshift(a):l?p?s=a:b[h]=a:o=a):typeof a!="object"||a===null?ar("Object expected"):(ir(i=a.get)&&(b.get=i),ir(i=a.set)&&(b.set=i),ir(i=a.init)&&g.unshift(i));return l||jp(t,o),b&&Nn(o,n,b),p?l^4?s:b:o};var vi=(t,e,n)=>e.has(t)||ar("Cannot "+n),Vp=(t,e)=>Object(e)!==e?ar('Cannot use the "in" operator on this value'):t.has(e),wu=(t,e,n)=>(vi(t,e,"read from private field"),n?n.call(t):e.get(t));var ku=(t,e,n,r)=>(vi(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),Kp=(t,e,n)=>(vi(t,e,"access private method"),n);var yt,S,ee,$,ze,Ge,$e,de,M,O,Rt,En,mo,_n,ho,go,Mn,ur,cr,dr,On,ie=et(()=>{"use strict";yt=Symbol.for("graphrefly/START"),S=Symbol.for("graphrefly/DATA"),ee=Symbol.for("graphrefly/DIRTY"),$=Symbol.for("graphrefly/RESOLVED"),ze=Symbol.for("graphrefly/INVALIDATE"),Ge=Symbol.for("graphrefly/PAUSE"),$e=Symbol.for("graphrefly/RESUME"),de=Symbol.for("graphrefly/TEARDOWN"),M=Symbol.for("graphrefly/COMPLETE"),O=Symbol.for("graphrefly/ERROR"),Rt=Object.freeze([ee]),En=Object.freeze([$]),mo=Object.freeze([ze]),_n=Object.freeze([yt]),ho=Object.freeze([M]),go=Object.freeze([de]),Mn=Object.freeze([Rt]),ur=Object.freeze([En]),cr=Object.freeze([mo]),dr=Object.freeze([ho]),On=Object.freeze([go])});function Ti(t){return{name:"dag-cbor",version:1,contentType:"application/dag-cbor",encode:e=>t.encode(e),decode:(e,n)=>t.decode(e)}}function wi(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 lr(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 pr(t,e){if(t.length<Mu)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${Mu})`);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 fr(t){t.registerCodec(yo)}function ki(t){if(t.length===0)throw new Error("WAL is empty \u2014 need at least one full snapshot");let e=t[0];if(e.mode!=="full")throw new Error("WAL must start with a full record carrying a baseline snapshot");let n=JSON.parse(JSON.stringify(e.snapshot)),r=e.seq;for(let o=1;o<t.length;o++){let s=t[o];if(s.seq<=r)throw new Error(`WAL chain broken at index ${o}: seq=${s.seq} must exceed prev seq=${r}`);if(s.mode==="full"){n=JSON.parse(JSON.stringify(s.snapshot)),r=s.seq;continue}let i=s.diff;for(let u of i.nodesRemoved)delete n.nodes[u];let a=i.nodesAddedFull;if(a!=null)for(let[u,c]of Object.entries(a))n.nodes[u]=JSON.parse(JSON.stringify(c));for(let u of i.nodesChanged){let c=n.nodes[u.path];c!=null&&(c[u.field]=u.to)}r=s.seq}return n}var yo,Cn,Mu,bo=et(()=>{"use strict";yo={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,Mu=4});function St(t){if(t==null)return bt;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var bt,mr=et(()=>{"use strict";bt={type:"system",id:""}});function Zt(){return An>0||hr}function Ou(){return An>0}function yr(t){An>0?gr.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(!hr){let n=gr.splice(0);for(let r of n)try{r()}catch{}Qt.length=0,Xt.length=0,Ln.length=0}}else Hp()}}function Hp(){let t=!hr;t&&(hr=!0);let e=[],n=0;try{for(;Qt.length>0||Xt.length>0||Ln.length>0||t&&gr.length>0;){if(t&&gr.length>0){let s=gr.splice(0);for(let i of s)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw Qt.length=0,Xt.length=0,Ln.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let o=(Qt.length>0?Qt:Xt.length>0?Xt:Ln).splice(0);for(let s of o)try{s()}catch(i){e.push(i)}}}finally{t&&(hr=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function Nt(t,e,n){if(e.length===0)return;if(e.length===1){let c=n(e[0][0]);if(c<3||!Zt()){t(e);return}(c>=5?Ln:c===4?Xt:Qt).push(()=>t(e));return}let r=e.length,o=r,s=r,i=r,a=0;for(;a<r&&n(e[a][0])<3;)a++;for(o=a;a<r&&n(e[a][0])===3;)a++;for(s=a;a<r&&n(e[a][0])===4;)a++;i=a;let u=Zt();if(o>0){let c=e.slice(0,o);t(c)}if(s>o){let c=e.slice(o,s);u?Qt.push(()=>t(c)):t(c)}if(i>s){let c=e.slice(s,i);u?Xt.push(()=>t(c)):t(c)}if(r>i){let c=e.slice(i,r);u?Ln.push(()=>t(c)):t(c)}}var An,hr,Qt,Xt,Ln,gr,_e=et(()=>{"use strict";An=0,hr=!1,Qt=[],Xt=[],Ln=[],gr=[]});function V(){return Math.trunc(performance.now()*1e6)}function le(){return Date.now()*1e6}var we=et(()=>{"use strict"});function br(t){t.registerMessageType(yt,{tier:0,wireCrossing:!1}),t.registerMessageType(ee,{tier:1,wireCrossing:!1}),t.registerMessageType(ze,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(Ge,{tier:2,wireCrossing:!1}),t.registerMessageType($e,{tier:2,wireCrossing:!1}),t.registerMessageType(S,{tier:3,wireCrossing:!0}),t.registerMessageType($,{tier:3,wireCrossing:!0}),t.registerMessageType(M,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(O,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(de,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var en,xi=et(()=>{"use strict";ie();en=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=n=>{let r=this._messageTypes.get(n);return r!=null?r.tier:1}}get onMessage(){return this._frozen=!0,this._onMessage}get onSubscribe(){return this._frozen=!0,this._onSubscribe}set onMessage(e){this._assertUnfrozen(),this._onMessage=e}set onSubscribe(e){this._assertUnfrozen(),this._onSubscribe=e}get defaultVersioning(){return this._defaultVersioning}set defaultVersioning(e){this._assertUnfrozen(),this._defaultVersioning=e}get defaultHashFn(){return this._defaultHashFn}set defaultHashFn(e){this._assertUnfrozen(),this._defaultHashFn=e}get inspectorEnabled(){return this._inspectorEnabled}set inspectorEnabled(e){this._inspectorEnabled=e}get globalInspector(){return this._globalInspector}set globalInspector(e){this._globalInspector=e}registerMessageType(e,n){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:n.tier,wireCrossing:n.wireCrossing??n.tier>=3,metaPassthrough:n.metaPassthrough??!0}),this}messageTier(e){let n=this._messageTypes.get(e);return n!=null?n.tier:1}isWireCrossing(e){let n=this._messageTypes.get(e);return n!=null?n.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let n=this._messageTypes.get(e);return n!=null?n.metaPassthrough:!0}isKnownMessageType(e){return this._messageTypes.has(e)}registerCodec(e){return this._assertUnfrozen(),this._codecs.set(e.name,e),this}lookupCodec(e){return this._codecs.get(e)}_isFrozen(){return this._frozen}_assertUnfrozen(){if(this._frozen)throw new Error("GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node.")}}});function Cu(t){return Array.isArray(t)?[...t]:[t]}function Wp(t,e){return t.has(e)||t.has("*")}function tn(t){let e=[];return t((o,s)=>{e.push({kind:"allow",actions:new Set(Cu(o)),where:s?.where??(()=>!0)})},(o,s)=>{e.push({kind:"deny",actions:new Set(Cu(o)),where:s?.where??(()=>!0)})}),(o,s)=>{let i=!1,a=!1;for(let u of e)Wp(u.actions,s)&&u.where(o)&&(u.kind==="deny"?i=!0:a=!0);return i?!1:a}}function vr(t){return tn((e,n)=>{for(let r of t){let o=r.actorType==null?null:new Set(Array.isArray(r.actorType)?r.actorType:[r.actorType]),s=r.actorId==null?null:new Set(Array.isArray(r.actorId)?r.actorId:[r.actorId]),i=Object.entries(r.claims??{}),a=u=>{if(o!==null&&!o.has(String(u.type))||s!==null&&!s.has(String(u.id??"")))return!1;for(let[c,d]of i)if(u[c]!==d)return!1;return!0};r.effect==="deny"?n(r.action,{where:a}):e(r.action,{where:a})}})}function Tr(t){let e=qp.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 nt,qp,nn=et(()=>{"use strict";nt=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}};qp=["human","llm","wallet","system"]});function Ri(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(Ri);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=Ri(t[n]);return e}return null}function Jp(t){let e=zp.encode(t),n=e.length,r=n*8,o=n+9+63&-64,s=new Uint8Array(o);s.set(e),s[n]=128;let i=new DataView(s.buffer);i.setUint32(o-4,r>>>0,!1),i.setUint32(o-8,Math.floor(r/4294967296)>>>0,!1);let a=1779033703,u=3144134277,c=1013904242,d=2773480762,l=1359893119,f=2600822924,p=528734635,m=1541459225,h=new Uint32Array(64),g=(b,v)=>b>>>v|b<<32-v;for(let b=0;b<o;b+=64){for(let L=0;L<16;L++)h[L]=i.getUint32(b+L*4,!1);for(let L=16;L<64;L++){let P=h[L-15],C=h[L-2],B=g(P,7)^g(P,18)^P>>>3,te=g(C,17)^g(C,19)^C>>>10;h[L]=h[L-16]+B+h[L-7]+te>>>0}let v=a,T=u,w=c,k=d,x=l,R=f,_=p,G=m;for(let L=0;L<64;L++){let P=g(x,6)^g(x,11)^g(x,25),C=x&R^~x&_,B=G+P+C+Up[L]+h[L]>>>0,te=g(v,2)^g(v,13)^g(v,22),F=v&T^v&w^T&w,A=te+F>>>0;G=_,_=R,R=x,x=k+B>>>0,k=w,w=T,T=v,v=B+A>>>0}a=a+v>>>0,u=u+T>>>0,c=c+w>>>0,d=d+k>>>0,l=l+x>>>0,f=f+R>>>0,p=p+_>>>0,m=m+G>>>0}let y=b=>b.toString(16).padStart(8,"0");return y(a)+y(u)+y(c)+y(d)+y(l)+y(f)+y(p)+y(m)}function Dt(t){let e=Ri(t??null),n=JSON.stringify(e);return Jp(n).slice(0,16)}function Yp(){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??Yp();if(t===0)return{id:r,version:0};let s=(n?.hash??Dt)(e);return{id:r,version:0,cid:s,prev:null}}function wr(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}function Si(t){return"cid"in t}var Up,zp,vo=et(()=>{"use strict";Up=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]),zp=new TextEncoder});function Iu(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function Ni(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function To(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function _i(t){if(Pe._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(Pe)}function K(t,e,n){let r=Pu(t)?t:[],o=typeof t=="function"?t:typeof e=="function"?e:void 0,s={};return Pu(t)?s=(Ei(e)?e:n)??{}:Ei(t)?s=t:s=(Ei(e)?e:n)??{},new Oe(r,o,s)}var Au,Lu,Qp,Xp,Pe,Oe,Pu,Ei,Ne=et(()=>{"use strict";bo();mr();_e();we();xi();nn();ie();vo();Au=()=>{},Lu=100;Qp=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},Xp=(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,[S,s]];o._status==="dirty"&&i.push(Rt),Nt(e,i,o._config.tierOf)},Pe=new en({onMessage:Qp,onSubscribe:Xp});br(Pe);fr(Pe);Oe=class t{_optsName;_describeKind;meta;_hasMeta;_config;_deps;_sinks=null;_sinkCount=0;_cached;_status;_cleanup;_store={};_waveHasNewData=!1;_hasNewTerminal=!1;_hasCalledFnOnce=!1;_paused=!1;_pendingWave=!1;_isExecutingFn=!1;_pendingRerun=!1;_rerunDepth=0;_dirtyDepCount=0;_batchPendingMessages=null;_pauseLocks=null;_pauseBuffer=null;_fn;_equals;_resubscribable;_resetOnTeardown;_autoComplete;_autoError;_pausable;_partial;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,n,r){this._config=r.config??Pe,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??Dt;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(Iu);let s={};for(let[a,u]of Object.entries(r.meta??{})){let c={initial:u,name:`${r.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};r.guard!=null&&(c.guard=r.guard),s[a]=new t([],void 0,c)}Object.freeze(s),this.meta=s,this._hasMeta=Object.keys(s).length>0;let i=this;this._actions={emit(a){i._emit([[S,a]])},down(a){i._emit(To(a))},up(a){i._emitUp(To(a))}},this.down=this.down.bind(this),this.up=this.up.bind(this)}get _isTerminal(){return this._status==="completed"||this._status==="errored"}get name(){return this._optsName}get status(){return this._status}get cache(){return this._cached===void 0?void 0:this._cached}get lastMutation(){return this._lastMutation}get v(){return this._versioning}hasGuard(){return this._guard!=null}_applyVersioning(e,n){if(this._isExecutingFn)throw new Error(`Node "${this.name}": _applyVersioning cannot run mid-fn \u2014 call it outside of \`_execFn\` (typically at graph setup time before the first subscribe).`);let r=this._versioningLevel;if(r!=null&&e<=r)return;let o=n?.hash??this._hashFn;o!==this._hashFn&&(this._hashFn=o);let s=this._cached===void 0?void 0:this._cached,i=this._versioning,a=i?.id??n?.id,u=i?.version??0,c=In(e,s,{id:a,hash:o});c.version=u,this._versioning=c,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let n=St(e);if(this._guard!=null&&!this._guard(n,"observe"))return!1;if(this._extraGuards!=null){for(let r of this._extraGuards)if(!r(n,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let n=this._guard!=null||this._extraGuards!=null,r=e?.actor!=null;if(!n&&!r)return;let o=St(e?.actor),s=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(o,s))throw new nt({actor:o,action:s,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(o,s))throw new nt({actor:o,action:s,nodeName:this.name})}this._lastMutation={actor:o,timestamp_ns:le()}}down(e,n){let r=To(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[S,e]])}up(e,n){if(this._deps.length===0)return;let r=To(e);if(r.length===0)return;this._checkGuard(n);let o=n??{internal:!0};this._validateUpTiers(r);for(let s of this._deps)s.node.up?.(r,o)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let n of this._deps)n.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let n=this._config.tierOf;for(let r of e){let o=n(r[0]);if(o===3||o===4)throw new Error(`Node "${this.name}": tier-${o} messages cannot flow up \u2014 DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \`down(...)\` for value delivery; \`up(...)\` is for control signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).`)}}subscribe(e,n){if(n!=null&&this._guard!=null){let u=St(n);if(!this._guard(u,"observe"))throw new nt({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)Ni(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=Au,s.unsub=s.node.subscribe(i=>{if(s.unsub===null)return;let a=this._config.tierOf,u=!1;for(let c of i)a(c[0])>=3&&(u=!0),this._config.onMessage(this,c,{direction:"down-in",depIndex:o},this._actions);u&&this._maybeRunFnOnSettlement()}),n++}}catch(r){this._deps[n].unsub=null;for(let o=0;o<n;o++){let s=this._deps[o];if(s.unsub!=null){let i=s.unsub;s.unsub=null;try{i()}catch{}Ni(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=Iu(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Mn),r.unsub=Au;try{r.unsub=e.subscribe(o=>{if(r.unsub===null)return;let s=this._config.tierOf,i=!1;for(let a of o)s(a[0])>=3&&(i=!0),this._config.onMessage(this,a,{direction:"down-in",depIndex:n},this._actions);i&&this._maybeRunFnOnSettlement()})}catch(o){throw r.unsub=null,this._deps.pop(),this._dirtyDepCount--,o}return n}_deactivate(e=!1){let n=this._cleanup;if(this._cleanup=void 0,typeof n=="function")try{n()}catch(r){this._emit([[O,this._wrapFnError("cleanup threw",r)]])}else if(n!=null&&typeof n=="object"){let r=n.deactivate;if(typeof r=="function")try{r()}catch(o){this._emit([[O,this._wrapFnError("cleanup.deactivate threw",o)]])}}for(let r of this._deps){if(r.unsub!=null){let o=r.unsub;r.unsub=null;try{o()}catch{}}Ni(r)}this._waveHasNewData=!1,this._hasNewTerminal=!1,this._hasCalledFnOnce=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._rerunDepth=0,this._store={},this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null,this._fn!=null&&(this._cached=void 0),e||(this._fn!=null||this._deps.length>0)&&(!this._isTerminal||this._resubscribable)&&(this._status="sentinel")}_onDepMessage(e,n){let r=this._deps[e],o=n[0];if(this._inspectorHooks!=null){let s={kind:"dep_message",depIndex:e,message:n};for(let i of this._inspectorHooks)i(s)}if(o!==yt){if(o===ee){this._depDirtied(r);return}if(o===ze){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(cr);return}if(o===Ge||o===$e){this._emit([n]);return}if(o===de){this._emit(On);return}if(o===S)this._depSettledAsData(r,n[1]);else if(o===$)this._depSettledAsResolved(r);else if(o===M)this._depSettledAsTerminal(r,!0);else if(o===O)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(o===S||o===$)&&this._emit([n]),(o===M||o===O)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(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(ur),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(n=>n.terminal!==void 0&&n.terminal!==!0);if(e!=null){this._autoError&&this._emit([[O,e.terminal]]);return}this._autoComplete&&this._deps.every(n=>n.terminal!==void 0)&&this._emit(dr)}_execFn(){if(!this._fn||this._isTerminal&&!this._resubscribable)return;if(this._isExecutingFn){this._pendingRerun=!0;return}let e=this._cleanup;if(typeof e=="function"){this._cleanup=void 0;try{e()}catch(i){this._emit([[O,this._wrapFnError("cleanup threw",i)]]);return}}else if(e!=null&&typeof e=="object"){let i=e.beforeRun;if(typeof i=="function"){e.beforeRun=void 0;try{i()}catch(a){this._emit([[O,this._wrapFnError("cleanup.beforeRun threw",a)]]);return}}}let n=this._deps.map(i=>i.involvedThisWave?i.dataBatch.length>0?[...i.dataBatch]:[]:void 0),r=this._deps.map(i=>i.prevData);for(let i=0;i<this._deps.length;i++){let a=n[i];a!=null&&a.length>0&&(this._deps[i].prevData=a[a.length-1])}let o=this._deps.map(i=>i.terminal),s={prevData:r,terminalDeps:o,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let i={kind:"run",batchData:n,prevData:r};for(let a of this._inspectorHooks)a(i)}this._isExecutingFn=!0;try{let i=this._fn(n,this._actions,s);if(typeof i=="function")this._cleanup=i;else if(i!=null&&typeof i=="object"){let a=i;(typeof a.beforeRun=="function"||typeof a.deactivate=="function"||typeof a.invalidate=="function")&&(this._cleanup=i)}}catch(i){this._emit([[O,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>Lu?(this._rerunDepth=0,this._emit([[O,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${Lu} \u2014 likely a reactive cycle`)]])):this._maybeRunFnOnSettlement()):this._rerunDepth=0,this._clearWaveFlags()}}_clearWaveFlags(){this._waveHasNewData=!1,this._hasNewTerminal=!1;for(let e of this._deps)e.involvedThisWave=!1,e.dataBatch.length=0}_wrapFnError(e,n){let r=n instanceof Error?n.message:String(n);return new Error(`Node "${this.name}": ${e}: ${r}`,{cause:n})}_frameBatch(e){let n=this._config.tierOf;if(e.length===1)return n(e[0][0])===3&&this._status!=="dirty"?[Rt,e[0]]:e;let r=!0,o=!1,s=!1,i=-1;for(let u of e){let c=n(u[0]);c<i&&(r=!1),c===3&&(o=!0),u[0]===ee&&(s=!0),i=c}let a=e;if(!r){let u=e.map((c,d)=>({m:c,i:d,tier:n(c[0])}));u.sort((c,d)=>c.tier-d.tier||c.i-d.i),a=u.map(c=>c.m)}if(o&&!s&&this._status!=="dirty"){let u=0;for(;u<a.length&&n(a[u][0])===0;)u++;return u===0?[Rt,...a]:[...a.slice(0,u),Rt,...a.slice(u)]}return a}_emit(e){if(e.length===0)return;for(let a=0;a<e.length;a++){let u=e[a];if(u[0]===O&&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]===ze);if(a.length===0)return;n=a}n=this._frameBatch(n);let o=null;for(let a=0;a<n.length;a++){let u=n[a],c=u[0];if(c!==Ge&&c!==$e){o?.push(u);continue}if(u.length<2)throw new Error(`Node "${this.name}": [[${c===Ge?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let d=!0;if(this._pausable!==!1){let l=u[1];if(c===Ge)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(l),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(l))d=!1;else if(this._pauseLocks.delete(l),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let f=this._pauseBuffer;this._pauseBuffer=[],this._emit(f)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}d?o?.push(u):o==null&&(o=n.slice(0,a))}if(o!=null){if(o.length===0)return;n=o}if(this._hasMeta&&n.some(a=>a[0]===de))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(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 c of s)a(c[0])===3?this._pauseBuffer.push(c):u.push(c);u.length>0&&this._dispatchOrAccumulate(u)}else this._dispatchOrAccumulate(s);i!=null&&this._emit([[O,i]])}_updateState(e){let n=this._config.tierOf,r,o,s=-1,i=0;for(let d of e)n(d[0])===3&&i++;let a=i<=1,u=-1;if(this._versioning!=null&&i>1){for(let d=e.length-1;d>=0;d--)if(e[d][0]===S){u=d;break}}for(let d=0;d<e.length;d++){let l=e[d],f=l[0];if(f===S){if(l.length>=2){let p=!1;if(a&&this._cached!==void 0)try{p=this._equals(this._cached,l[1])}catch(m){o=this._wrapFnError("equals threw",m),s=d;break}if(p){r==null&&(r=e.slice(0,d)),r.push(En),this._status="resolved";continue}this._cached=l[1],this._versioning!=null&&(u<0||d===u)&&wr(this._versioning,l[1],this._hashFn)}this._status="settled",r?.push(l)}else if(r?.push(l),f===ee)this._status="dirty";else if(f===$)this._status="resolved";else if(f===M)this._status="completed";else if(f===O)this._status="errored";else if(f===ze){this._cached=void 0,this._status="dirty";let p=this._cleanup;if(typeof p=="function"){this._cleanup=void 0;try{p()}catch{}}else if(p!=null&&typeof p=="object"){let m=p.invalidate;if(typeof m=="function")try{m()}catch{}}}else f===de&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let c=s>=0?r??e.slice(0,s):r??e;return o!=null?{finalMessages:c,equalsError:o}:{finalMessages:c}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let n=[...this._sinks];for(let r of n)r(e)};_dispatchOrAccumulate(e){if(Ou()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],yr(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}Nt(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let n=this._frameBatch(e);Nt(this._deliverToSinks,n,this._config.tierOf)}},Pu=t=>Array.isArray(t),Ei=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function N(t,e){return K([],{...e,initial:t})}function W(t,e){return K((r,o,s)=>t(o,s)??void 0,{describeKind:"producer",...e})}function E(t,e,n){return K(t,(o,s,i)=>{let a=o.map((u,c)=>u!=null&&u.length>0?u.at(-1):i.prevData[c]);s.emit(e(a,i))},{describeKind:"derived",...n})}function me(t,e,n){return K(t,(o,s,i)=>{let a=o.map((u,c)=>u!=null&&u.length>0?u.at(-1):i.prevData[c]);return e(a,s,i)??void 0},{describeKind:"effect",...n})}function kr(t,e,n){let r=new Map;return t.forEach((o,s)=>{r.set(o,s)}),E(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,c=d=>{let l=r.get(d);if(l!==void 0){if(l<s.length){let p=s[l];return p!=null&&p.length>0?p.at(-1):a.prevData[l]}return d.cache}u=!0;let f=n._addDep(d);return r.set(d,f),d.cache};try{let d=t(c,a);u||(i.emit(d),a.store.__autoTrackLastDiscoveryError!=null&&delete a.store.__autoTrackLastDiscoveryError)}catch(d){if(!u)throw d;a.store.__autoTrackLastDiscoveryError=d}};return n=new Oe([],o,{describeKind:"derived",...e}),n}function Mi(t,...e){let n=t;for(let r of e)n=r(n);return n}var ne=et(()=>{"use strict";Ne()});function Sr(t,e,n){let r=new Set;for(let o of t.split(",")){let[s,i]=o.split("/"),a=i?Number.parseInt(i,10):1;if(Number.isNaN(a)||a<1)throw new Error(`Invalid cron step: ${o}`);let u,c;if(s==="*")u=e,c=n;else if(s.includes("-")){let[d,l]=s.split("-");u=Number.parseInt(d,10),c=Number.parseInt(l,10)}else u=Number.parseInt(s,10),c=u;if(Number.isNaN(u)||Number.isNaN(c))throw new Error(`Invalid cron field: ${t}`);if(u<e||c>n)throw new Error(`Cron field out of range: ${t} (${e}-${n})`);if(u>c)throw new Error(`Invalid cron range: ${u}-${c} in ${t}`);for(let d=u;d<=c;d+=a)r.add(d)}return r}function Eo(t){let e=t.trim().split(/\s+/);if(e.length!==5)throw new Error(`Invalid cron: expected 5 fields, got ${e.length}`);return{minutes:Sr(e[0],0,59),hours:Sr(e[1],0,23),daysOfMonth:Sr(e[2],1,31),months:Sr(e[3],1,12),daysOfWeek:Sr(e[4],0,6)}}function _o(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 Ai=et(()=>{"use strict"});var Qu={};ye(Qu,{NS_PER_MS:()=>Be,NS_PER_SEC:()=>ot,constant:()=>Mo,decorrelatedJitter:()=>Lo,exponential:()=>Co,fibonacci:()=>Ao,linear:()=>Oo,resolveBackoffPreset:()=>Gt,withMaxAttempts:()=>Li});function sn(t){return t<0?0:t}function uf(t,e){return e==="none"?t:e==="full"?Math.random()*t:t/2+Math.random()*(t/2)}function cf(t,e){return t+Math.random()*(e-t)}function Mo(t){let e=sn(t);return()=>e}function Oo(t,e){let n=sn(t),r=e===void 0?n:sn(e);return o=>n+r*Math.max(0,o)}function Co(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 c=0;c<Math.max(0,s);c++){if(u>=a){u=a;break}u*=n}i=e*u,i>r&&(i=r)}return uf(i,o)}}function Ao(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 c=i+a;i=a,a=c}return a}return s=>{let i=o(s)*n;return i<=r?i:r}}function Lo(t=100*1e6,e=30*1e9){return(n,r,o)=>{let i=Math.min(e,(o??t)*3);return cf(t,i)}}function Li(t,e){return(n,r,o)=>n>=e?null:t(n,r,o)}function Gt(t){if(t==="constant")return Mo(1*1e9);if(t==="linear")return Oo(1*1e9);if(t==="exponential")return Co();if(t==="fibonacci")return Ao();if(t==="decorrelatedJitter")return Lo();throw new Error(`Unknown backoff preset: "${String(t)}". Use one of: constant, linear, exponential, fibonacci, decorrelatedJitter`)}var Be,ot,Vn=et(()=>{"use strict";Be=1e6,ot=1e9});var Ce,vt=et(()=>{"use strict";Ce=class{_timer;_gen=0;start(e,n){this.cancel(),this._gen+=1;let r=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,r===this._gen&&n()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var Zu={};ye(Zu,{CircuitOpenError:()=>dt,RateLimiterOverflowError:()=>an,TimeoutError:()=>un,circuitBreaker:()=>Tt,fallback:()=>qn,rateLimiter:()=>Wn,retry:()=>Kn,retrySource:()=>Ft,timeout:()=>Un,tokenBucket:()=>$t,withBreaker:()=>Hn,withStatus:()=>Bt});function cn(t){return{describeKind:"derived",...t}}function df(t){return t<0?0:t}function Io(t){return t[1]}function Xu(t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("backoff strategy must return a finite number");return t<0?0:t}function Kn(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"?Gt(r):r;return W(i=>{let a=0,u=!1,c=null,d,l=new Ce;function f(){d?.(),d=void 0}function p(h){if(u)return;if(a>=o){f(),i.down([[O,h]]);return}let g=s===null?0:s(a,h,c);if(g==null){f(),i.down([[O,h]]);return}let y;try{y=Xu(g)}catch{f(),i.down([[O,h]]);return}c=y,a+=1,f();let b=y>0?y/1e6:1;l.start(b,()=>{u||m()})}function m(){l.cancel(),f(),d=t.subscribe(h=>{if(!u)for(let g of h){let y=g[0];if(y===ee)i.down([[ee]]);else if(y===S)a=0,c=null,i.emit(g[1]);else if(y===$)i.down([[$]]);else if(y===M)f(),i.down([[M]]);else if(y===O){p(Io(g));return}else i.down([g])}})}return m(),()=>{u=!0,l.cancel(),f()}},{...cn(),initial:t.cache})}function Ft(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"?Gt(r):r;return W(i=>{let a=0,u=!1,c=null,d,l=new Ce;function f(){d?.(),d=void 0}function p(h){if(u)return;if(a>=o){f(),i.down([[O,h]]);return}let g=s===null?0:s(a,h,c);if(g==null){f(),i.down([[O,h]]);return}let y;try{y=Xu(g)}catch{f(),i.down([[O,h]]);return}c=y,a+=1,f();let b=y>0?y/1e6:1;l.start(b,()=>{u||m()})}function m(){l.cancel(),f();let h;try{h=t()}catch(g){p(g);return}d=h.subscribe(g=>{if(!u)for(let y of g){let b=y[0];if(b===ee)i.down([[ee]]);else if(b===S)a=0,c=null,i.emit(y[1]);else if(b===$)i.down([[$]]);else if(b===M)f(),i.down([[M]]);else if(b===O){p(Io(y));return}else i.down([y])}})}return m(),()=>{u=!0,l.cancel(),f()}},{...cn(),initial:e?.initial})}function Tt(t){let e=Math.max(1,t?.failureThreshold??5),n=df(t?.cooldownNs??30*1e9),r=t?.cooldown??null,o=Math.max(1,t?.halfOpenMax??1),s=t?.now??V,i="closed",a=0,u=0,c=0,d=n,l=0;function f(){if(!r)return n;let h=r(u);return h!==null?h:n}function p(){i="open",d=f(),c=s(),l=0}return{canExecute(){return i==="closed"?!0:i==="open"?s()-c>=d?(i="half-open",l=1,!0):!1:l<o?(l++,!0):!1},recordSuccess(){i==="half-open"?(i="closed",a=0,u=0):i==="closed"&&(a=0)},recordFailure(h){if(i==="half-open"){u++,p();return}i==="closed"&&(a++,a>=e&&p())},get state(){return i},get failureCount(){return a},reset(){i="closed",a=0,u=0,l=0}}}function Hn(t,e){let n=e?.onOpen??"skip";return r=>{let o=K([],(s,i)=>{function a(){o.meta.breakerState.down([[S,t.state]])}let u=r.subscribe(c=>{for(let d of c){let l=d[0];l===ee?i.down([[ee]]):l===S?t.canExecute()?(a(),i.emit(d[1])):(a(),n==="error"?i.down([[O,new dt]]):i.down([[$]])):l===$?i.down([[$]]):l===M?(t.recordSuccess(),a(),i.down([[M]])):l===O?(t.recordFailure(Io(d)),a(),i.down([d])):i.down([d])}});return a(),u},{...cn(),meta:{breakerState:t.state},completeWhenDepsComplete:!1,initial:r.cache});return{node:o,breakerState:o.meta.breakerState}}}function $t(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=V();function o(s){if(e>0){let i=s-r;n=Math.min(t,n+i/1e9*e)}r=s}return{available(){return o(V()),n},tryConsume(s=1){if(s<=0)return!0;let i=V();return o(i),n>=s?(n-=s,!0):!1},putBack(s=1){s<=0||(o(V()),n=Math.min(t,n+s))}}}function Wn(t,e){let{maxEvents:n,windowNs:r}=e;if(n<=0)throw new RangeError("maxEvents must be > 0");if(r<=0)throw new RangeError("windowNs must be > 0");let o=e.maxBuffer;if(o!==void 0&&o<1)throw new RangeError("maxBuffer must be >= 1");let s=e.onOverflow??"drop-newest",i=n*1e9/r;return W(a=>{let u=$t(n,i),c=[],d=new Ce,l=!1,f=1e9/i;function p(){for(;c.length>0;)if(u.tryConsume(1))a.emit(c.shift());else{d.start(Math.max(1,f/1e6),p);return}}let m=t.subscribe(h=>{for(let g of h){if(l)return;let y=g[0];if(y===ee)a.down([[ee]]);else if(y===S){if(o!==void 0&&c.length>=o){if(s!=="drop-newest")if(s==="drop-oldest")c.shift(),c.push(g[1]);else{l=!0,d.cancel(),c.length=0,a.down([[O,new an(o)]]);return}}else c.push(g[1]);p()}else if(y===$)a.down([[$]]);else if(y===M)l=!0,d.cancel(),c.length=0,a.down([[M]]);else if(y===O)l=!0,d.cancel(),c.length=0,a.down([g]);else if(y===de){l=!0,d.cancel(),c.length=0,a.down([g]);return}else a.down([g])}});return()=>{l=!0,d.cancel(),m()}},{...cn(),initial:t.cache})}function Bt(t,e){let n=e?.initialStatus??"pending",r=K([],(o,s)=>{let i=n;return r.meta.status.down([[S,n]]),r.meta.error.down([[S,null]]),t.subscribe(u=>{for(let c of u){let d=c[0];if(d===ee)s.down([[ee]]);else if(d===S)i==="errored"?X(()=>{r.meta.error.down([[S,null]]),r.meta.status.down([[S,"active"]])}):r.meta.status.down([[S,"active"]]),i="active",s.emit(c[1]);else if(d===$)s.down([[$]]);else if(d===M)r.meta.status.down([[S,"completed"]]),i="completed",s.down([[M]]);else if(d===O){let l=Io(c);X(()=>{r.meta.error.down([[S,l]]),r.meta.status.down([[S,"errored"]])}),i="errored",s.down([c])}else s.down([c])}})},{...cn(),meta:{status:n,error:null},completeWhenDepsComplete:!1,resubscribable:!0,initial:t.cache});return{node:r,status:r.meta.status,error:r.meta.error}}function lf(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function pf(t){return t!=null&&typeof t.then=="function"}function ff(t){return t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function"}function qn(t,e){return W(n=>{let r,o;function s(){o?.(),o=void 0,lf(e)||pf(e)||ff(e)?r=z(e).subscribe(a=>{n.down(a)}):(n.emit(e),n.down([[M]]))}return o=t.subscribe(i=>{for(let a of i){let u=a[0];if(u===ee)n.down([[ee]]);else if(u===S)n.emit(a[1]);else if(u===$)n.down([[$]]);else if(u===M)n.down([[M]]);else if(u===O){s();return}else if(u===de){r?.(),n.down([a]);return}else n.down([a])}}),()=>{o?.(),r?.()}},{...cn(),initial:t.cache})}function Un(t,e){if(e<=0)throw new RangeError("timeoutNs must be > 0");return W(n=>{let r=!1,o=new Ce;function s(){let a=e/1e6;o.start(a,()=>{r||(r=!0,i(),n.down([[O,new un(e)]]))})}let i=t.subscribe(a=>{for(let u of a){if(r)return;let c=u[0];if(c===ee)n.down([[ee]]);else if(c===S)s(),n.emit(u[1]);else if(c===$)n.down([[$]]);else if(c===M){o.cancel(),r=!0,n.down([[M]]);return}else if(c===O){o.cancel(),r=!0,n.down([u]);return}else if(c===de){o.cancel(),r=!0,n.down([u]);return}else n.down([u])}});return s(),()=>{r=!0,o.cancel(),i()}},{...cn(),initial:t.cache})}var dt,an,un,Et=et(()=>{"use strict";_e();we();ie();Ne();ne();Vn();ve();vt();dt=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 it(t){return{describeKind:"producer",...t}}function Pi(t){return/[\\^$+?.()|[\]{}]/.test(t)?`\\${t}`:t}function tc(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+=Pi(r)}return e+="$",new RegExp(e)}function nc(t,e){for(let n of e)if(n.test(t))return!0;return!1}function mf(t,e){let n=K([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[$]]);return}for(let a of i)s.emit(a)},{describeKind:"derived",initial:t.cache}),r=n.subscribe.bind(n);return n.subscribe=(o,s)=>(e(o),r(o,s)),n}function at(t,e){let{signal:n,period:r,...o}=e??{};return W(s=>{let i=!1,a=0,u,c,d=()=>{i=!0,u!==void 0&&clearTimeout(u),c!==void 0&&clearInterval(c),n?.removeEventListener("abort",f)},l=()=>{i||(r!=null?(s.emit(a++),c=setInterval(()=>{i||s.emit(a++)},r)):(i=!0,n?.removeEventListener("abort",f),s.emit(a++),s.down([[M]])))},f=()=>{i||(d(),s.down([[O,n.reason]]))};if(n?.aborted){f();return}return u=setTimeout(l,t),n?.addEventListener("abort",f,{once:!0}),d},it(o))}function rc(t){let{signal:e,...n}=t??{};return W(r=>{let o=!1,s,i,a=!1,u=!1,c=typeof requestAnimationFrame=="function"?requestAnimationFrame:void 0,d=typeof cancelAnimationFrame=="function"?cancelAnimationFrame:void 0,l=typeof document<"u"?document:void 0,f=()=>{s!==void 0&&d&&d(s),i!==void 0&&clearTimeout(i),s=void 0,i=void 0},p=()=>{o=!0,f(),a&&(e?.removeEventListener("abort",m),a=!1),u&&l&&(l.removeEventListener("visibilitychange",y),u=!1)},m=()=>{o||(p(),r.down([[O,e.reason]]))},h=b=>{o||(r.emit(b),g())},g=()=>{o||(c&&(!l||l.visibilityState!=="hidden")?s=c(h):i=setTimeout(()=>h(performance.now()),16))},y=()=>{o||(f(),g())};return e?.aborted?(m(),p):(e?.addEventListener("abort",m,{once:!0}),a=e!==void 0,l&&c&&(l.addEventListener("visibilitychange",y),u=!0),g(),p)},it(n))}function Do(t,e){let n=Eo(t),{tickMs:r,output:o,...s}=e??{},i=r??6e4,a=o==="date";return W(u=>{let c=-1,d=()=>{let f=new Date,p=f.getFullYear()*1e8+(f.getMonth()+1)*1e6+f.getDate()*1e4+f.getHours()*100+f.getMinutes();p!==c&&_o(n,f)&&(c=p,u.emit(a?f:le()))};d();let l=setInterval(d,i);return()=>clearInterval(l)},{...it(s),name:s.name??`cron:${t}`})}function oc(t,e,n){let{capture:r,passive:o,once:s,...i}=n??{};return W(a=>{let u=d=>{a.emit(d)},c={capture:r,passive:o,once:s};return t.addEventListener(e,u,c),()=>t.removeEventListener(e,u,c)},it(i))}function Go(t,e){return W(n=>{let r=!1;try{for(let o of t){if(r)return;n.emit(o)}r||n.down([[M]])}catch(o){r||n.down([[O,o]])}return()=>{r=!0}},it(e))}function hf(t){return t!=null&&typeof t.then=="function"}function Di(t,e){let{signal:n,...r}=e??{};return W(o=>{let s=!1,i=()=>{s||(s=!0,o.down([[O,n.reason]]))};if(n?.aborted){i();return}return n?.addEventListener("abort",i,{once:!0}),Promise.resolve(t).then(a=>{s||(s=!0,n?.removeEventListener("abort",i),o.emit(a),o.down([[M]]))},a=>{s||(s=!0,n?.removeEventListener("abort",i),o.down([[O,a]]))}),()=>{s=!0,n?.removeEventListener("abort",i)}},it(r))}function Gi(t,e){let{signal:n,...r}=e??{};return W(o=>{let s=new AbortController,i=()=>s.abort(n?.reason);n?.aborted?s.abort(n.reason):n?.addEventListener("abort",i,{once:!0});let a=n??s.signal,u=!1,c=t[Symbol.asyncIterator](),d=()=>{u||a.aborted||Promise.resolve(c.next()).then(l=>{if(!(u||a.aborted)){if(l.done){o.down([[M]]);return}o.emit(l.value),d()}},l=>{!u&&!a.aborted&&o.down([[O,l]])})};return d(),()=>{u=!0,n?.removeEventListener("abort",i),s.abort(),Promise.resolve(c.return?.()).catch(()=>{})}},it(r))}function gf(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function z(t,e){if(gf(t))return t;if(hf(t))return Di(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return Gi(t,e);if(typeof n[Symbol.iterator]=="function")return Go(t,e)}return Fi(t)}function Fi(...t){return Go(t,void 0)}function sc(t){return W(e=>{e.down([[M]])},it(t))}function ic(t){return W(()=>{},it(t))}function ac(t,e){return W(n=>{n.down([[O,t]])},it(e))}function jt(t,e,n){return K([t],(o,s)=>{let i=o[0];if(i!=null&&i.length>0)for(let a of i)e(a)},{describeKind:"effect",...n}).subscribe(()=>{})}function uc(t,e){return K([t],(n,r,o)=>{o.store.buf||(o.store.buf=[]);let s=o.store.buf,i=n[0];if(i!=null&&i.length>0)for(let a of i)s.push(a);if(o.terminalDeps[0]===!0){r.emit([...s]),r.down([[M]]);return}(i==null||i.length===0)&&r.down([[$]])},{describeKind:"derived",completeWhenDepsComplete:!1,...e})}function cc(t,e){return W(n=>t.subscribe(r=>{n.down(r)}),{...it(e),initial:t.cache})}function Fo(t,e,n){if(e<1)throw new RangeError("replay expects bufferSize >= 1");let r=[],o=W(s=>t.subscribe(i=>{for(let a of i)a[0]===S&&(r.push(a[1]),r.length>e&&r.shift());s.down(i)}),{...it(n),initial:t.cache});return mf(o,s=>{for(let i of r)s([[S,i]])})}function dc(t,e){return Fo(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]===S){r=!0,e(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===O){r=!0,n(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===M){r=!0,n(new Error("completed without DATA")),s?(s(),s=void 0):o=!0;return}}}),o&&(s?.(),s=void 0)})}function Po(t,e,n){return new Promise((r,o)=>{let s=!1,i=!1,a,u=n?.skipCurrent===!0;a=t.subscribe(c=>{for(let d of c){if(s)return;if(!(u&&d[0]===S)){if(d[0]===S){let l=d[1];if(e(l)){s=!0,r(l),a?(a(),a=void 0):i=!0;return}}if(d[0]===O){s=!0,o(d[1]),a?(a(),a=void 0):i=!0;return}if(d[0]===M){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 $o(t,e){let n=e?.predicate??(s=>s!=null),r=e?.skipCurrent;if(e?.timeoutMs==null||e.timeoutMs<=0)return await Po(t,n,{skipCurrent:r});if(Ii===void 0){let[s,i]=await Promise.all([Promise.resolve().then(()=>(Et(),Zu)),Promise.resolve().then(()=>(Vn(),Qu))]);Ii=s.timeout,ec=i.NS_PER_MS}let o=Ii(t,e.timeoutMs*ec);return await Po(o,n,{skipCurrent:r})}function lc(t,e){let n=new AbortController,r=e?.reason??new Error("cancelled via nodeSignal"),o,s=!1,i=()=>{o?(o(),o=void 0):s=!0};return o=t.subscribe(a=>{if(!n.signal.aborted)for(let u of a){if(u[0]===S&&u[1]===!0){n.abort(r),i();return}if(u[0]===O){n.abort(u[1]),i();return}if(u[0]===M){i();return}}}),s&&(o?.(),o=void 0),{signal:n.signal,dispose:()=>{o&&(o(),o=void 0)}}}function re(t){return t.subscribe(()=>{})}function $i(t){let e=N(0);return{node:e,increment(){let n=e.cache??0;return n>=t?!1:(e.down([[ee],[S,n+1]]),!0)},get(){return e.cache??0},atCap(){return(e.cache??0)>=t}}}var Ii,ec,pc,ve=et(()=>{"use strict";we();ie();Ne();ne();Ai();pc=Fo});var $y={};ye($y,{COMPLETE:()=>M,COMPLETE_MSG:()=>ho,COMPLETE_ONLY_BATCH:()=>dr,CircuitOpenError:()=>dt,ContentAddressedMissError:()=>Br,DATA:()=>S,DEFAULT_ACTOR:()=>bt,DIRTY:()=>ee,DIRTY_MSG:()=>Rt,DIRTY_ONLY_BATCH:()=>Mn,ENVELOPE_VERSION:()=>Cn,ERROR:()=>O,GRAPH_META_SEGMENT:()=>He,Graph:()=>q,GraphReFlyConfig:()=>en,GuardDenied:()=>nt,INVALIDATE:()=>ze,INVALIDATE_MSG:()=>mo,INVALIDATE_ONLY_BATCH:()=>cr,JsonCodec:()=>yo,NS_PER_MS:()=>Be,NS_PER_SEC:()=>ot,NativeIndexBackend:()=>Kr,NativeListBackend:()=>Hr,NativeLogBackend:()=>Or,NativeMapBackend:()=>Fr,NativePubSubBackend:()=>Vr,NodeImpl:()=>Oe,PAUSE:()=>Ge,RESOLVED:()=>$,RESOLVED_MSG:()=>En,RESOLVED_ONLY_BATCH:()=>ur,RESUME:()=>$e,RateLimiterOverflowError:()=>an,ResettableTimer:()=>Ce,SIZEOF_OVERHEAD:()=>De,SIZEOF_SYMBOL:()=>Uo,SNAPSHOT_VERSION:()=>lt,SNAPSHOT_WIRE_VERSION:()=>lo,START:()=>yt,START_MSG:()=>_n,SurfaceError:()=>ke,TEARDOWN:()=>de,TEARDOWN_MSG:()=>go,TEARDOWN_ONLY_BATCH:()=>On,TimeoutError:()=>un,accessHintForGuard:()=>Tr,accountability:()=>Us,advanceVersion:()=>wr,ai:()=>Hs,asSurfaceError:()=>ci,audit:()=>pd,autoTrackNode:()=>rn,awaitSettled:()=>$o,batch:()=>X,buffer:()=>fd,bufferCount:()=>md,bufferTime:()=>gd,cached:()=>dc,canonicalJson:()=>jr,cascadingCache:()=>Rl,catchError:()=>Nd,checkpointToRedis:()=>gl,checkpointToS3:()=>hl,circuitBreaker:()=>Tt,combine:()=>sa,combineLatest:()=>xd,compat:()=>ra,concat:()=>sd,concatMap:()=>ud,configure:()=>_i,constant:()=>Mo,contentAddressedStorage:()=>hs,core:()=>qi,cqrs:()=>es,createDagCborCodec:()=>Ti,createDagCborZstdCodec:()=>wi,createGraph:()=>or,createTransport:()=>Wt,createVersioning:()=>In,createWatermarkController:()=>zn,csvRows:()=>Qd,debounce:()=>aa,debounceTime:()=>Rd,decodeEnvelope:()=>pr,decorrelatedJitter:()=>Lo,defaultConfig:()=>Pe,defaultHash:()=>Dt,delay:()=>dd,deleteSnapshot:()=>gi,demoShell:()=>Js,derived:()=>E,deserializeError:()=>bn,dictStorage:()=>Pl,diffForWAL:()=>Qo,diffSnapshots:()=>mi,distill:()=>fs,distinctUntilChanged:()=>nd,domainTemplates:()=>Ys,downWithBatch:()=>Nt,dynamicNode:()=>kr,effect:()=>me,elementAt:()=>Zc,empty:()=>sc,encodeEnvelope:()=>lr,escapeRegexChar:()=>Pi,exhaustMap:()=>ad,explainPath:()=>_r,exponential:()=>Co,externalBundle:()=>ds,externalProducer:()=>mn,extra:()=>ba,fallback:()=>qn,fibonacci:()=>Ao,filter:()=>ft,find:()=>Xc,first:()=>ls,firstValueFrom:()=>Ye,firstWhere:()=>Po,flatMap:()=>cd,forEach:()=>jt,fromAny:()=>z,fromAsyncIter:()=>Gi,fromCSV:()=>Yd,fromClickHouseWatch:()=>tl,fromCron:()=>Do,fromDrizzle:()=>wl,fromEvent:()=>oc,fromHTTP:()=>pa,fromHTTPPoll:()=>Dd,fromHTTPStream:()=>Pd,fromIter:()=>Go,fromKafka:()=>qd,fromKysely:()=>kl,fromMCP:()=>$d,fromNATS:()=>ol,fromNDJSON:()=>el,fromOTel:()=>Bd,fromPrisma:()=>Tl,fromPrometheus:()=>Wd,fromPromise:()=>Di,fromPulsar:()=>nl,fromRabbitMQ:()=>il,fromRaf:()=>rc,fromRedisStream:()=>zd,fromSSE:()=>Id,fromSqlite:()=>yl,fromSqliteCursor:()=>bl,fromStatsD:()=>Kd,fromSyslog:()=>jd,fromTimer:()=>at,fromWebSocket:()=>la,fromWebSocketReconnect:()=>Fd,fromWebhook:()=>Ed,globToRegExp:()=>tc,graph:()=>zi,graphProfile:()=>pn,graphspec:()=>Ks,guarded:()=>Xs,harness:()=>ti,interval:()=>vd,isBatching:()=>Zt,isV1:()=>Si,jobQueue:()=>oi,jotai:()=>wo,keepalive:()=>re,last:()=>Qc,layout:()=>ai,lens:()=>ii,linear:()=>Oo,listSnapshots:()=>hi,lru:()=>ha,makeHttpError:()=>ht,map:()=>Lr,matchesAnyPattern:()=>nc,matchesCron:()=>_o,memory:()=>Bs,memoryStorage:()=>qr,merge:()=>wt,mergeMap:()=>ia,mermaidLiveUrl:()=>Yo,messaging:()=>Is,monotonicNs:()=>V,nameToSignal:()=>gn,nanostores:()=>So,ndjsonRows:()=>Xd,nestjs:()=>ns,never:()=>ic,node:()=>K,nodeSignal:()=>lc,normalizeActor:()=>St,of:()=>Fi,onFirstData:()=>Pr,orchestration:()=>Ps,pairwise:()=>rd,parseCron:()=>Eo,parsePrometheusText:()=>fa,parseSSEStream:()=>At,parseStatsD:()=>Hd,parseSyslog:()=>Vd,patterns:()=>vu,pausable:()=>wd,pipe:()=>Mi,policy:()=>tn,policyFromRules:()=>vr,producer:()=>W,pubsub:()=>Ml,race:()=>id,rateLimiter:()=>Wn,reachable:()=>fn,react:()=>rs,reactiveCounter:()=>$i,reactiveIndex:()=>Al,reactiveList:()=>gs,reactiveLog:()=>We,reactiveMap:()=>Qe,reactiveSink:()=>je,reduce:()=>zc,reduction:()=>Vs,refine:()=>ei,registerBuiltinCodecs:()=>fr,registerBuiltins:()=>br,repeat:()=>Td,replay:()=>Fo,replayWAL:()=>ki,rescue:()=>Dr,resilientPipeline:()=>ui,resolveBackoffPreset:()=>Gt,resolveDescribeFields:()=>_t,restoreSnapshot:()=>fi,retry:()=>Kn,retrySource:()=>Ft,runReduction:()=>di,sample:()=>ld,saveSnapshot:()=>pi,scan:()=>Uc,serializeError:()=>yn,share:()=>cc,shareReplay:()=>pc,signalToName:()=>Ht,signals:()=>ss,singleFromAny:()=>ys,singleNodeFromAny:()=>Ll,sizeof:()=>Mr,skip:()=>oa,solid:()=>is,sortJsonValue:()=>Wr,stableJsonString:()=>Il,state:()=>N,stratify:()=>Ur,surface:()=>yi,svelte:()=>as,switchMap:()=>Te,take:()=>Ir,takeUntil:()=>Yc,takeWhile:()=>Jc,tap:()=>ed,tapFirst:()=>td,throttle:()=>ua,throttleTime:()=>Sd,throwError:()=>ac,timeout:()=>Un,toArray:()=>uc,toCSV:()=>ul,toClickHouse:()=>cl,toFile:()=>ma,toHTTP:()=>_d,toKafka:()=>Ud,toLoki:()=>fl,toMongo:()=>pl,toNATS:()=>sl,toObservable:()=>No,toPostgres:()=>ll,toPulsar:()=>rl,toRabbitMQ:()=>al,toReadableStream:()=>Ld,toRedisStream:()=>Jd,toS3:()=>dl,toSSE:()=>Cd,toSSEBytes:()=>Ad,toSqlite:()=>vl,toTempo:()=>ml,toWebSocket:()=>Gd,tokenBucket:()=>$t,validateGraphObservability:()=>Ui,valve:()=>kd,verifiable:()=>El,version:()=>Fy,vue:()=>us,wallClockNs:()=>le,watchTopologyTree:()=>Mt,window:()=>bd,windowCount:()=>hd,windowTime:()=>yd,withBreaker:()=>Hn,withLatestFrom:()=>hn,withMaxAttempts:()=>Li,withStatus:()=>Bt,workerBridge:()=>ga,workerSelf:()=>ya,zip:()=>od,zustand:()=>cs});module.exports=$p($y);var ra={};ye(ra,{jotai:()=>wo,nanostores:()=>So,nestjs:()=>ns,react:()=>rs,signals:()=>ss,solid:()=>is,svelte:()=>as,vue:()=>us,zustand:()=>cs});var wo={};ye(wo,{atom:()=>Zp});ie();ne();function Zp(t,e,n){if(typeof t=="function"){let r=t;return typeof e=="function"?Du(r,e,n):Du(r,void 0,e)}return ef(t,e)}function xr(t){let e=t.cache,n;if(t.subscribe(o=>{for(let[s,i]of o)s===S&&(e=i),s===O&&(n=i)})(),n)throw n;return e}function ef(t,e){let n=N(t,{...e,resubscribable:!0,resetOnTeardown:!0});return{get:()=>n.status==="sentinel"?xr(n):n.cache,set:r=>n.emit(r),update:r=>{let o=n.status==="sentinel"?xr(n):n.cache;n.emit(r(o))},subscribe:r=>{let o=!0;return n.subscribe(s=>{for(let[i,a]of s)if(i===S){if(o){o=!1;continue}r(a)}})},meta:n.meta,_node:n}}function Du(t,e,n){let r=rn(s=>t(i=>{let a=i._node;return a.status==="sentinel"&&xr(a),s(a)}),{...n,resubscribable:!0,resetOnTeardown:!0}),o={get:()=>r.status==="sentinel"?xr(r):r.cache,subscribe:s=>{let i=!0;return r.subscribe(a=>{for(let[u,c]of a)if(u===S){if(i){i=!1;continue}s(c)}})},meta:r.meta,_node:r};if(e){let s=u=>u.get(),i=(u,c)=>u.set(c),a=o;return a.set=u=>e(s,i,u),a.update=u=>{let c=r.status==="sentinel"?xr(r):r.cache;return e(s,i,u(c))},a}return o}var So={};ye(So,{action:()=>af,atom:()=>tf,computed:()=>nf,getValue:()=>of,map:()=>rf,onMount:()=>sf,onStart:()=>$u,onStop:()=>Bu});_e();ie();ne();var xo=new WeakMap,Ro=new WeakMap;function ko(t,e){let n=e.get(t);if(n)for(let r of n)r()}function Oi(t,e={}){let n=0;return{...e,get:()=>Fu(t),subscribe:o=>{n===0&&ko(t,xo),n++;let s=t.subscribe(i=>{for(let[a,u]of i)a===S&&o(u)});return()=>{s(),n--,n===0&&ko(t,Ro)}},listen:o=>{n===0&&ko(t,xo),n++;let s=!0,i=t.subscribe(a=>{for(let[u,c]of a)if(u===S){if(s){s=!1;continue}o(c)}});return()=>{i(),n--,n===0&&ko(t,Ro)}},_node:t}}function Gu(t){let e=t.cache,n;if(t.subscribe(o=>{for(let[s,i]of o)s===S&&(e=i),s===O&&(n=i)})(),n)throw n;return e}function Fu(t){return t.status==="sentinel"?Gu(t):t.cache}function tf(t){let e=N(t,{resubscribable:!0,resetOnTeardown:!0});return Oi(e,{set:n=>e.emit(n)})}function nf(t,e){let n=Array.isArray(t)?t:[t],r=n.map(s=>s._node),o=kr(r,s=>{let i=n.map(a=>{let u=a._node;return u.status==="sentinel"&&Gu(u),s(u)});return e(...i)},{resubscribable:!0,resetOnTeardown:!0,equals:Object.is});return Oi(o)}function rf(t){let e=N(t,{resubscribable:!0,resetOnTeardown:!0,equals:()=>!1});return Oi(e,{set:n=>e.emit(n),setKey:(n,r)=>{let o=Fu(e);e.emit({...o,[n]:r})}})}function of(t){return t.get()}function $u(t,e){let n=t._node,r=xo.get(n);r||(r=new Set,xo.set(n,r)),r.add(e)}function Bu(t,e){let n=t._node,r=Ro.get(n);r||(r=new Set,Ro.set(n,r)),r.add(e)}function sf(t,e){$u(t,()=>{let n=e();typeof n=="function"&&Bu(t,n)})}function af(t,e,n){return(...r)=>{let o;return X(()=>{o=n(...r)}),o}}var ns={};ye(ns,{ACTOR_KEY:()=>jo,COMMAND_HANDLERS:()=>Fn,CQRS_EVENT_HANDLERS:()=>$n,CRON_HANDLERS:()=>Gn,CommandHandler:()=>Uu,EVENT_HANDLERS:()=>Pn,EventHandler:()=>zu,GRAPHREFLY_REQUEST_GRAPH:()=>on,GRAPHREFLY_ROOT_GRAPH:()=>st,GraphCron:()=>qu,GraphInterval:()=>Wu,GraphReflyEventExplorer:()=>dn,GraphReflyGuard:()=>bc,GraphReflyGuardImpl:()=>Nr,GraphReflyModule:()=>ts,INTERVAL_HANDLERS:()=>Dn,InjectCqrsGraph:()=>Vu,InjectGraph:()=>ju,InjectNode:()=>Ku,ObserveGateway:()=>Bo,OnGraphEvent:()=>Hu,QUERY_HANDLERS:()=>Bn,QueryHandler:()=>Ju,SAGA_HANDLERS:()=>jn,SagaHandler:()=>Yu,fromHeader:()=>gc,fromJwtPayload:()=>Vi,getActor:()=>yc,getGraphToken:()=>rt,getNodeToken:()=>ct,observeSSE:()=>mc,observeSubscription:()=>hc,toObservable:()=>No});var Ci=require("rxjs");ie();function No(t,e){return e?.raw?new Ci.Observable(n=>t.subscribe(o=>{if(!n.closed){n.next(o);for(let s of o){if(s[0]===O){n.error(s[1]);return}if(s[0]===M){n.complete();return}}}})):new Ci.Observable(n=>t.subscribe(o=>{for(let s of o){if(n.closed)return;if(s[0]===S)n.next(s[1]);else if(s[0]===O){n.error(s[1]);return}else if(s[0]===M){n.complete();return}}}))}var Rr=require("@nestjs/common");var st=Symbol.for("graphrefly:root-graph");var on=Symbol.for("graphrefly:request-graph");function rt(t){return Symbol.for(`graphrefly:graph:${t}`)}function ct(t){return Symbol.for(`graphrefly:node:${t}`)}var Pn=new Map,Dn=new Map,Gn=new Map,Fn=new Map,$n=new Map,Bn=new Map,jn=new Map;function ju(t){return t==="request"?(0,Rr.Inject)(on):(0,Rr.Inject)(t?rt(t):st)}function Vu(t){return(0,Rr.Inject)(rt(t))}function Ku(t){return(0,Rr.Inject)(ct(t))}function Hu(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 Wu(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 qu(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 Uu(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 zu(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 Ju(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=Bn.get(s)??[];i.push({cqrsName:t,projectionName:e,methodKey:o}),Bn.set(s,i)})}}function Yu(t,e,n){return(r,o)=>{let s=o.name;o.addInitializer(function(){let i=this.constructor,a=jn.get(i)??[];a.push({cqrsName:t,eventNames:n,sagaName:e,methodKey:s}),jn.set(i,a)})}}ie();ve();var fc=0,dn=class{constructor(e,n){this.graph=e;this.moduleRef=n}disposers=[];scheduleNodeNames=[];onModuleInit(){this.wireEvents(),this.wireIntervals(),this.wireCrons(),this.wireCqrsCommands(),this.wireCqrsEvents(),this.wireCqrsQueries(),this.wireCqrsSagas()}onModuleDestroy(){for(let e of this.disposers)e();this.disposers.length=0;for(let e of this.scheduleNodeNames)try{this.graph.remove(e)}catch{}this.scheduleNodeNames.length=0}wireEvents(){for(let[e,n]of Pn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireEventHandler(r,o)}}wireEventHandler(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),i=this.observeNode(n.nodeName).subscribe(a=>{for(let u of a)u[0]===S&&o(u[1])});this.disposers.push(i)}wireIntervals(){for(let[e,n]of 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)}.${fc++}`,u=at(r.ms,{period:r.ms,name:a});this.graph.add(u),this.scheduleNodeNames.push(a);let d=this.observeNode(a).subscribe(l=>{for(let f of l)f[0]===S&&s(f[1])});this.disposers.push(d)}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)}.${fc++}`,u=Do(r.expr,{name:a});this.graph.add(u),this.scheduleNodeNames.push(a);let d=this.observeNode(a).subscribe(l=>{for(let f of l)f[0]===S&&s(f[1])});this.disposers.push(d)}wireCqrsCommands(){for(let[e,n]of 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,d=this.observeNodeOn(s,n.eventName).subscribe(l=>{for(let f of l)if(f[0]===S){let p=f[1];for(let m of p)m.seq>u&&(o(m),u=m.seq)}});this.disposers.push(d)}wireCqrsQueries(){for(let[e,n]of Bn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsQuery(r,o)}}wireCqrsQuery(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);if(!s)return;let a=this.observeNodeOn(s,n.projectionName).subscribe(u=>{for(let c of u)c[0]===S&&o(c[1])});this.disposers.push(a)}wireCqrsSagas(){for(let[e,n]of jn){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(rt(e),{strict:!1})}catch{return console.warn(`[GraphReFly] CqrsGraph "${e}" not found in DI \u2014 did you import GraphReflyModule.forCqrs({ name: "${e}" })?`),null}}resolveInstance(e){try{return this.moduleRef.get(e,{strict:!1})}catch{return null}}};ie();ie();var yf=0;function zn(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-${++yf}`),r=0,o=!1;return{onEnqueue(){return r+=1,!o&&r>=e.highWaterMark?(o=!0,t([[Ge,n]]),!0):!1},onDequeue(){return r>0&&(r-=1),o&&r<=e.lowWaterMark?(o=!1,t([[$e,n]]),!0):!1},get pending(){return r},get paused(){return o},dispose(){o&&(o=!1,t([[$e,n]]))}}}function mc(t,e,n){let{actor:r,serialize:o=bf,keepAliveMs:s,signal:i}=n??{},a=new TextEncoder,u,c=n?.highWaterMark!=null,d,l,f=[],p=!1;return new ReadableStream({start(m){let h,g=()=>{},y=()=>{if(!p){p=!0,h!==void 0&&clearInterval(h),i?.removeEventListener("abort",b),g(),d?.dispose(),l?.(),l=void 0;for(let T of f)m.enqueue(T.frame);f.length=0,m.close()}};u=y;let b=()=>y(),v=t.observe(e,{actor:r});c&&(d=zn(T=>v.up(T),{highWaterMark:n.highWaterMark,lowWaterMark:n.lowWaterMark??Math.floor(n.highWaterMark/2)})),g=v.subscribe(T=>{for(let w of T){if(p)return;let k=w[0];if(k===S){let x=a.encode(Bi("data",o(w[1])));c?(f.push({frame:x,counted:!0}),d.onEnqueue(),l?.(),l=void 0):m.enqueue(x)}else if(k===O){let x=a.encode(Bi("error",o(w[1])));c?(f.push({frame:x,counted:!1}),l?.(),l=void 0):m.enqueue(x),y();return}else if(k===M||k===de){if(k===M){let x=a.encode(Bi("complete"));c?(f.push({frame:x,counted:!1}),l?.(),l=void 0):m.enqueue(x)}y();return}}}),s!==void 0&&s>0&&(h=setInterval(()=>{p||(c?(f.push({frame:a.encode(`: keepalive
2
2
 
3
3
  `),counted:!1}),l?.(),l=void 0):m.enqueue(a.encode(`: keepalive
4
4
 
5
- `)))},s)),i?.aborted?b():i?.addEventListener("abort",b,{once:!0})},pull(m){if(c&&!p){if(f.length>0){let h=f.shift();m.enqueue(h.frame),h.counted&&d.onDequeue();return}return new Promise(h=>{l=h})}},cancel(){try{u?.()}catch{}}})}function tc(t,e,n){let{actor:r,filter:o}=n??{},s=[],i=[],a=!1,u=t.observe(e,{actor:r}),c=n?.highWaterMark!=null?Hn(m=>u.up(m),{highWaterMark:n.highWaterMark,lowWaterMark:n.lowWaterMark??Math.floor(n.highWaterMark/2)}):void 0,d=()=>{a||(a=!0,c?.dispose(),f())},l=m=>{if(!a)if(i.length>0){let h=i.shift();m.done&&m.error?h.reject(m.error):m.done?h.resolve({done:!0,value:void 0}):h.resolve({done:!1,value:m.value})}else s.push(m),m.done||c?.onEnqueue()},f=u.subscribe(m=>{for(let h of m){let g=h[0];if(g===S){let y=h[1];if(o&&!o(y))continue;l({done:!1,value:y})}else if(g===M){let y=h[1]instanceof Error?h[1]:new Error(String(h[1]));l({done:!0,error:y}),d();return}else if(g===_||g===de){l({done:!0}),d();return}}});return{next(){if(s.length>0){let m=s.shift();return m.done||c?.onDequeue(),m.done&&m.error?Promise.reject(m.error):Promise.resolve(m.done?{done:!0,value:void 0}:{done:!1,value:m.value})}return a?Promise.resolve({done:!0,value:void 0}):new Promise((m,h)=>{i.push({resolve:m,reject:h})})},return(){d();for(let m of i)m.resolve({done:!0,value:void 0});return i.length=0,Promise.resolve({done:!0,value:void 0})},throw(m){return d(),Promise.reject(m)},[Symbol.asyncIterator](){return this}}}var No=class{constructor(e,n){this.graph=e;this.extractActor=n?.extractActor??(()=>{}),this.parse=n?.parse??uf,this.highWaterMark=n?.highWaterMark,this.lowWaterMark=n?.lowWaterMark}clients=new Map;extractActor;parse;highWaterMark;lowWaterMark;handleConnection(e){this.clients.has(e)||this.clients.set(e,new Map)}handleDisconnect(e){let n=this.clients.get(e);if(n){for(let r of n.values())r.wm?.dispose(),r.unsub();this.clients.delete(e)}}handleMessage(e,n,r){let o=r??cf.bind(null,e),s;try{s=typeof n=="string"?this.parse(n):n}catch{o({type:"err",message:"invalid command"});return}s.type==="subscribe"?this.subscribe(e,s.path,o):s.type==="unsubscribe"?this.unsubscribe(e,s.path,o):s.type==="ack"?this.ack(e,s.path,s.count??1):o({type:"err",message:`unknown command type: ${s.type}`})}subscriptionCount(e){return this.clients.get(e)?.size??0}destroy(){for(let[e]of this.clients)this.handleDisconnect(e)}subscribe(e,n,r){let o=this.clients.get(e);if(o||(o=new Map,this.clients.set(e,o)),o.has(n)){r({type:"subscribed",path:n});return}let s=this.extractActor(e),i;try{i=this.graph.observe(n,{actor:s})}catch(d){let l=d instanceof Error?d.message:String(d);r({type:"err",message:l});return}let a=this.highWaterMark!=null?Hn(d=>i.up(d),{highWaterMark:this.highWaterMark,lowWaterMark:this.lowWaterMark??Math.floor(this.highWaterMark/2)}):void 0,u=()=>{a?.dispose(),c(),o.delete(n)},c=i.subscribe(d=>{for(let l of d){let f=l[0];if(f===S)a?.onEnqueue(),Si(r,{type:"data",path:n,value:l[1]});else if(f===M){let p=l[1]instanceof Error?l[1].message:String(l[1]);Si(r,{type:"error",path:n,error:p}),u();return}else if(f===_||f===de){Si(r,{type:"complete",path:n}),u();return}}});o.set(n,{unsub:c,wm:a}),r({type:"subscribed",path:n})}unsubscribe(e,n,r){let o=this.clients.get(e),s=o?.get(n);s&&(s.wm?.dispose(),s.unsub(),o.delete(n)),r({type:"unsubscribed",path:n})}ack(e,n,r){let o=this.clients.get(e)?.get(n);if(!o?.wm)return;let s=Math.min(Math.max(0,Math.floor(r)),1024);for(let i=0;i<s;i++)o.wm.onDequeue()}};function af(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)}catch{return String(t)}}function Ri(t,e){let n=`event: ${t}
5
+ `)))},s)),i?.aborted?b():i?.addEventListener("abort",b,{once:!0})},pull(m){if(c&&!p){if(f.length>0){let h=f.shift();m.enqueue(h.frame),h.counted&&d.onDequeue();return}return new Promise(h=>{l=h})}},cancel(){try{u?.()}catch{}}})}function hc(t,e,n){let{actor:r,filter:o}=n??{},s=[],i=[],a=!1,u=t.observe(e,{actor:r}),c=n?.highWaterMark!=null?zn(m=>u.up(m),{highWaterMark:n.highWaterMark,lowWaterMark:n.lowWaterMark??Math.floor(n.highWaterMark/2)}):void 0,d=()=>{a||(a=!0,c?.dispose(),f())},l=m=>{if(!a)if(i.length>0){let h=i.shift();m.done&&m.error?h.reject(m.error):m.done?h.resolve({done:!0,value:void 0}):h.resolve({done:!1,value:m.value})}else s.push(m),m.done||c?.onEnqueue()},f=u.subscribe(m=>{for(let h of m){let g=h[0];if(g===S){let y=h[1];if(o&&!o(y))continue;l({done:!1,value:y})}else if(g===O){let y=h[1]instanceof Error?h[1]:new Error(String(h[1]));l({done:!0,error:y}),d();return}else if(g===M||g===de){l({done:!0}),d();return}}});return{next(){if(s.length>0){let m=s.shift();return m.done||c?.onDequeue(),m.done&&m.error?Promise.reject(m.error):Promise.resolve(m.done?{done:!0,value:void 0}:{done:!1,value:m.value})}return a?Promise.resolve({done:!0,value:void 0}):new Promise((m,h)=>{i.push({resolve:m,reject:h})})},return(){d();for(let m of i)m.resolve({done:!0,value:void 0});return i.length=0,Promise.resolve({done:!0,value:void 0})},throw(m){return d(),Promise.reject(m)},[Symbol.asyncIterator](){return this}}}var Bo=class{constructor(e,n){this.graph=e;this.extractActor=n?.extractActor??(()=>{}),this.parse=n?.parse??vf,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??Tf.bind(null,e),s;try{s=typeof n=="string"?this.parse(n):n}catch{o({type:"err",message:"invalid command"});return}s.type==="subscribe"?this.subscribe(e,s.path,o):s.type==="unsubscribe"?this.unsubscribe(e,s.path,o):s.type==="ack"?this.ack(e,s.path,s.count??1):o({type:"err",message:`unknown command type: ${s.type}`})}subscriptionCount(e){return this.clients.get(e)?.size??0}destroy(){for(let[e]of this.clients)this.handleDisconnect(e)}subscribe(e,n,r){let o=this.clients.get(e);if(o||(o=new Map,this.clients.set(e,o)),o.has(n)){r({type:"subscribed",path:n});return}let s=this.extractActor(e),i;try{i=this.graph.observe(n,{actor:s})}catch(d){let l=d instanceof Error?d.message:String(d);r({type:"err",message:l});return}let a=this.highWaterMark!=null?zn(d=>i.up(d),{highWaterMark:this.highWaterMark,lowWaterMark:this.lowWaterMark??Math.floor(this.highWaterMark/2)}):void 0,u=()=>{a?.dispose(),c(),o.delete(n)},c=i.subscribe(d=>{for(let l of d){let f=l[0];if(f===S)a?.onEnqueue(),ji(r,{type:"data",path:n,value:l[1]});else if(f===O){let p=l[1]instanceof Error?l[1].message:String(l[1]);ji(r,{type:"error",path:n,error:p}),u();return}else if(f===M||f===de){ji(r,{type:"complete",path:n}),u();return}}});o.set(n,{unsub:c,wm:a}),r({type:"subscribed",path:n})}unsubscribe(e,n,r){let o=this.clients.get(e),s=o?.get(n);s&&(s.wm?.dispose(),s.unsub(),o.delete(n)),r({type:"unsubscribed",path:n})}ack(e,n,r){let o=this.clients.get(e)?.get(n);if(!o?.wm)return;let s=Math.min(Math.max(0,Math.floor(r)),1024);for(let i=0;i<s;i++)o.wm.onDequeue()}};function bf(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)}catch{return String(t)}}function Bi(t,e){let n=`event: ${t}
6
6
  `;if(e!==void 0)for(let r of e.split(`
7
7
  `))n+=`data: ${r}
8
8
  `;return n+=`
9
- `,n}function uf(t){return JSON.parse(t)}function cf(t,e){try{t.send(JSON.stringify(e))}catch{}}function Si(t,e){try{t(e)}catch{}}ur();var Eo="graphReflyActor";function Ni(t){return e=>{let r=e.switchToHttp().getRequest()?.user;if(r!=null)return t?t(r):r}}function nc(t="x-graphrefly-actor"){return e=>{let r=e.switchToHttp().getRequest()?.headers?.[t.toLowerCase()];if(!(typeof r!="string"||r.length===0))try{return JSON.parse(r)}catch{return}}}function rc(t){let e=t?.[Eo];return e!=null?bt(e):lt}var Tr=class{constructor(e){this.extractor=e}canActivate(e){let n=bt(this.extractor(e)),r=e.switchToHttp().getRequest();return r!=null&&(r[Eo]=n),!0}};function oc(t){return new Tr(t??Ni())}var Nr=require("@nestjs/common"),_c=require("@nestjs/core");ur();Ne();ke();Qt();ie();Qt();xe();function wt(t,e){if(e!=null&&e.length>0)return new Set(e);switch(t){case"standard":return new Set(["type","status","value","deps","meta","v"]);case"full":return null;default:return new Set(["type","deps"])}}function df(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function lf(t){let e={};for(let[n,r]of Object.entries(t.meta))try{e[n]=r.cache}catch{}return e}function wr(t,e){let n=e==null,r=!n&&e!=null?[...e].filter(c=>c.startsWith("meta.")).map(c=>c.slice(5)):null,o=n||e.has("meta")||r!=null&&r.length>0,s="state",i=[];t instanceof Ee&&(s=df(t),i=t._deps.map(c=>c.node.name??""));let a={type:s,deps:i};(n||e.has("status"))&&(a.status=t.status);let u=t instanceof Ee?t._guard:void 0;if(o){let c={...lf(t)};if(u!=null&&c.access===void 0&&(c.access=mr(u)),r!=null&&r.length>0&&!e.has("meta")){let d={};for(let l of r)l in c&&(d[l]=c[l]);a.meta=d}else a.meta=c}if(t.name!=null&&(a.name=t.name),n||e.has("value")){t.status==="sentinel"&&(a.sentinel=!0);try{a.value=t.cache}catch{}}if((n||e.has("v"))&&t.v!=null){let c={id:t.v.id,version:t.v.version};"cid"in t.v&&(c.cid=t.v.cid,c.prev=t.v.prev),a.v=c}return(n||e.has("guard"))&&u!=null&&(a.guard=mr(u)),(n||e.has("lastMutation"))&&t.lastMutation!=null&&(a.lastMutation=t.lastMutation),a}xe();oe();Re();pt();var sn=class{constructor(e){this.capacity=e;if(!Number.isInteger(e)||e<=0)throw new Error(`RingBuffer capacity must be a positive integer (got ${e})`);this.buf=new Array(e)}buf;head=0;_size=0;get size(){return this._size}get maxSize(){return this.capacity}push(e){let n=(this.head+this._size)%this.capacity;this.buf[n]=e,this._size<this.capacity?this._size++:this.head=(this.head+1)%this.capacity}shift(){if(this._size===0)return;let e=this.buf[this.head];return this.buf[this.head]=void 0,this.head=(this.head+1)%this.capacity,this._size--,e}at(e){if(this._size===0)return;let n=e<0?this._size+e:e;if(!(n<0||n>=this._size))return this.buf[(this.head+n)%this.capacity]}toArray(){let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this.buf[(this.head+n)%this.capacity];return e}clear(){for(let e=0;e<this._size;e++)this.buf[(this.head+e)%this.capacity]=void 0;this.head=0,this._size=0}};ro();function Ei(t){return t>=768&&t<=879||t>=1155&&t<=1161||t>=1425&&t<=1469||t>=1552&&t<=1562||t>=1611&&t<=1631||t>=1648&&t===1648||t>=1750&&t<=1756||t>=1759&&t<=1764||t>=1767&&t<=1768||t>=1770&&t<=1773||t>=1840&&t<=1866||t>=1958&&t<=1968||t>=2304&&t<=2307||t>=2362&&t<=2383||t>=2385&&t<=2391||t>=2402&&t<=2403||t>=2433&&t<=2435||t>=2492&&t<=2509||t>=2561&&t<=2563||t>=2620&&t<=2641||t>=2672&&t<=2673||t>=2677&&t===2677||t>=3633&&t===3633||t>=3636&&t<=3642||t>=3655&&t<=3662||t>=3761&&t===3761||t>=3764&&t<=3772||t>=3784&&t<=3790||t>=7616&&t<=7679||t>=8400&&t<=8447||t>=65024&&t<=65039||t>=65056&&t<=65071||t===8205?0:t>=4352&&t<=4447||t>=8986&&t<=8987||t>=9001&&t<=9002||t>=9193&&t<=9203||t>=9208&&t<=9210||t>=9725&&t<=9726||t>=9748&&t<=9749||t>=9800&&t<=9811||t===9855||t===9875||t===9889||t>=9898&&t<=9899||t>=9917&&t<=9918||t>=9924&&t<=9925||t===9934||t===9940||t===9962||t>=9970&&t<=9971||t===9973||t===9978||t===9981||t===9986||t===9989||t>=9992&&t<=9997||t===9999||t>=10067&&t<=10069||t===10071||t>=10133&&t<=10135||t===10160||t===10175||t>=10548&&t<=10549||t>=11013&&t<=11015||t>=11035&&t<=11036||t===11088||t===11093||t>=11904&&t<=12350||t>=12352&&t<=12447||t>=12448&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12784&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=19968&&t<=40959||t>=43360&&t<=43388||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65131||t>=65281&&t<=65376||t>=65504&&t<=65510||t>=126980&&t===126980||t===127183||t>=127344&&t<=127345||t===127358||t===127359||t===127374||t>=127377&&t<=127386||t>=127456&&t<=127487||t>=127488&&t<=127490||t===127514||t===127535||t>=127538&&t<=127546||t>=127568&&t<=127569||t>=127744&&t<=129535||t>=129536&&t<=129791||t>=129792&&t<=130047||t>=131072&&t<=196605||t>=196608&&t<=262141?2:1}function Wn(t){let e=0;for(let n of t)e+=Ei(n.codePointAt(0));return e}function sc(t,e){if(e<=0)return"";let n=0,r="";for(let o of t){let s=Ei(o.codePointAt(0));if(n+s>e){if(e<=1)return"\u2026";for(;n+1>e&&r.length>0;){let i=[...r].pop();r=r.slice(0,-i.length),n-=Ei(i.codePointAt(0))}return`${r}\u2026`}r+=o,n+=s}return r}var pf={horizontal:"\u2500",vertical:"\u2502",cornerTL:"\u250C",cornerTR:"\u2510",cornerBL:"\u2514",cornerBR:"\u2518",tDown:"\u252C",tUp:"\u2534",tRight:"\u251C",tLeft:"\u2524",cross:"\u253C",arrowRight:"\u25B6",arrowDown:"\u25BC",arrowLeft:"\u25C0",arrowUp:"\u25B2",boxTL:"\u250C",boxTR:"\u2510",boxBL:"\u2514",boxBR:"\u2518",boxH:"\u2500",boxV:"\u2502"},ff={horizontal:"-",vertical:"|",cornerTL:"+",cornerTR:"+",cornerBL:"+",cornerBR:"+",tDown:"+",tUp:"+",tRight:"+",tLeft:"+",cross:"+",arrowRight:">",arrowDown:"v",arrowLeft:"<",arrowUp:"^",boxTL:"+",boxTR:"+",boxBL:"+",boxBR:"+",boxH:"-",boxV:"|"};function cc(t,e){let n=e.charset==="ascii"?ff:pf,r=t.width,o=t.height,s=Array.from({length:o},()=>Array.from({length:r},()=>" ")),i=Array.from({length:o},()=>Array.from({length:r},()=>"empty"));for(let a of t.edges)hf(s,i,n,a);for(let a of t.boxes)mf(s,i,n,a,e.labelOf(a.id));return s.map(a=>vf(a.join(""))).join(`
10
- `)}function mf(t,e,n,r,o){let{x:s,y:i,w:a,h:u}=r;if(a<2||u<2){u>0&&ic(t,e,s,i,a,o);return}Dt(t,e,s,i,n.boxTL);for(let d=s+1;d<s+a-1;d+=1)Dt(t,e,d,i,n.boxH);Dt(t,e,s+a-1,i,n.boxTR);for(let d=i+1;d<i+u-1;d+=1){Dt(t,e,s,d,n.boxV);for(let l=s+1;l<s+a-1;l+=1)dc(t,e,l,d," ","empty");Dt(t,e,s+a-1,d,n.boxV)}Dt(t,e,s,i+u-1,n.boxBL);for(let d=s+1;d<s+a-1;d+=1)Dt(t,e,d,i+u-1,n.boxH);Dt(t,e,s+a-1,i+u-1,n.boxBR);let c=i+Math.floor(u/2);ic(t,e,s+1,c,a-2,o)}function Dt(t,e,n,r,o){dc(t,e,n,r,o,o===" "?"empty":o==="\u2500"||o==="-"?"boxH":o==="\u2502"||o==="|"?"boxV":"boxCorner")}function dc(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];n<0||n>=i.length||(i[n]=o,e[r][n]=s)}function ic(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=n,a=o;for(let u of s){let c=Wn(u);if(c!==0){if(a<c)break;i>=0&&i<t[r].length&&(t[r][i]=u,e[r][i]="label",c===2&&i+1<t[r].length&&(t[r][i+1]="",e[r][i+1]="label")),i+=c,a-=c}}for(;a>0;)i>=0&&i<t[r].length&&(t[r][i]=" ",e[r][i]="empty"),i+=1,a-=1}function hf(t,e,n,r){let o=r.points;if(o.length<2)return;for(let u=0;u+1<o.length;u+=1)gf(t,e,n,o[u],o[u+1]);for(let u=1;u+1<o.length;u+=1){let c=o[u-1],d=o[u],l=o[u+1],f=yf(c,d,l,n);f&&uc(t,e,d.x,d.y,f,"edgeCorner")}let s=o[o.length-1],i=o[o.length-2],a=bf(i,s,n);a&&uc(t,e,s.x,s.y,a,"arrow")}function gf(t,e,n,r,o){if(!(r.x===o.x&&r.y===o.y)){if(r.y===o.y){let s=r.y,i=Math.min(r.x,o.x),a=Math.max(r.x,o.x);for(let u=i;u<=a;u+=1)ac(t,e,u,s,n,"h")}else if(r.x===o.x){let s=r.x,i=Math.min(r.y,o.y),a=Math.max(r.y,o.y);for(let u=i;u<=a;u+=1)ac(t,e,s,u,n,"v")}}}function ac(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];if(!(a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label")){if(a==="empty"){i[n]=s==="h"?o.horizontal:o.vertical,e[r][n]=s==="h"?"edgeH":"edgeV";return}if(a==="edgeH"&&s==="v"){i[n]=o.cross,e[r][n]="edgeCorner";return}if(a==="edgeV"&&s==="h"){i[n]=o.cross,e[r][n]="edgeCorner";return}}}function uc(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label"||(i[n]=o,e[r][n]=s)}function yf(t,e,n,r){let o=t.y===e.y,s=e.y===n.y;if(o===s)return;if(o){let u=t.x<e.x,c=n.y>e.y;return u&&c?r.cornerTR:u&&!c?r.cornerBR:!u&&c?r.cornerTL:r.cornerBL}let i=t.y<e.y,a=n.x>e.x;return i&&a?r.cornerBL:i&&!a?r.cornerBR:!i&&a?r.cornerTL:r.cornerTR}function bf(t,e,n){if(e.x>t.x)return n.arrowRight;if(e.x<t.x)return n.arrowLeft;if(e.y>t.y)return n.arrowDown;if(e.y<t.y)return n.arrowUp}function vf(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}function fc(t){let e=Tf(t);wf(e),kf(e),xf(e),Rf(e,t);let n=Ef(e,t),{width:r,height:o}=Mf(e),s=[];for(let i of e.layers)for(let a of i)a.isVirtual||s.push({id:a.id,layer:a.layer,order:a.order,x:a.x,y:a.y,w:a.w,h:a.h});return{boxes:s,edges:n,width:r,height:o}}function Tf(t){let e=new Map;for(let o of t.nodes)e.set(o,{id:o,isVirtual:!1,layer:-1,order:0,x:0,y:0,w:t.widthCells(o),h:t.heightCells(o),in:[],out:[]});let n=[],r=0;for(let o of t.edges){if(o.from===o.to)continue;let s=e.get(o.from),i=e.get(o.to);if(!s||!i)continue;let a={chainId:r++,chainFrom:o.from,chainTo:o.to,fromId:o.from,toId:o.to,hopIndex:0,chainLen:1};s.out.push(a),i.in.push(a),n.push(a)}return{nodes:e,layers:[],hops:n}}function wf(t){let e=new Map;for(let s of t.nodes.values())e.set(s.id,s.in.length);let n=[];for(let s of t.nodes.values())(e.get(s.id)??0)===0&&(s.layer=0,n.push(s));let r=new Set,o=0;for(;o<n.length;){let s=n[o++];if(!r.has(s.id)){r.add(s.id);for(let i of s.out){let a=t.nodes.get(i.toId);a.layer=Math.max(a.layer,s.layer+1);let u=(e.get(a.id)??0)-1;e.set(a.id,u),u<=0&&n.push(a)}}}for(let s of t.nodes.values())s.layer<0&&(s.layer=0)}function kf(t){let e=Math.max(0,...Array.from(t.nodes.values(),s=>s.layer)),n=Array.from({length:e+1},()=>[]);for(let s of t.nodes.values())n[s.layer].push(s);let r=[],o=0;for(let s of t.hops){let i=t.nodes.get(s.fromId),a=t.nodes.get(s.toId),u=a.layer-i.layer;if(u<=0){i.out=i.out.filter(l=>l!==s),a.in=a.in.filter(l=>l!==s);continue}if(u===1){s.hopIndex=0,s.chainLen=1,r.push(s);continue}i.out=i.out.filter(l=>l!==s),a.in=a.in.filter(l=>l!==s);let c=i;for(let l=1;l<u;l+=1){let f=`__virt_${o++}__`,p={id:f,isVirtual:!0,layer:i.layer+l,order:0,x:0,y:0,w:0,h:1,in:[],out:[]};t.nodes.set(f,p),n[p.layer].push(p);let m={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:c.id,toId:f,hopIndex:l-1,chainLen:u};c.out.push(m),p.in.push(m),r.push(m),c=p}let d={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:c.id,toId:a.id,hopIndex:u-1,chainLen:u};c.out.push(d),a.in.push(d),r.push(d)}for(let s of n)for(let i=0;i<s.length;i+=1)s[i].order=i;t.layers=n,t.hops=r}function xf(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)lc(t,t.layers[r],"in"),_o(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)lc(t,t.layers[r],"out"),_o(t.layers[r])}for(let n=0;n<2;n+=1){let r=!1;for(let o=1;o<t.layers.length;o+=1){let s=t.layers[o];for(let i=0;i+1<s.length;i+=1){let a=pc(t,s[i],s[i+1],"in");[s[i],s[i+1]]=[s[i+1],s[i]],_o(s),pc(t,s[i],s[i+1],"in")<a?r=!0:([s[i],s[i+1]]=[s[i+1],s[i]],_o(s))}}if(!r)break}}function lc(t,e,n){let r=new Map;for(let o of e){let s=n==="in"?o.in:o.out;if(s.length===0){r.set(o.id,o.order);continue}let i=0,a=0;for(let u of s){let c=t.nodes.get(n==="in"?u.fromId:u.toId);c&&(i+=c.order,a+=1)}r.set(o.id,a===0?o.order:i/a)}e.sort((o,s)=>{let i=r.get(o.id),a=r.get(s.id);return i!==a?i-a:o.order-s.order})}function _o(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function pc(t,e,n,r){let o=r==="in"?e.in:e.out,s=r==="in"?n.in:n.out,i=0;for(let a of o)for(let u of s){let c=t.nodes.get(r==="in"?a.fromId:a.toId)?.order??0,d=t.nodes.get(r==="in"?u.fromId:u.toId)?.order??0;(e.order<n.order&&c>d||e.order>n.order&&c<d)&&(i+=1)}return i}function Rf(t,e){e.direction==="LR"?Sf(t,e):Nf(t,e)}function Sf(t,e){let n=[],r=0;for(let o=0;o<t.layers.length;o+=1){n.push(r);let s=0;for(let i of t.layers[o])s=Math.max(s,i.w);r+=s+e.layerGap}for(let o=0;o<t.layers.length;o+=1)for(let s of t.layers[o])s.x=n[o];for(let o of t.layers){let s=0;for(let i of o)i.y=s,s+=i.h+e.nodeGap}mc(t,e,"y")}function Nf(t,e){let n=[],r=0;for(let o=0;o<t.layers.length;o+=1){n.push(r);let s=0;for(let i of t.layers[o])s=Math.max(s,i.h);r+=s+e.layerGap}for(let o=0;o<t.layers.length;o+=1)for(let s of t.layers[o])s.y=n[o];for(let o of t.layers){let s=0;for(let i of o)i.x=s,s+=i.w+e.nodeGap}mc(t,e,"x")}function mc(t,e,n){let r=s=>n==="y"?s.h:s.w,o=e.nodeGap;for(let s=0;s<2;s+=1){let i=s===0?t.layers.slice(1):t.layers.slice(0,-1).reverse();for(let a of i){let u=new Map;for(let d of a){let l=s===0?d.in:d.out;if(l.length===0)continue;let f=[];for(let m of l){let h=t.nodes.get(s===0?m.fromId:m.toId);if(!h)continue;let g=n==="y"?h.y:h.x;f.push(g+Math.floor(r(h)/2))}if(f.length===0)continue;f.sort((m,h)=>m-h);let p=f[Math.floor(f.length/2)];u.set(d.id,p-Math.floor(r(d)/2))}let c=0;for(let d of a){let l=u.get(d.id),f=n==="y"?d.y:d.x,m=Math.max(l??f,c);n==="y"?d.y=m:d.x=m,c=m+r(d)+o}}}}function Ef(t,e){let n=new Map;for(let c of t.hops){let d=n.get(c.chainId);d?d.push(c):n.set(c.chainId,[c])}for(let c of n.values())c.sort((d,l)=>d.hopIndex-l.hopIndex);let r=e.direction==="LR",o=c=>r?c.x:c.y,s=c=>r?c.w:c.h,i=c=>r?c.y+Math.floor(c.h/2):c.x+Math.floor(c.w/2),a=new Map;for(let c=0;c+1<t.layers.length;c+=1){let d=t.layers[c],l=t.layers[c+1],f=0;for(let R of d)f=Math.max(f,o(R)+s(R));let p=Number.POSITIVE_INFINITY;for(let R of l)p=Math.min(p,o(R));let m=Number.isFinite(p)?p-1:f,h=Math.max(1,m-f+1),g=[];for(let R of d)for(let E of R.out)g.push(E);g.sort((R,E)=>{let G=i(t.nodes.get(R.fromId)),L=i(t.nodes.get(E.fromId));if(G!==L)return G-L;let P=i(t.nodes.get(R.toId)),C=i(t.nodes.get(E.toId));return P-C});let y=[],b=new Map;for(let R of g){let E=i(t.nodes.get(R.fromId)),G=i(t.nodes.get(R.toId)),L=Math.min(E,G),P=Math.max(E,G),C=-1;for(let V=0;V<y.length;V+=1){let ne=y[V],F=!0;for(let A of ne)if(A.lo<=P&&L<=A.hi){F=!1;break}if(F){ne.push({lo:L,hi:P}),C=V;break}}C<0&&(y.push([{lo:L,hi:P}]),C=y.length-1),b.set(R,C)}let v=y.length,T=h>=Math.max(3,v+2),w=T?f+1:f,k=T?m-1:m,x=Math.max(1,k-w+1);for(let R of g){let E=b.get(R),G;if(v<=1)G=w+Math.floor(x/2);else{let L=(x-1)/(v-1);G=w+Math.floor(E*L)}a.set(R,Math.max(f,Math.min(m,G)))}}let u=[];for(let[,c]of n){let d=[];for(let f=0;f<c.length;f+=1){let p=c[f],m=t.nodes.get(p.fromId),h=t.nodes.get(p.toId),g=a.get(p),y=m.isVirtual?o(m):o(m)+s(m),b=h.isVirtual?o(h):o(h)-1,v=i(m),T=i(h);f===0&&Mo(d,r,y,v),v!==T&&(Mo(d,r,g,v),Mo(d,r,g,T)),Mo(d,r,b,T)}let l=c[0];u.push({from:l.chainFrom,to:l.chainTo,points:_f(d)})}return u}function Mo(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function _f(t){let e=[];for(let n of t){let r=e[e.length-1];(!r||r.x!==n.x||r.y!==n.y)&&e.push(n)}return e}function Mf(t){let e=0,n=0;for(let r of t.layers)for(let o of r)e=Math.max(e,o.x+o.w),n=Math.max(n,o.y+o.h);return{width:e,height:n}}var Of=24,Cf=4,Af=1,Lf=3;function hc(t,e){let n=If(e.direction),r=Math.max(3,e.maxLabelWidth??Of),o=e.asciiCharset??"unicode",s=Object.keys(t.nodes).sort(),i=new Set(s),a=t.edges.filter(p=>i.has(p.from)&&i.has(p.to)),u=new Map,c=new Map;for(let p of s){let m=sc(p,r);u.set(p,m),c.set(p,Wn(m)+4)}let d=fc({nodes:s,edges:a,widthCells:p=>c.get(p)??3,heightCells:()=>Lf,layerGap:Cf,nodeGap:Af,direction:n}),l=cc(d,{charset:o,labelOf:p=>u.get(p)??p}),f=e.logger;return f&&f(l),l}function If(t){if(t===void 0||t==="LR")return"LR";if(t==="TD")return"TD";throw new Error(`ascii describe supports direction "LR" or "TD" only; got ${String(t)}`)}function kr(t,e,n,r={}){let o=e in t.nodes,s=n in t.nodes;if(!o)return Oo(e,n,"no-such-from");if(!s)return Oo(e,n,"no-such-to");let i=r.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===n){if(r.findCycle===!0){let c=Pf(t,e,r);if(c!=null)return c}let u=Co(e,t.nodes[e],0,r);return Ao(e,n,[u])}if(i===0)return Oo(e,n,"no-path");let a=gc(t,e,n,i);return a.found?Ao(e,n,yc(t,a.pathOrder,r)):Oo(e,n,a.truncated?"max-depth-exceeded":"no-path")}function gc(t,e,n,r){let o=new Map,s=[{path:n,depth:0}],i=new Set([n]),a=0,u=!1;for(;a<s.length;){let l=s[a++];if(l.path===e)break;if(r!=null&&l.depth>=r){let h=t.nodes[l.path];h?.deps&&h.deps.length>0&&(u=!0);continue}let f=t.nodes[l.path];if(f==null)continue;let p=f.deps??[],m=new Map;for(let h=0;h<p.length;h++){let g=p[h];if(!g)continue;let y=m.get(g);y==null&&(y=[],m.set(g,y)),y.push(h)}for(let[h,g]of m)i.has(h)||(i.add(h),o.set(h,{from:l.path,depIndices:g}),s.push({path:h,depth:l.depth+1}))}if(!o.has(e))return{found:!1,pathOrder:[],truncated:u};let c=[{path:e}],d=e;for(;d!==n;){let l=o.get(d);if(l==null)return{found:!1,pathOrder:[],truncated:!1};c[c.length-1].depIndices=l.depIndices,c.push({path:l.from}),d=l.from}return{found:!0,pathOrder:c,truncated:!1}}function Pf(t,e,n){let r=t.nodes[e];if(r==null)return null;let o=r.deps??[],s=[];for(let a=0;a<o.length;a++)o[a]===e&&s.push(a);if(s.length>0){let a=Co(e,r,0,n);a.dep_index=s[0];let u=Co(e,r,1,n);return Ao(e,e,[a,u])}let i=null;for(let a=0;a<o.length;a++){let u=o[a];if(!u||u===e)continue;let c=gc(t,u,e,n.maxDepth);c.found&&(i==null||c.pathOrder.length<i.pathOrder.length)&&(i=c,i={found:!0,pathOrder:[{path:e,depIndices:[a]},...c.pathOrder],truncated:!1})}return i==null?null:Ao(e,e,yc(t,i.pathOrder,n))}function yc(t,e,n){return e.map((r,o)=>{let s=t.nodes[r.path],i=Co(r.path,s,o,n);return r.depIndices!=null&&r.depIndices.length>0&&(i.dep_index=r.depIndices[0],r.depIndices.length>1&&(i.dep_indices=[...r.depIndices])),i})}function Co(t,e,n,r){let o={path:t,type:e.type,hop:n};e.status!==void 0&&(o.status=e.status),"value"in e&&(o.value=e.value),e.v!=null&&(o.v=e.v);let s=r.annotations?.get(t)??e.annotation;s!=null&&(o.annotation=s);let i=r.lastMutations?.get(t)??e.lastMutation;return i!=null&&(o.lastMutation=i),o}function Ao(t,e,n){return bc(t,e,!0,"ok",n)}function Oo(t,e,n){return bc(t,e,!1,n,[])}function bc(t,e,n,r,o){let s=Df(t,e,n,r,o);return{from:t,to:e,found:n,reason:r,steps:o,text:s,toJSON(){return{from:t,to:e,found:n,reason:r,steps:o}}}}function Df(t,e,n,r,o){if(!n)switch(r){case"no-such-from":return`explainPath: no node named "${t}"`;case"no-such-to":return`explainPath: no node named "${e}"`;case"max-depth-exceeded":return`explainPath: no path from "${t}" to "${e}" within maxDepth`;default:return`explainPath: no path from "${t}" to "${e}"`}let s=[`Causal path: ${t} \u2192 ${e} (${o.length} step(s))`];for(let i of o){let u=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(s.push(u),"value"in i&&s.push(` value: ${Gf(i.value)}`),i.annotation!=null&&s.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let c=i.lastMutation.actor;s.push(` actor: ${c.type}${c.id?`:${c.id}`:""}`)}}return s.join(`
11
- `)}function Gf(t){if(t===void 0)return"<sentinel>";if(t===null)return"null";if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return e.length>80?`${e.slice(0,77)}...`:e}catch{return String(t)}}xe();var Le={object:56,array:64,string:40,number:8,boolean:4,null:0,undefined:0,symbol:40,bigint:16,function:120,map:72,set:72,mapEntry:40,setEntry:24,date:24,regexp:48,error:64,url:80,promise:48,weakmap:40,weakset:40},Lo=Symbol.for("sizeof");function xr(t){let e=new WeakSet,n=new WeakSet,r=[t],o=0;for(;r.length>0;){let s=r.pop();o+=Ff(s,e,n,r)}return o}function Ff(t,e,n,r){if(t==null)return 0;switch(typeof t){case"number":return Le.number;case"boolean":return Le.boolean;case"string":return Le.string+t.length*2;case"bigint":return Le.bigint+$f(t);case"symbol":return Le.symbol;case"function":return e.has(t)?0:(e.add(t),Le.function);case"undefined":return 0}let s=t;if(e.has(s))return 0;e.add(s);let i=s[Lo];if(typeof i=="function")try{let c=i.call(s);if(typeof c=="number"&&Number.isFinite(c))return c}catch{}if(s instanceof Date)return Le.date;if(s instanceof RegExp)return Le.regexp+s.source.length*2;if(s instanceof Error){let c=s.message?s.message.length*2:0,d=s.stack?s.stack.length*2:0;return Le.error+c+d}if(typeof URL<"u"&&s instanceof URL)return Le.url+s.href.length*2;if(typeof Promise<"u"&&s instanceof Promise)return Le.promise;if(s instanceof WeakMap)return Le.weakmap;if(s instanceof WeakSet)return Le.weakset;if(s instanceof Map){let c=Le.map;for(let[d,l]of s)c+=Le.mapEntry,r.push(d),r.push(l);return c}if(s instanceof Set){let c=Le.set;for(let d of s)c+=Le.setEntry,r.push(d);return c}if(Array.isArray(s)){let c=Le.array+s.length*8;for(let d of s)r.push(d);return c}if(s instanceof ArrayBuffer)return n.has(s)?0:(n.add(s),s.byteLength);if(ArrayBuffer.isView(s)){let c=s;return n.has(c.buffer)?48:(n.add(c.buffer),c.buffer.byteLength+48)}let a=Le.object,u=Object.keys(s);for(let c of u){a+=Le.string+c.length*2;try{r.push(s[c])}catch{}}return a}function $f(t){let e=t<0n?-t:t;if(e===0n)return 0;let n=e.toString(2).length;return Math.ceil(n/32)*8}function an(t,e){let n=e?.topN??10,r=t.describe({detail:"standard"}),o=[],s=t._collectObserveTargets;typeof s=="function"&&s.call(t,"",o);let i=new Map;for(let[f,p]of o)i.set(f,p);let a=[];for(let[f,p]of Object.entries(r.nodes)){let m=i.get(f),h=m instanceof Ee?m:null,g=h?xr(h.cache):0,y=h?h._sinkCount:0,b=p.deps?.length??0,v=p.type==="effect"&&y===0,T=y===0?p.type==="effect"?"orphan-effect":p.type==="derived"?"idle-derived":p.type==="producer"?"idle-producer":null:null;a.push({path:f,type:p.type,status:p.status??"unknown",valueSizeBytes:g,subscriberCount:y,depCount:b,isOrphanEffect:v,orphanKind:T})}let u=a.reduce((f,p)=>f+p.valueSizeBytes,0),c=(f,p)=>[...a].sort(p??((m,h)=>h[f]-m[f])).slice(0,n),d=a.filter(f=>f.orphanKind!=null),l=a.filter(f=>f.isOrphanEffect);return{nodeCount:a.length,edgeCount:r.edges.length,subgraphCount:r.subgraphs.length,nodes:a,totalValueSizeBytes:u,hotspots:{byValueSize:c("valueSizeBytes"),bySubscriberCount:c("subscriberCount"),byDepCount:c("depCount")},orphans:d,orphanEffects:l}}var Ce="::",je="__meta__",it=1;function vc(t,e){let n=Math.max(16,t.size*4),r=0;for(;t.size>0;){if(r++>=n){console.error(`[Graph "${e}".destroy] disposer drain exceeded cap (${n}); ${t.size} disposer(s) discarded`),t.clear();return}let o=t.values().next();if(o.done)return;let s=o.value;t.delete(s);try{s()}catch(i){console.error(`[Graph "${e}".destroy] disposer threw:`,i)}}}function Bf(t){let e=[];for(let n of Object.keys(t).sort()){let r=t[n].v;r!=null&&e.push(`${n} ${r.id} ${r.version}`)}return e.join(`
12
- `)}function Tc(t){if(t.version!==it)throw new Error(`unsupported snapshot version ${String(t.version)} (expected ${it})`);for(let e of["name","nodes","edges","subgraphs"])if(!(e in t))throw new Error(`snapshot missing required key "${e}"`);if(typeof t.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof t.nodes!="object"||t.nodes===null||Array.isArray(t.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(t.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(t.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function jf(t,e){let n=new WeakMap,r=(o,s)=>{if(Object.is(o,s))return!0;if(o==null||s==null||typeof o!="object"||typeof s!="object")return!1;let i=n.get(o);if(i==null&&(i=new WeakSet,n.set(o,i)),i.has(s))return!0;i.add(s);let a=o.constructor,u=s.constructor;if(a!==u)return!1;if(o instanceof Date)return o.getTime()===s.getTime();if(o instanceof RegExp)return o.source===s.source&&o.flags===s.flags;if(Array.isArray(o)){let f=s;if(o.length!==f.length)return!1;for(let p=0;p<o.length;p++)if(!r(o[p],f[p]))return!1;return!0}if(o instanceof Map){let f=s;if(o.size!==f.size)return!1;for(let[p,m]of o)if(!f.has(p)||!r(m,f.get(p)))return!1;return!0}if(o instanceof Set){let f=s;if(o.size!==f.size)return!1;for(let p of o){let m=!1;for(let h of f)if(r(p,h)){m=!0;break}if(!m)return!1}return!0}if(ArrayBuffer.isView(o)){let f=o,p=s;if(f.length!==p.length)return!1;for(let m=0;m<f.length;m++)if(f[m]!==p[m])return!1;return!0}let c=Object.keys(o),d=Object.keys(s);if(c.length!==d.length)return!1;let l=new Set(d);for(let f of c)if(!l.has(f)||!r(o[f],s[f]))return!1;return!0};return r(t,e)}function Mi(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(Mi);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=Mi(e[o]);return r}function Vf(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Kf(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Hf(t){return t==="TD"?"down":t==="BT"?"up":t==="RL"?"left":"right"}function kc(t){let e=new Set,n=[];function r(o,s){let i=`${o}\0${s}`;e.has(i)||(e.add(i),n.push([o,s]))}for(let[o,s]of Object.entries(t.nodes)){let i=s.deps;if(i)for(let a of i)r(a,o)}for(let o of t.edges)r(o.from,o.to);return n}function xc(t){if(t===void 0)return"LR";if(t==="TD"||t==="LR"||t==="BT"||t==="RL")return t;throw new Error(`invalid diagram direction ${String(t)}; expected one of: TD, LR, BT, RL`)}function Wf(t,e){let n=e.includeEdges??!0,r=e.includeSubgraphs??!0,{expand:o,...s}=t,i={...s,edges:n?t.edges:[],subgraphs:r?t.subgraphs:[]},a=JSON.stringify(Mi(i),null,e.indent??2);return e.logger?.(a),a}function qf(t,e){let n=e.includeEdges??!0,r=e.includeSubgraphs??!0,o=[];o.push(`Graph ${t.name}`),o.push("Nodes:");for(let i of Object.keys(t.nodes).sort()){let a=t.nodes[i];o.push(`- ${i} (${a.type}/${a.status}): ${Po(a.value)}`)}if(n){o.push("Edges:");for(let i of t.edges)o.push(`- ${i.from} -> ${i.to}`)}if(r){o.push("Subgraphs:");for(let i of t.subgraphs)o.push(`- ${i}`)}let s=o.join(`
13
- `);return e.logger?.(s),s}function Rc(t,e){let n=xc(e.direction),r=Object.keys(t.nodes).sort(),o=new Map;for(let i=0;i<r.length;i+=1)o.set(r[i],`n${i}`);let s=[`flowchart ${n}`];for(let i of r){let a=o.get(i);s.push(` ${a}["${Vf(i)}"]`)}for(let[i,a]of kc(t)){let u=o.get(i),c=o.get(a);!u||!c||s.push(` ${u} --> ${c}`)}return s.join(`
14
- `)}function Uf(t,e){let n=Rc(t,e);return Do(n)}function Do(t,e){let n=e?.theme??"default",r=e?.autoSync??!0,s=JSON.stringify({code:t,mermaid:{theme:n},autoSync:r}),i=new TextEncoder().encode(s),a="";for(let c=0;c<i.length;c++)a+=String.fromCharCode(i[c]);return`https://mermaid.live/edit#base64:${globalThis.btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`}function zf(t,e){let n=xc(e.direction),r=Object.keys(t.nodes).sort(),o=new Map;for(let i=0;i<r.length;i+=1)o.set(r[i],`n${i}`);let s=[`direction: ${Hf(n)}`];for(let i of r){let a=o.get(i);s.push(`${a}: "${Kf(i)}"`)}for(let[i,a]of kc(t)){let u=o.get(i),c=o.get(a);!u||!c||s.push(`${u} -> ${c}`)}return s.join(`
15
- `)}function Jf(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Io(t){let e="^";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="*"){e+=".*";continue}if(r==="?"){e+=".";continue}if(r==="["){let o=t.indexOf("]",n+1);if(o<=n+1){e+="\\[";continue}let s=t.slice(n+1,o);s.startsWith("!")&&(s=`^${s.slice(1)}`),s=s.replace(/\\/g,"\\\\"),e+=`[${s}]`,n=o;continue}e+=Jf(r)}return e+="$",new RegExp(e)}var Yf={data:"\x1B[32m",dirty:"\x1B[33m",resolved:"\x1B[36m",invalidate:"\x1B[93m",pause:"\x1B[90m",resume:"\x1B[96m",complete:"\x1B[34m",error:"\x1B[31m",teardown:"\x1B[91m",derived:"\x1B[35m",path:"\x1B[90m",reset:"\x1B[0m"},Qf={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function Po(t){if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||t==null)return String(t);try{return JSON.stringify(t)}catch{return"[unserializable]"}}function Xf(t){return t==="none"?Qf:t==="ansi"||t==null?Yf:{data:t.data??"",dirty:t.dirty??"",resolved:t.resolved??"",invalidate:t.invalidate??"",pause:t.pause??"",resume:t.resume??"",complete:t.complete??"",error:t.error??"",teardown:t.teardown??"",derived:t.derived??"",path:t.path??"",reset:t.reset??""}}function wc(t){if(t==null)return{};let e=t.detail;return e==="full"?{...t,structured:t.structured??!0,timeline:t.timeline??!0,causal:t.causal??!0,derived:t.derived??!0}:e==="minimal"?{...t,structured:t.structured??!0}:t.format==="stage-log"?{...t,structured:t.structured??!0,timeline:t.timeline??!0}:t}function Zf(t,e,n){for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);if(o<32||o===127)throw new Error(`Graph "${e}": ${n} "${t}" must not contain control character (U+${o.toString(16).padStart(4,"0").toUpperCase()} at index ${r})`)}}function _i(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(Ce))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${Ce}' (path separator)`);if(t===je)throw new Error(`Graph "${e}": ${n} name "${je}" is reserved for meta companion paths`);Zf(t,e,n)}function em(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(Ce);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function tm(t,e){let n=!1;for(let o of t)if(!e.isMetaPassthrough(o[0])){n=!0;break}return n?t.filter(o=>e.isMetaPassthrough(o[0])):t}function Sc(t){for(let e of t._mounts.values())Sc(e);for(let e of t._nodes.values())try{e.down([[de]],{internal:!0})}catch{}}var q=class t{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_topology;_topologyEmitters=new Set;constructor(e,n){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(Ce))throw new Error(`Graph name must not contain '${Ce}' (got "${e}")`);if(e===je)throw new Error(`Graph name "${je}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??Ae,this._traceRing=new sn(n?.traceCapacity??1e3),n?.versioning!=null&&this.setVersioning(n.versioning)}ancestors(e=!0){let n=[],r=e?this:this._parent;for(;r!=null;)n.push(r),r=r._parent;return n}get topology(){return this._topology==null&&(this._topology=W(e=>{let n=r=>{e.emit(r)};return this._topologyEmitters.add(n),()=>{this._topologyEmitters.delete(n)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let n of this._topologyEmitters)n(e)}add(e,n){let r=e.name,o=n?.name??r;if(o==null||o==="")throw new Error(`Graph "${this.name}": graph.add requires a non-empty name \u2014 pass via opts.name or set it on the node (e.g. state(0, { name: "x" }))`);let s=o,i=n?.annotation;if(_i(s,this.name,"add"),this._mounts.has(s))throw new Error(`Graph "${this.name}": name "${s}" is already a mount point`);if(this._nodes.has(s))throw new Error(`Graph "${this.name}": node "${s}" already exists`);let a=this._nodeToName.get(e);if(a!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${a}"`);return this._nodes.set(s,e),this._nodeToName.set(e,s),this._emitTopology({kind:"added",name:s,nodeKind:"node"}),i!=null&&(this._annotations.set(s,i),this.config.inspectorEnabled&&this._traceRing.push({path:s,annotation:i,timestamp_ns:$()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof Ee&&n._applyVersioning(e)}remove(e){_i(e,this.name,"remove");let n=this._mounts.get(e);if(n){let s={kind:"mount",nodes:[],mounts:[]},i=[];n._collectObserveTargets("",i);for(let[a,u]of i)a.includes(`${Ce}${je}${Ce}`)||s.nodes.push(a);return s.nodes.sort(),s.mounts.push(e),s.mounts.push(...n._collectSubgraphs(`${e}${Ce}`)),this._mounts.delete(e),n._parent=void 0,Sc(n),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:s}),s}let r=this._nodes.get(e);if(!r)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(r),r.down([[de]],{internal:!0});let o={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:o}),o}removeAll(e){let n=typeof e=="function"?e:(()=>{let s=Io(e);return i=>s.test(i)})(),r={kind:"mount",nodes:[],mounts:[]},o=[...this._nodes.keys(),...this._mounts.keys()].filter(s=>n(s));for(let s of o){let i=this.remove(s);r.nodes.push(...i.nodes),r.mounts.push(...i.mounts)}return r.nodes.sort(),r.mounts.sort(),r}[Symbol.iterator](){let e=[...this._nodes.keys()].sort(),n=this._nodes,r=0;return{[Symbol.iterator](){return this},next(){if(r>=e.length)return{value:void 0,done:!0};let o=e[r++];return{value:[o,n.get(o)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(Ce))return this.resolve(e);let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return n}get(e){return this.node(e).cache}set(e,n,r){let o=r?.internal===!0;this.node(e).down([[S,n]],{actor:r?.actor,internal:o,delivery:"write"})}setAll(e,n){let r=Symbol.iterator in e?e:Object.entries(e);te(()=>{for(let[o,s]of r)this.set(o,s,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[He]],{actor:n?.actor,internal:r,delivery:"write"})}error(e,n,r){let o=r?.internal===!0;this.node(e).down([[M,n]],{actor:r?.actor,internal:o,delivery:"write"})}complete(e,n){let r=n?.internal===!0;this.node(e).down([[_]],{actor:n?.actor,internal:r,delivery:"write"})}edges(e){let n=e?.recursive===!0,r=new Map;if(!n){for(let[u,c]of this._nodes)r.set(c,u);let a=[];for(let[u,c]of this._nodes)if(c instanceof Ee)for(let d of c._deps){let l=r.get(d.node);l!=null&&a.push([l,u])}return a.sort((u,c)=>u[0]<c[0]?-1:u[0]>c[0]?1:u[1]<c[1]?-1:u[1]>c[1]?1:0),a}let o=[];this._collectObserveTargets("",o);let s=new Map;for(let[a,u]of o)s.set(u,a);let i=[];for(let[a,u]of o)if(u instanceof Ee)for(let c of u._deps){let d=s.get(c.node);d!=null&&i.push([d,a])}return i.sort((a,u)=>a[0]<u[0]?-1:a[0]>u[0]?1:a[1]<u[1]?-1:a[1]>u[1]?1:0),i}mount(e,n){if(_i(e,this.name,"mount"),this._nodes.has(e))throw new Error(`Graph "${this.name}": cannot mount at "${e}" \u2014 node with that name exists`);if(this._mounts.has(e))throw new Error(`Graph "${this.name}": mount "${e}" already exists`);if(n===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(n._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${n._parent.name}"`);for(let r=this;r!=null;r=r._parent)if(r===n)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,n),n._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),n}resolve(e){let n=em(e,this.name);return this._resolveFromSegments(n)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let n=e;if(n[0]===this.name&&(n=n.slice(1),n.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let r=n[0],o=n.slice(1);if(o.length===0){let a=this._nodes.get(r);if(a)return a;throw this._mounts.has(r)?new Error(`Graph "${this.name}": path ends at subgraph "${r}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${r}"`)}let s=this._nodes.get(r);if(s&&o.length>0&&o[0]===je)return this._resolveMetaChainFromNode(s,o,n.join(Ce));let i=this._mounts.get(r);if(!i)throw this._nodes.has(r)?new Error(`Graph "${this.name}": "${r}" is a node; trailing path "${o.join(Ce)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(o.join(Ce))}_resolveMetaChainFromNode(e,n,r){let o=e,s=0,i=[...n];for(;s<i.length;){if(i[s]!==je)throw new Error(`Graph "${this.name}": expected ${je} segment in meta path "${r}"`);if(s+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${je} in "${r}"`);let a=i[s+1],u=o.meta[a];if(!u)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${r}"`);o=u,s+=2}return o}signal(e,n){if(n?.internal!==!0){for(let o of e)if(this.config.messageTier(o[0])===3)throw new Error(`Graph "${this.name}": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). For per-node value writes, use Graph.set or graph.node(name).down(...).`)}let r=[];if(this._signalDeliver(e,n??{},new Set,r),r.length>0)throw r[0]}_signalDeliver(e,n,r,o){for(let u of this._mounts.values())u._signalDeliver(e,n,r,o);let i=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},a=tm(e,this.config);for(let u of[...this._nodes.keys()].sort()){let c=this._nodes.get(u);if(!r.has(c)){r.add(c);try{c.down(e,i)}catch(d){if(d instanceof Je)throw d;o.push(d)}a.length!==0&&this._signalMetaSubtree(c,a,r,i,o)}}}_signalMetaSubtree(e,n,r,o,s){for(let i of Object.keys(e.meta).sort()){let a=e.meta[i];if(!r.has(a)){r.add(a);try{a.down(n,o)}catch(u){if(u instanceof Je)throw u;s.push(u)}this._signalMetaSubtree(a,n,r,o,s)}}}describe(e){if(e?.reactive===!0)return this._describeReactive(e);let n=e?.actor,r=e?.filter,o=wt(e?.detail,e?.fields),s=e?.format==="spec",i=s?wt("minimal"):o,a=[];this._collectObserveTargets("",a);let u=new Map;for(let[k,x]of a)u.set(x,k);let c=[];{let k=a.map(([,E])=>E),x=new Set(u.values()),R=0;for(;k.length>0;){let E=k.shift();if(E instanceof Ee)for(let G of E._deps){let L=G.node;if(u.has(L))continue;let P=L.name??"",C=P;if(!C||x.has(C))if(P){let V=2;for(;x.has(`${P}#${V}`);)V++;C=`${P}#${V}`}else for(C=`__internal__/${R++}`;x.has(C);)C=`__internal__/${R++}`;u.set(L,C),x.add(C),c.push([C,L]),k.push(L)}}}let d=[...a,...c],l={};for(let[k,x]of d){if(n!=null&&!x.allowsObserve(n))continue;let R=wr(x,i),E=x instanceof Ee?x._deps.map(C=>u.get(C.node)??C.node.name??""):[],{name:G,...L}=R,P={...L,deps:E};if(!s){let C=this._annotations.get(k);C!=null&&(P.annotation=C)}if(r!=null)if(typeof r=="function"){let C=r;if(!(C.length>=2?C(k,P):C(P)))continue}else{let C=!0;for(let[V,ne]of Object.entries(r)){let F=V==="deps_includes"?"depsIncludes":V==="meta_has"?"metaHas":V;if(F==="depsIncludes"){if(!P.deps.includes(String(ne))){C=!1;break}continue}if(F==="metaHas"){if(!Object.hasOwn(P.meta??{},String(ne))){C=!1;break}continue}if(P[F]!==ne){C=!1;break}}if(!C)continue}l[k]=P}let f=new Set(Object.keys(l)),p=[];for(let[k,x]of d)if(x instanceof Ee)for(let R of x._deps){let E=u.get(R.node);E!=null&&p.push([E,k])}p.sort((k,x)=>k[0]<x[0]?-1:k[0]>x[0]?1:k[1]<x[1]?-1:k[1]>x[1]?1:0);let m=p.map(([k,x])=>({from:k,to:x}));(n!=null||r!=null)&&(m=m.filter(k=>f.has(k.from)&&f.has(k.to)));let h=this._collectSubgraphs(""),g=n!=null||r!=null?h.filter(k=>{let x=`${k}${Ce}`;return[...f].some(R=>R===k||R.startsWith(x))}):h,y=this,b=e,v={name:this.name,nodes:l,edges:m,subgraphs:g,expand(k){let x={...b,format:void 0};return Array.isArray(k)?(x.fields=k,x.detail=void 0):(x.detail=k,x.fields=void 0),y.describe(x)}},T=e??{},w=T.format;return w==="json"?Wf(v,T):w==="pretty"?qf(v,T):w==="mermaid"?Rc(v,T):w==="mermaid-url"?Uf(v,T):w==="d2"?zf(v,T):w==="ascii"?hc(v,T):v}_collectSubgraphs(e){let n=[];for(let r of[...this._mounts.keys()].sort()){let o=e===""?r:`${e}${r}`;n.push(o),n.push(...this._mounts.get(r)._collectSubgraphs(`${o}${Ce}`))}return n}resourceProfile(e){return an(this,e)}reachable(e,n,r={}){return r.withDetail===!0?un(this.describe(),e,n,{...r,withDetail:!0}):un(this.describe(),e,n,r)}explain(e,n,r){return r?.reactive===!0?this._explainReactive(e,n,r):this._explainStatic(e,n,r)}_explainStatic(e,n,r){let o=this.describe({detail:"full"}),s=new Map(this._annotations),i=new Map;for(let[a,u]of Object.entries(o.nodes))u.lastMutation!=null&&i.set(a,u.lastMutation);return kr(o,e,n,{...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{},annotations:s,lastMutations:i})}_describeReactive(e){let n={...e,reactive:!1},r=e.reactiveName??"describe",o=0,s=N(o,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,u=!1,c=()=>{a||u||(a=!0,lr(()=>{a=!1,!u&&(o+=1,s.emit(o))}))},d=i.onEvent(g=>{let y=g.type;y!=="data"&&y!=="error"&&y!=="complete"&&y!=="teardown"||c()}),l=[],f=new WeakSet,p=g=>{if(f.has(g)||u)return;f.add(g);let y=g.topology.subscribe(b=>{for(let v of b){if(v[0]!==S)continue;let T=v[1];if(c(),T.kind==="added"&&T.nodeKind==="mount"){let w=g._mounts.get(T.name);w!=null&&p(w)}}});l.push(y);for(let b of g._mounts.keys()){let v=g._mounts.get(b);v!=null&&p(v)}};p(this);let m;try{m=O([s],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(g,y)=>g===y})}catch(g){d();for(let y of l)y();throw i.dispose(),g}let h=se(m);return{node:m,dispose(){u=!0,d();for(let g of l)g();l.length=0,i.dispose(),h()}}}_explainReactive(e,n,r){let o=0,s=N(o,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,u=!1,c=i.onEvent(p=>{let m=p.type;m!=="data"&&m!=="error"&&m!=="complete"&&m!=="teardown"||a||u||(a=!0,lr(()=>{a=!1,!u&&(o+=1,s.emit(o))}))}),d={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},l;try{l=O([s],()=>this._explainStatic(e,n,d),{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:e,to:n},equals:(p,m)=>p.found===m.found&&p.reason===m.reason&&p.steps.length===m.steps.length&&nm(p.steps,m.steps)})}catch(p){throw c(),i.dispose(),p}let f=se(l);return{node:l,dispose(){u=!0,c(),i.dispose(),f()}}}_pathsMatching(e){let n=Io(e),r=[];return this._collectObserveTargets("",r),r.map(([o])=>o).filter(o=>n.test(o))}_collectObserveTargets(e,n){for(let r of[...this._mounts.keys()].sort()){let o=e===""?r:`${e}${Ce}${r}`;this._mounts.get(r)._collectObserveTargets(o,n)}for(let r of[...this._nodes.keys()].sort()){let o=this._nodes.get(r),s=e===""?r:`${e}${Ce}${r}`;n.push([s,o]),this._appendMetaObserveTargets(s,o,n)}}_appendMetaObserveTargets(e,n,r){for(let o of Object.keys(n.meta).sort()){let s=n.meta[o],i=`${e}${Ce}${je}${Ce}${o}`;r.push([i,s]),this._appendMetaObserveTargets(i,s,r)}}observe(e,n){let r=typeof e=="string",s=wc(r?n:e),i=s.structured===!0||s.timeline===!0||s.causal===!0||s.derived===!0||s.detail==="minimal"||s.detail==="full"||s.format!=null,a=s.actor;if(r){let d=e,l=this.resolve(d);if(a!=null&&!l.allowsObserve(a))throw new Je({actor:a,action:"observe",nodeName:d});return i?this._buildStructuredObserver([[d,l]],s,"one"):{subscribe(f){return l.subscribe(f)},up(f){try{l.up?.(f)}catch(p){if(p instanceof Je)return;throw p}}}}let u=[];this._collectObserveTargets("",u),u.sort((d,l)=>d[0]<l[0]?-1:d[0]>l[0]?1:0);let c=a==null?u:u.filter(([,d])=>d.allowsObserve(a));return i?this._buildStructuredObserver(c,s,"all"):{subscribe:d=>{let l=c.map(([f,p])=>p.subscribe(m=>{d(f,m)}));return()=>{for(let f of l)f()}},up:(d,l)=>{try{this.resolve(d).up?.(l)}catch(f){if(f instanceof Je)return;throw f}}}}_buildStructuredObserver(e,n,r){let o=r==="one"?e[0]?.[0]:void 0,s=i=>{if(r==="one"&&o!=null){let d=this.resolve(o);return this._buildStructuredObserver([[o,d]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((d,l)=>d[0]<l[0]?-1:d[0]>l[0]?1:0);let u=i.actor,c=u==null?a:a.filter(([,d])=>d.allowsObserve(u));return this._buildStructuredObserver(c,i,"all")};return this._createObserveResult(e,n,s)}_createObserveResult(e,n,r){let o=n.timeline===!0,s=n.causal===!0,i=n.derived===!0,a=n.detail==="minimal",u=this.config.inspectorEnabled,c=(s||i)&&u,d=n.maxEvents,l=d!=null&&d>0?new sn(d):null,f=[],p=new Set,m={},h=new Set,g=0,y=0,b=0,v=0,T=0,w=0,k=!1,x=!1,R=0,E=new Map,G=new Map,L=new Map,P=j=>{l?l.push(j):f.push(j);for(let Y of p)Y(j)},C=()=>o?{timestamp_ns:$(),in_batch:zt(),batch_id:R}:{},V=(j,Y)=>{if(!(!c||!(j instanceof Ee)))return j._setInspectorHook(J=>{if(J.kind==="dep_message")E.set(j,J.depIndex);else if(J.kind==="run"){let z=J.batchData.map((H,le)=>H!=null&&H.length>0?H.at(-1):J.prevData[le]);G.set(j,z);let X=J.batchData.map(H=>H!=null?[...H]:void 0);L.set(j,X),i&&P({type:"derived",path:Y,dep_values:z,dep_batches:X,...C()})}})},ne=j=>{let Y=E.get(j),J=G.get(j);if(!s||J==null)return{};let X=(Y!=null&&Y>=0&&j instanceof Ee?j._deps[Y]:void 0)?.node,H=X?.v,le=L.get(j);return{trigger_dep_index:Y,trigger_dep_name:X?.name,...H!=null?{trigger_version:{id:H.id,version:H.version}}:{},dep_values:[...J],...le!=null?{dep_batches:le}:{}}},F=[],A=[];for(let[j,Y]of e){let J=V(Y,j);J&&F.push(J),A.push(Y.subscribe(z=>{R++;for(let X of z){let H=X[0],le=C();if(H===S){m[j]=X[1];let ve=Y instanceof Ee?Y.lastMutation?.actor??lt:lt;P({type:"data",path:j,data:X[1],actor:ve,...le,...ne(Y)})}else if(a)H===ee?g++:H===B?y++:H===He?b++:H===Ie?v++:H===Ge?T++:H===de?w++:H===_&&!h.has(j)?k=!0:H===M&&(x=!0,h.add(j));else if(H===ee)g++,P({type:"dirty",path:j,...le});else if(H===B)y++,P({type:"resolved",path:j,...le,...ne(Y)});else if(H===He)b++,P({type:"invalidate",path:j,...le});else if(H===Ie)v++,P({type:"pause",path:j,lockId:X[1],...le});else if(H===Ge)T++,P({type:"resume",path:j,lockId:X[1],...le});else if(H===_)h.has(j)||(k=!0),P({type:"complete",path:j,...le});else if(H===M){x=!0,h.add(j);let ve=Y instanceof Ee?Y.lastMutation?.actor??lt:lt;P({type:"error",path:j,data:X[1],actor:ve,...le})}else H===de&&(w++,P({type:"teardown",path:j,...le}))}}))}let D=!1,I=()=>{if(!D){D=!0;for(let j of A)j();for(let j of F)j();for(let j of U)j({value:void 0,done:!0});U.length=0}},Q=[],U=[];p.add(j=>{let Y=U.shift();Y?Y({value:j,done:!1}):Q.push(j)});let ae={get values(){return m},get dirtyCount(){return g},get resolvedCount(){return y},get invalidateCount(){return b},get pauseCount(){return v},get resumeCount(){return T},get teardownCount(){return w},get events(){return l?l.toArray():[...f]},get anyCompletedCleanly(){return k},get anyErrored(){return x},get completedWithoutErrors(){return k&&!x},onEvent(j){return p.add(j),()=>p.delete(j)},dispose:I,expand(j){I();let Y={...n};return typeof j=="string"?Y.detail=j:Object.assign(Y,j),r(wc(Y))},[Symbol.asyncIterator](){return{next(){return Q.length>0?Promise.resolve({value:Q.shift(),done:!1}):D?Promise.resolve({value:void 0,done:!0}):new Promise(j=>U.push(j))},return(){return I(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(ae,n),ae}_attachFormatLogger(e,n){let r=n.format;if(r==null)return;let o=n.logger??(m=>console.log(m)),s=n.includeTypes?new Set(n.includeTypes):null,i=n.excludeTypes?new Set(n.excludeTypes):null,a=s==null&&i==null?()=>!0:m=>(s==null||s.has(m))&&(i==null||!i.has(m)),u=Xf(n.theme),c=r==="stage-log"?$():0,d=m=>m==null?"":n.stageLabels?.[m]??m,l=(m,h)=>m.length>h?`${m.slice(0,h-1)}\u2026`:m,f=m=>m.type==="data"||m.type==="error"?l(Po(m.data),120):"",p=m=>{if(r==="stage-log"){let x=($()-c)/1e9,R=d(m.path).padEnd(9);if(m.type==="data"){let E=f(m);return`[${x.toFixed(3)}s] ${R} \u2190${E?` ${E}`:""}`}if(m.type==="error"){let E=f(m);return`[${x.toFixed(3)}s] ${R} \u2717${E?` ${E}`:""}`}return m.type==="complete"?`[${x.toFixed(3)}s] ${R} \u25A0 complete`:`[${x.toFixed(3)}s] ${R} ${m.type}`}if(r==="json")try{return JSON.stringify(m)}catch{return JSON.stringify({type:m.type,path:m.path,data:"[unserializable]"})}let h=u[m.type]??"",g=m.path?`${u.path}${m.path}${u.reset} `:"",y=m.type==="data"||m.type==="error",b=m.type==="pause"||m.type==="resume",v=y?` ${Po(m.data)}`:b?` ${Po(m.lockId)}`:"",T=m.type==="data"||m.type==="resolved"||m.type==="derived"?m:void 0,w=T?.trigger_dep_name!=null?` <- ${T.trigger_dep_name}`:T?.trigger_dep_index!=null?` <- #${T.trigger_dep_index}`:"",k=m.in_batch?" [batch]":"";return`${g}${h}${m.type.toUpperCase()}${u.reset}${v}${w}${k}`};e.onEvent(m=>{a(m.type)&&o(p(m),m)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){vc(this._disposers,this.name),this.signal([[de]],{internal:!0}),vc(this._storageDisposers,this.name);for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0}_destroyClearOnly(){for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0}snapshot(e){let{expand:n,...r}=this.describe({detail:"full"}),o={};for(let a of Object.keys(r.nodes).sort()){let{lastMutation:u,guard:c,...d}=r.nodes[a];o[a]=d}let s=[...r.subgraphs].sort(),i={...r,version:1,nodes:o,subgraphs:s};if(e?.format==null)return i;if(e.format==="json-string")return JSON.stringify(i);if(e.format==="bytes"){if(e.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let a=this.config.lookupCodec(e.codec);if(a==null)throw new Error(`snapshot: codec "${e.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return sr(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??Ae,{codec:o,codecVersion:s,payload:i}=ir(e,r);return o.decode(i,s)}restore(e,n){if(Tc(e),e.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${e.name}" does not match this graph`);let r=n?.only==null?null:(Array.isArray(n.only)?n.only:[n.only]).map(s=>Io(s)),o=n?.includeProducers===!0;for(let s of Object.keys(e.nodes).sort()){if(r!==null&&!r.some(a=>a.test(s)))continue;let i=e.nodes[s];if(i!==void 0){if(!("value"in i)||i.value===void 0){"value"in i&&i.value===void 0&&n?.onError?.(s,new Error(`restore: slice.value is undefined for "${s}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(i.type==="derived"||i.type==="effect")&&!(i.type==="producer"&&!o)){if(i.v!=null){let u=this.tryResolve(s)?.v;if(u!=null&&u.id===i.v.id&&u.version===i.v.version)continue}try{this.set(s,i.value)}catch(a){n?.onError?.(s,a)}}}}}static fromSnapshot(e,n){Tc(e);let r=typeof n=="function"?n:n?.build,o=typeof n=="function"?void 0:n?.factories,s=new t(e.name);if(r)return r(s),s.restore(e),s;for(let p of[...e.subgraphs].sort((m,h)=>{let g=m.split(Ce).length,y=h.split(Ce).length;return g!==y?g-y:m<h?-1:m>h?1:0})){let m=p.split(Ce),h=s;for(let g of m)h._mounts.has(g)||h.mount(g,new t(g)),h=h._mounts.get(g)}let i=o?Object.entries(o).map(([p,m])=>({re:Io(p),factory:m})):[],a=p=>{for(let m of i)if(m.re.test(p))return m.factory},u=p=>{let m=p.split(Ce),h=m.pop();if(h==null||h.length===0)throw new Error(`invalid snapshot path "${p}"`);let g=s;for(let y of m){let b=g._mounts.get(y);if(!b)throw new Error(`unknown mount "${y}" in path "${p}"`);g=b}return[g,h]},c=Object.entries(e.nodes).filter(([p])=>!p.includes(`${Ce}${je}${Ce}`)).sort((p,m)=>p[0]<m[0]?-1:p[0]>m[0]?1:0),d=new Map(c),l=new Map,f=!0;for(;d.size>0&&f;){f=!1;for(let[p,m]of[...d.entries()]){let h=m?.deps??[];if(!h.every(w=>l.has(w)))continue;let[g,y]=u(p),b={...m?.meta??{}},v=a(p),T;if(m?.type==="state")T=N(m.value,{meta:b});else{if(v==null)continue;T=v(y,{path:p,type:m.type,value:m.value,meta:b,deps:h,resolvedDeps:h.map(w=>l.get(w))})}g.add(T,{name:y}),l.set(p,T),d.delete(p),f=!0}}if(d.size>0){let p=[...d.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${p}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return s.restore(e),s}toJSON(){return this.snapshot()}attachStorage(e,n={}){let r=e.map(c=>({tier:c,debounceMs:Math.max(0,c.debounceMs??0),compactEvery:Math.max(1,c.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));n.autoRestore===!0&&this._cascadeRestore(e,n.onError);let o=(c,d)=>{if(c.disposed)return;let l=Bf(d.nodes);if(c.lastSnapshot!=null&&l!==""&&l===c.lastFingerprint)return;let f=c.seq+1,p=pe(),g=c.lastSnapshot==null||f%c.compactEvery===0?{mode:"full",snapshot:d,seq:f,timestamp_ns:p,format_version:it}:{mode:"diff",diff:Go(c.lastSnapshot,d),seq:f,timestamp_ns:p,format_version:it};if(c.tier.filter&&!c.tier.filter(this.name,g))return;let y;try{y=c.tier.save(this.name,g)}catch(b){n.onError?.(b,c.tier);return}if(y&&typeof y.then=="function"){let T=(c.savePending??Promise.resolve()).then(()=>y,()=>y).then(()=>{c.disposed||(c.seq=f,c.lastSnapshot=d,c.lastFingerprint=l)},w=>{n.onError?.(w,c.tier)});c.savePending=T.finally(()=>{c.savePending===T&&(c.savePending=void 0)})}else c.seq=f,c.lastSnapshot=d,c.lastFingerprint=l},s=(c,d)=>{try{o(c,d)}catch(l){n.onError?.(l,c.tier)}},i=(c,d)=>{if(!d.some(m=>{let h=this.config.messageTier(m[0]);return h>=3&&h<5}))return;if(n.filter){let m=this.tryResolve(c);if(m==null)return;let h=wr(m,wt("standard"));if(!n.filter(c,h))return}let f,p=()=>(f==null&&(f=this.snapshot()),f);for(let m of r)m.disposed||(m.debounceMs===0?s(m,p()):(m.timer==null&&(m.timer=new _e),m.timer.start(m.debounceMs,()=>{m.disposed||s(m,this.snapshot())})))},a;if(n.paths!=null){let d=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(l=>{let f=this.tryResolve(l);return f==null?()=>{}:f.subscribe(p=>i(l,p))});a=()=>{for(let l of d)l()}}else a=this.observe().subscribe((c,d)=>i(c,d));let u=()=>{a();for(let c of r)c.disposed=!0,c.timer?.cancel();this._storageDisposers.delete(u)};return this._storageDisposers.add(u),{dispose:u}}async _cascadeRestore(e,n){for(let r of e){let o;try{o=await r.load(this.name)}catch(i){n?.(i,r);continue}if(o==null||typeof o!="object"||Array.isArray(o))continue;let s=o;try{if(s.mode==="full"&&s.snapshot!=null)return this.restore(s.snapshot),!0;if(s.version===it&&s.nodes!=null)return this.restore(s),!0}catch(i){n?.(i,r)}}return!1}static async fromStorage(e,n,r){for(let o of n){let s;try{s=await o.load(e)}catch(u){r?.onError?.(u,o);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let i=s,a=i.mode==="full"&&i.snapshot!=null?i.snapshot:i.version===it&&i.nodes!=null?i:void 0;if(a!=null)try{return t.fromSnapshot(a,r)}catch(u){r?.onError?.(u,o)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${n.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,n,r){if(e!=null&&n!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,n),this.config.inspectorEnabled){let o={path:e,annotation:n,timestamp_ns:$(),...r?.actor!=null?{actor:r.actor}:{}};this._traceRing.push(o)}return}return e!=null?this.config.inspectorEnabled?this._annotations.get(e):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(e){return this._annotations.get(e)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(e){let n=this._traceRing.toArray().filter(o=>!e(o)),r=this._traceRing.size-n.length;this._traceRing.clear();for(let o of n)this._traceRing.push(o);return r}static diff(e,n){let r=new Set(Object.keys(e.nodes)),o=new Set(Object.keys(n.nodes)),s=[...o].filter(b=>!r.has(b)).sort(),i=[...r].filter(b=>!o.has(b)).sort(),a=[],u=[];for(let b of r){if(!o.has(b))continue;let v=e.nodes[b],T=n.nodes[b],w=v.v,k=T.v;w!=null&&k!=null&&w.id===k.id&&w.version!==k.version&&u.push({path:b,id:w.id,from:w.version,to:k.version});let x=w!=null&&k!=null&&w.id===k.id&&w.version===k.version;for(let R of["type","status","sentinel"]){let E=v[R],G=T[R];E!==G&&a.push({path:b,field:R,from:E,to:G})}if(!x)for(let R of["value","meta"]){let E=v[R],G=T[R];jf(E,G)||a.push({path:b,field:R,from:E,to:G})}}let c=b=>`${b.from} ${b.to}`,d=new Set(e.edges.map(c)),l=new Set(n.edges.map(c)),f=n.edges.filter(b=>!d.has(c(b))),p=e.edges.filter(b=>!l.has(c(b))),m=new Set(e.subgraphs),h=new Set(n.subgraphs),g=[...h].filter(b=>!m.has(b)).sort(),y=[...m].filter(b=>!h.has(b)).sort();return{nodesAdded:s,nodesRemoved:i,nodesChanged:a,versionChanges:u,edgesAdded:f,edgesRemoved:p,subgraphsAdded:g,subgraphsRemoved:y}}};function Go(t,e){let n=q.diff(t,e),r={};for(let o of n.nodesAdded){let s=e.nodes[o];s!=null&&(r[o]=s)}return{...n,nodesAddedFull:r}}function un(t,e,n,r={}){let o={paths:[],depths:new Map,truncated:!1};if(!e)return r.withDetail?o:[];if(!r.both&&n!=="upstream"&&n!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let s=r.maxDepth;if(s!=null&&(!Number.isInteger(s)||s<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(s===0)return r.withDetail?o:[];let i=new Map,a=new Map,u=new Map,c=new Map,d=new Set;for(let[v,T]of Object.entries(t.nodes)){if(!v)continue;d.add(v);let w=T.deps??[];i.set(v,w);for(let k of w)k&&(d.add(k),a.has(k)||a.set(k,new Set),a.get(k).add(v))}for(let v of t.edges){if(v==null||typeof v!="object")continue;let T=typeof v.from=="string"?v.from:"",w=typeof v.to=="string"?v.to:"";!T||!w||(d.add(T),d.add(w),c.has(T)||c.set(T,new Set),c.get(T).add(w),u.has(w)||u.set(w,new Set),u.get(w).add(T))}if(!d.has(e))return r.withDetail?o:[];let l=r.both===!0,f=v=>{if(l){let x=i.get(v)??[],R=u.get(v),E=a.get(v),G=c.get(v),L=[...x];return R&&L.push(...R),E&&L.push(...E),G&&L.push(...G),L}if(n==="upstream"){let x=i.get(v)??[],R=u.get(v);return R?[...x,...R]:x}let T=a.get(v),w=c.get(v),k=T?[...T]:[];return w&&k.push(...w),k},p=new Set([e]),m=new Map,h=[{path:e,depth:0}],g=0,y=!1;for(;g<h.length;){let v=h[g++];if(s!=null&&v.depth>=s){f(v.path).length>0&&(y=!0);continue}for(let T of f(v.path))!T||p.has(T)||(p.add(T),m.set(T,v.depth+1),h.push({path:T,depth:v.depth+1}))}let b=[...m.keys()].sort((v,T)=>v<T?-1:v>T?1:0);return r.withDetail?{paths:b,depths:m,truncated:y}:b}function nm(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.path!==o.path||r.type!==o.type||r.status!==o.status||r.hop!==o.hop||r.dep_index!==o.dep_index||r.annotation!==o.annotation||r.value!==o.value||r.lastMutation!==o.lastMutation)return!1;let s=r.v,i=o.v;if(s!==i&&(s==null||i==null||s.id!==i.id||s.version!==i.version))return!1}return!0}var Bo={};he(Bo,{CqrsGraph:()=>$o,MemoryEventStore:()=>Ii,cqrs:()=>Pi});Ne();ke();Qt();var Oi={};he(Oi,{COMPLETE:()=>_,COMPLETE_MSG:()=>eo,COMPLETE_ONLY_BATCH:()=>or,DATA:()=>S,DEFAULT_ACTOR:()=>lt,DIRTY:()=>ee,DIRTY_MSG:()=>yt,DIRTY_ONLY_BATCH:()=>Rn,ERROR:()=>M,GraphReFlyConfig:()=>Jt,GuardDenied:()=>Je,INVALIDATE:()=>He,INVALIDATE_MSG:()=>Zr,INVALIDATE_ONLY_BATCH:()=>rr,NodeImpl:()=>Ee,PAUSE:()=>Ie,RESOLVED:()=>B,RESOLVED_MSG:()=>kn,RESOLVED_ONLY_BATCH:()=>nr,RESUME:()=>Ge,START:()=>dt,START_MSG:()=>xn,TEARDOWN:()=>de,TEARDOWN_MSG:()=>to,TEARDOWN_ONLY_BATCH:()=>Sn,accessHintForGuard:()=>mr,advanceVersion:()=>hr,autoTrackNode:()=>Xt,batch:()=>te,configure:()=>pi,createVersioning:()=>Mn,defaultConfig:()=>Ae,defaultHash:()=>Ot,derived:()=>O,downWithBatch:()=>vt,dynamicNode:()=>gr,effect:()=>fe,isBatching:()=>zt,isV1:()=>ci,monotonicNs:()=>$,node:()=>K,normalizeActor:()=>bt,pipe:()=>fi,policy:()=>Yt,policyFromRules:()=>fr,producer:()=>W,registerBuiltins:()=>pr,resolveDescribeFields:()=>wt,state:()=>N,wallClockNs:()=>pe});ur();Ne();ke();ai();Qt();ie();xe();oe();oo();Ne();ie();oe();var Rr=class{_version=0;_maxSize;_buf;_head=0;_size=0;constructor(e,n){if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(this._maxSize=n,n!==void 0){if(this._buf=new Array(n),e&&e.length>0){let r=Math.min(e.length,n),o=e.length-r;for(let s=0;s<r;s++)this._buf[s]=e[o+s];this._size=r}}else this._buf=e?[...e]:[],this._size=this._buf.length}get version(){return this._version}get size(){return this._size}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._size+e;if(!(n<0||n>=this._size))return this._maxSize!==void 0?this._buf[(this._head+n)%this._maxSize]:this._buf[n]}append(e){this._rawAppend(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._maxSize!==void 0&&e.length>this._maxSize?e.length-this._maxSize:0;for(let r=n;r<e.length;r++)this._rawAppend(e[r]);this._version+=1}clear(){if(this._size===0)return 0;let e=this._size;if(this._maxSize===void 0)this._buf.length=0;else for(let n=0;n<e;n++)this._buf[(this._head+n)%this._maxSize]=void 0;return this._head=0,this._size=0,this._version+=1,e}trimHead(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`trimHead: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return 0;let n=Math.min(e,this._size);if(this._maxSize===void 0)this._buf.splice(0,n);else{for(let r=0;r<n;r++)this._buf[(this._head+r)%this._maxSize]=void 0;this._head=(this._head+n)%this._maxSize}return this._size-=n,this._version+=1,n}slice(e,n){if(!Number.isInteger(e)||e<0)throw new RangeError(`slice: start must be a non-negative integer (got ${e})`);if(n!==void 0&&(!Number.isInteger(n)||n<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${n})`);let r=n===void 0?this._size:Math.min(Math.max(n,0),this._size),o=Math.min(e,this._size);if(o>=r)return[];let s=r-o;if(this._maxSize===void 0)return this._buf.slice(o,r);let i=new Array(s);for(let a=0;a<s;a++)i[a]=this._buf[(this._head+o+a)%this._maxSize];return i}tail(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`tail: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return[];let n=Math.min(e,this._size);return this.slice(this._size-n,this._size)}toArray(){if(this._maxSize===void 0)return[...this._buf];let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this._buf[(this._head+n)%this._maxSize];return e}_rawAppend(e){if(this._maxSize===void 0){this._buf.push(e),this._size=this._buf.length;return}this._size<this._maxSize?(this._buf[(this._head+this._size)%this._maxSize]=e,this._size+=1):(this._buf[this._head]=e,this._head=(this._head+1)%this._maxSize)}};function Nc(t){return t.subscribe(()=>{})}var rm=64;function Ve(t,e={}){let{name:n,maxSize:r,versioning:o,backend:s}=e,i=s??new Rr(t,r),a=N(i.toArray(),{name:n,describeKind:"state",equals:(m,h)=>m===h,...o!=null?{versioning:o}:{}});function u(){let m=i.toArray();te(()=>{a.down([[ee]]),a.down([[S,m]])})}let c=new Map,d=new Map;function l(m,h){return`${m}:${h===void 0?"END":h}`}function f(m){if(m.size<rm)return;let h=m.keys().next();if(h.done)return;let g=m.get(h.value);g!==void 0&&g.dispose(),m.delete(h.value)}function p(m){let h=i.version;try{return m()}finally{i.version!==h&&u()}}return{entries:a,get size(){return i.size},at(m){return i.at(m)},append(m){p(()=>i.append(m))},appendMany(m){m.length!==0&&p(()=>i.appendMany(m))},clear(){p(()=>i.clear())},trimHead(m){p(()=>i.trimHead(m))},tail(m){if(!Number.isInteger(m)||m<0)throw new RangeError(`tail: n must be a non-negative integer (got ${m})`);let h=c.get(m);if(h!==void 0)return c.delete(m),c.set(m,h),h.node;f(c);let g=O([a],([b])=>{let v=b;return m===0||v.length===0?[]:v.slice(Math.max(0,v.length-m))},{initial:i.tail(m),describeKind:"derived"}),y=Nc(g);return c.set(m,{node:g,dispose:y}),g},slice(m,h){if(!Number.isInteger(m)||m<0)throw new RangeError(`slice: start must be a non-negative integer (got ${m})`);if(h!==void 0&&(!Number.isInteger(h)||h<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${h})`);let g=l(m,h),y=d.get(g);if(y!==void 0)return d.delete(g),d.set(g,y),y.node;f(d);let b=O([a],([T])=>{let w=T;return h===void 0?w.slice(m):w.slice(m,h)},{initial:i.slice(m,h),describeKind:"derived"}),v=Nc(b);return d.set(g,{node:b,dispose:v}),b},disposeTail(m){let h=c.get(m);return h===void 0?!1:(h.dispose(),c.delete(m),!0)},disposeSlice(m,h){let g=l(m,h),y=d.get(g);return y===void 0?!1:(y.dispose(),d.delete(g),!0)},disposeAllViews(){for(let m of c.values())m.dispose();c.clear();for(let m of d.values())m.dispose();d.clear()},dispose(){for(let m of c.values())m.dispose();c.clear();for(let m of d.values())m.dispose();d.clear()}}}var Ai={};he(Ai,{ENVELOPE_VERSION:()=>Nn,GRAPH_META_SEGMENT:()=>je,Graph:()=>q,JsonCodec:()=>no,SIZEOF_OVERHEAD:()=>Le,SIZEOF_SYMBOL:()=>Lo,SNAPSHOT_VERSION:()=>it,createDagCborCodec:()=>oi,createDagCborZstdCodec:()=>si,decodeEnvelope:()=>ir,diffForWAL:()=>Go,encodeEnvelope:()=>sr,explainPath:()=>kr,graphProfile:()=>an,mermaidLiveUrl:()=>Do,reachable:()=>un,registerBuiltinCodecs:()=>ar,replayWAL:()=>ii,sizeof:()=>xr,validateGraphObservability:()=>Ci,watchTopologyTree:()=>kt});ro();ie();function kt(t,e){let n=new Map,r=(o,s)=>{if(n.has(o))return;let i={off:()=>{},prefix:s};n.set(o,i);let a=o.topology.subscribe(u=>{for(let c of u){if(c[0]!==S)continue;let d=c[1];if(e(d,o,s),d.kind==="added"&&d.nodeKind==="mount"){let l=o._mounts.get(d.name);if(l instanceof q){let f=`${s}${d.name}::`;r(l,f)}}else if(d.kind==="removed"&&d.nodeKind==="mount"){let l=`${s}${d.name}::`;for(let[f,p]of Array.from(n.entries()))f!==t&&p.prefix.startsWith(l)&&(p.off(),n.delete(f))}}});i.off=a;for(let[u,c]of o._mounts)if(c instanceof q){let d=`${s}${u}::`;r(c,d)}};return r(t,""),()=>{for(let o of n.values())o.off();n.clear()}}function Ci(t,e={}){let n=[],r=e.requireFound??!0;if(e.skipDescribe!==!0)try{let c=t.describe(),d=new Set(Object.keys(c.nodes)),l=[];for(let[f,p]of Object.entries(c.nodes))for(let m of p.deps)m!==""&&!d.has(m)&&l.push(`${f} \u2192 ${m}`);for(let f of c.edges)d.has(f.from)||l.push(`edge.from: ${f.from}`),d.has(f.to)||l.push(`edge.to: ${f.to}`);l.length>0?n.push({kind:"describe",ok:!1,reason:`describe() has ${l.length} dangling pointer(s); nodes \u2289 deps`,danglingDeps:l}):n.push({kind:"describe",ok:!0,nodeCount:d.size,edgeCount:c.edges.length})}catch(c){n.push({kind:"describe",ok:!1,reason:`describe() threw: ${c instanceof Error?c.message:String(c)}`})}for(let c of e.formats??[])try{let d=t.describe({format:c});typeof d!="string"||d.length===0?n.push({kind:"describe-format",ok:!1,format:c,reason:`describe({ format: "${c}" }) returned empty or non-string output`}):n.push({kind:"describe-format",ok:!0,format:c,length:d.length})}catch(d){n.push({kind:"describe-format",ok:!1,format:c,reason:d instanceof Error?d.message:String(d)})}for(let c of e.paths??[])try{t.resolve(c),n.push({kind:"observe",ok:!0,path:c})}catch(d){n.push({kind:"observe",ok:!1,path:c,reason:d instanceof Error?d.message:String(d)})}for(let[c,d]of e.pairs??[])try{let l=t.explain(c,d);r&&l.found===!1?n.push({kind:"explain",ok:!1,from:c,to:d,reason:`explain(${c} \u2192 ${d}) found no path${l.reason?`: ${l.reason}`:""}`}):n.push({kind:"explain",ok:!0,from:c,to:d,found:l.found,steps:l.steps.length})}catch(l){n.push({kind:"explain",ok:!1,from:c,to:d,reason:l instanceof Error?l.message:String(l)})}let o=n.filter(c=>!c.ok),s=o.length===0,i=e.paths?.length??0,a=e.pairs?.length??0,u=e.formats?.length??0;return{ok:s,checks:n,failures:o,summary(){let c=[e.skipDescribe===!0?null:"describe",u>0?`${u} format${u===1?"":"s"}`:null,i>0?`${i} observe path${i===1?"":"s"}`:null,a>0?`${a} explain pair${a===1?"":"s"}`:null].filter(l=>l!=null),d=c.length>0?c.join(", "):"describe-only";return s?`validateGraphObservability: OK (${d})`:`validateGraphObservability: ${o.length} failure(s) across ${d}`}}}Ne();ie();xe();Re();function at(t,e){t!=null&&vt(n=>t.down(n),[[S,e]],Ae.tierOf)}function Sr(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[ee],[S,n+1]]),!0)}function Ke(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}function Li(t){return t.relatedTo?.[0]??t.summary}var om=Yt((t,e)=>{t("write"),t("signal"),e("observe")}),sm=Yt((t,e)=>{t("observe"),t("signal"),e("write")}),im=Yt((t,e)=>{t("observe"),t("signal"),e("write")});function Fo(t,e){return Ke("cqrs",t,e)}var Ii=class{_store=new Map;persist(e){let n=this._store.get(e.type);n||(n=[],this._store.set(e.type,n)),n.push(e)}loadEvents(e,n){let r=this._store.get(e)??[],o=n?.timestampNs,s=n?.seq,i=o==null?[...r]:r.filter(u=>u.timestampNs>o||u.timestampNs===o&&u.seq>(s??-1)),a=i.length>0?i[i.length-1]:void 0;return{events:i,cursor:a?{timestampNs:a.timestampNs,seq:a.seq}:n}}clear(){this._store.clear()}},$o=class extends q{_eventLogs=new Map;_commandHandlers=new Map;_projections=new Set;_sagas=new Set;_keepaliveDisposers=[];_eventStore;_seq=0;constructor(e,n={}){super(e,n.graph)}destroy(){for(let e of this._keepaliveDisposers)e();this._keepaliveDisposers.length=0,super.destroy()}event(e){let n=this._eventLogs.get(e);if(n)return n.node;let r=Ve([],{name:e,versioning:0}),o=r.entries,s=O([o],([i])=>i,{name:e,describeKind:"state",meta:Fo("event",{event_name:e}),guard:im,initial:o.cache});return this.add(s,{name:e}),this._keepaliveDisposers.push(se(s)),this._eventLogs.set(e,{log:r,node:s}),s}_appendEvent(e,n){let r=this._eventLogs.get(e);if(r||(this.event(e),r=this._eventLogs.get(e)),r.node.status==="completed"||r.node.status==="errored")throw new Error(`Cannot dispatch to terminated event stream "${e}" (status: ${r.node.status}).`);let o=r.log.entries.v,s={type:e,payload:n,timestampNs:pe(),seq:++this._seq,...o!=null?{v0:{id:o.id,version:o.version}}:{}};r.log.append(s),this._eventStore&&this._eventStore.persist(s)}command(e,n){let r=N(void 0,{name:e,describeKind:"state",meta:{...Fo("command",{command_name:e}),error:null},guard:om});return this.add(r,{name:e}),this._commandHandlers.set(e,n),r}dispatch(e,n){let r=this._commandHandlers.get(e);if(!r)throw new Error(`Unknown command: "${e}". Register with .command() first.`);let o=this.resolve(e);te(()=>{o.emit(n,{internal:!0});try{r(n,{emit:(s,i)=>this._appendEvent(s,i)}),o.meta.error.emit(null,{internal:!0})}catch(s){throw o.meta.error.emit(s,{internal:!0}),s}})}projection(e,n,r,o){let s=n.map(a=>(this._eventLogs.has(a)||this.event(a),this._eventLogs.get(a).node)),i=O(s,a=>{let u=[];for(let c of a){let d=c;u.push(...d)}return u.sort((c,d)=>c.timestampNs-d.timestampNs||c.seq-d.seq),r(o,u)},{name:e,describeKind:"derived",meta:Fo("projection",{projection_name:e,source_events:n}),guard:sm,initial:o});return this.add(i,{name:e}),this._keepaliveDisposers.push(se(i)),this._projections.add(e),i}saga(e,n,r){let o=n.map(u=>(this._eventLogs.has(u)||this.event(u),this._eventLogs.get(u).node)),s=new Map,i={},a=K(o,(u,c)=>{let d=i.n.meta.error;for(let l=0;l<u.length;l++){let f=u[l];if(f==null||f.length===0)continue;let p=f.at(-1);if(!p)continue;let m=n[l],h=s.get(m)??0;if(p.length>h){let g=p.slice(h);for(let y of g)try{r(y),d.emit(null,{internal:!0})}catch(b){d.emit(b,{internal:!0})}s.set(m,p.length)}}},{name:e,describeKind:"effect",meta:{...Fo("saga",{saga_name:e,source_events:n}),error:null}});return i.n=a,this.add(a,{name:e}),this._keepaliveDisposers.push(se(a)),this._sagas.add(e),a}useEventStore(e){this._eventStore=e}async rebuildProjection(e,n,r){if(!this._eventStore)throw new Error("No event store wired. Call useEventStore() first.");let o=[];for(let s of e){let i=await this._eventStore.loadEvents(s);o.push(...i.events)}return o.sort((s,i)=>s.timestampNs-i.timestampNs||s.seq-i.seq),n(r,o)}};function Pi(t,e){return new $o(t,e)}var Gi=class{constructor(e){this.graph=e}onModuleDestroy(){this.graph.destroy()}},Fi=class{graph=new q("request");onModuleDestroy(){this.graph.destroy()}},Ec,Di;Ec=[(0,Nr.Module)({})];var Gt=class Gt{static forRoot(e){let n=e??{},r=n.name??"root",o=[{provide:Xe,useFactory:()=>{let s=new q(r);return n.build&&n.build(s),n.snapshot&&s.restore(n.snapshot),s}},{provide:Symbol.for("graphrefly:root-lifecycle"),useFactory:s=>new Gi(s),inject:[Xe]},{provide:on,useFactory:(s,i)=>new on(s,i),inject:[Xe,_c.ModuleRef]}];if(n.nodes)for(let s of n.nodes)o.push({provide:ot(s),useFactory:i=>i.resolve(s),inject:[Xe]});return n.requestScope&&o.push({provide:Symbol.for("graphrefly:request-lifecycle"),useFactory:()=>new Fi,scope:Nr.Scope.REQUEST},{provide:Zt,useFactory:s=>s.graph,inject:[Symbol.for("graphrefly:request-lifecycle")],scope:Nr.Scope.REQUEST}),{module:Gt,global:!0,providers:o,exports:[Xe,...(n.nodes??[]).map(ot),...n.requestScope?[Zt]:[]]}}static forFeature(e){let n=[{provide:Ye(e.name),useFactory:r=>{let o=new q(e.name);return e.build&&e.build(o),e.snapshot&&o.restore(e.snapshot),r.mount(e.name,o),o},inject:[Xe]}];if(e.nodes)for(let r of e.nodes)n.push({provide:ot(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[Ye(e.name)]});return{module:Gt,providers:n,exports:[Ye(e.name),...(e.nodes??[]).map(r=>ot(`${e.name}::${r}`))]}}static forCqrs(e){let n=[{provide:Ye(e.name),useFactory:r=>{let o=Pi(e.name,e.cqrs);return e.eventStore&&o.useEventStore(e.eventStore),e.build&&e.build(o),r.mount(e.name,o),o},inject:[Xe]}];if(e.nodes)for(let r of e.nodes)n.push({provide:ot(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[Ye(e.name)]});return{module:Gt,providers:n,exports:[Ye(e.name),...(e.nodes??[]).map(r=>ot(`${e.name}::${r}`))]}}};Di=pu(null),Gt=hu(Di,0,"GraphReflyModule",Ec,Gt),mu(Di,1,Gt);var jo=Gt;var Ko={};he(Ko,{useStore:()=>am,useSubscribe:()=>Mc,useSubscribeRecord:()=>um});var xt=require("react");ie();function Mc(t){return(0,xt.useSyncExternalStore)(e=>{let n=!1,r=t.subscribe(()=>{n||e()});return()=>{n=!0,r()}},()=>t.cache,()=>t.cache)}function am(t){let e=Mc(t),n=(0,xt.useCallback)(r=>{t.down([[ee],[S,r]])},[t]);return[e,n]}function um(t,e){let n=(0,xt.useRef)(e);n.current=e;let r=(0,xt.useMemo)(()=>{let o=()=>{let i={},a=t.cache??[];for(let u of a){let c=n.current(u),d={};for(let l of Object.keys(c))d[l]=c[l].cache;i[u]=d}return i},s=o();return{subscribe:i=>{let a=!1,u=[],c=()=>{for(let f of u)f();u=[]},d=f=>{c();for(let p of f){let m=n.current(p);for(let h of Object.keys(m)){let g=m[h].subscribe(()=>{s=o(),a||i()});u.push(g)}}s=o(),a||i()},l=t.subscribe(f=>{let p=f.some(m=>m[0]===S||m[0]===B);!a&&p&&d(t.cache??[])});return d(t.cache??[]),()=>{a=!0,l(),c()}},getSnapshot:()=>s}},[t]);return(0,xt.useSyncExternalStore)(r.subscribe,r.getSnapshot,r.getSnapshot)}var Wo={};he(Wo,{Signal:()=>cm});Ne();ie();oe();var qn=[];function Ho(t){let e=t.cache;return t.subscribe(r=>{for(let[o,s]of r)o===S&&(e=s)})(),e}var $i=class{_node;_equals;constructor(e,n){this._equals=n?.equals??Object.is,this._node=N(e,{...n,resubscribable:!0,resetOnTeardown:!0})}get(){let e=qn[qn.length-1];return e?(this._node.status==="sentinel"&&Ho(this._node),e(this._node)):this._node.status==="sentinel"?Ho(this._node):this._node.cache}set(e){this._equals(this.get(),e)||te(()=>{this._node.down([[ee],[S,e]])})}},Bi=class{_node;constructor(e,n){this._node=Xt(r=>{qn.push(r);try{return e()}finally{qn.pop()}},{...n,describeKind:"derived",resubscribable:!0,resetOnTeardown:!0})}get(){let e=qn[qn.length-1];return e?(this._node.status==="sentinel"&&Ho(this._node),e(this._node)):this._node.status==="sentinel"?Ho(this._node):this._node.cache}},cm={State:$i,Computed:Bi,sub:(t,e)=>{let n=typeof e=="function"?{data:e,error:void 0,complete:void 0}:e,r=!0;return t._node.subscribe(o=>{for(let[s,i]of o){if(s===S){if(r){r=!1;continue}n.data?.(i)}s===M&&n.error?.(i),s===_&&n.complete?.()}})}};var qo={};he(qo,{useStore:()=>dm,useSubscribe:()=>Oc,useSubscribeRecord:()=>lm});var Rt=require("solid-js");ie();function Oc(t){let[e,n]=(0,Rt.createSignal)(t.cache,{equals:!1}),r=t.subscribe(()=>{n(()=>t.cache)});return(0,Rt.getOwner)()?(0,Rt.onCleanup)(()=>r()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Solid reactive owner \u2014 subscription will not be auto-disposed."),e}function dm(t){return[Oc(t),r=>{t.down([[ee],[S,r]])}]}function lm(t,e){let[n,r]=(0,Rt.createSignal)({},{equals:!1}),o=[],s=()=>{for(let c of o)c();o=[]},i=()=>{let c={};for(let d of t.cache??[]){let l=e(d),f={};for(let p of Object.keys(l))f[p]=l[p].cache;c[d]=f}return c},a=c=>{s();for(let d of c){let l=e(d);for(let f of Object.keys(l)){let p=l[f].subscribe(()=>{r(()=>i())});o.push(p)}}r(()=>i())},u=t.subscribe(c=>{c.some(d=>d[0]===S||d[0]===B)&&a(t.cache??[])});return a(t.cache??[]),(0,Rt.getOwner)()?(0,Rt.onCleanup)(()=>{u(),s()}):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribeRecord called outside a Solid reactive owner \u2014 subscription will not be auto-disposed."),n}var Uo={};he(Uo,{useStore:()=>fm,useSubscribe:()=>pm,useSubscribeRecord:()=>mm});ie();function pm(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n}}}function fm(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n},set(e){t.down([[ee],[S,e]])},update(e){let n=e(t.cache);t.down([[ee],[S,n]])}}}function mm(t,e){return{subscribe(n){let r=[],o=()=>{for(let u of r)u();r=[]},s=()=>{let u={};for(let c of t.cache??[]){let d=e(c),l={};for(let f of Object.keys(d))l[f]=d[f].cache;u[c]=l}return u},i=u=>{o();for(let c of u){let d=e(c);for(let l of Object.keys(d)){let f=d[l].subscribe(()=>{n(s())});r.push(f)}}n(s())},a=t.subscribe(u=>{u.some(c=>c[0]===S||c[0]===B)&&i(t.cache??[])});return i(t.cache??[]),()=>{a(),o()}}}}var zo={};he(zo,{useStore:()=>gm,useSubscribe:()=>hm,useSubscribeRecord:()=>ym});var Pe=require("vue");ie();function hm(t){let e=(0,Pe.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,Pe.getCurrentScope)()?(0,Pe.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Pe.readonly)(e)}function gm(t){let e=(0,Pe.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,Pe.getCurrentScope)()?(0,Pe.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useStore called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Pe.computed)({get:()=>e.value,set:r=>{t.down([[ee],[S,r]])}})}function ym(t,e){let n=(0,Pe.shallowRef)({}),r=new Map;function o(){let a={};for(let[u,c]of r)a[u]={...c.values};n.value=a}function s(a){for(let c of r.values())for(let d of c.subs)d();r.clear();for(let c of a){let d=e(c),l=Object.keys(d),f={},p=[];for(let m of l){let h=d[m];f[m]=h.cache;let g=h.subscribe(()=>{f[m]=h.cache,o()});p.push(g)}r.set(c,{subs:p,values:f})}let u={};for(let[c,d]of r)u[c]={...d.values};n.value=u}return(0,Pe.watch)(()=>[...(typeof t=="function"?t():(0,Pe.isRef)(t)?t.value:t)??[]],a=>s(a??[]),{immediate:!0}),(0,Pe.getCurrentScope)()?(0,Pe.onScopeDispose)(()=>{for(let a of r.values())for(let u of a.subs)u();r.clear()}):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribeRecord called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Pe.readonly)(n)}var Jo={};he(Jo,{create:()=>vm});ie();oe();var bm=()=>!1;function vm(t){let e=new q("zustand"),n=N(void 0,{name:"state",equals:bm});e.add(n,{name:"state"});let r=()=>n.cache,o=(a,u)=>{let c=n.cache,d=typeof a=="function"?a(c):a;n.emit(u?d:{...c,...d})},s={getState:r,setState:o,getInitialState:()=>i,subscribe:a=>{let u=!0,c=n.cache;return n.subscribe(d=>{for(let[l,f]of d)if(l===S){if(u){u=!1;continue}a(f,c),c=f}})},destroy:e.destroy.bind(e)},i=t(o,r,s);return n.emit(i),Object.assign(e,s)}var na={};he(na,{CircuitOpenError:()=>st,NS_PER_MS:()=>Fe,NS_PER_SEC:()=>Qe,NativeIndexBackend:()=>Ir,NativeListBackend:()=>Pr,NativeLogBackend:()=>Rr,NativeMapBackend:()=>Cr,NativePubSubBackend:()=>Lr,RateLimiterOverflowError:()=>tn,ResettableTimer:()=>_e,TimeoutError:()=>nn,audit:()=>Qc,awaitSettled:()=>So,buffer:()=>Xc,bufferCount:()=>Zc,bufferTime:()=>td,cached:()=>Qu,cascadingCache:()=>cl,catchError:()=>ld,checkpointToRedis:()=>tl,checkpointToS3:()=>el,circuitBreaker:()=>ft,combine:()=>Ki,combineLatest:()=>ud,concat:()=>Hc,concatMap:()=>Uc,constant:()=>ho,createTransport:()=>$t,createWatermarkController:()=>Hn,csvRows:()=>Dd,debounce:()=>Wi,debounceTime:()=>cd,decorrelatedJitter:()=>vo,delay:()=>Jc,deserializeError:()=>fn,dictStorage:()=>vl,distill:()=>Zo,distinctUntilChanged:()=>jc,elementAt:()=>$c,empty:()=>qu,escapeRegexChar:()=>vi,exhaustMap:()=>qc,exponential:()=>yo,externalBundle:()=>Yo,externalProducer:()=>cn,fallback:()=>jn,fibonacci:()=>bo,filter:()=>ut,find:()=>Fc,first:()=>Qo,firstValueFrom:()=>Kn,firstWhere:()=>wo,flatMap:()=>zc,forEach:()=>Pt,fromAny:()=>re,fromAsyncIter:()=>wi,fromCSV:()=>Pd,fromClickHouseWatch:()=>Bd,fromCron:()=>ko,fromDrizzle:()=>il,fromEvent:()=>Wu,fromHTTP:()=>Yi,fromHTTPPoll:()=>wd,fromHTTPStream:()=>Td,fromIter:()=>xo,fromKafka:()=>Cd,fromKysely:()=>al,fromMCP:()=>Rd,fromNATS:()=>Kd,fromNDJSON:()=>$d,fromOTel:()=>Sd,fromPrisma:()=>sl,fromPrometheus:()=>Od,fromPromise:()=>Ti,fromPulsar:()=>jd,fromRabbitMQ:()=>Wd,fromRaf:()=>Hu,fromRedisStream:()=>Ld,fromSSE:()=>vd,fromSqlite:()=>nl,fromSqliteCursor:()=>rl,fromStatsD:()=>_d,fromSyslog:()=>Nd,fromTimer:()=>et,fromWebSocket:()=>Ji,fromWebSocketReconnect:()=>xd,fromWebhook:()=>pd,globToRegExp:()=>Vu,interval:()=>od,keepalive:()=>se,last:()=>Gc,linear:()=>go,lru:()=>Zi,map:()=>Er,matchesAnyPattern:()=>Ku,matchesCron:()=>mo,memoryStorage:()=>Gr,merge:()=>mt,mergeMap:()=>Hi,nameToSignal:()=>ln,ndjsonRows:()=>Gd,never:()=>Uu,of:()=>ki,pairwise:()=>Vc,parseCron:()=>fo,parsePrometheusText:()=>Qi,parseStatsD:()=>Md,parseSyslog:()=>Ed,pausable:()=>id,pubsub:()=>fl,race:()=>Wc,rateLimiter:()=>Bn,reactiveCounter:()=>xi,reactiveIndex:()=>gl,reactiveList:()=>es,reactiveLog:()=>Ve,reactiveMap:()=>tt,reactiveSink:()=>$e,reduce:()=>Ic,repeat:()=>sd,replay:()=>Ro,rescue:()=>Mr,resolveBackoffPreset:()=>Ct,retry:()=>Fn,retrySource:()=>At,sample:()=>Yc,scan:()=>Lc,serializeError:()=>pn,share:()=>Yu,shareReplay:()=>Xu,signalToName:()=>Ft,singleFromAny:()=>ts,singleNodeFromAny:()=>yl,skip:()=>Vi,sortJsonValue:()=>Dr,stableJsonString:()=>bl,stratify:()=>Fr,switchMap:()=>be,take:()=>_r,takeUntil:()=>Dc,takeWhile:()=>Pc,tap:()=>Bc,throttle:()=>qi,throttleTime:()=>dd,throwError:()=>zu,timeout:()=>Vn,toArray:()=>Ju,toCSV:()=>Ud,toClickHouse:()=>zd,toFile:()=>Xi,toHTTP:()=>fd,toKafka:()=>Ad,toLoki:()=>Xd,toMongo:()=>Qd,toNATS:()=>Hd,toObservable:()=>po,toPostgres:()=>Yd,toPulsar:()=>Vd,toRabbitMQ:()=>qd,toReadableStream:()=>bd,toRedisStream:()=>Id,toS3:()=>Jd,toSSE:()=>gd,toSSEBytes:()=>yd,toSqlite:()=>ol,toTempo:()=>Zd,toWebSocket:()=>kd,tokenBucket:()=>Lt,valve:()=>ad,verifiable:()=>pl,window:()=>rd,windowCount:()=>ed,windowTime:()=>nd,withBreaker:()=>$n,withLatestFrom:()=>dn,withMaxAttempts:()=>yi,withStatus:()=>It,workerBridge:()=>ea,workerSelf:()=>ta,zip:()=>Kc});Ne();ke();ie();xe();oe();Ne();ie();oe();function Cc(t){return{describeKind:"producer",...t}}function cn(t,e){return W(n=>{let r=!0,o={emit(i){r&&n.emit(i)},error(i){r&&(r=!1,n.down([[M,i]]))},complete(){r&&(r=!1,n.down([[_]]))}},s;try{let i=t(o);s=typeof i=="function"?i:void 0}catch(i){return o.error(i),()=>{r=!1}}return()=>{r=!1;try{s?.()}catch{}}},Cc(e))}function Yo(t,e,n){let r=!0,o,s=0,i=0,a={},u=[],c=()=>{let p=o;o=void 0;try{p?.()}catch{}};for(let p of e){let m=n?.name?`${n.name}::${p}`:p,h=n?.channelOpts?.[p],g=W(y=>(s++,()=>{i++,s>0&&i>=s&&i>=e.length&&c()}),Cc({...h,name:m}));a[p]=g,u.push(g)}let d={};for(let p of e)d[p]=m=>{r&&a[p].down([[S,m]])};d.error=p=>{r&&(r=!1,te(()=>{for(let m of u)m.down([[M,p]])}),c())},d.complete=()=>{r&&(r=!1,te(()=>{for(let p of u)p.down([[_]])}),c())};let l=t(d);return o=typeof l=="function"?l:void 0,Object.assign(a,{dispose:()=>{r&&(r=!1,te(()=>{for(let p of u)try{p.down([[_]])}catch{}}),c())}})}ke();ie();xe();oe();Re();function ce(t){return{describeKind:"derived",...t}}function Ac(t){return{describeKind:"derived",partial:!0,...t}}function Er(t,e,n){return K([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[B]]);return}for(let i of s)o.emit(e(i))},ce(n))}function ut(t,e,n){return K([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[B]]);return}let i=!1;for(let a of s)e(a)&&(o.emit(a),i=!0);i||o.down([[B]])},ce(n))}function Lc(t,e,n,r){return K([t],(o,s,i)=>{"acc"in i.store||(i.store.acc=n);let a=o[0];if(a==null||a.length===0){s.down([[B]]);return}for(let u of a)i.store.acc=e(i.store.acc,u),s.emit(i.store.acc)},{...ce(r),initial:n,resetOnTeardown:!0})}function Ic(t,e,n,r){return K([t],(o,s,i)=>{if("acc"in i.store||(i.store.acc=n),i.terminalDeps[0]===!0){s.emit(i.store.acc),s.down([[_]]);return}let a=o[0];if(a==null||a.length===0){s.down([[B]]);return}for(let u of a)i.store.acc=e(i.store.acc,u)},{...ce(r),completeWhenDepsComplete:!1})}function _r(t,e,n){return e<=0?K([t],(r,o,s)=>{s.store.completed||(s.store.completed=!0,o.down([[_]]))},{...ce(n),completeWhenDepsComplete:!1}):K([t],(r,o,s)=>{if("taken"in s.store||(s.store.taken=0),s.store.done){o.down([[B]]);return}if(s.terminalDeps[0]===!0){s.store.done=!0,o.down([[_]]);return}let i=r[0];if(i==null||i.length===0){o.down([[B]]);return}for(let a of i)if(s.store.taken++,o.emit(a),s.store.taken>=e){s.store.done=!0,o.down([[_]]);return}},{...ce(n),completeWhenDepsComplete:!1})}function Vi(t,e,n){return K([t],(r,o,s)=>{"skipped"in s.store||(s.store.skipped=0);let i=r[0];if(i==null||i.length===0){o.down([[B]]);return}let a=!1;for(let u of i)s.store.skipped++,s.store.skipped<=e||(o.emit(u),a=!0);a||o.down([[B]])},ce(n))}function Pc(t,e,n){return K([t],(r,o,s)=>{if(s.store.done){o.down([[B]]);return}let i=r[0];if(i==null||i.length===0){o.down([[B]]);return}for(let a of i){if(!e(a)){s.store.done=!0,o.down([[_]]);return}o.emit(a)}},{...ce(n),completeWhenDepsComplete:!1})}function Dc(t,e,n){let r=n?.predicate??(i=>i[0]===S),{predicate:o,...s}=n??{};return W(i=>{let a=!1,u=t.subscribe(d=>{if(!a)for(let l of d){if(a)return;l[0]===S?i.emit(l[1]):(l[0]===_||l[0]===M)&&(a=!0,i.down([l]))}}),c=e.subscribe(d=>{if(!a)for(let l of d){if(a)return;if(r(l)){a=!0,i.down([[_]]);return}}});return()=>{u(),c()}},ce(s))}function Qo(t,e){return _r(t,1,e)}function Gc(t,e){let{defaultValue:n,...r}=e??{},o=e!=null&&Object.hasOwn(e,"defaultValue");return K([t],(s,i,a)=>{if(a.terminalDeps[0]===!0){a.store.has?i.emit(a.store.latest):o&&i.emit(n),i.down([[_]]);return}let u=s[0];if(u==null||u.length===0){i.down([[B]]);return}a.store.latest=u.at(-1),a.store.has=!0},{...ce(r),completeWhenDepsComplete:!1})}function Fc(t,e,n){return _r(ut(t,e,n),1,n)}function $c(t,e,n){return _r(Vi(t,e,n),1,n)}function Bc(t,e,n){if(typeof e=="function")return K([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[B]]);return}for(let a of i)e(a),s.emit(a)},ce(n));let r=e;return K([t],(o,s,i)=>{if(i.terminalDeps[0]!==void 0){i.terminalDeps[0]===!0?(r.complete?.(),s.down([[_]])):(r.error?.(i.terminalDeps[0]),s.down([[M,i.terminalDeps[0]]]));return}let a=o[0];if(a==null||a.length===0){s.down([[B]]);return}for(let u of a)r.data?.(u),s.emit(u)},{...ce(n),completeWhenDepsComplete:!1})}function jc(t,e=Object.is,n){return K([t],(r,o,s)=>{let i=r[0];if(i==null||i.length===0){o.down([[B]]);return}let a=!1;for(let u of i)s.store.hasPrev&&e(s.store.prev,u)||(s.store.prev=u,s.store.hasPrev=!0,o.emit(u),a=!0);a||o.down([[B]])},ce(n))}function Vc(t,e){return K([t],(n,r,o)=>{let s=n[0];if(s==null||s.length===0){r.down([[B]]);return}let i=!1;for(let a of s)if(!o.store.hasPrev)o.store.prev=a,o.store.hasPrev=!0;else{let u=[o.store.prev,a];o.store.prev=a,r.emit(u),i=!0}i||r.down([[B]])},ce(e))}function Ki(...t){let e=[...t];return O(e,n=>n,{...ce(),equals:(n,r)=>{if(n.length!==r.length)return!1;for(let o=0;o<n.length;o++)if(!Object.is(n[o],r[o]))return!1;return!0}})}function dn(t,e,n){return K([t,e],(r,o,s)=>{let i=r[0],a=r[1],u=a!=null&&a.length>0?a.at(-1):s.prevData[1];if(i!=null&&i.length>0){if(!(a!=null&&a.length>0)&&s.prevData[1]===void 0){o.down([[B]]);return}for(let c of i)o.emit([c,u])}else o.down([[B]])},Ac(n))}function mt(...t){return t.length===0?W(e=>{e.down([[_]])},ce()):W(e=>{let n=t.length,r=0,o=[];for(let s of t){let i=s.subscribe(a=>{for(let u of a)u[0]===S?e.emit(u[1]):u[0]===_?(r+=1,r>=n&&e.down([[_]])):u[0]===M&&e.down([u])});o.push(i)}return()=>{for(let s of o)s()}},ce())}function Kc(...t){let e=t.length;return e===0?W(n=>{n.emit([]),n.down([[_]])},ce()):W(n=>{let r=Array.from({length:e},()=>[]),o=e;function s(){for(;r.every(a=>a.length>0);){let a=r.map(u=>u.shift());n.emit(a)}}let i=[];for(let a=0;a<e;a++){let u=a,c=t[a].subscribe(d=>{for(let l of d)l[0]===S?(r[u].push(l[1]),s()):l[0]===_?(o-=1,(o===0||r[u].length===0)&&n.down([[_]])):l[0]===M&&n.down([l])});i.push(c)}return()=>{for(let a of i)a()}},ce())}function Hc(t,e,n){return W(r=>{let o=0,s=[],i,a;return a=e.subscribe(u=>{for(let c of u)o===0?c[0]===S?s.push(c[1]):c[0]===M&&r.down([c]):c[0]===S?r.emit(c[1]):(c[0]===_||c[0]===M)&&r.down([c])}),i=t.subscribe(u=>{for(let c of u)if(o===0)if(c[0]===S)r.emit(c[1]);else if(c[0]===_){o=1;for(let d of s)r.emit(d);s.length=0}else c[0]===M&&r.down([c])}),()=>{i?.(),a?.()}},ce(n))}function Wc(...t){return t.length===0?W(e=>{e.down([[_]])},ce()):t.length===1?K([t[0]],(e,n)=>{let r=e[0];if(r==null||r.length===0){n.down([[B]]);return}for(let o of r)n.emit(o)},ce()):W(e=>{let n=null,r=[];for(let o=0;o<t.length;o++){let s=o,i=t[o].subscribe(a=>{for(let u of a){if(n!==null&&s!==n)return;u[0]===S?(n===null&&(n=s),e.emit(u[1])):(u[0]===_||u[0]===M)&&(n===null||s===n)&&e.down([u])}});r.push(i)}return()=>{for(let o of r)o()}},ce())}function Xo(t,e,n){let r,o=!1,s=()=>{o||(o=!0,n())};return r=t.subscribe(i=>{let a=!1,u=!1;for(let c of i)c[0]!==dt&&(c[0]===S?e.emit(c[1]):c[0]===_?a=!0:c[0]===M?(u=!0,e.down([c])):(c[0]===ee||c[0]===B)&&e.down([c]));u?(r?.(),r=void 0,s()):a&&s()}),()=>{r?.(),r=void 0}}function be(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return K([t],(i,a,u)=>{if(u.terminalDeps[0]!=null&&u.terminalDeps[0]!==!0){s();return}if(u.terminalDeps[0]===!0){o=!0,r||a.down([[_]]);return}let c=i[0];if(!(c==null||c.length===0))return s(),r=Xo(re(e(c[c.length-1])),a,()=>{s(),o&&a.down([[_]])}),{deactivate:()=>{s(),o=!1}}},{...ce(n),completeWhenDepsComplete:!1})}function qc(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return K([t],(i,a,u)=>{if(u.terminalDeps[0]!=null&&u.terminalDeps[0]!==!0){s();return}if(u.terminalDeps[0]===!0){o=!0,r||a.down([[_]]);return}let c=i[0];if(!(c==null||c.length===0))return r===void 0?r=Xo(re(e(c[0])),a,()=>{s(),o&&a.down([[_]])}):a.down([[B]]),{deactivate:()=>{s(),o=!1}}},{...ce(n),completeWhenDepsComplete:!1})}function Uc(t,e,n){let{maxBuffer:r,...o}=n??{},s=[],i,a=!1,u;function c(){i?.(),i=void 0}function d(){if(!u||i!==void 0)return;if(s.length===0){a&&u.down([[_]]);return}let f=s.shift();i=Xo(re(e(f)),u,()=>{c(),d()})}function l(f){r&&r>0&&s.length>=r&&s.shift(),s.push(f),d()}return K([t],(f,p,m)=>{if(u=p,m.terminalDeps[0]!=null&&m.terminalDeps[0]!==!0){c(),s.length=0;return}if(m.terminalDeps[0]===!0){a=!0,d();return}let h=f[0];if(!(h==null||h.length===0)){for(let g of h)l(g);return{deactivate:()=>{c(),s.length=0,a=!1}}}},{...ce(o),completeWhenDepsComplete:!1})}function Hi(t,e,n){let{concurrent:r,...o}=n??{},s=r!=null&&r>0?r:Number.POSITIVE_INFINITY,i=0,a=!1,u=new Set,c=[],d;function l(){a&&i===0&&c.length===0&&d&&d.down([[_]])}function f(g){if(!d)return;i++;let y;y=Xo(re(e(g)),d,()=>{y&&u.delete(y),i--,p(),l()}),u.add(y)}function p(){for(;c.length>0&&i<s;)f(c.shift())}function m(g){i<s?f(g):c.push(g)}function h(){for(let g of u)g();u.clear(),i=0,c.length=0}return K([t],(g,y,b)=>{if(d=y,b.terminalDeps[0]!=null&&b.terminalDeps[0]!==!0){h();return}if(b.terminalDeps[0]===!0){a=!0,l();return}let v=g[0];if(!(v==null||v.length===0)){for(let T of v)m(T);return{deactivate:()=>{h(),a=!1}}}},{...ce(o),completeWhenDepsComplete:!1})}var zc=Hi;function Jc(t,e,n){return W(r=>{let o=new Set;function s(){for(let a of o)clearTimeout(a);o.clear()}let i=t.subscribe(a=>{for(let u of a)if(u[0]===S){let c=setTimeout(()=>{o.delete(c),r.emit(u[1])},e);o.add(c)}else if(u[0]===_){let c=setTimeout(()=>{o.delete(c),r.down([[_]])},e);o.add(c)}else u[0]===M&&(s(),r.down([u]))});return()=>{i(),s()}},ce(n))}function Wi(t,e,n){return W(r=>{let o,s;function i(){o!==void 0&&(clearTimeout(o),o=void 0)}let a=t.subscribe(u=>{for(let c of u)c[0]===S?(i(),s=c[1],o=setTimeout(()=>{o=void 0,r.emit(s)},e)):c[0]===_?(o!==void 0&&(i(),r.emit(s)),r.down([[_]])):c[0]===M&&(i(),r.down([c]))});return()=>{a(),i()}},ce(n))}function qi(t,e,n){let{leading:r,trailing:o,...s}=n??{},i=r!==!1,a=o===!0,u=e*1e6;return W(c=>{let d,l=-1/0,f,p=!1;function m(){d!==void 0&&(clearTimeout(d),d=void 0)}let h=t.subscribe(g=>{for(let y of g)if(y[0]===S){let b=y[1],v=$();if(i&&v-l>=u)l=v,c.emit(b),m(),a&&(d=setTimeout(()=>{d=void 0,p&&(l=$(),c.emit(f),p=!1)},e));else if(a&&(f=b,p=!0,d===void 0)){let T=(v-l)/1e6;d=setTimeout(()=>{d=void 0,p&&(l=$(),c.emit(f),p=!1)},Math.max(0,e-T))}}else(y[0]===_||y[0]===M)&&(m(),c.down([y]))});return()=>{h(),m()}},ce(s))}function Yc(t,e,n){return W(r=>{let o,s=!1,i=!1,a=t.subscribe(c=>{if(!s)for(let d of c){if(s)return;d[0]===S?o={v:d[1]}:d[0]===M?(s=!0,r.down([d])):d[0]===_&&(i=!0,o=void 0)}}),u=e.subscribe(c=>{if(!s)for(let d of c){if(s)return;d[0]===S?o!==void 0&&!i&&r.emit(o.v):d[0]===M?(s=!0,r.down([d])):d[0]===_&&(s=!0,r.down([[_]]))}});return()=>{a(),u()}},ce(n))}function Qc(t,e,n){return W(r=>{let o,s,i=!1;function a(){o!==void 0&&(clearTimeout(o),o=void 0)}let u=t.subscribe(c=>{for(let d of c)d[0]===S?(s=d[1],i=!0,a(),o=setTimeout(()=>{o=void 0,i&&(i=!1,r.emit(s))},e)):(d[0]===_||d[0]===M)&&(a(),r.down([d]))});return()=>{u(),a()}},ce(n))}function Xc(t,e,n){return W(r=>{let o=[],s=t.subscribe(a=>{for(let u of a)u[0]===S?o.push(u[1]):u[0]===_?(o.length>0&&r.emit([...o]),o.length=0,r.down([[_]])):u[0]===M&&r.down([u])}),i=e.subscribe(a=>{for(let u of a)u[0]===S?o.length>0&&(r.emit([...o]),o.length=0):u[0]===_?r.down([[_]]):u[0]===M&&r.down([u])});return()=>{s(),i(),o.length=0}},ce(n))}function Zc(t,e,n){if(e<=0)throw new RangeError("bufferCount expects count > 0");return W(r=>{let o=[],s=t.subscribe(i=>{for(let a of i)a[0]===S?(o.push(a[1]),o.length>=e&&r.emit(o.splice(0,o.length))):a[0]===_?(o.length>0&&r.emit([...o]),o.length=0,r.down([[_]])):a[0]===M&&r.down([a])});return()=>{s(),o.length=0}},ce(n))}function ed(t,e,n){if(e<=0)throw new RangeError("windowCount expects count > 0");return W(r=>{let o,s=0;function i(){let u=W(c=>(o=c.down.bind(c),()=>{o=void 0}),ce());s=0,r.emit(u)}let a=t.subscribe(u=>{for(let c of u)c[0]===S?(o||i(),o?.([[S,c[1]]]),s+=1,s>=e&&(o?.([[_]]),o=void 0)):c[0]===_?(o?.([[_]]),o=void 0,r.down([[_]])):c[0]===M&&(o?.([c]),o=void 0,r.down([c]))});return()=>{a(),o?.([[_]]),o=void 0}},ce(n))}function td(t,e,n){return W(r=>{let o=[],s=setInterval(()=>{o.length>0&&(r.emit([...o]),o.length=0)},e),i=t.subscribe(a=>{for(let u of a)u[0]===S?o.push(u[1]):u[0]===_?(clearInterval(s),o.length>0&&r.emit([...o]),o.length=0,r.down([[_]])):u[0]===M&&(clearInterval(s),r.down([u]))});return()=>{i(),clearInterval(s),o.length=0}},ce(n))}function nd(t,e,n){return W(r=>{let o;function s(){o?.([[_]]),o=void 0}function i(){let c=W(d=>(o=d.down.bind(d),()=>{o=void 0}),ce());r.emit(c)}i();let a=setInterval(()=>{s(),i()},e),u=t.subscribe(c=>{for(let d of c)d[0]===S?o?.([[S,d[1]]]):d[0]===_?(clearInterval(a),s(),r.down([[_]])):d[0]===M&&(clearInterval(a),o?.([d]),s(),r.down([d]))});return()=>{u(),clearInterval(a),s()}},ce(n))}function rd(t,e,n){return W(r=>{let o;function s(){o?.([[_]]),o=void 0}function i(){let c=W(d=>(o=d.down.bind(d),()=>{o=void 0}),ce());r.emit(c)}let a=t.subscribe(c=>{for(let d of c)d[0]===S?(o||i(),o?.([[S,d[1]]])):d[0]===_?(s(),r.down([[_]])):d[0]===M&&(o?.([d]),o=void 0,r.down([d]))}),u=e.subscribe(c=>{for(let d of c)d[0]===S&&(s(),i())});return()=>{a(),u(),s()}},ce(n))}function od(t,e){return W((n,r)=>{"n"in r.store||(r.store.n=0);let o=setInterval(()=>{n.emit(r.store.n),r.store.n=r.store.n+1},t);return()=>clearInterval(o)},ce(e))}function sd(t,e,n){if(e<=0)throw new RangeError("repeat expects count > 0");return W(r=>{let o=e,s,i=()=>{s?.(),s=t.subscribe(a=>{let u=!1,c=[];for(let d of a)d[0]===_?u=!0:c.push(d);c.length>0&&r.down(c),u&&(s?.(),s=void 0,o-=1,o>0?i():r.down([[_]]))})};return i(),()=>{s?.()}},ce(n))}function id(t,e){return K([t],(n,r)=>{let o=n[0];if(o==null||o.length===0){r.down([[B]]);return}for(let s of o)r.emit(s)},ce(e))}function Mr(t,e,n){return W(r=>{let o=t.subscribe(s=>{for(let i of s)if(i[0]===S)r.emit(i[1]);else if(i[0]===M)try{r.emit(e(i[1]))}catch(a){r.down([[M,a]])}else i[0]===_&&r.down([[_]])});return()=>{o()}},ce(n))}function ad(t,e,n){return K([t,e],(r,o,s)=>{let i=r[1];if(!(i!=null&&i.length>0?i.at(-1):s.prevData[1])){o.down([[B]]);return}let u=r[0];if(u!=null&&u.length>0){for(let c of u)o.emit(c);return}if(i!=null&&i.length>0&&s.prevData[0]!==void 0){o.emit(s.prevData[0]);return}o.down([[B]])},Ac(n))}var ud=Ki,cd=Wi,dd=qi,ld=Mr;ie();xe();oe();Gn();var Ui=class{ring;arr;constructor(e){e===Number.POSITIVE_INFINITY||e<=0?(this.arr=[],this.ring=null):(this.ring=new sn(e),this.arr=null)}get length(){return this.ring!=null?this.ring.size:this.arr.length}push(e){this.ring!=null?this.ring.push(e):this.arr.push(e)}shift(){return this.ring!=null?this.ring.shift():this.arr.shift()}drain(){if(this.ring!=null){let n=this.ring.toArray();return this.ring.clear(),n}let e=this.arr;return this.arr=[],e}};function Or(t){return t instanceof Error?t:new Error(String(t))}function Tm(t){return t===void 0?null:typeof t=="string"?Ct(t):t}function $e(t,e){let{name:n,onTransportError:r,retry:o,backpressure:s,batchSize:i=Number.POSITIVE_INFINITY,flushIntervalMs:a=0,serialize:u,stopOn:c,onUpstreamMessage:d,onDispose:l,send:f,sendBatch:p,ctx:m}=e;if(!f&&!p)throw new Error("reactiveSink: `send` or `sendBatch` must be provided");let h=m,g=Math.max(1,o?.maxAttempts??1),y=Tm(o?.backoff??(g>1?"exponential":void 0)),b=o?.shouldRetry??(()=>!0),v=p!==void 0||i<Number.POSITIVE_INFINITY||a>0,T=Z=>n?`${n}::${Z}`:void 0,w=N(void 0,{equals:()=>!1,name:T("sent")}),k=N(null,{name:T("failed")}),x=N(0,{name:T("inFlight")}),R=N(null,{name:T("errors")}),E=v?N(0,{name:T("buffered")}):void 0,G=s?N(!1,{name:T("paused")}):void 0,L=0,P=Z=>{L+=Z,x.down([[S,L]])},C=Z=>{try{r?.(Z)}catch{}try{R.down([[S,Z]])}catch{}},V=new Set,ne=Z=>{V.add(Z);let ue=()=>V.delete(Z);Z.then(ue,ue)},F=(Z,ue,me)=>{let Se=y?y(ue-1,me,null):0,De=Se==null?0:typeof Se=="number"&&Se>0?Se:0,qe=Math.max(1,Math.ceil(De/1e6));return new Promise(Te=>{setTimeout(()=>Te(Z()),qe)})},A=Z=>Z!=null&&typeof Z=="object"&&typeof Z.then=="function",D=Z=>{let ue;try{ue=u?u(Z):Z}catch(Te){let ye=Or(Te);return C({stage:"serialize",error:ye,value:Z}),k.down([[S,{value:Z,error:ye,attempts:0}]]),Promise.resolve()}let me=0,Se=Te=>{P(-1);let ye=Or(Te);if(C({stage:"send",error:ye,value:Z,attempt:me}),!(me<g&&b(ye,me))){k.down([[S,{value:Z,error:ye,attempts:me}]]);return}return F(qe,me,ye)},De=()=>{P(-1),w.down([[S,Z]])};function qe(){me+=1,P(1);let Te;try{Te=f(ue,h)}catch(ye){return Se(ye)??Promise.resolve()}return A(Te)?Te.then(De,ye=>Se(ye)):(De(),Promise.resolve())}return qe()},I=s?.maxBuffer??Number.POSITIVE_INFINITY,Q=new Ui(I),U,ae=!1,j=()=>{E?.down([[S,Q.length]])},Y=Z=>{G&&G.down([[S,Z]])},J=s?.strategy??"drop-oldest",z=(Z,ue)=>{let me={value:Z,payload:ue};if(Q.length<I)return Q.push(me),j(),!0;if(J==="drop-oldest"){let De=Q.shift();return Q.push(me),j(),Y(!0),k.down([[S,{value:De.value,error:new Error("backpressure: buffer overflow \u2014 dropped oldest"),attempts:0}]]),!0}if(J==="drop-newest")return Y(!0),k.down([[S,{value:Z,error:new Error("backpressure: buffer overflow \u2014 dropped newest"),attempts:0}]]),!1;let Se=new Error("backpressure: buffer overflow");return C({stage:"send",error:Se,value:Z}),k.down([[S,{value:Z,error:Se,attempts:0}]]),Y(!0),!1},X=Z=>{let ue=0,me=Z.map(Te=>Te.payload),Se=Te=>{P(-1);let ye=Or(Te);if(C({stage:"send",error:ye,value:Z.map(ni=>ni.value),attempt:ue}),!(ue<g&&b(ye,ue))){for(let{value:ni}of Z)k.down([[S,{value:ni,error:ye,attempts:ue}]]);return}return F(qe,ue,ye)},De=()=>{P(-1);for(let{value:Te}of Z)w.down([[S,Te]])};function qe(){ue+=1,P(1);let Te;try{Te=p(me,h)}catch(ye){return Se(ye)??Promise.resolve()}return A(Te)?Te.then(De,ye=>Se(ye)):(De(),Promise.resolve())}return qe()},H=async Z=>{for(let ue of Z)await le(ue.value,ue.payload)},le=(Z,ue)=>{let me=0,Se=Te=>{P(-1);let ye=Or(Te);if(C({stage:"send",error:ye,value:Z,attempt:me}),!(me<g&&b(ye,me))){k.down([[S,{value:Z,error:ye,attempts:me}]]);return}return F(qe,me,ye)},De=()=>{P(-1),w.down([[S,Z]])};function qe(){me+=1,P(1);let Te;try{Te=f(ue,h)}catch(ye){return Se(ye)??Promise.resolve()}return A(Te)?Te.then(De,ye=>Se(ye)):(De(),Promise.resolve())}return qe()},ve=()=>{if(ae||Q.length===0)return Promise.resolve();let Z=Q.drain();if(j(),Y(!1),p!==void 0){let me=X(Z);return ne(me),me}let ue=H(Z);return ne(ue),ue},Oe=()=>{U!==void 0||ae||a<=0||(U=setTimeout(()=>{U=void 0,ve()},a))},Be=t.subscribe(Z=>{for(let ue of Z){let me=ue[0];if(me!==S)try{d?.(ue)}catch{}if(me===S){let Se=ue[1];if(v){let De;if(u)try{De=u(Se)}catch(Te){let ye=Or(Te);C({stage:"serialize",error:ye,value:Se}),k.down([[S,{value:Se,error:ye,attempts:0}]]);continue}else De=Se;if(!z(Se,De))continue;Q.length>=i?ve():Oe()}else{let De=D(Se);ne(De)}}else Ae.messageTier(me)>=3&&v&&(U!==void 0&&(clearTimeout(U),U=void 0),ve())}}),gt;if(c){let Z=!1;gt=c.subscribe(ue=>{if(!Z){Z=!0;return}ue.length>0&&!Wt&&rt()})}let Wt=!1,rt=()=>{if(Wt)return;Wt=!0,U!==void 0&&(clearTimeout(U),U=void 0),v&&ve(),ae=!0,gt?.(),Be();let Z=ue=>{try{ue.down([[de]])}catch{}};Z(R),Z(k),Z(w),Z(x),E&&Z(E),G&&Z(G);try{l?.()}catch{}},We={dispose:rt,sent:w,failed:k,inFlight:x,errors:R};return v&&(We.buffered=E,We.flush=async()=>{ae||(await ve(),await Promise.all(V))}),G&&(We.paused=G),We}Tt();Re();function ct(t){return{describeKind:"producer",...t}}function Ji(t,e){let{parse:n,closeOnTeardown:r=!1,...o}=e??{};return W(s=>{let i=!0,a,u=()=>{let y=a;a=void 0,y?.()},c=y=>{i&&(i=!1,s.down([y]),u())},d=(y,b=y)=>{if(i)try{let v=y!==null&&typeof y=="object"&&"data"in y?y.data:y,T=n?n(v,b):v;s.emit(T)}catch(v){c([M,v])}},l=y=>{c([M,y])},f=()=>{c([_])};if(typeof t=="function"){try{if(a=t(d,l,f),typeof a!="function")throw new Error("fromWebSocket register contract violation: register must return cleanup callable")}catch(y){c([M,y])}return()=>{i=!1,u()}}let p=t,m=y=>d(y,y),h=y=>l(y),g=()=>f();return p.addEventListener("message",m),p.addEventListener("error",h),p.addEventListener("close",g),a=()=>{p.removeEventListener("message",m),p.removeEventListener("error",h),p.removeEventListener("close",g),r&&p.close()},()=>{i=!1,u()}},ct(o))}function pd(t,e){return cn(t,e)}function Yi(t,e){let{method:n="GET",headers:r,body:o,transform:s=v=>v.json(),timeoutNs:i=30*1e9,signal:a,completeAfterFetch:u=!1,refetchOnSubscribe:c=!1,...d}=e??{},l=N(0,{name:`${d.name??"http"}/fetchCount`}),f=N(0,{name:`${d.name??"http"}/lastUpdated`}),p=N(!1,{name:`${d.name??"http"}/fetched`}),m=0,h=o!==void 0?typeof o=="string"?o:JSON.stringify(o):void 0,g=v=>{let T=new AbortController,w=!0;if(a?.aborted)return w=!1,v.down([[M,a.reason??new Error("Aborted")]]),()=>{};a?.addEventListener("abort",()=>T.abort(a.reason),{once:!0});let k=setTimeout(()=>T.abort(new Error("Request timeout")),Math.ceil(i/1e6));return fetch(t,{method:n,headers:r,body:h,signal:T.signal}).then(async x=>{if(clearTimeout(k),!w)return;if(!x.ok)throw new Error(`HTTP ${x.status}: ${x.statusText}`);let R=await s(x);w&&(te(()=>{m+=1,l.down([[S,m]]),f.down([[S,pe()]]),p.down([[S,!0]]),v.emit(R)}),u&&v.down([[_]]))}).catch(x=>{clearTimeout(k),w&&(x&&x.name==="AbortError"||v.down([[M,x]]))}),()=>{w=!1,T.abort()}},y=W(v=>g({emit:T=>v.emit(T),down:T=>v.down(T)}),{...ct(d),resubscribable:c});return{...It(y),fetchCount:l,lastUpdated:f,fetched:p}}function fd(t,e,n){let{method:r="POST",headers:o={"Content-Type":"application/json"},serialize:s=m=>JSON.stringify(m),timeoutNs:i,batchFormat:a="json-array",batchSize:u,flushIntervalMs:c,retry:d,onTransportError:l}=n??{},f=async m=>{let h=i!==void 0?new AbortController:void 0,g;h&&i!==void 0&&(g=setTimeout(()=>h.abort(new Error("Request timeout")),Math.ceil(i/1e6)));try{let y=await fetch(e,{method:r,headers:o,body:m,signal:h?.signal}),b=async()=>{try{await y.arrayBuffer?.()}catch{}};if(!y.ok)throw await b(),new Error(`HTTP ${y.status}: ${y.statusText}`);await b()}finally{g!==void 0&&clearTimeout(g)}};return u!==void 0||c!==void 0?$e(t,{onTransportError:l,retry:d,batchSize:u,flushIntervalMs:c,sendBatch:async m=>{let h;a==="ndjson"?h=m.map(g=>{let y=s(g);return typeof y=="string"?y:new TextDecoder().decode(y)}).join(`
16
- `):h=JSON.stringify(m),await f(h)}}):$e(t,{onTransportError:l,retry:d,serialize:s,send:async m=>{await f(m)}})}function md(t){return Symbol.keyFor(t)??t.description??"message"}function Un(t,e){return typeof t=="string"?t:e(t)}function hd(t,e){let n=`event: ${t}
9
+ `,n}function vf(t){return JSON.parse(t)}function Tf(t,e){try{t.send(JSON.stringify(e))}catch{}}function ji(t,e){try{t(e)}catch{}}mr();var jo="graphReflyActor";function Vi(t){return e=>{let r=e.switchToHttp().getRequest()?.user;if(r!=null)return t?t(r):r}}function gc(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 yc(t){let e=t?.[jo];return e!=null?St(e):bt}var Nr=class{constructor(e){this.extractor=e}canActivate(e){let n=St(this.extractor(e)),r=e.switchToHttp().getRequest();return r!=null&&(r[jo]=n),!0}};function bc(t){return new Nr(t??Vi())}var Ar=require("@nestjs/common"),Vc=require("@nestjs/core");mr();_e();we();nn();ie();nn();Ne();function _t(t,e){if(e!=null&&e.length>0)return new Set(e);switch(t){case"standard":return new Set(["type","status","value","deps","meta","v"]);case"full":return null;default:return new Set(["type","deps"])}}function wf(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function kf(t){let e={};for(let[n,r]of Object.entries(t.meta))try{e[n]=r.cache}catch{}return e}function Er(t,e){let n=e==null,r=!n&&e!=null?[...e].filter(c=>c.startsWith("meta.")).map(c=>c.slice(5)):null,o=n||e.has("meta")||r!=null&&r.length>0,s="state",i=[];t instanceof Oe&&(s=wf(t),i=t._deps.map(c=>c.node.name??""));let a={type:s,deps:i};(n||e.has("status"))&&(a.status=t.status);let u=t instanceof Oe?t._guard:void 0;if(o){let c={...kf(t)};if(u!=null&&c.access===void 0&&(c.access=Tr(u)),r!=null&&r.length>0&&!e.has("meta")){let d={};for(let l of r)l in c&&(d[l]=c[l]);a.meta=d}else a.meta=c}if(t.name!=null&&(a.name=t.name),n||e.has("value")){t.status==="sentinel"&&(a.sentinel=!0);try{a.value=t.cache}catch{}}if((n||e.has("v"))&&t.v!=null){let c={id:t.v.id,version:t.v.version};"cid"in t.v&&(c.cid=t.v.cid,c.prev=t.v.prev),a.v=c}return(n||e.has("guard"))&&u!=null&&(a.guard=Tr(u)),(n||e.has("lastMutation"))&&t.lastMutation!=null&&(a.lastMutation=t.lastMutation),a}Ne();ne();ve();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}};bo();function Ki(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+=Ki(n.codePointAt(0));return e}function vc(t,e){if(e<=0)return"";let n=0,r="";for(let o of t){let s=Ki(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-=Ki(i.codePointAt(0))}return`${r}\u2026`}r+=o,n+=s}return r}var xf={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"},Rf={horizontal:"-",vertical:"|",cornerTL:"+",cornerTR:"+",cornerBL:"+",cornerBR:"+",tDown:"+",tUp:"+",tRight:"+",tLeft:"+",cross:"+",arrowRight:">",arrowDown:"v",arrowLeft:"<",arrowUp:"^",boxTL:"+",boxTR:"+",boxBL:"+",boxBR:"+",boxH:"-",boxV:"|"};function xc(t,e){let n=e.charset==="ascii"?Rf:xf,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)Nf(s,i,n,a);for(let a of t.boxes)Sf(s,i,n,a,e.labelOf(a.id));return s.map(a=>Of(a.join(""))).join(`
10
+ `)}function Sf(t,e,n,r,o){let{x:s,y:i,w:a,h:u}=r;if(a<2||u<2){u>0&&Tc(t,e,s,i,a,o);return}Vt(t,e,s,i,n.boxTL);for(let d=s+1;d<s+a-1;d+=1)Vt(t,e,d,i,n.boxH);Vt(t,e,s+a-1,i,n.boxTR);for(let d=i+1;d<i+u-1;d+=1){Vt(t,e,s,d,n.boxV);for(let l=s+1;l<s+a-1;l+=1)Rc(t,e,l,d," ","empty");Vt(t,e,s+a-1,d,n.boxV)}Vt(t,e,s,i+u-1,n.boxBL);for(let d=s+1;d<s+a-1;d+=1)Vt(t,e,d,i+u-1,n.boxH);Vt(t,e,s+a-1,i+u-1,n.boxBR);let c=i+Math.floor(u/2);Tc(t,e,s+1,c,a-2,o)}function Vt(t,e,n,r,o){Rc(t,e,n,r,o,o===" "?"empty":o==="\u2500"||o==="-"?"boxH":o==="\u2502"||o==="|"?"boxV":"boxCorner")}function Rc(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 Tc(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=n,a=o;for(let u of s){let c=Jn(u);if(c!==0){if(a<c)break;i>=0&&i<t[r].length&&(t[r][i]=u,e[r][i]="label",c===2&&i+1<t[r].length&&(t[r][i+1]="",e[r][i+1]="label")),i+=c,a-=c}}for(;a>0;)i>=0&&i<t[r].length&&(t[r][i]=" ",e[r][i]="empty"),i+=1,a-=1}function Nf(t,e,n,r){let o=r.points;if(o.length<2)return;for(let u=0;u+1<o.length;u+=1)Ef(t,e,n,o[u],o[u+1]);for(let u=1;u+1<o.length;u+=1){let c=o[u-1],d=o[u],l=o[u+1],f=_f(c,d,l,n);f&&kc(t,e,d.x,d.y,f,"edgeCorner")}let s=o[o.length-1],i=o[o.length-2],a=Mf(i,s,n);a&&kc(t,e,s.x,s.y,a,"arrow")}function Ef(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)wc(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)wc(t,e,s,u,n,"v")}}}function wc(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 kc(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label"||(i[n]=o,e[r][n]=s)}function _f(t,e,n,r){let o=t.y===e.y,s=e.y===n.y;if(o===s)return;if(o){let u=t.x<e.x,c=n.y>e.y;return u&&c?r.cornerTR:u&&!c?r.cornerBR:!u&&c?r.cornerTL:r.cornerBL}let i=t.y<e.y,a=n.x>e.x;return i&&a?r.cornerBL:i&&!a?r.cornerBR:!i&&a?r.cornerTL:r.cornerTR}function Mf(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 Of(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}function Ec(t){let e=Cf(t);Af(e),Lf(e),If(e),Pf(e,t);let n=Ff(e,t),{width:r,height:o}=Bf(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 Cf(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 Af(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 Lf(t){let e=Math.max(0,...Array.from(t.nodes.values(),s=>s.layer)),n=Array.from({length:e+1},()=>[]);for(let s of t.nodes.values())n[s.layer].push(s);let r=[],o=0;for(let s of t.hops){let i=t.nodes.get(s.fromId),a=t.nodes.get(s.toId),u=a.layer-i.layer;if(u<=0){i.out=i.out.filter(l=>l!==s),a.in=a.in.filter(l=>l!==s);continue}if(u===1){s.hopIndex=0,s.chainLen=1,r.push(s);continue}i.out=i.out.filter(l=>l!==s),a.in=a.in.filter(l=>l!==s);let c=i;for(let l=1;l<u;l+=1){let f=`__virt_${o++}__`,p={id:f,isVirtual:!0,layer:i.layer+l,order:0,x:0,y:0,w:0,h:1,in:[],out:[]};t.nodes.set(f,p),n[p.layer].push(p);let m={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:c.id,toId:f,hopIndex:l-1,chainLen:u};c.out.push(m),p.in.push(m),r.push(m),c=p}let d={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:c.id,toId:a.id,hopIndex:u-1,chainLen:u};c.out.push(d),a.in.push(d),r.push(d)}for(let s of n)for(let i=0;i<s.length;i+=1)s[i].order=i;t.layers=n,t.hops=r}function If(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)Sc(t,t.layers[r],"in"),Vo(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)Sc(t,t.layers[r],"out"),Vo(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=Nc(t,s[i],s[i+1],"in");[s[i],s[i+1]]=[s[i+1],s[i]],Vo(s),Nc(t,s[i],s[i+1],"in")<a?r=!0:([s[i],s[i+1]]=[s[i+1],s[i]],Vo(s))}}if(!r)break}}function Sc(t,e,n){let r=new Map;for(let o of e){let s=n==="in"?o.in:o.out;if(s.length===0){r.set(o.id,o.order);continue}let i=0,a=0;for(let u of s){let c=t.nodes.get(n==="in"?u.fromId:u.toId);c&&(i+=c.order,a+=1)}r.set(o.id,a===0?o.order:i/a)}e.sort((o,s)=>{let i=r.get(o.id),a=r.get(s.id);return i!==a?i-a:o.order-s.order})}function Vo(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function Nc(t,e,n,r){let o=r==="in"?e.in:e.out,s=r==="in"?n.in:n.out,i=0;for(let a of o)for(let u of s){let c=t.nodes.get(r==="in"?a.fromId:a.toId)?.order??0,d=t.nodes.get(r==="in"?u.fromId:u.toId)?.order??0;(e.order<n.order&&c>d||e.order>n.order&&c<d)&&(i+=1)}return i}function Pf(t,e){e.direction==="LR"?Df(t,e):Gf(t,e)}function Df(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}_c(t,e,"y")}function Gf(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}_c(t,e,"x")}function _c(t,e,n){let r=s=>n==="y"?s.h:s.w,o=e.nodeGap;for(let s=0;s<2;s+=1){let i=s===0?t.layers.slice(1):t.layers.slice(0,-1).reverse();for(let a of i){let u=new Map;for(let d of a){let l=s===0?d.in:d.out;if(l.length===0)continue;let f=[];for(let m of l){let h=t.nodes.get(s===0?m.fromId:m.toId);if(!h)continue;let g=n==="y"?h.y:h.x;f.push(g+Math.floor(r(h)/2))}if(f.length===0)continue;f.sort((m,h)=>m-h);let p=f[Math.floor(f.length/2)];u.set(d.id,p-Math.floor(r(d)/2))}let c=0;for(let d of a){let l=u.get(d.id),f=n==="y"?d.y:d.x,m=Math.max(l??f,c);n==="y"?d.y=m:d.x=m,c=m+r(d)+o}}}}function Ff(t,e){let n=new Map;for(let c of t.hops){let d=n.get(c.chainId);d?d.push(c):n.set(c.chainId,[c])}for(let c of n.values())c.sort((d,l)=>d.hopIndex-l.hopIndex);let r=e.direction==="LR",o=c=>r?c.x:c.y,s=c=>r?c.w:c.h,i=c=>r?c.y+Math.floor(c.h/2):c.x+Math.floor(c.w/2),a=new Map;for(let c=0;c+1<t.layers.length;c+=1){let d=t.layers[c],l=t.layers[c+1],f=0;for(let R of d)f=Math.max(f,o(R)+s(R));let p=Number.POSITIVE_INFINITY;for(let R of l)p=Math.min(p,o(R));let m=Number.isFinite(p)?p-1:f,h=Math.max(1,m-f+1),g=[];for(let R of d)for(let _ of R.out)g.push(_);g.sort((R,_)=>{let G=i(t.nodes.get(R.fromId)),L=i(t.nodes.get(_.fromId));if(G!==L)return G-L;let P=i(t.nodes.get(R.toId)),C=i(t.nodes.get(_.toId));return P-C});let y=[],b=new Map;for(let R of g){let _=i(t.nodes.get(R.fromId)),G=i(t.nodes.get(R.toId)),L=Math.min(_,G),P=Math.max(_,G),C=-1;for(let B=0;B<y.length;B+=1){let te=y[B],F=!0;for(let A of te)if(A.lo<=P&&L<=A.hi){F=!1;break}if(F){te.push({lo:L,hi:P}),C=B;break}}C<0&&(y.push([{lo:L,hi:P}]),C=y.length-1),b.set(R,C)}let v=y.length,T=h>=Math.max(3,v+2),w=T?f+1:f,k=T?m-1:m,x=Math.max(1,k-w+1);for(let R of g){let _=b.get(R),G;if(v<=1)G=w+Math.floor(x/2);else{let L=(x-1)/(v-1);G=w+Math.floor(_*L)}a.set(R,Math.max(f,Math.min(m,G)))}}let u=[];for(let[,c]of n){let d=[];for(let f=0;f<c.length;f+=1){let p=c[f],m=t.nodes.get(p.fromId),h=t.nodes.get(p.toId),g=a.get(p),y=m.isVirtual?o(m):o(m)+s(m),b=h.isVirtual?o(h):o(h)-1,v=i(m),T=i(h);f===0&&Ko(d,r,y,v),v!==T&&(Ko(d,r,g,v),Ko(d,r,g,T)),Ko(d,r,b,T)}let l=c[0];u.push({from:l.chainFrom,to:l.chainTo,points:$f(d)})}return u}function Ko(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function $f(t){let e=[];for(let n of t){let r=e[e.length-1];(!r||r.x!==n.x||r.y!==n.y)&&e.push(n)}return e}function Bf(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 jf=24,Vf=4,Kf=1,Hf=3;function Mc(t,e){let n=Wf(e.direction),r=Math.max(3,e.maxLabelWidth??jf),o=e.asciiCharset??"unicode",s=Object.keys(t.nodes).sort(),i=new Set(s),a=t.edges.filter(p=>i.has(p.from)&&i.has(p.to)),u=new Map,c=new Map;for(let p of s){let m=vc(p,r);u.set(p,m),c.set(p,Jn(m)+4)}let d=Ec({nodes:s,edges:a,widthCells:p=>c.get(p)??3,heightCells:()=>Hf,layerGap:Vf,nodeGap:Kf,direction:n}),l=xc(d,{charset:o,labelOf:p=>u.get(p)??p}),f=e.logger;return f&&f(l),l}function Wf(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 _r(t,e,n,r={}){let o=e in t.nodes,s=n in t.nodes;if(!o)return Ho(e,n,"no-such-from");if(!s)return Ho(e,n,"no-such-to");let i=r.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===n){if(r.findCycle===!0){let c=qf(t,e,r);if(c!=null)return c}let u=Wo(e,t.nodes[e],0,r);return qo(e,n,[u])}if(i===0)return Ho(e,n,"no-path");let a=Oc(t,e,n,i);return a.found?qo(e,n,Cc(t,a.pathOrder,r)):Ho(e,n,a.truncated?"max-depth-exceeded":"no-path")}function Oc(t,e,n,r){let o=new Map,s=[{path:n,depth:0}],i=new Set([n]),a=0,u=!1;for(;a<s.length;){let l=s[a++];if(l.path===e)break;if(r!=null&&l.depth>=r){let h=t.nodes[l.path];h?.deps&&h.deps.length>0&&(u=!0);continue}let f=t.nodes[l.path];if(f==null)continue;let p=f.deps??[],m=new Map;for(let h=0;h<p.length;h++){let g=p[h];if(!g)continue;let y=m.get(g);y==null&&(y=[],m.set(g,y)),y.push(h)}for(let[h,g]of m)i.has(h)||(i.add(h),o.set(h,{from:l.path,depIndices:g}),s.push({path:h,depth:l.depth+1}))}if(!o.has(e))return{found:!1,pathOrder:[],truncated:u};let c=[{path:e}],d=e;for(;d!==n;){let l=o.get(d);if(l==null)return{found:!1,pathOrder:[],truncated:!1};c[c.length-1].depIndices=l.depIndices,c.push({path:l.from}),d=l.from}return{found:!0,pathOrder:c,truncated:!1}}function qf(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=Wo(e,r,0,n);a.dep_index=s[0];let u=Wo(e,r,1,n);return qo(e,e,[a,u])}let i=null;for(let a=0;a<o.length;a++){let u=o[a];if(!u||u===e)continue;let c=Oc(t,u,e,n.maxDepth);c.found&&(i==null||c.pathOrder.length<i.pathOrder.length)&&(i=c,i={found:!0,pathOrder:[{path:e,depIndices:[a]},...c.pathOrder],truncated:!1})}return i==null?null:qo(e,e,Cc(t,i.pathOrder,n))}function Cc(t,e,n){return e.map((r,o)=>{let s=t.nodes[r.path],i=Wo(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 Wo(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 qo(t,e,n){return Ac(t,e,!0,"ok",n)}function Ho(t,e,n){return Ac(t,e,!1,n,[])}function Ac(t,e,n,r,o){let s=Uf(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 Uf(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: ${zf(i.value)}`),i.annotation!=null&&s.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let c=i.lastMutation.actor;s.push(` actor: ${c.type}${c.id?`:${c.id}`:""}`)}}return s.join(`
11
+ `)}function zf(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)}}Ne();var De={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},Uo=Symbol.for("sizeof");function Mr(t){let e=new WeakSet,n=new WeakSet,r=[t],o=0;for(;r.length>0;){let s=r.pop();o+=Jf(s,e,n,r)}return o}function Jf(t,e,n,r){if(t==null)return 0;switch(typeof t){case"number":return De.number;case"boolean":return De.boolean;case"string":return De.string+t.length*2;case"bigint":return De.bigint+Yf(t);case"symbol":return De.symbol;case"function":return e.has(t)?0:(e.add(t),De.function);case"undefined":return 0}let s=t;if(e.has(s))return 0;e.add(s);let i=s[Uo];if(typeof i=="function")try{let c=i.call(s);if(typeof c=="number"&&Number.isFinite(c))return c}catch{}if(s instanceof Date)return De.date;if(s instanceof RegExp)return De.regexp+s.source.length*2;if(s instanceof Error){let c=s.message?s.message.length*2:0,d=s.stack?s.stack.length*2:0;return De.error+c+d}if(typeof URL<"u"&&s instanceof URL)return De.url+s.href.length*2;if(typeof Promise<"u"&&s instanceof Promise)return De.promise;if(s instanceof WeakMap)return De.weakmap;if(s instanceof WeakSet)return De.weakset;if(s instanceof Map){let c=De.map;for(let[d,l]of s)c+=De.mapEntry,r.push(d),r.push(l);return c}if(s instanceof Set){let c=De.set;for(let d of s)c+=De.setEntry,r.push(d);return c}if(Array.isArray(s)){let c=De.array+s.length*8;for(let d of s)r.push(d);return c}if(s instanceof ArrayBuffer)return n.has(s)?0:(n.add(s),s.byteLength);if(ArrayBuffer.isView(s)){let c=s;return n.has(c.buffer)?48:(n.add(c.buffer),c.buffer.byteLength+48)}let a=De.object,u=Object.keys(s);for(let c of u){a+=De.string+c.length*2;try{r.push(s[c])}catch{}}return a}function Yf(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[f,p]of o)i.set(f,p);let a=[];for(let[f,p]of Object.entries(r.nodes)){let m=i.get(f),h=m instanceof Oe?m:null,g=h?Mr(h.cache):0,y=h?h._sinkCount:0,b=p.deps?.length??0,v=p.type==="effect"&&y===0,T=y===0?p.type==="effect"?"orphan-effect":p.type==="derived"?"idle-derived":p.type==="producer"?"idle-producer":null:null;a.push({path:f,type:p.type,status:p.status??"unknown",valueSizeBytes:g,subscriberCount:y,depCount:b,isOrphanEffect:v,orphanKind:T})}let u=a.reduce((f,p)=>f+p.valueSizeBytes,0),c=(f,p)=>[...a].sort(p??((m,h)=>h[f]-m[f])).slice(0,n),d=a.filter(f=>f.orphanKind!=null),l=a.filter(f=>f.isOrphanEffect);return{nodeCount:a.length,edgeCount:r.edges.length,subgraphCount:r.subgraphs.length,nodes:a,totalValueSizeBytes:u,hotspots:{byValueSize:c("valueSizeBytes"),bySubscriberCount:c("subscriberCount"),byDepCount:c("depCount")},orphans:d,orphanEffects:l}}var Ie="::",He="__meta__",lt=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 Qf(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 Ic(t){if(t.version!==lt)throw new Error(`unsupported snapshot version ${String(t.version)} (expected ${lt})`);for(let e of["name","nodes","edges","subgraphs"])if(!(e in t))throw new Error(`snapshot missing required key "${e}"`);if(typeof t.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof t.nodes!="object"||t.nodes===null||Array.isArray(t.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(t.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(t.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function Xf(t,e){let n=new WeakMap,r=(o,s)=>{if(Object.is(o,s))return!0;if(o==null||s==null||typeof o!="object"||typeof s!="object")return!1;let i=n.get(o);if(i==null&&(i=new WeakSet,n.set(o,i)),i.has(s))return!0;i.add(s);let a=o.constructor,u=s.constructor;if(a!==u)return!1;if(o instanceof Date)return o.getTime()===s.getTime();if(o instanceof RegExp)return o.source===s.source&&o.flags===s.flags;if(Array.isArray(o)){let f=s;if(o.length!==f.length)return!1;for(let p=0;p<o.length;p++)if(!r(o[p],f[p]))return!1;return!0}if(o instanceof Map){let f=s;if(o.size!==f.size)return!1;for(let[p,m]of o)if(!f.has(p)||!r(m,f.get(p)))return!1;return!0}if(o instanceof Set){let f=s;if(o.size!==f.size)return!1;for(let p of o){let m=!1;for(let h of f)if(r(p,h)){m=!0;break}if(!m)return!1}return!0}if(ArrayBuffer.isView(o)){let f=o,p=s;if(f.length!==p.length)return!1;for(let m=0;m<f.length;m++)if(f[m]!==p[m])return!1;return!0}let c=Object.keys(o),d=Object.keys(s);if(c.length!==d.length)return!1;let l=new Set(d);for(let f of c)if(!l.has(f)||!r(o[f],s[f]))return!1;return!0};return r(t,e)}function Wi(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(Wi);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=Wi(e[o]);return r}function Zf(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function em(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function tm(t){return t==="TD"?"down":t==="BT"?"up":t==="RL"?"left":"right"}function Dc(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 nm(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(Wi(i),null,e.indent??2);return e.logger?.(a),a}function rm(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}): ${Jo(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 Fc(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}["${Zf(i)}"]`)}for(let[i,a]of Dc(t)){let u=o.get(i),c=o.get(a);!u||!c||s.push(` ${u} --> ${c}`)}return s.join(`
14
+ `)}function om(t,e){let n=Fc(t,e);return Yo(n)}function Yo(t,e){let n=e?.theme??"default",r=e?.autoSync??!0,s=JSON.stringify({code:t,mermaid:{theme:n},autoSync:r}),i=new TextEncoder().encode(s),a="";for(let c=0;c<i.length;c++)a+=String.fromCharCode(i[c]);return`https://mermaid.live/edit#base64:${globalThis.btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`}function sm(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: ${tm(n)}`];for(let i of r){let a=o.get(i);s.push(`${a}: "${em(i)}"`)}for(let[i,a]of Dc(t)){let u=o.get(i),c=o.get(a);!u||!c||s.push(`${u} -> ${c}`)}return s.join(`
15
+ `)}function im(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function zo(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+=im(r)}return e+="$",new RegExp(e)}var am={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"},um={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function Jo(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 cm(t){return t==="none"?um:t==="ansi"||t==null?am:{data:t.data??"",dirty:t.dirty??"",resolved:t.resolved??"",invalidate:t.invalidate??"",pause:t.pause??"",resume:t.resume??"",complete:t.complete??"",error:t.error??"",teardown:t.teardown??"",derived:t.derived??"",path:t.path??"",reset:t.reset??""}}function Pc(t){if(t==null)return{};let e=t.detail;return e==="full"?{...t,structured:t.structured??!0,timeline:t.timeline??!0,causal:t.causal??!0,derived:t.derived??!0}:e==="minimal"?{...t,structured:t.structured??!0}:t.format==="stage-log"?{...t,structured:t.structured??!0,timeline:t.timeline??!0}:t}function dm(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 Hi(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(Ie))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${Ie}' (path separator)`);if(t===He)throw new Error(`Graph "${e}": ${n} name "${He}" is reserved for meta companion paths`);dm(t,e,n)}function lm(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(Ie);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function pm(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 $c(t){for(let e of t._mounts.values())$c(e);for(let e of t._nodes.values())try{e.down([[de]],{internal:!0})}catch{}}var q=class t{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_topology;_topologyEmitters=new Set;constructor(e,n){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(Ie))throw new Error(`Graph name must not contain '${Ie}' (got "${e}")`);if(e===He)throw new Error(`Graph name "${He}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??Pe,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=W(e=>{let n=r=>{e.emit(r)};return this._topologyEmitters.add(n),()=>{this._topologyEmitters.delete(n)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let n of this._topologyEmitters)n(e)}add(e,n){let r=e.name,o=n?.name??r;if(o==null||o==="")throw new Error(`Graph "${this.name}": graph.add requires a non-empty name \u2014 pass via opts.name or set it on the node (e.g. state(0, { name: "x" }))`);let s=o,i=n?.annotation;if(Hi(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:V()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof Oe&&n._applyVersioning(e)}remove(e){Hi(e,this.name,"remove");let n=this._mounts.get(e);if(n){let s={kind:"mount",nodes:[],mounts:[]},i=[];n._collectObserveTargets("",i);for(let[a,u]of i)a.includes(`${Ie}${He}${Ie}`)||s.nodes.push(a);return s.nodes.sort(),s.mounts.push(e),s.mounts.push(...n._collectSubgraphs(`${e}${Ie}`)),this._mounts.delete(e),n._parent=void 0,$c(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=zo(e);return i=>s.test(i)})(),r={kind:"mount",nodes:[],mounts:[]},o=[...this._nodes.keys(),...this._mounts.keys()].filter(s=>n(s));for(let s of o){let i=this.remove(s);r.nodes.push(...i.nodes),r.mounts.push(...i.mounts)}return r.nodes.sort(),r.mounts.sort(),r}[Symbol.iterator](){let e=[...this._nodes.keys()].sort(),n=this._nodes,r=0;return{[Symbol.iterator](){return this},next(){if(r>=e.length)return{value:void 0,done:!0};let o=e[r++];return{value:[o,n.get(o)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(Ie))return this.resolve(e);let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return n}get(e){return this.node(e).cache}set(e,n,r){let o=r?.internal===!0;this.node(e).down([[S,n]],{actor:r?.actor,internal:o,delivery:"write"})}setAll(e,n){let r=Symbol.iterator in e?e:Object.entries(e);X(()=>{for(let[o,s]of r)this.set(o,s,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[ze]],{actor:n?.actor,internal:r,delivery:"write"})}error(e,n,r){let o=r?.internal===!0;this.node(e).down([[O,n]],{actor:r?.actor,internal:o,delivery:"write"})}complete(e,n){let r=n?.internal===!0;this.node(e).down([[M]],{actor:n?.actor,internal:r,delivery:"write"})}edges(e){let n=e?.recursive===!0,r=new Map;if(!n){for(let[u,c]of this._nodes)r.set(c,u);let a=[];for(let[u,c]of this._nodes)if(c instanceof Oe)for(let d of c._deps){let l=r.get(d.node);l!=null&&a.push([l,u])}return a.sort((u,c)=>u[0]<c[0]?-1:u[0]>c[0]?1:u[1]<c[1]?-1:u[1]>c[1]?1:0),a}let o=[];this._collectObserveTargets("",o);let s=new Map;for(let[a,u]of o)s.set(u,a);let i=[];for(let[a,u]of o)if(u instanceof Oe)for(let c of u._deps){let d=s.get(c.node);d!=null&&i.push([d,a])}return i.sort((a,u)=>a[0]<u[0]?-1:a[0]>u[0]?1:a[1]<u[1]?-1:a[1]>u[1]?1:0),i}mount(e,n){if(Hi(e,this.name,"mount"),this._nodes.has(e))throw new Error(`Graph "${this.name}": cannot mount at "${e}" \u2014 node with that name exists`);if(this._mounts.has(e))throw new Error(`Graph "${this.name}": mount "${e}" already exists`);if(n===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(n._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${n._parent.name}"`);for(let r=this;r!=null;r=r._parent)if(r===n)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,n),n._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),n}resolve(e){let n=lm(e,this.name);return this._resolveFromSegments(n)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let n=e;if(n[0]===this.name&&(n=n.slice(1),n.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let r=n[0],o=n.slice(1);if(o.length===0){let a=this._nodes.get(r);if(a)return a;throw this._mounts.has(r)?new Error(`Graph "${this.name}": path ends at subgraph "${r}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${r}"`)}let s=this._nodes.get(r);if(s&&o.length>0&&o[0]===He)return this._resolveMetaChainFromNode(s,o,n.join(Ie));let i=this._mounts.get(r);if(!i)throw this._nodes.has(r)?new Error(`Graph "${this.name}": "${r}" is a node; trailing path "${o.join(Ie)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(o.join(Ie))}_resolveMetaChainFromNode(e,n,r){let o=e,s=0,i=[...n];for(;s<i.length;){if(i[s]!==He)throw new Error(`Graph "${this.name}": expected ${He} segment in meta path "${r}"`);if(s+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${He} in "${r}"`);let a=i[s+1],u=o.meta[a];if(!u)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${r}"`);o=u,s+=2}return o}signal(e,n){if(n?.internal!==!0){for(let o of e)if(this.config.messageTier(o[0])===3)throw new Error(`Graph "${this.name}": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). For per-node value writes, use Graph.set or graph.node(name).down(...).`)}let r=[];if(this._signalDeliver(e,n??{},new Set,r),r.length>0)throw r[0]}_signalDeliver(e,n,r,o){for(let u of this._mounts.values())u._signalDeliver(e,n,r,o);let i=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},a=pm(e,this.config);for(let u of[...this._nodes.keys()].sort()){let c=this._nodes.get(u);if(!r.has(c)){r.add(c);try{c.down(e,i)}catch(d){if(d instanceof nt)throw d;o.push(d)}a.length!==0&&this._signalMetaSubtree(c,a,r,i,o)}}}_signalMetaSubtree(e,n,r,o,s){for(let i of Object.keys(e.meta).sort()){let a=e.meta[i];if(!r.has(a)){r.add(a);try{a.down(n,o)}catch(u){if(u instanceof nt)throw u;s.push(u)}this._signalMetaSubtree(a,n,r,o,s)}}}describe(e){if(e?.reactive===!0)return this._describeReactive(e);let n=e?.actor,r=e?.filter,o=_t(e?.detail,e?.fields),s=e?.format==="spec",i=s?_t("minimal"):o,a=[];this._collectObserveTargets("",a);let u=new Map;for(let[k,x]of a)u.set(x,k);let c=[];{let k=a.map(([,_])=>_),x=new Set(u.values()),R=0;for(;k.length>0;){let _=k.shift();if(_ instanceof Oe)for(let G of _._deps){let L=G.node;if(u.has(L))continue;let P=L.name??"",C=P;if(!C||x.has(C))if(P){let B=2;for(;x.has(`${P}#${B}`);)B++;C=`${P}#${B}`}else for(C=`__internal__/${R++}`;x.has(C);)C=`__internal__/${R++}`;u.set(L,C),x.add(C),c.push([C,L]),k.push(L)}}}let d=[...a,...c],l={};for(let[k,x]of d){if(n!=null&&!x.allowsObserve(n))continue;let R=Er(x,i),_=x instanceof Oe?x._deps.map(C=>u.get(C.node)??C.node.name??""):[],{name:G,...L}=R,P={...L,deps:_};if(!s){let C=this._annotations.get(k);C!=null&&(P.annotation=C)}if(r!=null)if(typeof r=="function"){let C=r;if(!(C.length>=2?C(k,P):C(P)))continue}else{let C=!0;for(let[B,te]of Object.entries(r)){let F=B==="deps_includes"?"depsIncludes":B==="meta_has"?"metaHas":B;if(F==="depsIncludes"){if(!P.deps.includes(String(te))){C=!1;break}continue}if(F==="metaHas"){if(!Object.hasOwn(P.meta??{},String(te))){C=!1;break}continue}if(P[F]!==te){C=!1;break}}if(!C)continue}l[k]=P}let f=new Set(Object.keys(l)),p=[];for(let[k,x]of d)if(x instanceof Oe)for(let R of x._deps){let _=u.get(R.node);_!=null&&p.push([_,k])}p.sort((k,x)=>k[0]<x[0]?-1:k[0]>x[0]?1:k[1]<x[1]?-1:k[1]>x[1]?1:0);let m=p.map(([k,x])=>({from:k,to:x}));(n!=null||r!=null)&&(m=m.filter(k=>f.has(k.from)&&f.has(k.to)));let h=this._collectSubgraphs(""),g=n!=null||r!=null?h.filter(k=>{let x=`${k}${Ie}`;return[...f].some(R=>R===k||R.startsWith(x))}):h,y=this,b=e,v={name:this.name,nodes:l,edges:m,subgraphs:g,expand(k){let x={...b,format:void 0};return Array.isArray(k)?(x.fields=k,x.detail=void 0):(x.detail=k,x.fields=void 0),y.describe(x)}},T=e??{},w=T.format;return w==="json"?nm(v,T):w==="pretty"?rm(v,T):w==="mermaid"?Fc(v,T):w==="mermaid-url"?om(v,T):w==="d2"?sm(v,T):w==="ascii"?Mc(v,T):v}_collectSubgraphs(e){let n=[];for(let r of[...this._mounts.keys()].sort()){let o=e===""?r:`${e}${r}`;n.push(o),n.push(...this._mounts.get(r)._collectSubgraphs(`${o}${Ie}`))}return n}resourceProfile(e){return 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 _r(o,e,n,{...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{},annotations:s,lastMutations:i})}_describeReactive(e){let n={...e,reactive:!1},r=e.reactiveName??"describe",o=0,s=N(o,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,u=!1,c=()=>{a||u||(a=!0,yr(()=>{a=!1,!u&&(o+=1,s.emit(o))}))},d=i.onEvent(g=>{let y=g.type;y!=="data"&&y!=="error"&&y!=="complete"&&y!=="teardown"||c()}),l=[],f=new WeakSet,p=g=>{if(f.has(g)||u)return;f.add(g);let y=g.topology.subscribe(b=>{for(let v of b){if(v[0]!==S)continue;let T=v[1];if(c(),T.kind==="added"&&T.nodeKind==="mount"){let w=g._mounts.get(T.name);w!=null&&p(w)}}});l.push(y);for(let b of g._mounts.keys()){let v=g._mounts.get(b);v!=null&&p(v)}};p(this);let m;try{m=E([s],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(g,y)=>g===y})}catch(g){d();for(let y of l)y();throw i.dispose(),g}let h=re(m);return{node:m,dispose(){u=!0,d();for(let g of l)g();l.length=0,i.dispose(),h()}}}_explainReactive(e,n,r){let o=0,s=N(o,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,u=!1,c=i.onEvent(p=>{let m=p.type;m!=="data"&&m!=="error"&&m!=="complete"&&m!=="teardown"||a||u||(a=!0,yr(()=>{a=!1,!u&&(o+=1,s.emit(o))}))}),d={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},l;try{l=E([s],()=>this._explainStatic(e,n,d),{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:e,to:n},equals:(p,m)=>p.found===m.found&&p.reason===m.reason&&p.steps.length===m.steps.length&&fm(p.steps,m.steps)})}catch(p){throw c(),i.dispose(),p}let f=re(l);return{node:l,dispose(){u=!0,c(),i.dispose(),f()}}}_pathsMatching(e){let n=zo(e),r=[];return this._collectObserveTargets("",r),r.map(([o])=>o).filter(o=>n.test(o))}_collectObserveTargets(e,n){for(let r of[...this._mounts.keys()].sort()){let o=e===""?r:`${e}${Ie}${r}`;this._mounts.get(r)._collectObserveTargets(o,n)}for(let r of[...this._nodes.keys()].sort()){let o=this._nodes.get(r),s=e===""?r:`${e}${Ie}${r}`;n.push([s,o]),this._appendMetaObserveTargets(s,o,n)}}_appendMetaObserveTargets(e,n,r){for(let o of Object.keys(n.meta).sort()){let s=n.meta[o],i=`${e}${Ie}${He}${Ie}${o}`;r.push([i,s]),this._appendMetaObserveTargets(i,s,r)}}observe(e,n){let r=typeof e=="string",s=Pc(r?n:e),i=s.structured===!0||s.timeline===!0||s.causal===!0||s.derived===!0||s.detail==="minimal"||s.detail==="full"||s.format!=null,a=s.actor;if(r){let d=e,l=this.resolve(d);if(a!=null&&!l.allowsObserve(a))throw new nt({actor:a,action:"observe",nodeName:d});return i?this._buildStructuredObserver([[d,l]],s,"one"):{subscribe(f){return l.subscribe(f)},up(f){try{l.up?.(f)}catch(p){if(p instanceof nt)return;throw p}}}}let u=[];this._collectObserveTargets("",u),u.sort((d,l)=>d[0]<l[0]?-1:d[0]>l[0]?1:0);let c=a==null?u:u.filter(([,d])=>d.allowsObserve(a));return i?this._buildStructuredObserver(c,s,"all"):{subscribe:d=>{let l=c.map(([f,p])=>p.subscribe(m=>{d(f,m)}));return()=>{for(let f of l)f()}},up:(d,l)=>{try{this.resolve(d).up?.(l)}catch(f){if(f instanceof nt)return;throw f}}}}_buildStructuredObserver(e,n,r){let o=r==="one"?e[0]?.[0]:void 0,s=i=>{if(r==="one"&&o!=null){let d=this.resolve(o);return this._buildStructuredObserver([[o,d]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((d,l)=>d[0]<l[0]?-1:d[0]>l[0]?1:0);let u=i.actor,c=u==null?a:a.filter(([,d])=>d.allowsObserve(u));return this._buildStructuredObserver(c,i,"all")};return this._createObserveResult(e,n,s)}_createObserveResult(e,n,r){let o=n.timeline===!0,s=n.causal===!0,i=n.derived===!0,a=n.detail==="minimal",u=this.config.inspectorEnabled,c=(s||i)&&u,d=n.maxEvents,l=d!=null&&d>0?new ln(d):null,f=[],p=new Set,m={},h=new Set,g=0,y=0,b=0,v=0,T=0,w=0,k=!1,x=!1,R=0,_=new Map,G=new Map,L=new Map,P=j=>{l?l.push(j):f.push(j);for(let U of p)U(j)},C=()=>o?{timestamp_ns:V(),in_batch:Zt(),batch_id:R}:{},B=(j,U)=>{if(!(!c||!(j instanceof Oe)))return j._setInspectorHook(he=>{if(he.kind==="dep_message")_.set(j,he.depIndex);else if(he.kind==="run"){let ue=he.batchData.map((Z,Se)=>Z!=null&&Z.length>0?Z.at(-1):he.prevData[Se]);G.set(j,ue);let oe=he.batchData.map(Z=>Z!=null?[...Z]:void 0);L.set(j,oe),i&&P({type:"derived",path:U,dep_values:ue,dep_batches:oe,...C()})}})},te=j=>{let U=_.get(j),he=G.get(j);if(!s||he==null)return{};let oe=(U!=null&&U>=0&&j instanceof Oe?j._deps[U]:void 0)?.node,Z=oe?.v,Se=L.get(j);return{trigger_dep_index:U,trigger_dep_name:oe?.name,...Z!=null?{trigger_version:{id:Z.id,version:Z.version}}:{},dep_values:[...he],...Se!=null?{dep_batches:Se}:{}}},F=[],A=[];for(let[j,U]of e){let he=B(U,j);he&&F.push(he),A.push(U.subscribe(ue=>{R++;for(let oe of ue){let Z=oe[0],Se=C();if(Z===S){m[j]=oe[1];let Q=U instanceof Oe?U.lastMutation?.actor??bt:bt;P({type:"data",path:j,data:oe[1],actor:Q,...Se,...te(U)})}else if(a)Z===ee?g++:Z===$?y++:Z===ze?b++:Z===Ge?v++:Z===$e?T++:Z===de?w++:Z===M&&!h.has(j)?k=!0:Z===O&&(x=!0,h.add(j));else if(Z===ee)g++,P({type:"dirty",path:j,...Se});else if(Z===$)y++,P({type:"resolved",path:j,...Se,...te(U)});else if(Z===ze)b++,P({type:"invalidate",path:j,...Se});else if(Z===Ge)v++,P({type:"pause",path:j,lockId:oe[1],...Se});else if(Z===$e)T++,P({type:"resume",path:j,lockId:oe[1],...Se});else if(Z===M)h.has(j)||(k=!0),P({type:"complete",path:j,...Se});else if(Z===O){x=!0,h.add(j);let Q=U instanceof Oe?U.lastMutation?.actor??bt:bt;P({type:"error",path:j,data:oe[1],actor:Q,...Se})}else Z===de&&(w++,P({type:"teardown",path:j,...Se}))}}))}let D=!1,I=()=>{if(!D){D=!0;for(let j of A)j();for(let j of F)j();for(let j of H)j({value:void 0,done:!0});H.length=0}},J=[],H=[];p.add(j=>{let U=H.shift();U?U({value:j,done:!1}):J.push(j)});let ae={get values(){return m},get dirtyCount(){return g},get resolvedCount(){return y},get invalidateCount(){return b},get pauseCount(){return v},get resumeCount(){return T},get teardownCount(){return w},get events(){return l?l.toArray():[...f]},get anyCompletedCleanly(){return k},get anyErrored(){return x},get completedWithoutErrors(){return k&&!x},onEvent(j){return p.add(j),()=>p.delete(j)},dispose:I,expand(j){I();let U={...n};return typeof j=="string"?U.detail=j:Object.assign(U,j),r(Pc(U))},[Symbol.asyncIterator](){return{next(){return J.length>0?Promise.resolve({value:J.shift(),done:!1}):D?Promise.resolve({value:void 0,done:!0}):new Promise(j=>H.push(j))},return(){return I(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(ae,n),ae}_attachFormatLogger(e,n){let r=n.format;if(r==null)return;let o=n.logger??(m=>console.log(m)),s=n.includeTypes?new Set(n.includeTypes):null,i=n.excludeTypes?new Set(n.excludeTypes):null,a=s==null&&i==null?()=>!0:m=>(s==null||s.has(m))&&(i==null||!i.has(m)),u=cm(n.theme),c=r==="stage-log"?V():0,d=m=>m==null?"":n.stageLabels?.[m]??m,l=(m,h)=>m.length>h?`${m.slice(0,h-1)}\u2026`:m,f=m=>m.type==="data"||m.type==="error"?l(Jo(m.data),120):"",p=m=>{if(r==="stage-log"){let x=(V()-c)/1e9,R=d(m.path).padEnd(9);if(m.type==="data"){let _=f(m);return`[${x.toFixed(3)}s] ${R} \u2190${_?` ${_}`:""}`}if(m.type==="error"){let _=f(m);return`[${x.toFixed(3)}s] ${R} \u2717${_?` ${_}`:""}`}return m.type==="complete"?`[${x.toFixed(3)}s] ${R} \u25A0 complete`:`[${x.toFixed(3)}s] ${R} ${m.type}`}if(r==="json")try{return JSON.stringify(m)}catch{return JSON.stringify({type:m.type,path:m.path,data:"[unserializable]"})}let h=u[m.type]??"",g=m.path?`${u.path}${m.path}${u.reset} `:"",y=m.type==="data"||m.type==="error",b=m.type==="pause"||m.type==="resume",v=y?` ${Jo(m.data)}`:b?` ${Jo(m.lockId)}`:"",T=m.type==="data"||m.type==="resolved"||m.type==="derived"?m:void 0,w=T?.trigger_dep_name!=null?` <- ${T.trigger_dep_name}`:T?.trigger_dep_index!=null?` <- #${T.trigger_dep_index}`:"",k=m.in_batch?" [batch]":"";return`${g}${h}${m.type.toUpperCase()}${u.reset}${v}${w}${k}`};e.onEvent(m=>{a(m.type)&&o(p(m),m)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){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}_destroyClearOnly(){for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0}snapshot(e){let{expand:n,...r}=this.describe({detail:"full"}),o={};for(let a of Object.keys(r.nodes).sort()){let{lastMutation:u,guard:c,...d}=r.nodes[a];o[a]=d}let s=[...r.subgraphs].sort(),i={...r,version:1,nodes:o,subgraphs:s};if(e?.format==null)return i;if(e.format==="json-string")return JSON.stringify(i);if(e.format==="bytes"){if(e.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let a=this.config.lookupCodec(e.codec);if(a==null)throw new Error(`snapshot: codec "${e.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return lr(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??Pe,{codec:o,codecVersion:s,payload:i}=pr(e,r);return o.decode(i,s)}restore(e,n){if(Ic(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=>zo(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){Ic(e);let r=typeof n=="function"?n:n?.build,o=typeof n=="function"?void 0:n?.factories,s=new t(e.name);if(r)return r(s),s.restore(e),s;for(let p of[...e.subgraphs].sort((m,h)=>{let g=m.split(Ie).length,y=h.split(Ie).length;return g!==y?g-y:m<h?-1:m>h?1:0})){let m=p.split(Ie),h=s;for(let g of m)h._mounts.has(g)||h.mount(g,new t(g)),h=h._mounts.get(g)}let i=o?Object.entries(o).map(([p,m])=>({re:zo(p),factory:m})):[],a=p=>{for(let m of i)if(m.re.test(p))return m.factory},u=p=>{let m=p.split(Ie),h=m.pop();if(h==null||h.length===0)throw new Error(`invalid snapshot path "${p}"`);let g=s;for(let y of m){let b=g._mounts.get(y);if(!b)throw new Error(`unknown mount "${y}" in path "${p}"`);g=b}return[g,h]},c=Object.entries(e.nodes).filter(([p])=>!p.includes(`${Ie}${He}${Ie}`)).sort((p,m)=>p[0]<m[0]?-1:p[0]>m[0]?1:0),d=new Map(c),l=new Map,f=!0;for(;d.size>0&&f;){f=!1;for(let[p,m]of[...d.entries()]){let h=m?.deps??[];if(!h.every(w=>l.has(w)))continue;let[g,y]=u(p),b={...m?.meta??{}},v=a(p),T;if(m?.type==="state")T=N(m.value,{meta:b});else{if(v==null)continue;T=v(y,{path:p,type:m.type,value:m.value,meta:b,deps:h,resolvedDeps:h.map(w=>l.get(w))})}g.add(T,{name:y}),l.set(p,T),d.delete(p),f=!0}}if(d.size>0){let p=[...d.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${p}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return s.restore(e),s}toJSON(){return this.snapshot()}attachStorage(e,n={}){let r=e.map(c=>({tier:c,debounceMs:Math.max(0,c.debounceMs??0),compactEvery:Math.max(1,c.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));n.autoRestore===!0&&this._cascadeRestore(e,n.onError);let o=(c,d)=>{if(c.disposed)return;let l=Qf(d.nodes);if(c.lastSnapshot!=null&&l!==""&&l===c.lastFingerprint)return;let f=c.seq+1,p=le(),g=c.lastSnapshot==null||f%c.compactEvery===0?{mode:"full",snapshot:d,seq:f,timestamp_ns:p,format_version:lt}:{mode:"diff",diff:Qo(c.lastSnapshot,d),seq:f,timestamp_ns:p,format_version:lt};if(c.tier.filter&&!c.tier.filter(this.name,g))return;let y;try{y=c.tier.save(this.name,g)}catch(b){n.onError?.(b,c.tier);return}if(y&&typeof y.then=="function"){let T=(c.savePending??Promise.resolve()).then(()=>y,()=>y).then(()=>{c.disposed||(c.seq=f,c.lastSnapshot=d,c.lastFingerprint=l)},w=>{n.onError?.(w,c.tier)});c.savePending=T.finally(()=>{c.savePending===T&&(c.savePending=void 0)})}else c.seq=f,c.lastSnapshot=d,c.lastFingerprint=l},s=(c,d)=>{try{o(c,d)}catch(l){n.onError?.(l,c.tier)}},i=(c,d)=>{if(!d.some(m=>{let h=this.config.messageTier(m[0]);return h>=3&&h<5}))return;if(n.filter){let m=this.tryResolve(c);if(m==null)return;let h=Er(m,_t("standard"));if(!n.filter(c,h))return}let f,p=()=>(f==null&&(f=this.snapshot()),f);for(let m of r)m.disposed||(m.debounceMs===0?s(m,p()):(m.timer==null&&(m.timer=new Ce),m.timer.start(m.debounceMs,()=>{m.disposed||s(m,this.snapshot())})))},a;if(n.paths!=null){let d=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(l=>{let f=this.tryResolve(l);return f==null?()=>{}:f.subscribe(p=>i(l,p))});a=()=>{for(let l of d)l()}}else a=this.observe().subscribe((c,d)=>i(c,d));let u=()=>{a();for(let c of r)c.disposed=!0,c.timer?.cancel();this._storageDisposers.delete(u)};return this._storageDisposers.add(u),{dispose:u}}async _cascadeRestore(e,n){for(let r of e){let o;try{o=await r.load(this.name)}catch(i){n?.(i,r);continue}if(o==null||typeof o!="object"||Array.isArray(o))continue;let s=o;try{if(s.mode==="full"&&s.snapshot!=null)return this.restore(s.snapshot),!0;if(s.version===lt&&s.nodes!=null)return this.restore(s),!0}catch(i){n?.(i,r)}}return!1}static async fromStorage(e,n,r){for(let o of n){let s;try{s=await o.load(e)}catch(u){r?.onError?.(u,o);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let i=s,a=i.mode==="full"&&i.snapshot!=null?i.snapshot:i.version===lt&&i.nodes!=null?i:void 0;if(a!=null)try{return t.fromSnapshot(a,r)}catch(u){r?.onError?.(u,o)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${n.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,n,r){if(e!=null&&n!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,n),this.config.inspectorEnabled){let o={path:e,annotation:n,timestamp_ns:V(),...r?.actor!=null?{actor:r.actor}:{}};this._traceRing.push(o)}return}return e!=null?this.config.inspectorEnabled?this._annotations.get(e):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(e){return this._annotations.get(e)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(e){let n=this._traceRing.toArray().filter(o=>!e(o)),r=this._traceRing.size-n.length;this._traceRing.clear();for(let o of n)this._traceRing.push(o);return r}static diff(e,n){let r=new Set(Object.keys(e.nodes)),o=new Set(Object.keys(n.nodes)),s=[...o].filter(b=>!r.has(b)).sort(),i=[...r].filter(b=>!o.has(b)).sort(),a=[],u=[];for(let b of r){if(!o.has(b))continue;let v=e.nodes[b],T=n.nodes[b],w=v.v,k=T.v;w!=null&&k!=null&&w.id===k.id&&w.version!==k.version&&u.push({path:b,id:w.id,from:w.version,to:k.version});let x=w!=null&&k!=null&&w.id===k.id&&w.version===k.version;for(let R of["type","status","sentinel"]){let _=v[R],G=T[R];_!==G&&a.push({path:b,field:R,from:_,to:G})}if(!x)for(let R of["value","meta"]){let _=v[R],G=T[R];Xf(_,G)||a.push({path:b,field:R,from:_,to:G})}}let c=b=>`${b.from} ${b.to}`,d=new Set(e.edges.map(c)),l=new Set(n.edges.map(c)),f=n.edges.filter(b=>!d.has(c(b))),p=e.edges.filter(b=>!l.has(c(b))),m=new Set(e.subgraphs),h=new Set(n.subgraphs),g=[...h].filter(b=>!m.has(b)).sort(),y=[...m].filter(b=>!h.has(b)).sort();return{nodesAdded:s,nodesRemoved:i,nodesChanged:a,versionChanges:u,edgesAdded:f,edgesRemoved:p,subgraphsAdded:g,subgraphsRemoved:y}}};function Qo(t,e){let n=q.diff(t,e),r={};for(let o of n.nodesAdded){let s=e.nodes[o];s!=null&&(r[o]=s)}return{...n,nodesAddedFull:r}}function 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,c=new Map,d=new Set;for(let[v,T]of Object.entries(t.nodes)){if(!v)continue;d.add(v);let w=T.deps??[];i.set(v,w);for(let k of w)k&&(d.add(k),a.has(k)||a.set(k,new Set),a.get(k).add(v))}for(let v of t.edges){if(v==null||typeof v!="object")continue;let T=typeof v.from=="string"?v.from:"",w=typeof v.to=="string"?v.to:"";!T||!w||(d.add(T),d.add(w),c.has(T)||c.set(T,new Set),c.get(T).add(w),u.has(w)||u.set(w,new Set),u.get(w).add(T))}if(!d.has(e))return r.withDetail?o:[];let l=r.both===!0,f=v=>{if(l){let x=i.get(v)??[],R=u.get(v),_=a.get(v),G=c.get(v),L=[...x];return R&&L.push(...R),_&&L.push(..._),G&&L.push(...G),L}if(n==="upstream"){let x=i.get(v)??[],R=u.get(v);return R?[...x,...R]:x}let T=a.get(v),w=c.get(v),k=T?[...T]:[];return w&&k.push(...w),k},p=new Set([e]),m=new Map,h=[{path:e,depth:0}],g=0,y=!1;for(;g<h.length;){let v=h[g++];if(s!=null&&v.depth>=s){f(v.path).length>0&&(y=!0);continue}for(let T of f(v.path))!T||p.has(T)||(p.add(T),m.set(T,v.depth+1),h.push({path:T,depth:v.depth+1}))}let b=[...m.keys()].sort((v,T)=>v<T?-1:v>T?1:0);return r.withDetail?{paths:b,depths:m,truncated:y}:b}function fm(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 es={};ye(es,{CqrsGraph:()=>Zo,MemoryEventStore:()=>Yi,cqrs:()=>Qi});_e();we();nn();var qi={};ye(qi,{COMPLETE:()=>M,COMPLETE_MSG:()=>ho,COMPLETE_ONLY_BATCH:()=>dr,DATA:()=>S,DEFAULT_ACTOR:()=>bt,DIRTY:()=>ee,DIRTY_MSG:()=>Rt,DIRTY_ONLY_BATCH:()=>Mn,ERROR:()=>O,GraphReFlyConfig:()=>en,GuardDenied:()=>nt,INVALIDATE:()=>ze,INVALIDATE_MSG:()=>mo,INVALIDATE_ONLY_BATCH:()=>cr,NodeImpl:()=>Oe,PAUSE:()=>Ge,RESOLVED:()=>$,RESOLVED_MSG:()=>En,RESOLVED_ONLY_BATCH:()=>ur,RESUME:()=>$e,START:()=>yt,START_MSG:()=>_n,TEARDOWN:()=>de,TEARDOWN_MSG:()=>go,TEARDOWN_ONLY_BATCH:()=>On,accessHintForGuard:()=>Tr,advanceVersion:()=>wr,autoTrackNode:()=>rn,batch:()=>X,configure:()=>_i,createVersioning:()=>In,defaultConfig:()=>Pe,defaultHash:()=>Dt,derived:()=>E,downWithBatch:()=>Nt,dynamicNode:()=>kr,effect:()=>me,isBatching:()=>Zt,isV1:()=>Si,monotonicNs:()=>V,node:()=>K,normalizeActor:()=>St,pipe:()=>Mi,policy:()=>tn,policyFromRules:()=>vr,producer:()=>W,registerBuiltins:()=>br,resolveDescribeFields:()=>_t,state:()=>N,wallClockNs:()=>le});mr();_e();we();xi();nn();ie();Ne();ne();vo();_e();ie();ne();var Or=class{_version=0;_maxSize;_buf;_head=0;_size=0;constructor(e,n){if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(this._maxSize=n,n!==void 0){if(this._buf=new Array(n),e&&e.length>0){let r=Math.min(e.length,n),o=e.length-r;for(let s=0;s<r;s++)this._buf[s]=e[o+s];this._size=r}}else this._buf=e?[...e]:[],this._size=this._buf.length}get version(){return this._version}get size(){return this._size}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._size+e;if(!(n<0||n>=this._size))return this._maxSize!==void 0?this._buf[(this._head+n)%this._maxSize]:this._buf[n]}append(e){this._rawAppend(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._maxSize!==void 0&&e.length>this._maxSize?e.length-this._maxSize:0;for(let r=n;r<e.length;r++)this._rawAppend(e[r]);this._version+=1}clear(){if(this._size===0)return 0;let e=this._size;if(this._maxSize===void 0)this._buf.length=0;else for(let n=0;n<e;n++)this._buf[(this._head+n)%this._maxSize]=void 0;return this._head=0,this._size=0,this._version+=1,e}trimHead(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`trimHead: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return 0;let n=Math.min(e,this._size);if(this._maxSize===void 0)this._buf.splice(0,n);else{for(let r=0;r<n;r++)this._buf[(this._head+r)%this._maxSize]=void 0;this._head=(this._head+n)%this._maxSize}return this._size-=n,this._version+=1,n}slice(e,n){if(!Number.isInteger(e)||e<0)throw new RangeError(`slice: start must be a non-negative integer (got ${e})`);if(n!==void 0&&(!Number.isInteger(n)||n<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${n})`);let r=n===void 0?this._size:Math.min(Math.max(n,0),this._size),o=Math.min(e,this._size);if(o>=r)return[];let s=r-o;if(this._maxSize===void 0)return this._buf.slice(o,r);let i=new Array(s);for(let a=0;a<s;a++)i[a]=this._buf[(this._head+o+a)%this._maxSize];return i}tail(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`tail: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return[];let n=Math.min(e,this._size);return this.slice(this._size-n,this._size)}toArray(){if(this._maxSize===void 0)return[...this._buf];let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this._buf[(this._head+n)%this._maxSize];return e}_rawAppend(e){if(this._maxSize===void 0){this._buf.push(e),this._size=this._buf.length;return}this._size<this._maxSize?(this._buf[(this._head+this._size)%this._maxSize]=e,this._size+=1):(this._buf[this._head]=e,this._head=(this._head+1)%this._maxSize)}};function Bc(t){return t.subscribe(()=>{})}var mm=64;function We(t,e={}){let{name:n,maxSize:r,versioning:o,backend:s}=e,i=s??new Or(t,r),a=N(i.toArray(),{name:n,describeKind:"state",equals:(m,h)=>m===h,...o!=null?{versioning:o}:{}});function u(){let m=i.toArray();X(()=>{a.down([[ee]]),a.down([[S,m]])})}let c=new Map,d=new Map;function l(m,h){return`${m}:${h===void 0?"END":h}`}function f(m){if(m.size<mm)return;let h=m.keys().next();if(h.done)return;let g=m.get(h.value);g!==void 0&&g.dispose(),m.delete(h.value)}function p(m){let h=i.version;try{return m()}finally{i.version!==h&&u()}}return{entries:a,get size(){return i.size},at(m){return i.at(m)},append(m){p(()=>i.append(m))},appendMany(m){m.length!==0&&p(()=>i.appendMany(m))},clear(){p(()=>i.clear())},trimHead(m){p(()=>i.trimHead(m))},tail(m){if(!Number.isInteger(m)||m<0)throw new RangeError(`tail: n must be a non-negative integer (got ${m})`);let h=c.get(m);if(h!==void 0)return c.delete(m),c.set(m,h),h.node;f(c);let g=E([a],([b])=>{let v=b;return m===0||v.length===0?[]:v.slice(Math.max(0,v.length-m))},{initial:i.tail(m),describeKind:"derived"}),y=Bc(g);return c.set(m,{node:g,dispose:y}),g},slice(m,h){if(!Number.isInteger(m)||m<0)throw new RangeError(`slice: start must be a non-negative integer (got ${m})`);if(h!==void 0&&(!Number.isInteger(h)||h<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${h})`);let g=l(m,h),y=d.get(g);if(y!==void 0)return d.delete(g),d.set(g,y),y.node;f(d);let b=E([a],([T])=>{let w=T;return h===void 0?w.slice(m):w.slice(m,h)},{initial:i.slice(m,h),describeKind:"derived"}),v=Bc(b);return d.set(g,{node:b,dispose:v}),b},disposeTail(m){let h=c.get(m);return h===void 0?!1:(h.dispose(),c.delete(m),!0)},disposeSlice(m,h){let g=l(m,h),y=d.get(g);return y===void 0?!1:(y.dispose(),d.delete(g),!0)},disposeAllViews(){for(let m of c.values())m.dispose();c.clear();for(let m of d.values())m.dispose();d.clear()},dispose(){for(let m of c.values())m.dispose();c.clear();for(let m of d.values())m.dispose();d.clear()}}}var zi={};ye(zi,{ENVELOPE_VERSION:()=>Cn,GRAPH_META_SEGMENT:()=>He,Graph:()=>q,JsonCodec:()=>yo,SIZEOF_OVERHEAD:()=>De,SIZEOF_SYMBOL:()=>Uo,SNAPSHOT_VERSION:()=>lt,createDagCborCodec:()=>Ti,createDagCborZstdCodec:()=>wi,decodeEnvelope:()=>pr,diffForWAL:()=>Qo,encodeEnvelope:()=>lr,explainPath:()=>_r,graphProfile:()=>pn,mermaidLiveUrl:()=>Yo,reachable:()=>fn,registerBuiltinCodecs:()=>fr,replayWAL:()=>ki,sizeof:()=>Mr,validateGraphObservability:()=>Ui,watchTopologyTree:()=>Mt});bo();ie();function Mt(t,e){let n=new Map,r=(o,s)=>{if(n.has(o))return;let i={off:()=>{},prefix:s};n.set(o,i);let a=o.topology.subscribe(u=>{for(let c of u){if(c[0]!==S)continue;let d=c[1];if(e(d,o,s),d.kind==="added"&&d.nodeKind==="mount"){let l=o._mounts.get(d.name);if(l instanceof q){let f=`${s}${d.name}::`;r(l,f)}}else if(d.kind==="removed"&&d.nodeKind==="mount"){let l=`${s}${d.name}::`;for(let[f,p]of Array.from(n.entries()))f!==t&&p.prefix.startsWith(l)&&(p.off(),n.delete(f))}}});i.off=a;for(let[u,c]of o._mounts)if(c instanceof q){let d=`${s}${u}::`;r(c,d)}};return r(t,""),()=>{for(let o of n.values())o.off();n.clear()}}function Ui(t,e={}){let n=[],r=e.requireFound??!0;if(e.skipDescribe!==!0)try{let c=t.describe(),d=new Set(Object.keys(c.nodes)),l=[];for(let[f,p]of Object.entries(c.nodes))for(let m of p.deps)m!==""&&!d.has(m)&&l.push(`${f} \u2192 ${m}`);for(let f of c.edges)d.has(f.from)||l.push(`edge.from: ${f.from}`),d.has(f.to)||l.push(`edge.to: ${f.to}`);l.length>0?n.push({kind:"describe",ok:!1,reason:`describe() has ${l.length} dangling pointer(s); nodes \u2289 deps`,danglingDeps:l}):n.push({kind:"describe",ok:!0,nodeCount:d.size,edgeCount:c.edges.length})}catch(c){n.push({kind:"describe",ok:!1,reason:`describe() threw: ${c instanceof Error?c.message:String(c)}`})}for(let c of e.formats??[])try{let d=t.describe({format:c});typeof d!="string"||d.length===0?n.push({kind:"describe-format",ok:!1,format:c,reason:`describe({ format: "${c}" }) returned empty or non-string output`}):n.push({kind:"describe-format",ok:!0,format:c,length:d.length})}catch(d){n.push({kind:"describe-format",ok:!1,format:c,reason:d instanceof Error?d.message:String(d)})}for(let c of e.paths??[])try{t.resolve(c),n.push({kind:"observe",ok:!0,path:c})}catch(d){n.push({kind:"observe",ok:!1,path:c,reason:d instanceof Error?d.message:String(d)})}for(let[c,d]of e.pairs??[])try{let l=t.explain(c,d);r&&l.found===!1?n.push({kind:"explain",ok:!1,from:c,to:d,reason:`explain(${c} \u2192 ${d}) found no path${l.reason?`: ${l.reason}`:""}`}):n.push({kind:"explain",ok:!0,from:c,to:d,found:l.found,steps:l.steps.length})}catch(l){n.push({kind:"explain",ok:!1,from:c,to:d,reason:l instanceof Error?l.message:String(l)})}let o=n.filter(c=>!c.ok),s=o.length===0,i=e.paths?.length??0,a=e.pairs?.length??0,u=e.formats?.length??0;return{ok:s,checks:n,failures:o,summary(){let c=[e.skipDescribe===!0?null:"describe",u>0?`${u} format${u===1?"":"s"}`:null,i>0?`${i} observe path${i===1?"":"s"}`:null,a>0?`${a} explain pair${a===1?"":"s"}`:null].filter(l=>l!=null),d=c.length>0?c.join(", "):"describe-only";return s?`validateGraphObservability: OK (${d})`:`validateGraphObservability: ${o.length} failure(s) across ${d}`}}}_e();ie();Ne();ve();function pt(t,e){t!=null&&Nt(n=>t.down(n),[[S,e]],Pe.tierOf)}function Cr(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[ee],[S,n+1]]),!0)}function qe(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}function Ji(t){return t.relatedTo?.[0]??t.summary}var hm=tn((t,e)=>{t("write"),t("signal"),e("observe")}),gm=tn((t,e)=>{t("observe"),t("signal"),e("write")}),ym=tn((t,e)=>{t("observe"),t("signal"),e("write")});function Xo(t,e){return qe("cqrs",t,e)}var Yi=class{_store=new Map;persist(e){let n=this._store.get(e.type);n||(n=[],this._store.set(e.type,n)),n.push(e)}loadEvents(e,n){let r=this._store.get(e)??[],o=n?.timestampNs,s=n?.seq,i=o==null?[...r]:r.filter(u=>u.timestampNs>o||u.timestampNs===o&&u.seq>(s??-1)),a=i.length>0?i[i.length-1]:void 0;return{events:i,cursor:a?{timestampNs:a.timestampNs,seq:a.seq}:n}}clear(){this._store.clear()}},Zo=class extends q{_eventLogs=new Map;_commandHandlers=new Map;_projections=new Set;_sagas=new Set;_keepaliveDisposers=[];_eventStore;_seq=0;constructor(e,n={}){super(e,n.graph)}destroy(){for(let e of this._keepaliveDisposers)e();this._keepaliveDisposers.length=0,super.destroy()}event(e){let n=this._eventLogs.get(e);if(n)return n.node;let r=We([],{name:e,versioning:0}),o=r.entries,s=E([o],([i])=>i,{name:e,describeKind:"state",meta:Xo("event",{event_name:e}),guard:ym,initial:o.cache});return this.add(s,{name:e}),this._keepaliveDisposers.push(re(s)),this._eventLogs.set(e,{log:r,node:s}),s}_appendEvent(e,n){let r=this._eventLogs.get(e);if(r||(this.event(e),r=this._eventLogs.get(e)),r.node.status==="completed"||r.node.status==="errored")throw new Error(`Cannot dispatch to terminated event stream "${e}" (status: ${r.node.status}).`);let o=r.log.entries.v,s={type:e,payload:n,timestampNs:le(),seq:++this._seq,...o!=null?{v0:{id:o.id,version:o.version}}:{}};r.log.append(s),this._eventStore&&this._eventStore.persist(s)}command(e,n){let r=N(void 0,{name:e,describeKind:"state",meta:{...Xo("command",{command_name:e}),error:null},guard:hm});return this.add(r,{name:e}),this._commandHandlers.set(e,n),r}dispatch(e,n){let r=this._commandHandlers.get(e);if(!r)throw new Error(`Unknown command: "${e}". Register with .command() first.`);let o=this.resolve(e);X(()=>{o.emit(n,{internal:!0});try{r(n,{emit:(s,i)=>this._appendEvent(s,i)}),o.meta.error.emit(null,{internal:!0})}catch(s){throw o.meta.error.emit(s,{internal:!0}),s}})}projection(e,n,r,o){let s=n.map(a=>(this._eventLogs.has(a)||this.event(a),this._eventLogs.get(a).node)),i=E(s,a=>{let u=[];for(let c of a){let d=c;u.push(...d)}return u.sort((c,d)=>c.timestampNs-d.timestampNs||c.seq-d.seq),r(o,u)},{name:e,describeKind:"derived",meta:Xo("projection",{projection_name:e,source_events:n}),guard:gm,initial:o});return this.add(i,{name:e}),this._keepaliveDisposers.push(re(i)),this._projections.add(e),i}saga(e,n,r){let o=n.map(u=>(this._eventLogs.has(u)||this.event(u),this._eventLogs.get(u).node)),s=new Map,i={},a=K(o,(u,c)=>{let d=i.n.meta.error;for(let l=0;l<u.length;l++){let f=u[l];if(f==null||f.length===0)continue;let p=f.at(-1);if(!p)continue;let m=n[l],h=s.get(m)??0;if(p.length>h){let g=p.slice(h);for(let y of g)try{r(y),d.emit(null,{internal:!0})}catch(b){d.emit(b,{internal:!0})}s.set(m,p.length)}}},{name:e,describeKind:"effect",meta:{...Xo("saga",{saga_name:e,source_events:n}),error:null}});return i.n=a,this.add(a,{name:e}),this._keepaliveDisposers.push(re(a)),this._sagas.add(e),a}useEventStore(e){this._eventStore=e}async rebuildProjection(e,n,r){if(!this._eventStore)throw new Error("No event store wired. Call useEventStore() first.");let o=[];for(let s of e){let i=await this._eventStore.loadEvents(s);o.push(...i.events)}return o.sort((s,i)=>s.timestampNs-i.timestampNs||s.seq-i.seq),n(r,o)}};function Qi(t,e){return new Zo(t,e)}var Zi=class{constructor(e){this.graph=e}onModuleDestroy(){this.graph.destroy()}},ea=class{graph=new q("request");onModuleDestroy(){this.graph.destroy()}},jc,Xi;jc=[(0,Ar.Module)({})];var Kt=class Kt{static forRoot(e){let n=e??{},r=n.name??"root",o=[{provide:st,useFactory:()=>{let s=new q(r);return n.build&&n.build(s),n.snapshot&&s.restore(n.snapshot),s}},{provide:Symbol.for("graphrefly:root-lifecycle"),useFactory:s=>new Zi(s),inject:[st]},{provide:dn,useFactory:(s,i)=>new dn(s,i),inject:[st,Vc.ModuleRef]}];if(n.nodes)for(let s of n.nodes)o.push({provide:ct(s),useFactory:i=>i.resolve(s),inject:[st]});return n.requestScope&&o.push({provide:Symbol.for("graphrefly:request-lifecycle"),useFactory:()=>new ea,scope:Ar.Scope.REQUEST},{provide:on,useFactory:s=>s.graph,inject:[Symbol.for("graphrefly:request-lifecycle")],scope:Ar.Scope.REQUEST}),{module:Kt,global:!0,providers:o,exports:[st,...(n.nodes??[]).map(ct),...n.requestScope?[on]:[]]}}static forFeature(e){let n=[{provide:rt(e.name),useFactory:r=>{let o=new q(e.name);return e.build&&e.build(o),e.snapshot&&o.restore(e.snapshot),r.mount(e.name,o),o},inject:[st]}];if(e.nodes)for(let r of e.nodes)n.push({provide:ct(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[rt(e.name)]});return{module:Kt,providers:n,exports:[rt(e.name),...(e.nodes??[]).map(r=>ct(`${e.name}::${r}`))]}}static forCqrs(e){let n=[{provide:rt(e.name),useFactory:r=>{let o=Qi(e.name,e.cqrs);return e.eventStore&&o.useEventStore(e.eventStore),e.build&&e.build(o),r.mount(e.name,o),o},inject:[st]}];if(e.nodes)for(let r of e.nodes)n.push({provide:ct(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[rt(e.name)]});return{module:Kt,providers:n,exports:[rt(e.name),...(e.nodes??[]).map(r=>ct(`${e.name}::${r}`))]}}};Xi=Su(null),Kt=_u(Xi,0,"GraphReflyModule",jc,Kt),Eu(Xi,1,Kt);var ts=Kt;var rs={};ye(rs,{useStore:()=>bm,useSubscribe:()=>Kc,useSubscribeRecord:()=>vm});var Ot=require("react");ie();function Kc(t){return(0,Ot.useSyncExternalStore)(e=>{let n=!1,r=t.subscribe(()=>{n||e()});return()=>{n=!0,r()}},()=>t.cache,()=>t.cache)}function bm(t){let e=Kc(t),n=(0,Ot.useCallback)(r=>{t.down([[ee],[S,r]])},[t]);return[e,n]}function vm(t,e){let n=(0,Ot.useRef)(e);n.current=e;let r=(0,Ot.useMemo)(()=>{let o=()=>{let i={},a=t.cache??[];for(let u of a){let c=n.current(u),d={};for(let l of Object.keys(c))d[l]=c[l].cache;i[u]=d}return i},s=o();return{subscribe:i=>{let a=!1,u=[],c=()=>{for(let f of u)f();u=[]},d=f=>{c();for(let p of f){let m=n.current(p);for(let h of Object.keys(m)){let g=m[h].subscribe(()=>{s=o(),a||i()});u.push(g)}}s=o(),a||i()},l=t.subscribe(f=>{let p=f.some(m=>m[0]===S||m[0]===$);!a&&p&&d(t.cache??[])});return d(t.cache??[]),()=>{a=!0,l(),c()}},getSnapshot:()=>s}},[t]);return(0,Ot.useSyncExternalStore)(r.subscribe,r.getSnapshot,r.getSnapshot)}var ss={};ye(ss,{Signal:()=>Tm});_e();ie();ne();var Yn=[];function os(t){let e=t.cache;return t.subscribe(r=>{for(let[o,s]of r)o===S&&(e=s)})(),e}var ta=class{_node;_equals;constructor(e,n){this._equals=n?.equals??Object.is,this._node=N(e,{...n,resubscribable:!0,resetOnTeardown:!0})}get(){let e=Yn[Yn.length-1];return e?(this._node.status==="sentinel"&&os(this._node),e(this._node)):this._node.status==="sentinel"?os(this._node):this._node.cache}set(e){this._equals(this.get(),e)||X(()=>{this._node.down([[ee],[S,e]])})}},na=class{_node;constructor(e,n){this._node=rn(r=>{Yn.push(r);try{return e()}finally{Yn.pop()}},{...n,describeKind:"derived",resubscribable:!0,resetOnTeardown:!0})}get(){let e=Yn[Yn.length-1];return e?(this._node.status==="sentinel"&&os(this._node),e(this._node)):this._node.status==="sentinel"?os(this._node):this._node.cache}},Tm={State:ta,Computed:na,sub:(t,e)=>{let n=typeof e=="function"?{data:e,error:void 0,complete:void 0}:e,r=!0;return t._node.subscribe(o=>{for(let[s,i]of o){if(s===S){if(r){r=!1;continue}n.data?.(i)}s===O&&n.error?.(i),s===M&&n.complete?.()}})}};var is={};ye(is,{useStore:()=>wm,useSubscribe:()=>Hc,useSubscribeRecord:()=>km});var Ct=require("solid-js");ie();function Hc(t){let[e,n]=(0,Ct.createSignal)(t.cache,{equals:!1}),r=t.subscribe(()=>{n(()=>t.cache)});return(0,Ct.getOwner)()?(0,Ct.onCleanup)(()=>r()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Solid reactive owner \u2014 subscription will not be auto-disposed."),e}function wm(t){return[Hc(t),r=>{t.down([[ee],[S,r]])}]}function km(t,e){let[n,r]=(0,Ct.createSignal)({},{equals:!1}),o=[],s=()=>{for(let c of o)c();o=[]},i=()=>{let c={};for(let d of t.cache??[]){let l=e(d),f={};for(let p of Object.keys(l))f[p]=l[p].cache;c[d]=f}return c},a=c=>{s();for(let d of c){let l=e(d);for(let f of Object.keys(l)){let p=l[f].subscribe(()=>{r(()=>i())});o.push(p)}}r(()=>i())},u=t.subscribe(c=>{c.some(d=>d[0]===S||d[0]===$)&&a(t.cache??[])});return a(t.cache??[]),(0,Ct.getOwner)()?(0,Ct.onCleanup)(()=>{u(),s()}):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribeRecord called outside a Solid reactive owner \u2014 subscription will not be auto-disposed."),n}var as={};ye(as,{useStore:()=>Rm,useSubscribe:()=>xm,useSubscribeRecord:()=>Sm});ie();function xm(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n}}}function Rm(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n},set(e){t.down([[ee],[S,e]])},update(e){let n=e(t.cache);t.down([[ee],[S,n]])}}}function Sm(t,e){return{subscribe(n){let r=[],o=()=>{for(let u of r)u();r=[]},s=()=>{let u={};for(let c of t.cache??[]){let d=e(c),l={};for(let f of Object.keys(d))l[f]=d[f].cache;u[c]=l}return u},i=u=>{o();for(let c of u){let d=e(c);for(let l of Object.keys(d)){let f=d[l].subscribe(()=>{n(s())});r.push(f)}}n(s())},a=t.subscribe(u=>{u.some(c=>c[0]===S||c[0]===$)&&i(t.cache??[])});return i(t.cache??[]),()=>{a(),o()}}}}var us={};ye(us,{useStore:()=>Em,useSubscribe:()=>Nm,useSubscribeRecord:()=>_m});var Fe=require("vue");ie();function Nm(t){let e=(0,Fe.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,Fe.getCurrentScope)()?(0,Fe.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Fe.readonly)(e)}function Em(t){let e=(0,Fe.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,Fe.getCurrentScope)()?(0,Fe.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useStore called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Fe.computed)({get:()=>e.value,set:r=>{t.down([[ee],[S,r]])}})}function _m(t,e){let n=(0,Fe.shallowRef)({}),r=new Map;function o(){let a={};for(let[u,c]of r)a[u]={...c.values};n.value=a}function s(a){for(let c of r.values())for(let d of c.subs)d();r.clear();for(let c of a){let d=e(c),l=Object.keys(d),f={},p=[];for(let m of l){let h=d[m];f[m]=h.cache;let g=h.subscribe(()=>{f[m]=h.cache,o()});p.push(g)}r.set(c,{subs:p,values:f})}let u={};for(let[c,d]of r)u[c]={...d.values};n.value=u}return(0,Fe.watch)(()=>[...(typeof t=="function"?t():(0,Fe.isRef)(t)?t.value:t)??[]],a=>s(a??[]),{immediate:!0}),(0,Fe.getCurrentScope)()?(0,Fe.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,Fe.readonly)(n)}var cs={};ye(cs,{create:()=>Om});ie();ne();var Mm=()=>!1;function Om(t){let e=new q("zustand"),n=N(void 0,{name:"state",equals:Mm});e.add(n,{name:"state"});let r=()=>n.cache,o=(a,u)=>{let c=n.cache,d=typeof a=="function"?a(c):a;n.emit(u?d:{...c,...d})},s={getState:r,setState:o,getInitialState:()=>i,subscribe:a=>{let u=!0,c=n.cache;return n.subscribe(d=>{for(let[l,f]of d)if(l===S){if(u){u=!1;continue}a(f,c),c=f}})},destroy:e.destroy.bind(e)},i=t(o,r,s);return n.emit(i),Object.assign(e,s)}var ba={};ye(ba,{CircuitOpenError:()=>dt,ContentAddressedMissError:()=>Br,NS_PER_MS:()=>Be,NS_PER_SEC:()=>ot,NativeIndexBackend:()=>Kr,NativeListBackend:()=>Hr,NativeLogBackend:()=>Or,NativeMapBackend:()=>Fr,NativePubSubBackend:()=>Vr,RateLimiterOverflowError:()=>an,ResettableTimer:()=>Ce,TimeoutError:()=>un,audit:()=>pd,awaitSettled:()=>$o,buffer:()=>fd,bufferCount:()=>md,bufferTime:()=>gd,cached:()=>dc,canonicalJson:()=>jr,cascadingCache:()=>Rl,catchError:()=>Nd,checkpointToRedis:()=>gl,checkpointToS3:()=>hl,circuitBreaker:()=>Tt,combine:()=>sa,combineLatest:()=>xd,concat:()=>sd,concatMap:()=>ud,constant:()=>Mo,contentAddressedStorage:()=>hs,createTransport:()=>Wt,createWatermarkController:()=>zn,csvRows:()=>Qd,debounce:()=>aa,debounceTime:()=>Rd,decorrelatedJitter:()=>Lo,delay:()=>dd,deserializeError:()=>bn,dictStorage:()=>Pl,distill:()=>fs,distinctUntilChanged:()=>nd,elementAt:()=>Zc,empty:()=>sc,escapeRegexChar:()=>Pi,exhaustMap:()=>ad,exponential:()=>Co,externalBundle:()=>ds,externalProducer:()=>mn,fallback:()=>qn,fibonacci:()=>Ao,filter:()=>ft,find:()=>Xc,first:()=>ls,firstValueFrom:()=>Ye,firstWhere:()=>Po,flatMap:()=>cd,forEach:()=>jt,fromAny:()=>z,fromAsyncIter:()=>Gi,fromCSV:()=>Yd,fromClickHouseWatch:()=>tl,fromCron:()=>Do,fromDrizzle:()=>wl,fromEvent:()=>oc,fromHTTP:()=>pa,fromHTTPPoll:()=>Dd,fromHTTPStream:()=>Pd,fromIter:()=>Go,fromKafka:()=>qd,fromKysely:()=>kl,fromMCP:()=>$d,fromNATS:()=>ol,fromNDJSON:()=>el,fromOTel:()=>Bd,fromPrisma:()=>Tl,fromPrometheus:()=>Wd,fromPromise:()=>Di,fromPulsar:()=>nl,fromRabbitMQ:()=>il,fromRaf:()=>rc,fromRedisStream:()=>zd,fromSSE:()=>Id,fromSqlite:()=>yl,fromSqliteCursor:()=>bl,fromStatsD:()=>Kd,fromSyslog:()=>jd,fromTimer:()=>at,fromWebSocket:()=>la,fromWebSocketReconnect:()=>Fd,fromWebhook:()=>Ed,globToRegExp:()=>tc,interval:()=>vd,keepalive:()=>re,last:()=>Qc,linear:()=>Oo,lru:()=>ha,makeHttpError:()=>ht,map:()=>Lr,matchesAnyPattern:()=>nc,matchesCron:()=>_o,memoryStorage:()=>qr,merge:()=>wt,mergeMap:()=>ia,nameToSignal:()=>gn,ndjsonRows:()=>Xd,never:()=>ic,nodeSignal:()=>lc,of:()=>Fi,onFirstData:()=>Pr,pairwise:()=>rd,parseCron:()=>Eo,parsePrometheusText:()=>fa,parseSSEStream:()=>At,parseStatsD:()=>Hd,parseSyslog:()=>Vd,pausable:()=>wd,pubsub:()=>Ml,race:()=>id,rateLimiter:()=>Wn,reactiveCounter:()=>$i,reactiveIndex:()=>Al,reactiveList:()=>gs,reactiveLog:()=>We,reactiveMap:()=>Qe,reactiveSink:()=>je,reduce:()=>zc,repeat:()=>Td,replay:()=>Fo,rescue:()=>Dr,resolveBackoffPreset:()=>Gt,retry:()=>Kn,retrySource:()=>Ft,sample:()=>ld,scan:()=>Uc,serializeError:()=>yn,share:()=>cc,shareReplay:()=>pc,signalToName:()=>Ht,singleFromAny:()=>ys,singleNodeFromAny:()=>Ll,skip:()=>oa,sortJsonValue:()=>Wr,stableJsonString:()=>Il,stratify:()=>Ur,switchMap:()=>Te,take:()=>Ir,takeUntil:()=>Yc,takeWhile:()=>Jc,tap:()=>ed,tapFirst:()=>td,throttle:()=>ua,throttleTime:()=>Sd,throwError:()=>ac,timeout:()=>Un,toArray:()=>uc,toCSV:()=>ul,toClickHouse:()=>cl,toFile:()=>ma,toHTTP:()=>_d,toKafka:()=>Ud,toLoki:()=>fl,toMongo:()=>pl,toNATS:()=>sl,toObservable:()=>No,toPostgres:()=>ll,toPulsar:()=>rl,toRabbitMQ:()=>al,toReadableStream:()=>Ld,toRedisStream:()=>Jd,toS3:()=>dl,toSSE:()=>Cd,toSSEBytes:()=>Ad,toSqlite:()=>vl,toTempo:()=>ml,toWebSocket:()=>Gd,tokenBucket:()=>$t,valve:()=>kd,verifiable:()=>El,window:()=>bd,windowCount:()=>hd,windowTime:()=>yd,withBreaker:()=>Hn,withLatestFrom:()=>hn,withMaxAttempts:()=>Li,withStatus:()=>Bt,workerBridge:()=>ga,workerSelf:()=>ya,zip:()=>od});_e();we();ie();Ne();ne();_e();ie();ne();function Wc(t){return{describeKind:"producer",...t}}function mn(t,e){return W(n=>{let r=!0,o={emit(i){r&&n.emit(i)},error(i){r&&(r=!1,n.down([[O,i]]))},complete(){r&&(r=!1,n.down([[M]]))}},s;try{let i=t(o);s=typeof i=="function"?i:void 0}catch(i){return o.error(i),()=>{r=!1}}return()=>{r=!1;try{s?.()}catch{}}},Wc(e))}function ds(t,e,n){let r=!0,o,s=0,i=0,a={},u=[],c=()=>{let p=o;o=void 0;try{p?.()}catch{}};for(let p of e){let m=n?.name?`${n.name}::${p}`:p,h=n?.channelOpts?.[p],g=W(y=>(s++,()=>{i++,s>0&&i>=s&&i>=e.length&&c()}),Wc({...h,name:m}));a[p]=g,u.push(g)}let d={};for(let p of e)d[p]=m=>{r&&a[p].down([[S,m]])};d.error=p=>{r&&(r=!1,X(()=>{for(let m of u)m.down([[O,p]])}),c())},d.complete=()=>{r&&(r=!1,X(()=>{for(let p of u)p.down([[M]])}),c())};let l=t(d);return o=typeof l=="function"?l:void 0,Object.assign(a,{dispose:()=>{r&&(r=!1,X(()=>{for(let p of u)try{p.down([[M]])}catch{}}),c())}})}we();ie();Ne();ne();ve();function ce(t){return{describeKind:"derived",...t}}function qc(t){return{describeKind:"derived",partial:!0,...t}}function Lr(t,e,n){return K([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[$]]);return}for(let i of s)o.emit(e(i))},ce(n))}function ft(t,e,n){return K([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[$]]);return}let i=!1;for(let a of s)e(a)&&(o.emit(a),i=!0);i||o.down([[$]])},ce(n))}function Uc(t,e,n,r){return K([t],(o,s,i)=>{"acc"in i.store||(i.store.acc=n);let a=o[0];if(a==null||a.length===0){s.down([[$]]);return}for(let u of a)i.store.acc=e(i.store.acc,u),s.emit(i.store.acc)},{...ce(r),initial:n,resetOnTeardown:!0})}function zc(t,e,n,r){return K([t],(o,s,i)=>{if("acc"in i.store||(i.store.acc=n),i.terminalDeps[0]===!0){s.emit(i.store.acc),s.down([[M]]);return}let a=o[0];if(a==null||a.length===0){s.down([[$]]);return}for(let u of a)i.store.acc=e(i.store.acc,u)},{...ce(r),completeWhenDepsComplete:!1})}function Ir(t,e,n){return e<=0?K([t],(r,o,s)=>{s.store.completed||(s.store.completed=!0,o.down([[M]]))},{...ce(n),completeWhenDepsComplete:!1}):K([t],(r,o,s)=>{if("taken"in s.store||(s.store.taken=0),s.store.done){o.down([[$]]);return}if(s.terminalDeps[0]===!0){s.store.done=!0,o.down([[M]]);return}let i=r[0];if(i==null||i.length===0){o.down([[$]]);return}for(let a of i)if(s.store.taken++,o.emit(a),s.store.taken>=e){s.store.done=!0,o.down([[M]]);return}},{...ce(n),completeWhenDepsComplete:!1})}function oa(t,e,n){return K([t],(r,o,s)=>{"skipped"in s.store||(s.store.skipped=0);let i=r[0];if(i==null||i.length===0){o.down([[$]]);return}let a=!1;for(let u of i)s.store.skipped++,s.store.skipped<=e||(o.emit(u),a=!0);a||o.down([[$]])},ce(n))}function Jc(t,e,n){return K([t],(r,o,s)=>{if(s.store.done){o.down([[$]]);return}let i=r[0];if(i==null||i.length===0){o.down([[$]]);return}for(let a of i){if(!e(a)){s.store.done=!0,o.down([[M]]);return}o.emit(a)}},{...ce(n),completeWhenDepsComplete:!1})}function Yc(t,e,n){let r=n?.predicate??(i=>i[0]===S),{predicate:o,...s}=n??{};return W(i=>{let a=!1,u=t.subscribe(d=>{if(!a)for(let l of d){if(a)return;l[0]===S?i.emit(l[1]):(l[0]===M||l[0]===O)&&(a=!0,i.down([l]))}}),c=e.subscribe(d=>{if(!a)for(let l of d){if(a)return;if(r(l)){a=!0,i.down([[M]]);return}}});return()=>{u(),c()}},ce(s))}function ls(t,e){return Ir(t,1,e)}function Qc(t,e){let{defaultValue:n,...r}=e??{},o=e!=null&&Object.hasOwn(e,"defaultValue");return K([t],(s,i,a)=>{if(a.terminalDeps[0]===!0){a.store.has?i.emit(a.store.latest):o&&i.emit(n),i.down([[M]]);return}let u=s[0];if(u==null||u.length===0){i.down([[$]]);return}a.store.latest=u.at(-1),a.store.has=!0},{...ce(r),completeWhenDepsComplete:!1})}function Xc(t,e,n){return Ir(ft(t,e,n),1,n)}function Zc(t,e,n){return Ir(oa(t,e,n),1,n)}function ed(t,e,n){if(typeof e=="function")return K([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[$]]);return}for(let a of i)e(a),s.emit(a)},ce(n));let r=e;return K([t],(o,s,i)=>{if(i.terminalDeps[0]!==void 0){i.terminalDeps[0]===!0?(r.complete?.(),s.down([[M]])):(r.error?.(i.terminalDeps[0]),s.down([[O,i.terminalDeps[0]]]));return}let a=o[0];if(a==null||a.length===0){s.down([[$]]);return}for(let u of a)r.data?.(u),s.emit(u)},{...ce(n),completeWhenDepsComplete:!1})}function Pr(t,e,n){let r=n?.where??(s=>s!=null),o=!1;return K([t],(s,i)=>{let a=s[0];if(a==null||a.length===0){i.down([[$]]);return}for(let u of a)!o&&r(u)&&(o=!0,e(u)),i.emit(u)},ce(n))}var td=Pr;function nd(t,e=Object.is,n){return K([t],(r,o,s)=>{let i=r[0];if(i==null||i.length===0){o.down([[$]]);return}let a=!1;for(let u of i)s.store.hasPrev&&e(s.store.prev,u)||(s.store.prev=u,s.store.hasPrev=!0,o.emit(u),a=!0);a||o.down([[$]])},ce(n))}function rd(t,e){return K([t],(n,r,o)=>{let s=n[0];if(s==null||s.length===0){r.down([[$]]);return}let i=!1;for(let a of s)if(!o.store.hasPrev)o.store.prev=a,o.store.hasPrev=!0;else{let u=[o.store.prev,a];o.store.prev=a,r.emit(u),i=!0}i||r.down([[$]])},ce(e))}function sa(...t){let e=[...t];return E(e,n=>n,{...ce(),equals:(n,r)=>{if(n.length!==r.length)return!1;for(let o=0;o<n.length;o++)if(!Object.is(n[o],r[o]))return!1;return!0}})}function hn(t,e,n){return K([t,e],(r,o,s)=>{let i=r[0],a=r[1],u=a!=null&&a.length>0?a.at(-1):s.prevData[1];if(i!=null&&i.length>0){if(!(a!=null&&a.length>0)&&s.prevData[1]===void 0){o.down([[$]]);return}for(let c of i)o.emit([c,u])}else o.down([[$]])},qc(n))}function wt(...t){return t.length===0?W(e=>{e.down([[M]])},ce()):W(e=>{let n=t.length,r=0,o=[];for(let s of t){let i=s.subscribe(a=>{for(let u of a)u[0]===S?e.emit(u[1]):u[0]===M?(r+=1,r>=n&&e.down([[M]])):u[0]===O&&e.down([u])});o.push(i)}return()=>{for(let s of o)s()}},ce())}function od(...t){let e=t.length;return e===0?W(n=>{n.emit([]),n.down([[M]])},ce()):W(n=>{let r=Array.from({length:e},()=>[]),o=e;function s(){for(;r.every(a=>a.length>0);){let a=r.map(u=>u.shift());n.emit(a)}}let i=[];for(let a=0;a<e;a++){let u=a,c=t[a].subscribe(d=>{for(let l of d)l[0]===S?(r[u].push(l[1]),s()):l[0]===M?(o-=1,(o===0||r[u].length===0)&&n.down([[M]])):l[0]===O&&n.down([l])});i.push(c)}return()=>{for(let a of i)a()}},ce())}function sd(t,e,n){return W(r=>{let o=0,s=[],i,a;return a=e.subscribe(u=>{for(let c of u)o===0?c[0]===S?s.push(c[1]):c[0]===O&&r.down([c]):c[0]===S?r.emit(c[1]):(c[0]===M||c[0]===O)&&r.down([c])}),i=t.subscribe(u=>{for(let c of u)if(o===0)if(c[0]===S)r.emit(c[1]);else if(c[0]===M){o=1;for(let d of s)r.emit(d);s.length=0}else c[0]===O&&r.down([c])}),()=>{i?.(),a?.()}},ce(n))}function id(...t){return t.length===0?W(e=>{e.down([[M]])},ce()):t.length===1?K([t[0]],(e,n)=>{let r=e[0];if(r==null||r.length===0){n.down([[$]]);return}for(let o of r)n.emit(o)},ce()):W(e=>{let n=null,r=[];for(let o=0;o<t.length;o++){let s=o,i=t[o].subscribe(a=>{for(let u of a){if(n!==null&&s!==n)return;u[0]===S?(n===null&&(n=s),e.emit(u[1])):(u[0]===M||u[0]===O)&&(n===null||s===n)&&e.down([u])}});r.push(i)}return()=>{for(let o of r)o()}},ce())}function ps(t,e,n){let r,o=!1,s=()=>{o||(o=!0,n())};return r=t.subscribe(i=>{let a=!1,u=!1;for(let c of i)c[0]!==yt&&(c[0]===S?e.emit(c[1]):c[0]===M?a=!0:c[0]===O?(u=!0,e.down([c])):(c[0]===ee||c[0]===$)&&e.down([c]));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 K([t],(i,a,u)=>{if(u.terminalDeps[0]!=null&&u.terminalDeps[0]!==!0){s();return}if(u.terminalDeps[0]===!0){o=!0,r||a.down([[M]]);return}let c=i[0];if(!(c==null||c.length===0))return s(),r=ps(z(e(c[c.length-1])),a,()=>{s(),o&&a.down([[M]])}),{deactivate:()=>{s(),o=!1}}},{...ce(n),completeWhenDepsComplete:!1})}function ad(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return K([t],(i,a,u)=>{if(u.terminalDeps[0]!=null&&u.terminalDeps[0]!==!0){s();return}if(u.terminalDeps[0]===!0){o=!0,r||a.down([[M]]);return}let c=i[0];if(!(c==null||c.length===0))return r===void 0?r=ps(z(e(c[0])),a,()=>{s(),o&&a.down([[M]])}):a.down([[$]]),{deactivate:()=>{s(),o=!1}}},{...ce(n),completeWhenDepsComplete:!1})}function ud(t,e,n){let{maxBuffer:r,...o}=n??{},s=[],i,a=!1,u;function c(){i?.(),i=void 0}function d(){if(!u||i!==void 0)return;if(s.length===0){a&&u.down([[M]]);return}let f=s.shift();i=ps(z(e(f)),u,()=>{c(),d()})}function l(f){r&&r>0&&s.length>=r&&s.shift(),s.push(f),d()}return K([t],(f,p,m)=>{if(u=p,m.terminalDeps[0]!=null&&m.terminalDeps[0]!==!0){c(),s.length=0;return}if(m.terminalDeps[0]===!0){a=!0,d();return}let h=f[0];if(!(h==null||h.length===0)){for(let g of h)l(g);return{deactivate:()=>{c(),s.length=0,a=!1}}}},{...ce(o),completeWhenDepsComplete:!1})}function ia(t,e,n){let{concurrent:r,...o}=n??{},s=r!=null&&r>0?r:Number.POSITIVE_INFINITY,i=0,a=!1,u=new Set,c=[],d;function l(){a&&i===0&&c.length===0&&d&&d.down([[M]])}function f(g){if(!d)return;i++;let y;y=ps(z(e(g)),d,()=>{y&&u.delete(y),i--,p(),l()}),u.add(y)}function p(){for(;c.length>0&&i<s;)f(c.shift())}function m(g){i<s?f(g):c.push(g)}function h(){for(let g of u)g();u.clear(),i=0,c.length=0}return K([t],(g,y,b)=>{if(d=y,b.terminalDeps[0]!=null&&b.terminalDeps[0]!==!0){h();return}if(b.terminalDeps[0]===!0){a=!0,l();return}let v=g[0];if(!(v==null||v.length===0)){for(let T of v)m(T);return{deactivate:()=>{h(),a=!1}}}},{...ce(o),completeWhenDepsComplete:!1})}var cd=ia;function dd(t,e,n){return W(r=>{let o=new Set;function s(){for(let a of o)clearTimeout(a);o.clear()}let i=t.subscribe(a=>{for(let u of a)if(u[0]===S){let c=setTimeout(()=>{o.delete(c),r.emit(u[1])},e);o.add(c)}else if(u[0]===M){let c=setTimeout(()=>{o.delete(c),r.down([[M]])},e);o.add(c)}else u[0]===O&&(s(),r.down([u]))});return()=>{i(),s()}},ce(n))}function aa(t,e,n){return W(r=>{let o,s;function i(){o!==void 0&&(clearTimeout(o),o=void 0)}let a=t.subscribe(u=>{for(let c of u)c[0]===S?(i(),s=c[1],o=setTimeout(()=>{o=void 0,r.emit(s)},e)):c[0]===M?(o!==void 0&&(i(),r.emit(s)),r.down([[M]])):c[0]===O&&(i(),r.down([c]))});return()=>{a(),i()}},ce(n))}function ua(t,e,n){let{leading:r,trailing:o,...s}=n??{},i=r!==!1,a=o===!0,u=e*1e6;return W(c=>{let d,l=-1/0,f,p=!1;function m(){d!==void 0&&(clearTimeout(d),d=void 0)}let h=t.subscribe(g=>{for(let y of g)if(y[0]===S){let b=y[1],v=V();if(i&&v-l>=u)l=v,c.emit(b),m(),a&&(d=setTimeout(()=>{d=void 0,p&&(l=V(),c.emit(f),p=!1)},e));else if(a&&(f=b,p=!0,d===void 0)){let T=(v-l)/1e6;d=setTimeout(()=>{d=void 0,p&&(l=V(),c.emit(f),p=!1)},Math.max(0,e-T))}}else(y[0]===M||y[0]===O)&&(m(),c.down([y]))});return()=>{h(),m()}},ce(s))}function ld(t,e,n){return W(r=>{let o,s=!1,i=!1,a=t.subscribe(c=>{if(!s)for(let d of c){if(s)return;d[0]===S?o={v:d[1]}:d[0]===O?(s=!0,r.down([d])):d[0]===M&&(i=!0,o=void 0)}}),u=e.subscribe(c=>{if(!s)for(let d of c){if(s)return;d[0]===S?o!==void 0&&!i&&r.emit(o.v):d[0]===O?(s=!0,r.down([d])):d[0]===M&&(s=!0,r.down([[M]]))}});return()=>{a(),u()}},ce(n))}function pd(t,e,n){return W(r=>{let o,s,i=!1;function a(){o!==void 0&&(clearTimeout(o),o=void 0)}let u=t.subscribe(c=>{for(let d of c)d[0]===S?(s=d[1],i=!0,a(),o=setTimeout(()=>{o=void 0,i&&(i=!1,r.emit(s))},e)):(d[0]===M||d[0]===O)&&(a(),r.down([d]))});return()=>{u(),a()}},ce(n))}function fd(t,e,n){return W(r=>{let o=[],s=t.subscribe(a=>{for(let u of a)u[0]===S?o.push(u[1]):u[0]===M?(o.length>0&&r.emit([...o]),o.length=0,r.down([[M]])):u[0]===O&&r.down([u])}),i=e.subscribe(a=>{for(let u of a)u[0]===S?o.length>0&&(r.emit([...o]),o.length=0):u[0]===M?r.down([[M]]):u[0]===O&&r.down([u])});return()=>{s(),i(),o.length=0}},ce(n))}function md(t,e,n){if(e<=0)throw new RangeError("bufferCount expects count > 0");return W(r=>{let o=[],s=t.subscribe(i=>{for(let a of i)a[0]===S?(o.push(a[1]),o.length>=e&&r.emit(o.splice(0,o.length))):a[0]===M?(o.length>0&&r.emit([...o]),o.length=0,r.down([[M]])):a[0]===O&&r.down([a])});return()=>{s(),o.length=0}},ce(n))}function hd(t,e,n){if(e<=0)throw new RangeError("windowCount expects count > 0");return W(r=>{let o,s=0;function i(){let u=W(c=>(o=c.down.bind(c),()=>{o=void 0}),ce());s=0,r.emit(u)}let a=t.subscribe(u=>{for(let c of u)c[0]===S?(o||i(),o?.([[S,c[1]]]),s+=1,s>=e&&(o?.([[M]]),o=void 0)):c[0]===M?(o?.([[M]]),o=void 0,r.down([[M]])):c[0]===O&&(o?.([c]),o=void 0,r.down([c]))});return()=>{a(),o?.([[M]]),o=void 0}},ce(n))}function gd(t,e,n){return W(r=>{let o=[],s=setInterval(()=>{o.length>0&&(r.emit([...o]),o.length=0)},e),i=t.subscribe(a=>{for(let u of a)u[0]===S?o.push(u[1]):u[0]===M?(clearInterval(s),o.length>0&&r.emit([...o]),o.length=0,r.down([[M]])):u[0]===O&&(clearInterval(s),r.down([u]))});return()=>{i(),clearInterval(s),o.length=0}},ce(n))}function yd(t,e,n){return W(r=>{let o;function s(){o?.([[M]]),o=void 0}function i(){let c=W(d=>(o=d.down.bind(d),()=>{o=void 0}),ce());r.emit(c)}i();let a=setInterval(()=>{s(),i()},e),u=t.subscribe(c=>{for(let d of c)d[0]===S?o?.([[S,d[1]]]):d[0]===M?(clearInterval(a),s(),r.down([[M]])):d[0]===O&&(clearInterval(a),o?.([d]),s(),r.down([d]))});return()=>{u(),clearInterval(a),s()}},ce(n))}function bd(t,e,n){return W(r=>{let o;function s(){o?.([[M]]),o=void 0}function i(){let c=W(d=>(o=d.down.bind(d),()=>{o=void 0}),ce());r.emit(c)}let a=t.subscribe(c=>{for(let d of c)d[0]===S?(o||i(),o?.([[S,d[1]]])):d[0]===M?(s(),r.down([[M]])):d[0]===O&&(o?.([d]),o=void 0,r.down([d]))}),u=e.subscribe(c=>{for(let d of c)d[0]===S&&(s(),i())});return()=>{a(),u(),s()}},ce(n))}function vd(t,e){return W((n,r)=>{"n"in r.store||(r.store.n=0);let o=setInterval(()=>{n.emit(r.store.n),r.store.n=r.store.n+1},t);return()=>clearInterval(o)},ce(e))}function Td(t,e,n){if(e<=0)throw new RangeError("repeat expects count > 0");return W(r=>{let o=e,s,i=()=>{s?.(),s=t.subscribe(a=>{let u=!1,c=[];for(let d of a)d[0]===M?u=!0:c.push(d);c.length>0&&r.down(c),u&&(s?.(),s=void 0,o-=1,o>0?i():r.down([[M]]))})};return i(),()=>{s?.()}},ce(n))}function wd(t,e){return K([t],(n,r)=>{let o=n[0];if(o==null||o.length===0){r.down([[$]]);return}for(let s of o)r.emit(s)},ce(e))}function Dr(t,e,n){return W(r=>{let o=t.subscribe(s=>{for(let i of s)if(i[0]===S)r.emit(i[1]);else if(i[0]===O)try{r.emit(e(i[1]))}catch(a){r.down([[O,a]])}else i[0]===M&&r.down([[M]])});return()=>{o()}},ce(n))}function kd(t,e,n){return K([t,e],(r,o,s)=>{let i=r[1];if(!(i!=null&&i.length>0?i.at(-1):s.prevData[1])){o.down([[$]]);return}let u=r[0];if(u!=null&&u.length>0){for(let c of u)o.emit(c);return}if(i!=null&&i.length>0&&s.prevData[0]!==void 0){o.emit(s.prevData[0]);return}o.down([[$]])},qc(n))}var xd=sa,Rd=aa,Sd=ua,Nd=Dr;ie();Ne();ne();Vn();var ca=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 Gr(t){return t instanceof Error?t:new Error(String(t))}function Cm(t){return t===void 0?null:typeof t=="string"?Gt(t):t}function je(t,e){let{name:n,onTransportError:r,retry:o,backpressure:s,batchSize:i=Number.POSITIVE_INFINITY,flushIntervalMs:a=0,serialize:u,stopOn:c,onUpstreamMessage:d,onDispose:l,send:f,sendBatch:p,ctx:m}=e;if(!f&&!p)throw new Error("reactiveSink: `send` or `sendBatch` must be provided");let h=m,g=Math.max(1,o?.maxAttempts??1),y=Cm(o?.backoff??(g>1?"exponential":void 0)),b=o?.shouldRetry??(()=>!0),v=p!==void 0||i<Number.POSITIVE_INFINITY||a>0,T=Y=>n?`${n}::${Y}`:void 0,w=N(void 0,{equals:()=>!1,name:T("sent")}),k=N(null,{name:T("failed")}),x=N(0,{name:T("inFlight")}),R=N(null,{name:T("errors")}),_=v?N(0,{name:T("buffered")}):void 0,G=s?N(!1,{name:T("paused")}):void 0,L=0,P=Y=>{L+=Y,x.down([[S,L]])},C=Y=>{try{r?.(Y)}catch{}try{R.down([[S,Y]])}catch{}},B=new Set,te=Y=>{B.add(Y);let be=()=>B.delete(Y);Y.then(be,be)},F=(Y,be,Re)=>{let Me=y?y(be-1,Re,null):0,Ee=Me==null?0:typeof Me=="number"&&Me>0?Me:0,Ze=Math.max(1,Math.ceil(Ee/1e6));return new Promise(pe=>{setTimeout(()=>pe(Y()),Ze)})},A=Y=>Y!=null&&typeof Y=="object"&&typeof Y.then=="function",D=Y=>{let be;try{be=u?u(Y):Y}catch(pe){let fe=Gr(pe);return C({stage:"serialize",error:fe,value:Y}),k.down([[S,{value:Y,error:fe,attempts:0}]]),Promise.resolve()}let Re=0,Me=pe=>{P(-1);let fe=Gr(pe);if(C({stage:"send",error:fe,value:Y,attempt:Re}),!(Re<g&&b(fe,Re))){k.down([[S,{value:Y,error:fe,attempts:Re}]]);return}return F(Ze,Re,fe)},Ee=()=>{P(-1),w.down([[S,Y]])};function Ze(){Re+=1,P(1);let pe;try{pe=f(be,h)}catch(fe){return Me(fe)??Promise.resolve()}return A(pe)?pe.then(Ee,fe=>Me(fe)):(Ee(),Promise.resolve())}return Ze()},I=s?.maxBuffer??Number.POSITIVE_INFINITY,J=new ca(I),H,ae=!1,j=()=>{_?.down([[S,J.length]])},U=Y=>{G&&G.down([[S,Y]])},he=s?.strategy??"drop-oldest",ue=(Y,be)=>{let Re={value:Y,payload:be};if(J.length<I)return J.push(Re),j(),!0;if(he==="drop-oldest"){let Ee=J.shift();return J.push(Re),j(),U(!0),k.down([[S,{value:Ee.value,error:new Error("backpressure: buffer overflow \u2014 dropped oldest"),attempts:0}]]),!0}if(he==="drop-newest")return U(!0),k.down([[S,{value:Y,error:new Error("backpressure: buffer overflow \u2014 dropped newest"),attempts:0}]]),!1;let Me=new Error("backpressure: buffer overflow");return C({stage:"send",error:Me,value:Y}),k.down([[S,{value:Y,error:Me,attempts:0}]]),U(!0),!1},oe=Y=>{let be=0,Re=Y.map(pe=>pe.payload),Me=pe=>{P(-1);let fe=Gr(pe);if(C({stage:"send",error:fe,value:Y.map(sr=>sr.value),attempt:be}),!(be<g&&b(fe,be))){for(let{value:sr}of Y)k.down([[S,{value:sr,error:fe,attempts:be}]]);return}return F(Ze,be,fe)},Ee=()=>{P(-1);for(let{value:pe}of Y)w.down([[S,pe]])};function Ze(){be+=1,P(1);let pe;try{pe=p(Re,h)}catch(fe){return Me(fe)??Promise.resolve()}return A(pe)?pe.then(Ee,fe=>Me(fe)):(Ee(),Promise.resolve())}return Ze()},Z=async Y=>{for(let be of Y)await Se(be.value,be.payload)},Se=(Y,be)=>{let Re=0,Me=pe=>{P(-1);let fe=Gr(pe);if(C({stage:"send",error:fe,value:Y,attempt:Re}),!(Re<g&&b(fe,Re))){k.down([[S,{value:Y,error:fe,attempts:Re}]]);return}return F(Ze,Re,fe)},Ee=()=>{P(-1),w.down([[S,Y]])};function Ze(){Re+=1,P(1);let pe;try{pe=f(be,h)}catch(fe){return Me(fe)??Promise.resolve()}return A(pe)?pe.then(Ee,fe=>Me(fe)):(Ee(),Promise.resolve())}return Ze()},Q=()=>{if(ae||J.length===0)return Promise.resolve();let Y=J.drain();if(j(),U(!1),p!==void 0){let Re=oe(Y);return te(Re),Re}let be=Z(Y);return te(be),be},se=()=>{H!==void 0||ae||a<=0||(H=setTimeout(()=>{H=void 0,Q()},a))},xe=t.subscribe(Y=>{for(let be of Y){let Re=be[0];if(Re!==S)try{d?.(be)}catch{}if(Re===S){let Me=be[1];if(v){let Ee;if(u)try{Ee=u(Me)}catch(pe){let fe=Gr(pe);C({stage:"serialize",error:fe,value:Me}),k.down([[S,{value:Me,error:fe,attempts:0}]]);continue}else Ee=Me;if(!ue(Me,Ee))continue;J.length>=i?Q():se()}else{let Ee=D(Me);te(Ee)}}else Pe.messageTier(Re)>=3&&v&&(H!==void 0&&(clearTimeout(H),H=void 0),Q())}}),Le;if(c){let Y=!1;Le=c.subscribe(be=>{if(!Y){Y=!0;return}be.length>0&&!Ve&&Ke()})}let Ve=!1,Ke=()=>{if(Ve)return;Ve=!0,H!==void 0&&(clearTimeout(H),H=void 0),v&&Q(),ae=!0,Le?.(),xe();let Y=be=>{try{be.down([[de]])}catch{}};Y(R),Y(k),Y(w),Y(x),_&&Y(_),G&&Y(G);try{l?.()}catch{}},Je={dispose:Ke,sent:w,failed:k,inFlight:x,errors:R};return v&&(Je.buffered=_,Je.flush=async()=>{ae||(await Q(),await Promise.all(B))}),G&&(Je.paused=G),Je}Et();ve();function mt(t){return{describeKind:"producer",...t}}function la(t,e){let{parse:n,closeOnTeardown:r=!1,...o}=e??{};return W(s=>{let i=!0,a,u=()=>{let y=a;a=void 0,y?.()},c=y=>{i&&(i=!1,s.down([y]),u())},d=(y,b=y)=>{if(i)try{let v=y!==null&&typeof y=="object"&&"data"in y?y.data:y,T=n?n(v,b):v;s.emit(T)}catch(v){c([O,v])}},l=y=>{c([O,y])},f=()=>{c([M])};if(typeof t=="function"){try{if(a=t(d,l,f),typeof a!="function")throw new Error("fromWebSocket register contract violation: register must return cleanup callable")}catch(y){c([O,y])}return()=>{i=!1,u()}}let p=t,m=y=>d(y,y),h=y=>l(y),g=()=>f();return p.addEventListener("message",m),p.addEventListener("error",h),p.addEventListener("close",g),a=()=>{p.removeEventListener("message",m),p.removeEventListener("error",h),p.removeEventListener("close",g),r&&p.close()},()=>{i=!1,u()}},mt(o))}function Ed(t,e){return mn(t,e)}function pa(t,e){let{method:n="GET",headers:r,body:o,transform:s=v=>v.json(),timeoutNs:i=30*1e9,signal:a,completeAfterFetch:u=!1,refetchOnSubscribe:c=!1,...d}=e??{},l=N(0,{name:`${d.name??"http"}/fetchCount`}),f=N(0,{name:`${d.name??"http"}/lastUpdated`}),p=N(!1,{name:`${d.name??"http"}/fetched`}),m=0,h=o!==void 0?typeof o=="string"?o:JSON.stringify(o):void 0,g=v=>{let T=new AbortController,w=!0;if(a?.aborted)return w=!1,v.down([[O,a.reason??new Error("Aborted")]]),()=>{};a?.addEventListener("abort",()=>T.abort(a.reason),{once:!0});let k=setTimeout(()=>T.abort(new Error("Request timeout")),Math.ceil(i/1e6));return fetch(t,{method:n,headers:r,body:h,signal:T.signal}).then(async x=>{if(clearTimeout(k),!w)return;if(!x.ok)throw new Error(`HTTP ${x.status}: ${x.statusText}`);let R=await s(x);w&&(X(()=>{m+=1,l.down([[S,m]]),f.down([[S,le()]]),p.down([[S,!0]]),v.emit(R)}),u&&v.down([[M]]))}).catch(x=>{clearTimeout(k),w&&(x&&x.name==="AbortError"||v.down([[O,x]]))}),()=>{w=!1,T.abort()}},y=W(v=>g({emit:T=>v.emit(T),down:T=>v.down(T)}),{...mt(d),resubscribable:c});return{...Bt(y),fetchCount:l,lastUpdated:f,fetched:p}}function _d(t,e,n){let{method:r="POST",headers:o={"Content-Type":"application/json"},serialize:s=m=>JSON.stringify(m),timeoutNs:i,batchFormat:a="json-array",batchSize:u,flushIntervalMs:c,retry:d,onTransportError:l}=n??{},f=async m=>{let h=i!==void 0?new AbortController:void 0,g;h&&i!==void 0&&(g=setTimeout(()=>h.abort(new Error("Request timeout")),Math.ceil(i/1e6)));try{let y=await fetch(e,{method:r,headers:o,body:m,signal:h?.signal}),b=async()=>{try{await y.arrayBuffer?.()}catch{}};if(!y.ok)throw await b(),new Error(`HTTP ${y.status}: ${y.statusText}`);await b()}finally{g!==void 0&&clearTimeout(g)}};return u!==void 0||c!==void 0?je(t,{onTransportError:l,retry:d,batchSize:u,flushIntervalMs:c,sendBatch:async m=>{let h;a==="ndjson"?h=m.map(g=>{let y=s(g);return typeof y=="string"?y:new TextDecoder().decode(y)}).join(`
16
+ `):h=JSON.stringify(m),await f(h)}}):je(t,{onTransportError:l,retry:d,serialize:s,send:async m=>{await f(m)}})}function Md(t){return Symbol.keyFor(t)??t.description??"message"}function Qn(t,e){return typeof t=="string"?t:e(t)}function Od(t,e){let n=`event: ${t}
17
17
  `;if(e!==void 0){let r=e.split(/\r?\n/);for(let o of r)n+=`data: ${o}
18
18
  `}return`${n}
19
- `}function gd(t,e){let{serialize:n=p=>{if(p instanceof Error)return p.message;try{return JSON.stringify(p)}catch{return String(p)}},dataEvent:r="data",errorEvent:o="error",completeEvent:s="complete",includeResolved:i=!1,includeDirty:a=!1,keepAliveMs:u,signal:c,eventNameResolver:d=md}=e??{},l=new TextEncoder,f;return new ReadableStream({start(p){let m=!1,h,g=()=>{},y=()=>{m||(m=!0,h!==void 0&&clearInterval(h),c?.removeEventListener("abort",v),g(),p.close())};f=y;let b=(T,w)=>{m||p.enqueue(l.encode(hd(T,w)))},v=()=>{m||y()};g=t.subscribe(T=>{for(let w of T){let k=w[0];if(!(Ae.isLocalOnly(k)&&!(k===ee&&a))){if(k===S){b(r,Un(w[1],n));continue}if(k===M){b(o,Un(w[1],n)),y();return}if(k===_){b(s),y();return}!i&&k===B||b(d(k),w.length>1?Un(w[1],n):void 0)}}}),u!==void 0&&u>0&&(h=setInterval(()=>{m||p.enqueue(l.encode(`: keepalive
19
+ `}function Cd(t,e){let{serialize:n=p=>{if(p instanceof Error)return p.message;try{return JSON.stringify(p)}catch{return String(p)}},dataEvent:r="data",errorEvent:o="error",completeEvent:s="complete",includeResolved:i=!1,includeDirty:a=!1,keepAliveMs:u,signal:c,eventNameResolver:d=Md}=e??{},l=new TextEncoder,f;return new ReadableStream({start(p){let m=!1,h,g=()=>{},y=()=>{m||(m=!0,h!==void 0&&clearInterval(h),c?.removeEventListener("abort",v),g(),p.close())};f=y;let b=(T,w)=>{m||p.enqueue(l.encode(Od(T,w)))},v=()=>{m||y()};g=t.subscribe(T=>{for(let w of T){let k=w[0];if(!(Pe.isLocalOnly(k)&&!(k===ee&&a))){if(k===S){b(r,Qn(w[1],n));continue}if(k===O){b(o,Qn(w[1],n)),y();return}if(k===M){b(s),y();return}!i&&k===$||b(d(k),w.length>1?Qn(w[1],n):void 0)}}}),u!==void 0&&u>0&&(h=setInterval(()=>{m||p.enqueue(l.encode(`: keepalive
20
20
 
21
- `))},u)),c?.aborted?v():c?.addEventListener("abort",v,{once:!0})},cancel(){f?.()}})}function yd(t,e){let{serialize:n=f=>{if(f instanceof Error)return f.message;try{return JSON.stringify(f)}catch{return String(f)}},dataEvent:r="data",errorEvent:o="error",completeEvent:s="complete",includeResolved:i=!1,includeDirty:a=!1,keepAliveMs:u,signal:c,eventNameResolver:d=md}=e??{},l=new TextEncoder;return W(f=>{let p=!0,m,h=(b,v)=>{p&&f.emit(l.encode(hd(b,v)))},g=()=>{p&&(p=!1,f.down([[_]]))},y=t.subscribe(b=>{if(p)for(let v of b){let T=v[0];if(!(Ae.isLocalOnly(T)&&!(T===ee&&a))){if(T===S){h(r,Un(v[1],n));continue}if(T===M){h(o,Un(v[1],n)),p=!1,f.down([[_]]);return}if(T===_){h(s),p=!1,f.down([[_]]);return}!i&&T===B||h(d(T),v.length>1?Un(v[1],n):void 0)}}});return u!==void 0&&u>0&&(m=setInterval(()=>{p&&f.emit(l.encode(`: keepalive
21
+ `))},u)),c?.aborted?v():c?.addEventListener("abort",v,{once:!0})},cancel(){f?.()}})}function Ad(t,e){let{serialize:n=f=>{if(f instanceof Error)return f.message;try{return JSON.stringify(f)}catch{return String(f)}},dataEvent:r="data",errorEvent:o="error",completeEvent:s="complete",includeResolved:i=!1,includeDirty:a=!1,keepAliveMs:u,signal:c,eventNameResolver:d=Md}=e??{},l=new TextEncoder;return W(f=>{let p=!0,m,h=(b,v)=>{p&&f.emit(l.encode(Od(b,v)))},g=()=>{p&&(p=!1,f.down([[M]]))},y=t.subscribe(b=>{if(p)for(let v of b){let T=v[0];if(!(Pe.isLocalOnly(T)&&!(T===ee&&a))){if(T===S){h(r,Qn(v[1],n));continue}if(T===O){h(o,Qn(v[1],n)),p=!1,f.down([[M]]);return}if(T===M){h(s),p=!1,f.down([[M]]);return}!i&&T===$||h(d(T),v.length>1?Qn(v[1],n):void 0)}}});return u!==void 0&&u>0&&(m=setInterval(()=>{p&&f.emit(l.encode(`: keepalive
22
22
 
23
- `))},u)),c?.aborted?g():c?.addEventListener("abort",g,{once:!0}),()=>{p=!1,m!==void 0&&clearInterval(m),c?.removeEventListener("abort",g),y()}})}function bd(t){let e,n=!1;return new ReadableStream({start(r){e=t.subscribe(o=>{for(let s of o){let i=s[0];if(n)return;if(i===S)try{r.enqueue(s[1])}catch{n=!0,e?.()}else if(i===M){n=!0;try{r.error(s[1])}catch{}return}else if(i===_){n=!0;try{r.close()}catch{}return}}})},cancel(){n=!0,e?.()}})}function vd(t,e){let{parse:n=o=>o,...r}=e??{};return W(o=>{let s=!0,i=new TextDecoder,a="",u="message",c=[],d,l,f=()=>{if(c.length===0&&u==="message"&&d===void 0){c=[];return}let b=c.join(`
24
- `);o.emit({event:u,data:n(b),id:d,retry:l}),u="message",c=[],d=void 0,l=void 0},p=b=>{if(b===""){f();return}if(b.startsWith(":"))return;let v=b.indexOf(":"),T=v<0?b:b.slice(0,v),w=v<0?"":b.slice(v+1);switch(w.startsWith(" ")&&(w=w.slice(1)),T){case"event":u=w;break;case"data":c.push(w);break;case"id":w.includes("\0")||(d=w);break;case"retry":{let k=Number(w);Number.isFinite(k)&&(l=k);break}}},m=(b,v)=>{if(!s)return;a+=i.decode(b,{stream:!v});let T=a.split(/\r?\n/);a=T.pop()??"";for(let w of T)p(w)},h,g;return(async()=>{try{let b=t,v=t instanceof ReadableStream?t:b&&typeof b=="object"&&b.body instanceof ReadableStream?b.body:null;if(v){for(h=v.getReader();s;){let{value:T,done:w}=await h.read();if(w)break;m(T,!1)}m(new Uint8Array,!0)}else{for(g=t[Symbol.asyncIterator]();s;){let w=await g.next();if(w.done)break;m(w.value,!1)}m(new Uint8Array,!0)}if(a.trim()){for(let T of a.split(/\r?\n/))p(T);f()}s&&o.down([[_]])}catch(b){s&&o.down([[M,b]])}})(),()=>{s=!1,h&&h.cancel().catch(()=>{}),g&&typeof g.return=="function"&&Promise.resolve(g.return()).catch(()=>{})}},ct(r))}function Td(t,e){let{method:n="GET",headers:r,body:o,signal:s,...i}=e??{};return W(a=>{let u=!0,c=new AbortController;if(s?.aborted)return a.down([[M,s.reason??new Error("Aborted")]]),()=>{};s?.addEventListener("abort",()=>c.abort(s.reason),{once:!0});let d=o!==void 0?typeof o=="string"?o:JSON.stringify(o):void 0;return(async()=>{try{let f=await fetch(t,{method:n,headers:r,body:d,signal:c.signal});if(!u)return;if(!f.ok)throw new Error(`HTTP ${f.status}: ${f.statusText}`);if(!f.body)throw new Error("HTTP response has no body");let p=f.body.getReader();for(;u;){let{value:m,done:h}=await p.read();if(h)break;m&&a.emit(m)}u&&a.down([[_]])}catch(f){if(!u||f&&f.name==="AbortError")return;a.down([[M,f]])}})(),()=>{u=!1,c.abort()}},ct(i))}function wd(t,e){let{intervalMs:n=5e3,...r}=e??{};return be(et(n,{period:n}),()=>Yi(t,{...r,completeAfterFetch:!0}).node)}function kd(t,e,n){let{serialize:r=y=>{if(typeof y=="string"||y instanceof Blob||y instanceof ArrayBuffer||ArrayBuffer.isView(y))return y;try{return JSON.stringify(y)}catch{return String(y)}},closeOnComplete:o=!0,closeOnError:s=!0,closeCode:i,closeReason:a,onTransportError:u,retry:c,backpressure:d,stopOn:l}=n??{},f=!1,p=y=>{if(!f){f=!0;try{e.close(i,a)}catch(b){let v=b instanceof Error?b:new Error(String(b));try{u?.({stage:"close",error:v,value:void 0,message:y})}catch{}}}},m=null,g=$e(t,{onTransportError:u,serialize:y=>{let b=r(y);if(b===void 0)throw new Error("serialize returned undefined");return b},retry:c,backpressure:d,stopOn:l,onDispose:()=>{if(m){try{e.removeEventListener("close",m)}catch{}m=null}},send:y=>{e.send(y)},onUpstreamMessage:y=>{(y[0]===_&&o||y[0]===M&&s)&&p(y)}});return m=()=>{f=!0,g.dispose()},e.addEventListener("close",m),g}function xd(t,e){let{parse:n,maxRetries:r,backoff:o="exponential",closeOnTeardown:s=!0,...i}=e??{};return At(()=>Ji(t(),{parse:n,closeOnTeardown:s,...i}),{count:r,backoff:o})}function Rd(t,e){let{method:n="notifications/message",onDisconnect:r,...o}=e??{};return cn(({emit:s,error:i})=>(t.setNotificationHandler(n,a=>s(a)),r?.(a=>i(a??new Error("MCP client disconnected"))),()=>t.setNotificationHandler(n,()=>{})),o)}function Sd(t,e){return Yo(({traces:r,metrics:o,logs:s,error:i})=>t({onTraces:a=>{te(()=>{for(let u of a)r(u)})},onMetrics:a=>{te(()=>{for(let u of a)o(u)})},onLogs:a=>{te(()=>{for(let u of a)s(u)})},onError:i})??void 0,["traces","metrics","logs"],e?.name?{name:e.name}:void 0)}function Nd(t,e){return cn(t,e)}function Ed(t){let e=t.match(/^<(\d{1,3})>\d?\s*(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s*(.*)/s);if(!e){let r=pe();return{facility:1,severity:6,timestamp:new Date(Math.floor(r/1e6)).toISOString(),hostname:"-",appName:"-",procId:"-",msgId:"-",message:t.trim(),timestampNs:r}}let n=Number(e[1]);return{facility:n>>3,severity:n&7,timestamp:e[2],hostname:e[3],appName:e[4],procId:e[5],msgId:e[6],message:(e[7]??"").trim(),timestampNs:pe()}}function _d(t,e){return cn(t,e)}var wm={c:"counter",g:"gauge",ms:"timer",h:"histogram",s:"set",d:"distribution"};function Md(t){let e=t.split("|"),[n,r]=(e[0]??"").split(":");if(!n||r===void 0)throw new Error(`Invalid StatsD line: ${t}`);let o=e[1]?.trim()??"c",s=wm[o]??"counter",i=s==="set"?0:Number(r),a,u={};for(let c=2;c<e.length;c++){let d=e[c].trim();if(d.startsWith("@"))a=Number(d.slice(1));else if(d.startsWith("#"))for(let l of d.slice(1).split(",")){let[f,p]=l.split(":");f&&(u[f]=p??"")}}return{name:n.trim(),value:i,type:s,sampleRate:a,tags:u,timestampNs:pe()}}function Od(t,e){let{intervalNs:n=15*1e9,headers:r,timeoutNs:o=10*1e9,signal:s,maxConsecutiveErrors:i=1}=e??{},a=Math.ceil(n/1e6),u=0;return be(et(0,{period:a,signal:s}),()=>W(c=>{let d=!0,l=new AbortController,f=setTimeout(()=>l.abort(new Error("Scrape timeout")),Math.ceil(o/1e6));return(async()=>{try{let m=await fetch(t,{headers:{Accept:"text/plain",...r},signal:l.signal});if(clearTimeout(f),!d)return;if(!m.ok)throw new Error(`Prometheus scrape ${m.status}: ${m.statusText}`);let h=await m.text();if(!d)return;let g=Qi(h);for(let y of g)c.emit(y);u=0,c.down([[_]])}catch(m){if(clearTimeout(f),!d||m instanceof Error&&m.name==="AbortError")return;u+=1,u>=i&&c.down([[M,m]])}})(),()=>{d=!1,clearTimeout(f),l.abort()}}))}function Qi(t){let e=[],n=new Map,r=new Map;for(let o of t.split(`
25
- `)){let s=o.trim();if(!s)continue;if(s.startsWith("# TYPE ")){let f=s.slice(7),p=f.indexOf(" ");p>0&&n.set(f.slice(0,p),f.slice(p+1).trim());continue}if(s.startsWith("# HELP ")){let f=s.slice(7),p=f.indexOf(" ");p>0&&r.set(f.slice(0,p),f.slice(p+1).trim());continue}if(s.startsWith("#"))continue;let i,a={},u,c,d=s.indexOf("{");if(d>=0){i=s.slice(0,d);let f=s.indexOf("}",d);if(f<0)continue;let p=s.slice(d+1,f);a=km(p);let m=s.slice(f+1).trim().split(/\s+/);u=m[0]??"",c=m[1]}else{let f=s.split(/\s+/);i=f[0]??"",u=f[1]??"",c=f[2]}if(!i||!u)continue;let l=i.replace(/(_total|_count|_sum|_bucket|_created|_info)$/,"");e.push({name:i,labels:a,value:Number(u),timestampMs:c?Number(c):void 0,type:n.get(l)??n.get(i),help:r.get(l)??r.get(i),timestampNs:pe()})}return e}function km(t){let e={},n=/(\w+)="((?:[^"\\]|\\.)*)"/g,r=n.exec(t);for(;r!==null;)e[r[1]]=r[2].replace(/\\(.)/g,"$1"),r=n.exec(t);return e}function Cd(t,e,n){let{fromBeginning:r=!1,deserialize:o=i=>{if(i===null)return null;try{return JSON.parse(i.toString())}catch{return i.toString()}},...s}=n??{};return W(i=>{let a=!0;return(async()=>{try{await t.subscribe({topic:e,fromBeginning:r}),await t.run({eachMessage:async({topic:c,partition:d,message:l})=>{if(!a)return;let f={};if(l.headers)for(let[p,m]of Object.entries(l.headers))m!==void 0&&(f[p]=typeof m=="string"?m:m.toString());i.emit({topic:c,partition:d,key:l.key?.toString()??null,value:o(l.value),headers:f,offset:l.offset,timestamp:l.timestamp,timestampNs:pe()})}})}catch(c){a&&i.down([[M,c]])}})(),()=>{a=!1}},ct(s))}function Ad(t,e,n,r){let{serialize:o=a=>JSON.stringify(a),keyExtractor:s,onTransportError:i}=r??{};return $e(t,{onTransportError:i,send:async a=>{let u=s?.(a)??null,c=o(a);await e.send({topic:n,messages:[{key:u,value:Buffer.from(c)}]})}})}function Ld(t,e,n){let{blockMs:r=5e3,startId:o="$",parse:s=a=>{for(let c=0;c<a.length;c+=2)if(a[c]==="data")try{return JSON.parse(a[c+1])}catch{return a[c+1]}let u={};for(let c=0;c<a.length;c+=2)u[a[c]]=a[c+1];return u},...i}=n??{};return W(a=>{let u=!0,c=o;return(async()=>{for(;u;)try{let l=await t.xread("BLOCK",r,"STREAMS",e,c);if(!u)return;if(l)for(let[f,p]of l)for(let[m,h]of p)c=m,a.emit({id:m,key:e,data:s(h),timestampNs:pe()})}catch(l){if(!u)return;a.down([[M,l]]);return}})(),()=>{u=!1}},ct(i))}function Id(t,e,n,r){let{serialize:o=a=>["data",JSON.stringify(a)],maxLen:s,onTransportError:i}=r??{};return $e(t,{onTransportError:i,send:async a=>{let u=o(a);await(s!==void 0?e.xadd(n,"MAXLEN","~",String(s),"*",...u):e.xadd(n,"*",...u))}})}function Pd(t,e){let{delimiter:n=",",hasHeader:r=!0,columns:o,parseLine:s,...i}=e??{},a=s??(u=>Fd(u,n));return W(u=>{let c=!1;return(async()=>{try{let l=o,f="";for await(let p of t){if(c)return;f+=p;let m=f.split(/\r?\n/);f=m.pop()??"";for(let h of m){if(c)return;if(!h.trim())continue;let g=a(h);if(!l&&r){l=g;continue}l||(l=g.map((b,v)=>`col${v}`));let y={};for(let b=0;b<l.length;b++)y[l[b]]=g[b]??"";u.emit(y)}}if(!c&&f.trim()){let p=a(f);if(l){let m={};for(let h=0;h<l.length;h++)m[l[h]]=p[h]??"";u.emit(m)}}c||u.down([[_]])}catch(l){c||u.down([[M,l]])}})(),()=>{c=!0}},ct(i))}function Dd(t,e){let{delimiter:n=",",hasHeader:r=!0,columns:o,parseLine:s,...i}=e??{},a=s??(u=>Fd(u,n));return K([t],(u,c,d)=>{let l=u[0];if(l==null||l.length===0)return;let f=d.store;typeof f.buffer!="string"&&(f.buffer=""),f.headers===void 0&&o&&(f.headers=o.slice());for(let p of l){f.buffer=f.buffer+p;let m=f.buffer.split(/\r?\n/);f.buffer=m.pop()??"";for(let h of m){if(!h.trim())continue;let g=a(h);if(!f.headers&&r){f.headers=g;continue}f.headers||(f.headers=g.map((b,v)=>`col${v}`));let y={};for(let b=0;b<f.headers.length;b++)y[f.headers[b]]=g[b]??"";c.emit(y)}}},{describeKind:"derived",...i})}function Gd(t,e){return K([t],(n,r,o)=>{let s=n[0];if(s==null||s.length===0)return;let i=o.store;typeof i.buffer!="string"&&(i.buffer="");for(let a of s){i.buffer=i.buffer+a;let u=i.buffer.split(/\r?\n/);i.buffer=u.pop()??"";for(let c of u)if(c.trim())try{r.emit(JSON.parse(c))}catch(d){r.down([[M,d]]);return}}},{describeKind:"derived",...e??{}})}function Fd(t,e){let n=[],r="",o=!1;for(let s=0;s<t.length;s++){let i=t[s];o?i==='"'?t[s+1]==='"'?(r+='"',s++):o=!1:r+=i:i==='"'?o=!0:i===e?(n.push(r),r=""):r+=i}return n.push(r),n}function $d(t,e){return W(n=>{let r=!1;return(async()=>{try{let s="";for await(let i of t){if(r)return;s+=i;let a=s.split(/\r?\n/);s=a.pop()??"";for(let u of a){if(r)return;let c=u.trim();c&&n.emit(JSON.parse(c))}}!r&&s.trim()&&n.emit(JSON.parse(s.trim())),r||n.down([[_]])}catch(s){r||n.down([[M,s]])}})(),()=>{r=!0}},ct(e))}function Bd(t,e,n){let{intervalNs:r=5*1e9,format:o="JSONEachRow",signal:s,maxConsecutiveErrors:i=1}=n??{},a=Math.ceil(r/1e6),u=0;return be(et(0,{period:a,signal:s}),()=>W(c=>{let d=!0;return(async()=>{try{let f=await t.query({query:e,format:o});if(!d)return;let p=await f.json();if(!d)return;for(let m of p)c.emit(m);u=0,c.down([[_]])}catch(f){if(!d)return;u+=1,u>=i&&c.down([[M,f]])}})(),()=>{d=!1}}))}function jd(t,e){let{autoAck:n=!0,deserialize:r=a=>{try{return JSON.parse(a.toString())}catch{return a.toString()}},onAckError:o,...s}=e??{},i=a=>{if(o)try{o(a instanceof Error?a:new Error(String(a)))}catch{}};return W(a=>{let u=!0;return(async()=>{for(;u;)try{let d=await t.receive();if(!u)return;let l={topic:d.getTopicName(),messageId:d.getMessageId().toString(),key:d.getPartitionKey(),value:r(d.getData()),properties:d.getProperties(),publishTime:d.getPublishTimestamp(),eventTime:d.getEventTimestamp(),timestampNs:pe()};if(n)a.emit(l),t.acknowledge(d).catch(i);else{let f=!1,p={value:l,ack(){f||(f=!0,t.acknowledge(d).catch(i))},nack(m){if(f)return;f=!0;let h=t;try{let g=h.negativeAcknowledge?.(d);g&&typeof g.then=="function"&&g.catch(i)}catch(g){i(g)}}};a.emit(p)}}catch(d){u&&a.down([[M,d]]);return}})(),()=>{u=!1}},ct(s))}function Vd(t,e,n){let{serialize:r=a=>Buffer.from(JSON.stringify(a)),keyExtractor:o,propertiesExtractor:s,onTransportError:i}=n??{};return $e(t,{onTransportError:i,send:async a=>{await e.send({data:r(a),partitionKey:o?.(a),properties:s?.(a)})}})}function Kd(t,e,n){let r=new TextDecoder,{queue:o,deserialize:s=a=>{let u=r.decode(a);try{return JSON.parse(u)}catch{return u}},...i}=n??{};return W(a=>{let u=!0,c=t.subscribe(e,o?{queue:o}:void 0);return(async()=>{try{for await(let l of c){if(!u)return;let f={};if(l.headers)for(let p of l.headers.keys())f[p]=l.headers.get(p);a.emit({subject:l.subject,data:s(l.data),headers:f,reply:l.reply,sid:l.sid,timestampNs:pe()})}u&&a.down([[_]])}catch(l){u&&a.down([[M,l]])}})(),()=>{u=!1}},ct(i))}function Hd(t,e,n,r){let o=new TextEncoder,{serialize:s=a=>o.encode(JSON.stringify(a)),onTransportError:i}=r??{};return $e(t,{onTransportError:i,send:a=>{e.publish(n,s(a))}})}function Wd(t,e,n){let{autoAck:r=!0,deserialize:o=u=>{try{return JSON.parse(u.toString())}catch{return u.toString()}},onAckError:s,...i}=n??{},a=u=>{if(s)try{s(u instanceof Error?u:new Error(String(u)))}catch{}};return W(u=>{let c=!0,d;return(async()=>{try{d=(await t.consume(e,p=>{if(!c)return;if(p===null){c&&u.down([[M,new Error("Consumer cancelled by broker")]]);return}let m={queue:e,routingKey:p.fields.routingKey,exchange:p.fields.exchange,content:o(p.content),properties:p.properties,deliveryTag:p.fields.deliveryTag,redelivered:p.fields.redelivered,timestampNs:pe()};if(r){u.emit(m);try{t.ack(p)}catch(h){a(h)}}else{let h=!1,g=t,y={value:m,ack(){if(!h){h=!0;try{t.ack(p)}catch(b){a(b)}}},nack(b){if(h)return;h=!0;let v=b?.requeue;if(!g.nack){a(new Error("RabbitMQ channel does not expose `nack`; cannot negative-ack"));return}try{g.nack(p,!1,v)}catch(T){a(T)}}};u.emit(y)}},{noAck:!1})).consumerTag}catch(f){c&&u.down([[M,f]])}})(),()=>{c=!1,d!==void 0&&t.cancel(d)}},ct(i))}function qd(t,e,n,r){let{serialize:o=a=>Buffer.from(JSON.stringify(a)),routingKeyExtractor:s=()=>"",onTransportError:i}=r??{};return $e(t,{onTransportError:i,send:a=>{let u=s(a),c=o(a);e.publish(n,u,c)}})}function Xi(t,e,n){let{serialize:r=l=>`${JSON.stringify(l)}
26
- `,flushIntervalMs:o=0,batchSize:s=Number.POSITIVE_INFINITY,onTransportError:i,mode:a}=n??{},c=o>0||s<Number.POSITIVE_INFINITY?$e(t,{onTransportError:i,batchSize:s,flushIntervalMs:o,serialize:r,sendBatch:l=>{e.write(l.join(""))}}):$e(t,{onTransportError:i,serialize:r,send:l=>{e.write(l)}}),d=c.dispose;return c.dispose=()=>{d();try{e.end()}catch{}},c}function zi(t,e){return t.includes(e)||t.includes('"')||t.includes(`
27
- `)?`"${t.replace(/"/g,'""')}"`:t}function Ud(t,e,n){let{columns:r,delimiter:o=",",writeHeader:s=!0,cellExtractor:i=(p,m)=>String(p[m]??""),flushIntervalMs:a=0,batchSize:u=Number.POSITIVE_INFINITY,onTransportError:c,...d}=n,l=!1;return Xi(t,e,{serialize:p=>{if(!l&&s){l=!0;let m=r.map(g=>zi(g,o)).join(o),h=r.map(g=>zi(i(p,g),o)).join(o);return`${m}
23
+ `))},u)),c?.aborted?g():c?.addEventListener("abort",g,{once:!0}),()=>{p=!1,m!==void 0&&clearInterval(m),c?.removeEventListener("abort",g),y()}})}function Ld(t){let e,n=!1;return new ReadableStream({start(r){e=t.subscribe(o=>{for(let s of o){let i=s[0];if(n)return;if(i===S)try{r.enqueue(s[1])}catch{n=!0,e?.()}else if(i===O){n=!0;try{r.error(s[1])}catch{}return}else if(i===M){n=!0;try{r.close()}catch{}return}}})},cancel(){n=!0,e?.()}})}async function*At(t,e){let n=e?.parse??(w=>w),r=e?.signal,o=new TextDecoder,s="",i="message",a=[],u,c,d=[],l=()=>{if(a.length===0&&i==="message"&&u===void 0){a=[];return}let w=a.join(`
24
+ `);d.push({event:i,data:n(w),id:u,retry:c}),i="message",a=[],u=void 0,c=void 0},f=w=>{if(w===""){l();return}if(w.startsWith(":"))return;let k=w.indexOf(":"),x=k<0?w:w.slice(0,k),R=k<0?"":w.slice(k+1);switch(R.startsWith(" ")&&(R=R.slice(1)),x){case"event":i=R;break;case"data":a.push(R);break;case"id":R.includes("\0")||(u=R);break;case"retry":{let _=Number(R);Number.isFinite(_)&&(c=_);break}}},p=(w,k)=>{s+=o.decode(w,{stream:!k});let x=s.split(/\r?\n/);s=x.pop()??"";for(let R of x)f(R)},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(p(w,!1);d.length>0;)yield d.shift()}p(new Uint8Array,!0)}else{for(y=t[Symbol.asyncIterator]();!r?.aborted;){let k=await y.next();if(k.done)break;for(p(k.value,!1);d.length>0;)yield d.shift()}p(new Uint8Array,!0)}if(s.trim()){for(let w of s.split(/\r?\n/))f(w);l()}for(;d.length>0;)yield d.shift()}finally{r&&r.removeEventListener("abort",T),v()}}function Id(t,e){let{parse:n,...r}=e??{};return W(o=>{let s=!0,i=new AbortController;return(async()=>{try{for await(let u of At(t,{parse:n,signal:i.signal})){if(!s)return;o.emit(u)}s&&o.down([[M]])}catch(u){s&&o.down([[O,u]])}})(),()=>{s=!1,i.abort()}},mt(r))}function Pd(t,e){let{method:n="GET",headers:r,body:o,signal:s,...i}=e??{};return W(a=>{let u=!0,c=new AbortController;if(s?.aborted)return a.down([[O,s.reason??new Error("Aborted")]]),()=>{};s?.addEventListener("abort",()=>c.abort(s.reason),{once:!0});let d=o!==void 0?typeof o=="string"?o:JSON.stringify(o):void 0;return(async()=>{try{let f=await fetch(t,{method:n,headers:r,body:d,signal:c.signal});if(!u)return;if(!f.ok)throw new Error(`HTTP ${f.status}: ${f.statusText}`);if(!f.body)throw new Error("HTTP response has no body");let p=f.body.getReader();for(;u;){let{value:m,done:h}=await p.read();if(h)break;m&&a.emit(m)}u&&a.down([[M]])}catch(f){if(!u||f&&f.name==="AbortError")return;a.down([[O,f]])}})(),()=>{u=!1,c.abort()}},mt(i))}function Dd(t,e){let{intervalMs:n=5e3,...r}=e??{};return Te(at(n,{period:n}),()=>pa(t,{...r,completeAfterFetch:!0}).node)}function Gd(t,e,n){let{serialize:r=y=>{if(typeof y=="string"||y instanceof Blob||y instanceof ArrayBuffer||ArrayBuffer.isView(y))return y;try{return JSON.stringify(y)}catch{return String(y)}},closeOnComplete:o=!0,closeOnError:s=!0,closeCode:i,closeReason:a,onTransportError:u,retry:c,backpressure:d,stopOn:l}=n??{},f=!1,p=y=>{if(!f){f=!0;try{e.close(i,a)}catch(b){let v=b instanceof Error?b:new Error(String(b));try{u?.({stage:"close",error:v,value:void 0,message:y})}catch{}}}},m=null,g=je(t,{onTransportError:u,serialize:y=>{let b=r(y);if(b===void 0)throw new Error("serialize returned undefined");return b},retry:c,backpressure:d,stopOn:l,onDispose:()=>{if(m){try{e.removeEventListener("close",m)}catch{}m=null}},send:y=>{e.send(y)},onUpstreamMessage:y=>{(y[0]===M&&o||y[0]===O&&s)&&p(y)}});return m=()=>{f=!0,g.dispose()},e.addEventListener("close",m),g}function Fd(t,e){let{parse:n,maxRetries:r,backoff:o="exponential",closeOnTeardown:s=!0,...i}=e??{};return Ft(()=>la(t(),{parse:n,closeOnTeardown:s,...i}),{count:r,backoff:o})}function $d(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 Bd(t,e){return ds(({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 jd(t,e){return mn(t,e)}function Vd(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=le();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:le()}}function Kd(t,e){return mn(t,e)}var Am={c:"counter",g:"gauge",ms:"timer",h:"histogram",s:"set",d:"distribution"};function Hd(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=Am[o]??"counter",i=s==="set"?0:Number(r),a,u={};for(let c=2;c<e.length;c++){let d=e[c].trim();if(d.startsWith("@"))a=Number(d.slice(1));else if(d.startsWith("#"))for(let l of d.slice(1).split(",")){let[f,p]=l.split(":");f&&(u[f]=p??"")}}return{name:n.trim(),value:i,type:s,sampleRate:a,tags:u,timestampNs:le()}}function Wd(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(at(0,{period:a,signal:s}),()=>W(c=>{let d=!0,l=new AbortController,f=setTimeout(()=>l.abort(new Error("Scrape timeout")),Math.ceil(o/1e6));return(async()=>{try{let m=await fetch(t,{headers:{Accept:"text/plain",...r},signal:l.signal});if(clearTimeout(f),!d)return;if(!m.ok)throw new Error(`Prometheus scrape ${m.status}: ${m.statusText}`);let h=await m.text();if(!d)return;let g=fa(h);for(let y of g)c.emit(y);u=0,c.down([[M]])}catch(m){if(clearTimeout(f),!d||m instanceof Error&&m.name==="AbortError")return;u+=1,u>=i&&c.down([[O,m]])}})(),()=>{d=!1,clearTimeout(f),l.abort()}}))}function fa(t){let e=[],n=new Map,r=new Map;for(let o of t.split(`
25
+ `)){let s=o.trim();if(!s)continue;if(s.startsWith("# TYPE ")){let f=s.slice(7),p=f.indexOf(" ");p>0&&n.set(f.slice(0,p),f.slice(p+1).trim());continue}if(s.startsWith("# HELP ")){let f=s.slice(7),p=f.indexOf(" ");p>0&&r.set(f.slice(0,p),f.slice(p+1).trim());continue}if(s.startsWith("#"))continue;let i,a={},u,c,d=s.indexOf("{");if(d>=0){i=s.slice(0,d);let f=s.indexOf("}",d);if(f<0)continue;let p=s.slice(d+1,f);a=Lm(p);let m=s.slice(f+1).trim().split(/\s+/);u=m[0]??"",c=m[1]}else{let f=s.split(/\s+/);i=f[0]??"",u=f[1]??"",c=f[2]}if(!i||!u)continue;let l=i.replace(/(_total|_count|_sum|_bucket|_created|_info)$/,"");e.push({name:i,labels:a,value:Number(u),timestampMs:c?Number(c):void 0,type:n.get(l)??n.get(i),help:r.get(l)??r.get(i),timestampNs:le()})}return e}function Lm(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 qd(t,e,n){let{fromBeginning:r=!1,deserialize:o=i=>{if(i===null)return null;try{return JSON.parse(i.toString())}catch{return i.toString()}},...s}=n??{};return W(i=>{let a=!0;return(async()=>{try{await t.subscribe({topic:e,fromBeginning:r}),await t.run({eachMessage:async({topic:c,partition:d,message:l})=>{if(!a)return;let f={};if(l.headers)for(let[p,m]of Object.entries(l.headers))m!==void 0&&(f[p]=typeof m=="string"?m:m.toString());i.emit({topic:c,partition:d,key:l.key?.toString()??null,value:o(l.value),headers:f,offset:l.offset,timestamp:l.timestamp,timestampNs:le()})}})}catch(c){a&&i.down([[O,c]])}})(),()=>{a=!1}},mt(s))}function Ud(t,e,n,r){let{serialize:o=a=>JSON.stringify(a),keyExtractor:s,onTransportError:i}=r??{};return je(t,{onTransportError:i,send:async a=>{let u=s?.(a)??null,c=o(a);await e.send({topic:n,messages:[{key:u,value:Buffer.from(c)}]})}})}function zd(t,e,n){let{blockMs:r=5e3,startId:o="$",parse:s=a=>{for(let c=0;c<a.length;c+=2)if(a[c]==="data")try{return JSON.parse(a[c+1])}catch{return a[c+1]}let u={};for(let c=0;c<a.length;c+=2)u[a[c]]=a[c+1];return u},...i}=n??{};return W(a=>{let u=!0,c=o;return(async()=>{for(;u;)try{let l=await t.xread("BLOCK",r,"STREAMS",e,c);if(!u)return;if(l)for(let[f,p]of l)for(let[m,h]of p)c=m,a.emit({id:m,key:e,data:s(h),timestampNs:le()})}catch(l){if(!u)return;a.down([[O,l]]);return}})(),()=>{u=!1}},mt(i))}function Jd(t,e,n,r){let{serialize:o=a=>["data",JSON.stringify(a)],maxLen:s,onTransportError:i}=r??{};return je(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 Yd(t,e){let{delimiter:n=",",hasHeader:r=!0,columns:o,parseLine:s,...i}=e??{},a=s??(u=>Zd(u,n));return W(u=>{let c=!1;return(async()=>{try{let l=o,f="";for await(let p of t){if(c)return;f+=p;let m=f.split(/\r?\n/);f=m.pop()??"";for(let h of m){if(c)return;if(!h.trim())continue;let g=a(h);if(!l&&r){l=g;continue}l||(l=g.map((b,v)=>`col${v}`));let y={};for(let b=0;b<l.length;b++)y[l[b]]=g[b]??"";u.emit(y)}}if(!c&&f.trim()){let p=a(f);if(l){let m={};for(let h=0;h<l.length;h++)m[l[h]]=p[h]??"";u.emit(m)}}c||u.down([[M]])}catch(l){c||u.down([[O,l]])}})(),()=>{c=!0}},mt(i))}function Qd(t,e){let{delimiter:n=",",hasHeader:r=!0,columns:o,parseLine:s,...i}=e??{},a=s??(u=>Zd(u,n));return K([t],(u,c,d)=>{let l=u[0];if(l==null||l.length===0)return;let f=d.store;typeof f.buffer!="string"&&(f.buffer=""),f.headers===void 0&&o&&(f.headers=o.slice());for(let p of l){f.buffer=f.buffer+p;let m=f.buffer.split(/\r?\n/);f.buffer=m.pop()??"";for(let h of m){if(!h.trim())continue;let g=a(h);if(!f.headers&&r){f.headers=g;continue}f.headers||(f.headers=g.map((b,v)=>`col${v}`));let y={};for(let b=0;b<f.headers.length;b++)y[f.headers[b]]=g[b]??"";c.emit(y)}}},{describeKind:"derived",...i})}function Xd(t,e){return K([t],(n,r,o)=>{let s=n[0];if(s==null||s.length===0)return;let i=o.store;typeof i.buffer!="string"&&(i.buffer="");for(let a of s){i.buffer=i.buffer+a;let u=i.buffer.split(/\r?\n/);i.buffer=u.pop()??"";for(let c of u)if(c.trim())try{r.emit(JSON.parse(c))}catch(d){r.down([[O,d]]);return}}},{describeKind:"derived",...e??{}})}function Zd(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 el(t,e){return W(n=>{let r=!1;return(async()=>{try{let s="";for await(let i of t){if(r)return;s+=i;let a=s.split(/\r?\n/);s=a.pop()??"";for(let u of a){if(r)return;let c=u.trim();c&&n.emit(JSON.parse(c))}}!r&&s.trim()&&n.emit(JSON.parse(s.trim())),r||n.down([[M]])}catch(s){r||n.down([[O,s]])}})(),()=>{r=!0}},mt(e))}function tl(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(at(0,{period:a,signal:s}),()=>W(c=>{let d=!0;return(async()=>{try{let f=await t.query({query:e,format:o});if(!d)return;let p=await f.json();if(!d)return;for(let m of p)c.emit(m);u=0,c.down([[M]])}catch(f){if(!d)return;u+=1,u>=i&&c.down([[O,f]])}})(),()=>{d=!1}}))}function nl(t,e){let{autoAck:n=!0,deserialize:r=a=>{try{return JSON.parse(a.toString())}catch{return a.toString()}},onAckError:o,...s}=e??{},i=a=>{if(o)try{o(a instanceof Error?a:new Error(String(a)))}catch{}};return W(a=>{let u=!0;return(async()=>{for(;u;)try{let d=await t.receive();if(!u)return;let l={topic:d.getTopicName(),messageId:d.getMessageId().toString(),key:d.getPartitionKey(),value:r(d.getData()),properties:d.getProperties(),publishTime:d.getPublishTimestamp(),eventTime:d.getEventTimestamp(),timestampNs:le()};if(n)a.emit(l),t.acknowledge(d).catch(i);else{let f=!1,p={value:l,ack(){f||(f=!0,t.acknowledge(d).catch(i))},nack(m){if(f)return;f=!0;let h=t;try{let g=h.negativeAcknowledge?.(d);g&&typeof g.then=="function"&&g.catch(i)}catch(g){i(g)}}};a.emit(p)}}catch(d){u&&a.down([[O,d]]);return}})(),()=>{u=!1}},mt(s))}function rl(t,e,n){let{serialize:r=a=>Buffer.from(JSON.stringify(a)),keyExtractor:o,propertiesExtractor:s,onTransportError:i}=n??{};return je(t,{onTransportError:i,send:async a=>{await e.send({data:r(a),partitionKey:o?.(a),properties:s?.(a)})}})}function ol(t,e,n){let r=new TextDecoder,{queue:o,deserialize:s=a=>{let u=r.decode(a);try{return JSON.parse(u)}catch{return u}},...i}=n??{};return W(a=>{let u=!0,c=t.subscribe(e,o?{queue:o}:void 0);return(async()=>{try{for await(let l of c){if(!u)return;let f={};if(l.headers)for(let p of l.headers.keys())f[p]=l.headers.get(p);a.emit({subject:l.subject,data:s(l.data),headers:f,reply:l.reply,sid:l.sid,timestampNs:le()})}u&&a.down([[M]])}catch(l){u&&a.down([[O,l]])}})(),()=>{u=!1}},mt(i))}function sl(t,e,n,r){let o=new TextEncoder,{serialize:s=a=>o.encode(JSON.stringify(a)),onTransportError:i}=r??{};return je(t,{onTransportError:i,send:a=>{e.publish(n,s(a))}})}function il(t,e,n){let{autoAck:r=!0,deserialize:o=u=>{try{return JSON.parse(u.toString())}catch{return u.toString()}},onAckError:s,...i}=n??{},a=u=>{if(s)try{s(u instanceof Error?u:new Error(String(u)))}catch{}};return W(u=>{let c=!0,d;return(async()=>{try{d=(await t.consume(e,p=>{if(!c)return;if(p===null){c&&u.down([[O,new Error("Consumer cancelled by broker")]]);return}let m={queue:e,routingKey:p.fields.routingKey,exchange:p.fields.exchange,content:o(p.content),properties:p.properties,deliveryTag:p.fields.deliveryTag,redelivered:p.fields.redelivered,timestampNs:le()};if(r){u.emit(m);try{t.ack(p)}catch(h){a(h)}}else{let h=!1,g=t,y={value:m,ack(){if(!h){h=!0;try{t.ack(p)}catch(b){a(b)}}},nack(b){if(h)return;h=!0;let v=b?.requeue;if(!g.nack){a(new Error("RabbitMQ channel does not expose `nack`; cannot negative-ack"));return}try{g.nack(p,!1,v)}catch(T){a(T)}}};u.emit(y)}},{noAck:!1})).consumerTag}catch(f){c&&u.down([[O,f]])}})(),()=>{c=!1,d!==void 0&&t.cancel(d)}},mt(i))}function al(t,e,n,r){let{serialize:o=a=>Buffer.from(JSON.stringify(a)),routingKeyExtractor:s=()=>"",onTransportError:i}=r??{};return je(t,{onTransportError:i,send:a=>{let u=s(a),c=o(a);e.publish(n,u,c)}})}function ma(t,e,n){let{serialize:r=l=>`${JSON.stringify(l)}
26
+ `,flushIntervalMs:o=0,batchSize:s=Number.POSITIVE_INFINITY,onTransportError:i,mode:a}=n??{},c=o>0||s<Number.POSITIVE_INFINITY?je(t,{onTransportError:i,batchSize:s,flushIntervalMs:o,serialize:r,sendBatch:l=>{e.write(l.join(""))}}):je(t,{onTransportError:i,serialize:r,send:l=>{e.write(l)}}),d=c.dispose;return c.dispose=()=>{d();try{e.end()}catch{}},c}function da(t,e){return t.includes(e)||t.includes('"')||t.includes(`
27
+ `)?`"${t.replace(/"/g,'""')}"`:t}function ul(t,e,n){let{columns:r,delimiter:o=",",writeHeader:s=!0,cellExtractor:i=(p,m)=>String(p[m]??""),flushIntervalMs:a=0,batchSize:u=Number.POSITIVE_INFINITY,onTransportError:c,...d}=n,l=!1;return ma(t,e,{serialize:p=>{if(!l&&s){l=!0;let m=r.map(g=>da(g,o)).join(o),h=r.map(g=>da(i(p,g),o)).join(o);return`${m}
28
28
  ${h}
29
- `}return`${r.map(m=>zi(i(p,m),o)).join(o)}
30
- `},flushIntervalMs:a,batchSize:u,onTransportError:c,...d})}function zd(t,e,n,r){let{batchSize:o=1e3,flushIntervalMs:s=5e3,format:i="JSONEachRow",transform:a=c=>c,onTransportError:u}=r??{};return $e(t,{onTransportError:u,batchSize:o,flushIntervalMs:s,serialize:a,sendBatch:async c=>{await e.insert({table:n,values:c,format:i})}})}function Jd(t,e,n,r){let{format:o="ndjson",keyGenerator:s=(f,p)=>{let m=Math.floor(p/1e6);return`data/${new Date(m).toISOString().replace(/[:.]/g,"-")}-${f}.${o==="ndjson"?"ndjson":"json"}`},batchSize:i=1e3,flushIntervalMs:a=1e4,transform:u=f=>f,onTransportError:c}=r??{},d=o==="ndjson"?"application/x-ndjson":"application/json",l=0;return $e(t,{onTransportError:c,batchSize:i,flushIntervalMs:a,serialize:u,sendBatch:async f=>{l+=1;let p=o==="ndjson"?`${f.map(h=>JSON.stringify(h)).join(`
29
+ `}return`${r.map(m=>da(i(p,m),o)).join(o)}
30
+ `},flushIntervalMs:a,batchSize:u,onTransportError:c,...d})}function cl(t,e,n,r){let{batchSize:o=1e3,flushIntervalMs:s=5e3,format:i="JSONEachRow",transform:a=c=>c,onTransportError:u}=r??{};return je(t,{onTransportError:u,batchSize:o,flushIntervalMs:s,serialize:a,sendBatch:async c=>{await e.insert({table:n,values:c,format:i})}})}function dl(t,e,n,r){let{format:o="ndjson",keyGenerator:s=(f,p)=>{let m=Math.floor(p/1e6);return`data/${new Date(m).toISOString().replace(/[:.]/g,"-")}-${f}.${o==="ndjson"?"ndjson":"json"}`},batchSize:i=1e3,flushIntervalMs:a=1e4,transform:u=f=>f,onTransportError:c}=r??{},d=o==="ndjson"?"application/x-ndjson":"application/json",l=0;return je(t,{onTransportError:c,batchSize:i,flushIntervalMs:a,serialize:u,sendBatch:async f=>{l+=1;let p=o==="ndjson"?`${f.map(h=>JSON.stringify(h)).join(`
31
31
  `)}
32
- `:JSON.stringify(f),m=s(l,pe());await e.putObject({Bucket:n,Key:m,Body:p,ContentType:d})}})}function Yd(t,e,n,r){let{toSQL:o=(i,a)=>({sql:`INSERT INTO "${a.replace(/"/g,'""')}" (data) VALUES ($1)`,params:[JSON.stringify(i)]}),onTransportError:s}=r??{};return $e(t,{onTransportError:s,serialize:i=>o(i,n),send:async i=>{let a=i;await e.query(a.sql,a.params)}})}function Qd(t,e,n){let{toDocument:r=s=>s,onTransportError:o}=n??{};return $e(t,{onTransportError:o,serialize:r,send:async s=>{await e.insertOne(s)}})}function Xd(t,e,n){let{labels:r={},toLine:o=a=>JSON.stringify(a),toLabels:s,onTransportError:i}=n??{};return $e(t,{onTransportError:i,serialize:a=>({line:o(a),labels:s?{...r,...s(a)}:r}),send:async a=>{let{line:u,labels:c}=a,d=`${pe()}`;await e.push({streams:[{stream:c,values:[[d,u]]}]})}})}function Zd(t,e,n){let{toResourceSpans:r=s=>[s],onTransportError:o}=n??{};return $e(t,{onTransportError:o,serialize:r,send:async s=>{await e.push({resourceSpans:s})}})}function el(t,e,n,r){let{prefix:o="checkpoints/",debounceMs:s=500,compactEvery:i=10,onError:a}=r??{},u={debounceMs:s,compactEvery:i,save(c,d){let l=Math.floor(pe()/1e6),f=`${o}${t.name}/checkpoint-${l}.json`,p;try{p=JSON.stringify(d)}catch(m){a?.(m);return}e.putObject({Bucket:n,Key:f,Body:p,ContentType:"application/json"}).catch(m=>a?.(m))},load(){return null}};return t.attachStorage([u],{onError:c=>a?.(c)})}function tl(t,e,n){let{prefix:r="graphrefly:checkpoint:",debounceMs:o=500,compactEvery:s=10,onError:i}=n??{},a=`${r}${t.name}`,u={debounceMs:o,compactEvery:s,save(c,d){let l;try{l=JSON.stringify(d)}catch(f){i?.(f);return}e.set(a,l).catch(f=>i?.(f))},async load(){let c=await e.get(a);if(c==null)return null;try{return JSON.parse(c)}catch{return null}}};return t.attachStorage([u],{onError:c=>i?.(c)})}function nl(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return W(i=>{try{let u=t.query(e,o).map(r);i.emit(u),i.down([[_]])}catch(a){i.down([[M,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...s})}function rl(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return W(i=>{try{let a=t.iterate(e,o);te(()=>{for(let u of a)i.emit(r(u));i.down([[_]])})}catch(a){i.down([[M,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...s})}function ol(t,e,n,r){if(n.includes("\0")||n.length===0)throw new Error(`toSqlite: invalid table name: ${JSON.stringify(n)}`);let{toSQL:o=(C,V)=>({sql:`INSERT INTO "${V.replace(/"/g,'""')}" (data) VALUES (?)`,params:[JSON.stringify(C)]}),onTransportError:s,batchInsert:i=!1,maxBatchSize:a=1e3,flushIntervalMs:u=0}=r??{},c=C=>o(C,n);if(!i)return $e(t,{onTransportError:s,serialize:c,send:C=>{let V=C;e.query(V.sql,V.params)}});let d=N(null),l=N(void 0,{equals:()=>!1}),f=N(null),p=N(0),m=N(0),h=C=>{try{s?.(C)}catch{}try{d.down([[S,C]])}catch{}},g=[],y=!1,b,v=!1,T=()=>m.down([[S,g.length]]),w=C=>{v||l.down([[S,C]])},k=C=>{v||f.down([[S,C]])},x=C=>{v||p.down([[S,C]])},R=C=>{v||h(C)},E=()=>{if(g.length===0||y)return;y=!0,x(1);try{e.query("BEGIN",[])}catch(F){y=!1,x(0),R({stage:"send",error:F instanceof Error?F:new Error(String(F)),value:void 0});return}let C=g;g=[],T();let V,ne=0;for(let F of C)try{e.query(F.query.sql,F.query.params),ne+=1}catch(A){V=A instanceof Error?A:new Error(String(A));break}if(V){try{e.query("ROLLBACK",[])}catch{}R({stage:"send",error:V,value:void 0});for(let F of C)k({value:F.value,error:V,attempts:1})}else try{e.query("COMMIT",[]);for(let F of C)w(F.value)}catch(F){let A=F instanceof Error?F:new Error(String(F));R({stage:"send",error:A,value:void 0});for(let D=0;D<ne;D++)k({value:C[D].value,error:A,attempts:1})}y=!1,x(0)},G=()=>{u>0&&b===void 0&&!v&&(b=setTimeout(()=>{b=void 0,E()},u))},L=t.subscribe(C=>{for(let V of C){let ne=V[0];if(ne===S){let F=V[1],A;try{A=c(F)}catch(D){let I=D instanceof Error?D:new Error(String(D));h({stage:"serialize",error:I,value:F}),f.down([[S,{value:F,error:I,attempts:0}]]);continue}g.push({value:F,query:A}),T(),g.length>=a?E():G()}else Ae.messageTier(ne)>=3&&E()}});return{dispose:()=>{if(!v){b!==void 0&&(clearTimeout(b),b=void 0),E(),v=!0,L();for(let C of[d,l,f,p,m])try{C.down([[de]])}catch{}}},sent:l,failed:f,inFlight:p,errors:d,buffered:m,flush:async()=>{v||E()}}}function sl(t,e){let{args:n,mapRow:r=s=>s,...o}=e??{};return W(s=>{let i=!0;return t.findMany(n).then(a=>{i&&(s.emit(a.map(r)),s.down([[_]]))}).catch(a=>{if(i)try{s.down([[M,a instanceof Error?a:new Error(String(a))]])}catch{}}),()=>{i=!1}},{...o,describeKind:"producer",completeWhenDepsComplete:!1})}function il(t,e){let{mapRow:n=o=>o,...r}=e??{};return W(o=>{let s=!0;return t.execute().then(i=>{s&&(o.emit(i.map(n)),o.down([[_]]))}).catch(i=>{if(s)try{o.down([[M,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{s=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}function al(t,e){let{mapRow:n=o=>o,...r}=e??{};return W(o=>{let s=!0;return t.execute().then(i=>{s&&(o.emit(i.map(n)),o.down([[_]]))}).catch(i=>{if(s)try{o.down([[M,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{s=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}Gn();ie();oe();function Zi(){let t=new Map,e=null,n=null;function r(s){s.prev?s.prev.next=s.next:e=s.next,s.next?s.next.prev=s.prev:n=s.prev,s.prev=null,s.next=null}function o(s){s.next=e,s.prev=null,e&&(e.prev=s),e=s,n===null&&(n=s)}return{insert(s){if(t.has(s)){this.touch(s);return}let i={key:s,prev:null,next:null};t.set(s,i),o(i)},touch(s){let i=t.get(s);i&&(r(i),o(i))},delete(s){let i=t.get(s);i&&(r(i),t.delete(s))},evict(s){let i=[];for(let a=0;a<s&&n!==null;a++){let u=n;i.push(u.key),r(u),t.delete(u.key)}return i},size(){return t.size}}}function ul(t){return t!=null&&typeof t.then=="function"}function zn(t){ul(t)&&t.catch(()=>{})}function cl(t,e){let n=new Map,r=e?.maxSize??0,o=r>0?e?.eviction??Zi():null,s=e?.writeThrough??!1;function i(c,d,l){for(let f=0;f<l;f++)try{zn(t[f].save(c,d))}catch{}}function a(c,d,l=0){for(let f=l;f<t.length;f++){let p;try{p=t[f].load(c)}catch{continue}if(ul(p)){let m=f;p.then(h=>{h!=null?(d.down([[S,h]]),i(c,h,m)):a(c,d,m+1)},()=>{a(c,d,m+1)});return}if(p!=null){d.down([[S,p]]),i(c,p,f);return}}}function u(){if(!(!o||r<=0))for(;o.size()>=r;){let c=o.evict(1);if(c.length===0)break;for(let d of c){let l=n.get(d);if(l){let f=l.cache;if(l.status!=="sentinel"&&t.length>0){let p=t.length-1;try{zn(t[p].save(d,f))}catch{}for(let m=0;m<p;m++)try{let h=t[m].clear;h&&zn(h.call(t[m],d))}catch{}}l.down([[de]])}n.delete(d)}}}return{load(c){let d=n.get(c);if(d)return o?.touch(c),d;o&&r>0&&o.size()>=r&&u();let l=N(void 0);return n.set(c,l),o?.insert(c),a(c,l),l},save(c,d){if(s)for(let f of t)try{zn(f.save(c,d))}catch{}else if(t[0])try{zn(t[0].save(c,d))}catch{}let l=n.get(c);if(l)l.down([[S,d]]),o?.touch(c);else{o&&r>0&&o.size()>=r&&u();let f=N(d);n.set(c,f),o?.insert(c)}},invalidate(c){let d=n.get(c);d&&a(c,d)},delete(c){o?.delete(c);let d=n.get(c);d&&d.down([[de]]),n.delete(c);for(let l of t)try{let f=l.clear;f&&zn(f.call(l,c))}catch{}},has(c){return n.has(c)},get size(){return n.size}}}Ne();ie();oe();Ne();ke();ie();oe();var Cr=class{_version=0;_store=new Map;_maxSize;_defaultTtl;constructor(e={}){let{maxSize:n,defaultTtl:r}=e;if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(r!==void 0&&r<=0)throw new RangeError("defaultTtl must be positive");this._maxSize=n,this._defaultTtl=r}get version(){return this._version}get size(){return this._store.size}has(e){let n=this._store.get(e);return n===void 0?!1:this._isExpired(n)?(this._store.delete(e),this._version+=1,!1):(this._touchLru(e,n),!0)}get(e){let n=this._store.get(e);if(n!==void 0){if(this._isExpired(n)){this._store.delete(e),this._version+=1;return}return this._touchLru(e,n),n.value}}set(e,n,r){let o=this._resolveExpiresAt(r);this._store.has(e)&&this._store.delete(e),this._store.set(e,{value:n,expiresAt:o}),this._evictLruWhileOver(),this._version+=1}setMany(e,n){let r=this._resolveExpiresAt(n),o=0;try{for(let[s,i]of e)this._store.has(s)&&this._store.delete(s),this._store.set(s,{value:i,expiresAt:r}),o+=1}finally{o>0&&(this._evictLruWhileOver(),this._version+=1)}}delete(e){let n=this._store.delete(e);return n&&(this._version+=1),n}deleteMany(e){let n=0;try{for(let r of e)this._store.delete(r)&&(n+=1)}finally{n>0&&(this._version+=1)}return n}clear(){let e=this._store.size;return e===0?0:(this._store.clear(),this._version+=1,e)}pruneExpired(){let e=$(),n=0;for(let[r,o]of this._store)this._isExpired(o,e)&&(this._store.delete(r),n+=1);return n>0&&(this._version+=1),n}toMap(){let e=$(),n=new Map;for(let[r,o]of this._store)this._isExpired(o,e)||n.set(r,o.value);return n}_resolveExpiresAt(e){let n=e??this._defaultTtl;if(n!==void 0){if(!Number.isFinite(n)||n<=0)throw new RangeError(`MapBackend: ttl must be a positive finite number (got ${n})`);return $()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??$())>=e.expiresAt}_touchLru(e,n){this._store.delete(e),this._store.set(e,n)}_evictLruWhileOver(){if(this._maxSize!==void 0)for(;this._store.size>this._maxSize;){let e=this._store.keys().next().value;if(e===void 0)break;this._store.delete(e)}}};function tt(t={}){let{name:e,maxSize:n,defaultTtl:r,versioning:o,backend:s}=t,i=s??new Cr({maxSize:n,defaultTtl:r}),a=N(i.toMap(),{name:e,describeKind:"state",equals:(d,l)=>d===l,...o!=null?{versioning:o}:{}});function u(){let d=i.toMap();te(()=>{a.down([[ee]]),a.down([[S,d]])})}function c(d){let l=i.version;try{return d()}finally{i.version!==l&&u()}}return{entries:a,has(d){return c(()=>i.has(d))},get(d){return c(()=>i.get(d))},set(d,l,f){c(()=>i.set(d,l,f?.ttl))},setMany(d,l){c(()=>i.setMany(d,l?.ttl))},delete(d){c(()=>i.delete(d))},deleteMany(d){c(()=>i.deleteMany(d))},clear(){c(()=>i.clear())},pruneExpired(){c(()=>i.pruneExpired())},get size(){return i.size},dispose(){}}}Re();function xm(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function pl(t,e,n){let r=re(t),o=r.v!=null,s=N(n?.initialVerified??null,{...o?{meta:{sourceVersion:null}}:{}}),i=n?.trigger!==void 0&&n.trigger!==null,a=null;if(i&&n?.autoVerify?a=mt(re(n.trigger),r):i?a=re(n.trigger):n?.autoVerify&&(a=r),a!==null){let u;if(a===r)u=be(r,c=>e(c));else{let c=r.cache;r.subscribe(d=>{for(let l of d)l[0]===S&&(c=l[1])}),u=be(a,()=>e(c))}Pt(u,c=>{te(()=>{if(s.down([[S,c]]),o){let d=r.v;d!=null&&s.meta.sourceVersion.down([[S,{id:d.id,version:d.version}]])}})})}return{node:r,verified:s,trigger:a}}function dl(t){t.subscribe(()=>{})}function Ar(t){return t instanceof Map?t:new Map}function ll(t,e){if(!Array.isArray(e.upsert))throw new TypeError("distill extraction requires upsert: Array<{ key, value }>");te(()=>{for(let{key:n,value:r}of e.upsert)t.set(n,r);for(let n of e.remove??[])t.delete(n)})}function Zo(t,e,n){let r=re(t),o=tt(n.mapOptions??{}),s=n.budget??2e3,a=n.context!==void 0&&n.context!==null?re(n.context):N(null),u=Ar(o.entries.cache);o.entries.subscribe(p=>{for(let m of p)m[0]===S&&(u=Ar(m[1]))});let c=be(r,p=>e(p,u));if(Pt(c,p=>{ll(o,p)}),n.evict){let p=new Map,m=O([o.entries],([h])=>{let g=[],y=Ar(h);for(let b of p.keys())y.has(b)||(p.get(b)(),p.delete(b));for(let[b,v]of y){let T=n.evict(b,v);if(xm(T)){if(!p.has(b)){let w=Pt(T,k=>{k===!0&&o.has(b)&&o.delete(b)});p.set(b,w)}continue}if(typeof T=="boolean"){T&&g.push(b);continue}throw new TypeError("distill evict() must return boolean or Node<boolean>")}return g});Pt(m,h=>{for(let g of h)o.delete(g)})}let d=n.consolidateTrigger!==void 0&&n.consolidateTrigger!==null;if(n.consolidate&&d){let p=re(n.consolidateTrigger),m=be(p,()=>n.consolidate(u));Pt(m,h=>{ll(o,h)})}let l=O([o.entries,a],([p,m])=>{let h=[...Ar(p).entries()].map(([b,v])=>({key:b,value:v,score:n.score(v,m),cost:n.cost(v)}));h.sort((b,v)=>v.score-b.score);let g=[],y=s;for(let b of h)b.cost<=y&&(g.push({key:b.key,value:b.value,score:b.score}),y-=b.cost);return g}),f=O([o.entries],([p])=>Ar(p).size);return dl(l),dl(f),{store:o,compact:l,size:f}}gi();Ne();ie();xe();var Lr=class{_version=0;_topics=new Set;get version(){return this._version}get topicCount(){return this._topics.size}hasTopic(e){return this._topics.has(e)}topicNames(){return this._topics.values()}createTopic(e){return this._topics.has(e)?!1:(this._topics.add(e),this._version+=1,!0)}removeTopic(e){let n=this._topics.delete(e);return n&&(this._version+=1),n}};function fl(t={}){let{backend:e}=t,n=e??new Lr,r=new Map;function o(s){let i=r.get(s);return i===void 0&&(i=K({describeKind:"state"}),r.set(s,i),n.createTopic(s)),i}return{topic(s){return o(s)},publish(s,i){o(s).emit(i)},publishMany(s){te(()=>{for(let[i,a]of s)o(i).emit(a)})},removeTopic(s){let i=r.get(s);return i===void 0?!1:(r.delete(s),n.removeTopic(s),i.down([[de]]),!0)},has(s){return n.hasTopic(s)},get size(){return n.topicCount},topicNames(){return n.topicNames()}}}Ne();ie();oe();function ml(t,e){if(t===e)return 0;let n=typeof t;if(n===typeof e&&(n==="number"||n==="string"||n==="boolean"||n==="bigint")){let o=t,s=e;return o<s?-1:o>s?1:0}return String(t).localeCompare(String(e))}function Rm(t,e){let n=ml(t[0],e[0]);return n!==0?n:ml(t[1],e[1])}function hl(t){return[t.secondary,t.primary]}function Jn(t,e){let n=hl(e),r=0,o=t.length;for(;r<o;){let s=r+o>>1;Rm(n,hl(t[s]))>0?r=s+1:o=s}return r}var Ir=class{_version=0;_buf=[];_byPrimary=new Map;get version(){return this._version}get size(){return this._buf.length}has(e){return this._byPrimary.has(e)}get(e){return this._byPrimary.get(e)?.value}upsert(e,n,r,o){let s=this._byPrimary.get(e),i={primary:e,secondary:n,value:r};if(s!==void 0&&o?.equals?.(s,i))return!1;if(s!==void 0){let u=Jn(this._buf,s);this._buf.splice(u,1)}let a=Jn(this._buf,i);return this._buf.splice(a,0,i),this._byPrimary.set(e,i),this._version+=1,s===void 0}upsertMany(e,n){let r=0;try{for(let o of e){let s=this._byPrimary.get(o.primary),i={primary:o.primary,secondary:o.secondary,value:o.value};if(s!==void 0&&n?.equals?.(s,i))continue;if(s!==void 0){let u=Jn(this._buf,s);this._buf.splice(u,1)}let a=Jn(this._buf,i);this._buf.splice(a,0,i),this._byPrimary.set(o.primary,i),r+=1}}finally{r>0&&(this._version+=1)}return r}delete(e){let n=this._byPrimary.get(e);if(n===void 0)return!1;let r=Jn(this._buf,n);return this._buf.splice(r,1),this._byPrimary.delete(e),this._version+=1,!0}deleteMany(e){let n=0;try{for(let r of e){let o=this._byPrimary.get(r);if(o===void 0)continue;let s=Jn(this._buf,o);this._buf.splice(s,1),this._byPrimary.delete(r),n+=1}}finally{n>0&&(this._version+=1)}return n}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._byPrimary.clear(),this._version+=1,e)}toArray(){return[...this._buf]}toPrimaryMap(){let e=new Map;for(let n of this._buf)e.set(n.primary,n.value);return e}};function Sm(t){return t.subscribe(()=>{})}function gl(t={}){let{name:e,versioning:n,equals:r,backend:o}=t,s=o??new Ir;function i(p){return p?.equals!==void 0||r===void 0?p:{...p,equals:r}}let a=N([],{name:e,describeKind:"state",equals:(p,m)=>p===m,...n!=null?{versioning:n}:{}}),u=O([a],([p])=>{let m=p,h=new Map;for(let g of m)h.set(g.primary,g.value);return h},{initial:s.toPrimaryMap(),describeKind:"derived"}),c=Sm(u),d=!1;function l(){let p=s.toArray();te(()=>{a.down([[ee]]),a.down([[S,p]])})}function f(p){let m=s.version;try{return p()}finally{s.version!==m&&l()}}return{ordered:a,byPrimary:u,has(p){return s.has(p)},get(p){return s.get(p)},get size(){return s.size},upsert(p,m,h,g){return f(()=>s.upsert(p,m,h,i(g)))},upsertMany(p,m){let h=[...p];h.length!==0&&f(()=>s.upsertMany(h,i(m)))},delete(p){f(()=>s.delete(p))},deleteMany(p){let m=[...p];m.length!==0&&f(()=>s.deleteMany(m))},clear(){f(()=>s.clear())},dispose(){d||(d=!0,c())}}}Ne();ie();oe();var Pr=class{_version=0;_buf;constructor(e){this._buf=e?[...e]:[]}get version(){return this._version}get size(){return this._buf.length}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._buf.length+e;if(!(n<0||n>=this._buf.length))return this._buf[n]}append(e){this._buf.push(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._buf.length;this._buf.length=n+e.length;for(let r=0;r<e.length;r++)this._buf[n+r]=e[r];this._version+=1}insert(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insert: index ${e} out of range [0, ${this._buf.length}]`);this._buf.splice(e,0,n),this._version+=1}insertMany(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insertMany: index ${e} out of range [0, ${this._buf.length}]`);n.length!==0&&(this._buf.splice(e,0,...n),this._version+=1)}pop(e){if(this._buf.length===0)throw new RangeError("pop from empty list");if(!Number.isInteger(e))throw new RangeError(`pop: index ${e} must be an integer`);let n=e>=0?e:this._buf.length+e;if(n<0||n>=this._buf.length)throw new RangeError(`pop: index ${e} out of range`);let[r]=this._buf.splice(n,1);return this._version+=1,r}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._version+=1,e)}toArray(){return[...this._buf]}};function es(t,e={}){let{name:n,versioning:r,backend:o}=e,s=o??new Pr(t),i=N(s.toArray(),{name:n,describeKind:"state",equals:(c,d)=>c===d,...r!=null?{versioning:r}:{}});function a(){let c=s.toArray();te(()=>{i.down([[ee]]),i.down([[S,c]])})}function u(c){let d=s.version;try{return c()}finally{s.version!==d&&a()}}return{items:i,get size(){return s.size},at(c){return s.at(c)},append(c){u(()=>s.append(c))},appendMany(c){u(()=>s.appendMany(c))},insert(c,d){u(()=>s.insert(c,d))},insertMany(c,d){u(()=>s.insertMany(c,d))},pop(c=-1){return u(()=>s.pop(c))},clear(){u(()=>s.clear())},dispose(){}}}Tt();ie();Re();function ts(t,e={}){let n=e.keyFn??(o=>String(o)),r=new Map;return o=>{let s=n(o),i=r.get(s);if(i)return i;let a=t(o),u;a!=null&&typeof a.then=="function"?u=Promise.resolve(a):a!=null&&typeof a=="object"&&"subscribe"in a&&"cache"in a?u=Kn(a):a!=null&&typeof a=="object"&&Symbol.asyncIterator in a?u=(async()=>{let l=a[Symbol.asyncIterator]();try{let{value:f,done:p}=await l.next();if(p)throw new Error("singleFromAny: factory returned empty async iterable");return f}finally{await l.return?.()}})():a!=null&&typeof a=="object"&&Symbol.iterator in a?u=(async()=>{let l=a[Symbol.iterator]();try{let{value:f,done:p}=l.next();if(p)throw new Error("singleFromAny: factory returned empty iterable");return f}finally{l.return?.()}})():u=Promise.resolve(a);let c,d=()=>{r.get(s)===c&&r.delete(s)};return c=u.then(l=>(d(),l),l=>{throw d(),l}),r.set(s,c),c}}function yl(t,e={}){let n=e.keyFn??(o=>String(o)),r=new Map;return o=>{let s=n(o),i=r.get(s);if(i)return i;let a=re(t(o));r.set(s,a);let u=a.subscribe(c=>{for(let d of c)if(d[0]===M||d[0]===_){r.get(s)===a&&r.delete(s),u();return}});return a}}Re();function Dr(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(Dr);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=Dr(e[o]);return r}function bl(t){return JSON.stringify(Dr(t),void 0,0)}function Gr(){let t=new Map;return{save(e,n){t.set(e,JSON.parse(JSON.stringify(n)))},load(e){let n=t.get(e);return n===void 0?null:JSON.parse(JSON.stringify(n))},clear(e){t.delete(e)},list(){return[...t.keys()].sort()}}}function vl(t){return{save(e,n){t[e]=JSON.parse(JSON.stringify(n))},load(e){let n=t[e];return n===void 0?null:JSON.parse(JSON.stringify(n))},clear(e){delete t[e]},list(){return Object.keys(t).sort()}}}ie();xe();oe();function Fr(t,e,n,r){let o=new q(t,r);o.add(e,{name:"source"});let s=N(n,{meta:{kind:"stratify_rules"}});o.add(s,{name:"rules"});for(let i of n)Nm(o,e,s,i);return o}function Nm(t,e,n,r){let o=`branch/${r.name}`,s=Symbol("noValue"),i=!1,a=!1,u=!1,c=s,d=!1,l=n.cache??[];function f(h){if(u){u=!1;let g=c;if(c=s,g!==s){let y=l.find(v=>v.name===r.name),b=!1;try{b=y?.classify(g)??!1}catch{b=!1}b?(d=!1,h.emit(g)):d&&(d=!1,h.down([[ee],[B]]))}else d?(d=!1,h.down([[ee],[B]])):h.down([[B]])}}let p=K([],(h,g)=>{let y=e.subscribe(v=>{for(let T of v)m(T,0,g)}),b=n.subscribe(v=>{for(let T of v)m(T,1,g)});return()=>{y(),b()}},{describeKind:"derived",meta:{kind:"stratify_branch",branch:r.name},completeWhenDepsComplete:!1});function m(h,g,y){let b=h[0];return b===ee?(g===0?(i=!0,d=!0):a=!0,!0):b===S||b===B?(g===0?(i=!1,u=!0,c=b===S?h[1]:s):(b===S&&(l=h[1]),a=!1),i||a||f(y),!0):b===_||b===M||b===de?(i=!1,a=!1,u=!1,c=s,d=!1,g===0&&y.down([h]),!0):g===1}if(t.add(p,{name:o}),r.ops){let h=r.ops(p),g=`branch/${r.name}/out`;t.add(h,{name:g})}}pt();Ne();ie();xe();oe();Re();ie();var Em=new Map([[He,"INVALIDATE"],[Ie,"PAUSE"],[Ge,"RESUME"],[de,"TEARDOWN"],[_,"COMPLETE"],[M,"ERROR"]]),_m=new Map([["INVALIDATE",He],["PAUSE",Ie],["RESUME",Ge],["TEARDOWN",de],["COMPLETE",_],["ERROR",M]]);function Ft(t){let e=Em.get(t);return e||(Symbol.keyFor(t)??"UNKNOWN")}function ln(t){let e=_m.get(t);if(e)return e;if(t&&t!=="UNKNOWN")return Symbol.for(t)}function pn(t){return t instanceof Error?{message:t.message,name:t.name,stack:t.stack}:{message:String(t),name:"Error"}}function fn(t){let e=new Error(t.message);return e.name=t.name,t.stack&&(e.stack=t.stack),e}function $t(t){if(typeof MessagePort<"u"&&t instanceof MessagePort)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),t.start(),()=>t.removeEventListener("message",n)},terminate(){t.close()}};if(typeof SharedWorker<"u"&&t instanceof SharedWorker)return $t(t.port);if(typeof Worker<"u"&&t instanceof Worker)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),()=>t.removeEventListener("message",n)},terminate(){t.terminate()}};if(typeof BroadcastChannel<"u"&&t instanceof BroadcastChannel)return{post(e,n){n&&n.length>0&&console.warn("[graphrefly] WorkerTransport: BroadcastChannel does not support Transferable objects. The transfer argument is ignored and objects will be cloned instead."),t.postMessage(e)},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),()=>t.removeEventListener("message",n)},terminate(){t.close()}};if(typeof ServiceWorker<"u"&&t instanceof ServiceWorker)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>{r.source===t&&e(r.data)};return navigator.serviceWorker.addEventListener("message",n),()=>navigator.serviceWorker.removeEventListener("message",n)}};throw new Error("createTransport: unsupported target type. Expected Worker, SharedWorker, ServiceWorker, BroadcastChannel, or MessagePort.")}function Mm(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function ea(t,e){let n=Mm(t)?t:$t(t),r=e.name??"workerBridge",o=Object.entries(e.expose??{}),s=e.import??[],i=e.transfer??{},a=N("connecting",{name:`${r}::meta::status`}),u=N(null,{name:`${r}::meta::error`}),c=new Map,d=new Map;for(let b of s){let v=N(void 0,{name:`${r}::${b}`});c.set(b,v)}let l;if(o.length>0){let b=o.map(([,w])=>w),v=K(b,(w,k)=>{let x={};for(let R=0;R<o.length;R++){let[E]=o[R],G=w[R];G!=null&&G.length>0&&(x[E]=G.at(-1))}Object.keys(x).length!==0&&k.emit(x)},{name:`${r}::aggregated`,partial:!0});l=fe([v],w=>{let k=w[0];if(k==null||Object.keys(k).length===0)return;let x=[];for(let G of Object.keys(k)){let L=i[G];L&&x.push(...L(k[G]))}let R;for(let[G,L]of o)G in k&&L.v!=null&&(R==null&&(R={}),R[G]=L.v.version);let E={t:"b",u:k,...R?{v:R}:{}};try{n.post(E,x.length>0?x:void 0)}catch(G){u.down([[S,G instanceof Error?G:new Error(String(G))]])}}).subscribe(()=>{})}let f=!1,p=n.listen(b=>{if(f)return;let v=b;switch(v.t){case"r":{te(()=>{for(let[w,k]of Object.entries(v.stores)){let x=c.get(w);x&&x.down([[S,k]])}}),a.down([[S,"connected"]]);let T={};for(let[w,k]of o)T[w]=k.cache;n.post({t:"i",stores:T});break}case"v":{let T=c.get(v.s);T&&T.down([[S,v.d]]);break}case"b":{te(()=>{for(let[T,w]of Object.entries(v.u)){let k=v.v?.[T];if(k!=null){let R=d.get(T);if(R!=null&&k<=R)continue;d.set(T,k)}let x=c.get(T);x&&x.down([[S,w]])}});break}case"e":{let T=c.get(v.s);T&&T.down([[M,fn(v.err)]]);break}case"s":{let T=ln(v.sig);if(!T)break;let w=v.s==="*"?[...c.values()]:c.has(v.s)?[c.get(v.s)]:[];for(let k of w)k.down(v.d===void 0?[[T]]:[[T,v.d]]);break}}}),m=[];for(let[b,v]of o){let T=v.subscribe((w=>{if(!f)for(let k of w){let x=k[0];x!==S&&(Ae.isLocalOnly(x)||(x===M?n.post({t:"e",s:b,err:pn(k[1])}):n.post({t:"s",s:b,sig:Ft(x),d:k.length>1?k[1]:void 0})))}}));m.push(T)}let h;if(e.timeoutMs!=null&&e.timeoutMs>0){let b=et(e.timeoutMs),v=ut(a,w=>w==="connected");h=Qo(mt(Er(b,()=>"timeout"),Er(v,()=>"ready"))).subscribe(w=>{for(let k of w)k[0]===S&&k[1]==="timeout"&&(u.down([[S,new Error("Worker bridge handshake timeout")]]),g())})}function g(){if(!f){f=!0,h?.(),n.post({t:"s",s:"*",sig:Ft(de)}),l&&l();for(let b of m)b();m.length=0,p(),a.down([[S,"closed"]]),d.clear(),c.clear()}}let y={meta:{status:a,error:u},destroy:g};for(let[b,v]of c)y[b]=v;return y}Ne();ie();xe();oe();function Om(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function ta(t,e){let n=Om(t)?t:$t(t),r=e.import??[],o=e.transfer??{},s=new Map,i=new Map,a={};for(let g of r){let y=N(void 0,{name:`worker::${g}`});s.set(g,y),a[g]=y}let u=e.expose(a),c=Object.entries(u),d,l=!1;if(c.length>0){let g=c.map(([,v])=>v),y=K(g,(v,T)=>{let w={};for(let k=0;k<c.length;k++){let[x]=c[k],R=v[k];R!=null&&R.length>0&&(w[x]=R.at(-1))}Object.keys(w).length!==0&&T.emit(w)},{name:"workerSelf::aggregated",partial:!0});d=fe([y],v=>{if(l)return;let T=v[0];if(T==null||Object.keys(T).length===0)return;let w=[];for(let R of Object.keys(T)){let E=o[R];E&&w.push(...E(T[R]))}let k;for(let[R,E]of c)R in T&&E.v!=null&&(k==null&&(k={}),k[R]=E.v.version);let x={t:"b",u:T,...k?{v:k}:{}};try{n.post(x,w.length>0?w:void 0)}catch{}}).subscribe(()=>{})}let f=[];for(let[g,y]of c){let b=y.subscribe((v=>{if(!l)for(let T of v){let w=T[0];w!==S&&(Ae.isLocalOnly(w)||(w===M?n.post({t:"e",s:g,err:pn(T[1])}):n.post({t:"s",s:g,sig:Ft(w),d:T.length>1?T[1]:void 0})))}}));f.push(b)}let p=n.listen(g=>{if(l)return;let y=g;switch(y.t){case"i":{te(()=>{for(let[b,v]of Object.entries(y.stores)){let T=s.get(b);T&&T.down([[S,v]])}});break}case"v":{let b=s.get(y.s);b&&b.down([[S,y.d]]);break}case"b":{te(()=>{for(let[b,v]of Object.entries(y.u)){let T=y.v?.[b];if(T!=null){let k=i.get(b);if(k!=null&&T<=k)continue;i.set(b,T)}let w=s.get(b);w&&w.down([[S,v]])}});break}case"e":{let b=s.get(y.s);b&&b.down([[M,fn(y.err)]]);break}case"s":{let b=ln(y.sig);if(!b)break;if(b===de&&y.s==="*"){h();return}let v=y.s==="*"?[...s.values()]:s.has(y.s)?[s.get(y.s)]:[];for(let T of v)T.down(y.d===void 0?[[b]]:[[b,y.d]]);break}}}),m={};for(let[g,y]of c)m[g]=y.cache;n.post({t:"r",stores:m});function h(){if(!l){l=!0,d&&d();for(let g of f)g();f.length=0,p(),n.terminate?.(),i.clear(),s.clear()}}return{destroy:h}}var su={};he(su,{SNAPSHOT_WIRE_VERSION:()=>Xr,SurfaceError:()=>we,accountability:()=>_s,ai:()=>Ss,asSurfaceError:()=>Us,cqrs:()=>Bo,createGraph:()=>Zn,deleteSnapshot:()=>ei,demoShell:()=>Os,diffSnapshots:()=>Xs,domainTemplates:()=>Ls,graphspec:()=>Is,guarded:()=>Ds,harness:()=>$s,jobQueue:()=>Vs,layout:()=>Ws,lens:()=>Hs,listSnapshots:()=>Zs,memory:()=>Rs,messaging:()=>bs,orchestration:()=>vs,reduction:()=>As,refine:()=>Fs,resilientPipeline:()=>qs,restoreSnapshot:()=>Qs,runReduction:()=>zs,saveSnapshot:()=>Ys,surface:()=>ti});var Ss={};he(Ss,{AgentLoopGraph:()=>ks,AllTiersExhaustedError:()=>$r,BudgetExhaustedError:()=>ls,ChatStreamGraph:()=>Ts,CircuitOpenError:()=>st,DEFAULT_DECAY_RATE:()=>Ma,FallbackMissError:()=>$m,LLMTimeoutError:()=>Qn,ReplayCacheMissError:()=>mn,ToolRegistryGraph:()=>ws,admissionFilter3D:()=>rg,agentLoop:()=>Zh,agentMemory:()=>ig,anthropicAdapter:()=>ra,canonicalJson:()=>as,cascadingLlmAdapter:()=>va,chatStream:()=>ka,composePricing:()=>ih,computePrice:()=>Fl,contentGate:()=>Yh,costMeterExtractor:()=>Hh,createAdapter:()=>th,createCapabilitiesRegistry:()=>Cm,createPricingRegistry:()=>oh,dryRunAdapter:()=>St,dryRunPreset:()=>vh,fallbackAdapter:()=>ia,fromLLM:()=>Th,frozenContext:()=>Sh,gatedStream:()=>jh,gaugesAsContext:()=>ag,googleAdapter:()=>aa,graphFromSpec:()=>ug,handoff:()=>eg,keywordFlagExtractor:()=>qh,knobsAsTools:()=>dg,llmConsolidator:()=>_a,llmExtractor:()=>Ea,observableAdapter:()=>nh,openAICompatAdapter:()=>ca,parseRateLimitFromError:()=>ga,promptNode:()=>Br,redactor:()=>Qh,registryPricing:()=>sh,resilientAdapter:()=>bh,streamExtractor:()=>Uh,streamingPromptNode:()=>Bh,suggestStrategy:()=>pg,systemPromptBuilder:()=>Vh,toolCallExtractor:()=>Jh,toolRegistry:()=>xa,toolSelector:()=>tg,validateGraphDef:()=>Oa,withBreaker:()=>fa,withBudgetGate:()=>ha,withDryRun:()=>uh,withRateLimiter:()=>ba,withReplayCache:()=>sa,withRetry:()=>Ta,withTimeout:()=>wa,zeroPrice:()=>pa});function ns(t,e){return`${t}::${e}`}function Cm(t){let e=new Map,n=new Map,r=o=>{e.set(ns(o.provider,o.id),o);let s=n.get(o.provider);s||(s=new Set,n.set(o.provider,s)),s.add(o.id)};if(t)for(let o of t)r(o);return{register:r,lookup(o,s){let i=e.get(ns(o,s));if(i)return i;let a=n.get(o);if(!a)return;let u;for(let c of a)if(s.startsWith(c)&&(!u||c.length>u.key.length)){let d=e.get(ns(o,c));d&&(u={key:c,cap:d})}return u?.cap},remove(o,s){let i=e.delete(ns(o,s));if(i){let a=n.get(o);a?.delete(s),a&&a.size===0&&n.delete(o)}return i},entries(){return e.values()}}}ke();function ra(t={}){return t.sdk?Dm(t):Pm(t)}function rs(t,e,n,r){let o=e?.model??n;if(!o)throw new Error("anthropicAdapter: model must be set via options.model or invokeOpts.model");let{system:s,chat:i}=Am(t,e?.systemPrompt),a={model:o,messages:i.map(Lm),max_tokens:e?.maxTokens??4096};return s&&(a.system=s),e?.temperature!=null&&(a.temperature=e.temperature),e?.tools&&e.tools.length>0&&(a.tools=e.tools.map(Im)),e?.maxReasoningTokens!=null&&(a.thinking={type:"enabled",budget_tokens:e.maxReasoningTokens}),e?.cacheHint,r&&(a.stream=!0),e?.providerExtras&&Object.assign(a,e.providerExtras),a}function Am(t,e){let n=[];e&&n.push(e);let r=[];for(let o of t)o.role==="system"?n.push(o.content):r.push(o);return{system:n.length>0?n.join(`
32
+ `:JSON.stringify(f),m=s(l,le());await e.putObject({Bucket:n,Key:m,Body:p,ContentType:d})}})}function ll(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 je(t,{onTransportError:s,serialize:i=>o(i,n),send:async i=>{let a=i;await e.query(a.sql,a.params)}})}function pl(t,e,n){let{toDocument:r=s=>s,onTransportError:o}=n??{};return je(t,{onTransportError:o,serialize:r,send:async s=>{await e.insertOne(s)}})}function fl(t,e,n){let{labels:r={},toLine:o=a=>JSON.stringify(a),toLabels:s,onTransportError:i}=n??{};return je(t,{onTransportError:i,serialize:a=>({line:o(a),labels:s?{...r,...s(a)}:r}),send:async a=>{let{line:u,labels:c}=a,d=`${le()}`;await e.push({streams:[{stream:c,values:[[d,u]]}]})}})}function ml(t,e,n){let{toResourceSpans:r=s=>[s],onTransportError:o}=n??{};return je(t,{onTransportError:o,serialize:r,send:async s=>{await e.push({resourceSpans:s})}})}function hl(t,e,n,r){let{prefix:o="checkpoints/",debounceMs:s=500,compactEvery:i=10,onError:a}=r??{},u={debounceMs:s,compactEvery:i,save(c,d){let l=Math.floor(le()/1e6),f=`${o}${t.name}/checkpoint-${l}.json`,p;try{p=JSON.stringify(d)}catch(m){a?.(m);return}e.putObject({Bucket:n,Key:f,Body:p,ContentType:"application/json"}).catch(m=>a?.(m))},load(){return null}};return t.attachStorage([u],{onError:c=>a?.(c)})}function gl(t,e,n){let{prefix:r="graphrefly:checkpoint:",debounceMs:o=500,compactEvery:s=10,onError:i}=n??{},a=`${r}${t.name}`,u={debounceMs:o,compactEvery:s,save(c,d){let l;try{l=JSON.stringify(d)}catch(f){i?.(f);return}e.set(a,l).catch(f=>i?.(f))},async load(){let c=await e.get(a);if(c==null)return null;try{return JSON.parse(c)}catch{return null}}};return t.attachStorage([u],{onError:c=>i?.(c)})}function yl(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return W(i=>{try{let u=t.query(e,o).map(r);i.emit(u),i.down([[M]])}catch(a){i.down([[O,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...s})}function bl(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return W(i=>{try{let a=t.iterate(e,o);X(()=>{for(let u of a)i.emit(r(u));i.down([[M]])})}catch(a){i.down([[O,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...s})}function vl(t,e,n,r){if(n.includes("\0")||n.length===0)throw new Error(`toSqlite: invalid table name: ${JSON.stringify(n)}`);let{toSQL:o=(C,B)=>({sql:`INSERT INTO "${B.replace(/"/g,'""')}" (data) VALUES (?)`,params:[JSON.stringify(C)]}),onTransportError:s,batchInsert:i=!1,maxBatchSize:a=1e3,flushIntervalMs:u=0}=r??{},c=C=>o(C,n);if(!i)return je(t,{onTransportError:s,serialize:c,send:C=>{let B=C;e.query(B.sql,B.params)}});let d=N(null),l=N(void 0,{equals:()=>!1}),f=N(null),p=N(0),m=N(0),h=C=>{try{s?.(C)}catch{}try{d.down([[S,C]])}catch{}},g=[],y=!1,b,v=!1,T=()=>m.down([[S,g.length]]),w=C=>{v||l.down([[S,C]])},k=C=>{v||f.down([[S,C]])},x=C=>{v||p.down([[S,C]])},R=C=>{v||h(C)},_=()=>{if(g.length===0||y)return;y=!0,x(1);try{e.query("BEGIN",[])}catch(F){y=!1,x(0),R({stage:"send",error:F instanceof Error?F:new Error(String(F)),value:void 0});return}let C=g;g=[],T();let B,te=0;for(let F of C)try{e.query(F.query.sql,F.query.params),te+=1}catch(A){B=A instanceof Error?A:new Error(String(A));break}if(B){try{e.query("ROLLBACK",[])}catch{}R({stage:"send",error:B,value:void 0});for(let F of C)k({value:F.value,error:B,attempts:1})}else try{e.query("COMMIT",[]);for(let F of C)w(F.value)}catch(F){let A=F instanceof Error?F:new Error(String(F));R({stage:"send",error:A,value:void 0});for(let D=0;D<te;D++)k({value:C[D].value,error:A,attempts:1})}y=!1,x(0)},G=()=>{u>0&&b===void 0&&!v&&(b=setTimeout(()=>{b=void 0,_()},u))},L=t.subscribe(C=>{for(let B of C){let te=B[0];if(te===S){let F=B[1],A;try{A=c(F)}catch(D){let I=D instanceof Error?D:new Error(String(D));h({stage:"serialize",error:I,value:F}),f.down([[S,{value:F,error:I,attempts:0}]]);continue}g.push({value:F,query:A}),T(),g.length>=a?_():G()}else Pe.messageTier(te)>=3&&_()}});return{dispose:()=>{if(!v){b!==void 0&&(clearTimeout(b),b=void 0),_(),v=!0,L();for(let C of[d,l,f,p,m])try{C.down([[de]])}catch{}}},sent:l,failed:f,inFlight:p,errors:d,buffered:m,flush:async()=>{v||_()}}}function Tl(t,e){let{args:n,mapRow:r=s=>s,...o}=e??{};return W(s=>{let i=!0;return t.findMany(n).then(a=>{i&&(s.emit(a.map(r)),s.down([[M]]))}).catch(a=>{if(i)try{s.down([[O,a instanceof Error?a:new Error(String(a))]])}catch{}}),()=>{i=!1}},{...o,describeKind:"producer",completeWhenDepsComplete:!1})}function wl(t,e){let{mapRow:n=o=>o,...r}=e??{};return W(o=>{let s=!0;return t.execute().then(i=>{s&&(o.emit(i.map(n)),o.down([[M]]))}).catch(i=>{if(s)try{o.down([[O,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{s=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}function kl(t,e){let{mapRow:n=o=>o,...r}=e??{};return W(o=>{let s=!0;return t.execute().then(i=>{s&&(o.emit(i.map(n)),o.down([[M]]))}).catch(i=>{if(s)try{o.down([[O,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{s=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}Vn();ie();ne();function ha(){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 xl(t){return t!=null&&typeof t.then=="function"}function Xn(t){xl(t)&&t.catch(()=>{})}function Rl(t,e){let n=new Map,r=e?.maxSize??0,o=r>0?e?.eviction??ha():null,s=e?.writeThrough??!1;function i(c,d,l){for(let f=0;f<l;f++)try{Xn(t[f].save(c,d))}catch{}}function a(c,d,l=0){for(let f=l;f<t.length;f++){let p;try{p=t[f].load(c)}catch{continue}if(xl(p)){let m=f;p.then(h=>{h!=null?(d.down([[S,h]]),i(c,h,m)):a(c,d,m+1)},()=>{a(c,d,m+1)});return}if(p!=null){d.down([[S,p]]),i(c,p,f);return}}}function u(){if(!(!o||r<=0))for(;o.size()>=r;){let c=o.evict(1);if(c.length===0)break;for(let d of c){let l=n.get(d);if(l){let f=l.cache;if(l.status!=="sentinel"&&t.length>0){let p=t.length-1;try{Xn(t[p].save(d,f))}catch{}for(let m=0;m<p;m++)try{let h=t[m].clear;h&&Xn(h.call(t[m],d))}catch{}}l.down([[de]])}n.delete(d)}}}return{load(c){let d=n.get(c);if(d)return o?.touch(c),d;o&&r>0&&o.size()>=r&&u();let l=N(void 0);return n.set(c,l),o?.insert(c),a(c,l),l},save(c,d){if(s)for(let f of t)try{Xn(f.save(c,d))}catch{}else if(t[0])try{Xn(t[0].save(c,d))}catch{}let l=n.get(c);if(l)l.down([[S,d]]),o?.touch(c);else{o&&r>0&&o.size()>=r&&u();let f=N(d);n.set(c,f),o?.insert(c)}},invalidate(c){let d=n.get(c);d&&a(c,d)},delete(c){o?.delete(c);let d=n.get(c);d&&d.down([[de]]),n.delete(c);for(let l of t)try{let f=l.clear;f&&Xn(f.call(l,c))}catch{}},has(c){return n.has(c)},get size(){return n.size}}}_e();ie();ne();_e();we();ie();ne();var Fr=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=V(),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=V(),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 V()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??V())>=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 Qe(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 Fr({maxSize:n,defaultTtl:r}),u=N(a.toMap(),{name:e,describeKind:"state",equals:(f,p)=>f===p,...o!=null?{versioning:o}:{}});function c(){let f=a.toMap();X(()=>{u.down([[ee]]),u.down([[S,f]])})}function d(){if(!i)return;let f=a.toMap(),p=i.archiveThreshold,m=i.maxSize,h=[];for(let[y,b]of f)h.push({key:y,value:b,score:i.score(y,b)});h.sort((y,b)=>y.score-b.score);let g=new Set;if(p!==void 0)for(let y of h)if(y.score<p)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(f,p="mutation"){let m=a.version;try{return f()}finally{a.version!==m&&(p==="mutation"&&d(),c())}}return{entries:u,has(f){return l(()=>a.has(f),"read")},get(f){return l(()=>a.get(f),"read")},set(f,p,m){l(()=>a.set(f,p,m?.ttl))},setMany(f,p){l(()=>a.setMany(f,p?.ttl))},delete(f){l(()=>a.delete(f))},deleteMany(f){l(()=>a.deleteMany(f))},clear(){l(()=>a.clear())},pruneExpired(){l(()=>a.pruneExpired())},get size(){return a.size},dispose(){}}}ve();function Im(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function El(t,e,n){let r=z(t),o=r.v!=null,s=N(n?.initialVerified??null,{...o?{meta:{sourceVersion:null}}:{}}),i=n?.trigger!==void 0&&n.trigger!==null,a=null;if(i&&n?.autoVerify?a=wt(z(n.trigger),r):i?a=z(n.trigger):n?.autoVerify&&(a=r),a!==null){let u;if(a===r)u=Te(r,c=>e(c));else{let c=r.cache;r.subscribe(d=>{for(let l of d)l[0]===S&&(c=l[1])}),u=Te(a,()=>e(c))}jt(u,c=>{X(()=>{if(s.down([[S,c]]),o){let d=r.v;d!=null&&s.meta.sourceVersion.down([[S,{id:d.id,version:d.version}]])}})})}return{node:r,verified:s,trigger:a}}function Sl(t){t.subscribe(()=>{})}function $r(t){return t instanceof Map?t:new Map}function Nl(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 fs(t,e,n){let r=z(t),o=Qe(n.mapOptions??{}),s=n.budget??2e3,a=n.context!==void 0&&n.context!==null?z(n.context):N(null),u=$r(o.entries.cache);o.entries.subscribe(p=>{for(let m of p)m[0]===S&&(u=$r(m[1]))});let c=Te(r,p=>e(p,u));if(jt(c,p=>{Nl(o,p)}),n.evict){let p=new Map,m=E([o.entries],([h])=>{let g=[],y=$r(h);for(let b of p.keys())y.has(b)||(p.get(b)(),p.delete(b));for(let[b,v]of y){let T=n.evict(b,v);if(Im(T)){if(!p.has(b)){let w=jt(T,k=>{k===!0&&o.has(b)&&o.delete(b)});p.set(b,w)}continue}if(typeof T=="boolean"){T&&g.push(b);continue}throw new TypeError("distill evict() must return boolean or Node<boolean>")}return g});jt(m,h=>{for(let g of h)o.delete(g)})}let d=n.consolidateTrigger!==void 0&&n.consolidateTrigger!==null;if(n.consolidate&&d){let p=z(n.consolidateTrigger),m=Te(p,()=>n.consolidate(u));jt(m,h=>{Nl(o,h)})}let l=E([o.entries,a],([p,m])=>{let h=[...$r(p).entries()].map(([b,v])=>({key:b,value:v,score:n.score(v,m),cost:n.cost(v)}));h.sort((b,v)=>v.score-b.score);let g=[],y=s;for(let b of h)b.cost<=y&&(g.push({key:b.key,value:b.value,score:b.score}),y-=b.cost);return g}),f=E([o.entries],([p])=>$r(p).size);return Sl(l),Sl(f),{store:o,compact:l,size:f}}async function ms(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+=_l[r[s]];return o}var _l=new Array(256);for(let t=0;t<256;t++)_l[t]=t.toString(16).padStart(2,"0");var Br=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 jr(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 hs(t){let{storage:e,keyContext:n,keyPrefix:r,mode:o="read-write"}=t,s=n??(a=>a);async function i(a){let u=jr(s(a)),c=await ms(u);return r?`${r}:${c}`:c}return{keyFor:i,async lookup(a){if(o==="write")return;let u=await i(a),c=await e.load(u);if(c==null){if(o==="read-strict")throw new Br(u,a);return}return c},async store(a,u){if(o==="read")return;let c=await i(a);await e.save(c,u)},async forget(a){if(o==="read"||o==="write"||!e.clear)return;let u=await i(a);await e.clear(u)}}}Ai();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}_e();ie();Ne();var Vr=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 Ml(t={}){let{backend:e}=t,n=e??new Vr,r=new Map;function o(s){let i=r.get(s);return i===void 0&&(i=K({describeKind:"state"}),r.set(s,i),n.createTopic(s)),i}return{topic(s){return o(s)},publish(s,i){o(s).emit(i)},publishMany(s){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()}}}_e();ie();ne();function Ol(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 Pm(t,e){let n=Ol(t[0],e[0]);return n!==0?n:Ol(t[1],e[1])}function Cl(t){return[t.secondary,t.primary]}function Zn(t,e){let n=Cl(e),r=0,o=t.length;for(;r<o;){let s=r+o>>1;Pm(n,Cl(t[s]))>0?r=s+1:o=s}return r}var Kr=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=Zn(this._buf,s);this._buf.splice(u,1)}let a=Zn(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=Zn(this._buf,s);this._buf.splice(u,1)}let a=Zn(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=Zn(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=Zn(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 Dm(t){return t.subscribe(()=>{})}function Al(t={}){let{name:e,versioning:n,equals:r,backend:o}=t,s=o??new Kr;function i(p){return p?.equals!==void 0||r===void 0?p:{...p,equals:r}}let a=N([],{name:e,describeKind:"state",equals:(p,m)=>p===m,...n!=null?{versioning:n}:{}}),u=E([a],([p])=>{let m=p,h=new Map;for(let g of m)h.set(g.primary,g.value);return h},{initial:s.toPrimaryMap(),describeKind:"derived"}),c=Dm(u),d=!1;function l(){let p=s.toArray();X(()=>{a.down([[ee]]),a.down([[S,p]])})}function f(p){let m=s.version;try{return p()}finally{s.version!==m&&l()}}return{ordered:a,byPrimary:u,has(p){return s.has(p)},get(p){return s.get(p)},get size(){return s.size},upsert(p,m,h,g){return f(()=>s.upsert(p,m,h,i(g)))},upsertMany(p,m){let h=[...p];h.length!==0&&f(()=>s.upsertMany(h,i(m)))},delete(p){f(()=>s.delete(p))},deleteMany(p){let m=[...p];m.length!==0&&f(()=>s.deleteMany(m))},clear(){f(()=>s.clear())},dispose(){d||(d=!0,c())}}}_e();ie();ne();var Hr=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 gs(t,e={}){let{name:n,versioning:r,backend:o}=e,s=o??new Hr(t),i=N(s.toArray(),{name:n,describeKind:"state",equals:(c,d)=>c===d,...r!=null?{versioning:r}:{}});function a(){let c=s.toArray();X(()=>{i.down([[ee]]),i.down([[S,c]])})}function u(c){let d=s.version;try{return c()}finally{s.version!==d&&a()}}return{items:i,get size(){return s.size},at(c){return s.at(c)},append(c){u(()=>s.append(c))},appendMany(c){u(()=>s.appendMany(c))},insert(c,d){u(()=>s.insert(c,d))},insertMany(c,d){u(()=>s.insertMany(c,d))},pop(c=-1){return u(()=>s.pop(c))},clear(){u(()=>s.clear())},dispose(){}}}Et();ie();ve();function ys(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:f,done:p}=await l.next();if(p)throw new Error("singleFromAny: factory returned empty async iterable");return f}finally{await l.return?.()}})():a!=null&&typeof a=="object"&&Symbol.iterator in a?u=(async()=>{let l=a[Symbol.iterator]();try{let{value:f,done:p}=l.next();if(p)throw new Error("singleFromAny: factory returned empty iterable");return f}finally{l.return?.()}})():u=Promise.resolve(a);let c,d=()=>{r.get(s)===c&&r.delete(s)};return c=u.then(l=>(d(),l),l=>{throw d(),l}),r.set(s,c),c}}function Ll(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=z(t(o));r.set(s,a);let u=a.subscribe(c=>{for(let d of c)if(d[0]===O||d[0]===M){r.get(s)===a&&r.delete(s),u();return}});return a}}ve();function Wr(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(Wr);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=Wr(e[o]);return r}function Il(t){return JSON.stringify(Wr(t),void 0,0)}function qr(){let t=new Map;return{save(e,n){t.set(e,JSON.parse(JSON.stringify(n)))},load(e){let n=t.get(e);return n===void 0?null:JSON.parse(JSON.stringify(n))},clear(e){t.delete(e)},list(){return[...t.keys()].sort()}}}function Pl(t){return{save(e,n){t[e]=JSON.parse(JSON.stringify(n))},load(e){let n=t[e];return n===void 0?null:JSON.parse(JSON.stringify(n))},clear(e){delete t[e]},list(){return Object.keys(t).sort()}}}ie();Ne();ne();function Ur(t,e,n,r){let o=new q(t,r);o.add(e,{name:"source"});let s=N(n,{meta:{kind:"stratify_rules"}});o.add(s,{name:"rules"});for(let i of n)Gm(o,e,s,i);return o}function Gm(t,e,n,r){let o=`branch/${r.name}`,s=Symbol("noValue"),i=!1,a=!1,u=!1,c=s,d=!1,l=n.cache??[];function f(h){if(u){u=!1;let g=c;if(c=s,g!==s){let y=l.find(v=>v.name===r.name),b=!1;try{b=y?.classify(g)??!1}catch{b=!1}b?(d=!1,h.emit(g)):d&&(d=!1,h.down([[ee],[$]]))}else d?(d=!1,h.down([[ee],[$]])):h.down([[$]])}}let p=K([],(h,g)=>{let y=e.subscribe(v=>{for(let T of v)m(T,0,g)}),b=n.subscribe(v=>{for(let T of v)m(T,1,g)});return()=>{y(),b()}},{describeKind:"derived",meta:{kind:"stratify_branch",branch:r.name},completeWhenDepsComplete:!1});function m(h,g,y){let b=h[0];return b===ee?(g===0?(i=!0,d=!0):a=!0,!0):b===S||b===$?(g===0?(i=!1,u=!0,c=b===S?h[1]:s):(b===S&&(l=h[1]),a=!1),i||a||f(y),!0):b===M||b===O||b===de?(i=!1,a=!1,u=!1,c=s,d=!1,g===0&&y.down([h]),!0):g===1}if(t.add(p,{name:o}),r.ops){let h=r.ops(p),g=`branch/${r.name}/out`;t.add(h,{name:g})}}vt();_e();ie();Ne();ne();ve();ie();var Fm=new Map([[ze,"INVALIDATE"],[Ge,"PAUSE"],[$e,"RESUME"],[de,"TEARDOWN"],[M,"COMPLETE"],[O,"ERROR"]]),$m=new Map([["INVALIDATE",ze],["PAUSE",Ge],["RESUME",$e],["TEARDOWN",de],["COMPLETE",M],["ERROR",O]]);function Ht(t){let e=Fm.get(t);return e||(Symbol.keyFor(t)??"UNKNOWN")}function gn(t){let e=$m.get(t);if(e)return e;if(t&&t!=="UNKNOWN")return Symbol.for(t)}function yn(t){return t instanceof Error?{message:t.message,name:t.name,stack:t.stack}:{message:String(t),name:"Error"}}function bn(t){let e=new Error(t.message);return e.name=t.name,t.stack&&(e.stack=t.stack),e}function Wt(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 Wt(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 Bm(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function ga(t,e){let n=Bm(t)?t:Wt(t),r=e.name??"workerBridge",o=Object.entries(e.expose??{}),s=e.import??[],i=e.transfer??{},a=N("connecting",{name:`${r}::meta::status`}),u=N(null,{name:`${r}::meta::error`}),c=new Map,d=new Map;for(let b of s){let v=N(void 0,{name:`${r}::${b}`});c.set(b,v)}let l;if(o.length>0){let b=o.map(([,w])=>w),v=K(b,(w,k)=>{let x={};for(let R=0;R<o.length;R++){let[_]=o[R],G=w[R];G!=null&&G.length>0&&(x[_]=G.at(-1))}Object.keys(x).length!==0&&k.emit(x)},{name:`${r}::aggregated`,partial:!0});l=me([v],w=>{let k=w[0];if(k==null||Object.keys(k).length===0)return;let x=[];for(let G of Object.keys(k)){let L=i[G];L&&x.push(...L(k[G]))}let R;for(let[G,L]of o)G in k&&L.v!=null&&(R==null&&(R={}),R[G]=L.v.version);let _={t:"b",u:k,...R?{v:R}:{}};try{n.post(_,x.length>0?x:void 0)}catch(G){u.down([[S,G instanceof Error?G:new Error(String(G))]])}}).subscribe(()=>{})}let f=!1,p=n.listen(b=>{if(f)return;let v=b;switch(v.t){case"r":{X(()=>{for(let[w,k]of Object.entries(v.stores)){let x=c.get(w);x&&x.down([[S,k]])}}),a.down([[S,"connected"]]);let T={};for(let[w,k]of o)T[w]=k.cache;n.post({t:"i",stores:T});break}case"v":{let T=c.get(v.s);T&&T.down([[S,v.d]]);break}case"b":{X(()=>{for(let[T,w]of Object.entries(v.u)){let k=v.v?.[T];if(k!=null){let R=d.get(T);if(R!=null&&k<=R)continue;d.set(T,k)}let x=c.get(T);x&&x.down([[S,w]])}});break}case"e":{let T=c.get(v.s);T&&T.down([[O,bn(v.err)]]);break}case"s":{let T=gn(v.sig);if(!T)break;let w=v.s==="*"?[...c.values()]:c.has(v.s)?[c.get(v.s)]:[];for(let k of w)k.down(v.d===void 0?[[T]]:[[T,v.d]]);break}}}),m=[];for(let[b,v]of o){let T=v.subscribe((w=>{if(!f)for(let k of w){let x=k[0];x!==S&&(Pe.isLocalOnly(x)||(x===O?n.post({t:"e",s:b,err:yn(k[1])}):n.post({t:"s",s:b,sig:Ht(x),d:k.length>1?k[1]:void 0})))}}));m.push(T)}let h;if(e.timeoutMs!=null&&e.timeoutMs>0){let b=at(e.timeoutMs),v=ft(a,w=>w==="connected");h=ls(wt(Lr(b,()=>"timeout"),Lr(v,()=>"ready"))).subscribe(w=>{for(let k of w)k[0]===S&&k[1]==="timeout"&&(u.down([[S,new Error("Worker bridge handshake timeout")]]),g())})}function g(){if(!f){f=!0,h?.(),n.post({t:"s",s:"*",sig:Ht(de)}),l&&l();for(let b of m)b();m.length=0,p(),a.down([[S,"closed"]]),d.clear(),c.clear()}}let y={meta:{status:a,error:u},destroy:g};for(let[b,v]of c)y[b]=v;return y}_e();ie();Ne();ne();function jm(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function ya(t,e){let n=jm(t)?t:Wt(t),r=e.import??[],o=e.transfer??{},s=new Map,i=new Map,a={};for(let g of r){let y=N(void 0,{name:`worker::${g}`});s.set(g,y),a[g]=y}let u=e.expose(a),c=Object.entries(u),d,l=!1;if(c.length>0){let g=c.map(([,v])=>v),y=K(g,(v,T)=>{let w={};for(let k=0;k<c.length;k++){let[x]=c[k],R=v[k];R!=null&&R.length>0&&(w[x]=R.at(-1))}Object.keys(w).length!==0&&T.emit(w)},{name:"workerSelf::aggregated",partial:!0});d=me([y],v=>{if(l)return;let T=v[0];if(T==null||Object.keys(T).length===0)return;let w=[];for(let R of Object.keys(T)){let _=o[R];_&&w.push(..._(T[R]))}let k;for(let[R,_]of c)R in T&&_.v!=null&&(k==null&&(k={}),k[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 f=[];for(let[g,y]of c){let b=y.subscribe((v=>{if(!l)for(let T of v){let w=T[0];w!==S&&(Pe.isLocalOnly(w)||(w===O?n.post({t:"e",s:g,err:yn(T[1])}):n.post({t:"s",s:g,sig:Ht(w),d:T.length>1?T[1]:void 0})))}}));f.push(b)}let p=n.listen(g=>{if(l)return;let y=g;switch(y.t){case"i":{X(()=>{for(let[b,v]of Object.entries(y.stores)){let T=s.get(b);T&&T.down([[S,v]])}});break}case"v":{let b=s.get(y.s);b&&b.down([[S,y.d]]);break}case"b":{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([[S,v]])}});break}case"e":{let b=s.get(y.s);b&&b.down([[O,bn(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 c)m[g]=y.cache;n.post({t:"r",stores:m});function h(){if(!l){l=!0,d&&d();for(let g of f)g();f.length=0,p(),n.terminate?.(),i.clear(),s.clear()}}return{destroy:h}}var vu={};ye(vu,{SNAPSHOT_WIRE_VERSION:()=>lo,SurfaceError:()=>ke,accountability:()=>Us,ai:()=>Hs,asSurfaceError:()=>ci,cqrs:()=>es,createGraph:()=>or,deleteSnapshot:()=>gi,demoShell:()=>Js,diffSnapshots:()=>mi,domainTemplates:()=>Ys,graphspec:()=>Ks,guarded:()=>Xs,harness:()=>ti,jobQueue:()=>oi,layout:()=>ai,lens:()=>ii,listSnapshots:()=>hi,memory:()=>Bs,messaging:()=>Is,orchestration:()=>Ps,reduction:()=>Vs,refine:()=>ei,resilientPipeline:()=>ui,restoreSnapshot:()=>fi,runReduction:()=>di,saveSnapshot:()=>pi,surface:()=>yi});var Hs={};ye(Hs,{AgentLoopGraph:()=>Fs,AllTiersExhaustedError:()=>Yr,BudgetExhaustedError:()=>Ns,ChatStreamGraph:()=>Ds,CircuitOpenError:()=>dt,DEFAULT_DECAY_RATE:()=>Wa,FallbackMissError:()=>Jm,LLMTimeoutError:()=>tr,ReplayCacheMissError:()=>wn,ToolRegistryGraph:()=>Gs,admissionFilter3D:()=>dg,agentLoop:()=>ig,agentMemory:()=>fg,anthropicAdapter:()=>va,canonicalJson:()=>wa,cascadingLlmAdapter:()=>Ia,chatStream:()=>Fa,composePricing:()=>mh,computePrice:()=>Ea,contentGate:()=>rg,costMeterExtractor:()=>Qh,createAdapter:()=>ch,createCapabilitiesRegistry:()=>Vm,createPricingRegistry:()=>ph,dryRunAdapter:()=>vn,fallbackAdapter:()=>ka,fromLLM:()=>_h,frozenContext:()=>Lh,gatedStream:()=>zh,gaugesAsContext:()=>mg,googleAdapter:()=>xa,graphFromSpec:()=>Sg,handoff:()=>ag,keywordFlagExtractor:()=>Zh,knobsAsTools:()=>Eg,llmConsolidator:()=>Ha,llmExtractor:()=>Ka,observableAdapter:()=>dh,openAICompatAdapter:()=>Sa,parseRateLimitFromError:()=>Ca,pricingFor:()=>hh,promptNode:()=>Qr,redactor:()=>og,registryPricing:()=>fh,resilientAdapter:()=>Eh,streamExtractor:()=>eg,streamingPromptNode:()=>Uh,suggestStrategy:()=>Mg,systemPromptBuilder:()=>Jh,tier:()=>Sh,toolCallExtractor:()=>ng,toolRegistry:()=>$a,toolSelector:()=>ug,validateGraphDef:()=>Og,withBreaker:()=>_a,withBudgetGate:()=>Oa,withDryRun:()=>yh,withRateLimiter:()=>La,withReplayCache:()=>Jr,withRetry:()=>Pa,withTimeout:()=>Da,zeroPrice:()=>Ss});ne();function zr(t,e){return`${t}::${e}`}function Vm(t){let e=Qe({name:"capabilitiesRegistry"}),n=c=>{e.set(zr(c.provider,c.id),c)};if(t)for(let c of t)n(c);let r=(c,d)=>{let l=e.get(zr(c,d));if(l)return l;let f=e.entries.cache;if(!f)return;let p;for(let[,m]of f){if(m.provider!==c)continue;let h=m.id;d.startsWith(h)&&(!p||h.length>p.id.length)&&(p=m)}return p},o=128,s=new Map,i=new Map,a=(c,d,l,f)=>{for(c.has(d)&&c.delete(d),c.set(d,l);c.size>f;){let p=c.keys().next().value;if(p===void 0)break;c.delete(p)}},u=E([e.entries],([c])=>Array.from(c.values()),{name:"capabilitiesRegistry/entries",initial:[]});return{register:n,lookup:r,remove(c,d){let l=e.has(zr(c,d));return l&&e.delete(zr(c,d)),l},entries(){let c=e.entries.cache;return(function*(){if(c)for(let d of c.values())yield d})()},lookupNode(c,d){let l=zr(c,d),f=s.get(l);if(f)return s.delete(l),s.set(l,f),f;let p=E([e.entries],()=>r(c,d),{name:`capabilitiesRegistry/lookup/${c}::${d}`,initial:void 0});return a(s,l,p,o),p},entriesNode:u,byProvider(c){let d=i.get(c);if(d)return i.delete(c),i.set(c,d),d;let l=E([u],([f])=>f.filter(p=>p.provider===c),{name:`capabilitiesRegistry/byProvider/${c}`,initial:[]});return a(i,c,l,o),l}}}we();function va(t={}){return t.sdk?Um(t):qm(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}=Km(t,e?.systemPrompt),a={model:o,messages:i.map(Hm),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(Wm)),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 Km(t,e){let n=[];e&&n.push(e);let r=[];for(let o of t)o.role==="system"?n.push(o.content):r.push(o);return{system:n.length>0?n.join(`
33
33
 
34
- `):void 0,chat:r}}function Lm(t){if(t.role==="tool")return{role:"user",content:[{type:"tool_result",tool_use_id:t.toolCallId,content:t.content}]};if(t.role==="assistant"&&t.toolCalls&&t.toolCalls.length>0){let e=[];t.content&&e.push({type:"text",text:t.content});for(let n of t.toolCalls)e.push({type:"tool_use",id:n.id,name:n.name,input:n.arguments});return{role:"assistant",content:e}}return{role:t.role,content:t.content}}function Im(t){return{name:t.name,description:t.description,input_schema:t.parameters}}function os(t,e){if(!t)return{...e};let n={...t};return e.input_tokens!=null&&(n.input_tokens=e.input_tokens),e.output_tokens!=null&&(n.output_tokens=e.output_tokens),e.cache_read_input_tokens!=null&&(n.cache_read_input_tokens=e.cache_read_input_tokens),e.cache_creation_input_tokens!=null&&(n.cache_creation_input_tokens=e.cache_creation_input_tokens),e.cache_creation&&(n.cache_creation={...t.cache_creation??{},...e.cache_creation}),e.server_tool_use&&(n.server_tool_use={...t.server_tool_use??{},...e.server_tool_use}),n}function oa(t){let e={input:{regular:t?.input_tokens??0},output:{regular:t?.output_tokens??0},raw:t};return t?.cache_read_input_tokens&&(e.input.cacheRead=t.cache_read_input_tokens),t?.cache_creation?(t.cache_creation.ephemeral_5m_input_tokens&&(e.input.cacheWrite5m=t.cache_creation.ephemeral_5m_input_tokens),t.cache_creation.ephemeral_1h_input_tokens&&(e.input.cacheWrite1h=t.cache_creation.ephemeral_1h_input_tokens)):t?.cache_creation_input_tokens&&(e.input.cacheWrite5m=t.cache_creation_input_tokens),t?.server_tool_use?.web_search_requests&&(e.auxiliary={webSearchRequests:t.server_tool_use.web_search_requests}),e}function xl(t,e){let n=[],r=[];for(let o of t.content)if(o.type==="text"&&typeof o.text=="string")n.push(o.text);else if(o.type==="tool_use"){let s=o;r.push({id:s.id,name:s.name,arguments:s.input??{}})}return{content:n.join(""),toolCalls:r.length>0?r:void 0,usage:oa(t.usage),finishReason:t.stop_reason,latencyMs:e,model:t.model,provider:"anthropic"}}function Pm(t){let e=t.apiKey??globalThis.process?.env?.ANTHROPIC_API_KEY,n=t.baseURL??"https://api.anthropic.com",r=t.anthropicVersion??"2023-06-01",o=t.fetchImpl??fetch,s=()=>{if(!e)throw new Error("anthropicAdapter: apiKey required for invoke/stream (or provide opts.sdk)");return{"x-api-key":e,"anthropic-version":r,"content-type":"application/json",...t.headers??{}}};return{provider:"anthropic",model:t.model,async invoke(i,a){let u=rs(i,a,t.model,!1),c=$(),d=await o(`${n}/v1/messages`,{method:"POST",headers:s(),body:JSON.stringify(u),signal:a?.signal});if(!d.ok)throw await kl(d);let l=await d.json(),f=Math.max(0,($()-c)/1e6);return xl(l,f)},async*stream(i,a){let u=rs(i,a,t.model,!0),c=await o(`${n}/v1/messages`,{method:"POST",headers:{...s(),accept:"text/event-stream"},body:JSON.stringify(u),signal:a?.signal});if(!c.ok)throw await kl(c);if(!c.body)throw new Error("anthropicAdapter: streaming response has no body");let d,l,f=new Map;for await(let p of Gm(c.body)){let m=p.data;if(!m)continue;let h;try{h=JSON.parse(m)}catch{continue}switch(h.type){case"message_start":{d=os(d,h.message.usage);break}case"content_block_start":{let g=h,y=g.content_block;y.type==="tool_use"&&(f.set(g.index,{id:String(y.id??""),name:String(y.name??""),argBuf:""}),yield{type:"tool-call-delta",delta:{id:String(y.id??""),name:String(y.name??"")}});break}case"content_block_delta":{let g=h,y=g.delta;if(y.type==="text_delta"&&typeof y.text=="string")yield{type:"token",delta:y.text};else if(y.type==="input_json_delta"&&typeof y.partial_json=="string"){let b=f.get(g.index);b&&(b.argBuf+=y.partial_json),yield{type:"tool-call-delta",delta:{argumentsDelta:y.partial_json}}}else y.type==="thinking_delta"&&typeof y.thinking=="string"&&(yield{type:"thinking",delta:y.thinking});break}case"message_delta":{let g=h;g.delta.stop_reason&&(l=g.delta.stop_reason),g.delta.usage&&(d=os(d,g.delta.usage));break}case"message_stop":break}}d&&(yield{type:"usage",usage:oa(d)}),yield{type:"finish",reason:l??"stop"}}}}function Dm(t){let e=t.sdk;if(!e)throw new Error("sdkBackedAnthropic: sdk instance required");return{provider:"anthropic",model:t.model,async invoke(n,r){let o=rs(n,r,t.model,!1),s=$(),i=await e.messages.create(o,{signal:r?.signal}),a=Math.max(0,($()-s)/1e6);return xl(i,a)},async*stream(n,r){if(!e.messages.stream)throw new Error("sdkBackedAnthropic: SDK instance does not expose .messages.stream");let o=rs(n,r,t.model,!0),s,i;for await(let a of e.messages.stream(o,{signal:r?.signal}))switch(a.type){case"message_start":s=os(s,a.message.usage);break;case"content_block_delta":{let u=a.delta;u?.type==="text_delta"&&typeof u.text=="string"?yield{type:"token",delta:u.text}:u?.type==="input_json_delta"&&typeof u.partial_json=="string"?yield{type:"tool-call-delta",delta:{argumentsDelta:u.partial_json}}:u?.type==="thinking_delta"&&typeof u.thinking=="string"&&(yield{type:"thinking",delta:u.thinking});break}case"message_delta":{let u=a;u.delta.stop_reason&&(i=u.delta.stop_reason),u.delta.usage&&(s=os(s,u.delta.usage));break}}s&&(yield{type:"usage",usage:oa(s)}),yield{type:"finish",reason:i??"stop"}}}}async function*Gm(t){let e=t.getReader(),n=new TextDecoder,r="";try{for(;;){let{done:o,value:s}=await e.read();if(o){r.length>0&&(yield Tl(r));return}r+=n.decode(s,{stream:!0});let i=wl(r);for(;i!==null;){let a=r.slice(0,i.index);r=r.slice(i.index+i.length);let u=Tl(a);(u.data||u.event)&&(yield u),i=wl(r)}}}finally{e.releaseLock()}}function Tl(t){let e={},n=[];for(let r of t.split(`
35
- `)){let o=r.endsWith("\r")?r.slice(0,-1):r;if(!o||o.startsWith(":"))continue;let s=o.indexOf(":"),i=s===-1?o:o.slice(0,s),a=s===-1?"":o.slice(s+1).replace(/^ /,"");i==="data"?n.push(a):i==="event"?e.event=a:i==="id"&&(e.id=a)}return n.length>0&&(e.data=n.join(`
36
- `)),e}function wl(t){let e=t.indexOf(`\r
37
- \r
38
- `),n=t.indexOf(`
34
+ `):void 0,chat:r}}function Hm(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 Wm(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 Ta(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 Dl(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:Ta(t.usage),finishReason:t.stop_reason,latencyMs:e,model:t.model,provider:"anthropic"}}function qm(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),c=V(),d=await o(`${n}/v1/messages`,{method:"POST",headers:s(),body:JSON.stringify(u),signal:a?.signal});if(!d.ok)throw await ht(d,"Anthropic");let l=await d.json(),f=Math.max(0,(V()-c)/1e6);return Dl(l,f)},async*stream(i,a){let u=bs(i,a,t.model,!0),c=await o(`${n}/v1/messages`,{method:"POST",headers:{...s(),accept:"text/event-stream"},body:JSON.stringify(u),signal:a?.signal});if(!c.ok)throw await ht(c,"Anthropic");if(!c.body)throw new Error("anthropicAdapter: streaming response has no body");let d,l,f=new Map;for await(let p of At(c.body,{signal:a?.signal})){let m=p.data;if(!m)continue;let h;try{h=JSON.parse(m)}catch{continue}switch(h.type){case"message_start":{d=vs(d,h.message.usage);break}case"content_block_start":{let g=h,y=g.content_block;y.type==="tool_use"&&(f.set(g.index,{id:String(y.id??""),name:String(y.name??""),argBuf:""}),yield{type:"tool-call-delta",delta:{id:String(y.id??""),name:String(y.name??"")}});break}case"content_block_delta":{let g=h,y=g.delta;if(y.type==="text_delta"&&typeof y.text=="string")yield{type:"token",delta:y.text};else if(y.type==="input_json_delta"&&typeof y.partial_json=="string"){let b=f.get(g.index);b&&(b.argBuf+=y.partial_json),yield{type:"tool-call-delta",delta:{argumentsDelta:y.partial_json}}}else y.type==="thinking_delta"&&typeof y.thinking=="string"&&(yield{type:"thinking",delta:y.thinking});break}case"message_delta":{let g=h;g.delta.stop_reason&&(l=g.delta.stop_reason),g.delta.usage&&(d=vs(d,g.delta.usage));break}case"message_stop":break}}d&&(yield{type:"usage",usage:Ta(d)}),yield{type:"finish",reason:l??"stop"}}}}function Um(t){let e=t.sdk;if(!e)throw new Error("sdkBackedAnthropic: sdk instance required");return{provider:"anthropic",model:t.model,async invoke(n,r){let o=bs(n,r,t.model,!1),s=V(),i=await e.messages.create(o,{signal:r?.signal}),a=Math.max(0,(V()-s)/1e6);return Dl(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:Ta(s)}),yield{type:"finish",reason:i??"stop"}}}}vt();function Ts(){let t=new Error("aborted");return t.name="AbortError",t}function Gl(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Ts()):new Promise((n,r)=>{let o=new Ce,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(Ts())},e.addEventListener("abort",s,{once:!0}))})}function vn(t={}){let e=t.provider??"dry-run",n=t.model??"dry-run-v1",r=t.latencyMs??0,o=Math.max(1,t.streamChunkSize??16),s=t.respond??(a=>{let u=[...a].reverse().find(c=>c.role==="user");return u?`echo: ${u.content}`:"dry-run: no user message"}),i=t.usage??((a,u)=>{let c=a.reduce((d,l)=>d+l.content.length,0);return{input:{regular:Math.ceil(c/4)},output:{regular:Math.ceil(u.length/4)}}});return{provider:e,model:n,async invoke(a,u){if(await Gl(r,u?.signal),u?.signal?.aborted)throw Ts();let c=s(a,u),d=i(a,c);return{content:c,usage:d,finishReason:"stop",model:u?.model??n,provider:e,tier:u?.tier,metadata:{dryRun:!0}}},async*stream(a,u){let c=s(a,u),d=i(a,c),l=Math.ceil(c.length/o)||1,f=r>0?r/l:0;for(let p=0;p<c.length;p+=o){if(u?.signal?.aborted)throw Ts();await Gl(f,u?.signal),yield{type:"token",delta:c.slice(p,p+o)}}yield{type:"usage",usage:d},yield{type:"finish",reason:"stop"}}}}we();we();ve();vt();function Fl(t){let{storage:e,mode:n="read-write",keyFn:r,keyPrefix:o="llm-replay"}=t,i=hs({storage:e,keyPrefix:o,mode:n==="read-strict"?"read":n,keyContext:({messages:u,opts:c})=>{let{signal:d,keyContext:l,...f}=c??{};return{messages:u,opts:f}}});async function a(u,c){if(r){if(r.length<=1){let l={messages:u,opts:c,context:c?.keyContext},f=await r(l);return`${o}:${f}`}let d=await r(u,c);return`${o}:${d}`}return i.keyFor({messages:u,opts:c})}return{keyFor:a,async lookup(u,c){if(n!=="write"){if(r){let d=await a(u,c),l=await e.load(d);return l??void 0}return i.lookup({messages:u,opts:c})}},async store(u,c,d){if(n!=="read"){if(r){let l=await a(u,c);await e.save(l,d);return}await i.store({messages:u,opts:c},d)}},async forget(u,c){if(!(n==="read"||n==="write")&&e.clear){if(r){let d=await a(u,c);await e.clear(d);return}await i.forget({messages:u,opts:c})}}}}we();ie();ne();ve();function Xe(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 ws(t,e){let{onResp:n,onError:r,name:o}=e;if(t!=null&&typeof t.then=="function"){let c=t;return r?c.then(n).catch(d=>{throw r(d),d}):c.then(n)}if(t!=null&&typeof t=="object"&&"content"in t)return n(t);let s=z(t);if(r){let c=!1;s.subscribe(d=>{for(let l of d){if(c)return;l[0]===O&&(c=!0,r(l[1]))}})}let i,a=!1,u=Pr(s,c=>{i=n(c),a=!0});return E([u],([c])=>c==null?null:a?i:n(c),{name:o??"adapt/invokeTap"})}function Tn(t){let e=t.endNs??V();return{timestamp:e,wallClock:t.startWallClockNs??le(),provider:t.provider,model:t.model,tier:t.tier,usage:t.usage,latencyMs:Math.max(0,(e-t.startNs)/1e6),method:t.method,...t.error?{error:t.error}:{}}}function kt(){return{input:{regular:0},output:{regular:0}}}var $l=Symbol.for("graphrefly.adapter.middlewareLayers");function Ue(t,e,n){let o=[...n?zm(n):[],e];return Object.defineProperty(t,$l,{value:Object.freeze(o),enumerable:!1,writable:!1,configurable:!1}),t}function zm(t){let e=t[$l];return Array.isArray(e)?e:[]}var wn=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 Jr(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=Fl({storage:e.storage,mode:n==="write-only"?"write":n,keyFn:e.keyFn,keyPrefix:i}),c=f=>f<=0?Promise.resolve():new Promise(p=>{new Ce().start(f,()=>p())}),d=ys(async({messages:f,invokeOpts:p})=>await Ye(z(t.invoke(f,p))),{keyFn:({_precomputedKey:f})=>f}),l=Xe(t,{async invoke(f,p){let m=await u.keyFor(f,p),h=await u.lookup(f,p);if(h?.response){let y=h.response;return{...y,metadata:{...y.metadata??{},replayCache:"hit"}}}if(n==="read-strict")throw new wn(m,"invoke");let g=await d({messages:f,invokeOpts:p,_precomputedKey:m});return a||await u.store(f,p,{response:g,storedAtNs:le()}),g},async*stream(f,p){if(!r){for await(let k of t.stream(f,p))yield k;return}let m=await u.keyFor(f,p),h=await u.lookup(f,p);if(h){let k=h.response;if(h.streamChunks&&h.streamCadenceMs)for(let x=0;x<h.streamChunks.length;x++){let R=h.streamCadenceMs[x]??0,_=s>0?R/s:0;_>0&&await c(_),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 wn(m,"stream");let g="",y,b,v=[],T=[],w;for await(let k of t.stream(f,p)){if(k.type==="token"&&(g+=k.delta,o)){let x=V(),R=w===void 0?0:(x-w)/1e6;T.push(R),w=x,v.push({delta:k.delta})}k.type==="usage"&&(y=k.usage),k.type==="finish"&&(b=k.reason),yield k}if((g||y)&&!a){let x={response:{content:g,usage:y??{input:{regular:0},output:{regular:0}},finishReason:b,model:t.model??p?.model??"",provider:t.provider},storedAtNs:le(),...o?{streamChunks:v,streamCadenceMs:T}:{}};await u.store(f,p,x)}}});return Ue(l,"withReplayCache",t),l}var wa=jr;var Jm=wn;function Bl(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 jl(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 Ym(t,e){if("key"in t)return t.key;let n=wa({messages:t.messages,opts:t.invokeOpts??{}}),r=await ms(n);return`${e}:${r}`}function Qm(t){let e={response:t.response,storedAtNs:le()};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 Xm(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=qr(),o=t.fixtures,s=(async()=>{for(let i of o){let a=await Ym(i,e);await r.save(a,Qm(i))}})();return s.catch(()=>{}),{tier:r,seedReady:s}}return t.fixturesStorage?{tier:t.fixturesStorage,seedReady:Promise.resolve()}:{tier:void 0,seedReady:Promise.resolve()}}function ka(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"?vn({provider:e,model:n,respond:()=>"[unreachable: read-strict mode throws on miss]"}):{provider:e,model:n,async invoke(d,l){let f=t.respond?t.respond(d,l):Bl(e,n);return jl(f,e,n)},async*stream(d,l){let f=t.respond?t.respond(d,l):Bl(e,n),p=jl(f,e,n);yield{type:"token",delta:p.content},p.usage&&(yield{type:"usage",usage:p.usage}),yield{type:"finish",reason:p.finishReason??"stop"}}},i,a=Promise.resolve();if(t.record){if(!t.record.storage)throw new TypeError("fallbackAdapter: `record.storage` is required in record mode. For filesystem `record.dir` convenience, use the node subpath's `fallbackAdapter`.");i=t.record.storage}else{let d=Xm(t,o);i=d.tier??qr(),a=d.seedReady}let u=t.record?"read-write":r==="throw"?"read-strict":"read",c=Jr(s,{storage:i,mode:u,keyPrefix:o,cacheStreaming:!0,captureStreamCadence:!0,replaySpeed:t.replaySpeed,...t.keyFn?{keyFn:t.keyFn}:{}});return{provider:e,model:n,capabilities:c.capabilities?.bind(c),async invoke(d,l){return await a,c.invoke(d,l)},async*stream(d,l){await a;for await(let f of c.stream(d,l))yield f}}}we();function xa(t={}){return t.sdk?nh(t):th(t)}function ks(t,e){let n=[],r=[];e?.systemPrompt&&n.push(e.systemPrompt);for(let i of t){if(i.role==="system"){n.push(i.content);continue}if(i.role==="tool"){r.push({role:"user",parts:[{functionResponse:{name:i.name??i.toolCallId??"tool",response:{result:i.content}}}]});continue}if(i.role==="assistant"&&i.toolCalls&&i.toolCalls.length>0){let a=[];i.content&&a.push({text:i.content});for(let u of i.toolCalls)a.push({functionCall:{name:u.name,args:u.arguments}});r.push({role:"model",parts:a});continue}r.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let o={contents:r};n.length>0&&(o.systemInstruction={role:"system",parts:[{text:n.join(`
39
35
 
40
- `),r=null;return e!==-1&&(r={index:e,length:4}),n!==-1&&(r===null||n<r.index)&&(r={index:n,length:2}),r}async function kl(t){let e;try{e=await t.text()}catch{e=""}let n=new Error(`Anthropic API ${t.status}: ${t.statusText}${e?` \u2014 ${e}`:""}`);return n.status=t.status,n.headers=t.headers,n}pt();function ss(){let t=new Error("aborted");return t.name="AbortError",t}function Rl(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(ss()):new Promise((n,r)=>{let o=new _e,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(ss())},e.addEventListener("abort",s,{once:!0}))})}function St(t={}){let e=t.provider??"dry-run",n=t.model??"dry-run-v1",r=t.latencyMs??0,o=Math.max(1,t.streamChunkSize??16),s=t.respond??(a=>{let u=[...a].reverse().find(c=>c.role==="user");return u?`echo: ${u.content}`:"dry-run: no user message"}),i=t.usage??((a,u)=>{let c=a.reduce((d,l)=>d+l.content.length,0);return{input:{regular:Math.ceil(c/4)},output:{regular:Math.ceil(u.length/4)}}});return{provider:e,model:n,async invoke(a,u){if(await Rl(r,u?.signal),u?.signal?.aborted)throw ss();let c=s(a,u),d=i(a,c);return{content:c,usage:d,finishReason:"stop",model:u?.model??n,provider:e,tier:u?.tier,metadata:{dryRun:!0}}},async*stream(a,u){let c=s(a,u),d=i(a,c),l=Math.ceil(c.length/o)||1,f=r>0?r/l:0;for(let p=0;p<c.length;p+=o){if(u?.signal?.aborted)throw ss();await Rl(f,u?.signal),yield{type:"token",delta:c.slice(p,p+o)}}yield{type:"usage",usage:d},yield{type:"finish",reason:"stop"}}}}ke();async function is(t){let e=typeof t=="string"?new TextEncoder().encode(t):t,n=await globalThis.crypto.subtle.digest("SHA-256",e),r=new Uint8Array(n),o="";for(let s=0;s<r.length;s++)o+=Sl[r[s]];return o}var Sl=new Array(256);for(let t=0;t<256;t++)Sl[t]=t.toString(16).padStart(2,"0");ke();pt();var mn=class extends Error{constructor(n,r){super(`withReplayCache: no cached response for ${r} (key=${n}, mode=read-strict)`);this.key=n;this.method=r}name="ReplayCacheMissError"};function sa(t,e){let n=e.mode??"read-write",r=e.cacheStreaming??!1,o=e.captureStreamCadence??!1,s=e.replaySpeed??1,i=e.keyPrefix??"llm-replay",a=e.storage,u=n==="read"||n==="read-strict",c=async(h,g)=>{if(e.keyFn){let k=e.keyFn;if(k.length<=1){let R={messages:h,opts:g,context:g?.keyContext},E=await k(R);return`${i}:${E}`}let x=await k(h,g);return`${i}:${x}`}let{signal:y,keyContext:b,...v}=g??{},T=as({messages:h,opts:v}),w=await is(T);return`${i}:${w}`},d=async h=>{if(n==="write-only")return;let g=await a.load(h);if(g!=null)try{return typeof g=="string"?JSON.parse(g):g}catch{return}},l=async h=>(await d(h))?.response,f=async(h,g,y)=>{if(u)return;let b={response:g,storedAtNs:pe(),...y?{streamChunks:y.chunks,streamCadenceMs:y.delaysMs}:{}};await a.save(h,b)},p=h=>h<=0?Promise.resolve():new Promise(g=>{new _e().start(h,()=>g())}),m=ts(async({messages:h,invokeOpts:g})=>{let y=t.invoke(h,g);return await Fm(y)},{keyFn:({_precomputedKey:h})=>h});return{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(h,g){let y=await c(h,g),b=await l(y);if(b)return{...b,metadata:{...b.metadata??{},replayCache:"hit"}};if(n==="read-strict")throw new mn(y,"invoke");let v=await m({messages:h,invokeOpts:g,_precomputedKey:y});return await f(y,v),v},async*stream(h,g){if(!r){for await(let E of t.stream(h,g))yield E;return}let y=await c(h,g),b=await d(y);if(b){let E=b.response;if(b.streamChunks&&b.streamCadenceMs)for(let G=0;G<b.streamChunks.length;G++){let L=b.streamCadenceMs[G]??0,P=s>0?L/s:0;P>0&&await p(P),yield{type:"token",delta:b.streamChunks[G]?.delta??""}}else E.content&&(yield{type:"token",delta:E.content});E.usage&&(yield{type:"usage",usage:E.usage}),yield{type:"finish",reason:E.finishReason??"stop"};return}if(n==="read-strict")throw new mn(y,"stream");let v="",T,w,k=[],x=[],R;for await(let E of t.stream(h,g)){if(E.type==="token"&&(v+=E.delta,o)){let G=$(),L=R===void 0?0:(G-R)/1e6;x.push(L),R=G,k.push({delta:E.delta})}E.type==="usage"&&(T=E.usage),E.type==="finish"&&(w=E.reason),yield E}if(v||T){let E={content:v,usage:T??{input:{regular:0},output:{regular:0}},finishReason:w,model:t.model??g?.model??"",provider:t.provider};await f(y,E,o?{chunks:k,delaysMs:x}:void 0)}}}}function as(t){let e=new Set,n=r=>{if(r===null||typeof r!="object")return r;let o=r;if(e.has(o))return{__cycle:!0};e.add(o);try{if(Array.isArray(r))return r.map(n);let s={};for(let i of Object.keys(r).sort())s[i]=n(r[i]);return s}finally{e.delete(o)}};return JSON.stringify(n(t))}async function Fm(t){if(t!=null&&typeof t.then=="function")return await t;if(t&&typeof t=="object"&&"content"in t)return t;throw new Error("withReplayCache: adapter.invoke must return Promise or LLMResponse (Node input not supported in cache path)")}var $m=mn;function Nl(t,e){return{content:"[fallback: no cached response available for this request]",usage:{input:{regular:0},output:{regular:0}},finishReason:"stop",model:e,provider:t,metadata:{degraded:!0,reason:"no-fixture"}}}function El(t,e,n){return typeof t=="string"?{content:t,usage:{input:{regular:0},output:{regular:0}},finishReason:"stop",model:n,provider:e,metadata:{degraded:!0,reason:"respond"}}:t}async function Bm(t,e){if("key"in t)return t.key;let n=as({messages:t.messages,opts:t.invokeOpts??{}}),r=await is(n);return`${e}:${r}`}function jm(t){let e={response:t.response,storedAtNs:pe()};if("key"in t&&t.stream){let n=t.stream.chunks.filter(r=>r.type==="token");return{...e,streamChunks:n.map(r=>({delta:r.delta})),streamCadenceMs:t.stream.delaysMs??n.map(()=>0)}}return e}function Vm(t,e){let n=[];if(t.fixtures!=null&&n.push("fixtures"),t.fixturesStorage!=null&&n.push("fixturesStorage"),n.length>1)throw new TypeError(`fallbackAdapter: \`fixtures\` and \`fixturesStorage\` are mutually exclusive; got both ${n.join(" and ")}. Pick one source. For filesystem directories use the node subpath's \`fallbackAdapter\`.`);if(t.fixtures){let r=Gr(),o=t.fixtures,s=(async()=>{for(let i of o){let a=await Bm(i,e);await r.save(a,jm(i))}})();return s.catch(()=>{}),{tier:r,seedReady:s}}return t.fixturesStorage?{tier:t.fixturesStorage,seedReady:Promise.resolve()}:{tier:void 0,seedReady:Promise.resolve()}}function ia(t={}){let e=t.provider??"fallback",n=t.model??"fallback",r=t.onMiss??"respond",o=t.keyPrefix??"fallback",s=t.record?t.record.adapter:r==="throw"?St({provider:e,model:n,respond:()=>"[unreachable: read-strict mode throws on miss]"}):{provider:e,model:n,async invoke(d,l){let f=t.respond?t.respond(d,l):Nl(e,n);return El(f,e,n)},async*stream(d,l){let f=t.respond?t.respond(d,l):Nl(e,n),p=El(f,e,n);yield{type:"token",delta:p.content},p.usage&&(yield{type:"usage",usage:p.usage}),yield{type:"finish",reason:p.finishReason??"stop"}}},i,a=Promise.resolve();if(t.record){if(!t.record.storage)throw new TypeError("fallbackAdapter: `record.storage` is required in record mode. For filesystem `record.dir` convenience, use the node subpath's `fallbackAdapter`.");i=t.record.storage}else{let d=Vm(t,o);i=d.tier??Gr(),a=d.seedReady}let u=t.record?"read-write":r==="throw"?"read-strict":"read",c=sa(s,{storage:i,mode:u,keyPrefix:o,cacheStreaming:!0,captureStreamCadence:!0,replaySpeed:t.replaySpeed,...t.keyFn?{keyFn:t.keyFn}:{}});return{provider:e,model:n,capabilities:c.capabilities?.bind(c),async invoke(d,l){return await a,c.invoke(d,l)},async*stream(d,l){await a;for await(let f of c.stream(d,l))yield f}}}ke();function aa(t={}){return t.sdk?qm(t):Wm(t)}function us(t,e){let n=[],r=[];e?.systemPrompt&&n.push(e.systemPrompt);for(let i of t){if(i.role==="system"){n.push(i.content);continue}if(i.role==="tool"){r.push({role:"user",parts:[{functionResponse:{name:i.name??i.toolCallId??"tool",response:{result:i.content}}}]});continue}if(i.role==="assistant"&&i.toolCalls&&i.toolCalls.length>0){let a=[];i.content&&a.push({text:i.content});for(let u of i.toolCalls)a.push({functionCall:{name:u.name,args:u.arguments}});r.push({role:"model",parts:a});continue}r.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let o={contents:r};n.length>0&&(o.systemInstruction={role:"system",parts:[{text:n.join(`
36
+ `)}]});let s={};return e?.maxTokens!=null&&(s.maxOutputTokens=e.maxTokens),e?.temperature!=null&&(s.temperature=e.temperature),e?.maxReasoningTokens!=null&&(s.thinkingConfig={thinkingBudget:e.maxReasoningTokens}),Object.keys(s).length>0&&(o.generationConfig=s),e?.tools&&e.tools.length>0&&(o.tools=[{functionDeclarations:e.tools.map(Zm)}]),e?.providerExtras&&Object.assign(o,e.providerExtras),o}function Zm(t){return{name:t.name,description:t.description,parameters:t.parameters}}function Ra(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 Vl(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:Ra(t.usageMetadata),finishReason:n?.finishReason,latencyMs:e,model:t.modelVersion,provider:"google"}}function eh(t){if(t.apiKey)return t.apiKey;let e=globalThis.process?.env;return e?.GOOGLE_API_KEY??e?.GEMINI_API_KEY}function th(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=eh(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=ks(s,i),c=V(),d=`${e}/models/${encodeURIComponent(a)}:generateContent?${o()}`,l=await n(d,{method:"POST",headers:{"content-type":"application/json",...t.headers??{}},body:JSON.stringify(u),signal:i?.signal});if(!l.ok)throw await ht(l,"Google");let f=await l.json(),p=Math.max(0,(V()-c)/1e6);return Vl(f,p)},async*stream(s,i){let a=r(i),u=ks(s,i),c=`${e}/models/${encodeURIComponent(a)}:streamGenerateContent?alt=sse&${o()}`,d=await n(c,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",...t.headers??{}},body:JSON.stringify(u),signal:i?.signal});if(!d.ok)throw await ht(d,"Google");if(!d.body)throw new Error("googleAdapter: streaming response has no body");let l,f;for await(let p of At(d.body,{signal:i?.signal})){if(!p.data)continue;let m;try{m=JSON.parse(p.data)}catch{continue}let h=m.candidates?.[0];for(let g of h?.content?.parts??[])typeof g.text=="string"&&(g.thought?yield{type:"thinking",delta:g.text}:yield{type:"token",delta:g.text}),g.functionCall&&(yield{type:"tool-call-delta",delta:{name:g.functionCall.name,argumentsDelta:JSON.stringify(g.functionCall.args??{})}});h?.finishReason&&(f=h.finishReason),m.usageMetadata&&(l=m.usageMetadata)}l&&(yield{type:"usage",usage:Ra(l)}),yield{type:"finish",reason:f??"stop"}}}}function nh(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=ks(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=V(),a=await e.models.generateContent({...o,model:s},{signal:r?.signal}),u=Math.max(0,(V()-i)/1e6);return Vl(a,u)},async*stream(n,r){if(!e.models.generateContentStream)throw new Error("sdkBackedGoogle: SDK instance does not expose generateContentStream");let o=ks(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i,a;for await(let u of e.models.generateContentStream({...o,model:s},{signal:r?.signal})){let c=u.candidates?.[0];for(let d of c?.content?.parts??[])typeof d.text=="string"&&(d.thought?yield{type:"thinking",delta:d.text}:yield{type:"token",delta:d.text}),d.functionCall&&(yield{type:"tool-call-delta",delta:{name:d.functionCall.name,argumentsDelta:JSON.stringify(d.functionCall.args??{})}});c?.finishReason&&(a=c.finishReason),u.usageMetadata&&(i=u.usageMetadata)}i&&(yield{type:"usage",usage:Ra(i)}),yield{type:"finish",reason:a??"stop"}}}}we();var rh={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 Sa(t={}){return t.sdk?uh(t):ah(t)}function xs(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(oh);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(sh)),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 oh(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 sh(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}}function Na(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 Kl(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:ih(a.function.arguments)}));return{content:s,toolCalls:i.length>0?i:void 0,usage:Na(t.usage),finishReason:r?.finish_reason,latencyMs:e,model:t.model,provider:n}}function ih(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!=null?e:{_raw:t}}catch{return{_raw:t}}}function Hl(t){let e=t.preset??"openai",n=rh[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 ah(t){let{provider:e,baseURL:n,apiKey:r}=Hl(t),o=t.fetchImpl??fetch,s=e!=="ollama",i=()=>{let a={"content-type":"application/json",...t.headers??{}};if(s){if(!r)throw new Error(`openAICompatAdapter[${e}]: apiKey required for invoke/stream`);a.authorization=`Bearer ${r}`}return a};return{provider:e,model:t.model,async invoke(a,u){let c=xs(a,u,t.model,!1,t.bodyExtras),d=V(),l=await o(`${n}/chat/completions`,{method:"POST",headers:i(),body:JSON.stringify(c),signal:u?.signal});if(!l.ok)throw await ht(l,e);let f=await l.json(),p=Math.max(0,(V()-d)/1e6);return Kl(f,p,e)},async*stream(a,u){let c=xs(a,u,t.model,!0,t.bodyExtras),d=await o(`${n}/chat/completions`,{method:"POST",headers:{...i(),accept:"text/event-stream"},body:JSON.stringify(c),signal:u?.signal});if(!d.ok)throw await ht(d,e);if(!d.body)throw new Error(`openAICompatAdapter[${e}]: streaming response has no body`);let l,f;for await(let p of At(d.body,{signal:u?.signal})){if(!p.data||p.data==="[DONE]")continue;let m;try{m=JSON.parse(p.data)}catch{continue}let h=m.choices;if(h){let g=h[0];if(g?.delta?.content&&(yield{type:"token",delta:g.delta.content}),g?.delta?.reasoning_content&&(yield{type:"thinking",delta:g.delta.reasoning_content}),g?.delta?.tool_calls)for(let y of g.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:y.id,name:y.function?.name,argumentsDelta:y.function?.arguments}};g?.finish_reason&&(f=g.finish_reason)}m.usage&&(l=m.usage,yield{type:"usage",usage:Na(l)})}yield{type:"finish",reason:f??"stop"}}}}function uh(t){let e=t.sdk;if(!e)throw new Error("sdkBackedOpenAI: sdk instance required");let{provider:n}=Hl(t);return{provider:n,model:t.model,async invoke(r,o){let s=xs(r,o,t.model,!1,t.bodyExtras),i=V(),a=await e.chat.completions.create(s,{signal:o?.signal}),u=Math.max(0,(V()-i)/1e6);return Kl(a,u,n)},async*stream(r,o){let s=xs(r,o,t.model,!0,t.bodyExtras),i=await e.chat.completions.create(s,{signal:o?.signal}),a,u;for await(let c of i){let d=c.choices;if(d){let f=d[0];if(f?.delta?.content&&(yield{type:"token",delta:f.delta.content}),f?.delta?.reasoning_content&&(yield{type:"thinking",delta:f.delta.reasoning_content}),f?.delta?.tool_calls)for(let p of f.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:p.id,name:p.function?.name,argumentsDelta:p.function?.arguments}};f?.finish_reason&&(u=f.finish_reason)}let l=c.usage;l&&(a=l,yield{type:"usage",usage:Na(l)})}yield{type:"finish",reason:u??"stop"}}}}function ch(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 va(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 xa(e)}case"dry-run":{let e={model:t.model,...t.extras};return vn(e)}case"fallback":{let e={provider:t.provider,model:t.model,...t.extras};return ka(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 Sa(e)}default:{let e=t.provider;throw new Error(`createAdapter: unknown provider: ${String(e)}`)}}}we();ne();ve();function gt(t){let e=t.input,n=e.regular+(e.cacheRead??0)+(e.cacheWrite5m??0)+(e.cacheWrite1h??0)+(e.cacheWriteOther??0)+(e.audio??0)+(e.image??0)+(e.video??0)+(e.toolUse??0);if(!e.extensions)return n;let r=0;for(let o of Object.values(e.extensions))r+=o;return n+r}function Lt(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 Wl(){return{input:{regular:0},output:{regular:0}}}function dh(t,e){let n=e?.logMax??1e3,r=We(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:n}),o=N(null,{name:"adapterStats/lastCall"}),s=E([r.entries],([h])=>h.length,{name:"adapterStats/totalCalls",initial:0}),i=E([r.entries],([h])=>h.reduce((g,y)=>g+gt(y.usage),0),{name:"adapterStats/totalInputTokens",initial:0}),a=E([r.entries],([h])=>h.reduce((g,y)=>g+Lt(y.usage),0),{name:"adapterStats/totalOutputTokens",initial:0}),u=[re(s),re(i),re(a)],c=h=>{r.append(h),o.emit(h)},d=()=>{r.clear(),o.emit(null)},l=Xe(t,{invoke(h,g){let y=V(),b=le(),v=t.model??g?.model??"",T=k=>(c(Tn({provider:t.provider,model:t.model??g?.model??k.model??"",tier:g?.tier??k.tier,usage:k.usage??kt(),startNs:y,startWallClockNs:b,method:"invoke"})),k),w=k=>{let x=k;c(Tn({provider:t.provider,model:v,tier:g?.tier,usage:kt(),startNs:y,startWallClockNs:b,method:"invoke",error:{type:x?.name??"Error",message:x?.message??String(k)}}))};return ws(t.invoke(h,g),{onResp:T,onError:w,name:"adapterStats/invokeTap"})},async*stream(h,g){let y=V(),b=le(),v=t.model??g?.model??"",T;try{for await(let w of t.stream(h,g))w.type==="usage"&&(T=w.usage),yield w;c(Tn({provider:t.provider,model:v,tier:g?.tier,usage:T??kt(),startNs:y,startWallClockNs:b,method:"stream"}))}catch(w){let k=w;throw c(Tn({provider:t.provider,model:v,tier:g?.tier,usage:T??kt(),startNs:y,startWallClockNs:b,method:"stream",error:{type:k?.name??"Error",message:k?.message??String(w)}})),w}}});Ue(l,"observableAdapter",t);let f=!1;return{adapter:l,stats:{lastCall:o,allCalls:r,totalCalls:s,totalInputTokens:i,totalOutputTokens:a,reset:d,dispose:()=>{if(!f){f=!0;for(let h of u)h();u.length=0}}}}}function lh(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function Ss(t="USD"){return{total:0,currency:t}}function Ea(t,e,n){let r=gt(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=lh(b,r),T=y*v/1e6;a+=T,s&&(i[g]=(i[g]??0)+T)},c=t.input,d=e.input;if(d&&(u("input.regular",c.regular,d.regular),u("input.cacheRead",c.cacheRead??0,d.cacheRead),u("input.cacheWrite5m",c.cacheWrite5m??0,d.cacheWrite5m),u("input.cacheWrite1h",c.cacheWrite1h??0,d.cacheWrite1h),u("input.cacheWriteOther",c.cacheWriteOther??0,d.cacheWriteOther),u("input.audio",c.audio??0,d.audio),u("input.image",c.image??0,d.image),u("input.video",c.video??0,d.video),u("input.toolUse",c.toolUse??0,d.toolUse),c.extensions&&d.extensions))for(let[g,y]of Object.entries(c.extensions))u(`input.ext.${g}`,y,d.extensions[g]);let l=t.output,f=e.output;if(f&&(u("output.regular",l.regular,f.regular),u("output.reasoning",l.reasoning??0,f.reasoning),u("output.audio",l.audio??0,f.audio),u("output.predictionAccepted",l.predictionAccepted??0,f.predictionAccepted),u("output.predictionRejected",l.predictionRejected??0,f.predictionRejected),l.extensions&&f.extensions))for(let[g,y]of Object.entries(l.extensions))u(`output.ext.${g}`,y,f.extensions[g]);let p=n?.tier;if(p&&e.tierMultipliers){let g=e.tierMultipliers[p];if(g!=null&&(a*=g,s))for(let y of Object.keys(i))i[y]*=g}let m=t.auxiliary,h=e.auxiliary;if(m&&h)for(let[g,y]of Object.entries(m)){let b=h[g];if(b==null||!y)continue;let v=y*b;a+=v,s&&(i[`auxiliary.${g}`]=v)}return s?{total:a,currency:o,breakdown:i}:{total:a,currency:o}}function Rs(t,e){return`${t}::${e}`}function ph(t){let e=new Map,n=new Map,r=(o,s,i)=>{e.set(Rs(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(Rs(o,s));if(i)return i.pricing;let a=n.get(o);if(!a)return;let u;for(let c of a)if(s.startsWith(c)&&(!u||c.length>u.key.length)){let d=e.get(Rs(o,c));d&&(u={key:c,pricing:d.pricing})}return u?.pricing},remove(o,s){let i=e.delete(Rs(o,s));if(i){let a=n.get(o);a?.delete(s),a&&a.size===0&&n.delete(o)}return i},entries(){let o=e.values();return(function*(){for(let{provider:s,model:i,pricing:a}of o)yield[s,i,a]})()}}}function fh(t,e="USD"){return(n,r)=>{let o=t.lookup(r.provider,r.model);return o?Ea(n,o,{tier:r.tier,withBreakdown:r.withBreakdown}):Ss(e)}}function mh(...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):Ss()}}function hh(t,e,n){return t?.pricing?Ea(e,t.pricing,n):Ss()}Et();ve();function _a(t,e={}){let n=e.breaker??Tt(e),r=Xe(t,{async invoke(o,s){if(!n.canExecute())throw new dt;try{let i=await Ye(z(t.invoke(o,s)));return n.recordSuccess(),i}catch(i){throw n.recordFailure(i),i}},async*stream(o,s){if(!n.canExecute())throw new dt;try{for await(let i of t.stream(o,s))yield i;n.recordSuccess()}catch(i){throw n.recordFailure(i),i}}});return Ue(r,"withBreaker",t),{adapter:r,breaker:n}}we();ie();ne();ve();var Ns=class extends Error{constructor(n,r,o){super(`Budget exhausted: ${n} (limit=${r}, observed=${o})`);this.which=n;this.limit=r;this.observed=o}name="BudgetExhaustedError"},Ma=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),ql=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function Oa(t,e){let n=We(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),r=N(ql(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=E([r],([c])=>{let d=c;return!(e.caps.calls!=null&&d.calls>=e.caps.calls||e.caps.inputTokens!=null&&d.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&d.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&d.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(re(o),e.onExhausted!=null){let c=e.onExhausted,d=!1,l=!0;o.subscribe(f=>{for(let p of f)if(p[0]===S){let m=p[1];if(d&&l&&m===!1){let h=Ul(r.cache??Ma,e.caps);h&&c(h)}l=m,d=!0}})}let s=()=>{if(o.cache===!1){let c=r.cache??Ma,d=Ul(c,e.caps);return new Ns(d??"budget",e.caps[d??"calls"]??0,gh(c,d??"calls"))}},i=(c,d)=>{let l=t.provider,f=Tn({provider:l,model:d.model,tier:d.tier,usage:c,startNs:d.startNs,method:d.method,...d.error?{error:d.error}:{}});n.append(f);let p=r.cache??Ma,m=e.pricingFn?p.usd+e.pricingFn(c,{model:d.model,provider:l,tier:d.tier}).total:p.usd;r.emit({calls:p.calls+1,inputTokens:p.inputTokens+gt(c),outputTokens:p.outputTokens+Lt(c),usd:m})},a=()=>{n.clear(),r.emit(ql())},u=Xe(t,{invoke(c,d){let l=s();if(l)return Promise.reject(l);let f=V(),p=t.model??d?.model??"",m=g=>(i(g.usage??kt(),{model:t.model??d?.model??g.model??"",tier:d?.tier??g.tier,startNs:f,method:"invoke"}),g),h=g=>{let y=g;i(kt(),{model:p,tier:d?.tier,startNs:f,method:"invoke",error:{type:y?.name??"Error",message:y?.message??String(g)}})};return ws(t.invoke(c,d),{onResp:m,onError:h,name:"budgetGate/invokeTap"})},async*stream(c,d){let l=s();if(l)throw l;let f=V(),p;try{for await(let m of t.stream(c,d))m.type==="usage"&&(p=m.usage),yield m;i(p??kt(),{model:t.model??d?.model??"",tier:d?.tier,startNs:f,method:"stream"})}catch(m){let h=m;throw i(p??kt(),{model:t.model??d?.model??"",tier:d?.tier,startNs:f,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 Ul(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 gh(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}ve();function yh(t,e){let n=e.mock??vn({provider:t.provider,model:t.model}),r=typeof e.enabled=="boolean"?e.enabled:void 0,o=r===void 0?z(e.enabled):void 0,s;o&&(s=re(o));let i=()=>r!==void 0?r:!!o?.cache,a=Xe(t,{invoke(c,d){return i()?n.invoke(c,d):t.invoke(c,d)},stream(c,d){return i()?n.stream(c,d):t.stream(c,d)}});return Ue(a,"withDryRun",t),{adapter:a,dispose:()=>{s&&(s(),s=void 0)}}}function Ca(t){if(t==null||typeof t!="object")return;let e=t,n=e.status,r=bh(e.headers);if(n!==429&&n!==503&&!Rh(e.message))return;let o={},s=r("retry-after"),i=Th(s);i!=null&&(o.retryAfterMs=i);let a=r("anthropic-ratelimit-requests-reset");if(a){let p=zl(a);p!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,p))}let u=r("anthropic-ratelimit-tokens-reset");if(u){let p=zl(u);p!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,p))}let c=Es(r,"x-ratelimit-limit-requests");c!=null&&(o.rpmCap=c);let d=Es(r,"x-ratelimit-limit-tokens");d!=null&&(o.tpmCap=d);let l=Es(r,"x-ratelimit-remaining-requests"),f=Es(r,"x-ratelimit-remaining-tokens");if(l!=null&&c!=null&&c>0&&(o.usageHint??={},o.usageHint.rpm=1-l/c),f!=null&&d!=null&&d>0&&(o.usageHint??={},o.usageHint.tpm=1-f/d),o.retryAfterMs==null&&e.message){let p=kh(e.message);p!=null&&(o.retryAfterMs=p)}return e.headers&&(o.metadata={headers:vh(e.headers)}),o.retryAfterMs==null&&o.rpmCap==null&&o.tpmCap==null&&o.usageHint==null?o.metadata?o:void 0:o}function bh(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 vh(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 Es(t,e){let n=t(e);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function Th(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 zl(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var wh=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function kh(t){let e=wh.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 xh=/rate\s*limit|too\s*many\s*requests|quota|429/i;function Rh(t){return!!t&&xh.test(t)}we();ie();ne();Et();ve();vt();function Aa(t){let e=new Error(t);return e.name="AbortError",e}function Yl(t={}){let e=Math.max(1,t.burstMultiplier??1),n=t.clampCooldownMs??6e4,r=t.rpm!=null?z(t.rpm):N(Number.POSITIVE_INFINITY),o=t.tpm!=null?z(t.tpm):N(Number.POSITIVE_INFINITY),s=N(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),i=N(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),a=N({},{name:"adaptiveRateLimiter/lastSignal"}),u=E([r,s],([C,B])=>Math.min(Number(C??1/0),Number(B??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),c=E([o,i],([C,B])=>Math.min(Number(C??1/0),Number(B??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),d=er(Number(r.cache??Number.POSITIVE_INFINITY),e),l=er(Number(o.cache??Number.POSITIVE_INFINITY),e),f=!1,p=!1,m=u.subscribe(C=>{for(let B of C)if(B[0]===S){let te=Number(B[1]);Number.isFinite(te)&&te>0?(d=er(te,e),f=!1):te===1/0?(d=er(1/0,e),f=!1):te<=0&&(f=!0)}}),h=c.subscribe(C=>{for(let B of C)if(B[0]===S){let te=Number(B[1]);Number.isFinite(te)&&te>0?(l=er(te,e),p=!1):te===1/0?(l=er(1/0,e),p=!1):te<=0&&(p=!0)}}),g=0,y=new Ce,b=new Ce,v;t.adaptation!=null&&(v=z(t.adaptation).subscribe(B=>{for(let te of B)te[0]===S&&T(te[1])}));function T(C){if(a.emit(C),C.rpmCap!=null&&Number.isFinite(C.rpmCap)&&C.rpmCap>=0&&(s.emit(C.rpmCap),Number.isFinite(n)&&n>0&&y.start(n,()=>s.emit(Number.POSITIVE_INFINITY))),C.tpmCap!=null&&Number.isFinite(C.tpmCap)&&C.tpmCap>=0&&(i.emit(C.tpmCap),Number.isFinite(n)&&n>0&&b.start(n,()=>i.emit(Number.POSITIVE_INFINITY))),C.retryAfterMs!=null&&C.retryAfterMs>0){let B=V()+C.retryAfterMs*1e6;B>g&&(g=B)}}let w=N(0,{name:"adaptiveRateLimiter/pending"}),k=N(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),x=N(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),R=C=>{w.emit((w.cache??0)+C)},_=()=>{k.emit(d.available()),x.emit(l.available())};async function G(C={}){let B=C.requestCost??1,te=C.tokenCost??0,F=C.signal;R(1);try{for(;;){if(F?.aborted)throw Aa("AdaptiveRateLimiter.acquire aborted");let A=V();if(g>A){let ae=Math.ceil((g-A)/1e6);await _s(ae,F);continue}if(B>0&&f||te>0&&p){await _s(250,F);continue}let D=d,I=l;if(!D.tryConsume(B)){await _s(Jl(D,B),F);continue}if(!(te>0?I.tryConsume(te):!0)){D.putBack(B),await _s(Jl(I,te),F);continue}_();return}}finally{R(-1)}}function L(C){C>0?l.tryConsume(C):C<0&&l.putBack(-C),_()}function P(){m(),h(),v?.(),y.cancel(),b.cancel()}return{effectiveRpm:u,effectiveTpm:c,lastSignal:a,pending:w,rpmAvailable:k,tpmAvailable:x,acquire:G,recordUsage:L,recordSignal:T,dispose:P}}function er(t,e){if(!Number.isFinite(t)||t===1/0)return $t(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let n=Math.max(1,t*e),r=t/60;return $t(n,r)}function Jl(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 _s(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Aa("AdaptiveRateLimiter.acquire aborted")):new Promise((n,r)=>{let o=new Ce,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(Aa("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",s,{once:!0}))})}ve();function La(t,e={}){let n=e.limiter??Yl({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=Ca(i);a&&n.recordSignal(a)},s=Xe(t,{async invoke(i,a){let u=r(i,a);await n.acquire({requestCost:1,tokenCost:u,signal:a?.signal});try{let c=await Ye(z(t.invoke(i,a))),d=c.usage??Wl(),f=gt(d)+Lt(d)-u;return f>0&&n.recordUsage(f),c}catch(c){throw o(c),c}},async*stream(i,a){let u=r(i,a);await n.acquire({requestCost:1,tokenCost:u,signal:a?.signal});try{let c=0;for await(let l of t.stream(i,a))l.type==="usage"&&(c=gt(l.usage)+Lt(l.usage)),yield l;let d=c-u;d>0&&n.recordUsage(d)}catch(c){throw o(c),c}}});return Ue(s,"withRateLimiter",t),{adapter:s,limiter:n}}Et();ve();var Yr=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 Ia(t,e={}){if(t.length===0)throw new RangeError("cascadingLlmAdapter: tiers must be non-empty");let n=t.map(s=>({name:s.name,adapter:s.adapter,filter:s.filter,breaker:s.breaker?"canExecute"in s.breaker?s.breaker:Tt(s.breaker):void 0})),r=e.streamRetryBeforeFirstChunk??!0,o={provider:"cascading",model:void 0,async invoke(s,i){let a=[],u=new Map;for(let d=0;d<n.length;d++){let l=n[d];if(l.filter&&!l.filter(s,i)){a.push({name:l.name,reason:"filter"});continue}if(l.breaker&&!l.breaker.canExecute()){a.push({name:l.name,reason:"breaker"});continue}try{let f=await Ye(z(l.adapter.invoke(s,i)));return l.breaker?.recordSuccess(),{...f,metadata:{...f.metadata??{},tier:l.name}}}catch(f){u.set(l.name,f),l.breaker?.recordFailure(f);let p=n[d+1];p&&e.onFallback?.(l.name,p.name,f)}}let c={skipped:a,failed:u};throw e.onExhausted?.(c),new Yr(c)},async*stream(s,i){let a=[],u=new Map;for(let d=0;d<n.length;d++){let l=n[d];if(l.filter&&!l.filter(s,i)){a.push({name:l.name,reason:"filter"});continue}if(l.breaker&&!l.breaker.canExecute()){a.push({name:l.name,reason:"breaker"});continue}let f=!1;try{for await(let p of l.adapter.stream(s,i))f=!0,yield p;l.breaker?.recordSuccess();return}catch(p){if(u.set(l.name,p),l.breaker?.recordFailure(p),f||!r)throw p;let m=n[d+1];m&&e.onFallback?.(l.name,m.name,p)}}let c={skipped:a,failed:u};throw e.onExhausted?.(c),new Yr(c)}};return Ue(o,`cascade[${n.map(s=>s.name).join(",")}]`),o}function Sh(t,e,n){let r={name:t,adapter:e};return n?.breaker&&(r.breaker=n.breaker),n?.filter&&(r.filter=n.filter),r}ve();vt();function Ms(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function Ql(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Ms()):new Promise((n,r)=>{let o=new Ce,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(Ms())},e.addEventListener("abort",s,{once:!0}))})}function Pa(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??Nh,u=e.retryStreaming??!0,c=(l,f)=>{if(s==="decorrelated"){let g=Math.min(o,Math.max(r,f*3));return r+Math.random()*(g-r)}let p=s==="exp"?r*2**(l-1):r*l,m=Math.min(o,p);if(!i)return m;let h=m*(.5+Math.random());return Math.min(o,h)},d=Xe(t,{async invoke(l,f){if(f?.signal?.aborted)throw Ms();let p,m=r;for(let h=1;h<=n;h++)try{return await Ye(z(t.invoke(l,f)))}catch(g){if(p=g,h>=n||!a(g,h))throw g;let y=c(h,m);m=y,await Ql(y,f?.signal)}throw p},async*stream(l,f){if(f?.signal?.aborted)throw Ms();if(!u){for await(let h of t.stream(l,f))yield h;return}let p,m=r;for(let h=1;h<=n;h++){let g=!1;try{for await(let y of t.stream(l,f))g=!0,yield y;return}catch(y){if(p=y,g||h>=n||!a(y,h))throw y;let b=c(h,m);m=b,await Ql(b,f?.signal)}}throw p}});return Ue(d,"withRetry",t),d}function Nh(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}ve();vt();var tr=class extends Error{constructor(n){super(`LLM call timed out after ${n}ms`);this.ms=n}name="LLMTimeoutError"};function Da(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let n=s=>{let i=new AbortController,a=!1,u,c=new Ce;return s&&(s.aborted?i.abort(s.reason):(u=()=>{c.cancel(),i.abort(s.reason)},s.addEventListener("abort",u,{once:!0}))),c.start(e,()=>{a=!0,i.abort(new tr(e))}),{signal:i.signal,cancel:()=>{c.cancel(),s&&u&&s.removeEventListener("abort",u)},timedOut:()=>a}},r=(s,i)=>{if(!i||s instanceof tr)throw s;let a=s;if(a?.name==="AbortError"||a?.name==="DOMException"&&Number(a.code)===20||s?.message==="aborted"){let c=new tr(e);throw c.cause=s,c}throw s},o=Xe(t,{async invoke(s,i){let{signal:a,cancel:u,timedOut:c}=n(i?.signal);try{return await Ye(z(t.invoke(s,{...i,signal:a})))}catch(d){return r(d,c())}finally{u()}},async*stream(s,i){let{signal:a,cancel:u,timedOut:c}=n(i?.signal);try{for await(let d of t.stream(s,{...i,signal:a}))yield d}catch(d){r(d,c())}finally{u()}}});return Ue(o,"withTimeout",t),o}function Eh(t,e={}){let n={adapter:t},r=t;if(e.rateLimit){let o=La(r,e.rateLimit);r=o.adapter,n.rateLimiter=o.limiter}if(e.budget){let o=Oa(r,e.budget);r=o.adapter,n.budget=o.budget}if(e.breaker){let o=_a(r,e.breaker);r=o.adapter,n.breaker=o.breaker}if(e.timeoutMs!=null&&(r=Da(r,e.timeoutMs)),e.retry&&(r=Pa(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=Ia([{name:e.name??"primary",adapter:r},{name:"fallback",adapter:e.fallback}],o)}return e.cache&&(r=Jr(r,e.cache)),n.adapter=r,n}ne();ve();function _h(t,e,n){let r=z(e);return Te(r,s=>{if(!s||s.length===0)return N(null);let i=n?.tools;return t.invoke(s,{model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,tools:i,systemPrompt:n?.systemPrompt})})}Ne();ve();ie();ve();vt();function ge(t,e){return qe("ai",t,e)}function Mh(t){return t!=null&&typeof t.then=="function"}function Oh(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function Ch(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var Ah=3e4;function Xl(t,e){if(t.status==="settled"){let r=t.cache;if(r!==void 0)return Promise.resolve(r)}let n=e?.timeoutMs??Ah;return new Promise((r,o)=>{let s=new Ce,i=t.subscribe(a=>{for(let u of a){if(u[0]===S){s.cancel(),i(),r(u[1]);return}if(u[0]===O){s.cancel(),i(),o(u[1]);return}if(u[0]===M){s.cancel(),i(),o(new Error("firstDataFromNode: completed without producing a value"));return}}});s.start(n,()=>{i(),o(new Error(`firstDataFromNode: timed out after ${n}ms`))})})}async function kn(t){return Mh(t)?kn(await t):Oh(t)?Xl(t):Ch(t)?Xl(z(t)):t}function nr(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function Lh(t,e){let n=z(t),r=e?.refreshTrigger!=null?z(e.refreshTrigger):null;return r==null?K([n],(o,s,i)=>{if(i.store.emitted===!0)return;let u=o[0],c=u!=null&&u.length>0?u.at(-1):i.prevData[0];if(c!==void 0)return i.store.emitted=!0,s.emit(c),{invalidate:()=>{i.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:ge("frozen_context")}):K([n,r],(o,s,i)=>{let a=o[1];if(!(a!=null&&a.length>0))return;let c=o[0],d=c!=null&&c.length>0?c.at(-1):i.prevData[0];s.emit(d)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:ge("frozen_context")})}ne();function Ih(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function Qr(t,e,n,r){let o=r?.format??"text",s=r?.retries??0,i=r?.cache??!1,a=i?new Map:null,u=E(e,d=>{if(d.some(p=>p==null))return[];let l=typeof n=="string"?n:n(...d);if(!l)return[];let f=[];return r?.systemPrompt&&f.push({role:"system",content:r.systemPrompt}),f.push({role:"user",content:l}),f},{name:r?.name?`${r.name}::messages`:"prompt_node::messages",meta:ge("prompt_node"),initial:[]});return Te(u,d=>{if(!d||d.length===0)return N(null);let l=i?JSON.stringify(d.map(p=>[p.role,p.content])):"";if(a?.has(l))return N(a.get(l));async function f(p){try{let m=await new Promise((y,b)=>{let v=t.invoke(d,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt});v&&typeof v.then=="function"?v.then(y,b):v&&typeof v.subscribe=="function"?y(v.cache):y(v)}),h=Ih(m),g;return o==="json"?g=JSON.parse(nr(h)):g=h,a?.set(l,g),g}catch(m){if(p>0)return f(p-1);throw m}}return f(s)})}_e();we();ne();ve();var Is={};ye(Is,{MessagingHubGraph:()=>As,SubscriptionGraph:()=>Xr,TopicBridgeGraph:()=>Cs,TopicGraph:()=>ut,messagingHub:()=>Ga,subscription:()=>Zl,topic:()=>Ls,topicBridge:()=>Dh});Ne();var Ph=2147483647;function Os(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function xn(t,e){return qe("messaging",t,e)}var ut=class extends q{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=We([],{name:"events",maxSize:n.retainedLimit}),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=E([this.events],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:xn("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(re(this.latest)),this.hasLatest=E([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:xn("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(re(this.hasLatest)),this.addDisposer(()=>{this.events.down([[M]])}),this.addDisposer(()=>this._log.disposeAllViews())}publish(e){this._log.append(e)}retained(){return this.events.cache}},Xr=class extends q{source;cursor;available;topic;constructor(e,n,r={}){super(e,r.graph);let o=Os(r.cursor??0,"subscription cursor");this.topic=n;let s=n.events;this.source=E([s],([i])=>i,{name:"source",describeKind:"derived",meta:xn("subscription_source"),initial:s.cache}),this.add(this.source,{name:"source"}),this.cursor=N(o,{name:"cursor",describeKind:"state",meta:xn("subscription_cursor")}),this.add(this.cursor,{name:"cursor"}),this.available=E([this.source,this.cursor],([i,a])=>{let u=i,c=Math.max(0,Math.trunc(a??0));return u.slice(c)},{name:"available",describeKind:"derived",meta:xn("subscription_available"),initial:[]}),this.add(this.available,{name:"available"}),this.addDisposer(re(this.source)),this.addDisposer(re(this.available))}ack(e){let n=this.available.cache,r=e===void 0?n.length:Os(e,"subscription ack count"),o=Math.min(r,n.length);if(o<=0)return this.cursor.cache;let s=this.cursor.cache+o;return this.cursor.emit(s),s}pull(e,n={}){let r=this.available.cache,o=e===void 0?r.length:Os(e,"subscription pull limit"),s=r.slice(0,o);return n.ack&&s.length>0&&this.ack(s.length),s}},Cs=class extends q{_sourceSub;_target;bridgedCount;constructor(e,n,r,o={}){super(e,o.graph),this._sourceSub=Zl(`${e}-subscription`,n,{cursor:o.cursor}),this._target=r,this.mount("subscription",this._sourceSub),this.bridgedCount=N(0,{name:"bridgedCount",describeKind:"state",meta:xn("topic_bridge_count")}),this.add(this.bridgedCount,{name:"bridgedCount"});let s=Math.max(1,Os(o.maxPerPump??Ph,"topic bridge maxPerPump")),i=o.map??(u=>u),a=K([this._sourceSub.available],()=>{let u=this._sourceSub.pull(s,{ack:!0});if(u.length===0)return;let c=0;for(let d of u){let l=i(d);l!==void 0&&(this._target.publish(l),c+=1)}if(c>0){let d=this.bridgedCount.cache;this.bridgedCount.emit(d+c)}},{name:"pump",describeKind:"effect",meta:xn("topic_bridge_pump")});this.add(a,{name:"pump"}),this.addDisposer(re(a))}},As=class extends q{_topics=new Map;_version=0;_defaultTopicOptions;constructor(e,n={}){super(e,n.graph),this._defaultTopicOptions={...n.defaultTopicOptions??{}}}get version(){return this._version}get size(){return this._topics.size}has(e){return this._topics.has(e)}topicNames(){return this._topics.keys()}topic(e,n){let r=this._topics.get(e);if(r===void 0){let o={...this._defaultTopicOptions,...n??{}};r=new ut(e,o),this._topics.set(e,r),this.mount(e,r),this._version+=1}return r}publish(e,n){this.topic(e).publish(n)}publishMany(e){X(()=>{for(let[n,r]of e)this.topic(n).publish(r)})}subscribe(e,n,r){let o=this.topic(n);return new Xr(e,o,r)}removeTopic(e){if(!this._topics.has(e))return!1;try{this.remove(e)}finally{this._topics.delete(e),this._version+=1}return!0}};function Ls(t,e){return new ut(t,e)}function Ga(t,e){return new As(t,e)}function Zl(t,e,n){return new Xr(t,e,n)}function Dh(t,e,n,r){return new Cs(t,e,n,r)}var Ps={};ye(Ps,{approval:()=>jh,branch:()=>Bh,gate:()=>Zr,join:()=>Vh,loop:()=>Kh,onFailure:()=>qh,pipeline:()=>ep,sensor:()=>Wh,subPipeline:()=>Hh,task:()=>$h});_e();ie();Ne();ne();function It(t,e){if(typeof e=="string")return{node:t.resolve(e),path:e};let n=Gh(t,e);if(!n)throw new Error("orchestration dep node must already be registered in the graph so explicit edges can be recorded; pass a string path or register the node first");return{node:e,path:n}}function Gh(t,e){let n=t.describe(),r=`::${He}::`;for(let o of Object.keys(n.nodes).sort())if(!o.includes(r))try{if(t.resolve(o)===e)return o}catch{}}function qt(t,e,n,r){t.add(n,{name:e})}function Ut(t,e){return qe("orchestration",t,e)}function Fh(t){let e=r=>{let o=r.trim();return o.length===0?0:Number(o)},n;return typeof t=="string"?n=e(t):t===null?n=0:n=Number(t),Number.isFinite(n)?Math.max(0,Math.trunc(n)):1}function ep(t,e){return new q(t,e)}function $h(t,e,n,r){let s=(r?.deps??[]).map(d=>It(t,d)),{deps:i,...a}=r??{},u=(d,l,f)=>{let p=d.map((m,h)=>m!=null&&m.length>0?m.at(-1):f.prevData[h]);l.emit(n(p,f))},c=K(s.map(d=>d.node),u,{...a,name:e,describeKind:"derived",meta:Ut("task",r?.meta)});return qt(t,e,c,s.flatMap(d=>d.path?[d.path]:[])),c}function Bh(t,e,n,r,o){let s=It(t,n),i=E([s.node],([a])=>({branch:r(a)?"then":"else",value:a}),{...o,name:e,meta:Ut("branch",o?.meta)});return qt(t,e,i,s.path?[s.path]:[]),i}function jh(t,e,n,r,o){let s=It(t,n),i=It(t,r),a=o?.isApproved??(c=>!!c),u=K([s.node,i.node],(c,d,l)=>{let f=c[0],p=c[1],m=p!=null&&p.length>0?p.at(-1):l.prevData[1];if(m===void 0||!a(m)){d.down([[$]]);return}if(f==null||f.length===0){p!=null&&p.length>0&&l.prevData[0]!==void 0?d.emit(l.prevData[0]):d.down([[$]]);return}for(let h of f)d.emit(h)},{...o,name:e,describeKind:"derived",meta:Ut("approval",o?.meta)});return qt(t,e,u,[s.path,i.path].filter(c=>typeof c=="string")),u}function Zr(t,e,n,r){let o=r?.maxPending??1/0;if(o<1&&o!==1/0)throw new RangeError("gate: maxPending must be >= 1");let s=r?.startOpen??!1,i=It(t,n),a=N([],{name:"pending",equals:()=>!1}),u=N(s,{name:"isOpen"}),c=E([a],([w])=>w.length,{name:"count"}),d=[],l=!1,f=s,p=u.subscribe(w=>{for(let k of w)k[0]===S&&(f=k[1])});function m(){a.emit([...d])}function h(w){d.push(w),d.length>o&&d.shift(),m()}function g(w){let k=d.splice(0,w);return m(),k}function y(w){if(l)throw new Error(`gate: ${w}() called after gate was torn down`)}let b=K([i.node],(w,k,x)=>{let R=x.terminalDeps[0];if(R!==void 0){l=!0,d=[],m(),k.down(R===!0?[[M]]:[[O,R]]);return}let _=w[0];if(_==null||_.length===0){k.down([[$]]);return}for(let G of _)f?k.emit(G):(h(G),k.down([[$]]))},{name:e,describeKind:"derived",meta:Ut("gate",r?.meta)}),v={node:b,pending:a,count:c,isOpen:u,approve(w=1){y("approve");let k=g(w);for(let x of k){if(l)break;b.emit(x)}},reject(w=1){y("reject"),g(w)},modify(w,k=1){y("modify");let x=[...d],R=g(k);for(let _=0;_<R.length&&!l;_++)b.emit(w(R[_],_,x))},open(){y("open"),X(()=>{u.emit(!0);let w=g(d.length);for(let k of w){if(l)break;b.emit(k)}})},close(){y("close"),u.emit(!1)}};t.addDisposer(c.subscribe(()=>{})),t.addDisposer(p),qt(t,e,b,i.path?[i.path]:[]);let T=new q(`${e}_state`);return T.add(a,{name:"pending"}),T.add(u,{name:"isOpen"}),T.add(c,{name:"count"}),t.mount(`${e}_state`,T),v}function Vh(t,e,n,r){let o=n.map(i=>It(t,i)),s=E(o.map(i=>i.node),i=>i,{...r,name:e,meta:Ut("join",r?.meta)});return qt(t,e,s,o.flatMap(i=>i.path?[i.path]:[])),s}function Kh(t,e,n,r,o){let s=It(t,n),i=o?.iterations,a=typeof i=="number"||i===void 0?void 0:It(t,i),u=typeof i=="number"?i:void 0,c=K(a?[s.node,a.node]:[s.node],(d,l,f)=>{let p=d[0],m=p!=null&&p.length>0?p.at(-1):f.prevData[0],h=a?d[1]:void 0,g=u??(a?h!=null&&h.length>0?h.at(-1):f.prevData[1]:1),y=Fh(g);for(let b=0;b<y;b+=1)m=r(m,b,l);l.emit(m)},{...o,name:e,describeKind:"derived",meta:Ut("loop",o?.meta)});return qt(t,e,c,[s.path,a?.path].filter(d=>typeof d=="string")),c}function Hh(t,e,n,r){let o=n instanceof q?n:ep(e,r);return typeof n=="function"&&n(o),t.mount(e,o),o}function Wh(t,e,n,r){let o=K([],()=>{},{...r,name:e,initial:n,describeKind:"producer",meta:Ut("sensor",r?.meta)});return qt(t,e,o,[]),{node:o,push(s){o.emit(s)},error(s){o.down([[O,s]])},complete(){o.down([[M]])}}}function qh(t,e,n,r,o){let s=It(t,n),i=!1,a=K([],(u,c)=>{let d=s.node.subscribe(l=>{for(let f of l){if(i)return;if(f[0]===O)try{c.emit(r(f[1],c))}catch(p){i=!0,c.down([[O,p]])}else c.down([f]),f[0]===M&&(i=!0)}});return()=>d()},{...o,name:e,describeKind:"derived",completeWhenDepsComplete:!1,errorWhenDepsError:!1,meta:Ut("onFailure",o?.meta)});return qt(t,e,a,s.path?[s.path]:[]),a}async function tp(t,e,n,r){let o="",s=0;for await(let i of t.stream(e,n))r.publish({...i,seq:s++,ts:le()}),i.type==="token"&&(o+=i.delta);return o}function np(t,e){if(e==="json")try{return JSON.parse(nr(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 rp(t,e){return E([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:ge("accumulated_text"),initial:""})}function Uh(t,e,n,r){let o=r?.name??"llm",s=r?.format??"text",i=Ls(`${o}/stream`,{...r?.retainedLimit!=null?{retainedLimit:r.retainedLimit}:{}}),a=E(e,l=>{if(l.some(p=>p==null))return[];let f=typeof n=="string"?n:n(...l);return f?[{role:"user",content:f}]:[]},{name:`${o}::messages`,meta:ge("prompt_node::messages"),initial:[]}),u=Te(a,l=>{let f=l;if(!f||f.length===0)return N(null);let p=new AbortController;async function*m(){try{let h=await tp(t,f,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,signal:p.signal},i);yield np(h,s)}finally{p.abort()}}return z(m())}),c=rp(i,`${o}::accumulatedText`),d=re(u);return{output:u,deltaTopic:i,accumulatedText:c,dispose:()=>{d(),i.destroy()}}}function zh(t,e,n,r,o,s){let i=N(0,{name:`${e}/cancel`}),a=0,u=[...r,i],c=s?.name??e,d=s?.format??"text",l=Ls(`${c}/stream`,{...s?.retainedLimit!=null?{retainedLimit:s.retainedLimit}:{}}),f=E(u,T=>{let w=T.slice(0,-1);if(w.some(x=>x==null))return[];let k=typeof o=="string"?o:o(...w);return k?[{role:"user",content:k}]:[]},{name:`${c}::messages`,meta:ge("prompt_node::messages"),initial:[]}),p=Te(f,T=>{let w=T;if(!w||w.length===0)return N(null);let k=new AbortController;async function*x(){try{let R=await tp(n,w,{model:s?.model,temperature:s?.temperature,maxTokens:s?.maxTokens,systemPrompt:s?.systemPrompt,signal:k.signal},l);yield np(R,d)}finally{k.abort()}}return z(x())}),m=rp(l,`${c}::accumulatedText`),h=E([p],([T])=>{if(T!=null)return T},{name:`${e}/filter`});t.add(h,{name:`${e}/raw`});let g=Zr(t,`${e}/gate`,`${e}/raw`,s?.gate),y=re(p),b=g.reject.bind(g),v={...g,reject(T=1){X(()=>{b(T),i.emit(++a)})}};return{output:g.node,deltaTopic:l,accumulatedText:m,gate:v,dispose:()=>{y(),l.destroy()}}}ne();ve();function Jh(t,e){let n=e?.separator??`
41
37
 
42
- `)}]});let s={};return e?.maxTokens!=null&&(s.maxOutputTokens=e.maxTokens),e?.temperature!=null&&(s.temperature=e.temperature),e?.maxReasoningTokens!=null&&(s.thinkingConfig={thinkingBudget:e.maxReasoningTokens}),Object.keys(s).length>0&&(o.generationConfig=s),e?.tools&&e.tools.length>0&&(o.tools=[{functionDeclarations:e.tools.map(Km)}]),e?.providerExtras&&Object.assign(o,e.providerExtras),o}function Km(t){return{name:t.name,description:t.description,parameters:t.parameters}}function ua(t){let e={input:{regular:0},output:{regular:0},raw:t};if(!t)return e;let n=t.promptTokenCount??0,r=t.cachedContentTokenCount??0;if(e.input.regular=Math.max(0,n-r),r>0&&(e.input.cacheRead=r),t.toolUsePromptTokenCount&&(e.input.toolUse=t.toolUsePromptTokenCount),t.promptTokensDetails)for(let o of t.promptTokensDetails){let s=o.modality?.toLowerCase();s==="image"?e.input.image=(e.input.image??0)+o.tokenCount:s==="audio"?e.input.audio=(e.input.audio??0)+o.tokenCount:s==="video"&&(e.input.video=(e.input.video??0)+o.tokenCount)}return e.output.regular=t.candidatesTokenCount??0,t.thoughtsTokenCount&&(e.output.reasoning=t.thoughtsTokenCount),e}function Cl(t,e){let n=t.candidates?.[0],r=n?.content?.parts??[],o=[],s=[],i=0;for(let a of r)typeof a.text=="string"&&o.push(a.text),a.functionCall&&s.push({id:`${a.functionCall.name}-${i++}`,name:a.functionCall.name,arguments:a.functionCall.args??{}});return{content:o.join(""),toolCalls:s.length>0?s:void 0,usage:ua(t.usageMetadata),finishReason:n?.finishReason,latencyMs:e,model:t.modelVersion,provider:"google"}}function Hm(t){if(t.apiKey)return t.apiKey;let e=globalThis.process?.env;return e?.GOOGLE_API_KEY??e?.GEMINI_API_KEY}function Wm(t){let e=t.baseURL??"https://generativelanguage.googleapis.com/v1beta",n=t.fetchImpl??fetch,r=s=>{let i=s?.model??t.model;if(!i)throw new Error("googleAdapter: model must be set via options.model or invokeOpts.model");return i},o=()=>{let s=Hm(t);if(!s)throw new Error("googleAdapter: apiKey required for invoke/stream");return`key=${encodeURIComponent(s)}`};return{provider:"google",model:t.model,async invoke(s,i){let a=r(i),u=us(s,i),c=$(),d=`${e}/models/${encodeURIComponent(a)}:generateContent?${o()}`,l=await n(d,{method:"POST",headers:{"content-type":"application/json",...t.headers??{}},body:JSON.stringify(u),signal:i?.signal});if(!l.ok)throw await Ol(l);let f=await l.json(),p=Math.max(0,($()-c)/1e6);return Cl(f,p)},async*stream(s,i){let a=r(i),u=us(s,i),c=`${e}/models/${encodeURIComponent(a)}:streamGenerateContent?alt=sse&${o()}`,d=await n(c,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",...t.headers??{}},body:JSON.stringify(u),signal:i?.signal});if(!d.ok)throw await Ol(d);if(!d.body)throw new Error("googleAdapter: streaming response has no body");let l,f;for await(let p of Um(d.body)){if(!p.data)continue;let m;try{m=JSON.parse(p.data)}catch{continue}let h=m.candidates?.[0];for(let g of h?.content?.parts??[])typeof g.text=="string"&&(g.thought?yield{type:"thinking",delta:g.text}:yield{type:"token",delta:g.text}),g.functionCall&&(yield{type:"tool-call-delta",delta:{name:g.functionCall.name,argumentsDelta:JSON.stringify(g.functionCall.args??{})}});h?.finishReason&&(f=h.finishReason),m.usageMetadata&&(l=m.usageMetadata)}l&&(yield{type:"usage",usage:ua(l)}),yield{type:"finish",reason:f??"stop"}}}}function qm(t){let e=t.sdk;if(!e)throw new Error("sdkBackedGoogle: sdk instance required");return{provider:"google",model:t.model,async invoke(n,r){let o=us(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=$(),a=await e.models.generateContent({...o,model:s},{signal:r?.signal}),u=Math.max(0,($()-i)/1e6);return Cl(a,u)},async*stream(n,r){if(!e.models.generateContentStream)throw new Error("sdkBackedGoogle: SDK instance does not expose generateContentStream");let o=us(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i,a;for await(let u of e.models.generateContentStream({...o,model:s},{signal:r?.signal})){let c=u.candidates?.[0];for(let d of c?.content?.parts??[])typeof d.text=="string"&&(d.thought?yield{type:"thinking",delta:d.text}:yield{type:"token",delta:d.text}),d.functionCall&&(yield{type:"tool-call-delta",delta:{name:d.functionCall.name,argumentsDelta:JSON.stringify(d.functionCall.args??{})}});c?.finishReason&&(a=c.finishReason),u.usageMetadata&&(i=u.usageMetadata)}i&&(yield{type:"usage",usage:ua(i)}),yield{type:"finish",reason:a??"stop"}}}}async function*Um(t){let e=t.getReader(),n=new TextDecoder,r="";try{for(;;){let{done:o,value:s}=await e.read();if(o){r.length>0&&(yield _l(r));return}r+=n.decode(s,{stream:!0});let i=Ml(r);for(;i!==null;){let a=r.slice(0,i.index);r=r.slice(i.index+i.length);let u=_l(a);(u.data||u.event)&&(yield u),i=Ml(r)}}}finally{e.releaseLock()}}function _l(t){let e={},n=[];for(let r of t.split(`
43
- `)){let o=r.endsWith("\r")?r.slice(0,-1):r;if(!o||o.startsWith(":"))continue;let s=o.indexOf(":"),i=s===-1?o:o.slice(0,s),a=s===-1?"":o.slice(s+1).replace(/^ /,"");i==="data"?n.push(a):i==="event"?e.event=a:i==="id"&&(e.id=a)}return n.length>0&&(e.data=n.join(`
44
- `)),e}function Ml(t){let e=t.indexOf(`\r
45
- \r
46
- `),n=t.indexOf(`
47
-
48
- `),r=null;return e!==-1&&(r={index:e,length:4}),n!==-1&&(r===null||n<r.index)&&(r={index:n,length:2}),r}async function Ol(t){let e;try{e=await t.text()}catch{e=""}let n=new Error(`Google API ${t.status}: ${t.statusText}${e?` \u2014 ${e}`:""}`);return n.status=t.status,n.headers=t.headers,n}ke();var zm={openai:{baseURL:"https://api.openai.com/v1",apiKeyEnv:"OPENAI_API_KEY",provider:"openai"},openrouter:{baseURL:"https://openrouter.ai/api/v1",apiKeyEnv:"OPENROUTER_API_KEY",provider:"openrouter"},groq:{baseURL:"https://api.groq.com/openai/v1",apiKeyEnv:"GROQ_API_KEY",provider:"groq"},ollama:{baseURL:"http://localhost:11434/v1",provider:"ollama"},deepseek:{baseURL:"https://api.deepseek.com/v1",apiKeyEnv:"DEEPSEEK_API_KEY",provider:"deepseek"},xai:{baseURL:"https://api.x.ai/v1",apiKeyEnv:"XAI_API_KEY",provider:"xai"}};function ca(t={}){return t.sdk?Zm(t):Xm(t)}function cs(t,e,n,r,o){let s=e?.model??n;if(!s)throw new Error("openAICompatAdapter: model must be set via options.model or invokeOpts.model");let i=t.map(Jm);e?.systemPrompt&&!t.some(u=>u.role==="system")&&i.unshift({role:"system",content:e.systemPrompt});let a={model:s,messages:i};return e?.maxTokens!=null&&(a.max_tokens=e.maxTokens),e?.temperature!=null&&(a.temperature=e.temperature),e?.tools&&e.tools.length>0&&(a.tools=e.tools.map(Ym)),e?.maxReasoningTokens!=null&&(a.reasoning={max_tokens:e.maxReasoningTokens}),r&&(a.stream=!0,a.stream_options={include_usage:!0}),o&&Object.assign(a,o),e?.providerExtras&&Object.assign(a,e.providerExtras),a}function Jm(t){return t.role==="tool"?{role:"tool",tool_call_id:t.toolCallId,content:t.content}:t.role==="assistant"&&t.toolCalls&&t.toolCalls.length>0?{role:"assistant",content:t.content||null,tool_calls:t.toolCalls.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.arguments)}}))}:{role:t.role,content:t.content}}function Ym(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}}function da(t){let e={input:{regular:0},output:{regular:0},raw:t};if(!t)return e;let n=t.prompt_tokens??0,r=t.prompt_tokens_details?.cached_tokens??0;t.prompt_cache_hit_tokens!=null?(r=t.prompt_cache_hit_tokens,e.input.regular=t.prompt_cache_miss_tokens??Math.max(0,n-r)):e.input.regular=Math.max(0,n-r),r>0&&(e.input.cacheRead=r),t.prompt_tokens_details?.audio_tokens&&(e.input.audio=t.prompt_tokens_details.audio_tokens);let o=t.completion_tokens??0,s=t.completion_tokens_details?.reasoning_tokens??0;return e.output.regular=Math.max(0,o-s),s>0&&(e.output.reasoning=s),t.completion_tokens_details?.audio_tokens&&(e.output.audio=t.completion_tokens_details.audio_tokens),t.completion_tokens_details?.accepted_prediction_tokens&&(e.output.predictionAccepted=t.completion_tokens_details.accepted_prediction_tokens),t.completion_tokens_details?.rejected_prediction_tokens&&(e.output.predictionRejected=t.completion_tokens_details.rejected_prediction_tokens),e}function Pl(t,e,n){let r=t.choices[0],o=r?.message,s=o?.content??"",i=(o?.tool_calls??[]).map(a=>({id:a.id,name:a.function.name,arguments:Qm(a.function.arguments)}));return{content:s,toolCalls:i.length>0?i:void 0,usage:da(t.usage),finishReason:r?.finish_reason,latencyMs:e,model:t.model,provider:n}}function Qm(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!=null?e:{_raw:t}}catch{return{_raw:t}}}function Dl(t){let e=t.preset??"openai",n=zm[e],r=t.baseURL??n.baseURL,o=t.provider??n.provider,s=n.apiKeyEnv,i=t.apiKey??(s?globalThis.process?.env?.[s]:void 0);return{provider:o,baseURL:r,apiKey:i}}function Xm(t){let{provider:e,baseURL:n,apiKey:r}=Dl(t),o=t.fetchImpl??fetch,s=e!=="ollama",i=()=>{let a={"content-type":"application/json",...t.headers??{}};if(s){if(!r)throw new Error(`openAICompatAdapter[${e}]: apiKey required for invoke/stream`);a.authorization=`Bearer ${r}`}return a};return{provider:e,model:t.model,async invoke(a,u){let c=cs(a,u,t.model,!1,t.bodyExtras),d=$(),l=await o(`${n}/chat/completions`,{method:"POST",headers:i(),body:JSON.stringify(c),signal:u?.signal});if(!l.ok)throw await Il(l,e);let f=await l.json(),p=Math.max(0,($()-d)/1e6);return Pl(f,p,e)},async*stream(a,u){let c=cs(a,u,t.model,!0,t.bodyExtras),d=await o(`${n}/chat/completions`,{method:"POST",headers:{...i(),accept:"text/event-stream"},body:JSON.stringify(c),signal:u?.signal});if(!d.ok)throw await Il(d,e);if(!d.body)throw new Error(`openAICompatAdapter[${e}]: streaming response has no body`);let l,f;for await(let p of eh(d.body)){if(!p.data||p.data==="[DONE]")continue;let m;try{m=JSON.parse(p.data)}catch{continue}let h=m.choices;if(h){let g=h[0];if(g?.delta?.content&&(yield{type:"token",delta:g.delta.content}),g?.delta?.reasoning_content&&(yield{type:"thinking",delta:g.delta.reasoning_content}),g?.delta?.tool_calls)for(let y of g.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:y.id,name:y.function?.name,argumentsDelta:y.function?.arguments}};g?.finish_reason&&(f=g.finish_reason)}m.usage&&(l=m.usage,yield{type:"usage",usage:da(l)})}yield{type:"finish",reason:f??"stop"}}}}function Zm(t){let e=t.sdk;if(!e)throw new Error("sdkBackedOpenAI: sdk instance required");let{provider:n}=Dl(t);return{provider:n,model:t.model,async invoke(r,o){let s=cs(r,o,t.model,!1,t.bodyExtras),i=$(),a=await e.chat.completions.create(s,{signal:o?.signal}),u=Math.max(0,($()-i)/1e6);return Pl(a,u,n)},async*stream(r,o){let s=cs(r,o,t.model,!0,t.bodyExtras),i=await e.chat.completions.create(s,{signal:o?.signal}),a,u;for await(let c of i){let d=c.choices;if(d){let f=d[0];if(f?.delta?.content&&(yield{type:"token",delta:f.delta.content}),f?.delta?.reasoning_content&&(yield{type:"thinking",delta:f.delta.reasoning_content}),f?.delta?.tool_calls)for(let p of f.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:p.id,name:p.function?.name,argumentsDelta:p.function?.arguments}};f?.finish_reason&&(u=f.finish_reason)}let l=c.usage;l&&(a=l,yield{type:"usage",usage:da(l)})}yield{type:"finish",reason:u??"stop"}}}}async function*eh(t){let e=t.getReader(),n=new TextDecoder,r="";try{for(;;){let{done:o,value:s}=await e.read();if(o){r.length>0&&(yield Al(r));return}r+=n.decode(s,{stream:!0});let i=Ll(r);for(;i!==null;){let a=r.slice(0,i.index);r=r.slice(i.index+i.length);let u=Al(a);(u.data||u.event)&&(yield u),i=Ll(r)}}}finally{e.releaseLock()}}function Al(t){let e={},n=[];for(let r of t.split(`
49
- `)){let o=r.endsWith("\r")?r.slice(0,-1):r;if(!o||o.startsWith(":"))continue;let s=o.indexOf(":"),i=s===-1?o:o.slice(0,s),a=s===-1?"":o.slice(s+1).replace(/^ /,"");i==="data"?n.push(a):i==="event"?e.event=a:i==="id"&&(e.id=a)}return n.length>0&&(e.data=n.join(`
50
- `)),e}function Ll(t){let e=t.indexOf(`\r
51
- \r
52
- `),n=t.indexOf(`
53
-
54
- `),r=null;return e!==-1&&(r={index:e,length:4}),n!==-1&&(r===null||n<r.index)&&(r={index:n,length:2}),r}async function Il(t,e){let n;try{n=await t.text()}catch{n=""}let r=new Error(`${e} API ${t.status}: ${t.statusText}${n?` \u2014 ${n}`:""}`);return r.status=t.status,r.headers=t.headers,r}function th(t){switch(t.provider){case"anthropic":{let e={apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return ra(e)}case"google":{let e={apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return aa(e)}case"dry-run":{let e={model:t.model,...t.extras};return St(e)}case"fallback":{let e={provider:t.provider,model:t.model,...t.extras};return ia(e)}case"openai":case"openrouter":case"groq":case"ollama":case"deepseek":case"xai":{let e={preset:t.provider,apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,bodyExtras:t.bodyExtras,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return ca(e)}default:{let e=t.provider;throw new Error(`createAdapter: unknown provider: ${String(e)}`)}}}ke();oe();Re();function Nt(t){let e=t.input,n=e.regular+(e.cacheRead??0)+(e.cacheWrite5m??0)+(e.cacheWrite1h??0)+(e.cacheWriteOther??0)+(e.audio??0)+(e.image??0)+(e.video??0)+(e.toolUse??0);if(!e.extensions)return n;let r=0;for(let o of Object.values(e.extensions))r+=o;return n+r}function hn(t){let e=t.output,n=e.regular+(e.reasoning??0)+(e.audio??0)+(e.predictionAccepted??0)+(e.predictionRejected??0);if(!e.extensions)return n;let r=0;for(let o of Object.values(e.extensions))r+=o;return n+r}function Gl(){return{input:{regular:0},output:{regular:0}}}function nh(t,e){let n=e?.logMax??1e3,r=Ve(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:n}),o=N(null,{name:"adapterStats/lastCall"}),s=N(0,{name:"adapterStats/totalCalls"}),i=N(0,{name:"adapterStats/totalInputTokens"}),a=N(0,{name:"adapterStats/totalOutputTokens"}),u=f=>{r.append(f),o.emit(f),s.emit((s.cache??0)+1),i.emit((i.cache??0)+Nt(f.usage)),a.emit((a.cache??0)+hn(f.usage))},c=()=>{r.clear(),o.emit(null),s.emit(0),i.emit(0),a.emit(0)};return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),invoke(f,p){let m=$(),h=pe(),g=t.invoke(f,p),y=v=>{let T=$();return u({timestamp:T,wallClock:h,provider:t.provider,model:t.model??p?.model??v.model??"",tier:p?.tier??v.tier,usage:v.usage??la(),latencyMs:Math.max(0,(T-m)/1e6),method:"invoke"}),v};if(g!=null&&typeof g.then=="function")return g.then(y);if(g!=null&&typeof g=="object"&&"content"in g)return y(g);let b=!1;return O([re(g)],([v])=>v==null||b?v:(b=!0,y(v)),{name:"adapterStats/invokeTap"})},async*stream(f,p){let m=$(),h=pe(),g;try{for await(let b of t.stream(f,p))b.type==="usage"&&(g=b.usage),yield b;let y=$();u({timestamp:y,wallClock:h,provider:t.provider,model:t.model??p?.model??"",tier:p?.tier,usage:g??la(),latencyMs:Math.max(0,(y-m)/1e6),method:"stream"})}catch(y){let b=$(),v=y;throw u({timestamp:b,wallClock:h,provider:t.provider,model:t.model??p?.model??"",tier:p?.tier,usage:g??la(),latencyMs:Math.max(0,(b-m)/1e6),method:"stream",error:{type:v?.name??"Error",message:v?.message??String(y)}}),y}}},stats:{lastCall:o,allCalls:r,totalCalls:s,totalInputTokens:i,totalOutputTokens:a,reset:c}}}function la(){return{input:{regular:0},output:{regular:0}}}function rh(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function pa(t="USD"){return{total:0,currency:t}}function Fl(t,e,n){let r=Nt(t),o=e.currency??"USD",s=n?.withBreakdown===!0,i=s?{}:null,a=0,u=(g,y,b)=>{if(!y||b==null)return;let v=rh(b,r),T=y*v/1e6;a+=T,s&&(i[g]=(i[g]??0)+T)},c=t.input,d=e.input;if(d&&(u("input.regular",c.regular,d.regular),u("input.cacheRead",c.cacheRead??0,d.cacheRead),u("input.cacheWrite5m",c.cacheWrite5m??0,d.cacheWrite5m),u("input.cacheWrite1h",c.cacheWrite1h??0,d.cacheWrite1h),u("input.cacheWriteOther",c.cacheWriteOther??0,d.cacheWriteOther),u("input.audio",c.audio??0,d.audio),u("input.image",c.image??0,d.image),u("input.video",c.video??0,d.video),u("input.toolUse",c.toolUse??0,d.toolUse),c.extensions&&d.extensions))for(let[g,y]of Object.entries(c.extensions))u(`input.ext.${g}`,y,d.extensions[g]);let l=t.output,f=e.output;if(f&&(u("output.regular",l.regular,f.regular),u("output.reasoning",l.reasoning??0,f.reasoning),u("output.audio",l.audio??0,f.audio),u("output.predictionAccepted",l.predictionAccepted??0,f.predictionAccepted),u("output.predictionRejected",l.predictionRejected??0,f.predictionRejected),l.extensions&&f.extensions))for(let[g,y]of Object.entries(l.extensions))u(`output.ext.${g}`,y,f.extensions[g]);let p=n?.tier;if(p&&e.tierMultipliers){let g=e.tierMultipliers[p];if(g!=null&&(a*=g,s))for(let y of Object.keys(i))i[y]*=g}let m=t.auxiliary,h=e.auxiliary;if(m&&h)for(let[g,y]of Object.entries(m)){let b=h[g];if(b==null||!y)continue;let v=y*b;a+=v,s&&(i[`auxiliary.${g}`]=v)}return s?{total:a,currency:o,breakdown:i}:{total:a,currency:o}}function ds(t,e){return`${t}::${e}`}function oh(t){let e=new Map,n=new Map,r=(o,s,i)=>{e.set(ds(o,s),{provider:o,model:s,pricing:i});let a=n.get(o);a||(a=new Set,n.set(o,a)),a.add(s)};if(t)for(let[o,s,i]of t)r(o,s,i);return{register:r,lookup(o,s){let i=e.get(ds(o,s));if(i)return i.pricing;let a=n.get(o);if(!a)return;let u;for(let c of a)if(s.startsWith(c)&&(!u||c.length>u.key.length)){let d=e.get(ds(o,c));d&&(u={key:c,pricing:d.pricing})}return u?.pricing},remove(o,s){let i=e.delete(ds(o,s));if(i){let a=n.get(o);a?.delete(s),a&&a.size===0&&n.delete(o)}return i},entries(){let o=e.values();return(function*(){for(let{provider:s,model:i,pricing:a}of o)yield[s,i,a]})()}}}function sh(t,e="USD"){return(n,r)=>{let o=t.lookup(r.provider,r.model);return o?Fl(n,o,{tier:r.tier,withBreakdown:r.withBreakdown}):pa(e)}}function ih(...t){return(e,n)=>{for(let r of t){let o=r(e,n);if(o.total!==0)return o}return t.length>0?t[0](e,n):pa()}}Tt();function fa(t,e={}){let n=e.breaker??ft(e);return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(o,s){if(!n.canExecute())throw new st;try{let i=await Promise.resolve(t.invoke(o,s));return n.recordSuccess(),i}catch(i){throw n.recordFailure(i),i}},async*stream(o,s){if(!n.canExecute())throw new st;try{for await(let i of t.stream(o,s))yield i;n.recordSuccess()}catch(i){throw n.recordFailure(i),i}}},breaker:n}}ke();ie();oe();Re();var ls=class extends Error{constructor(n,r,o){super(`Budget exhausted: ${n} (limit=${r}, observed=${o})`);this.which=n;this.limit=r;this.observed=o}name="BudgetExhaustedError"},ma=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),$l=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function ha(t,e){let n=Ve(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),r=N($l(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=O([r],([d])=>{let l=d;return!(e.caps.calls!=null&&l.calls>=e.caps.calls||e.caps.inputTokens!=null&&l.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&l.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&l.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(se(o),e.onExhausted!=null){let d=e.onExhausted,l=!1,f=!0;o.subscribe(p=>{for(let m of p)if(m[0]===S){let h=m[1];if(l&&f&&h===!1){let g=Bl(r.cache??ma,e.caps);g&&d(g)}f=h,l=!0}})}let s=()=>{if(o.cache===!1){let d=r.cache??ma,l=Bl(d,e.caps);return new ls(l??"budget",e.caps[l??"calls"]??0,ah(d,l??"calls"))}},i=(d,l)=>{let f=t.provider,p={timestamp:$(),wallClock:pe(),provider:f,model:l.model,tier:l.tier,usage:d,latencyMs:l.latencyMs,method:l.method,...l.error?{error:l.error}:{}};n.append(p);let m=r.cache??ma,h=e.pricingFn?m.usd+e.pricingFn(d,{model:l.model,provider:f,tier:l.tier}).total:m.usd;r.emit({calls:m.calls+1,inputTokens:m.inputTokens+Nt(d),outputTokens:m.outputTokens+hn(d),usd:h})},a=()=>{n.clear(),r.emit($l())},u=()=>({input:{regular:0},output:{regular:0}});return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),invoke(d,l){let f=s();if(f)return Promise.reject(f);let p=$(),m=t.invoke(d,l),h=y=>{let b=Math.max(0,($()-p)/1e6);return i(y.usage??u(),{model:t.model??l?.model??y.model??"",tier:l?.tier??y.tier,latencyMs:b,method:"invoke"}),y};if(m!=null&&typeof m.then=="function")return m.then(h);if(m!=null&&typeof m=="object"&&"content"in m)return h(m);let g=!1;return O([re(m)],([y])=>y==null||g?y:(g=!0,h(y)),{name:"budgetGate/invokeTap"})},async*stream(d,l){let f=s();if(f)throw f;let p=$(),m;try{for await(let h of t.stream(d,l))h.type==="usage"&&(m=h.usage),yield h;i(m??u(),{model:t.model??l?.model??"",tier:l?.tier,latencyMs:Math.max(0,($()-p)/1e6),method:"stream"})}catch(h){let g=h;throw i(m??u(),{model:t.model??l?.model??"",tier:l?.tier,latencyMs:Math.max(0,($()-p)/1e6),method:"stream",error:{type:g?.name??"Error",message:g?.message??String(h)}}),h}}},budget:{totals:r,isOpen:o,log:n,reset:a}}}function Bl(t,e){if(e.calls!=null&&t.calls>=e.calls)return"calls";if(e.inputTokens!=null&&t.inputTokens>=e.inputTokens)return"inputTokens";if(e.outputTokens!=null&&t.outputTokens>=e.outputTokens)return"outputTokens";if(e.usd!=null&&t.usd>=e.usd)return"usd"}function ah(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}Re();function uh(t,e){let n=e.mock??St({provider:t.provider,model:t.model}),r=typeof e.enabled=="boolean"?e.enabled:void 0,o=r===void 0?re(e.enabled):void 0,s;o&&(s=se(o));let i=()=>r!==void 0?r:!!o?.cache;return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),invoke(c,d){return i()?n.invoke(c,d):t.invoke(c,d)},stream(c,d){return i()?n.stream(c,d):t.stream(c,d)}},dispose:()=>{s&&(s(),s=void 0)}}}function ga(t){if(t==null||typeof t!="object")return;let e=t,n=e.status,r=ch(e.headers);if(n!==429&&n!==503&&!hh(e.message))return;let o={},s=r("retry-after"),i=lh(s);i!=null&&(o.retryAfterMs=i);let a=r("anthropic-ratelimit-requests-reset");if(a){let p=jl(a);p!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,p))}let u=r("anthropic-ratelimit-tokens-reset");if(u){let p=jl(u);p!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,p))}let c=ps(r,"x-ratelimit-limit-requests");c!=null&&(o.rpmCap=c);let d=ps(r,"x-ratelimit-limit-tokens");d!=null&&(o.tpmCap=d);let l=ps(r,"x-ratelimit-remaining-requests"),f=ps(r,"x-ratelimit-remaining-tokens");if(l!=null&&c!=null&&c>0&&(o.usageHint??={},o.usageHint.rpm=1-l/c),f!=null&&d!=null&&d>0&&(o.usageHint??={},o.usageHint.tpm=1-f/d),o.retryAfterMs==null&&e.message){let p=fh(e.message);p!=null&&(o.retryAfterMs=p)}return e.headers&&(o.metadata={headers:dh(e.headers)}),o.retryAfterMs==null&&o.rpmCap==null&&o.tpmCap==null&&o.usageHint==null?o.metadata?o:void 0:o}function ch(t){if(!t)return()=>{};if(typeof t.get=="function"){let r=t;return o=>r.get(o)??r.get(o.toLowerCase())??void 0}let e=t,n={};for(let[r,o]of Object.entries(e)){let s=Array.isArray(o)?o.join(", "):o;s!=null&&(n[r.toLowerCase()]=s)}return r=>n[r.toLowerCase()]}function dh(t){let e={};if(typeof t.forEach=="function")return t.forEach((n,r)=>{e[r]=n}),e;for(let[n,r]of Object.entries(t))r!=null&&(e[n]=Array.isArray(r)?r.join(", "):r);return e}function ps(t,e){let n=t(e);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function lh(t){if(!t)return;let e=t.trim(),n=Number(e);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(e);if(Number.isFinite(r)){let o=r-Date.now();if(o>0)return o}}function jl(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var ph=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function fh(t){let e=ph.exec(t);if(!e)return;let n=Number(e[1]);if(!Number.isFinite(n))return;let r=(e[2]??"s").toLowerCase();if(r==="ms")return n;if(r.startsWith("s"))return n*1e3;if(r.startsWith("m"))return n*6e4}var mh=/rate\s*limit|too\s*many\s*requests|quota|429/i;function hh(t){return!!t&&mh.test(t)}ke();ie();oe();Tt();Re();pt();function ya(t){let e=new Error(t);return e.name="AbortError",e}function Kl(t={}){let e=Math.max(1,t.burstMultiplier??1),n=t.clampCooldownMs??6e4,r=t.rpm!=null?re(t.rpm):N(Number.POSITIVE_INFINITY),o=t.tpm!=null?re(t.tpm):N(Number.POSITIVE_INFINITY),s=N(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),i=N(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),a=N({},{name:"adaptiveRateLimiter/lastSignal"}),u=O([r,s],([C,V])=>Math.min(Number(C??1/0),Number(V??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),c=O([o,i],([C,V])=>Math.min(Number(C??1/0),Number(V??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),d=Yn(Number(r.cache??Number.POSITIVE_INFINITY),e),l=Yn(Number(o.cache??Number.POSITIVE_INFINITY),e),f=!1,p=!1,m=u.subscribe(C=>{for(let V of C)if(V[0]===S){let ne=Number(V[1]);Number.isFinite(ne)&&ne>0?(d=Yn(ne,e),f=!1):ne===1/0?(d=Yn(1/0,e),f=!1):ne<=0&&(f=!0)}}),h=c.subscribe(C=>{for(let V of C)if(V[0]===S){let ne=Number(V[1]);Number.isFinite(ne)&&ne>0?(l=Yn(ne,e),p=!1):ne===1/0?(l=Yn(1/0,e),p=!1):ne<=0&&(p=!0)}}),g=0,y=new _e,b=new _e,v;t.adaptation!=null&&(v=re(t.adaptation).subscribe(V=>{for(let ne of V)ne[0]===S&&T(ne[1])}));function T(C){if(a.emit(C),C.rpmCap!=null&&Number.isFinite(C.rpmCap)&&C.rpmCap>=0&&(s.emit(C.rpmCap),Number.isFinite(n)&&n>0&&y.start(n,()=>s.emit(Number.POSITIVE_INFINITY))),C.tpmCap!=null&&Number.isFinite(C.tpmCap)&&C.tpmCap>=0&&(i.emit(C.tpmCap),Number.isFinite(n)&&n>0&&b.start(n,()=>i.emit(Number.POSITIVE_INFINITY))),C.retryAfterMs!=null&&C.retryAfterMs>0){let V=$()+C.retryAfterMs*1e6;V>g&&(g=V)}}let w=N(0,{name:"adaptiveRateLimiter/pending"}),k=N(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),x=N(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),R=C=>{w.emit((w.cache??0)+C)},E=()=>{k.emit(d.available()),x.emit(l.available())};async function G(C={}){let V=C.requestCost??1,ne=C.tokenCost??0,F=C.signal;R(1);try{for(;;){if(F?.aborted)throw ya("AdaptiveRateLimiter.acquire aborted");let A=$();if(g>A){let ae=Math.ceil((g-A)/1e6);await fs(ae,F);continue}if(V>0&&f||ne>0&&p){await fs(250,F);continue}let D=d,I=l;if(!D.tryConsume(V)){await fs(Vl(D,V),F);continue}if(!(ne>0?I.tryConsume(ne):!0)){D.putBack(V),await fs(Vl(I,ne),F);continue}E();return}}finally{R(-1)}}function L(C){C>0?l.tryConsume(C):C<0&&l.putBack(-C),E()}function P(){m(),h(),v?.(),y.cancel(),b.cancel()}return{effectiveRpm:u,effectiveTpm:c,lastSignal:a,pending:w,rpmAvailable:k,tpmAvailable:x,acquire:G,recordUsage:L,recordSignal:T,dispose:P}}function Yn(t,e){if(!Number.isFinite(t)||t===1/0)return Lt(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let n=Math.max(1,t*e),r=t/60;return Lt(n,r)}function Vl(t,e){let n=t.available(),r=Math.max(0,e-n);return r<=0?25:Math.min(5e3,Math.max(50,r*100))}function fs(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(ya("AdaptiveRateLimiter.acquire aborted")):new Promise((n,r)=>{let o=new _e,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(ya("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",s,{once:!0}))})}Re();function ba(t,e={}){let n=e.limiter??Kl({name:e.name??"rateLimiter",rpm:e.rpm,tpm:e.tpm,adaptation:e.adaptation,burstMultiplier:e.burstMultiplier}),r=(i,a)=>e.costFn?e.costFn(i,a):0,o=i=>{let a=ga(i);a&&n.recordSignal(a)};return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(i,a){let u=r(i,a);await n.acquire({requestCost:1,tokenCost:u,signal:a?.signal});try{let c=t.invoke(i,a),d=await gh(c),l=d.usage??Gl(),p=Nt(l)+hn(l)-u;return p>0&&n.recordUsage(p),d}catch(c){throw o(c),c}},async*stream(i,a){let u=r(i,a);await n.acquire({requestCost:1,tokenCost:u,signal:a?.signal});try{let c=0;for await(let l of t.stream(i,a))l.type==="usage"&&(c=Nt(l.usage)+hn(l.usage)),yield l;let d=c-u;d>0&&n.recordUsage(d)}catch(c){throw o(c),c}}},limiter:n}}async function gh(t){return t!=null&&typeof t.then=="function"?await t:t&&typeof t=="object"&&"content"in t?t:await Kn(re(t))}Tt();var $r=class extends Error{name="AllTiersExhaustedError";skipped;failed;constructor(e){let n=[];e.failed.size>0&&n.push(`failed=[${[...e.failed.keys()].join(",")}]`),e.skipped.length>0&&n.push(`skipped=[${e.skipped.map(r=>`${r.name}(${r.reason})`).join(",")}]`),super(`All LLM adapter tiers exhausted: ${n.join(" ")}`),this.skipped=e.skipped,this.failed=e.failed}};function va(t,e={}){if(t.length===0)throw new RangeError("cascadingLlmAdapter: tiers must be non-empty");let n=t.map(o=>({name:o.name,adapter:o.adapter,filter:o.filter,breaker:o.breaker?"canExecute"in o.breaker?o.breaker:ft(o.breaker):void 0})),r=e.streamRetryBeforeFirstChunk??!0;return{provider:"cascading",model:void 0,async invoke(o,s){let i=[],a=new Map;for(let c=0;c<n.length;c++){let d=n[c];if(d.filter&&!d.filter(o,s)){i.push({name:d.name,reason:"filter"});continue}if(d.breaker&&!d.breaker.canExecute()){i.push({name:d.name,reason:"breaker"});continue}try{let l=await Promise.resolve(d.adapter.invoke(o,s));return d.breaker?.recordSuccess(),{...l,metadata:{...l.metadata??{},tier:d.name}}}catch(l){a.set(d.name,l),d.breaker?.recordFailure(l);let f=n[c+1];f&&e.onFallback?.(d.name,f.name,l)}}let u={skipped:i,failed:a};throw e.onExhausted?.(u),new $r(u)},async*stream(o,s){let i=[],a=new Map;for(let c=0;c<n.length;c++){let d=n[c];if(d.filter&&!d.filter(o,s)){i.push({name:d.name,reason:"filter"});continue}if(d.breaker&&!d.breaker.canExecute()){i.push({name:d.name,reason:"breaker"});continue}let l=!1;try{for await(let f of d.adapter.stream(o,s))l=!0,yield f;d.breaker?.recordSuccess();return}catch(f){if(a.set(d.name,f),d.breaker?.recordFailure(f),l||!r)throw f;let p=n[c+1];p&&e.onFallback?.(d.name,p.name,f)}}let u={skipped:i,failed:a};throw e.onExhausted?.(u),new $r(u)}}}pt();function ms(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function Hl(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(ms()):new Promise((n,r)=>{let o=new _e,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(ms())},e.addEventListener("abort",s,{once:!0}))})}function Ta(t,e={}){let n=e.attempts??3,r=e.baseDelayMs??500,o=e.maxDelayMs??1e4,s=e.strategy??"decorrelated",i=e.jitter??!0,a=e.shouldRetry??yh,u=e.retryStreaming??!0,c=(d,l)=>{if(s==="decorrelated"){let h=Math.min(o,Math.max(r,l*3));return r+Math.random()*(h-r)}let f=s==="exp"?r*2**(d-1):r*d,p=Math.min(o,f);if(!i)return p;let m=p*(.5+Math.random());return Math.min(o,m)};return{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(d,l){if(l?.signal?.aborted)throw ms();let f,p=r;for(let m=1;m<=n;m++)try{return await Promise.resolve(t.invoke(d,l))}catch(h){if(f=h,m>=n||!a(h,m))throw h;let g=c(m,p);p=g,await Hl(g,l?.signal)}throw f},async*stream(d,l){if(l?.signal?.aborted)throw ms();if(!u){for await(let m of t.stream(d,l))yield m;return}let f,p=r;for(let m=1;m<=n;m++){let h=!1;try{for await(let g of t.stream(d,l))h=!0,yield g;return}catch(g){if(f=g,h||m>=n||!a(g,m))throw g;let y=c(m,p);p=y,await Hl(y,l?.signal)}}throw f}}}function yh(t,e){if(t==null)return!1;let n=t;return n.name==="LLMTimeoutError"?!0:n.name==="AbortError"||n.message==="aborted"||n.name==="DOMException"&&n.code!=null&&Number(n.code)===20||n.name==="BudgetExhaustedError"||n.name==="CircuitOpenError"?!1:n.status!=null?n.status===429||n.status>=500&&n.status<600:n.code&&typeof n.code=="string"&&/^E[A-Z]+$/.test(n.code)?!0:n.message?/network|timeout|socket|fetch|econn|eai_/i.test(n.message):!1}pt();var Qn=class extends Error{constructor(n){super(`LLM call timed out after ${n}ms`);this.ms=n}name="LLMTimeoutError"};function wa(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let n=o=>{let s=new AbortController,i=!1,a;o&&(o.aborted?s.abort(o.reason):(a=()=>s.abort(o.reason),o.addEventListener("abort",a,{once:!0})));let u=new _e;return u.start(e,()=>{i=!0,s.abort(new Qn(e))}),{signal:s.signal,cancel:()=>{u.cancel(),o&&a&&o.removeEventListener("abort",a)},timedOut:()=>i}},r=(o,s)=>{if(!s||o instanceof Qn)throw o;let i=o;if(i?.name==="AbortError"||i?.name==="DOMException"&&Number(i.code)===20||o?.message==="aborted"){let u=new Qn(e);throw u.cause=o,u}throw o};return{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(o,s){let{signal:i,cancel:a,timedOut:u}=n(s?.signal);try{return await Promise.resolve(t.invoke(o,{...s,signal:i}))}catch(c){return r(c,u())}finally{a()}},async*stream(o,s){let{signal:i,cancel:a,timedOut:u}=n(s?.signal);try{for await(let c of t.stream(o,{...s,signal:i}))yield c}catch(c){r(c,u())}finally{a()}}}}function bh(t,e={}){let n={adapter:t},r=t;if(e.rateLimit){let o=ba(r,e.rateLimit);r=o.adapter,n.rateLimiter=o.limiter}if(e.budget){let o=ha(r,e.budget);r=o.adapter,n.budget=o.budget}if(e.breaker){let o=fa(r,e.breaker);r=o.adapter,n.breaker=o.breaker}if(e.timeoutMs!=null&&(r=wa(r,e.timeoutMs)),e.retry&&(r=Ta(r,e.retry)),e.fallback){if(e.name==="fallback")throw new RangeError('resilientAdapter: `name` cannot be "fallback" \u2014 collides with the secondary tier label.');let o={};e.onFallback&&(o.onFallback=e.onFallback),e.onExhausted&&(o.onExhausted=e.onExhausted),r=va([{name:e.name??"primary",adapter:r},{name:"fallback",adapter:e.fallback}],o)}return n.adapter=r,n}function vh(){return St()}oe();Re();function Th(t,e,n){let r=re(e);return be(r,s=>{if(!s||s.length===0)return N(null);let i=n?.tools;return t.invoke(s,{model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,tools:i,systemPrompt:n?.systemPrompt})})}xe();Re();ie();Re();pt();function ge(t,e){return Ke("ai",t,e)}function wh(t){return t!=null&&typeof t.then=="function"}function kh(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function xh(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var Rh=3e4;function Wl(t,e){if(t.status==="settled"){let r=t.cache;if(r!==void 0)return Promise.resolve(r)}let n=e?.timeoutMs??Rh;return new Promise((r,o)=>{let s=new _e,i=t.subscribe(a=>{for(let u of a){if(u[0]===S){s.cancel(),i(),r(u[1]);return}if(u[0]===M){s.cancel(),i(),o(u[1]);return}if(u[0]===_){s.cancel(),i(),o(new Error("firstDataFromNode: completed without producing a value"));return}}});s.start(n,()=>{i(),o(new Error(`firstDataFromNode: timed out after ${n}ms`))})})}async function gn(t){return wh(t)?gn(await t):kh(t)?Wl(t):xh(t)?Wl(re(t)):t}function yn(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function Sh(t,e){let n=re(t),r=e?.refreshTrigger!=null?re(e.refreshTrigger):null;return r==null?K([n],(o,s,i)=>{if(i.store.emitted===!0)return;let u=o[0],c=u!=null&&u.length>0?u.at(-1):i.prevData[0];if(c!==void 0)return i.store.emitted=!0,s.emit(c),{invalidate:()=>{i.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:ge("frozen_context")}):K([n,r],(o,s,i)=>{let a=o[1];if(!(a!=null&&a.length>0))return;let c=o[0],d=c!=null&&c.length>0?c.at(-1):i.prevData[0];s.emit(d)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:ge("frozen_context")})}oe();function Nh(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function Br(t,e,n,r){let o=r?.format??"text",s=r?.retries??0,i=r?.cache??!1,a=i?new Map:null,u=O(e,d=>{if(d.some(p=>p==null))return[];let l=typeof n=="string"?n:n(...d);if(!l)return[];let f=[];return r?.systemPrompt&&f.push({role:"system",content:r.systemPrompt}),f.push({role:"user",content:l}),f},{name:r?.name?`${r.name}::messages`:"prompt_node::messages",meta:ge("prompt_node"),initial:[]});return be(u,d=>{if(!d||d.length===0)return N(null);let l=i?JSON.stringify(d.map(p=>[p.role,p.content])):"";if(a?.has(l))return N(a.get(l));async function f(p){try{let m=await new Promise((y,b)=>{let v=t.invoke(d,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt});v&&typeof v.then=="function"?v.then(y,b):v&&typeof v.subscribe=="function"?y(v.cache):y(v)}),h=Nh(m),g;return o==="json"?g=JSON.parse(yn(h)):g=h,a?.set(l,g),g}catch(m){if(p>0)return f(p-1);throw m}}return f(s)})}oe();Re();var bs={};he(bs,{MessagingHubGraph:()=>ys,SubscriptionGraph:()=>jr,TopicBridgeGraph:()=>gs,TopicGraph:()=>nt,messagingHub:()=>_h,subscription:()=>ql,topic:()=>Et,topicBridge:()=>Mh});xe();var Eh=2147483647;function hs(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function bn(t,e){return Ke("messaging",t,e)}var nt=class extends q{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=Ve([],{name:"events",maxSize:n.retainedLimit}),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=O([this.events],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:bn("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(se(this.latest)),this.hasLatest=O([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:bn("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(se(this.hasLatest)),this.addDisposer(()=>{this.events.down([[_]])}),this.addDisposer(()=>this._log.disposeAllViews())}publish(e){this._log.append(e)}retained(){return this.events.cache}},jr=class extends q{source;cursor;available;topic;constructor(e,n,r={}){super(e,r.graph);let o=hs(r.cursor??0,"subscription cursor");this.topic=n;let s=n.events;this.source=O([s],([i])=>i,{name:"source",describeKind:"derived",meta:bn("subscription_source"),initial:s.cache}),this.add(this.source,{name:"source"}),this.cursor=N(o,{name:"cursor",describeKind:"state",meta:bn("subscription_cursor")}),this.add(this.cursor,{name:"cursor"}),this.available=O([this.source,this.cursor],([i,a])=>{let u=i,c=Math.max(0,Math.trunc(a??0));return u.slice(c)},{name:"available",describeKind:"derived",meta:bn("subscription_available"),initial:[]}),this.add(this.available,{name:"available"}),this.addDisposer(se(this.source)),this.addDisposer(se(this.available))}ack(e){let n=this.available.cache,r=e===void 0?n.length:hs(e,"subscription ack count"),o=Math.min(r,n.length);if(o<=0)return this.cursor.cache;let s=this.cursor.cache+o;return this.cursor.emit(s),s}pull(e,n={}){let r=this.available.cache,o=e===void 0?r.length:hs(e,"subscription pull limit"),s=r.slice(0,o);return n.ack&&s.length>0&&this.ack(s.length),s}},gs=class extends q{_sourceSub;_target;bridgedCount;constructor(e,n,r,o={}){super(e,o.graph),this._sourceSub=ql(`${e}-subscription`,n,{cursor:o.cursor}),this._target=r,this.mount("subscription",this._sourceSub),this.bridgedCount=N(0,{name:"bridgedCount",describeKind:"state",meta:bn("topic_bridge_count")}),this.add(this.bridgedCount,{name:"bridgedCount"});let s=Math.max(1,hs(o.maxPerPump??Eh,"topic bridge maxPerPump")),i=o.map??(u=>u),a=K([this._sourceSub.available],()=>{let u=this._sourceSub.pull(s,{ack:!0});if(u.length===0)return;let c=0;for(let d of u){let l=i(d);l!==void 0&&(this._target.publish(l),c+=1)}if(c>0){let d=this.bridgedCount.cache;this.bridgedCount.emit(d+c)}},{name:"pump",describeKind:"effect",meta:bn("topic_bridge_pump")});this.add(a,{name:"pump"}),this.addDisposer(se(a))}},ys=class extends q{_topics=new Map;_version=0;_defaultTopicOptions;constructor(e,n={}){super(e,n.graph),this._defaultTopicOptions={...n.defaultTopicOptions??{}}}get version(){return this._version}get size(){return this._topics.size}has(e){return this._topics.has(e)}topicNames(){return this._topics.keys()}topic(e,n){let r=this._topics.get(e);if(r===void 0){let o={...this._defaultTopicOptions,...n??{}};r=new nt(e,o),this._topics.set(e,r),this.mount(e,r),this._version+=1}return r}publish(e,n){this.topic(e).publish(n)}publishMany(e){te(()=>{for(let[n,r]of e)this.topic(n).publish(r)})}subscribe(e,n,r){let o=this.topic(n);return new jr(e,o,r)}removeTopic(e){if(!this._topics.has(e))return!1;try{this.remove(e)}finally{this._topics.delete(e),this._version+=1}return!0}};function Et(t,e){return new nt(t,e)}function _h(t,e){return new ys(t,e)}function ql(t,e,n){return new jr(t,e,n)}function Mh(t,e,n,r){return new gs(t,e,n,r)}var vs={};he(vs,{approval:()=>Ih,branch:()=>Lh,gate:()=>Vr,join:()=>Ph,loop:()=>Dh,onFailure:()=>$h,pipeline:()=>Ul,sensor:()=>Fh,subPipeline:()=>Gh,task:()=>Ah});Ne();ie();xe();oe();function _t(t,e){if(typeof e=="string")return{node:t.resolve(e),path:e};let n=Oh(t,e);if(!n)throw new Error("orchestration dep node must already be registered in the graph so explicit edges can be recorded; pass a string path or register the node first");return{node:e,path:n}}function Oh(t,e){let n=t.describe(),r=`::${je}::`;for(let o of Object.keys(n.nodes).sort())if(!o.includes(r))try{if(t.resolve(o)===e)return o}catch{}}function Bt(t,e,n,r){t.add(n,{name:e})}function jt(t,e){return Ke("orchestration",t,e)}function Ch(t){let e=r=>{let o=r.trim();return o.length===0?0:Number(o)},n;return typeof t=="string"?n=e(t):t===null?n=0:n=Number(t),Number.isFinite(n)?Math.max(0,Math.trunc(n)):1}function Ul(t,e){return new q(t,e)}function Ah(t,e,n,r){let s=(r?.deps??[]).map(d=>_t(t,d)),{deps:i,...a}=r??{},u=(d,l,f)=>{let p=d.map((m,h)=>m!=null&&m.length>0?m.at(-1):f.prevData[h]);l.emit(n(p,f))},c=K(s.map(d=>d.node),u,{...a,name:e,describeKind:"derived",meta:jt("task",r?.meta)});return Bt(t,e,c,s.flatMap(d=>d.path?[d.path]:[])),c}function Lh(t,e,n,r,o){let s=_t(t,n),i=O([s.node],([a])=>({branch:r(a)?"then":"else",value:a}),{...o,name:e,meta:jt("branch",o?.meta)});return Bt(t,e,i,s.path?[s.path]:[]),i}function Ih(t,e,n,r,o){let s=_t(t,n),i=_t(t,r),a=o?.isApproved??(c=>!!c),u=K([s.node,i.node],(c,d,l)=>{let f=c[0],p=c[1],m=p!=null&&p.length>0?p.at(-1):l.prevData[1];if(m===void 0||!a(m)){d.down([[B]]);return}if(f==null||f.length===0){p!=null&&p.length>0&&l.prevData[0]!==void 0?d.emit(l.prevData[0]):d.down([[B]]);return}for(let h of f)d.emit(h)},{...o,name:e,describeKind:"derived",meta:jt("approval",o?.meta)});return Bt(t,e,u,[s.path,i.path].filter(c=>typeof c=="string")),u}function Vr(t,e,n,r){let o=r?.maxPending??1/0;if(o<1&&o!==1/0)throw new RangeError("gate: maxPending must be >= 1");let s=r?.startOpen??!1,i=_t(t,n),a=N([],{name:"pending",equals:()=>!1}),u=N(s,{name:"isOpen"}),c=O([a],([w])=>w.length,{name:"count"}),d=[],l=!1,f=s,p=u.subscribe(w=>{for(let k of w)k[0]===S&&(f=k[1])});function m(){a.emit([...d])}function h(w){d.push(w),d.length>o&&d.shift(),m()}function g(w){let k=d.splice(0,w);return m(),k}function y(w){if(l)throw new Error(`gate: ${w}() called after gate was torn down`)}let b=K([i.node],(w,k,x)=>{let R=x.terminalDeps[0];if(R!==void 0){l=!0,d=[],m(),k.down(R===!0?[[_]]:[[M,R]]);return}let E=w[0];if(E==null||E.length===0){k.down([[B]]);return}for(let G of E)f?k.emit(G):(h(G),k.down([[B]]))},{name:e,describeKind:"derived",meta:jt("gate",r?.meta)}),v={node:b,pending:a,count:c,isOpen:u,approve(w=1){y("approve");let k=g(w);for(let x of k){if(l)break;b.emit(x)}},reject(w=1){y("reject"),g(w)},modify(w,k=1){y("modify");let x=[...d],R=g(k);for(let E=0;E<R.length&&!l;E++)b.emit(w(R[E],E,x))},open(){y("open"),te(()=>{u.emit(!0);let w=g(d.length);for(let k of w){if(l)break;b.emit(k)}})},close(){y("close"),u.emit(!1)}};t.addDisposer(c.subscribe(()=>{})),t.addDisposer(p),Bt(t,e,b,i.path?[i.path]:[]);let T=new q(`${e}_state`);return T.add(a,{name:"pending"}),T.add(u,{name:"isOpen"}),T.add(c,{name:"count"}),t.mount(`${e}_state`,T),v}function Ph(t,e,n,r){let o=n.map(i=>_t(t,i)),s=O(o.map(i=>i.node),i=>i,{...r,name:e,meta:jt("join",r?.meta)});return Bt(t,e,s,o.flatMap(i=>i.path?[i.path]:[])),s}function Dh(t,e,n,r,o){let s=_t(t,n),i=o?.iterations,a=typeof i=="number"||i===void 0?void 0:_t(t,i),u=typeof i=="number"?i:void 0,c=K(a?[s.node,a.node]:[s.node],(d,l,f)=>{let p=d[0],m=p!=null&&p.length>0?p.at(-1):f.prevData[0],h=a?d[1]:void 0,g=u??(a?h!=null&&h.length>0?h.at(-1):f.prevData[1]:1),y=Ch(g);for(let b=0;b<y;b+=1)m=r(m,b,l);l.emit(m)},{...o,name:e,describeKind:"derived",meta:jt("loop",o?.meta)});return Bt(t,e,c,[s.path,a?.path].filter(d=>typeof d=="string")),c}function Gh(t,e,n,r){let o=n instanceof q?n:Ul(e,r);return typeof n=="function"&&n(o),t.mount(e,o),o}function Fh(t,e,n,r){let o=K([],()=>{},{...r,name:e,initial:n,describeKind:"producer",meta:jt("sensor",r?.meta)});return Bt(t,e,o,[]),{node:o,push(s){o.emit(s)},error(s){o.down([[M,s]])},complete(){o.down([[_]])}}}function $h(t,e,n,r,o){let s=_t(t,n),i=!1,a=K([],(u,c)=>{let d=s.node.subscribe(l=>{for(let f of l){if(i)return;if(f[0]===M)try{c.emit(r(f[1],c))}catch(p){i=!0,c.down([[M,p]])}else c.down([f]),f[0]===_&&(i=!0)}});return()=>d()},{...o,name:e,describeKind:"derived",completeWhenDepsComplete:!1,errorWhenDepsError:!1,meta:jt("onFailure",o?.meta)});return Bt(t,e,a,s.path?[s.path]:[]),a}function Bh(t,e,n,r){let o=r?.name??"llm",s=r?.format??"text",i=Et(`${o}/stream`),a=O(e,d=>{if(d.some(p=>p==null))return[];let l=typeof n=="string"?n:n(...d);if(!l)return[];let f=[];return r?.systemPrompt&&f.push({role:"system",content:r.systemPrompt}),f.push({role:"user",content:l}),f}),u=be(a,d=>{let l=d;if(!l||l.length===0)return N(null);let f=new AbortController;async function*p(){let m="",h=0;try{for await(let y of t.stream(l,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,signal:f.signal})){if(y.type!=="token")continue;let b=y.delta;m+=b,i.publish({source:o,token:b,accumulated:m,index:h++})}let g;if(s==="json")try{g=JSON.parse(yn(m))}catch{g=null}else g=m;yield g}finally{f.abort()}}return re(p())}),c=se(u);return{output:u,stream:i,dispose:()=>{c(),i.destroy()}}}function jh(t,e,n,r,o,s){let i=N(0,{name:`${e}/cancel`}),a=0,u=[...r,i],c=s?.name??e,d=s?.format??"text",l=Et(`${c}/stream`),f=O(u,v=>{let T=v.slice(0,-1);if(T.some(x=>x==null))return[];let w=typeof o=="string"?o:o(...T);if(!w)return[];let k=[];return s?.systemPrompt&&k.push({role:"system",content:s.systemPrompt}),k.push({role:"user",content:w}),k}),p=be(f,v=>{let T=v;if(!T||T.length===0)return N(null);let w=new AbortController;async function*k(){let x="",R=0;try{for await(let G of n.stream(T,{model:s?.model,temperature:s?.temperature,maxTokens:s?.maxTokens,systemPrompt:s?.systemPrompt,signal:w.signal})){if(G.type!=="token")continue;let L=G.delta;x+=L,l.publish({source:c,token:L,accumulated:x,index:R++})}let E;if(d==="json")try{E=JSON.parse(yn(x))}catch{E=null}else E=x;yield E}finally{w.abort()}}return re(k())}),m=se(p),h=O([p],([v])=>{if(v!=null)return v},{name:`${e}/filter`});t.add(h,{name:`${e}/raw`});let g=Vr(t,`${e}/gate`,`${e}/raw`,s?.gate),y=g.reject.bind(g),b={...g,reject(v=1){y(v),i.emit(++a)}};return{output:g.node,stream:l,gate:b,dispose:()=>{m(),l.destroy()}}}oe();Re();function Vh(t,e){let n=e?.separator??`
55
-
56
- `,r=t.map(i=>typeof i=="string"?N(i):re(i)),o=O(r,i=>i.filter(a=>a!=null&&a!=="").join(n),{name:e?.name??"systemPrompt",describeKind:"derived",meta:ge("system_prompt"),initial:""}),s=se(o);return Object.assign(o,{dispose:s})}oe();var Kh=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens;function Hh(t,e){let n=e?.charsPerToken??4;return O([t.latest],([r])=>{if(r==null)return{chunkCount:0,charCount:0,estimatedTokens:0};let o=r,s=o.accumulated.length;return{chunkCount:o.index+1,charCount:s,estimatedTokens:Math.ceil(s/n)}},{name:e?.name??"cost-meter",describeKind:"derived",initial:{chunkCount:0,charCount:0,estimatedTokens:0},meta:ge("cost_meter_extractor"),equals:Kh})}oe();var Wh=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.label!==o.label||r.pattern!==o.pattern||r.match!==o.match||r.position!==o.position)return!1}return!0};function qh(t,e){let n=e.maxPatternLength??128;return O([t.latest],([r],o)=>{if(r==null)return[];let s=r.accumulated;"flags"in o.store||(o.store.flags=[],o.store.scannedTo=0);let i=o.store.flags,a=o.store.scannedTo,u=Math.max(0,a-n),c=s.slice(u),d=!1;for(let{pattern:l,label:f}of e.patterns){let p=new RegExp(l.source,`${l.flags.replace("g","")}g`);for(let m of c.matchAll(p)){let h=u+m.index;h+m[0].length<=a||(i.push({label:f,pattern:l,match:m[0],position:h}),d=!0)}}return o.store.scannedTo=s.length,d?[...i]:i.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:ge("keyword_flag_extractor"),equals:Wh})}oe();function Uh(t,e,n){return O([t.latest],([r])=>r==null?null:e(r.accumulated),{name:n?.name??"extractor",describeKind:"derived",initial:null,meta:ge("stream_extractor"),...n?.equals?{equals:n.equals}:{}})}oe();var zh=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.startIndex!==o.startIndex||r.name!==o.name||r.raw!==o.raw)return!1}return!0};function Jh(t,e){return O([t.latest],([n],r)=>{if(n==null)return[];let o=n.accumulated;"calls"in r.store||(r.store.calls=[],r.store.scanFrom=0);let s=r.store.calls,i=r.store.scanFrom,a=!1;for(;i<o.length;){let u=o.indexOf("{",i);if(u===-1){r.store.scanFrom=o.length;break}let c=0,d=-1,l=!1;for(let p=u;p<o.length;p++){let m=o[p];if(l)m==="\\"&&p+1<o.length?p++:m==='"'&&(l=!1);else if(m==='"')l=!0;else if(m==="{")c++;else if(m==="}"&&(c--,c===0)){d=p;break}}if(d===-1){r.store.scanFrom=u;break}let f=o.slice(u,d+1);try{let p=JSON.parse(f);typeof p.name=="string"&&p.arguments!=null&&typeof p.arguments=="object"&&(s.push({name:p.name,arguments:p.arguments,raw:f,startIndex:u}),a=!0)}catch{}i=d+1,r.store.scanFrom=i}return a?[...s]:s.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:ge("tool_call_extractor"),equals:zh})}oe();function Yh(t,e,n,r){let o=n*(r?.hardMultiplier??1.5),s=typeof e!="function",i=[t.latest];return s&&i.push(e),O(i,a=>{let u=a[0];if(u==null)return"allow";let c=s?a[1]??0:e(u.accumulated);return c>=o?"block":c>=n?"review":"allow"},{name:r?.name??"content-gate",initial:"allow"})}oe();function Qh(t,e,n,r){let o=n??(()=>"[REDACTED]");function s(i){let a=i;for(let u of e){let c=u.global?u:new RegExp(u.source,`${u.flags}g`);a=a.replace(c,d=>o(d,u))}return a}return O([t.latest],([i])=>{if(i==null)return{source:"",token:"",accumulated:"",index:-1};let a=i,u=s(a.accumulated),c=s(a.token);return{source:a.source,token:c,accumulated:u,index:a.index}},{name:r?.name??"redactor"})}Ne();ie();xe();oe();Tt();Re();oe();var Ts=class extends q{_log;messages;latest;messageCount;constructor(e,n={}){super(e,n.graph),this._log=Ve([],{name:"messages",maxSize:n.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=O([this.messages],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:ge("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(se(this.latest)),this.messageCount=O([this.messages],([r])=>r.length,{name:"messageCount",describeKind:"derived",meta:ge("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(se(this.messageCount))}append(e,n,r){this._log.append({role:e,content:n,...r})}appendToolResult(e,n){this._log.append({role:"tool",content:n,toolCallId:e})}clear(){this._log.clear()}allMessages(){return this.messages.cache}};function ka(t,e){return new Ts(t,e)}oe();var ws=class extends q{definitions;schemas;constructor(e,n={}){super(e,n.graph),this.definitions=N(new Map,{name:"definitions",describeKind:"state",meta:ge("tool_definitions")}),this.add(this.definitions,{name:"definitions"}),this.schemas=O([this.definitions],([r])=>[...(r??new Map).values()],{name:"schemas",describeKind:"derived",meta:ge("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(se(this.schemas))}register(e){let n=this.definitions.cache,r=new Map(n);r.set(e.name,e),this.definitions.emit(r)}unregister(e){let n=this.definitions.cache;if(!n.has(e))return;let r=new Map(n);r.delete(e),this.definitions.emit(r)}async execute(e,n){let o=this.definitions.cache.get(e);if(!o)throw new Error(`toolRegistry: unknown tool "${e}"`);let s=o.handler(n);return gn(s)}getDefinition(e){return this.definitions.cache?.get(e)}};function xa(t,e){return new ws(t,e)}var ks=class extends q{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;turnCount;_terminalResult;_disposeRunWiring;_runVersion=0;_running=!1;_currentAbortController=null;constructor(e,n){if(super(e,n.graph),this.chat=ka(`${e}-chat`,{maxMessages:n.maxMessages}),this.mount("chat",this.chat),this.tools=xa(`${e}-tools`),this.mount("tools",this.tools),n.tools)for(let F of n.tools)this.tools.register(F);this.status=N("idle",{name:"status",describeKind:"state",meta:ge("agent_status")}),this.add(this.status,{name:"status"}),this.turn=N(0,{name:"turn",describeKind:"state",meta:ge("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.turnCount=this.turn,this.aborted=N(!1,{name:"aborted",describeKind:"state",meta:ge("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let r=0,o=this.turn.subscribe(F=>{for(let A of F)A[0]===S&&(r=A[1])}),s=!1,i=this.aborted.subscribe(F=>{for(let A of F)A[0]===S&&(s=A[1])}),a=n.adapter,u=n.systemPrompt,c=n.model,d=n.temperature,l=n.maxTokens,f=n.maxTurns??10,p=n.stopWhen,m=this.chat,h=this.tools,g=this.status,y=this.turn,b=this.aborted,v=K([g],(F,A,D)=>{if(Kr(F,D.prevData,0,"idle")!=="thinking"||s||r>=f){A.down([[B]]);return}let Q=m.allMessages();if(Q.length===0){A.down([[B]]);return}let U=h.schemas.cache??[];A.emit({messages:Q,tools:U})},{name:"promptInput",describeKind:"derived",meta:ge("agent_prompt_input")}),T=be(v,F=>{let A=new AbortController;return this._currentAbortController=A,s&&A.abort(new Error("agentLoop: aborted")),re(Promise.resolve(a.invoke(F.messages,{tools:F.tools.length>0?F.tools:void 0,systemPrompt:u,model:c,temperature:d,maxTokens:l,signal:A.signal})),{signal:A.signal})},{equals:()=>!1}),w=N(null,{name:"lastResponse",describeKind:"state",meta:ge("agent_last_response")});this.lastResponse=w;let k=K([w,g],(F,A,D)=>{let I=Kr(F,D.prevData,0,null);if(Kr(F,D.prevData,1,"idle")!=="acting"){A.down([[B]]);return}let U=I?.toolCalls;if(U==null||U.length===0){A.down([[B]]);return}A.emit(U)},{name:"toolCalls",describeKind:"derived",meta:ge("agent_tool_calls")}),x=n.interceptToolCalls?n.interceptToolCalls(k):k;this.toolCalls=x;let R=(F,A)=>{if(F===A)return!0;if(F.length!==A.length)return!1;for(let D=0;D<F.length;D++){let I=F[D],Q=A[D];if(I?.id!==Q?.id||I?.content!==Q?.content)return!1}return!0},E=be(x,F=>{if(F==null||F.length===0)throw new Error("agentLoop: toolResultsNode received an empty tool-call batch as DATA \u2014 toolCallsNode gating invariant broken (should emit RESOLVED for empty). Audit toolCallsNode.");let A=F.map(D=>Xh(D,h));return O(A,D=>D.map((I,Q)=>{let U=I;return U!=null&&typeof U=="object"&&"id"in U&&"content"in U?U:{id:F[Q].id,content:JSON.stringify(I??null)}}),{name:"toolResults_batch",equals:R})});this.toolResults=E;let G=fe([T],([F])=>{if(s)return;let A=F,D=r+1,I=A.toolCalls!=null&&A.toolCalls.length>0,Q=A.finishReason==="end_turn"&&(!A.toolCalls||A.toolCalls.length===0),U=p?.(A)===!0,ae=D>=f,j=U||Q||!I||ae?"done":"acting";te(()=>{w.emit(A),g.emit(j),y.emit(D),m.append("assistant",A.content,{toolCalls:A.toolCalls})})}),L=fe([E],([F])=>{if(s)return;let A=F;if(A.length===0)return;let D=r>=f?"done":"thinking";te(()=>{g.emit(D);for(let I of A)m.appendToolResult(I.id,I.content)})}),P=fe([b],([F])=>{F===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),g.emit("done"))}),C=se(G),V=se(L),ne=se(P);this._terminalResult=K([g,w],(F,A,D)=>{let I=Kr(F,D.prevData,0,"idle"),Q=Kr(F,D.prevData,1,null);if(I==="done"){if(Q!=null){A.emit({response:Q,runVersion:this._runVersion});return}let U=new Error("agentLoop: aborted");U.name="AbortError",A.down([[M,U]]);return}if(I==="error"){A.down([[M,new Error("agentLoop: errored")]]);return}A.down([[B]])},{name:"terminalResult",describeKind:"derived",meta:ge("agent_terminal_result")}),this.addDisposer(o),this.addDisposer(i),this.addDisposer(C),this.addDisposer(V),this.addDisposer(ne),this._disposeRunWiring=()=>{}}async run(e,n){if(this._running)throw new RangeError(`agentLoop "${this.name}": run() called while a previous run() is still pending \u2014 await the previous run before starting another, or call abort() first`);this._running=!0;let r=++this._runVersion;te(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle")}),e!=null&&this.chat.append("user",e),this.status.emit("thinking");let o;if(n!=null)if(n.aborted)this.aborted.emit(!0);else{let s=()=>this.aborted.emit(!0);n.addEventListener("abort",s,{once:!0}),o=()=>n.removeEventListener("abort",s)}try{return(await So(this._terminalResult,{predicate:i=>i!=null&&typeof i=="object"&&i.runVersion===r})).response}finally{o?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function Xh(t,e){let n=At(()=>re(Promise.resolve().then(()=>e.execute(t.name,t.arguments))),{count:1}),r=O([n],([o])=>({id:t.id,content:typeof o=="string"?o:JSON.stringify(o)}));return Mr(r,o=>({id:t.id,content:JSON.stringify({error:String(o)})}))}function Kr(t,e,n,r){let o=t[n];if(o!=null&&o.length>0)return o[o.length-1];let s=e[n];return s!==void 0?s:r}function Zh(t,e){return new ks(t,e)}oe();Re();function eg(t,e,n){let r=re(t),o=n?.condition!=null?re(n.condition):null,s=N(null,{name:n?.name?`${n.name}::null`:"handoff::null"});if(o==null)return be(r,a=>{if(a==null)return s;let u=N(a);return e(u)});let i=O([r,o],([a,u])=>({v:a,open:u===!0}),{name:n?.name?`${n.name}::router`:"handoff::router",describeKind:"derived"});return be(i,({v:a,open:u})=>{if(a==null)return s;if(!u)return N(a);let c=N(a);return e(c)})}oe();Re();function tg(t,e,n){let r=re(t),o=e.map(i=>re(i)),s=[r,...o];return O(s,i=>{let a=i[0]??[],u=i.slice(1);return a.filter(c=>{for(let d of u)if(d!=null&&!d(c))return!1;return!0})},{name:n?.name??"tool-selector",describeKind:"derived",meta:ge("tool_selector"),equals:(i,a)=>{let u=i,c=a;if(u.length!==c.length)return!1;for(let d=0;d<u.length;d++)if(u[d]!==c[d])return!1;return!0}})}function ng(t){return{persistence:.5,structure:.5,personalValue:.5}}function rg(t={}){let e=t.scoreFn??ng,n=t.persistenceThreshold??.3,r=t.personalValueThreshold??.3,o=t.requireStructured??!1;return s=>{let i=e(s);return!(i.persistence<n||i.personalValue<r||o&&i.structure<=0)}}Ne();ke();oe();Re();var Rs={};he(Rs,{collection:()=>sg,decay:()=>vn,knowledgeGraph:()=>Na,lightCollection:()=>Ra,vectorIndex:()=>Sa});ke();oe();function vn(t,e,n,r=0){if(!Number.isFinite(t))return r;if(!Number.isFinite(e)||e<=0||!Number.isFinite(n)||n<=0)return Math.max(r,t);let o=t*Math.exp(-n*e);return Math.max(r,o)}function zl(t){if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1")}function ht(t){return new Map(t)}function ze(t){return t.cache??new Map}function xs(t){return t.cache??[]}function og(t,e){let n=Math.max(t.length,e.length),r=0,o=0,s=0;for(let i=0;i<n;i+=1){let a=t[i]??0,u=e[i]??0;r+=a*u,o+=a*a,s+=u*u}return o===0||s===0?0:r/Math.sqrt(o*s)}function Ra(t={}){let e=t.maxSize,n=t.policy??"fifo";zl(e);let r=N(new Map,{name:t.name,describeKind:"state"});function o(i){if(e!==void 0)for(;i.size>e;){let a;for(let u of i.values()){if(!a){a=u;continue}let c=n==="lru"?u.lastAccessNs:u.createdAtNs,d=n==="lru"?a.lastAccessNs:a.createdAtNs;c<d&&(a=u)}if(!a)break;i.delete(a.id)}}function s(i){r.emit(i)}return{entries:r,upsert(i,a){let u=$(),c=ze(r),d=c.get(i),l=ht(c);l.set(i,{id:i,value:a,createdAtNs:d?.createdAtNs??u,lastAccessNs:u}),o(l),s(l)},remove(i){let a=ht(ze(r));a.delete(i)&&s(a)},clear(){ze(r).size!==0&&s(new Map)},get(i){let a=ze(r),u=a.get(i);if(u){if(n==="lru"){let c=$(),d=ht(a);d.set(i,{...u,lastAccessNs:c}),s(d)}return u.value}},has(i){return ze(r).has(i)}}}function sg(t,e={}){let n=e.maxSize,r=e.policy??"lru",o=e.decayRate??0,s=e.minScore??0,i=e.score??(()=>1);zl(n);let a=new q(t),u=N(new Map,{name:"items",describeKind:"state"}),c=O([u],([h])=>{let g=h??new Map,y=$(),b=[...g.values()].map(v=>{let T=(y-v.lastAccessNs)/1e9;return{...v,score:vn(v.baseScore,T,o,s)}});return b.sort((v,T)=>T.score-v.score||T.lastAccessNs-v.lastAccessNs),b},{name:"ranked",describeKind:"derived"}),d=O([u],([h])=>(h??new Map).size,{name:"size",describeKind:"derived",initial:0});c.subscribe(()=>{}),d.subscribe(()=>{}),a.add(u,{name:"items"}),a.add(c,{name:"ranked"}),a.add(d,{name:"size"});function l(h,g){let y=(g-h.lastAccessNs)/1e9;return vn(h.baseScore,y,o,s)}function f(h){if(n!==void 0)for(;h.size>n;){let g=$(),y,b=Number.POSITIVE_INFINITY;for(let v of h.values()){let T=l(v,g);if(T<b){y=v,b=T;continue}if(T===b&&y){let w=r==="lru"?v.lastAccessNs:v.createdAtNs,k=r==="lru"?y.lastAccessNs:y.createdAtNs;w<k&&(y=v)}}if(!y)break;h.delete(y.id)}}function p(h){u.emit(h)}return Object.assign(a,{upsert(h,g,y){let b=$(),v=ze(u),T=v.get(h),w=y?.score??i(g),k=ht(v);k.set(h,{id:h,value:g,baseScore:w,createdAtNs:T?.createdAtNs??b,lastAccessNs:b}),f(k),p(k)},remove(h){let g=ht(ze(u));g.delete(h)&&p(g)},clear(){ze(u).size!==0&&p(new Map)},getItem(h){let g=ze(u),y=g.get(h);if(y){if(r==="lru"){let b=ht(g);b.set(h,{...y,lastAccessNs:$()}),p(b)}return y}}})}function Sa(t={}){let e=t.backend??"flat",n=t.dimension,r;if(e==="hnsw"&&(r=t.hnswFactory?.(),!r))throw new Error('vectorIndex backend "hnsw" requires an optional dependency adapter; install your HNSW package and provide `hnswFactory`.');let o=N(new Map,{describeKind:"state",name:"vector-index"});function s(a){if(n!==void 0&&a.length!==n)throw new RangeError(`vector dimension mismatch: expected ${n}, got ${a.length}`)}function i(a){o.emit(a)}return{backend:e,entries:o,upsert(a,u,c){s(u);let d=ht(ze(o));d.set(a,{id:a,vector:[...u],meta:c}),e==="hnsw"&&r.upsert(a,u,c),i(d)},remove(a){let u=ht(ze(o));u.delete(a)&&(e==="hnsw"&&r.remove(a),i(u))},clear(){ze(o).size!==0&&(e==="hnsw"&&r.clear(),i(new Map))},search(a,u=5){return s(a),u<=0?[]:e==="hnsw"?r.search(a,u):[...ze(o).values()].map(d=>({id:d.id,score:og(a,d.vector),meta:d.meta})).sort((d,l)=>l.score-d.score).slice(0,u)}}}function Na(t){let e=new q(t),n=N(new Map,{name:"entities",describeKind:"state"}),r=N([],{name:"edges",describeKind:"state"}),o=O([r],([u])=>{let c=u??[],d=new Map;for(let l of c){let f=d.get(l.from)??[];d.set(l.from,Object.freeze([...f,l]))}return d},{name:"adjacency",describeKind:"derived",initial:new Map});o.subscribe(()=>{}),e.add(n,{name:"entities"}),e.add(r,{name:"edges"}),e.add(o,{name:"adjacency"});function s(u){n.emit(u)}function i(u){r.emit(u)}return Object.assign(e,{upsertEntity(u,c){let d=ht(ze(n));d.set(u,c),s(d)},removeEntity(u){let c=ht(ze(n)),d=c.delete(u),l=xs(r),f=l.filter(p=>p.from!==u&&p.to!==u);!d&&f.length===l.length||(s(c),i(f))},link(u,c,d,l=1){let f=`${u}\0${c}\0${d}`,p=xs(r),m=new Set(p.map(g=>`${g.from}\0${g.to}\0${g.relation}`)),h=[...p];if(m.has(f))for(let g=0;g<h.length;g+=1){let y=h[g];if(y.from===u&&y.to===c&&y.relation===d){h[g]={...y,weight:l};break}}else h.push({from:u,to:c,relation:d,weight:l});i(h)},unlink(u,c,d){let l=xs(r),f=l.filter(p=>d===void 0?!(p.from===u&&p.to===c):!(p.from===u&&p.to===c&&p.relation===d));f.length!==l.length&&i(f)},related(u,c){return xs(r).filter(d=>(d.from===u||d.to===u)&&(c===void 0||d.relation===c))}})}ie();oe();Re();function Ea(t,e){return(n,r)=>{let o=[...r.keys()].slice(0,100),s=[{role:"system",content:t},{role:"user",content:JSON.stringify({input:n,existingKeys:o})}];return W(i=>{let a=!0,u=e.adapter.invoke(s,{model:e.model,temperature:e.temperature??0,maxTokens:e.maxTokens}),d=re(u).subscribe(l=>{if(!a)return;let f=!1;for(let p of l){if(f)break;if(p[0]===S){let m=p[1];try{let h=JSON.parse(m.content);i.emit(h),i.down([[_]])}catch{i.down([[M,new Error("llmExtractor: failed to parse LLM response as JSON")]])}f=!0}else p[0]===M?(i.down([[M,p[1]]]),f=!0):p[0]===_?(i.down([[_]]),f=!0):i.down([[p[0],p[1]]])}});return()=>{d(),a=!1}})}}function _a(t,e){return n=>{let r=[...n.entries()].map(([s,i])=>({key:s,value:i})),o=[{role:"system",content:t},{role:"user",content:JSON.stringify({memories:r})}];return W(s=>{let i=!0,a=e.adapter.invoke(o,{model:e.model,temperature:e.temperature??0,maxTokens:e.maxTokens}),c=re(a).subscribe(d=>{if(!i)return;let l=!1;for(let f of d){if(l)break;if(f[0]===S){let p=f[1];try{let m=JSON.parse(p.content);s.emit(m),s.down([[_]])}catch{s.down([[M,new Error("llmConsolidator: failed to parse LLM response as JSON")]])}l=!0}else f[0]===M?(s.down([[M,f[1]]]),l=!0):f[0]===_?(s.down([[_]]),l=!0):s.down([[f[0],f[1]]])}});return()=>{c(),i=!1}})}}var Ma=Math.LN2/604800;function Hr(t){return t instanceof Map?t:new Map}function ig(t,e,n){let r=new q(t,n.graph),o=[],s;if(n.extractFn)s=n.extractFn;else if(n.adapter&&n.extractPrompt)s=Ea(n.extractPrompt,{adapter:n.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let i=(v,T)=>v==null?{upsert:[]}:s(v,T),a=e;if(n.admissionFilter){let v=re(e),T=n.admissionFilter;a=O([v],([w])=>{if(T(w))return w},{name:"admissionFilter",describeKind:"derived"})}let u;n.consolidateFn?u=n.consolidateFn:n.adapter&&n.consolidatePrompt&&(u=_a(n.consolidatePrompt,{adapter:n.adapter}));let c=n.consolidateTrigger;if(!c&&u&&n.reflection?.enabled!==!1){let v=n.reflection?.interval??3e5;c=et(v,{period:v})}let d={score:n.score,cost:n.cost,budget:n.budget??2e3,context:n.context,consolidate:u,consolidateTrigger:c},l=Zo(a,i,d);r.add(l.store.entries,{name:"store"}),r.add(l.compact,{name:"compact"}),r.add(l.size,{name:"size"});let f=null;n.vectorDimensions&&n.vectorDimensions>0&&n.embedFn&&(f=Sa({dimension:n.vectorDimensions}),r.add(f.entries,{name:"vectorIndex"}));let p=null;n.enableKnowledgeGraph&&(p=Na(`${t}-kg`),r.mount("kg",p));let m=null;if(n.tiers){let v=n.tiers,T=v.decayRate??Ma,w=v.maxActive??1e3,k=v.archiveThreshold??.1,x=v.permanentFilter??(()=>!1),R=Ra({name:"permanent"});r.add(R.entries,{name:"permanent"});let E=new Set,G=A=>E.has(A)?"permanent":Hr(l.store.entries.cache).has(A)?"active":"archived",L=(A,D)=>{E.add(A),R.upsert(A,D)},P=new Map,C=l.store.entries,V=n.context?re(n.context):N(null),ne=fe([C,V],([A,D])=>{let I=Hr(A),Q=$(),U=[],ae=[];for(let[Y,J]of I){if(P.has(Y)||P.set(Y,Q),x(Y,J)){ae.push({key:Y,value:J});continue}let z=n.score(J,D),X=P.get(Y)??Q,H=Number(Q-X)/1e9;vn(z,H,T)<k&&U.push(Y)}for(let Y of P.keys())I.has(Y)||P.delete(Y);for(let{key:Y,value:J}of ae)E.has(Y)||L(Y,J);let j=I.size-E.size;if(j>w){let Y=[...I.entries()].filter(([z])=>!E.has(z)).map(([z,X])=>({key:z,score:n.score(X,D)})).sort((z,X)=>z.score-X.score),J=j-w;for(let z=0;z<J&&z<Y.length;z++){let X=Y[z].key;U.includes(X)||U.push(X)}}U.length>0&&te(()=>{for(let Y of U)l.store.delete(Y)})});o.push(ne.subscribe(()=>{}));let F=null;v.archiveTier&&(F=r.attachStorage([v.archiveTier],v.archiveStorageOptions??{})),m={permanent:R,activeEntries:C,archiveHandle:F,tierOf:G,markPermanent:L}}if(f||p){let v=n.embedFn,T=n.entityFn,w=l.store.entries,k=fe([w],([x])=>{let R=Hr(x);for(let[E,G]of R){if(f&&v){let L=v(G);L&&f.upsert(E,L,G)}if(p&&T){let L=T(E,G);if(L){for(let P of L.entities??[])p.upsertEntity(P.id,P.value);for(let P of L.relations??[])p.link(P.from,P.to,P.relation,P.weight)}}}});o.push(k.subscribe(()=>{}))}let h=null,g=null,y=null,b=null;if(f||p){let v=n.retrieval?.topK??20,T=n.retrieval?.graphDepth??1,w=n.budget??2e3,k=n.cost,x=n.score,R=n.contextOf,E=n.contextWeight??0,G=n.context?re(n.context):N(null),L=(F,A)=>{if(!F||!A)return 0;let D=Math.min(F.length,A.length),I=0;for(;I<D&&F[I]===A[I];)I++;return I},P=(F,A,D)=>{let I=new Map,Q=[];if(f&&D.vector){Q=f.search(D.vector,v);for(let X of Q){let H=F.get(X.id);H&&I.set(X.id,{value:H,sources:new Set(["vector"])})}}let U=[];if(p){let X=[...D.entityIds??[],...I.keys()],H=new Set,le=X;for(let ve=0;ve<T;ve++){let Oe=[];for(let Be of le){if(H.has(Be))continue;H.add(Be);let gt=p.related(Be);for(let Wt of gt){let rt=Wt.to;if(!H.has(rt)){Oe.push(rt);let We=F.get(rt);if(We){let Z=I.get(rt);Z?Z.sources.add("graph"):I.set(rt,{value:We,sources:new Set(["graph"])}),U.push(rt)}}}}le=Oe}}for(let[X,H]of F)I.has(X)||I.set(X,{value:H,sources:new Set(["store"])});let ae=D.context?.length??0,j=[];for(let[X,{value:H,sources:le}]of I){let ve=R?R(H):void 0,Oe=x(H,A);if(E>0&&ae>0){let gt=L(D.context,ve);gt>0&&(Oe=Oe*(1+E*gt/ae))}let Be=ve?{key:X,value:H,score:Oe,sources:[...le],context:ve}:{key:X,value:H,score:Oe,sources:[...le]};j.push(Be)}j.sort((X,H)=>H.score-X.score);let Y=[],J=0;for(let X of j){let H=k(X.value);if(J+H>w&&Y.length>0)break;Y.push(X),J+=H}return{packed:Y,trace:{vectorCandidates:Q,graphExpanded:U,ranked:j,packed:Y}}},C=N([],{name:"retrieval",describeKind:"state",meta:ge("retrieval_pipeline")});r.add(C,{name:"retrieval"}),h=C;let V=N(null,{name:"retrievalTrace",describeKind:"state",meta:ge("retrieval_trace")});r.add(V,{name:"retrievalTrace"}),g=V,y=F=>{let A=Hr(l.store.entries.cache),{packed:D,trace:I}=P(A,G.cache,F);return te(()=>{C.emit(D),V.emit(I)}),D},b=F=>{let A=re(F);return O([l.store.entries,G,A],([D,I,Q])=>{if(Q==null)return[];let U=Hr(D);return P(U,I,Q).packed},{name:"retrievalReactive",describeKind:"derived",meta:ge("retrieval_reactive"),initial:[]})}}return r.addDisposer(()=>{for(let v of o)v();o.length=0}),Object.assign(r,{distillBundle:l,compact:l.compact,size:l.size,vectors:f,kg:p,memoryTiers:m,retrieval:h,retrievalTrace:g,retrieve:y,retrieveReactive:b})}function ag(t,e,n){let r=t.describe({actor:e,detail:"full"}),o=n?.groupByTags??!0,s=n?.separator??`
57
- `,i=[],a=n?.sinceVersion;for(let[u,c]of Object.entries(r.nodes)){let d=c.meta??{},l=d.description,f=d.format;if(!l&&!f)continue;if(a!=null&&c.v!=null){let y=a.get(u);if(y!=null&&y.id===c.v.id&&c.v.version<=y.version)continue}let p=l??u,m=c.value,h=d.unit,g;f==="currency"&&typeof m=="number"?g=`$${m.toFixed(2)}`:f==="percentage"&&typeof m=="number"?g=`${(m*100).toFixed(1)}%`:m==null?g="(no value)":g=String(m),h&&f!=="currency"&&f!=="percentage"&&(g=`${g} ${h}`),i.push({path:u,description:p,formatted:g})}if(i.length===0)return"";if(o){let u=new Map,c=[];for(let l of i){let p=r.nodes[l.path].meta?.tags;if(p&&p.length>0){let m=p[0],h=u.get(m);h||(h=[],u.set(m,h)),h.push(l)}else c.push(l)}if(u.size===0)return i.map(l=>`- ${l.description}: ${l.formatted}`).join(s);let d=[];for(let[l,f]of[...u.entries()].sort((p,m)=>p[0].localeCompare(m[0])))d.push(`[${l}]${s}${f.map(p=>`- ${p.description}: ${p.formatted}`).join(s)}`);return c.length>0&&d.push(c.map(l=>`- ${l.description}: ${l.formatted}`).join(s)),d.join(s+s)}return i.map(u=>`- ${u.description}: ${u.formatted}`).join(s)}var Jl=new Set(["state","derived","producer","operator","effect"]);function Oa(t){let e=[];if(t==null||typeof t!="object")return{valid:!1,errors:["Definition must be a non-null object"]};let n=t;if((typeof n.name!="string"||n.name.length===0)&&e.push("Missing or empty 'name' field"),n.nodes==null||typeof n.nodes!="object"||Array.isArray(n.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e};let r=new Set(Object.keys(n.nodes));for(let[o,s]of Object.entries(n.nodes)){if(s==null||typeof s!="object"){e.push(`Node "${o}": must be an object`);continue}let i=s;if((typeof i.type!="string"||!Jl.has(i.type))&&e.push(`Node "${o}": invalid type "${String(i.type)}" (expected: ${[...Jl].join(", ")})`),Array.isArray(i.deps))for(let a of i.deps)typeof a=="string"&&!r.has(a)&&e.push(`Node "${o}": dep "${a}" does not reference an existing node`)}if(!Array.isArray(n.edges))n.edges!==void 0&&e.push("'edges' must be an array");else{let o=new Set;for(let s=0;s<n.edges.length;s++){let i=n.edges[s];if(i==null||typeof i!="object"){e.push(`Edge [${s}]: must be an object`);continue}let a=i;(typeof a.from!="string"||!r.has(a.from))&&e.push(`Edge [${s}]: 'from' "${String(a.from)}" does not reference an existing node`),(typeof a.to!="string"||!r.has(a.to))&&e.push(`Edge [${s}]: 'to' "${String(a.to)}" does not reference an existing node`);let u=`${a.from}->${a.to}`;o.has(u)&&e.push(`Edge [${s}]: duplicate edge ${u}`),o.add(u)}}return{valid:e.length===0,errors:e}}var Yl=`You are a graph architect for GraphReFly, a reactive graph protocol.
58
-
59
- Given a natural-language description, produce a JSON graph definition with this structure:
60
-
61
- {
62
- "name": "<graph_name>",
63
- "nodes": {
64
- "<node_name>": {
65
- "type": "state" | "derived" | "producer" | "operator" | "effect",
66
- "value": <initial_value_or_null>,
67
- "deps": ["<dep_node_name>", ...],
68
- "meta": {
69
- "description": "<human-readable purpose>",
70
- "type": "string" | "number" | "boolean" | "integer" | "enum",
71
- "range": [min, max],
72
- "values": ["a", "b"],
73
- "format": "currency" | "percentage" | "status",
74
- "access": "human" | "llm" | "both" | "system",
75
- "unit": "<unit>",
76
- "tags": ["<tag>"]
77
- }
78
- }
79
- },
80
- "edges": [
81
- { "from": "<source_node>", "to": "<target_node>" }
82
- ]
83
- }
84
-
85
- Rules:
86
- - "state" nodes have no deps and hold user/LLM-writable values (knobs).
87
- - "derived" nodes have deps and compute from them.
88
- - "effect" nodes have deps but produce side effects (no return value).
89
- - "producer" nodes have no deps but generate values asynchronously.
90
- - Edges wire output of one node as input to another. They must match deps.
91
- - meta.description is required for every node.
92
- - Return ONLY valid JSON, no markdown fences or commentary.`;async function ug(t,e,n){let o=[{role:"system",content:n?.systemPromptExtra?`${Yl}
93
-
94
- ${n.systemPromptExtra}`:Yl},{role:"user",content:t}],s=e.invoke(o,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens}),a=(await gn(s)).content.trim();a.startsWith("```")&&(a=yn(a));let u;try{u=JSON.parse(a)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${a.slice(0,200)}`)}let c=Oa(u);if(!c.valid)throw new Error(`graphFromSpec: invalid graph definition:
95
- ${c.errors.join(`
96
- `)}`);let d=u;return d.version===void 0&&(d.version=1),Array.isArray(d.subgraphs)||(d.subgraphs=[]),q.fromSnapshot(d,n?.build)}function cg(t){let e={},n=t.type;return n==="enum"&&Array.isArray(t.values)?(e.type="string",e.enum=t.values):n==="integer"?e.type="integer":n==="number"?e.type="number":n==="boolean"?e.type="boolean":n==="string"?e.type="string":e.type=["string","number","boolean"],Array.isArray(t.range)&&t.range.length===2&&(e.minimum=t.range[0],e.maximum=t.range[1]),typeof t.format=="string"&&(e.description=`Format: ${t.format}`),typeof t.unit=="string"&&(e.description?e.description+=` (${t.unit})`:e.description=`Unit: ${t.unit}`),e}function dg(t,e){let n=t.describe({actor:e,detail:"full"}),r=[],o=[],s=[];for(let[i,a]of Object.entries(n.nodes)){if(a.type!=="state"||i.includes("::__meta__::")||a.status==="completed"||a.status==="errored")continue;let u=a.meta??{},c=u.access;if(c==="human"||c==="system")continue;let d=u.description??`Set the value of ${i}`,l=cg(u),f={type:"object",required:["value"],properties:{value:l},additionalProperties:!1},p=i.replace(/::/g,"__");r.push({type:"function",function:{name:p,description:d,parameters:f}}),o.push({name:i,description:d,inputSchema:f});let m=t,h=e,g=a.v;s.push({name:i,description:d,parameters:f,handler(y){return m.set(i,y.value,h?{actor:h}:void 0),y.value},...g!=null?{version:{id:g.id,version:g.version}}:{}})}return{openai:r,mcp:o,definitions:s}}var lg=`You are a reactive graph optimizer for GraphReFly.
97
-
98
- Given a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.
99
-
100
- Return ONLY valid JSON with this structure:
101
- {
102
- "summary": "<one-line summary of the strategy>",
103
- "reasoning": "<explanation of why these changes help>",
104
- "operations": [
105
- { "type": "add_node", "name": "<name>", "nodeType": "state|derived|effect|producer|operator", "meta": {...}, "initial": <value> },
106
- { "type": "remove_node", "name": "<name>" },
107
- { "type": "connect", "from": "<source>", "to": "<target>" },
108
- { "type": "disconnect", "from": "<source>", "to": "<target>" },
109
- { "type": "set_value", "name": "<name>", "value": <new_value> },
110
- { "type": "update_meta", "name": "<name>", "key": "<meta_key>", "value": <new_value> }
111
- ]
112
- }
113
-
114
- Rules:
115
- - Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).
116
- - Keep changes minimal \u2014 prefer the smallest set of operations that solves the problem.
117
- - Return ONLY valid JSON, no markdown fences or commentary.`;async function pg(t,e,n,r){let{expand:o,...s}=t.describe({actor:r?.actor,detail:"standard"}),i=[{role:"system",content:lg},{role:"user",content:JSON.stringify({graph:s,problem:e})}],a=n.invoke(i,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens}),c=(await gn(a)).content.trim();c.startsWith("```")&&(c=c.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let d;try{d=JSON.parse(c)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${c.slice(0,200)}`)}let l=d;if(typeof l.summary!="string")throw new Error("suggestStrategy: missing 'summary' in response");if(typeof l.reasoning!="string")throw new Error("suggestStrategy: missing 'reasoning' in response");if(!Array.isArray(l.operations))throw new Error("suggestStrategy: missing 'operations' array in response");return{summary:l.summary,reasoning:l.reasoning,operations:l.operations}}var _s={};he(_s,{AuditTrailGraph:()=>Ns,PolicyEnforcerGraph:()=>Es,auditTrail:()=>mg,complianceSnapshot:()=>hg,policyEnforcer:()=>Aa,reactiveExplainPath:()=>La});ke();Qt();ie();xe();oe();oo();function Xl(t,e){return Ke("audit",t,e)}var fg=new Set(["data","error","complete","teardown"]),Ns=class extends q{entries;count;_log;_target;constructor(e,n){super(n.name??`${e.name}_audit`,n.graph),this._target=e,this._log=Ve([],{name:"entries",...n.maxSize!=null?{maxSize:n.maxSize}:{}}),this.entries=this._log.entries,this.add(this.entries,{name:"entries"}),this.count=O([this.entries],([u])=>u.length,{name:"count",describeKind:"derived",meta:Xl("count")}),this.add(this.count,{name:"count"}),this.addDisposer(se(this.count));let r=n.includeTypes!=null?new Set(n.includeTypes):fg,o=n.filter,s=0,i=e.observe({timeline:!0,structured:!0}),a=i.onEvent(u=>{if(u.type==="derived")return;let c=u.type;if(!r.has(c))return;let d=u.path??"",l={seq:s++,timestamp_ns:u.timestamp_ns??$(),wall_clock_ns:pe(),path:d,type:c},p=(d?Ca(e,d):void 0)?.lastMutation;p!=null&&(l.actor=p.actor),c==="data"&&(l.value=u.data),c==="error"&&(l.error=u.data);let m=d?yg(e,d):void 0;m!=null&&(l.annotation=m),!(o!=null&&!o(l))&&this._log.append(l)});this.addDisposer(()=>{a(),i.dispose()}),this.addDisposer(()=>this._log.disposeAllViews())}all(){return this.entries.cache??[]}byNode(e){return this.all().filter(n=>n.path===e)}byActor(e){return this.all().filter(n=>n.actor?.id===e)}byActorType(e){return this.all().filter(n=>n.actor?.type===e)}byTimeRange(e,n){return this.all().filter(r=>!(r.timestamp_ns<e||n!=null&&r.timestamp_ns>=n))}get target(){return this._target}};function mg(t,e={}){return new Ns(t,e)}var Es=class extends q{policies;violations;violationCount;_target;_mode;_currentGuard;constructor(e,n,r){super(r.name??`${e.name}_policy`,r.graph),this._target=e,this._mode=r.mode??"audit";let o=gg(n)?n:N(n,{name:"policies"});this.policies=o,this.add(this.policies,{name:"policies"}),this.violations=new nt("violations",{retainedLimit:r.violationsLimit??1e3}),this.mount("violations",this.violations),this.violationCount=O([this.violations.events],([c])=>c.length,{name:"violationCount",describeKind:"derived",meta:Xl("policy_violation_count")}),this.add(this.violationCount,{name:"violationCount"}),this.addDisposer(se(this.violationCount));let i=o.cache??[];this._currentGuard=fr(i);let a=o.subscribe(c=>{for(let d of c)d[0]===S&&(i=d[1]??[],this._currentGuard=fr(i))});this.addDisposer(a);let u=r.paths!=null?[...r.paths]:Ql(e);if(this._mode==="enforce"){let c=new Map,d=l=>{if(c.has(l))return;let f=Ca(e,l);if(!(f instanceof Ee))return;let p=(m,h)=>{let g=this._currentGuard(m,h);return g||this._publishViolation(m,h,l,"blocked"),g};c.set(l,f._pushGuard(p))};for(let l of u)d(l);if(r.paths==null){let l=kt(e,(f,p,m)=>{if(f.kind==="added")if(f.nodeKind==="node")d(`${m}${f.name}`);else{let h=p._mounts.get(f.name);if(!(h instanceof q))return;let g=`${m}${f.name}::`,y=Ql(h);for(let b of y)d(b===""?`${m}${f.name}`:`${g}${b}`)}else if(f.kind==="removed")if(f.nodeKind==="node"){let h=`${m}${f.name}`,g=c.get(h);g!=null&&(g(),c.delete(h))}else{let h=`${m}${f.name}`,g=`${h}::`;for(let[y,b]of c)(y===h||y.startsWith(g))&&(b(),c.delete(y))}});this.addDisposer(l)}else{let l=e.topology.subscribe(f=>{for(let p of f){if(p[0]!==S)continue;let m=p[1];if(m.kind!=="removed"||m.nodeKind!=="node")continue;let h=c.get(m.name);h!=null&&(h(),c.delete(m.name))}});this.addDisposer(l)}this.addDisposer(()=>{for(let l of c.values())l();c.clear()})}else{let c=e.observe({timeline:!0,structured:!0}),d=c.onEvent(l=>{if(l.type!=="data"&&l.type!=="error")return;let f=l.path??"";if(!f||r.paths!=null&&!r.paths.includes(f))return;let p=l.actor??Ca(e,f)?.lastMutation?.actor;if(p==null)return;let m="write";this._currentGuard(p,m)||this._publishViolation(p,m,f,"observed")});this.addDisposer(()=>{d(),c.dispose()})}}_publishViolation(e,n,r,o){this.violations.publish({timestamp_ns:$(),wall_clock_ns:pe(),path:r,actor:e,action:n,mode:this._mode,result:o})}all(){return this.violations.retained()}get mode(){return this._mode}get target(){return this._target}};function Aa(t,e,n={}){return new Es(t,e,n)}function La(t,e,n,r){return t.explain(e,n,{reactive:!0,...r})}function hg(t,e={}){let n={format_version:1,timestamp_ns:$(),wall_clock_ns:pe(),graph:t.snapshot()};if(e.actor!=null&&(n.actor=e.actor),e.audit!=null){let o=[...e.audit.all()];n.audit={count:o.length,entries:o}}if(e.policies!=null){let o=e.policies.policies.cache??[];n.policies={mode:e.policies.mode,rules:o,violations:[...e.policies.all()]}}let r=bg(n);return{...n,fingerprint:r}}function gg(t){return typeof t=="object"&&t!==null&&"subscribe"in t}function Ca(t,e){try{return t.node(e)}catch{return}}function yg(t,e){try{return t.annotation(e)}catch{return}}function Ql(t){let e=t.describe({detail:"minimal"});return Object.keys(e.nodes)}function bg(t){return Ot(JSON.stringify(vg(t)))}function vg(t){let e=new Set,n=r=>{if(r===void 0)return{__undefined:!0};if(r===null)return null;let o=typeof r;if(o==="bigint")return{__bigint:r.toString()};if(o!=="object")return r;let s=r;if(e.has(s))return{__circular:!0};e.add(s);try{if(Array.isArray(s))return s.map(n);if(s instanceof Date)return{__date:s.toISOString()};if(s instanceof RegExp)return{__regexp:{source:s.source,flags:s.flags}};if(s instanceof Map)return{__map:[...s.entries()].map(([u,c])=>[n(u),n(c)])};if(s instanceof Set)return{__set:[...s].map(n)};if(ArrayBuffer.isView(s)){let a=s,u=new Array(a.length);for(let c=0;c<a.length;c++)u[c]=a[c]??0;return{__typed_array:{ctor:s.constructor.name,data:u}}}let i={};for(let a of Object.keys(s).sort())i[a]=n(s[a]);return i}finally{e.delete(s)}};return n(t)}var Os={};he(Os,{demoShell:()=>Eg});Ne();oe();ke();xe();oe();function Tg(t){for(let e of t){let n=e.codePointAt(0);if(n>=19968&&n<=40959||n>=13312&&n<=19903||n>=12288&&n<=12351||n>=12352&&n<=12447||n>=12448&&n<=12543||n>=44032&&n<=55215||n>=65280&&n<=65519)return!0}return!1}var Zl=new Set(["\uFF0C","\uFF0E","\uFF01","\uFF1A","\uFF1B","\uFF1F","\u3001","\u3002","\u30FB","\uFF09","\u3015","\u3009","\u300B","\u300D","\u300F","\u3011"]),wg=new Set([".",",","!","?",":",";",")","]","}","%",'"',"\u201D","\u2019","\xBB","\u203A","\u2026"]);function kg(t){return t.replace(/[\t\n\r\f ]+/g," ").replace(/^ | $/g,"")}function xg(t){let e=new Intl.Segmenter(void 0,{granularity:"word"}),n=[];for(let r of e.segment(t)){let o=r.segment,s=r.isWordLike??!1,i=[],a=[],u=[],c="",d=null;for(let l of o){let f;l===" "?f="space":l==="\u200B"?f="zero-width-break":l==="\xAD"?f="soft-hyphen":l===`
118
- `?f="hard-break":f="text",d!==null&&f===d?c+=l:(d!==null&&(i.push(c),a.push(d==="text"&&s),u.push(d)),c=l,d=f)}d!==null&&(i.push(c),a.push(d==="text"&&s),u.push(d)),n.push({texts:i,isWordLike:a,kinds:u})}return n}function Mt(t,e,n,r,o){let s=kg(t);if(s.length===0)return[];let i=xg(s),a=new Intl.Segmenter(void 0,{granularity:"grapheme"}),u=[],c=[],d=[];for(let y of i)for(let b=0;b<y.texts.length;b++)u.push(y.texts[b]),c.push(y.kinds[b]),d.push(y.isWordLike[b]);let l=[],f=[],p=[];for(let y=0;y<u.length;y++){let b=u[y],v=c[y],T=d[y];if(v==="text"&&!T&&l.length>0&&f[f.length-1]==="text"&&b.length===1&&(wg.has(b)||Zl.has(b))){l[l.length-1]+=b;continue}if(b==="-"&&l.length>0&&f[f.length-1]==="text"&&p[p.length-1]){l[l.length-1]+=b;continue}l.push(b),f.push(v),p.push(T)}let m=r.get(e);m||(m=new Map,r.set(e,m));function h(y){let b=m.get(y);if(b===void 0){o&&(o.misses+=1);let v=n.measureSegment(y,e).width;b=Number.isFinite(v)&&v>=0?v:0,m.set(y,b)}else o&&(o.hits+=1);return b}let g=[];for(let y=0;y<l.length;y++){let b=l[y],v=f[y];if(v!=="text"){g.push({text:b,width:v==="space"?h(" ")*b.length:0,kind:v,graphemeWidths:null});continue}if(Tg(b)){let k="";for(let x of a.segment(b)){let R=x.segment;if(k.length>0&&Zl.has(R)){k+=R;continue}if(k.length>0){let E=h(k);g.push({text:k,width:E,kind:"text",graphemeWidths:null})}k=R}if(k.length>0){let x=h(k);g.push({text:k,width:x,kind:"text",graphemeWidths:null})}continue}let T=h(b),w=null;if(p[y]&&b.length>1){let k=[];for(let x of a.segment(b))k.push(h(x.segment));k.length>1&&(w=k)}g.push({text:b,width:T,kind:"text",graphemeWidths:w})}return g}function Tn(t,e,n,r,o){if(t.length===0)return{lines:[],lineCount:0};let s=[],i=0,a=!1,u=0,c=0,d=0,l=0,f=-1,p=0,m=o.get(r);m||(m=new Map,o.set(r,m));let h=m.get("-");h===void 0&&(h=n.measureSegment("-",r).width,m.set("-",h));function g(w=d,k=l,x=i){let R="";for(let E=u;E<w;E++){let G=t[E];if(!(G.kind==="soft-hyphen"||G.kind==="hard-break"))if(E===u&&c>0&&G.graphemeWidths){let P=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(G.text)].map(C=>C.segment);R+=P.slice(c).join("")}else R+=G.text}if(k>0&&w<t.length){let E=t[w],L=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(E.text)].map(C=>C.segment),P=u===w?c:0;R+=L.slice(P,k).join("")}w>0&&t[w-1]?.kind==="soft-hyphen"&&!(u===w&&c>0)&&(R+="-"),s.push({text:R,width:x,startSegment:u,startGrapheme:c,endSegment:w,endGrapheme:k}),i=0,a=!1,f=-1,p=0}function y(w){return w==="space"||w==="zero-width-break"||w==="soft-hyphen"}function b(w,k,x){a=!0,u=w,c=k,d=w+1,l=0,i=x}function v(w,k,x){a=!0,u=w,c=k,d=w,l=k+1,i=x}for(let w=0;w<t.length;w++){let k=t[w];if(k.kind==="hard-break"){a?g():s.push({text:"",width:0,startSegment:w,startGrapheme:0,endSegment:w,endGrapheme:0}),u=w+1,c=0;continue}let x=k.width;if(!a){x>e&&k.graphemeWidths?T(w,0,k.graphemeWidths):b(w,0,x),y(k.kind)&&(f=w+1,p=k.kind==="space"?i-x:i);continue}let R=i+x;if(R>e+.005){if(y(k.kind)){i+=x,d=w+1,l=0,g(w+1,0,k.kind==="space"?i-x:i);continue}if(f>=0){g(f,0,p),w--;continue}if(x>e&&k.graphemeWidths){g(),T(w,0,k.graphemeWidths);continue}g(),w--;continue}i=R,d=w+1,l=0,y(k.kind)&&(f=w+1,p=k.kind==="space"?i-x:i)}return a&&g(),{lines:s,lineCount:s.length};function T(w,k,x){for(let R=k;R<x.length;R++){let E=x[R];if(!a){v(w,R,E);continue}i+E>e+.005?(g(),v(w,R,E)):(i+=E,d=w,l=R+1)}a&&d===w&&l===x.length&&(d=w+1,l=0)}}function Ia(t){return t==="space"||t==="zero-width-break"||t==="soft-hyphen"}var Pa=null;function Rg(){return Pa===null&&(Pa=new Intl.Segmenter(void 0,{granularity:"grapheme"})),Pa}function ep(t,e,n){if(e===0&&n<0)return t.text;let r=[...Rg().segment(t.text)].map(s=>s.segment),o=n<0?r.length:n;return r.slice(e,o).join("")}function Vt(t,e,n,r,o,s){let i="";for(let a=e;a<r;a++){let u=t[a];u.kind==="soft-hyphen"||u.kind==="hard-break"||(a===e&&n>0?i+=ep(u,n,-1):i+=u.text)}if(o>0&&r<t.length){let a=t[r];i+=ep(a,e===r?n:0,o)}return s&&(i+="-"),i}function Sg(t){if(!t?.adapter||!t.font)return 0;let e=t.cache;if(e){let n=e.get(t.font);n||(n=new Map,e.set(t.font,n));let r=n.get("-");return r===void 0&&(r=t.adapter.measureSegment("-",t.font).width,n.set("-",r)),r}return t.adapter.measureSegment("-",t.font).width}function Da(t,e,n,r){let o=e.segmentIndex,s=e.graphemeIndex;if(o>=t.length)return null;if(s===0){for(;o<t.length;){let w=t[o];if(w.kind==="hard-break")return{text:"",width:0,start:{segmentIndex:e.segmentIndex,graphemeIndex:0},end:{segmentIndex:o+1,graphemeIndex:0}};if(w.kind==="space"||w.kind==="zero-width-break"||w.kind==="soft-hyphen"){o+=1;continue}break}if(o>=t.length)return null}let i=Sg(r),a=o,u=o===e.segmentIndex?s:0,c=0,d=a,l=0,f=!1,p=-1,m=0,h=0,g=!1,y=(w,k,x,R)=>{p=w,m=k,h=x,g=R==="soft-hyphen"},b=(w,k,x)=>{for(let R=k;R<x.length;R++){let E=x[R];if(!f){c=E,d=w,l=R+1,f=!0;continue}if(c+E>n+.005)return!0;c+=E,d=w,l=R+1}return d===w&&l===x.length&&(d=w+1,l=0),!1};if(u>0&&a<t.length){let w=t[a];if(w.graphemeWidths){if(b(a,u,w.graphemeWidths))return{text:Vt(t,a,u,d,l,!1),width:c,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}};o=d}}for(;o<t.length;){let w=t[o];if(w.kind==="hard-break"){if(f){let R=d>0&&t[d-1]?.kind==="soft-hyphen";return{text:Vt(t,a,u,d,l,R),width:c+(R?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}}return{text:"",width:0,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:o+1,graphemeIndex:0}}}let k=w.width;if(!f){if(k>n&&w.graphemeWidths){if(b(o,0,w.graphemeWidths))return{text:Vt(t,a,u,d,l,!1),width:c,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}};o=d;continue}c=k,d=o+1,l=0,f=!0,Ia(w.kind)&&y(o+1,0,w.kind==="space"?c-k:c,w.kind),o+=1;continue}let x=c+k;if(x>n+.005){if(Ia(w.kind)){d=o+1,l=0;let E=w.kind==="soft-hyphen",G=w.kind==="space"?c:c+(E?i:0);return{text:Vt(t,a,u,d,l,E),width:G,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}}return p>=0?{text:Vt(t,a,u,p,m,g),width:h+(g?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:p,graphemeIndex:m}}:k>n&&w.graphemeWidths?{text:Vt(t,a,u,d,l,!1),width:c,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}:{text:Vt(t,a,u,d,l,!1),width:c,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}}c=x,d=o+1,l=0,Ia(w.kind)&&y(o+1,0,w.kind==="space"?c-k:c,w.kind),o+=1}if(!f)return null;let v=d>0&&t[d-1]?.kind==="soft-hyphen";return{text:Vt(t,a,u,d,l,v),width:c+(v?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}}function Ga(t,e,n=0){let r=[t];for(let o=0;o<e.length;o++){let s=e[o],i=[];for(let a=0;a<r.length;a++){let u=r[a];if(s.right<=u.left||s.left>=u.right){i.push(u);continue}s.left>u.left&&i.push({left:u.left,right:s.left}),s.right<u.right&&i.push({left:s.right,right:u.right})}r=i}return n>0?r.filter(o=>o.right-o.left>=n):r}function Ms(t,e,n){let r=[],o=new Intl.Segmenter(void 0,{granularity:"grapheme"});for(let s=0;s<t.lines.length;s++){let i=t.lines[s],a=s*n,u=0;for(let c=i.startSegment;c<e.length;c++){let d=e[c];if(d.kind==="soft-hyphen"||d.kind==="hard-break"){if(c>=i.endSegment&&i.endGrapheme===0)break;continue}let l=[...o.segment(d.text)].map(m=>m.segment);if(l.length===0)continue;let f=c===i.startSegment?i.startGrapheme:0,p;if(c<i.endSegment)p=l.length;else if(c===i.endSegment&&i.endGrapheme>0)p=i.endGrapheme;else break;for(let m=f;m<p;m++){let h=d.graphemeWidths?d.graphemeWidths[m]:d.width/l.length;r.push({x:u,y:a,width:h,height:n,line:s}),u+=h}}}return r}function Ng(t){let{adapter:e,name:n="reactive-layout"}=t,r=new q(n),o=new Map,s=N(t.text??"",{name:"text"}),i=N(t.font??"16px sans-serif",{name:"font"}),a=N(t.lineHeight??20,{name:"line-height"}),u=N(Math.max(0,t.maxWidth??800),{name:"max-width"});function c(m,h){if(m===null||h===null)return m===h;if(m.length!==h.length)return!1;for(let g=0;g<m.length;g++)if(m[g]!==h[g])return!1;return!0}let d=K([s,i],(m,h,g)=>{let y=m[0],b=y!=null&&y.length>0?y.at(-1):g.prevData[0],v=m[1],T=v!=null&&v.length>0?v.at(-1):g.prevData[1],w=$(),k={hits:0,misses:0},x=Mt(b,T,e,o,k),R=$()-w,E=k.hits+k.misses,G=E===0?1:k.hits/E,L=d.meta;L&&(at(L["cache-hit-rate"],G),at(L["segment-count"],x.length),at(L["layout-time-ns"],R)),h.emit(x);let P=()=>{o.clear(),e.clearCache?.()};return{deactivate:P,invalidate:P}},{name:"segments",describeKind:"derived",meta:{"cache-hit-rate":0,"segment-count":0,"layout-time-ns":0},equals:(m,h)=>{let g=m,y=h;if(g==null||y==null)return g===y;if(g.length!==y.length)return!1;for(let b=0;b<g.length;b++){let v=g[b],T=y[b];if(v.text!==T.text||v.width!==T.width||v.kind!==T.kind||!c(v.graphemeWidths??null,T.graphemeWidths??null))return!1}return!0}}),l=O([d,u,i],([m,h,g])=>Tn(m,h,e,g,o),{name:"line-breaks",equals:(m,h)=>{let g=m,y=h;if(g==null||y==null)return g===y;if(g.lineCount!==y.lineCount)return!1;for(let b=0;b<g.lines.length;b++){let v=g.lines[b],T=y.lines[b];if(v.text!==T.text||v.width!==T.width||v.startSegment!==T.startSegment||v.startGrapheme!==T.startGrapheme||v.endSegment!==T.endSegment||v.endGrapheme!==T.endGrapheme)return!1}return!0}}),f=O([l,a],([m,h])=>m.lineCount*h,{name:"height"}),p=O([l,d,a],([m,h,g])=>Ms(m,h,g),{name:"char-positions",equals:(m,h)=>{let g=m,y=h;if(g==null||y==null)return g===y;if(g.length!==y.length)return!1;for(let b=0;b<g.length;b++)if(g[b].x!==y[b].x||g[b].y!==y[b].y||g[b].width!==y[b].width)return!1;return!0}});return r.add(s,{name:"text"}),r.add(i,{name:"font"}),r.add(a,{name:"line-height"}),r.add(u,{name:"max-width"}),r.add(d,{name:"segments"}),r.add(l,{name:"line-breaks"}),r.add(f,{name:"height"}),r.add(p,{name:"char-positions"}),{graph:r,setText:m=>r.set("text",m),setFont:m=>r.set("font",m),setLineHeight:m=>r.set("line-height",m),setMaxWidth:m=>r.set("max-width",Math.max(0,m)),segments:d,lineBreaks:l,height:f,charPositions:p}}function Wr(t){return Math.max(0,Math.min(1,t))}function Eg(t){let e=Wr(t?.mainRatio??.65),n=Wr(t?.sideSplit??.5),r=Math.max(0,t?.viewportWidth??1280),o=t?.nodeRegistry??new Map,s=t?.adapter??null,i=t?.layoutFont??"14px monospace",a=t?.onHighlight,u=new q("demo-shell"),c=N(e,{name:"pane/main-ratio"}),d=N(n,{name:"pane/side-split"}),l=N(null,{name:"pane/fullscreen"}),f=N(r,{name:"viewport/width"});u.add(c,{name:"pane/main-ratio"}),u.add(d,{name:"pane/side-split"}),u.add(l,{name:"pane/fullscreen"}),u.add(f,{name:"viewport/width"});let p=O([c,f,l],([A,D,I])=>{let Q=A,U=D,ae=I;return ae==="main"?U:ae==="graph"||ae==="code"?0:Math.round(U*Q)},{name:"pane/main-width"}),m=O([p,f,l],([A,D,I])=>{let Q=I,U=D;return Q==="main"?0:Q==="graph"||Q==="code"?U:U-A},{name:"pane/side-width"}),h=O([d,l],([A,D])=>{let I=D;return I==="graph"?1:I==="code"||I==="main"?0:Wr(A)},{name:"pane/graph-height-ratio"}),g=O([h,l],([A,D])=>{let I=D;return I==="code"?1:I==="graph"||I==="main"?0:1-A},{name:"pane/code-height-ratio"});u.add(p,{name:"pane/main-width"}),u.add(m,{name:"pane/side-width"}),u.add(h,{name:"pane/graph-height-ratio"}),u.add(g,{name:"pane/code-height-ratio"});let y=N(null,{name:"demo/graph-ref"}),b=N(0,{name:"demo/graph-tick"});u.add(y,{name:"demo/graph-ref"}),u.add(b,{name:"demo/graph-tick"});let v=O([y,b],([A,D])=>{let I=A;return I?I.describe({format:"mermaid"}):""},{name:"graph/mermaid"}),T=O([y,b],([A,D])=>{let I=A;if(!I)return null;let{expand:Q,...U}=I.describe({detail:"standard"});return U},{name:"graph/describe"});u.add(v,{name:"graph/mermaid"}),u.add(T,{name:"graph/describe"});let w=N(null,{name:"hover/target"});u.add(w,{name:"hover/target"});let k=O([w],([A])=>{let D=A;if(!D)return null;let I=o.get(D.id);return I?I.codeLine:null},{name:"highlight/code-scroll"}),x=O([w],([A])=>{let D=A;if(!D)return null;let I=o.get(D.id);return I?I.visualSelector:null},{name:"highlight/visual"}),R=O([w],([A])=>{let D=A;return D?D.id:null},{name:"highlight/graph"});if(u.add(k,{name:"highlight/code-scroll"}),u.add(x,{name:"highlight/visual"}),u.add(R,{name:"highlight/graph"}),a?.codeScroll){let A=a.codeScroll,D=fe([k],([I])=>{A(I)});u.add(D,{name:"highlight/apply-code-scroll"})}if(a?.visual){let A=a.visual,D=fe([x],([I])=>{A(I)});u.add(D,{name:"highlight/apply-visual"})}if(a?.graph){let A=a.graph,D=fe([R],([I])=>{A(I)});u.add(D,{name:"highlight/apply-graph"})}let E=N(null,{name:"inspect/selected-node"});u.add(E,{name:"inspect/selected-node"});let G=wt("standard"),L=O([E,y,b],([A,D,I])=>{let Q=D,U=A;if(!Q||!U)return null;try{let ae=Q.resolve(U),j=wr(ae,G);return{path:U,...j,value:ae.cache}}catch{return null}},{name:"inspect/node-detail"}),P=O([y,b],([A,D])=>{let I=A;return I?I.trace():[]},{name:"inspect/trace-log"});u.add(L,{name:"inspect/node-detail"}),u.add(P,{name:"inspect/trace-log"});let C=N(!1,{name:"meta/debug"});u.add(C,{name:"meta/debug"});let V=O([C,b],([A,D])=>A?u.describe({format:"mermaid"}):"",{name:"meta/shell-mermaid"});u.add(V,{name:"meta/shell-mermaid"});let ne=N("",{name:"layout/code-text"});if(u.add(ne,{name:"layout/code-text"}),s){let A=new Map,D=O([T],([U])=>{let ae=U;if(!ae)return new Map;let j=new Map;for(let[Y]of Object.entries(ae.nodes)){let J=Mt(Y,i,s,A),z=Tn(J,1/0,s,i,A),X=z.lines.reduce((le,ve)=>Math.max(le,ve.width),0),H=z.lineCount*20;j.set(Y,{width:X,height:H})}return j},{name:"layout/graph-labels",equals:(U,ae)=>{if(U===ae)return!0;let j=U,Y=ae;if(j.size!==Y.size)return!1;for(let[J,z]of j){let X=Y.get(J);if(!X||X.width!==z.width||X.height!==z.height)return!1}return!0}}),I=O([ne,m],([U,ae])=>{let j=U;if(!j)return{lineCount:0,lines:[]};let Y=Mt(j,i,s,A),J=ae-40;return Tn(Y,Math.max(100,J),s,i,A)},{name:"layout/code-lines"}),Q=O([D],([U])=>{let ae=U;if(ae.size===0)return 200;let j=0;for(let{width:Y}of ae.values())Y>j&&(j=Y);return Math.max(200,Math.round(j+80))},{name:"layout/side-width-hint"});u.add(D,{name:"layout/graph-labels"}),u.add(I,{name:"layout/code-lines"}),u.add(Q,{name:"layout/side-width-hint"})}let F=0;return{graph:u,setMainRatio(A){u.set("pane/main-ratio",Wr(A))},setSideSplit(A){u.set("pane/side-split",Wr(A))},setFullscreen(A){u.set("pane/fullscreen",A)},setViewportWidth(A){u.set("viewport/width",Math.max(0,A))},setHoverTarget(A){u.set("hover/target",A)},setDemoGraph(A){u.set("demo/graph-ref",A)},bumpGraphTick(){u.set("demo/graph-tick",++F)},selectNode(A){u.set("inspect/selected-node",A)},setMetaDebug(A){u.set("meta/debug",A)},setCodeText(A){u.set("layout/code-text",A)},batch(A){te(A)},destroy(){u.destroy()}}}var Ls={};he(Ls,{contentModerationGraph:()=>Ag,dataQualityGraph:()=>Lg,issueTrackerGraph:()=>Cg,observabilityGraph:()=>Og});Ne();oe();var As={};he(As,{budgetGate:()=>Fa,effectivenessTracker:()=>Mg,feedback:()=>Kt,funnel:()=>_g,scorer:()=>qr});Ne();ie();xe();oe();function Cs(t,e){return Ke("reduction",t,e)}function _g(t,e,n,r){if(e.length===0)throw new RangeError("funnel requires at least one source");if(n.length===0)throw new RangeError("funnel requires at least one stage");let o=new q(t,r),s=e.length===1?e[0]:mt(...e);o.add(s,{name:"merged"});let i="merged";for(let a=0;a<n.length;a++){let u=n[a],c=new q(u.name);u.build(c);try{c.resolve("input")}catch{throw new Error(`funnel stage "${u.name}" must define an "input" node`)}try{c.resolve("output")}catch{throw new Error(`funnel stage "${u.name}" must define an "output" node`)}o.mount(u.name,c);let d=o.resolve(i),l=`${u.name}::input`,f=o.resolve(l),p=`__bridge_${i}\u2192${u.name}_input`,m=fe([d],([h])=>{f.emit(h)},{name:p});o.add(m,{name:p}),o.addDisposer(se(m)),i=`${u.name}::output`}return o}function Kt(t,e,n,r){let o=r?.maxIterations??10,s=`__feedback_${e}`,i=N(0,{meta:Cs("feedback_counter",{maxIterations:o,feedbackFrom:e,feedbackTo:n})});t.add(i,{name:s});let a=t.resolve(e),u=t.resolve(n),c=`__feedback_effect_${e}`,d=K([],(l,f)=>{let p=a.subscribe(m=>{for(let h of m){let g=h[0];if(g===S){let y=h[1];if(y==null)return;te(()=>{Sr(i,o)&&u.emit(y)})}else if(g===_||g===M){let y=g===M&&h.length>1?[M,h[1]]:[g];i.down([y])}}});return()=>p()},{name:c,describeKind:"effect",meta:{...Cs("feedback_effect",{feedbackFrom:e,feedbackTo:n}),_internal:!0}});return t.add(d,{name:c}),t.addDisposer(se(d)),t}function Fa(t,e,n){if(e.length===0)throw new RangeError("budgetGate requires at least one constraint");let r=e.map(p=>p.node),o=[t,...r],s=[],i=!1,a=!1,u=Symbol("budget-gate"),c=new Array(e.length);function d(){return e.every((p,m)=>p.check(c[m]))}function l(p){for(;s.length>0&&d();){let m=s[0];s=s.slice(1),p.emit(m)}s.length===0&&a&&(a=!1,p.down([[B]]))}return K([],(p,m)=>{for(let g=0;g<e.length;g++)c[g]=e[g].node.cache;let h=[];for(let g=0;g<o.length;g++){let y=o[g];h.push(y.subscribe(b=>{for(let v of b)f(v,g,m)}))}return()=>{for(let g of h)g()}},{...n,describeKind:"derived",meta:Cs("budget_gate",n?.meta)});function f(p,m,h){let g=p[0];if(m===0){if(g===S)return d()&&s.length===0?h.emit(p[1]):(s.push(p[1]),i||(i=!0,h.up([[Ie,u]]))),!0;if(g===ee)return h.down([[ee]]),!0;if(g===B)return s.length===0?h.down([[B]]):a=!0,!0;if(g===_||g===M){for(let y of s)h.emit(y);return s=[],a=!1,i&&(i=!1,h.up([[Ge,u]])),h.down([p]),!0}return!1}return g===S&&(c[m-1]=p[1]),g===S||g===B?(d()&&s.length>0?(l(h),s.length===0&&i&&(i=!1,h.up([[Ge,u]]))):!d()&&!i&&s.length>0&&(i=!0,h.up([[Ie,u]])),!0):g===ee?!0:g===M?(h.down([p]),!0):g===_}}function qr(t,e,n){if(t.length===0)throw new RangeError("scorer requires at least one source");if(t.length!==e.length)throw new RangeError("scorer requires the same number of sources and weights");let r=[...t,...e],o=t.length,s=n?.scoreFns;return O(r,i=>{let a=i.slice(0,o),u=i.slice(o),c=[],d=0;for(let l=0;l<o;l++){let f=a[l]??0,p=u[l]??0,h=(s?.[l]?s[l](f):f)*p;c.push(h),d+=h}return{value:a,score:d,breakdown:c}},{...n?{equals:n.equals,resubscribable:n.resubscribable,resetOnTeardown:n.resetOnTeardown}:{},describeKind:"derived",meta:Cs("scorer",n?.meta)})}function Mg(t){let e=tt({name:t?.name??"effectiveness-entries"}),n=O([e.entries],([i])=>new Map(i),{name:`${t?.name??"effectiveness"}-snapshot`,equals:(i,a)=>{let u=i,c=a;if(u.size!==c.size)return!1;for(let[d,l]of u){let f=c.get(d);if(!f||l.attempts!==f.attempts||l.successes!==f.successes)return!1}return!0}});function r(i,a){let u=e.get(i),c=(u?.attempts??0)+1,d=(u?.successes??0)+(a?1:0);e.set(i,{key:i,attempts:c,successes:d,successRate:d/c})}function o(i){return e.get(i)}let s=se(n);return{node:n,record:r,lookup:o,dispose:()=>s()}}function Me(t,e){return Ke("domain_template",t,e)}function Og(t,e){let n=new q(t,e);n.add(e.source,{name:"source"});let r=[{name:"errors",classify:T=>$a(T,"error")},{name:"traces",classify:T=>$a(T,"trace")},{name:"metrics",classify:T=>$a(T,"metric")}],o=e.branches??r,s=o.map(T=>({name:T.name,classify:T.classify})),i=Fr("stratify",e.source,s);n.mount("stratify",i);let a=o.map(T=>{try{let w=n.resolve(`stratify::branch/${T.name}`);return O([w],([k])=>k,{initial:null})}catch{return N(null)}}),u=e.correlate??(T=>T),c=O(a,T=>u(T),{meta:Me("observability",{stage:"correlate"})});n.add(c,{name:"correlate"});let d=e.sloCheck??(()=>({pass:!0})),l=O([c],T=>T[0],{meta:Me("observability",{stage:"slo_value"})}),f=O([l],T=>d(T[0]),{meta:Me("observability",{stage:"slo_verified"})});n.add(l,{name:"slo_value"}),n.add(f,{name:"slo_verified"});let p=e.weights??o.map(()=>1),m=a.map(T=>O([T],w=>w[0]!=null?1:0)),h=p.map(T=>N(T));for(let T=0;T<m.length;T++)n.add(m[T],{name:`__signal_${T}`}),n.add(h[T],{name:`__weight_${T}`});let g=qr(m,h);n.add(g,{name:"alerts"});let y=O([g,f],T=>({scored:T[0],slo:T[1]}),{meta:Me("observability",{stage:"output"})});n.add(y,{name:"output"});let b=N(null,{meta:Me("observability",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=O([f],T=>{let w=T[0];return w&&w.pass===!1?w:null},{meta:Me("observability",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),Kt(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??5}),n}function Cg(t,e){let n=new q(t,e);n.add(e.source,{name:"source"});let r=0,o=T=>({id:`issue-${++r}`,title:String(T),severity:1,source:"unknown",raw:T}),s=e.extract??o,i=O([e.source],T=>s(T[0]),{meta:Me("issue_tracker",{stage:"extract"})});n.add(i,{name:"extract"});let a=e.verify??(()=>({valid:!0})),u=O([i],T=>{let w=T[0];return{issue:w,verification:a(w)}},{meta:Me("issue_tracker",{stage:"verify"})});n.add(u,{name:"verify"});let c=N([],{meta:Me("issue_tracker",{stage:"known_patterns"})});n.add(c,{name:"known_patterns"});let d=e.detectRegression??(()=>({regression:!1})),l=O([i,c],T=>{let w=T[0],k=T[1];return{issue:w,regression:d(w,k)}},{meta:Me("issue_tracker",{stage:"regression"})});n.add(l,{name:"regression"});let f=O([i],T=>T[0]?.severity??0),p=O([l],T=>T[0]?.regression?2:0);n.add(f,{name:"__severity_signal"}),n.add(p,{name:"__regression_signal"});let m=N(1),h=N(1.5);n.add(m,{name:"__severity_weight"}),n.add(h,{name:"__regression_weight"});let g=qr([f,p],[m,h]);n.add(g,{name:"priority"});let y=O([u,l,g],T=>({verified:T[0],regression:T[1],priority:T[2]}),{meta:Me("issue_tracker",{stage:"output"})});n.add(y,{name:"output"});let b=N(null,{meta:Me("issue_tracker",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=O([u],T=>{let w=T[0];if(w){let k=w.verification;if(k&&k.valid===!1)return w}return null},{meta:Me("issue_tracker",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),Kt(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??3}),n}function Ag(t,e){let n=new q(t,e);n.add(e.source,{name:"source"});let r=v=>({label:"review",confidence:.5,original:v}),o=e.classify??r,s=O([e.source],v=>o(v[0]),{meta:Me("content_moderation",{stage:"classify"})});n.add(s,{name:"classify"});let i=Fr("stratify",s,[{name:"safe",classify:v=>v.label==="safe"},{name:"review",classify:v=>v.label==="review"},{name:"block",classify:v=>v.label==="block"}]);n.mount("stratify",i);let a=Ve([],{name:"review_queue",maxSize:e.maxQueueSize});n.add(a.entries,{name:"review_queue"});let u;try{u=n.resolve("stratify::branch/review")}catch{u=N(null),n.add(u,{name:"__review_fallback"})}let c=fe([u],v=>{let T=v[0];T&&a.append(T)});n.add(c,{name:"__review_accumulator"}),n.addDisposer(se(c));let d=N({},{meta:Me("content_moderation",{stage:"policy",access:"both",description:"Moderation policy rules \u2014 updated via feedback"})});n.add(d,{name:"policy"});let l=e.weights??[.1,1,2],f=O([s],v=>v[0]?.confidence??0),p=O([s],v=>{let T=v[0];return T?T.label==="block"?l[2]:T.label==="review"?l[1]:l[0]:0});n.add(f,{name:"__confidence_signal"}),n.add(p,{name:"__severity_signal"});let m=N(1),h=N(1);n.add(m,{name:"__w_confidence"}),n.add(h,{name:"__w_severity"});let g=qr([f,p],[m,h]);n.add(g,{name:"priority"});let y=O([s,g],v=>({classification:v[0],priority:v[1]}),{meta:Me("content_moderation",{stage:"output"})});n.add(y,{name:"output"});let b=O([a.entries,d],v=>{let T=v[0];if(T&&T.length>0){let w=T[T.length-1];if(w&&w.falsePositive)return w}return null},{meta:Me("content_moderation",{stage:"feedback_condition"})});return n.add(b,{name:"feedback_condition"}),Kt(n,"feedback_condition","policy",{maxIterations:e.maxFeedbackIterations??5}),n}function Lg(t,e){let n=new q(t,e);n.add(e.source,{name:"source"});let r=e.validate??(g=>({valid:!0,errors:[],record:g})),o=O([e.source],g=>g[0]!=null?r(g[0]):void 0,{meta:Me("data_quality",{stage:"validate"})});n.add(o,{name:"validate"});let s=e.detectAnomaly??(g=>({anomaly:!1,score:0,record:g})),i=O([e.source],g=>g[0]!=null?s(g[0]):void 0,{meta:Me("data_quality",{stage:"anomaly"})});n.add(i,{name:"anomaly"});let a=N(null,{meta:Me("data_quality",{stage:"baseline",description:"Rolling baseline for drift detection"})});n.add(a,{name:"baseline"});let u=fe([o],g=>{let y=g[0];y?.valid&&te(()=>{a.emit(y.record)})});n.add(u,{name:"__baseline_updater"}),se(u);let c=e.detectDrift??(()=>({drift:!1})),d=O([e.source,a],g=>c(g[0],g[1]),{meta:Me("data_quality",{stage:"drift"})});n.add(d,{name:"drift"});let l=e.suggest??(()=>null),f=O([o,i],g=>l({validation:g[0],anomaly:g[1]}),{meta:Me("data_quality",{stage:"remediate"})});n.add(f,{name:"remediate"});let p=O([o,i,d,f],g=>({validation:g[0],anomaly:g[1],drift:g[2],remediation:g[3]}),{meta:Me("data_quality",{stage:"output"})});n.add(p,{name:"output"});let m=N([],{meta:Me("data_quality",{stage:"validation_rules"})});n.add(m,{name:"validation_rules"});let h=O([i],g=>{let y=g[0];return y?.anomaly?y:null},{meta:Me("data_quality",{stage:"feedback_condition"})});return n.add(h,{name:"feedback_condition"}),Kt(n,"feedback_condition","validation_rules",{maxIterations:e.maxFeedbackIterations??3}),n}function $a(t,e){if(t==null||typeof t!="object")return!1;let n=t;return n.type===e||n.kind===e}var Is={};he(Is,{compileSpec:()=>Va,decompileGraph:()=>$g,extractFnFactory:()=>np,extractSourceFactory:()=>rp,generateCatalogPrompt:()=>op,isRichFnEntry:()=>Ur,isRichSourceEntry:()=>ja,llmCompose:()=>jg,llmRefine:()=>ap,specDiff:()=>Bg,validateSpec:()=>Xn,validateSpecAgainstCatalog:()=>zr});oe();function Ur(t){return typeof t=="object"&&t!==null&&"factory"in t}function ja(t){return typeof t=="object"&&t!==null&&"factory"in t}function np(t){return Ur(t)?t.factory:t}function rp(t){return ja(t)?t.factory:t}function op(t){let e=[];if(t.fns){let n=new Map;for(let[r,o]of Object.entries(t.fns)){let s=Ur(o)?o.tags?.[0]??"Other":"Other";n.has(s)||n.set(s,[]),n.get(s).push(Ig(r,o))}for(let[r,o]of n)e.push(`${r}:
38
+ `,r=t.map(i=>typeof i=="string"?N(i):z(i)),o=E(r,i=>i.filter(a=>a!=null&&a!=="").join(n),{name:e?.name??"systemPrompt",describeKind:"derived",meta:ge("system_prompt"),initial:""}),s=re(o);return Object.assign(o,{dispose:s})}ne();var Yh=(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 E([t.latest],([o],s)=>{if(o==null)return r;let i=o;"chunkCount"in s.store||(s.store.chunkCount=0,s.store.charCount=0,s.store.usageTokens=0,s.store.sawUsage=!1);let a=s.store;i.type==="token"?(a.chunkCount+=1,a.charCount+=i.delta.length):i.type==="usage"&&(a.sawUsage=!0,a.usageTokens=gt(i.usage)+Lt(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:ge("cost_meter_extractor"),equals:Yh})}ne();var Xh=(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 Zh(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 E([t],([o],s)=>{if(o==null)return[];let i=o;"flags"in s.store||(s.store.flags=[],s.store.scannedTo=0);let a=s.store.flags,u=s.store.scannedTo,c=Math.max(0,u-n),d=i.slice(c),l=!1;for(let{pattern:f,label:p,compiled:m}of r){m.lastIndex=0;for(let h of d.matchAll(m)){let g=c+(h.index??0);g+h[0].length<=u||(a.push({label:p,pattern:f,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:ge("keyword_flag_extractor"),equals:Xh})}ne();function eg(t,e,n){return E([t],([r])=>r==null?null:e(r),{name:n?.name??"extractor",describeKind:"derived",initial:null,meta:ge("stream_extractor"),...n?.equals?{equals:n.equals}:{}})}ne();var tg=(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 ng(t,e){return E([t],([n],r)=>{if(n==null)return[];let o=n;"calls"in r.store||(r.store.calls=[],r.store.scanFrom=0);let s=r.store.calls,i=r.store.scanFrom,a=!1;for(;i<o.length;){let u=o.indexOf("{",i);if(u===-1){r.store.scanFrom=o.length;break}let c=0,d=-1,l=!1;for(let p=u;p<o.length;p++){let m=o[p];if(l)m==="\\"&&p+1<o.length?p++:m==='"'&&(l=!1);else if(m==='"')l=!0;else if(m==="{")c++;else if(m==="}"&&(c--,c===0)){d=p;break}}if(d===-1){r.store.scanFrom=u;break}let f=o.slice(u,d+1);try{let p=JSON.parse(f);typeof p.name=="string"&&p.arguments!=null&&typeof p.arguments=="object"&&(s.push({name:p.name,arguments:p.arguments,raw:f,startIndex:u}),a=!0)}catch{}i=d+1,r.store.scanFrom=i}return a?[...s]:s.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:ge("tool_call_extractor"),equals:tg})}ne();function rg(t,e,n,r){let o=n*(r?.hardMultiplier??1.5),s=typeof e!="function",i=[t];return s&&i.push(e),E(i,a=>{let u=a[0]??"";if(u.length===0)return"allow";let c=s?a[1]??0:e(u);return c>=o?"block":c>=n?"review":"allow"},{name:r?.name??"content-gate",initial:"allow"})}ne();function og(t,e,n,r){let o=n??(()=>"[REDACTED]");function s(i){let a=i;for(let u of e){let c=u.global?u:new RegExp(u.source,`${u.flags}g`);a=a.replace(c,d=>o(d,u))}return a}return E([t],([i])=>s(i??""),{name:r?.name??"redactor",initial:""})}_e();ie();Ne();ne();Et();ve();ne();var Ds=class extends q{_log;messages;latest;messageCount;constructor(e,n={}){super(e,n.graph),this._log=We([],{name:"messages",maxSize:n.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=E([this.messages],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:ge("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(re(this.latest)),this.messageCount=E([this.messages],([r])=>r.length,{name:"messageCount",describeKind:"derived",meta:ge("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 Fa(t,e){return new Ds(t,e)}ne();ve();var Gs=class extends q{definitions;schemas;_bundle;constructor(e,n={}){super(e,n.graph),this._bundle=Qe({name:"definitions"}),this.definitions=this._bundle.entries,this.add(this.definitions,{name:"definitions"}),this.schemas=E([this.definitions],([r])=>[...(r??new Map).values()],{name:"schemas",describeKind:"derived",meta:ge("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)}async execute(e,n){let r=this._bundle.get(e);if(!r)throw new Error(`toolRegistry: unknown tool "${e}"`);let o=r.handler(n);return kn(o)}executeReactive(e,n){let r=this._bundle.get(e);if(!r)throw new Error(`toolRegistry: unknown tool "${e}"`);return z(r.handler(n))}getDefinition(e){return this._bundle.entries.cache?.get(e)}};function $a(t,e){return new Gs(t,e)}var Fs=class extends q{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;turnCount;_terminalResult;_disposeRunWiring;_runVersion=0;_running=!1;_currentAbortController=null;constructor(e,n){if(super(e,n.graph),this.chat=Fa(`${e}-chat`,{maxMessages:n.maxMessages}),this.mount("chat",this.chat),this.tools=$a(`${e}-tools`),this.mount("tools",this.tools),n.tools)for(let F of n.tools)this.tools.register(F);this.status=N("idle",{name:"status",describeKind:"state",meta:ge("agent_status")}),this.add(this.status,{name:"status"}),this.turn=N(0,{name:"turn",describeKind:"state",meta:ge("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.turnCount=this.turn,this.aborted=N(!1,{name:"aborted",describeKind:"state",meta:ge("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let r=0,o=this.turn.subscribe(F=>{for(let A of F)A[0]===S&&(r=A[1])}),s=!1,i=this.aborted.subscribe(F=>{for(let A of F)A[0]===S&&(s=A[1])}),a=n.adapter,u=n.systemPrompt,c=n.model,d=n.temperature,l=n.maxTokens,f=n.maxTurns??10,p=n.stopWhen,m=this.chat,h=this.tools,g=this.status,y=this.turn,b=this.aborted,v=K([g],(F,A,D)=>{if(eo(F,D.prevData,0,"idle")!=="thinking"||s||r>=f){A.down([[$]]);return}let J=m.allMessages();if(J.length===0){A.down([[$]]);return}let H=h.schemas.cache??[];A.emit({messages:J,tools:H})},{name:"promptInput",describeKind:"derived",meta:ge("agent_prompt_input")}),T=Te(v,F=>{let A=new AbortController;return this._currentAbortController=A,s&&A.abort(new Error("agentLoop: aborted")),z(Promise.resolve(a.invoke(F.messages,{tools:F.tools.length>0?F.tools:void 0,systemPrompt:u,model:c,temperature:d,maxTokens:l,signal:A.signal})),{signal:A.signal})},{equals:()=>!1}),w=N(null,{name:"lastResponse",describeKind:"state",meta:ge("agent_last_response")});this.lastResponse=w;let k=K([w,g],(F,A,D)=>{let I=eo(F,D.prevData,0,null);if(eo(F,D.prevData,1,"idle")!=="acting"){A.down([[$]]);return}let H=I?.toolCalls;if(H==null||H.length===0){A.down([[$]]);return}A.emit(H)},{name:"toolCalls",describeKind:"derived",meta:ge("agent_tool_calls")}),x=n.interceptToolCalls?n.interceptToolCalls(k):k;this.toolCalls=x;let R=(F,A)=>{if(F===A)return!0;if(F.length!==A.length)return!1;for(let D=0;D<F.length;D++){let I=F[D],J=A[D];if(I?.id!==J?.id||I?.content!==J?.content)return!1}return!0},_=Te(x,F=>{if(F==null||F.length===0)throw new Error("agentLoop: toolResultsNode received an empty tool-call batch as DATA \u2014 toolCallsNode gating invariant broken (should emit RESOLVED for empty). Audit toolCallsNode.");let A=F.map(D=>sg(D,h));return E(A,D=>D.map((I,J)=>{let H=I;return H!=null&&typeof H=="object"&&"id"in H&&"content"in H?H:{id:F[J].id,content:JSON.stringify(I??null)}}),{name:"toolResults_batch",equals:R})});this.toolResults=_;let G=me([T],([F])=>{if(s)return;let A=F,D=r+1,I=A.toolCalls!=null&&A.toolCalls.length>0,J=A.finishReason==="end_turn"&&(!A.toolCalls||A.toolCalls.length===0),H=p?.(A)===!0,ae=D>=f,j=H||J||!I||ae?"done":"acting";X(()=>{w.emit(A),g.emit(j),y.emit(D),m.append("assistant",A.content,{toolCalls:A.toolCalls})})}),L=me([_],([F])=>{if(s)return;let A=F;if(A.length===0)return;let D=r>=f?"done":"thinking";X(()=>{g.emit(D);for(let I of A)m.appendToolResult(I.id,I.content)})}),P=me([b],([F])=>{F===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),g.emit("done"))}),C=re(G),B=re(L),te=re(P);this._terminalResult=K([g,w],(F,A,D)=>{let I=eo(F,D.prevData,0,"idle"),J=eo(F,D.prevData,1,null);if(I==="done"){if(J!=null){A.emit({response:J,runVersion:this._runVersion});return}let H=new Error("agentLoop: aborted");H.name="AbortError",A.down([[O,H]]);return}if(I==="error"){A.down([[O,new Error("agentLoop: errored")]]);return}A.down([[$]])},{name:"terminalResult",describeKind:"derived",meta:ge("agent_terminal_result")}),this.addDisposer(o),this.addDisposer(i),this.addDisposer(C),this.addDisposer(B),this.addDisposer(te),this._disposeRunWiring=()=>{}}async run(e,n){if(this._running)throw new RangeError(`agentLoop "${this.name}": run() called while a previous run() is still pending \u2014 await the previous run before starting another, or call abort() first`);this._running=!0;let r=++this._runVersion;X(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle")}),e!=null&&this.chat.append("user",e),this.status.emit("thinking");let o;if(n!=null)if(n.aborted)this.aborted.emit(!0);else{let s=()=>this.aborted.emit(!0);n.addEventListener("abort",s,{once:!0}),o=()=>n.removeEventListener("abort",s)}try{return(await $o(this._terminalResult,{predicate:i=>i!=null&&typeof i=="object"&&i.runVersion===r})).response}finally{o?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function sg(t,e){let n=Ft(()=>z(Promise.resolve().then(()=>e.execute(t.name,t.arguments))),{count:1}),r=E([n],([o])=>({id:t.id,content:typeof o=="string"?o:JSON.stringify(o)}));return Dr(r,o=>({id:t.id,content:JSON.stringify({error:String(o)})}))}function eo(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 ig(t,e){return new Fs(t,e)}ne();ve();function ag(t,e,n){let r=z(t),o=n?.condition!=null?z(n.condition):null,s=N(null,{name:n?.name?`${n.name}::null`:"handoff::null"});if(o==null)return Te(r,a=>{if(a==null)return s;let u=N(a);return e(u)});let i=E([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 N(a);let c=N(a);return e(c)})}ne();ve();function ug(t,e,n){let r=z(t),o=e.map(i=>z(i)),s=[r,...o];return E(s,i=>{let a=i[0]??[],u=i.slice(1);return a.filter(c=>{for(let d of u)if(d!=null&&!d(c))return!1;return!0})},{name:n?.name??"tool-selector",describeKind:"derived",meta:ge("tool_selector"),equals:(i,a)=>{let u=i,c=a;if(u.length!==c.length)return!1;for(let d=0;d<u.length;d++)if(u[d]!==c[d])return!1;return!0}})}function cg(t){return{persistence:.5,structure:.5,personalValue:.5}}function dg(t={}){let e=t.scoreFn??cg,n=t.persistenceThreshold??.3,r=t.personalValueThreshold??.3,o=t.requireStructured??!1;return s=>{let i=e(s);return!(i.persistence<n||i.personalValue<r||o&&i.structure<=0)}}_e();we();ne();ve();var Bs={};ye(Bs,{collection:()=>pg,decay:()=>Rn,knowledgeGraph:()=>Va,lightCollection:()=>Ba,vectorIndex:()=>ja});we();ne();function Rn(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 op(t){if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1")}function xt(t){return new Map(t)}function tt(t){return t.cache??new Map}function $s(t){return t.cache??[]}function lg(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 Ba(t={}){let e=t.maxSize,n=t.policy??"fifo";op(e);let r=N(new Map,{name:t.name,describeKind:"state"});function o(i){if(e!==void 0)for(;i.size>e;){let a;for(let u of i.values()){if(!a){a=u;continue}let c=n==="lru"?u.lastAccessNs:u.createdAtNs,d=n==="lru"?a.lastAccessNs:a.createdAtNs;c<d&&(a=u)}if(!a)break;i.delete(a.id)}}function s(i){r.emit(i)}return{entries:r,upsert(i,a){let u=V(),c=tt(r),d=c.get(i),l=xt(c);l.set(i,{id:i,value:a,createdAtNs:d?.createdAtNs??u,lastAccessNs:u}),o(l),s(l)},remove(i){let a=xt(tt(r));a.delete(i)&&s(a)},clear(){tt(r).size!==0&&s(new Map)},get(i){let a=tt(r),u=a.get(i);if(u){if(n==="lru"){let c=V(),d=xt(a);d.set(i,{...u,lastAccessNs:c}),s(d)}return u.value}},has(i){return tt(r).has(i)}}}function pg(t,e={}){let n=e.maxSize,r=e.policy??"lru",o=e.decayRate??0,s=e.minScore??0,i=e.score??(()=>1);op(n);let a=new q(t),u=N(new Map,{name:"items",describeKind:"state"}),c=E([u],([h])=>{let g=h??new Map,y=V(),b=[...g.values()].map(v=>{let T=(y-v.lastAccessNs)/1e9;return{...v,score:Rn(v.baseScore,T,o,s)}});return b.sort((v,T)=>T.score-v.score||T.lastAccessNs-v.lastAccessNs),b},{name:"ranked",describeKind:"derived"}),d=E([u],([h])=>(h??new Map).size,{name:"size",describeKind:"derived",initial:0});c.subscribe(()=>{}),d.subscribe(()=>{}),a.add(u,{name:"items"}),a.add(c,{name:"ranked"}),a.add(d,{name:"size"});function l(h,g){let y=(g-h.lastAccessNs)/1e9;return Rn(h.baseScore,y,o,s)}function f(h){if(n!==void 0)for(;h.size>n;){let g=V(),y,b=Number.POSITIVE_INFINITY;for(let v of h.values()){let T=l(v,g);if(T<b){y=v,b=T;continue}if(T===b&&y){let w=r==="lru"?v.lastAccessNs:v.createdAtNs,k=r==="lru"?y.lastAccessNs:y.createdAtNs;w<k&&(y=v)}}if(!y)break;h.delete(y.id)}}function p(h){u.emit(h)}return Object.assign(a,{upsert(h,g,y){let b=V(),v=tt(u),T=v.get(h),w=y?.score??i(g),k=xt(v);k.set(h,{id:h,value:g,baseScore:w,createdAtNs:T?.createdAtNs??b,lastAccessNs:b}),f(k),p(k)},remove(h){let g=xt(tt(u));g.delete(h)&&p(g)},clear(){tt(u).size!==0&&p(new Map)},getItem(h){let g=tt(u),y=g.get(h);if(y){if(r==="lru"){let b=xt(g);b.set(h,{...y,lastAccessNs:V()}),p(b)}return y}}})}function ja(t={}){let e=t.backend??"flat",n=t.dimension,r;if(e==="hnsw"&&(r=t.hnswFactory?.(),!r))throw new Error('vectorIndex backend "hnsw" requires an optional dependency adapter; install your HNSW package and provide `hnswFactory`.');let o=N(new Map,{describeKind:"state",name:"vector-index"});function s(a){if(n!==void 0&&a.length!==n)throw new RangeError(`vector dimension mismatch: expected ${n}, got ${a.length}`)}function i(a){o.emit(a)}return{backend:e,entries:o,upsert(a,u,c){s(u);let d=xt(tt(o));d.set(a,{id:a,vector:[...u],meta:c}),e==="hnsw"&&r.upsert(a,u,c),i(d)},remove(a){let u=xt(tt(o));u.delete(a)&&(e==="hnsw"&&r.remove(a),i(u))},clear(){tt(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):[...tt(o).values()].map(d=>({id:d.id,score:lg(a,d.vector),meta:d.meta})).sort((d,l)=>l.score-d.score).slice(0,u)}}}function Va(t){let e=new q(t),n=N(new Map,{name:"entities",describeKind:"state"}),r=N([],{name:"edges",describeKind:"state"}),o=E([r],([u])=>{let c=u??[],d=new Map;for(let l of c){let f=d.get(l.from)??[];d.set(l.from,Object.freeze([...f,l]))}return d},{name:"adjacency",describeKind:"derived",initial:new Map});o.subscribe(()=>{}),e.add(n,{name:"entities"}),e.add(r,{name:"edges"}),e.add(o,{name:"adjacency"});function s(u){n.emit(u)}function i(u){r.emit(u)}return Object.assign(e,{upsertEntity(u,c){let d=xt(tt(n));d.set(u,c),s(d)},removeEntity(u){let c=xt(tt(n)),d=c.delete(u),l=$s(r),f=l.filter(p=>p.from!==u&&p.to!==u);!d&&f.length===l.length||(s(c),i(f))},link(u,c,d,l=1){let f=`${u}\0${c}\0${d}`,p=$s(r),m=new Set(p.map(g=>`${g.from}\0${g.to}\0${g.relation}`)),h=[...p];if(m.has(f))for(let g=0;g<h.length;g+=1){let y=h[g];if(y.from===u&&y.to===c&&y.relation===d){h[g]={...y,weight:l};break}}else h.push({from:u,to:c,relation:d,weight:l});i(h)},unlink(u,c,d){let l=$s(r),f=l.filter(p=>d===void 0?!(p.from===u&&p.to===c):!(p.from===u&&p.to===c&&p.relation===d));f.length!==l.length&&i(f)},related(u,c){return $s(r).filter(d=>(d.from===u||d.to===u)&&(c===void 0||d.relation===c))}})}ie();ne();ve();function Ka(t,e){return(n,r)=>{let o=[...r.keys()].slice(0,100),s=[{role:"system",content:t},{role:"user",content:JSON.stringify({input:n,existingKeys:o})}];return W(i=>{let a=!0,u=e.adapter.invoke(s,{model:e.model,temperature:e.temperature??0,maxTokens:e.maxTokens}),d=z(u).subscribe(l=>{if(!a)return;let f=!1;for(let p of l){if(f)break;if(p[0]===S){let m=p[1];try{let h=JSON.parse(m.content);i.emit(h),i.down([[M]])}catch{i.down([[O,new Error("llmExtractor: failed to parse LLM response as JSON")]])}f=!0}else p[0]===O?(i.down([[O,p[1]]]),f=!0):p[0]===M?(i.down([[M]]),f=!0):i.down([[p[0],p[1]]])}});return()=>{d(),a=!1}})}}function Ha(t,e){return n=>{let r=[...n.entries()].map(([s,i])=>({key:s,value:i})),o=[{role:"system",content:t},{role:"user",content:JSON.stringify({memories:r})}];return W(s=>{let i=!0,a=e.adapter.invoke(o,{model:e.model,temperature:e.temperature??0,maxTokens:e.maxTokens}),c=z(a).subscribe(d=>{if(!i)return;let l=!1;for(let f of d){if(l)break;if(f[0]===S){let p=f[1];try{let m=JSON.parse(p.content);s.emit(m),s.down([[M]])}catch{s.down([[O,new Error("llmConsolidator: failed to parse LLM response as JSON")]])}l=!0}else f[0]===O?(s.down([[O,f[1]]]),l=!0):f[0]===M?(s.down([[M]]),l=!0):s.down([[f[0],f[1]]])}});return()=>{c(),i=!1}})}}var Wa=Math.LN2/604800;function to(t){return t instanceof Map?t:new Map}function fg(t,e,n){let r=new q(t,n.graph),o=[],s;if(n.extractFn)s=n.extractFn;else if(n.adapter&&n.extractPrompt)s=Ka(n.extractPrompt,{adapter:n.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let i=(v,T)=>v==null?{upsert:[]}:s(v,T),a=e;if(n.admissionFilter){let v=z(e),T=n.admissionFilter;a=E([v],([w])=>{if(T(w))return w},{name:"admissionFilter",describeKind:"derived"})}let u;n.consolidateFn?u=n.consolidateFn:n.adapter&&n.consolidatePrompt&&(u=Ha(n.consolidatePrompt,{adapter:n.adapter}));let c=n.consolidateTrigger;if(!c&&u&&n.reflection?.enabled!==!1){let v=n.reflection?.interval??3e5;c=at(v,{period:v})}let d={score:n.score,cost:n.cost,budget:n.budget??2e3,context:n.context,consolidate:u,consolidateTrigger:c},l=fs(a,i,d);r.add(l.store.entries,{name:"store"}),r.add(l.compact,{name:"compact"}),r.add(l.size,{name:"size"});let f=null;n.vectorDimensions&&n.vectorDimensions>0&&n.embedFn&&(f=ja({dimension:n.vectorDimensions}),r.add(f.entries,{name:"vectorIndex"}));let p=null;n.enableKnowledgeGraph&&(p=Va(`${t}-kg`),r.mount("kg",p));let m=null;if(n.tiers){let v=n.tiers,T=v.decayRate??Wa,w=v.maxActive??1e3,k=v.archiveThreshold??.1,x=v.permanentFilter??(()=>!1),R=Ba({name:"permanent"});r.add(R.entries,{name:"permanent"});let _=new Set,G=A=>_.has(A)?"permanent":to(l.store.entries.cache).has(A)?"active":"archived",L=(A,D)=>{_.add(A),R.upsert(A,D)},P=new Map,C=l.store.entries,B=n.context?z(n.context):N(null),te=me([C,B],([A,D])=>{let I=to(A),J=V(),H=[],ae=[];for(let[U,he]of I){if(P.has(U)||P.set(U,J),x(U,he)){ae.push({key:U,value:he});continue}let ue=n.score(he,D),oe=P.get(U)??J,Z=Number(J-oe)/1e9;Rn(ue,Z,T)<k&&H.push(U)}for(let U of P.keys())I.has(U)||P.delete(U);for(let{key:U,value:he}of ae)_.has(U)||L(U,he);let j=I.size-_.size;if(j>w){let U=[...I.entries()].filter(([ue])=>!_.has(ue)).map(([ue,oe])=>({key:ue,score:n.score(oe,D)})).sort((ue,oe)=>ue.score-oe.score),he=j-w;for(let ue=0;ue<he&&ue<U.length;ue++){let oe=U[ue].key;H.includes(oe)||H.push(oe)}}H.length>0&&X(()=>{for(let U of H)l.store.delete(U)})});o.push(te.subscribe(()=>{}));let F=null;v.archiveTier&&(F=r.attachStorage([v.archiveTier],v.archiveStorageOptions??{})),m={permanent:R,activeEntries:C,archiveHandle:F,tierOf:G,markPermanent:L}}if(f||p){let v=n.embedFn,T=n.entityFn,w=l.store.entries,k=me([w],([x])=>{let R=to(x);for(let[_,G]of R){if(f&&v){let L=v(G);L&&f.upsert(_,L,G)}if(p&&T){let L=T(_,G);if(L){for(let P of L.entities??[])p.upsertEntity(P.id,P.value);for(let P of L.relations??[])p.link(P.from,P.to,P.relation,P.weight)}}}});o.push(k.subscribe(()=>{}))}let h=null,g=null,y=null,b=null;if(f||p){let v=n.retrieval?.topK??20,T=n.retrieval?.graphDepth??1,w=n.budget??2e3,k=n.cost,x=n.score,R=n.contextOf,_=n.contextWeight??0,G=n.context?z(n.context):N(null),L=(F,A)=>{if(!F||!A)return 0;let D=Math.min(F.length,A.length),I=0;for(;I<D&&F[I]===A[I];)I++;return I},P=(F,A,D)=>{let I=new Map,J=[];if(f&&D.vector){J=f.search(D.vector,v);for(let oe of J){let Z=F.get(oe.id);Z&&I.set(oe.id,{value:Z,sources:new Set(["vector"])})}}let H=[];if(p){let oe=[...D.entityIds??[],...I.keys()],Z=new Set,Se=oe;for(let Q=0;Q<T;Q++){let se=[];for(let xe of Se){if(Z.has(xe))continue;Z.add(xe);let Le=p.related(xe);for(let Ve of Le){let Ke=Ve.to;if(!Z.has(Ke)){se.push(Ke);let Je=F.get(Ke);if(Je){let Y=I.get(Ke);Y?Y.sources.add("graph"):I.set(Ke,{value:Je,sources:new Set(["graph"])}),H.push(Ke)}}}}Se=se}}for(let[oe,Z]of F)I.has(oe)||I.set(oe,{value:Z,sources:new Set(["store"])});let ae=D.context?.length??0,j=[];for(let[oe,{value:Z,sources:Se}]of I){let Q=R?R(Z):void 0,se=x(Z,A);if(_>0&&ae>0){let Le=L(D.context,Q);Le>0&&(se=se*(1+_*Le/ae))}let xe=Q?{key:oe,value:Z,score:se,sources:[...Se],context:Q}:{key:oe,value:Z,score:se,sources:[...Se]};j.push(xe)}j.sort((oe,Z)=>Z.score-oe.score);let U=[],he=0;for(let oe of j){let Z=k(oe.value);if(he+Z>w&&U.length>0)break;U.push(oe),he+=Z}return{packed:U,trace:{vectorCandidates:J,graphExpanded:H,ranked:j,packed:U}}},C=N([],{name:"retrieval",describeKind:"state",meta:ge("retrieval_pipeline")});r.add(C,{name:"retrieval"}),h=C;let B=N(null,{name:"retrievalTrace",describeKind:"state",meta:ge("retrieval_trace")});r.add(B,{name:"retrievalTrace"}),g=B,y=F=>{let A=to(l.store.entries.cache),{packed:D,trace:I}=P(A,G.cache,F);return X(()=>{C.emit(D),B.emit(I)}),D},b=F=>{let A=z(F);return E([l.store.entries,G,A],([D,I,J])=>{if(J==null)return[];let H=to(D);return P(H,I,J).packed},{name:"retrievalReactive",describeKind:"derived",meta:ge("retrieval_reactive"),initial:[]})}}return r.addDisposer(()=>{for(let v of o)v();o.length=0}),Object.assign(r,{distillBundle:l,compact:l.compact,size:l.size,vectors:f,kg:p,memoryTiers:m,retrieval:h,retrievalTrace:g,retrieve:y,retrieveReactive:b})}function mg(t,e,n){let r=t.describe({actor:e,detail:"full"}),o=n?.groupByTags??!0,s=n?.separator??`
39
+ `,i=[],a=n?.sinceVersion;for(let[u,c]of Object.entries(r.nodes)){let d=c.meta??{},l=d.description,f=d.format;if(!l&&!f)continue;if(a!=null&&c.v!=null){let y=a.get(u);if(y!=null&&y.id===c.v.id&&c.v.version<=y.version)continue}let p=l??u,m=c.value,h=d.unit,g;f==="currency"&&typeof m=="number"?g=`$${m.toFixed(2)}`:f==="percentage"&&typeof m=="number"?g=`${(m*100).toFixed(1)}%`:m==null?g="(no value)":g=String(m),h&&f!=="currency"&&f!=="percentage"&&(g=`${g} ${h}`),i.push({path:u,description:p,formatted:g})}if(i.length===0)return"";if(o){let u=new Map,c=[];for(let l of i){let p=r.nodes[l.path].meta?.tags;if(p&&p.length>0){let m=p[0],h=u.get(m);h||(h=[],u.set(m,h)),h.push(l)}else c.push(l)}if(u.size===0)return i.map(l=>`- ${l.description}: ${l.formatted}`).join(s);let d=[];for(let[l,f]of[...u.entries()].sort((p,m)=>p[0].localeCompare(m[0])))d.push(`[${l}]${s}${f.map(p=>`- ${p.description}: ${p.formatted}`).join(s)}`);return c.length>0&&d.push(c.map(l=>`- ${l.description}: ${l.formatted}`).join(s)),d.join(s+s)}return i.map(u=>`- ${u.description}: ${u.formatted}`).join(s)}var Ks={};ye(Ks,{compileSpec:()=>so,decompileGraph:()=>kg,extractFnFactory:()=>ip,extractSourceFactory:()=>ap,generateCatalogPrompt:()=>up,isRichFnEntry:()=>ro,isRichSourceEntry:()=>za,llmCompose:()=>Rg,llmRefine:()=>lp,specDiff:()=>xg,validateSpec:()=>rr,validateSpecAgainstCatalog:()=>oo});ne();var Vs={};ye(Vs,{budgetGate:()=>qa,effectivenessTracker:()=>gg,feedback:()=>zt,funnel:()=>hg,scorer:()=>no});_e();ie();Ne();ne();function js(t,e){return qe("reduction",t,e)}function hg(t,e,n,r){if(e.length===0)throw new RangeError("funnel requires at least one source");if(n.length===0)throw new RangeError("funnel requires at least one stage");let o=new q(t,r),s=e.length===1?e[0]:wt(...e);o.add(s,{name:"merged"});let i="merged";for(let a=0;a<n.length;a++){let u=n[a],c=new q(u.name);u.build(c);try{c.resolve("input")}catch{throw new Error(`funnel stage "${u.name}" must define an "input" node`)}try{c.resolve("output")}catch{throw new Error(`funnel stage "${u.name}" must define an "output" node`)}o.mount(u.name,c);let d=o.resolve(i),l=`${u.name}::input`,f=o.resolve(l),p=`__bridge_${i}\u2192${u.name}_input`,m=me([d],([h])=>{f.emit(h)},{name:p});o.add(m,{name:p}),o.addDisposer(re(m)),i=`${u.name}::output`}return o}function zt(t,e,n,r){let o=r?.maxIterations??10,s=`__feedback_${e}`,i=N(0,{meta:js("feedback_counter",{maxIterations:o,feedbackFrom:e,feedbackTo:n})});t.add(i,{name:s});let a=t.resolve(e),u=t.resolve(n),c=`__feedback_effect_${e}`,d=K([],(l,f)=>{let p=a.subscribe(m=>{for(let h of m){let g=h[0];if(g===S){let y=h[1];if(y==null)return;X(()=>{Cr(i,o)&&u.emit(y)})}else if(g===M||g===O){let y=g===O&&h.length>1?[O,h[1]]:[g];i.down([y])}}});return()=>p()},{name:c,describeKind:"effect",meta:{...js("feedback_effect",{feedbackFrom:e,feedbackTo:n}),_internal:!0}});return t.add(d,{name:c}),t.addDisposer(re(d)),t}function qa(t,e,n){if(e.length===0)throw new RangeError("budgetGate requires at least one constraint");let r=e.map(p=>p.node),o=[t,...r],s=[],i=!1,a=!1,u=Symbol("budget-gate"),c=new Array(e.length);function d(){return e.every((p,m)=>p.check(c[m]))}function l(p){for(;s.length>0&&d();){let m=s[0];s=s.slice(1),p.emit(m)}s.length===0&&a&&(a=!1,p.down([[$]]))}return K([],(p,m)=>{for(let g=0;g<e.length;g++)c[g]=e[g].node.cache;let h=[];for(let g=0;g<o.length;g++){let y=o[g];h.push(y.subscribe(b=>{for(let v of b)f(v,g,m)}))}return()=>{for(let g of h)g()}},{...n,describeKind:"derived",meta:js("budget_gate",n?.meta)});function f(p,m,h){let g=p[0];if(m===0){if(g===S)return d()&&s.length===0?h.emit(p[1]):(s.push(p[1]),i||(i=!0,h.up([[Ge,u]]))),!0;if(g===ee)return h.down([[ee]]),!0;if(g===$)return s.length===0?h.down([[$]]):a=!0,!0;if(g===M||g===O){for(let y of s)h.emit(y);return s=[],a=!1,i&&(i=!1,h.up([[$e,u]])),h.down([p]),!0}return!1}return g===S&&(c[m-1]=p[1]),g===S||g===$?(d()&&s.length>0?(l(h),s.length===0&&i&&(i=!1,h.up([[$e,u]]))):!d()&&!i&&s.length>0&&(i=!0,h.up([[Ge,u]])),!0):g===ee?!0:g===O?(h.down([p]),!0):g===M}}function no(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 E(r,i=>{let a=i.slice(0,o),u=i.slice(o),c=[],d=0;for(let l=0;l<o;l++){let f=a[l]??0,p=u[l]??0,h=(s?.[l]?s[l](f):f)*p;c.push(h),d+=h}return{value:a,score:d,breakdown:c}},{...n?{equals:n.equals,resubscribable:n.resubscribable,resetOnTeardown:n.resetOnTeardown}:{},describeKind:"derived",meta:js("scorer",n?.meta)})}function gg(t){let e=Qe({name:t?.name??"effectiveness-entries"}),n=E([e.entries],([i])=>new Map(i),{name:`${t?.name??"effectiveness"}-snapshot`,equals:(i,a)=>{let u=i,c=a;if(u.size!==c.size)return!1;for(let[d,l]of u){let f=c.get(d);if(!f||l.attempts!==f.attempts||l.successes!==f.successes)return!1}return!0}});function r(i,a){let u=e.get(i),c=(u?.attempts??0)+1,d=(u?.successes??0)+(a?1:0);e.set(i,{key:i,attempts:c,successes:d,successRate:d/c})}function o(i){return e.get(i)}let s=re(n);return{node:n,record:r,lookup:o,dispose:()=>s()}}function ro(t){return typeof t=="object"&&t!==null&&"factory"in t}function za(t){return typeof t=="object"&&t!==null&&"factory"in t}function ip(t){return ro(t)?t.factory:t}function ap(t){return za(t)?t.factory:t}function up(t){let e=[];if(t.fns){let n=new Map;for(let[r,o]of Object.entries(t.fns)){let s=ro(o)?o.tags?.[0]??"Other":"Other";n.has(s)||n.set(s,[]),n.get(s).push(yg(r,o))}for(let[r,o]of n)e.push(`${r}:
119
40
  ${o.join(`
120
- `)}`)}if(t.sources){let n=[];for(let[r,o]of Object.entries(t.sources))n.push(Pg(r,o));n.length>0&&e.push(`Sources:
41
+ `)}`)}if(t.sources){let n=[];for(let[r,o]of Object.entries(t.sources))n.push(bg(r,o));n.length>0&&e.push(`Sources:
121
42
  ${n.join(`
122
43
  `)}`)}return e.join(`
123
44
 
124
- `)}function Ig(t,e){if(!Ur(e))return`- ${t}`;let n=`- ${t}: ${e.description}`;if(e.configSchema){let r=Object.entries(e.configSchema).map(([o,s])=>{let i=`${o}: ${s.type}`;return s.enum&&(i+=` (${s.enum.join("|")})`),s.required===!1&&(i+="?"),i});n+=`. Config: { ${r.join(", ")} }`}return n}function Pg(t,e){if(!ja(e))return`- ${t}`;let n=`- ${t}: ${e.description}`;if(e.configSchema){let r=Object.entries(e.configSchema).map(([o,s])=>{let i=`${o}: ${s.type}`;return s.required===!1&&(i+="?"),i});n+=`. Config: { ${r.join(", ")} }`}return n}function zr(t,e){let n=[],r=new Set(Object.keys(e.fns??{})),o=new Set(Object.keys(e.sources??{}));for(let[s,i]of Object.entries(t.nodes)){if(i.type==="template")continue;let a=i;if(a.fn&&r.size>0&&!r.has(a.fn))if(o.has(a.fn))n.push(`Node "${s}": fn "${a.fn}" is a source, not a function. Use it as a producer source instead, or use a function from: ${[...r].join(", ")}`);else{let u=Ba(a.fn,r);n.push(`Node "${s}": fn "${a.fn}" not found in catalog`+(u?`. Did you mean "${u}"?`:""))}if(a.source&&o.size>0&&!o.has(a.source))if(r.has(a.source))n.push(`Node "${s}": source "${a.source}" is a function, not a source. Use it as fn instead, or use a source from: ${[...o].join(", ")}`);else{let u=Ba(a.source,o);n.push(`Node "${s}": source "${a.source}" not found in catalog`+(u?`. Did you mean "${u}"?`:""))}if(a.fn&&a.config&&e.fns?.[a.fn]){let u=e.fns[a.fn];if(Ur(u)&&u.configSchema){for(let[c,d]of Object.entries(u.configSchema))if(d.required!==!1&&!(c in a.config)&&n.push(`Node "${s}": config missing required field "${c}"`),c in a.config&&d.enum){let l=a.config[c];d.enum.includes(l)||n.push(`Node "${s}": config.${c} = ${JSON.stringify(l)}, expected one of: ${d.enum.join(", ")}`)}}}}if(t.templates){for(let[s,i]of Object.entries(t.templates))for(let[a,u]of Object.entries(i.nodes))if(u.fn&&r.size>0&&!r.has(u.fn)){let c=Ba(u.fn,r);n.push(`Template "${s}" node "${a}": fn "${u.fn}" not found in catalog`+(c?`. Did you mean "${c}"?`:""))}}return{valid:n.length===0,errors:n}}function Ba(t,e){let n=null,r=1/0,o=t.toLowerCase();for(let s of e){let i=Dg(o,s.toLowerCase());i<r&&i<=Math.max(3,Math.floor(t.length/2))&&(r=i,n=s)}return n}function Dg(t,e){let n=t.length,r=e.length,o=Array.from({length:n+1},(s,i)=>Array.from({length:r+1},(a,u)=>i===0?u:u===0?i:0));for(let s=1;s<=n;s++)for(let i=1;i<=r;i++)o[s][i]=t[s-1]===e[i-1]?o[s-1][i-1]:1+Math.min(o[s-1][i],o[s][i-1],o[s-1][i-1]);return o[n][r]}var tp=new Set(["state","producer","derived","effect","operator","template"]),Gg=new Set(["state","producer","derived","effect","operator"]);function Xn(t){let e=[];if(t==null||typeof t!="object")return{valid:!1,errors:["GraphSpec must be a non-null object"]};let n=t;if((typeof n.name!="string"||n.name.length===0)&&e.push("Missing or empty 'name' field"),n.nodes==null||typeof n.nodes!="object"||Array.isArray(n.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e};let r=new Set(Object.keys(n.nodes)),o=new Map,s=new Map;if(n.templates!=null&&typeof n.templates=="object"&&!Array.isArray(n.templates)){for(let[i,a]of Object.entries(n.templates))if(a!=null&&typeof a=="object"){let u=a;s.set(i,{params:Array.isArray(u.params)?u.params:[]})}}if(n.templates!=null)if(typeof n.templates!="object"||Array.isArray(n.templates))e.push("'templates' must be an object");else for(let[i,a]of Object.entries(n.templates)){if(a==null||typeof a!="object"){e.push(`Template "${i}": must be an object`);continue}let u=a;if(Array.isArray(u.params)||e.push(`Template "${i}": missing 'params' array`),u.nodes==null||typeof u.nodes!="object"||Array.isArray(u.nodes))e.push(`Template "${i}": missing or invalid 'nodes' object`);else{let c=new Set(Array.isArray(u.params)?u.params:[]),d=new Set(Object.keys(u.nodes));for(let[l,f]of Object.entries(u.nodes)){if(f==null||typeof f!="object"){e.push(`Template "${i}" node "${l}": must be an object`);continue}let p=f;if((typeof p.type!="string"||!Gg.has(p.type))&&e.push(`Template "${i}" node "${l}": invalid type`),Array.isArray(p.deps))for(let m of p.deps)!d.has(m)&&!c.has(m)&&e.push(`Template "${i}" node "${l}": dep "${m}" is not an inner node or param`)}typeof u.output!="string"?e.push(`Template "${i}": missing 'output' string`):u.nodes[u.output]||e.push(`Template "${i}": output "${u.output}" is not a declared node`)}}for(let[i,a]of Object.entries(n.nodes)){if(a==null||typeof a!="object"){e.push(`Node "${i}": must be an object`);continue}let u=a;if(typeof u.type!="string"||!tp.has(u.type)){e.push(`Node "${i}": invalid type "${String(u.type)}" (expected: ${[...tp].join(", ")})`);continue}if(o.set(i,u.type),u.type==="template")if(typeof u.template!="string"||!s.has(u.template))e.push(`Node "${i}": template "${String(u.template)}" not found in templates`);else if(u.bind==null||typeof u.bind!="object"||Array.isArray(u.bind))e.push(`Node "${i}": template ref requires 'bind' object`);else{let c=s.get(u.template),d=u.bind;for(let l of c.params)l in d||e.push(`Node "${i}": template param "${l}" is not bound (template "${u.template}")`);for(let[,l]of Object.entries(d))typeof l=="string"&&!r.has(l)&&e.push(`Node "${i}": bind target "${l}" does not reference an existing node`)}else{if(Array.isArray(u.deps))for(let c of u.deps)c===i?e.push(`Node "${i}": self-referencing dep`):r.has(c)||e.push(`Node "${i}": dep "${c}" does not reference an existing node`);(u.type==="derived"||u.type==="effect"||u.type==="operator")&&!Array.isArray(u.deps)&&e.push(`Node "${i}": ${u.type} node should have a 'deps' array`)}}if(n.feedback!=null)if(!Array.isArray(n.feedback))e.push("'feedback' must be an array");else for(let i=0;i<n.feedback.length;i++){let a=n.feedback[i];if(a==null||typeof a!="object"){e.push(`Feedback [${i}]: must be an object`);continue}let u=a;(typeof u.from!="string"||!r.has(u.from))&&e.push(`Feedback [${i}]: 'from' "${String(u.from)}" does not reference an existing node`),typeof u.from=="string"&&u.from===u.to&&e.push(`Feedback [${i}]: 'from' and 'to' must be different nodes`),typeof u.to!="string"||!r.has(u.to)?e.push(`Feedback [${i}]: 'to' "${String(u.to)}" does not reference an existing node`):typeof u.to=="string"&&o.get(u.to)!=="state"&&e.push(`Feedback [${i}]: 'to' node "${u.to}" must be a state node (got "${o.get(u.to)??"unknown"}")`)}return{valid:e.length===0,errors:e}}function Va(t,e){let n=Xn(t);if(!n.valid)throw new Error(`compileSpec: invalid GraphSpec:
45
+ `)}function yg(t,e){if(!ro(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 bg(t,e){if(!za(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 oo(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=Ua(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=Ua(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(ro(u)&&u.configSchema){for(let[c,d]of Object.entries(u.configSchema))if(d.required!==!1&&!(c in a.config)&&n.push(`Node "${s}": config missing required field "${c}"`),c in a.config&&d.enum){let l=a.config[c];d.enum.includes(l)||n.push(`Node "${s}": config.${c} = ${JSON.stringify(l)}, expected one of: ${d.enum.join(", ")}`)}}}}if(t.templates){for(let[s,i]of Object.entries(t.templates))for(let[a,u]of Object.entries(i.nodes))if(u.fn&&r.size>0&&!r.has(u.fn)){let c=Ua(u.fn,r);n.push(`Template "${s}" node "${a}": fn "${u.fn}" not found in catalog`+(c?`. Did you mean "${c}"?`:""))}}return{valid:n.length===0,errors:n}}function Ua(t,e){let n=null,r=1/0,o=t.toLowerCase();for(let s of e){let i=vg(o,s.toLowerCase());i<r&&i<=Math.max(3,Math.floor(t.length/2))&&(r=i,n=s)}return n}function vg(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 sp=new Set(["state","producer","derived","effect","operator","template"]),Tg=new Set(["state","producer","derived","effect","operator"]);function rr(t){let e=[];if(t==null||typeof t!="object")return{valid:!1,errors:["GraphSpec must be a non-null object"]};let n=t;if((typeof n.name!="string"||n.name.length===0)&&e.push("Missing or empty 'name' field"),n.nodes==null||typeof n.nodes!="object"||Array.isArray(n.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e};let r=new Set(Object.keys(n.nodes)),o=new Map,s=new Map;if(n.templates!=null&&typeof n.templates=="object"&&!Array.isArray(n.templates)){for(let[i,a]of Object.entries(n.templates))if(a!=null&&typeof a=="object"){let u=a;s.set(i,{params:Array.isArray(u.params)?u.params:[]})}}if(n.templates!=null)if(typeof n.templates!="object"||Array.isArray(n.templates))e.push("'templates' must be an object");else for(let[i,a]of Object.entries(n.templates)){if(a==null||typeof a!="object"){e.push(`Template "${i}": must be an object`);continue}let u=a;if(Array.isArray(u.params)||e.push(`Template "${i}": missing 'params' array`),u.nodes==null||typeof u.nodes!="object"||Array.isArray(u.nodes))e.push(`Template "${i}": missing or invalid 'nodes' object`);else{let c=new Set(Array.isArray(u.params)?u.params:[]),d=new Set(Object.keys(u.nodes));for(let[l,f]of Object.entries(u.nodes)){if(f==null||typeof f!="object"){e.push(`Template "${i}" node "${l}": must be an object`);continue}let p=f;if((typeof p.type!="string"||!Tg.has(p.type))&&e.push(`Template "${i}" node "${l}": invalid type`),Array.isArray(p.deps))for(let m of p.deps)!d.has(m)&&!c.has(m)&&e.push(`Template "${i}" node "${l}": dep "${m}" is not an inner node or param`)}typeof u.output!="string"?e.push(`Template "${i}": missing 'output' string`):u.nodes[u.output]||e.push(`Template "${i}": output "${u.output}" is not a declared node`)}}for(let[i,a]of Object.entries(n.nodes)){if(a==null||typeof a!="object"){e.push(`Node "${i}": must be an object`);continue}let u=a;if(typeof u.type!="string"||!sp.has(u.type)){e.push(`Node "${i}": invalid type "${String(u.type)}" (expected: ${[...sp].join(", ")})`);continue}if(o.set(i,u.type),u.type==="template")if(typeof u.template!="string"||!s.has(u.template))e.push(`Node "${i}": template "${String(u.template)}" not found in templates`);else if(u.bind==null||typeof u.bind!="object"||Array.isArray(u.bind))e.push(`Node "${i}": template ref requires 'bind' object`);else{let c=s.get(u.template),d=u.bind;for(let l of c.params)l in d||e.push(`Node "${i}": template param "${l}" is not bound (template "${u.template}")`);for(let[,l]of Object.entries(d))typeof l=="string"&&!r.has(l)&&e.push(`Node "${i}": bind target "${l}" does not reference an existing node`)}else{if(Array.isArray(u.deps))for(let c of u.deps)c===i?e.push(`Node "${i}": self-referencing dep`):r.has(c)||e.push(`Node "${i}": dep "${c}" does not reference an existing node`);(u.type==="derived"||u.type==="effect"||u.type==="operator")&&!Array.isArray(u.deps)&&e.push(`Node "${i}": ${u.type} node should have a 'deps' array`)}}if(n.feedback!=null)if(!Array.isArray(n.feedback))e.push("'feedback' must be an array");else for(let i=0;i<n.feedback.length;i++){let a=n.feedback[i];if(a==null||typeof a!="object"){e.push(`Feedback [${i}]: must be an object`);continue}let u=a;(typeof u.from!="string"||!r.has(u.from))&&e.push(`Feedback [${i}]: 'from' "${String(u.from)}" does not reference an existing node`),typeof u.from=="string"&&u.from===u.to&&e.push(`Feedback [${i}]: 'from' and 'to' must be different nodes`),typeof u.to!="string"||!r.has(u.to)?e.push(`Feedback [${i}]: 'to' "${String(u.to)}" does not reference an existing node`):typeof u.to=="string"&&o.get(u.to)!=="state"&&e.push(`Feedback [${i}]: 'to' node "${u.to}" must be a state node (got "${o.get(u.to)??"unknown"}")`)}return{valid:e.length===0,errors:e}}function so(t,e){let n=rr(t);if(!n.valid)throw new Error(`compileSpec: invalid GraphSpec:
125
46
  ${n.errors.join(`
126
- `)}`);let r=e?.catalog??{},o=new q(t.name),s=t.templates??{},i=zr(t,r);if(!i.valid)throw new Error(`compileSpec: catalog validation errors:
47
+ `)}`);let r=e?.catalog??{},o=new q(t.name),s=t.templates??{},i=oo(t,r);if(!i.valid)throw new Error(`compileSpec: catalog validation errors:
127
48
  ${i.errors.join(`
128
- `)}`);let a=p=>{let m=r.fns?.[p];return m?np(m):void 0},u=p=>{let m=r.sources?.[p];return m?rp(m):void 0},c=new Map,d=[];for(let[p,m]of Object.entries(t.nodes)){if(m.type==="template")continue;let h=m;if(h.type==="state"){let g=N(h.initial,{name:p,meta:h.meta?{...h.meta}:void 0});o.add(g,{name:p}),c.set(p,g)}else if(h.type==="producer"){let g=h.source?u(h.source):void 0,y=h.fn?a(h.fn):void 0;if(g){let b=g(h.config??{});o.add(b,{name:p}),c.set(p,b)}else if(y){let b=y([],h.config??{});o.add(b,{name:p}),c.set(p,b)}else{let b=W(()=>{},{name:p,meta:{...h.meta,_specFn:h.fn,_specSource:h.source}});o.add(b,{name:p}),c.set(p,b)}}else d.push([p,h])}let l=!0,f=new Map(d);for(;f.size>0&&l;){l=!1;for(let[p,m]of[...f.entries()]){let h=m.deps??[];if(!h.every(v=>c.has(v)))continue;let g=h.map(v=>c.get(v)),y=m.fn?a(m.fn):void 0,b;y?b=y(g,m.config??{}):m.type==="effect"?b=fe(g,()=>{}):b=O(g,v=>v[0]),o.add(b,{name:p}),c.set(p,b),f.delete(p),l=!0}}if(f.size>0){let p=[...f.keys()].sort().join(", ");throw new Error(`compileSpec: unresolvable deps for nodes: ${p}`)}for(let[p,m]of Object.entries(t.nodes)){if(m.type!=="template")continue;let h=m,g=s[h.template],y=new q(p),b=new Map,v=[];for(let[x,R]of Object.entries(g.nodes)){let E=(R.deps??[]).map(L=>L.startsWith("$")&&h.bind[L]?h.bind[L]:L),G={...R,deps:E};if(R.type==="state"){let L=N(R.initial,{name:x,meta:R.meta?{...R.meta}:void 0});y.add(L,{name:x}),b.set(x,L)}else if(R.type==="producer"){let L=R.source?u(R.source):void 0,P=R.fn?a(R.fn):void 0;if(L){let C=L(R.config??{});y.add(C,{name:x}),b.set(x,C)}else if(P){let C=P([],R.config??{});y.add(C,{name:x}),b.set(x,C)}else{let C=W(()=>{},{name:x,meta:{...R.meta,_specFn:R.fn,_specSource:R.source}});y.add(C,{name:x}),b.set(x,C)}}else v.push([x,G])}let T=!0,w=new Map(v);for(;w.size>0&&T;){T=!1;for(let[x,R]of[...w.entries()]){let E=R.deps??[];if(!E.every(V=>b.has(V)||c.has(V)))continue;let L=E.map(V=>b.get(V)??c.get(V)),P=R.fn?a(R.fn):void 0,C;P?C=P(L,R.config??{}):R.type==="effect"?C=fe(L,()=>{}):C=O(L,V=>V[0]),y.add(C,{name:x}),b.set(x,C),w.delete(x),T=!0}}if(w.size>0){let x=[...w.keys()].sort().join(", ");throw new Error(`compileSpec: template "${h.template}" has unresolvable deps: ${x}`)}o.mount(p,y);let k=`${p}::${g.output}`;c.set(p,o.resolve(k));try{let x=o.resolve(k);x.meta._templateName?.emit(h.template),x.meta._templateBind?.emit(h.bind)}catch{}}for(let p of t.feedback??[])Kt(o,p.from,p.to,{maxIterations:p.maxIterations});return o}var Fg=new Set(["reduction","reduction_type","_specFn","_specSource","_templateName","_templateBind","feedbackFrom","feedbackTo","_internal"]);function $g(t){let e=t.describe({detail:"standard"}),n={},r=[],o=`::${je}::`,s=/^__feedback_(?!effect_)(.+)$/,i=new Set;for(let p of Object.keys(e.nodes)){if(p.includes(o))continue;let m=s.exec(p);if(m){i.add(m[1]);let h=e.nodes[p]?.meta;h?.feedbackFrom&&h?.feedbackTo&&r.push({from:h.feedbackFrom,to:h.feedbackTo,...h.maxIterations?{maxIterations:h.maxIterations}:{}})}}for(let[p,m]of Object.entries(e.nodes)){if(p.includes(o)||s.test(p)||m.meta?._internal||p.startsWith("__feedback_effect_")||p.startsWith("__bridge_")||p.includes("::"))continue;let h={type:m.type};if(m.deps.length>0&&(h.deps=m.deps.filter(g=>!g.includes("::"))),m.type==="state"&&m.value!==void 0&&(h.initial=m.value),m.meta&&Object.keys(m.meta).length>0){let g={};for(let[y,b]of Object.entries(m.meta))Fg.has(y)||(g[y]=b);Object.keys(g).length>0&&(h.meta=g)}n[p]=h}let a={},u={},c=new Set;for(let p of e.subgraphs){let m=`${p}::`;for(let[h,g]of Object.entries(e.nodes)){if(!h.startsWith(m)||h.includes(o))continue;let y=g.meta;if(y?._templateName&&y?._templateBind){let b=y._templateName,v=y._templateBind;if(!a[b]){let T={},w=new Set,k=`${p}::`;for(let[P,C]of Object.entries(e.nodes)){if(!P.startsWith(k)||P.includes(o))continue;let V=P.slice(k.length);V.includes("::")||(w.add(V),T[V]={type:C.type,...C.deps.length>0?{deps:C.deps.map(ne=>ne.startsWith(k)?ne.slice(k.length):ne)}:{}})}let x=[],R=new Map;for(let P of Object.values(T))for(let C of P.deps??[])if(!w.has(C)&&!R.has(C)){let V=`$${C}`;x.push(V),R.set(C,V)}for(let P of Object.values(T))P.deps&&(P.deps=P.deps.map(C=>R.get(C)??C));let E=new Set;for(let P of Object.values(T))for(let C of P.deps??[])w.has(C)&&E.add(C);let L=[...w].filter(P=>!E.has(P))[0]??[...w].pop();a[b]={params:x,nodes:T,output:L}}delete n[p],u[p]={type:"template",template:b,bind:v},c.add(p);break}}}let d=new Map;for(let p of e.subgraphs){if(c.has(p))continue;let m={},h=`${p}::`;for(let[y,b]of Object.entries(e.nodes)){if(y.includes(o)||!y.startsWith(h))continue;let v=y.slice(h.length);v.includes("::")||(m[v]={type:b.type,...b.deps.length>0?{deps:b.deps.map(T=>T.startsWith(h)?T.slice(h.length):T)}:{}})}let g=JSON.stringify(Object.fromEntries(Object.entries(m).sort(([y],[b])=>y.localeCompare(b)).map(([y,b])=>[y,{type:b.type,deps:b.deps??[]}])));d.has(g)||d.set(g,[]),d.get(g).push({name:p,nodes:m})}for(let[,p]of d){if(p.length<2)continue;let m=`${p[0].name}_template`,h=p[0].nodes,g=new Set(Object.keys(h)),y=[],b=new Map;for(let x of Object.values(h))for(let R of x.deps??[])if(!g.has(R)&&!b.has(R)){let E=`$${R}`;y.push(E),b.set(R,E)}let v=new Set;for(let x of Object.values(h))for(let R of x.deps??[])g.has(R)&&v.add(R);let w=[...g].filter(x=>!v.has(x))[0]??[...g].pop(),k={};for(let[x,R]of Object.entries(h))k[x]={...R,deps:R.deps?.map(E=>b.get(E)??E)};a[m]={params:y,nodes:k,output:w};for(let x of p){delete n[x.name];let R={},E=new Set(Object.keys(x.nodes));for(let G of Object.values(x.nodes))for(let L of G.deps??[])if(!E.has(L)){let P=b.get(L)??`$${L}`;R[P]=L}u[x.name]={type:"template",template:m,bind:R}}}let l={...n,...u},f={name:e.name,nodes:l};return Object.keys(a).length>0&&(f.templates=a),r.length>0&&(f.feedback=r),f}function Bg(t,e){let n=[];t.name!==e.name&&n.push({type:"changed",path:"name",detail:`"${t.name}" \u2192 "${e.name}"`});let r=new Set(Object.keys(t.nodes)),o=new Set(Object.keys(e.nodes));for(let b of o)if(!r.has(b)){let v=e.nodes[b];n.push({type:"added",path:`nodes.${b}`,detail:`type: ${v.type}`})}for(let b of r)o.has(b)||n.push({type:"removed",path:`nodes.${b}`});for(let b of r){if(!o.has(b))continue;let v=t.nodes[b],T=e.nodes[b];if(JSON.stringify(v)!==JSON.stringify(T)){let w=[];v.type!==T.type&&w.push(`type: ${v.type} \u2192 ${T.type}`),JSON.stringify(v.deps)!==JSON.stringify(T.deps)&&w.push("deps changed"),v.fn!==T.fn&&w.push(`fn: ${v.fn} \u2192 ${T.fn}`),JSON.stringify(v.config)!==JSON.stringify(T.config)&&w.push("config changed"),n.push({type:"changed",path:`nodes.${b}`,detail:w.join("; ")||"modified"})}}let s=t.templates??{},i=e.templates??{},a=new Set(Object.keys(s)),u=new Set(Object.keys(i));for(let b of u)a.has(b)||n.push({type:"added",path:`templates.${b}`});for(let b of a)u.has(b)||n.push({type:"removed",path:`templates.${b}`});for(let b of a)u.has(b)&&JSON.stringify(s[b])!==JSON.stringify(i[b])&&n.push({type:"changed",path:`templates.${b}`,detail:"template definition changed"});let c=t.feedback??[],d=e.feedback??[],l=new Set(c.map(b=>`${b.from}->${b.to}`)),f=new Set(d.map(b=>`${b.from}->${b.to}`));for(let b of d){let v=`${b.from}->${b.to}`;l.has(v)||n.push({type:"added",path:`feedback.${v}`,detail:`maxIterations: ${b.maxIterations??10}`})}for(let b of c){let v=`${b.from}->${b.to}`;f.has(v)||n.push({type:"removed",path:`feedback.${v}`})}for(let b of c){let v=`${b.from}->${b.to}`,T=d.find(w=>w.from===b.from&&w.to===b.to);T&&JSON.stringify(b)!==JSON.stringify(T)&&n.push({type:"changed",path:`feedback.${v}`,detail:`maxIterations: ${b.maxIterations??10} \u2192 ${T.maxIterations??10}`})}let p=n.filter(b=>b.type==="added").length,m=n.filter(b=>b.type==="removed").length,h=n.filter(b=>b.type==="changed").length,g=[];p&&g.push(`${p} added`),m&&g.push(`${m} removed`),h&&g.push(`${h} changed`);let y=g.length>0?g.join(", "):"no changes";return{entries:n,summary:y}}var sp=`You are a graph architect for GraphReFly, a reactive graph protocol.
49
+ `)}`);let a=p=>{let m=r.fns?.[p];return m?ip(m):void 0},u=p=>{let m=r.sources?.[p];return m?ap(m):void 0},c=new Map,d=[];for(let[p,m]of Object.entries(t.nodes)){if(m.type==="template")continue;let h=m;if(h.type==="state"){let g=N(h.initial,{name:p,meta:h.meta?{...h.meta}:void 0});o.add(g,{name:p}),c.set(p,g)}else if(h.type==="producer"){let g=h.source?u(h.source):void 0,y=h.fn?a(h.fn):void 0;if(g){let b=g(h.config??{});o.add(b,{name:p}),c.set(p,b)}else if(y){let b=y([],h.config??{});o.add(b,{name:p}),c.set(p,b)}else{let b=W(()=>{},{name:p,meta:{...h.meta,_specFn:h.fn,_specSource:h.source}});o.add(b,{name:p}),c.set(p,b)}}else d.push([p,h])}let l=!0,f=new Map(d);for(;f.size>0&&l;){l=!1;for(let[p,m]of[...f.entries()]){let h=m.deps??[];if(!h.every(v=>c.has(v)))continue;let g=h.map(v=>c.get(v)),y=m.fn?a(m.fn):void 0,b;y?b=y(g,m.config??{}):m.type==="effect"?b=me(g,()=>{}):b=E(g,v=>v[0]),o.add(b,{name:p}),c.set(p,b),f.delete(p),l=!0}}if(f.size>0){let p=[...f.keys()].sort().join(", ");throw new Error(`compileSpec: unresolvable deps for nodes: ${p}`)}for(let[p,m]of Object.entries(t.nodes)){if(m.type!=="template")continue;let h=m,g=s[h.template],y=new q(p),b=new Map,v=[];for(let[x,R]of Object.entries(g.nodes)){let _=(R.deps??[]).map(L=>L.startsWith("$")&&h.bind[L]?h.bind[L]:L),G={...R,deps:_};if(R.type==="state"){let L=N(R.initial,{name:x,meta:R.meta?{...R.meta}:void 0});y.add(L,{name:x}),b.set(x,L)}else if(R.type==="producer"){let L=R.source?u(R.source):void 0,P=R.fn?a(R.fn):void 0;if(L){let C=L(R.config??{});y.add(C,{name:x}),b.set(x,C)}else if(P){let C=P([],R.config??{});y.add(C,{name:x}),b.set(x,C)}else{let C=W(()=>{},{name:x,meta:{...R.meta,_specFn:R.fn,_specSource:R.source}});y.add(C,{name:x}),b.set(x,C)}}else v.push([x,G])}let T=!0,w=new Map(v);for(;w.size>0&&T;){T=!1;for(let[x,R]of[...w.entries()]){let _=R.deps??[];if(!_.every(B=>b.has(B)||c.has(B)))continue;let L=_.map(B=>b.get(B)??c.get(B)),P=R.fn?a(R.fn):void 0,C;P?C=P(L,R.config??{}):R.type==="effect"?C=me(L,()=>{}):C=E(L,B=>B[0]),y.add(C,{name:x}),b.set(x,C),w.delete(x),T=!0}}if(w.size>0){let x=[...w.keys()].sort().join(", ");throw new Error(`compileSpec: template "${h.template}" has unresolvable deps: ${x}`)}o.mount(p,y);let k=`${p}::${g.output}`;c.set(p,o.resolve(k));try{let x=o.resolve(k);x.meta._templateName?.emit(h.template),x.meta._templateBind?.emit(h.bind)}catch{}}for(let p of t.feedback??[])zt(o,p.from,p.to,{maxIterations:p.maxIterations});return o}var wg=new Set(["reduction","reduction_type","_specFn","_specSource","_templateName","_templateBind","feedbackFrom","feedbackTo","_internal"]);function kg(t){let e=t.describe({detail:"standard"}),n={},r=[],o=`::${He}::`,s=/^__feedback_(?!effect_)(.+)$/,i=new Set;for(let p of Object.keys(e.nodes)){if(p.includes(o))continue;let m=s.exec(p);if(m){i.add(m[1]);let h=e.nodes[p]?.meta;h?.feedbackFrom&&h?.feedbackTo&&r.push({from:h.feedbackFrom,to:h.feedbackTo,...h.maxIterations?{maxIterations:h.maxIterations}:{}})}}for(let[p,m]of Object.entries(e.nodes)){if(p.includes(o)||s.test(p)||m.meta?._internal||p.startsWith("__feedback_effect_")||p.startsWith("__bridge_")||p.includes("::"))continue;let h={type:m.type};if(m.deps.length>0&&(h.deps=m.deps.filter(g=>!g.includes("::"))),m.type==="state"&&m.value!==void 0&&(h.initial=m.value),m.meta&&Object.keys(m.meta).length>0){let g={};for(let[y,b]of Object.entries(m.meta))wg.has(y)||(g[y]=b);Object.keys(g).length>0&&(h.meta=g)}n[p]=h}let a={},u={},c=new Set;for(let p of e.subgraphs){let m=`${p}::`;for(let[h,g]of Object.entries(e.nodes)){if(!h.startsWith(m)||h.includes(o))continue;let y=g.meta;if(y?._templateName&&y?._templateBind){let b=y._templateName,v=y._templateBind;if(!a[b]){let T={},w=new Set,k=`${p}::`;for(let[P,C]of Object.entries(e.nodes)){if(!P.startsWith(k)||P.includes(o))continue;let B=P.slice(k.length);B.includes("::")||(w.add(B),T[B]={type:C.type,...C.deps.length>0?{deps:C.deps.map(te=>te.startsWith(k)?te.slice(k.length):te)}:{}})}let x=[],R=new Map;for(let P of Object.values(T))for(let C of P.deps??[])if(!w.has(C)&&!R.has(C)){let B=`$${C}`;x.push(B),R.set(C,B)}for(let P of Object.values(T))P.deps&&(P.deps=P.deps.map(C=>R.get(C)??C));let _=new Set;for(let P of Object.values(T))for(let C of P.deps??[])w.has(C)&&_.add(C);let L=[...w].filter(P=>!_.has(P))[0]??[...w].pop();a[b]={params:x,nodes:T,output:L}}delete n[p],u[p]={type:"template",template:b,bind:v},c.add(p);break}}}let d=new Map;for(let p of e.subgraphs){if(c.has(p))continue;let m={},h=`${p}::`;for(let[y,b]of Object.entries(e.nodes)){if(y.includes(o)||!y.startsWith(h))continue;let v=y.slice(h.length);v.includes("::")||(m[v]={type:b.type,...b.deps.length>0?{deps:b.deps.map(T=>T.startsWith(h)?T.slice(h.length):T)}:{}})}let g=JSON.stringify(Object.fromEntries(Object.entries(m).sort(([y],[b])=>y.localeCompare(b)).map(([y,b])=>[y,{type:b.type,deps:b.deps??[]}])));d.has(g)||d.set(g,[]),d.get(g).push({name:p,nodes:m})}for(let[,p]of d){if(p.length<2)continue;let m=`${p[0].name}_template`,h=p[0].nodes,g=new Set(Object.keys(h)),y=[],b=new Map;for(let x of Object.values(h))for(let R of x.deps??[])if(!g.has(R)&&!b.has(R)){let _=`$${R}`;y.push(_),b.set(R,_)}let v=new Set;for(let x of Object.values(h))for(let R of x.deps??[])g.has(R)&&v.add(R);let w=[...g].filter(x=>!v.has(x))[0]??[...g].pop(),k={};for(let[x,R]of Object.entries(h))k[x]={...R,deps:R.deps?.map(_=>b.get(_)??_)};a[m]={params:y,nodes:k,output:w};for(let x of p){delete n[x.name];let R={},_=new Set(Object.keys(x.nodes));for(let G of Object.values(x.nodes))for(let L of G.deps??[])if(!_.has(L)){let P=b.get(L)??`$${L}`;R[P]=L}u[x.name]={type:"template",template:m,bind:R}}}let l={...n,...u},f={name:e.name,nodes:l};return Object.keys(a).length>0&&(f.templates=a),r.length>0&&(f.feedback=r),f}function xg(t,e){let n=[];t.name!==e.name&&n.push({type:"changed",path:"name",detail:`"${t.name}" \u2192 "${e.name}"`});let r=new Set(Object.keys(t.nodes)),o=new Set(Object.keys(e.nodes));for(let b of o)if(!r.has(b)){let v=e.nodes[b];n.push({type:"added",path:`nodes.${b}`,detail:`type: ${v.type}`})}for(let b of r)o.has(b)||n.push({type:"removed",path:`nodes.${b}`});for(let b of r){if(!o.has(b))continue;let v=t.nodes[b],T=e.nodes[b];if(JSON.stringify(v)!==JSON.stringify(T)){let w=[];v.type!==T.type&&w.push(`type: ${v.type} \u2192 ${T.type}`),JSON.stringify(v.deps)!==JSON.stringify(T.deps)&&w.push("deps changed"),v.fn!==T.fn&&w.push(`fn: ${v.fn} \u2192 ${T.fn}`),JSON.stringify(v.config)!==JSON.stringify(T.config)&&w.push("config changed"),n.push({type:"changed",path:`nodes.${b}`,detail:w.join("; ")||"modified"})}}let s=t.templates??{},i=e.templates??{},a=new Set(Object.keys(s)),u=new Set(Object.keys(i));for(let b of u)a.has(b)||n.push({type:"added",path:`templates.${b}`});for(let b of a)u.has(b)||n.push({type:"removed",path:`templates.${b}`});for(let b of a)u.has(b)&&JSON.stringify(s[b])!==JSON.stringify(i[b])&&n.push({type:"changed",path:`templates.${b}`,detail:"template definition changed"});let c=t.feedback??[],d=e.feedback??[],l=new Set(c.map(b=>`${b.from}->${b.to}`)),f=new Set(d.map(b=>`${b.from}->${b.to}`));for(let b of d){let v=`${b.from}->${b.to}`;l.has(v)||n.push({type:"added",path:`feedback.${v}`,detail:`maxIterations: ${b.maxIterations??10}`})}for(let b of c){let v=`${b.from}->${b.to}`;f.has(v)||n.push({type:"removed",path:`feedback.${v}`})}for(let b of c){let v=`${b.from}->${b.to}`,T=d.find(w=>w.from===b.from&&w.to===b.to);T&&JSON.stringify(b)!==JSON.stringify(T)&&n.push({type:"changed",path:`feedback.${v}`,detail:`maxIterations: ${b.maxIterations??10} \u2192 ${T.maxIterations??10}`})}let p=n.filter(b=>b.type==="added").length,m=n.filter(b=>b.type==="removed").length,h=n.filter(b=>b.type==="changed").length,g=[];p&&g.push(`${p} added`),m&&g.push(`${m} removed`),h&&g.push(`${h} changed`);let y=g.length>0?g.join(", "):"no changes";return{entries:n,summary:y}}var cp=`You are a graph architect for GraphReFly, a reactive graph protocol.
129
50
 
130
51
  Given a natural-language description, produce a JSON GraphSpec with this structure:
131
52
 
@@ -167,20 +88,20 @@ Rules:
167
88
  - Use "templates" when the same subgraph pattern repeats (e.g., per-source resilience).
168
89
  - Use "feedback" for bounded cycles where a derived value writes back to a state node.
169
90
  - meta.description is required for every node.
170
- - Return ONLY valid JSON, no markdown fences or commentary.`;function ip(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}async function jg(t,e,n){let r=sp,o=n?.catalogDescription??(n?.catalog?op(n.catalog):void 0);o&&(r+=`
91
+ - Return ONLY valid JSON, no markdown fences or commentary.`;function dp(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}async function Rg(t,e,n){let r=cp,o=n?.catalogDescription??(n?.catalog?up(n.catalog):void 0);o&&(r+=`
171
92
 
172
93
  Available catalog (use ONLY these names):
173
94
  ${o}`),n?.systemPromptExtra&&(r+=`
174
95
 
175
- ${n.systemPromptExtra}`);let s=[{role:"system",content:r},{role:"user",content:t}],u=(await e.invoke(s,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens})).content.trim();u.startsWith("```")&&(u=ip(u));let c;try{c=JSON.parse(u)}catch{throw new Error(`llmCompose: LLM response is not valid JSON: ${u.slice(0,200)}`)}let d=Xn(c);if(!d.valid)throw new Error(`llmCompose: invalid GraphSpec:
96
+ ${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=dp(u));let c;try{c=JSON.parse(u)}catch{throw new Error(`llmCompose: LLM response is not valid JSON: ${u.slice(0,200)}`)}let d=rr(c);if(!d.valid)throw new Error(`llmCompose: invalid GraphSpec:
176
97
  ${d.errors.join(`
177
- `)}`);let l=c;if(n?.catalog){let f=n.maxAutoRefine??0;for(let p=0;p<=f;p++){let m=zr(l,n.catalog);if(m.valid)break;if(p===f)throw new Error(`llmCompose: catalog validation failed after ${f} refine attempts:
98
+ `)}`);let l=c;if(n?.catalog){let f=n.maxAutoRefine??0;for(let p=0;p<=f;p++){let m=oo(l,n.catalog);if(m.valid)break;if(p===f)throw new Error(`llmCompose: catalog validation failed after ${f} refine attempts:
178
99
  ${m.errors.join(`
179
- `)}`);l=await ap(l,`Fix these catalog errors:
100
+ `)}`);l=await lp(l,`Fix these catalog errors:
180
101
  ${m.errors.join(`
181
102
  `)}
182
103
 
183
- Use ONLY functions and sources from the catalog.`,e,{...n,catalogDescription:o})}}return l}async function ap(t,e,n,r){let o=sp;r?.catalogDescription&&(o+=`
104
+ Use ONLY functions and sources from the catalog.`,e,{...n,catalogDescription:o})}}return l}async function lp(t,e,n,r){let o=cp;r?.catalogDescription&&(o+=`
184
105
 
185
106
  Available catalog:
186
107
  ${r.catalogDescription}`),r?.systemPromptExtra&&(o+=`
@@ -190,9 +111,66 @@ ${JSON.stringify(t,null,2)}
190
111
 
191
112
  Modification request: ${e}
192
113
 
193
- Return the complete modified GraphSpec as JSON.`}],u=(await n.invoke(s,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens})).content.trim();u.startsWith("```")&&(u=ip(u));let c;try{c=JSON.parse(u)}catch{throw new Error(`llmRefine: LLM response is not valid JSON: ${u.slice(0,200)}`)}let d=Xn(c);if(!d.valid)throw new Error(`llmRefine: invalid GraphSpec:
114
+ 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=dp(u));let c;try{c=JSON.parse(u)}catch{throw new Error(`llmRefine: LLM response is not valid JSON: ${u.slice(0,200)}`)}let d=rr(c);if(!d.valid)throw new Error(`llmRefine: invalid GraphSpec:
194
115
  ${d.errors.join(`
195
- `)}`);return c}var Ds={};he(Ds,{GuardedExecutionGraph:()=>Ps,guardedExecution:()=>Vg});var Ps=class extends q{enforcer;violations;_target;_defaultActor;constructor(e,n){super(n.name??`${e.name}_guarded`,n.graph),this._target=e,this._defaultActor=n.actor;let r={mode:n.mode??"enforce",name:"enforcer"};n.violationsLimit!=null&&(r.violationsLimit=n.violationsLimit),this.enforcer=Aa(e,n.policies,r),this.violations=this.enforcer.violations,this.mount("enforcer",this.enforcer)}scopedDescribe(e){let n=e?.actor??this._defaultActor,r={...e,...n!=null?{actor:n}:{}};return this._target.describe(r)}get target(){return this._target}};function Vg(t,e){return new Ps(t,e)}var $s={};he($s,{DEFAULT_DECAY_RATE:()=>Wa,DEFAULT_QUEUE_CONFIGS:()=>qa,DEFAULT_SEVERITY_WEIGHTS:()=>Ha,HarnessGraph:()=>Gs,QUEUE_NAMES:()=>Ht,affectedTaskFilter:()=>Ug,beforeAfterCompare:()=>qg,codeChangeBridge:()=>zg,createIntakeBridge:()=>Kg,defaultErrorClassifier:()=>Ka,defaultLlmExecutor:()=>up,defaultLlmVerifier:()=>cp,evalIntakeBridge:()=>Hg,evalSource:()=>Wg,evalVerifier:()=>Zg,harnessLoop:()=>oy,harnessProfile:()=>sy,harnessTrace:()=>my,notifyEffect:()=>Jg,priorityScore:()=>ey,refineExecutor:()=>py,strategyKey:()=>Jr,strategyModel:()=>Ua});oe();Re();function Kg(t,e,n,r){return fe([t],([o])=>{if(o==null)return;let s=n(o);for(let i of s)e.publish(i)},{name:r?.name??"intake-bridge"})}function Hg(t,e,n){let r=n?.defaultSeverity??"medium";return fe([t],([o])=>{if(o==null)return;let s=Array.isArray(o)?o:[o];for(let i of s)for(let a of i.tasks)if(!(a.valid&&a.judge_scores?.every(u=>u.pass))){if(!a.valid&&(!a.judge_scores||a.judge_scores.length===0)){e.publish({source:"eval",summary:`Task ${a.task_id} invalid (model: ${i.model})`,evidence:`Run ${i.run_id}: task produced invalid output`,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:r});continue}if(a.judge_scores)for(let u of a.judge_scores)u.pass||e.publish({source:"eval",summary:`${a.task_id}: ${u.claim} (model: ${i.model})`,evidence:u.reasoning,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:r})}},{name:n?.name??"eval-intake-bridge"})}function Wg(t,e){return be(t,()=>re(e()))}function qg(t,e){return O([t,e],([n,r])=>{let o=n,s=r,i=new Map(o.tasks.map(f=>[f.task_id,f])),a=new Map(s.tasks.map(f=>[f.task_id,f])),u=new Set([...i.keys(),...a.keys()]),c=[],d=[],l=[];for(let f of u){let p=i.get(f),m=a.get(f),h=p?.valid??!1,g=m?.valid??!1,y=p?.judge_scores?p.judge_scores.filter(T=>T.pass).length:void 0,b=m?.judge_scores?m.judge_scores.filter(T=>T.pass).length:void 0,v=y!==void 0&&b!==void 0?b-y:void 0;c.push({taskId:f,before:h,after:g,scoreDiff:v}),h&&!g&&d.push(f),!h&&g&&l.push(f)}return{newFailures:d,resolved:l,taskDeltas:c,overallImproved:l.length>d.length}},{name:"eval-delta"})}function Ug(t,e){let n=e==null?null:Array.isArray(e)?N(e):e,r=[t];return n&&r.push(n),O(r,o=>{let s=o[0],i=n?new Set(o[1]):null,a=new Set;for(let u of s)for(let c of u.affectsEvalTasks??[])(i==null||i.has(c))&&a.add(c);return[...a].sort()},{name:"affected-task-filter"})}function zg(t,e,n,r){let o=r?.defaultSeverity??"high";function s(a){let u=[];for(let c of a.lintErrors??[])u.push({source:"code-change",summary:`Lint: ${c.rule} in ${c.file}:${c.line}`,evidence:c.message,affectsAreas:[c.file],severity:o});for(let c of a.testFailures??[])u.push({source:"test",summary:`Test failure: ${c.testId}`,evidence:c.message,affectsAreas:[c.file],affectsEvalTasks:[c.testId],severity:o});return u}let i=n??s;return fe([t],([a])=>{if(a!=null)for(let u of i(a))e.publish(u)},{name:r?.name??"code-change-bridge"})}function Jg(t,e,n){return fe([t.latest],([r])=>{r!=null&&e(r)},{name:n?.name??"notify-effect"})}oe();function Yg(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let n of t)e+=n.score;return e/t.length}function Qg(t){let{passCount:e,total:n,meanScore:r,threshold:o,missingArtifact:s}=t,i=Number.isFinite(r)?r.toFixed(3):String(r),a=!s&&n>0&&r>=o,u=s?["EXECUTE stage did not emit an artifact; cannot verify reactively"]:a?[`${e}/${n} eval tasks passed; mean score ${i} \u2265 ${o}`]:n===0?["No eval tasks were selected for this item \u2014 cannot verify"]:[`${e}/${n} eval tasks passed; mean score ${i} < threshold ${o}`];return a?{verified:!0,findings:u}:{verified:!1,findings:u,errorClass:"structural"}}function Xg(t){return t.artifact}function Zg(t){let e=t.name??"eval-verifier",n=t.threshold??.5,r=t.toOutput??Qg,o=t.extractArtifact??Xg;return s=>{let i=ut(s,u=>u!=null&&u[0]!=null&&u[1]!=null),a=be(i,([u,c])=>{let d=o(u,c);if(d==null)return N(r({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:n,missingArtifact:!0}));let l=N([d],{name:`${e}/candidates`}),f=N(t.datasetFor(c),{name:`${e}/dataset`}),p=t.evaluator(l,f);return O([p],([m])=>{let h=m;if(h==null)return null;let g=Yg(h),y=h.filter(b=>b.score>=n).length;return r({scores:h,meanScore:g,passCount:y,total:h.length,threshold:n})},{name:`${e}/output`})},{name:e});return ut(a,u=>u!=null)}}xe();oe();ke();oe();var Ht=["auto-fix","needs-decision","investigation","backlog"];function Jr(t,e){return`${t}\u2192${e}`}function Ka(t){let e=t.detail.toLowerCase();return e.includes("parse")||e.includes("json")||e.includes("config")||e.includes("validation")||e.includes("syntax")?"self-correctable":"structural"}var Ha={critical:100,high:70,medium:40,low:10},Wa=Math.LN2/(168*3600),qa={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1,startOpen:!1}};function Ua(){let t=tt({name:"strategy-entries"}),e=O([t.entries],([i])=>{let a=i;return new Map(a)},{name:"strategy-model",equals:(i,a)=>{let u=i,c=a;if(u.size!==c.size)return!1;for(let[d,l]of u){let f=c.get(d);if(!f||l.attempts!==f.attempts||l.successes!==f.successes)return!1}return!0}});function n(i,a,u){let c=Jr(i,a),d=t.get(c),l=(d?.attempts??0)+1,f=(d?.successes??0)+(u?1:0);t.set(c,{rootCause:i,intervention:a,attempts:l,successes:f,successRate:f/l})}function r(i,a){return t.get(Jr(i,a))}let o=e.subscribe(()=>{});function s(){o()}return{node:e,record:n,lookup:r,dispose:s}}function ey(t,e,n,r,o){let s={...Ha,...o?.severityWeights},i=o?.decayRate??Wa,a=o?.effectivenessThreshold??.7,u=o?.effectivenessBoost??15,c=[t,e,n];return r&&c.push(r),O(c,d=>{let l=d[0],f=d[1],p=d[2],m=r?d[3]:0,h=s[l.severity??"medium"],g=($()-p)/1e9,y=vn(h,g,i,0),b=Jr(l.rootCause,l.intervention),v=f.get(b);return v&&v.successRate>=a&&(y+=u),y+=m*20,y},{name:"priority-score"})}var ty=`You are a triage classifier for a reactive collaboration harness.
116
+ `)}`);return c}var pp=`You are a graph architect for GraphReFly, a reactive graph protocol.
117
+
118
+ Given a natural-language description, produce a JSON graph specification with this structure:
119
+
120
+ {
121
+ "name": "<graph_name>",
122
+ "nodes": {
123
+ "<node_name>": {
124
+ "type": "state" | "derived" | "producer" | "effect" | "operator",
125
+ "initial": <initial_value_for_state_nodes>,
126
+ "deps": ["<dep_node_name>", ...],
127
+ "meta": {
128
+ "description": "<human-readable purpose>",
129
+ "type": "string" | "number" | "boolean" | "integer" | "enum",
130
+ "range": [min, max],
131
+ "values": ["a", "b"],
132
+ "format": "currency" | "percentage" | "status",
133
+ "access": "human" | "llm" | "both" | "system",
134
+ "unit": "<unit>",
135
+ "tags": ["<tag>"]
136
+ }
137
+ }
138
+ }
139
+ }
140
+
141
+ Rules:
142
+ - "state" nodes have no deps and hold user/LLM-writable values (knobs). Use "initial" for the starting value.
143
+ - "derived" nodes have deps and compute from them (pure, no side effects).
144
+ - "effect" nodes have deps but produce side effects (no return value).
145
+ - "producer" nodes have no deps but generate values asynchronously.
146
+ - "operator" nodes are parameterized transformations with deps.
147
+ - Use "deps" inside each node to declare dependencies \u2014 no separate "edges" array.
148
+ - meta.description is required for every node.
149
+ - Return ONLY valid JSON, no markdown fences or commentary.`;async function Sg(t,e,n){let o=[{role:"system",content:n?.systemPromptExtra?`${pp}
150
+
151
+ ${n.systemPromptExtra}`:pp},{role:"user",content:t}],s=e.invoke(o,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens}),a=(await kn(s)).content.trim();a.startsWith("```")&&(a=nr(a));let u;try{u=JSON.parse(a)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${a.slice(0,200)}`)}return so(u,{catalog:n?.catalog})}function Ng(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 Eg(t,e){let n=t.describe({actor:e,detail:"full"}),r=[],o=[],s=[];for(let[i,a]of Object.entries(n.nodes)){if(a.type!=="state"||i.includes("::__meta__::")||a.status==="completed"||a.status==="errored")continue;let u=a.meta??{},c=u.access;if(c==="human"||c==="system")continue;let d=u.description??`Set the value of ${i}`,l=Ng(u),f={type:"object",required:["value"],properties:{value:l},additionalProperties:!1},p=i.replace(/::/g,"__");r.push({type:"function",function:{name:p,description:d,parameters:f}}),o.push({name:i,description:d,inputSchema:f});let m=t,h=e,g=a.v;s.push({name:i,description:d,parameters:f,handler(y){return m.set(i,y.value,h?{actor:h}:void 0),y.value},...g!=null?{version:{id:g.id,version:g.version}}:{}})}return{openai:r,mcp:o,definitions:s}}var _g=`You are a reactive graph optimizer for GraphReFly.
152
+
153
+ Given a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.
154
+
155
+ Return ONLY valid JSON with this structure:
156
+ {
157
+ "summary": "<one-line summary of the strategy>",
158
+ "reasoning": "<explanation of why these changes help>",
159
+ "operations": [
160
+ { "type": "add_node", "name": "<name>", "nodeType": "state|derived|effect|producer|operator", "meta": {...}, "initial": <value> },
161
+ { "type": "remove_node", "name": "<name>" },
162
+ { "type": "connect", "from": "<source>", "to": "<target>" },
163
+ { "type": "disconnect", "from": "<source>", "to": "<target>" },
164
+ { "type": "set_value", "name": "<name>", "value": <new_value> },
165
+ { "type": "update_meta", "name": "<name>", "key": "<meta_key>", "value": <new_value> }
166
+ ]
167
+ }
168
+
169
+ Rules:
170
+ - Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).
171
+ - Keep changes minimal \u2014 prefer the smallest set of operations that solves the problem.
172
+ - Return ONLY valid JSON, no markdown fences or commentary.`;async function Mg(t,e,n,r){let{expand:o,...s}=t.describe({actor:r?.actor,detail:"standard"}),i=[{role:"system",content:_g},{role:"user",content:JSON.stringify({graph:s,problem:e})}],a=n.invoke(i,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens}),c=(await kn(a)).content.trim();c.startsWith("```")&&(c=c.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let d;try{d=JSON.parse(c)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${c.slice(0,200)}`)}let l=d;if(typeof l.summary!="string")throw new Error("suggestStrategy: missing 'summary' in response");if(typeof l.reasoning!="string")throw new Error("suggestStrategy: missing 'reasoning' in response");if(!Array.isArray(l.operations))throw new Error("suggestStrategy: missing 'operations' array in response");return{summary:l.summary,reasoning:l.reasoning,operations:l.operations}}var fp=new Set(["state","derived","producer","operator","effect"]);function Og(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"||!fp.has(i.type))&&e.push(`Node "${o}": invalid type "${String(i.type)}" (expected: ${[...fp].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 Us={};ye(Us,{AuditTrailGraph:()=>Ws,PolicyEnforcerGraph:()=>qs,auditTrail:()=>Ag,complianceSnapshot:()=>Lg,policyEnforcer:()=>Ya,reactiveExplainPath:()=>Qa});we();nn();ie();Ne();ne();vo();function hp(t,e){return qe("audit",t,e)}var Cg=new Set(["data","error","complete","teardown"]),Ws=class extends q{entries;count;_log;_target;constructor(e,n){super(n.name??`${e.name}_audit`,n.graph),this._target=e,this._log=We([],{name:"entries",...n.maxSize!=null?{maxSize:n.maxSize}:{}}),this.entries=this._log.entries,this.add(this.entries,{name:"entries"}),this.count=E([this.entries],([u])=>u.length,{name:"count",describeKind:"derived",meta:hp("count")}),this.add(this.count,{name:"count"}),this.addDisposer(re(this.count));let r=n.includeTypes!=null?new Set(n.includeTypes):Cg,o=n.filter,s=0,i=e.observe({timeline:!0,structured:!0}),a=i.onEvent(u=>{if(u.type==="derived")return;let c=u.type;if(!r.has(c))return;let d=u.path??"",l={seq:s++,timestamp_ns:u.timestamp_ns??V(),wall_clock_ns:le(),path:d,type:c},p=(d?Ja(e,d):void 0)?.lastMutation;p!=null&&(l.actor=p.actor),c==="data"&&(l.value=u.data),c==="error"&&(l.error=u.data);let m=d?Pg(e,d):void 0;m!=null&&(l.annotation=m),!(o!=null&&!o(l))&&this._log.append(l)});this.addDisposer(()=>{a(),i.dispose()}),this.addDisposer(()=>this._log.disposeAllViews())}all(){return this.entries.cache??[]}byNode(e){return this.all().filter(n=>n.path===e)}byActor(e){return this.all().filter(n=>n.actor?.id===e)}byActorType(e){return this.all().filter(n=>n.actor?.type===e)}byTimeRange(e,n){return this.all().filter(r=>!(r.timestamp_ns<e||n!=null&&r.timestamp_ns>=n))}get target(){return this._target}};function Ag(t,e={}){return new Ws(t,e)}var qs=class extends q{policies;violations;violationCount;_target;_mode;_currentGuard;constructor(e,n,r){super(r.name??`${e.name}_policy`,r.graph),this._target=e,this._mode=r.mode??"audit";let o=Ig(n)?n:N(n,{name:"policies"});this.policies=o,this.add(this.policies,{name:"policies"}),this.violations=new ut("violations",{retainedLimit:r.violationsLimit??1e3}),this.mount("violations",this.violations),this.violationCount=E([this.violations.events],([c])=>c.length,{name:"violationCount",describeKind:"derived",meta:hp("policy_violation_count")}),this.add(this.violationCount,{name:"violationCount"}),this.addDisposer(re(this.violationCount));let i=o.cache??[];this._currentGuard=vr(i);let a=o.subscribe(c=>{for(let d of c)d[0]===S&&(i=d[1]??[],this._currentGuard=vr(i))});this.addDisposer(a);let u=r.paths!=null?[...r.paths]:mp(e);if(this._mode==="enforce"){let c=new Map,d=l=>{if(c.has(l))return;let f=Ja(e,l);if(!(f instanceof Oe))return;let p=(m,h)=>{let g=this._currentGuard(m,h);return g||this._publishViolation(m,h,l,"blocked"),g};c.set(l,f._pushGuard(p))};for(let l of u)d(l);if(r.paths==null){let l=Mt(e,(f,p,m)=>{if(f.kind==="added")if(f.nodeKind==="node")d(`${m}${f.name}`);else{let h=p._mounts.get(f.name);if(!(h instanceof q))return;let g=`${m}${f.name}::`,y=mp(h);for(let b of y)d(b===""?`${m}${f.name}`:`${g}${b}`)}else if(f.kind==="removed")if(f.nodeKind==="node"){let h=`${m}${f.name}`,g=c.get(h);g!=null&&(g(),c.delete(h))}else{let h=`${m}${f.name}`,g=`${h}::`;for(let[y,b]of c)(y===h||y.startsWith(g))&&(b(),c.delete(y))}});this.addDisposer(l)}else{let l=e.topology.subscribe(f=>{for(let p of f){if(p[0]!==S)continue;let m=p[1];if(m.kind!=="removed"||m.nodeKind!=="node")continue;let h=c.get(m.name);h!=null&&(h(),c.delete(m.name))}});this.addDisposer(l)}this.addDisposer(()=>{for(let l of c.values())l();c.clear()})}else{let c=e.observe({timeline:!0,structured:!0}),d=c.onEvent(l=>{if(l.type!=="data"&&l.type!=="error")return;let f=l.path??"";if(!f||r.paths!=null&&!r.paths.includes(f))return;let p=l.actor??Ja(e,f)?.lastMutation?.actor;if(p==null)return;let m="write";this._currentGuard(p,m)||this._publishViolation(p,m,f,"observed")});this.addDisposer(()=>{d(),c.dispose()})}}_publishViolation(e,n,r,o){this.violations.publish({timestamp_ns:V(),wall_clock_ns:le(),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 Ya(t,e,n={}){return new qs(t,e,n)}function Qa(t,e,n,r){return t.explain(e,n,{reactive:!0,...r})}function Lg(t,e={}){let n={format_version:1,timestamp_ns:V(),wall_clock_ns:le(),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=Dg(n);return{...n,fingerprint:r}}function Ig(t){return typeof t=="object"&&t!==null&&"subscribe"in t}function Ja(t,e){try{return t.node(e)}catch{return}}function Pg(t,e){try{return t.annotation(e)}catch{return}}function mp(t){let e=t.describe({detail:"minimal"});return Object.keys(e.nodes)}function Dg(t){return Dt(JSON.stringify(Gg(t)))}function Gg(t){let e=new Set,n=r=>{if(r===void 0)return{__undefined:!0};if(r===null)return null;let o=typeof r;if(o==="bigint")return{__bigint:r.toString()};if(o!=="object")return r;let s=r;if(e.has(s))return{__circular:!0};e.add(s);try{if(Array.isArray(s))return s.map(n);if(s instanceof Date)return{__date:s.toISOString()};if(s instanceof RegExp)return{__regexp:{source:s.source,flags:s.flags}};if(s instanceof Map)return{__map:[...s.entries()].map(([u,c])=>[n(u),n(c)])};if(s instanceof Set)return{__set:[...s].map(n)};if(ArrayBuffer.isView(s)){let a=s,u=new Array(a.length);for(let c=0;c<a.length;c++)u[c]=a[c]??0;return{__typed_array:{ctor:s.constructor.name,data:u}}}let i={};for(let a of Object.keys(s).sort())i[a]=n(s[a]);return i}finally{e.delete(s)}};return n(t)}var Js={};ye(Js,{demoShell:()=>Wg});_e();ne();we();Ne();ne();function Fg(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 gp=new Set(["\uFF0C","\uFF0E","\uFF01","\uFF1A","\uFF1B","\uFF1F","\u3001","\u3002","\u30FB","\uFF09","\u3015","\u3009","\u300B","\u300D","\u300F","\u3011"]),$g=new Set([".",",","!","?",":",";",")","]","}","%",'"',"\u201D","\u2019","\xBB","\u203A","\u2026"]);function Bg(t){return t.replace(/[\t\n\r\f ]+/g," ").replace(/^ | $/g,"")}function jg(t){let e=new Intl.Segmenter(void 0,{granularity:"word"}),n=[];for(let r of e.segment(t)){let o=r.segment,s=r.isWordLike??!1,i=[],a=[],u=[],c="",d=null;for(let l of o){let f;l===" "?f="space":l==="\u200B"?f="zero-width-break":l==="\xAD"?f="soft-hyphen":l===`
173
+ `?f="hard-break":f="text",d!==null&&f===d?c+=l:(d!==null&&(i.push(c),a.push(d==="text"&&s),u.push(d)),c=l,d=f)}d!==null&&(i.push(c),a.push(d==="text"&&s),u.push(d)),n.push({texts:i,isWordLike:a,kinds:u})}return n}function Pt(t,e,n,r,o){let s=Bg(t);if(s.length===0)return[];let i=jg(s),a=new Intl.Segmenter(void 0,{granularity:"grapheme"}),u=[],c=[],d=[];for(let y of i)for(let b=0;b<y.texts.length;b++)u.push(y.texts[b]),c.push(y.kinds[b]),d.push(y.isWordLike[b]);let l=[],f=[],p=[];for(let y=0;y<u.length;y++){let b=u[y],v=c[y],T=d[y];if(v==="text"&&!T&&l.length>0&&f[f.length-1]==="text"&&b.length===1&&($g.has(b)||gp.has(b))){l[l.length-1]+=b;continue}if(b==="-"&&l.length>0&&f[f.length-1]==="text"&&p[p.length-1]){l[l.length-1]+=b;continue}l.push(b),f.push(v),p.push(T)}let m=r.get(e);m||(m=new Map,r.set(e,m));function h(y){let b=m.get(y);if(b===void 0){o&&(o.misses+=1);let v=n.measureSegment(y,e).width;b=Number.isFinite(v)&&v>=0?v:0,m.set(y,b)}else o&&(o.hits+=1);return b}let g=[];for(let y=0;y<l.length;y++){let b=l[y],v=f[y];if(v!=="text"){g.push({text:b,width:v==="space"?h(" ")*b.length:0,kind:v,graphemeWidths:null});continue}if(Fg(b)){let k="";for(let x of a.segment(b)){let R=x.segment;if(k.length>0&&gp.has(R)){k+=R;continue}if(k.length>0){let _=h(k);g.push({text:k,width:_,kind:"text",graphemeWidths:null})}k=R}if(k.length>0){let x=h(k);g.push({text:k,width:x,kind:"text",graphemeWidths:null})}continue}let T=h(b),w=null;if(p[y]&&b.length>1){let k=[];for(let x of a.segment(b))k.push(h(x.segment));k.length>1&&(w=k)}g.push({text:b,width:T,kind:"text",graphemeWidths:w})}return g}function Sn(t,e,n,r,o){if(t.length===0)return{lines:[],lineCount:0};let s=[],i=0,a=!1,u=0,c=0,d=0,l=0,f=-1,p=0,m=o.get(r);m||(m=new Map,o.set(r,m));let h=m.get("-");h===void 0&&(h=n.measureSegment("-",r).width,m.set("-",h));function g(w=d,k=l,x=i){let R="";for(let _=u;_<w;_++){let G=t[_];if(!(G.kind==="soft-hyphen"||G.kind==="hard-break"))if(_===u&&c>0&&G.graphemeWidths){let P=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(G.text)].map(C=>C.segment);R+=P.slice(c).join("")}else R+=G.text}if(k>0&&w<t.length){let _=t[w],L=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(_.text)].map(C=>C.segment),P=u===w?c:0;R+=L.slice(P,k).join("")}w>0&&t[w-1]?.kind==="soft-hyphen"&&!(u===w&&c>0)&&(R+="-"),s.push({text:R,width:x,startSegment:u,startGrapheme:c,endSegment:w,endGrapheme:k}),i=0,a=!1,f=-1,p=0}function y(w){return w==="space"||w==="zero-width-break"||w==="soft-hyphen"}function b(w,k,x){a=!0,u=w,c=k,d=w+1,l=0,i=x}function v(w,k,x){a=!0,u=w,c=k,d=w,l=k+1,i=x}for(let w=0;w<t.length;w++){let k=t[w];if(k.kind==="hard-break"){a?g():s.push({text:"",width:0,startSegment:w,startGrapheme:0,endSegment:w,endGrapheme:0}),u=w+1,c=0;continue}let x=k.width;if(!a){x>e&&k.graphemeWidths?T(w,0,k.graphemeWidths):b(w,0,x),y(k.kind)&&(f=w+1,p=k.kind==="space"?i-x:i);continue}let R=i+x;if(R>e+.005){if(y(k.kind)){i+=x,d=w+1,l=0,g(w+1,0,k.kind==="space"?i-x:i);continue}if(f>=0){g(f,0,p),w--;continue}if(x>e&&k.graphemeWidths){g(),T(w,0,k.graphemeWidths);continue}g(),w--;continue}i=R,d=w+1,l=0,y(k.kind)&&(f=w+1,p=k.kind==="space"?i-x:i)}return a&&g(),{lines:s,lineCount:s.length};function T(w,k,x){for(let R=k;R<x.length;R++){let _=x[R];if(!a){v(w,R,_);continue}i+_>e+.005?(g(),v(w,R,_)):(i+=_,d=w,l=R+1)}a&&d===w&&l===x.length&&(d=w+1,l=0)}}function Xa(t){return t==="space"||t==="zero-width-break"||t==="soft-hyphen"}var Za=null;function Vg(){return Za===null&&(Za=new Intl.Segmenter(void 0,{granularity:"grapheme"})),Za}function yp(t,e,n){if(e===0&&n<0)return t.text;let r=[...Vg().segment(t.text)].map(s=>s.segment),o=n<0?r.length:n;return r.slice(e,o).join("")}function Jt(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+=yp(u,n,-1):i+=u.text)}if(o>0&&r<t.length){let a=t[r];i+=yp(a,e===r?n:0,o)}return s&&(i+="-"),i}function Kg(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 eu(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=Kg(r),a=o,u=o===e.segmentIndex?s:0,c=0,d=a,l=0,f=!1,p=-1,m=0,h=0,g=!1,y=(w,k,x,R)=>{p=w,m=k,h=x,g=R==="soft-hyphen"},b=(w,k,x)=>{for(let R=k;R<x.length;R++){let _=x[R];if(!f){c=_,d=w,l=R+1,f=!0;continue}if(c+_>n+.005)return!0;c+=_,d=w,l=R+1}return d===w&&l===x.length&&(d=w+1,l=0),!1};if(u>0&&a<t.length){let w=t[a];if(w.graphemeWidths){if(b(a,u,w.graphemeWidths))return{text:Jt(t,a,u,d,l,!1),width:c,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}};o=d}}for(;o<t.length;){let w=t[o];if(w.kind==="hard-break"){if(f){let R=d>0&&t[d-1]?.kind==="soft-hyphen";return{text:Jt(t,a,u,d,l,R),width:c+(R?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}}return{text:"",width:0,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:o+1,graphemeIndex:0}}}let k=w.width;if(!f){if(k>n&&w.graphemeWidths){if(b(o,0,w.graphemeWidths))return{text:Jt(t,a,u,d,l,!1),width:c,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}};o=d;continue}c=k,d=o+1,l=0,f=!0,Xa(w.kind)&&y(o+1,0,w.kind==="space"?c-k:c,w.kind),o+=1;continue}let x=c+k;if(x>n+.005){if(Xa(w.kind)){d=o+1,l=0;let _=w.kind==="soft-hyphen",G=w.kind==="space"?c:c+(_?i:0);return{text:Jt(t,a,u,d,l,_),width:G,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}}return p>=0?{text:Jt(t,a,u,p,m,g),width:h+(g?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:p,graphemeIndex:m}}:k>n&&w.graphemeWidths?{text:Jt(t,a,u,d,l,!1),width:c,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}:{text:Jt(t,a,u,d,l,!1),width:c,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}}c=x,d=o+1,l=0,Xa(w.kind)&&y(o+1,0,w.kind==="space"?c-k:c,w.kind),o+=1}if(!f)return null;let v=d>0&&t[d-1]?.kind==="soft-hyphen";return{text:Jt(t,a,u,d,l,v),width:c+(v?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}}function tu(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 zs(t,e,n){let r=[],o=new Intl.Segmenter(void 0,{granularity:"grapheme"});for(let s=0;s<t.lines.length;s++){let i=t.lines[s],a=s*n,u=0;for(let c=i.startSegment;c<e.length;c++){let d=e[c];if(d.kind==="soft-hyphen"||d.kind==="hard-break"){if(c>=i.endSegment&&i.endGrapheme===0)break;continue}let l=[...o.segment(d.text)].map(m=>m.segment);if(l.length===0)continue;let f=c===i.startSegment?i.startGrapheme:0,p;if(c<i.endSegment)p=l.length;else if(c===i.endSegment&&i.endGrapheme>0)p=i.endGrapheme;else break;for(let m=f;m<p;m++){let h=d.graphemeWidths?d.graphemeWidths[m]:d.width/l.length;r.push({x:u,y:a,width:h,height:n,line:s}),u+=h}}}return r}function Hg(t){let{adapter:e,name:n="reactive-layout"}=t,r=new q(n),o=new Map,s=N(t.text??"",{name:"text"}),i=N(t.font??"16px sans-serif",{name:"font"}),a=N(t.lineHeight??20,{name:"line-height"}),u=N(Math.max(0,t.maxWidth??800),{name:"max-width"});function c(m,h){if(m===null||h===null)return m===h;if(m.length!==h.length)return!1;for(let g=0;g<m.length;g++)if(m[g]!==h[g])return!1;return!0}let d=K([s,i],(m,h,g)=>{let y=m[0],b=y!=null&&y.length>0?y.at(-1):g.prevData[0],v=m[1],T=v!=null&&v.length>0?v.at(-1):g.prevData[1],w=V(),k={hits:0,misses:0},x=Pt(b,T,e,o,k),R=V()-w,_=k.hits+k.misses,G=_===0?1:k.hits/_,L=d.meta;L&&(pt(L["cache-hit-rate"],G),pt(L["segment-count"],x.length),pt(L["layout-time-ns"],R)),h.emit(x);let P=()=>{o.clear(),e.clearCache?.()};return{deactivate:P,invalidate:P}},{name:"segments",describeKind:"derived",meta:{"cache-hit-rate":0,"segment-count":0,"layout-time-ns":0},equals:(m,h)=>{let g=m,y=h;if(g==null||y==null)return g===y;if(g.length!==y.length)return!1;for(let b=0;b<g.length;b++){let v=g[b],T=y[b];if(v.text!==T.text||v.width!==T.width||v.kind!==T.kind||!c(v.graphemeWidths??null,T.graphemeWidths??null))return!1}return!0}}),l=E([d,u,i],([m,h,g])=>Sn(m,h,e,g,o),{name:"line-breaks",equals:(m,h)=>{let g=m,y=h;if(g==null||y==null)return g===y;if(g.lineCount!==y.lineCount)return!1;for(let b=0;b<g.lines.length;b++){let v=g.lines[b],T=y.lines[b];if(v.text!==T.text||v.width!==T.width||v.startSegment!==T.startSegment||v.startGrapheme!==T.startGrapheme||v.endSegment!==T.endSegment||v.endGrapheme!==T.endGrapheme)return!1}return!0}}),f=E([l,a],([m,h])=>m.lineCount*h,{name:"height"}),p=E([l,d,a],([m,h,g])=>zs(m,h,g),{name:"char-positions",equals:(m,h)=>{let g=m,y=h;if(g==null||y==null)return g===y;if(g.length!==y.length)return!1;for(let b=0;b<g.length;b++)if(g[b].x!==y[b].x||g[b].y!==y[b].y||g[b].width!==y[b].width)return!1;return!0}});return r.add(s,{name:"text"}),r.add(i,{name:"font"}),r.add(a,{name:"line-height"}),r.add(u,{name:"max-width"}),r.add(d,{name:"segments"}),r.add(l,{name:"line-breaks"}),r.add(f,{name:"height"}),r.add(p,{name:"char-positions"}),{graph:r,setText:m=>r.set("text",m),setFont:m=>r.set("font",m),setLineHeight:m=>r.set("line-height",m),setMaxWidth:m=>r.set("max-width",Math.max(0,m)),segments:d,lineBreaks:l,height:f,charPositions:p}}function io(t){return Math.max(0,Math.min(1,t))}function Wg(t){let e=io(t?.mainRatio??.65),n=io(t?.sideSplit??.5),r=Math.max(0,t?.viewportWidth??1280),o=t?.nodeRegistry??new Map,s=t?.adapter??null,i=t?.layoutFont??"14px monospace",a=t?.onHighlight,u=new q("demo-shell"),c=N(e,{name:"pane/main-ratio"}),d=N(n,{name:"pane/side-split"}),l=N(null,{name:"pane/fullscreen"}),f=N(r,{name:"viewport/width"});u.add(c,{name:"pane/main-ratio"}),u.add(d,{name:"pane/side-split"}),u.add(l,{name:"pane/fullscreen"}),u.add(f,{name:"viewport/width"});let p=E([c,f,l],([A,D,I])=>{let J=A,H=D,ae=I;return ae==="main"?H:ae==="graph"||ae==="code"?0:Math.round(H*J)},{name:"pane/main-width"}),m=E([p,f,l],([A,D,I])=>{let J=I,H=D;return J==="main"?0:J==="graph"||J==="code"?H:H-A},{name:"pane/side-width"}),h=E([d,l],([A,D])=>{let I=D;return I==="graph"?1:I==="code"||I==="main"?0:io(A)},{name:"pane/graph-height-ratio"}),g=E([h,l],([A,D])=>{let I=D;return I==="code"?1:I==="graph"||I==="main"?0:1-A},{name:"pane/code-height-ratio"});u.add(p,{name:"pane/main-width"}),u.add(m,{name:"pane/side-width"}),u.add(h,{name:"pane/graph-height-ratio"}),u.add(g,{name:"pane/code-height-ratio"});let y=N(null,{name:"demo/graph-ref"}),b=N(0,{name:"demo/graph-tick"});u.add(y,{name:"demo/graph-ref"}),u.add(b,{name:"demo/graph-tick"});let v=E([y,b],([A,D])=>{let I=A;return I?I.describe({format:"mermaid"}):""},{name:"graph/mermaid"}),T=E([y,b],([A,D])=>{let I=A;if(!I)return null;let{expand:J,...H}=I.describe({detail:"standard"});return H},{name:"graph/describe"});u.add(v,{name:"graph/mermaid"}),u.add(T,{name:"graph/describe"});let w=N(null,{name:"hover/target"});u.add(w,{name:"hover/target"});let k=E([w],([A])=>{let D=A;if(!D)return null;let I=o.get(D.id);return I?I.codeLine:null},{name:"highlight/code-scroll"}),x=E([w],([A])=>{let D=A;if(!D)return null;let I=o.get(D.id);return I?I.visualSelector:null},{name:"highlight/visual"}),R=E([w],([A])=>{let D=A;return D?D.id:null},{name:"highlight/graph"});if(u.add(k,{name:"highlight/code-scroll"}),u.add(x,{name:"highlight/visual"}),u.add(R,{name:"highlight/graph"}),a?.codeScroll){let A=a.codeScroll,D=me([k],([I])=>{A(I)});u.add(D,{name:"highlight/apply-code-scroll"})}if(a?.visual){let A=a.visual,D=me([x],([I])=>{A(I)});u.add(D,{name:"highlight/apply-visual"})}if(a?.graph){let A=a.graph,D=me([R],([I])=>{A(I)});u.add(D,{name:"highlight/apply-graph"})}let _=N(null,{name:"inspect/selected-node"});u.add(_,{name:"inspect/selected-node"});let G=_t("standard"),L=E([_,y,b],([A,D,I])=>{let J=D,H=A;if(!J||!H)return null;try{let ae=J.resolve(H),j=Er(ae,G);return{path:H,...j,value:ae.cache}}catch{return null}},{name:"inspect/node-detail"}),P=E([y,b],([A,D])=>{let I=A;return I?I.trace():[]},{name:"inspect/trace-log"});u.add(L,{name:"inspect/node-detail"}),u.add(P,{name:"inspect/trace-log"});let C=N(!1,{name:"meta/debug"});u.add(C,{name:"meta/debug"});let B=E([C,b],([A,D])=>A?u.describe({format:"mermaid"}):"",{name:"meta/shell-mermaid"});u.add(B,{name:"meta/shell-mermaid"});let te=N("",{name:"layout/code-text"});if(u.add(te,{name:"layout/code-text"}),s){let A=new Map,D=E([T],([H])=>{let ae=H;if(!ae)return new Map;let j=new Map;for(let[U]of Object.entries(ae.nodes)){let he=Pt(U,i,s,A),ue=Sn(he,1/0,s,i,A),oe=ue.lines.reduce((Se,Q)=>Math.max(Se,Q.width),0),Z=ue.lineCount*20;j.set(U,{width:oe,height:Z})}return j},{name:"layout/graph-labels",equals:(H,ae)=>{if(H===ae)return!0;let j=H,U=ae;if(j.size!==U.size)return!1;for(let[he,ue]of j){let oe=U.get(he);if(!oe||oe.width!==ue.width||oe.height!==ue.height)return!1}return!0}}),I=E([te,m],([H,ae])=>{let j=H;if(!j)return{lineCount:0,lines:[]};let U=Pt(j,i,s,A),he=ae-40;return Sn(U,Math.max(100,he),s,i,A)},{name:"layout/code-lines"}),J=E([D],([H])=>{let ae=H;if(ae.size===0)return 200;let j=0;for(let{width:U}of ae.values())U>j&&(j=U);return Math.max(200,Math.round(j+80))},{name:"layout/side-width-hint"});u.add(D,{name:"layout/graph-labels"}),u.add(I,{name:"layout/code-lines"}),u.add(J,{name:"layout/side-width-hint"})}let F=0;return{graph:u,setMainRatio(A){u.set("pane/main-ratio",io(A))},setSideSplit(A){u.set("pane/side-split",io(A))},setFullscreen(A){u.set("pane/fullscreen",A)},setViewportWidth(A){u.set("viewport/width",Math.max(0,A))},setHoverTarget(A){u.set("hover/target",A)},setDemoGraph(A){u.set("demo/graph-ref",A)},bumpGraphTick(){u.set("demo/graph-tick",++F)},selectNode(A){u.set("inspect/selected-node",A)},setMetaDebug(A){u.set("meta/debug",A)},setCodeText(A){u.set("layout/code-text",A)},batch(A){X(A)},destroy(){u.destroy()}}}var Ys={};ye(Ys,{contentModerationGraph:()=>zg,dataQualityGraph:()=>Jg,issueTrackerGraph:()=>Ug,observabilityGraph:()=>qg});_e();ne();function Ae(t,e){return qe("domain_template",t,e)}function qg(t,e){let n=new q(t,e);n.add(e.source,{name:"source"});let r=[{name:"errors",classify:T=>nu(T,"error")},{name:"traces",classify:T=>nu(T,"trace")},{name:"metrics",classify:T=>nu(T,"metric")}],o=e.branches??r,s=o.map(T=>({name:T.name,classify:T.classify})),i=Ur("stratify",e.source,s);n.mount("stratify",i);let a=o.map(T=>{try{let w=n.resolve(`stratify::branch/${T.name}`);return E([w],([k])=>k,{initial:null})}catch{return N(null)}}),u=e.correlate??(T=>T),c=E(a,T=>u(T),{meta:Ae("observability",{stage:"correlate"})});n.add(c,{name:"correlate"});let d=e.sloCheck??(()=>({pass:!0})),l=E([c],T=>T[0],{meta:Ae("observability",{stage:"slo_value"})}),f=E([l],T=>d(T[0]),{meta:Ae("observability",{stage:"slo_verified"})});n.add(l,{name:"slo_value"}),n.add(f,{name:"slo_verified"});let p=e.weights??o.map(()=>1),m=a.map(T=>E([T],w=>w[0]!=null?1:0)),h=p.map(T=>N(T));for(let T=0;T<m.length;T++)n.add(m[T],{name:`__signal_${T}`}),n.add(h[T],{name:`__weight_${T}`});let g=no(m,h);n.add(g,{name:"alerts"});let y=E([g,f],T=>({scored:T[0],slo:T[1]}),{meta:Ae("observability",{stage:"output"})});n.add(y,{name:"output"});let b=N(null,{meta:Ae("observability",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=E([f],T=>{let w=T[0];return w&&w.pass===!1?w:null},{meta:Ae("observability",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),zt(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??5}),n}function Ug(t,e){let n=new q(t,e);n.add(e.source,{name:"source"});let r=0,o=T=>({id:`issue-${++r}`,title:String(T),severity:1,source:"unknown",raw:T}),s=e.extract??o,i=E([e.source],T=>s(T[0]),{meta:Ae("issue_tracker",{stage:"extract"})});n.add(i,{name:"extract"});let a=e.verify??(()=>({valid:!0})),u=E([i],T=>{let w=T[0];return{issue:w,verification:a(w)}},{meta:Ae("issue_tracker",{stage:"verify"})});n.add(u,{name:"verify"});let c=N([],{meta:Ae("issue_tracker",{stage:"known_patterns"})});n.add(c,{name:"known_patterns"});let d=e.detectRegression??(()=>({regression:!1})),l=E([i,c],T=>{let w=T[0],k=T[1];return{issue:w,regression:d(w,k)}},{meta:Ae("issue_tracker",{stage:"regression"})});n.add(l,{name:"regression"});let f=E([i],T=>T[0]?.severity??0),p=E([l],T=>T[0]?.regression?2:0);n.add(f,{name:"__severity_signal"}),n.add(p,{name:"__regression_signal"});let m=N(1),h=N(1.5);n.add(m,{name:"__severity_weight"}),n.add(h,{name:"__regression_weight"});let g=no([f,p],[m,h]);n.add(g,{name:"priority"});let y=E([u,l,g],T=>({verified:T[0],regression:T[1],priority:T[2]}),{meta:Ae("issue_tracker",{stage:"output"})});n.add(y,{name:"output"});let b=N(null,{meta:Ae("issue_tracker",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=E([u],T=>{let w=T[0];if(w){let k=w.verification;if(k&&k.valid===!1)return w}return null},{meta:Ae("issue_tracker",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),zt(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??3}),n}function zg(t,e){let n=new q(t,e);n.add(e.source,{name:"source"});let r=v=>({label:"review",confidence:.5,original:v}),o=e.classify??r,s=E([e.source],v=>o(v[0]),{meta:Ae("content_moderation",{stage:"classify"})});n.add(s,{name:"classify"});let i=Ur("stratify",s,[{name:"safe",classify:v=>v.label==="safe"},{name:"review",classify:v=>v.label==="review"},{name:"block",classify:v=>v.label==="block"}]);n.mount("stratify",i);let a=We([],{name:"review_queue",maxSize:e.maxQueueSize});n.add(a.entries,{name:"review_queue"});let u;try{u=n.resolve("stratify::branch/review")}catch{u=N(null),n.add(u,{name:"__review_fallback"})}let c=me([u],v=>{let T=v[0];T&&a.append(T)});n.add(c,{name:"__review_accumulator"}),n.addDisposer(re(c));let d=N({},{meta:Ae("content_moderation",{stage:"policy",access:"both",description:"Moderation policy rules \u2014 updated via feedback"})});n.add(d,{name:"policy"});let l=e.weights??[.1,1,2],f=E([s],v=>v[0]?.confidence??0),p=E([s],v=>{let T=v[0];return T?T.label==="block"?l[2]:T.label==="review"?l[1]:l[0]:0});n.add(f,{name:"__confidence_signal"}),n.add(p,{name:"__severity_signal"});let m=N(1),h=N(1);n.add(m,{name:"__w_confidence"}),n.add(h,{name:"__w_severity"});let g=no([f,p],[m,h]);n.add(g,{name:"priority"});let y=E([s,g],v=>({classification:v[0],priority:v[1]}),{meta:Ae("content_moderation",{stage:"output"})});n.add(y,{name:"output"});let b=E([a.entries,d],v=>{let T=v[0];if(T&&T.length>0){let w=T[T.length-1];if(w&&w.falsePositive)return w}return null},{meta:Ae("content_moderation",{stage:"feedback_condition"})});return n.add(b,{name:"feedback_condition"}),zt(n,"feedback_condition","policy",{maxIterations:e.maxFeedbackIterations??5}),n}function Jg(t,e){let n=new q(t,e);n.add(e.source,{name:"source"});let r=e.validate??(g=>({valid:!0,errors:[],record:g})),o=E([e.source],g=>g[0]!=null?r(g[0]):void 0,{meta:Ae("data_quality",{stage:"validate"})});n.add(o,{name:"validate"});let s=e.detectAnomaly??(g=>({anomaly:!1,score:0,record:g})),i=E([e.source],g=>g[0]!=null?s(g[0]):void 0,{meta:Ae("data_quality",{stage:"anomaly"})});n.add(i,{name:"anomaly"});let a=N(null,{meta:Ae("data_quality",{stage:"baseline",description:"Rolling baseline for drift detection"})});n.add(a,{name:"baseline"});let u=me([o],g=>{let y=g[0];y?.valid&&X(()=>{a.emit(y.record)})});n.add(u,{name:"__baseline_updater"}),re(u);let c=e.detectDrift??(()=>({drift:!1})),d=E([e.source,a],g=>c(g[0],g[1]),{meta:Ae("data_quality",{stage:"drift"})});n.add(d,{name:"drift"});let l=e.suggest??(()=>null),f=E([o,i],g=>l({validation:g[0],anomaly:g[1]}),{meta:Ae("data_quality",{stage:"remediate"})});n.add(f,{name:"remediate"});let p=E([o,i,d,f],g=>({validation:g[0],anomaly:g[1],drift:g[2],remediation:g[3]}),{meta:Ae("data_quality",{stage:"output"})});n.add(p,{name:"output"});let m=N([],{meta:Ae("data_quality",{stage:"validation_rules"})});n.add(m,{name:"validation_rules"});let h=E([i],g=>{let y=g[0];return y?.anomaly?y:null},{meta:Ae("data_quality",{stage:"feedback_condition"})});return n.add(h,{name:"feedback_condition"}),zt(n,"feedback_condition","validation_rules",{maxIterations:e.maxFeedbackIterations??3}),n}function nu(t,e){if(t==null||typeof t!="object")return!1;let n=t;return n.type===e||n.kind===e}var Xs={};ye(Xs,{GuardedExecutionGraph:()=>Qs,guardedExecution:()=>Yg});var Qs=class extends q{enforcer;violations;_target;_defaultActor;constructor(e,n){super(n.name??`${e.name}_guarded`,n.graph),this._target=e,this._defaultActor=n.actor;let r={mode:n.mode??"enforce",name:"enforcer"};n.violationsLimit!=null&&(r.violationsLimit=n.violationsLimit),this.enforcer=Ya(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 Yg(t,e){return new Qs(t,e)}var ti={};ye(ti,{DEFAULT_DECAY_RATE:()=>su,DEFAULT_QUEUE_CONFIGS:()=>iu,DEFAULT_SEVERITY_WEIGHTS:()=>ou,HarnessGraph:()=>Zs,QUEUE_NAMES:()=>Yt,affectedTaskFilter:()=>ty,beforeAfterCompare:()=>ey,codeChangeBridge:()=>ny,createIntakeBridge:()=>Qg,defaultErrorClassifier:()=>ru,defaultLlmExecutor:()=>bp,defaultLlmVerifier:()=>vp,evalIntakeBridge:()=>Xg,evalSource:()=>Zg,evalVerifier:()=>ay,harnessLoop:()=>py,harnessProfile:()=>fy,harnessTrace:()=>ky,notifyEffect:()=>ry,priorityScore:()=>uy,refineExecutor:()=>Ty,strategyKey:()=>ao,strategyModel:()=>au});ne();ve();function Qg(t,e,n,r){return me([t],([o])=>{if(o==null)return;let s=n(o);for(let i of s)e.publish(i)},{name:r?.name??"intake-bridge"})}function Xg(t,e,n){let r=n?.defaultSeverity??"medium";return me([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 Zg(t,e){return Te(t,()=>z(e()))}function ey(t,e){return E([t,e],([n,r])=>{let o=n,s=r,i=new Map(o.tasks.map(f=>[f.task_id,f])),a=new Map(s.tasks.map(f=>[f.task_id,f])),u=new Set([...i.keys(),...a.keys()]),c=[],d=[],l=[];for(let f of u){let p=i.get(f),m=a.get(f),h=p?.valid??!1,g=m?.valid??!1,y=p?.judge_scores?p.judge_scores.filter(T=>T.pass).length:void 0,b=m?.judge_scores?m.judge_scores.filter(T=>T.pass).length:void 0,v=y!==void 0&&b!==void 0?b-y:void 0;c.push({taskId:f,before:h,after:g,scoreDiff:v}),h&&!g&&d.push(f),!h&&g&&l.push(f)}return{newFailures:d,resolved:l,taskDeltas:c,overallImproved:l.length>d.length}},{name:"eval-delta"})}function ty(t,e){let n=e==null?null:Array.isArray(e)?N(e):e,r=[t];return n&&r.push(n),E(r,o=>{let s=o[0],i=n?new Set(o[1]):null,a=new Set;for(let u of s)for(let c of u.affectsEvalTasks??[])(i==null||i.has(c))&&a.add(c);return[...a].sort()},{name:"affected-task-filter"})}function ny(t,e,n,r){let o=r?.defaultSeverity??"high";function s(a){let u=[];for(let c of a.lintErrors??[])u.push({source:"code-change",summary:`Lint: ${c.rule} in ${c.file}:${c.line}`,evidence:c.message,affectsAreas:[c.file],severity:o});for(let c of a.testFailures??[])u.push({source:"test",summary:`Test failure: ${c.testId}`,evidence:c.message,affectsAreas:[c.file],affectsEvalTasks:[c.testId],severity:o});return u}let i=n??s;return me([t],([a])=>{if(a!=null)for(let u of i(a))e.publish(u)},{name:r?.name??"code-change-bridge"})}function ry(t,e,n){return me([t.latest],([r])=>{r!=null&&e(r)},{name:n?.name??"notify-effect"})}ne();function oy(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 sy(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 iy(t){return t.artifact}function ay(t){let e=t.name??"eval-verifier",n=t.threshold??.5,r=t.toOutput??sy,o=t.extractArtifact??iy;return s=>{let i=ft(s,u=>u!=null&&u[0]!=null&&u[1]!=null),a=Te(i,([u,c])=>{let d=o(u,c);if(d==null)return N(r({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:n,missingArtifact:!0}));let l=N([d],{name:`${e}/candidates`}),f=N(t.datasetFor(c),{name:`${e}/dataset`}),p=t.evaluator(l,f);return E([p],([m])=>{let h=m;if(h==null)return null;let g=oy(h),y=h.filter(b=>b.score>=n).length;return r({scores:h,meanScore:g,passCount:y,total:h.length,threshold:n})},{name:`${e}/output`})},{name:e});return ft(a,u=>u!=null)}}Ne();ne();we();ne();var Yt=["auto-fix","needs-decision","investigation","backlog"];function ao(t,e){return`${t}\u2192${e}`}function ru(t){let e=t.detail.toLowerCase();return e.includes("parse")||e.includes("json")||e.includes("config")||e.includes("validation")||e.includes("syntax")?"self-correctable":"structural"}var ou={critical:100,high:70,medium:40,low:10},su=Math.LN2/(168*3600),iu={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1,startOpen:!1}};function au(){let t=Qe({name:"strategy-entries"}),e=E([t.entries],([i])=>{let a=i;return new Map(a)},{name:"strategy-model",equals:(i,a)=>{let u=i,c=a;if(u.size!==c.size)return!1;for(let[d,l]of u){let f=c.get(d);if(!f||l.attempts!==f.attempts||l.successes!==f.successes)return!1}return!0}});function n(i,a,u){let c=ao(i,a),d=t.get(c),l=(d?.attempts??0)+1,f=(d?.successes??0)+(u?1:0);t.set(c,{rootCause:i,intervention:a,attempts:l,successes:f,successRate:f/l})}function r(i,a){return t.get(ao(i,a))}let o=e.subscribe(()=>{});function s(){o()}return{node:e,record:n,lookup:r,dispose:s}}function uy(t,e,n,r,o){let s={...ou,...o?.severityWeights},i=o?.decayRate??su,a=o?.effectivenessThreshold??.7,u=o?.effectivenessBoost??15,c=[t,e,n];return r&&c.push(r),E(c,d=>{let l=d[0],f=d[1],p=d[2],m=r?d[3]:0,h=s[l.severity??"medium"],g=(V()-p)/1e9,y=Rn(h,g,i,0),b=ao(l.rootCause,l.intervention),v=f.get(b);return v&&v.successRate>=a&&(y+=u),y+=m*20,y},{name:"priority-score"})}var cy=`You are a triage classifier for a reactive collaboration harness.
196
174
 
197
175
  Given an intake item, classify it and output JSON:
198
176
  {
@@ -207,7 +185,7 @@ Strategy model (past effectiveness):
207
185
  {{strategy}}
208
186
 
209
187
  Intake item:
210
- {{item}}`,ny=`You are an implementation agent.
188
+ {{item}}`,dy=`You are an implementation agent.
211
189
 
212
190
  Given a triaged issue with root cause and intervention type, produce a fix.
213
191
 
@@ -218,7 +196,7 @@ Output JSON:
218
196
  {
219
197
  "outcome": "success" | "failure" | "partial",
220
198
  "detail": "<description of what was done or what failed>"
221
- }`,ry=`You are a QA reviewer.
199
+ }`,ly=`You are a QA reviewer.
222
200
 
223
201
  Given an execution result, verify whether the fix is correct.
224
202
 
@@ -233,11 +211,11 @@ Output JSON:
233
211
  "verified": true/false,
234
212
  "findings": ["<finding1>", ...],
235
213
  "errorClass": "self-correctable" | "structural" // only if verified=false
236
- }`;function up(t,e){let n=e??(r=>ny.replace("{{item}}",JSON.stringify(r)));return r=>Br(t,[r],n,{name:"execute",format:"json",retries:1})}function cp(t,e){let n=e??(r=>{let[o,s]=r;return ry.replace("{{execution}}",JSON.stringify(o)).replace("{{item}}",JSON.stringify(s))});return r=>Br(t,[r],n,{name:"verify",format:"json",retries:1})}var Gs=class extends q{intake;queues;gates;strategy;verifyResults;totalRetries;totalReingestions;constructor(e,n,r,o,s,i,a,u){super(e),this.intake=n,this.queues=r,this.gates=o,this.strategy=s,this.verifyResults=i,this.totalRetries=a,this.totalReingestions=u}};function oy(t,e){let n=e.adapter,r=e.maxRetries??2,o=e.retainedLimit??1e3,s=e.errorClassifier??Ka,i=new Map;for(let I of Ht)i.set(I,{...qa[I],...e.queues?.[I]});let a=new nt("intake",{retainedLimit:o}),u=Ua(),c=dn(a.latest,u.node),d=Br(n,[c],e.triagePrompt??(I=>{let[Q,U]=I;return Q?ty.replace("{{strategy}}",JSON.stringify(Array.from(U.entries()))).replace("{{item}}",JSON.stringify(Q)):""}),{name:"triage",format:"json",retries:1}),l=new Map;for(let I of Ht)l.set(I,new nt(`queue/${I}`,{retainedLimit:o}));let f=dn(d,c),m=fe([f],([I])=>{if(I==null)return;let[Q,U]=I;if(!Q?.route)return;let ae=U?.[0],j={...Q,...ae},Y=l.get(j.route);Y&&Y.publish(j)}).subscribe(()=>{}),h=new q("gates"),g=new Map;for(let I of Ht){let Q=i.get(I),U=l.get(I);if(Q.gated){h.add(U.latest,{name:`${I}/source`});let ae=Vr(h,`${I}/gate`,`${I}/source`,{maxPending:Q.maxPending,startOpen:Q.startOpen});g.set(I,ae)}}let y=new nt("retry-input",{retainedLimit:o}),b=[];for(let I of Ht)i.get(I).gated&&g.has(I)?b.push(g.get(I).node):b.push(l.get(I).latest);b.push(y.latest);let v=mt(...b),w=(e.executor??up(n,e.executePrompt))(v),k=dn(w,v),x=new nt("verify-results",{retainedLimit:o}),E=(e.verifier??cp(n,e.verifyPrompt))(k),G=dn(E,k),L=e.maxReingestions??1,P=Math.min(e.maxTotalRetries??r*10,100),C=Math.min(e.maxTotalReingestions??L*10,100),V=N(0),ne=N(0),A=K([G],(I,Q)=>{let U=I[0];if(U==null||U.length===0)return;let ae=U[U.length-1];if(ae==null)return;let[j,Y]=ae,[J,z]=Y??[null,null];if(!j||!z)return;let X={item:z,outcome:J?.outcome??"failure",detail:J?.detail??"unknown",artifact:J?.artifact},H={item:z,execution:X,verified:j.verified,findings:j.findings??[],errorClass:j.errorClass};if(H.verified){u.record(z.rootCause,z.intervention,!0),x.publish(H);return}let le=H.errorClass??s({item:z,outcome:"failure",detail:H.findings.join("; ")}),ve=z._retries??0;if(le==="self-correctable"&&ve<r&&Sr(V,P)){let Oe=Li(z),Be={...z,_retries:ve+1,summary:`[RETRY ${ve+1}/${r}] ${Oe} \u2014 Previous attempt failed: ${H.findings.join("; ")}`,relatedTo:[Oe]};y.publish(Be)}else{u.record(z.rootCause,z.intervention,!1),x.publish(H);let Oe=Li(z),Be=z._reingestions??0;Be<L&&Sr(ne,C)&&a.publish({source:"eval",summary:`Verification failed for: ${Oe}`,evidence:H.findings.join(`
237
- `),affectsAreas:z.affectsAreas,affectsEvalTasks:z.affectsEvalTasks,severity:"high",relatedTo:[Oe],_reingestions:Be+1})}}).subscribe(()=>{}),D=new Gs(t,a,l,g,u,x,V,ne);D.addDisposer(m),D.addDisposer(A),D.addDisposer(u.dispose),D.add(d,{name:"triage"}),D.add(w,{name:"execute"}),D.add(E,{name:"verify"}),D.add(u.node,{name:"strategy"}),D.mount("intake",a);for(let[I,Q]of l)D.mount(`queue/${I}`,Q);return D.mount("gates",h),D.mount("retry-input",y),D.mount("verify-results",x),D}function sy(t,e){let n=an(t,e),r={};for(let[o,s]of t.queues)r[o]=s.retained().length;return{...n,queueDepths:r,strategyEntries:t.strategy.node.cache?.size??0,totalRetries:t.totalRetries.cache??0,totalReingestions:t.totalReingestions.cache??0}}oe();var Fs={};he(Fs,{blindVariation:()=>ay,errorCritique:()=>dy,refineLoop:()=>Ja});Ne();ke();ie();xe();oe();function iy(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.subscribe=="function"&&typeof e.down=="function"&&typeof e.emit=="function"}function dp(t,e){if(t.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(t.length===1){let s=za(e);return{best:t[0],bestScore:s}}if(e.some(s=>typeof s.candidateIndex=="number")){let s=new Array(t.length);for(let u=0;u<t.length;u++)s[u]={sum:0,count:0};for(let u of e){let c=u.candidateIndex;typeof c=="number"&&c>=0&&c<t.length&&(s[c].sum+=u.score,s[c].count+=1)}let i=t[0],a=s[0].count>0?s[0].sum/s[0].count:Number.NEGATIVE_INFINITY;for(let u=1;u<t.length;u++){let c=s[u].count>0?s[u].sum/s[u].count:Number.NEGATIVE_INFINITY;c>a&&(a=c,i=t[u])}return{best:i,bestScore:a}}let r=t[0],o=e[0]?.score??Number.NEGATIVE_INFINITY;for(let s=1;s<t.length;s++){let i=e[s]?.score??Number.NEGATIVE_INFINITY;i>o&&(o=i,r=t[s])}return{best:r,bestScore:o}}function za(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let n of t)e+=n.score;return e/t.length}function Ja(t,e,n,r){let o=r.name??"refine-loop",s=new q(o,r.graph),i=iy(r.dataset)?r.dataset:N(r.dataset,{name:"dataset"});s.add(i,{name:"dataset"});let a=N(0,{name:"iteration"});s.add(a,{name:"iteration"});let u=N(n,{name:"strategy",equals:()=>!1});s.add(u,{name:"strategy"});let c=N(null,{name:"lastFeedback"});s.add(c,{name:"lastFeedback"});let d=N([],{name:"prevCandidates"});s.add(d,{name:"prevCandidates"});let l=N(!1,{name:"paused"});s.add(l,{name:"paused"});let f=N("running",{name:"status"});s.add(f,{name:"status"});let p=N([],{name:"history",equals:()=>!1});s.add(p,{name:"history"});let m=N(null,{name:"best"});s.add(m,{name:"best"});let h=N(Number.NEGATIVE_INFINITY,{name:"score"});s.add(h,{name:"score"});let g=N(0,{name:"budget-used"});s.add(g,{name:"budget-used"});let y=Et("GENERATE"),b=Et("EVALUATE"),v=Et("ANALYZE"),T=Et("DECIDE");s.mount("GENERATE",y),s.mount("EVALUATE",b),s.mount("ANALYZE",v),s.mount("DECIDE",T);let w=n,k=null,x=[];s.addDisposer(u.subscribe(J=>{for(let z of J)z[0]===S&&(w=z[1])})),s.addDisposer(c.subscribe(J=>{for(let z of J)z[0]===S&&(k=z[1])})),s.addDisposer(d.subscribe(J=>{for(let z of J)z[0]===S&&(x=z[1])}));let R=be(a,J=>{let z=w,X=J===0||k==null;return K([],(H,le)=>{let ve=!1;try{let Oe=X?z.seed(t):z.generate(k,x);if(Oe instanceof Promise)return Oe.then(Be=>{ve||le.emit(Be)},Be=>{ve||le.down([[M,Be]])}),()=>{ve=!0};le.emit(Oe)}catch(Oe){ve=!0,le.down([[M,Oe]])}},{describeKind:"producer"})},{name:"candidates"});s.add(R,{name:"candidates"});let E=fe([R],(J,z,X)=>{let H=X.terminalDeps[0];H!==void 0&&H!==!0&&f.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});s.add(E,{name:"error-watcher"}),s.addDisposer(E.subscribe(()=>{}));let G=fe([R,a],([J,z])=>{let X=J,H=z;te(()=>{y.publish({iteration:H,candidates:X,timestamp_ns:$()}),d.emit(X)})},{name:"generate-bridge"});s.add(G,{name:"generate-bridge"}),s.addDisposer(G.subscribe(()=>{}));let L=e(R,i);s.add(L,{name:"scores"});let P=fe([L,R,a],([J,z,X])=>{b.publish({iteration:X,candidates:z,scores:J,timestamp_ns:$()})},{name:"evaluate-bridge"});s.add(P,{name:"evaluate-bridge"}),s.addDisposer(P.subscribe(()=>{}));let C=O([L,R],([J,z])=>w.analyze(J,z),{name:"feedback"});s.add(C,{name:"feedback"});let V=fe([C,R,a],([J,z,X])=>{v.publish({iteration:X,candidates:z,feedback:J,timestamp_ns:$()})},{name:"analyze-bridge"});s.add(V,{name:"analyze-bridge"}),s.addDisposer(V.subscribe(()=>{}));let ne=O([p],([J])=>{let z=J;if(r.patience==null||z.length<=r.patience)return!1;let X=z.slice(-(r.patience+1)),H=X[0].bestScore;return X.slice(1).every(le=>le.bestScore<=H)},{name:"patience-check"});s.add(ne,{name:"patience-check"});let F=O([h],([J])=>r.minScore!=null&&J>=r.minScore,{name:"min-score-check"});s.add(F,{name:"min-score-check"});let A=O([p],([J])=>{let z=J;if(r.minDelta==null||z.length<2)return!1;let X=z[z.length-2].bestScore,H=z[z.length-1].bestScore;return Math.abs(H-X)<r.minDelta},{name:"min-delta-check"});s.add(A,{name:"min-delta-check"});let D=O([g],([J])=>r.maxEvaluations!=null&&J>=r.maxEvaluations,{name:"max-evaluations-check"});s.add(D,{name:"max-evaluations-check"});let I=O([a],([J])=>r.maxIterations!=null&&J>=r.maxIterations,{name:"max-iterations-check"});s.add(I,{name:"max-iterations-check"});let Q=O([g],([J])=>r.budget!=null&&J>=r.budget,{name:"budget-exhausted-check"});s.add(Q,{name:"budget-exhausted-check"}),s.addDisposer(ne.subscribe(()=>{})),s.addDisposer(F.subscribe(()=>{})),s.addDisposer(A.subscribe(()=>{})),s.addDisposer(D.subscribe(()=>{})),s.addDisposer(I.subscribe(()=>{})),s.addDisposer(Q.subscribe(()=>{}));let U=O([ne,F,A,D,I],([J,z,X,H,le])=>J?{converged:!0,reason:"patience"}:z?{converged:!0,reason:"min-score"}:X?{converged:!0,reason:"min-delta"}:H?{converged:!0,reason:"max-evaluations"}:le?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});s.add(U,{name:"converged"}),s.addDisposer(U.subscribe(()=>{}));let ae=-1,j=fe([C,L,R],([J,z,X])=>{let H=a.cache,le=J,ve=X,Oe=z;if(H<=ae)return;ae=H;let{best:Be,bestScore:gt}=dp(ve,Oe),Wt=p.cache,rt={n:H,candidates:ve,scores:Oe,feedback:le,best:Be,bestScore:gt,timestamp_ns:$()},We=[...Wt,rt],Z=g.cache+ve.length,ue="continue",me,Se=r.budget!=null&&Z>=r.budget,De=l.cache;if(Se)ue="budget",me="budget";else if(r.minScore!=null&&le.score>=r.minScore)ue="converged",me="min-score";else if(r.maxIterations!=null&&H>=r.maxIterations)ue="converged",me="max-iterations";else if(r.maxEvaluations!=null&&Z>=r.maxEvaluations)ue="converged",me="max-evaluations";else if(r.minDelta!=null&&We.length>=2){let qe=We[We.length-2].bestScore,Te=We[We.length-1].bestScore;Math.abs(Te-qe)<r.minDelta&&(ue="converged",me="min-delta")}else if(r.patience!=null&&We.length>r.patience){let qe=We.slice(-(r.patience+1)),Te=qe[0].bestScore;qe.slice(1).every(ye=>ye.bestScore<=Te)&&(ue="converged",me="patience")}ue==="continue"&&De&&(ue="paused"),te(()=>{m.emit(Be),h.emit(le.score),p.emit(We),g.emit(Z),c.emit(le),T.publish({iteration:H,decision:ue,reason:me,timestamp_ns:$()}),ue==="continue"?a.emit(H+1):f.emit(ue==="converged"?"converged":ue==="budget"?"budget":"paused")})},{name:"decide-bridge"});return s.add(j,{name:"decide-bridge"}),s.addDisposer(j.subscribe(()=>{})),Object.assign(s,{best:m,score:h,status:f,history:p,strategy:u,iteration:a,generate:y,evaluate:b,analyze:v,decide:T,setStrategy(J){u.emit(J)},pause(){l.emit(!0)},resume(){f.cache==="paused"&&te(()=>{l.emit(!1),f.emit("running"),a.emit(a.cache+1)})}})}function ay(t){let e=t.width??4;return{name:t.name??"blindVariation",seed(r){return[r]},analyze(r,o){let s=za(r),i=null;for(let a of r)(!i||a.score<i.score)&&(i=a);return{summary:`blindVariation iteration: mean=${s.toFixed(3)}, n=${r.length}`,score:s,weakTasks:i?[i.taskId]:[]}},async generate(r,o){if(o.length===0)throw new Error("blindVariation.generate: empty candidate batch \u2014 cannot derive prior for teacher");let s=o[o.length-1],i=0,u={prior:s,reportCost:c=>{i+=c}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(u)));let c=[];for(let d=0;d<e;d++)c.push(await t.teacher(u));return c}finally{if(t.tokens!=null&&i>0){let c=t.tokens.cache??0;t.tokens.emit(c+i)}}}}}function uy(t){return typeof t=="object"&&t!==null&&t.kind==="errorCritique"}function cy(t,e){return t.length===0?`No task scored below the batch mean (${e.score.toFixed(3)}). Reinforce the current direction.`:`Failures below threshold:
214
+ }`;function bp(t,e){let n=e??(r=>dy.replace("{{item}}",JSON.stringify(r)));return r=>Qr(t,[r],n,{name:"execute",format:"json",retries:1})}function vp(t,e){let n=e??(r=>{let[o,s]=r;return ly.replace("{{execution}}",JSON.stringify(o)).replace("{{item}}",JSON.stringify(s))});return r=>Qr(t,[r],n,{name:"verify",format:"json",retries:1})}var Zs=class extends q{intake;queues;gates;strategy;verifyResults;totalRetries;totalReingestions;constructor(e,n,r,o,s,i,a,u){super(e),this.intake=n,this.queues=r,this.gates=o,this.strategy=s,this.verifyResults=i,this.totalRetries=a,this.totalReingestions=u}};function py(t,e){let n=e.adapter,r=e.maxRetries??2,o=e.retainedLimit??1e3,s=e.errorClassifier??ru,i=new Map;for(let I of Yt)i.set(I,{...iu[I],...e.queues?.[I]});let a=new ut("intake",{retainedLimit:o}),u=au(),c=hn(a.latest,u.node),d=Qr(n,[c],e.triagePrompt??(I=>{let[J,H]=I;return J?cy.replace("{{strategy}}",JSON.stringify(Array.from(H.entries()))).replace("{{item}}",JSON.stringify(J)):""}),{name:"triage",format:"json",retries:1}),l=new Map;for(let I of Yt)l.set(I,new ut(`queue/${I}`,{retainedLimit:o}));let f=hn(d,c),m=me([f],([I])=>{if(I==null)return;let[J,H]=I;if(!J?.route)return;let ae=H?.[0],j={...J,...ae},U=l.get(j.route);U&&U.publish(j)}).subscribe(()=>{}),h=new q("gates"),g=new Map;for(let I of Yt){let J=i.get(I),H=l.get(I);if(J.gated){h.add(H.latest,{name:`${I}/source`});let ae=Zr(h,`${I}/gate`,`${I}/source`,{maxPending:J.maxPending,startOpen:J.startOpen});g.set(I,ae)}}let y=new ut("retry-input",{retainedLimit:o}),b=[];for(let I of Yt)i.get(I).gated&&g.has(I)?b.push(g.get(I).node):b.push(l.get(I).latest);b.push(y.latest);let v=wt(...b),w=(e.executor??bp(n,e.executePrompt))(v),k=hn(w,v),x=new ut("verify-results",{retainedLimit:o}),_=(e.verifier??vp(n,e.verifyPrompt))(k),G=hn(_,k),L=e.maxReingestions??1,P=Math.min(e.maxTotalRetries??r*10,100),C=Math.min(e.maxTotalReingestions??L*10,100),B=N(0),te=N(0),A=K([G],(I,J)=>{let H=I[0];if(H==null||H.length===0)return;let ae=H[H.length-1];if(ae==null)return;let[j,U]=ae,[he,ue]=U??[null,null];if(!j||!ue)return;let oe={item:ue,outcome:he?.outcome??"failure",detail:he?.detail??"unknown",artifact:he?.artifact},Z={item:ue,execution:oe,verified:j.verified,findings:j.findings??[],errorClass:j.errorClass};if(Z.verified){u.record(ue.rootCause,ue.intervention,!0),x.publish(Z);return}let Se=Z.errorClass??s({item:ue,outcome:"failure",detail:Z.findings.join("; ")}),Q=ue._retries??0;if(Se==="self-correctable"&&Q<r&&Cr(B,P)){let se=Ji(ue),xe={...ue,_retries:Q+1,summary:`[RETRY ${Q+1}/${r}] ${se} \u2014 Previous attempt failed: ${Z.findings.join("; ")}`,relatedTo:[se]};y.publish(xe)}else{u.record(ue.rootCause,ue.intervention,!1),x.publish(Z);let se=Ji(ue),xe=ue._reingestions??0;xe<L&&Cr(te,C)&&a.publish({source:"eval",summary:`Verification failed for: ${se}`,evidence:Z.findings.join(`
215
+ `),affectsAreas:ue.affectsAreas,affectsEvalTasks:ue.affectsEvalTasks,severity:"high",relatedTo:[se],_reingestions:xe+1})}}).subscribe(()=>{}),D=new Zs(t,a,l,g,u,x,B,te);D.addDisposer(m),D.addDisposer(A),D.addDisposer(u.dispose),D.add(d,{name:"triage"}),D.add(w,{name:"execute"}),D.add(_,{name:"verify"}),D.add(u.node,{name:"strategy"}),D.mount("intake",a);for(let[I,J]of l)D.mount(`queue/${I}`,J);return D.mount("gates",h),D.mount("retry-input",y),D.mount("verify-results",x),D}function fy(t,e){let n=pn(t,e),r={};for(let[o,s]of t.queues)r[o]=s.retained().length;return{...n,queueDepths:r,strategyEntries:t.strategy.node.cache?.size??0,totalRetries:t.totalRetries.cache??0,totalReingestions:t.totalReingestions.cache??0}}ne();var ei={};ye(ei,{blindVariation:()=>hy,errorCritique:()=>by,refineLoop:()=>cu});_e();we();ie();Ne();ne();function my(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 Tp(t,e){if(t.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(t.length===1){let s=uu(e);return{best:t[0],bestScore:s}}if(e.some(s=>typeof s.candidateIndex=="number")){let s=new Array(t.length);for(let u=0;u<t.length;u++)s[u]={sum:0,count:0};for(let u of e){let c=u.candidateIndex;typeof c=="number"&&c>=0&&c<t.length&&(s[c].sum+=u.score,s[c].count+=1)}let i=t[0],a=s[0].count>0?s[0].sum/s[0].count:Number.NEGATIVE_INFINITY;for(let u=1;u<t.length;u++){let c=s[u].count>0?s[u].sum/s[u].count:Number.NEGATIVE_INFINITY;c>a&&(a=c,i=t[u])}return{best:i,bestScore:a}}let r=t[0],o=e[0]?.score??Number.NEGATIVE_INFINITY;for(let s=1;s<t.length;s++){let i=e[s]?.score??Number.NEGATIVE_INFINITY;i>o&&(o=i,r=t[s])}return{best:r,bestScore:o}}function uu(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 cu(t,e,n,r){let o=r.name??"refine-loop",s=new q(o,r.graph),i=my(r.dataset)?r.dataset:N(r.dataset,{name:"dataset"});s.add(i,{name:"dataset"});let a=N(0,{name:"iteration"});s.add(a,{name:"iteration"});let u=N(n,{name:"strategy",equals:()=>!1});s.add(u,{name:"strategy"});let c=N(null,{name:"lastFeedback"});s.add(c,{name:"lastFeedback"});let d=N([],{name:"prevCandidates"});s.add(d,{name:"prevCandidates"});let l=N(!1,{name:"paused"});s.add(l,{name:"paused"});let f=N("running",{name:"status"});s.add(f,{name:"status"});let p=N([],{name:"history",equals:()=>!1});s.add(p,{name:"history"});let m=N(null,{name:"best"});s.add(m,{name:"best"});let h=N(Number.NEGATIVE_INFINITY,{name:"score"});s.add(h,{name:"score"});let g=N(0,{name:"budget-used"});s.add(g,{name:"budget-used"});let y=Ga("stages");s.mount("stages",y);let b=y.topic("generate"),v=y.topic("evaluate"),T=y.topic("analyze"),w=y.topic("decide"),k=n,x=null,R=[];s.addDisposer(u.subscribe(Q=>{for(let se of Q)se[0]===S&&(k=se[1])})),s.addDisposer(c.subscribe(Q=>{for(let se of Q)se[0]===S&&(x=se[1])})),s.addDisposer(d.subscribe(Q=>{for(let se of Q)se[0]===S&&(R=se[1])}));let _=Te(a,Q=>{let se=k,xe=Q===0||x==null;return K([],(Le,Ve)=>{let Ke=!1;try{let Je=xe?se.seed(t):se.generate(x,R);if(Je instanceof Promise)return Je.then(Y=>{Ke||Ve.emit(Y)},Y=>{Ke||Ve.down([[O,Y]])}),()=>{Ke=!0};Ve.emit(Je)}catch(Je){Ke=!0,Ve.down([[O,Je]])}},{describeKind:"producer"})},{name:"candidates"});s.add(_,{name:"candidates"});let G=me([_],(Q,se,xe)=>{let Le=xe.terminalDeps[0];Le!==void 0&&Le!==!0&&f.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});s.add(G,{name:"error-watcher"}),s.addDisposer(G.subscribe(()=>{}));let L=E([_,a],([Q,se])=>({iteration:se,candidates:Q,timestamp_ns:V()}),{name:"generate-event"});s.add(L,{name:"generate-event"}),s.addDisposer(L.subscribe(()=>{}));let P=me([L],([Q])=>{b.publish(Q)},{name:"generate-publish"});s.add(P,{name:"generate-publish"}),s.addDisposer(P.subscribe(()=>{}));let C=me([_],([Q])=>{d.emit(Q)},{name:"generate-mirror"});s.add(C,{name:"generate-mirror"}),s.addDisposer(C.subscribe(()=>{}));let B=e(_,i);s.add(B,{name:"scores"});let te=E([B,_,a],([Q,se,xe])=>({iteration:xe,candidates:se,scores:Q,timestamp_ns:V()}),{name:"evaluate-event"});s.add(te,{name:"evaluate-event"}),s.addDisposer(te.subscribe(()=>{}));let F=me([te],([Q])=>{v.publish(Q)},{name:"evaluate-publish"});s.add(F,{name:"evaluate-publish"}),s.addDisposer(F.subscribe(()=>{}));let A=E([B,_],([Q,se])=>k.analyze(Q,se),{name:"feedback"});s.add(A,{name:"feedback"});let D=E([A,_,a],([Q,se,xe])=>({iteration:xe,candidates:se,feedback:Q,timestamp_ns:V()}),{name:"analyze-event"});s.add(D,{name:"analyze-event"}),s.addDisposer(D.subscribe(()=>{}));let I=me([D],([Q])=>{T.publish(Q)},{name:"analyze-publish"});s.add(I,{name:"analyze-publish"}),s.addDisposer(I.subscribe(()=>{}));let J=E([p],([Q])=>{let se=Q;if(r.patience==null||se.length<=r.patience)return!1;let xe=se.slice(-(r.patience+1)),Le=xe[0].bestScore;return xe.slice(1).every(Ve=>Ve.bestScore<=Le)},{name:"patience-check"});s.add(J,{name:"patience-check"});let H=E([h],([Q])=>r.minScore!=null&&Q>=r.minScore,{name:"min-score-check"});s.add(H,{name:"min-score-check"});let ae=E([p],([Q])=>{let se=Q;if(r.minDelta==null||se.length<2)return!1;let xe=se[se.length-2].bestScore,Le=se[se.length-1].bestScore;return Math.abs(Le-xe)<r.minDelta},{name:"min-delta-check"});s.add(ae,{name:"min-delta-check"});let j=E([g],([Q])=>r.maxEvaluations!=null&&Q>=r.maxEvaluations,{name:"max-evaluations-check"});s.add(j,{name:"max-evaluations-check"});let U=E([a],([Q])=>r.maxIterations!=null&&Q>=r.maxIterations,{name:"max-iterations-check"});s.add(U,{name:"max-iterations-check"});let he=E([g],([Q])=>r.budget!=null&&Q>=r.budget,{name:"budget-exhausted-check"});s.add(he,{name:"budget-exhausted-check"}),s.addDisposer(J.subscribe(()=>{})),s.addDisposer(H.subscribe(()=>{})),s.addDisposer(ae.subscribe(()=>{})),s.addDisposer(j.subscribe(()=>{})),s.addDisposer(U.subscribe(()=>{})),s.addDisposer(he.subscribe(()=>{}));let ue=E([J,H,ae,j,U],([Q,se,xe,Le,Ve])=>Q?{converged:!0,reason:"patience"}:se?{converged:!0,reason:"min-score"}:xe?{converged:!0,reason:"min-delta"}:Le?{converged:!0,reason:"max-evaluations"}:Ve?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});s.add(ue,{name:"converged"}),s.addDisposer(ue.subscribe(()=>{}));let oe=-1,Z=me([A,B,_],([Q,se,xe])=>{let Le=a.cache,Ve=Q,Ke=xe,Je=se;if(Le<=oe)return;oe=Le;let{best:Y,bestScore:be}=Tp(Ke,Je),Re=p.cache,Me={n:Le,candidates:Ke,scores:Je,feedback:Ve,best:Y,bestScore:be,timestamp_ns:V()},Ee=[...Re,Me],Ze=g.cache+Ke.length,pe="continue",fe,po=r.budget!=null&&Ze>=r.budget,sr=l.cache;if(po)pe="budget",fe="budget";else if(r.minScore!=null&&Ve.score>=r.minScore)pe="converged",fe="min-score";else if(r.maxIterations!=null&&Le>=r.maxIterations)pe="converged",fe="max-iterations";else if(r.maxEvaluations!=null&&Ze>=r.maxEvaluations)pe="converged",fe="max-evaluations";else if(r.minDelta!=null&&Ee.length>=2){let fo=Ee[Ee.length-2].bestScore,bi=Ee[Ee.length-1].bestScore;Math.abs(bi-fo)<r.minDelta&&(pe="converged",fe="min-delta")}else if(r.patience!=null&&Ee.length>r.patience){let fo=Ee.slice(-(r.patience+1)),bi=fo[0].bestScore;fo.slice(1).every(Lp=>Lp.bestScore<=bi)&&(pe="converged",fe="patience")}pe==="continue"&&sr&&(pe="paused"),X(()=>{m.emit(Y),h.emit(Ve.score),p.emit(Ee),g.emit(Ze),c.emit(Ve),w.publish({iteration:Le,decision:pe,reason:fe,timestamp_ns:V()}),pe==="continue"?a.emit(Le+1):f.emit(pe==="converged"?"converged":pe==="budget"?"budget":"paused")})},{name:"decide-bridge"});return s.add(Z,{name:"decide-bridge"}),s.addDisposer(Z.subscribe(()=>{})),Object.assign(s,{best:m,score:h,status:f,history:p,strategy:u,iteration:a,generate:b,evaluate:v,analyze:T,decide:w,setStrategy(Q){u.emit(Q)},pause(){l.emit(!0)},resume(){f.cache==="paused"&&X(()=>{l.emit(!1),f.emit("running"),a.emit(a.cache+1)})}})}function hy(t){let e=t.width??4;return{name:t.name??"blindVariation",seed(r){return[r]},analyze(r,o){let s=uu(r),i=null;for(let a of r)(!i||a.score<i.score)&&(i=a);return{summary:`blindVariation iteration: mean=${s.toFixed(3)}, n=${r.length}`,score:s,weakTasks:i?[i.taskId]:[]}},async generate(r,o){if(o.length===0)throw new Error("blindVariation.generate: empty candidate batch \u2014 cannot derive prior for teacher");let s=o[o.length-1],i=0,u={prior:s,reportCost:c=>{i+=c}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(u)));let c=[];for(let d=0;d<e;d++)c.push(await t.teacher(u));return c}finally{if(t.tokens!=null&&i>0){let c=t.tokens.cache??0;t.tokens.emit(c+i)}}}}}function gy(t){return typeof t=="object"&&t!==null&&t.kind==="errorCritique"}function yy(t,e){return t.length===0?`No task scored below the batch mean (${e.score.toFixed(3)}). Reinforce the current direction.`:`Failures below threshold:
238
216
  ${t.map(r=>{let o=r.error!=null?` | error: ${r.error}`:"";return`- ${r.taskId} (score=${r.score.toFixed(3)})${o}`}).join(`
239
- `)}`}function dy(t){let e=t.width??4,n=t.name??"errorCritique",r=t.maxFailureSamples??5,o=t.formatCritique??cy;return{name:n,seed(s){return[s]},analyze(s,i){let a=za(s),u=typeof t.failureThreshold=="function"?t.failureThreshold(s):t.failureThreshold,c=u===void 0&&!Number.isFinite(a),d=u??a,l=c?[...s].sort((v,T)=>v.score-T.score):s.filter(v=>v.score<d).slice().sort((v,T)=>v.score-T.score),f=l.slice(0,r),{best:p,bestScore:m}=dp(i,s),h={summary:"",score:a,weakTasks:f.map(v=>v.taskId)},g=o(f,h),y={kind:"errorCritique",best:p,failures:f,critiqueText:g},b=l.length>f.length?` (top ${f.length} retained)`:"";return{summary:`errorCritique iteration: mean=${a.toFixed(3)}, failures=${l.length}${b}/${s.length}, bestScore=${m.toFixed(3)}`,critique:y,weakTasks:f.map(v=>v.taskId),score:a}},async generate(s,i){if(i.length===0)throw new Error("errorCritique.generate: empty candidate batch \u2014 cannot derive prior for teacher");let a=uy(s.critique)?s.critique:void 0,u=a!==void 0?a.best:i[i.length-1],c=a?.critiqueText??s.summary,d=a?.failures??[],l=0,p={prior:u,critique:c,failures:d,reportCost:m=>{l+=m}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(p)));let m=[];for(let h=0;h<e;h++)m.push(await t.teacher(p));return m}finally{if(t.tokens!=null&&l>0){let m=t.tokens.cache??0;t.tokens.emit(m+l)}}}}}function ly(t){let{best:e,score:n,status:r}=t,o=Number.isFinite(n)?n.toFixed(3):String(n);return r==="converged"?{outcome:"success",detail:`refineLoop converged at score ${o}`,artifact:e}:r==="budget"?{outcome:"partial",detail:`refineLoop hit budget at score ${o}`,artifact:e}:{outcome:"failure",detail:`refineLoop errored (status=${r})`,artifact:e}}function py(t){let e=t.name??"refine-executor",n=t.toOutput??ly;return r=>{let o=ut(r,i=>i!=null),s=be(o,i=>{let a=Ja(t.seedFrom(i),t.evaluator,t.strategy,{...t.refine,dataset:t.datasetFor(i),name:`${e}/inner`});return O([a.status,a.best,a.score],([u,c,d])=>{let l=u;return l!=="converged"&&l!=="budget"&&l!=="errored"?null:n({best:c,score:d,status:l})},{name:`${e}/output`})},{name:e});return ut(s,i=>i!=null)}}ke();function fy(t){let e={"intake::latest":"INTAKE",triage:"TRIAGE",execute:"EXECUTE","verify-results::latest":"VERIFY",strategy:"STRATEGY"};for(let n of Ht)e[`queue/${n}::latest`]="QUEUE";for(let[n]of t.gates)e[`gates::${n}/gate`]="GATE";return e}function my(t,e){let n=e?.logger===null?null:e?.logger??console.log,r=e?.detail??"summary",o=$(),s=[],i=[],a=fy(t);function u(){return($()-o)/1e9}function c(d,l,f){let p={elapsed:u(),stage:d,type:l};r!=="summary"&&(p.summary=hy(f)),r==="full"&&(p.data=f),i.push(p)}for(let[d,l]of Object.entries(a))try{let f=t.observe(d,{format:"stage-log",stageLabels:a,logger:n?p=>n(p):()=>{},includeTypes:["data","error","complete"]});f.onEvent(p=>{p.type==="data"?c(l,"data",p.data):p.type==="error"?c(l,"error",p.data):p.type==="complete"&&c(l,"complete",void 0)}),s.push(f)}catch(f){let p=f instanceof Error?f.message:String(f);c(l,"error",`observe-unavailable: ${d} \u2014 ${p}`),n&&n(`[${u().toFixed(3)}s] ${l.padEnd(9)} \u2717 observe-unavailable: ${p}`)}return{get events(){return i},dispose(){for(let d of s)d.dispose();s.length=0}}}function hy(t){if(t==null)return"null";if(typeof t=="string")return lp(t,80);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return lp(e,120)}catch{return String(t)}}function lp(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}var Vs={};he(Vs,{JobFlowGraph:()=>js,JobQueueGraph:()=>Bs,jobFlow:()=>yy,jobQueue:()=>fp});xe();var gy=2147483647;function pp(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Ya(t,e){return Ke("job_queue",t,e)}var Bs=class extends q{_pending;_jobs;_seq=0;pending;jobs;depth;constructor(e,n={}){super(e,n.graph),this._pending=es([],{name:"pending"}),this._jobs=tt({name:"jobs"}),this.pending=this._pending.items,this.jobs=this._jobs.entries,this.add(this.pending,{name:"pending"}),this.add(this.jobs,{name:"jobs"}),this.depth=O([this.pending],([r])=>r.length,{name:"depth",describeKind:"derived",meta:Ya("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(se(this.depth))}enqueue(e,n={}){let r=n.id??`${this.name}-${++this._seq}`;if(this._jobs.get(r)!==void 0)throw new Error(`jobQueue("${this.name}"): duplicate job id "${r}"`);let o={id:r,payload:e,attempts:0,metadata:Object.freeze({...n.metadata??{}}),state:"queued"};return this._jobs.set(r,o),this._pending.append(r),r}claim(e=1){let n=pp(e,"job queue claim limit");if(n===0)return[];let r=[];for(;r.length<n&&this.pending.cache.length!==0;){let s=this._pending.pop(0),i=this._jobs.get(s);if(!i||i.state!=="queued")continue;let a={...i,state:"inflight",attempts:i.attempts+1};this._jobs.set(s,a),r.push(a)}return r}ack(e){let n=this._jobs.get(e);return!n||n.state!=="inflight"?!1:(this._jobs.delete(e),!0)}nack(e,n={}){let r=this._jobs.get(e);return!r||r.state!=="inflight"?!1:n.requeue??!0?(this._jobs.set(e,{...r,state:"queued"}),this._pending.append(e),!0):(this._jobs.delete(e),!0)}},js=class extends q{_stageNames;_queues=new Map;_completed;completed;completedCount;constructor(e,n={}){super(e,n.graph);let r=(n.stages??["incoming","processing","done"]).map(i=>i.trim());if(r.length<2)throw new Error(`jobFlow("${e}"): requires at least 2 stages`);if(new Set(r).size!==r.length)throw new Error(`jobFlow("${e}"): stage names must be unique`);this._stageNames=Object.freeze([...r]);for(let i of this._stageNames){let a=fp(`${e}-${i}`);this._queues.set(i,a),this.mount(i,a)}this._completed=Ve([],{name:"completed"}),this.completed=this._completed.entries,this.add(this.completed,{name:"completed"}),this.completedCount=O([this.completed],([i])=>i.length,{name:"completedCount",describeKind:"derived",meta:Ya("job_flow_completed_count"),initial:0}),this.add(this.completedCount,{name:"completedCount"}),this.addDisposer(se(this.completedCount));let s=Math.max(1,pp(n.maxPerPump??gy,"job flow maxPerPump"));for(let i=0;i<this._stageNames.length;i+=1){let a=this._stageNames[i],u=this.queue(a),c=i+1<this._stageNames.length?this.queue(this._stageNames[i+1]):null,d=K([u.pending],()=>{let l=0;for(;l<s;){let f=u.claim(1);if(f.length===0)break;let p=f[0];if(!p)break;c?c.enqueue(p.payload,{metadata:{...p.metadata,job_flow_from:a}}):this._completed.append(p),u.ack(p.id),l+=1}},{name:`pump_${a}`,describeKind:"effect",meta:Ya("job_flow_pump")});this.add(d,{name:`pump_${a}`}),this.addDisposer(se(d))}}stages(){return this._stageNames}queue(e){let n=this._queues.get(e);if(!n)throw new Error(`jobFlow("${this.name}"): unknown stage "${e}"`);return n}enqueue(e,n={}){return this.queue(this._stageNames[0]).enqueue(e,n)}retainedCompleted(){return this.completed.cache}};function fp(t,e){return new Bs(t,e)}function yy(t,e){return new js(t,e)}var Hs={};he(Hs,{LensGraph:()=>Ks,graphLens:()=>ky,watchTopologyTree:()=>kt});ke();oe();function mp(t){return Ke("lens",t)}function by(t){let e=Object.keys(t.nodes),n=new Map,r=new Map;for(let h of e){let g=t.nodes[h]?.deps??[];n.set(h,g);for(let y of g)r.has(y)||r.set(y,new Set),r.get(y).add(h)}let o=[],s=[];for(let h of e)(n.get(h)??[]).length===0&&o.push(h),r.has(h)||s.push(h);o.sort(),s.sort();let i=t.edges.length,a=0,u=1,c=2,d=new Map;for(let h of e)d.set(h,a);let l=!1,f=new Map,p=h=>{let g=d.get(h)??a;if(g===u)return l=!0,0;if(g===c)return f.get(h)??0;d.set(h,u);let y=0,b=r.get(h);if(b!=null)for(let v of b){let T=p(v);T+1>y&&(y=T+1)}return d.set(h,c),f.set(h,y),y},m=0;for(let h of o){let g=p(h);g>m&&(m=g)}for(let h of e)d.get(h)===a&&p(h);return{nodeCount:e.length,edgeCount:i,subgraphCount:t.subgraphs.length,sources:o,sinks:s,depth:m,hasCycles:l}}function vy(t){let e=[];for(let[n,r]of Object.entries(t.nodes)){if(r.status!=="errored")continue;let o={path:n,status:"errored"},s=un(t,n,"upstream",{});for(let i of s)if(i!==n&&t.nodes[i]?.status==="errored"){o.upstreamCause=i;break}e.push(o)}return e.sort((n,r)=>n.path<r.path?-1:n.path>r.path?1:0),{ok:e.length===0,problems:e}}function Ty(t,e){return t.nodeCount===e.nodeCount&&t.edgeCount===e.edgeCount&&t.subgraphCount===e.subgraphCount&&t.depth===e.depth&&t.hasCycles===e.hasCycles&&hp(t.sources,e.sources)&&hp(t.sinks,e.sinks)}function wy(t,e){if(t.ok!==e.ok||t.problems.length!==e.problems.length)return!1;for(let n=0;n<t.problems.length;n++){let r=t.problems[n],o=e.problems[n];if(r.path!==o.path||r.status!==o.status||r.upstreamCause!==o.upstreamCause)return!1}return!0}function hp(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}var Ks=class extends q{stats;health;flow;_target;constructor(e,n={}){super(n.name??`${e.name}_lens`,n.graph),this._target=e;let r=0,o=0,s=N(0,{name:"stats_tick"}),i=N(0,{name:"health_tick"});this.add(s,{name:"stats_tick"}),this.add(i,{name:"health_tick"});let a={name:"flow"};n.maxFlowPaths!=null&&(a.maxSize=n.maxFlowPaths),this.flow=tt(a),this.add(this.flow.entries,{name:"flow"});let u=n.pathFilter,c=kt(e,(f,p,m)=>{if(r+=1,s.emit(r),o+=1,i.emit(o),f.kind==="removed")if(f.nodeKind==="node"){let h=`${m}${f.name}`;this.flow.delete(h)}else{let h=`${m}${f.name}::`,g=[];for(let y of f.audit.nodes){let b=y===""?`${m}${f.name}`:`${h}${y}`;g.push(b)}g.length>0&&this.flow.deleteMany(g)}});this.addDisposer(c);let d=e.observe({timeline:!0,structured:!0}),l=d.onEvent(f=>{let p=f.type;if((p==="error"||p==="complete"||p==="data"||p==="teardown")&&(o+=1,i.emit(o)),p==="data"){let m=f.path??"";if(!m||u!=null&&!u(m))return;let h=this.flow.get(m),g=h!=null?h.count+1:1;this.flow.set(m,{path:m,count:g,lastUpdate_ns:$()})}});this.addDisposer(()=>{l(),d.dispose()}),this.stats=O([s],()=>by(e.describe({detail:"minimal"})),{name:"stats",describeKind:"derived",equals:Ty,meta:mp("stats")}),this.add(this.stats,{name:"stats"}),this.addDisposer(se(this.stats)),this.health=O([i],()=>vy(e.describe({detail:"standard"})),{name:"health",describeKind:"derived",equals:wy,meta:mp("health")}),this.add(this.health,{name:"health"}),this.addDisposer(se(this.health))}why(e,n,r){let o=La(this._target,e,n,r);return this.addDisposer(o.dispose),o}get target(){return this._target}};function ky(t,e){return new Ks(t,e)}var Ws={};he(Ws,{CanvasMeasureAdapter:()=>eu,CliMeasureAdapter:()=>Qa,ImageSizeAdapter:()=>ru,NodeCanvasMeasureAdapter:()=>tu,PrecomputedAdapter:()=>Za,SvgBoundsAdapter:()=>nu,analyzeAndMeasure:()=>Mt,carveTextLineSlots:()=>Ga,circleIntervalForBand:()=>Tp,computeBlockFlow:()=>bp,computeCharPositions:()=>Ms,computeFlowLines:()=>kp,computeLineBreaks:()=>Tn,computeTotalHeight:()=>vp,layoutNextLine:()=>Da,measureBlock:()=>gp,measureBlocks:()=>yp,reactiveBlockLayout:()=>xy,reactiveFlowLayout:()=>Sy,reactiveLayout:()=>Ng,rectIntervalForBand:()=>wp});var Qa=class{cellPx;constructor(e){this.cellPx=e?.cellPx??8}measureSegment(e,n){return{width:Wn(e)*this.cellPx}}},Xa=class extends Error{name="KeyError"},Za=class{metrics;fallback;constructor(e){this.metrics=e.metrics;let n=e.fallback??"per-char";if(n!=="per-char"&&n!=="error")throw new Error(`fallback must be 'per-char' or 'error', got ${JSON.stringify(e.fallback)}`);this.fallback=n}measureSegment(e,n){let r=this.metrics[n];if(r){let s=r[e];if(s!==void 0)return{width:s}}if(this.fallback==="error")throw new Xa(`PrecomputedAdapter: no metrics for segment ${JSON.stringify(e)} in font ${JSON.stringify(n)}`);let o=0;if(r)for(let s of e){let i=r[s];i!==void 0&&(o+=i)}return{width:o}}},eu=class{ctx=null;currentFont="";emojiCorrection;constructor(e){this.emojiCorrection=e?.emojiCorrection??1}getContext(){if(!this.ctx){if(typeof OffscreenCanvas>"u")throw new Error("CanvasMeasureAdapter requires a browser environment with OffscreenCanvas support. Use CliMeasureAdapter or NodeCanvasMeasureAdapter for Node.js.");let n=new OffscreenCanvas(0,0).getContext("2d");if(!n)throw new Error("CanvasMeasureAdapter: failed to get 2d context");this.ctx=n}return this.ctx}measureSegment(e,n){let r=this.getContext();n!==this.currentFont&&(r.font=n,this.currentFont=n);let o=r.measureText(e).width;return this.emojiCorrection!==1&&new RegExp("\\p{Emoji_Presentation}","u").test(e)&&(o*=this.emojiCorrection),{width:o}}clearCache(){this.currentFont=""}},tu=class{ctx=null;currentFont="";canvasModule;constructor(e){this.canvasModule=e}getContext(){if(!this.ctx){let n=this.canvasModule.createCanvas(0,0).getContext("2d");if(!n)throw new Error("NodeCanvasMeasureAdapter: failed to get 2d context");this.ctx=n}return this.ctx}measureSegment(e,n){let r=this.getContext();return n!==this.currentFont&&(r.font=n,this.currentFont=n),{width:r.measureText(e).width}}clearCache(){this.currentFont=""}},nu=class{measureSvg(e){let n=e.match(/viewBox\s*=\s*["']([^"']+)["']/);if(n){let s=n[1].trim().split(/[\s,]+/);if(s.length>=4){let i=Number.parseFloat(s[2]),a=Number.parseFloat(s[3]);if(Number.isFinite(i)&&Number.isFinite(a)&&i>0&&a>0)return{width:i,height:a};throw new Error("SvgBoundsAdapter: viewBox width/height are missing, non-finite, or not positive")}}let r=e.match(/<svg[^>]*\bwidth\s*=\s*["']?([\d.]+)/),o=e.match(/<svg[^>]*\bheight\s*=\s*["']?([\d.]+)/);if(r&&o){let s=Number.parseFloat(r[1]),i=Number.parseFloat(o[1]);if(Number.isFinite(s)&&Number.isFinite(i)&&s>0&&i>0)return{width:s,height:i};throw new Error("SvgBoundsAdapter: svg width/height attributes are non-finite or not positive")}throw new Error("SvgBoundsAdapter: cannot determine dimensions \u2014 SVG has no viewBox or width/height attributes")}},ru=class{sizes;constructor(e){this.sizes=new Map(Object.entries(e))}measureImage(e){let n=this.sizes.get(e);if(!n)throw new Error(`ImageSizeAdapter: no dimensions registered for ${JSON.stringify(e)}`);return{width:n.width,height:n.height}}};ke();xe();oe();function gp(t,e,n,r,o,s,i){switch(t.type){case"text":{let a=t.font??o,u=t.lineHeight??s,c=Mt(t.text,a,n.text,r),d=Tn(c,e,n.text,a,r),l=Ms(d,c,u),f=d.lineCount*u,p=0;for(let m of d.lines)m.width>p&&(p=m.width);return{index:i,type:"text",width:Math.min(p,e),height:f,textSegments:c,textLineBreaks:d,textCharPositions:l}}case"image":{let a,u;if(t.naturalWidth!=null&&t.naturalHeight!=null)a=t.naturalWidth,u=t.naturalHeight;else if(n.image){let c=n.image.measureImage(t.src);a=c.width,u=c.height}else throw new Error(`Image block at index ${i} has no naturalWidth/naturalHeight and no ImageMeasurer adapter`);return a>e&&(u=u*e/a,a=e),{index:i,type:"image",width:a,height:u}}case"svg":{let a,u;if(t.viewBox)a=t.viewBox.width,u=t.viewBox.height;else if(n.svg){let c=n.svg.measureSvg(t.content);a=c.width,u=c.height}else throw new Error(`SVG block at index ${i} has no viewBox and no SvgMeasurer adapter`);return a>e&&(u=u*e/a,a=e),{index:i,type:"svg",width:a,height:u}}}}function yp(t,e,n,r,o,s){return t.map((i,a)=>gp(i,e,n,r,o,s,a))}function bp(t,e){let n=[],r=0;for(let o=0;o<t.length;o++){let s=t[o];n.push({...s,x:0,y:r}),r+=s.height+(o<t.length-1?e:0)}return n}function vp(t){if(t.length===0)return 0;let e=t[t.length-1];return e.y+e.height}function xy(t){let{adapters:e,name:n="reactive-block-layout",defaultFont:r="16px sans-serif",defaultLineHeight:o=20}=t,s=new q(n),i=new Map,a=N(t.blocks??[],{name:"blocks"}),u=N(Math.max(0,t.maxWidth??800),{name:"max-width"}),c=N(t.gap??0,{name:"gap"}),d=K([a,u],(p,m,h)=>{let g=p[0]!=null&&p[0].length>0?p[0].at(-1):h.prevData[0],y=p[1]!=null&&p[1].length>0?p[1].at(-1):h.prevData[1],b=$(),v=yp(g,y,e,i,r,o),T=$()-b,w=d.meta;w&&(at(w["block-count"],v.length),at(w["layout-time-ns"],T)),m.emit(v);let k=()=>{i.clear(),e.text.clearCache?.()};return{deactivate:k,invalidate:k}},{name:"measured-blocks",describeKind:"derived",meta:{"block-count":0,"layout-time-ns":0},equals:(p,m)=>{let h=p,g=m;if(h==null||g==null)return h===g;if(h.length!==g.length)return!1;for(let y=0;y<h.length;y++){let b=h[y],v=g[y];if(b.type!==v.type||b.width!==v.width||b.height!==v.height||b.index!==v.index)return!1}return!0}}),l=O([d,c],([p,m])=>bp(p,m),{name:"block-flow",equals:(p,m)=>{let h=p,g=m;if(h==null||g==null)return h===g;if(h.length!==g.length)return!1;for(let y=0;y<h.length;y++){let b=h[y],v=g[y];if(b.x!==v.x||b.y!==v.y||b.width!==v.width||b.height!==v.height)return!1}return!0}}),f=O([l],([p])=>vp(p),{name:"total-height"});return s.add(a,{name:"blocks"}),s.add(u,{name:"max-width"}),s.add(c,{name:"gap"}),s.add(d,{name:"measured-blocks"}),s.add(l,{name:"block-flow"}),s.add(f,{name:"total-height"}),{graph:s,setBlocks:p=>s.set("blocks",p),setMaxWidth:p=>s.set("max-width",Math.max(0,p)),setGap:p=>s.set("gap",p),measuredBlocks:d,blockFlow:l,totalHeight:f}}ke();xe();oe();function Tp(t,e,n){let r=t.hPad??0,o=t.vPad??0,s=e-o,i=n+o;if(s>=t.cy+t.r||i<=t.cy-t.r)return null;let a=t.cy>=s&&t.cy<=i?0:t.cy<s?s-t.cy:t.cy-i;if(a>=t.r)return null;let u=Math.sqrt(t.r*t.r-a*a);return{left:t.cx-u-r,right:t.cx+u+r}}function wp(t,e,n){let r=t.hPad??0,o=t.vPad??0;return n<=t.y-o||e>=t.y+t.h+o?null:{left:t.x-r,right:t.x+t.w+r}}function Ry(t,e,n){return t.kind==="circle"?Tp(t,e,n):wp(t,e,n)}function kp(t,e,n,r,o,s,i){let a=i?.paragraphSpacing??o,u=[],c={segmentIndex:0,graphemeIndex:0};if(t.length===0||n.count<=0||o<=0)return{lines:u,cursor:c};let d=e.paddingX??0,l=e.paddingY??0,f=Math.max(0,e.width-d*2),p=Math.max(0,e.height-l*2),m=n.gap*Math.max(0,n.count-1),h=Math.max(0,(f-m)/n.count);if(h<=0)return{lines:u,cursor:c};e:for(let g=0;g<n.count;g++){let y=d+g*(h+n.gap),b=y+h,v=l;for(;v+o<=l+p;){let T=v+o,w=[];for(let R=0;R<r.length;R++){let E=Ry(r[R],v,T);E!==null&&w.push(E)}let k=Ga({left:y,right:b},w,s);if(k.length===0){v+=o;continue}let x=!1;for(let R=0;R<k.length;R++){let E=k[R],G=E.right-E.left,L=Da(t,c,G);if(L===null)return{lines:u,cursor:c};if(L.text.length===0&&L.width===0){c=L.end,x=!0;break}u.push({x:E.left,y:v,width:L.width,slotWidth:G,text:L.text,columnIndex:g,flushToRight:E.right<b-.5}),c=L.end}if(x){v+=a;continue}if(v+=o,c.segmentIndex>=t.length)break e}if(c.segmentIndex>=t.length)break}return{lines:u,cursor:c}}function Sy(t){let{adapter:e,name:n="reactive-flow-layout",minSlotWidth:r=20}=t,o=new q(n),s=new Map,i=N(t.text??"",{name:"text"}),a=N(t.font??"16px sans-serif",{name:"font"}),u=N(t.lineHeight??20,{name:"line-height"}),c=N(t.container??{width:800,height:600,paddingX:0,paddingY:0},{name:"container"}),d=N(t.columns??{count:1,gap:0},{name:"columns"}),l=N(t.obstacles??[],{name:"obstacles"}),f=N(t.paragraphSpacing??null,{name:"paragraph-spacing"}),p=K([i,a],(h,g,y)=>{let b=h[0],v=b!=null&&b.length>0?b.at(-1):y.prevData[0],T=h[1],w=T!=null&&T.length>0?T.at(-1):y.prevData[1],k=Mt(v,w,e,s);g.emit(k);let x=()=>{s.clear(),e.clearCache?.()};return{deactivate:x,invalidate:x}},{name:"segments",describeKind:"derived"}),m=O([p,c,d,l,u,f],([h,g,y,b,v,T])=>{let w=h,k=$(),x=T??v,{lines:R,cursor:E}=kp(w,g,y,b,v,r,{paragraphSpacing:x}),G=$()-k,L=Math.max(0,w.length-E.segmentIndex),P=m.meta;return P&&(at(P["line-count"],R.length),at(P["layout-time-ns"],G),at(P["overflow-segments"],L)),R},{name:"flow-lines",meta:{"line-count":0,"layout-time-ns":0,"overflow-segments":0},equals:(h,g)=>{let y=h,b=g;if(y.length!==b.length)return!1;for(let v=0;v<y.length;v++){let T=y[v],w=b[v];if(T.x!==w.x||T.y!==w.y||T.width!==w.width||T.slotWidth!==w.slotWidth||T.text!==w.text||T.columnIndex!==w.columnIndex||T.flushToRight!==w.flushToRight)return!1}return!0}});return o.add(i,{name:"text"}),o.add(a,{name:"font"}),o.add(u,{name:"line-height"}),o.add(c,{name:"container"}),o.add(d,{name:"columns"}),o.add(l,{name:"obstacles"}),o.add(f,{name:"paragraph-spacing"}),o.add(p,{name:"segments"}),o.add(m,{name:"flow-lines"}),{graph:o,setText:h=>o.set("text",h),setFont:h=>o.set("font",h),setLineHeight:h=>o.set("line-height",h),setContainer:h=>o.set("container",h),setColumns:h=>o.set("columns",h),setObstacles:h=>o.set("obstacles",h),setParagraphSpacing:h=>o.set("paragraph-spacing",h),segments:p,flowLines:m}}var qs={};he(qs,{NS_PER_MS:()=>Fe,NS_PER_SEC:()=>Qe,resilientPipeline:()=>Ny});Gn();Tt();function Ny(t,e={}){let n=t;e.rateLimit!=null&&(n=Bn(n,e.rateLimit)),e.budget!=null&&e.budget.length>0&&(n=Fa(n,e.budget));let r;if(e.breaker!=null){let s=ft(e.breaker),i=e.breakerOnOpen??"skip",a=$n(s,{onOpen:i})(n);n=a.node,r=a.breakerState}if(e.timeoutMs!=null){if(e.timeoutMs<=0)throw new RangeError("timeoutMs must be > 0");if(e.timeoutMs>9e6)throw new RangeError("timeoutMs must be <= 9_000_000 (\u22482.5h) to stay within safe ns arithmetic");n=Vn(n,e.timeoutMs*1e6)}e.retry!=null&&(n=Fn(n,e.retry)),e.fallback!==void 0&&(n=jn(n,e.fallback));let o=It(n,{initialStatus:e.initialStatus??"pending"});return{node:o.node,status:o.status,error:o.error,breakerState:r}}var ti={};he(ti,{SNAPSHOT_WIRE_VERSION:()=>Xr,SurfaceError:()=>we,asSurfaceError:()=>Us,createGraph:()=>Zn,deleteSnapshot:()=>ei,diffSnapshots:()=>Xs,listSnapshots:()=>Zs,restoreSnapshot:()=>Qs,runReduction:()=>zs,saveSnapshot:()=>Ys});var we=class extends Error{code;details;constructor(e,n,r){super(n),this.name="SurfaceError",this.code=e,r!==void 0&&(this.details=r)}toJSON(){let e={code:this.code,message:this.message};if(this.details!==void 0){let n=Ey(this.details);n!==void 0&&(e.details=n)}return e}};function Ey(t){try{return JSON.parse(JSON.stringify(t))}catch{return}}function Us(t,e="internal-error"){if(t instanceof we)return t;let n=t instanceof Error?t.message:String(t);return new we(e,n)}function Zn(t,e){let n=Xn(t);if(!n.valid)throw new we("invalid-spec",`GraphSpec validation failed:
217
+ `)}`}function by(t){let e=t.width??4,n=t.name??"errorCritique",r=t.maxFailureSamples??5,o=t.formatCritique??yy;return{name:n,seed(s){return[s]},analyze(s,i){let a=uu(s),u=typeof t.failureThreshold=="function"?t.failureThreshold(s):t.failureThreshold,c=u===void 0&&!Number.isFinite(a),d=u??a,l=c?[...s].sort((v,T)=>v.score-T.score):s.filter(v=>v.score<d).slice().sort((v,T)=>v.score-T.score),f=l.slice(0,r),{best:p,bestScore:m}=Tp(i,s),h={summary:"",score:a,weakTasks:f.map(v=>v.taskId)},g=o(f,h),y={kind:"errorCritique",best:p,failures:f,critiqueText:g},b=l.length>f.length?` (top ${f.length} retained)`:"";return{summary:`errorCritique iteration: mean=${a.toFixed(3)}, failures=${l.length}${b}/${s.length}, bestScore=${m.toFixed(3)}`,critique:y,weakTasks:f.map(v=>v.taskId),score:a}},async generate(s,i){if(i.length===0)throw new Error("errorCritique.generate: empty candidate batch \u2014 cannot derive prior for teacher");let a=gy(s.critique)?s.critique:void 0,u=a!==void 0?a.best:i[i.length-1],c=a?.critiqueText??s.summary,d=a?.failures??[],l=0,p={prior:u,critique:c,failures:d,reportCost:m=>{l+=m}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(p)));let m=[];for(let h=0;h<e;h++)m.push(await t.teacher(p));return m}finally{if(t.tokens!=null&&l>0){let m=t.tokens.cache??0;t.tokens.emit(m+l)}}}}}function vy(t){let{best:e,score:n,status:r}=t,o=Number.isFinite(n)?n.toFixed(3):String(n);return r==="converged"?{outcome:"success",detail:`refineLoop converged at score ${o}`,artifact:e}:r==="budget"?{outcome:"partial",detail:`refineLoop hit budget at score ${o}`,artifact:e}:{outcome:"failure",detail:`refineLoop errored (status=${r})`,artifact:e}}function Ty(t){let e=t.name??"refine-executor",n=t.toOutput??vy;return r=>{let o=ft(r,i=>i!=null),s=Te(o,i=>{let a=cu(t.seedFrom(i),t.evaluator,t.strategy,{...t.refine,dataset:t.datasetFor(i),name:`${e}/inner`});return E([a.status,a.best,a.score],([u,c,d])=>{let l=u;return l!=="converged"&&l!=="budget"&&l!=="errored"?null:n({best:c,score:d,status:l})},{name:`${e}/output`})},{name:e});return ft(s,i=>i!=null)}}we();function wy(t){let e={"intake::latest":"INTAKE",triage:"TRIAGE",execute:"EXECUTE","verify-results::latest":"VERIFY",strategy:"STRATEGY"};for(let n of Yt)e[`queue/${n}::latest`]="QUEUE";for(let[n]of t.gates)e[`gates::${n}/gate`]="GATE";return e}function ky(t,e){let n=e?.logger===null?null:e?.logger??console.log,r=e?.detail??"summary",o=V(),s=[],i=[],a=wy(t);function u(){return(V()-o)/1e9}function c(d,l,f){let p={elapsed:u(),stage:d,type:l};r!=="summary"&&(p.summary=xy(f)),r==="full"&&(p.data=f),i.push(p)}for(let[d,l]of Object.entries(a))try{let f=t.observe(d,{format:"stage-log",stageLabels:a,logger:n?p=>n(p):()=>{},includeTypes:["data","error","complete"]});f.onEvent(p=>{p.type==="data"?c(l,"data",p.data):p.type==="error"?c(l,"error",p.data):p.type==="complete"&&c(l,"complete",void 0)}),s.push(f)}catch(f){let p=f instanceof Error?f.message:String(f);c(l,"error",`observe-unavailable: ${d} \u2014 ${p}`),n&&n(`[${u().toFixed(3)}s] ${l.padEnd(9)} \u2717 observe-unavailable: ${p}`)}return{get events(){return i},dispose(){for(let d of s)d.dispose();s.length=0}}}function xy(t){if(t==null)return"null";if(typeof t=="string")return wp(t,80);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return wp(e,120)}catch{return String(t)}}function wp(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}var oi={};ye(oi,{JobFlowGraph:()=>ri,JobQueueGraph:()=>ni,jobFlow:()=>Sy,jobQueue:()=>xp});Ne();var Ry=2147483647;function kp(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function du(t,e){return qe("job_queue",t,e)}var ni=class extends q{_pending;_jobs;_seq=0;pending;jobs;depth;constructor(e,n={}){super(e,n.graph),this._pending=gs([],{name:"pending"}),this._jobs=Qe({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=E([this.pending],([r])=>r.length,{name:"depth",describeKind:"derived",meta:du("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(re(this.depth))}enqueue(e,n={}){let r=n.id??`${this.name}-${++this._seq}`;if(this._jobs.get(r)!==void 0)throw new Error(`jobQueue("${this.name}"): duplicate job id "${r}"`);let o={id:r,payload:e,attempts:0,metadata:Object.freeze({...n.metadata??{}}),state:"queued"};return this._jobs.set(r,o),this._pending.append(r),r}claim(e=1){let n=kp(e,"job queue claim limit");if(n===0)return[];let r=[];for(;r.length<n&&this.pending.cache.length!==0;){let s=this._pending.pop(0),i=this._jobs.get(s);if(!i||i.state!=="queued")continue;let a={...i,state:"inflight",attempts:i.attempts+1};this._jobs.set(s,a),r.push(a)}return r}ack(e){let n=this._jobs.get(e);return!n||n.state!=="inflight"?!1:(this._jobs.delete(e),!0)}nack(e,n={}){let r=this._jobs.get(e);return!r||r.state!=="inflight"?!1:n.requeue??!0?(this._jobs.set(e,{...r,state:"queued"}),this._pending.append(e),!0):(this._jobs.delete(e),!0)}},ri=class extends q{_stageNames;_queues=new Map;_completed;completed;completedCount;constructor(e,n={}){super(e,n.graph);let r=(n.stages??["incoming","processing","done"]).map(i=>i.trim());if(r.length<2)throw new Error(`jobFlow("${e}"): requires at least 2 stages`);if(new Set(r).size!==r.length)throw new Error(`jobFlow("${e}"): stage names must be unique`);this._stageNames=Object.freeze([...r]);for(let i of this._stageNames){let a=xp(`${e}-${i}`);this._queues.set(i,a),this.mount(i,a)}this._completed=We([],{name:"completed"}),this.completed=this._completed.entries,this.add(this.completed,{name:"completed"}),this.completedCount=E([this.completed],([i])=>i.length,{name:"completedCount",describeKind:"derived",meta:du("job_flow_completed_count"),initial:0}),this.add(this.completedCount,{name:"completedCount"}),this.addDisposer(re(this.completedCount));let s=Math.max(1,kp(n.maxPerPump??Ry,"job flow maxPerPump"));for(let i=0;i<this._stageNames.length;i+=1){let a=this._stageNames[i],u=this.queue(a),c=i+1<this._stageNames.length?this.queue(this._stageNames[i+1]):null,d=K([u.pending],()=>{let l=0;for(;l<s;){let f=u.claim(1);if(f.length===0)break;let p=f[0];if(!p)break;c?c.enqueue(p.payload,{metadata:{...p.metadata,job_flow_from:a}}):this._completed.append(p),u.ack(p.id),l+=1}},{name:`pump_${a}`,describeKind:"effect",meta:du("job_flow_pump")});this.add(d,{name:`pump_${a}`}),this.addDisposer(re(d))}}stages(){return this._stageNames}queue(e){let n=this._queues.get(e);if(!n)throw new Error(`jobFlow("${this.name}"): unknown stage "${e}"`);return n}enqueue(e,n={}){return this.queue(this._stageNames[0]).enqueue(e,n)}retainedCompleted(){return this.completed.cache}};function xp(t,e){return new ni(t,e)}function Sy(t,e){return new ri(t,e)}var ii={};ye(ii,{LensGraph:()=>si,graphLens:()=>Oy,watchTopologyTree:()=>Mt});we();ne();function Rp(t){return qe("lens",t)}function Ny(t){let e=Object.keys(t.nodes),n=new Map,r=new Map;for(let h of e){let g=t.nodes[h]?.deps??[];n.set(h,g);for(let y of g)r.has(y)||r.set(y,new Set),r.get(y).add(h)}let o=[],s=[];for(let h of e)(n.get(h)??[]).length===0&&o.push(h),r.has(h)||s.push(h);o.sort(),s.sort();let i=t.edges.length,a=0,u=1,c=2,d=new Map;for(let h of e)d.set(h,a);let l=!1,f=new Map,p=h=>{let g=d.get(h)??a;if(g===u)return l=!0,0;if(g===c)return f.get(h)??0;d.set(h,u);let y=0,b=r.get(h);if(b!=null)for(let v of b){let T=p(v);T+1>y&&(y=T+1)}return d.set(h,c),f.set(h,y),y},m=0;for(let h of o){let g=p(h);g>m&&(m=g)}for(let h of e)d.get(h)===a&&p(h);return{nodeCount:e.length,edgeCount:i,subgraphCount:t.subgraphs.length,sources:o,sinks:s,depth:m,hasCycles:l}}function Ey(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 _y(t,e){return t.nodeCount===e.nodeCount&&t.edgeCount===e.edgeCount&&t.subgraphCount===e.subgraphCount&&t.depth===e.depth&&t.hasCycles===e.hasCycles&&Sp(t.sources,e.sources)&&Sp(t.sinks,e.sinks)}function My(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 Sp(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 si=class extends q{stats;health;flow;_target;constructor(e,n={}){super(n.name??`${e.name}_lens`,n.graph),this._target=e;let r=0,o=0,s=N(0,{name:"stats_tick"}),i=N(0,{name:"health_tick"});this.add(s,{name:"stats_tick"}),this.add(i,{name:"health_tick"});let a={name:"flow"};n.maxFlowPaths!=null&&(a.maxSize=n.maxFlowPaths),this.flow=Qe(a),this.add(this.flow.entries,{name:"flow"});let u=n.pathFilter,c=Mt(e,(f,p,m)=>{if(r+=1,s.emit(r),o+=1,i.emit(o),f.kind==="removed")if(f.nodeKind==="node"){let h=`${m}${f.name}`;this.flow.delete(h)}else{let h=`${m}${f.name}::`,g=[];for(let y of f.audit.nodes){let b=y===""?`${m}${f.name}`:`${h}${y}`;g.push(b)}g.length>0&&this.flow.deleteMany(g)}});this.addDisposer(c);let d=e.observe({timeline:!0,structured:!0}),l=d.onEvent(f=>{let p=f.type;if((p==="error"||p==="complete"||p==="data"||p==="teardown")&&(o+=1,i.emit(o)),p==="data"){let m=f.path??"";if(!m||u!=null&&!u(m))return;let h=this.flow.get(m),g=h!=null?h.count+1:1;this.flow.set(m,{path:m,count:g,lastUpdate_ns:V()})}});this.addDisposer(()=>{l(),d.dispose()}),this.stats=E([s],()=>Ny(e.describe({detail:"minimal"})),{name:"stats",describeKind:"derived",equals:_y,meta:Rp("stats")}),this.add(this.stats,{name:"stats"}),this.addDisposer(re(this.stats)),this.health=E([i],()=>Ey(e.describe({detail:"standard"})),{name:"health",describeKind:"derived",equals:My,meta:Rp("health")}),this.add(this.health,{name:"health"}),this.addDisposer(re(this.health))}why(e,n,r){let o=Qa(this._target,e,n,r);return this.addDisposer(o.dispose),o}get target(){return this._target}};function Oy(t,e){return new si(t,e)}var ai={};ye(ai,{CanvasMeasureAdapter:()=>mu,CliMeasureAdapter:()=>lu,ImageSizeAdapter:()=>yu,NodeCanvasMeasureAdapter:()=>hu,PrecomputedAdapter:()=>fu,SvgBoundsAdapter:()=>gu,analyzeAndMeasure:()=>Pt,carveTextLineSlots:()=>tu,circleIntervalForBand:()=>Op,computeBlockFlow:()=>_p,computeCharPositions:()=>zs,computeFlowLines:()=>Ap,computeLineBreaks:()=>Sn,computeTotalHeight:()=>Mp,layoutNextLine:()=>eu,measureBlock:()=>Np,measureBlocks:()=>Ep,reactiveBlockLayout:()=>Cy,reactiveFlowLayout:()=>Ly,reactiveLayout:()=>Hg,rectIntervalForBand:()=>Cp});var lu=class{cellPx;constructor(e){this.cellPx=e?.cellPx??8}measureSegment(e,n){return{width:Jn(e)*this.cellPx}}},pu=class extends Error{name="KeyError"},fu=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 pu(`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}}},mu=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=""}},hu=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=""}},gu=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")}},yu=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}}};we();Ne();ne();function Np(t,e,n,r,o,s,i){switch(t.type){case"text":{let a=t.font??o,u=t.lineHeight??s,c=Pt(t.text,a,n.text,r),d=Sn(c,e,n.text,a,r),l=zs(d,c,u),f=d.lineCount*u,p=0;for(let m of d.lines)m.width>p&&(p=m.width);return{index:i,type:"text",width:Math.min(p,e),height:f,textSegments:c,textLineBreaks:d,textCharPositions:l}}case"image":{let a,u;if(t.naturalWidth!=null&&t.naturalHeight!=null)a=t.naturalWidth,u=t.naturalHeight;else if(n.image){let c=n.image.measureImage(t.src);a=c.width,u=c.height}else throw new Error(`Image block at index ${i} has no naturalWidth/naturalHeight and no ImageMeasurer adapter`);return a>e&&(u=u*e/a,a=e),{index:i,type:"image",width:a,height:u}}case"svg":{let a,u;if(t.viewBox)a=t.viewBox.width,u=t.viewBox.height;else if(n.svg){let c=n.svg.measureSvg(t.content);a=c.width,u=c.height}else throw new Error(`SVG block at index ${i} has no viewBox and no SvgMeasurer adapter`);return a>e&&(u=u*e/a,a=e),{index:i,type:"svg",width:a,height:u}}}}function Ep(t,e,n,r,o,s){return t.map((i,a)=>Np(i,e,n,r,o,s,a))}function _p(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 Mp(t){if(t.length===0)return 0;let e=t[t.length-1];return e.y+e.height}function Cy(t){let{adapters:e,name:n="reactive-block-layout",defaultFont:r="16px sans-serif",defaultLineHeight:o=20}=t,s=new q(n),i=new Map,a=N(t.blocks??[],{name:"blocks"}),u=N(Math.max(0,t.maxWidth??800),{name:"max-width"}),c=N(t.gap??0,{name:"gap"}),d=K([a,u],(p,m,h)=>{let g=p[0]!=null&&p[0].length>0?p[0].at(-1):h.prevData[0],y=p[1]!=null&&p[1].length>0?p[1].at(-1):h.prevData[1],b=V(),v=Ep(g,y,e,i,r,o),T=V()-b,w=d.meta;w&&(pt(w["block-count"],v.length),pt(w["layout-time-ns"],T)),m.emit(v);let k=()=>{i.clear(),e.text.clearCache?.()};return{deactivate:k,invalidate:k}},{name:"measured-blocks",describeKind:"derived",meta:{"block-count":0,"layout-time-ns":0},equals:(p,m)=>{let h=p,g=m;if(h==null||g==null)return h===g;if(h.length!==g.length)return!1;for(let y=0;y<h.length;y++){let b=h[y],v=g[y];if(b.type!==v.type||b.width!==v.width||b.height!==v.height||b.index!==v.index)return!1}return!0}}),l=E([d,c],([p,m])=>_p(p,m),{name:"block-flow",equals:(p,m)=>{let h=p,g=m;if(h==null||g==null)return h===g;if(h.length!==g.length)return!1;for(let y=0;y<h.length;y++){let b=h[y],v=g[y];if(b.x!==v.x||b.y!==v.y||b.width!==v.width||b.height!==v.height)return!1}return!0}}),f=E([l],([p])=>Mp(p),{name:"total-height"});return s.add(a,{name:"blocks"}),s.add(u,{name:"max-width"}),s.add(c,{name:"gap"}),s.add(d,{name:"measured-blocks"}),s.add(l,{name:"block-flow"}),s.add(f,{name:"total-height"}),{graph:s,setBlocks:p=>s.set("blocks",p),setMaxWidth:p=>s.set("max-width",Math.max(0,p)),setGap:p=>s.set("gap",p),measuredBlocks:d,blockFlow:l,totalHeight:f}}we();Ne();ne();function Op(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 Cp(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 Ay(t,e,n){return t.kind==="circle"?Op(t,e,n):Cp(t,e,n)}function Ap(t,e,n,r,o,s,i){let a=i?.paragraphSpacing??o,u=[],c={segmentIndex:0,graphemeIndex:0};if(t.length===0||n.count<=0||o<=0)return{lines:u,cursor:c};let d=e.paddingX??0,l=e.paddingY??0,f=Math.max(0,e.width-d*2),p=Math.max(0,e.height-l*2),m=n.gap*Math.max(0,n.count-1),h=Math.max(0,(f-m)/n.count);if(h<=0)return{lines:u,cursor:c};e:for(let g=0;g<n.count;g++){let y=d+g*(h+n.gap),b=y+h,v=l;for(;v+o<=l+p;){let T=v+o,w=[];for(let R=0;R<r.length;R++){let _=Ay(r[R],v,T);_!==null&&w.push(_)}let k=tu({left:y,right:b},w,s);if(k.length===0){v+=o;continue}let x=!1;for(let R=0;R<k.length;R++){let _=k[R],G=_.right-_.left,L=eu(t,c,G);if(L===null)return{lines:u,cursor:c};if(L.text.length===0&&L.width===0){c=L.end,x=!0;break}u.push({x:_.left,y:v,width:L.width,slotWidth:G,text:L.text,columnIndex:g,flushToRight:_.right<b-.5}),c=L.end}if(x){v+=a;continue}if(v+=o,c.segmentIndex>=t.length)break e}if(c.segmentIndex>=t.length)break}return{lines:u,cursor:c}}function Ly(t){let{adapter:e,name:n="reactive-flow-layout",minSlotWidth:r=20}=t,o=new q(n),s=new Map,i=N(t.text??"",{name:"text"}),a=N(t.font??"16px sans-serif",{name:"font"}),u=N(t.lineHeight??20,{name:"line-height"}),c=N(t.container??{width:800,height:600,paddingX:0,paddingY:0},{name:"container"}),d=N(t.columns??{count:1,gap:0},{name:"columns"}),l=N(t.obstacles??[],{name:"obstacles"}),f=N(t.paragraphSpacing??null,{name:"paragraph-spacing"}),p=K([i,a],(h,g,y)=>{let b=h[0],v=b!=null&&b.length>0?b.at(-1):y.prevData[0],T=h[1],w=T!=null&&T.length>0?T.at(-1):y.prevData[1],k=Pt(v,w,e,s);g.emit(k);let x=()=>{s.clear(),e.clearCache?.()};return{deactivate:x,invalidate:x}},{name:"segments",describeKind:"derived"}),m=E([p,c,d,l,u,f],([h,g,y,b,v,T])=>{let w=h,k=V(),x=T??v,{lines:R,cursor:_}=Ap(w,g,y,b,v,r,{paragraphSpacing:x}),G=V()-k,L=Math.max(0,w.length-_.segmentIndex),P=m.meta;return P&&(pt(P["line-count"],R.length),pt(P["layout-time-ns"],G),pt(P["overflow-segments"],L)),R},{name:"flow-lines",meta:{"line-count":0,"layout-time-ns":0,"overflow-segments":0},equals:(h,g)=>{let y=h,b=g;if(y.length!==b.length)return!1;for(let v=0;v<y.length;v++){let T=y[v],w=b[v];if(T.x!==w.x||T.y!==w.y||T.width!==w.width||T.slotWidth!==w.slotWidth||T.text!==w.text||T.columnIndex!==w.columnIndex||T.flushToRight!==w.flushToRight)return!1}return!0}});return o.add(i,{name:"text"}),o.add(a,{name:"font"}),o.add(u,{name:"line-height"}),o.add(c,{name:"container"}),o.add(d,{name:"columns"}),o.add(l,{name:"obstacles"}),o.add(f,{name:"paragraph-spacing"}),o.add(p,{name:"segments"}),o.add(m,{name:"flow-lines"}),{graph:o,setText:h=>o.set("text",h),setFont:h=>o.set("font",h),setLineHeight:h=>o.set("line-height",h),setContainer:h=>o.set("container",h),setColumns:h=>o.set("columns",h),setObstacles:h=>o.set("obstacles",h),setParagraphSpacing:h=>o.set("paragraph-spacing",h),segments:p,flowLines:m}}var ui={};ye(ui,{NS_PER_MS:()=>Be,NS_PER_SEC:()=>ot,resilientPipeline:()=>Iy});Vn();Et();function Iy(t,e={}){let n=t;e.rateLimit!=null&&(n=Wn(n,e.rateLimit)),e.budget!=null&&e.budget.length>0&&(n=qa(n,e.budget));let r;if(e.breaker!=null){let s=Tt(e.breaker),i=e.breakerOnOpen??"skip",a=Hn(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=Un(n,e.timeoutMs*1e6)}e.retry!=null&&(n=Kn(n,e.retry)),e.fallback!==void 0&&(n=qn(n,e.fallback));let o=Bt(n,{initialStatus:e.initialStatus??"pending"});return{node:o.node,status:o.status,error:o.error,breakerState:r}}var yi={};ye(yi,{SNAPSHOT_WIRE_VERSION:()=>lo,SurfaceError:()=>ke,asSurfaceError:()=>ci,createGraph:()=>or,deleteSnapshot:()=>gi,diffSnapshots:()=>mi,listSnapshots:()=>hi,restoreSnapshot:()=>fi,runReduction:()=>di,saveSnapshot:()=>pi});var ke=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=Py(this.details);n!==void 0&&(e.details=n)}return e}};function Py(t){try{return JSON.parse(JSON.stringify(t))}catch{return}}function ci(t,e="internal-error"){if(t instanceof ke)return t;let n=t instanceof Error?t.message:String(t);return new ke(e,n)}function or(t,e){let n=rr(t);if(!n.valid)throw new ke("invalid-spec",`GraphSpec validation failed:
240
218
  ${n.errors.join(`
241
- `)}`,{errors:n.errors});let r=e?.catalog??{},o=zr(t,r);if(!o.valid)throw new we("catalog-error",`Catalog validation failed:
219
+ `)}`,{errors:n.errors});let r=e?.catalog??{},o=oo(t,r);if(!o.valid)throw new ke("catalog-error",`Catalog validation failed:
242
220
  ${o.errors.join(`
243
- `)}`,{errors:o.errors});try{return Va(t,e)}catch(s){let i=s instanceof Error?s.message:String(s);throw new we("catalog-error",i)}}ie();var _y=3e4;async function zs(t,e,n){let r=n?.inputPath??"input",o=n?.outputPath??"output",s=n?.timeoutMs??_y,i=Zn(t,{catalog:n?.catalog}),a;try{a=i.resolve(o)}catch{throw i.destroy(),new we("node-not-found",`reduce: output path "${o}" is not registered`,{path:o})}try{i.resolve(r)}catch{throw i.destroy(),new we("node-not-found",`reduce: input path "${r}" is not registered`,{path:r})}try{return await new Promise((u,c)=>{let d=!1,l=!1,f,p,m=!1,h=g=>{l||(l=!0,f!==void 0&&clearTimeout(f),p!==void 0?(p(),p=void 0):m=!0,g())};p=a.subscribe(g=>{for(let y of g){if(l)return;if(d){if(y[0]===S){h(()=>u(y[1]));return}if(y[0]===B){let b=a.cache;h(()=>u(b));return}if(y[0]===M){let b=y[1],v=b instanceof Error?b.message:String(b),T=b instanceof Error?b:void 0;h(()=>c(new we("internal-error",`reduce: output emitted ERROR: ${v}`,T!=null?{cause:T}:void 0)));return}if(y[0]===_){h(()=>c(new we("internal-error","reduce: output COMPLETEd without a post-push DATA")));return}}}}),m&&(p?.(),p=void 0),d=!0;try{i.set(r,e)}catch(g){let y=g instanceof Error?g.message:String(g),b=g instanceof Error?g:void 0;h(()=>c(new we("internal-error",`reduce: failed to set input on "${r}": ${y}`,b!=null?{path:r,cause:b}:{path:r})));return}!l&&Number.isFinite(s)&&s>0&&(f=setTimeout(()=>{h(()=>c(new we("reduce-timeout",`reduce: no output emitted within ${s}ms`,{timeoutMs:s,outputPath:o})))},s),f.unref?.())})}finally{i.destroy()}}ke();var Xr=it,Yr="snapshot:";function Qr(t){if(t.startsWith(Yr))throw new we("snapshot-failed",`snapshot id must not start with "${Yr}" (reserved); got "${t}"`,{snapshotId:t})}function Js(t){return`${Yr}${t}`}function My(t){return t.startsWith(Yr)?t.slice(Yr.length):void 0}function ou(t,e){if(t==null||typeof t!="object")throw new we("snapshot-not-found",`snapshot "${e}" not found in tier`,{snapshotId:e});let n=t;if("mode"in n){if(n.mode==="full"&&"snapshot"in n)return n.snapshot;throw n.mode==="diff"?new we("restore-failed",`snapshot "${e}" is a diff record; restore the baseline and replay WAL instead`,{snapshotId:e,mode:"diff"}):new we("restore-failed",`snapshot "${e}" has unknown mode "${String(n.mode)}"`,{snapshotId:e,mode:String(n.mode)})}if("nodes"in n&&"edges"in n&&"subgraphs"in n&&"name"in n)return n;throw new we("restore-failed",`snapshot "${e}" payload is not a GraphCheckpointRecord or GraphPersistSnapshot`,{snapshotId:e})}async function Ys(t,e,n){Qr(e);let r;try{r=t.snapshot()}catch(s){let i=s instanceof Error?s.message:String(s);throw new we("snapshot-failed",`snapshot "${e}" serialization failed: ${i}`,{snapshotId:e})}let o={mode:"full",seq:0,timestamp_ns:pe(),format_version:Xr,snapshot:r};try{await n.save(Js(e),o)}catch(s){let i=s instanceof Error?s.message:String(s);throw new we("snapshot-failed",`snapshot "${e}" save failed: ${i}`,{snapshotId:e})}return{snapshotId:e,timestamp_ns:o.timestamp_ns}}async function Qs(t,e,n){Qr(t);let r=Js(t),o=await e.load(r);o==null&&(o=await e.load(t));let s=ou(o,t);try{return q.fromSnapshot(s,n?.factories?{factories:n.factories}:void 0)}catch(i){let a=i instanceof Error?i.message:String(i);throw new we("restore-failed",`snapshot "${t}" restore failed: ${a}`,{snapshotId:t})}}async function Xs(t,e,n){Qr(t),Qr(e);let r=async u=>{let c=Js(u),d=await n.load(c);return d==null&&(d=await n.load(u)),d},[o,s]=await Promise.all([r(t),r(e)]),i=ou(o,t),a=ou(s,e);return q.diff(i,a)}async function Zs(t,e){if(typeof t.list!="function")throw new we("tier-no-list","StorageTier does not implement list(); wrap the tier with an enumerator or use a different backend");let n=await t.list(),r=[],o=e?.includeUnprefixed===!0;for(let s of n){let i=My(s);i!==void 0?r.push(i):o&&r.push(s)}return r}async function ei(t,e){if(Qr(t),typeof e.clear!="function")throw new we("snapshot-failed",`StorageTier is append-only (no clear()); cannot delete "${t}"`,{snapshotId:t});try{await e.clear(Js(t))}catch(n){let r=n instanceof Error?n.message:String(n);throw new we("snapshot-failed",`snapshot "${t}" delete failed: ${r}`,{snapshotId:t})}}var Oy="0.0.0";0&&(module.exports={COMPLETE,COMPLETE_MSG,COMPLETE_ONLY_BATCH,CircuitOpenError,DATA,DEFAULT_ACTOR,DIRTY,DIRTY_MSG,DIRTY_ONLY_BATCH,ENVELOPE_VERSION,ERROR,GRAPH_META_SEGMENT,Graph,GraphReFlyConfig,GuardDenied,INVALIDATE,INVALIDATE_MSG,INVALIDATE_ONLY_BATCH,JsonCodec,NS_PER_MS,NS_PER_SEC,NativeIndexBackend,NativeListBackend,NativeLogBackend,NativeMapBackend,NativePubSubBackend,NodeImpl,PAUSE,RESOLVED,RESOLVED_MSG,RESOLVED_ONLY_BATCH,RESUME,RateLimiterOverflowError,ResettableTimer,SIZEOF_OVERHEAD,SIZEOF_SYMBOL,SNAPSHOT_VERSION,SNAPSHOT_WIRE_VERSION,START,START_MSG,SurfaceError,TEARDOWN,TEARDOWN_MSG,TEARDOWN_ONLY_BATCH,TimeoutError,accessHintForGuard,accountability,advanceVersion,ai,asSurfaceError,audit,autoTrackNode,awaitSettled,batch,buffer,bufferCount,bufferTime,cached,cascadingCache,catchError,checkpointToRedis,checkpointToS3,circuitBreaker,combine,combineLatest,compat,concat,concatMap,configure,constant,core,cqrs,createDagCborCodec,createDagCborZstdCodec,createGraph,createTransport,createVersioning,createWatermarkController,csvRows,debounce,debounceTime,decodeEnvelope,decorrelatedJitter,defaultConfig,defaultHash,delay,deleteSnapshot,demoShell,derived,deserializeError,dictStorage,diffForWAL,diffSnapshots,distill,distinctUntilChanged,domainTemplates,downWithBatch,dynamicNode,effect,elementAt,empty,encodeEnvelope,escapeRegexChar,exhaustMap,explainPath,exponential,externalBundle,externalProducer,extra,fallback,fibonacci,filter,find,first,firstValueFrom,firstWhere,flatMap,forEach,fromAny,fromAsyncIter,fromCSV,fromClickHouseWatch,fromCron,fromDrizzle,fromEvent,fromHTTP,fromHTTPPoll,fromHTTPStream,fromIter,fromKafka,fromKysely,fromMCP,fromNATS,fromNDJSON,fromOTel,fromPrisma,fromPrometheus,fromPromise,fromPulsar,fromRabbitMQ,fromRaf,fromRedisStream,fromSSE,fromSqlite,fromSqliteCursor,fromStatsD,fromSyslog,fromTimer,fromWebSocket,fromWebSocketReconnect,fromWebhook,globToRegExp,graph,graphProfile,graphspec,guarded,harness,interval,isBatching,isV1,jobQueue,jotai,keepalive,last,layout,lens,linear,listSnapshots,lru,map,matchesAnyPattern,matchesCron,memory,memoryStorage,merge,mergeMap,mermaidLiveUrl,messaging,monotonicNs,nameToSignal,nanostores,ndjsonRows,nestjs,never,node,normalizeActor,of,orchestration,pairwise,parseCron,parsePrometheusText,parseStatsD,parseSyslog,patterns,pausable,pipe,policy,policyFromRules,producer,pubsub,race,rateLimiter,reachable,react,reactiveCounter,reactiveIndex,reactiveList,reactiveLog,reactiveMap,reactiveSink,reduce,reduction,refine,registerBuiltinCodecs,registerBuiltins,repeat,replay,replayWAL,rescue,resilientPipeline,resolveBackoffPreset,resolveDescribeFields,restoreSnapshot,retry,retrySource,runReduction,sample,saveSnapshot,scan,serializeError,share,shareReplay,signalToName,signals,singleFromAny,singleNodeFromAny,sizeof,skip,solid,sortJsonValue,stableJsonString,state,stratify,surface,svelte,switchMap,take,takeUntil,takeWhile,tap,throttle,throttleTime,throwError,timeout,toArray,toCSV,toClickHouse,toFile,toHTTP,toKafka,toLoki,toMongo,toNATS,toObservable,toPostgres,toPulsar,toRabbitMQ,toReadableStream,toRedisStream,toS3,toSSE,toSSEBytes,toSqlite,toTempo,toWebSocket,tokenBucket,validateGraphObservability,valve,verifiable,version,vue,wallClockNs,watchTopologyTree,window,windowCount,windowTime,withBreaker,withLatestFrom,withMaxAttempts,withStatus,workerBridge,workerSelf,zip,zustand});
221
+ `)}`,{errors:o.errors});try{return so(t,e)}catch(s){let i=s instanceof Error?s.message:String(s);throw new ke("catalog-error",i)}}ie();var Dy=3e4;async function di(t,e,n){let r=n?.inputPath??"input",o=n?.outputPath??"output",s=n?.timeoutMs??Dy,i=or(t,{catalog:n?.catalog}),a;try{a=i.resolve(o)}catch{throw i.destroy(),new ke("node-not-found",`reduce: output path "${o}" is not registered`,{path:o})}try{i.resolve(r)}catch{throw i.destroy(),new ke("node-not-found",`reduce: input path "${r}" is not registered`,{path:r})}try{return await new Promise((u,c)=>{let d=!1,l=!1,f,p,m=!1,h=g=>{l||(l=!0,f!==void 0&&clearTimeout(f),p!==void 0?(p(),p=void 0):m=!0,g())};p=a.subscribe(g=>{for(let y of g){if(l)return;if(d){if(y[0]===S){h(()=>u(y[1]));return}if(y[0]===$){let b=a.cache;h(()=>u(b));return}if(y[0]===O){let b=y[1],v=b instanceof Error?b.message:String(b),T=b instanceof Error?b:void 0;h(()=>c(new ke("internal-error",`reduce: output emitted ERROR: ${v}`,T!=null?{cause:T}:void 0)));return}if(y[0]===M){h(()=>c(new ke("internal-error","reduce: output COMPLETEd without a post-push DATA")));return}}}}),m&&(p?.(),p=void 0),d=!0;try{i.set(r,e)}catch(g){let y=g instanceof Error?g.message:String(g),b=g instanceof Error?g:void 0;h(()=>c(new ke("internal-error",`reduce: failed to set input on "${r}": ${y}`,b!=null?{path:r,cause:b}:{path:r})));return}!l&&Number.isFinite(s)&&s>0&&(f=setTimeout(()=>{h(()=>c(new ke("reduce-timeout",`reduce: no output emitted within ${s}ms`,{timeoutMs:s,outputPath:o})))},s),f.unref?.())})}finally{i.destroy()}}we();var lo=lt,uo="snapshot:";function co(t){if(t.startsWith(uo))throw new ke("snapshot-failed",`snapshot id must not start with "${uo}" (reserved); got "${t}"`,{snapshotId:t})}function li(t){return`${uo}${t}`}function Gy(t){return t.startsWith(uo)?t.slice(uo.length):void 0}function bu(t,e){if(t==null||typeof t!="object")throw new ke("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 ke("restore-failed",`snapshot "${e}" is a diff record; restore the baseline and replay WAL instead`,{snapshotId:e,mode:"diff"}):new ke("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 ke("restore-failed",`snapshot "${e}" payload is not a GraphCheckpointRecord or GraphPersistSnapshot`,{snapshotId:e})}async function pi(t,e,n){co(e);let r;try{r=t.snapshot()}catch(s){let i=s instanceof Error?s.message:String(s);throw new ke("snapshot-failed",`snapshot "${e}" serialization failed: ${i}`,{snapshotId:e})}let o={mode:"full",seq:0,timestamp_ns:le(),format_version:lo,snapshot:r};try{await n.save(li(e),o)}catch(s){let i=s instanceof Error?s.message:String(s);throw new ke("snapshot-failed",`snapshot "${e}" save failed: ${i}`,{snapshotId:e})}return{snapshotId:e,timestamp_ns:o.timestamp_ns}}async function fi(t,e,n){co(t);let r=li(t),o=await e.load(r);o==null&&(o=await e.load(t));let s=bu(o,t);try{return q.fromSnapshot(s,n?.factories?{factories:n.factories}:void 0)}catch(i){let a=i instanceof Error?i.message:String(i);throw new ke("restore-failed",`snapshot "${t}" restore failed: ${a}`,{snapshotId:t})}}async function mi(t,e,n){co(t),co(e);let r=async u=>{let c=li(u),d=await n.load(c);return d==null&&(d=await n.load(u)),d},[o,s]=await Promise.all([r(t),r(e)]),i=bu(o,t),a=bu(s,e);return q.diff(i,a)}async function hi(t,e){if(typeof t.list!="function")throw new ke("tier-no-list","StorageTier does not implement list(); wrap the tier with an enumerator or use a different backend");let n=await t.list(),r=[],o=e?.includeUnprefixed===!0;for(let s of n){let i=Gy(s);i!==void 0?r.push(i):o&&r.push(s)}return r}async function gi(t,e){if(co(t),typeof e.clear!="function")throw new ke("snapshot-failed",`StorageTier is append-only (no clear()); cannot delete "${t}"`,{snapshotId:t});try{await e.clear(li(t))}catch(n){let r=n instanceof Error?n.message:String(n);throw new ke("snapshot-failed",`snapshot "${t}" delete failed: ${r}`,{snapshotId:t})}}var Fy="0.0.0";0&&(module.exports={COMPLETE,COMPLETE_MSG,COMPLETE_ONLY_BATCH,CircuitOpenError,ContentAddressedMissError,DATA,DEFAULT_ACTOR,DIRTY,DIRTY_MSG,DIRTY_ONLY_BATCH,ENVELOPE_VERSION,ERROR,GRAPH_META_SEGMENT,Graph,GraphReFlyConfig,GuardDenied,INVALIDATE,INVALIDATE_MSG,INVALIDATE_ONLY_BATCH,JsonCodec,NS_PER_MS,NS_PER_SEC,NativeIndexBackend,NativeListBackend,NativeLogBackend,NativeMapBackend,NativePubSubBackend,NodeImpl,PAUSE,RESOLVED,RESOLVED_MSG,RESOLVED_ONLY_BATCH,RESUME,RateLimiterOverflowError,ResettableTimer,SIZEOF_OVERHEAD,SIZEOF_SYMBOL,SNAPSHOT_VERSION,SNAPSHOT_WIRE_VERSION,START,START_MSG,SurfaceError,TEARDOWN,TEARDOWN_MSG,TEARDOWN_ONLY_BATCH,TimeoutError,accessHintForGuard,accountability,advanceVersion,ai,asSurfaceError,audit,autoTrackNode,awaitSettled,batch,buffer,bufferCount,bufferTime,cached,canonicalJson,cascadingCache,catchError,checkpointToRedis,checkpointToS3,circuitBreaker,combine,combineLatest,compat,concat,concatMap,configure,constant,contentAddressedStorage,core,cqrs,createDagCborCodec,createDagCborZstdCodec,createGraph,createTransport,createVersioning,createWatermarkController,csvRows,debounce,debounceTime,decodeEnvelope,decorrelatedJitter,defaultConfig,defaultHash,delay,deleteSnapshot,demoShell,derived,deserializeError,dictStorage,diffForWAL,diffSnapshots,distill,distinctUntilChanged,domainTemplates,downWithBatch,dynamicNode,effect,elementAt,empty,encodeEnvelope,escapeRegexChar,exhaustMap,explainPath,exponential,externalBundle,externalProducer,extra,fallback,fibonacci,filter,find,first,firstValueFrom,firstWhere,flatMap,forEach,fromAny,fromAsyncIter,fromCSV,fromClickHouseWatch,fromCron,fromDrizzle,fromEvent,fromHTTP,fromHTTPPoll,fromHTTPStream,fromIter,fromKafka,fromKysely,fromMCP,fromNATS,fromNDJSON,fromOTel,fromPrisma,fromPrometheus,fromPromise,fromPulsar,fromRabbitMQ,fromRaf,fromRedisStream,fromSSE,fromSqlite,fromSqliteCursor,fromStatsD,fromSyslog,fromTimer,fromWebSocket,fromWebSocketReconnect,fromWebhook,globToRegExp,graph,graphProfile,graphspec,guarded,harness,interval,isBatching,isV1,jobQueue,jotai,keepalive,last,layout,lens,linear,listSnapshots,lru,makeHttpError,map,matchesAnyPattern,matchesCron,memory,memoryStorage,merge,mergeMap,mermaidLiveUrl,messaging,monotonicNs,nameToSignal,nanostores,ndjsonRows,nestjs,never,node,nodeSignal,normalizeActor,of,onFirstData,orchestration,pairwise,parseCron,parsePrometheusText,parseSSEStream,parseStatsD,parseSyslog,patterns,pausable,pipe,policy,policyFromRules,producer,pubsub,race,rateLimiter,reachable,react,reactiveCounter,reactiveIndex,reactiveList,reactiveLog,reactiveMap,reactiveSink,reduce,reduction,refine,registerBuiltinCodecs,registerBuiltins,repeat,replay,replayWAL,rescue,resilientPipeline,resolveBackoffPreset,resolveDescribeFields,restoreSnapshot,retry,retrySource,runReduction,sample,saveSnapshot,scan,serializeError,share,shareReplay,signalToName,signals,singleFromAny,singleNodeFromAny,sizeof,skip,solid,sortJsonValue,stableJsonString,state,stratify,surface,svelte,switchMap,take,takeUntil,takeWhile,tap,tapFirst,throttle,throttleTime,throwError,timeout,toArray,toCSV,toClickHouse,toFile,toHTTP,toKafka,toLoki,toMongo,toNATS,toObservable,toPostgres,toPulsar,toRabbitMQ,toReadableStream,toRedisStream,toS3,toSSE,toSSEBytes,toSqlite,toTempo,toWebSocket,tokenBucket,validateGraphObservability,valve,verifiable,version,vue,wallClockNs,watchTopologyTree,window,windowCount,windowTime,withBreaker,withLatestFrom,withMaxAttempts,withStatus,workerBridge,workerSelf,zip,zustand});