@graphrefly/graphrefly 0.36.0 → 0.38.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.
- package/dist/{chunk-J6TGRQUP.js → chunk-2YFDSYEF.js} +1 -1
- package/dist/{chunk-JUJEPZOI.js → chunk-4BDQXBXE.js} +1 -1
- package/dist/chunk-5BGFS2XH.js +1 -0
- package/dist/chunk-6773HURD.js +1 -0
- package/dist/{chunk-AQC53OWG.js → chunk-6KZZ6XQE.js} +1 -1
- package/dist/{chunk-5CPPC75H.js → chunk-6VFC334U.js} +1 -1
- package/dist/{chunk-KUVDFOJH.js → chunk-7KZZLWZ6.js} +1 -1
- package/dist/{chunk-Q7EUZ6NN.js → chunk-B5S7KTGP.js} +1 -1
- package/dist/chunk-CMTN3KPT.js +80 -0
- package/dist/chunk-DQJLC6YY.js +1 -0
- package/dist/chunk-DSOVKKTI.js +1 -0
- package/dist/chunk-FAYEMS5M.js +1 -0
- package/dist/chunk-FWGIZP3W.js +1 -0
- package/dist/{chunk-5Z3AFBN7.js → chunk-G7JN6LCB.js} +1 -1
- package/dist/{chunk-PCD2MU7X.js → chunk-IBGE62GZ.js} +1 -1
- package/dist/{chunk-MYFR67PY.js → chunk-K5C67OGE.js} +1 -1
- package/dist/chunk-KJEAIIIY.js +43 -0
- package/dist/chunk-LV3ACS5J.js +1 -0
- package/dist/{chunk-7LYIKMW5.js → chunk-NBGPXQSP.js} +1 -1
- package/dist/chunk-NN3QPJ6U.js +1 -0
- package/dist/{chunk-T6RPUERH.js → chunk-NSAZ6PR6.js} +1 -1
- package/dist/{chunk-KCE6WWJE.js → chunk-NV63VQHI.js} +1 -1
- package/dist/{chunk-PYEIPRSZ.js → chunk-O245YLM5.js} +1 -1
- package/dist/{chunk-K5ZXJPWU.js → chunk-O2BLVQU4.js} +1 -1
- package/dist/chunk-PHXZRR6C.js +1 -0
- package/dist/{chunk-I57VSGRB.js → chunk-POCWFIJ7.js} +1 -1
- package/dist/{chunk-TQSTS3BY.js → chunk-QEVSIVSF.js} +1 -1
- package/dist/chunk-QMC2PLNM.js +7 -0
- package/dist/chunk-QOJFR6GS.js +1 -0
- package/dist/{chunk-MQZWA3DF.js → chunk-RZ5HKPGI.js} +1 -1
- package/dist/{chunk-XINLP35X.js → chunk-SFK7MN7S.js} +1 -1
- package/dist/{chunk-YOUAVGHJ.js → chunk-SP5O2MIX.js} +1 -1
- package/dist/chunk-TB7JKSVS.js +61 -0
- package/dist/{chunk-6G5YD37E.js → chunk-TMVY7OWG.js} +1 -1
- package/dist/{chunk-F36TA3ET.js → chunk-UAXFKMAG.js} +1 -1
- package/dist/{chunk-AACJX2L7.js → chunk-UVLZX2OU.js} +1 -1
- package/dist/chunk-XIMFHEKV.js +1 -0
- package/dist/{chunk-LO3LO2TO.js → chunk-XLMYQB6F.js} +1 -1
- package/dist/{chunk-44QWWUA3.js → chunk-XLYF4LBH.js} +1 -1
- package/dist/compat/index.cjs +9 -9
- package/dist/compat/index.d.cts +7 -7
- package/dist/compat/index.d.ts +7 -7
- package/dist/compat/index.js +1 -1
- package/dist/compat/nestjs/index.cjs +9 -9
- package/dist/compat/nestjs/index.d.cts +5 -5
- package/dist/compat/nestjs/index.d.ts +5 -5
- package/dist/compat/nestjs/index.js +1 -1
- package/dist/compat/zustand/index.cjs +7 -7
- package/dist/compat/zustand/index.d.cts +3 -3
- package/dist/compat/zustand/index.d.ts +3 -3
- package/dist/compat/zustand/index.js +1 -1
- package/dist/{composite-_XckYx2e.d.cts → composite-CgG0MqHm.d.cts} +8 -1
- package/dist/{composite-CT_mApQD.d.ts → composite-DTOlDuch.d.ts} +8 -1
- package/dist/core/index.cjs +1 -1
- package/dist/core/index.d.cts +2 -2
- package/dist/core/index.d.ts +2 -2
- package/dist/core/index.js +1 -1
- package/dist/extra/index.cjs +19 -19
- package/dist/extra/index.d.cts +5 -5
- package/dist/extra/index.d.ts +5 -5
- package/dist/extra/index.js +1 -1
- package/dist/extra/node.cjs +2 -2
- package/dist/extra/node.d.cts +107 -1
- package/dist/extra/node.d.ts +107 -1
- package/dist/extra/node.js +2 -2
- package/dist/extra/operators.cjs +1 -1
- package/dist/extra/operators.js +1 -1
- package/dist/extra/reactive.d.cts +1 -1
- package/dist/extra/reactive.d.ts +1 -1
- package/dist/extra/reactive.js +1 -1
- package/dist/extra/sources.cjs +1 -1
- package/dist/extra/sources.js +1 -1
- package/dist/extra/storage-tiers-browser.d.cts +76 -5
- package/dist/extra/storage-tiers-browser.d.ts +76 -5
- package/dist/extra/storage-tiers-node.d.cts +137 -13
- package/dist/extra/storage-tiers-node.d.ts +137 -13
- package/dist/extra/storage-tiers.d.cts +151 -23
- package/dist/extra/storage-tiers.d.ts +151 -23
- package/dist/graph/index.cjs +7 -7
- package/dist/graph/index.d.cts +4 -4
- package/dist/graph/index.d.ts +4 -4
- package/dist/graph/index.js +1 -1
- package/dist/{graph-Cv-8x0ZI.d.ts → graph-BjW1taJl.d.ts} +243 -11
- package/dist/{graph-kTltt95s.d.cts → graph-CHsVwf9S.d.cts} +243 -11
- package/dist/{index-CZAixNU3.d.ts → index-5dNRlW7J.d.ts} +3 -3
- package/dist/{index-DtSVSKnd.d.ts → index-AUqWe_fX.d.ts} +7 -4
- package/dist/{index-DLyQC5Ww.d.ts → index-B-ORMr3k.d.ts} +2 -2
- package/dist/{index-C4ig7whw.d.cts → index-B2IUcH13.d.cts} +2 -2
- package/dist/{index-KeBhbNg3.d.ts → index-BFaALJxR.d.ts} +2 -2
- package/dist/{index-CsD0fqnO.d.ts → index-BI1wMfyc.d.ts} +2 -2
- package/dist/{index-DxxvGTXp.d.ts → index-BUFCHvOR.d.ts} +2 -2
- package/dist/{index-HCp5ua_i.d.cts → index-BWUMIt7J.d.cts} +3 -3
- package/dist/{index-DHv2M7s8.d.cts → index-BaSy4L6w.d.cts} +37 -17
- package/dist/{index-BhkPzu-Z.d.cts → index-BgzPO43H.d.cts} +2 -2
- package/dist/{index-BsZlbHM5.d.cts → index-BhzwpIJc.d.cts} +1 -1
- package/dist/{index-BC-xjOrd.d.cts → index-BkQqf1EF.d.cts} +80 -7
- package/dist/{index-BBdwz2BW.d.ts → index-BmWuVdER.d.ts} +2 -2
- package/dist/{index-CVhBdCMf.d.ts → index-Bn0uZEL4.d.ts} +2 -2
- package/dist/{index-33mF4XyU.d.cts → index-BpMZzX9P.d.cts} +2 -2
- package/dist/{index-ZhKyR8co.d.cts → index-Bpr0Pwgl.d.cts} +2 -2
- package/dist/{index-2URa-V4S.d.cts → index-BqcgiSQg.d.cts} +2 -2
- package/dist/{index-DzYTXMBz.d.ts → index-BsZk9T8y.d.ts} +1 -1
- package/dist/{index-CvUrRb4m.d.cts → index-BsgxnHN8.d.cts} +2 -2
- package/dist/index-Bub6x_D4.d.cts +427 -0
- package/dist/{index-BZ1V5GzX.d.ts → index-BwOsJfLJ.d.ts} +2 -2
- package/dist/{index-BuMzxRO2.d.ts → index-Byp771zP.d.ts} +1 -1
- package/dist/{index-DKp1CIbG.d.cts → index-C-3UXnHT.d.cts} +1 -1
- package/dist/{index-GaW6Welt.d.cts → index-C56XZiDe.d.cts} +2 -2
- package/dist/{index-k67aNfqC.d.cts → index-CAV-3RpJ.d.cts} +2 -2
- package/dist/{index-DmtWMP0X.d.cts → index-CAbHN_rP.d.cts} +1 -1
- package/dist/{index-BTJxM-wZ.d.ts → index-CEVzBWeB.d.ts} +2 -2
- package/dist/{index-BVNGEX7d.d.cts → index-CM-i58FY.d.cts} +2 -2
- package/dist/{index-EfPb77rT.d.cts → index-CQsqqEVz.d.cts} +1 -1
- package/dist/{index-Cot94_82.d.ts → index-CijfwEWx.d.ts} +2 -2
- package/dist/{index-PluovH45.d.cts → index-Ckil6miL.d.cts} +2 -2
- package/dist/{index-XxSeddWP.d.cts → index-CpdnP-0y.d.cts} +1 -1
- package/dist/{index-Pu1Wa7en.d.ts → index-CrlHFsiT.d.ts} +37 -17
- package/dist/{index-BWH17rK_.d.cts → index-Czk3r0yA.d.cts} +37 -3
- package/dist/{index-BlRVj-7Q.d.cts → index-D-B7U42V.d.cts} +2 -2
- package/dist/{index-B4s70vYf.d.ts → index-D-HZ7sP4.d.ts} +2 -2
- package/dist/{index-Cjrpx2Mg.d.cts → index-D7-RSD93.d.cts} +2 -2
- package/dist/{index-kBUQj-rT.d.ts → index-D9vBTuzo.d.ts} +2 -2
- package/dist/{index-DzCQt2FJ.d.cts → index-DJNAWzcH.d.cts} +2 -2
- package/dist/{index-DSSsxS7B.d.ts → index-DJVQ-t07.d.ts} +2 -2
- package/dist/{index-BwYGLgmI.d.ts → index-DKrIuF-r.d.ts} +2 -2
- package/dist/{index-DXSLMoma.d.ts → index-DOU1Ee_k.d.ts} +1 -1
- package/dist/{index-DlccEIi3.d.ts → index-DTDVDzhA.d.ts} +37 -3
- package/dist/{index-B5UR87KG.d.ts → index-DY2f2b9z.d.ts} +4 -2
- package/dist/{index-D8IyqHvT.d.cts → index-DeSsvHDD.d.cts} +4 -2
- package/dist/index-Di7OdwlO.d.ts +427 -0
- package/dist/{index-isdlyeeO.d.ts → index-DqICM_I7.d.ts} +80 -7
- package/dist/{index-DFe2Pk2u.d.ts → index-ML6vHKXK.d.ts} +1 -1
- package/dist/{index-RJIY7QVW.d.cts → index-UsU9ptzs.d.cts} +7 -4
- package/dist/{index-jA_OwwNg.d.ts → index-Vz7KPfgz.d.ts} +1 -1
- package/dist/index.cjs +50 -50
- package/dist/index.d.cts +32 -32
- package/dist/index.d.ts +32 -32
- package/dist/index.js +1 -1
- package/dist/meta-BYqlATmg.d.ts +98 -0
- package/dist/meta-DreaEM_a.d.cts +98 -0
- package/dist/patterns/ai/browser.cjs +2 -2
- package/dist/patterns/ai/browser.js +1 -1
- package/dist/patterns/ai/index.cjs +21 -21
- package/dist/patterns/ai/index.d.cts +9 -9
- package/dist/patterns/ai/index.d.ts +9 -9
- package/dist/patterns/ai/index.js +1 -1
- package/dist/patterns/ai/node.js +1 -1
- package/dist/patterns/audit/index.cjs +7 -7
- package/dist/patterns/audit/index.d.cts +5 -5
- package/dist/patterns/audit/index.d.ts +5 -5
- package/dist/patterns/audit/index.js +1 -1
- package/dist/patterns/cqrs/index.cjs +7 -7
- package/dist/patterns/cqrs/index.d.cts +4 -4
- package/dist/patterns/cqrs/index.d.ts +4 -4
- package/dist/patterns/cqrs/index.js +1 -1
- package/dist/patterns/demo-shell/index.cjs +8 -8
- package/dist/patterns/demo-shell/index.d.cts +4 -4
- package/dist/patterns/demo-shell/index.d.ts +4 -4
- package/dist/patterns/demo-shell/index.js +1 -1
- package/dist/patterns/domain-templates/index.cjs +7 -7
- package/dist/patterns/domain-templates/index.d.cts +3 -3
- package/dist/patterns/domain-templates/index.d.ts +3 -3
- package/dist/patterns/domain-templates/index.js +1 -1
- package/dist/patterns/graphspec/index.cjs +21 -21
- package/dist/patterns/graphspec/index.d.cts +3 -3
- package/dist/patterns/graphspec/index.d.ts +3 -3
- package/dist/patterns/graphspec/index.js +1 -1
- package/dist/patterns/guarded-execution/index.cjs +7 -7
- package/dist/patterns/guarded-execution/index.d.cts +6 -6
- package/dist/patterns/guarded-execution/index.d.ts +6 -6
- package/dist/patterns/guarded-execution/index.js +1 -1
- package/dist/patterns/harness/index.cjs +12 -12
- package/dist/patterns/harness/index.d.cts +8 -8
- package/dist/patterns/harness/index.d.ts +8 -8
- package/dist/patterns/harness/index.js +1 -1
- package/dist/patterns/job-queue/index.cjs +7 -7
- package/dist/patterns/job-queue/index.d.cts +4 -4
- package/dist/patterns/job-queue/index.d.ts +4 -4
- package/dist/patterns/job-queue/index.js +1 -1
- package/dist/patterns/lens/index.cjs +7 -7
- package/dist/patterns/lens/index.d.cts +4 -4
- package/dist/patterns/lens/index.d.ts +4 -4
- package/dist/patterns/lens/index.js +1 -1
- package/dist/patterns/memory/index.cjs +7 -7
- package/dist/patterns/memory/index.d.cts +6 -4
- package/dist/patterns/memory/index.d.ts +6 -4
- package/dist/patterns/memory/index.js +1 -1
- package/dist/patterns/messaging/index.cjs +7 -7
- package/dist/patterns/messaging/index.d.cts +4 -4
- package/dist/patterns/messaging/index.d.ts +4 -4
- package/dist/patterns/messaging/index.js +1 -1
- package/dist/patterns/orchestration/index.cjs +7 -7
- package/dist/patterns/orchestration/index.d.cts +4 -4
- package/dist/patterns/orchestration/index.d.ts +4 -4
- package/dist/patterns/orchestration/index.js +1 -1
- package/dist/patterns/process/index.cjs +1 -1
- package/dist/patterns/process/index.d.cts +5 -5
- package/dist/patterns/process/index.d.ts +5 -5
- package/dist/patterns/process/index.js +1 -1
- package/dist/patterns/reactive-layout/index.cjs +8 -8
- package/dist/patterns/reactive-layout/index.d.cts +4 -4
- package/dist/patterns/reactive-layout/index.d.ts +4 -4
- package/dist/patterns/reactive-layout/index.js +1 -1
- package/dist/patterns/reduction/index.cjs +7 -7
- package/dist/patterns/reduction/index.d.cts +3 -3
- package/dist/patterns/reduction/index.d.ts +3 -3
- package/dist/patterns/reduction/index.js +1 -1
- package/dist/patterns/refine-loop/index.cjs +8 -8
- package/dist/patterns/refine-loop/index.d.cts +5 -5
- package/dist/patterns/refine-loop/index.d.ts +5 -5
- package/dist/patterns/refine-loop/index.js +1 -1
- package/dist/patterns/resilient-pipeline/index.cjs +1 -1
- package/dist/patterns/resilient-pipeline/index.d.cts +4 -4
- package/dist/patterns/resilient-pipeline/index.d.ts +4 -4
- package/dist/patterns/resilient-pipeline/index.js +1 -1
- package/dist/patterns/surface/index.cjs +14 -14
- package/dist/patterns/surface/index.d.cts +4 -4
- package/dist/patterns/surface/index.d.ts +4 -4
- package/dist/patterns/surface/index.js +1 -1
- package/dist/{pipeline-graph-DdBoRu37.d.ts → pipeline-graph-9JBbmRxA.d.ts} +2 -2
- package/dist/{pipeline-graph-BlLBWSZ2.d.cts → pipeline-graph-DuHpXSOn.d.cts} +2 -2
- package/dist/{reactive-layout-D9zqqaqK.d.cts → reactive-layout-BMLDB4Vd.d.cts} +1 -1
- package/dist/{reactive-layout-Btv0-efV.d.ts → reactive-layout-D-tRiNhg.d.ts} +1 -1
- package/dist/{reactive-log-jirQsxMY.d.ts → reactive-log-BgWSA1fg.d.ts} +28 -1
- package/dist/{reactive-log-ScpWyqny.d.cts → reactive-log-C3IMAGpT.d.cts} +28 -1
- package/dist/resilience-LGBK236C.js +1 -0
- package/dist/{topology-tree-CJsT24DP.d.ts → topology-tree-D47-nI6Z.d.ts} +1 -1
- package/dist/{topology-tree-C50l9ARE.d.cts → topology-tree-jrZue3ao.d.cts} +1 -1
- package/package.json +1 -1
- package/dist/chunk-3U7IIQB2.js +0 -1
- package/dist/chunk-533RQFF6.js +0 -1
- package/dist/chunk-5CZ3KIRJ.js +0 -1
- package/dist/chunk-5KPIYVCC.js +0 -7
- package/dist/chunk-5RTZ6DXG.js +0 -1
- package/dist/chunk-A5HZZYRK.js +0 -1
- package/dist/chunk-CGA5RXO6.js +0 -1
- package/dist/chunk-DBPFMCVH.js +0 -1
- package/dist/chunk-GWOKTENT.js +0 -1
- package/dist/chunk-JJTF75VS.js +0 -1
- package/dist/chunk-KL7CILPL.js +0 -1
- package/dist/chunk-M27MVZCP.js +0 -1
- package/dist/chunk-N2GCKKKH.js +0 -43
- package/dist/chunk-QKUWS7CO.js +0 -80
- package/dist/chunk-YBA5N4XY.js +0 -61
- package/dist/index-CI_yjtua.d.ts +0 -139
- package/dist/index-D9qoEOj_.d.cts +0 -139
- package/dist/meta-BGO6C7K9.d.cts +0 -41
- package/dist/meta-CC6EPdpK.d.ts +0 -41
- package/dist/resilience-OBU472D2.js +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,55 +1,55 @@
|
|
|
1
|
-
"use strict";var Of=Object.create;var En=Object.defineProperty;var td=Object.getOwnPropertyDescriptor;var Cf=Object.getOwnPropertyNames;var Af=Object.prototype.hasOwnProperty;var nd=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),gr=t=>{throw TypeError(t)};var Lf=(t,e,n)=>e in t?En(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Xu=(t,e)=>En(t,"name",{value:e,configurable:!0});var tt=(t,e)=>()=>(t&&(e=t(t=0)),e);var ke=(t,e)=>{for(var n in e)En(t,n,{get:e[n],enumerable:!0})},If=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Cf(e))!Af.call(t,o)&&o!==n&&En(t,o,{get:()=>e[o],enumerable:!(r=td(e,o))||r.enumerable});return t};var Pf=t=>If(En({},"__esModule",{value:!0}),t);var rd=t=>[,,,Of(t?.[nd("metadata")]??null)],od=["class","method","getter","setter","accessor","field","value","get","set"],mr=t=>t!==void 0&&typeof t!="function"?gr("Function expected"):t,Df=(t,e,n,r,o)=>({kind:od[t],name:e,metadata:r,addInitializer:s=>n._?gr("Already initialized"):o.push(mr(s||null))}),Gf=(t,e)=>Lf(e,nd("metadata"),t[3]),sd=(t,e,n,r)=>{for(var o=0,s=t[e>>1],i=s&&s.length;o<i;o++)e&1?s[o].call(n):r=s[o].call(n,r);return r},id=(t,e,n,r,o,s)=>{var i,a,u,d,c,l=e&7,p=!!(e&8),f=!!(e&16),m=l>3?t.length+1:l?p?1:2:0,h=od[l+5],g=l>3&&(t[m-1]=[]),y=t[m]||(t[m]=[]),b=l&&(!f&&!p&&(o=o.prototype),l<5&&(l>3||!f)&&td(l<4?o:{get[n](){return Zu(this,s)},set[n](T){return ed(this,s,T)}},n));l?f&&l<4&&Xu(s,(l>2?"set ":l>1?"get ":"")+n):Xu(o,n);for(var v=r.length-1;v>=0;v--)d=Df(l,n,u={},t[3],y),l&&(d.static=p,d.private=f,c=d.access={has:f?T=>Ff(o,T):T=>n in T},l^3&&(c.get=f?T=>(l^1?Zu:$f)(T,o,l^4?s:b.get):T=>T[n]),l>2&&(c.set=f?(T,w)=>ed(T,o,w,l^4?s:b.set):(T,w)=>T[n]=w)),a=(0,r[v])(l?l<4?f?s:b[h]:l>4?void 0:{get:b.get,set:b.set}:o,d),u._=1,l^4||a===void 0?mr(a)&&(l>4?g.unshift(a):l?f?s=a:b[h]=a:o=a):typeof a!="object"||a===null?gr("Object expected"):(mr(i=a.get)&&(b.get=i),mr(i=a.set)&&(b.set=i),mr(i=a.init)&&g.unshift(i));return l||Gf(t,o),b&&En(o,n,b),f?l^4?s:b:o};var Ui=(t,e,n)=>e.has(t)||gr("Cannot "+n),Ff=(t,e)=>Object(e)!==e?gr('Cannot use the "in" operator on this value'):t.has(e),Zu=(t,e,n)=>(Ui(t,e,"read from private field"),n?n.call(t):e.get(t));var ed=(t,e,n,r)=>(Ui(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),$f=(t,e,n)=>(Ui(t,e,"access private method"),n);var dt,E,ne,V,Je,Be,qe,le,L,C,Et,Nn,Mo,_n,Oo,Co,Mn,hr,yr,br,On,ae=tt(()=>{"use strict";dt=Symbol.for("graphrefly/START"),E=Symbol.for("graphrefly/DATA"),ne=Symbol.for("graphrefly/DIRTY"),V=Symbol.for("graphrefly/RESOLVED"),Je=Symbol.for("graphrefly/INVALIDATE"),Be=Symbol.for("graphrefly/PAUSE"),qe=Symbol.for("graphrefly/RESUME"),le=Symbol.for("graphrefly/TEARDOWN"),L=Symbol.for("graphrefly/COMPLETE"),C=Symbol.for("graphrefly/ERROR"),Et=Object.freeze([ne]),Nn=Object.freeze([V]),Mo=Object.freeze([Je]),_n=Object.freeze([dt]),Oo=Object.freeze([L]),Co=Object.freeze([le]),Mn=Object.freeze([Et]),hr=Object.freeze([Nn]),yr=Object.freeze([Mo]),br=Object.freeze([Oo]),On=Object.freeze([Co])});function Ji(t){return{name:"dag-cbor",version:1,contentType:"application/dag-cbor",encode:e=>t.encode(e),decode:(e,n)=>t.decode(e)}}function Yi(t,e){return{name:"dag-cbor-zstd",version:1,contentType:"application/dag-cbor+zstd",encode:n=>e.compressSync(t.encode(n)),decode:(n,r)=>t.decode(e.decompressSync(n))}}function vr(t,e){let n=new TextEncoder().encode(t.name);if(n.length===0||n.length>255)throw new Error(`encodeEnvelope: codec name "${t.name}" encodes to ${n.length} bytes (must be 1\u2013255)`);let r=t.version;if(!Number.isInteger(r)||r<0||r>65535)throw new Error(`encodeEnvelope: codec.version ${r} out of u16 range (expected integer 0\u201365535)`);let o=2+n.length+2+e.length;if(o>4294967295)throw new Error(`encodeEnvelope: total envelope size ${o} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let s=new Uint8Array(o),i=0;return s[i++]=Cn,s[i++]=n.length,s.set(n,i),i+=n.length,s[i++]=r>>>8&255,s[i++]=r&255,s.set(e,i),s}function Tr(t,e){if(t.length<ad)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${ad})`);let n=0,r=t[n++];if(r!==Cn)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${Cn})`);let o=t[n++];if(o===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(n+o+2>t.length)throw new Error(`decodeEnvelope: envelope truncated (need ${n+o+2} bytes, have ${t.length})`);let s=new TextDecoder().decode(t.subarray(n,n+o));n+=o;let i=(t[n]<<8|t[n+1])>>>0;n+=2;let a=t.subarray(n),u=e.lookupCodec(s);if(u==null)throw new Error(`decodeEnvelope: codec "${s}" not registered (envelope codec_v=${i})`);return{codec:u,codecVersion:i,payload:a}}function wr(t){t.registerCodec(Ao)}function Qi(t){if(t.length===0)throw new Error("WAL is empty \u2014 need at least one full snapshot");let e=t[0];if(e.mode!=="full")throw new Error("WAL must start with a full record carrying a baseline snapshot");let n=JSON.parse(JSON.stringify(e.snapshot)),r=e.seq;for(let o=1;o<t.length;o++){let s=t[o];if(s.seq<=r)throw new Error(`WAL chain broken at index ${o}: seq=${s.seq} must exceed prev seq=${r}`);if(s.mode==="full"){n=JSON.parse(JSON.stringify(s.snapshot)),r=s.seq;continue}let i=s.diff;for(let u of i.nodesRemoved)delete n.nodes[u];let a=i.nodesAddedFull;if(a!=null)for(let[u,d]of Object.entries(a))n.nodes[u]=JSON.parse(JSON.stringify(d));for(let u of i.nodesChanged){let d=n.nodes[u.path];d!=null&&(d[u.field]=u.to)}r=s.seq}return n}var Ao,Cn,ad,Lo=tt(()=>{"use strict";Ao={name:"json",version:1,contentType:"application/json",encode(t){let e=JSON.stringify(t);return new TextEncoder().encode(e)},decode(t,e){let n=new TextDecoder().decode(t);return JSON.parse(n)}};Cn=1,ad=4});function Nt(t){if(t==null)return bt;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var bt,kr=tt(()=>{"use strict";bt={type:"system",id:""}});function tn(){return An>0||xr}function ud(){return An>0}function Sr(t){An>0?Rr.push(t):t()}function X(t){An+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(An-=1,An===0)if(e){if(!xr){let n=Rr.splice(0);for(let r of n)try{r()}catch{}Zt.length=0,en.length=0,Ln.length=0}}else jf()}}function jf(){let t=!xr;t&&(xr=!0);let e=[],n=0;try{for(;Zt.length>0||en.length>0||Ln.length>0||t&&Rr.length>0;){if(t&&Rr.length>0){let s=Rr.splice(0);for(let i of s)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw Zt.length=0,en.length=0,Ln.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let o=(Zt.length>0?Zt:en.length>0?en:Ln).splice(0);for(let s of o)try{s()}catch(i){e.push(i)}}}finally{t&&(xr=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function _t(t,e,n){if(e.length===0)return;if(e.length===1){let d=n(e[0][0]);if(d<3||!tn()){t(e);return}(d>=5?Ln:d===4?en:Zt).push(()=>t(e));return}let r=e.length,o=r,s=r,i=r,a=0;for(;a<r&&n(e[a][0])<3;)a++;for(o=a;a<r&&n(e[a][0])===3;)a++;for(s=a;a<r&&n(e[a][0])===4;)a++;i=a;let u=tn();if(o>0){let d=e.slice(0,o);t(d)}if(s>o){let d=e.slice(o,s);u?Zt.push(()=>t(d)):t(d)}if(i>s){let d=e.slice(s,i);u?en.push(()=>t(d)):t(d)}if(r>i){let d=e.slice(i,r);u?Ln.push(()=>t(d)):t(d)}}var An,xr,Zt,en,Ln,Rr,Me=tt(()=>{"use strict";An=0,xr=!1,Zt=[],en=[],Ln=[],Rr=[]});function H(){return Math.trunc(performance.now()*1e6)}function oe(){return Date.now()*1e6}var xe=tt(()=>{"use strict"});function Er(t){t.registerMessageType(dt,{tier:0,wireCrossing:!1}),t.registerMessageType(ne,{tier:1,wireCrossing:!1}),t.registerMessageType(Je,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(Be,{tier:2,wireCrossing:!1}),t.registerMessageType(qe,{tier:2,wireCrossing:!1}),t.registerMessageType(E,{tier:3,wireCrossing:!0}),t.registerMessageType(V,{tier:3,wireCrossing:!0}),t.registerMessageType(L,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(C,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(le,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var nn,Xi=tt(()=>{"use strict";ae();nn=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_rigorRecorder;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=n=>{let r=this._messageTypes.get(n);return r!=null?r.tier:1}}get onMessage(){return this._frozen=!0,this._onMessage}get onSubscribe(){return this._frozen=!0,this._onSubscribe}set onMessage(e){this._assertUnfrozen(),this._onMessage=e}set onSubscribe(e){this._assertUnfrozen(),this._onSubscribe=e}get defaultVersioning(){return this._defaultVersioning}set defaultVersioning(e){this._assertUnfrozen(),this._defaultVersioning=e}get defaultHashFn(){return this._defaultHashFn}set defaultHashFn(e){this._assertUnfrozen(),this._defaultHashFn=e}get inspectorEnabled(){return this._inspectorEnabled}set inspectorEnabled(e){this._inspectorEnabled=e}get globalInspector(){return this._globalInspector}set globalInspector(e){this._globalInspector=e}get rigorRecorder(){return this._rigorRecorder}set rigorRecorder(e){this._rigorRecorder=e}registerMessageType(e,n){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:n.tier,wireCrossing:n.wireCrossing??n.tier>=3,metaPassthrough:n.metaPassthrough??!0}),this}messageTier(e){let n=this._messageTypes.get(e);return n!=null?n.tier:1}isWireCrossing(e){let n=this._messageTypes.get(e);return n!=null?n.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let n=this._messageTypes.get(e);return n!=null?n.metaPassthrough:!0}isKnownMessageType(e){return this._messageTypes.has(e)}registerCodec(e){return this._assertUnfrozen(),this._codecs.set(e.name,e),this}lookupCodec(e){return this._codecs.get(e)}_isFrozen(){return this._frozen}_assertUnfrozen(){if(this._frozen)throw new Error("GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node.")}}});function dd(t){return Array.isArray(t)?[...t]:[t]}function Bf(t,e){return t.has(e)||t.has("*")}function Mt(t){let e=[];return t((o,s)=>{e.push({kind:"allow",actions:new Set(dd(o)),where:s?.where??(()=>!0)})},(o,s)=>{e.push({kind:"deny",actions:new Set(dd(o)),where:s?.where??(()=>!0)})}),(o,s)=>{let i=!1,a=!1;for(let u of e)Bf(u.actions,s)&&u.where(o)&&(u.kind==="deny"?i=!0:a=!0);return i?!1:a}}function Nr(t){return Mt((e,n)=>{for(let r of t){let o=r.actorType==null?null:new Set(Array.isArray(r.actorType)?r.actorType:[r.actorType]),s=r.actorId==null?null:new Set(Array.isArray(r.actorId)?r.actorId:[r.actorId]),i=Object.entries(r.claims??{}),a=u=>{if(o!==null&&!o.has(String(u.type))||s!==null&&!s.has(String(u.id??"")))return!1;for(let[d,c]of i)if(u[d]!==c)return!1;return!0};r.effect==="deny"?n(r.action,{where:a}):e(r.action,{where:a})}})}function _r(t){let e=Vf.filter(n=>t({type:n,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(n=>n==="human"||n==="llm"||n==="system")?"both":e.length===1?e[0]:e.join("+")}var rt,Vf,$t=tt(()=>{"use strict";rt=class extends Error{actor;action;nodeName;constructor(e,n){super(n??`GuardDenied: action "${String(e.action)}" denied for actor type "${String(e.actor.type)}"`),this.name="GuardDenied",this.actor=e.actor,this.action=e.action,this.nodeName=e.nodeName}get node(){return this.nodeName}};Vf=["human","llm","wallet","system"]});function Zi(t){if(t===void 0)return null;if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`Cannot hash non-finite number: ${t}`);if(Number.isInteger(t)&&!Number.isSafeInteger(t))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${t}. Cross-language cid parity is not guaranteed for unsafe integers.`);return t}if(typeof t=="string"||typeof t=="boolean"||t===null)return t;if(Array.isArray(t))return t.map(Zi);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=Zi(t[n]);return e}return null}function Hf(t){let e=qf.encode(t),n=e.length,r=n*8,o=n+9+63&-64,s=new Uint8Array(o);s.set(e),s[n]=128;let i=new DataView(s.buffer);i.setUint32(o-4,r>>>0,!1),i.setUint32(o-8,Math.floor(r/4294967296)>>>0,!1);let a=1779033703,u=3144134277,d=1013904242,c=2773480762,l=1359893119,p=2600822924,f=528734635,m=1541459225,h=new Uint32Array(64),g=(b,v)=>b>>>v|b<<32-v;for(let b=0;b<o;b+=64){for(let _=0;_<16;_++)h[_]=i.getUint32(b+_*4,!1);for(let _=16;_<64;_++){let I=h[_-15],O=h[_-2],P=g(I,7)^g(I,18)^I>>>3,B=g(O,17)^g(O,19)^O>>>10;h[_]=h[_-16]+P+h[_-7]+B>>>0}let v=a,T=u,w=d,x=c,k=l,S=p,R=f,N=m;for(let _=0;_<64;_++){let I=g(k,6)^g(k,11)^g(k,25),O=k&S^~k&R,P=N+I+O+Kf[_]+h[_]>>>0,B=g(v,2)^g(v,13)^g(v,22),j=v&T^v&w^T&w,D=B+j>>>0;N=R,R=S,S=k,k=x+P>>>0,x=w,w=T,T=v,v=P+D>>>0}a=a+v>>>0,u=u+T>>>0,d=d+w>>>0,c=c+x>>>0,l=l+k>>>0,p=p+S>>>0,f=f+R>>>0,m=m+N>>>0}let y=b=>b.toString(16).padStart(8,"0");return y(a)+y(u)+y(d)+y(c)+y(l)+y(p)+y(f)+y(m)}function jt(t){let e=Zi(t??null),n=JSON.stringify(e);return Hf(n).slice(0,16)}function Wf(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),n=e()+e()+e()+e();return`${n.slice(0,8)}-${n.slice(8,12)}-4${n.slice(13,16)}-${(parseInt(n.slice(16,17),16)&3|8).toString(16)}${n.slice(17,20)}-${n.slice(20,32)}`}function In(t,e,n){let r=n?.id??Wf();if(t===0)return{id:r,version:0};let s=(n?.hash??jt)(e);return{id:r,version:0,cid:s,prev:null}}function Mr(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}function ea(t){return"cid"in t}var Kf,qf,Io=tt(()=>{"use strict";Kf=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),qf=new TextEncoder});function pd(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function ta(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function Po(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function ra(t){if($e._isFrozen())throw new Error("configure() called after a node was created \u2014 the default GraphReFlyConfig is frozen. Call configure(...) at application startup, before any node factories run.");t($e)}function z(t,e,n){let r=fd(t)?t:[],o=typeof t=="function"?t:typeof e=="function"?e:void 0,s={};return fd(t)?s=(na(e)?e:n)??{}:na(t)?s=t:s=(na(e)?e:n)??{},new Ae(r,o,s)}var cd,ld,zf,Uf,$e,Ae,fd,na,_e=tt(()=>{"use strict";Lo();kr();Me();xe();Xi();$t();ae();Io();cd=()=>{},ld=100;zf=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},Uf=(t,e,n,r)=>{let o=t;if(o._status==="completed"||o._status==="errored")return;let s=o._cached,i=s===void 0?[_n]:[_n,[E,s]];o._status==="dirty"&&i.push(Et),_t(e,i,o._config.tierOf)},$e=new nn({onMessage:zf,onSubscribe:Uf});Er($e);wr($e);Ae=class t{_optsName;_describeKind;meta;_hasMeta;_config;_deps;_sinks=null;_sinkCount=0;_cached;_status;_cleanup;_store={};_waveHasNewData=!1;_hasNewTerminal=!1;_hasCalledFnOnce=!1;_paused=!1;_pendingWave=!1;_isExecutingFn=!1;_pendingRerun=!1;_rerunDepth=0;_dirtyDepCount=0;_batchPendingMessages=null;_pauseLocks=null;_pauseBuffer=null;_fn;_equals;_resubscribable;_resetOnTeardown;_autoComplete;_autoError;_pausable;_partial;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,n,r){this._config=r.config??$e,this._config.onMessage,this._optsName=r.name,this._describeKind=r.describeKind,this._equals=r.equals??Object.is,this._resubscribable=r.resubscribable??!1,this._resetOnTeardown=r.resetOnTeardown??!1,this._autoComplete=r.completeWhenDepsComplete??!0,this._autoError=r.errorWhenDepsError??!0,this._pausable=r.pausable??!0,this._guard=r.guard,this._fn=n,this._partial=r.partial??!1,this._cached=r.initial!==void 0?r.initial:void 0,this._status=e.length===0&&n==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=r.versioningHash??this._config.defaultHashFn??jt;let o=r.versioning??this._config.defaultVersioning;this._versioningLevel=o,this._versioning=o!=null?In(o,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(pd);let s={};for(let[a,u]of Object.entries(r.meta??{})){let d={initial:u,name:`${r.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};r.guard!=null&&(d.guard=r.guard),s[a]=new t([],void 0,d)}Object.freeze(s),this.meta=s,this._hasMeta=Object.keys(s).length>0;let i=this;this._actions={emit(a){i._emit([[E,a]])},down(a){i._emit(Po(a))},up(a){i._emitUp(Po(a))}},this.down=this.down.bind(this),this.up=this.up.bind(this)}get _isTerminal(){return this._status==="completed"||this._status==="errored"}get name(){return this._optsName}get status(){return this._status}get cache(){return this._cached===void 0?void 0:this._cached}get lastMutation(){return this._lastMutation}get v(){return this._versioning}hasGuard(){return this._guard!=null}_applyVersioning(e,n){if(this._isExecutingFn)throw new Error(`Node "${this.name}": _applyVersioning cannot run mid-fn \u2014 call it outside of \`_execFn\` (typically at graph setup time before the first subscribe).`);let r=this._versioningLevel;if(r!=null&&e<=r)return;let o=n?.hash??this._hashFn;o!==this._hashFn&&(this._hashFn=o);let s=this._cached===void 0?void 0:this._cached,i=this._versioning,a=i?.id??n?.id,u=i?.version??0,d=In(e,s,{id:a,hash:o});d.version=u,this._versioning=d,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let n=Nt(e);if(this._guard!=null&&!this._guard(n,"observe"))return!1;if(this._extraGuards!=null){for(let r of this._extraGuards)if(!r(n,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let n=this._guard!=null||this._extraGuards!=null,r=e?.actor!=null;if(!n&&!r)return;let o=Nt(e?.actor),s=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(o,s))throw new rt({actor:o,action:s,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(o,s))throw new rt({actor:o,action:s,nodeName:this.name})}this._lastMutation={actor:o,timestamp_ns:oe()}}down(e,n){let r=Po(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[E,e]])}up(e,n){if(this._deps.length===0)return;let r=Po(e);if(r.length===0)return;this._checkGuard(n);let o=n??{internal:!0};this._validateUpTiers(r);for(let s of this._deps)s.node.up?.(r,o)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let n of this._deps)n.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let n=this._config.tierOf;for(let r of e){let o=n(r[0]);if(o===3||o===4)throw new Error(`Node "${this.name}": tier-${o} messages cannot flow up \u2014 DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \`down(...)\` for value delivery; \`up(...)\` is for control signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).`)}}subscribe(e,n){if(n!=null&&this._guard!=null){let u=Nt(n);if(!this._guard(u,"observe"))throw new rt({actor:u,action:"observe",nodeName:this.name})}let o=this._isTerminal&&this._resubscribable;if(o){this._cached=void 0,this._status="sentinel",this._store={},this._hasCalledFnOnce=!1,this._waveHasNewData=!1,this._hasNewTerminal=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._isExecutingFn=!1,this._rerunDepth=0,this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null;for(let u of this._deps)ta(u);if(this._partial===!1){for(let u of this._deps)if(u.prevData!==void 0||u.dataBatch.length!==0||u.terminal!==void 0||u.dirty)throw new Error(`resubscribable-reset invariant: DepRecord not fully reset for node ${this._optsName??"(anonymous)"}`)}}this._sinkCount+=1;let s;try{s=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:o},this._actions)}catch(u){throw this._sinkCount-=1,u}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let i=this._isTerminal;if(this._sinkCount===1&&!i)try{this._activate()}catch(u){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof s=="function")try{s()}catch{}throw u}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let a=!1;return()=>{a||(a=!0,this._sinkCount-=1,this._removeSink(e),typeof s=="function"&&s(),this._sinks==null&&this._deactivate())}}_removeSink(e){if(this._sinks===e)this._sinks=null;else if(this._sinks!=null&&typeof this._sinks!="function")if(this._sinks.delete(e),this._sinks.size===1){let[n]=this._sinks;this._sinks=n}else this._sinks.size===0&&(this._sinks=null)}_activate(){if(this._deps.length===0){this._fn&&this._execFn();return}this._dirtyDepCount=0;let e=this._deps.length,n=0;try{for(let r=0;r<e;r++){let o=r,s=this._deps[r];s.unsub=cd,s.unsub=s.node.subscribe(i=>{if(s.unsub===null)return;let a=this._config.tierOf,u=!1;for(let d of i)a(d[0])>=3&&(u=!0),this._config.onMessage(this,d,{direction:"down-in",depIndex:o},this._actions);u&&this._maybeRunFnOnSettlement()}),n++}}catch(r){this._deps[n].unsub=null;for(let o=0;o<n;o++){let s=this._deps[o];if(s.unsub!=null){let i=s.unsub;s.unsub=null;try{i()}catch{}ta(s)}}throw this._dirtyDepCount=0,r}}_addDep(e){for(let o=0;o<this._deps.length;o++)if(this._deps[o].node===e)return o;let n=this._deps.length,r=pd(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Mn),r.unsub=cd;try{r.unsub=e.subscribe(o=>{if(r.unsub===null)return;let s=this._config.tierOf,i=!1;for(let a of o)s(a[0])>=3&&(i=!0),this._config.onMessage(this,a,{direction:"down-in",depIndex:n},this._actions);i&&this._maybeRunFnOnSettlement()})}catch(o){throw r.unsub=null,this._deps.pop(),this._dirtyDepCount--,o}return n}_deactivate(e=!1){let n=this._cleanup;if(this._cleanup=void 0,typeof n=="function")try{n()}catch(r){this._emit([[C,this._wrapFnError("cleanup threw",r)]])}else if(n!=null&&typeof n=="object"){let r=n.deactivate;if(typeof r=="function")try{r()}catch(o){this._emit([[C,this._wrapFnError("cleanup.deactivate threw",o)]])}}for(let r of this._deps){if(r.unsub!=null){let o=r.unsub;r.unsub=null;try{o()}catch{}}ta(r)}this._waveHasNewData=!1,this._hasNewTerminal=!1,this._hasCalledFnOnce=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._rerunDepth=0,this._store={},this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null,this._fn!=null&&(this._cached=void 0),e||(this._fn!=null||this._deps.length>0)&&(!this._isTerminal||this._resubscribable)&&(this._status="sentinel")}_onDepMessage(e,n){let r=this._deps[e],o=n[0];if(this._inspectorHooks!=null){let s={kind:"dep_message",depIndex:e,message:n};for(let i of this._inspectorHooks)i(s)}if(o!==dt){if(o===ne){this._depDirtied(r);return}if(o===Je){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(yr);return}if(o===Be||o===qe){this._emit([n]);return}if(o===le){this._emit(On);return}if(o===E)this._depSettledAsData(r,n[1]);else if(o===V)this._depSettledAsResolved(r);else if(o===L)this._depSettledAsTerminal(r,!0);else if(o===C)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(o===E||o===V)&&this._emit([n]),(o===L||o===C)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Mn))}_depSettledAsData(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(n),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=n,e.involvedThisWave=!0,this._hasNewTerminal=!0}_depInvalidated(e){e.prevData=void 0,e.terminal=void 0,e.dataBatch.length=0,e.dirty?e.involvedThisWave=!1:(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++)}_maybeRunFnOnSettlement(){if(!(this._isTerminal&&!this._resubscribable)&&!(this._dirtyDepCount>0)){if(!this._partial&&!this._hasCalledFnOnce)for(let e=0;e<this._deps.length;e++){let n=this._deps[e];if(n.dataBatch.length===0&&n.prevData===void 0&&n.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(hr),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(n=>n.terminal!==void 0&&n.terminal!==!0);if(e!=null){this._autoError&&this._emit([[C,e.terminal]]);return}this._autoComplete&&this._deps.every(n=>n.terminal!==void 0)&&this._emit(br)}_execFn(){if(!this._fn||this._isTerminal&&!this._resubscribable)return;if(this._isExecutingFn){this._pendingRerun=!0;return}let e=this._cleanup;if(typeof e=="function"){this._cleanup=void 0;try{e()}catch(i){this._emit([[C,this._wrapFnError("cleanup threw",i)]]);return}}else if(e!=null&&typeof e=="object"){let i=e.beforeRun;if(typeof i=="function"){e.beforeRun=void 0;try{i()}catch(a){this._emit([[C,this._wrapFnError("cleanup.beforeRun threw",a)]]);return}}}let n=this._deps.map(i=>i.involvedThisWave?i.dataBatch.length>0?[...i.dataBatch]:[]:void 0),r=this._deps.map(i=>i.prevData);for(let i=0;i<this._deps.length;i++){let a=n[i];a!=null&&a.length>0&&(this._deps[i].prevData=a[a.length-1])}let o=this._deps.map(i=>i.terminal),s={prevData:r,terminalDeps:o,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let i={kind:"run",batchData:n,prevData:r};for(let a of this._inspectorHooks)a(i)}this._isExecutingFn=!0;try{let i=this._fn(n,this._actions,s);if(typeof i=="function")this._cleanup=i;else if(i!=null&&typeof i=="object"){let a=i;(typeof a.beforeRun=="function"||typeof a.deactivate=="function"||typeof a.invalidate=="function")&&(this._cleanup=i)}}catch(i){this._emit([[C,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>ld?(this._rerunDepth=0,this._emit([[C,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${ld} \u2014 likely a reactive cycle`)]])):this._maybeRunFnOnSettlement()):this._rerunDepth=0,this._clearWaveFlags()}}_clearWaveFlags(){this._waveHasNewData=!1,this._hasNewTerminal=!1;for(let e of this._deps)e.involvedThisWave=!1,e.dataBatch.length=0}_wrapFnError(e,n){let r=n instanceof Error?n.message:String(n);return new Error(`Node "${this.name}": ${e}: ${r}`,{cause:n})}_frameBatch(e){let n=this._config.tierOf;if(e.length===1)return n(e[0][0])===3&&this._status!=="dirty"?[Et,e[0]]:e;let r=!0,o=!1,s=!1,i=-1;for(let u of e){let d=n(u[0]);d<i&&(r=!1),d===3&&(o=!0),u[0]===ne&&(s=!0),i=d}let a=e;if(!r){let u=e.map((d,c)=>({m:d,i:c,tier:n(d[0])}));u.sort((d,c)=>d.tier-c.tier||d.i-c.i),a=u.map(d=>d.m)}if(o&&!s&&this._status!=="dirty"){let u=0;for(;u<a.length&&n(a[u][0])===0;)u++;return u===0?[Et,...a]:[...a.slice(0,u),Et,...a.slice(u)]}return a}_emit(e){if(e.length===0)return;for(let a=0;a<e.length;a++){let u=e[a];if(u[0]===C&&u[1]===void 0)throw new TypeError('[ERROR, payload] requires a non-undefined payload (spec \xA71.2). Pass an Error object or domain tag instead \u2014 e.g. node.down([[ERROR, new Error("reason")]])')}let n=e;if(this._isTerminal&&!this._resubscribable){let a=e.filter(u=>u[0]===le||u[0]===Je);if(a.length===0)return;n=a}n=this._frameBatch(n);let o=null;for(let a=0;a<n.length;a++){let u=n[a],d=u[0];if(d!==Be&&d!==qe){o?.push(u);continue}if(u.length<2)throw new Error(`Node "${this.name}": [[${d===Be?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let c=!0;if(this._pausable!==!1){let l=u[1];if(d===Be)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(l),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(l))c=!1;else if(this._pauseLocks.delete(l),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let p=this._pauseBuffer;this._pauseBuffer=[],this._emit(p)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?o?.push(u):o==null&&(o=n.slice(0,a))}if(o!=null){if(o.length===0)return;n=o}if(this._hasMeta&&n.some(a=>a[0]===le))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(On)}catch{}let{finalMessages:s,equalsError:i}=this._updateState(n);if(s.length>0&&this._config.inspectorEnabled){let a=this._config.globalInspector;if(a!=null)try{a({kind:"emit",node:this,messages:s})}catch{}}if(s.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let a=this._config.tierOf,u=[];for(let d of s)a(d[0])===3?this._pauseBuffer.push(d):u.push(d);u.length>0&&this._dispatchOrAccumulate(u)}else this._dispatchOrAccumulate(s);i!=null&&this._emit([[C,i]])}_updateState(e){let n=this._config.tierOf,r,o,s=-1,i=0;for(let c of e)n(c[0])===3&&i++;let a=i<=1,u=-1;if(this._versioning!=null&&i>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===E){u=c;break}}for(let c=0;c<e.length;c++){let l=e[c],p=l[0];if(p===E){if(l.length>=2){let f=!1;if(a&&this._cached!==void 0)try{f=this._equals(this._cached,l[1])}catch(m){o=this._wrapFnError("equals threw",m),s=c;break}if(f){r==null&&(r=e.slice(0,c)),r.push(Nn),this._status="resolved";continue}this._cached=l[1],this._versioning!=null&&(u<0||c===u)&&Mr(this._versioning,l[1],this._hashFn)}this._status="settled",r?.push(l)}else if(r?.push(l),p===ne)this._status="dirty";else if(p===V)this._status="resolved";else if(p===L){this._status="completed";{let f=this._config.rigorRecorder;if(f!=null)try{f.onTerminalTransition(this,"completed",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===C){this._status="errored";{let f=this._config.rigorRecorder;if(f!=null)try{f.onTerminalTransition(this,"errored",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===Je){if(this._cached!==void 0){let m=this._config.rigorRecorder;if(m!=null)try{m.onNonVacuousInvalidate(this,this._cached)}catch{}}this._cached=void 0,this._status="dirty";let f=this._cleanup;if(typeof f=="function"){this._cleanup=void 0;try{f()}catch{}}else if(f!=null&&typeof f=="object"){let m=f.invalidate;if(typeof m=="function")try{m()}catch{}}}else p===le&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let d=s>=0?r??e.slice(0,s):r??e;return o!=null?{finalMessages:d,equalsError:o}:{finalMessages:d}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let n=[...this._sinks];for(let r of n)r(e)};_dispatchOrAccumulate(e){if(ud()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],Sr(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}_t(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let n=this._frameBatch(e);_t(this._deliverToSinks,n,this._config.tierOf)}},fd=t=>Array.isArray(t),na=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function M(t,e){return z([],{...e,initial:t})}function K(t,e){return z((r,o,s)=>t(o,s)??void 0,{describeKind:"producer",...e})}function A(t,e,n){return z(t,(o,s,i)=>{let a=o.map((u,d)=>u!=null&&u.length>0?u.at(-1):i.prevData[d]);s.emit(e(a,i))},{describeKind:"derived",...n})}function pe(t,e,n){return z(t,(o,s,i)=>{let a=o.map((u,d)=>u!=null&&u.length>0?u.at(-1):i.prevData[d]);return e(a,s,i)??void 0},{describeKind:"effect",...n})}function Or(t,e,n){let r=new Map;return t.forEach((o,s)=>{r.set(o,s)}),A(t,(o,s)=>e(a=>{let u=r.get(a);if(u==null)throw new Error(`dynamicNode: untracked dep "${a.name??"<unnamed>"}"`);return o[u]},s),n)}function rn(t,e){let n,r=new Map,o=(s,i,a)=>{let u=!1,d=c=>{let l=r.get(c);if(l!==void 0){if(l<s.length){let f=s[l];return f!=null&&f.length>0?f.at(-1):a.prevData[l]}return c.cache}u=!0;let p=n._addDep(c);return r.set(c,p),c.cache};try{let c=t(d,a);u||(i.emit(c),a.store.__autoTrackLastDiscoveryError!=null&&delete a.store.__autoTrackLastDiscoveryError)}catch(c){if(!u)throw c;a.store.__autoTrackLastDiscoveryError=c}};return n=new Ae([],o,{describeKind:"derived",...e}),n}function oa(t,...e){let n=t;for(let r of e)n=r(n);return n}var ee=tt(()=>{"use strict";_e()});function Lr(t,e,n){let r=new Set;for(let o of t.split(",")){let[s,i]=o.split("/"),a=i?Number.parseInt(i,10):1;if(Number.isNaN(a)||a<1)throw new Error(`Invalid cron step: ${o}`);let u,d;if(s==="*")u=e,d=n;else if(s.includes("-")){let[c,l]=s.split("-");u=Number.parseInt(c,10),d=Number.parseInt(l,10)}else u=Number.parseInt(s,10),d=u;if(Number.isNaN(u)||Number.isNaN(d))throw new Error(`Invalid cron field: ${t}`);if(u<e||d>n)throw new Error(`Cron field out of range: ${t} (${e}-${n})`);if(u>d)throw new Error(`Invalid cron range: ${u}-${d} in ${t}`);for(let c=u;c<=d;c+=a)r.add(c)}return r}function Vo(t){let e=t.trim().split(/\s+/);if(e.length!==5)throw new Error(`Invalid cron: expected 5 fields, got ${e.length}`);return{minutes:Lr(e[0],0,59),hours:Lr(e[1],0,23),daysOfMonth:Lr(e[2],1,31),months:Lr(e[3],1,12),daysOfWeek:Lr(e[4],0,6)}}function Ko(t,e){return t.minutes.has(e.getMinutes())&&t.hours.has(e.getHours())&&t.daysOfMonth.has(e.getDate())&&t.months.has(e.getMonth()+1)&&t.daysOfWeek.has(e.getDay())}var aa=tt(()=>{"use strict"});var Md={};ke(Md,{NS_PER_MS:()=>He,NS_PER_SEC:()=>at,constant:()=>qo,decorrelatedJitter:()=>Uo,exponential:()=>Wo,fibonacci:()=>zo,linear:()=>Ho,resolveBackoffPreset:()=>Bt,withMaxAttempts:()=>ua});function sn(t){return t<0?0:t}function rm(t,e){return e==="none"?t:e==="full"?Math.random()*t:t/2+Math.random()*(t/2)}function om(t,e){return t+Math.random()*(e-t)}function qo(t){let e=sn(t);return()=>e}function Ho(t,e){let n=sn(t),r=e===void 0?n:sn(e);return o=>n+r*Math.max(0,o)}function Wo(t){let e=sn(t?.baseNs??1e8),n=t?.factor!==void 0&&t.factor<1?1:t?.factor??2,r=sn(t?.maxDelayNs??30*1e9),o=t?.jitter??"none";return s=>{let i;if(e===0)i=0;else if(n===1)i=e;else{let a=r/e,u=1;for(let d=0;d<Math.max(0,s);d++){if(u>=a){u=a;break}u*=n}i=e*u,i>r&&(i=r)}return rm(i,o)}}function zo(t=100*1e6,e=30*1e9){let n=sn(t),r=sn(e);function o(s){if(s<=0)return 1;let i=1,a=2;for(let u=1;u<s;u++){let d=i+a;i=a,a=d}return a}return s=>{let i=o(s)*n;return i<=r?i:r}}function Uo(t=100*1e6,e=30*1e9){return(n,r,o)=>{let i=Math.min(e,(o??t)*3);return om(t,i)}}function ua(t,e){return(n,r,o)=>n>=e?null:t(n,r,o)}function Bt(t){if(t==="constant")return qo(1*1e9);if(t==="linear")return Ho(1*1e9);if(t==="exponential")return Wo();if(t==="fibonacci")return zo();if(t==="decorrelatedJitter")return Uo();throw new Error(`Unknown backoff preset: "${String(t)}". Use one of: constant, linear, exponential, fibonacci, decorrelatedJitter`)}var He,at,Vn=tt(()=>{"use strict";He=1e6,at=1e9});var Le,vt=tt(()=>{"use strict";Le=class{_timer;_gen=0;start(e,n){this.cancel(),this._gen+=1;let r=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,r===this._gen&&n()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var Cd={};ke(Cd,{CircuitOpenError:()=>pt,RateLimiterOverflowError:()=>an,TimeoutError:()=>un,circuitBreaker:()=>wt,fallback:()=>Hn,rateLimiter:()=>qn,retry:()=>Tt,timeout:()=>Wn,tokenBucket:()=>Vt,withBreaker:()=>Kn,withStatus:()=>Kt});function dn(t){return{describeKind:"derived",...t}}function sm(t){return t<0?0:t}function Jo(t){return t[1]}function Od(t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("backoff strategy must return a finite number");return t<0?0:t}function Tt(t,e){return typeof t=="function"?am(t,e):im(t,e)}function im(t,e){let n=e?.count,r=e?.backoff,o=n!==void 0?n:r===void 0?0:2147483647;if(o<0)throw new RangeError("retry count must be >= 0");let s=r===void 0?null:typeof r=="string"?Bt(r):r;return K(i=>{let a=0,u=!1,d=null,c,l=new Le;function p(){c?.(),c=void 0}function f(h){if(u)return;if(a>=o){p(),i.down([[C,h]]);return}let g=s===null?0:s(a,h,d);if(g==null){p(),i.down([[C,h]]);return}let y;try{y=Od(g)}catch{p(),i.down([[C,h]]);return}d=y,a+=1,p();let b=y>0?y/1e6:1;l.start(b,()=>{u||m()})}function m(){l.cancel(),p(),c=t.subscribe(h=>{if(!u)for(let g of h){let y=g[0];if(y===ne)i.down([[ne]]);else if(y===E)a=0,d=null,i.emit(g[1]);else if(y===V)i.down([[V]]);else if(y===L)p(),i.down([[L]]);else if(y===C){f(Jo(g));return}else i.down([g])}})}return m(),()=>{u=!0,l.cancel(),p()}},{...dn(),initial:t.cache})}function am(t,e){let n=e?.count,r=e?.backoff,o=n!==void 0?n:r===void 0?0:2147483647;if(o<0)throw new RangeError("retry count must be >= 0");let s=r===void 0?null:typeof r=="string"?Bt(r):r;return K(i=>{let a=0,u=!1,d=null,c,l=new Le;function p(){c?.(),c=void 0}function f(h){if(u)return;if(a>=o){p(),i.down([[C,h]]);return}let g=s===null?0:s(a,h,d);if(g==null){p(),i.down([[C,h]]);return}let y;try{y=Od(g)}catch{p(),i.down([[C,h]]);return}d=y,a+=1,p();let b=y>0?y/1e6:1;l.start(b,()=>{u||m()})}function m(){l.cancel(),p();let h;try{h=t()}catch(g){f(g);return}c=h.subscribe(g=>{if(!u)for(let y of g){let b=y[0];if(b===ne)i.down([[ne]]);else if(b===E)a=0,d=null,i.emit(y[1]);else if(b===V)i.down([[V]]);else if(b===L)p(),i.down([[L]]);else if(b===C){f(Jo(y));return}else i.down([y])}})}return m(),()=>{u=!0,l.cancel(),p()}},{...dn(),initial:e?.initial})}function wt(t){let e=Math.max(1,t?.failureThreshold??5),n=sm(t?.cooldownNs??30*1e9),r=t?.cooldown??null,o=Math.max(1,t?.halfOpenMax??1),s=t?.now??H,i="closed",a=0,u=0,d=0,c=n,l=0;function p(){if(!r)return n;let h=r(u);return h!==null?h:n}function f(){i="open",c=p(),d=s(),l=0}return{canExecute(){return i==="closed"?!0:i==="open"?s()-d>=c?(i="half-open",l=1,!0):!1:l<o?(l++,!0):!1},recordSuccess(){i==="half-open"?(i="closed",a=0,u=0):i==="closed"&&(a=0)},recordFailure(h){if(i==="half-open"){u++,f();return}i==="closed"&&(a++,a>=e&&f())},get state(){return i},get failureCount(){return a},reset(){i="closed",a=0,u=0,l=0}}}function Kn(t,e){let n=e?.onOpen??"skip";return r=>{let o=z([],(s,i)=>{function a(){o.meta.breakerState.down([[E,t.state]])}let u=r.subscribe(d=>{for(let c of d){let l=c[0];l===ne?i.down([[ne]]):l===E?t.canExecute()?(a(),i.emit(c[1])):(a(),n==="error"?i.down([[C,new pt]]):i.down([[V]])):l===V?i.down([[V]]):l===L?(t.recordSuccess(),a(),i.down([[L]])):l===C?(t.recordFailure(Jo(c)),a(),i.down([c])):i.down([c])}});return a(),u},{...dn(),meta:{breakerState:t.state},completeWhenDepsComplete:!1,initial:r.cache});return{node:o,breakerState:o.meta.breakerState}}}function Vt(t,e){if(t<=0)throw new RangeError("capacity must be > 0");if(e<0)throw new RangeError("refillPerSecond must be >= 0");let n=t,r=H();function o(s){if(e>0){let i=s-r;n=Math.min(t,n+i/1e9*e)}r=s}return{available(){return o(H()),n},tryConsume(s=1){if(s<=0)return!0;let i=H();return o(i),n>=s?(n-=s,!0):!1},putBack(s=1){s<=0||(o(H()),n=Math.min(t,n+s))}}}function qn(t,e){let{maxEvents:n,windowNs:r}=e;if(n<=0)throw new RangeError("maxEvents must be > 0");if(r<=0)throw new RangeError("windowNs must be > 0");let o=e.maxBuffer;if(o!==void 0&&o<1)throw new RangeError("maxBuffer must be >= 1");let s=e.onOverflow??"drop-newest",i=n*1e9/r;return K(a=>{let u=Vt(n,i),d=[],c=new Le,l=!1,p=1e9/i;function f(){for(;d.length>0;)if(u.tryConsume(1))a.emit(d.shift());else{c.start(Math.max(1,p/1e6),f);return}}let m=t.subscribe(h=>{for(let g of h){if(l)return;let y=g[0];if(y===ne)a.down([[ne]]);else if(y===E){if(o!==void 0&&d.length>=o){if(s!=="drop-newest")if(s==="drop-oldest")d.shift(),d.push(g[1]);else{l=!0,c.cancel(),d.length=0,a.down([[C,new an(o)]]);return}}else d.push(g[1]);f()}else if(y===V)a.down([[V]]);else if(y===L)l=!0,c.cancel(),d.length=0,a.down([[L]]);else if(y===C)l=!0,c.cancel(),d.length=0,a.down([g]);else if(y===le){l=!0,c.cancel(),d.length=0,a.down([g]);return}else a.down([g])}});return()=>{l=!0,c.cancel(),m()}},{...dn(),initial:t.cache})}function Kt(t,e){let n=e?.initialStatus??"pending",r=z([],(o,s)=>{let i=n;return r.meta.status.down([[E,n]]),r.meta.error.down([[E,null]]),t.subscribe(u=>{for(let d of u){let c=d[0];if(c===ne)s.down([[ne]]);else if(c===E)i==="errored"?X(()=>{r.meta.error.down([[E,null]]),r.meta.status.down([[E,"active"]])}):r.meta.status.down([[E,"active"]]),i="active",s.emit(d[1]);else if(c===V)s.down([[V]]);else if(c===L)r.meta.status.down([[E,"completed"]]),i="completed",s.down([[L]]);else if(c===C){let l=Jo(d);X(()=>{r.meta.error.down([[E,l]]),r.meta.status.down([[E,"errored"]])}),i="errored",s.down([d])}else s.down([d])}})},{...dn(),meta:{status:n,error:null},completeWhenDepsComplete:!1,resubscribable:!0,initial:t.cache});return{node:r,status:r.meta.status,error:r.meta.error}}function um(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function dm(t){return t!=null&&typeof t.then=="function"}function cm(t){return t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function"}function Hn(t,e){return K(n=>{let r,o;function s(){o?.(),o=void 0,um(e)||dm(e)||cm(e)?r=U(e).subscribe(a=>{n.down(a)}):(n.emit(e),n.down([[L]]))}return o=t.subscribe(i=>{for(let a of i){let u=a[0];if(u===ne)n.down([[ne]]);else if(u===E)n.emit(a[1]);else if(u===V)n.down([[V]]);else if(u===L)n.down([[L]]);else if(u===C){s();return}else if(u===le){r?.(),n.down([a]);return}else n.down([a])}}),()=>{o?.(),r?.()}},{...dn(),initial:t.cache})}function Wn(t,e){if(e<=0)throw new RangeError("timeoutNs must be > 0");return K(n=>{let r=!1,o=new Le;function s(){let a=e/1e6;o.start(a,()=>{r||(r=!0,i(),n.down([[C,new un(e)]]))})}let i=t.subscribe(a=>{for(let u of a){if(r)return;let d=u[0];if(d===ne)n.down([[ne]]);else if(d===E)s(),n.emit(u[1]);else if(d===V)n.down([[V]]);else if(d===L){o.cancel(),r=!0,n.down([[L]]);return}else if(d===C){o.cancel(),r=!0,n.down([u]);return}else if(d===le){o.cancel(),r=!0,n.down([u]);return}else n.down([u])}});return s(),()=>{r=!0,o.cancel(),i()}},{...dn(),initial:t.cache})}var pt,an,un,Ot=tt(()=>{"use strict";Me();xe();ae();_e();ee();Vn();he();vt();pt=class extends Error{name="CircuitOpenError";constructor(){super("Circuit breaker is open")}};an=class extends Error{name="RateLimiterOverflowError";constructor(e){super(`rateLimiter buffer overflow (maxBuffer=${e})`)}};un=class extends Error{name="TimeoutError";constructor(e){super(`Timed out after ${e/1e6}ms`)}}});function ut(t){return{describeKind:"producer",...t}}function ca(t){return/[\\^$+?.()|[\]{}]/.test(t)?`\\${t}`:t}function Ld(t){let e="^";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="*"){t[n+1]==="*"?(e+=".*",n+=1):e+="[^/]*";continue}e+=ca(r)}return e+="$",new RegExp(e)}function Id(t,e){for(let n of e)if(n.test(t))return!0;return!1}function lm(t,e){let n=z([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[V]]);return}for(let a of i)s.emit(a)},{describeKind:"derived",initial:t.cache}),r=n.subscribe.bind(n);return n.subscribe=(o,s)=>(e(o),r(o,s)),n}function st(t,e){let{signal:n,period:r,...o}=e??{};return K(s=>{let i=!1,a=0,u,d,c=()=>{i=!0,u!==void 0&&clearTimeout(u),d!==void 0&&clearInterval(d),n?.removeEventListener("abort",p)},l=()=>{i||(r!=null?(s.emit(a++),d=setInterval(()=>{i||s.emit(a++)},r)):(i=!0,n?.removeEventListener("abort",p),s.emit(a++),s.down([[L]])))},p=()=>{i||(c(),s.down([[C,n.reason]]))};if(n?.aborted){p();return}return u=setTimeout(l,t),n?.addEventListener("abort",p,{once:!0}),c},ut(o))}function Pd(t){let{signal:e,...n}=t??{};return K(r=>{let o=!1,s,i,a=!1,u=!1,d=typeof requestAnimationFrame=="function"?requestAnimationFrame:void 0,c=typeof cancelAnimationFrame=="function"?cancelAnimationFrame:void 0,l=typeof document<"u"?document:void 0,p=()=>{s!==void 0&&c&&c(s),i!==void 0&&clearTimeout(i),s=void 0,i=void 0},f=()=>{o=!0,p(),a&&(e?.removeEventListener("abort",m),a=!1),u&&l&&(l.removeEventListener("visibilitychange",y),u=!1)},m=()=>{o||(f(),r.down([[C,e.reason]]))},h=b=>{o||(r.emit(b),g())},g=()=>{o||(d&&(!l||l.visibilityState!=="hidden")?s=d(h):i=setTimeout(()=>h(performance.now()),16))},y=()=>{o||(p(),g())};return e?.aborted?(m(),f):(e?.addEventListener("abort",m,{once:!0}),a=e!==void 0,l&&d&&(l.addEventListener("visibilitychange",y),u=!0),g(),f)},ut(n))}function Qo(t,e){let n=Vo(t),{tickMs:r,output:o,...s}=e??{},i=r??6e4,a=o==="date";return K(u=>{let d=-1,c=()=>{let p=new Date,f=p.getFullYear()*1e8+(p.getMonth()+1)*1e6+p.getDate()*1e4+p.getHours()*100+p.getMinutes();f!==d&&Ko(n,p)&&(d=f,u.emit(a?p:oe()))};c();let l=setInterval(c,i);return()=>clearInterval(l)},{...ut(s),name:s.name??`cron:${t}`})}function Dd(t,e,n){let{capture:r,passive:o,once:s,...i}=n??{};return K(a=>{let u=c=>{a.emit(c)},d={capture:r,passive:o,once:s};return t.addEventListener(e,u,d),()=>t.removeEventListener(e,u,d)},ut(i))}function Xo(t,e){return K(n=>{let r=!1;try{for(let o of t){if(r)return;n.emit(o)}r||n.down([[L]])}catch(o){r||n.down([[C,o]])}return()=>{r=!0}},ut(e))}function pm(t){return t!=null&&typeof t.then=="function"}function zn(t,e){let{signal:n,...r}=e??{};return K(o=>{let s=!1,i=()=>{s||(s=!0,o.down([[C,n.reason]]))};if(n?.aborted){i();return}return n?.addEventListener("abort",i,{once:!0}),Promise.resolve(t).then(a=>{s||(s=!0,n?.removeEventListener("abort",i),o.emit(a),o.down([[L]]))},a=>{s||(s=!0,n?.removeEventListener("abort",i),o.down([[C,a]]))}),()=>{s=!0,n?.removeEventListener("abort",i)}},ut(r))}function Ir(t,e){let{signal:n,...r}=e??{};return K(o=>{let s=new AbortController,i=()=>s.abort(n?.reason);n?.aborted?s.abort(n.reason):n?.addEventListener("abort",i,{once:!0});let a=n??s.signal,u=!1,d=t[Symbol.asyncIterator](),c=()=>{u||a.aborted||Promise.resolve(d.next()).then(l=>{if(!(u||a.aborted)){if(l.done){o.down([[L]]);return}o.emit(l.value),c()}},l=>{!u&&!a.aborted&&o.down([[C,l]])})};return c(),()=>{u=!0,n?.removeEventListener("abort",i),s.abort(),Promise.resolve(d.return?.()).catch(()=>{})}},ut(r))}function fm(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function U(t,e){if(fm(t))return t;if(pm(t))return zn(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return Ir(t,e);if(typeof n[Symbol.iterator]=="function")return Xo(t,e)}return la(t)}function la(...t){return Xo(t,void 0)}function Gd(t){return K(e=>{e.down([[L]])},ut(t))}function Fd(t){return K(()=>{},ut(t))}function $d(t,e){return K(n=>{n.down([[C,t]])},ut(e))}function jd(t,e){let{signal:n,...r}=e??{},o=ut(r),s=o.resubscribable===void 0?{...o,resubscribable:!0}:o;return K(i=>{let a,u=!1;try{let d=t();a=U(d,e).subscribe(l=>{if(!u)for(let p of l){let f=p[0];if(f!==dt)if(f===E)i.emit(p[1]);else if(f===L){u=!0,i.down([[L]]);break}else if(f===C){u=!0,i.down([[C,p[1]]]);break}else i.down([p])}})}catch(d){let c=d===void 0?new Error("defer: thunk threw undefined"):d;i.down([[C,c]])}return()=>{u=!0,a?.()}},s)}function qt(t,e,n){return z([t],(o,s)=>{let i=o[0];if(i!=null&&i.length>0)for(let a of i)e(a)},{describeKind:"effect",...n}).subscribe(()=>{})}function Bd(t,e){return z([t],(n,r,o)=>{o.store.buf||(o.store.buf=[]);let s=o.store.buf,i=n[0];if(i!=null&&i.length>0)for(let a of i)s.push(a);if(o.terminalDeps[0]===!0){r.emit([...s]),r.down([[L]]);return}(i==null||i.length===0)&&r.down([[V]])},{describeKind:"derived",completeWhenDepsComplete:!1,...e})}function Vd(t,e){return K(n=>t.subscribe(r=>{n.down(r)}),{...ut(e),initial:t.cache})}function Zo(t,e,n){if(e<1)throw new RangeError("replay expects bufferSize >= 1");let r=[],o=K(s=>t.subscribe(i=>{for(let a of i)a[0]===E&&(r.push(a[1]),r.length>e&&r.shift());s.down(i)}),{...ut(n),initial:t.cache});return lm(o,s=>{for(let i of r)s([[E,i]])})}function Kd(t,e){return Zo(t,1,e)}function Ye(t){return new Promise((e,n)=>{let r=!1,o=!1,s;s=t.subscribe(i=>{for(let a of i){if(r)return;if(a[0]===E){r=!0,e(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===C){r=!0,n(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===L){r=!0,n(new Error("completed without DATA")),s?(s(),s=void 0):o=!0;return}}}),o&&(s?.(),s=void 0)})}function Yo(t,e,n){return new Promise((r,o)=>{let s=!1,i=!1,a,u=n?.skipCurrent===!0;a=t.subscribe(d=>{for(let c of d){if(s)return;if(!(u&&c[0]===E)){if(c[0]===E){let l=c[1];if(e(l)){s=!0,r(l),a?(a(),a=void 0):i=!0;return}}if(c[0]===C){s=!0,o(c[1]),a?(a(),a=void 0):i=!0;return}if(c[0]===L){s=!0,o(new Error("completed without matching value")),a?(a(),a=void 0):i=!0;return}}}}),u=!1,i&&(a?.(),a=void 0)})}async function es(t,e){let n=e?.predicate??(s=>s!=null),r=e?.skipCurrent;if(e?.timeoutMs==null||e.timeoutMs<=0)return await Yo(t,n,{skipCurrent:r});if(da===void 0){let[s,i]=await Promise.all([Promise.resolve().then(()=>(Ot(),Cd)),Promise.resolve().then(()=>(Vn(),Md))]);da=s.timeout,Ad=i.NS_PER_MS}let o=da(t,e.timeoutMs*Ad);return await Yo(o,n,{skipCurrent:r})}function ts(t,e){let n=new AbortController,r=e?.reason??new Error("cancelled via nodeSignal"),o,s=!1,i=()=>{o?(o(),o=void 0):s=!0};return o=t.subscribe(a=>{if(!n.signal.aborted)for(let u of a){if(u[0]===E&&u[1]===!0){n.abort(r),i();return}if(u[0]===C){n.abort(u[1]),i();return}if(u[0]===L){i();return}}}),s&&(o?.(),o=void 0),{signal:n.signal,dispose:()=>{o&&(o(),o=void 0)}}}function re(t){return t.subscribe(()=>{})}function pa(t){let e=M(0);return{node:e,increment(){let n=e.cache??0;return n>=t?!1:(e.down([[ne],[E,n+1]]),!0)},get(){return e.cache??0},atCap(){return(e.cache??0)>=t}}}var da,Ad,qd,he=tt(()=>{"use strict";xe();ae();_e();ee();aa();qd=Zo});var Kb={};ke(Kb,{COMPLETE:()=>L,COMPLETE_MSG:()=>Oo,COMPLETE_ONLY_BATCH:()=>br,CircuitOpenError:()=>pt,ContentAddressedMissError:()=>eo,DATA:()=>E,DEFAULT_ACTOR:()=>bt,DIRTY:()=>ne,DIRTY_MSG:()=>Et,DIRTY_ONLY_BATCH:()=>Mn,ENVELOPE_VERSION:()=>Cn,ERROR:()=>C,GRAPH_META_SEGMENT:()=>Qe,Graph:()=>Y,GraphReFlyConfig:()=>nn,GuardDenied:()=>rt,INVALIDATE:()=>Je,INVALIDATE_MSG:()=>Mo,INVALIDATE_ONLY_BATCH:()=>yr,JsonCodec:()=>Ao,NS_PER_MS:()=>He,NS_PER_SEC:()=>at,NativeIndexBackend:()=>ro,NativeListBackend:()=>oo,NativeLogBackend:()=>jr,NativeMapBackend:()=>Xr,NativePubSubBackend:()=>no,NodeImpl:()=>Ae,PAUSE:()=>Be,RESOLVED:()=>V,RESOLVED_MSG:()=>Nn,RESOLVED_ONLY_BATCH:()=>hr,RESUME:()=>qe,RateLimiterOverflowError:()=>an,ResettableTimer:()=>Le,SIZEOF_OVERHEAD:()=>je,SIZEOF_SYMBOL:()=>ds,SNAPSHOT_VERSION:()=>ft,SNAPSHOT_WIRE_VERSION:()=>No,START:()=>dt,START_MSG:()=>_n,SurfaceError:()=>Ne,TEARDOWN:()=>le,TEARDOWN_MSG:()=>Co,TEARDOWN_ONLY_BATCH:()=>On,TimeoutError:()=>un,accessHintForGuard:()=>_r,accountability:()=>yi,advanceVersion:()=>Mr,ai:()=>mi,appendLogStorage:()=>Ka,asSurfaceError:()=>Fi,audit:()=>zc,autoTrackNode:()=>rn,awaitSettled:()=>es,batch:()=>X,buffer:()=>Uc,bufferCount:()=>Jc,bufferTime:()=>Qc,cached:()=>Kd,canonicalJson:()=>to,cascadingCache:()=>sp,catchError:()=>al,checkpointToRedis:()=>Ql,checkpointToS3:()=>Yl,circuitBreaker:()=>wt,combine:()=>Aa,combineLatest:()=>ol,compat:()=>Oa,concat:()=>jc,concatMap:()=>Kc,configure:()=>ra,constant:()=>qo,contentAddressedStorage:()=>Ps,core:()=>va,cqrs:()=>Ts,createDagCborCodec:()=>Ji,createDagCborZstdCodec:()=>Yi,createGraph:()=>pr,createTransport:()=>Jt,createVersioning:()=>In,createWatermarkController:()=>Un,csvRows:()=>Al,debounce:()=>Ia,debounceTime:()=>sl,decodeEnvelope:()=>Tr,decorrelatedJitter:()=>Uo,defaultConfig:()=>$e,defaultHash:()=>jt,defer:()=>jd,delay:()=>Hc,deleteSnapshot:()=>Hi,demoShell:()=>vi,derived:()=>A,deserializeError:()=>yn,dictKv:()=>bp,dictSnapshot:()=>vp,diffForWAL:()=>fs,diffSnapshots:()=>Ki,distill:()=>Ls,distinctUntilChanged:()=>Gc,domainTemplates:()=>Ti,downWithBatch:()=>_t,dynamicNode:()=>Or,effect:()=>pe,elementAt:()=>Ic,empty:()=>Gd,encodeEnvelope:()=>vr,escapeRegexChar:()=>ca,exhaustMap:()=>Vc,explainPath:()=>Gr,exponential:()=>Wo,externalBundle:()=>Os,externalProducer:()=>mn,extra:()=>Wa,fallback:()=>Hn,fibonacci:()=>zo,filter:()=>Xe,find:()=>Lc,first:()=>Cs,firstValueFrom:()=>Ye,firstWhere:()=>Yo,flatMap:()=>qc,forEach:()=>qt,fromAny:()=>U,fromAsyncIter:()=>Ir,fromCSV:()=>Cl,fromClickHouseWatch:()=>Dl,fromCron:()=>Qo,fromDrizzle:()=>np,fromEvent:()=>Dd,fromHTTP:()=>$a,fromHTTPPoll:()=>yl,fromHTTPStream:()=>hl,fromIter:()=>Xo,fromKafka:()=>Nl,fromKysely:()=>rp,fromMCP:()=>Tl,fromNATS:()=>$l,fromNDJSON:()=>Pl,fromOTel:()=>wl,fromPrisma:()=>tp,fromPrometheus:()=>El,fromPromise:()=>zn,fromPulsar:()=>Gl,fromRabbitMQ:()=>Bl,fromRaf:()=>Pd,fromRedisStream:()=>Ml,fromSSE:()=>gl,fromSqlite:()=>Xl,fromSqliteCursor:()=>Zl,fromStatsD:()=>Rl,fromSyslog:()=>kl,fromTimer:()=>st,fromWebSocket:()=>Fa,fromWebSocketReconnect:()=>vl,fromWebhook:()=>ul,globToRegExp:()=>Ld,graph:()=>ka,graphProfile:()=>pn,graphspec:()=>fi,guarded:()=>ki,harness:()=>Ai,interval:()=>el,isBatching:()=>tn,isV1:()=>ea,jobQueue:()=>Oi,jotai:()=>Do,jsonCodec:()=>tr,jsonCodecFor:()=>gp,keepalive:()=>re,kvStorage:()=>js,last:()=>Ac,layout:()=>Di,lens:()=>Ii,linear:()=>Ho,listSnapshots:()=>qi,lru:()=>Va,makeHttpError:()=>ht,map:()=>zr,matchesAnyPattern:()=>Id,matchesCron:()=>Ko,memory:()=>ci,memoryAppendLog:()=>yp,memoryBackend:()=>io,memoryKv:()=>ao,memorySnapshot:()=>hp,merge:()=>xt,mergeMap:()=>La,mergeReactiveLogs:()=>bc,mermaidLiveUrl:()=>ps,messaging:()=>oi,monotonicNs:()=>H,nameToSignal:()=>gn,nanostores:()=>jo,ndjsonRows:()=>Ll,nestjs:()=>ks,never:()=>Fd,node:()=>z,nodeSignal:()=>ts,normalizeActor:()=>Nt,of:()=>la,onFirstData:()=>Jr,orchestration:()=>si,pairwise:()=>Fc,parseCron:()=>Vo,parsePrometheusText:()=>ja,parseSSEStream:()=>Dt,parseStatsD:()=>Sl,parseSyslog:()=>xl,patterns:()=>Qu,pausable:()=>nl,pipe:()=>oa,policy:()=>Mt,policyFromRules:()=>Nr,process:()=>Pi,producer:()=>K,pubsub:()=>cp,race:()=>Bc,rateLimiter:()=>qn,reachable:()=>fn,react:()=>xs,reactiveCounter:()=>pa,reactiveIndex:()=>fp,reactiveList:()=>Ds,reactiveLog:()=>Ve,reactiveMap:()=>Ze,reactiveSink:()=>We,reduce:()=>Mc,reduction:()=>pi,refine:()=>Si,registerBuiltinCodecs:()=>wr,registerBuiltins:()=>Er,repeat:()=>tl,replay:()=>Zo,replayWAL:()=>Qi,rescue:()=>Yr,resilientPipeline:()=>Gi,resolveBackoffPreset:()=>Bt,resolveDescribeFields:()=>Ct,restoreSnapshot:()=>Vi,retry:()=>Tt,runReduction:()=>$i,sample:()=>Wc,saveSnapshot:()=>Bi,scan:()=>_c,serializeError:()=>hn,share:()=>Vd,shareReplay:()=>qd,signalToName:()=>Ut,signals:()=>Ss,singleFromAny:()=>Gs,singleNodeFromAny:()=>mp,sizeof:()=>Fr,skip:()=>Ca,snapshotStorage:()=>$s,solid:()=>Es,sortJsonValue:()=>so,stableJsonString:()=>Fs,state:()=>M,stratify:()=>uo,surface:()=>Wi,svelte:()=>Ns,switchMap:()=>Te,take:()=>Ur,takeUntil:()=>Cc,takeWhile:()=>Oc,tap:()=>Pc,tapFirst:()=>Dc,throttle:()=>Pa,throttleTime:()=>il,throwError:()=>$d,timeout:()=>Wn,toArray:()=>Bd,toCSV:()=>Kl,toClickHouse:()=>ql,toFile:()=>Ba,toHTTP:()=>dl,toKafka:()=>_l,toLoki:()=>Ul,toMongo:()=>zl,toNATS:()=>jl,toObservable:()=>Bo,toPostgres:()=>Wl,toPulsar:()=>Fl,toRabbitMQ:()=>Vl,toReadableStream:()=>ml,toRedisStream:()=>Ol,toS3:()=>Hl,toSSE:()=>pl,toSSEBytes:()=>fl,toSqlite:()=>ep,toTempo:()=>Jl,toWebSocket:()=>bl,tokenBucket:()=>Vt,validateGraphObservability:()=>wa,valve:()=>rl,verifiable:()=>up,version:()=>Vb,vue:()=>_s,wallClockNs:()=>oe,watchTopologyTree:()=>At,window:()=>Zc,windowCount:()=>Yc,windowTime:()=>Xc,withBreaker:()=>Kn,withLatestFrom:()=>Pt,withMaxAttempts:()=>ua,withStatus:()=>Kt,workerBridge:()=>qa,workerSelf:()=>Ha,zip:()=>$c,zustand:()=>Ms});module.exports=Pf(Kb);var Oa={};ke(Oa,{jotai:()=>Do,nanostores:()=>jo,nestjs:()=>ks,react:()=>xs,signals:()=>Ss,solid:()=>Es,svelte:()=>Ns,vue:()=>_s,zustand:()=>Ms});var Do={};ke(Do,{atom:()=>Jf});ae();ee();function Jf(t,e,n){if(typeof t=="function"){let r=t;return typeof e=="function"?md(r,e,n):md(r,void 0,e)}return Yf(t,e)}function Cr(t){let e=t.cache,n;if(t.subscribe(o=>{for(let[s,i]of o)s===E&&(e=i),s===C&&(n=i)})(),n)throw n;return e}function Yf(t,e){let n=M(t,{...e,resubscribable:!0,resetOnTeardown:!0});return{get:()=>n.status==="sentinel"?Cr(n):n.cache,set:r=>n.emit(r),update:r=>{let o=n.status==="sentinel"?Cr(n):n.cache;n.emit(r(o))},subscribe:r=>{let o=!0;return n.subscribe(s=>{for(let[i,a]of s)if(i===E){if(o){o=!1;continue}r(a)}})},meta:n.meta,_node:n}}function md(t,e,n){let r=rn(s=>t(i=>{let a=i._node;return a.status==="sentinel"&&Cr(a),s(a)}),{...n,resubscribable:!0,resetOnTeardown:!0}),o={get:()=>r.status==="sentinel"?Cr(r):r.cache,subscribe:s=>{let i=!0;return r.subscribe(a=>{for(let[u,d]of a)if(u===E){if(i){i=!1;continue}s(d)}})},meta:r.meta,_node:r};if(e){let s=u=>u.get(),i=(u,d)=>u.set(d),a=o;return a.set=u=>e(s,i,u),a.update=u=>{let d=r.status==="sentinel"?Cr(r):r.cache;return e(s,i,u(d))},a}return o}var jo={};ke(jo,{action:()=>nm,atom:()=>Qf,computed:()=>Xf,getValue:()=>em,map:()=>Zf,onMount:()=>tm,onStart:()=>yd,onStop:()=>bd});Me();ae();ee();var Fo=new WeakMap,$o=new WeakMap;function Go(t,e){let n=e.get(t);if(n)for(let r of n)r()}function sa(t,e={}){let n=0;return{...e,get:()=>hd(t),subscribe:o=>{n===0&&Go(t,Fo),n++;let s=t.subscribe(i=>{for(let[a,u]of i)a===E&&o(u)});return()=>{s(),n--,n===0&&Go(t,$o)}},listen:o=>{n===0&&Go(t,Fo),n++;let s=!0,i=t.subscribe(a=>{for(let[u,d]of a)if(u===E){if(s){s=!1;continue}o(d)}});return()=>{i(),n--,n===0&&Go(t,$o)}},_node:t}}function gd(t){let e=t.cache,n;if(t.subscribe(o=>{for(let[s,i]of o)s===E&&(e=i),s===C&&(n=i)})(),n)throw n;return e}function hd(t){return t.status==="sentinel"?gd(t):t.cache}function Qf(t){let e=M(t,{resubscribable:!0,resetOnTeardown:!0});return sa(e,{set:n=>e.emit(n)})}function Xf(t,e){let n=Array.isArray(t)?t:[t],r=n.map(s=>s._node),o=Or(r,s=>{let i=n.map(a=>{let u=a._node;return u.status==="sentinel"&&gd(u),s(u)});return e(...i)},{resubscribable:!0,resetOnTeardown:!0,equals:Object.is});return sa(o)}function Zf(t){let e=M(t,{resubscribable:!0,resetOnTeardown:!0,equals:()=>!1});return sa(e,{set:n=>e.emit(n),setKey:(n,r)=>{let o=hd(e);e.emit({...o,[n]:r})}})}function em(t){return t.get()}function yd(t,e){let n=t._node,r=Fo.get(n);r||(r=new Set,Fo.set(n,r)),r.add(e)}function bd(t,e){let n=t._node,r=$o.get(n);r||(r=new Set,$o.set(n,r)),r.add(e)}function tm(t,e){yd(t,()=>{let n=e();typeof n=="function"&&bd(t,n)})}function nm(t,e,n){return(...r)=>{let o;return X(()=>{o=n(...r)}),o}}var ks={};ke(ks,{ACTOR_KEY:()=>rs,COMMAND_HANDLERS:()=>Fn,CQRS_EVENT_HANDLERS:()=>$n,CRON_HANDLERS:()=>Gn,CommandHandler:()=>Sd,EVENT_HANDLERS:()=>Pn,EventHandler:()=>Ed,GRAPHREFLY_REQUEST_GRAPH:()=>on,GRAPHREFLY_ROOT_GRAPH:()=>ct,GraphCron:()=>Rd,GraphInterval:()=>xd,GraphReflyEventExplorer:()=>cn,GraphReflyGuard:()=>Yd,GraphReflyGuardImpl:()=>Pr,GraphReflyModule:()=>ws,INTERVAL_HANDLERS:()=>Dn,InjectCqrsGraph:()=>Td,InjectGraph:()=>vd,InjectNode:()=>wd,ObserveGateway:()=>ns,OnGraphEvent:()=>kd,QUERY_HANDLERS:()=>jn,QueryHandler:()=>Nd,SAGA_HANDLERS:()=>Bn,SagaHandler:()=>_d,fromHeader:()=>Ud,fromJwtPayload:()=>ga,getActor:()=>Jd,getGraphToken:()=>ot,getNodeToken:()=>lt,observeSSE:()=>Wd,observeSubscription:()=>zd,toObservable:()=>Bo});var ia=require("rxjs");ae();function Bo(t,e){return e?.raw?new ia.Observable(n=>t.subscribe(o=>{if(!n.closed){n.next(o);for(let s of o){if(s[0]===C){n.error(s[1]);return}if(s[0]===L){n.complete();return}}}})):new ia.Observable(n=>t.subscribe(o=>{for(let s of o){if(n.closed)return;if(s[0]===E)n.next(s[1]);else if(s[0]===C){n.error(s[1]);return}else if(s[0]===L){n.complete();return}}}))}var Ar=require("@nestjs/common");var ct=Symbol.for("graphrefly:root-graph");var on=Symbol.for("graphrefly:request-graph");function ot(t){return Symbol.for(`graphrefly:graph:${t}`)}function lt(t){return Symbol.for(`graphrefly:node:${t}`)}var Pn=new Map,Dn=new Map,Gn=new Map,Fn=new Map,$n=new Map,jn=new Map,Bn=new Map;function vd(t){return t==="request"?(0,Ar.Inject)(on):(0,Ar.Inject)(t?ot(t):ct)}function Td(t){return(0,Ar.Inject)(ot(t))}function wd(t){return(0,Ar.Inject)(lt(t))}function kd(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=Pn.get(o)??[];s.push({nodeName:t,methodKey:r}),Pn.set(o,s)})}}function xd(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=Dn.get(o)??[];s.push({ms:t,methodKey:r}),Dn.set(o,s)})}}function Rd(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=Gn.get(o)??[];s.push({expr:t,methodKey:r}),Gn.set(o,s)})}}function Sd(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=Fn.get(s)??[];i.push({cqrsName:t,commandName:e,methodKey:o}),Fn.set(s,i)})}}function Ed(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=$n.get(s)??[];i.push({cqrsName:t,eventName:e,methodKey:o}),$n.set(s,i)})}}function Nd(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=jn.get(s)??[];i.push({cqrsName:t,projectionName:e,methodKey:o}),jn.set(s,i)})}}function _d(t,e,n){return(r,o)=>{let s=o.name;o.addInitializer(function(){let i=this.constructor,a=Bn.get(i)??[];a.push({cqrsName:t,eventNames:n,sagaName:e,methodKey:s}),Bn.set(i,a)})}}ae();he();var Hd=0,cn=class{constructor(e,n){this.graph=e;this.moduleRef=n}disposers=[];scheduleNodeNames=[];onModuleInit(){this.wireEvents(),this.wireIntervals(),this.wireCrons(),this.wireCqrsCommands(),this.wireCqrsEvents(),this.wireCqrsQueries(),this.wireCqrsSagas()}onModuleDestroy(){for(let e of this.disposers)e();this.disposers.length=0;for(let e of this.scheduleNodeNames)try{this.graph.remove(e)}catch{}this.scheduleNodeNames.length=0}wireEvents(){for(let[e,n]of Pn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireEventHandler(r,o)}}wireEventHandler(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),i=this.observeNode(n.nodeName).subscribe(a=>{for(let u of a)u[0]===E&&o(u[1])});this.disposers.push(i)}wireIntervals(){for(let[e,n]of Dn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireIntervalHandler(r,e,o)}}wireIntervalHandler(e,n,r){let o=e[r.methodKey];if(typeof o!="function")return;let s=o.bind(e),a=`__schedule__.${n.name??"anonymous"}.${String(r.methodKey)}.${Hd++}`,u=st(r.ms,{period:r.ms,name:a});this.graph.add(u),this.scheduleNodeNames.push(a);let c=this.observeNode(a).subscribe(l=>{for(let p of l)p[0]===E&&s(p[1])});this.disposers.push(c)}wireCrons(){for(let[e,n]of Gn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCronHandler(r,e,o)}}wireCronHandler(e,n,r){let o=e[r.methodKey];if(typeof o!="function")return;let s=o.bind(e),a=`__schedule__.${n.name??"anonymous"}.${String(r.methodKey)}.${Hd++}`,u=Qo(r.expr,{name:a});this.graph.add(u),this.scheduleNodeNames.push(a);let c=this.observeNode(a).subscribe(l=>{for(let p of l)p[0]===E&&s(p[1])});this.disposers.push(c)}wireCqrsCommands(){for(let[e,n]of Fn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsCommand(r,o)}}wireCqrsCommand(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);s&&s.command(n.commandName,o)}wireCqrsEvents(){for(let[e,n]of $n){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsEventHandler(r,o)}}wireCqrsEventHandler(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);if(!s)return;s.event(n.eventName);let a=s.resolve(n.eventName).cache,u=a&&a.length>0?a[a.length-1].seq:0,c=this.observeNodeOn(s,n.eventName).subscribe(l=>{for(let p of l)if(p[0]===E){let f=p[1];for(let m of f)m.seq>u&&(o(m),u=m.seq)}});this.disposers.push(c)}wireCqrsQueries(){for(let[e,n]of jn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsQuery(r,o)}}wireCqrsQuery(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);if(!s)return;let a=this.observeNodeOn(s,n.projectionName).subscribe(u=>{for(let d of u)d[0]===E&&o(d[1])});this.disposers.push(a)}wireCqrsSagas(){for(let[e,n]of Bn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsSaga(r,o)}}wireCqrsSaga(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);s&&s.saga(n.sagaName,n.eventNames,o)}observeNode(e){return this.graph.observe(e)}observeNodeOn(e,n){return e.observe(n)}resolveCqrsGraph(e){try{return this.moduleRef.get(ot(e),{strict:!1})}catch{return console.warn(`[GraphReFly] CqrsGraph "${e}" not found in DI \u2014 did you import GraphReflyModule.forCqrs({ name: "${e}" })?`),null}}resolveInstance(e){try{return this.moduleRef.get(e,{strict:!1})}catch{return null}}};ae();ae();var mm=0;function Un(t,e){if(e.highWaterMark<1)throw new RangeError("highWaterMark must be >= 1");if(e.lowWaterMark<0)throw new RangeError("lowWaterMark must be >= 0");if(e.lowWaterMark>=e.highWaterMark)throw new RangeError("lowWaterMark must be < highWaterMark");let n=Symbol(`bp-${++mm}`),r=0,o=!1;return{onEnqueue(){return r+=1,!o&&r>=e.highWaterMark?(o=!0,t([[Be,n]]),!0):!1},onDequeue(){return r>0&&(r-=1),o&&r<=e.lowWaterMark?(o=!1,t([[qe,n]]),!0):!1},get pending(){return r},get paused(){return o},dispose(){o&&(o=!1,t([[qe,n]]))}}}function Wd(t,e,n){let{actor:r,serialize:o=gm,keepAliveMs:s,signal:i}=n??{},a=new TextEncoder,u,d=n?.highWaterMark!=null,c,l,p=[],f=!1;return new ReadableStream({start(m){let h,g=()=>{},y=()=>{if(!f){f=!0,h!==void 0&&clearInterval(h),i?.removeEventListener("abort",b),g(),c?.dispose(),l?.(),l=void 0;for(let T of p)m.enqueue(T.frame);p.length=0,m.close()}};u=y;let b=()=>y(),v=t.observe(e,{actor:r});d&&(c=Un(T=>v.up(T),{highWaterMark:n.highWaterMark,lowWaterMark:n.lowWaterMark??Math.floor(n.highWaterMark/2)})),g=v.subscribe(T=>{for(let w of T){if(f)return;let x=w[0];if(x===E){let k=a.encode(fa("data",o(w[1])));d?(p.push({frame:k,counted:!0}),c.onEnqueue(),l?.(),l=void 0):m.enqueue(k)}else if(x===C){let k=a.encode(fa("error",o(w[1])));d?(p.push({frame:k,counted:!1}),l?.(),l=void 0):m.enqueue(k),y();return}else if(x===L||x===le){if(x===L){let k=a.encode(fa("complete"));d?(p.push({frame:k,counted:!1}),l?.(),l=void 0):m.enqueue(k)}y();return}}}),s!==void 0&&s>0&&(h=setInterval(()=>{f||(d?(p.push({frame:a.encode(`: keepalive
|
|
1
|
+
"use strict";var Yf=Object.create;var On=Object.defineProperty;var pu=Object.getOwnPropertyDescriptor;var Qf=Object.getOwnPropertyNames;var Xf=Object.prototype.hasOwnProperty;var fu=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),kr=t=>{throw TypeError(t)};var Zf=(t,e,n)=>e in t?On(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var uu=(t,e)=>On(t,"name",{value:e,configurable:!0});var Xe=(t,e)=>()=>(t&&(e=t(t=0)),e);var Se=(t,e)=>{for(var n in e)On(t,n,{get:e[n],enumerable:!0})},em=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Qf(e))!Xf.call(t,o)&&o!==n&&On(t,o,{get:()=>e[o],enumerable:!(r=pu(e,o))||r.enumerable});return t};var tm=t=>em(On({},"__esModule",{value:!0}),t);var mu=t=>[,,,Yf(t?.[fu("metadata")]??null)],gu=["class","method","getter","setter","accessor","field","value","get","set"],wr=t=>t!==void 0&&typeof t!="function"?kr("Function expected"):t,nm=(t,e,n,r,o)=>({kind:gu[t],name:e,metadata:r,addInitializer:s=>n._?kr("Already initialized"):o.push(wr(s||null))}),rm=(t,e)=>Zf(e,fu("metadata"),t[3]),hu=(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},yu=(t,e,n,r,o,s)=>{var i,a,d,u,c,l=e&7,p=!!(e&8),f=!!(e&16),m=l>3?t.length+1:l?p?1:2:0,h=gu[l+5],g=l>3&&(t[m-1]=[]),y=t[m]||(t[m]=[]),b=l&&(!f&&!p&&(o=o.prototype),l<5&&(l>3||!f)&&pu(l<4?o:{get[n](){return cu(this,s)},set[n](T){return lu(this,s,T)}},n));l?f&&l<4&&uu(s,(l>2?"set ":l>1?"get ":"")+n):uu(o,n);for(var v=r.length-1;v>=0;v--)u=nm(l,n,d={},t[3],y),l&&(u.static=p,u.private=f,c=u.access={has:f?T=>om(o,T):T=>n in T},l^3&&(c.get=f?T=>(l^1?cu:sm)(T,o,l^4?s:b.get):T=>T[n]),l>2&&(c.set=f?(T,w)=>lu(T,o,w,l^4?s:b.set):(T,w)=>T[n]=w)),a=(0,r[v])(l?l<4?f?s:b[h]:l>4?void 0:{get:b.get,set:b.set}:o,u),d._=1,l^4||a===void 0?wr(a)&&(l>4?g.unshift(a):l?f?s=a:b[h]=a:o=a):typeof a!="object"||a===null?kr("Object expected"):(wr(i=a.get)&&(b.get=i),wr(i=a.set)&&(b.set=i),wr(i=a.init)&&g.unshift(i));return l||rm(t,o),b&&On(o,n,b),f?l^4?s:b:o};var na=(t,e,n)=>e.has(t)||kr("Cannot "+n),om=(t,e)=>Object(e)!==e?kr('Cannot use the "in" operator on this value'):t.has(e),cu=(t,e,n)=>(na(t,e,"read from private field"),n?n.call(t):e.get(t));var lu=(t,e,n,r)=>(na(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),sm=(t,e,n)=>(na(t,e,"access private method"),n);var ft,M,oe,q,Qe,Ve,ze,le,P,I,Mt,An,Do,Cn,Go,Fo,Ln,xr,Rr,Sr,In,ae=Xe(()=>{"use strict";ft=Symbol.for("graphrefly/START"),M=Symbol.for("graphrefly/DATA"),oe=Symbol.for("graphrefly/DIRTY"),q=Symbol.for("graphrefly/RESOLVED"),Qe=Symbol.for("graphrefly/INVALIDATE"),Ve=Symbol.for("graphrefly/PAUSE"),ze=Symbol.for("graphrefly/RESUME"),le=Symbol.for("graphrefly/TEARDOWN"),P=Symbol.for("graphrefly/COMPLETE"),I=Symbol.for("graphrefly/ERROR"),Mt=Object.freeze([oe]),An=Object.freeze([q]),Do=Object.freeze([Qe]),Cn=Object.freeze([ft]),Go=Object.freeze([P]),Fo=Object.freeze([le]),Ln=Object.freeze([Mt]),xr=Object.freeze([An]),Rr=Object.freeze([Do]),Sr=Object.freeze([Go]),In=Object.freeze([Fo])});function ra(t){return{name:"dag-cbor",version:1,contentType:"application/dag-cbor",encode:e=>t.encode(e),decode:(e,n)=>t.decode(e)}}function oa(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 Nr(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++]=Pn,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 Er(t,e){if(t.length<bu)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${bu})`);let n=0,r=t[n++];if(r!==Pn)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${Pn})`);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),d=e.lookupCodec(s);if(d==null)throw new Error(`decodeEnvelope: codec "${s}" not registered (envelope codec_v=${i})`);return{codec:d,codecVersion:i,payload:a}}function _r(t){t.registerCodec($o)}function sa(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 d of i.nodesRemoved)delete n.nodes[d];let a=i.nodesAddedFull;if(a!=null)for(let[d,u]of Object.entries(a))n.nodes[d]=JSON.parse(JSON.stringify(u));for(let d of i.nodesChanged){let u=n.nodes[d.path];u!=null&&(u[d.field]=d.to)}r=s.seq}return n}var $o,Pn,bu,jo=Xe(()=>{"use strict";$o={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)}};Pn=1,bu=4});function Ot(t){if(t==null)return xt;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var xt,Mr=Xe(()=>{"use strict";xt={type:"system",id:""}});function sn(){return Dn>0||Or}function vu(){return Dn>0}function Fn(t){Dn>0?Ar.push(t):t()}function Z(t){Dn+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(Dn-=1,Dn===0)if(e){if(!Or){let n=Ar.splice(0);for(let r of n)try{r()}catch{}rn.length=0,on.length=0,Gn.length=0}}else im()}}function im(){let t=!Or;t&&(Or=!0);let e=[],n=0;try{for(;rn.length>0||on.length>0||Gn.length>0||t&&Ar.length>0;){if(t&&Ar.length>0){let s=Ar.splice(0);for(let i of s)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw rn.length=0,on.length=0,Gn.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let o=(rn.length>0?rn:on.length>0?on:Gn).splice(0);for(let s of o)try{s()}catch(i){e.push(i)}}}finally{t&&(Or=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function At(t,e,n){if(e.length===0)return;if(e.length===1){let u=n(e[0][0]);if(u<3||!sn()){t(e);return}(u>=5?Gn:u===4?on:rn).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 d=sn();if(o>0){let u=e.slice(0,o);t(u)}if(s>o){let u=e.slice(o,s);d?rn.push(()=>t(u)):t(u)}if(i>s){let u=e.slice(s,i);d?on.push(()=>t(u)):t(u)}if(r>i){let u=e.slice(i,r);d?Gn.push(()=>t(u)):t(u)}}var Dn,Or,rn,on,Gn,Ar,Ae=Xe(()=>{"use strict";Dn=0,Or=!1,rn=[],on=[],Gn=[],Ar=[]});function V(){return Math.trunc(performance.now()*1e6)}function se(){return Date.now()*1e6}var Re=Xe(()=>{"use strict"});function Cr(t){t.registerMessageType(ft,{tier:0,wireCrossing:!1}),t.registerMessageType(oe,{tier:1,wireCrossing:!1}),t.registerMessageType(Qe,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(Ve,{tier:2,wireCrossing:!1}),t.registerMessageType(ze,{tier:2,wireCrossing:!1}),t.registerMessageType(M,{tier:3,wireCrossing:!0}),t.registerMessageType(q,{tier:3,wireCrossing:!0}),t.registerMessageType(P,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(I,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(le,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var an,ia=Xe(()=>{"use strict";ae();an=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_rigorRecorder;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=n=>{let r=this._messageTypes.get(n);return r!=null?r.tier:1}}get onMessage(){return this._frozen=!0,this._onMessage}get onSubscribe(){return this._frozen=!0,this._onSubscribe}set onMessage(e){this._assertUnfrozen(),this._onMessage=e}set onSubscribe(e){this._assertUnfrozen(),this._onSubscribe=e}get defaultVersioning(){return this._defaultVersioning}set defaultVersioning(e){this._assertUnfrozen(),this._defaultVersioning=e}get defaultHashFn(){return this._defaultHashFn}set defaultHashFn(e){this._assertUnfrozen(),this._defaultHashFn=e}get inspectorEnabled(){return this._inspectorEnabled}set inspectorEnabled(e){this._inspectorEnabled=e}get globalInspector(){return this._globalInspector}set globalInspector(e){this._globalInspector=e}get rigorRecorder(){return this._rigorRecorder}set rigorRecorder(e){this._rigorRecorder=e}registerMessageType(e,n){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:n.tier,wireCrossing:n.wireCrossing??n.tier>=3,metaPassthrough:n.metaPassthrough??!0}),this}messageTier(e){let n=this._messageTypes.get(e);return n!=null?n.tier:1}isWireCrossing(e){let n=this._messageTypes.get(e);return n!=null?n.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let n=this._messageTypes.get(e);return n!=null?n.metaPassthrough:!0}isKnownMessageType(e){return this._messageTypes.has(e)}registerCodec(e){return this._assertUnfrozen(),this._codecs.set(e.name,e),this}lookupCodec(e){return this._codecs.get(e)}_isFrozen(){return this._frozen}_assertUnfrozen(){if(this._frozen)throw new Error("GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node.")}}});function Tu(t){return Array.isArray(t)?[...t]:[t]}function am(t,e){return t.has(e)||t.has("*")}function Ct(t){let e=[];return t((o,s)=>{e.push({kind:"allow",actions:new Set(Tu(o)),where:s?.where??(()=>!0)})},(o,s)=>{e.push({kind:"deny",actions:new Set(Tu(o)),where:s?.where??(()=>!0)})}),(o,s)=>{let i=!1,a=!1;for(let d of e)am(d.actions,s)&&d.where(o)&&(d.kind==="deny"?i=!0:a=!0);return i?!1:a}}function Lr(t){return Ct((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=d=>{if(o!==null&&!o.has(String(d.type))||s!==null&&!s.has(String(d.id??"")))return!1;for(let[u,c]of i)if(d[u]!==c)return!1;return!0};r.effect==="deny"?n(r.action,{where:a}):e(r.action,{where:a})}})}function Ir(t){let e=dm.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 dt,dm,Vt=Xe(()=>{"use strict";dt=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}};dm=["human","llm","wallet","system"]});function aa(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(aa);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=aa(t[n]);return e}return null}function lm(t){let e=cm.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,d=3144134277,u=1013904242,c=2773480762,l=1359893119,p=2600822924,f=528734635,m=1541459225,h=new Uint32Array(64),g=(b,v)=>b>>>v|b<<32-v;for(let b=0;b<o;b+=64){for(let _=0;_<16;_++)h[_]=i.getUint32(b+_*4,!1);for(let _=16;_<64;_++){let O=h[_-15],N=h[_-2],L=g(O,7)^g(O,18)^O>>>3,j=g(N,17)^g(N,19)^N>>>10;h[_]=h[_-16]+L+h[_-7]+j>>>0}let v=a,T=d,w=u,x=c,k=l,S=p,R=f,E=m;for(let _=0;_<64;_++){let O=g(k,6)^g(k,11)^g(k,25),N=k&S^~k&R,L=E+O+N+um[_]+h[_]>>>0,j=g(v,2)^g(v,13)^g(v,22),$=v&T^v&w^T&w,D=j+$>>>0;E=R,R=S,S=k,k=x+L>>>0,x=w,w=T,T=v,v=L+D>>>0}a=a+v>>>0,d=d+T>>>0,u=u+w>>>0,c=c+x>>>0,l=l+k>>>0,p=p+S>>>0,f=f+R>>>0,m=m+E>>>0}let y=b=>b.toString(16).padStart(8,"0");return y(a)+y(d)+y(u)+y(c)+y(l)+y(p)+y(f)+y(m)}function Kt(t){let e=aa(t??null),n=JSON.stringify(e);return lm(n).slice(0,16)}function pm(){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 $n(t,e,n){let r=n?.id??pm();if(t===0)return{id:r,version:0};let s=(n?.hash??Kt)(e);return{id:r,version:0,cid:s,prev:null}}function Pr(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}function da(t){return"cid"in t}var um,cm,Bo=Xe(()=>{"use strict";um=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]),cm=new TextEncoder});function xu(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function ua(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function Vo(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function la(t){if(Fe._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(Fe)}function U(t,e,n){let r=Ru(t)?t:[],o=typeof t=="function"?t:typeof e=="function"?e:void 0,s={};return Ru(t)?s=(ca(e)?e:n)??{}:ca(t)?s=t:s=(ca(e)?e:n)??{},new Oe(r,o,s)}var wu,ku,fm,mm,Fe,Oe,Ru,ca,Me=Xe(()=>{"use strict";jo();Mr();Ae();Re();ia();Vt();ae();Bo();wu=()=>{},ku=100;fm=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},mm=(t,e,n,r)=>{let o=t;if(o._status==="completed"||o._status==="errored")return;let s=o._cached,i=s===void 0?[Cn]:[Cn,[M,s]];o._status==="dirty"&&i.push(Mt),At(e,i,o._config.tierOf)},Fe=new an({onMessage:fm,onSubscribe:mm});Cr(Fe);_r(Fe);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??Fe,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??Kt;let o=r.versioning??this._config.defaultVersioning;this._versioningLevel=o,this._versioning=o!=null?$n(o,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(xu);let s={};for(let[a,d]of Object.entries(r.meta??{})){let u={initial:d,name:`${r.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};r.guard!=null&&(u.guard=r.guard),s[a]=new t([],void 0,u)}Object.freeze(s),this.meta=s,this._hasMeta=Object.keys(s).length>0;let i=this;this._actions={emit(a){i._emit([[M,a]])},down(a){i._emit(Vo(a))},up(a){i._emitUp(Vo(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,d=i?.version??0,u=$n(e,s,{id:a,hash:o});u.version=d,this._versioning=u,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let n=Ot(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=Ot(e?.actor),s=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(o,s))throw new dt({actor:o,action:s,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(o,s))throw new dt({actor:o,action:s,nodeName:this.name})}this._lastMutation={actor:o,timestamp_ns:se()}}down(e,n){let r=Vo(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[M,e]])}up(e,n){if(this._deps.length===0)return;let r=Vo(e);if(r.length===0)return;this._checkGuard(n);let o=n??{internal:!0};this._validateUpTiers(r);for(let s of this._deps)s.node.up?.(r,o)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let n of this._deps)n.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let n=this._config.tierOf;for(let r of e){let o=n(r[0]);if(o===3||o===4)throw new Error(`Node "${this.name}": tier-${o} messages cannot flow up \u2014 DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \`down(...)\` for value delivery; \`up(...)\` is for control signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).`)}}subscribe(e,n){if(n!=null&&this._guard!=null){let d=Ot(n);if(!this._guard(d,"observe"))throw new dt({actor:d,action:"observe",nodeName:this.name})}let o=this._isTerminal&&this._resubscribable;if(o){this._cached=void 0,this._status="sentinel",this._store={},this._hasCalledFnOnce=!1,this._waveHasNewData=!1,this._hasNewTerminal=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._isExecutingFn=!1,this._rerunDepth=0,this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null;for(let d of this._deps)ua(d);if(this._partial===!1){for(let d of this._deps)if(d.prevData!==void 0||d.dataBatch.length!==0||d.terminal!==void 0||d.dirty)throw new Error(`resubscribable-reset invariant: DepRecord not fully reset for node ${this._optsName??"(anonymous)"}`)}}this._sinkCount+=1;let s;try{s=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:o},this._actions)}catch(d){throw this._sinkCount-=1,d}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let i=this._isTerminal;if(this._sinkCount===1&&!i)try{this._activate()}catch(d){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof s=="function")try{s()}catch{}throw d}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let 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=wu,s.unsub=s.node.subscribe(i=>{if(s.unsub===null)return;let a=this._config.tierOf,d=!1;for(let u of i)a(u[0])>=3&&(d=!0),this._config.onMessage(this,u,{direction:"down-in",depIndex:o},this._actions);d&&this._maybeRunFnOnSettlement()}),n++}}catch(r){this._deps[n].unsub=null;for(let o=0;o<n;o++){let s=this._deps[o];if(s.unsub!=null){let i=s.unsub;s.unsub=null;try{i()}catch{}ua(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=xu(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Ln),r.unsub=wu;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([[I,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([[I,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{}}ua(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!==ft){if(o===oe){this._depDirtied(r);return}if(o===Qe){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(Rr);return}if(o===Ve||o===ze){this._emit([n]);return}if(o===le){this._emit(In);return}if(o===M)this._depSettledAsData(r,n[1]);else if(o===q)this._depSettledAsResolved(r);else if(o===P)this._depSettledAsTerminal(r,!0);else if(o===I)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(o===M||o===q)&&this._emit([n]),(o===P||o===I)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Ln))}_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(xr),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([[I,e.terminal]]);return}this._autoComplete&&this._deps.every(n=>n.terminal!==void 0)&&this._emit(Sr)}_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([[I,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([[I,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([[I,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>ku?(this._rerunDepth=0,this._emit([[I,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${ku} \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"?[Mt,e[0]]:e;let r=!0,o=!1,s=!1,i=-1;for(let d of e){let u=n(d[0]);u<i&&(r=!1),u===3&&(o=!0),d[0]===oe&&(s=!0),i=u}let a=e;if(!r){let d=e.map((u,c)=>({m:u,i:c,tier:n(u[0])}));d.sort((u,c)=>u.tier-c.tier||u.i-c.i),a=d.map(u=>u.m)}if(o&&!s&&this._status!=="dirty"){let d=0;for(;d<a.length&&n(a[d][0])===0;)d++;return d===0?[Mt,...a]:[...a.slice(0,d),Mt,...a.slice(d)]}return a}_emit(e){if(e.length===0)return;for(let a=0;a<e.length;a++){let d=e[a];if(d[0]===I&&d[1]===void 0)throw new TypeError('[ERROR, payload] requires a non-undefined payload (spec \xA71.2). Pass an Error object or domain tag instead \u2014 e.g. node.down([[ERROR, new Error("reason")]])')}let n=e;if(this._isTerminal&&!this._resubscribable){let a=e.filter(d=>d[0]===le||d[0]===Qe);if(a.length===0)return;n=a}n=this._frameBatch(n);let o=null;for(let a=0;a<n.length;a++){let d=n[a],u=d[0];if(u!==Ve&&u!==ze){o?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${u===Ve?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let c=!0;if(this._pausable!==!1){let l=d[1];if(u===Ve)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(l),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(l))c=!1;else if(this._pauseLocks.delete(l),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let p=this._pauseBuffer;this._pauseBuffer=[],this._emit(p)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?o?.push(d):o==null&&(o=n.slice(0,a))}if(o!=null){if(o.length===0)return;n=o}if(this._hasMeta&&n.some(a=>a[0]===le))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(In)}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,d=[];for(let u of s)a(u[0])===3?this._pauseBuffer.push(u):d.push(u);d.length>0&&this._dispatchOrAccumulate(d)}else this._dispatchOrAccumulate(s);i!=null&&this._emit([[I,i]])}_updateState(e){let n=this._config.tierOf,r,o,s=-1,i=0;for(let c of e)n(c[0])===3&&i++;let a=i<=1,d=-1;if(this._versioning!=null&&i>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===M){d=c;break}}for(let c=0;c<e.length;c++){let l=e[c],p=l[0];if(p===M){if(l.length>=2){let f=!1;if(a&&this._cached!==void 0)try{f=this._equals(this._cached,l[1])}catch(m){o=this._wrapFnError("equals threw",m),s=c;break}if(f){r==null&&(r=e.slice(0,c)),r.push(An),this._status="resolved";continue}this._cached=l[1],this._versioning!=null&&(d<0||c===d)&&Pr(this._versioning,l[1],this._hashFn)}this._status="settled",r?.push(l)}else if(r?.push(l),p===oe)this._status="dirty";else if(p===q)this._status="resolved";else if(p===P){this._status="completed";{let f=this._config.rigorRecorder;if(f!=null)try{f.onTerminalTransition(this,"completed",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===I){this._status="errored";{let f=this._config.rigorRecorder;if(f!=null)try{f.onTerminalTransition(this,"errored",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===Qe){if(this._cached!==void 0){let m=this._config.rigorRecorder;if(m!=null)try{m.onNonVacuousInvalidate(this,this._cached)}catch{}}this._cached=void 0,this._status="dirty";let f=this._cleanup;if(typeof f=="function"){this._cleanup=void 0;try{f()}catch{}}else if(f!=null&&typeof f=="object"){let m=f.invalidate;if(typeof m=="function")try{m()}catch{}}}else p===le&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let u=s>=0?r??e.slice(0,s):r??e;return o!=null?{finalMessages:u,equalsError:o}:{finalMessages:u}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let n=[...this._sinks];for(let r of n)r(e)};_dispatchOrAccumulate(e){if(vu()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],Fn(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}At(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);At(this._deliverToSinks,n,this._config.tierOf)}},Ru=t=>Array.isArray(t),ca=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function A(t,e){return U([],{...e,initial:t})}function z(t,e){return U((r,o,s)=>t(o,s)??void 0,{describeKind:"producer",...e})}function C(t,e,n){return U(t,(o,s,i)=>{let a=o.map((d,u)=>d!=null&&d.length>0?d.at(-1):i.prevData[u]);s.emit(e(a,i))},{describeKind:"derived",...n})}function ge(t,e,n){return U(t,(o,s,i)=>{let a=o.map((d,u)=>d!=null&&d.length>0?d.at(-1):i.prevData[u]);return e(a,s,i)??void 0},{describeKind:"effect",...n})}function Dr(t,e,n){let r=new Map;return t.forEach((o,s)=>{r.set(o,s)}),C(t,(o,s)=>e(a=>{let d=r.get(a);if(d==null)throw new Error(`dynamicNode: untracked dep "${a.name??"<unnamed>"}"`);return o[d]},s),n)}function dn(t,e){let n,r=new Map,o=(s,i,a)=>{let d=!1,u=c=>{let l=r.get(c);if(l!==void 0){if(l<s.length){let f=s[l];return f!=null&&f.length>0?f.at(-1):a.prevData[l]}return c.cache}d=!0;let p=n._addDep(c);return r.set(c,p),c.cache};try{let c=t(u,a);d||(i.emit(c),a.store.__autoTrackLastDiscoveryError!=null&&delete a.store.__autoTrackLastDiscoveryError)}catch(c){if(!d)throw c;a.store.__autoTrackLastDiscoveryError=c}};return n=new Oe([],o,{describeKind:"derived",...e}),n}function pa(t,...e){let n=t;for(let r of e)n=r(n);return n}var ne=Xe(()=>{"use strict";Me()});function $r(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 d,u;if(s==="*")d=e,u=n;else if(s.includes("-")){let[c,l]=s.split("-");d=Number.parseInt(c,10),u=Number.parseInt(l,10)}else d=Number.parseInt(s,10),u=d;if(Number.isNaN(d)||Number.isNaN(u))throw new Error(`Invalid cron field: ${t}`);if(d<e||u>n)throw new Error(`Cron field out of range: ${t} (${e}-${n})`);if(d>u)throw new Error(`Invalid cron range: ${d}-${u} in ${t}`);for(let c=d;c<=u;c+=a)r.add(c)}return r}function Jo(t){let e=t.trim().split(/\s+/);if(e.length!==5)throw new Error(`Invalid cron: expected 5 fields, got ${e.length}`);return{minutes:$r(e[0],0,59),hours:$r(e[1],0,23),daysOfMonth:$r(e[2],1,31),months:$r(e[3],1,12),daysOfWeek:$r(e[4],0,6)}}function Yo(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 ga=Xe(()=>{"use strict"});function Lt(t,e){if(e!=null&&e.length>0)return new Set(e);switch(t){case"standard":return new Set(["type","status","value","deps","meta","v"]);case"full":return null;case"spec":return new Set(["type","deps","meta"]);default:return new Set(["type","deps"])}}function xm(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function st(t){let e=new WeakSet,n={};for(let[r,o]of ju(t))n[r]=ha(o,e);return n}function ha(t,e){if(t==null)return t;let n=typeof t;if(n==="boolean"||n==="number"||n==="string")return t;if(n==="function")return"<function>";if(Array.isArray(t))return e.has(t)?"<cycle>":(e.add(t),t.map(r=>ha(r,e)));if(n==="object"){let r=t;if(e.has(r))return"<cycle>";e.add(r);try{if(typeof r.subscribe=="function"&&"cache"in r)return"<Node>"}catch{return"<unserializable>"}let o={};for(let[s,i]of ju(r))o[s]=ha(i,e);return o}return"<unserializable>"}function ju(t){let e=[],n;try{n=Object.keys(t)}catch{return e}for(let r of n)try{e.push([r,t[r]])}catch{e.push([r,"<unserializable>"])}return e}function we(t,e){let n={factory:t};return e!==void 0&&(n.factoryArgs=e),n}function Rm(t){let e={};for(let[n,r]of Object.entries(t.meta))try{e[n]=r.cache}catch{}return e}function jr(t,e){let n=e==null,r=!n&&e!=null?[...e].filter(u=>u.startsWith("meta.")).map(u=>u.slice(5)):null,o=n||e.has("meta")||r!=null&&r.length>0,s="state",i=[];t instanceof Oe&&(s=xm(t),i=t._deps.map(u=>u.node.name??""));let a={type:s,deps:i};(n||e.has("status"))&&(a.status=t.status);let d=t instanceof Oe?t._guard:void 0;if(o){let u={...Rm(t)};if(d!=null&&u.access===void 0&&(u.access=Ir(d)),r!=null&&r.length>0&&!e.has("meta")){let c={};for(let l of r)l in u&&(c[l]=u[l]);a.meta=c}else a.meta=u}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 u={id:t.v.id,version:t.v.version};"cid"in t.v&&(u.cid=t.v.cid,u.prev=t.v.prev),a.v=u}return(n||e.has("guard"))&&d!=null&&(a.guard=Ir(d)),(n||e.has("lastMutation"))&&t.lastMutation!=null&&(a.lastMutation=t.lastMutation),a}var it=Xe(()=>{"use strict";Vt();Me()});var Bu={};Se(Bu,{NS_PER_MS:()=>He,NS_PER_SEC:()=>lt,constant:()=>Qo,decorrelatedJitter:()=>ts,exponential:()=>Zo,fibonacci:()=>es,linear:()=>Xo,resolveBackoffPreset:()=>qt,withMaxAttempts:()=>ya});function cn(t){return t<0?0:t}function Sm(t,e){return e==="none"?t:e==="full"?Math.random()*t:t/2+Math.random()*(t/2)}function Nm(t,e){return t+Math.random()*(e-t)}function Qo(t){let e=cn(t);return()=>e}function Xo(t,e){let n=cn(t),r=e===void 0?n:cn(e);return o=>n+r*Math.max(0,o)}function Zo(t){let e=cn(t?.baseNs??1e8),n=t?.factor!==void 0&&t.factor<1?1:t?.factor??2,r=cn(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,d=1;for(let u=0;u<Math.max(0,s);u++){if(d>=a){d=a;break}d*=n}i=e*d,i>r&&(i=r)}return Sm(i,o)}}function es(t=100*1e6,e=30*1e9){let n=cn(t),r=cn(e);function o(s){if(s<=0)return 1;let i=1,a=2;for(let d=1;d<s;d++){let u=i+a;i=a,a=u}return a}return s=>{let i=o(s)*n;return i<=r?i:r}}function ts(t=100*1e6,e=30*1e9){return(n,r,o)=>{let i=Math.min(e,(o??t)*3);return Nm(t,i)}}function ya(t,e){return(n,r,o)=>n>=e?null:t(n,r,o)}function qt(t){if(t==="constant")return Qo(1*1e9);if(t==="linear")return Xo(1*1e9);if(t==="exponential")return Zo();if(t==="fibonacci")return es();if(t==="decorrelatedJitter")return ts();throw new Error(`Unknown backoff preset: "${String(t)}". Use one of: constant, linear, exponential, fibonacci, decorrelatedJitter`)}var He,lt,Wn=Xe(()=>{"use strict";He=1e6,lt=1e9});var Ie,Rt=Xe(()=>{"use strict";Ie=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 qu={};Se(qu,{CircuitOpenError:()=>yt,RateLimiterOverflowError:()=>ln,TimeoutError:()=>pn,circuitBreaker:()=>Nt,fallback:()=>Yn,rateLimiter:()=>Jn,retry:()=>St,timeout:()=>Qn,tokenBucket:()=>zt,withBreaker:()=>Un,withStatus:()=>Ht});function fn(t){return{describeKind:"derived",...t}}function Em(t){return t<0?0:t}function ns(t){return t[1]}function Vu(t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("backoff strategy must return a finite number");return t<0?0:t}function St(t,e){return typeof t=="function"?Mm(t,e):_m(t,e)}function Ku(t){let e={};return t?.count!==void 0&&(e.count=t.count),typeof t?.backoff=="string"&&(e.backoff=t.backoff),Object.keys(e).length>0?e:void 0}function _m(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"?qt(r):r;return z(i=>{let a=0,d=!1,u=null,c,l=new Ie;function p(){c?.(),c=void 0}function f(h){if(d)return;if(a>=o){p(),i.down([[I,h]]);return}let g=s===null?0:s(a,h,u);if(g==null){p(),i.down([[I,h]]);return}let y;try{y=Vu(g)}catch{p(),i.down([[I,h]]);return}u=y,a+=1,p();let b=y>0?y/1e6:1;l.start(b,()=>{d||m()})}function m(){l.cancel(),p(),c=t.subscribe(h=>{if(!d)for(let g of h){let y=g[0];if(y===oe)i.down([[oe]]);else if(y===M)a=0,u=null,i.emit(g[1]);else if(y===q)i.down([[q]]);else if(y===P)p(),i.down([[P]]);else if(y===I){f(ns(g));return}else i.down([g])}})}return m(),()=>{d=!0,l.cancel(),p()}},{...fn(),initial:t.cache,meta:{...we("retry",Ku(e))}})}function Mm(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"?qt(r):r;return z(i=>{let a=0,d=!1,u=null,c,l=new Ie;function p(){c?.(),c=void 0}function f(h){if(d)return;if(a>=o){p(),i.down([[I,h]]);return}let g=s===null?0:s(a,h,u);if(g==null){p(),i.down([[I,h]]);return}let y;try{y=Vu(g)}catch{p(),i.down([[I,h]]);return}u=y,a+=1,p();let b=y>0?y/1e6:1;l.start(b,()=>{d||m()})}function m(){l.cancel(),p();let h;try{h=t()}catch(g){f(g);return}c=h.subscribe(g=>{if(!d)for(let y of g){let b=y[0];if(b===oe)i.down([[oe]]);else if(b===M)a=0,u=null,i.emit(y[1]);else if(b===q)i.down([[q]]);else if(b===P)p(),i.down([[P]]);else if(b===I){f(ns(y));return}else i.down([y])}})}return m(),()=>{d=!0,l.cancel(),p()}},{...fn(),initial:e?.initial,meta:{...we("retry",Ku(e))}})}function Nt(t){let e=Math.max(1,t?.failureThreshold??5),n=Em(t?.cooldownNs??30*1e9),r=t?.cooldown??null,o=Math.max(1,t?.halfOpenMax??1),s=t?.now??V,i="closed",a=0,d=0,u=0,c=n,l=0;function p(){if(!r)return n;let h=r(d);return h!==null?h:n}function f(){i="open",c=p(),u=s(),l=0}return{canExecute(){return i==="closed"?!0:i==="open"?s()-u>=c?(i="half-open",l=1,!0):!1:l<o?(l++,!0):!1},recordSuccess(){i==="half-open"?(i="closed",a=0,d=0):i==="closed"&&(a=0)},recordFailure(h){if(i==="half-open"){d++,f();return}i==="closed"&&(a++,a>=e&&f())},get state(){return i},get failureCount(){return a},reset(){i="closed",a=0,d=0,l=0}}}function Un(t,e){let n=e?.onOpen??"skip";return r=>{let o=U([],(s,i)=>{function a(){o.meta.breakerState.down([[M,t.state]])}let d=r.subscribe(u=>{for(let c of u){let l=c[0];l===oe?i.down([[oe]]):l===M?t.canExecute()?(a(),i.emit(c[1])):(a(),n==="error"?i.down([[I,new yt]]):i.down([[q]])):l===q?i.down([[q]]):l===P?(t.recordSuccess(),a(),i.down([[P]])):l===I?(t.recordFailure(ns(c)),a(),i.down([c])):i.down([c])}});return a(),d},{...fn(),meta:{breakerState:t.state,...we("withBreaker",{onOpen:n})},completeWhenDepsComplete:!1,initial:r.cache});return{node:o,breakerState:o.meta.breakerState}}}function zt(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 Jn(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 z(a=>{let d=zt(n,i),u=[],c=new Ie,l=!1,p=1e9/i;function f(){for(;u.length>0;)if(d.tryConsume(1))a.emit(u.shift());else{c.start(Math.max(1,p/1e6),f);return}}let m=t.subscribe(h=>{for(let g of h){if(l)return;let y=g[0];if(y===oe)a.down([[oe]]);else if(y===M){if(o!==void 0&&u.length>=o){if(s!=="drop-newest")if(s==="drop-oldest")u.shift(),u.push(g[1]);else{l=!0,c.cancel(),u.length=0,a.down([[I,new ln(o)]]);return}}else u.push(g[1]);f()}else if(y===q)a.down([[q]]);else if(y===P)l=!0,c.cancel(),u.length=0,a.down([[P]]);else if(y===I)l=!0,c.cancel(),u.length=0,a.down([g]);else if(y===le){l=!0,c.cancel(),u.length=0,a.down([g]);return}else a.down([g])}});return()=>{l=!0,c.cancel(),m()}},{...fn(),initial:t.cache,meta:{...we("rateLimiter",e)}})}function Ht(t,e){let n=e?.initialStatus??"pending",r=U([],(o,s)=>{let i=n;return r.meta.status.down([[M,n]]),r.meta.error.down([[M,null]]),t.subscribe(d=>{for(let u of d){let c=u[0];if(c===oe)s.down([[oe]]);else if(c===M)i==="errored"?Z(()=>{r.meta.error.down([[M,null]]),r.meta.status.down([[M,"active"]])}):r.meta.status.down([[M,"active"]]),i="active",s.emit(u[1]);else if(c===q)s.down([[q]]);else if(c===P)r.meta.status.down([[M,"completed"]]),i="completed",s.down([[P]]);else if(c===I){let l=ns(u);Z(()=>{r.meta.error.down([[M,l]]),r.meta.status.down([[M,"errored"]])}),i="errored",s.down([u])}else s.down([u])}})},{...fn(),meta:{status:n,error:null,...we("withStatus",{initialStatus:n})},completeWhenDepsComplete:!1,resubscribable:!0,initial:t.cache});return{node:r,status:r.meta.status,error:r.meta.error}}function Om(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function Am(t){return t!=null&&typeof t.then=="function"}function Cm(t){return t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function"}function Yn(t,e){return z(n=>{let r,o;function s(){o?.(),o=void 0,Om(e)||Am(e)||Cm(e)?r=Y(e).subscribe(a=>{n.down(a)}):(n.emit(e),n.down([[P]]))}return o=t.subscribe(i=>{for(let a of i){let d=a[0];if(d===oe)n.down([[oe]]);else if(d===M)n.emit(a[1]);else if(d===q)n.down([[q]]);else if(d===P)n.down([[P]]);else if(d===I){s();return}else if(d===le){r?.(),n.down([a]);return}else n.down([a])}}),()=>{o?.(),r?.()}},{...fn(),initial:t.cache,meta:{...we("fallback")}})}function Qn(t,e){if(e<=0)throw new RangeError("timeoutNs must be > 0");return z(n=>{let r=!1,o=new Ie;function s(){let a=e/1e6;o.start(a,()=>{r||(r=!0,i(),n.down([[I,new pn(e)]]))})}let i=t.subscribe(a=>{for(let d of a){if(r)return;let u=d[0];if(u===oe)n.down([[oe]]);else if(u===M)s(),n.emit(d[1]);else if(u===q)n.down([[q]]);else if(u===P){o.cancel(),r=!0,n.down([[P]]);return}else if(u===I){o.cancel(),r=!0,n.down([d]);return}else if(u===le){o.cancel(),r=!0,n.down([d]);return}else n.down([d])}});return s(),()=>{r=!0,o.cancel(),i()}},{...fn(),initial:t.cache,meta:{...we("timeout",{timeoutNs:e})}})}var yt,ln,pn,It=Xe(()=>{"use strict";Ae();Re();ae();it();Me();ne();Wn();ve();Rt();yt=class extends Error{name="CircuitOpenError";constructor(){super("Circuit breaker is open")}};ln=class extends Error{name="RateLimiterOverflowError";constructor(e){super(`rateLimiter buffer overflow (maxBuffer=${e})`)}};pn=class extends Error{name="TimeoutError";constructor(e){super(`Timed out after ${e/1e6}ms`)}}});function pt(t){return{describeKind:"producer",...t}}function va(t){return/[\\^$+?.()|[\]{}]/.test(t)?`\\${t}`:t}function Hu(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+=va(r)}return e+="$",new RegExp(e)}function Wu(t,e){for(let n of e)if(n.test(t))return!0;return!1}function Lm(t,e){let n=U([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[q]]);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 Ze(t,e){let{signal:n,period:r,...o}=e??{};return z(s=>{let i=!1,a=0,d,u,c=()=>{i=!0,d!==void 0&&clearTimeout(d),u!==void 0&&clearInterval(u),n?.removeEventListener("abort",p)},l=()=>{i||(r!=null?(s.emit(a++),u=setInterval(()=>{i||s.emit(a++)},r)):(i=!0,n?.removeEventListener("abort",p),s.emit(a++),s.down([[P]])))},p=()=>{i||(c(),s.down([[I,n.reason]]))};if(n?.aborted){p();return}return d=setTimeout(l,t),n?.addEventListener("abort",p,{once:!0}),c},pt(o))}function Uu(t){let{signal:e,...n}=t??{};return z(r=>{let o=!1,s,i,a=!1,d=!1,u=typeof requestAnimationFrame=="function"?requestAnimationFrame:void 0,c=typeof cancelAnimationFrame=="function"?cancelAnimationFrame:void 0,l=typeof document<"u"?document:void 0,p=()=>{s!==void 0&&c&&c(s),i!==void 0&&clearTimeout(i),s=void 0,i=void 0},f=()=>{o=!0,p(),a&&(e?.removeEventListener("abort",m),a=!1),d&&l&&(l.removeEventListener("visibilitychange",y),d=!1)},m=()=>{o||(f(),r.down([[I,e.reason]]))},h=b=>{o||(r.emit(b),g())},g=()=>{o||(u&&(!l||l.visibilityState!=="hidden")?s=u(h):i=setTimeout(()=>h(performance.now()),16))},y=()=>{o||(p(),g())};return e?.aborted?(m(),f):(e?.addEventListener("abort",m,{once:!0}),a=e!==void 0,l&&u&&(l.addEventListener("visibilitychange",y),d=!0),g(),f)},pt(n))}function os(t,e){let n=Jo(t),{tickMs:r,output:o,...s}=e??{},i=r??6e4,a=o==="date";return z(d=>{let u=-1,c=()=>{let p=new Date,f=p.getFullYear()*1e8+(p.getMonth()+1)*1e6+p.getDate()*1e4+p.getHours()*100+p.getMinutes();f!==u&&Yo(n,p)&&(u=f,d.emit(a?p:se()))};c();let l=setInterval(c,i);return()=>clearInterval(l)},{...pt(s),name:s.name??`cron:${t}`})}function Ju(t,e,n){let{capture:r,passive:o,once:s,...i}=n??{};return z(a=>{let d=c=>{a.emit(c)},u={capture:r,passive:o,once:s};return t.addEventListener(e,d,u),()=>t.removeEventListener(e,d,u)},pt(i))}function ss(t,e){return z(n=>{let r=!1;try{for(let o of t){if(r)return;n.emit(o)}r||n.down([[P]])}catch(o){r||n.down([[I,o]])}return()=>{r=!0}},pt(e))}function Im(t){return t!=null&&typeof t.then=="function"}function Xn(t,e){let{signal:n,...r}=e??{};return z(o=>{let s=!1,i=()=>{s||(s=!0,o.down([[I,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([[P]]))},a=>{s||(s=!0,n?.removeEventListener("abort",i),o.down([[I,a]]))}),()=>{s=!0,n?.removeEventListener("abort",i)}},pt(r))}function Br(t,e){let{signal:n,...r}=e??{};return z(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,d=!1,u=t[Symbol.asyncIterator](),c=()=>{d||a.aborted||Promise.resolve(u.next()).then(l=>{if(!(d||a.aborted)){if(l.done){o.down([[P]]);return}o.emit(l.value),c()}},l=>{!d&&!a.aborted&&o.down([[I,l]])})};return c(),()=>{d=!0,n?.removeEventListener("abort",i),s.abort(),Promise.resolve(u.return?.()).catch(()=>{})}},pt(r))}function Pm(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function Y(t,e){if(Pm(t))return t;if(Im(t))return Xn(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return Br(t,e);if(typeof n[Symbol.iterator]=="function")return ss(t,e)}return Ta(t)}function Ta(...t){return ss(t,void 0)}function Yu(t){return z(e=>{e.down([[P]])},pt(t))}function Qu(t){return z(()=>{},pt(t))}function Xu(t,e){return z(n=>{n.down([[I,t]])},pt(e))}function Zu(t,e){let{signal:n,...r}=e??{},o=pt(r),s=o.resubscribable===void 0?{...o,resubscribable:!0}:o;return z(i=>{let a,d=!1;try{let u=t();a=Y(u,e).subscribe(l=>{if(!d)for(let p of l){let f=p[0];if(f!==ft)if(f===M)i.emit(p[1]);else if(f===P){d=!0,i.down([[P]]);break}else if(f===I){d=!0,i.down([[I,p[1]]]);break}else i.down([p])}})}catch(u){let c=u===void 0?new Error("defer: thunk threw undefined"):u;i.down([[I,c]])}return()=>{d=!0,a?.()}},s)}function Wt(t,e,n){return U([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 ec(t,e){return U([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([[P]]);return}(i==null||i.length===0)&&r.down([[q]])},{describeKind:"derived",completeWhenDepsComplete:!1,...e})}function tc(t,e){return z(n=>t.subscribe(r=>{n.down(r)}),{...pt(e),initial:t.cache})}function is(t,e,n){if(e<1)throw new RangeError("replay expects bufferSize >= 1");let r=[],o=z(s=>t.subscribe(i=>{for(let a of i)a[0]===M&&(r.push(a[1]),r.length>e&&r.shift());s.down(i)}),{...pt(n),initial:t.cache});return Lm(o,s=>{for(let i of r)s([[M,i]])})}function nc(t,e){return is(t,1,e)}function et(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]===M){r=!0,e(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===I){r=!0,n(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===P){r=!0,n(new Error("completed without DATA")),s?(s(),s=void 0):o=!0;return}}}),o&&(s?.(),s=void 0)})}function rs(t,e,n){return new Promise((r,o)=>{let s=!1,i=!1,a,d=n?.skipCurrent===!0;a=t.subscribe(u=>{for(let c of u){if(s)return;if(!(d&&c[0]===M)){if(c[0]===M){let l=c[1];if(e(l)){s=!0,r(l),a?(a(),a=void 0):i=!0;return}}if(c[0]===I){s=!0,o(c[1]),a?(a(),a=void 0):i=!0;return}if(c[0]===P){s=!0,o(new Error("completed without matching value")),a?(a(),a=void 0):i=!0;return}}}}),d=!1,i&&(a?.(),a=void 0)})}async function as(t,e){let n=e?.predicate??(s=>s!=null),r=e?.skipCurrent;if(e?.timeoutMs==null||e.timeoutMs<=0)return await rs(t,n,{skipCurrent:r});if(ba===void 0){let[s,i]=await Promise.all([Promise.resolve().then(()=>(It(),qu)),Promise.resolve().then(()=>(Wn(),Bu))]);ba=s.timeout,zu=i.NS_PER_MS}let o=ba(t,e.timeoutMs*zu);return await rs(o,n,{skipCurrent:r})}function ds(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 d of a){if(d[0]===M&&d[1]===!0){n.abort(r),i();return}if(d[0]===I){n.abort(d[1]),i();return}if(d[0]===P){i();return}}}),s&&(o?.(),o=void 0),{signal:n.signal,dispose:()=>{o&&(o(),o=void 0)}}}function te(t){return t.subscribe(()=>{})}function wa(t){let e=A(0);return{node:e,increment(){let n=e.cache??0;return n>=t?!1:(e.down([[oe],[M,n+1]]),!0)},get(){return e.cache??0},atCap(){return(e.cache??0)>=t}}}var ba,zu,rc,ve=Xe(()=>{"use strict";Re();ae();Me();ne();ga();rc=is});var pv={};Se(pv,{COMPLETE:()=>P,COMPLETE_MSG:()=>Go,COMPLETE_ONLY_BATCH:()=>Sr,CircuitOpenError:()=>yt,ContentAddressedMissError:()=>ao,DATA:()=>M,DEFAULT_ACTOR:()=>xt,DIRTY:()=>oe,DIRTY_MSG:()=>Mt,DIRTY_ONLY_BATCH:()=>Ln,ENVELOPE_VERSION:()=>Pn,ERROR:()=>I,GRAPH_META_SEGMENT:()=>tt,Graph:()=>Q,GraphReFlyConfig:()=>an,GuardDenied:()=>dt,INVALIDATE:()=>Qe,INVALIDATE_MSG:()=>Do,INVALIDATE_ONLY_BATCH:()=>Rr,JsonCodec:()=>$o,NS_PER_MS:()=>He,NS_PER_SEC:()=>lt,NativeIndexBackend:()=>lo,NativeListBackend:()=>po,NativeLogBackend:()=>Hr,NativeMapBackend:()=>so,NativePubSubBackend:()=>co,NodeImpl:()=>Oe,PAUSE:()=>Ve,RESOLVED:()=>q,RESOLVED_MSG:()=>An,RESOLVED_ONLY_BATCH:()=>xr,RESUME:()=>ze,RateLimiterOverflowError:()=>ln,ResettableTimer:()=>Ie,SIZEOF_OVERHEAD:()=>$e,SIZEOF_SYMBOL:()=>hs,SNAPSHOT_VERSION:()=>bt,SNAPSHOT_WIRE_VERSION:()=>Io,START:()=>ft,START_MSG:()=>Cn,SurfaceError:()=>_e,TEARDOWN:()=>le,TEARDOWN_MSG:()=>Fo,TEARDOWN_ONLY_BATCH:()=>In,TimeoutError:()=>pn,accessHintForGuard:()=>Ir,accountability:()=>Si,advanceVersion:()=>Pr,ai:()=>ki,appendLogStorage:()=>ed,asSurfaceError:()=>Hi,audit:()=>al,autoTrackNode:()=>dn,awaitSettled:()=>as,batch:()=>Z,buffer:()=>dl,bufferCount:()=>ul,bufferTime:()=>ll,cached:()=>nc,canonicalJson:()=>uo,cascadingCache:()=>vp,catchError:()=>wl,checkpointToRedis:()=>lp,checkpointToS3:()=>cp,circuitBreaker:()=>Nt,combine:()=>Ka,combineLatest:()=>bl,compat:()=>Ba,concat:()=>el,concatMap:()=>rl,configure:()=>la,constant:()=>Qo,contentAddressedStorage:()=>Vs,core:()=>Ma,cqrs:()=>Es,createDagCborCodec:()=>ra,createDagCborZstdCodec:()=>oa,createGraph:()=>vr,createTransport:()=>Zt,createVersioning:()=>$n,createWatermarkController:()=>Zn,csvRows:()=>Hl,debounce:()=>za,debounceTime:()=>vl,decodeEnvelope:()=>Er,decorrelatedJitter:()=>ts,defaultConfig:()=>Fe,defaultHash:()=>Kt,defer:()=>Zu,delay:()=>sl,deleteSnapshot:()=>Zi,demoShell:()=>Ei,derived:()=>C,deserializeError:()=>wn,dictKv:()=>Cp,dictSnapshot:()=>Lp,diffForWAL:()=>Ts,diffSnapshots:()=>Qi,distill:()=>js,distinctUntilChanged:()=>Qc,domainTemplates:()=>_i,downWithBatch:()=>At,dynamicNode:()=>Dr,effect:()=>ge,elementAt:()=>Uc,empty:()=>Yu,encodeEnvelope:()=>Nr,escapeRegexChar:()=>va,exhaustMap:()=>nl,explainPath:()=>Kr,exponential:()=>Zo,externalBundle:()=>Gs,externalProducer:()=>bn,extra:()=>rd,factoryTag:()=>we,fallback:()=>Yn,fibonacci:()=>es,filter:()=>rt,find:()=>Wc,first:()=>Fs,firstValueFrom:()=>et,firstWhere:()=>rs,flatMap:()=>ol,forEach:()=>Wt,fromAny:()=>Y,fromAsyncIter:()=>Br,fromCSV:()=>zl,fromClickHouseWatch:()=>Yl,fromCron:()=>os,fromDrizzle:()=>hp,fromEvent:()=>Ju,fromHTTP:()=>Ya,fromHTTPPoll:()=>Al,fromHTTPStream:()=>Ol,fromIter:()=>ss,fromKafka:()=>Bl,fromKysely:()=>yp,fromMCP:()=>Il,fromNATS:()=>Zl,fromNDJSON:()=>Jl,fromOTel:()=>Pl,fromPrisma:()=>gp,fromPrometheus:()=>jl,fromPromise:()=>Xn,fromPulsar:()=>Ql,fromRabbitMQ:()=>tp,fromRaf:()=>Uu,fromRedisStream:()=>Kl,fromSSE:()=>Ml,fromSqlite:()=>pp,fromSqliteCursor:()=>fp,fromStatsD:()=>Fl,fromSyslog:()=>Dl,fromTimer:()=>Ze,fromWebSocket:()=>Ja,fromWebSocketReconnect:()=>Ll,fromWebhook:()=>kl,globToRegExp:()=>Hu,graph:()=>Ca,graphProfile:()=>hn,graphspec:()=>wi,guarded:()=>Oi,harness:()=>ji,interval:()=>ml,isBatching:()=>sn,isV1:()=>da,jobQueue:()=>Fi,jotai:()=>Ko,jsonCodec:()=>ar,jsonCodecFor:()=>Mp,keepalive:()=>te,kvStorage:()=>Ws,last:()=>Hc,layout:()=>qi,lens:()=>Vi,linear:()=>Xo,listSnapshots:()=>Xi,lru:()=>Za,makeHttpError:()=>wt,map:()=>eo,matchesAnyPattern:()=>Wu,matchesCron:()=>Yo,memory:()=>bi,memoryAppendLog:()=>Ap,memoryBackend:()=>mo,memoryKv:()=>go,memorySnapshot:()=>Op,merge:()=>Et,mergeMap:()=>qa,mergeReactiveLogs:()=>Lc,mermaidLiveUrl:()=>vs,messaging:()=>li,monotonicNs:()=>V,nameToSignal:()=>vn,nanostores:()=>Wo,ndjsonRows:()=>Wl,nestjs:()=>Ms,never:()=>Qu,node:()=>U,nodeSignal:()=>ds,normalizeActor:()=>Ot,of:()=>Ta,onFirstData:()=>no,orchestration:()=>pi,pairwise:()=>Xc,parseCron:()=>Jo,parsePrometheusText:()=>Qa,parseSSEStream:()=>$t,parseStatsD:()=>$l,parseSyslog:()=>Gl,patterns:()=>du,pausable:()=>hl,pipe:()=>pa,placeholderArgs:()=>st,policy:()=>Ct,policyFromRules:()=>Lr,process:()=>Ki,producer:()=>z,pubsub:()=>Rp,race:()=>tl,rateLimiter:()=>Jn,reachable:()=>yn,react:()=>Os,reactiveCounter:()=>wa,reactiveIndex:()=>Ep,reactiveList:()=>Ks,reactiveLog:()=>Ke,reactiveMap:()=>je,reactiveSink:()=>Ue,reduce:()=>Kc,reduction:()=>Ti,refine:()=>Li,registerBuiltinCodecs:()=>_r,registerBuiltins:()=>Cr,repeat:()=>gl,replay:()=>is,replayWAL:()=>sa,rescue:()=>ro,resilientPipeline:()=>zi,resolveBackoffPreset:()=>qt,resolveDescribeFields:()=>Lt,restoreSnapshot:()=>Yi,retry:()=>St,runReduction:()=>Wi,sample:()=>il,saveSnapshot:()=>Ji,scan:()=>Vc,serializeError:()=>Tn,share:()=>tc,shareReplay:()=>rc,signalToName:()=>Xt,signals:()=>Cs,singleFromAny:()=>qs,singleNodeFromAny:()=>_p,sizeof:()=>qr,skip:()=>Va,snapshotStorage:()=>Hs,solid:()=>Ls,sortJsonValue:()=>fo,stableJsonString:()=>zs,state:()=>A,stratify:()=>ho,surface:()=>ea,svelte:()=>Is,switchMap:()=>ke,take:()=>to,takeUntil:()=>zc,takeWhile:()=>qc,tap:()=>Jc,tapFirst:()=>Yc,throttle:()=>Ha,throttleTime:()=>Tl,throwError:()=>Xu,timeout:()=>Qn,toArray:()=>ec,toCSV:()=>rp,toClickHouse:()=>op,toFile:()=>Xa,toHTTP:()=>xl,toKafka:()=>Vl,toLoki:()=>dp,toMongo:()=>ap,toNATS:()=>ep,toObservable:()=>Uo,toPostgres:()=>ip,toPulsar:()=>Xl,toRabbitMQ:()=>np,toReadableStream:()=>_l,toRedisStream:()=>ql,toS3:()=>sp,toSSE:()=>Nl,toSSEBytes:()=>El,toSqlite:()=>mp,toTempo:()=>up,toWebSocket:()=>Cl,tokenBucket:()=>zt,topologyDiff:()=>er,validateGraphObservability:()=>Aa,valve:()=>yl,verifiable:()=>kp,version:()=>lv,vue:()=>Ps,wallClockNs:()=>se,watchTopologyTree:()=>Pt,window:()=>fl,windowCount:()=>cl,windowTime:()=>pl,withBreaker:()=>Un,withLatestFrom:()=>Ft,withMaxAttempts:()=>ya,withStatus:()=>Ht,workerBridge:()=>td,workerSelf:()=>nd,zip:()=>Zc,zustand:()=>Ds});module.exports=tm(pv);var Ba={};Se(Ba,{jotai:()=>Ko,nanostores:()=>Wo,nestjs:()=>Ms,react:()=>Os,signals:()=>Cs,solid:()=>Ls,svelte:()=>Is,vue:()=>Ps,zustand:()=>Ds});var Ko={};Se(Ko,{atom:()=>gm});ae();ne();function gm(t,e,n){if(typeof t=="function"){let r=t;return typeof e=="function"?Su(r,e,n):Su(r,void 0,e)}return hm(t,e)}function Gr(t){let e=t.cache,n;if(t.subscribe(o=>{for(let[s,i]of o)s===M&&(e=i),s===I&&(n=i)})(),n)throw n;return e}function hm(t,e){let n=A(t,{...e,resubscribable:!0,resetOnTeardown:!0});return{get:()=>n.status==="sentinel"?Gr(n):n.cache,set:r=>n.emit(r),update:r=>{let o=n.status==="sentinel"?Gr(n):n.cache;n.emit(r(o))},subscribe:r=>{let o=!0;return n.subscribe(s=>{for(let[i,a]of s)if(i===M){if(o){o=!1;continue}r(a)}})},meta:n.meta,_node:n}}function Su(t,e,n){let r=dn(s=>t(i=>{let a=i._node;return a.status==="sentinel"&&Gr(a),s(a)}),{...n,resubscribable:!0,resetOnTeardown:!0}),o={get:()=>r.status==="sentinel"?Gr(r):r.cache,subscribe:s=>{let i=!0;return r.subscribe(a=>{for(let[d,u]of a)if(d===M){if(i){i=!1;continue}s(u)}})},meta:r.meta,_node:r};if(e){let s=d=>d.get(),i=(d,u)=>d.set(u),a=o;return a.set=d=>e(s,i,d),a.update=d=>{let u=r.status==="sentinel"?Gr(r):r.cache;return e(s,i,d(u))},a}return o}var Wo={};Se(Wo,{action:()=>km,atom:()=>ym,computed:()=>bm,getValue:()=>Tm,map:()=>vm,onMount:()=>wm,onStart:()=>_u,onStop:()=>Mu});Ae();ae();ne();var zo=new WeakMap,Ho=new WeakMap;function qo(t,e){let n=e.get(t);if(n)for(let r of n)r()}function fa(t,e={}){let n=0;return{...e,get:()=>Eu(t),subscribe:o=>{n===0&&qo(t,zo),n++;let s=t.subscribe(i=>{for(let[a,d]of i)a===M&&o(d)});return()=>{s(),n--,n===0&&qo(t,Ho)}},listen:o=>{n===0&&qo(t,zo),n++;let s=!0,i=t.subscribe(a=>{for(let[d,u]of a)if(d===M){if(s){s=!1;continue}o(u)}});return()=>{i(),n--,n===0&&qo(t,Ho)}},_node:t}}function Nu(t){let e=t.cache,n;if(t.subscribe(o=>{for(let[s,i]of o)s===M&&(e=i),s===I&&(n=i)})(),n)throw n;return e}function Eu(t){return t.status==="sentinel"?Nu(t):t.cache}function ym(t){let e=A(t,{resubscribable:!0,resetOnTeardown:!0});return fa(e,{set:n=>e.emit(n)})}function bm(t,e){let n=Array.isArray(t)?t:[t],r=n.map(s=>s._node),o=Dr(r,s=>{let i=n.map(a=>{let d=a._node;return d.status==="sentinel"&&Nu(d),s(d)});return e(...i)},{resubscribable:!0,resetOnTeardown:!0,equals:Object.is});return fa(o)}function vm(t){let e=A(t,{resubscribable:!0,resetOnTeardown:!0,equals:()=>!1});return fa(e,{set:n=>e.emit(n),setKey:(n,r)=>{let o=Eu(e);e.emit({...o,[n]:r})}})}function Tm(t){return t.get()}function _u(t,e){let n=t._node,r=zo.get(n);r||(r=new Set,zo.set(n,r)),r.add(e)}function Mu(t,e){let n=t._node,r=Ho.get(n);r||(r=new Set,Ho.set(n,r)),r.add(e)}function wm(t,e){_u(t,()=>{let n=e();typeof n=="function"&&Mu(t,n)})}function km(t,e,n){return(...r)=>{let o;return Z(()=>{o=n(...r)}),o}}var Ms={};Se(Ms,{ACTOR_KEY:()=>cs,COMMAND_HANDLERS:()=>Kn,CQRS_EVENT_HANDLERS:()=>qn,CRON_HANDLERS:()=>Vn,CommandHandler:()=>Du,EVENT_HANDLERS:()=>jn,EventHandler:()=>Gu,GRAPHREFLY_REQUEST_GRAPH:()=>un,GRAPHREFLY_ROOT_GRAPH:()=>mt,GraphCron:()=>Pu,GraphInterval:()=>Iu,GraphReflyEventExplorer:()=>mn,GraphReflyGuard:()=>uc,GraphReflyGuardImpl:()=>Vr,GraphReflyModule:()=>_s,INTERVAL_HANDLERS:()=>Bn,InjectCqrsGraph:()=>Au,InjectGraph:()=>Ou,InjectNode:()=>Cu,ObserveGateway:()=>us,OnGraphEvent:()=>Lu,QUERY_HANDLERS:()=>zn,QueryHandler:()=>Fu,SAGA_HANDLERS:()=>Hn,SagaHandler:()=>$u,fromHeader:()=>ac,fromJwtPayload:()=>Ra,getActor:()=>dc,getGraphToken:()=>ut,getNodeToken:()=>ht,observeSSE:()=>sc,observeSubscription:()=>ic,toObservable:()=>Uo});var ma=require("rxjs");ae();function Uo(t,e){return e?.raw?new ma.Observable(n=>t.subscribe(o=>{if(!n.closed){n.next(o);for(let s of o){if(s[0]===I){n.error(s[1]);return}if(s[0]===P){n.complete();return}}}})):new ma.Observable(n=>t.subscribe(o=>{for(let s of o){if(n.closed)return;if(s[0]===M)n.next(s[1]);else if(s[0]===I){n.error(s[1]);return}else if(s[0]===P){n.complete();return}}}))}var Fr=require("@nestjs/common");var mt=Symbol.for("graphrefly:root-graph");var un=Symbol.for("graphrefly:request-graph");function ut(t){return Symbol.for(`graphrefly:graph:${t}`)}function ht(t){return Symbol.for(`graphrefly:node:${t}`)}var jn=new Map,Bn=new Map,Vn=new Map,Kn=new Map,qn=new Map,zn=new Map,Hn=new Map;function Ou(t){return t==="request"?(0,Fr.Inject)(un):(0,Fr.Inject)(t?ut(t):mt)}function Au(t){return(0,Fr.Inject)(ut(t))}function Cu(t){return(0,Fr.Inject)(ht(t))}function Lu(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=jn.get(o)??[];s.push({nodeName:t,methodKey:r}),jn.set(o,s)})}}function Iu(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=Bn.get(o)??[];s.push({ms:t,methodKey:r}),Bn.set(o,s)})}}function Pu(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=Vn.get(o)??[];s.push({expr:t,methodKey:r}),Vn.set(o,s)})}}function Du(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=Kn.get(s)??[];i.push({cqrsName:t,commandName:e,methodKey:o}),Kn.set(s,i)})}}function Gu(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=qn.get(s)??[];i.push({cqrsName:t,eventName:e,methodKey:o}),qn.set(s,i)})}}function Fu(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=zn.get(s)??[];i.push({cqrsName:t,projectionName:e,methodKey:o}),zn.set(s,i)})}}function $u(t,e,n){return(r,o)=>{let s=o.name;o.addInitializer(function(){let i=this.constructor,a=Hn.get(i)??[];a.push({cqrsName:t,eventNames:n,sagaName:e,methodKey:s}),Hn.set(i,a)})}}ae();ve();var oc=0,mn=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 jn){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 d of a)d[0]===M&&o(d[1])});this.disposers.push(i)}wireIntervals(){for(let[e,n]of Bn){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)}.${oc++}`,d=Ze(r.ms,{period:r.ms,name:a});this.graph.add(d),this.scheduleNodeNames.push(a);let c=this.observeNode(a).subscribe(l=>{for(let p of l)p[0]===M&&s(p[1])});this.disposers.push(c)}wireCrons(){for(let[e,n]of Vn){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)}.${oc++}`,d=os(r.expr,{name:a});this.graph.add(d),this.scheduleNodeNames.push(a);let c=this.observeNode(a).subscribe(l=>{for(let p of l)p[0]===M&&s(p[1])});this.disposers.push(c)}wireCqrsCommands(){for(let[e,n]of Kn){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 qn){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,d=a&&a.length>0?a[a.length-1].seq:0,c=this.observeNodeOn(s,n.eventName).subscribe(l=>{for(let p of l)if(p[0]===M){let f=p[1];for(let m of f)m.seq>d&&(o(m),d=m.seq)}});this.disposers.push(c)}wireCqrsQueries(){for(let[e,n]of zn){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(d=>{for(let u of d)u[0]===M&&o(u[1])});this.disposers.push(a)}wireCqrsSagas(){for(let[e,n]of Hn){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(ut(e),{strict:!1})}catch{return console.warn(`[GraphReFly] CqrsGraph "${e}" not found in DI \u2014 did you import GraphReflyModule.forCqrs({ name: "${e}" })?`),null}}resolveInstance(e){try{return this.moduleRef.get(e,{strict:!1})}catch{return null}}};ae();ae();var Dm=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-${++Dm}`),r=0,o=!1;return{onEnqueue(){return r+=1,!o&&r>=e.highWaterMark?(o=!0,t([[Ve,n]]),!0):!1},onDequeue(){return r>0&&(r-=1),o&&r<=e.lowWaterMark?(o=!1,t([[ze,n]]),!0):!1},get pending(){return r},get paused(){return o},dispose(){o&&(o=!1,t([[ze,n]]))}}}function sc(t,e,n){let{actor:r,serialize:o=Gm,keepAliveMs:s,signal:i}=n??{},a=new TextEncoder,d,u=n?.highWaterMark!=null,c,l,p=[],f=!1;return new ReadableStream({start(m){let h,g=()=>{},y=()=>{if(!f){f=!0,h!==void 0&&clearInterval(h),i?.removeEventListener("abort",b),g(),c?.dispose(),l?.(),l=void 0;for(let T of p)m.enqueue(T.frame);p.length=0,m.close()}};d=y;let b=()=>y(),v=t.observe(e,{actor:r});u&&(c=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(f)return;let x=w[0];if(x===M){let k=a.encode(ka("data",o(w[1])));u?(p.push({frame:k,counted:!0}),c.onEnqueue(),l?.(),l=void 0):m.enqueue(k)}else if(x===I){let k=a.encode(ka("error",o(w[1])));u?(p.push({frame:k,counted:!1}),l?.(),l=void 0):m.enqueue(k),y();return}else if(x===P||x===le){if(x===P){let k=a.encode(ka("complete"));u?(p.push({frame:k,counted:!1}),l?.(),l=void 0):m.enqueue(k)}y();return}}}),s!==void 0&&s>0&&(h=setInterval(()=>{f||(u?(p.push({frame:a.encode(`: keepalive
|
|
2
2
|
|
|
3
3
|
`),counted:!1}),l?.(),l=void 0):m.enqueue(a.encode(`: keepalive
|
|
4
4
|
|
|
5
|
-
`)))},s)),i?.aborted?b():i?.addEventListener("abort",b,{once:!0})},pull(m){if(
|
|
5
|
+
`)))},s)),i?.aborted?b():i?.addEventListener("abort",b,{once:!0})},pull(m){if(u&&!f){if(p.length>0){let h=p.shift();m.enqueue(h.frame),h.counted&&c.onDequeue();return}return new Promise(h=>{l=h})}},cancel(){try{d?.()}catch{}}})}function ic(t,e,n){let{actor:r,filter:o}=n??{},s=[],i=[],a=!1,d=t.observe(e,{actor:r}),u=n?.highWaterMark!=null?Zn(m=>d.up(m),{highWaterMark:n.highWaterMark,lowWaterMark:n.lowWaterMark??Math.floor(n.highWaterMark/2)}):void 0,c=()=>{a||(a=!0,u?.dispose(),p())},l=m=>{if(!a)if(i.length>0){let h=i.shift();m.done&&m.error?h.reject(m.error):m.done?h.resolve({done:!0,value:void 0}):h.resolve({done:!1,value:m.value})}else s.push(m),m.done||u?.onEnqueue()},p=d.subscribe(m=>{for(let h of m){let g=h[0];if(g===M){let y=h[1];if(o&&!o(y))continue;l({done:!1,value:y})}else if(g===I){let y=h[1]instanceof Error?h[1]:new Error(String(h[1]));l({done:!0,error:y}),c();return}else if(g===P||g===le){l({done:!0}),c();return}}});return{next(){if(s.length>0){let m=s.shift();return m.done||u?.onDequeue(),m.done&&m.error?Promise.reject(m.error):Promise.resolve(m.done?{done:!0,value:void 0}:{done:!1,value:m.value})}return a?Promise.resolve({done:!0,value:void 0}):new Promise((m,h)=>{i.push({resolve:m,reject:h})})},return(){c();for(let m of i)m.resolve({done:!0,value:void 0});return i.length=0,Promise.resolve({done:!0,value:void 0})},throw(m){return c(),Promise.reject(m)},[Symbol.asyncIterator](){return this}}}var us=class{constructor(e,n){this.graph=e;this.extractActor=n?.extractActor??(()=>{}),this.parse=n?.parse??Fm,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??$m.bind(null,e),s;try{s=typeof n=="string"?this.parse(n):n}catch{o({type:"err",message:"invalid command"});return}s.type==="subscribe"?this.subscribe(e,s.path,o):s.type==="unsubscribe"?this.unsubscribe(e,s.path,o):s.type==="ack"?this.ack(e,s.path,s.count??1):o({type:"err",message:`unknown command type: ${s.type}`})}subscriptionCount(e){return this.clients.get(e)?.size??0}destroy(){for(let[e]of this.clients)this.handleDisconnect(e)}subscribe(e,n,r){let o=this.clients.get(e);if(o||(o=new Map,this.clients.set(e,o)),o.has(n)){r({type:"subscribed",path:n});return}let s=this.extractActor(e),i;try{i=this.graph.observe(n,{actor:s})}catch(c){let l=c instanceof Error?c.message:String(c);r({type:"err",message:l});return}let a=this.highWaterMark!=null?Zn(c=>i.up(c),{highWaterMark:this.highWaterMark,lowWaterMark:this.lowWaterMark??Math.floor(this.highWaterMark/2)}):void 0,d=()=>{a?.dispose(),u(),o.delete(n)},u=i.subscribe(c=>{for(let l of c){let p=l[0];if(p===M)a?.onEnqueue(),xa(r,{type:"data",path:n,value:l[1]});else if(p===I){let f=l[1]instanceof Error?l[1].message:String(l[1]);xa(r,{type:"error",path:n,error:f}),d();return}else if(p===P||p===le){xa(r,{type:"complete",path:n}),d();return}}});o.set(n,{unsub:u,wm:a}),r({type:"subscribed",path:n})}unsubscribe(e,n,r){let o=this.clients.get(e),s=o?.get(n);s&&(s.wm?.dispose(),s.unsub(),o.delete(n)),r({type:"unsubscribed",path:n})}ack(e,n,r){let o=this.clients.get(e)?.get(n);if(!o?.wm)return;let s=Math.min(Math.max(0,Math.floor(r)),1024);for(let i=0;i<s;i++)o.wm.onDequeue()}};function Gm(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)}catch{return String(t)}}function ka(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
|
|
10
|
-
`)}function km(t,e,n,r,o){let{x:s,y:i,w:a,h:u}=r;if(a<2||u<2){u>0&&Xd(t,e,s,i,a,o);return}Ht(t,e,s,i,n.boxTL);for(let c=s+1;c<s+a-1;c+=1)Ht(t,e,c,i,n.boxH);Ht(t,e,s+a-1,i,n.boxTR);for(let c=i+1;c<i+u-1;c+=1){Ht(t,e,s,c,n.boxV);for(let l=s+1;l<s+a-1;l+=1)nc(t,e,l,c," ","empty");Ht(t,e,s+a-1,c,n.boxV)}Ht(t,e,s,i+u-1,n.boxBL);for(let c=s+1;c<s+a-1;c+=1)Ht(t,e,c,i+u-1,n.boxH);Ht(t,e,s+a-1,i+u-1,n.boxBR);let d=i+Math.floor(u/2);Xd(t,e,s+1,d,a-2,o)}function Ht(t,e,n,r,o){nc(t,e,n,r,o,o===" "?"empty":o==="\u2500"||o==="-"?"boxH":o==="\u2502"||o==="|"?"boxV":"boxCorner")}function nc(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];n<0||n>=i.length||(i[n]=o,e[r][n]=s)}function Xd(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=n,a=o;for(let u of s){let d=Jn(u);if(d!==0){if(a<d)break;i>=0&&i<t[r].length&&(t[r][i]=u,e[r][i]="label",d===2&&i+1<t[r].length&&(t[r][i+1]="",e[r][i+1]="label")),i+=d,a-=d}}for(;a>0;)i>=0&&i<t[r].length&&(t[r][i]=" ",e[r][i]="empty"),i+=1,a-=1}function xm(t,e,n,r){let o=r.points;if(o.length<2)return;for(let u=0;u+1<o.length;u+=1)Rm(t,e,n,o[u],o[u+1]);for(let u=1;u+1<o.length;u+=1){let d=o[u-1],c=o[u],l=o[u+1],p=Sm(d,c,l,n);p&&ec(t,e,c.x,c.y,p,"edgeCorner")}let s=o[o.length-1],i=o[o.length-2],a=Em(i,s,n);a&&ec(t,e,s.x,s.y,a,"arrow")}function Rm(t,e,n,r,o){if(!(r.x===o.x&&r.y===o.y)){if(r.y===o.y){let s=r.y,i=Math.min(r.x,o.x),a=Math.max(r.x,o.x);for(let u=i;u<=a;u+=1)Zd(t,e,u,s,n,"h")}else if(r.x===o.x){let s=r.x,i=Math.min(r.y,o.y),a=Math.max(r.y,o.y);for(let u=i;u<=a;u+=1)Zd(t,e,s,u,n,"v")}}}function Zd(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];if(!(a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label")){if(a==="empty"){i[n]=s==="h"?o.horizontal:o.vertical,e[r][n]=s==="h"?"edgeH":"edgeV";return}if(a==="edgeH"&&s==="v"){i[n]=o.cross,e[r][n]="edgeCorner";return}if(a==="edgeV"&&s==="h"){i[n]=o.cross,e[r][n]="edgeCorner";return}}}function ec(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label"||(i[n]=o,e[r][n]=s)}function Sm(t,e,n,r){let o=t.y===e.y,s=e.y===n.y;if(o===s)return;if(o){let u=t.x<e.x,d=n.y>e.y;return u&&d?r.cornerTR:u&&!d?r.cornerBR:!u&&d?r.cornerTL:r.cornerBL}let i=t.y<e.y,a=n.x>e.x;return i&&a?r.cornerBL:i&&!a?r.cornerBR:!i&&a?r.cornerTL:r.cornerTR}function Em(t,e,n){if(e.x>t.x)return n.arrowRight;if(e.x<t.x)return n.arrowLeft;if(e.y>t.y)return n.arrowDown;if(e.y<t.y)return n.arrowUp}function Nm(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}function sc(t){let e=_m(t);Mm(e),Om(e),Cm(e),Am(e,t);let n=Pm(e,t),{width:r,height:o}=Gm(e),s=[];for(let i of e.layers)for(let a of i)a.isVirtual||s.push({id:a.id,layer:a.layer,order:a.order,x:a.x,y:a.y,w:a.w,h:a.h});return{boxes:s,edges:n,width:r,height:o}}function _m(t){let e=new Map;for(let o of t.nodes)e.set(o,{id:o,isVirtual:!1,layer:-1,order:0,x:0,y:0,w:t.widthCells(o),h:t.heightCells(o),in:[],out:[]});let n=[],r=0;for(let o of t.edges){if(o.from===o.to)continue;let s=e.get(o.from),i=e.get(o.to);if(!s||!i)continue;let a={chainId:r++,chainFrom:o.from,chainTo:o.to,fromId:o.from,toId:o.to,hopIndex:0,chainLen:1};s.out.push(a),i.in.push(a),n.push(a)}return{nodes:e,layers:[],hops:n}}function Mm(t){let e=new Map;for(let s of t.nodes.values())e.set(s.id,s.in.length);let n=[];for(let s of t.nodes.values())(e.get(s.id)??0)===0&&(s.layer=0,n.push(s));let r=new Set,o=0;for(;o<n.length;){let s=n[o++];if(!r.has(s.id)){r.add(s.id);for(let i of s.out){let a=t.nodes.get(i.toId);a.layer=Math.max(a.layer,s.layer+1);let u=(e.get(a.id)??0)-1;e.set(a.id,u),u<=0&&n.push(a)}}}for(let s of t.nodes.values())s.layer<0&&(s.layer=0)}function Om(t){let e=Math.max(0,...Array.from(t.nodes.values(),s=>s.layer)),n=Array.from({length:e+1},()=>[]);for(let s of t.nodes.values())n[s.layer].push(s);let r=[],o=0;for(let s of t.hops){let i=t.nodes.get(s.fromId),a=t.nodes.get(s.toId),u=a.layer-i.layer;if(u<=0){i.out=i.out.filter(l=>l!==s),a.in=a.in.filter(l=>l!==s);continue}if(u===1){s.hopIndex=0,s.chainLen=1,r.push(s);continue}i.out=i.out.filter(l=>l!==s),a.in=a.in.filter(l=>l!==s);let d=i;for(let l=1;l<u;l+=1){let p=`__virt_${o++}__`,f={id:p,isVirtual:!0,layer:i.layer+l,order:0,x:0,y:0,w:0,h:1,in:[],out:[]};t.nodes.set(p,f),n[f.layer].push(f);let m={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:d.id,toId:p,hopIndex:l-1,chainLen:u};d.out.push(m),f.in.push(m),r.push(m),d=f}let c={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:d.id,toId:a.id,hopIndex:u-1,chainLen:u};d.out.push(c),a.in.push(c),r.push(c)}for(let s of n)for(let i=0;i<s.length;i+=1)s[i].order=i;t.layers=n,t.hops=r}function Cm(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)rc(t,t.layers[r],"in"),os(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)rc(t,t.layers[r],"out"),os(t.layers[r])}for(let n=0;n<2;n+=1){let r=!1;for(let o=1;o<t.layers.length;o+=1){let s=t.layers[o];for(let i=0;i+1<s.length;i+=1){let a=oc(t,s[i],s[i+1],"in");[s[i],s[i+1]]=[s[i+1],s[i]],os(s),oc(t,s[i],s[i+1],"in")<a?r=!0:([s[i],s[i+1]]=[s[i+1],s[i]],os(s))}}if(!r)break}}function rc(t,e,n){let r=new Map;for(let o of e){let s=n==="in"?o.in:o.out;if(s.length===0){r.set(o.id,o.order);continue}let i=0,a=0;for(let u of s){let d=t.nodes.get(n==="in"?u.fromId:u.toId);d&&(i+=d.order,a+=1)}r.set(o.id,a===0?o.order:i/a)}e.sort((o,s)=>{let i=r.get(o.id),a=r.get(s.id);return i!==a?i-a:o.order-s.order})}function os(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function oc(t,e,n,r){let o=r==="in"?e.in:e.out,s=r==="in"?n.in:n.out,i=0;for(let a of o)for(let u of s){let d=t.nodes.get(r==="in"?a.fromId:a.toId)?.order??0,c=t.nodes.get(r==="in"?u.fromId:u.toId)?.order??0;(e.order<n.order&&d>c||e.order>n.order&&d<c)&&(i+=1)}return i}function Am(t,e){e.direction==="LR"?Lm(t,e):Im(t,e)}function Lm(t,e){let n=[],r=0;for(let o=0;o<t.layers.length;o+=1){n.push(r);let s=0;for(let i of t.layers[o])s=Math.max(s,i.w);r+=s+e.layerGap}for(let o=0;o<t.layers.length;o+=1)for(let s of t.layers[o])s.x=n[o];for(let o of t.layers){let s=0;for(let i of o)i.y=s,s+=i.h+e.nodeGap}ic(t,e,"y")}function Im(t,e){let n=[],r=0;for(let o=0;o<t.layers.length;o+=1){n.push(r);let s=0;for(let i of t.layers[o])s=Math.max(s,i.h);r+=s+e.layerGap}for(let o=0;o<t.layers.length;o+=1)for(let s of t.layers[o])s.y=n[o];for(let o of t.layers){let s=0;for(let i of o)i.x=s,s+=i.w+e.nodeGap}ic(t,e,"x")}function ic(t,e,n){let r=s=>n==="y"?s.h:s.w,o=e.nodeGap;for(let s=0;s<2;s+=1){let i=s===0?t.layers.slice(1):t.layers.slice(0,-1).reverse();for(let a of i){let u=new Map;for(let c of a){let l=s===0?c.in:c.out;if(l.length===0)continue;let p=[];for(let m of l){let h=t.nodes.get(s===0?m.fromId:m.toId);if(!h)continue;let g=n==="y"?h.y:h.x;p.push(g+Math.floor(r(h)/2))}if(p.length===0)continue;p.sort((m,h)=>m-h);let f=p[Math.floor(p.length/2)];u.set(c.id,f-Math.floor(r(c)/2))}let d=0;for(let c of a){let l=u.get(c.id),p=n==="y"?c.y:c.x,m=Math.max(l??p,d);n==="y"?c.y=m:c.x=m,d=m+r(c)+o}}}}function Pm(t,e){let n=new Map;for(let d of t.hops){let c=n.get(d.chainId);c?c.push(d):n.set(d.chainId,[d])}for(let d of n.values())d.sort((c,l)=>c.hopIndex-l.hopIndex);let r=e.direction==="LR",o=d=>r?d.x:d.y,s=d=>r?d.w:d.h,i=d=>r?d.y+Math.floor(d.h/2):d.x+Math.floor(d.w/2),a=new Map;for(let d=0;d+1<t.layers.length;d+=1){let c=t.layers[d],l=t.layers[d+1],p=0;for(let S of c)p=Math.max(p,o(S)+s(S));let f=Number.POSITIVE_INFINITY;for(let S of l)f=Math.min(f,o(S));let m=Number.isFinite(f)?f-1:p,h=Math.max(1,m-p+1),g=[];for(let S of c)for(let R of S.out)g.push(R);g.sort((S,R)=>{let N=i(t.nodes.get(S.fromId)),_=i(t.nodes.get(R.fromId));if(N!==_)return N-_;let I=i(t.nodes.get(S.toId)),O=i(t.nodes.get(R.toId));return I-O});let y=[],b=new Map;for(let S of g){let R=i(t.nodes.get(S.fromId)),N=i(t.nodes.get(S.toId)),_=Math.min(R,N),I=Math.max(R,N),O=-1;for(let P=0;P<y.length;P+=1){let B=y[P],j=!0;for(let D of B)if(D.lo<=I&&_<=D.hi){j=!1;break}if(j){B.push({lo:_,hi:I}),O=P;break}}O<0&&(y.push([{lo:_,hi:I}]),O=y.length-1),b.set(S,O)}let v=y.length,T=h>=Math.max(3,v+2),w=T?p+1:p,x=T?m-1:m,k=Math.max(1,x-w+1);for(let S of g){let R=b.get(S),N;if(v<=1)N=w+Math.floor(k/2);else{let _=(k-1)/(v-1);N=w+Math.floor(R*_)}a.set(S,Math.max(p,Math.min(m,N)))}}let u=[];for(let[,d]of n){let c=[];for(let p=0;p<d.length;p+=1){let f=d[p],m=t.nodes.get(f.fromId),h=t.nodes.get(f.toId),g=a.get(f),y=m.isVirtual?o(m):o(m)+s(m),b=h.isVirtual?o(h):o(h)-1,v=i(m),T=i(h);p===0&&ss(c,r,y,v),v!==T&&(ss(c,r,g,v),ss(c,r,g,T)),ss(c,r,b,T)}let l=d[0];u.push({from:l.chainFrom,to:l.chainTo,points:Dm(c)})}return u}function ss(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function Dm(t){let e=[];for(let n of t){let r=e[e.length-1];(!r||r.x!==n.x||r.y!==n.y)&&e.push(n)}return e}function Gm(t){let e=0,n=0;for(let r of t.layers)for(let o of r)e=Math.max(e,o.x+o.w),n=Math.max(n,o.y+o.h);return{width:e,height:n}}var Fm=24,$m=4,jm=1,Bm=3;function ac(t,e){let n=Vm(e.direction),r=Math.max(3,e.maxLabelWidth??Fm),o=e.asciiCharset??"unicode",s=Object.keys(t.nodes).sort(),i=new Set(s),a=t.edges.filter(f=>i.has(f.from)&&i.has(f.to)),u=new Map,d=new Map;for(let f of s){let m=Qd(f,r);u.set(f,m),d.set(f,Jn(m)+4)}let c=sc({nodes:s,edges:a,widthCells:f=>d.get(f)??3,heightCells:()=>Bm,layerGap:$m,nodeGap:jm,direction:n}),l=tc(c,{charset:o,labelOf:f=>u.get(f)??f}),p=e.logger;return p&&p(l),l}function Vm(t){if(t===void 0||t==="LR")return"LR";if(t==="TD")return"TD";throw new Error(`ascii describe supports direction "LR" or "TD" only; got ${String(t)}`)}function Gr(t,e,n,r={}){let o=e in t.nodes,s=n in t.nodes;if(!o)return is(e,n,"no-such-from");if(!s)return is(e,n,"no-such-to");let i=r.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===n){if(r.findCycle===!0){let d=Km(t,e,r);if(d!=null)return d}let u=as(e,t.nodes[e],0,r);return us(e,n,[u])}if(i===0)return is(e,n,"no-path");let a=uc(t,e,n,i);return a.found?us(e,n,dc(t,a.pathOrder,r)):is(e,n,a.truncated?"max-depth-exceeded":"no-path")}function uc(t,e,n,r){let o=new Map,s=[{path:n,depth:0}],i=new Set([n]),a=0,u=!1;for(;a<s.length;){let l=s[a++];if(l.path===e)break;if(r!=null&&l.depth>=r){let h=t.nodes[l.path];h?.deps&&h.deps.length>0&&(u=!0);continue}let p=t.nodes[l.path];if(p==null)continue;let f=p.deps??[],m=new Map;for(let h=0;h<f.length;h++){let g=f[h];if(!g)continue;let y=m.get(g);y==null&&(y=[],m.set(g,y)),y.push(h)}for(let[h,g]of m)i.has(h)||(i.add(h),o.set(h,{from:l.path,depIndices:g}),s.push({path:h,depth:l.depth+1}))}if(!o.has(e))return{found:!1,pathOrder:[],truncated:u};let d=[{path:e}],c=e;for(;c!==n;){let l=o.get(c);if(l==null)return{found:!1,pathOrder:[],truncated:!1};d[d.length-1].depIndices=l.depIndices,d.push({path:l.from}),c=l.from}return{found:!0,pathOrder:d,truncated:!1}}function Km(t,e,n){let r=t.nodes[e];if(r==null)return null;let o=r.deps??[],s=[];for(let a=0;a<o.length;a++)o[a]===e&&s.push(a);if(s.length>0){let a=as(e,r,0,n);a.dep_index=s[0];let u=as(e,r,1,n);return us(e,e,[a,u])}let i=null;for(let a=0;a<o.length;a++){let u=o[a];if(!u||u===e)continue;let d=uc(t,u,e,n.maxDepth);d.found&&(i==null||d.pathOrder.length<i.pathOrder.length)&&(i=d,i={found:!0,pathOrder:[{path:e,depIndices:[a]},...d.pathOrder],truncated:!1})}return i==null?null:us(e,e,dc(t,i.pathOrder,n))}function dc(t,e,n){return e.map((r,o)=>{let s=t.nodes[r.path],i=as(r.path,s,o,n);return r.depIndices!=null&&r.depIndices.length>0&&(i.dep_index=r.depIndices[0],r.depIndices.length>1&&(i.dep_indices=[...r.depIndices])),i})}function as(t,e,n,r){let o={path:t,type:e.type,hop:n};e.status!==void 0&&(o.status=e.status),"value"in e&&(o.value=e.value),e.v!=null&&(o.v=e.v);let s=r.annotations?.get(t)??e.annotation;s!=null&&(o.annotation=s);let i=r.lastMutations?.get(t)??e.lastMutation;return i!=null&&(o.lastMutation=i),o}function us(t,e,n){return cc(t,e,!0,"ok",n)}function is(t,e,n){return cc(t,e,!1,n,[])}function cc(t,e,n,r,o){let s=qm(t,e,n,r,o);return{from:t,to:e,found:n,reason:r,steps:o,text:s,toJSON(){return{from:t,to:e,found:n,reason:r,steps:o}}}}function qm(t,e,n,r,o){if(!n)switch(r){case"no-such-from":return`explainPath: no node named "${t}"`;case"no-such-to":return`explainPath: no node named "${e}"`;case"max-depth-exceeded":return`explainPath: no path from "${t}" to "${e}" within maxDepth`;default:return`explainPath: no path from "${t}" to "${e}"`}let s=[`Causal path: ${t} \u2192 ${e} (${o.length} step(s))`];for(let i of o){let u=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(s.push(u),"value"in i&&s.push(` value: ${Hm(i.value)}`),i.annotation!=null&&s.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let d=i.lastMutation.actor;s.push(` actor: ${d.type}${d.id?`:${d.id}`:""}`)}}return s.join(`
|
|
11
|
-
`)}function
|
|
12
|
-
`)}function
|
|
13
|
-
`);return e.logger?.(s),s}function
|
|
14
|
-
`)}function
|
|
15
|
-
`)}function rg(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function cs(t){let e="^";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="*"){e+=".*";continue}if(r==="?"){e+=".";continue}if(r==="["){let o=t.indexOf("]",n+1);if(o<=n+1){e+="\\[";continue}let s=t.slice(n+1,o);s.startsWith("!")&&(s=`^${s.slice(1)}`),s=s.replace(/\\/g,"\\\\"),e+=`[${s}]`,n=o;continue}e+=rg(r)}return e+="$",new RegExp(e)}var og={data:"\x1B[32m",dirty:"\x1B[33m",resolved:"\x1B[36m",invalidate:"\x1B[93m",pause:"\x1B[90m",resume:"\x1B[96m",complete:"\x1B[34m",error:"\x1B[31m",teardown:"\x1B[91m",derived:"\x1B[35m",path:"\x1B[90m",reset:"\x1B[0m"},sg={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function ls(t){if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||t==null)return String(t);try{return JSON.stringify(t)}catch{return"[unserializable]"}}function ig(t){return t==="none"?sg:t==="ansi"||t==null?og:{data:t.data??"",dirty:t.dirty??"",resolved:t.resolved??"",invalidate:t.invalidate??"",pause:t.pause??"",resume:t.resume??"",complete:t.complete??"",error:t.error??"",teardown:t.teardown??"",derived:t.derived??"",path:t.path??"",reset:t.reset??""}}function fc(t){if(t==null)return{};let e=t.detail;return e==="full"?{...t,structured:t.structured??!0,timeline:t.timeline??!0,causal:t.causal??!0,derived:t.derived??!0}:e==="minimal"?{...t,structured:t.structured??!0}:t.format==="stage-log"?{...t,structured:t.structured??!0,timeline:t.timeline??!0}:t}function ag(t,e,n){for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);if(o<32||o===127)throw new Error(`Graph "${e}": ${n} "${t}" must not contain control character (U+${o.toString(16).padStart(4,"0").toUpperCase()} at index ${r})`)}}function ya(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(De))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${De}' (path separator)`);if(t===Qe)throw new Error(`Graph "${e}": ${n} name "${Qe}" is reserved for meta companion paths`);ag(t,e,n)}function ug(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(De);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function dg(t,e){let n=!1;for(let o of t)if(!e.isMetaPassthrough(o[0])){n=!0;break}return n?t.filter(o=>e.isMetaPassthrough(o[0])):t}function yc(t){for(let e of t._mounts.values())yc(e);for(let e of t._nodes.values())try{e.down([[le]],{internal:!0})}catch{}}var Y=class t{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_destroyed=!1;_topology;_topologyEmitters=new Set;constructor(e,n){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(De))throw new Error(`Graph name must not contain '${De}' (got "${e}")`);if(e===Qe)throw new Error(`Graph name "${Qe}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??$e,this._traceRing=new ln(n?.traceCapacity??1e3),n?.versioning!=null&&this.setVersioning(n.versioning)}ancestors(e=!0){let n=[],r=e?this:this._parent;for(;r!=null;)n.push(r),r=r._parent;return n}get topology(){return this._topology==null&&(this._topology=K(e=>{let n=r=>{e.emit(r)};return this._topologyEmitters.add(n),()=>{this._topologyEmitters.delete(n)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let n of this._topologyEmitters)n(e)}nameOf(e){return this._nodeToName.get(e)}add(e,n){let r=e.name,o=n?.name??r;if(o==null||o==="")throw new Error(`Graph "${this.name}": graph.add requires a non-empty name \u2014 pass via opts.name or set it on the node (e.g. state(0, { name: "x" }))`);let s=o,i=n?.annotation;if(ya(s,this.name,"add"),this._mounts.has(s))throw new Error(`Graph "${this.name}": name "${s}" is already a mount point`);if(this._nodes.has(s))throw new Error(`Graph "${this.name}": node "${s}" already exists`);let a=this._nodeToName.get(e);if(a!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${a}"`);return this._nodes.set(s,e),this._nodeToName.set(e,s),this._emitTopology({kind:"added",name:s,nodeKind:"node"}),i!=null&&(this._annotations.set(s,i),this.config.inspectorEnabled&&this._traceRing.push({path:s,annotation:i,timestamp_ns:H()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof Ae&&n._applyVersioning(e)}remove(e){ya(e,this.name,"remove");let n=this._mounts.get(e);if(n){let s={kind:"mount",nodes:[],mounts:[]},i=[];n._collectObserveTargets("",i);for(let[a,u]of i)a.includes(`${De}${Qe}${De}`)||s.nodes.push(a);return s.nodes.sort(),s.mounts.push(e),s.mounts.push(...n._collectSubgraphs(`${e}${De}`)),this._mounts.delete(e),n._parent=void 0,yc(n),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:s}),s}let r=this._nodes.get(e);if(!r)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(r),r.down([[le]],{internal:!0});let o={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:o}),o}removeAll(e){let n=typeof e=="function"?e:(()=>{let s=cs(e);return i=>s.test(i)})(),r={kind:"mount",nodes:[],mounts:[]},o=[...this._nodes.keys(),...this._mounts.keys()].filter(s=>n(s));for(let s of o){let i=this.remove(s);r.nodes.push(...i.nodes),r.mounts.push(...i.mounts)}return r.nodes.sort(),r.mounts.sort(),r}[Symbol.iterator](){let e=[...this._nodes.keys()].sort(),n=this._nodes,r=0;return{[Symbol.iterator](){return this},next(){if(r>=e.length)return{value:void 0,done:!0};let o=e[r++];return{value:[o,n.get(o)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(De))return this.resolve(e);let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return n}get(e){return this.node(e).cache}set(e,n,r){let o=r?.internal===!0;this.node(e).down([[E,n]],{actor:r?.actor,internal:o,delivery:"write"})}setAll(e,n){let r=Symbol.iterator in e?e:Object.entries(e);X(()=>{for(let[o,s]of r)this.set(o,s,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[Je]],{actor:n?.actor,internal:r,delivery:"write"})}error(e,n,r){let o=r?.internal===!0;this.node(e).down([[C,n]],{actor:r?.actor,internal:o,delivery:"write"})}complete(e,n){let r=n?.internal===!0;this.node(e).down([[L]],{actor:n?.actor,internal:r,delivery:"write"})}edges(e){let n=e?.recursive===!0,r=new Map;if(!n){for(let[u,d]of this._nodes)r.set(d,u);let a=[];for(let[u,d]of this._nodes)if(d instanceof Ae)for(let c of d._deps){let l=r.get(c.node);l!=null&&a.push([l,u])}return a.sort((u,d)=>u[0]<d[0]?-1:u[0]>d[0]?1:u[1]<d[1]?-1:u[1]>d[1]?1:0),a}let o=[];this._collectObserveTargets("",o);let s=new Map;for(let[a,u]of o)s.set(u,a);let i=[];for(let[a,u]of o)if(u instanceof Ae)for(let d of u._deps){let c=s.get(d.node);c!=null&&i.push([c,a])}return i.sort((a,u)=>a[0]<u[0]?-1:a[0]>u[0]?1:a[1]<u[1]?-1:a[1]>u[1]?1:0),i}mount(e,n){if(n===void 0){let o=new t(e);return this.mount(e,o)}if(typeof n=="function"){let o=new t(e);return n(o),this.mount(e,o)}let r=n;if(ya(e,this.name,"mount"),this._nodes.has(e))throw new Error(`Graph "${this.name}": cannot mount at "${e}" \u2014 node with that name exists`);if(this._mounts.has(e))throw new Error(`Graph "${this.name}": mount "${e}" already exists`);if(r===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(r._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${r._parent.name}"`);for(let o=this;o!=null;o=o._parent)if(o===r)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,r),r._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),r}resolve(e){let n=ug(e,this.name);return this._resolveFromSegments(n)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let n=e;if(n[0]===this.name&&(n=n.slice(1),n.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let r=n[0],o=n.slice(1);if(o.length===0){let a=this._nodes.get(r);if(a)return a;throw this._mounts.has(r)?new Error(`Graph "${this.name}": path ends at subgraph "${r}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${r}"`)}let s=this._nodes.get(r);if(s&&o.length>0&&o[0]===Qe)return this._resolveMetaChainFromNode(s,o,n.join(De));let i=this._mounts.get(r);if(!i)throw this._nodes.has(r)?new Error(`Graph "${this.name}": "${r}" is a node; trailing path "${o.join(De)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(o.join(De))}_resolveMetaChainFromNode(e,n,r){let o=e,s=0,i=[...n];for(;s<i.length;){if(i[s]!==Qe)throw new Error(`Graph "${this.name}": expected ${Qe} segment in meta path "${r}"`);if(s+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${Qe} in "${r}"`);let a=i[s+1],u=o.meta[a];if(!u)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${r}"`);o=u,s+=2}return o}signal(e,n){if(n?.internal!==!0){for(let o of e)if(this.config.messageTier(o[0])===3)throw new Error(`Graph "${this.name}": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). For per-node value writes, use Graph.set or graph.node(name).down(...).`)}let r=[];if(this._signalDeliver(e,n??{},new Set,r),r.length>0)throw r[0]}_signalDeliver(e,n,r,o){for(let u of this._mounts.values())u._signalDeliver(e,n,r,o);let i=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},a=dg(e,this.config);for(let u of[...this._nodes.keys()].sort()){let d=this._nodes.get(u);if(!r.has(d)){r.add(d);try{d.down(e,i)}catch(c){if(c instanceof rt)throw c;o.push(c)}a.length!==0&&this._signalMetaSubtree(d,a,r,i,o)}}}_signalMetaSubtree(e,n,r,o,s){for(let i of Object.keys(e.meta).sort()){let a=e.meta[i];if(!r.has(a)){r.add(a);try{a.down(n,o)}catch(u){if(u instanceof rt)throw u;s.push(u)}this._signalMetaSubtree(a,n,r,o,s)}}}describe(e){if(e?.reactive===!0)return this._describeReactive(e);let n=e?.actor,r=e?.filter,o=Ct(e?.detail,e?.fields),s=e?.format==="spec",i=s?Ct("minimal"):o,a=[];this._collectObserveTargets("",a);let u=new Map;for(let[x,k]of a)u.set(k,x);let d=[];{let x=a.map(([,R])=>R),k=new Set(u.values()),S=0;for(;x.length>0;){let R=x.shift();if(R instanceof Ae)for(let N of R._deps){let _=N.node;if(u.has(_))continue;let I=_.name??"",O=I;if(!O||k.has(O))if(I){let P=2;for(;k.has(`${I}#${P}`);)P++;O=`${I}#${P}`}else for(O=`__internal__/${S++}`;k.has(O);)O=`__internal__/${S++}`;u.set(_,O),k.add(O),d.push([O,_]),x.push(_)}}}let c=[...a,...d],l={};for(let[x,k]of c){if(n!=null&&!k.allowsObserve(n))continue;let S=Dr(k,i),R=k instanceof Ae?k._deps.map(O=>u.get(O.node)??O.node.name??""):[],{name:N,..._}=S,I={..._,deps:R};if(!s){let O=this._annotations.get(x);O!=null&&(I.annotation=O)}if(r!=null)if(typeof r=="function"){let O=r;if(!(O.length>=2?O(x,I):O(I)))continue}else{let O=!0;for(let[P,B]of Object.entries(r)){let j=P==="deps_includes"?"depsIncludes":P==="meta_has"?"metaHas":P;if(j==="depsIncludes"){if(!I.deps.includes(String(B))){O=!1;break}continue}if(j==="metaHas"){if(!Object.hasOwn(I.meta??{},String(B))){O=!1;break}continue}if(I[j]!==B){O=!1;break}}if(!O)continue}l[x]=I}let p=new Set(Object.keys(l)),f=[];for(let[x,k]of c)if(k instanceof Ae)for(let S of k._deps){let R=u.get(S.node);R!=null&&f.push([R,x])}f.sort((x,k)=>x[0]<k[0]?-1:x[0]>k[0]?1:x[1]<k[1]?-1:x[1]>k[1]?1:0);let m=f.map(([x,k])=>({from:x,to:k}));(n!=null||r!=null)&&(m=m.filter(x=>p.has(x.from)&&p.has(x.to)));let h=this._collectSubgraphs(""),g=n!=null||r!=null?h.filter(x=>{let k=`${x}${De}`;return[...p].some(S=>S===x||S.startsWith(k))}):h,y=this,b=e,v={name:this.name,nodes:l,edges:m,subgraphs:g,expand(x){let k={...b,format:void 0};return Array.isArray(x)?(k.fields=x,k.detail=void 0):(k.detail=x,k.fields=void 0),y.describe(k)}},T=e??{},w=T.format;return w==="json"?Zm(v,T):w==="pretty"?eg(v,T):w==="mermaid"?hc(v,T):w==="mermaid-url"?tg(v,T):w==="d2"?ng(v,T):w==="ascii"?ac(v,T):v}_collectSubgraphs(e){let n=[];for(let r of[...this._mounts.keys()].sort()){let o=e===""?r:`${e}${r}`;n.push(o),n.push(...this._mounts.get(r)._collectSubgraphs(`${o}${De}`))}return n}resourceProfile(e){return pn(this,e)}reachable(e,n,r={}){return r.withDetail===!0?fn(this.describe(),e,n,{...r,withDetail:!0}):fn(this.describe(),e,n,r)}explain(e,n,r){return r?.reactive===!0?this._explainReactive(e,n,r):this._explainStatic(e,n,r)}_explainStatic(e,n,r){let o=this.describe({detail:"full"}),s=new Map(this._annotations),i=new Map;for(let[a,u]of Object.entries(o.nodes))u.lastMutation!=null&&i.set(a,u.lastMutation);return Gr(o,e,n,{...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{},annotations:s,lastMutations:i})}_describeReactive(e){let n={...e,reactive:!1},r=e.reactiveName??"describe",o=0,s=M(o,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,u=!1,d=()=>{a||u||(a=!0,Sr(()=>{a=!1,!u&&(o+=1,s.emit(o))}))},c=i.onEvent(g=>{let y=g.type;y!=="data"&&y!=="error"&&y!=="complete"&&y!=="teardown"||d()}),l=[],p=new WeakSet,f=g=>{if(p.has(g)||u)return;p.add(g);let y=g.topology.subscribe(b=>{for(let v of b){if(v[0]!==E)continue;let T=v[1];if(d(),T.kind==="added"&&T.nodeKind==="mount"){let w=g._mounts.get(T.name);w!=null&&f(w)}}});l.push(y);for(let b of g._mounts.keys()){let v=g._mounts.get(b);v!=null&&f(v)}};f(this);let m;try{m=A([s],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(g,y)=>g===y})}catch(g){c();for(let y of l)y();throw i.dispose(),g}let h=re(m);return{node:m,dispose(){u=!0,c();for(let g of l)g();l.length=0,i.dispose(),h()}}}_explainReactive(e,n,r){let o=0,s=M(o,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,u=!1,d=i.onEvent(f=>{let m=f.type;m!=="data"&&m!=="error"&&m!=="complete"&&m!=="teardown"||a||u||(a=!0,Sr(()=>{a=!1,!u&&(o+=1,s.emit(o))}))}),c={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},l;try{l=A([s],()=>this._explainStatic(e,n,c),{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:e,to:n},equals:(f,m)=>f.found===m.found&&f.reason===m.reason&&f.steps.length===m.steps.length&&cg(f.steps,m.steps)})}catch(f){throw d(),i.dispose(),f}let p=re(l);return{node:l,dispose(){u=!0,d(),i.dispose(),p()}}}_pathsMatching(e){let n=cs(e),r=[];return this._collectObserveTargets("",r),r.map(([o])=>o).filter(o=>n.test(o))}_collectObserveTargets(e,n){for(let r of[...this._mounts.keys()].sort()){let o=e===""?r:`${e}${De}${r}`;this._mounts.get(r)._collectObserveTargets(o,n)}for(let r of[...this._nodes.keys()].sort()){let o=this._nodes.get(r),s=e===""?r:`${e}${De}${r}`;n.push([s,o]),this._appendMetaObserveTargets(s,o,n)}}_appendMetaObserveTargets(e,n,r){for(let o of Object.keys(n.meta).sort()){let s=n.meta[o],i=`${e}${De}${Qe}${De}${o}`;r.push([i,s]),this._appendMetaObserveTargets(i,s,r)}}observe(e,n){let r=typeof e=="string",s=fc(r?n:e),i=s.structured===!0||s.timeline===!0||s.causal===!0||s.derived===!0||s.detail==="minimal"||s.detail==="full"||s.format!=null,a=s.actor;if(r){let c=e,l=this.resolve(c);if(a!=null&&!l.allowsObserve(a))throw new rt({actor:a,action:"observe",nodeName:c});return i?this._buildStructuredObserver([[c,l]],s,"one"):{subscribe(p){return l.subscribe(p)},up(p){try{l.up?.(p)}catch(f){if(f instanceof rt)return;throw f}}}}let u=[];this._collectObserveTargets("",u),u.sort((c,l)=>c[0]<l[0]?-1:c[0]>l[0]?1:0);let d=a==null?u:u.filter(([,c])=>c.allowsObserve(a));return i?this._buildStructuredObserver(d,s,"all"):{subscribe:c=>{let l=d.map(([p,f])=>f.subscribe(m=>{c(p,m)}));return()=>{for(let p of l)p()}},up:(c,l)=>{try{this.resolve(c).up?.(l)}catch(p){if(p instanceof rt)return;throw p}}}}_buildStructuredObserver(e,n,r){let o=r==="one"?e[0]?.[0]:void 0,s=i=>{if(r==="one"&&o!=null){let c=this.resolve(o);return this._buildStructuredObserver([[o,c]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((c,l)=>c[0]<l[0]?-1:c[0]>l[0]?1:0);let u=i.actor,d=u==null?a:a.filter(([,c])=>c.allowsObserve(u));return this._buildStructuredObserver(d,i,"all")};return this._createObserveResult(e,n,s)}_createObserveResult(e,n,r){let o=n.timeline===!0,s=n.causal===!0,i=n.derived===!0,a=n.detail==="minimal",u=this.config.inspectorEnabled,d=(s||i)&&u,c=n.maxEvents,l=c!=null&&c>0?new ln(c):null,p=[],f=new Set,m={},h=new Set,g=0,y=0,b=0,v=0,T=0,w=0,x=!1,k=!1,S=0,R=new Map,N=new Map,_=new Map,I=$=>{l?l.push($):p.push($);for(let te of f)te($)},O=()=>o?{timestamp_ns:H(),in_batch:tn(),batch_id:S}:{},P=($,te)=>{if(!(!d||!($ instanceof Ae)))return $._setInspectorHook(Re=>{if(Re.kind==="dep_message")R.set($,Re.depIndex);else if(Re.kind==="run"){let Oe=Re.batchData.map((ye,Ge)=>ye!=null&&ye.length>0?ye.at(-1):Re.prevData[Ge]);N.set($,Oe);let Ce=Re.batchData.map(ye=>ye!=null?[...ye]:void 0);_.set($,Ce),i&&I({type:"derived",path:te,dep_values:Oe,dep_batches:Ce,...O()})}})},B=$=>{let te=R.get($),Re=N.get($);if(!s||Re==null)return{};let Ce=(te!=null&&te>=0&&$ instanceof Ae?$._deps[te]:void 0)?.node,ye=Ce?.v,Ge=_.get($);return{trigger_dep_index:te,trigger_dep_name:Ce?.name,...ye!=null?{trigger_version:{id:ye.id,version:ye.version}}:{},dep_values:[...Re],...Ge!=null?{dep_batches:Ge}:{}}},j=[],D=[];for(let[$,te]of e){let Re=P(te,$);Re&&j.push(Re),D.push(te.subscribe(Oe=>{S++;for(let Ce of Oe){let ye=Ce[0],Ge=O();if(ye===E){m[$]=Ce[1];let ie=te instanceof Ae?te.lastMutation?.actor??bt:bt;I({type:"data",path:$,data:Ce[1],actor:ie,...Ge,...B(te)})}else if(a)ye===ne?g++:ye===V?y++:ye===Je?b++:ye===Be?v++:ye===qe?T++:ye===le?w++:ye===L&&!h.has($)?x=!0:ye===C&&(k=!0,h.add($));else if(ye===ne)g++,I({type:"dirty",path:$,...Ge});else if(ye===V)y++,I({type:"resolved",path:$,...Ge,...B(te)});else if(ye===Je)b++,I({type:"invalidate",path:$,...Ge});else if(ye===Be)v++,I({type:"pause",path:$,lockId:Ce[1],...Ge});else if(ye===qe)T++,I({type:"resume",path:$,lockId:Ce[1],...Ge});else if(ye===L)h.has($)||(x=!0),I({type:"complete",path:$,...Ge});else if(ye===C){k=!0,h.add($);let ie=te instanceof Ae?te.lastMutation?.actor??bt:bt;I({type:"error",path:$,data:Ce[1],actor:ie,...Ge})}else ye===le&&(w++,I({type:"teardown",path:$,...Ge}))}}))}let Z=!1,F=()=>{if(!Z){Z=!0;for(let $ of D)$();for(let $ of j)$();for(let $ of G)$({value:void 0,done:!0});G.length=0}},Q=[],G=[];f.add($=>{let te=G.shift();te?te({value:$,done:!1}):Q.push($)});let q={get values(){return m},get dirtyCount(){return g},get resolvedCount(){return y},get invalidateCount(){return b},get pauseCount(){return v},get resumeCount(){return T},get teardownCount(){return w},get events(){return l?l.toArray():[...p]},get anyCompletedCleanly(){return x},get anyErrored(){return k},get completedWithoutErrors(){return x&&!k},onEvent($){return f.add($),()=>f.delete($)},dispose:F,expand($){F();let te={...n};return typeof $=="string"?te.detail=$:Object.assign(te,$),r(fc(te))},[Symbol.asyncIterator](){return{next(){return Q.length>0?Promise.resolve({value:Q.shift(),done:!1}):Z?Promise.resolve({value:void 0,done:!0}):new Promise($=>G.push($))},return(){return F(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(q,n),q}_attachFormatLogger(e,n){let r=n.format;if(r==null)return;let o=n.logger??(m=>console.log(m)),s=n.includeTypes?new Set(n.includeTypes):null,i=n.excludeTypes?new Set(n.excludeTypes):null,a=s==null&&i==null?()=>!0:m=>(s==null||s.has(m))&&(i==null||!i.has(m)),u=ig(n.theme),d=r==="stage-log"?H():0,c=m=>m==null?"":n.stageLabels?.[m]??m,l=(m,h)=>m.length>h?`${m.slice(0,h-1)}\u2026`:m,p=m=>m.type==="data"||m.type==="error"?l(ls(m.data),120):"",f=m=>{if(r==="stage-log"){let k=(H()-d)/1e9,S=c(m.path).padEnd(9);if(m.type==="data"){let R=p(m);return`[${k.toFixed(3)}s] ${S} \u2190${R?` ${R}`:""}`}if(m.type==="error"){let R=p(m);return`[${k.toFixed(3)}s] ${S} \u2717${R?` ${R}`:""}`}return m.type==="complete"?`[${k.toFixed(3)}s] ${S} \u25A0 complete`:`[${k.toFixed(3)}s] ${S} ${m.type}`}if(r==="json")try{return JSON.stringify(m)}catch{return JSON.stringify({type:m.type,path:m.path,data:"[unserializable]"})}let h=u[m.type]??"",g=m.path?`${u.path}${m.path}${u.reset} `:"",y=m.type==="data"||m.type==="error",b=m.type==="pause"||m.type==="resume",v=y?` ${ls(m.data)}`:b?` ${ls(m.lockId)}`:"",T=m.type==="data"||m.type==="resolved"||m.type==="derived"?m:void 0,w=T?.trigger_dep_name!=null?` <- ${T.trigger_dep_name}`:T?.trigger_dep_index!=null?` <- #${T.trigger_dep_index}`:"",x=m.in_batch?" [batch]":"";return`${g}${h}${m.type.toUpperCase()}${u.reset}${v}${w}${x}`};e.onEvent(m=>{a(m.type)&&o(f(m),m)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){lc(this._disposers,this.name),this.signal([[le]],{internal:!0}),lc(this._storageDisposers,this.name);for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}get destroyed(){return this._destroyed}_destroyClearOnly(){for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}snapshot(e){let{expand:n,...r}=this.describe({detail:"full"}),o={};for(let a of Object.keys(r.nodes).sort()){let{lastMutation:u,guard:d,...c}=r.nodes[a];o[a]=c}let s=[...r.subgraphs].sort(),i={...r,version:1,nodes:o,subgraphs:s};if(e?.format==null)return i;if(e.format==="json-string")return JSON.stringify(i);if(e.format==="bytes"){if(e.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let a=this.config.lookupCodec(e.codec);if(a==null)throw new Error(`snapshot: codec "${e.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return vr(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??$e,{codec:o,codecVersion:s,payload:i}=Tr(e,r);return o.decode(i,s)}restore(e,n){if(pc(e),e.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${e.name}" does not match this graph`);let r=n?.only==null?null:(Array.isArray(n.only)?n.only:[n.only]).map(s=>cs(s)),o=n?.includeProducers===!0;for(let s of Object.keys(e.nodes).sort()){if(r!==null&&!r.some(a=>a.test(s)))continue;let i=e.nodes[s];if(i!==void 0){if(!("value"in i)||i.value===void 0){"value"in i&&i.value===void 0&&n?.onError?.(s,new Error(`restore: slice.value is undefined for "${s}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(i.type==="derived"||i.type==="effect")&&!(i.type==="producer"&&!o)){if(i.v!=null){let u=this.tryResolve(s)?.v;if(u!=null&&u.id===i.v.id&&u.version===i.v.version)continue}try{this.set(s,i.value)}catch(a){n?.onError?.(s,a)}}}}}static fromSnapshot(e,n){pc(e);let r=typeof n=="function"?n:n?.build,o=typeof n=="function"?void 0:n?.factories,s=new t(e.name);if(r)return r(s),s.restore(e),s;for(let f of[...e.subgraphs].sort((m,h)=>{let g=m.split(De).length,y=h.split(De).length;return g!==y?g-y:m<h?-1:m>h?1:0})){let m=f.split(De),h=s;for(let g of m)h._mounts.has(g)||h.mount(g,new t(g)),h=h._mounts.get(g)}let i=o?Object.entries(o).map(([f,m])=>({re:cs(f),factory:m})):[],a=f=>{for(let m of i)if(m.re.test(f))return m.factory},u=f=>{let m=f.split(De),h=m.pop();if(h==null||h.length===0)throw new Error(`invalid snapshot path "${f}"`);let g=s;for(let y of m){let b=g._mounts.get(y);if(!b)throw new Error(`unknown mount "${y}" in path "${f}"`);g=b}return[g,h]},d=Object.entries(e.nodes).filter(([f])=>!f.includes(`${De}${Qe}${De}`)).sort((f,m)=>f[0]<m[0]?-1:f[0]>m[0]?1:0),c=new Map(d),l=new Map,p=!0;for(;c.size>0&&p;){p=!1;for(let[f,m]of[...c.entries()]){let h=m?.deps??[];if(!h.every(w=>l.has(w)))continue;let[g,y]=u(f),b={...m?.meta??{}},v=a(f),T;if(m?.type==="state")T=M(m.value,{meta:b});else{if(v==null)continue;T=v(y,{path:f,type:m.type,value:m.value,meta:b,deps:h,resolvedDeps:h.map(w=>l.get(w))})}g.add(T,{name:y}),l.set(f,T),c.delete(f),p=!0}}if(c.size>0){let f=[...c.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${f}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return s.restore(e),s}toJSON(){return this.snapshot()}attachSnapshotStorage(e,n={}){let r=e.map(d=>({tier:d,debounceMs:Math.max(0,d.debounceMs??0),compactEvery:Math.max(1,d.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));n.autoRestore===!0&&this._cascadeRestore(e,n.onError);let o=(d,c)=>{if(d.disposed)return;let l=Um(c.nodes);if(d.lastSnapshot!=null&&l!==""&&l===d.lastFingerprint)return;let p=d.seq+1,f=oe(),g=d.lastSnapshot==null||p%d.compactEvery===0?{name:this.name,mode:"full",snapshot:c,seq:p,timestamp_ns:f,format_version:ft}:{name:this.name,mode:"diff",diff:fs(d.lastSnapshot,c),seq:p,timestamp_ns:f,format_version:ft};if(d.tier.filter&&!d.tier.filter(g))return;let y;try{y=d.tier.save(g)}catch(b){n.onError?.(b,d.tier);return}if(y&&typeof y.then=="function"){let T=(d.savePending??Promise.resolve()).then(()=>y,()=>y).then(()=>{d.disposed||(d.seq=p,d.lastSnapshot=c,d.lastFingerprint=l)},w=>{n.onError?.(w,d.tier)});d.savePending=T.finally(()=>{d.savePending===T&&(d.savePending=void 0)})}else d.seq=p,d.lastSnapshot=c,d.lastFingerprint=l},s=(d,c)=>{try{o(d,c)}catch(l){n.onError?.(l,d.tier)}},i=(d,c)=>{if(!c.some(m=>{let h=this.config.messageTier(m[0]);return h>=3&&h<5}))return;if(n.filter){let m=this.tryResolve(d);if(m==null)return;let h=Dr(m,Ct("standard"));if(!n.filter(d,h))return}let p,f=()=>(p==null&&(p=this.snapshot()),p);for(let m of r)m.disposed||(m.debounceMs===0?s(m,f()):(m.timer==null&&(m.timer=new Le),m.timer.start(m.debounceMs,()=>{m.disposed||s(m,this.snapshot())})))},a;if(n.paths!=null){let c=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(l=>{let p=this.tryResolve(l);return p==null?()=>{}:p.subscribe(f=>i(l,f))});a=()=>{for(let l of c)l()}}else a=this.observe().subscribe((d,c)=>i(d,c));let u=()=>{a();for(let d of r)d.disposed=!0,d.timer?.cancel();this._storageDisposers.delete(u)};return this._storageDisposers.add(u),{dispose:u}}async _cascadeRestore(e,n){for(let r of e){let o;try{o=await r.load?.()}catch(i){n?.(i,r);continue}if(o==null||typeof o!="object"||Array.isArray(o))continue;let s=o;try{if(s.mode==="full"&&s.snapshot!=null)return this.restore(s.snapshot),!0;if(s.version===ft&&s.nodes!=null)return this.restore(s),!0}catch(i){n?.(i,r)}}return!1}static async fromStorage(e,n,r){for(let o of n){let s;try{s=await o.load?.()}catch(u){r?.onError?.(u,o);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let i=s,a=i.mode==="full"&&i.snapshot!=null?i.snapshot:i.version===ft&&i.nodes!=null?i:void 0;if(a!=null)try{return t.fromSnapshot(a,r)}catch(u){r?.onError?.(u,o)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${n.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,n,r){if(e!=null&&n!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,n),this.config.inspectorEnabled){let o={path:e,annotation:n,timestamp_ns:H(),...r?.actor!=null?{actor:r.actor}:{}};this._traceRing.push(o)}return}return e!=null?this.config.inspectorEnabled?this._annotations.get(e):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(e){return this._annotations.get(e)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(e){let n=this._traceRing.toArray().filter(o=>!e(o)),r=this._traceRing.size-n.length;this._traceRing.clear();for(let o of n)this._traceRing.push(o);return r}static diff(e,n){let r=new Set(Object.keys(e.nodes)),o=new Set(Object.keys(n.nodes)),s=[...o].filter(b=>!r.has(b)).sort(),i=[...r].filter(b=>!o.has(b)).sort(),a=[],u=[];for(let b of r){if(!o.has(b))continue;let v=e.nodes[b],T=n.nodes[b],w=v.v,x=T.v;w!=null&&x!=null&&w.id===x.id&&w.version!==x.version&&u.push({path:b,id:w.id,from:w.version,to:x.version});let k=w!=null&&x!=null&&w.id===x.id&&w.version===x.version;for(let S of["type","status","sentinel"]){let R=v[S],N=T[S];R!==N&&a.push({path:b,field:S,from:R,to:N})}if(!k)for(let S of["value","meta"]){let R=v[S],N=T[S];Jm(R,N)||a.push({path:b,field:S,from:R,to:N})}}let d=b=>`${b.from} ${b.to}`,c=new Set(e.edges.map(d)),l=new Set(n.edges.map(d)),p=n.edges.filter(b=>!c.has(d(b))),f=e.edges.filter(b=>!l.has(d(b))),m=new Set(e.subgraphs),h=new Set(n.subgraphs),g=[...h].filter(b=>!m.has(b)).sort(),y=[...m].filter(b=>!h.has(b)).sort();return{nodesAdded:s,nodesRemoved:i,nodesChanged:a,versionChanges:u,edgesAdded:p,edgesRemoved:f,subgraphsAdded:g,subgraphsRemoved:y}}};function fs(t,e){let n=Y.diff(t,e),r={};for(let o of n.nodesAdded){let s=e.nodes[o];s!=null&&(r[o]=s)}return{...n,nodesAddedFull:r}}function fn(t,e,n,r={}){let o={paths:[],depths:new Map,truncated:!1};if(!e)return r.withDetail?o:[];if(!r.both&&n!=="upstream"&&n!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let s=r.maxDepth;if(s!=null&&(!Number.isInteger(s)||s<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(s===0)return r.withDetail?o:[];let i=new Map,a=new Map,u=new Map,d=new Map,c=new Set;for(let[v,T]of Object.entries(t.nodes)){if(!v)continue;c.add(v);let w=T.deps??[];i.set(v,w);for(let x of w)x&&(c.add(x),a.has(x)||a.set(x,new Set),a.get(x).add(v))}for(let v of t.edges){if(v==null||typeof v!="object")continue;let T=typeof v.from=="string"?v.from:"",w=typeof v.to=="string"?v.to:"";!T||!w||(c.add(T),c.add(w),d.has(T)||d.set(T,new Set),d.get(T).add(w),u.has(w)||u.set(w,new Set),u.get(w).add(T))}if(!c.has(e))return r.withDetail?o:[];let l=r.both===!0,p=v=>{if(l){let k=i.get(v)??[],S=u.get(v),R=a.get(v),N=d.get(v),_=[...k];return S&&_.push(...S),R&&_.push(...R),N&&_.push(...N),_}if(n==="upstream"){let k=i.get(v)??[],S=u.get(v);return S?[...k,...S]:k}let T=a.get(v),w=d.get(v),x=T?[...T]:[];return w&&x.push(...w),x},f=new Set([e]),m=new Map,h=[{path:e,depth:0}],g=0,y=!1;for(;g<h.length;){let v=h[g++];if(s!=null&&v.depth>=s){p(v.path).length>0&&(y=!0);continue}for(let T of p(v.path))!T||f.has(T)||(f.add(T),m.set(T,v.depth+1),h.push({path:T,depth:v.depth+1}))}let b=[...m.keys()].sort((v,T)=>v<T?-1:v>T?1:0);return r.withDetail?{paths:b,depths:m,truncated:y}:b}function cg(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.path!==o.path||r.type!==o.type||r.status!==o.status||r.hop!==o.hop||r.dep_index!==o.dep_index||r.annotation!==o.annotation||r.value!==o.value||r.lastMutation!==o.lastMutation)return!1;let s=r.v,i=o.v;if(s!==i&&(s==null||i==null||s.id!==i.id||s.version!==i.version))return!1}return!0}var Ts={};ke(Ts,{CqrsGraph:()=>vs,cqrs:()=>Ra,cqrsEventKeyOf:()=>hg,dispatchKeyOf:()=>yg,sagaInvocationKeyOf:()=>bg});Me();xe();$t();var va={};ke(va,{COMPLETE:()=>L,COMPLETE_MSG:()=>Oo,COMPLETE_ONLY_BATCH:()=>br,DATA:()=>E,DEFAULT_ACTOR:()=>bt,DIRTY:()=>ne,DIRTY_MSG:()=>Et,DIRTY_ONLY_BATCH:()=>Mn,ERROR:()=>C,GraphReFlyConfig:()=>nn,GuardDenied:()=>rt,INVALIDATE:()=>Je,INVALIDATE_MSG:()=>Mo,INVALIDATE_ONLY_BATCH:()=>yr,NodeImpl:()=>Ae,PAUSE:()=>Be,RESOLVED:()=>V,RESOLVED_MSG:()=>Nn,RESOLVED_ONLY_BATCH:()=>hr,RESUME:()=>qe,START:()=>dt,START_MSG:()=>_n,TEARDOWN:()=>le,TEARDOWN_MSG:()=>Co,TEARDOWN_ONLY_BATCH:()=>On,accessHintForGuard:()=>_r,advanceVersion:()=>Mr,autoTrackNode:()=>rn,batch:()=>X,configure:()=>ra,createVersioning:()=>In,defaultConfig:()=>$e,defaultHash:()=>jt,derived:()=>A,downWithBatch:()=>_t,dynamicNode:()=>Or,effect:()=>pe,isBatching:()=>tn,isV1:()=>ea,monotonicNs:()=>H,node:()=>z,normalizeActor:()=>Nt,pipe:()=>oa,policy:()=>Mt,policyFromRules:()=>Nr,producer:()=>K,registerBuiltins:()=>Er,resolveDescribeFields:()=>Ct,state:()=>M,wallClockNs:()=>oe});kr();Me();xe();Xi();$t();ae();_e();ee();Io();Me();ae();_e();ee();he();var jr=class{_version=0;_maxSize;_buf;_head=0;_size=0;constructor(e,n){if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(this._maxSize=n,n!==void 0){if(this._buf=new Array(n),e&&e.length>0){let r=Math.min(e.length,n),o=e.length-r;for(let s=0;s<r;s++)this._buf[s]=e[o+s];this._size=r}}else this._buf=e?[...e]:[],this._size=this._buf.length}get version(){return this._version}get size(){return this._size}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._size+e;if(!(n<0||n>=this._size))return this._maxSize!==void 0?this._buf[(this._head+n)%this._maxSize]:this._buf[n]}append(e){this._rawAppend(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._maxSize!==void 0&&e.length>this._maxSize?e.length-this._maxSize:0;for(let r=n;r<e.length;r++)this._rawAppend(e[r]);this._version+=1}clear(){if(this._size===0)return 0;let e=this._size;if(this._maxSize===void 0)this._buf.length=0;else for(let n=0;n<e;n++)this._buf[(this._head+n)%this._maxSize]=void 0;return this._head=0,this._size=0,this._version+=1,e}trimHead(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`trimHead: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return 0;let n=Math.min(e,this._size);if(this._maxSize===void 0)this._buf.splice(0,n);else{for(let r=0;r<n;r++)this._buf[(this._head+r)%this._maxSize]=void 0;this._head=(this._head+n)%this._maxSize}return this._size-=n,this._version+=1,n}slice(e,n){if(!Number.isInteger(e)||e<0)throw new RangeError(`slice: start must be a non-negative integer (got ${e})`);if(n!==void 0&&(!Number.isInteger(n)||n<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${n})`);let r=n===void 0?this._size:Math.min(Math.max(n,0),this._size),o=Math.min(e,this._size);if(o>=r)return[];let s=r-o;if(this._maxSize===void 0)return this._buf.slice(o,r);let i=new Array(s);for(let a=0;a<s;a++)i[a]=this._buf[(this._head+o+a)%this._maxSize];return i}tail(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`tail: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return[];let n=Math.min(e,this._size);return this.slice(this._size-n,this._size)}toArray(){if(this._maxSize===void 0)return[...this._buf];let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this._buf[(this._head+n)%this._maxSize];return e}snapshot(){return this.toArray()}restore(e){if(this._maxSize===void 0){this._buf.length=0;for(let n=0;n<e.length;n++)this._buf.push(e[n]);this._size=this._buf.length}else{let n=this._maxSize;for(let s=0;s<n;s++)this._buf[s]=void 0;this._head=0;let r=Math.min(e.length,n),o=e.length-r;for(let s=0;s<r;s++)this._buf[s]=e[o+s];this._size=r}this._version+=1}_rawAppend(e){if(this._maxSize===void 0){this._buf.push(e),this._size=this._buf.length;return}this._size<this._maxSize?(this._buf[(this._head+this._size)%this._maxSize]=e,this._size+=1):(this._buf[this._head]=e,this._head=(this._head+1)%this._maxSize)}};function $r(t){return t.subscribe(()=>{})}var lg=64;function Ve(t,e={}){let{name:n,maxSize:r,versioning:o,guard:s,backend:i}=e,a=i??new jr(t,r),u=M(a.toArray(),{name:n,describeKind:"state",equals:(k,S)=>k===S,...o!=null?{versioning:o}:{},...s!=null?{guard:s}:{}});function d(){let k=a.toArray();X(()=>{u.down([[ne]],{internal:!0}),u.down([[E,k]],{internal:!0})})}let c=new Map,l=new Map,p=new Map;function f(k,S){return`${k}:${S===void 0?"END":S}`}function m(k){if(k.size<lg)return;let S=k.keys().next();if(S.done)return;let R=k.get(S.value);R!==void 0&&R.dispose(),k.delete(S.value)}function h(k){let S=a.version;try{return k()}finally{a.version!==S&&d()}}function g(k){if(!Number.isInteger(k)||k<0)throw new RangeError(`tail: n must be a non-negative integer (got ${k})`);let S=c.get(k);if(S!==void 0)return c.delete(k),c.set(k,S),S.node;m(c);let R=A([u],([_])=>{let I=_;return k===0||I.length===0?[]:I.slice(Math.max(0,I.length-k))},{initial:a.tail(k),describeKind:"derived"}),N=$r(R);return c.set(k,{node:R,dispose:N}),R}function y(k,S){if(!Number.isInteger(k)||k<0)throw new RangeError(`slice: start must be a non-negative integer (got ${k})`);if(S!==void 0&&(!Number.isInteger(S)||S<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${S})`);let R=f(k,S),N=l.get(R);if(N!==void 0)return l.delete(R),l.set(R,N),N.node;m(l);let _=A([u],([O])=>{let P=O;return S===void 0?P.slice(k):P.slice(k,S)},{initial:a.slice(k,S),describeKind:"derived"}),I=$r(_);return l.set(R,{node:_,dispose:I}),_}function b(k){let S=p.get(k);if(S!==void 0)return S.node;let R=A([u,k],([_,I])=>{let O=_,P=Math.max(0,Math.trunc(I??0));return O.slice(P)},{initial:[],describeKind:"derived"}),N=$r(R);return p.set(k,{node:R,dispose:N}),R}let v,T;function w(){v===void 0&&(v=z([u],(k,S,R)=>{let N=k[0],I=N!=null&&N.length>0?N.at(-1):R.prevData[0];if(I==null||I.length===0){S.down([[V]]);return}S.emit(I[I.length-1])},{name:n!=null?`${n}::lastValue`:"lastValue",describeKind:"derived",initial:a.size===0?void 0:a.at(a.size-1)}),T=A([u],([k])=>k.length>0,{name:n!=null?`${n}::hasLatest`:"hasLatest",describeKind:"derived",initial:a.size>0}),$r(v),$r(T))}let x={entries:u,get size(){return a.size},at(k){return a.at(k)},append(k){h(()=>a.append(k))},appendMany(k){k.length!==0&&h(()=>a.appendMany(k))},clear(){h(()=>a.clear())},trimHead(k){h(()=>a.trimHead(k))},withLatest(){return w(),u},get lastValue(){return w(),v},get hasLatest(){return w(),T},view(k){switch(k.kind){case"tail":return g(k.n);case"slice":return y(k.start,k.stop);case"fromCursor":return b(k.cursor)}},attach(k){let S=k.subscribe(R=>{for(let N of R)N[0]===E&&x.append(N[1])});return()=>S()},attachStorage(k){if(k.length===0)return()=>{};let S=new Map;for(let N of k)S.set(N,a.size);(async()=>{for(let N of k)if(typeof N.loadEntries=="function")try{let _=await Promise.resolve(N.loadEntries());_.entries.length>0&&a.size===0&&(a.restore(_.entries),S.set(N,_.entries.length),d());break}catch{}})();let R=u.subscribe(N=>{for(let _ of N){if(_[0]!==E)continue;let I=_[1];for(let O of k){let P=S.get(O)??0;if(I.length<P){try{let j=O.appendEntries(I);j instanceof Promise&&j.catch(()=>{})}catch{}S.set(O,I.length);continue}if(I.length===P)continue;let B=I.slice(P);S.set(O,I.length);try{let j=O.appendEntries(B);j instanceof Promise&&j.catch(()=>{})}catch{}}}});return()=>R()},disposeAllViews(){for(let k of c.values())k.dispose();c.clear();for(let k of l.values())k.dispose();l.clear();for(let k of p.values())k.dispose();p.clear()},dispose(){for(let k of c.values())k.dispose();c.clear();for(let k of l.values())k.dispose();l.clear();for(let k of p.values())k.dispose();p.clear()}};return x}var Ta=new WeakMap;function bc(t){let e=Ta.get(t);if(e)return e;let n=t.map(c=>c.cache??[]),r=n.flat(),o=M(r,{name:"mergeReactiveLogs",describeKind:"state",equals:(c,l)=>c===l}),s=t.map((c,l)=>[...n[l]??[]]),i=[];for(let c=0;c<t.length;c++){let l=c,p=t[l].subscribe(f=>{for(let m of f)if(m[0]===E)s[l]=[...m[1]],o.emit(s.flat());else if(m[0]===L){s[l]=[];let h=i[l];h!==void 0&&(i[l]=void 0,h())}else m[0]===C&&o.down([[C,m[1]]])});i.push(p)}let a=re(o),u=!1,d={node:o,dispose(){if(!u){u=!0;for(let c of i)c?.();i.length=0,a(),Ta.delete(t)}}};return Ta.set(t,d),d}var ka={};ke(ka,{ENVELOPE_VERSION:()=>Cn,GRAPH_META_SEGMENT:()=>Qe,Graph:()=>Y,JsonCodec:()=>Ao,SIZEOF_OVERHEAD:()=>je,SIZEOF_SYMBOL:()=>ds,SNAPSHOT_VERSION:()=>ft,createDagCborCodec:()=>Ji,createDagCborZstdCodec:()=>Yi,decodeEnvelope:()=>Tr,diffForWAL:()=>fs,encodeEnvelope:()=>vr,explainPath:()=>Gr,graphProfile:()=>pn,mermaidLiveUrl:()=>ps,reachable:()=>fn,registerBuiltinCodecs:()=>wr,replayWAL:()=>Qi,sizeof:()=>Fr,validateGraphObservability:()=>wa,watchTopologyTree:()=>At});Lo();ae();function At(t,e){let n=new Map,r=(o,s)=>{if(n.has(o))return;let i={off:()=>{},prefix:s};n.set(o,i);let a=o.topology.subscribe(u=>{for(let d of u){if(d[0]!==E)continue;let c=d[1];if(e(c,o,s),c.kind==="added"&&c.nodeKind==="mount"){let l=o._mounts.get(c.name);if(l instanceof Y){let p=`${s}${c.name}::`;r(l,p)}}else if(c.kind==="removed"&&c.nodeKind==="mount"){let l=`${s}${c.name}::`;for(let[p,f]of Array.from(n.entries()))p!==t&&f.prefix.startsWith(l)&&(f.off(),n.delete(p))}}});i.off=a;for(let[u,d]of o._mounts)if(d instanceof Y){let c=`${s}${u}::`;r(d,c)}};return r(t,""),()=>{for(let o of n.values())o.off();n.clear()}}function wa(t,e={}){let n=[],r=e.requireFound??!0;if(e.skipDescribe!==!0)try{let d=t.describe(),c=new Set(Object.keys(d.nodes)),l=[];for(let[p,f]of Object.entries(d.nodes))for(let m of f.deps)m!==""&&!c.has(m)&&l.push(`${p} \u2192 ${m}`);for(let p of d.edges)c.has(p.from)||l.push(`edge.from: ${p.from}`),c.has(p.to)||l.push(`edge.to: ${p.to}`);l.length>0?n.push({kind:"describe",ok:!1,reason:`describe() has ${l.length} dangling pointer(s); nodes \u2289 deps`,danglingDeps:l}):n.push({kind:"describe",ok:!0,nodeCount:c.size,edgeCount:d.edges.length})}catch(d){n.push({kind:"describe",ok:!1,reason:`describe() threw: ${d instanceof Error?d.message:String(d)}`})}for(let d of e.formats??[])try{let c=t.describe({format:d});typeof c!="string"||c.length===0?n.push({kind:"describe-format",ok:!1,format:d,reason:`describe({ format: "${d}" }) returned empty or non-string output`}):n.push({kind:"describe-format",ok:!0,format:d,length:c.length})}catch(c){n.push({kind:"describe-format",ok:!1,format:d,reason:c instanceof Error?c.message:String(c)})}for(let d of e.paths??[])try{t.resolve(d),n.push({kind:"observe",ok:!0,path:d})}catch(c){n.push({kind:"observe",ok:!1,path:d,reason:c instanceof Error?c.message:String(c)})}for(let[d,c]of e.pairs??[])try{let l=t.explain(d,c);r&&l.found===!1?n.push({kind:"explain",ok:!1,from:d,to:c,reason:`explain(${d} \u2192 ${c}) found no path${l.reason?`: ${l.reason}`:""}`}):n.push({kind:"explain",ok:!0,from:d,to:c,found:l.found,steps:l.steps.length})}catch(l){n.push({kind:"explain",ok:!1,from:d,to:c,reason:l instanceof Error?l.message:String(l)})}let o=n.filter(d=>!d.ok),s=o.length===0,i=e.paths?.length??0,a=e.pairs?.length??0,u=e.formats?.length??0;return{ok:s,checks:n,failures:o,summary(){let d=[e.skipDescribe===!0?null:"describe",u>0?`${u} format${u===1?"":"s"}`:null,i>0?`${i} observe path${i===1?"":"s"}`:null,a>0?`${a} explain pair${a===1?"":"s"}`:null].filter(l=>l!=null),c=d.length>0?d.join(", "):"describe-only";return s?`validateGraphObservability: OK (${c})`:`validateGraphObservability: ${o.length} failure(s) across ${c}`}}}var Wt=class extends Error{constructor(e,n){super(e,n),this.name=this.constructor.name}},ms=class extends Wt{constructor(n,r){super(`Duplicate ${n} registration: "${r}"`);this.kind=n;this.registrationName=r}},gs=class extends Wt{constructor(n,r,o){super(`Command "${n}" emitted undeclared event "${r}". Declared emits: [${o.join(", ")}]`);this.commandName=n;this.eventName=r;this.declaredEmits=o}},hs=class extends Wt{constructor(n,r,o){super(`Optimistic concurrency conflict on aggregate "${n}": expected version ${r}, got ${o}`);this.aggregateId=n;this.expected=r;this.actual=o}},ys=class extends Wt{constructor(n){super(`Unknown command: "${n}". Register with command() first.`);this.commandName=n}},Br=class extends Wt{constructor(n,r){super(`Command handler "${n}" threw: ${r instanceof Error?r.message:String(r)}`,{cause:r});this.commandName=n}};var Vr=class extends Wt{constructor(n,r){super(`Projection "${n}" rebuild failed: ${r instanceof Error?r.message:String(r)}`,{cause:r});this.projectionName=n}};Me();xe();$t();ae();ee();var pg=Mt((t,e)=>{t("observe"),t("signal"),e("write")});function kt(t){let e=Ve([],{name:t.name,maxSize:t.retainedLimit??1024,guard:t.guard??pg,...t.versioning!=null?{versioning:t.versioning}:{}});return e.withLatest(),t.graph&&t.graph.add(e.entries,{name:t.name}),e}function vc(t){if(t===null||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.keys(t))vc(t[e]);return Object.freeze(t)}function fg(t){let n=(t.cache??0)+1;return t.down([[ne],[E,n]]),n}function Yn(t,e){let n=e.freeze??!0;return function(...o){let s=n?o.map(vc):o,i=oe(),a,u,d=!1,c;try{X(()=>{e.seq&&(c=fg(e.seq));try{if(a=t(...s),e.onSuccess){let l=e.onSuccess(s,a,{t_ns:i,seq:c});if(l!==void 0){let p=e.handlerVersion!=null?{...l,handlerVersion:e.handlerVersion}:l;e.audit.append(p)}}}catch(l){throw u=l,d=!0,l}})}catch(l){if(d&&e.onFailure){let p=u instanceof Error?u.name:typeof u,f=e.onFailure(s,u,{t_ns:i,seq:c,errorType:p});if(f!==void 0){let m=e.handlerVersion!=null?{...f,handlerVersion:e.handlerVersion}:f;e.audit.append(m)}}throw d?u:l}return a}}function bs(t,e,n=0){let r=M(n,{name:e,describeKind:"state"});return t.add(r,{name:e}),r}function Tc(t,e,n,r=0){let o={},s=new Y(e);for(let i of n){let a=M(r,{name:i,describeKind:"state"});s.add(a,{name:i}),o[i]=a}return t.mount(e,s),o}Me();ae();_e();he();function mt(t,e){t!=null&&_t(n=>t.down(n),[[E,e]],$e.tierOf)}function Kr(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[ne],[E,n+1]]),!0)}function ze(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}function qr(t){return t.relatedTo?.[0]??t.summary}var mg=Mt((t,e)=>{t("write"),t("signal"),e("observe")}),gg=Mt((t,e)=>{t("observe"),t("signal"),e("write")}),wc=Mt((t,e)=>{t("observe"),t("signal"),e("write")});function Hr(t,e){return ze("cqrs",t,e)}function xa(t){if(t===null||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.keys(t))xa(t[e]);return Object.freeze(t)}var hg=t=>`${t.type}::${t.aggregateId??"__default__"}`,yg=t=>t.commandName,bg=t=>t.eventType,vs=class extends Y{_eventLogs=new Map;_eventLogsByAggregate=new Map;_aggregateVersions=new Map;_aggregateLru=new Map;_commandRegs=new Map;_projections=new Set;_sagas=new Set;_keepaliveDisposers=[];_seq=0;_retainedLimit;_freezeCommandPayload;_freezeEventPayload;_maxAggregates;_dispatchSeqCursor;dispatches;audit;aggregateEvictions;constructor(e,n={}){super(e,n.graph),this._retainedLimit=n.retainedLimit??1024,this._freezeCommandPayload=n.freezeCommandPayload??!0,this._freezeEventPayload=n.freezeEventPayload??!0,this._maxAggregates=n.maxAggregates??1e4,this.dispatches=kt({name:"dispatches",retainedLimit:this._retainedLimit,graph:this}),this.audit=this.dispatches,this.aggregateEvictions=kt({name:"aggregateEvictions",retainedLimit:this._retainedLimit,graph:this}),this._dispatchSeqCursor=bs(this,"dispatch_seq",0)}aggregateVersion(e,n){return this._aggregateVersions.get(`${e}::${n}`)??0}_touchAggregate(e){this._aggregateLru.delete(e),this._aggregateLru.set(e,!0)}_enforceAggregateLru(){for(;this._aggregateLru.size>this._maxAggregates;){let e=this._aggregateLru.keys().next();if(e.done)break;let n=e.value;this._aggregateLru.delete(n);let r=n.indexOf("::");if(r<0)continue;let o=n.slice(0,r),s=n.slice(r+2),i=this._aggregateVersions.get(n)??0;this._aggregateVersions.delete(n);let a=this._eventLogsByAggregate.get(o);a&&(a.delete(s),a.size===0&&this._eventLogsByAggregate.delete(o)),this.aggregateEvictions.append({aggregateId:s,type:o,lastVersion:i,t_ns:oe()})}}destroy(){for(let e of this._keepaliveDisposers)e();this._keepaliveDisposers.length=0,super.destroy()}_attachedEventTiers=[];_attachedTierDisposers=new Map;attachEventStorage(e){this._attachedEventTiers.push(e);for(let[n,r]of this._eventLogs){let o=r.log.attachStorage(e),s=this._attachedTierDisposers.get(n);s||(s=[],this._attachedTierDisposers.set(n,s)),s.push(o)}for(let[n,r]of this._eventLogsByAggregate)for(let[o,s]of r){let i=`${n}::${o}`,a=s.log.attachStorage(e),u=this._attachedTierDisposers.get(i);u||(u=[],this._attachedTierDisposers.set(i,u)),u.push(a)}return()=>{let n=this._attachedEventTiers.indexOf(e);n>=0&&this._attachedEventTiers.splice(n,1)}}_autoWireStreamStorage(e,n){if(this._attachedEventTiers.length===0)return;let r=this._attachedTierDisposers.get(e);r||(r=[],this._attachedTierDisposers.set(e,r));for(let o of this._attachedEventTiers)r.push(n.attachStorage(o))}_bumpDispatchSeq(){let n=(this._dispatchSeqCursor.cache??0)+1;return this._dispatchSeqCursor.emit(n),n}event(e,n){if(n!==void 0)return this._ensureAggregateStream(e,n).node;let r=this._eventLogs.get(e);if(r)return r.node;let o=Ve([],{name:e,versioning:0,maxSize:this._retainedLimit});o.withLatest();let s=o.entries,i=A([s],([a])=>a,{name:e,describeKind:"state",meta:Hr("event",{event_name:e}),guard:wc,initial:s.cache});return this.add(i,{name:e}),this._keepaliveDisposers.push(re(i)),this._eventLogs.set(e,{log:o,node:i}),this._autoWireStreamStorage(e,o),i}_ensureAggregateStream(e,n){this._eventLogs.has(e)||this.event(e);let r=this._eventLogsByAggregate.get(e);r||(r=new Map,this._eventLogsByAggregate.set(e,r));let o=`${e}::${n}`;this._touchAggregate(o);let s=r.get(n);if(s)return s;let i=`${e}_${n.replace(/[^a-zA-Z0-9_-]/g,"_")}`,a=Ve([],{name:i,versioning:0,maxSize:this._retainedLimit});a.withLatest();let u=a.entries,d=A([u],([f])=>f,{name:i,describeKind:"state",meta:Hr("event_aggregate",{event_name:e,aggregate_id:n}),guard:wc,initial:u.cache}),c=i,l=0;for(;this.nameOf(this.resolveOptional(c)??d)===c&&(l+=1,c=`${i}_${l}`,this.resolveOptional(c)!==void 0););try{this.add(d,{name:c})}catch{}this._keepaliveDisposers.push(re(d));let p={log:a,node:d};return r.set(n,p),this._autoWireStreamStorage(`${e}::${n}`,a),this._enforceAggregateLru(),p}resolveOptional(e){try{return this.resolve(e)}catch{return}}_appendEvent(e,n,r){let o=this._eventLogs.get(e);if(o||(this.event(e),o=this._eventLogs.get(e)),o.node.status==="completed"||o.node.status==="errored")throw new Error(`Cannot dispatch to terminated event stream "${e}" (status: ${o.node.status}).`);let s,i;if(r?.aggregateId!==void 0){let c=`${e}::${r.aggregateId}`;s=(this._aggregateVersions.get(c)??0)+1,this._aggregateVersions.set(c,s),i=this._ensureAggregateStream(e,r.aggregateId)}let a=o.log.entries.v,u=this._freezeEventPayload?xa(n):n,d={type:e,payload:u,timestampNs:oe(),seq:++this._seq,...r?.aggregateId!==void 0?{aggregateId:r.aggregateId}:{},...s!==void 0?{aggregateVersion:s}:{},...r?.correlationId!==void 0?{correlationId:r.correlationId}:{},...r?.causationId!==void 0?{causationId:r.causationId}:{},...r?.metadata!==void 0?{metadata:Object.freeze({...r.metadata})}:{},...r?.handlerVersion!==void 0?{handlerVersion:r.handlerVersion}:{},...a!=null?{v0:{id:a.id,version:a.version}}:{}};return o.log.append(d),i&&i.log.append(d),d}command(e,n){if(this._commandRegs.has(e))throw new ms("command",e);let r=typeof n=="function"?{handler:n}:n,o=M(void 0,{name:e,describeKind:"state",meta:{...Hr("command",{command_name:e}),error:null},guard:mg});if(this.add(o,{name:e}),this._commandRegs.set(e,{handler:r.handler,...r.emits!==void 0?{emits:r.emits}:{},...r.handlerVersion!==void 0?{handlerVersion:r.handlerVersion}:{}}),r.emits)for(let s of r.emits)this._eventLogs.has(s)||this.event(s);return o}dispatch(e,n,r){let o=this._commandRegs.get(e);if(!o)throw new ys(e);if(r?.aggregateId!==void 0&&r.expectedAggregateVersion!==void 0&&o.emits!==void 0){let p=0;for(let f of o.emits){let m=this._aggregateVersions.get(`${f}::${r.aggregateId}`);m!==void 0&&m>p&&(p=m)}if(p!==r.expectedAggregateVersion)throw new hs(r.aggregateId,r.expectedAggregateVersion,p)}let s=this.resolve(e),i=this._freezeCommandPayload?xa(n):n,a=[],u=oe(),d=0,c,l=!1;try{X(()=>{d=this._bumpDispatchSeq(),s.emit(i,{internal:!0});try{o.handler(i,{emit:(p,f)=>{if(o.emits!==void 0&&!o.emits.includes(p))throw new gs(e,p,o.emits);a.push(p),this._appendEvent(p,f,{...r?.aggregateId!==void 0?{aggregateId:r.aggregateId}:{},...r?.correlationId!==void 0?{correlationId:r.correlationId}:{},...r?.causationId!==void 0?{causationId:r.causationId}:{},...r?.metadata!==void 0?{metadata:Object.freeze({...r.metadata})}:{},...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}})}}),s.meta.error.emit(null,{internal:!0}),this.dispatches.append({commandName:e,payload:i,status:"success",emittedEvents:[...a],t_ns:u,seq:d,...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}})}catch(p){throw c=p,l=!0,p}})}catch(p){if(l){s.meta.error.emit(c,{internal:!0});let f=c instanceof Error?c.name:typeof c,m=c instanceof Br?c:new Br(e,c);this.dispatches.append({commandName:e,payload:i,status:"failed",error:m,errorType:f,emittedEvents:[...a],t_ns:u,seq:d,...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}})}throw l?c:p}}projection(e){let{name:n,events:r,reducer:o,initial:s}=e,i=e.mode??"scan",a=e.freezeInputs??!0,u=e.snapshot,d=r.map(N=>(this._eventLogs.has(N)||this.event(N),this._eventLogs.get(N).node));function c(N){N.sort((_,I)=>_.timestampNs-I.timestampNs||_.seq-I.seq||(_.aggregateId??"").localeCompare(I.aggregateId??""))}function l(N){let _=[];for(let I of N)_.push(...I);return c(_),_}let p=d.map(N=>N.cache??[]),f=l(p),m=a?Object.freeze(f):f,h=0,g=s;i==="scan"&&f.length>0&&(g=o(s,m),h=f.length);let y=i==="replay"?o(s,m):g,b=u?.saveDebounceMs??1e3,v=u?.saveEvery??1e3,T,w=0;function x(N){if(u?.save){if(w+=1,w>=v){w=0,T!==void 0&&(clearTimeout(T),T=void 0);let _=u.save(N);_ instanceof Promise&&_.catch(()=>{});return}T!==void 0&&clearTimeout(T),T=setTimeout(()=>{T=void 0,w=0;let _=u.save(N);_ instanceof Promise&&_.catch(()=>{})},b)}}let k=A(d,N=>{let _=l(N),I;if(i==="replay"){let O=a?Object.freeze(_):_;I=o(s,O)}else{let O=_.slice(h);h=_.length;let P=a?Object.freeze(O):O;I=o(g,P),g=I}return x(I),I},{name:n,describeKind:"derived",meta:Hr("projection",{projection_name:n,source_events:r}),guard:gg,initial:y});return this.add(k,{name:n}),this._keepaliveDisposers.push(re(k)),this._keepaliveDisposers.push(()=>{T!==void 0&&(clearTimeout(T),T=void 0)}),this._projections.add(n),{node:k,rebuild:async N=>{try{let _=N?.pageSize??1e3,I=N?.fromTier??this._attachedEventTiers[0]?.[0],O=l(d.map(B=>B.cache??[])).length,P=s;if(u?.load){let B=await u.load();B!==void 0&&(P=B)}if(!I||!I.loadEntries){let B=l(d.map(D=>D.cache??[])),j=a?Object.freeze(B):B;P=o(P,j)}else{let B=new Set(r),j,D=!1;for(;!D;){let Z=await I.loadEntries({cursor:j,pageSize:_}),F=[...Z.entries].filter(G=>B.has(G.type));c(F);let Q=a?Object.freeze(F):F;P=o(P,Q),j=Z.cursor,D=!j||Z.entries.length===0}}if(i==="scan"){let B=l(d.map(D=>D.cache??[])),j=B.slice(O);if(j.length>0){let D=a?Object.freeze(j):j;P=o(P,D)}g=P,h=B.length}return k.emit(P,{internal:!0}),P}catch(_){throw new Vr(n,_)}},reset:async()=>{try{let N=s;if(u?.load){let P=await u.load();P!==void 0&&(N=P)}let _=l(d.map(P=>P.cache??[])),I=a?Object.freeze(_):_,O=o(N,I);return i==="scan"&&(g=O,h=_.length),k.emit(O,{internal:!0}),O}catch(N){throw new Vr(n,N)}}}}saga(e,n,r,o={}){let s=n.map(f=>(this._eventLogs.has(f)||this.event(f),this._eventLogs.get(f).node)),i=Tc(this,`${e}_cursor`,n,0),a=kt({name:`${e}_invocations`,retainedLimit:this._retainedLimit,graph:this}),u=o.aggregateId,d=o.errorPolicy??"advance",c=new Map;for(let f of n){let m=i[f];c.set(f,m.cache??0);let h=m.subscribe(g=>{for(let y of g)y[0]===E&&c.set(f,y[1])});this._keepaliveDisposers.push(h)}let l={},p=z(s,(f,m)=>{let h=l.n.meta.error;for(let g=0;g<f.length;g++){let y=f[g];if(y==null||y.length===0)continue;let b=y.at(-1);if(!b)continue;let v=n[g],T=i[v],w=c.get(v)??0;if(b.length>w){let x=b.slice(w),k=w;for(let S of x){let R=S;if(u!==void 0&&R.aggregateId!==u){k+=1;continue}try{r(R),h.emit(null,{internal:!0}),a.append({eventType:v,status:"success",aggregateId:R.aggregateId,event:R,t_ns:oe(),...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}}),k+=1}catch(N){if(h.emit(N,{internal:!0}),a.append({eventType:v,status:"failed",error:N,errorType:N instanceof Error?N.name:typeof N,aggregateId:R.aggregateId,event:R,t_ns:oe(),...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}}),d==="hold")break;k+=1}}T.emit(k)}}},{name:e,describeKind:"effect",meta:{...Hr("saga",{saga_name:e,source_events:n}),error:null}});return l.n=p,this.add(p,{name:e}),this._keepaliveDisposers.push(re(p)),this._sagas.add(e),{node:p,invocations:a,audit:a,cursors:i}}};function Ra(t,e){return new vs(t,e)}var Ea=class{constructor(e){this.graph=e}onModuleDestroy(){this.graph.destroy()}},Na=class{graph=new Y("request");onModuleDestroy(){this.graph.destroy()}},kc,Sa;kc=[(0,Wr.Module)({})];var zt=class zt{static forRoot(e){let n=e??{},r=n.name??"root",o=[{provide:ct,useFactory:()=>{let s=new Y(r);return n.build&&n.build(s),n.snapshot&&s.restore(n.snapshot),s}},{provide:Symbol.for("graphrefly:root-lifecycle"),useFactory:s=>new Ea(s),inject:[ct]},{provide:cn,useFactory:(s,i)=>new cn(s,i),inject:[ct,xc.ModuleRef]}];if(n.nodes)for(let s of n.nodes)o.push({provide:lt(s),useFactory:i=>i.resolve(s),inject:[ct]});return n.requestScope&&o.push({provide:Symbol.for("graphrefly:request-lifecycle"),useFactory:()=>new Na,scope:Wr.Scope.REQUEST},{provide:on,useFactory:s=>s.graph,inject:[Symbol.for("graphrefly:request-lifecycle")],scope:Wr.Scope.REQUEST}),{module:zt,global:!0,providers:o,exports:[ct,...(n.nodes??[]).map(lt),...n.requestScope?[on]:[]]}}static forFeature(e){let n=[{provide:ot(e.name),useFactory:r=>{let o=new Y(e.name);return e.build&&e.build(o),e.snapshot&&o.restore(e.snapshot),r.mount(e.name,o),o},inject:[ct]}];if(e.nodes)for(let r of e.nodes)n.push({provide:lt(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[ot(e.name)]});return{module:zt,providers:n,exports:[ot(e.name),...(e.nodes??[]).map(r=>lt(`${e.name}::${r}`))]}}static forCqrs(e){let n=[{provide:ot(e.name),useFactory:r=>{let o=Ra(e.name,e.cqrs);return e.eventStorage&&o.attachEventStorage(e.eventStorage),e.build&&e.build(o),r.mount(e.name,o),o},inject:[ct]}];if(e.nodes)for(let r of e.nodes)n.push({provide:lt(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[ot(e.name)]});return{module:zt,providers:n,exports:[ot(e.name),...(e.nodes??[]).map(r=>lt(`${e.name}::${r}`))]}}};Sa=rd(null),zt=id(Sa,0,"GraphReflyModule",kc,zt),sd(Sa,1,zt);var ws=zt;var xs={};ke(xs,{useStore:()=>vg,useSubscribe:()=>Rc,useSubscribeRecord:()=>Tg});var Lt=require("react");ae();function Rc(t){return(0,Lt.useSyncExternalStore)(e=>{let n=!1,r=t.subscribe(()=>{n||e()});return()=>{n=!0,r()}},()=>t.cache,()=>t.cache)}function vg(t){let e=Rc(t),n=(0,Lt.useCallback)(r=>{t.down([[ne],[E,r]])},[t]);return[e,n]}function Tg(t,e){let n=(0,Lt.useRef)(e);n.current=e;let r=(0,Lt.useMemo)(()=>{let o=()=>{let i={},a=t.cache??[];for(let u of a){let d=n.current(u),c={};for(let l of Object.keys(d))c[l]=d[l].cache;i[u]=c}return i},s=o();return{subscribe:i=>{let a=!1,u=[],d=()=>{for(let p of u)p();u=[]},c=p=>{d();for(let f of p){let m=n.current(f);for(let h of Object.keys(m)){let g=m[h].subscribe(()=>{s=o(),a||i()});u.push(g)}}s=o(),a||i()},l=t.subscribe(p=>{let f=p.some(m=>m[0]===E||m[0]===V);!a&&f&&c(t.cache??[])});return c(t.cache??[]),()=>{a=!0,l(),d()}},getSnapshot:()=>s}},[t]);return(0,Lt.useSyncExternalStore)(r.subscribe,r.getSnapshot,r.getSnapshot)}var Ss={};ke(Ss,{Signal:()=>wg});Me();ae();ee();var Qn=[];function Rs(t){let e=t.cache;return t.subscribe(r=>{for(let[o,s]of r)o===E&&(e=s)})(),e}var _a=class{_node;_equals;constructor(e,n){this._equals=n?.equals??Object.is,this._node=M(e,{...n,resubscribable:!0,resetOnTeardown:!0})}get(){let e=Qn[Qn.length-1];return e?(this._node.status==="sentinel"&&Rs(this._node),e(this._node)):this._node.status==="sentinel"?Rs(this._node):this._node.cache}set(e){this._equals(this.get(),e)||X(()=>{this._node.down([[ne],[E,e]])})}},Ma=class{_node;constructor(e,n){this._node=rn(r=>{Qn.push(r);try{return e()}finally{Qn.pop()}},{...n,describeKind:"derived",resubscribable:!0,resetOnTeardown:!0})}get(){let e=Qn[Qn.length-1];return e?(this._node.status==="sentinel"&&Rs(this._node),e(this._node)):this._node.status==="sentinel"?Rs(this._node):this._node.cache}},wg={State:_a,Computed:Ma,sub:(t,e)=>{let n=typeof e=="function"?{data:e,error:void 0,complete:void 0}:e,r=!0;return t._node.subscribe(o=>{for(let[s,i]of o){if(s===E){if(r){r=!1;continue}n.data?.(i)}s===C&&n.error?.(i),s===L&&n.complete?.()}})}};var Es={};ke(Es,{useStore:()=>kg,useSubscribe:()=>Sc,useSubscribeRecord:()=>xg});var It=require("solid-js");ae();function Sc(t){let[e,n]=(0,It.createSignal)(t.cache,{equals:!1}),r=t.subscribe(()=>{n(()=>t.cache)});return(0,It.getOwner)()?(0,It.onCleanup)(()=>r()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Solid reactive owner \u2014 subscription will not be auto-disposed."),e}function kg(t){return[Sc(t),r=>{t.down([[ne],[E,r]])}]}function xg(t,e){let[n,r]=(0,It.createSignal)({},{equals:!1}),o=[],s=()=>{for(let d of o)d();o=[]},i=()=>{let d={};for(let c of t.cache??[]){let l=e(c),p={};for(let f of Object.keys(l))p[f]=l[f].cache;d[c]=p}return d},a=d=>{s();for(let c of d){let l=e(c);for(let p of Object.keys(l)){let f=l[p].subscribe(()=>{r(()=>i())});o.push(f)}}r(()=>i())},u=t.subscribe(d=>{d.some(c=>c[0]===E||c[0]===V)&&a(t.cache??[])});return a(t.cache??[]),(0,It.getOwner)()?(0,It.onCleanup)(()=>{u(),s()}):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribeRecord called outside a Solid reactive owner \u2014 subscription will not be auto-disposed."),n}var Ns={};ke(Ns,{useStore:()=>Sg,useSubscribe:()=>Rg,useSubscribeRecord:()=>Eg});ae();function Rg(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n}}}function Sg(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n},set(e){t.down([[ne],[E,e]])},update(e){let n=e(t.cache);t.down([[ne],[E,n]])}}}function Eg(t,e){return{subscribe(n){let r=[],o=()=>{for(let u of r)u();r=[]},s=()=>{let u={};for(let d of t.cache??[]){let c=e(d),l={};for(let p of Object.keys(c))l[p]=c[p].cache;u[d]=l}return u},i=u=>{o();for(let d of u){let c=e(d);for(let l of Object.keys(c)){let p=c[l].subscribe(()=>{n(s())});r.push(p)}}n(s())},a=t.subscribe(u=>{u.some(d=>d[0]===E||d[0]===V)&&i(t.cache??[])});return i(t.cache??[]),()=>{a(),o()}}}}var _s={};ke(_s,{useStore:()=>_g,useSubscribe:()=>Ng,useSubscribeRecord:()=>Mg});var Ke=require("vue");ae();function Ng(t){let e=(0,Ke.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,Ke.getCurrentScope)()?(0,Ke.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Ke.readonly)(e)}function _g(t){let e=(0,Ke.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,Ke.getCurrentScope)()?(0,Ke.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useStore called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Ke.computed)({get:()=>e.value,set:r=>{t.down([[ne],[E,r]])}})}function Mg(t,e){let n=(0,Ke.shallowRef)({}),r=new Map;function o(){let a={};for(let[u,d]of r)a[u]={...d.values};n.value=a}function s(a){for(let d of r.values())for(let c of d.subs)c();r.clear();for(let d of a){let c=e(d),l=Object.keys(c),p={},f=[];for(let m of l){let h=c[m];p[m]=h.cache;let g=h.subscribe(()=>{p[m]=h.cache,o()});f.push(g)}r.set(d,{subs:f,values:p})}let u={};for(let[d,c]of r)u[d]={...c.values};n.value=u}return(0,Ke.watch)(()=>[...(typeof t=="function"?t():(0,Ke.isRef)(t)?t.value:t)??[]],a=>s(a??[]),{immediate:!0}),(0,Ke.getCurrentScope)()?(0,Ke.onScopeDispose)(()=>{for(let a of r.values())for(let u of a.subs)u();r.clear()}):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribeRecord called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Ke.readonly)(n)}var Ms={};ke(Ms,{create:()=>Cg});ae();ee();var Og=()=>!1;function Cg(t){let e=new Y("zustand"),n=M(void 0,{name:"state",equals:Og});e.add(n,{name:"state"});let r=()=>n.cache,o=(a,u)=>{let d=n.cache,c=typeof a=="function"?a(d):a;n.emit(u?c:{...d,...c})},s={getState:r,setState:o,getInitialState:()=>i,subscribe:a=>{let u=!0,d=n.cache;return n.subscribe(c=>{for(let[l,p]of c)if(l===E){if(u){u=!1;continue}a(p,d),d=p}})},destroy:e.destroy.bind(e)},i=t(o,r,s);return n.emit(i),Object.assign(e,s)}var Wa={};ke(Wa,{CircuitOpenError:()=>pt,ContentAddressedMissError:()=>eo,NS_PER_MS:()=>He,NS_PER_SEC:()=>at,NativeIndexBackend:()=>ro,NativeListBackend:()=>oo,NativeLogBackend:()=>jr,NativeMapBackend:()=>Xr,NativePubSubBackend:()=>no,RateLimiterOverflowError:()=>an,ResettableTimer:()=>Le,TimeoutError:()=>un,appendLogStorage:()=>Ka,audit:()=>zc,awaitSettled:()=>es,buffer:()=>Uc,bufferCount:()=>Jc,bufferTime:()=>Qc,cached:()=>Kd,canonicalJson:()=>to,cascadingCache:()=>sp,catchError:()=>al,checkpointToRedis:()=>Ql,checkpointToS3:()=>Yl,circuitBreaker:()=>wt,combine:()=>Aa,combineLatest:()=>ol,concat:()=>jc,concatMap:()=>Kc,constant:()=>qo,contentAddressedStorage:()=>Ps,createTransport:()=>Jt,createWatermarkController:()=>Un,csvRows:()=>Al,debounce:()=>Ia,debounceTime:()=>sl,decorrelatedJitter:()=>Uo,defer:()=>jd,delay:()=>Hc,deserializeError:()=>yn,dictKv:()=>bp,dictSnapshot:()=>vp,distill:()=>Ls,distinctUntilChanged:()=>Gc,elementAt:()=>Ic,empty:()=>Gd,escapeRegexChar:()=>ca,exhaustMap:()=>Vc,exponential:()=>Wo,externalBundle:()=>Os,externalProducer:()=>mn,fallback:()=>Hn,fibonacci:()=>zo,filter:()=>Xe,find:()=>Lc,first:()=>Cs,firstValueFrom:()=>Ye,firstWhere:()=>Yo,flatMap:()=>qc,forEach:()=>qt,fromAny:()=>U,fromAsyncIter:()=>Ir,fromCSV:()=>Cl,fromClickHouseWatch:()=>Dl,fromCron:()=>Qo,fromDrizzle:()=>np,fromEvent:()=>Dd,fromHTTP:()=>$a,fromHTTPPoll:()=>yl,fromHTTPStream:()=>hl,fromIter:()=>Xo,fromKafka:()=>Nl,fromKysely:()=>rp,fromMCP:()=>Tl,fromNATS:()=>$l,fromNDJSON:()=>Pl,fromOTel:()=>wl,fromPrisma:()=>tp,fromPrometheus:()=>El,fromPromise:()=>zn,fromPulsar:()=>Gl,fromRabbitMQ:()=>Bl,fromRaf:()=>Pd,fromRedisStream:()=>Ml,fromSSE:()=>gl,fromSqlite:()=>Xl,fromSqliteCursor:()=>Zl,fromStatsD:()=>Rl,fromSyslog:()=>kl,fromTimer:()=>st,fromWebSocket:()=>Fa,fromWebSocketReconnect:()=>vl,fromWebhook:()=>ul,globToRegExp:()=>Ld,interval:()=>el,jsonCodec:()=>tr,jsonCodecFor:()=>gp,keepalive:()=>re,kvStorage:()=>js,last:()=>Ac,linear:()=>Ho,lru:()=>Va,makeHttpError:()=>ht,map:()=>zr,matchesAnyPattern:()=>Id,matchesCron:()=>Ko,memoryAppendLog:()=>yp,memoryBackend:()=>io,memoryKv:()=>ao,memorySnapshot:()=>hp,merge:()=>xt,mergeMap:()=>La,mergeReactiveLogs:()=>bc,nameToSignal:()=>gn,ndjsonRows:()=>Ll,never:()=>Fd,nodeSignal:()=>ts,of:()=>la,onFirstData:()=>Jr,pairwise:()=>Fc,parseCron:()=>Vo,parsePrometheusText:()=>ja,parseSSEStream:()=>Dt,parseStatsD:()=>Sl,parseSyslog:()=>xl,pausable:()=>nl,pubsub:()=>cp,race:()=>Bc,rateLimiter:()=>qn,reactiveCounter:()=>pa,reactiveIndex:()=>fp,reactiveList:()=>Ds,reactiveLog:()=>Ve,reactiveMap:()=>Ze,reactiveSink:()=>We,reduce:()=>Mc,repeat:()=>tl,replay:()=>Zo,rescue:()=>Yr,resolveBackoffPreset:()=>Bt,retry:()=>Tt,sample:()=>Wc,scan:()=>_c,serializeError:()=>hn,share:()=>Vd,shareReplay:()=>qd,signalToName:()=>Ut,singleFromAny:()=>Gs,singleNodeFromAny:()=>mp,skip:()=>Ca,snapshotStorage:()=>$s,sortJsonValue:()=>so,stableJsonString:()=>Fs,stratify:()=>uo,switchMap:()=>Te,take:()=>Ur,takeUntil:()=>Cc,takeWhile:()=>Oc,tap:()=>Pc,tapFirst:()=>Dc,throttle:()=>Pa,throttleTime:()=>il,throwError:()=>$d,timeout:()=>Wn,toArray:()=>Bd,toCSV:()=>Kl,toClickHouse:()=>ql,toFile:()=>Ba,toHTTP:()=>dl,toKafka:()=>_l,toLoki:()=>Ul,toMongo:()=>zl,toNATS:()=>jl,toObservable:()=>Bo,toPostgres:()=>Wl,toPulsar:()=>Fl,toRabbitMQ:()=>Vl,toReadableStream:()=>ml,toRedisStream:()=>Ol,toS3:()=>Hl,toSSE:()=>pl,toSSEBytes:()=>fl,toSqlite:()=>ep,toTempo:()=>Jl,toWebSocket:()=>bl,tokenBucket:()=>Vt,valve:()=>rl,verifiable:()=>up,window:()=>Zc,windowCount:()=>Yc,windowTime:()=>Xc,withBreaker:()=>Kn,withLatestFrom:()=>Pt,withMaxAttempts:()=>ua,withStatus:()=>Kt,workerBridge:()=>qa,workerSelf:()=>Ha,zip:()=>$c});Me();xe();ae();_e();ee();Me();ae();ee();function Ec(t){return{describeKind:"producer",...t}}function mn(t,e){return K(n=>{let r=!0,o={emit(i){r&&n.emit(i)},error(i){r&&(r=!1,n.down([[C,i]]))},complete(){r&&(r=!1,n.down([[L]]))}},s;try{let i=t(o);s=typeof i=="function"?i:void 0}catch(i){return o.error(i),()=>{r=!1}}return()=>{r=!1;try{s?.()}catch{}}},Ec(e))}function Os(t,e,n){let r=!0,o,s=0,i=0,a={},u=[],d=()=>{let f=o;o=void 0;try{f?.()}catch{}};for(let f of e){let m=n?.name?`${n.name}::${f}`:f,h=n?.channelOpts?.[f],g=K(y=>(s++,()=>{i++,s>0&&i>=s&&i>=e.length&&d()}),Ec({...h,name:m}));a[f]=g,u.push(g)}let c={};for(let f of e)c[f]=m=>{r&&a[f].down([[E,m]])};c.error=f=>{r&&(r=!1,X(()=>{for(let m of u)m.down([[C,f]])}),d())},c.complete=()=>{r&&(r=!1,X(()=>{for(let f of u)f.down([[L]])}),d())};let l=t(c);return o=typeof l=="function"?l:void 0,Object.assign(a,{dispose:()=>{r&&(r=!1,X(()=>{for(let f of u)try{f.down([[L]])}catch{}}),d())}})}xe();ae();_e();ee();he();function ue(t){return{describeKind:"derived",...t}}function Nc(t){return{describeKind:"derived",partial:!0,...t}}function zr(t,e,n){return z([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[V]]);return}for(let i of s)o.emit(e(i))},ue(n))}function Xe(t,e,n){return z([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[V]]);return}let i=!1;for(let a of s)e(a)&&(o.emit(a),i=!0);i||o.down([[V]])},ue(n))}function _c(t,e,n,r){return z([t],(o,s,i)=>{"acc"in i.store||(i.store.acc=n);let a=o[0];if(a==null||a.length===0){s.down([[V]]);return}for(let u of a)i.store.acc=e(i.store.acc,u),s.emit(i.store.acc)},{...ue(r),initial:n,resetOnTeardown:!0})}function Mc(t,e,n,r){return z([t],(o,s,i)=>{if("acc"in i.store||(i.store.acc=n),i.terminalDeps[0]===!0){s.emit(i.store.acc),s.down([[L]]);return}let a=o[0];if(a==null||a.length===0){s.down([[V]]);return}for(let u of a)i.store.acc=e(i.store.acc,u)},{...ue(r),completeWhenDepsComplete:!1})}function Ur(t,e,n){return e<=0?z([t],(r,o,s)=>{s.store.completed||(s.store.completed=!0,o.down([[L]]))},{...ue(n),completeWhenDepsComplete:!1}):z([t],(r,o,s)=>{if("taken"in s.store||(s.store.taken=0),s.store.done){o.down([[V]]);return}if(s.terminalDeps[0]===!0){s.store.done=!0,o.down([[L]]);return}let i=r[0];if(i==null||i.length===0){o.down([[V]]);return}for(let a of i)if(s.store.taken++,o.emit(a),s.store.taken>=e){s.store.done=!0,o.down([[L]]);return}},{...ue(n),completeWhenDepsComplete:!1})}function Ca(t,e,n){return z([t],(r,o,s)=>{"skipped"in s.store||(s.store.skipped=0);let i=r[0];if(i==null||i.length===0){o.down([[V]]);return}let a=!1;for(let u of i)s.store.skipped++,s.store.skipped<=e||(o.emit(u),a=!0);a||o.down([[V]])},ue(n))}function Oc(t,e,n){return z([t],(r,o,s)=>{if(s.store.done){o.down([[V]]);return}let i=r[0];if(i==null||i.length===0){o.down([[V]]);return}for(let a of i){if(!e(a)){s.store.done=!0,o.down([[L]]);return}o.emit(a)}},{...ue(n),completeWhenDepsComplete:!1})}function Cc(t,e,n){let r=n?.predicate??(i=>i[0]===E),{predicate:o,...s}=n??{};return K(i=>{let a=!1,u=t.subscribe(c=>{if(!a)for(let l of c){if(a)return;l[0]===E?i.emit(l[1]):(l[0]===L||l[0]===C)&&(a=!0,i.down([l]))}}),d=e.subscribe(c=>{if(!a)for(let l of c){if(a)return;if(r(l)){a=!0,i.down([[L]]);return}}});return()=>{u(),d()}},ue(s))}function Cs(t,e){return Ur(t,1,e)}function Ac(t,e){let{defaultValue:n,...r}=e??{},o=e!=null&&Object.hasOwn(e,"defaultValue");return z([t],(s,i,a)=>{if(a.terminalDeps[0]===!0){a.store.has?i.emit(a.store.latest):o&&i.emit(n),i.down([[L]]);return}let u=s[0];if(u==null||u.length===0){i.down([[V]]);return}a.store.latest=u.at(-1),a.store.has=!0},{...ue(r),completeWhenDepsComplete:!1})}function Lc(t,e,n){return Ur(Xe(t,e,n),1,n)}function Ic(t,e,n){return Ur(Ca(t,e,n),1,n)}function Pc(t,e,n){if(typeof e=="function")return z([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[V]]);return}for(let a of i)e(a),s.emit(a)},ue(n));let r=e;return z([t],(o,s,i)=>{if(i.terminalDeps[0]!==void 0){i.terminalDeps[0]===!0?(r.complete?.(),s.down([[L]])):(r.error?.(i.terminalDeps[0]),s.down([[C,i.terminalDeps[0]]]));return}let a=o[0];if(a==null||a.length===0){s.down([[V]]);return}for(let u of a)r.data?.(u),s.emit(u)},{...ue(n),completeWhenDepsComplete:!1})}function Jr(t,e,n){let r=n?.where??(s=>s!=null),o=!1;return z([t],(s,i)=>{let a=s[0];if(a==null||a.length===0){i.down([[V]]);return}for(let u of a)!o&&r(u)&&(o=!0,e(u)),i.emit(u)},ue(n))}var Dc=Jr;function Gc(t,e=Object.is,n){return z([t],(r,o,s)=>{let i=r[0];if(i==null||i.length===0){o.down([[V]]);return}let a=!1;for(let u of i)s.store.hasPrev&&e(s.store.prev,u)||(s.store.prev=u,s.store.hasPrev=!0,o.emit(u),a=!0);a||o.down([[V]])},ue(n))}function Fc(t,e){return z([t],(n,r,o)=>{let s=n[0];if(s==null||s.length===0){r.down([[V]]);return}let i=!1;for(let a of s)if(!o.store.hasPrev)o.store.prev=a,o.store.hasPrev=!0;else{let u=[o.store.prev,a];o.store.prev=a,r.emit(u),i=!0}i||r.down([[V]])},ue(e))}function Aa(...t){let e=[...t];return A(e,n=>n,{...ue(),equals:(n,r)=>{if(n.length!==r.length)return!1;for(let o=0;o<n.length;o++)if(!Object.is(n[o],r[o]))return!1;return!0}})}function Pt(t,e,n){return z([t,e],(r,o,s)=>{let i=r[0],a=r[1],u=a!=null&&a.length>0?a.at(-1):s.prevData[1];if(i!=null&&i.length>0){if(!(a!=null&&a.length>0)&&s.prevData[1]===void 0){o.down([[V]]);return}for(let d of i)o.emit([d,u])}else o.down([[V]])},Nc(n))}function xt(...t){return t.length===0?K(e=>{e.down([[L]])},ue()):K(e=>{let n=t.length,r=0,o=[];for(let s of t){let i=s.subscribe(a=>{for(let u of a)u[0]===E?e.emit(u[1]):u[0]===L?(r+=1,r>=n&&e.down([[L]])):u[0]===C&&e.down([u])});o.push(i)}return()=>{for(let s of o)s()}},ue())}function $c(...t){let e=t.length;return e===0?K(n=>{n.emit([]),n.down([[L]])},ue()):K(n=>{let r=Array.from({length:e},()=>[]),o=e;function s(){for(;r.every(a=>a.length>0);){let a=r.map(u=>u.shift());n.emit(a)}}let i=[];for(let a=0;a<e;a++){let u=a,d=t[a].subscribe(c=>{for(let l of c)l[0]===E?(r[u].push(l[1]),s()):l[0]===L?(o-=1,(o===0||r[u].length===0)&&n.down([[L]])):l[0]===C&&n.down([l])});i.push(d)}return()=>{for(let a of i)a()}},ue())}function jc(t,e,n){return K(r=>{let o=0,s=[],i,a;return a=e.subscribe(u=>{for(let d of u)o===0?d[0]===E?s.push(d[1]):d[0]===C&&r.down([d]):d[0]===E?r.emit(d[1]):(d[0]===L||d[0]===C)&&r.down([d])}),i=t.subscribe(u=>{for(let d of u)if(o===0)if(d[0]===E)r.emit(d[1]);else if(d[0]===L){o=1;for(let c of s)r.emit(c);s.length=0}else d[0]===C&&r.down([d])}),()=>{i?.(),a?.()}},ue(n))}function Bc(...t){return t.length===0?K(e=>{e.down([[L]])},ue()):t.length===1?z([t[0]],(e,n)=>{let r=e[0];if(r==null||r.length===0){n.down([[V]]);return}for(let o of r)n.emit(o)},ue()):K(e=>{let n=null,r=[];for(let o=0;o<t.length;o++){let s=o,i=t[o].subscribe(a=>{for(let u of a){if(n!==null&&s!==n)return;u[0]===E?(n===null&&(n=s),e.emit(u[1])):(u[0]===L||u[0]===C)&&(n===null||s===n)&&e.down([u])}});r.push(i)}return()=>{for(let o of r)o()}},ue())}function As(t,e,n){let r,o=!1,s=()=>{o||(o=!0,n())};return r=t.subscribe(i=>{let a=!1,u=!1;for(let d of i)d[0]!==dt&&(d[0]===E?e.emit(d[1]):d[0]===L?a=!0:d[0]===C?(u=!0,e.down([d])):(d[0]===ne||d[0]===V)&&e.down([d]));u?(r?.(),r=void 0,s()):a&&s()}),()=>{r?.(),r=void 0}}function Te(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return z([t],(i,a,u)=>{if(u.terminalDeps[0]!=null&&u.terminalDeps[0]!==!0){s();return}if(u.terminalDeps[0]===!0){o=!0,r||a.down([[L]]);return}let d=i[0];if(!(d==null||d.length===0))return s(),r=As(U(e(d[d.length-1])),a,()=>{s(),o&&a.down([[L]])}),{deactivate:()=>{s(),o=!1}}},{...ue(n),completeWhenDepsComplete:!1})}function Vc(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return z([t],(i,a,u)=>{if(u.terminalDeps[0]!=null&&u.terminalDeps[0]!==!0){s();return}if(u.terminalDeps[0]===!0){o=!0,r||a.down([[L]]);return}let d=i[0];if(!(d==null||d.length===0))return r===void 0?r=As(U(e(d[0])),a,()=>{s(),o&&a.down([[L]])}):a.down([[V]]),{deactivate:()=>{s(),o=!1}}},{...ue(n),completeWhenDepsComplete:!1})}function Kc(t,e,n){let{maxBuffer:r,...o}=n??{},s=[],i,a=!1,u;function d(){i?.(),i=void 0}function c(){if(!u||i!==void 0)return;if(s.length===0){a&&u.down([[L]]);return}let p=s.shift();i=As(U(e(p)),u,()=>{d(),c()})}function l(p){r&&r>0&&s.length>=r&&s.shift(),s.push(p),c()}return z([t],(p,f,m)=>{if(u=f,m.terminalDeps[0]!=null&&m.terminalDeps[0]!==!0){d(),s.length=0;return}if(m.terminalDeps[0]===!0){a=!0,c();return}let h=p[0];if(!(h==null||h.length===0)){for(let g of h)l(g);return{deactivate:()=>{d(),s.length=0,a=!1}}}},{...ue(o),completeWhenDepsComplete:!1})}function La(t,e,n){let{concurrent:r,...o}=n??{},s=r!=null&&r>0?r:Number.POSITIVE_INFINITY,i=0,a=!1,u=new Set,d=[],c;function l(){a&&i===0&&d.length===0&&c&&c.down([[L]])}function p(g){if(!c)return;i++;let y;y=As(U(e(g)),c,()=>{y&&u.delete(y),i--,f(),l()}),u.add(y)}function f(){for(;d.length>0&&i<s;)p(d.shift())}function m(g){i<s?p(g):d.push(g)}function h(){for(let g of u)g();u.clear(),i=0,d.length=0}return z([t],(g,y,b)=>{if(c=y,b.terminalDeps[0]!=null&&b.terminalDeps[0]!==!0){h();return}if(b.terminalDeps[0]===!0){a=!0,l();return}let v=g[0];if(!(v==null||v.length===0)){for(let T of v)m(T);return{deactivate:()=>{h(),a=!1}}}},{...ue(o),completeWhenDepsComplete:!1})}var qc=La;function Hc(t,e,n){return K(r=>{let o=new Set;function s(){for(let a of o)clearTimeout(a);o.clear()}let i=t.subscribe(a=>{for(let u of a)if(u[0]===E){let d=setTimeout(()=>{o.delete(d),r.emit(u[1])},e);o.add(d)}else if(u[0]===L){let d=setTimeout(()=>{o.delete(d),r.down([[L]])},e);o.add(d)}else u[0]===C&&(s(),r.down([u]))});return()=>{i(),s()}},ue(n))}function Ia(t,e,n){return K(r=>{let o,s;function i(){o!==void 0&&(clearTimeout(o),o=void 0)}let a=t.subscribe(u=>{for(let d of u)d[0]===E?(i(),s=d[1],o=setTimeout(()=>{o=void 0,r.emit(s)},e)):d[0]===L?(o!==void 0&&(i(),r.emit(s)),r.down([[L]])):d[0]===C&&(i(),r.down([d]))});return()=>{a(),i()}},ue(n))}function Pa(t,e,n){let{leading:r,trailing:o,...s}=n??{},i=r!==!1,a=o===!0,u=e*1e6;return K(d=>{let c,l=-1/0,p,f=!1;function m(){c!==void 0&&(clearTimeout(c),c=void 0)}let h=t.subscribe(g=>{for(let y of g)if(y[0]===E){let b=y[1],v=H();if(i&&v-l>=u)l=v,d.emit(b),m(),a&&(c=setTimeout(()=>{c=void 0,f&&(l=H(),d.emit(p),f=!1)},e));else if(a&&(p=b,f=!0,c===void 0)){let T=(v-l)/1e6;c=setTimeout(()=>{c=void 0,f&&(l=H(),d.emit(p),f=!1)},Math.max(0,e-T))}}else(y[0]===L||y[0]===C)&&(m(),d.down([y]))});return()=>{h(),m()}},ue(s))}function Wc(t,e,n){return K(r=>{let o,s=!1,i=!1,a=t.subscribe(d=>{if(!s)for(let c of d){if(s)return;c[0]===E?o={v:c[1]}:c[0]===C?(s=!0,r.down([c])):c[0]===L&&(i=!0,o=void 0)}}),u=e.subscribe(d=>{if(!s)for(let c of d){if(s)return;c[0]===E?o!==void 0&&!i&&r.emit(o.v):c[0]===C?(s=!0,r.down([c])):c[0]===L&&(s=!0,r.down([[L]]))}});return()=>{a(),u()}},ue(n))}function zc(t,e,n){return K(r=>{let o,s,i=!1;function a(){o!==void 0&&(clearTimeout(o),o=void 0)}let u=t.subscribe(d=>{for(let c of d)c[0]===E?(s=c[1],i=!0,a(),o=setTimeout(()=>{o=void 0,i&&(i=!1,r.emit(s))},e)):(c[0]===L||c[0]===C)&&(a(),r.down([c]))});return()=>{u(),a()}},ue(n))}function Uc(t,e,n){return K(r=>{let o=[],s=t.subscribe(a=>{for(let u of a)u[0]===E?o.push(u[1]):u[0]===L?(o.length>0&&r.emit([...o]),o.length=0,r.down([[L]])):u[0]===C&&r.down([u])}),i=e.subscribe(a=>{for(let u of a)u[0]===E?o.length>0&&(r.emit([...o]),o.length=0):u[0]===L?r.down([[L]]):u[0]===C&&r.down([u])});return()=>{s(),i(),o.length=0}},ue(n))}function Jc(t,e,n){if(e<=0)throw new RangeError("bufferCount expects count > 0");return K(r=>{let o=[],s=t.subscribe(i=>{for(let a of i)a[0]===E?(o.push(a[1]),o.length>=e&&r.emit(o.splice(0,o.length))):a[0]===L?(o.length>0&&r.emit([...o]),o.length=0,r.down([[L]])):a[0]===C&&r.down([a])});return()=>{s(),o.length=0}},ue(n))}function Yc(t,e,n){if(e<=0)throw new RangeError("windowCount expects count > 0");return K(r=>{let o,s=0;function i(){let u=K(d=>(o=d.down.bind(d),()=>{o=void 0}),ue());s=0,r.emit(u)}let a=t.subscribe(u=>{for(let d of u)d[0]===E?(o||i(),o?.([[E,d[1]]]),s+=1,s>=e&&(o?.([[L]]),o=void 0)):d[0]===L?(o?.([[L]]),o=void 0,r.down([[L]])):d[0]===C&&(o?.([d]),o=void 0,r.down([d]))});return()=>{a(),o?.([[L]]),o=void 0}},ue(n))}function Qc(t,e,n){return K(r=>{let o=[],s=setInterval(()=>{o.length>0&&(r.emit([...o]),o.length=0)},e),i=t.subscribe(a=>{for(let u of a)u[0]===E?o.push(u[1]):u[0]===L?(clearInterval(s),o.length>0&&r.emit([...o]),o.length=0,r.down([[L]])):u[0]===C&&(clearInterval(s),r.down([u]))});return()=>{i(),clearInterval(s),o.length=0}},ue(n))}function Xc(t,e,n){return K(r=>{let o;function s(){o?.([[L]]),o=void 0}function i(){let d=K(c=>(o=c.down.bind(c),()=>{o=void 0}),ue());r.emit(d)}i();let a=setInterval(()=>{s(),i()},e),u=t.subscribe(d=>{for(let c of d)c[0]===E?o?.([[E,c[1]]]):c[0]===L?(clearInterval(a),s(),r.down([[L]])):c[0]===C&&(clearInterval(a),o?.([c]),s(),r.down([c]))});return()=>{u(),clearInterval(a),s()}},ue(n))}function Zc(t,e,n){return K(r=>{let o;function s(){o?.([[L]]),o=void 0}function i(){let d=K(c=>(o=c.down.bind(c),()=>{o=void 0}),ue());r.emit(d)}let a=t.subscribe(d=>{for(let c of d)c[0]===E?(o||i(),o?.([[E,c[1]]])):c[0]===L?(s(),r.down([[L]])):c[0]===C&&(o?.([c]),o=void 0,r.down([c]))}),u=e.subscribe(d=>{for(let c of d)c[0]===E&&(s(),i())});return()=>{a(),u(),s()}},ue(n))}function el(t,e){return K((n,r)=>{"n"in r.store||(r.store.n=0);let o=setInterval(()=>{n.emit(r.store.n),r.store.n=r.store.n+1},t);return()=>clearInterval(o)},ue(e))}function tl(t,e,n){if(e<=0)throw new RangeError("repeat expects count > 0");return K(r=>{let o=e,s,i=()=>{s?.(),s=t.subscribe(a=>{let u=!1,d=[];for(let c of a)c[0]===L?u=!0:d.push(c);d.length>0&&r.down(d),u&&(s?.(),s=void 0,o-=1,o>0?i():r.down([[L]]))})};return i(),()=>{s?.()}},ue(n))}function nl(t,e){return z([t],(n,r)=>{let o=n[0];if(o==null||o.length===0){r.down([[V]]);return}for(let s of o)r.emit(s)},ue(e))}function Yr(t,e,n){return K(r=>{let o=t.subscribe(s=>{for(let i of s)if(i[0]===E)r.emit(i[1]);else if(i[0]===C)try{r.emit(e(i[1]))}catch(a){r.down([[C,a]])}else i[0]===L&&r.down([[L]])});return()=>{o()}},ue(n))}function rl(t,e,n){return z([t,e],(r,o,s)=>{let i=r[1];if(!(i!=null&&i.length>0?i.at(-1):s.prevData[1])){o.down([[V]]);return}let u=r[0];if(u!=null&&u.length>0){for(let d of u)o.emit(d);return}if(i!=null&&i.length>0&&s.prevData[0]!==void 0){o.emit(s.prevData[0]);return}o.down([[V]])},Nc(n))}var ol=Aa,sl=Ia,il=Pa,al=Yr;ae();_e();ee();Vn();var Da=class{ring;arr;constructor(e){e===Number.POSITIVE_INFINITY||e<=0?(this.arr=[],this.ring=null):(this.ring=new ln(e),this.arr=null)}get length(){return this.ring!=null?this.ring.size:this.arr.length}push(e){this.ring!=null?this.ring.push(e):this.arr.push(e)}shift(){return this.ring!=null?this.ring.shift():this.arr.shift()}drain(){if(this.ring!=null){let n=this.ring.toArray();return this.ring.clear(),n}let e=this.arr;return this.arr=[],e}};function Qr(t){return t instanceof Error?t:new Error(String(t))}function Ag(t){return t===void 0?null:typeof t=="string"?Bt(t):t}function We(t,e){let{name:n,onTransportError:r,retry:o,backpressure:s,batchSize:i=Number.POSITIVE_INFINITY,flushIntervalMs:a=0,serialize:u,stopOn:d,onUpstreamMessage:c,onDispose:l,send:p,sendBatch:f,ctx:m}=e;if(!p&&!f)throw new Error("reactiveSink: `send` or `sendBatch` must be provided");let h=m,g=Math.max(1,o?.maxAttempts??1),y=Ag(o?.backoff??(g>1?"exponential":void 0)),b=o?.shouldRetry??(()=>!0),v=f!==void 0||i<Number.POSITIVE_INFINITY||a>0,T=W=>n?`${n}::${W}`:void 0,w=M(void 0,{equals:()=>!1,name:T("sent")}),x=M(null,{name:T("failed")}),k=M(0,{name:T("inFlight")}),S=M(null,{name:T("errors")}),R=v?M(0,{name:T("buffered")}):void 0,N=s?M(!1,{name:T("paused")}):void 0,_=0,I=W=>{_+=W,k.down([[E,_]])},O=W=>{try{r?.(W)}catch{}try{S.down([[E,W]])}catch{}},P=new Set,B=W=>{P.add(W);let de=()=>P.delete(W);W.then(de,de)},j=(W,de,Se)=>{let Ee=y?y(de-1,Se,null):0,ce=Ee==null?0:typeof Ee=="number"&&Ee>0?Ee:0,Pe=Math.max(1,Math.ceil(ce/1e6));return new Promise(me=>{setTimeout(()=>me(W()),Pe)})},D=W=>W!=null&&typeof W=="object"&&typeof W.then=="function",Z=W=>{let de;try{de=u?u(W):W}catch(me){let ge=Qr(me);return O({stage:"serialize",error:ge,value:W}),x.down([[E,{value:W,error:ge,attempts:0}]]),Promise.resolve()}let Se=0,Ee=me=>{I(-1);let ge=Qr(me);if(O({stage:"send",error:ge,value:W,attempt:Se}),!(Se<g&&b(ge,Se))){x.down([[E,{value:W,error:ge,attempts:Se}]]);return}return j(Pe,Se,ge)},ce=()=>{I(-1),w.down([[E,W]])};function Pe(){Se+=1,I(1);let me;try{me=p(de,h)}catch(ge){return Ee(ge)??Promise.resolve()}return D(me)?me.then(ce,ge=>Ee(ge)):(ce(),Promise.resolve())}return Pe()},F=s?.maxBuffer??Number.POSITIVE_INFINITY,Q=new Da(F),G,q=!1,$=()=>{R?.down([[E,Q.length]])},te=W=>{N&&N.down([[E,W]])},Re=s?.strategy??"drop-oldest",Oe=(W,de)=>{let Se={value:W,payload:de};if(Q.length<F)return Q.push(Se),$(),!0;if(Re==="drop-oldest"){let ce=Q.shift();return Q.push(Se),$(),te(!0),x.down([[E,{value:ce.value,error:new Error("backpressure: buffer overflow \u2014 dropped oldest"),attempts:0}]]),!0}if(Re==="drop-newest")return te(!0),x.down([[E,{value:W,error:new Error("backpressure: buffer overflow \u2014 dropped newest"),attempts:0}]]),!1;let Ee=new Error("backpressure: buffer overflow");return O({stage:"send",error:Ee,value:W}),x.down([[E,{value:W,error:Ee,attempts:0}]]),te(!0),!1},Ce=W=>{let de=0,Se=W.map(me=>me.payload),Ee=me=>{I(-1);let ge=Qr(me);if(O({stage:"send",error:ge,value:W.map(Sn=>Sn.value),attempt:de}),!(de<g&&b(ge,de))){for(let{value:Sn}of W)x.down([[E,{value:Sn,error:ge,attempts:de}]]);return}return j(Pe,de,ge)},ce=()=>{I(-1);for(let{value:me}of W)w.down([[E,me]])};function Pe(){de+=1,I(1);let me;try{me=f(Se,h)}catch(ge){return Ee(ge)??Promise.resolve()}return D(me)?me.then(ce,ge=>Ee(ge)):(ce(),Promise.resolve())}return Pe()},ye=async W=>{for(let de of W)await Ge(de.value,de.payload)},Ge=(W,de)=>{let Se=0,Ee=me=>{I(-1);let ge=Qr(me);if(O({stage:"send",error:ge,value:W,attempt:Se}),!(Se<g&&b(ge,Se))){x.down([[E,{value:W,error:ge,attempts:Se}]]);return}return j(Pe,Se,ge)},ce=()=>{I(-1),w.down([[E,W]])};function Pe(){Se+=1,I(1);let me;try{me=p(de,h)}catch(ge){return Ee(ge)??Promise.resolve()}return D(me)?me.then(ce,ge=>Ee(ge)):(ce(),Promise.resolve())}return Pe()},ie=()=>{if(q||Q.length===0)return Promise.resolve();let W=Q.drain();if($(),te(!1),f!==void 0){let Se=Ce(W);return B(Se),Se}let de=ye(W);return B(de),de},we=()=>{G!==void 0||q||a<=0||(G=setTimeout(()=>{G=void 0,ie()},a))},Fe=t.subscribe(W=>{for(let de of W){let Se=de[0];if(Se!==E)try{c?.(de)}catch{}if(Se===E){let Ee=de[1];if(v){let ce;if(u)try{ce=u(Ee)}catch(me){let ge=Qr(me);O({stage:"serialize",error:ge,value:Ee}),x.down([[E,{value:Ee,error:ge,attempts:0}]]);continue}else ce=Ee;if(!Oe(Ee,ce))continue;Q.length>=i?ie():we()}else{let ce=Z(Ee);B(ce)}}else $e.messageTier(Se)>=3&&v&&(G!==void 0&&(clearTimeout(G),G=void 0),ie())}}),be;if(d){let W=!1;be=d.subscribe(de=>{if(!W){W=!0;return}de.length>0&&!J&&se()})}let J=!1,se=()=>{if(J)return;J=!0,G!==void 0&&(clearTimeout(G),G=void 0),v&&ie(),q=!0,be?.(),Fe();let W=de=>{try{de.down([[le]])}catch{}};W(S),W(x),W(w),W(k),R&&W(R),N&&W(N);try{l?.()}catch{}},ve={dispose:se,sent:w,failed:x,inFlight:k,errors:S};return v&&(ve.buffered=R,ve.flush=async()=>{q||(await ie(),await Promise.all(P))}),N&&(ve.paused=N),ve}Ot();he();function gt(t){return{describeKind:"producer",...t}}function Fa(t,e){let{parse:n,closeOnTeardown:r=!1,...o}=e??{};return K(s=>{let i=!0,a,u=()=>{let y=a;a=void 0,y?.()},d=y=>{i&&(i=!1,s.down([y]),u())},c=(y,b=y)=>{if(i)try{let v=y!==null&&typeof y=="object"&&"data"in y?y.data:y,T=n?n(v,b):v;s.emit(T)}catch(v){d([C,v])}},l=y=>{d([C,y])},p=()=>{d([L])};if(typeof t=="function"){try{if(a=t(c,l,p),typeof a!="function")throw new Error("fromWebSocket register contract violation: register must return cleanup callable")}catch(y){d([C,y])}return()=>{i=!1,u()}}let f=t,m=y=>c(y,y),h=y=>l(y),g=()=>p();return f.addEventListener("message",m),f.addEventListener("error",h),f.addEventListener("close",g),a=()=>{f.removeEventListener("message",m),f.removeEventListener("error",h),f.removeEventListener("close",g),r&&f.close()},()=>{i=!1,u()}},gt(o))}function ul(t,e){return mn(t,e)}function $a(t,e){let{method:n="GET",headers:r,body:o,transform:s=v=>v.json(),timeoutNs:i=30*1e9,signal:a,completeAfterFetch:u=!1,refetchOnSubscribe:d=!1,...c}=e??{},l=M(0,{name:`${c.name??"http"}/fetchCount`}),p=M(0,{name:`${c.name??"http"}/lastUpdated`}),f=M(!1,{name:`${c.name??"http"}/fetched`}),m=0,h=o!==void 0?typeof o=="string"?o:JSON.stringify(o):void 0,g=v=>{let T=new AbortController,w=!0;if(a?.aborted)return w=!1,v.down([[C,a.reason??new Error("Aborted")]]),()=>{};a?.addEventListener("abort",()=>T.abort(a.reason),{once:!0});let x=setTimeout(()=>T.abort(new Error("Request timeout")),Math.ceil(i/1e6));return fetch(t,{method:n,headers:r,body:h,signal:T.signal}).then(async k=>{if(clearTimeout(x),!w)return;if(!k.ok)throw new Error(`HTTP ${k.status}: ${k.statusText}`);let S=await s(k);w&&(X(()=>{m+=1,l.down([[E,m]]),p.down([[E,oe()]]),f.down([[E,!0]]),v.emit(S)}),u&&v.down([[L]]))}).catch(k=>{clearTimeout(x),w&&(k&&k.name==="AbortError"||v.down([[C,k]]))}),()=>{w=!1,T.abort()}},y=K(v=>g({emit:T=>v.emit(T),down:T=>v.down(T)}),{...gt(c),resubscribable:d});return{...Kt(y),fetchCount:l,lastUpdated:p,fetched:f}}function dl(t,e,n){let{method:r="POST",headers:o={"Content-Type":"application/json"},serialize:s=m=>JSON.stringify(m),timeoutNs:i,batchFormat:a="json-array",batchSize:u,flushIntervalMs:d,retry:c,onTransportError:l}=n??{},p=async m=>{let h=i!==void 0?new AbortController:void 0,g;h&&i!==void 0&&(g=setTimeout(()=>h.abort(new Error("Request timeout")),Math.ceil(i/1e6)));try{let y=await fetch(e,{method:r,headers:o,body:m,signal:h?.signal}),b=async()=>{try{await y.arrayBuffer?.()}catch{}};if(!y.ok)throw await b(),new Error(`HTTP ${y.status}: ${y.statusText}`);await b()}finally{g!==void 0&&clearTimeout(g)}};return u!==void 0||d!==void 0?We(t,{onTransportError:l,retry:c,batchSize:u,flushIntervalMs:d,sendBatch:async m=>{let h;a==="ndjson"?h=m.map(g=>{let y=s(g);return typeof y=="string"?y:new TextDecoder().decode(y)}).join(`
|
|
16
|
-
`):h=JSON.stringify(m),await p(h)}}):
|
|
9
|
+
`,n}function Fm(t){return JSON.parse(t)}function $m(t,e){try{t.send(JSON.stringify(e))}catch{}}function xa(t,e){try{t(e)}catch{}}Mr();var cs="graphReflyActor";function Ra(t){return e=>{let r=e.switchToHttp().getRequest()?.user;if(r!=null)return t?t(r):r}}function ac(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 dc(t){let e=t?.[cs];return e!=null?Ot(e):xt}var Vr=class{constructor(e){this.extractor=e}canActivate(e){let n=Ot(this.extractor(e)),r=e.switchToHttp().getRequest();return r!=null&&(r[cs]=n),!0}};function uc(t){return new Vr(t??Ra())}var Zr=require("@nestjs/common"),Gc=require("@nestjs/core");Mr();Ae();Re();Vt();ae();it();Me();ne();Re();function Sa(t,e){if(Object.is(t,e))return!0;if(t==null||e==null||typeof t!="object"||typeof e!="object")return!1;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(let s=0;s<t.length;s++)if(!Sa(t[s],e[s]))return!1;return!0}if(Array.isArray(e))return!1;let n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;let o=new Set(r);for(let s of n)if(!o.has(s)||!Sa(t[s],e[s]))return!1;return!0}function cc(t,e){return`${t}\0${e}`}function er(t,e){let n=[],r=new Set(t.subgraphs),o=new Set(e.subgraphs),s=[];for(let g of o)r.has(g)||s.push(g);s.sort();for(let g of s)n.push({type:"subgraph-mounted",path:g});let i=new Set(Object.keys(t.nodes)),a=new Set(Object.keys(e.nodes)),d=[];for(let g of a)i.has(g)||d.push(g);d.sort();for(let g of d)n.push({type:"node-added",path:g,node:{...e.nodes[g]}});let u=[];for(let g of a){if(!i.has(g))continue;let y=t.nodes[g]?.meta,b=e.nodes[g]?.meta;y==null&&b==null||Sa(y??{},b??{})||u.push(g)}u.sort();for(let g of u)n.push({type:"node-meta-changed",path:g,prevMeta:t.nodes[g]?.meta??{},nextMeta:e.nodes[g]?.meta??{}});let c=new Map;for(let g of t.edges)c.set(cc(g.from,g.to),g);let l=new Map;for(let g of e.edges)l.set(cc(g.from,g.to),g);let p=[];for(let[g,y]of l)c.has(g)||p.push(y);p.sort((g,y)=>g.from<y.from?-1:g.from>y.from?1:g.to<y.to?-1:g.to>y.to?1:0);for(let g of p)n.push({type:"edge-added",from:g.from,to:g.to});let f=[];for(let[g,y]of c)l.has(g)||f.push(y);f.sort((g,y)=>g.from<y.from?-1:g.from>y.from?1:g.to<y.to?-1:g.to>y.to?1:0);for(let g of f)n.push({type:"edge-removed",from:g.from,to:g.to});let m=[];for(let g of i)a.has(g)||m.push(g);m.sort();for(let g of m)n.push({type:"node-removed",path:g});let h=[];for(let g of r)o.has(g)||h.push(g);h.sort();for(let g of h)n.push({type:"subgraph-unmounted",path:g});return{events:n,flushedAt_ns:V()}}ve();Rt();var gn=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}};jo();function Na(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 tr(t){let e=0;for(let n of t)e+=Na(n.codePointAt(0));return e}function lc(t,e){if(e<=0)return"";let n=0,r="";for(let o of t){let s=Na(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-=Na(i.codePointAt(0))}return`${r}\u2026`}r+=o,n+=s}return r}var jm={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"},Bm={horizontal:"-",vertical:"|",cornerTL:"+",cornerTR:"+",cornerBL:"+",cornerBR:"+",tDown:"+",tUp:"+",tRight:"+",tLeft:"+",cross:"+",arrowRight:">",arrowDown:"v",arrowLeft:"<",arrowUp:"^",boxTL:"+",boxTR:"+",boxBL:"+",boxBR:"+",boxH:"-",boxV:"|"};function gc(t,e){let n=e.charset==="ascii"?Bm:jm,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)Km(s,i,n,a);for(let a of t.boxes)Vm(s,i,n,a,e.labelOf(a.id));return s.map(a=>Wm(a.join(""))).join(`
|
|
10
|
+
`)}function Vm(t,e,n,r,o){let{x:s,y:i,w:a,h:d}=r;if(a<2||d<2){d>0&&pc(t,e,s,i,a,o);return}Ut(t,e,s,i,n.boxTL);for(let c=s+1;c<s+a-1;c+=1)Ut(t,e,c,i,n.boxH);Ut(t,e,s+a-1,i,n.boxTR);for(let c=i+1;c<i+d-1;c+=1){Ut(t,e,s,c,n.boxV);for(let l=s+1;l<s+a-1;l+=1)hc(t,e,l,c," ","empty");Ut(t,e,s+a-1,c,n.boxV)}Ut(t,e,s,i+d-1,n.boxBL);for(let c=s+1;c<s+a-1;c+=1)Ut(t,e,c,i+d-1,n.boxH);Ut(t,e,s+a-1,i+d-1,n.boxBR);let u=i+Math.floor(d/2);pc(t,e,s+1,u,a-2,o)}function Ut(t,e,n,r,o){hc(t,e,n,r,o,o===" "?"empty":o==="\u2500"||o==="-"?"boxH":o==="\u2502"||o==="|"?"boxV":"boxCorner")}function hc(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 pc(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=n,a=o;for(let d of s){let u=tr(d);if(u!==0){if(a<u)break;i>=0&&i<t[r].length&&(t[r][i]=d,e[r][i]="label",u===2&&i+1<t[r].length&&(t[r][i+1]="",e[r][i+1]="label")),i+=u,a-=u}}for(;a>0;)i>=0&&i<t[r].length&&(t[r][i]=" ",e[r][i]="empty"),i+=1,a-=1}function Km(t,e,n,r){let o=r.points;if(o.length<2)return;for(let d=0;d+1<o.length;d+=1)qm(t,e,n,o[d],o[d+1]);for(let d=1;d+1<o.length;d+=1){let u=o[d-1],c=o[d],l=o[d+1],p=zm(u,c,l,n);p&&mc(t,e,c.x,c.y,p,"edgeCorner")}let s=o[o.length-1],i=o[o.length-2],a=Hm(i,s,n);a&&mc(t,e,s.x,s.y,a,"arrow")}function qm(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 d=i;d<=a;d+=1)fc(t,e,d,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 d=i;d<=a;d+=1)fc(t,e,s,d,n,"v")}}}function fc(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 mc(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 zm(t,e,n,r){let o=t.y===e.y,s=e.y===n.y;if(o===s)return;if(o){let d=t.x<e.x,u=n.y>e.y;return d&&u?r.cornerTR:d&&!u?r.cornerBR:!d&&u?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 Hm(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 Wm(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}function vc(t){let e=Um(t);Jm(e),Ym(e),Qm(e),Xm(e,t);let n=tg(e,t),{width:r,height:o}=rg(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 Um(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 Jm(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 d=(e.get(a.id)??0)-1;e.set(a.id,d),d<=0&&n.push(a)}}}for(let s of t.nodes.values())s.layer<0&&(s.layer=0)}function Ym(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),d=a.layer-i.layer;if(d<=0){i.out=i.out.filter(l=>l!==s),a.in=a.in.filter(l=>l!==s);continue}if(d===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 u=i;for(let l=1;l<d;l+=1){let p=`__virt_${o++}__`,f={id:p,isVirtual:!0,layer:i.layer+l,order:0,x:0,y:0,w:0,h:1,in:[],out:[]};t.nodes.set(p,f),n[f.layer].push(f);let m={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:u.id,toId:p,hopIndex:l-1,chainLen:d};u.out.push(m),f.in.push(m),r.push(m),u=f}let c={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:u.id,toId:a.id,hopIndex:d-1,chainLen:d};u.out.push(c),a.in.push(c),r.push(c)}for(let s of n)for(let i=0;i<s.length;i+=1)s[i].order=i;t.layers=n,t.hops=r}function Qm(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)yc(t,t.layers[r],"in"),ls(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)yc(t,t.layers[r],"out"),ls(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=bc(t,s[i],s[i+1],"in");[s[i],s[i+1]]=[s[i+1],s[i]],ls(s),bc(t,s[i],s[i+1],"in")<a?r=!0:([s[i],s[i+1]]=[s[i+1],s[i]],ls(s))}}if(!r)break}}function yc(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 d of s){let u=t.nodes.get(n==="in"?d.fromId:d.toId);u&&(i+=u.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 ls(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function bc(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 d of s){let u=t.nodes.get(r==="in"?a.fromId:a.toId)?.order??0,c=t.nodes.get(r==="in"?d.fromId:d.toId)?.order??0;(e.order<n.order&&u>c||e.order>n.order&&u<c)&&(i+=1)}return i}function Xm(t,e){e.direction==="LR"?Zm(t,e):eg(t,e)}function Zm(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}Tc(t,e,"y")}function eg(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}Tc(t,e,"x")}function Tc(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 d=new Map;for(let c of a){let l=s===0?c.in:c.out;if(l.length===0)continue;let p=[];for(let m of l){let h=t.nodes.get(s===0?m.fromId:m.toId);if(!h)continue;let g=n==="y"?h.y:h.x;p.push(g+Math.floor(r(h)/2))}if(p.length===0)continue;p.sort((m,h)=>m-h);let f=p[Math.floor(p.length/2)];d.set(c.id,f-Math.floor(r(c)/2))}let u=0;for(let c of a){let l=d.get(c.id),p=n==="y"?c.y:c.x,m=Math.max(l??p,u);n==="y"?c.y=m:c.x=m,u=m+r(c)+o}}}}function tg(t,e){let n=new Map;for(let u of t.hops){let c=n.get(u.chainId);c?c.push(u):n.set(u.chainId,[u])}for(let u of n.values())u.sort((c,l)=>c.hopIndex-l.hopIndex);let r=e.direction==="LR",o=u=>r?u.x:u.y,s=u=>r?u.w:u.h,i=u=>r?u.y+Math.floor(u.h/2):u.x+Math.floor(u.w/2),a=new Map;for(let u=0;u+1<t.layers.length;u+=1){let c=t.layers[u],l=t.layers[u+1],p=0;for(let S of c)p=Math.max(p,o(S)+s(S));let f=Number.POSITIVE_INFINITY;for(let S of l)f=Math.min(f,o(S));let m=Number.isFinite(f)?f-1:p,h=Math.max(1,m-p+1),g=[];for(let S of c)for(let R of S.out)g.push(R);g.sort((S,R)=>{let E=i(t.nodes.get(S.fromId)),_=i(t.nodes.get(R.fromId));if(E!==_)return E-_;let O=i(t.nodes.get(S.toId)),N=i(t.nodes.get(R.toId));return O-N});let y=[],b=new Map;for(let S of g){let R=i(t.nodes.get(S.fromId)),E=i(t.nodes.get(S.toId)),_=Math.min(R,E),O=Math.max(R,E),N=-1;for(let L=0;L<y.length;L+=1){let j=y[L],$=!0;for(let D of j)if(D.lo<=O&&_<=D.hi){$=!1;break}if($){j.push({lo:_,hi:O}),N=L;break}}N<0&&(y.push([{lo:_,hi:O}]),N=y.length-1),b.set(S,N)}let v=y.length,T=h>=Math.max(3,v+2),w=T?p+1:p,x=T?m-1:m,k=Math.max(1,x-w+1);for(let S of g){let R=b.get(S),E;if(v<=1)E=w+Math.floor(k/2);else{let _=(k-1)/(v-1);E=w+Math.floor(R*_)}a.set(S,Math.max(p,Math.min(m,E)))}}let d=[];for(let[,u]of n){let c=[];for(let p=0;p<u.length;p+=1){let f=u[p],m=t.nodes.get(f.fromId),h=t.nodes.get(f.toId),g=a.get(f),y=m.isVirtual?o(m):o(m)+s(m),b=h.isVirtual?o(h):o(h)-1,v=i(m),T=i(h);p===0&&ps(c,r,y,v),v!==T&&(ps(c,r,g,v),ps(c,r,g,T)),ps(c,r,b,T)}let l=u[0];d.push({from:l.chainFrom,to:l.chainTo,points:ng(c)})}return d}function ps(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function ng(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 rg(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 og=24,sg=4,ig=1,ag=3;function wc(t,e){let n=dg(e.direction),r=Math.max(3,e.maxLabelWidth??og),o=e.asciiCharset??"unicode",s=Object.keys(t.nodes).sort(),i=new Set(s),a=t.edges.filter(f=>i.has(f.from)&&i.has(f.to)),d=new Map,u=new Map;for(let f of s){let m=lc(f,r);d.set(f,m),u.set(f,tr(m)+4)}let c=vc({nodes:s,edges:a,widthCells:f=>u.get(f)??3,heightCells:()=>ag,layerGap:sg,nodeGap:ig,direction:n}),l=gc(c,{charset:o,labelOf:f=>d.get(f)??f}),p=e.logger;return p&&p(l),l}function dg(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 fs(e,n,"no-such-from");if(!s)return fs(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 u=ug(t,e,r);if(u!=null)return u}let d=ms(e,t.nodes[e],0,r);return gs(e,n,[d])}if(i===0)return fs(e,n,"no-path");let a=kc(t,e,n,i);return a.found?gs(e,n,xc(t,a.pathOrder,r)):fs(e,n,a.truncated?"max-depth-exceeded":"no-path")}function kc(t,e,n,r){let o=new Map,s=[{path:n,depth:0}],i=new Set([n]),a=0,d=!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&&(d=!0);continue}let p=t.nodes[l.path];if(p==null)continue;let f=p.deps??[],m=new Map;for(let h=0;h<f.length;h++){let g=f[h];if(!g)continue;let y=m.get(g);y==null&&(y=[],m.set(g,y)),y.push(h)}for(let[h,g]of m)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:d};let u=[{path:e}],c=e;for(;c!==n;){let l=o.get(c);if(l==null)return{found:!1,pathOrder:[],truncated:!1};u[u.length-1].depIndices=l.depIndices,u.push({path:l.from}),c=l.from}return{found:!0,pathOrder:u,truncated:!1}}function ug(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=ms(e,r,0,n);a.dep_index=s[0];let d=ms(e,r,1,n);return gs(e,e,[a,d])}let i=null;for(let a=0;a<o.length;a++){let d=o[a];if(!d||d===e)continue;let u=kc(t,d,e,n.maxDepth);u.found&&(i==null||u.pathOrder.length<i.pathOrder.length)&&(i=u,i={found:!0,pathOrder:[{path:e,depIndices:[a]},...u.pathOrder],truncated:!1})}return i==null?null:gs(e,e,xc(t,i.pathOrder,n))}function xc(t,e,n){return e.map((r,o)=>{let s=t.nodes[r.path],i=ms(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 ms(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 gs(t,e,n){return Rc(t,e,!0,"ok",n)}function fs(t,e,n){return Rc(t,e,!1,n,[])}function Rc(t,e,n,r,o){let s=cg(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 cg(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 d=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(s.push(d),"value"in i&&s.push(` value: ${lg(i.value)}`),i.annotation!=null&&s.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let u=i.lastMutation.actor;s.push(` actor: ${u.type}${u.id?`:${u.id}`:""}`)}}return s.join(`
|
|
11
|
+
`)}function lg(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)}}Me();var $e={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},hs=Symbol.for("sizeof");function qr(t){let e=new WeakSet,n=new WeakSet,r=[t],o=0;for(;r.length>0;){let s=r.pop();o+=pg(s,e,n,r)}return o}function pg(t,e,n,r){if(t==null)return 0;switch(typeof t){case"number":return $e.number;case"boolean":return $e.boolean;case"string":return $e.string+t.length*2;case"bigint":return $e.bigint+fg(t);case"symbol":return $e.symbol;case"function":return e.has(t)?0:(e.add(t),$e.function);case"undefined":return 0}let s=t;if(e.has(s))return 0;e.add(s);let i=s[hs];if(typeof i=="function")try{let u=i.call(s);if(typeof u=="number"&&Number.isFinite(u))return u}catch{}if(s instanceof Date)return $e.date;if(s instanceof RegExp)return $e.regexp+s.source.length*2;if(s instanceof Error){let u=s.message?s.message.length*2:0,c=s.stack?s.stack.length*2:0;return $e.error+u+c}if(typeof URL<"u"&&s instanceof URL)return $e.url+s.href.length*2;if(typeof Promise<"u"&&s instanceof Promise)return $e.promise;if(s instanceof WeakMap)return $e.weakmap;if(s instanceof WeakSet)return $e.weakset;if(s instanceof Map){let u=$e.map;for(let[c,l]of s)u+=$e.mapEntry,r.push(c),r.push(l);return u}if(s instanceof Set){let u=$e.set;for(let c of s)u+=$e.setEntry,r.push(c);return u}if(Array.isArray(s)){let u=$e.array+s.length*8;for(let c of s)r.push(c);return u}if(s instanceof ArrayBuffer)return n.has(s)?0:(n.add(s),s.byteLength);if(ArrayBuffer.isView(s)){let u=s;return n.has(u.buffer)?48:(n.add(u.buffer),u.buffer.byteLength+48)}let a=$e.object,d=Object.keys(s);for(let u of d){a+=$e.string+u.length*2;try{r.push(s[u])}catch{}}return a}function fg(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 hn(t,e){let n=e?.topN??10,r=t.describe({detail:"standard"}),o=[],s=t._collectObserveTargets;typeof s=="function"&&s.call(t,"",o);let i=new Map;for(let[p,f]of o)i.set(p,f);let a=[];for(let[p,f]of Object.entries(r.nodes)){let m=i.get(p),h=m instanceof Oe?m:null,g=h?qr(h.cache):0,y=h?h._sinkCount:0,b=f.deps?.length??0,v=f.type==="effect"&&y===0,T=y===0?f.type==="effect"?"orphan-effect":f.type==="derived"?"idle-derived":f.type==="producer"?"idle-producer":null:null;a.push({path:p,type:f.type,status:f.status??"unknown",valueSizeBytes:g,subscriberCount:y,depCount:b,isOrphanEffect:v,orphanKind:T})}let d=a.reduce((p,f)=>p+f.valueSizeBytes,0),u=(p,f)=>[...a].sort(f??((m,h)=>h[p]-m[p])).slice(0,n),c=a.filter(p=>p.orphanKind!=null),l=a.filter(p=>p.isOrphanEffect);return{nodeCount:a.length,edgeCount:r.edges.length,subgraphCount:r.subgraphs.length,nodes:a,totalValueSizeBytes:d,hotspots:{byValueSize:u("valueSizeBytes"),bySubscriberCount:u("subscriberCount"),byDepCount:u("depCount")},orphans:c,orphanEffects:l}}var Ge="::",tt="__meta__",bt=1;function Sc(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 _c(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"&&typeof t.down=="function"}function mg(t){if(t!=null)return _c(t)?t.cache:t}function gg(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 Nc(t){if(t.version!==bt)throw new Error(`unsupported snapshot version ${String(t.version)} (expected ${bt})`);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 hg(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,d=s.constructor;if(a!==d)return!1;if(o instanceof Date)return o.getTime()===s.getTime();if(o instanceof RegExp)return o.source===s.source&&o.flags===s.flags;if(Array.isArray(o)){let p=s;if(o.length!==p.length)return!1;for(let f=0;f<o.length;f++)if(!r(o[f],p[f]))return!1;return!0}if(o instanceof Map){let p=s;if(o.size!==p.size)return!1;for(let[f,m]of o)if(!p.has(f)||!r(m,p.get(f)))return!1;return!0}if(o instanceof Set){let p=s;if(o.size!==p.size)return!1;for(let f of o){let m=!1;for(let h of p)if(r(f,h)){m=!0;break}if(!m)return!1}return!0}if(ArrayBuffer.isView(o)){let p=o,f=s;if(p.length!==f.length)return!1;for(let m=0;m<p.length;m++)if(p[m]!==f[m])return!1;return!0}let u=Object.keys(o),c=Object.keys(s);if(u.length!==c.length)return!1;let l=new Set(c);for(let p of u)if(!l.has(p)||!r(o[p],s[p]))return!1;return!0};return r(t,e)}function _a(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(_a);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=_a(e[o]);return r}function yg(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function bg(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function vg(t){return t==="TD"?"down":t==="BT"?"up":t==="RL"?"left":"right"}function Mc(t){let e=new Set,n=[];function r(o,s){let i=`${o}\0${s}`;e.has(i)||(e.add(i),n.push([o,s]))}for(let[o,s]of Object.entries(t.nodes)){let i=s.deps;if(i)for(let a of i)r(a,o)}for(let o of t.edges)r(o.from,o.to);return n}function Oc(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 Tg(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(_a(i),null,e.indent??2);return e.logger?.(a),a}function wg(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}): ${bs(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 Ac(t,e){let n=Oc(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}["${yg(i)}"]`)}for(let[i,a]of Mc(t)){let d=o.get(i),u=o.get(a);!d||!u||s.push(` ${d} --> ${u}`)}return s.join(`
|
|
14
|
+
`)}function kg(t,e){let n=Ac(t,e);return vs(n)}function vs(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 u=0;u<i.length;u++)a+=String.fromCharCode(i[u]);return`https://mermaid.live/edit#base64:${globalThis.btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`}function xg(t,e){let n=Oc(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: ${vg(n)}`];for(let i of r){let a=o.get(i);s.push(`${a}: "${bg(i)}"`)}for(let[i,a]of Mc(t)){let d=o.get(i),u=o.get(a);!d||!u||s.push(`${d} -> ${u}`)}return s.join(`
|
|
15
|
+
`)}function Rg(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ys(t){let e="^";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="*"){e+=".*";continue}if(r==="?"){e+=".";continue}if(r==="["){let o=t.indexOf("]",n+1);if(o<=n+1){e+="\\[";continue}let s=t.slice(n+1,o);s.startsWith("!")&&(s=`^${s.slice(1)}`),s=s.replace(/\\/g,"\\\\"),e+=`[${s}]`,n=o;continue}e+=Rg(r)}return e+="$",new RegExp(e)}var Sg={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"},Ng={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function bs(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 Eg(t){return t==="none"?Ng:t==="ansi"||t==null?Sg:{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 Ec(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 _g(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 Ea(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(Ge))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${Ge}' (path separator)`);if(t===tt)throw new Error(`Graph "${e}": ${n} name "${tt}" is reserved for meta companion paths`);_g(t,e,n)}function Mg(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(Ge);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function Og(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 Cc(t){for(let e of t._mounts.values())Cc(e);for(let e of t._nodes.values())try{e.down([[le]],{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;_destroyed=!1;_topology;_topologyEmitters=new Set;_factory;_factoryArgs;constructor(e,n){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(Ge))throw new Error(`Graph name must not contain '${Ge}' (got "${e}")`);if(e===tt)throw new Error(`Graph name "${tt}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??Fe,this._traceRing=new gn(n?.traceCapacity??1e3),n?.versioning!=null&&this.setVersioning(n.versioning),typeof n?.factory=="string"&&(this._factory=n.factory,n.factoryArgs!==void 0&&(this._factoryArgs=n.factoryArgs))}tagFactory(e,n){return this._factory=e,this._factoryArgs=n,this}ancestors(e=!0){let n=[],r=e?this:this._parent;for(;r!=null;)n.push(r),r=r._parent;return n}get topology(){return this._topology==null&&(this._topology=z(e=>{let n=r=>{e.emit(r)};return this._topologyEmitters.add(n),()=>{this._topologyEmitters.delete(n)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let n of this._topologyEmitters)n(e)}nameOf(e){return this._nodeToName.get(e)}add(e,n){let r=e.name,o=n?.name??r;if(o==null||o==="")throw new Error(`Graph "${this.name}": graph.add requires a non-empty name \u2014 pass via opts.name or set it on the node (e.g. state(0, { name: "x" }))`);let s=o,i=n?.annotation;if(Ea(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){Ea(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,d]of i)a.includes(`${Ge}${tt}${Ge}`)||s.nodes.push(a);return s.nodes.sort(),s.mounts.push(e),s.mounts.push(...n._collectSubgraphs(`${e}${Ge}`)),this._mounts.delete(e),n._parent=void 0,Cc(n),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:s}),s}let r=this._nodes.get(e);if(!r)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(r),r.down([[le]],{internal:!0});let o={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:o}),o}removeAll(e){let n=typeof e=="function"?e:(()=>{let s=ys(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(Ge))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([[M,n]],{actor:r?.actor,internal:o,delivery:"write"})}setAll(e,n){let r=Symbol.iterator in e?e:Object.entries(e);Z(()=>{for(let[o,s]of r)this.set(o,s,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[Qe]],{actor:n?.actor,internal:r,delivery:"write"})}error(e,n,r){let o=r?.internal===!0;this.node(e).down([[I,n]],{actor:r?.actor,internal:o,delivery:"write"})}complete(e,n){let r=n?.internal===!0;this.node(e).down([[P]],{actor:n?.actor,internal:r,delivery:"write"})}edges(e){let n=e?.recursive===!0,r=new Map;if(!n){for(let[d,u]of this._nodes)r.set(u,d);let a=[];for(let[d,u]of this._nodes)if(u instanceof Oe)for(let c of u._deps){let l=r.get(c.node);l!=null&&a.push([l,d])}return a.sort((d,u)=>d[0]<u[0]?-1:d[0]>u[0]?1:d[1]<u[1]?-1:d[1]>u[1]?1:0),a}let o=[];this._collectObserveTargets("",o);let s=new Map;for(let[a,d]of o)s.set(d,a);let i=[];for(let[a,d]of o)if(d instanceof Oe)for(let u of d._deps){let c=s.get(u.node);c!=null&&i.push([c,a])}return i.sort((a,d)=>a[0]<d[0]?-1:a[0]>d[0]?1:a[1]<d[1]?-1:a[1]>d[1]?1:0),i}mount(e,n){if(n===void 0){let o=new t(e);return this.mount(e,o)}if(typeof n=="function"){let o=new t(e);return n(o),this.mount(e,o)}let r=n;if(Ea(e,this.name,"mount"),this._nodes.has(e))throw new Error(`Graph "${this.name}": cannot mount at "${e}" \u2014 node with that name exists`);if(this._mounts.has(e))throw new Error(`Graph "${this.name}": mount "${e}" already exists`);if(r===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(r._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${r._parent.name}"`);for(let o=this;o!=null;o=o._parent)if(o===r)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,r),r._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),r}resolve(e){let n=Mg(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]===tt)return this._resolveMetaChainFromNode(s,o,n.join(Ge));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(Ge)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(o.join(Ge))}_resolveMetaChainFromNode(e,n,r){let o=e,s=0,i=[...n];for(;s<i.length;){if(i[s]!==tt)throw new Error(`Graph "${this.name}": expected ${tt} segment in meta path "${r}"`);if(s+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${tt} in "${r}"`);let a=i[s+1],d=o.meta[a];if(!d)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${r}"`);o=d,s+=2}return o}signal(e,n){if(n?.internal!==!0){for(let o of e)if(this.config.messageTier(o[0])===3)throw new Error(`Graph "${this.name}": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). For per-node value writes, use Graph.set or graph.node(name).down(...).`)}let r=[];if(this._signalDeliver(e,n??{},new Set,r),r.length>0)throw r[0]}_signalDeliver(e,n,r,o){for(let d of this._mounts.values())d._signalDeliver(e,n,r,o);let i=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},a=Og(e,this.config);for(let d of[...this._nodes.keys()].sort()){let u=this._nodes.get(d);if(!r.has(u)){r.add(u);try{u.down(e,i)}catch(c){if(c instanceof dt)throw c;o.push(c)}a.length!==0&&this._signalMetaSubtree(u,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(d){if(d instanceof dt)throw d;s.push(d)}this._signalMetaSubtree(a,n,r,o,s)}}}describe(e){if(e?.reactive==="diff")return this._describeReactiveDiff(e);if(e?.reactive===!0)return this._describeReactive(e);let n=mg(e?.actor),r=e?.filter,o=Lt(e?.detail,e?.fields),s=e?.format==="spec",i=s?Lt("minimal"):o,a=[];this._collectObserveTargets("",a);let d=new Map;for(let[x,k]of a)d.set(k,x);let u=[];{let x=a.map(([,R])=>R),k=new Set(d.values()),S=0;for(;x.length>0;){let R=x.shift();if(R instanceof Oe)for(let E of R._deps){let _=E.node;if(d.has(_))continue;let O=_.name??"",N=O;if(!N||k.has(N))if(O){let L=2;for(;k.has(`${O}#${L}`);)L++;N=`${O}#${L}`}else for(N=`__internal__/${S++}`;k.has(N);)N=`__internal__/${S++}`;d.set(_,N),k.add(N),u.push([N,_]),x.push(_)}}}let c=[...a,...u],l={};for(let[x,k]of c){if(n!=null&&!k.allowsObserve(n))continue;let S=jr(k,i),R=k instanceof Oe?k._deps.map(N=>d.get(N.node)??N.node.name??""):[],{name:E,..._}=S,O={..._,deps:R};if(!s){let N=this._annotations.get(x);N!=null&&(O.annotation=N)}if(r!=null)if(typeof r=="function"){let N=r;if(!(N.length>=2?N(x,O):N(O)))continue}else{let N=!0;for(let[L,j]of Object.entries(r)){let $=L==="deps_includes"?"depsIncludes":L==="meta_has"?"metaHas":L;if($==="depsIncludes"){if(!O.deps.includes(String(j))){N=!1;break}continue}if($==="metaHas"){if(!Object.hasOwn(O.meta??{},String(j))){N=!1;break}continue}if(O[$]!==j){N=!1;break}}if(!N)continue}l[x]=O}let p=new Set(Object.keys(l)),f=[];for(let[x,k]of c)if(k instanceof Oe)for(let S of k._deps){let R=d.get(S.node);R!=null&&f.push([R,x])}f.sort((x,k)=>x[0]<k[0]?-1:x[0]>k[0]?1:x[1]<k[1]?-1:x[1]>k[1]?1:0);let m=f.map(([x,k])=>({from:x,to:k}));(n!=null||r!=null)&&(m=m.filter(x=>p.has(x.from)&&p.has(x.to)));let h=this._collectSubgraphs(""),g=n!=null||r!=null?h.filter(x=>{let k=`${x}${Ge}`;return[...p].some(S=>S===x||S.startsWith(k))}):h,y=this,b=e,v={name:this.name,nodes:l,edges:m,subgraphs:g,...this._factory!==void 0?{factory:this._factory}:{},...this._factoryArgs!==void 0?{factoryArgs:this._factoryArgs}:{},expand(x){let k={...b,format:void 0};return Array.isArray(x)?(k.fields=x,k.detail=void 0):(k.detail=x,k.fields=void 0),y.describe(k)}},T=e??{},w=T.format;return w==="json"?Tg(v,T):w==="pretty"?wg(v,T):w==="mermaid"?Ac(v,T):w==="mermaid-url"?kg(v,T):w==="d2"?xg(v,T):w==="ascii"?wc(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}${Ge}`))}return n}resourceProfile(e){return hn(this,e)}reachable(e,n,r={}){return r.withDetail===!0?yn(this.describe(),e,n,{...r,withDetail:!0}):yn(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,d]of Object.entries(o.nodes))d.lastMutation!=null&&i.set(a,d.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=A(o,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,Fn(()=>{a=!1,!d&&(o+=1,s.emit(o))}))},c=i.onEvent(b=>{let v=b.type;v!=="data"&&v!=="error"&&v!=="complete"&&v!=="teardown"||u()}),l=[],p=new WeakSet,f=b=>{if(p.has(b)||d)return;p.add(b);let v=b.topology.subscribe(T=>{for(let w of T){if(w[0]!==M)continue;let x=w[1];if(u(),x.kind==="added"&&x.nodeKind==="mount"){let k=b._mounts.get(x.name);k!=null&&f(k)}}});l.push(v);for(let T of b._mounts.keys()){let w=b._mounts.get(T);w!=null&&f(w)}};f(this);let m,h=e.actor;_c(h)&&(m=h.subscribe(b=>{let v=!1,T=!1;for(let w of b){let x=w[0];x===M?v=!0:(x===P||x===I||x===le)&&(T=!0)}v&&u(),T&&(m?.(),m=void 0,u())}));let g;try{g=C([s],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(b,v)=>b===v})}catch(b){c(),m?.();for(let v of l)v();throw i.dispose(),b}let y=te(g);return{node:g,dispose(){d=!0,c(),m?.();for(let b of l)b();l.length=0,i.dispose(),y()}}}_describeReactiveDiff(e){let n={...e,format:void 0,reactive:!1},r=e.reactiveName??"describe-diff",o={name:this.name,nodes:{},edges:[],subgraphs:[]},s=this.describe(n),i=er(o,s),a=A(i,{name:r,meta:{domain:"audit",kind:"describe-diff"},equals:(p,f)=>p===f}),d=this._describeReactive({...e,format:void 0,reactiveName:void 0}),u=!1,c=d.node.subscribe(p=>{if(!u)for(let f of p){if(f[0]!==M)continue;let m=f[1],h=er(s,m);s=m,h.events.length!==0&&a.emit(h)}}),l=te(a);return{node:a,dispose(){u=!0,c(),d.dispose(),a.down([[le,"describe-diff disposed"]]),l()}}}_explainReactive(e,n,r){let o=0,s=A(o,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=i.onEvent(f=>{let m=f.type;m!=="data"&&m!=="error"&&m!=="complete"&&m!=="teardown"||a||d||(a=!0,Fn(()=>{a=!1,!d&&(o+=1,s.emit(o))}))}),c={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},l;try{l=C([s],()=>this._explainStatic(e,n,c),{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:e,to:n},equals:(f,m)=>f.found===m.found&&f.reason===m.reason&&f.steps.length===m.steps.length&&Ag(f.steps,m.steps)})}catch(f){throw u(),i.dispose(),f}let p=te(l);return{node:l,dispose(){d=!0,u(),i.dispose(),p()}}}_pathsMatching(e){let n=ys(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}${Ge}${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}${Ge}${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}${Ge}${tt}${Ge}${o}`;r.push([i,s]),this._appendMetaObserveTargets(i,s,r)}}observe(e,n){let r=typeof e=="string",s=Ec(r?n:e);if(s.reactive===!0)return this._observeReactive(r?e:void 0,s);let i=s.structured===!0||s.timeline===!0||s.causal===!0||s.derived===!0||s.detail==="minimal"||s.detail==="full"||s.format!=null,a=s.actor;if(r){let c=e,l=this.resolve(c);if(a!=null&&!l.allowsObserve(a))throw new dt({actor:a,action:"observe",nodeName:c});return i?this._buildStructuredObserver([[c,l]],s,"one"):{subscribe(p){return l.subscribe(p)},up(p){try{l.up?.(p)}catch(f){if(f instanceof dt)return;throw f}}}}let d=[];this._collectObserveTargets("",d),d.sort((c,l)=>c[0]<l[0]?-1:c[0]>l[0]?1:0);let u=a==null?d:d.filter(([,c])=>c.allowsObserve(a));return i?this._buildStructuredObserver(u,s,"all"):{subscribe:c=>{let l=u.map(([p,f])=>f.subscribe(m=>{c(p,m)}));return()=>{for(let p of l)p()}},up:(c,l)=>{try{this.resolve(c).up?.(l)}catch(p){if(p instanceof dt)return;throw p}}}}_observeReactive(e,n){let r=n.tiers,o=r!=null?new Set(r):null,s=n.reactiveName??"observe";return z(i=>{let a=[],d=!1,u=!1,c=()=>{if(a.length===0||u)return;let h={events:a.slice(),flushedAt_ns:V()};a.length=0,i.emit(h)},l={...n,reactive:!1,structured:!0,timeline:!0},p=e!=null?this.observe(e,l):this.observe(l),f=h=>{u||(a.push(h),!d&&(d=!0,Fn(()=>{d=!1,c()})))};for(let h of p.events)f(h);let m=p.onEvent(f);return()=>{u=!0,m(),p.dispose()}},{name:s,meta:{domain:"audit",kind:"observe-reactive"}})}_buildStructuredObserver(e,n,r){let o=r==="one"?e[0]?.[0]:void 0,s=i=>{if(r==="one"&&o!=null){let c=this.resolve(o);return this._buildStructuredObserver([[o,c]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((c,l)=>c[0]<l[0]?-1:c[0]>l[0]?1:0);let d=i.actor,u=d==null?a:a.filter(([,c])=>c.allowsObserve(d));return this._buildStructuredObserver(u,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",d=this.config.inspectorEnabled,u=(s||i)&&d,c=n.maxEvents,l=c!=null&&c>0?new gn(c):null,p=[],f=new Set,m=n.tiers!=null?new Set(n.tiers):null,h={},g=new Set,y=0,b=0,v=0,T=0,w=0,x=0,k=!1,S=!1,R=0,E=new Map,_=new Map,O=new Map,N=ee=>{if(!(m!=null&&!m.has(ee.type))){l?l.push(ee):p.push(ee);for(let ue of f)ue(ee)}},L=ee=>m==null||m.has(ee),j=()=>o?{timestamp_ns:V(),in_batch:sn(),batch_id:R}:{},$=(ee,ue)=>{if(!(!u||!(ee instanceof Oe)))return ee._setInspectorHook(Ce=>{if(Ce.kind==="dep_message")E.set(ee,Ce.depIndex);else if(Ce.kind==="run"){let Ye=Ce.batchData.map((J,de)=>J!=null&&J.length>0?J.at(-1):Ce.prevData[de]);_.set(ee,Ye);let Be=Ce.batchData.map(J=>J!=null?[...J]:void 0);O.set(ee,Be),i&&N({type:"derived",path:ue,dep_values:Ye,dep_batches:Be,...j()})}})},D=ee=>{let ue=E.get(ee),Ce=_.get(ee);if(!s||Ce==null)return{};let Be=(ue!=null&&ue>=0&&ee instanceof Oe?ee._deps[ue]:void 0)?.node,J=Be?.v,de=O.get(ee);return{trigger_dep_index:ue,trigger_dep_name:Be?.name,...J!=null?{trigger_version:{id:J.id,version:J.version}}:{},dep_values:[...Ce],...de!=null?{dep_batches:de}:{}}},K=[],F=[];for(let[ee,ue]of e){let Ce=$(ue,ee);Ce&&K.push(Ce),F.push(ue.subscribe(Ye=>{R++;for(let Be of Ye){let J=Be[0],de=j();if(J===M){h[ee]=Be[1];let Le=ue instanceof Oe?ue.lastMutation?.actor??xt:xt;N({type:"data",path:ee,data:Be[1],actor:Le,...de,...D(ue)})}else if(a)J===oe?L("dirty")&&y++:J===q?L("resolved")&&b++:J===Qe?L("invalidate")&&v++:J===Ve?L("pause")&&T++:J===ze?L("resume")&&w++:J===le?L("teardown")&&x++:J===P&&!g.has(ee)?L("complete")&&(k=!0):J===I&&L("error")&&(S=!0,g.add(ee));else if(J===oe)L("dirty")&&y++,N({type:"dirty",path:ee,...de});else if(J===q)L("resolved")&&b++,N({type:"resolved",path:ee,...de,...D(ue)});else if(J===Qe)L("invalidate")&&v++,N({type:"invalidate",path:ee,...de});else if(J===Ve)L("pause")&&T++,N({type:"pause",path:ee,lockId:Be[1],...de});else if(J===ze)L("resume")&&w++,N({type:"resume",path:ee,lockId:Be[1],...de});else if(J===P)L("complete")&&!g.has(ee)&&(k=!0),N({type:"complete",path:ee,...de});else if(J===I){L("error")&&(S=!0,g.add(ee));let Le=ue instanceof Oe?ue.lastMutation?.actor??xt:xt;N({type:"error",path:ee,data:Be[1],actor:Le,...de})}else J===le&&(L("teardown")&&x++,N({type:"teardown",path:ee,...de}))}}))}let H=!1,G=()=>{if(!H){H=!0;for(let ee of F)ee();for(let ee of K)ee();for(let ee of re)ee({value:void 0,done:!0});re.length=0}},B=[],re=[];f.add(ee=>{let ue=re.shift();ue?ue({value:ee,done:!1}):B.push(ee)});let pe={get values(){return h},get dirtyCount(){return y},get resolvedCount(){return b},get invalidateCount(){return v},get pauseCount(){return T},get resumeCount(){return w},get teardownCount(){return x},get events(){return l?l.toArray():[...p]},get anyCompletedCleanly(){return k},get anyErrored(){return S},get completedWithoutErrors(){return k&&!S},onEvent(ee){return f.add(ee),()=>f.delete(ee)},dispose:G,expand(ee){G();let ue={...n};return typeof ee=="string"?ue.detail=ee:Object.assign(ue,ee),r(Ec(ue))},[Symbol.asyncIterator](){return{next(){return B.length>0?Promise.resolve({value:B.shift(),done:!1}):H?Promise.resolve({value:void 0,done:!0}):new Promise(ee=>re.push(ee))},return(){return G(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(pe,n),pe}_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)),d=Eg(n.theme),u=r==="stage-log"?V():0,c=m=>m==null?"":n.stageLabels?.[m]??m,l=(m,h)=>m.length>h?`${m.slice(0,h-1)}\u2026`:m,p=m=>m.type==="data"||m.type==="error"?l(bs(m.data),120):"",f=m=>{if(r==="stage-log"){let k=(V()-u)/1e9,S=c(m.path).padEnd(9);if(m.type==="data"){let R=p(m);return`[${k.toFixed(3)}s] ${S} \u2190${R?` ${R}`:""}`}if(m.type==="error"){let R=p(m);return`[${k.toFixed(3)}s] ${S} \u2717${R?` ${R}`:""}`}return m.type==="complete"?`[${k.toFixed(3)}s] ${S} \u25A0 complete`:`[${k.toFixed(3)}s] ${S} ${m.type}`}if(r==="json")try{return JSON.stringify(m)}catch{return JSON.stringify({type:m.type,path:m.path,data:"[unserializable]"})}let h=d[m.type]??"",g=m.path?`${d.path}${m.path}${d.reset} `:"",y=m.type==="data"||m.type==="error",b=m.type==="pause"||m.type==="resume",v=y?` ${bs(m.data)}`:b?` ${bs(m.lockId)}`:"",T=m.type==="data"||m.type==="resolved"||m.type==="derived"?m:void 0,w=T?.trigger_dep_name!=null?` <- ${T.trigger_dep_name}`:T?.trigger_dep_index!=null?` <- #${T.trigger_dep_index}`:"",x=m.in_batch?" [batch]":"";return`${g}${h}${m.type.toUpperCase()}${d.reset}${v}${w}${x}`};e.onEvent(m=>{a(m.type)&&o(f(m),m)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){Sc(this._disposers,this.name),this.signal([[le]],{internal:!0}),Sc(this._storageDisposers,this.name);for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}get destroyed(){return this._destroyed}_destroyClearOnly(){for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}snapshot(e){let{expand:n,...r}=this.describe({detail:"full"}),o={};for(let a of Object.keys(r.nodes).sort()){let{lastMutation:d,guard:u,...c}=r.nodes[a];o[a]=c}let s=[...r.subgraphs].sort(),i={...r,version:1,nodes:o,subgraphs:s};if(e?.format==null)return i;if(e.format==="json-string")return JSON.stringify(i);if(e.format==="bytes"){if(e.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let a=this.config.lookupCodec(e.codec);if(a==null)throw new Error(`snapshot: codec "${e.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return Nr(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??Fe,{codec:o,codecVersion:s,payload:i}=Er(e,r);return o.decode(i,s)}restore(e,n){if(Nc(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=>ys(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 d=this.tryResolve(s)?.v;if(d!=null&&d.id===i.v.id&&d.version===i.v.version)continue}try{this.set(s,i.value)}catch(a){n?.onError?.(s,a)}}}}}static fromSnapshot(e,n){Nc(e);let r=typeof n=="function"?n:n?.build,o=typeof n=="function"?void 0:n?.factories,s=new t(e.name);if(r)return r(s),s.restore(e),s;for(let f of[...e.subgraphs].sort((m,h)=>{let g=m.split(Ge).length,y=h.split(Ge).length;return g!==y?g-y:m<h?-1:m>h?1:0})){let m=f.split(Ge),h=s;for(let g of m)h._mounts.has(g)||h.mount(g,new t(g)),h=h._mounts.get(g)}let i=o?Object.entries(o).map(([f,m])=>({re:ys(f),factory:m})):[],a=f=>{for(let m of i)if(m.re.test(f))return m.factory},d=f=>{let m=f.split(Ge),h=m.pop();if(h==null||h.length===0)throw new Error(`invalid snapshot path "${f}"`);let g=s;for(let y of m){let b=g._mounts.get(y);if(!b)throw new Error(`unknown mount "${y}" in path "${f}"`);g=b}return[g,h]},u=Object.entries(e.nodes).filter(([f])=>!f.includes(`${Ge}${tt}${Ge}`)).sort((f,m)=>f[0]<m[0]?-1:f[0]>m[0]?1:0),c=new Map(u),l=new Map,p=!0;for(;c.size>0&&p;){p=!1;for(let[f,m]of[...c.entries()]){let h=m?.deps??[];if(!h.every(w=>l.has(w)))continue;let[g,y]=d(f),b={...m?.meta??{}},v=a(f),T;if(m?.type==="state")T=A(m.value,{meta:b});else{if(v==null)continue;T=v(y,{path:f,type:m.type,value:m.value,meta:b,deps:h,resolvedDeps:h.map(w=>l.get(w))})}g.add(T,{name:y}),l.set(f,T),c.delete(f),p=!0}}if(c.size>0){let f=[...c.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${f}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return s.restore(e),s}toJSON(){return this.snapshot()}attachSnapshotStorage(e,n={}){let r=e.map(u=>({tier:u,debounceMs:Math.max(0,u.debounceMs??0),compactEvery:Math.max(1,u.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));n.autoRestore===!0&&this._cascadeRestore(e,n.onError);let o=(u,c)=>{if(u.disposed)return;let l=gg(c.nodes);if(u.lastSnapshot!=null&&l!==""&&l===u.lastFingerprint)return;let p=u.seq+1,f=se(),g=u.lastSnapshot==null||p%u.compactEvery===0?{name:this.name,mode:"full",snapshot:c,seq:p,timestamp_ns:f,format_version:bt}:{name:this.name,mode:"diff",diff:Ts(u.lastSnapshot,c),seq:p,timestamp_ns:f,format_version:bt};if(u.tier.filter&&!u.tier.filter(g))return;let y;try{y=u.tier.save(g)}catch(b){n.onError?.(b,u.tier);return}if(y&&typeof y.then=="function"){let T=(u.savePending??Promise.resolve()).then(()=>y,()=>y).then(()=>{u.disposed||(u.seq=p,u.lastSnapshot=c,u.lastFingerprint=l)},w=>{n.onError?.(w,u.tier)});u.savePending=T.finally(()=>{u.savePending===T&&(u.savePending=void 0)})}else u.seq=p,u.lastSnapshot=c,u.lastFingerprint=l},s=(u,c)=>{try{o(u,c)}catch(l){n.onError?.(l,u.tier)}},i=(u,c)=>{if(!c.some(m=>{let h=this.config.messageTier(m[0]);return h>=3&&h<5}))return;if(n.filter){let m=this.tryResolve(u);if(m==null)return;let h=jr(m,Lt("standard"));if(!n.filter(u,h))return}let p,f=()=>(p==null&&(p=this.snapshot()),p);for(let m of r)m.disposed||(m.debounceMs===0?s(m,f()):(m.timer==null&&(m.timer=new Ie),m.timer.start(m.debounceMs,()=>{m.disposed||s(m,this.snapshot())})))},a;if(n.paths!=null){let c=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(l=>{let p=this.tryResolve(l);return p==null?()=>{}:p.subscribe(f=>i(l,f))});a=()=>{for(let l of c)l()}}else a=this.observe().subscribe((u,c)=>i(u,c));let d=()=>{a();for(let u of r)u.disposed=!0,u.timer?.cancel();this._storageDisposers.delete(d)};return this._storageDisposers.add(d),{dispose:d}}async _cascadeRestore(e,n){for(let r of e){let o;try{o=await r.load?.()}catch(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===bt&&s.nodes!=null)return this.restore(s),!0}catch(i){n?.(i,r)}}return!1}static async fromStorage(e,n,r){for(let o of n){let s;try{s=await o.load?.()}catch(d){r?.onError?.(d,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===bt&&i.nodes!=null?i:void 0;if(a!=null)try{return t.fromSnapshot(a,r)}catch(d){r?.onError?.(d,o)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${n.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,n,r){if(e!=null&&n!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,n),this.config.inspectorEnabled){let o={path:e,annotation:n,timestamp_ns: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=[],d=[];for(let b of r){if(!o.has(b))continue;let v=e.nodes[b],T=n.nodes[b],w=v.v,x=T.v;w!=null&&x!=null&&w.id===x.id&&w.version!==x.version&&d.push({path:b,id:w.id,from:w.version,to:x.version});let k=w!=null&&x!=null&&w.id===x.id&&w.version===x.version;for(let S of["type","status","sentinel"]){let R=v[S],E=T[S];R!==E&&a.push({path:b,field:S,from:R,to:E})}if(!k)for(let S of["value","meta"]){let R=v[S],E=T[S];hg(R,E)||a.push({path:b,field:S,from:R,to:E})}}let u=b=>`${b.from} ${b.to}`,c=new Set(e.edges.map(u)),l=new Set(n.edges.map(u)),p=n.edges.filter(b=>!c.has(u(b))),f=e.edges.filter(b=>!l.has(u(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:d,edgesAdded:p,edgesRemoved:f,subgraphsAdded:g,subgraphsRemoved:y}}};function Ts(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 yn(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,d=new Map,u=new Map,c=new Set;for(let[v,T]of Object.entries(t.nodes)){if(!v)continue;c.add(v);let w=T.deps??[];i.set(v,w);for(let x of w)x&&(c.add(x),a.has(x)||a.set(x,new Set),a.get(x).add(v))}for(let v of t.edges){if(v==null||typeof v!="object")continue;let T=typeof v.from=="string"?v.from:"",w=typeof v.to=="string"?v.to:"";!T||!w||(c.add(T),c.add(w),u.has(T)||u.set(T,new Set),u.get(T).add(w),d.has(w)||d.set(w,new Set),d.get(w).add(T))}if(!c.has(e))return r.withDetail?o:[];let l=r.both===!0,p=v=>{if(l){let k=i.get(v)??[],S=d.get(v),R=a.get(v),E=u.get(v),_=[...k];return S&&_.push(...S),R&&_.push(...R),E&&_.push(...E),_}if(n==="upstream"){let k=i.get(v)??[],S=d.get(v);return S?[...k,...S]:k}let T=a.get(v),w=u.get(v),x=T?[...T]:[];return w&&x.push(...w),x},f=new Set([e]),m=new Map,h=[{path:e,depth:0}],g=0,y=!1;for(;g<h.length;){let v=h[g++];if(s!=null&&v.depth>=s){p(v.path).length>0&&(y=!0);continue}for(let T of p(v.path))!T||f.has(T)||(f.add(T),m.set(T,v.depth+1),h.push({path:T,depth:v.depth+1}))}let b=[...m.keys()].sort((v,T)=>v<T?-1:v>T?1:0);return r.withDetail?{paths:b,depths:m,truncated:y}:b}function Ag(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={};Se(Es,{CqrsGraph:()=>Ns,cqrs:()=>Pa,cqrsEventKeyOf:()=>Dg,dispatchKeyOf:()=>Gg,sagaInvocationKeyOf:()=>Fg});Ae();Re();Vt();var Ma={};Se(Ma,{COMPLETE:()=>P,COMPLETE_MSG:()=>Go,COMPLETE_ONLY_BATCH:()=>Sr,DATA:()=>M,DEFAULT_ACTOR:()=>xt,DIRTY:()=>oe,DIRTY_MSG:()=>Mt,DIRTY_ONLY_BATCH:()=>Ln,ERROR:()=>I,GraphReFlyConfig:()=>an,GuardDenied:()=>dt,INVALIDATE:()=>Qe,INVALIDATE_MSG:()=>Do,INVALIDATE_ONLY_BATCH:()=>Rr,NodeImpl:()=>Oe,PAUSE:()=>Ve,RESOLVED:()=>q,RESOLVED_MSG:()=>An,RESOLVED_ONLY_BATCH:()=>xr,RESUME:()=>ze,START:()=>ft,START_MSG:()=>Cn,TEARDOWN:()=>le,TEARDOWN_MSG:()=>Fo,TEARDOWN_ONLY_BATCH:()=>In,accessHintForGuard:()=>Ir,advanceVersion:()=>Pr,autoTrackNode:()=>dn,batch:()=>Z,configure:()=>la,createVersioning:()=>$n,defaultConfig:()=>Fe,defaultHash:()=>Kt,derived:()=>C,downWithBatch:()=>At,dynamicNode:()=>Dr,effect:()=>ge,factoryTag:()=>we,isBatching:()=>sn,isV1:()=>da,monotonicNs:()=>V,node:()=>U,normalizeActor:()=>Ot,pipe:()=>pa,placeholderArgs:()=>st,policy:()=>Ct,policyFromRules:()=>Lr,producer:()=>z,registerBuiltins:()=>Cr,resolveDescribeFields:()=>Lt,state:()=>A,wallClockNs:()=>se});Mr();Ae();Re();ia();Vt();ae();it();Me();ne();Bo();Ae();ae();Me();ne();ve();var Hr=class{_version=0;_maxSize;_buf;_head=0;_size=0;constructor(e,n){if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(this._maxSize=n,n!==void 0){if(this._buf=new Array(n),e&&e.length>0){let r=Math.min(e.length,n),o=e.length-r;for(let s=0;s<r;s++)this._buf[s]=e[o+s];this._size=r}}else this._buf=e?[...e]:[],this._size=this._buf.length}get version(){return this._version}get size(){return this._size}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._size+e;if(!(n<0||n>=this._size))return this._maxSize!==void 0?this._buf[(this._head+n)%this._maxSize]:this._buf[n]}append(e){this._rawAppend(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._maxSize!==void 0&&e.length>this._maxSize?e.length-this._maxSize:0;for(let r=n;r<e.length;r++)this._rawAppend(e[r]);this._version+=1}clear(){if(this._size===0)return 0;let e=this._size;if(this._maxSize===void 0)this._buf.length=0;else for(let n=0;n<e;n++)this._buf[(this._head+n)%this._maxSize]=void 0;return this._head=0,this._size=0,this._version+=1,e}trimHead(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`trimHead: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return 0;let n=Math.min(e,this._size);if(this._maxSize===void 0)this._buf.splice(0,n);else{for(let r=0;r<n;r++)this._buf[(this._head+r)%this._maxSize]=void 0;this._head=(this._head+n)%this._maxSize}return this._size-=n,this._version+=1,n}slice(e,n){if(!Number.isInteger(e)||e<0)throw new RangeError(`slice: start must be a non-negative integer (got ${e})`);if(n!==void 0&&(!Number.isInteger(n)||n<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${n})`);let r=n===void 0?this._size:Math.min(Math.max(n,0),this._size),o=Math.min(e,this._size);if(o>=r)return[];let s=r-o;if(this._maxSize===void 0)return this._buf.slice(o,r);let i=new Array(s);for(let a=0;a<s;a++)i[a]=this._buf[(this._head+o+a)%this._maxSize];return i}tail(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`tail: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return[];let n=Math.min(e,this._size);return this.slice(this._size-n,this._size)}toArray(){if(this._maxSize===void 0)return[...this._buf];let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this._buf[(this._head+n)%this._maxSize];return e}snapshot(){return this.toArray()}restore(e){if(this._maxSize===void 0){this._buf.length=0;for(let n=0;n<e.length;n++)this._buf.push(e[n]);this._size=this._buf.length}else{let n=this._maxSize;for(let s=0;s<n;s++)this._buf[s]=void 0;this._head=0;let r=Math.min(e.length,n),o=e.length-r;for(let s=0;s<r;s++)this._buf[s]=e[o+s];this._size=r}this._version+=1}_rawAppend(e){if(this._maxSize===void 0){this._buf.push(e),this._size=this._buf.length;return}this._size<this._maxSize?(this._buf[(this._head+this._size)%this._maxSize]=e,this._size+=1):(this._buf[this._head]=e,this._head=(this._head+1)%this._maxSize)}};function zr(t){return t.subscribe(()=>{})}var Cg=64;function Ke(t,e={}){let{name:n,maxSize:r,versioning:o,guard:s,backend:i}=e,a=i??new Hr(t,r),d=A(a.toArray(),{name:n,describeKind:"state",equals:(k,S)=>k===S,...o!=null?{versioning:o}:{},...s!=null?{guard:s}:{}});function u(){let k=a.toArray();Z(()=>{d.down([[oe]],{internal:!0}),d.down([[M,k]],{internal:!0})})}let c=new Map,l=new Map,p=new Map;function f(k,S){return`${k}:${S===void 0?"END":S}`}function m(k){if(k.size<Cg)return;let S=k.keys().next();if(S.done)return;let R=k.get(S.value);R!==void 0&&R.dispose(),k.delete(S.value)}function h(k){let S=a.version;try{return k()}finally{a.version!==S&&u()}}function g(k){if(!Number.isInteger(k)||k<0)throw new RangeError(`tail: n must be a non-negative integer (got ${k})`);let S=c.get(k);if(S!==void 0)return c.delete(k),c.set(k,S),S.node;m(c);let R=C([d],([_])=>{let O=_;return k===0||O.length===0?[]:O.slice(Math.max(0,O.length-k))},{initial:a.tail(k),describeKind:"derived"}),E=zr(R);return c.set(k,{node:R,dispose:E}),R}function y(k,S){if(!Number.isInteger(k)||k<0)throw new RangeError(`slice: start must be a non-negative integer (got ${k})`);if(S!==void 0&&(!Number.isInteger(S)||S<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${S})`);let R=f(k,S),E=l.get(R);if(E!==void 0)return l.delete(R),l.set(R,E),E.node;m(l);let _=C([d],([N])=>{let L=N;return S===void 0?L.slice(k):L.slice(k,S)},{initial:a.slice(k,S),describeKind:"derived"}),O=zr(_);return l.set(R,{node:_,dispose:O}),_}function b(k){let S=p.get(k);if(S!==void 0)return S.node;let R=C([d,k],([_,O])=>{let N=_,L=Math.max(0,Math.trunc(O??0));return N.slice(L)},{initial:[],describeKind:"derived"}),E=zr(R);return p.set(k,{node:R,dispose:E}),R}let v,T;function w(){v===void 0&&(v=U([d],(k,S,R)=>{let E=k[0],O=E!=null&&E.length>0?E.at(-1):R.prevData[0];if(O==null||O.length===0){S.down([[q]]);return}S.emit(O[O.length-1])},{name:n!=null?`${n}::lastValue`:"lastValue",describeKind:"derived",initial:a.size===0?void 0:a.at(a.size-1)}),T=C([d],([k])=>k.length>0,{name:n!=null?`${n}::hasLatest`:"hasLatest",describeKind:"derived",initial:a.size>0}),zr(v),zr(T))}let x={entries:d,get size(){return a.size},at(k){return a.at(k)},append(k){h(()=>a.append(k))},appendMany(k){k.length!==0&&h(()=>a.appendMany(k))},clear(){h(()=>a.clear())},trimHead(k){h(()=>a.trimHead(k))},withLatest(){return w(),d},get lastValue(){return w(),v},get hasLatest(){return w(),T},view(k){switch(k.kind){case"tail":return g(k.n);case"slice":return y(k.start,k.stop);case"fromCursor":return b(k.cursor)}},attach(k){let S=k.subscribe(R=>{for(let E of R)E[0]===M&&x.append(E[1])});return()=>S()},attachStorage(k){if(k.length===0)return()=>{};let S=new Map;for(let E of k)S.set(E,a.size);(async()=>{for(let E of k)if(typeof E.loadEntries=="function")try{let _=await Promise.resolve(E.loadEntries());_.entries.length>0&&a.size===0&&(a.restore(_.entries),S.set(E,_.entries.length),u());break}catch{}})();let R=d.subscribe(E=>{for(let _ of E){if(_[0]!==M)continue;let O=_[1];for(let N of k){let L=S.get(N)??0;if(O.length<L){try{let $=N.appendEntries(O);$ instanceof Promise&&$.catch(()=>{})}catch{}S.set(N,O.length);continue}if(O.length===L)continue;let j=O.slice(L);S.set(N,O.length);try{let $=N.appendEntries(j);$ instanceof Promise&&$.catch(()=>{})}catch{}}}});return()=>R()},disposeAllViews(){for(let k of c.values())k.dispose();c.clear();for(let k of l.values())k.dispose();l.clear();for(let k of p.values())k.dispose();p.clear()},dispose(){for(let k of c.values())k.dispose();c.clear();for(let k of l.values())k.dispose();l.clear();for(let k of p.values())k.dispose();p.clear()}};return x}var Oa=new WeakMap;function Lc(t){let e=Oa.get(t);if(e)return e;let n=t.map(c=>c.cache??[]),r=n.flat(),o=A(r,{name:"mergeReactiveLogs",describeKind:"state",equals:(c,l)=>c===l}),s=t.map((c,l)=>[...n[l]??[]]),i=[];for(let c=0;c<t.length;c++){let l=c,p=t[l].subscribe(f=>{for(let m of f)if(m[0]===M)s[l]=[...m[1]],o.emit(s.flat());else if(m[0]===P){s[l]=[];let h=i[l];h!==void 0&&(i[l]=void 0,h())}else m[0]===I&&o.down([[I,m[1]]])});i.push(p)}let a=te(o),d=!1,u={node:o,dispose(){if(!d){d=!0;for(let c of i)c?.();i.length=0,a(),Oa.delete(t)}}};return Oa.set(t,u),u}var Ca={};Se(Ca,{ENVELOPE_VERSION:()=>Pn,GRAPH_META_SEGMENT:()=>tt,Graph:()=>Q,JsonCodec:()=>$o,SIZEOF_OVERHEAD:()=>$e,SIZEOF_SYMBOL:()=>hs,SNAPSHOT_VERSION:()=>bt,createDagCborCodec:()=>ra,createDagCborZstdCodec:()=>oa,decodeEnvelope:()=>Er,diffForWAL:()=>Ts,encodeEnvelope:()=>Nr,explainPath:()=>Kr,graphProfile:()=>hn,mermaidLiveUrl:()=>vs,reachable:()=>yn,registerBuiltinCodecs:()=>_r,replayWAL:()=>sa,sizeof:()=>qr,validateGraphObservability:()=>Aa,watchTopologyTree:()=>Pt});jo();ae();function Pt(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(d=>{for(let u of d){if(u[0]!==M)continue;let c=u[1];if(e(c,o,s),c.kind==="added"&&c.nodeKind==="mount"){let l=o._mounts.get(c.name);if(l instanceof Q){let p=`${s}${c.name}::`;r(l,p)}}else if(c.kind==="removed"&&c.nodeKind==="mount"){let l=`${s}${c.name}::`;for(let[p,f]of Array.from(n.entries()))p!==t&&f.prefix.startsWith(l)&&(f.off(),n.delete(p))}}});i.off=a;for(let[d,u]of o._mounts)if(u instanceof Q){let c=`${s}${d}::`;r(u,c)}};return r(t,""),()=>{for(let o of n.values())o.off();n.clear()}}function Aa(t,e={}){let n=[],r=e.requireFound??!0;if(e.skipDescribe!==!0)try{let u=t.describe(),c=new Set(Object.keys(u.nodes)),l=[];for(let[p,f]of Object.entries(u.nodes))for(let m of f.deps)m!==""&&!c.has(m)&&l.push(`${p} \u2192 ${m}`);for(let p of u.edges)c.has(p.from)||l.push(`edge.from: ${p.from}`),c.has(p.to)||l.push(`edge.to: ${p.to}`);l.length>0?n.push({kind:"describe",ok:!1,reason:`describe() has ${l.length} dangling pointer(s); nodes \u2289 deps`,danglingDeps:l}):n.push({kind:"describe",ok:!0,nodeCount:c.size,edgeCount:u.edges.length})}catch(u){n.push({kind:"describe",ok:!1,reason:`describe() threw: ${u instanceof Error?u.message:String(u)}`})}for(let u of e.formats??[])try{let c=t.describe({format:u});typeof c!="string"||c.length===0?n.push({kind:"describe-format",ok:!1,format:u,reason:`describe({ format: "${u}" }) returned empty or non-string output`}):n.push({kind:"describe-format",ok:!0,format:u,length:c.length})}catch(c){n.push({kind:"describe-format",ok:!1,format:u,reason:c instanceof Error?c.message:String(c)})}for(let u of e.paths??[])try{t.resolve(u),n.push({kind:"observe",ok:!0,path:u})}catch(c){n.push({kind:"observe",ok:!1,path:u,reason:c instanceof Error?c.message:String(c)})}for(let[u,c]of e.pairs??[])try{let l=t.explain(u,c);r&&l.found===!1?n.push({kind:"explain",ok:!1,from:u,to:c,reason:`explain(${u} \u2192 ${c}) found no path${l.reason?`: ${l.reason}`:""}`}):n.push({kind:"explain",ok:!0,from:u,to:c,found:l.found,steps:l.steps.length})}catch(l){n.push({kind:"explain",ok:!1,from:u,to:c,reason:l instanceof Error?l.message:String(l)})}let o=n.filter(u=>!u.ok),s=o.length===0,i=e.paths?.length??0,a=e.pairs?.length??0,d=e.formats?.length??0;return{ok:s,checks:n,failures:o,summary(){let u=[e.skipDescribe===!0?null:"describe",d>0?`${d} format${d===1?"":"s"}`:null,i>0?`${i} observe path${i===1?"":"s"}`:null,a>0?`${a} explain pair${a===1?"":"s"}`:null].filter(l=>l!=null),c=u.length>0?u.join(", "):"describe-only";return s?`validateGraphObservability: OK (${c})`:`validateGraphObservability: ${o.length} failure(s) across ${c}`}}}var Jt=class extends Error{constructor(e,n){super(e,n),this.name=this.constructor.name}},ws=class extends Jt{constructor(n,r){super(`Duplicate ${n} registration: "${r}"`);this.kind=n;this.registrationName=r}},ks=class extends Jt{constructor(n,r,o){super(`Command "${n}" emitted undeclared event "${r}". Declared emits: [${o.join(", ")}]`);this.commandName=n;this.eventName=r;this.declaredEmits=o}},xs=class extends Jt{constructor(n,r,o){super(`Optimistic concurrency conflict on aggregate "${n}": expected version ${r}, got ${o}`);this.aggregateId=n;this.expected=r;this.actual=o}},Rs=class extends Jt{constructor(n){super(`Unknown command: "${n}". Register with command() first.`);this.commandName=n}},Wr=class extends Jt{constructor(n,r){super(`Command handler "${n}" threw: ${r instanceof Error?r.message:String(r)}`,{cause:r});this.commandName=n}};var Ur=class extends Jt{constructor(n,r){super(`Projection "${n}" rebuild failed: ${r instanceof Error?r.message:String(r)}`,{cause:r});this.projectionName=n}};Ae();Re();Vt();ae();ne();var Lg=Ct((t,e)=>{t("observe"),t("signal"),e("write")});function at(t){let e=Ke([],{name:t.name,maxSize:t.retainedLimit??1024,guard:t.guard??Lg,...t.versioning!=null?{versioning:t.versioning}:{}});return e.withLatest(),t.graph&&t.graph.add(e.entries,{name:t.name}),e}function La(t){if(t===null||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.keys(t))La(t[e]);return Object.freeze(t)}function Jr(t){let e=t.cache,r=(typeof e=="number"&&Number.isFinite(e)?e:0)+1;return t.down([[oe],[M,r]]),r}function Ss(t,e,n,r,o,s){let i=e(n,r,o);if(i===void 0)return;let a=s!=null?{...i,handlerVersion:s}:i;t.append(a)}function nt(t,e){let n=e.freeze??!0;return function(...o){let s=n?o.map(La):o,i=se(),a=e.seq?Jr(e.seq):void 0;try{let d=t(...s);return e.onSuccess&&Ss(e.audit,e.onSuccess,s,d,{t_ns:i,seq:a},e.handlerVersion),d}catch(d){if(e.onFailure){let u=d instanceof Error?d.name:typeof d;Ss(e.audit,e.onFailure,s,d,{t_ns:i,seq:a,errorType:u},e.handlerVersion)}throw d}}}function nr(t,e){let n=e.freeze??!0;return function(...o){let s=n?o.map(La):o,i=se(),a,d,u=!1,c;try{Z(()=>{e.seq&&(c=Jr(e.seq));try{a=t(...s),e.onSuccess&&Ss(e.audit,e.onSuccess,s,a,{t_ns:i,seq:c},e.handlerVersion)}catch(l){throw d=l,u=!0,l}})}catch(l){if(u&&e.onFailure){let p=d instanceof Error?d.name:typeof d;Ss(e.audit,e.onFailure,s,d,{t_ns:i,seq:c,errorType:p},e.handlerVersion)}throw u?d:l}return a}}function Yt(t,e,n=0){let r=A(n,{name:e,describeKind:"state"});return t.add(r,{name:e}),r}function Ic(t,e,n,r=0){let o={},s=new Q(e);for(let i of n){let a=A(r,{name:i,describeKind:"state"});s.add(a,{name:i}),o[i]=a}return t.mount(e,s),o}Ae();ae();Me();ve();function vt(t,e){t!=null&&At(n=>t.down(n),[[M,e]],Fe.tierOf)}function Yr(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[oe],[M,n+1]]),!0)}function We(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}function Qr(t){return t.relatedTo?.[0]??t.summary}var Ig=Ct((t,e)=>{t("write"),t("signal"),e("observe")}),Pg=Ct((t,e)=>{t("observe"),t("signal"),e("write")}),Pc=Ct((t,e)=>{t("observe"),t("signal"),e("write")});function Xr(t,e){return We("cqrs",t,e)}function Ia(t){if(t===null||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.keys(t))Ia(t[e]);return Object.freeze(t)}var Dg=t=>`${t.type}::${t.aggregateId??"__default__"}`,Gg=t=>t.commandName,Fg=t=>t.eventType,Ns=class extends Q{_eventLogs=new Map;_eventLogsByAggregate=new Map;_aggregateVersions=new Map;_aggregateLru=new Map;_commandRegs=new Map;_projections=new Set;_sagas=new Set;_keepaliveDisposers=[];_seq=0;_retainedLimit;_freezeCommandPayload;_freezeEventPayload;_maxAggregates;_dispatchSeqCursor;dispatches;audit;aggregateEvictions;constructor(e,n={}){super(e,n.graph),this._retainedLimit=n.retainedLimit??1024,this._freezeCommandPayload=n.freezeCommandPayload??!0,this._freezeEventPayload=n.freezeEventPayload??!0,this._maxAggregates=n.maxAggregates??1e4,this.dispatches=at({name:"dispatches",retainedLimit:this._retainedLimit,graph:this}),this.audit=this.dispatches,this.aggregateEvictions=at({name:"aggregateEvictions",retainedLimit:this._retainedLimit,graph:this}),this._dispatchSeqCursor=Yt(this,"dispatch_seq",0)}aggregateVersion(e,n){return this._aggregateVersions.get(`${e}::${n}`)??0}_touchAggregate(e){this._aggregateLru.delete(e),this._aggregateLru.set(e,!0)}_enforceAggregateLru(){for(;this._aggregateLru.size>this._maxAggregates;){let e=this._aggregateLru.keys().next();if(e.done)break;let n=e.value;this._aggregateLru.delete(n);let r=n.indexOf("::");if(r<0)continue;let o=n.slice(0,r),s=n.slice(r+2),i=this._aggregateVersions.get(n)??0;this._aggregateVersions.delete(n);let a=this._eventLogsByAggregate.get(o);a&&(a.delete(s),a.size===0&&this._eventLogsByAggregate.delete(o)),this.aggregateEvictions.append({aggregateId:s,type:o,lastVersion:i,t_ns:se()})}}destroy(){for(let e of this._keepaliveDisposers)e();this._keepaliveDisposers.length=0,super.destroy()}_attachedEventTiers=[];_attachedTierDisposers=new Map;attachEventStorage(e){this._attachedEventTiers.push(e);for(let[n,r]of this._eventLogs){let o=r.log.attachStorage(e),s=this._attachedTierDisposers.get(n);s||(s=[],this._attachedTierDisposers.set(n,s)),s.push(o)}for(let[n,r]of this._eventLogsByAggregate)for(let[o,s]of r){let i=`${n}::${o}`,a=s.log.attachStorage(e),d=this._attachedTierDisposers.get(i);d||(d=[],this._attachedTierDisposers.set(i,d)),d.push(a)}return()=>{let n=this._attachedEventTiers.indexOf(e);n>=0&&this._attachedEventTiers.splice(n,1)}}_autoWireStreamStorage(e,n){if(this._attachedEventTiers.length===0)return;let r=this._attachedTierDisposers.get(e);r||(r=[],this._attachedTierDisposers.set(e,r));for(let o of this._attachedEventTiers)r.push(n.attachStorage(o))}_bumpDispatchSeq(){let n=(this._dispatchSeqCursor.cache??0)+1;return this._dispatchSeqCursor.emit(n),n}event(e,n){if(n!==void 0)return this._ensureAggregateStream(e,n).node;let r=this._eventLogs.get(e);if(r)return r.node;let o=Ke([],{name:e,versioning:0,maxSize:this._retainedLimit});o.withLatest();let s=o.entries,i=C([s],([a])=>a,{name:e,describeKind:"state",meta:Xr("event",{event_name:e}),guard:Pc,initial:s.cache});return this.add(i,{name:e}),this._keepaliveDisposers.push(te(i)),this._eventLogs.set(e,{log:o,node:i}),this._autoWireStreamStorage(e,o),i}_ensureAggregateStream(e,n){this._eventLogs.has(e)||this.event(e);let r=this._eventLogsByAggregate.get(e);r||(r=new Map,this._eventLogsByAggregate.set(e,r));let o=`${e}::${n}`;this._touchAggregate(o);let s=r.get(n);if(s)return s;let i=`${e}_${n.replace(/[^a-zA-Z0-9_-]/g,"_")}`,a=Ke([],{name:i,versioning:0,maxSize:this._retainedLimit});a.withLatest();let d=a.entries,u=C([d],([f])=>f,{name:i,describeKind:"state",meta:Xr("event_aggregate",{event_name:e,aggregate_id:n}),guard:Pc,initial:d.cache}),c=i,l=0;for(;this.nameOf(this.resolveOptional(c)??u)===c&&(l+=1,c=`${i}_${l}`,this.resolveOptional(c)!==void 0););try{this.add(u,{name:c})}catch{}this._keepaliveDisposers.push(te(u));let p={log:a,node:u};return r.set(n,p),this._autoWireStreamStorage(`${e}::${n}`,a),this._enforceAggregateLru(),p}resolveOptional(e){try{return this.resolve(e)}catch{return}}_appendEvent(e,n,r){let o=this._eventLogs.get(e);if(o||(this.event(e),o=this._eventLogs.get(e)),o.node.status==="completed"||o.node.status==="errored")throw new Error(`Cannot dispatch to terminated event stream "${e}" (status: ${o.node.status}).`);let s,i;if(r?.aggregateId!==void 0){let c=`${e}::${r.aggregateId}`;s=(this._aggregateVersions.get(c)??0)+1,this._aggregateVersions.set(c,s),i=this._ensureAggregateStream(e,r.aggregateId)}let a=o.log.entries.v,d=this._freezeEventPayload?Ia(n):n,u={type:e,payload:d,timestampNs:se(),seq:++this._seq,...r?.aggregateId!==void 0?{aggregateId:r.aggregateId}:{},...s!==void 0?{aggregateVersion:s}:{},...r?.correlationId!==void 0?{correlationId:r.correlationId}:{},...r?.causationId!==void 0?{causationId:r.causationId}:{},...r?.metadata!==void 0?{metadata:Object.freeze({...r.metadata})}:{},...r?.handlerVersion!==void 0?{handlerVersion:r.handlerVersion}:{},...a!=null?{v0:{id:a.id,version:a.version}}:{}};return o.log.append(u),i&&i.log.append(u),u}command(e,n){if(this._commandRegs.has(e))throw new ws("command",e);let r=typeof n=="function"?{handler:n}:n,o=A(void 0,{name:e,describeKind:"state",meta:{...Xr("command",{command_name:e}),error:null},guard:Ig});if(this.add(o,{name:e}),this._commandRegs.set(e,{handler:r.handler,...r.emits!==void 0?{emits:r.emits}:{},...r.handlerVersion!==void 0?{handlerVersion:r.handlerVersion}:{}}),r.emits)for(let s of r.emits)this._eventLogs.has(s)||this.event(s);return o}dispatch(e,n,r){let o=this._commandRegs.get(e);if(!o)throw new Rs(e);if(r?.aggregateId!==void 0&&r.expectedAggregateVersion!==void 0&&o.emits!==void 0){let p=0;for(let f of o.emits){let m=this._aggregateVersions.get(`${f}::${r.aggregateId}`);m!==void 0&&m>p&&(p=m)}if(p!==r.expectedAggregateVersion)throw new xs(r.aggregateId,r.expectedAggregateVersion,p)}let s=this.resolve(e),i=this._freezeCommandPayload?Ia(n):n,a=[],d=se(),u=0,c,l=!1;try{Z(()=>{u=this._bumpDispatchSeq(),s.emit(i,{internal:!0});try{o.handler(i,{emit:(p,f)=>{if(o.emits!==void 0&&!o.emits.includes(p))throw new ks(e,p,o.emits);a.push(p),this._appendEvent(p,f,{...r?.aggregateId!==void 0?{aggregateId:r.aggregateId}:{},...r?.correlationId!==void 0?{correlationId:r.correlationId}:{},...r?.causationId!==void 0?{causationId:r.causationId}:{},...r?.metadata!==void 0?{metadata:Object.freeze({...r.metadata})}:{},...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}})}}),s.meta.error.emit(null,{internal:!0}),this.dispatches.append({commandName:e,payload:i,status:"success",emittedEvents:[...a],t_ns:d,seq:u,...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}})}catch(p){throw c=p,l=!0,p}})}catch(p){if(l){s.meta.error.emit(c,{internal:!0});let f=c instanceof Error?c.name:typeof c,m=c instanceof Wr?c:new Wr(e,c);this.dispatches.append({commandName:e,payload:i,status:"failed",error:m,errorType:f,emittedEvents:[...a],t_ns:d,seq:u,...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}})}throw l?c:p}}projection(e){let{name:n,events:r,reducer:o,initial:s}=e,i=e.mode??"scan",a=e.freezeInputs??!0,d=e.snapshot,u=r.map(E=>(this._eventLogs.has(E)||this.event(E),this._eventLogs.get(E).node));function c(E){E.sort((_,O)=>_.timestampNs-O.timestampNs||_.seq-O.seq||(_.aggregateId??"").localeCompare(O.aggregateId??""))}function l(E){let _=[];for(let O of E)_.push(...O);return c(_),_}let p=u.map(E=>E.cache??[]),f=l(p),m=a?Object.freeze(f):f,h=0,g=s;i==="scan"&&f.length>0&&(g=o(s,m),h=f.length);let y=i==="replay"?o(s,m):g,b=d?.saveDebounceMs??1e3,v=d?.saveEvery??1e3,T,w=0;function x(E){if(d?.save){if(w+=1,w>=v){w=0,T!==void 0&&(clearTimeout(T),T=void 0);let _=d.save(E);_ instanceof Promise&&_.catch(()=>{});return}T!==void 0&&clearTimeout(T),T=setTimeout(()=>{T=void 0,w=0;let _=d.save(E);_ instanceof Promise&&_.catch(()=>{})},b)}}let k=C(u,E=>{let _=l(E),O;if(i==="replay"){let N=a?Object.freeze(_):_;O=o(s,N)}else{let N=_.slice(h);h=_.length;let L=a?Object.freeze(N):N;O=o(g,L),g=O}return x(O),O},{name:n,describeKind:"derived",meta:Xr("projection",{projection_name:n,source_events:r}),guard:Pg,initial:y});return this.add(k,{name:n}),this._keepaliveDisposers.push(te(k)),this._keepaliveDisposers.push(()=>{T!==void 0&&(clearTimeout(T),T=void 0)}),this._projections.add(n),{node:k,rebuild:async E=>{try{let _=E?.pageSize??1e3,O=E?.fromTier??this._attachedEventTiers[0]?.[0],N=l(u.map(j=>j.cache??[])).length,L=s;if(d?.load){let j=await d.load();j!==void 0&&(L=j)}if(!O||!O.loadEntries){let j=l(u.map(D=>D.cache??[])),$=a?Object.freeze(j):j;L=o(L,$)}else{let j=new Set(r),$,D=!1;for(;!D;){let K=await O.loadEntries({cursor:$,pageSize:_}),F=[...K.entries].filter(G=>j.has(G.type));c(F);let H=a?Object.freeze(F):F;L=o(L,H),$=K.cursor,D=!$||K.entries.length===0}}if(i==="scan"){let j=l(u.map(D=>D.cache??[])),$=j.slice(N);if($.length>0){let D=a?Object.freeze($):$;L=o(L,D)}g=L,h=j.length}return k.emit(L,{internal:!0}),L}catch(_){throw new Ur(n,_)}},reset:async()=>{try{let E=s;if(d?.load){let L=await d.load();L!==void 0&&(E=L)}let _=l(u.map(L=>L.cache??[])),O=a?Object.freeze(_):_,N=o(E,O);return i==="scan"&&(g=N,h=_.length),k.emit(N,{internal:!0}),N}catch(E){throw new Ur(n,E)}}}}saga(e,n,r,o={}){let s=n.map(f=>(this._eventLogs.has(f)||this.event(f),this._eventLogs.get(f).node)),i=Ic(this,`${e}_cursor`,n,0),a=at({name:`${e}_invocations`,retainedLimit:this._retainedLimit,graph:this}),d=o.aggregateId,u=o.errorPolicy??"advance",c=new Map;for(let f of n){let m=i[f];c.set(f,m.cache??0);let h=m.subscribe(g=>{for(let y of g)y[0]===M&&c.set(f,y[1])});this._keepaliveDisposers.push(h)}let l={},p=U(s,(f,m)=>{let h=l.n.meta.error;for(let g=0;g<f.length;g++){let y=f[g];if(y==null||y.length===0)continue;let b=y.at(-1);if(!b)continue;let v=n[g],T=i[v],w=c.get(v)??0;if(b.length>w){let x=b.slice(w),k=w;for(let S of x){let R=S;if(d!==void 0&&R.aggregateId!==d){k+=1;continue}try{r(R),h.emit(null,{internal:!0}),a.append({eventType:v,status:"success",aggregateId:R.aggregateId,event:R,t_ns:se(),...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}}),k+=1}catch(E){if(h.emit(E,{internal:!0}),a.append({eventType:v,status:"failed",error:E,errorType:E instanceof Error?E.name:typeof E,aggregateId:R.aggregateId,event:R,t_ns:se(),...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}}),u==="hold")break;k+=1}}T.emit(k)}}},{name:e,describeKind:"effect",meta:{...Xr("saga",{saga_name:e,source_events:n}),error:null}});return l.n=p,this.add(p,{name:e}),this._keepaliveDisposers.push(te(p)),this._sagas.add(e),{node:p,invocations:a,audit:a,cursors:i}}};function Pa(t,e){let n=new Ns(t,e),{factory:r,factoryArgs:o,...s}=e??{};return n.tagFactory("cqrs",st(s)),n}var Ga=class{constructor(e){this.graph=e}onModuleDestroy(){this.graph.destroy()}},Fa=class{graph=new Q("request");onModuleDestroy(){this.graph.destroy()}},Dc,Da;Dc=[(0,Zr.Module)({})];var Qt=class Qt{static forRoot(e){let n=e??{},r=n.name??"root",o=[{provide:mt,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 Ga(s),inject:[mt]},{provide:mn,useFactory:(s,i)=>new mn(s,i),inject:[mt,Gc.ModuleRef]}];if(n.nodes)for(let s of n.nodes)o.push({provide:ht(s),useFactory:i=>i.resolve(s),inject:[mt]});return n.requestScope&&o.push({provide:Symbol.for("graphrefly:request-lifecycle"),useFactory:()=>new Fa,scope:Zr.Scope.REQUEST},{provide:un,useFactory:s=>s.graph,inject:[Symbol.for("graphrefly:request-lifecycle")],scope:Zr.Scope.REQUEST}),{module:Qt,global:!0,providers:o,exports:[mt,...(n.nodes??[]).map(ht),...n.requestScope?[un]:[]]}}static forFeature(e){let n=[{provide:ut(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:[mt]}];if(e.nodes)for(let r of e.nodes)n.push({provide:ht(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[ut(e.name)]});return{module:Qt,providers:n,exports:[ut(e.name),...(e.nodes??[]).map(r=>ht(`${e.name}::${r}`))]}}static forCqrs(e){let n=[{provide:ut(e.name),useFactory:r=>{let o=Pa(e.name,e.cqrs);return e.eventStorage&&o.attachEventStorage(e.eventStorage),e.build&&e.build(o),r.mount(e.name,o),o},inject:[mt]}];if(e.nodes)for(let r of e.nodes)n.push({provide:ht(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[ut(e.name)]});return{module:Qt,providers:n,exports:[ut(e.name),...(e.nodes??[]).map(r=>ht(`${e.name}::${r}`))]}}};Da=mu(null),Qt=yu(Da,0,"GraphReflyModule",Dc,Qt),hu(Da,1,Qt);var _s=Qt;var Os={};Se(Os,{useStore:()=>$g,useSubscribe:()=>Fc,useSubscribeRecord:()=>jg});var Dt=require("react");ae();function Fc(t){return(0,Dt.useSyncExternalStore)(e=>{let n=!1,r=t.subscribe(()=>{n||e()});return()=>{n=!0,r()}},()=>t.cache,()=>t.cache)}function $g(t){let e=Fc(t),n=(0,Dt.useCallback)(r=>{t.down([[oe],[M,r]])},[t]);return[e,n]}function jg(t,e){let n=(0,Dt.useRef)(e);n.current=e;let r=(0,Dt.useMemo)(()=>{let o=()=>{let i={},a=t.cache??[];for(let d of a){let u=n.current(d),c={};for(let l of Object.keys(u))c[l]=u[l].cache;i[d]=c}return i},s=o();return{subscribe:i=>{let a=!1,d=[],u=()=>{for(let p of d)p();d=[]},c=p=>{u();for(let f of p){let m=n.current(f);for(let h of Object.keys(m)){let g=m[h].subscribe(()=>{s=o(),a||i()});d.push(g)}}s=o(),a||i()},l=t.subscribe(p=>{let f=p.some(m=>m[0]===M||m[0]===q);!a&&f&&c(t.cache??[])});return c(t.cache??[]),()=>{a=!0,l(),u()}},getSnapshot:()=>s}},[t]);return(0,Dt.useSyncExternalStore)(r.subscribe,r.getSnapshot,r.getSnapshot)}var Cs={};Se(Cs,{Signal:()=>Bg});Ae();ae();ne();var rr=[];function As(t){let e=t.cache;return t.subscribe(r=>{for(let[o,s]of r)o===M&&(e=s)})(),e}var $a=class{_node;_equals;constructor(e,n){this._equals=n?.equals??Object.is,this._node=A(e,{...n,resubscribable:!0,resetOnTeardown:!0})}get(){let e=rr[rr.length-1];return e?(this._node.status==="sentinel"&&As(this._node),e(this._node)):this._node.status==="sentinel"?As(this._node):this._node.cache}set(e){this._equals(this.get(),e)||Z(()=>{this._node.down([[oe],[M,e]])})}},ja=class{_node;constructor(e,n){this._node=dn(r=>{rr.push(r);try{return e()}finally{rr.pop()}},{...n,describeKind:"derived",resubscribable:!0,resetOnTeardown:!0})}get(){let e=rr[rr.length-1];return e?(this._node.status==="sentinel"&&As(this._node),e(this._node)):this._node.status==="sentinel"?As(this._node):this._node.cache}},Bg={State:$a,Computed:ja,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===M){if(r){r=!1;continue}n.data?.(i)}s===I&&n.error?.(i),s===P&&n.complete?.()}})}};var Ls={};Se(Ls,{useStore:()=>Vg,useSubscribe:()=>$c,useSubscribeRecord:()=>Kg});var Gt=require("solid-js");ae();function $c(t){let[e,n]=(0,Gt.createSignal)(t.cache,{equals:!1}),r=t.subscribe(()=>{n(()=>t.cache)});return(0,Gt.getOwner)()?(0,Gt.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 Vg(t){return[$c(t),r=>{t.down([[oe],[M,r]])}]}function Kg(t,e){let[n,r]=(0,Gt.createSignal)({},{equals:!1}),o=[],s=()=>{for(let u of o)u();o=[]},i=()=>{let u={};for(let c of t.cache??[]){let l=e(c),p={};for(let f of Object.keys(l))p[f]=l[f].cache;u[c]=p}return u},a=u=>{s();for(let c of u){let l=e(c);for(let p of Object.keys(l)){let f=l[p].subscribe(()=>{r(()=>i())});o.push(f)}}r(()=>i())},d=t.subscribe(u=>{u.some(c=>c[0]===M||c[0]===q)&&a(t.cache??[])});return a(t.cache??[]),(0,Gt.getOwner)()?(0,Gt.onCleanup)(()=>{d(),s()}):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribeRecord called outside a Solid reactive owner \u2014 subscription will not be auto-disposed."),n}var Is={};Se(Is,{useStore:()=>zg,useSubscribe:()=>qg,useSubscribeRecord:()=>Hg});ae();function qg(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n}}}function zg(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n},set(e){t.down([[oe],[M,e]])},update(e){let n=e(t.cache);t.down([[oe],[M,n]])}}}function Hg(t,e){return{subscribe(n){let r=[],o=()=>{for(let d of r)d();r=[]},s=()=>{let d={};for(let u of t.cache??[]){let c=e(u),l={};for(let p of Object.keys(c))l[p]=c[p].cache;d[u]=l}return d},i=d=>{o();for(let u of d){let c=e(u);for(let l of Object.keys(c)){let p=c[l].subscribe(()=>{n(s())});r.push(p)}}n(s())},a=t.subscribe(d=>{d.some(u=>u[0]===M||u[0]===q)&&i(t.cache??[])});return i(t.cache??[]),()=>{a(),o()}}}}var Ps={};Se(Ps,{useStore:()=>Ug,useSubscribe:()=>Wg,useSubscribeRecord:()=>Jg});var qe=require("vue");ae();function Wg(t){let e=(0,qe.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,qe.getCurrentScope)()?(0,qe.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,qe.readonly)(e)}function Ug(t){let e=(0,qe.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,qe.getCurrentScope)()?(0,qe.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useStore called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,qe.computed)({get:()=>e.value,set:r=>{t.down([[oe],[M,r]])}})}function Jg(t,e){let n=(0,qe.shallowRef)({}),r=new Map;function o(){let a={};for(let[d,u]of r)a[d]={...u.values};n.value=a}function s(a){for(let u of r.values())for(let c of u.subs)c();r.clear();for(let u of a){let c=e(u),l=Object.keys(c),p={},f=[];for(let m of l){let h=c[m];p[m]=h.cache;let g=h.subscribe(()=>{p[m]=h.cache,o()});f.push(g)}r.set(u,{subs:f,values:p})}let d={};for(let[u,c]of r)d[u]={...c.values};n.value=d}return(0,qe.watch)(()=>[...(typeof t=="function"?t():(0,qe.isRef)(t)?t.value:t)??[]],a=>s(a??[]),{immediate:!0}),(0,qe.getCurrentScope)()?(0,qe.onScopeDispose)(()=>{for(let a of r.values())for(let d of a.subs)d();r.clear()}):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribeRecord called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,qe.readonly)(n)}var Ds={};Se(Ds,{create:()=>Qg});ae();ne();var Yg=()=>!1;function Qg(t){let e=new Q("zustand"),n=A(void 0,{name:"state",equals:Yg});e.add(n,{name:"state"});let r=()=>n.cache,o=(a,d)=>{let u=n.cache,c=typeof a=="function"?a(u):a;n.emit(d?c:{...u,...c})},s={getState:r,setState:o,getInitialState:()=>i,subscribe:a=>{let d=!0,u=n.cache;return n.subscribe(c=>{for(let[l,p]of c)if(l===M){if(d){d=!1;continue}a(p,u),u=p}})},destroy:e.destroy.bind(e)},i=t(o,r,s);return n.emit(i),Object.assign(e,s)}var rd={};Se(rd,{CircuitOpenError:()=>yt,ContentAddressedMissError:()=>ao,NS_PER_MS:()=>He,NS_PER_SEC:()=>lt,NativeIndexBackend:()=>lo,NativeListBackend:()=>po,NativeLogBackend:()=>Hr,NativeMapBackend:()=>so,NativePubSubBackend:()=>co,RateLimiterOverflowError:()=>ln,ResettableTimer:()=>Ie,TimeoutError:()=>pn,appendLogStorage:()=>ed,audit:()=>al,awaitSettled:()=>as,buffer:()=>dl,bufferCount:()=>ul,bufferTime:()=>ll,cached:()=>nc,canonicalJson:()=>uo,cascadingCache:()=>vp,catchError:()=>wl,checkpointToRedis:()=>lp,checkpointToS3:()=>cp,circuitBreaker:()=>Nt,combine:()=>Ka,combineLatest:()=>bl,concat:()=>el,concatMap:()=>rl,constant:()=>Qo,contentAddressedStorage:()=>Vs,createTransport:()=>Zt,createWatermarkController:()=>Zn,csvRows:()=>Hl,debounce:()=>za,debounceTime:()=>vl,decorrelatedJitter:()=>ts,defer:()=>Zu,delay:()=>sl,deserializeError:()=>wn,dictKv:()=>Cp,dictSnapshot:()=>Lp,distill:()=>js,distinctUntilChanged:()=>Qc,elementAt:()=>Uc,empty:()=>Yu,escapeRegexChar:()=>va,exhaustMap:()=>nl,exponential:()=>Zo,externalBundle:()=>Gs,externalProducer:()=>bn,fallback:()=>Yn,fibonacci:()=>es,filter:()=>rt,find:()=>Wc,first:()=>Fs,firstValueFrom:()=>et,firstWhere:()=>rs,flatMap:()=>ol,forEach:()=>Wt,fromAny:()=>Y,fromAsyncIter:()=>Br,fromCSV:()=>zl,fromClickHouseWatch:()=>Yl,fromCron:()=>os,fromDrizzle:()=>hp,fromEvent:()=>Ju,fromHTTP:()=>Ya,fromHTTPPoll:()=>Al,fromHTTPStream:()=>Ol,fromIter:()=>ss,fromKafka:()=>Bl,fromKysely:()=>yp,fromMCP:()=>Il,fromNATS:()=>Zl,fromNDJSON:()=>Jl,fromOTel:()=>Pl,fromPrisma:()=>gp,fromPrometheus:()=>jl,fromPromise:()=>Xn,fromPulsar:()=>Ql,fromRabbitMQ:()=>tp,fromRaf:()=>Uu,fromRedisStream:()=>Kl,fromSSE:()=>Ml,fromSqlite:()=>pp,fromSqliteCursor:()=>fp,fromStatsD:()=>Fl,fromSyslog:()=>Dl,fromTimer:()=>Ze,fromWebSocket:()=>Ja,fromWebSocketReconnect:()=>Ll,fromWebhook:()=>kl,globToRegExp:()=>Hu,interval:()=>ml,jsonCodec:()=>ar,jsonCodecFor:()=>Mp,keepalive:()=>te,kvStorage:()=>Ws,last:()=>Hc,linear:()=>Xo,lru:()=>Za,makeHttpError:()=>wt,map:()=>eo,matchesAnyPattern:()=>Wu,matchesCron:()=>Yo,memoryAppendLog:()=>Ap,memoryBackend:()=>mo,memoryKv:()=>go,memorySnapshot:()=>Op,merge:()=>Et,mergeMap:()=>qa,mergeReactiveLogs:()=>Lc,nameToSignal:()=>vn,ndjsonRows:()=>Wl,never:()=>Qu,nodeSignal:()=>ds,of:()=>Ta,onFirstData:()=>no,pairwise:()=>Xc,parseCron:()=>Jo,parsePrometheusText:()=>Qa,parseSSEStream:()=>$t,parseStatsD:()=>$l,parseSyslog:()=>Gl,pausable:()=>hl,pubsub:()=>Rp,race:()=>tl,rateLimiter:()=>Jn,reactiveCounter:()=>wa,reactiveIndex:()=>Ep,reactiveList:()=>Ks,reactiveLog:()=>Ke,reactiveMap:()=>je,reactiveSink:()=>Ue,reduce:()=>Kc,repeat:()=>gl,replay:()=>is,rescue:()=>ro,resolveBackoffPreset:()=>qt,retry:()=>St,sample:()=>il,scan:()=>Vc,serializeError:()=>Tn,share:()=>tc,shareReplay:()=>rc,signalToName:()=>Xt,singleFromAny:()=>qs,singleNodeFromAny:()=>_p,skip:()=>Va,snapshotStorage:()=>Hs,sortJsonValue:()=>fo,stableJsonString:()=>zs,stratify:()=>ho,switchMap:()=>ke,take:()=>to,takeUntil:()=>zc,takeWhile:()=>qc,tap:()=>Jc,tapFirst:()=>Yc,throttle:()=>Ha,throttleTime:()=>Tl,throwError:()=>Xu,timeout:()=>Qn,toArray:()=>ec,toCSV:()=>rp,toClickHouse:()=>op,toFile:()=>Xa,toHTTP:()=>xl,toKafka:()=>Vl,toLoki:()=>dp,toMongo:()=>ap,toNATS:()=>ep,toObservable:()=>Uo,toPostgres:()=>ip,toPulsar:()=>Xl,toRabbitMQ:()=>np,toReadableStream:()=>_l,toRedisStream:()=>ql,toS3:()=>sp,toSSE:()=>Nl,toSSEBytes:()=>El,toSqlite:()=>mp,toTempo:()=>up,toWebSocket:()=>Cl,tokenBucket:()=>zt,topologyDiff:()=>er,valve:()=>yl,verifiable:()=>kp,window:()=>fl,windowCount:()=>cl,windowTime:()=>pl,withBreaker:()=>Un,withLatestFrom:()=>Ft,withMaxAttempts:()=>ya,withStatus:()=>Ht,workerBridge:()=>td,workerSelf:()=>nd,zip:()=>Zc});Ae();Re();ae();Me();ne();Ae();ae();ne();function jc(t){return{describeKind:"producer",...t}}function bn(t,e){return z(n=>{let r=!0,o={emit(i){r&&n.emit(i)},error(i){r&&(r=!1,n.down([[I,i]]))},complete(){r&&(r=!1,n.down([[P]]))}},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{}}},jc(e))}function Gs(t,e,n){let r=!0,o,s=0,i=0,a={},d=[],u=()=>{let f=o;o=void 0;try{f?.()}catch{}};for(let f of e){let m=n?.name?`${n.name}::${f}`:f,h=n?.channelOpts?.[f],g=z(y=>(s++,()=>{i++,s>0&&i>=s&&i>=e.length&&u()}),jc({...h,name:m}));a[f]=g,d.push(g)}let c={};for(let f of e)c[f]=m=>{r&&a[f].down([[M,m]])};c.error=f=>{r&&(r=!1,Z(()=>{for(let m of d)m.down([[I,f]])}),u())},c.complete=()=>{r&&(r=!1,Z(()=>{for(let f of d)f.down([[P]])}),u())};let l=t(c);return o=typeof l=="function"?l:void 0,Object.assign(a,{dispose:()=>{r&&(r=!1,Z(()=>{for(let f of d)try{f.down([[P]])}catch{}}),u())}})}Re();ae();it();Me();ne();ve();function ce(t){return{describeKind:"derived",...t}}function Bc(t){return{describeKind:"derived",partial:!0,...t}}function eo(t,e,n){return U([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[q]]);return}for(let i of s)o.emit(e(i))},{...ce(n),meta:{...we("map"),...n?.meta??{}}})}function rt(t,e,n){return U([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[q]]);return}let i=!1;for(let a of s)e(a)&&(o.emit(a),i=!0);i||o.down([[q]])},{...ce(n),meta:{...we("filter"),...n?.meta??{}}})}function Vc(t,e,n,r){return U([t],(o,s,i)=>{"acc"in i.store||(i.store.acc=n);let a=o[0];if(a==null||a.length===0){s.down([[q]]);return}for(let d of a)i.store.acc=e(i.store.acc,d),s.emit(i.store.acc)},{...ce(r),initial:n,resetOnTeardown:!0,meta:{...we("scan",{initial:n}),...r?.meta??{}}})}function Kc(t,e,n,r){return U([t],(o,s,i)=>{if("acc"in i.store||(i.store.acc=n),i.terminalDeps[0]===!0){s.emit(i.store.acc),s.down([[P]]);return}let a=o[0];if(a==null||a.length===0){s.down([[q]]);return}for(let d of a)i.store.acc=e(i.store.acc,d)},{...ce(r),completeWhenDepsComplete:!1,meta:{...we("reduce",{initial:n}),...r?.meta??{}}})}function to(t,e,n){return e<=0?U([t],(r,o,s)=>{s.store.completed||(s.store.completed=!0,o.down([[P]]))},{...ce(n),completeWhenDepsComplete:!1,meta:{...we("take",{count:e}),...n?.meta??{}}}):U([t],(r,o,s)=>{if("taken"in s.store||(s.store.taken=0),s.store.done){o.down([[q]]);return}if(s.terminalDeps[0]===!0){s.store.done=!0,o.down([[P]]);return}let i=r[0];if(i==null||i.length===0){o.down([[q]]);return}for(let a of i)if(s.store.taken++,o.emit(a),s.store.taken>=e){s.store.done=!0,o.down([[P]]);return}},{...ce(n),completeWhenDepsComplete:!1,meta:{...we("take",{count:e}),...n?.meta??{}}})}function Va(t,e,n){return U([t],(r,o,s)=>{"skipped"in s.store||(s.store.skipped=0);let i=r[0];if(i==null||i.length===0){o.down([[q]]);return}let a=!1;for(let d of i)s.store.skipped++,s.store.skipped<=e||(o.emit(d),a=!0);a||o.down([[q]])},ce(n))}function qc(t,e,n){return U([t],(r,o,s)=>{if(s.store.done){o.down([[q]]);return}let i=r[0];if(i==null||i.length===0){o.down([[q]]);return}for(let a of i){if(!e(a)){s.store.done=!0,o.down([[P]]);return}o.emit(a)}},{...ce(n),completeWhenDepsComplete:!1})}function zc(t,e,n){let r=n?.predicate??(i=>i[0]===M),{predicate:o,...s}=n??{};return z(i=>{let a=!1,d=t.subscribe(c=>{if(!a)for(let l of c){if(a)return;l[0]===M?i.emit(l[1]):(l[0]===P||l[0]===I)&&(a=!0,i.down([l]))}}),u=e.subscribe(c=>{if(!a)for(let l of c){if(a)return;if(r(l)){a=!0,i.down([[P]]);return}}});return()=>{d(),u()}},ce(s))}function Fs(t,e){return to(t,1,e)}function Hc(t,e){let{defaultValue:n,...r}=e??{},o=e!=null&&Object.hasOwn(e,"defaultValue");return U([t],(s,i,a)=>{if(a.terminalDeps[0]===!0){a.store.has?i.emit(a.store.latest):o&&i.emit(n),i.down([[P]]);return}let d=s[0];if(d==null||d.length===0){i.down([[q]]);return}a.store.latest=d.at(-1),a.store.has=!0},{...ce(r),completeWhenDepsComplete:!1})}function Wc(t,e,n){return to(rt(t,e,n),1,n)}function Uc(t,e,n){return to(Va(t,e,n),1,n)}function Jc(t,e,n){if(typeof e=="function")return U([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[q]]);return}for(let a of i)e(a),s.emit(a)},{...ce(n),meta:{...we("tap"),...n?.meta??{}}});let r=e;return U([t],(o,s,i)=>{if(i.terminalDeps[0]!==void 0){i.terminalDeps[0]===!0?(r.complete?.(),s.down([[P]])):(r.error?.(i.terminalDeps[0]),s.down([[I,i.terminalDeps[0]]]));return}let a=o[0];if(a==null||a.length===0){s.down([[q]]);return}for(let d of a)r.data?.(d),s.emit(d)},{...ce(n),completeWhenDepsComplete:!1,meta:{...we("tap"),...n?.meta??{}}})}function no(t,e,n){let r=n?.where??(s=>s!=null),o=!1;return U([t],(s,i)=>{let a=s[0];if(a==null||a.length===0){i.down([[q]]);return}for(let d of a)!o&&r(d)&&(o=!0,e(d)),i.emit(d)},ce(n))}var Yc=no;function Qc(t,e=Object.is,n){return U([t],(r,o,s)=>{let i=r[0];if(i==null||i.length===0){o.down([[q]]);return}let a=!1;for(let d of i)s.store.hasPrev&&e(s.store.prev,d)||(s.store.prev=d,s.store.hasPrev=!0,o.emit(d),a=!0);a||o.down([[q]])},{...ce(n),meta:{...we("distinctUntilChanged"),...n?.meta??{}}})}function Xc(t,e){return U([t],(n,r,o)=>{let s=n[0];if(s==null||s.length===0){r.down([[q]]);return}let i=!1;for(let a of s)if(!o.store.hasPrev)o.store.prev=a,o.store.hasPrev=!0;else{let d=[o.store.prev,a];o.store.prev=a,r.emit(d),i=!0}i||r.down([[q]])},ce(e))}function Ka(...t){let e=[...t];return C(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 Ft(t,e,n){return U([t,e],(r,o,s)=>{let i=r[0],a=r[1],d=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([[q]]);return}for(let u of i)o.emit([u,d])}else o.down([[q]])},{...Bc(n),meta:{...we("withLatestFrom"),...n?.meta??{}}})}function Et(...t){return t.length===0?z(e=>{e.down([[P]])},{...ce(),meta:{...we("merge")}}):z(e=>{let n=t.length,r=0,o=[];for(let s of t){let i=s.subscribe(a=>{for(let d of a)d[0]===M?e.emit(d[1]):d[0]===P?(r+=1,r>=n&&e.down([[P]])):d[0]===I&&e.down([d])});o.push(i)}return()=>{for(let s of o)s()}},{...ce(),meta:{...we("merge")}})}function Zc(...t){let e=t.length;return e===0?z(n=>{n.emit([]),n.down([[P]])},ce()):z(n=>{let r=Array.from({length:e},()=>[]),o=e;function s(){for(;r.every(a=>a.length>0);){let a=r.map(d=>d.shift());n.emit(a)}}let i=[];for(let a=0;a<e;a++){let d=a,u=t[a].subscribe(c=>{for(let l of c)l[0]===M?(r[d].push(l[1]),s()):l[0]===P?(o-=1,(o===0||r[d].length===0)&&n.down([[P]])):l[0]===I&&n.down([l])});i.push(u)}return()=>{for(let a of i)a()}},ce())}function el(t,e,n){return z(r=>{let o=0,s=[],i,a;return a=e.subscribe(d=>{for(let u of d)o===0?u[0]===M?s.push(u[1]):u[0]===I&&r.down([u]):u[0]===M?r.emit(u[1]):(u[0]===P||u[0]===I)&&r.down([u])}),i=t.subscribe(d=>{for(let u of d)if(o===0)if(u[0]===M)r.emit(u[1]);else if(u[0]===P){o=1;for(let c of s)r.emit(c);s.length=0}else u[0]===I&&r.down([u])}),()=>{i?.(),a?.()}},ce(n))}function tl(...t){return t.length===0?z(e=>{e.down([[P]])},ce()):t.length===1?U([t[0]],(e,n)=>{let r=e[0];if(r==null||r.length===0){n.down([[q]]);return}for(let o of r)n.emit(o)},ce()):z(e=>{let n=null,r=[];for(let o=0;o<t.length;o++){let s=o,i=t[o].subscribe(a=>{for(let d of a){if(n!==null&&s!==n)return;d[0]===M?(n===null&&(n=s),e.emit(d[1])):(d[0]===P||d[0]===I)&&(n===null||s===n)&&e.down([d])}});r.push(i)}return()=>{for(let o of r)o()}},ce())}function $s(t,e,n){let r,o=!1,s=()=>{o||(o=!0,n())};return r=t.subscribe(i=>{let a=!1,d=!1;for(let u of i)u[0]!==ft&&(u[0]===M?e.emit(u[1]):u[0]===P?a=!0:u[0]===I?(d=!0,e.down([u])):(u[0]===oe||u[0]===q)&&e.down([u]));d?(r?.(),r=void 0,s()):a&&s()}),()=>{r?.(),r=void 0}}function ke(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return U([t],(i,a,d)=>{if(d.terminalDeps[0]!=null&&d.terminalDeps[0]!==!0){s();return}if(d.terminalDeps[0]===!0){o=!0,r||a.down([[P]]);return}let u=i[0];if(!(u==null||u.length===0))return s(),r=$s(Y(e(u[u.length-1])),a,()=>{s(),o&&a.down([[P]])}),{deactivate:()=>{s(),o=!1}}},{...ce(n),completeWhenDepsComplete:!1,meta:{...we("switchMap"),...n?.meta??{}}})}function nl(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return U([t],(i,a,d)=>{if(d.terminalDeps[0]!=null&&d.terminalDeps[0]!==!0){s();return}if(d.terminalDeps[0]===!0){o=!0,r||a.down([[P]]);return}let u=i[0];if(!(u==null||u.length===0))return r===void 0?r=$s(Y(e(u[0])),a,()=>{s(),o&&a.down([[P]])}):a.down([[q]]),{deactivate:()=>{s(),o=!1}}},{...ce(n),completeWhenDepsComplete:!1})}function rl(t,e,n){let{maxBuffer:r,...o}=n??{},s=[],i,a=!1,d;function u(){i?.(),i=void 0}function c(){if(!d||i!==void 0)return;if(s.length===0){a&&d.down([[P]]);return}let p=s.shift();i=$s(Y(e(p)),d,()=>{u(),c()})}function l(p){r&&r>0&&s.length>=r&&s.shift(),s.push(p),c()}return U([t],(p,f,m)=>{if(d=f,m.terminalDeps[0]!=null&&m.terminalDeps[0]!==!0){u(),s.length=0;return}if(m.terminalDeps[0]===!0){a=!0,c();return}let h=p[0];if(!(h==null||h.length===0)){for(let g of h)l(g);return{deactivate:()=>{u(),s.length=0,a=!1}}}},{...ce(o),completeWhenDepsComplete:!1})}function qa(t,e,n){let{concurrent:r,...o}=n??{},s=r!=null&&r>0?r:Number.POSITIVE_INFINITY,i=0,a=!1,d=new Set,u=[],c;function l(){a&&i===0&&u.length===0&&c&&c.down([[P]])}function p(g){if(!c)return;i++;let y;y=$s(Y(e(g)),c,()=>{y&&d.delete(y),i--,f(),l()}),d.add(y)}function f(){for(;u.length>0&&i<s;)p(u.shift())}function m(g){i<s?p(g):u.push(g)}function h(){for(let g of d)g();d.clear(),i=0,u.length=0}return U([t],(g,y,b)=>{if(c=y,b.terminalDeps[0]!=null&&b.terminalDeps[0]!==!0){h();return}if(b.terminalDeps[0]===!0){a=!0,l();return}let v=g[0];if(!(v==null||v.length===0)){for(let T of v)m(T);return{deactivate:()=>{h(),a=!1}}}},{...ce(o),completeWhenDepsComplete:!1})}var ol=qa;function sl(t,e,n){return z(r=>{let o=new Set;function s(){for(let a of o)clearTimeout(a);o.clear()}let i=t.subscribe(a=>{for(let d of a)if(d[0]===M){let u=setTimeout(()=>{o.delete(u),r.emit(d[1])},e);o.add(u)}else if(d[0]===P){let u=setTimeout(()=>{o.delete(u),r.down([[P]])},e);o.add(u)}else d[0]===I&&(s(),r.down([d]))});return()=>{i(),s()}},ce(n))}function za(t,e,n){return z(r=>{let o,s;function i(){o!==void 0&&(clearTimeout(o),o=void 0)}let a=t.subscribe(d=>{for(let u of d)u[0]===M?(i(),s=u[1],o=setTimeout(()=>{o=void 0,r.emit(s)},e)):u[0]===P?(o!==void 0&&(i(),r.emit(s)),r.down([[P]])):u[0]===I&&(i(),r.down([u]))});return()=>{a(),i()}},{...ce(n),meta:{...we("debounce",{ms:e}),...n?.meta??{}}})}function Ha(t,e,n){let{leading:r,trailing:o,...s}=n??{},i=r!==!1,a=o===!0,d=e*1e6;return z(u=>{let c,l=-1/0,p,f=!1;function m(){c!==void 0&&(clearTimeout(c),c=void 0)}let h=t.subscribe(g=>{for(let y of g)if(y[0]===M){let b=y[1],v=V();if(i&&v-l>=d)l=v,u.emit(b),m(),a&&(c=setTimeout(()=>{c=void 0,f&&(l=V(),u.emit(p),f=!1)},e));else if(a&&(p=b,f=!0,c===void 0)){let T=(v-l)/1e6;c=setTimeout(()=>{c=void 0,f&&(l=V(),u.emit(p),f=!1)},Math.max(0,e-T))}}else(y[0]===P||y[0]===I)&&(m(),u.down([y]))});return()=>{h(),m()}},{...ce(s),meta:{...we("throttle",{ms:e,leading:i,trailing:a}),...s.meta??{}}})}function il(t,e,n){return z(r=>{let o,s=!1,i=!1,a=t.subscribe(u=>{if(!s)for(let c of u){if(s)return;c[0]===M?o={v:c[1]}:c[0]===I?(s=!0,r.down([c])):c[0]===P&&(i=!0,o=void 0)}}),d=e.subscribe(u=>{if(!s)for(let c of u){if(s)return;c[0]===M?o!==void 0&&!i&&r.emit(o.v):c[0]===I?(s=!0,r.down([c])):c[0]===P&&(s=!0,r.down([[P]]))}});return()=>{a(),d()}},ce(n))}function al(t,e,n){return z(r=>{let o,s,i=!1;function a(){o!==void 0&&(clearTimeout(o),o=void 0)}let d=t.subscribe(u=>{for(let c of u)c[0]===M?(s=c[1],i=!0,a(),o=setTimeout(()=>{o=void 0,i&&(i=!1,r.emit(s))},e)):(c[0]===P||c[0]===I)&&(a(),r.down([c]))});return()=>{d(),a()}},ce(n))}function dl(t,e,n){return z(r=>{let o=[],s=t.subscribe(a=>{for(let d of a)d[0]===M?o.push(d[1]):d[0]===P?(o.length>0&&r.emit([...o]),o.length=0,r.down([[P]])):d[0]===I&&r.down([d])}),i=e.subscribe(a=>{for(let d of a)d[0]===M?o.length>0&&(r.emit([...o]),o.length=0):d[0]===P?r.down([[P]]):d[0]===I&&r.down([d])});return()=>{s(),i(),o.length=0}},ce(n))}function ul(t,e,n){if(e<=0)throw new RangeError("bufferCount expects count > 0");return z(r=>{let o=[],s=t.subscribe(i=>{for(let a of i)a[0]===M?(o.push(a[1]),o.length>=e&&r.emit(o.splice(0,o.length))):a[0]===P?(o.length>0&&r.emit([...o]),o.length=0,r.down([[P]])):a[0]===I&&r.down([a])});return()=>{s(),o.length=0}},ce(n))}function cl(t,e,n){if(e<=0)throw new RangeError("windowCount expects count > 0");return z(r=>{let o,s=0;function i(){let d=z(u=>(o=u.down.bind(u),()=>{o=void 0}),ce());s=0,r.emit(d)}let a=t.subscribe(d=>{for(let u of d)u[0]===M?(o||i(),o?.([[M,u[1]]]),s+=1,s>=e&&(o?.([[P]]),o=void 0)):u[0]===P?(o?.([[P]]),o=void 0,r.down([[P]])):u[0]===I&&(o?.([u]),o=void 0,r.down([u]))});return()=>{a(),o?.([[P]]),o=void 0}},ce(n))}function ll(t,e,n){return z(r=>{let o=[],s=setInterval(()=>{o.length>0&&(r.emit([...o]),o.length=0)},e),i=t.subscribe(a=>{for(let d of a)d[0]===M?o.push(d[1]):d[0]===P?(clearInterval(s),o.length>0&&r.emit([...o]),o.length=0,r.down([[P]])):d[0]===I&&(clearInterval(s),r.down([d]))});return()=>{i(),clearInterval(s),o.length=0}},{...ce(n),meta:{...we("bufferTime",{ms:e}),...n?.meta??{}}})}function pl(t,e,n){return z(r=>{let o;function s(){o?.([[P]]),o=void 0}function i(){let u=z(c=>(o=c.down.bind(c),()=>{o=void 0}),ce());r.emit(u)}i();let a=setInterval(()=>{s(),i()},e),d=t.subscribe(u=>{for(let c of u)c[0]===M?o?.([[M,c[1]]]):c[0]===P?(clearInterval(a),s(),r.down([[P]])):c[0]===I&&(clearInterval(a),o?.([c]),s(),r.down([c]))});return()=>{d(),clearInterval(a),s()}},ce(n))}function fl(t,e,n){return z(r=>{let o;function s(){o?.([[P]]),o=void 0}function i(){let u=z(c=>(o=c.down.bind(c),()=>{o=void 0}),ce());r.emit(u)}let a=t.subscribe(u=>{for(let c of u)c[0]===M?(o||i(),o?.([[M,c[1]]])):c[0]===P?(s(),r.down([[P]])):c[0]===I&&(o?.([c]),o=void 0,r.down([c]))}),d=e.subscribe(u=>{for(let c of u)c[0]===M&&(s(),i())});return()=>{a(),d(),s()}},ce(n))}function ml(t,e){return z((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 gl(t,e,n){if(e<=0)throw new RangeError("repeat expects count > 0");return z(r=>{let o=e,s,i=()=>{s?.(),s=t.subscribe(a=>{let d=!1,u=[];for(let c of a)c[0]===P?d=!0:u.push(c);u.length>0&&r.down(u),d&&(s?.(),s=void 0,o-=1,o>0?i():r.down([[P]]))})};return i(),()=>{s?.()}},ce(n))}function hl(t,e){return U([t],(n,r)=>{let o=n[0];if(o==null||o.length===0){r.down([[q]]);return}for(let s of o)r.emit(s)},ce(e))}function ro(t,e,n){return z(r=>{let o=t.subscribe(s=>{for(let i of s)if(i[0]===M)r.emit(i[1]);else if(i[0]===I)try{r.emit(e(i[1]))}catch(a){r.down([[I,a]])}else i[0]===P&&r.down([[P]])});return()=>{o()}},ce(n))}function yl(t,e,n){return U([t,e],(r,o,s)=>{let i=r[1];if(!(i!=null&&i.length>0?i.at(-1):s.prevData[1])){o.down([[q]]);return}let d=r[0];if(d!=null&&d.length>0){for(let u of d)o.emit(u);return}if(i!=null&&i.length>0&&s.prevData[0]!==void 0){o.emit(s.prevData[0]);return}o.down([[q]])},Bc(n))}var bl=Ka,vl=za,Tl=Ha,wl=ro;ae();Me();ne();Wn();var Wa=class{ring;arr;constructor(e){e===Number.POSITIVE_INFINITY||e<=0?(this.arr=[],this.ring=null):(this.ring=new gn(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 oo(t){return t instanceof Error?t:new Error(String(t))}function Xg(t){return t===void 0?null:typeof t=="string"?qt(t):t}function Ue(t,e){let{name:n,onTransportError:r,retry:o,backpressure:s,batchSize:i=Number.POSITIVE_INFINITY,flushIntervalMs:a=0,serialize:d,stopOn:u,onUpstreamMessage:c,onDispose:l,send:p,sendBatch:f,ctx:m}=e;if(!p&&!f)throw new Error("reactiveSink: `send` or `sendBatch` must be provided");let h=m,g=Math.max(1,o?.maxAttempts??1),y=Xg(o?.backoff??(g>1?"exponential":void 0)),b=o?.shouldRetry??(()=>!0),v=f!==void 0||i<Number.POSITIVE_INFINITY||a>0,T=W=>n?`${n}::${W}`:void 0,w=A(void 0,{equals:()=>!1,name:T("sent")}),x=A(null,{name:T("failed")}),k=A(0,{name:T("inFlight")}),S=A(null,{name:T("errors")}),R=v?A(0,{name:T("buffered")}):void 0,E=s?A(!1,{name:T("paused")}):void 0,_=0,O=W=>{_+=W,k.down([[M,_]])},N=W=>{try{r?.(W)}catch{}try{S.down([[M,W]])}catch{}},L=new Set,j=W=>{L.add(W);let fe=()=>L.delete(W);W.then(fe,fe)},$=(W,fe,Ne)=>{let Ee=y?y(fe-1,Ne,null):0,me=Ee==null?0:typeof Ee=="number"&&Ee>0?Ee:0,De=Math.max(1,Math.ceil(me/1e6));return new Promise(ye=>{setTimeout(()=>ye(W()),De)})},D=W=>W!=null&&typeof W=="object"&&typeof W.then=="function",K=W=>{let fe;try{fe=d?d(W):W}catch(ye){let be=oo(ye);return N({stage:"serialize",error:be,value:W}),x.down([[M,{value:W,error:be,attempts:0}]]),Promise.resolve()}let Ne=0,Ee=ye=>{O(-1);let be=oo(ye);if(N({stage:"send",error:be,value:W,attempt:Ne}),!(Ne<g&&b(be,Ne))){x.down([[M,{value:W,error:be,attempts:Ne}]]);return}return $(De,Ne,be)},me=()=>{O(-1),w.down([[M,W]])};function De(){Ne+=1,O(1);let ye;try{ye=p(fe,h)}catch(be){return Ee(be)??Promise.resolve()}return D(ye)?ye.then(me,be=>Ee(be)):(me(),Promise.resolve())}return De()},F=s?.maxBuffer??Number.POSITIVE_INFINITY,H=new Wa(F),G,B=!1,re=()=>{R?.down([[M,H.length]])},pe=W=>{E&&E.down([[M,W]])},ee=s?.strategy??"drop-oldest",ue=(W,fe)=>{let Ne={value:W,payload:fe};if(H.length<F)return H.push(Ne),re(),!0;if(ee==="drop-oldest"){let me=H.shift();return H.push(Ne),re(),pe(!0),x.down([[M,{value:me.value,error:new Error("backpressure: buffer overflow \u2014 dropped oldest"),attempts:0}]]),!0}if(ee==="drop-newest")return pe(!0),x.down([[M,{value:W,error:new Error("backpressure: buffer overflow \u2014 dropped newest"),attempts:0}]]),!1;let Ee=new Error("backpressure: buffer overflow");return N({stage:"send",error:Ee,value:W}),x.down([[M,{value:W,error:Ee,attempts:0}]]),pe(!0),!1},Ce=W=>{let fe=0,Ne=W.map(ye=>ye.payload),Ee=ye=>{O(-1);let be=oo(ye);if(N({stage:"send",error:be,value:W.map(Mn=>Mn.value),attempt:fe}),!(fe<g&&b(be,fe))){for(let{value:Mn}of W)x.down([[M,{value:Mn,error:be,attempts:fe}]]);return}return $(De,fe,be)},me=()=>{O(-1);for(let{value:ye}of W)w.down([[M,ye]])};function De(){fe+=1,O(1);let ye;try{ye=f(Ne,h)}catch(be){return Ee(be)??Promise.resolve()}return D(ye)?ye.then(me,be=>Ee(be)):(me(),Promise.resolve())}return De()},Ye=async W=>{for(let fe of W)await Be(fe.value,fe.payload)},Be=(W,fe)=>{let Ne=0,Ee=ye=>{O(-1);let be=oo(ye);if(N({stage:"send",error:be,value:W,attempt:Ne}),!(Ne<g&&b(be,Ne))){x.down([[M,{value:W,error:be,attempts:Ne}]]);return}return $(De,Ne,be)},me=()=>{O(-1),w.down([[M,W]])};function De(){Ne+=1,O(1);let ye;try{ye=p(fe,h)}catch(be){return Ee(be)??Promise.resolve()}return D(ye)?ye.then(me,be=>Ee(be)):(me(),Promise.resolve())}return De()},J=()=>{if(B||H.length===0)return Promise.resolve();let W=H.drain();if(re(),pe(!1),f!==void 0){let Ne=Ce(W);return j(Ne),Ne}let fe=Ye(W);return j(fe),fe},de=()=>{G!==void 0||B||a<=0||(G=setTimeout(()=>{G=void 0,J()},a))},Le=t.subscribe(W=>{for(let fe of W){let Ne=fe[0];if(Ne!==M)try{c?.(fe)}catch{}if(Ne===M){let Ee=fe[1];if(v){let me;if(d)try{me=d(Ee)}catch(ye){let be=oo(ye);N({stage:"serialize",error:be,value:Ee}),x.down([[M,{value:Ee,error:be,attempts:0}]]);continue}else me=Ee;if(!ue(Ee,me))continue;H.length>=i?J():de()}else{let me=K(Ee);j(me)}}else Fe.messageTier(Ne)>=3&&v&&(G!==void 0&&(clearTimeout(G),G=void 0),J())}}),Te;if(u){let W=!1;Te=u.subscribe(fe=>{if(!W){W=!0;return}fe.length>0&&!X&&ie()})}let X=!1,ie=()=>{if(X)return;X=!0,G!==void 0&&(clearTimeout(G),G=void 0),v&&J(),B=!0,Te?.(),Le();let W=fe=>{try{fe.down([[le]])}catch{}};W(S),W(x),W(w),W(k),R&&W(R),E&&W(E);try{l?.()}catch{}},xe={dispose:ie,sent:w,failed:x,inFlight:k,errors:S};return v&&(xe.buffered=R,xe.flush=async()=>{B||(await J(),await Promise.all(L))}),E&&(xe.paused=E),xe}It();ve();function Tt(t){return{describeKind:"producer",...t}}function Ja(t,e){let{parse:n,closeOnTeardown:r=!1,...o}=e??{};return z(s=>{let i=!0,a,d=()=>{let y=a;a=void 0,y?.()},u=y=>{i&&(i=!1,s.down([y]),d())},c=(y,b=y)=>{if(i)try{let v=y!==null&&typeof y=="object"&&"data"in y?y.data:y,T=n?n(v,b):v;s.emit(T)}catch(v){u([I,v])}},l=y=>{u([I,y])},p=()=>{u([P])};if(typeof t=="function"){try{if(a=t(c,l,p),typeof a!="function")throw new Error("fromWebSocket register contract violation: register must return cleanup callable")}catch(y){u([I,y])}return()=>{i=!1,d()}}let f=t,m=y=>c(y,y),h=y=>l(y),g=()=>p();return f.addEventListener("message",m),f.addEventListener("error",h),f.addEventListener("close",g),a=()=>{f.removeEventListener("message",m),f.removeEventListener("error",h),f.removeEventListener("close",g),r&&f.close()},()=>{i=!1,d()}},Tt(o))}function kl(t,e){return bn(t,e)}function Ya(t,e){let{method:n="GET",headers:r,body:o,transform:s=v=>v.json(),timeoutNs:i=30*1e9,signal:a,completeAfterFetch:d=!1,refetchOnSubscribe:u=!1,...c}=e??{},l=A(0,{name:`${c.name??"http"}/fetchCount`}),p=A(0,{name:`${c.name??"http"}/lastUpdated`}),f=A(!1,{name:`${c.name??"http"}/fetched`}),m=0,h=o!==void 0?typeof o=="string"?o:JSON.stringify(o):void 0,g=v=>{let T=new AbortController,w=!0;if(a?.aborted)return w=!1,v.down([[I,a.reason??new Error("Aborted")]]),()=>{};a?.addEventListener("abort",()=>T.abort(a.reason),{once:!0});let x=setTimeout(()=>T.abort(new Error("Request timeout")),Math.ceil(i/1e6));return fetch(t,{method:n,headers:r,body:h,signal:T.signal}).then(async k=>{if(clearTimeout(x),!w)return;if(!k.ok)throw new Error(`HTTP ${k.status}: ${k.statusText}`);let S=await s(k);w&&(Z(()=>{m+=1,l.down([[M,m]]),p.down([[M,se()]]),f.down([[M,!0]]),v.emit(S)}),d&&v.down([[P]]))}).catch(k=>{clearTimeout(x),w&&(k&&k.name==="AbortError"||v.down([[I,k]]))}),()=>{w=!1,T.abort()}},y=z(v=>g({emit:T=>v.emit(T),down:T=>v.down(T)}),{...Tt(c),resubscribable:u});return{...Ht(y),fetchCount:l,lastUpdated:p,fetched:f}}function xl(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:d,flushIntervalMs:u,retry:c,onTransportError:l}=n??{},p=async m=>{let h=i!==void 0?new AbortController:void 0,g;h&&i!==void 0&&(g=setTimeout(()=>h.abort(new Error("Request timeout")),Math.ceil(i/1e6)));try{let y=await fetch(e,{method:r,headers:o,body:m,signal:h?.signal}),b=async()=>{try{await y.arrayBuffer?.()}catch{}};if(!y.ok)throw await b(),new Error(`HTTP ${y.status}: ${y.statusText}`);await b()}finally{g!==void 0&&clearTimeout(g)}};return d!==void 0||u!==void 0?Ue(t,{onTransportError:l,retry:c,batchSize:d,flushIntervalMs:u,sendBatch:async m=>{let h;a==="ndjson"?h=m.map(g=>{let y=s(g);return typeof y=="string"?y:new TextDecoder().decode(y)}).join(`
|
|
16
|
+
`):h=JSON.stringify(m),await p(h)}}):Ue(t,{onTransportError:l,retry:c,serialize:s,send:async m=>{await p(m)}})}function Rl(t){return Symbol.keyFor(t)??t.description??"message"}function or(t,e){return typeof t=="string"?t:e(t)}function Sl(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
|
|
19
|
+
`}function Nl(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:d,signal:u,eventNameResolver:c=Rl}=e??{},l=new TextEncoder,p;return new ReadableStream({start(f){let m=!1,h,g=()=>{},y=()=>{m||(m=!0,h!==void 0&&clearInterval(h),u?.removeEventListener("abort",v),g(),f.close())};p=y;let b=(T,w)=>{m||f.enqueue(l.encode(Sl(T,w)))},v=()=>{m||y()};g=t.subscribe(T=>{for(let w of T){let x=w[0];if(!(Fe.isLocalOnly(x)&&!(x===oe&&a))){if(x===M){b(r,or(w[1],n));continue}if(x===I){b(o,or(w[1],n)),y();return}if(x===P){b(s),y();return}!i&&x===q||b(c(x),w.length>1?or(w[1],n):void 0)}}}),d!==void 0&&d>0&&(h=setInterval(()=>{m||f.enqueue(l.encode(`: keepalive
|
|
20
20
|
|
|
21
|
-
`))},
|
|
21
|
+
`))},d)),u?.aborted?v():u?.addEventListener("abort",v,{once:!0})},cancel(){p?.()}})}function El(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:d,signal:u,eventNameResolver:c=Rl}=e??{},l=new TextEncoder;return z(p=>{let f=!0,m,h=(b,v)=>{f&&p.emit(l.encode(Sl(b,v)))},g=()=>{f&&(f=!1,p.down([[P]]))},y=t.subscribe(b=>{if(f)for(let v of b){let T=v[0];if(!(Fe.isLocalOnly(T)&&!(T===oe&&a))){if(T===M){h(r,or(v[1],n));continue}if(T===I){h(o,or(v[1],n)),f=!1,p.down([[P]]);return}if(T===P){h(s),f=!1,p.down([[P]]);return}!i&&T===q||h(c(T),v.length>1?or(v[1],n):void 0)}}});return d!==void 0&&d>0&&(m=setInterval(()=>{f&&p.emit(l.encode(`: keepalive
|
|
22
22
|
|
|
23
|
-
`))},
|
|
24
|
-
`);c.push({event:i,data:n(w),id:
|
|
25
|
-
`)){let s=o.trim();if(!s)continue;if(s.startsWith("# TYPE ")){let p=s.slice(7),f=p.indexOf(" ");f>0&&n.set(p.slice(0,f),p.slice(f+1).trim());continue}if(s.startsWith("# HELP ")){let p=s.slice(7),f=p.indexOf(" ");f>0&&r.set(p.slice(0,f),p.slice(f+1).trim());continue}if(s.startsWith("#"))continue;let i,a={},u,
|
|
26
|
-
`,flushIntervalMs:o=0,batchSize:s=Number.POSITIVE_INFINITY,onTransportError:i,mode:a}=n??{},
|
|
27
|
-
`)?`"${t.replace(/"/g,'""')}"`:t}function
|
|
23
|
+
`))},d)),u?.aborted?g():u?.addEventListener("abort",g,{once:!0}),()=>{f=!1,m!==void 0&&clearInterval(m),u?.removeEventListener("abort",g),y()}})}function _l(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===M)try{r.enqueue(s[1])}catch{n=!0,e?.()}else if(i===I){n=!0;try{r.error(s[1])}catch{}return}else if(i===P){n=!0;try{r.close()}catch{}return}}})},cancel(){n=!0,e?.()}})}async function*$t(t,e){let n=e?.parse??(w=>w),r=e?.signal,o=new TextDecoder,s="",i="message",a=[],d,u,c=[],l=()=>{if(a.length===0&&i==="message"&&d===void 0){a=[];return}let w=a.join(`
|
|
24
|
+
`);c.push({event:i,data:n(w),id:d,retry:u}),i="message",a=[],d=void 0,u=void 0},p=w=>{if(w===""){l();return}if(w.startsWith(":"))return;let x=w.indexOf(":"),k=x<0?w:w.slice(0,x),S=x<0?"":w.slice(x+1);switch(S.startsWith(" ")&&(S=S.slice(1)),k){case"event":i=S;break;case"data":a.push(S);break;case"id":S.includes("\0")||(d=S);break;case"retry":{let R=Number(S);Number.isFinite(R)&&(u=R);break}}},f=(w,x)=>{s+=o.decode(w,{stream:!x});let k=s.split(/\r?\n/);s=k.pop()??"";for(let S of k)p(S)},m=t,h=t instanceof ReadableStream?t:m&&typeof m=="object"&&m.body instanceof ReadableStream?m.body:null,g,y,b=!1,v=()=>{b||(b=!0,g&&g.cancel().catch(()=>{}),y&&typeof y.return=="function"&&Promise.resolve(y.return()).catch(()=>{}))},T=()=>{v()};if(r){if(r.aborted)return;r.addEventListener("abort",T,{once:!0})}try{if(h){for(g=h.getReader();!r?.aborted;){let{value:w,done:x}=await g.read();if(x)break;for(f(w,!1);c.length>0;)yield c.shift()}f(new Uint8Array,!0)}else{for(y=t[Symbol.asyncIterator]();!r?.aborted;){let x=await y.next();if(x.done)break;for(f(x.value,!1);c.length>0;)yield c.shift()}f(new Uint8Array,!0)}if(s.trim()){for(let w of s.split(/\r?\n/))p(w);l()}for(;c.length>0;)yield c.shift()}finally{r&&r.removeEventListener("abort",T),v()}}function Ml(t,e){let{parse:n,...r}=e??{};return z(o=>{let s=!0,i=new AbortController;return(async()=>{try{for await(let d of $t(t,{parse:n,signal:i.signal})){if(!s)return;o.emit(d)}s&&o.down([[P]])}catch(d){s&&o.down([[I,d]])}})(),()=>{s=!1,i.abort()}},Tt(r))}function Ol(t,e){let{method:n="GET",headers:r,body:o,signal:s,...i}=e??{};return z(a=>{let d=!0,u=new AbortController;if(s?.aborted)return a.down([[I,s.reason??new Error("Aborted")]]),()=>{};s?.addEventListener("abort",()=>u.abort(s.reason),{once:!0});let c=o!==void 0?typeof o=="string"?o:JSON.stringify(o):void 0;return(async()=>{try{let p=await fetch(t,{method:n,headers:r,body:c,signal:u.signal});if(!d)return;if(!p.ok)throw new Error(`HTTP ${p.status}: ${p.statusText}`);if(!p.body)throw new Error("HTTP response has no body");let f=p.body.getReader();for(;d;){let{value:m,done:h}=await f.read();if(h)break;m&&a.emit(m)}d&&a.down([[P]])}catch(p){if(!d||p&&p.name==="AbortError")return;a.down([[I,p]])}})(),()=>{d=!1,u.abort()}},Tt(i))}function Al(t,e){let{intervalMs:n=5e3,...r}=e??{};return ke(Ze(n,{period:n}),()=>Ya(t,{...r,completeAfterFetch:!0}).node)}function Cl(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:d,retry:u,backpressure:c,stopOn:l}=n??{},p=!1,f=y=>{if(!p){p=!0;try{e.close(i,a)}catch(b){let v=b instanceof Error?b:new Error(String(b));try{d?.({stage:"close",error:v,value:void 0,message:y})}catch{}}}},m=null,g=Ue(t,{onTransportError:d,serialize:y=>{let b=r(y);if(b===void 0)throw new Error("serialize returned undefined");return b},retry:u,backpressure:c,stopOn:l,onDispose:()=>{if(m){try{e.removeEventListener("close",m)}catch{}m=null}},send:y=>{e.send(y)},onUpstreamMessage:y=>{(y[0]===P&&o||y[0]===I&&s)&&f(y)}});return m=()=>{p=!0,g.dispose()},e.addEventListener("close",m),g}function Ll(t,e){let{parse:n,maxRetries:r,backoff:o="exponential",closeOnTeardown:s=!0,...i}=e??{};return St(()=>Ja(t(),{parse:n,closeOnTeardown:s,...i}),{count:r,backoff:o})}function Il(t,e){let{method:n="notifications/message",onDisconnect:r,...o}=e??{};return bn(({emit:s,error:i})=>(t.setNotificationHandler(n,a=>s(a)),r?.(a=>i(a??new Error("MCP client disconnected"))),()=>t.setNotificationHandler(n,()=>{})),o)}function Pl(t,e){return Gs(({traces:r,metrics:o,logs:s,error:i})=>t({onTraces:a=>{Z(()=>{for(let d of a)r(d)})},onMetrics:a=>{Z(()=>{for(let d of a)o(d)})},onLogs:a=>{Z(()=>{for(let d of a)s(d)})},onError:i})??void 0,["traces","metrics","logs"],e?.name?{name:e.name}:void 0)}function Dl(t,e){return bn(t,e)}function Gl(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=se();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:se()}}function Fl(t,e){return bn(t,e)}var Zg={c:"counter",g:"gauge",ms:"timer",h:"histogram",s:"set",d:"distribution"};function $l(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=Zg[o]??"counter",i=s==="set"?0:Number(r),a,d={};for(let u=2;u<e.length;u++){let c=e[u].trim();if(c.startsWith("@"))a=Number(c.slice(1));else if(c.startsWith("#"))for(let l of c.slice(1).split(",")){let[p,f]=l.split(":");p&&(d[p]=f??"")}}return{name:n.trim(),value:i,type:s,sampleRate:a,tags:d,timestampNs:se()}}function jl(t,e){let{intervalNs:n=15*1e9,headers:r,timeoutNs:o=10*1e9,signal:s,maxConsecutiveErrors:i=1}=e??{},a=Math.ceil(n/1e6),d=0;return ke(Ze(0,{period:a,signal:s}),()=>z(u=>{let c=!0,l=new AbortController,p=setTimeout(()=>l.abort(new Error("Scrape timeout")),Math.ceil(o/1e6));return(async()=>{try{let m=await fetch(t,{headers:{Accept:"text/plain",...r},signal:l.signal});if(clearTimeout(p),!c)return;if(!m.ok)throw new Error(`Prometheus scrape ${m.status}: ${m.statusText}`);let h=await m.text();if(!c)return;let g=Qa(h);for(let y of g)u.emit(y);d=0,u.down([[P]])}catch(m){if(clearTimeout(p),!c||m instanceof Error&&m.name==="AbortError")return;d+=1,d>=i&&u.down([[I,m]])}})(),()=>{c=!1,clearTimeout(p),l.abort()}}))}function Qa(t){let e=[],n=new Map,r=new Map;for(let o of t.split(`
|
|
25
|
+
`)){let s=o.trim();if(!s)continue;if(s.startsWith("# TYPE ")){let p=s.slice(7),f=p.indexOf(" ");f>0&&n.set(p.slice(0,f),p.slice(f+1).trim());continue}if(s.startsWith("# HELP ")){let p=s.slice(7),f=p.indexOf(" ");f>0&&r.set(p.slice(0,f),p.slice(f+1).trim());continue}if(s.startsWith("#"))continue;let i,a={},d,u,c=s.indexOf("{");if(c>=0){i=s.slice(0,c);let p=s.indexOf("}",c);if(p<0)continue;let f=s.slice(c+1,p);a=eh(f);let m=s.slice(p+1).trim().split(/\s+/);d=m[0]??"",u=m[1]}else{let p=s.split(/\s+/);i=p[0]??"",d=p[1]??"",u=p[2]}if(!i||!d)continue;let l=i.replace(/(_total|_count|_sum|_bucket|_created|_info)$/,"");e.push({name:i,labels:a,value:Number(d),timestampMs:u?Number(u):void 0,type:n.get(l)??n.get(i),help:r.get(l)??r.get(i),timestampNs:se()})}return e}function eh(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 Bl(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 z(i=>{let a=!0;return(async()=>{try{await t.subscribe({topic:e,fromBeginning:r}),await t.run({eachMessage:async({topic:u,partition:c,message:l})=>{if(!a)return;let p={};if(l.headers)for(let[f,m]of Object.entries(l.headers))m!==void 0&&(p[f]=typeof m=="string"?m:m.toString());i.emit({topic:u,partition:c,key:l.key?.toString()??null,value:o(l.value),headers:p,offset:l.offset,timestamp:l.timestamp,timestampNs:se()})}})}catch(u){a&&i.down([[I,u]])}})(),()=>{a=!1}},Tt(s))}function Vl(t,e,n,r){let{serialize:o=a=>JSON.stringify(a),keyExtractor:s,onTransportError:i}=r??{};return Ue(t,{onTransportError:i,send:async a=>{let d=s?.(a)??null,u=o(a);await e.send({topic:n,messages:[{key:d,value:Buffer.from(u)}]})}})}function Kl(t,e,n){let{blockMs:r=5e3,startId:o="$",parse:s=a=>{for(let u=0;u<a.length;u+=2)if(a[u]==="data")try{return JSON.parse(a[u+1])}catch{return a[u+1]}let d={};for(let u=0;u<a.length;u+=2)d[a[u]]=a[u+1];return d},...i}=n??{};return z(a=>{let d=!0,u=o;return(async()=>{for(;d;)try{let l=await t.xread("BLOCK",r,"STREAMS",e,u);if(!d)return;if(l)for(let[p,f]of l)for(let[m,h]of f)u=m,a.emit({id:m,key:e,data:s(h),timestampNs:se()})}catch(l){if(!d)return;a.down([[I,l]]);return}})(),()=>{d=!1}},Tt(i))}function ql(t,e,n,r){let{serialize:o=a=>["data",JSON.stringify(a)],maxLen:s,onTransportError:i}=r??{};return Ue(t,{onTransportError:i,send:async a=>{let d=o(a);await(s!==void 0?e.xadd(n,"MAXLEN","~",String(s),"*",...d):e.xadd(n,"*",...d))}})}function zl(t,e){let{delimiter:n=",",hasHeader:r=!0,columns:o,parseLine:s,...i}=e??{},a=s??(d=>Ul(d,n));return z(d=>{let u=!1;return(async()=>{try{let l=o,p="";for await(let f of t){if(u)return;p+=f;let m=p.split(/\r?\n/);p=m.pop()??"";for(let h of m){if(u)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]??"";d.emit(y)}}if(!u&&p.trim()){let f=a(p);if(l){let m={};for(let h=0;h<l.length;h++)m[l[h]]=f[h]??"";d.emit(m)}}u||d.down([[P]])}catch(l){u||d.down([[I,l]])}})(),()=>{u=!0}},Tt(i))}function Hl(t,e){let{delimiter:n=",",hasHeader:r=!0,columns:o,parseLine:s,...i}=e??{},a=s??(d=>Ul(d,n));return U([t],(d,u,c)=>{let l=d[0];if(l==null||l.length===0)return;let p=c.store;typeof p.buffer!="string"&&(p.buffer=""),p.headers===void 0&&o&&(p.headers=o.slice());for(let f of l){p.buffer=p.buffer+f;let m=p.buffer.split(/\r?\n/);p.buffer=m.pop()??"";for(let h of m){if(!h.trim())continue;let g=a(h);if(!p.headers&&r){p.headers=g;continue}p.headers||(p.headers=g.map((b,v)=>`col${v}`));let y={};for(let b=0;b<p.headers.length;b++)y[p.headers[b]]=g[b]??"";u.emit(y)}}},{describeKind:"derived",...i})}function Wl(t,e){return U([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 d=i.buffer.split(/\r?\n/);i.buffer=d.pop()??"";for(let u of d)if(u.trim())try{r.emit(JSON.parse(u))}catch(c){r.down([[I,c]]);return}}},{describeKind:"derived",...e??{}})}function Ul(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 Jl(t,e){return z(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 d of a){if(r)return;let u=d.trim();u&&n.emit(JSON.parse(u))}}!r&&s.trim()&&n.emit(JSON.parse(s.trim())),r||n.down([[P]])}catch(s){r||n.down([[I,s]])}})(),()=>{r=!0}},Tt(e))}function Yl(t,e,n){let{intervalNs:r=5*1e9,format:o="JSONEachRow",signal:s,maxConsecutiveErrors:i=1}=n??{},a=Math.ceil(r/1e6),d=0;return ke(Ze(0,{period:a,signal:s}),()=>z(u=>{let c=!0;return(async()=>{try{let p=await t.query({query:e,format:o});if(!c)return;let f=await p.json();if(!c)return;for(let m of f)u.emit(m);d=0,u.down([[P]])}catch(p){if(!c)return;d+=1,d>=i&&u.down([[I,p]])}})(),()=>{c=!1}}))}function Ql(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 z(a=>{let d=!0;return(async()=>{for(;d;)try{let c=await t.receive();if(!d)return;let l={topic:c.getTopicName(),messageId:c.getMessageId().toString(),key:c.getPartitionKey(),value:r(c.getData()),properties:c.getProperties(),publishTime:c.getPublishTimestamp(),eventTime:c.getEventTimestamp(),timestampNs:se()};if(n)a.emit(l),t.acknowledge(c).catch(i);else{let p=!1,f={value:l,ack(){p||(p=!0,t.acknowledge(c).catch(i))},nack(m){if(p)return;p=!0;let h=t;try{let g=h.negativeAcknowledge?.(c);g&&typeof g.then=="function"&&g.catch(i)}catch(g){i(g)}}};a.emit(f)}}catch(c){d&&a.down([[I,c]]);return}})(),()=>{d=!1}},Tt(s))}function Xl(t,e,n){let{serialize:r=a=>Buffer.from(JSON.stringify(a)),keyExtractor:o,propertiesExtractor:s,onTransportError:i}=n??{};return Ue(t,{onTransportError:i,send:async a=>{await e.send({data:r(a),partitionKey:o?.(a),properties:s?.(a)})}})}function Zl(t,e,n){let r=new TextDecoder,{queue:o,deserialize:s=a=>{let d=r.decode(a);try{return JSON.parse(d)}catch{return d}},...i}=n??{};return z(a=>{let d=!0,u=t.subscribe(e,o?{queue:o}:void 0);return(async()=>{try{for await(let l of u){if(!d)return;let p={};if(l.headers)for(let f of l.headers.keys())p[f]=l.headers.get(f);a.emit({subject:l.subject,data:s(l.data),headers:p,reply:l.reply,sid:l.sid,timestampNs:se()})}d&&a.down([[P]])}catch(l){d&&a.down([[I,l]])}})(),()=>{d=!1}},Tt(i))}function ep(t,e,n,r){let o=new TextEncoder,{serialize:s=a=>o.encode(JSON.stringify(a)),onTransportError:i}=r??{};return Ue(t,{onTransportError:i,send:a=>{e.publish(n,s(a))}})}function tp(t,e,n){let{autoAck:r=!0,deserialize:o=d=>{try{return JSON.parse(d.toString())}catch{return d.toString()}},onAckError:s,...i}=n??{},a=d=>{if(s)try{s(d instanceof Error?d:new Error(String(d)))}catch{}};return z(d=>{let u=!0,c;return(async()=>{try{c=(await t.consume(e,f=>{if(!u)return;if(f===null){u&&d.down([[I,new Error("Consumer cancelled by broker")]]);return}let m={queue:e,routingKey:f.fields.routingKey,exchange:f.fields.exchange,content:o(f.content),properties:f.properties,deliveryTag:f.fields.deliveryTag,redelivered:f.fields.redelivered,timestampNs:se()};if(r){d.emit(m);try{t.ack(f)}catch(h){a(h)}}else{let h=!1,g=t,y={value:m,ack(){if(!h){h=!0;try{t.ack(f)}catch(b){a(b)}}},nack(b){if(h)return;h=!0;let v=b?.requeue;if(!g.nack){a(new Error("RabbitMQ channel does not expose `nack`; cannot negative-ack"));return}try{g.nack(f,!1,v)}catch(T){a(T)}}};d.emit(y)}},{noAck:!1})).consumerTag}catch(p){u&&d.down([[I,p]])}})(),()=>{u=!1,c!==void 0&&t.cancel(c)}},Tt(i))}function np(t,e,n,r){let{serialize:o=a=>Buffer.from(JSON.stringify(a)),routingKeyExtractor:s=()=>"",onTransportError:i}=r??{};return Ue(t,{onTransportError:i,send:a=>{let d=s(a),u=o(a);e.publish(n,d,u)}})}function Xa(t,e,n){let{serialize:r=l=>`${JSON.stringify(l)}
|
|
26
|
+
`,flushIntervalMs:o=0,batchSize:s=Number.POSITIVE_INFINITY,onTransportError:i,mode:a}=n??{},u=o>0||s<Number.POSITIVE_INFINITY?Ue(t,{onTransportError:i,batchSize:s,flushIntervalMs:o,serialize:r,sendBatch:l=>{e.write(l.join(""))}}):Ue(t,{onTransportError:i,serialize:r,send:l=>{e.write(l)}}),c=u.dispose;return u.dispose=()=>{c();try{e.end()}catch{}},u}function Ua(t,e){return t.includes(e)||t.includes('"')||t.includes(`
|
|
27
|
+
`)?`"${t.replace(/"/g,'""')}"`:t}function rp(t,e,n){let{columns:r,delimiter:o=",",writeHeader:s=!0,cellExtractor:i=(f,m)=>String(f[m]??""),flushIntervalMs:a=0,batchSize:d=Number.POSITIVE_INFINITY,onTransportError:u,...c}=n,l=!1;return Xa(t,e,{serialize:f=>{if(!l&&s){l=!0;let m=r.map(g=>Ua(g,o)).join(o),h=r.map(g=>Ua(i(f,g),o)).join(o);return`${m}
|
|
28
28
|
${h}
|
|
29
|
-
`}return`${r.map(m=>
|
|
30
|
-
`},flushIntervalMs:a,batchSize:
|
|
29
|
+
`}return`${r.map(m=>Ua(i(f,m),o)).join(o)}
|
|
30
|
+
`},flushIntervalMs:a,batchSize:d,onTransportError:u,...c})}function op(t,e,n,r){let{batchSize:o=1e3,flushIntervalMs:s=5e3,format:i="JSONEachRow",transform:a=u=>u,onTransportError:d}=r??{};return Ue(t,{onTransportError:d,batchSize:o,flushIntervalMs:s,serialize:a,sendBatch:async u=>{await e.insert({table:n,values:u,format:i})}})}function sp(t,e,n,r){let{format:o="ndjson",keyGenerator:s=(p,f)=>{let m=Math.floor(f/1e6);return`data/${new Date(m).toISOString().replace(/[:.]/g,"-")}-${p}.${o==="ndjson"?"ndjson":"json"}`},batchSize:i=1e3,flushIntervalMs:a=1e4,transform:d=p=>p,onTransportError:u}=r??{},c=o==="ndjson"?"application/x-ndjson":"application/json",l=0;return Ue(t,{onTransportError:u,batchSize:i,flushIntervalMs:a,serialize:d,sendBatch:async p=>{l+=1;let f=o==="ndjson"?`${p.map(h=>JSON.stringify(h)).join(`
|
|
31
31
|
`)}
|
|
32
|
-
`:JSON.stringify(p),m=s(l,oe());await e.putObject({Bucket:n,Key:m,Body:f,ContentType:c})}})}function Wl(t,e,n,r){let{toSQL:o=(i,a)=>({sql:`INSERT INTO "${a.replace(/"/g,'""')}" (data) VALUES ($1)`,params:[JSON.stringify(i)]}),onTransportError:s}=r??{};return We(t,{onTransportError:s,serialize:i=>o(i,n),send:async i=>{let a=i;await e.query(a.sql,a.params)}})}function zl(t,e,n){let{toDocument:r=s=>s,onTransportError:o}=n??{};return We(t,{onTransportError:o,serialize:r,send:async s=>{await e.insertOne(s)}})}function Ul(t,e,n){let{labels:r={},toLine:o=a=>JSON.stringify(a),toLabels:s,onTransportError:i}=n??{};return We(t,{onTransportError:i,serialize:a=>({line:o(a),labels:s?{...r,...s(a)}:r}),send:async a=>{let{line:u,labels:d}=a,c=`${oe()}`;await e.push({streams:[{stream:d,values:[[c,u]]}]})}})}function Jl(t,e,n){let{toResourceSpans:r=s=>[s],onTransportError:o}=n??{};return We(t,{onTransportError:o,serialize:r,send:async s=>{await e.push({resourceSpans:s})}})}function Yl(t,e,n,r){let{prefix:o="checkpoints/",debounceMs:s=500,compactEvery:i=10,onError:a}=r??{},u={name:`s3:${n}`,debounceMs:s,compactEvery:i,save(d){let c=Math.floor(oe()/1e6),l=`${o}${t.name}/checkpoint-${c}.json`,p;try{p=JSON.stringify(d)}catch(f){a?.(f);return}e.putObject({Bucket:n,Key:l,Body:p,ContentType:"application/json"}).catch(f=>a?.(f))}};return t.attachSnapshotStorage([u],{onError:d=>a?.(d)})}function Ql(t,e,n){let{prefix:r="graphrefly:checkpoint:",debounceMs:o=500,compactEvery:s=10,onError:i}=n??{},a=`${r}${t.name}`,u={name:`redis:${a}`,debounceMs:o,compactEvery:s,save(d){let c;try{c=JSON.stringify(d)}catch(l){i?.(l);return}e.set(a,c).catch(l=>i?.(l))},async load(){let d=await e.get(a);if(d!=null)try{return JSON.parse(d)}catch{return}}};return t.attachSnapshotStorage([u],{onError:d=>i?.(d)})}function Xl(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return K(i=>{try{let u=t.query(e,o).map(r);i.emit(u),i.down([[L]])}catch(a){i.down([[C,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...s})}function Zl(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return K(i=>{try{let a=t.iterate(e,o);X(()=>{for(let u of a)i.emit(r(u));i.down([[L]])})}catch(a){i.down([[C,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...s})}function ep(t,e,n,r){if(n.includes("\0")||n.length===0)throw new Error(`toSqlite: invalid table name: ${JSON.stringify(n)}`);let{toSQL:o=(O,P)=>({sql:`INSERT INTO "${P.replace(/"/g,'""')}" (data) VALUES (?)`,params:[JSON.stringify(O)]}),onTransportError:s,batchInsert:i=!1,maxBatchSize:a=1e3,flushIntervalMs:u=0}=r??{},d=O=>o(O,n);if(!i)return We(t,{onTransportError:s,serialize:d,send:O=>{let P=O;e.query(P.sql,P.params)}});let c=M(null),l=M(void 0,{equals:()=>!1}),p=M(null),f=M(0),m=M(0),h=O=>{try{s?.(O)}catch{}try{c.down([[E,O]])}catch{}},g=[],y=!1,b,v=!1,T=()=>m.down([[E,g.length]]),w=O=>{v||l.down([[E,O]])},x=O=>{v||p.down([[E,O]])},k=O=>{v||f.down([[E,O]])},S=O=>{v||h(O)},R=()=>{if(g.length===0||y)return;y=!0,k(1);try{e.query("BEGIN",[])}catch(j){y=!1,k(0),S({stage:"send",error:j instanceof Error?j:new Error(String(j)),value:void 0});return}let O=g;g=[],T();let P,B=0;for(let j of O)try{e.query(j.query.sql,j.query.params),B+=1}catch(D){P=D instanceof Error?D:new Error(String(D));break}if(P){try{e.query("ROLLBACK",[])}catch{}S({stage:"send",error:P,value:void 0});for(let j of O)x({value:j.value,error:P,attempts:1})}else try{e.query("COMMIT",[]);for(let j of O)w(j.value)}catch(j){let D=j instanceof Error?j:new Error(String(j));S({stage:"send",error:D,value:void 0});for(let Z=0;Z<B;Z++)x({value:O[Z].value,error:D,attempts:1})}y=!1,k(0)},N=()=>{u>0&&b===void 0&&!v&&(b=setTimeout(()=>{b=void 0,R()},u))},_=t.subscribe(O=>{for(let P of O){let B=P[0];if(B===E){let j=P[1],D;try{D=d(j)}catch(Z){let F=Z instanceof Error?Z:new Error(String(Z));h({stage:"serialize",error:F,value:j}),p.down([[E,{value:j,error:F,attempts:0}]]);continue}g.push({value:j,query:D}),T(),g.length>=a?R():N()}else $e.messageTier(B)>=3&&R()}});return{dispose:()=>{if(!v){b!==void 0&&(clearTimeout(b),b=void 0),R(),v=!0,_();for(let O of[c,l,p,f,m])try{O.down([[le]])}catch{}}},sent:l,failed:p,inFlight:f,errors:c,buffered:m,flush:async()=>{v||R()}}}function tp(t,e){let{args:n,mapRow:r=s=>s,...o}=e??{};return K(s=>{let i=!0;return t.findMany(n).then(a=>{i&&(s.emit(a.map(r)),s.down([[L]]))}).catch(a=>{if(i)try{s.down([[C,a instanceof Error?a:new Error(String(a))]])}catch{}}),()=>{i=!1}},{...o,describeKind:"producer",completeWhenDepsComplete:!1})}function np(t,e){let{mapRow:n=o=>o,...r}=e??{};return K(o=>{let s=!0;return t.execute().then(i=>{s&&(o.emit(i.map(n)),o.down([[L]]))}).catch(i=>{if(s)try{o.down([[C,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{s=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}function rp(t,e){let{mapRow:n=o=>o,...r}=e??{};return K(o=>{let s=!0;return t.execute().then(i=>{s&&(o.emit(i.map(n)),o.down([[L]]))}).catch(i=>{if(s)try{o.down([[C,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{s=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}Vn();ae();ee();function Va(){let t=new Map,e=null,n=null;function r(s){s.prev?s.prev.next=s.next:e=s.next,s.next?s.next.prev=s.prev:n=s.prev,s.prev=null,s.next=null}function o(s){s.next=e,s.prev=null,e&&(e.prev=s),e=s,n===null&&(n=s)}return{insert(s){if(t.has(s)){this.touch(s);return}let i={key:s,prev:null,next:null};t.set(s,i),o(i)},touch(s){let i=t.get(s);i&&(r(i),o(i))},delete(s){let i=t.get(s);i&&(r(i),t.delete(s))},evict(s){let i=[];for(let a=0;a<s&&n!==null;a++){let u=n;i.push(u.key),r(u),t.delete(u.key)}return i},size(){return t.size}}}function op(t){return t!=null&&typeof t.then=="function"}function Zn(t){op(t)&&t.catch(()=>{})}function sp(t,e){let n=new Map,r=e?.maxSize??0,o=r>0?e?.eviction??Va():null,s=e?.writeThrough??!1;function i(d,c,l){for(let p=0;p<l;p++)try{Zn(t[p].save(d,c))}catch{}}function a(d,c,l=0){for(let p=l;p<t.length;p++){let f;try{f=t[p].load(d)}catch{continue}if(op(f)){let m=p;f.then(h=>{h!==void 0?(c.down([[E,h]]),i(d,h,m)):a(d,c,m+1)},()=>{a(d,c,m+1)});return}if(f!==void 0){c.down([[E,f]]),i(d,f,p);return}}}function u(){if(!(!o||r<=0))for(;o.size()>=r;){let d=o.evict(1);if(d.length===0)break;for(let c of d){let l=n.get(c);if(l){let p=l.cache;if(l.status!=="sentinel"&&t.length>0){let f=t.length-1;try{Zn(t[f].save(c,p))}catch{}for(let m=0;m<f;m++)try{let h=t[m].delete;h&&Zn(h.call(t[m],c))}catch{}}l.down([[le]])}n.delete(c)}}}return{load(d){let c=n.get(d);if(c)return o?.touch(d),c;o&&r>0&&o.size()>=r&&u();let l=M(void 0);return n.set(d,l),o?.insert(d),a(d,l),l},save(d,c){if(s)for(let p of t)try{Zn(p.save(d,c))}catch{}else if(t[0])try{Zn(t[0].save(d,c))}catch{}let l=n.get(d);if(l)l.down([[E,c]]),o?.touch(d);else{o&&r>0&&o.size()>=r&&u();let p=M(c);n.set(d,p),o?.insert(d)}},invalidate(d){let c=n.get(d);c&&a(d,c)},delete(d){o?.delete(d);let c=n.get(d);c&&c.down([[le]]),n.delete(d);for(let l of t)try{let p=l.delete;p&&Zn(p.call(l,d))}catch{}},has(d){return n.has(d)},get size(){return n.size}}}Me();ae();ee();Me();xe();ae();ee();var Xr=class{_version=0;_store=new Map;_maxSize;_defaultTtl;constructor(e={}){let{maxSize:n,defaultTtl:r}=e;if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(r!==void 0&&r<=0)throw new RangeError("defaultTtl must be positive");this._maxSize=n,this._defaultTtl=r}get version(){return this._version}get size(){return this._store.size}has(e){let n=this._store.get(e);return n===void 0?!1:this._isExpired(n)?(this._store.delete(e),this._version+=1,!1):(this._touchLru(e,n),!0)}get(e){let n=this._store.get(e);if(n!==void 0){if(this._isExpired(n)){this._store.delete(e),this._version+=1;return}return this._touchLru(e,n),n.value}}set(e,n,r){let o=this._resolveExpiresAt(r);this._store.has(e)&&this._store.delete(e),this._store.set(e,{value:n,expiresAt:o}),this._evictLruWhileOver(),this._version+=1}setMany(e,n){let r=this._resolveExpiresAt(n),o=0;try{for(let[s,i]of e)this._store.has(s)&&this._store.delete(s),this._store.set(s,{value:i,expiresAt:r}),o+=1}finally{o>0&&(this._evictLruWhileOver(),this._version+=1)}}delete(e){let n=this._store.delete(e);return n&&(this._version+=1),n}deleteMany(e){let n=0;try{for(let r of e)this._store.delete(r)&&(n+=1)}finally{n>0&&(this._version+=1)}return n}clear(){let e=this._store.size;return e===0?0:(this._store.clear(),this._version+=1,e)}pruneExpired(){let e=H(),n=0;for(let[r,o]of this._store)this._isExpired(o,e)&&(this._store.delete(r),n+=1);return n>0&&(this._version+=1),n}toMap(){let e=H(),n=new Map;for(let[r,o]of this._store)this._isExpired(o,e)||n.set(r,o.value);return n}_resolveExpiresAt(e){let n=e??this._defaultTtl;if(n!==void 0){if(!Number.isFinite(n)||n<=0)throw new RangeError(`MapBackend: ttl must be a positive finite number (got ${n})`);return H()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??H())>=e.expiresAt}_touchLru(e,n){this._store.delete(e),this._store.set(e,n)}_evictLruWhileOver(){if(this._maxSize!==void 0)for(;this._store.size>this._maxSize;){let e=this._store.keys().next().value;if(e===void 0)break;this._store.delete(e)}}};function Ze(t={}){let{name:e,maxSize:n,defaultTtl:r,versioning:o,backend:s,retention:i}=t;if(i&&n!==void 0)throw new RangeError("reactiveMap: `maxSize` (LRU) and `retention` (score-based) are mutually exclusive. Pick one eviction policy.");if(i&&i.archiveThreshold===void 0&&i.maxSize===void 0)throw new RangeError("reactiveMap: `retention` requires at least one of `archiveThreshold` or `maxSize` to trigger archival.");let a=s??new Xr({maxSize:n,defaultTtl:r}),u=M(a.toMap(),{name:e,describeKind:"state",equals:(p,f)=>p===f,...o!=null?{versioning:o}:{}});function d(){let p=a.toMap();X(()=>{u.down([[ne]]),u.down([[E,p]])})}function c(){if(!i)return;let p=a.toMap(),f=i.archiveThreshold,m=i.maxSize,h=[];for(let[y,b]of p)h.push({key:y,value:b,score:i.score(y,b)});h.sort((y,b)=>y.score-b.score);let g=new Set;if(f!==void 0)for(let y of h)if(y.score<f)g.add(y.key);else break;if(m!==void 0&&h.length-g.size>m)for(let y of h){if(h.length-g.size<=m)break;g.has(y.key)||g.add(y.key)}if(g.size!==0)for(let y of h)g.has(y.key)&&(i.onArchive?.(y.key,y.value,y.score),a.delete(y.key))}function l(p,f="mutation"){let m=a.version;try{return p()}finally{a.version!==m&&(f==="mutation"&&c(),d())}}return{entries:u,has(p){return l(()=>a.has(p),"read")},get(p){return l(()=>a.get(p),"read")},set(p,f,m){l(()=>a.set(p,f,m?.ttl))},setMany(p,f){l(()=>a.setMany(p,f?.ttl))},delete(p){l(()=>a.delete(p))},deleteMany(p){l(()=>a.deleteMany(p))},clear(){l(()=>a.clear())},pruneExpired(){l(()=>a.pruneExpired())},get size(){return a.size},dispose(){}}}he();function Pg(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function up(t,e,n){let r=U(t),o=r.v!=null,s=M(n?.initialVerified??null,{...o?{meta:{sourceVersion:null}}:{}}),i=n?.trigger!==void 0&&n.trigger!==null,a=null;if(i&&n?.autoVerify?a=xt(U(n.trigger),r):i?a=U(n.trigger):n?.autoVerify&&(a=r),a!==null){let u;if(a===r)u=Te(r,d=>e(d));else{let d=r.cache;r.subscribe(c=>{for(let l of c)l[0]===E&&(d=l[1])}),u=Te(a,()=>e(d))}qt(u,d=>{X(()=>{if(s.down([[E,d]]),o){let c=r.v;c!=null&&s.meta.sourceVersion.down([[E,{id:c.id,version:c.version}]])}})})}return{node:r,verified:s,trigger:a}}function ip(t){t.subscribe(()=>{})}function Zr(t){return t instanceof Map?t:new Map}function ap(t,e){if(!Array.isArray(e.upsert))throw new TypeError("distill extraction requires upsert: Array<{ key, value }>");X(()=>{for(let{key:n,value:r}of e.upsert)t.set(n,r);for(let n of e.remove??[])t.delete(n)})}function Ls(t,e,n){let r=U(t),o=Ze(n.mapOptions??{}),s=n.budget??2e3,a=n.context!==void 0&&n.context!==null?U(n.context):M(null),u=Zr(o.entries.cache);o.entries.subscribe(f=>{for(let m of f)m[0]===E&&(u=Zr(m[1]))});let d=Te(r,f=>e(f,u));if(qt(d,f=>{ap(o,f)}),n.evict){let f=new Map,m=A([o.entries],([h])=>{let g=[],y=Zr(h);for(let b of f.keys())y.has(b)||(f.get(b)(),f.delete(b));for(let[b,v]of y){let T=n.evict(b,v);if(Pg(T)){if(!f.has(b)){let w=qt(T,x=>{x===!0&&o.has(b)&&o.delete(b)});f.set(b,w)}continue}if(typeof T=="boolean"){T&&g.push(b);continue}throw new TypeError("distill evict() must return boolean or Node<boolean>")}return g});qt(m,h=>{for(let g of h)o.delete(g)})}let c=n.consolidateTrigger!==void 0&&n.consolidateTrigger!==null;if(n.consolidate&&c){let f=U(n.consolidateTrigger),m=Te(f,()=>n.consolidate(u));qt(m,h=>{ap(o,h)})}let l=A([o.entries,a],([f,m])=>{let h=[...Zr(f).entries()].map(([b,v])=>({key:b,value:v,score:n.score(v,m),cost:n.cost(v)}));h.sort((b,v)=>v.score-b.score);let g=[],y=s;for(let b of h)b.cost<=y&&(g.push({key:b.key,value:b.value,score:b.score}),y-=b.cost);return g}),p=A([o.entries],([f])=>Zr(f).size);return ip(l),ip(p),{store:o,compact:l,size:p}}async function Is(t){let e=typeof t=="string"?new TextEncoder().encode(t):t,n=await globalThis.crypto.subtle.digest("SHA-256",e),r=new Uint8Array(n),o="";for(let s=0;s<r.length;s++)o+=dp[r[s]];return o}var dp=new Array(256);for(let t=0;t<256;t++)dp[t]=t.toString(16).padStart(2,"0");var eo=class extends Error{constructor(n,r){super(`content-addressed lookup miss in read-strict mode: ${n}`);this.key=n;this.context=r;this.name="ContentAddressedMissError"}};function to(t){let e=new Set,n=r=>{if(r===null||typeof r!="object")return r;let o=r;if(e.has(o))return{__cycle:!0};e.add(o);try{if(Array.isArray(r))return r.map(n);let s={};for(let i of Object.keys(r).sort())s[i]=n(r[i]);return s}finally{e.delete(o)}};return JSON.stringify(n(t))}function Ps(t){let{storage:e,keyContext:n,keyPrefix:r,mode:o="read-write"}=t,s=n??(a=>a);async function i(a){let u=to(s(a)),d=await Is(u);return r?`${r}:${d}`:d}return{keyFor:i,async lookup(a){if(o==="write")return;let u=await i(a),d=await e.load(u);if(d===void 0){if(o==="read-strict")throw new eo(u,a);return}return d},async store(a,u){if(o==="read")return;let d=await i(a);await e.save(d,u)},async forget(a){if(o==="read"||o==="write"||!e.delete)return;let u=await i(a);await e.delete(u)}}}aa();async function ht(t,e){let n;try{n=await t.text()}catch{n=""}let r=e??"HTTP",o=new Error(`${r} API ${t.status}: ${t.statusText}${n?` \u2014 ${n}`:""}`);return o.status=t.status,o.headers=t.headers,o}Me();ae();_e();var no=class{_version=0;_topics=new Set;get version(){return this._version}get topicCount(){return this._topics.size}hasTopic(e){return this._topics.has(e)}topicNames(){return this._topics.values()}createTopic(e){return this._topics.has(e)?!1:(this._topics.add(e),this._version+=1,!0)}removeTopic(e){let n=this._topics.delete(e);return n&&(this._version+=1),n}};function cp(t={}){let{backend:e}=t,n=e??new no,r=new Map;function o(s){let i=r.get(s);return i===void 0&&(i=z({describeKind:"state"}),r.set(s,i),n.createTopic(s)),i}return{topic(s){return o(s)},publish(s,i){o(s).emit(i)},publishMany(s){X(()=>{for(let[i,a]of s)o(i).emit(a)})},removeTopic(s){let i=r.get(s);return i===void 0?!1:(r.delete(s),n.removeTopic(s),i.down([[le]]),!0)},has(s){return n.hasTopic(s)},get size(){return n.topicCount},topicNames(){return n.topicNames()}}}Me();ae();ee();function lp(t,e){if(t===e)return 0;let n=typeof t;if(n===typeof e&&(n==="number"||n==="string"||n==="boolean"||n==="bigint")){let o=t,s=e;return o<s?-1:o>s?1:0}return String(t).localeCompare(String(e))}function Dg(t,e){let n=lp(t[0],e[0]);return n!==0?n:lp(t[1],e[1])}function pp(t){return[t.secondary,t.primary]}function er(t,e){let n=pp(e),r=0,o=t.length;for(;r<o;){let s=r+o>>1;Dg(n,pp(t[s]))>0?r=s+1:o=s}return r}var ro=class{_version=0;_buf=[];_byPrimary=new Map;get version(){return this._version}get size(){return this._buf.length}has(e){return this._byPrimary.has(e)}get(e){return this._byPrimary.get(e)?.value}upsert(e,n,r,o){let s=this._byPrimary.get(e),i={primary:e,secondary:n,value:r};if(s!==void 0&&o?.equals?.(s,i))return!1;if(s!==void 0){let u=er(this._buf,s);this._buf.splice(u,1)}let a=er(this._buf,i);return this._buf.splice(a,0,i),this._byPrimary.set(e,i),this._version+=1,s===void 0}upsertMany(e,n){let r=0;try{for(let o of e){let s=this._byPrimary.get(o.primary),i={primary:o.primary,secondary:o.secondary,value:o.value};if(s!==void 0&&n?.equals?.(s,i))continue;if(s!==void 0){let u=er(this._buf,s);this._buf.splice(u,1)}let a=er(this._buf,i);this._buf.splice(a,0,i),this._byPrimary.set(o.primary,i),r+=1}}finally{r>0&&(this._version+=1)}return r}delete(e){let n=this._byPrimary.get(e);if(n===void 0)return!1;let r=er(this._buf,n);return this._buf.splice(r,1),this._byPrimary.delete(e),this._version+=1,!0}deleteMany(e){let n=0;try{for(let r of e){let o=this._byPrimary.get(r);if(o===void 0)continue;let s=er(this._buf,o);this._buf.splice(s,1),this._byPrimary.delete(r),n+=1}}finally{n>0&&(this._version+=1)}return n}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._byPrimary.clear(),this._version+=1,e)}toArray(){return[...this._buf]}toPrimaryMap(){let e=new Map;for(let n of this._buf)e.set(n.primary,n.value);return e}};function Gg(t){return t.subscribe(()=>{})}function fp(t={}){let{name:e,versioning:n,equals:r,backend:o}=t,s=o??new ro;function i(f){return f?.equals!==void 0||r===void 0?f:{...f,equals:r}}let a=M([],{name:e,describeKind:"state",equals:(f,m)=>f===m,...n!=null?{versioning:n}:{}}),u=A([a],([f])=>{let m=f,h=new Map;for(let g of m)h.set(g.primary,g.value);return h},{initial:s.toPrimaryMap(),describeKind:"derived"}),d=Gg(u),c=!1;function l(){let f=s.toArray();X(()=>{a.down([[ne]]),a.down([[E,f]])})}function p(f){let m=s.version;try{return f()}finally{s.version!==m&&l()}}return{ordered:a,byPrimary:u,has(f){return s.has(f)},get(f){return s.get(f)},get size(){return s.size},upsert(f,m,h,g){return p(()=>s.upsert(f,m,h,i(g)))},upsertMany(f,m){let h=[...f];h.length!==0&&p(()=>s.upsertMany(h,i(m)))},delete(f){p(()=>s.delete(f))},deleteMany(f){let m=[...f];m.length!==0&&p(()=>s.deleteMany(m))},clear(){p(()=>s.clear())},dispose(){c||(c=!0,d())}}}Me();ae();ee();var oo=class{_version=0;_buf;constructor(e){this._buf=e?[...e]:[]}get version(){return this._version}get size(){return this._buf.length}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._buf.length+e;if(!(n<0||n>=this._buf.length))return this._buf[n]}append(e){this._buf.push(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._buf.length;this._buf.length=n+e.length;for(let r=0;r<e.length;r++)this._buf[n+r]=e[r];this._version+=1}insert(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insert: index ${e} out of range [0, ${this._buf.length}]`);this._buf.splice(e,0,n),this._version+=1}insertMany(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insertMany: index ${e} out of range [0, ${this._buf.length}]`);n.length!==0&&(this._buf.splice(e,0,...n),this._version+=1)}pop(e){if(this._buf.length===0)throw new RangeError("pop from empty list");if(!Number.isInteger(e))throw new RangeError(`pop: index ${e} must be an integer`);let n=e>=0?e:this._buf.length+e;if(n<0||n>=this._buf.length)throw new RangeError(`pop: index ${e} out of range`);let[r]=this._buf.splice(n,1);return this._version+=1,r}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._version+=1,e)}toArray(){return[...this._buf]}};function Ds(t,e={}){let{name:n,versioning:r,backend:o}=e,s=o??new oo(t),i=M(s.toArray(),{name:n,describeKind:"state",equals:(d,c)=>d===c,...r!=null?{versioning:r}:{}});function a(){let d=s.toArray();X(()=>{i.down([[ne]]),i.down([[E,d]])})}function u(d){let c=s.version;try{return d()}finally{s.version!==c&&a()}}return{items:i,get size(){return s.size},at(d){return s.at(d)},append(d){u(()=>s.append(d))},appendMany(d){u(()=>s.appendMany(d))},insert(d,c){u(()=>s.insert(d,c))},insertMany(d,c){u(()=>s.insertMany(d,c))},pop(d=-1){return u(()=>s.pop(d))},clear(){u(()=>s.clear())},dispose(){}}}Ot();ae();he();function Gs(t,e={}){let n=e.keyFn??(o=>String(o)),r=new Map;return o=>{let s=n(o),i=r.get(s);if(i)return i;let a=t(o),u;a!=null&&typeof a.then=="function"?u=Promise.resolve(a):a!=null&&typeof a=="object"&&"subscribe"in a&&"cache"in a?u=Ye(a):a!=null&&typeof a=="object"&&Symbol.asyncIterator in a?u=(async()=>{let l=a[Symbol.asyncIterator]();try{let{value:p,done:f}=await l.next();if(f)throw new Error("singleFromAny: factory returned empty async iterable");return p}finally{await l.return?.()}})():a!=null&&typeof a=="object"&&Symbol.iterator in a?u=(async()=>{let l=a[Symbol.iterator]();try{let{value:p,done:f}=l.next();if(f)throw new Error("singleFromAny: factory returned empty iterable");return p}finally{l.return?.()}})():u=Promise.resolve(a);let d,c=()=>{r.get(s)===d&&r.delete(s)};return d=u.then(l=>(c(),l),l=>{throw c(),l}),r.set(s,d),d}}function mp(t,e={}){let n=e.keyFn??(o=>String(o)),r=new Map;return o=>{let s=n(o),i=r.get(s);if(i)return i;let a=U(t(o));r.set(s,a);let u=a.subscribe(d=>{for(let c of d)if(c[0]===C||c[0]===L){r.get(s)===a&&r.delete(s),u();return}});return a}}he();function so(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(so);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=so(e[o]);return r}function Fs(t){return JSON.stringify(so(t),void 0,0)}var Fg=new TextEncoder,$g=new TextDecoder("utf-8",{fatal:!0}),tr={name:"json",version:1,encode(t){return Fg.encode(Fs(t))},decode(t){return JSON.parse($g.decode(t))}};function gp(){return tr}function io(){let t=new Map;return{name:"memory",read(e){let n=t.get(e);return n===void 0?void 0:new Uint8Array(n)},write(e,n){t.set(e,new Uint8Array(n))},delete(e){t.delete(e)},list(e){let n=[...t.keys()];return e?n.filter(r=>r.startsWith(e)).sort():n.sort()}}}function $s(t,e={}){let n=e.codec??tr,r=e.name??t.name??"snapshot",o=e.keyOf??(l=>l.name??e.name??t.name??"snapshot"),s,i=0,a=e.compactEvery,u,d={name:r,debounceMs:e.debounceMs,compactEvery:a,filter:e.filter,keyOf:o,save(l){if(!(e.filter&&!e.filter(l))&&(s={snapshot:l},i+=1,a!==void 0&&i%a===0||!e.debounceMs))return c()},load(){let l=u??r,p=t.read(l);if(p!==void 0)return p instanceof Uint8Array?p.length===0?void 0:n.decode(p):Promise.resolve(p).then(f=>f===void 0||f.length===0?void 0:n.decode(f))},async flush(){await c()},async rollback(){s=void 0}};function c(){let l=s;if(!l)return;s=void 0;let p=o(l.snapshot),f=n.encode(l.snapshot),m=t.write(p,f);if(m instanceof Promise)return m.then(()=>{u=p});u=p}return d}function Ka(t,e={}){let n=e.codec??tr,r=e.name??t.name??"append-log",o=e.keyOf??(p=>r),s=e.compactEvery,i=new Map,a=0,u,d={name:r,debounceMs:e.debounceMs,compactEvery:s,keyOf:o,appendEntries(p){if(p.length!==0){for(let f of p){let m=o(f),h=i.get(m);h||(h=[],i.set(m,h)),h.push(f)}if(a+=p.length,s!==void 0&&a%s===0||!e.debounceMs)return c()}},async loadEntries(p){let f=p?.keyFilter,m=t.list===void 0?f!==void 0?[f]:[r]:await Promise.resolve(t.list(f)),h=[];for(let g of m){let y=await Promise.resolve(t.read(g));if(y===void 0||y.length===0)continue;let b=n.decode(y);Array.isArray(b)&&h.push(...b)}return{entries:h,cursor:void 0}},async flush(){await c()},async rollback(){i=new Map}};function c(){if(i.size===0)return;let p=i;i=new Map;let f=(u??Promise.resolve()).then(()=>{let m=l(p);return m instanceof Promise?m:Promise.resolve()},()=>{let m=l(p);return m instanceof Promise?m:Promise.resolve()});return u=f.finally(()=>{u===f&&(u=void 0)}),u}function l(p){let f=[];for(let[m,h]of p){let g=t.read(m),y=b=>{let T=[...b===void 0||b.length===0?[]:n.decode(b)??[],...h],w=n.encode(T);return t.write(m,w)};if(g instanceof Promise)f.push(g.then(async b=>{let v=y(b);v instanceof Promise&&await v}));else{let b=y(g);b instanceof Promise&&f.push(b)}}if(f.length>0)return Promise.all(f).then(()=>{})}return d}function js(t,e={}){let n=e.codec??tr,r=e.name??t.name??"kv",o=e.compactEvery,s=new Map,i=0,a={name:r,debounceMs:e.debounceMs,compactEvery:o,filter:e.filter,save(d,c){if(!(e.filter&&!e.filter(d,c))&&(s.set(d,c),i+=1,o!==void 0&&i%o===0||!e.debounceMs))return u()},load(d){let c=t.read(d);if(c!==void 0)return c instanceof Uint8Array?c.length===0?void 0:n.decode(c):Promise.resolve(c).then(l=>l===void 0||l.length===0?void 0:n.decode(l))},delete(d){if(s.delete(d),!!t.delete)return t.delete(d)},list(d){return t.list?t.list(d):[]},async flush(){await u()},async rollback(){s=new Map}};function u(){if(s.size===0)return;let d=s;s=new Map;let c=[];for(let[l,p]of d){let f=n.encode(p),m=t.write(l,f);m instanceof Promise&&c.push(m)}if(c.length>0)return Promise.all(c).then(()=>{})}return a}function hp(t){return $s(io(),t)}function yp(t){return Ka(io(),t)}function ao(t){return js(io(),t)}function bp(t,e){let n={name:e?.name??"dict-kv",read(r){return t[r]},write(r,o){t[r]=new Uint8Array(o)},delete(r){delete t[r]},list(r){let o=Object.keys(t).sort();return r?o.filter(s=>s.startsWith(r)):o}};return js(n,e)}function vp(t,e){return $s({name:"dict",read(r){return t[r]},write(r,o){t[r]=new Uint8Array(o)},delete(r){delete t[r]},list(r){let o=Object.keys(t).sort();return r?o.filter(s=>s.startsWith(r)):o}},e)}ae();_e();ee();function uo(t,e,n,r){let o=new Y(t,r);o.add(e,{name:"source"});let s=M(n,{meta:{kind:"stratify_rules"}});o.add(s,{name:"rules"});for(let i of n)jg(o,e,s,i);return o}function jg(t,e,n,r){let o=`branch/${r.name}`,s=Symbol("noValue"),i=!1,a=!1,u=!1,d=s,c=!1,l=n.cache??[];function p(h){if(u){u=!1;let g=d;if(d=s,g!==s){let y=l.find(v=>v.name===r.name),b=!1;try{b=y?.classify(g)??!1}catch{b=!1}b?(c=!1,h.emit(g)):c&&(c=!1,h.down([[ne],[V]]))}else c?(c=!1,h.down([[ne],[V]])):h.down([[V]])}}let f=z([],(h,g)=>{let y=e.subscribe(v=>{for(let T of v)m(T,0,g)}),b=n.subscribe(v=>{for(let T of v)m(T,1,g)});return()=>{y(),b()}},{describeKind:"derived",meta:{kind:"stratify_branch",branch:r.name},completeWhenDepsComplete:!1});function m(h,g,y){let b=h[0];return b===ne?(g===0?(i=!0,c=!0):a=!0,!0):b===E||b===V?(g===0?(i=!1,u=!0,d=b===E?h[1]:s):(b===E&&(l=h[1]),a=!1),i||a||p(y),!0):b===L||b===C||b===le?(i=!1,a=!1,u=!1,d=s,c=!1,g===0&&y.down([h]),!0):g===1}if(t.add(f,{name:o}),r.ops){let h=r.ops(f),g=`branch/${r.name}/out`;t.add(h,{name:g})}}vt();Me();ae();_e();ee();he();ae();var Bg=new Map([[Je,"INVALIDATE"],[Be,"PAUSE"],[qe,"RESUME"],[le,"TEARDOWN"],[L,"COMPLETE"],[C,"ERROR"]]),Vg=new Map([["INVALIDATE",Je],["PAUSE",Be],["RESUME",qe],["TEARDOWN",le],["COMPLETE",L],["ERROR",C]]);function Ut(t){let e=Bg.get(t);return e||(Symbol.keyFor(t)??"UNKNOWN")}function gn(t){let e=Vg.get(t);if(e)return e;if(t&&t!=="UNKNOWN")return Symbol.for(t)}function hn(t){return t instanceof Error?{message:t.message,name:t.name,stack:t.stack}:{message:String(t),name:"Error"}}function yn(t){let e=new Error(t.message);return e.name=t.name,t.stack&&(e.stack=t.stack),e}function Jt(t){if(typeof MessagePort<"u"&&t instanceof MessagePort)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),t.start(),()=>t.removeEventListener("message",n)},terminate(){t.close()}};if(typeof SharedWorker<"u"&&t instanceof SharedWorker)return Jt(t.port);if(typeof Worker<"u"&&t instanceof Worker)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),()=>t.removeEventListener("message",n)},terminate(){t.terminate()}};if(typeof BroadcastChannel<"u"&&t instanceof BroadcastChannel)return{post(e,n){n&&n.length>0&&console.warn("[graphrefly] WorkerTransport: BroadcastChannel does not support Transferable objects. The transfer argument is ignored and objects will be cloned instead."),t.postMessage(e)},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),()=>t.removeEventListener("message",n)},terminate(){t.close()}};if(typeof ServiceWorker<"u"&&t instanceof ServiceWorker)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>{r.source===t&&e(r.data)};return navigator.serviceWorker.addEventListener("message",n),()=>navigator.serviceWorker.removeEventListener("message",n)}};throw new Error("createTransport: unsupported target type. Expected Worker, SharedWorker, ServiceWorker, BroadcastChannel, or MessagePort.")}function Kg(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function qa(t,e){let n=Kg(t)?t:Jt(t),r=e.name??"workerBridge",o=Object.entries(e.expose??{}),s=e.import??[],i=e.transfer??{},a=M("connecting",{name:`${r}::meta::status`}),u=M(null,{name:`${r}::meta::error`}),d=new Map,c=new Map;for(let b of s){let v=M(void 0,{name:`${r}::${b}`});d.set(b,v)}let l;if(o.length>0){let b=o.map(([,w])=>w),v=z(b,(w,x)=>{let k={};for(let S=0;S<o.length;S++){let[R]=o[S],N=w[S];N!=null&&N.length>0&&(k[R]=N.at(-1))}Object.keys(k).length!==0&&x.emit(k)},{name:`${r}::aggregated`,partial:!0});l=pe([v],w=>{let x=w[0];if(x==null||Object.keys(x).length===0)return;let k=[];for(let N of Object.keys(x)){let _=i[N];_&&k.push(..._(x[N]))}let S;for(let[N,_]of o)N in x&&_.v!=null&&(S==null&&(S={}),S[N]=_.v.version);let R={t:"b",u:x,...S?{v:S}:{}};try{n.post(R,k.length>0?k:void 0)}catch(N){u.down([[E,N instanceof Error?N:new Error(String(N))]])}}).subscribe(()=>{})}let p=!1,f=n.listen(b=>{if(p)return;let v=b;switch(v.t){case"r":{X(()=>{for(let[w,x]of Object.entries(v.stores)){let k=d.get(w);k&&k.down([[E,x]])}}),a.down([[E,"connected"]]);let T={};for(let[w,x]of o)T[w]=x.cache;n.post({t:"i",stores:T});break}case"v":{let T=d.get(v.s);T&&T.down([[E,v.d]]);break}case"b":{X(()=>{for(let[T,w]of Object.entries(v.u)){let x=v.v?.[T];if(x!=null){let S=c.get(T);if(S!=null&&x<=S)continue;c.set(T,x)}let k=d.get(T);k&&k.down([[E,w]])}});break}case"e":{let T=d.get(v.s);T&&T.down([[C,yn(v.err)]]);break}case"s":{let T=gn(v.sig);if(!T)break;let w=v.s==="*"?[...d.values()]:d.has(v.s)?[d.get(v.s)]:[];for(let x of w)x.down(v.d===void 0?[[T]]:[[T,v.d]]);break}}}),m=[];for(let[b,v]of o){let T=v.subscribe((w=>{if(!p)for(let x of w){let k=x[0];k!==E&&($e.isLocalOnly(k)||(k===C?n.post({t:"e",s:b,err:hn(x[1])}):n.post({t:"s",s:b,sig:Ut(k),d:x.length>1?x[1]:void 0})))}}));m.push(T)}let h;if(e.timeoutMs!=null&&e.timeoutMs>0){let b=st(e.timeoutMs),v=Xe(a,w=>w==="connected");h=Cs(xt(zr(b,()=>"timeout"),zr(v,()=>"ready"))).subscribe(w=>{for(let x of w)x[0]===E&&x[1]==="timeout"&&(u.down([[E,new Error("Worker bridge handshake timeout")]]),g())})}function g(){if(!p){p=!0,h?.(),n.post({t:"s",s:"*",sig:Ut(le)}),l&&l();for(let b of m)b();m.length=0,f(),a.down([[E,"closed"]]),c.clear(),d.clear()}}let y={meta:{status:a,error:u},destroy:g};for(let[b,v]of d)y[b]=v;return y}Me();ae();_e();ee();function qg(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function Ha(t,e){let n=qg(t)?t:Jt(t),r=e.import??[],o=e.transfer??{},s=new Map,i=new Map,a={};for(let g of r){let y=M(void 0,{name:`worker::${g}`});s.set(g,y),a[g]=y}let u=e.expose(a),d=Object.entries(u),c,l=!1;if(d.length>0){let g=d.map(([,v])=>v),y=z(g,(v,T)=>{let w={};for(let x=0;x<d.length;x++){let[k]=d[x],S=v[x];S!=null&&S.length>0&&(w[k]=S.at(-1))}Object.keys(w).length!==0&&T.emit(w)},{name:"workerSelf::aggregated",partial:!0});c=pe([y],v=>{if(l)return;let T=v[0];if(T==null||Object.keys(T).length===0)return;let w=[];for(let S of Object.keys(T)){let R=o[S];R&&w.push(...R(T[S]))}let x;for(let[S,R]of d)S in T&&R.v!=null&&(x==null&&(x={}),x[S]=R.v.version);let k={t:"b",u:T,...x?{v:x}:{}};try{n.post(k,w.length>0?w:void 0)}catch{}}).subscribe(()=>{})}let p=[];for(let[g,y]of d){let b=y.subscribe((v=>{if(!l)for(let T of v){let w=T[0];w!==E&&($e.isLocalOnly(w)||(w===C?n.post({t:"e",s:g,err:hn(T[1])}):n.post({t:"s",s:g,sig:Ut(w),d:T.length>1?T[1]:void 0})))}}));p.push(b)}let f=n.listen(g=>{if(l)return;let y=g;switch(y.t){case"i":{X(()=>{for(let[b,v]of Object.entries(y.stores)){let T=s.get(b);T&&T.down([[E,v]])}});break}case"v":{let b=s.get(y.s);b&&b.down([[E,y.d]]);break}case"b":{X(()=>{for(let[b,v]of Object.entries(y.u)){let T=y.v?.[b];if(T!=null){let x=i.get(b);if(x!=null&&T<=x)continue;i.set(b,T)}let w=s.get(b);w&&w.down([[E,v]])}});break}case"e":{let b=s.get(y.s);b&&b.down([[C,yn(y.err)]]);break}case"s":{let b=gn(y.sig);if(!b)break;if(b===le&&y.s==="*"){h();return}let v=y.s==="*"?[...s.values()]:s.has(y.s)?[s.get(y.s)]:[];for(let T of v)T.down(y.d===void 0?[[b]]:[[b,y.d]]);break}}}),m={};for(let[g,y]of d)m[g]=y.cache;n.post({t:"r",stores:m});function h(){if(!l){l=!0,c&&c();for(let g of p)g();p.length=0,f(),n.terminate?.(),i.clear(),s.clear()}}return{destroy:h}}var Qu={};ke(Qu,{SNAPSHOT_WIRE_VERSION:()=>No,SurfaceError:()=>Ne,accountability:()=>yi,ai:()=>mi,asSurfaceError:()=>Fi,cqrs:()=>Ts,createGraph:()=>pr,deleteSnapshot:()=>Hi,demoShell:()=>vi,diffSnapshots:()=>Ki,domainTemplates:()=>Ti,graphspec:()=>fi,guarded:()=>ki,harness:()=>Ai,jobQueue:()=>Oi,layout:()=>Di,lens:()=>Ii,listSnapshots:()=>qi,memory:()=>ci,messaging:()=>oi,orchestration:()=>si,process:()=>Pi,reduction:()=>pi,refine:()=>Si,resilientPipeline:()=>Gi,restoreSnapshot:()=>Vi,runReduction:()=>$i,saveSnapshot:()=>Bi,surface:()=>Wi});var mi={};ke(mi,{AgentLoopGraph:()=>ui,AllTiersExhaustedError:()=>po,BudgetExhaustedError:()=>Js,ChatStreamGraph:()=>ii,CircuitOpenError:()=>pt,DEFAULT_DECAY_RATE:()=>Tu,FallbackMissError:()=>Xg,LLMTimeoutError:()=>rr,ReplayCacheMissError:()=>Tn,ToolRegistryGraph:()=>ai,admissionFilter3D:()=>ry,admissionScored:()=>qp,agentLoop:()=>ey,agentMemory:()=>ay,anthropicAdapter:()=>za,canonicalJson:()=>Ja,cascadingLlmAdapter:()=>uu,chatStream:()=>pu,composePricing:()=>yh,computePrice:()=>tu,contentGate:()=>Yh,costMeterExtractor:()=>qh,createAdapter:()=>ph,createCapabilitiesRegistry:()=>Hg,createPricingRegistry:()=>gh,dryRunAdapter:()=>bn,fallbackAdapter:()=>Ya,fromLLM:()=>Ch,frozenContext:()=>Ph,gatedStream:()=>Bh,gaugesAsContext:()=>uy,googleAdapter:()=>Qa,graphFromSpec:()=>tf,graphFromSpecReactive:()=>vy,handoff:()=>ty,keywordFlagExtractor:()=>Wh,knobsAsTools:()=>wy,llmConsolidator:()=>hu,llmExtractor:()=>gu,memoryRetrieval:()=>Ru,memoryWithKG:()=>ku,memoryWithTiers:()=>xu,memoryWithVectors:()=>wu,observableAdapter:()=>fh,openAICompatAdapter:()=>Za,parseRateLimitFromError:()=>su,pricingFor:()=>bh,promptNode:()=>wn,redactor:()=>Qh,registryPricing:()=>hh,resilientAdapter:()=>Oh,streamExtractor:()=>zh,streamingPromptNode:()=>jh,suggestStrategy:()=>nf,suggestStrategyReactive:()=>xy,systemPromptBuilder:()=>Vh,tier:()=>_h,toolCallExtractor:()=>Jh,toolExecution:()=>fu,toolRegistry:()=>mu,toolSelector:()=>ny,validateGraphDef:()=>Ry,withBreaker:()=>nu,withBudgetGate:()=>ou,withDryRun:()=>Th,withRateLimiter:()=>au,withReplayCache:()=>lo,withRetry:()=>du,withTimeout:()=>cu,zeroPrice:()=>Us});ee();function co(t,e){return`${t}::${e}`}function Hg(t){let e=Ze({name:"capabilitiesRegistry"}),n=d=>{e.set(co(d.provider,d.id),d)};if(t)for(let d of t)n(d);let r=(d,c)=>{let l=e.get(co(d,c));if(l)return l;let p=e.entries.cache;if(!p)return;let f;for(let[,m]of p){if(m.provider!==d)continue;let h=m.id;c.startsWith(h)&&(!f||h.length>f.id.length)&&(f=m)}return f},o=128,s=new Map,i=new Map,a=(d,c,l,p)=>{for(d.has(c)&&d.delete(c),d.set(c,l);d.size>p;){let f=d.keys().next().value;if(f===void 0)break;d.delete(f)}},u=A([e.entries],([d])=>Array.from(d.values()),{name:"capabilitiesRegistry/entries",initial:[]});return{register:n,lookup:r,remove(d,c){let l=e.has(co(d,c));return l&&e.delete(co(d,c)),l},entries(){let d=e.entries.cache;return(function*(){if(d)for(let c of d.values())yield c})()},lookupNode(d,c){let l=co(d,c),p=s.get(l);if(p)return s.delete(l),s.set(l,p),p;let f=A([e.entries],()=>r(d,c),{name:`capabilitiesRegistry/lookup/${d}::${c}`,initial:void 0});return a(s,l,f,o),f},entriesNode:u,byProvider(d){let c=i.get(d);if(c)return i.delete(d),i.set(d,c),c;let l=A([u],([p])=>p.filter(f=>f.provider===d),{name:`capabilitiesRegistry/byProvider/${d}`,initial:[]});return a(i,d,l,o),l}}}xe();function za(t={}){return t.sdk?Yg(t):Jg(t)}function Bs(t,e,n,r){let o=e?.model??n;if(!o)throw new Error("anthropicAdapter: model must be set via options.model or invokeOpts.model");let{system:s,chat:i}=Wg(t,e?.systemPrompt),a={model:o,messages:i.map(zg),max_tokens:e?.maxTokens??4096};return s&&(a.system=s),e?.temperature!=null&&(a.temperature=e.temperature),e?.tools&&e.tools.length>0&&(a.tools=e.tools.map(Ug)),e?.maxReasoningTokens!=null&&(a.thinking={type:"enabled",budget_tokens:e.maxReasoningTokens}),e?.cacheHint,r&&(a.stream=!0),e?.providerExtras&&Object.assign(a,e.providerExtras),a}function Wg(t,e){let n=[];e&&n.push(e);let r=[];for(let o of t)o.role==="system"?n.push(o.content):r.push(o);return{system:n.length>0?n.join(`
|
|
32
|
+
`:JSON.stringify(p),m=s(l,se());await e.putObject({Bucket:n,Key:m,Body:f,ContentType:c})}})}function ip(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 Ue(t,{onTransportError:s,serialize:i=>o(i,n),send:async i=>{let a=i;await e.query(a.sql,a.params)}})}function ap(t,e,n){let{toDocument:r=s=>s,onTransportError:o}=n??{};return Ue(t,{onTransportError:o,serialize:r,send:async s=>{await e.insertOne(s)}})}function dp(t,e,n){let{labels:r={},toLine:o=a=>JSON.stringify(a),toLabels:s,onTransportError:i}=n??{};return Ue(t,{onTransportError:i,serialize:a=>({line:o(a),labels:s?{...r,...s(a)}:r}),send:async a=>{let{line:d,labels:u}=a,c=`${se()}`;await e.push({streams:[{stream:u,values:[[c,d]]}]})}})}function up(t,e,n){let{toResourceSpans:r=s=>[s],onTransportError:o}=n??{};return Ue(t,{onTransportError:o,serialize:r,send:async s=>{await e.push({resourceSpans:s})}})}function cp(t,e,n,r){let{prefix:o="checkpoints/",debounceMs:s=500,compactEvery:i=10,onError:a}=r??{},d={name:`s3:${n}`,debounceMs:s,compactEvery:i,save(u){let c=Math.floor(se()/1e6),l=`${o}${t.name}/checkpoint-${c}.json`,p;try{p=JSON.stringify(u)}catch(f){a?.(f);return}e.putObject({Bucket:n,Key:l,Body:p,ContentType:"application/json"}).catch(f=>a?.(f))}};return t.attachSnapshotStorage([d],{onError:u=>a?.(u)})}function lp(t,e,n){let{prefix:r="graphrefly:checkpoint:",debounceMs:o=500,compactEvery:s=10,onError:i}=n??{},a=`${r}${t.name}`,d={name:`redis:${a}`,debounceMs:o,compactEvery:s,save(u){let c;try{c=JSON.stringify(u)}catch(l){i?.(l);return}e.set(a,c).catch(l=>i?.(l))},async load(){let u=await e.get(a);if(u!=null)try{return JSON.parse(u)}catch{return}}};return t.attachSnapshotStorage([d],{onError:u=>i?.(u)})}function pp(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return z(i=>{try{let d=t.query(e,o).map(r);i.emit(d),i.down([[P]])}catch(a){i.down([[I,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...s})}function fp(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return z(i=>{try{let a=t.iterate(e,o);Z(()=>{for(let d of a)i.emit(r(d));i.down([[P]])})}catch(a){i.down([[I,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...s})}function mp(t,e,n,r){if(n.includes("\0")||n.length===0)throw new Error(`toSqlite: invalid table name: ${JSON.stringify(n)}`);let{toSQL:o=(N,L)=>({sql:`INSERT INTO "${L.replace(/"/g,'""')}" (data) VALUES (?)`,params:[JSON.stringify(N)]}),onTransportError:s,batchInsert:i=!1,maxBatchSize:a=1e3,flushIntervalMs:d=0}=r??{},u=N=>o(N,n);if(!i)return Ue(t,{onTransportError:s,serialize:u,send:N=>{let L=N;e.query(L.sql,L.params)}});let c=A(null),l=A(void 0,{equals:()=>!1}),p=A(null),f=A(0),m=A(0),h=N=>{try{s?.(N)}catch{}try{c.down([[M,N]])}catch{}},g=[],y=!1,b,v=!1,T=()=>m.down([[M,g.length]]),w=N=>{v||l.down([[M,N]])},x=N=>{v||p.down([[M,N]])},k=N=>{v||f.down([[M,N]])},S=N=>{v||h(N)},R=()=>{if(g.length===0||y)return;y=!0,k(1);try{e.query("BEGIN",[])}catch($){y=!1,k(0),S({stage:"send",error:$ instanceof Error?$:new Error(String($)),value:void 0});return}let N=g;g=[],T();let L,j=0;for(let $ of N)try{e.query($.query.sql,$.query.params),j+=1}catch(D){L=D instanceof Error?D:new Error(String(D));break}if(L){try{e.query("ROLLBACK",[])}catch{}S({stage:"send",error:L,value:void 0});for(let $ of N)x({value:$.value,error:L,attempts:1})}else try{e.query("COMMIT",[]);for(let $ of N)w($.value)}catch($){let D=$ instanceof Error?$:new Error(String($));S({stage:"send",error:D,value:void 0});for(let K=0;K<j;K++)x({value:N[K].value,error:D,attempts:1})}y=!1,k(0)},E=()=>{d>0&&b===void 0&&!v&&(b=setTimeout(()=>{b=void 0,R()},d))},_=t.subscribe(N=>{for(let L of N){let j=L[0];if(j===M){let $=L[1],D;try{D=u($)}catch(K){let F=K instanceof Error?K:new Error(String(K));h({stage:"serialize",error:F,value:$}),p.down([[M,{value:$,error:F,attempts:0}]]);continue}g.push({value:$,query:D}),T(),g.length>=a?R():E()}else Fe.messageTier(j)>=3&&R()}});return{dispose:()=>{if(!v){b!==void 0&&(clearTimeout(b),b=void 0),R(),v=!0,_();for(let N of[c,l,p,f,m])try{N.down([[le]])}catch{}}},sent:l,failed:p,inFlight:f,errors:c,buffered:m,flush:async()=>{v||R()}}}function gp(t,e){let{args:n,mapRow:r=s=>s,...o}=e??{};return z(s=>{let i=!0;return t.findMany(n).then(a=>{i&&(s.emit(a.map(r)),s.down([[P]]))}).catch(a=>{if(i)try{s.down([[I,a instanceof Error?a:new Error(String(a))]])}catch{}}),()=>{i=!1}},{...o,describeKind:"producer",completeWhenDepsComplete:!1})}function hp(t,e){let{mapRow:n=o=>o,...r}=e??{};return z(o=>{let s=!0;return t.execute().then(i=>{s&&(o.emit(i.map(n)),o.down([[P]]))}).catch(i=>{if(s)try{o.down([[I,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{s=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}function yp(t,e){let{mapRow:n=o=>o,...r}=e??{};return z(o=>{let s=!0;return t.execute().then(i=>{s&&(o.emit(i.map(n)),o.down([[P]]))}).catch(i=>{if(s)try{o.down([[I,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{s=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}Wn();ae();ne();function Za(){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 d=n;i.push(d.key),r(d),t.delete(d.key)}return i},size(){return t.size}}}function bp(t){return t!=null&&typeof t.then=="function"}function sr(t){bp(t)&&t.catch(()=>{})}function vp(t,e){let n=new Map,r=e?.maxSize??0,o=r>0?e?.eviction??Za():null,s=e?.writeThrough??!1;function i(u,c,l){for(let p=0;p<l;p++)try{sr(t[p].save(u,c))}catch{}}function a(u,c,l=0){for(let p=l;p<t.length;p++){let f;try{f=t[p].load(u)}catch{continue}if(bp(f)){let m=p;f.then(h=>{h!==void 0?(c.down([[M,h]]),i(u,h,m)):a(u,c,m+1)},()=>{a(u,c,m+1)});return}if(f!==void 0){c.down([[M,f]]),i(u,f,p);return}}}function d(){if(!(!o||r<=0))for(;o.size()>=r;){let u=o.evict(1);if(u.length===0)break;for(let c of u){let l=n.get(c);if(l){let p=l.cache;if(l.status!=="sentinel"&&t.length>0){let f=t.length-1;try{sr(t[f].save(c,p))}catch{}for(let m=0;m<f;m++)try{let h=t[m].delete;h&&sr(h.call(t[m],c))}catch{}}l.down([[le]])}n.delete(c)}}}return{load(u){let c=n.get(u);if(c)return o?.touch(u),c;o&&r>0&&o.size()>=r&&d();let l=A(void 0);return n.set(u,l),o?.insert(u),a(u,l),l},save(u,c){if(s)for(let p of t)try{sr(p.save(u,c))}catch{}else if(t[0])try{sr(t[0].save(u,c))}catch{}let l=n.get(u);if(l)l.down([[M,c]]),o?.touch(u);else{o&&r>0&&o.size()>=r&&d();let p=A(c);n.set(u,p),o?.insert(u)}},invalidate(u){let c=n.get(u);c&&a(u,c)},delete(u){o?.delete(u);let c=n.get(u);c&&c.down([[le]]),n.delete(u);for(let l of t)try{let p=l.delete;p&&sr(p.call(l,u))}catch{}},has(u){return n.has(u)},get size(){return n.size}}}Ae();ae();it();ne();Ae();Re();ae();ne();var so=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 je(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 so({maxSize:n,defaultTtl:r}),d=A(a.toMap(),{name:e,describeKind:"state",equals:(p,f)=>p===f,...o!=null?{versioning:o}:{}});function u(){let p=a.toMap();Z(()=>{d.down([[oe]]),d.down([[M,p]])})}function c(){if(!i)return;let p=a.toMap(),f=i.archiveThreshold,m=i.maxSize,h=[];for(let[y,b]of p)h.push({key:y,value:b,score:i.score(y,b)});h.sort((y,b)=>y.score-b.score);let g=new Set;if(f!==void 0)for(let y of h)if(y.score<f)g.add(y.key);else break;if(m!==void 0&&h.length-g.size>m)for(let y of h){if(h.length-g.size<=m)break;g.has(y.key)||g.add(y.key)}if(g.size!==0)for(let y of h)g.has(y.key)&&(i.onArchive?.(y.key,y.value,y.score),a.delete(y.key))}function l(p,f="mutation"){let m=a.version;try{return p()}finally{a.version!==m&&(f==="mutation"&&c(),u())}}return{entries:d,has(p){return l(()=>a.has(p),"read")},get(p){return l(()=>a.get(p),"read")},set(p,f,m){l(()=>a.set(p,f,m?.ttl))},setMany(p,f){l(()=>a.setMany(p,f?.ttl))},delete(p){l(()=>a.delete(p))},deleteMany(p){l(()=>a.deleteMany(p))},clear(){l(()=>a.clear())},pruneExpired(){l(()=>a.pruneExpired())},get size(){return a.size},dispose(){}}}ve();function th(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function kp(t,e,n){let r=Y(t),o=r.v!=null,s=A(n?.initialVerified??null,{meta:{...we("verifiable"),...o?{sourceVersion:null}:{}}}),i=n?.trigger!==void 0&&n.trigger!==null,a=null;if(i&&n?.autoVerify?a=Et(Y(n.trigger),r):i?a=Y(n.trigger):n?.autoVerify&&(a=r),a!==null){let d;if(a===r)d=ke(r,u=>e(u));else{let u=r.cache;r.subscribe(c=>{for(let l of c)l[0]===M&&(u=l[1])}),d=ke(a,()=>e(u))}Wt(d,u=>{Z(()=>{if(s.down([[M,u]]),o){let c=r.v;c!=null&&s.meta.sourceVersion.down([[M,{id:c.id,version:c.version}]])}})})}return{node:r,verified:s,trigger:a}}function Tp(t){t.subscribe(()=>{})}function io(t){return t instanceof Map?t:new Map}function wp(t,e){if(!Array.isArray(e.upsert))throw new TypeError("distill extraction requires upsert: Array<{ key, value }>");Z(()=>{for(let{key:n,value:r}of e.upsert)t.set(n,r);for(let n of e.remove??[])t.delete(n)})}function js(t,e,n){let r=Y(t),o=je(n.mapOptions??{}),s=n.budget??2e3,a=n.context!==void 0&&n.context!==null?Y(n.context):A(null),d=io(o.entries.cache);o.entries.subscribe(f=>{for(let m of f)m[0]===M&&(d=io(m[1]))});let u=Y(e(r,o.entries));if(Wt(u,f=>{wp(o,f)}),n.evict){let f=new Map,m=C([o.entries],([h])=>{let g=[],y=io(h);for(let b of f.keys())y.has(b)||(f.get(b)(),f.delete(b));for(let[b,v]of y){let T=n.evict(b,v);if(th(T)){if(!f.has(b)){let w=Wt(T,x=>{x===!0&&o.has(b)&&o.delete(b)});f.set(b,w)}continue}if(typeof T=="boolean"){T&&g.push(b);continue}throw new TypeError("distill evict() must return boolean or Node<boolean>")}return g});Wt(m,h=>{for(let g of h)o.delete(g)})}let c=n.consolidateTrigger!==void 0&&n.consolidateTrigger!==null;if(n.consolidate&&c){let f=Y(n.consolidateTrigger),m=ke(f,()=>n.consolidate(d));Wt(m,h=>{wp(o,h)})}let l=C([o.entries,a],([f,m])=>{let h=[...io(f).entries()].map(([b,v])=>({key:b,value:v,score:n.score(v,m),cost:n.cost(v)}));h.sort((b,v)=>v.score-b.score);let g=[],y=s;for(let b of h)b.cost<=y&&(g.push({key:b.key,value:b.value,score:b.score}),y-=b.cost);return g},{meta:{...we("distill",{budget:s})}}),p=C([o.entries],([f])=>io(f).size);return Tp(l),Tp(p),{store:o,compact:l,size:p}}async function Bs(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+=xp[r[s]];return o}var xp=new Array(256);for(let t=0;t<256;t++)xp[t]=t.toString(16).padStart(2,"0");var ao=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 uo(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 Vs(t){let{storage:e,keyContext:n,keyPrefix:r,mode:o="read-write"}=t,s=n??(a=>a);async function i(a){let d=uo(s(a)),u=await Bs(d);return r?`${r}:${u}`:u}return{keyFor:i,async lookup(a){if(o==="write")return;let d=await i(a),u=await e.load(d);if(u===void 0){if(o==="read-strict")throw new ao(d,a);return}return u},async store(a,d){if(o==="read")return;let u=await i(a);await e.save(u,d)},async forget(a){if(o==="read"||o==="write"||!e.delete)return;let d=await i(a);await e.delete(d)}}}ga();async function wt(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}Ae();ae();Me();var co=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 Rp(t={}){let{backend:e}=t,n=e??new co,r=new Map;function o(s){let i=r.get(s);return i===void 0&&(i=U({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){Z(()=>{for(let[i,a]of s)o(i).emit(a)})},removeTopic(s){let i=r.get(s);return i===void 0?!1:(r.delete(s),n.removeTopic(s),i.down([[le]]),!0)},has(s){return n.hasTopic(s)},get size(){return n.topicCount},topicNames(){return n.topicNames()}}}Ae();ae();ne();function Sp(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 nh(t,e){let n=Sp(t[0],e[0]);return n!==0?n:Sp(t[1],e[1])}function Np(t){return[t.secondary,t.primary]}function ir(t,e){let n=Np(e),r=0,o=t.length;for(;r<o;){let s=r+o>>1;nh(n,Np(t[s]))>0?r=s+1:o=s}return r}var lo=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 d=ir(this._buf,s);this._buf.splice(d,1)}let a=ir(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 d=ir(this._buf,s);this._buf.splice(d,1)}let a=ir(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=ir(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=ir(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 rh(t){return t.subscribe(()=>{})}function Ep(t={}){let{name:e,versioning:n,equals:r,backend:o}=t,s=o??new lo;function i(f){return f?.equals!==void 0||r===void 0?f:{...f,equals:r}}let a=A([],{name:e,describeKind:"state",equals:(f,m)=>f===m,...n!=null?{versioning:n}:{}}),d=C([a],([f])=>{let m=f,h=new Map;for(let g of m)h.set(g.primary,g.value);return h},{initial:s.toPrimaryMap(),describeKind:"derived"}),u=rh(d),c=!1;function l(){let f=s.toArray();Z(()=>{a.down([[oe]]),a.down([[M,f]])})}function p(f){let m=s.version;try{return f()}finally{s.version!==m&&l()}}return{ordered:a,byPrimary:d,has(f){return s.has(f)},get(f){return s.get(f)},get size(){return s.size},upsert(f,m,h,g){return p(()=>s.upsert(f,m,h,i(g)))},upsertMany(f,m){let h=[...f];h.length!==0&&p(()=>s.upsertMany(h,i(m)))},delete(f){p(()=>s.delete(f))},deleteMany(f){let m=[...f];m.length!==0&&p(()=>s.deleteMany(m))},clear(){p(()=>s.clear())},dispose(){c||(c=!0,u())}}}Ae();ae();ne();var po=class{_version=0;_buf;constructor(e){this._buf=e?[...e]:[]}get version(){return this._version}get size(){return this._buf.length}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._buf.length+e;if(!(n<0||n>=this._buf.length))return this._buf[n]}append(e){this._buf.push(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._buf.length;this._buf.length=n+e.length;for(let r=0;r<e.length;r++)this._buf[n+r]=e[r];this._version+=1}insert(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insert: index ${e} out of range [0, ${this._buf.length}]`);this._buf.splice(e,0,n),this._version+=1}insertMany(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insertMany: index ${e} out of range [0, ${this._buf.length}]`);n.length!==0&&(this._buf.splice(e,0,...n),this._version+=1)}pop(e){if(this._buf.length===0)throw new RangeError("pop from empty list");if(!Number.isInteger(e))throw new RangeError(`pop: index ${e} must be an integer`);let n=e>=0?e:this._buf.length+e;if(n<0||n>=this._buf.length)throw new RangeError(`pop: index ${e} out of range`);let[r]=this._buf.splice(n,1);return this._version+=1,r}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._version+=1,e)}toArray(){return[...this._buf]}};function Ks(t,e={}){let{name:n,versioning:r,backend:o}=e,s=o??new po(t),i=A(s.toArray(),{name:n,describeKind:"state",equals:(u,c)=>u===c,...r!=null?{versioning:r}:{}});function a(){let u=s.toArray();Z(()=>{i.down([[oe]]),i.down([[M,u]])})}function d(u){let c=s.version;try{return u()}finally{s.version!==c&&a()}}return{items:i,get size(){return s.size},at(u){return s.at(u)},append(u){d(()=>s.append(u))},appendMany(u){d(()=>s.appendMany(u))},insert(u,c){d(()=>s.insert(u,c))},insertMany(u,c){d(()=>s.insertMany(u,c))},pop(u=-1){return d(()=>s.pop(u))},clear(){d(()=>s.clear())},dispose(){}}}It();ae();ve();function qs(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),d;a!=null&&typeof a.then=="function"?d=Promise.resolve(a):a!=null&&typeof a=="object"&&"subscribe"in a&&"cache"in a?d=et(a):a!=null&&typeof a=="object"&&Symbol.asyncIterator in a?d=(async()=>{let l=a[Symbol.asyncIterator]();try{let{value:p,done:f}=await l.next();if(f)throw new Error("singleFromAny: factory returned empty async iterable");return p}finally{await l.return?.()}})():a!=null&&typeof a=="object"&&Symbol.iterator in a?d=(async()=>{let l=a[Symbol.iterator]();try{let{value:p,done:f}=l.next();if(f)throw new Error("singleFromAny: factory returned empty iterable");return p}finally{l.return?.()}})():d=Promise.resolve(a);let u,c=()=>{r.get(s)===u&&r.delete(s)};return u=d.then(l=>(c(),l),l=>{throw c(),l}),r.set(s,u),u}}function _p(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=Y(t(o));r.set(s,a);let d=a.subscribe(u=>{for(let c of u)if(c[0]===I||c[0]===P){r.get(s)===a&&r.delete(s),d();return}});return a}}ve();function fo(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(fo);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=fo(e[o]);return r}function zs(t){return JSON.stringify(fo(t),void 0,0)}var oh=new TextEncoder,sh=new TextDecoder("utf-8",{fatal:!0}),ar={name:"json",version:1,encode(t){return oh.encode(zs(t))},decode(t){return JSON.parse(sh.decode(t))}};function Mp(){return ar}function mo(){let t=new Map;return{name:"memory",read(e){let n=t.get(e);return n===void 0?void 0:new Uint8Array(n)},write(e,n){t.set(e,new Uint8Array(n))},delete(e){t.delete(e)},list(e){let n=[...t.keys()];return e?n.filter(r=>r.startsWith(e)).sort():n.sort()}}}function Hs(t,e={}){let n=e.codec??ar,r=e.name??t.name??"snapshot",o=e.keyOf??(l=>l.name??e.name??t.name??"snapshot"),s,i=0,a=e.compactEvery,d,u={name:r,debounceMs:e.debounceMs,compactEvery:a,filter:e.filter,keyOf:o,save(l){if(!(e.filter&&!e.filter(l))&&(s={snapshot:l},i+=1,a!==void 0&&i%a===0||!e.debounceMs))return c()},load(){let l=d??r,p=t.read(l);if(p!==void 0)return p instanceof Uint8Array?p.length===0?void 0:n.decode(p):Promise.resolve(p).then(f=>f===void 0||f.length===0?void 0:n.decode(f))},async flush(){await c()},async rollback(){s=void 0}};function c(){let l=s;if(!l)return;s=void 0;let p=o(l.snapshot),f=n.encode(l.snapshot),m=t.write(p,f);if(m instanceof Promise)return m.then(()=>{d=p});d=p}return u}function ed(t,e={}){let n=e.codec??ar,r=e.name??t.name??"append-log",o=e.keyOf??(p=>r),s=e.compactEvery,i=new Map,a=0,d,u={name:r,debounceMs:e.debounceMs,compactEvery:s,keyOf:o,appendEntries(p){if(p.length!==0){for(let f of p){let m=o(f),h=i.get(m);h||(h=[],i.set(m,h)),h.push(f)}if(a+=p.length,s!==void 0&&a%s===0||!e.debounceMs)return c()}},async loadEntries(p){let f=p?.keyFilter,m=t.list===void 0?f!==void 0?[f]:[r]:await Promise.resolve(t.list(f)),h=[];for(let g of m){let y=await Promise.resolve(t.read(g));if(y===void 0||y.length===0)continue;let b=n.decode(y);Array.isArray(b)&&h.push(...b)}return{entries:h,cursor:void 0}},async flush(){await c()},async rollback(){i=new Map}};function c(){if(i.size===0)return;let p=i;i=new Map;let f=(d??Promise.resolve()).then(()=>{let m=l(p);return m instanceof Promise?m:Promise.resolve()},()=>{let m=l(p);return m instanceof Promise?m:Promise.resolve()});return d=f.finally(()=>{d===f&&(d=void 0)}),d}function l(p){let f=[];for(let[m,h]of p){let g=t.read(m),y=b=>{let T=[...b===void 0||b.length===0?[]:n.decode(b)??[],...h],w=n.encode(T);return t.write(m,w)};if(g instanceof Promise)f.push(g.then(async b=>{let v=y(b);v instanceof Promise&&await v}));else{let b=y(g);b instanceof Promise&&f.push(b)}}if(f.length>0)return Promise.all(f).then(()=>{})}return u}function Ws(t,e={}){let n=e.codec??ar,r=e.name??t.name??"kv",o=e.compactEvery,s=new Map,i=0,a={name:r,debounceMs:e.debounceMs,compactEvery:o,filter:e.filter,save(u,c){if(!(e.filter&&!e.filter(u,c))&&(s.set(u,c),i+=1,o!==void 0&&i%o===0||!e.debounceMs))return d()},load(u){let c=t.read(u);if(c!==void 0)return c instanceof Uint8Array?c.length===0?void 0:n.decode(c):Promise.resolve(c).then(l=>l===void 0||l.length===0?void 0:n.decode(l))},delete(u){if(s.delete(u),!!t.delete)return t.delete(u)},list(u){return t.list?t.list(u):[]},async flush(){await d()},async rollback(){s=new Map}};function d(){if(s.size===0)return;let u=s;s=new Map;let c=[];for(let[l,p]of u){let f=n.encode(p),m=t.write(l,f);m instanceof Promise&&c.push(m)}if(c.length>0)return Promise.all(c).then(()=>{})}return a}function Op(t){return Hs(mo(),t)}function Ap(t){return ed(mo(),t)}function go(t){return Ws(mo(),t)}function Cp(t,e){let n={name:e?.name??"dict-kv",read(r){return t[r]},write(r,o){t[r]=new Uint8Array(o)},delete(r){delete t[r]},list(r){let o=Object.keys(t).sort();return r?o.filter(s=>s.startsWith(r)):o}};return Ws(n,e)}function Lp(t,e){return Hs({name:"dict",read(r){return t[r]},write(r,o){t[r]=new Uint8Array(o)},delete(r){delete t[r]},list(r){let o=Object.keys(t).sort();return r?o.filter(s=>s.startsWith(r)):o}},e)}ae();Me();ne();function ho(t,e,n,r){let o=new Q(t,r);o.add(e,{name:"source"});let s=A(n,{meta:{kind:"stratify_rules"}});o.add(s,{name:"rules"});for(let i of n)ih(o,e,s,i);return o}function ih(t,e,n,r){let o=`branch/${r.name}`,s=Symbol("noValue"),i=!1,a=!1,d=!1,u=s,c=!1,l=n.cache??[];function p(h){if(d){d=!1;let g=u;if(u=s,g!==s){let y=l.find(v=>v.name===r.name),b=!1;try{b=y?.classify(g)??!1}catch{b=!1}b?(c=!1,h.emit(g)):c&&(c=!1,h.down([[oe],[q]]))}else c?(c=!1,h.down([[oe],[q]])):h.down([[q]])}}let f=U([],(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===oe?(g===0?(i=!0,c=!0):a=!0,!0):b===M||b===q?(g===0?(i=!1,d=!0,u=b===M?h[1]:s):(b===M&&(l=h[1]),a=!1),i||a||p(y),!0):b===P||b===I||b===le?(i=!1,a=!1,d=!1,u=s,c=!1,g===0&&y.down([h]),!0):g===1}if(t.add(f,{name:o}),r.ops){let h=r.ops(f),g=`branch/${r.name}/out`;t.add(h,{name:g})}}Rt();Ae();ae();Me();ne();ve();ae();var ah=new Map([[Qe,"INVALIDATE"],[Ve,"PAUSE"],[ze,"RESUME"],[le,"TEARDOWN"],[P,"COMPLETE"],[I,"ERROR"]]),dh=new Map([["INVALIDATE",Qe],["PAUSE",Ve],["RESUME",ze],["TEARDOWN",le],["COMPLETE",P],["ERROR",I]]);function Xt(t){let e=ah.get(t);return e||(Symbol.keyFor(t)??"UNKNOWN")}function vn(t){let e=dh.get(t);if(e)return e;if(t&&t!=="UNKNOWN")return Symbol.for(t)}function Tn(t){return t instanceof Error?{message:t.message,name:t.name,stack:t.stack}:{message:String(t),name:"Error"}}function wn(t){let e=new Error(t.message);return e.name=t.name,t.stack&&(e.stack=t.stack),e}function Zt(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 Zt(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 uh(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function td(t,e){let n=uh(t)?t:Zt(t),r=e.name??"workerBridge",o=Object.entries(e.expose??{}),s=e.import??[],i=e.transfer??{},a=A("connecting",{name:`${r}::meta::status`}),d=A(null,{name:`${r}::meta::error`}),u=new Map,c=new Map;for(let b of s){let v=A(void 0,{name:`${r}::${b}`});u.set(b,v)}let l;if(o.length>0){let b=o.map(([,w])=>w),v=U(b,(w,x)=>{let k={};for(let S=0;S<o.length;S++){let[R]=o[S],E=w[S];E!=null&&E.length>0&&(k[R]=E.at(-1))}Object.keys(k).length!==0&&x.emit(k)},{name:`${r}::aggregated`,partial:!0});l=ge([v],w=>{let x=w[0];if(x==null||Object.keys(x).length===0)return;let k=[];for(let E of Object.keys(x)){let _=i[E];_&&k.push(..._(x[E]))}let S;for(let[E,_]of o)E in x&&_.v!=null&&(S==null&&(S={}),S[E]=_.v.version);let R={t:"b",u:x,...S?{v:S}:{}};try{n.post(R,k.length>0?k:void 0)}catch(E){d.down([[M,E instanceof Error?E:new Error(String(E))]])}}).subscribe(()=>{})}let p=!1,f=n.listen(b=>{if(p)return;let v=b;switch(v.t){case"r":{Z(()=>{for(let[w,x]of Object.entries(v.stores)){let k=u.get(w);k&&k.down([[M,x]])}}),a.down([[M,"connected"]]);let T={};for(let[w,x]of o)T[w]=x.cache;n.post({t:"i",stores:T});break}case"v":{let T=u.get(v.s);T&&T.down([[M,v.d]]);break}case"b":{Z(()=>{for(let[T,w]of Object.entries(v.u)){let x=v.v?.[T];if(x!=null){let S=c.get(T);if(S!=null&&x<=S)continue;c.set(T,x)}let k=u.get(T);k&&k.down([[M,w]])}});break}case"e":{let T=u.get(v.s);T&&T.down([[I,wn(v.err)]]);break}case"s":{let T=vn(v.sig);if(!T)break;let w=v.s==="*"?[...u.values()]:u.has(v.s)?[u.get(v.s)]:[];for(let x of w)x.down(v.d===void 0?[[T]]:[[T,v.d]]);break}}}),m=[];for(let[b,v]of o){let T=v.subscribe((w=>{if(!p)for(let x of w){let k=x[0];k!==M&&(Fe.isLocalOnly(k)||(k===I?n.post({t:"e",s:b,err:Tn(x[1])}):n.post({t:"s",s:b,sig:Xt(k),d:x.length>1?x[1]:void 0})))}}));m.push(T)}let h;if(e.timeoutMs!=null&&e.timeoutMs>0){let b=Ze(e.timeoutMs),v=rt(a,w=>w==="connected");h=Fs(Et(eo(b,()=>"timeout"),eo(v,()=>"ready"))).subscribe(w=>{for(let x of w)x[0]===M&&x[1]==="timeout"&&(d.down([[M,new Error("Worker bridge handshake timeout")]]),g())})}function g(){if(!p){p=!0,h?.(),n.post({t:"s",s:"*",sig:Xt(le)}),l&&l();for(let b of m)b();m.length=0,f(),a.down([[M,"closed"]]),c.clear(),u.clear()}}let y={meta:{status:a,error:d},destroy:g};for(let[b,v]of u)y[b]=v;return y}Ae();ae();Me();ne();function ch(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function nd(t,e){let n=ch(t)?t:Zt(t),r=e.import??[],o=e.transfer??{},s=new Map,i=new Map,a={};for(let g of r){let y=A(void 0,{name:`worker::${g}`});s.set(g,y),a[g]=y}let d=e.expose(a),u=Object.entries(d),c,l=!1;if(u.length>0){let g=u.map(([,v])=>v),y=U(g,(v,T)=>{let w={};for(let x=0;x<u.length;x++){let[k]=u[x],S=v[x];S!=null&&S.length>0&&(w[k]=S.at(-1))}Object.keys(w).length!==0&&T.emit(w)},{name:"workerSelf::aggregated",partial:!0});c=ge([y],v=>{if(l)return;let T=v[0];if(T==null||Object.keys(T).length===0)return;let w=[];for(let S of Object.keys(T)){let R=o[S];R&&w.push(...R(T[S]))}let x;for(let[S,R]of u)S in T&&R.v!=null&&(x==null&&(x={}),x[S]=R.v.version);let k={t:"b",u:T,...x?{v:x}:{}};try{n.post(k,w.length>0?w:void 0)}catch{}}).subscribe(()=>{})}let p=[];for(let[g,y]of u){let b=y.subscribe((v=>{if(!l)for(let T of v){let w=T[0];w!==M&&(Fe.isLocalOnly(w)||(w===I?n.post({t:"e",s:g,err:Tn(T[1])}):n.post({t:"s",s:g,sig:Xt(w),d:T.length>1?T[1]:void 0})))}}));p.push(b)}let f=n.listen(g=>{if(l)return;let y=g;switch(y.t){case"i":{Z(()=>{for(let[b,v]of Object.entries(y.stores)){let T=s.get(b);T&&T.down([[M,v]])}});break}case"v":{let b=s.get(y.s);b&&b.down([[M,y.d]]);break}case"b":{Z(()=>{for(let[b,v]of Object.entries(y.u)){let T=y.v?.[b];if(T!=null){let x=i.get(b);if(x!=null&&T<=x)continue;i.set(b,T)}let w=s.get(b);w&&w.down([[M,v]])}});break}case"e":{let b=s.get(y.s);b&&b.down([[I,wn(y.err)]]);break}case"s":{let b=vn(y.sig);if(!b)break;if(b===le&&y.s==="*"){h();return}let v=y.s==="*"?[...s.values()]:s.has(y.s)?[s.get(y.s)]:[];for(let T of v)T.down(y.d===void 0?[[b]]:[[b,y.d]]);break}}}),m={};for(let[g,y]of u)m[g]=y.cache;n.post({t:"r",stores:m});function h(){if(!l){l=!0,c&&c();for(let g of p)g();p.length=0,f(),n.terminate?.(),i.clear(),s.clear()}}return{destroy:h}}var du={};Se(du,{SNAPSHOT_WIRE_VERSION:()=>Io,SurfaceError:()=>_e,accountability:()=>Si,ai:()=>ki,asSurfaceError:()=>Hi,cqrs:()=>Es,createGraph:()=>vr,deleteSnapshot:()=>Zi,demoShell:()=>Ei,diffSnapshots:()=>Qi,domainTemplates:()=>_i,graphspec:()=>wi,guarded:()=>Oi,harness:()=>ji,jobQueue:()=>Fi,layout:()=>qi,lens:()=>Vi,listSnapshots:()=>Xi,memory:()=>bi,messaging:()=>li,orchestration:()=>pi,process:()=>Ki,reduction:()=>Ti,refine:()=>Li,resilientPipeline:()=>zi,restoreSnapshot:()=>Yi,runReduction:()=>Wi,saveSnapshot:()=>Ji,surface:()=>ea});var ki={};Se(ki,{AgentLoopGraph:()=>gi,AllTiersExhaustedError:()=>vo,BudgetExhaustedError:()=>ni,ChatStreamGraph:()=>fi,CircuitOpenError:()=>yt,DEFAULT_DECAY_RATE:()=>Ad,FallbackMissError:()=>bh,LLMTimeoutError:()=>ur,ReplayCacheMissError:()=>Rn,ToolRegistryGraph:()=>mi,admissionFilter3D:()=>xy,admissionScored:()=>of,agentLoop:()=>Ty,agentMemory:()=>My,anthropicAdapter:()=>od,canonicalJson:()=>id,cascadingLlmAdapter:()=>vd,chatStream:()=>xd,composePricing:()=>Gh,computePrice:()=>pd,contentGate:()=>hy,costMeterExtractor:()=>cy,createAdapter:()=>Ch,createCapabilitiesRegistry:()=>lh,createPricingRegistry:()=>Ph,dryRunAdapter:()=>kn,fallbackAdapter:()=>ad,fromLLM:()=>Qh,frozenContext:()=>ty,gatedStream:()=>ay,gaugesAsContext:()=>Oy,googleAdapter:()=>dd,graphFromSpec:()=>wf,graphFromSpecReactive:()=>Vy,handoff:()=>wy,keywordFlagExtractor:()=>py,knobsAsTools:()=>qy,llmConsolidator:()=>Ed,llmExtractor:()=>Nd,memoryRetrieval:()=>Pd,memoryWithKG:()=>Ld,memoryWithTiers:()=>Id,memoryWithVectors:()=>Cd,observableAdapter:()=>Lh,openAICompatAdapter:()=>cd,parseRateLimitFromError:()=>hd,pricingFor:()=>Fh,promptNode:()=>Sn,redactor:()=>yy,registryPricing:()=>Dh,resilientAdapter:()=>Yh,streamExtractor:()=>fy,streamingPromptNode:()=>iy,suggestStrategy:()=>kf,suggestStrategyReactive:()=>Hy,systemPromptBuilder:()=>dy,tier:()=>Uh,toolCallExtractor:()=>gy,toolExecution:()=>Rd,toolRegistry:()=>Sd,toolSelector:()=>ky,validateGraphDef:()=>Wy,withBreaker:()=>fd,withBudgetGate:()=>gd,withDryRun:()=>jh,withRateLimiter:()=>bd,withReplayCache:()=>bo,withRetry:()=>Td,withTimeout:()=>wd,zeroPrice:()=>ti});ne();function yo(t,e){return`${t}::${e}`}function lh(t){let e=je({name:"capabilitiesRegistry"}),n=u=>{e.set(yo(u.provider,u.id),u)};if(t)for(let u of t)n(u);let r=(u,c)=>{let l=e.get(yo(u,c));if(l)return l;let p=e.entries.cache;if(!p)return;let f;for(let[,m]of p){if(m.provider!==u)continue;let h=m.id;c.startsWith(h)&&(!f||h.length>f.id.length)&&(f=m)}return f},o=128,s=new Map,i=new Map,a=(u,c,l,p)=>{for(u.has(c)&&u.delete(c),u.set(c,l);u.size>p;){let f=u.keys().next().value;if(f===void 0)break;u.delete(f)}},d=C([e.entries],([u])=>Array.from(u.values()),{name:"capabilitiesRegistry/entries",initial:[]});return{register:n,lookup:r,remove(u,c){let l=e.has(yo(u,c));return l&&e.delete(yo(u,c)),l},entries(){let u=e.entries.cache;return(function*(){if(u)for(let c of u.values())yield c})()},lookupNode(u,c){let l=yo(u,c),p=s.get(l);if(p)return s.delete(l),s.set(l,p),p;let f=C([e.entries],()=>r(u,c),{name:`capabilitiesRegistry/lookup/${u}::${c}`,initial:void 0});return a(s,l,f,o),f},entriesNode:d,byProvider(u){let c=i.get(u);if(c)return i.delete(u),i.set(u,c),c;let l=C([d],([p])=>p.filter(f=>f.provider===u),{name:`capabilitiesRegistry/byProvider/${u}`,initial:[]});return a(i,u,l,o),l}}}Re();function od(t={}){return t.sdk?hh(t):gh(t)}function Us(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}=ph(t,e?.systemPrompt),a={model:o,messages:i.map(fh),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(mh)),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 ph(t,e){let n=[];e&&n.push(e);let r=[];for(let o of t)o.role==="system"?n.push(o.content):r.push(o);return{system:n.length>0?n.join(`
|
|
33
33
|
|
|
34
|
-
`):void 0,chat:r}}function zg(t){if(t.role==="tool")return{role:"user",content:[{type:"tool_result",tool_use_id:t.toolCallId,content:t.content}]};if(t.role==="assistant"&&t.toolCalls&&t.toolCalls.length>0){let e=[];t.content&&e.push({type:"text",text:t.content});for(let n of t.toolCalls)e.push({type:"tool_use",id:n.id,name:n.name,input:n.arguments});return{role:"assistant",content:e}}return{role:t.role,content:t.content}}function Ug(t){return{name:t.name,description:t.description,input_schema:t.parameters}}function Vs(t,e){if(!t)return{...e};let n={...t};return e.input_tokens!=null&&(n.input_tokens=e.input_tokens),e.output_tokens!=null&&(n.output_tokens=e.output_tokens),e.cache_read_input_tokens!=null&&(n.cache_read_input_tokens=e.cache_read_input_tokens),e.cache_creation_input_tokens!=null&&(n.cache_creation_input_tokens=e.cache_creation_input_tokens),e.cache_creation&&(n.cache_creation={...t.cache_creation??{},...e.cache_creation}),e.server_tool_use&&(n.server_tool_use={...t.server_tool_use??{},...e.server_tool_use}),n}function Ua(t){let e={input:{regular:t?.input_tokens??0},output:{regular:t?.output_tokens??0},raw:t};return t?.cache_read_input_tokens&&(e.input.cacheRead=t.cache_read_input_tokens),t?.cache_creation?(t.cache_creation.ephemeral_5m_input_tokens&&(e.input.cacheWrite5m=t.cache_creation.ephemeral_5m_input_tokens),t.cache_creation.ephemeral_1h_input_tokens&&(e.input.cacheWrite1h=t.cache_creation.ephemeral_1h_input_tokens)):t?.cache_creation_input_tokens&&(e.input.cacheWrite5m=t.cache_creation_input_tokens),t?.server_tool_use?.web_search_requests&&(e.auxiliary={webSearchRequests:t.server_tool_use.web_search_requests}),e}function Tp(t,e){let n=[],r=[];for(let o of t.content)if(o.type==="text"&&typeof o.text=="string")n.push(o.text);else if(o.type==="tool_use"){let s=o;r.push({id:s.id,name:s.name,arguments:s.input??{}})}return{content:n.join(""),toolCalls:r.length>0?r:void 0,usage:Ua(t.usage),finishReason:t.stop_reason,latencyMs:e,model:t.model,provider:"anthropic"}}function Jg(t){let e=t.apiKey??globalThis.process?.env?.ANTHROPIC_API_KEY,n=t.baseURL??"https://api.anthropic.com",r=t.anthropicVersion??"2023-06-01",o=t.fetchImpl??fetch,s=()=>{if(!e)throw new Error("anthropicAdapter: apiKey required for invoke/stream (or provide opts.sdk)");return{"x-api-key":e,"anthropic-version":r,"content-type":"application/json",...t.headers??{}}};return{provider:"anthropic",model:t.model,async invoke(i,a){let u=Bs(i,a,t.model,!1),d=H(),c=await o(`${n}/v1/messages`,{method:"POST",headers:s(),body:JSON.stringify(u),signal:a?.signal});if(!c.ok)throw await ht(c,"Anthropic");let l=await c.json(),p=Math.max(0,(H()-d)/1e6);return Tp(l,p)},async*stream(i,a){let u=Bs(i,a,t.model,!0),d=await o(`${n}/v1/messages`,{method:"POST",headers:{...s(),accept:"text/event-stream"},body:JSON.stringify(u),signal:a?.signal});if(!d.ok)throw await ht(d,"Anthropic");if(!d.body)throw new Error("anthropicAdapter: streaming response has no body");let c,l,p=new Map;for await(let f of Dt(d.body,{signal:a?.signal})){let m=f.data;if(!m)continue;let h;try{h=JSON.parse(m)}catch{continue}switch(h.type){case"message_start":{c=Vs(c,h.message.usage);break}case"content_block_start":{let g=h,y=g.content_block;y.type==="tool_use"&&(p.set(g.index,{id:String(y.id??""),name:String(y.name??""),argBuf:""}),yield{type:"tool-call-delta",delta:{id:String(y.id??""),name:String(y.name??"")}});break}case"content_block_delta":{let g=h,y=g.delta;if(y.type==="text_delta"&&typeof y.text=="string")yield{type:"token",delta:y.text};else if(y.type==="input_json_delta"&&typeof y.partial_json=="string"){let b=p.get(g.index);b&&(b.argBuf+=y.partial_json),yield{type:"tool-call-delta",delta:{argumentsDelta:y.partial_json}}}else y.type==="thinking_delta"&&typeof y.thinking=="string"&&(yield{type:"thinking",delta:y.thinking});break}case"message_delta":{let g=h;g.delta.stop_reason&&(l=g.delta.stop_reason),g.delta.usage&&(c=Vs(c,g.delta.usage));break}case"message_stop":break}}c&&(yield{type:"usage",usage:Ua(c)}),yield{type:"finish",reason:l??"stop"}}}}function Yg(t){let e=t.sdk;if(!e)throw new Error("sdkBackedAnthropic: sdk instance required");return{provider:"anthropic",model:t.model,async invoke(n,r){let o=Bs(n,r,t.model,!1),s=H(),i=await e.messages.create(o,{signal:r?.signal}),a=Math.max(0,(H()-s)/1e6);return Tp(i,a)},async*stream(n,r){if(!e.messages.stream)throw new Error("sdkBackedAnthropic: SDK instance does not expose .messages.stream");let o=Bs(n,r,t.model,!0),s,i;for await(let a of e.messages.stream(o,{signal:r?.signal}))switch(a.type){case"message_start":s=Vs(s,a.message.usage);break;case"content_block_delta":{let u=a.delta;u?.type==="text_delta"&&typeof u.text=="string"?yield{type:"token",delta:u.text}:u?.type==="input_json_delta"&&typeof u.partial_json=="string"?yield{type:"tool-call-delta",delta:{argumentsDelta:u.partial_json}}:u?.type==="thinking_delta"&&typeof u.thinking=="string"&&(yield{type:"thinking",delta:u.thinking});break}case"message_delta":{let u=a;u.delta.stop_reason&&(i=u.delta.stop_reason),u.delta.usage&&(s=Vs(s,u.delta.usage));break}}s&&(yield{type:"usage",usage:Ua(s)}),yield{type:"finish",reason:i??"stop"}}}}vt();function Ks(){let t=new Error("aborted");return t.name="AbortError",t}function wp(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Ks()):new Promise((n,r)=>{let o=new Le,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(Ks())},e.addEventListener("abort",s,{once:!0}))})}function bn(t={}){let e=t.provider??"dry-run",n=t.model??"dry-run-v1",r=t.latencyMs??0,o=Math.max(1,t.streamChunkSize??16),s=t.respond??(a=>{let u=[...a].reverse().find(d=>d.role==="user");return u?`echo: ${u.content}`:"dry-run: no user message"}),i=t.usage??((a,u)=>{let d=a.reduce((c,l)=>c+l.content.length,0);return{input:{regular:Math.ceil(d/4)},output:{regular:Math.ceil(u.length/4)}}});return{provider:e,model:n,async invoke(a,u){if(await wp(r,u?.signal),u?.signal?.aborted)throw Ks();let d=s(a,u),c=i(a,d);return{content:d,usage:c,finishReason:"stop",model:u?.model??n,provider:e,tier:u?.tier,metadata:{dryRun:!0}}},async*stream(a,u){let d=s(a,u),c=i(a,d),l=Math.ceil(d.length/o)||1,p=r>0?r/l:0;for(let f=0;f<d.length;f+=o){if(u?.signal?.aborted)throw Ks();await wp(p,u?.signal),yield{type:"token",delta:d.slice(f,f+o)}}yield{type:"usage",usage:c},yield{type:"finish",reason:"stop"}}}}xe();xe();he();vt();function kp(t){let{storage:e,mode:n="read-write",keyFn:r,keyPrefix:o="llm-replay"}=t,i=Ps({storage:e,keyPrefix:o,mode:n==="read-strict"?"read":n,keyContext:({messages:u,opts:d})=>{let{signal:c,keyContext:l,...p}=d??{};return{messages:u,opts:p}}});async function a(u,d){if(r){if(r.length<=1){let l={messages:u,opts:d,context:d?.keyContext},p=await r(l);return`${o}:${p}`}let c=await r(u,d);return`${o}:${c}`}return i.keyFor({messages:u,opts:d})}return{keyFor:a,async lookup(u,d){if(n!=="write"){if(r){let c=await a(u,d),l=await e.load(c);return l===void 0?void 0:l}return i.lookup({messages:u,opts:d})}},async store(u,d,c){if(n!=="read"){if(r){let l=await a(u,d);await e.save(l,c);return}await i.store({messages:u,opts:d},c)}},async forget(u,d){if(!(n==="read"||n==="write")&&e.delete){if(r){let c=await a(u,d);await e.delete(c);return}await i.forget({messages:u,opts:d})}}}}xe();ae();ee();he();function et(t,e,n){return{provider:n?.provider??t.provider,model:n?.model??t.model,capabilities:n?.capabilities??t.capabilities?.bind(t),invoke:e.invoke,stream:e.stream}}function qs(t,e){let{onResp:n,onError:r,name:o}=e;if(t!=null&&typeof t.then=="function"){let d=t;return r?d.then(n).catch(c=>{throw r(c),c}):d.then(n)}if(t!=null&&typeof t=="object"&&"content"in t)return n(t);let s=U(t);if(r){let d=!1;s.subscribe(c=>{for(let l of c){if(d)return;l[0]===C&&(d=!0,r(l[1]))}})}let i,a=!1,u=Jr(s,d=>{i=n(d),a=!0});return A([u],([d])=>d==null?null:a?i:n(d),{name:o??"adapt/invokeTap"})}function vn(t){let e=t.endNs??H();return{timestamp:e,wallClock:t.startWallClockNs??oe(),provider:t.provider,model:t.model,tier:t.tier,usage:t.usage,latencyMs:Math.max(0,(e-t.startNs)/1e6),method:t.method,...t.error?{error:t.error}:{}}}function Rt(){return{input:{regular:0},output:{regular:0}}}var xp=Symbol.for("graphrefly.adapter.middlewareLayers");function Ue(t,e,n){let o=[...n?Qg(n):[],e];return Object.defineProperty(t,xp,{value:Object.freeze(o),enumerable:!1,writable:!1,configurable:!1}),t}function Qg(t){let e=t[xp];return Array.isArray(e)?e:[]}var Tn=class extends Error{constructor(n,r){super(`withReplayCache: no cached response for ${r} (key=${n}, mode=read-strict)`);this.key=n;this.method=r}name="ReplayCacheMissError"};function lo(t,e){let n=e.mode??"read-write",r=e.cacheStreaming??!1,o=e.captureStreamCadence??!1,s=e.replaySpeed??1,i=e.keyPrefix??"llm-replay",a=n==="read"||n==="read-strict",u=kp({storage:e.storage,mode:n==="write-only"?"write":n,keyFn:e.keyFn,keyPrefix:i}),d=p=>p<=0?Promise.resolve():new Promise(f=>{new Le().start(p,()=>f())}),c=Gs(async({messages:p,invokeOpts:f})=>await Ye(U(t.invoke(p,f))),{keyFn:({_precomputedKey:p})=>p}),l=et(t,{async invoke(p,f){let m=await u.keyFor(p,f),h=await u.lookup(p,f);if(h?.response){let y=h.response;return{...y,metadata:{...y.metadata??{},replayCache:"hit"}}}if(n==="read-strict")throw new Tn(m,"invoke");let g=await c({messages:p,invokeOpts:f,_precomputedKey:m});return a||await u.store(p,f,{response:g,storedAtNs:oe()}),g},async*stream(p,f){if(!r){for await(let x of t.stream(p,f))yield x;return}let m=await u.keyFor(p,f),h=await u.lookup(p,f);if(h){let x=h.response;if(h.streamChunks&&h.streamCadenceMs)for(let k=0;k<h.streamChunks.length;k++){let S=h.streamCadenceMs[k]??0,R=s>0?S/s:0;R>0&&await d(R),yield{type:"token",delta:h.streamChunks[k]?.delta??""}}else x.content&&(yield{type:"token",delta:x.content});x.usage&&(yield{type:"usage",usage:x.usage}),yield{type:"finish",reason:x.finishReason??"stop"};return}if(n==="read-strict")throw new Tn(m,"stream");let g="",y,b,v=[],T=[],w;for await(let x of t.stream(p,f)){if(x.type==="token"&&(g+=x.delta,o)){let k=H(),S=w===void 0?0:(k-w)/1e6;T.push(S),w=k,v.push({delta:x.delta})}x.type==="usage"&&(y=x.usage),x.type==="finish"&&(b=x.reason),yield x}if((g||y)&&!a){let k={response:{content:g,usage:y??{input:{regular:0},output:{regular:0}},finishReason:b,model:t.model??f?.model??"",provider:t.provider},storedAtNs:oe(),...o?{streamChunks:v,streamCadenceMs:T}:{}};await u.store(p,f,k)}}});return Ue(l,"withReplayCache",t),l}var Ja=to;var Xg=Tn;function Rp(t,e){return{content:"[fallback: no cached response available for this request]",usage:{input:{regular:0},output:{regular:0}},finishReason:"stop",model:e,provider:t,metadata:{degraded:!0,reason:"no-fixture"}}}function Sp(t,e,n){return typeof t=="string"?{content:t,usage:{input:{regular:0},output:{regular:0}},finishReason:"stop",model:n,provider:e,metadata:{degraded:!0,reason:"respond"}}:t}async function Zg(t,e){if("key"in t)return t.key;let n=Ja({messages:t.messages,opts:t.invokeOpts??{}}),r=await Is(n);return`${e}:${r}`}function eh(t){let e={response:t.response,storedAtNs:oe()};if("key"in t&&t.stream){let n=t.stream.chunks.filter(r=>r.type==="token");return{...e,streamChunks:n.map(r=>({delta:r.delta})),streamCadenceMs:t.stream.delaysMs??n.map(()=>0)}}return e}function th(t,e){let n=[];if(t.fixtures!=null&&n.push("fixtures"),t.fixturesStorage!=null&&n.push("fixturesStorage"),n.length>1)throw new TypeError(`fallbackAdapter: \`fixtures\` and \`fixturesStorage\` are mutually exclusive; got both ${n.join(" and ")}. Pick one source. For filesystem directories use the node subpath's \`fallbackAdapter\`.`);if(t.fixtures){let r=ao(),o=t.fixtures,s=(async()=>{for(let i of o){let a=await Zg(i,e);await r.save(a,eh(i))}})();return s.catch(()=>{}),{tier:r,seedReady:s}}return t.fixturesStorage?{tier:t.fixturesStorage,seedReady:Promise.resolve()}:{tier:void 0,seedReady:Promise.resolve()}}function Ya(t={}){let e=t.provider??"fallback",n=t.model??"fallback",r=t.onMiss??"respond",o=t.keyPrefix??"fallback",s=t.record?t.record.adapter:r==="throw"?bn({provider:e,model:n,respond:()=>"[unreachable: read-strict mode throws on miss]"}):{provider:e,model:n,async invoke(c,l){let p=t.respond?t.respond(c,l):Rp(e,n);return Sp(p,e,n)},async*stream(c,l){let p=t.respond?t.respond(c,l):Rp(e,n),f=Sp(p,e,n);yield{type:"token",delta:f.content},f.usage&&(yield{type:"usage",usage:f.usage}),yield{type:"finish",reason:f.finishReason??"stop"}}},i,a=Promise.resolve();if(t.record){if(!t.record.storage)throw new TypeError("fallbackAdapter: `record.storage` is required in record mode. For filesystem `record.dir` convenience, use the node subpath's `fallbackAdapter`.");i=t.record.storage}else{let c=th(t,o);i=c.tier??ao(),a=c.seedReady}let u=t.record?"read-write":r==="throw"?"read-strict":"read",d=lo(s,{storage:i,mode:u,keyPrefix:o,cacheStreaming:!0,captureStreamCadence:!0,replaySpeed:t.replaySpeed,...t.keyFn?{keyFn:t.keyFn}:{}});return{provider:e,model:n,capabilities:d.capabilities?.bind(d),async invoke(c,l){return await a,d.invoke(c,l)},async*stream(c,l){await a;for await(let p of d.stream(c,l))yield p}}}xe();function Qa(t={}){return t.sdk?sh(t):oh(t)}function Hs(t,e){let n=[],r=[];e?.systemPrompt&&n.push(e.systemPrompt);for(let i of t){if(i.role==="system"){n.push(i.content);continue}if(i.role==="tool"){r.push({role:"user",parts:[{functionResponse:{name:i.name??i.toolCallId??"tool",response:{result:i.content}}}]});continue}if(i.role==="assistant"&&i.toolCalls&&i.toolCalls.length>0){let a=[];i.content&&a.push({text:i.content});for(let u of i.toolCalls)a.push({functionCall:{name:u.name,args:u.arguments}});r.push({role:"model",parts:a});continue}r.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let o={contents:r};n.length>0&&(o.systemInstruction={role:"system",parts:[{text:n.join(`
|
|
34
|
+
`):void 0,chat:r}}function fh(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 mh(t){return{name:t.name,description:t.description,input_schema:t.parameters}}function Js(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 sd(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 Ip(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:sd(t.usage),finishReason:t.stop_reason,latencyMs:e,model:t.model,provider:"anthropic"}}function gh(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 d=Us(i,a,t.model,!1),u=V(),c=await o(`${n}/v1/messages`,{method:"POST",headers:s(),body:JSON.stringify(d),signal:a?.signal});if(!c.ok)throw await wt(c,"Anthropic");let l=await c.json(),p=Math.max(0,(V()-u)/1e6);return Ip(l,p)},async*stream(i,a){let d=Us(i,a,t.model,!0),u=await o(`${n}/v1/messages`,{method:"POST",headers:{...s(),accept:"text/event-stream"},body:JSON.stringify(d),signal:a?.signal});if(!u.ok)throw await wt(u,"Anthropic");if(!u.body)throw new Error("anthropicAdapter: streaming response has no body");let c,l,p=new Map;for await(let f of $t(u.body,{signal:a?.signal})){let m=f.data;if(!m)continue;let h;try{h=JSON.parse(m)}catch{continue}switch(h.type){case"message_start":{c=Js(c,h.message.usage);break}case"content_block_start":{let g=h,y=g.content_block;y.type==="tool_use"&&(p.set(g.index,{id:String(y.id??""),name:String(y.name??""),argBuf:""}),yield{type:"tool-call-delta",delta:{id:String(y.id??""),name:String(y.name??"")}});break}case"content_block_delta":{let g=h,y=g.delta;if(y.type==="text_delta"&&typeof y.text=="string")yield{type:"token",delta:y.text};else if(y.type==="input_json_delta"&&typeof y.partial_json=="string"){let b=p.get(g.index);b&&(b.argBuf+=y.partial_json),yield{type:"tool-call-delta",delta:{argumentsDelta:y.partial_json}}}else y.type==="thinking_delta"&&typeof y.thinking=="string"&&(yield{type:"thinking",delta:y.thinking});break}case"message_delta":{let g=h;g.delta.stop_reason&&(l=g.delta.stop_reason),g.delta.usage&&(c=Js(c,g.delta.usage));break}case"message_stop":break}}c&&(yield{type:"usage",usage:sd(c)}),yield{type:"finish",reason:l??"stop"}}}}function hh(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=Us(n,r,t.model,!1),s=V(),i=await e.messages.create(o,{signal:r?.signal}),a=Math.max(0,(V()-s)/1e6);return Ip(i,a)},async*stream(n,r){if(!e.messages.stream)throw new Error("sdkBackedAnthropic: SDK instance does not expose .messages.stream");let o=Us(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=Js(s,a.message.usage);break;case"content_block_delta":{let d=a.delta;d?.type==="text_delta"&&typeof d.text=="string"?yield{type:"token",delta:d.text}:d?.type==="input_json_delta"&&typeof d.partial_json=="string"?yield{type:"tool-call-delta",delta:{argumentsDelta:d.partial_json}}:d?.type==="thinking_delta"&&typeof d.thinking=="string"&&(yield{type:"thinking",delta:d.thinking});break}case"message_delta":{let d=a;d.delta.stop_reason&&(i=d.delta.stop_reason),d.delta.usage&&(s=Js(s,d.delta.usage));break}}s&&(yield{type:"usage",usage:sd(s)}),yield{type:"finish",reason:i??"stop"}}}}Rt();function Ys(){let t=new Error("aborted");return t.name="AbortError",t}function Pp(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Ys()):new Promise((n,r)=>{let o=new Ie,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(Ys())},e.addEventListener("abort",s,{once:!0}))})}function kn(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 d=[...a].reverse().find(u=>u.role==="user");return d?`echo: ${d.content}`:"dry-run: no user message"}),i=t.usage??((a,d)=>{let u=a.reduce((c,l)=>c+l.content.length,0);return{input:{regular:Math.ceil(u/4)},output:{regular:Math.ceil(d.length/4)}}});return{provider:e,model:n,async invoke(a,d){if(await Pp(r,d?.signal),d?.signal?.aborted)throw Ys();let u=s(a,d),c=i(a,u);return{content:u,usage:c,finishReason:"stop",model:d?.model??n,provider:e,tier:d?.tier,metadata:{dryRun:!0}}},async*stream(a,d){let u=s(a,d),c=i(a,u),l=Math.ceil(u.length/o)||1,p=r>0?r/l:0;for(let f=0;f<u.length;f+=o){if(d?.signal?.aborted)throw Ys();await Pp(p,d?.signal),yield{type:"token",delta:u.slice(f,f+o)}}yield{type:"usage",usage:c},yield{type:"finish",reason:"stop"}}}}Re();Re();ve();Rt();function Dp(t){let{storage:e,mode:n="read-write",keyFn:r,keyPrefix:o="llm-replay"}=t,i=Vs({storage:e,keyPrefix:o,mode:n==="read-strict"?"read":n,keyContext:({messages:d,opts:u})=>{let{signal:c,keyContext:l,...p}=u??{};return{messages:d,opts:p}}});async function a(d,u){if(r){if(r.length<=1){let l={messages:d,opts:u,context:u?.keyContext},p=await r(l);return`${o}:${p}`}let c=await r(d,u);return`${o}:${c}`}return i.keyFor({messages:d,opts:u})}return{keyFor:a,async lookup(d,u){if(n!=="write"){if(r){let c=await a(d,u),l=await e.load(c);return l===void 0?void 0:l}return i.lookup({messages:d,opts:u})}},async store(d,u,c){if(n!=="read"){if(r){let l=await a(d,u);await e.save(l,c);return}await i.store({messages:d,opts:u},c)}},async forget(d,u){if(!(n==="read"||n==="write")&&e.delete){if(r){let c=await a(d,u);await e.delete(c);return}await i.forget({messages:d,opts:u})}}}}Re();ae();ne();ve();function ot(t,e,n){return{provider:n?.provider??t.provider,model:n?.model??t.model,capabilities:n?.capabilities??t.capabilities?.bind(t),invoke:e.invoke,stream:e.stream}}function Qs(t,e){let{onResp:n,onError:r,name:o}=e;if(t!=null&&typeof t.then=="function"){let u=t;return r?u.then(n).catch(c=>{throw r(c),c}):u.then(n)}if(t!=null&&typeof t=="object"&&"content"in t)return n(t);let s=Y(t);if(r){let u=!1;s.subscribe(c=>{for(let l of c){if(u)return;l[0]===I&&(u=!0,r(l[1]))}})}let i,a=!1,d=no(s,u=>{i=n(u),a=!0});return C([d],([u])=>u==null?null:a?i:n(u),{name:o??"adapt/invokeTap"})}function xn(t){let e=t.endNs??V();return{timestamp:e,wallClock:t.startWallClockNs??se(),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 _t(){return{input:{regular:0},output:{regular:0}}}var Gp=Symbol.for("graphrefly.adapter.middlewareLayers");function Je(t,e,n){let o=[...n?yh(n):[],e];return Object.defineProperty(t,Gp,{value:Object.freeze(o),enumerable:!1,writable:!1,configurable:!1}),t}function yh(t){let e=t[Gp];return Array.isArray(e)?e:[]}var Rn=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 bo(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",d=Dp({storage:e.storage,mode:n==="write-only"?"write":n,keyFn:e.keyFn,keyPrefix:i}),u=p=>p<=0?Promise.resolve():new Promise(f=>{new Ie().start(p,()=>f())}),c=qs(async({messages:p,invokeOpts:f})=>await et(Y(t.invoke(p,f))),{keyFn:({_precomputedKey:p})=>p}),l=ot(t,{async invoke(p,f){let m=await d.keyFor(p,f),h=await d.lookup(p,f);if(h?.response){let y=h.response;return{...y,metadata:{...y.metadata??{},replayCache:"hit"}}}if(n==="read-strict")throw new Rn(m,"invoke");let g=await c({messages:p,invokeOpts:f,_precomputedKey:m});return a||await d.store(p,f,{response:g,storedAtNs:se()}),g},async*stream(p,f){if(!r){for await(let x of t.stream(p,f))yield x;return}let m=await d.keyFor(p,f),h=await d.lookup(p,f);if(h){let x=h.response;if(h.streamChunks&&h.streamCadenceMs)for(let k=0;k<h.streamChunks.length;k++){let S=h.streamCadenceMs[k]??0,R=s>0?S/s:0;R>0&&await u(R),yield{type:"token",delta:h.streamChunks[k]?.delta??""}}else x.content&&(yield{type:"token",delta:x.content});x.usage&&(yield{type:"usage",usage:x.usage}),yield{type:"finish",reason:x.finishReason??"stop"};return}if(n==="read-strict")throw new Rn(m,"stream");let g="",y,b,v=[],T=[],w;for await(let x of t.stream(p,f)){if(x.type==="token"&&(g+=x.delta,o)){let k=V(),S=w===void 0?0:(k-w)/1e6;T.push(S),w=k,v.push({delta:x.delta})}x.type==="usage"&&(y=x.usage),x.type==="finish"&&(b=x.reason),yield x}if((g||y)&&!a){let k={response:{content:g,usage:y??{input:{regular:0},output:{regular:0}},finishReason:b,model:t.model??f?.model??"",provider:t.provider},storedAtNs:se(),...o?{streamChunks:v,streamCadenceMs:T}:{}};await d.store(p,f,k)}}});return Je(l,"withReplayCache",t),l}var id=uo;var bh=Rn;function Fp(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 $p(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 vh(t,e){if("key"in t)return t.key;let n=id({messages:t.messages,opts:t.invokeOpts??{}}),r=await Bs(n);return`${e}:${r}`}function Th(t){let e={response:t.response,storedAtNs:se()};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 wh(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=go(),o=t.fixtures,s=(async()=>{for(let i of o){let a=await vh(i,e);await r.save(a,Th(i))}})();return s.catch(()=>{}),{tier:r,seedReady:s}}return t.fixturesStorage?{tier:t.fixturesStorage,seedReady:Promise.resolve()}:{tier:void 0,seedReady:Promise.resolve()}}function ad(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"?kn({provider:e,model:n,respond:()=>"[unreachable: read-strict mode throws on miss]"}):{provider:e,model:n,async invoke(c,l){let p=t.respond?t.respond(c,l):Fp(e,n);return $p(p,e,n)},async*stream(c,l){let p=t.respond?t.respond(c,l):Fp(e,n),f=$p(p,e,n);yield{type:"token",delta:f.content},f.usage&&(yield{type:"usage",usage:f.usage}),yield{type:"finish",reason:f.finishReason??"stop"}}},i,a=Promise.resolve();if(t.record){if(!t.record.storage)throw new TypeError("fallbackAdapter: `record.storage` is required in record mode. For filesystem `record.dir` convenience, use the node subpath's `fallbackAdapter`.");i=t.record.storage}else{let c=wh(t,o);i=c.tier??go(),a=c.seedReady}let d=t.record?"read-write":r==="throw"?"read-strict":"read",u=bo(s,{storage:i,mode:d,keyPrefix:o,cacheStreaming:!0,captureStreamCadence:!0,replaySpeed:t.replaySpeed,...t.keyFn?{keyFn:t.keyFn}:{}});return{provider:e,model:n,capabilities:u.capabilities?.bind(u),async invoke(c,l){return await a,u.invoke(c,l)},async*stream(c,l){await a;for await(let p of u.stream(c,l))yield p}}}Re();function dd(t={}){return t.sdk?Sh(t):Rh(t)}function Xs(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 d of i.toolCalls)a.push({functionCall:{name:d.name,args:d.arguments}});r.push({role:"model",parts:a});continue}r.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let o={contents:r};n.length>0&&(o.systemInstruction={role:"system",parts:[{text:n.join(`
|
|
35
35
|
|
|
36
|
-
`)}]});let s={};return e?.maxTokens!=null&&(s.maxOutputTokens=e.maxTokens),e?.temperature!=null&&(s.temperature=e.temperature),e?.maxReasoningTokens!=null&&(s.thinkingConfig={thinkingBudget:e.maxReasoningTokens}),Object.keys(s).length>0&&(o.generationConfig=s),e?.tools&&e.tools.length>0&&(o.tools=[{functionDeclarations:e.tools.map(nh)}]),e?.providerExtras&&Object.assign(o,e.providerExtras),o}function nh(t){return{name:t.name,description:t.description,parameters:t.parameters}}function Ep(t,e,n){let r={},o=t.generationConfig;o&&(typeof o.maxOutputTokens=="number"&&(r.maxOutputTokens=o.maxOutputTokens),typeof o.temperature=="number"&&(r.temperature=o.temperature),o.thinkingConfig&&(r.thinkingConfig=o.thinkingConfig)),t.systemInstruction&&(r.systemInstruction=t.systemInstruction),t.tools&&(r.tools=t.tools);for(let[s,i]of Object.entries(t))s==="contents"||s==="generationConfig"||s==="systemInstruction"||s==="tools"||s==="abortSignal"||s==="model"||(r[s]=i);return n&&(r.abortSignal=n),{model:e,contents:t.contents,config:Object.keys(r).length>0?r:void 0}}function Xa(t){let e={input:{regular:0},output:{regular:0},raw:t};if(!t)return e;let n=t.promptTokenCount??0,r=t.cachedContentTokenCount??0;if(e.input.regular=Math.max(0,n-r),r>0&&(e.input.cacheRead=r),t.toolUsePromptTokenCount&&(e.input.toolUse=t.toolUsePromptTokenCount),t.promptTokensDetails)for(let o of t.promptTokensDetails){let s=o.modality?.toLowerCase();s==="image"?e.input.image=(e.input.image??0)+o.tokenCount:s==="audio"?e.input.audio=(e.input.audio??0)+o.tokenCount:s==="video"&&(e.input.video=(e.input.video??0)+o.tokenCount)}return e.output.regular=t.candidatesTokenCount??0,t.thoughtsTokenCount&&(e.output.reasoning=t.thoughtsTokenCount),e}function Np(t,e){let n=t.candidates?.[0],r=n?.content?.parts??[],o=[],s=[],i=0;for(let a of r)typeof a.text=="string"&&o.push(a.text),a.functionCall&&s.push({id:`${a.functionCall.name}-${i++}`,name:a.functionCall.name,arguments:a.functionCall.args??{}});return{content:o.join(""),toolCalls:s.length>0?s:void 0,usage:Xa(t.usageMetadata),finishReason:n?.finishReason,latencyMs:e,model:t.modelVersion,provider:"google"}}function rh(t){if(t.apiKey)return t.apiKey;let e=globalThis.process?.env;return e?.GOOGLE_API_KEY??e?.GEMINI_API_KEY}function oh(t){let e=t.baseURL??"https://generativelanguage.googleapis.com/v1beta",n=t.fetchImpl??fetch,r=s=>{let i=s?.model??t.model;if(!i)throw new Error("googleAdapter: model must be set via options.model or invokeOpts.model");return i},o=()=>{let s=rh(t);if(!s)throw new Error("googleAdapter: apiKey required for invoke/stream");return`key=${encodeURIComponent(s)}`};return{provider:"google",model:t.model,async invoke(s,i){let a=r(i),u=Hs(s,i),d=H(),c=`${e}/models/${encodeURIComponent(a)}:generateContent?${o()}`,l=await n(c,{method:"POST",headers:{"content-type":"application/json",...t.headers??{}},body:JSON.stringify(u),signal:i?.signal});if(!l.ok)throw await ht(l,"Google");let p=await l.json(),f=Math.max(0,(H()-d)/1e6);return Np(p,f)},async*stream(s,i){let a=r(i),u=Hs(s,i),d=`${e}/models/${encodeURIComponent(a)}:streamGenerateContent?alt=sse&${o()}`,c=await n(d,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",...t.headers??{}},body:JSON.stringify(u),signal:i?.signal});if(!c.ok)throw await ht(c,"Google");if(!c.body)throw new Error("googleAdapter: streaming response has no body");let l,p;for await(let f of Dt(c.body,{signal:i?.signal})){if(!f.data)continue;let m;try{m=JSON.parse(f.data)}catch{continue}let h=m.candidates?.[0];for(let g of h?.content?.parts??[])typeof g.text=="string"&&(g.thought?yield{type:"thinking",delta:g.text}:yield{type:"token",delta:g.text}),g.functionCall&&(yield{type:"tool-call-delta",delta:{name:g.functionCall.name,argumentsDelta:JSON.stringify(g.functionCall.args??{})}});h?.finishReason&&(p=h.finishReason),m.usageMetadata&&(l=m.usageMetadata)}l&&(yield{type:"usage",usage:Xa(l)}),yield{type:"finish",reason:p??"stop"}}}}function sh(t){let e=t.sdk;if(!e)throw new Error("sdkBackedGoogle: sdk instance required");return{provider:"google",model:t.model,async invoke(n,r){let o=Hs(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=Ep(o,s,r?.signal),a=H(),u=await e.models.generateContent(i),d=Math.max(0,(H()-a)/1e6);return Np(u,d)},async*stream(n,r){if(!e.models.generateContentStream)throw new Error("sdkBackedGoogle: SDK instance does not expose generateContentStream");let o=Hs(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=Ep(o,s,r?.signal),a,u,d=await e.models.generateContentStream(i);for await(let c of d){let l=c.candidates?.[0];for(let p of l?.content?.parts??[])typeof p.text=="string"&&(p.thought?yield{type:"thinking",delta:p.text}:yield{type:"token",delta:p.text}),p.functionCall&&(yield{type:"tool-call-delta",delta:{name:p.functionCall.name,argumentsDelta:JSON.stringify(p.functionCall.args??{})}});l?.finishReason&&(u=l.finishReason),c.usageMetadata&&(a=c.usageMetadata)}a&&(yield{type:"usage",usage:Xa(a)}),yield{type:"finish",reason:u??"stop"}}}}xe();var ih={openai:{baseURL:"https://api.openai.com/v1",apiKeyEnv:"OPENAI_API_KEY",provider:"openai"},openrouter:{baseURL:"https://openrouter.ai/api/v1",apiKeyEnv:"OPENROUTER_API_KEY",provider:"openrouter"},groq:{baseURL:"https://api.groq.com/openai/v1",apiKeyEnv:"GROQ_API_KEY",provider:"groq"},ollama:{baseURL:"http://localhost:11434/v1",provider:"ollama"},deepseek:{baseURL:"https://api.deepseek.com/v1",apiKeyEnv:"DEEPSEEK_API_KEY",provider:"deepseek"},xai:{baseURL:"https://api.x.ai/v1",apiKeyEnv:"XAI_API_KEY",provider:"xai"}};function Za(t={}){return t.sdk?lh(t):ch(t)}function Ws(t,e,n,r,o){let s=e?.model??n;if(!s)throw new Error("openAICompatAdapter: model must be set via options.model or invokeOpts.model");let i=t.map(ah);e?.systemPrompt&&!t.some(u=>u.role==="system")&&i.unshift({role:"system",content:e.systemPrompt});let a={model:s,messages:i};return e?.maxTokens!=null&&(a.max_tokens=e.maxTokens),e?.temperature!=null&&(a.temperature=e.temperature),e?.tools&&e.tools.length>0&&(a.tools=e.tools.map(uh)),e?.maxReasoningTokens!=null&&(a.reasoning={max_tokens:e.maxReasoningTokens}),r&&(a.stream=!0,a.stream_options={include_usage:!0}),o&&Object.assign(a,o),e?.providerExtras&&Object.assign(a,e.providerExtras),a}function ah(t){return t.role==="tool"?{role:"tool",tool_call_id:t.toolCallId,content:t.content}:t.role==="assistant"&&t.toolCalls&&t.toolCalls.length>0?{role:"assistant",content:t.content||null,tool_calls:t.toolCalls.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.arguments)}}))}:{role:t.role,content:t.content}}function uh(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}}function eu(t){let e={input:{regular:0},output:{regular:0},raw:t};if(!t)return e;let n=t.prompt_tokens??0,r=t.prompt_tokens_details?.cached_tokens??0;t.prompt_cache_hit_tokens!=null?(r=t.prompt_cache_hit_tokens,e.input.regular=t.prompt_cache_miss_tokens??Math.max(0,n-r)):e.input.regular=Math.max(0,n-r),r>0&&(e.input.cacheRead=r),t.prompt_tokens_details?.audio_tokens&&(e.input.audio=t.prompt_tokens_details.audio_tokens);let o=t.completion_tokens??0,s=t.completion_tokens_details?.reasoning_tokens??0;return e.output.regular=Math.max(0,o-s),s>0&&(e.output.reasoning=s),t.completion_tokens_details?.audio_tokens&&(e.output.audio=t.completion_tokens_details.audio_tokens),t.completion_tokens_details?.accepted_prediction_tokens&&(e.output.predictionAccepted=t.completion_tokens_details.accepted_prediction_tokens),t.completion_tokens_details?.rejected_prediction_tokens&&(e.output.predictionRejected=t.completion_tokens_details.rejected_prediction_tokens),e}function _p(t,e,n){let r=t.choices[0],o=r?.message,s=o?.content??"",i=(o?.tool_calls??[]).map(a=>({id:a.id,name:a.function.name,arguments:dh(a.function.arguments)}));return{content:s,toolCalls:i.length>0?i:void 0,usage:eu(t.usage),finishReason:r?.finish_reason,latencyMs:e,model:t.model,provider:n}}function dh(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!=null?e:{_raw:t}}catch{return{_raw:t}}}function Mp(t){let e=t.preset??"openai",n=ih[e],r=t.baseURL??n.baseURL,o=t.provider??n.provider,s=n.apiKeyEnv,i=t.apiKey??(s?globalThis.process?.env?.[s]:void 0);return{provider:o,baseURL:r,apiKey:i}}function ch(t){let{provider:e,baseURL:n,apiKey:r}=Mp(t),o=t.fetchImpl??fetch,s=e!=="ollama",i=()=>{let a={"content-type":"application/json",...t.headers??{}};if(s){if(!r)throw new Error(`openAICompatAdapter[${e}]: apiKey required for invoke/stream`);a.authorization=`Bearer ${r}`}return a};return{provider:e,model:t.model,async invoke(a,u){let d=Ws(a,u,t.model,!1,t.bodyExtras),c=H(),l=await o(`${n}/chat/completions`,{method:"POST",headers:i(),body:JSON.stringify(d),signal:u?.signal});if(!l.ok)throw await ht(l,e);let p=await l.json(),f=Math.max(0,(H()-c)/1e6);return _p(p,f,e)},async*stream(a,u){let d=Ws(a,u,t.model,!0,t.bodyExtras),c=await o(`${n}/chat/completions`,{method:"POST",headers:{...i(),accept:"text/event-stream"},body:JSON.stringify(d),signal:u?.signal});if(!c.ok)throw await ht(c,e);if(!c.body)throw new Error(`openAICompatAdapter[${e}]: streaming response has no body`);let l,p;for await(let f of Dt(c.body,{signal:u?.signal})){if(!f.data||f.data==="[DONE]")continue;let m;try{m=JSON.parse(f.data)}catch{continue}let h=m.choices;if(h){let g=h[0];if(g?.delta?.content&&(yield{type:"token",delta:g.delta.content}),g?.delta?.reasoning_content&&(yield{type:"thinking",delta:g.delta.reasoning_content}),g?.delta?.tool_calls)for(let y of g.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:y.id,name:y.function?.name,argumentsDelta:y.function?.arguments}};g?.finish_reason&&(p=g.finish_reason)}m.usage&&(l=m.usage,yield{type:"usage",usage:eu(l)})}yield{type:"finish",reason:p??"stop"}}}}function lh(t){let e=t.sdk;if(!e)throw new Error("sdkBackedOpenAI: sdk instance required");let{provider:n}=Mp(t);return{provider:n,model:t.model,async invoke(r,o){let s=Ws(r,o,t.model,!1,t.bodyExtras),i=H(),a=await e.chat.completions.create(s,{signal:o?.signal}),u=Math.max(0,(H()-i)/1e6);return _p(a,u,n)},async*stream(r,o){let s=Ws(r,o,t.model,!0,t.bodyExtras),i=await e.chat.completions.create(s,{signal:o?.signal}),a,u;for await(let d of i){let c=d.choices;if(c){let p=c[0];if(p?.delta?.content&&(yield{type:"token",delta:p.delta.content}),p?.delta?.reasoning_content&&(yield{type:"thinking",delta:p.delta.reasoning_content}),p?.delta?.tool_calls)for(let f of p.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:f.id,name:f.function?.name,argumentsDelta:f.function?.arguments}};p?.finish_reason&&(u=p.finish_reason)}let l=d.usage;l&&(a=l,yield{type:"usage",usage:eu(l)})}yield{type:"finish",reason:u??"stop"}}}}function ph(t){switch(t.provider){case"anthropic":{let e={apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return za(e)}case"google":{let e={apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return Qa(e)}case"dry-run":{let e={model:t.model,...t.extras};return bn(e)}case"fallback":{let e={provider:t.provider,model:t.model,...t.extras};return Ya(e)}case"openai":case"openrouter":case"groq":case"ollama":case"deepseek":case"xai":{let e={preset:t.provider,apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,bodyExtras:t.bodyExtras,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return Za(e)}default:{let e=t.provider;throw new Error(`createAdapter: unknown provider: ${String(e)}`)}}}xe();ee();he();function yt(t){let e=t.input,n=e.regular+(e.cacheRead??0)+(e.cacheWrite5m??0)+(e.cacheWrite1h??0)+(e.cacheWriteOther??0)+(e.audio??0)+(e.image??0)+(e.video??0)+(e.toolUse??0);if(!e.extensions)return n;let r=0;for(let o of Object.values(e.extensions))r+=o;return n+r}function Gt(t){let e=t.output,n=e.regular+(e.reasoning??0)+(e.audio??0)+(e.predictionAccepted??0)+(e.predictionRejected??0);if(!e.extensions)return n;let r=0;for(let o of Object.values(e.extensions))r+=o;return n+r}function Op(){return{input:{regular:0},output:{regular:0}}}function fh(t,e){let n=e?.logMax??1e3,r=Ve(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:n}),o=M(null,{name:"adapterStats/lastCall"}),s=A([r.entries],([h])=>h.length,{name:"adapterStats/totalCalls",initial:0}),i=A([r.entries],([h])=>h.reduce((g,y)=>g+yt(y.usage),0),{name:"adapterStats/totalInputTokens",initial:0}),a=A([r.entries],([h])=>h.reduce((g,y)=>g+Gt(y.usage),0),{name:"adapterStats/totalOutputTokens",initial:0}),u=[re(s),re(i),re(a)],d=h=>{r.append(h),o.emit(h)},c=()=>{r.clear(),o.emit(null)},l=et(t,{invoke(h,g){let y=H(),b=oe(),v=t.model??g?.model??"",T=x=>(d(vn({provider:t.provider,model:t.model??g?.model??x.model??"",tier:g?.tier??x.tier,usage:x.usage??Rt(),startNs:y,startWallClockNs:b,method:"invoke"})),x),w=x=>{let k=x;d(vn({provider:t.provider,model:v,tier:g?.tier,usage:Rt(),startNs:y,startWallClockNs:b,method:"invoke",error:{type:k?.name??"Error",message:k?.message??String(x)}}))};return qs(t.invoke(h,g),{onResp:T,onError:w,name:"adapterStats/invokeTap"})},async*stream(h,g){let y=H(),b=oe(),v=t.model??g?.model??"",T;try{for await(let w of t.stream(h,g))w.type==="usage"&&(T=w.usage),yield w;d(vn({provider:t.provider,model:v,tier:g?.tier,usage:T??Rt(),startNs:y,startWallClockNs:b,method:"stream"}))}catch(w){let x=w;throw d(vn({provider:t.provider,model:v,tier:g?.tier,usage:T??Rt(),startNs:y,startWallClockNs:b,method:"stream",error:{type:x?.name??"Error",message:x?.message??String(w)}})),w}}});Ue(l,"observableAdapter",t);let p=!1;return{adapter:l,stats:{lastCall:o,allCalls:r,totalCalls:s,totalInputTokens:i,totalOutputTokens:a,reset:c,dispose:()=>{if(!p){p=!0;for(let h of u)h();u.length=0}}}}}function mh(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function Us(t="USD"){return{total:0,currency:t}}function tu(t,e,n){let r=yt(t),o=e.currency??"USD",s=n?.withBreakdown===!0,i=s?{}:null,a=0,u=(g,y,b)=>{if(!y||b==null)return;let v=mh(b,r),T=y*v/1e6;a+=T,s&&(i[g]=(i[g]??0)+T)},d=t.input,c=e.input;if(c&&(u("input.regular",d.regular,c.regular),u("input.cacheRead",d.cacheRead??0,c.cacheRead),u("input.cacheWrite5m",d.cacheWrite5m??0,c.cacheWrite5m),u("input.cacheWrite1h",d.cacheWrite1h??0,c.cacheWrite1h),u("input.cacheWriteOther",d.cacheWriteOther??0,c.cacheWriteOther),u("input.audio",d.audio??0,c.audio),u("input.image",d.image??0,c.image),u("input.video",d.video??0,c.video),u("input.toolUse",d.toolUse??0,c.toolUse),d.extensions&&c.extensions))for(let[g,y]of Object.entries(d.extensions))u(`input.ext.${g}`,y,c.extensions[g]);let l=t.output,p=e.output;if(p&&(u("output.regular",l.regular,p.regular),u("output.reasoning",l.reasoning??0,p.reasoning),u("output.audio",l.audio??0,p.audio),u("output.predictionAccepted",l.predictionAccepted??0,p.predictionAccepted),u("output.predictionRejected",l.predictionRejected??0,p.predictionRejected),l.extensions&&p.extensions))for(let[g,y]of Object.entries(l.extensions))u(`output.ext.${g}`,y,p.extensions[g]);let f=n?.tier;if(f&&e.tierMultipliers){let g=e.tierMultipliers[f];if(g!=null&&(a*=g,s))for(let y of Object.keys(i))i[y]*=g}let m=t.auxiliary,h=e.auxiliary;if(m&&h)for(let[g,y]of Object.entries(m)){let b=h[g];if(b==null||!y)continue;let v=y*b;a+=v,s&&(i[`auxiliary.${g}`]=v)}return s?{total:a,currency:o,breakdown:i}:{total:a,currency:o}}function zs(t,e){return`${t}::${e}`}function gh(t){let e=new Map,n=new Map,r=(o,s,i)=>{e.set(zs(o,s),{provider:o,model:s,pricing:i});let a=n.get(o);a||(a=new Set,n.set(o,a)),a.add(s)};if(t)for(let[o,s,i]of t)r(o,s,i);return{register:r,lookup(o,s){let i=e.get(zs(o,s));if(i)return i.pricing;let a=n.get(o);if(!a)return;let u;for(let d of a)if(s.startsWith(d)&&(!u||d.length>u.key.length)){let c=e.get(zs(o,d));c&&(u={key:d,pricing:c.pricing})}return u?.pricing},remove(o,s){let i=e.delete(zs(o,s));if(i){let a=n.get(o);a?.delete(s),a&&a.size===0&&n.delete(o)}return i},entries(){let o=e.values();return(function*(){for(let{provider:s,model:i,pricing:a}of o)yield[s,i,a]})()}}}function hh(t,e="USD"){return(n,r)=>{let o=t.lookup(r.provider,r.model);return o?tu(n,o,{tier:r.tier,withBreakdown:r.withBreakdown}):Us(e)}}function yh(...t){return(e,n)=>{for(let r of t){let o=r(e,n);if(o.total!==0)return o}return t.length>0?t[0](e,n):Us()}}function bh(t,e,n){return t?.pricing?tu(e,t.pricing,n):Us()}Ot();he();function nu(t,e={}){let n=e.breaker??wt(e),r=et(t,{async invoke(o,s){if(!n.canExecute())throw new pt;try{let i=await Ye(U(t.invoke(o,s)));return n.recordSuccess(),i}catch(i){throw n.recordFailure(i),i}},async*stream(o,s){if(!n.canExecute())throw new pt;try{for await(let i of t.stream(o,s))yield i;n.recordSuccess()}catch(i){throw n.recordFailure(i),i}}});return Ue(r,"withBreaker",t),{adapter:r,breaker:n}}xe();ae();ee();he();var Js=class extends Error{constructor(n,r,o){super(`Budget exhausted: ${n} (limit=${r}, observed=${o})`);this.which=n;this.limit=r;this.observed=o}name="BudgetExhaustedError"},ru=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),Cp=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function ou(t,e){let n=Ve(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),r=M(Cp(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=A([r],([d])=>{let c=d;return!(e.caps.calls!=null&&c.calls>=e.caps.calls||e.caps.inputTokens!=null&&c.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&c.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&c.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(re(o),e.onExhausted!=null){let d=e.onExhausted,c=!1,l=!0;o.subscribe(p=>{for(let f of p)if(f[0]===E){let m=f[1];if(c&&l&&m===!1){let h=Ap(r.cache??ru,e.caps);h&&d(h)}l=m,c=!0}})}let s=()=>{if(o.cache===!1){let d=r.cache??ru,c=Ap(d,e.caps);return new Js(c??"budget",e.caps[c??"calls"]??0,vh(d,c??"calls"))}},i=(d,c)=>{let l=t.provider,p=vn({provider:l,model:c.model,tier:c.tier,usage:d,startNs:c.startNs,method:c.method,...c.error?{error:c.error}:{}});n.append(p);let f=r.cache??ru,m=e.pricingFn?f.usd+e.pricingFn(d,{model:c.model,provider:l,tier:c.tier}).total:f.usd;r.emit({calls:f.calls+1,inputTokens:f.inputTokens+yt(d),outputTokens:f.outputTokens+Gt(d),usd:m})},a=()=>{n.clear(),r.emit(Cp())},u=et(t,{invoke(d,c){let l=s();if(l)return Promise.reject(l);let p=H(),f=t.model??c?.model??"",m=g=>(i(g.usage??Rt(),{model:t.model??c?.model??g.model??"",tier:c?.tier??g.tier,startNs:p,method:"invoke"}),g),h=g=>{let y=g;i(Rt(),{model:f,tier:c?.tier,startNs:p,method:"invoke",error:{type:y?.name??"Error",message:y?.message??String(g)}})};return qs(t.invoke(d,c),{onResp:m,onError:h,name:"budgetGate/invokeTap"})},async*stream(d,c){let l=s();if(l)throw l;let p=H(),f;try{for await(let m of t.stream(d,c))m.type==="usage"&&(f=m.usage),yield m;i(f??Rt(),{model:t.model??c?.model??"",tier:c?.tier,startNs:p,method:"stream"})}catch(m){let h=m;throw i(f??Rt(),{model:t.model??c?.model??"",tier:c?.tier,startNs:p,method:"stream",error:{type:h?.name??"Error",message:h?.message??String(m)}}),m}}});return Ue(u,"withBudgetGate",t),{adapter:u,budget:{totals:r,isOpen:o,log:n,reset:a}}}function Ap(t,e){if(e.calls!=null&&t.calls>=e.calls)return"calls";if(e.inputTokens!=null&&t.inputTokens>=e.inputTokens)return"inputTokens";if(e.outputTokens!=null&&t.outputTokens>=e.outputTokens)return"outputTokens";if(e.usd!=null&&t.usd>=e.usd)return"usd"}function vh(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}he();function Th(t,e){let n=e.mock??bn({provider:t.provider,model:t.model}),r=typeof e.enabled=="boolean"?e.enabled:void 0,o=r===void 0?U(e.enabled):void 0,s;o&&(s=re(o));let i=()=>r!==void 0?r:!!o?.cache,a=et(t,{invoke(d,c){return i()?n.invoke(d,c):t.invoke(d,c)},stream(d,c){return i()?n.stream(d,c):t.stream(d,c)}});return Ue(a,"withDryRun",t),{adapter:a,dispose:()=>{s&&(s(),s=void 0)}}}function su(t){if(t==null||typeof t!="object")return;let e=t,n=e.status,r=wh(e.headers);if(n!==429&&n!==503&&!Nh(e.message))return;let o={},s=r("retry-after"),i=xh(s);i!=null&&(o.retryAfterMs=i);let a=r("anthropic-ratelimit-requests-reset");if(a){let f=Lp(a);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let u=r("anthropic-ratelimit-tokens-reset");if(u){let f=Lp(u);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let d=Ys(r,"x-ratelimit-limit-requests");d!=null&&(o.rpmCap=d);let c=Ys(r,"x-ratelimit-limit-tokens");c!=null&&(o.tpmCap=c);let l=Ys(r,"x-ratelimit-remaining-requests"),p=Ys(r,"x-ratelimit-remaining-tokens");if(l!=null&&d!=null&&d>0&&(o.usageHint??={},o.usageHint.rpm=1-l/d),p!=null&&c!=null&&c>0&&(o.usageHint??={},o.usageHint.tpm=1-p/c),o.retryAfterMs==null&&e.message){let f=Sh(e.message);f!=null&&(o.retryAfterMs=f)}return e.headers&&(o.metadata={headers:kh(e.headers)}),o.retryAfterMs==null&&o.rpmCap==null&&o.tpmCap==null&&o.usageHint==null?o.metadata?o:void 0:o}function wh(t){if(!t)return()=>{};if(typeof t.get=="function"){let r=t;return o=>r.get(o)??r.get(o.toLowerCase())??void 0}let e=t,n={};for(let[r,o]of Object.entries(e)){let s=Array.isArray(o)?o.join(", "):o;s!=null&&(n[r.toLowerCase()]=s)}return r=>n[r.toLowerCase()]}function kh(t){let e={};if(typeof t.forEach=="function")return t.forEach((n,r)=>{e[r]=n}),e;for(let[n,r]of Object.entries(t))r!=null&&(e[n]=Array.isArray(r)?r.join(", "):r);return e}function Ys(t,e){let n=t(e);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function xh(t){if(!t)return;let e=t.trim(),n=Number(e);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(e);if(Number.isFinite(r)){let o=r-Date.now();if(o>0)return o}}function Lp(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var Rh=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function Sh(t){let e=Rh.exec(t);if(!e)return;let n=Number(e[1]);if(!Number.isFinite(n))return;let r=(e[2]??"s").toLowerCase();if(r==="ms")return n;if(r.startsWith("s"))return n*1e3;if(r.startsWith("m"))return n*6e4}var Eh=/rate\s*limit|too\s*many\s*requests|quota|429/i;function Nh(t){return!!t&&Eh.test(t)}xe();ae();ee();Ot();he();vt();function iu(t){let e=new Error(t);return e.name="AbortError",e}function Pp(t={}){let e=Math.max(1,t.burstMultiplier??1),n=t.clampCooldownMs??6e4,r=t.rpm!=null?U(t.rpm):M(Number.POSITIVE_INFINITY),o=t.tpm!=null?U(t.tpm):M(Number.POSITIVE_INFINITY),s=M(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),i=M(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),a=M({},{name:"adaptiveRateLimiter/lastSignal"}),u=A([r,s],([O,P])=>Math.min(Number(O??1/0),Number(P??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),d=A([o,i],([O,P])=>Math.min(Number(O??1/0),Number(P??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),c=nr(Number(r.cache??Number.POSITIVE_INFINITY),e),l=nr(Number(o.cache??Number.POSITIVE_INFINITY),e),p=!1,f=!1,m=u.subscribe(O=>{for(let P of O)if(P[0]===E){let B=Number(P[1]);Number.isFinite(B)&&B>0?(c=nr(B,e),p=!1):B===1/0?(c=nr(1/0,e),p=!1):B<=0&&(p=!0)}}),h=d.subscribe(O=>{for(let P of O)if(P[0]===E){let B=Number(P[1]);Number.isFinite(B)&&B>0?(l=nr(B,e),f=!1):B===1/0?(l=nr(1/0,e),f=!1):B<=0&&(f=!0)}}),g=0,y=new Le,b=new Le,v;t.adaptation!=null&&(v=U(t.adaptation).subscribe(P=>{for(let B of P)B[0]===E&&T(B[1])}));function T(O){if(a.emit(O),O.rpmCap!=null&&Number.isFinite(O.rpmCap)&&O.rpmCap>=0&&(s.emit(O.rpmCap),Number.isFinite(n)&&n>0&&y.start(n,()=>s.emit(Number.POSITIVE_INFINITY))),O.tpmCap!=null&&Number.isFinite(O.tpmCap)&&O.tpmCap>=0&&(i.emit(O.tpmCap),Number.isFinite(n)&&n>0&&b.start(n,()=>i.emit(Number.POSITIVE_INFINITY))),O.retryAfterMs!=null&&O.retryAfterMs>0){let P=H()+O.retryAfterMs*1e6;P>g&&(g=P)}}let w=M(0,{name:"adaptiveRateLimiter/pending"}),x=M(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),k=M(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),S=O=>{w.emit((w.cache??0)+O)},R=()=>{x.emit(c.available()),k.emit(l.available())};async function N(O={}){let P=O.requestCost??1,B=O.tokenCost??0,j=O.signal;S(1);try{for(;;){if(j?.aborted)throw iu("AdaptiveRateLimiter.acquire aborted");let D=H();if(g>D){let q=Math.ceil((g-D)/1e6);await Qs(q,j);continue}if(P>0&&p||B>0&&f){await Qs(250,j);continue}let Z=c,F=l;if(!Z.tryConsume(P)){await Qs(Ip(Z,P),j);continue}if(!(B>0?F.tryConsume(B):!0)){Z.putBack(P),await Qs(Ip(F,B),j);continue}R();return}}finally{S(-1)}}function _(O){O>0?l.tryConsume(O):O<0&&l.putBack(-O),R()}function I(){m(),h(),v?.(),y.cancel(),b.cancel()}return{effectiveRpm:u,effectiveTpm:d,lastSignal:a,pending:w,rpmAvailable:x,tpmAvailable:k,acquire:N,recordUsage:_,recordSignal:T,dispose:I}}function nr(t,e){if(!Number.isFinite(t)||t===1/0)return Vt(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let n=Math.max(1,t*e),r=t/60;return Vt(n,r)}function Ip(t,e){let n=t.available(),r=Math.max(0,e-n);return r<=0?25:Math.min(5e3,Math.max(50,r*100))}function Qs(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(iu("AdaptiveRateLimiter.acquire aborted")):new Promise((n,r)=>{let o=new Le,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(iu("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",s,{once:!0}))})}he();function au(t,e={}){let n=e.limiter??Pp({name:e.name??"rateLimiter",rpm:e.rpm,tpm:e.tpm,adaptation:e.adaptation,burstMultiplier:e.burstMultiplier}),r=(i,a)=>e.costFn?e.costFn(i,a):0,o=i=>{let a=su(i);a&&n.recordSignal(a)},s=et(t,{async invoke(i,a){let u=r(i,a);await n.acquire({requestCost:1,tokenCost:u,signal:a?.signal});try{let d=await Ye(U(t.invoke(i,a))),c=d.usage??Op(),p=yt(c)+Gt(c)-u;return p>0&&n.recordUsage(p),d}catch(d){throw o(d),d}},async*stream(i,a){let u=r(i,a);await n.acquire({requestCost:1,tokenCost:u,signal:a?.signal});try{let d=0;for await(let l of t.stream(i,a))l.type==="usage"&&(d=yt(l.usage)+Gt(l.usage)),yield l;let c=d-u;c>0&&n.recordUsage(c)}catch(d){throw o(d),d}}});return Ue(s,"withRateLimiter",t),{adapter:s,limiter:n}}Ot();he();var po=class extends Error{name="AllTiersExhaustedError";skipped;failed;constructor(e){let n=[];e.failed.size>0&&n.push(`failed=[${[...e.failed.keys()].join(",")}]`),e.skipped.length>0&&n.push(`skipped=[${e.skipped.map(r=>`${r.name}(${r.reason})`).join(",")}]`),super(`All LLM adapter tiers exhausted: ${n.join(" ")}`),this.skipped=e.skipped,this.failed=e.failed}};function uu(t,e={}){if(t.length===0)throw new RangeError("cascadingLlmAdapter: tiers must be non-empty");let n=t.map(s=>({name:s.name,adapter:s.adapter,filter:s.filter,breaker:s.breaker?"canExecute"in s.breaker?s.breaker:wt(s.breaker):void 0})),r=e.streamRetryBeforeFirstChunk??!0,o={provider:"cascading",model:void 0,async invoke(s,i){let a=[],u=new Map;for(let c=0;c<n.length;c++){let l=n[c];if(l.filter&&!l.filter(s,i)){a.push({name:l.name,reason:"filter"});continue}if(l.breaker&&!l.breaker.canExecute()){a.push({name:l.name,reason:"breaker"});continue}try{let p=await Ye(U(l.adapter.invoke(s,i)));return l.breaker?.recordSuccess(),{...p,metadata:{...p.metadata??{},tier:l.name}}}catch(p){u.set(l.name,p),l.breaker?.recordFailure(p);let f=n[c+1];f&&e.onFallback?.(l.name,f.name,p)}}let d={skipped:a,failed:u};throw e.onExhausted?.(d),new po(d)},async*stream(s,i){let a=[],u=new Map;for(let c=0;c<n.length;c++){let l=n[c];if(l.filter&&!l.filter(s,i)){a.push({name:l.name,reason:"filter"});continue}if(l.breaker&&!l.breaker.canExecute()){a.push({name:l.name,reason:"breaker"});continue}let p=!1;try{for await(let f of l.adapter.stream(s,i))p=!0,yield f;l.breaker?.recordSuccess();return}catch(f){if(u.set(l.name,f),l.breaker?.recordFailure(f),p||!r)throw f;let m=n[c+1];m&&e.onFallback?.(l.name,m.name,f)}}let d={skipped:a,failed:u};throw e.onExhausted?.(d),new po(d)}};return Ue(o,`cascade[${n.map(s=>s.name).join(",")}]`),o}function _h(t,e,n){let r={name:t,adapter:e};return n?.breaker&&(r.breaker=n.breaker),n?.filter&&(r.filter=n.filter),r}he();vt();function Xs(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function Dp(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Xs()):new Promise((n,r)=>{let o=new Le,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(Xs())},e.addEventListener("abort",s,{once:!0}))})}function du(t,e={}){let n=e.attempts??3,r=e.baseDelayMs??500,o=e.maxDelayMs??1e4,s=e.strategy??"decorrelated",i=e.jitter??!0,a=e.shouldRetry??Mh,u=e.retryStreaming??!0,d=(l,p)=>{if(s==="decorrelated"){let g=Math.min(o,Math.max(r,p*3));return r+Math.random()*(g-r)}let f=s==="exp"?r*2**(l-1):r*l,m=Math.min(o,f);if(!i)return m;let h=m*(.5+Math.random());return Math.min(o,h)},c=et(t,{async invoke(l,p){if(p?.signal?.aborted)throw Xs();let f,m=r;for(let h=1;h<=n;h++)try{return await Ye(U(t.invoke(l,p)))}catch(g){if(f=g,h>=n||!a(g,h))throw g;let y=d(h,m);m=y,await Dp(y,p?.signal)}throw f},async*stream(l,p){if(p?.signal?.aborted)throw Xs();if(!u){for await(let h of t.stream(l,p))yield h;return}let f,m=r;for(let h=1;h<=n;h++){let g=!1;try{for await(let y of t.stream(l,p))g=!0,yield y;return}catch(y){if(f=y,g||h>=n||!a(y,h))throw y;let b=d(h,m);m=b,await Dp(b,p?.signal)}}throw f}});return Ue(c,"withRetry",t),c}function Mh(t,e){if(t==null)return!1;let n=t;return n.name==="LLMTimeoutError"?!0:n.name==="AbortError"||n.message==="aborted"||n.name==="DOMException"&&n.code!=null&&Number(n.code)===20||n.name==="BudgetExhaustedError"||n.name==="CircuitOpenError"?!1:n.status!=null?n.status===429||n.status>=500&&n.status<600:n.code&&typeof n.code=="string"&&/^E[A-Z]+$/.test(n.code)?!0:n.message?/network|timeout|socket|fetch|econn|eai_/i.test(n.message):!1}he();vt();var rr=class extends Error{constructor(n){super(`LLM call timed out after ${n}ms`);this.ms=n}name="LLMTimeoutError"};function cu(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let n=s=>{let i=new AbortController,a=!1,u,d=new Le;return s&&(s.aborted?i.abort(s.reason):(u=()=>{d.cancel(),i.abort(s.reason)},s.addEventListener("abort",u,{once:!0}))),d.start(e,()=>{a=!0,i.abort(new rr(e))}),{signal:i.signal,cancel:()=>{d.cancel(),s&&u&&s.removeEventListener("abort",u)},timedOut:()=>a}},r=(s,i)=>{if(!i||s instanceof rr)throw s;let a=s;if(a?.name==="AbortError"||a?.name==="DOMException"&&Number(a.code)===20||s?.message==="aborted"){let d=new rr(e);throw d.cause=s,d}throw s},o=et(t,{async invoke(s,i){let{signal:a,cancel:u,timedOut:d}=n(i?.signal);try{return await Ye(U(t.invoke(s,{...i,signal:a})))}catch(c){return r(c,d())}finally{u()}},async*stream(s,i){let{signal:a,cancel:u,timedOut:d}=n(i?.signal);try{for await(let c of t.stream(s,{...i,signal:a}))yield c}catch(c){r(c,d())}finally{u()}}});return Ue(o,"withTimeout",t),o}function Oh(t,e={}){let n={adapter:t},r=t;if(e.rateLimit){let o=au(r,e.rateLimit);r=o.adapter,n.rateLimiter=o.limiter}if(e.budget){let o=ou(r,e.budget);r=o.adapter,n.budget=o.budget}if(e.breaker){let o=nu(r,e.breaker);r=o.adapter,n.breaker=o.breaker}if(e.timeoutMs!=null&&(r=cu(r,e.timeoutMs)),e.retry&&(r=du(r,e.retry)),e.fallback){if(e.name==="fallback")throw new RangeError('resilientAdapter: `name` cannot be "fallback" \u2014 collides with the secondary tier label.');let o={};e.onFallback&&(o.onFallback=e.onFallback),e.onExhausted&&(o.onExhausted=e.onExhausted),r=uu([{name:e.name??"primary",adapter:r},{name:"fallback",adapter:e.fallback}],o)}return e.cache&&(r=lo(r,e.cache)),n.adapter=r,n}ee();he();function Ch(t,e,n){let r=U(e);return Te(r,s=>{if(!s||s.length===0)return M(null);let i=n?.tools;return t.invoke(s,{model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,tools:i,systemPrompt:n?.systemPrompt})})}_e();he();ae();he();vt();function fe(t,e){return ze("ai",t,e)}function Ah(t){return t!=null&&typeof t.then=="function"}function lu(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function Lh(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var Ih=3e4;function Gp(t,e){if(t.status==="settled"){let r=t.cache;if(r!==void 0)return Promise.resolve(r)}let n=e?.timeoutMs??Ih;return new Promise((r,o)=>{let s=new Le,i=t.subscribe(a=>{for(let u of a){if(u[0]===E){s.cancel(),i(),r(u[1]);return}if(u[0]===C){s.cancel(),i(),o(u[1]);return}if(u[0]===L){s.cancel(),i(),o(new Error("firstDataFromNode: completed without producing a value"));return}}});s.start(n,()=>{i(),o(new Error(`firstDataFromNode: timed out after ${n}ms`))})})}async function fo(t){return Ah(t)?fo(await t):lu(t)?Gp(t):Lh(t)?Gp(U(t)):t}function or(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function Ph(t,e){let n=U(t),r=e?.refreshTrigger!=null?U(e.refreshTrigger):null;return r==null?z([n],(o,s,i)=>{if(i.store.emitted===!0)return;let u=o[0],d=u!=null&&u.length>0?u.at(-1):i.prevData[0];if(d!==void 0)return i.store.emitted=!0,s.emit(d),{invalidate:()=>{i.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:fe("frozen_context")}):z([n,r],(o,s,i)=>{let a=o[1];if(!(a!=null&&a.length>0))return;let d=o[0],c=d!=null&&d.length>0?d.at(-1):i.prevData[0];s.emit(c)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:fe("frozen_context")})}ae();ee();he();function Fp(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function Dh(t,e=200){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function wn(t,e,n,r){let o=r?.format??"text",s=r?.name??"prompt_node",i=A(e,u=>{if(u.some(c=>c==null))return[];let d=typeof n=="string"?n:n(...u);return d?[{role:"user",content:d}]:[]},{name:`${s}::messages`,meta:fe("prompt_node")});return Te(i,u=>!u||u.length===0?M(null):K(d=>{let c=!1,l=!1,p,f={model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt};if(r?.abort){let y=ts(r.abort);f.signal=y.signal,p=y.dispose}let m;try{m=t.invoke(u,f)}catch(y){return c=!0,d.down([[C,y]]),()=>{p?.()}}let g=U(m).subscribe(y=>{if(!(l||c))for(let b of y){if(c)return;if(b[0]===E){let v=b[1];try{let T=Fp(v),w=o==="json"?JSON.parse(or(T)):T;d.emit(w)}catch(T){let w=Fp(v),x=new Error(`promptNode: failed to parse LLM response as JSON: ${T.message}
|
|
37
|
-
Raw content (first 200 chars): ${Dh(w)}`);c=!0,d.down([[C,x]]);return}}else if(b[0]===C){c=!0,d.down([[C,b[1]]]);return}else if(b[0]===L){c=!0,d.down([[L]]);return}else d.down([b])}});return()=>{l=!0,g(),p?.()}},{name:`${s}::call`,meta:fe("prompt_node::call")}),{name:`${s}::output`,meta:r?.meta?{...fe("prompt_node::output"),...r.meta}:fe("prompt_node::output")})}Me();xe();ee();he();var oi={};ke(oi,{MessagingHubGraph:()=>ti,SubscriptionGraph:()=>mo,TopicBridgeGraph:()=>Zs,TopicGraph:()=>kn,TopicRegistry:()=>ei,messagingHub:()=>go,subscription:()=>$p,topic:()=>ni,topicBridge:()=>ri});_e();var Gh=256;function sr(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Yt(t,e){return ze("messaging",t,e)}var Fh=1024,kn=class extends Y{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=Ve([],{name:"events",maxSize:n.retainedLimit??Fh}),this._log.withLatest(),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=A([this.events],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:Yt("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(re(this.latest)),this.hasLatest=A([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:Yt("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(re(this.hasLatest)),this.addDisposer(()=>{this.events.down([[L]])}),this.addDisposer(()=>this._log.disposeAllViews())}publish(e){if(e===void 0)throw new TypeError(`TopicGraph "${this.name}": publish(undefined) is not allowed (spec \xA75.12 SENTINEL).`);this._log.append(e)}attachEventStorage(e){return this._log.attachStorage(e)}retained(){return this.events.cache}get _logBundle(){return this._log}},mo=class extends Y{cursor;available;topic;_disposed=!1;constructor(e,n,r={}){super(e,r.graph),this.topic=n;let o;if(r.from!==void 0?r.from==="retained"?o=0:r.from==="now"?o=n.events.cache.length:o=sr(r.from,"subscription from"):o=sr(r.cursor??0,"subscription cursor"),this.cursor=M(o,{name:"cursor",describeKind:"state",meta:Yt("subscription_cursor")}),this.add(this.cursor,{name:"cursor"}),this.available=n._logBundle.view({kind:"fromCursor",cursor:this.cursor}),this.add(this.available,{name:"available"}),this.addDisposer(re(this.available)),r.advanceOn!==void 0){let s=r.advanceOn,i=!1,a=z([s],()=>{if(!i){i=!0;return}if(this._disposed)return;let u=this.available.cache;if(u.length===0)return;let d=this.cursor.cache+u.length;this.cursor.emit(d)},{name:"advancePump",describeKind:"effect",meta:Yt("subscription_advance_pump")});this.add(a,{name:"advancePump"}),this.addDisposer(re(a))}}ack(e){if(this._disposed)return this.cursor.cache;let n=this.available.cache,r=e===void 0?n.length:sr(e,"subscription ack count"),o=Math.min(r,n.length);if(o<=0)return this.cursor.cache;let s=this.cursor.cache+o;return this.cursor.emit(s),s}pull(e){if(this._disposed)return[];let n=this.available.cache,r=e===void 0?n.length:sr(e,"subscription pull limit");return n.slice(0,r)}pullAndAck(e){if(this._disposed)return{items:[],cursor:this.cursor.cache};let n=this.available.cache,r=e===void 0?n.length:sr(e,"subscription pullAndAck limit"),o=n.slice(0,r);if(o.length===0)return{items:o,cursor:this.cursor.cache};let s=this.cursor.cache+o.length;return this.cursor.emit(s),{items:o,cursor:s}}dispose(){this._disposed||(this._disposed=!0,this.cursor.down([[L]]),this.destroy())}},Zs=class extends Y{_sourceSub;bridgedCount;output;constructor(e,n,r,o={}){super(e,o.graph),this._sourceSub=$p(`${e}-subscription`,n,{cursor:o.cursor}),this.mount("subscription",this._sourceSub);let s=Math.max(1,sr(o.maxPerPump??Gh,"topic bridge maxPerPump")),i=o.map??(p=>p);this.output=A([this._sourceSub.available],([p])=>{let f=p,m=[],h=Math.min(f.length,s);for(let g=0;g<h;g++){let y=i(f[g]);y!==void 0&&m.push(y)}return m},{name:"output",describeKind:"derived",meta:Yt("topic_bridge_output",{targetRef:r.name}),initial:[]}),this.add(this.output,{name:"output"}),this.addDisposer(re(this.output)),this.bridgedCount=M(0,{name:"bridgedCount",describeKind:"state",meta:Yt("topic_bridge_count")}),this.add(this.bridgedCount,{name:"bridgedCount"}),this.addDisposer(re(this.bridgedCount));let a=this.output,u=this._sourceSub,d=this.bridgedCount,c=z([a],()=>{let p=a.cache;if(p.length===0)return;let f=u.available.cache.length,m=Math.min(f,s);if(m>0){u.ack(m);let h=d.cache??0;d.emit(h+p.length)}},{name:"ackPump",describeKind:"effect",meta:Yt("topic_bridge_ack_pump")});this.add(c,{name:"ackPump"}),this.addDisposer(re(c));let l=$h(this.output,r);this.addDisposer(l)}};function $h(t,e){return t.subscribe(n=>{for(let r of n){if(r[0]!==E)continue;let o=r[1];o.length!==0&&X(()=>{for(let s of o)e.publish(s)})}})}var ei=class{_map=new Map;version;constructor(e){this.version=e}get size(){return this._map.size}has(e){return this._map.has(e)}get(e){return this._map.get(e)}set(e,n){this._map.set(e,n)}delete(e){return this._map.delete(e)}keys(){return this._map.keys()}},ti=class extends Y{_registry;version;_defaultTopicOptions;constructor(e,n={}){super(e,n.graph);let r=M(0,{name:"version",describeKind:"state",meta:Yt("hub_version")});this.add(r,{name:"version"}),this.version=r,this._registry=new ei(r),this._defaultTopicOptions={...n.defaultTopicOptions??{}}}get size(){return this._registry.size}has(e){return this._registry.has(e)}topicNames(){return this._registry.keys()}topic(e,n){let r=this._registry.get(e);if(r===void 0){let o={...this._defaultTopicOptions,...n??{}};r=new kn(e,o),this._registry.set(e,r),this.mount(e,r);let s=this.version.cache??0;this.version.emit(s+1)}return r}publish(e,n){this.topic(e).publish(n)}publishMany(e){X(()=>{for(let[n,r]of e)this.topic(n).publish(r)})}subscribe(e,n,r){let o=this.topic(n);return new mo(e,o,r)}removeTopic(e){if(!this._registry.has(e))return!1;try{this.remove(e)}finally{this._registry.delete(e);let n=this.version.cache??0;this.version.emit(n+1)}return!0}};function ni(t,e){return new kn(t,e)}function go(t,e){return new ti(t,e)}function $p(t,e,n){return new mo(t,e,n)}function ri(t,e,n,r){return new Zs(t,e,n,r)}var si={};ke(si,{PipelineGraph:()=>yo,decisionKeyOf:()=>jp,pipelineGraph:()=>ir});Me();xe();ae();_e();ee();function ho(t,e){return ze("orchestration",t,e)}var jp=t=>t.action,yo=class extends Y{constructor(e,n){super(e,n)}task(e,n,r={}){let o=(r.deps??[]).map(i=>this._resolveStep(i)),s=A(o,n,{name:e,describeKind:"derived",meta:ho("task",r.meta)});return this.add(s,{name:e}),s}classify(e,n,r,o={}){let s=this._resolveStep(n),i=A([s],([a])=>{try{return{tag:r(a),value:a}}catch(u){return{tag:"error",value:a,error:u}}},{name:e,describeKind:"derived",meta:ho("classify",o.meta)});return this.add(i,{name:e}),i}combine(e,n,r={}){let o=Object.keys(n),s=o.map(a=>this._resolveStep(n[a])),i=A(s,a=>{let u={};for(let d=0;d<o.length;d++)u[o[d]]=a[d];return u},{name:e,describeKind:"derived",meta:ho("combine",r.meta)});return this.add(i,{name:e}),i}gate(e,n,r={}){let o=r.maxPending??1e3;if(o<1&&o!==Number.POSITIVE_INFINITY)throw new RangeError("gate: maxPending must be >= 1");let s=r.startOpen??!1;typeof n!="string"&&this.nameOf(n)===void 0&&this.add(n,{name:`${e}/source`});let i=this._resolveStep(n),a=new Y(`${e}_state`),u=M([],{name:"pending",equals:()=>!1}),d=M(s,{name:"isOpen"}),c=A([u],([F])=>F.length,{name:"count"}),l=M(0,{name:"droppedCount"}),p=kt({name:"decisions",retainedLimit:1024,graph:a});a.add(u,{name:"pending"}),a.add(d,{name:"isOpen"}),a.add(c,{name:"count"}),a.add(l,{name:"droppedCount"}),this.mount(`${e}_state`,a);let f=[],m=!1,h=!1,g=s,y=d.subscribe(F=>{for(let Q of F)Q[0]===E&&(g=Q[1])});this.addDisposer(y);function b(){u.emit([...f])}function v(F,Q,G){p.append({action:F,t_ns:oe(),...Q!==void 0?{items:Q,count:Q.length}:{},...G!==void 0?{unflushed:G}:{},...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}function T(F){if(f.push(F),f.length>o){let Q=f.shift();l.emit(l.cache+1),v("drop",[Q])}b()}function w(F){let Q=f.splice(0,F);return b(),Q}let x=z([i],(F,Q,G)=>{let q=G.terminalDeps[0];if(q!==void 0){m=!0;let te=f.length;f=[],b(),v("teardown",void 0,te),Q.down(q===!0?[[L]]:[[C,q]]);return}let $=F[0];if($==null||$.length===0){Q.down([[V]]);return}for(let te of $)g?Q.emit(te):(T(te),Q.down([[V]]))},{name:e,describeKind:"derived",meta:ho("gate",r.meta)});if(this.add(x,{name:e}),r.approver!=null){r.approver.cache&&(d.emit(!0),g=!0,r.onceOnly&&(h=!0));let Q=r.approver.subscribe(G=>{for(let q of G){if(q[0]!==E)continue;let $=!!q[1];if($&&!g){if(r.onceOnly){if(h)continue;h=!0}X(()=>{d.emit(!0);let te=w(f.length);v("open",te);for(let Re of te){if(m)break;x.emit(Re)}})}else if(!$&&g){if(r.onceOnly&&h)continue;X(()=>{d.emit(!1),v("close")})}}});this.addDisposer(Q)}let k=F=>{if(m)throw new Error(`gate: ${F}() called after gate was torn down`)},S=(F=1)=>{k("approve");let Q=w(F);for(let G of Q){if(m)break;x.emit(G)}},R=(F=1)=>{k("reject"),w(F)},N=(F,Q=1)=>{k("modify");let G=[...f],q=w(Q);for(let $=0;$<q.length&&!m;$++)x.emit(F(q[$],$,G))},_=()=>{k("open"),d.emit(!0);let F=w(f.length);for(let Q of F){if(m)break;x.emit(Q)}},I=()=>{k("close"),!(r.onceOnly&&h)&&d.emit(!1)},O=Yn(S,{audit:p,freeze:!1,onSuccess:(F,Q,G)=>({action:"approve",count:F[0]??1,t_ns:G.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,Q,G)=>({action:"drop",t_ns:G.t_ns,errorType:G.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),P=Yn(R,{audit:p,freeze:!1,onSuccess:(F,Q,G)=>({action:"reject",count:F[0]??1,t_ns:G.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,Q,G)=>({action:"drop",t_ns:G.t_ns,errorType:G.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),B=Yn(N,{audit:p,freeze:!1,onSuccess:(F,Q,G)=>({action:"modify",count:F[1]??1,t_ns:G.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,Q,G)=>({action:"drop",t_ns:G.t_ns,errorType:G.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),j=Yn(_,{audit:p,freeze:!1,onSuccess:(F,Q,G)=>({action:"open",t_ns:G.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,Q,G)=>({action:"drop",t_ns:G.t_ns,errorType:G.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),D=Yn(I,{audit:p,freeze:!1,onSuccess:(F,Q,G)=>({action:"close",t_ns:G.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,Q,G)=>({action:"drop",t_ns:G.t_ns,errorType:G.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})});return this.addDisposer(c.subscribe(()=>{})),{node:x,pending:u,count:c,isOpen:d,droppedCount:l,decisions:p,audit:p,approve:O,reject:P,modify:B,open:j,close:D}}approval(e,n,r,o={}){return this.gate(e,n,{...o,approver:r,maxPending:1})}catch(e,n,r,o={}){let s=this._resolveStep(n),i=o.on??"error",a=z([s],(u,d,c)=>{let l=c.terminalDeps[0];if(l!==void 0){let f=l===!0?{kind:"complete"}:{kind:"error",error:l};if(i==="terminal"||i===f.kind){d.emit(r(f,d));return}d.down(f.kind==="complete"?[[L]]:[[C,f.error]]);return}let p=u[0];if(p==null||p.length===0){d.down([[V]]);return}for(let f of p)d.emit(f)},{name:e,describeKind:"derived",completeWhenDepsComplete:o.completeWhenDepsComplete??!(i==="complete"||i==="terminal"),errorWhenDepsError:!(i==="error"||i==="terminal"),meta:ho("catch",o.meta)});return this.add(a,{name:e}),a}_resolveStep(e){if(typeof e=="string")return this.resolve(e);if(this.nameOf(e)===void 0)throw new Error(`PipelineGraph "${this.name}": Node dep is not registered. Pass a string path or call graph.add(node) first.`);return e}};function ir(t,e){return new yo(t,e)}async function Bp(t,e,n,r){let o="",s=0;for await(let i of t.stream(e,n))r.publish({...i,seq:s++,ts:oe()}),i.type==="token"&&(o+=i.delta);return o}function Vp(t,e){if(e==="json")try{return JSON.parse(or(t))}catch(n){let r=t.slice(0,160);throw new Error(`streamingPromptNode: format:"json" \u2014 failed to parse accumulated text as JSON: ${n.message}; content preview: ${r}`)}return t}function Kp(t,e){return A([t.latest],([n],r)=>{let o=r.store;if(n==null)return o.acc??"";let s=n;return s.seq===0&&(o.acc=""),s.type==="token"&&(o.acc=(o.acc??"")+s.delta),o.acc??""},{name:e,meta:fe("accumulated_text"),initial:""})}function jh(t,e,n,r){let o=r?.name??"llm",s=r?.format??"text",i=ni(`${o}/stream`,{...r?.retainedLimit!=null?{retainedLimit:r.retainedLimit}:{}}),a=A(e,l=>{if(l.some(f=>f==null))return[];let p=typeof n=="string"?n:n(...l);return p?[{role:"user",content:p}]:[]},{name:`${o}::messages`,meta:fe("prompt_node::messages"),initial:[]}),u=Te(a,l=>{let p=l;if(!p||p.length===0)return M(null);let f=new AbortController;async function*m(){try{let h=await Bp(t,p,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,signal:f.signal},i);yield Vp(h,s)}finally{f.abort()}}return U(m())}),d=Kp(i,`${o}::accumulatedText`),c=re(u);return{output:u,deltaTopic:i,accumulatedText:d,dispose:()=>{c(),i.destroy()}}}function Bh(t,e,n,r,o,s){let i=M(0,{name:`${e}/cancel`}),a=0,u=[...r,i],d=s?.name??e,c=s?.format??"text",l=ni(`${d}/stream`,{...s?.retainedLimit!=null?{retainedLimit:s.retainedLimit}:{}}),p=A(u,k=>{let S=k.slice(0,-1);if(S.some(N=>N==null))return[];let R=typeof o=="string"?o:o(...S);return R?[{role:"user",content:R}]:[]},{name:`${d}::messages`,meta:fe("prompt_node::messages"),initial:[]}),f=Te(p,k=>{let S=k;if(!S||S.length===0)return M(null);let R=new AbortController;async function*N(){try{let _=await Bp(n,S,{model:s?.model,temperature:s?.temperature,maxTokens:s?.maxTokens,systemPrompt:s?.systemPrompt,signal:R.signal},l);yield Vp(_,c)}finally{R.abort()}}return U(N())}),m=Kp(l,`${d}::accumulatedText`),h=Xe(f,k=>k!=null);t.add(h,{name:`${e}/raw`});let g=ir(`${e}/gate-graph`);t.mount(`${e}/gate-graph`,g),g.add(h,{name:`${e}/raw`});let y=g.gate(`${e}/gate`,`${e}/raw`,s?.gate),b=re(f),v=re(y.node),T=re(m);t.addDisposer(b),t.addDisposer(v),t.addDisposer(T);let w=y.reject.bind(y),x={...y,reject(k=1){X(()=>{w(k),i.emit(++a)})}};return{output:y.node,deltaTopic:l,accumulatedText:m,gate:x,dispose:()=>{b(),v(),T(),l.destroy()}}}ee();he();function Vh(t,e){let n=e?.separator??`
|
|
36
|
+
`)}]});let s={};return e?.maxTokens!=null&&(s.maxOutputTokens=e.maxTokens),e?.temperature!=null&&(s.temperature=e.temperature),e?.maxReasoningTokens!=null&&(s.thinkingConfig={thinkingBudget:e.maxReasoningTokens}),Object.keys(s).length>0&&(o.generationConfig=s),e?.tools&&e.tools.length>0&&(o.tools=[{functionDeclarations:e.tools.map(kh)}]),e?.providerExtras&&Object.assign(o,e.providerExtras),o}function kh(t){return{name:t.name,description:t.description,parameters:t.parameters}}function jp(t,e,n){let r={},o=t.generationConfig;o&&(typeof o.maxOutputTokens=="number"&&(r.maxOutputTokens=o.maxOutputTokens),typeof o.temperature=="number"&&(r.temperature=o.temperature),o.thinkingConfig&&(r.thinkingConfig=o.thinkingConfig)),t.systemInstruction&&(r.systemInstruction=t.systemInstruction),t.tools&&(r.tools=t.tools);for(let[s,i]of Object.entries(t))s==="contents"||s==="generationConfig"||s==="systemInstruction"||s==="tools"||s==="abortSignal"||s==="model"||(r[s]=i);return n&&(r.abortSignal=n),{model:e,contents:t.contents,config:Object.keys(r).length>0?r:void 0}}function ud(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 Bp(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:ud(t.usageMetadata),finishReason:n?.finishReason,latencyMs:e,model:t.modelVersion,provider:"google"}}function xh(t){if(t.apiKey)return t.apiKey;let e=globalThis.process?.env;return e?.GOOGLE_API_KEY??e?.GEMINI_API_KEY}function Rh(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=xh(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),d=Xs(s,i),u=V(),c=`${e}/models/${encodeURIComponent(a)}:generateContent?${o()}`,l=await n(c,{method:"POST",headers:{"content-type":"application/json",...t.headers??{}},body:JSON.stringify(d),signal:i?.signal});if(!l.ok)throw await wt(l,"Google");let p=await l.json(),f=Math.max(0,(V()-u)/1e6);return Bp(p,f)},async*stream(s,i){let a=r(i),d=Xs(s,i),u=`${e}/models/${encodeURIComponent(a)}:streamGenerateContent?alt=sse&${o()}`,c=await n(u,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",...t.headers??{}},body:JSON.stringify(d),signal:i?.signal});if(!c.ok)throw await wt(c,"Google");if(!c.body)throw new Error("googleAdapter: streaming response has no body");let l,p;for await(let f of $t(c.body,{signal:i?.signal})){if(!f.data)continue;let m;try{m=JSON.parse(f.data)}catch{continue}let h=m.candidates?.[0];for(let g of h?.content?.parts??[])typeof g.text=="string"&&(g.thought?yield{type:"thinking",delta:g.text}:yield{type:"token",delta:g.text}),g.functionCall&&(yield{type:"tool-call-delta",delta:{name:g.functionCall.name,argumentsDelta:JSON.stringify(g.functionCall.args??{})}});h?.finishReason&&(p=h.finishReason),m.usageMetadata&&(l=m.usageMetadata)}l&&(yield{type:"usage",usage:ud(l)}),yield{type:"finish",reason:p??"stop"}}}}function Sh(t){let e=t.sdk;if(!e)throw new Error("sdkBackedGoogle: sdk instance required");return{provider:"google",model:t.model,async invoke(n,r){let o=Xs(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=jp(o,s,r?.signal),a=V(),d=await e.models.generateContent(i),u=Math.max(0,(V()-a)/1e6);return Bp(d,u)},async*stream(n,r){if(!e.models.generateContentStream)throw new Error("sdkBackedGoogle: SDK instance does not expose generateContentStream");let o=Xs(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=jp(o,s,r?.signal),a,d,u=await e.models.generateContentStream(i);for await(let c of u){let l=c.candidates?.[0];for(let p of l?.content?.parts??[])typeof p.text=="string"&&(p.thought?yield{type:"thinking",delta:p.text}:yield{type:"token",delta:p.text}),p.functionCall&&(yield{type:"tool-call-delta",delta:{name:p.functionCall.name,argumentsDelta:JSON.stringify(p.functionCall.args??{})}});l?.finishReason&&(d=l.finishReason),c.usageMetadata&&(a=c.usageMetadata)}a&&(yield{type:"usage",usage:ud(a)}),yield{type:"finish",reason:d??"stop"}}}}Re();var Nh={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 cd(t={}){return t.sdk?Ah(t):Oh(t)}function Zs(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(Eh);e?.systemPrompt&&!t.some(d=>d.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(_h)),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 Eh(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 _h(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}}function ld(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 Vp(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:Mh(a.function.arguments)}));return{content:s,toolCalls:i.length>0?i:void 0,usage:ld(t.usage),finishReason:r?.finish_reason,latencyMs:e,model:t.model,provider:n}}function Mh(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!=null?e:{_raw:t}}catch{return{_raw:t}}}function Kp(t){let e=t.preset??"openai",n=Nh[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 Oh(t){let{provider:e,baseURL:n,apiKey:r}=Kp(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,d){let u=Zs(a,d,t.model,!1,t.bodyExtras),c=V(),l=await o(`${n}/chat/completions`,{method:"POST",headers:i(),body:JSON.stringify(u),signal:d?.signal});if(!l.ok)throw await wt(l,e);let p=await l.json(),f=Math.max(0,(V()-c)/1e6);return Vp(p,f,e)},async*stream(a,d){let u=Zs(a,d,t.model,!0,t.bodyExtras),c=await o(`${n}/chat/completions`,{method:"POST",headers:{...i(),accept:"text/event-stream"},body:JSON.stringify(u),signal:d?.signal});if(!c.ok)throw await wt(c,e);if(!c.body)throw new Error(`openAICompatAdapter[${e}]: streaming response has no body`);let l,p;for await(let f of $t(c.body,{signal:d?.signal})){if(!f.data||f.data==="[DONE]")continue;let m;try{m=JSON.parse(f.data)}catch{continue}let h=m.choices;if(h){let g=h[0];if(g?.delta?.content&&(yield{type:"token",delta:g.delta.content}),g?.delta?.reasoning_content&&(yield{type:"thinking",delta:g.delta.reasoning_content}),g?.delta?.tool_calls)for(let y of g.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:y.id,name:y.function?.name,argumentsDelta:y.function?.arguments}};g?.finish_reason&&(p=g.finish_reason)}m.usage&&(l=m.usage,yield{type:"usage",usage:ld(l)})}yield{type:"finish",reason:p??"stop"}}}}function Ah(t){let e=t.sdk;if(!e)throw new Error("sdkBackedOpenAI: sdk instance required");let{provider:n}=Kp(t);return{provider:n,model:t.model,async invoke(r,o){let s=Zs(r,o,t.model,!1,t.bodyExtras),i=V(),a=await e.chat.completions.create(s,{signal:o?.signal}),d=Math.max(0,(V()-i)/1e6);return Vp(a,d,n)},async*stream(r,o){let s=Zs(r,o,t.model,!0,t.bodyExtras),i=await e.chat.completions.create(s,{signal:o?.signal}),a,d;for await(let u of i){let c=u.choices;if(c){let p=c[0];if(p?.delta?.content&&(yield{type:"token",delta:p.delta.content}),p?.delta?.reasoning_content&&(yield{type:"thinking",delta:p.delta.reasoning_content}),p?.delta?.tool_calls)for(let f of p.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:f.id,name:f.function?.name,argumentsDelta:f.function?.arguments}};p?.finish_reason&&(d=p.finish_reason)}let l=u.usage;l&&(a=l,yield{type:"usage",usage:ld(l)})}yield{type:"finish",reason:d??"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 od(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 dd(e)}case"dry-run":{let e={model:t.model,...t.extras};return kn(e)}case"fallback":{let e={provider:t.provider,model:t.model,...t.extras};return ad(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 cd(e)}default:{let e=t.provider;throw new Error(`createAdapter: unknown provider: ${String(e)}`)}}}Re();ne();ve();function kt(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 jt(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 qp(){return{input:{regular:0},output:{regular:0}}}function Lh(t,e){let n=e?.logMax??1e3,r=Ke(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:n}),o=A(null,{name:"adapterStats/lastCall"}),s=C([r.entries],([h])=>h.length,{name:"adapterStats/totalCalls",initial:0}),i=C([r.entries],([h])=>h.reduce((g,y)=>g+kt(y.usage),0),{name:"adapterStats/totalInputTokens",initial:0}),a=C([r.entries],([h])=>h.reduce((g,y)=>g+jt(y.usage),0),{name:"adapterStats/totalOutputTokens",initial:0}),d=[te(s),te(i),te(a)],u=h=>{r.append(h),o.emit(h)},c=()=>{r.clear(),o.emit(null)},l=ot(t,{invoke(h,g){let y=V(),b=se(),v=t.model??g?.model??"",T=x=>(u(xn({provider:t.provider,model:t.model??g?.model??x.model??"",tier:g?.tier??x.tier,usage:x.usage??_t(),startNs:y,startWallClockNs:b,method:"invoke"})),x),w=x=>{let k=x;u(xn({provider:t.provider,model:v,tier:g?.tier,usage:_t(),startNs:y,startWallClockNs:b,method:"invoke",error:{type:k?.name??"Error",message:k?.message??String(x)}}))};return Qs(t.invoke(h,g),{onResp:T,onError:w,name:"adapterStats/invokeTap"})},async*stream(h,g){let y=V(),b=se(),v=t.model??g?.model??"",T;try{for await(let w of t.stream(h,g))w.type==="usage"&&(T=w.usage),yield w;u(xn({provider:t.provider,model:v,tier:g?.tier,usage:T??_t(),startNs:y,startWallClockNs:b,method:"stream"}))}catch(w){let x=w;throw u(xn({provider:t.provider,model:v,tier:g?.tier,usage:T??_t(),startNs:y,startWallClockNs:b,method:"stream",error:{type:x?.name??"Error",message:x?.message??String(w)}})),w}}});Je(l,"observableAdapter",t);let p=!1;return{adapter:l,stats:{lastCall:o,allCalls:r,totalCalls:s,totalInputTokens:i,totalOutputTokens:a,reset:c,dispose:()=>{if(!p){p=!0;for(let h of d)h();d.length=0}}}}}function Ih(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function ti(t="USD"){return{total:0,currency:t}}function pd(t,e,n){let r=kt(t),o=e.currency??"USD",s=n?.withBreakdown===!0,i=s?{}:null,a=0,d=(g,y,b)=>{if(!y||b==null)return;let v=Ih(b,r),T=y*v/1e6;a+=T,s&&(i[g]=(i[g]??0)+T)},u=t.input,c=e.input;if(c&&(d("input.regular",u.regular,c.regular),d("input.cacheRead",u.cacheRead??0,c.cacheRead),d("input.cacheWrite5m",u.cacheWrite5m??0,c.cacheWrite5m),d("input.cacheWrite1h",u.cacheWrite1h??0,c.cacheWrite1h),d("input.cacheWriteOther",u.cacheWriteOther??0,c.cacheWriteOther),d("input.audio",u.audio??0,c.audio),d("input.image",u.image??0,c.image),d("input.video",u.video??0,c.video),d("input.toolUse",u.toolUse??0,c.toolUse),u.extensions&&c.extensions))for(let[g,y]of Object.entries(u.extensions))d(`input.ext.${g}`,y,c.extensions[g]);let l=t.output,p=e.output;if(p&&(d("output.regular",l.regular,p.regular),d("output.reasoning",l.reasoning??0,p.reasoning),d("output.audio",l.audio??0,p.audio),d("output.predictionAccepted",l.predictionAccepted??0,p.predictionAccepted),d("output.predictionRejected",l.predictionRejected??0,p.predictionRejected),l.extensions&&p.extensions))for(let[g,y]of Object.entries(l.extensions))d(`output.ext.${g}`,y,p.extensions[g]);let f=n?.tier;if(f&&e.tierMultipliers){let g=e.tierMultipliers[f];if(g!=null&&(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 ei(t,e){return`${t}::${e}`}function Ph(t){let e=new Map,n=new Map,r=(o,s,i)=>{e.set(ei(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(ei(o,s));if(i)return i.pricing;let a=n.get(o);if(!a)return;let d;for(let u of a)if(s.startsWith(u)&&(!d||u.length>d.key.length)){let c=e.get(ei(o,u));c&&(d={key:u,pricing:c.pricing})}return d?.pricing},remove(o,s){let i=e.delete(ei(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 Dh(t,e="USD"){return(n,r)=>{let o=t.lookup(r.provider,r.model);return o?pd(n,o,{tier:r.tier,withBreakdown:r.withBreakdown}):ti(e)}}function Gh(...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):ti()}}function Fh(t,e,n){return t?.pricing?pd(e,t.pricing,n):ti()}It();ve();function fd(t,e={}){let n=e.breaker??Nt(e),r=ot(t,{async invoke(o,s){if(!n.canExecute())throw new yt;try{let i=await et(Y(t.invoke(o,s)));return n.recordSuccess(),i}catch(i){throw n.recordFailure(i),i}},async*stream(o,s){if(!n.canExecute())throw new yt;try{for await(let i of t.stream(o,s))yield i;n.recordSuccess()}catch(i){throw n.recordFailure(i),i}}});return Je(r,"withBreaker",t),{adapter:r,breaker:n}}Re();ae();ne();ve();var ni=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"},md=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),zp=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function gd(t,e){let n=Ke(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),r=A(zp(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=C([r],([u])=>{let c=u;return!(e.caps.calls!=null&&c.calls>=e.caps.calls||e.caps.inputTokens!=null&&c.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&c.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&c.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(te(o),e.onExhausted!=null){let u=e.onExhausted,c=!1,l=!0;o.subscribe(p=>{for(let f of p)if(f[0]===M){let m=f[1];if(c&&l&&m===!1){let h=Hp(r.cache??md,e.caps);h&&u(h)}l=m,c=!0}})}let s=()=>{if(o.cache===!1){let u=r.cache??md,c=Hp(u,e.caps);return new ni(c??"budget",e.caps[c??"calls"]??0,$h(u,c??"calls"))}},i=(u,c)=>{let l=t.provider,p=xn({provider:l,model:c.model,tier:c.tier,usage:u,startNs:c.startNs,method:c.method,...c.error?{error:c.error}:{}});n.append(p);let f=r.cache??md,m=e.pricingFn?f.usd+e.pricingFn(u,{model:c.model,provider:l,tier:c.tier}).total:f.usd;r.emit({calls:f.calls+1,inputTokens:f.inputTokens+kt(u),outputTokens:f.outputTokens+jt(u),usd:m})},a=()=>{n.clear(),r.emit(zp())},d=ot(t,{invoke(u,c){let l=s();if(l)return Promise.reject(l);let p=V(),f=t.model??c?.model??"",m=g=>(i(g.usage??_t(),{model:t.model??c?.model??g.model??"",tier:c?.tier??g.tier,startNs:p,method:"invoke"}),g),h=g=>{let y=g;i(_t(),{model:f,tier:c?.tier,startNs:p,method:"invoke",error:{type:y?.name??"Error",message:y?.message??String(g)}})};return Qs(t.invoke(u,c),{onResp:m,onError:h,name:"budgetGate/invokeTap"})},async*stream(u,c){let l=s();if(l)throw l;let p=V(),f;try{for await(let m of t.stream(u,c))m.type==="usage"&&(f=m.usage),yield m;i(f??_t(),{model:t.model??c?.model??"",tier:c?.tier,startNs:p,method:"stream"})}catch(m){let h=m;throw i(f??_t(),{model:t.model??c?.model??"",tier:c?.tier,startNs:p,method:"stream",error:{type:h?.name??"Error",message:h?.message??String(m)}}),m}}});return Je(d,"withBudgetGate",t),{adapter:d,budget:{totals:r,isOpen:o,log:n,reset:a}}}function Hp(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 $h(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 jh(t,e){let n=e.mock??kn({provider:t.provider,model:t.model}),r=typeof e.enabled=="boolean"?e.enabled:void 0,o=r===void 0?Y(e.enabled):void 0,s;o&&(s=te(o));let i=()=>r!==void 0?r:!!o?.cache,a=ot(t,{invoke(u,c){return i()?n.invoke(u,c):t.invoke(u,c)},stream(u,c){return i()?n.stream(u,c):t.stream(u,c)}});return Je(a,"withDryRun",t),{adapter:a,dispose:()=>{s&&(s(),s=void 0)}}}function hd(t){if(t==null||typeof t!="object")return;let e=t,n=e.status,r=Bh(e.headers);if(n!==429&&n!==503&&!Wh(e.message))return;let o={},s=r("retry-after"),i=Kh(s);i!=null&&(o.retryAfterMs=i);let a=r("anthropic-ratelimit-requests-reset");if(a){let f=Wp(a);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let d=r("anthropic-ratelimit-tokens-reset");if(d){let f=Wp(d);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let u=ri(r,"x-ratelimit-limit-requests");u!=null&&(o.rpmCap=u);let c=ri(r,"x-ratelimit-limit-tokens");c!=null&&(o.tpmCap=c);let l=ri(r,"x-ratelimit-remaining-requests"),p=ri(r,"x-ratelimit-remaining-tokens");if(l!=null&&u!=null&&u>0&&(o.usageHint??={},o.usageHint.rpm=1-l/u),p!=null&&c!=null&&c>0&&(o.usageHint??={},o.usageHint.tpm=1-p/c),o.retryAfterMs==null&&e.message){let f=zh(e.message);f!=null&&(o.retryAfterMs=f)}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 ri(t,e){let n=t(e);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function Kh(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 Wp(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var qh=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function zh(t){let e=qh.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 Hh=/rate\s*limit|too\s*many\s*requests|quota|429/i;function Wh(t){return!!t&&Hh.test(t)}Re();ae();ne();It();ve();Rt();function yd(t){let e=new Error(t);return e.name="AbortError",e}function Jp(t={}){let e=Math.max(1,t.burstMultiplier??1),n=t.clampCooldownMs??6e4,r=t.rpm!=null?Y(t.rpm):A(Number.POSITIVE_INFINITY),o=t.tpm!=null?Y(t.tpm):A(Number.POSITIVE_INFINITY),s=A(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),i=A(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),a=A({},{name:"adaptiveRateLimiter/lastSignal"}),d=C([r,s],([N,L])=>Math.min(Number(N??1/0),Number(L??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),u=C([o,i],([N,L])=>Math.min(Number(N??1/0),Number(L??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),c=dr(Number(r.cache??Number.POSITIVE_INFINITY),e),l=dr(Number(o.cache??Number.POSITIVE_INFINITY),e),p=!1,f=!1,m=d.subscribe(N=>{for(let L of N)if(L[0]===M){let j=Number(L[1]);Number.isFinite(j)&&j>0?(c=dr(j,e),p=!1):j===1/0?(c=dr(1/0,e),p=!1):j<=0&&(p=!0)}}),h=u.subscribe(N=>{for(let L of N)if(L[0]===M){let j=Number(L[1]);Number.isFinite(j)&&j>0?(l=dr(j,e),f=!1):j===1/0?(l=dr(1/0,e),f=!1):j<=0&&(f=!0)}}),g=0,y=new Ie,b=new Ie,v;t.adaptation!=null&&(v=Y(t.adaptation).subscribe(L=>{for(let j of L)j[0]===M&&T(j[1])}));function T(N){if(a.emit(N),N.rpmCap!=null&&Number.isFinite(N.rpmCap)&&N.rpmCap>=0&&(s.emit(N.rpmCap),Number.isFinite(n)&&n>0&&y.start(n,()=>s.emit(Number.POSITIVE_INFINITY))),N.tpmCap!=null&&Number.isFinite(N.tpmCap)&&N.tpmCap>=0&&(i.emit(N.tpmCap),Number.isFinite(n)&&n>0&&b.start(n,()=>i.emit(Number.POSITIVE_INFINITY))),N.retryAfterMs!=null&&N.retryAfterMs>0){let L=V()+N.retryAfterMs*1e6;L>g&&(g=L)}}let w=A(0,{name:"adaptiveRateLimiter/pending"}),x=A(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),k=A(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),S=N=>{w.emit((w.cache??0)+N)},R=()=>{x.emit(c.available()),k.emit(l.available())};async function E(N={}){let L=N.requestCost??1,j=N.tokenCost??0,$=N.signal;S(1);try{for(;;){if($?.aborted)throw yd("AdaptiveRateLimiter.acquire aborted");let D=V();if(g>D){let B=Math.ceil((g-D)/1e6);await oi(B,$);continue}if(L>0&&p||j>0&&f){await oi(250,$);continue}let K=c,F=l;if(!K.tryConsume(L)){await oi(Up(K,L),$);continue}if(!(j>0?F.tryConsume(j):!0)){K.putBack(L),await oi(Up(F,j),$);continue}R();return}}finally{S(-1)}}function _(N){N>0?l.tryConsume(N):N<0&&l.putBack(-N),R()}function O(){m(),h(),v?.(),y.cancel(),b.cancel()}return{effectiveRpm:d,effectiveTpm:u,lastSignal:a,pending:w,rpmAvailable:x,tpmAvailable:k,acquire:E,recordUsage:_,recordSignal:T,dispose:O}}function dr(t,e){if(!Number.isFinite(t)||t===1/0)return zt(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let n=Math.max(1,t*e),r=t/60;return zt(n,r)}function Up(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 oi(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(yd("AdaptiveRateLimiter.acquire aborted")):new Promise((n,r)=>{let o=new Ie,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(yd("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",s,{once:!0}))})}ve();function bd(t,e={}){let n=e.limiter??Jp({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=hd(i);a&&n.recordSignal(a)},s=ot(t,{async invoke(i,a){let d=r(i,a);await n.acquire({requestCost:1,tokenCost:d,signal:a?.signal});try{let u=await et(Y(t.invoke(i,a))),c=u.usage??qp(),p=kt(c)+jt(c)-d;return p>0&&n.recordUsage(p),u}catch(u){throw o(u),u}},async*stream(i,a){let d=r(i,a);await n.acquire({requestCost:1,tokenCost:d,signal:a?.signal});try{let u=0;for await(let l of t.stream(i,a))l.type==="usage"&&(u=kt(l.usage)+jt(l.usage)),yield l;let c=u-d;c>0&&n.recordUsage(c)}catch(u){throw o(u),u}}});return Je(s,"withRateLimiter",t),{adapter:s,limiter:n}}It();ve();var vo=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 vd(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:Nt(s.breaker):void 0})),r=e.streamRetryBeforeFirstChunk??!0,o={provider:"cascading",model:void 0,async invoke(s,i){let a=[],d=new Map;for(let c=0;c<n.length;c++){let l=n[c];if(l.filter&&!l.filter(s,i)){a.push({name:l.name,reason:"filter"});continue}if(l.breaker&&!l.breaker.canExecute()){a.push({name:l.name,reason:"breaker"});continue}try{let p=await et(Y(l.adapter.invoke(s,i)));return l.breaker?.recordSuccess(),{...p,metadata:{...p.metadata??{},tier:l.name}}}catch(p){d.set(l.name,p),l.breaker?.recordFailure(p);let f=n[c+1];f&&e.onFallback?.(l.name,f.name,p)}}let u={skipped:a,failed:d};throw e.onExhausted?.(u),new vo(u)},async*stream(s,i){let a=[],d=new Map;for(let c=0;c<n.length;c++){let l=n[c];if(l.filter&&!l.filter(s,i)){a.push({name:l.name,reason:"filter"});continue}if(l.breaker&&!l.breaker.canExecute()){a.push({name:l.name,reason:"breaker"});continue}let p=!1;try{for await(let f of l.adapter.stream(s,i))p=!0,yield f;l.breaker?.recordSuccess();return}catch(f){if(d.set(l.name,f),l.breaker?.recordFailure(f),p||!r)throw f;let m=n[c+1];m&&e.onFallback?.(l.name,m.name,f)}}let u={skipped:a,failed:d};throw e.onExhausted?.(u),new vo(u)}};return Je(o,`cascade[${n.map(s=>s.name).join(",")}]`),o}function Uh(t,e,n){let r={name:t,adapter:e};return n?.breaker&&(r.breaker=n.breaker),n?.filter&&(r.filter=n.filter),r}ve();Rt();function si(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function Yp(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(si()):new Promise((n,r)=>{let o=new Ie,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(si())},e.addEventListener("abort",s,{once:!0}))})}function Td(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??Jh,d=e.retryStreaming??!0,u=(l,p)=>{if(s==="decorrelated"){let g=Math.min(o,Math.max(r,p*3));return r+Math.random()*(g-r)}let f=s==="exp"?r*2**(l-1):r*l,m=Math.min(o,f);if(!i)return m;let h=m*(.5+Math.random());return Math.min(o,h)},c=ot(t,{async invoke(l,p){if(p?.signal?.aborted)throw si();let f,m=r;for(let h=1;h<=n;h++)try{return await et(Y(t.invoke(l,p)))}catch(g){if(f=g,h>=n||!a(g,h))throw g;let y=u(h,m);m=y,await Yp(y,p?.signal)}throw f},async*stream(l,p){if(p?.signal?.aborted)throw si();if(!d){for await(let h of t.stream(l,p))yield h;return}let f,m=r;for(let h=1;h<=n;h++){let g=!1;try{for await(let y of t.stream(l,p))g=!0,yield y;return}catch(y){if(f=y,g||h>=n||!a(y,h))throw y;let b=u(h,m);m=b,await Yp(b,p?.signal)}}throw f}});return Je(c,"withRetry",t),c}function Jh(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();Rt();var ur=class extends Error{constructor(n){super(`LLM call timed out after ${n}ms`);this.ms=n}name="LLMTimeoutError"};function wd(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let n=s=>{let i=new AbortController,a=!1,d,u=new Ie;return s&&(s.aborted?i.abort(s.reason):(d=()=>{u.cancel(),i.abort(s.reason)},s.addEventListener("abort",d,{once:!0}))),u.start(e,()=>{a=!0,i.abort(new ur(e))}),{signal:i.signal,cancel:()=>{u.cancel(),s&&d&&s.removeEventListener("abort",d)},timedOut:()=>a}},r=(s,i)=>{if(!i||s instanceof ur)throw s;let a=s;if(a?.name==="AbortError"||a?.name==="DOMException"&&Number(a.code)===20||s?.message==="aborted"){let u=new ur(e);throw u.cause=s,u}throw s},o=ot(t,{async invoke(s,i){let{signal:a,cancel:d,timedOut:u}=n(i?.signal);try{return await et(Y(t.invoke(s,{...i,signal:a})))}catch(c){return r(c,u())}finally{d()}},async*stream(s,i){let{signal:a,cancel:d,timedOut:u}=n(i?.signal);try{for await(let c of t.stream(s,{...i,signal:a}))yield c}catch(c){r(c,u())}finally{d()}}});return Je(o,"withTimeout",t),o}function Yh(t,e={}){let n={adapter:t},r=t;if(e.rateLimit){let o=bd(r,e.rateLimit);r=o.adapter,n.rateLimiter=o.limiter}if(e.budget){let o=gd(r,e.budget);r=o.adapter,n.budget=o.budget}if(e.breaker){let o=fd(r,e.breaker);r=o.adapter,n.breaker=o.breaker}if(e.timeoutMs!=null&&(r=wd(r,e.timeoutMs)),e.retry&&(r=Td(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=vd([{name:e.name??"primary",adapter:r},{name:"fallback",adapter:e.fallback}],o)}return e.cache&&(r=bo(r,e.cache)),n.adapter=r,n}ne();ve();function Qh(t,e,n){let r=Y(e);return ke(r,s=>{if(!s||s.length===0)return A(null);let i=n?.tools;return t.invoke(s,{model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,tools:i,systemPrompt:n?.systemPrompt})})}it();Me();ve();ae();ve();Rt();function he(t,e){return We("ai",t,e)}function Xh(t){return t!=null&&typeof t.then=="function"}function kd(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function Zh(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var ey=3e4;function Qp(t,e){if(t.status==="settled"){let r=t.cache;if(r!==void 0)return Promise.resolve(r)}let n=e?.timeoutMs??ey;return new Promise((r,o)=>{let s=new Ie,i=t.subscribe(a=>{for(let d of a){if(d[0]===M){s.cancel(),i(),r(d[1]);return}if(d[0]===I){s.cancel(),i(),o(d[1]);return}if(d[0]===P){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 To(t){return Xh(t)?To(await t):kd(t)?Qp(t):Zh(t)?Qp(Y(t)):t}function cr(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function ty(t,e){let n=Y(t),r=e?.refreshTrigger!=null?Y(e.refreshTrigger):null,o=e?.name!==void 0?{name:e.name}:void 0,s=we("frozenContext",o);return r==null?U([n],(i,a,d)=>{if(d.store.emitted===!0)return;let c=i[0],l=c!=null&&c.length>0?c.at(-1):d.prevData[0];if(l!==void 0)return d.store.emitted=!0,a.emit(l),{invalidate:()=>{d.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:he("frozen_context",{...s})}):U([n,r],(i,a,d)=>{let u=i[1];if(!(u!=null&&u.length>0))return;let l=i[0],p=l!=null&&l.length>0?l.at(-1):d.prevData[0];a.emit(p)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:he("frozen_context",{...s})})}ae();ne();ve();function Xp(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function ny(t,e=200){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Sn(t,e,n,r){let o=r?.format??"text",s=r?.name??"prompt_node",i=C(e,d=>{if(d.some(c=>c==null))return[];let u=typeof n=="string"?n:n(...d);return u?[{role:"user",content:u}]:[]},{name:`${s}::messages`,meta:he("prompt_node")});return ke(i,d=>!d||d.length===0?A(null):z(u=>{let c=!1,l=!1,p,f={model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt};if(r?.abort){let y=ds(r.abort);f.signal=y.signal,p=y.dispose}let m;try{m=t.invoke(d,f)}catch(y){return c=!0,u.down([[I,y]]),()=>{p?.()}}let g=Y(m).subscribe(y=>{if(!(l||c))for(let b of y){if(c)return;if(b[0]===M){let v=b[1];try{let T=Xp(v),w=o==="json"?JSON.parse(cr(T)):T;u.emit(w)}catch(T){let w=Xp(v),x=new Error(`promptNode: failed to parse LLM response as JSON: ${T.message}
|
|
37
|
+
Raw content (first 200 chars): ${ny(w)}`);c=!0,u.down([[I,x]]);return}}else if(b[0]===I){c=!0,u.down([[I,b[1]]]);return}else if(b[0]===P){c=!0,u.down([[P]]);return}else u.down([b])}});return()=>{l=!0,g(),p?.()}},{name:`${s}::call`,meta:he("prompt_node::call")}),{name:`${s}::output`,meta:r?.meta?{...he("prompt_node::output"),...r.meta}:he("prompt_node::output")})}Ae();Re();it();ne();ve();var li={};Se(li,{MessagingHubGraph:()=>di,SubscriptionGraph:()=>wo,TopicBridgeGraph:()=>ii,TopicGraph:()=>Nn,TopicRegistry:()=>ai,messagingHub:()=>ko,subscription:()=>Zp,topic:()=>ui,topicBridge:()=>ci});Me();var ry=256;function lr(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function en(t,e){return We("messaging",t,e)}var oy=1024,Nn=class extends Q{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=Ke([],{name:"events",maxSize:n.retainedLimit??oy}),this._log.withLatest(),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=C([this.events],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:en("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(te(this.latest)),this.hasLatest=C([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:en("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(te(this.hasLatest)),this.addDisposer(()=>{this.events.down([[P]])}),this.addDisposer(()=>this._log.disposeAllViews())}publish(e){if(e===void 0)throw new TypeError(`TopicGraph "${this.name}": publish(undefined) is not allowed (spec \xA75.12 SENTINEL).`);this._log.append(e)}attachEventStorage(e){return this._log.attachStorage(e)}retained(){return this.events.cache}get _logBundle(){return this._log}},wo=class extends Q{cursor;available;topic;_disposed=!1;constructor(e,n,r={}){super(e,r.graph),this.topic=n;let o;if(r.from!==void 0?r.from==="retained"?o=0:r.from==="now"?o=n.events.cache.length:o=lr(r.from,"subscription from"):o=lr(r.cursor??0,"subscription cursor"),this.cursor=A(o,{name:"cursor",describeKind:"state",meta:en("subscription_cursor")}),this.add(this.cursor,{name:"cursor"}),this.available=n._logBundle.view({kind:"fromCursor",cursor:this.cursor}),this.add(this.available,{name:"available"}),this.addDisposer(te(this.available)),r.advanceOn!==void 0){let s=r.advanceOn,i=!1,a=U([s],()=>{if(!i){i=!0;return}if(this._disposed)return;let d=this.available.cache;if(d.length===0)return;let u=this.cursor.cache+d.length;this.cursor.emit(u)},{name:"advancePump",describeKind:"effect",meta:en("subscription_advance_pump")});this.add(a,{name:"advancePump"}),this.addDisposer(te(a))}}ack(e){if(this._disposed)return this.cursor.cache;let n=this.available.cache,r=e===void 0?n.length:lr(e,"subscription ack count"),o=Math.min(r,n.length);if(o<=0)return this.cursor.cache;let s=this.cursor.cache+o;return this.cursor.emit(s),s}pull(e){if(this._disposed)return[];let n=this.available.cache,r=e===void 0?n.length:lr(e,"subscription pull limit");return n.slice(0,r)}pullAndAck(e){if(this._disposed)return{items:[],cursor:this.cursor.cache};let n=this.available.cache,r=e===void 0?n.length:lr(e,"subscription pullAndAck limit"),o=n.slice(0,r);if(o.length===0)return{items:o,cursor:this.cursor.cache};let s=this.cursor.cache+o.length;return this.cursor.emit(s),{items:o,cursor:s}}dispose(){this._disposed||(this._disposed=!0,this.cursor.down([[P]]),this.destroy())}},ii=class extends Q{_sourceSub;bridgedCount;output;constructor(e,n,r,o={}){super(e,o.graph),this._sourceSub=Zp(`${e}-subscription`,n,{cursor:o.cursor}),this.mount("subscription",this._sourceSub);let s=Math.max(1,lr(o.maxPerPump??ry,"topic bridge maxPerPump")),i=o.map??(p=>p);this.output=C([this._sourceSub.available],([p])=>{let f=p,m=[],h=Math.min(f.length,s);for(let g=0;g<h;g++){let y=i(f[g]);y!==void 0&&m.push(y)}return m},{name:"output",describeKind:"derived",meta:en("topic_bridge_output",{targetRef:r.name}),initial:[]}),this.add(this.output,{name:"output"}),this.addDisposer(te(this.output)),this.bridgedCount=A(0,{name:"bridgedCount",describeKind:"state",meta:en("topic_bridge_count")}),this.add(this.bridgedCount,{name:"bridgedCount"}),this.addDisposer(te(this.bridgedCount));let a=this.output,d=this._sourceSub,u=this.bridgedCount,c=U([a],()=>{let p=a.cache;if(p.length===0)return;let f=d.available.cache.length,m=Math.min(f,s);if(m>0){d.ack(m);let h=u.cache??0;u.emit(h+p.length)}},{name:"ackPump",describeKind:"effect",meta:en("topic_bridge_ack_pump")});this.add(c,{name:"ackPump"}),this.addDisposer(te(c));let l=sy(this.output,r);this.addDisposer(l)}};function sy(t,e){return t.subscribe(n=>{for(let r of n){if(r[0]!==M)continue;let o=r[1];o.length!==0&&Z(()=>{for(let s of o)e.publish(s)})}})}var ai=class{_map=new Map;version;constructor(e){this.version=e}get size(){return this._map.size}has(e){return this._map.has(e)}get(e){return this._map.get(e)}set(e,n){this._map.set(e,n)}delete(e){return this._map.delete(e)}keys(){return this._map.keys()}},di=class extends Q{_registry;version;_defaultTopicOptions;constructor(e,n={}){super(e,n.graph);let r=A(0,{name:"version",describeKind:"state",meta:en("hub_version")});this.add(r,{name:"version"}),this.version=r,this._registry=new ai(r),this._defaultTopicOptions={...n.defaultTopicOptions??{}}}get size(){return this._registry.size}has(e){return this._registry.has(e)}topicNames(){return this._registry.keys()}topic(e,n){let r=this._registry.get(e);if(r===void 0){let o={...this._defaultTopicOptions,...n??{}};r=new Nn(e,o),this._registry.set(e,r),this.mount(e,r);let s=this.version.cache??0;this.version.emit(s+1)}return r}publish(e,n){this.topic(e).publish(n)}publishMany(e){Z(()=>{for(let[n,r]of e)this.topic(n).publish(r)})}subscribe(e,n,r){let o=this.topic(n);return new wo(e,o,r)}removeTopic(e){if(!this._registry.has(e))return!1;try{this.remove(e)}finally{this._registry.delete(e);let n=this.version.cache??0;this.version.emit(n+1)}return!0}};function ui(t,e){return new Nn(t,e)}function ko(t,e){return new di(t,e)}function Zp(t,e,n){return new wo(t,e,n)}function ci(t,e,n,r){return new ii(t,e,n,r)}var pi={};Se(pi,{PipelineGraph:()=>Ro,decisionKeyOf:()=>ef,pipelineGraph:()=>pr});Ae();Re();ae();it();Me();ne();function xo(t,e){return We("orchestration",t,e)}var ef=t=>t.action,Ro=class extends Q{constructor(e,n){super(e,n)}task(e,n,r={}){let o=(r.deps??[]).map(i=>this._resolveStep(i)),s=C(o,n,{name:e,describeKind:"derived",meta:xo("task",r.meta)});return this.add(s,{name:e}),s}classify(e,n,r,o={}){let s=this._resolveStep(n),i=C([s],([a])=>{try{return{tag:r(a),value:a}}catch(d){return{tag:"error",value:a,error:d}}},{name:e,describeKind:"derived",meta:xo("classify",o.meta)});return this.add(i,{name:e}),i}combine(e,n,r={}){let o=Object.keys(n),s=o.map(a=>this._resolveStep(n[a])),i=C(s,a=>{let d={};for(let u=0;u<o.length;u++)d[o[u]]=a[u];return d},{name:e,describeKind:"derived",meta:xo("combine",r.meta)});return this.add(i,{name:e}),i}gate(e,n,r={}){let o=r.maxPending??1e3;if(o<1&&o!==Number.POSITIVE_INFINITY)throw new RangeError("gate: maxPending must be >= 1");let s=r.startOpen??!1;typeof n!="string"&&this.nameOf(n)===void 0&&this.add(n,{name:`${e}/source`});let i=this._resolveStep(n),a=new Q(`${e}_state`),d=A([],{name:"pending",equals:()=>!1}),u=A(s,{name:"isOpen"}),c=C([d],([F])=>F.length,{name:"count"}),l=A(0,{name:"droppedCount"}),p=at({name:"decisions",retainedLimit:1024,graph:a});a.add(d,{name:"pending"}),a.add(u,{name:"isOpen"}),a.add(c,{name:"count"}),a.add(l,{name:"droppedCount"}),this.mount(`${e}_state`,a);let f=[],m=!1,h=!1,g=s,y=u.subscribe(F=>{for(let H of F)H[0]===M&&(g=H[1])});this.addDisposer(y);function b(){d.emit([...f])}function v(F,H,G){p.append({action:F,t_ns:se(),...H!==void 0?{items:H,count:H.length}:{},...G!==void 0?{unflushed:G}:{},...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}function T(F){if(f.push(F),f.length>o){let H=f.shift();l.emit(l.cache+1),v("drop",[H])}b()}function w(F){let H=f.splice(0,F);return b(),H}let x=U([i],(F,H,G)=>{let B=G.terminalDeps[0];if(B!==void 0){m=!0;let pe=f.length;f=[],b(),v("teardown",void 0,pe),H.down(B===!0?[[P]]:[[I,B]]);return}let re=F[0];if(re==null||re.length===0){H.down([[q]]);return}for(let pe of re)g?H.emit(pe):(T(pe),H.down([[q]]))},{name:e,describeKind:"derived",meta:xo("gate",r.meta)});if(this.add(x,{name:e}),r.approver!=null){r.approver.cache&&(u.emit(!0),g=!0,r.onceOnly&&(h=!0));let H=r.approver.subscribe(G=>{for(let B of G){if(B[0]!==M)continue;let re=!!B[1];if(re&&!g){if(r.onceOnly){if(h)continue;h=!0}Z(()=>{u.emit(!0);let pe=w(f.length);v("open",pe);for(let ee of pe){if(m)break;x.emit(ee)}})}else if(!re&&g){if(r.onceOnly&&h)continue;Z(()=>{u.emit(!1),v("close")})}}});this.addDisposer(H)}let k=F=>{if(m)throw new Error(`gate: ${F}() called after gate was torn down`)},S=(F=1)=>{k("approve");let H=w(F);for(let G of H){if(m)break;x.emit(G)}},R=(F=1)=>{k("reject"),w(F)},E=(F,H=1)=>{k("modify");let G=[...f],B=w(H);for(let re=0;re<B.length&&!m;re++)x.emit(F(B[re],re,G))},_=()=>{k("open"),u.emit(!0);let F=w(f.length);for(let H of F){if(m)break;x.emit(H)}},O=()=>{k("close"),!(r.onceOnly&&h)&&u.emit(!1)},N=nr(S,{audit:p,freeze:!1,onSuccess:(F,H,G)=>({action:"approve",count:F[0]??1,t_ns:G.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,H,G)=>({action:"drop",t_ns:G.t_ns,errorType:G.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),L=nr(R,{audit:p,freeze:!1,onSuccess:(F,H,G)=>({action:"reject",count:F[0]??1,t_ns:G.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,H,G)=>({action:"drop",t_ns:G.t_ns,errorType:G.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),j=nr(E,{audit:p,freeze:!1,onSuccess:(F,H,G)=>({action:"modify",count:F[1]??1,t_ns:G.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,H,G)=>({action:"drop",t_ns:G.t_ns,errorType:G.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),$=nr(_,{audit:p,freeze:!1,onSuccess:(F,H,G)=>({action:"open",t_ns:G.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,H,G)=>({action:"drop",t_ns:G.t_ns,errorType:G.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),D=nr(O,{audit:p,freeze:!1,onSuccess:(F,H,G)=>({action:"close",t_ns:G.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,H,G)=>({action:"drop",t_ns:G.t_ns,errorType:G.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})});return this.addDisposer(c.subscribe(()=>{})),{node:x,pending:d,count:c,isOpen:u,droppedCount:l,decisions:p,audit:p,approve:N,reject:L,modify:j,open:$,close:D}}approval(e,n,r,o={}){return this.gate(e,n,{...o,approver:r,maxPending:1})}catch(e,n,r,o={}){let s=this._resolveStep(n),i=o.on??"error",a=U([s],(d,u,c)=>{let l=c.terminalDeps[0];if(l!==void 0){let f=l===!0?{kind:"complete"}:{kind:"error",error:l};if(i==="terminal"||i===f.kind){u.emit(r(f,u));return}u.down(f.kind==="complete"?[[P]]:[[I,f.error]]);return}let p=d[0];if(p==null||p.length===0){u.down([[q]]);return}for(let f of p)u.emit(f)},{name:e,describeKind:"derived",completeWhenDepsComplete:o.completeWhenDepsComplete??!(i==="complete"||i==="terminal"),errorWhenDepsError:!(i==="error"||i==="terminal"),meta:xo("catch",o.meta)});return this.add(a,{name:e}),a}_resolveStep(e){if(typeof e=="string")return this.resolve(e);if(this.nameOf(e)===void 0)throw new Error(`PipelineGraph "${this.name}": Node dep is not registered. Pass a string path or call graph.add(node) first.`);return e}};function pr(t,e){let n=new Ro(t,e),{factory:r,factoryArgs:o,...s}=e??{};return n.tagFactory("pipelineGraph",st(s)),n}async function tf(t,e,n,r){let o="",s=0;for await(let i of t.stream(e,n))r.publish({...i,seq:s++,ts:se()}),i.type==="token"&&(o+=i.delta);return o}function nf(t,e){if(e==="json")try{return JSON.parse(cr(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 rf(t,e){return C([t.latest],([n],r)=>{let o=r.store;if(n==null)return o.acc??"";let s=n;return s.seq===0&&(o.acc=""),s.type==="token"&&(o.acc=(o.acc??"")+s.delta),o.acc??""},{name:e,meta:he("accumulated_text"),initial:""})}function iy(t,e,n,r){let o=r?.name??"llm",s=r?.format??"text",i=ui(`${o}/stream`,{...r?.retainedLimit!=null?{retainedLimit:r.retainedLimit}:{}}),a=C(e,l=>{if(l.some(f=>f==null))return[];let p=typeof n=="string"?n:n(...l);return p?[{role:"user",content:p}]:[]},{name:`${o}::messages`,meta:he("prompt_node::messages"),initial:[]}),d=ke(a,l=>{let p=l;if(!p||p.length===0)return A(null);let f=new AbortController;async function*m(){try{let h=await tf(t,p,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,signal:f.signal},i);yield nf(h,s)}finally{f.abort()}}return Y(m())},{meta:we("streamingPromptNode")}),u=rf(i,`${o}::accumulatedText`),c=te(d);return{output:d,deltaTopic:i,accumulatedText:u,dispose:()=>{c(),i.destroy()}}}function ay(t,e,n,r,o,s){let i=A(0,{name:`${e}/cancel`}),a=0,d=[...r,i],u=s?.name??e,c=s?.format??"text",l=ui(`${u}/stream`,{...s?.retainedLimit!=null?{retainedLimit:s.retainedLimit}:{}}),p=C(d,k=>{let S=k.slice(0,-1);if(S.some(E=>E==null))return[];let R=typeof o=="string"?o:o(...S);return R?[{role:"user",content:R}]:[]},{name:`${u}::messages`,meta:he("prompt_node::messages"),initial:[]}),f=ke(p,k=>{let S=k;if(!S||S.length===0)return A(null);let R=new AbortController;async function*E(){try{let _=await tf(n,S,{model:s?.model,temperature:s?.temperature,maxTokens:s?.maxTokens,systemPrompt:s?.systemPrompt,signal:R.signal},l);yield nf(_,c)}finally{R.abort()}}return Y(E())},{meta:we("gatedStream")}),m=rf(l,`${u}::accumulatedText`),h=rt(f,k=>k!=null);t.add(h,{name:`${e}/raw`});let g=pr(`${e}/gate-graph`);t.mount(`${e}/gate-graph`,g),g.add(h,{name:`${e}/raw`});let y=g.gate(`${e}/gate`,`${e}/raw`,s?.gate),b=te(f),v=te(y.node),T=te(m);t.addDisposer(b),t.addDisposer(v),t.addDisposer(T);let w=y.reject.bind(y),x={...y,reject(k=1){Z(()=>{w(k),i.emit(++a)})}};return{output:y.node,deltaTopic:l,accumulatedText:m,gate:x,dispose:()=>{b(),v(),T(),l.destroy()}}}ne();ve();function dy(t,e){let n=e?.separator??`
|
|
38
38
|
|
|
39
|
-
`,r=t.map(i=>typeof i=="string"?M(i):U(i)),o=A(r,i=>i.filter(a=>a!=null&&a!=="").join(n),{name:e?.name??"systemPrompt",describeKind:"derived",meta:fe("system_prompt"),initial:""}),s=re(o);return Object.assign(o,{dispose:s})}ee();var Kh=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens&&t.estimated===e.estimated;function qh(t,e){let n=e?.charsPerToken??4,r={chunkCount:0,charCount:0,estimatedTokens:0,estimated:!0};return A([t.latest],([o],s)=>{if(o==null)return r;let i=o;"chunkCount"in s.store||(s.store.chunkCount=0,s.store.charCount=0,s.store.usageTokens=0,s.store.sawUsage=!1);let a=s.store;i.type==="token"?(a.chunkCount+=1,a.charCount+=i.delta.length):i.type==="usage"&&(a.sawUsage=!0,a.usageTokens=yt(i.usage)+Gt(i.usage));let u=a.sawUsage?a.usageTokens:Math.ceil(a.charCount/n);return{chunkCount:a.chunkCount,charCount:a.charCount,estimatedTokens:u,estimated:!a.sawUsage}},{name:e?.name??"cost-meter",describeKind:"derived",initial:r,meta:fe("cost_meter_extractor"),equals:Kh})}ee();var Hh=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.label!==o.label||r.pattern!==o.pattern||r.match!==o.match||r.position!==o.position)return!1}return!0};function Wh(t,e){let n=e.maxPatternLength??128;for(let o of e.patterns)if(o.pattern.source.length>n)throw new Error(`keywordFlagExtractor: pattern "${o.label}" literal exceeds maxPatternLength (${o.pattern.source.length} > ${n}); raise the option or shorten the pattern.`);let r=e.patterns.map(o=>({label:o.label,pattern:o.pattern,compiled:new RegExp(o.pattern.source,`${o.pattern.flags.replace("g","")}g`)}));return A([t],([o],s)=>{if(o==null)return[];let i=o;"flags"in s.store||(s.store.flags=[],s.store.scannedTo=0);let a=s.store.flags,u=s.store.scannedTo,d=Math.max(0,u-n),c=i.slice(d),l=!1;for(let{pattern:p,label:f,compiled:m}of r){m.lastIndex=0;for(let h of c.matchAll(m)){let g=d+(h.index??0);g+h[0].length<=u||(a.push({label:f,pattern:p,match:h[0],position:g}),l=!0)}}return s.store.scannedTo=i.length,l?[...a]:a.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:fe("keyword_flag_extractor"),equals:Hh})}ee();function zh(t,e,n){return A([t],([r])=>r==null?null:e(r),{name:n?.name??"extractor",describeKind:"derived",initial:null,meta:fe("stream_extractor"),...n?.equals?{equals:n.equals}:{}})}ee();var Uh=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.startIndex!==o.startIndex||r.name!==o.name||r.raw!==o.raw)return!1}return!0};function Jh(t,e){return A([t],([n],r)=>{if(n==null)return[];let o=n;"calls"in r.store||(r.store.calls=[],r.store.scanFrom=0);let s=r.store.calls,i=r.store.scanFrom,a=!1;for(;i<o.length;){let u=o.indexOf("{",i);if(u===-1){r.store.scanFrom=o.length;break}let d=0,c=-1,l=!1;for(let f=u;f<o.length;f++){let m=o[f];if(l)m==="\\"&&f+1<o.length?f++:m==='"'&&(l=!1);else if(m==='"')l=!0;else if(m==="{")d++;else if(m==="}"&&(d--,d===0)){c=f;break}}if(c===-1){r.store.scanFrom=u;break}let p=o.slice(u,c+1);try{let f=JSON.parse(p);typeof f.name=="string"&&f.arguments!=null&&typeof f.arguments=="object"&&(s.push({name:f.name,arguments:f.arguments,raw:p,startIndex:u}),a=!0)}catch{}i=c+1,r.store.scanFrom=i}return a?[...s]:s.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:fe("tool_call_extractor"),equals:Uh})}ee();function Yh(t,e,n,r){let o=n*(r?.hardMultiplier??1.5),s=typeof e!="function",i=[t];return s&&i.push(e),A(i,a=>{let u=a[0]??"";if(u.length===0)return"allow";let d=s?a[1]??0:e(u);return d>=o?"block":d>=n?"review":"allow"},{name:r?.name??"content-gate",initial:"allow"})}ee();function Qh(t,e,n,r){let o=n??(()=>"[REDACTED]");function s(i){let a=i;for(let u of e){let d=u.global?u:new RegExp(u.source,`${u.flags}g`);a=a.replace(d,c=>o(c,u))}return a}return A([t],([i])=>s(i??""),{name:r?.name??"redactor",initial:""})}Me();ae();_e();ee();he();ee();var ii=class extends Y{_log;messages;latest;messageCount;constructor(e,n={}){super(e,n.graph),this._log=Ve([],{name:"messages",maxSize:n.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=A([this.messages],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:fe("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(re(this.latest)),this.messageCount=A([this.messages],([r])=>r.length,{name:"messageCount",describeKind:"derived",meta:fe("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(re(this.messageCount))}append(e,n,r){this._log.append({role:e,content:n,...r})}appendToolResult(e,n){this._log.append({role:"tool",content:n,toolCallId:e})}clear(){this._log.clear()}allMessages(){return this.messages.cache}};function pu(t,e){return new ii(t,e)}ee();Ot();function fu(t){let{toolCalls:e,tools:n}=t,r=t.retryCount??1,o=t.onError??"rescue",s=(i,a)=>{if(i===a)return!0;if(i.length!==a.length)return!1;for(let u=0;u<i.length;u++){let d=i[u],c=a[u];if(d?.id!==c?.id||d?.content!==c?.content)return!1}return!0};return Te(e,i=>{if(i==null||i.length===0)throw new Error("toolExecution: received an empty tool-call batch as DATA \u2014 callers must upstream-filter empty batches (emit RESOLVED) so switchMap is only dispatched for non-empty batches.");let a=i.map(u=>Xh(u,n,r,o));return A(a,u=>u,{name:"toolExecution::batch",equals:s})})}function Xh(t,e,n,r){let o=Tt(()=>e.executeReactive(t.name,t.arguments),{count:n}),s=A([o],([i])=>({id:t.id,content:typeof i=="string"?i:JSON.stringify(i)}));return r==="propagate"?s:Yr(s,i=>({id:t.id,content:JSON.stringify({error:String(i)})}))}ae();ee();he();var ai=class extends Y{definitions;schemas;_bundle;constructor(e,n={}){super(e,n.graph),this._bundle=Ze({name:"definitions"}),this.definitions=this._bundle.entries,this.add(this.definitions,{name:"definitions"}),this.schemas=A([this.definitions],([r])=>[...(r??new Map).values()],{name:"schemas",describeKind:"derived",meta:fe("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(re(this.schemas))}register(e){this._bundle.set(e.name,e)}unregister(e){this._bundle.delete(e)}executeReactive(e,n){let r=this._bundle.get(e);if(!r)throw new Error(`toolRegistry: unknown tool "${e}"`);return K(o=>{let s=new AbortController,i;try{let u=r.handler(n,{signal:s.signal});i=Zh(u,s.signal)}catch(u){return o.down([[C,u]]),()=>{s.abort()}}let a=i.subscribe(u=>{o.down(u)});return()=>{s.abort(),a()}},{name:`executeReactive::${e}`,meta:fe("tool_execute_reactive")})}getDefinition(e){return this._bundle.entries.cache?.get(e)}};function mu(t,e){return new ai(t,e)}function Zh(t,e){return lu(t)?t:t!=null&&typeof t.then=="function"?zn(t,{signal:e}):t!=null&&typeof t=="object"&&Symbol.asyncIterator in t?Ir(t,{signal:e}):zn(Promise.resolve(t),{signal:e})}var ui=class extends Y{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;_terminalResult;_disposeRunWiring;_running=!1;_currentAbortController=null;constructor(e,n){if(super(e,n.graph),this.chat=pu(`${e}-chat`,{maxMessages:n.maxMessages}),this.mount("chat",this.chat),this.tools=mu(`${e}-tools`),this.mount("tools",this.tools),n.tools)for(let G of n.tools)this.tools.register(G);this.status=M("idle",{name:"status",describeKind:"state",meta:fe("agent_status")}),this.add(this.status,{name:"status"}),this.turn=M(0,{name:"turn",describeKind:"state",meta:fe("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.aborted=M(!1,{name:"aborted",describeKind:"state",meta:fe("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let r=0,o=this.turn.subscribe(G=>{for(let q of G)q[0]===E&&(r=q[1])}),s=!1,i=this.aborted.subscribe(G=>{for(let q of G)q[0]===E&&(s=q[1])}),a=this.chat.messages.cache??[],u=this.chat.messages.subscribe(G=>{for(let q of G)q[0]===E&&(a=q[1])}),d=this.tools.schemas.cache??[],c=this.tools.schemas.subscribe(G=>{for(let q of G)q[0]===E&&(d=q[1])}),l=n.adapter,p=n.systemPrompt,f=n.model,m=n.temperature,h=n.maxTokens,g=n.maxTurns??10,y=n.stopWhen,b=this.chat,v=this.tools,T=this.status,w=this.turn,x=this.aborted,k=z([T],(G,q,$)=>{if(bo(G,$.prevData,0,"idle")!=="thinking"||s||r>=g){q.down([[V]]);return}if(a.length===0){q.down([[V]]);return}q.emit({messages:a,tools:d})},{name:"promptInput",describeKind:"derived",meta:fe("agent_prompt_input",{closureReads:["aborted","turn","chat.messages","tools.schemas"]})}),S=Te(k,G=>{let q=new AbortController;return this._currentAbortController=q,s&&q.abort(new Error("agentLoop: aborted")),U(l.invoke(G.messages,{tools:G.tools.length>0?G.tools:void 0,systemPrompt:p,model:f,temperature:m,maxTokens:h,signal:q.signal}),{signal:q.signal})},{equals:()=>!1}),R=M(null,{name:"lastResponse",describeKind:"state",meta:fe("agent_last_response")});this.lastResponse=R;let N=z([R,T],(G,q,$)=>{let te=bo(G,$.prevData,0,null);if(bo(G,$.prevData,1,"idle")!=="acting"){q.down([[V]]);return}let Oe=te?.toolCalls;if(Oe==null||Oe.length===0){q.down([[V]]);return}q.emit(Oe)},{name:"toolCallsRaw",describeKind:"derived",meta:fe("agent_tool_calls_raw")}),_=n.interceptToolCalls?n.interceptToolCalls(N):N;this.toolCalls=_;let I=fu({toolCalls:_,tools:v,retryCount:1});this.toolResults=I;let O=pe([S],([G])=>{if(s)return;let q=G,$=r+1,te=q.toolCalls!=null&&q.toolCalls.length>0,Re=q.finishReason==="end_turn"&&(!q.toolCalls||q.toolCalls.length===0),Oe=y?.(q)===!0,Ce=$>=g,ye=Oe||Re||!te||Ce?"done":"acting";X(()=>{R.emit(q),T.emit(ye),w.emit($),b.append("assistant",q.content,{toolCalls:q.toolCalls})})}),P=pe([I],([G])=>{if(s)return;let q=G;if(q.length===0)return;let $=r>=g?"done":"thinking";X(()=>{T.emit($);for(let te of q)b.appendToolResult(te.id,te.content)})}),B=T.cache??"idle",j=T.subscribe(G=>{for(let q of G)q[0]===E&&(B=q[1])}),D=pe([x],([G])=>{G===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),B!=="done"&&T.emit("done"))}),Z=re(O),F=re(P),Q=re(D);this._terminalResult=z([T,R],(G,q,$)=>{let te=bo(G,$.prevData,0,"idle"),Re=bo(G,$.prevData,1,null);if(te==="done"){if(Re!=null){q.emit(Re);return}let Oe=new Error("agentLoop: aborted");Oe.name="AbortError",q.down([[C,Oe]]);return}if(te==="error"){q.down([[C,new Error("agentLoop: errored")]]);return}q.down([[V]])},{name:"terminalResult",describeKind:"derived",meta:fe("agent_terminal_result")}),this.add(k,{name:"promptInput"}),this.add(S,{name:"llmResponse"}),this.add(this.lastResponse,{name:"lastResponse"}),this.toolCalls===N?this.add(this.toolCalls,{name:"toolCalls"}):(this.add(N,{name:"toolCallsRaw"}),this.add(this.toolCalls,{name:"toolCalls"})),this.add(I,{name:"toolResults"}),this.add(this._terminalResult,{name:"terminalResult"}),this.addDisposer(o),this.addDisposer(i),this.addDisposer(j),this.addDisposer(u),this.addDisposer(c),this.addDisposer(Z),this.addDisposer(F),this.addDisposer(Q),this._disposeRunWiring=()=>{}}async run(e,n){if(this._running)throw new RangeError(`agentLoop "${this.name}": run() called while a previous run() is still pending \u2014 await the previous run before starting another, or call abort() first`);this._running=!0;let r;try{X(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle"),this.lastResponse.emit(null)}),e!=null&&this.chat.append("user",e);let o=es(this._terminalResult,{skipCurrent:!0});if(n!=null)if(n.aborted)this.aborted.emit(!0);else{let s=()=>this.aborted.emit(!0);n.addEventListener("abort",s,{once:!0}),r=()=>n.removeEventListener("abort",s)}return n?.aborted!==!0&&this.status.emit("thinking"),await o}finally{r?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function bo(t,e,n,r){let o=t[n];if(o!=null&&o.length>0)return o[o.length-1];let s=e[n];return s!==void 0?s:r}function ey(t,e){return new ui(t,e)}ee();he();function ty(t,e,n){let r=U(t),o=n?.condition!=null?U(n.condition):null,s=M(null,{name:n?.name?`${n.name}::null`:"handoff::null"});if(o==null)return Te(r,a=>{if(a==null)return s;let u=M(a);return e(u)});let i=A([r,o],([a,u])=>({v:a,open:u===!0}),{name:n?.name?`${n.name}::router`:"handoff::router",describeKind:"derived"});return Te(i,({v:a,open:u})=>{if(a==null)return s;if(!u)return M(a);let d=M(a);return e(d)})}ee();he();function ny(t,e,n){let r=U(t),o=e.map(i=>U(i)),s=[r,...o];return A(s,i=>{let a=i[0]??[],u=i.slice(1);return a.filter(d=>{for(let c of u)if(c!=null&&!c(d))return!1;return!0})},{name:n?.name??"tool-selector",describeKind:"derived",meta:fe("tool_selector"),equals:(i,a)=>{let u=i,d=a;if(u.length!==d.length)return!1;for(let c=0;c<u.length;c++)if(u[c]!==d[c])return!1;return!0}})}function qp(t){let e=t.thresholds??{};return n=>{let r=t.scoreFn(n);for(let o of Object.keys(e)){let s=e[o];if(s===void 0)continue;let i=r[o];if((Number.isFinite(i)?i:Number.NEGATIVE_INFINITY)<s)return!1}return!0}}function ry(t){let e={persistence:t.persistenceThreshold??.3,personalValue:t.personalValueThreshold??.3},n=qp({scoreFn:t.scoreFn,thresholds:e});return t.requireStructured?r=>{if(!n(r))return!1;let o=t.scoreFn(r).structure;return Number.isFinite(o)&&o>0}:n}ee();he();ee();function Hp(t,e,n,r){let o=n.name??r;return s=>{let i=M(s);return wn(n.adapter,[i],a=>e(a),{name:o,format:"json",systemPrompt:t,model:n.model,temperature:n.temperature??0,maxTokens:n.maxTokens})}}function gu(t,e){let n=e.maxExistingKeys??100,r=Hp(t,o=>JSON.stringify({input:o.raw,existingKeys:o.existingKeys}),e,"llmExtractor");return(o,s)=>{let i=n===Number.POSITIVE_INFINITY?[...s.keys()]:[...s.keys()].slice(0,n);return r({raw:o,existingKeys:i})}}function hu(t,e){let n=Hp(t,r=>JSON.stringify({memories:r}),e,"llmConsolidator");return r=>{let o=[...r.entries()].map(([s,i])=>({key:s,value:i}));return n(o)}}Me();xe();ee();he();var ci={};ke(ci,{collection:()=>sy,decay:()=>xn,knowledgeGraph:()=>vu,lightCollection:()=>yu,vectorIndex:()=>bu});xe();ee();function xn(t,e,n,r=0){if(!Number.isFinite(t))return r;if(!Number.isFinite(e)||e<=0||!Number.isFinite(n)||n<=0)return Math.max(r,t);let o=t*Math.exp(-n*e);return Math.max(r,o)}function Wp(t){if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1")}function St(t){return new Map(t)}function nt(t){return t.cache??new Map}function di(t){return t.cache??[]}function oy(t,e){let n=Math.max(t.length,e.length),r=0,o=0,s=0;for(let i=0;i<n;i+=1){let a=t[i]??0,u=e[i]??0;r+=a*u,o+=a*a,s+=u*u}return o===0||s===0?0:r/Math.sqrt(o*s)}function yu(t={}){let e=t.maxSize,n=t.policy??"fifo";Wp(e);let r=M(new Map,{name:t.name,describeKind:"state"});function o(i){if(e!==void 0)for(;i.size>e;){let a;for(let u of i.values()){if(!a){a=u;continue}let d=n==="lru"?u.lastAccessNs:u.createdAtNs,c=n==="lru"?a.lastAccessNs:a.createdAtNs;d<c&&(a=u)}if(!a)break;i.delete(a.id)}}function s(i){r.emit(i)}return{entries:r,upsert(i,a){let u=H(),d=nt(r),c=d.get(i),l=St(d);l.set(i,{id:i,value:a,createdAtNs:c?.createdAtNs??u,lastAccessNs:u}),o(l),s(l)},remove(i){let a=St(nt(r));a.delete(i)&&s(a)},clear(){nt(r).size!==0&&s(new Map)},get(i){let a=nt(r),u=a.get(i);if(u){if(n==="lru"){let d=H(),c=St(a);c.set(i,{...u,lastAccessNs:d}),s(c)}return u.value}},has(i){return nt(r).has(i)}}}function sy(t,e={}){let n=e.maxSize,r=e.policy??"lru",o=e.decayRate??0,s=e.minScore??0,i=e.score??(()=>1);Wp(n);let a=new Y(t),u=M(new Map,{name:"items",describeKind:"state"}),d=A([u],([h])=>{let g=h??new Map,y=H(),b=[...g.values()].map(v=>{let T=(y-v.lastAccessNs)/1e9;return{...v,score:xn(v.baseScore,T,o,s)}});return b.sort((v,T)=>T.score-v.score||T.lastAccessNs-v.lastAccessNs),b},{name:"ranked",describeKind:"derived"}),c=A([u],([h])=>(h??new Map).size,{name:"size",describeKind:"derived",initial:0});d.subscribe(()=>{}),c.subscribe(()=>{}),a.add(u,{name:"items"}),a.add(d,{name:"ranked"}),a.add(c,{name:"size"});function l(h,g){let y=(g-h.lastAccessNs)/1e9;return xn(h.baseScore,y,o,s)}function p(h){if(n!==void 0)for(;h.size>n;){let g=H(),y,b=Number.POSITIVE_INFINITY;for(let v of h.values()){let T=l(v,g);if(T<b){y=v,b=T;continue}if(T===b&&y){let w=r==="lru"?v.lastAccessNs:v.createdAtNs,x=r==="lru"?y.lastAccessNs:y.createdAtNs;w<x&&(y=v)}}if(!y)break;h.delete(y.id)}}function f(h){u.emit(h)}return Object.assign(a,{upsert(h,g,y){let b=H(),v=nt(u),T=v.get(h),w=y?.score??i(g),x=St(v);x.set(h,{id:h,value:g,baseScore:w,createdAtNs:T?.createdAtNs??b,lastAccessNs:b}),p(x),f(x)},remove(h){let g=St(nt(u));g.delete(h)&&f(g)},clear(){nt(u).size!==0&&f(new Map)},getItem(h){let g=nt(u),y=g.get(h);if(y){if(r==="lru"){let b=St(g);b.set(h,{...y,lastAccessNs:H()}),f(b)}return y}}})}function bu(t={}){let e=t.backend??"flat",n=t.dimension,r;if(e==="hnsw"&&(r=t.hnswFactory?.(),!r))throw new Error('vectorIndex backend "hnsw" requires an optional dependency adapter; install your HNSW package and provide `hnswFactory`.');let o=M(new Map,{describeKind:"state",name:"vector-index"});function s(a){if(n!==void 0&&a.length!==n)throw new RangeError(`vector dimension mismatch: expected ${n}, got ${a.length}`)}function i(a){o.emit(a)}return{backend:e,entries:o,upsert(a,u,d){s(u);let c=St(nt(o));c.set(a,{id:a,vector:[...u],meta:d}),e==="hnsw"&&r.upsert(a,u,d),i(c)},remove(a){let u=St(nt(o));u.delete(a)&&(e==="hnsw"&&r.remove(a),i(u))},clear(){nt(o).size!==0&&(e==="hnsw"&&r.clear(),i(new Map))},search(a,u=5){return s(a),u<=0?[]:e==="hnsw"?r.search(a,u):[...nt(o).values()].map(c=>({id:c.id,score:oy(a,c.vector),meta:c.meta})).sort((c,l)=>l.score-c.score).slice(0,u)}}}function vu(t){let e=new Y(t),n=M(new Map,{name:"entities",describeKind:"state"}),r=M([],{name:"edges",describeKind:"state"}),o=A([r],([u])=>{let d=u??[],c=new Map;for(let l of d){let p=c.get(l.from)??[];c.set(l.from,Object.freeze([...p,l]))}return c},{name:"adjacency",describeKind:"derived",initial:new Map});o.subscribe(()=>{}),e.add(n,{name:"entities"}),e.add(r,{name:"edges"}),e.add(o,{name:"adjacency"});function s(u){n.emit(u)}function i(u){r.emit(u)}return Object.assign(e,{upsertEntity(u,d){let c=St(nt(n));c.set(u,d),s(c)},removeEntity(u){let d=St(nt(n)),c=d.delete(u),l=di(r),p=l.filter(f=>f.from!==u&&f.to!==u);!c&&p.length===l.length||(s(d),i(p))},link(u,d,c,l=1){let p=`${u}\0${d}\0${c}`,f=di(r),m=new Set(f.map(g=>`${g.from}\0${g.to}\0${g.relation}`)),h=[...f];if(m.has(p))for(let g=0;g<h.length;g+=1){let y=h[g];if(y.from===u&&y.to===d&&y.relation===c){h[g]={...y,weight:l};break}}else h.push({from:u,to:d,relation:c,weight:l});i(h)},unlink(u,d,c){let l=di(r),p=l.filter(f=>c===void 0?!(f.from===u&&f.to===d):!(f.from===u&&f.to===d&&f.relation===c));p.length!==l.length&&i(p)},related(u,d){return di(r).filter(c=>(c.from===u||c.to===u)&&(d===void 0||c.relation===d))}})}var Tu=Math.LN2/604800;function ar(t){return t instanceof Map?t:new Map}function wu(t,e,n){let r=bu({dimension:n.dimension});t.add(r.entries,{name:"vectorIndex"});let s=pe([e.store.entries],([i])=>{let a=ar(i);for(let[u,d]of a){let c=n.embedFn(d);c&&r.upsert(u,c,d)}}).subscribe(()=>{});return t.addDisposer(s),{vectors:r,dispose:()=>s()}}function ku(t,e,n,r){let o=r.mountPath??n,s=vu(`${n}-kg`);if(t.mount(o,s),!r.entityFn)return{kg:s,dispose:()=>{}};let i=r.entityFn,u=pe([e.store.entries],([d])=>{let c=ar(d);for(let[l,p]of c){let f=i(l,p);if(f){for(let m of f.entities??[])s.upsertEntity(m.id,m.value);for(let m of f.relations??[])s.link(m.from,m.to,m.relation,m.weight)}}}).subscribe(()=>{});return t.addDisposer(u),{kg:s,dispose:()=>u()}}function xu(t,e,n){let r=n.decayRate??Tu,o=n.maxActive??1e3,s=n.archiveThreshold??.1,i=n.permanentFilter??(()=>!1),a=yu({name:"permanent"});t.add(a.entries,{name:"permanent"});let u=new Set,d=b=>u.has(b)?"permanent":ar(e.store.entries.cache).has(b)?"active":"archived",c=(b,v)=>{u.add(b),a.upsert(b,v)},l=new Map,p=e.store.entries,f=n.context?U(n.context):M(null),h=pe([p,f],([b,v])=>{let T=ar(b),w=H(),x=[],k=[];for(let[R,N]of T){if(l.has(R)||l.set(R,w),i(R,N)){k.push({key:R,value:N});continue}let _=n.score(N,v),I=l.get(R)??w,O=Number(w-I)/1e9;xn(_,O,r)<s&&x.push(R)}for(let R of l.keys())T.has(R)||l.delete(R);for(let{key:R,value:N}of k)u.has(R)||c(R,N);let S=T.size-u.size;if(S>o){let R=[...T.entries()].filter(([_])=>!u.has(_)).map(([_,I])=>({key:_,score:n.score(I,v)})).sort((_,I)=>_.score-I.score),N=S-o;for(let _=0;_<N&&_<R.length;_++){let I=R[_].key;x.includes(I)||x.push(I)}}x.length>0&&X(()=>{for(let R of x)e.store.delete(R)})}).subscribe(()=>{}),g=null;n.archiveTier&&(g=t.attachSnapshotStorage([n.archiveTier],n.archiveStorageOptions??{}));let y=()=>{h(),g?.dispose()};return t.addDisposer(y),{tiers:{permanent:a,activeEntries:p,archiveHandle:g,tierOf:d,markPermanent:c},dispose:y}}function iy(t,e){if(!t||!e)return 0;let n=Math.min(t.length,e.length),r=0;for(;r<n&&t[r]===e[r];)r++;return r}function Ru(t,e,n,r,o){let s=o.topK??20,i=o.graphDepth??1,a=o.budget??2e3,u=o.contextWeight??0,d=o.context?U(o.context):M(null),c=(g,y,b)=>{let v=new Map,T=[];if(n&&b.vector){T=n.search(b.vector,s);for(let N of T){let _=g.get(N.id);_&&v.set(N.id,{value:_,sources:new Set(["vector"])})}}let w=[];if(r){let N=[...b.entityIds??[],...v.keys()],_=new Set,I=N;for(let O=0;O<i;O++){let P=[];for(let B of I)if(!_.has(B)){_.add(B);for(let j of r.related(B)){let D=j.to;if(!_.has(D)){P.push(D);let Z=g.get(D);if(Z){let F=v.get(D);F?F.sources.add("graph"):v.set(D,{value:Z,sources:new Set(["graph"])}),w.push(D)}}}}I=P}}for(let[N,_]of g)v.has(N)||v.set(N,{value:_,sources:new Set(["store"])});let x=b.context?.length??0,k=[];for(let[N,{value:_,sources:I}]of v){let O=o.contextOf?o.contextOf(_):void 0,P=o.score(_,y);if(u>0&&x>0){let j=iy(b.context,O);j>0&&(P=P*(1+u*j/x))}let B=O?{key:N,value:_,score:P,sources:[...I],context:O}:{key:N,value:_,score:P,sources:[...I]};k.push(B)}k.sort((N,_)=>_.score-N.score);let S=[],R=0;for(let N of k){let _=o.cost(N.value);if(R+_>a&&S.length>0)break;S.push(N),R+=_}return{packed:S,trace:{vectorCandidates:T,graphExpanded:w,ranked:k,packed:S}}},l=(g,y)=>{if(g===y)return!0;if(g.length!==y.length)return!1;for(let b=0;b<g.length;b++)if(g[b]!==y[b])return!1;return!0},p=M([],{name:"retrieval",describeKind:"state",meta:fe("retrieval_pipeline"),equals:l});t.add(p,{name:"retrieval"});let f=M(null,{name:"retrievalTrace",describeKind:"state",meta:fe("retrieval_trace")});return t.add(f,{name:"retrievalTrace"}),{retrieval:p,retrievalTrace:f,retrieve:g=>{let y=ar(e.store.entries.cache),{packed:b,trace:v}=c(y,d.cache,g);return X(()=>{p.emit(b),f.emit(v)}),b},retrieveReactive:g=>{let y=U(g),b=A([e.store.entries,d,y],([w,x,k])=>{if(k==null)return{packed:[],trace:null};let S=ar(w),{packed:R,trace:N}=c(S,x,k);return{packed:R,trace:N}},{name:"retrievalReactive::result",describeKind:"derived",meta:fe("retrieval_reactive_result"),initial:{packed:[],trace:null}}),T=pe([b],([w])=>{let x=w;X(()=>{p.emit(x.packed),x.trace&&f.emit(x.trace)})}).subscribe(()=>{});return t.addDisposer(T),A([b],([w])=>w.packed,{name:"retrievalReactive",describeKind:"derived",meta:fe("retrieval_reactive"),initial:[],equals:l})}}}function ay(t,e,n){let r=new Y(t,n.graph),o;if(n.extractFn)o=n.extractFn;else if(n.adapter&&n.extractPrompt)o=gu(n.extractPrompt,{adapter:n.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let s=(b,v)=>b==null?{upsert:[]}:o(b,v),i=e;if(n.admissionFilter){let b=U(e),v=n.admissionFilter;i=A([b],([T])=>{if(v(T))return T},{name:"admissionFilter",describeKind:"derived"})}let a;n.consolidateFn?a=n.consolidateFn:n.adapter&&n.consolidatePrompt&&(a=hu(n.consolidatePrompt,{adapter:n.adapter}));let u=n.consolidateTrigger;if(!u&&a&&n.reflection?.enabled!==!1){let b=n.reflection?.interval??3e5;u=st(b,{period:b})}let d={score:n.score,cost:n.cost,budget:n.budget??2e3,context:n.context,consolidate:a,consolidateTrigger:u},c=Ls(i,s,d);r.add(c.store.entries,{name:"store"}),r.add(c.compact,{name:"compact"}),r.add(c.size,{name:"size"});let l=null;n.vectorDimensions&&n.vectorDimensions>0&&n.embedFn&&(l=wu(r,c,{dimension:n.vectorDimensions,embedFn:n.embedFn}).vectors);let p=null;n.enableKnowledgeGraph&&(p=ku(r,c,t,{mountPath:"kg",entityFn:n.entityFn}).kg);let f=null;n.tiers&&(f=xu(r,c,{...n.tiers,score:n.score,context:n.context}).tiers);let m=null,h=null,g=null,y=null;if(l||p){let b=Ru(r,c,l,p,{score:n.score,cost:n.cost,budget:n.budget,topK:n.retrieval?.topK,graphDepth:n.retrieval?.graphDepth,contextOf:n.contextOf,contextWeight:n.contextWeight,context:n.context});m=b.retrieval,h=b.retrievalTrace,g=b.retrieve,y=b.retrieveReactive}return Object.assign(r,{distillBundle:c,compact:c.compact,size:c.size,vectors:l,kg:p,memoryTiers:f,retrieval:m,retrievalTrace:h,retrieve:g,retrieveReactive:y})}function uy(t,e,n){let r=t.describe({actor:e,detail:"full"}),o=n?.groupByTags??!0,s=n?.separator??`
|
|
40
|
-
`,i=[],a=n?.sinceVersion;for(let[u
|
|
39
|
+
`,r=t.map(i=>typeof i=="string"?A(i):Y(i)),o=C(r,i=>i.filter(a=>a!=null&&a!=="").join(n),{name:e?.name??"systemPrompt",describeKind:"derived",meta:he("system_prompt"),initial:""}),s=te(o);return Object.assign(o,{dispose:s})}ne();var uy=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens&&t.estimated===e.estimated;function cy(t,e){let n=e?.charsPerToken??4,r={chunkCount:0,charCount:0,estimatedTokens:0,estimated:!0};return C([t.latest],([o],s)=>{if(o==null)return r;let i=o;"chunkCount"in s.store||(s.store.chunkCount=0,s.store.charCount=0,s.store.usageTokens=0,s.store.sawUsage=!1);let a=s.store;i.type==="token"?(a.chunkCount+=1,a.charCount+=i.delta.length):i.type==="usage"&&(a.sawUsage=!0,a.usageTokens=kt(i.usage)+jt(i.usage));let d=a.sawUsage?a.usageTokens:Math.ceil(a.charCount/n);return{chunkCount:a.chunkCount,charCount:a.charCount,estimatedTokens:d,estimated:!a.sawUsage}},{name:e?.name??"cost-meter",describeKind:"derived",initial:r,meta:he("cost_meter_extractor"),equals:uy})}ne();var ly=(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 py(t,e){let n=e.maxPatternLength??128;for(let o of e.patterns)if(o.pattern.source.length>n)throw new Error(`keywordFlagExtractor: pattern "${o.label}" literal exceeds maxPatternLength (${o.pattern.source.length} > ${n}); raise the option or shorten the pattern.`);let r=e.patterns.map(o=>({label:o.label,pattern:o.pattern,compiled:new RegExp(o.pattern.source,`${o.pattern.flags.replace("g","")}g`)}));return C([t],([o],s)=>{if(o==null)return[];let i=o;"flags"in s.store||(s.store.flags=[],s.store.scannedTo=0);let a=s.store.flags,d=s.store.scannedTo,u=Math.max(0,d-n),c=i.slice(u),l=!1;for(let{pattern:p,label:f,compiled:m}of r){m.lastIndex=0;for(let h of c.matchAll(m)){let g=u+(h.index??0);g+h[0].length<=d||(a.push({label:f,pattern:p,match:h[0],position:g}),l=!0)}}return s.store.scannedTo=i.length,l?[...a]:a.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:he("keyword_flag_extractor"),equals:ly})}ne();function fy(t,e,n){return C([t],([r])=>r==null?null:e(r),{name:n?.name??"extractor",describeKind:"derived",initial:null,meta:he("stream_extractor"),...n?.equals?{equals:n.equals}:{}})}ne();var my=(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 gy(t,e){return C([t],([n],r)=>{if(n==null)return[];let o=n;"calls"in r.store||(r.store.calls=[],r.store.scanFrom=0);let s=r.store.calls,i=r.store.scanFrom,a=!1;for(;i<o.length;){let d=o.indexOf("{",i);if(d===-1){r.store.scanFrom=o.length;break}let u=0,c=-1,l=!1;for(let f=d;f<o.length;f++){let m=o[f];if(l)m==="\\"&&f+1<o.length?f++:m==='"'&&(l=!1);else if(m==='"')l=!0;else if(m==="{")u++;else if(m==="}"&&(u--,u===0)){c=f;break}}if(c===-1){r.store.scanFrom=d;break}let p=o.slice(d,c+1);try{let f=JSON.parse(p);typeof f.name=="string"&&f.arguments!=null&&typeof f.arguments=="object"&&(s.push({name:f.name,arguments:f.arguments,raw:p,startIndex:d}),a=!0)}catch{}i=c+1,r.store.scanFrom=i}return a?[...s]:s.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:he("tool_call_extractor"),equals:my})}ne();function hy(t,e,n,r){let o=n*(r?.hardMultiplier??1.5),s=typeof e!="function",i=[t];return s&&i.push(e),C(i,a=>{let d=a[0]??"";if(d.length===0)return"allow";let u=s?a[1]??0:e(d);return u>=o?"block":u>=n?"review":"allow"},{name:r?.name??"content-gate",initial:"allow"})}ne();function yy(t,e,n,r){let o=n??(()=>"[REDACTED]");function s(i){let a=i;for(let d of e){let u=d.global?d:new RegExp(d.source,`${d.flags}g`);a=a.replace(u,c=>o(c,d))}return a}return C([t],([i])=>s(i??""),{name:r?.name??"redactor",initial:""})}Ae();ae();it();Me();ne();ve();ne();var fi=class extends Q{_log;messages;latest;messageCount;constructor(e,n={}){super(e,n.graph),this._log=Ke([],{name:"messages",maxSize:n.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=C([this.messages],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:he("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(te(this.latest)),this.messageCount=C([this.messages],([r])=>r.length,{name:"messageCount",describeKind:"derived",meta:he("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(te(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 xd(t,e){return new fi(t,e)}ne();It();function Rd(t){let{toolCalls:e,tools:n}=t,r=t.retryCount??1,o=t.onError??"rescue",s=(i,a)=>{if(i===a)return!0;if(i.length!==a.length)return!1;for(let d=0;d<i.length;d++){let u=i[d],c=a[d];if(u?.id!==c?.id||u?.content!==c?.content)return!1}return!0};return ke(e,i=>{if(i==null||i.length===0)throw new Error("toolExecution: received an empty tool-call batch as DATA \u2014 callers must upstream-filter empty batches (emit RESOLVED) so switchMap is only dispatched for non-empty batches.");let a=i.map(d=>by(d,n,r,o));return C(a,d=>d,{name:"toolExecution::batch",equals:s})})}function by(t,e,n,r){let o=St(()=>e.executeReactive(t.name,t.arguments),{count:n}),s=C([o],([i])=>({id:t.id,content:typeof i=="string"?i:JSON.stringify(i)}));return r==="propagate"?s:ro(s,i=>({id:t.id,content:JSON.stringify({error:String(i)})}))}ae();ne();ve();var mi=class extends Q{definitions;schemas;_bundle;constructor(e,n={}){super(e,n.graph),this._bundle=je({name:"definitions"}),this.definitions=this._bundle.entries,this.add(this.definitions,{name:"definitions"}),this.schemas=C([this.definitions],([r])=>[...(r??new Map).values()],{name:"schemas",describeKind:"derived",meta:he("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(te(this.schemas))}register(e){this._bundle.set(e.name,e)}unregister(e){this._bundle.delete(e)}executeReactive(e,n){let r=this._bundle.get(e);if(!r)throw new Error(`toolRegistry: unknown tool "${e}"`);return z(o=>{let s=new AbortController,i;try{let d=r.handler(n,{signal:s.signal});i=vy(d,s.signal)}catch(d){return o.down([[I,d]]),()=>{s.abort()}}let a=i.subscribe(d=>{o.down(d)});return()=>{s.abort(),a()}},{name:`executeReactive::${e}`,meta:he("tool_execute_reactive")})}getDefinition(e){return this._bundle.entries.cache?.get(e)}};function Sd(t,e){return new mi(t,e)}function vy(t,e){return kd(t)?t:t!=null&&typeof t.then=="function"?Xn(t,{signal:e}):t!=null&&typeof t=="object"&&Symbol.asyncIterator in t?Br(t,{signal:e}):Xn(Promise.resolve(t),{signal:e})}var gi=class extends Q{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;_terminalResult;_disposeRunWiring;_running=!1;_currentAbortController=null;constructor(e,n){if(super(e,n.graph),this.chat=xd(`${e}-chat`,{maxMessages:n.maxMessages}),this.mount("chat",this.chat),this.tools=Sd(`${e}-tools`),this.mount("tools",this.tools),n.tools)for(let G of n.tools)this.tools.register(G);this.status=A("idle",{name:"status",describeKind:"state",meta:he("agent_status")}),this.add(this.status,{name:"status"}),this.turn=A(0,{name:"turn",describeKind:"state",meta:he("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.aborted=A(!1,{name:"aborted",describeKind:"state",meta:he("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let r=0,o=this.turn.subscribe(G=>{for(let B of G)B[0]===M&&(r=B[1])}),s=!1,i=this.aborted.subscribe(G=>{for(let B of G)B[0]===M&&(s=B[1])}),a=this.chat.messages.cache??[],d=this.chat.messages.subscribe(G=>{for(let B of G)B[0]===M&&(a=B[1])}),u=this.tools.schemas.cache??[],c=this.tools.schemas.subscribe(G=>{for(let B of G)B[0]===M&&(u=B[1])}),l=n.adapter,p=n.systemPrompt,f=n.model,m=n.temperature,h=n.maxTokens,g=n.maxTurns??10,y=n.stopWhen,b=this.chat,v=this.tools,T=this.status,w=this.turn,x=this.aborted,k=U([T],(G,B,re)=>{if(So(G,re.prevData,0,"idle")!=="thinking"||s||r>=g){B.down([[q]]);return}if(a.length===0){B.down([[q]]);return}B.emit({messages:a,tools:u})},{name:"promptInput",describeKind:"derived",meta:he("agent_prompt_input",{closureReads:["aborted","turn","chat.messages","tools.schemas"]})}),S=ke(k,G=>{let B=new AbortController;return this._currentAbortController=B,s&&B.abort(new Error("agentLoop: aborted")),Y(l.invoke(G.messages,{tools:G.tools.length>0?G.tools:void 0,systemPrompt:p,model:f,temperature:m,maxTokens:h,signal:B.signal}),{signal:B.signal})},{equals:()=>!1}),R=A(null,{name:"lastResponse",describeKind:"state",meta:he("agent_last_response")});this.lastResponse=R;let E=U([R,T],(G,B,re)=>{let pe=So(G,re.prevData,0,null);if(So(G,re.prevData,1,"idle")!=="acting"){B.down([[q]]);return}let ue=pe?.toolCalls;if(ue==null||ue.length===0){B.down([[q]]);return}B.emit(ue)},{name:"toolCallsRaw",describeKind:"derived",meta:he("agent_tool_calls_raw")}),_=n.interceptToolCalls?n.interceptToolCalls(E):E;this.toolCalls=_;let O=Rd({toolCalls:_,tools:v,retryCount:1});this.toolResults=O;let N=ge([S],([G])=>{if(s)return;let B=G,re=r+1,pe=B.toolCalls!=null&&B.toolCalls.length>0,ee=B.finishReason==="end_turn"&&(!B.toolCalls||B.toolCalls.length===0),ue=y?.(B)===!0,Ce=re>=g,Ye=ue||ee||!pe||Ce?"done":"acting";Z(()=>{R.emit(B),T.emit(Ye),w.emit(re),b.append("assistant",B.content,{toolCalls:B.toolCalls})})}),L=ge([O],([G])=>{if(s)return;let B=G;if(B.length===0)return;let re=r>=g?"done":"thinking";Z(()=>{T.emit(re);for(let pe of B)b.appendToolResult(pe.id,pe.content)})}),j=T.cache??"idle",$=T.subscribe(G=>{for(let B of G)B[0]===M&&(j=B[1])}),D=ge([x],([G])=>{G===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),j!=="done"&&T.emit("done"))}),K=te(N),F=te(L),H=te(D);this._terminalResult=U([T,R],(G,B,re)=>{let pe=So(G,re.prevData,0,"idle"),ee=So(G,re.prevData,1,null);if(pe==="done"){if(ee!=null){B.emit(ee);return}let ue=new Error("agentLoop: aborted");ue.name="AbortError",B.down([[I,ue]]);return}if(pe==="error"){B.down([[I,new Error("agentLoop: errored")]]);return}B.down([[q]])},{name:"terminalResult",describeKind:"derived",meta:he("agent_terminal_result")}),this.add(k,{name:"promptInput"}),this.add(S,{name:"llmResponse"}),this.add(this.lastResponse,{name:"lastResponse"}),this.toolCalls===E?this.add(this.toolCalls,{name:"toolCalls"}):(this.add(E,{name:"toolCallsRaw"}),this.add(this.toolCalls,{name:"toolCalls"})),this.add(O,{name:"toolResults"}),this.add(this._terminalResult,{name:"terminalResult"}),this.addDisposer(o),this.addDisposer(i),this.addDisposer($),this.addDisposer(d),this.addDisposer(c),this.addDisposer(K),this.addDisposer(F),this.addDisposer(H),this._disposeRunWiring=()=>{}}async run(e,n){if(this._running)throw new RangeError(`agentLoop "${this.name}": run() called while a previous run() is still pending \u2014 await the previous run before starting another, or call abort() first`);this._running=!0;let r;try{Z(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle"),this.lastResponse.emit(null)}),e!=null&&this.chat.append("user",e);let o=as(this._terminalResult,{skipCurrent:!0});if(n!=null)if(n.aborted)this.aborted.emit(!0);else{let s=()=>this.aborted.emit(!0);n.addEventListener("abort",s,{once:!0}),r=()=>n.removeEventListener("abort",s)}return n?.aborted!==!0&&this.status.emit("thinking"),await o}finally{r?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function So(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 Ty(t,e){let n=new gi(t,e);return n.tagFactory("agentLoop",st(e)),n}it();ne();ve();function wy(t,e,n){let r=Y(t),o=n?.condition!=null?Y(n.condition):null,s=A(null,{name:n?.name?`${n.name}::null`:"handoff::null"});if(o==null)return ke(r,a=>{if(a==null)return s;let d=A(a);return e(d)},{meta:we("handoff")});let i=C([r,o],([a,d])=>({v:a,open:d===!0}),{name:n?.name?`${n.name}::router`:"handoff::router",describeKind:"derived"});return ke(i,({v:a,open:d})=>{if(a==null)return s;if(!d)return A(a);let u=A(a);return e(u)},{meta:we("handoff")})}it();ne();ve();function ky(t,e,n){let r=Y(t),o=e.map(i=>Y(i)),s=[r,...o];return C(s,i=>{let a=i[0]??[],d=i.slice(1);return a.filter(u=>{for(let c of d)if(c!=null&&!c(u))return!1;return!0})},{name:n?.name??"tool-selector",describeKind:"derived",meta:{...he("tool_selector"),...we("toolSelector")},equals:(i,a)=>{let d=i,u=a;if(d.length!==u.length)return!1;for(let c=0;c<d.length;c++)if(d[c]!==u[c])return!1;return!0}})}function of(t){let e=t.thresholds??{};return n=>{let r=t.scoreFn(n);for(let o of Object.keys(e)){let s=e[o];if(s===void 0)continue;let i=r[o];if((Number.isFinite(i)?i:Number.NEGATIVE_INFINITY)<s)return!1}return!0}}function xy(t){let e={persistence:t.persistenceThreshold??.3,personalValue:t.personalValueThreshold??.3},n=of({scoreFn:t.scoreFn,thresholds:e});return t.requireStructured?r=>{if(!n(r))return!1;let o=t.scoreFn(r).structure;return Number.isFinite(o)&&o>0}:n}ae();it();ne();ve();ne();function sf(t,e,n,r){let o=n.name??r;return s=>{let i=A(s);return Sn(n.adapter,[i],a=>e(a),{name:o,format:"json",systemPrompt:t,model:n.model,temperature:n.temperature??0,maxTokens:n.maxTokens})}}function Nd(t,e){let n=e.maxExistingKeys??100,r=sf(t,o=>JSON.stringify({input:o.raw,existingKeys:o.existingKeys}),e,"llmExtractor");return(o,s)=>{let i=n===Number.POSITIVE_INFINITY?[...s.keys()]:[...s.keys()].slice(0,n);return r({raw:o,existingKeys:i})}}function Ed(t,e){let n=sf(t,r=>JSON.stringify({memories:r}),e,"llmConsolidator");return r=>{let o=[...r.entries()].map(([s,i])=>({key:s,value:i}));return n(o)}}Ae();Re();ne();ve();var bi={};Se(bi,{collection:()=>Ey,cosineSimilarity:()=>yi,decay:()=>En,knowledgeGraph:()=>Od,lightCollection:()=>_d,vectorIndex:()=>Md});Re();Me();ne();ve();var Ry=1e9;function gt(t,e){return We("memory",t,e)}function fr(t,e){return t instanceof Oe?t:A(t,e?{name:e}:void 0)}function af(t,e){return(t-e)/Ry}function En(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 yi(t,e){let n=Math.max(t.length,e.length),r=0,o=0,s=0;for(let a=0;a<n;a+=1){let d=t[a]??0,u=e[a]??0;r+=d*u,o+=d*d,s+=u*u}if(o===0||s===0)return 0;let i=r/Math.sqrt(o*s);return Number.isFinite(i)?i:0}function Sy(t,e){if(t===e)return!0;if(t==null||e==null||t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1){let r=t[n],o=e[n];if(r.id!==o.id||r.score!==o.score||r.meta!==o.meta)return!1}return!0}function _d(t={}){let e=t.maxSize;if(e!==void 0&&e<1)throw new RangeError("lightCollection: maxSize must be >= 1");let n=je({name:t.name,...e!==void 0?{maxSize:e}:{}}),r=n.entries,o=at({name:t.name?`${t.name}_events`:"events",retainedLimit:1024}),s=(f,m)=>{let h=V(),g=r.cache?.get(f);n.set(f,{id:f,value:m,createdAtNs:g?.createdAtNs??h,lastAccessNs:h})},i=f=>{n.has(f)&&n.delete(f)},a=()=>{n.size!==0&&n.clear()},d=nt(s,{audit:o,onSuccess:([f],m,h)=>({action:"upsert",id:f,t_ns:h.t_ns}),onFailure:(f,m,h)=>({action:"upsert",t_ns:h.t_ns,handlerVersion:{id:"lightCollection.upsert",version:1}})}),u=nt(i,{audit:o,onSuccess:([f],m,h)=>({action:"remove",id:f,t_ns:h.t_ns})}),c=nt(a,{audit:o,onSuccess:(f,m,h)=>({action:"clear",t_ns:h.t_ns})});function l(f){let m=fr(f,"id");return C([r,m],([h,g])=>h?.get(g),{describeKind:"derived",meta:gt("light_collection_item")})}function p(f){let m=fr(f,"id");return C([r,m],([h,g])=>h?.has(g)??!1,{describeKind:"derived",meta:gt("light_collection_has")})}return{entries:r,events:o,upsert:d,remove:u,clear:c,itemNode:l,hasNode:p}}function Ny(t,e){if(t===e)return!0;if(t==null||e==null||t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1){let r=t[n],o=e[n];if(r.id!==o.id||r.score!==o.score||r.lastAccessNs!==o.lastAccessNs||r.value!==o.value)return!1}return!0}function Ey(t,e={}){let n=e.maxSize,r=e.decayRate??0,o=e.minScore??0;if(n!==void 0&&n<1)throw new RangeError("collection: maxSize must be >= 1");let s=()=>1,i=e.score??s,a=i instanceof Oe?i:void 0,d=()=>a?a.cache??s:i,u=new Q(t),l=je({name:"items",...n!==void 0?{retention:{score:(O,N)=>En(N.baseScore,af(V(),N.lastAccessNs),r,o),maxSize:n}}:{}});u.add(l.entries,{name:"items"});let p;if(r>0){let O=e.refreshIntervalMs??Math.max(1,1e3*Math.LN2/(10*r)),N=Ze(O,{period:O});p=C([N],()=>V(),{name:"refresh_tick_ns",describeKind:"derived",initial:V(),meta:gt("clock")}),u.add(p,{name:"refresh_tick_ns"})}let f=[l.entries];p&&f.push(p),a&&f.push(a);let m=C(f,O=>{let N=O[0],L;if(p){let $=O[1];L=typeof $=="number"?$:V()}else L=V();if(!N||N.size===0)return[];let j=[];for(let $ of N.values())j.push({...$,score:En($.baseScore,af(L,$.lastAccessNs),r,o)});return j.sort(($,D)=>D.score-$.score||D.lastAccessNs-$.lastAccessNs),j},{name:"ranked",describeKind:"derived",equals:Ny,meta:gt("ranked")});u.add(m,{name:"ranked"});let h=C([l.entries],([O])=>(O??new Map).size,{name:"size",describeKind:"derived",initial:0,meta:gt("size")});u.add(h,{name:"size"}),u.addDisposer(te(h));let g=at({name:"events",retainedLimit:1024,graph:u}),y=Yt(u,"seq",0),b=(O,N,L)=>{let j=V(),$=l.get(O),D=L?.score??d()(N);l.set(O,{id:O,value:N,baseScore:D,createdAtNs:$?.createdAtNs??j,lastAccessNs:j})},v=O=>{l.has(O)&&l.delete(O)},T=()=>{l.size!==0&&l.clear()},w=()=>{let O=d(),N=l.entries.cache;if(!N||N.size===0)return;let L=[];for(let j of N.values())L.push([j.id,{...j,baseScore:O(j.value)}]);l.setMany(L)},x=nt(b,{audit:g,seq:y,onSuccess:([O],N,L)=>({action:"upsert",id:O,t_ns:L.t_ns,seq:L.seq})}),k=nt(v,{audit:g,seq:y,onSuccess:([O],N,L)=>({action:"remove",id:O,t_ns:L.t_ns,seq:L.seq})}),S=nt(T,{audit:g,seq:y,onSuccess:(O,N,L)=>({action:"clear",t_ns:L.t_ns,seq:L.seq})}),R=nt(w,{audit:g,seq:y,onSuccess:(O,N,L)=>({action:"rescore",t_ns:L.t_ns,seq:L.seq})});function E(O){let N=fr(O,"id");return C([l.entries,N],([L,j])=>L?.get(j),{describeKind:"derived",meta:gt("collection_item")})}return Object.assign(u,{events:g,items:l.entries,ranked:m,size:h,upsert:x,remove:k,clear:S,rescore:R,itemNode:E})}function Md(t={}){let e=t.backend??"flat",n=t.dimension,r=t.strictDimension??!0,o=t.maxSize,s=t.retentionScore,i;if(e==="hnsw"&&(i=t.hnswFactory?.(),!i))throw new Error('vectorIndex backend "hnsw" requires an optional dependency adapter; install your HNSW package and provide `hnswFactory`.');let a=new Q(t.name??"vector_index"),d;function u(R){if(n!==void 0){if(R.length!==n)throw new RangeError(`vector dimension mismatch: expected ${n}, got ${R.length}`);return}if(r){if(d===void 0){d=R.length;return}if(R.length!==d)throw new RangeError(`vector dimension mismatch: inferred ${d} from first upsert, got ${R.length}. Pass \`strictDimension: false\` to opt into zero-pad behavior, or set an explicit \`dimension\`.`)}}let c=s??(R=>R.upsertedAtNs),l=!1,p=at({name:"events",retainedLimit:1024,graph:a}),f=Yt(a,"seq",0),m=je({name:"entries",...o!==void 0?{retention:{score:(R,E)=>c(E),maxSize:o,onArchive:R=>{l||(e==="hnsw"&&i.remove(R),p.append({action:"evict",id:R,t_ns:se(),seq:Jr(f)}))}}}:{}});if(a.add(m.entries,{name:"entries"}),a.addDisposer(te(m.entries)),i?.dispose){let R=i.dispose.bind(i);a.addDisposer(()=>R())}let h=(R,E,_)=>{u(E),e==="hnsw"&&i.upsert(R,E,_);let O=(()=>{if(_!==void 0)return _===null||typeof _!="object"?_:Array.isArray(_)?[..._]:{..._}})(),N={id:R,vector:[...E],...O!==void 0?{meta:O}:{},upsertedAtNs:V()};m.set(R,N)},g=R=>{m.has(R)&&(e==="hnsw"&&i.remove(R),m.delete(R))},y=()=>{if(m.size!==0){l=!0;try{m.clear(),e==="hnsw"&&i.clear()}finally{l=!1}d=void 0}},b=()=>{if(e!=="hnsw")return;let R=m.entries.cache;if(R){i.clear();for(let E of R.values())i.upsert(E.id,E.vector,E.meta)}},v=nt(h,{audit:p,freeze:!1,seq:f,onSuccess:([R],E,_)=>({action:"upsert",id:R,t_ns:_.t_ns,seq:_.seq})}),T=nt(g,{audit:p,seq:f,onSuccess:([R],E,_)=>({action:"remove",id:R,t_ns:_.t_ns,seq:_.seq})}),w=nt(y,{audit:p,seq:f,onSuccess:(R,E,_)=>({action:"clear",t_ns:_.t_ns,seq:_.seq})}),x=nt(b,{audit:p,seq:f,onSuccess:(R,E,_)=>({action:"reindex",t_ns:_.t_ns,seq:_.seq})});function k(R,E=5){let _=fr(E,"k");return C([m.entries,R,_],O=>{let N=O[0],L=O[1],j=O[2],$=Number.isFinite(j)?Math.max(0,Math.floor(j)):0;if(!N||N.size===0||$<=0)return[];if(L==null||L.length===0)return[];let D=n??(r?d:void 0);return D!==void 0&&L.length!==D?[]:e==="hnsw"?[...i.search(L,$)]:[...N.values()].map(F=>({id:F.id,score:yi(L,F.vector),...F.meta!==void 0?{meta:F.meta}:{}})).sort((F,H)=>H.score-F.score).slice(0,$)},{describeKind:"derived",equals:(O,N)=>Sy(O,N),meta:gt("vector_search")})}return Object.assign(a,{backend:e,events:p,entries:m.entries,upsert:v,remove:T,clear:w,reindex:x,searchNode:k})}var df="\0";function hi(t,e,n){return`${t}${df}${e}${df}${n}`}function uf(t,e){if(!t||t.size===0)return new Map;let n=new Map;for(let o of t.values()){let s=e==="from"?o.from:o.to,i=n.get(s);i||(i=[],n.set(s,i)),i.push(o)}let r=new Map;for(let[o,s]of n)r.set(o,Object.freeze(s));return r}function cf(t,e){if(t===e)return!0;if(t==null||e==null||t.size!==e.size)return!1;for(let[n,r]of t){let o=e.get(n);if(!o||r.length!==o.length)return!1;for(let s=0;s<r.length;s+=1){let i=r[s],a=o[s];if(i.from!==a.from||i.to!==a.to||i.relation!==a.relation||i.weight!==a.weight)return!1}}return!0}function Od(t,e={}){let n=e.orphanGC??"keep";if(e.entitiesMaxSize!==void 0&&e.entitiesMaxSize<1)throw new RangeError("knowledgeGraph: entitiesMaxSize must be >= 1");if(e.edgesMaxSize!==void 0&&e.edgesMaxSize<1)throw new RangeError("knowledgeGraph: edgesMaxSize must be >= 1");let r=new Q(t),o=je({name:"entities",...e.entitiesMaxSize!==void 0?{maxSize:e.entitiesMaxSize}:{}}),s=je({name:"edges",...e.edgesMaxSize!==void 0?{maxSize:e.edgesMaxSize}:{}});r.add(o.entries,{name:"entities"}),r.add(s.entries,{name:"edges"});let i=C([s.entries],([S])=>uf(S,"from"),{name:"adjacencyOut",describeKind:"derived",initial:new Map,equals:cf,meta:gt("adjacency_out")}),a=C([s.entries],([S])=>uf(S,"to"),{name:"adjacencyIn",describeKind:"derived",initial:new Map,equals:cf,meta:gt("adjacency_in")});r.add(i,{name:"adjacencyOut"}),r.add(a,{name:"adjacencyIn"}),r.addDisposer(te(i)),r.addDisposer(te(a));let d=C([o.entries],([S])=>(S??new Map).size,{name:"entityCount",describeKind:"derived",initial:0,meta:gt("entity_count")}),u=C([s.entries],([S])=>(S??new Map).size,{name:"edgeCount",describeKind:"derived",initial:0,meta:gt("edge_count")});r.add(d,{name:"entityCount"}),r.add(u,{name:"edgeCount"}),r.addDisposer(te(d)),r.addDisposer(te(u));let c=at({name:"events",retainedLimit:1024,graph:r}),l=Yt(r,"seq",0);function p(S){let R=i.cache,E=a.cache;return(R?.get(S)?.length??0)>0||(E?.get(S)?.length??0)>0}function f(S){if(n==="remove")for(let R of S)o.has(R)&&(p(R)||(o.delete(R),c.append({action:"orphanRemove",id:R,t_ns:se(),seq:Jr(l)})))}let m=(S,R)=>{o.set(S,R)},h=S=>{let R=s.entries.cache,E=new Set;if(R){let _=[];for(let[O,N]of R)(N.from===S||N.to===S)&&(_.push(O),N.from!==S&&E.add(N.from),N.to!==S&&E.add(N.to));_.length>0&&s.deleteMany(_)}o.has(S)&&o.delete(S),f([...E])},g=(S,R,E,_=1)=>{s.set(hi(S,R,E),{from:S,to:R,relation:E,weight:_})},y=(S,R,E)=>{if(E!==void 0)s.delete(hi(S,R,E));else{let _=s.entries.cache;if(!_)return;let O=[];for(let[N,L]of _)L.from===S&&L.to===R&&O.push(N);O.length>0&&s.deleteMany(O)}f([S,R])},b=nt(m,{audit:c,seq:l,onSuccess:([S],R,E)=>({action:"upsertEntity",id:S,t_ns:E.t_ns,seq:E.seq})}),v=nt(h,{audit:c,seq:l,onSuccess:([S],R,E)=>({action:"removeEntity",id:S,t_ns:E.t_ns,seq:E.seq})}),T=nt(g,{audit:c,seq:l,onSuccess:([S,R,E,_],O,N)=>({action:"link",from:S,to:R,relation:E,weight:_??1,t_ns:N.t_ns,seq:N.seq})}),w=nt(y,{audit:c,seq:l,onSuccess:([S,R,E],_,O)=>({action:"unlink",from:S,to:R,...E!==void 0?{relation:E}:{},t_ns:O.t_ns,seq:O.seq})});function x(S,R){let E=fr(S,"id"),_=R!==void 0?fr(R,"relation"):void 0;return C(_?[i,a,E,_]:[i,a,E],N=>{let L=N[0],j=N[1],$=N[2],D=_?N[3]:void 0,K=L.get($)??[],F=j.get($)??[],H=new Set,G=[];for(let B of K){let re=hi(B.from,B.to,B.relation);H.has(re)||D!==void 0&&B.relation!==D||(H.add(re),G.push(B))}for(let B of F){let re=hi(B.from,B.to,B.relation);H.has(re)||D!==void 0&&B.relation!==D||(H.add(re),G.push(B))}return G},{describeKind:"derived",equals:(N,L)=>{let j=N,$=L;if(j===$)return!0;if(j==null||$==null||j.length!==$.length)return!1;for(let D=0;D<j.length;D+=1){let K=j[D],F=$[D];if(K.from!==F.from||K.to!==F.to||K.relation!==F.relation||K.weight!==F.weight)return!1}return!0},meta:gt("related")})}return Object.assign(r,{events:c,entities:o.entries,edges:s.entries,adjacencyOut:i,adjacencyIn:a,entityCount:d,edgeCount:u,upsertEntity:b,removeEntity:v,link:T,unlink:w,relatedNode:x})}var Ad=Math.LN2/604800;function mr(t){return t instanceof Map?t:new Map}function Cd(t,e,n){let r=Md({dimension:n.dimension});t.add(r.entries,{name:"vectorIndex"});let s=ge([e.store.entries],([i])=>{let a=mr(i);for(let[d,u]of a){let c=n.embedFn(u);c&&r.upsert(d,c,u)}}).subscribe(()=>{});return t.addDisposer(s),{vectors:r,dispose:()=>s()}}function Ld(t,e,n,r){let o=r.mountPath??n,s=Od(`${n}-kg`);if(t.mount(o,s),!r.entityFn)return{kg:s,dispose:()=>{}};let i=r.entityFn,d=ge([e.store.entries],([u])=>{let c=mr(u);for(let[l,p]of c){let f=i(l,p);if(f){for(let m of f.entities??[])s.upsertEntity(m.id,m.value);for(let m of f.relations??[])s.link(m.from,m.to,m.relation,m.weight)}}}).subscribe(()=>{});return t.addDisposer(d),{kg:s,dispose:()=>d()}}function Id(t,e,n){let r=n.decayRate??Ad,o=n.maxActive??1e3,s=n.archiveThreshold??.1,i=n.permanentFilter??(()=>!1),a=_d({name:"permanent"});t.add(a.entries,{name:"permanent"});let d=new Set,u=b=>d.has(b)?"permanent":mr(e.store.entries.cache).has(b)?"active":"archived",c=(b,v)=>{d.add(b),a.upsert(b,v)},l=new Map,p=e.store.entries,f=n.context?Y(n.context):A(null),h=ge([p,f],([b,v])=>{let T=mr(b),w=V(),x=[],k=[];for(let[R,E]of T){if(l.has(R)||l.set(R,w),i(R,E)){k.push({key:R,value:E});continue}let _=n.score(E,v),O=l.get(R)??w,N=Number(w-O)/1e9;En(_,N,r)<s&&x.push(R)}for(let R of l.keys())T.has(R)||l.delete(R);for(let{key:R,value:E}of k)d.has(R)||c(R,E);let S=T.size-d.size;if(S>o){let R=[...T.entries()].filter(([_])=>!d.has(_)).map(([_,O])=>({key:_,score:n.score(O,v)})).sort((_,O)=>_.score-O.score),E=S-o;for(let _=0;_<E&&_<R.length;_++){let O=R[_].key;x.includes(O)||x.push(O)}}x.length>0&&Z(()=>{for(let R of x)e.store.delete(R)})}).subscribe(()=>{}),g=null;n.archiveTier&&(g=t.attachSnapshotStorage([n.archiveTier],n.archiveStorageOptions??{}));let y=()=>{h(),g?.dispose()};return t.addDisposer(y),{tiers:{permanent:a,activeEntries:p,archiveHandle:g,tierOf:u,markPermanent:c},dispose:y}}function _y(t,e){if(!t||!e)return 0;let n=Math.min(t.length,e.length),r=0;for(;r<n&&t[r]===e[r];)r++;return r}function Pd(t,e,n,r,o){let s=o.topK??20,i=o.graphDepth??1,a=o.budget??2e3,d=o.contextWeight??0,u=o.context?Y(o.context):A(null),c=(g,y,b)=>{let v=new Map,T=[];if(n&&b.vector){let E=b.vector,_=n.entries.cache;if(_&&_.size>0&&s>0){T=[..._.values()].map(N=>({id:N.id,score:yi(E,N.vector),...N.meta!==void 0?{meta:N.meta}:{}})).sort((N,L)=>L.score-N.score).slice(0,s);for(let N of T){let L=g.get(N.id);L&&v.set(N.id,{value:L,sources:new Set(["vector"])})}}}let w=[];if(r){let E=r.adjacencyOut.cache,_=r.adjacencyIn.cache,O=[...b.entityIds??[],...v.keys()],N=new Set,L=O;for(let j=0;j<i;j++){let $=[];for(let D of L){if(N.has(D))continue;N.add(D);let K=E?.get(D)??[],F=_?.get(D)??[];for(let H of K){let G=H.to;if(!N.has(G)){$.push(G);let B=g.get(G);if(B){let re=v.get(G);re?re.sources.add("graph"):v.set(G,{value:B,sources:new Set(["graph"])}),w.push(G)}}}for(let H of F){let G=H.from;if(!N.has(G)){$.push(G);let B=g.get(G);if(B){let re=v.get(G);re?re.sources.add("graph"):v.set(G,{value:B,sources:new Set(["graph"])}),w.push(G)}}}}L=$}}for(let[E,_]of g)v.has(E)||v.set(E,{value:_,sources:new Set(["store"])});let x=b.context?.length??0,k=[];for(let[E,{value:_,sources:O}]of v){let N=o.contextOf?o.contextOf(_):void 0,L=o.score(_,y);if(d>0&&x>0){let $=_y(b.context,N);$>0&&(L=L*(1+d*$/x))}let j=N?{key:E,value:_,score:L,sources:[...O],context:N}:{key:E,value:_,score:L,sources:[...O]};k.push(j)}k.sort((E,_)=>_.score-E.score);let S=[],R=0;for(let E of k){let _=o.cost(E.value);if(R+_>a&&S.length>0)break;S.push(E),R+=_}return{packed:S,trace:{vectorCandidates:T,graphExpanded:w,ranked:k,packed:S}}},l=(g,y)=>{if(g===y)return!0;if(g.length!==y.length)return!1;for(let b=0;b<g.length;b++)if(g[b]!==y[b])return!1;return!0},p=A([],{name:"retrieval",describeKind:"state",meta:he("retrieval_pipeline"),equals:l});t.add(p,{name:"retrieval"});let f=A(null,{name:"retrievalTrace",describeKind:"state",meta:he("retrieval_trace")});return t.add(f,{name:"retrievalTrace"}),{retrieval:p,retrievalTrace:f,retrieve:g=>{let y=mr(e.store.entries.cache),{packed:b,trace:v}=c(y,u.cache,g);return Z(()=>{p.emit(b),f.emit(v)}),b},retrieveReactive:g=>{let y=Y(g),b=C([e.store.entries,u,y],([w,x,k])=>{if(k==null)return{packed:[],trace:null};let S=mr(w),{packed:R,trace:E}=c(S,x,k);return{packed:R,trace:E}},{name:"retrievalReactive::result",describeKind:"derived",meta:he("retrieval_reactive_result"),initial:{packed:[],trace:null}}),T=ge([b],([w])=>{let x=w;Z(()=>{p.emit(x.packed),x.trace&&f.emit(x.trace)})}).subscribe(()=>{});return t.addDisposer(T),C([b],([w])=>w.packed,{name:"retrievalReactive",describeKind:"derived",meta:he("retrieval_reactive"),initial:[],equals:l})}}}function My(t,e,n){let r=new Q(t,n.graph);r.tagFactory("agentMemory",st(n));let o;if(n.extractFn)o=n.extractFn;else if(n.adapter&&n.extractPrompt)o=Nd(n.extractPrompt,{adapter:n.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let s=(b,v)=>{let T=v.cache??new Map,w=v.subscribe(x=>{for(let k of x)k[0]===M&&(T=k[1])});return r.addDisposer(w),ke(b,x=>x==null?{upsert:[]}:o(x,T))},i=e;if(n.admissionFilter){let b=Y(e),v=n.admissionFilter;i=C([b],([T])=>{if(v(T))return T},{name:"admissionFilter",describeKind:"derived"})}let a;n.consolidateFn?a=n.consolidateFn:n.adapter&&n.consolidatePrompt&&(a=Ed(n.consolidatePrompt,{adapter:n.adapter}));let d=n.consolidateTrigger;if(!d&&a&&n.reflection?.enabled!==!1){let b=n.reflection?.interval??3e5;d=Ze(b,{period:b})}let u={score:n.score,cost:n.cost,budget:n.budget??2e3,context:n.context,consolidate:a,consolidateTrigger:d},c=js(i,s,u);r.add(c.store.entries,{name:"store"}),r.add(c.compact,{name:"compact"}),r.add(c.size,{name:"size"});let l=null;n.vectorDimensions&&n.vectorDimensions>0&&n.embedFn&&(l=Cd(r,c,{dimension:n.vectorDimensions,embedFn:n.embedFn}).vectors);let p=null;n.enableKnowledgeGraph&&(p=Ld(r,c,t,{mountPath:"kg",entityFn:n.entityFn}).kg);let f=null;n.tiers&&(f=Id(r,c,{...n.tiers,score:n.score,context:n.context}).tiers);let m=null,h=null,g=null,y=null;if(l||p){let b=Pd(r,c,l,p,{score:n.score,cost:n.cost,budget:n.budget,topK:n.retrieval?.topK,graphDepth:n.retrieval?.graphDepth,contextOf:n.contextOf,contextWeight:n.contextWeight,context:n.context});m=b.retrieval,h=b.retrievalTrace,g=b.retrieve,y=b.retrieveReactive}return Object.assign(r,{distillBundle:c,compact:c.compact,size:c.size,vectors:l,kg:p,memoryTiers:f,retrieval:m,retrievalTrace:h,retrieve:g,retrieveReactive:y})}function Oy(t,e,n){let r=t.describe({actor:e,detail:"full"}),o=n?.groupByTags??!0,s=n?.separator??`
|
|
40
|
+
`,i=[],a=n?.sinceVersion;for(let[d,u]of Object.entries(r.nodes)){let c=u.meta??{},l=c.description,p=c.format;if(!l&&!p)continue;if(a!=null&&u.v!=null){let y=a.get(d);if(y!=null&&y.id===u.v.id&&u.v.version<=y.version)continue}let f=l??d,m=u.value,h=c.unit,g;p==="currency"&&typeof m=="number"?g=`$${m.toFixed(2)}`:p==="percentage"&&typeof m=="number"?g=`${(m*100).toFixed(1)}%`:m==null?g="(no value)":g=String(m),h&&p!=="currency"&&p!=="percentage"&&(g=`${g} ${h}`),i.push({path:d,description:f,formatted:g})}if(i.length===0)return"";if(o){let d=new Map,u=[];for(let l of i){let f=r.nodes[l.path].meta?.tags;if(f&&f.length>0){let m=f[0],h=d.get(m);h||(h=[],d.set(m,h)),h.push(l)}else u.push(l)}if(d.size===0)return i.map(l=>`- ${l.description}: ${l.formatted}`).join(s);let c=[];for(let[l,p]of[...d.entries()].sort((f,m)=>f[0].localeCompare(m[0])))c.push(`[${l}]${s}${p.map(f=>`- ${f.description}: ${f.formatted}`).join(s)}`);return u.length>0&&c.push(u.map(l=>`- ${l.description}: ${l.formatted}`).join(s)),c.join(s+s)}return i.map(d=>`- ${d.description}: ${d.formatted}`).join(s)}ae();ne();ve();var wi={};Se(wi,{compileSpec:()=>Mo,decompileGraph:()=>hf,decompileSpec:()=>$y,extractFnFactory:()=>ff,extractSourceFactory:()=>mf,generateCatalogPrompt:()=>gf,isRichFnEntry:()=>Eo,isRichSourceEntry:()=>Fd,llmCompose:()=>By,llmRefine:()=>vf,specDiff:()=>jy,validateSpec:()=>gr,validateSpecAgainstCatalog:()=>_o});ne();var Ti={};Se(Ti,{budgetGate:()=>Dd,effectivenessTracker:()=>Cy,feedback:()=>tn,funnel:()=>Ay,scorer:()=>No});Ae();ae();Me();ne();function vi(t,e){return We("reduction",t,e)}function Ay(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]:Et(...e);o.add(s,{name:"merged"});let i="merged";for(let a=0;a<n.length;a++){let d=n[a],u=new Q(d.name);d.build(u);try{u.resolve("input")}catch{throw new Error(`funnel stage "${d.name}" must define an "input" node`)}try{u.resolve("output")}catch{throw new Error(`funnel stage "${d.name}" must define an "output" node`)}o.mount(d.name,u);let c=o.resolve(i),l=`${d.name}::input`,p=o.resolve(l),f=`__bridge_${i}\u2192${d.name}_input`,m=ge([c],([h])=>{p.emit(h)},{name:f});o.add(m,{name:f}),o.addDisposer(te(m)),i=`${d.name}::output`}return o}function tn(t,e,n,r){let o=r?.maxIterations??10,s=`__feedback_${e}`,i=A(0,{meta:vi("feedback_counter",{maxIterations:o,feedbackFrom:e,feedbackTo:n})});t.add(i,{name:s});let a=t.resolve(e),d=t.resolve(n),u=`__feedback_effect_${e}`,c=U([],(l,p)=>{let f=a.subscribe(m=>{for(let h of m){let g=h[0];if(g===M){let y=h[1];if(y==null)return;Z(()=>{Yr(i,o)&&d.emit(y)})}else if(g===P||g===I){let y=g===I&&h.length>1?[I,h[1]]:[g];i.down([y])}}});return()=>f()},{name:u,describeKind:"effect",meta:{...vi("feedback_effect",{feedbackFrom:e,feedbackTo:n}),_internal:!0}});return t.add(c,{name:u}),t.addDisposer(te(c)),t}function Dd(t,e,n){if(e.length===0)throw new RangeError("budgetGate requires at least one constraint");let r=e.map(f=>f.node),o=[t,...r],s=[],i=!1,a=!1,d=Symbol("budget-gate"),u=new Array(e.length);function c(){return e.every((f,m)=>f.check(u[m]))}function l(f){for(;s.length>0&&c();){let m=s[0];s=s.slice(1),f.emit(m)}s.length===0&&a&&(a=!1,f.down([[q]]))}return U([],(f,m)=>{for(let g=0;g<e.length;g++)u[g]=e[g].node.cache;let h=[];for(let g=0;g<o.length;g++){let y=o[g];h.push(y.subscribe(b=>{for(let v of b)p(v,g,m)}))}return()=>{for(let g of h)g()}},{...n,describeKind:"derived",meta:vi("budget_gate",n?.meta)});function p(f,m,h){let g=f[0];if(m===0){if(g===M)return c()&&s.length===0?h.emit(f[1]):(s.push(f[1]),i||(i=!0,h.up([[Ve,d]]))),!0;if(g===oe)return h.down([[oe]]),!0;if(g===q)return s.length===0?h.down([[q]]):a=!0,!0;if(g===P||g===I){for(let y of s)h.emit(y);return s=[],a=!1,i&&(i=!1,h.up([[ze,d]])),h.down([f]),!0}return!1}return g===M&&(u[m-1]=f[1]),g===M||g===q?(c()&&s.length>0?(l(h),s.length===0&&i&&(i=!1,h.up([[ze,d]]))):!c()&&!i&&s.length>0&&(i=!0,h.up([[Ve,d]])),!0):g===oe?!0:g===I?(h.down([f]),!0):g===P}}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 C(r,i=>{let a=i.slice(0,o),d=i.slice(o),u=[],c=0;for(let l=0;l<o;l++){let p=a[l]??0,f=d[l]??0,h=(s?.[l]?s[l](p):p)*f;u.push(h),c+=h}return{value:a,score:c,breakdown:u}},{...n?{equals:n.equals,resubscribable:n.resubscribable,resetOnTeardown:n.resetOnTeardown}:{},describeKind:"derived",meta:vi("scorer",n?.meta)})}function Cy(t){let e=je({name:t?.name??"effectiveness-entries"}),n=C([e.entries],([i])=>new Map(i),{name:`${t?.name??"effectiveness"}-snapshot`,equals:(i,a)=>{let d=i,u=a;if(d.size!==u.size)return!1;for(let[c,l]of d){let p=u.get(c);if(!p||l.attempts!==p.attempts||l.successes!==p.successes)return!1}return!0}});function r(i,a){let d=e.get(i),u=(d?.attempts??0)+1,c=(d?.successes??0)+(a?1:0);e.set(i,{key:i,attempts:u,successes:c,successRate:c/u})}function o(i){return e.get(i)}let s=te(n);return{node:n,record:r,lookup:o,dispose:()=>s()}}function Eo(t){return typeof t=="object"&&t!==null&&"factory"in t}function Fd(t){return typeof t=="object"&&t!==null&&"factory"in t}function ff(t){return Eo(t)?t.factory:t}function mf(t){return Fd(t)?t.factory:t}function lf(t){let e=t.meta;if(!e||typeof e.factory!="string")return t;let n=e.factory,r=e.factoryArgs??{},o={...t},s=!1;if(t.type==="producer"?o.source==null&&o.fn==null&&(o.source=n,s=!0):o.fn==null&&(o.fn=n,s=!0),o.config==null&&(o.config=r),!s&&(o.meta??e)===e){let i={...e};delete i.factory,delete i.factoryArgs,Object.keys(i).length>0?o.meta=i:o.meta=void 0}return o}function Ly(t){let e={},n=!1;for(let[i,a]of Object.entries(t.nodes)){if(a.type==="template"){e[i]=a;continue}let d=lf(a);e[i]=d,d!==a&&(n=!0)}let r=t.templates,o;if(r){o={};for(let[i,a]of Object.entries(r)){let d={},u=!1;for(let[c,l]of Object.entries(a.nodes)){let p=lf(l);d[c]=p,p!==l&&(u=!0)}o[i]=u?{...a,nodes:d}:a,u&&(n=!0)}}if(!n)return t;let s={...t,nodes:e};return o&&(s.templates=o),s}function gf(t){let e=[];if(t.fns){let n=new Map;for(let[r,o]of Object.entries(t.fns)){let s=Eo(o)?o.tags?.[0]??"Other":"Other";n.has(s)||n.set(s,[]),n.get(s).push(Iy(r,o))}for(let[r,o]of n)e.push(`${r}:
|
|
41
41
|
${o.join(`
|
|
42
|
-
`)}`)}if(t.sources){let n=[];for(let[r,o]of Object.entries(t.sources))n.push(
|
|
42
|
+
`)}`)}if(t.sources){let n=[];for(let[r,o]of Object.entries(t.sources))n.push(Py(r,o));n.length>0&&e.push(`Sources:
|
|
43
43
|
${n.join(`
|
|
44
44
|
`)}`)}return e.join(`
|
|
45
45
|
|
|
46
|
-
`)}function
|
|
46
|
+
`)}function Iy(t,e){if(!Eo(e))return`- ${t}`;let n=`- ${t}: ${e.description}`;if(e.configSchema){let r=Object.entries(e.configSchema).map(([o,s])=>{let i=`${o}: ${s.type}`;return s.enum&&(i+=` (${s.enum.join("|")})`),s.required===!1&&(i+="?"),i});n+=`. Config: { ${r.join(", ")} }`}return n}function Py(t,e){if(!Fd(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 _o(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 d=Gd(a.fn,r);n.push(`Node "${s}": fn "${a.fn}" not found in catalog`+(d?`. Did you mean "${d}"?`:""))}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 d=Gd(a.source,o);n.push(`Node "${s}": source "${a.source}" not found in catalog`+(d?`. Did you mean "${d}"?`:""))}if(a.fn&&a.config&&e.fns?.[a.fn]){let d=e.fns[a.fn];if(Eo(d)&&d.configSchema){for(let[u,c]of Object.entries(d.configSchema))if(c.required!==!1&&!(u in a.config)&&n.push(`Node "${s}": config missing required field "${u}"`),u in a.config&&c.enum){let l=a.config[u];c.enum.includes(l)||n.push(`Node "${s}": config.${u} = ${JSON.stringify(l)}, expected one of: ${c.enum.join(", ")}`)}}}}if(t.templates){for(let[s,i]of Object.entries(t.templates))for(let[a,d]of Object.entries(i.nodes))if(d.fn&&r.size>0&&!r.has(d.fn)){let u=Gd(d.fn,r);n.push(`Template "${s}" node "${a}": fn "${d.fn}" not found in catalog`+(u?`. Did you mean "${u}"?`:""))}}return{valid:n.length===0,errors:n,warnings:[]}}function Gd(t,e){let n=null,r=1/0,o=t.toLowerCase();for(let s of e){let i=Dy(o,s.toLowerCase());i<r&&i<=Math.max(3,Math.floor(t.length/2))&&(r=i,n=s)}return n}function Dy(t,e){let n=t.length,r=e.length,o=Array.from({length:n+1},(s,i)=>Array.from({length:r+1},(a,d)=>i===0?d:d===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 pf=new Set(["state","producer","derived","effect","operator","template"]),Gy=new Set(["state","producer","derived","effect","operator"]);function gr(t){let e=[],n=[];if(t==null||typeof t!="object")return{valid:!1,errors:["GraphSpec must be a non-null object"],warnings:n};let r=t;if((typeof r.name!="string"||r.name.length===0)&&e.push("Missing or empty 'name' field"),r.nodes==null||typeof r.nodes!="object"||Array.isArray(r.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e,warnings:n};let o=new Set(Object.keys(r.nodes)),s=new Map,i=new Map;if(r.templates!=null&&typeof r.templates=="object"&&!Array.isArray(r.templates)){for(let[a,d]of Object.entries(r.templates))if(d!=null&&typeof d=="object"){let u=d;i.set(a,{params:Array.isArray(u.params)?u.params:[]})}}if(r.templates!=null)if(typeof r.templates!="object"||Array.isArray(r.templates))e.push("'templates' must be an object");else for(let[a,d]of Object.entries(r.templates)){if(d==null||typeof d!="object"){e.push(`Template "${a}": must be an object`);continue}let u=d;if(Array.isArray(u.params)||e.push(`Template "${a}": missing 'params' array`),u.nodes==null||typeof u.nodes!="object"||Array.isArray(u.nodes))e.push(`Template "${a}": missing or invalid 'nodes' object`);else{let c=new Set(Array.isArray(u.params)?u.params:[]),l=new Set(Object.keys(u.nodes));for(let[p,f]of Object.entries(u.nodes)){if(f==null||typeof f!="object"){e.push(`Template "${a}" node "${p}": must be an object`);continue}let m=f;if((typeof m.type!="string"||!Gy.has(m.type))&&e.push(`Template "${a}" node "${p}": invalid type`),Array.isArray(m.deps))for(let h of m.deps)!l.has(h)&&!c.has(h)&&e.push(`Template "${a}" node "${p}": dep "${h}" is not an inner node or param`)}typeof u.output!="string"?e.push(`Template "${a}": missing 'output' string`):u.nodes[u.output]||e.push(`Template "${a}": output "${u.output}" is not a declared node`)}}for(let[a,d]of Object.entries(r.nodes)){if(d==null||typeof d!="object"){e.push(`Node "${a}": must be an object`);continue}let u=d;if(typeof u.type!="string"||!pf.has(u.type)){e.push(`Node "${a}": invalid type "${String(u.type)}" (expected: ${[...pf].join(", ")})`);continue}if(s.set(a,u.type),u.type==="template")if(typeof u.template!="string"||!i.has(u.template))e.push(`Node "${a}": template "${String(u.template)}" not found in templates`);else if(u.bind==null||typeof u.bind!="object"||Array.isArray(u.bind))e.push(`Node "${a}": template ref requires 'bind' object`);else{let c=i.get(u.template),l=u.bind;for(let p of c.params)p in l||e.push(`Node "${a}": template param "${p}" is not bound (template "${u.template}")`);for(let[,p]of Object.entries(l))typeof p=="string"&&!o.has(p)&&e.push(`Node "${a}": bind target "${p}" does not reference an existing node`)}else{if(Array.isArray(u.deps))for(let c of u.deps)c===a?e.push(`Node "${a}": self-referencing dep`):o.has(c)||e.push(`Node "${a}": dep "${c}" does not reference an existing node`);(u.type==="derived"||u.type==="effect"||u.type==="operator")&&!Array.isArray(u.deps)&&e.push(`Node "${a}": ${u.type} node should have a 'deps' array`)}}if(r.feedback!=null)if(!Array.isArray(r.feedback))e.push("'feedback' must be an array");else for(let a=0;a<r.feedback.length;a++){let d=r.feedback[a];if(d==null||typeof d!="object"){e.push(`Feedback [${a}]: must be an object`);continue}let u=d;typeof u.from!="string"||!o.has(u.from)?e.push(`Feedback [${a}]: 'from' "${String(u.from)}" does not reference an existing node`):s.get(u.from)==="effect"&&n.push(`Feedback [${a}]: 'from' "${u.from}" is an effect node \u2014 effects emit no DATA, so the feedback edge will never fire. Did you mean a derived/state node upstream?`),typeof u.from=="string"&&u.from===u.to&&e.push(`Feedback [${a}]: 'from' and 'to' must be different nodes`),typeof u.to!="string"||!o.has(u.to)?e.push(`Feedback [${a}]: 'to' "${String(u.to)}" does not reference an existing node`):typeof u.to=="string"&&s.get(u.to)!=="state"&&e.push(`Feedback [${a}]: 'to' node "${u.to}" must be a state node (got "${s.get(u.to)??"unknown"}")`)}return{valid:e.length===0,errors:e,warnings:n}}function Mo(t,e){let n=gr(t);if(!n.valid)throw new Error(`compileSpec: invalid GraphSpec:
|
|
47
47
|
${n.errors.join(`
|
|
48
|
-
`)}`);let r=e?.catalog??{},
|
|
49
|
-
${
|
|
50
|
-
`)}`);let
|
|
51
|
-
${
|
|
52
|
-
`)}`)}if(
|
|
48
|
+
`)}`);let r=t.factory,o=t.factoryArgs;if(typeof r=="string"){let b=e?.catalog?.graphFactories?.[r];if(b)return b(o)}t=Ly(t);let s=e?.catalog??{},i=e?.onMissing??"placeholder",a=new Q(t.name),d=t.templates??{},u=_o(t,s);if(!u.valid)throw new Error(`compileSpec: catalog validation errors:
|
|
49
|
+
${u.errors.join(`
|
|
50
|
+
`)}`);let c=[],l=(b,v,T)=>{if(T){c.push({path:b,kind:"source",name:T});return}v&&c.push({path:b,kind:"fn",name:v})},p=b=>{let v=s.fns?.[b];return v?ff(v):void 0},f=b=>{let v=s.sources?.[b];return v?mf(v):void 0},m=new Map,h=[];for(let[b,v]of Object.entries(t.nodes)){if(v.type==="template")continue;let T=v;if(T.type==="state"){let w=A(T.initial,{name:b,meta:T.meta?{...T.meta}:void 0});a.add(w,{name:b}),m.set(b,w)}else if(T.type==="producer"){let w=T.source?f(T.source):void 0,x=T.fn?p(T.fn):void 0;if(w){let k=w(T.config??{});a.add(k,{name:b}),m.set(b,k)}else if(x){let k=x([],T.config??{});a.add(k,{name:b}),m.set(b,k)}else{l(b,T.fn,T.source);let k=z(()=>{},{name:b,meta:{...T.meta,_specFn:T.fn,_specSource:T.source}});a.add(k,{name:b}),m.set(b,k)}}else h.push([b,T])}let g=!0,y=new Map(h);for(;y.size>0&&g;){g=!1;for(let[b,v]of[...y.entries()]){let T=v.deps??[];if(!T.every(S=>m.has(S)))continue;let w=T.map(S=>m.get(S)),x=v.fn?p(v.fn):void 0,k;x?k=x(w,v.config??{}):v.type==="effect"?(v.fn&&l(b,v.fn,void 0),k=ge(w,()=>{})):(v.fn&&l(b,v.fn,void 0),k=C(w,S=>S[0])),a.add(k,{name:b}),m.set(b,k),y.delete(b),g=!0}}if(y.size>0){let b=[...y.keys()].sort().join(", ");throw new Error(`compileSpec: unresolvable deps for nodes: ${b}`)}for(let[b,v]of Object.entries(t.nodes)){if(v.type!=="template")continue;let T=v,w=d[T.template],x=new Q(b),k=new Map,S=[];for(let[O,N]of Object.entries(w.nodes)){let L=(N.deps??[]).map($=>$.startsWith("$")&&T.bind[$]?T.bind[$]:$),j={...N,deps:L};if(N.type==="state"){let $=A(N.initial,{name:O,meta:N.meta?{...N.meta}:void 0});x.add($,{name:O}),k.set(O,$)}else if(N.type==="producer"){let $=N.source?f(N.source):void 0,D=N.fn?p(N.fn):void 0;if($){let K=$(N.config??{});x.add(K,{name:O}),k.set(O,K)}else if(D){let K=D([],N.config??{});x.add(K,{name:O}),k.set(O,K)}else{l(`${b}.${O}`,N.fn,N.source);let K=z(()=>{},{name:O,meta:{...N.meta,_specFn:N.fn,_specSource:N.source}});x.add(K,{name:O}),k.set(O,K)}}else S.push([O,j])}let R=!0,E=new Map(S);for(;E.size>0&&R;){R=!1;for(let[O,N]of[...E.entries()]){let L=N.deps??[];if(!L.every(F=>k.has(F)||m.has(F)))continue;let $=L.map(F=>k.get(F)??m.get(F)),D=N.fn?p(N.fn):void 0,K;D?K=D($,N.config??{}):N.type==="effect"?(N.fn&&l(`${b}.${O}`,N.fn,void 0),K=ge($,()=>{})):(N.fn&&l(`${b}.${O}`,N.fn,void 0),K=C($,F=>F[0])),x.add(K,{name:O}),k.set(O,K),E.delete(O),R=!0}}if(E.size>0){let O=[...E.keys()].sort().join(", ");throw new Error(`compileSpec: template "${T.template}" has unresolvable deps: ${O}`)}a.mount(b,x);let _=`${b}::${w.output}`;m.set(b,a.resolve(_));try{let O=a.resolve(_);O.meta._templateName?.emit(T.template),O.meta._templateBind?.emit(T.bind)}catch{}}for(let b of t.feedback??[])tn(a,b.from,b.to,{maxIterations:b.maxIterations});if(c.length>0){if(i==="error"){let b=c.map(v=>` - ${v.path}: missing ${v.kind} "${v.name}"`);throw new Error(`compileSpec: ${c.length} catalog entr${c.length===1?"y":"ies"} missing \u2014 pass them via opts.catalog or set opts.onMissing to "warn"/"placeholder":
|
|
51
|
+
${b.join(`
|
|
52
|
+
`)}`)}if(i==="warn"){let b=e?.onWarn??(v=>console.warn(v));for(let v of c)b(`compileSpec: ${v.path} references missing ${v.kind} "${v.name}" \u2014 substituted placeholder`)}}return a}var Fy=new Set(["reduction","reduction_type","_specFn","_specSource","_templateName","_templateBind","feedbackFrom","feedbackTo","_internal"]);function $y(t){return hf(t)}function hf(t){let e=t.describe({detail:"standard"}),n={},r=[],o=`::${tt}::`,s=/^__feedback_(?!effect_)(.+)$/,i=new Set;for(let f of Object.keys(e.nodes)){if(f.includes(o))continue;let m=s.exec(f);if(m){i.add(m[1]);let h=e.nodes[f]?.meta;h?.feedbackFrom&&h?.feedbackTo&&r.push({from:h.feedbackFrom,to:h.feedbackTo,...h.maxIterations?{maxIterations:h.maxIterations}:{}})}}for(let[f,m]of Object.entries(e.nodes)){if(f.includes(o)||s.test(f)||m.meta?._internal||f.startsWith("__feedback_effect_")||f.startsWith("__bridge_")||f.includes("::"))continue;let h={type:m.type};if(m.deps.length>0&&(h.deps=m.deps.filter(g=>!g.includes("::"))),m.type==="state"&&m.value!==void 0&&(h.initial=m.value),m.meta&&Object.keys(m.meta).length>0){let g={};for(let[y,b]of Object.entries(m.meta))Fy.has(y)||(g[y]=b);g.factory==="withStatus"?(delete g.status,delete g.error):g.factory==="withBreaker"?delete g.breakerState:g.factory==="verifiable"&&delete g.sourceVersion,Object.keys(g).length>0&&(h.meta=g)}n[f]=h}let a={},d={},u=new Set;for(let f of e.subgraphs){let m=`${f}::`;for(let[h,g]of Object.entries(e.nodes)){if(!h.startsWith(m)||h.includes(o))continue;let y=g.meta;if(y?._templateName&&y?._templateBind){let b=y._templateName,v=y._templateBind;if(!a[b]){let T={},w=new Set,x=`${f}::`;for(let[O,N]of Object.entries(e.nodes)){if(!O.startsWith(x)||O.includes(o))continue;let L=O.slice(x.length);L.includes("::")||(w.add(L),T[L]={type:N.type,...N.deps.length>0?{deps:N.deps.map(j=>j.startsWith(x)?j.slice(x.length):j)}:{}})}let k=[],S=new Map;for(let O of Object.values(T))for(let N of O.deps??[])if(!w.has(N)&&!S.has(N)){let L=`$${N}`;k.push(L),S.set(N,L)}for(let O of Object.values(T))O.deps&&(O.deps=O.deps.map(N=>S.get(N)??N));let R=new Set;for(let O of Object.values(T))for(let N of O.deps??[])w.has(N)&&R.add(N);let _=[...w].filter(O=>!R.has(O))[0]??[...w].pop();a[b]={params:k,nodes:T,output:_}}delete n[f],d[f]={type:"template",template:b,bind:v},u.add(f);break}}}let c=new Map;for(let f of e.subgraphs){if(u.has(f))continue;let m={},h=`${f}::`;for(let[y,b]of Object.entries(e.nodes)){if(y.includes(o)||!y.startsWith(h))continue;let v=y.slice(h.length);v.includes("::")||(m[v]={type:b.type,...b.deps.length>0?{deps:b.deps.map(T=>T.startsWith(h)?T.slice(h.length):T)}:{}})}let g=JSON.stringify(Object.fromEntries(Object.entries(m).sort(([y],[b])=>y.localeCompare(b)).map(([y,b])=>[y,{type:b.type,deps:b.deps??[]}])));c.has(g)||c.set(g,[]),c.get(g).push({name:f,nodes:m})}for(let[,f]of c){if(f.length<2)continue;let m=`${f[0].name}_template`,h=f[0].nodes,g=new Set(Object.keys(h)),y=[],b=new Map;for(let k of Object.values(h))for(let S of k.deps??[])if(!g.has(S)&&!b.has(S)){let R=`$${S}`;y.push(R),b.set(S,R)}let v=new Set;for(let k of Object.values(h))for(let S of k.deps??[])g.has(S)&&v.add(S);let w=[...g].filter(k=>!v.has(k))[0]??[...g].pop(),x={};for(let[k,S]of Object.entries(h))x[k]={...S,deps:S.deps?.map(R=>b.get(R)??R)};a[m]={params:y,nodes:x,output:w};for(let k of f){delete n[k.name];let S={},R=new Set(Object.keys(k.nodes));for(let E of Object.values(k.nodes))for(let _ of E.deps??[])if(!R.has(_)){let O=b.get(_)??`$${_}`;S[O]=_}d[k.name]={type:"template",template:m,bind:S}}}let l={...n,...d},p={name:e.name,nodes:l};return Object.keys(a).length>0&&(p.templates=a),r.length>0&&(p.feedback=r),e.factory!==void 0&&(p.factory=e.factory),e.factoryArgs!==void 0&&(p.factoryArgs=e.factoryArgs),p}function jy(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)),d=new Set(Object.keys(i));for(let b of d)a.has(b)||n.push({type:"added",path:`templates.${b}`});for(let b of a)d.has(b)||n.push({type:"removed",path:`templates.${b}`});for(let b of a)d.has(b)&&JSON.stringify(s[b])!==JSON.stringify(i[b])&&n.push({type:"changed",path:`templates.${b}`,detail:"template definition changed"});let u=t.feedback??[],c=e.feedback??[],l=new Set(u.map(b=>`${b.from}->${b.to}`)),p=new Set(c.map(b=>`${b.from}->${b.to}`));for(let b of c){let v=`${b.from}->${b.to}`;l.has(v)||n.push({type:"added",path:`feedback.${v}`,detail:`maxIterations: ${b.maxIterations??10}`})}for(let b of u){let v=`${b.from}->${b.to}`;p.has(v)||n.push({type:"removed",path:`feedback.${v}`})}for(let b of u){let v=`${b.from}->${b.to}`,T=c.find(w=>w.from===b.from&&w.to===b.to);T&&JSON.stringify(b)!==JSON.stringify(T)&&n.push({type:"changed",path:`feedback.${v}`,detail:`maxIterations: ${b.maxIterations??10} \u2192 ${T.maxIterations??10}`})}let f=n.filter(b=>b.type==="added").length,m=n.filter(b=>b.type==="removed").length,h=n.filter(b=>b.type==="changed").length,g=[];f&&g.push(`${f} added`),m&&g.push(`${m} removed`),h&&g.push(`${h} changed`);let y=g.length>0?g.join(", "):"no changes";return{entries:n,summary:y}}var yf=`You are a graph architect for GraphReFly, a reactive graph protocol.
|
|
53
53
|
|
|
54
54
|
Given a natural-language description, produce a JSON GraphSpec with this structure:
|
|
55
55
|
|
|
@@ -91,20 +91,20 @@ Rules:
|
|
|
91
91
|
- Use "templates" when the same subgraph pattern repeats (e.g., per-source resilience).
|
|
92
92
|
- Use "feedback" for bounded cycles where a derived value writes back to a state node.
|
|
93
93
|
- meta.description is required for every node.
|
|
94
|
-
- Return ONLY valid JSON, no markdown fences or commentary.`;function
|
|
94
|
+
- Return ONLY valid JSON, no markdown fences or commentary.`;function bf(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}async function By(t,e,n){let r=yf,o=n?.catalogDescription??(n?.catalog?gf(n.catalog):void 0);o&&(r+=`
|
|
95
95
|
|
|
96
96
|
Available catalog (use ONLY these names):
|
|
97
97
|
${o}`),n?.systemPromptExtra&&(r+=`
|
|
98
98
|
|
|
99
|
-
${n.systemPromptExtra}`);let s=[{role:"system",content:r},{role:"user",content:t}],
|
|
99
|
+
${n.systemPromptExtra}`);let s=[{role:"system",content:r},{role:"user",content:t}],d=(await e.invoke(s,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens})).content.trim();d.startsWith("```")&&(d=bf(d));let u;try{u=JSON.parse(d)}catch{throw new Error(`llmCompose: LLM response is not valid JSON: ${d.slice(0,200)}`)}let c=gr(u);if(!c.valid)throw new Error(`llmCompose: invalid GraphSpec:
|
|
100
100
|
${c.errors.join(`
|
|
101
|
-
`)}`);let l=
|
|
101
|
+
`)}`);let l=u;if(n?.catalog){let p=n.maxAutoRefine??0;for(let f=0;f<=p;f++){let m=_o(l,n.catalog);if(m.valid)break;if(f===p)throw new Error(`llmCompose: catalog validation failed after ${p} refine attempts:
|
|
102
102
|
${m.errors.join(`
|
|
103
|
-
`)}`);l=await
|
|
103
|
+
`)}`);l=await vf(l,`Fix these catalog errors:
|
|
104
104
|
${m.errors.join(`
|
|
105
105
|
`)}
|
|
106
106
|
|
|
107
|
-
Use ONLY functions and sources from the catalog.`,e,{...n,catalogDescription:o})}}return l}async function
|
|
107
|
+
Use ONLY functions and sources from the catalog.`,e,{...n,catalogDescription:o})}}return l}async function vf(t,e,n,r){let o=yf;r?.catalogDescription&&(o+=`
|
|
108
108
|
|
|
109
109
|
Available catalog:
|
|
110
110
|
${r.catalogDescription}`),r?.systemPromptExtra&&(o+=`
|
|
@@ -114,9 +114,9 @@ ${JSON.stringify(t,null,2)}
|
|
|
114
114
|
|
|
115
115
|
Modification request: ${e}
|
|
116
116
|
|
|
117
|
-
Return the complete modified GraphSpec as JSON.`}],
|
|
117
|
+
Return the complete modified GraphSpec as JSON.`}],d=(await n.invoke(s,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens})).content.trim();d.startsWith("```")&&(d=bf(d));let u;try{u=JSON.parse(d)}catch{throw new Error(`llmRefine: LLM response is not valid JSON: ${d.slice(0,200)}`)}let c=gr(u);if(!c.valid)throw new Error(`llmRefine: invalid GraphSpec:
|
|
118
118
|
${c.errors.join(`
|
|
119
|
-
`)}`);return
|
|
119
|
+
`)}`);return u}var Tf=`You are a graph architect for GraphReFly, a reactive graph protocol.
|
|
120
120
|
|
|
121
121
|
Given a natural-language description, produce a JSON graph specification with this structure:
|
|
122
122
|
|
|
@@ -149,9 +149,9 @@ Rules:
|
|
|
149
149
|
- "operator" nodes are parameterized transformations with deps.
|
|
150
150
|
- Use "deps" inside each node to declare dependencies \u2014 no separate "edges" array.
|
|
151
151
|
- meta.description is required for every node.
|
|
152
|
-
- Return ONLY valid JSON, no markdown fences or commentary.`;async function
|
|
152
|
+
- Return ONLY valid JSON, no markdown fences or commentary.`;async function wf(t,e,n){let o=[{role:"system",content:n?.systemPromptExtra?`${Tf}
|
|
153
153
|
|
|
154
|
-
${n.systemPromptExtra}`:
|
|
154
|
+
${n.systemPromptExtra}`:Tf},{role:"user",content:t}],s=e.invoke(o,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens,signal:n?.signal}),a=(await To(s)).content.trim();a.startsWith("```")&&(a=cr(a));let d;try{d=JSON.parse(a)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${a.slice(0,200)}`)}return Mo(d,{catalog:n?.catalog})}function Vy(t,e,n){let r=Y(t);return ke(r,o=>!o||typeof o!="string"||o.trim().length===0?A(null):z(s=>{let i=new AbortController,a=!1;return wf(o,e,{...n,signal:i.signal}).then(d=>{if(a){d.destroy();return}s.emit(d),s.down([[P]])}).catch(d=>{a||s.down([[I,d]])}),()=>{a=!0,i.abort()}},{name:"graphFromSpec::call"}))}function Ky(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 qy(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 d=a.meta??{},u=d.access;if(u==="human"||u==="system")continue;let c=d.description??`Set the value of ${i}`,l=Ky(d),p={type:"object",required:["value"],properties:{value:l},additionalProperties:!1},f=i.replace(/::/g,"__");r.push({type:"function",function:{name:f,description:c,parameters:p}}),o.push({name:i,description:c,inputSchema:p});let m=t,h=e,g=a.v;s.push({name:i,description:c,parameters:p,handler(y){return m.set(i,y.value,h?{actor:h}:void 0),y.value},...g!=null?{version:{id:g.id,version:g.version}}:{}})}return{openai:r,mcp:o,definitions:s}}ae();ne();ve();var zy=`You are a reactive graph optimizer for GraphReFly.
|
|
155
155
|
|
|
156
156
|
Given a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.
|
|
157
157
|
|
|
@@ -172,8 +172,8 @@ Return ONLY valid JSON with this structure:
|
|
|
172
172
|
Rules:
|
|
173
173
|
- Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).
|
|
174
174
|
- Keep changes minimal \u2014 prefer the smallest set of operations that solves the problem.
|
|
175
|
-
- Return ONLY valid JSON, no markdown fences or commentary.`;async function
|
|
176
|
-
`?p="hard-break":p="text",c!==null&&p===c?d+=l:(c!==null&&(i.push(d),a.push(c==="text"&&s),u.push(c)),d=l,c=p)}c!==null&&(i.push(d),a.push(c==="text"&&s),u.push(c)),n.push({texts:i,isWordLike:a,kinds:u})}return n}function Ft(t,e,n,r,o){let s=Iy(t);if(s.length===0)return[];let i=Py(s),a=new Intl.Segmenter(void 0,{granularity:"grapheme"}),u=[],d=[],c=[];for(let y of i)for(let b=0;b<y.texts.length;b++)u.push(y.texts[b]),d.push(y.kinds[b]),c.push(y.isWordLike[b]);let l=[],p=[],f=[];for(let y=0;y<u.length;y++){let b=u[y],v=d[y],T=c[y];if(v==="text"&&!T&&l.length>0&&p[p.length-1]==="text"&&b.length===1&&(Ly.has(b)||af.has(b))){l[l.length-1]+=b;continue}if(b==="-"&&l.length>0&&p[p.length-1]==="text"&&f[f.length-1]){l[l.length-1]+=b;continue}l.push(b),p.push(v),f.push(T)}let m=r.get(e);m||(m=new Map,r.set(e,m));function h(y){let b=m.get(y);if(b===void 0){o&&(o.misses+=1);let v=n.measureSegment(y,e).width;b=Number.isFinite(v)&&v>=0?v:0,m.set(y,b)}else o&&(o.hits+=1);return b}let g=[];for(let y=0;y<l.length;y++){let b=l[y],v=p[y];if(v!=="text"){g.push({text:b,width:v==="space"?h(" ")*b.length:0,kind:v,graphemeWidths:null});continue}if(Ay(b)){let x="";for(let k of a.segment(b)){let S=k.segment;if(x.length>0&&af.has(S)){x+=S;continue}if(x.length>0){let R=h(x);g.push({text:x,width:R,kind:"text",graphemeWidths:null})}x=S}if(x.length>0){let k=h(x);g.push({text:x,width:k,kind:"text",graphemeWidths:null})}continue}let T=h(b),w=null;if(f[y]&&b.length>1){let x=[];for(let k of a.segment(b))x.push(h(k.segment));x.length>1&&(w=x)}g.push({text:b,width:T,kind:"text",graphemeWidths:w})}return g}function Rn(t,e,n,r,o){if(t.length===0)return{lines:[],lineCount:0};let s=[],i=0,a=!1,u=0,d=0,c=0,l=0,p=-1,f=0,m=o.get(r);m||(m=new Map,o.set(r,m));let h=m.get("-");h===void 0&&(h=n.measureSegment("-",r).width,m.set("-",h));function g(w=c,x=l,k=i){let S="";for(let R=u;R<w;R++){let N=t[R];if(!(N.kind==="soft-hyphen"||N.kind==="hard-break"))if(R===u&&d>0&&N.graphemeWidths){let I=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(N.text)].map(O=>O.segment);S+=I.slice(d).join("")}else S+=N.text}if(x>0&&w<t.length){let R=t[w],_=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(R.text)].map(O=>O.segment),I=u===w?d:0;S+=_.slice(I,x).join("")}w>0&&t[w-1]?.kind==="soft-hyphen"&&!(u===w&&d>0)&&(S+="-"),s.push({text:S,width:k,startSegment:u,startGrapheme:d,endSegment:w,endGrapheme:x}),i=0,a=!1,p=-1,f=0}function y(w){return w==="space"||w==="zero-width-break"||w==="soft-hyphen"}function b(w,x,k){a=!0,u=w,d=x,c=w+1,l=0,i=k}function v(w,x,k){a=!0,u=w,d=x,c=w,l=x+1,i=k}for(let w=0;w<t.length;w++){let x=t[w];if(x.kind==="hard-break"){a?g():s.push({text:"",width:0,startSegment:w,startGrapheme:0,endSegment:w,endGrapheme:0}),u=w+1,d=0;continue}let k=x.width;if(!a){k>e&&x.graphemeWidths?T(w,0,x.graphemeWidths):b(w,0,k),y(x.kind)&&(p=w+1,f=x.kind==="space"?i-k:i);continue}let S=i+k;if(S>e+.005){if(y(x.kind)){i+=k,c=w+1,l=0,g(w+1,0,x.kind==="space"?i-k:i);continue}if(p>=0){g(p,0,f),w--;continue}if(k>e&&x.graphemeWidths){g(),T(w,0,x.graphemeWidths);continue}g(),w--;continue}i=S,c=w+1,l=0,y(x.kind)&&(p=w+1,f=x.kind==="space"?i-k:i)}return a&&g(),{lines:s,lineCount:s.length};function T(w,x,k){for(let S=x;S<k.length;S++){let R=k[S];if(!a){v(w,S,R);continue}i+R>e+.005?(g(),v(w,S,R)):(i+=R,c=w,l=S+1)}a&&c===w&&l===k.length&&(c=w+1,l=0)}}function Cu(t){return t==="space"||t==="zero-width-break"||t==="soft-hyphen"}var Au=null;function Dy(){return Au===null&&(Au=new Intl.Segmenter(void 0,{granularity:"grapheme"})),Au}function uf(t,e,n){if(e===0&&n<0)return t.text;let r=[...Dy().segment(t.text)].map(s=>s.segment),o=n<0?r.length:n;return r.slice(e,o).join("")}function Xt(t,e,n,r,o,s){let i="";for(let a=e;a<r;a++){let u=t[a];u.kind==="soft-hyphen"||u.kind==="hard-break"||(a===e&&n>0?i+=uf(u,n,-1):i+=u.text)}if(o>0&&r<t.length){let a=t[r];i+=uf(a,e===r?n:0,o)}return s&&(i+="-"),i}function Gy(t){if(!t?.adapter||!t.font)return 0;let e=t.cache;if(e){let n=e.get(t.font);n||(n=new Map,e.set(t.font,n));let r=n.get("-");return r===void 0&&(r=t.adapter.measureSegment("-",t.font).width,n.set("-",r)),r}return t.adapter.measureSegment("-",t.font).width}function Lu(t,e,n,r){let o=e.segmentIndex,s=e.graphemeIndex;if(o>=t.length)return null;if(s===0){for(;o<t.length;){let w=t[o];if(w.kind==="hard-break")return{text:"",width:0,start:{segmentIndex:e.segmentIndex,graphemeIndex:0},end:{segmentIndex:o+1,graphemeIndex:0}};if(w.kind==="space"||w.kind==="zero-width-break"||w.kind==="soft-hyphen"){o+=1;continue}break}if(o>=t.length)return null}let i=Gy(r),a=o,u=o===e.segmentIndex?s:0,d=0,c=a,l=0,p=!1,f=-1,m=0,h=0,g=!1,y=(w,x,k,S)=>{f=w,m=x,h=k,g=S==="soft-hyphen"},b=(w,x,k)=>{for(let S=x;S<k.length;S++){let R=k[S];if(!p){d=R,c=w,l=S+1,p=!0;continue}if(d+R>n+.005)return!0;d+=R,c=w,l=S+1}return c===w&&l===k.length&&(c=w+1,l=0),!1};if(u>0&&a<t.length){let w=t[a];if(w.graphemeWidths){if(b(a,u,w.graphemeWidths))return{text:Xt(t,a,u,c,l,!1),width:d,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}};o=c}}for(;o<t.length;){let w=t[o];if(w.kind==="hard-break"){if(p){let S=c>0&&t[c-1]?.kind==="soft-hyphen";return{text:Xt(t,a,u,c,l,S),width:d+(S?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}}}return{text:"",width:0,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:o+1,graphemeIndex:0}}}let x=w.width;if(!p){if(x>n&&w.graphemeWidths){if(b(o,0,w.graphemeWidths))return{text:Xt(t,a,u,c,l,!1),width:d,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}};o=c;continue}d=x,c=o+1,l=0,p=!0,Cu(w.kind)&&y(o+1,0,w.kind==="space"?d-x:d,w.kind),o+=1;continue}let k=d+x;if(k>n+.005){if(Cu(w.kind)){c=o+1,l=0;let R=w.kind==="soft-hyphen",N=w.kind==="space"?d:d+(R?i:0);return{text:Xt(t,a,u,c,l,R),width:N,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}}}return f>=0?{text:Xt(t,a,u,f,m,g),width:h+(g?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:f,graphemeIndex:m}}:x>n&&w.graphemeWidths?{text:Xt(t,a,u,c,l,!1),width:d,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}}:{text:Xt(t,a,u,c,l,!1),width:d,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}}}d=k,c=o+1,l=0,Cu(w.kind)&&y(o+1,0,w.kind==="space"?d-x:d,w.kind),o+=1}if(!p)return null;let v=c>0&&t[c-1]?.kind==="soft-hyphen";return{text:Xt(t,a,u,c,l,v),width:d+(v?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}}}function Iu(t,e,n=0){let r=[t];for(let o=0;o<e.length;o++){let s=e[o],i=[];for(let a=0;a<r.length;a++){let u=r[a];if(s.right<=u.left||s.left>=u.right){i.push(u);continue}s.left>u.left&&i.push({left:u.left,right:s.left}),s.right<u.right&&i.push({left:s.right,right:u.right})}r=i}return n>0?r.filter(o=>o.right-o.left>=n):r}function bi(t,e,n){let r=[],o=new Intl.Segmenter(void 0,{granularity:"grapheme"});for(let s=0;s<t.lines.length;s++){let i=t.lines[s],a=s*n,u=0;for(let d=i.startSegment;d<e.length;d++){let c=e[d];if(c.kind==="soft-hyphen"||c.kind==="hard-break"){if(d>=i.endSegment&&i.endGrapheme===0)break;continue}let l=[...o.segment(c.text)].map(m=>m.segment);if(l.length===0)continue;let p=d===i.startSegment?i.startGrapheme:0,f;if(d<i.endSegment)f=l.length;else if(d===i.endSegment&&i.endGrapheme>0)f=i.endGrapheme;else break;for(let m=p;m<f;m++){let h=c.graphemeWidths?c.graphemeWidths[m]:c.width/l.length;r.push({x:u,y:a,width:h,height:n,line:s}),u+=h}}}return r}function Fy(t){let{adapter:e,name:n="reactive-layout"}=t,r=new Y(n),o=new Map,s=M(t.text??"",{name:"text"}),i=M(t.font??"16px sans-serif",{name:"font"}),a=M(t.lineHeight??20,{name:"line-height"}),u=M(Math.max(0,t.maxWidth??800),{name:"max-width"});function d(m,h){if(m===null||h===null)return m===h;if(m.length!==h.length)return!1;for(let g=0;g<m.length;g++)if(m[g]!==h[g])return!1;return!0}let c=z([s,i],(m,h,g)=>{let y=m[0],b=y!=null&&y.length>0?y.at(-1):g.prevData[0],v=m[1],T=v!=null&&v.length>0?v.at(-1):g.prevData[1],w=H(),x={hits:0,misses:0},k=Ft(b,T,e,o,x),S=H()-w,R=x.hits+x.misses,N=R===0?1:x.hits/R,_=c.meta;_&&(mt(_["cache-hit-rate"],N),mt(_["segment-count"],k.length),mt(_["layout-time-ns"],S)),h.emit(k);let I=()=>{o.clear(),e.clearCache?.()};return{deactivate:I,invalidate:I}},{name:"segments",describeKind:"derived",meta:{"cache-hit-rate":0,"segment-count":0,"layout-time-ns":0},equals:(m,h)=>{let g=m,y=h;if(g==null||y==null)return g===y;if(g.length!==y.length)return!1;for(let b=0;b<g.length;b++){let v=g[b],T=y[b];if(v.text!==T.text||v.width!==T.width||v.kind!==T.kind||!d(v.graphemeWidths??null,T.graphemeWidths??null))return!1}return!0}}),l=A([c,u,i],([m,h,g])=>Rn(m,h,e,g,o),{name:"line-breaks",equals:(m,h)=>{let g=m,y=h;if(g==null||y==null)return g===y;if(g.lineCount!==y.lineCount)return!1;for(let b=0;b<g.lines.length;b++){let v=g.lines[b],T=y.lines[b];if(v.text!==T.text||v.width!==T.width||v.startSegment!==T.startSegment||v.startGrapheme!==T.startGrapheme||v.endSegment!==T.endSegment||v.endGrapheme!==T.endGrapheme)return!1}return!0}}),p=A([l,a],([m,h])=>m.lineCount*h,{name:"height"}),f=A([l,c,a],([m,h,g])=>bi(m,h,g),{name:"char-positions",equals:(m,h)=>{let g=m,y=h;if(g==null||y==null)return g===y;if(g.length!==y.length)return!1;for(let b=0;b<g.length;b++)if(g[b].x!==y[b].x||g[b].y!==y[b].y||g[b].width!==y[b].width)return!1;return!0}});return r.add(s,{name:"text"}),r.add(i,{name:"font"}),r.add(a,{name:"line-height"}),r.add(u,{name:"max-width"}),r.add(c,{name:"segments"}),r.add(l,{name:"line-breaks"}),r.add(p,{name:"height"}),r.add(f,{name:"char-positions"}),{graph:r,setText:m=>r.set("text",m),setFont:m=>r.set("font",m),setLineHeight:m=>r.set("line-height",m),setMaxWidth:m=>r.set("max-width",Math.max(0,m)),segments:c,lineBreaks:l,height:p,charPositions:f}}function xo(t){return Math.max(0,Math.min(1,t))}function $y(t){let e=xo(t?.mainRatio??.65),n=xo(t?.sideSplit??.5),r=Math.max(0,t?.viewportWidth??1280),o=t?.nodeRegistry??new Map,s=t?.adapter??null,i=t?.layoutFont??"14px monospace",a=t?.onHighlight,u=new Y("demo-shell"),d=M(e,{name:"pane/main-ratio"}),c=M(n,{name:"pane/side-split"}),l=M(null,{name:"pane/fullscreen"}),p=M(r,{name:"viewport/width"});u.add(d,{name:"pane/main-ratio"}),u.add(c,{name:"pane/side-split"}),u.add(l,{name:"pane/fullscreen"}),u.add(p,{name:"viewport/width"});let f=A([d,p,l],([D,Z,F])=>{let Q=D,G=Z,q=F;return q==="main"?G:q==="graph"||q==="code"?0:Math.round(G*Q)},{name:"pane/main-width"}),m=A([f,p,l],([D,Z,F])=>{let Q=F,G=Z;return Q==="main"?0:Q==="graph"||Q==="code"?G:G-D},{name:"pane/side-width"}),h=A([c,l],([D,Z])=>{let F=Z;return F==="graph"?1:F==="code"||F==="main"?0:xo(D)},{name:"pane/graph-height-ratio"}),g=A([h,l],([D,Z])=>{let F=Z;return F==="code"?1:F==="graph"||F==="main"?0:1-D},{name:"pane/code-height-ratio"});u.add(f,{name:"pane/main-width"}),u.add(m,{name:"pane/side-width"}),u.add(h,{name:"pane/graph-height-ratio"}),u.add(g,{name:"pane/code-height-ratio"});let y=M(null,{name:"demo/graph-ref"}),b=M(0,{name:"demo/graph-tick"});u.add(y,{name:"demo/graph-ref"}),u.add(b,{name:"demo/graph-tick"});let v=A([y,b],([D,Z])=>{let F=D;return F?F.describe({format:"mermaid"}):""},{name:"graph/mermaid"}),T=A([y,b],([D,Z])=>{let F=D;if(!F)return null;let{expand:Q,...G}=F.describe({detail:"standard"});return G},{name:"graph/describe"});u.add(v,{name:"graph/mermaid"}),u.add(T,{name:"graph/describe"});let w=M(null,{name:"hover/target"});u.add(w,{name:"hover/target"});let x=A([w],([D])=>{let Z=D;if(!Z)return null;let F=o.get(Z.id);return F?F.codeLine:null},{name:"highlight/code-scroll"}),k=A([w],([D])=>{let Z=D;if(!Z)return null;let F=o.get(Z.id);return F?F.visualSelector:null},{name:"highlight/visual"}),S=A([w],([D])=>{let Z=D;return Z?Z.id:null},{name:"highlight/graph"});if(u.add(x,{name:"highlight/code-scroll"}),u.add(k,{name:"highlight/visual"}),u.add(S,{name:"highlight/graph"}),a?.codeScroll){let D=a.codeScroll,Z=pe([x],([F])=>{D(F)});u.add(Z,{name:"highlight/apply-code-scroll"})}if(a?.visual){let D=a.visual,Z=pe([k],([F])=>{D(F)});u.add(Z,{name:"highlight/apply-visual"})}if(a?.graph){let D=a.graph,Z=pe([S],([F])=>{D(F)});u.add(Z,{name:"highlight/apply-graph"})}let R=M(null,{name:"inspect/selected-node"});u.add(R,{name:"inspect/selected-node"});let N=Ct("standard"),_=A([R,y,b],([D,Z,F])=>{let Q=Z,G=D;if(!Q||!G)return null;try{let q=Q.resolve(G),$=Dr(q,N);return{path:G,...$,value:q.cache}}catch{return null}},{name:"inspect/node-detail"}),I=A([y,b],([D,Z])=>{let F=D;return F?F.trace():[]},{name:"inspect/trace-log"});u.add(_,{name:"inspect/node-detail"}),u.add(I,{name:"inspect/trace-log"});let O=M(!1,{name:"meta/debug"});u.add(O,{name:"meta/debug"});let P=A([O,b],([D,Z])=>D?u.describe({format:"mermaid"}):"",{name:"meta/shell-mermaid"});u.add(P,{name:"meta/shell-mermaid"});let B=M("",{name:"layout/code-text"});if(u.add(B,{name:"layout/code-text"}),s){let D=new Map,Z=A([T],([G])=>{let q=G;if(!q)return new Map;let $=new Map;for(let[te]of Object.entries(q.nodes)){let Re=Ft(te,i,s,D),Oe=Rn(Re,1/0,s,i,D),Ce=Oe.lines.reduce((Ge,ie)=>Math.max(Ge,ie.width),0),ye=Oe.lineCount*20;$.set(te,{width:Ce,height:ye})}return $},{name:"layout/graph-labels",equals:(G,q)=>{if(G===q)return!0;let $=G,te=q;if($.size!==te.size)return!1;for(let[Re,Oe]of $){let Ce=te.get(Re);if(!Ce||Ce.width!==Oe.width||Ce.height!==Oe.height)return!1}return!0}}),F=A([B,m],([G,q])=>{let $=G;if(!$)return{lineCount:0,lines:[]};let te=Ft($,i,s,D),Re=q-40;return Rn(te,Math.max(100,Re),s,i,D)},{name:"layout/code-lines"}),Q=A([Z],([G])=>{let q=G;if(q.size===0)return 200;let $=0;for(let{width:te}of q.values())te>$&&($=te);return Math.max(200,Math.round($+80))},{name:"layout/side-width-hint"});u.add(Z,{name:"layout/graph-labels"}),u.add(F,{name:"layout/code-lines"}),u.add(Q,{name:"layout/side-width-hint"})}let j=0;return{graph:u,setMainRatio(D){u.set("pane/main-ratio",xo(D))},setSideSplit(D){u.set("pane/side-split",xo(D))},setFullscreen(D){u.set("pane/fullscreen",D)},setViewportWidth(D){u.set("viewport/width",Math.max(0,D))},setHoverTarget(D){u.set("hover/target",D)},setDemoGraph(D){u.set("demo/graph-ref",D)},bumpGraphTick(){u.set("demo/graph-tick",++j)},selectNode(D){u.set("inspect/selected-node",D)},setMetaDebug(D){u.set("meta/debug",D)},setCodeText(D){u.set("layout/code-text",D)},batch(D){X(D)},destroy(){u.destroy()}}}var Ti={};ke(Ti,{contentModerationGraph:()=>Vy,dataQualityGraph:()=>Ky,issueTrackerGraph:()=>By,observabilityGraph:()=>jy});Me();ee();function Ie(t,e){return ze("domain_template",t,e)}function jy(t,e){let n=new Y(t,e);n.add(e.source,{name:"source"});let r=[{name:"errors",classify:T=>Pu(T,"error")},{name:"traces",classify:T=>Pu(T,"trace")},{name:"metrics",classify:T=>Pu(T,"metric")}],o=e.branches??r,s=o.map(T=>({name:T.name,classify:T.classify})),i=uo("stratify",e.source,s);n.mount("stratify",i);let a=o.map(T=>{try{let w=n.resolve(`stratify::branch/${T.name}`);return A([w],([x])=>x,{initial:null})}catch{return M(null)}}),u=e.correlate??(T=>T),d=A(a,T=>u(T),{meta:Ie("observability",{stage:"correlate"})});n.add(d,{name:"correlate"});let c=e.sloCheck??(()=>({pass:!0})),l=A([d],T=>T[0],{meta:Ie("observability",{stage:"slo_value"})}),p=A([l],T=>c(T[0]),{meta:Ie("observability",{stage:"slo_verified"})});n.add(l,{name:"slo_value"}),n.add(p,{name:"slo_verified"});let f=e.weights??o.map(()=>1),m=a.map(T=>A([T],w=>w[0]!=null?1:0)),h=f.map(T=>M(T));for(let T=0;T<m.length;T++)n.add(m[T],{name:`__signal_${T}`}),n.add(h[T],{name:`__weight_${T}`});let g=vo(m,h);n.add(g,{name:"alerts"});let y=A([g,p],T=>({scored:T[0],slo:T[1]}),{meta:Ie("observability",{stage:"output"})});n.add(y,{name:"output"});let b=M(null,{meta:Ie("observability",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=A([p],T=>{let w=T[0];return w&&w.pass===!1?w:null},{meta:Ie("observability",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),Qt(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??5}),n}function By(t,e){let n=new Y(t,e);n.add(e.source,{name:"source"});let r=0,o=T=>({id:`issue-${++r}`,title:String(T),severity:1,source:"unknown",raw:T}),s=e.extract??o,i=A([e.source],T=>s(T[0]),{meta:Ie("issue_tracker",{stage:"extract"})});n.add(i,{name:"extract"});let a=e.verify??(()=>({valid:!0})),u=A([i],T=>{let w=T[0];return{issue:w,verification:a(w)}},{meta:Ie("issue_tracker",{stage:"verify"})});n.add(u,{name:"verify"});let d=M([],{meta:Ie("issue_tracker",{stage:"known_patterns"})});n.add(d,{name:"known_patterns"});let c=e.detectRegression??(()=>({regression:!1})),l=A([i,d],T=>{let w=T[0],x=T[1];return{issue:w,regression:c(w,x)}},{meta:Ie("issue_tracker",{stage:"regression"})});n.add(l,{name:"regression"});let p=A([i],T=>T[0]?.severity??0),f=A([l],T=>T[0]?.regression?2:0);n.add(p,{name:"__severity_signal"}),n.add(f,{name:"__regression_signal"});let m=M(1),h=M(1.5);n.add(m,{name:"__severity_weight"}),n.add(h,{name:"__regression_weight"});let g=vo([p,f],[m,h]);n.add(g,{name:"priority"});let y=A([u,l,g],T=>({verified:T[0],regression:T[1],priority:T[2]}),{meta:Ie("issue_tracker",{stage:"output"})});n.add(y,{name:"output"});let b=M(null,{meta:Ie("issue_tracker",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=A([u],T=>{let w=T[0];if(w){let x=w.verification;if(x&&x.valid===!1)return w}return null},{meta:Ie("issue_tracker",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),Qt(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??3}),n}function Vy(t,e){let n=new Y(t,e);n.add(e.source,{name:"source"});let r=v=>({label:"review",confidence:.5,original:v}),o=e.classify??r,s=A([e.source],v=>o(v[0]),{meta:Ie("content_moderation",{stage:"classify"})});n.add(s,{name:"classify"});let i=uo("stratify",s,[{name:"safe",classify:v=>v.label==="safe"},{name:"review",classify:v=>v.label==="review"},{name:"block",classify:v=>v.label==="block"}]);n.mount("stratify",i);let a=Ve([],{name:"review_queue",maxSize:e.maxQueueSize});n.add(a.entries,{name:"review_queue"});let u;try{u=n.resolve("stratify::branch/review")}catch{u=M(null),n.add(u,{name:"__review_fallback"})}let d=pe([u],v=>{let T=v[0];T&&a.append(T)});n.add(d,{name:"__review_accumulator"}),n.addDisposer(re(d));let c=M({},{meta:Ie("content_moderation",{stage:"policy",access:"both",description:"Moderation policy rules \u2014 updated via feedback"})});n.add(c,{name:"policy"});let l=e.weights??[.1,1,2],p=A([s],v=>v[0]?.confidence??0),f=A([s],v=>{let T=v[0];return T?T.label==="block"?l[2]:T.label==="review"?l[1]:l[0]:0});n.add(p,{name:"__confidence_signal"}),n.add(f,{name:"__severity_signal"});let m=M(1),h=M(1);n.add(m,{name:"__w_confidence"}),n.add(h,{name:"__w_severity"});let g=vo([p,f],[m,h]);n.add(g,{name:"priority"});let y=A([s,g],v=>({classification:v[0],priority:v[1]}),{meta:Ie("content_moderation",{stage:"output"})});n.add(y,{name:"output"});let b=A([a.entries,c],v=>{let T=v[0];if(T&&T.length>0){let w=T[T.length-1];if(w&&w.falsePositive)return w}return null},{meta:Ie("content_moderation",{stage:"feedback_condition"})});return n.add(b,{name:"feedback_condition"}),Qt(n,"feedback_condition","policy",{maxIterations:e.maxFeedbackIterations??5}),n}function Ky(t,e){let n=new Y(t,e);n.add(e.source,{name:"source"});let r=e.validate??(g=>({valid:!0,errors:[],record:g})),o=A([e.source],g=>g[0]!=null?r(g[0]):void 0,{meta:Ie("data_quality",{stage:"validate"})});n.add(o,{name:"validate"});let s=e.detectAnomaly??(g=>({anomaly:!1,score:0,record:g})),i=A([e.source],g=>g[0]!=null?s(g[0]):void 0,{meta:Ie("data_quality",{stage:"anomaly"})});n.add(i,{name:"anomaly"});let a=M(null,{meta:Ie("data_quality",{stage:"baseline",description:"Rolling baseline for drift detection"})});n.add(a,{name:"baseline"});let u=pe([o],g=>{let y=g[0];y?.valid&&X(()=>{a.emit(y.record)})});n.add(u,{name:"__baseline_updater"}),re(u);let d=e.detectDrift??(()=>({drift:!1})),c=A([e.source,a],g=>d(g[0],g[1]),{meta:Ie("data_quality",{stage:"drift"})});n.add(c,{name:"drift"});let l=e.suggest??(()=>null),p=A([o,i],g=>l({validation:g[0],anomaly:g[1]}),{meta:Ie("data_quality",{stage:"remediate"})});n.add(p,{name:"remediate"});let f=A([o,i,c,p],g=>({validation:g[0],anomaly:g[1],drift:g[2],remediation:g[3]}),{meta:Ie("data_quality",{stage:"output"})});n.add(f,{name:"output"});let m=M([],{meta:Ie("data_quality",{stage:"validation_rules"})});n.add(m,{name:"validation_rules"});let h=A([i],g=>{let y=g[0];return y?.anomaly?y:null},{meta:Ie("data_quality",{stage:"feedback_condition"})});return n.add(h,{name:"feedback_condition"}),Qt(n,"feedback_condition","validation_rules",{maxIterations:e.maxFeedbackIterations??3}),n}function Pu(t,e){if(t==null||typeof t!="object")return!1;let n=t;return n.type===e||n.kind===e}var ki={};ke(ki,{GuardedExecutionGraph:()=>wi,guardedExecution:()=>qy});var wi=class extends Y{enforcer;violations;_target;_defaultActor;constructor(e,n){super(n.name??`${e.name}_guarded`,n.graph),this._target=e,this._defaultActor=n.actor;let r={mode:n.mode??"enforce",name:"enforcer"};n.violationsLimit!=null&&(r.violationsLimit=n.violationsLimit),this.enforcer=Mu(e,n.policies,r),this.violations=this.enforcer.violations,this.mount("enforcer",this.enforcer)}scopedDescribe(e){let n=e?.actor??this._defaultActor,r={...e,...n!=null?{actor:n}:{}};return this._target.describe(r)}get target(){return this._target}};function qy(t,e){return new wi(t,e)}var Ai={};ke(Ai,{DEFAULT_DECAY_RATE:()=>cr,DEFAULT_EXECUTE_PROMPT:()=>Gu,DEFAULT_QUEUE_CONFIGS:()=>xi,DEFAULT_SEVERITY_WEIGHTS:()=>dr,DEFAULT_TRIAGE_PROMPT:()=>Du,DEFAULT_VERIFY_PROMPT:()=>Fu,HarnessGraph:()=>Ci,QUEUE_NAMES:()=>it,actuatorExecutor:()=>Jy,affectedTaskFilter:()=>tb,autoSolidify:()=>Yy,beforeAfterCompare:()=>eb,codeChangeBridge:()=>nb,createIntakeBridge:()=>Qy,defaultErrorClassifier:()=>Ri,defaultLlmExecutor:()=>hf,defaultLlmVerifier:()=>yf,evalIntakeBridge:()=>Xy,evalSource:()=>Zy,evalVerifier:()=>cf,harnessEvalPair:()=>mb,harnessLoop:()=>wb,harnessProfile:()=>xb,harnessTrace:()=>Sb,notifyEffect:()=>rb,priorityScore:()=>vb,refineExecutor:()=>Bu,resolvePromptFn:()=>Ro,strategyKey:()=>lr,strategyModel:()=>Vu});ae();ee();he();function Hy(t,e){return{outcome:"success",detail:`actuator applied ${e.intervention} for ${Uy(e.summary)}`,artifact:t}}function Wy(t,e){let n=t instanceof Error?t.message:String(t);return{outcome:"failure",detail:`actuator threw on ${e.intervention}: ${n}`}}function zy(t){return`actuator skipped ${t.intervention} (shouldApply returned false)`}function Uy(t,e=80){return t.length<=e?t:`${t.slice(0,e-1)}\u2026`}function Jy(t){let e=t.name??"actuator-executor",n=t.toOutput??Hy,r=t.onError??Wy,o=t.skipDetail??zy;return s=>{let i=Xe(s,u=>u!=null,{name:`${e}/gate-in`}),a=Te(i,u=>t.shouldApply&&!t.shouldApply(u)?K(d=>(d.down([[E,{outcome:"failure",detail:o(u)}],[L]]),()=>{}),{name:`${e}/skip`}):K(d=>{let c=new AbortController,l=!1,p=null,f=h=>{l||(l=!0,d.down([[E,h],[L]]),p?.(),p=null)},m;try{let h=t.apply(u,{signal:c.signal});m=U(h,{signal:c.signal})}catch(h){return f(r(h,u)),()=>{c.abort()}}return p=m.subscribe(h=>{for(let g of h){if(l)return;if(g[0]===E){f(n(g[1],u));return}if(g[0]===C){f(r(g[1],u));return}if(g[0]===L){f(r(new Error("actuator inner completed without emitting DATA"),u));return}}}),l&&p&&(p(),p=null),()=>{c.abort(),p?.(),p=null}},{name:`${e}/inner`}),{name:e});return Xe(a,u=>u!=null,{name:`${e}/gate-out`})}}ae();ee();function Yy(t){let e=t.name??"auto-solidify",n=t.extract??(o=>o.execution.artifact??null),r=t.predicate??(()=>!0);return K(o=>{let s=null,i=!1,a=()=>{i||(i=!0,s?.(),s=null)},u=d=>{i||(o.down([[C,d]]),a())};return s=t.verifyResults.subscribe(d=>{if(!i)for(let c of d){if(i)return;if(c[0]!==E){if(c[0]===L){o.down([[L]]),a();return}continue}let l=c[1];if(l==null||!l.verified)continue;let p;try{p=r(l)}catch(m){u(m);return}if(!p)continue;let f;try{f=n(l)}catch(m){u(m);return}if(f!=null){try{t.write(f,l)}catch(m){u(m);return}o.down([[E,f]])}}}),i&&s&&(s(),s=null),()=>{a()}},{name:e})}ee();he();function Qy(t,e,n,r){return pe([t],([o])=>{if(o==null)return;let s=n(o);for(let i of s)e.publish(i)},{name:r?.name??"intake-bridge"})}function Xy(t,e,n){let r=n?.defaultSeverity??"medium";return pe([t],([o])=>{if(o==null)return;let s=Array.isArray(o)?o:[o];for(let i of s)for(let a of i.tasks)if(!(a.valid&&a.judge_scores?.every(u=>u.pass))){if(!a.valid&&(!a.judge_scores||a.judge_scores.length===0)){e.publish({source:"eval",summary:`Task ${a.task_id} invalid (model: ${i.model})`,evidence:`Run ${i.run_id}: task produced invalid output`,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:r});continue}if(a.judge_scores)for(let u of a.judge_scores)u.pass||e.publish({source:"eval",summary:`${a.task_id}: ${u.claim} (model: ${i.model})`,evidence:u.reasoning,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:r})}},{name:n?.name??"eval-intake-bridge"})}function Zy(t,e){return Te(t,()=>U(e()))}function eb(t,e){return A([t,e],([n,r])=>{let o=n,s=r,i=new Map(o.tasks.map(p=>[p.task_id,p])),a=new Map(s.tasks.map(p=>[p.task_id,p])),u=new Set([...i.keys(),...a.keys()]),d=[],c=[],l=[];for(let p of u){let f=i.get(p),m=a.get(p),h=f?.valid??!1,g=m?.valid??!1,y=f?.judge_scores?f.judge_scores.filter(T=>T.pass).length:void 0,b=m?.judge_scores?m.judge_scores.filter(T=>T.pass).length:void 0,v=y!==void 0&&b!==void 0?b-y:void 0;d.push({taskId:p,before:h,after:g,scoreDiff:v}),h&&!g&&c.push(p),!h&&g&&l.push(p)}return{newFailures:c,resolved:l,taskDeltas:d,overallImproved:l.length>c.length}},{name:"eval-delta"})}function tb(t,e){let n=e==null?null:Array.isArray(e)?M(e):e,r=[t];return n&&r.push(n),A(r,o=>{let s=o[0],i=n?new Set(o[1]):null,a=new Set;for(let u of s)for(let d of u.affectsEvalTasks??[])(i==null||i.has(d))&&a.add(d);return[...a].sort()},{name:"affected-task-filter"})}function nb(t,e,n,r){let o=r?.defaultSeverity??"high";function s(a){let u=[];for(let d of a.lintErrors??[])u.push({source:"code-change",summary:`Lint: ${d.rule} in ${d.file}:${d.line}`,evidence:d.message,affectsAreas:[d.file],severity:o});for(let d of a.testFailures??[])u.push({source:"test",summary:`Test failure: ${d.testId}`,evidence:d.message,affectsAreas:[d.file],affectsEvalTasks:[d.testId],severity:o});return u}let i=n??s;return pe([t],([a])=>{if(a!=null)for(let u of i(a))e.publish(u)},{name:r?.name??"code-change-bridge"})}function rb(t,e,n){return pe([t.latest],([r])=>{r!=null&&e(r)},{name:n?.name??"notify-effect"})}var it=["auto-fix","needs-decision","investigation","backlog"],xi={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1}},dr={critical:100,high:70,medium:40,low:10},cr=Math.LN2/(168*3600);function lr(t,e){return`${t}\u2192${e}`}var ob=/\b(parse|json|config|validation|syntax)\b/i,Ri=t=>ob.test(t.detail)?"self-correctable":"structural",Du=`You are a triage classifier for a reactive collaboration harness.
|
|
175
|
+
- Return ONLY valid JSON, no markdown fences or commentary.`;async function kf(t,e,n,r){let{expand:o,...s}=t.describe({actor:r?.actor,detail:"standard"}),i=[{role:"system",content:zy},{role:"user",content:JSON.stringify({graph:s,problem:e})}],a=n.invoke(i,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens,signal:r?.signal}),u=(await To(a)).content.trim();u.startsWith("```")&&(u=u.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let c;try{c=JSON.parse(u)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${u.slice(0,200)}`)}let l=c;if(typeof l.summary!="string")throw new Error("suggestStrategy: missing 'summary' in response");if(typeof l.reasoning!="string")throw new Error("suggestStrategy: missing 'reasoning' in response");if(!Array.isArray(l.operations))throw new Error("suggestStrategy: missing 'operations' array in response");return{summary:l.summary,reasoning:l.reasoning,operations:l.operations}}function Hy(t,e,n,r){let o=Y(e),s=Ft(o,t);return ke(s,i=>{if(i==null)return A(null);let[a,d]=i;return!d||!a||typeof a!="string"||a.trim().length===0?A(null):d.destroyed?A(null):z(u=>{let c=new AbortController,l=!1;return kf(d,a,n,{...r,signal:c.signal}).then(p=>{l||(u.emit(p),u.down([[P]]))}).catch(p=>{l||u.down([[I,p]])}),()=>{l=!0,c.abort()}},{name:"suggestStrategy::call"})})}var xf=new Set(["state","derived","producer","operator","effect"]);function Wy(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"||!xf.has(i.type))&&e.push(`Node "${o}": invalid type "${String(i.type)}" (expected: ${[...xf].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 d=`${a.from}->${a.to}`;o.has(d)&&e.push(`Edge [${s}]: duplicate edge ${d}`),o.add(d)}}return{valid:e.length===0,errors:e}}var Si={};Se(Si,{AuditTrailGraph:()=>xi,PolicyEnforcerGraph:()=>Ri,auditTrail:()=>Jy,complianceSnapshot:()=>Yy,policyEnforcer:()=>jd,reactiveExplainPath:()=>Bd});Re();Vt();ae();Me();ne();Bo();function Sf(t,e){return We("audit",t,e)}var Uy=new Set(["data","error","complete","teardown"]),xi=class extends Q{entries;count;_log;_target;constructor(e,n){super(n.name??`${e.name}_audit`,n.graph),this._target=e,this._log=Ke([],{name:"entries",...n.maxSize!=null?{maxSize:n.maxSize}:{}}),this.entries=this._log.entries,this.add(this.entries,{name:"entries"}),this.count=C([this.entries],([d])=>d.length,{name:"count",describeKind:"derived",meta:Sf("count")}),this.add(this.count,{name:"count"}),this.addDisposer(te(this.count));let r=n.includeTypes!=null?new Set(n.includeTypes):Uy,o=n.filter,s=0,i=e.observe({timeline:!0,structured:!0}),a=i.onEvent(d=>{if(d.type==="derived")return;let u=d.type;if(!r.has(u))return;let c=d.path??"",l={seq:s++,timestamp_ns:d.timestamp_ns??V(),wall_clock_ns:se(),path:c,type:u},f=(c?$d(e,c):void 0)?.lastMutation;f!=null&&(l.actor=f.actor),u==="data"&&(l.value=d.data),u==="error"&&(l.error=d.data);let m=c?Xy(e,c):void 0;m!=null&&(l.annotation=m),!(o!=null&&!o(l))&&this._log.append(l)});this.addDisposer(()=>{a(),i.dispose()}),this.addDisposer(()=>this._log.disposeAllViews())}all(){return this.entries.cache??[]}byNode(e){return this.all().filter(n=>n.path===e)}byActor(e){return this.all().filter(n=>n.actor?.id===e)}byActorType(e){return this.all().filter(n=>n.actor?.type===e)}byTimeRange(e,n){return this.all().filter(r=>!(r.timestamp_ns<e||n!=null&&r.timestamp_ns>=n))}get target(){return this._target}};function Jy(t,e={}){return new xi(t,e)}var Ri=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=Qy(n)?n:A(n,{name:"policies"});this.policies=o,this.add(this.policies,{name:"policies"}),this.violations=new Nn("violations",{retainedLimit:r.violationsLimit??1e3}),this.mount("violations",this.violations),this.violationCount=C([this.violations.events],([u])=>u.length,{name:"violationCount",describeKind:"derived",meta:Sf("policy_violation_count")}),this.add(this.violationCount,{name:"violationCount"}),this.addDisposer(te(this.violationCount));let i=o.cache??[];this._currentGuard=Lr(i);let a=o.subscribe(u=>{for(let c of u)c[0]===M&&(i=c[1]??[],this._currentGuard=Lr(i))});this.addDisposer(a);let d=r.paths!=null?[...r.paths]:Rf(e);if(this._mode==="enforce"){let u=new Map,c=l=>{if(u.has(l))return;let p=$d(e,l);if(!(p instanceof Oe))return;let f=(m,h)=>{let g=this._currentGuard(m,h);return g||this._publishViolation(m,h,l,"blocked"),g};u.set(l,p._pushGuard(f))};for(let l of d)c(l);if(r.paths==null){let l=Pt(e,(p,f,m)=>{if(p.kind==="added")if(p.nodeKind==="node")c(`${m}${p.name}`);else{let h=f._mounts.get(p.name);if(!(h instanceof Q))return;let g=`${m}${p.name}::`,y=Rf(h);for(let b of y)c(b===""?`${m}${p.name}`:`${g}${b}`)}else if(p.kind==="removed")if(p.nodeKind==="node"){let h=`${m}${p.name}`,g=u.get(h);g!=null&&(g(),u.delete(h))}else{let h=`${m}${p.name}`,g=`${h}::`;for(let[y,b]of u)(y===h||y.startsWith(g))&&(b(),u.delete(y))}});this.addDisposer(l)}else{let l=e.topology.subscribe(p=>{for(let f of p){if(f[0]!==M)continue;let m=f[1];if(m.kind!=="removed"||m.nodeKind!=="node")continue;let h=u.get(m.name);h!=null&&(h(),u.delete(m.name))}});this.addDisposer(l)}this.addDisposer(()=>{for(let l of u.values())l();u.clear()})}else{let u=e.observe({timeline:!0,structured:!0}),c=u.onEvent(l=>{if(l.type!=="data"&&l.type!=="error")return;let p=l.path??"";if(!p||r.paths!=null&&!r.paths.includes(p))return;let f=l.actor??$d(e,p)?.lastMutation?.actor;if(f==null)return;let m="write";this._currentGuard(f,m)||this._publishViolation(f,m,p,"observed")});this.addDisposer(()=>{c(),u.dispose()})}}_publishViolation(e,n,r,o){this.violations.publish({timestamp_ns:V(),wall_clock_ns:se(),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 jd(t,e,n={}){return new Ri(t,e,n)}function Bd(t,e,n,r){return t.explain(e,n,{reactive:!0,...r})}function Yy(t,e={}){let n={format_version:1,timestamp_ns:V(),wall_clock_ns:se(),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=Zy(n);return{...n,fingerprint:r}}function Qy(t){return typeof t=="object"&&t!==null&&"subscribe"in t}function $d(t,e){try{return t.node(e)}catch{return}}function Xy(t,e){try{return t.annotation(e)}catch{return}}function Rf(t){let e=t.describe({detail:"minimal"});return Object.keys(e.nodes)}function Zy(t){return Kt(JSON.stringify(eb(t)))}function eb(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(([d,u])=>[n(d),n(u)])};if(s instanceof Set)return{__set:[...s].map(n)};if(ArrayBuffer.isView(s)){let a=s,d=new Array(a.length);for(let u=0;u<a.length;u++)d[u]=a[u]??0;return{__typed_array:{ctor:s.constructor.name,data:d}}}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 Ei={};Se(Ei,{demoShell:()=>db});Ae();it();ne();Re();Me();ne();function tb(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 Nf=new Set(["\uFF0C","\uFF0E","\uFF01","\uFF1A","\uFF1B","\uFF1F","\u3001","\u3002","\u30FB","\uFF09","\u3015","\u3009","\u300B","\u300D","\u300F","\u3011"]),nb=new Set([".",",","!","?",":",";",")","]","}","%",'"',"\u201D","\u2019","\xBB","\u203A","\u2026"]);function rb(t){return t.replace(/[\t\n\r\f ]+/g," ").replace(/^ | $/g,"")}function ob(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=[],d=[],u="",c=null;for(let l of o){let p;l===" "?p="space":l==="\u200B"?p="zero-width-break":l==="\xAD"?p="soft-hyphen":l===`
|
|
176
|
+
`?p="hard-break":p="text",c!==null&&p===c?u+=l:(c!==null&&(i.push(u),a.push(c==="text"&&s),d.push(c)),u=l,c=p)}c!==null&&(i.push(u),a.push(c==="text"&&s),d.push(c)),n.push({texts:i,isWordLike:a,kinds:d})}return n}function Bt(t,e,n,r,o){let s=rb(t);if(s.length===0)return[];let i=ob(s),a=new Intl.Segmenter(void 0,{granularity:"grapheme"}),d=[],u=[],c=[];for(let y of i)for(let b=0;b<y.texts.length;b++)d.push(y.texts[b]),u.push(y.kinds[b]),c.push(y.isWordLike[b]);let l=[],p=[],f=[];for(let y=0;y<d.length;y++){let b=d[y],v=u[y],T=c[y];if(v==="text"&&!T&&l.length>0&&p[p.length-1]==="text"&&b.length===1&&(nb.has(b)||Nf.has(b))){l[l.length-1]+=b;continue}if(b==="-"&&l.length>0&&p[p.length-1]==="text"&&f[f.length-1]){l[l.length-1]+=b;continue}l.push(b),p.push(v),f.push(T)}let m=r.get(e);m||(m=new Map,r.set(e,m));function h(y){let b=m.get(y);if(b===void 0){o&&(o.misses+=1);let v=n.measureSegment(y,e).width;b=Number.isFinite(v)&&v>=0?v:0,m.set(y,b)}else o&&(o.hits+=1);return b}let g=[];for(let y=0;y<l.length;y++){let b=l[y],v=p[y];if(v!=="text"){g.push({text:b,width:v==="space"?h(" ")*b.length:0,kind:v,graphemeWidths:null});continue}if(tb(b)){let x="";for(let k of a.segment(b)){let S=k.segment;if(x.length>0&&Nf.has(S)){x+=S;continue}if(x.length>0){let R=h(x);g.push({text:x,width:R,kind:"text",graphemeWidths:null})}x=S}if(x.length>0){let k=h(x);g.push({text:x,width:k,kind:"text",graphemeWidths:null})}continue}let T=h(b),w=null;if(f[y]&&b.length>1){let x=[];for(let k of a.segment(b))x.push(h(k.segment));x.length>1&&(w=x)}g.push({text:b,width:T,kind:"text",graphemeWidths:w})}return g}function _n(t,e,n,r,o){if(t.length===0)return{lines:[],lineCount:0};let s=[],i=0,a=!1,d=0,u=0,c=0,l=0,p=-1,f=0,m=o.get(r);m||(m=new Map,o.set(r,m));let h=m.get("-");h===void 0&&(h=n.measureSegment("-",r).width,m.set("-",h));function g(w=c,x=l,k=i){let S="";for(let R=d;R<w;R++){let E=t[R];if(!(E.kind==="soft-hyphen"||E.kind==="hard-break"))if(R===d&&u>0&&E.graphemeWidths){let O=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(E.text)].map(N=>N.segment);S+=O.slice(u).join("")}else S+=E.text}if(x>0&&w<t.length){let R=t[w],_=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(R.text)].map(N=>N.segment),O=d===w?u:0;S+=_.slice(O,x).join("")}w>0&&t[w-1]?.kind==="soft-hyphen"&&!(d===w&&u>0)&&(S+="-"),s.push({text:S,width:k,startSegment:d,startGrapheme:u,endSegment:w,endGrapheme:x}),i=0,a=!1,p=-1,f=0}function y(w){return w==="space"||w==="zero-width-break"||w==="soft-hyphen"}function b(w,x,k){a=!0,d=w,u=x,c=w+1,l=0,i=k}function v(w,x,k){a=!0,d=w,u=x,c=w,l=x+1,i=k}for(let w=0;w<t.length;w++){let x=t[w];if(x.kind==="hard-break"){a?g():s.push({text:"",width:0,startSegment:w,startGrapheme:0,endSegment:w,endGrapheme:0}),d=w+1,u=0;continue}let k=x.width;if(!a){k>e&&x.graphemeWidths?T(w,0,x.graphemeWidths):b(w,0,k),y(x.kind)&&(p=w+1,f=x.kind==="space"?i-k:i);continue}let S=i+k;if(S>e+.005){if(y(x.kind)){i+=k,c=w+1,l=0,g(w+1,0,x.kind==="space"?i-k:i);continue}if(p>=0){g(p,0,f),w--;continue}if(k>e&&x.graphemeWidths){g(),T(w,0,x.graphemeWidths);continue}g(),w--;continue}i=S,c=w+1,l=0,y(x.kind)&&(p=w+1,f=x.kind==="space"?i-k:i)}return a&&g(),{lines:s,lineCount:s.length};function T(w,x,k){for(let S=x;S<k.length;S++){let R=k[S];if(!a){v(w,S,R);continue}i+R>e+.005?(g(),v(w,S,R)):(i+=R,c=w,l=S+1)}a&&c===w&&l===k.length&&(c=w+1,l=0)}}function Vd(t){return t==="space"||t==="zero-width-break"||t==="soft-hyphen"}var Kd=null;function sb(){return Kd===null&&(Kd=new Intl.Segmenter(void 0,{granularity:"grapheme"})),Kd}function Ef(t,e,n){if(e===0&&n<0)return t.text;let r=[...sb().segment(t.text)].map(s=>s.segment),o=n<0?r.length:n;return r.slice(e,o).join("")}function nn(t,e,n,r,o,s){let i="";for(let a=e;a<r;a++){let d=t[a];d.kind==="soft-hyphen"||d.kind==="hard-break"||(a===e&&n>0?i+=Ef(d,n,-1):i+=d.text)}if(o>0&&r<t.length){let a=t[r];i+=Ef(a,e===r?n:0,o)}return s&&(i+="-"),i}function ib(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 qd(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=ib(r),a=o,d=o===e.segmentIndex?s:0,u=0,c=a,l=0,p=!1,f=-1,m=0,h=0,g=!1,y=(w,x,k,S)=>{f=w,m=x,h=k,g=S==="soft-hyphen"},b=(w,x,k)=>{for(let S=x;S<k.length;S++){let R=k[S];if(!p){u=R,c=w,l=S+1,p=!0;continue}if(u+R>n+.005)return!0;u+=R,c=w,l=S+1}return c===w&&l===k.length&&(c=w+1,l=0),!1};if(d>0&&a<t.length){let w=t[a];if(w.graphemeWidths){if(b(a,d,w.graphemeWidths))return{text:nn(t,a,d,c,l,!1),width:u,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}};o=c}}for(;o<t.length;){let w=t[o];if(w.kind==="hard-break"){if(p){let S=c>0&&t[c-1]?.kind==="soft-hyphen";return{text:nn(t,a,d,c,l,S),width:u+(S?i:0),start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}}return{text:"",width:0,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:o+1,graphemeIndex:0}}}let x=w.width;if(!p){if(x>n&&w.graphemeWidths){if(b(o,0,w.graphemeWidths))return{text:nn(t,a,d,c,l,!1),width:u,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}};o=c;continue}u=x,c=o+1,l=0,p=!0,Vd(w.kind)&&y(o+1,0,w.kind==="space"?u-x:u,w.kind),o+=1;continue}let k=u+x;if(k>n+.005){if(Vd(w.kind)){c=o+1,l=0;let R=w.kind==="soft-hyphen",E=w.kind==="space"?u:u+(R?i:0);return{text:nn(t,a,d,c,l,R),width:E,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}}return f>=0?{text:nn(t,a,d,f,m,g),width:h+(g?i:0),start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:f,graphemeIndex:m}}:x>n&&w.graphemeWidths?{text:nn(t,a,d,c,l,!1),width:u,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}:{text:nn(t,a,d,c,l,!1),width:u,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}}u=k,c=o+1,l=0,Vd(w.kind)&&y(o+1,0,w.kind==="space"?u-x:u,w.kind),o+=1}if(!p)return null;let v=c>0&&t[c-1]?.kind==="soft-hyphen";return{text:nn(t,a,d,c,l,v),width:u+(v?i:0),start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}}function zd(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 d=r[a];if(s.right<=d.left||s.left>=d.right){i.push(d);continue}s.left>d.left&&i.push({left:d.left,right:s.left}),s.right<d.right&&i.push({left:s.right,right:d.right})}r=i}return n>0?r.filter(o=>o.right-o.left>=n):r}function Ni(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,d=0;for(let u=i.startSegment;u<e.length;u++){let c=e[u];if(c.kind==="soft-hyphen"||c.kind==="hard-break"){if(u>=i.endSegment&&i.endGrapheme===0)break;continue}let l=[...o.segment(c.text)].map(m=>m.segment);if(l.length===0)continue;let p=u===i.startSegment?i.startGrapheme:0,f;if(u<i.endSegment)f=l.length;else if(u===i.endSegment&&i.endGrapheme>0)f=i.endGrapheme;else break;for(let m=p;m<f;m++){let h=c.graphemeWidths?c.graphemeWidths[m]:c.width/l.length;r.push({x:d,y:a,width:h,height:n,line:s}),d+=h}}}return r}function ab(t){let{adapter:e,name:n="reactive-layout"}=t,r=new Q(n),o=new Map,s=A(t.text??"",{name:"text"}),i=A(t.font??"16px sans-serif",{name:"font"}),a=A(t.lineHeight??20,{name:"line-height"}),d=A(Math.max(0,t.maxWidth??800),{name:"max-width"});function u(m,h){if(m===null||h===null)return m===h;if(m.length!==h.length)return!1;for(let g=0;g<m.length;g++)if(m[g]!==h[g])return!1;return!0}let c=U([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(),x={hits:0,misses:0},k=Bt(b,T,e,o,x),S=V()-w,R=x.hits+x.misses,E=R===0?1:x.hits/R,_=c.meta;_&&(vt(_["cache-hit-rate"],E),vt(_["segment-count"],k.length),vt(_["layout-time-ns"],S)),h.emit(k);let O=()=>{o.clear(),e.clearCache?.()};return{deactivate:O,invalidate:O}},{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||!u(v.graphemeWidths??null,T.graphemeWidths??null))return!1}return!0}}),l=C([c,d,i],([m,h,g])=>_n(m,h,e,g,o),{name:"line-breaks",equals:(m,h)=>{let g=m,y=h;if(g==null||y==null)return g===y;if(g.lineCount!==y.lineCount)return!1;for(let b=0;b<g.lines.length;b++){let v=g.lines[b],T=y.lines[b];if(v.text!==T.text||v.width!==T.width||v.startSegment!==T.startSegment||v.startGrapheme!==T.startGrapheme||v.endSegment!==T.endSegment||v.endGrapheme!==T.endGrapheme)return!1}return!0}}),p=C([l,a],([m,h])=>m.lineCount*h,{name:"height"}),f=C([l,c,a],([m,h,g])=>Ni(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(d,{name:"max-width"}),r.add(c,{name:"segments"}),r.add(l,{name:"line-breaks"}),r.add(p,{name:"height"}),r.add(f,{name:"char-positions"}),{graph:r,setText:m=>r.set("text",m),setFont:m=>r.set("font",m),setLineHeight:m=>r.set("line-height",m),setMaxWidth:m=>r.set("max-width",Math.max(0,m)),segments:c,lineBreaks:l,height:p,charPositions:f}}function Oo(t){return Math.max(0,Math.min(1,t))}function db(t){let e=Oo(t?.mainRatio??.65),n=Oo(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,d=new Q("demo-shell"),u=A(e,{name:"pane/main-ratio"}),c=A(n,{name:"pane/side-split"}),l=A(null,{name:"pane/fullscreen"}),p=A(r,{name:"viewport/width"});d.add(u,{name:"pane/main-ratio"}),d.add(c,{name:"pane/side-split"}),d.add(l,{name:"pane/fullscreen"}),d.add(p,{name:"viewport/width"});let f=C([u,p,l],([D,K,F])=>{let H=D,G=K,B=F;return B==="main"?G:B==="graph"||B==="code"?0:Math.round(G*H)},{name:"pane/main-width"}),m=C([f,p,l],([D,K,F])=>{let H=F,G=K;return H==="main"?0:H==="graph"||H==="code"?G:G-D},{name:"pane/side-width"}),h=C([c,l],([D,K])=>{let F=K;return F==="graph"?1:F==="code"||F==="main"?0:Oo(D)},{name:"pane/graph-height-ratio"}),g=C([h,l],([D,K])=>{let F=K;return F==="code"?1:F==="graph"||F==="main"?0:1-D},{name:"pane/code-height-ratio"});d.add(f,{name:"pane/main-width"}),d.add(m,{name:"pane/side-width"}),d.add(h,{name:"pane/graph-height-ratio"}),d.add(g,{name:"pane/code-height-ratio"});let y=A(null,{name:"demo/graph-ref"}),b=A(0,{name:"demo/graph-tick"});d.add(y,{name:"demo/graph-ref"}),d.add(b,{name:"demo/graph-tick"});let v=C([y,b],([D,K])=>{let F=D;return F?F.describe({format:"mermaid"}):""},{name:"graph/mermaid"}),T=C([y,b],([D,K])=>{let F=D;if(!F)return null;let{expand:H,...G}=F.describe({detail:"standard"});return G},{name:"graph/describe"});d.add(v,{name:"graph/mermaid"}),d.add(T,{name:"graph/describe"});let w=A(null,{name:"hover/target"});d.add(w,{name:"hover/target"});let x=C([w],([D])=>{let K=D;if(!K)return null;let F=o.get(K.id);return F?F.codeLine:null},{name:"highlight/code-scroll"}),k=C([w],([D])=>{let K=D;if(!K)return null;let F=o.get(K.id);return F?F.visualSelector:null},{name:"highlight/visual"}),S=C([w],([D])=>{let K=D;return K?K.id:null},{name:"highlight/graph"});if(d.add(x,{name:"highlight/code-scroll"}),d.add(k,{name:"highlight/visual"}),d.add(S,{name:"highlight/graph"}),a?.codeScroll){let D=a.codeScroll,K=ge([x],([F])=>{D(F)});d.add(K,{name:"highlight/apply-code-scroll"})}if(a?.visual){let D=a.visual,K=ge([k],([F])=>{D(F)});d.add(K,{name:"highlight/apply-visual"})}if(a?.graph){let D=a.graph,K=ge([S],([F])=>{D(F)});d.add(K,{name:"highlight/apply-graph"})}let R=A(null,{name:"inspect/selected-node"});d.add(R,{name:"inspect/selected-node"});let E=Lt("standard"),_=C([R,y,b],([D,K,F])=>{let H=K,G=D;if(!H||!G)return null;try{let B=H.resolve(G),re=jr(B,E);return{path:G,...re,value:B.cache}}catch{return null}},{name:"inspect/node-detail"}),O=C([y,b],([D,K])=>{let F=D;return F?F.trace():[]},{name:"inspect/trace-log"});d.add(_,{name:"inspect/node-detail"}),d.add(O,{name:"inspect/trace-log"});let N=A(!1,{name:"meta/debug"});d.add(N,{name:"meta/debug"});let L=C([N,b],([D,K])=>D?d.describe({format:"mermaid"}):"",{name:"meta/shell-mermaid"});d.add(L,{name:"meta/shell-mermaid"});let j=A("",{name:"layout/code-text"});if(d.add(j,{name:"layout/code-text"}),s){let D=new Map,K=C([T],([G])=>{let B=G;if(!B)return new Map;let re=new Map;for(let[pe]of Object.entries(B.nodes)){let ee=Bt(pe,i,s,D),ue=_n(ee,1/0,s,i,D),Ce=ue.lines.reduce((Be,J)=>Math.max(Be,J.width),0),Ye=ue.lineCount*20;re.set(pe,{width:Ce,height:Ye})}return re},{name:"layout/graph-labels",equals:(G,B)=>{if(G===B)return!0;let re=G,pe=B;if(re.size!==pe.size)return!1;for(let[ee,ue]of re){let Ce=pe.get(ee);if(!Ce||Ce.width!==ue.width||Ce.height!==ue.height)return!1}return!0}}),F=C([j,m],([G,B])=>{let re=G;if(!re)return{lineCount:0,lines:[]};let pe=Bt(re,i,s,D),ee=B-40;return _n(pe,Math.max(100,ee),s,i,D)},{name:"layout/code-lines"}),H=C([K],([G])=>{let B=G;if(B.size===0)return 200;let re=0;for(let{width:pe}of B.values())pe>re&&(re=pe);return Math.max(200,Math.round(re+80))},{name:"layout/side-width-hint"});d.add(K,{name:"layout/graph-labels"}),d.add(F,{name:"layout/code-lines"}),d.add(H,{name:"layout/side-width-hint"})}let $=0;return{graph:d,setMainRatio(D){d.set("pane/main-ratio",Oo(D))},setSideSplit(D){d.set("pane/side-split",Oo(D))},setFullscreen(D){d.set("pane/fullscreen",D)},setViewportWidth(D){d.set("viewport/width",Math.max(0,D))},setHoverTarget(D){d.set("hover/target",D)},setDemoGraph(D){d.set("demo/graph-ref",D)},bumpGraphTick(){d.set("demo/graph-tick",++$)},selectNode(D){d.set("inspect/selected-node",D)},setMetaDebug(D){d.set("meta/debug",D)},setCodeText(D){d.set("layout/code-text",D)},batch(D){Z(D)},destroy(){d.destroy()}}}var _i={};Se(_i,{contentModerationGraph:()=>lb,dataQualityGraph:()=>pb,issueTrackerGraph:()=>cb,observabilityGraph:()=>ub});Ae();ne();function Pe(t,e){return We("domain_template",t,e)}function ub(t,e){let n=new Q(t,e);n.add(e.source,{name:"source"});let r=[{name:"errors",classify:T=>Hd(T,"error")},{name:"traces",classify:T=>Hd(T,"trace")},{name:"metrics",classify:T=>Hd(T,"metric")}],o=e.branches??r,s=o.map(T=>({name:T.name,classify:T.classify})),i=ho("stratify",e.source,s);n.mount("stratify",i);let a=o.map(T=>{try{let w=n.resolve(`stratify::branch/${T.name}`);return C([w],([x])=>x,{initial:null})}catch{return A(null)}}),d=e.correlate??(T=>T),u=C(a,T=>d(T),{meta:Pe("observability",{stage:"correlate"})});n.add(u,{name:"correlate"});let c=e.sloCheck??(()=>({pass:!0})),l=C([u],T=>T[0],{meta:Pe("observability",{stage:"slo_value"})}),p=C([l],T=>c(T[0]),{meta:Pe("observability",{stage:"slo_verified"})});n.add(l,{name:"slo_value"}),n.add(p,{name:"slo_verified"});let f=e.weights??o.map(()=>1),m=a.map(T=>C([T],w=>w[0]!=null?1:0)),h=f.map(T=>A(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=C([g,p],T=>({scored:T[0],slo:T[1]}),{meta:Pe("observability",{stage:"output"})});n.add(y,{name:"output"});let b=A(null,{meta:Pe("observability",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=C([p],T=>{let w=T[0];return w&&w.pass===!1?w:null},{meta:Pe("observability",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),tn(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??5}),n}function cb(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=C([e.source],T=>s(T[0]),{meta:Pe("issue_tracker",{stage:"extract"})});n.add(i,{name:"extract"});let a=e.verify??(()=>({valid:!0})),d=C([i],T=>{let w=T[0];return{issue:w,verification:a(w)}},{meta:Pe("issue_tracker",{stage:"verify"})});n.add(d,{name:"verify"});let u=A([],{meta:Pe("issue_tracker",{stage:"known_patterns"})});n.add(u,{name:"known_patterns"});let c=e.detectRegression??(()=>({regression:!1})),l=C([i,u],T=>{let w=T[0],x=T[1];return{issue:w,regression:c(w,x)}},{meta:Pe("issue_tracker",{stage:"regression"})});n.add(l,{name:"regression"});let p=C([i],T=>T[0]?.severity??0),f=C([l],T=>T[0]?.regression?2:0);n.add(p,{name:"__severity_signal"}),n.add(f,{name:"__regression_signal"});let m=A(1),h=A(1.5);n.add(m,{name:"__severity_weight"}),n.add(h,{name:"__regression_weight"});let g=No([p,f],[m,h]);n.add(g,{name:"priority"});let y=C([d,l,g],T=>({verified:T[0],regression:T[1],priority:T[2]}),{meta:Pe("issue_tracker",{stage:"output"})});n.add(y,{name:"output"});let b=A(null,{meta:Pe("issue_tracker",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=C([d],T=>{let w=T[0];if(w){let x=w.verification;if(x&&x.valid===!1)return w}return null},{meta:Pe("issue_tracker",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),tn(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??3}),n}function lb(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=C([e.source],v=>o(v[0]),{meta:Pe("content_moderation",{stage:"classify"})});n.add(s,{name:"classify"});let i=ho("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=Ke([],{name:"review_queue",maxSize:e.maxQueueSize});n.add(a.entries,{name:"review_queue"});let d;try{d=n.resolve("stratify::branch/review")}catch{d=A(null),n.add(d,{name:"__review_fallback"})}let u=ge([d],v=>{let T=v[0];T&&a.append(T)});n.add(u,{name:"__review_accumulator"}),n.addDisposer(te(u));let c=A({},{meta:Pe("content_moderation",{stage:"policy",access:"both",description:"Moderation policy rules \u2014 updated via feedback"})});n.add(c,{name:"policy"});let l=e.weights??[.1,1,2],p=C([s],v=>v[0]?.confidence??0),f=C([s],v=>{let T=v[0];return T?T.label==="block"?l[2]:T.label==="review"?l[1]:l[0]:0});n.add(p,{name:"__confidence_signal"}),n.add(f,{name:"__severity_signal"});let m=A(1),h=A(1);n.add(m,{name:"__w_confidence"}),n.add(h,{name:"__w_severity"});let g=No([p,f],[m,h]);n.add(g,{name:"priority"});let y=C([s,g],v=>({classification:v[0],priority:v[1]}),{meta:Pe("content_moderation",{stage:"output"})});n.add(y,{name:"output"});let b=C([a.entries,c],v=>{let T=v[0];if(T&&T.length>0){let w=T[T.length-1];if(w&&w.falsePositive)return w}return null},{meta:Pe("content_moderation",{stage:"feedback_condition"})});return n.add(b,{name:"feedback_condition"}),tn(n,"feedback_condition","policy",{maxIterations:e.maxFeedbackIterations??5}),n}function pb(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=C([e.source],g=>g[0]!=null?r(g[0]):void 0,{meta:Pe("data_quality",{stage:"validate"})});n.add(o,{name:"validate"});let s=e.detectAnomaly??(g=>({anomaly:!1,score:0,record:g})),i=C([e.source],g=>g[0]!=null?s(g[0]):void 0,{meta:Pe("data_quality",{stage:"anomaly"})});n.add(i,{name:"anomaly"});let a=A(null,{meta:Pe("data_quality",{stage:"baseline",description:"Rolling baseline for drift detection"})});n.add(a,{name:"baseline"});let d=ge([o],g=>{let y=g[0];y?.valid&&Z(()=>{a.emit(y.record)})});n.add(d,{name:"__baseline_updater"}),te(d);let u=e.detectDrift??(()=>({drift:!1})),c=C([e.source,a],g=>u(g[0],g[1]),{meta:Pe("data_quality",{stage:"drift"})});n.add(c,{name:"drift"});let l=e.suggest??(()=>null),p=C([o,i],g=>l({validation:g[0],anomaly:g[1]}),{meta:Pe("data_quality",{stage:"remediate"})});n.add(p,{name:"remediate"});let f=C([o,i,c,p],g=>({validation:g[0],anomaly:g[1],drift:g[2],remediation:g[3]}),{meta:Pe("data_quality",{stage:"output"})});n.add(f,{name:"output"});let m=A([],{meta:Pe("data_quality",{stage:"validation_rules"})});n.add(m,{name:"validation_rules"});let h=C([i],g=>{let y=g[0];return y?.anomaly?y:null},{meta:Pe("data_quality",{stage:"feedback_condition"})});return n.add(h,{name:"feedback_condition"}),tn(n,"feedback_condition","validation_rules",{maxIterations:e.maxFeedbackIterations??3}),n}function Hd(t,e){if(t==null||typeof t!="object")return!1;let n=t;return n.type===e||n.kind===e}var Oi={};Se(Oi,{GuardedExecutionGraph:()=>Mi,guardedExecution:()=>fb});var Mi=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=jd(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 fb(t,e){return new Mi(t,e)}var ji={};Se(ji,{DEFAULT_DECAY_RATE:()=>yr,DEFAULT_EXECUTE_PROMPT:()=>Ud,DEFAULT_QUEUE_CONFIGS:()=>Ai,DEFAULT_SEVERITY_WEIGHTS:()=>hr,DEFAULT_TRIAGE_PROMPT:()=>Wd,DEFAULT_VERIFY_PROMPT:()=>Jd,HarnessGraph:()=>$i,QUEUE_NAMES:()=>ct,actuatorExecutor:()=>_f,affectedTaskFilter:()=>Rb,autoSolidify:()=>vb,beforeAfterCompare:()=>xb,codeChangeBridge:()=>Sb,createIntakeBridge:()=>Tb,defaultErrorClassifier:()=>Ci,defaultLlmExecutor:()=>Df,defaultLlmVerifier:()=>Gf,dispatchActuator:()=>bb,evalIntakeBridge:()=>wb,evalSource:()=>kb,evalVerifier:()=>Of,harnessEvalPair:()=>Gb,harnessLoop:()=>qb,harnessProfile:()=>Hb,harnessTrace:()=>Ub,notifyEffect:()=>Nb,priorityScore:()=>Vb,refineExecutor:()=>Xd,resolvePromptFn:()=>Ao,strategyKey:()=>br,strategyModel:()=>Zd});ae();ne();ve();function mb(t,e){return{outcome:"success",detail:`actuator applied ${e.intervention} for ${yb(e.summary)}`,artifact:t}}function gb(t,e){let n=t instanceof Error?t.message:String(t);return{outcome:"failure",detail:`actuator threw on ${e.intervention}: ${n}`}}function hb(t){return`actuator skipped ${t.intervention} (shouldApply returned false)`}function yb(t,e=80){return t.length<=e?t:`${t.slice(0,e-1)}\u2026`}function _f(t){let e=t.name??"actuator-executor",n=t.toOutput??mb,r=t.onError??gb,o=t.skipDetail??hb;return s=>{let i=rt(s,d=>d!=null,{name:`${e}/gate-in`}),a=ke(i,d=>t.shouldApply&&!t.shouldApply(d)?z(u=>(u.down([[M,{outcome:"failure",detail:o(d)}],[P]]),()=>{}),{name:`${e}/skip`}):z(u=>{let c=new AbortController,l=!1,p=null,f=h=>{l||(l=!0,u.down([[M,h],[P]]),p?.(),p=null)},m;try{let h=t.apply(d,{signal:c.signal});m=Y(h,{signal:c.signal})}catch(h){return f(r(h,d)),()=>{c.abort()}}return p=m.subscribe(h=>{for(let g of h){if(l)return;if(g[0]===M){f(n(g[1],d));return}if(g[0]===I){f(r(g[1],d));return}if(g[0]===P){f(r(new Error("actuator inner completed without emitting DATA"),d));return}}}),l&&p&&(p(),p=null),()=>{c.abort(),p?.(),p=null}},{name:`${e}/inner`}),{name:e});return rt(a,d=>d!=null,{name:`${e}/gate-out`})}}function bb(t){let e=t.name??"dispatch-actuator",n=t.default??null,r=n!=null;return _f({apply:(o,s)=>{let i=Object.hasOwn(t.routes,o.intervention)?t.routes[o.intervention]:n;if(!i)throw new Error(`dispatchActuator: no route for intervention '${o.intervention}'`);return i(o,s)},shouldApply:o=>Object.hasOwn(t.routes,o.intervention)||r,skipDetail:o=>`no route for intervention '${o.intervention}'`,name:e})}ae();ne();function vb(t){let e=t.name??"auto-solidify",n=t.extract??(o=>o.execution.artifact??null),r=t.predicate??(()=>!0);return z(o=>{let s=null,i=!1,a=()=>{i||(i=!0,s?.(),s=null)},d=u=>{i||(o.down([[I,u]]),a())};return s=t.verifyResults.subscribe(u=>{if(!i)for(let c of u){if(i)return;if(c[0]!==M){if(c[0]===P){o.down([[P]]),a();return}continue}let l=c[1];if(l==null||!l.verified)continue;let p;try{p=r(l)}catch(m){d(m);return}if(!p)continue;let f;try{f=n(l)}catch(m){d(m);return}if(f!=null){try{t.write(f,l)}catch(m){d(m);return}o.down([[M,f]])}}}),i&&s&&(s(),s=null),()=>{a()}},{name:e})}ne();ve();function Tb(t,e,n,r){return ge([t],([o])=>{if(o==null)return;let s=n(o);for(let i of s)e.publish(i)},{name:r?.name??"intake-bridge"})}function wb(t,e,n){let r=n?.defaultSeverity??"medium";return ge([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(d=>d.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 d of a.judge_scores)d.pass||e.publish({source:"eval",summary:`${a.task_id}: ${d.claim} (model: ${i.model})`,evidence:d.reasoning,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:r})}},{name:n?.name??"eval-intake-bridge"})}function kb(t,e){return ke(t,()=>Y(e()))}function xb(t,e){return C([t,e],([n,r])=>{let o=n,s=r,i=new Map(o.tasks.map(p=>[p.task_id,p])),a=new Map(s.tasks.map(p=>[p.task_id,p])),d=new Set([...i.keys(),...a.keys()]),u=[],c=[],l=[];for(let p of d){let f=i.get(p),m=a.get(p),h=f?.valid??!1,g=m?.valid??!1,y=f?.judge_scores?f.judge_scores.filter(T=>T.pass).length:void 0,b=m?.judge_scores?m.judge_scores.filter(T=>T.pass).length:void 0,v=y!==void 0&&b!==void 0?b-y:void 0;u.push({taskId:p,before:h,after:g,scoreDiff:v}),h&&!g&&c.push(p),!h&&g&&l.push(p)}return{newFailures:c,resolved:l,taskDeltas:u,overallImproved:l.length>c.length}},{name:"eval-delta"})}function Rb(t,e){let n=e==null?null:Array.isArray(e)?A(e):e,r=[t];return n&&r.push(n),C(r,o=>{let s=o[0],i=n?new Set(o[1]):null,a=new Set;for(let d of s)for(let u of d.affectsEvalTasks??[])(i==null||i.has(u))&&a.add(u);return[...a].sort()},{name:"affected-task-filter"})}function Sb(t,e,n,r){let o=r?.defaultSeverity??"high";function s(a){let d=[];for(let u of a.lintErrors??[])d.push({source:"code-change",summary:`Lint: ${u.rule} in ${u.file}:${u.line}`,evidence:u.message,affectsAreas:[u.file],severity:o});for(let u of a.testFailures??[])d.push({source:"test",summary:`Test failure: ${u.testId}`,evidence:u.message,affectsAreas:[u.file],affectsEvalTasks:[u.testId],severity:o});return d}let i=n??s;return ge([t],([a])=>{if(a!=null)for(let d of i(a))e.publish(d)},{name:r?.name??"code-change-bridge"})}function Nb(t,e,n){return ge([t.latest],([r])=>{r!=null&&e(r)},{name:n?.name??"notify-effect"})}var ct=["auto-fix","needs-decision","investigation","backlog"],Ai={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1}},hr={critical:100,high:70,medium:40,low:10},yr=Math.LN2/(168*3600);function br(t,e){return`${t}\u2192${e}`}var Eb=/\b(parse|json|config|validation|syntax)\b/i,Ci=t=>Eb.test(t.detail)?"self-correctable":"structural",Wd=`You are a triage classifier for a reactive collaboration harness.
|
|
177
177
|
|
|
178
178
|
Given an intake item, classify it and output JSON:
|
|
179
179
|
{
|
|
@@ -188,7 +188,7 @@ Strategy model (past effectiveness):
|
|
|
188
188
|
{{strategy}}
|
|
189
189
|
|
|
190
190
|
Intake item:
|
|
191
|
-
{{item}}`,
|
|
191
|
+
{{item}}`,Ud=`You are an implementation agent.
|
|
192
192
|
|
|
193
193
|
Given a triaged issue with root cause and intervention type, produce a fix.
|
|
194
194
|
|
|
@@ -199,7 +199,7 @@ Output JSON:
|
|
|
199
199
|
{
|
|
200
200
|
"outcome": "success" | "failure" | "partial",
|
|
201
201
|
"detail": "<description of what was done or what failed>"
|
|
202
|
-
}`,
|
|
202
|
+
}`,Jd=`You are a QA reviewer.
|
|
203
203
|
|
|
204
204
|
Given an execution result, verify whether the fix is correct.
|
|
205
205
|
|
|
@@ -214,11 +214,11 @@ Output JSON:
|
|
|
214
214
|
"verified": true/false,
|
|
215
215
|
"findings": ["<finding1>", ...],
|
|
216
216
|
"errorClass": "self-correctable" | "structural" // only if verified=false
|
|
217
|
-
}`;function
|
|
217
|
+
}`;function Ao(t,e,n){if(typeof t=="function")return t;let r=t??e;return o=>n(r,o)}ne();ne();var Li={};Se(Li,{blindVariation:()=>Mb,errorCritique:()=>Cb,refineLoop:()=>Qd});Ae();Re();ae();Me();ne();function _b(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 Mf(t,e){if(t.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(t.length===1){let s=Yd(e);return{best:t[0],bestScore:s}}if(e.some(s=>typeof s.candidateIndex=="number")){let s=new Array(t.length);for(let d=0;d<t.length;d++)s[d]={sum:0,count:0};for(let d of e){let u=d.candidateIndex;typeof u=="number"&&u>=0&&u<t.length&&(s[u].sum+=d.score,s[u].count+=1)}let i=t[0],a=s[0].count>0?s[0].sum/s[0].count:Number.NEGATIVE_INFINITY;for(let d=1;d<t.length;d++){let u=s[d].count>0?s[d].sum/s[d].count:Number.NEGATIVE_INFINITY;u>a&&(a=u,i=t[d])}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 Yd(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 Qd(t,e,n,r){let o=r.name??"refine-loop",s=new Q(o,r.graph),i=_b(r.dataset)?r.dataset:A(r.dataset,{name:"dataset"});s.add(i,{name:"dataset"});let a=A(0,{name:"iteration"});s.add(a,{name:"iteration"});let d=A(n,{name:"strategy",equals:()=>!1});s.add(d,{name:"strategy"});let u=A(null,{name:"lastFeedback"});s.add(u,{name:"lastFeedback"});let c=A([],{name:"prevCandidates"});s.add(c,{name:"prevCandidates"});let l=A(!1,{name:"paused"});s.add(l,{name:"paused"});let p=A("running",{name:"status"});s.add(p,{name:"status"});let f=A([],{name:"history",equals:()=>!1});s.add(f,{name:"history"});let m=A(null,{name:"best"});s.add(m,{name:"best"});let h=A(Number.NEGATIVE_INFINITY,{name:"score"});s.add(h,{name:"score"});let g=A(0,{name:"budget-used"});s.add(g,{name:"budget-used"});let y=ko("stages");s.mount("stages",y);let b=y.topic("generate"),v=y.topic("evaluate"),T=y.topic("analyze"),w=y.topic("decide"),x=n,k=null,S=[];s.addDisposer(d.subscribe(J=>{for(let de of J)de[0]===M&&(x=de[1])})),s.addDisposer(u.subscribe(J=>{for(let de of J)de[0]===M&&(k=de[1])})),s.addDisposer(c.subscribe(J=>{for(let de of J)de[0]===M&&(S=de[1])}));let R=ke(a,J=>{let de=x,Le=J===0||k==null;return U([],(Te,X)=>{let ie=!1;try{let xe=Le?de.seed(t):de.generate(k,S);if(xe instanceof Promise)return xe.then(W=>{ie||X.emit(W)},W=>{ie||X.down([[I,W]])}),()=>{ie=!0};X.emit(xe)}catch(xe){ie=!0,X.down([[I,xe]])}},{describeKind:"producer"})},{name:"candidates"});s.add(R,{name:"candidates"});let E=ge([R],(J,de,Le)=>{let Te=Le.terminalDeps[0];Te!==void 0&&Te!==!0&&p.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});s.add(E,{name:"error-watcher"}),s.addDisposer(E.subscribe(()=>{}));let _=C([R,a],([J,de])=>({iteration:de,candidates:J,timestamp_ns:V()}),{name:"generate-event"});s.add(_,{name:"generate-event"}),s.addDisposer(_.subscribe(()=>{}));let O=ge([_],([J])=>{b.publish(J)},{name:"generate-publish"});s.add(O,{name:"generate-publish"}),s.addDisposer(O.subscribe(()=>{}));let N=ge([R],([J])=>{c.emit(J)},{name:"generate-mirror"});s.add(N,{name:"generate-mirror"}),s.addDisposer(N.subscribe(()=>{}));let L=e(R,i);s.add(L,{name:"scores"});let j=C([L,R,a],([J,de,Le])=>({iteration:Le,candidates:de,scores:J,timestamp_ns:V()}),{name:"evaluate-event"});s.add(j,{name:"evaluate-event"}),s.addDisposer(j.subscribe(()=>{}));let $=ge([j],([J])=>{v.publish(J)},{name:"evaluate-publish"});s.add($,{name:"evaluate-publish"}),s.addDisposer($.subscribe(()=>{}));let D=C([L,R],([J,de])=>x.analyze(J,de),{name:"feedback"});s.add(D,{name:"feedback"});let K=C([D,R,a],([J,de,Le])=>({iteration:Le,candidates:de,feedback:J,timestamp_ns:V()}),{name:"analyze-event"});s.add(K,{name:"analyze-event"}),s.addDisposer(K.subscribe(()=>{}));let F=ge([K],([J])=>{T.publish(J)},{name:"analyze-publish"});s.add(F,{name:"analyze-publish"}),s.addDisposer(F.subscribe(()=>{}));let H=C([f],([J])=>{let de=J;if(r.patience==null||de.length<=r.patience)return!1;let Le=de.slice(-(r.patience+1)),Te=Le[0].bestScore;return Le.slice(1).every(X=>X.bestScore<=Te)},{name:"patience-check"});s.add(H,{name:"patience-check"});let G=C([h],([J])=>r.minScore!=null&&J>=r.minScore,{name:"min-score-check"});s.add(G,{name:"min-score-check"});let B=C([f],([J])=>{let de=J;if(r.minDelta==null||de.length<2)return!1;let Le=de[de.length-2].bestScore,Te=de[de.length-1].bestScore;return Math.abs(Te-Le)<r.minDelta},{name:"min-delta-check"});s.add(B,{name:"min-delta-check"});let re=C([g],([J])=>r.maxEvaluations!=null&&J>=r.maxEvaluations,{name:"max-evaluations-check"});s.add(re,{name:"max-evaluations-check"});let pe=C([a],([J])=>r.maxIterations!=null&&J>=r.maxIterations,{name:"max-iterations-check"});s.add(pe,{name:"max-iterations-check"});let ee=C([g],([J])=>r.budget!=null&&J>=r.budget,{name:"budget-exhausted-check"});s.add(ee,{name:"budget-exhausted-check"}),s.addDisposer(H.subscribe(()=>{})),s.addDisposer(G.subscribe(()=>{})),s.addDisposer(B.subscribe(()=>{})),s.addDisposer(re.subscribe(()=>{})),s.addDisposer(pe.subscribe(()=>{})),s.addDisposer(ee.subscribe(()=>{}));let ue=C([H,G,B,re,pe],([J,de,Le,Te,X])=>J?{converged:!0,reason:"patience"}:de?{converged:!0,reason:"min-score"}:Le?{converged:!0,reason:"min-delta"}:Te?{converged:!0,reason:"max-evaluations"}:X?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});s.add(ue,{name:"converged"}),s.addDisposer(ue.subscribe(()=>{}));let Ce=-1,Ye=ge([D,L,R],([J,de,Le])=>{let Te=a.cache,X=J,ie=Le,xe=de;if(Te<=Ce)return;Ce=Te;let{best:W,bestScore:fe}=Mf(ie,xe),Ne=f.cache,Ee={n:Te,candidates:ie,scores:xe,feedback:X,best:W,bestScore:fe,timestamp_ns:V()},me=[...Ne,Ee],De=g.cache+ie.length,ye="continue",be,Tr=r.budget!=null&&De>=r.budget,Mn=l.cache;if(Tr)ye="budget",be="budget";else if(r.minScore!=null&&X.score>=r.minScore)ye="converged",be="min-score";else if(r.maxIterations!=null&&Te>=r.maxIterations)ye="converged",be="max-iterations";else if(r.maxEvaluations!=null&&De>=r.maxEvaluations)ye="converged",be="max-evaluations";else if(r.minDelta!=null&&me.length>=2){let Po=me[me.length-2].bestScore,ta=me[me.length-1].bestScore;Math.abs(ta-Po)<r.minDelta&&(ye="converged",be="min-delta")}else if(r.patience!=null&&me.length>r.patience){let Po=me.slice(-(r.patience+1)),ta=Po[0].bestScore;Po.slice(1).every(Jf=>Jf.bestScore<=ta)&&(ye="converged",be="patience")}ye==="continue"&&Mn&&(ye="paused"),Z(()=>{m.emit(W),h.emit(X.score),f.emit(me),g.emit(De),u.emit(X),w.publish({iteration:Te,decision:ye,reason:be,timestamp_ns:V()}),ye==="continue"?a.emit(Te+1):p.emit(ye==="converged"?"converged":ye==="budget"?"budget":"paused")})},{name:"decide-bridge"});return s.add(Ye,{name:"decide-bridge"}),s.addDisposer(Ye.subscribe(()=>{})),Object.assign(s,{best:m,score:h,status:p,history:f,strategy:d,iteration:a,generate:b,evaluate:v,analyze:T,decide:w,setStrategy(J){d.emit(J)},pause(){l.emit(!0)},resume(){p.cache==="paused"&&Z(()=>{l.emit(!1),p.emit("running"),a.emit(a.cache+1)})}})}function Mb(t){let e=t.width??4;return{name:t.name??"blindVariation",seed(r){return[r]},analyze(r,o){let s=Yd(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,d={prior:s,reportCost:u=>{i+=u}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(d)));let u=[];for(let c=0;c<e;c++)u.push(await t.teacher(d));return u}finally{if(t.tokens!=null&&i>0){let u=t.tokens.cache??0;t.tokens.emit(u+i)}}}}}function Ob(t){return typeof t=="object"&&t!==null&&t.kind==="errorCritique"}function Ab(t,e){return t.length===0?`No task scored below the batch mean (${e.score.toFixed(3)}). Reinforce the current direction.`:`Failures below threshold:
|
|
218
218
|
${t.map(r=>{let o=r.error!=null?` | error: ${r.error}`:"";return`- ${r.taskId} (score=${r.score.toFixed(3)})${o}`}).join(`
|
|
219
|
-
`)}`}function db(t){let e=t.width??4,n=t.name??"errorCritique",r=t.maxFailureSamples??5,o=t.formatCritique??ub;return{name:n,seed(s){return[s]},analyze(s,i){let a=$u(s),u=typeof t.failureThreshold=="function"?t.failureThreshold(s):t.failureThreshold,d=u===void 0&&!Number.isFinite(a),c=u??a,l=d?[...s].sort((v,T)=>v.score-T.score):s.filter(v=>v.score<c).slice().sort((v,T)=>v.score-T.score),p=l.slice(0,r),{best:f,bestScore:m}=df(i,s),h={summary:"",score:a,weakTasks:p.map(v=>v.taskId)},g=o(p,h),y={kind:"errorCritique",best:f,failures:p,critiqueText:g},b=l.length>p.length?` (top ${p.length} retained)`:"";return{summary:`errorCritique iteration: mean=${a.toFixed(3)}, failures=${l.length}${b}/${s.length}, bestScore=${m.toFixed(3)}`,critique:y,weakTasks:p.map(v=>v.taskId),score:a}},async generate(s,i){if(i.length===0)throw new Error("errorCritique.generate: empty candidate batch \u2014 cannot derive prior for teacher");let a=ab(s.critique)?s.critique:void 0,u=a!==void 0?a.best:i[i.length-1],d=a?.critiqueText??s.summary,c=a?.failures??[],l=0,f={prior:u,critique:d,failures:c,reportCost:m=>{l+=m}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(f)));let m=[];for(let h=0;h<e;h++)m.push(await t.teacher(f));return m}finally{if(t.tokens!=null&&l>0){let m=t.tokens.cache??0;t.tokens.emit(m+l)}}}}}function cb(t){let{best:e,score:n,status:r}=t,o=Number.isFinite(n)?n.toFixed(3):String(n),s=e??void 0;return r==="converged"?{outcome:"success",detail:`refineLoop converged at score ${o}`,artifact:s}:r==="budget"?{outcome:"partial",detail:`refineLoop hit budget at score ${o}`,artifact:s}:{outcome:"failure",detail:`refineLoop errored (status=${r})`,artifact:s}}function Bu(t){let e=t.name??"refine-executor",n=t.toOutput??cb;return r=>{let o=Xe(r,i=>i!=null,{name:`${e}/gate-in`}),s=Te(o,i=>{let a=ju(t.seedFrom(i),t.evaluator,t.strategy,{...t.refine,dataset:t.datasetFor(i),name:`${e}/inner`});return A([a.status,a.best,a.score],([u,d,c])=>{let l=u;return l!=="converged"&&l!=="budget"&&l!=="errored"?null:n({best:d,score:c,status:l})},{name:`${e}/output`})},{name:e});return Xe(s,i=>i!=null,{name:`${e}/gate-out`})}}function lb(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let n of t)e+=n.score;return e/t.length}function pb(t){let{passCount:e,total:n,meanScore:r,threshold:o,missingArtifact:s}=t,i=Number.isFinite(r)?r.toFixed(3):String(r),a=!s&&n>0&&r>=o,u=s?["EXECUTE stage did not emit an artifact; cannot verify reactively"]:a?[`${e}/${n} eval tasks passed; mean score ${i} \u2265 ${o}`]:n===0?["No eval tasks were selected for this item \u2014 cannot verify"]:[`${e}/${n} eval tasks passed; mean score ${i} < threshold ${o}`];return a?{verified:!0,findings:u}:{verified:!1,findings:u,errorClass:"structural"}}function fb(t){return t.artifact??null}function cf(t){let e=t.name??"eval-verifier",n=t.threshold??.5,r=t.toOutput??pb,o=t.extractArtifact??fb;return s=>{let i=Xe(s,u=>u!=null&&u[0]!=null&&u[1]!=null,{name:`${e}/gate-in`}),a=Te(i,u=>{let[d,c]=u,l=o(d,c);if(l==null)return M(r({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:n,missingArtifact:!0}));let p=M([l],{name:`${e}/candidates`}),f=M(t.datasetFor(c),{name:`${e}/dataset`}),m=t.evaluator(p,f);return A([m],([h])=>{let g=h;if(g==null)return null;let y=lb(g),b=g.filter(v=>v.score>=n).length;return r({scores:g,meanScore:y,passCount:b,total:g.length,threshold:n})},{name:`${e}/output`})},{name:e});return Xe(a,u=>u!=null,{name:`${e}/gate-out`})}}function mb(t){let e=t.name??"harness-pair",n=Bu({name:`${e}-exec`,seedFrom:t.seedFrom,evaluator:t.evaluator,strategy:t.strategy,datasetFor:t.datasetFor,refine:t.refine}),r=cf({name:`${e}-verify`,evaluator:t.evaluator,datasetFor:t.datasetFor,threshold:t.threshold});return{executor:n,verifier:r}}xe();_e();ee();var Oi={};ke(Oi,{JobFlowGraph:()=>_i,JobQueueGraph:()=>Ni,jobEventKeyOf:()=>yb,jobFlow:()=>bb,jobQueue:()=>Mi});xe();_e();he();var gb=256,hb=1024;function lf(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Ei(t,e){return ze("job_queue",t,e)}var yb=t=>t.action,Ni=class extends Y{_pending;_jobs;_seqCursor;pending;jobs;depth;events;audit;constructor(e,n={}){super(e,n.graph),this._pending=Ds([],{name:"pending"}),this._jobs=Ze({name:"jobs"}),this.pending=this._pending.items,this.jobs=this._jobs.entries,this.add(this.pending,{name:"pending"}),this.add(this.jobs,{name:"jobs"}),this.depth=A([this.pending],([r])=>r.length,{name:"depth",describeKind:"derived",meta:Ei("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(re(this.depth)),this.events=kt({name:"events",retainedLimit:1024,graph:this}),this.audit=this.events,this._seqCursor=bs(this,"seq",0)}_bumpSeq(){let n=(this._seqCursor.cache??0)+1;return this._seqCursor.emit(n),n}attachEventStorage(e){return this.events.attachStorage(e)}enqueue(e,n={}){let r=this._bumpSeq(),o=n.id??`${this.name}-${r}`;if(this._jobs.get(o)!==void 0)throw new Error(`jobQueue("${this.name}"): duplicate job id "${o}"`);let s={id:o,payload:e,attempts:0,metadata:Object.freeze({...n.metadata??{}}),state:"queued"};return this._jobs.set(o,s),this._pending.append(o),this.events.append({action:"enqueue",id:o,payload:e,t_ns:oe(),seq:r}),o}claim(e=1){let n=lf(e,"job queue claim limit");if(n===0)return[];let r=[];for(;r.length<n&&this.pending.cache.length!==0;){let s=this._pending.pop(0),i=this._jobs.get(s);if(!i||i.state!=="queued")continue;let a={...i,state:"inflight",attempts:i.attempts+1};this._jobs.set(s,a),r.push(a),this.events.append({action:"claim",id:s,attempts:a.attempts,t_ns:oe(),seq:this._bumpSeq()})}return r}ack(e){let n=this._jobs.get(e);return!n||n.state!=="inflight"?!1:(this._jobs.delete(e),this.events.append({action:"ack",id:e,attempts:n.attempts,t_ns:oe(),seq:this._bumpSeq()}),!0)}nack(e,n={}){let r=this._jobs.get(e);return!r||r.state!=="inflight"?!1:n.requeue??!0?(this._jobs.set(e,{...r,state:"queued"}),this._pending.append(e),this.events.append({action:"nack",id:e,attempts:r.attempts,t_ns:oe(),seq:this._bumpSeq()}),!0):(this._jobs.delete(e),this.events.append({action:"nack",id:e,attempts:r.attempts,t_ns:oe(),seq:this._bumpSeq()}),!0)}removeById(e){let n=this._jobs.get(e);if(!n)return!1;if(n.state==="queued"){let o=this.pending.cache.indexOf(e);o>=0&&this._pending.pop(o)}return this._jobs.delete(e),this.events.append({action:"remove",id:e,attempts:n.attempts,t_ns:oe(),seq:this._bumpSeq()}),!0}consumeFrom(e,n){return e.subscribe(r=>{for(let o of r){if(o[0]!==E)continue;let s=o[1];this.enqueue(s,n?{metadata:n.metadata}:void 0)}})}},_i=class extends Y{_stageNames;_stageWorkFns;_queues=new Map;_completed;completed;completedCount;constructor(e,n={}){super(e,n.graph);let r=n.stages??["incoming","processing","done"],o=[],s=new Map;for(let u of r){let d=typeof u=="string"?u.trim():u.name.trim();typeof u!="string"&&u.work&&s.set(d,u.work),o.push(d)}if(o.length<2)throw new Error(`jobFlow("${e}"): requires at least 2 stages`);if(new Set(o).size!==o.length)throw new Error(`jobFlow("${e}"): stage names must be unique`);this._stageNames=Object.freeze([...o]),this._stageWorkFns=s;for(let u of this._stageNames){let d=Mi(`${e}-${u}`);this._queues.set(u,d),this.mount(u,d)}this._completed=Ve([],{name:"completed",maxSize:hb}),this.completed=this._completed.entries,this.add(this.completed,{name:"completed"}),this.completedCount=A([this.completed],([u])=>u.length,{name:"completedCount",describeKind:"derived",meta:Ei("job_flow_completed_count"),initial:0}),this.add(this.completedCount,{name:"completedCount"}),this.addDisposer(re(this.completedCount));let a=Math.max(1,lf(n.maxPerPump??gb,"job flow maxPerPump"));for(let u=0;u<this._stageNames.length;u+=1){let d=this._stageNames[u],c=this.queue(d),l=u+1<this._stageNames.length?this.queue(this._stageNames[u+1]):null,p=this._stageWorkFns.get(d),f=l===null;if(p){let m=z([c.pending],()=>{let h=0;for(;h<a;){let g=c.claim(1);if(g.length===0)break;let y=g[0];if(!y)break;let v=[...y.metadata.job_flow_path??[],d],T;try{T=p(y)}catch{c.nack(y.id,{requeue:!1}),h+=1;continue}let w=U(T),x=!1,k;k=w.subscribe(S=>{if(!x){for(let R of S)if(R[0]===E){x=!0,k?k():Promise.resolve().then(()=>k?.());let N=R[1],_={...y.metadata,job_flow_path:v};if(f){let I={...y,payload:N,metadata:Object.freeze(_)};X(()=>{c.ack(y.id),this._completed.append(I)})}else X(()=>{c.ack(y.id),l.enqueue(N,{metadata:_})});return}else if(R[0]===C){x=!0,k?k():Promise.resolve().then(()=>k?.()),c.nack(y.id,{requeue:!1});return}}}),h+=1}},{name:`pump_${d}`,describeKind:"effect",meta:Ei("job_flow_pump",{stage:d,has_work:!0})});this.add(m,{name:`pump_${d}`}),this.addDisposer(re(m))}else{let m=z([c.pending],()=>{let h=0;for(;h<a;){let g=c.claim(1);if(g.length===0)break;let y=g[0];if(!y)break;let v=[...y.metadata.job_flow_path??[],d],T={...y.metadata,job_flow_path:v};if(f){let w={...y,metadata:Object.freeze(T)};X(()=>{c.ack(y.id),this._completed.append(w)})}else X(()=>{c.ack(y.id),l.enqueue(y.payload,{metadata:T})});h+=1}},{name:`pump_${d}`,describeKind:"effect",meta:Ei("job_flow_pump",{stage:d,has_work:!1})});this.add(m,{name:`pump_${d}`}),this.addDisposer(re(m))}}}stages(){return this._stageNames}queue(e){let n=this._queues.get(e);if(!n)throw new Error(`jobFlow("${this.name}"): unknown stage "${e}"`);return n}enqueue(e,n={}){return this.queue(this._stageNames[0]).enqueue(e,n)}retainedCompleted(){return this.completed.cache}};function Mi(t,e){return new Ni(t,e)}function bb(t,e){return new _i(t,e)}xe();ee();function Vu(){let t=Ze({name:"strategy-entries"}),e=A([t.entries],([i])=>{let a=i;return new Map(a)},{name:"strategy-model",equals:(i,a)=>{let u=i,d=a;if(u.size!==d.size)return!1;for(let[c,l]of u){let p=d.get(c);if(!p||l.attempts!==p.attempts||l.successes!==p.successes)return!1}return!0}});function n(i,a,u){let d=lr(i,a),c=t.get(d),l=(c?.attempts??0)+1,p=(c?.successes??0)+(u?1:0);t.set(d,{rootCause:i,intervention:a,attempts:l,successes:p,successRate:p/l})}function r(i,a){return t.get(lr(i,a))}let o=e.subscribe(()=>{});function s(){o()}return{node:e,record:n,lookup:r,dispose:s}}function vb(t,e,n,r,o){let s={...dr,...o?.severityWeights},i=o?.decayRate??cr,a=o?.effectivenessThreshold??.7,u=o?.effectivenessBoost??15,d=[t,e,n];return r&&d.push(r),A(d,c=>{let l=c[0],p=c[1],f=c[2],m=r?c[3]:0,h=s[l.severity??"medium"],g=(H()-f)/1e9,y=xn(h,g,i,0),b=lr(l.rootCause,l.intervention),v=p.get(b);return v&&v.successRate>=a&&(y+=u),y+=m*20,y},{name:"priority-score"})}var pf="intake",Tb="triage-output",ff="retry",mf="verify-results",gf="__unrouted";function hf(t,e){let n=Ro(e,Gu,(r,o)=>r.replace("{{item}}",JSON.stringify(o)));return r=>wn(t,[r],n,{name:"execute",format:"json"})}function yf(t,e){let n=Ro(e,Fu,(r,o)=>{let[s,i]=o;return r.replace("{{execution}}",JSON.stringify(s)).replace("{{item}}",JSON.stringify(i))});return r=>wn(t,[r],o=>o==null?"":n(o),{name:"verify",format:"json"})}var Ci=class extends Y{queues;jobs;gates;queueTopics;strategy;totalRetries;totalReingestions;priorityScores;constructor(e,n,r,o,s,i,a,u,d){super(e),this.queues=n,this.queueTopics=r,this.jobs=o,this.gates=s,this.strategy=i,this.totalRetries=a,this.totalReingestions=u,this.priorityScores=d}get intake(){return this.queues.topic(pf)}get verifyResults(){return this.queues.topic(mf)}get retry(){return this.queues.topic(ff)}get unrouted(){return this.queues.topic(gf)}stageNodes(){let e=this.queues,n=i=>e.has(i)?`queues::${i}::latest`:null,r=i=>i==null?[]:[i],o=it.flatMap(i=>r(n(i))),s=[];for(let[i]of this.gates)s.push(`gates::${i}/gate`);return[{label:"INTAKE",paths:r(n("intake"))},{label:"TRIAGE",paths:["triage"]},{label:"QUEUE",paths:o},{label:"GATE",paths:s},{label:"EXECUTE",paths:["execute"]},{label:"VERIFY",paths:r(n("verify-results"))},{label:"REFLECT",paths:["reflect"]},{label:"STRATEGY",paths:["strategy"]}]}};function wb(t,e){let n=e.adapter,r=e.maxRetries??2,o=e.retainedLimit??1e3,s=e.errorClassifier??Ri,i=new Map;for(let J of it)i.set(J,{...xi[J],...e.queues?.[J]});let a=go(`${t}/queues`,{defaultTopicOptions:{retainedLimit:o}}),u=a.topic(pf),d=a.topic(Tb),c=a.topic(ff),l=a.topic(mf),p=new Map;for(let J of it)p.set(J,a.topic(J));let f=a.topic(gf),m=Vu(),h=Pt(u.latest,m.node),g=Ro(e.triagePrompt,Du,(J,se)=>{let[ve,W]=se;return J.replace("{{strategy}}",JSON.stringify(Array.from(W.entries()))).replace("{{item}}",JSON.stringify(ve))}),y=wn(n,[h],J=>{let se=J;return!se||!se[0]?"":g(se)},{name:"triage",format:"json"}),b=Pt(y,h),T=pe([b],([J])=>{if(J==null)return;let[se,ve]=J;if(!se?.route)return;let W=ve?.[0],de={...se,...W};d.publish(de)}).subscribe(()=>{}),w=new Set(it);for(let J of it)ri(`bridge/${J}`,d,p.get(J),{map:se=>se.route===J?se:void 0});ri("bridge/__unrouted",d,f,{map:J=>w.has(J.route)?void 0:J});let x=new Map,k=new Map;for(let J of it)x.set(J,Mi(`jobs/${J}`));let S=[];for(let J of it){let se=p.get(J),ve=x.get(J),W=new WeakSet,de=pe([se.events],([Se])=>{let Ee=Se??[];for(let ce of Ee){if(W.has(ce))continue;W.add(ce);let Pe=ve.enqueue(ce);k.set(qr(ce),{route:J,id:Pe})}},{name:`jobs/${J}-mirror`});S.push(de.subscribe(()=>{}))}function R(J){let se=qr(J),ve=k.get(se);ve&&(x.get(ve.route)?.removeById(ve.id),k.delete(se))}let N=ir("gates"),_=new Map;for(let J of it){let se=i.get(J);if(!se.gated)continue;let ve=p.get(J),W=N.gate(`${J}/gate`,ve.latest,{maxPending:se.maxPending,startOpen:se.startOpen});_.set(J,W)}let I=[];for(let J of it)i.get(J).gated&&_.has(J)?I.push(_.get(J).node):I.push(p.get(J).latest);I.push(c.latest);let O=xt(...I),B=(e.executor??hf(n,e.executePrompt))(O),j=Pt(B,O),Z=(e.verifier??yf(n,e.verifyPrompt))(j),F=Pt(Z,j),Q=e.maxReingestions??1,G=Math.min(e.maxTotalRetries??r*10,100),q=Math.min(e.maxTotalReingestions??Q*10,100),$=M(0),te=M(0);function Re(J,se,ve){let W={item:ve,outcome:se?.outcome??"failure",detail:se?.detail??"unknown",artifact:se?.artifact};return{item:ve,execution:W,verified:J.verified,findings:J.findings??[],errorClass:J.errorClass}}function Oe(J,se){m.record(se.rootCause,se.intervention,!0),l.publish(J),R(se)}function Ce(J,se){let ve=qr(se),W=se.$retries??0,de={...se,$retries:W+1,summary:`[RETRY ${W+1}/${r}] ${ve} \u2014 Previous attempt failed: ${J.findings.join("; ")}`,relatedTo:[ve]};c.publish(de)}function ye(J,se){m.record(se.rootCause,se.intervention,!1),l.publish(J),R(se);let ve=qr(se),W=se.$reingestions??0;W<Q&&Kr(te,q)&&u.publish({source:se.source,summary:`Verification failed for: ${ve}`,evidence:J.findings.join(`
|
|
220
|
-
`),affectsAreas:se.affectsAreas,affectsEvalTasks:se.affectsEvalTasks,severity:se.severity??"high",relatedTo:[ve],$reingestions:W+1})}let Ge=z([F],(J,se)=>{let ve=J[0];if(ve==null||ve.length===0)return;let W=ve[ve.length-1];if(W==null)return;let[de,Se]=W,[Ee,ce]=Se??[null,null];if(!de||!ce)return;if(Ee==null){ye({item:ce,execution:{item:ce,outcome:"failure",detail:"executor returned null"},verified:!1,findings:["executor returned null"],errorClass:"structural"},ce);return}let Pe=Re(de,Ee,ce);if(Pe.verified){Oe(Pe,ce);return}let me=Pe.errorClass??s({item:ce,outcome:Ee.outcome,detail:Pe.findings.join("; ")}),ge=ce.$retries??0;me==="self-correctable"&&ge<r&&Kr($,G)?Ce(Pe,ce):ye(Pe,ce)}),ie=Ge.subscribe(()=>{}),we=A([Ge],()=>null,{name:"reflect",equals:()=>!1}),Fe;e.priority&&(Fe=kb(p,m,e));let be=new Ci(t,a,p,x,_,m,$,te,Fe);be.addDisposer(T),be.addDisposer(ie),be.addDisposer(m.dispose);for(let J of S)be.addDisposer(J);if(be.add(y,{name:"triage"}),be.add(O,{name:"execute-input"}),be.add(B,{name:"execute"}),be.add(j,{name:"execute-context"}),be.add(Z,{name:"verify"}),be.add(F,{name:"verify-context"}),be.add(Ge,{name:"verify-dispatch"}),be.add(we,{name:"reflect"}),be.add(m.node,{name:"strategy"}),be.addDisposer(we.subscribe(()=>{})),Fe)for(let[J,se]of Fe)be.add(se,{name:`priority/${J}`}),be.addDisposer(se.subscribe(()=>{}));be.mount("queues",a),be.mount("gates",N);for(let[J,se]of x)be.mount(`jobs/${J}`,se);return be}function kb(t,e,n){if(!n.lastInteractionNs)throw new Error("harnessLoop: `opts.priority` requires `opts.lastInteractionNs` \u2014 pass a Node<number> (e.g. `fromTimer(60_000)` or a `state(monotonicNs())` you bump on human interaction). Priority scores only decay when this node settles; an internal default would freeze age at construction time.");let r=n.lastInteractionNs,o=n.priority??{},s={...dr,...o.severityWeights},i=o.decayRate??cr,a=o.effectivenessThreshold??.7,u=o.effectivenessBoost??15,d=new Map;for(let[c,l]of t){let p=A([l.latest,e.node,r],f=>{let m=f[0];if(m==null)return 0;let h=s[m.severity??"medium"]??40,g=(H()-f[2])/1e9,y=h*Math.exp(-i*Math.max(0,g)),b=`${m.rootCause}\u2192${m.intervention}`,T=f[1]?.get(b);return T&&T.successRate>=a&&(y+=u),y},{name:`priority/${c}`});d.set(c,p)}return d}function xb(t,e){let n=pn(t,e),r={};for(let o of it){let s=t.queues.has(o)?t.queues.topic(o):null;r[o]=s?.retained().length??0}return{...n,queueDepths:r,strategyEntries:t.strategy.node.cache?.size??0,totalRetries:t.totalRetries.cache??0,totalReingestions:t.totalReingestions.cache??0}}xe();function Rb(t){let e={};for(let{label:n,paths:r}of t.stageNodes())for(let o of r)e[o]=n;return e}function Sb(t,e){let n=e?.logger===null?null:e?.logger??console.log,r=e?.detail??"summary",o=H(),s=[],i=[],a=Rb(t);function u(){return(H()-o)/1e9}function d(c,l,p){let f={elapsed:u(),stage:c,type:l};r!=="summary"&&(f.summary=Eb(p)),r==="full"&&(f.data=p),i.push(f)}for(let[c,l]of Object.entries(a))try{let p=t.observe(c,{format:"stage-log",stageLabels:a,logger:n?f=>n(f):()=>{},includeTypes:["data","error","complete"]});p.onEvent(f=>{f.type==="data"?d(l,"data",f.data):f.type==="error"?d(l,"error",f.data):f.type==="complete"&&d(l,"complete",void 0)}),s.push(p)}catch(p){let f=p instanceof Error?p.message:String(p);d(l,"error",`observe-unavailable: ${c} \u2014 ${f}`),n&&n(`[${u().toFixed(3)}s] ${l.padEnd(9)} \u2717 observe-unavailable: ${f}`)}return{get events(){return i},dispose(){for(let c of s)c.dispose();s.length=0}}}function Eb(t){if(t==null)return"null";if(typeof t=="string")return bf(t,80);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return bf(e,120)}catch{return String(t)}}function bf(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}var Ii={};ke(Ii,{LensGraph:()=>Li,graphLens:()=>Cb,watchTopologyTree:()=>At});xe();ee();function vf(t){return ze("lens",t)}function Nb(t){let e=Object.keys(t.nodes),n=new Map,r=new Map;for(let h of e){let g=t.nodes[h]?.deps??[];n.set(h,g);for(let y of g)r.has(y)||r.set(y,new Set),r.get(y).add(h)}let o=[],s=[];for(let h of e)(n.get(h)??[]).length===0&&o.push(h),r.has(h)||s.push(h);o.sort(),s.sort();let i=t.edges.length,a=0,u=1,d=2,c=new Map;for(let h of e)c.set(h,a);let l=!1,p=new Map,f=h=>{let g=c.get(h)??a;if(g===u)return l=!0,0;if(g===d)return p.get(h)??0;c.set(h,u);let y=0,b=r.get(h);if(b!=null)for(let v of b){let T=f(v);T+1>y&&(y=T+1)}return c.set(h,d),p.set(h,y),y},m=0;for(let h of o){let g=f(h);g>m&&(m=g)}for(let h of e)c.get(h)===a&&f(h);return{nodeCount:e.length,edgeCount:i,subgraphCount:t.subgraphs.length,sources:o,sinks:s,depth:m,hasCycles:l}}function _b(t){let e=[];for(let[n,r]of Object.entries(t.nodes)){if(r.status!=="errored")continue;let o={path:n,status:"errored"},s=fn(t,n,"upstream",{});for(let i of s)if(i!==n&&t.nodes[i]?.status==="errored"){o.upstreamCause=i;break}e.push(o)}return e.sort((n,r)=>n.path<r.path?-1:n.path>r.path?1:0),{ok:e.length===0,problems:e}}function Mb(t,e){return t.nodeCount===e.nodeCount&&t.edgeCount===e.edgeCount&&t.subgraphCount===e.subgraphCount&&t.depth===e.depth&&t.hasCycles===e.hasCycles&&Tf(t.sources,e.sources)&&Tf(t.sinks,e.sinks)}function Ob(t,e){if(t.ok!==e.ok||t.problems.length!==e.problems.length)return!1;for(let n=0;n<t.problems.length;n++){let r=t.problems[n],o=e.problems[n];if(r.path!==o.path||r.status!==o.status||r.upstreamCause!==o.upstreamCause)return!1}return!0}function Tf(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}var Li=class extends Y{stats;health;flow;_target;constructor(e,n={}){super(n.name??`${e.name}_lens`,n.graph),this._target=e;let r=0,o=0,s=M(0,{name:"stats_tick"}),i=M(0,{name:"health_tick"});this.add(s,{name:"stats_tick"}),this.add(i,{name:"health_tick"});let a={name:"flow"};n.maxFlowPaths!=null&&(a.maxSize=n.maxFlowPaths),this.flow=Ze(a),this.add(this.flow.entries,{name:"flow"});let u=n.pathFilter,d=At(e,(p,f,m)=>{if(r+=1,s.emit(r),o+=1,i.emit(o),p.kind==="removed")if(p.nodeKind==="node"){let h=`${m}${p.name}`;this.flow.delete(h)}else{let h=`${m}${p.name}::`,g=[];for(let y of p.audit.nodes){let b=y===""?`${m}${p.name}`:`${h}${y}`;g.push(b)}g.length>0&&this.flow.deleteMany(g)}});this.addDisposer(d);let c=e.observe({timeline:!0,structured:!0}),l=c.onEvent(p=>{let f=p.type;if((f==="error"||f==="complete"||f==="data"||f==="teardown")&&(o+=1,i.emit(o)),f==="data"){let m=p.path??"";if(!m||u!=null&&!u(m))return;let h=this.flow.get(m),g=h!=null?h.count+1:1;this.flow.set(m,{path:m,count:g,lastUpdate_ns:H()})}});this.addDisposer(()=>{l(),c.dispose()}),this.stats=A([s],()=>Nb(e.describe({detail:"minimal"})),{name:"stats",describeKind:"derived",equals:Mb,meta:vf("stats")}),this.add(this.stats,{name:"stats"}),this.addDisposer(re(this.stats)),this.health=A([i],()=>_b(e.describe({detail:"standard"})),{name:"health",describeKind:"derived",equals:Ob,meta:vf("health")}),this.add(this.health,{name:"health"}),this.addDisposer(re(this.health))}why(e,n,r){let o=Ou(this._target,e,n,r);return this.addDisposer(o.dispose),o}get target(){return this._target}};function Cb(t,e){return new Li(t,e)}var Pi={};ke(Pi,{processInstanceKeyOf:()=>Ab,processManager:()=>Ib});xe();ae();he();var Ab=t=>t.correlationId;function wf(t){if(t==null)return Promise.resolve(void 0);let e=U(t);return new Promise((n,r)=>{let o=!1,s,i=()=>{s&&s()};s=e.subscribe(a=>{if(!o)for(let u of a){if(u[0]===E){o=!0,Promise.resolve().then(i),n(u[1]);return}if(u[0]===C){o=!0,Promise.resolve().then(i),r(u[1]);return}if(u[0]===L){o=!0,Promise.resolve().then(i),n(void 0);return}}})})}async function Lb(t,e,n,r,o){let s;for(let i=0;i<=r;i++){if(i>0){let a=o[Math.min(i-1,o.length-1)]??0;a>0&&await new Promise(u=>setTimeout(u,a))}try{return await wf(t(e,n))}catch(a){s=a}}return{kind:"fail",error:s}}function Ib(t,e,n){let r=n.retryMax??0,o=n.backoffMs??[0],s=1024,i=new Map,a=new Set,u=new Map,d=kt({name:`${e}_process_instances`,retainedLimit:s,graph:t}),c=0;function l(){return++c}function p(R,N,_){f(R,N,_,void 0)}function f(R,N,_,I){let O=oe(),P={correlationId:R,state:N,status:_,startedAt:u.get(R)??O,updatedAt:O,t_ns:O,seq:l(),...n.handlerVersion!==void 0?{handlerVersion:n.handlerVersion}:{},...I!==void 0?{reason:I}:{}};d.append(P)}let m=`_process_${e}_started`;t.event(m),n.persistence?.eventStorage&&t.attachEventStorage(n.persistence.eventStorage);async function h(R,N,_,I){if(a.delete(R),i.delete(R),u.delete(R),n.compensate)try{await wf(n.compensate(N,_)),f(R,N,"compensated",I)}catch{p(R,N,"failed")}else p(R,N,"failed")}async function g(R,N){if(a.has(R)){if(N.kind==="fail"){let _=i.get(R)??n.initial;await h(R,_,N.error);return}if(N.kind==="continue"){if(i.set(R,N.state),N.emit)for(let _ of N.emit)try{t._appendEvent(_.type,_.payload,{correlationId:R,aggregateId:R})}catch{}if(p(R,N.state,"running"),n.isTerminal?.(N.state)){a.delete(R),i.delete(R),u.delete(R),p(R,N.state,"terminated");return}if(N.schedule){let{afterMs:_,eventType:I}=N.schedule,O,P=st(_),B=j=>{for(let D of j)if(D[0]===E){if(O?O():queueMicrotask(()=>O?.()),!a.has(R))return;let Z=i.get(R);if(Z===void 0)return;let F=n.steps[I];if(!F)return;let Q={type:I,payload:null,timestampNs:oe(),seq:Number.NaN,correlationId:R,aggregateId:R};b(R,F,Z,Q)}};O=P.subscribe(B)}return}if(N.kind==="terminate"){if(i.set(R,N.state),N.emit)for(let _ of N.emit)try{t._appendEvent(_.type,_.payload,{correlationId:R,aggregateId:R})}catch{}a.delete(R),i.delete(R),u.delete(R),p(R,N.state,"terminated")}}}let y=new Map;function b(R,N,_,I){let P=(y.get(R)??Promise.resolve()).then(async()=>{let B=i.get(R);if(B===void 0||!a.has(R))return;let j;try{j=await Lb(N,B,I,r,o)}catch(D){await h(R,i.get(R)??n.initial,D);return}await g(R,j)});y.set(R,P),P.finally(()=>{y.get(R)===P&&y.delete(R)})}let v=!1,T=[];for(let R of n.watching){let N=t.event(R),_=0;_=(N.cache??[]).length;let O=N.subscribe(P=>{for(let B of P){if(B[0]!==E)continue;let j=B[1];if(j.length<=_)continue;let D=j.slice(_);_=j.length;for(let Z of D){let F=Z.correlationId;if(F===void 0||!a.has(F))continue;let Q=n.steps[R];if(!Q)continue;let G=i.get(F);G!==void 0&&b(F,Q,G,Z)}}});T.push(O)}function w(R,N){if(v||a.has(R))return;let _=oe();u.set(R,_),i.set(R,n.initial),a.add(R);try{t._appendEvent(m,N??null,{correlationId:R,aggregateId:R})}catch{}p(R,n.initial,"running")}function x(R,N){if(v||!a.has(R))return;let _=i.get(R)??n.initial;h(R,_,new Error(`cancelled: ${N??"no reason given"}`),N)}function k(R){return i.get(R)}function S(){if(!v){v=!0;for(let R of T)try{R()}catch{}T.length=0}}return{instances:d,audit:d,start:w,cancel:x,getState:k,dispose:S}}var Di={};ke(Di,{CanvasMeasureAdapter:()=>Wu,CliMeasureAdapter:()=>Ku,ImageSizeAdapter:()=>Ju,NodeCanvasMeasureAdapter:()=>zu,PrecomputedAdapter:()=>Hu,SvgBoundsAdapter:()=>Uu,analyzeAndMeasure:()=>Ft,carveTextLineSlots:()=>Iu,circleIntervalForBand:()=>Ef,computeBlockFlow:()=>Rf,computeCharPositions:()=>bi,computeFlowLines:()=>_f,computeLineBreaks:()=>Rn,computeTotalHeight:()=>Sf,layoutNextLine:()=>Lu,measureBlock:()=>kf,measureBlocks:()=>xf,reactiveBlockLayout:()=>Pb,reactiveFlowLayout:()=>Gb,reactiveLayout:()=>Fy,rectIntervalForBand:()=>Nf});var Ku=class{cellPx;constructor(e){this.cellPx=e?.cellPx??8}measureSegment(e,n){return{width:Jn(e)*this.cellPx}}},qu=class extends Error{name="KeyError"},Hu=class{metrics;fallback;constructor(e){this.metrics=e.metrics;let n=e.fallback??"per-char";if(n!=="per-char"&&n!=="error")throw new Error(`fallback must be 'per-char' or 'error', got ${JSON.stringify(e.fallback)}`);this.fallback=n}measureSegment(e,n){let r=this.metrics[n];if(r){let s=r[e];if(s!==void 0)return{width:s}}if(this.fallback==="error")throw new qu(`PrecomputedAdapter: no metrics for segment ${JSON.stringify(e)} in font ${JSON.stringify(n)}`);let o=0;if(r)for(let s of e){let i=r[s];i!==void 0&&(o+=i)}return{width:o}}},Wu=class{ctx=null;currentFont="";emojiCorrection;constructor(e){this.emojiCorrection=e?.emojiCorrection??1}getContext(){if(!this.ctx){if(typeof OffscreenCanvas>"u")throw new Error("CanvasMeasureAdapter requires a browser environment with OffscreenCanvas support. Use CliMeasureAdapter or NodeCanvasMeasureAdapter for Node.js.");let n=new OffscreenCanvas(0,0).getContext("2d");if(!n)throw new Error("CanvasMeasureAdapter: failed to get 2d context");this.ctx=n}return this.ctx}measureSegment(e,n){let r=this.getContext();n!==this.currentFont&&(r.font=n,this.currentFont=n);let o=r.measureText(e).width;return this.emojiCorrection!==1&&new RegExp("\\p{Emoji_Presentation}","u").test(e)&&(o*=this.emojiCorrection),{width:o}}clearCache(){this.currentFont=""}},zu=class{ctx=null;currentFont="";canvasModule;constructor(e){this.canvasModule=e}getContext(){if(!this.ctx){let n=this.canvasModule.createCanvas(0,0).getContext("2d");if(!n)throw new Error("NodeCanvasMeasureAdapter: failed to get 2d context");this.ctx=n}return this.ctx}measureSegment(e,n){let r=this.getContext();return n!==this.currentFont&&(r.font=n,this.currentFont=n),{width:r.measureText(e).width}}clearCache(){this.currentFont=""}},Uu=class{measureSvg(e){let n=e.match(/viewBox\s*=\s*["']([^"']+)["']/);if(n){let s=n[1].trim().split(/[\s,]+/);if(s.length>=4){let i=Number.parseFloat(s[2]),a=Number.parseFloat(s[3]);if(Number.isFinite(i)&&Number.isFinite(a)&&i>0&&a>0)return{width:i,height:a};throw new Error("SvgBoundsAdapter: viewBox width/height are missing, non-finite, or not positive")}}let r=e.match(/<svg[^>]*\bwidth\s*=\s*["']?([\d.]+)/),o=e.match(/<svg[^>]*\bheight\s*=\s*["']?([\d.]+)/);if(r&&o){let s=Number.parseFloat(r[1]),i=Number.parseFloat(o[1]);if(Number.isFinite(s)&&Number.isFinite(i)&&s>0&&i>0)return{width:s,height:i};throw new Error("SvgBoundsAdapter: svg width/height attributes are non-finite or not positive")}throw new Error("SvgBoundsAdapter: cannot determine dimensions \u2014 SVG has no viewBox or width/height attributes")}},Ju=class{sizes;constructor(e){this.sizes=new Map(Object.entries(e))}measureImage(e){let n=this.sizes.get(e);if(!n)throw new Error(`ImageSizeAdapter: no dimensions registered for ${JSON.stringify(e)}`);return{width:n.width,height:n.height}}};xe();_e();ee();function kf(t,e,n,r,o,s,i){switch(t.type){case"text":{let a=t.font??o,u=t.lineHeight??s,d=Ft(t.text,a,n.text,r),c=Rn(d,e,n.text,a,r),l=bi(c,d,u),p=c.lineCount*u,f=0;for(let m of c.lines)m.width>f&&(f=m.width);return{index:i,type:"text",width:Math.min(f,e),height:p,textSegments:d,textLineBreaks:c,textCharPositions:l}}case"image":{let a,u;if(t.naturalWidth!=null&&t.naturalHeight!=null)a=t.naturalWidth,u=t.naturalHeight;else if(n.image){let d=n.image.measureImage(t.src);a=d.width,u=d.height}else throw new Error(`Image block at index ${i} has no naturalWidth/naturalHeight and no ImageMeasurer adapter`);return a>e&&(u=u*e/a,a=e),{index:i,type:"image",width:a,height:u}}case"svg":{let a,u;if(t.viewBox)a=t.viewBox.width,u=t.viewBox.height;else if(n.svg){let d=n.svg.measureSvg(t.content);a=d.width,u=d.height}else throw new Error(`SVG block at index ${i} has no viewBox and no SvgMeasurer adapter`);return a>e&&(u=u*e/a,a=e),{index:i,type:"svg",width:a,height:u}}}}function xf(t,e,n,r,o,s){return t.map((i,a)=>kf(i,e,n,r,o,s,a))}function Rf(t,e){let n=[],r=0;for(let o=0;o<t.length;o++){let s=t[o];n.push({...s,x:0,y:r}),r+=s.height+(o<t.length-1?e:0)}return n}function Sf(t){if(t.length===0)return 0;let e=t[t.length-1];return e.y+e.height}function Pb(t){let{adapters:e,name:n="reactive-block-layout",defaultFont:r="16px sans-serif",defaultLineHeight:o=20}=t,s=new Y(n),i=new Map,a=M(t.blocks??[],{name:"blocks"}),u=M(Math.max(0,t.maxWidth??800),{name:"max-width"}),d=M(t.gap??0,{name:"gap"}),c=z([a,u],(f,m,h)=>{let g=f[0]!=null&&f[0].length>0?f[0].at(-1):h.prevData[0],y=f[1]!=null&&f[1].length>0?f[1].at(-1):h.prevData[1],b=H(),v=xf(g,y,e,i,r,o),T=H()-b,w=c.meta;w&&(mt(w["block-count"],v.length),mt(w["layout-time-ns"],T)),m.emit(v);let x=()=>{i.clear(),e.text.clearCache?.()};return{deactivate:x,invalidate:x}},{name:"measured-blocks",describeKind:"derived",meta:{"block-count":0,"layout-time-ns":0},equals:(f,m)=>{let h=f,g=m;if(h==null||g==null)return h===g;if(h.length!==g.length)return!1;for(let y=0;y<h.length;y++){let b=h[y],v=g[y];if(b.type!==v.type||b.width!==v.width||b.height!==v.height||b.index!==v.index)return!1}return!0}}),l=A([c,d],([f,m])=>Rf(f,m),{name:"block-flow",equals:(f,m)=>{let h=f,g=m;if(h==null||g==null)return h===g;if(h.length!==g.length)return!1;for(let y=0;y<h.length;y++){let b=h[y],v=g[y];if(b.x!==v.x||b.y!==v.y||b.width!==v.width||b.height!==v.height)return!1}return!0}}),p=A([l],([f])=>Sf(f),{name:"total-height"});return s.add(a,{name:"blocks"}),s.add(u,{name:"max-width"}),s.add(d,{name:"gap"}),s.add(c,{name:"measured-blocks"}),s.add(l,{name:"block-flow"}),s.add(p,{name:"total-height"}),{graph:s,setBlocks:f=>s.set("blocks",f),setMaxWidth:f=>s.set("max-width",Math.max(0,f)),setGap:f=>s.set("gap",f),measuredBlocks:c,blockFlow:l,totalHeight:p}}xe();_e();ee();function Ef(t,e,n){let r=t.hPad??0,o=t.vPad??0,s=e-o,i=n+o;if(s>=t.cy+t.r||i<=t.cy-t.r)return null;let a=t.cy>=s&&t.cy<=i?0:t.cy<s?s-t.cy:t.cy-i;if(a>=t.r)return null;let u=Math.sqrt(t.r*t.r-a*a);return{left:t.cx-u-r,right:t.cx+u+r}}function Nf(t,e,n){let r=t.hPad??0,o=t.vPad??0;return n<=t.y-o||e>=t.y+t.h+o?null:{left:t.x-r,right:t.x+t.w+r}}function Db(t,e,n){return t.kind==="circle"?Ef(t,e,n):Nf(t,e,n)}function _f(t,e,n,r,o,s,i){let a=i?.paragraphSpacing??o,u=[],d={segmentIndex:0,graphemeIndex:0};if(t.length===0||n.count<=0||o<=0)return{lines:u,cursor:d};let c=e.paddingX??0,l=e.paddingY??0,p=Math.max(0,e.width-c*2),f=Math.max(0,e.height-l*2),m=n.gap*Math.max(0,n.count-1),h=Math.max(0,(p-m)/n.count);if(h<=0)return{lines:u,cursor:d};e:for(let g=0;g<n.count;g++){let y=c+g*(h+n.gap),b=y+h,v=l;for(;v+o<=l+f;){let T=v+o,w=[];for(let S=0;S<r.length;S++){let R=Db(r[S],v,T);R!==null&&w.push(R)}let x=Iu({left:y,right:b},w,s);if(x.length===0){v+=o;continue}let k=!1;for(let S=0;S<x.length;S++){let R=x[S],N=R.right-R.left,_=Lu(t,d,N);if(_===null)return{lines:u,cursor:d};if(_.text.length===0&&_.width===0){d=_.end,k=!0;break}u.push({x:R.left,y:v,width:_.width,slotWidth:N,text:_.text,columnIndex:g,flushToRight:R.right<b-.5}),d=_.end}if(k){v+=a;continue}if(v+=o,d.segmentIndex>=t.length)break e}if(d.segmentIndex>=t.length)break}return{lines:u,cursor:d}}function Gb(t){let{adapter:e,name:n="reactive-flow-layout",minSlotWidth:r=20}=t,o=new Y(n),s=new Map,i=M(t.text??"",{name:"text"}),a=M(t.font??"16px sans-serif",{name:"font"}),u=M(t.lineHeight??20,{name:"line-height"}),d=M(t.container??{width:800,height:600,paddingX:0,paddingY:0},{name:"container"}),c=M(t.columns??{count:1,gap:0},{name:"columns"}),l=M(t.obstacles??[],{name:"obstacles"}),p=M(t.paragraphSpacing??null,{name:"paragraph-spacing"}),f=z([i,a],(h,g,y)=>{let b=h[0],v=b!=null&&b.length>0?b.at(-1):y.prevData[0],T=h[1],w=T!=null&&T.length>0?T.at(-1):y.prevData[1],x=Ft(v,w,e,s);g.emit(x);let k=()=>{s.clear(),e.clearCache?.()};return{deactivate:k,invalidate:k}},{name:"segments",describeKind:"derived"}),m=A([f,d,c,l,u,p],([h,g,y,b,v,T])=>{let w=h,x=H(),k=T??v,{lines:S,cursor:R}=_f(w,g,y,b,v,r,{paragraphSpacing:k}),N=H()-x,_=Math.max(0,w.length-R.segmentIndex),I=m.meta;return I&&(mt(I["line-count"],S.length),mt(I["layout-time-ns"],N),mt(I["overflow-segments"],_)),S},{name:"flow-lines",meta:{"line-count":0,"layout-time-ns":0,"overflow-segments":0},equals:(h,g)=>{let y=h,b=g;if(y.length!==b.length)return!1;for(let v=0;v<y.length;v++){let T=y[v],w=b[v];if(T.x!==w.x||T.y!==w.y||T.width!==w.width||T.slotWidth!==w.slotWidth||T.text!==w.text||T.columnIndex!==w.columnIndex||T.flushToRight!==w.flushToRight)return!1}return!0}});return o.add(i,{name:"text"}),o.add(a,{name:"font"}),o.add(u,{name:"line-height"}),o.add(d,{name:"container"}),o.add(c,{name:"columns"}),o.add(l,{name:"obstacles"}),o.add(p,{name:"paragraph-spacing"}),o.add(f,{name:"segments"}),o.add(m,{name:"flow-lines"}),{graph:o,setText:h=>o.set("text",h),setFont:h=>o.set("font",h),setLineHeight:h=>o.set("line-height",h),setContainer:h=>o.set("container",h),setColumns:h=>o.set("columns",h),setObstacles:h=>o.set("obstacles",h),setParagraphSpacing:h=>o.set("paragraph-spacing",h),segments:f,flowLines:m}}var Gi={};ke(Gi,{NS_PER_MS:()=>He,NS_PER_SEC:()=>at,resilientPipeline:()=>Fb});Vn();Ot();function Fb(t,e={}){let n=t;e.rateLimit!=null&&(n=qn(n,e.rateLimit)),e.budget!=null&&e.budget.length>0&&(n=Su(n,e.budget));let r;if(e.breaker!=null){let s=wt(e.breaker),i=e.breakerOnOpen??"skip",a=Kn(s,{onOpen:i})(n);n=a.node,r=a.breakerState}if(e.timeoutMs!=null){if(e.timeoutMs<=0)throw new RangeError("timeoutMs must be > 0");if(e.timeoutMs>9e6)throw new RangeError("timeoutMs must be <= 9_000_000 (\u22482.5h) to stay within safe ns arithmetic");n=Wn(n,e.timeoutMs*1e6)}e.retry!=null&&(n=Tt(n,e.retry)),e.fallback!==void 0&&(n=Hn(n,e.fallback));let o=Kt(n,{initialStatus:e.initialStatus??"pending"});return{node:o.node,status:o.status,error:o.error,breakerState:r}}var Wi={};ke(Wi,{SNAPSHOT_WIRE_VERSION:()=>No,SurfaceError:()=>Ne,asSurfaceError:()=>Fi,createGraph:()=>pr,deleteSnapshot:()=>Hi,diffSnapshots:()=>Ki,listSnapshots:()=>qi,restoreSnapshot:()=>Vi,runReduction:()=>$i,saveSnapshot:()=>Bi});var Ne=class extends Error{code;details;constructor(e,n,r){super(n),this.name="SurfaceError",this.code=e,r!==void 0&&(this.details=r)}toJSON(){let e={code:this.code,message:this.message};if(this.details!==void 0){let n=$b(this.details);n!==void 0&&(e.details=n)}return e}};function $b(t){try{return JSON.parse(JSON.stringify(t))}catch{return}}function Fi(t,e="internal-error"){if(t instanceof Ne)return t;let n=t instanceof Error?t.message:String(t);return new Ne(e,n)}function pr(t,e){let n=ur(t);if(!n.valid)throw new Ne("invalid-spec",`GraphSpec validation failed:
|
|
219
|
+
`)}`}function Cb(t){let e=t.width??4,n=t.name??"errorCritique",r=t.maxFailureSamples??5,o=t.formatCritique??Ab;return{name:n,seed(s){return[s]},analyze(s,i){let a=Yd(s),d=typeof t.failureThreshold=="function"?t.failureThreshold(s):t.failureThreshold,u=d===void 0&&!Number.isFinite(a),c=d??a,l=u?[...s].sort((v,T)=>v.score-T.score):s.filter(v=>v.score<c).slice().sort((v,T)=>v.score-T.score),p=l.slice(0,r),{best:f,bestScore:m}=Mf(i,s),h={summary:"",score:a,weakTasks:p.map(v=>v.taskId)},g=o(p,h),y={kind:"errorCritique",best:f,failures:p,critiqueText:g},b=l.length>p.length?` (top ${p.length} retained)`:"";return{summary:`errorCritique iteration: mean=${a.toFixed(3)}, failures=${l.length}${b}/${s.length}, bestScore=${m.toFixed(3)}`,critique:y,weakTasks:p.map(v=>v.taskId),score:a}},async generate(s,i){if(i.length===0)throw new Error("errorCritique.generate: empty candidate batch \u2014 cannot derive prior for teacher");let a=Ob(s.critique)?s.critique:void 0,d=a!==void 0?a.best:i[i.length-1],u=a?.critiqueText??s.summary,c=a?.failures??[],l=0,f={prior:d,critique:u,failures:c,reportCost:m=>{l+=m}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(f)));let m=[];for(let h=0;h<e;h++)m.push(await t.teacher(f));return m}finally{if(t.tokens!=null&&l>0){let m=t.tokens.cache??0;t.tokens.emit(m+l)}}}}}function Lb(t){let{best:e,score:n,status:r}=t,o=Number.isFinite(n)?n.toFixed(3):String(n),s=e??void 0;return r==="converged"?{outcome:"success",detail:`refineLoop converged at score ${o}`,artifact:s}:r==="budget"?{outcome:"partial",detail:`refineLoop hit budget at score ${o}`,artifact:s}:{outcome:"failure",detail:`refineLoop errored (status=${r})`,artifact:s}}function Xd(t){let e=t.name??"refine-executor",n=t.toOutput??Lb;return r=>{let o=rt(r,i=>i!=null,{name:`${e}/gate-in`}),s=ke(o,i=>{let a=Qd(t.seedFrom(i),t.evaluator,t.strategy,{...t.refine,dataset:t.datasetFor(i),name:`${e}/inner`});return C([a.status,a.best,a.score],([d,u,c])=>{let l=d;return l!=="converged"&&l!=="budget"&&l!=="errored"?null:n({best:u,score:c,status:l})},{name:`${e}/output`})},{name:e});return rt(s,i=>i!=null,{name:`${e}/gate-out`})}}function Ib(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let n of t)e+=n.score;return e/t.length}function Pb(t){let{passCount:e,total:n,meanScore:r,threshold:o,missingArtifact:s}=t,i=Number.isFinite(r)?r.toFixed(3):String(r),a=!s&&n>0&&r>=o,d=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:d}:{verified:!1,findings:d,errorClass:"structural"}}function Db(t){return t.artifact??null}function Of(t){let e=t.name??"eval-verifier",n=t.threshold??.5,r=t.toOutput??Pb,o=t.extractArtifact??Db;return s=>{let i=rt(s,d=>d!=null&&d[0]!=null&&d[1]!=null,{name:`${e}/gate-in`}),a=ke(i,d=>{let[u,c]=d,l=o(u,c);if(l==null)return A(r({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:n,missingArtifact:!0}));let p=A([l],{name:`${e}/candidates`}),f=A(t.datasetFor(c),{name:`${e}/dataset`}),m=t.evaluator(p,f);return C([m],([h])=>{let g=h;if(g==null)return null;let y=Ib(g),b=g.filter(v=>v.score>=n).length;return r({scores:g,meanScore:y,passCount:b,total:g.length,threshold:n})},{name:`${e}/output`})},{name:e});return rt(a,d=>d!=null,{name:`${e}/gate-out`})}}function Gb(t){let e=t.name??"harness-pair",n=Xd({name:`${e}-exec`,seedFrom:t.seedFrom,evaluator:t.evaluator,strategy:t.strategy,datasetFor:t.datasetFor,refine:t.refine}),r=Of({name:`${e}-verify`,evaluator:t.evaluator,datasetFor:t.datasetFor,threshold:t.threshold});return{executor:n,verifier:r}}Re();it();Me();ne();var Fi={};Se(Fi,{JobFlowGraph:()=>Di,JobQueueGraph:()=>Pi,jobEventKeyOf:()=>jb,jobFlow:()=>Bb,jobQueue:()=>Gi});Re();Me();ve();var Fb=256,$b=1024;function Af(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Ii(t,e){return We("job_queue",t,e)}var jb=t=>t.action,Pi=class extends Q{_pending;_jobs;_seqCursor;pending;jobs;depth;events;audit;constructor(e,n={}){super(e,n.graph),this._pending=Ks([],{name:"pending"}),this._jobs=je({name:"jobs"}),this.pending=this._pending.items,this.jobs=this._jobs.entries,this.add(this.pending,{name:"pending"}),this.add(this.jobs,{name:"jobs"}),this.depth=C([this.pending],([r])=>r.length,{name:"depth",describeKind:"derived",meta:Ii("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(te(this.depth)),this.events=at({name:"events",retainedLimit:1024,graph:this}),this.audit=this.events,this._seqCursor=Yt(this,"seq",0)}_bumpSeq(){let n=(this._seqCursor.cache??0)+1;return this._seqCursor.emit(n),n}attachEventStorage(e){return this.events.attachStorage(e)}enqueue(e,n={}){let r=this._bumpSeq(),o=n.id??`${this.name}-${r}`;if(this._jobs.get(o)!==void 0)throw new Error(`jobQueue("${this.name}"): duplicate job id "${o}"`);let s={id:o,payload:e,attempts:0,metadata:Object.freeze({...n.metadata??{}}),state:"queued"};return this._jobs.set(o,s),this._pending.append(o),this.events.append({action:"enqueue",id:o,payload:e,t_ns:se(),seq:r}),o}claim(e=1){let n=Af(e,"job queue claim limit");if(n===0)return[];let r=[];for(;r.length<n&&this.pending.cache.length!==0;){let s=this._pending.pop(0),i=this._jobs.get(s);if(!i||i.state!=="queued")continue;let a={...i,state:"inflight",attempts:i.attempts+1};this._jobs.set(s,a),r.push(a),this.events.append({action:"claim",id:s,attempts:a.attempts,t_ns:se(),seq:this._bumpSeq()})}return r}ack(e){let n=this._jobs.get(e);return!n||n.state!=="inflight"?!1:(this._jobs.delete(e),this.events.append({action:"ack",id:e,attempts:n.attempts,t_ns:se(),seq:this._bumpSeq()}),!0)}nack(e,n={}){let r=this._jobs.get(e);return!r||r.state!=="inflight"?!1:n.requeue??!0?(this._jobs.set(e,{...r,state:"queued"}),this._pending.append(e),this.events.append({action:"nack",id:e,attempts:r.attempts,t_ns:se(),seq:this._bumpSeq()}),!0):(this._jobs.delete(e),this.events.append({action:"nack",id:e,attempts:r.attempts,t_ns:se(),seq:this._bumpSeq()}),!0)}removeById(e){let n=this._jobs.get(e);if(!n)return!1;if(n.state==="queued"){let o=this.pending.cache.indexOf(e);o>=0&&this._pending.pop(o)}return this._jobs.delete(e),this.events.append({action:"remove",id:e,attempts:n.attempts,t_ns:se(),seq:this._bumpSeq()}),!0}consumeFrom(e,n){return e.subscribe(r=>{for(let o of r){if(o[0]!==M)continue;let s=o[1];this.enqueue(s,n?{metadata:n.metadata}:void 0)}})}},Di=class extends Q{_stageNames;_stageWorkFns;_queues=new Map;_completed;completed;completedCount;constructor(e,n={}){super(e,n.graph);let r=n.stages??["incoming","processing","done"],o=[],s=new Map;for(let d of r){let u=typeof d=="string"?d.trim():d.name.trim();typeof d!="string"&&d.work&&s.set(u,d.work),o.push(u)}if(o.length<2)throw new Error(`jobFlow("${e}"): requires at least 2 stages`);if(new Set(o).size!==o.length)throw new Error(`jobFlow("${e}"): stage names must be unique`);this._stageNames=Object.freeze([...o]),this._stageWorkFns=s;for(let d of this._stageNames){let u=Gi(`${e}-${d}`);this._queues.set(d,u),this.mount(d,u)}this._completed=Ke([],{name:"completed",maxSize:$b}),this.completed=this._completed.entries,this.add(this.completed,{name:"completed"}),this.completedCount=C([this.completed],([d])=>d.length,{name:"completedCount",describeKind:"derived",meta:Ii("job_flow_completed_count"),initial:0}),this.add(this.completedCount,{name:"completedCount"}),this.addDisposer(te(this.completedCount));let a=Math.max(1,Af(n.maxPerPump??Fb,"job flow maxPerPump"));for(let d=0;d<this._stageNames.length;d+=1){let u=this._stageNames[d],c=this.queue(u),l=d+1<this._stageNames.length?this.queue(this._stageNames[d+1]):null,p=this._stageWorkFns.get(u),f=l===null;if(p){let m=U([c.pending],()=>{let h=0;for(;h<a;){let g=c.claim(1);if(g.length===0)break;let y=g[0];if(!y)break;let v=[...y.metadata.job_flow_path??[],u],T;try{T=p(y)}catch{c.nack(y.id,{requeue:!1}),h+=1;continue}let w=Y(T),x=!1,k;k=w.subscribe(S=>{if(!x){for(let R of S)if(R[0]===M){x=!0,k?k():Promise.resolve().then(()=>k?.());let E=R[1],_={...y.metadata,job_flow_path:v};if(f){let O={...y,payload:E,metadata:Object.freeze(_)};Z(()=>{c.ack(y.id),this._completed.append(O)})}else Z(()=>{c.ack(y.id),l.enqueue(E,{metadata:_})});return}else if(R[0]===I){x=!0,k?k():Promise.resolve().then(()=>k?.()),c.nack(y.id,{requeue:!1});return}}}),h+=1}},{name:`pump_${u}`,describeKind:"effect",meta:Ii("job_flow_pump",{stage:u,has_work:!0})});this.add(m,{name:`pump_${u}`}),this.addDisposer(te(m))}else{let m=U([c.pending],()=>{let h=0;for(;h<a;){let g=c.claim(1);if(g.length===0)break;let y=g[0];if(!y)break;let v=[...y.metadata.job_flow_path??[],u],T={...y.metadata,job_flow_path:v};if(f){let w={...y,metadata:Object.freeze(T)};Z(()=>{c.ack(y.id),this._completed.append(w)})}else Z(()=>{c.ack(y.id),l.enqueue(y.payload,{metadata:T})});h+=1}},{name:`pump_${u}`,describeKind:"effect",meta:Ii("job_flow_pump",{stage:u,has_work:!1})});this.add(m,{name:`pump_${u}`}),this.addDisposer(te(m))}}}stages(){return this._stageNames}queue(e){let n=this._queues.get(e);if(!n)throw new Error(`jobFlow("${this.name}"): unknown stage "${e}"`);return n}enqueue(e,n={}){return this.queue(this._stageNames[0]).enqueue(e,n)}retainedCompleted(){return this.completed.cache}};function Gi(t,e){return new Pi(t,e)}function Bb(t,e){let n=new Di(t,e),{factory:r,factoryArgs:o,...s}=e??{};return n.tagFactory("jobFlow",st(s)),n}Re();ne();function Zd(){let t=je({name:"strategy-entries"}),e=C([t.entries],([i])=>{let a=i;return new Map(a)},{name:"strategy-model",equals:(i,a)=>{let d=i,u=a;if(d.size!==u.size)return!1;for(let[c,l]of d){let p=u.get(c);if(!p||l.attempts!==p.attempts||l.successes!==p.successes)return!1}return!0}});function n(i,a,d){let u=br(i,a),c=t.get(u),l=(c?.attempts??0)+1,p=(c?.successes??0)+(d?1:0);t.set(u,{rootCause:i,intervention:a,attempts:l,successes:p,successRate:p/l})}function r(i,a){return t.get(br(i,a))}let o=e.subscribe(()=>{});function s(){o()}return{node:e,record:n,lookup:r,dispose:s}}function Vb(t,e,n,r,o){let s={...hr,...o?.severityWeights},i=o?.decayRate??yr,a=o?.effectivenessThreshold??.7,d=o?.effectivenessBoost??15,u=[t,e,n];return r&&u.push(r),C(u,c=>{let l=c[0],p=c[1],f=c[2],m=r?c[3]:0,h=s[l.severity??"medium"],g=(V()-f)/1e9,y=En(h,g,i,0),b=br(l.rootCause,l.intervention),v=p.get(b);return v&&v.successRate>=a&&(y+=d),y+=m*20,y},{name:"priority-score"})}var Cf="intake",Kb="triage-output",Lf="retry",If="verify-results",Pf="__unrouted";function Df(t,e){let n=Ao(e,Ud,(r,o)=>r.replace("{{item}}",JSON.stringify(o)));return r=>Sn(t,[r],n,{name:"execute",format:"json"})}function Gf(t,e){let n=Ao(e,Jd,(r,o)=>{let[s,i]=o;return r.replace("{{execution}}",JSON.stringify(s)).replace("{{item}}",JSON.stringify(i))});return r=>Sn(t,[r],o=>o==null?"":n(o),{name:"verify",format:"json"})}var $i=class extends Q{queues;jobs;gates;queueTopics;strategy;totalRetries;totalReingestions;priorityScores;constructor(e,n,r,o,s,i,a,d,u){super(e),this.queues=n,this.queueTopics=r,this.jobs=o,this.gates=s,this.strategy=i,this.totalRetries=a,this.totalReingestions=d,this.priorityScores=u}get intake(){return this.queues.topic(Cf)}get verifyResults(){return this.queues.topic(If)}get retry(){return this.queues.topic(Lf)}get unrouted(){return this.queues.topic(Pf)}stageNodes(){let e=this.queues,n=i=>e.has(i)?`queues::${i}::latest`:null,r=i=>i==null?[]:[i],o=ct.flatMap(i=>r(n(i))),s=[];for(let[i]of this.gates)s.push(`gates::${i}/gate`);return[{label:"INTAKE",paths:r(n("intake"))},{label:"TRIAGE",paths:["triage"]},{label:"QUEUE",paths:o},{label:"GATE",paths:s},{label:"EXECUTE",paths:["execute"]},{label:"VERIFY",paths:r(n("verify-results"))},{label:"REFLECT",paths:["reflect"]},{label:"STRATEGY",paths:["strategy"]}]}};function qb(t,e){let n=e.adapter,r=e.maxRetries??2,o=e.retainedLimit??1e3,s=e.errorClassifier??Ci,i=new Map;for(let X of ct)i.set(X,{...Ai[X],...e.queues?.[X]});let a=ko(`${t}/queues`,{defaultTopicOptions:{retainedLimit:o}}),d=a.topic(Cf),u=a.topic(Kb),c=a.topic(Lf),l=a.topic(If),p=new Map;for(let X of ct)p.set(X,a.topic(X));let f=a.topic(Pf),m=Zd(),h=Ft(d.latest,m.node),g=Ao(e.triagePrompt,Wd,(X,ie)=>{let[xe,W]=ie;return X.replace("{{strategy}}",JSON.stringify(Array.from(W.entries()))).replace("{{item}}",JSON.stringify(xe))}),y=Sn(n,[h],X=>{let ie=X;return!ie||!ie[0]?"":g(ie)},{name:"triage",format:"json"}),b=Ft(y,h),T=ge([b],([X])=>{if(X==null)return;let[ie,xe]=X;if(!ie?.route)return;let W=xe?.[0],fe={...ie,...W};u.publish(fe)}).subscribe(()=>{}),w=new Set(ct);for(let X of ct)ci(`bridge/${X}`,u,p.get(X),{map:ie=>ie.route===X?ie:void 0});ci("bridge/__unrouted",u,f,{map:X=>w.has(X.route)?void 0:X});let x=new Map,k=new Map;for(let X of ct)x.set(X,Gi(`jobs/${X}`));let S=[];for(let X of ct){let ie=p.get(X),xe=x.get(X),W=new WeakSet,fe=ge([ie.events],([Ne])=>{let Ee=Ne??[];for(let me of Ee){if(W.has(me))continue;W.add(me);let De=xe.enqueue(me);k.set(Qr(me),{route:X,id:De})}},{name:`jobs/${X}-mirror`});S.push(fe.subscribe(()=>{}))}function R(X){let ie=Qr(X),xe=k.get(ie);xe&&(x.get(xe.route)?.removeById(xe.id),k.delete(ie))}let E=pr("gates"),_=new Map;for(let X of ct){let ie=i.get(X);if(!ie.gated)continue;let xe=p.get(X),W=E.gate(`${X}/gate`,xe.latest,{maxPending:ie.maxPending,startOpen:ie.startOpen});_.set(X,W)}let O=[];for(let X of ct)i.get(X).gated&&_.has(X)?O.push(_.get(X).node):O.push(p.get(X).latest);O.push(c.latest);let N=Et(...O),j=(e.executor??Df(n,e.executePrompt))(N),$=Ft(j,N),K=(e.verifier??Gf(n,e.verifyPrompt))($),F=Ft(K,$),H=e.maxReingestions??1,G=Math.min(e.maxTotalRetries??r*10,100),B=Math.min(e.maxTotalReingestions??H*10,100),re=A(0),pe=A(0);function ee(X,ie,xe){let W={item:xe,outcome:ie?.outcome??"failure",detail:ie?.detail??"unknown",artifact:ie?.artifact};return{item:xe,execution:W,verified:X.verified,findings:X.findings??[],errorClass:X.errorClass}}function ue(X,ie){m.record(ie.rootCause,ie.intervention,!0),l.publish(X),R(ie)}function Ce(X,ie){let xe=Qr(ie),W=ie.$retries??0,fe={...ie,$retries:W+1,summary:`[RETRY ${W+1}/${r}] ${xe} \u2014 Previous attempt failed: ${X.findings.join("; ")}`,relatedTo:[xe]};c.publish(fe)}function Ye(X,ie){m.record(ie.rootCause,ie.intervention,!1),l.publish(X),R(ie);let xe=Qr(ie),W=ie.$reingestions??0;W<H&&Yr(pe,B)&&d.publish({source:ie.source,summary:`Verification failed for: ${xe}`,evidence:X.findings.join(`
|
|
220
|
+
`),affectsAreas:ie.affectsAreas,affectsEvalTasks:ie.affectsEvalTasks,severity:ie.severity??"high",relatedTo:[xe],$reingestions:W+1})}let Be=U([F],(X,ie)=>{let xe=X[0];if(xe==null||xe.length===0)return;let W=xe[xe.length-1];if(W==null)return;let[fe,Ne]=W,[Ee,me]=Ne??[null,null];if(!fe||!me)return;if(Ee==null){Ye({item:me,execution:{item:me,outcome:"failure",detail:"executor returned null"},verified:!1,findings:["executor returned null"],errorClass:"structural"},me);return}let De=ee(fe,Ee,me);if(De.verified){ue(De,me);return}let ye=De.errorClass??s({item:me,outcome:Ee.outcome,detail:De.findings.join("; ")}),be=me.$retries??0;ye==="self-correctable"&&be<r&&Yr(re,G)?Ce(De,me):Ye(De,me)}),J=Be.subscribe(()=>{}),de=C([Be],()=>null,{name:"reflect",equals:()=>!1}),Le;e.priority&&(Le=zb(p,m,e));let Te=new $i(t,a,p,x,_,m,re,pe,Le);Te.addDisposer(T),Te.addDisposer(J),Te.addDisposer(m.dispose);for(let X of S)Te.addDisposer(X);if(Te.add(y,{name:"triage"}),Te.add(N,{name:"execute-input"}),Te.add(j,{name:"execute"}),Te.add($,{name:"execute-context"}),Te.add(K,{name:"verify"}),Te.add(F,{name:"verify-context"}),Te.add(Be,{name:"verify-dispatch"}),Te.add(de,{name:"reflect"}),Te.add(m.node,{name:"strategy"}),Te.addDisposer(de.subscribe(()=>{})),Le)for(let[X,ie]of Le)Te.add(ie,{name:`priority/${X}`}),Te.addDisposer(ie.subscribe(()=>{}));Te.mount("queues",a),Te.mount("gates",E);for(let[X,ie]of x)Te.mount(`jobs/${X}`,ie);return Te.tagFactory("harnessLoop",st(e)),Te}function zb(t,e,n){if(!n.lastInteractionNs)throw new Error("harnessLoop: `opts.priority` requires `opts.lastInteractionNs` \u2014 pass a Node<number> (e.g. `fromTimer(60_000)` or a `state(monotonicNs())` you bump on human interaction). Priority scores only decay when this node settles; an internal default would freeze age at construction time.");let r=n.lastInteractionNs,o=n.priority??{},s={...hr,...o.severityWeights},i=o.decayRate??yr,a=o.effectivenessThreshold??.7,d=o.effectivenessBoost??15,u=new Map;for(let[c,l]of t){let p=C([l.latest,e.node,r],f=>{let m=f[0];if(m==null)return 0;let h=s[m.severity??"medium"]??40,g=(V()-f[2])/1e9,y=h*Math.exp(-i*Math.max(0,g)),b=`${m.rootCause}\u2192${m.intervention}`,T=f[1]?.get(b);return T&&T.successRate>=a&&(y+=d),y},{name:`priority/${c}`});u.set(c,p)}return u}function Hb(t,e){let n=hn(t,e),r={};for(let o of ct){let s=t.queues.has(o)?t.queues.topic(o):null;r[o]=s?.retained().length??0}return{...n,queueDepths:r,strategyEntries:t.strategy.node.cache?.size??0,totalRetries:t.totalRetries.cache??0,totalReingestions:t.totalReingestions.cache??0}}Re();function Wb(t){let e={};for(let{label:n,paths:r}of t.stageNodes())for(let o of r)e[o]=n;return e}function Ub(t,e){let n=e?.logger===null?null:e?.logger??console.log,r=e?.detail??"summary",o=V(),s=[],i=[],a=Wb(t);function d(){return(V()-o)/1e9}function u(c,l,p){let f={elapsed:d(),stage:c,type:l};r!=="summary"&&(f.summary=Jb(p)),r==="full"&&(f.data=p),i.push(f)}for(let[c,l]of Object.entries(a))try{let p=t.observe(c,{format:"stage-log",stageLabels:a,logger:n?f=>n(f):()=>{},includeTypes:["data","error","complete"]});p.onEvent(f=>{f.type==="data"?u(l,"data",f.data):f.type==="error"?u(l,"error",f.data):f.type==="complete"&&u(l,"complete",void 0)}),s.push(p)}catch(p){let f=p instanceof Error?p.message:String(p);u(l,"error",`observe-unavailable: ${c} \u2014 ${f}`),n&&n(`[${d().toFixed(3)}s] ${l.padEnd(9)} \u2717 observe-unavailable: ${f}`)}return{get events(){return i},dispose(){for(let c of s)c.dispose();s.length=0}}}function Jb(t){if(t==null)return"null";if(typeof t=="string")return Ff(t,80);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return Ff(e,120)}catch{return String(t)}}function Ff(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}var Vi={};Se(Vi,{LensGraph:()=>Bi,graphLens:()=>ev,watchTopologyTree:()=>Pt});Re();ne();function $f(t){return We("lens",t)}function Yb(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,d=1,u=2,c=new Map;for(let h of e)c.set(h,a);let l=!1,p=new Map,f=h=>{let g=c.get(h)??a;if(g===d)return l=!0,0;if(g===u)return p.get(h)??0;c.set(h,d);let y=0,b=r.get(h);if(b!=null)for(let v of b){let T=f(v);T+1>y&&(y=T+1)}return c.set(h,u),p.set(h,y),y},m=0;for(let h of o){let g=f(h);g>m&&(m=g)}for(let h of e)c.get(h)===a&&f(h);return{nodeCount:e.length,edgeCount:i,subgraphCount:t.subgraphs.length,sources:o,sinks:s,depth:m,hasCycles:l}}function Qb(t){let e=[];for(let[n,r]of Object.entries(t.nodes)){if(r.status!=="errored")continue;let o={path:n,status:"errored"},s=yn(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 Xb(t,e){return t.nodeCount===e.nodeCount&&t.edgeCount===e.edgeCount&&t.subgraphCount===e.subgraphCount&&t.depth===e.depth&&t.hasCycles===e.hasCycles&&jf(t.sources,e.sources)&&jf(t.sinks,e.sinks)}function Zb(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 jf(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 Bi=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=A(0,{name:"stats_tick"}),i=A(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=je(a),this.add(this.flow.entries,{name:"flow"});let d=n.pathFilter,u=Pt(e,(p,f,m)=>{if(r+=1,s.emit(r),o+=1,i.emit(o),p.kind==="removed")if(p.nodeKind==="node"){let h=`${m}${p.name}`;this.flow.delete(h)}else{let h=`${m}${p.name}::`,g=[];for(let y of p.audit.nodes){let b=y===""?`${m}${p.name}`:`${h}${y}`;g.push(b)}g.length>0&&this.flow.deleteMany(g)}});this.addDisposer(u);let c=e.observe({timeline:!0,structured:!0}),l=c.onEvent(p=>{let f=p.type;if((f==="error"||f==="complete"||f==="data"||f==="teardown")&&(o+=1,i.emit(o)),f==="data"){let m=p.path??"";if(!m||d!=null&&!d(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(),c.dispose()}),this.stats=C([s],()=>Yb(e.describe({detail:"minimal"})),{name:"stats",describeKind:"derived",equals:Xb,meta:$f("stats")}),this.add(this.stats,{name:"stats"}),this.addDisposer(te(this.stats)),this.health=C([i],()=>Qb(e.describe({detail:"standard"})),{name:"health",describeKind:"derived",equals:Zb,meta:$f("health")}),this.add(this.health,{name:"health"}),this.addDisposer(te(this.health))}why(e,n,r){let o=Bd(this._target,e,n,r);return this.addDisposer(o.dispose),o}get target(){return this._target}};function ev(t,e){return new Bi(t,e)}var Ki={};Se(Ki,{processInstanceKeyOf:()=>tv,processManager:()=>rv});Re();ae();ve();var tv=t=>t.correlationId;function Bf(t){if(t==null)return Promise.resolve(void 0);let e=Y(t);return new Promise((n,r)=>{let o=!1,s,i=()=>{s&&s()};s=e.subscribe(a=>{if(!o)for(let d of a){if(d[0]===M){o=!0,Promise.resolve().then(i),n(d[1]);return}if(d[0]===I){o=!0,Promise.resolve().then(i),r(d[1]);return}if(d[0]===P){o=!0,Promise.resolve().then(i),n(void 0);return}}})})}async function nv(t,e,n,r,o){let s;for(let i=0;i<=r;i++){if(i>0){let a=o[Math.min(i-1,o.length-1)]??0;a>0&&await new Promise(d=>setTimeout(d,a))}try{return await Bf(t(e,n))}catch(a){s=a}}return{kind:"fail",error:s}}function rv(t,e,n){let r=n.retryMax??0,o=n.backoffMs??[0],s=1024,i=new Map,a=new Set,d=new Map,u=at({name:`${e}_process_instances`,retainedLimit:s,graph:t}),c=0;function l(){return++c}function p(R,E,_){f(R,E,_,void 0)}function f(R,E,_,O){let N=se(),L={correlationId:R,state:E,status:_,startedAt:d.get(R)??N,updatedAt:N,t_ns:N,seq:l(),...n.handlerVersion!==void 0?{handlerVersion:n.handlerVersion}:{},...O!==void 0?{reason:O}:{}};u.append(L)}let m=`_process_${e}_started`;t.event(m),n.persistence?.eventStorage&&t.attachEventStorage(n.persistence.eventStorage);async function h(R,E,_,O){if(a.delete(R),i.delete(R),d.delete(R),n.compensate)try{await Bf(n.compensate(E,_)),f(R,E,"compensated",O)}catch{p(R,E,"failed")}else p(R,E,"failed")}async function g(R,E){if(a.has(R)){if(E.kind==="fail"){let _=i.get(R)??n.initial;await h(R,_,E.error);return}if(E.kind==="continue"){if(i.set(R,E.state),E.emit)for(let _ of E.emit)try{t._appendEvent(_.type,_.payload,{correlationId:R,aggregateId:R})}catch{}if(p(R,E.state,"running"),n.isTerminal?.(E.state)){a.delete(R),i.delete(R),d.delete(R),p(R,E.state,"terminated");return}if(E.schedule){let{afterMs:_,eventType:O}=E.schedule,N,L=Ze(_),j=$=>{for(let D of $)if(D[0]===M){if(N?N():queueMicrotask(()=>N?.()),!a.has(R))return;let K=i.get(R);if(K===void 0)return;let F=n.steps[O];if(!F)return;let H={type:O,payload:null,timestampNs:se(),seq:Number.NaN,correlationId:R,aggregateId:R};b(R,F,K,H)}};N=L.subscribe(j)}return}if(E.kind==="terminate"){if(i.set(R,E.state),E.emit)for(let _ of E.emit)try{t._appendEvent(_.type,_.payload,{correlationId:R,aggregateId:R})}catch{}a.delete(R),i.delete(R),d.delete(R),p(R,E.state,"terminated")}}}let y=new Map;function b(R,E,_,O){let L=(y.get(R)??Promise.resolve()).then(async()=>{let j=i.get(R);if(j===void 0||!a.has(R))return;let $;try{$=await nv(E,j,O,r,o)}catch(D){await h(R,i.get(R)??n.initial,D);return}await g(R,$)});y.set(R,L),L.finally(()=>{y.get(R)===L&&y.delete(R)})}let v=!1,T=[];for(let R of n.watching){let E=t.event(R),_=0;_=(E.cache??[]).length;let N=E.subscribe(L=>{for(let j of L){if(j[0]!==M)continue;let $=j[1];if($.length<=_)continue;let D=$.slice(_);_=$.length;for(let K of D){let F=K.correlationId;if(F===void 0||!a.has(F))continue;let H=n.steps[R];if(!H)continue;let G=i.get(F);G!==void 0&&b(F,H,G,K)}}});T.push(N)}function w(R,E){if(v||a.has(R))return;let _=se();d.set(R,_),i.set(R,n.initial),a.add(R);try{t._appendEvent(m,E??null,{correlationId:R,aggregateId:R})}catch{}p(R,n.initial,"running")}function x(R,E){if(v||!a.has(R))return;let _=i.get(R)??n.initial;h(R,_,new Error(`cancelled: ${E??"no reason given"}`),E)}function k(R){return i.get(R)}function S(){if(!v){v=!0;for(let R of T)try{R()}catch{}T.length=0}}return{instances:u,audit:u,start:w,cancel:x,getState:k,dispose:S}}var qi={};Se(qi,{CanvasMeasureAdapter:()=>ru,CliMeasureAdapter:()=>eu,ImageSizeAdapter:()=>iu,NodeCanvasMeasureAdapter:()=>ou,PrecomputedAdapter:()=>nu,SvgBoundsAdapter:()=>su,analyzeAndMeasure:()=>Bt,carveTextLineSlots:()=>zd,circleIntervalForBand:()=>Hf,computeBlockFlow:()=>qf,computeCharPositions:()=>Ni,computeFlowLines:()=>Uf,computeLineBreaks:()=>_n,computeTotalHeight:()=>zf,layoutNextLine:()=>qd,measureBlock:()=>Vf,measureBlocks:()=>Kf,reactiveBlockLayout:()=>ov,reactiveFlowLayout:()=>iv,reactiveLayout:()=>ab,rectIntervalForBand:()=>Wf});var eu=class{cellPx;constructor(e){this.cellPx=e?.cellPx??8}measureSegment(e,n){return{width:tr(e)*this.cellPx}}},tu=class extends Error{name="KeyError"},nu=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 tu(`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}}},ru=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=""}},ou=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=""}},su=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")}},iu=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}}};Re();Me();ne();function Vf(t,e,n,r,o,s,i){switch(t.type){case"text":{let a=t.font??o,d=t.lineHeight??s,u=Bt(t.text,a,n.text,r),c=_n(u,e,n.text,a,r),l=Ni(c,u,d),p=c.lineCount*d,f=0;for(let m of c.lines)m.width>f&&(f=m.width);return{index:i,type:"text",width:Math.min(f,e),height:p,textSegments:u,textLineBreaks:c,textCharPositions:l}}case"image":{let a,d;if(t.naturalWidth!=null&&t.naturalHeight!=null)a=t.naturalWidth,d=t.naturalHeight;else if(n.image){let u=n.image.measureImage(t.src);a=u.width,d=u.height}else throw new Error(`Image block at index ${i} has no naturalWidth/naturalHeight and no ImageMeasurer adapter`);return a>e&&(d=d*e/a,a=e),{index:i,type:"image",width:a,height:d}}case"svg":{let a,d;if(t.viewBox)a=t.viewBox.width,d=t.viewBox.height;else if(n.svg){let u=n.svg.measureSvg(t.content);a=u.width,d=u.height}else throw new Error(`SVG block at index ${i} has no viewBox and no SvgMeasurer adapter`);return a>e&&(d=d*e/a,a=e),{index:i,type:"svg",width:a,height:d}}}}function Kf(t,e,n,r,o,s){return t.map((i,a)=>Vf(i,e,n,r,o,s,a))}function qf(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 zf(t){if(t.length===0)return 0;let e=t[t.length-1];return e.y+e.height}function ov(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=A(t.blocks??[],{name:"blocks"}),d=A(Math.max(0,t.maxWidth??800),{name:"max-width"}),u=A(t.gap??0,{name:"gap"}),c=U([a,d],(f,m,h)=>{let g=f[0]!=null&&f[0].length>0?f[0].at(-1):h.prevData[0],y=f[1]!=null&&f[1].length>0?f[1].at(-1):h.prevData[1],b=V(),v=Kf(g,y,e,i,r,o),T=V()-b,w=c.meta;w&&(vt(w["block-count"],v.length),vt(w["layout-time-ns"],T)),m.emit(v);let x=()=>{i.clear(),e.text.clearCache?.()};return{deactivate:x,invalidate:x}},{name:"measured-blocks",describeKind:"derived",meta:{"block-count":0,"layout-time-ns":0},equals:(f,m)=>{let h=f,g=m;if(h==null||g==null)return h===g;if(h.length!==g.length)return!1;for(let y=0;y<h.length;y++){let b=h[y],v=g[y];if(b.type!==v.type||b.width!==v.width||b.height!==v.height||b.index!==v.index)return!1}return!0}}),l=C([c,u],([f,m])=>qf(f,m),{name:"block-flow",equals:(f,m)=>{let h=f,g=m;if(h==null||g==null)return h===g;if(h.length!==g.length)return!1;for(let y=0;y<h.length;y++){let b=h[y],v=g[y];if(b.x!==v.x||b.y!==v.y||b.width!==v.width||b.height!==v.height)return!1}return!0}}),p=C([l],([f])=>zf(f),{name:"total-height"});return s.add(a,{name:"blocks"}),s.add(d,{name:"max-width"}),s.add(u,{name:"gap"}),s.add(c,{name:"measured-blocks"}),s.add(l,{name:"block-flow"}),s.add(p,{name:"total-height"}),{graph:s,setBlocks:f=>s.set("blocks",f),setMaxWidth:f=>s.set("max-width",Math.max(0,f)),setGap:f=>s.set("gap",f),measuredBlocks:c,blockFlow:l,totalHeight:p}}Re();Me();ne();function Hf(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 d=Math.sqrt(t.r*t.r-a*a);return{left:t.cx-d-r,right:t.cx+d+r}}function Wf(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 sv(t,e,n){return t.kind==="circle"?Hf(t,e,n):Wf(t,e,n)}function Uf(t,e,n,r,o,s,i){let a=i?.paragraphSpacing??o,d=[],u={segmentIndex:0,graphemeIndex:0};if(t.length===0||n.count<=0||o<=0)return{lines:d,cursor:u};let c=e.paddingX??0,l=e.paddingY??0,p=Math.max(0,e.width-c*2),f=Math.max(0,e.height-l*2),m=n.gap*Math.max(0,n.count-1),h=Math.max(0,(p-m)/n.count);if(h<=0)return{lines:d,cursor:u};e:for(let g=0;g<n.count;g++){let y=c+g*(h+n.gap),b=y+h,v=l;for(;v+o<=l+f;){let T=v+o,w=[];for(let S=0;S<r.length;S++){let R=sv(r[S],v,T);R!==null&&w.push(R)}let x=zd({left:y,right:b},w,s);if(x.length===0){v+=o;continue}let k=!1;for(let S=0;S<x.length;S++){let R=x[S],E=R.right-R.left,_=qd(t,u,E);if(_===null)return{lines:d,cursor:u};if(_.text.length===0&&_.width===0){u=_.end,k=!0;break}d.push({x:R.left,y:v,width:_.width,slotWidth:E,text:_.text,columnIndex:g,flushToRight:R.right<b-.5}),u=_.end}if(k){v+=a;continue}if(v+=o,u.segmentIndex>=t.length)break e}if(u.segmentIndex>=t.length)break}return{lines:d,cursor:u}}function iv(t){let{adapter:e,name:n="reactive-flow-layout",minSlotWidth:r=20}=t,o=new Q(n),s=new Map,i=A(t.text??"",{name:"text"}),a=A(t.font??"16px sans-serif",{name:"font"}),d=A(t.lineHeight??20,{name:"line-height"}),u=A(t.container??{width:800,height:600,paddingX:0,paddingY:0},{name:"container"}),c=A(t.columns??{count:1,gap:0},{name:"columns"}),l=A(t.obstacles??[],{name:"obstacles"}),p=A(t.paragraphSpacing??null,{name:"paragraph-spacing"}),f=U([i,a],(h,g,y)=>{let b=h[0],v=b!=null&&b.length>0?b.at(-1):y.prevData[0],T=h[1],w=T!=null&&T.length>0?T.at(-1):y.prevData[1],x=Bt(v,w,e,s);g.emit(x);let k=()=>{s.clear(),e.clearCache?.()};return{deactivate:k,invalidate:k}},{name:"segments",describeKind:"derived"}),m=C([f,u,c,l,d,p],([h,g,y,b,v,T])=>{let w=h,x=V(),k=T??v,{lines:S,cursor:R}=Uf(w,g,y,b,v,r,{paragraphSpacing:k}),E=V()-x,_=Math.max(0,w.length-R.segmentIndex),O=m.meta;return O&&(vt(O["line-count"],S.length),vt(O["layout-time-ns"],E),vt(O["overflow-segments"],_)),S},{name:"flow-lines",meta:{"line-count":0,"layout-time-ns":0,"overflow-segments":0},equals:(h,g)=>{let y=h,b=g;if(y.length!==b.length)return!1;for(let v=0;v<y.length;v++){let T=y[v],w=b[v];if(T.x!==w.x||T.y!==w.y||T.width!==w.width||T.slotWidth!==w.slotWidth||T.text!==w.text||T.columnIndex!==w.columnIndex||T.flushToRight!==w.flushToRight)return!1}return!0}});return o.add(i,{name:"text"}),o.add(a,{name:"font"}),o.add(d,{name:"line-height"}),o.add(u,{name:"container"}),o.add(c,{name:"columns"}),o.add(l,{name:"obstacles"}),o.add(p,{name:"paragraph-spacing"}),o.add(f,{name:"segments"}),o.add(m,{name:"flow-lines"}),{graph:o,setText:h=>o.set("text",h),setFont:h=>o.set("font",h),setLineHeight:h=>o.set("line-height",h),setContainer:h=>o.set("container",h),setColumns:h=>o.set("columns",h),setObstacles:h=>o.set("obstacles",h),setParagraphSpacing:h=>o.set("paragraph-spacing",h),segments:f,flowLines:m}}var zi={};Se(zi,{NS_PER_MS:()=>He,NS_PER_SEC:()=>lt,resilientPipeline:()=>av});Wn();It();function av(t,e={}){let n=t;e.rateLimit!=null&&(n=Jn(n,e.rateLimit)),e.budget!=null&&e.budget.length>0&&(n=Dd(n,e.budget));let r;if(e.breaker!=null){let s=Nt(e.breaker),i=e.breakerOnOpen??"skip",a=Un(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=Qn(n,e.timeoutMs*1e6)}e.retry!=null&&(n=St(n,e.retry)),e.fallback!==void 0&&(n=Yn(n,e.fallback));let o=Ht(n,{initialStatus:e.initialStatus??"pending"});return{node:o.node,status:o.status,error:o.error,breakerState:r}}var ea={};Se(ea,{SNAPSHOT_WIRE_VERSION:()=>Io,SurfaceError:()=>_e,asSurfaceError:()=>Hi,createGraph:()=>vr,deleteSnapshot:()=>Zi,diffSnapshots:()=>Qi,listSnapshots:()=>Xi,restoreSnapshot:()=>Yi,runReduction:()=>Wi,saveSnapshot:()=>Ji});var _e=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=dv(this.details);n!==void 0&&(e.details=n)}return e}};function dv(t){try{return JSON.parse(JSON.stringify(t))}catch{return}}function Hi(t,e="internal-error"){if(t instanceof _e)return t;let n=t instanceof Error?t.message:String(t);return new _e(e,n)}function vr(t,e){let n=gr(t);if(!n.valid)throw new _e("invalid-spec",`GraphSpec validation failed:
|
|
221
221
|
${n.errors.join(`
|
|
222
|
-
`)}`,{errors:n.errors});let r=e?.catalog??{},o=
|
|
222
|
+
`)}`,{errors:n.errors});let r=e?.catalog??{},o=_o(t,r);if(!o.valid)throw new _e("catalog-error",`Catalog validation failed:
|
|
223
223
|
${o.errors.join(`
|
|
224
|
-
`)}`,{errors:o.errors});try{return
|
|
224
|
+
`)}`,{errors:o.errors});try{return Mo(t,e)}catch(s){let i=s instanceof Error?s.message:String(s);throw new _e("catalog-error",i)}}ae();var uv=3e4;async function Wi(t,e,n){let r=n?.inputPath??"input",o=n?.outputPath??"output",s=n?.timeoutMs??uv,i=vr(t,{catalog:n?.catalog}),a;try{a=i.resolve(o)}catch{throw i.destroy(),new _e("node-not-found",`reduce: output path "${o}" is not registered`,{path:o})}try{i.resolve(r)}catch{throw i.destroy(),new _e("node-not-found",`reduce: input path "${r}" is not registered`,{path:r})}try{return await new Promise((d,u)=>{let c=!1,l=!1,p,f,m=!1,h=g=>{l||(l=!0,p!==void 0&&clearTimeout(p),f!==void 0?(f(),f=void 0):m=!0,g())};f=a.subscribe(g=>{for(let y of g){if(l)return;if(c){if(y[0]===M){h(()=>d(y[1]));return}if(y[0]===q){let b=a.cache;h(()=>d(b));return}if(y[0]===I){let b=y[1],v=b instanceof Error?b.message:String(b),T=b instanceof Error?b:void 0;h(()=>u(new _e("internal-error",`reduce: output emitted ERROR: ${v}`,T!=null?{cause:T}:void 0)));return}if(y[0]===P){h(()=>u(new _e("internal-error","reduce: output COMPLETEd without a post-push DATA")));return}}}}),m&&(f?.(),f=void 0),c=!0;try{i.set(r,e)}catch(g){let y=g instanceof Error?g.message:String(g),b=g instanceof Error?g:void 0;h(()=>u(new _e("internal-error",`reduce: failed to set input on "${r}": ${y}`,b!=null?{path:r,cause:b}:{path:r})));return}!l&&Number.isFinite(s)&&s>0&&(p=setTimeout(()=>{h(()=>u(new _e("reduce-timeout",`reduce: no output emitted within ${s}ms`,{timeoutMs:s,outputPath:o})))},s),p.unref?.())})}finally{i.destroy()}}Re();var Io=bt,Co="snapshot:";function Lo(t){if(t.startsWith(Co))throw new _e("snapshot-failed",`snapshot id must not start with "${Co}" (reserved); got "${t}"`,{snapshotId:t})}function Ui(t){return`${Co}${t}`}function cv(t){return t.startsWith(Co)?t.slice(Co.length):void 0}function au(t,e){if(t==null||typeof t!="object")throw new _e("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 _e("restore-failed",`snapshot "${e}" is a diff record; restore the baseline and replay WAL instead`,{snapshotId:e,mode:"diff"}):new _e("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 _e("restore-failed",`snapshot "${e}" payload is not a GraphCheckpointRecord or GraphPersistSnapshot`,{snapshotId:e})}async function Ji(t,e,n){Lo(e);let r;try{r=t.snapshot()}catch(s){let i=s instanceof Error?s.message:String(s);throw new _e("snapshot-failed",`snapshot "${e}" serialization failed: ${i}`,{snapshotId:e})}let o={name:t.name,mode:"full",seq:0,timestamp_ns:se(),format_version:Io,snapshot:r};try{await n.save(Ui(e),o)}catch(s){let i=s instanceof Error?s.message:String(s);throw new _e("snapshot-failed",`snapshot "${e}" save failed: ${i}`,{snapshotId:e})}return{snapshotId:e,timestamp_ns:o.timestamp_ns}}async function Yi(t,e,n){Lo(t);let r=Ui(t),o=await e.load(r);o===void 0&&(o=await e.load(t));let s=au(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 _e("restore-failed",`snapshot "${t}" restore failed: ${a}`,{snapshotId:t})}}async function Qi(t,e,n){Lo(t),Lo(e);let r=async d=>{let u=Ui(d),c=await n.load(u);return c===void 0&&(c=await n.load(d)),c},[o,s]=await Promise.all([r(t),r(e)]),i=au(o,t),a=au(s,e);return Q.diff(i,a)}async function Xi(t,e){if(typeof t.list!="function")throw new _e("tier-no-list","KvStorageTier does not implement list(); wrap the tier with an enumerator or use a different backend");let n=await t.list(),r=[],o=e?.includeUnprefixed===!0;for(let s of n){let i=cv(s);i!==void 0?r.push(i):o&&r.push(s)}return r}async function Zi(t,e){if(Lo(t),typeof e.delete!="function")throw new _e("snapshot-failed",`KvStorageTier is append-only (no delete()); cannot delete "${t}"`,{snapshotId:t});try{await e.delete(Ui(t))}catch(n){let r=n instanceof Error?n.message:String(n);throw new _e("snapshot-failed",`snapshot "${t}" delete failed: ${r}`,{snapshotId:t})}}var lv="0.0.0";0&&(module.exports={COMPLETE,COMPLETE_MSG,COMPLETE_ONLY_BATCH,CircuitOpenError,ContentAddressedMissError,DATA,DEFAULT_ACTOR,DIRTY,DIRTY_MSG,DIRTY_ONLY_BATCH,ENVELOPE_VERSION,ERROR,GRAPH_META_SEGMENT,Graph,GraphReFlyConfig,GuardDenied,INVALIDATE,INVALIDATE_MSG,INVALIDATE_ONLY_BATCH,JsonCodec,NS_PER_MS,NS_PER_SEC,NativeIndexBackend,NativeListBackend,NativeLogBackend,NativeMapBackend,NativePubSubBackend,NodeImpl,PAUSE,RESOLVED,RESOLVED_MSG,RESOLVED_ONLY_BATCH,RESUME,RateLimiterOverflowError,ResettableTimer,SIZEOF_OVERHEAD,SIZEOF_SYMBOL,SNAPSHOT_VERSION,SNAPSHOT_WIRE_VERSION,START,START_MSG,SurfaceError,TEARDOWN,TEARDOWN_MSG,TEARDOWN_ONLY_BATCH,TimeoutError,accessHintForGuard,accountability,advanceVersion,ai,appendLogStorage,asSurfaceError,audit,autoTrackNode,awaitSettled,batch,buffer,bufferCount,bufferTime,cached,canonicalJson,cascadingCache,catchError,checkpointToRedis,checkpointToS3,circuitBreaker,combine,combineLatest,compat,concat,concatMap,configure,constant,contentAddressedStorage,core,cqrs,createDagCborCodec,createDagCborZstdCodec,createGraph,createTransport,createVersioning,createWatermarkController,csvRows,debounce,debounceTime,decodeEnvelope,decorrelatedJitter,defaultConfig,defaultHash,defer,delay,deleteSnapshot,demoShell,derived,deserializeError,dictKv,dictSnapshot,diffForWAL,diffSnapshots,distill,distinctUntilChanged,domainTemplates,downWithBatch,dynamicNode,effect,elementAt,empty,encodeEnvelope,escapeRegexChar,exhaustMap,explainPath,exponential,externalBundle,externalProducer,extra,factoryTag,fallback,fibonacci,filter,find,first,firstValueFrom,firstWhere,flatMap,forEach,fromAny,fromAsyncIter,fromCSV,fromClickHouseWatch,fromCron,fromDrizzle,fromEvent,fromHTTP,fromHTTPPoll,fromHTTPStream,fromIter,fromKafka,fromKysely,fromMCP,fromNATS,fromNDJSON,fromOTel,fromPrisma,fromPrometheus,fromPromise,fromPulsar,fromRabbitMQ,fromRaf,fromRedisStream,fromSSE,fromSqlite,fromSqliteCursor,fromStatsD,fromSyslog,fromTimer,fromWebSocket,fromWebSocketReconnect,fromWebhook,globToRegExp,graph,graphProfile,graphspec,guarded,harness,interval,isBatching,isV1,jobQueue,jotai,jsonCodec,jsonCodecFor,keepalive,kvStorage,last,layout,lens,linear,listSnapshots,lru,makeHttpError,map,matchesAnyPattern,matchesCron,memory,memoryAppendLog,memoryBackend,memoryKv,memorySnapshot,merge,mergeMap,mergeReactiveLogs,mermaidLiveUrl,messaging,monotonicNs,nameToSignal,nanostores,ndjsonRows,nestjs,never,node,nodeSignal,normalizeActor,of,onFirstData,orchestration,pairwise,parseCron,parsePrometheusText,parseSSEStream,parseStatsD,parseSyslog,patterns,pausable,pipe,placeholderArgs,policy,policyFromRules,process,producer,pubsub,race,rateLimiter,reachable,react,reactiveCounter,reactiveIndex,reactiveList,reactiveLog,reactiveMap,reactiveSink,reduce,reduction,refine,registerBuiltinCodecs,registerBuiltins,repeat,replay,replayWAL,rescue,resilientPipeline,resolveBackoffPreset,resolveDescribeFields,restoreSnapshot,retry,runReduction,sample,saveSnapshot,scan,serializeError,share,shareReplay,signalToName,signals,singleFromAny,singleNodeFromAny,sizeof,skip,snapshotStorage,solid,sortJsonValue,stableJsonString,state,stratify,surface,svelte,switchMap,take,takeUntil,takeWhile,tap,tapFirst,throttle,throttleTime,throwError,timeout,toArray,toCSV,toClickHouse,toFile,toHTTP,toKafka,toLoki,toMongo,toNATS,toObservable,toPostgres,toPulsar,toRabbitMQ,toReadableStream,toRedisStream,toS3,toSSE,toSSEBytes,toSqlite,toTempo,toWebSocket,tokenBucket,topologyDiff,validateGraphObservability,valve,verifiable,version,vue,wallClockNs,watchTopologyTree,window,windowCount,windowTime,withBreaker,withLatestFrom,withMaxAttempts,withStatus,workerBridge,workerSelf,zip,zustand});
|